@ornexus/neocortex 4.60.76 → 4.60.78

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 (51) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1194 -1194
  3. package/docs/install/installer-diagnostics.md +6 -5
  4. package/docs/install/linux-global-install.md +5 -3
  5. package/install.ps1 +80 -66
  6. package/install.sh +63 -57
  7. package/package.json +3 -3
  8. package/packages/client/dist/agent/refresh-stubs.d.ts +7 -0
  9. package/packages/client/dist/agent/refresh-stubs.js +2 -2
  10. package/packages/client/dist/agent/update-description.js +1 -1
  11. package/packages/client/dist/commands/invoke.d.ts +6 -0
  12. package/packages/client/dist/commands/invoke.js +57 -57
  13. package/packages/client/dist/commands/refresh-memory.js +3 -3
  14. package/packages/client/dist/memory/project-memory-writer.d.ts +2 -0
  15. package/packages/client/dist/memory/project-memory-writer.js +17 -16
  16. package/packages/client/dist/memory/shared-project-memory-types.js +1 -1
  17. package/packages/client/dist/runner/headless/managed-profile.js +1 -1
  18. package/packages/client/dist/runner/host-capacity.d.ts +27 -0
  19. package/packages/client/dist/runner/host-capacity.js +1 -0
  20. package/packages/shared/dist/project-memory-targets.js +9 -3
  21. package/packages/shared/dist/yoloop/host-capacity.js +76 -0
  22. package/postinstall.js +1 -1
  23. package/targets-stubs/antigravity/gemini.md +1 -1
  24. package/targets-stubs/antigravity/install-antigravity.sh +6 -5
  25. package/targets-stubs/antigravity/neocortex.md +37 -7
  26. package/targets-stubs/antigravity/skill/SKILL.md +30 -1
  27. package/targets-stubs/claude-code/neocortex-root.agent.yaml +2 -1
  28. package/targets-stubs/claude-code/neocortex-root.md +45 -19
  29. package/targets-stubs/claude-code/neocortex.agent.yaml +2 -1
  30. package/targets-stubs/claude-code/neocortex.md +64 -69
  31. package/targets-stubs/codex/AGENTS.md +36 -31
  32. package/targets-stubs/codex/README.md +7 -3
  33. package/targets-stubs/codex/install-codex.sh +22 -11
  34. package/targets-stubs/codex/neocortex.toml +14 -8
  35. package/targets-stubs/cursor/agent.md +39 -8
  36. package/targets-stubs/cursor/install-cursor.sh +1 -1
  37. package/targets-stubs/deepseek-harness/SKILL.md +8 -3
  38. package/targets-stubs/gemini-cli/agent.md +48 -16
  39. package/targets-stubs/gemini-cli/agents/neocortex.md +6 -0
  40. package/targets-stubs/gemini-cli/install-gemini.sh +20 -10
  41. package/targets-stubs/grok/SKILL.md +29 -0
  42. package/targets-stubs/grok/install-grok.sh +12 -3
  43. package/targets-stubs/kimi/neocortex.md +34 -2
  44. package/targets-stubs/lib/managed-config-merge.js +28 -1
  45. package/targets-stubs/lib/managed-profile.sh +81 -7
  46. package/targets-stubs/openclaw/SKILL.md +29 -0
  47. package/targets-stubs/opencode/neocortex-root.md +62 -28
  48. package/targets-stubs/opencode/neocortex.md +36 -4
  49. package/targets-stubs/vscode/install-vscode.sh +3 -3
  50. package/targets-stubs/vscode/neocortex.agent.md +55 -22
  51. package/docs/install/coderabbit-manual-setup.md +0 -86
@@ -1,59 +1,59 @@
1
- import{classifyNonUiArchitectureTransition as Ui,architectureMemoryPredecessorCount as fr}from"./architecture-non-ui-continuation.js";import{parseArchitectureNonUiScopeReceipt as mr}from"./shared-architecture-non-ui.js";import{createHash as Pe,randomUUID as sn}from"node:crypto";import{loadPactAnswerReceipt as yr,loadPactPrivateAnswers as $i}from"./architecture-answers.js";import{acceptedArchitectureTerminalMemoryReceipt as Ft,deriveArchitectureTerminalMemoryReceipt as kn}from"./architecture-memory-terminal.js";import{deriveCommittedArchitectureEpicGraphRevision as Yt,explicitArchitectureEpicTarget as Hi}from"./architecture-root-binding.js";import{derivePactWriteSet as Gi}from"../private-execution/pact-write-set.js";import{execFileSync as Ge}from"node:child_process";import{existsSync as Mt,readFileSync as We,renameSync as Ir,unlinkSync as On,writeFileSync as dn,mkdirSync as qt,statSync as Wi,openSync as zt,closeSync as Jt,fsyncSync as pn,realpathSync as Fi,lstatSync as jt}from"node:fs";import{isDeepStrictEqual as v}from"node:util";import{join as Q,isAbsolute as Yi,resolve as Nn}from"node:path";import{homedir as Kt}from"node:os";import{isPrivateExecutionPublicEnvelope as qi,isPrivatePlanningRootPublicEnvelope as zi,PRIVATE_MUTATION_QA_GATE_STEP_TOKEN as Ji}from"../private-execution/delivery.js";import{acceptedPlanningDiagnosisPredecessor as Er}from"../private-execution/planning-diagnosis-checkpoint.js";import{acceptedPlanningResearchPredecessor as Sr}from"../private-execution/planning-research-checkpoint.js";import{verifyCommittedPlanningMemory as vr}from"../private-execution/planning-memory-checkpoint.js";import{verifyCommittedPlanningGeneration as Ki}from"../private-execution/planning-generation-checkpoint.js";import{PLANNING_RAW_INTENT_MAX_CHARS as Qi}from"../../../shared/dist/planning/diagnosis-state.js";import{applyCrossEpicContinuationReconciliation as Xi,buildCrossEpicContinuationPayloadHash as Zi,classifyCrossEpicContinuationReconciliation as ea,epicOperationalHash as Et,readEpicOperationalState as Cr}from"../git/epic-operational-state.js";import{LicenseClient as ta}from"../license/license-client.js";import{EncryptedCache as Ln}from"../cache/encrypted-cache.js";import{NoOpCache as _r}from"../types/index.js";import{resolveClientPreFlightTrigger as ln,TierAwareClient as na}from"../tier/tier-aware-client.js";import{COMMAND_REGISTRY_CHECKSUM as at,COMMAND_REGISTRY_VERSION as ot,GENERATED_CLIENT_COMMANDS as ra}from"../generated/command-registry.generated.js";import{loadSecureConfig as Dn}from"../config/secure-config.js";import{neocortexProfileDirectory as ia}from"../config/profile-directory.js";import{DEFAULT_SERVER_URL as aa}from"../constants.js";import{detectFirstRunLocale as oa,renderFirstRunMessage as ca}from"../i18n/first-run.js";import{humanizeError as wr,formatHumanizedError as Rr,detectErrorLocale as Ar}from"../errors/error-messages.js";import{degradeStateSnapshotForPayloadLimit as sa,projectStateSnapshotForInvoke as br,projectStateSnapshotResultV2ForInvoke as da}from"../state/project-state-snapshot.js";import{isInlineYoloMaterialization as xr,maybeRepairStateJsonBeforeInvoke as pa,StateRepairHardStopError as la}from"../state/state-json-repair.js";import{StructuralDagError as Tr}from"../state/structural-dag-projection.js";import{collectStateMigrationAuthority as ua,StateMigrationApplyError as ha}from"../migrations/state-json.js";import{RUNNER_BOOTSTRAP_POLICY_REASON_CODES as ga,classifyRunnerBootstrapPolicyFromArgs as fa}from"../continuity/runner-bootstrap-policy.js";import{RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES as ma,ensureRunnerSchedulerBootstrap as ya,observeRunnerOperationalStatus as Ia}from"../runner/scheduler.js";import{CONTINUITY_INVOKE_WATCH_DEFAULT_LIMIT as Pr,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_IDLE_POLLS as kr,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_POLLS as Or,CONTINUITY_INVOKE_WATCH_DEFAULT_POLL_INTERVAL_MS as Nr,openContinuityClientStateStore as Ea}from"../continuity/continuity-client-state-store.js";import{isLocalJobsConsoleArgs as Sa,runLocalJobsConsoleCommand as va}from"../runner/local-console.js";import{detectNativeHostAttestation as Ca,detectPlatform as _a}from"../adapters/platform-detector.js";import{signNxInvokeRequest as wa}from"../../../shared/dist/nx-invoke-signature.js";import{YOLO_INVOKE_ENVELOPE_CAPABILITY as Ra}from"../../../shared/dist/yolo/spec-envelope.js";import{parseReleaseBlockedResult as Aa}from"../../../shared/dist/yoloop/release-blocked.js";import{CLIENT_VERSION as Tt}from"../version.js";import{createCapabilityCache as Lr,executeInvokeQueryTransport as Mn,executeSecondaryNetworkMutation as ba}from"../effects/invoke-effect-gateways.js";import{STRICT_READ_ONLY_POLICY as xa,STRICT_READ_ONLY_CLIENT_PROJECTION as Dr,STRICT_READ_ONLY_SERVER_PROJECTION as Ta,StrictReadOnlyError as Vt,canonicalizeInvokeEffects as Pa,createInvokeEffectContext as ka,verifyStrictReadOnlyReceipt as Oa}from"../../../shared/dist/strict-readonly.js";import{admitInvocation as Na,assertInvokeInputEnvelopeV2 as La,assertProjectIdentityMigrationReceiptV1 as Da,buildProjectIdentityPublicDiagnostic as Bt,createInvocationAdmissionReceipt as Ma,projectInvokeInputEvidenceV1 as jn,recoverExplicitInvocation as ja,verifyStrictDiagnoseReceiptV1 as Va}from"../../../shared/dist/invocation/index.js";import{buildInvokeInputEnvelope as Qt,InvokeInputDecodeError as Ba}from"../invocation/invoke-input.js";import{COMPATIBILITY_REASON_CODES as Ut,createCompatibilityOffer as Ua,createLegacyCompatibilityResult as $a,isCompatibilityResultV1 as Ha}from"../../../shared/dist/compatibility/index.js";import{acknowledgeProjectIdentityMigration as Ga,finalizeProjectIdentityMigration as Wa,prepareProjectIdentityMigration as Fa,ProjectIdentityMigrationError as Vn,readProjectIdentityMigrationPhase as Ya}from"../migrations/project-identity.js";import{probeProjectIdentityMigrationCapability as qa}from"../migrations/project-identity-capability.js";import{normalizeYoloopStoryPlanningEvidence as za}from"../../../shared/dist/yoloop/planning-graph.js";import{normalizeContinuousWriteRef as un}from"../../../shared/dist/yoloop/wave-decision-receipt.js";import{epicHeadReconciliationInputDigest as Ja,epicHeadReconciliationPathsDigest as Mr,epicHeadReconciliationRangeDigest as Ka}from"../../../shared/dist/yoloop/epic-terminal-git.js";import{applyGitLifecycleRuntimeOverlay as jr,classifyGitLifecycleStoryCheckpointProjectionSync as Qa,ensureRuntimeEpic as Xa,ensureGitLifecycleRuntimeInitialized as Za,executeP205TransientAuthorities as eo,persistGitLifecycleGraphAuthority as to,P205_COMPLETE_COMMAND as Xt,gitLifecycleStoryWriteSet as Vr,mutateGitLifecycleRuntime as no,projectP205TransientExecutionEvidence as ro,readGitLifecycleRuntimeSync as hn,verifyLegacyCheckpointMigrationCandidateSync as io}from"../git/git-lifecycle-store.js";import{verifyRootMemoryPhysicalWriteSet as ao}from"../private-execution/root-memory-git-evidence.js";import{isRootProjectMemoryEffect as oo}from"../private-execution/shared-root-memory-types.js";import{probeYoloInvokeEnvelopeCapability as co}from"../yolo/invoke-envelope-capability.js";import{collectYoloSpecEnvelope as Br,extractTargetedYoloStoryId as so,refreshPrecollectedYoloSpecEnvelope as Ur}from"../yolo/spec-envelope-collector.js";const gn=ia(),Bn=Q(gn,"cache"),$r=Q(Bn,"menu-cache.json"),Hr=1440*60*1e3,Gr=3e4,Wr=256*1024,Fr=Wr,Yr=.8,St="[REDACTED]",po=1e5,Pt=2e3,lo=200,uo=200,ho=12,go=/(?:promptBody|workflow|workflowGraph|stepBody|privateUrl|rawLog|secret|credential|licenseKey|apiKey|internalRouting|serverOnly|proprietary|protected)/i,fo=/(?:PRIVATE|PROTECTED|SERVER_ONLY)[-_\s]*(?:PROMPT|PROMPT_BODY|WORKFLOW|WORKFLOW_GRAPH|STEP_BODY|STEP|ROUTING)\s*[:=][^\n\r]*/gi,mo=/(?: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,Un=Math.floor(Wr*Yr),qr=Q(gn,".first-run-shown"),yo="pending-epic-claims.json",zr=64;function Jr(e){return Q(e,".neocortex",yo)}function $t(e){const t=Jr(e);if(!Mt(t))return{schemaVersion:1,operations:{}};const i=JSON.parse(We(t,"utf8"));if(!i||typeof i!="object"||Array.isArray(i))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const r=i;if(r.schemaVersion!==1||!r.operations||typeof r.operations!="object"||Array.isArray(r.operations))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(Object.keys(r.operations).length>zr)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");for(const[a,n]of Object.entries(r.operations)){if(!/^[a-f0-9]{64}$/.test(a)||!n||typeof n!="object"||Array.isArray(n))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const o=n;if(o.planningProtocol!==void 0&&o.planningProtocol!=="root-staged-v1")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(typeof o.idempotencyKey!="string"||!/^[0-9a-f-]{36}$/.test(o.idempotencyKey)||typeof o.createdAt!="string")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(o.claimId!==void 0&&(typeof o.claimId!="string"||!/^[0-9a-f-]{36}$/.test(o.claimId))||o.epicId!==void 0&&(typeof o.epicId!="string"||!/^P[1-9][0-9]*$/.test(o.epicId))||o.claimId===void 0!=(o.epicId===void 0))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE")}return i}function $n(e,t){const i=Jr(e);qt(Q(e,".neocortex"),{recursive:!0,mode:448});const r=`${i}.${process.pid}.${sn()}.tmp`;dn(r,`${JSON.stringify(t)}
2
- `,{encoding:"utf8",mode:384,flag:"wx"}),Ir(r,i)}function Io(e,t){return Pe("sha256").update(`nx-epic-logical-operation-v1\0${JSON.stringify({command:t,args:e})}`,"utf8").digest("hex")}function Eo(e,t,i="create-epic"){const r=Io(t,i),a=$t(e),n=a.operations[r];if(n)return{key:n.idempotencyKey,fingerprint:r};if(Object.keys(a.operations).length>=zr)throw new Error("EPIC_CLAIM_CAPACITY_EXCEEDED");const o=sn(),p={...a.operations,[r]:{idempotencyKey:o,createdAt:new Date().toISOString()}};return $n(e,{schemaVersion:1,operations:p}),{key:o,fingerprint:r}}function So(e,t){const i=$t(e);if(!i.operations[t])return;const r={...i.operations};delete r[t],$n(e,{schemaVersion:1,operations:r})}function vo(e,t,i,r){const a=r.scope?.targetStoryId??r.current_session?.active_story_id??null,n=r.scope?.targetEpicId??r.current_session?.active_epic_id??null,o=a?r.stories[a]:void 0,p=Array.isArray(o?.steps_completed)?o.steps_completed.filter(I=>typeof I=="string"):[],s=i??Pe("sha256").update(`nx-yolo-project-path-v1\0${Nn(e)}`,"utf8").digest("hex"),l=JSON.stringify({projectBinding:s,args:t,storyId:a,epicId:n,status:typeof o?.status=="string"?o.status:null,lastStep:typeof o?.last_step=="string"?o.last_step:null,stepsCompleted:p});return`yolo-${Pe("sha256").update(`nx-yolo-logical-operation-v1\0${l}`,"utf8").digest("hex")}`}function Kr(e,t,i,r,a){if(!/^[0-9a-f-]{36}$/.test(i)||!/^P[1-9][0-9]*$/.test(r)||a!==void 0&&a!=="root-staged-v1")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const n=$t(e),o=n.operations[t];if(!o)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(o.claimId!==void 0&&(o.claimId!==i||o.epicId!==r))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");$n(e,{schemaVersion:1,operations:{...n.operations,[t]:{...o,claimId:i,epicId:r,...a?{planningProtocol:a}:{}}}})}function Co(){try{if(Mt(qr))return;const e=oa(),t=ca(e);process.stderr.write(t);try{qt(gn,{recursive:!0}),dn(qr,new Date().toISOString(),"utf-8")}catch{}}catch{}}function Hn(e,t=process.cwd()){return e&&e.trim().length>0?e:t}function _o(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 wo(e){const t=e.metadata;if(!t||!(t.yoloopReleaseBlocked===!0||t.terminalClass==="release-blocked"||t.releaseBlocked!==void 0))return;const r=Aa(t.releaseBlocked);return!r||t.yoloopReleaseBlocked!==!0||t.terminalClass!=="release-blocked"||t.yoloopComplete!==!1||t.yoloopAborted!==!1?{success:!1,error:"YOLOOP_RELEASE_BLOCKED_INVALID: terminal evidence was inconsistent.",errorCode:"YOLOOP_RELEASE_BLOCKED_INVALID",metadata:t,exitCode:1}:{success:!1,instructions:e.instructions,metadata:{...t,releaseBlocked:r},error:"YOLOOP_RELEASE_BLOCKED: the current release attempt ended without success.",errorCode:"YOLOOP_RELEASE_BLOCKED",exitCode:1}}function Qr(e){return Na(e,{registryVersion:ot,registryChecksum:at})}function Ro(e){return ja(e,{registryVersion:ot,registryChecksum:at})}const Ao=new Set(["completed","aborted","cancelled"]),bo=new Set(["watch-target-missing","watch-target-malformed","watch-target-ambiguous","watch-target-multiple"]),_e=Object.freeze({COMPLETED:"invoke-watch-completed",CANCELLED:"invoke-watch-cancelled",IDLE_TIMEOUT:"invoke-watch-idle-timeout",MAX_POLLS:"invoke-watch-max-polls",STORE_UNAVAILABLE:"invoke-watch-store-unavailable",TARGET_UNRESOLVED:"invoke-watch-target-unresolved"}),ke=Object.freeze({MISSING:"watch-target-missing",MALFORMED:"watch-target-malformed",AMBIGUOUS:"watch-target-ambiguous",CONFLICT:"watch-target-conflicting-evidence",SERVER_HELD_STREAM:"watch-target-server-held-stream-unsupported"}),F=Object.freeze({OK:"continuity-ok",WATCH_NO_SUMMARIES_YET:"watch-no-summaries-yet",WATCH_CURSOR_ADVANCED:"watch-cursor-advanced",WATCH_CURSOR_UNCHANGED:"watch-cursor-unchanged",WATCH_RENDER_PENDING:"watch-render-pending",WATCH_STOP_IDLE_LIMIT_REACHED:"watch-stop-idle-limit-reached",WATCH_STOP_MAX_POLLS_REACHED:"watch-stop-max-polls-reached",WATCH_TARGET_UNRESOLVED:"watch-target-unresolved",WATCH_SNAPSHOT_UNAVAILABLE:"watch-snapshot-unavailable",WATCH_EVIDENCE_UNAVAILABLE:"watch-evidence-unavailable"}),Xr=240,xo=/(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 To(e){return e.replace(/[\w.+-]+@[\w-]+\.[\w.-]+/g,St).replace(/(?:sk|pk|whsec|nxk)[-_](?:test|live|ant|proj|pro|free|enterprise)?[-_]?[A-Za-z0-9_-]{16,}/g,St).replace(/NX-[FPE]-[a-f0-9]{24}-[a-f0-9]{4}/g,St).replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,St).replace(fo,St).replace(mo,St)}function ze(e,t){const i=To(e);return i.length<=t?i:`${i.slice(0,t)}\u2026[TRUNCATED:${i.length-t}]`}function Gn(e,t=0,i=new WeakSet){if(t>ho)return"[MAX_DEPTH]";if(e==null)return e;if(typeof e=="string")return ze(e,Pt);if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e=="boolean")return e;if(typeof e=="bigint")return String(e);if(!(typeof e=="function"||typeof e=="symbol")&&typeof e=="object"){if(i.has(e))return"[CIRCULAR]";i.add(e);try{if(Array.isArray(e))return e.slice(0,lo).map(a=>Gn(a,t+1,i));const r={};for(const[a,n]of Object.entries(e).slice(0,uo)){if(go.test(a)){r[a]=St;continue}const o=Gn(n,t+1,i);o!==void 0&&(r[a]=o)}return r}finally{i.delete(e)}}}function fn(e,t){return{instructions:ze(e??"",po),metadata:t?Gn(t):void 0}}function Po(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e,i=typeof t.reason=="string"&&/^[a-z0-9-]{1,80}$/.test(t.reason)?t.reason:void 0,r=typeof t.baseSource=="string"&&["active-story-lease","published-execution-branch","local-default-branch","remote-default-branch","none"].includes(t.baseSource)?t.baseSource:void 0,a=typeof t.repair=="string"&&["not-eligible","not-attempted","applied"].includes(t.repair)?t.repair:void 0,n=typeof t.fallbackAction=="string"&&["reacquire-exact-story-setup","restore-verified-base-evidence","resolve-lease-conflict","inspect-repository-binding","none"].includes(t.fallbackAction)?t.fallbackAction:void 0,o=t.recollectionCount===0||t.recollectionCount===1?t.recollectionCount:void 0;if(!(!i||!r||!a||!n||o===void 0||t.publicSafe!==!0))return{reason:i,base_source:r,repair:a,recollection_count:o,fallback_action:n,public_safe:!0}}class mn extends Error{reason;source;byteLength;code;constructor(t,i,r,a,n){super(i),this.reason=r,this.source=a,this.byteLength=n,this.name="InvokeCliInputError",this.code=t}}function ko(e){const t=ln(e);return(t==="arch-plan"||t==="ui-ux-review")&&Oo(e,"--project-evidence")}function Oo(e,t){let i=null,r=-1,a=!1,n=!1;for(let o=0;o<=e.length;o+=1){const p=e[o];if(o===e.length||!i&&/\s/.test(p??"")){if(r>=0&&!a&&e.slice(r,o)===t)return!0;r=-1,a=!1,n=!1;continue}if(r<0&&(r=o),n){n=!1;continue}if(p==="\\"){n=!0;continue}(p==='"'||p==="'")&&(a=!0,i=i===p?null:i??p)}return!1}const No=/(?:^|\s)codex(?:-cli)?\s+([A-Za-z0-9][A-Za-z0-9._+-]{0,63})(?:\s|$)/i;function Lo(e,t){if(e.targetId!=="codex")return null;const i=t.CODEX_VERSION?.trim();if(i&&/^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/.test(i))return i;try{return Ge("codex",["--version"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim().match(No)?.[1]??null}catch{return null}}function Wn(){return Ua({clientVersion:Tt,registryVersion:ot,registryChecksum:at})}class Fn extends Error{code="PAYLOAD_TOO_LARGE";telemetry;constructor(t){super(`PAYLOAD_TOO_LARGE: invoke request is ${t.payloadBytes} bytes after deterministic degradation; limit is ${t.limitBytes}. Reduce command input or local state context and retry.`),this.name="InvokePayloadTooLargeError",this.telemetry=t}}class Yn 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 qn=!1;function Do(e){const t=[];if(!e||typeof e!="object")return t;const i=e,r=i.planning;if(r&&(r.current!==void 0||Array.isArray(r.history))&&t.push({code:"PLANNING_LEGACY",message:"legacy `planning.current`/`planning.history` detected (not read by v1 orchestrator)"}),Array.isArray(i.stories)&&t.push({code:"STORIES_AS_ARRAY",message:"`stories` is an Array (expected Object keyed by story ID)"}),i.epics&&typeof i.epics=="object"&&!Array.isArray(i.epics))for(const[n,o]of Object.entries(i.epics)){const p=o;if(p&&p.stories!==void 0&&!Array.isArray(p.stories)){t.push({code:"EPIC_STORIES_NOT_ARRAY",message:`epic "${n}" has non-array \`stories\` field (expected string[] of story IDs)`});break}}const a=i.epics&&typeof i.epics=="object"&&Object.keys(i.epics).length>0||i.stories&&typeof i.stories=="object"&&!Array.isArray(i.stories)&&Object.keys(i.stories).length>0||Array.isArray(i.stories)||r&&r.current!==void 0;return i.schema_version===void 0?a&&t.push({code:"SCHEMA_VERSION_MISSING",message:"`schema_version` field missing (expected: `schema_version: 1`)"}):i.schema_version!==1&&t.push({code:"SCHEMA_VERSION_OUTDATED",message:`schema_version=${String(i.schema_version)} (expected: 1)`}),t}function Mo(e){if(!(qn||e.length===0)){qn=!0;try{const t=e.map(i=>` - ${i.message}`).join(`
1
+ import{classifyNonUiArchitectureTransition as $i,architectureMemoryPredecessorCount as mr}from"./architecture-non-ui-continuation.js";import{parseArchitectureNonUiScopeReceipt as yr}from"./shared-architecture-non-ui.js";import{createHash as Pe,randomUUID as dn}from"node:crypto";import{loadPactAnswerReceipt as Ir,loadPactPrivateAnswers as Hi}from"./architecture-answers.js";import{acceptedArchitectureTerminalMemoryReceipt as Wt,deriveArchitectureTerminalMemoryReceipt as On}from"./architecture-memory-terminal.js";import{deriveCommittedArchitectureEpicGraphRevision as Ft,explicitArchitectureEpicTarget as Gi}from"./architecture-root-binding.js";import{derivePactWriteSet as Wi}from"../private-execution/pact-write-set.js";import{execFileSync as Ge}from"node:child_process";import{existsSync as Mt,readFileSync as We,renameSync as Er,unlinkSync as Nn,writeFileSync as pn,mkdirSync as Yt,statSync as Fi,openSync as qt,closeSync as zt,fsyncSync as ln,realpathSync as Yi,lstatSync as jt}from"node:fs";import{isDeepStrictEqual as v}from"node:util";import{join as Q,isAbsolute as qi,resolve as Ln}from"node:path";import{homedir as Jt}from"node:os";import{probeYoloopHostCapacity as zi}from"../runner/host-capacity.js";import{isPrivateExecutionPublicEnvelope as Ji,isPrivatePlanningRootPublicEnvelope as Ki,PRIVATE_MUTATION_QA_GATE_STEP_TOKEN as Qi}from"../private-execution/delivery.js";import{acceptedPlanningDiagnosisPredecessor as Sr}from"../private-execution/planning-diagnosis-checkpoint.js";import{acceptedPlanningResearchPredecessor as vr}from"../private-execution/planning-research-checkpoint.js";import{verifyCommittedPlanningMemory as Cr}from"../private-execution/planning-memory-checkpoint.js";import{verifyCommittedPlanningGeneration as Xi}from"../private-execution/planning-generation-checkpoint.js";import{PLANNING_RAW_INTENT_MAX_CHARS as Zi}from"../../../shared/dist/planning/diagnosis-state.js";import{applyCrossEpicContinuationReconciliation as ea,buildCrossEpicContinuationPayloadHash as ta,classifyCrossEpicContinuationReconciliation as na,epicOperationalHash as It,readEpicOperationalState as _r}from"../git/epic-operational-state.js";import{LicenseClient as ra}from"../license/license-client.js";import{EncryptedCache as Dn}from"../cache/encrypted-cache.js";import{NoOpCache as wr}from"../types/index.js";import{resolveClientPreFlightTrigger as un,TierAwareClient as ia}from"../tier/tier-aware-client.js";import{COMMAND_REGISTRY_CHECKSUM as at,COMMAND_REGISTRY_VERSION as ot,GENERATED_CLIENT_COMMANDS as aa}from"../generated/command-registry.generated.js";import{loadSecureConfig as Mn}from"../config/secure-config.js";import{neocortexProfileDirectory as oa}from"../config/profile-directory.js";import{DEFAULT_SERVER_URL as ca}from"../constants.js";import{detectFirstRunLocale as sa,renderFirstRunMessage as da}from"../i18n/first-run.js";import{humanizeError as Rr,formatHumanizedError as Ar,detectErrorLocale as br}from"../errors/error-messages.js";import{degradeStateSnapshotForPayloadLimit as pa,projectStateSnapshotForInvoke as xr,projectStateSnapshotResultV2ForInvoke as la}from"../state/project-state-snapshot.js";import{isInlineYoloMaterialization as Tr,maybeRepairStateJsonBeforeInvoke as ua,StateRepairHardStopError as ha}from"../state/state-json-repair.js";import{StructuralDagError as Pr}from"../state/structural-dag-projection.js";import{collectStateMigrationAuthority as ga,StateMigrationApplyError as fa}from"../migrations/state-json.js";import{RUNNER_BOOTSTRAP_POLICY_REASON_CODES as ma,classifyRunnerBootstrapPolicyFromArgs as ya}from"../continuity/runner-bootstrap-policy.js";import{RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES as Ia,ensureRunnerSchedulerBootstrap as Ea,observeRunnerOperationalStatus as Sa}from"../runner/scheduler.js";import{CONTINUITY_INVOKE_WATCH_DEFAULT_LIMIT as kr,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_IDLE_POLLS as Or,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_POLLS as Nr,CONTINUITY_INVOKE_WATCH_DEFAULT_POLL_INTERVAL_MS as Lr,openContinuityClientStateStore as va}from"../continuity/continuity-client-state-store.js";import{isLocalJobsConsoleArgs as Ca,runLocalJobsConsoleCommand as _a}from"../runner/local-console.js";import{detectNativeHostAttestation as wa,detectPlatform as Ra}from"../adapters/platform-detector.js";import{signNxInvokeRequest as Aa}from"../../../shared/dist/nx-invoke-signature.js";import{YOLO_INVOKE_ENVELOPE_CAPABILITY as ba}from"../../../shared/dist/yolo/spec-envelope.js";import{parseReleaseBlockedResult as xa}from"../../../shared/dist/yoloop/release-blocked.js";import{CLIENT_VERSION as Pt}from"../version.js";import{createCapabilityCache as Dr,executeInvokeQueryTransport as jn,executeSecondaryNetworkMutation as Ta}from"../effects/invoke-effect-gateways.js";import{STRICT_READ_ONLY_POLICY as Pa,STRICT_READ_ONLY_CLIENT_PROJECTION as Mr,STRICT_READ_ONLY_SERVER_PROJECTION as ka,StrictReadOnlyError as Vt,canonicalizeInvokeEffects as Oa,createInvokeEffectContext as Na,verifyStrictReadOnlyReceipt as La}from"../../../shared/dist/strict-readonly.js";import{admitInvocation as Da,assertInvokeInputEnvelopeV2 as Ma,assertProjectIdentityMigrationReceiptV1 as ja,buildProjectIdentityPublicDiagnostic as Bt,createInvocationAdmissionReceipt as Va,projectInvokeInputEvidenceV1 as Vn,recoverExplicitInvocation as Ba,verifyStrictDiagnoseReceiptV1 as Ua}from"../../../shared/dist/invocation/index.js";import{buildInvokeInputEnvelope as Kt,InvokeInputDecodeError as $a}from"../invocation/invoke-input.js";import{COMPATIBILITY_REASON_CODES as Ut,createCompatibilityOffer as Ha,createLegacyCompatibilityResult as Ga,isCompatibilityResultV1 as Wa}from"../../../shared/dist/compatibility/index.js";import{acknowledgeProjectIdentityMigration as Fa,finalizeProjectIdentityMigration as Ya,prepareProjectIdentityMigration as qa,ProjectIdentityMigrationError as Bn,readProjectIdentityMigrationPhase as za}from"../migrations/project-identity.js";import{probeProjectIdentityMigrationCapability as Ja}from"../migrations/project-identity-capability.js";import{normalizeYoloopStoryPlanningEvidence as Ka}from"../../../shared/dist/yoloop/planning-graph.js";import{normalizeContinuousWriteRef as hn}from"../../../shared/dist/yoloop/wave-decision-receipt.js";import{epicHeadReconciliationInputDigest as Qa,epicHeadReconciliationPathsDigest as jr,epicHeadReconciliationRangeDigest as Xa}from"../../../shared/dist/yoloop/epic-terminal-git.js";import{applyGitLifecycleRuntimeOverlay as Vr,classifyGitLifecycleStoryCheckpointProjectionSync as Za,ensureRuntimeEpic as eo,ensureGitLifecycleRuntimeInitialized as to,executeP205TransientAuthorities as no,persistGitLifecycleGraphAuthority as ro,P205_COMPLETE_COMMAND as Qt,gitLifecycleStoryWriteSet as Br,mutateGitLifecycleRuntime as io,projectP205TransientExecutionEvidence as ao,readGitLifecycleRuntimeSync as gn,verifyLegacyCheckpointMigrationCandidateSync as oo}from"../git/git-lifecycle-store.js";import{verifyRootMemoryPhysicalWriteSet as co}from"../private-execution/root-memory-git-evidence.js";import{isRootProjectMemoryEffect as so}from"../private-execution/shared-root-memory-types.js";import{probeYoloInvokeEnvelopeCapability as po}from"../yolo/invoke-envelope-capability.js";import{collectYoloSpecEnvelope as Ur,extractTargetedYoloStoryId as lo,refreshPrecollectedYoloSpecEnvelope as $r}from"../yolo/spec-envelope-collector.js";const fn=oa(),Un=Q(fn,"cache"),Hr=Q(Un,"menu-cache.json"),Gr=1440*60*1e3,Wr=3e4,Fr=256*1024,Yr=Fr,qr=.8,Et="[REDACTED]",uo=1e5,kt=2e3,ho=200,go=200,fo=12,mo=/(?:promptBody|workflow|workflowGraph|stepBody|privateUrl|rawLog|secret|credential|licenseKey|apiKey|internalRouting|serverOnly|proprietary|protected)/i,yo=/(?:PRIVATE|PROTECTED|SERVER_ONLY)[-_\s]*(?:PROMPT|PROMPT_BODY|WORKFLOW|WORKFLOW_GRAPH|STEP_BODY|STEP|ROUTING)\s*[:=][^\n\r]*/gi,Io=/(?:https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|private|internal)[^\s"'<>]*|raw[_-]?log|transcript|stack\s*trace|stderr:|stdout:|system prompt|prompt body|workflow body|step body|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|VENDOR_CORPUS|P180[_-]?SYNTHETIC[_-]?CONTINUITY|P185[_-]?SYNTHETIC[_-]?CONTINUITY|P187[_-]?SYNTHETIC[_-]?(?:CONTINUITY|RUNNER|WATCH)|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=)/gi,$n=Math.floor(Fr*qr),zr=Q(fn,".first-run-shown"),Eo="pending-epic-claims.json",Jr=64;function Kr(e){return Q(e,".neocortex",Eo)}function $t(e){const t=Kr(e);if(!Mt(t))return{schemaVersion:1,operations:{}};const i=JSON.parse(We(t,"utf8"));if(!i||typeof i!="object"||Array.isArray(i))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const r=i;if(r.schemaVersion!==1||!r.operations||typeof r.operations!="object"||Array.isArray(r.operations))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(Object.keys(r.operations).length>Jr)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");for(const[a,n]of Object.entries(r.operations)){if(!/^[a-f0-9]{64}$/.test(a)||!n||typeof n!="object"||Array.isArray(n))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const o=n;if(o.planningProtocol!==void 0&&o.planningProtocol!=="root-staged-v1")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(typeof o.idempotencyKey!="string"||!/^[0-9a-f-]{36}$/.test(o.idempotencyKey)||typeof o.createdAt!="string")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(o.claimId!==void 0&&(typeof o.claimId!="string"||!/^[0-9a-f-]{36}$/.test(o.claimId))||o.epicId!==void 0&&(typeof o.epicId!="string"||!/^P[1-9][0-9]*$/.test(o.epicId))||o.claimId===void 0!=(o.epicId===void 0))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE")}return i}function Hn(e,t){const i=Kr(e);Yt(Q(e,".neocortex"),{recursive:!0,mode:448});const r=`${i}.${process.pid}.${dn()}.tmp`;pn(r,`${JSON.stringify(t)}
2
+ `,{encoding:"utf8",mode:384,flag:"wx"}),Er(r,i)}function So(e,t){return Pe("sha256").update(`nx-epic-logical-operation-v1\0${JSON.stringify({command:t,args:e})}`,"utf8").digest("hex")}function vo(e,t,i="create-epic"){const r=So(t,i),a=$t(e),n=a.operations[r];if(n)return{key:n.idempotencyKey,fingerprint:r};if(Object.keys(a.operations).length>=Jr)throw new Error("EPIC_CLAIM_CAPACITY_EXCEEDED");const o=dn(),p={...a.operations,[r]:{idempotencyKey:o,createdAt:new Date().toISOString()}};return Hn(e,{schemaVersion:1,operations:p}),{key:o,fingerprint:r}}function Co(e,t){const i=$t(e);if(!i.operations[t])return;const r={...i.operations};delete r[t],Hn(e,{schemaVersion:1,operations:r})}function _o(e,t,i,r){const a=r.scope?.targetStoryId??r.current_session?.active_story_id??null,n=r.scope?.targetEpicId??r.current_session?.active_epic_id??null,o=a?r.stories[a]:void 0,p=Array.isArray(o?.steps_completed)?o.steps_completed.filter(I=>typeof I=="string"):[],s=i??Pe("sha256").update(`nx-yolo-project-path-v1\0${Ln(e)}`,"utf8").digest("hex"),l=JSON.stringify({projectBinding:s,args:t,storyId:a,epicId:n,status:typeof o?.status=="string"?o.status:null,lastStep:typeof o?.last_step=="string"?o.last_step:null,stepsCompleted:p});return`yolo-${Pe("sha256").update(`nx-yolo-logical-operation-v1\0${l}`,"utf8").digest("hex")}`}function Qr(e,t,i,r,a){if(!/^[0-9a-f-]{36}$/.test(i)||!/^P[1-9][0-9]*$/.test(r)||a!==void 0&&a!=="root-staged-v1")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const n=$t(e),o=n.operations[t];if(!o)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(o.claimId!==void 0&&(o.claimId!==i||o.epicId!==r))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");Hn(e,{schemaVersion:1,operations:{...n.operations,[t]:{...o,claimId:i,epicId:r,...a?{planningProtocol:a}:{}}}})}function wo(){try{if(Mt(zr))return;const e=sa(),t=da(e);process.stderr.write(t);try{Yt(fn,{recursive:!0}),pn(zr,new Date().toISOString(),"utf-8")}catch{}}catch{}}function Gn(e,t=process.cwd()){return e&&e.trim().length>0?e:t}function Ro(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 Ao(e){const t=e.metadata;if(!t||!(t.yoloopReleaseBlocked===!0||t.terminalClass==="release-blocked"||t.releaseBlocked!==void 0))return;const r=xa(t.releaseBlocked);return!r||t.yoloopReleaseBlocked!==!0||t.terminalClass!=="release-blocked"||t.yoloopComplete!==!1||t.yoloopAborted!==!1?{success:!1,error:"YOLOOP_RELEASE_BLOCKED_INVALID: terminal evidence was inconsistent.",errorCode:"YOLOOP_RELEASE_BLOCKED_INVALID",metadata:t,exitCode:1}:{success:!1,instructions:e.instructions,metadata:{...t,releaseBlocked:r},error:"YOLOOP_RELEASE_BLOCKED: the current release attempt ended without success.",errorCode:"YOLOOP_RELEASE_BLOCKED",exitCode:1}}function Xr(e){return Da(e,{registryVersion:ot,registryChecksum:at})}function bo(e){return Ba(e,{registryVersion:ot,registryChecksum:at})}const xo=new Set(["completed","aborted","cancelled"]),To=new Set(["watch-target-missing","watch-target-malformed","watch-target-ambiguous","watch-target-multiple"]),_e=Object.freeze({COMPLETED:"invoke-watch-completed",CANCELLED:"invoke-watch-cancelled",IDLE_TIMEOUT:"invoke-watch-idle-timeout",MAX_POLLS:"invoke-watch-max-polls",STORE_UNAVAILABLE:"invoke-watch-store-unavailable",TARGET_UNRESOLVED:"invoke-watch-target-unresolved"}),ke=Object.freeze({MISSING:"watch-target-missing",MALFORMED:"watch-target-malformed",AMBIGUOUS:"watch-target-ambiguous",CONFLICT:"watch-target-conflicting-evidence",SERVER_HELD_STREAM:"watch-target-server-held-stream-unsupported"}),Y=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"}),Zr=240,Po=/(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 ko(e){return e.replace(/[\w.+-]+@[\w-]+\.[\w.-]+/g,Et).replace(/(?:sk|pk|whsec|nxk)[-_](?:test|live|ant|proj|pro|free|enterprise)?[-_]?[A-Za-z0-9_-]{16,}/g,Et).replace(/NX-[FPE]-[a-f0-9]{24}-[a-f0-9]{4}/g,Et).replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,Et).replace(yo,Et).replace(Io,Et)}function ze(e,t){const i=ko(e);return i.length<=t?i:`${i.slice(0,t)}\u2026[TRUNCATED:${i.length-t}]`}function Wn(e,t=0,i=new WeakSet){if(t>fo)return"[MAX_DEPTH]";if(e==null)return e;if(typeof e=="string")return ze(e,kt);if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e=="boolean")return e;if(typeof e=="bigint")return String(e);if(!(typeof e=="function"||typeof e=="symbol")&&typeof e=="object"){if(i.has(e))return"[CIRCULAR]";i.add(e);try{if(Array.isArray(e))return e.slice(0,ho).map(a=>Wn(a,t+1,i));const r={};for(const[a,n]of Object.entries(e).slice(0,go)){if(mo.test(a)){r[a]=Et;continue}const o=Wn(n,t+1,i);o!==void 0&&(r[a]=o)}return r}finally{i.delete(e)}}}function mn(e,t){return{instructions:ze(e??"",uo),metadata:t?Wn(t):void 0}}function Oo(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e,i=typeof t.reason=="string"&&/^[a-z0-9-]{1,80}$/.test(t.reason)?t.reason:void 0,r=typeof t.baseSource=="string"&&["active-story-lease","published-execution-branch","local-default-branch","remote-default-branch","none"].includes(t.baseSource)?t.baseSource:void 0,a=typeof t.repair=="string"&&["not-eligible","not-attempted","applied"].includes(t.repair)?t.repair:void 0,n=typeof t.fallbackAction=="string"&&["reacquire-exact-story-setup","restore-verified-base-evidence","resolve-lease-conflict","inspect-repository-binding","none"].includes(t.fallbackAction)?t.fallbackAction:void 0,o=t.recollectionCount===0||t.recollectionCount===1?t.recollectionCount:void 0;if(!(!i||!r||!a||!n||o===void 0||t.publicSafe!==!0))return{reason:i,base_source:r,repair:a,recollection_count:o,fallback_action:n,public_safe:!0}}class yn extends Error{reason;source;byteLength;code;constructor(t,i,r,a,n){super(i),this.reason=r,this.source=a,this.byteLength=n,this.name="InvokeCliInputError",this.code=t}}function No(e){const t=un(e);return(t==="arch-plan"||t==="ui-ux-review")&&Lo(e,"--project-evidence")}function Lo(e,t){let i=null,r=-1,a=!1,n=!1;for(let o=0;o<=e.length;o+=1){const p=e[o];if(o===e.length||!i&&/\s/.test(p??"")){if(r>=0&&!a&&e.slice(r,o)===t)return!0;r=-1,a=!1,n=!1;continue}if(r<0&&(r=o),n){n=!1;continue}if(p==="\\"){n=!0;continue}(p==='"'||p==="'")&&(a=!0,i=i===p?null:i??p)}return!1}const Do=/(?:^|\s)codex(?:-cli)?\s+([A-Za-z0-9][A-Za-z0-9._+-]{0,63})(?:\s|$)/i;function Mo(e,t){if(e.targetId!=="codex")return null;const i=t.CODEX_VERSION?.trim();if(i&&/^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/.test(i))return i;try{return Ge("codex",["--version"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim().match(Do)?.[1]??null}catch{return null}}function Fn(){return Ha({clientVersion:Pt,registryVersion:ot,registryChecksum:at})}class Yn extends Error{code="PAYLOAD_TOO_LARGE";telemetry;constructor(t){super(`PAYLOAD_TOO_LARGE: invoke request is ${t.payloadBytes} bytes after deterministic degradation; limit is ${t.limitBytes}. Reduce command input or local state context and retry.`),this.name="InvokePayloadTooLargeError",this.telemetry=t}}class qn extends Error{code="STRUCTURAL_CONTEXT_TOO_LARGE";telemetry;constructor(t){super(`STRUCTURAL_CONTEXT_TOO_LARGE: the bounded structural projection is ${t.payloadBytes} bytes; the request limit is strictly below ${t.limitBytes}. Select an explicit epic/story target or split the dependency graph.`),this.name="InvokeStructuralContextTooLargeError",this.telemetry=t}}let zn=!1;function jo(e){const t=[];if(!e||typeof e!="object")return t;const i=e,r=i.planning;if(r&&(r.current!==void 0||Array.isArray(r.history))&&t.push({code:"PLANNING_LEGACY",message:"legacy `planning.current`/`planning.history` detected (not read by v1 orchestrator)"}),Array.isArray(i.stories)&&t.push({code:"STORIES_AS_ARRAY",message:"`stories` is an Array (expected Object keyed by story ID)"}),i.epics&&typeof i.epics=="object"&&!Array.isArray(i.epics))for(const[n,o]of Object.entries(i.epics)){const p=o;if(p&&p.stories!==void 0&&!Array.isArray(p.stories)){t.push({code:"EPIC_STORIES_NOT_ARRAY",message:`epic "${n}" has non-array \`stories\` field (expected string[] of story IDs)`});break}}const a=i.epics&&typeof i.epics=="object"&&Object.keys(i.epics).length>0||i.stories&&typeof i.stories=="object"&&!Array.isArray(i.stories)&&Object.keys(i.stories).length>0||Array.isArray(i.stories)||r&&r.current!==void 0;return i.schema_version===void 0?a&&t.push({code:"SCHEMA_VERSION_MISSING",message:"`schema_version` field missing (expected: `schema_version: 1`)"}):i.schema_version!==1&&t.push({code:"SCHEMA_VERSION_OUTDATED",message:`schema_version=${String(i.schema_version)} (expected: 1)`}),t}function Vo(e){if(!(zn||e.length===0)){zn=!0;try{const t=e.map(i=>` - ${i.message}`).join(`
3
3
  `);process.stderr.write(`[Neocortex] state.json schema drift detected:
4
4
  ${t}
5
5
  Run \`neocortex *migrate-state --preview\` to inspect or \`neocortex *migrate-state --apply\` to migrate.
6
6
  See docs/arquitetura-software/STATE-JSON-SCHEMA.md for the schema contract.
7
- `)}catch{}}}function yd(){qn=!1}function Zr(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function jo(e){return e==="active"||e==="archived"||e==="rolled-back"||e==="synthetic"||e==="orphan"?e:void 0}const Vo=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"]),Bo=/(?:[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}|(?:token|api[_-]?key|secret|password|credential|license[_-]?key)\s*[:=]\s*\S+|https?:\/\/(?:localhost|127\.0\.0\.1|10\.\d+\.\d+\.\d+|192\.168\.\d+\.\d+|172\.(?:1[6-9]|2\d|3[0-1])\.\d+\.\d+|[^\s/]*internal[^\s/]*)\S*|private\s+prompt|raw\s+vendor\s+corpus|sk-[A-Za-z0-9_-]{12,})/i;function Uo(e,t){if(!h(e)||e.schemaVersion!==1||e.epicId!==t||!/^P\d+$/.test(t))return{};try{const i=JSON.stringify(e),r=Buffer.byteLength(i);if(r>16384)return{diagnostic:Object.freeze({schemaVersion:"CreateEpicPlanningProjectionDiagnostic/1.0",outcome:"omitted",reasonCode:"budget-omitted",byteLengthBucket:r<=32768?"16385-32768":"32769-plus",publicSafe:!0})};if(Bo.test(i))return{};const a=(o,p)=>{if(Object.keys(o).some(s=>!p.includes(s)))throw new Error("planning-unknown-field")};if(a(e,["schemaVersion","epicId","intake","intakeRevision","diagnosisReceipt","researchReceipt","degradeAuthorization"]),!h(e.intake))return{};if(Object.keys(e.intake).some(o=>!Vo.has(o)))return{};for(const[o,p]of Object.entries(e.intake))if(["examples","contracts"].includes(o)){const s=o==="examples"?["id","title","actor","given","when","then","source","coveredRequirement","expectedValidation"]:["id","kind","description","path"];if(!Array.isArray(p)||p.length>16)return{};for(const l of p){if(!h(l))return{};if(a(l,s),Object.values(l).some(I=>typeof I!="string"||I.length>256))return{}}}else if(Array.isArray(p)){if(p.length>32||p.some(s=>typeof s!="string"||s.length>256))return{}}else if(typeof p=="string"){if(p.length>(o==="rawIntent"?Qi:512))return{}}else if(typeof p!="boolean"||!["uiScope","remediationStory"].includes(o))return{};const n=["schemaVersion","kind","epicId","intakeRevision","artifactSummary","artifactDigest","predecessorReceiptId","accepted","receiptId"];for(const o of[e.diagnosisReceipt,e.researchReceipt])if(o!==void 0){if(!h(o))return{};if(a(o,n),Object.values(o).some(p=>typeof p=="string"&&p.length>1024))return{}}if(e.degradeAuthorization!==void 0){if(!h(e.degradeAuthorization))return{};a(e.degradeAuthorization,["approved","intakeRevision","reasonCodes","assumptionCodes"]);for(const o of["reasonCodes","assumptionCodes"]){const p=e.degradeAuthorization[o];if(!Array.isArray(p)||p.length>32||p.some(s=>typeof s!="string"||s.length>128))return{}}}return{checkpoint:JSON.parse(i)}}catch{return{}}}function ei(e){return e==="create-epic"||e==="discovered"?e:void 0}function Se(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function $o(e){const t={};let i=!1;for(const r of["contracts","contract_refs","shared_surfaces","adr_refs","nfr_refs","acceptance_depends_on"]){if(e[r]===void 0)continue;const a=e[r];if(!Array.isArray(a)||a.length>128||a.some(n=>un(n)===void 0)){i=!0;continue}t[r]=a.map(n=>un(n))}if(e.planning!==void 0)try{if(!h(e.planning))throw new Error("planning-shape");const r=e.planning;for(const o of["claims","semanticArtifacts"]){if(r[o]===void 0)continue;const p=r[o];if(!Array.isArray(p)||p.length>128||p.some(s=>!h(s)||un(s.ref)===void 0))throw new Error("planning-refs")}if(r.attempts!==void 0&&(!Array.isArray(r.attempts)||r.attempts.length>32))throw new Error("planning-attempts");for(const o of r.attempts??[]){if(!h(o)||!Array.isArray(o.reasonCodes)||o.reasonCodes.length>32||o.reasonCodes.some(p=>typeof p!="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(p)))throw new Error("planning-attempt-reasons");if(o.discoveredClaims!==void 0&&(!Array.isArray(o.discoveredClaims)||o.discoveredClaims.length>128||o.discoveredClaims.some(p=>!h(p)||un(p.ref)===void 0)))throw new Error("planning-attempt-claims")}const{graphRevision:a,...n}=za(r);t.planning=n}catch{i=!0}return i&&(t.planning={schemaVersion:1,dependencyBasis:"unknown",claims:[],semanticArtifacts:[]}),t}function h(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function vt(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function te(e){if(typeof e!="string")return;const t=e.trim();if(t)return t.replace(/[^a-z0-9_.:-]+/gi,"_").slice(0,120)}function K(e){if(typeof e!="string")return;const t=e.trim(),i=te(e);return i===t?i:void 0}function ve(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240)&&/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(t)&&!(t.includes("..")||t.includes("//")||t.includes("@{")||t.endsWith("/")||t.endsWith("."))&&!t.split("/").some(i=>!i||i.startsWith(".")||i.endsWith(".lock")))return t}function w(e){return typeof e=="string"&&/^[0-9a-f]{7,64}$/i.test(e)?e:void 0}function Oe(e){if(!(typeof e!="string"||e.length>64)&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/.test(e))return Number.isFinite(Date.parse(e))?e:void 0}function ct(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240||t.includes("..")))return/^[A-Za-z0-9._:/#\-[\]]+$/.test(t)?t:void 0}function yn(e){if(!h(e))return;const t=u=>typeof u=="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,95}$/.test(u),i=u=>typeof u=="string"&&/^[a-f0-9]{64}$/.test(u),r=(u,_)=>Array.isArray(u)&&u.length<=_&&u.every(t)&&new Set(u).size===u.length?u:void 0,a=(u,_)=>{if(!(!h(u)||u.schemaVersion!==2||!t(u.requestId)||!t(u.stageCommand)||!i(u.requestHash)||!i(u.inputHash)||!i(u.stateHash)||!i(u.nonce)||!i(u.stageRevision)||!i(u.stageHash)||!i(u.catalogHash)||u.targetEpicId!==void 0&&!t(u.targetEpicId)||_&&(!i(u.outputHash)||!i(u.artifactHash))))return{schemaVersion:2,...u.targetEpicId?{targetEpicId:u.targetEpicId}:{},requestId:u.requestId,requestHash:u.requestHash,inputHash:u.inputHash,stateHash:u.stateHash,nonce:u.nonce,stageCommand:u.stageCommand,stageRevision:u.stageRevision,stageHash:u.stageHash,catalogHash:u.catalogHash,..._?{outputHash:u.outputHash,artifactHash:u.artifactHash}:{}}},n=(u,_)=>{if(!(!h(u)||u.schemaVersion!=="1.1"||u.kind!==_||!i(u.receiptId)||!i(u.graphHash)||!i(u.evidenceHash)||!t(u.elementId)||!t(u.caseId)||!t(u.category)))return{schemaVersion:"1.1",kind:_,receiptId:u.receiptId,graphHash:u.graphHash,elementId:u.elementId,caseId:u.caseId,category:u.category,evidenceHash:u.evidenceHash}},o=(u,_)=>{if(!h(u)||u.kind!==_||!i(u.receiptId)||!r(u.evidenceIds,24)||_==="architecture-stage-completion"&&!["succeeded","failed"].includes(String(u.status))||_==="architecture-stage-validation"&&!["passed","failed","pending"].includes(String(u.status)))return;const E=a(u,!0);if(!E)return;const g=_==="architecture-stage-validation"?n(u.isolated,"isolated"):void 0,y=_==="architecture-stage-validation"?n(u.regression,"regression"):void 0;if(!(_==="architecture-stage-validation"&&(!g||!y)))return{...E,kind:_,receiptId:u.receiptId,status:u.status,evidenceIds:u.evidenceIds,...g&&y?{isolated:g,regression:y}:{}}},p={};e.schemaVersion===1&&(p.schemaVersion=1),e.owner==="root"&&(p.owner="root"),t(e.currentStageCommand)&&(p.currentStageCommand=e.currentStageCommand),["ask-user","delegate","resume","advance","blocked","complete"].includes(String(e.continuationState))&&(p.continuationState=e.continuationState);const s=r(e.questionIds,16);if(s&&(p.questionIds=s),(e.childStatus==="succeeded"||e.childStatus==="failed")&&(p.childStatus=e.childStatus),(e.evidencePolicy==="legacy-compatible"||e.evidencePolicy==="v2-required")&&(p.evidencePolicy=e.evidencePolicy),t(e.targetEpicId)&&(p.targetEpicId=e.targetEpicId),i(e.graphRevision)&&(p.graphRevision=e.graphRevision),e.graphSource==="committed-epic-v1"&&(p.graphSource=e.graphSource),e.nonUiScopeReceipt!==void 0){const u=mr(e.nonUiScopeReceipt);if(!u||u.targetEpicId!==e.targetEpicId||u.graphRevision!==e.graphRevision||!h(e.accounting)||u.accountingId!==e.accounting.accountingId||!h(e.evidenceExpectation)||u.rootInputSha256!==e.evidenceExpectation.inputHash)throw new Error("architecture-non-ui-scope-invalid");p.nonUiScopeReceipt=u}h(e.pactAnswerReceipt)&&Object.keys(e.pactAnswerReceipt).sort().join(",")===["schemaVersion","targetEpicId","graphRevision","stateSha256","answersSha256","questionIds","publicSafe"].sort().join(",")&&e.pactAnswerReceipt.schemaVersion==="PactAnswerReceipt/1"&&e.pactAnswerReceipt.targetEpicId===e.targetEpicId&&e.pactAnswerReceipt.graphRevision===e.graphRevision&&i(e.pactAnswerReceipt.stateSha256)&&i(e.pactAnswerReceipt.answersSha256)&&v(e.pactAnswerReceipt.questionIds,["PACT-Q1-CONSUMER","PACT-Q2-PROVIDER","PACT-Q3-BROKER","PACT-Q4-MATCHERS","PACT-Q5-VERIFY"])&&e.pactAnswerReceipt.publicSafe===!0&&(p.pactAnswerReceipt=e.pactAnswerReceipt);const l=a(e.evidenceExpectation,!1);l&&(p.evidenceExpectation=l);const I=o(e.completionEvidence,"architecture-stage-completion"),S=o(e.validationEvidence,"architecture-stage-validation");if(I&&(p.completionEvidence=I),S&&(p.validationEvidence=S),h(e.reviewDecision)&&Object.keys(e.reviewDecision).sort().join(",")===["schemaVersion","targetEpicId","graphRevision","artifactHash","completionReceiptId","validationReceiptId","decision","evidenceIds","publicSafe"].sort().join(",")&&e.reviewDecision.schemaVersion==="ArchitectureReviewDecision/1"&&e.reviewDecision.targetEpicId===e.targetEpicId&&e.reviewDecision.graphRevision===e.graphRevision&&i(e.reviewDecision.graphRevision)&&i(e.reviewDecision.artifactHash)&&i(e.reviewDecision.completionReceiptId)&&i(e.reviewDecision.validationReceiptId)&&["approved","changes-requested"].includes(String(e.reviewDecision.decision))&&e.reviewDecision.publicSafe===!0){const u=r(e.reviewDecision.evidenceIds,24);u&&u.length>0&&(p.reviewDecision={...e.reviewDecision,evidenceIds:u})}if(Ft(e.terminalMemoryCheckpoint,e))p.terminalMemoryCheckpoint=e.terminalMemoryCheckpoint;else if(h(e.terminalMemoryCheckpoint)&&e.terminalMemoryCheckpoint.schemaVersion===void 0&&["passed","failed","pending"].includes(String(e.terminalMemoryCheckpoint.status))){const u=r(e.terminalMemoryCheckpoint.evidenceIds,24);u&&(p.terminalMemoryCheckpoint={status:e.terminalMemoryCheckpoint.status,evidenceIds:u})}if(Array.isArray(e.acceptedStages)&&e.acceptedStages.length<=15){const u=e.acceptedStages.map(_=>{if(!h(_)||!t(_.targetEpicId)||!t(_.stageCommand))return;const E=o(_.completionEvidence,"architecture-stage-completion"),g=o(_.validationEvidence,"architecture-stage-validation");return E&&g?{targetEpicId:_.targetEpicId,stageCommand:_.stageCommand,completionEvidence:E,validationEvidence:g}:void 0});u.every(_=>_!==void 0)&&(p.acceptedStages=u)}if(h(e.accounting)&&e.accounting.schemaVersion===1&&t(e.accounting.contractVersion)&&t(e.accounting.accountingId)&&typeof e.accounting.charged=="boolean"&&Number.isInteger(e.accounting.chargedQuotaUnits)&&typeof e.accounting.chargedQuotaUnits=="number"&&e.accounting.chargedQuotaUnits>=0&&e.accounting.chargedQuotaUnits<=13){const u=r(e.accounting.receiptIds,32);u&&(p.accounting={schemaVersion:1,contractVersion:e.accounting.contractVersion,accountingId:e.accounting.accountingId,charged:e.accounting.charged,chargedQuotaUnits:e.accounting.chargedQuotaUnits,receiptIds:u,...["in-progress","aborted","timed-out","failed","complete"].includes(String(e.accounting.lastOutcome))?{lastOutcome:e.accounting.lastOutcome}:{}})}return JSON.stringify(p).length<=96e3?p:void 0}function Ho(e){const t=h(e.metadata.archPlan)?e.metadata.archPlan.execution:void 0,i=h(t)?t.checkpoint:void 0,r=h(t)?t:void 0,a=h(i)?i:void 0,n=e.requestExecution,o=Array.isArray(a?.acceptedStages)?a.acceptedStages:[],p=n.currentStageCommand==="arch-prd"&&n.continuationState==="delegate"&&n.completionEvidence===void 0&&n.validationEvidence===void 0&&a?.currentStageCommand==="arch-prd"&&a.continuationState==="delegate"&&o.length===0&&r?.nextAction==="delegate",s=n.currentStageCommand==="arch-prd"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-architecture"&&a.continuationState==="advance"&&o.length===1&&h(o[0])&&o[0].stageCommand==="arch-prd"&&v(o[0].completionEvidence,n.completionEvidence)&&v(o[0].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",l=n.currentStageCommand==="arch-architecture"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-architecture"&&a.continuationState==="delegate"&&o.length===1&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",I=n.currentStageCommand==="arch-architecture"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-fitness-functions"&&a.continuationState==="advance"&&o.length===2&&h(o[0])&&h(o[1])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===1&&v(o[0],n.acceptedStages[0])&&v(o[1].completionEvidence,n.completionEvidence)&&v(o[1].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",S=n.currentStageCommand==="arch-fitness-functions"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-fitness-functions"&&a.continuationState==="delegate"&&o.length===2&&h(o[0])&&h(o[1])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",u=n.currentStageCommand==="arch-fitness-functions"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-api-contracts"&&a.continuationState==="advance"&&o.length===3&&h(o[0])&&h(o[1])&&h(o[2])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&o[2].stageCommand==="arch-fitness-functions"&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===2&&v(o.slice(0,2),n.acceptedStages)&&v(o[2].completionEvidence,n.completionEvidence)&&v(o[2].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",_=n.currentStageCommand==="arch-api-contracts"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-api-contracts"&&a.continuationState==="delegate"&&o.length===3&&h(o[0])&&h(o[1])&&h(o[2])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&o[2].stageCommand==="arch-fitness-functions"&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",E=["PACT-Q1-CONSUMER","PACT-Q2-PROVIDER","PACT-Q3-BROKER","PACT-Q4-MATCHERS","PACT-Q5-VERIFY"],g=n.currentStageCommand==="arch-api-contracts"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="generate-pacts"&&a.continuationState==="ask-user"&&o.length===4&&h(o[3])&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===3&&v(o.slice(0,3),n.acceptedStages)&&o[3].stageCommand==="arch-api-contracts"&&v(o[3].completionEvidence,n.completionEvidence)&&v(o[3].validationEvidence,n.validationEvidence)&&v(a.questionIds,E)&&v(r?.questionIds,E)&&r?.nextAction==="ask-user",y=n.currentStageCommand==="generate-pacts"&&n.continuationState==="ask-user"&&a?.currentStageCommand==="generate-pacts"&&a.continuationState==="delegate"&&o.length===4&&v(o,n.acceptedStages)&&v(n.questionIds,E)&&v(a.questionIds,[])&&v(a.pactAnswerReceipt,e.answerReceipt)&&v(r?.pactAnswerReceipt,e.answerReceipt)&&e.answerReceipt?.stateSha256===e.sourceStateSha256&&r?.nextAction==="resume",x=n.currentStageCommand==="generate-pacts"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&v(n.pactAnswerReceipt,e.pactRecordedReceipt)&&a?.currentStageCommand==="arch-api-integrations"&&a.continuationState==="advance"&&o.length===5&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===4&&v(o.slice(0,4),n.acceptedStages)&&o.map(B=>h(B)?B.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts"&&h(o[4])&&v(o[4].completionEvidence,n.completionEvidence)&&v(o[4].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",D=n.currentStageCommand==="arch-api-integrations"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-api-integrations"&&a.continuationState==="delegate"&&o.length===5&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",T=n.currentStageCommand==="arch-api-integrations"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-database"&&a.continuationState==="advance"&&o.length===6&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===5&&v(o.slice(0,5),n.acceptedStages)&&o.map(B=>h(B)?B.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations"&&h(o[5])&&v(o[5].completionEvidence,n.completionEvidence)&&v(o[5].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",P=n.currentStageCommand==="arch-database"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-database"&&a.continuationState==="delegate"&&o.length===6&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",C=n.currentStageCommand==="arch-database"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-security"&&a.continuationState==="advance"&&o.length===7&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===6&&v(o.slice(0,6),n.acceptedStages)&&o.map(B=>h(B)?B.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database"&&h(o[6])&&v(o[6].completionEvidence,n.completionEvidence)&&v(o[6].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",R=n.currentStageCommand==="arch-security"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-security"&&a.continuationState==="delegate"&&o.length===7&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",M=n.currentStageCommand==="arch-security"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-design-system"&&a.continuationState==="advance"&&o.length===8&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===7&&v(o.slice(0,7),n.acceptedStages)&&o.map(B=>h(B)?B.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security"&&h(o[7])&&v(o[7].completionEvidence,n.completionEvidence)&&v(o[7].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",N=n.currentStageCommand==="arch-design-system"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-design-system"&&a.continuationState==="delegate"&&o.length===8&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",q=n.currentStageCommand==="arch-design-system"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-ux-design"&&a.continuationState==="advance"&&o.length===9&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===8&&v(o.slice(0,8),n.acceptedStages)&&o.map(B=>h(B)?B.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system"&&h(o[8])&&v(o[8].completionEvidence,n.completionEvidence)&&v(o[8].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",Z=n.currentStageCommand==="arch-ux-design"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-ux-design"&&a.continuationState==="delegate"&&o.length===9&&v(o,n.acceptedStages)&&r?.nextAction==="blocked",j=n.currentStageCommand==="arch-ux-design"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-performance"&&a.continuationState==="advance"&&o.length===10&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===9&&v(o.slice(0,9),n.acceptedStages)&&o.map(B=>h(B)?B.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design"&&h(o[9])&&v(o[9].completionEvidence,n.completionEvidence)&&v(o[9].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",V=n.currentStageCommand==="arch-performance"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-performance"&&a.continuationState==="delegate"&&o.length===10&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",ee=n.currentStageCommand==="arch-performance"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-testing"&&a.continuationState==="advance"&&o.length===11&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===10&&v(o.slice(0,10),n.acceptedStages)&&o.map(B=>h(B)?B.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance"&&h(o[10])&&v(o[10].completionEvidence,n.completionEvidence)&&v(o[10].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",H=n.currentStageCommand==="arch-testing"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-testing"&&a.continuationState==="delegate"&&o.length===11&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",lt=n.currentStageCommand==="arch-testing"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-infrastructure"&&a.continuationState==="advance"&&o.length===12&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===11&&v(o.slice(0,11),n.acceptedStages)&&o.map(B=>h(B)?B.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance,arch-testing"&&h(o[11])&&v(o[11].completionEvidence,n.completionEvidence)&&v(o[11].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",Ye=n.currentStageCommand==="arch-infrastructure"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-infrastructure"&&a.continuationState==="delegate"&&o.length===12&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",he=n.currentStageCommand==="arch-infrastructure"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-review"&&a.continuationState==="advance"&&o.length===13&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===12&&v(o.slice(0,12),n.acceptedStages)&&o.map(B=>h(B)?B.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance,arch-testing,arch-infrastructure"&&h(o[12])&&v(o[12].completionEvidence,n.completionEvidence)&&v(o[12].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",k=n.currentStageCommand==="arch-review"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-review"&&a.continuationState==="delegate"&&o.length===13&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",G=n.currentStageCommand==="arch-review"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&n.reviewDecision===void 0&&a?.currentStageCommand==="arch-review"&&a.continuationState==="ask-user"&&o.length===13&&v(o,n.acceptedStages)&&v(a.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&v(a.completionEvidence,n.completionEvidence)&&v(a.validationEvidence,n.validationEvidence)&&r?.nextAction==="ask-user",_t=n.currentStageCommand==="arch-review"&&n.continuationState==="ask-user"&&n.childStatus==="succeeded"&&h(n.reviewDecision)&&n.reviewDecision.decision==="approved"&&v(n.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&a?.currentStageCommand==="update-memory"&&a.continuationState==="advance"&&o.length===14&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===13&&v(o.slice(0,13),n.acceptedStages)&&h(o[13])&&o[13].stageCommand==="arch-review"&&v(o[13].completionEvidence,n.completionEvidence)&&v(o[13].validationEvidence,n.validationEvidence)&&v(a.reviewDecision,n.reviewDecision)&&r?.nextAction==="resume",De=n.currentStageCommand==="update-memory"&&n.continuationState==="advance"&&h(n.reviewDecision)&&n.reviewDecision.decision==="approved"&&a?.currentStageCommand==="update-memory"&&a.continuationState==="delegate"&&o.length===14&&v(o,n.acceptedStages)&&v(a.reviewDecision,n.reviewDecision)&&r?.nextAction==="delegate",se=n.currentStageCommand==="update-memory"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="update-memory"&&a.continuationState==="complete"&&o.length===15&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===14&&v(o.slice(0,14),n.acceptedStages)&&h(o[14])&&o[14].targetEpicId===n.targetEpicId&&o[14].stageCommand==="update-memory"&&v(o[14].completionEvidence,n.completionEvidence)&&v(o[14].validationEvidence,n.validationEvidence)&&v(a.reviewDecision,n.reviewDecision)&&v(a.completionEvidence,n.completionEvidence)&&v(a.validationEvidence,n.validationEvidence)&&Ft(a.terminalMemoryCheckpoint,n)!==null&&v(a.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)&&r?.nextAction==="complete",tt=n.currentStageCommand==="update-memory"&&n.continuationState==="complete"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="update-memory"&&a.continuationState==="complete"&&o.length===15&&v(o,n.acceptedStages)&&v(a.reviewDecision,n.reviewDecision)&&v(a.completionEvidence,n.completionEvidence)&&v(a.validationEvidence,n.validationEvidence)&&Ft(a.terminalMemoryCheckpoint,n)&&v(a.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)&&r?.nextAction==="complete",ut=r?Ui(n,r,Ft(n.terminalMemoryCheckpoint,n)&&v(a?.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)):void 0;if(e.metadata.mode!=="arch-plan"||e.metadata.resolvedTrigger!=="arch-plan"||!h(t)||!h(i)||t.owner!=="root"||t.currentStageCommand!==i.currentStageCommand||t.continuationState!==i.continuationState||i.owner!=="root"||i.evidencePolicy!=="v2-required"||i.targetEpicId!==n.targetEpicId||i.graphRevision!==n.graphRevision||i.graphSource!==n.graphSource||!/^P[1-9][0-9]{0,11}$/.test(String(i.targetEpicId))||!/^[a-f0-9]{64}$/.test(String(i.graphRevision))||!Array.isArray(i.acceptedStages)||!(ut||p||s||l||I||S||u||_||g||y||x||D||T||P||C||R||M||N||q||Z||j||V||ee||H||lt||Ye||he||k||G||_t||De||se||tt)||!h(i.accounting)||i.accounting.charged!==!0||!v(yn(i),i))throw new Error("architecture-root-checkpoint-invalid");const X=Q(e.projectRoot,".neocortex"),ye=Q(X,"state.json"),le=Q(X,"state.json.architecture.lock"),Ot=zt(le,"wx",384);let we;try{const B=jt(ye);if(!B.isFile()||B.isSymbolicLink())throw new Error("architecture-root-state-binding-invalid");const je=We(ye,"utf8");if(Pe("sha256").update(je).digest("hex")!==e.sourceStateSha256)throw new Error("architecture-root-state-conflict");const z=JSON.parse(je),ge=h(z)&&h(z.archPlan)?z.archPlan:{};if(!h(z)||!h(z.epics)||!Object.hasOwn(z.epics,i.targetEpicId)||(e.initialBinding?ge.execution!==void 0||n.graphSource!=="committed-epic-v1":!v(yn(ge.execution),n))||h(z.scope)&&z.scope.kind==="projected")throw new Error("architecture-root-state-binding-invalid");if(n.graphSource==="committed-epic-v1"&&n.graphRevision!==Yt(e.projectRoot,String(n.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");if(tt||ut==="complete-replay"){const Nt={...n,continuationState:"delegate",acceptedStages:n.acceptedStages.slice(0,fr(n))};if(!v(n.terminalMemoryCheckpoint,kn(e.projectRoot,Nt)))throw new Error("architecture-root-state-conflict");return}const Ve=sn(),ne=Ge("git",["rev-parse","--git-common-dir"],{cwd:e.projectRoot,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),wt=Yi(ne)?Nn(ne):Nn(e.projectRoot,ne);if(Fi(wt)!==wt)throw new Error("architecture-root-backup-dir-invalid");const qe=Q(wt,"neocortex-architecture");qt(qe,{recursive:!0,mode:448});const Ie=jt(qe);if(!Ie.isDirectory()||Ie.isSymbolicLink()||Ie.uid!==process.getuid?.()||(Ie.mode&63)!==0)throw new Error("architecture-root-backup-dir-invalid");const J=Q(qe,`state-backup-${Ve}.json`),Wt=zt(J,"wx",384);try{dn(Wt,je),pn(Wt)}finally{Jt(Wt)}const ht=zt(qe,"r");try{pn(ht)}finally{Jt(ht)}const O={...z,archPlan:{...ge,execution:i}};we=Q(X,`state.json.architecture-tmp-${Ve}`);const gt=zt(we,"wx",384);try{dn(gt,`${JSON.stringify(O,null,2)}
8
- `),pn(gt)}finally{Jt(gt)}if((se||ut==="complete")&&!v(n.terminalMemoryCheckpoint,kn(e.projectRoot,n)))throw new Error("architecture-root-state-conflict");if(n.graphSource==="committed-epic-v1"&&n.graphRevision!==Yt(e.projectRoot,String(n.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");Ir(we,ye),we=void 0;const f=zt(X,"r");try{pn(f)}finally{Jt(f)}}finally{if(we)try{On(we)}catch{}Jt(Ot),On(le)}}function In(e,t){if(!h(e))return;const i={};for(const r of t){const a=e[r];if(typeof a=="boolean")i[r]=a;else if(typeof a=="number"&&Number.isFinite(a))i[r]=a;else if(typeof a=="string"){const n=te(a);n&&(i[r]=n)}}return Object.keys(i).length>0?i:void 0}function En(e){return e==="epic"||e==="story"?e:void 0}function ti(e){if(!h(e)||e.schemaVersion!==1)return;const t=K(e.ownerStoryId),i=K(e.sessionId),r=K(e.idempotencyKey),a=Oe(e.acquiredAt),n=Oe(e.expiresAt);if(!(!t||!i||!r||!a||!n||Date.parse(n)<=Date.parse(a)))return{schemaVersion:1,ownerStoryId:t,sessionId:i,idempotencyKey:r,acquiredAt:a,expiresAt:n}}function ni(e){if(!h(e)||e.schemaVersion!==1)return;const t=K(e.storyId),i=K(e.epicId),r=ve(e.branch),a=w(e.baseSha),n=w(e.headSha),o=K(e.idempotencyKey),p=Oe(e.recordedAt),s=Se(e.commits).map(w).filter(D=>!!D).slice(0,256),l=Se(e.receiptRefs).map(ct).filter(D=>!!D).slice(0,256),I=e.dispatchId===void 0?void 0:K(e.dispatchId),S=e.bundleId===void 0?void 0:K(e.bundleId),u=e.bundleDigest===void 0?void 0:w(e.bundleDigest),_=e.graphRevision===void 0?void 0:w(e.graphRevision),E=e.claimRevision===void 0?void 0:K(e.claimRevision),g=Go(e.qaReceipt),y=Wo(e.reviewReceipt),x=e.rootMemoryEffect===void 0?void 0:oo(e.rootMemoryEffect)?e.rootMemoryEffect:void 0;if(!(!t||!i||!t.startsWith(`${i}.`)||!r||!a||!n||a===n||!o||!p||s.length===0||l.length===0||!Array.isArray(e.commits)||s.length!==e.commits.length||e.commits.length>256||!Array.isArray(e.receiptRefs)||l.length!==e.receiptRefs.length||e.receiptRefs.length>256||e.dispatchId!==void 0&&!I||e.bundleId!==void 0&&!S||e.bundleDigest!==void 0&&(!u||u.length!==64)||e.graphRevision!==void 0&&(!_||_.length!==64)||e.claimRevision!==void 0&&!E||e.rootMemoryEffect!==void 0&&(!x||x.storyId!==t||x.epicId!==i||x.executionBranch!==r||x.sourceHeadSha!==a||x.childClaimRevision!==E)||e.qaVerdict!=="passed"&&e.qaVerdict!=="blocked"||!["approved","changes-requested","pending"].includes(String(e.reviewVerdict))||!g||e.reviewVerdict!=="pending"&&!y||e.reviewVerdict==="pending"&&y||g.verdict!==e.qaVerdict||y&&y.verdict!==e.reviewVerdict||!ai(g,{storyId:t,epicId:i,baseSha:a,headSha:n,bundleDigest:u,graphRevision:_})||y&&(!ai(y,{storyId:t,epicId:i,baseSha:a,headSha:n,bundleDigest:u,graphRevision:_})||y.qaReceiptRef!==g?.receiptRef||y.receiptRef===g?.receiptRef)||!l.includes(String(g.receiptRef))||y&&(!l.includes(String(y.receiptRef))||Date.parse(String(y.reviewedAt))<Date.parse(String(g.checkedAt)))))return{schemaVersion:1,storyId:t,epicId:i,branch:r,baseSha:a,headSha:n,idempotencyKey:o,...I?{dispatchId:I}:{},...S?{bundleId:S}:{},...u?{bundleDigest:u}:{},..._?{graphRevision:_}:{},...E?{claimRevision:E}:{},...x?{rootMemoryEffect:structuredClone(x)}:{},qaVerdict:e.qaVerdict,reviewVerdict:e.reviewVerdict,...g?{qaReceipt:g}:{},...y?{reviewReceipt:y}:{},recordedAt:p,commits:s,receiptRefs:l}}function Go(e){if(!h(e)||e.schemaVersion!==1||e.kind!=="story_qa_evidence"||e.producer!=="local-yolo-tdd"||e.evidenceVersion!==void 0&&e.evidenceVersion!=="git-immutable-v1"&&e.evidenceVersion!=="p205-execution-v2"||!["passed","blocked"].includes(String(e.verdict)))return;const t=K(e.storyId),i=K(e.epicId),r=w(e.baseSha),a=w(e.headSha),n=w(e.bundleDigest),o=w(e.graphRevision),p=w(e.sourceEvidenceDigest),s=Oe(e.checkedAt),l=ct(e.receiptRef),I=e.evidenceVersion==="p205-execution-v2"&&e.contract==="P205-CI-02"?e.contract:void 0,S=e.evidenceVersion==="p205-execution-v2"&&e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,u=e.evidenceVersion==="p205-execution-v2"?w(e.manifestDigest):void 0,_=e.evidenceVersion==="p205-execution-v2"?w(e.resultDigest):void 0,E=e.evidenceVersion==="p205-execution-v2"?Se(e.gateIds).map(K).filter(g=>!!g).slice(0,64):void 0;if(!(!t||!i||!r||!a||!n||n.length!==64||!o||o.length!==64||!p||p.length!==64||!s||!l||e.evidenceVersion==="p205-execution-v2"&&(!I||S!=="node scripts/test-root.mjs --gate complete"||!u||u.length!==64||!_||_.length!==64||!Array.isArray(e.gateIds)||!E||E.length===0||E.length!==e.gateIds.length)))return{schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",...e.evidenceVersion?{evidenceVersion:e.evidenceVersion}:{},storyId:t,epicId:i,...e.evidenceVersion==="p205-execution-v2"?{contract:I,command:S,manifestDigest:u,gateIds:E,resultDigest:_}:{},baseSha:r,headSha:a,bundleDigest:n,graphRevision:o,sourceEvidenceDigest:p,verdict:e.verdict,checkedAt:s,receiptRef:l}}function ri(e){if(!h(e)||e.schemaVersion!==1||e.kind!=="story_checkpoint_physical_verification"||e.producer!=="client-p205-transient-v1"||e.publicSafe!==!0||e.verdict!=="verified"&&e.verdict!=="rejected")return;const t=K(e.storyId),i=K(e.epicId),r=ve(e.branch),a=w(e.baseSha),n=w(e.headSha),o=w(e.aggregateHeadSha),p=w(e.commitBodyDigest),s=w(e.changedPathsDigest),l=e.claimVerification==="canonical"||e.claimVerification==="legacy-migration"?e.claimVerification:void 0,I=w(e.effectiveClaimRevision),S=e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,u=w(e.manifestDigest),_=Se(e.gateIds).map(K).filter(P=>!!P).slice(0,64),E=w(e.resultDigest),g=w(e.graphRevision),y=w(e.executionEvidenceDigest),x=w(e.sourceEvidenceDigest),D=Oe(e.verifiedAt),T=Se(e.reasonCodes).map(K).filter(P=>!!P).slice(0,16);if(!(!t||!i||!r||!a||a.length<40||!n||n.length<40||!o||o.length<40||!p||p.length!==64||!s||s.length!==64||!l||!I||I.length!==64||!S||!u||u.length!==64||!Array.isArray(e.gateIds)||_.length!==e.gateIds.length||!E||E.length!==64||!g||g.length!==64||!y||y.length!==64||!x||x.length!==64||!D||T.length===0||e.verdict==="verified"&&(_.length===0||!T.includes("checkpoint-p205-transient-verified"))))return{schemaVersion:1,kind:"story_checkpoint_physical_verification",producer:"client-p205-transient-v1",storyId:t,epicId:i,branch:r,baseSha:a,headSha:n,aggregateHeadSha:o,commitBodyDigest:p,changedPathsDigest:s,claimVerification:l,effectiveClaimRevision:I,command:S,manifestDigest:u,gateIds:_,resultDigest:E,graphRevision:g,executionEvidenceDigest:y,sourceEvidenceDigest:x,verifiedAt:D,verdict:e.verdict,reasonCodes:T,publicSafe:!0}}function ii(e){const t=["schemaVersion","kind","producer","storyId","epicId","branch","baseSha","headSha","graphRevision","effectiveClaimRevision","sourceEvidenceDigest","verifiedAt","reasonCodes","integrationAuthorized","publicSafe"];if(!h(e)||Object.keys(e).some(u=>!t.includes(u))||e.schemaVersion!==1||e.kind!=="story_scheduling_checkpoint_evidence"||e.producer!=="client-git-physical-v1"||e.integrationAuthorized!==!1||e.publicSafe!==!0)return;const i=K(e.storyId),r=K(e.epicId),a=ve(e.branch),n=w(e.baseSha),o=w(e.headSha),p=w(e.graphRevision),s=w(e.effectiveClaimRevision),l=w(e.sourceEvidenceDigest),I=Oe(e.verifiedAt),S=Se(e.reasonCodes).map(K).filter(u=>!!u);if(!(!i||!r||!a||!n||n.length<40||!o||o.length<40||!p||p.length!==64||!s||s.length!==64||!l||l.length!==64||!I||!Array.isArray(e.reasonCodes)||S.length!==1||S[0]!=="checkpoint-git-scheduling-verified"))return{schemaVersion:1,kind:"story_scheduling_checkpoint_evidence",producer:"client-git-physical-v1",storyId:i,epicId:r,branch:a,baseSha:n,headSha:o,graphRevision:p,effectiveClaimRevision:s,sourceEvidenceDigest:l,verifiedAt:I,reasonCodes:S,integrationAuthorized:!1,publicSafe:!0}}function Wo(e){if(!h(e)||e.schemaVersion!==1||e.kind!=="story_review_evidence"||e.producer!=="root-commit-range-review"||!["approved","changes-requested"].includes(String(e.verdict)))return;const t=K(e.storyId),i=K(e.epicId),r=w(e.baseSha),a=w(e.headSha),n=w(e.bundleDigest),o=w(e.graphRevision),p=w(e.sourceEvidenceDigest),s=ct(e.qaReceiptRef),l=Oe(e.reviewedAt),I=ct(e.receiptRef);if(!(!t||!i||!r||!a||!n||n.length!==64||!o||o.length!==64||!p||p.length!==64||!s||!l||!I))return{schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:t,epicId:i,baseSha:r,headSha:a,bundleDigest:n,graphRevision:o,sourceEvidenceDigest:p,qaReceiptRef:s,verdict:e.verdict,reviewedAt:l,receiptRef:I}}function ai(e,t){return["storyId","epicId","baseSha","headSha","bundleDigest","graphRevision"].every(i=>e[i]===t[i])}function oi(e){if(!h(e)||e.schemaVersion!==1||e.capturedFromCurrentCheckout!==!0)return;const t=ve(e.originBranch),i=w(e.originHeadSha),r=ve(e.executionBranch),a=Oe(e.capturedAt);if(!(!t||!i||i.length<40||!r||!a||t===r))return{schemaVersion:1,originBranch:t,originHeadSha:i,executionBranch:r,capturedFromCurrentCheckout:!0,capturedAt:a}}function ci(e){if(!h(e)||e.schemaVersion!==1||e.verdict!=="passed")return;const t=w(e.executionHeadSha),i=w(e.graphRevision),r=Oe(e.checkedAt),a=ct(e.receiptRef),n=Se(e.gateIds).map(K).filter(I=>!!I).slice(0,128),o=e.evidenceVersion==="p205-execution-v2"&&e.producer==="local-yolo-tdd"&&e.contract==="P205-CI-02"&&e.command==="node scripts/test-root.mjs --gate complete",p=e.evidenceVersion===void 0&&e.producer===void 0&&e.contract===void 0&&e.command===void 0&&e.manifestDigest===void 0&&e.resultDigest===void 0,s=o?w(e.manifestDigest):void 0,l=o?w(e.resultDigest):void 0;if(!(!t||t.length<40||!i||i.length!==64||!r||!a||n.length===0||!Array.isArray(e.gateIds)||n.length!==e.gateIds.length||e.gateIds.length>128||!p&&!o||o&&(!s||s.length!==64||!l||l.length!==64)))return{schemaVersion:1,...o?{evidenceVersion:"p205-execution-v2",producer:"local-yolo-tdd",contract:"P205-CI-02",command:"node scripts/test-root.mjs --gate complete",manifestDigest:s,resultDigest:l}:{},verdict:"passed",executionHeadSha:t,graphRevision:i,checkedAt:r,receiptRef:a,gateIds:n}}function si(e){if(!h(e)||e.schemaVersion!==1||e.kind!=="epic_head_reconciliation"||e.producer!=="client-p205-head-reconciliation-v1"||e.publicSafe!==!0)return;const t={schemaVersion:1,kind:"epic_head_reconciliation",producer:"client-p205-head-reconciliation-v1",epicId:K(e.epicId),executionBranch:ve(e.executionBranch),originBranch:ve(e.originBranch),graphRevision:w(e.graphRevision),originHeadSha:w(e.originHeadSha),lastAcceptedCheckpointHeadSha:w(e.lastAcceptedCheckpointHeadSha),executionHeadSha:w(e.executionHeadSha),acceptedCheckpointIds:Se(e.acceptedCheckpointIds),acceptedCheckpointHeads:Se(e.acceptedCheckpointHeads),reconciliationCommitShas:Se(e.reconciliationCommitShas),commitRangeDigest:w(e.commitRangeDigest),changedPaths:Se(e.changedPaths),changedPathsDigest:w(e.changedPathsDigest),allowedWriteSet:Se(e.allowedWriteSet),allowedWriteSetDigest:w(e.allowedWriteSetDigest),aggregateReceiptRef:ct(e.aggregateReceiptRef),aggregateManifestDigest:w(e.aggregateManifestDigest),aggregateResultDigest:w(e.aggregateResultDigest),producedAt:Oe(e.producedAt),revalidatedAt:Oe(e.revalidatedAt),publicSafe:!0};if(!t.epicId||!t.executionBranch||!t.originBranch||!t.graphRevision||t.graphRevision.length!==64||!t.originHeadSha||t.originHeadSha.length<40||!t.lastAcceptedCheckpointHeadSha||t.lastAcceptedCheckpointHeadSha.length<40||!t.executionHeadSha||t.executionHeadSha.length<40||t.acceptedCheckpointIds.length===0||t.acceptedCheckpointIds.length>2048||t.acceptedCheckpointIds.length!==t.acceptedCheckpointHeads.length||t.acceptedCheckpointHeads.some(a=>!/^[a-f0-9]{40,64}$/i.test(a))||t.reconciliationCommitShas.length>2048||t.reconciliationCommitShas.some(a=>!/^[a-f0-9]{40,64}$/i.test(a))||t.changedPaths.length>2048||(t.lastAcceptedCheckpointHeadSha===t.executionHeadSha?t.reconciliationCommitShas.length!==0||t.changedPaths.length!==0:t.reconciliationCommitShas.length===0||t.changedPaths.length===0)||t.allowedWriteSet.length===0||t.allowedWriteSet.length>2048||!t.commitRangeDigest||!t.changedPathsDigest||!t.allowedWriteSetDigest||!t.aggregateReceiptRef||!t.aggregateManifestDigest||!t.aggregateResultDigest||!t.producedAt||!t.revalidatedAt||t.commitRangeDigest!==Ka(t.lastAcceptedCheckpointHeadSha,t.executionHeadSha,t.reconciliationCommitShas)||t.changedPathsDigest!==Mr(t.changedPaths)||t.allowedWriteSetDigest!==Mr(t.allowedWriteSet))return;const i=t,r=w(e.inputDigest);if(!(!r||r.length!==64||r!==Ja(i)))return{...i,inputDigest:r}}function zn(e){if(!h(e)||e.schemaVersion!==1)return;const t=In(e,["schemaVersion","kind","storyId","epicId","baseSha","headSha","originalBaseSha","originalHeadSha","gitPullRequest","preservesLaterCommits","historyRewrite","recordedAt"])??{},i=Se(e.receiptRefs).map(ct).filter(a=>!!a).slice(0,256),r=Se(e.revertCommits).map(te).filter(a=>!!a).slice(0,256);return{...t,...i.length?{receiptRefs:i}:{},...r.length?{revertCommits:r}:{}}}function Fo(e){if(!(!h(e)||Object.keys(e).sort().join(",")!=="gitPullRequest,headSha,kind,prNumber,reviewEvidenceDigest,schemaVersion"||e.schemaVersion!==1||e.kind!=="git-pull-request"||e.gitPullRequest!==!0||!Number.isSafeInteger(e.prNumber)||Number(e.prNumber)<=0||typeof e.headSha!="string"||!/^[a-f0-9]{40}$/.test(e.headSha)||typeof e.reviewEvidenceDigest!="string"||!/^[a-f0-9]{64}$/.test(e.reviewEvidenceDigest)))return{schemaVersion:1,kind:"git-pull-request",gitPullRequest:!0,prNumber:e.prNumber,headSha:e.headSha,reviewEvidenceDigest:e.reviewEvidenceDigest}}function di(e){if(!h(e)||e.schemaVersion!==1||e.publicSafe!==!0)return;const t=K(e.epicId),i=ve(e.executionBranch),r=ve(e.originBranch),a=w(e.baseSha),n=w(e.executionHeadSha),o=e.mergeSha===void 0?void 0:w(e.mergeSha),p=e.pushedSha===void 0?void 0:w(e.pushedSha),s=K(e.idempotencyKey),l=Oe(e.attemptStartedAt),I=e.completedAt===void 0?void 0:Oe(e.completedAt),S=Se(e.localGateReceiptRefs).map(ct).filter(g=>!!g).slice(0,256),u=Se(e.reasonCodes).map(K).filter(g=>!!g).slice(0,64),_=qo(e.candidateQa),E=Yo(e.providerGuard);if(!(!t||!i||!r||!a||!n||!s||!l||S.length===0||u.length===0||!["direct","single_pr"].includes(String(e.strategy))||!["prepared","merged","pushed","denied_external_gate","blocked_local_or_repo"].includes(String(e.physicalStatus))||typeof e.retryEligible!="boolean"||e.providerGuard!==void 0&&!E||E&&(e.strategy!=="single_pr"||e.physicalStatus!=="pushed"||E.prHeadSha!==o||E.originHeadSha!==a)))return{schemaVersion:1,epicId:t,executionBranch:i,originBranch:r,baseSha:a,executionHeadSha:n,...o?{mergeSha:o}:{},...p?{pushedSha:p}:{},strategy:e.strategy,...vt(e.prNumber)?{prNumber:vt(e.prNumber)}:{},physicalStatus:e.physicalStatus,localGateReceiptRefs:S,idempotencyKey:s,attemptStartedAt:l,..._?{candidateQa:_}:{},...E?{providerGuard:E}:{},...I?{completedAt:I}:{},retryEligible:e.retryEligible,reasonCodes:u,publicSafe:!0}}function Yo(e){if(!h(e)||e.schemaVersion!==1||e.provider!=="github"||e.publicSafe!==!0)return;const t=String(e.mode),i=String(e.source),r=t==="recovered_exact_tree"?i==="physical_recovery":t==="strict_up_to_date_expected_head"&&["branch_protection","ruleset","branch_protection_and_ruleset"].includes(i),a=w(e.prHeadSha),n=w(e.originHeadSha),o=Oe(e.checkedAt);if(!(!r||!a||!n||!o))return{schemaVersion:1,provider:"github",mode:t,source:i,prHeadSha:a,originHeadSha:n,checkedAt:o,publicSafe:!0}}function qo(e){if(!h(e)||e.schemaVersion!==1||e.kind!=="epic_merge_candidate_qa"||e.contract!=="P205-CI-02"||e.command!==Xt)return;const i=Object.fromEntries(["originHeadSha","executionHeadSha","mergeSha","treeSha","graphRevision","manifestDigest","resultDigest"].map(o=>[o,w(e[o])])),r=Oe(e.checkedAt),a=ct(e.receiptRef),n=Se(e.gateIds).filter(o=>/^[a-z0-9-]+$/.test(o)).slice(0,128);if(!(Object.values(i).some(o=>!o)||!r||!a||n.length===0))return{schemaVersion:1,kind:e.kind,contract:e.contract,command:e.command,...i,checkedAt:r,receiptRef:a,gateIds:n}}function zo(e){if(!h(e))return;const t={...te(e.active_epic_id??e.activeEpicId)?{active_epic_id:te(e.active_epic_id??e.activeEpicId)}:{},...te(e.active_story_id??e.activeStoryId)?{active_story_id:te(e.active_story_id??e.activeStoryId)}:{},...te(e.active_step_id??e.activeStepId)?{active_step_id:te(e.active_step_id??e.activeStepId)}:{},...te(e.session_id??e.sessionId)?{session_id:te(e.session_id??e.sessionId)}:{},...te(e.started_at??e.startedAt)?{started_at:te(e.started_at??e.startedAt)}:{}};return Object.keys(t).length>0?t:void 0}function Jo(e){const t=In(e.completionEvidence??e.completion_evidence,["prNumber","pr_number","prState","pr_state","pullRequestState","merged","mergedAt","issueNumber","issue_number","issueState","issue_state","closedAt"]),i=In(e.issueCloseAudit??e.issue_close_audit,["schema_version","event","storyId","epicId","issueNumber","closedAt","publicSafe","rawLogStorage"]),r=In(e.scopedCiEvidence??e.scoped_ci_evidence,["schema_version","storyId","epicId","prNumber","finalState","publicSafe","rawLogStorage"]);return{...typeof e.merged=="boolean"?{merged:e.merged}:{},...typeof e.safeToContinueYoloop=="boolean"?{safeToContinueYoloop:e.safeToContinueYoloop}:{},...typeof e.mergeBlockedRemotely=="boolean"?{mergeBlockedRemotely:e.mergeBlockedRemotely}:{},...te(e.physicalMergeStatus)?{physicalMergeStatus:te(e.physicalMergeStatus)}:{},...te(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)?{pr_state:te(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)}:{},...te(e.issue_state??e.issueState??e.workflow_issue_state)?{issue_state:te(e.issue_state??e.issueState??e.workflow_issue_state)}:{},...vt(e.issue_number??e.issueNumber)?{issue_number:vt(e.issue_number??e.issueNumber)}:{},...t?{completionEvidence:t}:{},...i?{issueCloseAudit:i}:{},...r?{scopedCiEvidence:r}:{}}}class st extends Error{reasonCode;constructor(t){super(t),this.name="StateSnapshotIntegrityError",this.reasonCode=t}}const Ko=new Set(["yolo","yoloop","finalize-epic","audit"]);function pi(e){return typeof e=="string"&&Ko.has(e)}function Jn(e,t={}){const i=Q(e,".neocortex","state.json");if(!Mt(i))throw new st("git-lifecycle-state-missing");let r;try{r=JSON.parse(We(i,"utf8"))}catch{throw new st("git-lifecycle-state-corrupt")}if(!h(r)||!h(r.epics)||!h(r.stories))throw new st("git-lifecycle-state-shape-invalid");const a=Object.values(r.epics).some(n=>h(n)&&(n.branch_mode==="epic"||ve(n.execution_branch)!==void 0));if(a)try{hn(e,{required:!0})}catch(n){const o=n instanceof Error&&/^git-lifecycle-/.test(n.message)?n.message:"git-lifecycle-runtime-invalid";if(t.allowMissingRuntime&&o==="git-lifecycle-runtime-missing")return{lifecycleDeclared:!0,runtimeMissing:!0};throw new st(o)}return{lifecycleDeclared:a,runtimeMissing:!1}}function Sn(e,t={}){const i=Q(e,".neocortex","state.json");if(!Mt(i)){if(t.epicAware&&!t.projectless)throw new st("git-lifecycle-state-missing");return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}let r,a;try{const E=We(i,"utf-8");a=Pe("sha256").update(E).digest("hex");const g=JSON.parse(E),y=h(g.epics)?g.epics:{},x=Object.values(y).some(R=>h(R)&&(R.branch_mode==="epic"||ve(R.execution_branch)!==void 0)),D=hn(e,{required:!!(t.epicAware&&x&&!t.projectless)});r=jr(g,D);const T=h(r.stories)?r.stories:{},P=h(r.epics)?r.epics:{},C=h(g.stories)?g.stories:{};for(const[R,M]of Object.entries(T)){const N=h(M)?M:void 0;if(!N?.checkpoint)continue;const q=typeof N.epic_id=="string"?N.epic_id:R.split(".")[0],Z=h(P[q])?P[q]:void 0,j=ve(Z?.execution_branch);if(!j)continue;const V=Qa(e,N.checkpoint,R,q,j,t.p205Authorities?.[R],Vr(R,N,h(N.checkpoint)?N.checkpoint:void 0));if(V.kind==="integration-authorized")N.checkpoint_verification=V.verification,delete N.scheduling_checkpoint_evidence;else if(V.kind==="scheduling-only")N.scheduling_checkpoint_evidence=V.evidence,delete N.checkpoint,delete N.checkpoint_verification;else if(V.kind==="rejected"){N.checkpoint_verification=V.verification,delete N.scheduling_checkpoint_evidence;const ee=h(C[R])?C[R]:void 0;if(delete N.checkpoint,D.stories[R]?.checkpoint!==void 0)for(const H of["status","last_step","steps_completed"])ee&&Object.prototype.hasOwnProperty.call(ee,H)?N[H]=structuredClone(ee[H]):delete N[H];["done","completed","merged"].includes(String(N.status).toLowerCase())&&(N.status="blocked")}}}catch(E){if(t.epicAware&&!t.projectless){const g=E instanceof Error&&/^git-lifecycle-/.test(E.message)?E.message:"git-lifecycle-state-corrupt";throw new st(g)}return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}try{const E=Do(r);E.length>0&&Mo(E)}catch{}const n=r.config??r.project??{},o=r.stories??{},p={};for(const[E,g]of Object.entries(o)){const y=h(g.review_request)&&g.review_request.kind==="git-pull-request"?Fo(g.review_request):zn(g.review_request);p[E]={id:g.id??E,title:g.title,epic_id:g.epic_id,status:g.status??"backlog",...ei(g.source)?{source:ei(g.source)}:{},steps_completed:g.steps_completed??[],last_step:g.last_step??null,branch_name:g.branch_name??null,pr_number:g.pr_number,...En(g.branch_mode)?{branch_mode:En(g.branch_mode)}:{},...ni(g.checkpoint)?{checkpoint:ni(g.checkpoint)}:{},...ri(g.checkpoint_verification)?{checkpoint_verification:ri(g.checkpoint_verification)}:{},...ii(g.scheduling_checkpoint_evidence)?{scheduling_checkpoint_evidence:ii(g.scheduling_checkpoint_evidence)}:{},...y?{review_request:y}:{},...zn(g.rollback_receipt)?{rollback_receipt:zn(g.rollback_receipt)}:{},...vt(g.workflow_issue)?{workflow_issue:vt(g.workflow_issue)}:{},...Jo(g),depends_on:Zr(g.depends_on),files_to_modify:Se(g.files_to_modify),...$o(g),risk:typeof g.risk=="string"?g.risk:void 0,blast_radius:typeof g.blast_radius=="number"?g.blast_radius:void 0}}const s=r.epics??{},l={};for(const[E,g]of Object.entries(s)){const y=jo(g.lifecycle_classification),x=Uo(g.createEpicPlanning,E),D=x.checkpoint;let T,P,C,R;if(D&&h(g.createEpicPlanningClaim)&&typeof g.createEpicPlanningClaim.claimId=="string"&&h(g.createEpicPlanningPhysical))try{Er(r,g.createEpicPlanningClaim.claimId,E,!0),T=JSON.parse(JSON.stringify(g.createEpicPlanningPhysical))}catch{}if(T&&h(g.createEpicPlanningClaim)&&typeof g.createEpicPlanningClaim.claimId=="string"&&h(g.createEpicPlanningResearchPhysical))try{Sr(r,g.createEpicPlanningClaim.claimId,E),P=JSON.parse(JSON.stringify(g.createEpicPlanningResearchPhysical))}catch{}if(t.verifyPlanningGeneration&&D&&g.status==="generated"&&h(g.createEpicPlanningClaim)&&typeof g.createEpicPlanningClaim.claimId=="string"&&h(g.createEpicPlanningGenerationPhysical))try{if(Ki(e,g.createEpicPlanningClaim.claimId,E).stateSha256!==a)throw new Error("planning-generation-snapshot-raced");C=JSON.parse(JSON.stringify(g.createEpicPlanningGenerationPhysical)),T=JSON.parse(JSON.stringify(g.createEpicPlanningPhysical)),P=JSON.parse(JSON.stringify(g.createEpicPlanningResearchPhysical))}catch{}if(C&&h(g.createEpicPlanningClaim)&&typeof g.createEpicPlanningClaim.claimId=="string")try{const M=vr(e,g.createEpicPlanningClaim.claimId,E);if(M.stateSha256!==a)throw new Error("planning-memory-snapshot-raced");R=JSON.parse(JSON.stringify(M))}catch{}l[E]={id:g.id??E,title:g.title,...D?{createEpicPlanning:D}:{},...x.diagnostic?{createEpicPlanningProjection:x.diagnostic}:{},...T?{createEpicPlanningPhysical:T}:{},...P?{createEpicPlanningResearchPhysical:P}:{},...C?{createEpicPlanningGenerationPhysical:C}:{},...R?{createEpicPlanningMemoryPhysical:R}:{},status:g.status,stories:g.stories,total_stories:g.total_stories,completed_stories:g.completed_stories,depends_on:Zr(g.depends_on),...En(g.branch_mode)?{branch_mode:En(g.branch_mode)}:{},...ve(g.execution_branch)?{execution_branch:ve(g.execution_branch)}:{},...ve(g.origin_branch)?{origin_branch:ve(g.origin_branch)}:{},...ti(g.branch_lease)?{branch_lease:ti(g.branch_lease)}:{},...oi(g.origin_binding)?{origin_binding:oi(g.origin_binding)}:{},...ci(g.aggregate_qa_receipt)?{aggregate_qa_receipt:ci(g.aggregate_qa_receipt)}:{},...si(g.head_reconciliation_receipt)?{head_reconciliation_receipt:si(g.head_reconciliation_receipt)}:{},...vt(g.pr_number)?{pr_number:vt(g.pr_number)}:{},...te(g.physicalMergeStatus)?{physicalMergeStatus:te(g.physicalMergeStatus)}:{},...w(g.graph_revision)?{graph_revision:w(g.graph_revision)}:{},...di(g.terminal_git_receipt)?{terminal_git_receipt:di(g.terminal_git_receipt)}:{},...y?{lifecycle_classification:y}:{}}}const I=zo(r.current_session??r.currentSession),S=h(r.archPlan)?yn(r.archPlan.execution):void 0,u=r.epic_id_ledger,_=Array.isArray(u?.reserved_ids)?[...new Set(u.reserved_ids.filter(E=>typeof E=="string"&&/^P\d+$/.test(E)))].slice(0,2048):[];return{schema_version:typeof r.schema_version=="number"?r.schema_version:void 0,config:{project_name:n.project_name??n.name??"unknown",default_branch:n.default_branch??"main",language:n.language??"pt-BR",yolo_mode:n.yolo_mode,user_name:n.user_name,worktree_base:n.worktree_base,max_parallel_stories:n.max_parallel_stories,project_id:typeof n.project_id=="string"?n.project_id:void 0},stories:p,epics:l,..._.length>0?{epic_id_ledger:{schema_version:1,reserved_ids:_}}:{},...I?{current_session:I}:{},...S?{archPlan:{execution:S}}:{}}}const Kn=[["P222.01","fbc3176b33687b13a8fadf8c7ea7cc06b6b6c500"],["P222.02","c7d3feb9a168f9e15b35516a972c767f3aa357da"],["P222.03","4d9bd4f2a1a3a1dc6399c572eb84b8b74c017806"],["P222.04","66590ef2f706c9d036f42edf5e517b237724f74f"],["P222.05","3ee2662538311e9788796340ed11b65864a8d8d5"],["P222.06","8660d07e3f68503a9ceb24dc138d24f62ab6cb45"],["P222.07","d99c80feacee8ea4033aa3322990147fffa2df91"],["P222.08","1f9e37dc922d87908efefb9595db32d32db30b00"],["P222.09","5ae12e485900992658e346cf3e38568fda1c2eeb"],["P222.10","6c5b8dc4f03d629fea4b62a33f4794af8e27e4f0"],["P222.11","cfe90f2f955c0027c57e4c621141d17912db65cc"],["P222.12","65f253c5cb600a8ee1dd94a1efdfef2fa5cd1629"],["P222.13","1e78c75b393515803a55d1a9b63a7fec23f710c9"],["P222.14","3f3e0bfd247a8581170df2a23c89497b5ae3641e"],["P222.15","1fd6dd25fffa5714d4ffa8b4303735e417f93de6"]],Qn="6a41a47ff2521f80c2296ed811b0f0b304c54750",Xn="dbc6d4670b2b7868a01973b1240e24589f1c5b7d",li="30dccfff07f9c969be11ae1d28e62a09731a0768";function Qo(e,t){try{const i=t.indexOf(li);if(i<1||t[i-1]!==Qn)return new Map;const r=Ge("git",["show","--no-patch","--format=%P",li],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim(),a=Ge("git",["show","--no-patch","--format=%P",Xn],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim();if(r!==`${Qn} ${Xn}`||a!==`${Kn.at(-1)[1]} ${Qn}`)return new Map;const n=Ge("git",["rev-list","--first-parent","--reverse",Xn],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
9
- `),o=new Map;let p=-1;for(const[s,[l,I]]of Kn.entries()){const S=n.indexOf(I);if(S<=p)return new Map;p=S,o.set(l,{headSha:I,position:s-Kn.length})}return o}catch{return new Map}}async function Xo(e,t,i){if(!pi(i))return{};if(i==="audit"||i==="yoloop")return{};if(xr(t,i))return{};try{const r=JSON.parse(We(Q(e,".neocortex","state.json"),"utf8")),a=hn(e,{required:!0}),n=jr(r,a),o=h(n.stories)?n.stories:{},p=h(n.epics)?n.epics:{},s=Ge("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8"}).trim(),l=Ge("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8"}).trim(),I=Ge("git",["rev-list","--first-parent","--reverse",s],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
10
- `).filter(Boolean),S=new Map(I.map((C,R)=>[C,R])),u=Qo(e,I),_=t.match(/(?:^|\s)@?docs\/stories\/([A-Za-z][A-Za-z0-9._-]*)\.story\.md(?:\s|$)/)?.[1],E=i==="yoloop"?t.match(/(?:^|[\s/@])epic-(P[1-9][0-9]*)\.md(?:\s|$)/i)?.[1]?.toUpperCase():void 0,g=new Set,y=Object.entries(o).flatMap(([C,R])=>{if(_&&C!==_)return[];const M=h(R)?R:void 0,N=h(M?.checkpoint)?M.checkpoint:void 0;if(!N)return[];const q=typeof M?.epic_id=="string"?M.epic_id:C.split(".")[0];if(E&&q!==E)return[];const Z=w(N?.headSha),j=q==="P222"?u.get(C):void 0,V=S.get(Z??"")??(j&&j.headSha===Z?j.position:void 0);if(!Z||Z.length<40||V===void 0)return g.add(q),[];const ee=h(p[q])?p[q]:void 0;if(ee?.branch_mode!=="epic"||ve(ee.execution_branch)!==l||ve(N.branch)!==l)return g.add(q),[];const H=w(N.graphRevision);if(!H||H.length!==64)return g.add(q),[];const lt=w(N.claimRevision),Ye=[...Vr(C,M,N)].sort(),he=io(e,N,C,q,l,Ye);if(!he&&lt){if(Ye.length===0)return g.add(q),[];const k=Ge("git",["diff-tree","--no-commit-id","--name-only","-r","-z",Z],{cwd:e,encoding:"utf8"}).split("\0").filter(Boolean);let G=[];if(N.rootMemoryEffect!==void 0)try{G=ao(e,N.rootMemoryEffect,{storyId:C,executionBranch:l,baseSha:String(N.baseSha),headRef:Z,childPaths:Ye}).files.map(se=>se.path)}catch{return g.add(q),[]}if(k.length===0||k.some(se=>!Ye.some(tt=>tt===se||tt.endsWith("/")&&se.startsWith(tt))&&!G.includes(se)))return g.add(q),[];const _t=Pe("sha256").update(Ye.join("\0")).digest("hex"),De=Pe("sha256").update(JSON.stringify(Ye)).digest("hex");if(lt!==_t&&lt!==De)return g.add(q),[]}else if(!he)return g.add(q),[];return H?.length===64?[{storyId:C,epicId:q,graphRevision:H,checkpointHead:Z,position:V}]:[]}),x=new Set(g);for(const[C,R]of Object.entries(p)){const M=h(R)?R:void 0,N=Array.isArray(M?.stories)?M.stories.filter(V=>typeof V=="string"):Object.keys(o).filter(V=>V.startsWith(`${C}.`)),q=y.filter(V=>V.epicId===C),Z=N.filter(V=>q.some(ee=>ee.storyId===V)),j=[...q].sort((V,ee)=>V.position-ee.position).map(V=>V.storyId);(JSON.stringify(Z)!==JSON.stringify(j)||new Set(j).size!==j.length)&&x.add(C)}const D={},T=[...new Set(y.filter(C=>!x.has(C.epicId)).map(C=>C.graphRevision))],P=T.length>0?await eo(e,{headSha:s,graphRevisions:T}):new Map;for(const C of y){if(x.has(C.epicId))continue;const R=P.get(C.graphRevision);if(!R)throw new Error("p205-transient-authority-missing");D[C.storyId]=R}return await Zo({projectRoot:e,commandId:i,targetEpicId:E,currentHead:s,epics:p,candidates:y,authorities:D}),D}catch(r){const a=r instanceof Error&&/^(?:p205|git-lifecycle)-[a-z0-9-]+$/.test(r.message)?r.message:"p205-transient-execution-failed";return process.stderr.write(`[Neocortex] ${a}. Checkpoint projection remains fail-closed.
11
- `),{}}}async function Zo(e){if(e.commandId!=="yoloop"||!e.targetEpicId)return;const t=e.epics[e.targetEpicId],i=h(t)?t:void 0,r=h(i?.aggregate_qa_receipt)?i.aggregate_qa_receipt:void 0,a=w(i?.graph_revision);if(!r||!a||a.length!==64||r.schemaVersion!==1||r.evidenceVersion!=="p205-execution-v2"||r.producer!=="local-yolo-tdd"||r.contract!=="P205-CI-02"||r.command!==Xt||r.verdict!=="passed"||r.executionHeadSha!==e.currentHead||r.graphRevision!==a||!Array.isArray(r.gateIds)||r.gateIds.length===0||!r.gateIds.every(S=>typeof S=="string")||typeof r.manifestDigest!="string"||!/^[a-f0-9]{64}$/i.test(r.manifestDigest)||typeof r.resultDigest!="string"||!/^[a-f0-9]{64}$/i.test(r.resultDigest)||typeof r.receiptRef!="string"||!/^local-yolo-tdd:[a-f0-9]{64}$/i.test(r.receiptRef))return;const n=r.gateIds,o=`local-yolo-tdd:${Pe("sha256").update(["epic-aggregate-p205-execution-v2",Xt,e.currentHead,a,r.manifestDigest,n.join(","),r.resultDigest].join("\0")).digest("hex")}`;if(r.receiptRef!==o)return;const p=e.candidates.find(S=>S.epicId===e.targetEpicId&&S.graphRevision===a&&e.authorities[S.storyId]),s=p?ro(e.authorities[p.storyId]):void 0;if(!s||s.executionHeadSha!==e.currentHead||s.graphRevision!==a||s.manifestDigest!==r.manifestDigest||!ec(s.gateIds,n))return;const l=`local-yolo-tdd:${Pe("sha256").update(["epic-aggregate-p205-execution-v2",Xt,e.currentHead,a,s.manifestDigest,s.gateIds.join(","),s.resultDigest].join("\0")).digest("hex")}`,I=r.receiptRef;await no(e.projectRoot,S=>{const u=Xa(S,e.targetEpicId),_=h(u.aggregate_qa_receipt)?u.aggregate_qa_receipt:void 0;!_||_.executionHeadSha!==e.currentHead||_.graphRevision!==a||_.receiptRef!==I||(u.aggregate_qa_receipt={schemaVersion:1,evidenceVersion:"p205-execution-v2",producer:"local-yolo-tdd",contract:"P205-CI-02",command:Xt,verdict:"passed",executionHeadSha:e.currentHead,graphRevision:a,manifestDigest:s.manifestDigest,resultDigest:s.resultDigest,checkedAt:s.executedAt,receiptRef:l,gateIds:[...s.gateIds]})})}function ec(e,t){if(e.length!==t.length)return!1;const i=[...t].sort();return[...e].sort().every((r,a)=>r===i[a])}function Id(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 ui="neocortex:menu:cache";async function tc(e){try{const t=await e.get(ui);if(!t)return null;const i=JSON.parse(t);return i.version!==Tt||Date.now()-i.cachedAt>Hr?null:i}catch{return null}}async function nc(e,t,i){try{const r={instructions:t,metadata:i,cachedAt:Date.now(),version:Tt};await e.set(ui,JSON.stringify(r),Hr),rc()}catch{}}function rc(){try{Mt($r)&&On($r)}catch{}}function hi(e){return e.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>Dn(),()=>Dn({strictReadOnly:!0}))}async function gi(e,t,i){const r=i.mode==="strict";try{let a;if(r&&t)a=new Ln({cacheDir:Bn,passphrase:t,strictReadOnly:!0});else if(r)a=new _r;else if(t){const I=Q(gn,"cache");a=new Ln({cacheDir:I,passphrase:t})}else process.stderr.write(`[neocortex] Warning: No license key in config. Run "neocortex activate" to re-authenticate.
12
- `),a=new _r;const n=Lr(i,a,"auth-cache"),o=Lr(i,a,"tier-cache"),p=new ta({serverUrl:e,licenseKey:t??"",cacheProvider:n,strictReadOnly:r});let s;if(r){const I=await p.inspectToken();if(I.status!=="authenticated")return I;s=I.token}else s=await p.getToken();if(!s)return t?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"};const l=new na({cacheProvider:o,licenseClient:p});return{status:"authenticated",token:s,client:p,tierClient:l}}catch{return t?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"}}}let fi=!1;function ic(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 mi=3,vn=50;function ac(e){return new Promise(t=>setTimeout(t,e))}function oc(e,t,i){return e.status>=500&&e.status<=599?!0:i&&e.status===409&&t.error_code==="SIGNATURE_REPLAYED"}async function Zt(e,t,i,r,a={}){const n=Math.max(1,Math.min(a.maxAttempts??mi,mi)),o=a.sleep??ac;let p=r,s=!1,l=!1,I=0;for(let S=1;S<=n;S+=1){const u=Math.max(Math.floor(Date.now()/1e3),I+1);I=u;const _=cc(t,i,p,{nowSeconds:u}),E=new AbortController,g=setTimeout(()=>E.abort(),Gr);try{const y=await fetch(`${e}${t}`,{method:"POST",headers:_.headers,body:_.body,signal:E.signal});if(a.admitResponseBeforeBodyRead&&!a.admitResponseBeforeBodyRead(y))return{response:y,text:"",parsed:{},networkFailure:!1,responseAdmissionRejected:!0};const x=await y.text().catch(()=>""),D=y.ok&&a.deferSuccessfulJsonParsing?{}:(()=>{try{return x?JSON.parse(x):{}}catch{return{}}})();if(y.status===401&&!s&&a.refreshToken&&(D.fallback_action==="refresh_token"||D.fallback_action==="re_authenticate")){s=!0;const T=await a.refreshToken();if(T&&S<n){p=T,a.onTokenChanged?.(T),await o(vn*S);continue}}if(y.status===401&&D.error_code==="SIGNATURE_EXPIRED"&&!l&&S<n){l=!0,await o(vn*S);continue}if(S<n&&oc(y,D,a.allowReplayRetry===!0)){await o(vn*S);continue}return{response:y,text:x,parsed:D,networkFailure:!1}}catch{if(S<n){await o(vn*S);continue}return{text:"",parsed:{},networkFailure:!0}}finally{clearTimeout(g)}}return{text:"",parsed:{},networkFailure:!0}}function cc(e,t,i,r={}){const a=Buffer.from(JSON.stringify(t),"utf8"),n=wa({method:"POST",target:e,body:a,bearerToken:i,clientVersion:Tt,nowSeconds:r.nowSeconds,nonceBytes:r.nonceBytes});return{body:n.body,headers:{...n.headers,Authorization:`Bearer ${i}`}}}function yi(e){return Pe("sha256").update(e).digest("hex")}function sc(){const e=Number(process.env.NEOCORTEX_INVOKE_CHUNK_BYTES??"49152");return Number.isFinite(e)&&e>=1024&&e<=98304?Math.floor(e):49152}function dc(e,t,i){return`args-${Pe("sha256").update("invoke-materialization:v1").update(e).update(String(t)).update(JSON.stringify(i)).digest("hex")}`}async function Ii(e,t,i,r,a={}){const n=await Zt(e,t,i,r,{...a,allowReplayRetry:!0});if(n.networkFailure||!n.response)throw new Error("NETWORK_ERROR: materialization request failed after bounded retries");const{response:o,parsed:p}=n;if(!o.ok){const s=typeof p.error_code=="string"?p.error_code:`HTTP_${o.status}`,l=typeof p.message=="string"?p.message:"materialization upload failed";throw new Error(`${s}: ${l}`)}return p}async function pc(e,t,i,r){const a=Buffer.from(t,"utf8"),n=sc(),o=[];for(let E=0,g=0;E<a.byteLength;E+=n,g++){const y=a.subarray(E,Math.min(E+n,a.byteLength));o.push({index:g,sha256:yi(y),byteLength:y.byteLength})}const p=yi(a),s=dc(p,a.byteLength,o),l=Number(process.env.NEOCORTEX_INVOKE_CHUNK_TTL_SECONDS??"900");let I=i;const S={refreshToken:r,onTokenChanged(E){I=E}};for(const E of o){const g=E.index*n,y=a.subarray(g,g+E.byteLength);await Ii(e,"/api/v1/invoke/materialization/chunks",{manifestId:s,index:E.index,sha256:E.sha256,byteLength:E.byteLength,contentBase64:y.toString("base64"),ttlSeconds:l,idempotencyKey:`${s}:${E.index}:${E.sha256}`},I,S)}const _=(await Ii(e,"/api/v1/invoke/materialization/manifests",{manifestId:s,sha256:p,byteLength:a.byteLength,chunkCount:o.length,chunks:o,ttlSeconds:l,retry:{attempt:1,budget:3,idempotencyKey:s}},I,S)).argsRef;if(!_?.manifestId)throw new Error("MATERIALIZATION_RESPONSE_INVALID: missing argsRef");return{argsRef:_,chunks:o}}function Ht(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function lc(...e){const t=new Set,i=[];for(const r of e)for(const a of r??[]){const n=te(a);if(!(!n||t.has(n))&&(t.add(n),i.push(n),i.length>=16))return i}return i}function uc(e){const t=e.graphRetrieval;if(!h(t))return{accepted:!1,itemCount:0};const i=Array.isArray(t.items)?t.items.length:0;return{accepted:i>0||typeof t.retrievalId=="string"||t.accepted===!0,itemCount:i}}function Zn(e,t=Ht(e),i=[],r={}){const a=e.stateSnapshot.scope,n=Object.keys(e.stateSnapshot.stories).length,o=Object.keys(e.stateSnapshot.epics).length,p=a?.kind??"full";return{schemaVersion:1,payloadBytes:t,limitBytes:r.limitBytes??Fr,warningThresholdBytes:r.warningThresholdBytes??Un,scope:{kind:p,...a?.projectionMode?{projectionMode:a.projectionMode}:{},commandId:a?.commandId??null,stateProjectionPolicy:a?.stateProjectionPolicy??null},includedStories:a?.includedStoryCount??n,omittedStories:a?.omittedStoryCount??0,includedEpics:a?.includedEpicCount??o,omittedEpics:a?.omittedEpicCount??0,graphRetrieval:uc(e.stateSnapshot),reasonCodes:lc(i,a?.reasonCodes),publicSafe:!0}}function hc(e){const t=h(e.budget)?e.budget:void 0,i=typeof t?.maxPayloadBytes=="number"&&Number.isFinite(t.maxPayloadBytes)?t.maxPayloadBytes:12*1024;return Math.max(1024,Math.min(i,12*1024))}function gc(e){return h(e)?{stableId:te(e.stableId)??"unknown",...h(e.source)?{source:e.source}:{},reasonCode:"budget_exceeded"}:{stableId:"unknown",reasonCode:"budget_exceeded"}}function Ei(e){const t=Array.isArray(e)?e.filter(i=>typeof i=="string"):[];return t.includes("budget_exceeded")?t:[...t,"budget_exceeded"]}function fc(e){const t=e.graphRetrieval;if(!h(t)||!Array.isArray(t.items))return e;const i=hc(t);let r=[...t.items],a=Array.isArray(t.skipped)?[...t.skipped]:[],n=t;for(;Buffer.byteLength(JSON.stringify(n),"utf8")>i&&r.length>0;){const o=r.pop();a=[...a,gc(o)].slice(-32),n={...t,items:r,skipped:a,warnings:Ei(t.warnings)}}return Buffer.byteLength(JSON.stringify(n),"utf8")>i&&(n={...t,query:typeof t.query=="string"?t.query.slice(0,240):t.query,items:[],skipped:[],warnings:Ei(t.warnings)}),n===t?e:{...e,graphRetrieval:n}}function er(e,t={}){const i=t.limitBytes??Fr,r=t.warningThresholdBytes??Math.floor(i*Yr),a=Ht(e);if(a<i)return{body:e,degraded:!1,telemetry:Zn(e,a,["payload-within-limit"],{limitBytes:i,warningThresholdBytes:r})};let n={...e,stateSnapshot:sa(e.stateSnapshot)},o=["payload-size-guardrail","state-degraded"],p=Ht(n);p>=i&&(n={...n,stateSnapshot:fc(n.stateSnapshot)},o=[...o,"graph-retrieval-budget-enforced"],p=Ht(n));const s=Zn(n,p,o,{limitBytes:i,warningThresholdBytes:r});if(p>=i){const l=n.stateSnapshot.scope?.projectionMode;throw l==="yolo-story"||l==="yoloop-target"||l==="yoloop-session"||l==="yoloop-discovery"||l==="structural-required"?new Yn(s):new Fn(s)}return{body:n,degraded:!0,telemetry:s}}function Si(e){const t=e.stateSnapshot.scope?.commandId??"resolved-command";return e.args!==void 0?t:`${t}:argsRef`}function mc(e){const t=Ht(e);if(t<Un)return t;const i=Zn(e,t,["payload-warning-threshold"]);return process.stderr.write(`[Neocortex] invoke payload near server limit: trigger=${Si(e)} scope=${i.scope.kind} mode=${i.scope.projectionMode??i.scope.kind} payloadBytes=${i.payloadBytes} limit=${i.limitBytes} includedStories=${i.includedStories} omittedStories=${i.omittedStories} includedEpics=${i.includedEpics} omittedEpics=${i.omittedEpics} graphRetrieval.accepted=${i.graphRetrieval.accepted} graphRetrieval.itemCount=${i.graphRetrieval.itemCount} reasonCodes=${i.reasonCodes.join(",")||"none"}
13
- `),t}function vi(e,t){process.stderr.write(`[Neocortex] invoke payload guardrail: trigger=${Si(e)} scope.kind=${t.scope.kind} payloadBytes=${t.payloadBytes} limit=${t.limitBytes} includedStories=${t.includedStories} omittedStories=${t.omittedStories} includedEpics=${t.includedEpics} omittedEpics=${t.omittedEpics} graphRetrieval.accepted=${t.graphRetrieval.accepted} graphRetrieval.itemCount=${t.graphRetrieval.itemCount} reasonCodes=${t.reasonCodes.join(",")||"none"}
14
- `)}async function yc(e){const t=fa(e.args,{platformTarget:e.platformTarget,environment:e.environment??process.env});if(t.action==="skipped")return{shouldContinue:!0,attachToRequest:Ic(t),metadata:Ci(t)};const i=e.bootstrapper??ya;let r;try{r=await i({projectRoot:e.projectRoot,env:e.environment??process.env,effectAuthority:e.effectAuthority})}catch{r={ok:!1,attempted:!0,installed:!1,started:!1,cached:!1,projectKey:"unknown",reasonCodes:[ma.UNEXPECTED_ERROR],publicSummary:"runner scheduler bootstrap stopped unexpectedly.",publicSafe:!0}}const a=Ci(t,r);if(r.ok)return{shouldContinue:!0,attachToRequest:!0,metadata:a};const n=a.reasonCodes.slice(0,5).join(",");return t.failurePolicy==="fail-open"?{shouldContinue:!0,attachToRequest:!0,metadata:{...a,failOpenWarning:!0},warning:`Runner auto-bootstrap warning (${n}); continuing fail-open for operator command.`}:{shouldContinue:!1,attachToRequest:!1,metadata:a,errorCode:"RUNNER_BOOTSTRAP_REQUIRED_FAILED",error:`Runner auto-bootstrap required but failed (${n}). Run neocortex-runner doctor or retry after resolving scheduler setup.`,exitCode:1}}function Ic(e){return!e.reasonCodes.includes(ga.SKIPPED_NON_CONTINUITY_COMMAND)}function Ci(e,t){return{schemaVersion:1,action:e.action,failurePolicy:e.failurePolicy,command:e.command,operation:e.operation,attempted:t?.attempted??!1,ok:t?.ok??!0,cached:t?.cached??!1,installed:t?.installed??!1,started:t?.started??!1,...t?.projectKey?{projectKey:t.projectKey}:{},reasonCodes:Me([...e.reasonCodes,...t?.reasonCodes??[]]),publicSummary:t?.publicSummary??e.publicSummary,publicSafe:!0}}function Me(e){return Array.from(new Set(e.map(t=>t.slice(0,120))))}function Cn(e,t,i){const r=Math.floor(e??t);return Number.isFinite(r)?Math.max(1,Math.min(i,r)):t}function _n(e,t){const i=process.env[e];if(!i)return t;const r=Number(i);return Number.isFinite(r)?r:t}function Y(e,t=Xr){const i=typeof e=="string"&&e.trim().length>0?e.trim():"unknown",r=ze(i,t),a=xo.test(r)?St:r;return a.length<=t?a:`${a.slice(0,t)}\u2026[TRUNCATED:${a.length-t}]`}function tr(e,t=Xr){if(!(typeof e!="string"||e.trim().length===0))return Y(e,t)}function nr(e,t,i,r){const a=tr(e?.targetId??t,120),n=e?.selectorKind??(a?ir(a):void 0),o=(e?.relatedJobIds??[]).map(p=>tr(p,120)).filter(p=>!!p);return{schemaVersion:1,contractVersion:"continuity-v1",targetResolutionState:i,...n?{targetKind:n}:{},...a?{targetId:a}:{},...t?{targetJobId:Y(t,120)}:{},...e?.jobId?{jobId:Y(e.jobId,120)}:{},...e?.goalId?{goalId:Y(e.goalId,120)}:{},...e?.loopId?{loopId:Y(e.loopId,120)}:{},...o.length>0?{relatedJobIds:o}:{},relatedJobCount:o.length,reasonCodes:Me(r.length>0?r:[F.OK]),publicSafe:!0}}function dt(e,t,i,r,a=[]){const n=(e?.redactions?.length??0)>0,o=e?n?"unsafe":i&&r===0?"empty":"available":"unavailable",p=tr(t[t.length-1]?.eventId,120),s=a.length>0?a:o==="unavailable"?[F.WATCH_SNAPSHOT_UNAVAILABLE]:o==="empty"?[F.WATCH_NO_SUMMARIES_YET]:[F.OK];return{schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:o,...e?.generatedAt?{generatedAt:Y(e.generatedAt,80)}:{},renderedSummaryCount:r,...p?{latestEventId:p}:{},reasonCodes:Me(s),publicSafe:!0}}function Xe(e,t,i,r,a=[],n){const o=r[r.length-1],p=i??o?.cursor,s=!!(p&&p!==t&&r.length>0),l=n??(s?"advanced":t||p?"unchanged":"not_started"),I=a.length>0?a:l==="advanced"?[F.WATCH_CURSOR_ADVANCED]:l==="unavailable"?[F.WATCH_EVIDENCE_UNAVAILABLE]:[F.WATCH_CURSOR_UNCHANGED];return{schemaVersion:1,contractVersion:"continuity-v1",cursorState:l,...e?{initialCursor:Y(e,200)}:{},...t?{currentCursor:Y(t,200)}:{},...p?{nextCursor:Y(p,200)}:{},cursorAdvanced:s,...o?.eventId?{eventId:Y(o.eventId,120)}:{},reasonCodes:Me(I),publicSafe:!0}}function Ze(e){const t=e.targetEvidence;return{type:"watch_status",schemaVersion:1,contractVersion:"continuity-v1",recordType:"watch_status",command:"invoke",operation:"watch",watchStatus:e.watchStatus,active:e.active,...t?.targetResolutionState?{targetResolutionState:t.targetResolutionState}:{},...t?.targetKind?{targetKind:t.targetKind}:{},...t?.targetId?{targetId:t.targetId}:{},...t?{targetEvidence:t}:{},...e.snapshotEvidence?{snapshotEvidence:e.snapshotEvidence}:{},...e.cursorEvidence?{cursorEvidence:e.cursorEvidence}:{},...e.stopReason?{stopReason:e.stopReason}:{},reasonCodes:Me([...e.reasonCodes??[],...t?.reasonCodes??[],...e.snapshotEvidence?.reasonCodes??[],...e.cursorEvidence?.reasonCodes??[]]),generatedAt:Y(e.generatedAt??new Date().toISOString(),80),publicSafe:!0}}function Ec(e){const t=e.targetKind&&e.targetId?`${e.targetKind}/${e.targetId}`:e.targetId??"[unresolved]",i=e.snapshotEvidence?.renderedSummaryCount??0,r=e.targetEvidence?.relatedJobCount??0,a=e.cursorEvidence?.cursorState??"unavailable",n=e.cursorEvidence?.currentCursor??"[none]",o=e.cursorEvidence?.nextCursor??"[none]",p=e.snapshotEvidence?.snapshotStatus??"not_requested",s=e.snapshotEvidence?.generatedAt??e.generatedAt;return[`[watch-status] ${e.targetResolutionState==="unresolved"||e.stopReason==="target_unresolved"?"unresolved-target":i===0&&(e.watchStatus==="waiting"||e.watchStatus==="active")?"no-new-summary":e.watchStatus==="stopped"?"stopped":"lifecycle"}`,`status=${e.watchStatus}`,`active=${e.active}`,`target=${t}`,`resolution=${e.targetResolutionState??"unavailable"}`,`relatedJobs=${r}`,`summaries=${i}`,`snapshot=${p}`,`generatedAt=${s}`,`cursor=${a}`,`current=${Y(n,200)}`,`next=${Y(o,200)}`,`advanced=${e.cursorEvidence?.cursorAdvanced??!1}`,`stop=${e.stopReason??"not_stopped"}`,`reasons=${e.reasonCodes.join(",")}`].join(" ")}function et(e,t,i,r=!1){if(r){const a={type:"watch_status",watchStatus:e.watchStatus,active:e.active,renderedSummaryCount:e.snapshotEvidence?.renderedSummaryCount??0,stopReason:e.stopReason??"not_stopped",protectedProjection:!0,publicSafe:!0};i.write(t==="json"?`${JSON.stringify(a)}
7
+ `)}catch{}}}function Sd(){zn=!1}function ei(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Bo(e){return e==="active"||e==="archived"||e==="rolled-back"||e==="synthetic"||e==="orphan"?e:void 0}const Uo=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"]),$o=/(?:[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}|(?:token|api[_-]?key|secret|password|credential|license[_-]?key)\s*[:=]\s*\S+|https?:\/\/(?:localhost|127\.0\.0\.1|10\.\d+\.\d+\.\d+|192\.168\.\d+\.\d+|172\.(?:1[6-9]|2\d|3[0-1])\.\d+\.\d+|[^\s/]*internal[^\s/]*)\S*|private\s+prompt|raw\s+vendor\s+corpus|sk-[A-Za-z0-9_-]{12,})/i;function Ho(e,t){if(!h(e)||e.schemaVersion!==1||e.epicId!==t||!/^P\d+$/.test(t))return{};try{const i=JSON.stringify(e),r=Buffer.byteLength(i);if(r>16384)return{diagnostic:Object.freeze({schemaVersion:"CreateEpicPlanningProjectionDiagnostic/1.0",outcome:"omitted",reasonCode:"budget-omitted",byteLengthBucket:r<=32768?"16385-32768":"32769-plus",publicSafe:!0})};if($o.test(i))return{};const a=(o,p)=>{if(Object.keys(o).some(s=>!p.includes(s)))throw new Error("planning-unknown-field")};if(a(e,["schemaVersion","epicId","intake","intakeRevision","diagnosisReceipt","researchReceipt","degradeAuthorization"]),!h(e.intake))return{};if(Object.keys(e.intake).some(o=>!Uo.has(o)))return{};for(const[o,p]of Object.entries(e.intake))if(["examples","contracts"].includes(o)){const s=o==="examples"?["id","title","actor","given","when","then","source","coveredRequirement","expectedValidation"]:["id","kind","description","path"];if(!Array.isArray(p)||p.length>16)return{};for(const l of p){if(!h(l))return{};if(a(l,s),Object.values(l).some(I=>typeof I!="string"||I.length>256))return{}}}else if(Array.isArray(p)){if(p.length>32||p.some(s=>typeof s!="string"||s.length>256))return{}}else if(typeof p=="string"){if(p.length>(o==="rawIntent"?Zi:512))return{}}else if(typeof p!="boolean"||!["uiScope","remediationStory"].includes(o))return{};const n=["schemaVersion","kind","epicId","intakeRevision","artifactSummary","artifactDigest","predecessorReceiptId","accepted","receiptId"];for(const o of[e.diagnosisReceipt,e.researchReceipt])if(o!==void 0){if(!h(o))return{};if(a(o,n),Object.values(o).some(p=>typeof p=="string"&&p.length>1024))return{}}if(e.degradeAuthorization!==void 0){if(!h(e.degradeAuthorization))return{};a(e.degradeAuthorization,["approved","intakeRevision","reasonCodes","assumptionCodes"]);for(const o of["reasonCodes","assumptionCodes"]){const p=e.degradeAuthorization[o];if(!Array.isArray(p)||p.length>32||p.some(s=>typeof s!="string"||s.length>128))return{}}}return{checkpoint:JSON.parse(i)}}catch{return{}}}function ti(e){return e==="create-epic"||e==="discovered"?e:void 0}function Se(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Go(e){const t={};let i=!1;for(const r of["contracts","contract_refs","shared_surfaces","adr_refs","nfr_refs","acceptance_depends_on"]){if(e[r]===void 0)continue;const a=e[r];if(!Array.isArray(a)||a.length>128||a.some(n=>hn(n)===void 0)){i=!0;continue}t[r]=a.map(n=>hn(n))}if(e.planning!==void 0)try{if(!h(e.planning))throw new Error("planning-shape");const r=e.planning;for(const o of["claims","semanticArtifacts"]){if(r[o]===void 0)continue;const p=r[o];if(!Array.isArray(p)||p.length>128||p.some(s=>!h(s)||hn(s.ref)===void 0))throw new Error("planning-refs")}if(r.attempts!==void 0&&(!Array.isArray(r.attempts)||r.attempts.length>32))throw new Error("planning-attempts");for(const o of r.attempts??[]){if(!h(o)||!Array.isArray(o.reasonCodes)||o.reasonCodes.length>32||o.reasonCodes.some(p=>typeof p!="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(p)))throw new Error("planning-attempt-reasons");if(o.discoveredClaims!==void 0&&(!Array.isArray(o.discoveredClaims)||o.discoveredClaims.length>128||o.discoveredClaims.some(p=>!h(p)||hn(p.ref)===void 0)))throw new Error("planning-attempt-claims")}const{graphRevision:a,...n}=Ka(r);t.planning=n}catch{i=!0}return i&&(t.planning={schemaVersion:1,dependencyBasis:"unknown",claims:[],semanticArtifacts:[]}),t}function h(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function St(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function te(e){if(typeof e!="string")return;const t=e.trim();if(t)return t.replace(/[^a-z0-9_.:-]+/gi,"_").slice(0,120)}function K(e){if(typeof e!="string")return;const t=e.trim(),i=te(e);return i===t?i:void 0}function ve(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240)&&/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(t)&&!(t.includes("..")||t.includes("//")||t.includes("@{")||t.endsWith("/")||t.endsWith("."))&&!t.split("/").some(i=>!i||i.startsWith(".")||i.endsWith(".lock")))return t}function w(e){return typeof e=="string"&&/^[0-9a-f]{7,64}$/i.test(e)?e:void 0}function Oe(e){if(!(typeof e!="string"||e.length>64)&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/.test(e))return Number.isFinite(Date.parse(e))?e:void 0}function ct(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240||t.includes("..")))return/^[A-Za-z0-9._:/#\-[\]]+$/.test(t)?t:void 0}function In(e){if(!h(e))return;const t=u=>typeof u=="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,95}$/.test(u),i=u=>typeof u=="string"&&/^[a-f0-9]{64}$/.test(u),r=(u,_)=>Array.isArray(u)&&u.length<=_&&u.every(t)&&new Set(u).size===u.length?u:void 0,a=(u,_)=>{if(!(!h(u)||u.schemaVersion!==2||!t(u.requestId)||!t(u.stageCommand)||!i(u.requestHash)||!i(u.inputHash)||!i(u.stateHash)||!i(u.nonce)||!i(u.stageRevision)||!i(u.stageHash)||!i(u.catalogHash)||u.targetEpicId!==void 0&&!t(u.targetEpicId)||_&&(!i(u.outputHash)||!i(u.artifactHash))))return{schemaVersion:2,...u.targetEpicId?{targetEpicId:u.targetEpicId}:{},requestId:u.requestId,requestHash:u.requestHash,inputHash:u.inputHash,stateHash:u.stateHash,nonce:u.nonce,stageCommand:u.stageCommand,stageRevision:u.stageRevision,stageHash:u.stageHash,catalogHash:u.catalogHash,..._?{outputHash:u.outputHash,artifactHash:u.artifactHash}:{}}},n=(u,_)=>{if(!(!h(u)||u.schemaVersion!=="1.1"||u.kind!==_||!i(u.receiptId)||!i(u.graphHash)||!i(u.evidenceHash)||!t(u.elementId)||!t(u.caseId)||!t(u.category)))return{schemaVersion:"1.1",kind:_,receiptId:u.receiptId,graphHash:u.graphHash,elementId:u.elementId,caseId:u.caseId,category:u.category,evidenceHash:u.evidenceHash}},o=(u,_)=>{if(!h(u)||u.kind!==_||!i(u.receiptId)||!r(u.evidenceIds,24)||_==="architecture-stage-completion"&&!["succeeded","failed"].includes(String(u.status))||_==="architecture-stage-validation"&&!["passed","failed","pending"].includes(String(u.status)))return;const E=a(u,!0);if(!E)return;const g=_==="architecture-stage-validation"?n(u.isolated,"isolated"):void 0,y=_==="architecture-stage-validation"?n(u.regression,"regression"):void 0;if(!(_==="architecture-stage-validation"&&(!g||!y)))return{...E,kind:_,receiptId:u.receiptId,status:u.status,evidenceIds:u.evidenceIds,...g&&y?{isolated:g,regression:y}:{}}},p={};e.schemaVersion===1&&(p.schemaVersion=1),e.owner==="root"&&(p.owner="root"),t(e.currentStageCommand)&&(p.currentStageCommand=e.currentStageCommand),["ask-user","delegate","resume","advance","blocked","complete"].includes(String(e.continuationState))&&(p.continuationState=e.continuationState);const s=r(e.questionIds,16);if(s&&(p.questionIds=s),(e.childStatus==="succeeded"||e.childStatus==="failed")&&(p.childStatus=e.childStatus),(e.evidencePolicy==="legacy-compatible"||e.evidencePolicy==="v2-required")&&(p.evidencePolicy=e.evidencePolicy),t(e.targetEpicId)&&(p.targetEpicId=e.targetEpicId),i(e.graphRevision)&&(p.graphRevision=e.graphRevision),e.graphSource==="committed-epic-v1"&&(p.graphSource=e.graphSource),e.nonUiScopeReceipt!==void 0){const u=yr(e.nonUiScopeReceipt);if(!u||u.targetEpicId!==e.targetEpicId||u.graphRevision!==e.graphRevision||!h(e.accounting)||u.accountingId!==e.accounting.accountingId||!h(e.evidenceExpectation)||u.rootInputSha256!==e.evidenceExpectation.inputHash)throw new Error("architecture-non-ui-scope-invalid");p.nonUiScopeReceipt=u}h(e.pactAnswerReceipt)&&Object.keys(e.pactAnswerReceipt).sort().join(",")===["schemaVersion","targetEpicId","graphRevision","stateSha256","answersSha256","questionIds","publicSafe"].sort().join(",")&&e.pactAnswerReceipt.schemaVersion==="PactAnswerReceipt/1"&&e.pactAnswerReceipt.targetEpicId===e.targetEpicId&&e.pactAnswerReceipt.graphRevision===e.graphRevision&&i(e.pactAnswerReceipt.stateSha256)&&i(e.pactAnswerReceipt.answersSha256)&&v(e.pactAnswerReceipt.questionIds,["PACT-Q1-CONSUMER","PACT-Q2-PROVIDER","PACT-Q3-BROKER","PACT-Q4-MATCHERS","PACT-Q5-VERIFY"])&&e.pactAnswerReceipt.publicSafe===!0&&(p.pactAnswerReceipt=e.pactAnswerReceipt);const l=a(e.evidenceExpectation,!1);l&&(p.evidenceExpectation=l);const I=o(e.completionEvidence,"architecture-stage-completion"),S=o(e.validationEvidence,"architecture-stage-validation");if(I&&(p.completionEvidence=I),S&&(p.validationEvidence=S),h(e.reviewDecision)&&Object.keys(e.reviewDecision).sort().join(",")===["schemaVersion","targetEpicId","graphRevision","artifactHash","completionReceiptId","validationReceiptId","decision","evidenceIds","publicSafe"].sort().join(",")&&e.reviewDecision.schemaVersion==="ArchitectureReviewDecision/1"&&e.reviewDecision.targetEpicId===e.targetEpicId&&e.reviewDecision.graphRevision===e.graphRevision&&i(e.reviewDecision.graphRevision)&&i(e.reviewDecision.artifactHash)&&i(e.reviewDecision.completionReceiptId)&&i(e.reviewDecision.validationReceiptId)&&["approved","changes-requested"].includes(String(e.reviewDecision.decision))&&e.reviewDecision.publicSafe===!0){const u=r(e.reviewDecision.evidenceIds,24);u&&u.length>0&&(p.reviewDecision={...e.reviewDecision,evidenceIds:u})}if(Wt(e.terminalMemoryCheckpoint,e))p.terminalMemoryCheckpoint=e.terminalMemoryCheckpoint;else if(h(e.terminalMemoryCheckpoint)&&e.terminalMemoryCheckpoint.schemaVersion===void 0&&["passed","failed","pending"].includes(String(e.terminalMemoryCheckpoint.status))){const u=r(e.terminalMemoryCheckpoint.evidenceIds,24);u&&(p.terminalMemoryCheckpoint={status:e.terminalMemoryCheckpoint.status,evidenceIds:u})}if(Array.isArray(e.acceptedStages)&&e.acceptedStages.length<=15){const u=e.acceptedStages.map(_=>{if(!h(_)||!t(_.targetEpicId)||!t(_.stageCommand))return;const E=o(_.completionEvidence,"architecture-stage-completion"),g=o(_.validationEvidence,"architecture-stage-validation");return E&&g?{targetEpicId:_.targetEpicId,stageCommand:_.stageCommand,completionEvidence:E,validationEvidence:g}:void 0});u.every(_=>_!==void 0)&&(p.acceptedStages=u)}if(h(e.accounting)&&e.accounting.schemaVersion===1&&t(e.accounting.contractVersion)&&t(e.accounting.accountingId)&&typeof e.accounting.charged=="boolean"&&Number.isInteger(e.accounting.chargedQuotaUnits)&&typeof e.accounting.chargedQuotaUnits=="number"&&e.accounting.chargedQuotaUnits>=0&&e.accounting.chargedQuotaUnits<=13){const u=r(e.accounting.receiptIds,32);u&&(p.accounting={schemaVersion:1,contractVersion:e.accounting.contractVersion,accountingId:e.accounting.accountingId,charged:e.accounting.charged,chargedQuotaUnits:e.accounting.chargedQuotaUnits,receiptIds:u,...["in-progress","aborted","timed-out","failed","complete"].includes(String(e.accounting.lastOutcome))?{lastOutcome:e.accounting.lastOutcome}:{}})}return JSON.stringify(p).length<=96e3?p:void 0}function Wo(e){const t=h(e.metadata.archPlan)?e.metadata.archPlan.execution:void 0,i=h(t)?t.checkpoint:void 0,r=h(t)?t:void 0,a=h(i)?i:void 0,n=e.requestExecution,o=Array.isArray(a?.acceptedStages)?a.acceptedStages:[],p=n.currentStageCommand==="arch-prd"&&n.continuationState==="delegate"&&n.completionEvidence===void 0&&n.validationEvidence===void 0&&a?.currentStageCommand==="arch-prd"&&a.continuationState==="delegate"&&o.length===0&&r?.nextAction==="delegate",s=n.currentStageCommand==="arch-prd"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-architecture"&&a.continuationState==="advance"&&o.length===1&&h(o[0])&&o[0].stageCommand==="arch-prd"&&v(o[0].completionEvidence,n.completionEvidence)&&v(o[0].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",l=n.currentStageCommand==="arch-architecture"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-architecture"&&a.continuationState==="delegate"&&o.length===1&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",I=n.currentStageCommand==="arch-architecture"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-fitness-functions"&&a.continuationState==="advance"&&o.length===2&&h(o[0])&&h(o[1])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===1&&v(o[0],n.acceptedStages[0])&&v(o[1].completionEvidence,n.completionEvidence)&&v(o[1].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",S=n.currentStageCommand==="arch-fitness-functions"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-fitness-functions"&&a.continuationState==="delegate"&&o.length===2&&h(o[0])&&h(o[1])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",u=n.currentStageCommand==="arch-fitness-functions"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-api-contracts"&&a.continuationState==="advance"&&o.length===3&&h(o[0])&&h(o[1])&&h(o[2])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&o[2].stageCommand==="arch-fitness-functions"&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===2&&v(o.slice(0,2),n.acceptedStages)&&v(o[2].completionEvidence,n.completionEvidence)&&v(o[2].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",_=n.currentStageCommand==="arch-api-contracts"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-api-contracts"&&a.continuationState==="delegate"&&o.length===3&&h(o[0])&&h(o[1])&&h(o[2])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&o[2].stageCommand==="arch-fitness-functions"&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",E=["PACT-Q1-CONSUMER","PACT-Q2-PROVIDER","PACT-Q3-BROKER","PACT-Q4-MATCHERS","PACT-Q5-VERIFY"],g=n.currentStageCommand==="arch-api-contracts"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="generate-pacts"&&a.continuationState==="ask-user"&&o.length===4&&h(o[3])&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===3&&v(o.slice(0,3),n.acceptedStages)&&o[3].stageCommand==="arch-api-contracts"&&v(o[3].completionEvidence,n.completionEvidence)&&v(o[3].validationEvidence,n.validationEvidence)&&v(a.questionIds,E)&&v(r?.questionIds,E)&&r?.nextAction==="ask-user",y=n.currentStageCommand==="generate-pacts"&&n.continuationState==="ask-user"&&a?.currentStageCommand==="generate-pacts"&&a.continuationState==="delegate"&&o.length===4&&v(o,n.acceptedStages)&&v(n.questionIds,E)&&v(a.questionIds,[])&&v(a.pactAnswerReceipt,e.answerReceipt)&&v(r?.pactAnswerReceipt,e.answerReceipt)&&e.answerReceipt?.stateSha256===e.sourceStateSha256&&r?.nextAction==="resume",b=n.currentStageCommand==="generate-pacts"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&v(n.pactAnswerReceipt,e.pactRecordedReceipt)&&a?.currentStageCommand==="arch-api-integrations"&&a.continuationState==="advance"&&o.length===5&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===4&&v(o.slice(0,4),n.acceptedStages)&&o.map(B=>h(B)?B.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts"&&h(o[4])&&v(o[4].completionEvidence,n.completionEvidence)&&v(o[4].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",L=n.currentStageCommand==="arch-api-integrations"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-api-integrations"&&a.continuationState==="delegate"&&o.length===5&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",T=n.currentStageCommand==="arch-api-integrations"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-database"&&a.continuationState==="advance"&&o.length===6&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===5&&v(o.slice(0,5),n.acceptedStages)&&o.map(B=>h(B)?B.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations"&&h(o[5])&&v(o[5].completionEvidence,n.completionEvidence)&&v(o[5].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",P=n.currentStageCommand==="arch-database"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-database"&&a.continuationState==="delegate"&&o.length===6&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",C=n.currentStageCommand==="arch-database"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-security"&&a.continuationState==="advance"&&o.length===7&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===6&&v(o.slice(0,6),n.acceptedStages)&&o.map(B=>h(B)?B.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database"&&h(o[6])&&v(o[6].completionEvidence,n.completionEvidence)&&v(o[6].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",R=n.currentStageCommand==="arch-security"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-security"&&a.continuationState==="delegate"&&o.length===7&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",M=n.currentStageCommand==="arch-security"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-design-system"&&a.continuationState==="advance"&&o.length===8&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===7&&v(o.slice(0,7),n.acceptedStages)&&o.map(B=>h(B)?B.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security"&&h(o[7])&&v(o[7].completionEvidence,n.completionEvidence)&&v(o[7].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",N=n.currentStageCommand==="arch-design-system"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-design-system"&&a.continuationState==="delegate"&&o.length===8&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",z=n.currentStageCommand==="arch-design-system"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-ux-design"&&a.continuationState==="advance"&&o.length===9&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===8&&v(o.slice(0,8),n.acceptedStages)&&o.map(B=>h(B)?B.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system"&&h(o[8])&&v(o[8].completionEvidence,n.completionEvidence)&&v(o[8].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",Z=n.currentStageCommand==="arch-ux-design"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-ux-design"&&a.continuationState==="delegate"&&o.length===9&&v(o,n.acceptedStages)&&r?.nextAction==="blocked",j=n.currentStageCommand==="arch-ux-design"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-performance"&&a.continuationState==="advance"&&o.length===10&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===9&&v(o.slice(0,9),n.acceptedStages)&&o.map(B=>h(B)?B.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design"&&h(o[9])&&v(o[9].completionEvidence,n.completionEvidence)&&v(o[9].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",V=n.currentStageCommand==="arch-performance"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-performance"&&a.continuationState==="delegate"&&o.length===10&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",ee=n.currentStageCommand==="arch-performance"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-testing"&&a.continuationState==="advance"&&o.length===11&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===10&&v(o.slice(0,10),n.acceptedStages)&&o.map(B=>h(B)?B.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance"&&h(o[10])&&v(o[10].completionEvidence,n.completionEvidence)&&v(o[10].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",G=n.currentStageCommand==="arch-testing"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-testing"&&a.continuationState==="delegate"&&o.length===11&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",lt=n.currentStageCommand==="arch-testing"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-infrastructure"&&a.continuationState==="advance"&&o.length===12&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===11&&v(o.slice(0,11),n.acceptedStages)&&o.map(B=>h(B)?B.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance,arch-testing"&&h(o[11])&&v(o[11].completionEvidence,n.completionEvidence)&&v(o[11].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",Ye=n.currentStageCommand==="arch-infrastructure"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-infrastructure"&&a.continuationState==="delegate"&&o.length===12&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",he=n.currentStageCommand==="arch-infrastructure"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-review"&&a.continuationState==="advance"&&o.length===13&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===12&&v(o.slice(0,12),n.acceptedStages)&&o.map(B=>h(B)?B.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance,arch-testing,arch-infrastructure"&&h(o[12])&&v(o[12].completionEvidence,n.completionEvidence)&&v(o[12].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",O=n.currentStageCommand==="arch-review"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-review"&&a.continuationState==="delegate"&&o.length===13&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",H=n.currentStageCommand==="arch-review"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&n.reviewDecision===void 0&&a?.currentStageCommand==="arch-review"&&a.continuationState==="ask-user"&&o.length===13&&v(o,n.acceptedStages)&&v(a.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&v(a.completionEvidence,n.completionEvidence)&&v(a.validationEvidence,n.validationEvidence)&&r?.nextAction==="ask-user",Ct=n.currentStageCommand==="arch-review"&&n.continuationState==="ask-user"&&n.childStatus==="succeeded"&&h(n.reviewDecision)&&n.reviewDecision.decision==="approved"&&v(n.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&a?.currentStageCommand==="update-memory"&&a.continuationState==="advance"&&o.length===14&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===13&&v(o.slice(0,13),n.acceptedStages)&&h(o[13])&&o[13].stageCommand==="arch-review"&&v(o[13].completionEvidence,n.completionEvidence)&&v(o[13].validationEvidence,n.validationEvidence)&&v(a.reviewDecision,n.reviewDecision)&&r?.nextAction==="resume",De=n.currentStageCommand==="update-memory"&&n.continuationState==="advance"&&h(n.reviewDecision)&&n.reviewDecision.decision==="approved"&&a?.currentStageCommand==="update-memory"&&a.continuationState==="delegate"&&o.length===14&&v(o,n.acceptedStages)&&v(a.reviewDecision,n.reviewDecision)&&r?.nextAction==="delegate",se=n.currentStageCommand==="update-memory"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="update-memory"&&a.continuationState==="complete"&&o.length===15&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===14&&v(o.slice(0,14),n.acceptedStages)&&h(o[14])&&o[14].targetEpicId===n.targetEpicId&&o[14].stageCommand==="update-memory"&&v(o[14].completionEvidence,n.completionEvidence)&&v(o[14].validationEvidence,n.validationEvidence)&&v(a.reviewDecision,n.reviewDecision)&&v(a.completionEvidence,n.completionEvidence)&&v(a.validationEvidence,n.validationEvidence)&&Wt(a.terminalMemoryCheckpoint,n)!==null&&v(a.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)&&r?.nextAction==="complete",tt=n.currentStageCommand==="update-memory"&&n.continuationState==="complete"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="update-memory"&&a.continuationState==="complete"&&o.length===15&&v(o,n.acceptedStages)&&v(a.reviewDecision,n.reviewDecision)&&v(a.completionEvidence,n.completionEvidence)&&v(a.validationEvidence,n.validationEvidence)&&Wt(a.terminalMemoryCheckpoint,n)&&v(a.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)&&r?.nextAction==="complete",ut=r?$i(n,r,Wt(n.terminalMemoryCheckpoint,n)&&v(a?.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)):void 0;if(e.metadata.mode!=="arch-plan"||e.metadata.resolvedTrigger!=="arch-plan"||!h(t)||!h(i)||t.owner!=="root"||t.currentStageCommand!==i.currentStageCommand||t.continuationState!==i.continuationState||i.owner!=="root"||i.evidencePolicy!=="v2-required"||i.targetEpicId!==n.targetEpicId||i.graphRevision!==n.graphRevision||i.graphSource!==n.graphSource||!/^P[1-9][0-9]{0,11}$/.test(String(i.targetEpicId))||!/^[a-f0-9]{64}$/.test(String(i.graphRevision))||!Array.isArray(i.acceptedStages)||!(ut||p||s||l||I||S||u||_||g||y||b||L||T||P||C||R||M||N||z||Z||j||V||ee||G||lt||Ye||he||O||H||Ct||De||se||tt)||!h(i.accounting)||i.accounting.charged!==!0||!v(In(i),i))throw new Error("architecture-root-checkpoint-invalid");const X=Q(e.projectRoot,".neocortex"),ye=Q(X,"state.json"),le=Q(X,"state.json.architecture.lock"),Nt=qt(le,"wx",384);let we;try{const B=jt(ye);if(!B.isFile()||B.isSymbolicLink())throw new Error("architecture-root-state-binding-invalid");const je=We(ye,"utf8");if(Pe("sha256").update(je).digest("hex")!==e.sourceStateSha256)throw new Error("architecture-root-state-conflict");const J=JSON.parse(je),ge=h(J)&&h(J.archPlan)?J.archPlan:{};if(!h(J)||!h(J.epics)||!Object.hasOwn(J.epics,i.targetEpicId)||(e.initialBinding?ge.execution!==void 0||n.graphSource!=="committed-epic-v1":!v(In(ge.execution),n))||h(J.scope)&&J.scope.kind==="projected")throw new Error("architecture-root-state-binding-invalid");if(n.graphSource==="committed-epic-v1"&&n.graphRevision!==Ft(e.projectRoot,String(n.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");if(tt||ut==="complete-replay"){const f={...n,continuationState:"delegate",acceptedStages:n.acceptedStages.slice(0,mr(n))};if(!v(n.terminalMemoryCheckpoint,On(e.projectRoot,f)))throw new Error("architecture-root-state-conflict");return}const Ve=dn(),ne=Ge("git",["rev-parse","--git-common-dir"],{cwd:e.projectRoot,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),_t=qi(ne)?Ln(ne):Ln(e.projectRoot,ne);if(Yi(_t)!==_t)throw new Error("architecture-root-backup-dir-invalid");const qe=Q(_t,"neocortex-architecture");Yt(qe,{recursive:!0,mode:448});const Ie=jt(qe);if(!Ie.isDirectory()||Ie.isSymbolicLink()||Ie.uid!==process.getuid?.()||(Ie.mode&63)!==0)throw new Error("architecture-root-backup-dir-invalid");const ht=Q(qe,`state-backup-${Ve}.json`),W=qt(ht,"wx",384);try{pn(W,je),ln(W)}finally{zt(W)}const tn=qt(qe,"r");try{ln(tn)}finally{zt(tn)}const wt={...J,archPlan:{...ge,execution:i}};we=Q(X,`state.json.architecture-tmp-${Ve}`);const k=qt(we,"wx",384);try{pn(k,`${JSON.stringify(wt,null,2)}
8
+ `),ln(k)}finally{zt(k)}if((se||ut==="complete")&&!v(n.terminalMemoryCheckpoint,On(e.projectRoot,n)))throw new Error("architecture-root-state-conflict");if(n.graphSource==="committed-epic-v1"&&n.graphRevision!==Ft(e.projectRoot,String(n.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");Er(we,ye),we=void 0;const Rt=qt(X,"r");try{ln(Rt)}finally{zt(Rt)}}finally{if(we)try{Nn(we)}catch{}zt(Nt),Nn(le)}}function En(e,t){if(!h(e))return;const i={};for(const r of t){const a=e[r];if(typeof a=="boolean")i[r]=a;else if(typeof a=="number"&&Number.isFinite(a))i[r]=a;else if(typeof a=="string"){const n=te(a);n&&(i[r]=n)}}return Object.keys(i).length>0?i:void 0}function Sn(e){return e==="epic"||e==="story"?e:void 0}function ni(e){if(!h(e)||e.schemaVersion!==1)return;const t=K(e.ownerStoryId),i=K(e.sessionId),r=K(e.idempotencyKey),a=Oe(e.acquiredAt),n=Oe(e.expiresAt);if(!(!t||!i||!r||!a||!n||Date.parse(n)<=Date.parse(a)))return{schemaVersion:1,ownerStoryId:t,sessionId:i,idempotencyKey:r,acquiredAt:a,expiresAt:n}}function ri(e){if(!h(e)||e.schemaVersion!==1)return;const t=K(e.storyId),i=K(e.epicId),r=ve(e.branch),a=w(e.baseSha),n=w(e.headSha),o=K(e.idempotencyKey),p=Oe(e.recordedAt),s=Se(e.commits).map(w).filter(L=>!!L).slice(0,256),l=Se(e.receiptRefs).map(ct).filter(L=>!!L).slice(0,256),I=e.dispatchId===void 0?void 0:K(e.dispatchId),S=e.bundleId===void 0?void 0:K(e.bundleId),u=e.bundleDigest===void 0?void 0:w(e.bundleDigest),_=e.graphRevision===void 0?void 0:w(e.graphRevision),E=e.claimRevision===void 0?void 0:K(e.claimRevision),g=Fo(e.qaReceipt),y=Yo(e.reviewReceipt),b=e.rootMemoryEffect===void 0?void 0:so(e.rootMemoryEffect)?e.rootMemoryEffect:void 0;if(!(!t||!i||!t.startsWith(`${i}.`)||!r||!a||!n||a===n||!o||!p||s.length===0||l.length===0||!Array.isArray(e.commits)||s.length!==e.commits.length||e.commits.length>256||!Array.isArray(e.receiptRefs)||l.length!==e.receiptRefs.length||e.receiptRefs.length>256||e.dispatchId!==void 0&&!I||e.bundleId!==void 0&&!S||e.bundleDigest!==void 0&&(!u||u.length!==64)||e.graphRevision!==void 0&&(!_||_.length!==64)||e.claimRevision!==void 0&&!E||e.rootMemoryEffect!==void 0&&(!b||b.storyId!==t||b.epicId!==i||b.executionBranch!==r||b.sourceHeadSha!==a||b.childClaimRevision!==E)||e.qaVerdict!=="passed"&&e.qaVerdict!=="blocked"||!["approved","changes-requested","pending"].includes(String(e.reviewVerdict))||!g||e.reviewVerdict!=="pending"&&!y||e.reviewVerdict==="pending"&&y||g.verdict!==e.qaVerdict||y&&y.verdict!==e.reviewVerdict||!oi(g,{storyId:t,epicId:i,baseSha:a,headSha:n,bundleDigest:u,graphRevision:_})||y&&(!oi(y,{storyId:t,epicId:i,baseSha:a,headSha:n,bundleDigest:u,graphRevision:_})||y.qaReceiptRef!==g?.receiptRef||y.receiptRef===g?.receiptRef)||!l.includes(String(g.receiptRef))||y&&(!l.includes(String(y.receiptRef))||Date.parse(String(y.reviewedAt))<Date.parse(String(g.checkedAt)))))return{schemaVersion:1,storyId:t,epicId:i,branch:r,baseSha:a,headSha:n,idempotencyKey:o,...I?{dispatchId:I}:{},...S?{bundleId:S}:{},...u?{bundleDigest:u}:{},..._?{graphRevision:_}:{},...E?{claimRevision:E}:{},...b?{rootMemoryEffect:structuredClone(b)}:{},qaVerdict:e.qaVerdict,reviewVerdict:e.reviewVerdict,...g?{qaReceipt:g}:{},...y?{reviewReceipt:y}:{},recordedAt:p,commits:s,receiptRefs:l}}function Fo(e){if(!h(e)||e.schemaVersion!==1||e.kind!=="story_qa_evidence"||e.producer!=="local-yolo-tdd"||e.evidenceVersion!==void 0&&e.evidenceVersion!=="git-immutable-v1"&&e.evidenceVersion!=="p205-execution-v2"||!["passed","blocked"].includes(String(e.verdict)))return;const t=K(e.storyId),i=K(e.epicId),r=w(e.baseSha),a=w(e.headSha),n=w(e.bundleDigest),o=w(e.graphRevision),p=w(e.sourceEvidenceDigest),s=Oe(e.checkedAt),l=ct(e.receiptRef),I=e.evidenceVersion==="p205-execution-v2"&&e.contract==="P205-CI-02"?e.contract:void 0,S=e.evidenceVersion==="p205-execution-v2"&&e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,u=e.evidenceVersion==="p205-execution-v2"?w(e.manifestDigest):void 0,_=e.evidenceVersion==="p205-execution-v2"?w(e.resultDigest):void 0,E=e.evidenceVersion==="p205-execution-v2"?Se(e.gateIds).map(K).filter(g=>!!g).slice(0,64):void 0;if(!(!t||!i||!r||!a||!n||n.length!==64||!o||o.length!==64||!p||p.length!==64||!s||!l||e.evidenceVersion==="p205-execution-v2"&&(!I||S!=="node scripts/test-root.mjs --gate complete"||!u||u.length!==64||!_||_.length!==64||!Array.isArray(e.gateIds)||!E||E.length===0||E.length!==e.gateIds.length)))return{schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",...e.evidenceVersion?{evidenceVersion:e.evidenceVersion}:{},storyId:t,epicId:i,...e.evidenceVersion==="p205-execution-v2"?{contract:I,command:S,manifestDigest:u,gateIds:E,resultDigest:_}:{},baseSha:r,headSha:a,bundleDigest:n,graphRevision:o,sourceEvidenceDigest:p,verdict:e.verdict,checkedAt:s,receiptRef:l}}function ii(e){if(!h(e)||e.schemaVersion!==1||e.kind!=="story_checkpoint_physical_verification"||e.producer!=="client-p205-transient-v1"||e.publicSafe!==!0||e.verdict!=="verified"&&e.verdict!=="rejected")return;const t=K(e.storyId),i=K(e.epicId),r=ve(e.branch),a=w(e.baseSha),n=w(e.headSha),o=w(e.aggregateHeadSha),p=w(e.commitBodyDigest),s=w(e.changedPathsDigest),l=e.claimVerification==="canonical"||e.claimVerification==="legacy-migration"?e.claimVerification:void 0,I=w(e.effectiveClaimRevision),S=e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,u=w(e.manifestDigest),_=Se(e.gateIds).map(K).filter(P=>!!P).slice(0,64),E=w(e.resultDigest),g=w(e.graphRevision),y=w(e.executionEvidenceDigest),b=w(e.sourceEvidenceDigest),L=Oe(e.verifiedAt),T=Se(e.reasonCodes).map(K).filter(P=>!!P).slice(0,16);if(!(!t||!i||!r||!a||a.length<40||!n||n.length<40||!o||o.length<40||!p||p.length!==64||!s||s.length!==64||!l||!I||I.length!==64||!S||!u||u.length!==64||!Array.isArray(e.gateIds)||_.length!==e.gateIds.length||!E||E.length!==64||!g||g.length!==64||!y||y.length!==64||!b||b.length!==64||!L||T.length===0||e.verdict==="verified"&&(_.length===0||!T.includes("checkpoint-p205-transient-verified"))))return{schemaVersion:1,kind:"story_checkpoint_physical_verification",producer:"client-p205-transient-v1",storyId:t,epicId:i,branch:r,baseSha:a,headSha:n,aggregateHeadSha:o,commitBodyDigest:p,changedPathsDigest:s,claimVerification:l,effectiveClaimRevision:I,command:S,manifestDigest:u,gateIds:_,resultDigest:E,graphRevision:g,executionEvidenceDigest:y,sourceEvidenceDigest:b,verifiedAt:L,verdict:e.verdict,reasonCodes:T,publicSafe:!0}}function ai(e){const t=["schemaVersion","kind","producer","storyId","epicId","branch","baseSha","headSha","graphRevision","effectiveClaimRevision","sourceEvidenceDigest","verifiedAt","reasonCodes","integrationAuthorized","publicSafe"];if(!h(e)||Object.keys(e).some(u=>!t.includes(u))||e.schemaVersion!==1||e.kind!=="story_scheduling_checkpoint_evidence"||e.producer!=="client-git-physical-v1"||e.integrationAuthorized!==!1||e.publicSafe!==!0)return;const i=K(e.storyId),r=K(e.epicId),a=ve(e.branch),n=w(e.baseSha),o=w(e.headSha),p=w(e.graphRevision),s=w(e.effectiveClaimRevision),l=w(e.sourceEvidenceDigest),I=Oe(e.verifiedAt),S=Se(e.reasonCodes).map(K).filter(u=>!!u);if(!(!i||!r||!a||!n||n.length<40||!o||o.length<40||!p||p.length!==64||!s||s.length!==64||!l||l.length!==64||!I||!Array.isArray(e.reasonCodes)||S.length!==1||S[0]!=="checkpoint-git-scheduling-verified"))return{schemaVersion:1,kind:"story_scheduling_checkpoint_evidence",producer:"client-git-physical-v1",storyId:i,epicId:r,branch:a,baseSha:n,headSha:o,graphRevision:p,effectiveClaimRevision:s,sourceEvidenceDigest:l,verifiedAt:I,reasonCodes:S,integrationAuthorized:!1,publicSafe:!0}}function Yo(e){if(!h(e)||e.schemaVersion!==1||e.kind!=="story_review_evidence"||e.producer!=="root-commit-range-review"||!["approved","changes-requested"].includes(String(e.verdict)))return;const t=K(e.storyId),i=K(e.epicId),r=w(e.baseSha),a=w(e.headSha),n=w(e.bundleDigest),o=w(e.graphRevision),p=w(e.sourceEvidenceDigest),s=ct(e.qaReceiptRef),l=Oe(e.reviewedAt),I=ct(e.receiptRef);if(!(!t||!i||!r||!a||!n||n.length!==64||!o||o.length!==64||!p||p.length!==64||!s||!l||!I))return{schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:t,epicId:i,baseSha:r,headSha:a,bundleDigest:n,graphRevision:o,sourceEvidenceDigest:p,qaReceiptRef:s,verdict:e.verdict,reviewedAt:l,receiptRef:I}}function oi(e,t){return["storyId","epicId","baseSha","headSha","bundleDigest","graphRevision"].every(i=>e[i]===t[i])}function ci(e){if(!h(e)||e.schemaVersion!==1||e.capturedFromCurrentCheckout!==!0)return;const t=ve(e.originBranch),i=w(e.originHeadSha),r=ve(e.executionBranch),a=Oe(e.capturedAt);if(!(!t||!i||i.length<40||!r||!a||t===r))return{schemaVersion:1,originBranch:t,originHeadSha:i,executionBranch:r,capturedFromCurrentCheckout:!0,capturedAt:a}}function si(e){if(!h(e)||e.schemaVersion!==1||e.verdict!=="passed")return;const t=w(e.executionHeadSha),i=w(e.graphRevision),r=Oe(e.checkedAt),a=ct(e.receiptRef),n=Se(e.gateIds).map(K).filter(I=>!!I).slice(0,128),o=e.evidenceVersion==="p205-execution-v2"&&e.producer==="local-yolo-tdd"&&e.contract==="P205-CI-02"&&e.command==="node scripts/test-root.mjs --gate complete",p=e.evidenceVersion===void 0&&e.producer===void 0&&e.contract===void 0&&e.command===void 0&&e.manifestDigest===void 0&&e.resultDigest===void 0,s=o?w(e.manifestDigest):void 0,l=o?w(e.resultDigest):void 0;if(!(!t||t.length<40||!i||i.length!==64||!r||!a||n.length===0||!Array.isArray(e.gateIds)||n.length!==e.gateIds.length||e.gateIds.length>128||!p&&!o||o&&(!s||s.length!==64||!l||l.length!==64)))return{schemaVersion:1,...o?{evidenceVersion:"p205-execution-v2",producer:"local-yolo-tdd",contract:"P205-CI-02",command:"node scripts/test-root.mjs --gate complete",manifestDigest:s,resultDigest:l}:{},verdict:"passed",executionHeadSha:t,graphRevision:i,checkedAt:r,receiptRef:a,gateIds:n}}function di(e){if(!h(e)||e.schemaVersion!==1||e.kind!=="epic_head_reconciliation"||e.producer!=="client-p205-head-reconciliation-v1"||e.publicSafe!==!0)return;const t={schemaVersion:1,kind:"epic_head_reconciliation",producer:"client-p205-head-reconciliation-v1",epicId:K(e.epicId),executionBranch:ve(e.executionBranch),originBranch:ve(e.originBranch),graphRevision:w(e.graphRevision),originHeadSha:w(e.originHeadSha),lastAcceptedCheckpointHeadSha:w(e.lastAcceptedCheckpointHeadSha),executionHeadSha:w(e.executionHeadSha),acceptedCheckpointIds:Se(e.acceptedCheckpointIds),acceptedCheckpointHeads:Se(e.acceptedCheckpointHeads),reconciliationCommitShas:Se(e.reconciliationCommitShas),commitRangeDigest:w(e.commitRangeDigest),changedPaths:Se(e.changedPaths),changedPathsDigest:w(e.changedPathsDigest),allowedWriteSet:Se(e.allowedWriteSet),allowedWriteSetDigest:w(e.allowedWriteSetDigest),aggregateReceiptRef:ct(e.aggregateReceiptRef),aggregateManifestDigest:w(e.aggregateManifestDigest),aggregateResultDigest:w(e.aggregateResultDigest),producedAt:Oe(e.producedAt),revalidatedAt:Oe(e.revalidatedAt),publicSafe:!0};if(!t.epicId||!t.executionBranch||!t.originBranch||!t.graphRevision||t.graphRevision.length!==64||!t.originHeadSha||t.originHeadSha.length<40||!t.lastAcceptedCheckpointHeadSha||t.lastAcceptedCheckpointHeadSha.length<40||!t.executionHeadSha||t.executionHeadSha.length<40||t.acceptedCheckpointIds.length===0||t.acceptedCheckpointIds.length>2048||t.acceptedCheckpointIds.length!==t.acceptedCheckpointHeads.length||t.acceptedCheckpointHeads.some(a=>!/^[a-f0-9]{40,64}$/i.test(a))||t.reconciliationCommitShas.length>2048||t.reconciliationCommitShas.some(a=>!/^[a-f0-9]{40,64}$/i.test(a))||t.changedPaths.length>2048||(t.lastAcceptedCheckpointHeadSha===t.executionHeadSha?t.reconciliationCommitShas.length!==0||t.changedPaths.length!==0:t.reconciliationCommitShas.length===0||t.changedPaths.length===0)||t.allowedWriteSet.length===0||t.allowedWriteSet.length>2048||!t.commitRangeDigest||!t.changedPathsDigest||!t.allowedWriteSetDigest||!t.aggregateReceiptRef||!t.aggregateManifestDigest||!t.aggregateResultDigest||!t.producedAt||!t.revalidatedAt||t.commitRangeDigest!==Xa(t.lastAcceptedCheckpointHeadSha,t.executionHeadSha,t.reconciliationCommitShas)||t.changedPathsDigest!==jr(t.changedPaths)||t.allowedWriteSetDigest!==jr(t.allowedWriteSet))return;const i=t,r=w(e.inputDigest);if(!(!r||r.length!==64||r!==Qa(i)))return{...i,inputDigest:r}}function Jn(e){if(!h(e)||e.schemaVersion!==1)return;const t=En(e,["schemaVersion","kind","storyId","epicId","baseSha","headSha","originalBaseSha","originalHeadSha","gitPullRequest","preservesLaterCommits","historyRewrite","recordedAt"])??{},i=Se(e.receiptRefs).map(ct).filter(a=>!!a).slice(0,256),r=Se(e.revertCommits).map(te).filter(a=>!!a).slice(0,256);return{...t,...i.length?{receiptRefs:i}:{},...r.length?{revertCommits:r}:{}}}function qo(e){if(!(!h(e)||Object.keys(e).sort().join(",")!=="gitPullRequest,headSha,kind,prNumber,reviewEvidenceDigest,schemaVersion"||e.schemaVersion!==1||e.kind!=="git-pull-request"||e.gitPullRequest!==!0||!Number.isSafeInteger(e.prNumber)||Number(e.prNumber)<=0||typeof e.headSha!="string"||!/^[a-f0-9]{40}$/.test(e.headSha)||typeof e.reviewEvidenceDigest!="string"||!/^[a-f0-9]{64}$/.test(e.reviewEvidenceDigest)))return{schemaVersion:1,kind:"git-pull-request",gitPullRequest:!0,prNumber:e.prNumber,headSha:e.headSha,reviewEvidenceDigest:e.reviewEvidenceDigest}}function pi(e){if(!h(e)||e.schemaVersion!==1||e.publicSafe!==!0)return;const t=K(e.epicId),i=ve(e.executionBranch),r=ve(e.originBranch),a=w(e.baseSha),n=w(e.executionHeadSha),o=e.mergeSha===void 0?void 0:w(e.mergeSha),p=e.pushedSha===void 0?void 0:w(e.pushedSha),s=K(e.idempotencyKey),l=Oe(e.attemptStartedAt),I=e.completedAt===void 0?void 0:Oe(e.completedAt),S=Se(e.localGateReceiptRefs).map(ct).filter(g=>!!g).slice(0,256),u=Se(e.reasonCodes).map(K).filter(g=>!!g).slice(0,64),_=Jo(e.candidateQa),E=zo(e.providerGuard);if(!(!t||!i||!r||!a||!n||!s||!l||S.length===0||u.length===0||!["direct","single_pr"].includes(String(e.strategy))||!["prepared","merged","pushed","denied_external_gate","blocked_local_or_repo"].includes(String(e.physicalStatus))||typeof e.retryEligible!="boolean"||e.providerGuard!==void 0&&!E||E&&(e.strategy!=="single_pr"||e.physicalStatus!=="pushed"||E.prHeadSha!==o||E.originHeadSha!==a)))return{schemaVersion:1,epicId:t,executionBranch:i,originBranch:r,baseSha:a,executionHeadSha:n,...o?{mergeSha:o}:{},...p?{pushedSha:p}:{},strategy:e.strategy,...St(e.prNumber)?{prNumber:St(e.prNumber)}:{},physicalStatus:e.physicalStatus,localGateReceiptRefs:S,idempotencyKey:s,attemptStartedAt:l,..._?{candidateQa:_}:{},...E?{providerGuard:E}:{},...I?{completedAt:I}:{},retryEligible:e.retryEligible,reasonCodes:u,publicSafe:!0}}function zo(e){if(!h(e)||e.schemaVersion!==1||e.provider!=="github"||e.publicSafe!==!0)return;const t=String(e.mode),i=String(e.source),r=t==="recovered_exact_tree"?i==="physical_recovery":t==="strict_up_to_date_expected_head"&&["branch_protection","ruleset","branch_protection_and_ruleset"].includes(i),a=w(e.prHeadSha),n=w(e.originHeadSha),o=Oe(e.checkedAt);if(!(!r||!a||!n||!o))return{schemaVersion:1,provider:"github",mode:t,source:i,prHeadSha:a,originHeadSha:n,checkedAt:o,publicSafe:!0}}function Jo(e){if(!h(e)||e.schemaVersion!==1||e.kind!=="epic_merge_candidate_qa"||e.contract!=="P205-CI-02"||e.command!==Qt)return;const i=Object.fromEntries(["originHeadSha","executionHeadSha","mergeSha","treeSha","graphRevision","manifestDigest","resultDigest"].map(o=>[o,w(e[o])])),r=Oe(e.checkedAt),a=ct(e.receiptRef),n=Se(e.gateIds).filter(o=>/^[a-z0-9-]+$/.test(o)).slice(0,128);if(!(Object.values(i).some(o=>!o)||!r||!a||n.length===0))return{schemaVersion:1,kind:e.kind,contract:e.contract,command:e.command,...i,checkedAt:r,receiptRef:a,gateIds:n}}function Ko(e){if(!h(e))return;const t={...te(e.active_epic_id??e.activeEpicId)?{active_epic_id:te(e.active_epic_id??e.activeEpicId)}:{},...te(e.active_story_id??e.activeStoryId)?{active_story_id:te(e.active_story_id??e.activeStoryId)}:{},...te(e.active_step_id??e.activeStepId)?{active_step_id:te(e.active_step_id??e.activeStepId)}:{},...te(e.session_id??e.sessionId)?{session_id:te(e.session_id??e.sessionId)}:{},...te(e.started_at??e.startedAt)?{started_at:te(e.started_at??e.startedAt)}:{}};return Object.keys(t).length>0?t:void 0}function Qo(e){const t=En(e.completionEvidence??e.completion_evidence,["prNumber","pr_number","prState","pr_state","pullRequestState","merged","mergedAt","issueNumber","issue_number","issueState","issue_state","closedAt"]),i=En(e.issueCloseAudit??e.issue_close_audit,["schema_version","event","storyId","epicId","issueNumber","closedAt","publicSafe","rawLogStorage"]),r=En(e.scopedCiEvidence??e.scoped_ci_evidence,["schema_version","storyId","epicId","prNumber","finalState","publicSafe","rawLogStorage"]);return{...typeof e.merged=="boolean"?{merged:e.merged}:{},...typeof e.safeToContinueYoloop=="boolean"?{safeToContinueYoloop:e.safeToContinueYoloop}:{},...typeof e.mergeBlockedRemotely=="boolean"?{mergeBlockedRemotely:e.mergeBlockedRemotely}:{},...te(e.physicalMergeStatus)?{physicalMergeStatus:te(e.physicalMergeStatus)}:{},...te(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)?{pr_state:te(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)}:{},...te(e.issue_state??e.issueState??e.workflow_issue_state)?{issue_state:te(e.issue_state??e.issueState??e.workflow_issue_state)}:{},...St(e.issue_number??e.issueNumber)?{issue_number:St(e.issue_number??e.issueNumber)}:{},...t?{completionEvidence:t}:{},...i?{issueCloseAudit:i}:{},...r?{scopedCiEvidence:r}:{}}}class st extends Error{reasonCode;constructor(t){super(t),this.name="StateSnapshotIntegrityError",this.reasonCode=t}}const Xo=new Set(["yolo","yoloop","finalize-epic","audit"]);function li(e){return typeof e=="string"&&Xo.has(e)}function Kn(e,t={}){const i=Q(e,".neocortex","state.json");if(!Mt(i))throw new st("git-lifecycle-state-missing");let r;try{r=JSON.parse(We(i,"utf8"))}catch{throw new st("git-lifecycle-state-corrupt")}if(!h(r)||!h(r.epics)||!h(r.stories))throw new st("git-lifecycle-state-shape-invalid");const a=Object.values(r.epics).some(n=>h(n)&&(n.branch_mode==="epic"||ve(n.execution_branch)!==void 0));if(a)try{gn(e,{required:!0})}catch(n){const o=n instanceof Error&&/^git-lifecycle-/.test(n.message)?n.message:"git-lifecycle-runtime-invalid";if(t.allowMissingRuntime&&o==="git-lifecycle-runtime-missing")return{lifecycleDeclared:!0,runtimeMissing:!0};throw new st(o)}return{lifecycleDeclared:a,runtimeMissing:!1}}function vn(e,t={}){const i=Q(e,".neocortex","state.json");if(!Mt(i)){if(t.epicAware&&!t.projectless)throw new st("git-lifecycle-state-missing");return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}let r,a;try{const E=We(i,"utf-8");a=Pe("sha256").update(E).digest("hex");const g=JSON.parse(E),y=h(g.epics)?g.epics:{},b=Object.values(y).some(R=>h(R)&&(R.branch_mode==="epic"||ve(R.execution_branch)!==void 0)),L=gn(e,{required:!!(t.epicAware&&b&&!t.projectless)});r=Vr(g,L);const T=h(r.stories)?r.stories:{},P=h(r.epics)?r.epics:{},C=h(g.stories)?g.stories:{};for(const[R,M]of Object.entries(T)){const N=h(M)?M:void 0;if(!N?.checkpoint)continue;const z=typeof N.epic_id=="string"?N.epic_id:R.split(".")[0],Z=h(P[z])?P[z]:void 0,j=ve(Z?.execution_branch);if(!j)continue;const V=Za(e,N.checkpoint,R,z,j,t.p205Authorities?.[R],Br(R,N,h(N.checkpoint)?N.checkpoint:void 0));if(V.kind==="integration-authorized")N.checkpoint_verification=V.verification,delete N.scheduling_checkpoint_evidence;else if(V.kind==="scheduling-only")N.scheduling_checkpoint_evidence=V.evidence,delete N.checkpoint,delete N.checkpoint_verification;else if(V.kind==="rejected"){N.checkpoint_verification=V.verification,delete N.scheduling_checkpoint_evidence;const ee=h(C[R])?C[R]:void 0;if(delete N.checkpoint,L.stories[R]?.checkpoint!==void 0)for(const G of["status","last_step","steps_completed"])ee&&Object.prototype.hasOwnProperty.call(ee,G)?N[G]=structuredClone(ee[G]):delete N[G];["done","completed","merged"].includes(String(N.status).toLowerCase())&&(N.status="blocked")}}}catch(E){if(t.epicAware&&!t.projectless){const g=E instanceof Error&&/^git-lifecycle-/.test(E.message)?E.message:"git-lifecycle-state-corrupt";throw new st(g)}return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}try{const E=jo(r);E.length>0&&Vo(E)}catch{}const n=r.config??r.project??{},o=r.stories??{},p={};for(const[E,g]of Object.entries(o)){const y=h(g.review_request)&&g.review_request.kind==="git-pull-request"?qo(g.review_request):Jn(g.review_request);p[E]={id:g.id??E,title:g.title,epic_id:g.epic_id,status:g.status??"backlog",...ti(g.source)?{source:ti(g.source)}:{},steps_completed:g.steps_completed??[],last_step:g.last_step??null,branch_name:g.branch_name??null,pr_number:g.pr_number,...Sn(g.branch_mode)?{branch_mode:Sn(g.branch_mode)}:{},...ri(g.checkpoint)?{checkpoint:ri(g.checkpoint)}:{},...ii(g.checkpoint_verification)?{checkpoint_verification:ii(g.checkpoint_verification)}:{},...ai(g.scheduling_checkpoint_evidence)?{scheduling_checkpoint_evidence:ai(g.scheduling_checkpoint_evidence)}:{},...y?{review_request:y}:{},...Jn(g.rollback_receipt)?{rollback_receipt:Jn(g.rollback_receipt)}:{},...St(g.workflow_issue)?{workflow_issue:St(g.workflow_issue)}:{},...Qo(g),depends_on:ei(g.depends_on),files_to_modify:Se(g.files_to_modify),...Go(g),risk:typeof g.risk=="string"?g.risk:void 0,blast_radius:typeof g.blast_radius=="number"?g.blast_radius:void 0}}const s=r.epics??{},l={};for(const[E,g]of Object.entries(s)){const y=Bo(g.lifecycle_classification),b=Ho(g.createEpicPlanning,E),L=b.checkpoint;let T,P,C,R;if(L&&h(g.createEpicPlanningClaim)&&typeof g.createEpicPlanningClaim.claimId=="string"&&h(g.createEpicPlanningPhysical))try{Sr(r,g.createEpicPlanningClaim.claimId,E,!0),T=JSON.parse(JSON.stringify(g.createEpicPlanningPhysical))}catch{}if(T&&h(g.createEpicPlanningClaim)&&typeof g.createEpicPlanningClaim.claimId=="string"&&h(g.createEpicPlanningResearchPhysical))try{vr(r,g.createEpicPlanningClaim.claimId,E),P=JSON.parse(JSON.stringify(g.createEpicPlanningResearchPhysical))}catch{}if(t.verifyPlanningGeneration&&L&&g.status==="generated"&&h(g.createEpicPlanningClaim)&&typeof g.createEpicPlanningClaim.claimId=="string"&&h(g.createEpicPlanningGenerationPhysical))try{if(Xi(e,g.createEpicPlanningClaim.claimId,E).stateSha256!==a)throw new Error("planning-generation-snapshot-raced");C=JSON.parse(JSON.stringify(g.createEpicPlanningGenerationPhysical)),T=JSON.parse(JSON.stringify(g.createEpicPlanningPhysical)),P=JSON.parse(JSON.stringify(g.createEpicPlanningResearchPhysical))}catch{}if(C&&h(g.createEpicPlanningClaim)&&typeof g.createEpicPlanningClaim.claimId=="string")try{const M=Cr(e,g.createEpicPlanningClaim.claimId,E);if(M.stateSha256!==a)throw new Error("planning-memory-snapshot-raced");R=JSON.parse(JSON.stringify(M))}catch{}l[E]={id:g.id??E,title:g.title,...L?{createEpicPlanning:L}:{},...b.diagnostic?{createEpicPlanningProjection:b.diagnostic}:{},...T?{createEpicPlanningPhysical:T}:{},...P?{createEpicPlanningResearchPhysical:P}:{},...C?{createEpicPlanningGenerationPhysical:C}:{},...R?{createEpicPlanningMemoryPhysical:R}:{},status:g.status,stories:g.stories,total_stories:g.total_stories,completed_stories:g.completed_stories,depends_on:ei(g.depends_on),...Sn(g.branch_mode)?{branch_mode:Sn(g.branch_mode)}:{},...ve(g.execution_branch)?{execution_branch:ve(g.execution_branch)}:{},...ve(g.origin_branch)?{origin_branch:ve(g.origin_branch)}:{},...ni(g.branch_lease)?{branch_lease:ni(g.branch_lease)}:{},...ci(g.origin_binding)?{origin_binding:ci(g.origin_binding)}:{},...si(g.aggregate_qa_receipt)?{aggregate_qa_receipt:si(g.aggregate_qa_receipt)}:{},...di(g.head_reconciliation_receipt)?{head_reconciliation_receipt:di(g.head_reconciliation_receipt)}:{},...St(g.pr_number)?{pr_number:St(g.pr_number)}:{},...te(g.physicalMergeStatus)?{physicalMergeStatus:te(g.physicalMergeStatus)}:{},...w(g.graph_revision)?{graph_revision:w(g.graph_revision)}:{},...pi(g.terminal_git_receipt)?{terminal_git_receipt:pi(g.terminal_git_receipt)}:{},...y?{lifecycle_classification:y}:{}}}const I=Ko(r.current_session??r.currentSession),S=h(r.archPlan)?In(r.archPlan.execution):void 0,u=r.epic_id_ledger,_=Array.isArray(u?.reserved_ids)?[...new Set(u.reserved_ids.filter(E=>typeof E=="string"&&/^P\d+$/.test(E)))].slice(0,2048):[];return{schema_version:typeof r.schema_version=="number"?r.schema_version:void 0,config:{project_name:n.project_name??n.name??"unknown",default_branch:n.default_branch??"main",language:n.language??"pt-BR",yolo_mode:n.yolo_mode,user_name:n.user_name,worktree_base:n.worktree_base,max_parallel_stories:n.max_parallel_stories,project_id:typeof n.project_id=="string"?n.project_id:void 0},stories:p,epics:l,..._.length>0?{epic_id_ledger:{schema_version:1,reserved_ids:_}}:{},...I?{current_session:I}:{},...S?{archPlan:{execution:S}}:{}}}const Qn=[["P222.01","fbc3176b33687b13a8fadf8c7ea7cc06b6b6c500"],["P222.02","c7d3feb9a168f9e15b35516a972c767f3aa357da"],["P222.03","4d9bd4f2a1a3a1dc6399c572eb84b8b74c017806"],["P222.04","66590ef2f706c9d036f42edf5e517b237724f74f"],["P222.05","3ee2662538311e9788796340ed11b65864a8d8d5"],["P222.06","8660d07e3f68503a9ceb24dc138d24f62ab6cb45"],["P222.07","d99c80feacee8ea4033aa3322990147fffa2df91"],["P222.08","1f9e37dc922d87908efefb9595db32d32db30b00"],["P222.09","5ae12e485900992658e346cf3e38568fda1c2eeb"],["P222.10","6c5b8dc4f03d629fea4b62a33f4794af8e27e4f0"],["P222.11","cfe90f2f955c0027c57e4c621141d17912db65cc"],["P222.12","65f253c5cb600a8ee1dd94a1efdfef2fa5cd1629"],["P222.13","1e78c75b393515803a55d1a9b63a7fec23f710c9"],["P222.14","3f3e0bfd247a8581170df2a23c89497b5ae3641e"],["P222.15","1fd6dd25fffa5714d4ffa8b4303735e417f93de6"]],Xn="6a41a47ff2521f80c2296ed811b0f0b304c54750",Zn="dbc6d4670b2b7868a01973b1240e24589f1c5b7d",ui="30dccfff07f9c969be11ae1d28e62a09731a0768";function Zo(e,t){try{const i=t.indexOf(ui);if(i<1||t[i-1]!==Xn)return new Map;const r=Ge("git",["show","--no-patch","--format=%P",ui],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim(),a=Ge("git",["show","--no-patch","--format=%P",Zn],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim();if(r!==`${Xn} ${Zn}`||a!==`${Qn.at(-1)[1]} ${Xn}`)return new Map;const n=Ge("git",["rev-list","--first-parent","--reverse",Zn],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
9
+ `),o=new Map;let p=-1;for(const[s,[l,I]]of Qn.entries()){const S=n.indexOf(I);if(S<=p)return new Map;p=S,o.set(l,{headSha:I,position:s-Qn.length})}return o}catch{return new Map}}async function ec(e,t,i){if(!li(i))return{};if(i==="audit"||i==="yoloop")return{};if(Tr(t,i))return{};try{const r=JSON.parse(We(Q(e,".neocortex","state.json"),"utf8")),a=gn(e,{required:!0}),n=Vr(r,a),o=h(n.stories)?n.stories:{},p=h(n.epics)?n.epics:{},s=Ge("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8"}).trim(),l=Ge("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8"}).trim(),I=Ge("git",["rev-list","--first-parent","--reverse",s],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
10
+ `).filter(Boolean),S=new Map(I.map((C,R)=>[C,R])),u=Zo(e,I),_=t.match(/(?:^|\s)@?docs\/stories\/([A-Za-z][A-Za-z0-9._-]*)\.story\.md(?:\s|$)/)?.[1],E=i==="yoloop"?t.match(/(?:^|[\s/@])epic-(P[1-9][0-9]*)\.md(?:\s|$)/i)?.[1]?.toUpperCase():void 0,g=new Set,y=Object.entries(o).flatMap(([C,R])=>{if(_&&C!==_)return[];const M=h(R)?R:void 0,N=h(M?.checkpoint)?M.checkpoint:void 0;if(!N)return[];const z=typeof M?.epic_id=="string"?M.epic_id:C.split(".")[0];if(E&&z!==E)return[];const Z=w(N?.headSha),j=z==="P222"?u.get(C):void 0,V=S.get(Z??"")??(j&&j.headSha===Z?j.position:void 0);if(!Z||Z.length<40||V===void 0)return g.add(z),[];const ee=h(p[z])?p[z]:void 0;if(ee?.branch_mode!=="epic"||ve(ee.execution_branch)!==l||ve(N.branch)!==l)return g.add(z),[];const G=w(N.graphRevision);if(!G||G.length!==64)return g.add(z),[];const lt=w(N.claimRevision),Ye=[...Br(C,M,N)].sort(),he=oo(e,N,C,z,l,Ye);if(!he&&lt){if(Ye.length===0)return g.add(z),[];const O=Ge("git",["diff-tree","--no-commit-id","--name-only","-r","-z",Z],{cwd:e,encoding:"utf8"}).split("\0").filter(Boolean);let H=[];if(N.rootMemoryEffect!==void 0)try{H=co(e,N.rootMemoryEffect,{storyId:C,executionBranch:l,baseSha:String(N.baseSha),headRef:Z,childPaths:Ye}).files.map(se=>se.path)}catch{return g.add(z),[]}if(O.length===0||O.some(se=>!Ye.some(tt=>tt===se||tt.endsWith("/")&&se.startsWith(tt))&&!H.includes(se)))return g.add(z),[];const Ct=Pe("sha256").update(Ye.join("\0")).digest("hex"),De=Pe("sha256").update(JSON.stringify(Ye)).digest("hex");if(lt!==Ct&&lt!==De)return g.add(z),[]}else if(!he)return g.add(z),[];return G?.length===64?[{storyId:C,epicId:z,graphRevision:G,checkpointHead:Z,position:V}]:[]}),b=new Set(g);for(const[C,R]of Object.entries(p)){const M=h(R)?R:void 0,N=Array.isArray(M?.stories)?M.stories.filter(V=>typeof V=="string"):Object.keys(o).filter(V=>V.startsWith(`${C}.`)),z=y.filter(V=>V.epicId===C),Z=N.filter(V=>z.some(ee=>ee.storyId===V)),j=[...z].sort((V,ee)=>V.position-ee.position).map(V=>V.storyId);(JSON.stringify(Z)!==JSON.stringify(j)||new Set(j).size!==j.length)&&b.add(C)}const L={},T=[...new Set(y.filter(C=>!b.has(C.epicId)).map(C=>C.graphRevision))],P=T.length>0?await no(e,{headSha:s,graphRevisions:T}):new Map;for(const C of y){if(b.has(C.epicId))continue;const R=P.get(C.graphRevision);if(!R)throw new Error("p205-transient-authority-missing");L[C.storyId]=R}return await tc({projectRoot:e,commandId:i,targetEpicId:E,currentHead:s,epics:p,candidates:y,authorities:L}),L}catch(r){const a=r instanceof Error&&/^(?:p205|git-lifecycle)-[a-z0-9-]+$/.test(r.message)?r.message:"p205-transient-execution-failed";return process.stderr.write(`[Neocortex] ${a}. Checkpoint projection remains fail-closed.
11
+ `),{}}}async function tc(e){if(e.commandId!=="yoloop"||!e.targetEpicId)return;const t=e.epics[e.targetEpicId],i=h(t)?t:void 0,r=h(i?.aggregate_qa_receipt)?i.aggregate_qa_receipt:void 0,a=w(i?.graph_revision);if(!r||!a||a.length!==64||r.schemaVersion!==1||r.evidenceVersion!=="p205-execution-v2"||r.producer!=="local-yolo-tdd"||r.contract!=="P205-CI-02"||r.command!==Qt||r.verdict!=="passed"||r.executionHeadSha!==e.currentHead||r.graphRevision!==a||!Array.isArray(r.gateIds)||r.gateIds.length===0||!r.gateIds.every(S=>typeof S=="string")||typeof r.manifestDigest!="string"||!/^[a-f0-9]{64}$/i.test(r.manifestDigest)||typeof r.resultDigest!="string"||!/^[a-f0-9]{64}$/i.test(r.resultDigest)||typeof r.receiptRef!="string"||!/^local-yolo-tdd:[a-f0-9]{64}$/i.test(r.receiptRef))return;const n=r.gateIds,o=`local-yolo-tdd:${Pe("sha256").update(["epic-aggregate-p205-execution-v2",Qt,e.currentHead,a,r.manifestDigest,n.join(","),r.resultDigest].join("\0")).digest("hex")}`;if(r.receiptRef!==o)return;const p=e.candidates.find(S=>S.epicId===e.targetEpicId&&S.graphRevision===a&&e.authorities[S.storyId]),s=p?ao(e.authorities[p.storyId]):void 0;if(!s||s.executionHeadSha!==e.currentHead||s.graphRevision!==a||s.manifestDigest!==r.manifestDigest||!nc(s.gateIds,n))return;const l=`local-yolo-tdd:${Pe("sha256").update(["epic-aggregate-p205-execution-v2",Qt,e.currentHead,a,s.manifestDigest,s.gateIds.join(","),s.resultDigest].join("\0")).digest("hex")}`,I=r.receiptRef;await io(e.projectRoot,S=>{const u=eo(S,e.targetEpicId),_=h(u.aggregate_qa_receipt)?u.aggregate_qa_receipt:void 0;!_||_.executionHeadSha!==e.currentHead||_.graphRevision!==a||_.receiptRef!==I||(u.aggregate_qa_receipt={schemaVersion:1,evidenceVersion:"p205-execution-v2",producer:"local-yolo-tdd",contract:"P205-CI-02",command:Qt,verdict:"passed",executionHeadSha:e.currentHead,graphRevision:a,manifestDigest:s.manifestDigest,resultDigest:s.resultDigest,checkedAt:s.executedAt,receiptRef:l,gateIds:[...s.gateIds]})})}function nc(e,t){if(e.length!==t.length)return!1;const i=[...t].sort();return[...e].sort().every((r,a)=>r===i[a])}function vd(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 hi="neocortex:menu:cache";async function rc(e){try{const t=await e.get(hi);if(!t)return null;const i=JSON.parse(t);return i.version!==Pt||Date.now()-i.cachedAt>Gr?null:i}catch{return null}}async function ic(e,t,i){try{const r={instructions:t,metadata:i,cachedAt:Date.now(),version:Pt};await e.set(hi,JSON.stringify(r),Gr),ac()}catch{}}function ac(){try{Mt(Hr)&&Nn(Hr)}catch{}}function gi(e){return e.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>Mn(),()=>Mn({strictReadOnly:!0}))}async function fi(e,t,i){const r=i.mode==="strict";try{let a;if(r&&t)a=new Dn({cacheDir:Un,passphrase:t,strictReadOnly:!0});else if(r)a=new wr;else if(t){const I=Q(fn,"cache");a=new Dn({cacheDir:I,passphrase:t})}else process.stderr.write(`[neocortex] Warning: No license key in config. Run "neocortex activate" to re-authenticate.
12
+ `),a=new wr;const n=Dr(i,a,"auth-cache"),o=Dr(i,a,"tier-cache"),p=new ra({serverUrl:e,licenseKey:t??"",cacheProvider:n,strictReadOnly:r});let s;if(r){const I=await p.inspectToken();if(I.status!=="authenticated")return I;s=I.token}else s=await p.getToken();if(!s)return t?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"};const l=new ia({cacheProvider:o,licenseClient:p});return{status:"authenticated",token:s,client:p,tierClient:l}}catch{return t?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"}}}let mi=!1;function oc(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 yi=3,Cn=50;function cc(e){return new Promise(t=>setTimeout(t,e))}function sc(e,t,i){return e.status>=500&&e.status<=599?!0:i&&e.status===409&&t.error_code==="SIGNATURE_REPLAYED"}async function Xt(e,t,i,r,a={}){const n=Math.max(1,Math.min(a.maxAttempts??yi,yi)),o=a.sleep??cc;let p=r,s=!1,l=!1,I=0;for(let S=1;S<=n;S+=1){const u=Math.max(Math.floor(Date.now()/1e3),I+1);I=u;const _=dc(t,i,p,{nowSeconds:u}),E=new AbortController,g=setTimeout(()=>E.abort(),Wr);try{const y=await fetch(`${e}${t}`,{method:"POST",headers:_.headers,body:_.body,signal:E.signal});if(a.admitResponseBeforeBodyRead&&!a.admitResponseBeforeBodyRead(y))return{response:y,text:"",parsed:{},networkFailure:!1,responseAdmissionRejected:!0};const b=await y.text().catch(()=>""),L=y.ok&&a.deferSuccessfulJsonParsing?{}:(()=>{try{return b?JSON.parse(b):{}}catch{return{}}})();if(y.status===401&&!s&&a.refreshToken&&(L.fallback_action==="refresh_token"||L.fallback_action==="re_authenticate")){s=!0;const T=await a.refreshToken();if(T&&S<n){p=T,a.onTokenChanged?.(T),await o(Cn*S);continue}}if(y.status===401&&L.error_code==="SIGNATURE_EXPIRED"&&!l&&S<n){l=!0,await o(Cn*S);continue}if(S<n&&sc(y,L,a.allowReplayRetry===!0)){await o(Cn*S);continue}return{response:y,text:b,parsed:L,networkFailure:!1}}catch{if(S<n){await o(Cn*S);continue}return{text:"",parsed:{},networkFailure:!0}}finally{clearTimeout(g)}}return{text:"",parsed:{},networkFailure:!0}}function dc(e,t,i,r={}){const a=Buffer.from(JSON.stringify(t),"utf8"),n=Aa({method:"POST",target:e,body:a,bearerToken:i,clientVersion:Pt,nowSeconds:r.nowSeconds,nonceBytes:r.nonceBytes});return{body:n.body,headers:{...n.headers,Authorization:`Bearer ${i}`}}}function Ii(e){return Pe("sha256").update(e).digest("hex")}function pc(){const e=Number(process.env.NEOCORTEX_INVOKE_CHUNK_BYTES??"49152");return Number.isFinite(e)&&e>=1024&&e<=98304?Math.floor(e):49152}function lc(e,t,i){return`args-${Pe("sha256").update("invoke-materialization:v1").update(e).update(String(t)).update(JSON.stringify(i)).digest("hex")}`}async function Ei(e,t,i,r,a={}){const n=await Xt(e,t,i,r,{...a,allowReplayRetry:!0});if(n.networkFailure||!n.response)throw new Error("NETWORK_ERROR: materialization request failed after bounded retries");const{response:o,parsed:p}=n;if(!o.ok){const s=typeof p.error_code=="string"?p.error_code:`HTTP_${o.status}`,l=typeof p.message=="string"?p.message:"materialization upload failed";throw new Error(`${s}: ${l}`)}return p}async function uc(e,t,i,r){const a=Buffer.from(t,"utf8"),n=pc(),o=[];for(let E=0,g=0;E<a.byteLength;E+=n,g++){const y=a.subarray(E,Math.min(E+n,a.byteLength));o.push({index:g,sha256:Ii(y),byteLength:y.byteLength})}const p=Ii(a),s=lc(p,a.byteLength,o),l=Number(process.env.NEOCORTEX_INVOKE_CHUNK_TTL_SECONDS??"900");let I=i;const S={refreshToken:r,onTokenChanged(E){I=E}};for(const E of o){const g=E.index*n,y=a.subarray(g,g+E.byteLength);await Ei(e,"/api/v1/invoke/materialization/chunks",{manifestId:s,index:E.index,sha256:E.sha256,byteLength:E.byteLength,contentBase64:y.toString("base64"),ttlSeconds:l,idempotencyKey:`${s}:${E.index}:${E.sha256}`},I,S)}const _=(await Ei(e,"/api/v1/invoke/materialization/manifests",{manifestId:s,sha256:p,byteLength:a.byteLength,chunkCount:o.length,chunks:o,ttlSeconds:l,retry:{attempt:1,budget:3,idempotencyKey:s}},I,S)).argsRef;if(!_?.manifestId)throw new Error("MATERIALIZATION_RESPONSE_INVALID: missing argsRef");return{argsRef:_,chunks:o}}function Ht(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function hc(...e){const t=new Set,i=[];for(const r of e)for(const a of r??[]){const n=te(a);if(!(!n||t.has(n))&&(t.add(n),i.push(n),i.length>=16))return i}return i}function gc(e){const t=e.graphRetrieval;if(!h(t))return{accepted:!1,itemCount:0};const i=Array.isArray(t.items)?t.items.length:0;return{accepted:i>0||typeof t.retrievalId=="string"||t.accepted===!0,itemCount:i}}function er(e,t=Ht(e),i=[],r={}){const a=e.stateSnapshot.scope,n=Object.keys(e.stateSnapshot.stories).length,o=Object.keys(e.stateSnapshot.epics).length,p=a?.kind??"full";return{schemaVersion:1,payloadBytes:t,limitBytes:r.limitBytes??Yr,warningThresholdBytes:r.warningThresholdBytes??$n,scope:{kind:p,...a?.projectionMode?{projectionMode:a.projectionMode}:{},commandId:a?.commandId??null,stateProjectionPolicy:a?.stateProjectionPolicy??null},includedStories:a?.includedStoryCount??n,omittedStories:a?.omittedStoryCount??0,includedEpics:a?.includedEpicCount??o,omittedEpics:a?.omittedEpicCount??0,graphRetrieval:gc(e.stateSnapshot),reasonCodes:hc(i,a?.reasonCodes),publicSafe:!0}}function fc(e){const t=h(e.budget)?e.budget:void 0,i=typeof t?.maxPayloadBytes=="number"&&Number.isFinite(t.maxPayloadBytes)?t.maxPayloadBytes:12*1024;return Math.max(1024,Math.min(i,12*1024))}function mc(e){return h(e)?{stableId:te(e.stableId)??"unknown",...h(e.source)?{source:e.source}:{},reasonCode:"budget_exceeded"}:{stableId:"unknown",reasonCode:"budget_exceeded"}}function Si(e){const t=Array.isArray(e)?e.filter(i=>typeof i=="string"):[];return t.includes("budget_exceeded")?t:[...t,"budget_exceeded"]}function yc(e){const t=e.graphRetrieval;if(!h(t)||!Array.isArray(t.items))return e;const i=fc(t);let r=[...t.items],a=Array.isArray(t.skipped)?[...t.skipped]:[],n=t;for(;Buffer.byteLength(JSON.stringify(n),"utf8")>i&&r.length>0;){const o=r.pop();a=[...a,mc(o)].slice(-32),n={...t,items:r,skipped:a,warnings:Si(t.warnings)}}return Buffer.byteLength(JSON.stringify(n),"utf8")>i&&(n={...t,query:typeof t.query=="string"?t.query.slice(0,240):t.query,items:[],skipped:[],warnings:Si(t.warnings)}),n===t?e:{...e,graphRetrieval:n}}function tr(e,t={}){const i=t.limitBytes??Yr,r=t.warningThresholdBytes??Math.floor(i*qr),a=Ht(e);if(a<i)return{body:e,degraded:!1,telemetry:er(e,a,["payload-within-limit"],{limitBytes:i,warningThresholdBytes:r})};let n={...e,stateSnapshot:pa(e.stateSnapshot)},o=["payload-size-guardrail","state-degraded"],p=Ht(n);p>=i&&(n={...n,stateSnapshot:yc(n.stateSnapshot)},o=[...o,"graph-retrieval-budget-enforced"],p=Ht(n));const s=er(n,p,o,{limitBytes:i,warningThresholdBytes:r});if(p>=i){const l=n.stateSnapshot.scope?.projectionMode;throw l==="yolo-story"||l==="yoloop-target"||l==="yoloop-session"||l==="yoloop-discovery"||l==="structural-required"?new qn(s):new Yn(s)}return{body:n,degraded:!0,telemetry:s}}function vi(e){const t=e.stateSnapshot.scope?.commandId??"resolved-command";return e.args!==void 0?t:`${t}:argsRef`}function Ic(e){const t=Ht(e);if(t<$n)return t;const i=er(e,t,["payload-warning-threshold"]);return process.stderr.write(`[Neocortex] invoke payload near server limit: trigger=${vi(e)} scope=${i.scope.kind} mode=${i.scope.projectionMode??i.scope.kind} payloadBytes=${i.payloadBytes} limit=${i.limitBytes} includedStories=${i.includedStories} omittedStories=${i.omittedStories} includedEpics=${i.includedEpics} omittedEpics=${i.omittedEpics} graphRetrieval.accepted=${i.graphRetrieval.accepted} graphRetrieval.itemCount=${i.graphRetrieval.itemCount} reasonCodes=${i.reasonCodes.join(",")||"none"}
13
+ `),t}function Ci(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"}
14
+ `)}async function Ec(e){const t=ya(e.args,{platformTarget:e.platformTarget,environment:e.environment??process.env});if(t.action==="skipped")return{shouldContinue:!0,attachToRequest:Sc(t),metadata:_i(t)};const i=e.bootstrapper??Ea;let r;try{r=await i({projectRoot:e.projectRoot,env:e.environment??process.env,effectAuthority:e.effectAuthority})}catch{r={ok:!1,attempted:!0,installed:!1,started:!1,cached:!1,projectKey:"unknown",reasonCodes:[Ia.UNEXPECTED_ERROR],publicSummary:"runner scheduler bootstrap stopped unexpectedly.",publicSafe:!0}}const a=_i(t,r);if(r.ok)return{shouldContinue:!0,attachToRequest:!0,metadata:a};const n=a.reasonCodes.slice(0,5).join(",");return t.failurePolicy==="fail-open"?{shouldContinue:!0,attachToRequest:!0,metadata:{...a,failOpenWarning:!0},warning:`Runner auto-bootstrap warning (${n}); continuing fail-open for operator command.`}:{shouldContinue:!1,attachToRequest:!1,metadata:a,errorCode:"RUNNER_BOOTSTRAP_REQUIRED_FAILED",error:`Runner auto-bootstrap required but failed (${n}). Run neocortex-runner doctor or retry after resolving scheduler setup.`,exitCode:1}}function Sc(e){return!e.reasonCodes.includes(ma.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:Me([...e.reasonCodes,...t?.reasonCodes??[]]),publicSummary:t?.publicSummary??e.publicSummary,publicSafe:!0}}function Me(e){return Array.from(new Set(e.map(t=>t.slice(0,120))))}function _n(e,t,i){const r=Math.floor(e??t);return Number.isFinite(r)?Math.max(1,Math.min(i,r)):t}function wn(e,t){const i=process.env[e];if(!i)return t;const r=Number(i);return Number.isFinite(r)?r:t}function q(e,t=Zr){const i=typeof e=="string"&&e.trim().length>0?e.trim():"unknown",r=ze(i,t),a=Po.test(r)?Et:r;return a.length<=t?a:`${a.slice(0,t)}\u2026[TRUNCATED:${a.length-t}]`}function nr(e,t=Zr){if(!(typeof e!="string"||e.trim().length===0))return q(e,t)}function rr(e,t,i,r){const a=nr(e?.targetId??t,120),n=e?.selectorKind??(a?ar(a):void 0),o=(e?.relatedJobIds??[]).map(p=>nr(p,120)).filter(p=>!!p);return{schemaVersion:1,contractVersion:"continuity-v1",targetResolutionState:i,...n?{targetKind:n}:{},...a?{targetId:a}:{},...t?{targetJobId:q(t,120)}:{},...e?.jobId?{jobId:q(e.jobId,120)}:{},...e?.goalId?{goalId:q(e.goalId,120)}:{},...e?.loopId?{loopId:q(e.loopId,120)}:{},...o.length>0?{relatedJobIds:o}:{},relatedJobCount:o.length,reasonCodes:Me(r.length>0?r:[Y.OK]),publicSafe:!0}}function dt(e,t,i,r,a=[]){const n=(e?.redactions?.length??0)>0,o=e?n?"unsafe":i&&r===0?"empty":"available":"unavailable",p=nr(t[t.length-1]?.eventId,120),s=a.length>0?a:o==="unavailable"?[Y.WATCH_SNAPSHOT_UNAVAILABLE]:o==="empty"?[Y.WATCH_NO_SUMMARIES_YET]:[Y.OK];return{schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:o,...e?.generatedAt?{generatedAt:q(e.generatedAt,80)}:{},renderedSummaryCount:r,...p?{latestEventId:p}:{},reasonCodes:Me(s),publicSafe:!0}}function Xe(e,t,i,r,a=[],n){const o=r[r.length-1],p=i??o?.cursor,s=!!(p&&p!==t&&r.length>0),l=n??(s?"advanced":t||p?"unchanged":"not_started"),I=a.length>0?a:l==="advanced"?[Y.WATCH_CURSOR_ADVANCED]:l==="unavailable"?[Y.WATCH_EVIDENCE_UNAVAILABLE]:[Y.WATCH_CURSOR_UNCHANGED];return{schemaVersion:1,contractVersion:"continuity-v1",cursorState:l,...e?{initialCursor:q(e,200)}:{},...t?{currentCursor:q(t,200)}:{},...p?{nextCursor:q(p,200)}:{},cursorAdvanced:s,...o?.eventId?{eventId:q(o.eventId,120)}:{},reasonCodes:Me(I),publicSafe:!0}}function Ze(e){const t=e.targetEvidence;return{type:"watch_status",schemaVersion:1,contractVersion:"continuity-v1",recordType:"watch_status",command:"invoke",operation:"watch",watchStatus:e.watchStatus,active:e.active,...t?.targetResolutionState?{targetResolutionState:t.targetResolutionState}:{},...t?.targetKind?{targetKind:t.targetKind}:{},...t?.targetId?{targetId:t.targetId}:{},...t?{targetEvidence:t}:{},...e.snapshotEvidence?{snapshotEvidence:e.snapshotEvidence}:{},...e.cursorEvidence?{cursorEvidence:e.cursorEvidence}:{},...e.stopReason?{stopReason:e.stopReason}:{},reasonCodes:Me([...e.reasonCodes??[],...t?.reasonCodes??[],...e.snapshotEvidence?.reasonCodes??[],...e.cursorEvidence?.reasonCodes??[]]),generatedAt:q(e.generatedAt??new Date().toISOString(),80),publicSafe:!0}}function vc(e){const t=e.targetKind&&e.targetId?`${e.targetKind}/${e.targetId}`:e.targetId??"[unresolved]",i=e.snapshotEvidence?.renderedSummaryCount??0,r=e.targetEvidence?.relatedJobCount??0,a=e.cursorEvidence?.cursorState??"unavailable",n=e.cursorEvidence?.currentCursor??"[none]",o=e.cursorEvidence?.nextCursor??"[none]",p=e.snapshotEvidence?.snapshotStatus??"not_requested",s=e.snapshotEvidence?.generatedAt??e.generatedAt;return[`[watch-status] ${e.targetResolutionState==="unresolved"||e.stopReason==="target_unresolved"?"unresolved-target":i===0&&(e.watchStatus==="waiting"||e.watchStatus==="active")?"no-new-summary":e.watchStatus==="stopped"?"stopped":"lifecycle"}`,`status=${e.watchStatus}`,`active=${e.active}`,`target=${t}`,`resolution=${e.targetResolutionState??"unavailable"}`,`relatedJobs=${r}`,`summaries=${i}`,`snapshot=${p}`,`generatedAt=${s}`,`cursor=${a}`,`current=${q(n,200)}`,`next=${q(o,200)}`,`advanced=${e.cursorEvidence?.cursorAdvanced??!1}`,`stop=${e.stopReason??"not_stopped"}`,`reasons=${e.reasonCodes.join(",")}`].join(" ")}function et(e,t,i,r=!1){if(r){const a={type:"watch_status",watchStatus:e.watchStatus,active:e.active,renderedSummaryCount:e.snapshotEvidence?.renderedSummaryCount??0,stopReason:e.stopReason??"not_stopped",protectedProjection:!0,publicSafe:!0};i.write(t==="json"?`${JSON.stringify(a)}
15
15
  `:`[watch-status] status=${a.watchStatus} active=${a.active} summaries=${a.renderedSummaryCount} stop=${a.stopReason}
16
16
  `);return}if(t==="json"){i.write(JSON.stringify(e)+`
17
- `);return}i.write(Ec(e)+`
18
- `)}function Sc(e,t,i){return{continuityInvokeWatch:{schemaVersion:1,contractVersion:"continuity-v1",command:"invoke",operation:"watch",watchStatus:e.watchStatus,stopReason:e.stopReason??"not_stopped",targetResolutionState:e.targetResolutionState,targetKind:e.targetKind,targetId:e.targetId,snapshotStatus:e.snapshotEvidence?.snapshotStatus,snapshotGeneratedAt:e.snapshotEvidence?.generatedAt,renderedSummaryCount:e.snapshotEvidence?.renderedSummaryCount??t,cursorState:e.cursorEvidence?.cursorState,cursorAdvanced:e.cursorEvidence?.cursorAdvanced,summariesEmitted:t,polls:i,statusRecord:e,publicSafe:!0}}}function pt(e,t,i,r,a=!1){return a?{status:e,summariesEmitted:t,polls:i,reasonCodes:[],watchStatus:r.watchStatus,stopReason:r.stopReason,metadata:{continuityInvokeWatch:{schemaVersion:1,contractVersion:"continuity-v1",command:"invoke",operation:"watch",watchStatus:r.watchStatus,stopReason:r.stopReason??"not_stopped",summariesEmitted:t,polls:i,protectedProjection:!0,publicSafe:!0}},publicSafe:!0}:{status:e,summariesEmitted:t,polls:i,reasonCodes:r.reasonCodes,watchStatus:r.watchStatus,stopReason:r.stopReason,targetEvidence:r.targetEvidence,snapshotEvidence:r.snapshotEvidence,cursorEvidence:r.cursorEvidence,statusRecord:r,metadata:Sc(r,t,i),publicSafe:!0}}function vc(e){const t=e.reasonCode?` reason=${Y(e.reasonCode,80)}`:"",i=e.goalId?` goal=${Y(e.goalId,100)}`:"",r=e.loopId?` loop=${Y(e.loopId,100)}`:"";return`[watch] ${Y(e.createdAt,80)} event=${Y(e.eventId,120)} job=${Y(e.jobId,100)}${i}${r} execution=${Y(e.executionId,120)}${t} -- ${Y(e.publicSummary)}`}function Cc(e){return{type:"processing_summary",source:"local_continuity_sqlite",eventId:Y(e.eventId,120),jobId:Y(e.jobId,100),...e.goalId?{goalId:Y(e.goalId,100)}:{},...e.loopId?{loopId:Y(e.loopId,100)}:{},executionId:Y(e.executionId,120),...e.reasonCode?{reasonCode:Y(e.reasonCode,80)}:{},createdAt:Y(e.createdAt,80),publicSummary:Y(e.publicSummary),publicSafe:!0}}function _c(e,t,i,r=!1){if(r){i.write(t==="json"?`${JSON.stringify({type:"processing_summary",source:"local_continuity_sqlite",publicSummary:"A local processing update is available.",protectedProjection:!0,publicSafe:!0})}
19
- `:`[watch] A local processing update is available.
20
- `);return}if(t==="json"){i.write(JSON.stringify(Cc(e))+`
21
17
  `);return}i.write(vc(e)+`
22
- `)}function rr(e){return Ao.has(e.status)}function wc(e,t,i){if(t){const a=e.find(n=>n.jobId===t);return!!(a&&rr(a))}return i<=0?!1:e.filter(a=>!rr(a)).length===0}function Rc(e,t,i,r){return i<r?!1:t?!e.some(a=>a.jobId===t&&!rr(a)):e.length===0}function Ac(e,t){return t?.aborted?Promise.resolve():new Promise(i=>{const r=setTimeout(a,e);function a(){clearTimeout(r),t?.removeEventListener("abort",a),i()}t?.addEventListener("abort",a,{once:!0})})}function bc(e){return e.includes(ke.MALFORMED)?"malformed":e.includes(ke.AMBIGUOUS)?"ambiguous":e.includes("watch-target-multiple")?"multiple":e.includes("watch-evidence-unsafe")?"unsafe":e.includes(ke.MISSING)||e.includes(_e.TARGET_UNRESOLVED)?"unresolved":"unavailable"}function _i(e,t){const i=t?en(t):void 0,r=Me([...e,_e.TARGET_UNRESOLVED,F.WATCH_TARGET_UNRESOLVED]),a=nr(i,i?.targetId,bc(r),r),n=dt({generatedAt:new Date().toISOString()},[],!1,0,[F.WATCH_TARGET_UNRESOLVED]),o=Xe(void 0,void 0,void 0,[],[F.WATCH_TARGET_UNRESOLVED],"unavailable");return Ze({watchStatus:"blocked",active:!1,targetEvidence:a,snapshotEvidence:n,cursorEvidence:o,stopReason:"target_unresolved",reasonCodes:r,generatedAt:n.generatedAt})}function xc(e,t,i,r,a=!1){const n=_i(e,Ri(t));return et(n,i,r,a),pt("target-unresolved",0,0,n,a)}async function Tc(e){if(e.signal?.aborted){const P=nr(e.target??en(e.targetJobId),e.targetJobId,e.target??e.targetJobId?"resolved":"unresolved",[_e.CANCELLED]),C=dt(void 0,[],!1,0),R=Xe(e.initialCursor,e.initialCursor,e.initialCursor,[],[_e.CANCELLED],"unavailable"),M=Ze({watchStatus:"stopped",active:!1,targetEvidence:P,snapshotEvidence:C,cursorEvidence:R,stopReason:"cancelled",reasonCodes:[_e.CANCELLED]});return pt("cancelled",0,0,M,e.protectedOutput)}const t=e.target??en(e.targetJobId),i=e.targetJobId??t?.targetId,r=e.stdout??process.stdout;if(!t){const P=_i([ke.MISSING,_e.TARGET_UNRESOLVED]);return et(P,e.format,r,e.protectedOutput),pt("target-unresolved",0,0,P,e.protectedOutput)}const a=Cn(e.limit??_n("NEOCORTEX_INVOKE_WATCH_LIMIT",Pr),Pr,50),n=Math.max(50,Cn(e.pollIntervalMs??_n("NEOCORTEX_INVOKE_WATCH_POLL_INTERVAL_MS",Nr),Nr,6e4)),o=Cn(e.maxIdlePolls??_n("NEOCORTEX_INVOKE_WATCH_MAX_IDLE_POLLS",kr),kr,120),p=Cn(e.maxPolls??_n("NEOCORTEX_INVOKE_WATCH_MAX_POLLS",Or),Or,86400),s=e.sleep??Ac;let l=e.initialCursor,I=0,S=0,u=0;const _=nr(t,i,"resolved",[F.OK]),E={schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:"pending",renderedSummaryCount:0,reasonCodes:[F.WATCH_RENDER_PENDING],publicSafe:!0},g=Xe(e.initialCursor,l,l,[],e.initialCursor?[F.WATCH_CURSOR_UNCHANGED]:[F.WATCH_NO_SUMMARIES_YET],e.initialCursor?"unchanged":"not_started");et(Ze({watchStatus:"active",active:!0,targetEvidence:_,snapshotEvidence:E,cursorEvidence:g,stopReason:"not_stopped",reasonCodes:[F.OK]}),e.format,r,e.protectedOutput);let y;try{y=await Ea({projectRoot:e.projectRoot,strictReadOnly:e.strictReadOnly})}catch{const P=dt(void 0,[],!1,I,[F.WATCH_SNAPSHOT_UNAVAILABLE]),C=Xe(e.initialCursor,l,l,[],[F.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),R=Ze({watchStatus:"blocked",active:!1,targetEvidence:_,snapshotEvidence:P,cursorEvidence:C,stopReason:"unavailable_evidence",reasonCodes:[_e.STORE_UNAVAILABLE]});return et(R,e.format,r,e.protectedOutput),pt("store-unavailable",I,u,R,e.protectedOutput)}try{for(;!e.signal?.aborted&&u<p;){u+=1;const P=l,C=y.collectProcessingOutputSummaryCursor({...l?{cursor:l}:{},...t?{target:t}:{},...i?{jobId:i}:{},limit:a}),R=y.collectSnapshot({jobLimit:50,processingSummaryLimit:1}),M=R.jobs;if(C.summaries.length>0){for(const Z of C.summaries)_c(Z,e.format,r,e.protectedOutput),I+=1;l=C.nextCursor??C.summaries[C.summaries.length-1]?.cursor??l,S=0}else l=C.nextCursor??l,S+=1;const N=dt(R,C.summaries,!0,C.summaries.length),q=Xe(e.initialCursor,P,l,C.summaries,C.summaries.length>0?[F.WATCH_CURSOR_ADVANCED]:[F.WATCH_NO_SUMMARIES_YET]);if(et(Ze({watchStatus:C.summaries.length>0?"polling":"waiting",active:!0,targetEvidence:_,snapshotEvidence:N,cursorEvidence:q,stopReason:"not_stopped",reasonCodes:C.summaries.length>0?[F.WATCH_CURSOR_ADVANCED]:[F.WATCH_NO_SUMMARIES_YET],generatedAt:R.generatedAt}),e.format,r,e.protectedOutput),!C.hasMore&&wc(M,i,I)){const Z=dt(R,C.summaries,!1,I,[_e.COMPLETED]),j=Xe(e.initialCursor,P,l,C.summaries,[_e.COMPLETED],"exhausted"),V=Ze({watchStatus:"stopped",active:!1,targetEvidence:_,snapshotEvidence:Z,cursorEvidence:j,stopReason:"not_stopped",reasonCodes:[_e.COMPLETED],generatedAt:R.generatedAt});return et(V,e.format,r,e.protectedOutput),pt("completed",I,u,V,e.protectedOutput)}if(!C.hasMore&&Rc(M,i,S,o)){const Z=dt(R,C.summaries,!1,I,[F.WATCH_STOP_IDLE_LIMIT_REACHED]),j=Xe(e.initialCursor,P,l,C.summaries,[F.WATCH_STOP_IDLE_LIMIT_REACHED],"exhausted"),V=Ze({watchStatus:"stopped",active:!1,targetEvidence:_,snapshotEvidence:Z,cursorEvidence:j,stopReason:"idle_limit_reached",reasonCodes:[_e.IDLE_TIMEOUT,F.WATCH_STOP_IDLE_LIMIT_REACHED],generatedAt:R.generatedAt});return et(V,e.format,r,e.protectedOutput),pt("idle-timeout",I,u,V,e.protectedOutput)}C.hasMore||await s(n,e.signal)}}catch{const P=dt(void 0,[],!1,I,[F.WATCH_SNAPSHOT_UNAVAILABLE]),C=Xe(e.initialCursor,l,l,[],[F.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),R=Ze({watchStatus:"blocked",active:!1,targetEvidence:_,snapshotEvidence:P,cursorEvidence:C,stopReason:"unavailable_evidence",reasonCodes:[_e.STORE_UNAVAILABLE]});return et(R,e.format,r,e.protectedOutput),pt("store-unavailable",I,u,R,e.protectedOutput)}finally{y.close()}if(e.signal?.aborted){const P=dt(void 0,[],!1,I,[_e.CANCELLED]),C=Xe(e.initialCursor,l,l,[],[_e.CANCELLED],"unavailable"),R=Ze({watchStatus:"stopped",active:!1,targetEvidence:_,snapshotEvidence:P,cursorEvidence:C,stopReason:"cancelled",reasonCodes:[_e.CANCELLED]});return et(R,e.format,r,e.protectedOutput),pt("cancelled",I,u,R,e.protectedOutput)}const x=dt(void 0,[],!1,I,[F.WATCH_STOP_MAX_POLLS_REACHED]),D=Xe(e.initialCursor,l,l,[],[F.WATCH_STOP_MAX_POLLS_REACHED],"exhausted"),T=Ze({watchStatus:"stopped",active:!1,targetEvidence:_,snapshotEvidence:x,cursorEvidence:D,stopReason:"max_polls_reached",reasonCodes:[_e.MAX_POLLS,F.WATCH_STOP_MAX_POLLS_REACHED]});return et(T,e.format,r,e.protectedOutput),pt("max-polls",I,u,T,e.protectedOutput)}function Je(e){const t=e.trim().replace(/^@/,"").match(/^(job|goal|loop)-([JGL])(\d{3,})$/i);if(!t)return;const i=t[1].toLowerCase(),r=t[2].toUpperCase();if(!(i==="job"&&r!=="J"||i==="goal"&&r!=="G"||i==="loop"&&r!=="L"))return`${i}-${r}${t[3]}`}function ir(e){if(e.startsWith("job-J"))return"job";if(e.startsWith("goal-G"))return"goal";if(e.startsWith("loop-L"))return"loop"}function wi(e){const t=[],i=/(?:^|[\s"'([,{])@?(job-[Jj]\d{3,}|goal-[Gg]\d{3,}|loop-[Ll]\d{3,})(?=$|[\s"')\]},.;:!?])/g;let r;for(;(r=i.exec(e))!==null;){const a=Je(r[1]);a&&t.push(a)}return Me(t)}function Ri(e){return wi(e)[0]}function en(e){const t=e?Je(e):void 0;if(t){if(t.startsWith("job-J"))return{selectorKind:"job",targetId:t,jobId:t,publicSafe:!0};if(t.startsWith("goal-G"))return{selectorKind:"goal",targetId:t,goalId:t,publicSafe:!0};if(t.startsWith("loop-L"))return{selectorKind:"loop",targetId:t,loopId:t,publicSafe:!0}}}function ar(e){return Me(e.filter(t=>typeof t=="string").map(t=>Je(t)).filter(t=>!!t?.startsWith("job-J")))}function Pc(e,t){const i=ar(t).filter(r=>r!==e.targetId&&r!==e.jobId);return i.length>0?{...e,relatedJobIds:i}:e}function kc(e){if(!e)return;const t=h(e.target)?e.target:void 0,i=typeof e.selectorKind=="string"?e.selectorKind:typeof t?.selectorKind=="string"?t.selectorKind:void 0,r=typeof e.targetId=="string"?Je(e.targetId):typeof t?.targetId=="string"?Je(t.targetId):typeof e.targetJobId=="string"?Je(e.targetJobId):void 0,a=en(r);if(!a||i&&i!==a.selectorKind)return;const n=Array.isArray(e.relatedJobIds)?e.relatedJobIds:Array.isArray(t?.relatedJobIds)?t.relatedJobIds:void 0,o=ar([...n??[],e.jobId,t?.jobId,e.targetJobId,t?.targetJobId]).filter(p=>p!==a.targetId&&p!==a.jobId);return{...a,...typeof(e.jobId??t?.jobId)=="string"?{jobId:Je(e.jobId??t?.jobId)??a.jobId}:{},...typeof(e.goalId??t?.goalId)=="string"?{goalId:Je(e.goalId??t?.goalId)??a.goalId}:{},...typeof(e.loopId??t?.loopId)=="string"?{loopId:Je(e.loopId??t?.loopId)??a.loopId}:{},...o.length>0?{relatedJobIds:o}:{}}}function Ai(e){const t=e.trim().split(/\s+/).filter(Boolean),i=t[0]?.replace(/^\*/,"").toLowerCase(),r=t[1]?.replace(/^--/,"").toLowerCase();return(i==="jobs"||i==="job"||i==="continuity-jobs"||i==="61")&&r==="watch"}const xe=Object.freeze({ACTIVE:"command-level-watch-active",INACTIVE:"command-level-watch-inactive",DUPLICATE:"command-level-watch-duplicate",AMBIGUOUS:"command-level-watch-ambiguous",QUOTED:"command-level-watch-quoted",MALFORMED:"command-level-watch-malformed",NON_FINAL:"command-level-watch-non-final",UNRESOLVED:"command-level-watch-unresolved",UNSUPPORTED:"command-level-watch-unsupported",TARGET_INVALID:"command-level-watch-target-invalid"}),Oc=new Set(["create","start","resume"]),Nc=new Set(["create","resume","run-once"]);function or(e,t,i,r,a){return{schemaVersion:1,contractVersion:"continuity-v1",...i?{command:i}:{},...r?{operation:r}:{},active:e,...a?{watchToken:a}:{},reasonCodes:Me(t),serverHeldStream:!1,allJobsPolling:!1,targetResolution:e?"required-after-dispatch":"inactive",publicSafe:!0}}function Ne(e,t=[],i,r){const a=t.length>0?t:[xe.INACTIVE];return{args:e,watch:!1,reasonCodes:a,metadata:or(!1,a,i,r),publicSafe:!0}}function Lc(e){const t=e.trim().split(/\s+/).filter(Boolean),i=t.slice(2).filter(n=>n==="--watch").length;if(i===0)return Ne(e,[],"jobs","watch");if(i!==1)return Ne(e,[xe.AMBIGUOUS],"jobs","watch");const r=t.filter((n,o)=>o<2||n!=="--watch").join(" ");return Ai(r)?r.trim().split(/\s+/).filter(Boolean).slice(2).length!==1?Ne(e,[xe.AMBIGUOUS],"jobs","watch"):Ri(r)?{args:r,watch:!0,reasonCodes:[xe.ACTIVE],metadata:or(!0,[xe.ACTIVE],"jobs","watch"),publicSafe:!0}:Ne(e,[xe.TARGET_INVALID],"jobs","watch"):Ne(e,[xe.UNSUPPORTED],"jobs","watch")}function Dc(e){const t=[];let i=!1,r=0;for(;r<e.length;){for(;r<e.length&&/\s/.test(e[r]);)r+=1;if(r>=e.length)break;const a=r;let n="",o=!1,p=null;for(;r<e.length;){const s=e[r];if(p){if(s===p){o=!0,p=null,r+=1;continue}if(s==="\\"&&r+1<e.length){n+=e[r+1],r+=2;continue}n+=s,r+=1;continue}if(/\s/.test(s))break;if(s==='"'||s==="'"){o=!0,p=s,r+=1;continue}n+=s,r+=1}p&&(i=!0),t.push({value:n,start:a,end:r,quoted:o})}return{tokens:t,malformed:i}}function Mc(e){if(!e||e.quoted)return;const t=e.value.replace(/^\*/,"").toLowerCase();return t==="goal"||t==="loop"?t:void 0}function jc(e,t){if(!e||e==="jobs"||!t||t.quoted)return;const i=t.value.toLowerCase();return(e==="goal"?Oc:Nc).has(i)?i:void 0}function Vc(e){return!e.quoted&&e.value!=="--watch"&&e.value.toLowerCase().startsWith("--watch")}function Bc(e){const{tokens:t,malformed:i}=Dc(e),r=Mc(t[0]),a=jc(r,t[1]);if(i)return Ne(e,[xe.MALFORMED],r,a);const n=t.filter(u=>u.value==="--watch"&&!u.quoted),o=t.filter(u=>u.value==="--watch"&&u.quoted),p=t.filter(Vc);if(!(n.length>0||o.length>0||p.length>0))return Ne(e,[],r,a);if(n.length>1)return Ne(e,[xe.DUPLICATE],r,a);if(n.length===1&&(o.length>0||p.length>0))return Ne(e,[xe.AMBIGUOUS],r,a);if(o.length>0)return Ne(e,[xe.QUOTED],r,a);if(p.length>0)return Ne(e,[xe.MALFORMED],r,a);const l=n[0];if(!l)return Ne(e,[],r,a);if(t[t.length-1]!==l)return Ne(e,[xe.NON_FINAL],r,a);if(!r||!a)return Ne(e,[xe.UNRESOLVED],r,a);const I=`${e.slice(0,l.start)}${e.slice(l.end)}`.trim(),S={literal:"--watch",position:"final",start:l.start,end:l.end,quoted:!1,publicSafe:!0};return{args:I,watch:!0,reasonCodes:[xe.ACTIVE],metadata:or(!0,[xe.ACTIVE],r,a,S),publicSafe:!0}}function Uc(e){return Ai(e)?Lc(e):Bc(e)}function $c(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&bo.has(t)):[]}function Gt(e){return{disabled:!0,reasonCodes:Me(e.length>0?e:[ke.MISSING])}}function cr(e,t,i=[],r){const a=en(t);if(a)return{source:e,target:Pc(a,i),targetJobId:a.targetId,...r?{initialCursor:r}:{},serverHeldStream:!1}}function Hc(e){const t=new Map;for(const i of e){const r=`${i.target.selectorKind}:${i.target.targetId}`,a=t.get(r);if(!a){t.set(r,i);continue}const n=Me([...a.target.relatedJobIds??[],...i.target.relatedJobIds??[]]);t.set(r,{...a,target:n.length>0?{...a.target,relatedJobIds:n}:a.target,initialCursor:a.initialCursor??i.initialCursor})}return Array.from(t.values())}function Ct(e,t,i,r){return{source:e,hasEvidence:t,candidates:Hc(i.filter(a=>!!a)),...r&&r.length>0?{disabledReasonCodes:Me(r)}:{}}}function Gc(e,t){return e.target.selectorKind===t.target.selectorKind&&e.target.targetId===t.target.targetId}function tn(e,t){const i=Me(e.filter(r=>typeof r=="string").map(r=>Je(r)).filter(r=>!!r));if(t){const r=i.find(a=>ir(a)===t);if(r)return r}return i[0]}function wn(e,t){return Me(e.filter(i=>typeof i=="string").map(i=>Je(i)).filter(i=>!!i)).find(i=>ir(i)===t)}function Wc(e){const t=h(e?.continuity)?e.continuity:void 0,i=h(t?.jobs)?t.jobs:void 0,r=h(i?.watcher)?i.watcher:void 0,a=$c(r?.reasonCodes??i?.reasonCodes);if(!r)return Ct("watcher-metadata",a.length>0,[],a);if(r.active===!1||a.length>0)return Ct("watcher-metadata",!0,[],a.length>0?a:[ke.MALFORMED]);if(r.serverHeldStream!==!1)return Ct("watcher-metadata",!0,[],[ke.SERVER_HELD_STREAM]);const n=kc(r);if(!n)return Ct("watcher-metadata",!0,[],[ke.MISSING]);const o=typeof r.initialCursor=="string"?r.initialCursor:void 0;return Ct("watcher-metadata",!0,[{source:"watcher-metadata",target:n,targetJobId:n.targetId,...o?{initialCursor:o}:{},serverHeldStream:!1}])}function bi(e,t){const i=h(e.loopJobPlan)?e.loopJobPlan:void 0,r=h(i?.metadata)?i.metadata:void 0,a=h(e.metadata)?e.metadata:void 0,o=(t==="goal"?tn([e.goalId,e.targetGoalId,e.campaignId,e.jobId,e.targetJobId,a?.goalId,a?.campaignId,a?.jobId],"goal"):tn([e.loopId,e.targetLoopId,e.jobId,e.targetJobId,a?.loopId,a?.jobId,r?.loopId,r?.jobId],"loop"))??tn([e.jobId,e.targetJobId,a?.jobId,r?.jobId]);return cr("goal-loop-continuity-metadata",o,[e.jobId,e.targetJobId,a?.jobId,r?.jobId])}function Fc(e){const t=h(e?.continuity)?e.continuity:void 0,i=h(t?.goal)?t.goal:void 0,r=h(t?.loop)?t.loop:void 0,a=[i?bi(i,"goal"):void 0,r?bi(r,"loop"):void 0],n=!!(i||r);return Ct("goal-loop-continuity-metadata",n,a,n&&a.every(o=>!o)?[ke.MISSING]:void 0)}function Yc(e){return Array.isArray(e)?e.filter(h):h(e)?Array.isArray(e.operationLogs)?e.operationLogs.filter(h):h(e.operationLog)?[e.operationLog]:Array.isArray(e.operations)?[e]:[]:[]}function xi(e,t){const i=h(t.metadata)?t.metadata:void 0,r=wn([t.goalId,t.targetGoalId,t.campaignId,i?.goalId,i?.campaignId,t.jobId,i?.jobId],"goal"),a=wn([t.loopId,t.targetLoopId,i?.loopId,t.jobId,i?.jobId],"loop"),n=tn([t.jobId,t.targetJobId,i?.jobId],"job"),o=r??a??n;if(!o)return;const p=e.get(o)??{targetId:o,relatedJobIds:[]};p.relatedJobIds.push(...ar([n,t.jobId,t.targetJobId,i?.jobId])),e.set(o,p)}function qc(e){const t=h(e.metadata)?e.metadata:void 0;return!!(wn([e.goalId,e.targetGoalId,e.campaignId,t?.goalId,t?.campaignId,e.jobId,t?.jobId],"goal")??wn([e.loopId,e.targetLoopId,t?.loopId,e.jobId,t?.jobId],"loop"))}function zc(e){const t=h(e.metadata)?e.metadata:void 0;return!!tn([e.goalId,e.targetGoalId,e.campaignId,e.loopId,e.targetLoopId,e.jobId,e.targetJobId,t?.goalId,t?.campaignId,t?.loopId,t?.jobId])}function Ti(e,t){const i=[];for(const o of["metadata","job","event","receipt","processingOutputSummary"]){const p=t[o];h(p)&&i.push(p)}const r=h(t.event)?t.event:void 0;h(r?.metadata)&&i.push(r.metadata),h(r?.processingOutputSummary)&&i.push(r.processingOutputSummary);const a=h(t.receipt)?t.receipt:void 0;h(a?.metadata)&&i.push(a.metadata);const n=i.some(zc);for(const o of i)xi(e,o);(!n||qc(t))&&xi(e,t)}function Jc(e){const t=Yc(e?.continuityStateUpdate),i=new Map;for(const a of t){Ti(i,a);const n=Array.isArray(a.operations)?a.operations.filter(h):[];for(const o of n)Ti(i,o)}const r=Array.from(i.values()).map(a=>cr("continuity-state-update-operation-log",a.targetId,a.relatedJobIds));return Ct("continuity-state-update-operation-log",t.length>0,r,t.length>0&&r.every(a=>!a)?[ke.MISSING]:void 0)}function Kc(e){const t=wi(e);return Ct("explicit-args",t.length>0,t.map(i=>cr("explicit-args",i)))}function Qc(e,t){const i=[Wc(e),Fc(e),Jc(e),Kc(t)];for(let r=0;r<i.length;r+=1){const a=i[r];if(!a.hasEvidence)continue;if(a.disabledReasonCodes&&a.disabledReasonCodes.length>0)return Gt(a.disabledReasonCodes);if(a.candidates.length!==1)return Gt([a.candidates.length>1?ke.AMBIGUOUS:ke.MISSING]);const n=a.candidates[0];for(const o of i.slice(r+1)){if(!o.hasEvidence)continue;if(o.disabledReasonCodes&&o.disabledReasonCodes.length>0)return Gt(o.disabledReasonCodes);if(o.candidates.length>1)return Gt([ke.AMBIGUOUS]);const p=o.candidates[0];if(p&&!Gc(n,p))return Gt([ke.CONFLICT])}return{target:n.target,targetJobId:n.targetJobId,...n.initialCursor?{initialCursor:n.initialCursor}:{},source:n.source,serverHeldStream:!1}}return Gt([ke.MISSING])}async function sr(e,t,i,r={}){const a="/api/v1/invoke";let n,o;const p=await Zt(e,a,t,i,{...r,deferSuccessfulJsonParsing:!0,...t.privateExecution?{maxAttempts:1,allowReplayRetry:!1}:{},admitResponseBeforeBodyRead:S=>{const u=S.headers.get("X-Neocortex-Compatibility");if(u!==null)try{if(u.length===0||u.length>8192)throw new Error("header-size");const _=JSON.parse(Buffer.from(u,"base64url").toString("utf8"));if(!Ha(_))throw new Error("header-shape");if(n=_,_.status==="incompatible")return o="incompatible",!1}catch{return o="malformed",!1}return r.admitResponseBeforeBodyRead?.(S)??!0}});if(p.networkFailure||!p.response)return{ok:!1,status:0,error:"Network error after bounded retries"};if(p.responseAdmissionRejected){const S=o==="malformed"?Ut.RESULT_MALFORMED:n?.reasonCodes[0]??Ut.OFFER_MALFORMED;return{ok:!1,status:p.response.status,error:`COMPATIBILITY_INCOMPATIBLE: ${S}`,errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:S,fallback_action:n?.remediationHint??"upgrade-client"},...n?{compatibility:n}:{}}}const{response:s,text:l}=p;let I=p.parsed;try{if(t.compatibility&&!n){if(/"(?:reviewReconciliation|review_reconciliation|reconciliationMetadata|releaseLifecycle|release_lifecycle|releaseBlocked|release_blocked|yoloopReleaseBlocked)"\s*:/u.test(l))return{ok:!1,status:s.status,error:`COMPATIBILITY_INCOMPATIBLE: ${Ut.UNNEGOTIATED_PROTECTED_FIELD}`,errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:Ut.UNNEGOTIATED_PROTECTED_FIELD,fallback_action:"upgrade-client"}};n=$a({clientVersion:t.compatibility.clientVersion,serverVersion:"0.0.0",registryVersion:t.registryVersion,registryChecksum:t.registryChecksum,reason:Ut.SERVER_NEGOTIATION_MISSING})}if(s.ok)try{I=l?JSON.parse(l):{}}catch{return{ok:!1,status:s.status,error:"COMPATIBILITY_INCOMPATIBLE: response-json-malformed",errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:Ut.RESULT_MALFORMED},...n?{compatibility:n}:{}}}if(!s.ok)return t.privateExecution?{ok:!1,status:s.status,error:"private-execution-invoke-unavailable"}:{ok:!1,status:s.status,error:Object.keys(I).length>0?`${I.error_code??"ERROR"}: ${I.message??l}`:`HTTP ${s.status}: ${l}`,errorBody:Object.keys(I).length>0?I:void 0,...n?{compatibility:n}:{}};const S=I,u=s.headers.get("X-Client-Version-Warning");return u&&!fi&&(fi=!0,process.stderr.write(`
18
+ `)}function Cc(e,t,i){return{continuityInvokeWatch:{schemaVersion:1,contractVersion:"continuity-v1",command:"invoke",operation:"watch",watchStatus:e.watchStatus,stopReason:e.stopReason??"not_stopped",targetResolutionState:e.targetResolutionState,targetKind:e.targetKind,targetId:e.targetId,snapshotStatus:e.snapshotEvidence?.snapshotStatus,snapshotGeneratedAt:e.snapshotEvidence?.generatedAt,renderedSummaryCount:e.snapshotEvidence?.renderedSummaryCount??t,cursorState:e.cursorEvidence?.cursorState,cursorAdvanced:e.cursorEvidence?.cursorAdvanced,summariesEmitted:t,polls:i,statusRecord:e,publicSafe:!0}}}function pt(e,t,i,r,a=!1){return a?{status:e,summariesEmitted:t,polls:i,reasonCodes:[],watchStatus:r.watchStatus,stopReason:r.stopReason,metadata:{continuityInvokeWatch:{schemaVersion:1,contractVersion:"continuity-v1",command:"invoke",operation:"watch",watchStatus:r.watchStatus,stopReason:r.stopReason??"not_stopped",summariesEmitted:t,polls:i,protectedProjection:!0,publicSafe:!0}},publicSafe:!0}:{status:e,summariesEmitted:t,polls:i,reasonCodes:r.reasonCodes,watchStatus:r.watchStatus,stopReason:r.stopReason,targetEvidence:r.targetEvidence,snapshotEvidence:r.snapshotEvidence,cursorEvidence:r.cursorEvidence,statusRecord:r,metadata:Cc(r,t,i),publicSafe:!0}}function _c(e){const t=e.reasonCode?` reason=${q(e.reasonCode,80)}`:"",i=e.goalId?` goal=${q(e.goalId,100)}`:"",r=e.loopId?` loop=${q(e.loopId,100)}`:"";return`[watch] ${q(e.createdAt,80)} event=${q(e.eventId,120)} job=${q(e.jobId,100)}${i}${r} execution=${q(e.executionId,120)}${t} -- ${q(e.publicSummary)}`}function wc(e){return{type:"processing_summary",source:"local_continuity_sqlite",eventId:q(e.eventId,120),jobId:q(e.jobId,100),...e.goalId?{goalId:q(e.goalId,100)}:{},...e.loopId?{loopId:q(e.loopId,100)}:{},executionId:q(e.executionId,120),...e.reasonCode?{reasonCode:q(e.reasonCode,80)}:{},createdAt:q(e.createdAt,80),publicSummary:q(e.publicSummary),publicSafe:!0}}function Rc(e,t,i,r=!1){if(r){i.write(t==="json"?`${JSON.stringify({type:"processing_summary",source:"local_continuity_sqlite",publicSummary:"A local processing update is available.",protectedProjection:!0,publicSafe:!0})}
19
+ `:`[watch] A local processing update is available.
20
+ `);return}if(t==="json"){i.write(JSON.stringify(wc(e))+`
21
+ `);return}i.write(_c(e)+`
22
+ `)}function ir(e){return xo.has(e.status)}function Ac(e,t,i){if(t){const a=e.find(n=>n.jobId===t);return!!(a&&ir(a))}return i<=0?!1:e.filter(a=>!ir(a)).length===0}function bc(e,t,i,r){return i<r?!1:t?!e.some(a=>a.jobId===t&&!ir(a)):e.length===0}function xc(e,t){return t?.aborted?Promise.resolve():new Promise(i=>{const r=setTimeout(a,e);function a(){clearTimeout(r),t?.removeEventListener("abort",a),i()}t?.addEventListener("abort",a,{once:!0})})}function Tc(e){return e.includes(ke.MALFORMED)?"malformed":e.includes(ke.AMBIGUOUS)?"ambiguous":e.includes("watch-target-multiple")?"multiple":e.includes("watch-evidence-unsafe")?"unsafe":e.includes(ke.MISSING)||e.includes(_e.TARGET_UNRESOLVED)?"unresolved":"unavailable"}function wi(e,t){const i=t?Zt(t):void 0,r=Me([...e,_e.TARGET_UNRESOLVED,Y.WATCH_TARGET_UNRESOLVED]),a=rr(i,i?.targetId,Tc(r),r),n=dt({generatedAt:new Date().toISOString()},[],!1,0,[Y.WATCH_TARGET_UNRESOLVED]),o=Xe(void 0,void 0,void 0,[],[Y.WATCH_TARGET_UNRESOLVED],"unavailable");return Ze({watchStatus:"blocked",active:!1,targetEvidence:a,snapshotEvidence:n,cursorEvidence:o,stopReason:"target_unresolved",reasonCodes:r,generatedAt:n.generatedAt})}function Pc(e,t,i,r,a=!1){const n=wi(e,Ai(t));return et(n,i,r,a),pt("target-unresolved",0,0,n,a)}async function kc(e){if(e.signal?.aborted){const P=rr(e.target??Zt(e.targetJobId),e.targetJobId,e.target??e.targetJobId?"resolved":"unresolved",[_e.CANCELLED]),C=dt(void 0,[],!1,0),R=Xe(e.initialCursor,e.initialCursor,e.initialCursor,[],[_e.CANCELLED],"unavailable"),M=Ze({watchStatus:"stopped",active:!1,targetEvidence:P,snapshotEvidence:C,cursorEvidence:R,stopReason:"cancelled",reasonCodes:[_e.CANCELLED]});return pt("cancelled",0,0,M,e.protectedOutput)}const t=e.target??Zt(e.targetJobId),i=e.targetJobId??t?.targetId,r=e.stdout??process.stdout;if(!t){const P=wi([ke.MISSING,_e.TARGET_UNRESOLVED]);return et(P,e.format,r,e.protectedOutput),pt("target-unresolved",0,0,P,e.protectedOutput)}const a=_n(e.limit??wn("NEOCORTEX_INVOKE_WATCH_LIMIT",kr),kr,50),n=Math.max(50,_n(e.pollIntervalMs??wn("NEOCORTEX_INVOKE_WATCH_POLL_INTERVAL_MS",Lr),Lr,6e4)),o=_n(e.maxIdlePolls??wn("NEOCORTEX_INVOKE_WATCH_MAX_IDLE_POLLS",Or),Or,120),p=_n(e.maxPolls??wn("NEOCORTEX_INVOKE_WATCH_MAX_POLLS",Nr),Nr,86400),s=e.sleep??xc;let l=e.initialCursor,I=0,S=0,u=0;const _=rr(t,i,"resolved",[Y.OK]),E={schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:"pending",renderedSummaryCount:0,reasonCodes:[Y.WATCH_RENDER_PENDING],publicSafe:!0},g=Xe(e.initialCursor,l,l,[],e.initialCursor?[Y.WATCH_CURSOR_UNCHANGED]:[Y.WATCH_NO_SUMMARIES_YET],e.initialCursor?"unchanged":"not_started");et(Ze({watchStatus:"active",active:!0,targetEvidence:_,snapshotEvidence:E,cursorEvidence:g,stopReason:"not_stopped",reasonCodes:[Y.OK]}),e.format,r,e.protectedOutput);let y;try{y=await va({projectRoot:e.projectRoot,strictReadOnly:e.strictReadOnly})}catch{const P=dt(void 0,[],!1,I,[Y.WATCH_SNAPSHOT_UNAVAILABLE]),C=Xe(e.initialCursor,l,l,[],[Y.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),R=Ze({watchStatus:"blocked",active:!1,targetEvidence:_,snapshotEvidence:P,cursorEvidence:C,stopReason:"unavailable_evidence",reasonCodes:[_e.STORE_UNAVAILABLE]});return et(R,e.format,r,e.protectedOutput),pt("store-unavailable",I,u,R,e.protectedOutput)}try{for(;!e.signal?.aborted&&u<p;){u+=1;const P=l,C=y.collectProcessingOutputSummaryCursor({...l?{cursor:l}:{},...t?{target:t}:{},...i?{jobId:i}:{},limit:a}),R=y.collectSnapshot({jobLimit:50,processingSummaryLimit:1}),M=R.jobs;if(C.summaries.length>0){for(const Z of C.summaries)Rc(Z,e.format,r,e.protectedOutput),I+=1;l=C.nextCursor??C.summaries[C.summaries.length-1]?.cursor??l,S=0}else l=C.nextCursor??l,S+=1;const N=dt(R,C.summaries,!0,C.summaries.length),z=Xe(e.initialCursor,P,l,C.summaries,C.summaries.length>0?[Y.WATCH_CURSOR_ADVANCED]:[Y.WATCH_NO_SUMMARIES_YET]);if(et(Ze({watchStatus:C.summaries.length>0?"polling":"waiting",active:!0,targetEvidence:_,snapshotEvidence:N,cursorEvidence:z,stopReason:"not_stopped",reasonCodes:C.summaries.length>0?[Y.WATCH_CURSOR_ADVANCED]:[Y.WATCH_NO_SUMMARIES_YET],generatedAt:R.generatedAt}),e.format,r,e.protectedOutput),!C.hasMore&&Ac(M,i,I)){const Z=dt(R,C.summaries,!1,I,[_e.COMPLETED]),j=Xe(e.initialCursor,P,l,C.summaries,[_e.COMPLETED],"exhausted"),V=Ze({watchStatus:"stopped",active:!1,targetEvidence:_,snapshotEvidence:Z,cursorEvidence:j,stopReason:"not_stopped",reasonCodes:[_e.COMPLETED],generatedAt:R.generatedAt});return et(V,e.format,r,e.protectedOutput),pt("completed",I,u,V,e.protectedOutput)}if(!C.hasMore&&bc(M,i,S,o)){const Z=dt(R,C.summaries,!1,I,[Y.WATCH_STOP_IDLE_LIMIT_REACHED]),j=Xe(e.initialCursor,P,l,C.summaries,[Y.WATCH_STOP_IDLE_LIMIT_REACHED],"exhausted"),V=Ze({watchStatus:"stopped",active:!1,targetEvidence:_,snapshotEvidence:Z,cursorEvidence:j,stopReason:"idle_limit_reached",reasonCodes:[_e.IDLE_TIMEOUT,Y.WATCH_STOP_IDLE_LIMIT_REACHED],generatedAt:R.generatedAt});return et(V,e.format,r,e.protectedOutput),pt("idle-timeout",I,u,V,e.protectedOutput)}C.hasMore||await s(n,e.signal)}}catch{const P=dt(void 0,[],!1,I,[Y.WATCH_SNAPSHOT_UNAVAILABLE]),C=Xe(e.initialCursor,l,l,[],[Y.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),R=Ze({watchStatus:"blocked",active:!1,targetEvidence:_,snapshotEvidence:P,cursorEvidence:C,stopReason:"unavailable_evidence",reasonCodes:[_e.STORE_UNAVAILABLE]});return et(R,e.format,r,e.protectedOutput),pt("store-unavailable",I,u,R,e.protectedOutput)}finally{y.close()}if(e.signal?.aborted){const P=dt(void 0,[],!1,I,[_e.CANCELLED]),C=Xe(e.initialCursor,l,l,[],[_e.CANCELLED],"unavailable"),R=Ze({watchStatus:"stopped",active:!1,targetEvidence:_,snapshotEvidence:P,cursorEvidence:C,stopReason:"cancelled",reasonCodes:[_e.CANCELLED]});return et(R,e.format,r,e.protectedOutput),pt("cancelled",I,u,R,e.protectedOutput)}const b=dt(void 0,[],!1,I,[Y.WATCH_STOP_MAX_POLLS_REACHED]),L=Xe(e.initialCursor,l,l,[],[Y.WATCH_STOP_MAX_POLLS_REACHED],"exhausted"),T=Ze({watchStatus:"stopped",active:!1,targetEvidence:_,snapshotEvidence:b,cursorEvidence:L,stopReason:"max_polls_reached",reasonCodes:[_e.MAX_POLLS,Y.WATCH_STOP_MAX_POLLS_REACHED]});return et(T,e.format,r,e.protectedOutput),pt("max-polls",I,u,T,e.protectedOutput)}function Je(e){const t=e.trim().replace(/^@/,"").match(/^(job|goal|loop)-([JGL])(\d{3,})$/i);if(!t)return;const i=t[1].toLowerCase(),r=t[2].toUpperCase();if(!(i==="job"&&r!=="J"||i==="goal"&&r!=="G"||i==="loop"&&r!=="L"))return`${i}-${r}${t[3]}`}function ar(e){if(e.startsWith("job-J"))return"job";if(e.startsWith("goal-G"))return"goal";if(e.startsWith("loop-L"))return"loop"}function Ri(e){const t=[],i=/(?:^|[\s"'([,{])@?(job-[Jj]\d{3,}|goal-[Gg]\d{3,}|loop-[Ll]\d{3,})(?=$|[\s"')\]},.;:!?])/g;let r;for(;(r=i.exec(e))!==null;){const a=Je(r[1]);a&&t.push(a)}return Me(t)}function Ai(e){return Ri(e)[0]}function Zt(e){const t=e?Je(e):void 0;if(t){if(t.startsWith("job-J"))return{selectorKind:"job",targetId:t,jobId:t,publicSafe:!0};if(t.startsWith("goal-G"))return{selectorKind:"goal",targetId:t,goalId:t,publicSafe:!0};if(t.startsWith("loop-L"))return{selectorKind:"loop",targetId:t,loopId:t,publicSafe:!0}}}function or(e){return Me(e.filter(t=>typeof t=="string").map(t=>Je(t)).filter(t=>!!t?.startsWith("job-J")))}function Oc(e,t){const i=or(t).filter(r=>r!==e.targetId&&r!==e.jobId);return i.length>0?{...e,relatedJobIds:i}:e}function Nc(e){if(!e)return;const t=h(e.target)?e.target:void 0,i=typeof e.selectorKind=="string"?e.selectorKind:typeof t?.selectorKind=="string"?t.selectorKind:void 0,r=typeof e.targetId=="string"?Je(e.targetId):typeof t?.targetId=="string"?Je(t.targetId):typeof e.targetJobId=="string"?Je(e.targetJobId):void 0,a=Zt(r);if(!a||i&&i!==a.selectorKind)return;const n=Array.isArray(e.relatedJobIds)?e.relatedJobIds:Array.isArray(t?.relatedJobIds)?t.relatedJobIds:void 0,o=or([...n??[],e.jobId,t?.jobId,e.targetJobId,t?.targetJobId]).filter(p=>p!==a.targetId&&p!==a.jobId);return{...a,...typeof(e.jobId??t?.jobId)=="string"?{jobId:Je(e.jobId??t?.jobId)??a.jobId}:{},...typeof(e.goalId??t?.goalId)=="string"?{goalId:Je(e.goalId??t?.goalId)??a.goalId}:{},...typeof(e.loopId??t?.loopId)=="string"?{loopId:Je(e.loopId??t?.loopId)??a.loopId}:{},...o.length>0?{relatedJobIds:o}:{}}}function bi(e){const t=e.trim().split(/\s+/).filter(Boolean),i=t[0]?.replace(/^\*/,"").toLowerCase(),r=t[1]?.replace(/^--/,"").toLowerCase();return(i==="jobs"||i==="job"||i==="continuity-jobs"||i==="61")&&r==="watch"}const xe=Object.freeze({ACTIVE:"command-level-watch-active",INACTIVE:"command-level-watch-inactive",DUPLICATE:"command-level-watch-duplicate",AMBIGUOUS:"command-level-watch-ambiguous",QUOTED:"command-level-watch-quoted",MALFORMED:"command-level-watch-malformed",NON_FINAL:"command-level-watch-non-final",UNRESOLVED:"command-level-watch-unresolved",UNSUPPORTED:"command-level-watch-unsupported",TARGET_INVALID:"command-level-watch-target-invalid"}),Lc=new Set(["create","start","resume"]),Dc=new Set(["create","resume","run-once"]);function cr(e,t,i,r,a){return{schemaVersion:1,contractVersion:"continuity-v1",...i?{command:i}:{},...r?{operation:r}:{},active:e,...a?{watchToken:a}:{},reasonCodes:Me(t),serverHeldStream:!1,allJobsPolling:!1,targetResolution:e?"required-after-dispatch":"inactive",publicSafe:!0}}function Ne(e,t=[],i,r){const a=t.length>0?t:[xe.INACTIVE];return{args:e,watch:!1,reasonCodes:a,metadata:cr(!1,a,i,r),publicSafe:!0}}function Mc(e){const t=e.trim().split(/\s+/).filter(Boolean),i=t.slice(2).filter(n=>n==="--watch").length;if(i===0)return Ne(e,[],"jobs","watch");if(i!==1)return Ne(e,[xe.AMBIGUOUS],"jobs","watch");const r=t.filter((n,o)=>o<2||n!=="--watch").join(" ");return bi(r)?r.trim().split(/\s+/).filter(Boolean).slice(2).length!==1?Ne(e,[xe.AMBIGUOUS],"jobs","watch"):Ai(r)?{args:r,watch:!0,reasonCodes:[xe.ACTIVE],metadata:cr(!0,[xe.ACTIVE],"jobs","watch"),publicSafe:!0}:Ne(e,[xe.TARGET_INVALID],"jobs","watch"):Ne(e,[xe.UNSUPPORTED],"jobs","watch")}function jc(e){const t=[];let i=!1,r=0;for(;r<e.length;){for(;r<e.length&&/\s/.test(e[r]);)r+=1;if(r>=e.length)break;const a=r;let n="",o=!1,p=null;for(;r<e.length;){const s=e[r];if(p){if(s===p){o=!0,p=null,r+=1;continue}if(s==="\\"&&r+1<e.length){n+=e[r+1],r+=2;continue}n+=s,r+=1;continue}if(/\s/.test(s))break;if(s==='"'||s==="'"){o=!0,p=s,r+=1;continue}n+=s,r+=1}p&&(i=!0),t.push({value:n,start:a,end:r,quoted:o})}return{tokens:t,malformed:i}}function Vc(e){if(!e||e.quoted)return;const t=e.value.replace(/^\*/,"").toLowerCase();return t==="goal"||t==="loop"?t:void 0}function Bc(e,t){if(!e||e==="jobs"||!t||t.quoted)return;const i=t.value.toLowerCase();return(e==="goal"?Lc:Dc).has(i)?i:void 0}function Uc(e){return!e.quoted&&e.value!=="--watch"&&e.value.toLowerCase().startsWith("--watch")}function $c(e){const{tokens:t,malformed:i}=jc(e),r=Vc(t[0]),a=Bc(r,t[1]);if(i)return Ne(e,[xe.MALFORMED],r,a);const n=t.filter(u=>u.value==="--watch"&&!u.quoted),o=t.filter(u=>u.value==="--watch"&&u.quoted),p=t.filter(Uc);if(!(n.length>0||o.length>0||p.length>0))return Ne(e,[],r,a);if(n.length>1)return Ne(e,[xe.DUPLICATE],r,a);if(n.length===1&&(o.length>0||p.length>0))return Ne(e,[xe.AMBIGUOUS],r,a);if(o.length>0)return Ne(e,[xe.QUOTED],r,a);if(p.length>0)return Ne(e,[xe.MALFORMED],r,a);const l=n[0];if(!l)return Ne(e,[],r,a);if(t[t.length-1]!==l)return Ne(e,[xe.NON_FINAL],r,a);if(!r||!a)return Ne(e,[xe.UNRESOLVED],r,a);const I=`${e.slice(0,l.start)}${e.slice(l.end)}`.trim(),S={literal:"--watch",position:"final",start:l.start,end:l.end,quoted:!1,publicSafe:!0};return{args:I,watch:!0,reasonCodes:[xe.ACTIVE],metadata:cr(!0,[xe.ACTIVE],r,a,S),publicSafe:!0}}function Hc(e){return bi(e)?Mc(e):$c(e)}function Gc(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&To.has(t)):[]}function Gt(e){return{disabled:!0,reasonCodes:Me(e.length>0?e:[ke.MISSING])}}function sr(e,t,i=[],r){const a=Zt(t);if(a)return{source:e,target:Oc(a,i),targetJobId:a.targetId,...r?{initialCursor:r}:{},serverHeldStream:!1}}function Wc(e){const t=new Map;for(const i of e){const r=`${i.target.selectorKind}:${i.target.targetId}`,a=t.get(r);if(!a){t.set(r,i);continue}const n=Me([...a.target.relatedJobIds??[],...i.target.relatedJobIds??[]]);t.set(r,{...a,target:n.length>0?{...a.target,relatedJobIds:n}:a.target,initialCursor:a.initialCursor??i.initialCursor})}return Array.from(t.values())}function vt(e,t,i,r){return{source:e,hasEvidence:t,candidates:Wc(i.filter(a=>!!a)),...r&&r.length>0?{disabledReasonCodes:Me(r)}:{}}}function Fc(e,t){return e.target.selectorKind===t.target.selectorKind&&e.target.targetId===t.target.targetId}function en(e,t){const i=Me(e.filter(r=>typeof r=="string").map(r=>Je(r)).filter(r=>!!r));if(t){const r=i.find(a=>ar(a)===t);if(r)return r}return i[0]}function Rn(e,t){return Me(e.filter(i=>typeof i=="string").map(i=>Je(i)).filter(i=>!!i)).find(i=>ar(i)===t)}function Yc(e){const t=h(e?.continuity)?e.continuity:void 0,i=h(t?.jobs)?t.jobs:void 0,r=h(i?.watcher)?i.watcher:void 0,a=Gc(r?.reasonCodes??i?.reasonCodes);if(!r)return vt("watcher-metadata",a.length>0,[],a);if(r.active===!1||a.length>0)return vt("watcher-metadata",!0,[],a.length>0?a:[ke.MALFORMED]);if(r.serverHeldStream!==!1)return vt("watcher-metadata",!0,[],[ke.SERVER_HELD_STREAM]);const n=Nc(r);if(!n)return vt("watcher-metadata",!0,[],[ke.MISSING]);const o=typeof r.initialCursor=="string"?r.initialCursor:void 0;return vt("watcher-metadata",!0,[{source:"watcher-metadata",target:n,targetJobId:n.targetId,...o?{initialCursor:o}:{},serverHeldStream:!1}])}function xi(e,t){const i=h(e.loopJobPlan)?e.loopJobPlan:void 0,r=h(i?.metadata)?i.metadata:void 0,a=h(e.metadata)?e.metadata:void 0,o=(t==="goal"?en([e.goalId,e.targetGoalId,e.campaignId,e.jobId,e.targetJobId,a?.goalId,a?.campaignId,a?.jobId],"goal"):en([e.loopId,e.targetLoopId,e.jobId,e.targetJobId,a?.loopId,a?.jobId,r?.loopId,r?.jobId],"loop"))??en([e.jobId,e.targetJobId,a?.jobId,r?.jobId]);return sr("goal-loop-continuity-metadata",o,[e.jobId,e.targetJobId,a?.jobId,r?.jobId])}function qc(e){const t=h(e?.continuity)?e.continuity:void 0,i=h(t?.goal)?t.goal:void 0,r=h(t?.loop)?t.loop:void 0,a=[i?xi(i,"goal"):void 0,r?xi(r,"loop"):void 0],n=!!(i||r);return vt("goal-loop-continuity-metadata",n,a,n&&a.every(o=>!o)?[ke.MISSING]:void 0)}function zc(e){return Array.isArray(e)?e.filter(h):h(e)?Array.isArray(e.operationLogs)?e.operationLogs.filter(h):h(e.operationLog)?[e.operationLog]:Array.isArray(e.operations)?[e]:[]:[]}function Ti(e,t){const i=h(t.metadata)?t.metadata:void 0,r=Rn([t.goalId,t.targetGoalId,t.campaignId,i?.goalId,i?.campaignId,t.jobId,i?.jobId],"goal"),a=Rn([t.loopId,t.targetLoopId,i?.loopId,t.jobId,i?.jobId],"loop"),n=en([t.jobId,t.targetJobId,i?.jobId],"job"),o=r??a??n;if(!o)return;const p=e.get(o)??{targetId:o,relatedJobIds:[]};p.relatedJobIds.push(...or([n,t.jobId,t.targetJobId,i?.jobId])),e.set(o,p)}function Jc(e){const t=h(e.metadata)?e.metadata:void 0;return!!(Rn([e.goalId,e.targetGoalId,e.campaignId,t?.goalId,t?.campaignId,e.jobId,t?.jobId],"goal")??Rn([e.loopId,e.targetLoopId,t?.loopId,e.jobId,t?.jobId],"loop"))}function Kc(e){const t=h(e.metadata)?e.metadata:void 0;return!!en([e.goalId,e.targetGoalId,e.campaignId,e.loopId,e.targetLoopId,e.jobId,e.targetJobId,t?.goalId,t?.campaignId,t?.loopId,t?.jobId])}function Pi(e,t){const i=[];for(const o of["metadata","job","event","receipt","processingOutputSummary"]){const p=t[o];h(p)&&i.push(p)}const r=h(t.event)?t.event:void 0;h(r?.metadata)&&i.push(r.metadata),h(r?.processingOutputSummary)&&i.push(r.processingOutputSummary);const a=h(t.receipt)?t.receipt:void 0;h(a?.metadata)&&i.push(a.metadata);const n=i.some(Kc);for(const o of i)Ti(e,o);(!n||Jc(t))&&Ti(e,t)}function Qc(e){const t=zc(e?.continuityStateUpdate),i=new Map;for(const a of t){Pi(i,a);const n=Array.isArray(a.operations)?a.operations.filter(h):[];for(const o of n)Pi(i,o)}const r=Array.from(i.values()).map(a=>sr("continuity-state-update-operation-log",a.targetId,a.relatedJobIds));return vt("continuity-state-update-operation-log",t.length>0,r,t.length>0&&r.every(a=>!a)?[ke.MISSING]:void 0)}function Xc(e){const t=Ri(e);return vt("explicit-args",t.length>0,t.map(i=>sr("explicit-args",i)))}function Zc(e,t){const i=[Yc(e),qc(e),Qc(e),Xc(t)];for(let r=0;r<i.length;r+=1){const a=i[r];if(!a.hasEvidence)continue;if(a.disabledReasonCodes&&a.disabledReasonCodes.length>0)return Gt(a.disabledReasonCodes);if(a.candidates.length!==1)return Gt([a.candidates.length>1?ke.AMBIGUOUS:ke.MISSING]);const n=a.candidates[0];for(const o of i.slice(r+1)){if(!o.hasEvidence)continue;if(o.disabledReasonCodes&&o.disabledReasonCodes.length>0)return Gt(o.disabledReasonCodes);if(o.candidates.length>1)return Gt([ke.AMBIGUOUS]);const p=o.candidates[0];if(p&&!Fc(n,p))return Gt([ke.CONFLICT])}return{target:n.target,targetJobId:n.targetJobId,...n.initialCursor?{initialCursor:n.initialCursor}:{},source:n.source,serverHeldStream:!1}}return Gt([ke.MISSING])}async function dr(e,t,i,r={}){const a="/api/v1/invoke";let n,o;const p=await Xt(e,a,t,i,{...r,deferSuccessfulJsonParsing:!0,...t.privateExecution?{maxAttempts:1,allowReplayRetry:!1}:{},admitResponseBeforeBodyRead:S=>{const u=S.headers.get("X-Neocortex-Compatibility");if(u!==null)try{if(u.length===0||u.length>8192)throw new Error("header-size");const _=JSON.parse(Buffer.from(u,"base64url").toString("utf8"));if(!Wa(_))throw new Error("header-shape");if(n=_,_.status==="incompatible")return o="incompatible",!1}catch{return o="malformed",!1}return r.admitResponseBeforeBodyRead?.(S)??!0}});if(p.networkFailure||!p.response)return{ok:!1,status:0,error:"Network error after bounded retries"};if(p.responseAdmissionRejected){const S=o==="malformed"?Ut.RESULT_MALFORMED:n?.reasonCodes[0]??Ut.OFFER_MALFORMED;return{ok:!1,status:p.response.status,error:`COMPATIBILITY_INCOMPATIBLE: ${S}`,errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:S,fallback_action:n?.remediationHint??"upgrade-client"},...n?{compatibility:n}:{}}}const{response:s,text:l}=p;let I=p.parsed;try{if(t.compatibility&&!n){if(/"(?:reviewReconciliation|review_reconciliation|reconciliationMetadata|releaseLifecycle|release_lifecycle|releaseBlocked|release_blocked|yoloopReleaseBlocked)"\s*:/u.test(l))return{ok:!1,status:s.status,error:`COMPATIBILITY_INCOMPATIBLE: ${Ut.UNNEGOTIATED_PROTECTED_FIELD}`,errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:Ut.UNNEGOTIATED_PROTECTED_FIELD,fallback_action:"upgrade-client"}};n=Ga({clientVersion:t.compatibility.clientVersion,serverVersion:"0.0.0",registryVersion:t.registryVersion,registryChecksum:t.registryChecksum,reason:Ut.SERVER_NEGOTIATION_MISSING})}if(s.ok)try{I=l?JSON.parse(l):{}}catch{return{ok:!1,status:s.status,error:"COMPATIBILITY_INCOMPATIBLE: response-json-malformed",errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:Ut.RESULT_MALFORMED},...n?{compatibility:n}:{}}}if(!s.ok)return t.privateExecution?{ok:!1,status:s.status,error:"private-execution-invoke-unavailable"}:{ok:!1,status:s.status,error:Object.keys(I).length>0?`${I.error_code??"ERROR"}: ${I.message??l}`:`HTTP ${s.status}: ${l}`,errorBody:Object.keys(I).length>0?I:void 0,...n?{compatibility:n}:{}};const S=I,u=s.headers.get("X-Client-Version-Warning");return u&&!mi&&(mi=!0,process.stderr.write(`
23
23
  [Neocortex] ${u}
24
24
 
25
- `)),{ok:!0,status:s.status,data:S,...n?{compatibility:n}:{}}}catch(S){return{ok:!1,status:0,error:(S instanceof Error?S.message:String(S)).includes("abort")?`Request timeout after ${Gr/1e3}s`:"Network error: invalid response"}}}async function Xc(e,t,i){const r=await Zt(e,"/api/v1/invoke/private-execution/consume",t,i,{maxAttempts:1,allowReplayRetry:!1});if(r.networkFailure||!r.response||!r.response.ok)throw new Error("private-execution-delivery-unavailable");return r.parsed}async function Zc(e,t,i){const r=await Zt(e,"/api/v1/invoke/private-execution/cancel",t,i,{maxAttempts:1,allowReplayRetry:!1});return!!r.response?.ok&&r.parsed.status==="cancelled"}async function Pi(e,t,i,r={}){const a=await Zt(e,"/api/v1/invoke/epic-claims/acknowledge",{...i,registryVersion:ot,registryChecksum:at},t,r);return!!a.response?.ok&&a.parsed.status==="ok"&&a.parsed.claimOutcome===i.status&&(!i.planningCheckpoint||a.parsed.memoryReceiptId===i.planningCheckpoint.memoryReceiptId)}async function es(e,t,i,r,a,n={}){if(!a)return 0;const o=$t(e);let p=0;for(const[s,l]of Object.entries(o.operations))l.planningProtocol==="root-staged-v1"||!l.claimId||!l.epicId||!t.epics?.[l.epicId]||!await Pi(i,r,{claimId:l.claimId,projectId:a,epicId:l.epicId,status:"materialized"},n)||(So(e,s),p+=1);return p}function ts(e,t){const i=t.state.pendingContinuationAuthorities,r=t.state.continuationSession;if(t.state.continuationPolicy!=="p205-finite-resume-v2"||i?.length!==1||!r)return;const a=i[0],n=a.certificate,o=n?.expectedTransition;if(a.storyIds!=="[CIRCULAR]"||n?.rank!=="[CIRCULAR]"||o?.selectedStoryIds!=="[CIRCULAR]")return;const p=typeof r.epicId=="string"?r.epicId:"",s=e.epics[p],l=Array.isArray(o.storyLifecycle)?o.storyLifecycle:[],I=l.length===1&&typeof l[0]?.storyId=="string"?l[0].storyId:"",u=e.stories[I]?.checkpoint;if(!s||s.branch_mode!=="epic"||typeof s.execution_branch!="string"||typeof s.origin_branch!="string"||s.branch_lease!==void 0&&s.branch_lease!==null||!u||u.qaVerdict!=="passed"||u.reviewVerdict!=="approved"||!Array.isArray(u.receiptRefs))return;const E=(Array.isArray(s.stories)?s.stories.filter(g=>typeof g=="string"):[]).find(g=>{const y=e.stories[g];return!y||["done","completed","merged"].includes(String(y.status))?!1:(Array.isArray(y.depends_on)?y.depends_on.filter(D=>typeof D=="string"):[]).every(D=>["done","completed","merged"].includes(String(e.stories[D]?.status)))});if(E)return{epicId:p,expectedNextStoryId:E,branchMode:"epic",executionBranch:s.execution_branch,originBranch:s.origin_branch,branchLeaseReleased:!0,checkpoint:{schemaVersion:1,storyId:u.storyId,epicId:u.epicId,branch:u.branch,baseSha:u.baseSha,headSha:u.headSha,receiptRefs:[...u.receiptRefs],qaVerdict:"passed",reviewVerdict:"approved"}}}const dr=["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"],ki=new Set(["done","completed","merged","cancelled","canceled","abandoned"]),Oi=new Set(["skipped-with-debt","documented"]);function Ni(e){return typeof e=="string"?e.trim().toLowerCase().replace(/_/g,"-"):""}function ns(e){const t=Ni(e);if(ki.has(t)||Oi.has(t))return 0;const i=dr.indexOf(t);return i<0?dr.length:dr.length-1-i}function rs(e,t){const i=e.epics[t];if(!i||!Array.isArray(i.stories)||i.stories.some(I=>typeof I!="string"||!/^P[1-9][0-9]*\.[0-9]+$/.test(I)))return null;const r=[...i.stories],a=[],n=[];let o=0,p=0;const s=[];for(const I of r){const S=e.stories[I];if(!S||!Array.isArray(S.depends_on)||S.depends_on.some(g=>typeof g!="string"))return null;const u=[...S.depends_on].sort(),_=ns(S.status),E=Ni(S.status);a.push({id:I,dependsOn:u}),n.push({id:I,status:S.status,dependsOn:u}),s.push({storyId:I,remaining:_}),o+=_,!ki.has(E)&&!Oi.has(E)&&(p+=1)}const l={version:1,policy:"p205-finite-resume-v2",epicId:t,storyIds:r,queueEpicIds:[t],initialEpicIndex:0,graphFingerprint:Et("p205-yoloop-graph-v1",a),lifecycleVersion:"p205-lifecycle-v1",terminalPredicateVersion:"p205-terminal-v1",initialSnapshotFingerprint:Et("p205-yoloop-initial-snapshot-v1",{epicId:t,stories:n}),initialRank:{version:1,queue:0,epic:p,lifecycle:o},initialStoryLifecycle:s};return Object.freeze({...l,sessionId:Et("p205-yoloop-session-v1",l)})}function Li(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 is(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=rs(e.snapshot,e.targetEpicId);if(!t)throw new Error("yoloop-causal-reconciliation-target-invalid");const i=String(t.graphFingerprint),r=Cr(e.projectRoot),a=Object.values(r.operational.identities).filter(M=>M.epicId===e.targetEpicId&&M.graphRevision===i);if(a.length!==1)throw new Error("epic-operational-identity-mismatch");const n=e.snapshot.yoloop,o=n?n.lock!==null||n.state.currentSession!==null?"active":"inactive":"unknown",p=ea({document:r.document,targetIdentityHash:a[0].identityHash,targetEpicId:e.targetEpicId,targetGraphRevision:i,legacyActivity:o});if(p.kind!=="eligible")throw new Error(p.reasonCodes[0]??"yoloop-causal-reconciliation-ineligible");const s=r.operational,l=s.yoloop.state.continuationSession,I=s.yoloop.state.pendingContinuationAuthorities??[],S=s.yoloop.state.runControl;if(!l||typeof l.sessionId!="string"||!S||!["success","exhausted"].includes(S.status)||I.length>1)throw new Error("yoloop-causal-reconciliation-preimage-invalid");const u=Et("p224-common-continuation-session-v1",s.yoloop.state.continuationSession??null),_=Et("p224-common-pending-authorities-v1",I),E=Et("p224-common-continuation-session-v1",t),g=Et("p224-invoke-session-recovery-v1",{identityHash:a[0].identityHash,originalInputSha256:e.originalInputSha256,canonicalInputSha256:e.canonicalInputSha256,expectedSessionHash:u,expectedPendingHash:_,nextSessionHash:E,runId:S.runId,runRevision:S.revision}),y={operationId:`p224rec-${g.slice(0,32)}`,idempotencyKey:`p224rec-${g.slice(0,32)}`,expectedCommonRevision:r.document.revision,expectedWriterEpoch:s.writerEpoch,expectedIdentityHash:a[0].identityHash,sourceEpicId:p.evidence.sourceEpicId,sourceGraphRevision:p.evidence.sourceGraphRevision,targetEpicId:e.targetEpicId,targetGraphRevision:i,expectedRunId:S.runId,expectedRunStatus:S.status,expectedRunRevision:S.revision,expectedSnapshotHash:S.latestSnapshotHash,sourceSessionId:l.sessionId,expectedSessionHash:u,expectedPendingHash:_,expectedPendingCount:I.length,nextSession:t,nextSessionHash:E},x=Zi(y),D={schemaVersion:"YoloopCrossEpicReconciliationReceipt/1.0",operationId:y.operationId,idempotencyKey:y.idempotencyKey,payloadHash:x,sourceEpicId:y.sourceEpicId,sourceGraphRevision:y.sourceGraphRevision,targetEpicId:y.targetEpicId,targetGraphRevision:y.targetGraphRevision,runId:y.expectedRunId,previousSessionHash:u,nextSessionHash:E,retiredAuthorityHash:_,retiredAuthorityCount:y.expectedPendingCount,outcome:"cross-epic-reconciled",publicSafe:!0},T={type:"reconcile_cross_epic_continuation",...y,payloadHash:x,receipt:D};await Xi(e.projectRoot,T);const P=Cr(e.projectRoot),C=P.operational.yoloop.state.pendingContinuationAuthorities??[];if(!P.operational.reconciliationReceipts.find(M=>M.payloadHash===x)||C.length!==0||Et("p224-common-continuation-session-v1",P.operational.yoloop.state.continuationSession??null)!==E)throw new Error("yoloop-causal-reconciliation-postimage-unverified");return Object.freeze({outcome:"applied",payloadHash:x,retryCount:1,publicSafe:!0})}catch(t){return Object.freeze({outcome:"blocked",reasonCode:Li(t),retryCount:0,publicSafe:!0})}}async function as(e){let t;try{if(t=e.inputEnvelope??Qt(e.inputSource??"args",e.args),La(t),t.rawArgs!==e.args)throw new Error("INVOKE_INPUT_ENVELOPE_ARGUMENT_CONFLICT")}catch{return{success:!1,error:"INVOCATION_MALFORMED_INPUT: explicit input integrity could not be verified.",errorCode:"INVOCATION_MALFORMED_INPUT",metadata:{invocationInput:{reason:"input-integrity-conflict",remediation:"Retry with exactly one of --args, --stdin or --args-file.",publicSafe:!0}},exitCode:1}}const i=t.rawArgs,r=jn(t);let a=i,n=r,o=Qr(i),p;if(o.outcome!=="resolved"){const c=Ro(i);c.kind==="canonicalized"&&(a=c.canonicalArgs,n=jn(Qt(t.source,a)),p=c.binding,o=Qr(a))}if(o.outcome!=="resolved"){const c=Ma(o,"client"),d=o.outcome==="malformed_input"?o.reason==="input_limit"||o.reason==="token_limit"||o.reason==="token_size_limit"?"input-limit-exceeded":o.reason==="invalid_control"||o.reason==="invalid_surrogate"?"invalid-control-character":o.reason==="unterminated_quote"||o.reason==="trailing_escape"||o.reason==="unsupported_escape"?"unterminated-quote":void 0:void 0,m=d?{code:"INVOCATION_MALFORMED_INPUT",reason:d,source:t.source,byteLength:t.byteLength,remediation:d==="input-limit-exceeded"?"Reduce the explicit command input or split the requested work into bounded invocations.":d==="invalid-control-character"?"Remove invalid control characters and retry with valid UTF-8 text.":"Close quotes and escapes, or use --stdin/--args-file for multiline content."}:void 0;return{success:!1,error:`INVOCATION_${o.outcome.toUpperCase()}`,errorCode:`INVOCATION_${o.outcome.toUpperCase()}`,metadata:{invocationAdmission:c,...m?{invocationInput:m}:{}},exitCode:1}}if(p&&(e={...e,args:a}),e.privateExecutionModel!==void 0&&(!e.privateExecutionBeta||e.strictReadOnly||!/^gpt-[a-z0-9][a-z0-9.-]{0,63}$/.test(e.privateExecutionModel)))return{success:!1,error:"private-codex-model-invalid",errorCode:"private-codex-model-invalid",exitCode:1};const s=Hn(e.projectRoot),l=o.selection.commandId,I=l==="yolo"&&!xr(a,l)?so(a):null,S=l==="tech-debt"&&o.selection.positionals.length===0&&(o.selection.operationId==="scan"&&Object.keys(o.selection.options).length===0||o.selection.operationId===void 0&&o.selection.options.scan===!0&&Object.keys(o.selection.options).length===1),u=ra.find(c=>c.id===l),_=u?.subcommands.find(c=>c.id===o.selection.operationId),E=_?_.policy.strictReadOnly==="allow":u?.policy.strictReadOnly==="allow",g=l==="diagnose";let y;try{y=ka({invocationId:sn(),intent:e.strictReadOnly||g?{schemaVersion:1,policy:xa,registryVersion:ot,registryChecksum:at}:void 0,registryVersion:ot,registryChecksum:at,registryAllowsStrict:E,requestCanonicalBytes:JSON.stringify({command:l})})}catch(c){if(c instanceof Vt)return{success:!1,error:c.code,errorCode:c.code,exitCode:1};throw c}{y.beginProjection();for(const c of Dr)y.project(c);for(const c of Ta)y.project(c);y.seal()}const x=y.mode==="strict";if(l==="create-epic"||l==="idea-diagnose")try{const c=Ya(s);if(c&&c!=="finalized")return{success:!1,error:'PROJECT_IDENTITY_MIGRATION_INCOMPLETE: retry `neocortex-client invoke --args "*migrate-project-id"` before create-epic.',errorCode:"PROJECT_IDENTITY_MIGRATION_INCOMPLETE",metadata:{projectIdentityMigration:{phase:c,publicSafe:!0}},exitCode:1}}catch(c){const d=c instanceof Vn?c.code:"PROJECT_IDENTITY_MIGRATION_STATE_CORRUPT";return{success:!1,error:d,errorCode:d,exitCode:1}}const D=e.environment??process.env;if(e.privateExecutionBeta&&(l!=="yolo"&&l!=="research"&&l!=="write-spec"&&l!=="create-tasks"&&l!=="implement"&&l!=="exec"&&l!=="create-epic"&&l!=="idea-diagnose"&&l!=="idea-research"&&l!=="generate-epic"&&l!=="sync-openapi"&&l!=="chaos-plan"&&l!=="ui-ux-review"&&l!=="arch-prd"&&l!=="arch-architecture"&&l!=="arch-fitness-functions"&&l!=="arch-api-contracts"&&l!=="arch-api-integrations"&&l!=="arch-database"&&l!=="arch-security"&&l!=="arch-design-system"&&l!=="arch-performance"&&l!=="arch-testing"&&l!=="arch-infrastructure"&&l!=="arch-review"&&l!=="update-memory"&&l!=="arch-ux-design"&&l!=="generate-pacts"&&l!=="property-test"&&!S||x||e.platformTarget!==void 0&&e.platformTarget!=="codex"))return{success:!1,error:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",errorCode:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",exitCode:1};const T=_a({cwd:s,env:D,targetFlag:e.privateExecutionBeta?"codex":e.platformTarget}),P=T.targetId,C=e.privateExecutionBeta?void 0:Ca({cwd:s,env:D,targetFlag:e.platformTarget,nativeHostVersion:Lo(T,D)},T);if(I)try{Jn(s,{allowMissingRuntime:!0})}catch(c){const d=c instanceof st?c.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${d}. No request was sent; repair the canonical project state/runtime sidecar and retry.
26
- `),{success:!1,error:d,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}let R=I?Dn({strictReadOnly:!0}):hi(y);const M=(e.serverUrl??R?.serverUrl??aa).replace(/\/+$/,"");let N;if(I){const c=await co(M);if(!c.supported)return{success:!1,error:`YOLO_INVOKE_ENVELOPE_CAPABILITY_UNAVAILABLE: target server does not advertise ${Ra}; Local YOLO/TDD Release Gate was not executed and no invoke request was sent.`,errorCode:"YOLO_INVOKE_ENVELOPE_CAPABILITY_UNAVAILABLE",metadata:{yoloInvokeEnvelopeCapability:c},exitCode:1};try{N=Br({projectRoot:s,storyId:I,epicId:I.split(".")[0],inputSha256:n.sha256,onOmittedReferences:d=>process.stderr.write(`[Neocortex] yolo-spec-supporting-references-omitted count=${d}; core story artifacts preserved.
27
- `)})}catch(d){const m=d instanceof Error&&/^yolo-spec-envelope-[a-z-]+$/.test(d.message)?d.message:"yolo-spec-envelope-unsafe";return{success:!1,error:m,errorCode:m,exitCode:1}}R=hi(y)}if(l!=="migrate-project-id"&&y.execute({phase:"client-preflight",domain:"client-persistence",category:"first-run-marker",operation:"create"},()=>Co(),()=>{}),l==="migrate-project-id"){const c=await qa(M);if(!c.supported)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_CAPABILITY_UNAVAILABLE: the server did not advertise the versioned migration capability; no local state was changed.",errorCode:"PROJECT_IDENTITY_MIGRATION_CAPABILITY_UNAVAILABLE",metadata:{projectIdentityMigrationCapability:c},exitCode:1};const d=[];let m;try{m=Fa(s)}catch($){const Ee=$ instanceof Vn?$.code:"PROJECT_IDENTITY_MIGRATION_PREPARE_FAILED";return{success:!1,error:Ee,errorCode:Ee,exitCode:1}}d.push(Bt({phase:"prepare",outcome:m.changed&&m.document.phase==="prepared"?"prepared":"retry",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId}));const A=Sn(s);if(A.config.project_id!==m.document.projectId)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",errorCode:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",metadata:{invocationDiagnostics:d},exitCode:1};const U=await gi(M,R?.licenseKey,y);if(U.status!=="authenticated"){const $=U.status==="refresh-required";return{success:!1,error:$?"Authentication refresh required. Run: neocortex activate YOUR-LICENSE-KEY":"Not authenticated. Visit https://neocortex.sh/portal/login to get your license key, then run: neocortex activate YOUR-LICENSE-KEY",errorCode:$?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",metadata:{invocationDiagnostics:d},exitCode:$?1:2}}let ie;try{ie=br(e.args.trim(),A)}catch($){const Ee=$ instanceof Tr?$.code:"PROJECT_IDENTITY_MIGRATION_PROJECTION_FAILED";return{success:!1,error:Ee,errorCode:Ee,metadata:{invocationDiagnostics:d},exitCode:1}}let de={args:i,projectRoot:s.replace(Kt(),"~"),stateSnapshot:ie,platformTarget:P,...C?{nativeHostAttestation:C}:{},projectId:m.document.projectId,projectIdentityMigration:m.request,inputEvidence:r,idempotencyKey:m.document.operationId,registryVersion:ot,registryChecksum:at,compatibility:Wn()};try{de=er(de).body}catch($){if($ instanceof Fn||$ instanceof Yn)return{success:!1,error:$.message,errorCode:$.code,metadata:{invokePayload:$.telemetry,invocationDiagnostics:d},exitCode:1};throw $}const ae=await Mn("invoke-query",()=>sr(M,de,U.token,{refreshToken:()=>U.client.forceRefresh()}));if(!ae.ok||!ae.data)return d.push(Bt({phase:"seed",outcome:"rejected",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId})),{success:!1,error:ze(ae.error??"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",Pt),errorCode:typeof ae.errorBody?.error_code=="string"?ae.errorBody.error_code:"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",metadata:{invocationDiagnostics:d},exitCode:ae.status===401?2:1};const fe=ae.data.metadata?.projectIdentityMigration;try{Da(fe),d.push(Bt({phase:"seed",outcome:fe.status,floor:fe.acceptedLegacyFloor,licenseId:"local-client",projectId:fe.projectId})),Ga(s,fe),d.push(Bt({phase:"remote-acknowledged",outcome:fe.status,floor:fe.acceptedLegacyFloor,licenseId:"local-client",projectId:fe.projectId})),Wa(s,fe),d.push(Bt({phase:"finalize",outcome:"finalized",floor:fe.acceptedLegacyFloor,licenseId:"local-client",projectId:fe.projectId}))}catch($){d.push(Bt({phase:"reconcile",outcome:"rejected",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId}));const Ee=$ instanceof Vn?$.code:$ instanceof Error?$.message:"PROJECT_IDENTITY_MIGRATION_RECEIPT_INVALID";return{success:!1,error:Ee,errorCode:Ee,metadata:{invocationDiagnostics:d},exitCode:1}}return y.complete(),{success:!0,instructions:ae.data.instructions,metadata:{...ae.data.metadata,...ae.compatibility?{compatibility:ae.compatibility}:{},invocationDiagnostics:d},exitCode:0}}try{const{normalizeYoloopTargetArgs:c}=await import("../yoloop/target-normalization.js"),d=c(e.args,{projectRoot:s});if(!d.ok)return process.stderr.write(`${d.message} reason=${d.reasonCode}
25
+ `)),{ok:!0,status:s.status,data:S,...n?{compatibility:n}:{}}}catch(S){return{ok:!1,status:0,error:(S instanceof Error?S.message:String(S)).includes("abort")?`Request timeout after ${Wr/1e3}s`:"Network error: invalid response"}}}async function es(e,t,i){const r=await Xt(e,"/api/v1/invoke/private-execution/consume",t,i,{maxAttempts:1,allowReplayRetry:!1});if(r.networkFailure||!r.response||!r.response.ok)throw new Error("private-execution-delivery-unavailable");return r.parsed}async function ts(e,t,i){const r=await Xt(e,"/api/v1/invoke/private-execution/cancel",t,i,{maxAttempts:1,allowReplayRetry:!1});return!!r.response?.ok&&r.parsed.status==="cancelled"}async function ki(e,t,i,r={}){const a=await Xt(e,"/api/v1/invoke/epic-claims/acknowledge",{...i,registryVersion:ot,registryChecksum:at},t,r);return!!a.response?.ok&&a.parsed.status==="ok"&&a.parsed.claimOutcome===i.status&&(!i.planningCheckpoint||a.parsed.memoryReceiptId===i.planningCheckpoint.memoryReceiptId)}async function ns(e,t,i,r,a,n={}){if(!a)return 0;const o=$t(e);let p=0;for(const[s,l]of Object.entries(o.operations))l.planningProtocol==="root-staged-v1"||!l.claimId||!l.epicId||!t.epics?.[l.epicId]||!await ki(i,r,{claimId:l.claimId,projectId:a,epicId:l.epicId,status:"materialized"},n)||(Co(e,s),p+=1);return p}function rs(e,t){const i=t.state.pendingContinuationAuthorities,r=t.state.continuationSession;if(t.state.continuationPolicy!=="p205-finite-resume-v2"||i?.length!==1||!r)return;const a=i[0],n=a.certificate,o=n?.expectedTransition;if(a.storyIds!=="[CIRCULAR]"||n?.rank!=="[CIRCULAR]"||o?.selectedStoryIds!=="[CIRCULAR]")return;const p=typeof r.epicId=="string"?r.epicId:"",s=e.epics[p],l=Array.isArray(o.storyLifecycle)?o.storyLifecycle:[],I=l.length===1&&typeof l[0]?.storyId=="string"?l[0].storyId:"",u=e.stories[I]?.checkpoint;if(!s||s.branch_mode!=="epic"||typeof s.execution_branch!="string"||typeof s.origin_branch!="string"||s.branch_lease!==void 0&&s.branch_lease!==null||!u||u.qaVerdict!=="passed"||u.reviewVerdict!=="approved"||!Array.isArray(u.receiptRefs))return;const E=(Array.isArray(s.stories)?s.stories.filter(g=>typeof g=="string"):[]).find(g=>{const y=e.stories[g];return!y||["done","completed","merged"].includes(String(y.status))?!1:(Array.isArray(y.depends_on)?y.depends_on.filter(L=>typeof L=="string"):[]).every(L=>["done","completed","merged"].includes(String(e.stories[L]?.status)))});if(E)return{epicId:p,expectedNextStoryId:E,branchMode:"epic",executionBranch:s.execution_branch,originBranch:s.origin_branch,branchLeaseReleased:!0,checkpoint:{schemaVersion:1,storyId:u.storyId,epicId:u.epicId,branch:u.branch,baseSha:u.baseSha,headSha:u.headSha,receiptRefs:[...u.receiptRefs],qaVerdict:"passed",reviewVerdict:"approved"}}}const pr=["backlog","pending","ready","in-progress","branch-ready","diagnose","research","write-spec","create-tasks","implemented","refactor-suggest-done","property-tests-emitted","tests-validated","qa-gate-passed","memory-updated","committed","synced","pr-created","pr-reviewed","done"],Oi=new Set(["done","completed","merged","cancelled","canceled","abandoned"]),Ni=new Set(["skipped-with-debt","documented"]);function Li(e){return typeof e=="string"?e.trim().toLowerCase().replace(/_/g,"-"):""}function is(e){const t=Li(e);if(Oi.has(t)||Ni.has(t))return 0;const i=pr.indexOf(t);return i<0?pr.length:pr.length-1-i}function as(e,t){const i=e.epics[t];if(!i||!Array.isArray(i.stories)||i.stories.some(I=>typeof I!="string"||!/^P[1-9][0-9]*\.[0-9]+$/.test(I)))return null;const r=[...i.stories],a=[],n=[];let o=0,p=0;const s=[];for(const I of r){const S=e.stories[I];if(!S||!Array.isArray(S.depends_on)||S.depends_on.some(g=>typeof g!="string"))return null;const u=[...S.depends_on].sort(),_=is(S.status),E=Li(S.status);a.push({id:I,dependsOn:u}),n.push({id:I,status:S.status,dependsOn:u}),s.push({storyId:I,remaining:_}),o+=_,!Oi.has(E)&&!Ni.has(E)&&(p+=1)}const l={version:1,policy:"p205-finite-resume-v2",epicId:t,storyIds:r,queueEpicIds:[t],initialEpicIndex:0,graphFingerprint:It("p205-yoloop-graph-v1",a),lifecycleVersion:"p205-lifecycle-v1",terminalPredicateVersion:"p205-terminal-v1",initialSnapshotFingerprint:It("p205-yoloop-initial-snapshot-v1",{epicId:t,stories:n}),initialRank:{version:1,queue:0,epic:p,lifecycle:o},initialStoryLifecycle:s};return Object.freeze({...l,sessionId:It("p205-yoloop-session-v1",l)})}function Di(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 os(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=as(e.snapshot,e.targetEpicId);if(!t)throw new Error("yoloop-causal-reconciliation-target-invalid");const i=String(t.graphFingerprint),r=_r(e.projectRoot),a=Object.values(r.operational.identities).filter(M=>M.epicId===e.targetEpicId&&M.graphRevision===i);if(a.length!==1)throw new Error("epic-operational-identity-mismatch");const n=e.snapshot.yoloop,o=n?n.lock!==null||n.state.currentSession!==null?"active":"inactive":"unknown",p=na({document:r.document,targetIdentityHash:a[0].identityHash,targetEpicId:e.targetEpicId,targetGraphRevision:i,legacyActivity:o});if(p.kind!=="eligible")throw new Error(p.reasonCodes[0]??"yoloop-causal-reconciliation-ineligible");const s=r.operational,l=s.yoloop.state.continuationSession,I=s.yoloop.state.pendingContinuationAuthorities??[],S=s.yoloop.state.runControl;if(!l||typeof l.sessionId!="string"||!S||!["success","exhausted"].includes(S.status)||I.length>1)throw new Error("yoloop-causal-reconciliation-preimage-invalid");const u=It("p224-common-continuation-session-v1",s.yoloop.state.continuationSession??null),_=It("p224-common-pending-authorities-v1",I),E=It("p224-common-continuation-session-v1",t),g=It("p224-invoke-session-recovery-v1",{identityHash:a[0].identityHash,originalInputSha256:e.originalInputSha256,canonicalInputSha256:e.canonicalInputSha256,expectedSessionHash:u,expectedPendingHash:_,nextSessionHash:E,runId:S.runId,runRevision:S.revision}),y={operationId:`p224rec-${g.slice(0,32)}`,idempotencyKey:`p224rec-${g.slice(0,32)}`,expectedCommonRevision:r.document.revision,expectedWriterEpoch:s.writerEpoch,expectedIdentityHash:a[0].identityHash,sourceEpicId:p.evidence.sourceEpicId,sourceGraphRevision:p.evidence.sourceGraphRevision,targetEpicId:e.targetEpicId,targetGraphRevision:i,expectedRunId:S.runId,expectedRunStatus:S.status,expectedRunRevision:S.revision,expectedSnapshotHash:S.latestSnapshotHash,sourceSessionId:l.sessionId,expectedSessionHash:u,expectedPendingHash:_,expectedPendingCount:I.length,nextSession:t,nextSessionHash:E},b=ta(y),L={schemaVersion:"YoloopCrossEpicReconciliationReceipt/1.0",operationId:y.operationId,idempotencyKey:y.idempotencyKey,payloadHash:b,sourceEpicId:y.sourceEpicId,sourceGraphRevision:y.sourceGraphRevision,targetEpicId:y.targetEpicId,targetGraphRevision:y.targetGraphRevision,runId:y.expectedRunId,previousSessionHash:u,nextSessionHash:E,retiredAuthorityHash:_,retiredAuthorityCount:y.expectedPendingCount,outcome:"cross-epic-reconciled",publicSafe:!0},T={type:"reconcile_cross_epic_continuation",...y,payloadHash:b,receipt:L};await ea(e.projectRoot,T);const P=_r(e.projectRoot),C=P.operational.yoloop.state.pendingContinuationAuthorities??[];if(!P.operational.reconciliationReceipts.find(M=>M.payloadHash===b)||C.length!==0||It("p224-common-continuation-session-v1",P.operational.yoloop.state.continuationSession??null)!==E)throw new Error("yoloop-causal-reconciliation-postimage-unverified");return Object.freeze({outcome:"applied",payloadHash:b,retryCount:1,publicSafe:!0})}catch(t){return Object.freeze({outcome:"blocked",reasonCode:Di(t),retryCount:0,publicSafe:!0})}}async function cs(e){let t;try{if(t=e.inputEnvelope??Kt(e.inputSource??"args",e.args),Ma(t),t.rawArgs!==e.args)throw new Error("INVOKE_INPUT_ENVELOPE_ARGUMENT_CONFLICT")}catch{return{success:!1,error:"INVOCATION_MALFORMED_INPUT: explicit input integrity could not be verified.",errorCode:"INVOCATION_MALFORMED_INPUT",metadata:{invocationInput:{reason:"input-integrity-conflict",remediation:"Retry with exactly one of --args, --stdin or --args-file.",publicSafe:!0}},exitCode:1}}const i=t.rawArgs,r=Vn(t);let a=i,n=r,o=Xr(i),p;if(o.outcome!=="resolved"){const c=bo(i);c.kind==="canonicalized"&&(a=c.canonicalArgs,n=Vn(Kt(t.source,a)),p=c.binding,o=Xr(a))}if(o.outcome!=="resolved"){const c=Va(o,"client"),d=o.outcome==="malformed_input"?o.reason==="input_limit"||o.reason==="token_limit"||o.reason==="token_size_limit"?"input-limit-exceeded":o.reason==="invalid_control"||o.reason==="invalid_surrogate"?"invalid-control-character":o.reason==="unterminated_quote"||o.reason==="trailing_escape"||o.reason==="unsupported_escape"?"unterminated-quote":void 0:void 0,m=d?{code:"INVOCATION_MALFORMED_INPUT",reason:d,source:t.source,byteLength:t.byteLength,remediation:d==="input-limit-exceeded"?"Reduce the explicit command input or split the requested work into bounded invocations.":d==="invalid-control-character"?"Remove invalid control characters and retry with valid UTF-8 text.":"Close quotes and escapes, or use --stdin/--args-file for multiline content."}:void 0;return{success:!1,error:`INVOCATION_${o.outcome.toUpperCase()}`,errorCode:`INVOCATION_${o.outcome.toUpperCase()}`,metadata:{invocationAdmission:c,...m?{invocationInput:m}:{}},exitCode:1}}if(p&&(e={...e,args:a}),e.privateExecutionModel!==void 0&&(!e.privateExecutionBeta||e.strictReadOnly||!/^gpt-[a-z0-9][a-z0-9.-]{0,63}$/.test(e.privateExecutionModel)))return{success:!1,error:"private-codex-model-invalid",errorCode:"private-codex-model-invalid",exitCode:1};const s=Gn(e.projectRoot),l=o.selection.commandId,I=l==="yolo"&&!Tr(a,l)?lo(a):null,S=l==="tech-debt"&&o.selection.positionals.length===0&&(o.selection.operationId==="scan"&&Object.keys(o.selection.options).length===0||o.selection.operationId===void 0&&o.selection.options.scan===!0&&Object.keys(o.selection.options).length===1),u=aa.find(c=>c.id===l),_=u?.subcommands.find(c=>c.id===o.selection.operationId),E=_?_.policy.strictReadOnly==="allow":u?.policy.strictReadOnly==="allow",g=l==="diagnose";let y;try{y=Na({invocationId:dn(),intent:e.strictReadOnly||g?{schemaVersion:1,policy:Pa,registryVersion:ot,registryChecksum:at}:void 0,registryVersion:ot,registryChecksum:at,registryAllowsStrict:E,requestCanonicalBytes:JSON.stringify({command:l})})}catch(c){if(c instanceof Vt)return{success:!1,error:c.code,errorCode:c.code,exitCode:1};throw c}{y.beginProjection();for(const c of Mr)y.project(c);for(const c of ka)y.project(c);y.seal()}const b=y.mode==="strict";if(l==="create-epic"||l==="idea-diagnose")try{const c=za(s);if(c&&c!=="finalized")return{success:!1,error:'PROJECT_IDENTITY_MIGRATION_INCOMPLETE: retry `neocortex-client invoke --args "*migrate-project-id"` before create-epic.',errorCode:"PROJECT_IDENTITY_MIGRATION_INCOMPLETE",metadata:{projectIdentityMigration:{phase:c,publicSafe:!0}},exitCode:1}}catch(c){const d=c instanceof Bn?c.code:"PROJECT_IDENTITY_MIGRATION_STATE_CORRUPT";return{success:!1,error:d,errorCode:d,exitCode:1}}const L=e.environment??process.env;if(e.privateExecutionBeta&&(l!=="yolo"&&l!=="research"&&l!=="write-spec"&&l!=="create-tasks"&&l!=="implement"&&l!=="exec"&&l!=="create-epic"&&l!=="idea-diagnose"&&l!=="idea-research"&&l!=="generate-epic"&&l!=="sync-openapi"&&l!=="chaos-plan"&&l!=="ui-ux-review"&&l!=="arch-prd"&&l!=="arch-architecture"&&l!=="arch-fitness-functions"&&l!=="arch-api-contracts"&&l!=="arch-api-integrations"&&l!=="arch-database"&&l!=="arch-security"&&l!=="arch-design-system"&&l!=="arch-performance"&&l!=="arch-testing"&&l!=="arch-infrastructure"&&l!=="arch-review"&&l!=="update-memory"&&l!=="arch-ux-design"&&l!=="generate-pacts"&&l!=="property-test"&&!S||b||e.platformTarget!==void 0&&e.platformTarget!=="codex"))return{success:!1,error:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",errorCode:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",exitCode:1};const T=Ra({cwd:s,env:L,targetFlag:e.privateExecutionBeta?"codex":e.platformTarget}),P=T.targetId,C=e.privateExecutionBeta?void 0:wa({cwd:s,env:L,targetFlag:e.platformTarget,nativeHostVersion:Mo(T,L)},T);if(I)try{Kn(s,{allowMissingRuntime:!0})}catch(c){const d=c instanceof st?c.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${d}. No request was sent; repair the canonical project state/runtime sidecar and retry.
26
+ `),{success:!1,error:d,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}let R=I?Mn({strictReadOnly:!0}):gi(y);const M=(e.serverUrl??R?.serverUrl??ca).replace(/\/+$/,"");let N;if(I){const c=await po(M);if(!c.supported)return{success:!1,error:`YOLO_INVOKE_ENVELOPE_CAPABILITY_UNAVAILABLE: target server does not advertise ${ba}; Local YOLO/TDD Release Gate was not executed and no invoke request was sent.`,errorCode:"YOLO_INVOKE_ENVELOPE_CAPABILITY_UNAVAILABLE",metadata:{yoloInvokeEnvelopeCapability:c},exitCode:1};try{N=Ur({projectRoot:s,storyId:I,epicId:I.split(".")[0],inputSha256:n.sha256,onOmittedReferences:d=>process.stderr.write(`[Neocortex] yolo-spec-supporting-references-omitted count=${d}; core story artifacts preserved.
27
+ `)})}catch(d){const m=d instanceof Error&&/^yolo-spec-envelope-[a-z-]+$/.test(d.message)?d.message:"yolo-spec-envelope-unsafe";return{success:!1,error:m,errorCode:m,exitCode:1}}R=gi(y)}if(l!=="migrate-project-id"&&y.execute({phase:"client-preflight",domain:"client-persistence",category:"first-run-marker",operation:"create"},()=>wo(),()=>{}),l==="migrate-project-id"){const c=await Ja(M);if(!c.supported)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_CAPABILITY_UNAVAILABLE: the server did not advertise the versioned migration capability; no local state was changed.",errorCode:"PROJECT_IDENTITY_MIGRATION_CAPABILITY_UNAVAILABLE",metadata:{projectIdentityMigrationCapability:c},exitCode:1};const d=[];let m;try{m=qa(s)}catch($){const Ee=$ instanceof Bn?$.code:"PROJECT_IDENTITY_MIGRATION_PREPARE_FAILED";return{success:!1,error:Ee,errorCode:Ee,exitCode:1}}d.push(Bt({phase:"prepare",outcome:m.changed&&m.document.phase==="prepared"?"prepared":"retry",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId}));const A=vn(s);if(A.config.project_id!==m.document.projectId)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",errorCode:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",metadata:{invocationDiagnostics:d},exitCode:1};const U=await fi(M,R?.licenseKey,y);if(U.status!=="authenticated"){const $=U.status==="refresh-required";return{success:!1,error:$?"Authentication refresh required. Run: neocortex activate YOUR-LICENSE-KEY":"Not authenticated. Visit https://neocortex.sh/portal/login to get your license key, then run: neocortex activate YOUR-LICENSE-KEY",errorCode:$?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",metadata:{invocationDiagnostics:d},exitCode:$?1:2}}let ie;try{ie=xr(e.args.trim(),A)}catch($){const Ee=$ instanceof Pr?$.code:"PROJECT_IDENTITY_MIGRATION_PROJECTION_FAILED";return{success:!1,error:Ee,errorCode:Ee,metadata:{invocationDiagnostics:d},exitCode:1}}let de={args:i,projectRoot:s.replace(Jt(),"~"),stateSnapshot:ie,platformTarget:P,...C?{nativeHostAttestation:C}:{},projectId:m.document.projectId,projectIdentityMigration:m.request,inputEvidence:r,idempotencyKey:m.document.operationId,registryVersion:ot,registryChecksum:at,compatibility:Fn()};try{de=tr(de).body}catch($){if($ instanceof Yn||$ instanceof qn)return{success:!1,error:$.message,errorCode:$.code,metadata:{invokePayload:$.telemetry,invocationDiagnostics:d},exitCode:1};throw $}const ae=await jn("invoke-query",()=>dr(M,de,U.token,{refreshToken:()=>U.client.forceRefresh()}));if(!ae.ok||!ae.data)return d.push(Bt({phase:"seed",outcome:"rejected",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId})),{success:!1,error:ze(ae.error??"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",kt),errorCode:typeof ae.errorBody?.error_code=="string"?ae.errorBody.error_code:"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",metadata:{invocationDiagnostics:d},exitCode:ae.status===401?2:1};const fe=ae.data.metadata?.projectIdentityMigration;try{ja(fe),d.push(Bt({phase:"seed",outcome:fe.status,floor:fe.acceptedLegacyFloor,licenseId:"local-client",projectId:fe.projectId})),Fa(s,fe),d.push(Bt({phase:"remote-acknowledged",outcome:fe.status,floor:fe.acceptedLegacyFloor,licenseId:"local-client",projectId:fe.projectId})),Ya(s,fe),d.push(Bt({phase:"finalize",outcome:"finalized",floor:fe.acceptedLegacyFloor,licenseId:"local-client",projectId:fe.projectId}))}catch($){d.push(Bt({phase:"reconcile",outcome:"rejected",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId}));const Ee=$ instanceof Bn?$.code:$ instanceof Error?$.message:"PROJECT_IDENTITY_MIGRATION_RECEIPT_INVALID";return{success:!1,error:Ee,errorCode:Ee,metadata:{invocationDiagnostics:d},exitCode:1}}return y.complete(),{success:!0,instructions:ae.data.instructions,metadata:{...ae.data.metadata,...ae.compatibility?{compatibility:ae.compatibility}:{},invocationDiagnostics:d},exitCode:0}}try{const{normalizeYoloopTargetArgs:c}=await import("../yoloop/target-normalization.js"),d=c(e.args,{projectRoot:s});if(!d.ok)return process.stderr.write(`${d.message} reason=${d.reasonCode}
28
28
  `),{success:!1,error:d.message,exitCode:1};d.changed&&(e={...e,args:d.args},process.stderr.write(`[Neocortex] yoloop target normalized: ${d.reasonCodes.join(",")}
29
29
  `))}catch{const c="INVALID_YOLOOP_TARGET: yoloop target normalization was unavailable; no request was sent.";return process.stderr.write(`${c}
30
- `),{success:!1,error:c,exitCode:1}}const q=pi(l);if(q)try{Jn(s,{allowMissingRuntime:!0}).runtimeMissing&&(await y.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},async()=>Za(s),async()=>{}),Jn(s))}catch(c){const d=c instanceof st?c.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${d}. No request was sent; repair the canonical project state and retry.
31
- `),{success:!1,error:d,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}if(l!=="migrate-state")try{y.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>pa(s,{args:e.args,canonicalCommandId:l}),()=>{})}catch(c){if(c instanceof la)return process.stderr.write(`${c.message}
30
+ `),{success:!1,error:c,exitCode:1}}const z=li(l);if(z)try{Kn(s,{allowMissingRuntime:!0}).runtimeMissing&&(await y.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},async()=>to(s),async()=>{}),Kn(s))}catch(c){const d=c instanceof st?c.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${d}. No request was sent; repair the canonical project state and retry.
31
+ `),{success:!1,error:d,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}if(l!=="migrate-state")try{y.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>ua(s,{args:e.args,canonicalCommandId:l}),()=>{})}catch(c){if(c instanceof ha)return process.stderr.write(`${c.message}
32
32
  `),{success:!1,error:c.message,exitCode:1};const d=c instanceof Error?c.message:String(c);return process.stderr.write(`[Neocortex] state.json repair stopped unexpectedly: ${d}. No request was sent; inspect .neocortex/state.json and rerun.
33
- `),{success:!1,error:d,exitCode:1}}let Z;if(e.privateExecutionBeta&&(l==="sync-openapi"||l==="chaos-plan"||l==="arch-prd"||l==="arch-architecture"||l==="arch-fitness-functions"||l==="arch-api-contracts"||l==="arch-api-integrations"||l==="arch-database"||l==="arch-security"||l==="arch-design-system"||l==="arch-performance"||l==="arch-testing"||l==="arch-infrastructure"||l==="arch-review"||l==="update-memory"||l==="arch-ux-design"||l==="generate-pacts"||l==="property-test"||S))try{const{capturePrivateProjectStepBaseline:c}=await import("../private-execution/isolated-workspace.js");Z=c(s)}catch{const c="private-execution-project-snapshot-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let j;try{const c=await Xo(s,e.args,l);j=Sn(s,{epicAware:q,p205Authorities:c,verifyPlanningGeneration:e.privateExecutionBeta&&l==="create-epic"})}catch(c){const d=c instanceof st?c.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${d}. No request was sent; repair the canonical project state/runtime sidecar and retry.
33
+ `),{success:!1,error:d,exitCode:1}}let Z;if(e.privateExecutionBeta&&(l==="sync-openapi"||l==="chaos-plan"||l==="arch-prd"||l==="arch-architecture"||l==="arch-fitness-functions"||l==="arch-api-contracts"||l==="arch-api-integrations"||l==="arch-database"||l==="arch-security"||l==="arch-design-system"||l==="arch-performance"||l==="arch-testing"||l==="arch-infrastructure"||l==="arch-review"||l==="update-memory"||l==="arch-ux-design"||l==="generate-pacts"||l==="property-test"||S))try{const{capturePrivateProjectStepBaseline:c}=await import("../private-execution/isolated-workspace.js");Z=c(s)}catch{const c="private-execution-project-snapshot-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let j;try{const c=await ec(s,e.args,l);j=vn(s,{epicAware:z,p205Authorities:c,verifyPlanningGeneration:e.privateExecutionBeta&&l==="create-epic"})}catch(c){const d=c instanceof st?c.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${d}. No request was sent; repair the canonical project state/runtime sidecar and retry.
34
34
  `),{success:!1,error:d,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}try{const{maybeAutoResolveYoloopArgs:c}=await import("../yoloop/invoke-hooks.js"),d={args:e.args,projectRoot:s,logger:{info:m=>process.stderr.write(`${m}
35
35
  `),warn:m=>process.stderr.write(`${m}
36
- `)}};c(d),d.args!==e.args&&(e={...e,args:d.args},a=d.args,n=jn(Qt(t.source,a)))}catch(c){const d=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] Auto-resolve hook (P121.05) failed: ${d}. Proceeding with raw args.
37
- `)}try{const{readYoloopForRequest:c}=await import("../yoloop/invoke-hooks.js"),d=await c(e.args,s);if(d){const m=ts(j,d);j.yoloop=m?{...d,continuationRecoveryEvidence:m}:d}}catch(c){if(/^\s*\*?(?:yoloop|auto-yolo|epic-runner|story-runner|loop-yolo|auto-epic)\b/i.test(e.args)){const m=c instanceof Error?c.message.match(/\bYOLOOP_[A-Z0-9_]+\b/)?.[0]??"YOLOOP_STATE_READ_FAILED":"YOLOOP_STATE_READ_FAILED";return process.stderr.write(`[Neocortex] ${m}. No yoloop request was sent and no state was mutated.
36
+ `)}};c(d),d.args!==e.args&&(e={...e,args:d.args},a=d.args,n=Vn(Kt(t.source,a)))}catch(c){const d=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] Auto-resolve hook (P121.05) failed: ${d}. Proceeding with raw args.
37
+ `)}try{const{readYoloopForRequest:c}=await import("../yoloop/invoke-hooks.js"),d=await c(e.args,s);if(d){const m=rs(j,d);j.yoloop=m?{...d,continuationRecoveryEvidence:m}:d}}catch(c){if(/^\s*\*?(?:yoloop|auto-yolo|epic-runner|story-runner|loop-yolo|auto-epic)\b/i.test(e.args)){const m=c instanceof Error?c.message.match(/\bYOLOOP_[A-Z0-9_]+\b/)?.[0]??"YOLOOP_STATE_READ_FAILED":"YOLOOP_STATE_READ_FAILED";return process.stderr.write(`[Neocortex] ${m}. No yoloop request was sent and no state was mutated.
38
38
  `),{success:!1,error:m,errorCode:m,exitCode:1}}}try{const{readContinuityForRequest:c}=await import("../continuity/invoke-hooks.js"),d=await c(e.args,s,void 0,y,{includeExistingStore:!g});d&&(j.continuity=d)}catch(c){if(c instanceof Vt)return{success:!1,error:c.code,errorCode:c.code,exitCode:1};const d=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] continuity snapshot hook failed: ${d}. Proceeding without continuity state.
39
39
  `)}try{const{maybeRunDiscoveryHook:c}=await import("../yoloop/invoke-hooks.js");await c({args:e.args,projectRoot:s,stateSnapshot:j,featureFlag:process.env.YOLOOP_AUTO_DISCOVERY!=="off",logger:{warn:d=>{console.warn(d)},info:d=>{console.error(d)}}})}catch(c){const d=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] discovery hook failed: ${d}. Proceeding without enrichment.
40
40
  `)}try{const{readArchitecturePolicy:c}=await import("../policy/architecture-policy.js"),d=await c(s);d&&(j.architecture_policy=d)}catch(c){const d=c instanceof Error?c.message:String(c);console.warn(`[Neocortex] architecture-policy hook failed: ${d}. Proceeding without policy.`)}try{const c=/^(1|true|on|yes)$/i.test(process.env.NEOCORTEX_GRAPH_RETRIEVAL??""),{maybeRunGraphRetrievalHook:d}=await import("../yoloop/invoke-hooks.js"),m=await d({args:e.args,projectRoot:s,featureFlag:c,logger:{warn:A=>process.stderr.write(`${A}
41
41
  `)}});m.applied&&m.metadata&&(j.graphRetrieval=m.metadata)}catch(c){const d=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] graph retrieval hook failed: ${d}. Proceeding without enrichment.
42
- `)}try{if(ko(e.args)){const{collectProjectEvidence:c}=await import("../evidence/collector.js"),d=o.selection.uiUxReview?.architectureDir,m=c({projectRoot:s,...d?{candidatePaths:[d],includeFallbackInventory:!0}:{}});(m.evidence.length>0||m.exclusions.length>0)&&(j.projectEvidence=m)}}catch(c){const d=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] project evidence collection failed: ${d}. Proceeding without local project evidence.
42
+ `)}try{if(No(e.args)){const{collectProjectEvidence:c}=await import("../evidence/collector.js"),d=o.selection.uiUxReview?.architectureDir,m=c({projectRoot:s,...d?{candidatePaths:[d],includeFallbackInventory:!0}:{}});(m.evidence.length>0||m.exclusions.length>0)&&(j.projectEvidence=m)}}catch(c){const d=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] project evidence collection failed: ${d}. Proceeding without local project evidence.
43
43
  `)}try{const c=await y.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"checkpoint-consume",operation:"consume"},async()=>{const{readAndConsumeCheckpoint:d}=await import("../checkpoint/index.js");return d(s)},async()=>{});c&&(j.implementCheckpoint=c)}catch(c){const d=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] checkpoint hook failed: ${d}. Proceeding without checkpoint.
44
- `)}const V=R?.licenseKey?new Ln({cacheDir:Bn,passphrase:R.licenseKey,strictReadOnly:x}):null,ee=a.trim();if(!ee&&V){const c=await y.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>tc(V),async()=>null);if(c)return y.complete(),{success:!0,instructions:c.instructions,metadata:c.metadata,exitCode:0}}const H=await gi(M,R?.licenseKey,y);if(H.status!=="authenticated"){const c=H.status==="refresh-required",d=!c&&R&&!R.licenseKey?" This may be caused by a machine fingerprint change (e.g., hardware or hostname change).":"";try{const m=Ar(),A=wr(c?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",m);A&&process.stderr.write(Rr(A,m))}catch{}return{success:!1,error:c?"Authentication refresh required. Run: neocortex activate YOUR-LICENSE-KEY":`Not authenticated.${d} Visit https://neocortex.sh/portal/login to get your license key, then run: neocortex activate YOUR-LICENSE-KEY`,errorCode:c?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",exitCode:c?1:2}}const lt=j.config.project_id;try{await y.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>es(s,j,M,H.token,lt,{refreshToken:()=>H.client.forceRefresh()}),async()=>0)}catch{}const Ye=os(ee);if(Ye&&!g)try{const c=await H.tierClient.preFlightCheck(Ye);if(!c.allowed)return process.stderr.write(`[neocortex] ${c.message}
45
- `),{success:!1,error:c.message??"Trigger not available on your plan",exitCode:1}}catch{}const he=await yc({args:ee,projectRoot:s,platformTarget:P,environment:e.environment??process.env,bootstrapper:e.runnerBootstrapper,effectAuthority:y});if(he.attachToRequest&&(j.runnerBootstrap=he.metadata),he.warning&&process.stderr.write(`[Neocortex] ${he.warning}
44
+ `)}const V=R?.licenseKey?new Dn({cacheDir:Un,passphrase:R.licenseKey,strictReadOnly:b}):null,ee=a.trim();if(!ee&&V){const c=await y.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>rc(V),async()=>null);if(c)return y.complete(),{success:!0,instructions:c.instructions,metadata:c.metadata,exitCode:0}}const G=await fi(M,R?.licenseKey,y);if(G.status!=="authenticated"){const c=G.status==="refresh-required",d=!c&&R&&!R.licenseKey?" This may be caused by a machine fingerprint change (e.g., hardware or hostname change).":"";try{const m=br(),A=Rr(c?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",m);A&&process.stderr.write(Ar(A,m))}catch{}return{success:!1,error:c?"Authentication refresh required. Run: neocortex activate YOUR-LICENSE-KEY":`Not authenticated.${d} Visit https://neocortex.sh/portal/login to get your license key, then run: neocortex activate YOUR-LICENSE-KEY`,errorCode:c?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",exitCode:c?1:2}}const lt=j.config.project_id;try{await y.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>ns(s,j,M,G.token,lt,{refreshToken:()=>G.client.forceRefresh()}),async()=>0)}catch{}const Ye=ss(ee);if(Ye&&!g)try{const c=await G.tierClient.preFlightCheck(Ye);if(!c.allowed)return process.stderr.write(`[neocortex] ${c.message}
45
+ `),{success:!1,error:c.message??"Trigger not available on your plan",exitCode:1}}catch{}const he=await Ec({args:ee,projectRoot:s,platformTarget:P,environment:e.environment??process.env,bootstrapper:e.runnerBootstrapper,effectAuthority:y});if(he.attachToRequest&&(j.runnerBootstrap=he.metadata),he.warning&&process.stderr.write(`[Neocortex] ${he.warning}
46
46
  `),!he.shouldContinue)return he.error&&process.stderr.write(`[Neocortex] ${he.error}
47
- `),{success:!1,error:he.error??"Runner auto-bootstrap required but failed.",errorCode:he.errorCode,exitCode:he.exitCode??1};if(he.metadata.command==="runner"&&(he.metadata.operation==="status"||he.metadata.operation==="doctor"))try{const c=e.runnerObserver??Ia;j.runnerOperationalStatus=await c(he.metadata.operation,{projectRoot:s,env:e.environment??process.env,effectAuthority:y})}catch{}let k;try{const c=da(ee,j);if(c&&!c.ok){const d=`${c.code}: structural projection failed closed; select a valid target or repair the dependency DAG.`;return process.stderr.write(`${d}
48
- `),{success:!1,error:d,errorCode:c.code,metadata:{stateProjection:c,publicSafe:!0},exitCode:1}}k=c?.snapshot??br(ee,j),ln(ee)==="migrate-state"&&(k={...k,migrationAuthority:ua(s)})}catch(c){if(c instanceof ha)return{success:!1,error:c.reasonCode,errorCode:c.reasonCode,exitCode:1};if(c instanceof Tr){const d=`${c.code}: structural projection failed closed; select a valid target or repair the dependency DAG.`;return process.stderr.write(`${d}
49
- `),{success:!1,error:d,errorCode:c.code,metadata:{structuralProjection:{...c.publicDetails,publicSafe:!0}},exitCode:1}}throw c}if(!x)try{const{openNativeAgentPrivateStore:c,resolveNativeAgentPrivateRuntimePaths:d}=await import("../continuity/native-agent-store.js"),m=d(s);if(Mt(m.databasePath)){const A=await c(s);try{const U=A.store.listRecentNativeAgentDispatches(20);U.length>0&&(k.nativeAgentDispatches=U)}finally{A.store.close()}}}catch{}const G=ln(ee);let _t=!1;if(G==="arch-plan"&&!x&&k.archPlan?.execution===void 0){const c=Hi(a);if(c)try{if(!Object.hasOwn(j.epics,c)||!Object.hasOwn(k.epics,c))throw new Error("architecture-root-epic-binding-invalid");const d=Yt(s,c);k={...k,archPlan:{execution:{schemaVersion:1,owner:"root",currentStageCommand:"arch-prd",continuationState:"delegate",evidencePolicy:"v2-required",targetEpicId:c,graphRevision:d,graphSource:"committed-epic-v1",acceptedStages:[]}}},_t=!0}catch{return{success:!1,error:"architecture-root-epic-binding-invalid",errorCode:"architecture-root-epic-binding-invalid",exitCode:1}}}if((G==="arch-plan"||G?.startsWith("arch-")||G==="generate-pacts"||G==="update-memory")&&k.archPlan?.execution?.graphSource==="committed-epic-v1")try{const c=k.archPlan.execution;if(typeof c.targetEpicId!="string"||typeof c.graphRevision!="string"||c.graphRevision!==Yt(s,c.targetEpicId))throw new Error("architecture-root-epic-binding-invalid")}catch{return{success:!1,error:"architecture-root-epic-binding-invalid",errorCode:"architecture-root-epic-binding-invalid",exitCode:1}}const De=lt;if((G==="create-epic"||G==="idea-diagnose")&&!De){const c='EPIC_PROJECT_ID_REQUIRED: run `neocortex-client invoke --args "*migrate-project-id"` and retry the planning command. No repository checkout or database credentials are required.';return process.stderr.write(`${c}
50
- `),{success:!1,error:c,errorCode:"EPIC_PROJECT_ID_REQUIRED",exitCode:1}}let se;try{se=y.execute({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>G==="create-epic"||G==="idea-diagnose"?Eo(s,ee,G):void 0,()=>{})}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const tt=se?.key??(G==="yolo"?vo(s,ee,De,k):void 0);if(e.privateExecutionBeta&&G==="create-epic"&&se){const c=$t(s).operations[se.fingerprint],d=c?.epicId?j.epics[c.epicId]:void 0,m=h(d?.createEpicPlanningPhysical)?d.createEpicPlanningPhysical:void 0;c?.claimId&&c.epicId&&d&&m?.claimId===c.claimId&&(k={...k,epics:{...k.epics,[c.epicId]:d},stories:{...k.stories,...Object.fromEntries((Array.isArray(d.stories)?d.stories:[]).filter(A=>typeof A=="string"&&j.stories[A]?.epic_id===c.epicId).map(A=>[A,j.stories[A]]))}})}const ut=x?{schemaVersion:1,invocationId:y.invocationId,intent:y.intent,clientProjection:Pa(Dr.map(c=>({...c,count:1})))}:void 0;let X,ye,le;if(e.privateExecutionBeta&&G==="idea-research")try{const c=k.scope?.targetEpicId,d=c?k.epics[c]:void 0,m=h(d?.createEpicPlanningPhysical)?d.createEpicPlanningPhysical:void 0;if(!c||!m||typeof m.claimId!="string"||typeof m.receiptId!="string")throw new Error("planning-research-predecessor-unavailable");const A=Q(s,".neocortex/state.json"),U=jt(A);if(!U.isFile()||U.isSymbolicLink()||U.size>8*1024*1024)throw new Error("planning-research-state-unavailable");const ie=We(A),de=JSON.parse(ie.toString("utf8")),ae=Er(de,m.claimId,c),fe=h(de)&&h(de.epics)&&h(de.epics[c])?de.epics[c]:void 0,$=h(fe?.createEpicPlanningPhysical)?fe.createEpicPlanningPhysical:void 0;if($?.receiptId!==m.receiptId||!v($,m))throw new Error("planning-research-predecessor-drift");const Ee=[".neocortex/state.json",".neocortex/planning/planning.json",`.neocortex/planning/epic-${c}/idea.json`,`.neocortex/planning/epic-${c}/diagnosis.md`,`.neocortex/planning/epic-${c}/enriched-prompt.md`],Be={...process.env};for(const me of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete Be[me];for(const me of Ee){const Ue=jt(Q(s,me));if(!Ue.isFile()||Ue.isSymbolicLink()||Ue.size>8*1024*1024)throw new Error("planning-research-source-unavailable");const Ke=Ge("git",["show",`HEAD:${me}`],{cwd:s,env:Be,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!We(Q(s,me)).equals(Ke))throw new Error("planning-research-source-uncommitted")}ye={claimId:m.claimId,epicId:c,diagnosisReceiptId:ae.diagnosisReceiptId,intakeRevision:ae.intakeRevision,physicalAcceptanceReceiptId:m.receiptId,sourceStateSha256:Pe("sha256").update(ie).digest("hex")}}catch{return{success:!1,error:"private-execution-planning-predecessor-unavailable",errorCode:"private-execution-planning-predecessor-unavailable",exitCode:1}}if(e.privateExecutionBeta&&G==="generate-epic")try{const c=k.scope?.targetEpicId,d=c?k.epics[c]:void 0,m=h(d?.createEpicPlanningResearchPhysical)?d.createEpicPlanningResearchPhysical:void 0;if(!c||!m||typeof m.claimId!="string"||typeof m.receiptId!="string")throw new Error("planning-generation-predecessor-unavailable");const A=Q(s,".neocortex/state.json"),U=jt(A);if(!U.isFile()||U.isSymbolicLink()||U.size>8*1024*1024)throw new Error("planning-generation-state-unavailable");const ie=We(A),de=JSON.parse(ie.toString("utf8")),ae=Sr(de,m.claimId,c),fe=h(de)&&h(de.epics)&&h(de.epics[c])?de.epics[c]:void 0,$=h(fe?.createEpicPlanningResearchPhysical)?fe.createEpicPlanningResearchPhysical:void 0;if($?.receiptId!==m.receiptId||!v($,m))throw new Error("planning-generation-predecessor-drift");const Ee=[".neocortex/state.json",".neocortex/planning/planning.json",`.neocortex/planning/epic-${c}/idea.json`,`.neocortex/planning/epic-${c}/diagnosis.md`,`.neocortex/planning/epic-${c}/enriched-prompt.md`,`.neocortex/planning/epic-${c}/research.md`],Be={...process.env};for(const me of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete Be[me];for(const me of Ee){const Ue=jt(Q(s,me));if(!Ue.isFile()||Ue.isSymbolicLink()||Ue.size>8*1024*1024)throw new Error("planning-generation-source-unavailable");const Ke=Ge("git",["show",`HEAD:${me}`],{cwd:s,env:Be,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!We(Q(s,me)).equals(Ke))throw new Error("planning-generation-source-uncommitted")}le={claimId:m.claimId,epicId:c,diagnosisReceiptId:ae.diagnosisReceiptId,researchReceiptId:ae.researchReceiptId,intakeRevision:ae.intakeRevision,physicalAcceptanceReceiptId:ae.physicalAcceptanceReceiptId,sourceStateSha256:Pe("sha256").update(ie).digest("hex")}}catch{return{success:!1,error:"private-execution-planning-predecessor-unavailable",errorCode:"private-execution-planning-predecessor-unavailable",exitCode:1}}if(e.privateExecutionBeta)try{const{preflightPrivateCodexExecutor:c}=await import("../private-execution/codex-executor.js");X=await c(s)}catch(c){const d=c instanceof Error&&/^private-codex-[a-z-]+$/.test(c.message)?c.message:"private-codex-preflight-unavailable";return{success:!1,error:d,errorCode:d,exitCode:1}}const Ot=X?{schemaVersion:1,hostKind:"codex-cli",hostVersion:X.hostVersion,sandboxProof:{schemaVersion:6,trust:"client-self-attested",credentialKind:"chatgpt-subscription",authIsolation:"passed",workspaceWrite:"passed",gitControlWriteDenied:"passed",gitLifecycleReadDenied:"passed",mcpIsolation:"passed",environmentIsolation:"passed",networkDenied:"passed",webSearchDisabled:"passed",observedAtMs:X.observedAtMs}}:void 0;let we;if(G==="arch-plan"&&k.archPlan?.execution?.currentStageCommand==="generate-pacts"&&k.archPlan.execution.continuationState==="ask-user")try{if(we=yr(s),!we)throw new Error("architecture-answers-required")}catch(c){const d=c instanceof Error&&/^architecture-answers-[a-z-]+$/.test(c.message)?c.message:"architecture-answers-failed";return{success:!1,error:d,errorCode:d,exitCode:1}}let B;if(G==="arch-plan"&&k.archPlan?.execution?.currentStageCommand==="generate-pacts"&&k.archPlan.execution.continuationState==="delegate"&&k.archPlan.execution.childStatus==="succeeded")try{if(B=yr(s),!B||!v(k.archPlan.execution.pactAnswerReceipt,B))throw new Error("architecture-answers-conflict")}catch{return{success:!1,error:"architecture-answers-conflict",errorCode:"architecture-answers-conflict",exitCode:1}}let je,z,ge;if(e.privateExecutionBeta&&G==="generate-pacts")try{const c=a.trim().match(/^\*?generate-pacts (P[1-9][0-9]{0,11})$/)?.[1],d=k.archPlan?.execution;if(z=$i(s),!c||!d||d.currentStageCommand!=="generate-pacts"||d.continuationState!=="delegate"||d.targetEpicId!==c||!z||!v(d.pactAnswerReceipt,z.receipt))throw new Error("private-execution-pact-admission-unverified");const m=Gi(s,z.answers.generateProvider);if(m.outcome!=="ready")throw new Error("private-execution-pact-admission-unverified");je=m.writeSet,ge={schemaVersion:1,targetEpicId:c,graphRevision:z.receipt.graphRevision,answersSha256:z.receipt.answersSha256,specSha256:je.specSha256,pathsSha256:je.pathsSha256,endpointCount:je.endpointCount,pathCount:je.paths.length,publicSafe:!0}}catch{const c="private-execution-pact-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let Ve,ne;if(e.privateExecutionBeta&&G==="arch-ux-design")try{const c=a.trim().match(/^\*?arch-ux-design (P[1-9][0-9]{0,11})$/)?.[1],d=k.archPlan?.execution;if(!c||!d||d.currentStageCommand!=="arch-ux-design"||d.continuationState!=="delegate"||d.targetEpicId!==c||typeof d.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(d.graphRevision))throw new Error("private-execution-ux-admission-unverified");const{deriveUxWriteSet:m}=await import("../private-execution/ux-write-set.js");Ve=m(s,c),ne={schemaVersion:1,targetEpicId:c,graphRevision:d.graphRevision,adapterId:Ve.adapterId,authoritySha256:Ve.authoritySha256,pathsSha256:Ve.pathsSha256,screenCount:Ve.screenCount,pathCount:Ve.pathCount,publicSafe:!0}}catch{const c="private-execution-ux-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let wt,qe,Ie;if(e.privateExecutionBeta&&G==="property-test")try{if(o.selection.positionals.length!==0||o.selection.operationId!==void 0||Object.keys(o.selection.options).length!==0)throw new Error("private-execution-property-admission-unverified");const{loadPropertyTestChoices:c}=await import("../private-execution/property-test-choices.js"),{propertyTestExecutionInput:d}=await import("../private-execution/property-test-plan.js"),m=c(s);if(!m)throw new Error("private-execution-property-admission-unverified");wt=m.choices,qe=m.plan,Ie=d(m.plan)}catch{const c="private-execution-property-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let J={args:a,projectRoot:s.replace(Kt(),"~"),stateSnapshot:k,...we?{architectureAnswerReceipt:we}:{},...ge?{pactExecutionInput:ge}:{},...ne?{uxExecutionInput:ne}:{},...Ie?{propertyTestExecutionInput:Ie}:{},platformTarget:P,...C?{nativeHostAttestation:C}:{},...Ot?{privateExecution:Ot}:{},projectId:De,inputEvidence:n,...p?{invocationRecovery:p}:{},idempotencyKey:tt,registryVersion:ot,registryChecksum:at,compatibility:Wn(),...e.releaseGate?{releaseGate:e.releaseGate}:{},...ut?{strictReadOnly:ut}:{}};const Wt=Ht(J);if(!x&&e.inputSource&&e.inputSource!=="args"&&Wt>=Un)try{J={argsRef:(await ba(y,"secondary-mutation",()=>pc(M,a,H.token,()=>H.client.forceRefresh()),async()=>{throw new Vt("readonly-physical-boundary-unsafe","boundary")})).argsRef,projectRoot:s.replace(Kt(),"~"),stateSnapshot:k,...we?{architectureAnswerReceipt:we}:{},platformTarget:P,...C?{nativeHostAttestation:C}:{},...Ot?{privateExecution:Ot}:{},projectId:De,inputEvidence:n,...p?{invocationRecovery:p}:{},idempotencyKey:tt,registryVersion:ot,registryChecksum:at,compatibility:Wn(),...e.releaseGate?{releaseGate:e.releaseGate}:{},...ut?{strictReadOnly:ut}:{}}}catch(c){return c instanceof Vt?{success:!1,error:c.code,errorCode:c.code,exitCode:1}:{success:!1,error:`INVOKE_MATERIALIZATION_FAILED: ${c instanceof Error?c.message:String(c)}`,errorCode:"INVOKE_MATERIALIZATION_FAILED",exitCode:1}}let ht;if(G==="yolo"&&k.scope?.projectionMode==="yolo-story"){const c=k.scope?.targetStoryId,d=k.scope?.targetEpicId;if(!c||!d||!N||N.storyId!==c||N.epicId!==d)return{success:!1,error:"yolo-spec-envelope-target-mismatch",errorCode:"yolo-spec-envelope-target-mismatch",exitCode:1};try{let m=Ur(N);if(/\sbranchless-preparation\s*$/.test(a))J={...J,yoloSpecEnvelope:m};else{const{collectYoloChangeEvidence:A,reconcileYoloChangeEvidenceLease:U}=await import("../yolo/change-evidence-collector.js");ht=await U({projectRoot:s,storyId:c,epicId:d}),ht.repair==="applied"&&(m=Ur(N));const ie=A({projectRoot:s,defaultBranch:k.config.default_branch,expectedHeadSha:m.sourceRevision.headSha,storyId:c,epicId:d,reconciliation:ht});J={...J,yoloSpecEnvelope:m,yoloChangeEvidence:ie}}}catch(m){const{yoloChangeEvidenceDiagnostic:A}=await import("../yolo/change-evidence-collector.js"),U=A(m),ie=m instanceof Error&&/^yolo-(?:spec-envelope|change-evidence)-[a-z-]+$/.test(m.message)?m.message:"yolo-spec-envelope-unsafe";return{success:!1,error:ie,errorCode:ie,...U?{metadata:{yoloChangeEvidence:U}}:{},exitCode:1}}}try{const c=er(J);if(G==="migrate-state"&&c.degraded)return{success:!1,error:"state_migration_payload_degraded",errorCode:"state_migration_payload_degraded",exitCode:1};J=c.body,c.degraded?vi(J,c.telemetry):mc(J)}catch(c){if(c instanceof Fn||c instanceof Yn)return vi(J,c.telemetry),process.stderr.write(`[Neocortex] ${c.message}
51
- `),{success:!1,error:c.message,errorCode:c.code,metadata:{invokePayload:c.telemetry},exitCode:1};throw c}if(G==="yolo"&&J.yoloSpecEnvelope)try{const c=Br({projectRoot:s,storyId:J.yoloSpecEnvelope.storyId,epicId:J.yoloSpecEnvelope.epicId,inputSha256:n.sha256,collectedAt:J.yoloSpecEnvelope.collectedAt});if(c.envelopeSha256!==J.yoloSpecEnvelope.envelopeSha256)throw new Error("yolo-spec-envelope-stale");if(J.yoloChangeEvidence){const{collectYoloChangeEvidence:d}=await import("../yolo/change-evidence-collector.js"),m=d({projectRoot:s,defaultBranch:k.config.default_branch,expectedHeadSha:c.sourceRevision.headSha,storyId:c.storyId,epicId:c.epicId,...ht?{reconciliation:ht}:{}});if(m.pathsSha256!==J.yoloChangeEvidence.pathsSha256||m.baseSha!==J.yoloChangeEvidence.baseSha)throw new Error("yolo-change-evidence-stale")}}catch(c){const d=c instanceof Error&&c.message==="yolo-change-evidence-stale"?c.message:"yolo-spec-envelope-stale",{yoloChangeEvidenceDiagnostic:m}=await import("../yolo/change-evidence-collector.js"),A=m(c);return{success:!1,error:d,errorCode:d,...A?{metadata:{yoloChangeEvidence:A}}:{},exitCode:1}}const O=G==="arch-plan"?J.stateSnapshot.archPlan?.execution:void 0;let gt;if(O?.owner==="root"&&(O.currentStageCommand==="arch-prd"||O.currentStageCommand==="arch-architecture"||O.currentStageCommand==="arch-fitness-functions"||O.currentStageCommand==="arch-api-contracts"||O.currentStageCommand==="generate-pacts"||O.currentStageCommand==="arch-api-integrations"||O.currentStageCommand==="arch-database"||O.currentStageCommand==="arch-security"||O.currentStageCommand==="arch-design-system"||O.currentStageCommand==="arch-ux-design"||O.currentStageCommand==="arch-performance"||O.currentStageCommand==="arch-testing"||O.currentStageCommand==="arch-infrastructure"||O.currentStageCommand==="arch-review"||O.currentStageCommand==="update-memory")&&(O.continuationState==="delegate"||O.continuationState==="advance"||O.currentStageCommand==="update-memory"&&O.continuationState==="complete"||O.currentStageCommand==="arch-review"&&O.continuationState==="ask-user"||O.currentStageCommand==="generate-pacts"&&O.continuationState==="ask-user"))try{const c=We(Q(s,".neocortex","state.json"),"utf8"),d=JSON.parse(c),m=h(d.archPlan)?d.archPlan.execution:void 0;if(_t?m!==void 0||!h(d.epics)||!Object.hasOwn(d.epics,String(O.targetEpicId))||O.graphSource!=="committed-epic-v1"||O.graphRevision!==Yt(s,String(O.targetEpicId)):!v(yn(m),O))throw new Error("architecture-root-state-binding-invalid");if(gt=Pe("sha256").update(c).digest("hex"),we&&we.stateSha256!==gt)throw new Error("architecture-root-state-binding-invalid");if(O.currentStageCommand==="update-memory"&&O.childStatus==="succeeded"){const A=O.continuationState==="complete"&&Array.isArray(O.acceptedStages)?{...O,continuationState:"delegate",acceptedStages:O.acceptedStages.slice(0,fr(O))}:O;if(!Ft(O.terminalMemoryCheckpoint,O)||!v(O.terminalMemoryCheckpoint,kn(s,A)))throw new Error("architecture-terminal-memory-physical-invalid")}}catch{return{success:!1,error:"architecture-root-state-binding-invalid",errorCode:"architecture-root-state-binding-invalid",exitCode:1}}let f=await Mn("invoke-query",()=>sr(M,J,H.token,{refreshToken:()=>H.client.forceRefresh()}));if(G==="yoloop"&&!x&&f.ok&&f.data?.metadata?.errorCode==="YOLOOP_SPEC_NOT_READY"&&f.data.metadata.hint==="yoloop-session-invalidated"){const c=k.scope?.targetEpicId;if(!c)return{success:!1,error:"yoloop-causal-reconciliation-target-invalid",errorCode:"YOLOOP_CAUSAL_RECONCILIATION_BLOCKED",exitCode:1};const d=await is({projectRoot:s,snapshot:j,targetEpicId:c,originalInputSha256:n.sha256,canonicalInputSha256:p?.canonicalSha256??n.sha256});if(d.outcome!=="applied")return{success:!1,error:d.reasonCode,errorCode:"YOLOOP_CAUSAL_RECONCILIATION_BLOCKED",metadata:{yoloopCausalRecovery:d},exitCode:1};try{const{readYoloopForRequest:m}=await import("../yoloop/invoke-hooks.js"),A=await m(a,s);if(!A)throw new Error("yoloop-causal-reconciliation-postimage-unverified");J=er({...J,stateSnapshot:{...J.stateSnapshot,yoloop:A}}).body}catch(m){const A=Li(m);return{success:!1,error:A,errorCode:"YOLOOP_CAUSAL_RECONCILIATION_BLOCKED",metadata:{yoloopCausalRecovery:{outcome:"blocked",reasonCode:A,retryCount:0,publicSafe:!0}},exitCode:1}}f=await Mn("invoke-query",()=>sr(M,J,H.token,{refreshToken:()=>H.client.forceRefresh()}))}let Nt;if(x&&f.ok)try{if(g){const d=f.data?.metadata;if(d&&["stateUpdate","stateMutated","yoloopStateUpdate","continuityStateUpdate","checkpoint","schedulerStateUpdate","quotaCacheUpdate","projectIdentityMigration","epicClaim","gitLifecycleGraphAuthority"].some(A=>d[A]!==void 0))throw new Vt("readonly-response-conflict")}const c=f.data?.metadata.strictReadOnly;Oa(y,c),g&&Va(f.data?.metadata.strictDiagnose,i,f.data?.instructions??""),Nt=c.security}catch(c){const d=c instanceof Vt?c.code:"readonly-receipt-mismatch";return{success:!1,error:d,errorCode:d,exitCode:1}}if(!f.ok&&f.status===426){const c=f.errorBody,d=c?.upgrade_command??"npm install -g @ornexus/neocortex@latest",m=c?.min_version??"unknown";return process.stderr.write(`
47
+ `),{success:!1,error:he.error??"Runner auto-bootstrap required but failed.",errorCode:he.errorCode,exitCode:he.exitCode??1};if(he.metadata.command==="runner"&&(he.metadata.operation==="status"||he.metadata.operation==="doctor"))try{const c=e.runnerObserver??Sa;j.runnerOperationalStatus=await c(he.metadata.operation,{projectRoot:s,env:e.environment??process.env,effectAuthority:y})}catch{}let O;try{const c=la(ee,j);if(c&&!c.ok){const d=`${c.code}: structural projection failed closed; select a valid target or repair the dependency DAG.`;return process.stderr.write(`${d}
48
+ `),{success:!1,error:d,errorCode:c.code,metadata:{stateProjection:c,publicSafe:!0},exitCode:1}}O=c?.snapshot??xr(ee,j),un(ee)==="migrate-state"&&(O={...O,migrationAuthority:ga(s)})}catch(c){if(c instanceof fa)return{success:!1,error:c.reasonCode,errorCode:c.reasonCode,exitCode:1};if(c instanceof Pr){const d=`${c.code}: structural projection failed closed; select a valid target or repair the dependency DAG.`;return process.stderr.write(`${d}
49
+ `),{success:!1,error:d,errorCode:c.code,metadata:{structuralProjection:{...c.publicDetails,publicSafe:!0}},exitCode:1}}throw c}if(!b)try{const{openNativeAgentPrivateStore:c,resolveNativeAgentPrivateRuntimePaths:d}=await import("../continuity/native-agent-store.js"),m=d(s);if(Mt(m.databasePath)){const A=await c(s);try{const U=A.store.listRecentNativeAgentDispatches(20);U.length>0&&(O.nativeAgentDispatches=U)}finally{A.store.close()}}}catch{}const H=un(ee);let Ct=!1;if(H==="arch-plan"&&!b&&O.archPlan?.execution===void 0){const c=Gi(a);if(c)try{if(!Object.hasOwn(j.epics,c)||!Object.hasOwn(O.epics,c))throw new Error("architecture-root-epic-binding-invalid");const d=Ft(s,c);O={...O,archPlan:{execution:{schemaVersion:1,owner:"root",currentStageCommand:"arch-prd",continuationState:"delegate",evidencePolicy:"v2-required",targetEpicId:c,graphRevision:d,graphSource:"committed-epic-v1",acceptedStages:[]}}},Ct=!0}catch{return{success:!1,error:"architecture-root-epic-binding-invalid",errorCode:"architecture-root-epic-binding-invalid",exitCode:1}}}if((H==="arch-plan"||H?.startsWith("arch-")||H==="generate-pacts"||H==="update-memory")&&O.archPlan?.execution?.graphSource==="committed-epic-v1")try{const c=O.archPlan.execution;if(typeof c.targetEpicId!="string"||typeof c.graphRevision!="string"||c.graphRevision!==Ft(s,c.targetEpicId))throw new Error("architecture-root-epic-binding-invalid")}catch{return{success:!1,error:"architecture-root-epic-binding-invalid",errorCode:"architecture-root-epic-binding-invalid",exitCode:1}}const De=lt;if((H==="create-epic"||H==="idea-diagnose")&&!De){const c='EPIC_PROJECT_ID_REQUIRED: run `neocortex-client invoke --args "*migrate-project-id"` and retry the planning command. No repository checkout or database credentials are required.';return process.stderr.write(`${c}
50
+ `),{success:!1,error:c,errorCode:"EPIC_PROJECT_ID_REQUIRED",exitCode:1}}let se;try{se=y.execute({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>H==="create-epic"||H==="idea-diagnose"?vo(s,ee,H):void 0,()=>{})}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const tt=se?.key??(H==="yolo"?_o(s,ee,De,O):void 0);if(e.privateExecutionBeta&&H==="create-epic"&&se){const c=$t(s).operations[se.fingerprint],d=c?.epicId?j.epics[c.epicId]:void 0,m=h(d?.createEpicPlanningPhysical)?d.createEpicPlanningPhysical:void 0;c?.claimId&&c.epicId&&d&&m?.claimId===c.claimId&&(O={...O,epics:{...O.epics,[c.epicId]:d},stories:{...O.stories,...Object.fromEntries((Array.isArray(d.stories)?d.stories:[]).filter(A=>typeof A=="string"&&j.stories[A]?.epic_id===c.epicId).map(A=>[A,j.stories[A]]))}})}const ut=b?{schemaVersion:1,invocationId:y.invocationId,intent:y.intent,clientProjection:Oa(Mr.map(c=>({...c,count:1})))}:void 0;let X,ye,le;if(e.privateExecutionBeta&&H==="idea-research")try{const c=O.scope?.targetEpicId,d=c?O.epics[c]:void 0,m=h(d?.createEpicPlanningPhysical)?d.createEpicPlanningPhysical:void 0;if(!c||!m||typeof m.claimId!="string"||typeof m.receiptId!="string")throw new Error("planning-research-predecessor-unavailable");const A=Q(s,".neocortex/state.json"),U=jt(A);if(!U.isFile()||U.isSymbolicLink()||U.size>8*1024*1024)throw new Error("planning-research-state-unavailable");const ie=We(A),de=JSON.parse(ie.toString("utf8")),ae=Sr(de,m.claimId,c),fe=h(de)&&h(de.epics)&&h(de.epics[c])?de.epics[c]:void 0,$=h(fe?.createEpicPlanningPhysical)?fe.createEpicPlanningPhysical:void 0;if($?.receiptId!==m.receiptId||!v($,m))throw new Error("planning-research-predecessor-drift");const Ee=[".neocortex/state.json",".neocortex/planning/planning.json",`.neocortex/planning/epic-${c}/idea.json`,`.neocortex/planning/epic-${c}/diagnosis.md`,`.neocortex/planning/epic-${c}/enriched-prompt.md`],Be={...process.env};for(const me of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete Be[me];for(const me of Ee){const Ue=jt(Q(s,me));if(!Ue.isFile()||Ue.isSymbolicLink()||Ue.size>8*1024*1024)throw new Error("planning-research-source-unavailable");const Ke=Ge("git",["show",`HEAD:${me}`],{cwd:s,env:Be,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!We(Q(s,me)).equals(Ke))throw new Error("planning-research-source-uncommitted")}ye={claimId:m.claimId,epicId:c,diagnosisReceiptId:ae.diagnosisReceiptId,intakeRevision:ae.intakeRevision,physicalAcceptanceReceiptId:m.receiptId,sourceStateSha256:Pe("sha256").update(ie).digest("hex")}}catch{return{success:!1,error:"private-execution-planning-predecessor-unavailable",errorCode:"private-execution-planning-predecessor-unavailable",exitCode:1}}if(e.privateExecutionBeta&&H==="generate-epic")try{const c=O.scope?.targetEpicId,d=c?O.epics[c]:void 0,m=h(d?.createEpicPlanningResearchPhysical)?d.createEpicPlanningResearchPhysical:void 0;if(!c||!m||typeof m.claimId!="string"||typeof m.receiptId!="string")throw new Error("planning-generation-predecessor-unavailable");const A=Q(s,".neocortex/state.json"),U=jt(A);if(!U.isFile()||U.isSymbolicLink()||U.size>8*1024*1024)throw new Error("planning-generation-state-unavailable");const ie=We(A),de=JSON.parse(ie.toString("utf8")),ae=vr(de,m.claimId,c),fe=h(de)&&h(de.epics)&&h(de.epics[c])?de.epics[c]:void 0,$=h(fe?.createEpicPlanningResearchPhysical)?fe.createEpicPlanningResearchPhysical:void 0;if($?.receiptId!==m.receiptId||!v($,m))throw new Error("planning-generation-predecessor-drift");const Ee=[".neocortex/state.json",".neocortex/planning/planning.json",`.neocortex/planning/epic-${c}/idea.json`,`.neocortex/planning/epic-${c}/diagnosis.md`,`.neocortex/planning/epic-${c}/enriched-prompt.md`,`.neocortex/planning/epic-${c}/research.md`],Be={...process.env};for(const me of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete Be[me];for(const me of Ee){const Ue=jt(Q(s,me));if(!Ue.isFile()||Ue.isSymbolicLink()||Ue.size>8*1024*1024)throw new Error("planning-generation-source-unavailable");const Ke=Ge("git",["show",`HEAD:${me}`],{cwd:s,env:Be,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!We(Q(s,me)).equals(Ke))throw new Error("planning-generation-source-uncommitted")}le={claimId:m.claimId,epicId:c,diagnosisReceiptId:ae.diagnosisReceiptId,researchReceiptId:ae.researchReceiptId,intakeRevision:ae.intakeRevision,physicalAcceptanceReceiptId:ae.physicalAcceptanceReceiptId,sourceStateSha256:Pe("sha256").update(ie).digest("hex")}}catch{return{success:!1,error:"private-execution-planning-predecessor-unavailable",errorCode:"private-execution-planning-predecessor-unavailable",exitCode:1}}if(e.privateExecutionBeta)try{const{preflightPrivateCodexExecutor:c}=await import("../private-execution/codex-executor.js");X=await c(s)}catch(c){const d=c instanceof Error&&/^private-codex-[a-z-]+$/.test(c.message)?c.message:"private-codex-preflight-unavailable";return{success:!1,error:d,errorCode:d,exitCode:1}}const Nt=X?{schemaVersion:1,hostKind:"codex-cli",hostVersion:X.hostVersion,sandboxProof:{schemaVersion:6,trust:"client-self-attested",credentialKind:"chatgpt-subscription",authIsolation:"passed",workspaceWrite:"passed",gitControlWriteDenied:"passed",gitLifecycleReadDenied:"passed",mcpIsolation:"passed",environmentIsolation:"passed",networkDenied:"passed",webSearchDisabled:"passed",observedAtMs:X.observedAtMs}}:void 0;let we;if(H==="arch-plan"&&O.archPlan?.execution?.currentStageCommand==="generate-pacts"&&O.archPlan.execution.continuationState==="ask-user")try{if(we=Ir(s),!we)throw new Error("architecture-answers-required")}catch(c){const d=c instanceof Error&&/^architecture-answers-[a-z-]+$/.test(c.message)?c.message:"architecture-answers-failed";return{success:!1,error:d,errorCode:d,exitCode:1}}let B;if(H==="arch-plan"&&O.archPlan?.execution?.currentStageCommand==="generate-pacts"&&O.archPlan.execution.continuationState==="delegate"&&O.archPlan.execution.childStatus==="succeeded")try{if(B=Ir(s),!B||!v(O.archPlan.execution.pactAnswerReceipt,B))throw new Error("architecture-answers-conflict")}catch{return{success:!1,error:"architecture-answers-conflict",errorCode:"architecture-answers-conflict",exitCode:1}}let je,J,ge;if(e.privateExecutionBeta&&H==="generate-pacts")try{const c=a.trim().match(/^\*?generate-pacts (P[1-9][0-9]{0,11})$/)?.[1],d=O.archPlan?.execution;if(J=Hi(s),!c||!d||d.currentStageCommand!=="generate-pacts"||d.continuationState!=="delegate"||d.targetEpicId!==c||!J||!v(d.pactAnswerReceipt,J.receipt))throw new Error("private-execution-pact-admission-unverified");const m=Wi(s,J.answers.generateProvider);if(m.outcome!=="ready")throw new Error("private-execution-pact-admission-unverified");je=m.writeSet,ge={schemaVersion:1,targetEpicId:c,graphRevision:J.receipt.graphRevision,answersSha256:J.receipt.answersSha256,specSha256:je.specSha256,pathsSha256:je.pathsSha256,endpointCount:je.endpointCount,pathCount:je.paths.length,publicSafe:!0}}catch{const c="private-execution-pact-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let Ve,ne;if(e.privateExecutionBeta&&H==="arch-ux-design")try{const c=a.trim().match(/^\*?arch-ux-design (P[1-9][0-9]{0,11})$/)?.[1],d=O.archPlan?.execution;if(!c||!d||d.currentStageCommand!=="arch-ux-design"||d.continuationState!=="delegate"||d.targetEpicId!==c||typeof d.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(d.graphRevision))throw new Error("private-execution-ux-admission-unverified");const{deriveUxWriteSet:m}=await import("../private-execution/ux-write-set.js");Ve=m(s,c),ne={schemaVersion:1,targetEpicId:c,graphRevision:d.graphRevision,adapterId:Ve.adapterId,authoritySha256:Ve.authoritySha256,pathsSha256:Ve.pathsSha256,screenCount:Ve.screenCount,pathCount:Ve.pathCount,publicSafe:!0}}catch{const c="private-execution-ux-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let _t,qe,Ie;if(e.privateExecutionBeta&&H==="property-test")try{if(o.selection.positionals.length!==0||o.selection.operationId!==void 0||Object.keys(o.selection.options).length!==0)throw new Error("private-execution-property-admission-unverified");const{loadPropertyTestChoices:c}=await import("../private-execution/property-test-choices.js"),{propertyTestExecutionInput:d}=await import("../private-execution/property-test-plan.js"),m=c(s);if(!m)throw new Error("private-execution-property-admission-unverified");_t=m.choices,qe=m.plan,Ie=d(m.plan)}catch{const c="private-execution-property-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let ht;if(H==="yoloop"&&!b&&!e.privateExecutionBeta)try{ht=(e.hostCapacityProbe??zi)({platformTarget:P,env:L})}catch{ht=void 0}let W={args:a,projectRoot:s.replace(Jt(),"~"),stateSnapshot:O,...we?{architectureAnswerReceipt:we}:{},...ge?{pactExecutionInput:ge}:{},...ne?{uxExecutionInput:ne}:{},...Ie?{propertyTestExecutionInput:Ie}:{},platformTarget:P,...C?{nativeHostAttestation:C}:{},...ht?{hostCapacity:ht}:{},...Nt?{privateExecution:Nt}:{},projectId:De,inputEvidence:n,...p?{invocationRecovery:p}:{},idempotencyKey:tt,registryVersion:ot,registryChecksum:at,compatibility:Fn(),...e.releaseGate?{releaseGate:e.releaseGate}:{},...ut?{strictReadOnly:ut}:{}};const tn=Ht(W);if(!b&&e.inputSource&&e.inputSource!=="args"&&tn>=$n)try{W={argsRef:(await Ta(y,"secondary-mutation",()=>uc(M,a,G.token,()=>G.client.forceRefresh()),async()=>{throw new Vt("readonly-physical-boundary-unsafe","boundary")})).argsRef,projectRoot:s.replace(Jt(),"~"),stateSnapshot:O,...we?{architectureAnswerReceipt:we}:{},platformTarget:P,...C?{nativeHostAttestation:C}:{},...ht?{hostCapacity:ht}:{},...Nt?{privateExecution:Nt}:{},projectId:De,inputEvidence:n,...p?{invocationRecovery:p}:{},idempotencyKey:tt,registryVersion:ot,registryChecksum:at,compatibility:Fn(),...e.releaseGate?{releaseGate:e.releaseGate}:{},...ut?{strictReadOnly:ut}:{}}}catch(c){return c instanceof Vt?{success:!1,error:c.code,errorCode:c.code,exitCode:1}:{success:!1,error:`INVOKE_MATERIALIZATION_FAILED: ${c instanceof Error?c.message:String(c)}`,errorCode:"INVOKE_MATERIALIZATION_FAILED",exitCode:1}}let wt;if(H==="yolo"&&O.scope?.projectionMode==="yolo-story"){const c=O.scope?.targetStoryId,d=O.scope?.targetEpicId;if(!c||!d||!N||N.storyId!==c||N.epicId!==d)return{success:!1,error:"yolo-spec-envelope-target-mismatch",errorCode:"yolo-spec-envelope-target-mismatch",exitCode:1};try{let m=$r(N);if(/\sbranchless-preparation\s*$/.test(a))W={...W,yoloSpecEnvelope:m};else{const{collectYoloChangeEvidence:A,reconcileYoloChangeEvidenceLease:U}=await import("../yolo/change-evidence-collector.js");wt=await U({projectRoot:s,storyId:c,epicId:d}),wt.repair==="applied"&&(m=$r(N));const ie=A({projectRoot:s,defaultBranch:O.config.default_branch,expectedHeadSha:m.sourceRevision.headSha,storyId:c,epicId:d,reconciliation:wt});W={...W,yoloSpecEnvelope:m,yoloChangeEvidence:ie}}}catch(m){const{yoloChangeEvidenceDiagnostic:A}=await import("../yolo/change-evidence-collector.js"),U=A(m),ie=m instanceof Error&&/^yolo-(?:spec-envelope|change-evidence)-[a-z-]+$/.test(m.message)?m.message:"yolo-spec-envelope-unsafe";return{success:!1,error:ie,errorCode:ie,...U?{metadata:{yoloChangeEvidence:U}}:{},exitCode:1}}}try{const c=tr(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?Ci(W,c.telemetry):Ic(W)}catch(c){if(c instanceof Yn||c instanceof qn)return Ci(W,c.telemetry),process.stderr.write(`[Neocortex] ${c.message}
51
+ `),{success:!1,error:c.message,errorCode:c.code,metadata:{invokePayload:c.telemetry},exitCode:1};throw c}if(H==="yolo"&&W.yoloSpecEnvelope)try{const c=Ur({projectRoot:s,storyId:W.yoloSpecEnvelope.storyId,epicId:W.yoloSpecEnvelope.epicId,inputSha256:n.sha256,collectedAt:W.yoloSpecEnvelope.collectedAt});if(c.envelopeSha256!==W.yoloSpecEnvelope.envelopeSha256)throw new Error("yolo-spec-envelope-stale");if(W.yoloChangeEvidence){const{collectYoloChangeEvidence:d}=await import("../yolo/change-evidence-collector.js"),m=d({projectRoot:s,defaultBranch:O.config.default_branch,expectedHeadSha:c.sourceRevision.headSha,storyId:c.storyId,epicId:c.epicId,...wt?{reconciliation:wt}:{}});if(m.pathsSha256!==W.yoloChangeEvidence.pathsSha256||m.baseSha!==W.yoloChangeEvidence.baseSha)throw new Error("yolo-change-evidence-stale")}}catch(c){const d=c instanceof Error&&c.message==="yolo-change-evidence-stale"?c.message:"yolo-spec-envelope-stale",{yoloChangeEvidenceDiagnostic:m}=await import("../yolo/change-evidence-collector.js"),A=m(c);return{success:!1,error:d,errorCode:d,...A?{metadata:{yoloChangeEvidence:A}}:{},exitCode:1}}const k=H==="arch-plan"?W.stateSnapshot.archPlan?.execution:void 0;let Rt;if(k?.owner==="root"&&(k.currentStageCommand==="arch-prd"||k.currentStageCommand==="arch-architecture"||k.currentStageCommand==="arch-fitness-functions"||k.currentStageCommand==="arch-api-contracts"||k.currentStageCommand==="generate-pacts"||k.currentStageCommand==="arch-api-integrations"||k.currentStageCommand==="arch-database"||k.currentStageCommand==="arch-security"||k.currentStageCommand==="arch-design-system"||k.currentStageCommand==="arch-ux-design"||k.currentStageCommand==="arch-performance"||k.currentStageCommand==="arch-testing"||k.currentStageCommand==="arch-infrastructure"||k.currentStageCommand==="arch-review"||k.currentStageCommand==="update-memory")&&(k.continuationState==="delegate"||k.continuationState==="advance"||k.currentStageCommand==="update-memory"&&k.continuationState==="complete"||k.currentStageCommand==="arch-review"&&k.continuationState==="ask-user"||k.currentStageCommand==="generate-pacts"&&k.continuationState==="ask-user"))try{const c=We(Q(s,".neocortex","state.json"),"utf8"),d=JSON.parse(c),m=h(d.archPlan)?d.archPlan.execution:void 0;if(Ct?m!==void 0||!h(d.epics)||!Object.hasOwn(d.epics,String(k.targetEpicId))||k.graphSource!=="committed-epic-v1"||k.graphRevision!==Ft(s,String(k.targetEpicId)):!v(In(m),k))throw new Error("architecture-root-state-binding-invalid");if(Rt=Pe("sha256").update(c).digest("hex"),we&&we.stateSha256!==Rt)throw new Error("architecture-root-state-binding-invalid");if(k.currentStageCommand==="update-memory"&&k.childStatus==="succeeded"){const A=k.continuationState==="complete"&&Array.isArray(k.acceptedStages)?{...k,continuationState:"delegate",acceptedStages:k.acceptedStages.slice(0,mr(k))}:k;if(!Wt(k.terminalMemoryCheckpoint,k)||!v(k.terminalMemoryCheckpoint,On(s,A)))throw new Error("architecture-terminal-memory-physical-invalid")}}catch{return{success:!1,error:"architecture-root-state-binding-invalid",errorCode:"architecture-root-state-binding-invalid",exitCode:1}}let f=await jn("invoke-query",()=>dr(M,W,G.token,{refreshToken:()=>G.client.forceRefresh()}));if(H==="yoloop"&&!b&&f.ok&&f.data?.metadata?.errorCode==="YOLOOP_SPEC_NOT_READY"&&f.data.metadata.hint==="yoloop-session-invalidated"){const c=O.scope?.targetEpicId;if(!c)return{success:!1,error:"yoloop-causal-reconciliation-target-invalid",errorCode:"YOLOOP_CAUSAL_RECONCILIATION_BLOCKED",exitCode:1};const d=await os({projectRoot:s,snapshot:j,targetEpicId:c,originalInputSha256:n.sha256,canonicalInputSha256:p?.canonicalSha256??n.sha256});if(d.outcome!=="applied")return{success:!1,error:d.reasonCode,errorCode:"YOLOOP_CAUSAL_RECONCILIATION_BLOCKED",metadata:{yoloopCausalRecovery:d},exitCode:1};try{const{readYoloopForRequest:m}=await import("../yoloop/invoke-hooks.js"),A=await m(a,s);if(!A)throw new Error("yoloop-causal-reconciliation-postimage-unverified");W=tr({...W,stateSnapshot:{...W.stateSnapshot,yoloop:A}}).body}catch(m){const A=Di(m);return{success:!1,error:A,errorCode:"YOLOOP_CAUSAL_RECONCILIATION_BLOCKED",metadata:{yoloopCausalRecovery:{outcome:"blocked",reasonCode:A,retryCount:0,publicSafe:!0}},exitCode:1}}f=await jn("invoke-query",()=>dr(M,W,G.token,{refreshToken:()=>G.client.forceRefresh()}))}let nn;if(b&&f.ok)try{if(g){const d=f.data?.metadata;if(d&&["stateUpdate","stateMutated","yoloopStateUpdate","continuityStateUpdate","checkpoint","schedulerStateUpdate","quotaCacheUpdate","projectIdentityMigration","epicClaim","gitLifecycleGraphAuthority"].some(A=>d[A]!==void 0))throw new Vt("readonly-response-conflict")}const c=f.data?.metadata.strictReadOnly;La(y,c),g&&Ua(f.data?.metadata.strictDiagnose,i,f.data?.instructions??""),nn=c.security}catch(c){const d=c instanceof Vt?c.code:"readonly-receipt-mismatch";return{success:!1,error:d,errorCode:d,exitCode:1}}if(!f.ok&&f.status===426){const c=f.errorBody,d=c?.upgrade_command??"npm install -g @ornexus/neocortex@latest",m=c?.min_version??"unknown";return process.stderr.write(`
52
52
  `),process.stderr.write(`==================================================
53
53
  `),process.stderr.write(` UPGRADE REQUIRED
54
54
  `),process.stderr.write(`==================================================
55
55
  `),process.stderr.write(`
56
- Your Neocortex version (${Tt}) is no longer supported.
56
+ Your Neocortex version (${Pt}) is no longer supported.
57
57
  `),process.stderr.write(` Minimum required: ${m}
58
58
 
59
59
  `),process.stderr.write(` Run this command to update:
@@ -63,17 +63,17 @@ ${t}
63
63
  `),process.stderr.write(` After updating, re-run your command.
64
64
  `),process.stderr.write(`==================================================
65
65
 
66
- `),{success:!1,error:`UPGRADE_REQUIRED: Client version ${Tt} is below minimum ${m}. Run: ${d}`,exitCode:3}}if(!f.ok||!f.data){const c=f.status===401?2:(f.status===429||f.status>=500,1),d=ic(f),m=_o(d);if(m)return process.stderr.write(`[Neocortex] ${m.error}
67
- `),m;try{if(d){const A=Ar(),U=wr(d,A);U&&process.stderr.write(Rr(U,A))}}catch{}return{success:!1,error:ze(f.error??"Unknown error from server",Pt),...d?{errorCode:d}:{},...f.compatibility?{metadata:{compatibility:f.compatibility}}:{},exitCode:c}}const pr=wo(f.data);if(pr)return y.complete(Nt),pr;let Re;try{Re=e.privateExecutionBeta&&G==="create-epic"&&se?$t(s).operations[se.fingerprint]:void 0}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const nn=Re?.planningProtocol==="root-staged-v1"&&typeof Re.claimId=="string"&&typeof Re.epicId=="string"&&zi(f.data,{claimId:Re.claimId,epicId:Re.epicId,...h(j.epics[Re.epicId]?.createEpicPlanningMemoryPhysical)?{memoryReceiptId:j.epics[Re.epicId].createEpicPlanningMemoryPhysical.receiptId}:{}});if(e.privateExecutionBeta&&!nn&&!qi(f.data))return{success:!1,error:"private-execution-public-envelope-invalid",errorCode:"private-execution-public-envelope-invalid",exitCode:1};if(gt&&O&&f.data.metadata?.mode==="arch-plan"&&h(f.data.metadata.archPlan)&&h(f.data.metadata.archPlan.execution)&&(f.data.metadata.archPlan.execution.nextAction==="delegate"||f.data.metadata.archPlan.execution.nextAction==="resume"||f.data.metadata.archPlan.execution.nextAction==="ask-user"||f.data.metadata.archPlan.execution.nextAction==="complete"&&f.data.metadata.archPlan.execution.currentStageCommand==="update-memory"||f.data.metadata.archPlan.execution.nextAction==="blocked"&&(f.data.metadata.archPlan.execution.currentStageCommand==="arch-ux-design"||f.data.metadata.archPlan.execution.currentStageCommand==="arch-performance"||f.data.metadata.archPlan.execution.currentStageCommand==="arch-testing"||f.data.metadata.archPlan.execution.currentStageCommand==="arch-infrastructure"||f.data.metadata.archPlan.execution.currentStageCommand==="arch-review")))try{await y.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>Ho({projectRoot:s,sourceStateSha256:gt,requestExecution:O,initialBinding:_t,answerReceipt:we,pactRecordedReceipt:B,metadata:f.data.metadata}),async()=>{throw new Error("architecture-root-writeback-effect-skipped")})}catch(c){const d=c instanceof Error&&/^architecture-root-[a-z-]+$/.test(c.message)?c.message:"architecture-root-writeback-failed";return process.stderr.write(`[Neocortex] ${d}. Root stage instruction was not released.
68
- `),{success:!1,error:d,errorCode:d,exitCode:1}}if(!ee&&f.data.metadata?.mode==="menu"&&V&&await y.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>nc(V,f.data.instructions,f.data.metadata),async()=>{}).catch(()=>{}),f.data.metadata&&await y.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"tier-cache",operation:"update"},()=>H.tierClient.updateQuotaFromResponse(f.data.metadata),async()=>{}).catch(()=>{}),f.data.metadata?.stateMutated===!0)try{const c=await y.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>{const{persistMigratedStateFromResponse:d}=await import("../yoloop/invoke-hooks.js");return d(f.data.metadata,s)},async()=>({applied:!1,blocking:!1,reasonCode:"state-writeback-effect-skipped"}));if(c.blocking){const d=`STATE_WRITEBACK_BLOCKED: ${c.reasonCode}. Canonical state was not replaced.`;return process.stderr.write(`${d}
69
- `),{success:!1,error:d,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}catch(c){if(f.data.metadata?.stateMutationReason==="inline-yolo-materialized-synthetic-story"){const d=c instanceof Error?c.message:String(c),m=`STATE_WRITEBACK_BLOCKED: inline-yolo persistence failed (${ze(d,Pt)}).`;return process.stderr.write(`${m}
70
- `),{success:!1,error:m,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}if(f.data.metadata?.gitLifecycleGraphAuthority)try{await y.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},()=>to(s,f.data.metadata.gitLifecycleGraphAuthority),async()=>{throw new Error("git-lifecycle-graph-authority-effect-skipped")})}catch(c){const d=c instanceof Error&&/^git-lifecycle-/.test(c.message)?c.message:"git-lifecycle-graph-authority-persist-failed";return process.stderr.write(`[Neocortex] ${d}. Graph authority was not persisted; no YOLO checkpoint instruction was released.
66
+ `),{success:!1,error:`UPGRADE_REQUIRED: Client version ${Pt} is below minimum ${m}. Run: ${d}`,exitCode:3}}if(!f.ok||!f.data){const c=f.status===401?2:(f.status===429||f.status>=500,1),d=oc(f),m=Ro(d);if(m)return process.stderr.write(`[Neocortex] ${m.error}
67
+ `),m;try{if(d){const A=br(),U=Rr(d,A);U&&process.stderr.write(Ar(U,A))}}catch{}return{success:!1,error:ze(f.error??"Unknown error from server",kt),...d?{errorCode:d}:{},...f.compatibility?{metadata:{compatibility:f.compatibility}}:{},exitCode:c}}const lr=Ao(f.data);if(lr)return y.complete(nn),lr;let Re;try{Re=e.privateExecutionBeta&&H==="create-epic"&&se?$t(s).operations[se.fingerprint]:void 0}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const rn=Re?.planningProtocol==="root-staged-v1"&&typeof Re.claimId=="string"&&typeof Re.epicId=="string"&&Ki(f.data,{claimId:Re.claimId,epicId:Re.epicId,...h(j.epics[Re.epicId]?.createEpicPlanningMemoryPhysical)?{memoryReceiptId:j.epics[Re.epicId].createEpicPlanningMemoryPhysical.receiptId}:{}});if(e.privateExecutionBeta&&!rn&&!Ji(f.data))return{success:!1,error:"private-execution-public-envelope-invalid",errorCode:"private-execution-public-envelope-invalid",exitCode:1};if(Rt&&k&&f.data.metadata?.mode==="arch-plan"&&h(f.data.metadata.archPlan)&&h(f.data.metadata.archPlan.execution)&&(f.data.metadata.archPlan.execution.nextAction==="delegate"||f.data.metadata.archPlan.execution.nextAction==="resume"||f.data.metadata.archPlan.execution.nextAction==="ask-user"||f.data.metadata.archPlan.execution.nextAction==="complete"&&f.data.metadata.archPlan.execution.currentStageCommand==="update-memory"||f.data.metadata.archPlan.execution.nextAction==="blocked"&&(f.data.metadata.archPlan.execution.currentStageCommand==="arch-ux-design"||f.data.metadata.archPlan.execution.currentStageCommand==="arch-performance"||f.data.metadata.archPlan.execution.currentStageCommand==="arch-testing"||f.data.metadata.archPlan.execution.currentStageCommand==="arch-infrastructure"||f.data.metadata.archPlan.execution.currentStageCommand==="arch-review")))try{await y.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>Wo({projectRoot:s,sourceStateSha256:Rt,requestExecution:k,initialBinding:Ct,answerReceipt:we,pactRecordedReceipt:B,metadata:f.data.metadata}),async()=>{throw new Error("architecture-root-writeback-effect-skipped")})}catch(c){const d=c instanceof Error&&/^architecture-root-[a-z-]+$/.test(c.message)?c.message:"architecture-root-writeback-failed";return process.stderr.write(`[Neocortex] ${d}. Root stage instruction was not released.
68
+ `),{success:!1,error:d,errorCode:d,exitCode:1}}if(!ee&&f.data.metadata?.mode==="menu"&&V&&await y.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>ic(V,f.data.instructions,f.data.metadata),async()=>{}).catch(()=>{}),f.data.metadata&&await y.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"tier-cache",operation:"update"},()=>G.tierClient.updateQuotaFromResponse(f.data.metadata),async()=>{}).catch(()=>{}),f.data.metadata?.stateMutated===!0)try{const c=await y.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>{const{persistMigratedStateFromResponse:d}=await import("../yoloop/invoke-hooks.js");return d(f.data.metadata,s)},async()=>({applied:!1,blocking:!1,reasonCode:"state-writeback-effect-skipped"}));if(c.blocking){const d=`STATE_WRITEBACK_BLOCKED: ${c.reasonCode}. Canonical state was not replaced.`;return process.stderr.write(`${d}
69
+ `),{success:!1,error:d,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}catch(c){if(f.data.metadata?.stateMutationReason==="inline-yolo-materialized-synthetic-story"){const d=c instanceof Error?c.message:String(c),m=`STATE_WRITEBACK_BLOCKED: inline-yolo persistence failed (${ze(d,kt)}).`;return process.stderr.write(`${m}
70
+ `),{success:!1,error:m,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}if(f.data.metadata?.gitLifecycleGraphAuthority)try{await y.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},()=>ro(s,f.data.metadata.gitLifecycleGraphAuthority),async()=>{throw new Error("git-lifecycle-graph-authority-effect-skipped")})}catch(c){const d=c instanceof Error&&/^git-lifecycle-/.test(c.message)?c.message:"git-lifecycle-graph-authority-persist-failed";return process.stderr.write(`[Neocortex] ${d}. Graph authority was not persisted; no YOLO checkpoint instruction was released.
71
71
  `),{success:!1,error:d,errorCode:"GIT_LIFECYCLE_GRAPH_AUTHORITY_INVALID",exitCode:1}}if(f.data.metadata?.mode==="error"&&f.data.metadata?.errorCode==="CLIENT_UPGRADE_REQUIRED")return process.stderr.write(`
72
72
  `),process.stderr.write(`==================================================
73
73
  `),process.stderr.write(` YOLOOP CLIENT UPGRADE REQUIRED
74
74
  `),process.stderr.write(`==================================================
75
75
  `),process.stderr.write(`
76
- Your Neocortex client version (${Tt}) does not
76
+ Your Neocortex client version (${Pt}) does not
77
77
  `),process.stderr.write(` support client-side yoloop state persistence.
78
78
 
79
79
  `),process.stderr.write(` Run this command to upgrade:
@@ -87,12 +87,12 @@ ${t}
87
87
  `),{success:!1,error:A,errorCode:A,exitCode:1}}}catch(m){if(d){const A=m instanceof Error?m.message.match(/\bYOLOOP_[A-Z0-9_]+\b/)?.[0]??"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED":"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED";return process.stderr.write(`[Neocortex] ${A}. No yoloop continuation instructions were released.
88
88
  `),{success:!1,error:A,errorCode:A,exitCode:1}}}}if(f.data.metadata?.continuityStateUpdate)try{const c=await y.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"continuity-store",operation:"update"},async()=>{const{persistContinuityFromResponse:d}=await import("../continuity/invoke-hooks.js");return d(f.data.metadata,s)},async()=>({ok:!0,reasonCodes:[]}));if(!c.ok){const d=c.reasonCodes.join(",");return process.stderr.write(`[Neocortex] continuity persistence failed: ${d}. No continuity mutation was committed.
89
89
  `),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${d}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}}catch(c){const d=c instanceof Error?c.message:String(c);return process.stderr.write(`[Neocortex] continuity persistence hook failed: ${d}. No continuity mutation was committed.
90
- `),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${ze(d,Pt)}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}if(f.data.metadata?.tier_changed){const c=f.data.metadata.current_tier;try{await H.client.forceRefresh()?(await H.tierClient.invalidateTierCache(),process.stderr.write(`[Neocortex] Token atualizado automaticamente para tier ${c}
90
+ `),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${ze(d,kt)}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}if(f.data.metadata?.tier_changed){const c=f.data.metadata.current_tier;try{await G.client.forceRefresh()?(await G.tierClient.invalidateTierCache(),process.stderr.write(`[Neocortex] Token atualizado automaticamente para tier ${c}
91
91
  `)):process.stderr.write(`[Neocortex] Seu tier foi atualizado para ${c}! Execute "neocortex activate" para obter um token atualizado.
92
92
  `)}catch{process.stderr.write(`[Neocortex] Seu tier foi atualizado para ${c}! Execute "neocortex activate" para obter um token atualizado.
93
- `)}}let re,lr=!1;if(e.privateExecutionBeta&&!nn)try{if(!X||!f.data.metadata?.privateExecution||!De||f.data.metadata?.mode!=="yolo"&&f.data.metadata?.mode!=="step"&&f.data.metadata?.mode!=="pipeline"&&f.data.metadata?.mode!=="create-epic"&&f.data.metadata?.mode!=="utility"&&f.data.metadata?.mode!=="tech-debt"&&f.data.metadata?.mode!=="ui-ux-review"||typeof f.data.metadata.stepId!="string")throw new Error("private-execution-descriptor-unavailable");const{consumePrivateExecutionDelivery:c,privateExecutionStateSnapshotSha256:d}=await import("../private-execution/delivery.js"),{preflightPrivateCodexExecutor:m,runPrivateCodexStep:A}=await import("../private-execution/codex-executor.js"),U=f.data.metadata.mode==="yolo",ie=f.data.metadata.mode==="ui-ux-review"&&f.data.metadata.resolvedTrigger==="ui-ux-review",de=f.data.metadata.mode==="create-epic",ae=h(f.data.metadata.privateExecution)?f.data.metadata.privateExecution:void 0,fe=h(ae?.binding)?ae.binding:void 0,$=de&&f.data.metadata.resolvedTrigger==="create-epic"&&fe?.writeSetId==="idea-diagnosis-v1"&&f.data.metadata.stepId==="step-acd455ed";if(de&&!$)throw new Error("private-execution-planning-root-protocol-required");const Ee=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="idea-diagnose"||$,Be=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="idea-research",me=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="generate-epic",Ue=de||Ee;if(Be&&!ye||me&&!le)throw new Error("private-execution-planning-predecessor-unavailable");const Ke=f.data.metadata.mode==="utility"&&f.data.metadata.resolvedTrigger==="sync-openapi"||f.data.metadata.mode==="utility"&&f.data.metadata.resolvedTrigger==="chaos-plan"||S&&f.data.metadata.mode==="tech-debt"&&f.data.metadata.resolvedTrigger==="tech-debt",Ce=f.data.metadata.mode==="step"&&(f.data.metadata.resolvedTrigger==="arch-prd"||f.data.metadata.resolvedTrigger==="arch-architecture"||f.data.metadata.resolvedTrigger==="arch-fitness-functions"||f.data.metadata.resolvedTrigger==="arch-api-contracts"||f.data.metadata.resolvedTrigger==="arch-api-integrations"||f.data.metadata.resolvedTrigger==="arch-database"||f.data.metadata.resolvedTrigger==="arch-security"||f.data.metadata.resolvedTrigger==="arch-design-system"||f.data.metadata.resolvedTrigger==="arch-performance"||f.data.metadata.resolvedTrigger==="arch-testing"||f.data.metadata.resolvedTrigger==="arch-infrastructure"||f.data.metadata.resolvedTrigger==="arch-review"||f.data.metadata.resolvedTrigger==="update-memory")?f.data.metadata.resolvedTrigger:void 0,ft=Ce!==void 0,An=Ce==="arch-prd"?"arch-prd-docs-v1":Ce==="update-memory"?"arch-memory-canonical-v1":Ce==="arch-review"?"arch-review-doc-v1":Ce==="arch-infrastructure"?"arch-infrastructure-doc-v1":Ce==="arch-testing"?"arch-testing-doc-v1":Ce==="arch-performance"?"arch-performance-doc-v1":Ce==="arch-design-system"?"arch-design-system-doc-v1":Ce==="arch-security"?"arch-security-doc-v1":Ce==="arch-database"?"arch-database-doc-v1":Ce==="arch-api-integrations"?"arch-api-integrations-doc-v1":Ce==="arch-api-contracts"?"arch-api-contracts-docs-v1":Ce==="arch-fitness-functions"?"arch-fitness-tools-v1":"arch-architecture-doc-v1",nt=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="generate-pacts",mt=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="arch-ux-design",yt=f.data.metadata.mode==="utility"&&f.data.metadata.resolvedTrigger==="property-test",bn=S?"tech-debt":f.data.metadata.resolvedTrigger==="chaos-plan"?"chaos-plan":"sync-openapi",ur=S?"tech-debt-registry-v1":bn==="chaos-plan"?"chaos-quarterly-v1":"sync-openapi-contract-v1",Fe=k.archPlan?.execution,an=Fe?.targetEpicId,on=Fe?.graphRevision;if(ft&&(Fe?.currentStageCommand!==Ce||typeof an!="string"||!/^P[1-9][0-9]{0,11}$/.test(an)||typeof on!="string"||!/^[a-f0-9]{64}$/.test(on)))throw new Error("private-execution-architecture-admission-unverified");if(nt&&(!ge||!je||!z||Fe?.currentStageCommand!=="generate-pacts"||Fe.continuationState!=="delegate"||Fe.targetEpicId!==ge.targetEpicId||Fe.graphRevision!==ge.graphRevision||!v(Fe.pactAnswerReceipt,z.receipt)))throw new Error("private-execution-pact-admission-unverified");if(mt&&(!ne||!Ve||Fe?.currentStageCommand!=="arch-ux-design"||Fe.continuationState!=="delegate"||Fe.targetEpicId!==ne.targetEpicId||Fe.graphRevision!==ne.graphRevision))throw new Error("private-execution-ux-admission-unverified");if(yt&&(!Ie||!wt||!qe||f.data.metadata.stepId!=="step-a8ce5c64"))throw new Error("private-execution-property-admission-unverified");let hr;if(nt){const{planPactToolchainManifest:ce,preparePactToolchainCandidate:ue}=await import("../private-execution/pact-toolchain.js");try{ce(s,z.answers.generateProvider),hr=ue(s,z.answers.generateProvider)}catch(W){if(W.message!=="pact-toolchain-manifest-unsupported")throw W}}let Rt,pe,xn;const oe=f.data.metadata.gitLifecycleGraphAuthority,At=f.data.metadata.privateExecutionRootAction;let Qe;if(U){if(!oe||typeof oe.storyId!="string"||typeof oe.graphRevision!="string"||typeof oe.executionBranch!="string")throw new Error("private-execution-graph-unavailable");if(Qe=oe.storyId,At?.action==="prepare-epic-checkout"){const{parsePrivateExecutionDescriptor:b}=await import("../private-execution/delivery.js"),{prepareDirectYoloSetup:Te}=await import("../git/direct-yolo-checkpoint.js"),{acceptDirectYoloSetupCheckpoint:It}=await import("../git/direct-yolo-checkpoint.js"),{capturePrivateYoloCleanHead:He,recordPrivateYoloCleanBaseline:Ae}=await import("../private-execution/clean-baseline.js"),be=b(f.data.metadata.privateExecution,{projectId:De,commandId:"yolo",stepId:f.data.metadata.stepId,graphRevision:oe.graphRevision,inputSha256:n.sha256,hostKind:"codex-cli",hostVersion:X.hostVersion}),it=await H.client.getToken();if(!it)throw new Error("private-execution-auth-unavailable");if(!await Zc(M,{leaseId:be.leaseId,...be.binding},it))throw new Error("private-execution-setup-lease-cancel-unverified");const Dt=He(s),cn=await Te({projectRoot:s,storyId:At.storyId});if(!cn.ok)throw new Error("private-execution-root-setup-denied");await Ae(s,cn.value,Dt);const{ensurePrivateYoloIsolatedSession:bt}=await import("../private-execution/isolated-session.js");await bt(s,At.storyId,oe.graphRevision,e.privateExecutionWorkspaceParent);const xt=await It({projectRoot:s,storyId:At.storyId});if(!xt.ok)throw new Error(`private-execution-root-setup-checkpoint-denied:${xt.reasonCode}`);re={schemaVersion:1,outcome:"setup-accepted",executorOutcome:"not-run-root-only",setup:xt.value,publicSafe:!0};const Tn=fn(f.data.instructions,{...f.data.metadata,...f.compatibility?{compatibility:f.compatibility}:{}});return y.complete(Nt),{success:!0,instructions:`# Setup do branch validado
93
+ `)}}let re,ur=!1;if(e.privateExecutionBeta&&!rn)try{if(!X||!f.data.metadata?.privateExecution||!De||f.data.metadata?.mode!=="yolo"&&f.data.metadata?.mode!=="step"&&f.data.metadata?.mode!=="pipeline"&&f.data.metadata?.mode!=="create-epic"&&f.data.metadata?.mode!=="utility"&&f.data.metadata?.mode!=="tech-debt"&&f.data.metadata?.mode!=="ui-ux-review"||typeof f.data.metadata.stepId!="string")throw new Error("private-execution-descriptor-unavailable");const{consumePrivateExecutionDelivery:c,privateExecutionStateSnapshotSha256:d}=await import("../private-execution/delivery.js"),{preflightPrivateCodexExecutor:m,runPrivateCodexStep:A}=await import("../private-execution/codex-executor.js"),U=f.data.metadata.mode==="yolo",ie=f.data.metadata.mode==="ui-ux-review"&&f.data.metadata.resolvedTrigger==="ui-ux-review",de=f.data.metadata.mode==="create-epic",ae=h(f.data.metadata.privateExecution)?f.data.metadata.privateExecution:void 0,fe=h(ae?.binding)?ae.binding:void 0,$=de&&f.data.metadata.resolvedTrigger==="create-epic"&&fe?.writeSetId==="idea-diagnosis-v1"&&f.data.metadata.stepId==="step-acd455ed";if(de&&!$)throw new Error("private-execution-planning-root-protocol-required");const Ee=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="idea-diagnose"||$,Be=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="idea-research",me=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="generate-epic",Ue=de||Ee;if(Be&&!ye||me&&!le)throw new Error("private-execution-planning-predecessor-unavailable");const Ke=f.data.metadata.mode==="utility"&&f.data.metadata.resolvedTrigger==="sync-openapi"||f.data.metadata.mode==="utility"&&f.data.metadata.resolvedTrigger==="chaos-plan"||S&&f.data.metadata.mode==="tech-debt"&&f.data.metadata.resolvedTrigger==="tech-debt",Ce=f.data.metadata.mode==="step"&&(f.data.metadata.resolvedTrigger==="arch-prd"||f.data.metadata.resolvedTrigger==="arch-architecture"||f.data.metadata.resolvedTrigger==="arch-fitness-functions"||f.data.metadata.resolvedTrigger==="arch-api-contracts"||f.data.metadata.resolvedTrigger==="arch-api-integrations"||f.data.metadata.resolvedTrigger==="arch-database"||f.data.metadata.resolvedTrigger==="arch-security"||f.data.metadata.resolvedTrigger==="arch-design-system"||f.data.metadata.resolvedTrigger==="arch-performance"||f.data.metadata.resolvedTrigger==="arch-testing"||f.data.metadata.resolvedTrigger==="arch-infrastructure"||f.data.metadata.resolvedTrigger==="arch-review"||f.data.metadata.resolvedTrigger==="update-memory")?f.data.metadata.resolvedTrigger:void 0,gt=Ce!==void 0,bn=Ce==="arch-prd"?"arch-prd-docs-v1":Ce==="update-memory"?"arch-memory-canonical-v1":Ce==="arch-review"?"arch-review-doc-v1":Ce==="arch-infrastructure"?"arch-infrastructure-doc-v1":Ce==="arch-testing"?"arch-testing-doc-v1":Ce==="arch-performance"?"arch-performance-doc-v1":Ce==="arch-design-system"?"arch-design-system-doc-v1":Ce==="arch-security"?"arch-security-doc-v1":Ce==="arch-database"?"arch-database-doc-v1":Ce==="arch-api-integrations"?"arch-api-integrations-doc-v1":Ce==="arch-api-contracts"?"arch-api-contracts-docs-v1":Ce==="arch-fitness-functions"?"arch-fitness-tools-v1":"arch-architecture-doc-v1",nt=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="generate-pacts",ft=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="arch-ux-design",mt=f.data.metadata.mode==="utility"&&f.data.metadata.resolvedTrigger==="property-test",xn=S?"tech-debt":f.data.metadata.resolvedTrigger==="chaos-plan"?"chaos-plan":"sync-openapi",hr=S?"tech-debt-registry-v1":xn==="chaos-plan"?"chaos-quarterly-v1":"sync-openapi-contract-v1",Fe=O.archPlan?.execution,on=Fe?.targetEpicId,cn=Fe?.graphRevision;if(gt&&(Fe?.currentStageCommand!==Ce||typeof on!="string"||!/^P[1-9][0-9]{0,11}$/.test(on)||typeof cn!="string"||!/^[a-f0-9]{64}$/.test(cn)))throw new Error("private-execution-architecture-admission-unverified");if(nt&&(!ge||!je||!J||Fe?.currentStageCommand!=="generate-pacts"||Fe.continuationState!=="delegate"||Fe.targetEpicId!==ge.targetEpicId||Fe.graphRevision!==ge.graphRevision||!v(Fe.pactAnswerReceipt,J.receipt)))throw new Error("private-execution-pact-admission-unverified");if(ft&&(!ne||!Ve||Fe?.currentStageCommand!=="arch-ux-design"||Fe.continuationState!=="delegate"||Fe.targetEpicId!==ne.targetEpicId||Fe.graphRevision!==ne.graphRevision))throw new Error("private-execution-ux-admission-unverified");if(mt&&(!Ie||!_t||!qe||f.data.metadata.stepId!=="step-a8ce5c64"))throw new Error("private-execution-property-admission-unverified");let gr;if(nt){const{planPactToolchainManifest:ce,preparePactToolchainCandidate:ue}=await import("../private-execution/pact-toolchain.js");try{ce(s,J.answers.generateProvider),gr=ue(s,J.answers.generateProvider)}catch(F){if(F.message!=="pact-toolchain-manifest-unsupported")throw F}}let At,pe,Tn;const oe=f.data.metadata.gitLifecycleGraphAuthority,bt=f.data.metadata.privateExecutionRootAction;let Qe;if(U){if(!oe||typeof oe.storyId!="string"||typeof oe.graphRevision!="string"||typeof oe.executionBranch!="string")throw new Error("private-execution-graph-unavailable");if(Qe=oe.storyId,bt?.action==="prepare-epic-checkout"){const{parsePrivateExecutionDescriptor:x}=await import("../private-execution/delivery.js"),{prepareDirectYoloSetup:Te}=await import("../git/direct-yolo-checkpoint.js"),{acceptDirectYoloSetupCheckpoint:yt}=await import("../git/direct-yolo-checkpoint.js"),{capturePrivateYoloCleanHead:He,recordPrivateYoloCleanBaseline:Ae}=await import("../private-execution/clean-baseline.js"),be=x(f.data.metadata.privateExecution,{projectId:De,commandId:"yolo",stepId:f.data.metadata.stepId,graphRevision:oe.graphRevision,inputSha256:n.sha256,hostKind:"codex-cli",hostVersion:X.hostVersion}),it=await G.client.getToken();if(!it)throw new Error("private-execution-auth-unavailable");if(!await ts(M,{leaseId:be.leaseId,...be.binding},it))throw new Error("private-execution-setup-lease-cancel-unverified");const Dt=He(s),sn=await Te({projectRoot:s,storyId:bt.storyId});if(!sn.ok)throw new Error("private-execution-root-setup-denied");await Ae(s,sn.value,Dt);const{ensurePrivateYoloIsolatedSession:xt}=await import("../private-execution/isolated-session.js");await xt(s,bt.storyId,oe.graphRevision,e.privateExecutionWorkspaceParent);const Tt=await yt({projectRoot:s,storyId:bt.storyId});if(!Tt.ok)throw new Error(`private-execution-root-setup-checkpoint-denied:${Tt.reasonCode}`);re={schemaVersion:1,outcome:"setup-accepted",executorOutcome:"not-run-root-only",setup:Tt.value,publicSafe:!0};const Pn=mn(f.data.instructions,{...f.data.metadata,...f.compatibility?{compatibility:f.compatibility}:{}});return y.complete(nn),{success:!0,instructions:`# Setup do branch validado
94
94
 
95
- O root confirmou o checkpoint C01 no branch do \xE9pico. Reexecute o mesmo YOLO para avan\xE7ar \xE0 pr\xF3xima etapa.`,metadata:{...Tn.metadata,privateExecutionReceipt:re},exitCode:0}}let ce;try{ce=Ge("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:s,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{throw new Error("private-execution-execution-branch-mismatch")}if(ce!==oe.executionBranch)throw new Error("private-execution-execution-branch-mismatch");const ue=hn(s,{required:!0}),W=typeof oe.epicId=="string"?ue.epics[oe.epicId]:void 0,L=h(W?.branch_lease)?W.branch_lease:void 0;if(!W||W.graph_revision!==oe.graphRevision||!L||L.ownerStoryId!==oe.storyId||typeof L.expiresAt!="string"||!Number.isFinite(Date.parse(L.expiresAt))||Date.parse(L.expiresAt)<=Date.now())throw new Error("private-execution-writer-lease-unavailable")}else if(f.data.metadata.mode==="step"&&(f.data.metadata.resolvedTrigger==="research"||f.data.metadata.resolvedTrigger==="write-spec"||f.data.metadata.resolvedTrigger==="create-tasks"||f.data.metadata.resolvedTrigger==="implement")||f.data.metadata.mode==="pipeline"&&f.data.metadata.resolvedTrigger==="exec"||de&&f.data.metadata.resolvedTrigger==="create-epic"||ie||Ee||Be||me||Ke||ft||nt||mt||yt){if(!Ue&&!Be&&!me&&!Ke&&!ie&&!ft&&!nt&&!mt&&!yt&&typeof f.data.metadata.storyId!="string")throw new Error("private-execution-descriptor-unavailable")}else throw new Error("private-execution-descriptor-unavailable");if(U){const{ensurePrivateYoloIsolatedSession:ce,reconcilePrivateYoloIsolatedSession:ue}=await import("../private-execution/isolated-session.js");if(At?.action==="checkpoint-epic-story")await ue(s,Qe,oe.graphRevision);else{const W=await ce(s,Qe,oe.graphRevision,e.privateExecutionWorkspaceParent),L=await m(W.workspace.workspacePath);if(L.hostVersion!==X.hostVersion)throw new Error("private-codex-version-drift");X=L}}if(Date.now()-X.observedAtMs>2e4){const ce=await m(X.projectRoot);if(ce.hostVersion!==X.hostVersion)throw new Error("private-codex-version-drift");X=ce}const gr=await H.client.getToken();if(!gr)throw new Error("private-execution-auth-unavailable");const $e=Ue?f.data.metadata.epicClaim:void 0;if(Ue&&(!$e||typeof $e.claimId!="string"||typeof $e.epicId!="string"))throw new Error("private-execution-descriptor-unavailable");if(Ue){if(!se)throw new Error("private-execution-epic-claim-admission-unverified");y.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Kr(s,se.fingerprint,$e.claimId,$e.epicId,$?"root-staged-v1":void 0),()=>{}),lr=!0;const{preparePrivateYoloIsolatedWorkspace:ce,PRIVATE_EPIC_PENDING_SIDECAR:ue}=await import("../private-execution/isolated-workspace.js"),W=e.privateExecutionWorkspaceParent??Q(Kt(),".local","share","neocortex","private-epic-workspaces");e.privateExecutionWorkspaceParent||qt(W,{recursive:!0,mode:448}),Rt=ce(s,W,!0),xn=Pe("sha256").update(We(Q(s,ue))).digest("hex");const L=await m(Rt.workspacePath);if(L.hostVersion!==X.hostVersion)throw new Error("private-codex-version-drift");X=L}else if(!U&&!ie){const{preparePrivateYoloIsolatedWorkspace:ce}=await import("../private-execution/isolated-workspace.js"),ue=e.privateExecutionWorkspaceParent??Q(Kt(),".local","share","neocortex","private-step-workspaces");if(e.privateExecutionWorkspaceParent||qt(ue,{recursive:!0,mode:448}),pe=ce(s,ue,Be||me),Ke||ft||nt||mt||yt){if(!Z)throw new Error("private-execution-project-snapshot-unverified");const{assertPrivateProjectStepBaseline:L}=await import("../private-execution/isolated-workspace.js");L(pe,Z)}const W=await m(pe.workspacePath);if(W.hostVersion!==X.hostVersion)throw new Error("private-codex-version-drift");X=W}const rt=await c(f.data.metadata.privateExecution,{projectId:De,commandId:U?"yolo":de?"create-epic":ft?Ce:nt?"generate-pacts":mt?"arch-ux-design":yt?"property-test":Ke?bn:f.data.metadata.mode==="pipeline"?"exec":f.data.metadata.resolvedTrigger,stepId:f.data.metadata.stepId,...U?{graphRevision:oe.graphRevision}:{...Ue?{claimId:$e.claimId,epicId:$e.epicId,...Ee?{writeSetId:"idea-diagnosis-v1"}:{}}:Be?{claimId:ye.claimId,epicId:ye.epicId,diagnosisReceiptId:ye.diagnosisReceiptId,intakeRevision:ye.intakeRevision,physicalAcceptanceReceiptId:ye.physicalAcceptanceReceiptId,writeSetId:"idea-research-v1"}:me?{claimId:le.claimId,epicId:le.epicId,diagnosisReceiptId:le.diagnosisReceiptId,researchReceiptId:le.researchReceiptId,intakeRevision:le.intakeRevision,physicalAcceptanceReceiptId:le.physicalAcceptanceReceiptId,writeSetId:"generate-epic-v1"}:Ke?{writeSetId:ur}:ie?{format:o.selection.uiUxReview?.json===!0?"json":"markdown"}:ft?{targetEpicId:an,graphRevision:on,writeSetId:An}:nt?{targetEpicId:ge.targetEpicId,graphRevision:ge.graphRevision,answersSha256:ge.answersSha256,specSha256:ge.specSha256,pathsSha256:ge.pathsSha256,endpointCount:ge.endpointCount,pathCount:ge.pathCount}:mt?{targetEpicId:ne.targetEpicId,graphRevision:ne.graphRevision,adapterId:ne.adapterId,authoritySha256:ne.authoritySha256,pathsSha256:ne.pathsSha256,screenCount:ne.screenCount,pathCount:ne.pathCount}:yt?{prdPath:Ie.prdPath,prdSha256:Ie.prdSha256,planSha256:Ie.planSha256,pathsSha256:Ie.pathsSha256,aggregateCount:Ie.aggregateCount,invariantCount:Ie.invariantCount,pathCount:Ie.pathCount,language:Ie.language,numRuns:Ie.numRuns}:{storyId:f.data.metadata.storyId},stateSnapshotSha256:d(k)},inputSha256:n.sha256,hostKind:"codex-cli",hostVersion:X.hostVersion},ce=>Xc(M,{...ce},gr));if(ie){const{parsePrivateExecutionDescriptor:ce}=await import("../private-execution/delivery.js"),ue=ce(f.data.metadata.privateExecution);if(ue.schemaVersion!==11||ue.binding.commandId!=="ui-ux-review"||ue.binding.format!==(o.selection.uiUxReview?.json===!0?"json":"markdown"))throw new Error("private-execution-report-binding-unverified");const{storePrivateUiUxReviewReport:W}=await import("../private-execution/private-report-store.js");re={schemaVersion:1,outcome:"report-stored",report:await W({projectRoot:s,material:rt,format:ue.binding.format,sha256:ue.materialSha256}),publicSafe:!0}}else if(At?.action==="checkpoint-epic-story"){const{runPrivateYoloRootCheckpoint:ce}=await import("../private-execution/root-checkpoint.js");re={...await ce(s,At)}}else{const ce=Ee?`${rt}
95
+ O root confirmou o checkpoint C01 no branch do \xE9pico. Reexecute o mesmo YOLO para avan\xE7ar \xE0 pr\xF3xima etapa.`,metadata:{...Pn.metadata,privateExecutionReceipt:re},exitCode:0}}let ce;try{ce=Ge("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:s,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{throw new Error("private-execution-execution-branch-mismatch")}if(ce!==oe.executionBranch)throw new Error("private-execution-execution-branch-mismatch");const ue=gn(s,{required:!0}),F=typeof oe.epicId=="string"?ue.epics[oe.epicId]:void 0,D=h(F?.branch_lease)?F.branch_lease:void 0;if(!F||F.graph_revision!==oe.graphRevision||!D||D.ownerStoryId!==oe.storyId||typeof D.expiresAt!="string"||!Number.isFinite(Date.parse(D.expiresAt))||Date.parse(D.expiresAt)<=Date.now())throw new Error("private-execution-writer-lease-unavailable")}else if(f.data.metadata.mode==="step"&&(f.data.metadata.resolvedTrigger==="research"||f.data.metadata.resolvedTrigger==="write-spec"||f.data.metadata.resolvedTrigger==="create-tasks"||f.data.metadata.resolvedTrigger==="implement")||f.data.metadata.mode==="pipeline"&&f.data.metadata.resolvedTrigger==="exec"||de&&f.data.metadata.resolvedTrigger==="create-epic"||ie||Ee||Be||me||Ke||gt||nt||ft||mt){if(!Ue&&!Be&&!me&&!Ke&&!ie&&!gt&&!nt&&!ft&&!mt&&typeof f.data.metadata.storyId!="string")throw new Error("private-execution-descriptor-unavailable")}else throw new Error("private-execution-descriptor-unavailable");if(U){const{ensurePrivateYoloIsolatedSession:ce,reconcilePrivateYoloIsolatedSession:ue}=await import("../private-execution/isolated-session.js");if(bt?.action==="checkpoint-epic-story")await ue(s,Qe,oe.graphRevision);else{const F=await ce(s,Qe,oe.graphRevision,e.privateExecutionWorkspaceParent),D=await m(F.workspace.workspacePath);if(D.hostVersion!==X.hostVersion)throw new Error("private-codex-version-drift");X=D}}if(Date.now()-X.observedAtMs>2e4){const ce=await m(X.projectRoot);if(ce.hostVersion!==X.hostVersion)throw new Error("private-codex-version-drift");X=ce}const fr=await G.client.getToken();if(!fr)throw new Error("private-execution-auth-unavailable");const $e=Ue?f.data.metadata.epicClaim:void 0;if(Ue&&(!$e||typeof $e.claimId!="string"||typeof $e.epicId!="string"))throw new Error("private-execution-descriptor-unavailable");if(Ue){if(!se)throw new Error("private-execution-epic-claim-admission-unverified");y.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Qr(s,se.fingerprint,$e.claimId,$e.epicId,$?"root-staged-v1":void 0),()=>{}),ur=!0;const{preparePrivateYoloIsolatedWorkspace:ce,PRIVATE_EPIC_PENDING_SIDECAR:ue}=await import("../private-execution/isolated-workspace.js"),F=e.privateExecutionWorkspaceParent??Q(Jt(),".local","share","neocortex","private-epic-workspaces");e.privateExecutionWorkspaceParent||Yt(F,{recursive:!0,mode:448}),At=ce(s,F,!0),Tn=Pe("sha256").update(We(Q(s,ue))).digest("hex");const D=await m(At.workspacePath);if(D.hostVersion!==X.hostVersion)throw new Error("private-codex-version-drift");X=D}else if(!U&&!ie){const{preparePrivateYoloIsolatedWorkspace:ce}=await import("../private-execution/isolated-workspace.js"),ue=e.privateExecutionWorkspaceParent??Q(Jt(),".local","share","neocortex","private-step-workspaces");if(e.privateExecutionWorkspaceParent||Yt(ue,{recursive:!0,mode:448}),pe=ce(s,ue,Be||me),Ke||gt||nt||ft||mt){if(!Z)throw new Error("private-execution-project-snapshot-unverified");const{assertPrivateProjectStepBaseline:D}=await import("../private-execution/isolated-workspace.js");D(pe,Z)}const F=await m(pe.workspacePath);if(F.hostVersion!==X.hostVersion)throw new Error("private-codex-version-drift");X=F}const rt=await c(f.data.metadata.privateExecution,{projectId:De,commandId:U?"yolo":de?"create-epic":gt?Ce:nt?"generate-pacts":ft?"arch-ux-design":mt?"property-test":Ke?xn:f.data.metadata.mode==="pipeline"?"exec":f.data.metadata.resolvedTrigger,stepId:f.data.metadata.stepId,...U?{graphRevision:oe.graphRevision}:{...Ue?{claimId:$e.claimId,epicId:$e.epicId,...Ee?{writeSetId:"idea-diagnosis-v1"}:{}}:Be?{claimId:ye.claimId,epicId:ye.epicId,diagnosisReceiptId:ye.diagnosisReceiptId,intakeRevision:ye.intakeRevision,physicalAcceptanceReceiptId:ye.physicalAcceptanceReceiptId,writeSetId:"idea-research-v1"}:me?{claimId:le.claimId,epicId:le.epicId,diagnosisReceiptId:le.diagnosisReceiptId,researchReceiptId:le.researchReceiptId,intakeRevision:le.intakeRevision,physicalAcceptanceReceiptId:le.physicalAcceptanceReceiptId,writeSetId:"generate-epic-v1"}:Ke?{writeSetId:hr}:ie?{format:o.selection.uiUxReview?.json===!0?"json":"markdown"}:gt?{targetEpicId:on,graphRevision:cn,writeSetId:bn}:nt?{targetEpicId:ge.targetEpicId,graphRevision:ge.graphRevision,answersSha256:ge.answersSha256,specSha256:ge.specSha256,pathsSha256:ge.pathsSha256,endpointCount:ge.endpointCount,pathCount:ge.pathCount}:ft?{targetEpicId:ne.targetEpicId,graphRevision:ne.graphRevision,adapterId:ne.adapterId,authoritySha256:ne.authoritySha256,pathsSha256:ne.pathsSha256,screenCount:ne.screenCount,pathCount:ne.pathCount}:mt?{prdPath:Ie.prdPath,prdSha256:Ie.prdSha256,planSha256:Ie.planSha256,pathsSha256:Ie.pathsSha256,aggregateCount:Ie.aggregateCount,invariantCount:Ie.invariantCount,pathCount:Ie.pathCount,language:Ie.language,numRuns:Ie.numRuns}:{storyId:f.data.metadata.storyId},stateSnapshotSha256:d(O)},inputSha256:n.sha256,hostKind:"codex-cli",hostVersion:X.hostVersion},ce=>es(M,{...ce},fr));if(ie){const{parsePrivateExecutionDescriptor:ce}=await import("../private-execution/delivery.js"),ue=ce(f.data.metadata.privateExecution);if(ue.schemaVersion!==11||ue.binding.commandId!=="ui-ux-review"||ue.binding.format!==(o.selection.uiUxReview?.json===!0?"json":"markdown"))throw new Error("private-execution-report-binding-unverified");const{storePrivateUiUxReviewReport:F}=await import("../private-execution/private-report-store.js");re={schemaVersion:1,outcome:"report-stored",report:await F({projectRoot:s,material:rt,format:ue.binding.format,sha256:ue.materialSha256}),publicSafe:!0}}else if(bt?.action==="checkpoint-epic-story"){const{runPrivateYoloRootCheckpoint:ce}=await import("../private-execution/root-checkpoint.js");re={...await ce(s,bt)}}else{const ce=Ee?`${rt}
96
96
 
97
97
  Private P01 handoff (local only):
98
98
  The durable reserved epic ID is ${$e.epicId}. Complete only the diagnosis for this exact ID. Write exactly .neocortex/planning/epic-${$e.epicId}/idea.json, diagnosis.md, enriched-prompt.md and the matching entry in .neocortex/planning/planning.json. Do not write state.json, Git controls, another epic, or P02/P03 artifacts; do not auto-continue to the next step. The root will independently review and persist the accepted planning checkpoint.
@@ -104,34 +104,34 @@ The admitted epic is ${ye.epicId}. Research only this exact diagnosed epic. Writ
104
104
 
105
105
  Private P03 handoff (local only):
106
106
  The admitted epic is ${le.epicId}. Generate exactly docs/epics/epic-${le.epicId}.md, 1 to 24 contiguous docs/stories/${le.epicId}.NN.story.md files (01 through 24), and the matching transition in .neocortex/planning/planning.json. The 1 to 24 range is a safety maximum, not a required count. Derive the implementation story count from the accepted research scope; keep later epic lifecycle gates out of implementation stories. Epic frontmatter must contain its exact id and stories_count matching the files, and the document must contain the exact section heading ## Stories. Story frontmatter must use exactly one canonical epic_id field for this epic, with status backlog; do not emit the legacy epic alias. Each story needs the exact heading ## Acceptance Criteria and Given/When/Then criteria. In planning.json preserve all other entries and fields; for this epic set status generated, append only the current generation step after the two accepted predecessors, set completed_at to a non-null ISO timestamp, and add output_files.epic plus the ordered output_files.stories list. Keep a valid ISO last_scan. This is completion of the candidate index only, not root QA, memory or epic completion. Do not write state.json, Git controls, another epic, or subsequent-stage artifacts; do not auto-continue. The root will independently review and seal the generated candidate.
107
- `:ft?(await import("../private-execution/isolated-admission.js")).appendPrivateArchitectureHandoff(rt,Ce,An,mr(k.archPlan?.execution?.nonUiScopeReceipt)?"non-ui":"all"):nt?`${rt}
107
+ `:gt?(await import("../private-execution/isolated-admission.js")).appendPrivateArchitectureHandoff(rt,Ce,bn,yr(O.archPlan?.execution?.nonUiScopeReceipt)?"non-ui":"all"):nt?`${rt}
108
108
 
109
109
  Private A03.5 handoff (local only):
110
- ${JSON.stringify({consumer:z.answers.consumer,provider:z.answers.provider,matchersAggressive:z.answers.matchersAggressive,generateProvider:z.answers.generateProvider,brokerConfigured:z.answers.brokerUrl!==null,allowedPaths:je.paths})}
110
+ ${JSON.stringify({consumer:J.answers.consumer,provider:J.answers.provider,matchersAggressive:J.answers.matchersAggressive,generateProvider:J.answers.generateProvider,brokerConfigured:J.answers.brokerUrl!==null,allowedPaths:je.paths})}
111
111
  Read docs/api/openapi.yaml. Write only the listed new test files. Do not write package files, CI, Git, graph, or tracked configuration. Use describe and it from vitest for every consumer and provider test, plus expect for consumers. Consumer Pact imports are PactV3 and, only when matchersAggressive is true, MatchersV3. When false, use exact literal values and no matcher helpers or matchingRules. Provider imports Verifier. Do not import Node builtins, filesystem/path helpers or other packages; consumer application imports are allowed only for an existing tracked local client. Each consumer must use a literal HTTP method and concrete path in withRequest, willRespondWith and executeTest with actual response assertions. If no application client exists, label the direct fetch test a mock-only scaffold without claiming compatibility. If specifying a Pact output directory, use the literal pacts or pact-files without subdirectories. Never embed a broker URL. When brokerConfigured is false, verify only local pact files through literal pactUrls and never add broker configuration or token fields. When true, read PACT_BROKER_URL at runtime. Provider base URL may use PACT_PROVIDER_BASE_URL; missing runtime inputs must fail rather than skip. No network, install, provider startup, Git or QA authority is granted to the model.
112
- `:mt?`${rt}
112
+ `:ft?`${rt}
113
113
 
114
114
  Private A08 handoff (local only):
115
115
  ${JSON.stringify({targetEpicId:ne.targetEpicId,graphRevision:ne.graphRevision,adapterId:ne.adapterId,approvedScreens:Ve.screens,allowedPaths:Ve.paths})}
116
116
  Write only the approved paths. Keep synthetic fixtures and the canonical approved-story manifest. No Git, graph, QA or configuration effects.
117
- `:yt?`${rt}
117
+ `:mt?`${rt}
118
118
 
119
119
  Private property-test handoff (local only):
120
- ${JSON.stringify({language:qe.language,numRuns:qe.numRuns,aggregates:qe.aggregates.map(L=>({name:L.name,implementationFile:L.implementationFile,testFile:L.testFile,invariantCount:L.invariantCount}))})}
120
+ ${JSON.stringify({language:qe.language,numRuns:qe.numRuns,aggregates:qe.aggregates.map(D=>({name:D.name,implementationFile:D.implementationFile,testFile:D.testFile,invariantCount:D.invariantCount}))})}
121
121
  Read the PRD and implementation files inside this isolated clone. Write exactly the listed test files. Do not edit the PRD, state, Git, QA records or any other path. Scaffolds with unfinished assertions must fail explicitly; do not use skipped or todo tests. The root will write the confirmed PRD configuration and independently assess QA.
122
- `:rt;let ue=ce;if(U){const{readPrivateYoloFrozenWriteSet:L}=await import("../private-execution/clean-baseline.js"),{appendPrivateYoloFrozenHandoff:b}=await import("../private-execution/frozen-handoff.js"),Te=await L(s,Qe,oe.executionBranch,oe.graphRevision);ue=b(ce,Te);const{resumePrivateYoloIsolatedSession:It}=await import("../private-execution/isolated-session.js"),He=await It(s,Qe,oe.graphRevision),Ae=Sn(s,{epicAware:!0}).stories[Qe],be=k.stories[Qe];if(!Ae||!be||Ae.status!==be.status||JSON.stringify(Ae.steps_completed)!==JSON.stringify(be.steps_completed))throw new Error("private-execution-phase-snapshot-drift");const it=Ge("git",["rev-parse","HEAD"],{cwd:s,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();ue+=`
122
+ `:rt;let ue=ce;if(U){const{readPrivateYoloFrozenWriteSet:D}=await import("../private-execution/clean-baseline.js"),{appendPrivateYoloFrozenHandoff:x}=await import("../private-execution/frozen-handoff.js"),Te=await D(s,Qe,oe.executionBranch,oe.graphRevision);ue=x(ce,Te);const{resumePrivateYoloIsolatedSession:yt}=await import("../private-execution/isolated-session.js"),He=await yt(s,Qe,oe.graphRevision),Ae=vn(s,{epicAware:!0}).stories[Qe],be=O.stories[Qe];if(!Ae||!be||Ae.status!==be.status||JSON.stringify(Ae.steps_completed)!==JSON.stringify(be.steps_completed))throw new Error("private-execution-phase-snapshot-drift");const it=Ge("git",["rev-parse","HEAD"],{cwd:s,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();ue+=`
123
123
  Root physical dispatch observations (data, not phase completion):
124
124
  `+JSON.stringify({storyId:Qe,graphRevision:oe.graphRevision,sourceHeadSha:it,privateSnapshotSha:He.snapshotSha,effectiveStatus:Ae.status,hostKind:"codex-cli",hostVersion:X.hostVersion})+`
125
125
  Use these observed revisions and runtime facts; do not infer Git metadata or substitute an invented revision.
126
- `}const W=await A(ue,X,{requireWorkspaceEffect:!0,...e.onPrivateExecutionWorkspaceFailure===void 0?{}:{onWorkspaceEffectFailure:e.onPrivateExecutionWorkspaceFailure},...e.privateExecutionModel===void 0?{}:{model:e.privateExecutionModel},...U?{expectedExecutionBranch:oe.executionBranch}:Rt?{expectedExecutionBranch:Rt.executionBranch}:pe?{expectedExecutionBranch:pe.executionBranch}:{}});if(U){const{admitPrivateYoloIsolatedSessionStep:L}=await import("../private-execution/isolated-session.js"),b=await L(s,Qe,oe.graphRevision);let Te;if(f.data.metadata.stepId===Ji){const He=f.data.metadata.mutationQaFeature;if(!He)throw new Error("private-execution-mutation-qa-authority-unavailable");if(!He.enabled)Te={schemaVersion:1,status:"skipped-server-authority",publicSafe:!0};else{let Ae,be;try{const it=b.session.workspace.workspacePath,Dt=`sha:${b.session.workspace.baseSha}`,{planMutationQa:cn}=await import("./mutation-qa.js"),bt=cn(it,Dt);if(bt.headSha!==b.session.snapshotSha)throw new Error("private-execution-mutation-qa-snapshot-drift");let xt="not-run";if(bt.outcome==="ready"){const{runAndRecordMutationQa:Pn}=await import("./mutation-qa-checkpoint.js");if(xt=Pn(it,Dt,bt.planSha256).result.outcome,xt==="skipped-host-isolation-unavailable")throw new Error("private-execution-mutation-qa-host-isolation-unavailable")}const{classifyMutationQaGate:Tn}=await import("./mutation-qa-gate.js");if(Ae=Tn(it,Dt,bt.planSha256),Ae.followUpDebtRequired){const{recordMutationQaFollowUpDebt:Pn}=await import("./mutation-qa-checkpoint.js");be=Pn(it,Dt,bt.planSha256,Ae.status,xt,s)}const{resumePrivateYoloIsolatedSession:Bi}=await import("../private-execution/isolated-session.js");if((await Bi(s,Qe,oe.graphRevision)).snapshotSha!==b.session.snapshotSha)throw new Error("private-execution-mutation-qa-snapshot-drift")}catch{throw new Error("private-execution-mutation-qa-unverified")}if(Ae.blocksLocalQa||!Ae.safeToContinueLocalQa&&!be)throw new Error(`private-execution-mutation-qa-${Ae.status}`);Te={...Ae,...be?{followUpDebt:{status:"recorded",owner:be.owner,severity:be.severity,reasonCode:be.reasonCode,planSha256:be.planSha256,publicSafe:!0}}:{}}}}const It={schemaVersion:1,outcome:b.admission.outcome,sequence:b.session.sequence,snapshotSha:b.session.snapshotSha,patchSha256:b.admission.patchSha256,changedPathCount:b.admission.changedPaths.length};re={...W,isolation:It,...Te?{mutationQa:Te}:{}}}else if(Rt){const{admitPrivateEpicClaimWorkspace:L,admitPrivateIdeaDiagnosisWorkspace:b}=await import("../private-execution/isolated-admission.js"),Te=Ee?b(Rt,$e.claimId,$e.epicId,se.fingerprint,xn,o.selection.positionals.join(" ").replace(/^[-:–—]\s+/,"")):L(Rt,$e.claimId,$e.epicId,se.fingerprint,xn);re={...W,isolation:{schemaVersion:1,outcome:Te.outcome,baseSha:Te.baseSha,patchSha256:Te.patchSha256,changedPathCount:Te.changedPaths.length}}}else if(pe&&Be){const{admitPrivateIdeaResearchWorkspace:L}=await import("../private-execution/isolated-admission.js"),b=L(pe,ye.claimId,ye.epicId,ye.diagnosisReceiptId,ye.intakeRevision,ye.sourceStateSha256);re={...W,isolation:{schemaVersion:1,outcome:b.outcome,baseSha:b.baseSha,patchSha256:b.patchSha256,changedPathCount:b.changedPaths.length}}}else if(pe&&me){const{admitPrivateGenerateEpicWorkspace:L}=await import("../private-execution/isolated-admission.js"),b=L(pe,le.claimId,le.epicId,le.diagnosisReceiptId,le.researchReceiptId,le.intakeRevision,le.sourceStateSha256);re={...W,isolation:{schemaVersion:1,outcome:b.outcome,baseSha:b.baseSha,patchSha256:b.patchSha256,changedPathCount:b.changedPaths.length}}}else if(pe&&nt){const{admitPrivatePactWorkspace:L}=await import("../private-execution/isolated-admission.js"),{inspectPactToolchain:b}=await import("../private-execution/pact-toolchain.js"),{verifyPactConsumerRuntime:Te}=await import("../private-execution/pact-consumer-runtime.js"),It=z.answers.generateProvider,He=L(pe,ge.targetEpicId,ge.graphRevision,z.receipt,je,hr),Ae=b(s,It),be=Te(s,je,It);re={...W,isolation:{schemaVersion:1,outcome:He.outcome,baseSha:He.baseSha,patchSha256:He.patchSha256,changedPathCount:He.changedPaths.length,consumerBindingCandidateCount:He.consumerBindingCandidateCount,consumerScaffoldCount:He.consumerScaffoldCount,toolchain:Ae,consumerRuntime:be}}}else if(pe&&mt){const{admitPrivateUxWorkspace:L}=await import("../private-execution/isolated-admission.js"),b=L(pe,ne.targetEpicId,ne.graphRevision,Ve);re={...W,isolation:{schemaVersion:1,outcome:b.outcome,baseSha:b.baseSha,patchSha256:b.patchSha256,changedPathCount:b.changedPaths.length}}}else if(pe&&yt){const{admitPrivatePropertyTestWorkspace:L}=await import("../private-execution/isolated-admission.js"),b=L(pe,wt,qe);re={...W,isolation:{schemaVersion:1,outcome:b.outcome,baseSha:b.baseSha,patchSha256:b.patchSha256,changedPathCount:b.changedPaths.length,checkpointAccepted:!1,qaAccepted:!1,rootNextAction:"property-semantic-review-required"}}}else if(pe&&ft){const{admitPrivateArchitectureStageWorkspace:L}=await import("../private-execution/isolated-admission.js"),b=L(pe,Ce,An,an,on);re={...W,isolation:{schemaVersion:1,outcome:b.outcome,baseSha:b.baseSha,patchSha256:b.patchSha256,changedPathCount:b.changedPaths.length}}}else if(pe&&Ke){const{admitPrivateProjectStepWorkspace:L}=await import("../private-execution/isolated-admission.js"),b=L(pe,bn,ur);re={...W,isolation:{schemaVersion:1,outcome:b.outcome,baseSha:b.baseSha,patchSha256:b.patchSha256,changedPathCount:b.changedPaths.length}}}else if(pe){const{admitPrivateStateBoundStepWorkspace:L}=await import("../private-execution/isolated-admission.js"),b=L(pe,f.data.metadata.storyId);re={...W,isolation:{schemaVersion:1,outcome:b.outcome,baseSha:b.baseSha,patchSha256:b.patchSha256,changedPathCount:b.changedPaths.length}}}else re={...W}}}catch(c){const d=c instanceof Error&&/^(private-execution|private-codex)-[a-z-]+$/.test(c.message)?c.message:"private-execution-unverified";return{success:!1,error:d,errorCode:d,exitCode:1}}let Rn;if(nn&&h(f.data.metadata.planningRootContinuation)&&f.data.metadata.planningRootContinuation.planningComplete===!0)try{if(!Re?.claimId||!Re.epicId||!De)throw new Error("missing-reservation");const c=vr(s,Re.claimId,Re.epicId);if(f.data.metadata.planningRootContinuation.memoryReceiptId!==c.receiptId)throw new Error("memory-receipt-conflict");const d=Sn(s,{verifyPlanningGeneration:!0}),m=d.epics[Re.epicId];if(!h(m?.createEpicPlanningMemoryPhysical)||m.createEpicPlanningMemoryPhysical.receiptId!==c.receiptId)throw new Error("memory-recheck-failed");const A={config:{project_id:De},epics:{[Re.epicId]:m},stories:Object.fromEntries((Array.isArray(m.stories)?m.stories:[]).map(ie=>[ie,d.stories[ie]])),epic_id_ledger:d.epic_id_ledger};if(!await y.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Pi(M,H.token,{claimId:Re.claimId,projectId:De,epicId:Re.epicId,status:"materialized",planningCheckpoint:{memoryReceiptId:c.receiptId,snapshot:A}},{refreshToken:()=>H.client.forceRefresh()}),async()=>!1))throw new Error("acknowledgement-unavailable");Rn={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 rn=fn(f.data.instructions,{...f.data.metadata,...f.compatibility?{compatibility:f.compatibility}:{}}),Lt=re?.isolation,Vi=rn.metadata?.resolvedTrigger==="property-test"&&Lt!==null&&typeof Lt=="object"&&!Array.isArray(Lt)&&Lt.outcome==="admitted-unverified"&&Lt.checkpointAccepted===!1&&Lt.rootNextAction==="property-semantic-review-required";if(se&&!lr&&!nn&&f.data.metadata?.mode!=="error")try{const c=f.data.metadata?.epicClaim;if(!c||typeof c!="object"||Array.isArray(c))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const d=c;if(d.outcome!=="reserved"||typeof d.claimId!="string"||typeof d.epicId!="string")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");y.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Kr(s,se.fingerprint,d.claimId,d.epicId),()=>{})}catch{}return y.complete(Nt),{success:!0,instructions:re?re.outcome==="checkpoint-validated"?`# Checkpoint da story validado
126
+ `}const F=await A(ue,X,{requireWorkspaceEffect:!0,...e.onPrivateExecutionWorkspaceFailure===void 0?{}:{onWorkspaceEffectFailure:e.onPrivateExecutionWorkspaceFailure},...e.privateExecutionModel===void 0?{}:{model:e.privateExecutionModel},...U?{expectedExecutionBranch:oe.executionBranch}:At?{expectedExecutionBranch:At.executionBranch}:pe?{expectedExecutionBranch:pe.executionBranch}:{}});if(U){const{admitPrivateYoloIsolatedSessionStep:D}=await import("../private-execution/isolated-session.js"),x=await D(s,Qe,oe.graphRevision);let Te;if(f.data.metadata.stepId===Qi){const He=f.data.metadata.mutationQaFeature;if(!He)throw new Error("private-execution-mutation-qa-authority-unavailable");if(!He.enabled)Te={schemaVersion:1,status:"skipped-server-authority",publicSafe:!0};else{let Ae,be;try{const it=x.session.workspace.workspacePath,Dt=`sha:${x.session.workspace.baseSha}`,{planMutationQa:sn}=await import("./mutation-qa.js"),xt=sn(it,Dt);if(xt.headSha!==x.session.snapshotSha)throw new Error("private-execution-mutation-qa-snapshot-drift");let Tt="not-run";if(xt.outcome==="ready"){const{runAndRecordMutationQa:kn}=await import("./mutation-qa-checkpoint.js");if(Tt=kn(it,Dt,xt.planSha256).result.outcome,Tt==="skipped-host-isolation-unavailable")throw new Error("private-execution-mutation-qa-host-isolation-unavailable")}const{classifyMutationQaGate:Pn}=await import("./mutation-qa-gate.js");if(Ae=Pn(it,Dt,xt.planSha256),Ae.followUpDebtRequired){const{recordMutationQaFollowUpDebt:kn}=await import("./mutation-qa-checkpoint.js");be=kn(it,Dt,xt.planSha256,Ae.status,Tt,s)}const{resumePrivateYoloIsolatedSession:Ui}=await import("../private-execution/isolated-session.js");if((await Ui(s,Qe,oe.graphRevision)).snapshotSha!==x.session.snapshotSha)throw new Error("private-execution-mutation-qa-snapshot-drift")}catch{throw new Error("private-execution-mutation-qa-unverified")}if(Ae.blocksLocalQa||!Ae.safeToContinueLocalQa&&!be)throw new Error(`private-execution-mutation-qa-${Ae.status}`);Te={...Ae,...be?{followUpDebt:{status:"recorded",owner:be.owner,severity:be.severity,reasonCode:be.reasonCode,planSha256:be.planSha256,publicSafe:!0}}:{}}}}const yt={schemaVersion:1,outcome:x.admission.outcome,sequence:x.session.sequence,snapshotSha:x.session.snapshotSha,patchSha256:x.admission.patchSha256,changedPathCount:x.admission.changedPaths.length};re={...F,isolation:yt,...Te?{mutationQa:Te}:{}}}else if(At){const{admitPrivateEpicClaimWorkspace:D,admitPrivateIdeaDiagnosisWorkspace:x}=await import("../private-execution/isolated-admission.js"),Te=Ee?x(At,$e.claimId,$e.epicId,se.fingerprint,Tn,o.selection.positionals.join(" ").replace(/^[-:–—]\s+/,"")):D(At,$e.claimId,$e.epicId,se.fingerprint,Tn);re={...F,isolation:{schemaVersion:1,outcome:Te.outcome,baseSha:Te.baseSha,patchSha256:Te.patchSha256,changedPathCount:Te.changedPaths.length}}}else if(pe&&Be){const{admitPrivateIdeaResearchWorkspace:D}=await import("../private-execution/isolated-admission.js"),x=D(pe,ye.claimId,ye.epicId,ye.diagnosisReceiptId,ye.intakeRevision,ye.sourceStateSha256);re={...F,isolation:{schemaVersion:1,outcome:x.outcome,baseSha:x.baseSha,patchSha256:x.patchSha256,changedPathCount:x.changedPaths.length}}}else if(pe&&me){const{admitPrivateGenerateEpicWorkspace:D}=await import("../private-execution/isolated-admission.js"),x=D(pe,le.claimId,le.epicId,le.diagnosisReceiptId,le.researchReceiptId,le.intakeRevision,le.sourceStateSha256);re={...F,isolation:{schemaVersion:1,outcome:x.outcome,baseSha:x.baseSha,patchSha256:x.patchSha256,changedPathCount:x.changedPaths.length}}}else if(pe&&nt){const{admitPrivatePactWorkspace:D}=await import("../private-execution/isolated-admission.js"),{inspectPactToolchain:x}=await import("../private-execution/pact-toolchain.js"),{verifyPactConsumerRuntime:Te}=await import("../private-execution/pact-consumer-runtime.js"),yt=J.answers.generateProvider,He=D(pe,ge.targetEpicId,ge.graphRevision,J.receipt,je,gr),Ae=x(s,yt),be=Te(s,je,yt);re={...F,isolation:{schemaVersion:1,outcome:He.outcome,baseSha:He.baseSha,patchSha256:He.patchSha256,changedPathCount:He.changedPaths.length,consumerBindingCandidateCount:He.consumerBindingCandidateCount,consumerScaffoldCount:He.consumerScaffoldCount,toolchain:Ae,consumerRuntime:be}}}else if(pe&&ft){const{admitPrivateUxWorkspace:D}=await import("../private-execution/isolated-admission.js"),x=D(pe,ne.targetEpicId,ne.graphRevision,Ve);re={...F,isolation:{schemaVersion:1,outcome:x.outcome,baseSha:x.baseSha,patchSha256:x.patchSha256,changedPathCount:x.changedPaths.length}}}else if(pe&&mt){const{admitPrivatePropertyTestWorkspace:D}=await import("../private-execution/isolated-admission.js"),x=D(pe,_t,qe);re={...F,isolation:{schemaVersion:1,outcome:x.outcome,baseSha:x.baseSha,patchSha256:x.patchSha256,changedPathCount:x.changedPaths.length,checkpointAccepted:!1,qaAccepted:!1,rootNextAction:"property-semantic-review-required"}}}else if(pe&&gt){const{admitPrivateArchitectureStageWorkspace:D}=await import("../private-execution/isolated-admission.js"),x=D(pe,Ce,bn,on,cn);re={...F,isolation:{schemaVersion:1,outcome:x.outcome,baseSha:x.baseSha,patchSha256:x.patchSha256,changedPathCount:x.changedPaths.length}}}else if(pe&&Ke){const{admitPrivateProjectStepWorkspace:D}=await import("../private-execution/isolated-admission.js"),x=D(pe,xn,hr);re={...F,isolation:{schemaVersion:1,outcome:x.outcome,baseSha:x.baseSha,patchSha256:x.patchSha256,changedPathCount:x.changedPaths.length}}}else if(pe){const{admitPrivateStateBoundStepWorkspace:D}=await import("../private-execution/isolated-admission.js"),x=D(pe,f.data.metadata.storyId);re={...F,isolation:{schemaVersion:1,outcome:x.outcome,baseSha:x.baseSha,patchSha256:x.patchSha256,changedPathCount:x.changedPaths.length}}}else re={...F}}}catch(c){const d=c instanceof Error&&/^(private-execution|private-codex)-[a-z-]+$/.test(c.message)?c.message:"private-execution-unverified";return{success:!1,error:d,errorCode:d,exitCode:1}}let An;if(rn&&h(f.data.metadata.planningRootContinuation)&&f.data.metadata.planningRootContinuation.planningComplete===!0)try{if(!Re?.claimId||!Re.epicId||!De)throw new Error("missing-reservation");const c=Cr(s,Re.claimId,Re.epicId);if(f.data.metadata.planningRootContinuation.memoryReceiptId!==c.receiptId)throw new Error("memory-receipt-conflict");const d=vn(s,{verifyPlanningGeneration:!0}),m=d.epics[Re.epicId];if(!h(m?.createEpicPlanningMemoryPhysical)||m.createEpicPlanningMemoryPhysical.receiptId!==c.receiptId)throw new Error("memory-recheck-failed");const A={config:{project_id:De},epics:{[Re.epicId]:m},stories:Object.fromEntries((Array.isArray(m.stories)?m.stories:[]).map(ie=>[ie,d.stories[ie]])),epic_id_ledger:d.epic_id_ledger};if(!await y.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>ki(M,G.token,{claimId:Re.claimId,projectId:De,epicId:Re.epicId,status:"materialized",planningCheckpoint:{memoryReceiptId:c.receiptId,snapshot:A}},{refreshToken:()=>G.client.forceRefresh()}),async()=>!1))throw new Error("acknowledgement-unavailable");An={schemaVersion:1,acknowledged:!0,claimId:c.claimId,epicId:c.epicId,memoryReceiptId:c.receiptId,publicSafe:!0}}catch{return{success:!1,error:"planning-root-materialization-unavailable",errorCode:"planning-root-materialization-unavailable",exitCode:1}}const an=mn(f.data.instructions,{...f.data.metadata,...f.compatibility?{compatibility:f.compatibility}:{}}),Lt=re?.isolation,Bi=an.metadata?.resolvedTrigger==="property-test"&&Lt!==null&&typeof Lt=="object"&&!Array.isArray(Lt)&&Lt.outcome==="admitted-unverified"&&Lt.checkpointAccepted===!1&&Lt.rootNextAction==="property-semantic-review-required";if(se&&!ur&&!rn&&f.data.metadata?.mode!=="error")try{const c=f.data.metadata?.epicClaim;if(!c||typeof c!="object"||Array.isArray(c))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const d=c;if(d.outcome!=="reserved"||typeof d.claimId!="string"||typeof d.epicId!="string")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");y.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Qr(s,se.fingerprint,d.claimId,d.epicId),()=>{})}catch{}return y.complete(nn),{success:!0,instructions:re?re.outcome==="checkpoint-validated"?`# Checkpoint da story validado
127
127
 
128
128
  O root registrou o commit e a valida\xE7\xE3o f\xEDsica no branch do epic.`:re.outcome==="setup-accepted"?`# Setup do branch validado
129
129
 
130
130
  O root confirmou o checkpoint C01 no branch do \xE9pico. Reexecute o mesmo YOLO para avan\xE7ar \xE0 pr\xF3xima etapa.`:re.outcome==="report-stored"?`# Relat\xF3rio privado salvo
131
131
 
132
- Consulte o caminho local em metadata.privateExecutionReceipt.report.path. Nenhum agente foi executado ou projeto alterado.`:Vi?"# Property-test: candidato admitido, QA pendente\n\nO root deve inspecionar os arquivos locais, executar `neocortex-client property-qa review-plan --project-root . --format json` e comparar cada invariante do PRD com a implementa\xE7\xE3o e sua asser\xE7\xE3o. Somente uma revis\xE3o root independente, registrada fora do projeto e enviada por stdin a `property-qa review-accept --authorize-review`, pode autorizar o aceite; esse comando repete a execu\xE7\xE3o positiva e a falha causal no sandbox. Consulte `property-qa review-status` para revalidar o recibo. Se o toolchain ou a evid\xEAncia n\xE3o forem suportados, pare sem declarar QA aprovado. O agente privado n\xE3o recebe autoridade de revis\xE3o, Git ou checkpoint.":`# Execu\xE7\xE3o privada conclu\xEDda; valida\xE7\xE3o f\xEDsica pendente
132
+ Consulte o caminho local em metadata.privateExecutionReceipt.report.path. Nenhum agente foi executado ou projeto alterado.`:Bi?"# Property-test: candidato admitido, QA pendente\n\nO root deve inspecionar os arquivos locais, executar `neocortex-client property-qa review-plan --project-root . --format json` e comparar cada invariante do PRD com a implementa\xE7\xE3o e sua asser\xE7\xE3o. Somente uma revis\xE3o root independente, registrada fora do projeto e enviada por stdin a `property-qa review-accept --authorize-review`, pode autorizar o aceite; esse comando repete a execu\xE7\xE3o positiva e a falha causal no sandbox. Consulte `property-qa review-status` para revalidar o recibo. Se o toolchain ou a evid\xEAncia n\xE3o forem suportados, pare sem declarar QA aprovado. O agente privado n\xE3o recebe autoridade de revis\xE3o, Git ou checkpoint.":`# Execu\xE7\xE3o privada conclu\xEDda; valida\xE7\xE3o f\xEDsica pendente
133
133
 
134
- O executor Codex retornou sem erro. Nenhum checkpoint ou aprova\xE7\xE3o da story foi emitido.`:rn.instructions,metadata:re?{...rn.metadata,privateExecutionReceipt:re}:{...rn.metadata,...Rn?{planningMaterialization:Rn}:{}},exitCode:0}}function os(e){const[t]=e.trim().split(/\s+/,1);return t?/^@?epic-[a-z0-9][a-z0-9._-]*$/i.test(t)?"epic":ln(t):null}const Di="Provide exactly one invoke input source: --args <string>, --stdin, or --args-file <path>.",cs=`
134
+ O executor Codex retornou sem erro. Nenhum checkpoint ou aprova\xE7\xE3o da story foi emitido.`:an.instructions,metadata:re?{...an.metadata,privateExecutionReceipt:re}:{...an.metadata,...An?{planningMaterialization:An}:{}},exitCode:0}}function ss(e){const[t]=e.trim().split(/\s+/,1);return t?/^@?epic-[a-z0-9][a-z0-9._-]*$/i.test(t)?"epic":un(t):null}const Mi="Provide exactly one invoke input source: --args <string>, --stdin, or --args-file <path>.",ds=`
135
135
  neocortex-client invoke - Send orchestration request to server
136
136
 
137
137
  Usage:
@@ -202,12 +202,12 @@ Safety:
202
202
  Jobs console is Plane B/local-only: no hosted server call for raw output, no server-held stream, no raw persistence, and stdin requires explicit local confirmation.
203
203
  Jobs, goal and loop watch use serverHeldStream=false and foreground local SQLite polling of public processing summaries only.
204
204
  Unresolved targets disable polling with public reason codes; there is no all-jobs fallback.
205
- `.trim();function ss(e){return e.includes("--help")||e.includes("-h")||e.includes("help")}function Le(e,t,i,r){return new mn("INVOCATION_MALFORMED_INPUT",t,e,i,r)}function kt(e){return Le("missing-input-value",`${e} requires a value. ${Di}`)}function ds(e){try{if(!Wi(e).isFile())throw Le("missing-input-value","--args-file must point to a readable UTF-8 text file.","args-file");return We(e)}catch(t){throw t instanceof mn?t:Le("missing-input-value","--args-file could not be read as UTF-8 text. Check the path and permissions.","args-file")}}function ps(){try{if(process.stdin.isTTY)throw Le("missing-input-value","--stdin requires piped UTF-8 text, for example: neocortex-client invoke --stdin < synthetic.story.md","stdin");return We(0)}catch(e){throw e instanceof mn?e:Le("missing-input-value","--stdin could not be read as UTF-8 text. Pipe command text into stdin and retry.","stdin")}}function ls(e,t={}){let i,r=!1,a,n,o="plain",p=!1,s,l,I=!1,S=!1,u;for(let T=0;T<e.length;T++){const P=e[T];switch(P){case"--args":{const C=e[++T];if(C===void 0)throw kt("--args");if(i!==void 0)throw Le("multiple-input-sources","Provide --args only once. Use one explicit invoke input source.","args");i=C;break}case"--stdin":if(r)throw Le("multiple-input-sources","Provide --stdin only once. Use one explicit invoke input source.","stdin");r=!0;break;case"--args-file":{const C=e[++T];if(C===void 0)throw kt("--args-file");if(a!==void 0)throw Le("multiple-input-sources","Provide --args-file only once. Use one explicit invoke input source.","args-file");a=C;break}case"--project-root":{const C=e[++T];if(C===void 0)throw kt("--project-root");n=C;break}case"--format":{const C=e[++T];if(C===void 0)throw kt("--format");if(C!=="json"&&C!=="plain")throw Le("unexpected-cli-token","--format accepts only json or plain.");o=C;break}case"--watch":p=!0;break;case"--server-url":{const C=e[++T];if(C===void 0)throw kt("--server-url");s=C;break}case"--platform-target":{const C=e[++T];if(C===void 0)throw kt("--platform-target");l=C;break}case"--strict-read-only":I=!0;break;case"--private-execution-beta":S=!0;break;case"--private-execution-model":{const C=e[++T];if(C===void 0)throw kt("--private-execution-model");if(u!==void 0||!/^gpt-[a-z0-9][a-z0-9.-]{0,63}$/.test(C))throw Le("unexpected-cli-token","Invalid or duplicate private execution model.");u=C;break}default:if(i!==void 0&&P&&(!P.startsWith("-")||P==="-")){i+=` ${P}`;break}throw Le("unexpected-cli-token","Unexpected top-level CLI token. Quote the complete --args payload or use --stdin/--args-file for multiline content.")}}if(u!==void 0&&(!S||I))throw Le("unexpected-cli-token","A private execution model requires private beta without strict read-only.");const _=[i!==void 0?"args":void 0,r?"stdin":void 0,a!==void 0?"args-file":void 0].filter(T=>T!==void 0);if(_.length===0)throw Le("missing-input-value",Di);if(_.length>1)throw Le("multiple-input-sources",`Choose only one invoke input source; received ${_.join(", ")}.`);const E=_[0],g=E==="args"?i:E==="stdin"?(t.readStdin??ps)():(t.readArgsFile??ds)(a);let y;try{y=Qt(E,g)}catch(T){throw T instanceof Ba?Le("invalid-utf8",T.message,E):T}const x=E==="args"?Uc(y.rawArgs):Ne(y.rawArgs),D=x.args===y.rawArgs?y:Qt(E,x.args);return{args:x.args,inputSource:E,inputEnvelope:D,projectRoot:n,format:o,watch:p||x.watch,commandLevelWatch:x.metadata,serverUrl:s,platformTarget:l,strictReadOnly:I,privateExecutionBeta:S,...u===void 0?{}:{privateExecutionModel:u}}}function Mi(e,t){return t?.active?{...e??{},commandLevelWatch:t,serverHeldStream:!1}:e}function ji(e,t,i=process.stdout,r=process.stderr){if(t.format==="json"){const o=fn(e.instructions,e.metadata),p=Mi(o.metadata,t.commandLevelWatch);if(t.watch){i.write(JSON.stringify({type:"invoke_result",instructions:o.instructions,metadata:p,publicSafe:!0})+`
205
+ `.trim();function ps(e){return e.includes("--help")||e.includes("-h")||e.includes("help")}function Le(e,t,i,r){return new yn("INVOCATION_MALFORMED_INPUT",t,e,i,r)}function Ot(e){return Le("missing-input-value",`${e} requires a value. ${Mi}`)}function ls(e){try{if(!Fi(e).isFile())throw Le("missing-input-value","--args-file must point to a readable UTF-8 text file.","args-file");return We(e)}catch(t){throw t instanceof yn?t:Le("missing-input-value","--args-file could not be read as UTF-8 text. Check the path and permissions.","args-file")}}function us(){try{if(process.stdin.isTTY)throw Le("missing-input-value","--stdin requires piped UTF-8 text, for example: neocortex-client invoke --stdin < synthetic.story.md","stdin");return We(0)}catch(e){throw e instanceof yn?e:Le("missing-input-value","--stdin could not be read as UTF-8 text. Pipe command text into stdin and retry.","stdin")}}function hs(e,t={}){let i,r=!1,a,n,o="plain",p=!1,s,l,I=!1,S=!1,u;for(let T=0;T<e.length;T++){const P=e[T];switch(P){case"--args":{const C=e[++T];if(C===void 0)throw Ot("--args");if(i!==void 0)throw Le("multiple-input-sources","Provide --args only once. Use one explicit invoke input source.","args");i=C;break}case"--stdin":if(r)throw Le("multiple-input-sources","Provide --stdin only once. Use one explicit invoke input source.","stdin");r=!0;break;case"--args-file":{const C=e[++T];if(C===void 0)throw Ot("--args-file");if(a!==void 0)throw Le("multiple-input-sources","Provide --args-file only once. Use one explicit invoke input source.","args-file");a=C;break}case"--project-root":{const C=e[++T];if(C===void 0)throw Ot("--project-root");n=C;break}case"--format":{const C=e[++T];if(C===void 0)throw Ot("--format");if(C!=="json"&&C!=="plain")throw Le("unexpected-cli-token","--format accepts only json or plain.");o=C;break}case"--watch":p=!0;break;case"--server-url":{const C=e[++T];if(C===void 0)throw Ot("--server-url");s=C;break}case"--platform-target":{const C=e[++T];if(C===void 0)throw Ot("--platform-target");l=C;break}case"--strict-read-only":I=!0;break;case"--private-execution-beta":S=!0;break;case"--private-execution-model":{const C=e[++T];if(C===void 0)throw Ot("--private-execution-model");if(u!==void 0||!/^gpt-[a-z0-9][a-z0-9.-]{0,63}$/.test(C))throw Le("unexpected-cli-token","Invalid or duplicate private execution model.");u=C;break}default:if(i!==void 0&&P&&(!P.startsWith("-")||P==="-")){i+=` ${P}`;break}throw Le("unexpected-cli-token","Unexpected top-level CLI token. Quote the complete --args payload or use --stdin/--args-file for multiline content.")}}if(u!==void 0&&(!S||I))throw Le("unexpected-cli-token","A private execution model requires private beta without strict read-only.");const _=[i!==void 0?"args":void 0,r?"stdin":void 0,a!==void 0?"args-file":void 0].filter(T=>T!==void 0);if(_.length===0)throw Le("missing-input-value",Mi);if(_.length>1)throw Le("multiple-input-sources",`Choose only one invoke input source; received ${_.join(", ")}.`);const E=_[0],g=E==="args"?i:E==="stdin"?(t.readStdin??us)():(t.readArgsFile??ls)(a);let y;try{y=Kt(E,g)}catch(T){throw T instanceof $a?Le("invalid-utf8",T.message,E):T}const b=E==="args"?Hc(y.rawArgs):Ne(y.rawArgs),L=b.args===y.rawArgs?y:Kt(E,b.args);return{args:b.args,inputSource:E,inputEnvelope:L,projectRoot:n,format:o,watch:p||b.watch,commandLevelWatch:b.metadata,serverUrl:s,platformTarget:l,strictReadOnly:I,privateExecutionBeta:S,...u===void 0?{}:{privateExecutionModel:u}}}function ji(e,t){return t?.active?{...e??{},commandLevelWatch:t,serverHeldStream:!1}:e}function Vi(e,t,i=process.stdout,r=process.stderr){if(t.format==="json"){const o=mn(e.instructions,e.metadata),p=ji(o.metadata,t.commandLevelWatch);if(t.watch){i.write(JSON.stringify({type:"invoke_result",instructions:o.instructions,metadata:p,publicSafe:!0})+`
206
206
  `);return}i.write(JSON.stringify({instructions:o.instructions,metadata:p})+`
207
- `);return}const a=fn(e.instructions,e.metadata),n=Mi(a.metadata,t.commandLevelWatch);i.write(a.instructions+`
207
+ `);return}const a=mn(e.instructions,e.metadata),n=ji(a.metadata,t.commandLevelWatch);i.write(a.instructions+`
208
208
  `),n&&r.write(JSON.stringify(n)+`
209
- `)}async function Ed(e=process.stdout,t=process.stderr){const i=a=>new Promise(n=>{let o=!1;const p=I=>{o||(o=!0,clearTimeout(l),setImmediate(()=>a.removeListener("error",s)),n(I))},s=()=>p(!1),l=setTimeout(()=>p(!1),1e4);a.once("error",s);try{a.write("",I=>p(!I))}catch{p(!1)}});return(await Promise.all([i(e),i(t)])).every(Boolean)}function us(e){const t=()=>e.abort();return process.once("SIGINT",t),process.once("SIGTERM",t),()=>{process.removeListener("SIGINT",t),process.removeListener("SIGTERM",t)}}async function Sd(e){if(ss(e))return process.stdout.write(`${cs}
210
- `),0;let t;try{t=ls(e)}catch(r){if(r instanceof mn)return process.stderr.write(JSON.stringify({error_code:r.code,reason:r.reason,source:r.source,byte_length:r.byteLength,message:r.message,remediation:r.message})+`
211
- `),1;throw r}if(Sa(t.args))return t.strictReadOnly?(process.stderr.write(JSON.stringify({error_code:"readonly-registry-denied",message:"Strict read-only policy is not eligible for the local jobs console."})+`
212
- `),1):(await va({args:t.args,projectRoot:Hn(t.projectRoot),format:t.format,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})).exitCode;const i=await as({args:t.args,inputSource:t.inputSource,inputEnvelope:t.inputEnvelope,watch:t.watch,projectRoot:t.projectRoot,format:t.format,serverUrl:t.serverUrl,platformTarget:t.platformTarget,strictReadOnly:t.strictReadOnly,privateExecutionBeta:t.privateExecutionBeta,...t.privateExecutionModel===void 0?{}:{privateExecutionModel:t.privateExecutionModel}});if(!i.success&&i.errorCode==="YOLOOP_RELEASE_BLOCKED"&&i.instructions&&i.metadata)return ji(i,t),i.exitCode;if(!i.success){const r=i.metadata?.invocationInput,a=Po(i.metadata?.yoloChangeEvidence),n=r&&typeof r=="object"&&!Array.isArray(r)?r:void 0;return process.stderr.write(JSON.stringify({error_code:i.errorCode??(i.exitCode===2?"NOT_CONFIGURED":"INVOKE_ERROR"),message:ze(i.error??"",Pt),...typeof n?.reason=="string"?{reason:ze(n.reason,80)}:{},...typeof n?.source=="string"?{source:ze(n.source,20)}:{},...Number.isSafeInteger(n?.byteLength)?{byte_length:n.byteLength}:{},...typeof n?.remediation=="string"?{remediation:ze(n.remediation,Pt)}:{},...a?{yolo_change_evidence:a}:{}})+`
213
- `),i.exitCode}if(ji(i,t),t.watch){const r=new AbortController,a=us(r);try{const n=Qc(i.metadata,t.args);n.disabled?xc(n.reasonCodes??[_e.TARGET_UNRESOLVED],t.args,t.format,process.stdout,t.privateExecutionBeta):await Tc({projectRoot:Hn(t.projectRoot),format:t.format,strictReadOnly:t.strictReadOnly,protectedOutput:t.privateExecutionBeta,...n,signal:r.signal})}finally{a()}}return 0}export{cs as INVOKE_HELP_TEXT,Fr as INVOKE_PAYLOAD_LIMIT_BYTES,Un as INVOKE_PAYLOAD_WARNING_THRESHOLD_BYTES,mn as InvokeCliInputError,Fn as InvokePayloadTooLargeError,Yn as InvokeStructuralContextTooLargeError,st as StateSnapshotIntegrityError,yd as __resetSchemaDriftWarnedForTests,es as acknowledgeMaterializedPendingEpicClaims,Qr as admitClientInvocation,Jn as assertEpicAwareStateShapeBeforeRepair,Qo as boundedP222PremergeCheckpointPositions,Wn as buildInvokeCompatibilityOffer,cc as buildSignedInvokeAttempt,So as clearPendingEpicIdempotencyKey,Xo as collectInvokeP205Authorities,Sn as collectStateSnapshot,Ht as computeInvokeRequestBodySizeBytes,Id as createFullStateSnapshotScope,Zn as createInvokePayloadTelemetry,vo as deriveYoloLogicalIdempotencyKey,Do as detectStateSchemaDrift,os as extractPreFlightTrigger,Ed as flushInvokeCliOutput,Eo as getOrCreatePendingEpicIdempotencyKey,er as guardInvokeRequestBodySize,as as invoke,Sd as invokeCliHandler,pi as isEpicAwareCommandId,mc as maybeEmitInvokePayloadSizeWarning,yc as maybeRunInvokeRunnerAutoBootstrap,ls as parseInvokeCliOptions,Ii as postMaterializationJson,_o as projectRegistryDriftInvokeFailure,wo as projectReleaseBlockedInvokeResult,Po as projectYoloChangeEvidenceCliDiagnostic,is as reconcileInvalidatedYoloopSession,Kr as recordPendingEpicReservation,Ro as recoverClientInvocation,Uc as resolveInvokeCommandLevelWatch,Hn as resolveInvokeProjectRoot,ic as resolveInvokeTransportErrorCode,Qc as resolveInvokeWatchTarget,fn as sanitizeInvokeCliOutput,Pi as sendEpicClaimAcknowledgement,sr as sendInvokeRequest,Zc as sendPrivateExecutionCancelRequest,Xc as sendPrivateExecutionConsumeRequest,ko as shouldCollectProjectEvidenceForInvoke,Tc as watchContinuityProcessingSummaries,ji as writeInvokeCliSuccessOutput};
209
+ `)}async function Cd(e=process.stdout,t=process.stderr){const i=a=>new Promise(n=>{let o=!1;const p=I=>{o||(o=!0,clearTimeout(l),setImmediate(()=>a.removeListener("error",s)),n(I))},s=()=>p(!1),l=setTimeout(()=>p(!1),1e4);a.once("error",s);try{a.write("",I=>p(!I))}catch{p(!1)}});return(await Promise.all([i(e),i(t)])).every(Boolean)}function gs(e){const t=()=>e.abort();return process.once("SIGINT",t),process.once("SIGTERM",t),()=>{process.removeListener("SIGINT",t),process.removeListener("SIGTERM",t)}}async function _d(e){if(ps(e))return process.stdout.write(`${ds}
210
+ `),0;let t;try{t=hs(e)}catch(r){if(r instanceof yn)return process.stderr.write(JSON.stringify({error_code:r.code,reason:r.reason,source:r.source,byte_length:r.byteLength,message:r.message,remediation:r.message})+`
211
+ `),1;throw r}if(Ca(t.args))return t.strictReadOnly?(process.stderr.write(JSON.stringify({error_code:"readonly-registry-denied",message:"Strict read-only policy is not eligible for the local jobs console."})+`
212
+ `),1):(await _a({args:t.args,projectRoot:Gn(t.projectRoot),format:t.format,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})).exitCode;const i=await cs({args:t.args,inputSource:t.inputSource,inputEnvelope:t.inputEnvelope,watch:t.watch,projectRoot:t.projectRoot,format:t.format,serverUrl:t.serverUrl,platformTarget:t.platformTarget,strictReadOnly:t.strictReadOnly,privateExecutionBeta:t.privateExecutionBeta,...t.privateExecutionModel===void 0?{}:{privateExecutionModel:t.privateExecutionModel}});if(!i.success&&i.errorCode==="YOLOOP_RELEASE_BLOCKED"&&i.instructions&&i.metadata)return Vi(i,t),i.exitCode;if(!i.success){const r=i.metadata?.invocationInput,a=Oo(i.metadata?.yoloChangeEvidence),n=r&&typeof r=="object"&&!Array.isArray(r)?r:void 0;return process.stderr.write(JSON.stringify({error_code:i.errorCode??(i.exitCode===2?"NOT_CONFIGURED":"INVOKE_ERROR"),message:ze(i.error??"",kt),...typeof n?.reason=="string"?{reason:ze(n.reason,80)}:{},...typeof n?.source=="string"?{source:ze(n.source,20)}:{},...Number.isSafeInteger(n?.byteLength)?{byte_length:n.byteLength}:{},...typeof n?.remediation=="string"?{remediation:ze(n.remediation,kt)}:{},...a?{yolo_change_evidence:a}:{}})+`
213
+ `),i.exitCode}if(Vi(i,t),t.watch){const r=new AbortController,a=gs(r);try{const n=Zc(i.metadata,t.args);n.disabled?Pc(n.reasonCodes??[_e.TARGET_UNRESOLVED],t.args,t.format,process.stdout,t.privateExecutionBeta):await kc({projectRoot:Gn(t.projectRoot),format:t.format,strictReadOnly:t.strictReadOnly,protectedOutput:t.privateExecutionBeta,...n,signal:r.signal})}finally{a()}}return 0}export{ds as INVOKE_HELP_TEXT,Yr as INVOKE_PAYLOAD_LIMIT_BYTES,$n as INVOKE_PAYLOAD_WARNING_THRESHOLD_BYTES,yn as InvokeCliInputError,Yn as InvokePayloadTooLargeError,qn as InvokeStructuralContextTooLargeError,st as StateSnapshotIntegrityError,Sd as __resetSchemaDriftWarnedForTests,ns as acknowledgeMaterializedPendingEpicClaims,Xr as admitClientInvocation,Kn as assertEpicAwareStateShapeBeforeRepair,Zo as boundedP222PremergeCheckpointPositions,Fn as buildInvokeCompatibilityOffer,dc as buildSignedInvokeAttempt,Co as clearPendingEpicIdempotencyKey,ec as collectInvokeP205Authorities,vn as collectStateSnapshot,Ht as computeInvokeRequestBodySizeBytes,vd as createFullStateSnapshotScope,er as createInvokePayloadTelemetry,_o as deriveYoloLogicalIdempotencyKey,jo as detectStateSchemaDrift,ss as extractPreFlightTrigger,Cd as flushInvokeCliOutput,vo as getOrCreatePendingEpicIdempotencyKey,tr as guardInvokeRequestBodySize,cs as invoke,_d as invokeCliHandler,li as isEpicAwareCommandId,Ic as maybeEmitInvokePayloadSizeWarning,Ec as maybeRunInvokeRunnerAutoBootstrap,hs as parseInvokeCliOptions,Ei as postMaterializationJson,Ro as projectRegistryDriftInvokeFailure,Ao as projectReleaseBlockedInvokeResult,Oo as projectYoloChangeEvidenceCliDiagnostic,os as reconcileInvalidatedYoloopSession,Qr as recordPendingEpicReservation,bo as recoverClientInvocation,Hc as resolveInvokeCommandLevelWatch,Gn as resolveInvokeProjectRoot,oc as resolveInvokeTransportErrorCode,Zc as resolveInvokeWatchTarget,mn as sanitizeInvokeCliOutput,ki as sendEpicClaimAcknowledgement,dr as sendInvokeRequest,ts as sendPrivateExecutionCancelRequest,es as sendPrivateExecutionConsumeRequest,No as shouldCollectProjectEvidenceForInvoke,kc as watchContinuityProcessingSummaries,Vi as writeInvokeCliSuccessOutput};