@ornexus/neocortex 4.66.52 → 4.66.54

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 (39) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1190 -1190
  3. package/install.ps1 +1 -1
  4. package/install.sh +1 -1
  5. package/package.json +2 -2
  6. package/packages/client/dist/cli.js +2 -2
  7. package/packages/client/dist/commands/invoke.js +78 -78
  8. package/packages/client/dist/commands/story-worktree.d.ts +4 -1
  9. package/packages/client/dist/commands/story-worktree.js +4 -4
  10. package/packages/client/dist/git/epic-origin-rebind.d.ts +20 -0
  11. package/packages/client/dist/git/epic-origin-rebind.js +1 -0
  12. package/packages/client/dist/private-execution/isolated-workspace.d.ts +5 -0
  13. package/packages/client/dist/private-execution/isolated-workspace.js +1 -1
  14. package/packages/shared/dist/invocation/index.d.ts +1 -0
  15. package/packages/shared/dist/invocation/index.js +1 -0
  16. package/packages/shared/dist/invocation/invoke-validation-failure.d.ts +31 -0
  17. package/packages/shared/dist/invocation/invoke-validation-failure.js +48 -0
  18. package/packages/shared/dist/invocation/semantic-gate-remediation.d.ts +56 -0
  19. package/packages/shared/dist/invocation/semantic-gate-remediation.js +62 -0
  20. package/targets-stubs/antigravity/gemini.md +1 -1
  21. package/targets-stubs/antigravity/neocortex.md +1 -1
  22. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  23. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  24. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  25. package/targets-stubs/claude-code/neocortex-sentinel.md +1 -1
  26. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  27. package/targets-stubs/claude-code/neocortex.md +2 -2
  28. package/targets-stubs/codex/AGENTS.md +1 -1
  29. package/targets-stubs/codex/neocortex.toml +1 -1
  30. package/targets-stubs/cursor/agent.md +2 -2
  31. package/targets-stubs/deepseek-harness/SKILL.md +1 -1
  32. package/targets-stubs/gemini-cli/agent.md +2 -2
  33. package/targets-stubs/gemini-cli/agents/neocortex.md +2 -2
  34. package/targets-stubs/grok/SKILL.md +1 -1
  35. package/targets-stubs/kimi/neocortex.md +1 -1
  36. package/targets-stubs/openclaw/SKILL.md +1 -1
  37. package/targets-stubs/opencode/neocortex-root.md +2 -2
  38. package/targets-stubs/opencode/neocortex.md +2 -2
  39. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,78 +1,78 @@
1
- import{classifyNonUiArchitectureTransition as ua,architectureMemoryPredecessorCount as mo}from"./architecture-non-ui-continuation.js";import{parseArchitectureNonUiScopeReceipt as yo}from"./shared-architecture-non-ui.js";import{createHash as Le,randomUUID as Mr}from"node:crypto";import{loadPactAnswerReceipt as Io,loadPactPrivateAnswers as la}from"./architecture-answers.js";import{acceptedArchitectureTerminalMemoryReceipt as hr,deriveArchitectureTerminalMemoryReceipt as yn}from"./architecture-memory-terminal.js";import{deriveCommittedArchitectureEpicGraphRevision as fr,explicitArchitectureEpicTarget as ha}from"./architecture-root-binding.js";import{derivePactWriteSet as fa}from"../private-execution/pact-write-set.js";import{execFileSync as Ae}from"node:child_process";import{existsSync as Ct,readFileSync as $e,renameSync as Eo,unlinkSync as gr,writeFileSync as Vr,mkdirSync as rr,statSync as ga,openSync as Ht,closeSync as Gt,fsyncSync as mr,realpathSync as In,lstatSync as nr}from"node:fs";import{isDeepStrictEqual as v}from"node:util";import{join as q,isAbsolute as ma,resolve as En}from"node:path";import{homedir as yr}from"node:os";import{probeYoloopHostCapacity as ya}from"../runner/host-capacity.js";import{normalizeWorkflowTargetArgs as So,normalizeYoloStoryTargetArgs as Ia}from"../yoloop/target-normalization.js";import{reconcileMissingTrackedEpicState as vo}from"../git/epic-state-recovery.js";import{isPrivateExecutionPublicEnvelope as Ea,isPrivatePlanningRootPublicEnvelope as Sa,PRIVATE_MUTATION_QA_GATE_STEP_TOKEN as va}from"../private-execution/delivery.js";import{acceptedPlanningDiagnosisPredecessor as Co}from"../private-execution/planning-diagnosis-checkpoint.js";import{acceptedPlanningResearchPredecessor as _o}from"../private-execution/planning-research-checkpoint.js";import{verifyCommittedPlanningMemory as wo}from"../private-execution/planning-memory-checkpoint.js";import{verifyCommittedPlanningGeneration as Ca}from"../private-execution/planning-generation-checkpoint.js";import{PLANNING_CHECKPOINT_MAX_BYTES as Ro,PLANNING_RAW_INTENT_MAX_CHARS as _a}from"../../../shared/dist/planning/diagnosis-state.js";import{applyCrossEpicContinuationReconciliation as wa,buildCrossEpicContinuationPayloadHash as Ra,classifyCrossEpicContinuationReconciliation as Aa,epicOperationalHash as _t,readEpicOperationalState as Sn,registerEpicOperationalIdentity as ba}from"../git/epic-operational-state.js";import{applyEpicLifecycleBackfillWithoutClientDrift as xa,previewEpicLifecycleBackfill as Ta}from"../migrations/epic-lifecycle-backfill.js";import{LicenseClient as vn}from"../license/license-client.js";import{EncryptedCache as Ir}from"../cache/encrypted-cache.js";import{NoOpCache as Ao}from"../types/index.js";import{resolveClientPreFlightTrigger as Br,TierAwareClient as Pa}from"../tier/tier-aware-client.js";import{COMMAND_REGISTRY_CHECKSUM as wt,COMMAND_REGISTRY_VERSION as Rt,GENERATED_CLIENT_COMMANDS as ka}from"../generated/command-registry.generated.js";import{loadSecureConfig as $r}from"../config/secure-config.js";import{neocortexProfileDirectory as Oa}from"../config/profile-directory.js";import{normalizeInvokeProjectRoot as Na,resolveEffectiveProjectRoot as Da}from"../config/project-root.js";import{DEFAULT_SERVER_URL as bo}from"../constants.js";import{detectFirstRunLocale as La,renderFirstRunMessage as ja}from"../i18n/first-run.js";import{humanizeAuthRefreshRequired as xo,humanizeError as Cn,formatHumanizedError as _n,detectErrorLocale as Ur}from"../errors/error-messages.js";import{classifyTransportFailure as To}from"../errors/transport-failure.js";import{degradeStateSnapshotForPayloadLimit as Ma,projectStateSnapshotForInvoke as Po,projectStateSnapshotResultV2ForInvoke as Va}from"../state/project-state-snapshot.js";import{isInlineYoloMaterialization as ko,maybeRepairStateJsonBeforeInvoke as Ba,readStoryWorktreeRepairOverlay as $a,StateRepairHardStopError as Ua}from"../state/state-json-repair.js";import{StructuralDagError as Oo}from"../state/structural-dag-projection.js";import{collectStateMigrationAuthority as Ha,StateMigrationApplyError as Ga}from"../migrations/state-json.js";import{RUNNER_BOOTSTRAP_POLICY_REASON_CODES as Wa,classifyRunnerBootstrapPolicyFromArgs as Fa}from"../continuity/runner-bootstrap-policy.js";import{RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES as za,ensureRunnerSchedulerBootstrap as Ya,observeRunnerOperationalStatus as qa}from"../runner/scheduler.js";import{CONTINUITY_INVOKE_WATCH_DEFAULT_LIMIT as No,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_IDLE_POLLS as Do,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_POLLS as Lo,CONTINUITY_INVOKE_WATCH_DEFAULT_POLL_INTERVAL_MS as jo,openContinuityClientStateStore as Ka}from"../continuity/continuity-client-state-store.js";import{isLocalJobsConsoleArgs as Ja,runLocalJobsConsoleCommand as Qa}from"../runner/local-console.js";import{detectNativeHostAttestation as Xa,detectPlatform as Mo}from"../adapters/platform-detector.js";import{signNxInvokeRequest as Za}from"../../../shared/dist/nx-invoke-signature.js";import{YOLO_INVOKE_ENVELOPE_CAPABILITY as ec}from"../../../shared/dist/yolo/spec-envelope.js";import{parseReleaseBlockedResult as tc}from"../../../shared/dist/yoloop/release-blocked.js";import{CLIENT_VERSION as Dt}from"../version.js";import{createCapabilityCache as Vo,executeInvokeQueryTransport as wn,executeSecondaryNetworkMutation as rc}from"../effects/invoke-effect-gateways.js";import{STRICT_READ_ONLY_POLICY as nc,STRICT_READ_ONLY_CLIENT_PROJECTION as Bo,STRICT_READ_ONLY_SERVER_PROJECTION as oc,StrictReadOnlyError as Wt,canonicalizeInvokeEffects as ic,createInvokeEffectContext as ac,verifyStrictReadOnlyReceipt as cc}from"../../../shared/dist/strict-readonly.js";import{admitInvocation as sc,assertDiagnoseDegradedContinuation as dc,assertInvokeInputEnvelopeV2 as pc,assertProjectIdentityMigrationReceiptV1 as uc,buildSemanticGateRemediation as lc,buildProjectIdentityPublicDiagnostic as or,createInvocationAdmissionReceipt as hc,materializeSemanticGateBoilerplate as fc,parseSemanticGateRemediation as Hr,projectInvokeInputEvidenceV1 as Er,projectPrivateExecutionHostFailure as $o,recoverExplicitInvocation as gc,semanticGatePrivateClaimSessionId as mc,semanticGateRequestSha256 as Uo,validateSemanticGateRemediationBinding as Ho,verifyStrictDiagnoseReceiptV1 as yc}from"../../../shared/dist/invocation/index.js";import{buildInvokeInputEnvelope as Ft,InvokeInputDecodeError as Ic}from"../invocation/invoke-input.js";import{COMPATIBILITY_CAPABILITIES as Gr,COMPATIBILITY_REASON_CODES as ir,COMPATIBILITY_SCHEMAS as Wr,createCompatibilityOffer as Ec,createLegacyCompatibilityResult as Sc,hostKindForPlatformTarget as Rn,isCompatibilityResultV1 as Go,PRIVATE_EXECUTION_CODEX_HOST_KIND as Wo}from"../../../shared/dist/compatibility/index.js";import{acknowledgeProjectIdentityMigration as vc,finalizeProjectIdentityMigration as Cc,prepareProjectIdentityMigration as _c,ProjectIdentityMigrationError as An,readProjectIdentityMigrationPhase as wc}from"../migrations/project-identity.js";import{probeProjectIdentityMigrationCapability as Rc}from"../migrations/project-identity-capability.js";import{normalizeYoloopStoryPlanningEvidence as Ac}from"../../../shared/dist/yoloop/planning-graph.js";import{normalizeContinuousWriteRef as Fr}from"../../../shared/dist/yoloop/wave-decision-receipt.js";import{epicHeadReconciliationInputDigest as bc,epicHeadReconciliationPathsDigest as zr,epicHeadReconciliationRangeDigest as xc}from"../../../shared/dist/yoloop/epic-terminal-git.js";import{applyGitLifecycleRuntimeOverlay as bn,classifyGitLifecycleStoryCheckpointProjectionSync as Tc,ensureRuntimeEpic as Pc,ensureGitLifecycleRuntimeInitialized as kc,executeP205TransientAuthorities as Oc,isP226GateReasonCode as Nc,persistGitLifecycleGraphAuthority as Dc,P205_COMPLETE_COMMAND as Sr,gitLifecycleStoryWriteSet as Fo,gitLifecycleStoryClaimCandidates as Lc,gitLifecycleWriteSetCovers as jc,appendStoryWorktreeEvidence as Mc,isStoryWorktreeEvidenceContainer as Vc,mutateGitLifecycleRuntime as zo,projectP205TransientExecutionEvidence as Bc,projectStoryWorktreeEvidenceForSnapshot as $c,readGitLifecycleRuntimeSync as ar,verifyLegacyCheckpointMigrationCandidateSync as Uc}from"../git/git-lifecycle-store.js";import{detectGovernanceModeSync as Hc,readGovernanceStateSourceSync as Gc,writeProjectStateMirrorSync as Wc}from"../git/governance-runtime-store.js";import{verifyRootMemoryPhysicalWriteSet as Fc}from"../private-execution/root-memory-git-evidence.js";import{isRootProjectMemoryEffect as zc}from"../private-execution/shared-root-memory-types.js";import{probeYoloInvokeEnvelopeCapability as Yc}from"../yolo/invoke-envelope-capability.js";import{attachProjectManifestProjection as qc}from"../yolo/project-manifest-projection-collector.js";import{collectYoloSpecEnvelope as Yo,extractTargetedYoloStoryId as Kc,refreshPrecollectedYoloSpecEnvelope as qo}from"../yolo/spec-envelope-collector.js";import{FRONTMATTER_LIST_TOO_LONG_DIAGNOSTIC_PATTERN as Jc}from"../errors/frontmatter-diagnostics.js";function Ko(e,t=!1){return e instanceof Error&&((t?/^yolo-(?:spec-envelope|change-evidence)-[a-z-]+$/:/^yolo-spec-envelope-[a-z-]+$/).test(e.message)||Jc.test(e.message))?e.message:"yolo-spec-envelope-unsafe"}function Qc(e){const t=Ho(e.remediation,e);return t?.reasonCode==="yoloop-session-invalidated"&&t.repairKind==="reconcile-deterministic-state"&&t.authority.operation==="cas-reconcile-yoloop-session"&&t.boilerplate.templateId==="gate-deterministic-reconciliation-v1"&&t.retry.limit===1?t:null}const Yr=Oa(),vr=q(Yr,"cache"),Jo=q(vr,"menu-cache.json"),Qo=1440*60*1e3,Xo=3e4,Zo=256*1024,ei=Zo,ti=.8,Lt="[REDACTED]",Xc=1e5,zt=2e3,Zc=200,es=200,ts=12,rs=/(?:promptBody|workflow|workflowGraph|stepBody|privateUrl|rawLog|secret|credential|licenseKey|apiKey|internalRouting|serverOnly|proprietary|protected)/i,ns=/(?:PRIVATE|PROTECTED|SERVER_ONLY)[-_\s]*(?:PROMPT|PROMPT_BODY|WORKFLOW|WORKFLOW_GRAPH|STEP_BODY|STEP|ROUTING)\s*[:=][^\n\r]*/gi,os=/(?: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,xn=Math.floor(Zo*ti),ri=q(Yr,".first-run-shown"),is="pending-epic-claims.json",ni=64;function Tn(e){return q(e,".neocortex",is)}function Yt(e){const t=Tn(e);if(!Ct(t))return{schemaVersion:1,operations:{}};const n=JSON.parse($e(t,"utf8"));if(!n||typeof n!="object"||Array.isArray(n))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const i=n;if(i.schemaVersion!==1||!i.operations||typeof i.operations!="object"||Array.isArray(i.operations))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(Object.keys(i.operations).length>ni)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");for(const[o,r]of Object.entries(i.operations)){if(!/^[a-f0-9]{64}$/.test(o)||!r||typeof r!="object"||Array.isArray(r))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const a=r;if(a.planningProtocol!==void 0&&a.planningProtocol!=="root-staged-v1")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(typeof a.idempotencyKey!="string"||!/^[0-9a-f-]{36}$/.test(a.idempotencyKey)||typeof a.createdAt!="string")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(a.claimId!==void 0&&(typeof a.claimId!="string"||!/^[0-9a-f-]{36}$/.test(a.claimId))||a.epicId!==void 0&&(typeof a.epicId!="string"||!/^P[1-9][0-9]*$/.test(a.epicId))||a.claimId===void 0!=(a.epicId===void 0))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE")}return n}function Pn(e,t){const n=Tn(e);rr(q(e,".neocortex"),{recursive:!0,mode:448});const i=`${n}.${process.pid}.${Mr()}.tmp`,o=Ht(i,"wx",384);try{try{Vr(o,`${JSON.stringify(t)}
2
- `,"utf8"),mr(o)}finally{Gt(o)}Eo(i,n)}catch(r){try{gr(i)}catch{}throw r}}function kn(e,t){const n=`${Tn(e)}.lock`;rr(q(e,".neocortex"),{recursive:!0,mode:448});let i;try{i=Ht(n,"wx",384)}catch(o){throw o.code==="EEXIST"?new Error("EPIC_CLAIM_WRITE_LOCKED"):o}try{return t()}finally{Gt(i),gr(n)}}function as(e,t){return Le("sha256").update(`nx-epic-logical-operation-v1\0${JSON.stringify({command:t,args:e})}`,"utf8").digest("hex")}function cs(e,t,n="create-epic"){const i=as(t,n);return kn(e,()=>{const o=Yt(e),r=o.operations[i];if(r)return{key:r.idempotencyKey,fingerprint:i};if(Object.keys(o.operations).length>=ni)throw new Error("EPIC_CLAIM_CAPACITY_EXCEEDED");const a=Mr(),s={...o.operations,[i]:{idempotencyKey:a,createdAt:new Date().toISOString()}};return Pn(e,{schemaVersion:1,operations:s}),{key:a,fingerprint:i}})}function ss(e,t,n){return kn(e,()=>{const i=Yt(e),o=i.operations[t];if(!o||n&&(o.idempotencyKey!==n.idempotencyKey||o.createdAt!==n.createdAt||o.claimId!==n.claimId||o.epicId!==n.epicId||o.planningProtocol!==n.planningProtocol))return!1;const r={...i.operations};return delete r[t],Pn(e,{schemaVersion:1,operations:r}),!0})}function ds(e,t,n,i){const o=i.scope?.targetStoryId??i.current_session?.active_story_id??null,r=i.scope?.targetEpicId??i.current_session?.active_epic_id??null,a=o?i.stories[o]:void 0,s=Array.isArray(a?.steps_completed)?a.steps_completed.filter(d=>typeof d=="string"):[],u=n??Le("sha256").update(`nx-yolo-project-path-v1\0${En(e)}`,"utf8").digest("hex"),g=JSON.stringify({projectBinding:u,args:t,storyId:o,epicId:r,status:typeof a?.status=="string"?a.status:null,lastStep:typeof a?.last_step=="string"?a.last_step:null,stepsCompleted:s});return`yolo-${Le("sha256").update(`nx-yolo-logical-operation-v1\0${g}`,"utf8").digest("hex")}`}function On(e,t,n,i,o){if(!/^[0-9a-f-]{36}$/.test(n)||!/^P[1-9][0-9]*$/.test(i)||o!==void 0&&o!=="root-staged-v1")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");kn(e,()=>{const r=Yt(e),a=r.operations[t];if(!a)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(a.claimId!==void 0&&(a.claimId!==n||a.epicId!==i))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");Pn(e,{schemaVersion:1,operations:{...r.operations,[t]:{...a,claimId:n,epicId:i,...o?{planningProtocol:o}:{}}}})})}function ps(){try{if(Ct(ri))return;const e=La(),t=ja(e);process.stderr.write(t);try{rr(Yr,{recursive:!0}),Vr(ri,new Date().toISOString(),"utf-8")}catch{}}catch{}}const oi=["linux","darwin","win32"],us=["executor-returned-unverified","private-executor-timeout","private-executor-output-exceeded","private-executor-exit-nonzero"],ls=["schemaVersion","kind","hostKind","os","outcome","stdoutSha256","stderrSha256","stdoutBytes","stderrBytes","publicSafe"],Nn=/^private-executor-[a-z-]+$/;function hs(e,t){return e===Wo&&t==="linux"}async function ii(e,t){const{createPrivateHarnessExecutorPort:n}=await import("../private-execution/harness-adapters/index.js");return n(e,{cwd:t.cwd})}async function ai(e,t,n=ii){let i;try{i=await n(e,{cwd:t})}catch{i=void 0}if(!i||typeof i!="object"||i.hostKind!==e||typeof i.preflight!="function"||typeof i.run!="function")throw new Error("private-executor-headless-unavailable");return i}function fs(e,t){if(!f(e)||Object.keys(e).sort().join(",")!=="hostKind,hostVersion,observedAtMs,os"||e.hostKind!==t||typeof e.hostVersion!="string"||!/^[0-9]+\.[0-9]+\.[0-9]+$/.test(e.hostVersion)||typeof e.os!="string"||!oi.includes(e.os)||typeof e.observedAtMs!="number"||!Number.isSafeInteger(e.observedAtMs)||e.observedAtMs<=0)throw new Error("private-executor-proof-invalid");return e}async function ci(e,t){let n;try{n=await e.preflight()}catch(i){throw new Error(i instanceof Error&&Nn.test(i.message)?i.message:"private-executor-proof-invalid")}return fs(n,t)}function gs(e,t){const n=i=>typeof i=="number"&&Number.isSafeInteger(i)&&i>=0;if(!f(e)||Object.keys(e).sort().join(",")!==[...ls].sort().join(",")||e.schemaVersion!==2||e.kind!=="PrivateHarnessExecutionReceipt/2"||e.hostKind!==t||typeof e.os!="string"||!oi.includes(e.os)||typeof e.outcome!="string"||!us.includes(e.outcome)||typeof e.stdoutSha256!="string"||!/^[a-f0-9]{64}$/.test(e.stdoutSha256)||typeof e.stderrSha256!="string"||!/^[a-f0-9]{64}$/.test(e.stderrSha256)||!n(e.stdoutBytes)||!n(e.stderrBytes)||e.publicSafe!==!0)throw new Error("private-executor-receipt-invalid");return e}function ms(e){return{schemaVersion:1,hostKind:e.hostKind,hostVersion:e.hostVersion,executorProof:{schemaVersion:7,preflight:"passed",hostVersion:"passed",stdinOnly:"passed",ephemeralHome:"passed",nativeNoPersistence:"passed",os:"passed"}}}function si(e){return{schemaVersion:1,hostKind:"codex-cli",hostVersion:e.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:e.observedAtMs}}}async function ys(e,t,n){const{captureDirectYoloCheckoutEvidence:i}=await import("../git/direct-yolo-checkpoint.js"),o=()=>new Error("private-executor-workspace-effect-unverified"),r=n.requireWorkspaceEffect?await i(n.workspaceRoot).catch(()=>{throw o()}):void 0;if(r&&n.expectedExecutionBranch!==void 0&&r.branch!==n.expectedExecutionBranch)throw o();let a;try{a=await e.run(t)}catch(u){throw new Error(u instanceof Error&&Nn.test(u.message)?u.message:"private-executor-run-failed")}const s=gs(a,n.hostKind);if(s.outcome!=="executor-returned-unverified")throw new Error(s.outcome);if(r){const u=await i(n.workspaceRoot).catch(()=>{throw o()});if(u.headSha!==r.headSha||u.branch!==r.branch||u.payloadDigest===r.payloadDigest)throw o()}return s}function Is(e){if(e.writeSetId==="idea-diagnosis-v1"&&e.stepId==="step-acd455ed")return"diagnosis";throw new Error(e.codexV6?"private-execution-planning-root-protocol-required":"private-execution-planning-step-unsupported")}function el(e,t=process.cwd()){return Na(e,t)}async function di(e){return(await Da({explicitRoot:e})).root}const Es=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,Ss="Reinstall Neocortex with optional dependencies and lifecycle scripts enabled, or run `npm rebuild better-sqlite3` from the installed package root before retrying the same request.";function pi(e){const t=f(e)&&e.code==="sqlite-adapter-unavailable"?"sqlite-adapter-unavailable":"native-custody-observation-failed";return Object.freeze({schemaVersion:1,reasonCode:t,remediation:t==="sqlite-adapter-unavailable"?Ss:"Run the Neocortex doctor, repair the reported local continuity-store condition, then retry the same yoloop request.",retrySafeAfterRepair:!0,publicSafe:!0})}function vs(e){if(!f(e)||e.schemaVersion!==1||e.reasonCode!=="sqlite-adapter-unavailable"&&e.reasonCode!=="native-custody-observation-failed"||e.retrySafeAfterRepair!==!0||e.publicSafe!==!0)return;const t=pi(e.reasonCode==="sqlite-adapter-unavailable"?{code:"sqlite-adapter-unavailable"}:void 0);if(e.remediation===t.remediation)return Object.freeze({schemaVersion:1,reasonCode:e.reasonCode,remediation:t.remediation,retrySafeAfterRepair:!0,publicSafe:!0})}function ui(e,t){if(t.success||Hr(t.metadata?.semanticGateRemediation))return t;const n=t.errorCode&&Es.test(t.errorCode)?t.errorCode:"INVOKE_ERROR",i=lc({templateId:"gate-manual-resolution-v1",reasonCode:n,requestSha256:Uo(e)});return{...t,metadata:{...t.metadata,semanticGateRemediation:i}}}function Cs(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 _s(e){const t=e.metadata;if(!t||!(t.yoloopReleaseBlocked===!0||t.terminalClass==="release-blocked"||t.releaseBlocked!==void 0))return;const i=tc(t.releaseBlocked);return!i||t.yoloopReleaseBlocked!==!0||t.terminalClass!=="release-blocked"||t.yoloopComplete!==!1||t.yoloopAborted!==!1?{success:!1,error:"YOLOOP_RELEASE_BLOCKED_INVALID: terminal evidence was inconsistent.",errorCode:"YOLOOP_RELEASE_BLOCKED_INVALID",metadata:t,exitCode:1}:{success:!1,instructions:e.instructions,metadata:{...t,releaseBlocked:i},error:"YOLOOP_RELEASE_BLOCKED: the current release attempt ended without success.",errorCode:"YOLOOP_RELEASE_BLOCKED",exitCode:1}}function Dn(e){return sc(e,{registryVersion:Rt,registryChecksum:wt})}function ws(e){return gc(e,{registryVersion:Rt,registryChecksum:wt})}const Rs=new Set(["completed","aborted","cancelled"]),As=new Set(["watch-target-missing","watch-target-malformed","watch-target-ambiguous","watch-target-multiple"]),Oe=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"}),Ue=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"}),K=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"}),li=240,bs=/(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 xs(e){return e.replace(/[\w.+-]+@[\w-]+\.[\w.-]+/g,Lt).replace(/(?:sk|pk|whsec|nxk)[-_](?:test|live|ant|proj|pro|free|enterprise)?[-_]?[A-Za-z0-9_-]{16,}/g,Lt).replace(/NX-[FPE]-[a-f0-9]{24}-[a-f0-9]{4}/g,Lt).replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,Lt).replace(ns,Lt).replace(os,Lt)}function nt(e,t){const n=xs(e);return n.length<=t?n:`${n.slice(0,t)}\u2026[TRUNCATED:${n.length-t}]`}function Ln(e,t=0,n=new WeakSet){if(t>ts)return"[MAX_DEPTH]";if(e==null)return e;if(typeof e=="string")return nt(e,zt);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(n.has(e))return"[CIRCULAR]";n.add(e);try{if(Array.isArray(e))return e.slice(0,Zc).map(o=>Ln(o,t+1,n));const i={};for(const[o,r]of Object.entries(e).slice(0,es)){if(rs.test(o)){i[o]=Lt;continue}const a=Ln(r,t+1,n);a!==void 0&&(i[o]=a)}return i}finally{n.delete(e)}}}function qr(e,t){return{instructions:nt(e??"",Xc),metadata:t?Ln(t):void 0}}function Ts(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e,n=typeof t.reason=="string"&&/^[a-z0-9-]{1,80}$/.test(t.reason)?t.reason:void 0,i=typeof t.baseSource=="string"&&["active-story-lease","published-execution-branch","local-default-branch","remote-default-branch","none"].includes(t.baseSource)?t.baseSource:void 0,o=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,a=t.recollectionCount===0||t.recollectionCount===1?t.recollectionCount:void 0;if(!(!n||!i||!o||!r||a===void 0||t.publicSafe!==!0))return{reason:n,base_source:i,repair:o,recollection_count:a,fallback_action:r,public_safe:!0}}class Kr extends Error{reason;source;byteLength;code;constructor(t,n,i,o,r){super(n),this.reason=i,this.source=o,this.byteLength=r,this.name="InvokeCliInputError",this.code=t}}function Ps(e){const t=Br(e);return(t==="arch-plan"||t==="ui-ux-review")&&ks(e,"--project-evidence")}function ks(e,t){let n=null,i=-1,o=!1,r=!1;for(let a=0;a<=e.length;a+=1){const s=e[a];if(a===e.length||!n&&/\s/.test(s??"")){if(i>=0&&!o&&e.slice(i,a)===t)return!0;i=-1,o=!1,r=!1;continue}if(i<0&&(i=a),r){r=!1;continue}if(s==="\\"){r=!0;continue}(s==='"'||s==="'")&&(o=!0,n=n===s?null:n??s)}return!1}const Os=/(?:^|\s)codex(?:-cli)?\s+([A-Za-z0-9][A-Za-z0-9._+-]{0,63})(?:\s|$)/i;function Ns(e,t){if(e.targetId!=="codex")return null;const n=t.CODEX_VERSION?.trim();if(n&&/^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/.test(n))return n;try{return Ae("codex",["--version"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim().match(Os)?.[1]??null}catch{return null}}function jn(e=!1){return Ec({clientVersion:Dt,registryVersion:Rt,registryChecksum:wt,capabilityIds:Object.values(Gr).filter(t=>e||t!==Gr.DIAGNOSE_SCOPED_CONTINUATION),schemaVersions:Object.values(Wr).filter(t=>e||t!==Wr.DIAGNOSE_SCOPED_CONTINUATION)})}class Mn extends Error{code="PAYLOAD_TOO_LARGE";telemetry;constructor(t){super(`PAYLOAD_TOO_LARGE: invoke request is ${t.payloadBytes} bytes after deterministic degradation; limit is ${t.limitBytes}. Reduce command input or local state context and retry.`),this.name="InvokePayloadTooLargeError",this.telemetry=t}}class Vn 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 Bn=!1;function Ds(e){const t=[];if(!e||typeof e!="object")return t;const n=e,i=n.planning;if(i&&(i.current!==void 0||Array.isArray(i.history))&&t.push({code:"PLANNING_LEGACY",message:"legacy `planning.current`/`planning.history` detected (not read by v1 orchestrator)"}),Array.isArray(n.stories)&&t.push({code:"STORIES_AS_ARRAY",message:"`stories` is an Array (expected Object keyed by story ID)"}),n.epics&&typeof n.epics=="object"&&!Array.isArray(n.epics))for(const[r,a]of Object.entries(n.epics)){const s=a;if(s&&s.stories!==void 0&&!Array.isArray(s.stories)){t.push({code:"EPIC_STORIES_NOT_ARRAY",message:`epic "${r}" has non-array \`stories\` field (expected string[] of story IDs)`});break}}const o=n.epics&&typeof n.epics=="object"&&Object.keys(n.epics).length>0||n.stories&&typeof n.stories=="object"&&!Array.isArray(n.stories)&&Object.keys(n.stories).length>0||Array.isArray(n.stories)||i&&i.current!==void 0;return n.schema_version===void 0?o&&t.push({code:"SCHEMA_VERSION_MISSING",message:"`schema_version` field missing (expected: `schema_version: 1`)"}):n.schema_version!==1&&t.push({code:"SCHEMA_VERSION_OUTDATED",message:`schema_version=${String(n.schema_version)} (expected: 1)`}),t}function Ls(e){if(!(Bn||e.length===0)){Bn=!0;try{const t=e.map(n=>` - ${n.message}`).join(`
1
+ import{classifyNonUiArchitectureTransition as fa,architectureMemoryPredecessorCount as yi}from"./architecture-non-ui-continuation.js";import{parseArchitectureNonUiScopeReceipt as Ii}from"./shared-architecture-non-ui.js";import{createHash as je,randomUUID as Mr}from"node:crypto";import{loadPactAnswerReceipt as Ei,loadPactPrivateAnswers as ga}from"./architecture-answers.js";import{acceptedArchitectureTerminalMemoryReceipt as hr,deriveArchitectureTerminalMemoryReceipt as yn}from"./architecture-memory-terminal.js";import{deriveCommittedArchitectureEpicGraphRevision as fr,explicitArchitectureEpicTarget as ma}from"./architecture-root-binding.js";import{derivePactWriteSet as ya}from"../private-execution/pact-write-set.js";import{execFileSync as Ae}from"node:child_process";import{existsSync as Ct,readFileSync as Ue,renameSync as Si,unlinkSync as gr,writeFileSync as Vr,mkdirSync as rr,statSync as Ia,openSync as Ht,closeSync as Gt,fsyncSync as mr,realpathSync as In,lstatSync as nr}from"node:fs";import{isDeepStrictEqual as C}from"node:util";import{join as J,isAbsolute as Ea,resolve as En}from"node:path";import{homedir as yr}from"node:os";import{probeYoloopHostCapacity as Sa}from"../runner/host-capacity.js";import{normalizeWorkflowTargetArgs as vi,normalizeYoloStoryTargetArgs as va}from"../yoloop/target-normalization.js";import{reconcileMissingTrackedEpicState as Ci}from"../git/epic-state-recovery.js";import{PrivateIsolatedWorkspaceError as Ca}from"../private-execution/isolated-workspace.js";import{isPrivateExecutionPublicEnvelope as _a,isPrivatePlanningRootPublicEnvelope as wa,PRIVATE_MUTATION_QA_GATE_STEP_TOKEN as Ra}from"../private-execution/delivery.js";import{acceptedPlanningDiagnosisPredecessor as _i}from"../private-execution/planning-diagnosis-checkpoint.js";import{acceptedPlanningResearchPredecessor as wi}from"../private-execution/planning-research-checkpoint.js";import{verifyCommittedPlanningMemory as Ri}from"../private-execution/planning-memory-checkpoint.js";import{verifyCommittedPlanningGeneration as Aa}from"../private-execution/planning-generation-checkpoint.js";import{PLANNING_CHECKPOINT_MAX_BYTES as Ai,PLANNING_RAW_INTENT_MAX_CHARS as ba}from"../../../shared/dist/planning/diagnosis-state.js";import{applyCrossEpicContinuationReconciliation as xa,buildCrossEpicContinuationPayloadHash as Ta,classifyCrossEpicContinuationReconciliation as Pa,epicOperationalHash as _t,readEpicOperationalState as Sn,registerEpicOperationalIdentity as ka}from"../git/epic-operational-state.js";import{applyEpicLifecycleBackfillWithoutClientDrift as Oa,previewEpicLifecycleBackfill as Na}from"../migrations/epic-lifecycle-backfill.js";import{LicenseClient as vn}from"../license/license-client.js";import{EncryptedCache as Ir}from"../cache/encrypted-cache.js";import{NoOpCache as bi}from"../types/index.js";import{resolveClientPreFlightTrigger as Br,TierAwareClient as Da}from"../tier/tier-aware-client.js";import{COMMAND_REGISTRY_CHECKSUM as wt,COMMAND_REGISTRY_VERSION as Rt,GENERATED_CLIENT_COMMANDS as La}from"../generated/command-registry.generated.js";import{loadSecureConfig as $r}from"../config/secure-config.js";import{neocortexProfileDirectory as ja}from"../config/profile-directory.js";import{normalizeInvokeProjectRoot as Ma,resolveEffectiveProjectRoot as Va}from"../config/project-root.js";import{DEFAULT_SERVER_URL as xi}from"../constants.js";import{detectFirstRunLocale as Ba,renderFirstRunMessage as $a}from"../i18n/first-run.js";import{humanizeAuthRefreshRequired as Ti,humanizeError as Cn,formatHumanizedError as _n,detectErrorLocale as Ur}from"../errors/error-messages.js";import{classifyTransportFailure as Pi}from"../errors/transport-failure.js";import{degradeStateSnapshotForPayloadLimit as Ua,projectStateSnapshotForInvoke as ki,projectStateSnapshotResultV2ForInvoke as Ha}from"../state/project-state-snapshot.js";import{isInlineYoloMaterialization as Oi,maybeRepairStateJsonBeforeInvoke as Ga,readStoryWorktreeRepairOverlay as Wa,StateRepairHardStopError as Fa}from"../state/state-json-repair.js";import{StructuralDagError as Ni}from"../state/structural-dag-projection.js";import{collectStateMigrationAuthority as za,StateMigrationApplyError as Ya}from"../migrations/state-json.js";import{RUNNER_BOOTSTRAP_POLICY_REASON_CODES as qa,classifyRunnerBootstrapPolicyFromArgs as Ka}from"../continuity/runner-bootstrap-policy.js";import{RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES as Ja,ensureRunnerSchedulerBootstrap as Qa,observeRunnerOperationalStatus as Xa}from"../runner/scheduler.js";import{CONTINUITY_INVOKE_WATCH_DEFAULT_LIMIT as Di,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_IDLE_POLLS as Li,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_POLLS as ji,CONTINUITY_INVOKE_WATCH_DEFAULT_POLL_INTERVAL_MS as Mi,openContinuityClientStateStore as Za}from"../continuity/continuity-client-state-store.js";import{isLocalJobsConsoleArgs as ec,runLocalJobsConsoleCommand as tc}from"../runner/local-console.js";import{detectNativeHostAttestation as rc,detectPlatform as Vi}from"../adapters/platform-detector.js";import{signNxInvokeRequest as nc}from"../../../shared/dist/nx-invoke-signature.js";import{YOLO_INVOKE_ENVELOPE_CAPABILITY as ic}from"../../../shared/dist/yolo/spec-envelope.js";import{parseReleaseBlockedResult as oc}from"../../../shared/dist/yoloop/release-blocked.js";import{CLIENT_VERSION as Dt}from"../version.js";import{createCapabilityCache as Bi,executeInvokeQueryTransport as wn,executeSecondaryNetworkMutation as ac}from"../effects/invoke-effect-gateways.js";import{STRICT_READ_ONLY_POLICY as cc,STRICT_READ_ONLY_CLIENT_PROJECTION as $i,STRICT_READ_ONLY_SERVER_PROJECTION as sc,StrictReadOnlyError as Wt,canonicalizeInvokeEffects as dc,createInvokeEffectContext as pc,verifyStrictReadOnlyReceipt as uc}from"../../../shared/dist/strict-readonly.js";import{admitInvocation as lc,assertDiagnoseDegradedContinuation as hc,assertInvokeInputEnvelopeV2 as fc,assertProjectIdentityMigrationReceiptV1 as gc,buildSemanticGateRemediation as mc,projectInvokeValidationFailure as Rn,buildPrivateExecutionWorkspaceFailure as yc,buildProjectIdentityPublicDiagnostic as ir,createInvocationAdmissionReceipt as Ic,materializeSemanticGateBoilerplate as Ec,parseSemanticGateRemediation as Hr,projectInvokeInputEvidenceV1 as Er,projectPrivateExecutionHostFailure as Ui,projectPrivateExecutionWorkspaceFailure as Hi,PRIVATE_EXECUTION_WORKSPACE_GATE as Gi,recoverExplicitInvocation as Sc,semanticGatePrivateClaimSessionId as vc,semanticGateRequestSha256 as Wi,validateSemanticGateRemediationBinding as Fi,verifyStrictDiagnoseReceiptV1 as Cc}from"../../../shared/dist/invocation/index.js";import{buildInvokeInputEnvelope as Ft,InvokeInputDecodeError as _c}from"../invocation/invoke-input.js";import{COMPATIBILITY_CAPABILITIES as Gr,COMPATIBILITY_REASON_CODES as or,COMPATIBILITY_SCHEMAS as Wr,createCompatibilityOffer as wc,createLegacyCompatibilityResult as Rc,hostKindForPlatformTarget as An,isCompatibilityResultV1 as zi,PRIVATE_EXECUTION_CODEX_HOST_KIND as bn}from"../../../shared/dist/compatibility/index.js";import{acknowledgeProjectIdentityMigration as Ac,finalizeProjectIdentityMigration as bc,prepareProjectIdentityMigration as xc,ProjectIdentityMigrationError as xn,readProjectIdentityMigrationPhase as Tc}from"../migrations/project-identity.js";import{probeProjectIdentityMigrationCapability as Pc}from"../migrations/project-identity-capability.js";import{normalizeYoloopStoryPlanningEvidence as kc}from"../../../shared/dist/yoloop/planning-graph.js";import{normalizeContinuousWriteRef as Fr}from"../../../shared/dist/yoloop/wave-decision-receipt.js";import{epicHeadReconciliationInputDigest as Oc,epicHeadReconciliationPathsDigest as zr,epicHeadReconciliationRangeDigest as Nc}from"../../../shared/dist/yoloop/epic-terminal-git.js";import{applyGitLifecycleRuntimeOverlay as Tn,classifyGitLifecycleStoryCheckpointProjectionSync as Dc,ensureRuntimeEpic as Lc,ensureGitLifecycleRuntimeInitialized as jc,executeP205TransientAuthorities as Mc,isP226GateReasonCode as Vc,persistGitLifecycleGraphAuthority as Bc,P205_COMPLETE_COMMAND as Sr,gitLifecycleStoryWriteSet as Yi,gitLifecycleStoryClaimCandidates as $c,gitLifecycleWriteSetCovers as Uc,appendStoryWorktreeEvidence as Hc,isStoryWorktreeEvidenceContainer as Gc,mutateGitLifecycleRuntime as qi,projectP205TransientExecutionEvidence as Wc,projectStoryWorktreeEvidenceForSnapshot as Fc,readGitLifecycleRuntimeSync as ar,verifyLegacyCheckpointMigrationCandidateSync as zc}from"../git/git-lifecycle-store.js";import{detectGovernanceModeSync as Yc,readGovernanceStateSourceSync as qc,writeProjectStateMirrorSync as Kc}from"../git/governance-runtime-store.js";import{verifyRootMemoryPhysicalWriteSet as Jc}from"../private-execution/root-memory-git-evidence.js";import{isRootProjectMemoryEffect as Qc}from"../private-execution/shared-root-memory-types.js";import{probeYoloInvokeEnvelopeCapability as Xc}from"../yolo/invoke-envelope-capability.js";import{attachProjectManifestProjection as Zc}from"../yolo/project-manifest-projection-collector.js";import{collectYoloSpecEnvelope as Ki,extractTargetedYoloStoryId as es,refreshPrecollectedYoloSpecEnvelope as Ji}from"../yolo/spec-envelope-collector.js";import{FRONTMATTER_LIST_TOO_LONG_DIAGNOSTIC_PATTERN as ts}from"../errors/frontmatter-diagnostics.js";function Qi(e,t=!1){return e instanceof Error&&((t?/^yolo-(?:spec-envelope|change-evidence)-[a-z-]+$/:/^yolo-spec-envelope-[a-z-]+$/).test(e.message)||ts.test(e.message))?e.message:"yolo-spec-envelope-unsafe"}function rs(e){const t=Fi(e.remediation,e);return t?.reasonCode==="yoloop-session-invalidated"&&t.repairKind==="reconcile-deterministic-state"&&t.authority.operation==="cas-reconcile-yoloop-session"&&t.boilerplate.templateId==="gate-deterministic-reconciliation-v1"&&t.retry.limit===1?t:null}const Yr=ja(),vr=J(Yr,"cache"),Xi=J(vr,"menu-cache.json"),Zi=1440*60*1e3,eo=3e4,to=256*1024,ro=to,no=.8,Lt="[REDACTED]",ns=1e5,zt=2e3,is=200,os=200,as=12,cs=/(?:promptBody|workflow|workflowGraph|stepBody|privateUrl|rawLog|secret|credential|licenseKey|apiKey|internalRouting|serverOnly|proprietary|protected)/i,ss=/(?:PRIVATE|PROTECTED|SERVER_ONLY)[-_\s]*(?:PROMPT|PROMPT_BODY|WORKFLOW|WORKFLOW_GRAPH|STEP_BODY|STEP|ROUTING)\s*[:=][^\n\r]*/gi,ds=/(?:https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|private|internal)[^\s"'<>]*|raw[_-]?log|transcript|stack\s*trace|stderr:|stdout:|system prompt|prompt body|workflow body|step body|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|VENDOR_CORPUS|P180[_-]?SYNTHETIC[_-]?CONTINUITY|P185[_-]?SYNTHETIC[_-]?CONTINUITY|P187[_-]?SYNTHETIC[_-]?(?:CONTINUITY|RUNNER|WATCH)|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=)/gi,Pn=Math.floor(to*no),io=J(Yr,".first-run-shown"),ps="pending-epic-claims.json",oo=64;function kn(e){return J(e,".neocortex",ps)}function Yt(e){const t=kn(e);if(!Ct(t))return{schemaVersion:1,operations:{}};const n=JSON.parse(Ue(t,"utf8"));if(!n||typeof n!="object"||Array.isArray(n))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const o=n;if(o.schemaVersion!==1||!o.operations||typeof o.operations!="object"||Array.isArray(o.operations))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(Object.keys(o.operations).length>oo)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");for(const[i,r]of Object.entries(o.operations)){if(!/^[a-f0-9]{64}$/.test(i)||!r||typeof r!="object"||Array.isArray(r))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const a=r;if(a.planningProtocol!==void 0&&a.planningProtocol!=="root-staged-v1")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(typeof a.idempotencyKey!="string"||!/^[0-9a-f-]{36}$/.test(a.idempotencyKey)||typeof a.createdAt!="string")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(a.claimId!==void 0&&(typeof a.claimId!="string"||!/^[0-9a-f-]{36}$/.test(a.claimId))||a.epicId!==void 0&&(typeof a.epicId!="string"||!/^P[1-9][0-9]*$/.test(a.epicId))||a.claimId===void 0!=(a.epicId===void 0))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE")}return n}function On(e,t){const n=kn(e);rr(J(e,".neocortex"),{recursive:!0,mode:448});const o=`${n}.${process.pid}.${Mr()}.tmp`,i=Ht(o,"wx",384);try{try{Vr(i,`${JSON.stringify(t)}
2
+ `,"utf8"),mr(i)}finally{Gt(i)}Si(o,n)}catch(r){try{gr(o)}catch{}throw r}}function Nn(e,t){const n=`${kn(e)}.lock`;rr(J(e,".neocortex"),{recursive:!0,mode:448});let o;try{o=Ht(n,"wx",384)}catch(i){throw i.code==="EEXIST"?new Error("EPIC_CLAIM_WRITE_LOCKED"):i}try{return t()}finally{Gt(o),gr(n)}}function us(e,t){return je("sha256").update(`nx-epic-logical-operation-v1\0${JSON.stringify({command:t,args:e})}`,"utf8").digest("hex")}function ls(e,t,n="create-epic"){const o=us(t,n);return Nn(e,()=>{const i=Yt(e),r=i.operations[o];if(r)return{key:r.idempotencyKey,fingerprint:o};if(Object.keys(i.operations).length>=oo)throw new Error("EPIC_CLAIM_CAPACITY_EXCEEDED");const a=Mr(),s={...i.operations,[o]:{idempotencyKey:a,createdAt:new Date().toISOString()}};return On(e,{schemaVersion:1,operations:s}),{key:a,fingerprint:o}})}function hs(e,t,n){return Nn(e,()=>{const o=Yt(e),i=o.operations[t];if(!i||n&&(i.idempotencyKey!==n.idempotencyKey||i.createdAt!==n.createdAt||i.claimId!==n.claimId||i.epicId!==n.epicId||i.planningProtocol!==n.planningProtocol))return!1;const r={...o.operations};return delete r[t],On(e,{schemaVersion:1,operations:r}),!0})}function fs(e,t,n,o){const i=o.scope?.targetStoryId??o.current_session?.active_story_id??null,r=o.scope?.targetEpicId??o.current_session?.active_epic_id??null,a=i?o.stories[i]:void 0,s=Array.isArray(a?.steps_completed)?a.steps_completed.filter(d=>typeof d=="string"):[],u=n??je("sha256").update(`nx-yolo-project-path-v1\0${En(e)}`,"utf8").digest("hex"),g=JSON.stringify({projectBinding:u,args:t,storyId:i,epicId:r,status:typeof a?.status=="string"?a.status:null,lastStep:typeof a?.last_step=="string"?a.last_step:null,stepsCompleted:s});return`yolo-${je("sha256").update(`nx-yolo-logical-operation-v1\0${g}`,"utf8").digest("hex")}`}function Dn(e,t,n,o,i){if(!/^[0-9a-f-]{36}$/.test(n)||!/^P[1-9][0-9]*$/.test(o)||i!==void 0&&i!=="root-staged-v1")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");Nn(e,()=>{const r=Yt(e),a=r.operations[t];if(!a)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(a.claimId!==void 0&&(a.claimId!==n||a.epicId!==o))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");On(e,{schemaVersion:1,operations:{...r.operations,[t]:{...a,claimId:n,epicId:o,...i?{planningProtocol:i}:{}}}})})}function gs(){try{if(Ct(io))return;const e=Ba(),t=$a(e);process.stderr.write(t);try{rr(Yr,{recursive:!0}),Vr(io,new Date().toISOString(),"utf-8")}catch{}}catch{}}const ao=["linux","darwin","win32"],ms=["executor-returned-unverified","private-executor-timeout","private-executor-output-exceeded","private-executor-exit-nonzero"],ys=["schemaVersion","kind","hostKind","os","outcome","stdoutSha256","stderrSha256","stdoutBytes","stderrBytes","publicSafe"],Ln=/^private-executor-[a-z-]+$/;function Is(e,t){return e===bn&&t==="linux"}async function co(e,t){const{createPrivateHarnessExecutorPort:n}=await import("../private-execution/harness-adapters/index.js");return n(e,{cwd:t.cwd})}async function so(e,t,n=co){let o;try{o=await n(e,{cwd:t})}catch{o=void 0}if(!o||typeof o!="object"||o.hostKind!==e||typeof o.preflight!="function"||typeof o.run!="function")throw new Error("private-executor-headless-unavailable");return o}function Es(e,t){if(!f(e)||Object.keys(e).sort().join(",")!=="hostKind,hostVersion,observedAtMs,os"||e.hostKind!==t||typeof e.hostVersion!="string"||!/^[0-9]+\.[0-9]+\.[0-9]+$/.test(e.hostVersion)||typeof e.os!="string"||!ao.includes(e.os)||typeof e.observedAtMs!="number"||!Number.isSafeInteger(e.observedAtMs)||e.observedAtMs<=0)throw new Error("private-executor-proof-invalid");return e}async function po(e,t){let n;try{n=await e.preflight()}catch(o){throw new Error(o instanceof Error&&Ln.test(o.message)?o.message:"private-executor-proof-invalid")}return Es(n,t)}function Ss(e,t){const n=o=>typeof o=="number"&&Number.isSafeInteger(o)&&o>=0;if(!f(e)||Object.keys(e).sort().join(",")!==[...ys].sort().join(",")||e.schemaVersion!==2||e.kind!=="PrivateHarnessExecutionReceipt/2"||e.hostKind!==t||typeof e.os!="string"||!ao.includes(e.os)||typeof e.outcome!="string"||!ms.includes(e.outcome)||typeof e.stdoutSha256!="string"||!/^[a-f0-9]{64}$/.test(e.stdoutSha256)||typeof e.stderrSha256!="string"||!/^[a-f0-9]{64}$/.test(e.stderrSha256)||!n(e.stdoutBytes)||!n(e.stderrBytes)||e.publicSafe!==!0)throw new Error("private-executor-receipt-invalid");return e}function vs(e){return{schemaVersion:1,hostKind:e.hostKind,hostVersion:e.hostVersion,executorProof:{schemaVersion:7,preflight:"passed",hostVersion:"passed",stdinOnly:"passed",ephemeralHome:"passed",nativeNoPersistence:"passed",os:"passed"}}}function uo(e){return{schemaVersion:1,hostKind:"codex-cli",hostVersion:e.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:e.observedAtMs}}}async function Cs(e,t,n){const{captureDirectYoloCheckoutEvidence:o}=await import("../git/direct-yolo-checkpoint.js"),i=()=>new Error("private-executor-workspace-effect-unverified"),r=n.requireWorkspaceEffect?await o(n.workspaceRoot).catch(()=>{throw i()}):void 0;if(r&&n.expectedExecutionBranch!==void 0&&r.branch!==n.expectedExecutionBranch)throw i();let a;try{a=await e.run(t)}catch(u){throw new Error(u instanceof Error&&Ln.test(u.message)?u.message:"private-executor-run-failed")}const s=Ss(a,n.hostKind);if(s.outcome!=="executor-returned-unverified")throw new Error(s.outcome);if(r){const u=await o(n.workspaceRoot).catch(()=>{throw i()});if(u.headSha!==r.headSha||u.branch!==r.branch||u.payloadDigest===r.payloadDigest)throw i()}return s}function _s(e){if(e.writeSetId==="idea-diagnosis-v1"&&e.stepId==="step-acd455ed")return"diagnosis";throw new Error(e.codexV6?"private-execution-planning-root-protocol-required":"private-execution-planning-step-unsupported")}function al(e,t=process.cwd()){return Ma(e,t)}async function lo(e){return(await Va({explicitRoot:e})).root}const ws=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,Rs="Reinstall Neocortex with optional dependencies and lifecycle scripts enabled, or run `npm rebuild better-sqlite3` from the installed package root before retrying the same request.";function ho(e){const t=f(e)&&e.code==="sqlite-adapter-unavailable"?"sqlite-adapter-unavailable":"native-custody-observation-failed";return Object.freeze({schemaVersion:1,reasonCode:t,remediation:t==="sqlite-adapter-unavailable"?Rs:"Run the Neocortex doctor, repair the reported local continuity-store condition, then retry the same yoloop request.",retrySafeAfterRepair:!0,publicSafe:!0})}function As(e){if(!f(e)||e.schemaVersion!==1||e.reasonCode!=="sqlite-adapter-unavailable"&&e.reasonCode!=="native-custody-observation-failed"||e.retrySafeAfterRepair!==!0||e.publicSafe!==!0)return;const t=ho(e.reasonCode==="sqlite-adapter-unavailable"?{code:"sqlite-adapter-unavailable"}:void 0);if(e.remediation===t.remediation)return Object.freeze({schemaVersion:1,reasonCode:e.reasonCode,remediation:t.remediation,retrySafeAfterRepair:!0,publicSafe:!0})}function fo(e,t){if(t.success||Hr(t.metadata?.semanticGateRemediation))return t;const o=(t.errorCode===Gi?Hi(t.metadata?.privateExecutionWorkspaceFailure):void 0)?.reason_code??(t.errorCode&&ws.test(t.errorCode)?t.errorCode:"INVOKE_ERROR"),i=mc({templateId:"gate-manual-resolution-v1",reasonCode:o,requestSha256:Wi(e)});return{...t,...o==="story-worktree-base-divergent"?{error:"The admitted story base is outside the execution branch history. For an unstarted epic moved to a verified origin, audit the origin binding with story-worktree rebind-origin --dry-run. Epics with story progress require reconciliation of their existing dispatches."}:{},metadata:{...t.metadata,semanticGateRemediation:i}}}function bs(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 xs(e){const t=e.metadata;if(!t||!(t.yoloopReleaseBlocked===!0||t.terminalClass==="release-blocked"||t.releaseBlocked!==void 0))return;const o=oc(t.releaseBlocked);return!o||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:o},error:"YOLOOP_RELEASE_BLOCKED: the current release attempt ended without success.",errorCode:"YOLOOP_RELEASE_BLOCKED",exitCode:1}}function jn(e){return lc(e,{registryVersion:Rt,registryChecksum:wt})}function Ts(e){return Sc(e,{registryVersion:Rt,registryChecksum:wt})}const Ps=new Set(["completed","aborted","cancelled"]),ks=new Set(["watch-target-missing","watch-target-malformed","watch-target-ambiguous","watch-target-multiple"]),Ne=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"}),He=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"}),Q=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"}),go=240,Os=/(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 Ns(e){return e.replace(/[\w.+-]+@[\w-]+\.[\w.-]+/g,Lt).replace(/(?:sk|pk|whsec|nxk)[-_](?:test|live|ant|proj|pro|free|enterprise)?[-_]?[A-Za-z0-9_-]{16,}/g,Lt).replace(/NX-[FPE]-[a-f0-9]{24}-[a-f0-9]{4}/g,Lt).replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,Lt).replace(ss,Lt).replace(ds,Lt)}function nt(e,t){const n=Ns(e);return n.length<=t?n:`${n.slice(0,t)}\u2026[TRUNCATED:${n.length-t}]`}function Mn(e,t=0,n=new WeakSet){if(t>as)return"[MAX_DEPTH]";if(e==null)return e;if(typeof e=="string")return nt(e,zt);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(n.has(e))return"[CIRCULAR]";n.add(e);try{if(Array.isArray(e))return e.slice(0,is).map(i=>Mn(i,t+1,n));const o={};for(const[i,r]of Object.entries(e).slice(0,os)){if(cs.test(i)){o[i]=Lt;continue}const a=Mn(r,t+1,n);a!==void 0&&(o[i]=a)}return o}finally{n.delete(e)}}}function qr(e,t){return{instructions:nt(e??"",ns),metadata:t?Mn(t):void 0}}function Ds(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e,n=typeof t.reason=="string"&&/^[a-z0-9-]{1,80}$/.test(t.reason)?t.reason:void 0,o=typeof t.baseSource=="string"&&["active-story-lease","published-execution-branch","local-default-branch","remote-default-branch","none"].includes(t.baseSource)?t.baseSource:void 0,i=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,a=t.recollectionCount===0||t.recollectionCount===1?t.recollectionCount:void 0;if(!(!n||!o||!i||!r||a===void 0||t.publicSafe!==!0))return{reason:n,base_source:o,repair:i,recollection_count:a,fallback_action:r,public_safe:!0}}class Kr extends Error{reason;source;byteLength;code;constructor(t,n,o,i,r){super(n),this.reason=o,this.source=i,this.byteLength=r,this.name="InvokeCliInputError",this.code=t}}function Ls(e){const t=Br(e);return(t==="arch-plan"||t==="ui-ux-review")&&js(e,"--project-evidence")}function js(e,t){let n=null,o=-1,i=!1,r=!1;for(let a=0;a<=e.length;a+=1){const s=e[a];if(a===e.length||!n&&/\s/.test(s??"")){if(o>=0&&!i&&e.slice(o,a)===t)return!0;o=-1,i=!1,r=!1;continue}if(o<0&&(o=a),r){r=!1;continue}if(s==="\\"){r=!0;continue}(s==='"'||s==="'")&&(i=!0,n=n===s?null:n??s)}return!1}const Ms=/(?:^|\s)codex(?:-cli)?\s+([A-Za-z0-9][A-Za-z0-9._+-]{0,63})(?:\s|$)/i;function Vs(e,t){if(e.targetId!=="codex")return null;const n=t.CODEX_VERSION?.trim();if(n&&/^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/.test(n))return n;try{return Ae("codex",["--version"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim().match(Ms)?.[1]??null}catch{return null}}function Vn(e=!1){return wc({clientVersion:Dt,registryVersion:Rt,registryChecksum:wt,capabilityIds:Object.values(Gr).filter(t=>e||t!==Gr.DIAGNOSE_SCOPED_CONTINUATION),schemaVersions:Object.values(Wr).filter(t=>e||t!==Wr.DIAGNOSE_SCOPED_CONTINUATION)})}class Bn extends Error{code="PAYLOAD_TOO_LARGE";telemetry;constructor(t){super(`PAYLOAD_TOO_LARGE: invoke request is ${t.payloadBytes} bytes after deterministic degradation; limit is ${t.limitBytes}. Reduce command input or local state context and retry.`),this.name="InvokePayloadTooLargeError",this.telemetry=t}}class $n extends Error{code="STRUCTURAL_CONTEXT_TOO_LARGE";telemetry;constructor(t){super(`STRUCTURAL_CONTEXT_TOO_LARGE: the bounded structural projection is ${t.payloadBytes} bytes; the request limit is strictly below ${t.limitBytes}. Select an explicit epic/story target or split the dependency graph.`),this.name="InvokeStructuralContextTooLargeError",this.telemetry=t}}let Un=!1;function Bs(e){const t=[];if(!e||typeof e!="object")return t;const n=e,o=n.planning;if(o&&(o.current!==void 0||Array.isArray(o.history))&&t.push({code:"PLANNING_LEGACY",message:"legacy `planning.current`/`planning.history` detected (not read by v1 orchestrator)"}),Array.isArray(n.stories)&&t.push({code:"STORIES_AS_ARRAY",message:"`stories` is an Array (expected Object keyed by story ID)"}),n.epics&&typeof n.epics=="object"&&!Array.isArray(n.epics))for(const[r,a]of Object.entries(n.epics)){const s=a;if(s&&s.stories!==void 0&&!Array.isArray(s.stories)){t.push({code:"EPIC_STORIES_NOT_ARRAY",message:`epic "${r}" has non-array \`stories\` field (expected string[] of story IDs)`});break}}const i=n.epics&&typeof n.epics=="object"&&Object.keys(n.epics).length>0||n.stories&&typeof n.stories=="object"&&!Array.isArray(n.stories)&&Object.keys(n.stories).length>0||Array.isArray(n.stories)||o&&o.current!==void 0;return n.schema_version===void 0?i&&t.push({code:"SCHEMA_VERSION_MISSING",message:"`schema_version` field missing (expected: `schema_version: 1`)"}):n.schema_version!==1&&t.push({code:"SCHEMA_VERSION_OUTDATED",message:`schema_version=${String(n.schema_version)} (expected: 1)`}),t}function $s(e){if(!(Un||e.length===0)){Un=!0;try{const t=e.map(n=>` - ${n.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 tl(){Bn=!1}function hi(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function js(e){return e==="active"||e==="archived"||e==="rolled-back"||e==="synthetic"||e==="orphan"?e:void 0}const Ms=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"]),Vs=/(?:[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,Bs=/^[a-z0-9][a-z0-9-]{0,127}$/;function $s(e,t){if(!f(e)||e.schemaVersion!==1||e.epicId!==t||!/^P\d+$/.test(t))return{};try{const n=JSON.stringify(e),i=Buffer.byteLength(n);if(i>Ro)return{diagnostic:Object.freeze({schemaVersion:"CreateEpicPlanningProjectionDiagnostic/1.1",outcome:"omitted",reasonCode:"budget-omitted",byteLength:i,maxBytes:Ro,publicSafe:!0})};if(Vs.test(n))return{};const o=(a,s)=>{if(Object.keys(a).some(u=>!s.includes(u)))throw new Error("planning-unknown-field")};if(o(e,["schemaVersion","epicId","intake","intakeRevision","diagnosisReceipt","researchReceipt","degradeAuthorization"]),!f(e.intake))return{};if(Object.keys(e.intake).some(a=>!Ms.has(a)))return{};for(const[a,s]of Object.entries(e.intake))if(["examples","contracts"].includes(a)){const u=a==="examples"?["id","title","actor","given","when","then","source","coveredRequirement","expectedValidation"]:["id","kind","description","path"];if(!Array.isArray(s)||s.length>16)return{};for(const g of s){if(!f(g))return{};if(o(g,u),Object.values(g).some(d=>typeof d!="string"||d.length>256))return{}}}else if(Array.isArray(s)){if(s.length>32||s.some(u=>typeof u!="string"||u.length>256))return{}}else if(typeof s=="string"){if(s.length>(a==="rawIntent"?_a:512))return{}}else if(typeof s!="boolean"||!["uiScope","remediationStory"].includes(a))return{};const r=["schemaVersion","kind","epicId","intakeRevision","artifactSummary","artifactDigest","predecessorReceiptId","accepted","receiptId"];for(const a of[e.diagnosisReceipt,e.researchReceipt])if(a!==void 0){if(!f(a))return{};if(o(a,r),Object.values(a).some(s=>typeof s=="string"&&s.length>1024))return{}}if(e.degradeAuthorization!==void 0){if(!f(e.degradeAuthorization))return{};o(e.degradeAuthorization,["approved","intakeRevision","reasonCodes","assumptionCodes"]);for(const a of["reasonCodes","assumptionCodes"]){const s=e.degradeAuthorization[a];if(!Array.isArray(s)||s.length>32||s.some(u=>typeof u!="string"||!Bs.test(u)))return{}}}return{checkpoint:JSON.parse(n)}}catch{return{}}}function fi(e){return e==="create-epic"||e==="discovered"?e:void 0}function ge(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function gi(e){if(!f(e))return;const t=/^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/;if(Object.keys(e).some(s=>!["epicId","storyId","integrationReceiptId","mergedCommit","digest"].includes(s)))return;const i=s=>typeof s=="string"&&t.test(s)&&!s.includes("..");if(!i(e.epicId)||e.storyId!==void 0&&!i(e.storyId))return;const o=e.integrationReceiptId,r=e.mergedCommit;if(o===void 0&&r===void 0||o!==void 0&&(typeof o!="string"||!/^[A-Za-z0-9][A-Za-z0-9_-]{7,95}$/.test(o))||r!==void 0&&(typeof r!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(r)))return;const a=e.digest;if(!(a!==void 0&&(typeof a!="string"||!/^[a-f0-9]{64}$/.test(a))))return{epicId:e.epicId,...e.storyId!==void 0?{storyId:e.storyId}:{},...o!==void 0?{integrationReceiptId:o}:{},...r!==void 0?{mergedCommit:r}:{},...a!==void 0?{digest:a}:{}}}function Us(e){const t={};let n=!1;for(const i of["contracts","contract_refs","shared_surfaces","adr_refs","nfr_refs","acceptance_depends_on"]){if(e[i]===void 0)continue;const o=e[i];if(!Array.isArray(o)||o.length>128||o.some(r=>Fr(r)===void 0)){n=!0;continue}t[i]=o.map(r=>Fr(r))}if(e.planning!==void 0)try{if(!f(e.planning))throw new Error("planning-shape");const i=e.planning;for(const a of["claims","semanticArtifacts"]){if(i[a]===void 0)continue;const s=i[a];if(!Array.isArray(s)||s.length>128||s.some(u=>!f(u)||Fr(u.ref)===void 0))throw new Error("planning-refs")}if(i.attempts!==void 0&&(!Array.isArray(i.attempts)||i.attempts.length>32))throw new Error("planning-attempts");for(const a of i.attempts??[]){if(!f(a)||!Array.isArray(a.reasonCodes)||a.reasonCodes.length>32||a.reasonCodes.some(s=>typeof s!="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(s)))throw new Error("planning-attempt-reasons");if(a.discoveredClaims!==void 0&&(!Array.isArray(a.discoveredClaims)||a.discoveredClaims.length>128||a.discoveredClaims.some(s=>!f(s)||Fr(s.ref)===void 0)))throw new Error("planning-attempt-claims")}const{graphRevision:o,...r}=Ac(i);t.planning=r}catch{n=!0}return n&&(t.planning={schemaVersion:1,dependencyBasis:"unknown",claims:[],semanticArtifacts:[]}),t}function f(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function jt(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function ue(e){if(typeof e!="string")return;const t=e.trim();if(t)return t.replace(/[^a-z0-9_.:-]+/gi,"_").slice(0,120)}function oe(e){if(typeof e!="string")return;const t=e.trim(),n=ue(e);return n===t?n:void 0}function _e(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240)&&/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(t)&&!(t.includes("..")||t.includes("//")||t.includes("@{")||t.endsWith("/")||t.endsWith("."))&&!t.split("/").some(n=>!n||n.startsWith(".")||n.endsWith(".lock")))return t}function x(e){return typeof e=="string"&&/^[0-9a-f]{7,64}$/i.test(e)?e:void 0}function He(e){if(!(typeof e!="string"||e.length>64)&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/.test(e))return Number.isFinite(Date.parse(e))?e:void 0}function At(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240||t.includes("..")))return/^[A-Za-z0-9._:/#\-[\]]+$/.test(t)?t:void 0}function Jr(e){if(!f(e))return;const t=l=>typeof l=="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,95}$/.test(l),n=l=>typeof l=="string"&&/^[a-f0-9]{64}$/.test(l),i=(l,E)=>Array.isArray(l)&&l.length<=E&&l.every(t)&&new Set(l).size===l.length?l:void 0,o=(l,E)=>{if(!(!f(l)||l.schemaVersion!==2||!t(l.requestId)||!t(l.stageCommand)||!n(l.requestHash)||!n(l.inputHash)||!n(l.stateHash)||!n(l.nonce)||!n(l.stageRevision)||!n(l.stageHash)||!n(l.catalogHash)||l.targetEpicId!==void 0&&!t(l.targetEpicId)||E&&(!n(l.outputHash)||!n(l.artifactHash))))return{schemaVersion:2,...l.targetEpicId?{targetEpicId:l.targetEpicId}:{},requestId:l.requestId,requestHash:l.requestHash,inputHash:l.inputHash,stateHash:l.stateHash,nonce:l.nonce,stageCommand:l.stageCommand,stageRevision:l.stageRevision,stageHash:l.stageHash,catalogHash:l.catalogHash,...E?{outputHash:l.outputHash,artifactHash:l.artifactHash}:{}}},r=(l,E)=>{if(!(!f(l)||l.schemaVersion!=="1.1"||l.kind!==E||!n(l.receiptId)||!n(l.graphHash)||!n(l.evidenceHash)||!t(l.elementId)||!t(l.caseId)||!t(l.category)))return{schemaVersion:"1.1",kind:E,receiptId:l.receiptId,graphHash:l.graphHash,elementId:l.elementId,caseId:l.caseId,category:l.category,evidenceHash:l.evidenceHash}},a=(l,E)=>{if(!f(l)||l.kind!==E||!n(l.receiptId)||!i(l.evidenceIds,24)||E==="architecture-stage-completion"&&!["succeeded","failed"].includes(String(l.status))||E==="architecture-stage-validation"&&!["passed","failed","pending"].includes(String(l.status)))return;const _=o(l,!0);if(!_)return;const w=E==="architecture-stage-validation"?r(l.isolated,"isolated"):void 0,S=E==="architecture-stage-validation"?r(l.regression,"regression"):void 0;if(!(E==="architecture-stage-validation"&&(!w||!S)))return{..._,kind:E,receiptId:l.receiptId,status:l.status,evidenceIds:l.evidenceIds,...w&&S?{isolated:w,regression:S}:{}}},s={};e.schemaVersion===1&&(s.schemaVersion=1),e.owner==="root"&&(s.owner="root"),t(e.currentStageCommand)&&(s.currentStageCommand=e.currentStageCommand),["ask-user","delegate","resume","advance","blocked","complete"].includes(String(e.continuationState))&&(s.continuationState=e.continuationState);const u=i(e.questionIds,16);if(u&&(s.questionIds=u),(e.childStatus==="succeeded"||e.childStatus==="failed")&&(s.childStatus=e.childStatus),(e.evidencePolicy==="legacy-compatible"||e.evidencePolicy==="v2-required")&&(s.evidencePolicy=e.evidencePolicy),t(e.targetEpicId)&&(s.targetEpicId=e.targetEpicId),n(e.graphRevision)&&(s.graphRevision=e.graphRevision),e.graphSource==="committed-epic-v1"&&(s.graphSource=e.graphSource),e.nonUiScopeReceipt!==void 0){const l=yo(e.nonUiScopeReceipt);if(!l||l.targetEpicId!==e.targetEpicId||l.graphRevision!==e.graphRevision||!f(e.accounting)||l.accountingId!==e.accounting.accountingId||!f(e.evidenceExpectation)||l.rootInputSha256!==e.evidenceExpectation.inputHash)throw new Error("architecture-non-ui-scope-invalid");s.nonUiScopeReceipt=l}f(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&&n(e.pactAnswerReceipt.stateSha256)&&n(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&&(s.pactAnswerReceipt=e.pactAnswerReceipt);const g=o(e.evidenceExpectation,!1);g&&(s.evidenceExpectation=g);const d=a(e.completionEvidence,"architecture-stage-completion"),h=a(e.validationEvidence,"architecture-stage-validation");if(d&&(s.completionEvidence=d),h&&(s.validationEvidence=h),f(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&&n(e.reviewDecision.graphRevision)&&n(e.reviewDecision.artifactHash)&&n(e.reviewDecision.completionReceiptId)&&n(e.reviewDecision.validationReceiptId)&&["approved","changes-requested"].includes(String(e.reviewDecision.decision))&&e.reviewDecision.publicSafe===!0){const l=i(e.reviewDecision.evidenceIds,24);l&&l.length>0&&(s.reviewDecision={...e.reviewDecision,evidenceIds:l})}if(hr(e.terminalMemoryCheckpoint,e))s.terminalMemoryCheckpoint=e.terminalMemoryCheckpoint;else if(f(e.terminalMemoryCheckpoint)&&e.terminalMemoryCheckpoint.schemaVersion===void 0&&["passed","failed","pending"].includes(String(e.terminalMemoryCheckpoint.status))){const l=i(e.terminalMemoryCheckpoint.evidenceIds,24);l&&(s.terminalMemoryCheckpoint={status:e.terminalMemoryCheckpoint.status,evidenceIds:l})}if(Array.isArray(e.acceptedStages)&&e.acceptedStages.length<=15){const l=e.acceptedStages.map(E=>{if(!f(E)||!t(E.targetEpicId)||!t(E.stageCommand))return;const _=a(E.completionEvidence,"architecture-stage-completion"),w=a(E.validationEvidence,"architecture-stage-validation");return _&&w?{targetEpicId:E.targetEpicId,stageCommand:E.stageCommand,completionEvidence:_,validationEvidence:w}:void 0});l.every(E=>E!==void 0)&&(s.acceptedStages=l)}if(f(e.accounting)&&e.accounting.schemaVersion===1&&t(e.accounting.contractVersion)&&t(e.accounting.accountingId)&&typeof e.accounting.charged=="boolean"&&Number.isInteger(e.accounting.chargedQuotaUnits)&&typeof e.accounting.chargedQuotaUnits=="number"&&e.accounting.chargedQuotaUnits>=0&&e.accounting.chargedQuotaUnits<=13){const l=i(e.accounting.receiptIds,32);l&&(s.accounting={schemaVersion:1,contractVersion:e.accounting.contractVersion,accountingId:e.accounting.accountingId,charged:e.accounting.charged,chargedQuotaUnits:e.accounting.chargedQuotaUnits,receiptIds:l,...["in-progress","aborted","timed-out","failed","complete"].includes(String(e.accounting.lastOutcome))?{lastOutcome:e.accounting.lastOutcome}:{}})}return JSON.stringify(s).length<=96e3?s:void 0}function Hs(e){const t=f(e.metadata.archPlan)?e.metadata.archPlan.execution:void 0,n=f(t)?t.checkpoint:void 0,i=f(t)?t:void 0,o=f(n)?n:void 0,r=e.requestExecution,a=Array.isArray(o?.acceptedStages)?o.acceptedStages:[],s=r.currentStageCommand==="arch-prd"&&r.continuationState==="delegate"&&r.completionEvidence===void 0&&r.validationEvidence===void 0&&o?.currentStageCommand==="arch-prd"&&o.continuationState==="delegate"&&a.length===0&&i?.nextAction==="delegate",u=r.currentStageCommand==="arch-prd"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&o?.currentStageCommand==="arch-architecture"&&o.continuationState==="advance"&&a.length===1&&f(a[0])&&a[0].stageCommand==="arch-prd"&&v(a[0].completionEvidence,r.completionEvidence)&&v(a[0].validationEvidence,r.validationEvidence)&&i?.nextAction==="resume",g=r.currentStageCommand==="arch-architecture"&&r.continuationState==="advance"&&o?.currentStageCommand==="arch-architecture"&&o.continuationState==="delegate"&&a.length===1&&v(a,r.acceptedStages)&&i?.nextAction==="delegate",d=r.currentStageCommand==="arch-architecture"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&o?.currentStageCommand==="arch-fitness-functions"&&o.continuationState==="advance"&&a.length===2&&f(a[0])&&f(a[1])&&a[0].stageCommand==="arch-prd"&&a[1].stageCommand==="arch-architecture"&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===1&&v(a[0],r.acceptedStages[0])&&v(a[1].completionEvidence,r.completionEvidence)&&v(a[1].validationEvidence,r.validationEvidence)&&i?.nextAction==="resume",h=r.currentStageCommand==="arch-fitness-functions"&&r.continuationState==="advance"&&o?.currentStageCommand==="arch-fitness-functions"&&o.continuationState==="delegate"&&a.length===2&&f(a[0])&&f(a[1])&&a[0].stageCommand==="arch-prd"&&a[1].stageCommand==="arch-architecture"&&v(a,r.acceptedStages)&&i?.nextAction==="delegate",l=r.currentStageCommand==="arch-fitness-functions"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&o?.currentStageCommand==="arch-api-contracts"&&o.continuationState==="advance"&&a.length===3&&f(a[0])&&f(a[1])&&f(a[2])&&a[0].stageCommand==="arch-prd"&&a[1].stageCommand==="arch-architecture"&&a[2].stageCommand==="arch-fitness-functions"&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===2&&v(a.slice(0,2),r.acceptedStages)&&v(a[2].completionEvidence,r.completionEvidence)&&v(a[2].validationEvidence,r.validationEvidence)&&i?.nextAction==="resume",E=r.currentStageCommand==="arch-api-contracts"&&r.continuationState==="advance"&&o?.currentStageCommand==="arch-api-contracts"&&o.continuationState==="delegate"&&a.length===3&&f(a[0])&&f(a[1])&&f(a[2])&&a[0].stageCommand==="arch-prd"&&a[1].stageCommand==="arch-architecture"&&a[2].stageCommand==="arch-fitness-functions"&&v(a,r.acceptedStages)&&i?.nextAction==="delegate",_=["PACT-Q1-CONSUMER","PACT-Q2-PROVIDER","PACT-Q3-BROKER","PACT-Q4-MATCHERS","PACT-Q5-VERIFY"],w=r.currentStageCommand==="arch-api-contracts"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&o?.currentStageCommand==="generate-pacts"&&o.continuationState==="ask-user"&&a.length===4&&f(a[3])&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===3&&v(a.slice(0,3),r.acceptedStages)&&a[3].stageCommand==="arch-api-contracts"&&v(a[3].completionEvidence,r.completionEvidence)&&v(a[3].validationEvidence,r.validationEvidence)&&v(o.questionIds,_)&&v(i?.questionIds,_)&&i?.nextAction==="ask-user",S=r.currentStageCommand==="generate-pacts"&&r.continuationState==="ask-user"&&o?.currentStageCommand==="generate-pacts"&&o.continuationState==="delegate"&&a.length===4&&v(a,r.acceptedStages)&&v(r.questionIds,_)&&v(o.questionIds,[])&&v(o.pactAnswerReceipt,e.answerReceipt)&&v(i?.pactAnswerReceipt,e.answerReceipt)&&e.answerReceipt?.stateSha256===e.sourceStateSha256&&i?.nextAction==="resume",y=r.currentStageCommand==="generate-pacts"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&v(r.pactAnswerReceipt,e.pactRecordedReceipt)&&o?.currentStageCommand==="arch-api-integrations"&&o.continuationState==="advance"&&a.length===5&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===4&&v(a.slice(0,4),r.acceptedStages)&&a.map(k=>f(k)?k.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts"&&f(a[4])&&v(a[4].completionEvidence,r.completionEvidence)&&v(a[4].validationEvidence,r.validationEvidence)&&i?.nextAction==="resume",D=r.currentStageCommand==="arch-api-integrations"&&r.continuationState==="advance"&&o?.currentStageCommand==="arch-api-integrations"&&o.continuationState==="delegate"&&a.length===5&&v(a,r.acceptedStages)&&i?.nextAction==="delegate",U=r.currentStageCommand==="arch-api-integrations"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&o?.currentStageCommand==="arch-database"&&o.continuationState==="advance"&&a.length===6&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===5&&v(a.slice(0,5),r.acceptedStages)&&a.map(k=>f(k)?k.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations"&&f(a[5])&&v(a[5].completionEvidence,r.completionEvidence)&&v(a[5].validationEvidence,r.validationEvidence)&&i?.nextAction==="resume",b=r.currentStageCommand==="arch-database"&&r.continuationState==="advance"&&o?.currentStageCommand==="arch-database"&&o.continuationState==="delegate"&&a.length===6&&v(a,r.acceptedStages)&&i?.nextAction==="delegate",C=r.currentStageCommand==="arch-database"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&o?.currentStageCommand==="arch-security"&&o.continuationState==="advance"&&a.length===7&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===6&&v(a.slice(0,6),r.acceptedStages)&&a.map(k=>f(k)?k.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database"&&f(a[6])&&v(a[6].completionEvidence,r.completionEvidence)&&v(a[6].validationEvidence,r.validationEvidence)&&i?.nextAction==="resume",A=r.currentStageCommand==="arch-security"&&r.continuationState==="advance"&&o?.currentStageCommand==="arch-security"&&o.continuationState==="delegate"&&a.length===7&&v(a,r.acceptedStages)&&i?.nextAction==="delegate",Y=r.currentStageCommand==="arch-security"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&o?.currentStageCommand==="arch-design-system"&&o.continuationState==="advance"&&a.length===8&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===7&&v(a.slice(0,7),r.acceptedStages)&&a.map(k=>f(k)?k.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security"&&f(a[7])&&v(a[7].completionEvidence,r.completionEvidence)&&v(a[7].validationEvidence,r.validationEvidence)&&i?.nextAction==="resume",Z=r.currentStageCommand==="arch-design-system"&&r.continuationState==="advance"&&o?.currentStageCommand==="arch-design-system"&&o.continuationState==="delegate"&&a.length===8&&v(a,r.acceptedStages)&&i?.nextAction==="delegate",Q=r.currentStageCommand==="arch-design-system"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&o?.currentStageCommand==="arch-ux-design"&&o.continuationState==="advance"&&a.length===9&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===8&&v(a.slice(0,8),r.acceptedStages)&&a.map(k=>f(k)?k.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system"&&f(a[8])&&v(a[8].completionEvidence,r.completionEvidence)&&v(a[8].validationEvidence,r.validationEvidence)&&i?.nextAction==="resume",j=r.currentStageCommand==="arch-ux-design"&&r.continuationState==="advance"&&o?.currentStageCommand==="arch-ux-design"&&o.continuationState==="delegate"&&a.length===9&&v(a,r.acceptedStages)&&i?.nextAction==="blocked",ae=r.currentStageCommand==="arch-ux-design"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&o?.currentStageCommand==="arch-performance"&&o.continuationState==="advance"&&a.length===10&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===9&&v(a.slice(0,9),r.acceptedStages)&&a.map(k=>f(k)?k.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design"&&f(a[9])&&v(a[9].completionEvidence,r.completionEvidence)&&v(a[9].validationEvidence,r.validationEvidence)&&i?.nextAction==="resume",ve=r.currentStageCommand==="arch-performance"&&r.continuationState==="advance"&&o?.currentStageCommand==="arch-performance"&&o.continuationState==="delegate"&&a.length===10&&v(a,r.acceptedStages)&&i?.nextAction==="delegate",be=r.currentStageCommand==="arch-performance"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&o?.currentStageCommand==="arch-testing"&&o.continuationState==="advance"&&a.length===11&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===10&&v(a.slice(0,10),r.acceptedStages)&&a.map(k=>f(k)?k.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance"&&f(a[10])&&v(a[10].completionEvidence,r.completionEvidence)&&v(a[10].validationEvidence,r.validationEvidence)&&i?.nextAction==="resume",T=r.currentStageCommand==="arch-testing"&&r.continuationState==="advance"&&o?.currentStageCommand==="arch-testing"&&o.continuationState==="delegate"&&a.length===11&&v(a,r.acceptedStages)&&i?.nextAction==="delegate",ee=r.currentStageCommand==="arch-testing"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&o?.currentStageCommand==="arch-infrastructure"&&o.continuationState==="advance"&&a.length===12&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===11&&v(a.slice(0,11),r.acceptedStages)&&a.map(k=>f(k)?k.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance,arch-testing"&&f(a[11])&&v(a[11].completionEvidence,r.completionEvidence)&&v(a[11].validationEvidence,r.validationEvidence)&&i?.nextAction==="resume",Ce=r.currentStageCommand==="arch-infrastructure"&&r.continuationState==="advance"&&o?.currentStageCommand==="arch-infrastructure"&&o.continuationState==="delegate"&&a.length===12&&v(a,r.acceptedStages)&&i?.nextAction==="delegate",xe=r.currentStageCommand==="arch-infrastructure"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&o?.currentStageCommand==="arch-review"&&o.continuationState==="advance"&&a.length===13&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===12&&v(a.slice(0,12),r.acceptedStages)&&a.map(k=>f(k)?k.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance,arch-testing,arch-infrastructure"&&f(a[12])&&v(a[12].completionEvidence,r.completionEvidence)&&v(a[12].validationEvidence,r.validationEvidence)&&i?.nextAction==="resume",ie=r.currentStageCommand==="arch-review"&&r.continuationState==="advance"&&o?.currentStageCommand==="arch-review"&&o.continuationState==="delegate"&&a.length===13&&v(a,r.acceptedStages)&&i?.nextAction==="delegate",B=r.currentStageCommand==="arch-review"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&r.reviewDecision===void 0&&o?.currentStageCommand==="arch-review"&&o.continuationState==="ask-user"&&a.length===13&&v(a,r.acceptedStages)&&v(o.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&v(o.completionEvidence,r.completionEvidence)&&v(o.validationEvidence,r.validationEvidence)&&i?.nextAction==="ask-user",Je=r.currentStageCommand==="arch-review"&&r.continuationState==="ask-user"&&r.childStatus==="succeeded"&&f(r.reviewDecision)&&r.reviewDecision.decision==="approved"&&v(r.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&o?.currentStageCommand==="update-memory"&&o.continuationState==="advance"&&a.length===14&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===13&&v(a.slice(0,13),r.acceptedStages)&&f(a[13])&&a[13].stageCommand==="arch-review"&&v(a[13].completionEvidence,r.completionEvidence)&&v(a[13].validationEvidence,r.validationEvidence)&&v(o.reviewDecision,r.reviewDecision)&&i?.nextAction==="resume",me=r.currentStageCommand==="update-memory"&&r.continuationState==="advance"&&f(r.reviewDecision)&&r.reviewDecision.decision==="approved"&&o?.currentStageCommand==="update-memory"&&o.continuationState==="delegate"&&a.length===14&&v(a,r.acceptedStages)&&v(o.reviewDecision,r.reviewDecision)&&i?.nextAction==="delegate",$=r.currentStageCommand==="update-memory"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&o?.currentStageCommand==="update-memory"&&o.continuationState==="complete"&&a.length===15&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===14&&v(a.slice(0,14),r.acceptedStages)&&f(a[14])&&a[14].targetEpicId===r.targetEpicId&&a[14].stageCommand==="update-memory"&&v(a[14].completionEvidence,r.completionEvidence)&&v(a[14].validationEvidence,r.validationEvidence)&&v(o.reviewDecision,r.reviewDecision)&&v(o.completionEvidence,r.completionEvidence)&&v(o.validationEvidence,r.validationEvidence)&&hr(o.terminalMemoryCheckpoint,r)!==null&&v(o.terminalMemoryCheckpoint,r.terminalMemoryCheckpoint)&&i?.nextAction==="complete",ye=r.currentStageCommand==="update-memory"&&r.continuationState==="complete"&&r.childStatus==="succeeded"&&o?.currentStageCommand==="update-memory"&&o.continuationState==="complete"&&a.length===15&&v(a,r.acceptedStages)&&v(o.reviewDecision,r.reviewDecision)&&v(o.completionEvidence,r.completionEvidence)&&v(o.validationEvidence,r.validationEvidence)&&hr(o.terminalMemoryCheckpoint,r)&&v(o.terminalMemoryCheckpoint,r.terminalMemoryCheckpoint)&&i?.nextAction==="complete",gt=i?ua(r,i,hr(r.terminalMemoryCheckpoint,r)&&v(o?.terminalMemoryCheckpoint,r.terminalMemoryCheckpoint)):void 0;if(e.metadata.mode!=="arch-plan"||e.metadata.resolvedTrigger!=="arch-plan"||!f(t)||!f(n)||t.owner!=="root"||t.currentStageCommand!==n.currentStageCommand||t.continuationState!==n.continuationState||n.owner!=="root"||n.evidencePolicy!=="v2-required"||n.targetEpicId!==r.targetEpicId||n.graphRevision!==r.graphRevision||n.graphSource!==r.graphSource||!/^P[1-9][0-9]{0,11}$/.test(String(n.targetEpicId))||!/^[a-f0-9]{64}$/.test(String(n.graphRevision))||!Array.isArray(n.acceptedStages)||!(gt||s||u||g||d||h||l||E||w||S||y||D||U||b||C||A||Y||Z||Q||j||ae||ve||be||T||ee||Ce||xe||ie||B||Je||me||$||ye)||!f(n.accounting)||n.accounting.charged!==!0||!v(Jr(n),n))throw new Error("architecture-root-checkpoint-invalid");const et=q(e.projectRoot,".neocortex"),fe=q(et,"state.json"),L=q(et,"state.json.architecture.lock"),H=Ht(L,"wx",384);let Ye;try{const k=nr(fe);if(!k.isFile()||k.isSymbolicLink())throw new Error("architecture-root-state-binding-invalid");const le=$e(fe,"utf8");if(Le("sha256").update(le).digest("hex")!==e.sourceStateSha256)throw new Error("architecture-root-state-conflict");const Qe=JSON.parse(le),Tt=f(Qe)&&f(Qe.archPlan)?Qe.archPlan:{};if(!f(Qe)||!f(Qe.epics)||!Object.hasOwn(Qe.epics,n.targetEpicId)||(e.initialBinding?Tt.execution!==void 0||r.graphSource!=="committed-epic-v1":!v(Jr(Tt.execution),r))||f(Qe.scope)&&Qe.scope.kind==="projected")throw new Error("architecture-root-state-binding-invalid");if(r.graphSource==="committed-epic-v1"&&r.graphRevision!==fr(e.projectRoot,String(r.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");if(ye||gt==="complete-replay"){const Kt={...r,continuationState:"delegate",acceptedStages:r.acceptedStages.slice(0,mo(r))};if(!v(r.terminalMemoryCheckpoint,yn(e.projectRoot,Kt)))throw new Error("architecture-root-state-conflict");return}const Ie=Mr(),Ee=Ae("git",["rev-parse","--git-common-dir"],{cwd:e.projectRoot,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),ce=ma(Ee)?En(Ee):En(e.projectRoot,Ee);if(In(ce)!==ce)throw new Error("architecture-root-backup-dir-invalid");const Se=q(ce,"neocortex-architecture");rr(Se,{recursive:!0,mode:448});const it=nr(Se);if(!it.isDirectory()||it.isSymbolicLink()||it.uid!==process.getuid?.()||(it.mode&63)!==0)throw new Error("architecture-root-backup-dir-invalid");const dr=q(Se,`state-backup-${Ie}.json`),at=Ht(dr,"wx",384);try{Vr(at,le),mr(at)}finally{Gt(at)}const tt=Ht(Se,"r");try{mr(tt)}finally{Gt(tt)}const Ar={...Qe,archPlan:{...Tt,execution:n}};Ye=q(et,`state.json.architecture-tmp-${Ie}`);const rt=Ht(Ye,"wx",384);try{Vr(rt,`${JSON.stringify(Ar,null,2)}
8
- `),mr(rt)}finally{Gt(rt)}if(($||gt==="complete")&&!v(r.terminalMemoryCheckpoint,yn(e.projectRoot,r)))throw new Error("architecture-root-state-conflict");if(r.graphSource==="committed-epic-v1"&&r.graphRevision!==fr(e.projectRoot,String(r.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");Eo(Ye,fe),Ye=void 0;const Xe=Ht(et,"r");try{mr(Xe)}finally{Gt(Xe)}}finally{if(Ye)try{gr(Ye)}catch{}Gt(H),gr(L)}}function Qr(e,t){if(!f(e))return;const n={};for(const i of t){const o=e[i];if(typeof o=="boolean")n[i]=o;else if(typeof o=="number"&&Number.isFinite(o))n[i]=o;else if(typeof o=="string"){const r=ue(o);r&&(n[i]=r)}}return Object.keys(n).length>0?n:void 0}function Xr(e){return e==="epic"||e==="story"?e:void 0}function mi(e){if(!f(e)||e.schemaVersion!==1)return;const t=oe(e.ownerStoryId),n=oe(e.sessionId),i=oe(e.idempotencyKey),o=He(e.acquiredAt),r=He(e.expiresAt);if(!(!t||!n||!i||!o||!r||Date.parse(r)<=Date.parse(o)))return{schemaVersion:1,ownerStoryId:t,sessionId:n,idempotencyKey:i,acquiredAt:o,expiresAt:r}}function yi(e){if(!f(e)||e.schemaVersion!==1)return;const t=oe(e.storyId),n=oe(e.epicId),i=_e(e.branch),o=x(e.baseSha),r=x(e.headSha),a=oe(e.idempotencyKey),s=He(e.recordedAt),u=ge(e.commits).map(x).filter(D=>!!D).slice(0,256),g=ge(e.receiptRefs).map(At).filter(D=>!!D).slice(0,256),d=e.dispatchId===void 0?void 0:oe(e.dispatchId),h=e.bundleId===void 0?void 0:oe(e.bundleId),l=e.bundleDigest===void 0?void 0:x(e.bundleDigest),E=e.graphRevision===void 0?void 0:x(e.graphRevision),_=e.claimRevision===void 0?void 0:oe(e.claimRevision),w=Gs(e.qaReceipt),S=Ws(e.reviewReceipt),y=e.rootMemoryEffect===void 0?void 0:zc(e.rootMemoryEffect)?e.rootMemoryEffect:void 0;if(!(!t||!n||!t.startsWith(`${n}.`)||!i||!o||!r||o===r||!a||!s||u.length===0||g.length===0||!Array.isArray(e.commits)||u.length!==e.commits.length||e.commits.length>256||!Array.isArray(e.receiptRefs)||g.length!==e.receiptRefs.length||e.receiptRefs.length>256||e.dispatchId!==void 0&&!d||e.bundleId!==void 0&&!h||e.bundleDigest!==void 0&&(!l||l.length!==64)||e.graphRevision!==void 0&&(!E||E.length!==64)||e.claimRevision!==void 0&&!_||e.rootMemoryEffect!==void 0&&(!y||y.storyId!==t||y.epicId!==n||y.executionBranch!==i||y.sourceHeadSha!==o||y.childClaimRevision!==_)||e.qaVerdict!=="passed"&&e.qaVerdict!=="blocked"||!["approved","changes-requested","pending"].includes(String(e.reviewVerdict))||!w||e.reviewVerdict!=="pending"&&!S||e.reviewVerdict==="pending"&&S||w.verdict!==e.qaVerdict||S&&S.verdict!==e.reviewVerdict||!Si(w,{storyId:t,epicId:n,baseSha:o,headSha:r,bundleDigest:l,graphRevision:E})||S&&(!Si(S,{storyId:t,epicId:n,baseSha:o,headSha:r,bundleDigest:l,graphRevision:E})||S.qaReceiptRef!==w?.receiptRef||S.receiptRef===w?.receiptRef)||!g.includes(String(w.receiptRef))||S&&(!g.includes(String(S.receiptRef))||Date.parse(String(S.reviewedAt))<Date.parse(String(w.checkedAt)))))return{schemaVersion:1,storyId:t,epicId:n,branch:i,baseSha:o,headSha:r,idempotencyKey:a,...d?{dispatchId:d}:{},...h?{bundleId:h}:{},...l?{bundleDigest:l}:{},...E?{graphRevision:E}:{},..._?{claimRevision:_}:{},...y?{rootMemoryEffect:structuredClone(y)}:{},qaVerdict:e.qaVerdict,reviewVerdict:e.reviewVerdict,...w?{qaReceipt:w}:{},...S?{reviewReceipt:S}:{},recordedAt:s,commits:u,receiptRefs:g}}function Gs(e){if(!f(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=oe(e.storyId),n=oe(e.epicId),i=x(e.baseSha),o=x(e.headSha),r=x(e.bundleDigest),a=x(e.graphRevision),s=x(e.sourceEvidenceDigest),u=He(e.checkedAt),g=At(e.receiptRef),d=e.evidenceVersion==="p205-execution-v2"&&e.contract==="P205-CI-02"?e.contract:void 0,h=e.evidenceVersion==="p205-execution-v2"&&e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,l=e.evidenceVersion==="p205-execution-v2"?x(e.manifestDigest):void 0,E=e.evidenceVersion==="p205-execution-v2"?x(e.resultDigest):void 0,_=e.evidenceVersion==="p205-execution-v2"?ge(e.gateIds).map(oe).filter(w=>!!w).slice(0,64):void 0;if(!(!t||!n||!i||!o||!r||r.length!==64||!a||a.length!==64||!s||s.length!==64||!u||!g||e.evidenceVersion==="p205-execution-v2"&&(!d||h!=="node scripts/test-root.mjs --gate complete"||!l||l.length!==64||!E||E.length!==64||!Array.isArray(e.gateIds)||!_||_.length===0||_.length!==e.gateIds.length)))return{schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",...e.evidenceVersion?{evidenceVersion:e.evidenceVersion}:{},storyId:t,epicId:n,...e.evidenceVersion==="p205-execution-v2"?{contract:d,command:h,manifestDigest:l,gateIds:_,resultDigest:E}:{},baseSha:i,headSha:o,bundleDigest:r,graphRevision:a,sourceEvidenceDigest:s,verdict:e.verdict,checkedAt:u,receiptRef:g}}function Ii(e){if(!f(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=oe(e.storyId),n=oe(e.epicId),i=_e(e.branch),o=x(e.baseSha),r=x(e.headSha),a=x(e.aggregateHeadSha),s=x(e.commitBodyDigest),u=x(e.changedPathsDigest),g=e.claimVerification==="canonical"||e.claimVerification==="legacy-migration"?e.claimVerification:void 0,d=x(e.effectiveClaimRevision),h=e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,l=x(e.manifestDigest),E=ge(e.gateIds).map(oe).filter(b=>!!b).slice(0,64),_=x(e.resultDigest),w=x(e.graphRevision),S=x(e.executionEvidenceDigest),y=x(e.sourceEvidenceDigest),D=He(e.verifiedAt),U=ge(e.reasonCodes).map(oe).filter(b=>!!b).slice(0,16);if(!(!t||!n||!i||!o||o.length<40||!r||r.length<40||!a||a.length<40||!s||s.length!==64||!u||u.length!==64||!g||!d||d.length!==64||!h||!l||l.length!==64||!Array.isArray(e.gateIds)||E.length!==e.gateIds.length||!_||_.length!==64||!w||w.length!==64||!S||S.length!==64||!y||y.length!==64||!D||U.length===0||e.verdict==="verified"&&(E.length===0||!U.includes("checkpoint-p205-transient-verified"))))return{schemaVersion:1,kind:"story_checkpoint_physical_verification",producer:"client-p205-transient-v1",storyId:t,epicId:n,branch:i,baseSha:o,headSha:r,aggregateHeadSha:a,commitBodyDigest:s,changedPathsDigest:u,claimVerification:g,effectiveClaimRevision:d,command:h,manifestDigest:l,gateIds:E,resultDigest:_,graphRevision:w,executionEvidenceDigest:S,sourceEvidenceDigest:y,verifiedAt:D,verdict:e.verdict,reasonCodes:U,publicSafe:!0}}function Ei(e){const t=["schemaVersion","kind","producer","storyId","epicId","branch","baseSha","headSha","graphRevision","effectiveClaimRevision","sourceEvidenceDigest","verifiedAt","reasonCodes","integrationAuthorized","publicSafe"];if(!f(e)||Object.keys(e).some(l=>!t.includes(l))||e.schemaVersion!==1||e.kind!=="story_scheduling_checkpoint_evidence"||e.producer!=="client-git-physical-v1"||e.integrationAuthorized!==!1||e.publicSafe!==!0)return;const n=oe(e.storyId),i=oe(e.epicId),o=_e(e.branch),r=x(e.baseSha),a=x(e.headSha),s=x(e.graphRevision),u=x(e.effectiveClaimRevision),g=x(e.sourceEvidenceDigest),d=He(e.verifiedAt),h=ge(e.reasonCodes).map(oe).filter(l=>!!l);if(!(!n||!i||!o||!r||r.length<40||!a||a.length<40||!s||s.length!==64||!u||u.length!==64||!g||g.length!==64||!d||!Array.isArray(e.reasonCodes)||h.length!==1||h[0]!=="checkpoint-git-scheduling-verified"))return{schemaVersion:1,kind:"story_scheduling_checkpoint_evidence",producer:"client-git-physical-v1",storyId:n,epicId:i,branch:o,baseSha:r,headSha:a,graphRevision:s,effectiveClaimRevision:u,sourceEvidenceDigest:g,verifiedAt:d,reasonCodes:h,integrationAuthorized:!1,publicSafe:!0}}function Ws(e){if(!f(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=oe(e.storyId),n=oe(e.epicId),i=x(e.baseSha),o=x(e.headSha),r=x(e.bundleDigest),a=x(e.graphRevision),s=x(e.sourceEvidenceDigest),u=At(e.qaReceiptRef),g=He(e.reviewedAt),d=At(e.receiptRef);if(!(!t||!n||!i||!o||!r||r.length!==64||!a||a.length!==64||!s||s.length!==64||!u||!g||!d))return{schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:t,epicId:n,baseSha:i,headSha:o,bundleDigest:r,graphRevision:a,sourceEvidenceDigest:s,qaReceiptRef:u,verdict:e.verdict,reviewedAt:g,receiptRef:d}}function Si(e,t){return["storyId","epicId","baseSha","headSha","bundleDigest","graphRevision"].every(n=>e[n]===t[n])}function $n(e){if(!f(e))return;const t=e.schemaVersion===1&&e.capturedFromCurrentCheckout===!0&&e.capturedFrom===void 0,n=e.schemaVersion===2&&e.capturedFromCurrentCheckout===void 0&&(e.capturedFrom==="current-checkout"||e.capturedFrom==="branch-ref");if(!t&&!n)return;const i=_e(e.originBranch),o=x(e.originHeadSha),r=_e(e.executionBranch),a=He(e.capturedAt);if(!(!i||!o||o.length<40||!r||!a||i===r))return t?{schemaVersion:1,originBranch:i,originHeadSha:o,executionBranch:r,capturedFromCurrentCheckout:!0,capturedAt:a}:{schemaVersion:2,originBranch:i,originHeadSha:o,executionBranch:r,capturedFrom:e.capturedFrom,capturedAt:a}}function vi(e){if(!f(e)||e.schemaVersion!==1||e.verdict!=="passed")return;const t=x(e.executionHeadSha),n=x(e.graphRevision),i=He(e.checkedAt),o=At(e.receiptRef),r=ge(e.gateIds).map(oe).filter(d=>!!d).slice(0,128),a=e.evidenceVersion==="p205-execution-v2"&&e.producer==="local-yolo-tdd"&&e.contract==="P205-CI-02"&&e.command==="node scripts/test-root.mjs --gate complete",s=e.evidenceVersion===void 0&&e.producer===void 0&&e.contract===void 0&&e.command===void 0&&e.manifestDigest===void 0&&e.resultDigest===void 0,u=a?x(e.manifestDigest):void 0,g=a?x(e.resultDigest):void 0;if(!(!t||t.length<40||!n||n.length!==64||!i||!o||r.length===0||!Array.isArray(e.gateIds)||r.length!==e.gateIds.length||e.gateIds.length>128||!s&&!a||a&&(!u||u.length!==64||!g||g.length!==64)))return{schemaVersion:1,...a?{evidenceVersion:"p205-execution-v2",producer:"local-yolo-tdd",contract:"P205-CI-02",command:"node scripts/test-root.mjs --gate complete",manifestDigest:u,resultDigest:g}:{},verdict:"passed",executionHeadSha:t,graphRevision:n,checkedAt:i,receiptRef:o,gateIds:r}}const Fs=16384;function zs(e){if(!f(e))return;const t=(i,o)=>i===null||typeof i=="boolean"?!0:typeof i=="number"?Number.isFinite(i):typeof i=="string"?i.length<=512&&!i.startsWith("/")&&!/^[A-Za-z]:[\\/]/.test(i)&&!i.includes("\\")&&!/:\/\//.test(i)&&!/[\u0000-\u001f]/.test(i):o>=4?!1:Array.isArray(i)?i.length<=256&&i.every(r=>t(r,o+1)):f(i)?Object.keys(i).length<=64&&Object.entries(i).every(([r,a])=>/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(r)&&t(a,o+1)):!1;if(!t(e,0))return;const n=JSON.stringify(e);if(!(Buffer.byteLength(n,"utf8")>Fs))return JSON.parse(n)}function Ci(e){if(!f(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:oe(e.epicId),executionBranch:_e(e.executionBranch),originBranch:_e(e.originBranch),graphRevision:x(e.graphRevision),originHeadSha:x(e.originHeadSha),lastAcceptedCheckpointHeadSha:x(e.lastAcceptedCheckpointHeadSha),executionHeadSha:x(e.executionHeadSha),acceptedCheckpointIds:ge(e.acceptedCheckpointIds),acceptedCheckpointHeads:ge(e.acceptedCheckpointHeads),reconciliationCommitShas:ge(e.reconciliationCommitShas),commitRangeDigest:x(e.commitRangeDigest),changedPaths:ge(e.changedPaths),changedPathsDigest:x(e.changedPathsDigest),allowedWriteSet:ge(e.allowedWriteSet),allowedWriteSetDigest:x(e.allowedWriteSetDigest),aggregateReceiptRef:At(e.aggregateReceiptRef),aggregateManifestDigest:x(e.aggregateManifestDigest),aggregateResultDigest:x(e.aggregateResultDigest),producedAt:He(e.producedAt),revalidatedAt:He(e.revalidatedAt),publicSafe:!0},n=["originSyncHeadSha","originSyncCommitShas","originSyncPaths","originSyncPathsDigest","originSyncResolvedPaths","originSyncResolvedPathsDigest"],i=n.filter(s=>e[s]!==void 0).length;if(i!==0&&i!==n.length)return;const o=i===0?void 0:{originSyncHeadSha:x(e.originSyncHeadSha),originSyncCommitShas:ge(e.originSyncCommitShas),originSyncPaths:ge(e.originSyncPaths),originSyncPathsDigest:x(e.originSyncPathsDigest),originSyncResolvedPaths:ge(e.originSyncResolvedPaths),originSyncResolvedPathsDigest:x(e.originSyncResolvedPathsDigest)};if(o&&(!o.originSyncHeadSha||o.originSyncHeadSha.length<40||o.originSyncCommitShas.length===0||o.originSyncCommitShas.length>256||o.originSyncCommitShas.some(s=>!/^[a-f0-9]{40,64}$/i.test(s))||o.originSyncPaths.length>2048||o.originSyncResolvedPaths.length>64||o.originSyncPathsDigest!==zr(o.originSyncPaths)||o.originSyncResolvedPathsDigest!==zr(o.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(s=>!/^[a-f0-9]{40,64}$/i.test(s))||t.reconciliationCommitShas.length>2048||t.reconciliationCommitShas.some(s=>!/^[a-f0-9]{40,64}$/i.test(s))||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!==xc(t.lastAcceptedCheckpointHeadSha,t.executionHeadSha,t.reconciliationCommitShas)||t.changedPathsDigest!==zr(t.changedPaths)||t.allowedWriteSetDigest!==zr(t.allowedWriteSet))return;const r={...t,...o??{}},a=x(e.inputDigest);if(!(!a||a.length!==64||a!==bc(r)))return{...r,inputDigest:a}}function Un(e){if(!f(e)||e.schemaVersion!==1)return;const t=Qr(e,["schemaVersion","kind","storyId","epicId","baseSha","headSha","originalBaseSha","originalHeadSha","gitPullRequest","preservesLaterCommits","historyRewrite","recordedAt"])??{},n=ge(e.receiptRefs).map(At).filter(o=>!!o).slice(0,256),i=ge(e.revertCommits).map(ue).filter(o=>!!o).slice(0,256);return{...t,...n.length?{receiptRefs:n}:{},...i.length?{revertCommits:i}:{}}}function Ys(e){if(!(!f(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 _i(e){if(!f(e)||e.schemaVersion!==1||e.publicSafe!==!0)return;const t=oe(e.epicId),n=_e(e.executionBranch),i=_e(e.originBranch),o=x(e.baseSha),r=x(e.executionHeadSha),a=e.mergeSha===void 0?void 0:x(e.mergeSha),s=e.pushedSha===void 0?void 0:x(e.pushedSha),u=oe(e.idempotencyKey),g=He(e.attemptStartedAt),d=e.completedAt===void 0?void 0:He(e.completedAt),h=ge(e.localGateReceiptRefs).map(At).filter(w=>!!w).slice(0,256),l=ge(e.reasonCodes).map(oe).filter(w=>!!w).slice(0,64),E=Ks(e.candidateQa),_=qs(e.providerGuard);if(!(!t||!n||!i||!o||!r||!u||!g||h.length===0||l.length===0||!["direct","single_pr"].includes(String(e.strategy))||!["prepared","merged","pushed","denied_external_gate","blocked_local_or_repo"].includes(String(e.physicalStatus))||typeof e.retryEligible!="boolean"||e.providerGuard!==void 0&&!_||_&&(e.strategy!=="single_pr"||e.physicalStatus!=="pushed"||_.prHeadSha!==a||_.originHeadSha!==o)))return{schemaVersion:1,epicId:t,executionBranch:n,originBranch:i,baseSha:o,executionHeadSha:r,...a?{mergeSha:a}:{},...s?{pushedSha:s}:{},strategy:e.strategy,...jt(e.prNumber)?{prNumber:jt(e.prNumber)}:{},physicalStatus:e.physicalStatus,localGateReceiptRefs:h,idempotencyKey:u,attemptStartedAt:g,...E?{candidateQa:E}:{},..._?{providerGuard:_}:{},...d?{completedAt:d}:{},retryEligible:e.retryEligible,reasonCodes:l,publicSafe:!0}}function qs(e){if(!f(e)||e.schemaVersion!==1||e.provider!=="github"||e.publicSafe!==!0)return;const t=String(e.mode),n=String(e.source),i=t==="recovered_exact_tree"?n==="physical_recovery":t==="strict_up_to_date_expected_head"&&["branch_protection","ruleset","branch_protection_and_ruleset"].includes(n),o=x(e.prHeadSha),r=x(e.originHeadSha),a=He(e.checkedAt);if(!(!i||!o||!r||!a))return{schemaVersion:1,provider:"github",mode:t,source:n,prHeadSha:o,originHeadSha:r,checkedAt:a,publicSafe:!0}}function Ks(e){if(!f(e)||e.schemaVersion!==1||e.kind!=="epic_merge_candidate_qa"||e.contract!=="P205-CI-02"||e.command!==Sr)return;const n=Object.fromEntries(["originHeadSha","executionHeadSha","mergeSha","treeSha","graphRevision","manifestDigest","resultDigest"].map(a=>[a,x(e[a])])),i=He(e.checkedAt),o=At(e.receiptRef),r=ge(e.gateIds).filter(a=>/^[a-z0-9-]+$/.test(a)).slice(0,128);if(!(Object.values(n).some(a=>!a)||!i||!o||r.length===0))return{schemaVersion:1,kind:e.kind,contract:e.contract,command:e.command,...n,checkedAt:i,receiptRef:o,gateIds:r}}function Js(e){if(!f(e))return;const t={...ue(e.active_epic_id??e.activeEpicId)?{active_epic_id:ue(e.active_epic_id??e.activeEpicId)}:{},...ue(e.active_story_id??e.activeStoryId)?{active_story_id:ue(e.active_story_id??e.activeStoryId)}:{},...ue(e.active_step_id??e.activeStepId)?{active_step_id:ue(e.active_step_id??e.activeStepId)}:{},...ue(e.session_id??e.sessionId)?{session_id:ue(e.session_id??e.sessionId)}:{},...ue(e.started_at??e.startedAt)?{started_at:ue(e.started_at??e.startedAt)}:{}};return Object.keys(t).length>0?t:void 0}function Qs(e){const t=Qr(e.completionEvidence??e.completion_evidence,["prNumber","pr_number","prState","pr_state","pullRequestState","merged","mergedAt","issueNumber","issue_number","issueState","issue_state","closedAt"]),n=Qr(e.issueCloseAudit??e.issue_close_audit,["schema_version","event","storyId","epicId","issueNumber","closedAt","publicSafe","rawLogStorage"]),i=Qr(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}:{},...ue(e.physicalMergeStatus)?{physicalMergeStatus:ue(e.physicalMergeStatus)}:{},...ue(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)?{pr_state:ue(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)}:{},...ue(e.issue_state??e.issueState??e.workflow_issue_state)?{issue_state:ue(e.issue_state??e.issueState??e.workflow_issue_state)}:{},...jt(e.issue_number??e.issueNumber)?{issue_number:jt(e.issue_number??e.issueNumber)}:{},...t?{completionEvidence:t}:{},...n?{issueCloseAudit:n}:{},...i?{scopedCiEvidence:i}:{}}}class ut extends Error{reasonCode;constructor(t){super(t),this.name="StateSnapshotIntegrityError",this.reasonCode=t}}const Xs=new Set(["yolo","yoloop","finalize-epic","audit"]),Zs=8;function ed(e,t){try{const n=In(String(Ae("git",["rev-parse","--absolute-git-dir"],{cwd:e,stdio:["ignore","pipe","ignore"],timeout:1e4,encoding:"utf8"})).trim()),i=In(String(Ae("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd:e,stdio:["ignore","pipe","ignore"],timeout:1e4,encoding:"utf8"})).trim());if(n!==i&&(!t||String(Ae("git",["symbolic-ref","--short","HEAD"],{cwd:e,stdio:["ignore","pipe","ignore"],timeout:1e4,encoding:"utf8"})).trim()!==`epic/${t}`))return;const o=q(e,".neocortex","state.json");if(!Ct(o))return;const r=Wc({projectRoot:e,bytes:$e(o)});r.ok||process.stderr.write(`[Neocortex] governance runtime store mirror skipped: ${r.reasonCode}
7
+ `)}catch{}}}function cl(){Un=!1}function mo(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Us(e){return e==="active"||e==="archived"||e==="rolled-back"||e==="synthetic"||e==="orphan"?e:void 0}const Hs=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"]),Gs=/(?:[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,Ws=/^[a-z0-9][a-z0-9-]{0,127}$/;function Fs(e,t){if(!f(e)||e.schemaVersion!==1||e.epicId!==t||!/^P\d+$/.test(t))return{};try{const n=JSON.stringify(e),o=Buffer.byteLength(n);if(o>Ai)return{diagnostic:Object.freeze({schemaVersion:"CreateEpicPlanningProjectionDiagnostic/1.1",outcome:"omitted",reasonCode:"budget-omitted",byteLength:o,maxBytes:Ai,publicSafe:!0})};if(Gs.test(n))return{};const i=(a,s)=>{if(Object.keys(a).some(u=>!s.includes(u)))throw new Error("planning-unknown-field")};if(i(e,["schemaVersion","epicId","intake","intakeRevision","diagnosisReceipt","researchReceipt","degradeAuthorization"]),!f(e.intake))return{};if(Object.keys(e.intake).some(a=>!Hs.has(a)))return{};for(const[a,s]of Object.entries(e.intake))if(["examples","contracts"].includes(a)){const u=a==="examples"?["id","title","actor","given","when","then","source","coveredRequirement","expectedValidation"]:["id","kind","description","path"];if(!Array.isArray(s)||s.length>16)return{};for(const g of s){if(!f(g))return{};if(i(g,u),Object.values(g).some(d=>typeof d!="string"||d.length>256))return{}}}else if(Array.isArray(s)){if(s.length>32||s.some(u=>typeof u!="string"||u.length>256))return{}}else if(typeof s=="string"){if(s.length>(a==="rawIntent"?ba:512))return{}}else if(typeof s!="boolean"||!["uiScope","remediationStory"].includes(a))return{};const r=["schemaVersion","kind","epicId","intakeRevision","artifactSummary","artifactDigest","predecessorReceiptId","accepted","receiptId"];for(const a of[e.diagnosisReceipt,e.researchReceipt])if(a!==void 0){if(!f(a))return{};if(i(a,r),Object.values(a).some(s=>typeof s=="string"&&s.length>1024))return{}}if(e.degradeAuthorization!==void 0){if(!f(e.degradeAuthorization))return{};i(e.degradeAuthorization,["approved","intakeRevision","reasonCodes","assumptionCodes"]);for(const a of["reasonCodes","assumptionCodes"]){const s=e.degradeAuthorization[a];if(!Array.isArray(s)||s.length>32||s.some(u=>typeof u!="string"||!Ws.test(u)))return{}}}return{checkpoint:JSON.parse(n)}}catch{return{}}}function yo(e){return e==="create-epic"||e==="discovered"?e:void 0}function ge(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Io(e){if(!f(e))return;const t=/^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/;if(Object.keys(e).some(s=>!["epicId","storyId","integrationReceiptId","mergedCommit","digest"].includes(s)))return;const o=s=>typeof s=="string"&&t.test(s)&&!s.includes("..");if(!o(e.epicId)||e.storyId!==void 0&&!o(e.storyId))return;const i=e.integrationReceiptId,r=e.mergedCommit;if(i===void 0&&r===void 0||i!==void 0&&(typeof i!="string"||!/^[A-Za-z0-9][A-Za-z0-9_-]{7,95}$/.test(i))||r!==void 0&&(typeof r!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(r)))return;const a=e.digest;if(!(a!==void 0&&(typeof a!="string"||!/^[a-f0-9]{64}$/.test(a))))return{epicId:e.epicId,...e.storyId!==void 0?{storyId:e.storyId}:{},...i!==void 0?{integrationReceiptId:i}:{},...r!==void 0?{mergedCommit:r}:{},...a!==void 0?{digest:a}:{}}}function zs(e){const t={};let n=!1;for(const o of["contracts","contract_refs","shared_surfaces","adr_refs","nfr_refs","acceptance_depends_on"]){if(e[o]===void 0)continue;const i=e[o];if(!Array.isArray(i)||i.length>128||i.some(r=>Fr(r)===void 0)){n=!0;continue}t[o]=i.map(r=>Fr(r))}if(e.planning!==void 0)try{if(!f(e.planning))throw new Error("planning-shape");const o=e.planning;for(const a of["claims","semanticArtifacts"]){if(o[a]===void 0)continue;const s=o[a];if(!Array.isArray(s)||s.length>128||s.some(u=>!f(u)||Fr(u.ref)===void 0))throw new Error("planning-refs")}if(o.attempts!==void 0&&(!Array.isArray(o.attempts)||o.attempts.length>32))throw new Error("planning-attempts");for(const a of o.attempts??[]){if(!f(a)||!Array.isArray(a.reasonCodes)||a.reasonCodes.length>32||a.reasonCodes.some(s=>typeof s!="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(s)))throw new Error("planning-attempt-reasons");if(a.discoveredClaims!==void 0&&(!Array.isArray(a.discoveredClaims)||a.discoveredClaims.length>128||a.discoveredClaims.some(s=>!f(s)||Fr(s.ref)===void 0)))throw new Error("planning-attempt-claims")}const{graphRevision:i,...r}=kc(o);t.planning=r}catch{n=!0}return n&&(t.planning={schemaVersion:1,dependencyBasis:"unknown",claims:[],semanticArtifacts:[]}),t}function f(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function jt(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function ue(e){if(typeof e!="string")return;const t=e.trim();if(t)return t.replace(/[^a-z0-9_.:-]+/gi,"_").slice(0,120)}function oe(e){if(typeof e!="string")return;const t=e.trim(),n=ue(e);return n===t?n:void 0}function _e(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240)&&/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(t)&&!(t.includes("..")||t.includes("//")||t.includes("@{")||t.endsWith("/")||t.endsWith("."))&&!t.split("/").some(n=>!n||n.startsWith(".")||n.endsWith(".lock")))return t}function x(e){return typeof e=="string"&&/^[0-9a-f]{7,64}$/i.test(e)?e:void 0}function Ge(e){if(!(typeof e!="string"||e.length>64)&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/.test(e))return Number.isFinite(Date.parse(e))?e:void 0}function At(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240||t.includes("..")))return/^[A-Za-z0-9._:/#\-[\]]+$/.test(t)?t:void 0}function Jr(e){if(!f(e))return;const t=l=>typeof l=="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,95}$/.test(l),n=l=>typeof l=="string"&&/^[a-f0-9]{64}$/.test(l),o=(l,E)=>Array.isArray(l)&&l.length<=E&&l.every(t)&&new Set(l).size===l.length?l:void 0,i=(l,E)=>{if(!(!f(l)||l.schemaVersion!==2||!t(l.requestId)||!t(l.stageCommand)||!n(l.requestHash)||!n(l.inputHash)||!n(l.stateHash)||!n(l.nonce)||!n(l.stageRevision)||!n(l.stageHash)||!n(l.catalogHash)||l.targetEpicId!==void 0&&!t(l.targetEpicId)||E&&(!n(l.outputHash)||!n(l.artifactHash))))return{schemaVersion:2,...l.targetEpicId?{targetEpicId:l.targetEpicId}:{},requestId:l.requestId,requestHash:l.requestHash,inputHash:l.inputHash,stateHash:l.stateHash,nonce:l.nonce,stageCommand:l.stageCommand,stageRevision:l.stageRevision,stageHash:l.stageHash,catalogHash:l.catalogHash,...E?{outputHash:l.outputHash,artifactHash:l.artifactHash}:{}}},r=(l,E)=>{if(!(!f(l)||l.schemaVersion!=="1.1"||l.kind!==E||!n(l.receiptId)||!n(l.graphHash)||!n(l.evidenceHash)||!t(l.elementId)||!t(l.caseId)||!t(l.category)))return{schemaVersion:"1.1",kind:E,receiptId:l.receiptId,graphHash:l.graphHash,elementId:l.elementId,caseId:l.caseId,category:l.category,evidenceHash:l.evidenceHash}},a=(l,E)=>{if(!f(l)||l.kind!==E||!n(l.receiptId)||!o(l.evidenceIds,24)||E==="architecture-stage-completion"&&!["succeeded","failed"].includes(String(l.status))||E==="architecture-stage-validation"&&!["passed","failed","pending"].includes(String(l.status)))return;const v=i(l,!0);if(!v)return;const w=E==="architecture-stage-validation"?r(l.isolated,"isolated"):void 0,S=E==="architecture-stage-validation"?r(l.regression,"regression"):void 0;if(!(E==="architecture-stage-validation"&&(!w||!S)))return{...v,kind:E,receiptId:l.receiptId,status:l.status,evidenceIds:l.evidenceIds,...w&&S?{isolated:w,regression:S}:{}}},s={};e.schemaVersion===1&&(s.schemaVersion=1),e.owner==="root"&&(s.owner="root"),t(e.currentStageCommand)&&(s.currentStageCommand=e.currentStageCommand),["ask-user","delegate","resume","advance","blocked","complete"].includes(String(e.continuationState))&&(s.continuationState=e.continuationState);const u=o(e.questionIds,16);if(u&&(s.questionIds=u),(e.childStatus==="succeeded"||e.childStatus==="failed")&&(s.childStatus=e.childStatus),(e.evidencePolicy==="legacy-compatible"||e.evidencePolicy==="v2-required")&&(s.evidencePolicy=e.evidencePolicy),t(e.targetEpicId)&&(s.targetEpicId=e.targetEpicId),n(e.graphRevision)&&(s.graphRevision=e.graphRevision),e.graphSource==="committed-epic-v1"&&(s.graphSource=e.graphSource),e.nonUiScopeReceipt!==void 0){const l=Ii(e.nonUiScopeReceipt);if(!l||l.targetEpicId!==e.targetEpicId||l.graphRevision!==e.graphRevision||!f(e.accounting)||l.accountingId!==e.accounting.accountingId||!f(e.evidenceExpectation)||l.rootInputSha256!==e.evidenceExpectation.inputHash)throw new Error("architecture-non-ui-scope-invalid");s.nonUiScopeReceipt=l}f(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&&n(e.pactAnswerReceipt.stateSha256)&&n(e.pactAnswerReceipt.answersSha256)&&C(e.pactAnswerReceipt.questionIds,["PACT-Q1-CONSUMER","PACT-Q2-PROVIDER","PACT-Q3-BROKER","PACT-Q4-MATCHERS","PACT-Q5-VERIFY"])&&e.pactAnswerReceipt.publicSafe===!0&&(s.pactAnswerReceipt=e.pactAnswerReceipt);const g=i(e.evidenceExpectation,!1);g&&(s.evidenceExpectation=g);const d=a(e.completionEvidence,"architecture-stage-completion"),h=a(e.validationEvidence,"architecture-stage-validation");if(d&&(s.completionEvidence=d),h&&(s.validationEvidence=h),f(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&&n(e.reviewDecision.graphRevision)&&n(e.reviewDecision.artifactHash)&&n(e.reviewDecision.completionReceiptId)&&n(e.reviewDecision.validationReceiptId)&&["approved","changes-requested"].includes(String(e.reviewDecision.decision))&&e.reviewDecision.publicSafe===!0){const l=o(e.reviewDecision.evidenceIds,24);l&&l.length>0&&(s.reviewDecision={...e.reviewDecision,evidenceIds:l})}if(hr(e.terminalMemoryCheckpoint,e))s.terminalMemoryCheckpoint=e.terminalMemoryCheckpoint;else if(f(e.terminalMemoryCheckpoint)&&e.terminalMemoryCheckpoint.schemaVersion===void 0&&["passed","failed","pending"].includes(String(e.terminalMemoryCheckpoint.status))){const l=o(e.terminalMemoryCheckpoint.evidenceIds,24);l&&(s.terminalMemoryCheckpoint={status:e.terminalMemoryCheckpoint.status,evidenceIds:l})}if(Array.isArray(e.acceptedStages)&&e.acceptedStages.length<=15){const l=e.acceptedStages.map(E=>{if(!f(E)||!t(E.targetEpicId)||!t(E.stageCommand))return;const v=a(E.completionEvidence,"architecture-stage-completion"),w=a(E.validationEvidence,"architecture-stage-validation");return v&&w?{targetEpicId:E.targetEpicId,stageCommand:E.stageCommand,completionEvidence:v,validationEvidence:w}:void 0});l.every(E=>E!==void 0)&&(s.acceptedStages=l)}if(f(e.accounting)&&e.accounting.schemaVersion===1&&t(e.accounting.contractVersion)&&t(e.accounting.accountingId)&&typeof e.accounting.charged=="boolean"&&Number.isInteger(e.accounting.chargedQuotaUnits)&&typeof e.accounting.chargedQuotaUnits=="number"&&e.accounting.chargedQuotaUnits>=0&&e.accounting.chargedQuotaUnits<=13){const l=o(e.accounting.receiptIds,32);l&&(s.accounting={schemaVersion:1,contractVersion:e.accounting.contractVersion,accountingId:e.accounting.accountingId,charged:e.accounting.charged,chargedQuotaUnits:e.accounting.chargedQuotaUnits,receiptIds:l,...["in-progress","aborted","timed-out","failed","complete"].includes(String(e.accounting.lastOutcome))?{lastOutcome:e.accounting.lastOutcome}:{}})}return JSON.stringify(s).length<=96e3?s:void 0}function Ys(e){const t=f(e.metadata.archPlan)?e.metadata.archPlan.execution:void 0,n=f(t)?t.checkpoint:void 0,o=f(t)?t:void 0,i=f(n)?n:void 0,r=e.requestExecution,a=Array.isArray(i?.acceptedStages)?i.acceptedStages:[],s=r.currentStageCommand==="arch-prd"&&r.continuationState==="delegate"&&r.completionEvidence===void 0&&r.validationEvidence===void 0&&i?.currentStageCommand==="arch-prd"&&i.continuationState==="delegate"&&a.length===0&&o?.nextAction==="delegate",u=r.currentStageCommand==="arch-prd"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&i?.currentStageCommand==="arch-architecture"&&i.continuationState==="advance"&&a.length===1&&f(a[0])&&a[0].stageCommand==="arch-prd"&&C(a[0].completionEvidence,r.completionEvidence)&&C(a[0].validationEvidence,r.validationEvidence)&&o?.nextAction==="resume",g=r.currentStageCommand==="arch-architecture"&&r.continuationState==="advance"&&i?.currentStageCommand==="arch-architecture"&&i.continuationState==="delegate"&&a.length===1&&C(a,r.acceptedStages)&&o?.nextAction==="delegate",d=r.currentStageCommand==="arch-architecture"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&i?.currentStageCommand==="arch-fitness-functions"&&i.continuationState==="advance"&&a.length===2&&f(a[0])&&f(a[1])&&a[0].stageCommand==="arch-prd"&&a[1].stageCommand==="arch-architecture"&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===1&&C(a[0],r.acceptedStages[0])&&C(a[1].completionEvidence,r.completionEvidence)&&C(a[1].validationEvidence,r.validationEvidence)&&o?.nextAction==="resume",h=r.currentStageCommand==="arch-fitness-functions"&&r.continuationState==="advance"&&i?.currentStageCommand==="arch-fitness-functions"&&i.continuationState==="delegate"&&a.length===2&&f(a[0])&&f(a[1])&&a[0].stageCommand==="arch-prd"&&a[1].stageCommand==="arch-architecture"&&C(a,r.acceptedStages)&&o?.nextAction==="delegate",l=r.currentStageCommand==="arch-fitness-functions"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&i?.currentStageCommand==="arch-api-contracts"&&i.continuationState==="advance"&&a.length===3&&f(a[0])&&f(a[1])&&f(a[2])&&a[0].stageCommand==="arch-prd"&&a[1].stageCommand==="arch-architecture"&&a[2].stageCommand==="arch-fitness-functions"&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===2&&C(a.slice(0,2),r.acceptedStages)&&C(a[2].completionEvidence,r.completionEvidence)&&C(a[2].validationEvidence,r.validationEvidence)&&o?.nextAction==="resume",E=r.currentStageCommand==="arch-api-contracts"&&r.continuationState==="advance"&&i?.currentStageCommand==="arch-api-contracts"&&i.continuationState==="delegate"&&a.length===3&&f(a[0])&&f(a[1])&&f(a[2])&&a[0].stageCommand==="arch-prd"&&a[1].stageCommand==="arch-architecture"&&a[2].stageCommand==="arch-fitness-functions"&&C(a,r.acceptedStages)&&o?.nextAction==="delegate",v=["PACT-Q1-CONSUMER","PACT-Q2-PROVIDER","PACT-Q3-BROKER","PACT-Q4-MATCHERS","PACT-Q5-VERIFY"],w=r.currentStageCommand==="arch-api-contracts"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&i?.currentStageCommand==="generate-pacts"&&i.continuationState==="ask-user"&&a.length===4&&f(a[3])&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===3&&C(a.slice(0,3),r.acceptedStages)&&a[3].stageCommand==="arch-api-contracts"&&C(a[3].completionEvidence,r.completionEvidence)&&C(a[3].validationEvidence,r.validationEvidence)&&C(i.questionIds,v)&&C(o?.questionIds,v)&&o?.nextAction==="ask-user",S=r.currentStageCommand==="generate-pacts"&&r.continuationState==="ask-user"&&i?.currentStageCommand==="generate-pacts"&&i.continuationState==="delegate"&&a.length===4&&C(a,r.acceptedStages)&&C(r.questionIds,v)&&C(i.questionIds,[])&&C(i.pactAnswerReceipt,e.answerReceipt)&&C(o?.pactAnswerReceipt,e.answerReceipt)&&e.answerReceipt?.stateSha256===e.sourceStateSha256&&o?.nextAction==="resume",y=r.currentStageCommand==="generate-pacts"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&C(r.pactAnswerReceipt,e.pactRecordedReceipt)&&i?.currentStageCommand==="arch-api-integrations"&&i.continuationState==="advance"&&a.length===5&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===4&&C(a.slice(0,4),r.acceptedStages)&&a.map(k=>f(k)?k.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts"&&f(a[4])&&C(a[4].completionEvidence,r.completionEvidence)&&C(a[4].validationEvidence,r.validationEvidence)&&o?.nextAction==="resume",N=r.currentStageCommand==="arch-api-integrations"&&r.continuationState==="advance"&&i?.currentStageCommand==="arch-api-integrations"&&i.continuationState==="delegate"&&a.length===5&&C(a,r.acceptedStages)&&o?.nextAction==="delegate",$=r.currentStageCommand==="arch-api-integrations"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&i?.currentStageCommand==="arch-database"&&i.continuationState==="advance"&&a.length===6&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===5&&C(a.slice(0,5),r.acceptedStages)&&a.map(k=>f(k)?k.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations"&&f(a[5])&&C(a[5].completionEvidence,r.completionEvidence)&&C(a[5].validationEvidence,r.validationEvidence)&&o?.nextAction==="resume",b=r.currentStageCommand==="arch-database"&&r.continuationState==="advance"&&i?.currentStageCommand==="arch-database"&&i.continuationState==="delegate"&&a.length===6&&C(a,r.acceptedStages)&&o?.nextAction==="delegate",_=r.currentStageCommand==="arch-database"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&i?.currentStageCommand==="arch-security"&&i.continuationState==="advance"&&a.length===7&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===6&&C(a.slice(0,6),r.acceptedStages)&&a.map(k=>f(k)?k.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database"&&f(a[6])&&C(a[6].completionEvidence,r.completionEvidence)&&C(a[6].validationEvidence,r.validationEvidence)&&o?.nextAction==="resume",A=r.currentStageCommand==="arch-security"&&r.continuationState==="advance"&&i?.currentStageCommand==="arch-security"&&i.continuationState==="delegate"&&a.length===7&&C(a,r.acceptedStages)&&o?.nextAction==="delegate",K=r.currentStageCommand==="arch-security"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&i?.currentStageCommand==="arch-design-system"&&i.continuationState==="advance"&&a.length===8&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===7&&C(a.slice(0,7),r.acceptedStages)&&a.map(k=>f(k)?k.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security"&&f(a[7])&&C(a[7].completionEvidence,r.completionEvidence)&&C(a[7].validationEvidence,r.validationEvidence)&&o?.nextAction==="resume",re=r.currentStageCommand==="arch-design-system"&&r.continuationState==="advance"&&i?.currentStageCommand==="arch-design-system"&&i.continuationState==="delegate"&&a.length===8&&C(a,r.acceptedStages)&&o?.nextAction==="delegate",Z=r.currentStageCommand==="arch-design-system"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&i?.currentStageCommand==="arch-ux-design"&&i.continuationState==="advance"&&a.length===9&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===8&&C(a.slice(0,8),r.acceptedStages)&&a.map(k=>f(k)?k.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system"&&f(a[8])&&C(a[8].completionEvidence,r.completionEvidence)&&C(a[8].validationEvidence,r.validationEvidence)&&o?.nextAction==="resume",j=r.currentStageCommand==="arch-ux-design"&&r.continuationState==="advance"&&i?.currentStageCommand==="arch-ux-design"&&i.continuationState==="delegate"&&a.length===9&&C(a,r.acceptedStages)&&o?.nextAction==="blocked",ae=r.currentStageCommand==="arch-ux-design"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&i?.currentStageCommand==="arch-performance"&&i.continuationState==="advance"&&a.length===10&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===9&&C(a.slice(0,9),r.acceptedStages)&&a.map(k=>f(k)?k.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design"&&f(a[9])&&C(a[9].completionEvidence,r.completionEvidence)&&C(a[9].validationEvidence,r.validationEvidence)&&o?.nextAction==="resume",ve=r.currentStageCommand==="arch-performance"&&r.continuationState==="advance"&&i?.currentStageCommand==="arch-performance"&&i.continuationState==="delegate"&&a.length===10&&C(a,r.acceptedStages)&&o?.nextAction==="delegate",be=r.currentStageCommand==="arch-performance"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&i?.currentStageCommand==="arch-testing"&&i.continuationState==="advance"&&a.length===11&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===10&&C(a.slice(0,10),r.acceptedStages)&&a.map(k=>f(k)?k.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance"&&f(a[10])&&C(a[10].completionEvidence,r.completionEvidence)&&C(a[10].validationEvidence,r.validationEvidence)&&o?.nextAction==="resume",T=r.currentStageCommand==="arch-testing"&&r.continuationState==="advance"&&i?.currentStageCommand==="arch-testing"&&i.continuationState==="delegate"&&a.length===11&&C(a,r.acceptedStages)&&o?.nextAction==="delegate",ne=r.currentStageCommand==="arch-testing"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&i?.currentStageCommand==="arch-infrastructure"&&i.continuationState==="advance"&&a.length===12&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===11&&C(a.slice(0,11),r.acceptedStages)&&a.map(k=>f(k)?k.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance,arch-testing"&&f(a[11])&&C(a[11].completionEvidence,r.completionEvidence)&&C(a[11].validationEvidence,r.validationEvidence)&&o?.nextAction==="resume",Ce=r.currentStageCommand==="arch-infrastructure"&&r.continuationState==="advance"&&i?.currentStageCommand==="arch-infrastructure"&&i.continuationState==="delegate"&&a.length===12&&C(a,r.acceptedStages)&&o?.nextAction==="delegate",xe=r.currentStageCommand==="arch-infrastructure"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&i?.currentStageCommand==="arch-review"&&i.continuationState==="advance"&&a.length===13&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===12&&C(a.slice(0,12),r.acceptedStages)&&a.map(k=>f(k)?k.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance,arch-testing,arch-infrastructure"&&f(a[12])&&C(a[12].completionEvidence,r.completionEvidence)&&C(a[12].validationEvidence,r.validationEvidence)&&o?.nextAction==="resume",ce=r.currentStageCommand==="arch-review"&&r.continuationState==="advance"&&i?.currentStageCommand==="arch-review"&&i.continuationState==="delegate"&&a.length===13&&C(a,r.acceptedStages)&&o?.nextAction==="delegate",V=r.currentStageCommand==="arch-review"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&r.reviewDecision===void 0&&i?.currentStageCommand==="arch-review"&&i.continuationState==="ask-user"&&a.length===13&&C(a,r.acceptedStages)&&C(i.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&C(i.completionEvidence,r.completionEvidence)&&C(i.validationEvidence,r.validationEvidence)&&o?.nextAction==="ask-user",Ke=r.currentStageCommand==="arch-review"&&r.continuationState==="ask-user"&&r.childStatus==="succeeded"&&f(r.reviewDecision)&&r.reviewDecision.decision==="approved"&&C(r.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&i?.currentStageCommand==="update-memory"&&i.continuationState==="advance"&&a.length===14&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===13&&C(a.slice(0,13),r.acceptedStages)&&f(a[13])&&a[13].stageCommand==="arch-review"&&C(a[13].completionEvidence,r.completionEvidence)&&C(a[13].validationEvidence,r.validationEvidence)&&C(i.reviewDecision,r.reviewDecision)&&o?.nextAction==="resume",me=r.currentStageCommand==="update-memory"&&r.continuationState==="advance"&&f(r.reviewDecision)&&r.reviewDecision.decision==="approved"&&i?.currentStageCommand==="update-memory"&&i.continuationState==="delegate"&&a.length===14&&C(a,r.acceptedStages)&&C(i.reviewDecision,r.reviewDecision)&&o?.nextAction==="delegate",B=r.currentStageCommand==="update-memory"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&i?.currentStageCommand==="update-memory"&&i.continuationState==="complete"&&a.length===15&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===14&&C(a.slice(0,14),r.acceptedStages)&&f(a[14])&&a[14].targetEpicId===r.targetEpicId&&a[14].stageCommand==="update-memory"&&C(a[14].completionEvidence,r.completionEvidence)&&C(a[14].validationEvidence,r.validationEvidence)&&C(i.reviewDecision,r.reviewDecision)&&C(i.completionEvidence,r.completionEvidence)&&C(i.validationEvidence,r.validationEvidence)&&hr(i.terminalMemoryCheckpoint,r)!==null&&C(i.terminalMemoryCheckpoint,r.terminalMemoryCheckpoint)&&o?.nextAction==="complete",ye=r.currentStageCommand==="update-memory"&&r.continuationState==="complete"&&r.childStatus==="succeeded"&&i?.currentStageCommand==="update-memory"&&i.continuationState==="complete"&&a.length===15&&C(a,r.acceptedStages)&&C(i.reviewDecision,r.reviewDecision)&&C(i.completionEvidence,r.completionEvidence)&&C(i.validationEvidence,r.validationEvidence)&&hr(i.terminalMemoryCheckpoint,r)&&C(i.terminalMemoryCheckpoint,r.terminalMemoryCheckpoint)&&o?.nextAction==="complete",gt=o?fa(r,o,hr(r.terminalMemoryCheckpoint,r)&&C(i?.terminalMemoryCheckpoint,r.terminalMemoryCheckpoint)):void 0;if(e.metadata.mode!=="arch-plan"||e.metadata.resolvedTrigger!=="arch-plan"||!f(t)||!f(n)||t.owner!=="root"||t.currentStageCommand!==n.currentStageCommand||t.continuationState!==n.continuationState||n.owner!=="root"||n.evidencePolicy!=="v2-required"||n.targetEpicId!==r.targetEpicId||n.graphRevision!==r.graphRevision||n.graphSource!==r.graphSource||!/^P[1-9][0-9]{0,11}$/.test(String(n.targetEpicId))||!/^[a-f0-9]{64}$/.test(String(n.graphRevision))||!Array.isArray(n.acceptedStages)||!(gt||s||u||g||d||h||l||E||w||S||y||N||$||b||_||A||K||re||Z||j||ae||ve||be||T||ne||Ce||xe||ce||V||Ke||me||B||ye)||!f(n.accounting)||n.accounting.charged!==!0||!C(Jr(n),n))throw new Error("architecture-root-checkpoint-invalid");const et=J(e.projectRoot,".neocortex"),fe=J(et,"state.json"),D=J(et,"state.json.architecture.lock"),H=Ht(D,"wx",384);let Ye;try{const k=nr(fe);if(!k.isFile()||k.isSymbolicLink())throw new Error("architecture-root-state-binding-invalid");const le=Ue(fe,"utf8");if(je("sha256").update(le).digest("hex")!==e.sourceStateSha256)throw new Error("architecture-root-state-conflict");const Je=JSON.parse(le),Tt=f(Je)&&f(Je.archPlan)?Je.archPlan:{};if(!f(Je)||!f(Je.epics)||!Object.hasOwn(Je.epics,n.targetEpicId)||(e.initialBinding?Tt.execution!==void 0||r.graphSource!=="committed-epic-v1":!C(Jr(Tt.execution),r))||f(Je.scope)&&Je.scope.kind==="projected")throw new Error("architecture-root-state-binding-invalid");if(r.graphSource==="committed-epic-v1"&&r.graphRevision!==fr(e.projectRoot,String(r.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");if(ye||gt==="complete-replay"){const Kt={...r,continuationState:"delegate",acceptedStages:r.acceptedStages.slice(0,yi(r))};if(!C(r.terminalMemoryCheckpoint,yn(e.projectRoot,Kt)))throw new Error("architecture-root-state-conflict");return}const Ie=Mr(),Ee=Ae("git",["rev-parse","--git-common-dir"],{cwd:e.projectRoot,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),se=Ea(Ee)?En(Ee):En(e.projectRoot,Ee);if(In(se)!==se)throw new Error("architecture-root-backup-dir-invalid");const Se=J(se,"neocortex-architecture");rr(Se,{recursive:!0,mode:448});const ot=nr(Se);if(!ot.isDirectory()||ot.isSymbolicLink()||ot.uid!==process.getuid?.()||(ot.mode&63)!==0)throw new Error("architecture-root-backup-dir-invalid");const dr=J(Se,`state-backup-${Ie}.json`),at=Ht(dr,"wx",384);try{Vr(at,le),mr(at)}finally{Gt(at)}const tt=Ht(Se,"r");try{mr(tt)}finally{Gt(tt)}const Ar={...Je,archPlan:{...Tt,execution:n}};Ye=J(et,`state.json.architecture-tmp-${Ie}`);const rt=Ht(Ye,"wx",384);try{Vr(rt,`${JSON.stringify(Ar,null,2)}
8
+ `),mr(rt)}finally{Gt(rt)}if((B||gt==="complete")&&!C(r.terminalMemoryCheckpoint,yn(e.projectRoot,r)))throw new Error("architecture-root-state-conflict");if(r.graphSource==="committed-epic-v1"&&r.graphRevision!==fr(e.projectRoot,String(r.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");Si(Ye,fe),Ye=void 0;const Qe=Ht(et,"r");try{mr(Qe)}finally{Gt(Qe)}}finally{if(Ye)try{gr(Ye)}catch{}Gt(H),gr(D)}}function Qr(e,t){if(!f(e))return;const n={};for(const o of t){const i=e[o];if(typeof i=="boolean")n[o]=i;else if(typeof i=="number"&&Number.isFinite(i))n[o]=i;else if(typeof i=="string"){const r=ue(i);r&&(n[o]=r)}}return Object.keys(n).length>0?n:void 0}function Xr(e){return e==="epic"||e==="story"?e:void 0}function Eo(e){if(!f(e)||e.schemaVersion!==1)return;const t=oe(e.ownerStoryId),n=oe(e.sessionId),o=oe(e.idempotencyKey),i=Ge(e.acquiredAt),r=Ge(e.expiresAt);if(!(!t||!n||!o||!i||!r||Date.parse(r)<=Date.parse(i)))return{schemaVersion:1,ownerStoryId:t,sessionId:n,idempotencyKey:o,acquiredAt:i,expiresAt:r}}function So(e){if(!f(e)||e.schemaVersion!==1)return;const t=oe(e.storyId),n=oe(e.epicId),o=_e(e.branch),i=x(e.baseSha),r=x(e.headSha),a=oe(e.idempotencyKey),s=Ge(e.recordedAt),u=ge(e.commits).map(x).filter(N=>!!N).slice(0,256),g=ge(e.receiptRefs).map(At).filter(N=>!!N).slice(0,256),d=e.dispatchId===void 0?void 0:oe(e.dispatchId),h=e.bundleId===void 0?void 0:oe(e.bundleId),l=e.bundleDigest===void 0?void 0:x(e.bundleDigest),E=e.graphRevision===void 0?void 0:x(e.graphRevision),v=e.claimRevision===void 0?void 0:oe(e.claimRevision),w=qs(e.qaReceipt),S=Ks(e.reviewReceipt),y=e.rootMemoryEffect===void 0?void 0:Qc(e.rootMemoryEffect)?e.rootMemoryEffect:void 0;if(!(!t||!n||!t.startsWith(`${n}.`)||!o||!i||!r||i===r||!a||!s||u.length===0||g.length===0||!Array.isArray(e.commits)||u.length!==e.commits.length||e.commits.length>256||!Array.isArray(e.receiptRefs)||g.length!==e.receiptRefs.length||e.receiptRefs.length>256||e.dispatchId!==void 0&&!d||e.bundleId!==void 0&&!h||e.bundleDigest!==void 0&&(!l||l.length!==64)||e.graphRevision!==void 0&&(!E||E.length!==64)||e.claimRevision!==void 0&&!v||e.rootMemoryEffect!==void 0&&(!y||y.storyId!==t||y.epicId!==n||y.executionBranch!==o||y.sourceHeadSha!==i||y.childClaimRevision!==v)||e.qaVerdict!=="passed"&&e.qaVerdict!=="blocked"||!["approved","changes-requested","pending"].includes(String(e.reviewVerdict))||!w||e.reviewVerdict!=="pending"&&!S||e.reviewVerdict==="pending"&&S||w.verdict!==e.qaVerdict||S&&S.verdict!==e.reviewVerdict||!_o(w,{storyId:t,epicId:n,baseSha:i,headSha:r,bundleDigest:l,graphRevision:E})||S&&(!_o(S,{storyId:t,epicId:n,baseSha:i,headSha:r,bundleDigest:l,graphRevision:E})||S.qaReceiptRef!==w?.receiptRef||S.receiptRef===w?.receiptRef)||!g.includes(String(w.receiptRef))||S&&(!g.includes(String(S.receiptRef))||Date.parse(String(S.reviewedAt))<Date.parse(String(w.checkedAt)))))return{schemaVersion:1,storyId:t,epicId:n,branch:o,baseSha:i,headSha:r,idempotencyKey:a,...d?{dispatchId:d}:{},...h?{bundleId:h}:{},...l?{bundleDigest:l}:{},...E?{graphRevision:E}:{},...v?{claimRevision:v}:{},...y?{rootMemoryEffect:structuredClone(y)}:{},qaVerdict:e.qaVerdict,reviewVerdict:e.reviewVerdict,...w?{qaReceipt:w}:{},...S?{reviewReceipt:S}:{},recordedAt:s,commits:u,receiptRefs:g}}function qs(e){if(!f(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=oe(e.storyId),n=oe(e.epicId),o=x(e.baseSha),i=x(e.headSha),r=x(e.bundleDigest),a=x(e.graphRevision),s=x(e.sourceEvidenceDigest),u=Ge(e.checkedAt),g=At(e.receiptRef),d=e.evidenceVersion==="p205-execution-v2"&&e.contract==="P205-CI-02"?e.contract:void 0,h=e.evidenceVersion==="p205-execution-v2"&&e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,l=e.evidenceVersion==="p205-execution-v2"?x(e.manifestDigest):void 0,E=e.evidenceVersion==="p205-execution-v2"?x(e.resultDigest):void 0,v=e.evidenceVersion==="p205-execution-v2"?ge(e.gateIds).map(oe).filter(w=>!!w).slice(0,64):void 0;if(!(!t||!n||!o||!i||!r||r.length!==64||!a||a.length!==64||!s||s.length!==64||!u||!g||e.evidenceVersion==="p205-execution-v2"&&(!d||h!=="node scripts/test-root.mjs --gate complete"||!l||l.length!==64||!E||E.length!==64||!Array.isArray(e.gateIds)||!v||v.length===0||v.length!==e.gateIds.length)))return{schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",...e.evidenceVersion?{evidenceVersion:e.evidenceVersion}:{},storyId:t,epicId:n,...e.evidenceVersion==="p205-execution-v2"?{contract:d,command:h,manifestDigest:l,gateIds:v,resultDigest:E}:{},baseSha:o,headSha:i,bundleDigest:r,graphRevision:a,sourceEvidenceDigest:s,verdict:e.verdict,checkedAt:u,receiptRef:g}}function vo(e){if(!f(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=oe(e.storyId),n=oe(e.epicId),o=_e(e.branch),i=x(e.baseSha),r=x(e.headSha),a=x(e.aggregateHeadSha),s=x(e.commitBodyDigest),u=x(e.changedPathsDigest),g=e.claimVerification==="canonical"||e.claimVerification==="legacy-migration"?e.claimVerification:void 0,d=x(e.effectiveClaimRevision),h=e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,l=x(e.manifestDigest),E=ge(e.gateIds).map(oe).filter(b=>!!b).slice(0,64),v=x(e.resultDigest),w=x(e.graphRevision),S=x(e.executionEvidenceDigest),y=x(e.sourceEvidenceDigest),N=Ge(e.verifiedAt),$=ge(e.reasonCodes).map(oe).filter(b=>!!b).slice(0,16);if(!(!t||!n||!o||!i||i.length<40||!r||r.length<40||!a||a.length<40||!s||s.length!==64||!u||u.length!==64||!g||!d||d.length!==64||!h||!l||l.length!==64||!Array.isArray(e.gateIds)||E.length!==e.gateIds.length||!v||v.length!==64||!w||w.length!==64||!S||S.length!==64||!y||y.length!==64||!N||$.length===0||e.verdict==="verified"&&(E.length===0||!$.includes("checkpoint-p205-transient-verified"))))return{schemaVersion:1,kind:"story_checkpoint_physical_verification",producer:"client-p205-transient-v1",storyId:t,epicId:n,branch:o,baseSha:i,headSha:r,aggregateHeadSha:a,commitBodyDigest:s,changedPathsDigest:u,claimVerification:g,effectiveClaimRevision:d,command:h,manifestDigest:l,gateIds:E,resultDigest:v,graphRevision:w,executionEvidenceDigest:S,sourceEvidenceDigest:y,verifiedAt:N,verdict:e.verdict,reasonCodes:$,publicSafe:!0}}function Co(e){const t=["schemaVersion","kind","producer","storyId","epicId","branch","baseSha","headSha","graphRevision","effectiveClaimRevision","sourceEvidenceDigest","verifiedAt","reasonCodes","integrationAuthorized","publicSafe"];if(!f(e)||Object.keys(e).some(l=>!t.includes(l))||e.schemaVersion!==1||e.kind!=="story_scheduling_checkpoint_evidence"||e.producer!=="client-git-physical-v1"||e.integrationAuthorized!==!1||e.publicSafe!==!0)return;const n=oe(e.storyId),o=oe(e.epicId),i=_e(e.branch),r=x(e.baseSha),a=x(e.headSha),s=x(e.graphRevision),u=x(e.effectiveClaimRevision),g=x(e.sourceEvidenceDigest),d=Ge(e.verifiedAt),h=ge(e.reasonCodes).map(oe).filter(l=>!!l);if(!(!n||!o||!i||!r||r.length<40||!a||a.length<40||!s||s.length!==64||!u||u.length!==64||!g||g.length!==64||!d||!Array.isArray(e.reasonCodes)||h.length!==1||h[0]!=="checkpoint-git-scheduling-verified"))return{schemaVersion:1,kind:"story_scheduling_checkpoint_evidence",producer:"client-git-physical-v1",storyId:n,epicId:o,branch:i,baseSha:r,headSha:a,graphRevision:s,effectiveClaimRevision:u,sourceEvidenceDigest:g,verifiedAt:d,reasonCodes:h,integrationAuthorized:!1,publicSafe:!0}}function Ks(e){if(!f(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=oe(e.storyId),n=oe(e.epicId),o=x(e.baseSha),i=x(e.headSha),r=x(e.bundleDigest),a=x(e.graphRevision),s=x(e.sourceEvidenceDigest),u=At(e.qaReceiptRef),g=Ge(e.reviewedAt),d=At(e.receiptRef);if(!(!t||!n||!o||!i||!r||r.length!==64||!a||a.length!==64||!s||s.length!==64||!u||!g||!d))return{schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:t,epicId:n,baseSha:o,headSha:i,bundleDigest:r,graphRevision:a,sourceEvidenceDigest:s,qaReceiptRef:u,verdict:e.verdict,reviewedAt:g,receiptRef:d}}function _o(e,t){return["storyId","epicId","baseSha","headSha","bundleDigest","graphRevision"].every(n=>e[n]===t[n])}function Hn(e){if(!f(e))return;const t=e.schemaVersion===1&&e.capturedFromCurrentCheckout===!0&&e.capturedFrom===void 0,n=e.schemaVersion===2&&e.capturedFromCurrentCheckout===void 0&&(e.capturedFrom==="current-checkout"||e.capturedFrom==="branch-ref");if(!t&&!n)return;const o=_e(e.originBranch),i=x(e.originHeadSha),r=_e(e.executionBranch),a=Ge(e.capturedAt);if(!(!o||!i||i.length<40||!r||!a||o===r))return t?{schemaVersion:1,originBranch:o,originHeadSha:i,executionBranch:r,capturedFromCurrentCheckout:!0,capturedAt:a}:{schemaVersion:2,originBranch:o,originHeadSha:i,executionBranch:r,capturedFrom:e.capturedFrom,capturedAt:a}}function wo(e){if(!f(e)||e.schemaVersion!==1||e.verdict!=="passed")return;const t=x(e.executionHeadSha),n=x(e.graphRevision),o=Ge(e.checkedAt),i=At(e.receiptRef),r=ge(e.gateIds).map(oe).filter(d=>!!d).slice(0,128),a=e.evidenceVersion==="p205-execution-v2"&&e.producer==="local-yolo-tdd"&&e.contract==="P205-CI-02"&&e.command==="node scripts/test-root.mjs --gate complete",s=e.evidenceVersion===void 0&&e.producer===void 0&&e.contract===void 0&&e.command===void 0&&e.manifestDigest===void 0&&e.resultDigest===void 0,u=a?x(e.manifestDigest):void 0,g=a?x(e.resultDigest):void 0;if(!(!t||t.length<40||!n||n.length!==64||!o||!i||r.length===0||!Array.isArray(e.gateIds)||r.length!==e.gateIds.length||e.gateIds.length>128||!s&&!a||a&&(!u||u.length!==64||!g||g.length!==64)))return{schemaVersion:1,...a?{evidenceVersion:"p205-execution-v2",producer:"local-yolo-tdd",contract:"P205-CI-02",command:"node scripts/test-root.mjs --gate complete",manifestDigest:u,resultDigest:g}:{},verdict:"passed",executionHeadSha:t,graphRevision:n,checkedAt:o,receiptRef:i,gateIds:r}}const Js=16384;function Qs(e){if(!f(e))return;const t=(o,i)=>o===null||typeof o=="boolean"?!0:typeof o=="number"?Number.isFinite(o):typeof o=="string"?o.length<=512&&!o.startsWith("/")&&!/^[A-Za-z]:[\\/]/.test(o)&&!o.includes("\\")&&!/:\/\//.test(o)&&!/[\u0000-\u001f]/.test(o):i>=4?!1:Array.isArray(o)?o.length<=256&&o.every(r=>t(r,i+1)):f(o)?Object.keys(o).length<=64&&Object.entries(o).every(([r,a])=>/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(r)&&t(a,i+1)):!1;if(!t(e,0))return;const n=JSON.stringify(e);if(!(Buffer.byteLength(n,"utf8")>Js))return JSON.parse(n)}function Ro(e){if(!f(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:oe(e.epicId),executionBranch:_e(e.executionBranch),originBranch:_e(e.originBranch),graphRevision:x(e.graphRevision),originHeadSha:x(e.originHeadSha),lastAcceptedCheckpointHeadSha:x(e.lastAcceptedCheckpointHeadSha),executionHeadSha:x(e.executionHeadSha),acceptedCheckpointIds:ge(e.acceptedCheckpointIds),acceptedCheckpointHeads:ge(e.acceptedCheckpointHeads),reconciliationCommitShas:ge(e.reconciliationCommitShas),commitRangeDigest:x(e.commitRangeDigest),changedPaths:ge(e.changedPaths),changedPathsDigest:x(e.changedPathsDigest),allowedWriteSet:ge(e.allowedWriteSet),allowedWriteSetDigest:x(e.allowedWriteSetDigest),aggregateReceiptRef:At(e.aggregateReceiptRef),aggregateManifestDigest:x(e.aggregateManifestDigest),aggregateResultDigest:x(e.aggregateResultDigest),producedAt:Ge(e.producedAt),revalidatedAt:Ge(e.revalidatedAt),publicSafe:!0},n=["originSyncHeadSha","originSyncCommitShas","originSyncPaths","originSyncPathsDigest","originSyncResolvedPaths","originSyncResolvedPathsDigest"],o=n.filter(s=>e[s]!==void 0).length;if(o!==0&&o!==n.length)return;const i=o===0?void 0:{originSyncHeadSha:x(e.originSyncHeadSha),originSyncCommitShas:ge(e.originSyncCommitShas),originSyncPaths:ge(e.originSyncPaths),originSyncPathsDigest:x(e.originSyncPathsDigest),originSyncResolvedPaths:ge(e.originSyncResolvedPaths),originSyncResolvedPathsDigest:x(e.originSyncResolvedPathsDigest)};if(i&&(!i.originSyncHeadSha||i.originSyncHeadSha.length<40||i.originSyncCommitShas.length===0||i.originSyncCommitShas.length>256||i.originSyncCommitShas.some(s=>!/^[a-f0-9]{40,64}$/i.test(s))||i.originSyncPaths.length>2048||i.originSyncResolvedPaths.length>64||i.originSyncPathsDigest!==zr(i.originSyncPaths)||i.originSyncResolvedPathsDigest!==zr(i.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(s=>!/^[a-f0-9]{40,64}$/i.test(s))||t.reconciliationCommitShas.length>2048||t.reconciliationCommitShas.some(s=>!/^[a-f0-9]{40,64}$/i.test(s))||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!==Nc(t.lastAcceptedCheckpointHeadSha,t.executionHeadSha,t.reconciliationCommitShas)||t.changedPathsDigest!==zr(t.changedPaths)||t.allowedWriteSetDigest!==zr(t.allowedWriteSet))return;const r={...t,...i??{}},a=x(e.inputDigest);if(!(!a||a.length!==64||a!==Oc(r)))return{...r,inputDigest:a}}function Gn(e){if(!f(e)||e.schemaVersion!==1)return;const t=Qr(e,["schemaVersion","kind","storyId","epicId","baseSha","headSha","originalBaseSha","originalHeadSha","gitPullRequest","preservesLaterCommits","historyRewrite","recordedAt"])??{},n=ge(e.receiptRefs).map(At).filter(i=>!!i).slice(0,256),o=ge(e.revertCommits).map(ue).filter(i=>!!i).slice(0,256);return{...t,...n.length?{receiptRefs:n}:{},...o.length?{revertCommits:o}:{}}}function Xs(e){if(!(!f(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 Ao(e){if(!f(e)||e.schemaVersion!==1||e.publicSafe!==!0)return;const t=oe(e.epicId),n=_e(e.executionBranch),o=_e(e.originBranch),i=x(e.baseSha),r=x(e.executionHeadSha),a=e.mergeSha===void 0?void 0:x(e.mergeSha),s=e.pushedSha===void 0?void 0:x(e.pushedSha),u=oe(e.idempotencyKey),g=Ge(e.attemptStartedAt),d=e.completedAt===void 0?void 0:Ge(e.completedAt),h=ge(e.localGateReceiptRefs).map(At).filter(w=>!!w).slice(0,256),l=ge(e.reasonCodes).map(oe).filter(w=>!!w).slice(0,64),E=ed(e.candidateQa),v=Zs(e.providerGuard);if(!(!t||!n||!o||!i||!r||!u||!g||h.length===0||l.length===0||!["direct","single_pr"].includes(String(e.strategy))||!["prepared","merged","pushed","denied_external_gate","blocked_local_or_repo"].includes(String(e.physicalStatus))||typeof e.retryEligible!="boolean"||e.providerGuard!==void 0&&!v||v&&(e.strategy!=="single_pr"||e.physicalStatus!=="pushed"||v.prHeadSha!==a||v.originHeadSha!==i)))return{schemaVersion:1,epicId:t,executionBranch:n,originBranch:o,baseSha:i,executionHeadSha:r,...a?{mergeSha:a}:{},...s?{pushedSha:s}:{},strategy:e.strategy,...jt(e.prNumber)?{prNumber:jt(e.prNumber)}:{},physicalStatus:e.physicalStatus,localGateReceiptRefs:h,idempotencyKey:u,attemptStartedAt:g,...E?{candidateQa:E}:{},...v?{providerGuard:v}:{},...d?{completedAt:d}:{},retryEligible:e.retryEligible,reasonCodes:l,publicSafe:!0}}function Zs(e){if(!f(e)||e.schemaVersion!==1||e.provider!=="github"||e.publicSafe!==!0)return;const t=String(e.mode),n=String(e.source),o=t==="recovered_exact_tree"?n==="physical_recovery":t==="strict_up_to_date_expected_head"&&["branch_protection","ruleset","branch_protection_and_ruleset"].includes(n),i=x(e.prHeadSha),r=x(e.originHeadSha),a=Ge(e.checkedAt);if(!(!o||!i||!r||!a))return{schemaVersion:1,provider:"github",mode:t,source:n,prHeadSha:i,originHeadSha:r,checkedAt:a,publicSafe:!0}}function ed(e){if(!f(e)||e.schemaVersion!==1||e.kind!=="epic_merge_candidate_qa"||e.contract!=="P205-CI-02"||e.command!==Sr)return;const n=Object.fromEntries(["originHeadSha","executionHeadSha","mergeSha","treeSha","graphRevision","manifestDigest","resultDigest"].map(a=>[a,x(e[a])])),o=Ge(e.checkedAt),i=At(e.receiptRef),r=ge(e.gateIds).filter(a=>/^[a-z0-9-]+$/.test(a)).slice(0,128);if(!(Object.values(n).some(a=>!a)||!o||!i||r.length===0))return{schemaVersion:1,kind:e.kind,contract:e.contract,command:e.command,...n,checkedAt:o,receiptRef:i,gateIds:r}}function td(e){if(!f(e))return;const t={...ue(e.active_epic_id??e.activeEpicId)?{active_epic_id:ue(e.active_epic_id??e.activeEpicId)}:{},...ue(e.active_story_id??e.activeStoryId)?{active_story_id:ue(e.active_story_id??e.activeStoryId)}:{},...ue(e.active_step_id??e.activeStepId)?{active_step_id:ue(e.active_step_id??e.activeStepId)}:{},...ue(e.session_id??e.sessionId)?{session_id:ue(e.session_id??e.sessionId)}:{},...ue(e.started_at??e.startedAt)?{started_at:ue(e.started_at??e.startedAt)}:{}};return Object.keys(t).length>0?t:void 0}function rd(e){const t=Qr(e.completionEvidence??e.completion_evidence,["prNumber","pr_number","prState","pr_state","pullRequestState","merged","mergedAt","issueNumber","issue_number","issueState","issue_state","closedAt"]),n=Qr(e.issueCloseAudit??e.issue_close_audit,["schema_version","event","storyId","epicId","issueNumber","closedAt","publicSafe","rawLogStorage"]),o=Qr(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}:{},...ue(e.physicalMergeStatus)?{physicalMergeStatus:ue(e.physicalMergeStatus)}:{},...ue(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)?{pr_state:ue(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)}:{},...ue(e.issue_state??e.issueState??e.workflow_issue_state)?{issue_state:ue(e.issue_state??e.issueState??e.workflow_issue_state)}:{},...jt(e.issue_number??e.issueNumber)?{issue_number:jt(e.issue_number??e.issueNumber)}:{},...t?{completionEvidence:t}:{},...n?{issueCloseAudit:n}:{},...o?{scopedCiEvidence:o}:{}}}class ut extends Error{reasonCode;constructor(t){super(t),this.name="StateSnapshotIntegrityError",this.reasonCode=t}}const nd=new Set(["yolo","yoloop","finalize-epic","audit"]),id=8;function od(e,t){try{const n=In(String(Ae("git",["rev-parse","--absolute-git-dir"],{cwd:e,stdio:["ignore","pipe","ignore"],timeout:1e4,encoding:"utf8"})).trim()),o=In(String(Ae("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd:e,stdio:["ignore","pipe","ignore"],timeout:1e4,encoding:"utf8"})).trim());if(n!==o&&(!t||String(Ae("git",["symbolic-ref","--short","HEAD"],{cwd:e,stdio:["ignore","pipe","ignore"],timeout:1e4,encoding:"utf8"})).trim()!==`epic/${t}`))return;const i=J(e,".neocortex","state.json");if(!Ct(i))return;const r=Kc({projectRoot:e,bytes:Ue(i)});r.ok||process.stderr.write(`[Neocortex] governance runtime store mirror skipped: ${r.reasonCode}
9
9
  `)}catch{process.stderr.write(`[Neocortex] governance runtime store mirror skipped: governance-mode-unavailable
10
- `)}}function Hn(e){return/docs\/epics\/epic-(P[1-9][0-9]*)\.md\b/.exec(e)?.[1]??/docs\/stories\/(P[1-9][0-9]*)\.[0-9]+\.story\.md\b/.exec(e)?.[1]}function td(e,t={},n={},i){const o=d=>{try{return String(Ae("git",[...d],{cwd:e,stdio:["ignore","pipe","ignore"],timeout:1e4,encoding:"utf8"})).trim()}catch{return}};if(o(["rev-parse","--is-inside-work-tree"])!=="true")return;const r=[],a=Object.entries(t).sort(([d],[h])=>+(h===i)-+(d===i));for(const[d,h]of a){if(r.length>=Zs)break;if(!f(h)||!f(h.origin_binding))continue;const l=h.execution_branch,E=h.origin_binding;if(typeof l!="string"||E.executionBranch!==l||typeof E.originHeadSha!="string"||!/^[a-f0-9]{40,64}$/.test(E.originHeadSha)||!/^[A-Za-z0-9][A-Za-z0-9._/-]{0,239}$/.test(l)||l.includes(".."))continue;const _=o(["rev-parse","--verify","--quiet",`refs/heads/${l}^{commit}`]);if(!_||!/^[a-f0-9]{40,64}$/.test(_)||o(["merge-base","--is-ancestor",E.originHeadSha,_])===void 0)continue;const w=[];for(const S of Object.values(n)){if(w.length>=128)break;if(!f(S)||(S.epic_id??S.epic)!==d)continue;const y=f(S.checkpoint)&&typeof S.checkpoint.headSha=="string"?S.checkpoint.headSha:f(S.scheduling_checkpoint_evidence)&&typeof S.scheduling_checkpoint_evidence.headSha=="string"?S.scheduling_checkpoint_evidence.headSha:void 0;!y||!/^[a-f0-9]{40,64}$/.test(y)||w.includes(y)||o(["merge-base","--is-ancestor",y,_])!==void 0&&w.push(y)}r.push(Object.freeze({epicId:d,executionBranch:l,originHeadSha:E.originHeadSha,executionHeadSha:_,...w.length>0?{containedHeadShas:Object.freeze(w)}:{}}))}const s=o(["ls-files","--error-unmatch","--",".neocortex/state.json"])!==void 0,u=s?void 0:Hc({projectRoot:e}),g=u===void 0?void 0:u.ok?u.mode==="runtime-store"?"runtime-store":void 0:u.reasonCode==="governance-tracking-ambiguous"?"ambiguous":void 0;return Object.freeze({schemaVersion:1,stateFileTracked:s,...r.length>0?{executionBases:Object.freeze(r)}:{},...g?{governanceMode:g,governanceCapability:Gr.STORY_GOVERNANCE_RUNTIME_STORE}:{}})}function wi(e){return typeof e=="string"&&Xs.has(e)}function Gn(e,t={}){const n=q(e,".neocortex","state.json"),i=Ct(n),o=i?void 0:Ri(e,{epicAware:!0});if(!i&&o===void 0)throw new ut("git-lifecycle-state-missing");let r;try{r=JSON.parse(o??$e(n,"utf8"))}catch{throw new ut("git-lifecycle-state-corrupt")}if(!f(r)||!f(r.epics)||!f(r.stories))throw new ut("git-lifecycle-state-shape-invalid");const a=Object.values(r.epics).some(s=>f(s)&&(s.branch_mode==="epic"||_e(s.execution_branch)!==void 0));if(a)try{ar(e,{required:!0})}catch(s){const u=s instanceof Error&&/^git-lifecycle-/.test(s.message)?s.message:"git-lifecycle-runtime-invalid";if(t.allowMissingRuntime&&i&&u==="git-lifecycle-runtime-missing")return{lifecycleDeclared:!0,runtimeMissing:!0};throw new ut(u)}return{lifecycleDeclared:a,runtimeMissing:!1}}function Ri(e,t){const n=Gc(e);if(!n.ok){if(t.epicAware&&!t.projectless)throw new ut(n.reasonCode);return}return n.value?.toString("utf8")}const rd=256,nd=/^[A-Za-z0-9][A-Za-z0-9_-]{7,95}$/,od=/^[a-f0-9]{64}$/;function id(e){const t=Date.now(),n={};for(const i of Object.values(e.storyWorktrees?.entries??{})){if(!f(i)||i.state!=="active")continue;const{epicId:o,storyId:r,leaseId:a,graphRevision:s,expiresAt:u}=i;typeof o!="string"||typeof r!="string"||!r.startsWith(`${o}.`)||typeof a!="string"||!nd.test(a)||typeof s!="string"||!od.test(s)||typeof u!="string"||!(Date.parse(u)>t)||(n[o]??=[]).push({schemaVersion:1,storyId:r,leaseId:a,graphRevision:s,expiresAt:u})}for(const[i,o]of Object.entries(n))o.length>rd?delete n[i]:o.sort((r,a)=>String(r.storyId).localeCompare(String(a.storyId))||String(r.leaseId).localeCompare(String(a.leaseId)));return n}function Zr(e,t={}){const n=q(e,".neocortex","state.json"),i=Ct(n)?void 0:Ri(e,t);if(!Ct(n)&&i===void 0){if(t.epicAware&&!t.projectless)throw new ut("git-lifecycle-state-missing");return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}let o,r,a={};try{const S=i??$e(n,"utf-8");r=Le("sha256").update(S).digest("hex");const y=$a(e,r)??JSON.parse(S),D=f(y.epics)?y.epics:{},U=Object.values(D).some(Z=>f(Z)&&(Z.branch_mode==="epic"||_e(Z.execution_branch)!==void 0)),b=ar(e,{required:!!(t.epicAware&&U&&!t.projectless)});o=bn(y,b),a=id(b);const C=f(o.stories)?o.stories:{},A=f(o.epics)?o.epics:{},Y=f(y.stories)?y.stories:{};for(const[Z,Q]of Object.entries(C)){const j=f(Q)?Q:void 0;if(!j?.checkpoint)continue;const ae=typeof j.epic_id=="string"?j.epic_id:Z.split(".")[0],ve=f(A[ae])?A[ae]:void 0,be=_e(ve?.execution_branch);if(!be)continue;const T=Tc(e,j.checkpoint,Z,ae,be,t.p205Authorities?.[Z],Fo(Z,j,f(j.checkpoint)?j.checkpoint:void 0));if(T.kind==="integration-authorized")j.checkpoint_verification=T.verification,delete j.scheduling_checkpoint_evidence;else if(T.kind==="scheduling-only")j.scheduling_checkpoint_evidence=T.evidence,delete j.checkpoint,delete j.checkpoint_verification;else if(T.kind==="rejected"){j.checkpoint_verification=T.verification,delete j.scheduling_checkpoint_evidence;const ee=f(Y[Z])?Y[Z]:void 0;if(delete j.checkpoint,b.stories[Z]?.checkpoint!==void 0)for(const Ce of["status","last_step","steps_completed"])ee&&Object.prototype.hasOwnProperty.call(ee,Ce)?j[Ce]=structuredClone(ee[Ce]):delete j[Ce];["done","completed","merged"].includes(String(j.status).toLowerCase())&&(j.status="blocked")}}}catch(S){if(t.epicAware&&!t.projectless){const y=S instanceof Error&&/^git-lifecycle-/.test(S.message)?S.message:"git-lifecycle-state-corrupt";throw new ut(y)}return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}try{const S=Ds(o);S.length>0&&Ls(S)}catch{}const s=o.config??o.project??{},u=o.stories??{},g={};for(const[S,y]of Object.entries(u)){const D=f(y.review_request)&&y.review_request.kind==="git-pull-request"?Ys(y.review_request):Un(y.review_request);g[S]={id:y.id??S,title:y.title,epic_id:y.epic_id,status:y.status??"backlog",...fi(y.source)?{source:fi(y.source)}:{},steps_completed:y.steps_completed??[],last_step:y.last_step??null,branch_name:y.branch_name??null,pr_number:y.pr_number,...Xr(y.branch_mode)?{branch_mode:Xr(y.branch_mode)}:{},...yi(y.checkpoint)?{checkpoint:yi(y.checkpoint)}:{},...Ii(y.checkpoint_verification)?{checkpoint_verification:Ii(y.checkpoint_verification)}:{},...Ei(y.scheduling_checkpoint_evidence)?{scheduling_checkpoint_evidence:Ei(y.scheduling_checkpoint_evidence)}:{},...D?{review_request:D}:{},...Un(y.rollback_receipt)?{rollback_receipt:Un(y.rollback_receipt)}:{},...jt(y.workflow_issue)?{workflow_issue:jt(y.workflow_issue)}:{},...Qs(y),...Array.isArray(y.depends_on)?{depends_on:hi(y.depends_on)}:{},files_to_modify:ge(y.files_to_modify),...typeof y.artifact_sha256=="string"&&/^[a-f0-9]{64}$/.test(y.artifact_sha256)?{artifact_sha256:y.artifact_sha256}:{},...Us(y),...gi(y.supersededBy)?{supersededBy:gi(y.supersededBy)}:{},risk:typeof y.risk=="string"?y.risk:void 0,blast_radius:typeof y.blast_radius=="number"?y.blast_radius:void 0}}const d=o.epics??{},h={};for(const[S,y]of Object.entries(d)){const D=js(y.lifecycle_classification),U=$s(y.createEpicPlanning,S),b=U.checkpoint;let C,A,Y,Z;if(b&&f(y.createEpicPlanningClaim)&&typeof y.createEpicPlanningClaim.claimId=="string"&&f(y.createEpicPlanningPhysical))try{Co(o,y.createEpicPlanningClaim.claimId,S,!0),C=JSON.parse(JSON.stringify(y.createEpicPlanningPhysical))}catch{}if(C&&f(y.createEpicPlanningClaim)&&typeof y.createEpicPlanningClaim.claimId=="string"&&f(y.createEpicPlanningResearchPhysical))try{_o(o,y.createEpicPlanningClaim.claimId,S),A=JSON.parse(JSON.stringify(y.createEpicPlanningResearchPhysical))}catch{}if(t.verifyPlanningGeneration&&b&&y.status==="generated"&&f(y.createEpicPlanningClaim)&&typeof y.createEpicPlanningClaim.claimId=="string"&&f(y.createEpicPlanningGenerationPhysical))try{if(Ca(e,y.createEpicPlanningClaim.claimId,S).stateSha256!==r)throw new Error("planning-generation-snapshot-raced");Y=JSON.parse(JSON.stringify(y.createEpicPlanningGenerationPhysical)),C=JSON.parse(JSON.stringify(y.createEpicPlanningPhysical)),A=JSON.parse(JSON.stringify(y.createEpicPlanningResearchPhysical))}catch{}if(Y&&f(y.createEpicPlanningClaim)&&typeof y.createEpicPlanningClaim.claimId=="string")try{const Q=wo(e,y.createEpicPlanningClaim.claimId,S);if(Q.stateSha256!==r)throw new Error("planning-memory-snapshot-raced");Z=JSON.parse(JSON.stringify(Q))}catch{}h[S]={id:y.id??S,title:y.title,...b?{createEpicPlanning:b}:{},...U.diagnostic?{createEpicPlanningProjection:U.diagnostic}:{},...C?{createEpicPlanningPhysical:C}:{},...A?{createEpicPlanningResearchPhysical:A}:{},...Y?{createEpicPlanningGenerationPhysical:Y}:{},...Z?{createEpicPlanningMemoryPhysical:Z}:{},status:y.status,stories:y.stories,total_stories:y.total_stories,completed_stories:y.completed_stories,depends_on:hi(y.depends_on),...Xr(y.branch_mode)?{branch_mode:Xr(y.branch_mode)}:{},..._e(y.execution_branch)?{execution_branch:_e(y.execution_branch)}:{},..._e(y.origin_branch)?{origin_branch:_e(y.origin_branch)}:{},...mi(y.branch_lease)?{branch_lease:mi(y.branch_lease)}:{},...$n(y.origin_binding)?{origin_binding:$n(y.origin_binding)}:{},...vi(y.aggregate_qa_receipt)?{aggregate_qa_receipt:vi(y.aggregate_qa_receipt)}:{},...Ci(y.head_reconciliation_receipt)?{head_reconciliation_receipt:Ci(y.head_reconciliation_receipt)}:{},...Vc(y.story_worktree_evidence)?{story_worktree_evidence:$c(y.story_worktree_evidence,S,t.publishedStoryReconciliations)}:{},...(a[S]?.length??0)>0?{story_worktree_leases:structuredClone(a[S])}:{},...(Q=>Q?{branch_mode_conversion_receipt:Q}:{})(zs(y.branch_mode_conversion_receipt)),...jt(y.pr_number)?{pr_number:jt(y.pr_number)}:{},...ue(y.physicalMergeStatus)?{physicalMergeStatus:ue(y.physicalMergeStatus)}:{},...x(y.graph_revision)?{graph_revision:x(y.graph_revision)}:{},..._i(y.terminal_git_receipt)?{terminal_git_receipt:_i(y.terminal_git_receipt)}:{},...D?{lifecycle_classification:D}:{},...(Q=>Q?{p205_authority_diagnostic:Q}:{})(dd(t.p205AuthorityDiagnostics,S))}}const l=Js(o.current_session??o.currentSession),E=f(o.archPlan)?Jr(o.archPlan.execution):void 0,_=o.epic_id_ledger,w=Array.isArray(_?.reserved_ids)?[...new Set(_.reserved_ids.filter(S=>typeof S=="string"&&/^P\d+$/.test(S)))].slice(0,2048):[];return{schema_version:typeof o.schema_version=="number"?o.schema_version:void 0,config:{project_name:s.project_name??s.name??"unknown",default_branch:s.default_branch??"main",language:s.language??"pt-BR",yolo_mode:s.yolo_mode,user_name:s.user_name,worktree_base:s.worktree_base,max_parallel_stories:s.max_parallel_stories,project_id:typeof s.project_id=="string"?s.project_id:void 0},stories:g,epics:h,...w.length>0?{epic_id_ledger:{schema_version:1,reserved_ids:w}}:{},...l?{current_session:l}:{},...E?{archPlan:{execution:E}}:{}}}const Wn=[["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"]],Fn="6a41a47ff2521f80c2296ed811b0f0b304c54750",zn="dbc6d4670b2b7868a01973b1240e24589f1c5b7d",Ai="30dccfff07f9c969be11ae1d28e62a09731a0768";function ad(e,t){try{const n=t.indexOf(Ai);if(n<1||t[n-1]!==Fn)return new Map;const i=Ae("git",["show","--no-patch","--format=%P",Ai],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim(),o=Ae("git",["show","--no-patch","--format=%P",zn],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim();if(i!==`${Fn} ${zn}`||o!==`${Wn.at(-1)[1]} ${Fn}`)return new Map;const r=Ae("git",["rev-list","--first-parent","--reverse",zn],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
11
- `),a=new Map;let s=-1;for(const[u,[g,d]]of Wn.entries()){const h=r.indexOf(d);if(h<=s)return new Map;s=h,a.set(g,{headSha:d,position:u-Wn.length})}return a}catch{return new Map}}function cd(e){return e instanceof Error&&(Nc(e.message)||/^(?:p205|git-lifecycle)-[a-z0-9-]+$/.test(e.message))?e.message:"p205-transient-execution-failed"}const bi="p205-authority-epic-order-mismatch";function sd(e,t){const n=new Set(e),i=[...t].sort((h,l)=>h.position-l.position),o=i.map(h=>h.storyId),r=new Set(o),a=e.length-n.size+(o.length-r.size),s=[...n].filter(h=>!r.has(h)).length,u=[...r].filter(h=>!n.has(h)).length,g=new Map(i.map(h=>[h.storyId,h.position]));let d=0;for(const h of i)for(const l of new Set(h.dependsOn)){const E=g.get(l);E!==void 0&&l!==h.storyId&&E>=h.position&&(d+=1)}return a===0&&s===0&&u===0&&d===0?{ok:!0,order:o}:{ok:!1,reasonCode:bi,counts:{listed:e.length,physical:o.length,missing:s,extra:u,duplicates:a,dependencyViolations:d}}}function dd(e,t){const n=e?.find(r=>r.epicId===t);if(!n||n.reasonCode!==bi)return;const i=r=>Number.isInteger(r)&&r>=0?Math.min(r,4096):0,{counts:o}=n;return{reasonCode:n.reasonCode,counts:{listed:i(o.listed),physical:i(o.physical),missing:i(o.missing),extra:i(o.extra),duplicates:i(o.duplicates),dependencyViolations:i(o.dependencyViolations)}}}function pd(e){const t=e?.depends_on;return Array.isArray(t)?t.filter(n=>typeof n=="string"&&/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(n)).slice(0,256):[]}async function rl(e,t,n){return(await xi(e,t,n)).authorities}async function xi(e,t,n,i={}){const o=[],r={},a=[],s=await ud(e,t,n,o,r,a),u=a.at(-1);return{authorities:s,diagnostics:o,epicAuthorities:r,...u?{failureReasonCode:u}:{}}}async function ud(e,t,n,i,o,r){if(!wi(n))return{};if(n==="audit"||n==="yoloop")return{};if(ko(t,n))return{};try{const a=JSON.parse($e(q(e,".neocortex","state.json"),"utf8")),s=ar(e,{required:!0}),u=bn(a,s),g=f(u.stories)?u.stories:{},d=f(u.epics)?u.epics:{},h=Ae("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8"}).trim(),l=Ae("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8"}).trim(),E=Ae("git",["rev-list","--first-parent","--reverse",h],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
12
- `).filter(Boolean),_=new Map(E.map((T,ee)=>[T,ee])),w=ad(e,E),S=t.match(/(?:^|\s)@?docs\/stories\/([A-Za-z][A-Za-z0-9._-]*)\.story\.md(?:\s|$)/)?.[1],y=n==="yoloop"?t.match(/(?:^|[\s/@])epic-(P[1-9][0-9]*)\.md(?:\s|$)/i)?.[1]?.toUpperCase():void 0,D=new Set,U=Object.entries(g).flatMap(([T,ee])=>{if(S&&T!==S)return[];const Ce=f(ee)?ee:void 0,xe=f(Ce?.checkpoint)?Ce.checkpoint:void 0;if(!xe)return[];const ie=typeof Ce?.epic_id=="string"?Ce.epic_id:T.split(".")[0];if(y&&ie!==y)return[];const B=x(xe?.headSha),Je=ie==="P222"?w.get(T):void 0,me=_.get(B??"")??(Je&&Je.headSha===B?Je.position:void 0);if(!B||B.length<40||me===void 0)return D.add(ie),[];const $=f(d[ie])?d[ie]:void 0;if($?.branch_mode!=="epic"||_e($.execution_branch)!==l||_e(xe.branch)!==l)return D.add(ie),[];const ye=x(xe.graphRevision);if(!ye||ye.length!==64)return D.add(ie),[];const gt=x(xe.claimRevision),et=[...Fo(T,Ce,xe)].sort(),fe=Uc(e,xe,T,ie,l,et);if(!fe&&gt){if(et.length===0)return D.add(ie),[];const L=Ae("git",["diff-tree","--no-commit-id","--name-only","-r","-z",B],{cwd:e,encoding:"utf8"}).split("\0").filter(Boolean),H=Lc(T,et).map(k=>[...k].sort()).find(k=>gt===Le("sha256").update(k.join("\0")).digest("hex")||gt===Le("sha256").update(JSON.stringify(k)).digest("hex"));if(!H)return D.add(ie),[];let Ye=[];if(xe.rootMemoryEffect!==void 0)try{Ye=Fc(e,xe.rootMemoryEffect,{storyId:T,executionBranch:l,baseSha:String(xe.baseSha),headRef:B,childPaths:H}).files.map(k=>k.path)}catch{return D.add(ie),[]}if(L.length===0||L.some(k=>!H.some(le=>jc(le,k))&&!Ye.includes(k)))return D.add(ie),[]}else if(!fe)return D.add(ie),[];return ye?.length===64?[{storyId:T,epicId:ie,graphRevision:ye,checkpointHead:B,position:me,dependsOn:pd(Ce)}]:[]}),b=new Set(D),C=[];for(const[T,ee]of Object.entries(d)){const Ce=f(ee)?ee:void 0,xe=Array.isArray(Ce?.stories)?Ce.stories.filter(ye=>typeof ye=="string"):Object.keys(g).filter(ye=>ye.startsWith(`${T}.`)),ie=U.filter(ye=>ye.epicId===T);if(ie.length===0||b.has(T))continue;const B=new Set(ie.map(ye=>ye.storyId)),Je=xe.filter(ye=>B.has(ye)),me=sd(Je,ie);if(me.ok){C.push(...me.order);continue}b.add(T),i.push({epicId:T,reasonCode:me.reasonCode,counts:me.counts});const{counts:$}=me;process.stderr.write(`[Neocortex] ${me.reasonCode} (listed=${$.listed} physical=${$.physical} missing=${$.missing} extra=${$.extra} duplicates=${$.duplicates} dependencyViolations=${$.dependencyViolations}). Checkpoint projection remains fail-closed.
13
- `)}const A=new Map(C.map((T,ee)=>[T,ee]));U.sort((T,ee)=>(A.get(T.storyId)??Number.MAX_SAFE_INTEGER)-(A.get(ee.storyId)??Number.MAX_SAFE_INTEGER));const Y={},Z=[...new Set(U.filter(T=>!b.has(T.epicId)).map(T=>T.graphRevision))],Q=n==="finalize-epic"?Yn(t):void 0,j=Q&&f(d[Q])?d[Q]:void 0,ae=x(j?.graph_revision),ve=!!(Q&&j?.branch_mode==="epic"&&ae&&ae.length===64&&!b.has(Q)&&U.some(T=>T.epicId===Q));ve&&!Z.includes(ae)&&Z.push(ae);let be=new Map;Z.length>0&&(be=await Oc(e,{headSha:h,graphRevisions:Z}));for(const T of U){if(b.has(T.epicId))continue;const ee=be.get(T.graphRevision);if(!ee)throw new Error("p205-transient-authority-missing");Y[T.storyId]=ee}if(ve){const T=be.get(ae);if(!T)throw new Error("p205-transient-authority-missing");o[Q]=T}return await ld({projectRoot:e,commandId:n,targetEpicId:y,currentHead:h,epics:d,candidates:U,authorities:Y}),Y}catch(a){const s=cd(a);return r.push(s),process.stderr.write(`[Neocortex] ${s}. Checkpoint projection remains fail-closed.
14
- `),{}}}async function ld(e){if(e.commandId!=="yoloop"||!e.targetEpicId)return;const t=e.epics[e.targetEpicId],n=f(t)?t:void 0,i=f(n?.aggregate_qa_receipt)?n.aggregate_qa_receipt:void 0,o=x(n?.graph_revision);if(!i||!o||o.length!==64||i.schemaVersion!==1||i.evidenceVersion!=="p205-execution-v2"||i.producer!=="local-yolo-tdd"||i.contract!=="P205-CI-02"||i.command!==Sr||i.verdict!=="passed"||i.executionHeadSha!==e.currentHead||i.graphRevision!==o||!Array.isArray(i.gateIds)||i.gateIds.length===0||!i.gateIds.every(h=>typeof h=="string")||typeof i.manifestDigest!="string"||!/^[a-f0-9]{64}$/i.test(i.manifestDigest)||typeof i.resultDigest!="string"||!/^[a-f0-9]{64}$/i.test(i.resultDigest)||typeof i.receiptRef!="string"||!/^local-yolo-tdd:[a-f0-9]{64}$/i.test(i.receiptRef))return;const r=i.gateIds,a=`local-yolo-tdd:${Le("sha256").update(["epic-aggregate-p205-execution-v2",Sr,e.currentHead,o,i.manifestDigest,r.join(","),i.resultDigest].join("\0")).digest("hex")}`;if(i.receiptRef!==a)return;const s=e.candidates.find(h=>h.epicId===e.targetEpicId&&h.graphRevision===o&&e.authorities[h.storyId]),u=s?Bc(e.authorities[s.storyId]):void 0;if(!u||u.executionHeadSha!==e.currentHead||u.graphRevision!==o||u.manifestDigest!==i.manifestDigest||!fd(u.gateIds,r))return;const g=`local-yolo-tdd:${Le("sha256").update(["epic-aggregate-p205-execution-v2",Sr,e.currentHead,o,u.manifestDigest,u.gateIds.join(","),u.resultDigest].join("\0")).digest("hex")}`,d=i.receiptRef;await zo(e.projectRoot,h=>{const l=Pc(h,e.targetEpicId),E=f(l.aggregate_qa_receipt)?l.aggregate_qa_receipt:void 0;!E||E.executionHeadSha!==e.currentHead||E.graphRevision!==o||E.receiptRef!==d||(l.aggregate_qa_receipt={schemaVersion:1,evidenceVersion:"p205-execution-v2",producer:"local-yolo-tdd",contract:"P205-CI-02",command:Sr,verdict:"passed",executionHeadSha:e.currentHead,graphRevision:o,manifestDigest:u.manifestDigest,resultDigest:u.resultDigest,checkedAt:u.executedAt,receiptRef:g,gateIds:[...u.gateIds]})})}function Yn(e){return(e.match(/(?:^|[\s/@])epic-(P[1-9][0-9]{0,30})\.md(?:\s|$)/i)?.[1]??e.match(/(?:^|\s)@?(P[1-9][0-9]{0,30})(?:\s|$)/i)?.[1])?.toUpperCase()}async function hd(e){if(e.commandId!=="finalize-epic")return;const t=Yn(e.args);if(!t)return;const{produceEpicLifecycleEvidence:n}=await import("../git/epic-lifecycle-evidence.js"),i=JSON.parse($e(q(e.projectRoot,".neocortex","state.json"),"utf8")),o=bn(i,ar(e.projectRoot,{required:!1})),r=f(o.epics)&&f(o.epics[t])?o.epics[t]:void 0;if(!r||r.branch_mode!=="epic")return;const a=e.epicAuthorities[t],s=async(...g)=>Ae("git",[...g],{cwd:e.projectRoot,encoding:"utf8",maxBuffer:32*1024*1024,stdio:["ignore","pipe","pipe"]}).trim(),u=await n({projectRoot:e.projectRoot,epicId:t,nowIso:e.nowIso??new Date().toISOString(),git:s,allowExecutionBranchSwitch:!1,requireProvidedP205Authority:!0,...a?{p205Authority:a}:{}});return u.ok||process.stderr.write(`[Neocortex] ${u.reasonCode}. Epic lifecycle evidence remains fail-closed.
15
- `),u}function fd(e,t){if(e.length!==t.length)return!1;const n=[...t].sort();return[...e].sort().every((i,o)=>i===n[o])}function nl(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 Ti="neocortex:menu:cache";async function gd(e){try{const t=await e.get(Ti);if(!t)return null;const n=JSON.parse(t);return n.version!==Dt||Date.now()-n.cachedAt>Qo?null:n}catch{return null}}async function md(e,t,n){try{const i={instructions:t,metadata:n,cachedAt:Date.now(),version:Dt};await e.set(Ti,JSON.stringify(i),Qo),yd()}catch{}}function yd(){try{Ct(Jo)&&gr(Jo)}catch{}}function Pi(e){return e.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>$r(),()=>$r({strictReadOnly:!0}))}function Cr(e,t){return{status:"refresh-required",reason:e==="expired"||e==="near-expiry"?e:"unavailable",cause:e,action:t}}function ki(e,t=Ur()){const n=xo(e.cause,t);return`${n.summary} Cause: ${e.cause}. ${n.whatToDo}${n.command?` Run: ${n.command}`:""}`}function en(e,t,n){const i="NETWORK_ERROR",o=Ur(),r=Cn(i,o),a=`${e}: ${t}`;return process.stderr.write(_n({...r,whatHappened:`${r.whatHappened} (${a})`},o)),{success:!1,errorCode:i,error:`${r.summary} (${a}) ${r.whatToDo} ${r.command}`,metadata:{...n,connection:{phase:e,reasonCode:t,publicSafe:!0}},exitCode:1}}function tn(e){return e==="transport-error"||e==="timeout"?e:void 0}async function Id(e,t){if(!t)return{schemaVersion:1,outcome:"deferred",reasonCode:"diagnose-auth-not-configured",publicSafe:!0};const n=new vn({serverUrl:e,licenseKey:t,cacheProvider:new Ir({cacheDir:vr,passphrase:t,strictReadOnly:!0}),strictReadOnly:!0,causalAuthRecovery:!0});let i;try{i=await n.inspectToken()}catch{return{schemaVersion:1,outcome:"deferred",reasonCode:"diagnose-auth-refresh-deferred",publicSafe:!0}}if(i.status==="authenticated")return{schemaVersion:1,outcome:"not-needed",reasonCode:"diagnose-auth-already-ready",publicSafe:!0};if(i.status==="not-configured")return{schemaVersion:1,outcome:"deferred",reasonCode:"diagnose-auth-not-configured",publicSafe:!0};if(i.reason!=="expired"&&i.reason!=="near-expiry")return{schemaVersion:1,outcome:"deferred",reasonCode:"diagnose-auth-refresh-not-eligible",publicSafe:!0};const o=new vn({serverUrl:e,licenseKey:t,cacheProvider:new Ir({cacheDir:vr,passphrase:t}),strictReadOnly:!1,causalAuthRecovery:!0});if(await o.forceRefresh())return{schemaVersion:1,outcome:"refreshed",reasonCode:"diagnose-auth-refreshed-before-strict",publicSafe:!0};const a=o.getLastRecoveryResult(),s=a?.status==="refresh-required"?tn(a.cause):void 0;return{schemaVersion:1,outcome:"deferred",reasonCode:"diagnose-auth-refresh-deferred",publicSafe:!0,...s?{connectionFailure:s}:{}}}async function Oi(e,t,n){const i=n.mode==="strict";try{let o;if(i&&t)o=new Ir({cacheDir:vr,passphrase:t,strictReadOnly:!0});else if(i)o=new Ao;else if(t){const d=q(Yr,"cache");o=new Ir({cacheDir:d,passphrase:t})}else process.stderr.write(`[neocortex] Warning: No license key in config. Run "neocortex activate" to re-authenticate.
16
- `),o=new Ao;const r=Vo(n,o,"auth-cache"),a=Vo(n,o,"tier-cache"),s=new vn({serverUrl:e,licenseKey:t??"",cacheProvider:r,strictReadOnly:i,causalAuthRecovery:!0});let u;if(i){const d=await s.inspectToken();if(d.status==="refresh-required"){const h=d.reason==="unavailable"?"store-unavailable":d.reason;return Cr(h,h==="expired"||h==="near-expiry"?"prepare":"retry-later")}if(d.status==="not-configured")return d;u=d.token}else u=await s.getToken();if(!u){if(!t)return{status:"not-configured"};const d=s.getLastRecoveryResult();return d?.status==="refresh-required"&&d.cause!=="valid"&&d.cause!=="not-configured"||d?.status==="uncertain"?Cr(d.cause,d.action):Cr("store-unavailable","retry-later")}const g=new Pa({cacheProvider:a,licenseClient:s});return{status:"authenticated",token:u,client:s,tierClient:g}}catch{return t?Cr("store-unavailable","retry-later"):{status:"not-configured"}}}let Ni=!1;const Ed=/^(?:(?:private-execution|story-worktree|planning-root|architecture-root|unclassified-invoke)[a-z0-9-]*|PRIVATE_EXECUTION_[A-Z0-9_]+|ORCHESTRATION_ERROR)$/,qn=/^[a-z0-9][a-z0-9._-]{0,127}$/,Sd=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function vd(e){if(!f(e))return;const t=e.error_code;if(typeof t!="string")return;const n=Hr(e.semanticGateRemediation),i=Sd.test(t)&&n?.reasonCode===t;if(!Ed.test(t)&&!i)return;const o={error_code:t};for(const a of["reason_code","fallback_action","next_action"]){const s=e[a];typeof s=="string"&&qn.test(s)&&(o[a]=s)}n&&(o.semanticGateRemediation=n);const r=e.epic_claim_recovery;return f(r)&&r.schemaVersion===1&&r.kind==="create-epic-claim-replay"&&typeof r.claimId=="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(r.claimId)&&typeof r.epicId=="string"&&/^P[1-9][0-9]{0,11}$/.test(r.epicId)&&r.nextAction==="reinvoke-same-command"&&r.publicSafe===!0&&(o.epic_claim_recovery={schemaVersion:1,kind:"create-epic-claim-replay",claimId:r.claimId,epicId:r.epicId,nextAction:"reinvoke-same-command",publicSafe:!0}),o}function Cd(e){if(!f(e)||e.schemaVersion!==1||typeof e.claimId!="string"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(e.claimId)||typeof e.epicId!="string"||!/^P[1-9][0-9]{0,11}$/.test(e.epicId)||e.nextAction!=="reinvoke-same-command"||e.persisted!==!0||e.publicSafe!==!0)return;const t=typeof e.reasonCode=="string"&&qn.test(e.reasonCode)?e.reasonCode:void 0,n=typeof e.fallbackAction=="string"&&qn.test(e.fallbackAction)?e.fallbackAction:void 0;return{...t?{reason_code:t}:{},...n?{fallback_action:n}:{},next_action:"reinvoke-same-command",claim_recovery:{epic_id:e.epicId,persisted:!0,public_safe:!0}}}function _d(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 Di=3,rn=50;function wd(e){return new Promise(t=>setTimeout(t,e))}function Rd(e,t,n){return e.status>=500&&e.status<=599?!0:n&&e.status===409&&t.error_code==="SIGNATURE_REPLAYED"}async function _r(e,t,n,i,o={}){const r=Math.max(1,Math.min(o.maxAttempts??Di,Di)),a=o.sleep??wd;let s=i,u=!1,g=!1,d=0;for(let h=1;h<=r;h+=1){const l=Math.max(Math.floor(Date.now()/1e3),d+1);d=l;const E=Ad(t,n,s,{nowSeconds:l}),_=new AbortController,w=setTimeout(()=>_.abort(),Xo);try{const S=await fetch(`${e}${t}`,{method:"POST",headers:E.headers,body:E.body,signal:_.signal});if(o.admitResponseBeforeBodyRead&&!o.admitResponseBeforeBodyRead(S))return{response:S,text:"",parsed:{},responseAdmissionRejected:!0};let y="";try{y=await S.text()}catch(U){if(S.ok)return{text:"",parsed:{},networkFailure:To(U,_.signal.aborted)}}const D=S.ok&&o.deferSuccessfulJsonParsing?{}:(()=>{try{return y?JSON.parse(y):{}}catch{return{}}})();if(S.status===401&&!u&&o.refreshToken&&(D.fallback_action==="refresh_token"||D.fallback_action==="re_authenticate")){u=!0;const U=await o.refreshToken();if(U&&h<r){s=U,o.onTokenChanged?.(U),await a(rn*h);continue}}if(S.status===401&&D.error_code==="SIGNATURE_EXPIRED"&&!g&&h<r){g=!0,await a(rn*h);continue}if(h<r&&Rd(S,D,o.allowReplayRetry===!0)){await a(rn*h);continue}return{response:S,text:y,parsed:D}}catch(S){if(h<r){await a(rn*h);continue}return{text:"",parsed:{},networkFailure:To(S,_.signal.aborted)}}finally{clearTimeout(w)}}return{text:"",parsed:{},networkFailure:"transport-error"}}function Ad(e,t,n,i={}){const o=Buffer.from(JSON.stringify(t),"utf8"),r=Za({method:"POST",target:e,body:o,bearerToken:n,clientVersion:Dt,nowSeconds:i.nowSeconds,nonceBytes:i.nonceBytes});return{body:r.body,headers:{...r.headers,Authorization:`Bearer ${n}`}}}function Li(e){return Le("sha256").update(e).digest("hex")}function bd(){const e=Number(process.env.NEOCORTEX_INVOKE_CHUNK_BYTES??"49152");return Number.isFinite(e)&&e>=1024&&e<=98304?Math.floor(e):49152}function xd(e,t,n){return`args-${Le("sha256").update("invoke-materialization:v1").update(e).update(String(t)).update(JSON.stringify(n)).digest("hex")}`}async function ji(e,t,n,i,o={}){const r=await _r(e,t,n,i,{...o,allowReplayRetry:!0});if(r.networkFailure||!r.response)throw new Error("NETWORK_ERROR: materialization request failed after bounded retries");const{response:a,parsed:s}=r;if(!a.ok){const u=typeof s.error_code=="string"?s.error_code:`HTTP_${a.status}`,g=typeof s.message=="string"?s.message:"materialization upload failed";throw new Error(`${u}: ${g}`)}return s}async function Td(e,t,n,i){const o=Buffer.from(t,"utf8"),r=bd(),a=[];for(let _=0,w=0;_<o.byteLength;_+=r,w++){const S=o.subarray(_,Math.min(_+r,o.byteLength));a.push({index:w,sha256:Li(S),byteLength:S.byteLength})}const s=Li(o),u=xd(s,o.byteLength,a),g=Number(process.env.NEOCORTEX_INVOKE_CHUNK_TTL_SECONDS??"900");let d=n;const h={refreshToken:i,onTokenChanged(_){d=_}};for(const _ of a){const w=_.index*r,S=o.subarray(w,w+_.byteLength);await ji(e,"/api/v1/invoke/materialization/chunks",{manifestId:u,index:_.index,sha256:_.sha256,byteLength:_.byteLength,contentBase64:S.toString("base64"),ttlSeconds:g,idempotencyKey:`${u}:${_.index}:${_.sha256}`},d,h)}const E=(await ji(e,"/api/v1/invoke/materialization/manifests",{manifestId:u,sha256:s,byteLength:o.byteLength,chunkCount:a.length,chunks:a,ttlSeconds:g,retry:{attempt:1,budget:3,idempotencyKey:u}},d,h)).argsRef;if(!E?.manifestId)throw new Error("MATERIALIZATION_RESPONSE_INVALID: missing argsRef");return{argsRef:E,chunks:a}}function cr(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function Pd(...e){const t=new Set,n=[];for(const i of e)for(const o of i??[]){const r=ue(o);if(!(!r||t.has(r))&&(t.add(r),n.push(r),n.length>=16))return n}return n}function kd(e){const t=e.graphRetrieval;if(!f(t))return{accepted:!1,itemCount:0};const n=Array.isArray(t.items)?t.items.length:0;return{accepted:n>0||typeof t.retrievalId=="string"||t.accepted===!0,itemCount:n}}function Kn(e,t=cr(e),n=[],i={}){const o=e.stateSnapshot.scope,r=Object.keys(e.stateSnapshot.stories).length,a=Object.keys(e.stateSnapshot.epics).length,s=o?.kind??"full";return{schemaVersion:1,payloadBytes:t,limitBytes:i.limitBytes??ei,warningThresholdBytes:i.warningThresholdBytes??xn,scope:{kind:s,...o?.projectionMode?{projectionMode:o.projectionMode}:{},commandId:o?.commandId??null,stateProjectionPolicy:o?.stateProjectionPolicy??null},includedStories:o?.includedStoryCount??r,omittedStories:o?.omittedStoryCount??0,includedEpics:o?.includedEpicCount??a,omittedEpics:o?.omittedEpicCount??0,graphRetrieval:kd(e.stateSnapshot),reasonCodes:Pd(n,o?.reasonCodes),publicSafe:!0}}function Od(e){const t=f(e.budget)?e.budget:void 0,n=typeof t?.maxPayloadBytes=="number"&&Number.isFinite(t.maxPayloadBytes)?t.maxPayloadBytes:12*1024;return Math.max(1024,Math.min(n,12*1024))}function Nd(e){return f(e)?{stableId:ue(e.stableId)??"unknown",...f(e.source)?{source:e.source}:{},reasonCode:"budget_exceeded"}:{stableId:"unknown",reasonCode:"budget_exceeded"}}function Mi(e){const t=Array.isArray(e)?e.filter(n=>typeof n=="string"):[];return t.includes("budget_exceeded")?t:[...t,"budget_exceeded"]}function Dd(e){const t=e.graphRetrieval;if(!f(t)||!Array.isArray(t.items))return e;const n=Od(t);let i=[...t.items],o=Array.isArray(t.skipped)?[...t.skipped]:[],r=t;for(;Buffer.byteLength(JSON.stringify(r),"utf8")>n&&i.length>0;){const a=i.pop();o=[...o,Nd(a)].slice(-32),r={...t,items:i,skipped:o,warnings:Mi(t.warnings)}}return Buffer.byteLength(JSON.stringify(r),"utf8")>n&&(r={...t,query:typeof t.query=="string"?t.query.slice(0,240):t.query,items:[],skipped:[],warnings:Mi(t.warnings)}),r===t?e:{...e,graphRetrieval:r}}function Jn(e,t={}){const n=t.limitBytes??ei,i=t.warningThresholdBytes??Math.floor(n*ti),o=cr(e);if(o<n)return{body:e,degraded:!1,telemetry:Kn(e,o,["payload-within-limit"],{limitBytes:n,warningThresholdBytes:i})};let r={...e,stateSnapshot:Ma(e.stateSnapshot)},a=["payload-size-guardrail","state-degraded"],s=cr(r);s>=n&&(r={...r,stateSnapshot:Dd(r.stateSnapshot)},a=[...a,"graph-retrieval-budget-enforced"],s=cr(r));const u=Kn(r,s,a,{limitBytes:n,warningThresholdBytes:i});if(s>=n){const g=r.stateSnapshot.scope?.projectionMode;throw g==="yolo-story"||g==="yoloop-target"||g==="yoloop-session"||g==="yoloop-discovery"||g==="structural-required"?new Vn(u):new Mn(u)}return{body:r,degraded:!0,telemetry:u}}function Vi(e){const t=e.stateSnapshot.scope?.commandId??"resolved-command";return e.args!==void 0?t:`${t}:argsRef`}function Ld(e){const t=cr(e);if(t<xn)return t;const n=Kn(e,t,["payload-warning-threshold"]);return process.stderr.write(`[Neocortex] invoke payload near server limit: trigger=${Vi(e)} scope=${n.scope.kind} mode=${n.scope.projectionMode??n.scope.kind} payloadBytes=${n.payloadBytes} limit=${n.limitBytes} includedStories=${n.includedStories} omittedStories=${n.omittedStories} includedEpics=${n.includedEpics} omittedEpics=${n.omittedEpics} graphRetrieval.accepted=${n.graphRetrieval.accepted} graphRetrieval.itemCount=${n.graphRetrieval.itemCount} reasonCodes=${n.reasonCodes.join(",")||"none"}
17
- `),t}function Bi(e,t){process.stderr.write(`[Neocortex] invoke payload guardrail: trigger=${Vi(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"}
18
- `)}async function jd(e){const t=Fa(e.args,{platformTarget:e.platformTarget,environment:e.environment??process.env});if(t.action==="skipped")return{shouldContinue:!0,attachToRequest:Md(t),metadata:$i(t)};const n=e.bootstrapper??Ya;let i;try{i=await n({projectRoot:e.projectRoot,env:e.environment??process.env,effectAuthority:e.effectAuthority})}catch{i={ok:!1,attempted:!0,installed:!1,started:!1,cached:!1,projectKey:"unknown",reasonCodes:[za.UNEXPECTED_ERROR],publicSummary:"runner scheduler bootstrap stopped unexpectedly.",publicSafe:!0}}const o=$i(t,i);if(i.ok)return{shouldContinue:!0,attachToRequest:!0,metadata:o};const r=o.reasonCodes.slice(0,5).join(",");return t.failurePolicy==="fail-open"?{shouldContinue:!0,attachToRequest:!0,metadata:{...o,failOpenWarning:!0},warning:`Runner auto-bootstrap warning (${r}); continuing fail-open for operator command.`}:{shouldContinue:!1,attachToRequest:!1,metadata:o,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 Md(e){return!e.reasonCodes.includes(Wa.SKIPPED_NON_CONTINUITY_COMMAND)}function $i(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:ze([...e.reasonCodes,...t?.reasonCodes??[]]),publicSummary:t?.publicSummary??e.publicSummary,publicSafe:!0}}function ze(e){return Array.from(new Set(e.map(t=>t.slice(0,120))))}function nn(e,t,n){const i=Math.floor(e??t);return Number.isFinite(i)?Math.max(1,Math.min(n,i)):t}function on(e,t){const n=process.env[e];if(!n)return t;const i=Number(n);return Number.isFinite(i)?i:t}function J(e,t=li){const n=typeof e=="string"&&e.trim().length>0?e.trim():"unknown",i=nt(n,t),o=bs.test(i)?Lt:i;return o.length<=t?o:`${o.slice(0,t)}\u2026[TRUNCATED:${o.length-t}]`}function Qn(e,t=li){if(!(typeof e!="string"||e.trim().length===0))return J(e,t)}function Xn(e,t,n,i){const o=Qn(e?.targetId??t,120),r=e?.selectorKind??(o?eo(o):void 0),a=(e?.relatedJobIds??[]).map(s=>Qn(s,120)).filter(s=>!!s);return{schemaVersion:1,contractVersion:"continuity-v1",targetResolutionState:n,...r?{targetKind:r}:{},...o?{targetId:o}:{},...t?{targetJobId:J(t,120)}:{},...e?.jobId?{jobId:J(e.jobId,120)}:{},...e?.goalId?{goalId:J(e.goalId,120)}:{},...e?.loopId?{loopId:J(e.loopId,120)}:{},...a.length>0?{relatedJobIds:a}:{},relatedJobCount:a.length,reasonCodes:ze(i.length>0?i:[K.OK]),publicSafe:!0}}function bt(e,t,n,i,o=[]){const r=(e?.redactions?.length??0)>0,a=e?r?"unsafe":n&&i===0?"empty":"available":"unavailable",s=Qn(t[t.length-1]?.eventId,120),u=o.length>0?o:a==="unavailable"?[K.WATCH_SNAPSHOT_UNAVAILABLE]:a==="empty"?[K.WATCH_NO_SUMMARIES_YET]:[K.OK];return{schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:a,...e?.generatedAt?{generatedAt:J(e.generatedAt,80)}:{},renderedSummaryCount:i,...s?{latestEventId:s}:{},reasonCodes:ze(u),publicSafe:!0}}function lt(e,t,n,i,o=[],r){const a=i[i.length-1],s=n??a?.cursor,u=!!(s&&s!==t&&i.length>0),g=r??(u?"advanced":t||s?"unchanged":"not_started"),d=o.length>0?o:g==="advanced"?[K.WATCH_CURSOR_ADVANCED]:g==="unavailable"?[K.WATCH_EVIDENCE_UNAVAILABLE]:[K.WATCH_CURSOR_UNCHANGED];return{schemaVersion:1,contractVersion:"continuity-v1",cursorState:g,...e?{initialCursor:J(e,200)}:{},...t?{currentCursor:J(t,200)}:{},...s?{nextCursor:J(s,200)}:{},cursorAdvanced:u,...a?.eventId?{eventId:J(a.eventId,120)}:{},reasonCodes:ze(d),publicSafe:!0}}function ht(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:ze([...e.reasonCodes??[],...t?.reasonCodes??[],...e.snapshotEvidence?.reasonCodes??[],...e.cursorEvidence?.reasonCodes??[]]),generatedAt:J(e.generatedAt??new Date().toISOString(),80),publicSafe:!0}}function Vd(e){const t=e.targetKind&&e.targetId?`${e.targetKind}/${e.targetId}`:e.targetId??"[unresolved]",n=e.snapshotEvidence?.renderedSummaryCount??0,i=e.targetEvidence?.relatedJobCount??0,o=e.cursorEvidence?.cursorState??"unavailable",r=e.cursorEvidence?.currentCursor??"[none]",a=e.cursorEvidence?.nextCursor??"[none]",s=e.snapshotEvidence?.snapshotStatus??"not_requested",u=e.snapshotEvidence?.generatedAt??e.generatedAt;return[`[watch-status] ${e.targetResolutionState==="unresolved"||e.stopReason==="target_unresolved"?"unresolved-target":n===0&&(e.watchStatus==="waiting"||e.watchStatus==="active")?"no-new-summary":e.watchStatus==="stopped"?"stopped":"lifecycle"}`,`status=${e.watchStatus}`,`active=${e.active}`,`target=${t}`,`resolution=${e.targetResolutionState??"unavailable"}`,`relatedJobs=${i}`,`summaries=${n}`,`snapshot=${s}`,`generatedAt=${u}`,`cursor=${o}`,`current=${J(r,200)}`,`next=${J(a,200)}`,`advanced=${e.cursorEvidence?.cursorAdvanced??!1}`,`stop=${e.stopReason??"not_stopped"}`,`reasons=${e.reasonCodes.join(",")}`].join(" ")}function ft(e,t,n,i=!1){if(i){const o={type:"watch_status",watchStatus:e.watchStatus,active:e.active,renderedSummaryCount:e.snapshotEvidence?.renderedSummaryCount??0,stopReason:e.stopReason??"not_stopped",protectedProjection:!0,publicSafe:!0};n.write(t==="json"?`${JSON.stringify(o)}
19
- `:`[watch-status] status=${o.watchStatus} active=${o.active} summaries=${o.renderedSummaryCount} stop=${o.stopReason}
10
+ `)}}function Wn(e){return/docs\/epics\/epic-(P[1-9][0-9]*)\.md\b/.exec(e)?.[1]??/docs\/stories\/(P[1-9][0-9]*)\.[0-9]+\.story\.md\b/.exec(e)?.[1]}function ad(e,t={},n={},o){const i=d=>{try{return String(Ae("git",[...d],{cwd:e,stdio:["ignore","pipe","ignore"],timeout:1e4,encoding:"utf8"})).trim()}catch{return}};if(i(["rev-parse","--is-inside-work-tree"])!=="true")return;const r=[],a=Object.entries(t).sort(([d],[h])=>+(h===o)-+(d===o));for(const[d,h]of a){if(r.length>=id)break;if(!f(h)||!f(h.origin_binding))continue;const l=h.execution_branch,E=h.origin_binding;if(typeof l!="string"||E.executionBranch!==l||typeof E.originHeadSha!="string"||!/^[a-f0-9]{40,64}$/.test(E.originHeadSha)||!/^[A-Za-z0-9][A-Za-z0-9._/-]{0,239}$/.test(l)||l.includes(".."))continue;const v=i(["rev-parse","--verify","--quiet",`refs/heads/${l}^{commit}`]);if(!v||!/^[a-f0-9]{40,64}$/.test(v)||i(["merge-base","--is-ancestor",E.originHeadSha,v])===void 0)continue;const w=[];for(const S of Object.values(n)){if(w.length>=128)break;if(!f(S)||(S.epic_id??S.epic)!==d)continue;const y=f(S.checkpoint)&&typeof S.checkpoint.headSha=="string"?S.checkpoint.headSha:f(S.scheduling_checkpoint_evidence)&&typeof S.scheduling_checkpoint_evidence.headSha=="string"?S.scheduling_checkpoint_evidence.headSha:void 0;!y||!/^[a-f0-9]{40,64}$/.test(y)||w.includes(y)||i(["merge-base","--is-ancestor",y,v])!==void 0&&w.push(y)}r.push(Object.freeze({epicId:d,executionBranch:l,originHeadSha:E.originHeadSha,executionHeadSha:v,...w.length>0?{containedHeadShas:Object.freeze(w)}:{}}))}const s=i(["ls-files","--error-unmatch","--",".neocortex/state.json"])!==void 0,u=s?void 0:Yc({projectRoot:e}),g=u===void 0?void 0:u.ok?u.mode==="runtime-store"?"runtime-store":void 0:u.reasonCode==="governance-tracking-ambiguous"?"ambiguous":void 0;return Object.freeze({schemaVersion:1,stateFileTracked:s,...r.length>0?{executionBases:Object.freeze(r)}:{},...g?{governanceMode:g,governanceCapability:Gr.STORY_GOVERNANCE_RUNTIME_STORE}:{}})}function bo(e){return typeof e=="string"&&nd.has(e)}function Fn(e,t={}){const n=J(e,".neocortex","state.json"),o=Ct(n),i=o?void 0:xo(e,{epicAware:!0});if(!o&&i===void 0)throw new ut("git-lifecycle-state-missing");let r;try{r=JSON.parse(i??Ue(n,"utf8"))}catch{throw new ut("git-lifecycle-state-corrupt")}if(!f(r)||!f(r.epics)||!f(r.stories))throw new ut("git-lifecycle-state-shape-invalid");const a=Object.values(r.epics).some(s=>f(s)&&(s.branch_mode==="epic"||_e(s.execution_branch)!==void 0));if(a)try{ar(e,{required:!0})}catch(s){const u=s instanceof Error&&/^git-lifecycle-/.test(s.message)?s.message:"git-lifecycle-runtime-invalid";if(t.allowMissingRuntime&&o&&u==="git-lifecycle-runtime-missing")return{lifecycleDeclared:!0,runtimeMissing:!0};throw new ut(u)}return{lifecycleDeclared:a,runtimeMissing:!1}}function xo(e,t){const n=qc(e);if(!n.ok){if(t.epicAware&&!t.projectless)throw new ut(n.reasonCode);return}return n.value?.toString("utf8")}const cd=256,sd=/^[A-Za-z0-9][A-Za-z0-9_-]{7,95}$/,dd=/^[a-f0-9]{64}$/;function pd(e){const t=Date.now(),n={};for(const o of Object.values(e.storyWorktrees?.entries??{})){if(!f(o)||o.state!=="active")continue;const{epicId:i,storyId:r,leaseId:a,graphRevision:s,expiresAt:u}=o;typeof i!="string"||typeof r!="string"||!r.startsWith(`${i}.`)||typeof a!="string"||!sd.test(a)||typeof s!="string"||!dd.test(s)||typeof u!="string"||!(Date.parse(u)>t)||(n[i]??=[]).push({schemaVersion:1,storyId:r,leaseId:a,graphRevision:s,expiresAt:u})}for(const[o,i]of Object.entries(n))i.length>cd?delete n[o]:i.sort((r,a)=>String(r.storyId).localeCompare(String(a.storyId))||String(r.leaseId).localeCompare(String(a.leaseId)));return n}function Zr(e,t={}){const n=J(e,".neocortex","state.json"),o=Ct(n)?void 0:xo(e,t);if(!Ct(n)&&o===void 0){if(t.epicAware&&!t.projectless)throw new ut("git-lifecycle-state-missing");return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}let i,r,a={};try{const S=o??Ue(n,"utf-8");r=je("sha256").update(S).digest("hex");const y=Wa(e,r)??JSON.parse(S),N=f(y.epics)?y.epics:{},$=Object.values(N).some(re=>f(re)&&(re.branch_mode==="epic"||_e(re.execution_branch)!==void 0)),b=ar(e,{required:!!(t.epicAware&&$&&!t.projectless)});i=Tn(y,b),a=pd(b);const _=f(i.stories)?i.stories:{},A=f(i.epics)?i.epics:{},K=f(y.stories)?y.stories:{};for(const[re,Z]of Object.entries(_)){const j=f(Z)?Z:void 0;if(!j?.checkpoint)continue;const ae=typeof j.epic_id=="string"?j.epic_id:re.split(".")[0],ve=f(A[ae])?A[ae]:void 0,be=_e(ve?.execution_branch);if(!be)continue;const T=Dc(e,j.checkpoint,re,ae,be,t.p205Authorities?.[re],Yi(re,j,f(j.checkpoint)?j.checkpoint:void 0));if(T.kind==="integration-authorized")j.checkpoint_verification=T.verification,delete j.scheduling_checkpoint_evidence;else if(T.kind==="scheduling-only")j.scheduling_checkpoint_evidence=T.evidence,delete j.checkpoint,delete j.checkpoint_verification;else if(T.kind==="rejected"){j.checkpoint_verification=T.verification,delete j.scheduling_checkpoint_evidence;const ne=f(K[re])?K[re]:void 0;if(delete j.checkpoint,b.stories[re]?.checkpoint!==void 0)for(const Ce of["status","last_step","steps_completed"])ne&&Object.prototype.hasOwnProperty.call(ne,Ce)?j[Ce]=structuredClone(ne[Ce]):delete j[Ce];["done","completed","merged"].includes(String(j.status).toLowerCase())&&(j.status="blocked")}}}catch(S){if(t.epicAware&&!t.projectless){const y=S instanceof Error&&/^git-lifecycle-/.test(S.message)?S.message:"git-lifecycle-state-corrupt";throw new ut(y)}return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}try{const S=Bs(i);S.length>0&&$s(S)}catch{}const s=i.config??i.project??{},u=i.stories??{},g={};for(const[S,y]of Object.entries(u)){const N=f(y.review_request)&&y.review_request.kind==="git-pull-request"?Xs(y.review_request):Gn(y.review_request);g[S]={id:y.id??S,title:y.title,epic_id:y.epic_id,status:y.status??"backlog",...yo(y.source)?{source:yo(y.source)}:{},steps_completed:y.steps_completed??[],last_step:y.last_step??null,branch_name:y.branch_name??null,pr_number:y.pr_number,...Xr(y.branch_mode)?{branch_mode:Xr(y.branch_mode)}:{},...So(y.checkpoint)?{checkpoint:So(y.checkpoint)}:{},...vo(y.checkpoint_verification)?{checkpoint_verification:vo(y.checkpoint_verification)}:{},...Co(y.scheduling_checkpoint_evidence)?{scheduling_checkpoint_evidence:Co(y.scheduling_checkpoint_evidence)}:{},...N?{review_request:N}:{},...Gn(y.rollback_receipt)?{rollback_receipt:Gn(y.rollback_receipt)}:{},...jt(y.workflow_issue)?{workflow_issue:jt(y.workflow_issue)}:{},...rd(y),...Array.isArray(y.depends_on)?{depends_on:mo(y.depends_on)}:{},files_to_modify:ge(y.files_to_modify),...typeof y.artifact_sha256=="string"&&/^[a-f0-9]{64}$/.test(y.artifact_sha256)?{artifact_sha256:y.artifact_sha256}:{},...zs(y),...Io(y.supersededBy)?{supersededBy:Io(y.supersededBy)}:{},risk:typeof y.risk=="string"?y.risk:void 0,blast_radius:typeof y.blast_radius=="number"?y.blast_radius:void 0}}const d=i.epics??{},h={};for(const[S,y]of Object.entries(d)){const N=Us(y.lifecycle_classification),$=Fs(y.createEpicPlanning,S),b=$.checkpoint;let _,A,K,re;if(b&&f(y.createEpicPlanningClaim)&&typeof y.createEpicPlanningClaim.claimId=="string"&&f(y.createEpicPlanningPhysical))try{_i(i,y.createEpicPlanningClaim.claimId,S,!0),_=JSON.parse(JSON.stringify(y.createEpicPlanningPhysical))}catch{}if(_&&f(y.createEpicPlanningClaim)&&typeof y.createEpicPlanningClaim.claimId=="string"&&f(y.createEpicPlanningResearchPhysical))try{wi(i,y.createEpicPlanningClaim.claimId,S),A=JSON.parse(JSON.stringify(y.createEpicPlanningResearchPhysical))}catch{}if(t.verifyPlanningGeneration&&b&&y.status==="generated"&&f(y.createEpicPlanningClaim)&&typeof y.createEpicPlanningClaim.claimId=="string"&&f(y.createEpicPlanningGenerationPhysical))try{if(Aa(e,y.createEpicPlanningClaim.claimId,S).stateSha256!==r)throw new Error("planning-generation-snapshot-raced");K=JSON.parse(JSON.stringify(y.createEpicPlanningGenerationPhysical)),_=JSON.parse(JSON.stringify(y.createEpicPlanningPhysical)),A=JSON.parse(JSON.stringify(y.createEpicPlanningResearchPhysical))}catch{}if(K&&f(y.createEpicPlanningClaim)&&typeof y.createEpicPlanningClaim.claimId=="string")try{const Z=Ri(e,y.createEpicPlanningClaim.claimId,S);if(Z.stateSha256!==r)throw new Error("planning-memory-snapshot-raced");re=JSON.parse(JSON.stringify(Z))}catch{}h[S]={id:y.id??S,title:y.title,...b?{createEpicPlanning:b}:{},...$.diagnostic?{createEpicPlanningProjection:$.diagnostic}:{},..._?{createEpicPlanningPhysical:_}:{},...A?{createEpicPlanningResearchPhysical:A}:{},...K?{createEpicPlanningGenerationPhysical:K}:{},...re?{createEpicPlanningMemoryPhysical:re}:{},status:y.status,stories:y.stories,total_stories:y.total_stories,completed_stories:y.completed_stories,depends_on:mo(y.depends_on),...Xr(y.branch_mode)?{branch_mode:Xr(y.branch_mode)}:{},..._e(y.execution_branch)?{execution_branch:_e(y.execution_branch)}:{},..._e(y.origin_branch)?{origin_branch:_e(y.origin_branch)}:{},...Eo(y.branch_lease)?{branch_lease:Eo(y.branch_lease)}:{},...Hn(y.origin_binding)?{origin_binding:Hn(y.origin_binding)}:{},...wo(y.aggregate_qa_receipt)?{aggregate_qa_receipt:wo(y.aggregate_qa_receipt)}:{},...Ro(y.head_reconciliation_receipt)?{head_reconciliation_receipt:Ro(y.head_reconciliation_receipt)}:{},...Gc(y.story_worktree_evidence)?{story_worktree_evidence:Fc(y.story_worktree_evidence,S,t.publishedStoryReconciliations)}:{},...(a[S]?.length??0)>0?{story_worktree_leases:structuredClone(a[S])}:{},...(Z=>Z?{branch_mode_conversion_receipt:Z}:{})(Qs(y.branch_mode_conversion_receipt)),...jt(y.pr_number)?{pr_number:jt(y.pr_number)}:{},...ue(y.physicalMergeStatus)?{physicalMergeStatus:ue(y.physicalMergeStatus)}:{},...x(y.graph_revision)?{graph_revision:x(y.graph_revision)}:{},...Ao(y.terminal_git_receipt)?{terminal_git_receipt:Ao(y.terminal_git_receipt)}:{},...N?{lifecycle_classification:N}:{},...(Z=>Z?{p205_authority_diagnostic:Z}:{})(fd(t.p205AuthorityDiagnostics,S))}}const l=td(i.current_session??i.currentSession),E=f(i.archPlan)?Jr(i.archPlan.execution):void 0,v=i.epic_id_ledger,w=Array.isArray(v?.reserved_ids)?[...new Set(v.reserved_ids.filter(S=>typeof S=="string"&&/^P\d+$/.test(S)))].slice(0,2048):[];return{schema_version:typeof i.schema_version=="number"?i.schema_version:void 0,config:{project_name:s.project_name??s.name??"unknown",default_branch:s.default_branch??"main",language:s.language??"pt-BR",yolo_mode:s.yolo_mode,user_name:s.user_name,worktree_base:s.worktree_base,max_parallel_stories:s.max_parallel_stories,project_id:typeof s.project_id=="string"?s.project_id:void 0},stories:g,epics:h,...w.length>0?{epic_id_ledger:{schema_version:1,reserved_ids:w}}:{},...l?{current_session:l}:{},...E?{archPlan:{execution:E}}:{}}}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"]],Yn="6a41a47ff2521f80c2296ed811b0f0b304c54750",qn="dbc6d4670b2b7868a01973b1240e24589f1c5b7d",To="30dccfff07f9c969be11ae1d28e62a09731a0768";function ud(e,t){try{const n=t.indexOf(To);if(n<1||t[n-1]!==Yn)return new Map;const o=Ae("git",["show","--no-patch","--format=%P",To],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim(),i=Ae("git",["show","--no-patch","--format=%P",qn],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim();if(o!==`${Yn} ${qn}`||i!==`${zn.at(-1)[1]} ${Yn}`)return new Map;const r=Ae("git",["rev-list","--first-parent","--reverse",qn],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
11
+ `),a=new Map;let s=-1;for(const[u,[g,d]]of zn.entries()){const h=r.indexOf(d);if(h<=s)return new Map;s=h,a.set(g,{headSha:d,position:u-zn.length})}return a}catch{return new Map}}function ld(e){return e instanceof Error&&(Vc(e.message)||/^(?:p205|git-lifecycle)-[a-z0-9-]+$/.test(e.message))?e.message:"p205-transient-execution-failed"}const Po="p205-authority-epic-order-mismatch";function hd(e,t){const n=new Set(e),o=[...t].sort((h,l)=>h.position-l.position),i=o.map(h=>h.storyId),r=new Set(i),a=e.length-n.size+(i.length-r.size),s=[...n].filter(h=>!r.has(h)).length,u=[...r].filter(h=>!n.has(h)).length,g=new Map(o.map(h=>[h.storyId,h.position]));let d=0;for(const h of o)for(const l of new Set(h.dependsOn)){const E=g.get(l);E!==void 0&&l!==h.storyId&&E>=h.position&&(d+=1)}return a===0&&s===0&&u===0&&d===0?{ok:!0,order:i}:{ok:!1,reasonCode:Po,counts:{listed:e.length,physical:i.length,missing:s,extra:u,duplicates:a,dependencyViolations:d}}}function fd(e,t){const n=e?.find(r=>r.epicId===t);if(!n||n.reasonCode!==Po)return;const o=r=>Number.isInteger(r)&&r>=0?Math.min(r,4096):0,{counts:i}=n;return{reasonCode:n.reasonCode,counts:{listed:o(i.listed),physical:o(i.physical),missing:o(i.missing),extra:o(i.extra),duplicates:o(i.duplicates),dependencyViolations:o(i.dependencyViolations)}}}function gd(e){const t=e?.depends_on;return Array.isArray(t)?t.filter(n=>typeof n=="string"&&/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(n)).slice(0,256):[]}async function sl(e,t,n){return(await ko(e,t,n)).authorities}async function ko(e,t,n,o={}){const i=[],r={},a=[],s=await md(e,t,n,i,r,a),u=a.at(-1);return{authorities:s,diagnostics:i,epicAuthorities:r,...u?{failureReasonCode:u}:{}}}async function md(e,t,n,o,i,r){if(!bo(n))return{};if(n==="audit"||n==="yoloop")return{};if(Oi(t,n))return{};try{const a=JSON.parse(Ue(J(e,".neocortex","state.json"),"utf8")),s=ar(e,{required:!0}),u=Tn(a,s),g=f(u.stories)?u.stories:{},d=f(u.epics)?u.epics:{},h=Ae("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8"}).trim(),l=Ae("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8"}).trim(),E=Ae("git",["rev-list","--first-parent","--reverse",h],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
12
+ `).filter(Boolean),v=new Map(E.map((T,ne)=>[T,ne])),w=ud(e,E),S=t.match(/(?:^|\s)@?docs\/stories\/([A-Za-z][A-Za-z0-9._-]*)\.story\.md(?:\s|$)/)?.[1],y=n==="yoloop"?t.match(/(?:^|[\s/@])epic-(P[1-9][0-9]*)\.md(?:\s|$)/i)?.[1]?.toUpperCase():void 0,N=new Set,$=Object.entries(g).flatMap(([T,ne])=>{if(S&&T!==S)return[];const Ce=f(ne)?ne:void 0,xe=f(Ce?.checkpoint)?Ce.checkpoint:void 0;if(!xe)return[];const ce=typeof Ce?.epic_id=="string"?Ce.epic_id:T.split(".")[0];if(y&&ce!==y)return[];const V=x(xe?.headSha),Ke=ce==="P222"?w.get(T):void 0,me=v.get(V??"")??(Ke&&Ke.headSha===V?Ke.position:void 0);if(!V||V.length<40||me===void 0)return N.add(ce),[];const B=f(d[ce])?d[ce]:void 0;if(B?.branch_mode!=="epic"||_e(B.execution_branch)!==l||_e(xe.branch)!==l)return N.add(ce),[];const ye=x(xe.graphRevision);if(!ye||ye.length!==64)return N.add(ce),[];const gt=x(xe.claimRevision),et=[...Yi(T,Ce,xe)].sort(),fe=zc(e,xe,T,ce,l,et);if(!fe&&gt){if(et.length===0)return N.add(ce),[];const D=Ae("git",["diff-tree","--no-commit-id","--name-only","-r","-z",V],{cwd:e,encoding:"utf8"}).split("\0").filter(Boolean),H=$c(T,et).map(k=>[...k].sort()).find(k=>gt===je("sha256").update(k.join("\0")).digest("hex")||gt===je("sha256").update(JSON.stringify(k)).digest("hex"));if(!H)return N.add(ce),[];let Ye=[];if(xe.rootMemoryEffect!==void 0)try{Ye=Jc(e,xe.rootMemoryEffect,{storyId:T,executionBranch:l,baseSha:String(xe.baseSha),headRef:V,childPaths:H}).files.map(k=>k.path)}catch{return N.add(ce),[]}if(D.length===0||D.some(k=>!H.some(le=>Uc(le,k))&&!Ye.includes(k)))return N.add(ce),[]}else if(!fe)return N.add(ce),[];return ye?.length===64?[{storyId:T,epicId:ce,graphRevision:ye,checkpointHead:V,position:me,dependsOn:gd(Ce)}]:[]}),b=new Set(N),_=[];for(const[T,ne]of Object.entries(d)){const Ce=f(ne)?ne:void 0,xe=Array.isArray(Ce?.stories)?Ce.stories.filter(ye=>typeof ye=="string"):Object.keys(g).filter(ye=>ye.startsWith(`${T}.`)),ce=$.filter(ye=>ye.epicId===T);if(ce.length===0||b.has(T))continue;const V=new Set(ce.map(ye=>ye.storyId)),Ke=xe.filter(ye=>V.has(ye)),me=hd(Ke,ce);if(me.ok){_.push(...me.order);continue}b.add(T),o.push({epicId:T,reasonCode:me.reasonCode,counts:me.counts});const{counts:B}=me;process.stderr.write(`[Neocortex] ${me.reasonCode} (listed=${B.listed} physical=${B.physical} missing=${B.missing} extra=${B.extra} duplicates=${B.duplicates} dependencyViolations=${B.dependencyViolations}). Checkpoint projection remains fail-closed.
13
+ `)}const A=new Map(_.map((T,ne)=>[T,ne]));$.sort((T,ne)=>(A.get(T.storyId)??Number.MAX_SAFE_INTEGER)-(A.get(ne.storyId)??Number.MAX_SAFE_INTEGER));const K={},re=[...new Set($.filter(T=>!b.has(T.epicId)).map(T=>T.graphRevision))],Z=n==="finalize-epic"?Kn(t):void 0,j=Z&&f(d[Z])?d[Z]:void 0,ae=x(j?.graph_revision),ve=!!(Z&&j?.branch_mode==="epic"&&ae&&ae.length===64&&!b.has(Z)&&$.some(T=>T.epicId===Z));ve&&!re.includes(ae)&&re.push(ae);let be=new Map;re.length>0&&(be=await Mc(e,{headSha:h,graphRevisions:re}));for(const T of $){if(b.has(T.epicId))continue;const ne=be.get(T.graphRevision);if(!ne)throw new Error("p205-transient-authority-missing");K[T.storyId]=ne}if(ve){const T=be.get(ae);if(!T)throw new Error("p205-transient-authority-missing");i[Z]=T}return await yd({projectRoot:e,commandId:n,targetEpicId:y,currentHead:h,epics:d,candidates:$,authorities:K}),K}catch(a){const s=ld(a);return r.push(s),process.stderr.write(`[Neocortex] ${s}. Checkpoint projection remains fail-closed.
14
+ `),{}}}async function yd(e){if(e.commandId!=="yoloop"||!e.targetEpicId)return;const t=e.epics[e.targetEpicId],n=f(t)?t:void 0,o=f(n?.aggregate_qa_receipt)?n.aggregate_qa_receipt:void 0,i=x(n?.graph_revision);if(!o||!i||i.length!==64||o.schemaVersion!==1||o.evidenceVersion!=="p205-execution-v2"||o.producer!=="local-yolo-tdd"||o.contract!=="P205-CI-02"||o.command!==Sr||o.verdict!=="passed"||o.executionHeadSha!==e.currentHead||o.graphRevision!==i||!Array.isArray(o.gateIds)||o.gateIds.length===0||!o.gateIds.every(h=>typeof h=="string")||typeof o.manifestDigest!="string"||!/^[a-f0-9]{64}$/i.test(o.manifestDigest)||typeof o.resultDigest!="string"||!/^[a-f0-9]{64}$/i.test(o.resultDigest)||typeof o.receiptRef!="string"||!/^local-yolo-tdd:[a-f0-9]{64}$/i.test(o.receiptRef))return;const r=o.gateIds,a=`local-yolo-tdd:${je("sha256").update(["epic-aggregate-p205-execution-v2",Sr,e.currentHead,i,o.manifestDigest,r.join(","),o.resultDigest].join("\0")).digest("hex")}`;if(o.receiptRef!==a)return;const s=e.candidates.find(h=>h.epicId===e.targetEpicId&&h.graphRevision===i&&e.authorities[h.storyId]),u=s?Wc(e.authorities[s.storyId]):void 0;if(!u||u.executionHeadSha!==e.currentHead||u.graphRevision!==i||u.manifestDigest!==o.manifestDigest||!Ed(u.gateIds,r))return;const g=`local-yolo-tdd:${je("sha256").update(["epic-aggregate-p205-execution-v2",Sr,e.currentHead,i,u.manifestDigest,u.gateIds.join(","),u.resultDigest].join("\0")).digest("hex")}`,d=o.receiptRef;await qi(e.projectRoot,h=>{const l=Lc(h,e.targetEpicId),E=f(l.aggregate_qa_receipt)?l.aggregate_qa_receipt:void 0;!E||E.executionHeadSha!==e.currentHead||E.graphRevision!==i||E.receiptRef!==d||(l.aggregate_qa_receipt={schemaVersion:1,evidenceVersion:"p205-execution-v2",producer:"local-yolo-tdd",contract:"P205-CI-02",command:Sr,verdict:"passed",executionHeadSha:e.currentHead,graphRevision:i,manifestDigest:u.manifestDigest,resultDigest:u.resultDigest,checkedAt:u.executedAt,receiptRef:g,gateIds:[...u.gateIds]})})}function Kn(e){return(e.match(/(?:^|[\s/@])epic-(P[1-9][0-9]{0,30})\.md(?:\s|$)/i)?.[1]??e.match(/(?:^|\s)@?(P[1-9][0-9]{0,30})(?:\s|$)/i)?.[1])?.toUpperCase()}async function Id(e){if(e.commandId!=="finalize-epic")return;const t=Kn(e.args);if(!t)return;const{produceEpicLifecycleEvidence:n}=await import("../git/epic-lifecycle-evidence.js"),o=JSON.parse(Ue(J(e.projectRoot,".neocortex","state.json"),"utf8")),i=Tn(o,ar(e.projectRoot,{required:!1})),r=f(i.epics)&&f(i.epics[t])?i.epics[t]:void 0;if(!r||r.branch_mode!=="epic")return;const a=e.epicAuthorities[t],s=async(...g)=>Ae("git",[...g],{cwd:e.projectRoot,encoding:"utf8",maxBuffer:32*1024*1024,stdio:["ignore","pipe","pipe"]}).trim(),u=await n({projectRoot:e.projectRoot,epicId:t,nowIso:e.nowIso??new Date().toISOString(),git:s,allowExecutionBranchSwitch:!1,requireProvidedP205Authority:!0,...a?{p205Authority:a}:{}});return u.ok||process.stderr.write(`[Neocortex] ${u.reasonCode}. Epic lifecycle evidence remains fail-closed.
15
+ `),u}function Ed(e,t){if(e.length!==t.length)return!1;const n=[...t].sort();return[...e].sort().every((o,i)=>o===n[i])}function dl(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 Oo="neocortex:menu:cache";async function Sd(e){try{const t=await e.get(Oo);if(!t)return null;const n=JSON.parse(t);return n.version!==Dt||Date.now()-n.cachedAt>Zi?null:n}catch{return null}}async function vd(e,t,n){try{const o={instructions:t,metadata:n,cachedAt:Date.now(),version:Dt};await e.set(Oo,JSON.stringify(o),Zi),Cd()}catch{}}function Cd(){try{Ct(Xi)&&gr(Xi)}catch{}}function No(e){return e.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>$r(),()=>$r({strictReadOnly:!0}))}function Cr(e,t){return{status:"refresh-required",reason:e==="expired"||e==="near-expiry"?e:"unavailable",cause:e,action:t}}function Do(e,t=Ur()){const n=Ti(e.cause,t);return`${n.summary} Cause: ${e.cause}. ${n.whatToDo}${n.command?` Run: ${n.command}`:""}`}function en(e,t,n){const o="NETWORK_ERROR",i=Ur(),r=Cn(o,i),a=`${e}: ${t}`;return process.stderr.write(_n({...r,whatHappened:`${r.whatHappened} (${a})`},i)),{success:!1,errorCode:o,error:`${r.summary} (${a}) ${r.whatToDo} ${r.command}`,metadata:{...n,connection:{phase:e,reasonCode:t,publicSafe:!0}},exitCode:1}}function tn(e){return e==="transport-error"||e==="timeout"?e:void 0}async function _d(e,t){if(!t)return{schemaVersion:1,outcome:"deferred",reasonCode:"diagnose-auth-not-configured",publicSafe:!0};const n=new vn({serverUrl:e,licenseKey:t,cacheProvider:new Ir({cacheDir:vr,passphrase:t,strictReadOnly:!0}),strictReadOnly:!0,causalAuthRecovery:!0});let o;try{o=await n.inspectToken()}catch{return{schemaVersion:1,outcome:"deferred",reasonCode:"diagnose-auth-refresh-deferred",publicSafe:!0}}if(o.status==="authenticated")return{schemaVersion:1,outcome:"not-needed",reasonCode:"diagnose-auth-already-ready",publicSafe:!0};if(o.status==="not-configured")return{schemaVersion:1,outcome:"deferred",reasonCode:"diagnose-auth-not-configured",publicSafe:!0};if(o.reason!=="expired"&&o.reason!=="near-expiry")return{schemaVersion:1,outcome:"deferred",reasonCode:"diagnose-auth-refresh-not-eligible",publicSafe:!0};const i=new vn({serverUrl:e,licenseKey:t,cacheProvider:new Ir({cacheDir:vr,passphrase:t}),strictReadOnly:!1,causalAuthRecovery:!0});if(await i.forceRefresh())return{schemaVersion:1,outcome:"refreshed",reasonCode:"diagnose-auth-refreshed-before-strict",publicSafe:!0};const a=i.getLastRecoveryResult(),s=a?.status==="refresh-required"?tn(a.cause):void 0;return{schemaVersion:1,outcome:"deferred",reasonCode:"diagnose-auth-refresh-deferred",publicSafe:!0,...s?{connectionFailure:s}:{}}}async function Lo(e,t,n){const o=n.mode==="strict";try{let i;if(o&&t)i=new Ir({cacheDir:vr,passphrase:t,strictReadOnly:!0});else if(o)i=new bi;else if(t){const d=J(Yr,"cache");i=new Ir({cacheDir:d,passphrase:t})}else process.stderr.write(`[neocortex] Warning: No license key in config. Run "neocortex activate" to re-authenticate.
16
+ `),i=new bi;const r=Bi(n,i,"auth-cache"),a=Bi(n,i,"tier-cache"),s=new vn({serverUrl:e,licenseKey:t??"",cacheProvider:r,strictReadOnly:o,causalAuthRecovery:!0});let u;if(o){const d=await s.inspectToken();if(d.status==="refresh-required"){const h=d.reason==="unavailable"?"store-unavailable":d.reason;return Cr(h,h==="expired"||h==="near-expiry"?"prepare":"retry-later")}if(d.status==="not-configured")return d;u=d.token}else u=await s.getToken();if(!u){if(!t)return{status:"not-configured"};const d=s.getLastRecoveryResult();return d?.status==="refresh-required"&&d.cause!=="valid"&&d.cause!=="not-configured"||d?.status==="uncertain"?Cr(d.cause,d.action):Cr("store-unavailable","retry-later")}const g=new Da({cacheProvider:a,licenseClient:s});return{status:"authenticated",token:u,client:s,tierClient:g}}catch{return t?Cr("store-unavailable","retry-later"):{status:"not-configured"}}}let jo=!1;const wd=/^(?:(?:private-execution|story-worktree|planning-root|architecture-root|unclassified-invoke)[a-z0-9-]*|PRIVATE_EXECUTION_[A-Z0-9_]+|ORCHESTRATION_ERROR)$/,Jn=/^[a-z0-9][a-z0-9._-]{0,127}$/,Rd=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function Ad(e){if(!f(e))return;const t=e.error_code;if(typeof t!="string")return;const n=Hr(e.semanticGateRemediation),o=Rd.test(t)&&n?.reasonCode===t;if(!wd.test(t)&&!o)return;const i={error_code:t};for(const s of["reason_code","fallback_action","next_action"]){const u=e[s];typeof u=="string"&&Jn.test(u)&&(i[s]=u)}const r=Rn(e);r&&(i.validation_stage=r.validation_stage,i.validation_field=r.validation_field),n&&(i.semanticGateRemediation=n);const a=e.epic_claim_recovery;return f(a)&&a.schemaVersion===1&&a.kind==="create-epic-claim-replay"&&typeof a.claimId=="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(a.claimId)&&typeof a.epicId=="string"&&/^P[1-9][0-9]{0,11}$/.test(a.epicId)&&a.nextAction==="reinvoke-same-command"&&a.publicSafe===!0&&(i.epic_claim_recovery={schemaVersion:1,kind:"create-epic-claim-replay",claimId:a.claimId,epicId:a.epicId,nextAction:"reinvoke-same-command",publicSafe:!0}),i}function bd(e){if(!f(e)||e.schemaVersion!==1||typeof e.claimId!="string"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(e.claimId)||typeof e.epicId!="string"||!/^P[1-9][0-9]{0,11}$/.test(e.epicId)||e.nextAction!=="reinvoke-same-command"||e.persisted!==!0||e.publicSafe!==!0)return;const t=typeof e.reasonCode=="string"&&Jn.test(e.reasonCode)?e.reasonCode:void 0,n=typeof e.fallbackAction=="string"&&Jn.test(e.fallbackAction)?e.fallbackAction:void 0;return{...t?{reason_code:t}:{},...n?{fallback_action:n}:{},next_action:"reinvoke-same-command",claim_recovery:{epic_id:e.epicId,persisted:!0,public_safe:!0}}}function xd(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 Mo=3,rn=50;function Td(e){return new Promise(t=>setTimeout(t,e))}function Pd(e,t,n){return e.status>=500&&e.status<=599?!0:n&&e.status===409&&t.error_code==="SIGNATURE_REPLAYED"}async function _r(e,t,n,o,i={}){const r=Math.max(1,Math.min(i.maxAttempts??Mo,Mo)),a=i.sleep??Td;let s=o,u=!1,g=!1,d=0;for(let h=1;h<=r;h+=1){const l=Math.max(Math.floor(Date.now()/1e3),d+1);d=l;const E=kd(t,n,s,{nowSeconds:l}),v=new AbortController,w=setTimeout(()=>v.abort(),eo);try{const S=await fetch(`${e}${t}`,{method:"POST",headers:E.headers,body:E.body,signal:v.signal});if(i.admitResponseBeforeBodyRead&&!i.admitResponseBeforeBodyRead(S))return{response:S,text:"",parsed:{},responseAdmissionRejected:!0};let y="";try{y=await S.text()}catch($){if(S.ok)return{text:"",parsed:{},networkFailure:Pi($,v.signal.aborted)}}const N=S.ok&&i.deferSuccessfulJsonParsing?{}:(()=>{try{return y?JSON.parse(y):{}}catch{return{}}})();if(S.status===401&&!u&&i.refreshToken&&(N.fallback_action==="refresh_token"||N.fallback_action==="re_authenticate")){u=!0;const $=await i.refreshToken();if($&&h<r){s=$,i.onTokenChanged?.($),await a(rn*h);continue}}if(S.status===401&&N.error_code==="SIGNATURE_EXPIRED"&&!g&&h<r){g=!0,await a(rn*h);continue}if(h<r&&Pd(S,N,i.allowReplayRetry===!0)){await a(rn*h);continue}return{response:S,text:y,parsed:N}}catch(S){if(h<r){await a(rn*h);continue}return{text:"",parsed:{},networkFailure:Pi(S,v.signal.aborted)}}finally{clearTimeout(w)}}return{text:"",parsed:{},networkFailure:"transport-error"}}function kd(e,t,n,o={}){const i=Buffer.from(JSON.stringify(t),"utf8"),r=nc({method:"POST",target:e,body:i,bearerToken:n,clientVersion:Dt,nowSeconds:o.nowSeconds,nonceBytes:o.nonceBytes});return{body:r.body,headers:{...r.headers,Authorization:`Bearer ${n}`}}}function Vo(e){return je("sha256").update(e).digest("hex")}function Od(){const e=Number(process.env.NEOCORTEX_INVOKE_CHUNK_BYTES??"49152");return Number.isFinite(e)&&e>=1024&&e<=98304?Math.floor(e):49152}function Nd(e,t,n){return`args-${je("sha256").update("invoke-materialization:v1").update(e).update(String(t)).update(JSON.stringify(n)).digest("hex")}`}async function Bo(e,t,n,o,i={}){const r=await _r(e,t,n,o,{...i,allowReplayRetry:!0});if(r.networkFailure||!r.response)throw new Error("NETWORK_ERROR: materialization request failed after bounded retries");const{response:a,parsed:s}=r;if(!a.ok){const u=typeof s.error_code=="string"?s.error_code:`HTTP_${a.status}`,g=typeof s.message=="string"?s.message:"materialization upload failed";throw new Error(`${u}: ${g}`)}return s}async function Dd(e,t,n,o){const i=Buffer.from(t,"utf8"),r=Od(),a=[];for(let v=0,w=0;v<i.byteLength;v+=r,w++){const S=i.subarray(v,Math.min(v+r,i.byteLength));a.push({index:w,sha256:Vo(S),byteLength:S.byteLength})}const s=Vo(i),u=Nd(s,i.byteLength,a),g=Number(process.env.NEOCORTEX_INVOKE_CHUNK_TTL_SECONDS??"900");let d=n;const h={refreshToken:o,onTokenChanged(v){d=v}};for(const v of a){const w=v.index*r,S=i.subarray(w,w+v.byteLength);await Bo(e,"/api/v1/invoke/materialization/chunks",{manifestId:u,index:v.index,sha256:v.sha256,byteLength:v.byteLength,contentBase64:S.toString("base64"),ttlSeconds:g,idempotencyKey:`${u}:${v.index}:${v.sha256}`},d,h)}const E=(await Bo(e,"/api/v1/invoke/materialization/manifests",{manifestId:u,sha256:s,byteLength:i.byteLength,chunkCount:a.length,chunks:a,ttlSeconds:g,retry:{attempt:1,budget:3,idempotencyKey:u}},d,h)).argsRef;if(!E?.manifestId)throw new Error("MATERIALIZATION_RESPONSE_INVALID: missing argsRef");return{argsRef:E,chunks:a}}function cr(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function Ld(...e){const t=new Set,n=[];for(const o of e)for(const i of o??[]){const r=ue(i);if(!(!r||t.has(r))&&(t.add(r),n.push(r),n.length>=16))return n}return n}function jd(e){const t=e.graphRetrieval;if(!f(t))return{accepted:!1,itemCount:0};const n=Array.isArray(t.items)?t.items.length:0;return{accepted:n>0||typeof t.retrievalId=="string"||t.accepted===!0,itemCount:n}}function Qn(e,t=cr(e),n=[],o={}){const i=e.stateSnapshot.scope,r=Object.keys(e.stateSnapshot.stories).length,a=Object.keys(e.stateSnapshot.epics).length,s=i?.kind??"full";return{schemaVersion:1,payloadBytes:t,limitBytes:o.limitBytes??ro,warningThresholdBytes:o.warningThresholdBytes??Pn,scope:{kind:s,...i?.projectionMode?{projectionMode:i.projectionMode}:{},commandId:i?.commandId??null,stateProjectionPolicy:i?.stateProjectionPolicy??null},includedStories:i?.includedStoryCount??r,omittedStories:i?.omittedStoryCount??0,includedEpics:i?.includedEpicCount??a,omittedEpics:i?.omittedEpicCount??0,graphRetrieval:jd(e.stateSnapshot),reasonCodes:Ld(n,i?.reasonCodes),publicSafe:!0}}function Md(e){const t=f(e.budget)?e.budget:void 0,n=typeof t?.maxPayloadBytes=="number"&&Number.isFinite(t.maxPayloadBytes)?t.maxPayloadBytes:12*1024;return Math.max(1024,Math.min(n,12*1024))}function Vd(e){return f(e)?{stableId:ue(e.stableId)??"unknown",...f(e.source)?{source:e.source}:{},reasonCode:"budget_exceeded"}:{stableId:"unknown",reasonCode:"budget_exceeded"}}function $o(e){const t=Array.isArray(e)?e.filter(n=>typeof n=="string"):[];return t.includes("budget_exceeded")?t:[...t,"budget_exceeded"]}function Bd(e){const t=e.graphRetrieval;if(!f(t)||!Array.isArray(t.items))return e;const n=Md(t);let o=[...t.items],i=Array.isArray(t.skipped)?[...t.skipped]:[],r=t;for(;Buffer.byteLength(JSON.stringify(r),"utf8")>n&&o.length>0;){const a=o.pop();i=[...i,Vd(a)].slice(-32),r={...t,items:o,skipped:i,warnings:$o(t.warnings)}}return Buffer.byteLength(JSON.stringify(r),"utf8")>n&&(r={...t,query:typeof t.query=="string"?t.query.slice(0,240):t.query,items:[],skipped:[],warnings:$o(t.warnings)}),r===t?e:{...e,graphRetrieval:r}}function Xn(e,t={}){const n=t.limitBytes??ro,o=t.warningThresholdBytes??Math.floor(n*no),i=cr(e);if(i<n)return{body:e,degraded:!1,telemetry:Qn(e,i,["payload-within-limit"],{limitBytes:n,warningThresholdBytes:o})};let r={...e,stateSnapshot:Ua(e.stateSnapshot)},a=["payload-size-guardrail","state-degraded"],s=cr(r);s>=n&&(r={...r,stateSnapshot:Bd(r.stateSnapshot)},a=[...a,"graph-retrieval-budget-enforced"],s=cr(r));const u=Qn(r,s,a,{limitBytes:n,warningThresholdBytes:o});if(s>=n){const g=r.stateSnapshot.scope?.projectionMode;throw g==="yolo-story"||g==="yoloop-target"||g==="yoloop-session"||g==="yoloop-discovery"||g==="structural-required"?new $n(u):new Bn(u)}return{body:r,degraded:!0,telemetry:u}}function Uo(e){const t=e.stateSnapshot.scope?.commandId??"resolved-command";return e.args!==void 0?t:`${t}:argsRef`}function $d(e){const t=cr(e);if(t<Pn)return t;const n=Qn(e,t,["payload-warning-threshold"]);return process.stderr.write(`[Neocortex] invoke payload near server limit: trigger=${Uo(e)} scope=${n.scope.kind} mode=${n.scope.projectionMode??n.scope.kind} payloadBytes=${n.payloadBytes} limit=${n.limitBytes} includedStories=${n.includedStories} omittedStories=${n.omittedStories} includedEpics=${n.includedEpics} omittedEpics=${n.omittedEpics} graphRetrieval.accepted=${n.graphRetrieval.accepted} graphRetrieval.itemCount=${n.graphRetrieval.itemCount} reasonCodes=${n.reasonCodes.join(",")||"none"}
17
+ `),t}function Ho(e,t){process.stderr.write(`[Neocortex] invoke payload guardrail: trigger=${Uo(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"}
18
+ `)}async function Ud(e){const t=Ka(e.args,{platformTarget:e.platformTarget,environment:e.environment??process.env});if(t.action==="skipped")return{shouldContinue:!0,attachToRequest:Hd(t),metadata:Go(t)};const n=e.bootstrapper??Qa;let o;try{o=await n({projectRoot:e.projectRoot,env:e.environment??process.env,effectAuthority:e.effectAuthority})}catch{o={ok:!1,attempted:!0,installed:!1,started:!1,cached:!1,projectKey:"unknown",reasonCodes:[Ja.UNEXPECTED_ERROR],publicSummary:"runner scheduler bootstrap stopped unexpectedly.",publicSafe:!0}}const i=Go(t,o);if(o.ok)return{shouldContinue:!0,attachToRequest:!0,metadata:i};const r=i.reasonCodes.slice(0,5).join(",");return t.failurePolicy==="fail-open"?{shouldContinue:!0,attachToRequest:!0,metadata:{...i,failOpenWarning:!0},warning:`Runner auto-bootstrap warning (${r}); continuing fail-open for operator command.`}:{shouldContinue:!1,attachToRequest:!1,metadata:i,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 Hd(e){return!e.reasonCodes.includes(qa.SKIPPED_NON_CONTINUITY_COMMAND)}function Go(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:ze([...e.reasonCodes,...t?.reasonCodes??[]]),publicSummary:t?.publicSummary??e.publicSummary,publicSafe:!0}}function ze(e){return Array.from(new Set(e.map(t=>t.slice(0,120))))}function nn(e,t,n){const o=Math.floor(e??t);return Number.isFinite(o)?Math.max(1,Math.min(n,o)):t}function on(e,t){const n=process.env[e];if(!n)return t;const o=Number(n);return Number.isFinite(o)?o:t}function X(e,t=go){const n=typeof e=="string"&&e.trim().length>0?e.trim():"unknown",o=nt(n,t),i=Os.test(o)?Lt:o;return i.length<=t?i:`${i.slice(0,t)}\u2026[TRUNCATED:${i.length-t}]`}function Zn(e,t=go){if(!(typeof e!="string"||e.trim().length===0))return X(e,t)}function ei(e,t,n,o){const i=Zn(e?.targetId??t,120),r=e?.selectorKind??(i?ri(i):void 0),a=(e?.relatedJobIds??[]).map(s=>Zn(s,120)).filter(s=>!!s);return{schemaVersion:1,contractVersion:"continuity-v1",targetResolutionState:n,...r?{targetKind:r}:{},...i?{targetId:i}:{},...t?{targetJobId:X(t,120)}:{},...e?.jobId?{jobId:X(e.jobId,120)}:{},...e?.goalId?{goalId:X(e.goalId,120)}:{},...e?.loopId?{loopId:X(e.loopId,120)}:{},...a.length>0?{relatedJobIds:a}:{},relatedJobCount:a.length,reasonCodes:ze(o.length>0?o:[Q.OK]),publicSafe:!0}}function bt(e,t,n,o,i=[]){const r=(e?.redactions?.length??0)>0,a=e?r?"unsafe":n&&o===0?"empty":"available":"unavailable",s=Zn(t[t.length-1]?.eventId,120),u=i.length>0?i:a==="unavailable"?[Q.WATCH_SNAPSHOT_UNAVAILABLE]:a==="empty"?[Q.WATCH_NO_SUMMARIES_YET]:[Q.OK];return{schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:a,...e?.generatedAt?{generatedAt:X(e.generatedAt,80)}:{},renderedSummaryCount:o,...s?{latestEventId:s}:{},reasonCodes:ze(u),publicSafe:!0}}function lt(e,t,n,o,i=[],r){const a=o[o.length-1],s=n??a?.cursor,u=!!(s&&s!==t&&o.length>0),g=r??(u?"advanced":t||s?"unchanged":"not_started"),d=i.length>0?i:g==="advanced"?[Q.WATCH_CURSOR_ADVANCED]:g==="unavailable"?[Q.WATCH_EVIDENCE_UNAVAILABLE]:[Q.WATCH_CURSOR_UNCHANGED];return{schemaVersion:1,contractVersion:"continuity-v1",cursorState:g,...e?{initialCursor:X(e,200)}:{},...t?{currentCursor:X(t,200)}:{},...s?{nextCursor:X(s,200)}:{},cursorAdvanced:u,...a?.eventId?{eventId:X(a.eventId,120)}:{},reasonCodes:ze(d),publicSafe:!0}}function ht(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:ze([...e.reasonCodes??[],...t?.reasonCodes??[],...e.snapshotEvidence?.reasonCodes??[],...e.cursorEvidence?.reasonCodes??[]]),generatedAt:X(e.generatedAt??new Date().toISOString(),80),publicSafe:!0}}function Gd(e){const t=e.targetKind&&e.targetId?`${e.targetKind}/${e.targetId}`:e.targetId??"[unresolved]",n=e.snapshotEvidence?.renderedSummaryCount??0,o=e.targetEvidence?.relatedJobCount??0,i=e.cursorEvidence?.cursorState??"unavailable",r=e.cursorEvidence?.currentCursor??"[none]",a=e.cursorEvidence?.nextCursor??"[none]",s=e.snapshotEvidence?.snapshotStatus??"not_requested",u=e.snapshotEvidence?.generatedAt??e.generatedAt;return[`[watch-status] ${e.targetResolutionState==="unresolved"||e.stopReason==="target_unresolved"?"unresolved-target":n===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=${o}`,`summaries=${n}`,`snapshot=${s}`,`generatedAt=${u}`,`cursor=${i}`,`current=${X(r,200)}`,`next=${X(a,200)}`,`advanced=${e.cursorEvidence?.cursorAdvanced??!1}`,`stop=${e.stopReason??"not_stopped"}`,`reasons=${e.reasonCodes.join(",")}`].join(" ")}function ft(e,t,n,o=!1){if(o){const i={type:"watch_status",watchStatus:e.watchStatus,active:e.active,renderedSummaryCount:e.snapshotEvidence?.renderedSummaryCount??0,stopReason:e.stopReason??"not_stopped",protectedProjection:!0,publicSafe:!0};n.write(t==="json"?`${JSON.stringify(i)}
19
+ `:`[watch-status] status=${i.watchStatus} active=${i.active} summaries=${i.renderedSummaryCount} stop=${i.stopReason}
20
20
  `);return}if(t==="json"){n.write(JSON.stringify(e)+`
21
- `);return}n.write(Vd(e)+`
22
- `)}function Bd(e,t,n){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:n,statusRecord:e,publicSafe:!0}}}function xt(e,t,n,i,o=!1){return o?{status:e,summariesEmitted:t,polls:n,reasonCodes:[],watchStatus:i.watchStatus,stopReason:i.stopReason,metadata:{continuityInvokeWatch:{schemaVersion:1,contractVersion:"continuity-v1",command:"invoke",operation:"watch",watchStatus:i.watchStatus,stopReason:i.stopReason??"not_stopped",summariesEmitted:t,polls:n,protectedProjection:!0,publicSafe:!0}},publicSafe:!0}:{status:e,summariesEmitted:t,polls:n,reasonCodes:i.reasonCodes,watchStatus:i.watchStatus,stopReason:i.stopReason,targetEvidence:i.targetEvidence,snapshotEvidence:i.snapshotEvidence,cursorEvidence:i.cursorEvidence,statusRecord:i,metadata:Bd(i,t,n),publicSafe:!0}}function $d(e){const t=e.reasonCode?` reason=${J(e.reasonCode,80)}`:"",n=e.goalId?` goal=${J(e.goalId,100)}`:"",i=e.loopId?` loop=${J(e.loopId,100)}`:"";return`[watch] ${J(e.createdAt,80)} event=${J(e.eventId,120)} job=${J(e.jobId,100)}${n}${i} execution=${J(e.executionId,120)}${t} -- ${J(e.publicSummary)}`}function Ud(e){return{type:"processing_summary",source:"local_continuity_sqlite",eventId:J(e.eventId,120),jobId:J(e.jobId,100),...e.goalId?{goalId:J(e.goalId,100)}:{},...e.loopId?{loopId:J(e.loopId,100)}:{},executionId:J(e.executionId,120),...e.reasonCode?{reasonCode:J(e.reasonCode,80)}:{},createdAt:J(e.createdAt,80),publicSummary:J(e.publicSummary),publicSafe:!0}}function Hd(e,t,n,i=!1){if(i){n.write(t==="json"?`${JSON.stringify({type:"processing_summary",source:"local_continuity_sqlite",publicSummary:"A local processing update is available.",protectedProjection:!0,publicSafe:!0})}
21
+ `);return}n.write(Gd(e)+`
22
+ `)}function Wd(e,t,n){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:n,statusRecord:e,publicSafe:!0}}}function xt(e,t,n,o,i=!1){return i?{status:e,summariesEmitted:t,polls:n,reasonCodes:[],watchStatus:o.watchStatus,stopReason:o.stopReason,metadata:{continuityInvokeWatch:{schemaVersion:1,contractVersion:"continuity-v1",command:"invoke",operation:"watch",watchStatus:o.watchStatus,stopReason:o.stopReason??"not_stopped",summariesEmitted:t,polls:n,protectedProjection:!0,publicSafe:!0}},publicSafe:!0}:{status:e,summariesEmitted:t,polls:n,reasonCodes:o.reasonCodes,watchStatus:o.watchStatus,stopReason:o.stopReason,targetEvidence:o.targetEvidence,snapshotEvidence:o.snapshotEvidence,cursorEvidence:o.cursorEvidence,statusRecord:o,metadata:Wd(o,t,n),publicSafe:!0}}function Fd(e){const t=e.reasonCode?` reason=${X(e.reasonCode,80)}`:"",n=e.goalId?` goal=${X(e.goalId,100)}`:"",o=e.loopId?` loop=${X(e.loopId,100)}`:"";return`[watch] ${X(e.createdAt,80)} event=${X(e.eventId,120)} job=${X(e.jobId,100)}${n}${o} execution=${X(e.executionId,120)}${t} -- ${X(e.publicSummary)}`}function zd(e){return{type:"processing_summary",source:"local_continuity_sqlite",eventId:X(e.eventId,120),jobId:X(e.jobId,100),...e.goalId?{goalId:X(e.goalId,100)}:{},...e.loopId?{loopId:X(e.loopId,100)}:{},executionId:X(e.executionId,120),...e.reasonCode?{reasonCode:X(e.reasonCode,80)}:{},createdAt:X(e.createdAt,80),publicSummary:X(e.publicSummary),publicSafe:!0}}function Yd(e,t,n,o=!1){if(o){n.write(t==="json"?`${JSON.stringify({type:"processing_summary",source:"local_continuity_sqlite",publicSummary:"A local processing update is available.",protectedProjection:!0,publicSafe:!0})}
23
23
  `:`[watch] A local processing update is available.
24
- `);return}if(t==="json"){n.write(JSON.stringify(Ud(e))+`
25
- `);return}n.write($d(e)+`
26
- `)}function Zn(e){return Rs.has(e.status)}function Gd(e,t,n){if(t){const o=e.find(r=>r.jobId===t);return!!(o&&Zn(o))}return n<=0?!1:e.filter(o=>!Zn(o)).length===0}function Wd(e,t,n,i){return n<i?!1:t?!e.some(o=>o.jobId===t&&!Zn(o)):e.length===0}function Fd(e,t){return t?.aborted?Promise.resolve():new Promise(n=>{const i=setTimeout(o,e);function o(){clearTimeout(i),t?.removeEventListener("abort",o),n()}t?.addEventListener("abort",o,{once:!0})})}function zd(e){return e.includes(Ue.MALFORMED)?"malformed":e.includes(Ue.AMBIGUOUS)?"ambiguous":e.includes("watch-target-multiple")?"multiple":e.includes("watch-evidence-unsafe")?"unsafe":e.includes(Ue.MISSING)||e.includes(Oe.TARGET_UNRESOLVED)?"unresolved":"unavailable"}function Ui(e,t){const n=t?wr(t):void 0,i=ze([...e,Oe.TARGET_UNRESOLVED,K.WATCH_TARGET_UNRESOLVED]),o=Xn(n,n?.targetId,zd(i),i),r=bt({generatedAt:new Date().toISOString()},[],!1,0,[K.WATCH_TARGET_UNRESOLVED]),a=lt(void 0,void 0,void 0,[],[K.WATCH_TARGET_UNRESOLVED],"unavailable");return ht({watchStatus:"blocked",active:!1,targetEvidence:o,snapshotEvidence:r,cursorEvidence:a,stopReason:"target_unresolved",reasonCodes:i,generatedAt:r.generatedAt})}function Yd(e,t,n,i,o=!1){const r=Ui(e,Gi(t));return ft(r,n,i,o),xt("target-unresolved",0,0,r,o)}async function qd(e){if(e.signal?.aborted){const b=Xn(e.target??wr(e.targetJobId),e.targetJobId,e.target??e.targetJobId?"resolved":"unresolved",[Oe.CANCELLED]),C=bt(void 0,[],!1,0),A=lt(e.initialCursor,e.initialCursor,e.initialCursor,[],[Oe.CANCELLED],"unavailable"),Y=ht({watchStatus:"stopped",active:!1,targetEvidence:b,snapshotEvidence:C,cursorEvidence:A,stopReason:"cancelled",reasonCodes:[Oe.CANCELLED]});return xt("cancelled",0,0,Y,e.protectedOutput)}const t=e.target??wr(e.targetJobId),n=e.targetJobId??t?.targetId,i=e.stdout??process.stdout;if(!t){const b=Ui([Ue.MISSING,Oe.TARGET_UNRESOLVED]);return ft(b,e.format,i,e.protectedOutput),xt("target-unresolved",0,0,b,e.protectedOutput)}const o=nn(e.limit??on("NEOCORTEX_INVOKE_WATCH_LIMIT",No),No,50),r=Math.max(50,nn(e.pollIntervalMs??on("NEOCORTEX_INVOKE_WATCH_POLL_INTERVAL_MS",jo),jo,6e4)),a=nn(e.maxIdlePolls??on("NEOCORTEX_INVOKE_WATCH_MAX_IDLE_POLLS",Do),Do,120),s=nn(e.maxPolls??on("NEOCORTEX_INVOKE_WATCH_MAX_POLLS",Lo),Lo,86400),u=e.sleep??Fd;let g=e.initialCursor,d=0,h=0,l=0;const E=Xn(t,n,"resolved",[K.OK]),_={schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:"pending",renderedSummaryCount:0,reasonCodes:[K.WATCH_RENDER_PENDING],publicSafe:!0},w=lt(e.initialCursor,g,g,[],e.initialCursor?[K.WATCH_CURSOR_UNCHANGED]:[K.WATCH_NO_SUMMARIES_YET],e.initialCursor?"unchanged":"not_started");ft(ht({watchStatus:"active",active:!0,targetEvidence:E,snapshotEvidence:_,cursorEvidence:w,stopReason:"not_stopped",reasonCodes:[K.OK]}),e.format,i,e.protectedOutput);let S;try{S=await Ka({projectRoot:e.projectRoot,strictReadOnly:e.strictReadOnly})}catch{const b=bt(void 0,[],!1,d,[K.WATCH_SNAPSHOT_UNAVAILABLE]),C=lt(e.initialCursor,g,g,[],[K.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),A=ht({watchStatus:"blocked",active:!1,targetEvidence:E,snapshotEvidence:b,cursorEvidence:C,stopReason:"unavailable_evidence",reasonCodes:[Oe.STORE_UNAVAILABLE]});return ft(A,e.format,i,e.protectedOutput),xt("store-unavailable",d,l,A,e.protectedOutput)}try{for(;!e.signal?.aborted&&l<s;){l+=1;const b=g,C=S.collectProcessingOutputSummaryCursor({...g?{cursor:g}:{},...t?{target:t}:{},...n?{jobId:n}:{},limit:o}),A=S.collectSnapshot({jobLimit:50,processingSummaryLimit:1}),Y=A.jobs;if(C.summaries.length>0){for(const j of C.summaries)Hd(j,e.format,i,e.protectedOutput),d+=1;g=C.nextCursor??C.summaries[C.summaries.length-1]?.cursor??g,h=0}else g=C.nextCursor??g,h+=1;const Z=bt(A,C.summaries,!0,C.summaries.length),Q=lt(e.initialCursor,b,g,C.summaries,C.summaries.length>0?[K.WATCH_CURSOR_ADVANCED]:[K.WATCH_NO_SUMMARIES_YET]);if(ft(ht({watchStatus:C.summaries.length>0?"polling":"waiting",active:!0,targetEvidence:E,snapshotEvidence:Z,cursorEvidence:Q,stopReason:"not_stopped",reasonCodes:C.summaries.length>0?[K.WATCH_CURSOR_ADVANCED]:[K.WATCH_NO_SUMMARIES_YET],generatedAt:A.generatedAt}),e.format,i,e.protectedOutput),!C.hasMore&&Gd(Y,n,d)){const j=bt(A,C.summaries,!1,d,[Oe.COMPLETED]),ae=lt(e.initialCursor,b,g,C.summaries,[Oe.COMPLETED],"exhausted"),ve=ht({watchStatus:"stopped",active:!1,targetEvidence:E,snapshotEvidence:j,cursorEvidence:ae,stopReason:"not_stopped",reasonCodes:[Oe.COMPLETED],generatedAt:A.generatedAt});return ft(ve,e.format,i,e.protectedOutput),xt("completed",d,l,ve,e.protectedOutput)}if(!C.hasMore&&Wd(Y,n,h,a)){const j=bt(A,C.summaries,!1,d,[K.WATCH_STOP_IDLE_LIMIT_REACHED]),ae=lt(e.initialCursor,b,g,C.summaries,[K.WATCH_STOP_IDLE_LIMIT_REACHED],"exhausted"),ve=ht({watchStatus:"stopped",active:!1,targetEvidence:E,snapshotEvidence:j,cursorEvidence:ae,stopReason:"idle_limit_reached",reasonCodes:[Oe.IDLE_TIMEOUT,K.WATCH_STOP_IDLE_LIMIT_REACHED],generatedAt:A.generatedAt});return ft(ve,e.format,i,e.protectedOutput),xt("idle-timeout",d,l,ve,e.protectedOutput)}C.hasMore||await u(r,e.signal)}}catch{const b=bt(void 0,[],!1,d,[K.WATCH_SNAPSHOT_UNAVAILABLE]),C=lt(e.initialCursor,g,g,[],[K.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),A=ht({watchStatus:"blocked",active:!1,targetEvidence:E,snapshotEvidence:b,cursorEvidence:C,stopReason:"unavailable_evidence",reasonCodes:[Oe.STORE_UNAVAILABLE]});return ft(A,e.format,i,e.protectedOutput),xt("store-unavailable",d,l,A,e.protectedOutput)}finally{S.close()}if(e.signal?.aborted){const b=bt(void 0,[],!1,d,[Oe.CANCELLED]),C=lt(e.initialCursor,g,g,[],[Oe.CANCELLED],"unavailable"),A=ht({watchStatus:"stopped",active:!1,targetEvidence:E,snapshotEvidence:b,cursorEvidence:C,stopReason:"cancelled",reasonCodes:[Oe.CANCELLED]});return ft(A,e.format,i,e.protectedOutput),xt("cancelled",d,l,A,e.protectedOutput)}const y=bt(void 0,[],!1,d,[K.WATCH_STOP_MAX_POLLS_REACHED]),D=lt(e.initialCursor,g,g,[],[K.WATCH_STOP_MAX_POLLS_REACHED],"exhausted"),U=ht({watchStatus:"stopped",active:!1,targetEvidence:E,snapshotEvidence:y,cursorEvidence:D,stopReason:"max_polls_reached",reasonCodes:[Oe.MAX_POLLS,K.WATCH_STOP_MAX_POLLS_REACHED]});return ft(U,e.format,i,e.protectedOutput),xt("max-polls",d,l,U,e.protectedOutput)}function ot(e){const t=e.trim().replace(/^@/,"").match(/^(job|goal|loop)-([JGL])(\d{3,})$/i);if(!t)return;const n=t[1].toLowerCase(),i=t[2].toUpperCase();if(!(n==="job"&&i!=="J"||n==="goal"&&i!=="G"||n==="loop"&&i!=="L"))return`${n}-${i}${t[3]}`}function eo(e){if(e.startsWith("job-J"))return"job";if(e.startsWith("goal-G"))return"goal";if(e.startsWith("loop-L"))return"loop"}function Hi(e){const t=[],n=/(?:^|[\s"'([,{])@?(job-[Jj]\d{3,}|goal-[Gg]\d{3,}|loop-[Ll]\d{3,})(?=$|[\s"')\]},.;:!?])/g;let i;for(;(i=n.exec(e))!==null;){const o=ot(i[1]);o&&t.push(o)}return ze(t)}function Gi(e){return Hi(e)[0]}function wr(e){const t=e?ot(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 to(e){return ze(e.filter(t=>typeof t=="string").map(t=>ot(t)).filter(t=>!!t?.startsWith("job-J")))}function Kd(e,t){const n=to(t).filter(i=>i!==e.targetId&&i!==e.jobId);return n.length>0?{...e,relatedJobIds:n}:e}function Jd(e){if(!e)return;const t=f(e.target)?e.target:void 0,n=typeof e.selectorKind=="string"?e.selectorKind:typeof t?.selectorKind=="string"?t.selectorKind:void 0,i=typeof e.targetId=="string"?ot(e.targetId):typeof t?.targetId=="string"?ot(t.targetId):typeof e.targetJobId=="string"?ot(e.targetJobId):void 0,o=wr(i);if(!o||n&&n!==o.selectorKind)return;const r=Array.isArray(e.relatedJobIds)?e.relatedJobIds:Array.isArray(t?.relatedJobIds)?t.relatedJobIds:void 0,a=to([...r??[],e.jobId,t?.jobId,e.targetJobId,t?.targetJobId]).filter(s=>s!==o.targetId&&s!==o.jobId);return{...o,...typeof(e.jobId??t?.jobId)=="string"?{jobId:ot(e.jobId??t?.jobId)??o.jobId}:{},...typeof(e.goalId??t?.goalId)=="string"?{goalId:ot(e.goalId??t?.goalId)??o.goalId}:{},...typeof(e.loopId??t?.loopId)=="string"?{loopId:ot(e.loopId??t?.loopId)??o.loopId}:{},...a.length>0?{relatedJobIds:a}:{}}}function Wi(e){const t=e.trim().split(/\s+/).filter(Boolean),n=t[0]?.replace(/^\*/,"").toLowerCase(),i=t[1]?.replace(/^--/,"").toLowerCase();return(n==="jobs"||n==="job"||n==="continuity-jobs"||n==="61")&&i==="watch"}const je=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"}),Qd=new Set(["create","start","resume"]),Xd=new Set(["create","resume","run-once"]);function ro(e,t,n,i,o){return{schemaVersion:1,contractVersion:"continuity-v1",...n?{command:n}:{},...i?{operation:i}:{},active:e,...o?{watchToken:o}:{},reasonCodes:ze(t),serverHeldStream:!1,allJobsPolling:!1,targetResolution:e?"required-after-dispatch":"inactive",publicSafe:!0}}function Ge(e,t=[],n,i){const o=t.length>0?t:[je.INACTIVE];return{args:e,watch:!1,reasonCodes:o,metadata:ro(!1,o,n,i),publicSafe:!0}}function Zd(e){const t=e.trim().split(/\s+/).filter(Boolean),n=t.slice(2).filter(r=>r==="--watch").length;if(n===0)return Ge(e,[],"jobs","watch");if(n!==1)return Ge(e,[je.AMBIGUOUS],"jobs","watch");const i=t.filter((r,a)=>a<2||r!=="--watch").join(" ");return Wi(i)?i.trim().split(/\s+/).filter(Boolean).slice(2).length!==1?Ge(e,[je.AMBIGUOUS],"jobs","watch"):Gi(i)?{args:i,watch:!0,reasonCodes:[je.ACTIVE],metadata:ro(!0,[je.ACTIVE],"jobs","watch"),publicSafe:!0}:Ge(e,[je.TARGET_INVALID],"jobs","watch"):Ge(e,[je.UNSUPPORTED],"jobs","watch")}function ep(e){const t=[];let n=!1,i=0;for(;i<e.length;){for(;i<e.length&&/\s/.test(e[i]);)i+=1;if(i>=e.length)break;const o=i;let r="",a=!1,s=null;for(;i<e.length;){const u=e[i];if(s){if(u===s){a=!0,s=null,i+=1;continue}if(u==="\\"&&i+1<e.length){r+=e[i+1],i+=2;continue}r+=u,i+=1;continue}if(/\s/.test(u))break;if(u==='"'||u==="'"){a=!0,s=u,i+=1;continue}r+=u,i+=1}s&&(n=!0),t.push({value:r,start:o,end:i,quoted:a})}return{tokens:t,malformed:n}}function tp(e){if(!e||e.quoted)return;const t=e.value.replace(/^\*/,"").toLowerCase();return t==="goal"||t==="loop"?t:void 0}function rp(e,t){if(!e||e==="jobs"||!t||t.quoted)return;const n=t.value.toLowerCase();return(e==="goal"?Qd:Xd).has(n)?n:void 0}function np(e){return!e.quoted&&e.value!=="--watch"&&e.value.toLowerCase().startsWith("--watch")}function op(e){const{tokens:t,malformed:n}=ep(e),i=tp(t[0]),o=rp(i,t[1]);if(n)return Ge(e,[je.MALFORMED],i,o);const r=t.filter(l=>l.value==="--watch"&&!l.quoted),a=t.filter(l=>l.value==="--watch"&&l.quoted),s=t.filter(np);if(!(r.length>0||a.length>0||s.length>0))return Ge(e,[],i,o);if(r.length>1)return Ge(e,[je.DUPLICATE],i,o);if(r.length===1&&(a.length>0||s.length>0))return Ge(e,[je.AMBIGUOUS],i,o);if(a.length>0)return Ge(e,[je.QUOTED],i,o);if(s.length>0)return Ge(e,[je.MALFORMED],i,o);const g=r[0];if(!g)return Ge(e,[],i,o);if(t[t.length-1]!==g)return Ge(e,[je.NON_FINAL],i,o);if(!i||!o)return Ge(e,[je.UNRESOLVED],i,o);const d=`${e.slice(0,g.start)}${e.slice(g.end)}`.trim(),h={literal:"--watch",position:"final",start:g.start,end:g.end,quoted:!1,publicSafe:!0};return{args:d,watch:!0,reasonCodes:[je.ACTIVE],metadata:ro(!0,[je.ACTIVE],i,o,h),publicSafe:!0}}function ip(e){return Wi(e)?Zd(e):op(e)}function ap(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&As.has(t)):[]}function sr(e){return{disabled:!0,reasonCodes:ze(e.length>0?e:[Ue.MISSING])}}function no(e,t,n=[],i){const o=wr(t);if(o)return{source:e,target:Kd(o,n),targetJobId:o.targetId,...i?{initialCursor:i}:{},serverHeldStream:!1}}function cp(e){const t=new Map;for(const n of e){const i=`${n.target.selectorKind}:${n.target.targetId}`,o=t.get(i);if(!o){t.set(i,n);continue}const r=ze([...o.target.relatedJobIds??[],...n.target.relatedJobIds??[]]);t.set(i,{...o,target:r.length>0?{...o.target,relatedJobIds:r}:o.target,initialCursor:o.initialCursor??n.initialCursor})}return Array.from(t.values())}function Mt(e,t,n,i){return{source:e,hasEvidence:t,candidates:cp(n.filter(o=>!!o)),...i&&i.length>0?{disabledReasonCodes:ze(i)}:{}}}function sp(e,t){return e.target.selectorKind===t.target.selectorKind&&e.target.targetId===t.target.targetId}function Rr(e,t){const n=ze(e.filter(i=>typeof i=="string").map(i=>ot(i)).filter(i=>!!i));if(t){const i=n.find(o=>eo(o)===t);if(i)return i}return n[0]}function an(e,t){return ze(e.filter(n=>typeof n=="string").map(n=>ot(n)).filter(n=>!!n)).find(n=>eo(n)===t)}function dp(e){const t=f(e?.continuity)?e.continuity:void 0,n=f(t?.jobs)?t.jobs:void 0,i=f(n?.watcher)?n.watcher:void 0,o=ap(i?.reasonCodes??n?.reasonCodes);if(!i)return Mt("watcher-metadata",o.length>0,[],o);if(i.active===!1||o.length>0)return Mt("watcher-metadata",!0,[],o.length>0?o:[Ue.MALFORMED]);if(i.serverHeldStream!==!1)return Mt("watcher-metadata",!0,[],[Ue.SERVER_HELD_STREAM]);const r=Jd(i);if(!r)return Mt("watcher-metadata",!0,[],[Ue.MISSING]);const a=typeof i.initialCursor=="string"?i.initialCursor:void 0;return Mt("watcher-metadata",!0,[{source:"watcher-metadata",target:r,targetJobId:r.targetId,...a?{initialCursor:a}:{},serverHeldStream:!1}])}function Fi(e,t){const n=f(e.loopJobPlan)?e.loopJobPlan:void 0,i=f(n?.metadata)?n.metadata:void 0,o=f(e.metadata)?e.metadata:void 0,a=(t==="goal"?Rr([e.goalId,e.targetGoalId,e.campaignId,e.jobId,e.targetJobId,o?.goalId,o?.campaignId,o?.jobId],"goal"):Rr([e.loopId,e.targetLoopId,e.jobId,e.targetJobId,o?.loopId,o?.jobId,i?.loopId,i?.jobId],"loop"))??Rr([e.jobId,e.targetJobId,o?.jobId,i?.jobId]);return no("goal-loop-continuity-metadata",a,[e.jobId,e.targetJobId,o?.jobId,i?.jobId])}function pp(e){const t=f(e?.continuity)?e.continuity:void 0,n=f(t?.goal)?t.goal:void 0,i=f(t?.loop)?t.loop:void 0,o=[n?Fi(n,"goal"):void 0,i?Fi(i,"loop"):void 0],r=!!(n||i);return Mt("goal-loop-continuity-metadata",r,o,r&&o.every(a=>!a)?[Ue.MISSING]:void 0)}function up(e){return Array.isArray(e)?e.filter(f):f(e)?Array.isArray(e.operationLogs)?e.operationLogs.filter(f):f(e.operationLog)?[e.operationLog]:Array.isArray(e.operations)?[e]:[]:[]}function zi(e,t){const n=f(t.metadata)?t.metadata:void 0,i=an([t.goalId,t.targetGoalId,t.campaignId,n?.goalId,n?.campaignId,t.jobId,n?.jobId],"goal"),o=an([t.loopId,t.targetLoopId,n?.loopId,t.jobId,n?.jobId],"loop"),r=Rr([t.jobId,t.targetJobId,n?.jobId],"job"),a=i??o??r;if(!a)return;const s=e.get(a)??{targetId:a,relatedJobIds:[]};s.relatedJobIds.push(...to([r,t.jobId,t.targetJobId,n?.jobId])),e.set(a,s)}function lp(e){const t=f(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 hp(e){const t=f(e.metadata)?e.metadata:void 0;return!!Rr([e.goalId,e.targetGoalId,e.campaignId,e.loopId,e.targetLoopId,e.jobId,e.targetJobId,t?.goalId,t?.campaignId,t?.loopId,t?.jobId])}function Yi(e,t){const n=[];for(const a of["metadata","job","event","receipt","processingOutputSummary"]){const s=t[a];f(s)&&n.push(s)}const i=f(t.event)?t.event:void 0;f(i?.metadata)&&n.push(i.metadata),f(i?.processingOutputSummary)&&n.push(i.processingOutputSummary);const o=f(t.receipt)?t.receipt:void 0;f(o?.metadata)&&n.push(o.metadata);const r=n.some(hp);for(const a of n)zi(e,a);(!r||lp(t))&&zi(e,t)}function fp(e){const t=up(e?.continuityStateUpdate),n=new Map;for(const o of t){Yi(n,o);const r=Array.isArray(o.operations)?o.operations.filter(f):[];for(const a of r)Yi(n,a)}const i=Array.from(n.values()).map(o=>no("continuity-state-update-operation-log",o.targetId,o.relatedJobIds));return Mt("continuity-state-update-operation-log",t.length>0,i,t.length>0&&i.every(o=>!o)?[Ue.MISSING]:void 0)}function gp(e){const t=Hi(e);return Mt("explicit-args",t.length>0,t.map(n=>no("explicit-args",n)))}function mp(e,t){const n=[dp(e),pp(e),fp(e),gp(t)];for(let i=0;i<n.length;i+=1){const o=n[i];if(!o.hasEvidence)continue;if(o.disabledReasonCodes&&o.disabledReasonCodes.length>0)return sr(o.disabledReasonCodes);if(o.candidates.length!==1)return sr([o.candidates.length>1?Ue.AMBIGUOUS:Ue.MISSING]);const r=o.candidates[0];for(const a of n.slice(i+1)){if(!a.hasEvidence)continue;if(a.disabledReasonCodes&&a.disabledReasonCodes.length>0)return sr(a.disabledReasonCodes);if(a.candidates.length>1)return sr([Ue.AMBIGUOUS]);const s=a.candidates[0];if(s&&!sp(r,s))return sr([Ue.CONFLICT])}return{target:r.target,targetJobId:r.targetJobId,...r.initialCursor?{initialCursor:r.initialCursor}:{},source:r.source,serverHeldStream:!1}}return sr([Ue.MISSING])}async function oo(e,t,n,i={}){const o="/api/v1/invoke";let r,a;const s=await _r(e,o,t,n,{...i,deferSuccessfulJsonParsing:!0,...t.privateExecution?{maxAttempts:1,allowReplayRetry:!1}:{},admitResponseBeforeBodyRead:h=>{const l=h.headers.get("X-Neocortex-Compatibility");if(l!==null)try{if(l.length===0||l.length>8192)throw new Error("header-size");const E=JSON.parse(Buffer.from(l,"base64url").toString("utf8"));if(!Go(E))throw new Error("header-shape");if(r=E,E.status==="incompatible")return a="incompatible",!1}catch{return a="malformed",!1}return i.admitResponseBeforeBodyRead?.(h)??!0}});if(s.networkFailure||!s.response)return{ok:!1,status:0,error:"Network error after bounded retries",networkFailure:s.networkFailure??"transport-error"};if(s.responseAdmissionRejected){const h=a==="malformed"?ir.RESULT_MALFORMED:r?.reasonCodes[0]??ir.OFFER_MALFORMED;return{ok:!1,status:s.response.status,error:`COMPATIBILITY_INCOMPATIBLE: ${h}`,errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:h,fallback_action:r?.remediationHint??"upgrade-client"},...r?{compatibility:r}:{}}}const{response:u,text:g}=s;let d=s.parsed;try{if(t.compatibility&&!r){if(/"(?:reviewReconciliation|review_reconciliation|reconciliationMetadata|releaseLifecycle|release_lifecycle|releaseBlocked|release_blocked|yoloopReleaseBlocked)"\s*:/u.test(g))return{ok:!1,status:u.status,error:`COMPATIBILITY_INCOMPATIBLE: ${ir.UNNEGOTIATED_PROTECTED_FIELD}`,errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:ir.UNNEGOTIATED_PROTECTED_FIELD,fallback_action:"upgrade-client"}};r=Sc({clientVersion:t.compatibility.clientVersion,serverVersion:"0.0.0",registryVersion:t.registryVersion,registryChecksum:t.registryChecksum,reason:ir.SERVER_NEGOTIATION_MISSING})}if(u.ok)try{d=g?JSON.parse(g):{}}catch{return{ok:!1,status:u.status,error:"COMPATIBILITY_INCOMPATIBLE: response-json-malformed",errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:ir.RESULT_MALFORMED},...r?{compatibility:r}:{}}}if(!u.ok){if(t.privateExecution){const E=vd(d),_=E?.error_code;return{ok:!1,status:u.status,error:typeof _=="string"?_:"private-execution-invoke-unavailable",...E?{errorBody:E}:{}}}return{ok:!1,status:u.status,error:Object.keys(d).length>0?`${d.error_code??"ERROR"}: ${d.message??g}`:`HTTP ${u.status}: ${g}`,errorBody:Object.keys(d).length>0?d:void 0,...r?{compatibility:r}:{}}}const h=d,l=u.headers.get("X-Client-Version-Warning");return l&&!Ni&&(Ni=!0,process.stderr.write(`
24
+ `);return}if(t==="json"){n.write(JSON.stringify(zd(e))+`
25
+ `);return}n.write(Fd(e)+`
26
+ `)}function ti(e){return Ps.has(e.status)}function qd(e,t,n){if(t){const i=e.find(r=>r.jobId===t);return!!(i&&ti(i))}return n<=0?!1:e.filter(i=>!ti(i)).length===0}function Kd(e,t,n,o){return n<o?!1:t?!e.some(i=>i.jobId===t&&!ti(i)):e.length===0}function Jd(e,t){return t?.aborted?Promise.resolve():new Promise(n=>{const o=setTimeout(i,e);function i(){clearTimeout(o),t?.removeEventListener("abort",i),n()}t?.addEventListener("abort",i,{once:!0})})}function Qd(e){return e.includes(He.MALFORMED)?"malformed":e.includes(He.AMBIGUOUS)?"ambiguous":e.includes("watch-target-multiple")?"multiple":e.includes("watch-evidence-unsafe")?"unsafe":e.includes(He.MISSING)||e.includes(Ne.TARGET_UNRESOLVED)?"unresolved":"unavailable"}function Wo(e,t){const n=t?wr(t):void 0,o=ze([...e,Ne.TARGET_UNRESOLVED,Q.WATCH_TARGET_UNRESOLVED]),i=ei(n,n?.targetId,Qd(o),o),r=bt({generatedAt:new Date().toISOString()},[],!1,0,[Q.WATCH_TARGET_UNRESOLVED]),a=lt(void 0,void 0,void 0,[],[Q.WATCH_TARGET_UNRESOLVED],"unavailable");return ht({watchStatus:"blocked",active:!1,targetEvidence:i,snapshotEvidence:r,cursorEvidence:a,stopReason:"target_unresolved",reasonCodes:o,generatedAt:r.generatedAt})}function Xd(e,t,n,o,i=!1){const r=Wo(e,zo(t));return ft(r,n,o,i),xt("target-unresolved",0,0,r,i)}async function Zd(e){if(e.signal?.aborted){const b=ei(e.target??wr(e.targetJobId),e.targetJobId,e.target??e.targetJobId?"resolved":"unresolved",[Ne.CANCELLED]),_=bt(void 0,[],!1,0),A=lt(e.initialCursor,e.initialCursor,e.initialCursor,[],[Ne.CANCELLED],"unavailable"),K=ht({watchStatus:"stopped",active:!1,targetEvidence:b,snapshotEvidence:_,cursorEvidence:A,stopReason:"cancelled",reasonCodes:[Ne.CANCELLED]});return xt("cancelled",0,0,K,e.protectedOutput)}const t=e.target??wr(e.targetJobId),n=e.targetJobId??t?.targetId,o=e.stdout??process.stdout;if(!t){const b=Wo([He.MISSING,Ne.TARGET_UNRESOLVED]);return ft(b,e.format,o,e.protectedOutput),xt("target-unresolved",0,0,b,e.protectedOutput)}const i=nn(e.limit??on("NEOCORTEX_INVOKE_WATCH_LIMIT",Di),Di,50),r=Math.max(50,nn(e.pollIntervalMs??on("NEOCORTEX_INVOKE_WATCH_POLL_INTERVAL_MS",Mi),Mi,6e4)),a=nn(e.maxIdlePolls??on("NEOCORTEX_INVOKE_WATCH_MAX_IDLE_POLLS",Li),Li,120),s=nn(e.maxPolls??on("NEOCORTEX_INVOKE_WATCH_MAX_POLLS",ji),ji,86400),u=e.sleep??Jd;let g=e.initialCursor,d=0,h=0,l=0;const E=ei(t,n,"resolved",[Q.OK]),v={schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:"pending",renderedSummaryCount:0,reasonCodes:[Q.WATCH_RENDER_PENDING],publicSafe:!0},w=lt(e.initialCursor,g,g,[],e.initialCursor?[Q.WATCH_CURSOR_UNCHANGED]:[Q.WATCH_NO_SUMMARIES_YET],e.initialCursor?"unchanged":"not_started");ft(ht({watchStatus:"active",active:!0,targetEvidence:E,snapshotEvidence:v,cursorEvidence:w,stopReason:"not_stopped",reasonCodes:[Q.OK]}),e.format,o,e.protectedOutput);let S;try{S=await Za({projectRoot:e.projectRoot,strictReadOnly:e.strictReadOnly})}catch{const b=bt(void 0,[],!1,d,[Q.WATCH_SNAPSHOT_UNAVAILABLE]),_=lt(e.initialCursor,g,g,[],[Q.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),A=ht({watchStatus:"blocked",active:!1,targetEvidence:E,snapshotEvidence:b,cursorEvidence:_,stopReason:"unavailable_evidence",reasonCodes:[Ne.STORE_UNAVAILABLE]});return ft(A,e.format,o,e.protectedOutput),xt("store-unavailable",d,l,A,e.protectedOutput)}try{for(;!e.signal?.aborted&&l<s;){l+=1;const b=g,_=S.collectProcessingOutputSummaryCursor({...g?{cursor:g}:{},...t?{target:t}:{},...n?{jobId:n}:{},limit:i}),A=S.collectSnapshot({jobLimit:50,processingSummaryLimit:1}),K=A.jobs;if(_.summaries.length>0){for(const j of _.summaries)Yd(j,e.format,o,e.protectedOutput),d+=1;g=_.nextCursor??_.summaries[_.summaries.length-1]?.cursor??g,h=0}else g=_.nextCursor??g,h+=1;const re=bt(A,_.summaries,!0,_.summaries.length),Z=lt(e.initialCursor,b,g,_.summaries,_.summaries.length>0?[Q.WATCH_CURSOR_ADVANCED]:[Q.WATCH_NO_SUMMARIES_YET]);if(ft(ht({watchStatus:_.summaries.length>0?"polling":"waiting",active:!0,targetEvidence:E,snapshotEvidence:re,cursorEvidence:Z,stopReason:"not_stopped",reasonCodes:_.summaries.length>0?[Q.WATCH_CURSOR_ADVANCED]:[Q.WATCH_NO_SUMMARIES_YET],generatedAt:A.generatedAt}),e.format,o,e.protectedOutput),!_.hasMore&&qd(K,n,d)){const j=bt(A,_.summaries,!1,d,[Ne.COMPLETED]),ae=lt(e.initialCursor,b,g,_.summaries,[Ne.COMPLETED],"exhausted"),ve=ht({watchStatus:"stopped",active:!1,targetEvidence:E,snapshotEvidence:j,cursorEvidence:ae,stopReason:"not_stopped",reasonCodes:[Ne.COMPLETED],generatedAt:A.generatedAt});return ft(ve,e.format,o,e.protectedOutput),xt("completed",d,l,ve,e.protectedOutput)}if(!_.hasMore&&Kd(K,n,h,a)){const j=bt(A,_.summaries,!1,d,[Q.WATCH_STOP_IDLE_LIMIT_REACHED]),ae=lt(e.initialCursor,b,g,_.summaries,[Q.WATCH_STOP_IDLE_LIMIT_REACHED],"exhausted"),ve=ht({watchStatus:"stopped",active:!1,targetEvidence:E,snapshotEvidence:j,cursorEvidence:ae,stopReason:"idle_limit_reached",reasonCodes:[Ne.IDLE_TIMEOUT,Q.WATCH_STOP_IDLE_LIMIT_REACHED],generatedAt:A.generatedAt});return ft(ve,e.format,o,e.protectedOutput),xt("idle-timeout",d,l,ve,e.protectedOutput)}_.hasMore||await u(r,e.signal)}}catch{const b=bt(void 0,[],!1,d,[Q.WATCH_SNAPSHOT_UNAVAILABLE]),_=lt(e.initialCursor,g,g,[],[Q.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),A=ht({watchStatus:"blocked",active:!1,targetEvidence:E,snapshotEvidence:b,cursorEvidence:_,stopReason:"unavailable_evidence",reasonCodes:[Ne.STORE_UNAVAILABLE]});return ft(A,e.format,o,e.protectedOutput),xt("store-unavailable",d,l,A,e.protectedOutput)}finally{S.close()}if(e.signal?.aborted){const b=bt(void 0,[],!1,d,[Ne.CANCELLED]),_=lt(e.initialCursor,g,g,[],[Ne.CANCELLED],"unavailable"),A=ht({watchStatus:"stopped",active:!1,targetEvidence:E,snapshotEvidence:b,cursorEvidence:_,stopReason:"cancelled",reasonCodes:[Ne.CANCELLED]});return ft(A,e.format,o,e.protectedOutput),xt("cancelled",d,l,A,e.protectedOutput)}const y=bt(void 0,[],!1,d,[Q.WATCH_STOP_MAX_POLLS_REACHED]),N=lt(e.initialCursor,g,g,[],[Q.WATCH_STOP_MAX_POLLS_REACHED],"exhausted"),$=ht({watchStatus:"stopped",active:!1,targetEvidence:E,snapshotEvidence:y,cursorEvidence:N,stopReason:"max_polls_reached",reasonCodes:[Ne.MAX_POLLS,Q.WATCH_STOP_MAX_POLLS_REACHED]});return ft($,e.format,o,e.protectedOutput),xt("max-polls",d,l,$,e.protectedOutput)}function it(e){const t=e.trim().replace(/^@/,"").match(/^(job|goal|loop)-([JGL])(\d{3,})$/i);if(!t)return;const n=t[1].toLowerCase(),o=t[2].toUpperCase();if(!(n==="job"&&o!=="J"||n==="goal"&&o!=="G"||n==="loop"&&o!=="L"))return`${n}-${o}${t[3]}`}function ri(e){if(e.startsWith("job-J"))return"job";if(e.startsWith("goal-G"))return"goal";if(e.startsWith("loop-L"))return"loop"}function Fo(e){const t=[],n=/(?:^|[\s"'([,{])@?(job-[Jj]\d{3,}|goal-[Gg]\d{3,}|loop-[Ll]\d{3,})(?=$|[\s"')\]},.;:!?])/g;let o;for(;(o=n.exec(e))!==null;){const i=it(o[1]);i&&t.push(i)}return ze(t)}function zo(e){return Fo(e)[0]}function wr(e){const t=e?it(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 ni(e){return ze(e.filter(t=>typeof t=="string").map(t=>it(t)).filter(t=>!!t?.startsWith("job-J")))}function ep(e,t){const n=ni(t).filter(o=>o!==e.targetId&&o!==e.jobId);return n.length>0?{...e,relatedJobIds:n}:e}function tp(e){if(!e)return;const t=f(e.target)?e.target:void 0,n=typeof e.selectorKind=="string"?e.selectorKind:typeof t?.selectorKind=="string"?t.selectorKind:void 0,o=typeof e.targetId=="string"?it(e.targetId):typeof t?.targetId=="string"?it(t.targetId):typeof e.targetJobId=="string"?it(e.targetJobId):void 0,i=wr(o);if(!i||n&&n!==i.selectorKind)return;const r=Array.isArray(e.relatedJobIds)?e.relatedJobIds:Array.isArray(t?.relatedJobIds)?t.relatedJobIds:void 0,a=ni([...r??[],e.jobId,t?.jobId,e.targetJobId,t?.targetJobId]).filter(s=>s!==i.targetId&&s!==i.jobId);return{...i,...typeof(e.jobId??t?.jobId)=="string"?{jobId:it(e.jobId??t?.jobId)??i.jobId}:{},...typeof(e.goalId??t?.goalId)=="string"?{goalId:it(e.goalId??t?.goalId)??i.goalId}:{},...typeof(e.loopId??t?.loopId)=="string"?{loopId:it(e.loopId??t?.loopId)??i.loopId}:{},...a.length>0?{relatedJobIds:a}:{}}}function Yo(e){const t=e.trim().split(/\s+/).filter(Boolean),n=t[0]?.replace(/^\*/,"").toLowerCase(),o=t[1]?.replace(/^--/,"").toLowerCase();return(n==="jobs"||n==="job"||n==="continuity-jobs"||n==="61")&&o==="watch"}const Me=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"}),rp=new Set(["create","start","resume"]),np=new Set(["create","resume","run-once"]);function ii(e,t,n,o,i){return{schemaVersion:1,contractVersion:"continuity-v1",...n?{command:n}:{},...o?{operation:o}:{},active:e,...i?{watchToken:i}:{},reasonCodes:ze(t),serverHeldStream:!1,allJobsPolling:!1,targetResolution:e?"required-after-dispatch":"inactive",publicSafe:!0}}function We(e,t=[],n,o){const i=t.length>0?t:[Me.INACTIVE];return{args:e,watch:!1,reasonCodes:i,metadata:ii(!1,i,n,o),publicSafe:!0}}function ip(e){const t=e.trim().split(/\s+/).filter(Boolean),n=t.slice(2).filter(r=>r==="--watch").length;if(n===0)return We(e,[],"jobs","watch");if(n!==1)return We(e,[Me.AMBIGUOUS],"jobs","watch");const o=t.filter((r,a)=>a<2||r!=="--watch").join(" ");return Yo(o)?o.trim().split(/\s+/).filter(Boolean).slice(2).length!==1?We(e,[Me.AMBIGUOUS],"jobs","watch"):zo(o)?{args:o,watch:!0,reasonCodes:[Me.ACTIVE],metadata:ii(!0,[Me.ACTIVE],"jobs","watch"),publicSafe:!0}:We(e,[Me.TARGET_INVALID],"jobs","watch"):We(e,[Me.UNSUPPORTED],"jobs","watch")}function op(e){const t=[];let n=!1,o=0;for(;o<e.length;){for(;o<e.length&&/\s/.test(e[o]);)o+=1;if(o>=e.length)break;const i=o;let r="",a=!1,s=null;for(;o<e.length;){const u=e[o];if(s){if(u===s){a=!0,s=null,o+=1;continue}if(u==="\\"&&o+1<e.length){r+=e[o+1],o+=2;continue}r+=u,o+=1;continue}if(/\s/.test(u))break;if(u==='"'||u==="'"){a=!0,s=u,o+=1;continue}r+=u,o+=1}s&&(n=!0),t.push({value:r,start:i,end:o,quoted:a})}return{tokens:t,malformed:n}}function ap(e){if(!e||e.quoted)return;const t=e.value.replace(/^\*/,"").toLowerCase();return t==="goal"||t==="loop"?t:void 0}function cp(e,t){if(!e||e==="jobs"||!t||t.quoted)return;const n=t.value.toLowerCase();return(e==="goal"?rp:np).has(n)?n:void 0}function sp(e){return!e.quoted&&e.value!=="--watch"&&e.value.toLowerCase().startsWith("--watch")}function dp(e){const{tokens:t,malformed:n}=op(e),o=ap(t[0]),i=cp(o,t[1]);if(n)return We(e,[Me.MALFORMED],o,i);const r=t.filter(l=>l.value==="--watch"&&!l.quoted),a=t.filter(l=>l.value==="--watch"&&l.quoted),s=t.filter(sp);if(!(r.length>0||a.length>0||s.length>0))return We(e,[],o,i);if(r.length>1)return We(e,[Me.DUPLICATE],o,i);if(r.length===1&&(a.length>0||s.length>0))return We(e,[Me.AMBIGUOUS],o,i);if(a.length>0)return We(e,[Me.QUOTED],o,i);if(s.length>0)return We(e,[Me.MALFORMED],o,i);const g=r[0];if(!g)return We(e,[],o,i);if(t[t.length-1]!==g)return We(e,[Me.NON_FINAL],o,i);if(!o||!i)return We(e,[Me.UNRESOLVED],o,i);const d=`${e.slice(0,g.start)}${e.slice(g.end)}`.trim(),h={literal:"--watch",position:"final",start:g.start,end:g.end,quoted:!1,publicSafe:!0};return{args:d,watch:!0,reasonCodes:[Me.ACTIVE],metadata:ii(!0,[Me.ACTIVE],o,i,h),publicSafe:!0}}function pp(e){return Yo(e)?ip(e):dp(e)}function up(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&ks.has(t)):[]}function sr(e){return{disabled:!0,reasonCodes:ze(e.length>0?e:[He.MISSING])}}function oi(e,t,n=[],o){const i=wr(t);if(i)return{source:e,target:ep(i,n),targetJobId:i.targetId,...o?{initialCursor:o}:{},serverHeldStream:!1}}function lp(e){const t=new Map;for(const n of e){const o=`${n.target.selectorKind}:${n.target.targetId}`,i=t.get(o);if(!i){t.set(o,n);continue}const r=ze([...i.target.relatedJobIds??[],...n.target.relatedJobIds??[]]);t.set(o,{...i,target:r.length>0?{...i.target,relatedJobIds:r}:i.target,initialCursor:i.initialCursor??n.initialCursor})}return Array.from(t.values())}function Mt(e,t,n,o){return{source:e,hasEvidence:t,candidates:lp(n.filter(i=>!!i)),...o&&o.length>0?{disabledReasonCodes:ze(o)}:{}}}function hp(e,t){return e.target.selectorKind===t.target.selectorKind&&e.target.targetId===t.target.targetId}function Rr(e,t){const n=ze(e.filter(o=>typeof o=="string").map(o=>it(o)).filter(o=>!!o));if(t){const o=n.find(i=>ri(i)===t);if(o)return o}return n[0]}function an(e,t){return ze(e.filter(n=>typeof n=="string").map(n=>it(n)).filter(n=>!!n)).find(n=>ri(n)===t)}function fp(e){const t=f(e?.continuity)?e.continuity:void 0,n=f(t?.jobs)?t.jobs:void 0,o=f(n?.watcher)?n.watcher:void 0,i=up(o?.reasonCodes??n?.reasonCodes);if(!o)return Mt("watcher-metadata",i.length>0,[],i);if(o.active===!1||i.length>0)return Mt("watcher-metadata",!0,[],i.length>0?i:[He.MALFORMED]);if(o.serverHeldStream!==!1)return Mt("watcher-metadata",!0,[],[He.SERVER_HELD_STREAM]);const r=tp(o);if(!r)return Mt("watcher-metadata",!0,[],[He.MISSING]);const a=typeof o.initialCursor=="string"?o.initialCursor:void 0;return Mt("watcher-metadata",!0,[{source:"watcher-metadata",target:r,targetJobId:r.targetId,...a?{initialCursor:a}:{},serverHeldStream:!1}])}function qo(e,t){const n=f(e.loopJobPlan)?e.loopJobPlan:void 0,o=f(n?.metadata)?n.metadata:void 0,i=f(e.metadata)?e.metadata:void 0,a=(t==="goal"?Rr([e.goalId,e.targetGoalId,e.campaignId,e.jobId,e.targetJobId,i?.goalId,i?.campaignId,i?.jobId],"goal"):Rr([e.loopId,e.targetLoopId,e.jobId,e.targetJobId,i?.loopId,i?.jobId,o?.loopId,o?.jobId],"loop"))??Rr([e.jobId,e.targetJobId,i?.jobId,o?.jobId]);return oi("goal-loop-continuity-metadata",a,[e.jobId,e.targetJobId,i?.jobId,o?.jobId])}function gp(e){const t=f(e?.continuity)?e.continuity:void 0,n=f(t?.goal)?t.goal:void 0,o=f(t?.loop)?t.loop:void 0,i=[n?qo(n,"goal"):void 0,o?qo(o,"loop"):void 0],r=!!(n||o);return Mt("goal-loop-continuity-metadata",r,i,r&&i.every(a=>!a)?[He.MISSING]:void 0)}function mp(e){return Array.isArray(e)?e.filter(f):f(e)?Array.isArray(e.operationLogs)?e.operationLogs.filter(f):f(e.operationLog)?[e.operationLog]:Array.isArray(e.operations)?[e]:[]:[]}function Ko(e,t){const n=f(t.metadata)?t.metadata:void 0,o=an([t.goalId,t.targetGoalId,t.campaignId,n?.goalId,n?.campaignId,t.jobId,n?.jobId],"goal"),i=an([t.loopId,t.targetLoopId,n?.loopId,t.jobId,n?.jobId],"loop"),r=Rr([t.jobId,t.targetJobId,n?.jobId],"job"),a=o??i??r;if(!a)return;const s=e.get(a)??{targetId:a,relatedJobIds:[]};s.relatedJobIds.push(...ni([r,t.jobId,t.targetJobId,n?.jobId])),e.set(a,s)}function yp(e){const t=f(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 Ip(e){const t=f(e.metadata)?e.metadata:void 0;return!!Rr([e.goalId,e.targetGoalId,e.campaignId,e.loopId,e.targetLoopId,e.jobId,e.targetJobId,t?.goalId,t?.campaignId,t?.loopId,t?.jobId])}function Jo(e,t){const n=[];for(const a of["metadata","job","event","receipt","processingOutputSummary"]){const s=t[a];f(s)&&n.push(s)}const o=f(t.event)?t.event:void 0;f(o?.metadata)&&n.push(o.metadata),f(o?.processingOutputSummary)&&n.push(o.processingOutputSummary);const i=f(t.receipt)?t.receipt:void 0;f(i?.metadata)&&n.push(i.metadata);const r=n.some(Ip);for(const a of n)Ko(e,a);(!r||yp(t))&&Ko(e,t)}function Ep(e){const t=mp(e?.continuityStateUpdate),n=new Map;for(const i of t){Jo(n,i);const r=Array.isArray(i.operations)?i.operations.filter(f):[];for(const a of r)Jo(n,a)}const o=Array.from(n.values()).map(i=>oi("continuity-state-update-operation-log",i.targetId,i.relatedJobIds));return Mt("continuity-state-update-operation-log",t.length>0,o,t.length>0&&o.every(i=>!i)?[He.MISSING]:void 0)}function Sp(e){const t=Fo(e);return Mt("explicit-args",t.length>0,t.map(n=>oi("explicit-args",n)))}function vp(e,t){const n=[fp(e),gp(e),Ep(e),Sp(t)];for(let o=0;o<n.length;o+=1){const i=n[o];if(!i.hasEvidence)continue;if(i.disabledReasonCodes&&i.disabledReasonCodes.length>0)return sr(i.disabledReasonCodes);if(i.candidates.length!==1)return sr([i.candidates.length>1?He.AMBIGUOUS:He.MISSING]);const r=i.candidates[0];for(const a of n.slice(o+1)){if(!a.hasEvidence)continue;if(a.disabledReasonCodes&&a.disabledReasonCodes.length>0)return sr(a.disabledReasonCodes);if(a.candidates.length>1)return sr([He.AMBIGUOUS]);const s=a.candidates[0];if(s&&!hp(r,s))return sr([He.CONFLICT])}return{target:r.target,targetJobId:r.targetJobId,...r.initialCursor?{initialCursor:r.initialCursor}:{},source:r.source,serverHeldStream:!1}}return sr([He.MISSING])}async function ai(e,t,n,o={}){const i="/api/v1/invoke";let r,a;const s=await _r(e,i,t,n,{...o,deferSuccessfulJsonParsing:!0,...t.privateExecution?{maxAttempts:1,allowReplayRetry:!1}:{},admitResponseBeforeBodyRead:h=>{const l=h.headers.get("X-Neocortex-Compatibility");if(l!==null)try{if(l.length===0||l.length>8192)throw new Error("header-size");const E=JSON.parse(Buffer.from(l,"base64url").toString("utf8"));if(!zi(E))throw new Error("header-shape");if(r=E,E.status==="incompatible")return a="incompatible",!1}catch{return a="malformed",!1}return o.admitResponseBeforeBodyRead?.(h)??!0}});if(s.networkFailure||!s.response)return{ok:!1,status:0,error:"Network error after bounded retries",networkFailure:s.networkFailure??"transport-error"};if(s.responseAdmissionRejected){const h=a==="malformed"?or.RESULT_MALFORMED:r?.reasonCodes[0]??or.OFFER_MALFORMED;return{ok:!1,status:s.response.status,error:`COMPATIBILITY_INCOMPATIBLE: ${h}`,errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:h,fallback_action:r?.remediationHint??"upgrade-client"},...r?{compatibility:r}:{}}}const{response:u,text:g}=s;let d=s.parsed;try{if(t.compatibility&&!r){if(/"(?:reviewReconciliation|review_reconciliation|reconciliationMetadata|releaseLifecycle|release_lifecycle|releaseBlocked|release_blocked|yoloopReleaseBlocked)"\s*:/u.test(g))return{ok:!1,status:u.status,error:`COMPATIBILITY_INCOMPATIBLE: ${or.UNNEGOTIATED_PROTECTED_FIELD}`,errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:or.UNNEGOTIATED_PROTECTED_FIELD,fallback_action:"upgrade-client"}};r=Rc({clientVersion:t.compatibility.clientVersion,serverVersion:"0.0.0",registryVersion:t.registryVersion,registryChecksum:t.registryChecksum,reason:or.SERVER_NEGOTIATION_MISSING})}if(u.ok)try{d=g?JSON.parse(g):{}}catch{return{ok:!1,status:u.status,error:"COMPATIBILITY_INCOMPATIBLE: response-json-malformed",errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:or.RESULT_MALFORMED},...r?{compatibility:r}:{}}}if(!u.ok){if(t.privateExecution){const E=Ad(d),v=E?.error_code;return{ok:!1,status:u.status,error:typeof v=="string"?v:"private-execution-invoke-unavailable",...E?{errorBody:E}:{}}}return{ok:!1,status:u.status,error:Object.keys(d).length>0?`${d.error_code??"ERROR"}: ${d.message??g}`:`HTTP ${u.status}: ${g}`,errorBody:Object.keys(d).length>0?d:void 0,...r?{compatibility:r}:{}}}const h=d,l=u.headers.get("X-Client-Version-Warning");return l&&!jo&&(jo=!0,process.stderr.write(`
27
27
  [Neocortex] ${l}
28
28
 
29
- `)),{ok:!0,status:u.status,data:h,...r?{compatibility:r}:{}}}catch(h){return{ok:!1,status:0,error:(h instanceof Error?h.message:String(h)).includes("abort")?`Request timeout after ${Xo/1e3}s`:"Network error: invalid response"}}}async function yp(e,t,n){const i=await _r(e,"/api/v1/invoke/private-execution/consume",t,n,{maxAttempts:1,allowReplayRetry:!1});if(i.networkFailure||!i.response||!i.response.ok)throw new Error("private-execution-delivery-unavailable");return i.parsed}async function qi(e,t,n){const i=await _r(e,"/api/v1/invoke/private-execution/cancel",t,n,{maxAttempts:1,allowReplayRetry:!1});return!!i.response?.ok&&i.parsed.status==="cancelled"}async function Ki(e,t,n,i={}){const o=await _r(e,"/api/v1/invoke/epic-claims/acknowledge",{...n,registryVersion:Rt,registryChecksum:wt},t,i);return!!o.response?.ok&&o.parsed.status==="ok"&&o.parsed.claimOutcome===n.status&&(!n.planningCheckpoint||o.parsed.memoryReceiptId===n.planningCheckpoint.memoryReceiptId)}async function Ip(e,t,n){try{const{YoloopClientStateStore:i,deriveYoloopRoundRefusedBeforeSetupReceipt:o}=await import("../yoloop/yoloop-client-state-store.js"),r=o({persisted:n.state,epics:t.epics??{},stories:t.stories??{}});if(!r)return n;const a=new i(e);return await a.recordRoundRefusedBeforeSetup(r)==="unchanged"?n:(process.stderr.write(`[yoloop] yoloop-round-refused-before-setup recorded for the pending authority.
30
- `),await a.readAll())}catch(i){const o=i instanceof Error?i.message.match(/\bYOLOOP_[A-Z0-9_]+\b/)?.[0]??"YOLOOP_ROUND_REFUSED_RECORD_FAILED":"YOLOOP_ROUND_REFUSED_RECORD_FAILED";return process.stderr.write(`[yoloop] ${o}. No refused-round receipt was recorded.
31
- `),n}}async function Ep(e,t,n,i,o,r,a={}){if(!o||!r||!t.epics?.[r])return 0;const s=Yt(e);let u=0;for(const[g,d]of Object.entries(s.operations)){if(d.planningProtocol==="root-staged-v1"||!d.claimId||d.epicId!==r)continue;await Ki(n,i,{claimId:d.claimId,projectId:o,epicId:d.epicId,status:"materialized"},a)&&ss(e,g,d)&&(u+=1)}return u}function Sp(e,t){const n=t.state.pendingContinuationAuthorities,i=t.state.continuationSession;if(t.state.continuationPolicy!=="p205-finite-resume-v2"||n?.length!==1||!i)return;const o=n[0],r=o.certificate,a=r?.expectedTransition;if(o.storyIds!=="[CIRCULAR]"||r?.rank!=="[CIRCULAR]"||a?.selectedStoryIds!=="[CIRCULAR]")return;const s=typeof i.epicId=="string"?i.epicId:"",u=e.epics[s],g=Array.isArray(a.storyLifecycle)?a.storyLifecycle:[],d=g.length===1&&typeof g[0]?.storyId=="string"?g[0].storyId:"",l=e.stories[d]?.checkpoint;if(!u||u.branch_mode!=="epic"||typeof u.execution_branch!="string"||typeof u.origin_branch!="string"||u.branch_lease!==void 0&&u.branch_lease!==null||!l||l.qaVerdict!=="passed"||l.reviewVerdict!=="approved"||!Array.isArray(l.receiptRefs))return;const _=(Array.isArray(u.stories)?u.stories.filter(w=>typeof w=="string"):[]).find(w=>{const S=e.stories[w];return!S||["done","completed","merged"].includes(String(S.status))?!1:(Array.isArray(S.depends_on)?S.depends_on.filter(D=>typeof D=="string"):[]).every(D=>["done","completed","merged"].includes(String(e.stories[D]?.status)))});if(_)return{epicId:s,expectedNextStoryId:_,branchMode:"epic",executionBranch:u.execution_branch,originBranch:u.origin_branch,branchLeaseReleased:!0,checkpoint:{schemaVersion:1,storyId:l.storyId,epicId:l.epicId,branch:l.branch,baseSha:l.baseSha,headSha:l.headSha,receiptRefs:[...l.receiptRefs],qaVerdict:"passed",reviewVerdict:"approved"}}}const io=["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"],Ji=new Set(["done","completed","merged","cancelled","canceled","abandoned"]),Qi=new Set(["skipped-with-debt","documented"]);function Xi(e){return typeof e=="string"?e.trim().toLowerCase().replace(/_/g,"-"):""}function vp(e){const t=Xi(e);if(Ji.has(t)||Qi.has(t))return 0;const n=io.indexOf(t);return n<0?io.length:io.length-1-n}function Cp(e,t){const n=e.epics[t];if(!n||!Array.isArray(n.stories)||n.stories.some(d=>typeof d!="string"||!/^P[1-9][0-9]*\.[0-9]+$/.test(d)))return null;const i=[...n.stories],o=[],r=[];let a=0,s=0;const u=[];for(const d of i){const h=e.stories[d];if(!h||!Array.isArray(h.depends_on)||h.depends_on.some(w=>typeof w!="string"))return null;const l=[...h.depends_on].sort(),E=vp(h.status),_=Xi(h.status);o.push({id:d,dependsOn:l}),r.push({id:d,status:h.status,dependsOn:l}),u.push({storyId:d,remaining:E}),a+=E,!Ji.has(_)&&!Qi.has(_)&&(s+=1)}const g={version:1,policy:"p205-finite-resume-v2",epicId:t,storyIds:i,queueEpicIds:[t],initialEpicIndex:0,graphFingerprint:_t("p205-yoloop-graph-v1",o),lifecycleVersion:"p205-lifecycle-v1",terminalPredicateVersion:"p205-terminal-v1",initialSnapshotFingerprint:_t("p205-yoloop-initial-snapshot-v1",{epicId:t,stories:r}),initialRank:{version:1,queue:0,epic:s,lifecycle:a},initialStoryLifecycle:u};return Object.freeze({...g,sessionId:_t("p205-yoloop-session-v1",g)})}function Zi(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 _p(e){try{return Sn(e.projectRoot)}catch(l){if(!(l instanceof Error)||l.message!=="epic-operational-store-missing")throw l}const t=e.snapshot.epics[e.targetEpicId],n=ar(e.projectRoot,{required:!0}),i=f(n.epics[e.targetEpicId])?n.epics[e.targetEpicId]:void 0,o=_e(i?.execution_branch??t?.execution_branch),r=$n(i?.origin_binding??t?.origin_binding);if(!t||t.branch_mode!=="epic"||!o||!r||r.executionBranch!==o)throw new Error("epic-operational-bootstrap-binding-invalid");const a=i?.graph_revision??t.graph_revision,s=typeof a=="string"&&/^[a-f0-9]{64}$/.test(a)?a:e.targetGraphRevision,u=_t("p224-epic-origin-binding-v1",r),g=await Ta(e.projectRoot,{epicId:e.targetEpicId,executionBranch:o,graphRevision:s,originBindingDigest:u});if(g.blockers.length>0||g.conflicts.length>0)throw new Error(g.blockers[0]??g.conflicts[0]??"epic-operational-approval-invalid");await xa(e.projectRoot,g);let d=Sn(e.projectRoot);if(!Object.values(d.operational.identities).find(l=>l.epicId===e.targetEpicId&&l.executionBranch===o&&l.graphRevision===e.targetGraphRevision)){const l=await ba(e.projectRoot,{identityHash:g.identity.identityHash,expectedRevision:d.document.revision,expectedWriterEpoch:d.operational.writerEpoch},{epicId:e.targetEpicId,executionBranch:o,graphRevision:e.targetGraphRevision,originBindingDigest:u});d={document:l.document,operational:l.operational}}return d}async function wp(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=Cp(e.snapshot,e.targetEpicId);if(!t)throw new Error("yoloop-causal-reconciliation-target-invalid");const n=String(t.graphFingerprint),i=await _p({projectRoot:e.projectRoot,snapshot:e.snapshot,targetEpicId:e.targetEpicId,targetGraphRevision:n}),o=Object.values(i.operational.identities).filter(Y=>Y.epicId===e.targetEpicId&&Y.graphRevision===n);if(o.length!==1)throw new Error("epic-operational-identity-mismatch");const r=e.snapshot.yoloop,a=r?r.lock!==null||r.state.currentSession!==null?"active":"inactive":"unknown",s=Aa({document:i.document,targetIdentityHash:o[0].identityHash,targetEpicId:e.targetEpicId,targetGraphRevision:n,legacyActivity:a});if(s.kind!=="eligible")throw new Error(s.reasonCodes[0]??"yoloop-causal-reconciliation-ineligible");const u=i.operational,g=u.yoloop.state.continuationSession,d=u.yoloop.state.pendingContinuationAuthorities??[],h=u.yoloop.state.runControl;if(!g||typeof g.sessionId!="string"||!h||!["success","exhausted"].includes(h.status)||d.length>1)throw new Error("yoloop-causal-reconciliation-preimage-invalid");const l=_t("p224-common-continuation-session-v1",u.yoloop.state.continuationSession??null),E=_t("p224-common-pending-authorities-v1",d),_=_t("p224-common-continuation-session-v1",t),w=_t("p224-invoke-session-recovery-v1",{identityHash:o[0].identityHash,originalInputSha256:e.originalInputSha256,canonicalInputSha256:e.canonicalInputSha256,expectedSessionHash:l,expectedPendingHash:E,nextSessionHash:_,runId:h.runId,runRevision:h.revision}),S={operationId:`p224rec-${w.slice(0,32)}`,idempotencyKey:`p224rec-${w.slice(0,32)}`,expectedCommonRevision:i.document.revision,expectedWriterEpoch:u.writerEpoch,expectedIdentityHash:o[0].identityHash,sourceEpicId:s.evidence.sourceEpicId,sourceGraphRevision:s.evidence.sourceGraphRevision,targetEpicId:e.targetEpicId,targetGraphRevision:n,expectedRunId:h.runId,expectedRunStatus:h.status,expectedRunRevision:h.revision,expectedSnapshotHash:h.latestSnapshotHash,sourceSessionId:g.sessionId,expectedSessionHash:l,expectedPendingHash:E,expectedPendingCount:d.length,nextSession:t,nextSessionHash:_},y=Ra(S),D={schemaVersion:"YoloopCrossEpicReconciliationReceipt/1.0",operationId:S.operationId,idempotencyKey:S.idempotencyKey,payloadHash:y,sourceEpicId:S.sourceEpicId,sourceGraphRevision:S.sourceGraphRevision,targetEpicId:S.targetEpicId,targetGraphRevision:S.targetGraphRevision,runId:S.expectedRunId,previousSessionHash:l,nextSessionHash:_,retiredAuthorityHash:E,retiredAuthorityCount:S.expectedPendingCount,outcome:"cross-epic-reconciled",publicSafe:!0},U={type:"reconcile_cross_epic_continuation",...S,payloadHash:y,receipt:D};await wa(e.projectRoot,U);const b=Sn(e.projectRoot),C=b.operational.yoloop.state.pendingContinuationAuthorities??[];if(!b.operational.reconciliationReceipts.find(Y=>Y.payloadHash===y)||C.length!==0||_t("p224-common-continuation-session-v1",b.operational.yoloop.state.continuationSession??null)!==_)throw new Error("yoloop-causal-reconciliation-postimage-unverified");return Object.freeze({outcome:"applied",payloadHash:y,retryCount:1,publicSafe:!0})}catch(t){return Object.freeze({outcome:"blocked",reasonCode:Zi(t),retryCount:0,publicSafe:!0})}}const Rp=/^\*yolo @docs\/stories\/[A-Za-z0-9][A-Za-z0-9._-]{0,79}\.story\.md story-worktree-phase-1$/,ea=9e4,ta=6,Ap=1e3;function bp(e){return typeof e=="string"&&Rp.test(e)&&!e.includes("..")}function xp(e){const t=e.metadata?.storyWorktreePhase;if(!e.success||!t||typeof t!="object"||Array.isArray(t))return;const n=t;return n.decision==="spec-barrier-waiting"&&n.phase==="phase-1"?n:void 0}async function Tp(e,t,n={}){const i=n.sleep??(g=>new Promise(d=>setTimeout(d,g))),o=n.now??Date.now,r=Math.max(1,Math.min(n.maxAttempts??ta,ta)),a=Math.max(0,Math.min(n.maxWaitMs??ea,ea)),s=o();let u=0;for(;;){const g=await t(e);u+=1;const d=xp(g);if(!d)return g;const h=typeof d.maxWaitMs=="number"&&Number.isFinite(d.maxWaitMs)?d.maxWaitMs:0,l=Math.min(a,Math.max(0,h)),E=typeof d.retryAfterMs=="number"&&Number.isFinite(d.retryAfterMs)?d.retryAfterMs:0,_=Math.min(Math.max(E,Ap),l),w=o()-s;if(u>=r||w+_>l)return{success:!0,instructions:`# Story-worktree spec barrier timeout
29
+ `)),{ok:!0,status:u.status,data:h,...r?{compatibility:r}:{}}}catch(h){return{ok:!1,status:0,error:(h instanceof Error?h.message:String(h)).includes("abort")?`Request timeout after ${eo/1e3}s`:"Network error: invalid response"}}}async function Cp(e,t,n){const o=await _r(e,"/api/v1/invoke/private-execution/consume",t,n,{maxAttempts:1,allowReplayRetry:!1});if(o.networkFailure||!o.response||!o.response.ok)throw new Error("private-execution-delivery-unavailable");return o.parsed}async function Qo(e,t,n){const o=await _r(e,"/api/v1/invoke/private-execution/cancel",t,n,{maxAttempts:1,allowReplayRetry:!1});return!!o.response?.ok&&o.parsed.status==="cancelled"}async function Xo(e,t,n,o={}){const i=await _r(e,"/api/v1/invoke/epic-claims/acknowledge",{...n,registryVersion:Rt,registryChecksum:wt},t,o);return!!i.response?.ok&&i.parsed.status==="ok"&&i.parsed.claimOutcome===n.status&&(!n.planningCheckpoint||i.parsed.memoryReceiptId===n.planningCheckpoint.memoryReceiptId)}async function _p(e,t,n){try{const{YoloopClientStateStore:o,deriveYoloopRoundRefusedBeforeSetupReceipt:i}=await import("../yoloop/yoloop-client-state-store.js"),r=i({persisted:n.state,epics:t.epics??{},stories:t.stories??{}});if(!r)return n;const a=new o(e);return await a.recordRoundRefusedBeforeSetup(r)==="unchanged"?n:(process.stderr.write(`[yoloop] yoloop-round-refused-before-setup recorded for the pending authority.
30
+ `),await a.readAll())}catch(o){const i=o instanceof Error?o.message.match(/\bYOLOOP_[A-Z0-9_]+\b/)?.[0]??"YOLOOP_ROUND_REFUSED_RECORD_FAILED":"YOLOOP_ROUND_REFUSED_RECORD_FAILED";return process.stderr.write(`[yoloop] ${i}. No refused-round receipt was recorded.
31
+ `),n}}async function wp(e,t,n,o,i,r,a={}){if(!i||!r||!t.epics?.[r])return 0;const s=Yt(e);let u=0;for(const[g,d]of Object.entries(s.operations)){if(d.planningProtocol==="root-staged-v1"||!d.claimId||d.epicId!==r)continue;await Xo(n,o,{claimId:d.claimId,projectId:i,epicId:d.epicId,status:"materialized"},a)&&hs(e,g,d)&&(u+=1)}return u}function Rp(e,t){const n=t.state.pendingContinuationAuthorities,o=t.state.continuationSession;if(t.state.continuationPolicy!=="p205-finite-resume-v2"||n?.length!==1||!o)return;const i=n[0],r=i.certificate,a=r?.expectedTransition;if(i.storyIds!=="[CIRCULAR]"||r?.rank!=="[CIRCULAR]"||a?.selectedStoryIds!=="[CIRCULAR]")return;const s=typeof o.epicId=="string"?o.epicId:"",u=e.epics[s],g=Array.isArray(a.storyLifecycle)?a.storyLifecycle:[],d=g.length===1&&typeof g[0]?.storyId=="string"?g[0].storyId:"",l=e.stories[d]?.checkpoint;if(!u||u.branch_mode!=="epic"||typeof u.execution_branch!="string"||typeof u.origin_branch!="string"||u.branch_lease!==void 0&&u.branch_lease!==null||!l||l.qaVerdict!=="passed"||l.reviewVerdict!=="approved"||!Array.isArray(l.receiptRefs))return;const v=(Array.isArray(u.stories)?u.stories.filter(w=>typeof w=="string"):[]).find(w=>{const S=e.stories[w];return!S||["done","completed","merged"].includes(String(S.status))?!1:(Array.isArray(S.depends_on)?S.depends_on.filter(N=>typeof N=="string"):[]).every(N=>["done","completed","merged"].includes(String(e.stories[N]?.status)))});if(v)return{epicId:s,expectedNextStoryId:v,branchMode:"epic",executionBranch:u.execution_branch,originBranch:u.origin_branch,branchLeaseReleased:!0,checkpoint:{schemaVersion:1,storyId:l.storyId,epicId:l.epicId,branch:l.branch,baseSha:l.baseSha,headSha:l.headSha,receiptRefs:[...l.receiptRefs],qaVerdict:"passed",reviewVerdict:"approved"}}}const ci=["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"],Zo=new Set(["done","completed","merged","cancelled","canceled","abandoned"]),ea=new Set(["skipped-with-debt","documented"]);function ta(e){return typeof e=="string"?e.trim().toLowerCase().replace(/_/g,"-"):""}function Ap(e){const t=ta(e);if(Zo.has(t)||ea.has(t))return 0;const n=ci.indexOf(t);return n<0?ci.length:ci.length-1-n}function bp(e,t){const n=e.epics[t];if(!n||!Array.isArray(n.stories)||n.stories.some(d=>typeof d!="string"||!/^P[1-9][0-9]*\.[0-9]+$/.test(d)))return null;const o=[...n.stories],i=[],r=[];let a=0,s=0;const u=[];for(const d of o){const h=e.stories[d];if(!h||!Array.isArray(h.depends_on)||h.depends_on.some(w=>typeof w!="string"))return null;const l=[...h.depends_on].sort(),E=Ap(h.status),v=ta(h.status);i.push({id:d,dependsOn:l}),r.push({id:d,status:h.status,dependsOn:l}),u.push({storyId:d,remaining:E}),a+=E,!Zo.has(v)&&!ea.has(v)&&(s+=1)}const g={version:1,policy:"p205-finite-resume-v2",epicId:t,storyIds:o,queueEpicIds:[t],initialEpicIndex:0,graphFingerprint:_t("p205-yoloop-graph-v1",i),lifecycleVersion:"p205-lifecycle-v1",terminalPredicateVersion:"p205-terminal-v1",initialSnapshotFingerprint:_t("p205-yoloop-initial-snapshot-v1",{epicId:t,stories:r}),initialRank:{version:1,queue:0,epic:s,lifecycle:a},initialStoryLifecycle:u};return Object.freeze({...g,sessionId:_t("p205-yoloop-session-v1",g)})}function ra(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 xp(e){try{return Sn(e.projectRoot)}catch(l){if(!(l instanceof Error)||l.message!=="epic-operational-store-missing")throw l}const t=e.snapshot.epics[e.targetEpicId],n=ar(e.projectRoot,{required:!0}),o=f(n.epics[e.targetEpicId])?n.epics[e.targetEpicId]:void 0,i=_e(o?.execution_branch??t?.execution_branch),r=Hn(o?.origin_binding??t?.origin_binding);if(!t||t.branch_mode!=="epic"||!i||!r||r.executionBranch!==i)throw new Error("epic-operational-bootstrap-binding-invalid");const a=o?.graph_revision??t.graph_revision,s=typeof a=="string"&&/^[a-f0-9]{64}$/.test(a)?a:e.targetGraphRevision,u=_t("p224-epic-origin-binding-v1",r),g=await Na(e.projectRoot,{epicId:e.targetEpicId,executionBranch:i,graphRevision:s,originBindingDigest:u});if(g.blockers.length>0||g.conflicts.length>0)throw new Error(g.blockers[0]??g.conflicts[0]??"epic-operational-approval-invalid");await Oa(e.projectRoot,g);let d=Sn(e.projectRoot);if(!Object.values(d.operational.identities).find(l=>l.epicId===e.targetEpicId&&l.executionBranch===i&&l.graphRevision===e.targetGraphRevision)){const l=await ka(e.projectRoot,{identityHash:g.identity.identityHash,expectedRevision:d.document.revision,expectedWriterEpoch:d.operational.writerEpoch},{epicId:e.targetEpicId,executionBranch:i,graphRevision:e.targetGraphRevision,originBindingDigest:u});d={document:l.document,operational:l.operational}}return d}async function Tp(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=bp(e.snapshot,e.targetEpicId);if(!t)throw new Error("yoloop-causal-reconciliation-target-invalid");const n=String(t.graphFingerprint),o=await xp({projectRoot:e.projectRoot,snapshot:e.snapshot,targetEpicId:e.targetEpicId,targetGraphRevision:n}),i=Object.values(o.operational.identities).filter(K=>K.epicId===e.targetEpicId&&K.graphRevision===n);if(i.length!==1)throw new Error("epic-operational-identity-mismatch");const r=e.snapshot.yoloop,a=r?r.lock!==null||r.state.currentSession!==null?"active":"inactive":"unknown",s=Pa({document:o.document,targetIdentityHash:i[0].identityHash,targetEpicId:e.targetEpicId,targetGraphRevision:n,legacyActivity:a});if(s.kind!=="eligible")throw new Error(s.reasonCodes[0]??"yoloop-causal-reconciliation-ineligible");const u=o.operational,g=u.yoloop.state.continuationSession,d=u.yoloop.state.pendingContinuationAuthorities??[],h=u.yoloop.state.runControl;if(!g||typeof g.sessionId!="string"||!h||!["success","exhausted"].includes(h.status)||d.length>1)throw new Error("yoloop-causal-reconciliation-preimage-invalid");const l=_t("p224-common-continuation-session-v1",u.yoloop.state.continuationSession??null),E=_t("p224-common-pending-authorities-v1",d),v=_t("p224-common-continuation-session-v1",t),w=_t("p224-invoke-session-recovery-v1",{identityHash:i[0].identityHash,originalInputSha256:e.originalInputSha256,canonicalInputSha256:e.canonicalInputSha256,expectedSessionHash:l,expectedPendingHash:E,nextSessionHash:v,runId:h.runId,runRevision:h.revision}),S={operationId:`p224rec-${w.slice(0,32)}`,idempotencyKey:`p224rec-${w.slice(0,32)}`,expectedCommonRevision:o.document.revision,expectedWriterEpoch:u.writerEpoch,expectedIdentityHash:i[0].identityHash,sourceEpicId:s.evidence.sourceEpicId,sourceGraphRevision:s.evidence.sourceGraphRevision,targetEpicId:e.targetEpicId,targetGraphRevision:n,expectedRunId:h.runId,expectedRunStatus:h.status,expectedRunRevision:h.revision,expectedSnapshotHash:h.latestSnapshotHash,sourceSessionId:g.sessionId,expectedSessionHash:l,expectedPendingHash:E,expectedPendingCount:d.length,nextSession:t,nextSessionHash:v},y=Ta(S),N={schemaVersion:"YoloopCrossEpicReconciliationReceipt/1.0",operationId:S.operationId,idempotencyKey:S.idempotencyKey,payloadHash:y,sourceEpicId:S.sourceEpicId,sourceGraphRevision:S.sourceGraphRevision,targetEpicId:S.targetEpicId,targetGraphRevision:S.targetGraphRevision,runId:S.expectedRunId,previousSessionHash:l,nextSessionHash:v,retiredAuthorityHash:E,retiredAuthorityCount:S.expectedPendingCount,outcome:"cross-epic-reconciled",publicSafe:!0},$={type:"reconcile_cross_epic_continuation",...S,payloadHash:y,receipt:N};await xa(e.projectRoot,$);const b=Sn(e.projectRoot),_=b.operational.yoloop.state.pendingContinuationAuthorities??[];if(!b.operational.reconciliationReceipts.find(K=>K.payloadHash===y)||_.length!==0||_t("p224-common-continuation-session-v1",b.operational.yoloop.state.continuationSession??null)!==v)throw new Error("yoloop-causal-reconciliation-postimage-unverified");return Object.freeze({outcome:"applied",payloadHash:y,retryCount:1,publicSafe:!0})}catch(t){return Object.freeze({outcome:"blocked",reasonCode:ra(t),retryCount:0,publicSafe:!0})}}const Pp=/^\*yolo @docs\/stories\/[A-Za-z0-9][A-Za-z0-9._-]{0,79}\.story\.md story-worktree-phase-1$/,na=9e4,ia=6,kp=1e3;function Op(e){return typeof e=="string"&&Pp.test(e)&&!e.includes("..")}function Np(e){const t=e.metadata?.storyWorktreePhase;if(!e.success||!t||typeof t!="object"||Array.isArray(t))return;const n=t;return n.decision==="spec-barrier-waiting"&&n.phase==="phase-1"?n:void 0}async function Dp(e,t,n={}){const o=n.sleep??(g=>new Promise(d=>setTimeout(d,g))),i=n.now??Date.now,r=Math.max(1,Math.min(n.maxAttempts??ia,ia)),a=Math.max(0,Math.min(n.maxWaitMs??na,na)),s=i();let u=0;for(;;){const g=await t(e);u+=1;const d=Np(g);if(!d)return g;const h=typeof d.maxWaitMs=="number"&&Number.isFinite(d.maxWaitMs)?d.maxWaitMs:0,l=Math.min(a,Math.max(0,h)),E=typeof d.retryAfterMs=="number"&&Number.isFinite(d.retryAfterMs)?d.retryAfterMs:0,v=Math.min(Math.max(E,kp),l),w=i()-s;if(u>=r||w+v>l)return{success:!0,instructions:`# Story-worktree spec barrier timeout
32
32
 
33
33
  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.
34
34
 
35
- [STORY_WORKTREE_SPEC_BARRIER_TIMEOUT]`,metadata:{...g.metadata,storyWorktreePhase:{...d,decision:"spec-barrier-timeout",reasonCode:"spec-barrier-waiting",resumable:!0,attempts:u,waitedMs:Math.max(0,w),publicSafe:!0}},exitCode:0};await i(_)}}function Pp(e,t){if(e===null||typeof e!="object"||Array.isArray(e)||typeof t!="string"||!/^[a-f0-9]{64}$/.test(t))return e;const n=e;return Object.keys(n).length!==3?e:{schemaVersion:2,storyId:n.storyId,specDigest:n.specDigest,graphRevision:n.graphRevision,specInputDigest:t}}async function kp(e,t){const n=t.metadata?.storyWorktreePhase;if(!t.success||!n||typeof n!="object"||Array.isArray(n))return;const i=n,o=Pp(i.specAcceptance,i.specInputDigest),r=i.phaseOneReceipt,a=typeof i.storyId=="string"?i.storyId:void 0,s=a&&/^P[0-9]{1,12}\./.test(a)?a.split(".")[0]:void 0;if(!(!s||o===void 0&&r===void 0))try{await zo(e,u=>{Mc(u,s,{...o!==void 0?{specAcceptances:[o]}:{},...r!==void 0?{receipts:[r]}:{}})})}catch(u){const g=u instanceof Error&&/^[a-z0-9-]{1,80}$/.test(u.message)?u.message:"story-worktree-evidence-persist-failed";process.stderr.write(`[Neocortex] story-worktree evidence not persisted (${g}); the root must re-dispatch this phase-1 prompt.
36
- `)}}async function Op(e){return ui(e.args,await Np(e))}async function Np(e){const t=Ia(e.args),n=t.ok?/^\*yolo @docs\/stories\/(P[1-9][0-9]*(?:\.[0-9]+)+)\.story\.md story-worktree-phase-2$/.exec(t.args):null;if(n){let o=e.projectRoot??process.cwd();const r=await cn(e,h=>{o=h}),a=r.metadata?.storyWorktreePhase;if(!f(a)||a.decision!=="refused"||a.reasonCode!=="story-worktree-sync-required"||a.phase!=="phase-2"||a.storyId!==n[1]||a.publicSafe!==!0||!f(a.dependencyReleaseDirective)||a.dependencyReleaseDirective.directiveId!==a.releaseDirectiveId||a.dependencyReleaseDirective.graphRevision!==a.graphRevision||a.dependencyReleaseDirective.releasedStepId!==a.stepId||a.dependencyReleaseDirective.storyId!==a.storyId)return r;const{StoryWorktreeManager:s}=await import("../git/story-worktree-manager.js"),u=new s({projectRoot:o}),g=await u.assertPhaseTwo({storyId:n[1]});if(!g.ok||g.value.headSha===a.dependencyReleaseDirective.integratedEpicHeadSha)return r;const d=await u.sync({leaseId:g.value.leaseId,directive:a.dependencyReleaseDirective,automatic:!0});return d.ok?cn(e):{...r,metadata:{...r.metadata,storyWorktreeSync:{reasonCode:d.reasonCode,publicSafe:!0}}}}if(!t.ok||!bp(t.args))return cn(e);let i=e.projectRoot??process.cwd();return Tp(e.args,async()=>{const o=await cn(e,r=>{i=r});return await kp(i,o),o})}async function cn(e,t){let n;try{if(n=e.inputEnvelope??Ft(e.inputSource??"args",e.args),pc(n),n.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=n.rawArgs,o=Er(n);let r=i,a=o,s;try{const c=So(r,{absoluteRoot:e.projectRoot});if(!c.ok)return process.stderr.write(`${c.message} reason=${c.reasonCode}
35
+ [STORY_WORKTREE_SPEC_BARRIER_TIMEOUT]`,metadata:{...g.metadata,storyWorktreePhase:{...d,decision:"spec-barrier-timeout",reasonCode:"spec-barrier-waiting",resumable:!0,attempts:u,waitedMs:Math.max(0,w),publicSafe:!0}},exitCode:0};await o(v)}}function Lp(e,t){if(e===null||typeof e!="object"||Array.isArray(e)||typeof t!="string"||!/^[a-f0-9]{64}$/.test(t))return e;const n=e;return Object.keys(n).length!==3?e:{schemaVersion:2,storyId:n.storyId,specDigest:n.specDigest,graphRevision:n.graphRevision,specInputDigest:t}}async function jp(e,t){const n=t.metadata?.storyWorktreePhase;if(!t.success||!n||typeof n!="object"||Array.isArray(n))return;const o=n,i=Lp(o.specAcceptance,o.specInputDigest),r=o.phaseOneReceipt,a=typeof o.storyId=="string"?o.storyId:void 0,s=a&&/^P[0-9]{1,12}\./.test(a)?a.split(".")[0]:void 0;if(!(!s||i===void 0&&r===void 0))try{await qi(e,u=>{Hc(u,s,{...i!==void 0?{specAcceptances:[i]}:{},...r!==void 0?{receipts:[r]}:{}})})}catch(u){const g=u instanceof Error&&/^[a-z0-9-]{1,80}$/.test(u.message)?u.message:"story-worktree-evidence-persist-failed";process.stderr.write(`[Neocortex] story-worktree evidence not persisted (${g}); the root must re-dispatch this phase-1 prompt.
36
+ `)}}async function Mp(e){return fo(e.args,await Vp(e))}async function Vp(e){const t=va(e.args),n=t.ok?/^\*yolo @docs\/stories\/(P[1-9][0-9]*(?:\.[0-9]+)+)\.story\.md story-worktree-phase-2$/.exec(t.args):null;if(n){let i=e.projectRoot??process.cwd();const r=await cn(e,h=>{i=h}),a=r.metadata?.storyWorktreePhase;if(!f(a)||a.decision!=="refused"||a.reasonCode!=="story-worktree-sync-required"||a.phase!=="phase-2"||a.storyId!==n[1]||a.publicSafe!==!0||!f(a.dependencyReleaseDirective)||a.dependencyReleaseDirective.directiveId!==a.releaseDirectiveId||a.dependencyReleaseDirective.graphRevision!==a.graphRevision||a.dependencyReleaseDirective.releasedStepId!==a.stepId||a.dependencyReleaseDirective.storyId!==a.storyId)return r;const{StoryWorktreeManager:s}=await import("../git/story-worktree-manager.js"),u=new s({projectRoot:i}),g=await u.assertPhaseTwo({storyId:n[1]});if(!g.ok||g.value.headSha===a.dependencyReleaseDirective.integratedEpicHeadSha)return r;const d=await u.sync({leaseId:g.value.leaseId,directive:a.dependencyReleaseDirective,automatic:!0});return d.ok?cn(e):{...r,metadata:{...r.metadata,storyWorktreeSync:{reasonCode:d.reasonCode,publicSafe:!0}}}}if(!t.ok||!Op(t.args))return cn(e);let o=e.projectRoot??process.cwd();return Dp(e.args,async()=>{const i=await cn(e,r=>{o=r});return await jp(o,i),i})}async function cn(e,t){let n;try{if(n=e.inputEnvelope??Ft(e.inputSource??"args",e.args),fc(n),n.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 o=n.rawArgs,i=Er(n);let r=o,a=i,s;try{const c=vi(r,{absoluteRoot:e.projectRoot});if(!c.ok)return process.stderr.write(`${c.message} reason=${c.reasonCode}
37
37
  `),{success:!1,error:c.message,errorCode:c.errorCode,metadata:{[c.errorCode==="INVALID_YOLO_TARGET"?"yoloTargetNormalization":"yoloopTargetNormalization"]:{reasonCode:c.reasonCode,publicSafe:!0}},exitCode:1};c.changed&&(r=c.args,c.reasonCodes.includes("absolute-target-root-canonicalized")&&(s=c.args),a=Er(Ft(n.source,r)),process.stderr.write(`[Neocortex] yoloop target normalized: ${c.reasonCodes.join(",")}
38
38
  `),c.reasonCodes.includes("workflow-advisory-root-only")&&process.stderr.write(`[Neocortex] Workflow guidance stays with the root agent in the original request. The server receives only the canonical target and any admitted options or story modifier.
39
39
  `))}catch{const c="INVALID_YOLOOP_TARGET: yoloop target normalization was unavailable; no request was sent.";return process.stderr.write(`${c}
40
- `),{success:!1,error:c,errorCode:"INVALID_YOLOOP_TARGET",exitCode:1}}let u=Dn(r),g;if(u.outcome!=="resolved"){const c=ws(r);c.kind==="canonicalized"&&(r=c.canonicalArgs,a=Er(Ft(n.source,r)),g=c.binding,u=Dn(r))}if(u.outcome!=="resolved"){const c=hc(u,"client"),p=u.outcome==="malformed_input"?u.reason==="input_limit"||u.reason==="token_limit"||u.reason==="token_size_limit"?"input-limit-exceeded":u.reason==="invalid_control"||u.reason==="invalid_surrogate"?"invalid-control-character":u.reason==="unterminated_quote"||u.reason==="trailing_escape"||u.reason==="unsupported_escape"?"unterminated-quote":void 0:void 0,I=p?{code:"INVOCATION_MALFORMED_INPUT",reason:p,source:n.source,byteLength:n.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_${u.outcome.toUpperCase()}`,errorCode:`INVOCATION_${u.outcome.toUpperCase()}`,metadata:{invocationAdmission:c,...I?{invocationInput:I}:{}},exitCode:1}}if(r!==i&&(e={...e,args:r}),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};let d;try{d=await di(e.projectRoot)}catch(c){const p=c instanceof Error&&/^project-root-[a-z-]+$/.test(c.message)?c.message:"project-root-resolution-failed";return{success:!1,error:p,errorCode:p,metadata:{projectRoot:{reasonCode:p,publicSafe:!0}},exitCode:1}}if(e={...e,projectRoot:d},s!==void 0){const c=So(i,{absoluteRoot:d,verifyAbsolutePhysical:!0});if(!c.ok||c.args!==s)return{success:!1,error:c.ok?"INVALID_YOLOOP_TARGET: the absolute Markdown target no longer matches the admitted project root.":c.message,errorCode:"INVALID_YOLOOP_TARGET",metadata:{yoloopTargetNormalization:{reasonCode:"markdown-link-target-unsafe-path",publicSafe:!0}},exitCode:1}}t?.(d);const h=u.selection.commandId,l=h==="yolo"&&!ko(r,h)?Kc(r):null,E=h==="tech-debt"&&u.selection.positionals.length===0&&(u.selection.operationId==="scan"&&Object.keys(u.selection.options).length===0||u.selection.operationId===void 0&&u.selection.options.scan===!0&&Object.keys(u.selection.options).length===1),_=ka.find(c=>c.id===h),w=_?.subcommands.find(c=>c.id===u.selection.operationId),S=w?w.policy.strictReadOnly==="allow":_?.policy.strictReadOnly==="allow",y=h==="diagnose",D=e.diagnoseScopedContinuation===!0&&y;let U,b;if(y)try{U=$r({strictReadOnly:!0});const c=(e.serverUrl??U?.serverUrl??bo).replace(/\/+$/,"");b=await Id(c,U?.licenseKey),b.outcome==="refreshed"&&process.stderr.write(`[Neocortex] diagnose-auth-refreshed-before-strict. Continuing in strict read-only mode.
41
- `)}catch{b={schemaVersion:1,outcome:"deferred",reasonCode:"diagnose-auth-refresh-deferred",publicSafe:!0}}let C;try{C=ac({invocationId:Mr(),intent:e.strictReadOnly||y?{schemaVersion:1,policy:nc,registryVersion:Rt,registryChecksum:wt}:void 0,registryVersion:Rt,registryChecksum:wt,registryAllowsStrict:S,requestCanonicalBytes:JSON.stringify({command:h})})}catch(c){if(c instanceof Wt)return{success:!1,error:c.code,errorCode:c.code,exitCode:1};throw c}{C.beginProjection();for(const c of Bo)C.project(c);for(const c of oc)C.project(c);C.seal()}const A=C.mode==="strict";if(h==="create-epic"||h==="idea-diagnose")try{const c=wc(d);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 An?c.code:"PROJECT_IDENTITY_MIGRATION_STATE_CORRUPT";return{success:!1,error:p,errorCode:p,exitCode:1}}const Y=e.environment??process.env;if(e.privateExecutionBeta&&(h!=="yolo"&&h!=="research"&&h!=="write-spec"&&h!=="create-tasks"&&h!=="implement"&&h!=="exec"&&h!=="create-epic"&&h!=="idea-diagnose"&&h!=="idea-research"&&h!=="generate-epic"&&h!=="sync-openapi"&&h!=="chaos-plan"&&h!=="ui-ux-review"&&h!=="arch-prd"&&h!=="arch-architecture"&&h!=="arch-fitness-functions"&&h!=="arch-api-contracts"&&h!=="arch-api-integrations"&&h!=="arch-database"&&h!=="arch-security"&&h!=="arch-design-system"&&h!=="arch-performance"&&h!=="arch-testing"&&h!=="arch-infrastructure"&&h!=="arch-review"&&h!=="update-memory"&&h!=="arch-ux-design"&&h!=="generate-pacts"&&h!=="property-test"&&!E||A||e.platformTarget!==void 0&&Rn(e.platformTarget)===void 0))return{success:!1,error:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",errorCode:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",exitCode:1};const Z=Mo({cwd:d,env:Y,targetFlag:e.platformTarget}),Q=e.privateExecutionBeta&&e.platformTarget===void 0&&Rn(Z.targetId)===void 0?Mo({cwd:d,env:Y,targetFlag:"codex"}):Z,j=Q.targetId,ae=e.privateExecutionBeta?Rn(j):void 0;if(e.privateExecutionBeta&&ae===void 0)return{success:!1,error:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",errorCode:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",exitCode:1};const ve=e.privateExecutionBeta?void 0:Xa({cwd:d,env:Y,targetFlag:e.platformTarget,nativeHostVersion:Ns(Q,Y)},Q);if(l)try{Gn(d,{allowMissingRuntime:!0})}catch(c){const p=c instanceof ut?c.reasonCode:"git-lifecycle-state-corrupt";if(p!=="git-lifecycle-state-missing"||g||!vo(d,r,{preview:!0}))return process.stderr.write(`[Neocortex] ${p}. No request was sent; repair the canonical project state/runtime sidecar and retry.
42
- `),{success:!1,error:p,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}let be=l?$r({strictReadOnly:!0}):y?U:Pi(C);const T=(e.serverUrl??be?.serverUrl??bo).replace(/\/+$/,"");let ee,Ce=!1;if(l){const c=await Yc(T);if(Ce=c.supported&&c.projectManifestProjection===!0,!c.supported)return{success:!1,error:`YOLO_INVOKE_ENVELOPE_CAPABILITY_UNAVAILABLE: target server does not advertise ${ec}; 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{ee=Yo({projectRoot:d,storyId:l,epicId:l.split(".")[0],inputSha256:a.sha256,onOmittedReferences:p=>process.stderr.write(`[Neocortex] yolo-spec-supporting-references-omitted count=${p}; core story artifacts preserved.
43
- `)})}catch(p){const I=Ko(p);return{success:!1,error:I,errorCode:I,exitCode:1}}be=Pi(C)}if(h!=="migrate-project-id"&&C.execute({phase:"client-preflight",domain:"client-persistence",category:"first-run-marker",operation:"create"},()=>ps(),()=>{}),h==="migrate-project-id"){const c=await Rc(T);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 I;try{I=_c(d)}catch(N){const se=N instanceof An?N.code:"PROJECT_IDENTITY_MIGRATION_PREPARE_FAILED";return{success:!1,error:se,errorCode:se,exitCode:1}}p.push(or({phase:"prepare",outcome:I.changed&&I.document.phase==="prepared"?"prepared":"retry",floor:I.document.legacyEpicFloor,licenseId:"local-client",projectId:I.document.projectId}));const R=Zr(d);if(R.config.project_id!==I.document.projectId)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",errorCode:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",metadata:{invocationDiagnostics:p},exitCode:1};const O=await Oi(T,be?.licenseKey,C);if(O.status!=="authenticated"){const N=O.status==="refresh-required",se=N?tn(O.cause):void 0;return se?en("authentication",se,{invocationDiagnostics:p}):{success:!1,error:N?ki(O):"Not authenticated. Visit https://neocortex.sh/portal/login to get your license key, then run: neocortex activate YOUR-LICENSE-KEY",errorCode:N?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",metadata:{invocationDiagnostics:p,...N?{auth:{cause:O.cause,action:O.action,publicSafe:!0}}:{}},exitCode:N?1:2}}let W;try{W=Po(e.args.trim(),R)}catch(N){const se=N instanceof Oo?N.code:"PROJECT_IDENTITY_MIGRATION_PROJECTION_FAILED";return{success:!1,error:se,errorCode:se,metadata:{invocationDiagnostics:p},exitCode:1}}let te={args:i,projectRoot:d.replace(yr(),"~"),stateSnapshot:W,platformTarget:j,...ve?{nativeHostAttestation:ve}:{},projectId:I.document.projectId,projectIdentityMigration:I.request,inputEvidence:o,idempotencyKey:I.document.operationId,registryVersion:Rt,registryChecksum:wt,compatibility:jn()};try{te=Jn(te).body}catch(N){if(N instanceof Mn||N instanceof Vn)return{success:!1,error:N.message,errorCode:N.code,metadata:{invokePayload:N.telemetry,invocationDiagnostics:p},exitCode:1};throw N}const V=await wn("invoke-query",()=>oo(T,te,O.token,{refreshToken:()=>O.client.forceRefresh()}));if(!V.ok||!V.data)return p.push(or({phase:"seed",outcome:"rejected",floor:I.document.legacyEpicFloor,licenseId:"local-client",projectId:I.document.projectId})),{success:!1,error:nt(V.error??"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",zt),errorCode:typeof V.errorBody?.error_code=="string"?V.errorBody.error_code:"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",metadata:{invocationDiagnostics:p},exitCode:V.status===401?2:1};const ne=V.data.metadata?.projectIdentityMigration;try{uc(ne),p.push(or({phase:"seed",outcome:ne.status,floor:ne.acceptedLegacyFloor,licenseId:"local-client",projectId:ne.projectId})),vc(d,ne),p.push(or({phase:"remote-acknowledged",outcome:ne.status,floor:ne.acceptedLegacyFloor,licenseId:"local-client",projectId:ne.projectId})),Cc(d,ne),p.push(or({phase:"finalize",outcome:"finalized",floor:ne.acceptedLegacyFloor,licenseId:"local-client",projectId:ne.projectId}))}catch(N){p.push(or({phase:"reconcile",outcome:"rejected",floor:I.document.legacyEpicFloor,licenseId:"local-client",projectId:I.document.projectId}));const se=N instanceof An?N.code:N instanceof Error?N.message:"PROJECT_IDENTITY_MIGRATION_RECEIPT_INVALID";return{success:!1,error:se,errorCode:se,metadata:{invocationDiagnostics:p},exitCode:1}}return C.complete(),{success:!0,instructions:V.data.instructions,metadata:{...V.data.metadata,...V.compatibility?{compatibility:V.compatibility}:{},invocationDiagnostics:p},exitCode:0}}try{const{normalizeYoloopTargetArgs:c}=await import("../yoloop/target-normalization.js"),p=c(r,{projectRoot:g?void 0:d});if(!p.ok)return process.stderr.write(`${p.message} reason=${p.reasonCode}
44
- `),{success:!1,error:p.message,errorCode:p.errorCode,metadata:{yoloopTargetNormalization:{reasonCode:p.reasonCode,publicSafe:!0}},exitCode:1};if(p.changed){const I=Dn(p.args);if(I.outcome!=="resolved"||I.selection.commandId!==h){const R="INVOCATION_CANONICAL_TARGET_CONFLICT";return process.stderr.write(`${R}. No request was sent.
40
+ `),{success:!1,error:c,errorCode:"INVALID_YOLOOP_TARGET",exitCode:1}}let u=jn(r),g;if(u.outcome!=="resolved"){const c=Ts(r);c.kind==="canonicalized"&&(r=c.canonicalArgs,a=Er(Ft(n.source,r)),g=c.binding,u=jn(r))}if(u.outcome!=="resolved"){const c=Ic(u,"client"),p=u.outcome==="malformed_input"?u.reason==="input_limit"||u.reason==="token_limit"||u.reason==="token_size_limit"?"input-limit-exceeded":u.reason==="invalid_control"||u.reason==="invalid_surrogate"?"invalid-control-character":u.reason==="unterminated_quote"||u.reason==="trailing_escape"||u.reason==="unsupported_escape"?"unterminated-quote":void 0:void 0,I=p?{code:"INVOCATION_MALFORMED_INPUT",reason:p,source:n.source,byteLength:n.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_${u.outcome.toUpperCase()}`,errorCode:`INVOCATION_${u.outcome.toUpperCase()}`,metadata:{invocationAdmission:c,...I?{invocationInput:I}:{}},exitCode:1}}if(r!==o&&(e={...e,args:r}),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};let d;try{d=await lo(e.projectRoot)}catch(c){const p=c instanceof Error&&/^project-root-[a-z-]+$/.test(c.message)?c.message:"project-root-resolution-failed";return{success:!1,error:p,errorCode:p,metadata:{projectRoot:{reasonCode:p,publicSafe:!0}},exitCode:1}}if(e={...e,projectRoot:d},s!==void 0){const c=vi(o,{absoluteRoot:d,verifyAbsolutePhysical:!0});if(!c.ok||c.args!==s)return{success:!1,error:c.ok?"INVALID_YOLOOP_TARGET: the absolute Markdown target no longer matches the admitted project root.":c.message,errorCode:"INVALID_YOLOOP_TARGET",metadata:{yoloopTargetNormalization:{reasonCode:"markdown-link-target-unsafe-path",publicSafe:!0}},exitCode:1}}t?.(d);const h=u.selection.commandId,l=h==="yolo"&&!Oi(r,h)?es(r):null,E=h==="tech-debt"&&u.selection.positionals.length===0&&(u.selection.operationId==="scan"&&Object.keys(u.selection.options).length===0||u.selection.operationId===void 0&&u.selection.options.scan===!0&&Object.keys(u.selection.options).length===1),v=La.find(c=>c.id===h),w=v?.subcommands.find(c=>c.id===u.selection.operationId),S=w?w.policy.strictReadOnly==="allow":v?.policy.strictReadOnly==="allow",y=h==="diagnose",N=e.diagnoseScopedContinuation===!0&&y;let $,b;if(y)try{$=$r({strictReadOnly:!0});const c=(e.serverUrl??$?.serverUrl??xi).replace(/\/+$/,"");b=await _d(c,$?.licenseKey),b.outcome==="refreshed"&&process.stderr.write(`[Neocortex] diagnose-auth-refreshed-before-strict. Continuing in strict read-only mode.
41
+ `)}catch{b={schemaVersion:1,outcome:"deferred",reasonCode:"diagnose-auth-refresh-deferred",publicSafe:!0}}let _;try{_=pc({invocationId:Mr(),intent:e.strictReadOnly||y?{schemaVersion:1,policy:cc,registryVersion:Rt,registryChecksum:wt}:void 0,registryVersion:Rt,registryChecksum:wt,registryAllowsStrict:S,requestCanonicalBytes:JSON.stringify({command:h})})}catch(c){if(c instanceof Wt)return{success:!1,error:c.code,errorCode:c.code,exitCode:1};throw c}{_.beginProjection();for(const c of $i)_.project(c);for(const c of sc)_.project(c);_.seal()}const A=_.mode==="strict";if(h==="create-epic"||h==="idea-diagnose")try{const c=Tc(d);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 xn?c.code:"PROJECT_IDENTITY_MIGRATION_STATE_CORRUPT";return{success:!1,error:p,errorCode:p,exitCode:1}}const K=e.environment??process.env;if(e.privateExecutionBeta&&(h!=="yolo"&&h!=="research"&&h!=="write-spec"&&h!=="create-tasks"&&h!=="implement"&&h!=="exec"&&h!=="create-epic"&&h!=="idea-diagnose"&&h!=="idea-research"&&h!=="generate-epic"&&h!=="sync-openapi"&&h!=="chaos-plan"&&h!=="ui-ux-review"&&h!=="arch-prd"&&h!=="arch-architecture"&&h!=="arch-fitness-functions"&&h!=="arch-api-contracts"&&h!=="arch-api-integrations"&&h!=="arch-database"&&h!=="arch-security"&&h!=="arch-design-system"&&h!=="arch-performance"&&h!=="arch-testing"&&h!=="arch-infrastructure"&&h!=="arch-review"&&h!=="update-memory"&&h!=="arch-ux-design"&&h!=="generate-pacts"&&h!=="property-test"&&!E||A||e.platformTarget!==void 0&&An(e.platformTarget)===void 0))return{success:!1,error:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",errorCode:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",exitCode:1};const re=Vi({cwd:d,env:K,targetFlag:e.platformTarget}),Z=e.privateExecutionBeta&&e.platformTarget===void 0&&An(re.targetId)===void 0?Vi({cwd:d,env:K,targetFlag:"codex"}):re,j=Z.targetId,ae=e.privateExecutionBeta?An(j):void 0;if(e.privateExecutionBeta&&ae===void 0)return{success:!1,error:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",errorCode:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",exitCode:1};const ve=e.privateExecutionBeta?void 0:rc({cwd:d,env:K,targetFlag:e.platformTarget,nativeHostVersion:Vs(Z,K)},Z);if(l)try{Fn(d,{allowMissingRuntime:!0})}catch(c){const p=c instanceof ut?c.reasonCode:"git-lifecycle-state-corrupt";if(p!=="git-lifecycle-state-missing"||g||!Ci(d,r,{preview:!0}))return process.stderr.write(`[Neocortex] ${p}. No request was sent; repair the canonical project state/runtime sidecar and retry.
42
+ `),{success:!1,error:p,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}let be=l?$r({strictReadOnly:!0}):y?$:No(_);const T=(e.serverUrl??be?.serverUrl??xi).replace(/\/+$/,"");let ne,Ce=!1;if(l){const c=await Xc(T);if(Ce=c.supported&&c.projectManifestProjection===!0,!c.supported)return{success:!1,error:`YOLO_INVOKE_ENVELOPE_CAPABILITY_UNAVAILABLE: target server does not advertise ${ic}; 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{ne=Ki({projectRoot:d,storyId:l,epicId:l.split(".")[0],inputSha256:a.sha256,onOmittedReferences:p=>process.stderr.write(`[Neocortex] yolo-spec-supporting-references-omitted count=${p}; core story artifacts preserved.
43
+ `)})}catch(p){const I=Qi(p);return{success:!1,error:I,errorCode:I,exitCode:1}}be=No(_)}if(h!=="migrate-project-id"&&_.execute({phase:"client-preflight",domain:"client-persistence",category:"first-run-marker",operation:"create"},()=>gs(),()=>{}),h==="migrate-project-id"){const c=await Pc(T);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 I;try{I=xc(d)}catch(L){const F=L instanceof xn?L.code:"PROJECT_IDENTITY_MIGRATION_PREPARE_FAILED";return{success:!1,error:F,errorCode:F,exitCode:1}}p.push(ir({phase:"prepare",outcome:I.changed&&I.document.phase==="prepared"?"prepared":"retry",floor:I.document.legacyEpicFloor,licenseId:"local-client",projectId:I.document.projectId}));const R=Zr(d);if(R.config.project_id!==I.document.projectId)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",errorCode:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",metadata:{invocationDiagnostics:p},exitCode:1};const O=await Lo(T,be?.licenseKey,_);if(O.status!=="authenticated"){const L=O.status==="refresh-required",F=L?tn(O.cause):void 0;return F?en("authentication",F,{invocationDiagnostics:p}):{success:!1,error:L?Do(O):"Not authenticated. Visit https://neocortex.sh/portal/login to get your license key, then run: neocortex activate YOUR-LICENSE-KEY",errorCode:L?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",metadata:{invocationDiagnostics:p,...L?{auth:{cause:O.cause,action:O.action,publicSafe:!0}}:{}},exitCode:L?1:2}}let U;try{U=ki(e.args.trim(),R)}catch(L){const F=L instanceof Ni?L.code:"PROJECT_IDENTITY_MIGRATION_PROJECTION_FAILED";return{success:!1,error:F,errorCode:F,metadata:{invocationDiagnostics:p},exitCode:1}}let ee={args:o,projectRoot:d.replace(yr(),"~"),stateSnapshot:U,platformTarget:j,...ve?{nativeHostAttestation:ve}:{},projectId:I.document.projectId,projectIdentityMigration:I.request,inputEvidence:i,idempotencyKey:I.document.operationId,registryVersion:Rt,registryChecksum:wt,compatibility:Vn()};try{ee=Xn(ee).body}catch(L){if(L instanceof Bn||L instanceof $n)return{success:!1,error:L.message,errorCode:L.code,metadata:{invokePayload:L.telemetry,invocationDiagnostics:p},exitCode:1};throw L}const Y=await wn("invoke-query",()=>ai(T,ee,O.token,{refreshToken:()=>O.client.forceRefresh()}));if(!Y.ok||!Y.data)return p.push(ir({phase:"seed",outcome:"rejected",floor:I.document.legacyEpicFloor,licenseId:"local-client",projectId:I.document.projectId})),{success:!1,error:nt(Y.error??"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",zt),errorCode:typeof Y.errorBody?.error_code=="string"?Y.errorBody.error_code:"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",metadata:{invocationDiagnostics:p},exitCode:Y.status===401?2:1};const G=Y.data.metadata?.projectIdentityMigration;try{gc(G),p.push(ir({phase:"seed",outcome:G.status,floor:G.acceptedLegacyFloor,licenseId:"local-client",projectId:G.projectId})),Ac(d,G),p.push(ir({phase:"remote-acknowledged",outcome:G.status,floor:G.acceptedLegacyFloor,licenseId:"local-client",projectId:G.projectId})),bc(d,G),p.push(ir({phase:"finalize",outcome:"finalized",floor:G.acceptedLegacyFloor,licenseId:"local-client",projectId:G.projectId}))}catch(L){p.push(ir({phase:"reconcile",outcome:"rejected",floor:I.document.legacyEpicFloor,licenseId:"local-client",projectId:I.document.projectId}));const F=L instanceof xn?L.code:L instanceof Error?L.message:"PROJECT_IDENTITY_MIGRATION_RECEIPT_INVALID";return{success:!1,error:F,errorCode:F,metadata:{invocationDiagnostics:p},exitCode:1}}return _.complete(),{success:!0,instructions:Y.data.instructions,metadata:{...Y.data.metadata,...Y.compatibility?{compatibility:Y.compatibility}:{},invocationDiagnostics:p},exitCode:0}}try{const{normalizeYoloopTargetArgs:c}=await import("../yoloop/target-normalization.js"),p=c(r,{projectRoot:g?void 0:d});if(!p.ok)return process.stderr.write(`${p.message} reason=${p.reasonCode}
44
+ `),{success:!1,error:p.message,errorCode:p.errorCode,metadata:{yoloopTargetNormalization:{reasonCode:p.reasonCode,publicSafe:!0}},exitCode:1};if(p.changed){const I=jn(p.args);if(I.outcome!=="resolved"||I.selection.commandId!==h){const R="INVOCATION_CANONICAL_TARGET_CONFLICT";return process.stderr.write(`${R}. No request was sent.
45
45
  `),{success:!1,error:R,errorCode:R,exitCode:1}}e={...e,args:p.args},r=p.args,a=Er(Ft(n.source,r)),process.stderr.write(`[Neocortex] yoloop target normalized: ${p.reasonCodes.join(",")}
46
46
  `)}}catch{const c="INVALID_YOLOOP_TARGET: yoloop target normalization was unavailable; no request was sent.";return process.stderr.write(`${c}
47
- `),{success:!1,error:c,errorCode:"INVALID_YOLOOP_TARGET",exitCode:1}}const xe=wi(h);if(xe)try{(h==="yoloop"||l)&&!g&&!Ct(q(d,".neocortex","state.json"))&&(C.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>vo(d,r),()=>!1)?process.stderr.write(`[Neocortex] git-lifecycle-state-restored-from-head.
48
- `):h==="yoloop"&&j==="runner"&&await C.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},async()=>(await import("../yoloop/runner-first-use.js")).initializeRunnerProjectFromPlanning(d,r),async()=>!1)&&process.stderr.write(`[Neocortex] Initialized v4 project state from committed epic planning.
49
- `)),Gn(d,{allowMissingRuntime:!0}).runtimeMissing&&(await C.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},async()=>kc(d),async()=>{}),Gn(d))}catch(c){const p=c instanceof ut?c.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${p}. No request was sent; repair the canonical project state and retry.
50
- `),{success:!1,error:p,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}if(h!=="migrate-state")try{C.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>Ba(d,{args:e.args,canonicalCommandId:h}),()=>{})}catch(c){if(c instanceof Ua)return process.stderr.write(`${c.message}
47
+ `),{success:!1,error:c,errorCode:"INVALID_YOLOOP_TARGET",exitCode:1}}const xe=bo(h);if(xe)try{(h==="yoloop"||l)&&!g&&!Ct(J(d,".neocortex","state.json"))&&(_.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>Ci(d,r),()=>!1)?process.stderr.write(`[Neocortex] git-lifecycle-state-restored-from-head.
48
+ `):h==="yoloop"&&j==="runner"&&await _.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},async()=>(await import("../yoloop/runner-first-use.js")).initializeRunnerProjectFromPlanning(d,r),async()=>!1)&&process.stderr.write(`[Neocortex] Initialized v4 project state from committed epic planning.
49
+ `)),Fn(d,{allowMissingRuntime:!0}).runtimeMissing&&(await _.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},async()=>jc(d),async()=>{}),Fn(d))}catch(c){const p=c instanceof ut?c.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${p}. No request was sent; repair the canonical project state and retry.
50
+ `),{success:!1,error:p,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}if(h!=="migrate-state")try{_.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>Ga(d,{args:e.args,canonicalCommandId:h}),()=>{})}catch(c){if(c instanceof Fa)return process.stderr.write(`${c.message}
51
51
  `),{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.
52
- `),{success:!1,error:p,exitCode:1}}let ie;if(e.privateExecutionBeta&&(h==="sync-openapi"||h==="chaos-plan"||h==="arch-prd"||h==="arch-architecture"||h==="arch-fitness-functions"||h==="arch-api-contracts"||h==="arch-api-integrations"||h==="arch-database"||h==="arch-security"||h==="arch-design-system"||h==="arch-performance"||h==="arch-testing"||h==="arch-infrastructure"||h==="arch-review"||h==="update-memory"||h==="arch-ux-design"||h==="generate-pacts"||h==="property-test"||E))try{const{capturePrivateProjectStepBaseline:c}=await import("../private-execution/isolated-workspace.js");ie=c(d)}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,d)}catch{}let B;try{let c=await xi(d,e.args,h);try{await hd({projectRoot:d,args:e.args,commandId:h,epicAuthorities:c.epicAuthorities})}catch{process.stderr.write(`[Neocortex] epic-lifecycle-evidence-production-failed. Epic lifecycle evidence remains fail-closed.
53
- `)}let p;if(h==="yoloop"||h==="yolo"){const I={},R=await C.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},async()=>(await import("../git/published-story-reconciliation.js")).reconcilePublishedWorkflowState(d,r,{captureTransientAuthority:(W,te)=>{I[W]=te}}),async()=>{});p=R?.reconciliations;const O=R?.checkpoint;if(O?.status==="pending"){const W=h==="yoloop"?"YOLOOP_PUBLISHED_CHECKPOINT_PENDING":"YOLO_PUBLISHED_CHECKPOINT_PENDING",te=O.reasonCode==="direct-yolo-recovery-root-governance-unverified"?"Root review must verify the project-memory and epic changes against the published commit.":"Resolve the checkpoint recovery reason and resume the same target.",V=`${W}: ${O.storyId} at ${O.headSha} (${O.reasonCode}). ${te} No replacement story task was dispatched.`;return process.stderr.write(`[Neocortex] ${V}
54
- `),{success:!1,error:V,errorCode:W,metadata:{publishedCheckpoint:O},exitCode:1}}O?.status==="recovered"&&(c={...c,authorities:{...c.authorities,...I}},process.stderr.write(`[Neocortex] Published checkpoint recovered: ${O.storyId} at ${O.headSha}.
55
- `))}B=Zr(d,{epicAware:xe,p205Authorities:c.authorities,publishedStoryReconciliations:p,p205AuthorityDiagnostics:c.diagnostics,verifyPlanningGeneration:e.privateExecutionBeta&&h==="create-epic"})}catch(c){const p=c instanceof ut?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.
52
+ `),{success:!1,error:p,exitCode:1}}let ce;if(e.privateExecutionBeta&&(h==="sync-openapi"||h==="chaos-plan"||h==="arch-prd"||h==="arch-architecture"||h==="arch-fitness-functions"||h==="arch-api-contracts"||h==="arch-api-integrations"||h==="arch-database"||h==="arch-security"||h==="arch-design-system"||h==="arch-performance"||h==="arch-testing"||h==="arch-infrastructure"||h==="arch-review"||h==="update-memory"||h==="arch-ux-design"||h==="generate-pacts"||h==="property-test"||E))try{const{capturePrivateProjectStepBaseline:c}=await import("../private-execution/isolated-workspace.js");ce=c(d)}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,d)}catch{}let V;try{let c=await ko(d,e.args,h);try{await Id({projectRoot:d,args:e.args,commandId:h,epicAuthorities:c.epicAuthorities})}catch{process.stderr.write(`[Neocortex] epic-lifecycle-evidence-production-failed. Epic lifecycle evidence remains fail-closed.
53
+ `)}let p;if(h==="yoloop"||h==="yolo"){const I={},R=await _.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},async()=>(await import("../git/published-story-reconciliation.js")).reconcilePublishedWorkflowState(d,r,{captureTransientAuthority:(U,ee)=>{I[U]=ee}}),async()=>{});p=R?.reconciliations;const O=R?.checkpoint;if(O?.status==="pending"){const U=h==="yoloop"?"YOLOOP_PUBLISHED_CHECKPOINT_PENDING":"YOLO_PUBLISHED_CHECKPOINT_PENDING",ee=O.reasonCode==="direct-yolo-recovery-root-governance-unverified"?"Root review must verify the project-memory and epic changes against the published commit.":"Resolve the checkpoint recovery reason and resume the same target.",Y=`${U}: ${O.storyId} at ${O.headSha} (${O.reasonCode}). ${ee} No replacement story task was dispatched.`;return process.stderr.write(`[Neocortex] ${Y}
54
+ `),{success:!1,error:Y,errorCode:U,metadata:{publishedCheckpoint:O},exitCode:1}}O?.status==="recovered"&&(c={...c,authorities:{...c.authorities,...I}},process.stderr.write(`[Neocortex] Published checkpoint recovered: ${O.storyId} at ${O.headSha}.
55
+ `))}V=Zr(d,{epicAware:xe,p205Authorities:c.authorities,publishedStoryReconciliations:p,p205AuthorityDiagnostics:c.diagnostics,verifyPlanningGeneration:e.privateExecutionBeta&&h==="create-epic"})}catch(c){const p=c instanceof ut?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.
56
56
  `),{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:d,logger:{info:I=>process.stderr.write(`${I}
57
57
  `),warn:I=>process.stderr.write(`${I}
58
58
  `)}};c(p),p.args!==e.args&&(e={...e,args:p.args},r=p.args,a=Er(Ft(n.source,r)))}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.
59
- `)}try{const{readYoloopForRequest:c}=await import("../yoloop/invoke-hooks.js");let p=await c(e.args,d);if(p&&(p=await Ip(d,B,p)),p){const I=Sp(B,p);B.yoloop=I?{...p,continuationRecoveryEvidence:I}:p}}catch(c){if(/^\s*\*?(?:yoloop|auto-yolo|epic-runner|story-runner|loop-yolo|auto-epic)\b/i.test(e.args)){const I=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] ${I}. No yoloop request was sent.
60
- `),{success:!1,error:I,errorCode:I,exitCode:1}}}try{const{readContinuityForRequest:c}=await import("../continuity/invoke-hooks.js"),p=await c(e.args,d,void 0,C,{includeExistingStore:!y});p&&(B.continuity=p)}catch(c){if(c instanceof Wt)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.
61
- `)}try{const{maybeRunDiscoveryHook:c}=await import("../yoloop/invoke-hooks.js");await c({args:e.args,projectRoot:d,stateSnapshot:B,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.
62
- `)}try{const{readArchitecturePolicy:c}=await import("../policy/architecture-policy.js"),p=await c(d);p&&(B.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"),I=await p({args:e.args,projectRoot:d,featureFlag:c,logger:{warn:R=>process.stderr.write(`${R}
63
- `)}});I.applied&&I.metadata&&(B.graphRetrieval=I.metadata)}catch(c){const p=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] graph retrieval hook failed: ${p}. Proceeding without enrichment.
64
- `)}try{if(Ps(e.args)){const{collectProjectEvidence:c}=await import("../evidence/collector.js"),p=u.selection.uiUxReview?.architectureDir,I=c({projectRoot:d,...p?{candidatePaths:[p],includeFallbackInventory:!0}:{}});(I.evidence.length>0||I.exclusions.length>0)&&(B.projectEvidence=I)}}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.
59
+ `)}try{const{readYoloopForRequest:c}=await import("../yoloop/invoke-hooks.js");let p=await c(e.args,d);if(p&&(p=await _p(d,V,p)),p){const I=Rp(V,p);V.yoloop=I?{...p,continuationRecoveryEvidence:I}:p}}catch(c){if(/^\s*\*?(?:yoloop|auto-yolo|epic-runner|story-runner|loop-yolo|auto-epic)\b/i.test(e.args)){const I=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] ${I}. No yoloop request was sent.
60
+ `),{success:!1,error:I,errorCode:I,exitCode:1}}}try{const{readContinuityForRequest:c}=await import("../continuity/invoke-hooks.js"),p=await c(e.args,d,void 0,_,{includeExistingStore:!y});p&&(V.continuity=p)}catch(c){if(c instanceof Wt)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.
61
+ `)}try{const{maybeRunDiscoveryHook:c}=await import("../yoloop/invoke-hooks.js");await c({args:e.args,projectRoot:d,stateSnapshot:V,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.
62
+ `)}try{const{readArchitecturePolicy:c}=await import("../policy/architecture-policy.js"),p=await c(d);p&&(V.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"),I=await p({args:e.args,projectRoot:d,featureFlag:c,logger:{warn:R=>process.stderr.write(`${R}
63
+ `)}});I.applied&&I.metadata&&(V.graphRetrieval=I.metadata)}catch(c){const p=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] graph retrieval hook failed: ${p}. Proceeding without enrichment.
64
+ `)}try{if(Ls(e.args)){const{collectProjectEvidence:c}=await import("../evidence/collector.js"),p=u.selection.uiUxReview?.architectureDir,I=c({projectRoot:d,...p?{candidatePaths:[p],includeFallbackInventory:!0}:{}});(I.evidence.length>0||I.exclusions.length>0)&&(V.projectEvidence=I)}}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.
65
65
  `)}if(h==="yoloop"&&j==="claude-code"){const{ensureClaudeWorktreeBaseRef:c}=await import("../agent/claude-worktree-base.js"),p=c();p.action==="applied"?process.stderr.write(`[yoloop] claude-worktree-baseref-applied: Claude Code worktree.baseRef set to "head" for v4 story worktrees.
66
66
  `):(p.reasonCode==="claude-worktree-baseref-user-value-kept"||p.reasonCode==="claude-settings-invalid")&&process.stderr.write(`[yoloop] ${p.reasonCode}: v4 story worktrees start from the remote default branch; set Claude Code worktree.baseRef to "head".
67
- `)}if(h==="yoloop"||h==="yolo"){const c=td(d,B.epics??{},B.stories??{},Hn(r));c&&(B.storyWorktreeReadiness=c),c?.governanceMode==="runtime-store"&&ed(d,j==="runner"&&h==="yoloop"?Hn(r):void 0)}try{const c=await C.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"checkpoint-consume",operation:"consume"},async()=>{const{readAndConsumeCheckpoint:p}=await import("../checkpoint/index.js");return p(d)},async()=>{});c&&(B.implementCheckpoint=c)}catch(c){const p=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] checkpoint hook failed: ${p}. Proceeding without checkpoint.
68
- `)}const Je=h==="menu"&&!e.privateExecutionBeta&&be?.licenseKey?new Ir({cacheDir:vr,passphrase:be.licenseKey,strictReadOnly:A}):null,me=r.trim();if(Je){const c=await C.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>gd(Je),async()=>null);if(c)return C.complete(),{success:!0,instructions:c.instructions,metadata:c.metadata,exitCode:0}}const $=await Oi(T,be?.licenseKey,C);if($.status!=="authenticated"){const c=$.status==="refresh-required",p=b?.connectionFailure??(c?tn($.cause):void 0);if(p)return en("authentication",p,b?{diagnoseAuthPreparation:b}:void 0);const I=!c&&be&&!be.licenseKey?" This may be caused by a machine fingerprint change (e.g., hardware or hostname change).":"";try{const R=Ur(),O=c?xo($.cause,R):Cn("NOT_CONFIGURED",R);O&&process.stderr.write(_n(O,R))}catch{}return{success:!1,error:c?ki($):`Not authenticated.${I} 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",...c?{metadata:{auth:{cause:$.cause,action:$.action,publicSafe:!0},...b?{diagnoseAuthPreparation:b}:{}}}:{},exitCode:c?1:2}}const ye=B.config.project_id,gt=h==="finalize-epic"?Yn(r):h==="yoloop"||h==="yolo"?Hn(r):void 0;try{await C.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Ep(d,B,T,$.token,ye,gt,{refreshToken:()=>$.client.forceRefresh()}),async()=>0)}catch{}const et=Dp(me);if(et&&!y)try{const c=await $.tierClient.preFlightCheck(et);if(!c.allowed)return process.stderr.write(`[neocortex] ${c.message}
69
- `),{success:!1,error:c.message??"Trigger not available on your plan",exitCode:1}}catch{}const fe=await jd({args:me,projectRoot:d,platformTarget:j,environment:e.environment??process.env,bootstrapper:e.runnerBootstrapper,effectAuthority:C});if(fe.attachToRequest&&(B.runnerBootstrap=fe.metadata),fe.warning&&process.stderr.write(`[Neocortex] ${fe.warning}
67
+ `)}if(h==="yoloop"||h==="yolo"){const c=ad(d,V.epics??{},V.stories??{},Wn(r));c&&(V.storyWorktreeReadiness=c),c?.governanceMode==="runtime-store"&&od(d,j==="runner"&&h==="yoloop"?Wn(r):void 0)}try{const c=await _.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"checkpoint-consume",operation:"consume"},async()=>{const{readAndConsumeCheckpoint:p}=await import("../checkpoint/index.js");return p(d)},async()=>{});c&&(V.implementCheckpoint=c)}catch(c){const p=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] checkpoint hook failed: ${p}. Proceeding without checkpoint.
68
+ `)}const Ke=h==="menu"&&!e.privateExecutionBeta&&be?.licenseKey?new Ir({cacheDir:vr,passphrase:be.licenseKey,strictReadOnly:A}):null,me=r.trim();if(Ke){const c=await _.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>Sd(Ke),async()=>null);if(c)return _.complete(),{success:!0,instructions:c.instructions,metadata:c.metadata,exitCode:0}}const B=await Lo(T,be?.licenseKey,_);if(B.status!=="authenticated"){const c=B.status==="refresh-required",p=b?.connectionFailure??(c?tn(B.cause):void 0);if(p)return en("authentication",p,b?{diagnoseAuthPreparation:b}:void 0);const I=!c&&be&&!be.licenseKey?" This may be caused by a machine fingerprint change (e.g., hardware or hostname change).":"";try{const R=Ur(),O=c?Ti(B.cause,R):Cn("NOT_CONFIGURED",R);O&&process.stderr.write(_n(O,R))}catch{}return{success:!1,error:c?Do(B):`Not authenticated.${I} 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",...c?{metadata:{auth:{cause:B.cause,action:B.action,publicSafe:!0},...b?{diagnoseAuthPreparation:b}:{}}}:{},exitCode:c?1:2}}const ye=V.config.project_id,gt=h==="finalize-epic"?Kn(r):h==="yoloop"||h==="yolo"?Wn(r):void 0;try{await _.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>wp(d,V,T,B.token,ye,gt,{refreshToken:()=>B.client.forceRefresh()}),async()=>0)}catch{}const et=Bp(me);if(et&&!y)try{const c=await B.tierClient.preFlightCheck(et);if(!c.allowed)return process.stderr.write(`[neocortex] ${c.message}
69
+ `),{success:!1,error:c.message??"Trigger not available on your plan",exitCode:1}}catch{}const fe=await Ud({args:me,projectRoot:d,platformTarget:j,environment:e.environment??process.env,bootstrapper:e.runnerBootstrapper,effectAuthority:_});if(fe.attachToRequest&&(V.runnerBootstrap=fe.metadata),fe.warning&&process.stderr.write(`[Neocortex] ${fe.warning}
70
70
  `),!fe.shouldContinue)return fe.error&&process.stderr.write(`[Neocortex] ${fe.error}
71
- `),{success:!1,error:fe.error??"Runner auto-bootstrap required but failed.",errorCode:fe.errorCode,exitCode:fe.exitCode??1};if(fe.metadata.command==="runner"&&(fe.metadata.operation==="status"||fe.metadata.operation==="doctor"))try{const c=e.runnerObserver??qa;B.runnerOperationalStatus=await c(fe.metadata.operation,{projectRoot:d,env:e.environment??process.env,effectAuthority:C})}catch{}let L;try{const c=Va(me,B);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}
72
- `),{success:!1,error:p,errorCode:c.code,metadata:{stateProjection:c,publicSafe:!0},exitCode:1}}L=c?.snapshot??Po(me,B),Br(me)==="migrate-state"&&(L={...L,migrationAuthority:Ha(d)})}catch(c){if(c instanceof Ga)return{success:!1,error:c.reasonCode,errorCode:c.reasonCode,exitCode:1};if(c instanceof Oo){const p=`${c.code}: structural projection failed closed; select a valid target or repair the dependency DAG.`;return process.stderr.write(`${p}
73
- `),{success:!1,error:p,errorCode:c.code,metadata:{structuralProjection:{...c.publicDetails,publicSafe:!0}},exitCode:1}}throw c}if(!A)try{const{openNativeAgentPrivateStore:c,resolveNativeAgentPrivateRuntimePaths:p}=await import("../continuity/native-agent-store.js"),I=p(d);if(Ct(I.databasePath)){const R=await c(d);try{const O=h==="yoloop"&&j==="runner",W=O?R.store.listUnsettledNativeAgentDispatches(21):R.store.listRecentNativeAgentDispatches(20);if(O&&W.length>20)throw new Error("native-dispatch-observation-limit");if(W.length>0&&(L.nativeAgentDispatches=W,O)){const{observeExpiredNativeWorktreeCustody:te}=await import("../continuity/native-worktree-custody.js"),V=await te(d,W);V.length>0&&(L.nativeAgentExpiredWorktrees=V)}}finally{R.store.close()}}}catch(c){if(h==="yoloop"&&j==="runner"){const p=pi(c);return{success:!1,exitCode:1,errorCode:"YOLOOP_NATIVE_CUSTODY_UNVERIFIED",error:`The runner could not verify whether existing native story workers are settled. ${p.remediation}`,metadata:{nativeCustody:p}}}}const H=Br(me);let Ye=!1;if(H==="arch-plan"&&!A&&L.archPlan?.execution===void 0){const c=ha(r);if(c)try{if(!Object.hasOwn(B.epics,c)||!Object.hasOwn(L.epics,c))throw new Error("architecture-root-epic-binding-invalid");const p=fr(d,c);L={...L,archPlan:{execution:{schemaVersion:1,owner:"root",currentStageCommand:"arch-prd",continuationState:"delegate",evidencePolicy:"v2-required",targetEpicId:c,graphRevision:p,graphSource:"committed-epic-v1",acceptedStages:[]}}},Ye=!0}catch{return{success:!1,error:"architecture-root-epic-binding-invalid",errorCode:"architecture-root-epic-binding-invalid",exitCode:1}}}if((H==="arch-plan"||H?.startsWith("arch-")||H==="generate-pacts"||H==="update-memory")&&L.archPlan?.execution?.graphSource==="committed-epic-v1")try{const c=L.archPlan.execution;if(typeof c.targetEpicId!="string"||typeof c.graphRevision!="string"||c.graphRevision!==fr(d,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 k=ye;if((H==="create-epic"||H==="idea-diagnose")&&!k){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}
74
- `),{success:!1,error:c,errorCode:"EPIC_PROJECT_ID_REQUIRED",exitCode:1}}let le;try{le=C.execute({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>H==="create-epic"||H==="idea-diagnose"?cs(d,me,H):void 0,()=>{})}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const Qe=le?.key??(H==="yolo"?ds(d,me,k,L):void 0);if(e.privateExecutionBeta&&H==="create-epic"&&le){const c=Yt(d).operations[le.fingerprint],p=c?.epicId?B.epics[c.epicId]:void 0,I=f(p?.createEpicPlanningPhysical)?p.createEpicPlanningPhysical:void 0;c?.claimId&&c.epicId&&p&&I?.claimId===c.claimId&&(L={...L,epics:{...L.epics,[c.epicId]:p},stories:{...L.stories,...Object.fromEntries((Array.isArray(p.stories)?p.stories:[]).filter(R=>typeof R=="string"&&B.stories[R]?.epic_id===c.epicId).map(R=>[R,B.stories[R]]))}})}const Tt=A?{schemaVersion:1,invocationId:C.invocationId,intent:C.intent,clientProjection:ic(Bo.map(c=>({...c,count:1})))}:void 0;let Ie,Ee,ce;if(e.privateExecutionBeta&&H==="idea-research")try{const c=L.scope?.targetEpicId,p=c?L.epics[c]:void 0,I=f(p?.createEpicPlanningPhysical)?p.createEpicPlanningPhysical:void 0;if(!c||!I||typeof I.claimId!="string"||typeof I.receiptId!="string")throw new Error("planning-research-predecessor-unavailable");const R=q(d,".neocortex/state.json"),O=nr(R);if(!O.isFile()||O.isSymbolicLink()||O.size>8*1024*1024)throw new Error("planning-research-state-unavailable");const W=$e(R),te=JSON.parse(W.toString("utf8")),V=Co(te,I.claimId,c),ne=f(te)&&f(te.epics)&&f(te.epics[c])?te.epics[c]:void 0,N=f(ne?.createEpicPlanningPhysical)?ne.createEpicPlanningPhysical:void 0;if(N?.receiptId!==I.receiptId||!v(N,I))throw new Error("planning-research-predecessor-drift");const se=[".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`],Ke={...process.env};for(const Fe of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete Ke[Fe];for(const Fe of se){const yt=nr(q(d,Fe));if(!yt.isFile()||yt.isSymbolicLink()||yt.size>8*1024*1024)throw new Error("planning-research-source-unavailable");const Dr=Ae("git",["show",`HEAD:${Fe}`],{cwd:d,env:Ke,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!$e(q(d,Fe)).equals(Dr))throw new Error("planning-research-source-uncommitted")}Ee={claimId:I.claimId,epicId:c,diagnosisReceiptId:V.diagnosisReceiptId,intakeRevision:V.intakeRevision,physicalAcceptanceReceiptId:I.receiptId,sourceStateSha256:Le("sha256").update(W).digest("hex")}}catch{return{success:!1,error:"private-execution-planning-predecessor-unavailable",errorCode:"private-execution-planning-predecessor-unavailable",exitCode:1}}if(e.privateExecutionBeta&&H==="generate-epic")try{const c=L.scope?.targetEpicId,p=c?L.epics[c]:void 0,I=f(p?.createEpicPlanningResearchPhysical)?p.createEpicPlanningResearchPhysical:void 0;if(!c||!I||typeof I.claimId!="string"||typeof I.receiptId!="string")throw new Error("planning-generation-predecessor-unavailable");const R=q(d,".neocortex/state.json"),O=nr(R);if(!O.isFile()||O.isSymbolicLink()||O.size>8*1024*1024)throw new Error("planning-generation-state-unavailable");const W=$e(R),te=JSON.parse(W.toString("utf8")),V=_o(te,I.claimId,c),ne=f(te)&&f(te.epics)&&f(te.epics[c])?te.epics[c]:void 0,N=f(ne?.createEpicPlanningResearchPhysical)?ne.createEpicPlanningResearchPhysical:void 0;if(N?.receiptId!==I.receiptId||!v(N,I))throw new Error("planning-generation-predecessor-drift");const se=[".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`],Ke={...process.env};for(const Fe of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete Ke[Fe];for(const Fe of se){const yt=nr(q(d,Fe));if(!yt.isFile()||yt.isSymbolicLink()||yt.size>8*1024*1024)throw new Error("planning-generation-source-unavailable");const Dr=Ae("git",["show",`HEAD:${Fe}`],{cwd:d,env:Ke,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!$e(q(d,Fe)).equals(Dr))throw new Error("planning-generation-source-uncommitted")}ce={claimId:I.claimId,epicId:c,diagnosisReceiptId:V.diagnosisReceiptId,researchReceiptId:V.researchReceiptId,intakeRevision:V.intakeRevision,physicalAcceptanceReceiptId:V.physicalAcceptanceReceiptId,sourceStateSha256:Le("sha256").update(W).digest("hex")}}catch{return{success:!1,error:"private-execution-planning-predecessor-unavailable",errorCode:"private-execution-planning-predecessor-unavailable",exitCode:1}}const Se=hs(ae,process.platform);let it=!1;if(e.privateExecutionBeta&&H==="create-epic"&&le)try{const c=Yt(d).operations[le.fingerprint];it=c?.planningProtocol==="root-staged-v1"&&typeof c.claimId=="string"&&typeof c.epicId=="string"}catch{}const dr=Dt.match(/^[0-9]+\.[0-9]+\.[0-9]+/)?.[0];if(e.privateExecutionBeta&&!Se&&it&&dr===void 0)return{success:!1,error:"private-execution-host-version-unavailable",errorCode:"private-execution-host-version-unavailable",exitCode:1};if(e.privateExecutionBeta&&Se)try{const{preflightPrivateCodexExecutor:c}=await import("../private-execution/codex-executor.js");Ie=await c(d)}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}}let at,tt;const Ar=e.privateHostExecutorLoader??ii;if(e.privateExecutionBeta&&!Se&&ae!==void 0&&!it)try{if(e.privateExecutionModel!==void 0)throw new Error("private-executor-model-unsupported");at=await ai(ae,d,Ar),tt=await ci(at,ae)}catch(c){const p=c instanceof Error&&Nn.test(c.message)?c.message:"private-executor-headless-unavailable";return{success:!1,error:p,errorCode:p,exitCode:1}}const rt=tt?ms(tt):Ie?si(Ie):e.privateExecutionBeta&&!Se&&it&&ae!==void 0&&dr!==void 0?{schemaVersion:1,hostKind:ae,hostVersion:dr}:void 0;let Xe;if(H==="arch-plan"&&L.archPlan?.execution?.currentStageCommand==="generate-pacts"&&L.archPlan.execution.continuationState==="ask-user")try{if(Xe=Io(d),!Xe)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 Kt;if(H==="arch-plan"&&L.archPlan?.execution?.currentStageCommand==="generate-pacts"&&L.archPlan.execution.continuationState==="delegate"&&L.archPlan.execution.childStatus==="succeeded")try{if(Kt=Io(d),!Kt||!v(L.archPlan.execution.pactAnswerReceipt,Kt))throw new Error("architecture-answers-conflict")}catch{return{success:!1,error:"architecture-answers-conflict",errorCode:"architecture-answers-conflict",exitCode:1}}let mt,Te,Me;if(e.privateExecutionBeta&&H==="generate-pacts")try{const c=r.trim().match(/^\*?generate-pacts (P[1-9][0-9]{0,11})$/)?.[1],p=L.archPlan?.execution;if(Te=la(d),!c||!p||p.currentStageCommand!=="generate-pacts"||p.continuationState!=="delegate"||p.targetEpicId!==c||!Te||!v(p.pactAnswerReceipt,Te.receipt))throw new Error("private-execution-pact-admission-unverified");const I=fa(d,Te.answers.generateProvider);if(I.outcome!=="ready")throw new Error("private-execution-pact-admission-unverified");mt=I.writeSet,Me={schemaVersion:1,targetEpicId:c,graphRevision:Te.receipt.graphRevision,answersSha256:Te.receipt.answersSha256,specSha256:mt.specSha256,pathsSha256:mt.pathsSha256,endpointCount:mt.endpointCount,pathCount:mt.paths.length,publicSafe:!0}}catch{const c="private-execution-pact-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let ct,we;if(e.privateExecutionBeta&&H==="arch-ux-design")try{const c=r.trim().match(/^\*?arch-ux-design (P[1-9][0-9]{0,11})$/)?.[1],p=L.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:I}=await import("../private-execution/ux-write-set.js");ct=I(d,c),we={schemaVersion:1,targetEpicId:c,graphRevision:p.graphRevision,adapterId:ct.adapterId,authoritySha256:ct.authoritySha256,pathsSha256:ct.pathsSha256,screenCount:ct.screenCount,pathCount:ct.pathCount,publicSafe:!0}}catch{const c="private-execution-ux-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let sn,Jt,qe;if(e.privateExecutionBeta&&H==="property-test")try{if(u.selection.positionals.length!==0||u.selection.operationId!==void 0||Object.keys(u.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"),I=c(d);if(!I)throw new Error("private-execution-property-admission-unverified");sn=I.choices,Jt=I.plan,qe=p(I.plan)}catch{const c="private-execution-property-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let Qt;if(H==="yoloop"&&!A&&!e.privateExecutionBeta)try{Qt=(e.hostCapacityProbe??ya)({platformTarget:j,env:Y})}catch{Qt=void 0}let G={args:r,projectRoot:d.replace(yr(),"~"),stateSnapshot:L,...Xe?{architectureAnswerReceipt:Xe}:{},...Me?{pactExecutionInput:Me}:{},...we?{uxExecutionInput:we}:{},...qe?{propertyTestExecutionInput:qe}:{},platformTarget:j,...ve?{nativeHostAttestation:ve}:{},...Qt?{hostCapacity:Qt}:{},...rt?{privateExecution:rt}:{},projectId:k,inputEvidence:a,...g?{invocationRecovery:g}:{},idempotencyKey:Qe,registryVersion:Rt,registryChecksum:wt,compatibility:jn(D),...e.releaseGate?{releaseGate:e.releaseGate}:{},...Tt?{strictReadOnly:Tt}:{}};const ia=cr(G);if(!A&&e.inputSource&&e.inputSource!=="args"&&ia>=xn)try{G={argsRef:(await rc(C,"secondary-mutation",()=>Td(T,r,$.token,()=>$.client.forceRefresh()),async()=>{throw new Wt("readonly-physical-boundary-unsafe","boundary")})).argsRef,projectRoot:d.replace(yr(),"~"),stateSnapshot:L,...Xe?{architectureAnswerReceipt:Xe}:{},platformTarget:j,...ve?{nativeHostAttestation:ve}:{},...Qt?{hostCapacity:Qt}:{},...rt?{privateExecution:rt}:{},projectId:k,inputEvidence:a,...g?{invocationRecovery:g}:{},idempotencyKey:Qe,registryVersion:Rt,registryChecksum:wt,compatibility:jn(),...e.releaseGate?{releaseGate:e.releaseGate}:{},...Tt?{strictReadOnly:Tt}:{}}}catch(c){return c instanceof Wt?{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 pr;if(H==="yolo"&&L.scope?.projectionMode==="yolo-story"){const c=L.scope?.targetStoryId,p=L.scope?.targetEpicId;if(!c||!p||!ee||ee.storyId!==c||ee.epicId!==p)return{success:!1,error:"yolo-spec-envelope-target-mismatch",errorCode:"yolo-spec-envelope-target-mismatch",exitCode:1};try{let I=qo(ee);if(/\sbranchless-preparation\s*$/.test(r))G={...G,yoloSpecEnvelope:I};else{const{collectYoloChangeEvidence:R,reconcileYoloChangeEvidenceLease:O}=await import("../yolo/change-evidence-collector.js");pr=await O({projectRoot:d,storyId:c,epicId:p}),pr.repair==="applied"&&(I=qo(ee));const W=R({projectRoot:d,defaultBranch:L.config.default_branch,expectedHeadSha:I.sourceRevision.headSha,storyId:c,epicId:p,reconciliation:pr});G={...G,yoloSpecEnvelope:I,yoloChangeEvidence:W}}G=qc(G,{projectRoot:d,supported:Ce})}catch(I){const{yoloChangeEvidenceDiagnostic:R}=await import("../yolo/change-evidence-collector.js"),O=R(I),W=Ko(I,!0);return{success:!1,error:W,errorCode:W,...O?{metadata:{yoloChangeEvidence:O}}:{},exitCode:1}}}try{const c=Jn(G);if(H==="migrate-state"&&c.degraded)return{success:!1,error:"state_migration_payload_degraded",errorCode:"state_migration_payload_degraded",exitCode:1};G=c.body,c.degraded?Bi(G,c.telemetry):Ld(G)}catch(c){if(c instanceof Mn||c instanceof Vn)return Bi(G,c.telemetry),process.stderr.write(`[Neocortex] ${c.message}
75
- `),{success:!1,error:c.message,errorCode:c.code,metadata:{invokePayload:c.telemetry},exitCode:1};throw c}if(H==="yolo"&&G.yoloSpecEnvelope)try{const c=Yo({projectRoot:d,storyId:G.yoloSpecEnvelope.storyId,epicId:G.yoloSpecEnvelope.epicId,inputSha256:a.sha256,collectedAt:G.yoloSpecEnvelope.collectedAt});if(c.envelopeSha256!==G.yoloSpecEnvelope.envelopeSha256)throw new Error("yolo-spec-envelope-stale");if(G.yoloChangeEvidence){const{collectYoloChangeEvidence:p}=await import("../yolo/change-evidence-collector.js"),I=p({projectRoot:d,defaultBranch:L.config.default_branch,expectedHeadSha:c.sourceRevision.headSha,storyId:c.storyId,epicId:c.epicId,...pr?{reconciliation:pr}:{}});if(I.pathsSha256!==G.yoloChangeEvidence.pathsSha256||I.baseSha!==G.yoloChangeEvidence.baseSha)throw new Error("yolo-change-evidence-stale")}}catch(c){const p=c instanceof Error&&c.message==="yolo-change-evidence-stale"?c.message:"yolo-spec-envelope-stale",{yoloChangeEvidenceDiagnostic:I}=await import("../yolo/change-evidence-collector.js"),R=I(c);return{success:!1,error:p,errorCode:p,...R?{metadata:{yoloChangeEvidence:R}}:{},exitCode:1}}const M=H==="arch-plan"?G.stateSnapshot.archPlan?.execution:void 0;let br;if(M?.owner==="root"&&(M.currentStageCommand==="arch-prd"||M.currentStageCommand==="arch-architecture"||M.currentStageCommand==="arch-fitness-functions"||M.currentStageCommand==="arch-api-contracts"||M.currentStageCommand==="generate-pacts"||M.currentStageCommand==="arch-api-integrations"||M.currentStageCommand==="arch-database"||M.currentStageCommand==="arch-security"||M.currentStageCommand==="arch-design-system"||M.currentStageCommand==="arch-ux-design"||M.currentStageCommand==="arch-performance"||M.currentStageCommand==="arch-testing"||M.currentStageCommand==="arch-infrastructure"||M.currentStageCommand==="arch-review"||M.currentStageCommand==="update-memory")&&(M.continuationState==="delegate"||M.continuationState==="advance"||M.currentStageCommand==="update-memory"&&M.continuationState==="complete"||M.currentStageCommand==="arch-review"&&M.continuationState==="ask-user"||M.currentStageCommand==="generate-pacts"&&M.continuationState==="ask-user"))try{const c=$e(q(d,".neocortex","state.json"),"utf8"),p=JSON.parse(c),I=f(p.archPlan)?p.archPlan.execution:void 0;if(Ye?I!==void 0||!f(p.epics)||!Object.hasOwn(p.epics,String(M.targetEpicId))||M.graphSource!=="committed-epic-v1"||M.graphRevision!==fr(d,String(M.targetEpicId)):!v(Jr(I),M))throw new Error("architecture-root-state-binding-invalid");if(br=Le("sha256").update(c).digest("hex"),Xe&&Xe.stateSha256!==br)throw new Error("architecture-root-state-binding-invalid");if(M.currentStageCommand==="update-memory"&&M.childStatus==="succeeded"){const R=M.continuationState==="complete"&&Array.isArray(M.acceptedStages)?{...M,continuationState:"delegate",acceptedStages:M.acceptedStages.slice(0,mo(M))}:M;if(!hr(M.terminalMemoryCheckpoint,M)||!v(M.terminalMemoryCheckpoint,yn(d,R)))throw new Error("architecture-terminal-memory-physical-invalid")}}catch{return{success:!1,error:"architecture-root-state-binding-invalid",errorCode:"architecture-root-state-binding-invalid",exitCode:1}}if(Ie&&Date.now()-Ie.observedAtMs>2e4)try{const{preflightPrivateCodexExecutor:c}=await import("../private-execution/codex-executor.js"),p=await c(Ie.projectRoot);if(p.hostVersion!==Ie.hostVersion)throw new Error("private-codex-host-version-changed");Ie=p,G={...G,privateExecution:si(p)}}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}}let dn;const ao=async()=>{const c=await $.client.forceRefresh(),p=c?null:$.client.getLastRecoveryResult();return dn=p?.status==="refresh-required"?tn(p.cause):void 0,c};let m=await wn("invoke-query",()=>oo(T,G,$.token,{refreshToken:ao}));const pn=m.ok?m.data?.metadata?.semanticGateRemediation:void 0,Xt=L.yoloop?.state?.continuationSession,co=Xt&&typeof Xt.sessionId=="string"?Xt.sessionId:void 0,so=Xt&&typeof Xt.graphFingerprint=="string"?Xt.graphFingerprint:void 0,xr=pn!==void 0&&co&&so?Qc({remediation:pn,requestSha256:a.sha256,sessionId:co,graphRevision:so}):null,aa=xr!==null,ca=pn===void 0&&m.ok&&m.data?.metadata?.errorCode==="YOLOOP_SPEC_NOT_READY"&&m.data.metadata.hint==="yoloop-session-invalidated";if(H==="yoloop"&&!A&&m.ok&&(aa||ca)){const c=L.scope?.targetEpicId;if(!c)return{success:!1,error:"yoloop-causal-reconciliation-target-invalid",errorCode:"YOLOOP_CAUSAL_RECONCILIATION_BLOCKED",exitCode:1};const p=await wp({projectRoot:d,snapshot:B,targetEpicId:c,originalInputSha256:a.sha256,canonicalInputSha256:g?.canonicalSha256??a.sha256});if(p.outcome!=="applied")return{success:!1,error:p.reasonCode,errorCode:"YOLOOP_CAUSAL_RECONCILIATION_BLOCKED",metadata:{yoloopCausalRecovery:p},exitCode:1};try{const{readYoloopForRequest:I}=await import("../yoloop/invoke-hooks.js"),R=await I(r,d);if(!R)throw new Error("yoloop-causal-reconciliation-postimage-unverified");if(xr){const O=fc(xr,[{source:"client-yoloop-state",requestBindingSha256:xr.binding.requestBindingSha256,value:R}]);if(O?.length!==1||O[0]?.field!=="stateSnapshot.yoloop"||O[0].value!==R)throw new Error("semantic-gate-boilerplate-materialization-invalid")}G=Jn({...G,stateSnapshot:{...G.stateSnapshot,yoloop:R}}).body}catch(I){const R=Zi(I);return{success:!1,error:R,errorCode:"YOLOOP_CAUSAL_RECONCILIATION_BLOCKED",metadata:{yoloopCausalRecovery:{outcome:"blocked",reasonCode:R,retryCount:0,publicSafe:!0}},exitCode:1}}m=await wn("invoke-query",()=>oo(T,G,$.token,{refreshToken:ao}))}let Tr;if(A&&m.ok)try{if(y){const p=m.data?.metadata;if(p&&["stateUpdate","stateMutated","yoloopStateUpdate","continuityStateUpdate","checkpoint","schedulerStateUpdate","quotaCacheUpdate","projectIdentityMigration","epicClaim","gitLifecycleGraphAuthority"].some(R=>p[R]!==void 0))throw new Wt("readonly-response-conflict")}const c=m.data?.metadata.strictReadOnly;if(cc(C,c),y){yc(m.data?.metadata.strictDiagnose,i,m.data?.instructions??"");const p=m.data?.metadata.diagnose;if(p?.schemaVersion===Wr.DIAGNOSE_SCOPED_CONTINUATION){const I=m.compatibility;if(!D||!Go(I)||I.status==="incompatible"||!I.capabilityIds.includes(Gr.DIAGNOSE_SCOPED_CONTINUATION)||!I.schemaVersions.includes(Wr.DIAGNOSE_SCOPED_CONTINUATION))throw new Wt("readonly-response-conflict");dc(p)}}Tr=c.security}catch(c){const p=c instanceof Wt?c.code:"readonly-receipt-mismatch";return{success:!1,error:p,errorCode:p,exitCode:1}}if(!m.ok&&m.status===426){const c=m.errorBody,p=c?.upgrade_command??"npm install -g @ornexus/neocortex@latest",I=c?.min_version??"unknown";return process.stderr.write(`
71
+ `),{success:!1,error:fe.error??"Runner auto-bootstrap required but failed.",errorCode:fe.errorCode,exitCode:fe.exitCode??1};if(fe.metadata.command==="runner"&&(fe.metadata.operation==="status"||fe.metadata.operation==="doctor"))try{const c=e.runnerObserver??Xa;V.runnerOperationalStatus=await c(fe.metadata.operation,{projectRoot:d,env:e.environment??process.env,effectAuthority:_})}catch{}let D;try{const c=Ha(me,V);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}
72
+ `),{success:!1,error:p,errorCode:c.code,metadata:{stateProjection:c,publicSafe:!0},exitCode:1}}D=c?.snapshot??ki(me,V),Br(me)==="migrate-state"&&(D={...D,migrationAuthority:za(d)})}catch(c){if(c instanceof Ya)return{success:!1,error:c.reasonCode,errorCode:c.reasonCode,exitCode:1};if(c instanceof Ni){const p=`${c.code}: structural projection failed closed; select a valid target or repair the dependency DAG.`;return process.stderr.write(`${p}
73
+ `),{success:!1,error:p,errorCode:c.code,metadata:{structuralProjection:{...c.publicDetails,publicSafe:!0}},exitCode:1}}throw c}if(!A)try{const{openNativeAgentPrivateStore:c,resolveNativeAgentPrivateRuntimePaths:p}=await import("../continuity/native-agent-store.js"),I=p(d);if(Ct(I.databasePath)){const R=await c(d);try{const O=h==="yoloop"&&j==="runner",U=O?R.store.listUnsettledNativeAgentDispatches(21):R.store.listRecentNativeAgentDispatches(20);if(O&&U.length>20)throw new Error("native-dispatch-observation-limit");if(U.length>0&&(D.nativeAgentDispatches=U,O)){const{observeExpiredNativeWorktreeCustody:ee}=await import("../continuity/native-worktree-custody.js"),Y=await ee(d,U);Y.length>0&&(D.nativeAgentExpiredWorktrees=Y)}}finally{R.store.close()}}}catch(c){if(h==="yoloop"&&j==="runner"){const p=ho(c);return{success:!1,exitCode:1,errorCode:"YOLOOP_NATIVE_CUSTODY_UNVERIFIED",error:`The runner could not verify whether existing native story workers are settled. ${p.remediation}`,metadata:{nativeCustody:p}}}}const H=Br(me);let Ye=!1;if(H==="arch-plan"&&!A&&D.archPlan?.execution===void 0){const c=ma(r);if(c)try{if(!Object.hasOwn(V.epics,c)||!Object.hasOwn(D.epics,c))throw new Error("architecture-root-epic-binding-invalid");const p=fr(d,c);D={...D,archPlan:{execution:{schemaVersion:1,owner:"root",currentStageCommand:"arch-prd",continuationState:"delegate",evidencePolicy:"v2-required",targetEpicId:c,graphRevision:p,graphSource:"committed-epic-v1",acceptedStages:[]}}},Ye=!0}catch{return{success:!1,error:"architecture-root-epic-binding-invalid",errorCode:"architecture-root-epic-binding-invalid",exitCode:1}}}if((H==="arch-plan"||H?.startsWith("arch-")||H==="generate-pacts"||H==="update-memory")&&D.archPlan?.execution?.graphSource==="committed-epic-v1")try{const c=D.archPlan.execution;if(typeof c.targetEpicId!="string"||typeof c.graphRevision!="string"||c.graphRevision!==fr(d,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 k=ye;if((H==="create-epic"||H==="idea-diagnose")&&!k){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}
74
+ `),{success:!1,error:c,errorCode:"EPIC_PROJECT_ID_REQUIRED",exitCode:1}}let le;try{le=_.execute({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>H==="create-epic"||H==="idea-diagnose"?ls(d,me,H):void 0,()=>{})}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const Je=le?.key??(H==="yolo"?fs(d,me,k,D):void 0);if(e.privateExecutionBeta&&H==="create-epic"&&le){const c=Yt(d).operations[le.fingerprint],p=c?.epicId?V.epics[c.epicId]:void 0,I=f(p?.createEpicPlanningPhysical)?p.createEpicPlanningPhysical:void 0;c?.claimId&&c.epicId&&p&&I?.claimId===c.claimId&&(D={...D,epics:{...D.epics,[c.epicId]:p},stories:{...D.stories,...Object.fromEntries((Array.isArray(p.stories)?p.stories:[]).filter(R=>typeof R=="string"&&V.stories[R]?.epic_id===c.epicId).map(R=>[R,V.stories[R]]))}})}const Tt=A?{schemaVersion:1,invocationId:_.invocationId,intent:_.intent,clientProjection:dc($i.map(c=>({...c,count:1})))}:void 0;let Ie,Ee,se;if(e.privateExecutionBeta&&H==="idea-research")try{const c=D.scope?.targetEpicId,p=c?D.epics[c]:void 0,I=f(p?.createEpicPlanningPhysical)?p.createEpicPlanningPhysical:void 0;if(!c||!I||typeof I.claimId!="string"||typeof I.receiptId!="string")throw new Error("planning-research-predecessor-unavailable");const R=J(d,".neocortex/state.json"),O=nr(R);if(!O.isFile()||O.isSymbolicLink()||O.size>8*1024*1024)throw new Error("planning-research-state-unavailable");const U=Ue(R),ee=JSON.parse(U.toString("utf8")),Y=_i(ee,I.claimId,c),G=f(ee)&&f(ee.epics)&&f(ee.epics[c])?ee.epics[c]:void 0,L=f(G?.createEpicPlanningPhysical)?G.createEpicPlanningPhysical:void 0;if(L?.receiptId!==I.receiptId||!C(L,I))throw new Error("planning-research-predecessor-drift");const F=[".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`],Xe={...process.env};for(const Pe 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 Xe[Pe];for(const Pe of F){const yt=nr(J(d,Pe));if(!yt.isFile()||yt.isSymbolicLink()||yt.size>8*1024*1024)throw new Error("planning-research-source-unavailable");const Dr=Ae("git",["show",`HEAD:${Pe}`],{cwd:d,env:Xe,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!Ue(J(d,Pe)).equals(Dr))throw new Error("planning-research-source-uncommitted")}Ee={claimId:I.claimId,epicId:c,diagnosisReceiptId:Y.diagnosisReceiptId,intakeRevision:Y.intakeRevision,physicalAcceptanceReceiptId:I.receiptId,sourceStateSha256:je("sha256").update(U).digest("hex")}}catch{return{success:!1,error:"private-execution-planning-predecessor-unavailable",errorCode:"private-execution-planning-predecessor-unavailable",exitCode:1}}if(e.privateExecutionBeta&&H==="generate-epic")try{const c=D.scope?.targetEpicId,p=c?D.epics[c]:void 0,I=f(p?.createEpicPlanningResearchPhysical)?p.createEpicPlanningResearchPhysical:void 0;if(!c||!I||typeof I.claimId!="string"||typeof I.receiptId!="string")throw new Error("planning-generation-predecessor-unavailable");const R=J(d,".neocortex/state.json"),O=nr(R);if(!O.isFile()||O.isSymbolicLink()||O.size>8*1024*1024)throw new Error("planning-generation-state-unavailable");const U=Ue(R),ee=JSON.parse(U.toString("utf8")),Y=wi(ee,I.claimId,c),G=f(ee)&&f(ee.epics)&&f(ee.epics[c])?ee.epics[c]:void 0,L=f(G?.createEpicPlanningResearchPhysical)?G.createEpicPlanningResearchPhysical:void 0;if(L?.receiptId!==I.receiptId||!C(L,I))throw new Error("planning-generation-predecessor-drift");const F=[".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`],Xe={...process.env};for(const Pe 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 Xe[Pe];for(const Pe of F){const yt=nr(J(d,Pe));if(!yt.isFile()||yt.isSymbolicLink()||yt.size>8*1024*1024)throw new Error("planning-generation-source-unavailable");const Dr=Ae("git",["show",`HEAD:${Pe}`],{cwd:d,env:Xe,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!Ue(J(d,Pe)).equals(Dr))throw new Error("planning-generation-source-uncommitted")}se={claimId:I.claimId,epicId:c,diagnosisReceiptId:Y.diagnosisReceiptId,researchReceiptId:Y.researchReceiptId,intakeRevision:Y.intakeRevision,physicalAcceptanceReceiptId:Y.physicalAcceptanceReceiptId,sourceStateSha256:je("sha256").update(U).digest("hex")}}catch{return{success:!1,error:"private-execution-planning-predecessor-unavailable",errorCode:"private-execution-planning-predecessor-unavailable",exitCode:1}}const Se=Is(ae,process.platform);let ot=!1;if(e.privateExecutionBeta&&ae!==bn&&H==="create-epic"&&le)try{const c=Yt(d).operations[le.fingerprint];if(c?.planningProtocol==="root-staged-v1"&&c.epicId&&c.claimId){const p=V.epics[c.epicId]?.createEpicPlanningPhysical;ot=f(p)&&p.claimId===c.claimId&&p.epicId===c.epicId}}catch{}const dr=Dt.match(/^[0-9]+\.[0-9]+\.[0-9]+/)?.[0];if(e.privateExecutionBeta&&!Se&&ot&&dr===void 0)return{success:!1,error:"private-execution-host-version-unavailable",errorCode:"private-execution-host-version-unavailable",exitCode:1};if(e.privateExecutionBeta&&Se)try{const{preflightPrivateCodexExecutor:c}=await import("../private-execution/codex-executor.js");Ie=await c(d)}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}}let at,tt;const Ar=e.privateHostExecutorLoader??co;if(e.privateExecutionBeta&&!Se&&ae!==void 0&&!ot)try{if(e.privateExecutionModel!==void 0)throw new Error("private-executor-model-unsupported");at=await so(ae,d,Ar),tt=await po(at,ae)}catch(c){const p=c instanceof Error&&Ln.test(c.message)?c.message:"private-executor-headless-unavailable";return{success:!1,error:p,errorCode:p,exitCode:1}}const rt=tt?vs(tt):Ie?uo(Ie):e.privateExecutionBeta&&!Se&&ot&&ae!==void 0&&dr!==void 0?{schemaVersion:1,hostKind:ae,hostVersion:dr}:void 0;let Qe;if(H==="arch-plan"&&D.archPlan?.execution?.currentStageCommand==="generate-pacts"&&D.archPlan.execution.continuationState==="ask-user")try{if(Qe=Ei(d),!Qe)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 Kt;if(H==="arch-plan"&&D.archPlan?.execution?.currentStageCommand==="generate-pacts"&&D.archPlan.execution.continuationState==="delegate"&&D.archPlan.execution.childStatus==="succeeded")try{if(Kt=Ei(d),!Kt||!C(D.archPlan.execution.pactAnswerReceipt,Kt))throw new Error("architecture-answers-conflict")}catch{return{success:!1,error:"architecture-answers-conflict",errorCode:"architecture-answers-conflict",exitCode:1}}let mt,Te,Ve;if(e.privateExecutionBeta&&H==="generate-pacts")try{const c=r.trim().match(/^\*?generate-pacts (P[1-9][0-9]{0,11})$/)?.[1],p=D.archPlan?.execution;if(Te=ga(d),!c||!p||p.currentStageCommand!=="generate-pacts"||p.continuationState!=="delegate"||p.targetEpicId!==c||!Te||!C(p.pactAnswerReceipt,Te.receipt))throw new Error("private-execution-pact-admission-unverified");const I=ya(d,Te.answers.generateProvider);if(I.outcome!=="ready")throw new Error("private-execution-pact-admission-unverified");mt=I.writeSet,Ve={schemaVersion:1,targetEpicId:c,graphRevision:Te.receipt.graphRevision,answersSha256:Te.receipt.answersSha256,specSha256:mt.specSha256,pathsSha256:mt.pathsSha256,endpointCount:mt.endpointCount,pathCount:mt.paths.length,publicSafe:!0}}catch{const c="private-execution-pact-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let ct,we;if(e.privateExecutionBeta&&H==="arch-ux-design")try{const c=r.trim().match(/^\*?arch-ux-design (P[1-9][0-9]{0,11})$/)?.[1],p=D.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:I}=await import("../private-execution/ux-write-set.js");ct=I(d,c),we={schemaVersion:1,targetEpicId:c,graphRevision:p.graphRevision,adapterId:ct.adapterId,authoritySha256:ct.authoritySha256,pathsSha256:ct.pathsSha256,screenCount:ct.screenCount,pathCount:ct.pathCount,publicSafe:!0}}catch{const c="private-execution-ux-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let sn,Jt,qe;if(e.privateExecutionBeta&&H==="property-test")try{if(u.selection.positionals.length!==0||u.selection.operationId!==void 0||Object.keys(u.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"),I=c(d);if(!I)throw new Error("private-execution-property-admission-unverified");sn=I.choices,Jt=I.plan,qe=p(I.plan)}catch{const c="private-execution-property-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let Qt;if(H==="yoloop"&&!A&&!e.privateExecutionBeta)try{Qt=(e.hostCapacityProbe??Sa)({platformTarget:j,env:K})}catch{Qt=void 0}let W={args:r,projectRoot:d.replace(yr(),"~"),stateSnapshot:D,...Qe?{architectureAnswerReceipt:Qe}:{},...Ve?{pactExecutionInput:Ve}:{},...we?{uxExecutionInput:we}:{},...qe?{propertyTestExecutionInput:qe}:{},platformTarget:j,...ve?{nativeHostAttestation:ve}:{},...Qt?{hostCapacity:Qt}:{},...rt?{privateExecution:rt}:{},projectId:k,inputEvidence:a,...g?{invocationRecovery:g}:{},idempotencyKey:Je,registryVersion:Rt,registryChecksum:wt,compatibility:Vn(N),...e.releaseGate?{releaseGate:e.releaseGate}:{},...Tt?{strictReadOnly:Tt}:{}};const sa=cr(W);if(!A&&e.inputSource&&e.inputSource!=="args"&&sa>=Pn)try{W={argsRef:(await ac(_,"secondary-mutation",()=>Dd(T,r,B.token,()=>B.client.forceRefresh()),async()=>{throw new Wt("readonly-physical-boundary-unsafe","boundary")})).argsRef,projectRoot:d.replace(yr(),"~"),stateSnapshot:D,...Qe?{architectureAnswerReceipt:Qe}:{},platformTarget:j,...ve?{nativeHostAttestation:ve}:{},...Qt?{hostCapacity:Qt}:{},...rt?{privateExecution:rt}:{},projectId:k,inputEvidence:a,...g?{invocationRecovery:g}:{},idempotencyKey:Je,registryVersion:Rt,registryChecksum:wt,compatibility:Vn(),...e.releaseGate?{releaseGate:e.releaseGate}:{},...Tt?{strictReadOnly:Tt}:{}}}catch(c){return c instanceof Wt?{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 pr;if(H==="yolo"&&D.scope?.projectionMode==="yolo-story"){const c=D.scope?.targetStoryId,p=D.scope?.targetEpicId;if(!c||!p||!ne||ne.storyId!==c||ne.epicId!==p)return{success:!1,error:"yolo-spec-envelope-target-mismatch",errorCode:"yolo-spec-envelope-target-mismatch",exitCode:1};try{let I=Ji(ne);if(/\sbranchless-preparation\s*$/.test(r))W={...W,yoloSpecEnvelope:I};else{const{collectYoloChangeEvidence:R,reconcileYoloChangeEvidenceLease:O}=await import("../yolo/change-evidence-collector.js");pr=await O({projectRoot:d,storyId:c,epicId:p}),pr.repair==="applied"&&(I=Ji(ne));const U=R({projectRoot:d,defaultBranch:D.config.default_branch,expectedHeadSha:I.sourceRevision.headSha,storyId:c,epicId:p,reconciliation:pr});W={...W,yoloSpecEnvelope:I,yoloChangeEvidence:U}}W=Zc(W,{projectRoot:d,supported:Ce})}catch(I){const{yoloChangeEvidenceDiagnostic:R}=await import("../yolo/change-evidence-collector.js"),O=R(I),U=Qi(I,!0);return{success:!1,error:U,errorCode:U,...O?{metadata:{yoloChangeEvidence:O}}:{},exitCode:1}}}try{const c=Xn(W);if(H==="migrate-state"&&c.degraded)return{success:!1,error:"state_migration_payload_degraded",errorCode:"state_migration_payload_degraded",exitCode:1};W=c.body,c.degraded?Ho(W,c.telemetry):$d(W)}catch(c){if(c instanceof Bn||c instanceof $n)return Ho(W,c.telemetry),process.stderr.write(`[Neocortex] ${c.message}
75
+ `),{success:!1,error:c.message,errorCode:c.code,metadata:{invokePayload:c.telemetry},exitCode:1};throw c}if(H==="yolo"&&W.yoloSpecEnvelope)try{const c=Ki({projectRoot:d,storyId:W.yoloSpecEnvelope.storyId,epicId:W.yoloSpecEnvelope.epicId,inputSha256:a.sha256,collectedAt:W.yoloSpecEnvelope.collectedAt});if(c.envelopeSha256!==W.yoloSpecEnvelope.envelopeSha256)throw new Error("yolo-spec-envelope-stale");if(W.yoloChangeEvidence){const{collectYoloChangeEvidence:p}=await import("../yolo/change-evidence-collector.js"),I=p({projectRoot:d,defaultBranch:D.config.default_branch,expectedHeadSha:c.sourceRevision.headSha,storyId:c.storyId,epicId:c.epicId,...pr?{reconciliation:pr}:{}});if(I.pathsSha256!==W.yoloChangeEvidence.pathsSha256||I.baseSha!==W.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:I}=await import("../yolo/change-evidence-collector.js"),R=I(c);return{success:!1,error:p,errorCode:p,...R?{metadata:{yoloChangeEvidence:R}}:{},exitCode:1}}const M=H==="arch-plan"?W.stateSnapshot.archPlan?.execution:void 0;let br;if(M?.owner==="root"&&(M.currentStageCommand==="arch-prd"||M.currentStageCommand==="arch-architecture"||M.currentStageCommand==="arch-fitness-functions"||M.currentStageCommand==="arch-api-contracts"||M.currentStageCommand==="generate-pacts"||M.currentStageCommand==="arch-api-integrations"||M.currentStageCommand==="arch-database"||M.currentStageCommand==="arch-security"||M.currentStageCommand==="arch-design-system"||M.currentStageCommand==="arch-ux-design"||M.currentStageCommand==="arch-performance"||M.currentStageCommand==="arch-testing"||M.currentStageCommand==="arch-infrastructure"||M.currentStageCommand==="arch-review"||M.currentStageCommand==="update-memory")&&(M.continuationState==="delegate"||M.continuationState==="advance"||M.currentStageCommand==="update-memory"&&M.continuationState==="complete"||M.currentStageCommand==="arch-review"&&M.continuationState==="ask-user"||M.currentStageCommand==="generate-pacts"&&M.continuationState==="ask-user"))try{const c=Ue(J(d,".neocortex","state.json"),"utf8"),p=JSON.parse(c),I=f(p.archPlan)?p.archPlan.execution:void 0;if(Ye?I!==void 0||!f(p.epics)||!Object.hasOwn(p.epics,String(M.targetEpicId))||M.graphSource!=="committed-epic-v1"||M.graphRevision!==fr(d,String(M.targetEpicId)):!C(Jr(I),M))throw new Error("architecture-root-state-binding-invalid");if(br=je("sha256").update(c).digest("hex"),Qe&&Qe.stateSha256!==br)throw new Error("architecture-root-state-binding-invalid");if(M.currentStageCommand==="update-memory"&&M.childStatus==="succeeded"){const R=M.continuationState==="complete"&&Array.isArray(M.acceptedStages)?{...M,continuationState:"delegate",acceptedStages:M.acceptedStages.slice(0,yi(M))}:M;if(!hr(M.terminalMemoryCheckpoint,M)||!C(M.terminalMemoryCheckpoint,yn(d,R)))throw new Error("architecture-terminal-memory-physical-invalid")}}catch{return{success:!1,error:"architecture-root-state-binding-invalid",errorCode:"architecture-root-state-binding-invalid",exitCode:1}}if(Ie&&Date.now()-Ie.observedAtMs>2e4)try{const{preflightPrivateCodexExecutor:c}=await import("../private-execution/codex-executor.js"),p=await c(Ie.projectRoot);if(p.hostVersion!==Ie.hostVersion)throw new Error("private-codex-host-version-changed");Ie=p,W={...W,privateExecution:uo(p)}}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}}let dn;const si=async()=>{const c=await B.client.forceRefresh(),p=c?null:B.client.getLastRecoveryResult();return dn=p?.status==="refresh-required"?tn(p.cause):void 0,c};let m=await wn("invoke-query",()=>ai(T,W,B.token,{refreshToken:si}));const pn=m.ok?m.data?.metadata?.semanticGateRemediation:void 0,Xt=D.yoloop?.state?.continuationSession,di=Xt&&typeof Xt.sessionId=="string"?Xt.sessionId:void 0,pi=Xt&&typeof Xt.graphFingerprint=="string"?Xt.graphFingerprint:void 0,xr=pn!==void 0&&di&&pi?rs({remediation:pn,requestSha256:a.sha256,sessionId:di,graphRevision:pi}):null,da=xr!==null,pa=pn===void 0&&m.ok&&m.data?.metadata?.errorCode==="YOLOOP_SPEC_NOT_READY"&&m.data.metadata.hint==="yoloop-session-invalidated";if(H==="yoloop"&&!A&&m.ok&&(da||pa)){const c=D.scope?.targetEpicId;if(!c)return{success:!1,error:"yoloop-causal-reconciliation-target-invalid",errorCode:"YOLOOP_CAUSAL_RECONCILIATION_BLOCKED",exitCode:1};const p=await Tp({projectRoot:d,snapshot:V,targetEpicId:c,originalInputSha256:a.sha256,canonicalInputSha256:g?.canonicalSha256??a.sha256});if(p.outcome!=="applied")return{success:!1,error:p.reasonCode,errorCode:"YOLOOP_CAUSAL_RECONCILIATION_BLOCKED",metadata:{yoloopCausalRecovery:p},exitCode:1};try{const{readYoloopForRequest:I}=await import("../yoloop/invoke-hooks.js"),R=await I(r,d);if(!R)throw new Error("yoloop-causal-reconciliation-postimage-unverified");if(xr){const O=Ec(xr,[{source:"client-yoloop-state",requestBindingSha256:xr.binding.requestBindingSha256,value:R}]);if(O?.length!==1||O[0]?.field!=="stateSnapshot.yoloop"||O[0].value!==R)throw new Error("semantic-gate-boilerplate-materialization-invalid")}W=Xn({...W,stateSnapshot:{...W.stateSnapshot,yoloop:R}}).body}catch(I){const R=ra(I);return{success:!1,error:R,errorCode:"YOLOOP_CAUSAL_RECONCILIATION_BLOCKED",metadata:{yoloopCausalRecovery:{outcome:"blocked",reasonCode:R,retryCount:0,publicSafe:!0}},exitCode:1}}m=await wn("invoke-query",()=>ai(T,W,B.token,{refreshToken:si}))}let Tr;if(A&&m.ok)try{if(y){const p=m.data?.metadata;if(p&&["stateUpdate","stateMutated","yoloopStateUpdate","continuityStateUpdate","checkpoint","schedulerStateUpdate","quotaCacheUpdate","projectIdentityMigration","epicClaim","gitLifecycleGraphAuthority"].some(R=>p[R]!==void 0))throw new Wt("readonly-response-conflict")}const c=m.data?.metadata.strictReadOnly;if(uc(_,c),y){Cc(m.data?.metadata.strictDiagnose,o,m.data?.instructions??"");const p=m.data?.metadata.diagnose;if(p?.schemaVersion===Wr.DIAGNOSE_SCOPED_CONTINUATION){const I=m.compatibility;if(!N||!zi(I)||I.status==="incompatible"||!I.capabilityIds.includes(Gr.DIAGNOSE_SCOPED_CONTINUATION)||!I.schemaVersions.includes(Wr.DIAGNOSE_SCOPED_CONTINUATION))throw new Wt("readonly-response-conflict");hc(p)}}Tr=c.security}catch(c){const p=c instanceof Wt?c.code:"readonly-receipt-mismatch";return{success:!1,error:p,errorCode:p,exitCode:1}}if(!m.ok&&m.status===426){const c=m.errorBody,p=c?.upgrade_command??"npm install -g @ornexus/neocortex@latest",I=c?.min_version??"unknown";return process.stderr.write(`
76
76
  `),process.stderr.write(`==================================================
77
77
  `),process.stderr.write(` UPGRADE REQUIRED
78
78
  `),process.stderr.write(`==================================================
@@ -87,12 +87,12 @@ The C04 barrier did not open within the bounded wait. Return this resumable rece
87
87
  `),process.stderr.write(` After updating, re-run your command.
88
88
  `),process.stderr.write(`==================================================
89
89
 
90
- `),{success:!1,error:`UPGRADE_REQUIRED: Client version ${Dt} is below minimum ${I}. Run: ${p}`,exitCode:3}}if(!m.ok||!m.data){if(m.networkFailure)return en("invocation",m.networkFailure);if(m.status===401&&dn)return en("authentication",dn);const c=m.status===401?2:(m.status===429||m.status>=500,1),p=_d(m),I=Cs(p);if(I)return process.stderr.write(`[Neocortex] ${I.error}
91
- `),I;try{if(p){const V=Ur(),ne=Cn(p,V);ne&&process.stderr.write(_n(ne,V))}}catch{}let R;const O=$o(m.errorBody),W=Hr(m.errorBody?.semanticGateRemediation);if(e.privateExecutionBeta&&H==="create-epic"&&le){const V=m.errorBody?.epic_claim_recovery;if(f(V)){const ne=Le("sha256").update("private-step-state-v1\0").update(JSON.stringify(G.stateSnapshot)).digest("hex");let N=null;if(typeof V.claimId=="string"&&typeof G.args=="string")try{N=Ho(W,{requestSha256:Uo(G.args),sessionId:mc(V.claimId),graphRevision:ne})}catch{}const se=N?.repairKind==="resubmit-bound-request"&&N.nextAction==="resubmit-once"&&N.authority.owner==="client"&&N.authority.operation==="resubmit-bound-request"&&N.retry.limit===1&&N.boilerplate.templateId==="gate-single-resubmission-v1"&&N.reasonCode===m.errorBody?.reason_code;let Ke=!1;if(se)try{C.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>On(d,le.fingerprint,V.claimId,V.epicId),()=>{}),Ke=!0}catch{}R={schemaVersion:1,claimId:V.claimId,epicId:V.epicId,nextAction:V.nextAction,...typeof m.errorBody?.reason_code=="string"?{reasonCode:m.errorBody.reason_code}:{},...typeof m.errorBody?.fallback_action=="string"?{fallbackAction:m.errorBody.fallback_action}:{},...N?{semanticGateRemediation:N}:{},persisted:Ke,publicSafe:!0}}}const te={...m.compatibility?{compatibility:m.compatibility}:{},...W?{semanticGateRemediation:W}:{},...O?{privateExecutionHostFailure:O}:{},...R?{createEpicClaimRecovery:R}:{}};return{success:!1,error:nt(O?.message??m.error??"Unknown error from server",zt),...p?{errorCode:p}:{},...Object.keys(te).length>0?{metadata:te}:{},exitCode:c}}const po=_s(m.data);if(po)return C.complete(Tr),po;let Ne;try{Ne=e.privateExecutionBeta&&H==="create-epic"&&le?Yt(d).operations[le.fingerprint]:void 0}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const Pr=Ne?.planningProtocol==="root-staged-v1"&&typeof Ne.claimId=="string"&&typeof Ne.epicId=="string"&&Sa(m.data,{claimId:Ne.claimId,epicId:Ne.epicId,...f(B.epics[Ne.epicId]?.createEpicPlanningMemoryPhysical)?{memoryReceiptId:B.epics[Ne.epicId].createEpicPlanningMemoryPhysical.receiptId}:{}});if(e.privateExecutionBeta&&!Pr&&!Ea(m.data))return{success:!1,error:"private-execution-public-envelope-invalid",errorCode:"private-execution-public-envelope-invalid",exitCode:1};if(br&&M&&m.data.metadata?.mode==="arch-plan"&&f(m.data.metadata.archPlan)&&f(m.data.metadata.archPlan.execution)&&(m.data.metadata.archPlan.execution.nextAction==="delegate"||m.data.metadata.archPlan.execution.nextAction==="resume"||m.data.metadata.archPlan.execution.nextAction==="ask-user"||m.data.metadata.archPlan.execution.nextAction==="complete"&&m.data.metadata.archPlan.execution.currentStageCommand==="update-memory"||m.data.metadata.archPlan.execution.nextAction==="blocked"&&(m.data.metadata.archPlan.execution.currentStageCommand==="arch-ux-design"||m.data.metadata.archPlan.execution.currentStageCommand==="arch-performance"||m.data.metadata.archPlan.execution.currentStageCommand==="arch-testing"||m.data.metadata.archPlan.execution.currentStageCommand==="arch-infrastructure"||m.data.metadata.archPlan.execution.currentStageCommand==="arch-review")))try{await C.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>Hs({projectRoot:d,sourceStateSha256:br,requestExecution:M,initialBinding:Ye,answerReceipt:Xe,pactRecordedReceipt:Kt,metadata:m.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.
92
- `),{success:!1,error:p,errorCode:p,exitCode:1}}if(Je&&m.data.metadata?.mode==="menu"&&await C.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>md(Je,m.data.instructions,m.data.metadata),async()=>{}).catch(()=>{}),m.data.metadata&&await C.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"tier-cache",operation:"update"},()=>$.tierClient.updateQuotaFromResponse(m.data.metadata),async()=>{}).catch(()=>{}),m.data.metadata?.stateMutated===!0)try{const c=await C.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>{const{persistMigratedStateFromResponse:p}=await import("../yoloop/invoke-hooks.js");return p(m.data.metadata,d)},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}
90
+ `),{success:!1,error:`UPGRADE_REQUIRED: Client version ${Dt} is below minimum ${I}. Run: ${p}`,exitCode:3}}if(!m.ok||!m.data){if(m.networkFailure)return en("invocation",m.networkFailure);if(m.status===401&&dn)return en("authentication",dn);const c=m.status===401?2:(m.status===429||m.status>=500,1),p=xd(m),I=bs(p);if(I)return process.stderr.write(`[Neocortex] ${I.error}
91
+ `),I;try{if(p){const G=Ur(),L=Cn(p,G);L&&process.stderr.write(_n(L,G))}}catch{}let R;const O=Ui(m.errorBody),U=Rn(m.errorBody),ee=Hr(m.errorBody?.semanticGateRemediation);if(e.privateExecutionBeta&&H==="create-epic"&&le){const G=m.errorBody?.epic_claim_recovery;if(f(G)){const L=je("sha256").update("private-step-state-v1\0").update(JSON.stringify(W.stateSnapshot)).digest("hex");let F=null;if(typeof G.claimId=="string"&&typeof W.args=="string")try{F=Fi(ee,{requestSha256:Wi(W.args),sessionId:vc(G.claimId),graphRevision:L})}catch{}const Xe=F?.repairKind==="resubmit-bound-request"&&F.nextAction==="resubmit-once"&&F.authority.owner==="client"&&F.authority.operation==="resubmit-bound-request"&&F.retry.limit===1&&F.boilerplate.templateId==="gate-single-resubmission-v1"&&F.reasonCode===m.errorBody?.reason_code;let Pe=!1;if(Xe)try{_.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Dn(d,le.fingerprint,G.claimId,G.epicId),()=>{}),Pe=!0}catch{}R={schemaVersion:1,claimId:G.claimId,epicId:G.epicId,nextAction:G.nextAction,...typeof m.errorBody?.reason_code=="string"?{reasonCode:m.errorBody.reason_code}:{},...typeof m.errorBody?.fallback_action=="string"?{fallbackAction:m.errorBody.fallback_action}:{},...F?{semanticGateRemediation:F}:{},persisted:Pe,publicSafe:!0}}}const Y={...m.compatibility?{compatibility:m.compatibility}:{},...ee?{semanticGateRemediation:ee}:{},...O?{privateExecutionHostFailure:O}:{},...U?{invokeValidationFailure:U}:{},...R?{createEpicClaimRecovery:R}:{}};return{success:!1,error:nt(O?.message??U?.message??m.error??"Unknown error from server",zt),...p?{errorCode:p}:{},...Object.keys(Y).length>0?{metadata:Y}:{},exitCode:c}}const ui=xs(m.data);if(ui)return _.complete(Tr),ui;let De;try{De=e.privateExecutionBeta&&H==="create-epic"&&le?Yt(d).operations[le.fingerprint]:void 0}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const Pr=De?.planningProtocol==="root-staged-v1"&&typeof De.claimId=="string"&&typeof De.epicId=="string"&&wa(m.data,{claimId:De.claimId,epicId:De.epicId,...f(V.epics[De.epicId]?.createEpicPlanningMemoryPhysical)?{memoryReceiptId:V.epics[De.epicId].createEpicPlanningMemoryPhysical.receiptId}:{}});if(e.privateExecutionBeta&&!Pr&&!_a(m.data))return{success:!1,error:"private-execution-public-envelope-invalid",errorCode:"private-execution-public-envelope-invalid",exitCode:1};if(br&&M&&m.data.metadata?.mode==="arch-plan"&&f(m.data.metadata.archPlan)&&f(m.data.metadata.archPlan.execution)&&(m.data.metadata.archPlan.execution.nextAction==="delegate"||m.data.metadata.archPlan.execution.nextAction==="resume"||m.data.metadata.archPlan.execution.nextAction==="ask-user"||m.data.metadata.archPlan.execution.nextAction==="complete"&&m.data.metadata.archPlan.execution.currentStageCommand==="update-memory"||m.data.metadata.archPlan.execution.nextAction==="blocked"&&(m.data.metadata.archPlan.execution.currentStageCommand==="arch-ux-design"||m.data.metadata.archPlan.execution.currentStageCommand==="arch-performance"||m.data.metadata.archPlan.execution.currentStageCommand==="arch-testing"||m.data.metadata.archPlan.execution.currentStageCommand==="arch-infrastructure"||m.data.metadata.archPlan.execution.currentStageCommand==="arch-review")))try{await _.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>Ys({projectRoot:d,sourceStateSha256:br,requestExecution:M,initialBinding:Ye,answerReceipt:Qe,pactRecordedReceipt:Kt,metadata:m.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.
92
+ `),{success:!1,error:p,errorCode:p,exitCode:1}}if(Ke&&m.data.metadata?.mode==="menu"&&await _.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>vd(Ke,m.data.instructions,m.data.metadata),async()=>{}).catch(()=>{}),m.data.metadata&&await _.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"tier-cache",operation:"update"},()=>B.tierClient.updateQuotaFromResponse(m.data.metadata),async()=>{}).catch(()=>{}),m.data.metadata?.stateMutated===!0)try{const c=await _.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>{const{persistMigratedStateFromResponse:p}=await import("../yoloop/invoke-hooks.js");return p(m.data.metadata,d)},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}
93
93
  `),{success:!1,error:p,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}catch(c){if(m.data.metadata?.stateMutationReason==="inline-yolo-materialized-synthetic-story"){const p=c instanceof Error?c.message:String(c),I=`STATE_WRITEBACK_BLOCKED: inline-yolo persistence failed (${nt(p,zt)}).`;return process.stderr.write(`${I}
94
94
  `),{success:!1,error:I,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}const kr=m.data.metadata?.yoloopStoryWorktreeFallback;if(f(kr)&&typeof kr.reasonCode=="string"&&/^story-worktree-[a-z0-9-]{1,64}$/.test(kr.reasonCode)&&process.stderr.write(`[yoloop] v4 story-worktree plan not used: ${kr.reasonCode}.
95
- `),m.data.metadata?.gitLifecycleGraphAuthority)try{await C.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},()=>Dc(d,m.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.
95
+ `),m.data.metadata?.gitLifecycleGraphAuthority)try{await _.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},()=>Bc(d,m.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.
96
96
  `),{success:!1,error:p,errorCode:"GIT_LIFECYCLE_GRAPH_AUTHORITY_INVALID",exitCode:1}}if(m.data.metadata?.mode==="error"&&m.data.metadata?.errorCode==="CLIENT_UPGRADE_REQUIRED")return process.stderr.write(`
97
97
  `),process.stderr.write(`==================================================
98
98
  `),process.stderr.write(` YOLOOP CLIENT UPGRADE REQUIRED
@@ -108,19 +108,19 @@ The C04 barrier did not open within the bounded wait. Return this resumable rece
108
108
  `),process.stderr.write(` After upgrading, re-run your yoloop command.
109
109
  `),process.stderr.write(`==================================================
110
110
 
111
- `),{success:!1,error:"CLIENT_UPGRADE_REQUIRED: This client does not support yoloop client-side persistence. Run: npm install -g @ornexus/neocortex@latest",exitCode:3};if(m.data.metadata?.yoloopStateUpdate){const p=(m.data.metadata.yoloopStateUpdate.operations??[]).some(I=>I.type==="rollover_session"||I.type==="commit_successor_transition"||I.type==="acquire_lock"||I.type==="release_lock"&&I.expectedLeaseId!==void 0);try{const I=await C.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>{const{persistYoloopFromResponse:R}=await import("../yoloop/invoke-hooks.js");return R(m.data.metadata,d)},async()=>({ok:!0,authoritative:!1,reasonCodes:[]}));if(I&&I.ok===!1){const R=I.reasonCodes[0]??"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED";return process.stderr.write(`[Neocortex] ${R}. No yoloop continuation instructions were released.
111
+ `),{success:!1,error:"CLIENT_UPGRADE_REQUIRED: This client does not support yoloop client-side persistence. Run: npm install -g @ornexus/neocortex@latest",exitCode:3};if(m.data.metadata?.yoloopStateUpdate){const p=(m.data.metadata.yoloopStateUpdate.operations??[]).some(I=>I.type==="rollover_session"||I.type==="commit_successor_transition"||I.type==="acquire_lock"||I.type==="release_lock"&&I.expectedLeaseId!==void 0);try{const I=await _.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>{const{persistYoloopFromResponse:R}=await import("../yoloop/invoke-hooks.js");return R(m.data.metadata,d)},async()=>({ok:!0,authoritative:!1,reasonCodes:[]}));if(I&&I.ok===!1){const R=I.reasonCodes[0]??"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED";return process.stderr.write(`[Neocortex] ${R}. No yoloop continuation instructions were released.
112
112
  `),{success:!1,error:R,errorCode:R,exitCode:1}}}catch(I){if(p){const R=I instanceof Error?I.message.match(/\bYOLOOP_[A-Z0-9_]+\b/)?.[0]??"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED":"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED";return process.stderr.write(`[Neocortex] ${R}. No yoloop continuation instructions were released.
113
- `),{success:!1,error:R,errorCode:R,exitCode:1}}}}if(m.data.metadata?.continuityStateUpdate)try{const c=await C.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"continuity-store",operation:"update"},async()=>{const{persistContinuityFromResponse:p}=await import("../continuity/invoke-hooks.js");return p(m.data.metadata,d)},async()=>({ok:!0,reasonCodes:[]}));if(!c.ok){const p=c.reasonCodes.join(",");return process.stderr.write(`[Neocortex] continuity persistence failed: ${p}. No continuity mutation was committed.
113
+ `),{success:!1,error:R,errorCode:R,exitCode:1}}}}if(m.data.metadata?.continuityStateUpdate)try{const c=await _.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"continuity-store",operation:"update"},async()=>{const{persistContinuityFromResponse:p}=await import("../continuity/invoke-hooks.js");return p(m.data.metadata,d)},async()=>({ok:!0,reasonCodes:[]}));if(!c.ok){const p=c.reasonCodes.join(",");return process.stderr.write(`[Neocortex] continuity persistence failed: ${p}. No continuity mutation was committed.
114
114
  `),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${p}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}}catch(c){const p=c instanceof Error?c.message:String(c);return process.stderr.write(`[Neocortex] continuity persistence hook failed: ${p}. No continuity mutation was committed.
115
- `),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${nt(p,zt)}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}if(m.data.metadata?.tier_changed){const c=m.data.metadata.current_tier;try{await $.client.forceRefresh()?(await $.tierClient.invalidateTierCache(),process.stderr.write(`[Neocortex] Token atualizado automaticamente para tier ${c}
115
+ `),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${nt(p,zt)}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}if(m.data.metadata?.tier_changed){const c=m.data.metadata.current_tier;try{await B.client.forceRefresh()?(await B.tierClient.invalidateTierCache(),process.stderr.write(`[Neocortex] Token atualizado automaticamente para tier ${c}
116
116
  `)):process.stderr.write(`[Neocortex] Seu tier foi atualizado para ${c}! Execute "neocortex activate" para obter um token atualizado.
117
117
  `)}catch{process.stderr.write(`[Neocortex] Seu tier foi atualizado para ${c}! Execute "neocortex activate" para obter um token atualizado.
118
- `)}}let he,uo=!1,Or=!1;if(e.privateExecutionBeta&&!Pr)try{if(!Se&&!at&&it)throw new Error("private-execution-descriptor-unavailable");const c=Se?Wo:tt?.hostKind,p=()=>Se?Ie.hostVersion:tt.hostVersion;let I=d;const R=async X=>{const re=await ai(c,X,Ar),F=await ci(re,c);if(F.hostVersion!==tt.hostVersion)throw new Error("private-executor-version-drift");at=re,tt=F,I=X};if(!(Se?Ie:at&&tt)||!m.data.metadata?.privateExecution||!k||m.data.metadata?.mode!=="yolo"&&m.data.metadata?.mode!=="step"&&m.data.metadata?.mode!=="pipeline"&&m.data.metadata?.mode!=="create-epic"&&m.data.metadata?.mode!=="utility"&&m.data.metadata?.mode!=="tech-debt"&&m.data.metadata?.mode!=="ui-ux-review"||typeof m.data.metadata.stepId!="string")throw new Error("private-execution-descriptor-unavailable");const{consumePrivateExecutionDelivery:O,privateExecutionStateSnapshotSha256:W}=await import("../private-execution/delivery.js"),{preflightPrivateCodexExecutor:te,runPrivateCodexStep:V}=await import("../private-execution/codex-executor.js"),ne=async X=>{if(!Se)return R(X);const re=await te(X);if(re.hostVersion!==Ie.hostVersion)throw new Error("private-codex-version-drift");Ie=re},N=m.data.metadata.mode==="yolo",se=m.data.metadata.mode==="ui-ux-review"&&m.data.metadata.resolvedTrigger==="ui-ux-review",Ke=m.data.metadata.mode==="create-epic",Fe=f(m.data.metadata.privateExecution)?m.data.metadata.privateExecution:void 0,yt=f(Fe?.binding)?Fe.binding:void 0,lo=(Ke?m.data.metadata.resolvedTrigger==="create-epic"?Is({codexV6:Se,writeSetId:yt?.writeSetId,stepId:m.data.metadata.stepId}):(()=>{throw new Error(Se?"private-execution-planning-root-protocol-required":"private-execution-planning-step-unsupported")})():void 0)==="diagnosis",er=m.data.metadata.mode==="step"&&m.data.metadata.resolvedTrigger==="idea-diagnose"||lo,Vt=m.data.metadata.mode==="step"&&m.data.metadata.resolvedTrigger==="idea-research",Bt=m.data.metadata.mode==="step"&&m.data.metadata.resolvedTrigger==="generate-epic",ur=Ke||er;if(Vt&&!Ee||Bt&&!ce)throw new Error("private-execution-planning-predecessor-unavailable");const tr=m.data.metadata.mode==="utility"&&m.data.metadata.resolvedTrigger==="sync-openapi"||m.data.metadata.mode==="utility"&&m.data.metadata.resolvedTrigger==="chaos-plan"||E&&m.data.metadata.mode==="tech-debt"&&m.data.metadata.resolvedTrigger==="tech-debt",Pe=m.data.metadata.mode==="step"&&(m.data.metadata.resolvedTrigger==="arch-prd"||m.data.metadata.resolvedTrigger==="arch-architecture"||m.data.metadata.resolvedTrigger==="arch-fitness-functions"||m.data.metadata.resolvedTrigger==="arch-api-contracts"||m.data.metadata.resolvedTrigger==="arch-api-integrations"||m.data.metadata.resolvedTrigger==="arch-database"||m.data.metadata.resolvedTrigger==="arch-security"||m.data.metadata.resolvedTrigger==="arch-design-system"||m.data.metadata.resolvedTrigger==="arch-performance"||m.data.metadata.resolvedTrigger==="arch-testing"||m.data.metadata.resolvedTrigger==="arch-infrastructure"||m.data.metadata.resolvedTrigger==="arch-review"||m.data.metadata.resolvedTrigger==="update-memory")?m.data.metadata.resolvedTrigger:void 0,Pt=Pe!==void 0,ln=Pe==="arch-prd"?"arch-prd-docs-v1":Pe==="update-memory"?"arch-memory-canonical-v1":Pe==="arch-review"?"arch-review-doc-v1":Pe==="arch-infrastructure"?"arch-infrastructure-doc-v1":Pe==="arch-testing"?"arch-testing-doc-v1":Pe==="arch-performance"?"arch-performance-doc-v1":Pe==="arch-design-system"?"arch-design-system-doc-v1":Pe==="arch-security"?"arch-security-doc-v1":Pe==="arch-database"?"arch-database-doc-v1":Pe==="arch-api-integrations"?"arch-api-integrations-doc-v1":Pe==="arch-api-contracts"?"arch-api-contracts-docs-v1":Pe==="arch-fitness-functions"?"arch-fitness-tools-v1":"arch-architecture-doc-v1",It=m.data.metadata.mode==="step"&&m.data.metadata.resolvedTrigger==="generate-pacts",kt=m.data.metadata.mode==="step"&&m.data.metadata.resolvedTrigger==="arch-ux-design",Ot=m.data.metadata.mode==="utility"&&m.data.metadata.resolvedTrigger==="property-test",hn=E?"tech-debt":m.data.metadata.resolvedTrigger==="chaos-plan"?"chaos-plan":"sync-openapi",ho=E?"tech-debt-registry-v1":hn==="chaos-plan"?"chaos-quarterly-v1":"sync-openapi-contract-v1",Ze=L.archPlan?.execution,Lr=Ze?.targetEpicId,jr=Ze?.graphRevision;if(Pt&&(Ze?.currentStageCommand!==Pe||typeof Lr!="string"||!/^P[1-9][0-9]{0,11}$/.test(Lr)||typeof jr!="string"||!/^[a-f0-9]{64}$/.test(jr)))throw new Error("private-execution-architecture-admission-unverified");if(It&&(!Me||!mt||!Te||Ze?.currentStageCommand!=="generate-pacts"||Ze.continuationState!=="delegate"||Ze.targetEpicId!==Me.targetEpicId||Ze.graphRevision!==Me.graphRevision||!v(Ze.pactAnswerReceipt,Te.receipt)))throw new Error("private-execution-pact-admission-unverified");if(kt&&(!we||!ct||Ze?.currentStageCommand!=="arch-ux-design"||Ze.continuationState!=="delegate"||Ze.targetEpicId!==we.targetEpicId||Ze.graphRevision!==we.graphRevision))throw new Error("private-execution-ux-admission-unverified");if(Ot&&(!qe||!sn||!Jt||m.data.metadata.stepId!=="step-a8ce5c64"))throw new Error("private-execution-property-admission-unverified");let fo;if(It){const{planPactToolchainManifest:X,preparePactToolchainCandidate:re}=await import("../private-execution/pact-toolchain.js");try{X(d,Te.answers.generateProvider),fo=re(d,Te.answers.generateProvider)}catch(F){if(F.message!=="pact-toolchain-manifest-unsupported")throw F}}let Et,de,fn;const pe=m.data.metadata.gitLifecycleGraphAuthority,$t=m.data.metadata.privateExecutionRootAction;let st;if(N){if(!pe||typeof pe.storyId!="string"||typeof pe.graphRevision!="string"||typeof pe.executionBranch!="string")throw new Error("private-execution-graph-unavailable");if(st=pe.storyId,$t?.action==="prepare-epic-checkout"){const{parsePrivateExecutionDescriptor:z}=await import("../private-execution/delivery.js"),{prepareDirectYoloSetup:P}=await import("../git/direct-yolo-checkpoint.js"),{acceptDirectYoloSetupCheckpoint:Re}=await import("../git/direct-yolo-checkpoint.js"),{capturePrivateYoloCleanHead:pt,recordPrivateYoloCleanBaseline:Be}=await import("../private-execution/clean-baseline.js"),ke=z(m.data.metadata.privateExecution,{projectId:k,commandId:"yolo",stepId:m.data.metadata.stepId,graphRevision:pe.graphRevision,inputSha256:a.sha256,hostKind:c,hostVersion:p()}),De=await $.client.getToken();if(!De)throw new Error("private-execution-auth-unavailable");if(Or=!0,!await qi(T,{leaseId:ke.leaseId,...ke.binding},De))throw new Error("private-execution-setup-lease-cancel-unverified");const Nt=pt(d),Ut=await P({projectRoot:d,storyId:$t.storyId});if(!Ut.ok)throw new Error("private-execution-root-setup-denied");await Be(d,Ut.value,Nt);const{ensurePrivateYoloIsolatedSession:gn}=await import("../private-execution/isolated-session.js");await gn(d,$t.storyId,pe.graphRevision,e.privateExecutionWorkspaceParent);const vt=await Re({projectRoot:d,storyId:$t.storyId});if(!vt.ok)throw new Error(`private-execution-root-setup-checkpoint-denied:${vt.reasonCode}`);he={schemaVersion:1,outcome:"setup-accepted",executorOutcome:"not-run-root-only",setup:vt.value,publicSafe:!0};const lr=qr(m.data.instructions,{...m.data.metadata,...m.compatibility?{compatibility:m.compatibility}:{}});return C.complete(Tr),{success:!0,instructions:`# Setup do branch validado
118
+ `)}}let he,li=!1,Or=!1;if(e.privateExecutionBeta&&!Pr)try{if(!Se&&!at&&ot)throw new Error("private-execution-descriptor-unavailable");const c=Se?bn:tt?.hostKind,p=()=>Se?Ie.hostVersion:tt.hostVersion;let I=d;const R=async te=>{const ie=await so(c,te,Ar),z=await po(ie,c);if(z.hostVersion!==tt.hostVersion)throw new Error("private-executor-version-drift");at=ie,tt=z,I=te};if(!(Se?Ie:at&&tt)||!m.data.metadata?.privateExecution||!k||m.data.metadata?.mode!=="yolo"&&m.data.metadata?.mode!=="step"&&m.data.metadata?.mode!=="pipeline"&&m.data.metadata?.mode!=="create-epic"&&m.data.metadata?.mode!=="utility"&&m.data.metadata?.mode!=="tech-debt"&&m.data.metadata?.mode!=="ui-ux-review"||typeof m.data.metadata.stepId!="string")throw new Error("private-execution-descriptor-unavailable");const{consumePrivateExecutionDelivery:O,privateExecutionStateSnapshotSha256:U}=await import("../private-execution/delivery.js"),{preflightPrivateCodexExecutor:ee,runPrivateCodexStep:Y}=await import("../private-execution/codex-executor.js"),G=async te=>{if(!Se)return R(te);const ie=await ee(te);if(ie.hostVersion!==Ie.hostVersion)throw new Error("private-codex-version-drift");Ie=ie},L=m.data.metadata.mode==="yolo",F=m.data.metadata.mode==="ui-ux-review"&&m.data.metadata.resolvedTrigger==="ui-ux-review",Xe=m.data.metadata.mode==="create-epic",Pe=f(m.data.metadata.privateExecution)?m.data.metadata.privateExecution:void 0,yt=f(Pe?.binding)?Pe.binding:void 0,hi=(Xe?m.data.metadata.resolvedTrigger==="create-epic"?_s({codexV6:Se,writeSetId:yt?.writeSetId,stepId:m.data.metadata.stepId}):(()=>{throw new Error(Se?"private-execution-planning-root-protocol-required":"private-execution-planning-step-unsupported")})():void 0)==="diagnosis",er=m.data.metadata.mode==="step"&&m.data.metadata.resolvedTrigger==="idea-diagnose"||hi,Vt=m.data.metadata.mode==="step"&&m.data.metadata.resolvedTrigger==="idea-research",Bt=m.data.metadata.mode==="step"&&m.data.metadata.resolvedTrigger==="generate-epic",ur=Xe||er;if(Vt&&!Ee||Bt&&!se)throw new Error("private-execution-planning-predecessor-unavailable");const tr=m.data.metadata.mode==="utility"&&m.data.metadata.resolvedTrigger==="sync-openapi"||m.data.metadata.mode==="utility"&&m.data.metadata.resolvedTrigger==="chaos-plan"||E&&m.data.metadata.mode==="tech-debt"&&m.data.metadata.resolvedTrigger==="tech-debt",ke=m.data.metadata.mode==="step"&&(m.data.metadata.resolvedTrigger==="arch-prd"||m.data.metadata.resolvedTrigger==="arch-architecture"||m.data.metadata.resolvedTrigger==="arch-fitness-functions"||m.data.metadata.resolvedTrigger==="arch-api-contracts"||m.data.metadata.resolvedTrigger==="arch-api-integrations"||m.data.metadata.resolvedTrigger==="arch-database"||m.data.metadata.resolvedTrigger==="arch-security"||m.data.metadata.resolvedTrigger==="arch-design-system"||m.data.metadata.resolvedTrigger==="arch-performance"||m.data.metadata.resolvedTrigger==="arch-testing"||m.data.metadata.resolvedTrigger==="arch-infrastructure"||m.data.metadata.resolvedTrigger==="arch-review"||m.data.metadata.resolvedTrigger==="update-memory")?m.data.metadata.resolvedTrigger:void 0,Pt=ke!==void 0,ln=ke==="arch-prd"?"arch-prd-docs-v1":ke==="update-memory"?"arch-memory-canonical-v1":ke==="arch-review"?"arch-review-doc-v1":ke==="arch-infrastructure"?"arch-infrastructure-doc-v1":ke==="arch-testing"?"arch-testing-doc-v1":ke==="arch-performance"?"arch-performance-doc-v1":ke==="arch-design-system"?"arch-design-system-doc-v1":ke==="arch-security"?"arch-security-doc-v1":ke==="arch-database"?"arch-database-doc-v1":ke==="arch-api-integrations"?"arch-api-integrations-doc-v1":ke==="arch-api-contracts"?"arch-api-contracts-docs-v1":ke==="arch-fitness-functions"?"arch-fitness-tools-v1":"arch-architecture-doc-v1",It=m.data.metadata.mode==="step"&&m.data.metadata.resolvedTrigger==="generate-pacts",kt=m.data.metadata.mode==="step"&&m.data.metadata.resolvedTrigger==="arch-ux-design",Ot=m.data.metadata.mode==="utility"&&m.data.metadata.resolvedTrigger==="property-test",hn=E?"tech-debt":m.data.metadata.resolvedTrigger==="chaos-plan"?"chaos-plan":"sync-openapi",fi=E?"tech-debt-registry-v1":hn==="chaos-plan"?"chaos-quarterly-v1":"sync-openapi-contract-v1",Ze=D.archPlan?.execution,Lr=Ze?.targetEpicId,jr=Ze?.graphRevision;if(Pt&&(Ze?.currentStageCommand!==ke||typeof Lr!="string"||!/^P[1-9][0-9]{0,11}$/.test(Lr)||typeof jr!="string"||!/^[a-f0-9]{64}$/.test(jr)))throw new Error("private-execution-architecture-admission-unverified");if(It&&(!Ve||!mt||!Te||Ze?.currentStageCommand!=="generate-pacts"||Ze.continuationState!=="delegate"||Ze.targetEpicId!==Ve.targetEpicId||Ze.graphRevision!==Ve.graphRevision||!C(Ze.pactAnswerReceipt,Te.receipt)))throw new Error("private-execution-pact-admission-unverified");if(kt&&(!we||!ct||Ze?.currentStageCommand!=="arch-ux-design"||Ze.continuationState!=="delegate"||Ze.targetEpicId!==we.targetEpicId||Ze.graphRevision!==we.graphRevision))throw new Error("private-execution-ux-admission-unverified");if(Ot&&(!qe||!sn||!Jt||m.data.metadata.stepId!=="step-a8ce5c64"))throw new Error("private-execution-property-admission-unverified");let gi;if(It){const{planPactToolchainManifest:te,preparePactToolchainCandidate:ie}=await import("../private-execution/pact-toolchain.js");try{te(d,Te.answers.generateProvider),gi=ie(d,Te.answers.generateProvider)}catch(z){if(z.message!=="pact-toolchain-manifest-unsupported")throw z}}let Et,de,fn;const pe=m.data.metadata.gitLifecycleGraphAuthority,$t=m.data.metadata.privateExecutionRootAction;let st;if(L){if(!pe||typeof pe.storyId!="string"||typeof pe.graphRevision!="string"||typeof pe.executionBranch!="string")throw new Error("private-execution-graph-unavailable");if(st=pe.storyId,$t?.action==="prepare-epic-checkout"){const{parsePrivateExecutionDescriptor:q}=await import("../private-execution/delivery.js"),{prepareDirectYoloSetup:P}=await import("../git/direct-yolo-checkpoint.js"),{acceptDirectYoloSetupCheckpoint:Re}=await import("../git/direct-yolo-checkpoint.js"),{capturePrivateYoloCleanHead:pt,recordPrivateYoloCleanBaseline:$e}=await import("../private-execution/clean-baseline.js"),Oe=q(m.data.metadata.privateExecution,{projectId:k,commandId:"yolo",stepId:m.data.metadata.stepId,graphRevision:pe.graphRevision,inputSha256:a.sha256,hostKind:c,hostVersion:p()}),Le=await B.client.getToken();if(!Le)throw new Error("private-execution-auth-unavailable");if(Or=!0,!await Qo(T,{leaseId:Oe.leaseId,...Oe.binding},Le))throw new Error("private-execution-setup-lease-cancel-unverified");const Nt=pt(d),Ut=await P({projectRoot:d,storyId:$t.storyId});if(!Ut.ok)throw new Error("private-execution-root-setup-denied");await $e(d,Ut.value,Nt);const{ensurePrivateYoloIsolatedSession:gn}=await import("../private-execution/isolated-session.js");await gn(d,$t.storyId,pe.graphRevision,e.privateExecutionWorkspaceParent);const vt=await Re({projectRoot:d,storyId:$t.storyId});if(!vt.ok)throw new Error(`private-execution-root-setup-checkpoint-denied:${vt.reasonCode}`);he={schemaVersion:1,outcome:"setup-accepted",executorOutcome:"not-run-root-only",setup:vt.value,publicSafe:!0};const lr=qr(m.data.instructions,{...m.data.metadata,...m.compatibility?{compatibility:m.compatibility}:{}});return _.complete(Tr),{success:!0,instructions:`# Setup do branch validado
119
119
 
120
- O root confirmou o checkpoint C01 no branch do \xE9pico. Reexecute o mesmo YOLO para avan\xE7ar \xE0 pr\xF3xima etapa.`,metadata:{...lr.metadata,privateExecutionReceipt:he},exitCode:0}}let X;try{X=Ae("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:d,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{throw new Error("private-execution-execution-branch-mismatch")}if(X!==pe.executionBranch)throw new Error("private-execution-execution-branch-mismatch");const re=ar(d,{required:!0}),F=typeof pe.epicId=="string"?re.epics[pe.epicId]:void 0,dt=f(F?.branch_lease)?F.branch_lease:void 0;if(!F||F.graph_revision!==pe.graphRevision||!dt||dt.ownerStoryId!==pe.storyId||typeof dt.expiresAt!="string"||!Number.isFinite(Date.parse(dt.expiresAt))||Date.parse(dt.expiresAt)<=Date.now())throw new Error("private-execution-writer-lease-unavailable")}else if(m.data.metadata.mode==="step"&&(m.data.metadata.resolvedTrigger==="research"||m.data.metadata.resolvedTrigger==="write-spec"||m.data.metadata.resolvedTrigger==="create-tasks"||m.data.metadata.resolvedTrigger==="implement")||m.data.metadata.mode==="pipeline"&&m.data.metadata.resolvedTrigger==="exec"||Ke&&m.data.metadata.resolvedTrigger==="create-epic"||se||er||Vt||Bt||tr||Pt||It||kt||Ot){if(!ur&&!Vt&&!Bt&&!tr&&!se&&!Pt&&!It&&!kt&&!Ot&&typeof m.data.metadata.storyId!="string")throw new Error("private-execution-descriptor-unavailable")}else throw new Error("private-execution-descriptor-unavailable");if(N){const{ensurePrivateYoloIsolatedSession:X,reconcilePrivateYoloIsolatedSession:re}=await import("../private-execution/isolated-session.js");if($t?.action==="checkpoint-epic-story")await re(d,st,pe.graphRevision);else{const F=await X(d,st,pe.graphRevision,e.privateExecutionWorkspaceParent);await ne(F.workspace.workspacePath)}}if(Se&&Date.now()-Ie.observedAtMs>2e4){const X=await te(Ie.projectRoot);if(X.hostVersion!==Ie.hostVersion)throw new Error("private-codex-version-drift");Ie=X}const go=await $.client.getToken();if(!go)throw new Error("private-execution-auth-unavailable");const Ve=ur?m.data.metadata.epicClaim:void 0;if(ur&&(!Ve||typeof Ve.claimId!="string"||typeof Ve.epicId!="string"))throw new Error("private-execution-descriptor-unavailable");if(ur){if(!le)throw new Error("private-execution-epic-claim-admission-unverified");C.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>On(d,le.fingerprint,Ve.claimId,Ve.epicId,lo?"root-staged-v1":void 0),()=>{}),uo=!0;const{preparePrivateYoloIsolatedWorkspace:X,PRIVATE_EPIC_PENDING_SIDECAR:re}=await import("../private-execution/isolated-workspace.js"),F=e.privateExecutionWorkspaceParent??q(yr(),".local","share","neocortex","private-epic-workspaces");e.privateExecutionWorkspaceParent||rr(F,{recursive:!0,mode:448}),Et=X(d,F,!0),fn=Le("sha256").update($e(q(d,re))).digest("hex"),await ne(Et.workspacePath)}else if(!N&&!se){const{preparePrivateYoloIsolatedWorkspace:X}=await import("../private-execution/isolated-workspace.js"),re=e.privateExecutionWorkspaceParent??q(yr(),".local","share","neocortex","private-step-workspaces");if(e.privateExecutionWorkspaceParent||rr(re,{recursive:!0,mode:448}),de=X(d,re,Vt||Bt),tr||Pt||It||kt||Ot){if(!ie)throw new Error("private-execution-project-snapshot-unverified");const{assertPrivateProjectStepBaseline:F}=await import("../private-execution/isolated-workspace.js");F(de,ie)}await ne(de.workspacePath)}const St=await O(m.data.metadata.privateExecution,{projectId:k,commandId:N?"yolo":Ke?"create-epic":Pt?Pe:It?"generate-pacts":kt?"arch-ux-design":Ot?"property-test":tr?hn:m.data.metadata.mode==="pipeline"?"exec":m.data.metadata.resolvedTrigger,stepId:m.data.metadata.stepId,...N?{graphRevision:pe.graphRevision}:{...ur?{claimId:Ve.claimId,epicId:Ve.epicId,...er?{writeSetId:"idea-diagnosis-v1"}:{}}:Vt?{claimId:Ee.claimId,epicId:Ee.epicId,diagnosisReceiptId:Ee.diagnosisReceiptId,intakeRevision:Ee.intakeRevision,physicalAcceptanceReceiptId:Ee.physicalAcceptanceReceiptId,writeSetId:"idea-research-v1"}:Bt?{claimId:ce.claimId,epicId:ce.epicId,diagnosisReceiptId:ce.diagnosisReceiptId,researchReceiptId:ce.researchReceiptId,intakeRevision:ce.intakeRevision,physicalAcceptanceReceiptId:ce.physicalAcceptanceReceiptId,writeSetId:"generate-epic-v1"}:tr?{writeSetId:ho}:se?{format:u.selection.uiUxReview?.json===!0?"json":"markdown"}:Pt?{targetEpicId:Lr,graphRevision:jr,writeSetId:ln}:It?{targetEpicId:Me.targetEpicId,graphRevision:Me.graphRevision,answersSha256:Me.answersSha256,specSha256:Me.specSha256,pathsSha256:Me.pathsSha256,endpointCount:Me.endpointCount,pathCount:Me.pathCount}:kt?{targetEpicId:we.targetEpicId,graphRevision:we.graphRevision,adapterId:we.adapterId,authoritySha256:we.authoritySha256,pathsSha256:we.pathsSha256,screenCount:we.screenCount,pathCount:we.pathCount}:Ot?{prdPath:qe.prdPath,prdSha256:qe.prdSha256,planSha256:qe.planSha256,pathsSha256:qe.pathsSha256,aggregateCount:qe.aggregateCount,invariantCount:qe.invariantCount,pathCount:qe.pathCount,language:qe.language,numRuns:qe.numRuns}:{storyId:m.data.metadata.storyId},stateSnapshotSha256:W(L)},inputSha256:a.sha256,hostKind:c,hostVersion:p()},X=>yp(T,{...X},go));if(Or=!0,se){const{parsePrivateExecutionDescriptor:X}=await import("../private-execution/delivery.js"),re=X(m.data.metadata.privateExecution);if(re.schemaVersion!==11||re.binding.commandId!=="ui-ux-review"||re.binding.format!==(u.selection.uiUxReview?.json===!0?"json":"markdown"))throw new Error("private-execution-report-binding-unverified");const{storePrivateUiUxReviewReport:F}=await import("../private-execution/private-report-store.js");he={schemaVersion:1,outcome:"report-stored",report:await F({projectRoot:d,material:St,format:re.binding.format,sha256:re.materialSha256}),publicSafe:!0}}else if($t?.action==="checkpoint-epic-story"){const{runPrivateYoloRootCheckpoint:X}=await import("../private-execution/root-checkpoint.js");he={...await X(d,$t)}}else{const X=er?`${St}
120
+ O root confirmou o checkpoint C01 no branch do \xE9pico. Reexecute o mesmo YOLO para avan\xE7ar \xE0 pr\xF3xima etapa.`,metadata:{...lr.metadata,privateExecutionReceipt:he},exitCode:0}}let te;try{te=Ae("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:d,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{throw new Error("private-execution-execution-branch-mismatch")}if(te!==pe.executionBranch)throw new Error("private-execution-execution-branch-mismatch");const ie=ar(d,{required:!0}),z=typeof pe.epicId=="string"?ie.epics[pe.epicId]:void 0,dt=f(z?.branch_lease)?z.branch_lease:void 0;if(!z||z.graph_revision!==pe.graphRevision||!dt||dt.ownerStoryId!==pe.storyId||typeof dt.expiresAt!="string"||!Number.isFinite(Date.parse(dt.expiresAt))||Date.parse(dt.expiresAt)<=Date.now())throw new Error("private-execution-writer-lease-unavailable")}else if(m.data.metadata.mode==="step"&&(m.data.metadata.resolvedTrigger==="research"||m.data.metadata.resolvedTrigger==="write-spec"||m.data.metadata.resolvedTrigger==="create-tasks"||m.data.metadata.resolvedTrigger==="implement")||m.data.metadata.mode==="pipeline"&&m.data.metadata.resolvedTrigger==="exec"||Xe&&m.data.metadata.resolvedTrigger==="create-epic"||F||er||Vt||Bt||tr||Pt||It||kt||Ot){if(!ur&&!Vt&&!Bt&&!tr&&!F&&!Pt&&!It&&!kt&&!Ot&&typeof m.data.metadata.storyId!="string")throw new Error("private-execution-descriptor-unavailable")}else throw new Error("private-execution-descriptor-unavailable");if(L){const{ensurePrivateYoloIsolatedSession:te,reconcilePrivateYoloIsolatedSession:ie}=await import("../private-execution/isolated-session.js");if($t?.action==="checkpoint-epic-story")await ie(d,st,pe.graphRevision);else{const z=await te(d,st,pe.graphRevision,e.privateExecutionWorkspaceParent);await G(z.workspace.workspacePath)}}if(Se&&Date.now()-Ie.observedAtMs>2e4){const te=await ee(Ie.projectRoot);if(te.hostVersion!==Ie.hostVersion)throw new Error("private-codex-version-drift");Ie=te}const mi=await B.client.getToken();if(!mi)throw new Error("private-execution-auth-unavailable");const Be=ur?m.data.metadata.epicClaim:void 0;if(ur&&(!Be||typeof Be.claimId!="string"||typeof Be.epicId!="string"))throw new Error("private-execution-descriptor-unavailable");if(ur){if(!le)throw new Error("private-execution-epic-claim-admission-unverified");_.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Dn(d,le.fingerprint,Be.claimId,Be.epicId,hi?"root-staged-v1":void 0),()=>{}),li=!0;const{preparePrivateYoloIsolatedWorkspace:te,PRIVATE_EPIC_PENDING_SIDECAR:ie}=await import("../private-execution/isolated-workspace.js"),z=e.privateExecutionWorkspaceParent??J(yr(),".local","share","neocortex","private-epic-workspaces");e.privateExecutionWorkspaceParent||rr(z,{recursive:!0,mode:448}),Et=te(d,z,!0),fn=je("sha256").update(Ue(J(d,ie))).digest("hex"),await G(Et.workspacePath)}else if(!L&&!F){const{preparePrivateYoloIsolatedWorkspace:te}=await import("../private-execution/isolated-workspace.js"),ie=e.privateExecutionWorkspaceParent??J(yr(),".local","share","neocortex","private-step-workspaces");if(e.privateExecutionWorkspaceParent||rr(ie,{recursive:!0,mode:448}),de=te(d,ie,Vt||Bt),tr||Pt||It||kt||Ot){if(!ce)throw new Error("private-execution-project-snapshot-unverified");const{assertPrivateProjectStepBaseline:z}=await import("../private-execution/isolated-workspace.js");z(de,ce)}await G(de.workspacePath)}const St=await O(m.data.metadata.privateExecution,{projectId:k,commandId:L?"yolo":Xe?"create-epic":Pt?ke:It?"generate-pacts":kt?"arch-ux-design":Ot?"property-test":tr?hn:m.data.metadata.mode==="pipeline"?"exec":m.data.metadata.resolvedTrigger,stepId:m.data.metadata.stepId,...L?{graphRevision:pe.graphRevision}:{...ur?{claimId:Be.claimId,epicId:Be.epicId,...er?{writeSetId:"idea-diagnosis-v1"}:{}}:Vt?{claimId:Ee.claimId,epicId:Ee.epicId,diagnosisReceiptId:Ee.diagnosisReceiptId,intakeRevision:Ee.intakeRevision,physicalAcceptanceReceiptId:Ee.physicalAcceptanceReceiptId,writeSetId:"idea-research-v1"}:Bt?{claimId:se.claimId,epicId:se.epicId,diagnosisReceiptId:se.diagnosisReceiptId,researchReceiptId:se.researchReceiptId,intakeRevision:se.intakeRevision,physicalAcceptanceReceiptId:se.physicalAcceptanceReceiptId,writeSetId:"generate-epic-v1"}:tr?{writeSetId:fi}:F?{format:u.selection.uiUxReview?.json===!0?"json":"markdown"}:Pt?{targetEpicId:Lr,graphRevision:jr,writeSetId:ln}:It?{targetEpicId:Ve.targetEpicId,graphRevision:Ve.graphRevision,answersSha256:Ve.answersSha256,specSha256:Ve.specSha256,pathsSha256:Ve.pathsSha256,endpointCount:Ve.endpointCount,pathCount:Ve.pathCount}:kt?{targetEpicId:we.targetEpicId,graphRevision:we.graphRevision,adapterId:we.adapterId,authoritySha256:we.authoritySha256,pathsSha256:we.pathsSha256,screenCount:we.screenCount,pathCount:we.pathCount}:Ot?{prdPath:qe.prdPath,prdSha256:qe.prdSha256,planSha256:qe.planSha256,pathsSha256:qe.pathsSha256,aggregateCount:qe.aggregateCount,invariantCount:qe.invariantCount,pathCount:qe.pathCount,language:qe.language,numRuns:qe.numRuns}:{storyId:m.data.metadata.storyId},stateSnapshotSha256:U(D)},inputSha256:a.sha256,hostKind:c,hostVersion:p()},te=>Cp(T,{...te},mi));if(Or=!0,F){const{parsePrivateExecutionDescriptor:te}=await import("../private-execution/delivery.js"),ie=te(m.data.metadata.privateExecution);if(ie.schemaVersion!==11||ie.binding.commandId!=="ui-ux-review"||ie.binding.format!==(u.selection.uiUxReview?.json===!0?"json":"markdown"))throw new Error("private-execution-report-binding-unverified");const{storePrivateUiUxReviewReport:z}=await import("../private-execution/private-report-store.js");he={schemaVersion:1,outcome:"report-stored",report:await z({projectRoot:d,material:St,format:ie.binding.format,sha256:ie.materialSha256}),publicSafe:!0}}else if($t?.action==="checkpoint-epic-story"){const{runPrivateYoloRootCheckpoint:te}=await import("../private-execution/root-checkpoint.js");he={...await te(d,$t)}}else{const te=er?`${St}
121
121
 
122
122
  Private P01 handoff (local only):
123
- The durable reserved epic ID is ${Ve.epicId}. Complete only the diagnosis for this exact ID. Write exactly .neocortex/planning/epic-${Ve.epicId}/idea.json, diagnosis.md, enriched-prompt.md and the matching entry in .neocortex/planning/planning.json. Do not write state.json, Git controls, another epic, or P02/P03 artifacts; do not auto-continue to the next step. The root will independently review and persist the accepted planning checkpoint.
123
+ The durable reserved epic ID is ${Be.epicId}. Complete only the diagnosis for this exact ID. Write exactly .neocortex/planning/epic-${Be.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.
124
124
  `:Vt?`${St}
125
125
 
126
126
  Private P02 handoff (local only):
@@ -128,8 +128,8 @@ The admitted epic is ${Ee.epicId}. Research only this exact diagnosed epic. Writ
128
128
  `:Bt?`${St}
129
129
 
130
130
  Private P03 handoff (local only):
131
- The admitted epic is ${ce.epicId}. Generate exactly docs/epics/epic-${ce.epicId}.md, 1 to 24 contiguous docs/stories/${ce.epicId}.NN.story.md files (01 through 24), and the matching transition in .neocortex/planning/planning.json. The 1 to 24 range is a safety maximum, not a required count. Derive the implementation story count from the accepted research scope; keep later epic lifecycle gates out of implementation stories. Epic frontmatter must contain its exact id and stories_count matching the files, and the document must contain the exact section heading ## Stories. Story frontmatter must use exactly one canonical epic_id field for this epic, with status backlog; do not emit the legacy epic alias. Each story needs the exact heading ## Acceptance Criteria and Given/When/Then criteria. In planning.json preserve all other entries and fields; for this epic set status generated, append only the current generation step after the two accepted predecessors, set completed_at to a non-null ISO timestamp, and add output_files.epic plus the ordered output_files.stories list. Keep a valid ISO last_scan. This is completion of the candidate index only, not root QA, memory or epic completion. Do not write state.json, Git controls, another epic, or subsequent-stage artifacts; do not auto-continue. The root will independently review and seal the generated candidate.
132
- `:Pt?(await import("../private-execution/isolated-admission.js")).appendPrivateArchitectureHandoff(St,Pe,ln,yo(L.archPlan?.execution?.nonUiScopeReceipt)?"non-ui":"all"):It?`${St}
131
+ The admitted epic is ${se.epicId}. Generate exactly docs/epics/epic-${se.epicId}.md, 1 to 24 contiguous docs/stories/${se.epicId}.NN.story.md files (01 through 24), and the matching transition in .neocortex/planning/planning.json. The 1 to 24 range is a safety maximum, not a required count. Derive the implementation story count from the accepted research scope; keep later epic lifecycle gates out of implementation stories. Epic frontmatter must contain its exact id and stories_count matching the files, and the document must contain the exact section heading ## Stories. Story frontmatter must use exactly one canonical epic_id field for this epic, with status backlog; do not emit the legacy epic alias. Each story needs the exact heading ## Acceptance Criteria and Given/When/Then criteria. In planning.json preserve all other entries and fields; for this epic set status generated, append only the current generation step after the two accepted predecessors, set completed_at to a non-null ISO timestamp, and add output_files.epic plus the ordered output_files.stories list. Keep a valid ISO last_scan. This is completion of the candidate index only, not root QA, memory or epic completion. Do not write state.json, Git controls, another epic, or subsequent-stage artifacts; do not auto-continue. The root will independently review and seal the generated candidate.
132
+ `:Pt?(await import("../private-execution/isolated-admission.js")).appendPrivateArchitectureHandoff(St,ke,ln,Ii(D.archPlan?.execution?.nonUiScopeReceipt)?"non-ui":"all"):It?`${St}
133
133
 
134
134
  Private A03.5 handoff (local only):
135
135
  ${JSON.stringify({consumer:Te.answers.consumer,provider:Te.answers.provider,matchersAggressive:Te.answers.matchersAggressive,generateProvider:Te.answers.generateProvider,brokerConfigured:Te.answers.brokerUrl!==null,allowedPaths:mt.paths})}
@@ -142,21 +142,21 @@ Write only the approved paths. Keep synthetic fixtures and the canonical approve
142
142
  `:Ot?`${St}
143
143
 
144
144
  Private property-test handoff (local only):
145
- ${JSON.stringify({language:Jt.language,numRuns:Jt.numRuns,aggregates:Jt.aggregates.map(z=>({name:z.name,implementationFile:z.implementationFile,testFile:z.testFile,invariantCount:z.invariantCount}))})}
145
+ ${JSON.stringify({language:Jt.language,numRuns:Jt.numRuns,aggregates:Jt.aggregates.map(q=>({name:q.name,implementationFile:q.implementationFile,testFile:q.testFile,invariantCount:q.invariantCount}))})}
146
146
  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.
147
- `:St;let re=X;if(N){const{readPrivateYoloFrozenWriteSet:z}=await import("../private-execution/clean-baseline.js"),{appendPrivateYoloFrozenHandoff:P}=await import("../private-execution/frozen-handoff.js"),Re=await z(d,st,pe.executionBranch,pe.graphRevision);re=P(X,Re);const{resumePrivateYoloIsolatedSession:pt}=await import("../private-execution/isolated-session.js"),Be=await pt(d,st,pe.graphRevision),ke=Zr(d,{epicAware:!0}).stories[st],De=L.stories[st];if(!ke||!De||ke.status!==De.status||JSON.stringify(ke.steps_completed)!==JSON.stringify(De.steps_completed))throw new Error("private-execution-phase-snapshot-drift");const Nt=Ae("git",["rev-parse","HEAD"],{cwd:d,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();re+=`
147
+ `:St;let ie=te;if(L){const{readPrivateYoloFrozenWriteSet:q}=await import("../private-execution/clean-baseline.js"),{appendPrivateYoloFrozenHandoff:P}=await import("../private-execution/frozen-handoff.js"),Re=await q(d,st,pe.executionBranch,pe.graphRevision);ie=P(te,Re);const{resumePrivateYoloIsolatedSession:pt}=await import("../private-execution/isolated-session.js"),$e=await pt(d,st,pe.graphRevision),Oe=Zr(d,{epicAware:!0}).stories[st],Le=D.stories[st];if(!Oe||!Le||Oe.status!==Le.status||JSON.stringify(Oe.steps_completed)!==JSON.stringify(Le.steps_completed))throw new Error("private-execution-phase-snapshot-drift");const Nt=Ae("git",["rev-parse","HEAD"],{cwd:d,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();ie+=`
148
148
  Root physical dispatch observations (data, not phase completion):
149
- `+JSON.stringify({storyId:st,graphRevision:pe.graphRevision,sourceHeadSha:Nt,privateSnapshotSha:Be.snapshotSha,effectiveStatus:ke.status,hostKind:c,hostVersion:p()})+`
149
+ `+JSON.stringify({storyId:st,graphRevision:pe.graphRevision,sourceHeadSha:Nt,privateSnapshotSha:$e.snapshotSha,effectiveStatus:Oe.status,hostKind:c,hostVersion:p()})+`
150
150
  Use these observed revisions and runtime facts; do not infer Git metadata or substitute an invented revision.
151
- `}const F=Se?await V(re,Ie,{requireWorkspaceEffect:!0,...e.onPrivateExecutionWorkspaceFailure===void 0?{}:{onWorkspaceEffectFailure:e.onPrivateExecutionWorkspaceFailure},...e.privateExecutionModel===void 0?{}:{model:e.privateExecutionModel},...N?{expectedExecutionBranch:pe.executionBranch}:Et?{expectedExecutionBranch:Et.executionBranch}:de?{expectedExecutionBranch:de.executionBranch}:{}}):await ys(at,re,{hostKind:c,workspaceRoot:I,requireWorkspaceEffect:!0,...N?{expectedExecutionBranch:pe.executionBranch}:Et?{expectedExecutionBranch:Et.executionBranch}:de?{expectedExecutionBranch:de.executionBranch}:{}}),dt=async(z,P,Re,pt)=>{if(Se)return{};const{planningQaReceiptFragment:Be}=await import("./planning-qa.js");return{planningQa:Be(z,{root:d,claimId:P,epicId:Re,admission:pt})}};if(N){const{admitPrivateYoloIsolatedSessionStep:z}=await import("../private-execution/isolated-session.js"),P=await z(d,st,pe.graphRevision);let Re;if(m.data.metadata.stepId===va){const Be=m.data.metadata.mutationQaFeature;if(!Be)throw new Error("private-execution-mutation-qa-authority-unavailable");if(!Be.enabled)Re={schemaVersion:1,status:"skipped-server-authority",publicSafe:!0};else{let ke,De;try{const Nt=P.session.workspace.workspacePath,Ut=`sha:${P.session.workspace.baseSha}`,{planMutationQa:gn}=await import("./mutation-qa.js"),vt=gn(Nt,Ut);if(vt.headSha!==P.session.snapshotSha)throw new Error("private-execution-mutation-qa-snapshot-drift");let lr="not-run";if(vt.outcome==="ready"){const{runAndRecordMutationQa:mn}=await import("./mutation-qa-checkpoint.js");if(lr=mn(Nt,Ut,vt.planSha256).result.outcome,lr==="skipped-host-isolation-unavailable")throw new Error("private-execution-mutation-qa-host-isolation-unavailable")}const{classifyMutationQaGate:da}=await import("./mutation-qa-gate.js");if(ke=da(Nt,Ut,vt.planSha256),ke.followUpDebtRequired){const{recordMutationQaFollowUpDebt:mn}=await import("./mutation-qa-checkpoint.js");De=mn(Nt,Ut,vt.planSha256,ke.status,lr,d)}const{resumePrivateYoloIsolatedSession:pa}=await import("../private-execution/isolated-session.js");if((await pa(d,st,pe.graphRevision)).snapshotSha!==P.session.snapshotSha)throw new Error("private-execution-mutation-qa-snapshot-drift")}catch{throw new Error("private-execution-mutation-qa-unverified")}if(ke.blocksLocalQa||!ke.safeToContinueLocalQa&&!De)throw new Error(`private-execution-mutation-qa-${ke.status}`);Re={...ke,...De?{followUpDebt:{status:"recorded",owner:De.owner,severity:De.severity,reasonCode:De.reasonCode,planSha256:De.planSha256,publicSafe:!0}}:{}}}}const pt={schemaVersion:1,outcome:P.admission.outcome,sequence:P.session.sequence,snapshotSha:P.session.snapshotSha,patchSha256:P.admission.patchSha256,changedPathCount:P.admission.changedPaths.length};he={...F,isolation:pt,...Re?{mutationQa:Re}:{}}}else if(Et){const{admitPrivateEpicClaimWorkspace:z,admitPrivateIdeaDiagnosisWorkspace:P}=await import("../private-execution/isolated-admission.js"),Re=er?P(Et,Ve.claimId,Ve.epicId,le.fingerprint,fn,u.selection.positionals.join(" ").replace(/^[-:–—]\s+/,"")):z(Et,Ve.claimId,Ve.epicId,le.fingerprint,fn);he={...F,isolation:{schemaVersion:1,outcome:Re.outcome,baseSha:Re.baseSha,patchSha256:Re.patchSha256,changedPathCount:Re.changedPaths.length},...er?await dt("diagnosis",Ve.claimId,Ve.epicId,Re):{}}}else if(de&&Vt){const{admitPrivateIdeaResearchWorkspace:z}=await import("../private-execution/isolated-admission.js"),P=z(de,Ee.claimId,Ee.epicId,Ee.diagnosisReceiptId,Ee.intakeRevision,Ee.sourceStateSha256);he={...F,isolation:{schemaVersion:1,outcome:P.outcome,baseSha:P.baseSha,patchSha256:P.patchSha256,changedPathCount:P.changedPaths.length},...await dt("research",Ee.claimId,Ee.epicId,P)}}else if(de&&Bt){const{admitPrivateGenerateEpicWorkspace:z}=await import("../private-execution/isolated-admission.js"),P=z(de,ce.claimId,ce.epicId,ce.diagnosisReceiptId,ce.researchReceiptId,ce.intakeRevision,ce.sourceStateSha256);he={...F,isolation:{schemaVersion:1,outcome:P.outcome,baseSha:P.baseSha,patchSha256:P.patchSha256,changedPathCount:P.changedPaths.length},...await dt("generation",ce.claimId,ce.epicId,P)}}else if(de&&It){const{admitPrivatePactWorkspace:z}=await import("../private-execution/isolated-admission.js"),{inspectPactToolchain:P}=await import("../private-execution/pact-toolchain.js"),{verifyPactConsumerRuntime:Re}=await import("../private-execution/pact-consumer-runtime.js"),pt=Te.answers.generateProvider,Be=z(de,Me.targetEpicId,Me.graphRevision,Te.receipt,mt,fo),ke=P(d,pt),De=Re(d,mt,pt);he={...F,isolation:{schemaVersion:1,outcome:Be.outcome,baseSha:Be.baseSha,patchSha256:Be.patchSha256,changedPathCount:Be.changedPaths.length,consumerBindingCandidateCount:Be.consumerBindingCandidateCount,consumerScaffoldCount:Be.consumerScaffoldCount,toolchain:ke,consumerRuntime:De}}}else if(de&&kt){const{admitPrivateUxWorkspace:z}=await import("../private-execution/isolated-admission.js"),P=z(de,we.targetEpicId,we.graphRevision,ct);he={...F,isolation:{schemaVersion:1,outcome:P.outcome,baseSha:P.baseSha,patchSha256:P.patchSha256,changedPathCount:P.changedPaths.length}}}else if(de&&Ot){const{admitPrivatePropertyTestWorkspace:z}=await import("../private-execution/isolated-admission.js"),P=z(de,sn,Jt);he={...F,isolation:{schemaVersion:1,outcome:P.outcome,baseSha:P.baseSha,patchSha256:P.patchSha256,changedPathCount:P.changedPaths.length,checkpointAccepted:!1,qaAccepted:!1,rootNextAction:"property-semantic-review-required"}}}else if(de&&Pt){const{admitPrivateArchitectureStageWorkspace:z}=await import("../private-execution/isolated-admission.js"),P=z(de,Pe,ln,Lr,jr);he={...F,isolation:{schemaVersion:1,outcome:P.outcome,baseSha:P.baseSha,patchSha256:P.patchSha256,changedPathCount:P.changedPaths.length}}}else if(de&&tr){const{admitPrivateProjectStepWorkspace:z}=await import("../private-execution/isolated-admission.js"),P=z(de,hn,ho);he={...F,isolation:{schemaVersion:1,outcome:P.outcome,baseSha:P.baseSha,patchSha256:P.patchSha256,changedPathCount:P.changedPaths.length}}}else if(de){const{admitPrivateStateBoundStepWorkspace:z}=await import("../private-execution/isolated-admission.js"),P=z(de,m.data.metadata.storyId);he={...F,isolation:{schemaVersion:1,outcome:P.outcome,baseSha:P.baseSha,patchSha256:P.patchSha256,changedPathCount:P.changedPaths.length}}}else he={...F}}}catch(c){const p=c instanceof Error&&/^(private-execution|private-codex|private-executor)-[a-z-]+$/.test(c.message)?c.message:"private-execution-unverified";if(!Se&&!Or){Or=!0;try{if(m.data.metadata?.privateExecution&&k&&rt){const{parsePrivateExecutionDescriptor:I}=await import("../private-execution/delivery.js"),R=I(m.data.metadata.privateExecution,{projectId:k,hostKind:rt.hostKind,hostVersion:rt.hostVersion}),O=await $.client.getToken();O&&await qi(T,{leaseId:R.leaseId,...R.binding},O)}}catch{}}return{success:!1,error:p,errorCode:p,exitCode:1}}let un;if(Pr&&f(m.data.metadata.planningRootContinuation)&&m.data.metadata.planningRootContinuation.planningComplete===!0)try{if(!Ne?.claimId||!Ne.epicId||!k)throw new Error("missing-reservation");const c=wo(d,Ne.claimId,Ne.epicId);if(m.data.metadata.planningRootContinuation.memoryReceiptId!==c.receiptId)throw new Error("memory-receipt-conflict");const p=Zr(d,{verifyPlanningGeneration:!0}),I=p.epics[Ne.epicId];if(!f(I?.createEpicPlanningMemoryPhysical)||I.createEpicPlanningMemoryPhysical.receiptId!==c.receiptId)throw new Error("memory-recheck-failed");const R={config:{project_id:k},epics:{[Ne.epicId]:I},stories:Object.fromEntries((Array.isArray(I.stories)?I.stories:[]).map(W=>[W,p.stories[W]])),epic_id_ledger:p.epic_id_ledger};if(!await C.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Ki(T,$.token,{claimId:Ne.claimId,projectId:k,epicId:Ne.epicId,status:"materialized",planningCheckpoint:{memoryReceiptId:c.receiptId,snapshot:R}},{refreshToken:()=>$.client.forceRefresh()}),async()=>!1))throw new Error("acknowledgement-unavailable");un={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 Nr=qr(m.data.instructions,{...m.data.metadata,...m.compatibility?{compatibility:m.compatibility}:{}}),Zt=he?.isolation,sa=Nr.metadata?.resolvedTrigger==="property-test"&&Zt!==null&&typeof Zt=="object"&&!Array.isArray(Zt)&&Zt.outcome==="admitted-unverified"&&Zt.checkpointAccepted===!1&&Zt.rootNextAction==="property-semantic-review-required";if(le&&!uo&&!Pr&&m.data.metadata?.mode!=="error")try{const c=m.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");C.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>On(d,le.fingerprint,p.claimId,p.epicId),()=>{})}catch{}return C.complete(Tr),{success:!0,instructions:he?he.outcome==="checkpoint-validated"?`# Checkpoint da story validado
151
+ `}const z=Se?await Y(ie,Ie,{requireWorkspaceEffect:!0,...e.onPrivateExecutionWorkspaceFailure===void 0?{}:{onWorkspaceEffectFailure:e.onPrivateExecutionWorkspaceFailure},...e.privateExecutionModel===void 0?{}:{model:e.privateExecutionModel},...L?{expectedExecutionBranch:pe.executionBranch}:Et?{expectedExecutionBranch:Et.executionBranch}:de?{expectedExecutionBranch:de.executionBranch}:{}}):await Cs(at,ie,{hostKind:c,workspaceRoot:I,requireWorkspaceEffect:!0,...L?{expectedExecutionBranch:pe.executionBranch}:Et?{expectedExecutionBranch:Et.executionBranch}:de?{expectedExecutionBranch:de.executionBranch}:{}}),dt=async(q,P,Re,pt)=>{if(Se)return{};const{planningQaReceiptFragment:$e}=await import("./planning-qa.js");return{planningQa:$e(q,{root:d,claimId:P,epicId:Re,admission:pt})}};if(L){const{admitPrivateYoloIsolatedSessionStep:q}=await import("../private-execution/isolated-session.js"),P=await q(d,st,pe.graphRevision);let Re;if(m.data.metadata.stepId===Ra){const $e=m.data.metadata.mutationQaFeature;if(!$e)throw new Error("private-execution-mutation-qa-authority-unavailable");if(!$e.enabled)Re={schemaVersion:1,status:"skipped-server-authority",publicSafe:!0};else{let Oe,Le;try{const Nt=P.session.workspace.workspacePath,Ut=`sha:${P.session.workspace.baseSha}`,{planMutationQa:gn}=await import("./mutation-qa.js"),vt=gn(Nt,Ut);if(vt.headSha!==P.session.snapshotSha)throw new Error("private-execution-mutation-qa-snapshot-drift");let lr="not-run";if(vt.outcome==="ready"){const{runAndRecordMutationQa:mn}=await import("./mutation-qa-checkpoint.js");if(lr=mn(Nt,Ut,vt.planSha256).result.outcome,lr==="skipped-host-isolation-unavailable")throw new Error("private-execution-mutation-qa-host-isolation-unavailable")}const{classifyMutationQaGate:la}=await import("./mutation-qa-gate.js");if(Oe=la(Nt,Ut,vt.planSha256),Oe.followUpDebtRequired){const{recordMutationQaFollowUpDebt:mn}=await import("./mutation-qa-checkpoint.js");Le=mn(Nt,Ut,vt.planSha256,Oe.status,lr,d)}const{resumePrivateYoloIsolatedSession:ha}=await import("../private-execution/isolated-session.js");if((await ha(d,st,pe.graphRevision)).snapshotSha!==P.session.snapshotSha)throw new Error("private-execution-mutation-qa-snapshot-drift")}catch{throw new Error("private-execution-mutation-qa-unverified")}if(Oe.blocksLocalQa||!Oe.safeToContinueLocalQa&&!Le)throw new Error(`private-execution-mutation-qa-${Oe.status}`);Re={...Oe,...Le?{followUpDebt:{status:"recorded",owner:Le.owner,severity:Le.severity,reasonCode:Le.reasonCode,planSha256:Le.planSha256,publicSafe:!0}}:{}}}}const pt={schemaVersion:1,outcome:P.admission.outcome,sequence:P.session.sequence,snapshotSha:P.session.snapshotSha,patchSha256:P.admission.patchSha256,changedPathCount:P.admission.changedPaths.length};he={...z,isolation:pt,...Re?{mutationQa:Re}:{}}}else if(Et){const{admitPrivateEpicClaimWorkspace:q,admitPrivateIdeaDiagnosisWorkspace:P}=await import("../private-execution/isolated-admission.js"),Re=er?P(Et,Be.claimId,Be.epicId,le.fingerprint,fn,u.selection.positionals.join(" ").replace(/^[-:–—]\s+/,"")):q(Et,Be.claimId,Be.epicId,le.fingerprint,fn);he={...z,isolation:{schemaVersion:1,outcome:Re.outcome,baseSha:Re.baseSha,patchSha256:Re.patchSha256,changedPathCount:Re.changedPaths.length},...er?await dt("diagnosis",Be.claimId,Be.epicId,Re):{}}}else if(de&&Vt){const{admitPrivateIdeaResearchWorkspace:q}=await import("../private-execution/isolated-admission.js"),P=q(de,Ee.claimId,Ee.epicId,Ee.diagnosisReceiptId,Ee.intakeRevision,Ee.sourceStateSha256);he={...z,isolation:{schemaVersion:1,outcome:P.outcome,baseSha:P.baseSha,patchSha256:P.patchSha256,changedPathCount:P.changedPaths.length},...await dt("research",Ee.claimId,Ee.epicId,P)}}else if(de&&Bt){const{admitPrivateGenerateEpicWorkspace:q}=await import("../private-execution/isolated-admission.js"),P=q(de,se.claimId,se.epicId,se.diagnosisReceiptId,se.researchReceiptId,se.intakeRevision,se.sourceStateSha256);he={...z,isolation:{schemaVersion:1,outcome:P.outcome,baseSha:P.baseSha,patchSha256:P.patchSha256,changedPathCount:P.changedPaths.length},...await dt("generation",se.claimId,se.epicId,P)}}else if(de&&It){const{admitPrivatePactWorkspace:q}=await import("../private-execution/isolated-admission.js"),{inspectPactToolchain:P}=await import("../private-execution/pact-toolchain.js"),{verifyPactConsumerRuntime:Re}=await import("../private-execution/pact-consumer-runtime.js"),pt=Te.answers.generateProvider,$e=q(de,Ve.targetEpicId,Ve.graphRevision,Te.receipt,mt,gi),Oe=P(d,pt),Le=Re(d,mt,pt);he={...z,isolation:{schemaVersion:1,outcome:$e.outcome,baseSha:$e.baseSha,patchSha256:$e.patchSha256,changedPathCount:$e.changedPaths.length,consumerBindingCandidateCount:$e.consumerBindingCandidateCount,consumerScaffoldCount:$e.consumerScaffoldCount,toolchain:Oe,consumerRuntime:Le}}}else if(de&&kt){const{admitPrivateUxWorkspace:q}=await import("../private-execution/isolated-admission.js"),P=q(de,we.targetEpicId,we.graphRevision,ct);he={...z,isolation:{schemaVersion:1,outcome:P.outcome,baseSha:P.baseSha,patchSha256:P.patchSha256,changedPathCount:P.changedPaths.length}}}else if(de&&Ot){const{admitPrivatePropertyTestWorkspace:q}=await import("../private-execution/isolated-admission.js"),P=q(de,sn,Jt);he={...z,isolation:{schemaVersion:1,outcome:P.outcome,baseSha:P.baseSha,patchSha256:P.patchSha256,changedPathCount:P.changedPaths.length,checkpointAccepted:!1,qaAccepted:!1,rootNextAction:"property-semantic-review-required"}}}else if(de&&Pt){const{admitPrivateArchitectureStageWorkspace:q}=await import("../private-execution/isolated-admission.js"),P=q(de,ke,ln,Lr,jr);he={...z,isolation:{schemaVersion:1,outcome:P.outcome,baseSha:P.baseSha,patchSha256:P.patchSha256,changedPathCount:P.changedPaths.length}}}else if(de&&tr){const{admitPrivateProjectStepWorkspace:q}=await import("../private-execution/isolated-admission.js"),P=q(de,hn,fi);he={...z,isolation:{schemaVersion:1,outcome:P.outcome,baseSha:P.baseSha,patchSha256:P.patchSha256,changedPathCount:P.changedPaths.length}}}else if(de){const{admitPrivateStateBoundStepWorkspace:q}=await import("../private-execution/isolated-admission.js"),P=q(de,m.data.metadata.storyId);he={...z,isolation:{schemaVersion:1,outcome:P.outcome,baseSha:P.baseSha,patchSha256:P.patchSha256,changedPathCount:P.changedPaths.length}}}else he={...z}}}catch(c){const p=c instanceof Error&&/^(private-execution|private-codex|private-executor)-[a-z-]+$/.test(c.message)?c.message:"private-execution-unverified";if(!Se&&!Or){Or=!0;try{if(m.data.metadata?.privateExecution&&k&&rt){const{parsePrivateExecutionDescriptor:R}=await import("../private-execution/delivery.js"),O=R(m.data.metadata.privateExecution,{projectId:k,hostKind:rt.hostKind,hostVersion:rt.hostVersion}),U=await B.client.getToken();U&&await Qo(T,{leaseId:O.leaseId,...O.binding},U)}}catch{}}const I=c instanceof Ca?yc(c.reasonCode):void 0;return{success:!1,error:I?.message??p,errorCode:p,exitCode:1,...I?{metadata:{privateExecutionWorkspaceFailure:I}}:{}}}let un;if(Pr&&f(m.data.metadata.planningRootContinuation)&&m.data.metadata.planningRootContinuation.planningComplete===!0)try{if(!De?.claimId||!De.epicId||!k)throw new Error("missing-reservation");const c=Ri(d,De.claimId,De.epicId);if(m.data.metadata.planningRootContinuation.memoryReceiptId!==c.receiptId)throw new Error("memory-receipt-conflict");const p=Zr(d,{verifyPlanningGeneration:!0}),I=p.epics[De.epicId];if(!f(I?.createEpicPlanningMemoryPhysical)||I.createEpicPlanningMemoryPhysical.receiptId!==c.receiptId)throw new Error("memory-recheck-failed");const R={config:{project_id:k},epics:{[De.epicId]:I},stories:Object.fromEntries((Array.isArray(I.stories)?I.stories:[]).map(U=>[U,p.stories[U]])),epic_id_ledger:p.epic_id_ledger};if(!await _.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Xo(T,B.token,{claimId:De.claimId,projectId:k,epicId:De.epicId,status:"materialized",planningCheckpoint:{memoryReceiptId:c.receiptId,snapshot:R}},{refreshToken:()=>B.client.forceRefresh()}),async()=>!1))throw new Error("acknowledgement-unavailable");un={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 Nr=qr(m.data.instructions,{...m.data.metadata,...m.compatibility?{compatibility:m.compatibility}:{}}),Zt=he?.isolation,ua=Nr.metadata?.resolvedTrigger==="property-test"&&Zt!==null&&typeof Zt=="object"&&!Array.isArray(Zt)&&Zt.outcome==="admitted-unverified"&&Zt.checkpointAccepted===!1&&Zt.rootNextAction==="property-semantic-review-required";if(le&&!li&&!Pr&&m.data.metadata?.mode!=="error")try{const c=m.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");_.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Dn(d,le.fingerprint,p.claimId,p.epicId),()=>{})}catch{}return _.complete(Tr),{success:!0,instructions:he?he.outcome==="checkpoint-validated"?`# Checkpoint da story validado
152
152
 
153
153
  O root registrou o commit e a valida\xE7\xE3o f\xEDsica no branch do epic.`:he.outcome==="setup-accepted"?`# Setup do branch validado
154
154
 
155
155
  O root confirmou o checkpoint C01 no branch do \xE9pico. Reexecute o mesmo YOLO para avan\xE7ar \xE0 pr\xF3xima etapa.`:he.outcome==="report-stored"?`# Relat\xF3rio privado salvo
156
156
 
157
- Consulte o caminho local em metadata.privateExecutionReceipt.report.path. Nenhum agente foi executado ou projeto alterado.`:sa?"# Property-test: candidato admitido, QA pendente\n\nO root deve inspecionar os arquivos locais, executar `neocortex-client property-qa review-plan --project-root . --format json` e comparar cada invariante do PRD com a implementa\xE7\xE3o e sua asser\xE7\xE3o. Somente uma revis\xE3o root independente, registrada fora do projeto e enviada por stdin a `property-qa review-accept --authorize-review`, pode autorizar o aceite; esse comando repete a execu\xE7\xE3o positiva e a falha causal no sandbox. Consulte `property-qa review-status` para revalidar o recibo. Se o toolchain ou a evid\xEAncia n\xE3o forem suportados, pare sem declarar QA aprovado. O agente privado n\xE3o recebe autoridade de revis\xE3o, Git ou checkpoint.":`# Execu\xE7\xE3o privada conclu\xEDda; valida\xE7\xE3o f\xEDsica pendente
157
+ Consulte o caminho local em metadata.privateExecutionReceipt.report.path. Nenhum agente foi executado ou projeto alterado.`:ua?"# 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
158
158
 
159
- O executor Codex retornou sem erro. Nenhum checkpoint ou aprova\xE7\xE3o da story foi emitido.`:Nr.instructions,metadata:he?{...Nr.metadata,privateExecutionReceipt:he}:{...Nr.metadata,...un?{planningMaterialization:un}:{}},exitCode:0}}function Dp(e){const[t]=e.trim().split(/\s+/,1);return t?/^@?epic-[a-z0-9][a-z0-9._-]*$/i.test(t)?"epic":Br(t):null}const ra="Provide exactly one invoke input source: --args <string>, --stdin, or --args-file <path>.",Lp=`
159
+ O executor Codex retornou sem erro. Nenhum checkpoint ou aprova\xE7\xE3o da story foi emitido.`:Nr.instructions,metadata:he?{...Nr.metadata,privateExecutionReceipt:he}:{...Nr.metadata,...un?{planningMaterialization:un}:{}},exitCode:0}}function Bp(e){const[t]=e.trim().split(/\s+/,1);return t?/^@?epic-[a-z0-9][a-z0-9._-]*$/i.test(t)?"epic":Br(t):null}const oa="Provide exactly one invoke input source: --args <string>, --stdin, or --args-file <path>.",$p=`
160
160
  neocortex-client invoke - Send orchestration request to server
161
161
 
162
162
  Usage:
@@ -228,13 +228,13 @@ Safety:
228
228
  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.
229
229
  Jobs, goal and loop watch use serverHeldStream=false and foreground local SQLite polling of public processing summaries only.
230
230
  Unresolved targets disable polling with public reason codes; there is no all-jobs fallback.
231
- `.trim();function jp(e){return e.includes("--help")||e.includes("-h")||e.includes("help")}function We(e,t,n,i){return new Kr("INVOCATION_MALFORMED_INPUT",t,e,n,i)}function qt(e){return We("missing-input-value",`${e} requires a value. ${ra}`)}function Mp(e){try{if(!ga(e).isFile())throw We("missing-input-value","--args-file must point to a readable UTF-8 text file.","args-file");return $e(e)}catch(t){throw t instanceof Kr?t:We("missing-input-value","--args-file could not be read as UTF-8 text. Check the path and permissions.","args-file")}}function Vp(){try{if(process.stdin.isTTY)throw We("missing-input-value","--stdin requires piped UTF-8 text, for example: neocortex-client invoke --stdin < synthetic.story.md","stdin");return $e(0)}catch(e){throw e instanceof Kr?e:We("missing-input-value","--stdin could not be read as UTF-8 text. Pipe command text into stdin and retry.","stdin")}}function Bp(e,t={}){let n,i=!1,o,r,a="plain",s=!1,u,g,d=!1,h,l=!1,E;for(let b=0;b<e.length;b++){const C=e[b];switch(C){case"--args":{const A=e[++b];if(A===void 0)throw qt("--args");if(n!==void 0)throw We("multiple-input-sources","Provide --args only once. Use one explicit invoke input source.","args");n=A;break}case"--stdin":if(i)throw We("multiple-input-sources","Provide --stdin only once. Use one explicit invoke input source.","stdin");i=!0;break;case"--args-file":{const A=e[++b];if(A===void 0)throw qt("--args-file");if(o!==void 0)throw We("multiple-input-sources","Provide --args-file only once. Use one explicit invoke input source.","args-file");o=A;break}case"--project-root":{const A=e[++b];if(A===void 0)throw qt("--project-root");r=A;break}case"--format":{const A=e[++b];if(A===void 0)throw qt("--format");if(A!=="json"&&A!=="plain")throw We("unexpected-cli-token","--format accepts only json or plain.");a=A;break}case"--watch":s=!0;break;case"--server-url":{const A=e[++b];if(A===void 0)throw qt("--server-url");u=A;break}case"--platform-target":{const A=e[++b];if(A===void 0)throw qt("--platform-target");g=A;break}case"--strict-read-only":d=!0;break;case"--diagnose-scoped-continuation":h=!0;break;case"--private-execution-beta":l=!0;break;case"--private-execution-model":{const A=e[++b];if(A===void 0)throw qt("--private-execution-model");if(E!==void 0||!/^gpt-[a-z0-9][a-z0-9.-]{0,63}$/.test(A))throw We("unexpected-cli-token","Invalid or duplicate private execution model.");E=A;break}default:if(n!==void 0&&C&&(!C.startsWith("-")||C==="-")){n+=` ${C}`;break}throw We("unexpected-cli-token","Unexpected top-level CLI token. Quote the complete --args payload or use --stdin/--args-file for multiline content.")}}if(E!==void 0&&(!l||d))throw We("unexpected-cli-token","A private execution model requires private beta without strict read-only.");const _=[n!==void 0?"args":void 0,i?"stdin":void 0,o!==void 0?"args-file":void 0].filter(b=>b!==void 0);if(_.length===0)throw We("missing-input-value",ra);if(_.length>1)throw We("multiple-input-sources",`Choose only one invoke input source; received ${_.join(", ")}.`);const w=_[0],S=w==="args"?n:w==="stdin"?(t.readStdin??Vp)():(t.readArgsFile??Mp)(o);let y;try{y=Ft(w,S)}catch(b){throw b instanceof Ic?We("invalid-utf8",b.message,w):b}const D=w==="args"?ip(y.rawArgs):Ge(y.rawArgs),U=D.args===y.rawArgs?y:Ft(w,D.args);return{args:D.args,inputSource:w,inputEnvelope:U,projectRoot:r,format:a,watch:s||D.watch,commandLevelWatch:D.metadata,serverUrl:u,platformTarget:g,strictReadOnly:d,...h?{diagnoseScopedContinuation:h}:{},privateExecutionBeta:l,...E===void 0?{}:{privateExecutionModel:E}}}function na(e,t){return t?.active?{...e??{},commandLevelWatch:t,serverHeldStream:!1}:e}function oa(e,t,n=process.stdout,i=process.stderr){if(t.format==="json"){const a=qr(e.instructions,e.metadata),s=na(a.metadata,t.commandLevelWatch);if(t.watch){n.write(JSON.stringify({type:"invoke_result",instructions:a.instructions,metadata:s,publicSafe:!0})+`
231
+ `.trim();function Up(e){return e.includes("--help")||e.includes("-h")||e.includes("help")}function Fe(e,t,n,o){return new Kr("INVOCATION_MALFORMED_INPUT",t,e,n,o)}function qt(e){return Fe("missing-input-value",`${e} requires a value. ${oa}`)}function Hp(e){try{if(!Ia(e).isFile())throw Fe("missing-input-value","--args-file must point to a readable UTF-8 text file.","args-file");return Ue(e)}catch(t){throw t instanceof Kr?t:Fe("missing-input-value","--args-file could not be read as UTF-8 text. Check the path and permissions.","args-file")}}function Gp(){try{if(process.stdin.isTTY)throw Fe("missing-input-value","--stdin requires piped UTF-8 text, for example: neocortex-client invoke --stdin < synthetic.story.md","stdin");return Ue(0)}catch(e){throw e instanceof Kr?e:Fe("missing-input-value","--stdin could not be read as UTF-8 text. Pipe command text into stdin and retry.","stdin")}}function Wp(e,t={}){let n,o=!1,i,r,a="plain",s=!1,u,g,d=!1,h,l=!1,E;for(let b=0;b<e.length;b++){const _=e[b];switch(_){case"--args":{const A=e[++b];if(A===void 0)throw qt("--args");if(n!==void 0)throw Fe("multiple-input-sources","Provide --args only once. Use one explicit invoke input source.","args");n=A;break}case"--stdin":if(o)throw Fe("multiple-input-sources","Provide --stdin only once. Use one explicit invoke input source.","stdin");o=!0;break;case"--args-file":{const A=e[++b];if(A===void 0)throw qt("--args-file");if(i!==void 0)throw Fe("multiple-input-sources","Provide --args-file only once. Use one explicit invoke input source.","args-file");i=A;break}case"--project-root":{const A=e[++b];if(A===void 0)throw qt("--project-root");r=A;break}case"--format":{const A=e[++b];if(A===void 0)throw qt("--format");if(A!=="json"&&A!=="plain")throw Fe("unexpected-cli-token","--format accepts only json or plain.");a=A;break}case"--watch":s=!0;break;case"--server-url":{const A=e[++b];if(A===void 0)throw qt("--server-url");u=A;break}case"--platform-target":{const A=e[++b];if(A===void 0)throw qt("--platform-target");g=A;break}case"--strict-read-only":d=!0;break;case"--diagnose-scoped-continuation":h=!0;break;case"--private-execution-beta":l=!0;break;case"--private-execution-model":{const A=e[++b];if(A===void 0)throw qt("--private-execution-model");if(E!==void 0||!/^gpt-[a-z0-9][a-z0-9.-]{0,63}$/.test(A))throw Fe("unexpected-cli-token","Invalid or duplicate private execution model.");E=A;break}default:if(n!==void 0&&_&&(!_.startsWith("-")||_==="-")){n+=` ${_}`;break}throw Fe("unexpected-cli-token","Unexpected top-level CLI token. Quote the complete --args payload or use --stdin/--args-file for multiline content.")}}if(E!==void 0&&(!l||d))throw Fe("unexpected-cli-token","A private execution model requires private beta without strict read-only.");const v=[n!==void 0?"args":void 0,o?"stdin":void 0,i!==void 0?"args-file":void 0].filter(b=>b!==void 0);if(v.length===0)throw Fe("missing-input-value",oa);if(v.length>1)throw Fe("multiple-input-sources",`Choose only one invoke input source; received ${v.join(", ")}.`);const w=v[0],S=w==="args"?n:w==="stdin"?(t.readStdin??Gp)():(t.readArgsFile??Hp)(i);let y;try{y=Ft(w,S)}catch(b){throw b instanceof _c?Fe("invalid-utf8",b.message,w):b}const N=w==="args"?pp(y.rawArgs):We(y.rawArgs),$=N.args===y.rawArgs?y:Ft(w,N.args);return{args:N.args,inputSource:w,inputEnvelope:$,projectRoot:r,format:a,watch:s||N.watch,commandLevelWatch:N.metadata,serverUrl:u,platformTarget:g,strictReadOnly:d,...h?{diagnoseScopedContinuation:h}:{},privateExecutionBeta:l,...E===void 0?{}:{privateExecutionModel:E}}}function aa(e,t){return t?.active?{...e??{},commandLevelWatch:t,serverHeldStream:!1}:e}function ca(e,t,n=process.stdout,o=process.stderr){if(t.format==="json"){const a=qr(e.instructions,e.metadata),s=aa(a.metadata,t.commandLevelWatch);if(t.watch){n.write(JSON.stringify({type:"invoke_result",instructions:a.instructions,metadata:s,publicSafe:!0})+`
232
232
  `);return}n.write(JSON.stringify({instructions:a.instructions,metadata:s})+`
233
- `);return}const o=qr(e.instructions,e.metadata),r=na(o.metadata,t.commandLevelWatch);n.write(o.instructions+`
234
- `),r&&i.write(JSON.stringify(r)+`
235
- `)}async function ol(e=process.stdout,t=process.stderr){const n=o=>new Promise(r=>{let a=!1;const s=d=>{a||(a=!0,clearTimeout(g),setImmediate(()=>o.removeListener("error",u)),r(d))},u=()=>s(!1),g=setTimeout(()=>s(!1),1e4);o.once("error",u);try{o.write("",d=>s(!d))}catch{s(!1)}});return(await Promise.all([n(e),n(t)])).every(Boolean)}function $p(e){const t=()=>e.abort();return process.once("SIGINT",t),process.once("SIGTERM",t),()=>{process.removeListener("SIGINT",t),process.removeListener("SIGTERM",t)}}async function il(e){if(jp(e))return process.stdout.write(`${Lp}
236
- `),0;let t;try{t=Bp(e)}catch(s){if(s instanceof Kr)return process.stderr.write(JSON.stringify({error_code:s.code,reason:s.reason,source:s.source,byte_length:s.byteLength,message:s.message,remediation:s.message})+`
237
- `),1;throw s}let n;try{n=await di(t.projectRoot)}catch(s){const u=s instanceof Error&&/^project-root-[a-z-]+$/.test(s.message)?s.message:"project-root-resolution-failed";return process.stderr.write(JSON.stringify({error_code:u,message:"Project root could not be resolved safely."})+`
238
- `),1}if(Ja(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."})+`
239
- `),1):(await Qa({args:t.args,projectRoot:n,format:t.format,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})).exitCode;const i={args:t.args,inputSource:t.inputSource,inputEnvelope:t.inputEnvelope,watch:t.watch,projectRoot:n,format:t.format,serverUrl:t.serverUrl,platformTarget:t.platformTarget,strictReadOnly:t.strictReadOnly,...t.diagnoseScopedContinuation?{diagnoseScopedContinuation:!0}:{},privateExecutionBeta:t.privateExecutionBeta,...t.privateExecutionModel===void 0?{}:{privateExecutionModel:t.privateExecutionModel}},{isYoloopInvocation:o}=await import("../yoloop/target-normalization.js"),r=o(t.args)&&!t.strictReadOnly?await(await import("../runner/headless/run-yoloop.js")).runDirectYoloop(i):await Op(i),a=ui(t.args,r);if(!a.success&&a.errorCode==="YOLOOP_RELEASE_BLOCKED"&&a.instructions&&a.metadata)return oa(a,t),a.exitCode;if(!a.success){const s=a.metadata?.invocationInput,u=Ts(a.metadata?.yoloChangeEvidence),g=s&&typeof s=="object"&&!Array.isArray(s)?s:void 0,d=Cd(a.metadata?.createEpicClaimRecovery),h=Hr(a.metadata?.semanticGateRemediation),l=vs(a.metadata?.nativeCustody),E=$o(a.metadata?.privateExecutionHostFailure);return process.stderr.write(JSON.stringify({error_code:a.errorCode??(a.exitCode===2?"NOT_CONFIGURED":"INVOKE_ERROR"),message:nt(a.error??"",zt),...typeof g?.reason=="string"?{reason:nt(g.reason,80)}:{},...typeof g?.source=="string"?{source:nt(g.source,20)}:{},...Number.isSafeInteger(g?.byteLength)?{byte_length:g.byteLength}:{},...typeof g?.remediation=="string"?{remediation:nt(g.remediation,zt)}:{},...u?{yolo_change_evidence:u}:{},...d??{},...E?{reason_code:E.reason_code,fallback_action:E.fallback_action}:{},...l?{reason_code:l.reasonCode,remediation:l.remediation,retry_safe_after_repair:l.retrySafeAfterRepair}:{},...h?{semantic_gate_remediation:h}:{}})+`
240
- `),a.exitCode}if(oa(a,t),t.watch){const s=new AbortController,u=$p(s);try{const g=mp(a.metadata,t.args);g.disabled?Yd(g.reasonCodes??[Oe.TARGET_UNRESOLVED],t.args,t.format,process.stdout,t.privateExecutionBeta):await qd({projectRoot:n,format:t.format,strictReadOnly:t.strictReadOnly,protectedOutput:t.privateExecutionBeta,...g,signal:s.signal})}finally{u()}}return 0}export{Lp as INVOKE_HELP_TEXT,ei as INVOKE_PAYLOAD_LIMIT_BYTES,xn as INVOKE_PAYLOAD_WARNING_THRESHOLD_BYTES,Kr as InvokeCliInputError,Mn as InvokePayloadTooLargeError,Vn as InvokeStructuralContextTooLargeError,bi as P205_AUTHORITY_EPIC_ORDER_MISMATCH,ta as STORY_WORKTREE_BARRIER_CLIENT_MAX_ATTEMPTS,ea as STORY_WORKTREE_BARRIER_CLIENT_MAX_WAIT_MS,ut as StateSnapshotIntegrityError,tl as __resetSchemaDriftWarnedForTests,Qc as acceptedSemanticYoloopSessionRecovery,Ep as acknowledgeMaterializedPendingEpicClaims,Dn as admitClientInvocation,Gn as assertEpicAwareStateShapeBeforeRepair,ad as boundedP222PremergeCheckpointPositions,jn as buildInvokeCompatibilityOffer,ms as buildPrivateHostExecutionRequest,Ad as buildSignedInvokeAttempt,sd as canonicalizeEpicCheckpointOrder,Is as classifyPrivateCreateEpicPlanningPhase,ss as clearPendingEpicIdempotencyKey,rl as collectInvokeP205Authorities,xi as collectInvokeP205AuthorityProjection,Zr as collectStateSnapshot,Pp as composeStoryWorktreeSpecAcceptance,cr as computeInvokeRequestBodySizeBytes,nl as createFullStateSnapshotScope,Kn as createInvokePayloadTelemetry,ii as defaultPrivateHostExecutorLoader,ds as deriveYoloLogicalIdempotencyKey,Ds as detectStateSchemaDrift,ui as ensureInvokeSemanticGateRemediation,Dp as extractPreFlightTrigger,Yn as finalizeEpicTargetId,ol as flushInvokeCliOutput,cs as getOrCreatePendingEpicIdempotencyKey,Jn as guardInvokeRequestBodySize,Op as invoke,il as invokeCliHandler,cd as invokeP205ProjectionReasonCode,wi as isEpicAwareCommandId,bp as isStoryWorktreePhaseOneInvocation,ai as loadPrivateHostExecutionPort,Ld as maybeEmitInvokePayloadSizeWarning,jd as maybeRunInvokeRunnerAutoBootstrap,ed as mirrorRuntimeStoreProjectState,td as observeStoryWorktreeReadiness,Bp as parseInvokeCliOptions,kp as persistStoryWorktreePhaseEvidence,Tp as pollStoryWorktreeSpecBarrier,ji as postMaterializationJson,hd as produceFinalizeEpicLifecycleEvidence,Cd as projectCreateEpicClaimRecoveryCli,vs as projectNativeCustodyCliDiagnostic,pi as projectNativeCustodyGateDiagnostic,vd as projectPrivateInvokeFailureBody,Cs as projectRegistryDriftInvokeFailure,_s as projectReleaseBlockedInvokeResult,Ts as projectYoloChangeEvidenceCliDiagnostic,Ko as publicYoloSpecEnvelopeErrorCode,wp as reconcileInvalidatedYoloopSession,On as recordPendingEpicReservation,Ip as recordRefusedYoloopRoundIfAny,ws as recoverClientInvocation,di as resolveInvokeCliProjectRoot,ip as resolveInvokeCommandLevelWatch,el as resolveInvokeProjectRoot,_d as resolveInvokeTransportErrorCode,mp as resolveInvokeWatchTarget,ys as runPrivateHostExecutionStep,zs as sanitizeBranchModeConversionReceipt,qr as sanitizeInvokeCliOutput,gs as sanitizePrivateHostReceiptV2,Ki as sendEpicClaimAcknowledgement,oo as sendInvokeRequest,qi as sendPrivateExecutionCancelRequest,yp as sendPrivateExecutionConsumeRequest,Ps as shouldCollectProjectEvidenceForInvoke,Hn as storyWorktreeReadinessTargetEpic,hs as usesPrivateCodexV6Executor,fs as validatePrivateHostPreflight,qd as watchContinuityProcessingSummaries,oa as writeInvokeCliSuccessOutput};
233
+ `);return}const i=qr(e.instructions,e.metadata),r=aa(i.metadata,t.commandLevelWatch);n.write(i.instructions+`
234
+ `),r&&o.write(JSON.stringify(r)+`
235
+ `)}async function pl(e=process.stdout,t=process.stderr){const n=i=>new Promise(r=>{let a=!1;const s=d=>{a||(a=!0,clearTimeout(g),setImmediate(()=>i.removeListener("error",u)),r(d))},u=()=>s(!1),g=setTimeout(()=>s(!1),1e4);i.once("error",u);try{i.write("",d=>s(!d))}catch{s(!1)}});return(await Promise.all([n(e),n(t)])).every(Boolean)}function Fp(e){const t=()=>e.abort();return process.once("SIGINT",t),process.once("SIGTERM",t),()=>{process.removeListener("SIGINT",t),process.removeListener("SIGTERM",t)}}async function ul(e){if(Up(e))return process.stdout.write(`${$p}
236
+ `),0;let t;try{t=Wp(e)}catch(s){if(s instanceof Kr)return process.stderr.write(JSON.stringify({error_code:s.code,reason:s.reason,source:s.source,byte_length:s.byteLength,message:s.message,remediation:s.message})+`
237
+ `),1;throw s}let n;try{n=await lo(t.projectRoot)}catch(s){const u=s instanceof Error&&/^project-root-[a-z-]+$/.test(s.message)?s.message:"project-root-resolution-failed";return process.stderr.write(JSON.stringify({error_code:u,message:"Project root could not be resolved safely."})+`
238
+ `),1}if(ec(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."})+`
239
+ `),1):(await tc({args:t.args,projectRoot:n,format:t.format,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})).exitCode;const o={args:t.args,inputSource:t.inputSource,inputEnvelope:t.inputEnvelope,watch:t.watch,projectRoot:n,format:t.format,serverUrl:t.serverUrl,platformTarget:t.platformTarget,strictReadOnly:t.strictReadOnly,...t.diagnoseScopedContinuation?{diagnoseScopedContinuation:!0}:{},privateExecutionBeta:t.privateExecutionBeta,...t.privateExecutionModel===void 0?{}:{privateExecutionModel:t.privateExecutionModel}},{isYoloopInvocation:i}=await import("../yoloop/target-normalization.js"),r=i(t.args)&&!t.strictReadOnly?await(await import("../runner/headless/run-yoloop.js")).runDirectYoloop(o):await Mp(o),a=fo(t.args,r);if(!a.success&&a.errorCode==="YOLOOP_RELEASE_BLOCKED"&&a.instructions&&a.metadata)return ca(a,t),a.exitCode;if(!a.success){const s=a.metadata?.invocationInput,u=Ds(a.metadata?.yoloChangeEvidence),g=s&&typeof s=="object"&&!Array.isArray(s)?s:void 0,d=bd(a.metadata?.createEpicClaimRecovery),h=Hr(a.metadata?.semanticGateRemediation),l=As(a.metadata?.nativeCustody),E=Ui(a.metadata?.privateExecutionHostFailure),v=Rn(a.metadata?.invokeValidationFailure),w=a.errorCode===Gi?Hi(a.metadata?.privateExecutionWorkspaceFailure):void 0;return process.stderr.write(JSON.stringify({error_code:a.errorCode??(a.exitCode===2?"NOT_CONFIGURED":"INVOKE_ERROR"),message:nt(a.error??"",zt),...typeof g?.reason=="string"?{reason:nt(g.reason,80)}:{},...typeof g?.source=="string"?{source:nt(g.source,20)}:{},...Number.isSafeInteger(g?.byteLength)?{byte_length:g.byteLength}:{},...typeof g?.remediation=="string"?{remediation:nt(g.remediation,zt)}:{},...u?{yolo_change_evidence:u}:{},...d??{},...v?{reason_code:v.reason_code,fallback_action:v.fallback_action,validation_stage:v.validation_stage,validation_field:v.validation_field}:{},...E?{reason_code:E.reason_code,fallback_action:E.fallback_action}:{},...w?{reason_code:w.reason_code,fallback_action:w.fallback_action}:{},...l?{reason_code:l.reasonCode,remediation:l.remediation,retry_safe_after_repair:l.retrySafeAfterRepair}:{},...h?{semantic_gate_remediation:h}:{}})+`
240
+ `),a.exitCode}if(ca(a,t),t.watch){const s=new AbortController,u=Fp(s);try{const g=vp(a.metadata,t.args);g.disabled?Xd(g.reasonCodes??[Ne.TARGET_UNRESOLVED],t.args,t.format,process.stdout,t.privateExecutionBeta):await Zd({projectRoot:n,format:t.format,strictReadOnly:t.strictReadOnly,protectedOutput:t.privateExecutionBeta,...g,signal:s.signal})}finally{u()}}return 0}export{$p as INVOKE_HELP_TEXT,ro as INVOKE_PAYLOAD_LIMIT_BYTES,Pn as INVOKE_PAYLOAD_WARNING_THRESHOLD_BYTES,Kr as InvokeCliInputError,Bn as InvokePayloadTooLargeError,$n as InvokeStructuralContextTooLargeError,Po as P205_AUTHORITY_EPIC_ORDER_MISMATCH,ia as STORY_WORKTREE_BARRIER_CLIENT_MAX_ATTEMPTS,na as STORY_WORKTREE_BARRIER_CLIENT_MAX_WAIT_MS,ut as StateSnapshotIntegrityError,cl as __resetSchemaDriftWarnedForTests,rs as acceptedSemanticYoloopSessionRecovery,wp as acknowledgeMaterializedPendingEpicClaims,jn as admitClientInvocation,Fn as assertEpicAwareStateShapeBeforeRepair,ud as boundedP222PremergeCheckpointPositions,Vn as buildInvokeCompatibilityOffer,vs as buildPrivateHostExecutionRequest,kd as buildSignedInvokeAttempt,hd as canonicalizeEpicCheckpointOrder,_s as classifyPrivateCreateEpicPlanningPhase,hs as clearPendingEpicIdempotencyKey,sl as collectInvokeP205Authorities,ko as collectInvokeP205AuthorityProjection,Zr as collectStateSnapshot,Lp as composeStoryWorktreeSpecAcceptance,cr as computeInvokeRequestBodySizeBytes,dl as createFullStateSnapshotScope,Qn as createInvokePayloadTelemetry,co as defaultPrivateHostExecutorLoader,fs as deriveYoloLogicalIdempotencyKey,Bs as detectStateSchemaDrift,fo as ensureInvokeSemanticGateRemediation,Bp as extractPreFlightTrigger,Kn as finalizeEpicTargetId,pl as flushInvokeCliOutput,ls as getOrCreatePendingEpicIdempotencyKey,Xn as guardInvokeRequestBodySize,Mp as invoke,ul as invokeCliHandler,ld as invokeP205ProjectionReasonCode,bo as isEpicAwareCommandId,Op as isStoryWorktreePhaseOneInvocation,so as loadPrivateHostExecutionPort,$d as maybeEmitInvokePayloadSizeWarning,Ud as maybeRunInvokeRunnerAutoBootstrap,od as mirrorRuntimeStoreProjectState,ad as observeStoryWorktreeReadiness,Wp as parseInvokeCliOptions,jp as persistStoryWorktreePhaseEvidence,Dp as pollStoryWorktreeSpecBarrier,Bo as postMaterializationJson,Id as produceFinalizeEpicLifecycleEvidence,bd as projectCreateEpicClaimRecoveryCli,As as projectNativeCustodyCliDiagnostic,ho as projectNativeCustodyGateDiagnostic,Ad as projectPrivateInvokeFailureBody,bs as projectRegistryDriftInvokeFailure,xs as projectReleaseBlockedInvokeResult,Ds as projectYoloChangeEvidenceCliDiagnostic,Qi as publicYoloSpecEnvelopeErrorCode,Tp as reconcileInvalidatedYoloopSession,Dn as recordPendingEpicReservation,_p as recordRefusedYoloopRoundIfAny,Ts as recoverClientInvocation,lo as resolveInvokeCliProjectRoot,pp as resolveInvokeCommandLevelWatch,al as resolveInvokeProjectRoot,xd as resolveInvokeTransportErrorCode,vp as resolveInvokeWatchTarget,Cs as runPrivateHostExecutionStep,Qs as sanitizeBranchModeConversionReceipt,qr as sanitizeInvokeCliOutput,Ss as sanitizePrivateHostReceiptV2,Xo as sendEpicClaimAcknowledgement,ai as sendInvokeRequest,Qo as sendPrivateExecutionCancelRequest,Cp as sendPrivateExecutionConsumeRequest,Ls as shouldCollectProjectEvidenceForInvoke,Wn as storyWorktreeReadinessTargetEpic,Is as usesPrivateCodexV6Executor,Es as validatePrivateHostPreflight,Zd as watchContinuityProcessingSummaries,ca as writeInvokeCliSuccessOutput};