@ornexus/neocortex 4.60.74 → 4.60.75
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.
- package/dist/release-source.json +1 -1
- package/install.ps1 +1 -1
- package/install.sh +1 -1
- package/package.json +2 -2
- package/packages/client/dist/cache/encrypted-cache.d.ts +27 -0
- package/packages/client/dist/cache/encrypted-cache.js +1 -1
- package/packages/client/dist/commands/invoke.d.ts +38 -1
- package/packages/client/dist/commands/invoke.js +79 -79
- package/packages/client/dist/config/host-auth-broker.d.ts +31 -0
- package/packages/client/dist/config/host-auth-broker.js +1 -0
- package/packages/client/dist/config/host-auth-reference.d.ts +32 -0
- package/packages/client/dist/config/host-auth-reference.js +1 -0
- package/packages/client/dist/config/secure-config.js +1 -1
- package/packages/client/dist/continuity/native-agent-types.d.ts +11 -0
- package/packages/client/dist/continuity/native-agent-types.js +1 -1
- package/packages/client/dist/errors/error-messages.d.ts +3 -0
- package/packages/client/dist/errors/error-messages.js +2 -2
- package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +11 -1
- package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -4
- package/packages/client/dist/index.d.ts +2 -0
- package/packages/client/dist/index.js +1 -1
- package/packages/client/dist/license/host-auth-recovery.d.ts +158 -0
- package/packages/client/dist/license/host-auth-recovery.js +1 -0
- package/packages/client/dist/license/license-client.d.ts +10 -1
- package/packages/client/dist/license/license-client.js +1 -1
- package/packages/client/dist/runner/epic-background-dispatcher.d.ts +61 -0
- package/packages/client/dist/runner/epic-background-dispatcher.js +1 -0
- package/packages/client/dist/runner/headless/background-root.d.ts +65 -0
- package/packages/client/dist/runner/headless/background-root.js +1 -0
- package/packages/client/dist/runner/headless/epic-terminal-git-runner.d.ts +9 -0
- package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +2 -2
- package/packages/client/dist/runner/headless/managed-environment-cleanup.d.ts +95 -0
- package/packages/client/dist/runner/headless/managed-environment-cleanup.js +1 -0
- package/packages/client/dist/state/project-state-snapshot.d.ts +7 -0
- package/packages/client/dist/state/project-state-snapshot.js +1 -1
- package/packages/client/dist/yolo/change-evidence-collector.d.ts +21 -1
- package/packages/client/dist/yolo/change-evidence-collector.js +1 -1
- package/packages/shared/dist/invocation/explicit-intent-recovery.d.ts +83 -0
- package/packages/shared/dist/invocation/explicit-intent-recovery.js +187 -0
- package/packages/shared/dist/invocation/index.d.ts +7 -0
- package/packages/shared/dist/invocation/index.js +22 -0
- package/targets-stubs/antigravity/gemini.md +1 -1
- package/targets-stubs/antigravity/skill/SKILL.md +1 -1
- package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex-root.md +2 -2
- package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex.md +2 -2
- package/targets-stubs/codex/AGENTS.md +24 -21
- package/targets-stubs/codex/README.md +6 -1
- package/targets-stubs/codex/neocortex.toml +7 -2
- package/targets-stubs/cursor/agent.md +2 -2
- package/targets-stubs/gemini-cli/agent.md +2 -2
- package/targets-stubs/opencode/neocortex-root.md +16 -1
- package/targets-stubs/opencode/neocortex.md +6 -0
- package/targets-stubs/vscode/neocortex.agent.md +2 -2
|
@@ -1,59 +1,59 @@
|
|
|
1
|
-
import{classifyNonUiArchitectureTransition as
|
|
2
|
-
`,{encoding:"utf8",mode:384,flag:"wx"}),
|
|
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(`
|
|
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 Ys(){Hn=!1}function Gr(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Eo(e){return e==="active"||e==="archived"||e==="rolled-back"||e==="synthetic"||e==="orphan"?e:void 0}const So=new Set(["goal","problem","desiredOutcome","rawIntent","context","users","surfaces","constraints","assumptions","risks","nonGoals","validationExpectations","debtRefs","repositoryEvidencePaths","journeyIds","screenIds","storybookStoryIds","backendContractIds","featureBlockerIds","remediationRefs","uiScope","remediationStory","examples","contracts"]),vo=/(?:[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}|(?:token|api[_-]?key|secret|password|credential|license[_-]?key)\s*[:=]\s*\S+|https?:\/\/(?:localhost|127\.0\.0\.1|10\.\d+\.\d+\.\d+|192\.168\.\d+\.\d+|172\.(?:1[6-9]|2\d|3[0-1])\.\d+\.\d+|[^\s/]*internal[^\s/]*)\S*|private\s+prompt|raw\s+vendor\s+corpus|sk-[A-Za-z0-9_-]{12,})/i;function Co(e,t){if(!(!h(e)||e.schemaVersion!==1||e.epicId!==t||!/^P\d+$/.test(t)))try{const r=JSON.stringify(e);if(Buffer.byteLength(r)>16384||vo.test(r))return;const i=(n,o)=>{if(Object.keys(n).some(s=>!o.includes(s)))throw new Error("planning-unknown-field")};if(i(e,["schemaVersion","epicId","intake","intakeRevision","diagnosisReceipt","researchReceipt","degradeAuthorization"]),!h(e.intake)||Object.keys(e.intake).some(n=>!So.has(n)))return;for(const[n,o]of Object.entries(e.intake))if(["examples","contracts"].includes(n)){const s=n==="examples"?["id","title","actor","given","when","then","source","coveredRequirement","expectedValidation"]:["id","kind","description","path"];if(!Array.isArray(o)||o.length>16)return;for(const l of o)if(!h(l)||(i(l,s),Object.values(l).some(f=>typeof f!="string"||f.length>256)))return}else if(Array.isArray(o)){if(o.length>32||o.some(s=>typeof s!="string"||s.length>256))return}else if(typeof o=="string"){if(o.length>(n==="rawIntent"?Bi:512))return}else if(typeof o!="boolean"||!["uiScope","remediationStory"].includes(n))return;const a=["schemaVersion","kind","epicId","intakeRevision","artifactSummary","artifactDigest","predecessorReceiptId","accepted","receiptId"];for(const n of[e.diagnosisReceipt,e.researchReceipt])if(n!==void 0&&(!h(n)||(i(n,a),Object.values(n).some(o=>typeof o=="string"&&o.length>1024))))return;if(e.degradeAuthorization!==void 0){if(!h(e.degradeAuthorization))return;i(e.degradeAuthorization,["approved","intakeRevision","reasonCodes","assumptionCodes"]);for(const n of["reasonCodes","assumptionCodes"]){const o=e.degradeAuthorization[n];if(!Array.isArray(o)||o.length>32||o.some(s=>typeof s!="string"||s.length>128))return}}return JSON.parse(r)}catch{return}}function Wr(e){return e==="create-epic"||e==="discovered"?e:void 0}function Ee(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function wo(e){const t={};let r=!1;for(const i of["contracts","contract_refs","shared_surfaces","adr_refs","nfr_refs","acceptance_depends_on"]){if(e[i]===void 0)continue;const a=e[i];if(!Array.isArray(a)||a.length>128||a.some(n=>sn(n)===void 0)){r=!0;continue}t[i]=a.map(n=>sn(n))}if(e.planning!==void 0)try{if(!h(e.planning))throw new Error("planning-shape");const i=e.planning;for(const o of["claims","semanticArtifacts"]){if(i[o]===void 0)continue;const s=i[o];if(!Array.isArray(s)||s.length>128||s.some(l=>!h(l)||sn(l.ref)===void 0))throw new Error("planning-refs")}if(i.attempts!==void 0&&(!Array.isArray(i.attempts)||i.attempts.length>32))throw new Error("planning-attempts");for(const o of i.attempts??[]){if(!h(o)||!Array.isArray(o.reasonCodes)||o.reasonCodes.length>32||o.reasonCodes.some(s=>typeof s!="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(s)))throw new Error("planning-attempt-reasons");if(o.discoveredClaims!==void 0&&(!Array.isArray(o.discoveredClaims)||o.discoveredClaims.length>128||o.discoveredClaims.some(s=>!h(s)||sn(s.ref)===void 0)))throw new Error("planning-attempt-claims")}const{graphRevision:a,...n}=Oa(i);t.planning=n}catch{r=!0}return r&&(t.planning={schemaVersion:1,dependencyBasis:"unknown",claims:[],semanticArtifacts:[]}),t}function h(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Et(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function ee(e){if(typeof e!="string")return;const t=e.trim();if(t)return t.replace(/[^a-z0-9_.:-]+/gi,"_").slice(0,120)}function J(e){if(typeof e!="string")return;const t=e.trim(),r=ee(e);return r===t?r:void 0}function Se(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240)&&/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(t)&&!(t.includes("..")||t.includes("//")||t.includes("@{")||t.endsWith("/")||t.endsWith("."))&&!t.split("/").some(r=>!r||r.startsWith(".")||r.endsWith(".lock")))return t}function _(e){return typeof e=="string"&&/^[0-9a-f]{7,64}$/i.test(e)?e:void 0}function Te(e){if(!(typeof e!="string"||e.length>64)&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/.test(e))return Number.isFinite(Date.parse(e))?e:void 0}function at(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240||t.includes("..")))return/^[A-Za-z0-9._:/#\-[\]]+$/.test(t)?t:void 0}function hn(e){if(!h(e))return;const t=u=>typeof u=="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,95}$/.test(u),r=u=>typeof u=="string"&&/^[a-f0-9]{64}$/.test(u),i=(u,v)=>Array.isArray(u)&&u.length<=v&&u.every(t)&&new Set(u).size===u.length?u:void 0,a=(u,v)=>{if(!(!h(u)||u.schemaVersion!==2||!t(u.requestId)||!t(u.stageCommand)||!r(u.requestHash)||!r(u.inputHash)||!r(u.stateHash)||!r(u.nonce)||!r(u.stageRevision)||!r(u.stageHash)||!r(u.catalogHash)||u.targetEpicId!==void 0&&!t(u.targetEpicId)||v&&(!r(u.outputHash)||!r(u.artifactHash))))return{schemaVersion:2,...u.targetEpicId?{targetEpicId:u.targetEpicId}:{},requestId:u.requestId,requestHash:u.requestHash,inputHash:u.inputHash,stateHash:u.stateHash,nonce:u.nonce,stageCommand:u.stageCommand,stageRevision:u.stageRevision,stageHash:u.stageHash,catalogHash:u.catalogHash,...v?{outputHash:u.outputHash,artifactHash:u.artifactHash}:{}}},n=(u,v)=>{if(!(!h(u)||u.schemaVersion!=="1.1"||u.kind!==v||!r(u.receiptId)||!r(u.graphHash)||!r(u.evidenceHash)||!t(u.elementId)||!t(u.caseId)||!t(u.category)))return{schemaVersion:"1.1",kind:v,receiptId:u.receiptId,graphHash:u.graphHash,elementId:u.elementId,caseId:u.caseId,category:u.category,evidenceHash:u.evidenceHash}},o=(u,v)=>{if(!h(u)||u.kind!==v||!r(u.receiptId)||!i(u.evidenceIds,24)||v==="architecture-stage-completion"&&!["succeeded","failed"].includes(String(u.status))||v==="architecture-stage-validation"&&!["passed","failed","pending"].includes(String(u.status)))return;const I=a(u,!0);if(!I)return;const p=v==="architecture-stage-validation"?n(u.isolated,"isolated"):void 0,C=v==="architecture-stage-validation"?n(u.regression,"regression"):void 0;if(!(v==="architecture-stage-validation"&&(!p||!C)))return{...I,kind:v,receiptId:u.receiptId,status:u.status,evidenceIds:u.evidenceIds,...p&&C?{isolated:p,regression:C}:{}}},s={};e.schemaVersion===1&&(s.schemaVersion=1),e.owner==="root"&&(s.owner="root"),t(e.currentStageCommand)&&(s.currentStageCommand=e.currentStageCommand),["ask-user","delegate","resume","advance","blocked","complete"].includes(String(e.continuationState))&&(s.continuationState=e.continuationState);const l=i(e.questionIds,16);if(l&&(s.questionIds=l),(e.childStatus==="succeeded"||e.childStatus==="failed")&&(s.childStatus=e.childStatus),(e.evidencePolicy==="legacy-compatible"||e.evidencePolicy==="v2-required")&&(s.evidencePolicy=e.evidencePolicy),t(e.targetEpicId)&&(s.targetEpicId=e.targetEpicId),r(e.graphRevision)&&(s.graphRevision=e.graphRevision),e.graphSource==="committed-epic-v1"&&(s.graphSource=e.graphSource),e.nonUiScopeReceipt!==void 0){const u=cr(e.nonUiScopeReceipt);if(!u||u.targetEpicId!==e.targetEpicId||u.graphRevision!==e.graphRevision||!h(e.accounting)||u.accountingId!==e.accounting.accountingId||!h(e.evidenceExpectation)||u.rootInputSha256!==e.evidenceExpectation.inputHash)throw new Error("architecture-non-ui-scope-invalid");s.nonUiScopeReceipt=u}h(e.pactAnswerReceipt)&&Object.keys(e.pactAnswerReceipt).sort().join(",")===["schemaVersion","targetEpicId","graphRevision","stateSha256","answersSha256","questionIds","publicSafe"].sort().join(",")&&e.pactAnswerReceipt.schemaVersion==="PactAnswerReceipt/1"&&e.pactAnswerReceipt.targetEpicId===e.targetEpicId&&e.pactAnswerReceipt.graphRevision===e.graphRevision&&r(e.pactAnswerReceipt.stateSha256)&&r(e.pactAnswerReceipt.answersSha256)&&E(e.pactAnswerReceipt.questionIds,["PACT-Q1-CONSUMER","PACT-Q2-PROVIDER","PACT-Q3-BROKER","PACT-Q4-MATCHERS","PACT-Q5-VERIFY"])&&e.pactAnswerReceipt.publicSafe===!0&&(s.pactAnswerReceipt=e.pactAnswerReceipt);const f=a(e.evidenceExpectation,!1);f&&(s.evidenceExpectation=f);const y=o(e.completionEvidence,"architecture-stage-completion"),w=o(e.validationEvidence,"architecture-stage-validation");if(y&&(s.completionEvidence=y),w&&(s.validationEvidence=w),h(e.reviewDecision)&&Object.keys(e.reviewDecision).sort().join(",")===["schemaVersion","targetEpicId","graphRevision","artifactHash","completionReceiptId","validationReceiptId","decision","evidenceIds","publicSafe"].sort().join(",")&&e.reviewDecision.schemaVersion==="ArchitectureReviewDecision/1"&&e.reviewDecision.targetEpicId===e.targetEpicId&&e.reviewDecision.graphRevision===e.graphRevision&&r(e.reviewDecision.graphRevision)&&r(e.reviewDecision.artifactHash)&&r(e.reviewDecision.completionReceiptId)&&r(e.reviewDecision.validationReceiptId)&&["approved","changes-requested"].includes(String(e.reviewDecision.decision))&&e.reviewDecision.publicSafe===!0){const u=i(e.reviewDecision.evidenceIds,24);u&&u.length>0&&(s.reviewDecision={...e.reviewDecision,evidenceIds:u})}if(Ht(e.terminalMemoryCheckpoint,e))s.terminalMemoryCheckpoint=e.terminalMemoryCheckpoint;else if(h(e.terminalMemoryCheckpoint)&&e.terminalMemoryCheckpoint.schemaVersion===void 0&&["passed","failed","pending"].includes(String(e.terminalMemoryCheckpoint.status))){const u=i(e.terminalMemoryCheckpoint.evidenceIds,24);u&&(s.terminalMemoryCheckpoint={status:e.terminalMemoryCheckpoint.status,evidenceIds:u})}if(Array.isArray(e.acceptedStages)&&e.acceptedStages.length<=15){const u=e.acceptedStages.map(v=>{if(!h(v)||!t(v.targetEpicId)||!t(v.stageCommand))return;const I=o(v.completionEvidence,"architecture-stage-completion"),p=o(v.validationEvidence,"architecture-stage-validation");return I&&p?{targetEpicId:v.targetEpicId,stageCommand:v.stageCommand,completionEvidence:I,validationEvidence:p}:void 0});u.every(v=>v!==void 0)&&(s.acceptedStages=u)}if(h(e.accounting)&&e.accounting.schemaVersion===1&&t(e.accounting.contractVersion)&&t(e.accounting.accountingId)&&typeof e.accounting.charged=="boolean"&&Number.isInteger(e.accounting.chargedQuotaUnits)&&typeof e.accounting.chargedQuotaUnits=="number"&&e.accounting.chargedQuotaUnits>=0&&e.accounting.chargedQuotaUnits<=13){const u=i(e.accounting.receiptIds,32);u&&(s.accounting={schemaVersion:1,contractVersion:e.accounting.contractVersion,accountingId:e.accounting.accountingId,charged:e.accounting.charged,chargedQuotaUnits:e.accounting.chargedQuotaUnits,receiptIds:u,...["in-progress","aborted","timed-out","failed","complete"].includes(String(e.accounting.lastOutcome))?{lastOutcome:e.accounting.lastOutcome}:{}})}return JSON.stringify(s).length<=96e3?s:void 0}function _o(e){const t=h(e.metadata.archPlan)?e.metadata.archPlan.execution:void 0,r=h(t)?t.checkpoint:void 0,i=h(t)?t:void 0,a=h(r)?r:void 0,n=e.requestExecution,o=Array.isArray(a?.acceptedStages)?a.acceptedStages:[],s=n.currentStageCommand==="arch-prd"&&n.continuationState==="delegate"&&n.completionEvidence===void 0&&n.validationEvidence===void 0&&a?.currentStageCommand==="arch-prd"&&a.continuationState==="delegate"&&o.length===0&&i?.nextAction==="delegate",l=n.currentStageCommand==="arch-prd"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-architecture"&&a.continuationState==="advance"&&o.length===1&&h(o[0])&&o[0].stageCommand==="arch-prd"&&E(o[0].completionEvidence,n.completionEvidence)&&E(o[0].validationEvidence,n.validationEvidence)&&i?.nextAction==="resume",f=n.currentStageCommand==="arch-architecture"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-architecture"&&a.continuationState==="delegate"&&o.length===1&&E(o,n.acceptedStages)&&i?.nextAction==="delegate",y=n.currentStageCommand==="arch-architecture"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-fitness-functions"&&a.continuationState==="advance"&&o.length===2&&h(o[0])&&h(o[1])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===1&&E(o[0],n.acceptedStages[0])&&E(o[1].completionEvidence,n.completionEvidence)&&E(o[1].validationEvidence,n.validationEvidence)&&i?.nextAction==="resume",w=n.currentStageCommand==="arch-fitness-functions"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-fitness-functions"&&a.continuationState==="delegate"&&o.length===2&&h(o[0])&&h(o[1])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&E(o,n.acceptedStages)&&i?.nextAction==="delegate",u=n.currentStageCommand==="arch-fitness-functions"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-api-contracts"&&a.continuationState==="advance"&&o.length===3&&h(o[0])&&h(o[1])&&h(o[2])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&o[2].stageCommand==="arch-fitness-functions"&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===2&&E(o.slice(0,2),n.acceptedStages)&&E(o[2].completionEvidence,n.completionEvidence)&&E(o[2].validationEvidence,n.validationEvidence)&&i?.nextAction==="resume",v=n.currentStageCommand==="arch-api-contracts"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-api-contracts"&&a.continuationState==="delegate"&&o.length===3&&h(o[0])&&h(o[1])&&h(o[2])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&o[2].stageCommand==="arch-fitness-functions"&&E(o,n.acceptedStages)&&i?.nextAction==="delegate",I=["PACT-Q1-CONSUMER","PACT-Q2-PROVIDER","PACT-Q3-BROKER","PACT-Q4-MATCHERS","PACT-Q5-VERIFY"],p=n.currentStageCommand==="arch-api-contracts"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="generate-pacts"&&a.continuationState==="ask-user"&&o.length===4&&h(o[3])&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===3&&E(o.slice(0,3),n.acceptedStages)&&o[3].stageCommand==="arch-api-contracts"&&E(o[3].completionEvidence,n.completionEvidence)&&E(o[3].validationEvidence,n.validationEvidence)&&E(a.questionIds,I)&&E(i?.questionIds,I)&&i?.nextAction==="ask-user",C=n.currentStageCommand==="generate-pacts"&&n.continuationState==="ask-user"&&a?.currentStageCommand==="generate-pacts"&&a.continuationState==="delegate"&&o.length===4&&E(o,n.acceptedStages)&&E(n.questionIds,I)&&E(a.questionIds,[])&&E(a.pactAnswerReceipt,e.answerReceipt)&&E(i?.pactAnswerReceipt,e.answerReceipt)&&e.answerReceipt?.stateSha256===e.sourceStateSha256&&i?.nextAction==="resume",O=n.currentStageCommand==="generate-pacts"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&E(n.pactAnswerReceipt,e.pactRecordedReceipt)&&a?.currentStageCommand==="arch-api-integrations"&&a.continuationState==="advance"&&o.length===5&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===4&&E(o.slice(0,4),n.acceptedStages)&&o.map(j=>h(j)?j.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts"&&h(o[4])&&E(o[4].completionEvidence,n.completionEvidence)&&E(o[4].validationEvidence,n.validationEvidence)&&i?.nextAction==="resume",V=n.currentStageCommand==="arch-api-integrations"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-api-integrations"&&a.continuationState==="delegate"&&o.length===5&&E(o,n.acceptedStages)&&i?.nextAction==="delegate",T=n.currentStageCommand==="arch-api-integrations"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-database"&&a.continuationState==="advance"&&o.length===6&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===5&&E(o.slice(0,5),n.acceptedStages)&&o.map(j=>h(j)?j.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations"&&h(o[5])&&E(o[5].completionEvidence,n.completionEvidence)&&E(o[5].validationEvidence,n.validationEvidence)&&i?.nextAction==="resume",P=n.currentStageCommand==="arch-database"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-database"&&a.continuationState==="delegate"&&o.length===6&&E(o,n.acceptedStages)&&i?.nextAction==="delegate",S=n.currentStageCommand==="arch-database"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-security"&&a.continuationState==="advance"&&o.length===7&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===6&&E(o.slice(0,6),n.acceptedStages)&&o.map(j=>h(j)?j.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database"&&h(o[6])&&E(o[6].completionEvidence,n.completionEvidence)&&E(o[6].validationEvidence,n.validationEvidence)&&i?.nextAction==="resume",R=n.currentStageCommand==="arch-security"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-security"&&a.continuationState==="delegate"&&o.length===7&&E(o,n.acceptedStages)&&i?.nextAction==="delegate",Q=n.currentStageCommand==="arch-security"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-design-system"&&a.continuationState==="advance"&&o.length===8&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===7&&E(o.slice(0,7),n.acceptedStages)&&o.map(j=>h(j)?j.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security"&&h(o[7])&&E(o[7].completionEvidence,n.completionEvidence)&&E(o[7].validationEvidence,n.validationEvidence)&&i?.nextAction==="resume",M=n.currentStageCommand==="arch-design-system"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-design-system"&&a.continuationState==="delegate"&&o.length===8&&E(o,n.acceptedStages)&&i?.nextAction==="delegate",$=n.currentStageCommand==="arch-design-system"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-ux-design"&&a.continuationState==="advance"&&o.length===9&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===8&&E(o.slice(0,8),n.acceptedStages)&&o.map(j=>h(j)?j.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system"&&h(o[8])&&E(o[8].completionEvidence,n.completionEvidence)&&E(o[8].validationEvidence,n.validationEvidence)&&i?.nextAction==="resume",N=n.currentStageCommand==="arch-ux-design"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-ux-design"&&a.continuationState==="delegate"&&o.length===9&&E(o,n.acceptedStages)&&i?.nextAction==="blocked",ae=n.currentStageCommand==="arch-ux-design"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-performance"&&a.continuationState==="advance"&&o.length===10&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===9&&E(o.slice(0,9),n.acceptedStages)&&o.map(j=>h(j)?j.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design"&&h(o[9])&&E(o[9].completionEvidence,n.completionEvidence)&&E(o[9].validationEvidence,n.validationEvidence)&&i?.nextAction==="resume",D=n.currentStageCommand==="arch-performance"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-performance"&&a.continuationState==="delegate"&&o.length===10&&E(o,n.acceptedStages)&&i?.nextAction==="delegate",H=n.currentStageCommand==="arch-performance"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-testing"&&a.continuationState==="advance"&&o.length===11&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===10&&E(o.slice(0,10),n.acceptedStages)&&o.map(j=>h(j)?j.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance"&&h(o[10])&&E(o[10].completionEvidence,n.completionEvidence)&&E(o[10].validationEvidence,n.validationEvidence)&&i?.nextAction==="resume",Oe=n.currentStageCommand==="arch-testing"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-testing"&&a.continuationState==="delegate"&&o.length===11&&E(o,n.acceptedStages)&&i?.nextAction==="delegate",dt=n.currentStageCommand==="arch-testing"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-infrastructure"&&a.continuationState==="advance"&&o.length===12&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===11&&E(o.slice(0,11),n.acceptedStages)&&o.map(j=>h(j)?j.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance,arch-testing"&&h(o[11])&&E(o[11].completionEvidence,n.completionEvidence)&&E(o[11].validationEvidence,n.validationEvidence)&&i?.nextAction==="resume",X=n.currentStageCommand==="arch-infrastructure"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-infrastructure"&&a.continuationState==="delegate"&&o.length===12&&E(o,n.acceptedStages)&&i?.nextAction==="delegate",k=n.currentStageCommand==="arch-infrastructure"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-review"&&a.continuationState==="advance"&&o.length===13&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===12&&E(o.slice(0,12),n.acceptedStages)&&o.map(j=>h(j)?j.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance,arch-testing,arch-infrastructure"&&h(o[12])&&E(o[12].completionEvidence,n.completionEvidence)&&E(o[12].validationEvidence,n.validationEvidence)&&i?.nextAction==="resume",G=n.currentStageCommand==="arch-review"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-review"&&a.continuationState==="delegate"&&o.length===13&&E(o,n.acceptedStages)&&i?.nextAction==="delegate",pt=n.currentStageCommand==="arch-review"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&n.reviewDecision===void 0&&a?.currentStageCommand==="arch-review"&&a.continuationState==="ask-user"&&o.length===13&&E(o,n.acceptedStages)&&E(a.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&E(a.completionEvidence,n.completionEvidence)&&E(a.validationEvidence,n.validationEvidence)&&i?.nextAction==="ask-user",Ne=n.currentStageCommand==="arch-review"&&n.continuationState==="ask-user"&&n.childStatus==="succeeded"&&h(n.reviewDecision)&&n.reviewDecision.decision==="approved"&&E(n.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&a?.currentStageCommand==="update-memory"&&a.continuationState==="advance"&&o.length===14&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===13&&E(o.slice(0,13),n.acceptedStages)&&h(o[13])&&o[13].stageCommand==="arch-review"&&E(o[13].completionEvidence,n.completionEvidence)&&E(o[13].validationEvidence,n.validationEvidence)&&E(a.reviewDecision,n.reviewDecision)&&i?.nextAction==="resume",we=n.currentStageCommand==="update-memory"&&n.continuationState==="advance"&&h(n.reviewDecision)&&n.reviewDecision.decision==="approved"&&a?.currentStageCommand==="update-memory"&&a.continuationState==="delegate"&&o.length===14&&E(o,n.acceptedStages)&&E(a.reviewDecision,n.reviewDecision)&&i?.nextAction==="delegate",We=n.currentStageCommand==="update-memory"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="update-memory"&&a.continuationState==="complete"&&o.length===15&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===14&&E(o.slice(0,14),n.acceptedStages)&&h(o[14])&&o[14].targetEpicId===n.targetEpicId&&o[14].stageCommand==="update-memory"&&E(o[14].completionEvidence,n.completionEvidence)&&E(o[14].validationEvidence,n.validationEvidence)&&E(a.reviewDecision,n.reviewDecision)&&E(a.completionEvidence,n.completionEvidence)&&E(a.validationEvidence,n.validationEvidence)&&Ht(a.terminalMemoryCheckpoint,n)!==null&&E(a.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)&&i?.nextAction==="complete",Fe=n.currentStageCommand==="update-memory"&&n.continuationState==="complete"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="update-memory"&&a.continuationState==="complete"&&o.length===15&&E(o,n.acceptedStages)&&E(a.reviewDecision,n.reviewDecision)&&E(a.completionEvidence,n.completionEvidence)&&E(a.validationEvidence,n.validationEvidence)&&Ht(a.terminalMemoryCheckpoint,n)&&E(a.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)&&i?.nextAction==="complete",Z=i?xi(n,i,Ht(n.terminalMemoryCheckpoint,n)&&E(a?.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)):void 0;if(e.metadata.mode!=="arch-plan"||e.metadata.resolvedTrigger!=="arch-plan"||!h(t)||!h(r)||t.owner!=="root"||t.currentStageCommand!==r.currentStageCommand||t.continuationState!==r.continuationState||r.owner!=="root"||r.evidencePolicy!=="v2-required"||r.targetEpicId!==n.targetEpicId||r.graphRevision!==n.graphRevision||r.graphSource!==n.graphSource||!/^P[1-9][0-9]{0,11}$/.test(String(r.targetEpicId))||!/^[a-f0-9]{64}$/.test(String(r.graphRevision))||!Array.isArray(r.acceptedStages)||!(Z||s||l||f||y||w||u||v||p||C||O||V||T||P||S||R||Q||M||$||N||ae||D||H||Oe||dt||X||k||G||pt||Ne||we||We||Fe)||!h(r.accounting)||r.accounting.charged!==!0||!E(hn(r),r))throw new Error("architecture-root-checkpoint-invalid");const ue=K(e.projectRoot,".neocortex"),oe=K(ue,"state.json"),vt=K(ue,"state.json.architecture.lock"),qe=Ft(vt,"wx",384);let Ye;try{const j=Lt(oe);if(!j.isFile()||j.isSymbolicLink())throw new Error("architecture-root-state-binding-invalid");const ce=He(oe,"utf8");if(Ue("sha256").update(ce).digest("hex")!==e.sourceStateSha256)throw new Error("architecture-root-state-conflict");const z=JSON.parse(ce),Le=h(z)&&h(z.archPlan)?z.archPlan:{};if(!h(z)||!h(z.epics)||!Object.hasOwn(z.epics,r.targetEpicId)||(e.initialBinding?Le.execution!==void 0||n.graphSource!=="committed-epic-v1":!E(hn(Le.execution),n))||h(z.scope)&&z.scope.kind==="projected")throw new Error("architecture-root-state-binding-invalid");if(n.graphSource==="committed-epic-v1"&&n.graphRevision!==Gt(e.projectRoot,String(n.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");if(Fe||Z==="complete-replay"){const ye={...n,continuationState:"delegate",acceptedStages:n.acceptedStages.slice(0,or(n))};if(!E(n.terminalMemoryCheckpoint,xn(e.projectRoot,ye)))throw new Error("architecture-root-state-conflict");return}const se=nn(),Ct=$e("git",["rev-parse","--git-common-dir"],{cwd:e.projectRoot,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),Ke=Li(Ct)?Pn(Ct):Pn(e.projectRoot,Ct);if(Ni(Ke)!==Ke)throw new Error("architecture-root-backup-dir-invalid");const me=K(Ke,"neocortex-architecture");Wt(me,{recursive:!0,mode:448});const Y=Lt(me);if(!Y.isDirectory()||Y.isSymbolicLink()||Y.uid!==process.getuid?.()||(Y.mode&63)!==0)throw new Error("architecture-root-backup-dir-invalid");const vn=K(me,`state-backup-${se}.json`),x=Ft(vn,"wx",384);try{rn(x,ce),an(x)}finally{qt(x)}const wt=Ft(me,"r");try{an(wt)}finally{qt(wt)}const g={...z,archPlan:{...Le,execution:r}};Ye=K(ue,`state.json.architecture-tmp-${se}`);const lt=Ft(Ye,"wx",384);try{rn(lt,`${JSON.stringify(g,null,2)}
|
|
8
|
-
`),an(lt)}finally{qt(lt)}if((We||Z==="complete")&&!E(n.terminalMemoryCheckpoint,xn(e.projectRoot,n)))throw new Error("architecture-root-state-conflict");if(n.graphSource==="committed-epic-v1"&&n.graphRevision!==Gt(e.projectRoot,String(n.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");dr(Ye,oe),Ye=void 0;const $t=Ft(ue,"r");try{an($t)}finally{qt($t)}}finally{if(Ye)try{Tn(Ye)}catch{}qt(qe),Tn(vt)}}function gn(e,t){if(!h(e))return;const r={};for(const i of t){const a=e[i];if(typeof a=="boolean")r[i]=a;else if(typeof a=="number"&&Number.isFinite(a))r[i]=a;else if(typeof a=="string"){const n=ee(a);n&&(r[i]=n)}}return Object.keys(r).length>0?r:void 0}function fn(e){return e==="epic"||e==="story"?e:void 0}function Fr(e){if(!h(e)||e.schemaVersion!==1)return;const t=J(e.ownerStoryId),r=J(e.sessionId),i=J(e.idempotencyKey),a=Te(e.acquiredAt),n=Te(e.expiresAt);if(!(!t||!r||!i||!a||!n||Date.parse(n)<=Date.parse(a)))return{schemaVersion:1,ownerStoryId:t,sessionId:r,idempotencyKey:i,acquiredAt:a,expiresAt:n}}function qr(e){if(!h(e)||e.schemaVersion!==1)return;const t=J(e.storyId),r=J(e.epicId),i=Se(e.branch),a=_(e.baseSha),n=_(e.headSha),o=J(e.idempotencyKey),s=Te(e.recordedAt),l=Ee(e.commits).map(_).filter(V=>!!V).slice(0,256),f=Ee(e.receiptRefs).map(at).filter(V=>!!V).slice(0,256),y=e.dispatchId===void 0?void 0:J(e.dispatchId),w=e.bundleId===void 0?void 0:J(e.bundleId),u=e.bundleDigest===void 0?void 0:_(e.bundleDigest),v=e.graphRevision===void 0?void 0:_(e.graphRevision),I=e.claimRevision===void 0?void 0:J(e.claimRevision),p=Ro(e.qaReceipt),C=Ao(e.reviewReceipt),O=e.rootMemoryEffect===void 0?void 0:Ha(e.rootMemoryEffect)?e.rootMemoryEffect:void 0;if(!(!t||!r||!t.startsWith(`${r}.`)||!i||!a||!n||a===n||!o||!s||l.length===0||f.length===0||!Array.isArray(e.commits)||l.length!==e.commits.length||e.commits.length>256||!Array.isArray(e.receiptRefs)||f.length!==e.receiptRefs.length||e.receiptRefs.length>256||e.dispatchId!==void 0&&!y||e.bundleId!==void 0&&!w||e.bundleDigest!==void 0&&(!u||u.length!==64)||e.graphRevision!==void 0&&(!v||v.length!==64)||e.claimRevision!==void 0&&!I||e.rootMemoryEffect!==void 0&&(!O||O.storyId!==t||O.epicId!==r||O.executionBranch!==i||O.sourceHeadSha!==a||O.childClaimRevision!==I)||e.qaVerdict!=="passed"&&e.qaVerdict!=="blocked"||!["approved","changes-requested","pending"].includes(String(e.reviewVerdict))||!p||e.reviewVerdict!=="pending"&&!C||e.reviewVerdict==="pending"&&C||p.verdict!==e.qaVerdict||C&&C.verdict!==e.reviewVerdict||!zr(p,{storyId:t,epicId:r,baseSha:a,headSha:n,bundleDigest:u,graphRevision:v})||C&&(!zr(C,{storyId:t,epicId:r,baseSha:a,headSha:n,bundleDigest:u,graphRevision:v})||C.qaReceiptRef!==p?.receiptRef||C.receiptRef===p?.receiptRef)||!f.includes(String(p.receiptRef))||C&&(!f.includes(String(C.receiptRef))||Date.parse(String(C.reviewedAt))<Date.parse(String(p.checkedAt)))))return{schemaVersion:1,storyId:t,epicId:r,branch:i,baseSha:a,headSha:n,idempotencyKey:o,...y?{dispatchId:y}:{},...w?{bundleId:w}:{},...u?{bundleDigest:u}:{},...v?{graphRevision:v}:{},...I?{claimRevision:I}:{},...O?{rootMemoryEffect:structuredClone(O)}:{},qaVerdict:e.qaVerdict,reviewVerdict:e.reviewVerdict,...p?{qaReceipt:p}:{},...C?{reviewReceipt:C}:{},recordedAt:s,commits:l,receiptRefs:f}}function Ro(e){if(!h(e)||e.schemaVersion!==1||e.kind!=="story_qa_evidence"||e.producer!=="local-yolo-tdd"||e.evidenceVersion!==void 0&&e.evidenceVersion!=="git-immutable-v1"&&e.evidenceVersion!=="p205-execution-v2"||!["passed","blocked"].includes(String(e.verdict)))return;const t=J(e.storyId),r=J(e.epicId),i=_(e.baseSha),a=_(e.headSha),n=_(e.bundleDigest),o=_(e.graphRevision),s=_(e.sourceEvidenceDigest),l=Te(e.checkedAt),f=at(e.receiptRef),y=e.evidenceVersion==="p205-execution-v2"&&e.contract==="P205-CI-02"?e.contract:void 0,w=e.evidenceVersion==="p205-execution-v2"&&e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,u=e.evidenceVersion==="p205-execution-v2"?_(e.manifestDigest):void 0,v=e.evidenceVersion==="p205-execution-v2"?_(e.resultDigest):void 0,I=e.evidenceVersion==="p205-execution-v2"?Ee(e.gateIds).map(J).filter(p=>!!p).slice(0,64):void 0;if(!(!t||!r||!i||!a||!n||n.length!==64||!o||o.length!==64||!s||s.length!==64||!l||!f||e.evidenceVersion==="p205-execution-v2"&&(!y||w!=="node scripts/test-root.mjs --gate complete"||!u||u.length!==64||!v||v.length!==64||!Array.isArray(e.gateIds)||!I||I.length===0||I.length!==e.gateIds.length)))return{schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",...e.evidenceVersion?{evidenceVersion:e.evidenceVersion}:{},storyId:t,epicId:r,...e.evidenceVersion==="p205-execution-v2"?{contract:y,command:w,manifestDigest:u,gateIds:I,resultDigest:v}:{},baseSha:i,headSha:a,bundleDigest:n,graphRevision:o,sourceEvidenceDigest:s,verdict:e.verdict,checkedAt:l,receiptRef:f}}function Yr(e){if(!h(e)||e.schemaVersion!==1||e.kind!=="story_checkpoint_physical_verification"||e.producer!=="client-p205-transient-v1"||e.publicSafe!==!0||e.verdict!=="verified"&&e.verdict!=="rejected")return;const t=J(e.storyId),r=J(e.epicId),i=Se(e.branch),a=_(e.baseSha),n=_(e.headSha),o=_(e.aggregateHeadSha),s=_(e.commitBodyDigest),l=_(e.changedPathsDigest),f=e.claimVerification==="canonical"||e.claimVerification==="legacy-migration"?e.claimVerification:void 0,y=_(e.effectiveClaimRevision),w=e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,u=_(e.manifestDigest),v=Ee(e.gateIds).map(J).filter(P=>!!P).slice(0,64),I=_(e.resultDigest),p=_(e.graphRevision),C=_(e.executionEvidenceDigest),O=_(e.sourceEvidenceDigest),V=Te(e.verifiedAt),T=Ee(e.reasonCodes).map(J).filter(P=>!!P).slice(0,16);if(!(!t||!r||!i||!a||a.length<40||!n||n.length<40||!o||o.length<40||!s||s.length!==64||!l||l.length!==64||!f||!y||y.length!==64||!w||!u||u.length!==64||!Array.isArray(e.gateIds)||v.length!==e.gateIds.length||!I||I.length!==64||!p||p.length!==64||!C||C.length!==64||!O||O.length!==64||!V||T.length===0||e.verdict==="verified"&&(v.length===0||!T.includes("checkpoint-p205-transient-verified"))))return{schemaVersion:1,kind:"story_checkpoint_physical_verification",producer:"client-p205-transient-v1",storyId:t,epicId:r,branch:i,baseSha:a,headSha:n,aggregateHeadSha:o,commitBodyDigest:s,changedPathsDigest:l,claimVerification:f,effectiveClaimRevision:y,command:w,manifestDigest:u,gateIds:v,resultDigest:I,graphRevision:p,executionEvidenceDigest:C,sourceEvidenceDigest:O,verifiedAt:V,verdict:e.verdict,reasonCodes:T,publicSafe:!0}}function Jr(e){const t=["schemaVersion","kind","producer","storyId","epicId","branch","baseSha","headSha","graphRevision","effectiveClaimRevision","sourceEvidenceDigest","verifiedAt","reasonCodes","integrationAuthorized","publicSafe"];if(!h(e)||Object.keys(e).some(u=>!t.includes(u))||e.schemaVersion!==1||e.kind!=="story_scheduling_checkpoint_evidence"||e.producer!=="client-git-physical-v1"||e.integrationAuthorized!==!1||e.publicSafe!==!0)return;const r=J(e.storyId),i=J(e.epicId),a=Se(e.branch),n=_(e.baseSha),o=_(e.headSha),s=_(e.graphRevision),l=_(e.effectiveClaimRevision),f=_(e.sourceEvidenceDigest),y=Te(e.verifiedAt),w=Ee(e.reasonCodes).map(J).filter(u=>!!u);if(!(!r||!i||!a||!n||n.length<40||!o||o.length<40||!s||s.length!==64||!l||l.length!==64||!f||f.length!==64||!y||!Array.isArray(e.reasonCodes)||w.length!==1||w[0]!=="checkpoint-git-scheduling-verified"))return{schemaVersion:1,kind:"story_scheduling_checkpoint_evidence",producer:"client-git-physical-v1",storyId:r,epicId:i,branch:a,baseSha:n,headSha:o,graphRevision:s,effectiveClaimRevision:l,sourceEvidenceDigest:f,verifiedAt:y,reasonCodes:w,integrationAuthorized:!1,publicSafe:!0}}function Ao(e){if(!h(e)||e.schemaVersion!==1||e.kind!=="story_review_evidence"||e.producer!=="root-commit-range-review"||!["approved","changes-requested"].includes(String(e.verdict)))return;const t=J(e.storyId),r=J(e.epicId),i=_(e.baseSha),a=_(e.headSha),n=_(e.bundleDigest),o=_(e.graphRevision),s=_(e.sourceEvidenceDigest),l=at(e.qaReceiptRef),f=Te(e.reviewedAt),y=at(e.receiptRef);if(!(!t||!r||!i||!a||!n||n.length!==64||!o||o.length!==64||!s||s.length!==64||!l||!f||!y))return{schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:t,epicId:r,baseSha:i,headSha:a,bundleDigest:n,graphRevision:o,sourceEvidenceDigest:s,qaReceiptRef:l,verdict:e.verdict,reviewedAt:f,receiptRef:y}}function zr(e,t){return["storyId","epicId","baseSha","headSha","bundleDigest","graphRevision"].every(r=>e[r]===t[r])}function Kr(e){if(!h(e)||e.schemaVersion!==1||e.capturedFromCurrentCheckout!==!0)return;const t=Se(e.originBranch),r=_(e.originHeadSha),i=Se(e.executionBranch),a=Te(e.capturedAt);if(!(!t||!r||r.length<40||!i||!a||t===i))return{schemaVersion:1,originBranch:t,originHeadSha:r,executionBranch:i,capturedFromCurrentCheckout:!0,capturedAt:a}}function Qr(e){if(!h(e)||e.schemaVersion!==1||e.verdict!=="passed")return;const t=_(e.executionHeadSha),r=_(e.graphRevision),i=Te(e.checkedAt),a=at(e.receiptRef),n=Ee(e.gateIds).map(J).filter(y=>!!y).slice(0,128),o=e.evidenceVersion==="p205-execution-v2"&&e.producer==="local-yolo-tdd"&&e.contract==="P205-CI-02"&&e.command==="node scripts/test-root.mjs --gate complete",s=e.evidenceVersion===void 0&&e.producer===void 0&&e.contract===void 0&&e.command===void 0&&e.manifestDigest===void 0&&e.resultDigest===void 0,l=o?_(e.manifestDigest):void 0,f=o?_(e.resultDigest):void 0;if(!(!t||t.length<40||!r||r.length!==64||!i||!a||n.length===0||!Array.isArray(e.gateIds)||n.length!==e.gateIds.length||e.gateIds.length>128||!s&&!o||o&&(!l||l.length!==64||!f||f.length!==64)))return{schemaVersion:1,...o?{evidenceVersion:"p205-execution-v2",producer:"local-yolo-tdd",contract:"P205-CI-02",command:"node scripts/test-root.mjs --gate complete",manifestDigest:l,resultDigest:f}:{},verdict:"passed",executionHeadSha:t,graphRevision:r,checkedAt:i,receiptRef:a,gateIds:n}}function Xr(e){if(!h(e)||e.schemaVersion!==1||e.kind!=="epic_head_reconciliation"||e.producer!=="client-p205-head-reconciliation-v1"||e.publicSafe!==!0)return;const t={schemaVersion:1,kind:"epic_head_reconciliation",producer:"client-p205-head-reconciliation-v1",epicId:J(e.epicId),executionBranch:Se(e.executionBranch),originBranch:Se(e.originBranch),graphRevision:_(e.graphRevision),originHeadSha:_(e.originHeadSha),lastAcceptedCheckpointHeadSha:_(e.lastAcceptedCheckpointHeadSha),executionHeadSha:_(e.executionHeadSha),acceptedCheckpointIds:Ee(e.acceptedCheckpointIds),acceptedCheckpointHeads:Ee(e.acceptedCheckpointHeads),reconciliationCommitShas:Ee(e.reconciliationCommitShas),commitRangeDigest:_(e.commitRangeDigest),changedPaths:Ee(e.changedPaths),changedPathsDigest:_(e.changedPathsDigest),allowedWriteSet:Ee(e.allowedWriteSet),allowedWriteSetDigest:_(e.allowedWriteSetDigest),aggregateReceiptRef:at(e.aggregateReceiptRef),aggregateManifestDigest:_(e.aggregateManifestDigest),aggregateResultDigest:_(e.aggregateResultDigest),producedAt:Te(e.producedAt),revalidatedAt:Te(e.revalidatedAt),publicSafe:!0};if(!t.epicId||!t.executionBranch||!t.originBranch||!t.graphRevision||t.graphRevision.length!==64||!t.originHeadSha||t.originHeadSha.length<40||!t.lastAcceptedCheckpointHeadSha||t.lastAcceptedCheckpointHeadSha.length<40||!t.executionHeadSha||t.executionHeadSha.length<40||t.acceptedCheckpointIds.length===0||t.acceptedCheckpointIds.length>2048||t.acceptedCheckpointIds.length!==t.acceptedCheckpointHeads.length||t.acceptedCheckpointHeads.some(a=>!/^[a-f0-9]{40,64}$/i.test(a))||t.reconciliationCommitShas.length>2048||t.reconciliationCommitShas.some(a=>!/^[a-f0-9]{40,64}$/i.test(a))||t.changedPaths.length>2048||(t.lastAcceptedCheckpointHeadSha===t.executionHeadSha?t.reconciliationCommitShas.length!==0||t.changedPaths.length!==0:t.reconciliationCommitShas.length===0||t.changedPaths.length===0)||t.allowedWriteSet.length===0||t.allowedWriteSet.length>2048||!t.commitRangeDigest||!t.changedPathsDigest||!t.allowedWriteSetDigest||!t.aggregateReceiptRef||!t.aggregateManifestDigest||!t.aggregateResultDigest||!t.producedAt||!t.revalidatedAt||t.commitRangeDigest!==La(t.lastAcceptedCheckpointHeadSha,t.executionHeadSha,t.reconciliationCommitShas)||t.changedPathsDigest!==xr(t.changedPaths)||t.allowedWriteSetDigest!==xr(t.allowedWriteSet))return;const r=t,i=_(e.inputDigest);if(!(!i||i.length!==64||i!==Na(r)))return{...r,inputDigest:i}}function Gn(e){if(!h(e)||e.schemaVersion!==1)return;const t=gn(e,["schemaVersion","kind","storyId","epicId","baseSha","headSha","originalBaseSha","originalHeadSha","gitPullRequest","preservesLaterCommits","historyRewrite","recordedAt"])??{},r=Ee(e.receiptRefs).map(at).filter(a=>!!a).slice(0,256),i=Ee(e.revertCommits).map(ee).filter(a=>!!a).slice(0,256);return{...t,...r.length?{receiptRefs:r}:{},...i.length?{revertCommits:i}:{}}}function bo(e){if(!(!h(e)||Object.keys(e).sort().join(",")!=="gitPullRequest,headSha,kind,prNumber,reviewEvidenceDigest,schemaVersion"||e.schemaVersion!==1||e.kind!=="git-pull-request"||e.gitPullRequest!==!0||!Number.isSafeInteger(e.prNumber)||Number(e.prNumber)<=0||typeof e.headSha!="string"||!/^[a-f0-9]{40}$/.test(e.headSha)||typeof e.reviewEvidenceDigest!="string"||!/^[a-f0-9]{64}$/.test(e.reviewEvidenceDigest)))return{schemaVersion:1,kind:"git-pull-request",gitPullRequest:!0,prNumber:e.prNumber,headSha:e.headSha,reviewEvidenceDigest:e.reviewEvidenceDigest}}function Zr(e){if(!h(e)||e.schemaVersion!==1||e.publicSafe!==!0)return;const t=J(e.epicId),r=Se(e.executionBranch),i=Se(e.originBranch),a=_(e.baseSha),n=_(e.executionHeadSha),o=e.mergeSha===void 0?void 0:_(e.mergeSha),s=e.pushedSha===void 0?void 0:_(e.pushedSha),l=J(e.idempotencyKey),f=Te(e.attemptStartedAt),y=e.completedAt===void 0?void 0:Te(e.completedAt),w=Ee(e.localGateReceiptRefs).map(at).filter(p=>!!p).slice(0,256),u=Ee(e.reasonCodes).map(J).filter(p=>!!p).slice(0,64),v=To(e.candidateQa),I=xo(e.providerGuard);if(!(!t||!r||!i||!a||!n||!l||!f||w.length===0||u.length===0||!["direct","single_pr"].includes(String(e.strategy))||!["prepared","merged","pushed","denied_external_gate","blocked_local_or_repo"].includes(String(e.physicalStatus))||typeof e.retryEligible!="boolean"||e.providerGuard!==void 0&&!I||I&&(e.strategy!=="single_pr"||e.physicalStatus!=="pushed"||I.prHeadSha!==o||I.originHeadSha!==a)))return{schemaVersion:1,epicId:t,executionBranch:r,originBranch:i,baseSha:a,executionHeadSha:n,...o?{mergeSha:o}:{},...s?{pushedSha:s}:{},strategy:e.strategy,...Et(e.prNumber)?{prNumber:Et(e.prNumber)}:{},physicalStatus:e.physicalStatus,localGateReceiptRefs:w,idempotencyKey:l,attemptStartedAt:f,...v?{candidateQa:v}:{},...I?{providerGuard:I}:{},...y?{completedAt:y}:{},retryEligible:e.retryEligible,reasonCodes:u,publicSafe:!0}}function xo(e){if(!h(e)||e.schemaVersion!==1||e.provider!=="github"||e.publicSafe!==!0)return;const t=String(e.mode),r=String(e.source),i=t==="recovered_exact_tree"?r==="physical_recovery":t==="strict_up_to_date_expected_head"&&["branch_protection","ruleset","branch_protection_and_ruleset"].includes(r),a=_(e.prHeadSha),n=_(e.originHeadSha),o=Te(e.checkedAt);if(!(!i||!a||!n||!o))return{schemaVersion:1,provider:"github",mode:t,source:r,prHeadSha:a,originHeadSha:n,checkedAt:o,publicSafe:!0}}function To(e){if(!h(e)||e.schemaVersion!==1||e.kind!=="epic_merge_candidate_qa"||e.contract!=="P205-CI-02"||e.command!==Ba)return;const r=Object.fromEntries(["originHeadSha","executionHeadSha","mergeSha","treeSha","graphRevision","manifestDigest","resultDigest"].map(o=>[o,_(e[o])])),i=Te(e.checkedAt),a=at(e.receiptRef),n=Ee(e.gateIds).filter(o=>/^[a-z0-9-]+$/.test(o)).slice(0,128);if(!(Object.values(r).some(o=>!o)||!i||!a||n.length===0))return{schemaVersion:1,kind:e.kind,contract:e.contract,command:e.command,...r,checkedAt:i,receiptRef:a,gateIds:n}}function Po(e){if(!h(e))return;const t={...ee(e.active_epic_id??e.activeEpicId)?{active_epic_id:ee(e.active_epic_id??e.activeEpicId)}:{},...ee(e.active_story_id??e.activeStoryId)?{active_story_id:ee(e.active_story_id??e.activeStoryId)}:{},...ee(e.active_step_id??e.activeStepId)?{active_step_id:ee(e.active_step_id??e.activeStepId)}:{},...ee(e.session_id??e.sessionId)?{session_id:ee(e.session_id??e.sessionId)}:{},...ee(e.started_at??e.startedAt)?{started_at:ee(e.started_at??e.startedAt)}:{}};return Object.keys(t).length>0?t:void 0}function ko(e){const t=gn(e.completionEvidence??e.completion_evidence,["prNumber","pr_number","prState","pr_state","pullRequestState","merged","mergedAt","issueNumber","issue_number","issueState","issue_state","closedAt"]),r=gn(e.issueCloseAudit??e.issue_close_audit,["schema_version","event","storyId","epicId","issueNumber","closedAt","publicSafe","rawLogStorage"]),i=gn(e.scopedCiEvidence??e.scoped_ci_evidence,["schema_version","storyId","epicId","prNumber","finalState","publicSafe","rawLogStorage"]);return{...typeof e.merged=="boolean"?{merged:e.merged}:{},...typeof e.safeToContinueYoloop=="boolean"?{safeToContinueYoloop:e.safeToContinueYoloop}:{},...typeof e.mergeBlockedRemotely=="boolean"?{mergeBlockedRemotely:e.mergeBlockedRemotely}:{},...ee(e.physicalMergeStatus)?{physicalMergeStatus:ee(e.physicalMergeStatus)}:{},...ee(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)?{pr_state:ee(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)}:{},...ee(e.issue_state??e.issueState??e.workflow_issue_state)?{issue_state:ee(e.issue_state??e.issueState??e.workflow_issue_state)}:{},...Et(e.issue_number??e.issueNumber)?{issue_number:Et(e.issue_number??e.issueNumber)}:{},...t?{completionEvidence:t}:{},...r?{issueCloseAudit:r}:{},...i?{scopedCiEvidence:i}:{}}}class ot extends Error{reasonCode;constructor(t){super(t),this.name="StateSnapshotIntegrityError",this.reasonCode=t}}const Oo=new Set(["yolo","yoloop","finalize-epic","audit"]);function ei(e){return typeof e=="string"&&Oo.has(e)}function Wn(e,t={}){const r=K(e,".neocortex","state.json");if(!Nt(r))throw new ot("git-lifecycle-state-missing");let i;try{i=JSON.parse(He(r,"utf8"))}catch{throw new ot("git-lifecycle-state-corrupt")}if(!h(i)||!h(i.epics)||!h(i.stories))throw new ot("git-lifecycle-state-shape-invalid");const a=Object.values(i.epics).some(n=>h(n)&&(n.branch_mode==="epic"||Se(n.execution_branch)!==void 0));if(a)try{dn(e,{required:!0})}catch(n){const o=n instanceof Error&&/^git-lifecycle-/.test(n.message)?n.message:"git-lifecycle-runtime-invalid";if(t.allowMissingRuntime&&o==="git-lifecycle-runtime-missing")return{lifecycleDeclared:!0,runtimeMissing:!0};throw new ot(o)}return{lifecycleDeclared:a,runtimeMissing:!1}}function mn(e,t={}){const r=K(e,".neocortex","state.json");if(!Nt(r)){if(t.epicAware&&!t.projectless)throw new ot("git-lifecycle-state-missing");return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}let i,a;try{const I=He(r,"utf-8");a=Ue("sha256").update(I).digest("hex");const p=JSON.parse(I),C=h(p.epics)?p.epics:{},O=Object.values(C).some(R=>h(R)&&(R.branch_mode==="epic"||Se(R.execution_branch)!==void 0)),V=dn(e,{required:!!(t.epicAware&&O&&!t.projectless)});i=Tr(p,V);const T=h(i.stories)?i.stories:{},P=h(i.epics)?i.epics:{},S=h(p.stories)?p.stories:{};for(const[R,Q]of Object.entries(T)){const M=h(Q)?Q:void 0;if(!M?.checkpoint)continue;const $=typeof M.epic_id=="string"?M.epic_id:R.split(".")[0],N=h(P[$])?P[$]:void 0,ae=Se(N?.execution_branch);if(!ae)continue;const D=Da(e,M.checkpoint,R,$,ae,t.p205Authorities?.[R],Pr(R,M,h(M.checkpoint)?M.checkpoint:void 0));if(D.kind==="integration-authorized")M.checkpoint_verification=D.verification,delete M.scheduling_checkpoint_evidence;else if(D.kind==="scheduling-only")M.scheduling_checkpoint_evidence=D.evidence,delete M.checkpoint,delete M.checkpoint_verification;else if(D.kind==="rejected"){M.checkpoint_verification=D.verification,delete M.scheduling_checkpoint_evidence;const H=h(S[R])?S[R]:void 0;if(delete M.checkpoint,V.stories[R]?.checkpoint!==void 0)for(const Oe of["status","last_step","steps_completed"])H&&Object.prototype.hasOwnProperty.call(H,Oe)?M[Oe]=structuredClone(H[Oe]):delete M[Oe];["done","completed","merged"].includes(String(M.status).toLowerCase())&&(M.status="blocked")}}}catch(I){if(t.epicAware&&!t.projectless){const p=I instanceof Error&&/^git-lifecycle-/.test(I.message)?I.message:"git-lifecycle-state-corrupt";throw new ot(p)}return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}try{const I=yo(i);I.length>0&&Io(I)}catch{}const n=i.config??i.project??{},o=i.stories??{},s={};for(const[I,p]of Object.entries(o)){const C=h(p.review_request)&&p.review_request.kind==="git-pull-request"?bo(p.review_request):Gn(p.review_request);s[I]={id:p.id??I,title:p.title,epic_id:p.epic_id,status:p.status??"backlog",...Wr(p.source)?{source:Wr(p.source)}:{},steps_completed:p.steps_completed??[],last_step:p.last_step??null,branch_name:p.branch_name??null,pr_number:p.pr_number,...fn(p.branch_mode)?{branch_mode:fn(p.branch_mode)}:{},...qr(p.checkpoint)?{checkpoint:qr(p.checkpoint)}:{},...Yr(p.checkpoint_verification)?{checkpoint_verification:Yr(p.checkpoint_verification)}:{},...Jr(p.scheduling_checkpoint_evidence)?{scheduling_checkpoint_evidence:Jr(p.scheduling_checkpoint_evidence)}:{},...C?{review_request:C}:{},...Gn(p.rollback_receipt)?{rollback_receipt:Gn(p.rollback_receipt)}:{},...Et(p.workflow_issue)?{workflow_issue:Et(p.workflow_issue)}:{},...ko(p),depends_on:Gr(p.depends_on),files_to_modify:Ee(p.files_to_modify),...wo(p),risk:typeof p.risk=="string"?p.risk:void 0,blast_radius:typeof p.blast_radius=="number"?p.blast_radius:void 0}}const l=i.epics??{},f={};for(const[I,p]of Object.entries(l)){const C=Eo(p.lifecycle_classification),O=Co(p.createEpicPlanning,I);let V,T,P,S;if(O&&h(p.createEpicPlanningClaim)&&typeof p.createEpicPlanningClaim.claimId=="string"&&h(p.createEpicPlanningPhysical))try{pr(i,p.createEpicPlanningClaim.claimId,I,!0),V=JSON.parse(JSON.stringify(p.createEpicPlanningPhysical))}catch{}if(V&&h(p.createEpicPlanningClaim)&&typeof p.createEpicPlanningClaim.claimId=="string"&&h(p.createEpicPlanningResearchPhysical))try{lr(i,p.createEpicPlanningClaim.claimId,I),T=JSON.parse(JSON.stringify(p.createEpicPlanningResearchPhysical))}catch{}if(t.verifyPlanningGeneration&&O&&p.status==="generated"&&h(p.createEpicPlanningClaim)&&typeof p.createEpicPlanningClaim.claimId=="string"&&h(p.createEpicPlanningGenerationPhysical))try{if(Vi(e,p.createEpicPlanningClaim.claimId,I).stateSha256!==a)throw new Error("planning-generation-snapshot-raced");P=JSON.parse(JSON.stringify(p.createEpicPlanningGenerationPhysical)),V=JSON.parse(JSON.stringify(p.createEpicPlanningPhysical)),T=JSON.parse(JSON.stringify(p.createEpicPlanningResearchPhysical))}catch{}if(P&&h(p.createEpicPlanningClaim)&&typeof p.createEpicPlanningClaim.claimId=="string")try{const R=ur(e,p.createEpicPlanningClaim.claimId,I);if(R.stateSha256!==a)throw new Error("planning-memory-snapshot-raced");S=JSON.parse(JSON.stringify(R))}catch{}f[I]={id:p.id??I,title:p.title,...O?{createEpicPlanning:O}:{},...V?{createEpicPlanningPhysical:V}:{},...T?{createEpicPlanningResearchPhysical:T}:{},...P?{createEpicPlanningGenerationPhysical:P}:{},...S?{createEpicPlanningMemoryPhysical:S}:{},status:p.status,stories:p.stories,total_stories:p.total_stories,completed_stories:p.completed_stories,depends_on:Gr(p.depends_on),...fn(p.branch_mode)?{branch_mode:fn(p.branch_mode)}:{},...Se(p.execution_branch)?{execution_branch:Se(p.execution_branch)}:{},...Se(p.origin_branch)?{origin_branch:Se(p.origin_branch)}:{},...Fr(p.branch_lease)?{branch_lease:Fr(p.branch_lease)}:{},...Kr(p.origin_binding)?{origin_binding:Kr(p.origin_binding)}:{},...Qr(p.aggregate_qa_receipt)?{aggregate_qa_receipt:Qr(p.aggregate_qa_receipt)}:{},...Xr(p.head_reconciliation_receipt)?{head_reconciliation_receipt:Xr(p.head_reconciliation_receipt)}:{},...Et(p.pr_number)?{pr_number:Et(p.pr_number)}:{},...ee(p.physicalMergeStatus)?{physicalMergeStatus:ee(p.physicalMergeStatus)}:{},..._(p.graph_revision)?{graph_revision:_(p.graph_revision)}:{},...Zr(p.terminal_git_receipt)?{terminal_git_receipt:Zr(p.terminal_git_receipt)}:{},...C?{lifecycle_classification:C}:{}}}const y=Po(i.current_session??i.currentSession),w=h(i.archPlan)?hn(i.archPlan.execution):void 0,u=i.epic_id_ledger,v=Array.isArray(u?.reserved_ids)?[...new Set(u.reserved_ids.filter(I=>typeof I=="string"&&/^P\d+$/.test(I)))].slice(0,2048):[];return{schema_version:typeof i.schema_version=="number"?i.schema_version:void 0,config:{project_name:n.project_name??n.name??"unknown",default_branch:n.default_branch??"main",language:n.language??"pt-BR",yolo_mode:n.yolo_mode,user_name:n.user_name,worktree_base:n.worktree_base,max_parallel_stories:n.max_parallel_stories,project_id:typeof n.project_id=="string"?n.project_id:void 0},stories:s,epics:f,...v.length>0?{epic_id_ledger:{schema_version:1,reserved_ids:v}}:{},...y?{current_session:y}:{},...w?{archPlan:{execution:w}}:{}}}const Fn=[["P222.01","fbc3176b33687b13a8fadf8c7ea7cc06b6b6c500"],["P222.02","c7d3feb9a168f9e15b35516a972c767f3aa357da"],["P222.03","4d9bd4f2a1a3a1dc6399c572eb84b8b74c017806"],["P222.04","66590ef2f706c9d036f42edf5e517b237724f74f"],["P222.05","3ee2662538311e9788796340ed11b65864a8d8d5"],["P222.06","8660d07e3f68503a9ceb24dc138d24f62ab6cb45"],["P222.07","d99c80feacee8ea4033aa3322990147fffa2df91"],["P222.08","1f9e37dc922d87908efefb9595db32d32db30b00"],["P222.09","5ae12e485900992658e346cf3e38568fda1c2eeb"],["P222.10","6c5b8dc4f03d629fea4b62a33f4794af8e27e4f0"],["P222.11","cfe90f2f955c0027c57e4c621141d17912db65cc"],["P222.12","65f253c5cb600a8ee1dd94a1efdfef2fa5cd1629"],["P222.13","1e78c75b393515803a55d1a9b63a7fec23f710c9"],["P222.14","3f3e0bfd247a8581170df2a23c89497b5ae3641e"],["P222.15","1fd6dd25fffa5714d4ffa8b4303735e417f93de6"]],qn="6a41a47ff2521f80c2296ed811b0f0b304c54750",Yn="dbc6d4670b2b7868a01973b1240e24589f1c5b7d",ti="30dccfff07f9c969be11ae1d28e62a09731a0768";function No(e,t){try{const r=t.indexOf(ti);if(r<1||t[r-1]!==qn)return new Map;const i=$e("git",["show","--no-patch","--format=%P",ti],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim(),a=$e("git",["show","--no-patch","--format=%P",Yn],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim();if(i!==`${qn} ${Yn}`||a!==`${Fn.at(-1)[1]} ${qn}`)return new Map;const n=$e("git",["rev-list","--first-parent","--reverse",Yn],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
|
|
9
|
-
`),o=new Map;let
|
|
10
|
-
`).filter(Boolean),
|
|
11
|
-
`),{}}}function
|
|
12
|
-
`),a=new
|
|
13
|
-
`),t}function
|
|
14
|
-
`)}async function
|
|
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&<){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&<!==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)}
|
|
15
15
|
`:`[watch-status] status=${a.watchStatus} active=${a.active} summaries=${a.renderedSummaryCount} stop=${a.stopReason}
|
|
16
|
-
`);return}if(t==="json"){
|
|
17
|
-
`);return}
|
|
18
|
-
`)}function
|
|
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
19
|
`:`[watch] A local processing update is available.
|
|
20
|
-
`);return}if(t==="json"){
|
|
21
|
-
`);return}
|
|
22
|
-
`)}function Qn(e){return so.has(e.status)}function ic(e,t,r){if(t){const a=e.find(n=>n.jobId===t);return!!(a&&Qn(a))}return r<=0?!1:e.filter(a=>!Qn(a)).length===0}function ac(e,t,r,i){return r<i?!1:t?!e.some(a=>a.jobId===t&&!Qn(a)):e.length===0}function oc(e,t){return t?.aborted?Promise.resolve():new Promise(r=>{const i=setTimeout(a,e);function a(){clearTimeout(i),t?.removeEventListener("abort",a),r()}t?.addEventListener("abort",a,{once:!0})})}function cc(e){return e.includes(xe.MALFORMED)?"malformed":e.includes(xe.AMBIGUOUS)?"ambiguous":e.includes("watch-target-multiple")?"multiple":e.includes("watch-evidence-unsafe")?"unsafe":e.includes(xe.MISSING)||e.includes(Ce.TARGET_UNRESOLVED)?"unresolved":"unavailable"}function gi(e,t){const r=t?zt(t):void 0,i=De([...e,Ce.TARGET_UNRESOLVED,F.WATCH_TARGET_UNRESOLVED]),a=Kn(r,r?.targetId,cc(i),i),n=ct({generatedAt:new Date().toISOString()},[],!1,0,[F.WATCH_TARGET_UNRESOLVED]),o=Ze(void 0,void 0,void 0,[],[F.WATCH_TARGET_UNRESOLVED],"unavailable");return et({watchStatus:"blocked",active:!1,targetEvidence:a,snapshotEvidence:n,cursorEvidence:o,stopReason:"target_unresolved",reasonCodes:i,generatedAt:n.generatedAt})}function sc(e,t,r,i,a=!1){const n=gi(e,mi(t));return tt(n,r,i,a),st("target-unresolved",0,0,n,a)}async function dc(e){if(e.signal?.aborted){const P=Kn(e.target??zt(e.targetJobId),e.targetJobId,e.target??e.targetJobId?"resolved":"unresolved",[Ce.CANCELLED]),S=ct(void 0,[],!1,0),R=Ze(e.initialCursor,e.initialCursor,e.initialCursor,[],[Ce.CANCELLED],"unavailable"),Q=et({watchStatus:"stopped",active:!1,targetEvidence:P,snapshotEvidence:S,cursorEvidence:R,stopReason:"cancelled",reasonCodes:[Ce.CANCELLED]});return st("cancelled",0,0,Q,e.protectedOutput)}const t=e.target??zt(e.targetJobId),r=e.targetJobId??t?.targetId,i=e.stdout??process.stdout;if(!t){const P=gi([xe.MISSING,Ce.TARGET_UNRESOLVED]);return tt(P,e.format,i,e.protectedOutput),st("target-unresolved",0,0,P,e.protectedOutput)}const a=In(e.limit??En("NEOCORTEX_INVOKE_WATCH_LIMIT",Sr),Sr,50),n=Math.max(50,In(e.pollIntervalMs??En("NEOCORTEX_INVOKE_WATCH_POLL_INTERVAL_MS",wr),wr,6e4)),o=In(e.maxIdlePolls??En("NEOCORTEX_INVOKE_WATCH_MAX_IDLE_POLLS",vr),vr,120),s=In(e.maxPolls??En("NEOCORTEX_INVOKE_WATCH_MAX_POLLS",Cr),Cr,86400),l=e.sleep??oc;let f=e.initialCursor,y=0,w=0,u=0;const v=Kn(t,r,"resolved",[F.OK]),I={schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:"pending",renderedSummaryCount:0,reasonCodes:[F.WATCH_RENDER_PENDING],publicSafe:!0},p=Ze(e.initialCursor,f,f,[],e.initialCursor?[F.WATCH_CURSOR_UNCHANGED]:[F.WATCH_NO_SUMMARIES_YET],e.initialCursor?"unchanged":"not_started");tt(et({watchStatus:"active",active:!0,targetEvidence:v,snapshotEvidence:I,cursorEvidence:p,stopReason:"not_stopped",reasonCodes:[F.OK]}),e.format,i,e.protectedOutput);let C;try{C=await ia({projectRoot:e.projectRoot,strictReadOnly:e.strictReadOnly})}catch{const P=ct(void 0,[],!1,y,[F.WATCH_SNAPSHOT_UNAVAILABLE]),S=Ze(e.initialCursor,f,f,[],[F.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),R=et({watchStatus:"blocked",active:!1,targetEvidence:v,snapshotEvidence:P,cursorEvidence:S,stopReason:"unavailable_evidence",reasonCodes:[Ce.STORE_UNAVAILABLE]});return tt(R,e.format,i,e.protectedOutput),st("store-unavailable",y,u,R,e.protectedOutput)}try{for(;!e.signal?.aborted&&u<s;){u+=1;const P=f,S=C.collectProcessingOutputSummaryCursor({...f?{cursor:f}:{},...t?{target:t}:{},...r?{jobId:r}:{},limit:a}),R=C.collectSnapshot({jobLimit:50,processingSummaryLimit:1}),Q=R.jobs;if(S.summaries.length>0){for(const N of S.summaries)rc(N,e.format,i,e.protectedOutput),y+=1;f=S.nextCursor??S.summaries[S.summaries.length-1]?.cursor??f,w=0}else f=S.nextCursor??f,w+=1;const M=ct(R,S.summaries,!0,S.summaries.length),$=Ze(e.initialCursor,P,f,S.summaries,S.summaries.length>0?[F.WATCH_CURSOR_ADVANCED]:[F.WATCH_NO_SUMMARIES_YET]);if(tt(et({watchStatus:S.summaries.length>0?"polling":"waiting",active:!0,targetEvidence:v,snapshotEvidence:M,cursorEvidence:$,stopReason:"not_stopped",reasonCodes:S.summaries.length>0?[F.WATCH_CURSOR_ADVANCED]:[F.WATCH_NO_SUMMARIES_YET],generatedAt:R.generatedAt}),e.format,i,e.protectedOutput),!S.hasMore&&ic(Q,r,y)){const N=ct(R,S.summaries,!1,y,[Ce.COMPLETED]),ae=Ze(e.initialCursor,P,f,S.summaries,[Ce.COMPLETED],"exhausted"),D=et({watchStatus:"stopped",active:!1,targetEvidence:v,snapshotEvidence:N,cursorEvidence:ae,stopReason:"not_stopped",reasonCodes:[Ce.COMPLETED],generatedAt:R.generatedAt});return tt(D,e.format,i,e.protectedOutput),st("completed",y,u,D,e.protectedOutput)}if(!S.hasMore&&ac(Q,r,w,o)){const N=ct(R,S.summaries,!1,y,[F.WATCH_STOP_IDLE_LIMIT_REACHED]),ae=Ze(e.initialCursor,P,f,S.summaries,[F.WATCH_STOP_IDLE_LIMIT_REACHED],"exhausted"),D=et({watchStatus:"stopped",active:!1,targetEvidence:v,snapshotEvidence:N,cursorEvidence:ae,stopReason:"idle_limit_reached",reasonCodes:[Ce.IDLE_TIMEOUT,F.WATCH_STOP_IDLE_LIMIT_REACHED],generatedAt:R.generatedAt});return tt(D,e.format,i,e.protectedOutput),st("idle-timeout",y,u,D,e.protectedOutput)}S.hasMore||await l(n,e.signal)}}catch{const P=ct(void 0,[],!1,y,[F.WATCH_SNAPSHOT_UNAVAILABLE]),S=Ze(e.initialCursor,f,f,[],[F.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),R=et({watchStatus:"blocked",active:!1,targetEvidence:v,snapshotEvidence:P,cursorEvidence:S,stopReason:"unavailable_evidence",reasonCodes:[Ce.STORE_UNAVAILABLE]});return tt(R,e.format,i,e.protectedOutput),st("store-unavailable",y,u,R,e.protectedOutput)}finally{C.close()}if(e.signal?.aborted){const P=ct(void 0,[],!1,y,[Ce.CANCELLED]),S=Ze(e.initialCursor,f,f,[],[Ce.CANCELLED],"unavailable"),R=et({watchStatus:"stopped",active:!1,targetEvidence:v,snapshotEvidence:P,cursorEvidence:S,stopReason:"cancelled",reasonCodes:[Ce.CANCELLED]});return tt(R,e.format,i,e.protectedOutput),st("cancelled",y,u,R,e.protectedOutput)}const O=ct(void 0,[],!1,y,[F.WATCH_STOP_MAX_POLLS_REACHED]),V=Ze(e.initialCursor,f,f,[],[F.WATCH_STOP_MAX_POLLS_REACHED],"exhausted"),T=et({watchStatus:"stopped",active:!1,targetEvidence:v,snapshotEvidence:O,cursorEvidence:V,stopReason:"max_polls_reached",reasonCodes:[Ce.MAX_POLLS,F.WATCH_STOP_MAX_POLLS_REACHED]});return tt(T,e.format,i,e.protectedOutput),st("max-polls",y,u,T,e.protectedOutput)}function ze(e){const t=e.trim().replace(/^@/,"").match(/^(job|goal|loop)-([JGL])(\d{3,})$/i);if(!t)return;const r=t[1].toLowerCase(),i=t[2].toUpperCase();if(!(r==="job"&&i!=="J"||r==="goal"&&i!=="G"||r==="loop"&&i!=="L"))return`${r}-${i}${t[3]}`}function Xn(e){if(e.startsWith("job-J"))return"job";if(e.startsWith("goal-G"))return"goal";if(e.startsWith("loop-L"))return"loop"}function fi(e){const t=[],r=/(?:^|[\s"'([,{])@?(job-[Jj]\d{3,}|goal-[Gg]\d{3,}|loop-[Ll]\d{3,})(?=$|[\s"')\]},.;:!?])/g;let i;for(;(i=r.exec(e))!==null;){const a=ze(i[1]);a&&t.push(a)}return De(t)}function mi(e){return fi(e)[0]}function zt(e){const t=e?ze(e):void 0;if(t){if(t.startsWith("job-J"))return{selectorKind:"job",targetId:t,jobId:t,publicSafe:!0};if(t.startsWith("goal-G"))return{selectorKind:"goal",targetId:t,goalId:t,publicSafe:!0};if(t.startsWith("loop-L"))return{selectorKind:"loop",targetId:t,loopId:t,publicSafe:!0}}}function Zn(e){return De(e.filter(t=>typeof t=="string").map(t=>ze(t)).filter(t=>!!t?.startsWith("job-J")))}function pc(e,t){const r=Zn(t).filter(i=>i!==e.targetId&&i!==e.jobId);return r.length>0?{...e,relatedJobIds:r}:e}function lc(e){if(!e)return;const t=h(e.target)?e.target:void 0,r=typeof e.selectorKind=="string"?e.selectorKind:typeof t?.selectorKind=="string"?t.selectorKind:void 0,i=typeof e.targetId=="string"?ze(e.targetId):typeof t?.targetId=="string"?ze(t.targetId):typeof e.targetJobId=="string"?ze(e.targetJobId):void 0,a=zt(i);if(!a||r&&r!==a.selectorKind)return;const n=Array.isArray(e.relatedJobIds)?e.relatedJobIds:Array.isArray(t?.relatedJobIds)?t.relatedJobIds:void 0,o=Zn([...n??[],e.jobId,t?.jobId,e.targetJobId,t?.targetJobId]).filter(s=>s!==a.targetId&&s!==a.jobId);return{...a,...typeof(e.jobId??t?.jobId)=="string"?{jobId:ze(e.jobId??t?.jobId)??a.jobId}:{},...typeof(e.goalId??t?.goalId)=="string"?{goalId:ze(e.goalId??t?.goalId)??a.goalId}:{},...typeof(e.loopId??t?.loopId)=="string"?{loopId:ze(e.loopId??t?.loopId)??a.loopId}:{},...o.length>0?{relatedJobIds:o}:{}}}function yi(e){const t=e.trim().split(/\s+/).filter(Boolean),r=t[0]?.replace(/^\*/,"").toLowerCase(),i=t[1]?.replace(/^--/,"").toLowerCase();return(r==="jobs"||r==="job"||r==="continuity-jobs"||r==="61")&&i==="watch"}const Ae=Object.freeze({ACTIVE:"command-level-watch-active",INACTIVE:"command-level-watch-inactive",DUPLICATE:"command-level-watch-duplicate",AMBIGUOUS:"command-level-watch-ambiguous",QUOTED:"command-level-watch-quoted",MALFORMED:"command-level-watch-malformed",NON_FINAL:"command-level-watch-non-final",UNRESOLVED:"command-level-watch-unresolved",UNSUPPORTED:"command-level-watch-unsupported",TARGET_INVALID:"command-level-watch-target-invalid"}),uc=new Set(["create","start","resume"]),hc=new Set(["create","resume","run-once"]);function er(e,t,r,i,a){return{schemaVersion:1,contractVersion:"continuity-v1",...r?{command:r}:{},...i?{operation:i}:{},active:e,...a?{watchToken:a}:{},reasonCodes:De(t),serverHeldStream:!1,allJobsPolling:!1,targetResolution:e?"required-after-dispatch":"inactive",publicSafe:!0}}function Pe(e,t=[],r,i){const a=t.length>0?t:[Ae.INACTIVE];return{args:e,watch:!1,reasonCodes:a,metadata:er(!1,a,r,i),publicSafe:!0}}function gc(e){const t=e.trim().split(/\s+/).filter(Boolean),r=t.slice(2).filter(n=>n==="--watch").length;if(r===0)return Pe(e,[],"jobs","watch");if(r!==1)return Pe(e,[Ae.AMBIGUOUS],"jobs","watch");const i=t.filter((n,o)=>o<2||n!=="--watch").join(" ");return yi(i)?i.trim().split(/\s+/).filter(Boolean).slice(2).length!==1?Pe(e,[Ae.AMBIGUOUS],"jobs","watch"):mi(i)?{args:i,watch:!0,reasonCodes:[Ae.ACTIVE],metadata:er(!0,[Ae.ACTIVE],"jobs","watch"),publicSafe:!0}:Pe(e,[Ae.TARGET_INVALID],"jobs","watch"):Pe(e,[Ae.UNSUPPORTED],"jobs","watch")}function fc(e){const t=[];let r=!1,i=0;for(;i<e.length;){for(;i<e.length&&/\s/.test(e[i]);)i+=1;if(i>=e.length)break;const a=i;let n="",o=!1,s=null;for(;i<e.length;){const l=e[i];if(s){if(l===s){o=!0,s=null,i+=1;continue}if(l==="\\"&&i+1<e.length){n+=e[i+1],i+=2;continue}n+=l,i+=1;continue}if(/\s/.test(l))break;if(l==='"'||l==="'"){o=!0,s=l,i+=1;continue}n+=l,i+=1}s&&(r=!0),t.push({value:n,start:a,end:i,quoted:o})}return{tokens:t,malformed:r}}function mc(e){if(!e||e.quoted)return;const t=e.value.replace(/^\*/,"").toLowerCase();return t==="goal"||t==="loop"?t:void 0}function yc(e,t){if(!e||e==="jobs"||!t||t.quoted)return;const r=t.value.toLowerCase();return(e==="goal"?uc:hc).has(r)?r:void 0}function Ic(e){return!e.quoted&&e.value!=="--watch"&&e.value.toLowerCase().startsWith("--watch")}function Ec(e){const{tokens:t,malformed:r}=fc(e),i=mc(t[0]),a=yc(i,t[1]);if(r)return Pe(e,[Ae.MALFORMED],i,a);const n=t.filter(u=>u.value==="--watch"&&!u.quoted),o=t.filter(u=>u.value==="--watch"&&u.quoted),s=t.filter(Ic);if(!(n.length>0||o.length>0||s.length>0))return Pe(e,[],i,a);if(n.length>1)return Pe(e,[Ae.DUPLICATE],i,a);if(n.length===1&&(o.length>0||s.length>0))return Pe(e,[Ae.AMBIGUOUS],i,a);if(o.length>0)return Pe(e,[Ae.QUOTED],i,a);if(s.length>0)return Pe(e,[Ae.MALFORMED],i,a);const f=n[0];if(!f)return Pe(e,[],i,a);if(t[t.length-1]!==f)return Pe(e,[Ae.NON_FINAL],i,a);if(!i||!a)return Pe(e,[Ae.UNRESOLVED],i,a);const y=`${e.slice(0,f.start)}${e.slice(f.end)}`.trim(),w={literal:"--watch",position:"final",start:f.start,end:f.end,quoted:!1,publicSafe:!0};return{args:y,watch:!0,reasonCodes:[Ae.ACTIVE],metadata:er(!0,[Ae.ACTIVE],i,a,w),publicSafe:!0}}function Sc(e){return yi(e)?gc(e):Ec(e)}function vc(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&po.has(t)):[]}function Ut(e){return{disabled:!0,reasonCodes:De(e.length>0?e:[xe.MISSING])}}function tr(e,t,r=[],i){const a=zt(t);if(a)return{source:e,target:pc(a,r),targetJobId:a.targetId,...i?{initialCursor:i}:{},serverHeldStream:!1}}function Cc(e){const t=new Map;for(const r of e){const i=`${r.target.selectorKind}:${r.target.targetId}`,a=t.get(i);if(!a){t.set(i,r);continue}const n=De([...a.target.relatedJobIds??[],...r.target.relatedJobIds??[]]);t.set(i,{...a,target:n.length>0?{...a.target,relatedJobIds:n}:a.target,initialCursor:a.initialCursor??r.initialCursor})}return Array.from(t.values())}function St(e,t,r,i){return{source:e,hasEvidence:t,candidates:Cc(r.filter(a=>!!a)),...i&&i.length>0?{disabledReasonCodes:De(i)}:{}}}function wc(e,t){return e.target.selectorKind===t.target.selectorKind&&e.target.targetId===t.target.targetId}function Kt(e,t){const r=De(e.filter(i=>typeof i=="string").map(i=>ze(i)).filter(i=>!!i));if(t){const i=r.find(a=>Xn(a)===t);if(i)return i}return r[0]}function Sn(e,t){return De(e.filter(r=>typeof r=="string").map(r=>ze(r)).filter(r=>!!r)).find(r=>Xn(r)===t)}function _c(e){const t=h(e?.continuity)?e.continuity:void 0,r=h(t?.jobs)?t.jobs:void 0,i=h(r?.watcher)?r.watcher:void 0,a=vc(i?.reasonCodes??r?.reasonCodes);if(!i)return St("watcher-metadata",a.length>0,[],a);if(i.active===!1||a.length>0)return St("watcher-metadata",!0,[],a.length>0?a:[xe.MALFORMED]);if(i.serverHeldStream!==!1)return St("watcher-metadata",!0,[],[xe.SERVER_HELD_STREAM]);const n=lc(i);if(!n)return St("watcher-metadata",!0,[],[xe.MISSING]);const o=typeof i.initialCursor=="string"?i.initialCursor:void 0;return St("watcher-metadata",!0,[{source:"watcher-metadata",target:n,targetJobId:n.targetId,...o?{initialCursor:o}:{},serverHeldStream:!1}])}function Ii(e,t){const r=h(e.loopJobPlan)?e.loopJobPlan:void 0,i=h(r?.metadata)?r.metadata:void 0,a=h(e.metadata)?e.metadata:void 0,o=(t==="goal"?Kt([e.goalId,e.targetGoalId,e.campaignId,e.jobId,e.targetJobId,a?.goalId,a?.campaignId,a?.jobId],"goal"):Kt([e.loopId,e.targetLoopId,e.jobId,e.targetJobId,a?.loopId,a?.jobId,i?.loopId,i?.jobId],"loop"))??Kt([e.jobId,e.targetJobId,a?.jobId,i?.jobId]);return tr("goal-loop-continuity-metadata",o,[e.jobId,e.targetJobId,a?.jobId,i?.jobId])}function Rc(e){const t=h(e?.continuity)?e.continuity:void 0,r=h(t?.goal)?t.goal:void 0,i=h(t?.loop)?t.loop:void 0,a=[r?Ii(r,"goal"):void 0,i?Ii(i,"loop"):void 0],n=!!(r||i);return St("goal-loop-continuity-metadata",n,a,n&&a.every(o=>!o)?[xe.MISSING]:void 0)}function Ac(e){return Array.isArray(e)?e.filter(h):h(e)?Array.isArray(e.operationLogs)?e.operationLogs.filter(h):h(e.operationLog)?[e.operationLog]:Array.isArray(e.operations)?[e]:[]:[]}function Ei(e,t){const r=h(t.metadata)?t.metadata:void 0,i=Sn([t.goalId,t.targetGoalId,t.campaignId,r?.goalId,r?.campaignId,t.jobId,r?.jobId],"goal"),a=Sn([t.loopId,t.targetLoopId,r?.loopId,t.jobId,r?.jobId],"loop"),n=Kt([t.jobId,t.targetJobId,r?.jobId],"job"),o=i??a??n;if(!o)return;const s=e.get(o)??{targetId:o,relatedJobIds:[]};s.relatedJobIds.push(...Zn([n,t.jobId,t.targetJobId,r?.jobId])),e.set(o,s)}function bc(e){const t=h(e.metadata)?e.metadata:void 0;return!!(Sn([e.goalId,e.targetGoalId,e.campaignId,t?.goalId,t?.campaignId,e.jobId,t?.jobId],"goal")??Sn([e.loopId,e.targetLoopId,t?.loopId,e.jobId,t?.jobId],"loop"))}function xc(e){const t=h(e.metadata)?e.metadata:void 0;return!!Kt([e.goalId,e.targetGoalId,e.campaignId,e.loopId,e.targetLoopId,e.jobId,e.targetJobId,t?.goalId,t?.campaignId,t?.loopId,t?.jobId])}function Si(e,t){const r=[];for(const o of["metadata","job","event","receipt","processingOutputSummary"]){const s=t[o];h(s)&&r.push(s)}const i=h(t.event)?t.event:void 0;h(i?.metadata)&&r.push(i.metadata),h(i?.processingOutputSummary)&&r.push(i.processingOutputSummary);const a=h(t.receipt)?t.receipt:void 0;h(a?.metadata)&&r.push(a.metadata);const n=r.some(xc);for(const o of r)Ei(e,o);(!n||bc(t))&&Ei(e,t)}function Tc(e){const t=Ac(e?.continuityStateUpdate),r=new Map;for(const a of t){Si(r,a);const n=Array.isArray(a.operations)?a.operations.filter(h):[];for(const o of n)Si(r,o)}const i=Array.from(r.values()).map(a=>tr("continuity-state-update-operation-log",a.targetId,a.relatedJobIds));return St("continuity-state-update-operation-log",t.length>0,i,t.length>0&&i.every(a=>!a)?[xe.MISSING]:void 0)}function Pc(e){const t=fi(e);return St("explicit-args",t.length>0,t.map(r=>tr("explicit-args",r)))}function kc(e,t){const r=[_c(e),Rc(e),Tc(e),Pc(t)];for(let i=0;i<r.length;i+=1){const a=r[i];if(!a.hasEvidence)continue;if(a.disabledReasonCodes&&a.disabledReasonCodes.length>0)return Ut(a.disabledReasonCodes);if(a.candidates.length!==1)return Ut([a.candidates.length>1?xe.AMBIGUOUS:xe.MISSING]);const n=a.candidates[0];for(const o of r.slice(i+1)){if(!o.hasEvidence)continue;if(o.disabledReasonCodes&&o.disabledReasonCodes.length>0)return Ut(o.disabledReasonCodes);if(o.candidates.length>1)return Ut([xe.AMBIGUOUS]);const s=o.candidates[0];if(s&&!wc(n,s))return Ut([xe.CONFLICT])}return{target:n.target,targetJobId:n.targetJobId,...n.initialCursor?{initialCursor:n.initialCursor}:{},source:n.source,serverHeldStream:!1}}return Ut([xe.MISSING])}async function vi(e,t,r,i={}){const a="/api/v1/invoke";let n,o;const s=await Jt(e,a,t,r,{...i,deferSuccessfulJsonParsing:!0,...t.privateExecution?{maxAttempts:1,allowReplayRetry:!1}:{},admitResponseBeforeBodyRead:w=>{const u=w.headers.get("X-Neocortex-Compatibility");if(u!==null)try{if(u.length===0||u.length>8192)throw new Error("header-size");const v=JSON.parse(Buffer.from(u,"base64url").toString("utf8"));if(!Aa(v))throw new Error("header-shape");if(n=v,v.status==="incompatible")return o="incompatible",!1}catch{return o="malformed",!1}return i.admitResponseBeforeBodyRead?.(w)??!0}});if(s.networkFailure||!s.response)return{ok:!1,status:0,error:"Network error after bounded retries"};if(s.responseAdmissionRejected){const w=o==="malformed"?jt.RESULT_MALFORMED:n?.reasonCodes[0]??jt.OFFER_MALFORMED;return{ok:!1,status:s.response.status,error:`COMPATIBILITY_INCOMPATIBLE: ${w}`,errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:w,fallback_action:n?.remediationHint??"upgrade-client"},...n?{compatibility:n}:{}}}const{response:l,text:f}=s;let y=s.parsed;try{if(t.compatibility&&!n){if(/"(?:reviewReconciliation|review_reconciliation|reconciliationMetadata|releaseLifecycle|release_lifecycle|releaseBlocked|release_blocked|yoloopReleaseBlocked)"\s*:/u.test(f))return{ok:!1,status:l.status,error:`COMPATIBILITY_INCOMPATIBLE: ${jt.UNNEGOTIATED_PROTECTED_FIELD}`,errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:jt.UNNEGOTIATED_PROTECTED_FIELD,fallback_action:"upgrade-client"}};n=Ra({clientVersion:t.compatibility.clientVersion,serverVersion:"0.0.0",registryVersion:t.registryVersion,registryChecksum:t.registryChecksum,reason:jt.SERVER_NEGOTIATION_MISSING})}if(l.ok)try{y=f?JSON.parse(f):{}}catch{return{ok:!1,status:l.status,error:"COMPATIBILITY_INCOMPATIBLE: response-json-malformed",errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:jt.RESULT_MALFORMED},...n?{compatibility:n}:{}}}if(!l.ok)return t.privateExecution?{ok:!1,status:l.status,error:"private-execution-invoke-unavailable"}:{ok:!1,status:l.status,error:Object.keys(y).length>0?`${y.error_code??"ERROR"}: ${y.message??f}`:`HTTP ${l.status}: ${f}`,errorBody:Object.keys(y).length>0?y:void 0,...n?{compatibility:n}:{}};const w=y,u=l.headers.get("X-Client-Version-Warning");return u&&!ai&&(ai=!0,process.stderr.write(`
|
|
20
|
+
`);return}if(t==="json"){i.write(JSON.stringify(Cc(e))+`
|
|
21
|
+
`);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(`
|
|
23
23
|
[Neocortex] ${u}
|
|
24
24
|
|
|
25
|
-
`)),{ok:!0,status:l.status,data:w,...n?{compatibility:n}:{}}}catch(w){return{ok:!1,status:0,error:(w instanceof Error?w.message:String(w)).includes("abort")?`Request timeout after ${Lr/1e3}s`:"Network error: invalid response"}}}async function Oc(e,t,r){const i=await Jt(e,"/api/v1/invoke/private-execution/consume",t,r,{maxAttempts:1,allowReplayRetry:!1});if(i.networkFailure||!i.response||!i.response.ok)throw new Error("private-execution-delivery-unavailable");return i.parsed}async function Nc(e,t,r){const i=await Jt(e,"/api/v1/invoke/private-execution/cancel",t,r,{maxAttempts:1,allowReplayRetry:!1});return!!i.response?.ok&&i.parsed.status==="cancelled"}async function Ci(e,t,r,i={}){const a=await Jt(e,"/api/v1/invoke/epic-claims/acknowledge",{...r,registryVersion:yt,registryChecksum:mt},t,i);return!!a.response?.ok&&a.parsed.status==="ok"&&a.parsed.claimOutcome===r.status&&(!r.planningCheckpoint||a.parsed.memoryReceiptId===r.planningCheckpoint.memoryReceiptId)}async function Lc(e,t,r,i,a,n={}){if(!a)return 0;const o=Vt(e);let s=0;for(const[l,f]of Object.entries(o.operations))f.planningProtocol==="root-staged-v1"||!f.claimId||!f.epicId||!t.epics?.[f.epicId]||!await Ci(r,i,{claimId:f.claimId,projectId:a,epicId:f.epicId,status:"materialized"},n)||(no(e,l),s+=1);return s}function Dc(e,t){const r=t.state.pendingContinuationAuthorities,i=t.state.continuationSession;if(t.state.continuationPolicy!=="p205-finite-resume-v2"||r?.length!==1||!i)return;const a=r[0],n=a.certificate,o=n?.expectedTransition;if(a.storyIds!=="[CIRCULAR]"||n?.rank!=="[CIRCULAR]"||o?.selectedStoryIds!=="[CIRCULAR]")return;const s=typeof i.epicId=="string"?i.epicId:"",l=e.epics[s],f=Array.isArray(o.storyLifecycle)?o.storyLifecycle:[],y=f.length===1&&typeof f[0]?.storyId=="string"?f[0].storyId:"",u=e.stories[y]?.checkpoint;if(!l||l.branch_mode!=="epic"||typeof l.execution_branch!="string"||typeof l.origin_branch!="string"||l.branch_lease!==void 0&&l.branch_lease!==null||!u||u.qaVerdict!=="passed"||u.reviewVerdict!=="approved"||!Array.isArray(u.receiptRefs))return;const I=(Array.isArray(l.stories)?l.stories.filter(p=>typeof p=="string"):[]).find(p=>{const C=e.stories[p];return!C||["done","completed","merged"].includes(String(C.status))?!1:(Array.isArray(C.depends_on)?C.depends_on.filter(V=>typeof V=="string"):[]).every(V=>["done","completed","merged"].includes(String(e.stories[V]?.status)))});if(I)return{epicId:s,expectedNextStoryId:I,branchMode:"epic",executionBranch:l.execution_branch,originBranch:l.origin_branch,branchLeaseReleased:!0,checkpoint:{schemaVersion:1,storyId:u.storyId,epicId:u.epicId,branch:u.branch,baseSha:u.baseSha,headSha:u.headSha,receiptRefs:[...u.receiptRefs],qaVerdict:"passed",reviewVerdict:"approved"}}}async function Mc(e){let t;try{if(t=e.inputEnvelope??cn(e.inputSource??"args",e.args),Ea(t),t.rawArgs!==e.args)throw new Error("INVOKE_INPUT_ENVELOPE_ARGUMENT_CONFLICT")}catch{return{success:!1,error:"INVOCATION_MALFORMED_INPUT: explicit input integrity could not be verified.",errorCode:"INVOCATION_MALFORMED_INPUT",metadata:{invocationInput:{reason:"input-integrity-conflict",remediation:"Retry with exactly one of --args, --stdin or --args-file.",publicSafe:!0}},exitCode:1}}const r=t.rawArgs,i=br(t);let a=r,n=i;const o=co(r);if(o.outcome!=="resolved"){const c=va(o,"client"),d=o.outcome==="malformed_input"?o.reason==="input_limit"||o.reason==="token_limit"||o.reason==="token_size_limit"?"input-limit-exceeded":o.reason==="invalid_control"||o.reason==="invalid_surrogate"?"invalid-control-character":o.reason==="unterminated_quote"||o.reason==="trailing_escape"||o.reason==="unsupported_escape"?"unterminated-quote":void 0:void 0,m=d?{code:"INVOCATION_MALFORMED_INPUT",reason:d,source:t.source,byteLength:t.byteLength,remediation:d==="input-limit-exceeded"?"Reduce the explicit command input or split the requested work into bounded invocations.":d==="invalid-control-character"?"Remove invalid control characters and retry with valid UTF-8 text.":"Close quotes and escapes, or use --stdin/--args-file for multiline content."}:void 0;return{success:!1,error:`INVOCATION_${o.outcome.toUpperCase()}`,errorCode:`INVOCATION_${o.outcome.toUpperCase()}`,metadata:{invocationAdmission:c,...m?{invocationInput:m}:{}},exitCode:1}}if(e.privateExecutionModel!==void 0&&(!e.privateExecutionBeta||e.strictReadOnly||!/^gpt-[a-z0-9][a-z0-9.-]{0,63}$/.test(e.privateExecutionModel)))return{success:!1,error:"private-codex-model-invalid",errorCode:"private-codex-model-invalid",exitCode:1};const s=jn(e.projectRoot),l=o.selection.commandId,f=l==="yolo"&&!Ir(r,l)?Wa(r):null,y=l==="tech-debt"&&o.selection.positionals.length===0&&(o.selection.operationId==="scan"&&Object.keys(o.selection.options).length===0||o.selection.operationId===void 0&&o.selection.options.scan===!0&&Object.keys(o.selection.options).length===1),w=Hi.find(c=>c.id===l),u=w?.subcommands.find(c=>c.id===o.selection.operationId),v=u?u.policy.strictReadOnly==="allow":w?.policy.strictReadOnly==="allow",I=l==="diagnose";let p;try{p=ma({invocationId:nn(),intent:e.strictReadOnly||I?{schemaVersion:1,policy:ha,registryVersion:yt,registryChecksum:mt}:void 0,registryVersion:yt,registryChecksum:mt,registryAllowsStrict:v,requestCanonicalBytes:JSON.stringify({command:l})})}catch(c){if(c instanceof Dt)return{success:!1,error:c.code,errorCode:c.code,exitCode:1};throw c}{p.beginProjection();for(const c of Ar)p.project(c);for(const c of ga)p.project(c);p.seal()}const C=p.mode==="strict";if(l==="create-epic"||l==="idea-diagnose")try{const c=Pa(s);if(c&&c!=="finalized")return{success:!1,error:'PROJECT_IDENTITY_MIGRATION_INCOMPLETE: retry `neocortex-client invoke --args "*migrate-project-id"` before create-epic.',errorCode:"PROJECT_IDENTITY_MIGRATION_INCOMPLETE",metadata:{projectIdentityMigration:{phase:c,publicSafe:!0}},exitCode:1}}catch(c){const d=c instanceof Nn?c.code:"PROJECT_IDENTITY_MIGRATION_STATE_CORRUPT";return{success:!1,error:d,errorCode:d,exitCode:1}}const O=e.environment??process.env;if(e.privateExecutionBeta&&(l!=="yolo"&&l!=="research"&&l!=="write-spec"&&l!=="create-tasks"&&l!=="implement"&&l!=="exec"&&l!=="create-epic"&&l!=="idea-diagnose"&&l!=="idea-research"&&l!=="generate-epic"&&l!=="sync-openapi"&&l!=="chaos-plan"&&l!=="ui-ux-review"&&l!=="arch-prd"&&l!=="arch-architecture"&&l!=="arch-fitness-functions"&&l!=="arch-api-contracts"&&l!=="arch-api-integrations"&&l!=="arch-database"&&l!=="arch-security"&&l!=="arch-design-system"&&l!=="arch-performance"&&l!=="arch-testing"&&l!=="arch-infrastructure"&&l!=="arch-review"&&l!=="update-memory"&&l!=="arch-ux-design"&&l!=="generate-pacts"&&l!=="property-test"&&!y||C||e.platformTarget!==void 0&&e.platformTarget!=="codex"))return{success:!1,error:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",errorCode:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",exitCode:1};const V=sa({cwd:s,env:O,targetFlag:e.privateExecutionBeta?"codex":e.platformTarget}),T=V.targetId,P=e.privateExecutionBeta?void 0:ca({cwd:s,env:O,targetFlag:e.platformTarget,nativeHostVersion:mo(V,O)},V);if(f)try{Wn(s,{allowMissingRuntime:!0})}catch(c){const d=c instanceof ot?c.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${d}. No request was sent; repair the canonical project state/runtime sidecar and retry.
|
|
26
|
-
`),{success:!1,error:d,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}let
|
|
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}}
|
|
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}
|
|
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
|
|
31
|
-
`),{success:!1,error:d,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}if(l!=="migrate-state")try{
|
|
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}
|
|
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
|
|
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.
|
|
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=
|
|
37
|
-
`)}try{const{readYoloopForRequest:c}=await import("../yoloop/invoke-hooks.js"),d=await c(e.args,s);if(d){const m=
|
|
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,
|
|
39
|
-
`)}try{const{maybeRunDiscoveryHook:c}=await import("../yoloop/invoke-hooks.js");await c({args:e.args,projectRoot:s,stateSnapshot:
|
|
40
|
-
`)}try{const{readArchitecturePolicy:c}=await import("../policy/architecture-policy.js"),d=await c(s);d&&(
|
|
41
|
-
`)}});m.applied&&m.metadata&&(
|
|
42
|
-
`)}try{if(
|
|
43
|
-
`)}try{const c=await
|
|
44
|
-
`)}const
|
|
45
|
-
`),{success:!1,error:c.message??"Trigger not available on your plan",exitCode:1}}catch{}const
|
|
46
|
-
`),!
|
|
47
|
-
`),{success:!1,error:
|
|
48
|
-
`),{success:!1,error:d,errorCode:c.code,metadata:{stateProjection:c,publicSafe:!0},exitCode:1}}k=c?.snapshot??
|
|
49
|
-
`),{success:!1,error:d,errorCode:c.code,metadata:{structuralProjection:{...c.publicDetails,publicSafe:!0}},exitCode:1}}throw c}if(!
|
|
50
|
-
`),{success:!1,error:c,errorCode:"EPIC_PROJECT_ID_REQUIRED",exitCode:1}}let we;try{we=p.execute({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>G==="create-epic"||G==="idea-diagnose"?to(s,D,G):void 0,()=>{})}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const We=we?.key??(G==="yolo"?ro(s,D,Ne,k):void 0);if(e.privateExecutionBeta&&G==="create-epic"&&we){const c=Vt(s).operations[we.fingerprint],d=c?.epicId?N.epics[c.epicId]:void 0,m=h(d?.createEpicPlanningPhysical)?d.createEpicPlanningPhysical:void 0;c?.claimId&&c.epicId&&d&&m?.claimId===c.claimId&&(k={...k,epics:{...k.epics,[c.epicId]:d},stories:{...k.stories,...Object.fromEntries((Array.isArray(d.stories)?d.stories:[]).filter(b=>typeof b=="string"&&N.stories[b]?.epic_id===c.epicId).map(b=>[b,N.stories[b]]))}})}const Fe=C?{schemaVersion:1,invocationId:p.invocationId,intent:p.intent,clientProjection:fa(Ar.map(c=>({...c,count:1})))}:void 0;let Z,ue,oe;if(e.privateExecutionBeta&&G==="idea-research")try{const c=k.scope?.targetEpicId,d=c?k.epics[c]:void 0,m=h(d?.createEpicPlanningPhysical)?d.createEpicPlanningPhysical:void 0;if(!c||!m||typeof m.claimId!="string"||typeof m.receiptId!="string")throw new Error("planning-research-predecessor-unavailable");const b=K(s,".neocortex/state.json"),U=Lt(b);if(!U.isFile()||U.isSymbolicLink()||U.size>8*1024*1024)throw new Error("planning-research-state-unavailable");const he=He(b),de=JSON.parse(he.toString("utf8")),ne=pr(de,m.claimId,c),ge=h(de)&&h(de.epics)&&h(de.epics[c])?de.epics[c]:void 0,B=h(ge?.createEpicPlanningPhysical)?ge.createEpicPlanningPhysical:void 0;if(B?.receiptId!==m.receiptId||!E(B,m))throw new Error("planning-research-predecessor-drift");const Ie=[".neocortex/state.json",".neocortex/planning/planning.json",`.neocortex/planning/epic-${c}/idea.json`,`.neocortex/planning/epic-${c}/diagnosis.md`,`.neocortex/planning/epic-${c}/enriched-prompt.md`],Me={...process.env};for(const fe of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete Me[fe];for(const fe of Ie){const je=Lt(K(s,fe));if(!je.isFile()||je.isSymbolicLink()||je.size>8*1024*1024)throw new Error("planning-research-source-unavailable");const Qe=$e("git",["show",`HEAD:${fe}`],{cwd:s,env:Me,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!He(K(s,fe)).equals(Qe))throw new Error("planning-research-source-uncommitted")}ue={claimId:m.claimId,epicId:c,diagnosisReceiptId:ne.diagnosisReceiptId,intakeRevision:ne.intakeRevision,physicalAcceptanceReceiptId:m.receiptId,sourceStateSha256:Ue("sha256").update(he).digest("hex")}}catch{return{success:!1,error:"private-execution-planning-predecessor-unavailable",errorCode:"private-execution-planning-predecessor-unavailable",exitCode:1}}if(e.privateExecutionBeta&&G==="generate-epic")try{const c=k.scope?.targetEpicId,d=c?k.epics[c]:void 0,m=h(d?.createEpicPlanningResearchPhysical)?d.createEpicPlanningResearchPhysical:void 0;if(!c||!m||typeof m.claimId!="string"||typeof m.receiptId!="string")throw new Error("planning-generation-predecessor-unavailable");const b=K(s,".neocortex/state.json"),U=Lt(b);if(!U.isFile()||U.isSymbolicLink()||U.size>8*1024*1024)throw new Error("planning-generation-state-unavailable");const he=He(b),de=JSON.parse(he.toString("utf8")),ne=lr(de,m.claimId,c),ge=h(de)&&h(de.epics)&&h(de.epics[c])?de.epics[c]:void 0,B=h(ge?.createEpicPlanningResearchPhysical)?ge.createEpicPlanningResearchPhysical:void 0;if(B?.receiptId!==m.receiptId||!E(B,m))throw new Error("planning-generation-predecessor-drift");const Ie=[".neocortex/state.json",".neocortex/planning/planning.json",`.neocortex/planning/epic-${c}/idea.json`,`.neocortex/planning/epic-${c}/diagnosis.md`,`.neocortex/planning/epic-${c}/enriched-prompt.md`,`.neocortex/planning/epic-${c}/research.md`],Me={...process.env};for(const fe of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete Me[fe];for(const fe of Ie){const je=Lt(K(s,fe));if(!je.isFile()||je.isSymbolicLink()||je.size>8*1024*1024)throw new Error("planning-generation-source-unavailable");const Qe=$e("git",["show",`HEAD:${fe}`],{cwd:s,env:Me,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!He(K(s,fe)).equals(Qe))throw new Error("planning-generation-source-uncommitted")}oe={claimId:m.claimId,epicId:c,diagnosisReceiptId:ne.diagnosisReceiptId,researchReceiptId:ne.researchReceiptId,intakeRevision:ne.intakeRevision,physicalAcceptanceReceiptId:ne.physicalAcceptanceReceiptId,sourceStateSha256:Ue("sha256").update(he).digest("hex")}}catch{return{success:!1,error:"private-execution-planning-predecessor-unavailable",errorCode:"private-execution-planning-predecessor-unavailable",exitCode:1}}if(e.privateExecutionBeta)try{const{preflightPrivateCodexExecutor:c}=await import("../private-execution/codex-executor.js");Z=await c(s)}catch(c){const d=c instanceof Error&&/^private-codex-[a-z-]+$/.test(c.message)?c.message:"private-codex-preflight-unavailable";return{success:!1,error:d,errorCode:d,exitCode:1}}const vt=Z?{schemaVersion:1,hostKind:"codex-cli",hostVersion:Z.hostVersion,sandboxProof:{schemaVersion:6,trust:"client-self-attested",credentialKind:"chatgpt-subscription",authIsolation:"passed",workspaceWrite:"passed",gitControlWriteDenied:"passed",gitLifecycleReadDenied:"passed",mcpIsolation:"passed",environmentIsolation:"passed",networkDenied:"passed",webSearchDisabled:"passed",observedAtMs:Z.observedAtMs}}:void 0;let qe;if(G==="arch-plan"&&k.archPlan?.execution?.currentStageCommand==="generate-pacts"&&k.archPlan.execution.continuationState==="ask-user")try{if(qe=sr(s),!qe)throw new Error("architecture-answers-required")}catch(c){const d=c instanceof Error&&/^architecture-answers-[a-z-]+$/.test(c.message)?c.message:"architecture-answers-failed";return{success:!1,error:d,errorCode:d,exitCode:1}}let Ye;if(G==="arch-plan"&&k.archPlan?.execution?.currentStageCommand==="generate-pacts"&&k.archPlan.execution.continuationState==="delegate"&&k.archPlan.execution.childStatus==="succeeded")try{if(Ye=sr(s),!Ye||!E(k.archPlan.execution.pactAnswerReceipt,Ye))throw new Error("architecture-answers-conflict")}catch{return{success:!1,error:"architecture-answers-conflict",errorCode:"architecture-answers-conflict",exitCode:1}}let j,ce,z;if(e.privateExecutionBeta&&G==="generate-pacts")try{const c=a.trim().match(/^\*?generate-pacts (P[1-9][0-9]{0,11})$/)?.[1],d=k.archPlan?.execution;if(ce=Ti(s),!c||!d||d.currentStageCommand!=="generate-pacts"||d.continuationState!=="delegate"||d.targetEpicId!==c||!ce||!E(d.pactAnswerReceipt,ce.receipt))throw new Error("private-execution-pact-admission-unverified");const m=ki(s,ce.answers.generateProvider);if(m.outcome!=="ready")throw new Error("private-execution-pact-admission-unverified");j=m.writeSet,z={schemaVersion:1,targetEpicId:c,graphRevision:ce.receipt.graphRevision,answersSha256:ce.receipt.answersSha256,specSha256:j.specSha256,pathsSha256:j.pathsSha256,endpointCount:j.endpointCount,pathCount:j.paths.length,publicSafe:!0}}catch{const c="private-execution-pact-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let Le,se;if(e.privateExecutionBeta&&G==="arch-ux-design")try{const c=a.trim().match(/^\*?arch-ux-design (P[1-9][0-9]{0,11})$/)?.[1],d=k.archPlan?.execution;if(!c||!d||d.currentStageCommand!=="arch-ux-design"||d.continuationState!=="delegate"||d.targetEpicId!==c||typeof d.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(d.graphRevision))throw new Error("private-execution-ux-admission-unverified");const{deriveUxWriteSet:m}=await import("../private-execution/ux-write-set.js");Le=m(s,c),se={schemaVersion:1,targetEpicId:c,graphRevision:d.graphRevision,adapterId:Le.adapterId,authoritySha256:Le.authoritySha256,pathsSha256:Le.pathsSha256,screenCount:Le.screenCount,pathCount:Le.pathCount,publicSafe:!0}}catch{const c="private-execution-ux-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let Ct,Ke,me;if(e.privateExecutionBeta&&G==="property-test")try{if(o.selection.positionals.length!==0||o.selection.operationId!==void 0||Object.keys(o.selection.options).length!==0)throw new Error("private-execution-property-admission-unverified");const{loadPropertyTestChoices:c}=await import("../private-execution/property-test-choices.js"),{propertyTestExecutionInput:d}=await import("../private-execution/property-test-plan.js"),m=c(s);if(!m)throw new Error("private-execution-property-admission-unverified");Ct=m.choices,Ke=m.plan,me=d(m.plan)}catch{const c="private-execution-property-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let Y={args:a,projectRoot:s.replace(Yt(),"~"),stateSnapshot:k,...qe?{architectureAnswerReceipt:qe}:{},...z?{pactExecutionInput:z}:{},...se?{uxExecutionInput:se}:{},...me?{propertyTestExecutionInput:me}:{},platformTarget:T,...P?{nativeHostAttestation:P}:{},...vt?{privateExecution:vt}:{},projectId:Ne,inputEvidence:n,idempotencyKey:We,registryVersion:yt,registryChecksum:mt,compatibility:Bn(),...e.releaseGate?{releaseGate:e.releaseGate}:{},...Fe?{strictReadOnly:Fe}:{}};const vn=Bt(Y);if(!C&&e.inputSource&&e.inputSource!=="args"&&vn>=Dn)try{Y={argsRef:(await ua(p,"secondary-mutation",()=>Wo(R,a,H.token,()=>H.client.forceRefresh()),async()=>{throw new Dt("readonly-physical-boundary-unsafe","boundary")})).argsRef,projectRoot:s.replace(Yt(),"~"),stateSnapshot:k,...qe?{architectureAnswerReceipt:qe}:{},platformTarget:T,...P?{nativeHostAttestation:P}:{},...vt?{privateExecution:vt}:{},projectId:Ne,inputEvidence:n,idempotencyKey:We,registryVersion:yt,registryChecksum:mt,compatibility:Bn(),...e.releaseGate?{releaseGate:e.releaseGate}:{},...Fe?{strictReadOnly:Fe}:{}}}catch(c){return c instanceof Dt?{success:!1,error:c.code,errorCode:c.code,exitCode:1}:{success:!1,error:`INVOKE_MATERIALIZATION_FAILED: ${c instanceof Error?c.message:String(c)}`,errorCode:"INVOKE_MATERIALIZATION_FAILED",exitCode:1}}if(G==="yolo"&&k.scope?.projectionMode==="yolo-story"){const c=k.scope?.targetStoryId,d=k.scope?.targetEpicId;if(!c||!d||!Q||Q.storyId!==c||Q.epicId!==d)return{success:!1,error:"yolo-spec-envelope-target-mismatch",errorCode:"yolo-spec-envelope-target-mismatch",exitCode:1};try{const m=Fa(Q);if(/\sbranchless-preparation\s*$/.test(a))Y={...Y,yoloSpecEnvelope:m};else{const{collectYoloChangeEvidence:b,reconcileYoloChangeEvidenceLease:U}=await import("../yolo/change-evidence-collector.js");await U({projectRoot:s,storyId:c,epicId:d});const he=b({projectRoot:s,defaultBranch:k.config.default_branch,expectedHeadSha:m.sourceRevision.headSha,storyId:c,epicId:d});Y={...Y,yoloSpecEnvelope:m,yoloChangeEvidence:he}}}catch(m){const b=m instanceof Error&&/^yolo-(?:spec-envelope|change-evidence)-[a-z-]+$/.test(m.message)?m.message:"yolo-spec-envelope-unsafe";return{success:!1,error:b,errorCode:b,exitCode:1}}}try{const c=pi(Y);if(G==="migrate-state"&&c.degraded)return{success:!1,error:"state_migration_payload_degraded",errorCode:"state_migration_payload_degraded",exitCode:1};Y=c.body,c.degraded?ui(Y,c.telemetry):Ko(Y)}catch(c){if(c instanceof Un||c instanceof $n)return ui(Y,c.telemetry),process.stderr.write(`[Neocortex] ${c.message}
|
|
51
|
-
`),{success:!1,error:c.message,errorCode:c.code,metadata:{invokePayload:c.telemetry},exitCode:1};throw c}if(G==="yolo"&&
|
|
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.
|
|
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
|
+
`)}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
|
+
`)}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
|
+
`)}});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.
|
|
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}
|
|
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(`
|
|
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 (${
|
|
56
|
+
Your Neocortex version (${Tt}) 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 ${
|
|
67
|
-
`),m;try{if(d){const
|
|
68
|
-
`),{success:!1,error:d,errorCode:d,exitCode:1}}if(!
|
|
69
|
-
`),{success:!1,error:d,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}catch(c){if(
|
|
70
|
-
`),{success:!1,error:m,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}if(
|
|
71
|
-
`),{success:!1,error:d,errorCode:"GIT_LIFECYCLE_GRAPH_AUTHORITY_INVALID",exitCode:1}}if(
|
|
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.
|
|
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 (${
|
|
76
|
+
Your Neocortex client version (${Tt}) 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:
|
|
@@ -83,55 +83,55 @@ ${t}
|
|
|
83
83
|
`),process.stderr.write(` After upgrading, re-run your yoloop command.
|
|
84
84
|
`),process.stderr.write(`==================================================
|
|
85
85
|
|
|
86
|
-
`),{success:!1,error:"CLIENT_UPGRADE_REQUIRED: This client does not support yoloop client-side persistence. Run: npm install -g @ornexus/neocortex@latest",exitCode:3};if(
|
|
87
|
-
`),{success:!1,error:
|
|
88
|
-
`),{success:!1,error:
|
|
86
|
+
`),{success:!1,error:"CLIENT_UPGRADE_REQUIRED: This client does not support yoloop client-side persistence. Run: npm install -g @ornexus/neocortex@latest",exitCode:3};if(f.data.metadata?.yoloopStateUpdate){const d=(f.data.metadata.yoloopStateUpdate.operations??[]).some(m=>m.type==="rollover_session");try{const m=await y.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>{const{persistYoloopFromResponse:A}=await import("../yoloop/invoke-hooks.js");return A(f.data.metadata,s)},async()=>({ok:!0,authoritative:!1,reasonCodes:[]}));if(m&&m.ok===!1){const A=m.reasonCodes[0]??"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED";return process.stderr.write(`[Neocortex] ${A}. No yoloop continuation instructions were released.
|
|
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
|
+
`),{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: ${
|
|
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}
|
|
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
|
|
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
|
|
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:{...
|
|
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}
|
|
96
96
|
|
|
97
97
|
Private P01 handoff (local only):
|
|
98
|
-
The durable reserved epic ID is ${
|
|
99
|
-
`:
|
|
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.
|
|
99
|
+
`:Be?`${rt}
|
|
100
100
|
|
|
101
101
|
Private P02 handoff (local only):
|
|
102
|
-
The admitted epic is ${
|
|
103
|
-
`:
|
|
102
|
+
The admitted epic is ${ye.epicId}. Research only this exact diagnosed epic. Write exactly .neocortex/planning/epic-${ye.epicId}/research.md and its transition in .neocortex/planning/planning.json. Do not write state.json, Git controls, another epic, or P03 artifacts; do not auto-continue. The root will independently review and seal the research candidate.
|
|
103
|
+
`:me?`${rt}
|
|
104
104
|
|
|
105
105
|
Private P03 handoff (local only):
|
|
106
|
-
The admitted epic is ${
|
|
107
|
-
`:
|
|
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}
|
|
108
108
|
|
|
109
109
|
Private A03.5 handoff (local only):
|
|
110
|
-
${JSON.stringify({consumer:
|
|
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})}
|
|
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
|
-
`:
|
|
112
|
+
`:mt?`${rt}
|
|
113
113
|
|
|
114
114
|
Private A08 handoff (local only):
|
|
115
|
-
${JSON.stringify({targetEpicId:
|
|
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
|
-
`:
|
|
117
|
+
`:yt?`${rt}
|
|
118
118
|
|
|
119
119
|
Private property-test handoff (local only):
|
|
120
|
-
${JSON.stringify({language:
|
|
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}))})}
|
|
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
|
|
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+=`
|
|
123
123
|
Root physical dispatch observations (data, not phase completion):
|
|
124
|
-
`+JSON.stringify({storyId:
|
|
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
|
|
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
|
|
127
127
|
|
|
128
|
-
O root registrou o commit e a valida\xE7\xE3o f\xEDsica no branch do epic.`:
|
|
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
|
-
O root confirmou o checkpoint C01 no branch do \xE9pico. Reexecute o mesmo YOLO para avan\xE7ar \xE0 pr\xF3xima etapa.`:
|
|
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.`:
|
|
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
|
|
133
133
|
|
|
134
|
-
O executor Codex retornou sem erro. Nenhum checkpoint ou aprova\xE7\xE3o da story foi emitido.`:
|
|
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=`
|
|
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
|
|
206
|
-
`);return}
|
|
207
|
-
`);return}const a=
|
|
208
|
-
`),n&&
|
|
209
|
-
`)}async function
|
|
210
|
-
`),0;let t;try{t=
|
|
211
|
-
`),1;throw
|
|
212
|
-
`),1):(await
|
|
213
|
-
`),
|
|
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})+`
|
|
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+`
|
|
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};
|