@ornexus/neocortex 4.64.2 → 4.64.4
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/dist/sbom.cdx.json +1193 -1193
- package/install.ps1 +10 -1
- package/install.sh +9 -1
- package/package.json +2 -2
- package/packages/client/dist/agent/refresh-stubs.js +2 -2
- package/packages/client/dist/commands/invoke.d.ts +25 -0
- package/packages/client/dist/commands/invoke.js +74 -73
- package/packages/client/dist/git/git-lifecycle-store.js +8 -8
- 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 +1 -1
- package/targets-stubs/cursor/agent.md +2 -2
- package/targets-stubs/gemini-cli/agent.md +2 -2
- package/targets-stubs/opencode/neocortex-root.md +1 -1
- package/targets-stubs/vscode/neocortex.agent.md +2 -2
|
@@ -1,65 +1,65 @@
|
|
|
1
|
-
import{classifyNonUiArchitectureTransition as qi,architectureMemoryPredecessorCount as Ir}from"./architecture-non-ui-continuation.js";import{parseArchitectureNonUiScopeReceipt as Er}from"./shared-architecture-non-ui.js";import{createHash as Ne,randomUUID as dn}from"node:crypto";import{loadPactAnswerReceipt as Sr,loadPactPrivateAnswers as zi}from"./architecture-answers.js";import{acceptedArchitectureTerminalMemoryReceipt as Ft,deriveArchitectureTerminalMemoryReceipt as Ln}from"./architecture-memory-terminal.js";import{deriveCommittedArchitectureEpicGraphRevision as Yt,explicitArchitectureEpicTarget as Ji}from"./architecture-root-binding.js";import{derivePactWriteSet as Ki}from"../private-execution/pact-write-set.js";import{execFileSync as Ge}from"node:child_process";import{existsSync as jt,readFileSync as Fe,renameSync as vr,unlinkSync as Dn,writeFileSync as pn,mkdirSync as qt,statSync as Qi,openSync as zt,closeSync as Jt,fsyncSync as ln,realpathSync as Xi,lstatSync as Vt}from"node:fs";import{isDeepStrictEqual as v}from"node:util";import{join as z,isAbsolute as Zi,resolve as Mn}from"node:path";import{homedir as Kt}from"node:os";import{probeYoloopHostCapacity as ea}from"../runner/host-capacity.js";import{isPrivateExecutionPublicEnvelope as ta,isPrivatePlanningRootPublicEnvelope as na,PRIVATE_MUTATION_QA_GATE_STEP_TOKEN as ra}from"../private-execution/delivery.js";import{acceptedPlanningDiagnosisPredecessor as Cr}from"../private-execution/planning-diagnosis-checkpoint.js";import{acceptedPlanningResearchPredecessor as _r}from"../private-execution/planning-research-checkpoint.js";import{verifyCommittedPlanningMemory as Rr}from"../private-execution/planning-memory-checkpoint.js";import{verifyCommittedPlanningGeneration as ia}from"../private-execution/planning-generation-checkpoint.js";import{PLANNING_RAW_INTENT_MAX_CHARS as aa}from"../../../shared/dist/planning/diagnosis-state.js";import{applyCrossEpicContinuationReconciliation as oa,buildCrossEpicContinuationPayloadHash as ca,classifyCrossEpicContinuationReconciliation as sa,epicOperationalHash as vt,readEpicOperationalState as wr}from"../git/epic-operational-state.js";import{LicenseClient as da}from"../license/license-client.js";import{EncryptedCache as jn}from"../cache/encrypted-cache.js";import{NoOpCache as Ar}from"../types/index.js";import{resolveClientPreFlightTrigger as un,TierAwareClient as pa}from"../tier/tier-aware-client.js";import{COMMAND_REGISTRY_CHECKSUM as st,COMMAND_REGISTRY_VERSION as dt,GENERATED_CLIENT_COMMANDS as la}from"../generated/command-registry.generated.js";import{loadSecureConfig as Vn}from"../config/secure-config.js";import{neocortexProfileDirectory as ua}from"../config/profile-directory.js";import{DEFAULT_SERVER_URL as ha}from"../constants.js";import{detectFirstRunLocale as ga,renderFirstRunMessage as fa}from"../i18n/first-run.js";import{humanizeError as br,formatHumanizedError as xr,detectErrorLocale as Tr}from"../errors/error-messages.js";import{degradeStateSnapshotForPayloadLimit as ma,projectStateSnapshotForInvoke as Pr,projectStateSnapshotResultV2ForInvoke as ya}from"../state/project-state-snapshot.js";import{isInlineYoloMaterialization as kr,maybeRepairStateJsonBeforeInvoke as Ia,readStoryWorktreeRepairOverlay as Ea,StateRepairHardStopError as Sa}from"../state/state-json-repair.js";import{StructuralDagError as Or}from"../state/structural-dag-projection.js";import{collectStateMigrationAuthority as va,StateMigrationApplyError as Ca}from"../migrations/state-json.js";import{RUNNER_BOOTSTRAP_POLICY_REASON_CODES as _a,classifyRunnerBootstrapPolicyFromArgs as Ra}from"../continuity/runner-bootstrap-policy.js";import{RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES as wa,ensureRunnerSchedulerBootstrap as Aa,observeRunnerOperationalStatus as ba}from"../runner/scheduler.js";import{CONTINUITY_INVOKE_WATCH_DEFAULT_LIMIT as Nr,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_IDLE_POLLS as Lr,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_POLLS as Dr,CONTINUITY_INVOKE_WATCH_DEFAULT_POLL_INTERVAL_MS as Mr,openContinuityClientStateStore as xa}from"../continuity/continuity-client-state-store.js";import{isLocalJobsConsoleArgs as Ta,runLocalJobsConsoleCommand as Pa}from"../runner/local-console.js";import{detectNativeHostAttestation as ka,detectPlatform as Oa}from"../adapters/platform-detector.js";import{signNxInvokeRequest as Na}from"../../../shared/dist/nx-invoke-signature.js";import{YOLO_INVOKE_ENVELOPE_CAPABILITY as La}from"../../../shared/dist/yolo/spec-envelope.js";import{parseReleaseBlockedResult as Da}from"../../../shared/dist/yoloop/release-blocked.js";import{CLIENT_VERSION as Pt}from"../version.js";import{createCapabilityCache as jr,executeInvokeQueryTransport as Bn,executeSecondaryNetworkMutation as Ma}from"../effects/invoke-effect-gateways.js";import{STRICT_READ_ONLY_POLICY as ja,STRICT_READ_ONLY_CLIENT_PROJECTION as Vr,STRICT_READ_ONLY_SERVER_PROJECTION as Va,StrictReadOnlyError as Bt,canonicalizeInvokeEffects as Ba,createInvokeEffectContext as Ua,verifyStrictReadOnlyReceipt as $a}from"../../../shared/dist/strict-readonly.js";import{admitInvocation as Ha,assertInvokeInputEnvelopeV2 as Wa,assertProjectIdentityMigrationReceiptV1 as Ga,buildProjectIdentityPublicDiagnostic as Ut,createInvocationAdmissionReceipt as Fa,projectInvokeInputEvidenceV1 as Un,recoverExplicitInvocation as Ya,verifyStrictDiagnoseReceiptV1 as qa}from"../../../shared/dist/invocation/index.js";import{buildInvokeInputEnvelope as Qt,InvokeInputDecodeError as za}from"../invocation/invoke-input.js";import{COMPATIBILITY_REASON_CODES as $t,createCompatibilityOffer as Ja,createLegacyCompatibilityResult as Ka,isCompatibilityResultV1 as Qa}from"../../../shared/dist/compatibility/index.js";import{acknowledgeProjectIdentityMigration as Xa,finalizeProjectIdentityMigration as Za,prepareProjectIdentityMigration as eo,ProjectIdentityMigrationError as $n,readProjectIdentityMigrationPhase as to}from"../migrations/project-identity.js";import{probeProjectIdentityMigrationCapability as no}from"../migrations/project-identity-capability.js";import{normalizeYoloopStoryPlanningEvidence as ro}from"../../../shared/dist/yoloop/planning-graph.js";import{normalizeContinuousWriteRef as hn}from"../../../shared/dist/yoloop/wave-decision-receipt.js";import{epicHeadReconciliationInputDigest as io,epicHeadReconciliationPathsDigest as gn,epicHeadReconciliationRangeDigest as ao}from"../../../shared/dist/yoloop/epic-terminal-git.js";import{applyGitLifecycleRuntimeOverlay as Br,classifyGitLifecycleStoryCheckpointProjectionSync as oo,ensureRuntimeEpic as co,ensureGitLifecycleRuntimeInitialized as so,executeP205TransientAuthorities as po,isP226GateReasonCode as lo,persistGitLifecycleGraphAuthority as uo,P205_COMPLETE_COMMAND as Xt,gitLifecycleStoryWriteSet as Ur,gitLifecycleStoryClaimCandidates as ho,gitLifecycleWriteSetCovers as go,appendStoryWorktreeEvidence as fo,isStoryWorktreeEvidenceContainer as mo,mutateGitLifecycleRuntime as $r,projectP205TransientExecutionEvidence as yo,readGitLifecycleRuntimeSync as fn,verifyLegacyCheckpointMigrationCandidateSync as Io}from"../git/git-lifecycle-store.js";import{verifyRootMemoryPhysicalWriteSet as Eo}from"../private-execution/root-memory-git-evidence.js";import{isRootProjectMemoryEffect as So}from"../private-execution/shared-root-memory-types.js";import{probeYoloInvokeEnvelopeCapability as vo}from"../yolo/invoke-envelope-capability.js";import{attachProjectManifestProjection as Co}from"../yolo/project-manifest-projection-collector.js";import{collectYoloSpecEnvelope as Hr,extractTargetedYoloStoryId as _o,refreshPrecollectedYoloSpecEnvelope as Wr}from"../yolo/spec-envelope-collector.js";import{FRONTMATTER_LIST_TOO_LONG_DIAGNOSTIC_PATTERN as Ro}from"../errors/frontmatter-diagnostics.js";function Gr(e,t=!1){return e instanceof Error&&((t?/^yolo-(?:spec-envelope|change-evidence)-[a-z-]+$/:/^yolo-spec-envelope-[a-z-]+$/).test(e.message)||Ro.test(e.message))?e.message:"yolo-spec-envelope-unsafe"}const mn=ua(),Hn=z(mn,"cache"),Fr=z(Hn,"menu-cache.json"),Yr=1440*60*1e3,qr=3e4,zr=256*1024,Jr=zr,Kr=.8,Ct="[REDACTED]",wo=1e5,kt=2e3,Ao=200,bo=200,xo=12,To=/(?:promptBody|workflow|workflowGraph|stepBody|privateUrl|rawLog|secret|credential|licenseKey|apiKey|internalRouting|serverOnly|proprietary|protected)/i,Po=/(?:PRIVATE|PROTECTED|SERVER_ONLY)[-_\s]*(?:PROMPT|PROMPT_BODY|WORKFLOW|WORKFLOW_GRAPH|STEP_BODY|STEP|ROUTING)\s*[:=][^\n\r]*/gi,ko=/(?:https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|private|internal)[^\s"'<>]*|raw[_-]?log|transcript|stack\s*trace|stderr:|stdout:|system prompt|prompt body|workflow body|step body|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|VENDOR_CORPUS|P180[_-]?SYNTHETIC[_-]?CONTINUITY|P185[_-]?SYNTHETIC[_-]?CONTINUITY|P187[_-]?SYNTHETIC[_-]?(?:CONTINUITY|RUNNER|WATCH)|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=)/gi,Wn=Math.floor(zr*Kr),Qr=z(mn,".first-run-shown"),Oo="pending-epic-claims.json",Xr=64;function Zr(e){return z(e,".neocortex",Oo)}function Ht(e){const t=Zr(e);if(!jt(t))return{schemaVersion:1,operations:{}};const i=JSON.parse(Fe(t,"utf8"));if(!i||typeof i!="object"||Array.isArray(i))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const n=i;if(n.schemaVersion!==1||!n.operations||typeof n.operations!="object"||Array.isArray(n.operations))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(Object.keys(n.operations).length>Xr)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");for(const[a,r]of Object.entries(n.operations)){if(!/^[a-f0-9]{64}$/.test(a)||!r||typeof r!="object"||Array.isArray(r))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const o=r;if(o.planningProtocol!==void 0&&o.planningProtocol!=="root-staged-v1")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(typeof o.idempotencyKey!="string"||!/^[0-9a-f-]{36}$/.test(o.idempotencyKey)||typeof o.createdAt!="string")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(o.claimId!==void 0&&(typeof o.claimId!="string"||!/^[0-9a-f-]{36}$/.test(o.claimId))||o.epicId!==void 0&&(typeof o.epicId!="string"||!/^P[1-9][0-9]*$/.test(o.epicId))||o.claimId===void 0!=(o.epicId===void 0))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE")}return i}function Gn(e,t){const i=Zr(e);qt(z(e,".neocortex"),{recursive:!0,mode:448});const n=`${i}.${process.pid}.${dn()}.tmp`;pn(n,`${JSON.stringify(t)}
|
|
2
|
-
`,{encoding:"utf8",mode:384,flag:"wx"}),
|
|
1
|
+
import{classifyNonUiArchitectureTransition as zi,architectureMemoryPredecessorCount as Ir}from"./architecture-non-ui-continuation.js";import{parseArchitectureNonUiScopeReceipt as Sr}from"./shared-architecture-non-ui.js";import{createHash as Ne,randomUUID as pn}from"node:crypto";import{loadPactAnswerReceipt as vr,loadPactPrivateAnswers as Ji}from"./architecture-answers.js";import{acceptedArchitectureTerminalMemoryReceipt as Ft,deriveArchitectureTerminalMemoryReceipt as Dn}from"./architecture-memory-terminal.js";import{deriveCommittedArchitectureEpicGraphRevision as Yt,explicitArchitectureEpicTarget as Ki}from"./architecture-root-binding.js";import{derivePactWriteSet as Qi}from"../private-execution/pact-write-set.js";import{execFileSync as Be}from"node:child_process";import{existsSync as jt,readFileSync as Fe,renameSync as Cr,unlinkSync as Mn,writeFileSync as ln,mkdirSync as qt,statSync as Xi,openSync as zt,closeSync as Jt,fsyncSync as un,realpathSync as Zi,lstatSync as Vt}from"node:fs";import{isDeepStrictEqual as C}from"node:util";import{join as z,isAbsolute as eo,resolve as jn}from"node:path";import{homedir as Kt}from"node:os";import{probeYoloopHostCapacity as to}from"../runner/host-capacity.js";import{isPrivateExecutionPublicEnvelope as no,isPrivatePlanningRootPublicEnvelope as ro,PRIVATE_MUTATION_QA_GATE_STEP_TOKEN as io}from"../private-execution/delivery.js";import{acceptedPlanningDiagnosisPredecessor as _r}from"../private-execution/planning-diagnosis-checkpoint.js";import{acceptedPlanningResearchPredecessor as Rr}from"../private-execution/planning-research-checkpoint.js";import{verifyCommittedPlanningMemory as wr}from"../private-execution/planning-memory-checkpoint.js";import{verifyCommittedPlanningGeneration as oo}from"../private-execution/planning-generation-checkpoint.js";import{PLANNING_RAW_INTENT_MAX_CHARS as ao}from"../../../shared/dist/planning/diagnosis-state.js";import{applyCrossEpicContinuationReconciliation as co,buildCrossEpicContinuationPayloadHash as so,classifyCrossEpicContinuationReconciliation as po,epicOperationalHash as vt,readEpicOperationalState as Ar}from"../git/epic-operational-state.js";import{LicenseClient as lo}from"../license/license-client.js";import{EncryptedCache as Vn}from"../cache/encrypted-cache.js";import{NoOpCache as br}from"../types/index.js";import{resolveClientPreFlightTrigger as hn,TierAwareClient as uo}from"../tier/tier-aware-client.js";import{COMMAND_REGISTRY_CHECKSUM as st,COMMAND_REGISTRY_VERSION as dt,GENERATED_CLIENT_COMMANDS as ho}from"../generated/command-registry.generated.js";import{loadSecureConfig as Bn}from"../config/secure-config.js";import{neocortexProfileDirectory as go}from"../config/profile-directory.js";import{DEFAULT_SERVER_URL as fo}from"../constants.js";import{detectFirstRunLocale as mo,renderFirstRunMessage as yo}from"../i18n/first-run.js";import{humanizeError as xr,formatHumanizedError as Tr,detectErrorLocale as Pr}from"../errors/error-messages.js";import{degradeStateSnapshotForPayloadLimit as Eo,projectStateSnapshotForInvoke as kr,projectStateSnapshotResultV2ForInvoke as Io}from"../state/project-state-snapshot.js";import{isInlineYoloMaterialization as Or,maybeRepairStateJsonBeforeInvoke as So,readStoryWorktreeRepairOverlay as vo,StateRepairHardStopError as Co}from"../state/state-json-repair.js";import{StructuralDagError as Nr}from"../state/structural-dag-projection.js";import{collectStateMigrationAuthority as _o,StateMigrationApplyError as Ro}from"../migrations/state-json.js";import{RUNNER_BOOTSTRAP_POLICY_REASON_CODES as wo,classifyRunnerBootstrapPolicyFromArgs as Ao}from"../continuity/runner-bootstrap-policy.js";import{RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES as bo,ensureRunnerSchedulerBootstrap as xo,observeRunnerOperationalStatus as To}from"../runner/scheduler.js";import{CONTINUITY_INVOKE_WATCH_DEFAULT_LIMIT as Lr,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_IDLE_POLLS as Dr,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_POLLS as Mr,CONTINUITY_INVOKE_WATCH_DEFAULT_POLL_INTERVAL_MS as jr,openContinuityClientStateStore as Po}from"../continuity/continuity-client-state-store.js";import{isLocalJobsConsoleArgs as ko,runLocalJobsConsoleCommand as Oo}from"../runner/local-console.js";import{detectNativeHostAttestation as No,detectPlatform as Lo}from"../adapters/platform-detector.js";import{signNxInvokeRequest as Do}from"../../../shared/dist/nx-invoke-signature.js";import{YOLO_INVOKE_ENVELOPE_CAPABILITY as Mo}from"../../../shared/dist/yolo/spec-envelope.js";import{parseReleaseBlockedResult as jo}from"../../../shared/dist/yoloop/release-blocked.js";import{CLIENT_VERSION as Pt}from"../version.js";import{createCapabilityCache as Vr,executeInvokeQueryTransport as Un,executeSecondaryNetworkMutation as Vo}from"../effects/invoke-effect-gateways.js";import{STRICT_READ_ONLY_POLICY as Bo,STRICT_READ_ONLY_CLIENT_PROJECTION as Br,STRICT_READ_ONLY_SERVER_PROJECTION as Uo,StrictReadOnlyError as Bt,canonicalizeInvokeEffects as $o,createInvokeEffectContext as Ho,verifyStrictReadOnlyReceipt as Wo}from"../../../shared/dist/strict-readonly.js";import{admitInvocation as Go,assertInvokeInputEnvelopeV2 as Fo,assertProjectIdentityMigrationReceiptV1 as Yo,buildProjectIdentityPublicDiagnostic as Ut,createInvocationAdmissionReceipt as qo,projectInvokeInputEvidenceV1 as $n,recoverExplicitInvocation as zo,verifyStrictDiagnoseReceiptV1 as Jo}from"../../../shared/dist/invocation/index.js";import{buildInvokeInputEnvelope as Qt,InvokeInputDecodeError as Ko}from"../invocation/invoke-input.js";import{COMPATIBILITY_REASON_CODES as $t,createCompatibilityOffer as Qo,createLegacyCompatibilityResult as Xo,isCompatibilityResultV1 as Zo}from"../../../shared/dist/compatibility/index.js";import{acknowledgeProjectIdentityMigration as ea,finalizeProjectIdentityMigration as ta,prepareProjectIdentityMigration as na,ProjectIdentityMigrationError as Hn,readProjectIdentityMigrationPhase as ra}from"../migrations/project-identity.js";import{probeProjectIdentityMigrationCapability as ia}from"../migrations/project-identity-capability.js";import{normalizeYoloopStoryPlanningEvidence as oa}from"../../../shared/dist/yoloop/planning-graph.js";import{normalizeContinuousWriteRef as gn}from"../../../shared/dist/yoloop/wave-decision-receipt.js";import{epicHeadReconciliationInputDigest as aa,epicHeadReconciliationPathsDigest as fn,epicHeadReconciliationRangeDigest as ca}from"../../../shared/dist/yoloop/epic-terminal-git.js";import{applyGitLifecycleRuntimeOverlay as Ur,classifyGitLifecycleStoryCheckpointProjectionSync as sa,ensureRuntimeEpic as da,ensureGitLifecycleRuntimeInitialized as pa,executeP205TransientAuthorities as la,isP226GateReasonCode as ua,persistGitLifecycleGraphAuthority as ha,P205_COMPLETE_COMMAND as Xt,gitLifecycleStoryWriteSet as $r,gitLifecycleStoryClaimCandidates as ga,gitLifecycleWriteSetCovers as fa,appendStoryWorktreeEvidence as ma,isStoryWorktreeEvidenceContainer as ya,mutateGitLifecycleRuntime as Hr,projectP205TransientExecutionEvidence as Ea,readGitLifecycleRuntimeSync as mn,verifyLegacyCheckpointMigrationCandidateSync as Ia}from"../git/git-lifecycle-store.js";import{verifyRootMemoryPhysicalWriteSet as Sa}from"../private-execution/root-memory-git-evidence.js";import{isRootProjectMemoryEffect as va}from"../private-execution/shared-root-memory-types.js";import{probeYoloInvokeEnvelopeCapability as Ca}from"../yolo/invoke-envelope-capability.js";import{attachProjectManifestProjection as _a}from"../yolo/project-manifest-projection-collector.js";import{collectYoloSpecEnvelope as Wr,extractTargetedYoloStoryId as Ra,refreshPrecollectedYoloSpecEnvelope as Gr}from"../yolo/spec-envelope-collector.js";import{FRONTMATTER_LIST_TOO_LONG_DIAGNOSTIC_PATTERN as wa}from"../errors/frontmatter-diagnostics.js";function Fr(e,t=!1){return e instanceof Error&&((t?/^yolo-(?:spec-envelope|change-evidence)-[a-z-]+$/:/^yolo-spec-envelope-[a-z-]+$/).test(e.message)||wa.test(e.message))?e.message:"yolo-spec-envelope-unsafe"}const yn=go(),Wn=z(yn,"cache"),Yr=z(Wn,"menu-cache.json"),qr=1440*60*1e3,zr=3e4,Jr=256*1024,Kr=Jr,Qr=.8,Ct="[REDACTED]",Aa=1e5,kt=2e3,ba=200,xa=200,Ta=12,Pa=/(?:promptBody|workflow|workflowGraph|stepBody|privateUrl|rawLog|secret|credential|licenseKey|apiKey|internalRouting|serverOnly|proprietary|protected)/i,ka=/(?:PRIVATE|PROTECTED|SERVER_ONLY)[-_\s]*(?:PROMPT|PROMPT_BODY|WORKFLOW|WORKFLOW_GRAPH|STEP_BODY|STEP|ROUTING)\s*[:=][^\n\r]*/gi,Oa=/(?: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,Gn=Math.floor(Jr*Qr),Xr=z(yn,".first-run-shown"),Na="pending-epic-claims.json",Zr=64;function ei(e){return z(e,".neocortex",Na)}function Ht(e){const t=ei(e);if(!jt(t))return{schemaVersion:1,operations:{}};const i=JSON.parse(Fe(t,"utf8"));if(!i||typeof i!="object"||Array.isArray(i))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const r=i;if(r.schemaVersion!==1||!r.operations||typeof r.operations!="object"||Array.isArray(r.operations))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(Object.keys(r.operations).length>Zr)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");for(const[o,n]of Object.entries(r.operations)){if(!/^[a-f0-9]{64}$/.test(o)||!n||typeof n!="object"||Array.isArray(n))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const a=n;if(a.planningProtocol!==void 0&&a.planningProtocol!=="root-staged-v1")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(typeof a.idempotencyKey!="string"||!/^[0-9a-f-]{36}$/.test(a.idempotencyKey)||typeof a.createdAt!="string")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(a.claimId!==void 0&&(typeof a.claimId!="string"||!/^[0-9a-f-]{36}$/.test(a.claimId))||a.epicId!==void 0&&(typeof a.epicId!="string"||!/^P[1-9][0-9]*$/.test(a.epicId))||a.claimId===void 0!=(a.epicId===void 0))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE")}return i}function Fn(e,t){const i=ei(e);qt(z(e,".neocortex"),{recursive:!0,mode:448});const r=`${i}.${process.pid}.${pn()}.tmp`;ln(r,`${JSON.stringify(t)}
|
|
2
|
+
`,{encoding:"utf8",mode:384,flag:"wx"}),Cr(r,i)}function La(e,t){return Ne("sha256").update(`nx-epic-logical-operation-v1\0${JSON.stringify({command:t,args:e})}`,"utf8").digest("hex")}function Da(e,t,i="create-epic"){const r=La(t,i),o=Ht(e),n=o.operations[r];if(n)return{key:n.idempotencyKey,fingerprint:r};if(Object.keys(o.operations).length>=Zr)throw new Error("EPIC_CLAIM_CAPACITY_EXCEEDED");const a=pn(),d={...o.operations,[r]:{idempotencyKey:a,createdAt:new Date().toISOString()}};return Fn(e,{schemaVersion:1,operations:d}),{key:a,fingerprint:r}}function Ma(e,t){const i=Ht(e);if(!i.operations[t])return;const r={...i.operations};delete r[t],Fn(e,{schemaVersion:1,operations:r})}function ja(e,t,i,r){const o=r.scope?.targetStoryId??r.current_session?.active_story_id??null,n=r.scope?.targetEpicId??r.current_session?.active_epic_id??null,a=o?r.stories[o]:void 0,d=Array.isArray(a?.steps_completed)?a.steps_completed.filter(m=>typeof m=="string"):[],s=i??Ne("sha256").update(`nx-yolo-project-path-v1\0${jn(e)}`,"utf8").digest("hex"),l=JSON.stringify({projectBinding:s,args:t,storyId:o,epicId:n,status:typeof a?.status=="string"?a.status:null,lastStep:typeof a?.last_step=="string"?a.last_step:null,stepsCompleted:d});return`yolo-${Ne("sha256").update(`nx-yolo-logical-operation-v1\0${l}`,"utf8").digest("hex")}`}function ti(e,t,i,r,o){if(!/^[0-9a-f-]{36}$/.test(i)||!/^P[1-9][0-9]*$/.test(r)||o!==void 0&&o!=="root-staged-v1")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const n=Ht(e),a=n.operations[t];if(!a)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(a.claimId!==void 0&&(a.claimId!==i||a.epicId!==r))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");Fn(e,{schemaVersion:1,operations:{...n.operations,[t]:{...a,claimId:i,epicId:r,...o?{planningProtocol:o}:{}}}})}function Va(){try{if(jt(Xr))return;const e=mo(),t=yo(e);process.stderr.write(t);try{qt(yn,{recursive:!0}),ln(Xr,new Date().toISOString(),"utf-8")}catch{}}catch{}}function Yn(e,t=process.cwd()){return e&&e.trim().length>0?e:t}function Ba(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 Ua(e){const t=e.metadata;if(!t||!(t.yoloopReleaseBlocked===!0||t.terminalClass==="release-blocked"||t.releaseBlocked!==void 0))return;const r=jo(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 ni(e){return Go(e,{registryVersion:dt,registryChecksum:st})}function $a(e){return zo(e,{registryVersion:dt,registryChecksum:st})}const Ha=new Set(["completed","aborted","cancelled"]),Wa=new Set(["watch-target-missing","watch-target-malformed","watch-target-ambiguous","watch-target-multiple"]),_e=Object.freeze({COMPLETED:"invoke-watch-completed",CANCELLED:"invoke-watch-cancelled",IDLE_TIMEOUT:"invoke-watch-idle-timeout",MAX_POLLS:"invoke-watch-max-polls",STORE_UNAVAILABLE:"invoke-watch-store-unavailable",TARGET_UNRESOLVED:"invoke-watch-target-unresolved"}),Le=Object.freeze({MISSING:"watch-target-missing",MALFORMED:"watch-target-malformed",AMBIGUOUS:"watch-target-ambiguous",CONFLICT:"watch-target-conflicting-evidence",SERVER_HELD_STREAM:"watch-target-server-held-stream-unsupported"}),G=Object.freeze({OK:"continuity-ok",WATCH_NO_SUMMARIES_YET:"watch-no-summaries-yet",WATCH_CURSOR_ADVANCED:"watch-cursor-advanced",WATCH_CURSOR_UNCHANGED:"watch-cursor-unchanged",WATCH_RENDER_PENDING:"watch-render-pending",WATCH_STOP_IDLE_LIMIT_REACHED:"watch-stop-idle-limit-reached",WATCH_STOP_MAX_POLLS_REACHED:"watch-stop-max-polls-reached",WATCH_TARGET_UNRESOLVED:"watch-target-unresolved",WATCH_SNAPSHOT_UNAVAILABLE:"watch-snapshot-unavailable",WATCH_EVIDENCE_UNAVAILABLE:"watch-evidence-unavailable"}),ri=240,Ga=/(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 Fa(e){return e.replace(/[\w.+-]+@[\w-]+\.[\w.-]+/g,Ct).replace(/(?:sk|pk|whsec|nxk)[-_](?:test|live|ant|proj|pro|free|enterprise)?[-_]?[A-Za-z0-9_-]{16,}/g,Ct).replace(/NX-[FPE]-[a-f0-9]{24}-[a-f0-9]{4}/g,Ct).replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,Ct).replace(ka,Ct).replace(Oa,Ct)}function Je(e,t){const i=Fa(e);return i.length<=t?i:`${i.slice(0,t)}\u2026[TRUNCATED:${i.length-t}]`}function qn(e,t=0,i=new WeakSet){if(t>Ta)return"[MAX_DEPTH]";if(e==null)return e;if(typeof e=="string")return Je(e,kt);if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e=="boolean")return e;if(typeof e=="bigint")return String(e);if(!(typeof e=="function"||typeof e=="symbol")&&typeof e=="object"){if(i.has(e))return"[CIRCULAR]";i.add(e);try{if(Array.isArray(e))return e.slice(0,ba).map(o=>qn(o,t+1,i));const r={};for(const[o,n]of Object.entries(e).slice(0,xa)){if(Pa.test(o)){r[o]=Ct;continue}const a=qn(n,t+1,i);a!==void 0&&(r[o]=a)}return r}finally{i.delete(e)}}}function En(e,t){return{instructions:Je(e??"",Aa),metadata:t?qn(t):void 0}}function Ya(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,o=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,a=t.recollectionCount===0||t.recollectionCount===1?t.recollectionCount:void 0;if(!(!i||!r||!o||!n||a===void 0||t.publicSafe!==!0))return{reason:i,base_source:r,repair:o,recollection_count:a,fallback_action:n,public_safe:!0}}class In extends Error{reason;source;byteLength;code;constructor(t,i,r,o,n){super(i),this.reason=r,this.source=o,this.byteLength=n,this.name="InvokeCliInputError",this.code=t}}function qa(e){const t=hn(e);return(t==="arch-plan"||t==="ui-ux-review")&&za(e,"--project-evidence")}function za(e,t){let i=null,r=-1,o=!1,n=!1;for(let a=0;a<=e.length;a+=1){const d=e[a];if(a===e.length||!i&&/\s/.test(d??"")){if(r>=0&&!o&&e.slice(r,a)===t)return!0;r=-1,o=!1,n=!1;continue}if(r<0&&(r=a),n){n=!1;continue}if(d==="\\"){n=!0;continue}(d==='"'||d==="'")&&(o=!0,i=i===d?null:i??d)}return!1}const Ja=/(?:^|\s)codex(?:-cli)?\s+([A-Za-z0-9][A-Za-z0-9._+-]{0,63})(?:\s|$)/i;function Ka(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 Be("codex",["--version"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim().match(Ja)?.[1]??null}catch{return null}}function zn(){return Qo({clientVersion:Pt,registryVersion:dt,registryChecksum:st})}class Jn 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 Kn 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 Qa(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,a]of Object.entries(i.epics)){const d=a;if(d&&d.stories!==void 0&&!Array.isArray(d.stories)){t.push({code:"EPIC_STORIES_NOT_ARRAY",message:`epic "${n}" has non-array \`stories\` field (expected string[] of story IDs)`});break}}const o=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?o&&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 Xa(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 Gd(){Kn=!1}function ri(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Xo(e){return e==="active"||e==="archived"||e==="rolled-back"||e==="synthetic"||e==="orphan"?e:void 0}const Zo=new Set(["goal","problem","desiredOutcome","rawIntent","context","users","surfaces","constraints","assumptions","risks","nonGoals","validationExpectations","debtRefs","repositoryEvidencePaths","journeyIds","screenIds","storybookStoryIds","backendContractIds","featureBlockerIds","remediationRefs","uiScope","remediationStory","examples","contracts"]),ec=/(?:[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}|(?:token|api[_-]?key|secret|password|credential|license[_-]?key)\s*[:=]\s*\S+|https?:\/\/(?:localhost|127\.0\.0\.1|10\.\d+\.\d+\.\d+|192\.168\.\d+\.\d+|172\.(?:1[6-9]|2\d|3[0-1])\.\d+\.\d+|[^\s/]*internal[^\s/]*)\S*|private\s+prompt|raw\s+vendor\s+corpus|sk-[A-Za-z0-9_-]{12,})/i;function tc(e,t){if(!g(e)||e.schemaVersion!==1||e.epicId!==t||!/^P\d+$/.test(t))return{};try{const i=JSON.stringify(e),n=Buffer.byteLength(i);if(n>16384)return{diagnostic:Object.freeze({schemaVersion:"CreateEpicPlanningProjectionDiagnostic/1.0",outcome:"omitted",reasonCode:"budget-omitted",byteLengthBucket:n<=32768?"16385-32768":"32769-plus",publicSafe:!0})};if(ec.test(i))return{};const a=(o,d)=>{if(Object.keys(o).some(s=>!d.includes(s)))throw new Error("planning-unknown-field")};if(a(e,["schemaVersion","epicId","intake","intakeRevision","diagnosisReceipt","researchReceipt","degradeAuthorization"]),!g(e.intake))return{};if(Object.keys(e.intake).some(o=>!Zo.has(o)))return{};for(const[o,d]of Object.entries(e.intake))if(["examples","contracts"].includes(o)){const s=o==="examples"?["id","title","actor","given","when","then","source","coveredRequirement","expectedValidation"]:["id","kind","description","path"];if(!Array.isArray(d)||d.length>16)return{};for(const l of d){if(!g(l))return{};if(a(l,s),Object.values(l).some(y=>typeof y!="string"||y.length>256))return{}}}else if(Array.isArray(d)){if(d.length>32||d.some(s=>typeof s!="string"||s.length>256))return{}}else if(typeof d=="string"){if(d.length>(o==="rawIntent"?aa:512))return{}}else if(typeof d!="boolean"||!["uiScope","remediationStory"].includes(o))return{};const r=["schemaVersion","kind","epicId","intakeRevision","artifactSummary","artifactDigest","predecessorReceiptId","accepted","receiptId"];for(const o of[e.diagnosisReceipt,e.researchReceipt])if(o!==void 0){if(!g(o))return{};if(a(o,r),Object.values(o).some(d=>typeof d=="string"&&d.length>1024))return{}}if(e.degradeAuthorization!==void 0){if(!g(e.degradeAuthorization))return{};a(e.degradeAuthorization,["approved","intakeRevision","reasonCodes","assumptionCodes"]);for(const o of["reasonCodes","assumptionCodes"]){const d=e.degradeAuthorization[o];if(!Array.isArray(d)||d.length>32||d.some(s=>typeof s!="string"||s.length>128))return{}}}return{checkpoint:JSON.parse(i)}}catch{return{}}}function ii(e){return e==="create-epic"||e==="discovered"?e:void 0}function de(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function nc(e){const t={};let i=!1;for(const n of["contracts","contract_refs","shared_surfaces","adr_refs","nfr_refs","acceptance_depends_on"]){if(e[n]===void 0)continue;const a=e[n];if(!Array.isArray(a)||a.length>128||a.some(r=>hn(r)===void 0)){i=!0;continue}t[n]=a.map(r=>hn(r))}if(e.planning!==void 0)try{if(!g(e.planning))throw new Error("planning-shape");const n=e.planning;for(const o of["claims","semanticArtifacts"]){if(n[o]===void 0)continue;const d=n[o];if(!Array.isArray(d)||d.length>128||d.some(s=>!g(s)||hn(s.ref)===void 0))throw new Error("planning-refs")}if(n.attempts!==void 0&&(!Array.isArray(n.attempts)||n.attempts.length>32))throw new Error("planning-attempts");for(const o of n.attempts??[]){if(!g(o)||!Array.isArray(o.reasonCodes)||o.reasonCodes.length>32||o.reasonCodes.some(d=>typeof d!="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(d)))throw new Error("planning-attempt-reasons");if(o.discoveredClaims!==void 0&&(!Array.isArray(o.discoveredClaims)||o.discoveredClaims.length>128||o.discoveredClaims.some(d=>!g(d)||hn(d.ref)===void 0)))throw new Error("planning-attempt-claims")}const{graphRevision:a,...r}=ro(n);t.planning=r}catch{i=!0}return i&&(t.planning={schemaVersion:1,dependencyBasis:"unknown",claims:[],semanticArtifacts:[]}),t}function g(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function _t(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function Q(e){if(typeof e!="string")return;const t=e.trim();if(t)return t.replace(/[^a-z0-9_.:-]+/gi,"_").slice(0,120)}function q(e){if(typeof e!="string")return;const t=e.trim(),i=Q(e);return i===t?i:void 0}function Ee(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240)&&/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(t)&&!(t.includes("..")||t.includes("//")||t.includes("@{")||t.endsWith("/")||t.endsWith("."))&&!t.split("/").some(i=>!i||i.startsWith(".")||i.endsWith(".lock")))return t}function R(e){return typeof e=="string"&&/^[0-9a-f]{7,64}$/i.test(e)?e:void 0}function De(e){if(!(typeof e!="string"||e.length>64)&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/.test(e))return Number.isFinite(Date.parse(e))?e:void 0}function pt(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240||t.includes("..")))return/^[A-Za-z0-9._:/#\-[\]]+$/.test(t)?t:void 0}function En(e){if(!g(e))return;const t=u=>typeof u=="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,95}$/.test(u),i=u=>typeof u=="string"&&/^[a-f0-9]{64}$/.test(u),n=(u,C)=>Array.isArray(u)&&u.length<=C&&u.every(t)&&new Set(u).size===u.length?u:void 0,a=(u,C)=>{if(!(!g(u)||u.schemaVersion!==2||!t(u.requestId)||!t(u.stageCommand)||!i(u.requestHash)||!i(u.inputHash)||!i(u.stateHash)||!i(u.nonce)||!i(u.stageRevision)||!i(u.stageHash)||!i(u.catalogHash)||u.targetEpicId!==void 0&&!t(u.targetEpicId)||C&&(!i(u.outputHash)||!i(u.artifactHash))))return{schemaVersion:2,...u.targetEpicId?{targetEpicId:u.targetEpicId}:{},requestId:u.requestId,requestHash:u.requestHash,inputHash:u.inputHash,stateHash:u.stateHash,nonce:u.nonce,stageCommand:u.stageCommand,stageRevision:u.stageRevision,stageHash:u.stageHash,catalogHash:u.catalogHash,...C?{outputHash:u.outputHash,artifactHash:u.artifactHash}:{}}},r=(u,C)=>{if(!(!g(u)||u.schemaVersion!=="1.1"||u.kind!==C||!i(u.receiptId)||!i(u.graphHash)||!i(u.evidenceHash)||!t(u.elementId)||!t(u.caseId)||!t(u.category)))return{schemaVersion:"1.1",kind:C,receiptId:u.receiptId,graphHash:u.graphHash,elementId:u.elementId,caseId:u.caseId,category:u.category,evidenceHash:u.evidenceHash}},o=(u,C)=>{if(!g(u)||u.kind!==C||!i(u.receiptId)||!n(u.evidenceIds,24)||C==="architecture-stage-completion"&&!["succeeded","failed"].includes(String(u.status))||C==="architecture-stage-validation"&&!["passed","failed","pending"].includes(String(u.status)))return;const E=a(u,!0);if(!E)return;const h=C==="architecture-stage-validation"?r(u.isolated,"isolated"):void 0,I=C==="architecture-stage-validation"?r(u.regression,"regression"):void 0;if(!(C==="architecture-stage-validation"&&(!h||!I)))return{...E,kind:C,receiptId:u.receiptId,status:u.status,evidenceIds:u.evidenceIds,...h&&I?{isolated:h,regression:I}:{}}},d={};e.schemaVersion===1&&(d.schemaVersion=1),e.owner==="root"&&(d.owner="root"),t(e.currentStageCommand)&&(d.currentStageCommand=e.currentStageCommand),["ask-user","delegate","resume","advance","blocked","complete"].includes(String(e.continuationState))&&(d.continuationState=e.continuationState);const s=n(e.questionIds,16);if(s&&(d.questionIds=s),(e.childStatus==="succeeded"||e.childStatus==="failed")&&(d.childStatus=e.childStatus),(e.evidencePolicy==="legacy-compatible"||e.evidencePolicy==="v2-required")&&(d.evidencePolicy=e.evidencePolicy),t(e.targetEpicId)&&(d.targetEpicId=e.targetEpicId),i(e.graphRevision)&&(d.graphRevision=e.graphRevision),e.graphSource==="committed-epic-v1"&&(d.graphSource=e.graphSource),e.nonUiScopeReceipt!==void 0){const u=Er(e.nonUiScopeReceipt);if(!u||u.targetEpicId!==e.targetEpicId||u.graphRevision!==e.graphRevision||!g(e.accounting)||u.accountingId!==e.accounting.accountingId||!g(e.evidenceExpectation)||u.rootInputSha256!==e.evidenceExpectation.inputHash)throw new Error("architecture-non-ui-scope-invalid");d.nonUiScopeReceipt=u}g(e.pactAnswerReceipt)&&Object.keys(e.pactAnswerReceipt).sort().join(",")===["schemaVersion","targetEpicId","graphRevision","stateSha256","answersSha256","questionIds","publicSafe"].sort().join(",")&&e.pactAnswerReceipt.schemaVersion==="PactAnswerReceipt/1"&&e.pactAnswerReceipt.targetEpicId===e.targetEpicId&&e.pactAnswerReceipt.graphRevision===e.graphRevision&&i(e.pactAnswerReceipt.stateSha256)&&i(e.pactAnswerReceipt.answersSha256)&&v(e.pactAnswerReceipt.questionIds,["PACT-Q1-CONSUMER","PACT-Q2-PROVIDER","PACT-Q3-BROKER","PACT-Q4-MATCHERS","PACT-Q5-VERIFY"])&&e.pactAnswerReceipt.publicSafe===!0&&(d.pactAnswerReceipt=e.pactAnswerReceipt);const l=a(e.evidenceExpectation,!1);l&&(d.evidenceExpectation=l);const y=o(e.completionEvidence,"architecture-stage-completion"),S=o(e.validationEvidence,"architecture-stage-validation");if(y&&(d.completionEvidence=y),S&&(d.validationEvidence=S),g(e.reviewDecision)&&Object.keys(e.reviewDecision).sort().join(",")===["schemaVersion","targetEpicId","graphRevision","artifactHash","completionReceiptId","validationReceiptId","decision","evidenceIds","publicSafe"].sort().join(",")&&e.reviewDecision.schemaVersion==="ArchitectureReviewDecision/1"&&e.reviewDecision.targetEpicId===e.targetEpicId&&e.reviewDecision.graphRevision===e.graphRevision&&i(e.reviewDecision.graphRevision)&&i(e.reviewDecision.artifactHash)&&i(e.reviewDecision.completionReceiptId)&&i(e.reviewDecision.validationReceiptId)&&["approved","changes-requested"].includes(String(e.reviewDecision.decision))&&e.reviewDecision.publicSafe===!0){const u=n(e.reviewDecision.evidenceIds,24);u&&u.length>0&&(d.reviewDecision={...e.reviewDecision,evidenceIds:u})}if(Ft(e.terminalMemoryCheckpoint,e))d.terminalMemoryCheckpoint=e.terminalMemoryCheckpoint;else if(g(e.terminalMemoryCheckpoint)&&e.terminalMemoryCheckpoint.schemaVersion===void 0&&["passed","failed","pending"].includes(String(e.terminalMemoryCheckpoint.status))){const u=n(e.terminalMemoryCheckpoint.evidenceIds,24);u&&(d.terminalMemoryCheckpoint={status:e.terminalMemoryCheckpoint.status,evidenceIds:u})}if(Array.isArray(e.acceptedStages)&&e.acceptedStages.length<=15){const u=e.acceptedStages.map(C=>{if(!g(C)||!t(C.targetEpicId)||!t(C.stageCommand))return;const E=o(C.completionEvidence,"architecture-stage-completion"),h=o(C.validationEvidence,"architecture-stage-validation");return E&&h?{targetEpicId:C.targetEpicId,stageCommand:C.stageCommand,completionEvidence:E,validationEvidence:h}:void 0});u.every(C=>C!==void 0)&&(d.acceptedStages=u)}if(g(e.accounting)&&e.accounting.schemaVersion===1&&t(e.accounting.contractVersion)&&t(e.accounting.accountingId)&&typeof e.accounting.charged=="boolean"&&Number.isInteger(e.accounting.chargedQuotaUnits)&&typeof e.accounting.chargedQuotaUnits=="number"&&e.accounting.chargedQuotaUnits>=0&&e.accounting.chargedQuotaUnits<=13){const u=n(e.accounting.receiptIds,32);u&&(d.accounting={schemaVersion:1,contractVersion:e.accounting.contractVersion,accountingId:e.accounting.accountingId,charged:e.accounting.charged,chargedQuotaUnits:e.accounting.chargedQuotaUnits,receiptIds:u,...["in-progress","aborted","timed-out","failed","complete"].includes(String(e.accounting.lastOutcome))?{lastOutcome:e.accounting.lastOutcome}:{}})}return JSON.stringify(d).length<=96e3?d:void 0}function rc(e){const t=g(e.metadata.archPlan)?e.metadata.archPlan.execution:void 0,i=g(t)?t.checkpoint:void 0,n=g(t)?t:void 0,a=g(i)?i:void 0,r=e.requestExecution,o=Array.isArray(a?.acceptedStages)?a.acceptedStages:[],d=r.currentStageCommand==="arch-prd"&&r.continuationState==="delegate"&&r.completionEvidence===void 0&&r.validationEvidence===void 0&&a?.currentStageCommand==="arch-prd"&&a.continuationState==="delegate"&&o.length===0&&n?.nextAction==="delegate",s=r.currentStageCommand==="arch-prd"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&a?.currentStageCommand==="arch-architecture"&&a.continuationState==="advance"&&o.length===1&&g(o[0])&&o[0].stageCommand==="arch-prd"&&v(o[0].completionEvidence,r.completionEvidence)&&v(o[0].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",l=r.currentStageCommand==="arch-architecture"&&r.continuationState==="advance"&&a?.currentStageCommand==="arch-architecture"&&a.continuationState==="delegate"&&o.length===1&&v(o,r.acceptedStages)&&n?.nextAction==="delegate",y=r.currentStageCommand==="arch-architecture"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&a?.currentStageCommand==="arch-fitness-functions"&&a.continuationState==="advance"&&o.length===2&&g(o[0])&&g(o[1])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===1&&v(o[0],r.acceptedStages[0])&&v(o[1].completionEvidence,r.completionEvidence)&&v(o[1].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",S=r.currentStageCommand==="arch-fitness-functions"&&r.continuationState==="advance"&&a?.currentStageCommand==="arch-fitness-functions"&&a.continuationState==="delegate"&&o.length===2&&g(o[0])&&g(o[1])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&v(o,r.acceptedStages)&&n?.nextAction==="delegate",u=r.currentStageCommand==="arch-fitness-functions"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&a?.currentStageCommand==="arch-api-contracts"&&a.continuationState==="advance"&&o.length===3&&g(o[0])&&g(o[1])&&g(o[2])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&o[2].stageCommand==="arch-fitness-functions"&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===2&&v(o.slice(0,2),r.acceptedStages)&&v(o[2].completionEvidence,r.completionEvidence)&&v(o[2].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",C=r.currentStageCommand==="arch-api-contracts"&&r.continuationState==="advance"&&a?.currentStageCommand==="arch-api-contracts"&&a.continuationState==="delegate"&&o.length===3&&g(o[0])&&g(o[1])&&g(o[2])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&o[2].stageCommand==="arch-fitness-functions"&&v(o,r.acceptedStages)&&n?.nextAction==="delegate",E=["PACT-Q1-CONSUMER","PACT-Q2-PROVIDER","PACT-Q3-BROKER","PACT-Q4-MATCHERS","PACT-Q5-VERIFY"],h=r.currentStageCommand==="arch-api-contracts"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&a?.currentStageCommand==="generate-pacts"&&a.continuationState==="ask-user"&&o.length===4&&g(o[3])&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===3&&v(o.slice(0,3),r.acceptedStages)&&o[3].stageCommand==="arch-api-contracts"&&v(o[3].completionEvidence,r.completionEvidence)&&v(o[3].validationEvidence,r.validationEvidence)&&v(a.questionIds,E)&&v(n?.questionIds,E)&&n?.nextAction==="ask-user",I=r.currentStageCommand==="generate-pacts"&&r.continuationState==="ask-user"&&a?.currentStageCommand==="generate-pacts"&&a.continuationState==="delegate"&&o.length===4&&v(o,r.acceptedStages)&&v(r.questionIds,E)&&v(a.questionIds,[])&&v(a.pactAnswerReceipt,e.answerReceipt)&&v(n?.pactAnswerReceipt,e.answerReceipt)&&e.answerReceipt?.stateSha256===e.sourceStateSha256&&n?.nextAction==="resume",b=r.currentStageCommand==="generate-pacts"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&v(r.pactAnswerReceipt,e.pactRecordedReceipt)&&a?.currentStageCommand==="arch-api-integrations"&&a.continuationState==="advance"&&o.length===5&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===4&&v(o.slice(0,4),r.acceptedStages)&&o.map(V=>g(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts"&&g(o[4])&&v(o[4].completionEvidence,r.completionEvidence)&&v(o[4].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",M=r.currentStageCommand==="arch-api-integrations"&&r.continuationState==="advance"&&a?.currentStageCommand==="arch-api-integrations"&&a.continuationState==="delegate"&&o.length===5&&v(o,r.acceptedStages)&&n?.nextAction==="delegate",P=r.currentStageCommand==="arch-api-integrations"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&a?.currentStageCommand==="arch-database"&&a.continuationState==="advance"&&o.length===6&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===5&&v(o.slice(0,5),r.acceptedStages)&&o.map(V=>g(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations"&&g(o[5])&&v(o[5].completionEvidence,r.completionEvidence)&&v(o[5].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",k=r.currentStageCommand==="arch-database"&&r.continuationState==="advance"&&a?.currentStageCommand==="arch-database"&&a.continuationState==="delegate"&&o.length===6&&v(o,r.acceptedStages)&&n?.nextAction==="delegate",_=r.currentStageCommand==="arch-database"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&a?.currentStageCommand==="arch-security"&&a.continuationState==="advance"&&o.length===7&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===6&&v(o.slice(0,6),r.acceptedStages)&&o.map(V=>g(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database"&&g(o[6])&&v(o[6].completionEvidence,r.completionEvidence)&&v(o[6].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",w=r.currentStageCommand==="arch-security"&&r.continuationState==="advance"&&a?.currentStageCommand==="arch-security"&&a.continuationState==="delegate"&&o.length===7&&v(o,r.acceptedStages)&&n?.nextAction==="delegate",L=r.currentStageCommand==="arch-security"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&a?.currentStageCommand==="arch-design-system"&&a.continuationState==="advance"&&o.length===8&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===7&&v(o.slice(0,7),r.acceptedStages)&&o.map(V=>g(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security"&&g(o[7])&&v(o[7].completionEvidence,r.completionEvidence)&&v(o[7].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",D=r.currentStageCommand==="arch-design-system"&&r.continuationState==="advance"&&a?.currentStageCommand==="arch-design-system"&&a.continuationState==="delegate"&&o.length===8&&v(o,r.acceptedStages)&&n?.nextAction==="delegate",Y=r.currentStageCommand==="arch-design-system"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&a?.currentStageCommand==="arch-ux-design"&&a.continuationState==="advance"&&o.length===9&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===8&&v(o.slice(0,8),r.acceptedStages)&&o.map(V=>g(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system"&&g(o[8])&&v(o[8].completionEvidence,r.completionEvidence)&&v(o[8].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",X=r.currentStageCommand==="arch-ux-design"&&r.continuationState==="advance"&&a?.currentStageCommand==="arch-ux-design"&&a.continuationState==="delegate"&&o.length===9&&v(o,r.acceptedStages)&&n?.nextAction==="blocked",pe=r.currentStageCommand==="arch-ux-design"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&a?.currentStageCommand==="arch-performance"&&a.continuationState==="advance"&&o.length===10&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===9&&v(o.slice(0,9),r.acceptedStages)&&o.map(V=>g(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design"&&g(o[9])&&v(o[9].completionEvidence,r.completionEvidence)&&v(o[9].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",x=r.currentStageCommand==="arch-performance"&&r.continuationState==="advance"&&a?.currentStageCommand==="arch-performance"&&a.continuationState==="delegate"&&o.length===10&&v(o,r.acceptedStages)&&n?.nextAction==="delegate",Se=r.currentStageCommand==="arch-performance"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&a?.currentStageCommand==="arch-testing"&&a.continuationState==="advance"&&o.length===11&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===10&&v(o.slice(0,10),r.acceptedStages)&&o.map(V=>g(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance"&&g(o[10])&&v(o[10].completionEvidence,r.completionEvidence)&&v(o[10].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",Z=r.currentStageCommand==="arch-testing"&&r.continuationState==="advance"&&a?.currentStageCommand==="arch-testing"&&a.continuationState==="delegate"&&o.length===11&&v(o,r.acceptedStages)&&n?.nextAction==="delegate",J=r.currentStageCommand==="arch-testing"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&a?.currentStageCommand==="arch-infrastructure"&&a.continuationState==="advance"&&o.length===12&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===11&&v(o.slice(0,11),r.acceptedStages)&&o.map(V=>g(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance,arch-testing"&&g(o[11])&&v(o[11].completionEvidence,r.completionEvidence)&&v(o[11].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",gt=r.currentStageCommand==="arch-infrastructure"&&r.continuationState==="advance"&&a?.currentStageCommand==="arch-infrastructure"&&a.continuationState==="delegate"&&o.length===12&&v(o,r.acceptedStages)&&n?.nextAction==="delegate",wt=r.currentStageCommand==="arch-infrastructure"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&a?.currentStageCommand==="arch-review"&&a.continuationState==="advance"&&o.length===13&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===12&&v(o.slice(0,12),r.acceptedStages)&&o.map(V=>g(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance,arch-testing,arch-infrastructure"&&g(o[12])&&v(o[12].completionEvidence,r.completionEvidence)&&v(o[12].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",ue=r.currentStageCommand==="arch-review"&&r.continuationState==="advance"&&a?.currentStageCommand==="arch-review"&&a.continuationState==="delegate"&&o.length===13&&v(o,r.acceptedStages)&&n?.nextAction==="delegate",O=r.currentStageCommand==="arch-review"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&r.reviewDecision===void 0&&a?.currentStageCommand==="arch-review"&&a.continuationState==="ask-user"&&o.length===13&&v(o,r.acceptedStages)&&v(a.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&v(a.completionEvidence,r.completionEvidence)&&v(a.validationEvidence,r.validationEvidence)&&n?.nextAction==="ask-user",$=r.currentStageCommand==="arch-review"&&r.continuationState==="ask-user"&&r.childStatus==="succeeded"&&g(r.reviewDecision)&&r.reviewDecision.decision==="approved"&&v(r.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&a?.currentStageCommand==="update-memory"&&a.continuationState==="advance"&&o.length===14&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===13&&v(o.slice(0,13),r.acceptedStages)&&g(o[13])&&o[13].stageCommand==="arch-review"&&v(o[13].completionEvidence,r.completionEvidence)&&v(o[13].validationEvidence,r.validationEvidence)&&v(a.reviewDecision,r.reviewDecision)&&n?.nextAction==="resume",xe=r.currentStageCommand==="update-memory"&&r.continuationState==="advance"&&g(r.reviewDecision)&&r.reviewDecision.decision==="approved"&&a?.currentStageCommand==="update-memory"&&a.continuationState==="delegate"&&o.length===14&&v(o,r.acceptedStages)&&v(a.reviewDecision,r.reviewDecision)&&n?.nextAction==="delegate",Te=r.currentStageCommand==="update-memory"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&a?.currentStageCommand==="update-memory"&&a.continuationState==="complete"&&o.length===15&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===14&&v(o.slice(0,14),r.acceptedStages)&&g(o[14])&&o[14].targetEpicId===r.targetEpicId&&o[14].stageCommand==="update-memory"&&v(o[14].completionEvidence,r.completionEvidence)&&v(o[14].validationEvidence,r.validationEvidence)&&v(a.reviewDecision,r.reviewDecision)&&v(a.completionEvidence,r.completionEvidence)&&v(a.validationEvidence,r.validationEvidence)&&Ft(a.terminalMemoryCheckpoint,r)!==null&&v(a.terminalMemoryCheckpoint,r.terminalMemoryCheckpoint)&&n?.nextAction==="complete",Pe=r.currentStageCommand==="update-memory"&&r.continuationState==="complete"&&r.childStatus==="succeeded"&&a?.currentStageCommand==="update-memory"&&a.continuationState==="complete"&&o.length===15&&v(o,r.acceptedStages)&&v(a.reviewDecision,r.reviewDecision)&&v(a.completionEvidence,r.completionEvidence)&&v(a.validationEvidence,r.validationEvidence)&&Ft(a.terminalMemoryCheckpoint,r)&&v(a.terminalMemoryCheckpoint,r.terminalMemoryCheckpoint)&&n?.nextAction==="complete",Nt=n?qi(r,n,Ft(r.terminalMemoryCheckpoint,r)&&v(a?.terminalMemoryCheckpoint,r.terminalMemoryCheckpoint)):void 0;if(e.metadata.mode!=="arch-plan"||e.metadata.resolvedTrigger!=="arch-plan"||!g(t)||!g(i)||t.owner!=="root"||t.currentStageCommand!==i.currentStageCommand||t.continuationState!==i.continuationState||i.owner!=="root"||i.evidencePolicy!=="v2-required"||i.targetEpicId!==r.targetEpicId||i.graphRevision!==r.graphRevision||i.graphSource!==r.graphSource||!/^P[1-9][0-9]{0,11}$/.test(String(i.targetEpicId))||!/^[a-f0-9]{64}$/.test(String(i.graphRevision))||!Array.isArray(i.acceptedStages)||!(Nt||d||s||l||y||S||u||C||h||I||b||M||P||k||_||w||L||D||Y||X||pe||x||Se||Z||J||gt||wt||ue||O||$||xe||Te||Pe)||!g(i.accounting)||i.accounting.charged!==!0||!v(En(i),i))throw new Error("architecture-root-checkpoint-invalid");const rt=z(e.projectRoot,".neocortex"),K=z(rt,"state.json"),ve=z(rt,"state.json.architecture.lock"),he=zt(ve,"wx",384);let qe;try{const V=Vt(K);if(!V.isFile()||V.isSymbolicLink())throw new Error("architecture-root-state-binding-invalid");const ft=Fe(K,"utf8");if(Ne("sha256").update(ft).digest("hex")!==e.sourceStateSha256)throw new Error("architecture-root-state-conflict");const ge=JSON.parse(ft),oe=g(ge)&&g(ge.archPlan)?ge.archPlan:{};if(!g(ge)||!g(ge.epics)||!Object.hasOwn(ge.epics,i.targetEpicId)||(e.initialBinding?oe.execution!==void 0||r.graphSource!=="committed-epic-v1":!v(En(oe.execution),r))||g(ge.scope)&&ge.scope.kind==="projected")throw new Error("architecture-root-state-binding-invalid");if(r.graphSource==="committed-epic-v1"&&r.graphRevision!==Yt(e.projectRoot,String(r.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");if(Pe||Nt==="complete-replay"){const Lt={...r,continuationState:"delegate",acceptedStages:r.acceptedStages.slice(0,Ir(r))};if(!v(r.terminalMemoryCheckpoint,Ln(e.projectRoot,Lt)))throw new Error("architecture-root-state-conflict");return}const ye=dn(),Ve=Ge("git",["rev-parse","--git-common-dir"],{cwd:e.projectRoot,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),ee=Zi(Ve)?Mn(Ve):Mn(e.projectRoot,Ve);if(Xi(ee)!==ee)throw new Error("architecture-root-backup-dir-invalid");const mt=z(ee,"neocortex-architecture");qt(mt,{recursive:!0,mode:448});const ze=Vt(mt);if(!ze.isDirectory()||ze.isSymbolicLink()||ze.uid!==process.getuid?.()||(ze.mode&63)!==0)throw new Error("architecture-root-backup-dir-invalid");const ke=z(mt,`state-backup-${ye}.json`),Qe=zt(ke,"wx",384);try{pn(Qe,ft),ln(Qe)}finally{Jt(Qe)}const H=zt(mt,"r");try{ln(H)}finally{Jt(H)}const bn={...ge,archPlan:{...oe,execution:i}};qe=z(rt,`state.json.architecture-tmp-${ye}`);const it=zt(qe,"wx",384);try{pn(it,`${JSON.stringify(bn,null,2)}
|
|
8
|
-
`),ln(it)}finally{Jt(it)}if((Te||Nt==="complete")&&!v(r.terminalMemoryCheckpoint,Ln(e.projectRoot,r)))throw new Error("architecture-root-state-conflict");if(r.graphSource==="committed-epic-v1"&&r.graphRevision!==Yt(e.projectRoot,String(r.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");vr(qe,K),qe=void 0;const N=zt(rt,"r");try{ln(N)}finally{Jt(N)}}finally{if(qe)try{Dn(qe)}catch{}Jt(he),Dn(ve)}}function Sn(e,t){if(!g(e))return;const i={};for(const n of t){const a=e[n];if(typeof a=="boolean")i[n]=a;else if(typeof a=="number"&&Number.isFinite(a))i[n]=a;else if(typeof a=="string"){const r=Q(a);r&&(i[n]=r)}}return Object.keys(i).length>0?i:void 0}function vn(e){return e==="epic"||e==="story"?e:void 0}function ai(e){if(!g(e)||e.schemaVersion!==1)return;const t=q(e.ownerStoryId),i=q(e.sessionId),n=q(e.idempotencyKey),a=De(e.acquiredAt),r=De(e.expiresAt);if(!(!t||!i||!n||!a||!r||Date.parse(r)<=Date.parse(a)))return{schemaVersion:1,ownerStoryId:t,sessionId:i,idempotencyKey:n,acquiredAt:a,expiresAt:r}}function oi(e){if(!g(e)||e.schemaVersion!==1)return;const t=q(e.storyId),i=q(e.epicId),n=Ee(e.branch),a=R(e.baseSha),r=R(e.headSha),o=q(e.idempotencyKey),d=De(e.recordedAt),s=de(e.commits).map(R).filter(M=>!!M).slice(0,256),l=de(e.receiptRefs).map(pt).filter(M=>!!M).slice(0,256),y=e.dispatchId===void 0?void 0:q(e.dispatchId),S=e.bundleId===void 0?void 0:q(e.bundleId),u=e.bundleDigest===void 0?void 0:R(e.bundleDigest),C=e.graphRevision===void 0?void 0:R(e.graphRevision),E=e.claimRevision===void 0?void 0:q(e.claimRevision),h=ic(e.qaReceipt),I=ac(e.reviewReceipt),b=e.rootMemoryEffect===void 0?void 0:So(e.rootMemoryEffect)?e.rootMemoryEffect:void 0;if(!(!t||!i||!t.startsWith(`${i}.`)||!n||!a||!r||a===r||!o||!d||s.length===0||l.length===0||!Array.isArray(e.commits)||s.length!==e.commits.length||e.commits.length>256||!Array.isArray(e.receiptRefs)||l.length!==e.receiptRefs.length||e.receiptRefs.length>256||e.dispatchId!==void 0&&!y||e.bundleId!==void 0&&!S||e.bundleDigest!==void 0&&(!u||u.length!==64)||e.graphRevision!==void 0&&(!C||C.length!==64)||e.claimRevision!==void 0&&!E||e.rootMemoryEffect!==void 0&&(!b||b.storyId!==t||b.epicId!==i||b.executionBranch!==n||b.sourceHeadSha!==a||b.childClaimRevision!==E)||e.qaVerdict!=="passed"&&e.qaVerdict!=="blocked"||!["approved","changes-requested","pending"].includes(String(e.reviewVerdict))||!h||e.reviewVerdict!=="pending"&&!I||e.reviewVerdict==="pending"&&I||h.verdict!==e.qaVerdict||I&&I.verdict!==e.reviewVerdict||!di(h,{storyId:t,epicId:i,baseSha:a,headSha:r,bundleDigest:u,graphRevision:C})||I&&(!di(I,{storyId:t,epicId:i,baseSha:a,headSha:r,bundleDigest:u,graphRevision:C})||I.qaReceiptRef!==h?.receiptRef||I.receiptRef===h?.receiptRef)||!l.includes(String(h.receiptRef))||I&&(!l.includes(String(I.receiptRef))||Date.parse(String(I.reviewedAt))<Date.parse(String(h.checkedAt)))))return{schemaVersion:1,storyId:t,epicId:i,branch:n,baseSha:a,headSha:r,idempotencyKey:o,...y?{dispatchId:y}:{},...S?{bundleId:S}:{},...u?{bundleDigest:u}:{},...C?{graphRevision:C}:{},...E?{claimRevision:E}:{},...b?{rootMemoryEffect:structuredClone(b)}:{},qaVerdict:e.qaVerdict,reviewVerdict:e.reviewVerdict,...h?{qaReceipt:h}:{},...I?{reviewReceipt:I}:{},recordedAt:d,commits:s,receiptRefs:l}}function ic(e){if(!g(e)||e.schemaVersion!==1||e.kind!=="story_qa_evidence"||e.producer!=="local-yolo-tdd"||e.evidenceVersion!==void 0&&e.evidenceVersion!=="git-immutable-v1"&&e.evidenceVersion!=="p205-execution-v2"||!["passed","blocked"].includes(String(e.verdict)))return;const t=q(e.storyId),i=q(e.epicId),n=R(e.baseSha),a=R(e.headSha),r=R(e.bundleDigest),o=R(e.graphRevision),d=R(e.sourceEvidenceDigest),s=De(e.checkedAt),l=pt(e.receiptRef),y=e.evidenceVersion==="p205-execution-v2"&&e.contract==="P205-CI-02"?e.contract:void 0,S=e.evidenceVersion==="p205-execution-v2"&&e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,u=e.evidenceVersion==="p205-execution-v2"?R(e.manifestDigest):void 0,C=e.evidenceVersion==="p205-execution-v2"?R(e.resultDigest):void 0,E=e.evidenceVersion==="p205-execution-v2"?de(e.gateIds).map(q).filter(h=>!!h).slice(0,64):void 0;if(!(!t||!i||!n||!a||!r||r.length!==64||!o||o.length!==64||!d||d.length!==64||!s||!l||e.evidenceVersion==="p205-execution-v2"&&(!y||S!=="node scripts/test-root.mjs --gate complete"||!u||u.length!==64||!C||C.length!==64||!Array.isArray(e.gateIds)||!E||E.length===0||E.length!==e.gateIds.length)))return{schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",...e.evidenceVersion?{evidenceVersion:e.evidenceVersion}:{},storyId:t,epicId:i,...e.evidenceVersion==="p205-execution-v2"?{contract:y,command:S,manifestDigest:u,gateIds:E,resultDigest:C}:{},baseSha:n,headSha:a,bundleDigest:r,graphRevision:o,sourceEvidenceDigest:d,verdict:e.verdict,checkedAt:s,receiptRef:l}}function ci(e){if(!g(e)||e.schemaVersion!==1||e.kind!=="story_checkpoint_physical_verification"||e.producer!=="client-p205-transient-v1"||e.publicSafe!==!0||e.verdict!=="verified"&&e.verdict!=="rejected")return;const t=q(e.storyId),i=q(e.epicId),n=Ee(e.branch),a=R(e.baseSha),r=R(e.headSha),o=R(e.aggregateHeadSha),d=R(e.commitBodyDigest),s=R(e.changedPathsDigest),l=e.claimVerification==="canonical"||e.claimVerification==="legacy-migration"?e.claimVerification:void 0,y=R(e.effectiveClaimRevision),S=e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,u=R(e.manifestDigest),C=de(e.gateIds).map(q).filter(k=>!!k).slice(0,64),E=R(e.resultDigest),h=R(e.graphRevision),I=R(e.executionEvidenceDigest),b=R(e.sourceEvidenceDigest),M=De(e.verifiedAt),P=de(e.reasonCodes).map(q).filter(k=>!!k).slice(0,16);if(!(!t||!i||!n||!a||a.length<40||!r||r.length<40||!o||o.length<40||!d||d.length!==64||!s||s.length!==64||!l||!y||y.length!==64||!S||!u||u.length!==64||!Array.isArray(e.gateIds)||C.length!==e.gateIds.length||!E||E.length!==64||!h||h.length!==64||!I||I.length!==64||!b||b.length!==64||!M||P.length===0||e.verdict==="verified"&&(C.length===0||!P.includes("checkpoint-p205-transient-verified"))))return{schemaVersion:1,kind:"story_checkpoint_physical_verification",producer:"client-p205-transient-v1",storyId:t,epicId:i,branch:n,baseSha:a,headSha:r,aggregateHeadSha:o,commitBodyDigest:d,changedPathsDigest:s,claimVerification:l,effectiveClaimRevision:y,command:S,manifestDigest:u,gateIds:C,resultDigest:E,graphRevision:h,executionEvidenceDigest:I,sourceEvidenceDigest:b,verifiedAt:M,verdict:e.verdict,reasonCodes:P,publicSafe:!0}}function si(e){const t=["schemaVersion","kind","producer","storyId","epicId","branch","baseSha","headSha","graphRevision","effectiveClaimRevision","sourceEvidenceDigest","verifiedAt","reasonCodes","integrationAuthorized","publicSafe"];if(!g(e)||Object.keys(e).some(u=>!t.includes(u))||e.schemaVersion!==1||e.kind!=="story_scheduling_checkpoint_evidence"||e.producer!=="client-git-physical-v1"||e.integrationAuthorized!==!1||e.publicSafe!==!0)return;const i=q(e.storyId),n=q(e.epicId),a=Ee(e.branch),r=R(e.baseSha),o=R(e.headSha),d=R(e.graphRevision),s=R(e.effectiveClaimRevision),l=R(e.sourceEvidenceDigest),y=De(e.verifiedAt),S=de(e.reasonCodes).map(q).filter(u=>!!u);if(!(!i||!n||!a||!r||r.length<40||!o||o.length<40||!d||d.length!==64||!s||s.length!==64||!l||l.length!==64||!y||!Array.isArray(e.reasonCodes)||S.length!==1||S[0]!=="checkpoint-git-scheduling-verified"))return{schemaVersion:1,kind:"story_scheduling_checkpoint_evidence",producer:"client-git-physical-v1",storyId:i,epicId:n,branch:a,baseSha:r,headSha:o,graphRevision:d,effectiveClaimRevision:s,sourceEvidenceDigest:l,verifiedAt:y,reasonCodes:S,integrationAuthorized:!1,publicSafe:!0}}function ac(e){if(!g(e)||e.schemaVersion!==1||e.kind!=="story_review_evidence"||e.producer!=="root-commit-range-review"||!["approved","changes-requested"].includes(String(e.verdict)))return;const t=q(e.storyId),i=q(e.epicId),n=R(e.baseSha),a=R(e.headSha),r=R(e.bundleDigest),o=R(e.graphRevision),d=R(e.sourceEvidenceDigest),s=pt(e.qaReceiptRef),l=De(e.reviewedAt),y=pt(e.receiptRef);if(!(!t||!i||!n||!a||!r||r.length!==64||!o||o.length!==64||!d||d.length!==64||!s||!l||!y))return{schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:t,epicId:i,baseSha:n,headSha:a,bundleDigest:r,graphRevision:o,sourceEvidenceDigest:d,qaReceiptRef:s,verdict:e.verdict,reviewedAt:l,receiptRef:y}}function di(e,t){return["storyId","epicId","baseSha","headSha","bundleDigest","graphRevision"].every(i=>e[i]===t[i])}function pi(e){if(!g(e))return;const t=e.schemaVersion===1&&e.capturedFromCurrentCheckout===!0&&e.capturedFrom===void 0,i=e.schemaVersion===2&&e.capturedFromCurrentCheckout===void 0&&(e.capturedFrom==="current-checkout"||e.capturedFrom==="branch-ref");if(!t&&!i)return;const n=Ee(e.originBranch),a=R(e.originHeadSha),r=Ee(e.executionBranch),o=De(e.capturedAt);if(!(!n||!a||a.length<40||!r||!o||n===r))return t?{schemaVersion:1,originBranch:n,originHeadSha:a,executionBranch:r,capturedFromCurrentCheckout:!0,capturedAt:o}:{schemaVersion:2,originBranch:n,originHeadSha:a,executionBranch:r,capturedFrom:e.capturedFrom,capturedAt:o}}function li(e){if(!g(e)||e.schemaVersion!==1||e.verdict!=="passed")return;const t=R(e.executionHeadSha),i=R(e.graphRevision),n=De(e.checkedAt),a=pt(e.receiptRef),r=de(e.gateIds).map(q).filter(y=>!!y).slice(0,128),o=e.evidenceVersion==="p205-execution-v2"&&e.producer==="local-yolo-tdd"&&e.contract==="P205-CI-02"&&e.command==="node scripts/test-root.mjs --gate complete",d=e.evidenceVersion===void 0&&e.producer===void 0&&e.contract===void 0&&e.command===void 0&&e.manifestDigest===void 0&&e.resultDigest===void 0,s=o?R(e.manifestDigest):void 0,l=o?R(e.resultDigest):void 0;if(!(!t||t.length<40||!i||i.length!==64||!n||!a||r.length===0||!Array.isArray(e.gateIds)||r.length!==e.gateIds.length||e.gateIds.length>128||!d&&!o||o&&(!s||s.length!==64||!l||l.length!==64)))return{schemaVersion:1,...o?{evidenceVersion:"p205-execution-v2",producer:"local-yolo-tdd",contract:"P205-CI-02",command:"node scripts/test-root.mjs --gate complete",manifestDigest:s,resultDigest:l}:{},verdict:"passed",executionHeadSha:t,graphRevision:i,checkedAt:n,receiptRef:a,gateIds:r}}const oc=16384;function cc(e){if(!g(e))return;const t=(n,a)=>n===null||typeof n=="boolean"?!0:typeof n=="number"?Number.isFinite(n):typeof n=="string"?n.length<=512&&!n.startsWith("/")&&!/^[A-Za-z]:[\\/]/.test(n)&&!n.includes("\\")&&!/:\/\//.test(n)&&!/[\u0000-\u001f]/.test(n):a>=4?!1:Array.isArray(n)?n.length<=256&&n.every(r=>t(r,a+1)):g(n)?Object.keys(n).length<=64&&Object.entries(n).every(([r,o])=>/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(r)&&t(o,a+1)):!1;if(!t(e,0))return;const i=JSON.stringify(e);if(!(Buffer.byteLength(i,"utf8")>oc))return JSON.parse(i)}function ui(e){if(!g(e)||e.schemaVersion!==1||e.kind!=="epic_head_reconciliation"||e.producer!=="client-p205-head-reconciliation-v1"||e.publicSafe!==!0)return;const t={schemaVersion:1,kind:"epic_head_reconciliation",producer:"client-p205-head-reconciliation-v1",epicId:q(e.epicId),executionBranch:Ee(e.executionBranch),originBranch:Ee(e.originBranch),graphRevision:R(e.graphRevision),originHeadSha:R(e.originHeadSha),lastAcceptedCheckpointHeadSha:R(e.lastAcceptedCheckpointHeadSha),executionHeadSha:R(e.executionHeadSha),acceptedCheckpointIds:de(e.acceptedCheckpointIds),acceptedCheckpointHeads:de(e.acceptedCheckpointHeads),reconciliationCommitShas:de(e.reconciliationCommitShas),commitRangeDigest:R(e.commitRangeDigest),changedPaths:de(e.changedPaths),changedPathsDigest:R(e.changedPathsDigest),allowedWriteSet:de(e.allowedWriteSet),allowedWriteSetDigest:R(e.allowedWriteSetDigest),aggregateReceiptRef:pt(e.aggregateReceiptRef),aggregateManifestDigest:R(e.aggregateManifestDigest),aggregateResultDigest:R(e.aggregateResultDigest),producedAt:De(e.producedAt),revalidatedAt:De(e.revalidatedAt),publicSafe:!0},i=["originSyncHeadSha","originSyncCommitShas","originSyncPaths","originSyncPathsDigest","originSyncResolvedPaths","originSyncResolvedPathsDigest"],n=i.filter(d=>e[d]!==void 0).length;if(n!==0&&n!==i.length)return;const a=n===0?void 0:{originSyncHeadSha:R(e.originSyncHeadSha),originSyncCommitShas:de(e.originSyncCommitShas),originSyncPaths:de(e.originSyncPaths),originSyncPathsDigest:R(e.originSyncPathsDigest),originSyncResolvedPaths:de(e.originSyncResolvedPaths),originSyncResolvedPathsDigest:R(e.originSyncResolvedPathsDigest)};if(a&&(!a.originSyncHeadSha||a.originSyncHeadSha.length<40||a.originSyncCommitShas.length===0||a.originSyncCommitShas.length>256||a.originSyncCommitShas.some(d=>!/^[a-f0-9]{40,64}$/i.test(d))||a.originSyncPaths.length>2048||a.originSyncResolvedPaths.length>64||a.originSyncPathsDigest!==gn(a.originSyncPaths)||a.originSyncResolvedPathsDigest!==gn(a.originSyncResolvedPaths))||!t.epicId||!t.executionBranch||!t.originBranch||!t.graphRevision||t.graphRevision.length!==64||!t.originHeadSha||t.originHeadSha.length<40||!t.lastAcceptedCheckpointHeadSha||t.lastAcceptedCheckpointHeadSha.length<40||!t.executionHeadSha||t.executionHeadSha.length<40||t.acceptedCheckpointIds.length===0||t.acceptedCheckpointIds.length>2048||t.acceptedCheckpointIds.length!==t.acceptedCheckpointHeads.length||t.acceptedCheckpointHeads.some(d=>!/^[a-f0-9]{40,64}$/i.test(d))||t.reconciliationCommitShas.length>2048||t.reconciliationCommitShas.some(d=>!/^[a-f0-9]{40,64}$/i.test(d))||t.changedPaths.length>2048||(t.lastAcceptedCheckpointHeadSha===t.executionHeadSha?t.reconciliationCommitShas.length!==0||t.changedPaths.length!==0:t.reconciliationCommitShas.length===0||t.changedPaths.length===0)||t.allowedWriteSet.length===0||t.allowedWriteSet.length>2048||!t.commitRangeDigest||!t.changedPathsDigest||!t.allowedWriteSetDigest||!t.aggregateReceiptRef||!t.aggregateManifestDigest||!t.aggregateResultDigest||!t.producedAt||!t.revalidatedAt||t.commitRangeDigest!==ao(t.lastAcceptedCheckpointHeadSha,t.executionHeadSha,t.reconciliationCommitShas)||t.changedPathsDigest!==gn(t.changedPaths)||t.allowedWriteSetDigest!==gn(t.allowedWriteSet))return;const r={...t,...a??{}},o=R(e.inputDigest);if(!(!o||o.length!==64||o!==io(r)))return{...r,inputDigest:o}}function Qn(e){if(!g(e)||e.schemaVersion!==1)return;const t=Sn(e,["schemaVersion","kind","storyId","epicId","baseSha","headSha","originalBaseSha","originalHeadSha","gitPullRequest","preservesLaterCommits","historyRewrite","recordedAt"])??{},i=de(e.receiptRefs).map(pt).filter(a=>!!a).slice(0,256),n=de(e.revertCommits).map(Q).filter(a=>!!a).slice(0,256);return{...t,...i.length?{receiptRefs:i}:{},...n.length?{revertCommits:n}:{}}}function sc(e){if(!(!g(e)||Object.keys(e).sort().join(",")!=="gitPullRequest,headSha,kind,prNumber,reviewEvidenceDigest,schemaVersion"||e.schemaVersion!==1||e.kind!=="git-pull-request"||e.gitPullRequest!==!0||!Number.isSafeInteger(e.prNumber)||Number(e.prNumber)<=0||typeof e.headSha!="string"||!/^[a-f0-9]{40}$/.test(e.headSha)||typeof e.reviewEvidenceDigest!="string"||!/^[a-f0-9]{64}$/.test(e.reviewEvidenceDigest)))return{schemaVersion:1,kind:"git-pull-request",gitPullRequest:!0,prNumber:e.prNumber,headSha:e.headSha,reviewEvidenceDigest:e.reviewEvidenceDigest}}function hi(e){if(!g(e)||e.schemaVersion!==1||e.publicSafe!==!0)return;const t=q(e.epicId),i=Ee(e.executionBranch),n=Ee(e.originBranch),a=R(e.baseSha),r=R(e.executionHeadSha),o=e.mergeSha===void 0?void 0:R(e.mergeSha),d=e.pushedSha===void 0?void 0:R(e.pushedSha),s=q(e.idempotencyKey),l=De(e.attemptStartedAt),y=e.completedAt===void 0?void 0:De(e.completedAt),S=de(e.localGateReceiptRefs).map(pt).filter(h=>!!h).slice(0,256),u=de(e.reasonCodes).map(q).filter(h=>!!h).slice(0,64),C=pc(e.candidateQa),E=dc(e.providerGuard);if(!(!t||!i||!n||!a||!r||!s||!l||S.length===0||u.length===0||!["direct","single_pr"].includes(String(e.strategy))||!["prepared","merged","pushed","denied_external_gate","blocked_local_or_repo"].includes(String(e.physicalStatus))||typeof e.retryEligible!="boolean"||e.providerGuard!==void 0&&!E||E&&(e.strategy!=="single_pr"||e.physicalStatus!=="pushed"||E.prHeadSha!==o||E.originHeadSha!==a)))return{schemaVersion:1,epicId:t,executionBranch:i,originBranch:n,baseSha:a,executionHeadSha:r,...o?{mergeSha:o}:{},...d?{pushedSha:d}:{},strategy:e.strategy,..._t(e.prNumber)?{prNumber:_t(e.prNumber)}:{},physicalStatus:e.physicalStatus,localGateReceiptRefs:S,idempotencyKey:s,attemptStartedAt:l,...C?{candidateQa:C}:{},...E?{providerGuard:E}:{},...y?{completedAt:y}:{},retryEligible:e.retryEligible,reasonCodes:u,publicSafe:!0}}function dc(e){if(!g(e)||e.schemaVersion!==1||e.provider!=="github"||e.publicSafe!==!0)return;const t=String(e.mode),i=String(e.source),n=t==="recovered_exact_tree"?i==="physical_recovery":t==="strict_up_to_date_expected_head"&&["branch_protection","ruleset","branch_protection_and_ruleset"].includes(i),a=R(e.prHeadSha),r=R(e.originHeadSha),o=De(e.checkedAt);if(!(!n||!a||!r||!o))return{schemaVersion:1,provider:"github",mode:t,source:i,prHeadSha:a,originHeadSha:r,checkedAt:o,publicSafe:!0}}function pc(e){if(!g(e)||e.schemaVersion!==1||e.kind!=="epic_merge_candidate_qa"||e.contract!=="P205-CI-02"||e.command!==Xt)return;const i=Object.fromEntries(["originHeadSha","executionHeadSha","mergeSha","treeSha","graphRevision","manifestDigest","resultDigest"].map(o=>[o,R(e[o])])),n=De(e.checkedAt),a=pt(e.receiptRef),r=de(e.gateIds).filter(o=>/^[a-z0-9-]+$/.test(o)).slice(0,128);if(!(Object.values(i).some(o=>!o)||!n||!a||r.length===0))return{schemaVersion:1,kind:e.kind,contract:e.contract,command:e.command,...i,checkedAt:n,receiptRef:a,gateIds:r}}function lc(e){if(!g(e))return;const t={...Q(e.active_epic_id??e.activeEpicId)?{active_epic_id:Q(e.active_epic_id??e.activeEpicId)}:{},...Q(e.active_story_id??e.activeStoryId)?{active_story_id:Q(e.active_story_id??e.activeStoryId)}:{},...Q(e.active_step_id??e.activeStepId)?{active_step_id:Q(e.active_step_id??e.activeStepId)}:{},...Q(e.session_id??e.sessionId)?{session_id:Q(e.session_id??e.sessionId)}:{},...Q(e.started_at??e.startedAt)?{started_at:Q(e.started_at??e.startedAt)}:{}};return Object.keys(t).length>0?t:void 0}function uc(e){const t=Sn(e.completionEvidence??e.completion_evidence,["prNumber","pr_number","prState","pr_state","pullRequestState","merged","mergedAt","issueNumber","issue_number","issueState","issue_state","closedAt"]),i=Sn(e.issueCloseAudit??e.issue_close_audit,["schema_version","event","storyId","epicId","issueNumber","closedAt","publicSafe","rawLogStorage"]),n=Sn(e.scopedCiEvidence??e.scoped_ci_evidence,["schema_version","storyId","epicId","prNumber","finalState","publicSafe","rawLogStorage"]);return{...typeof e.merged=="boolean"?{merged:e.merged}:{},...typeof e.safeToContinueYoloop=="boolean"?{safeToContinueYoloop:e.safeToContinueYoloop}:{},...typeof e.mergeBlockedRemotely=="boolean"?{mergeBlockedRemotely:e.mergeBlockedRemotely}:{},...Q(e.physicalMergeStatus)?{physicalMergeStatus:Q(e.physicalMergeStatus)}:{},...Q(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)?{pr_state:Q(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)}:{},...Q(e.issue_state??e.issueState??e.workflow_issue_state)?{issue_state:Q(e.issue_state??e.issueState??e.workflow_issue_state)}:{},..._t(e.issue_number??e.issueNumber)?{issue_number:_t(e.issue_number??e.issueNumber)}:{},...t?{completionEvidence:t}:{},...i?{issueCloseAudit:i}:{},...n?{scopedCiEvidence:n}:{}}}class lt extends Error{reasonCode;constructor(t){super(t),this.name="StateSnapshotIntegrityError",this.reasonCode=t}}const hc=new Set(["yolo","yoloop","finalize-epic","audit"]);function gi(e){return typeof e=="string"&&hc.has(e)}function Xn(e,t={}){const i=z(e,".neocortex","state.json");if(!jt(i))throw new lt("git-lifecycle-state-missing");let n;try{n=JSON.parse(Fe(i,"utf8"))}catch{throw new lt("git-lifecycle-state-corrupt")}if(!g(n)||!g(n.epics)||!g(n.stories))throw new lt("git-lifecycle-state-shape-invalid");const a=Object.values(n.epics).some(r=>g(r)&&(r.branch_mode==="epic"||Ee(r.execution_branch)!==void 0));if(a)try{fn(e,{required:!0})}catch(r){const o=r instanceof Error&&/^git-lifecycle-/.test(r.message)?r.message:"git-lifecycle-runtime-invalid";if(t.allowMissingRuntime&&o==="git-lifecycle-runtime-missing")return{lifecycleDeclared:!0,runtimeMissing:!0};throw new lt(o)}return{lifecycleDeclared:a,runtimeMissing:!1}}function Cn(e,t={}){const i=z(e,".neocortex","state.json");if(!jt(i)){if(t.epicAware&&!t.projectless)throw new lt("git-lifecycle-state-missing");return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}let n,a;try{const E=Fe(i,"utf-8");a=Ne("sha256").update(E).digest("hex");const h=Ea(e,a)??JSON.parse(E),I=g(h.epics)?h.epics:{},b=Object.values(I).some(w=>g(w)&&(w.branch_mode==="epic"||Ee(w.execution_branch)!==void 0)),M=fn(e,{required:!!(t.epicAware&&b&&!t.projectless)});n=Br(h,M);const P=g(n.stories)?n.stories:{},k=g(n.epics)?n.epics:{},_=g(h.stories)?h.stories:{};for(const[w,L]of Object.entries(P)){const D=g(L)?L:void 0;if(!D?.checkpoint)continue;const Y=typeof D.epic_id=="string"?D.epic_id:w.split(".")[0],X=g(k[Y])?k[Y]:void 0,pe=Ee(X?.execution_branch);if(!pe)continue;const x=oo(e,D.checkpoint,w,Y,pe,t.p205Authorities?.[w],Ur(w,D,g(D.checkpoint)?D.checkpoint:void 0));if(x.kind==="integration-authorized")D.checkpoint_verification=x.verification,delete D.scheduling_checkpoint_evidence;else if(x.kind==="scheduling-only")D.scheduling_checkpoint_evidence=x.evidence,delete D.checkpoint,delete D.checkpoint_verification;else if(x.kind==="rejected"){D.checkpoint_verification=x.verification,delete D.scheduling_checkpoint_evidence;const Se=g(_[w])?_[w]:void 0;if(delete D.checkpoint,M.stories[w]?.checkpoint!==void 0)for(const Z of["status","last_step","steps_completed"])Se&&Object.prototype.hasOwnProperty.call(Se,Z)?D[Z]=structuredClone(Se[Z]):delete D[Z];["done","completed","merged"].includes(String(D.status).toLowerCase())&&(D.status="blocked")}}}catch(E){if(t.epicAware&&!t.projectless){const h=E instanceof Error&&/^git-lifecycle-/.test(E.message)?E.message:"git-lifecycle-state-corrupt";throw new lt(h)}return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}try{const E=Ko(n);E.length>0&&Qo(E)}catch{}const r=n.config??n.project??{},o=n.stories??{},d={};for(const[E,h]of Object.entries(o)){const I=g(h.review_request)&&h.review_request.kind==="git-pull-request"?sc(h.review_request):Qn(h.review_request);d[E]={id:h.id??E,title:h.title,epic_id:h.epic_id,status:h.status??"backlog",...ii(h.source)?{source:ii(h.source)}:{},steps_completed:h.steps_completed??[],last_step:h.last_step??null,branch_name:h.branch_name??null,pr_number:h.pr_number,...vn(h.branch_mode)?{branch_mode:vn(h.branch_mode)}:{},...oi(h.checkpoint)?{checkpoint:oi(h.checkpoint)}:{},...ci(h.checkpoint_verification)?{checkpoint_verification:ci(h.checkpoint_verification)}:{},...si(h.scheduling_checkpoint_evidence)?{scheduling_checkpoint_evidence:si(h.scheduling_checkpoint_evidence)}:{},...I?{review_request:I}:{},...Qn(h.rollback_receipt)?{rollback_receipt:Qn(h.rollback_receipt)}:{},..._t(h.workflow_issue)?{workflow_issue:_t(h.workflow_issue)}:{},...uc(h),...Array.isArray(h.depends_on)?{depends_on:ri(h.depends_on)}:{},files_to_modify:de(h.files_to_modify),...nc(h),risk:typeof h.risk=="string"?h.risk:void 0,blast_radius:typeof h.blast_radius=="number"?h.blast_radius:void 0}}const s=n.epics??{},l={};for(const[E,h]of Object.entries(s)){const I=Xo(h.lifecycle_classification),b=tc(h.createEpicPlanning,E),M=b.checkpoint;let P,k,_,w;if(M&&g(h.createEpicPlanningClaim)&&typeof h.createEpicPlanningClaim.claimId=="string"&&g(h.createEpicPlanningPhysical))try{Cr(n,h.createEpicPlanningClaim.claimId,E,!0),P=JSON.parse(JSON.stringify(h.createEpicPlanningPhysical))}catch{}if(P&&g(h.createEpicPlanningClaim)&&typeof h.createEpicPlanningClaim.claimId=="string"&&g(h.createEpicPlanningResearchPhysical))try{_r(n,h.createEpicPlanningClaim.claimId,E),k=JSON.parse(JSON.stringify(h.createEpicPlanningResearchPhysical))}catch{}if(t.verifyPlanningGeneration&&M&&h.status==="generated"&&g(h.createEpicPlanningClaim)&&typeof h.createEpicPlanningClaim.claimId=="string"&&g(h.createEpicPlanningGenerationPhysical))try{if(ia(e,h.createEpicPlanningClaim.claimId,E).stateSha256!==a)throw new Error("planning-generation-snapshot-raced");_=JSON.parse(JSON.stringify(h.createEpicPlanningGenerationPhysical)),P=JSON.parse(JSON.stringify(h.createEpicPlanningPhysical)),k=JSON.parse(JSON.stringify(h.createEpicPlanningResearchPhysical))}catch{}if(_&&g(h.createEpicPlanningClaim)&&typeof h.createEpicPlanningClaim.claimId=="string")try{const L=Rr(e,h.createEpicPlanningClaim.claimId,E);if(L.stateSha256!==a)throw new Error("planning-memory-snapshot-raced");w=JSON.parse(JSON.stringify(L))}catch{}l[E]={id:h.id??E,title:h.title,...M?{createEpicPlanning:M}:{},...b.diagnostic?{createEpicPlanningProjection:b.diagnostic}:{},...P?{createEpicPlanningPhysical:P}:{},...k?{createEpicPlanningResearchPhysical:k}:{},..._?{createEpicPlanningGenerationPhysical:_}:{},...w?{createEpicPlanningMemoryPhysical:w}:{},status:h.status,stories:h.stories,total_stories:h.total_stories,completed_stories:h.completed_stories,depends_on:ri(h.depends_on),...vn(h.branch_mode)?{branch_mode:vn(h.branch_mode)}:{},...Ee(h.execution_branch)?{execution_branch:Ee(h.execution_branch)}:{},...Ee(h.origin_branch)?{origin_branch:Ee(h.origin_branch)}:{},...ai(h.branch_lease)?{branch_lease:ai(h.branch_lease)}:{},...pi(h.origin_binding)?{origin_binding:pi(h.origin_binding)}:{},...li(h.aggregate_qa_receipt)?{aggregate_qa_receipt:li(h.aggregate_qa_receipt)}:{},...ui(h.head_reconciliation_receipt)?{head_reconciliation_receipt:ui(h.head_reconciliation_receipt)}:{},...mo(h.story_worktree_evidence)?{story_worktree_evidence:structuredClone(h.story_worktree_evidence)}:{},...(L=>L?{branch_mode_conversion_receipt:L}:{})(cc(h.branch_mode_conversion_receipt)),..._t(h.pr_number)?{pr_number:_t(h.pr_number)}:{},...Q(h.physicalMergeStatus)?{physicalMergeStatus:Q(h.physicalMergeStatus)}:{},...R(h.graph_revision)?{graph_revision:R(h.graph_revision)}:{},...hi(h.terminal_git_receipt)?{terminal_git_receipt:hi(h.terminal_git_receipt)}:{},...I?{lifecycle_classification:I}:{}}}const y=lc(n.current_session??n.currentSession),S=g(n.archPlan)?En(n.archPlan.execution):void 0,u=n.epic_id_ledger,C=Array.isArray(u?.reserved_ids)?[...new Set(u.reserved_ids.filter(E=>typeof E=="string"&&/^P\d+$/.test(E)))].slice(0,2048):[];return{schema_version:typeof n.schema_version=="number"?n.schema_version:void 0,config:{project_name:r.project_name??r.name??"unknown",default_branch:r.default_branch??"main",language:r.language??"pt-BR",yolo_mode:r.yolo_mode,user_name:r.user_name,worktree_base:r.worktree_base,max_parallel_stories:r.max_parallel_stories,project_id:typeof r.project_id=="string"?r.project_id:void 0},stories:d,epics:l,...C.length>0?{epic_id_ledger:{schema_version:1,reserved_ids:C}}:{},...y?{current_session:y}:{},...S?{archPlan:{execution:S}}:{}}}const Zn=[["P222.01","fbc3176b33687b13a8fadf8c7ea7cc06b6b6c500"],["P222.02","c7d3feb9a168f9e15b35516a972c767f3aa357da"],["P222.03","4d9bd4f2a1a3a1dc6399c572eb84b8b74c017806"],["P222.04","66590ef2f706c9d036f42edf5e517b237724f74f"],["P222.05","3ee2662538311e9788796340ed11b65864a8d8d5"],["P222.06","8660d07e3f68503a9ceb24dc138d24f62ab6cb45"],["P222.07","d99c80feacee8ea4033aa3322990147fffa2df91"],["P222.08","1f9e37dc922d87908efefb9595db32d32db30b00"],["P222.09","5ae12e485900992658e346cf3e38568fda1c2eeb"],["P222.10","6c5b8dc4f03d629fea4b62a33f4794af8e27e4f0"],["P222.11","cfe90f2f955c0027c57e4c621141d17912db65cc"],["P222.12","65f253c5cb600a8ee1dd94a1efdfef2fa5cd1629"],["P222.13","1e78c75b393515803a55d1a9b63a7fec23f710c9"],["P222.14","3f3e0bfd247a8581170df2a23c89497b5ae3641e"],["P222.15","1fd6dd25fffa5714d4ffa8b4303735e417f93de6"]],er="6a41a47ff2521f80c2296ed811b0f0b304c54750",tr="dbc6d4670b2b7868a01973b1240e24589f1c5b7d",fi="30dccfff07f9c969be11ae1d28e62a09731a0768";function gc(e,t){try{const i=t.indexOf(fi);if(i<1||t[i-1]!==er)return new Map;const n=Ge("git",["show","--no-patch","--format=%P",fi],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim(),a=Ge("git",["show","--no-patch","--format=%P",tr],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim();if(n!==`${er} ${tr}`||a!==`${Zn.at(-1)[1]} ${er}`)return new Map;const r=Ge("git",["rev-list","--first-parent","--reverse",tr],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
|
|
9
|
-
`),
|
|
10
|
-
`).filter(Boolean),S=new Map(
|
|
11
|
-
`),{}}}async function
|
|
12
|
-
`),
|
|
13
|
-
`),t}function
|
|
14
|
-
`)}async function
|
|
15
|
-
`:`[watch-status] status=${
|
|
7
|
+
`)}catch{}}}function zd(){Qn=!1}function ii(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Za(e){return e==="active"||e==="archived"||e==="rolled-back"||e==="synthetic"||e==="orphan"?e:void 0}const ec=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"]),tc=/(?:[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 nc(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(tc.test(i))return{};const o=(a,d)=>{if(Object.keys(a).some(s=>!d.includes(s)))throw new Error("planning-unknown-field")};if(o(e,["schemaVersion","epicId","intake","intakeRevision","diagnosisReceipt","researchReceipt","degradeAuthorization"]),!h(e.intake))return{};if(Object.keys(e.intake).some(a=>!ec.has(a)))return{};for(const[a,d]of Object.entries(e.intake))if(["examples","contracts"].includes(a)){const s=a==="examples"?["id","title","actor","given","when","then","source","coveredRequirement","expectedValidation"]:["id","kind","description","path"];if(!Array.isArray(d)||d.length>16)return{};for(const l of d){if(!h(l))return{};if(o(l,s),Object.values(l).some(m=>typeof m!="string"||m.length>256))return{}}}else if(Array.isArray(d)){if(d.length>32||d.some(s=>typeof s!="string"||s.length>256))return{}}else if(typeof d=="string"){if(d.length>(a==="rawIntent"?ao:512))return{}}else if(typeof d!="boolean"||!["uiScope","remediationStory"].includes(a))return{};const n=["schemaVersion","kind","epicId","intakeRevision","artifactSummary","artifactDigest","predecessorReceiptId","accepted","receiptId"];for(const a of[e.diagnosisReceipt,e.researchReceipt])if(a!==void 0){if(!h(a))return{};if(o(a,n),Object.values(a).some(d=>typeof d=="string"&&d.length>1024))return{}}if(e.degradeAuthorization!==void 0){if(!h(e.degradeAuthorization))return{};o(e.degradeAuthorization,["approved","intakeRevision","reasonCodes","assumptionCodes"]);for(const a of["reasonCodes","assumptionCodes"]){const d=e.degradeAuthorization[a];if(!Array.isArray(d)||d.length>32||d.some(s=>typeof s!="string"||s.length>128))return{}}}return{checkpoint:JSON.parse(i)}}catch{return{}}}function oi(e){return e==="create-epic"||e==="discovered"?e:void 0}function de(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function rc(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 o=e[r];if(!Array.isArray(o)||o.length>128||o.some(n=>gn(n)===void 0)){i=!0;continue}t[r]=o.map(n=>gn(n))}if(e.planning!==void 0)try{if(!h(e.planning))throw new Error("planning-shape");const r=e.planning;for(const a of["claims","semanticArtifacts"]){if(r[a]===void 0)continue;const d=r[a];if(!Array.isArray(d)||d.length>128||d.some(s=>!h(s)||gn(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 a of r.attempts??[]){if(!h(a)||!Array.isArray(a.reasonCodes)||a.reasonCodes.length>32||a.reasonCodes.some(d=>typeof d!="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(d)))throw new Error("planning-attempt-reasons");if(a.discoveredClaims!==void 0&&(!Array.isArray(a.discoveredClaims)||a.discoveredClaims.length>128||a.discoveredClaims.some(d=>!h(d)||gn(d.ref)===void 0)))throw new Error("planning-attempt-claims")}const{graphRevision:o,...n}=oa(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 _t(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function Q(e){if(typeof e!="string")return;const t=e.trim();if(t)return t.replace(/[^a-z0-9_.:-]+/gi,"_").slice(0,120)}function q(e){if(typeof e!="string")return;const t=e.trim(),i=Q(e);return i===t?i:void 0}function Ie(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240)&&/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(t)&&!(t.includes("..")||t.includes("//")||t.includes("@{")||t.endsWith("/")||t.endsWith("."))&&!t.split("/").some(i=>!i||i.startsWith(".")||i.endsWith(".lock")))return t}function R(e){return typeof e=="string"&&/^[0-9a-f]{7,64}$/i.test(e)?e:void 0}function De(e){if(!(typeof e!="string"||e.length>64)&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/.test(e))return Number.isFinite(Date.parse(e))?e:void 0}function pt(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240||t.includes("..")))return/^[A-Za-z0-9._:/#\-[\]]+$/.test(t)?t:void 0}function Sn(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,v)=>Array.isArray(u)&&u.length<=v&&u.every(t)&&new Set(u).size===u.length?u:void 0,o=(u,v)=>{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)||v&&(!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,...v?{outputHash:u.outputHash,artifactHash:u.artifactHash}:{}}},n=(u,v)=>{if(!(!h(u)||u.schemaVersion!=="1.1"||u.kind!==v||!i(u.receiptId)||!i(u.graphHash)||!i(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}},a=(u,v)=>{if(!h(u)||u.kind!==v||!i(u.receiptId)||!r(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=o(u,!0);if(!I)return;const g=v==="architecture-stage-validation"?n(u.isolated,"isolated"):void 0,E=v==="architecture-stage-validation"?n(u.regression,"regression"):void 0;if(!(v==="architecture-stage-validation"&&(!g||!E)))return{...I,kind:v,receiptId:u.receiptId,status:u.status,evidenceIds:u.evidenceIds,...g&&E?{isolated:g,regression:E}:{}}},d={};e.schemaVersion===1&&(d.schemaVersion=1),e.owner==="root"&&(d.owner="root"),t(e.currentStageCommand)&&(d.currentStageCommand=e.currentStageCommand),["ask-user","delegate","resume","advance","blocked","complete"].includes(String(e.continuationState))&&(d.continuationState=e.continuationState);const s=r(e.questionIds,16);if(s&&(d.questionIds=s),(e.childStatus==="succeeded"||e.childStatus==="failed")&&(d.childStatus=e.childStatus),(e.evidencePolicy==="legacy-compatible"||e.evidencePolicy==="v2-required")&&(d.evidencePolicy=e.evidencePolicy),t(e.targetEpicId)&&(d.targetEpicId=e.targetEpicId),i(e.graphRevision)&&(d.graphRevision=e.graphRevision),e.graphSource==="committed-epic-v1"&&(d.graphSource=e.graphSource),e.nonUiScopeReceipt!==void 0){const u=Sr(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");d.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)&&C(e.pactAnswerReceipt.questionIds,["PACT-Q1-CONSUMER","PACT-Q2-PROVIDER","PACT-Q3-BROKER","PACT-Q4-MATCHERS","PACT-Q5-VERIFY"])&&e.pactAnswerReceipt.publicSafe===!0&&(d.pactAnswerReceipt=e.pactAnswerReceipt);const l=o(e.evidenceExpectation,!1);l&&(d.evidenceExpectation=l);const m=a(e.completionEvidence,"architecture-stage-completion"),S=a(e.validationEvidence,"architecture-stage-validation");if(m&&(d.completionEvidence=m),S&&(d.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&&(d.reviewDecision={...e.reviewDecision,evidenceIds:u})}if(Ft(e.terminalMemoryCheckpoint,e))d.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&&(d.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=a(v.completionEvidence,"architecture-stage-completion"),g=a(v.validationEvidence,"architecture-stage-validation");return I&&g?{targetEpicId:v.targetEpicId,stageCommand:v.stageCommand,completionEvidence:I,validationEvidence:g}:void 0});u.every(v=>v!==void 0)&&(d.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&&(d.accounting={schemaVersion:1,contractVersion:e.accounting.contractVersion,accountingId:e.accounting.accountingId,charged:e.accounting.charged,chargedQuotaUnits:e.accounting.chargedQuotaUnits,receiptIds:u,...["in-progress","aborted","timed-out","failed","complete"].includes(String(e.accounting.lastOutcome))?{lastOutcome:e.accounting.lastOutcome}:{}})}return JSON.stringify(d).length<=96e3?d:void 0}function ic(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,o=h(i)?i:void 0,n=e.requestExecution,a=Array.isArray(o?.acceptedStages)?o.acceptedStages:[],d=n.currentStageCommand==="arch-prd"&&n.continuationState==="delegate"&&n.completionEvidence===void 0&&n.validationEvidence===void 0&&o?.currentStageCommand==="arch-prd"&&o.continuationState==="delegate"&&a.length===0&&r?.nextAction==="delegate",s=n.currentStageCommand==="arch-prd"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&o?.currentStageCommand==="arch-architecture"&&o.continuationState==="advance"&&a.length===1&&h(a[0])&&a[0].stageCommand==="arch-prd"&&C(a[0].completionEvidence,n.completionEvidence)&&C(a[0].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",l=n.currentStageCommand==="arch-architecture"&&n.continuationState==="advance"&&o?.currentStageCommand==="arch-architecture"&&o.continuationState==="delegate"&&a.length===1&&C(a,n.acceptedStages)&&r?.nextAction==="delegate",m=n.currentStageCommand==="arch-architecture"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&o?.currentStageCommand==="arch-fitness-functions"&&o.continuationState==="advance"&&a.length===2&&h(a[0])&&h(a[1])&&a[0].stageCommand==="arch-prd"&&a[1].stageCommand==="arch-architecture"&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===1&&C(a[0],n.acceptedStages[0])&&C(a[1].completionEvidence,n.completionEvidence)&&C(a[1].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",S=n.currentStageCommand==="arch-fitness-functions"&&n.continuationState==="advance"&&o?.currentStageCommand==="arch-fitness-functions"&&o.continuationState==="delegate"&&a.length===2&&h(a[0])&&h(a[1])&&a[0].stageCommand==="arch-prd"&&a[1].stageCommand==="arch-architecture"&&C(a,n.acceptedStages)&&r?.nextAction==="delegate",u=n.currentStageCommand==="arch-fitness-functions"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&o?.currentStageCommand==="arch-api-contracts"&&o.continuationState==="advance"&&a.length===3&&h(a[0])&&h(a[1])&&h(a[2])&&a[0].stageCommand==="arch-prd"&&a[1].stageCommand==="arch-architecture"&&a[2].stageCommand==="arch-fitness-functions"&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===2&&C(a.slice(0,2),n.acceptedStages)&&C(a[2].completionEvidence,n.completionEvidence)&&C(a[2].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",v=n.currentStageCommand==="arch-api-contracts"&&n.continuationState==="advance"&&o?.currentStageCommand==="arch-api-contracts"&&o.continuationState==="delegate"&&a.length===3&&h(a[0])&&h(a[1])&&h(a[2])&&a[0].stageCommand==="arch-prd"&&a[1].stageCommand==="arch-architecture"&&a[2].stageCommand==="arch-fitness-functions"&&C(a,n.acceptedStages)&&r?.nextAction==="delegate",I=["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"&&o?.currentStageCommand==="generate-pacts"&&o.continuationState==="ask-user"&&a.length===4&&h(a[3])&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===3&&C(a.slice(0,3),n.acceptedStages)&&a[3].stageCommand==="arch-api-contracts"&&C(a[3].completionEvidence,n.completionEvidence)&&C(a[3].validationEvidence,n.validationEvidence)&&C(o.questionIds,I)&&C(r?.questionIds,I)&&r?.nextAction==="ask-user",E=n.currentStageCommand==="generate-pacts"&&n.continuationState==="ask-user"&&o?.currentStageCommand==="generate-pacts"&&o.continuationState==="delegate"&&a.length===4&&C(a,n.acceptedStages)&&C(n.questionIds,I)&&C(o.questionIds,[])&&C(o.pactAnswerReceipt,e.answerReceipt)&&C(r?.pactAnswerReceipt,e.answerReceipt)&&e.answerReceipt?.stateSha256===e.sourceStateSha256&&r?.nextAction==="resume",x=n.currentStageCommand==="generate-pacts"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&C(n.pactAnswerReceipt,e.pactRecordedReceipt)&&o?.currentStageCommand==="arch-api-integrations"&&o.continuationState==="advance"&&a.length===5&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===4&&C(a.slice(0,4),n.acceptedStages)&&a.map(V=>h(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts"&&h(a[4])&&C(a[4].completionEvidence,n.completionEvidence)&&C(a[4].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",M=n.currentStageCommand==="arch-api-integrations"&&n.continuationState==="advance"&&o?.currentStageCommand==="arch-api-integrations"&&o.continuationState==="delegate"&&a.length===5&&C(a,n.acceptedStages)&&r?.nextAction==="delegate",P=n.currentStageCommand==="arch-api-integrations"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&o?.currentStageCommand==="arch-database"&&o.continuationState==="advance"&&a.length===6&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===5&&C(a.slice(0,5),n.acceptedStages)&&a.map(V=>h(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations"&&h(a[5])&&C(a[5].completionEvidence,n.completionEvidence)&&C(a[5].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",k=n.currentStageCommand==="arch-database"&&n.continuationState==="advance"&&o?.currentStageCommand==="arch-database"&&o.continuationState==="delegate"&&a.length===6&&C(a,n.acceptedStages)&&r?.nextAction==="delegate",_=n.currentStageCommand==="arch-database"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&o?.currentStageCommand==="arch-security"&&o.continuationState==="advance"&&a.length===7&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===6&&C(a.slice(0,6),n.acceptedStages)&&a.map(V=>h(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database"&&h(a[6])&&C(a[6].completionEvidence,n.completionEvidence)&&C(a[6].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",w=n.currentStageCommand==="arch-security"&&n.continuationState==="advance"&&o?.currentStageCommand==="arch-security"&&o.continuationState==="delegate"&&a.length===7&&C(a,n.acceptedStages)&&r?.nextAction==="delegate",L=n.currentStageCommand==="arch-security"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&o?.currentStageCommand==="arch-design-system"&&o.continuationState==="advance"&&a.length===8&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===7&&C(a.slice(0,7),n.acceptedStages)&&a.map(V=>h(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security"&&h(a[7])&&C(a[7].completionEvidence,n.completionEvidence)&&C(a[7].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",D=n.currentStageCommand==="arch-design-system"&&n.continuationState==="advance"&&o?.currentStageCommand==="arch-design-system"&&o.continuationState==="delegate"&&a.length===8&&C(a,n.acceptedStages)&&r?.nextAction==="delegate",Y=n.currentStageCommand==="arch-design-system"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&o?.currentStageCommand==="arch-ux-design"&&o.continuationState==="advance"&&a.length===9&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===8&&C(a.slice(0,8),n.acceptedStages)&&a.map(V=>h(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system"&&h(a[8])&&C(a[8].completionEvidence,n.completionEvidence)&&C(a[8].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",X=n.currentStageCommand==="arch-ux-design"&&n.continuationState==="advance"&&o?.currentStageCommand==="arch-ux-design"&&o.continuationState==="delegate"&&a.length===9&&C(a,n.acceptedStages)&&r?.nextAction==="blocked",pe=n.currentStageCommand==="arch-ux-design"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&o?.currentStageCommand==="arch-performance"&&o.continuationState==="advance"&&a.length===10&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===9&&C(a.slice(0,9),n.acceptedStages)&&a.map(V=>h(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design"&&h(a[9])&&C(a[9].completionEvidence,n.completionEvidence)&&C(a[9].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",b=n.currentStageCommand==="arch-performance"&&n.continuationState==="advance"&&o?.currentStageCommand==="arch-performance"&&o.continuationState==="delegate"&&a.length===10&&C(a,n.acceptedStages)&&r?.nextAction==="delegate",Se=n.currentStageCommand==="arch-performance"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&o?.currentStageCommand==="arch-testing"&&o.continuationState==="advance"&&a.length===11&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===10&&C(a.slice(0,10),n.acceptedStages)&&a.map(V=>h(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance"&&h(a[10])&&C(a[10].completionEvidence,n.completionEvidence)&&C(a[10].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",Z=n.currentStageCommand==="arch-testing"&&n.continuationState==="advance"&&o?.currentStageCommand==="arch-testing"&&o.continuationState==="delegate"&&a.length===11&&C(a,n.acceptedStages)&&r?.nextAction==="delegate",J=n.currentStageCommand==="arch-testing"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&o?.currentStageCommand==="arch-infrastructure"&&o.continuationState==="advance"&&a.length===12&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===11&&C(a.slice(0,11),n.acceptedStages)&&a.map(V=>h(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance,arch-testing"&&h(a[11])&&C(a[11].completionEvidence,n.completionEvidence)&&C(a[11].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",gt=n.currentStageCommand==="arch-infrastructure"&&n.continuationState==="advance"&&o?.currentStageCommand==="arch-infrastructure"&&o.continuationState==="delegate"&&a.length===12&&C(a,n.acceptedStages)&&r?.nextAction==="delegate",wt=n.currentStageCommand==="arch-infrastructure"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&o?.currentStageCommand==="arch-review"&&o.continuationState==="advance"&&a.length===13&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===12&&C(a.slice(0,12),n.acceptedStages)&&a.map(V=>h(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance,arch-testing,arch-infrastructure"&&h(a[12])&&C(a[12].completionEvidence,n.completionEvidence)&&C(a[12].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",ue=n.currentStageCommand==="arch-review"&&n.continuationState==="advance"&&o?.currentStageCommand==="arch-review"&&o.continuationState==="delegate"&&a.length===13&&C(a,n.acceptedStages)&&r?.nextAction==="delegate",O=n.currentStageCommand==="arch-review"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&n.reviewDecision===void 0&&o?.currentStageCommand==="arch-review"&&o.continuationState==="ask-user"&&a.length===13&&C(a,n.acceptedStages)&&C(o.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&C(o.completionEvidence,n.completionEvidence)&&C(o.validationEvidence,n.validationEvidence)&&r?.nextAction==="ask-user",$=n.currentStageCommand==="arch-review"&&n.continuationState==="ask-user"&&n.childStatus==="succeeded"&&h(n.reviewDecision)&&n.reviewDecision.decision==="approved"&&C(n.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&o?.currentStageCommand==="update-memory"&&o.continuationState==="advance"&&a.length===14&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===13&&C(a.slice(0,13),n.acceptedStages)&&h(a[13])&&a[13].stageCommand==="arch-review"&&C(a[13].completionEvidence,n.completionEvidence)&&C(a[13].validationEvidence,n.validationEvidence)&&C(o.reviewDecision,n.reviewDecision)&&r?.nextAction==="resume",xe=n.currentStageCommand==="update-memory"&&n.continuationState==="advance"&&h(n.reviewDecision)&&n.reviewDecision.decision==="approved"&&o?.currentStageCommand==="update-memory"&&o.continuationState==="delegate"&&a.length===14&&C(a,n.acceptedStages)&&C(o.reviewDecision,n.reviewDecision)&&r?.nextAction==="delegate",Te=n.currentStageCommand==="update-memory"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&o?.currentStageCommand==="update-memory"&&o.continuationState==="complete"&&a.length===15&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===14&&C(a.slice(0,14),n.acceptedStages)&&h(a[14])&&a[14].targetEpicId===n.targetEpicId&&a[14].stageCommand==="update-memory"&&C(a[14].completionEvidence,n.completionEvidence)&&C(a[14].validationEvidence,n.validationEvidence)&&C(o.reviewDecision,n.reviewDecision)&&C(o.completionEvidence,n.completionEvidence)&&C(o.validationEvidence,n.validationEvidence)&&Ft(o.terminalMemoryCheckpoint,n)!==null&&C(o.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)&&r?.nextAction==="complete",Pe=n.currentStageCommand==="update-memory"&&n.continuationState==="complete"&&n.childStatus==="succeeded"&&o?.currentStageCommand==="update-memory"&&o.continuationState==="complete"&&a.length===15&&C(a,n.acceptedStages)&&C(o.reviewDecision,n.reviewDecision)&&C(o.completionEvidence,n.completionEvidence)&&C(o.validationEvidence,n.validationEvidence)&&Ft(o.terminalMemoryCheckpoint,n)&&C(o.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)&&r?.nextAction==="complete",Nt=r?zi(n,r,Ft(n.terminalMemoryCheckpoint,n)&&C(o?.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)||!(Nt||d||s||l||m||S||u||v||g||E||x||M||P||k||_||w||L||D||Y||X||pe||b||Se||Z||J||gt||wt||ue||O||$||xe||Te||Pe)||!h(i.accounting)||i.accounting.charged!==!0||!C(Sn(i),i))throw new Error("architecture-root-checkpoint-invalid");const rt=z(e.projectRoot,".neocortex"),K=z(rt,"state.json"),ve=z(rt,"state.json.architecture.lock"),he=zt(ve,"wx",384);let qe;try{const V=Vt(K);if(!V.isFile()||V.isSymbolicLink())throw new Error("architecture-root-state-binding-invalid");const ft=Fe(K,"utf8");if(Ne("sha256").update(ft).digest("hex")!==e.sourceStateSha256)throw new Error("architecture-root-state-conflict");const ge=JSON.parse(ft),ae=h(ge)&&h(ge.archPlan)?ge.archPlan:{};if(!h(ge)||!h(ge.epics)||!Object.hasOwn(ge.epics,i.targetEpicId)||(e.initialBinding?ae.execution!==void 0||n.graphSource!=="committed-epic-v1":!C(Sn(ae.execution),n))||h(ge.scope)&&ge.scope.kind==="projected")throw new Error("architecture-root-state-binding-invalid");if(n.graphSource==="committed-epic-v1"&&n.graphRevision!==Yt(e.projectRoot,String(n.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");if(Pe||Nt==="complete-replay"){const Lt={...n,continuationState:"delegate",acceptedStages:n.acceptedStages.slice(0,Ir(n))};if(!C(n.terminalMemoryCheckpoint,Dn(e.projectRoot,Lt)))throw new Error("architecture-root-state-conflict");return}const ye=pn(),Ve=Be("git",["rev-parse","--git-common-dir"],{cwd:e.projectRoot,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),ee=eo(Ve)?jn(Ve):jn(e.projectRoot,Ve);if(Zi(ee)!==ee)throw new Error("architecture-root-backup-dir-invalid");const mt=z(ee,"neocortex-architecture");qt(mt,{recursive:!0,mode:448});const ze=Vt(mt);if(!ze.isDirectory()||ze.isSymbolicLink()||ze.uid!==process.getuid?.()||(ze.mode&63)!==0)throw new Error("architecture-root-backup-dir-invalid");const ke=z(mt,`state-backup-${ye}.json`),Qe=zt(ke,"wx",384);try{ln(Qe,ft),un(Qe)}finally{Jt(Qe)}const H=zt(mt,"r");try{un(H)}finally{Jt(H)}const xn={...ge,archPlan:{...ae,execution:i}};qe=z(rt,`state.json.architecture-tmp-${ye}`);const it=zt(qe,"wx",384);try{ln(it,`${JSON.stringify(xn,null,2)}
|
|
8
|
+
`),un(it)}finally{Jt(it)}if((Te||Nt==="complete")&&!C(n.terminalMemoryCheckpoint,Dn(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");Cr(qe,K),qe=void 0;const N=zt(rt,"r");try{un(N)}finally{Jt(N)}}finally{if(qe)try{Mn(qe)}catch{}Jt(he),Mn(ve)}}function vn(e,t){if(!h(e))return;const i={};for(const r of t){const o=e[r];if(typeof o=="boolean")i[r]=o;else if(typeof o=="number"&&Number.isFinite(o))i[r]=o;else if(typeof o=="string"){const n=Q(o);n&&(i[r]=n)}}return Object.keys(i).length>0?i:void 0}function Cn(e){return e==="epic"||e==="story"?e:void 0}function ai(e){if(!h(e)||e.schemaVersion!==1)return;const t=q(e.ownerStoryId),i=q(e.sessionId),r=q(e.idempotencyKey),o=De(e.acquiredAt),n=De(e.expiresAt);if(!(!t||!i||!r||!o||!n||Date.parse(n)<=Date.parse(o)))return{schemaVersion:1,ownerStoryId:t,sessionId:i,idempotencyKey:r,acquiredAt:o,expiresAt:n}}function ci(e){if(!h(e)||e.schemaVersion!==1)return;const t=q(e.storyId),i=q(e.epicId),r=Ie(e.branch),o=R(e.baseSha),n=R(e.headSha),a=q(e.idempotencyKey),d=De(e.recordedAt),s=de(e.commits).map(R).filter(M=>!!M).slice(0,256),l=de(e.receiptRefs).map(pt).filter(M=>!!M).slice(0,256),m=e.dispatchId===void 0?void 0:q(e.dispatchId),S=e.bundleId===void 0?void 0:q(e.bundleId),u=e.bundleDigest===void 0?void 0:R(e.bundleDigest),v=e.graphRevision===void 0?void 0:R(e.graphRevision),I=e.claimRevision===void 0?void 0:q(e.claimRevision),g=oc(e.qaReceipt),E=ac(e.reviewReceipt),x=e.rootMemoryEffect===void 0?void 0:va(e.rootMemoryEffect)?e.rootMemoryEffect:void 0;if(!(!t||!i||!t.startsWith(`${i}.`)||!r||!o||!n||o===n||!a||!d||s.length===0||l.length===0||!Array.isArray(e.commits)||s.length!==e.commits.length||e.commits.length>256||!Array.isArray(e.receiptRefs)||l.length!==e.receiptRefs.length||e.receiptRefs.length>256||e.dispatchId!==void 0&&!m||e.bundleId!==void 0&&!S||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&&(!x||x.storyId!==t||x.epicId!==i||x.executionBranch!==r||x.sourceHeadSha!==o||x.childClaimRevision!==I)||e.qaVerdict!=="passed"&&e.qaVerdict!=="blocked"||!["approved","changes-requested","pending"].includes(String(e.reviewVerdict))||!g||e.reviewVerdict!=="pending"&&!E||e.reviewVerdict==="pending"&&E||g.verdict!==e.qaVerdict||E&&E.verdict!==e.reviewVerdict||!pi(g,{storyId:t,epicId:i,baseSha:o,headSha:n,bundleDigest:u,graphRevision:v})||E&&(!pi(E,{storyId:t,epicId:i,baseSha:o,headSha:n,bundleDigest:u,graphRevision:v})||E.qaReceiptRef!==g?.receiptRef||E.receiptRef===g?.receiptRef)||!l.includes(String(g.receiptRef))||E&&(!l.includes(String(E.receiptRef))||Date.parse(String(E.reviewedAt))<Date.parse(String(g.checkedAt)))))return{schemaVersion:1,storyId:t,epicId:i,branch:r,baseSha:o,headSha:n,idempotencyKey:a,...m?{dispatchId:m}:{},...S?{bundleId:S}:{},...u?{bundleDigest:u}:{},...v?{graphRevision:v}:{},...I?{claimRevision:I}:{},...x?{rootMemoryEffect:structuredClone(x)}:{},qaVerdict:e.qaVerdict,reviewVerdict:e.reviewVerdict,...g?{qaReceipt:g}:{},...E?{reviewReceipt:E}:{},recordedAt:d,commits:s,receiptRefs:l}}function oc(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=q(e.storyId),i=q(e.epicId),r=R(e.baseSha),o=R(e.headSha),n=R(e.bundleDigest),a=R(e.graphRevision),d=R(e.sourceEvidenceDigest),s=De(e.checkedAt),l=pt(e.receiptRef),m=e.evidenceVersion==="p205-execution-v2"&&e.contract==="P205-CI-02"?e.contract:void 0,S=e.evidenceVersion==="p205-execution-v2"&&e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,u=e.evidenceVersion==="p205-execution-v2"?R(e.manifestDigest):void 0,v=e.evidenceVersion==="p205-execution-v2"?R(e.resultDigest):void 0,I=e.evidenceVersion==="p205-execution-v2"?de(e.gateIds).map(q).filter(g=>!!g).slice(0,64):void 0;if(!(!t||!i||!r||!o||!n||n.length!==64||!a||a.length!==64||!d||d.length!==64||!s||!l||e.evidenceVersion==="p205-execution-v2"&&(!m||S!=="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:i,...e.evidenceVersion==="p205-execution-v2"?{contract:m,command:S,manifestDigest:u,gateIds:I,resultDigest:v}:{},baseSha:r,headSha:o,bundleDigest:n,graphRevision:a,sourceEvidenceDigest:d,verdict:e.verdict,checkedAt:s,receiptRef:l}}function si(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=q(e.storyId),i=q(e.epicId),r=Ie(e.branch),o=R(e.baseSha),n=R(e.headSha),a=R(e.aggregateHeadSha),d=R(e.commitBodyDigest),s=R(e.changedPathsDigest),l=e.claimVerification==="canonical"||e.claimVerification==="legacy-migration"?e.claimVerification:void 0,m=R(e.effectiveClaimRevision),S=e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,u=R(e.manifestDigest),v=de(e.gateIds).map(q).filter(k=>!!k).slice(0,64),I=R(e.resultDigest),g=R(e.graphRevision),E=R(e.executionEvidenceDigest),x=R(e.sourceEvidenceDigest),M=De(e.verifiedAt),P=de(e.reasonCodes).map(q).filter(k=>!!k).slice(0,16);if(!(!t||!i||!r||!o||o.length<40||!n||n.length<40||!a||a.length<40||!d||d.length!==64||!s||s.length!==64||!l||!m||m.length!==64||!S||!u||u.length!==64||!Array.isArray(e.gateIds)||v.length!==e.gateIds.length||!I||I.length!==64||!g||g.length!==64||!E||E.length!==64||!x||x.length!==64||!M||P.length===0||e.verdict==="verified"&&(v.length===0||!P.includes("checkpoint-p205-transient-verified"))))return{schemaVersion:1,kind:"story_checkpoint_physical_verification",producer:"client-p205-transient-v1",storyId:t,epicId:i,branch:r,baseSha:o,headSha:n,aggregateHeadSha:a,commitBodyDigest:d,changedPathsDigest:s,claimVerification:l,effectiveClaimRevision:m,command:S,manifestDigest:u,gateIds:v,resultDigest:I,graphRevision:g,executionEvidenceDigest:E,sourceEvidenceDigest:x,verifiedAt:M,verdict:e.verdict,reasonCodes:P,publicSafe:!0}}function di(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=q(e.storyId),r=q(e.epicId),o=Ie(e.branch),n=R(e.baseSha),a=R(e.headSha),d=R(e.graphRevision),s=R(e.effectiveClaimRevision),l=R(e.sourceEvidenceDigest),m=De(e.verifiedAt),S=de(e.reasonCodes).map(q).filter(u=>!!u);if(!(!i||!r||!o||!n||n.length<40||!a||a.length<40||!d||d.length!==64||!s||s.length!==64||!l||l.length!==64||!m||!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:o,baseSha:n,headSha:a,graphRevision:d,effectiveClaimRevision:s,sourceEvidenceDigest:l,verifiedAt:m,reasonCodes:S,integrationAuthorized:!1,publicSafe:!0}}function ac(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=q(e.storyId),i=q(e.epicId),r=R(e.baseSha),o=R(e.headSha),n=R(e.bundleDigest),a=R(e.graphRevision),d=R(e.sourceEvidenceDigest),s=pt(e.qaReceiptRef),l=De(e.reviewedAt),m=pt(e.receiptRef);if(!(!t||!i||!r||!o||!n||n.length!==64||!a||a.length!==64||!d||d.length!==64||!s||!l||!m))return{schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:t,epicId:i,baseSha:r,headSha:o,bundleDigest:n,graphRevision:a,sourceEvidenceDigest:d,qaReceiptRef:s,verdict:e.verdict,reviewedAt:l,receiptRef:m}}function pi(e,t){return["storyId","epicId","baseSha","headSha","bundleDigest","graphRevision"].every(i=>e[i]===t[i])}function li(e){if(!h(e))return;const t=e.schemaVersion===1&&e.capturedFromCurrentCheckout===!0&&e.capturedFrom===void 0,i=e.schemaVersion===2&&e.capturedFromCurrentCheckout===void 0&&(e.capturedFrom==="current-checkout"||e.capturedFrom==="branch-ref");if(!t&&!i)return;const r=Ie(e.originBranch),o=R(e.originHeadSha),n=Ie(e.executionBranch),a=De(e.capturedAt);if(!(!r||!o||o.length<40||!n||!a||r===n))return t?{schemaVersion:1,originBranch:r,originHeadSha:o,executionBranch:n,capturedFromCurrentCheckout:!0,capturedAt:a}:{schemaVersion:2,originBranch:r,originHeadSha:o,executionBranch:n,capturedFrom:e.capturedFrom,capturedAt:a}}function ui(e){if(!h(e)||e.schemaVersion!==1||e.verdict!=="passed")return;const t=R(e.executionHeadSha),i=R(e.graphRevision),r=De(e.checkedAt),o=pt(e.receiptRef),n=de(e.gateIds).map(q).filter(m=>!!m).slice(0,128),a=e.evidenceVersion==="p205-execution-v2"&&e.producer==="local-yolo-tdd"&&e.contract==="P205-CI-02"&&e.command==="node scripts/test-root.mjs --gate complete",d=e.evidenceVersion===void 0&&e.producer===void 0&&e.contract===void 0&&e.command===void 0&&e.manifestDigest===void 0&&e.resultDigest===void 0,s=a?R(e.manifestDigest):void 0,l=a?R(e.resultDigest):void 0;if(!(!t||t.length<40||!i||i.length!==64||!r||!o||n.length===0||!Array.isArray(e.gateIds)||n.length!==e.gateIds.length||e.gateIds.length>128||!d&&!a||a&&(!s||s.length!==64||!l||l.length!==64)))return{schemaVersion:1,...a?{evidenceVersion:"p205-execution-v2",producer:"local-yolo-tdd",contract:"P205-CI-02",command:"node scripts/test-root.mjs --gate complete",manifestDigest:s,resultDigest:l}:{},verdict:"passed",executionHeadSha:t,graphRevision:i,checkedAt:r,receiptRef:o,gateIds:n}}const cc=16384;function sc(e){if(!h(e))return;const t=(r,o)=>r===null||typeof r=="boolean"?!0:typeof r=="number"?Number.isFinite(r):typeof r=="string"?r.length<=512&&!r.startsWith("/")&&!/^[A-Za-z]:[\\/]/.test(r)&&!r.includes("\\")&&!/:\/\//.test(r)&&!/[\u0000-\u001f]/.test(r):o>=4?!1:Array.isArray(r)?r.length<=256&&r.every(n=>t(n,o+1)):h(r)?Object.keys(r).length<=64&&Object.entries(r).every(([n,a])=>/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(n)&&t(a,o+1)):!1;if(!t(e,0))return;const i=JSON.stringify(e);if(!(Buffer.byteLength(i,"utf8")>cc))return JSON.parse(i)}function hi(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:q(e.epicId),executionBranch:Ie(e.executionBranch),originBranch:Ie(e.originBranch),graphRevision:R(e.graphRevision),originHeadSha:R(e.originHeadSha),lastAcceptedCheckpointHeadSha:R(e.lastAcceptedCheckpointHeadSha),executionHeadSha:R(e.executionHeadSha),acceptedCheckpointIds:de(e.acceptedCheckpointIds),acceptedCheckpointHeads:de(e.acceptedCheckpointHeads),reconciliationCommitShas:de(e.reconciliationCommitShas),commitRangeDigest:R(e.commitRangeDigest),changedPaths:de(e.changedPaths),changedPathsDigest:R(e.changedPathsDigest),allowedWriteSet:de(e.allowedWriteSet),allowedWriteSetDigest:R(e.allowedWriteSetDigest),aggregateReceiptRef:pt(e.aggregateReceiptRef),aggregateManifestDigest:R(e.aggregateManifestDigest),aggregateResultDigest:R(e.aggregateResultDigest),producedAt:De(e.producedAt),revalidatedAt:De(e.revalidatedAt),publicSafe:!0},i=["originSyncHeadSha","originSyncCommitShas","originSyncPaths","originSyncPathsDigest","originSyncResolvedPaths","originSyncResolvedPathsDigest"],r=i.filter(d=>e[d]!==void 0).length;if(r!==0&&r!==i.length)return;const o=r===0?void 0:{originSyncHeadSha:R(e.originSyncHeadSha),originSyncCommitShas:de(e.originSyncCommitShas),originSyncPaths:de(e.originSyncPaths),originSyncPathsDigest:R(e.originSyncPathsDigest),originSyncResolvedPaths:de(e.originSyncResolvedPaths),originSyncResolvedPathsDigest:R(e.originSyncResolvedPathsDigest)};if(o&&(!o.originSyncHeadSha||o.originSyncHeadSha.length<40||o.originSyncCommitShas.length===0||o.originSyncCommitShas.length>256||o.originSyncCommitShas.some(d=>!/^[a-f0-9]{40,64}$/i.test(d))||o.originSyncPaths.length>2048||o.originSyncResolvedPaths.length>64||o.originSyncPathsDigest!==fn(o.originSyncPaths)||o.originSyncResolvedPathsDigest!==fn(o.originSyncResolvedPaths))||!t.epicId||!t.executionBranch||!t.originBranch||!t.graphRevision||t.graphRevision.length!==64||!t.originHeadSha||t.originHeadSha.length<40||!t.lastAcceptedCheckpointHeadSha||t.lastAcceptedCheckpointHeadSha.length<40||!t.executionHeadSha||t.executionHeadSha.length<40||t.acceptedCheckpointIds.length===0||t.acceptedCheckpointIds.length>2048||t.acceptedCheckpointIds.length!==t.acceptedCheckpointHeads.length||t.acceptedCheckpointHeads.some(d=>!/^[a-f0-9]{40,64}$/i.test(d))||t.reconciliationCommitShas.length>2048||t.reconciliationCommitShas.some(d=>!/^[a-f0-9]{40,64}$/i.test(d))||t.changedPaths.length>2048||(t.lastAcceptedCheckpointHeadSha===t.executionHeadSha?t.reconciliationCommitShas.length!==0||t.changedPaths.length!==0:t.reconciliationCommitShas.length===0||t.changedPaths.length===0)||t.allowedWriteSet.length===0||t.allowedWriteSet.length>2048||!t.commitRangeDigest||!t.changedPathsDigest||!t.allowedWriteSetDigest||!t.aggregateReceiptRef||!t.aggregateManifestDigest||!t.aggregateResultDigest||!t.producedAt||!t.revalidatedAt||t.commitRangeDigest!==ca(t.lastAcceptedCheckpointHeadSha,t.executionHeadSha,t.reconciliationCommitShas)||t.changedPathsDigest!==fn(t.changedPaths)||t.allowedWriteSetDigest!==fn(t.allowedWriteSet))return;const n={...t,...o??{}},a=R(e.inputDigest);if(!(!a||a.length!==64||a!==aa(n)))return{...n,inputDigest:a}}function Xn(e){if(!h(e)||e.schemaVersion!==1)return;const t=vn(e,["schemaVersion","kind","storyId","epicId","baseSha","headSha","originalBaseSha","originalHeadSha","gitPullRequest","preservesLaterCommits","historyRewrite","recordedAt"])??{},i=de(e.receiptRefs).map(pt).filter(o=>!!o).slice(0,256),r=de(e.revertCommits).map(Q).filter(o=>!!o).slice(0,256);return{...t,...i.length?{receiptRefs:i}:{},...r.length?{revertCommits:r}:{}}}function dc(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 gi(e){if(!h(e)||e.schemaVersion!==1||e.publicSafe!==!0)return;const t=q(e.epicId),i=Ie(e.executionBranch),r=Ie(e.originBranch),o=R(e.baseSha),n=R(e.executionHeadSha),a=e.mergeSha===void 0?void 0:R(e.mergeSha),d=e.pushedSha===void 0?void 0:R(e.pushedSha),s=q(e.idempotencyKey),l=De(e.attemptStartedAt),m=e.completedAt===void 0?void 0:De(e.completedAt),S=de(e.localGateReceiptRefs).map(pt).filter(g=>!!g).slice(0,256),u=de(e.reasonCodes).map(q).filter(g=>!!g).slice(0,64),v=lc(e.candidateQa),I=pc(e.providerGuard);if(!(!t||!i||!r||!o||!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&&!I||I&&(e.strategy!=="single_pr"||e.physicalStatus!=="pushed"||I.prHeadSha!==a||I.originHeadSha!==o)))return{schemaVersion:1,epicId:t,executionBranch:i,originBranch:r,baseSha:o,executionHeadSha:n,...a?{mergeSha:a}:{},...d?{pushedSha:d}:{},strategy:e.strategy,..._t(e.prNumber)?{prNumber:_t(e.prNumber)}:{},physicalStatus:e.physicalStatus,localGateReceiptRefs:S,idempotencyKey:s,attemptStartedAt:l,...v?{candidateQa:v}:{},...I?{providerGuard:I}:{},...m?{completedAt:m}:{},retryEligible:e.retryEligible,reasonCodes:u,publicSafe:!0}}function pc(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),o=R(e.prHeadSha),n=R(e.originHeadSha),a=De(e.checkedAt);if(!(!r||!o||!n||!a))return{schemaVersion:1,provider:"github",mode:t,source:i,prHeadSha:o,originHeadSha:n,checkedAt:a,publicSafe:!0}}function lc(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(a=>[a,R(e[a])])),r=De(e.checkedAt),o=pt(e.receiptRef),n=de(e.gateIds).filter(a=>/^[a-z0-9-]+$/.test(a)).slice(0,128);if(!(Object.values(i).some(a=>!a)||!r||!o||n.length===0))return{schemaVersion:1,kind:e.kind,contract:e.contract,command:e.command,...i,checkedAt:r,receiptRef:o,gateIds:n}}function uc(e){if(!h(e))return;const t={...Q(e.active_epic_id??e.activeEpicId)?{active_epic_id:Q(e.active_epic_id??e.activeEpicId)}:{},...Q(e.active_story_id??e.activeStoryId)?{active_story_id:Q(e.active_story_id??e.activeStoryId)}:{},...Q(e.active_step_id??e.activeStepId)?{active_step_id:Q(e.active_step_id??e.activeStepId)}:{},...Q(e.session_id??e.sessionId)?{session_id:Q(e.session_id??e.sessionId)}:{},...Q(e.started_at??e.startedAt)?{started_at:Q(e.started_at??e.startedAt)}:{}};return Object.keys(t).length>0?t:void 0}function hc(e){const t=vn(e.completionEvidence??e.completion_evidence,["prNumber","pr_number","prState","pr_state","pullRequestState","merged","mergedAt","issueNumber","issue_number","issueState","issue_state","closedAt"]),i=vn(e.issueCloseAudit??e.issue_close_audit,["schema_version","event","storyId","epicId","issueNumber","closedAt","publicSafe","rawLogStorage"]),r=vn(e.scopedCiEvidence??e.scoped_ci_evidence,["schema_version","storyId","epicId","prNumber","finalState","publicSafe","rawLogStorage"]);return{...typeof e.merged=="boolean"?{merged:e.merged}:{},...typeof e.safeToContinueYoloop=="boolean"?{safeToContinueYoloop:e.safeToContinueYoloop}:{},...typeof e.mergeBlockedRemotely=="boolean"?{mergeBlockedRemotely:e.mergeBlockedRemotely}:{},...Q(e.physicalMergeStatus)?{physicalMergeStatus:Q(e.physicalMergeStatus)}:{},...Q(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)?{pr_state:Q(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)}:{},...Q(e.issue_state??e.issueState??e.workflow_issue_state)?{issue_state:Q(e.issue_state??e.issueState??e.workflow_issue_state)}:{},..._t(e.issue_number??e.issueNumber)?{issue_number:_t(e.issue_number??e.issueNumber)}:{},...t?{completionEvidence:t}:{},...i?{issueCloseAudit:i}:{},...r?{scopedCiEvidence:r}:{}}}class lt extends Error{reasonCode;constructor(t){super(t),this.name="StateSnapshotIntegrityError",this.reasonCode=t}}const gc=new Set(["yolo","yoloop","finalize-epic","audit"]),fc=8;function mc(e){return/docs\/epics\/epic-(P[1-9][0-9]*)\.md\b/.exec(e)?.[1]??/docs\/stories\/(P[1-9][0-9]*)\.[0-9]+\.story\.md\b/.exec(e)?.[1]}function yc(e,t={},i={},r){const o=d=>{try{return String(Be("git",[...d],{cwd:e,stdio:["ignore","pipe","ignore"],timeout:1e4,encoding:"utf8"})).trim()}catch{return}};if(o(["rev-parse","--is-inside-work-tree"])!=="true")return;const n=[],a=Object.entries(t).sort(([d],[s])=>+(s===r)-+(d===r));for(const[d,s]of a){if(n.length>=fc)break;if(!h(s)||!h(s.origin_binding))continue;const l=s.execution_branch,m=s.origin_binding;if(typeof l!="string"||m.executionBranch!==l||typeof m.originHeadSha!="string"||!/^[a-f0-9]{40,64}$/.test(m.originHeadSha)||!/^[A-Za-z0-9][A-Za-z0-9._/-]{0,239}$/.test(l)||l.includes(".."))continue;const S=o(["rev-parse","--verify","--quiet",`refs/heads/${l}^{commit}`]);if(!S||!/^[a-f0-9]{40,64}$/.test(S)||o(["merge-base","--is-ancestor",m.originHeadSha,S])===void 0)continue;const u=[];for(const v of Object.values(i)){if(u.length>=128)break;if(!h(v)||(v.epic_id??v.epic)!==d)continue;const I=h(v.checkpoint)&&typeof v.checkpoint.headSha=="string"?v.checkpoint.headSha:h(v.scheduling_checkpoint_evidence)&&typeof v.scheduling_checkpoint_evidence.headSha=="string"?v.scheduling_checkpoint_evidence.headSha:void 0;!I||!/^[a-f0-9]{40,64}$/.test(I)||u.includes(I)||o(["merge-base","--is-ancestor",I,S])!==void 0&&u.push(I)}n.push(Object.freeze({epicId:d,executionBranch:l,originHeadSha:m.originHeadSha,executionHeadSha:S,...u.length>0?{containedHeadShas:Object.freeze(u)}:{}}))}return Object.freeze({schemaVersion:1,stateFileTracked:o(["ls-files","--error-unmatch","--",".neocortex/state.json"])!==void 0,...n.length>0?{executionBases:Object.freeze(n)}:{}})}function fi(e){return typeof e=="string"&&gc.has(e)}function Zn(e,t={}){const i=z(e,".neocortex","state.json");if(!jt(i))throw new lt("git-lifecycle-state-missing");let r;try{r=JSON.parse(Fe(i,"utf8"))}catch{throw new lt("git-lifecycle-state-corrupt")}if(!h(r)||!h(r.epics)||!h(r.stories))throw new lt("git-lifecycle-state-shape-invalid");const o=Object.values(r.epics).some(n=>h(n)&&(n.branch_mode==="epic"||Ie(n.execution_branch)!==void 0));if(o)try{mn(e,{required:!0})}catch(n){const a=n instanceof Error&&/^git-lifecycle-/.test(n.message)?n.message:"git-lifecycle-runtime-invalid";if(t.allowMissingRuntime&&a==="git-lifecycle-runtime-missing")return{lifecycleDeclared:!0,runtimeMissing:!0};throw new lt(a)}return{lifecycleDeclared:o,runtimeMissing:!1}}function _n(e,t={}){const i=z(e,".neocortex","state.json");if(!jt(i)){if(t.epicAware&&!t.projectless)throw new lt("git-lifecycle-state-missing");return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}let r,o;try{const I=Fe(i,"utf-8");o=Ne("sha256").update(I).digest("hex");const g=vo(e,o)??JSON.parse(I),E=h(g.epics)?g.epics:{},x=Object.values(E).some(w=>h(w)&&(w.branch_mode==="epic"||Ie(w.execution_branch)!==void 0)),M=mn(e,{required:!!(t.epicAware&&x&&!t.projectless)});r=Ur(g,M);const P=h(r.stories)?r.stories:{},k=h(r.epics)?r.epics:{},_=h(g.stories)?g.stories:{};for(const[w,L]of Object.entries(P)){const D=h(L)?L:void 0;if(!D?.checkpoint)continue;const Y=typeof D.epic_id=="string"?D.epic_id:w.split(".")[0],X=h(k[Y])?k[Y]:void 0,pe=Ie(X?.execution_branch);if(!pe)continue;const b=sa(e,D.checkpoint,w,Y,pe,t.p205Authorities?.[w],$r(w,D,h(D.checkpoint)?D.checkpoint:void 0));if(b.kind==="integration-authorized")D.checkpoint_verification=b.verification,delete D.scheduling_checkpoint_evidence;else if(b.kind==="scheduling-only")D.scheduling_checkpoint_evidence=b.evidence,delete D.checkpoint,delete D.checkpoint_verification;else if(b.kind==="rejected"){D.checkpoint_verification=b.verification,delete D.scheduling_checkpoint_evidence;const Se=h(_[w])?_[w]:void 0;if(delete D.checkpoint,M.stories[w]?.checkpoint!==void 0)for(const Z of["status","last_step","steps_completed"])Se&&Object.prototype.hasOwnProperty.call(Se,Z)?D[Z]=structuredClone(Se[Z]):delete D[Z];["done","completed","merged"].includes(String(D.status).toLowerCase())&&(D.status="blocked")}}}catch(I){if(t.epicAware&&!t.projectless){const g=I instanceof Error&&/^git-lifecycle-/.test(I.message)?I.message:"git-lifecycle-state-corrupt";throw new lt(g)}return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}try{const I=Qa(r);I.length>0&&Xa(I)}catch{}const n=r.config??r.project??{},a=r.stories??{},d={};for(const[I,g]of Object.entries(a)){const E=h(g.review_request)&&g.review_request.kind==="git-pull-request"?dc(g.review_request):Xn(g.review_request);d[I]={id:g.id??I,title:g.title,epic_id:g.epic_id,status:g.status??"backlog",...oi(g.source)?{source:oi(g.source)}:{},steps_completed:g.steps_completed??[],last_step:g.last_step??null,branch_name:g.branch_name??null,pr_number:g.pr_number,...Cn(g.branch_mode)?{branch_mode:Cn(g.branch_mode)}:{},...ci(g.checkpoint)?{checkpoint:ci(g.checkpoint)}:{},...si(g.checkpoint_verification)?{checkpoint_verification:si(g.checkpoint_verification)}:{},...di(g.scheduling_checkpoint_evidence)?{scheduling_checkpoint_evidence:di(g.scheduling_checkpoint_evidence)}:{},...E?{review_request:E}:{},...Xn(g.rollback_receipt)?{rollback_receipt:Xn(g.rollback_receipt)}:{},..._t(g.workflow_issue)?{workflow_issue:_t(g.workflow_issue)}:{},...hc(g),...Array.isArray(g.depends_on)?{depends_on:ii(g.depends_on)}:{},files_to_modify:de(g.files_to_modify),...rc(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[I,g]of Object.entries(s)){const E=Za(g.lifecycle_classification),x=nc(g.createEpicPlanning,I),M=x.checkpoint;let P,k,_,w;if(M&&h(g.createEpicPlanningClaim)&&typeof g.createEpicPlanningClaim.claimId=="string"&&h(g.createEpicPlanningPhysical))try{_r(r,g.createEpicPlanningClaim.claimId,I,!0),P=JSON.parse(JSON.stringify(g.createEpicPlanningPhysical))}catch{}if(P&&h(g.createEpicPlanningClaim)&&typeof g.createEpicPlanningClaim.claimId=="string"&&h(g.createEpicPlanningResearchPhysical))try{Rr(r,g.createEpicPlanningClaim.claimId,I),k=JSON.parse(JSON.stringify(g.createEpicPlanningResearchPhysical))}catch{}if(t.verifyPlanningGeneration&&M&&g.status==="generated"&&h(g.createEpicPlanningClaim)&&typeof g.createEpicPlanningClaim.claimId=="string"&&h(g.createEpicPlanningGenerationPhysical))try{if(oo(e,g.createEpicPlanningClaim.claimId,I).stateSha256!==o)throw new Error("planning-generation-snapshot-raced");_=JSON.parse(JSON.stringify(g.createEpicPlanningGenerationPhysical)),P=JSON.parse(JSON.stringify(g.createEpicPlanningPhysical)),k=JSON.parse(JSON.stringify(g.createEpicPlanningResearchPhysical))}catch{}if(_&&h(g.createEpicPlanningClaim)&&typeof g.createEpicPlanningClaim.claimId=="string")try{const L=wr(e,g.createEpicPlanningClaim.claimId,I);if(L.stateSha256!==o)throw new Error("planning-memory-snapshot-raced");w=JSON.parse(JSON.stringify(L))}catch{}l[I]={id:g.id??I,title:g.title,...M?{createEpicPlanning:M}:{},...x.diagnostic?{createEpicPlanningProjection:x.diagnostic}:{},...P?{createEpicPlanningPhysical:P}:{},...k?{createEpicPlanningResearchPhysical:k}:{},..._?{createEpicPlanningGenerationPhysical:_}:{},...w?{createEpicPlanningMemoryPhysical:w}:{},status:g.status,stories:g.stories,total_stories:g.total_stories,completed_stories:g.completed_stories,depends_on:ii(g.depends_on),...Cn(g.branch_mode)?{branch_mode:Cn(g.branch_mode)}:{},...Ie(g.execution_branch)?{execution_branch:Ie(g.execution_branch)}:{},...Ie(g.origin_branch)?{origin_branch:Ie(g.origin_branch)}:{},...ai(g.branch_lease)?{branch_lease:ai(g.branch_lease)}:{},...li(g.origin_binding)?{origin_binding:li(g.origin_binding)}:{},...ui(g.aggregate_qa_receipt)?{aggregate_qa_receipt:ui(g.aggregate_qa_receipt)}:{},...hi(g.head_reconciliation_receipt)?{head_reconciliation_receipt:hi(g.head_reconciliation_receipt)}:{},...ya(g.story_worktree_evidence)?{story_worktree_evidence:structuredClone(g.story_worktree_evidence)}:{},...(L=>L?{branch_mode_conversion_receipt:L}:{})(sc(g.branch_mode_conversion_receipt)),..._t(g.pr_number)?{pr_number:_t(g.pr_number)}:{},...Q(g.physicalMergeStatus)?{physicalMergeStatus:Q(g.physicalMergeStatus)}:{},...R(g.graph_revision)?{graph_revision:R(g.graph_revision)}:{},...gi(g.terminal_git_receipt)?{terminal_git_receipt:gi(g.terminal_git_receipt)}:{},...E?{lifecycle_classification:E}:{}}}const m=uc(r.current_session??r.currentSession),S=h(r.archPlan)?Sn(r.archPlan.execution):void 0,u=r.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 r.schema_version=="number"?r.schema_version:void 0,config:{project_name:n.project_name??n.name??"unknown",default_branch:n.default_branch??"main",language:n.language??"pt-BR",yolo_mode:n.yolo_mode,user_name:n.user_name,worktree_base:n.worktree_base,max_parallel_stories:n.max_parallel_stories,project_id:typeof n.project_id=="string"?n.project_id:void 0},stories:d,epics:l,...v.length>0?{epic_id_ledger:{schema_version:1,reserved_ids:v}}:{},...m?{current_session:m}:{},...S?{archPlan:{execution:S}}:{}}}const er=[["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"]],tr="6a41a47ff2521f80c2296ed811b0f0b304c54750",nr="dbc6d4670b2b7868a01973b1240e24589f1c5b7d",mi="30dccfff07f9c969be11ae1d28e62a09731a0768";function Ec(e,t){try{const i=t.indexOf(mi);if(i<1||t[i-1]!==tr)return new Map;const r=Be("git",["show","--no-patch","--format=%P",mi],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim(),o=Be("git",["show","--no-patch","--format=%P",nr],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim();if(r!==`${tr} ${nr}`||o!==`${er.at(-1)[1]} ${tr}`)return new Map;const n=Be("git",["rev-list","--first-parent","--reverse",nr],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
|
|
9
|
+
`),a=new Map;let d=-1;for(const[s,[l,m]]of er.entries()){const S=n.indexOf(m);if(S<=d)return new Map;d=S,a.set(l,{headSha:m,position:s-er.length})}return a}catch{return new Map}}function Ic(e){return e instanceof Error&&(ua(e.message)||/^(?:p205|git-lifecycle)-[a-z0-9-]+$/.test(e.message))?e.message:"p205-transient-execution-failed"}async function Sc(e,t,i){if(!fi(i))return{};if(i==="audit"||i==="yoloop")return{};if(Or(t,i))return{};try{const r=JSON.parse(Fe(z(e,".neocortex","state.json"),"utf8")),o=mn(e,{required:!0}),n=Ur(r,o),a=h(n.stories)?n.stories:{},d=h(n.epics)?n.epics:{},s=Be("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8"}).trim(),l=Be("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8"}).trim(),m=Be("git",["rev-list","--first-parent","--reverse",s],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
|
|
10
|
+
`).filter(Boolean),S=new Map(m.map((_,w)=>[_,w])),u=Ec(e,m),v=t.match(/(?:^|\s)@?docs\/stories\/([A-Za-z][A-Za-z0-9._-]*)\.story\.md(?:\s|$)/)?.[1],I=i==="yoloop"?t.match(/(?:^|[\s/@])epic-(P[1-9][0-9]*)\.md(?:\s|$)/i)?.[1]?.toUpperCase():void 0,g=new Set,E=Object.entries(a).flatMap(([_,w])=>{if(v&&_!==v)return[];const L=h(w)?w:void 0,D=h(L?.checkpoint)?L.checkpoint:void 0;if(!D)return[];const Y=typeof L?.epic_id=="string"?L.epic_id:_.split(".")[0];if(I&&Y!==I)return[];const X=R(D?.headSha),pe=Y==="P222"?u.get(_):void 0,b=S.get(X??"")??(pe&&pe.headSha===X?pe.position:void 0);if(!X||X.length<40||b===void 0)return g.add(Y),[];const Se=h(d[Y])?d[Y]:void 0;if(Se?.branch_mode!=="epic"||Ie(Se.execution_branch)!==l||Ie(D.branch)!==l)return g.add(Y),[];const Z=R(D.graphRevision);if(!Z||Z.length!==64)return g.add(Y),[];const J=R(D.claimRevision),gt=[...$r(_,L,D)].sort(),wt=Ia(e,D,_,Y,l,gt);if(!wt&&J){if(gt.length===0)return g.add(Y),[];const ue=Be("git",["diff-tree","--no-commit-id","--name-only","-r","-z",X],{cwd:e,encoding:"utf8"}).split("\0").filter(Boolean),O=ga(_,gt).map(xe=>[...xe].sort()).find(xe=>J===Ne("sha256").update(xe.join("\0")).digest("hex")||J===Ne("sha256").update(JSON.stringify(xe)).digest("hex"));if(!O)return g.add(Y),[];let $=[];if(D.rootMemoryEffect!==void 0)try{$=Sa(e,D.rootMemoryEffect,{storyId:_,executionBranch:l,baseSha:String(D.baseSha),headRef:X,childPaths:O}).files.map(xe=>xe.path)}catch{return g.add(Y),[]}if(ue.length===0||ue.some(xe=>!O.some(Te=>fa(Te,xe))&&!$.includes(xe)))return g.add(Y),[]}else if(!wt)return g.add(Y),[];return Z?.length===64?[{storyId:_,epicId:Y,graphRevision:Z,checkpointHead:X,position:b}]:[]}),x=new Set(g);for(const[_,w]of Object.entries(d)){const L=h(w)?w:void 0,D=Array.isArray(L?.stories)?L.stories.filter(b=>typeof b=="string"):Object.keys(a).filter(b=>b.startsWith(`${_}.`)),Y=E.filter(b=>b.epicId===_),X=D.filter(b=>Y.some(Se=>Se.storyId===b)),pe=[...Y].sort((b,Se)=>b.position-Se.position).map(b=>b.storyId);(JSON.stringify(X)!==JSON.stringify(pe)||new Set(pe).size!==pe.length)&&x.add(_)}const M={},P=[...new Set(E.filter(_=>!x.has(_.epicId)).map(_=>_.graphRevision))],k=P.length>0?await la(e,{headSha:s,graphRevisions:P}):new Map;for(const _ of E){if(x.has(_.epicId))continue;const w=k.get(_.graphRevision);if(!w)throw new Error("p205-transient-authority-missing");M[_.storyId]=w}return await vc({projectRoot:e,commandId:i,targetEpicId:I,currentHead:s,epics:d,candidates:E,authorities:M}),M}catch(r){const o=Ic(r);return process.stderr.write(`[Neocortex] ${o}. Checkpoint projection remains fail-closed.
|
|
11
|
+
`),{}}}async function vc(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,o=R(i?.graph_revision);if(!r||!o||o.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!==o||!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,a=`local-yolo-tdd:${Ne("sha256").update(["epic-aggregate-p205-execution-v2",Xt,e.currentHead,o,r.manifestDigest,n.join(","),r.resultDigest].join("\0")).digest("hex")}`;if(r.receiptRef!==a)return;const d=e.candidates.find(S=>S.epicId===e.targetEpicId&&S.graphRevision===o&&e.authorities[S.storyId]),s=d?Ea(e.authorities[d.storyId]):void 0;if(!s||s.executionHeadSha!==e.currentHead||s.graphRevision!==o||s.manifestDigest!==r.manifestDigest||!Cc(s.gateIds,n))return;const l=`local-yolo-tdd:${Ne("sha256").update(["epic-aggregate-p205-execution-v2",Xt,e.currentHead,o,s.manifestDigest,s.gateIds.join(","),s.resultDigest].join("\0")).digest("hex")}`,m=r.receiptRef;await Hr(e.projectRoot,S=>{const u=da(S,e.targetEpicId),v=h(u.aggregate_qa_receipt)?u.aggregate_qa_receipt:void 0;!v||v.executionHeadSha!==e.currentHead||v.graphRevision!==o||v.receiptRef!==m||(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:o,manifestDigest:s.manifestDigest,resultDigest:s.resultDigest,checkedAt:s.executedAt,receiptRef:l,gateIds:[...s.gateIds]})})}function Cc(e,t){if(e.length!==t.length)return!1;const i=[...t].sort();return[...e].sort().every((r,o)=>r===i[o])}function Jd(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 yi="neocortex:menu:cache";async function _c(e){try{const t=await e.get(yi);if(!t)return null;const i=JSON.parse(t);return i.version!==Pt||Date.now()-i.cachedAt>qr?null:i}catch{return null}}async function Rc(e,t,i){try{const r={instructions:t,metadata:i,cachedAt:Date.now(),version:Pt};await e.set(yi,JSON.stringify(r),qr),wc()}catch{}}function wc(){try{jt(Yr)&&Mn(Yr)}catch{}}function Ei(e){return e.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>Bn(),()=>Bn({strictReadOnly:!0}))}async function Ii(e,t,i){const r=i.mode==="strict";try{let o;if(r&&t)o=new Vn({cacheDir:Wn,passphrase:t,strictReadOnly:!0});else if(r)o=new br;else if(t){const m=z(yn,"cache");o=new Vn({cacheDir:m,passphrase:t})}else process.stderr.write(`[neocortex] Warning: No license key in config. Run "neocortex activate" to re-authenticate.
|
|
12
|
+
`),o=new br;const n=Vr(i,o,"auth-cache"),a=Vr(i,o,"tier-cache"),d=new lo({serverUrl:e,licenseKey:t??"",cacheProvider:n,strictReadOnly:r});let s;if(r){const m=await d.inspectToken();if(m.status!=="authenticated")return m;s=m.token}else s=await d.getToken();if(!s)return t?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"};const l=new uo({cacheProvider:a,licenseClient:d});return{status:"authenticated",token:s,client:d,tierClient:l}}catch{return t?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"}}}let Si=!1;function Ac(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 vi=3,Rn=50;function bc(e){return new Promise(t=>setTimeout(t,e))}function xc(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,o={}){const n=Math.max(1,Math.min(o.maxAttempts??vi,vi)),a=o.sleep??bc;let d=r,s=!1,l=!1,m=0;for(let S=1;S<=n;S+=1){const u=Math.max(Math.floor(Date.now()/1e3),m+1);m=u;const v=Tc(t,i,d,{nowSeconds:u}),I=new AbortController,g=setTimeout(()=>I.abort(),zr);try{const E=await fetch(`${e}${t}`,{method:"POST",headers:v.headers,body:v.body,signal:I.signal});if(o.admitResponseBeforeBodyRead&&!o.admitResponseBeforeBodyRead(E))return{response:E,text:"",parsed:{},networkFailure:!1,responseAdmissionRejected:!0};const x=await E.text().catch(()=>""),M=E.ok&&o.deferSuccessfulJsonParsing?{}:(()=>{try{return x?JSON.parse(x):{}}catch{return{}}})();if(E.status===401&&!s&&o.refreshToken&&(M.fallback_action==="refresh_token"||M.fallback_action==="re_authenticate")){s=!0;const P=await o.refreshToken();if(P&&S<n){d=P,o.onTokenChanged?.(P),await a(Rn*S);continue}}if(E.status===401&&M.error_code==="SIGNATURE_EXPIRED"&&!l&&S<n){l=!0,await a(Rn*S);continue}if(S<n&&xc(E,M,o.allowReplayRetry===!0)){await a(Rn*S);continue}return{response:E,text:x,parsed:M,networkFailure:!1}}catch{if(S<n){await a(Rn*S);continue}return{text:"",parsed:{},networkFailure:!0}}finally{clearTimeout(g)}}return{text:"",parsed:{},networkFailure:!0}}function Tc(e,t,i,r={}){const o=Buffer.from(JSON.stringify(t),"utf8"),n=Do({method:"POST",target:e,body:o,bearerToken:i,clientVersion:Pt,nowSeconds:r.nowSeconds,nonceBytes:r.nonceBytes});return{body:n.body,headers:{...n.headers,Authorization:`Bearer ${i}`}}}function Ci(e){return Ne("sha256").update(e).digest("hex")}function Pc(){const e=Number(process.env.NEOCORTEX_INVOKE_CHUNK_BYTES??"49152");return Number.isFinite(e)&&e>=1024&&e<=98304?Math.floor(e):49152}function kc(e,t,i){return`args-${Ne("sha256").update("invoke-materialization:v1").update(e).update(String(t)).update(JSON.stringify(i)).digest("hex")}`}async function _i(e,t,i,r,o={}){const n=await Zt(e,t,i,r,{...o,allowReplayRetry:!0});if(n.networkFailure||!n.response)throw new Error("NETWORK_ERROR: materialization request failed after bounded retries");const{response:a,parsed:d}=n;if(!a.ok){const s=typeof d.error_code=="string"?d.error_code:`HTTP_${a.status}`,l=typeof d.message=="string"?d.message:"materialization upload failed";throw new Error(`${s}: ${l}`)}return d}async function Oc(e,t,i,r){const o=Buffer.from(t,"utf8"),n=Pc(),a=[];for(let I=0,g=0;I<o.byteLength;I+=n,g++){const E=o.subarray(I,Math.min(I+n,o.byteLength));a.push({index:g,sha256:Ci(E),byteLength:E.byteLength})}const d=Ci(o),s=kc(d,o.byteLength,a),l=Number(process.env.NEOCORTEX_INVOKE_CHUNK_TTL_SECONDS??"900");let m=i;const S={refreshToken:r,onTokenChanged(I){m=I}};for(const I of a){const g=I.index*n,E=o.subarray(g,g+I.byteLength);await _i(e,"/api/v1/invoke/materialization/chunks",{manifestId:s,index:I.index,sha256:I.sha256,byteLength:I.byteLength,contentBase64:E.toString("base64"),ttlSeconds:l,idempotencyKey:`${s}:${I.index}:${I.sha256}`},m,S)}const v=(await _i(e,"/api/v1/invoke/materialization/manifests",{manifestId:s,sha256:d,byteLength:o.byteLength,chunkCount:a.length,chunks:a,ttlSeconds:l,retry:{attempt:1,budget:3,idempotencyKey:s}},m,S)).argsRef;if(!v?.manifestId)throw new Error("MATERIALIZATION_RESPONSE_INVALID: missing argsRef");return{argsRef:v,chunks:a}}function Wt(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function Nc(...e){const t=new Set,i=[];for(const r of e)for(const o of r??[]){const n=Q(o);if(!(!n||t.has(n))&&(t.add(n),i.push(n),i.length>=16))return i}return i}function Lc(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 rr(e,t=Wt(e),i=[],r={}){const o=e.stateSnapshot.scope,n=Object.keys(e.stateSnapshot.stories).length,a=Object.keys(e.stateSnapshot.epics).length,d=o?.kind??"full";return{schemaVersion:1,payloadBytes:t,limitBytes:r.limitBytes??Kr,warningThresholdBytes:r.warningThresholdBytes??Gn,scope:{kind:d,...o?.projectionMode?{projectionMode:o.projectionMode}:{},commandId:o?.commandId??null,stateProjectionPolicy:o?.stateProjectionPolicy??null},includedStories:o?.includedStoryCount??n,omittedStories:o?.omittedStoryCount??0,includedEpics:o?.includedEpicCount??a,omittedEpics:o?.omittedEpicCount??0,graphRetrieval:Lc(e.stateSnapshot),reasonCodes:Nc(i,o?.reasonCodes),publicSafe:!0}}function Dc(e){const t=h(e.budget)?e.budget:void 0,i=typeof t?.maxPayloadBytes=="number"&&Number.isFinite(t.maxPayloadBytes)?t.maxPayloadBytes:12*1024;return Math.max(1024,Math.min(i,12*1024))}function Mc(e){return h(e)?{stableId:Q(e.stableId)??"unknown",...h(e.source)?{source:e.source}:{},reasonCode:"budget_exceeded"}:{stableId:"unknown",reasonCode:"budget_exceeded"}}function Ri(e){const t=Array.isArray(e)?e.filter(i=>typeof i=="string"):[];return t.includes("budget_exceeded")?t:[...t,"budget_exceeded"]}function jc(e){const t=e.graphRetrieval;if(!h(t)||!Array.isArray(t.items))return e;const i=Dc(t);let r=[...t.items],o=Array.isArray(t.skipped)?[...t.skipped]:[],n=t;for(;Buffer.byteLength(JSON.stringify(n),"utf8")>i&&r.length>0;){const a=r.pop();o=[...o,Mc(a)].slice(-32),n={...t,items:r,skipped:o,warnings:Ri(t.warnings)}}return Buffer.byteLength(JSON.stringify(n),"utf8")>i&&(n={...t,query:typeof t.query=="string"?t.query.slice(0,240):t.query,items:[],skipped:[],warnings:Ri(t.warnings)}),n===t?e:{...e,graphRetrieval:n}}function ir(e,t={}){const i=t.limitBytes??Kr,r=t.warningThresholdBytes??Math.floor(i*Qr),o=Wt(e);if(o<i)return{body:e,degraded:!1,telemetry:rr(e,o,["payload-within-limit"],{limitBytes:i,warningThresholdBytes:r})};let n={...e,stateSnapshot:Eo(e.stateSnapshot)},a=["payload-size-guardrail","state-degraded"],d=Wt(n);d>=i&&(n={...n,stateSnapshot:jc(n.stateSnapshot)},a=[...a,"graph-retrieval-budget-enforced"],d=Wt(n));const s=rr(n,d,a,{limitBytes:i,warningThresholdBytes:r});if(d>=i){const l=n.stateSnapshot.scope?.projectionMode;throw l==="yolo-story"||l==="yoloop-target"||l==="yoloop-session"||l==="yoloop-discovery"||l==="structural-required"?new Kn(s):new Jn(s)}return{body:n,degraded:!0,telemetry:s}}function wi(e){const t=e.stateSnapshot.scope?.commandId??"resolved-command";return e.args!==void 0?t:`${t}:argsRef`}function Vc(e){const t=Wt(e);if(t<Gn)return t;const i=rr(e,t,["payload-warning-threshold"]);return process.stderr.write(`[Neocortex] invoke payload near server limit: trigger=${wi(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 Ai(e,t){process.stderr.write(`[Neocortex] invoke payload guardrail: trigger=${wi(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 Bc(e){const t=Ao(e.args,{platformTarget:e.platformTarget,environment:e.environment??process.env});if(t.action==="skipped")return{shouldContinue:!0,attachToRequest:Uc(t),metadata:bi(t)};const i=e.bootstrapper??xo;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:[bo.UNEXPECTED_ERROR],publicSummary:"runner scheduler bootstrap stopped unexpectedly.",publicSafe:!0}}const o=bi(t,r);if(r.ok)return{shouldContinue:!0,attachToRequest:!0,metadata:o};const n=o.reasonCodes.slice(0,5).join(",");return t.failurePolicy==="fail-open"?{shouldContinue:!0,attachToRequest:!0,metadata:{...o,failOpenWarning:!0},warning:`Runner auto-bootstrap warning (${n}); continuing fail-open for operator command.`}:{shouldContinue:!1,attachToRequest:!1,metadata:o,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 Uc(e){return!e.reasonCodes.includes(wo.SKIPPED_NON_CONTINUITY_COMMAND)}function bi(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:Ue([...e.reasonCodes,...t?.reasonCodes??[]]),publicSummary:t?.publicSummary??e.publicSummary,publicSafe:!0}}function Ue(e){return Array.from(new Set(e.map(t=>t.slice(0,120))))}function wn(e,t,i){const r=Math.floor(e??t);return Number.isFinite(r)?Math.max(1,Math.min(i,r)):t}function An(e,t){const i=process.env[e];if(!i)return t;const r=Number(i);return Number.isFinite(r)?r:t}function F(e,t=ri){const i=typeof e=="string"&&e.trim().length>0?e.trim():"unknown",r=Je(i,t),o=Ga.test(r)?Ct:r;return o.length<=t?o:`${o.slice(0,t)}\u2026[TRUNCATED:${o.length-t}]`}function or(e,t=ri){if(!(typeof e!="string"||e.trim().length===0))return F(e,t)}function ar(e,t,i,r){const o=or(e?.targetId??t,120),n=e?.selectorKind??(o?sr(o):void 0),a=(e?.relatedJobIds??[]).map(d=>or(d,120)).filter(d=>!!d);return{schemaVersion:1,contractVersion:"continuity-v1",targetResolutionState:i,...n?{targetKind:n}:{},...o?{targetId:o}:{},...t?{targetJobId:F(t,120)}:{},...e?.jobId?{jobId:F(e.jobId,120)}:{},...e?.goalId?{goalId:F(e.goalId,120)}:{},...e?.loopId?{loopId:F(e.loopId,120)}:{},...a.length>0?{relatedJobIds:a}:{},relatedJobCount:a.length,reasonCodes:Ue(r.length>0?r:[G.OK]),publicSafe:!0}}function ut(e,t,i,r,o=[]){const n=(e?.redactions?.length??0)>0,a=e?n?"unsafe":i&&r===0?"empty":"available":"unavailable",d=or(t[t.length-1]?.eventId,120),s=o.length>0?o:a==="unavailable"?[G.WATCH_SNAPSHOT_UNAVAILABLE]:a==="empty"?[G.WATCH_NO_SUMMARIES_YET]:[G.OK];return{schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:a,...e?.generatedAt?{generatedAt:F(e.generatedAt,80)}:{},renderedSummaryCount:r,...d?{latestEventId:d}:{},reasonCodes:Ue(s),publicSafe:!0}}function et(e,t,i,r,o=[],n){const a=r[r.length-1],d=i??a?.cursor,s=!!(d&&d!==t&&r.length>0),l=n??(s?"advanced":t||d?"unchanged":"not_started"),m=o.length>0?o:l==="advanced"?[G.WATCH_CURSOR_ADVANCED]:l==="unavailable"?[G.WATCH_EVIDENCE_UNAVAILABLE]:[G.WATCH_CURSOR_UNCHANGED];return{schemaVersion:1,contractVersion:"continuity-v1",cursorState:l,...e?{initialCursor:F(e,200)}:{},...t?{currentCursor:F(t,200)}:{},...d?{nextCursor:F(d,200)}:{},cursorAdvanced:s,...a?.eventId?{eventId:F(a.eventId,120)}:{},reasonCodes:Ue(m),publicSafe:!0}}function tt(e){const t=e.targetEvidence;return{type:"watch_status",schemaVersion:1,contractVersion:"continuity-v1",recordType:"watch_status",command:"invoke",operation:"watch",watchStatus:e.watchStatus,active:e.active,...t?.targetResolutionState?{targetResolutionState:t.targetResolutionState}:{},...t?.targetKind?{targetKind:t.targetKind}:{},...t?.targetId?{targetId:t.targetId}:{},...t?{targetEvidence:t}:{},...e.snapshotEvidence?{snapshotEvidence:e.snapshotEvidence}:{},...e.cursorEvidence?{cursorEvidence:e.cursorEvidence}:{},...e.stopReason?{stopReason:e.stopReason}:{},reasonCodes:Ue([...e.reasonCodes??[],...t?.reasonCodes??[],...e.snapshotEvidence?.reasonCodes??[],...e.cursorEvidence?.reasonCodes??[]]),generatedAt:F(e.generatedAt??new Date().toISOString(),80),publicSafe:!0}}function $c(e){const t=e.targetKind&&e.targetId?`${e.targetKind}/${e.targetId}`:e.targetId??"[unresolved]",i=e.snapshotEvidence?.renderedSummaryCount??0,r=e.targetEvidence?.relatedJobCount??0,o=e.cursorEvidence?.cursorState??"unavailable",n=e.cursorEvidence?.currentCursor??"[none]",a=e.cursorEvidence?.nextCursor??"[none]",d=e.snapshotEvidence?.snapshotStatus??"not_requested",s=e.snapshotEvidence?.generatedAt??e.generatedAt;return[`[watch-status] ${e.targetResolutionState==="unresolved"||e.stopReason==="target_unresolved"?"unresolved-target":i===0&&(e.watchStatus==="waiting"||e.watchStatus==="active")?"no-new-summary":e.watchStatus==="stopped"?"stopped":"lifecycle"}`,`status=${e.watchStatus}`,`active=${e.active}`,`target=${t}`,`resolution=${e.targetResolutionState??"unavailable"}`,`relatedJobs=${r}`,`summaries=${i}`,`snapshot=${d}`,`generatedAt=${s}`,`cursor=${o}`,`current=${F(n,200)}`,`next=${F(a,200)}`,`advanced=${e.cursorEvidence?.cursorAdvanced??!1}`,`stop=${e.stopReason??"not_stopped"}`,`reasons=${e.reasonCodes.join(",")}`].join(" ")}function nt(e,t,i,r=!1){if(r){const o={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(o)}
|
|
15
|
+
`:`[watch-status] status=${o.watchStatus} active=${o.active} summaries=${o.renderedSummaryCount} stop=${o.stopReason}
|
|
16
16
|
`);return}if(t==="json"){i.write(JSON.stringify(e)+`
|
|
17
|
-
`);return}i.write(
|
|
18
|
-
`)}function
|
|
17
|
+
`);return}i.write($c(e)+`
|
|
18
|
+
`)}function Hc(e,t,i){return{continuityInvokeWatch:{schemaVersion:1,contractVersion:"continuity-v1",command:"invoke",operation:"watch",watchStatus:e.watchStatus,stopReason:e.stopReason??"not_stopped",targetResolutionState:e.targetResolutionState,targetKind:e.targetKind,targetId:e.targetId,snapshotStatus:e.snapshotEvidence?.snapshotStatus,snapshotGeneratedAt:e.snapshotEvidence?.generatedAt,renderedSummaryCount:e.snapshotEvidence?.renderedSummaryCount??t,cursorState:e.cursorEvidence?.cursorState,cursorAdvanced:e.cursorEvidence?.cursorAdvanced,summariesEmitted:t,polls:i,statusRecord:e,publicSafe:!0}}}function ht(e,t,i,r,o=!1){return o?{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:Hc(r,t,i),publicSafe:!0}}function Wc(e){const t=e.reasonCode?` reason=${F(e.reasonCode,80)}`:"",i=e.goalId?` goal=${F(e.goalId,100)}`:"",r=e.loopId?` loop=${F(e.loopId,100)}`:"";return`[watch] ${F(e.createdAt,80)} event=${F(e.eventId,120)} job=${F(e.jobId,100)}${i}${r} execution=${F(e.executionId,120)}${t} -- ${F(e.publicSummary)}`}function Gc(e){return{type:"processing_summary",source:"local_continuity_sqlite",eventId:F(e.eventId,120),jobId:F(e.jobId,100),...e.goalId?{goalId:F(e.goalId,100)}:{},...e.loopId?{loopId:F(e.loopId,100)}:{},executionId:F(e.executionId,120),...e.reasonCode?{reasonCode:F(e.reasonCode,80)}:{},createdAt:F(e.createdAt,80),publicSummary:F(e.publicSummary),publicSafe:!0}}function Fc(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"){i.write(JSON.stringify(
|
|
21
|
-
`);return}i.write(
|
|
22
|
-
`)}function or(e){return $o.has(e.status)}function Hc(e,t,i){if(t){const a=e.find(r=>r.jobId===t);return!!(a&&or(a))}return i<=0?!1:e.filter(a=>!or(a)).length===0}function Wc(e,t,i,n){return i<n?!1:t?!e.some(a=>a.jobId===t&&!or(a)):e.length===0}function Gc(e,t){return t?.aborted?Promise.resolve():new Promise(i=>{const n=setTimeout(a,e);function a(){clearTimeout(n),t?.removeEventListener("abort",a),i()}t?.addEventListener("abort",a,{once:!0})})}function Fc(e){return e.includes(Le.MALFORMED)?"malformed":e.includes(Le.AMBIGUOUS)?"ambiguous":e.includes("watch-target-multiple")?"multiple":e.includes("watch-evidence-unsafe")?"unsafe":e.includes(Le.MISSING)||e.includes(_e.TARGET_UNRESOLVED)?"unresolved":"unavailable"}function bi(e,t){const i=t?en(t):void 0,n=Be([...e,_e.TARGET_UNRESOLVED,G.WATCH_TARGET_UNRESOLVED]),a=ar(i,i?.targetId,Fc(n),n),r=ut({generatedAt:new Date().toISOString()},[],!1,0,[G.WATCH_TARGET_UNRESOLVED]),o=et(void 0,void 0,void 0,[],[G.WATCH_TARGET_UNRESOLVED],"unavailable");return tt({watchStatus:"blocked",active:!1,targetEvidence:a,snapshotEvidence:r,cursorEvidence:o,stopReason:"target_unresolved",reasonCodes:n,generatedAt:r.generatedAt})}function Yc(e,t,i,n,a=!1){const r=bi(e,Ti(t));return nt(r,i,n,a),ht("target-unresolved",0,0,r,a)}async function qc(e){if(e.signal?.aborted){const k=ar(e.target??en(e.targetJobId),e.targetJobId,e.target??e.targetJobId?"resolved":"unresolved",[_e.CANCELLED]),_=ut(void 0,[],!1,0),w=et(e.initialCursor,e.initialCursor,e.initialCursor,[],[_e.CANCELLED],"unavailable"),L=tt({watchStatus:"stopped",active:!1,targetEvidence:k,snapshotEvidence:_,cursorEvidence:w,stopReason:"cancelled",reasonCodes:[_e.CANCELLED]});return ht("cancelled",0,0,L,e.protectedOutput)}const t=e.target??en(e.targetJobId),i=e.targetJobId??t?.targetId,n=e.stdout??process.stdout;if(!t){const k=bi([Le.MISSING,_e.TARGET_UNRESOLVED]);return nt(k,e.format,n,e.protectedOutput),ht("target-unresolved",0,0,k,e.protectedOutput)}const a=Rn(e.limit??wn("NEOCORTEX_INVOKE_WATCH_LIMIT",Nr),Nr,50),r=Math.max(50,Rn(e.pollIntervalMs??wn("NEOCORTEX_INVOKE_WATCH_POLL_INTERVAL_MS",Mr),Mr,6e4)),o=Rn(e.maxIdlePolls??wn("NEOCORTEX_INVOKE_WATCH_MAX_IDLE_POLLS",Lr),Lr,120),d=Rn(e.maxPolls??wn("NEOCORTEX_INVOKE_WATCH_MAX_POLLS",Dr),Dr,86400),s=e.sleep??Gc;let l=e.initialCursor,y=0,S=0,u=0;const C=ar(t,i,"resolved",[G.OK]),E={schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:"pending",renderedSummaryCount:0,reasonCodes:[G.WATCH_RENDER_PENDING],publicSafe:!0},h=et(e.initialCursor,l,l,[],e.initialCursor?[G.WATCH_CURSOR_UNCHANGED]:[G.WATCH_NO_SUMMARIES_YET],e.initialCursor?"unchanged":"not_started");nt(tt({watchStatus:"active",active:!0,targetEvidence:C,snapshotEvidence:E,cursorEvidence:h,stopReason:"not_stopped",reasonCodes:[G.OK]}),e.format,n,e.protectedOutput);let I;try{I=await xa({projectRoot:e.projectRoot,strictReadOnly:e.strictReadOnly})}catch{const k=ut(void 0,[],!1,y,[G.WATCH_SNAPSHOT_UNAVAILABLE]),_=et(e.initialCursor,l,l,[],[G.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),w=tt({watchStatus:"blocked",active:!1,targetEvidence:C,snapshotEvidence:k,cursorEvidence:_,stopReason:"unavailable_evidence",reasonCodes:[_e.STORE_UNAVAILABLE]});return nt(w,e.format,n,e.protectedOutput),ht("store-unavailable",y,u,w,e.protectedOutput)}try{for(;!e.signal?.aborted&&u<d;){u+=1;const k=l,_=I.collectProcessingOutputSummaryCursor({...l?{cursor:l}:{},...t?{target:t}:{},...i?{jobId:i}:{},limit:a}),w=I.collectSnapshot({jobLimit:50,processingSummaryLimit:1}),L=w.jobs;if(_.summaries.length>0){for(const X of _.summaries)$c(X,e.format,n,e.protectedOutput),y+=1;l=_.nextCursor??_.summaries[_.summaries.length-1]?.cursor??l,S=0}else l=_.nextCursor??l,S+=1;const D=ut(w,_.summaries,!0,_.summaries.length),Y=et(e.initialCursor,k,l,_.summaries,_.summaries.length>0?[G.WATCH_CURSOR_ADVANCED]:[G.WATCH_NO_SUMMARIES_YET]);if(nt(tt({watchStatus:_.summaries.length>0?"polling":"waiting",active:!0,targetEvidence:C,snapshotEvidence:D,cursorEvidence:Y,stopReason:"not_stopped",reasonCodes:_.summaries.length>0?[G.WATCH_CURSOR_ADVANCED]:[G.WATCH_NO_SUMMARIES_YET],generatedAt:w.generatedAt}),e.format,n,e.protectedOutput),!_.hasMore&&Hc(L,i,y)){const X=ut(w,_.summaries,!1,y,[_e.COMPLETED]),pe=et(e.initialCursor,k,l,_.summaries,[_e.COMPLETED],"exhausted"),x=tt({watchStatus:"stopped",active:!1,targetEvidence:C,snapshotEvidence:X,cursorEvidence:pe,stopReason:"not_stopped",reasonCodes:[_e.COMPLETED],generatedAt:w.generatedAt});return nt(x,e.format,n,e.protectedOutput),ht("completed",y,u,x,e.protectedOutput)}if(!_.hasMore&&Wc(L,i,S,o)){const X=ut(w,_.summaries,!1,y,[G.WATCH_STOP_IDLE_LIMIT_REACHED]),pe=et(e.initialCursor,k,l,_.summaries,[G.WATCH_STOP_IDLE_LIMIT_REACHED],"exhausted"),x=tt({watchStatus:"stopped",active:!1,targetEvidence:C,snapshotEvidence:X,cursorEvidence:pe,stopReason:"idle_limit_reached",reasonCodes:[_e.IDLE_TIMEOUT,G.WATCH_STOP_IDLE_LIMIT_REACHED],generatedAt:w.generatedAt});return nt(x,e.format,n,e.protectedOutput),ht("idle-timeout",y,u,x,e.protectedOutput)}_.hasMore||await s(r,e.signal)}}catch{const k=ut(void 0,[],!1,y,[G.WATCH_SNAPSHOT_UNAVAILABLE]),_=et(e.initialCursor,l,l,[],[G.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),w=tt({watchStatus:"blocked",active:!1,targetEvidence:C,snapshotEvidence:k,cursorEvidence:_,stopReason:"unavailable_evidence",reasonCodes:[_e.STORE_UNAVAILABLE]});return nt(w,e.format,n,e.protectedOutput),ht("store-unavailable",y,u,w,e.protectedOutput)}finally{I.close()}if(e.signal?.aborted){const k=ut(void 0,[],!1,y,[_e.CANCELLED]),_=et(e.initialCursor,l,l,[],[_e.CANCELLED],"unavailable"),w=tt({watchStatus:"stopped",active:!1,targetEvidence:C,snapshotEvidence:k,cursorEvidence:_,stopReason:"cancelled",reasonCodes:[_e.CANCELLED]});return nt(w,e.format,n,e.protectedOutput),ht("cancelled",y,u,w,e.protectedOutput)}const b=ut(void 0,[],!1,y,[G.WATCH_STOP_MAX_POLLS_REACHED]),M=et(e.initialCursor,l,l,[],[G.WATCH_STOP_MAX_POLLS_REACHED],"exhausted"),P=tt({watchStatus:"stopped",active:!1,targetEvidence:C,snapshotEvidence:b,cursorEvidence:M,stopReason:"max_polls_reached",reasonCodes:[_e.MAX_POLLS,G.WATCH_STOP_MAX_POLLS_REACHED]});return nt(P,e.format,n,e.protectedOutput),ht("max-polls",y,u,P,e.protectedOutput)}function Ke(e){const t=e.trim().replace(/^@/,"").match(/^(job|goal|loop)-([JGL])(\d{3,})$/i);if(!t)return;const i=t[1].toLowerCase(),n=t[2].toUpperCase();if(!(i==="job"&&n!=="J"||i==="goal"&&n!=="G"||i==="loop"&&n!=="L"))return`${i}-${n}${t[3]}`}function cr(e){if(e.startsWith("job-J"))return"job";if(e.startsWith("goal-G"))return"goal";if(e.startsWith("loop-L"))return"loop"}function xi(e){const t=[],i=/(?:^|[\s"'([,{])@?(job-[Jj]\d{3,}|goal-[Gg]\d{3,}|loop-[Ll]\d{3,})(?=$|[\s"')\]},.;:!?])/g;let n;for(;(n=i.exec(e))!==null;){const a=Ke(n[1]);a&&t.push(a)}return Be(t)}function Ti(e){return xi(e)[0]}function en(e){const t=e?Ke(e):void 0;if(t){if(t.startsWith("job-J"))return{selectorKind:"job",targetId:t,jobId:t,publicSafe:!0};if(t.startsWith("goal-G"))return{selectorKind:"goal",targetId:t,goalId:t,publicSafe:!0};if(t.startsWith("loop-L"))return{selectorKind:"loop",targetId:t,loopId:t,publicSafe:!0}}}function sr(e){return Be(e.filter(t=>typeof t=="string").map(t=>Ke(t)).filter(t=>!!t?.startsWith("job-J")))}function zc(e,t){const i=sr(t).filter(n=>n!==e.targetId&&n!==e.jobId);return i.length>0?{...e,relatedJobIds:i}:e}function Jc(e){if(!e)return;const t=g(e.target)?e.target:void 0,i=typeof e.selectorKind=="string"?e.selectorKind:typeof t?.selectorKind=="string"?t.selectorKind:void 0,n=typeof e.targetId=="string"?Ke(e.targetId):typeof t?.targetId=="string"?Ke(t.targetId):typeof e.targetJobId=="string"?Ke(e.targetJobId):void 0,a=en(n);if(!a||i&&i!==a.selectorKind)return;const r=Array.isArray(e.relatedJobIds)?e.relatedJobIds:Array.isArray(t?.relatedJobIds)?t.relatedJobIds:void 0,o=sr([...r??[],e.jobId,t?.jobId,e.targetJobId,t?.targetJobId]).filter(d=>d!==a.targetId&&d!==a.jobId);return{...a,...typeof(e.jobId??t?.jobId)=="string"?{jobId:Ke(e.jobId??t?.jobId)??a.jobId}:{},...typeof(e.goalId??t?.goalId)=="string"?{goalId:Ke(e.goalId??t?.goalId)??a.goalId}:{},...typeof(e.loopId??t?.loopId)=="string"?{loopId:Ke(e.loopId??t?.loopId)??a.loopId}:{},...o.length>0?{relatedJobIds:o}:{}}}function Pi(e){const t=e.trim().split(/\s+/).filter(Boolean),i=t[0]?.replace(/^\*/,"").toLowerCase(),n=t[1]?.replace(/^--/,"").toLowerCase();return(i==="jobs"||i==="job"||i==="continuity-jobs"||i==="61")&&n==="watch"}const be=Object.freeze({ACTIVE:"command-level-watch-active",INACTIVE:"command-level-watch-inactive",DUPLICATE:"command-level-watch-duplicate",AMBIGUOUS:"command-level-watch-ambiguous",QUOTED:"command-level-watch-quoted",MALFORMED:"command-level-watch-malformed",NON_FINAL:"command-level-watch-non-final",UNRESOLVED:"command-level-watch-unresolved",UNSUPPORTED:"command-level-watch-unsupported",TARGET_INVALID:"command-level-watch-target-invalid"}),Kc=new Set(["create","start","resume"]),Qc=new Set(["create","resume","run-once"]);function dr(e,t,i,n,a){return{schemaVersion:1,contractVersion:"continuity-v1",...i?{command:i}:{},...n?{operation:n}:{},active:e,...a?{watchToken:a}:{},reasonCodes:Be(t),serverHeldStream:!1,allJobsPolling:!1,targetResolution:e?"required-after-dispatch":"inactive",publicSafe:!0}}function Me(e,t=[],i,n){const a=t.length>0?t:[be.INACTIVE];return{args:e,watch:!1,reasonCodes:a,metadata:dr(!1,a,i,n),publicSafe:!0}}function Xc(e){const t=e.trim().split(/\s+/).filter(Boolean),i=t.slice(2).filter(r=>r==="--watch").length;if(i===0)return Me(e,[],"jobs","watch");if(i!==1)return Me(e,[be.AMBIGUOUS],"jobs","watch");const n=t.filter((r,o)=>o<2||r!=="--watch").join(" ");return Pi(n)?n.trim().split(/\s+/).filter(Boolean).slice(2).length!==1?Me(e,[be.AMBIGUOUS],"jobs","watch"):Ti(n)?{args:n,watch:!0,reasonCodes:[be.ACTIVE],metadata:dr(!0,[be.ACTIVE],"jobs","watch"),publicSafe:!0}:Me(e,[be.TARGET_INVALID],"jobs","watch"):Me(e,[be.UNSUPPORTED],"jobs","watch")}function Zc(e){const t=[];let i=!1,n=0;for(;n<e.length;){for(;n<e.length&&/\s/.test(e[n]);)n+=1;if(n>=e.length)break;const a=n;let r="",o=!1,d=null;for(;n<e.length;){const s=e[n];if(d){if(s===d){o=!0,d=null,n+=1;continue}if(s==="\\"&&n+1<e.length){r+=e[n+1],n+=2;continue}r+=s,n+=1;continue}if(/\s/.test(s))break;if(s==='"'||s==="'"){o=!0,d=s,n+=1;continue}r+=s,n+=1}d&&(i=!0),t.push({value:r,start:a,end:n,quoted:o})}return{tokens:t,malformed:i}}function es(e){if(!e||e.quoted)return;const t=e.value.replace(/^\*/,"").toLowerCase();return t==="goal"||t==="loop"?t:void 0}function ts(e,t){if(!e||e==="jobs"||!t||t.quoted)return;const i=t.value.toLowerCase();return(e==="goal"?Kc:Qc).has(i)?i:void 0}function ns(e){return!e.quoted&&e.value!=="--watch"&&e.value.toLowerCase().startsWith("--watch")}function rs(e){const{tokens:t,malformed:i}=Zc(e),n=es(t[0]),a=ts(n,t[1]);if(i)return Me(e,[be.MALFORMED],n,a);const r=t.filter(u=>u.value==="--watch"&&!u.quoted),o=t.filter(u=>u.value==="--watch"&&u.quoted),d=t.filter(ns);if(!(r.length>0||o.length>0||d.length>0))return Me(e,[],n,a);if(r.length>1)return Me(e,[be.DUPLICATE],n,a);if(r.length===1&&(o.length>0||d.length>0))return Me(e,[be.AMBIGUOUS],n,a);if(o.length>0)return Me(e,[be.QUOTED],n,a);if(d.length>0)return Me(e,[be.MALFORMED],n,a);const l=r[0];if(!l)return Me(e,[],n,a);if(t[t.length-1]!==l)return Me(e,[be.NON_FINAL],n,a);if(!n||!a)return Me(e,[be.UNRESOLVED],n,a);const y=`${e.slice(0,l.start)}${e.slice(l.end)}`.trim(),S={literal:"--watch",position:"final",start:l.start,end:l.end,quoted:!1,publicSafe:!0};return{args:y,watch:!0,reasonCodes:[be.ACTIVE],metadata:dr(!0,[be.ACTIVE],n,a,S),publicSafe:!0}}function is(e){return Pi(e)?Xc(e):rs(e)}function as(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&Ho.has(t)):[]}function Gt(e){return{disabled:!0,reasonCodes:Be(e.length>0?e:[Le.MISSING])}}function pr(e,t,i=[],n){const a=en(t);if(a)return{source:e,target:zc(a,i),targetJobId:a.targetId,...n?{initialCursor:n}:{},serverHeldStream:!1}}function os(e){const t=new Map;for(const i of e){const n=`${i.target.selectorKind}:${i.target.targetId}`,a=t.get(n);if(!a){t.set(n,i);continue}const r=Be([...a.target.relatedJobIds??[],...i.target.relatedJobIds??[]]);t.set(n,{...a,target:r.length>0?{...a.target,relatedJobIds:r}:a.target,initialCursor:a.initialCursor??i.initialCursor})}return Array.from(t.values())}function Rt(e,t,i,n){return{source:e,hasEvidence:t,candidates:os(i.filter(a=>!!a)),...n&&n.length>0?{disabledReasonCodes:Be(n)}:{}}}function cs(e,t){return e.target.selectorKind===t.target.selectorKind&&e.target.targetId===t.target.targetId}function tn(e,t){const i=Be(e.filter(n=>typeof n=="string").map(n=>Ke(n)).filter(n=>!!n));if(t){const n=i.find(a=>cr(a)===t);if(n)return n}return i[0]}function An(e,t){return Be(e.filter(i=>typeof i=="string").map(i=>Ke(i)).filter(i=>!!i)).find(i=>cr(i)===t)}function ss(e){const t=g(e?.continuity)?e.continuity:void 0,i=g(t?.jobs)?t.jobs:void 0,n=g(i?.watcher)?i.watcher:void 0,a=as(n?.reasonCodes??i?.reasonCodes);if(!n)return Rt("watcher-metadata",a.length>0,[],a);if(n.active===!1||a.length>0)return Rt("watcher-metadata",!0,[],a.length>0?a:[Le.MALFORMED]);if(n.serverHeldStream!==!1)return Rt("watcher-metadata",!0,[],[Le.SERVER_HELD_STREAM]);const r=Jc(n);if(!r)return Rt("watcher-metadata",!0,[],[Le.MISSING]);const o=typeof n.initialCursor=="string"?n.initialCursor:void 0;return Rt("watcher-metadata",!0,[{source:"watcher-metadata",target:r,targetJobId:r.targetId,...o?{initialCursor:o}:{},serverHeldStream:!1}])}function ki(e,t){const i=g(e.loopJobPlan)?e.loopJobPlan:void 0,n=g(i?.metadata)?i.metadata:void 0,a=g(e.metadata)?e.metadata:void 0,o=(t==="goal"?tn([e.goalId,e.targetGoalId,e.campaignId,e.jobId,e.targetJobId,a?.goalId,a?.campaignId,a?.jobId],"goal"):tn([e.loopId,e.targetLoopId,e.jobId,e.targetJobId,a?.loopId,a?.jobId,n?.loopId,n?.jobId],"loop"))??tn([e.jobId,e.targetJobId,a?.jobId,n?.jobId]);return pr("goal-loop-continuity-metadata",o,[e.jobId,e.targetJobId,a?.jobId,n?.jobId])}function ds(e){const t=g(e?.continuity)?e.continuity:void 0,i=g(t?.goal)?t.goal:void 0,n=g(t?.loop)?t.loop:void 0,a=[i?ki(i,"goal"):void 0,n?ki(n,"loop"):void 0],r=!!(i||n);return Rt("goal-loop-continuity-metadata",r,a,r&&a.every(o=>!o)?[Le.MISSING]:void 0)}function ps(e){return Array.isArray(e)?e.filter(g):g(e)?Array.isArray(e.operationLogs)?e.operationLogs.filter(g):g(e.operationLog)?[e.operationLog]:Array.isArray(e.operations)?[e]:[]:[]}function Oi(e,t){const i=g(t.metadata)?t.metadata:void 0,n=An([t.goalId,t.targetGoalId,t.campaignId,i?.goalId,i?.campaignId,t.jobId,i?.jobId],"goal"),a=An([t.loopId,t.targetLoopId,i?.loopId,t.jobId,i?.jobId],"loop"),r=tn([t.jobId,t.targetJobId,i?.jobId],"job"),o=n??a??r;if(!o)return;const d=e.get(o)??{targetId:o,relatedJobIds:[]};d.relatedJobIds.push(...sr([r,t.jobId,t.targetJobId,i?.jobId])),e.set(o,d)}function ls(e){const t=g(e.metadata)?e.metadata:void 0;return!!(An([e.goalId,e.targetGoalId,e.campaignId,t?.goalId,t?.campaignId,e.jobId,t?.jobId],"goal")??An([e.loopId,e.targetLoopId,t?.loopId,e.jobId,t?.jobId],"loop"))}function us(e){const t=g(e.metadata)?e.metadata:void 0;return!!tn([e.goalId,e.targetGoalId,e.campaignId,e.loopId,e.targetLoopId,e.jobId,e.targetJobId,t?.goalId,t?.campaignId,t?.loopId,t?.jobId])}function Ni(e,t){const i=[];for(const o of["metadata","job","event","receipt","processingOutputSummary"]){const d=t[o];g(d)&&i.push(d)}const n=g(t.event)?t.event:void 0;g(n?.metadata)&&i.push(n.metadata),g(n?.processingOutputSummary)&&i.push(n.processingOutputSummary);const a=g(t.receipt)?t.receipt:void 0;g(a?.metadata)&&i.push(a.metadata);const r=i.some(us);for(const o of i)Oi(e,o);(!r||ls(t))&&Oi(e,t)}function hs(e){const t=ps(e?.continuityStateUpdate),i=new Map;for(const a of t){Ni(i,a);const r=Array.isArray(a.operations)?a.operations.filter(g):[];for(const o of r)Ni(i,o)}const n=Array.from(i.values()).map(a=>pr("continuity-state-update-operation-log",a.targetId,a.relatedJobIds));return Rt("continuity-state-update-operation-log",t.length>0,n,t.length>0&&n.every(a=>!a)?[Le.MISSING]:void 0)}function gs(e){const t=xi(e);return Rt("explicit-args",t.length>0,t.map(i=>pr("explicit-args",i)))}function fs(e,t){const i=[ss(e),ds(e),hs(e),gs(t)];for(let n=0;n<i.length;n+=1){const a=i[n];if(!a.hasEvidence)continue;if(a.disabledReasonCodes&&a.disabledReasonCodes.length>0)return Gt(a.disabledReasonCodes);if(a.candidates.length!==1)return Gt([a.candidates.length>1?Le.AMBIGUOUS:Le.MISSING]);const r=a.candidates[0];for(const o of i.slice(n+1)){if(!o.hasEvidence)continue;if(o.disabledReasonCodes&&o.disabledReasonCodes.length>0)return Gt(o.disabledReasonCodes);if(o.candidates.length>1)return Gt([Le.AMBIGUOUS]);const d=o.candidates[0];if(d&&!cs(r,d))return Gt([Le.CONFLICT])}return{target:r.target,targetJobId:r.targetJobId,...r.initialCursor?{initialCursor:r.initialCursor}:{},source:r.source,serverHeldStream:!1}}return Gt([Le.MISSING])}async function lr(e,t,i,n={}){const a="/api/v1/invoke";let r,o;const d=await Zt(e,a,t,i,{...n,deferSuccessfulJsonParsing:!0,...t.privateExecution?{maxAttempts:1,allowReplayRetry:!1}:{},admitResponseBeforeBodyRead:S=>{const u=S.headers.get("X-Neocortex-Compatibility");if(u!==null)try{if(u.length===0||u.length>8192)throw new Error("header-size");const C=JSON.parse(Buffer.from(u,"base64url").toString("utf8"));if(!Qa(C))throw new Error("header-shape");if(r=C,C.status==="incompatible")return o="incompatible",!1}catch{return o="malformed",!1}return n.admitResponseBeforeBodyRead?.(S)??!0}});if(d.networkFailure||!d.response)return{ok:!1,status:0,error:"Network error after bounded retries"};if(d.responseAdmissionRejected){const S=o==="malformed"?$t.RESULT_MALFORMED:r?.reasonCodes[0]??$t.OFFER_MALFORMED;return{ok:!1,status:d.response.status,error:`COMPATIBILITY_INCOMPATIBLE: ${S}`,errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:S,fallback_action:r?.remediationHint??"upgrade-client"},...r?{compatibility:r}:{}}}const{response:s,text:l}=d;let y=d.parsed;try{if(t.compatibility&&!r){if(/"(?:reviewReconciliation|review_reconciliation|reconciliationMetadata|releaseLifecycle|release_lifecycle|releaseBlocked|release_blocked|yoloopReleaseBlocked)"\s*:/u.test(l))return{ok:!1,status:s.status,error:`COMPATIBILITY_INCOMPATIBLE: ${$t.UNNEGOTIATED_PROTECTED_FIELD}`,errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:$t.UNNEGOTIATED_PROTECTED_FIELD,fallback_action:"upgrade-client"}};r=Ka({clientVersion:t.compatibility.clientVersion,serverVersion:"0.0.0",registryVersion:t.registryVersion,registryChecksum:t.registryChecksum,reason:$t.SERVER_NEGOTIATION_MISSING})}if(s.ok)try{y=l?JSON.parse(l):{}}catch{return{ok:!1,status:s.status,error:"COMPATIBILITY_INCOMPATIBLE: response-json-malformed",errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:$t.RESULT_MALFORMED},...r?{compatibility:r}:{}}}if(!s.ok)return t.privateExecution?{ok:!1,status:s.status,error:"private-execution-invoke-unavailable"}:{ok:!1,status:s.status,error:Object.keys(y).length>0?`${y.error_code??"ERROR"}: ${y.message??l}`:`HTTP ${s.status}: ${l}`,errorBody:Object.keys(y).length>0?y:void 0,...r?{compatibility:r}:{}};const S=y,u=s.headers.get("X-Client-Version-Warning");return u&&!Ei&&(Ei=!0,process.stderr.write(`
|
|
20
|
+
`);return}if(t==="json"){i.write(JSON.stringify(Gc(e))+`
|
|
21
|
+
`);return}i.write(Wc(e)+`
|
|
22
|
+
`)}function cr(e){return Ha.has(e.status)}function Yc(e,t,i){if(t){const o=e.find(n=>n.jobId===t);return!!(o&&cr(o))}return i<=0?!1:e.filter(o=>!cr(o)).length===0}function qc(e,t,i,r){return i<r?!1:t?!e.some(o=>o.jobId===t&&!cr(o)):e.length===0}function zc(e,t){return t?.aborted?Promise.resolve():new Promise(i=>{const r=setTimeout(o,e);function o(){clearTimeout(r),t?.removeEventListener("abort",o),i()}t?.addEventListener("abort",o,{once:!0})})}function Jc(e){return e.includes(Le.MALFORMED)?"malformed":e.includes(Le.AMBIGUOUS)?"ambiguous":e.includes("watch-target-multiple")?"multiple":e.includes("watch-evidence-unsafe")?"unsafe":e.includes(Le.MISSING)||e.includes(_e.TARGET_UNRESOLVED)?"unresolved":"unavailable"}function xi(e,t){const i=t?en(t):void 0,r=Ue([...e,_e.TARGET_UNRESOLVED,G.WATCH_TARGET_UNRESOLVED]),o=ar(i,i?.targetId,Jc(r),r),n=ut({generatedAt:new Date().toISOString()},[],!1,0,[G.WATCH_TARGET_UNRESOLVED]),a=et(void 0,void 0,void 0,[],[G.WATCH_TARGET_UNRESOLVED],"unavailable");return tt({watchStatus:"blocked",active:!1,targetEvidence:o,snapshotEvidence:n,cursorEvidence:a,stopReason:"target_unresolved",reasonCodes:r,generatedAt:n.generatedAt})}function Kc(e,t,i,r,o=!1){const n=xi(e,Pi(t));return nt(n,i,r,o),ht("target-unresolved",0,0,n,o)}async function Qc(e){if(e.signal?.aborted){const k=ar(e.target??en(e.targetJobId),e.targetJobId,e.target??e.targetJobId?"resolved":"unresolved",[_e.CANCELLED]),_=ut(void 0,[],!1,0),w=et(e.initialCursor,e.initialCursor,e.initialCursor,[],[_e.CANCELLED],"unavailable"),L=tt({watchStatus:"stopped",active:!1,targetEvidence:k,snapshotEvidence:_,cursorEvidence:w,stopReason:"cancelled",reasonCodes:[_e.CANCELLED]});return ht("cancelled",0,0,L,e.protectedOutput)}const t=e.target??en(e.targetJobId),i=e.targetJobId??t?.targetId,r=e.stdout??process.stdout;if(!t){const k=xi([Le.MISSING,_e.TARGET_UNRESOLVED]);return nt(k,e.format,r,e.protectedOutput),ht("target-unresolved",0,0,k,e.protectedOutput)}const o=wn(e.limit??An("NEOCORTEX_INVOKE_WATCH_LIMIT",Lr),Lr,50),n=Math.max(50,wn(e.pollIntervalMs??An("NEOCORTEX_INVOKE_WATCH_POLL_INTERVAL_MS",jr),jr,6e4)),a=wn(e.maxIdlePolls??An("NEOCORTEX_INVOKE_WATCH_MAX_IDLE_POLLS",Dr),Dr,120),d=wn(e.maxPolls??An("NEOCORTEX_INVOKE_WATCH_MAX_POLLS",Mr),Mr,86400),s=e.sleep??zc;let l=e.initialCursor,m=0,S=0,u=0;const v=ar(t,i,"resolved",[G.OK]),I={schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:"pending",renderedSummaryCount:0,reasonCodes:[G.WATCH_RENDER_PENDING],publicSafe:!0},g=et(e.initialCursor,l,l,[],e.initialCursor?[G.WATCH_CURSOR_UNCHANGED]:[G.WATCH_NO_SUMMARIES_YET],e.initialCursor?"unchanged":"not_started");nt(tt({watchStatus:"active",active:!0,targetEvidence:v,snapshotEvidence:I,cursorEvidence:g,stopReason:"not_stopped",reasonCodes:[G.OK]}),e.format,r,e.protectedOutput);let E;try{E=await Po({projectRoot:e.projectRoot,strictReadOnly:e.strictReadOnly})}catch{const k=ut(void 0,[],!1,m,[G.WATCH_SNAPSHOT_UNAVAILABLE]),_=et(e.initialCursor,l,l,[],[G.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),w=tt({watchStatus:"blocked",active:!1,targetEvidence:v,snapshotEvidence:k,cursorEvidence:_,stopReason:"unavailable_evidence",reasonCodes:[_e.STORE_UNAVAILABLE]});return nt(w,e.format,r,e.protectedOutput),ht("store-unavailable",m,u,w,e.protectedOutput)}try{for(;!e.signal?.aborted&&u<d;){u+=1;const k=l,_=E.collectProcessingOutputSummaryCursor({...l?{cursor:l}:{},...t?{target:t}:{},...i?{jobId:i}:{},limit:o}),w=E.collectSnapshot({jobLimit:50,processingSummaryLimit:1}),L=w.jobs;if(_.summaries.length>0){for(const X of _.summaries)Fc(X,e.format,r,e.protectedOutput),m+=1;l=_.nextCursor??_.summaries[_.summaries.length-1]?.cursor??l,S=0}else l=_.nextCursor??l,S+=1;const D=ut(w,_.summaries,!0,_.summaries.length),Y=et(e.initialCursor,k,l,_.summaries,_.summaries.length>0?[G.WATCH_CURSOR_ADVANCED]:[G.WATCH_NO_SUMMARIES_YET]);if(nt(tt({watchStatus:_.summaries.length>0?"polling":"waiting",active:!0,targetEvidence:v,snapshotEvidence:D,cursorEvidence:Y,stopReason:"not_stopped",reasonCodes:_.summaries.length>0?[G.WATCH_CURSOR_ADVANCED]:[G.WATCH_NO_SUMMARIES_YET],generatedAt:w.generatedAt}),e.format,r,e.protectedOutput),!_.hasMore&&Yc(L,i,m)){const X=ut(w,_.summaries,!1,m,[_e.COMPLETED]),pe=et(e.initialCursor,k,l,_.summaries,[_e.COMPLETED],"exhausted"),b=tt({watchStatus:"stopped",active:!1,targetEvidence:v,snapshotEvidence:X,cursorEvidence:pe,stopReason:"not_stopped",reasonCodes:[_e.COMPLETED],generatedAt:w.generatedAt});return nt(b,e.format,r,e.protectedOutput),ht("completed",m,u,b,e.protectedOutput)}if(!_.hasMore&&qc(L,i,S,a)){const X=ut(w,_.summaries,!1,m,[G.WATCH_STOP_IDLE_LIMIT_REACHED]),pe=et(e.initialCursor,k,l,_.summaries,[G.WATCH_STOP_IDLE_LIMIT_REACHED],"exhausted"),b=tt({watchStatus:"stopped",active:!1,targetEvidence:v,snapshotEvidence:X,cursorEvidence:pe,stopReason:"idle_limit_reached",reasonCodes:[_e.IDLE_TIMEOUT,G.WATCH_STOP_IDLE_LIMIT_REACHED],generatedAt:w.generatedAt});return nt(b,e.format,r,e.protectedOutput),ht("idle-timeout",m,u,b,e.protectedOutput)}_.hasMore||await s(n,e.signal)}}catch{const k=ut(void 0,[],!1,m,[G.WATCH_SNAPSHOT_UNAVAILABLE]),_=et(e.initialCursor,l,l,[],[G.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),w=tt({watchStatus:"blocked",active:!1,targetEvidence:v,snapshotEvidence:k,cursorEvidence:_,stopReason:"unavailable_evidence",reasonCodes:[_e.STORE_UNAVAILABLE]});return nt(w,e.format,r,e.protectedOutput),ht("store-unavailable",m,u,w,e.protectedOutput)}finally{E.close()}if(e.signal?.aborted){const k=ut(void 0,[],!1,m,[_e.CANCELLED]),_=et(e.initialCursor,l,l,[],[_e.CANCELLED],"unavailable"),w=tt({watchStatus:"stopped",active:!1,targetEvidence:v,snapshotEvidence:k,cursorEvidence:_,stopReason:"cancelled",reasonCodes:[_e.CANCELLED]});return nt(w,e.format,r,e.protectedOutput),ht("cancelled",m,u,w,e.protectedOutput)}const x=ut(void 0,[],!1,m,[G.WATCH_STOP_MAX_POLLS_REACHED]),M=et(e.initialCursor,l,l,[],[G.WATCH_STOP_MAX_POLLS_REACHED],"exhausted"),P=tt({watchStatus:"stopped",active:!1,targetEvidence:v,snapshotEvidence:x,cursorEvidence:M,stopReason:"max_polls_reached",reasonCodes:[_e.MAX_POLLS,G.WATCH_STOP_MAX_POLLS_REACHED]});return nt(P,e.format,r,e.protectedOutput),ht("max-polls",m,u,P,e.protectedOutput)}function Ke(e){const t=e.trim().replace(/^@/,"").match(/^(job|goal|loop)-([JGL])(\d{3,})$/i);if(!t)return;const i=t[1].toLowerCase(),r=t[2].toUpperCase();if(!(i==="job"&&r!=="J"||i==="goal"&&r!=="G"||i==="loop"&&r!=="L"))return`${i}-${r}${t[3]}`}function sr(e){if(e.startsWith("job-J"))return"job";if(e.startsWith("goal-G"))return"goal";if(e.startsWith("loop-L"))return"loop"}function Ti(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 o=Ke(r[1]);o&&t.push(o)}return Ue(t)}function Pi(e){return Ti(e)[0]}function en(e){const t=e?Ke(e):void 0;if(t){if(t.startsWith("job-J"))return{selectorKind:"job",targetId:t,jobId:t,publicSafe:!0};if(t.startsWith("goal-G"))return{selectorKind:"goal",targetId:t,goalId:t,publicSafe:!0};if(t.startsWith("loop-L"))return{selectorKind:"loop",targetId:t,loopId:t,publicSafe:!0}}}function dr(e){return Ue(e.filter(t=>typeof t=="string").map(t=>Ke(t)).filter(t=>!!t?.startsWith("job-J")))}function Xc(e,t){const i=dr(t).filter(r=>r!==e.targetId&&r!==e.jobId);return i.length>0?{...e,relatedJobIds:i}:e}function Zc(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"?Ke(e.targetId):typeof t?.targetId=="string"?Ke(t.targetId):typeof e.targetJobId=="string"?Ke(e.targetJobId):void 0,o=en(r);if(!o||i&&i!==o.selectorKind)return;const n=Array.isArray(e.relatedJobIds)?e.relatedJobIds:Array.isArray(t?.relatedJobIds)?t.relatedJobIds:void 0,a=dr([...n??[],e.jobId,t?.jobId,e.targetJobId,t?.targetJobId]).filter(d=>d!==o.targetId&&d!==o.jobId);return{...o,...typeof(e.jobId??t?.jobId)=="string"?{jobId:Ke(e.jobId??t?.jobId)??o.jobId}:{},...typeof(e.goalId??t?.goalId)=="string"?{goalId:Ke(e.goalId??t?.goalId)??o.goalId}:{},...typeof(e.loopId??t?.loopId)=="string"?{loopId:Ke(e.loopId??t?.loopId)??o.loopId}:{},...a.length>0?{relatedJobIds:a}:{}}}function ki(e){const t=e.trim().split(/\s+/).filter(Boolean),i=t[0]?.replace(/^\*/,"").toLowerCase(),r=t[1]?.replace(/^--/,"").toLowerCase();return(i==="jobs"||i==="job"||i==="continuity-jobs"||i==="61")&&r==="watch"}const be=Object.freeze({ACTIVE:"command-level-watch-active",INACTIVE:"command-level-watch-inactive",DUPLICATE:"command-level-watch-duplicate",AMBIGUOUS:"command-level-watch-ambiguous",QUOTED:"command-level-watch-quoted",MALFORMED:"command-level-watch-malformed",NON_FINAL:"command-level-watch-non-final",UNRESOLVED:"command-level-watch-unresolved",UNSUPPORTED:"command-level-watch-unsupported",TARGET_INVALID:"command-level-watch-target-invalid"}),es=new Set(["create","start","resume"]),ts=new Set(["create","resume","run-once"]);function pr(e,t,i,r,o){return{schemaVersion:1,contractVersion:"continuity-v1",...i?{command:i}:{},...r?{operation:r}:{},active:e,...o?{watchToken:o}:{},reasonCodes:Ue(t),serverHeldStream:!1,allJobsPolling:!1,targetResolution:e?"required-after-dispatch":"inactive",publicSafe:!0}}function Me(e,t=[],i,r){const o=t.length>0?t:[be.INACTIVE];return{args:e,watch:!1,reasonCodes:o,metadata:pr(!1,o,i,r),publicSafe:!0}}function ns(e){const t=e.trim().split(/\s+/).filter(Boolean),i=t.slice(2).filter(n=>n==="--watch").length;if(i===0)return Me(e,[],"jobs","watch");if(i!==1)return Me(e,[be.AMBIGUOUS],"jobs","watch");const r=t.filter((n,a)=>a<2||n!=="--watch").join(" ");return ki(r)?r.trim().split(/\s+/).filter(Boolean).slice(2).length!==1?Me(e,[be.AMBIGUOUS],"jobs","watch"):Pi(r)?{args:r,watch:!0,reasonCodes:[be.ACTIVE],metadata:pr(!0,[be.ACTIVE],"jobs","watch"),publicSafe:!0}:Me(e,[be.TARGET_INVALID],"jobs","watch"):Me(e,[be.UNSUPPORTED],"jobs","watch")}function rs(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 o=r;let n="",a=!1,d=null;for(;r<e.length;){const s=e[r];if(d){if(s===d){a=!0,d=null,r+=1;continue}if(s==="\\"&&r+1<e.length){n+=e[r+1],r+=2;continue}n+=s,r+=1;continue}if(/\s/.test(s))break;if(s==='"'||s==="'"){a=!0,d=s,r+=1;continue}n+=s,r+=1}d&&(i=!0),t.push({value:n,start:o,end:r,quoted:a})}return{tokens:t,malformed:i}}function is(e){if(!e||e.quoted)return;const t=e.value.replace(/^\*/,"").toLowerCase();return t==="goal"||t==="loop"?t:void 0}function os(e,t){if(!e||e==="jobs"||!t||t.quoted)return;const i=t.value.toLowerCase();return(e==="goal"?es:ts).has(i)?i:void 0}function as(e){return!e.quoted&&e.value!=="--watch"&&e.value.toLowerCase().startsWith("--watch")}function cs(e){const{tokens:t,malformed:i}=rs(e),r=is(t[0]),o=os(r,t[1]);if(i)return Me(e,[be.MALFORMED],r,o);const n=t.filter(u=>u.value==="--watch"&&!u.quoted),a=t.filter(u=>u.value==="--watch"&&u.quoted),d=t.filter(as);if(!(n.length>0||a.length>0||d.length>0))return Me(e,[],r,o);if(n.length>1)return Me(e,[be.DUPLICATE],r,o);if(n.length===1&&(a.length>0||d.length>0))return Me(e,[be.AMBIGUOUS],r,o);if(a.length>0)return Me(e,[be.QUOTED],r,o);if(d.length>0)return Me(e,[be.MALFORMED],r,o);const l=n[0];if(!l)return Me(e,[],r,o);if(t[t.length-1]!==l)return Me(e,[be.NON_FINAL],r,o);if(!r||!o)return Me(e,[be.UNRESOLVED],r,o);const m=`${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:m,watch:!0,reasonCodes:[be.ACTIVE],metadata:pr(!0,[be.ACTIVE],r,o,S),publicSafe:!0}}function ss(e){return ki(e)?ns(e):cs(e)}function ds(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&Wa.has(t)):[]}function Gt(e){return{disabled:!0,reasonCodes:Ue(e.length>0?e:[Le.MISSING])}}function lr(e,t,i=[],r){const o=en(t);if(o)return{source:e,target:Xc(o,i),targetJobId:o.targetId,...r?{initialCursor:r}:{},serverHeldStream:!1}}function ps(e){const t=new Map;for(const i of e){const r=`${i.target.selectorKind}:${i.target.targetId}`,o=t.get(r);if(!o){t.set(r,i);continue}const n=Ue([...o.target.relatedJobIds??[],...i.target.relatedJobIds??[]]);t.set(r,{...o,target:n.length>0?{...o.target,relatedJobIds:n}:o.target,initialCursor:o.initialCursor??i.initialCursor})}return Array.from(t.values())}function Rt(e,t,i,r){return{source:e,hasEvidence:t,candidates:ps(i.filter(o=>!!o)),...r&&r.length>0?{disabledReasonCodes:Ue(r)}:{}}}function ls(e,t){return e.target.selectorKind===t.target.selectorKind&&e.target.targetId===t.target.targetId}function tn(e,t){const i=Ue(e.filter(r=>typeof r=="string").map(r=>Ke(r)).filter(r=>!!r));if(t){const r=i.find(o=>sr(o)===t);if(r)return r}return i[0]}function bn(e,t){return Ue(e.filter(i=>typeof i=="string").map(i=>Ke(i)).filter(i=>!!i)).find(i=>sr(i)===t)}function us(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,o=ds(r?.reasonCodes??i?.reasonCodes);if(!r)return Rt("watcher-metadata",o.length>0,[],o);if(r.active===!1||o.length>0)return Rt("watcher-metadata",!0,[],o.length>0?o:[Le.MALFORMED]);if(r.serverHeldStream!==!1)return Rt("watcher-metadata",!0,[],[Le.SERVER_HELD_STREAM]);const n=Zc(r);if(!n)return Rt("watcher-metadata",!0,[],[Le.MISSING]);const a=typeof r.initialCursor=="string"?r.initialCursor:void 0;return Rt("watcher-metadata",!0,[{source:"watcher-metadata",target:n,targetJobId:n.targetId,...a?{initialCursor:a}:{},serverHeldStream:!1}])}function Oi(e,t){const i=h(e.loopJobPlan)?e.loopJobPlan:void 0,r=h(i?.metadata)?i.metadata:void 0,o=h(e.metadata)?e.metadata:void 0,a=(t==="goal"?tn([e.goalId,e.targetGoalId,e.campaignId,e.jobId,e.targetJobId,o?.goalId,o?.campaignId,o?.jobId],"goal"):tn([e.loopId,e.targetLoopId,e.jobId,e.targetJobId,o?.loopId,o?.jobId,r?.loopId,r?.jobId],"loop"))??tn([e.jobId,e.targetJobId,o?.jobId,r?.jobId]);return lr("goal-loop-continuity-metadata",a,[e.jobId,e.targetJobId,o?.jobId,r?.jobId])}function hs(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,o=[i?Oi(i,"goal"):void 0,r?Oi(r,"loop"):void 0],n=!!(i||r);return Rt("goal-loop-continuity-metadata",n,o,n&&o.every(a=>!a)?[Le.MISSING]:void 0)}function gs(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 Ni(e,t){const i=h(t.metadata)?t.metadata:void 0,r=bn([t.goalId,t.targetGoalId,t.campaignId,i?.goalId,i?.campaignId,t.jobId,i?.jobId],"goal"),o=bn([t.loopId,t.targetLoopId,i?.loopId,t.jobId,i?.jobId],"loop"),n=tn([t.jobId,t.targetJobId,i?.jobId],"job"),a=r??o??n;if(!a)return;const d=e.get(a)??{targetId:a,relatedJobIds:[]};d.relatedJobIds.push(...dr([n,t.jobId,t.targetJobId,i?.jobId])),e.set(a,d)}function fs(e){const t=h(e.metadata)?e.metadata:void 0;return!!(bn([e.goalId,e.targetGoalId,e.campaignId,t?.goalId,t?.campaignId,e.jobId,t?.jobId],"goal")??bn([e.loopId,e.targetLoopId,t?.loopId,e.jobId,t?.jobId],"loop"))}function ms(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 Li(e,t){const i=[];for(const a of["metadata","job","event","receipt","processingOutputSummary"]){const d=t[a];h(d)&&i.push(d)}const r=h(t.event)?t.event:void 0;h(r?.metadata)&&i.push(r.metadata),h(r?.processingOutputSummary)&&i.push(r.processingOutputSummary);const o=h(t.receipt)?t.receipt:void 0;h(o?.metadata)&&i.push(o.metadata);const n=i.some(ms);for(const a of i)Ni(e,a);(!n||fs(t))&&Ni(e,t)}function ys(e){const t=gs(e?.continuityStateUpdate),i=new Map;for(const o of t){Li(i,o);const n=Array.isArray(o.operations)?o.operations.filter(h):[];for(const a of n)Li(i,a)}const r=Array.from(i.values()).map(o=>lr("continuity-state-update-operation-log",o.targetId,o.relatedJobIds));return Rt("continuity-state-update-operation-log",t.length>0,r,t.length>0&&r.every(o=>!o)?[Le.MISSING]:void 0)}function Es(e){const t=Ti(e);return Rt("explicit-args",t.length>0,t.map(i=>lr("explicit-args",i)))}function Is(e,t){const i=[us(e),hs(e),ys(e),Es(t)];for(let r=0;r<i.length;r+=1){const o=i[r];if(!o.hasEvidence)continue;if(o.disabledReasonCodes&&o.disabledReasonCodes.length>0)return Gt(o.disabledReasonCodes);if(o.candidates.length!==1)return Gt([o.candidates.length>1?Le.AMBIGUOUS:Le.MISSING]);const n=o.candidates[0];for(const a of i.slice(r+1)){if(!a.hasEvidence)continue;if(a.disabledReasonCodes&&a.disabledReasonCodes.length>0)return Gt(a.disabledReasonCodes);if(a.candidates.length>1)return Gt([Le.AMBIGUOUS]);const d=a.candidates[0];if(d&&!ls(n,d))return Gt([Le.CONFLICT])}return{target:n.target,targetJobId:n.targetJobId,...n.initialCursor?{initialCursor:n.initialCursor}:{},source:n.source,serverHeldStream:!1}}return Gt([Le.MISSING])}async function ur(e,t,i,r={}){const o="/api/v1/invoke";let n,a;const d=await Zt(e,o,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 v=JSON.parse(Buffer.from(u,"base64url").toString("utf8"));if(!Zo(v))throw new Error("header-shape");if(n=v,v.status==="incompatible")return a="incompatible",!1}catch{return a="malformed",!1}return r.admitResponseBeforeBodyRead?.(S)??!0}});if(d.networkFailure||!d.response)return{ok:!1,status:0,error:"Network error after bounded retries"};if(d.responseAdmissionRejected){const S=a==="malformed"?$t.RESULT_MALFORMED:n?.reasonCodes[0]??$t.OFFER_MALFORMED;return{ok:!1,status:d.response.status,error:`COMPATIBILITY_INCOMPATIBLE: ${S}`,errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:S,fallback_action:n?.remediationHint??"upgrade-client"},...n?{compatibility:n}:{}}}const{response:s,text:l}=d;let m=d.parsed;try{if(t.compatibility&&!n){if(/"(?:reviewReconciliation|review_reconciliation|reconciliationMetadata|releaseLifecycle|release_lifecycle|releaseBlocked|release_blocked|yoloopReleaseBlocked)"\s*:/u.test(l))return{ok:!1,status:s.status,error:`COMPATIBILITY_INCOMPATIBLE: ${$t.UNNEGOTIATED_PROTECTED_FIELD}`,errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:$t.UNNEGOTIATED_PROTECTED_FIELD,fallback_action:"upgrade-client"}};n=Xo({clientVersion:t.compatibility.clientVersion,serverVersion:"0.0.0",registryVersion:t.registryVersion,registryChecksum:t.registryChecksum,reason:$t.SERVER_NEGOTIATION_MISSING})}if(s.ok)try{m=l?JSON.parse(l):{}}catch{return{ok:!1,status:s.status,error:"COMPATIBILITY_INCOMPATIBLE: response-json-malformed",errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:$t.RESULT_MALFORMED},...n?{compatibility:n}:{}}}if(!s.ok)return t.privateExecution?{ok:!1,status:s.status,error:"private-execution-invoke-unavailable"}:{ok:!1,status:s.status,error:Object.keys(m).length>0?`${m.error_code??"ERROR"}: ${m.message??l}`:`HTTP ${s.status}: ${l}`,errorBody:Object.keys(m).length>0?m:void 0,...n?{compatibility:n}:{}};const S=m,u=s.headers.get("X-Client-Version-Warning");return u&&!Si&&(Si=!0,process.stderr.write(`
|
|
23
23
|
[Neocortex] ${u}
|
|
24
24
|
|
|
25
|
-
`)),{ok:!0,status:s.status,data:S,...
|
|
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 ${zr/1e3}s`:"Network error: invalid response"}}}async function Ss(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 vs(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 Di(e,t,i,r={}){const o=await Zt(e,"/api/v1/invoke/epic-claims/acknowledge",{...i,registryVersion:dt,registryChecksum:st},t,r);return!!o.response?.ok&&o.parsed.status==="ok"&&o.parsed.claimOutcome===i.status&&(!i.planningCheckpoint||o.parsed.memoryReceiptId===i.planningCheckpoint.memoryReceiptId)}async function Cs(e,t,i,r,o,n={}){if(!o)return 0;const a=Ht(e);let d=0;for(const[s,l]of Object.entries(a.operations))l.planningProtocol==="root-staged-v1"||!l.claimId||!l.epicId||!t.epics?.[l.epicId]||!await Di(i,r,{claimId:l.claimId,projectId:o,epicId:l.epicId,status:"materialized"},n)||(Ma(e,s),d+=1);return d}function _s(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 o=i[0],n=o.certificate,a=n?.expectedTransition;if(o.storyIds!=="[CIRCULAR]"||n?.rank!=="[CIRCULAR]"||a?.selectedStoryIds!=="[CIRCULAR]")return;const d=typeof r.epicId=="string"?r.epicId:"",s=e.epics[d],l=Array.isArray(a.storyLifecycle)?a.storyLifecycle:[],m=l.length===1&&typeof l[0]?.storyId=="string"?l[0].storyId:"",u=e.stories[m]?.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 I=(Array.isArray(s.stories)?s.stories.filter(g=>typeof g=="string"):[]).find(g=>{const E=e.stories[g];return!E||["done","completed","merged"].includes(String(E.status))?!1:(Array.isArray(E.depends_on)?E.depends_on.filter(M=>typeof M=="string"):[]).every(M=>["done","completed","merged"].includes(String(e.stories[M]?.status)))});if(I)return{epicId:d,expectedNextStoryId:I,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 hr=["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"],Mi=new Set(["done","completed","merged","cancelled","canceled","abandoned"]),ji=new Set(["skipped-with-debt","documented"]);function Vi(e){return typeof e=="string"?e.trim().toLowerCase().replace(/_/g,"-"):""}function Rs(e){const t=Vi(e);if(Mi.has(t)||ji.has(t))return 0;const i=hr.indexOf(t);return i<0?hr.length:hr.length-1-i}function ws(e,t){const i=e.epics[t];if(!i||!Array.isArray(i.stories)||i.stories.some(m=>typeof m!="string"||!/^P[1-9][0-9]*\.[0-9]+$/.test(m)))return null;const r=[...i.stories],o=[],n=[];let a=0,d=0;const s=[];for(const m of r){const S=e.stories[m];if(!S||!Array.isArray(S.depends_on)||S.depends_on.some(g=>typeof g!="string"))return null;const u=[...S.depends_on].sort(),v=Rs(S.status),I=Vi(S.status);o.push({id:m,dependsOn:u}),n.push({id:m,status:S.status,dependsOn:u}),s.push({storyId:m,remaining:v}),a+=v,!Mi.has(I)&&!ji.has(I)&&(d+=1)}const l={version:1,policy:"p205-finite-resume-v2",epicId:t,storyIds:r,queueEpicIds:[t],initialEpicIndex:0,graphFingerprint:vt("p205-yoloop-graph-v1",o),lifecycleVersion:"p205-lifecycle-v1",terminalPredicateVersion:"p205-terminal-v1",initialSnapshotFingerprint:vt("p205-yoloop-initial-snapshot-v1",{epicId:t,stories:n}),initialRank:{version:1,queue:0,epic:d,lifecycle:a},initialStoryLifecycle:s};return Object.freeze({...l,sessionId:vt("p205-yoloop-session-v1",l)})}function Bi(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 As(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=ws(e.snapshot,e.targetEpicId);if(!t)throw new Error("yoloop-causal-reconciliation-target-invalid");const i=String(t.graphFingerprint),r=Ar(e.projectRoot),o=Object.values(r.operational.identities).filter(L=>L.epicId===e.targetEpicId&&L.graphRevision===i);if(o.length!==1)throw new Error("epic-operational-identity-mismatch");const n=e.snapshot.yoloop,a=n?n.lock!==null||n.state.currentSession!==null?"active":"inactive":"unknown",d=po({document:r.document,targetIdentityHash:o[0].identityHash,targetEpicId:e.targetEpicId,targetGraphRevision:i,legacyActivity:a});if(d.kind!=="eligible")throw new Error(d.reasonCodes[0]??"yoloop-causal-reconciliation-ineligible");const s=r.operational,l=s.yoloop.state.continuationSession,m=s.yoloop.state.pendingContinuationAuthorities??[],S=s.yoloop.state.runControl;if(!l||typeof l.sessionId!="string"||!S||!["success","exhausted"].includes(S.status)||m.length>1)throw new Error("yoloop-causal-reconciliation-preimage-invalid");const u=vt("p224-common-continuation-session-v1",s.yoloop.state.continuationSession??null),v=vt("p224-common-pending-authorities-v1",m),I=vt("p224-common-continuation-session-v1",t),g=vt("p224-invoke-session-recovery-v1",{identityHash:o[0].identityHash,originalInputSha256:e.originalInputSha256,canonicalInputSha256:e.canonicalInputSha256,expectedSessionHash:u,expectedPendingHash:v,nextSessionHash:I,runId:S.runId,runRevision:S.revision}),E={operationId:`p224rec-${g.slice(0,32)}`,idempotencyKey:`p224rec-${g.slice(0,32)}`,expectedCommonRevision:r.document.revision,expectedWriterEpoch:s.writerEpoch,expectedIdentityHash:o[0].identityHash,sourceEpicId:d.evidence.sourceEpicId,sourceGraphRevision:d.evidence.sourceGraphRevision,targetEpicId:e.targetEpicId,targetGraphRevision:i,expectedRunId:S.runId,expectedRunStatus:S.status,expectedRunRevision:S.revision,expectedSnapshotHash:S.latestSnapshotHash,sourceSessionId:l.sessionId,expectedSessionHash:u,expectedPendingHash:v,expectedPendingCount:m.length,nextSession:t,nextSessionHash:I},x=so(E),M={schemaVersion:"YoloopCrossEpicReconciliationReceipt/1.0",operationId:E.operationId,idempotencyKey:E.idempotencyKey,payloadHash:x,sourceEpicId:E.sourceEpicId,sourceGraphRevision:E.sourceGraphRevision,targetEpicId:E.targetEpicId,targetGraphRevision:E.targetGraphRevision,runId:E.expectedRunId,previousSessionHash:u,nextSessionHash:I,retiredAuthorityHash:v,retiredAuthorityCount:E.expectedPendingCount,outcome:"cross-epic-reconciled",publicSafe:!0},P={type:"reconcile_cross_epic_continuation",...E,payloadHash:x,receipt:M};await co(e.projectRoot,P);const k=Ar(e.projectRoot),_=k.operational.yoloop.state.pendingContinuationAuthorities??[];if(!k.operational.reconciliationReceipts.find(L=>L.payloadHash===x)||_.length!==0||vt("p224-common-continuation-session-v1",k.operational.yoloop.state.continuationSession??null)!==I)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:Bi(t),retryCount:0,publicSafe:!0})}}const bs=/^\*yolo @docs\/stories\/[A-Za-z0-9][A-Za-z0-9._-]{0,79}\.story\.md story-worktree-phase-1$/,Ui=9e4,$i=6,xs=1e3;function Ts(e){return typeof e=="string"&&bs.test(e)&&!e.includes("..")}function Ps(e){const t=e.metadata?.storyWorktreePhase;if(!e.success||!t||typeof t!="object"||Array.isArray(t))return;const i=t;return i.decision==="spec-barrier-waiting"&&i.phase==="phase-1"?i:void 0}async function ks(e,t,i={}){const r=i.sleep??(l=>new Promise(m=>setTimeout(m,l))),o=i.now??Date.now,n=Math.max(1,Math.min(i.maxAttempts??$i,$i)),a=Math.max(0,Math.min(i.maxWaitMs??Ui,Ui)),d=o();let s=0;for(;;){const l=await t(e);s+=1;const m=Ps(l);if(!m)return l;const S=typeof m.maxWaitMs=="number"&&Number.isFinite(m.maxWaitMs)?m.maxWaitMs:0,u=Math.min(a,Math.max(0,S)),v=typeof m.retryAfterMs=="number"&&Number.isFinite(m.retryAfterMs)?m.retryAfterMs:0,I=Math.min(Math.max(v,xs),u),g=o()-d;if(s>=n||g+I>u)return{success:!0,instructions:`# Story-worktree spec barrier timeout
|
|
26
26
|
|
|
27
27
|
The C04 barrier did not open within the bounded wait. Return this resumable receipt to the root; the root re-dispatches the same phase-1 prompt, which resumes at C05. No C05 step was executed.
|
|
28
28
|
|
|
29
|
-
[STORY_WORKTREE_SPEC_BARRIER_TIMEOUT]`,metadata:{...l.metadata,storyWorktreePhase:{...
|
|
30
|
-
`)}}async function
|
|
31
|
-
`),{success:!1,error:p,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}let w=
|
|
32
|
-
`)})}catch(p){const
|
|
29
|
+
[STORY_WORKTREE_SPEC_BARRIER_TIMEOUT]`,metadata:{...l.metadata,storyWorktreePhase:{...m,decision:"spec-barrier-timeout",reasonCode:"spec-barrier-waiting",resumable:!0,attempts:s,waitedMs:Math.max(0,g),publicSafe:!0}},exitCode:0};await r(I)}}async function Os(e,t){const i=t.metadata?.storyWorktreePhase;if(!t.success||!i||typeof i!="object"||Array.isArray(i))return;const r=i,o=r.specAcceptance,n=r.phaseOneReceipt,a=typeof r.storyId=="string"?r.storyId:void 0,d=a&&/^P[0-9]{1,12}\./.test(a)?a.split(".")[0]:void 0;if(!(!d||o===void 0&&n===void 0))try{await Hr(e,s=>{ma(s,d,{...o!==void 0?{specAcceptances:[o]}:{},...n!==void 0?{receipts:[n]}:{}})})}catch(s){const l=s instanceof Error&&/^[a-z0-9-]{1,80}$/.test(s.message)?s.message:"story-worktree-evidence-persist-failed";process.stderr.write(`[Neocortex] story-worktree evidence not persisted (${l}); the root must re-dispatch this phase-1 prompt.
|
|
30
|
+
`)}}async function Ns(e){if(!Ts(e.args))return Hi(e);const t=e.projectRoot??process.cwd();return ks(e.args,async()=>{const i=await Hi(e);return await Os(t,i),i})}async function Hi(e){let t;try{if(t=e.inputEnvelope??Qt(e.inputSource??"args",e.args),Fo(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=$n(t);let o=i,n=r,a=ni(i),d;if(a.outcome!=="resolved"){const c=$a(i);c.kind==="canonicalized"&&(o=c.canonicalArgs,n=$n(Qt(t.source,o)),d=c.binding,a=ni(o))}if(a.outcome!=="resolved"){const c=qo(a,"client"),p=a.outcome==="malformed_input"?a.reason==="input_limit"||a.reason==="token_limit"||a.reason==="token_size_limit"?"input-limit-exceeded":a.reason==="invalid_control"||a.reason==="invalid_surrogate"?"invalid-control-character":a.reason==="unterminated_quote"||a.reason==="trailing_escape"||a.reason==="unsupported_escape"?"unterminated-quote":void 0:void 0,y=p?{code:"INVOCATION_MALFORMED_INPUT",reason:p,source:t.source,byteLength:t.byteLength,remediation:p==="input-limit-exceeded"?"Reduce the explicit command input or split the requested work into bounded invocations.":p==="invalid-control-character"?"Remove invalid control characters and retry with valid UTF-8 text.":"Close quotes and escapes, or use --stdin/--args-file for multiline content."}:void 0;return{success:!1,error:`INVOCATION_${a.outcome.toUpperCase()}`,errorCode:`INVOCATION_${a.outcome.toUpperCase()}`,metadata:{invocationAdmission:c,...y?{invocationInput:y}:{}},exitCode:1}}if(d&&(e={...e,args:o}),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=Yn(e.projectRoot),l=a.selection.commandId,m=l==="yolo"&&!Or(o,l)?Ra(o):null,S=l==="tech-debt"&&a.selection.positionals.length===0&&(a.selection.operationId==="scan"&&Object.keys(a.selection.options).length===0||a.selection.operationId===void 0&&a.selection.options.scan===!0&&Object.keys(a.selection.options).length===1),u=ho.find(c=>c.id===l),v=u?.subcommands.find(c=>c.id===a.selection.operationId),I=v?v.policy.strictReadOnly==="allow":u?.policy.strictReadOnly==="allow",g=l==="diagnose";let E;try{E=Ho({invocationId:pn(),intent:e.strictReadOnly||g?{schemaVersion:1,policy:Bo,registryVersion:dt,registryChecksum:st}:void 0,registryVersion:dt,registryChecksum:st,registryAllowsStrict:I,requestCanonicalBytes:JSON.stringify({command:l})})}catch(c){if(c instanceof Bt)return{success:!1,error:c.code,errorCode:c.code,exitCode:1};throw c}{E.beginProjection();for(const c of Br)E.project(c);for(const c of Uo)E.project(c);E.seal()}const x=E.mode==="strict";if(l==="create-epic"||l==="idea-diagnose")try{const c=ra(s);if(c&&c!=="finalized")return{success:!1,error:'PROJECT_IDENTITY_MIGRATION_INCOMPLETE: retry `neocortex-client invoke --args "*migrate-project-id"` before create-epic.',errorCode:"PROJECT_IDENTITY_MIGRATION_INCOMPLETE",metadata:{projectIdentityMigration:{phase:c,publicSafe:!0}},exitCode:1}}catch(c){const p=c instanceof Hn?c.code:"PROJECT_IDENTITY_MIGRATION_STATE_CORRUPT";return{success:!1,error:p,errorCode:p,exitCode:1}}const M=e.environment??process.env;if(e.privateExecutionBeta&&(l!=="yolo"&&l!=="research"&&l!=="write-spec"&&l!=="create-tasks"&&l!=="implement"&&l!=="exec"&&l!=="create-epic"&&l!=="idea-diagnose"&&l!=="idea-research"&&l!=="generate-epic"&&l!=="sync-openapi"&&l!=="chaos-plan"&&l!=="ui-ux-review"&&l!=="arch-prd"&&l!=="arch-architecture"&&l!=="arch-fitness-functions"&&l!=="arch-api-contracts"&&l!=="arch-api-integrations"&&l!=="arch-database"&&l!=="arch-security"&&l!=="arch-design-system"&&l!=="arch-performance"&&l!=="arch-testing"&&l!=="arch-infrastructure"&&l!=="arch-review"&&l!=="update-memory"&&l!=="arch-ux-design"&&l!=="generate-pacts"&&l!=="property-test"&&!S||x||e.platformTarget!==void 0&&e.platformTarget!=="codex"))return{success:!1,error:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",errorCode:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",exitCode:1};const P=Lo({cwd:s,env:M,targetFlag:e.privateExecutionBeta?"codex":e.platformTarget}),k=P.targetId,_=e.privateExecutionBeta?void 0:No({cwd:s,env:M,targetFlag:e.platformTarget,nativeHostVersion:Ka(P,M)},P);if(m)try{Zn(s,{allowMissingRuntime:!0})}catch(c){const p=c instanceof lt?c.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${p}. No request was sent; repair the canonical project state/runtime sidecar and retry.
|
|
31
|
+
`),{success:!1,error:p,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}let w=m?Bn({strictReadOnly:!0}):Ei(E);const L=(e.serverUrl??w?.serverUrl??fo).replace(/\/+$/,"");let D,Y=!1;if(m){const c=await Ca(L);if(Y=c.supported&&c.projectManifestProjection===!0,!c.supported)return{success:!1,error:`YOLO_INVOKE_ENVELOPE_CAPABILITY_UNAVAILABLE: target server does not advertise ${Mo}; Local YOLO/TDD Release Gate was not executed and no invoke request was sent.`,errorCode:"YOLO_INVOKE_ENVELOPE_CAPABILITY_UNAVAILABLE",metadata:{yoloInvokeEnvelopeCapability:c},exitCode:1};try{D=Wr({projectRoot:s,storyId:m,epicId:m.split(".")[0],inputSha256:n.sha256,onOmittedReferences:p=>process.stderr.write(`[Neocortex] yolo-spec-supporting-references-omitted count=${p}; core story artifacts preserved.
|
|
32
|
+
`)})}catch(p){const y=Fr(p);return{success:!1,error:y,errorCode:y,exitCode:1}}w=Ei(E)}if(l!=="migrate-project-id"&&E.execute({phase:"client-preflight",domain:"client-persistence",category:"first-run-marker",operation:"create"},()=>Va(),()=>{}),l==="migrate-project-id"){const c=await ia(L);if(!c.supported)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_CAPABILITY_UNAVAILABLE: the server did not advertise the versioned migration capability; no local state was changed.",errorCode:"PROJECT_IDENTITY_MIGRATION_CAPABILITY_UNAVAILABLE",metadata:{projectIdentityMigrationCapability:c},exitCode:1};const p=[];let y;try{y=na(s)}catch(U){const Ee=U instanceof Hn?U.code:"PROJECT_IDENTITY_MIGRATION_PREPARE_FAILED";return{success:!1,error:Ee,errorCode:Ee,exitCode:1}}p.push(Ut({phase:"prepare",outcome:y.changed&&y.document.phase==="prepared"?"prepared":"retry",floor:y.document.legacyEpicFloor,licenseId:"local-client",projectId:y.document.projectId}));const A=_n(s);if(A.config.project_id!==y.document.projectId)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",errorCode:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",metadata:{invocationDiagnostics:p},exitCode:1};const B=await Ii(L,w?.licenseKey,E);if(B.status!=="authenticated"){const U=B.status==="refresh-required";return{success:!1,error:U?"Authentication refresh required. Run: neocortex activate YOUR-LICENSE-KEY":"Not authenticated. Visit https://neocortex.sh/portal/login to get your license key, then run: neocortex activate YOUR-LICENSE-KEY",errorCode:U?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",metadata:{invocationDiagnostics:p},exitCode:U?1:2}}let ne;try{ne=kr(e.args.trim(),A)}catch(U){const Ee=U instanceof Nr?U.code:"PROJECT_IDENTITY_MIGRATION_PROJECTION_FAILED";return{success:!1,error:Ee,errorCode:Ee,metadata:{invocationDiagnostics:p},exitCode:1}}let ce={args:i,projectRoot:s.replace(Kt(),"~"),stateSnapshot:ne,platformTarget:k,..._?{nativeHostAttestation:_}:{},projectId:y.document.projectId,projectIdentityMigration:y.request,inputEvidence:r,idempotencyKey:y.document.operationId,registryVersion:dt,registryChecksum:st,compatibility:zn()};try{ce=ir(ce).body}catch(U){if(U instanceof Jn||U instanceof Kn)return{success:!1,error:U.message,errorCode:U.code,metadata:{invokePayload:U.telemetry,invocationDiagnostics:p},exitCode:1};throw U}const re=await Un("invoke-query",()=>ur(L,ce,B.token,{refreshToken:()=>B.client.forceRefresh()}));if(!re.ok||!re.data)return p.push(Ut({phase:"seed",outcome:"rejected",floor:y.document.legacyEpicFloor,licenseId:"local-client",projectId:y.document.projectId})),{success:!1,error:Je(re.error??"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",kt),errorCode:typeof re.errorBody?.error_code=="string"?re.errorBody.error_code:"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",metadata:{invocationDiagnostics:p},exitCode:re.status===401?2:1};const fe=re.data.metadata?.projectIdentityMigration;try{Yo(fe),p.push(Ut({phase:"seed",outcome:fe.status,floor:fe.acceptedLegacyFloor,licenseId:"local-client",projectId:fe.projectId})),ea(s,fe),p.push(Ut({phase:"remote-acknowledged",outcome:fe.status,floor:fe.acceptedLegacyFloor,licenseId:"local-client",projectId:fe.projectId})),ta(s,fe),p.push(Ut({phase:"finalize",outcome:"finalized",floor:fe.acceptedLegacyFloor,licenseId:"local-client",projectId:fe.projectId}))}catch(U){p.push(Ut({phase:"reconcile",outcome:"rejected",floor:y.document.legacyEpicFloor,licenseId:"local-client",projectId:y.document.projectId}));const Ee=U instanceof Hn?U.code:U instanceof Error?U.message:"PROJECT_IDENTITY_MIGRATION_RECEIPT_INVALID";return{success:!1,error:Ee,errorCode:Ee,metadata:{invocationDiagnostics:p},exitCode:1}}return E.complete(),{success:!0,instructions:re.data.instructions,metadata:{...re.data.metadata,...re.compatibility?{compatibility:re.compatibility}:{},invocationDiagnostics:p},exitCode:0}}try{const{normalizeYoloopTargetArgs:c}=await import("../yoloop/target-normalization.js"),p=c(e.args,{projectRoot:s});if(!p.ok)return process.stderr.write(`${p.message} reason=${p.reasonCode}
|
|
33
33
|
`),{success:!1,error:p.message,exitCode:1};p.changed&&(e={...e,args:p.args},process.stderr.write(`[Neocortex] yoloop target normalized: ${p.reasonCodes.join(",")}
|
|
34
34
|
`))}catch{const c="INVALID_YOLOOP_TARGET: yoloop target normalization was unavailable; no request was sent.";return process.stderr.write(`${c}
|
|
35
|
-
`),{success:!1,error:c,exitCode:1}}const X=
|
|
36
|
-
`),{success:!1,error:p,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}if(l!=="migrate-state")try{
|
|
35
|
+
`),{success:!1,error:c,exitCode:1}}const X=fi(l);if(X)try{Zn(s,{allowMissingRuntime:!0}).runtimeMissing&&(await E.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},async()=>pa(s),async()=>{}),Zn(s))}catch(c){const p=c instanceof lt?c.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${p}. No request was sent; repair the canonical project state and retry.
|
|
36
|
+
`),{success:!1,error:p,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}if(l!=="migrate-state")try{E.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>So(s,{args:e.args,canonicalCommandId:l}),()=>{})}catch(c){if(c instanceof Co)return process.stderr.write(`${c.message}
|
|
37
37
|
`),{success:!1,error:c.message,exitCode:1};const p=c instanceof Error?c.message:String(c);return process.stderr.write(`[Neocortex] state.json repair stopped unexpectedly: ${p}. No request was sent; inspect .neocortex/state.json and rerun.
|
|
38
|
-
`),{success:!1,error:p,exitCode:1}}let pe;if(e.privateExecutionBeta&&(l==="sync-openapi"||l==="chaos-plan"||l==="arch-prd"||l==="arch-architecture"||l==="arch-fitness-functions"||l==="arch-api-contracts"||l==="arch-api-integrations"||l==="arch-database"||l==="arch-security"||l==="arch-design-system"||l==="arch-performance"||l==="arch-testing"||l==="arch-infrastructure"||l==="arch-review"||l==="update-memory"||l==="arch-ux-design"||l==="generate-pacts"||l==="property-test"||S))try{const{capturePrivateProjectStepBaseline:c}=await import("../private-execution/isolated-workspace.js");pe=c(s)}catch{const c="private-execution-project-snapshot-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}if(/^\s*\*?(?:yoloop|auto-yolo|epic-runner|story-runner|loop-yolo|auto-epic)\b/i.test(e.args))try{await(await import("../yoloop/invoke-hooks.js")).maybeCaptureYoloopStartOriginBinding(e.args,s)}catch{}let
|
|
39
|
-
`),{success:!1,error:p,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}try{const{maybeAutoResolveYoloopArgs:c}=await import("../yoloop/invoke-hooks.js"),p={args:e.args,projectRoot:s,logger:{info:
|
|
40
|
-
`),warn:
|
|
41
|
-
`)}};c(p),p.args!==e.args&&(e={...e,args:p.args},
|
|
42
|
-
`)}try{const{readYoloopForRequest:c}=await import("../yoloop/invoke-hooks.js"),p=await c(e.args,s);if(p){const
|
|
43
|
-
`),{success:!1,error:
|
|
44
|
-
`)}try{const{maybeRunDiscoveryHook:c}=await import("../yoloop/invoke-hooks.js");await c({args:e.args,projectRoot:s,stateSnapshot:
|
|
45
|
-
`)}try{const{readArchitecturePolicy:c}=await import("../policy/architecture-policy.js"),p=await c(s);p&&(
|
|
46
|
-
`)}});
|
|
47
|
-
`)}try{if(
|
|
48
|
-
`)}try{const c=await
|
|
49
|
-
`)}const Se=w?.licenseKey?new
|
|
50
|
-
`),{success:!1,error:c.message??"Trigger not available on your plan",exitCode:1}}catch{}const ue=await
|
|
38
|
+
`),{success:!1,error:p,exitCode:1}}let pe;if(e.privateExecutionBeta&&(l==="sync-openapi"||l==="chaos-plan"||l==="arch-prd"||l==="arch-architecture"||l==="arch-fitness-functions"||l==="arch-api-contracts"||l==="arch-api-integrations"||l==="arch-database"||l==="arch-security"||l==="arch-design-system"||l==="arch-performance"||l==="arch-testing"||l==="arch-infrastructure"||l==="arch-review"||l==="update-memory"||l==="arch-ux-design"||l==="generate-pacts"||l==="property-test"||S))try{const{capturePrivateProjectStepBaseline:c}=await import("../private-execution/isolated-workspace.js");pe=c(s)}catch{const c="private-execution-project-snapshot-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}if(/^\s*\*?(?:yoloop|auto-yolo|epic-runner|story-runner|loop-yolo|auto-epic)\b/i.test(e.args))try{await(await import("../yoloop/invoke-hooks.js")).maybeCaptureYoloopStartOriginBinding(e.args,s)}catch{}let b;try{const c=await Sc(s,e.args,l);b=_n(s,{epicAware:X,p205Authorities:c,verifyPlanningGeneration:e.privateExecutionBeta&&l==="create-epic"})}catch(c){const p=c instanceof lt?c.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${p}. No request was sent; repair the canonical project state/runtime sidecar and retry.
|
|
39
|
+
`),{success:!1,error:p,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}try{const{maybeAutoResolveYoloopArgs:c}=await import("../yoloop/invoke-hooks.js"),p={args:e.args,projectRoot:s,logger:{info:y=>process.stderr.write(`${y}
|
|
40
|
+
`),warn:y=>process.stderr.write(`${y}
|
|
41
|
+
`)}};c(p),p.args!==e.args&&(e={...e,args:p.args},o=p.args,n=$n(Qt(t.source,o)))}catch(c){const p=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] Auto-resolve hook (P121.05) failed: ${p}. Proceeding with raw args.
|
|
42
|
+
`)}try{const{readYoloopForRequest:c}=await import("../yoloop/invoke-hooks.js"),p=await c(e.args,s);if(p){const y=_s(b,p);b.yoloop=y?{...p,continuationRecoveryEvidence:y}:p}}catch(c){if(/^\s*\*?(?:yoloop|auto-yolo|epic-runner|story-runner|loop-yolo|auto-epic)\b/i.test(e.args)){const y=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] ${y}. No yoloop request was sent.
|
|
43
|
+
`),{success:!1,error:y,errorCode:y,exitCode:1}}}try{const{readContinuityForRequest:c}=await import("../continuity/invoke-hooks.js"),p=await c(e.args,s,void 0,E,{includeExistingStore:!g});p&&(b.continuity=p)}catch(c){if(c instanceof Bt)return{success:!1,error:c.code,errorCode:c.code,exitCode:1};const p=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] continuity snapshot hook failed: ${p}. Proceeding without continuity state.
|
|
44
|
+
`)}try{const{maybeRunDiscoveryHook:c}=await import("../yoloop/invoke-hooks.js");await c({args:e.args,projectRoot:s,stateSnapshot:b,featureFlag:process.env.YOLOOP_AUTO_DISCOVERY!=="off",logger:{warn:p=>{console.warn(p)},info:p=>{console.error(p)}}})}catch(c){const p=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] discovery hook failed: ${p}. Proceeding without enrichment.
|
|
45
|
+
`)}try{const{readArchitecturePolicy:c}=await import("../policy/architecture-policy.js"),p=await c(s);p&&(b.architecture_policy=p)}catch(c){const p=c instanceof Error?c.message:String(c);console.warn(`[Neocortex] architecture-policy hook failed: ${p}. Proceeding without policy.`)}try{const c=/^(1|true|on|yes)$/i.test(process.env.NEOCORTEX_GRAPH_RETRIEVAL??""),{maybeRunGraphRetrievalHook:p}=await import("../yoloop/invoke-hooks.js"),y=await p({args:e.args,projectRoot:s,featureFlag:c,logger:{warn:A=>process.stderr.write(`${A}
|
|
46
|
+
`)}});y.applied&&y.metadata&&(b.graphRetrieval=y.metadata)}catch(c){const p=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] graph retrieval hook failed: ${p}. Proceeding without enrichment.
|
|
47
|
+
`)}try{if(qa(e.args)){const{collectProjectEvidence:c}=await import("../evidence/collector.js"),p=a.selection.uiUxReview?.architectureDir,y=c({projectRoot:s,...p?{candidatePaths:[p],includeFallbackInventory:!0}:{}});(y.evidence.length>0||y.exclusions.length>0)&&(b.projectEvidence=y)}}catch(c){const p=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] project evidence collection failed: ${p}. Proceeding without local project evidence.
|
|
48
|
+
`)}if(l==="yoloop"||l==="yolo"){const c=yc(s,b.epics??{},b.stories??{},mc(o));c&&(b.storyWorktreeReadiness=c)}try{const c=await E.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"checkpoint-consume",operation:"consume"},async()=>{const{readAndConsumeCheckpoint:p}=await import("../checkpoint/index.js");return p(s)},async()=>{});c&&(b.implementCheckpoint=c)}catch(c){const p=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] checkpoint hook failed: ${p}. Proceeding without checkpoint.
|
|
49
|
+
`)}const Se=w?.licenseKey?new Vn({cacheDir:Wn,passphrase:w.licenseKey,strictReadOnly:x}):null,Z=o.trim();if(!Z&&Se){const c=await E.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>_c(Se),async()=>null);if(c)return E.complete(),{success:!0,instructions:c.instructions,metadata:c.metadata,exitCode:0}}const J=await Ii(L,w?.licenseKey,E);if(J.status!=="authenticated"){const c=J.status==="refresh-required",p=!c&&w&&!w.licenseKey?" This may be caused by a machine fingerprint change (e.g., hardware or hostname change).":"";try{const y=Pr(),A=xr(c?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",y);A&&process.stderr.write(Tr(A,y))}catch{}return{success:!1,error:c?"Authentication refresh required. Run: neocortex activate YOUR-LICENSE-KEY":`Not authenticated.${p} Visit https://neocortex.sh/portal/login to get your license key, then run: neocortex activate YOUR-LICENSE-KEY`,errorCode:c?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",exitCode:c?1:2}}const gt=b.config.project_id;try{await E.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Cs(s,b,L,J.token,gt,{refreshToken:()=>J.client.forceRefresh()}),async()=>0)}catch{}const wt=Ls(Z);if(wt&&!g)try{const c=await J.tierClient.preFlightCheck(wt);if(!c.allowed)return process.stderr.write(`[neocortex] ${c.message}
|
|
50
|
+
`),{success:!1,error:c.message??"Trigger not available on your plan",exitCode:1}}catch{}const ue=await Bc({args:Z,projectRoot:s,platformTarget:k,environment:e.environment??process.env,bootstrapper:e.runnerBootstrapper,effectAuthority:E});if(ue.attachToRequest&&(b.runnerBootstrap=ue.metadata),ue.warning&&process.stderr.write(`[Neocortex] ${ue.warning}
|
|
51
51
|
`),!ue.shouldContinue)return ue.error&&process.stderr.write(`[Neocortex] ${ue.error}
|
|
52
|
-
`),{success:!1,error:ue.error??"Runner auto-bootstrap required but failed.",errorCode:ue.errorCode,exitCode:ue.exitCode??1};if(ue.metadata.command==="runner"&&(ue.metadata.operation==="status"||ue.metadata.operation==="doctor"))try{const c=e.runnerObserver??
|
|
53
|
-
`),{success:!1,error:p,errorCode:c.code,metadata:{stateProjection:c,publicSafe:!0},exitCode:1}}O=c?.snapshot??
|
|
54
|
-
`),{success:!1,error:p,errorCode:c.code,metadata:{structuralProjection:{...c.publicDetails,publicSafe:!0}},exitCode:1}}throw c}if(!
|
|
55
|
-
`),{success:!1,error:c,errorCode:"EPIC_PROJECT_ID_REQUIRED",exitCode:1}}let Pe;try{Pe=I.execute({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>$==="create-epic"||$==="idea-diagnose"?Lo(s,Z,$):void 0,()=>{})}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const Nt=Pe?.key??($==="yolo"?Mo(s,Z,Te,O):void 0);if(e.privateExecutionBeta&&$==="create-epic"&&Pe){const c=Ht(s).operations[Pe.fingerprint],p=c?.epicId?x.epics[c.epicId]:void 0,m=g(p?.createEpicPlanningPhysical)?p.createEpicPlanningPhysical:void 0;c?.claimId&&c.epicId&&p&&m?.claimId===c.claimId&&(O={...O,epics:{...O.epics,[c.epicId]:p},stories:{...O.stories,...Object.fromEntries((Array.isArray(p.stories)?p.stories:[]).filter(A=>typeof A=="string"&&x.stories[A]?.epic_id===c.epicId).map(A=>[A,x.stories[A]]))}})}const rt=b?{schemaVersion:1,invocationId:I.invocationId,intent:I.intent,clientProjection:Ba(Vr.map(c=>({...c,count:1})))}:void 0;let K,ve,he;if(e.privateExecutionBeta&&$==="idea-research")try{const c=O.scope?.targetEpicId,p=c?O.epics[c]:void 0,m=g(p?.createEpicPlanningPhysical)?p.createEpicPlanningPhysical:void 0;if(!c||!m||typeof m.claimId!="string"||typeof m.receiptId!="string")throw new Error("planning-research-predecessor-unavailable");const A=z(s,".neocortex/state.json"),B=Vt(A);if(!B.isFile()||B.isSymbolicLink()||B.size>8*1024*1024)throw new Error("planning-research-state-unavailable");const ne=Fe(A),ce=JSON.parse(ne.toString("utf8")),re=Cr(ce,m.claimId,c),fe=g(ce)&&g(ce.epics)&&g(ce.epics[c])?ce.epics[c]:void 0,U=g(fe?.createEpicPlanningPhysical)?fe.createEpicPlanningPhysical:void 0;if(U?.receiptId!==m.receiptId||!v(U,m))throw new Error("planning-research-predecessor-drift");const Ie=[".neocortex/state.json",".neocortex/planning/planning.json",`.neocortex/planning/epic-${c}/idea.json`,`.neocortex/planning/epic-${c}/diagnosis.md`,`.neocortex/planning/epic-${c}/enriched-prompt.md`],Ue={...process.env};for(const me of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete Ue[me];for(const me of Ie){const $e=Vt(z(s,me));if(!$e.isFile()||$e.isSymbolicLink()||$e.size>8*1024*1024)throw new Error("planning-research-source-unavailable");const Xe=Ge("git",["show",`HEAD:${me}`],{cwd:s,env:Ue,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!Fe(z(s,me)).equals(Xe))throw new Error("planning-research-source-uncommitted")}ve={claimId:m.claimId,epicId:c,diagnosisReceiptId:re.diagnosisReceiptId,intakeRevision:re.intakeRevision,physicalAcceptanceReceiptId:m.receiptId,sourceStateSha256:Ne("sha256").update(ne).digest("hex")}}catch{return{success:!1,error:"private-execution-planning-predecessor-unavailable",errorCode:"private-execution-planning-predecessor-unavailable",exitCode:1}}if(e.privateExecutionBeta&&$==="generate-epic")try{const c=O.scope?.targetEpicId,p=c?O.epics[c]:void 0,m=g(p?.createEpicPlanningResearchPhysical)?p.createEpicPlanningResearchPhysical:void 0;if(!c||!m||typeof m.claimId!="string"||typeof m.receiptId!="string")throw new Error("planning-generation-predecessor-unavailable");const A=z(s,".neocortex/state.json"),B=Vt(A);if(!B.isFile()||B.isSymbolicLink()||B.size>8*1024*1024)throw new Error("planning-generation-state-unavailable");const ne=Fe(A),ce=JSON.parse(ne.toString("utf8")),re=_r(ce,m.claimId,c),fe=g(ce)&&g(ce.epics)&&g(ce.epics[c])?ce.epics[c]:void 0,U=g(fe?.createEpicPlanningResearchPhysical)?fe.createEpicPlanningResearchPhysical:void 0;if(U?.receiptId!==m.receiptId||!v(U,m))throw new Error("planning-generation-predecessor-drift");const Ie=[".neocortex/state.json",".neocortex/planning/planning.json",`.neocortex/planning/epic-${c}/idea.json`,`.neocortex/planning/epic-${c}/diagnosis.md`,`.neocortex/planning/epic-${c}/enriched-prompt.md`,`.neocortex/planning/epic-${c}/research.md`],Ue={...process.env};for(const me of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete Ue[me];for(const me of Ie){const $e=Vt(z(s,me));if(!$e.isFile()||$e.isSymbolicLink()||$e.size>8*1024*1024)throw new Error("planning-generation-source-unavailable");const Xe=Ge("git",["show",`HEAD:${me}`],{cwd:s,env:Ue,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!Fe(z(s,me)).equals(Xe))throw new Error("planning-generation-source-uncommitted")}he={claimId:m.claimId,epicId:c,diagnosisReceiptId:re.diagnosisReceiptId,researchReceiptId:re.researchReceiptId,intakeRevision:re.intakeRevision,physicalAcceptanceReceiptId:re.physicalAcceptanceReceiptId,sourceStateSha256:Ne("sha256").update(ne).digest("hex")}}catch{return{success:!1,error:"private-execution-planning-predecessor-unavailable",errorCode:"private-execution-planning-predecessor-unavailable",exitCode:1}}if(e.privateExecutionBeta)try{const{preflightPrivateCodexExecutor:c}=await import("../private-execution/codex-executor.js");K=await c(s)}catch(c){const p=c instanceof Error&&/^private-codex-[a-z-]+$/.test(c.message)?c.message:"private-codex-preflight-unavailable";return{success:!1,error:p,errorCode:p,exitCode:1}}const qe=K?{schemaVersion:1,hostKind:"codex-cli",hostVersion:K.hostVersion,sandboxProof:{schemaVersion:6,trust:"client-self-attested",credentialKind:"chatgpt-subscription",authIsolation:"passed",workspaceWrite:"passed",gitControlWriteDenied:"passed",gitLifecycleReadDenied:"passed",mcpIsolation:"passed",environmentIsolation:"passed",networkDenied:"passed",webSearchDisabled:"passed",observedAtMs:K.observedAtMs}}:void 0;let V;if($==="arch-plan"&&O.archPlan?.execution?.currentStageCommand==="generate-pacts"&&O.archPlan.execution.continuationState==="ask-user")try{if(V=Sr(s),!V)throw new Error("architecture-answers-required")}catch(c){const p=c instanceof Error&&/^architecture-answers-[a-z-]+$/.test(c.message)?c.message:"architecture-answers-failed";return{success:!1,error:p,errorCode:p,exitCode:1}}let ft;if($==="arch-plan"&&O.archPlan?.execution?.currentStageCommand==="generate-pacts"&&O.archPlan.execution.continuationState==="delegate"&&O.archPlan.execution.childStatus==="succeeded")try{if(ft=Sr(s),!ft||!v(O.archPlan.execution.pactAnswerReceipt,ft))throw new Error("architecture-answers-conflict")}catch{return{success:!1,error:"architecture-answers-conflict",errorCode:"architecture-answers-conflict",exitCode:1}}let ge,oe,ye;if(e.privateExecutionBeta&&$==="generate-pacts")try{const c=a.trim().match(/^\*?generate-pacts (P[1-9][0-9]{0,11})$/)?.[1],p=O.archPlan?.execution;if(oe=zi(s),!c||!p||p.currentStageCommand!=="generate-pacts"||p.continuationState!=="delegate"||p.targetEpicId!==c||!oe||!v(p.pactAnswerReceipt,oe.receipt))throw new Error("private-execution-pact-admission-unverified");const m=Ki(s,oe.answers.generateProvider);if(m.outcome!=="ready")throw new Error("private-execution-pact-admission-unverified");ge=m.writeSet,ye={schemaVersion:1,targetEpicId:c,graphRevision:oe.receipt.graphRevision,answersSha256:oe.receipt.answersSha256,specSha256:ge.specSha256,pathsSha256:ge.pathsSha256,endpointCount:ge.endpointCount,pathCount:ge.paths.length,publicSafe:!0}}catch{const c="private-execution-pact-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let Ve,ee;if(e.privateExecutionBeta&&$==="arch-ux-design")try{const c=a.trim().match(/^\*?arch-ux-design (P[1-9][0-9]{0,11})$/)?.[1],p=O.archPlan?.execution;if(!c||!p||p.currentStageCommand!=="arch-ux-design"||p.continuationState!=="delegate"||p.targetEpicId!==c||typeof p.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(p.graphRevision))throw new Error("private-execution-ux-admission-unverified");const{deriveUxWriteSet:m}=await import("../private-execution/ux-write-set.js");Ve=m(s,c),ee={schemaVersion:1,targetEpicId:c,graphRevision:p.graphRevision,adapterId:Ve.adapterId,authoritySha256:Ve.authoritySha256,pathsSha256:Ve.pathsSha256,screenCount:Ve.screenCount,pathCount:Ve.pathCount,publicSafe:!0}}catch{const c="private-execution-ux-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let mt,ze,ke;if(e.privateExecutionBeta&&$==="property-test")try{if(o.selection.positionals.length!==0||o.selection.operationId!==void 0||Object.keys(o.selection.options).length!==0)throw new Error("private-execution-property-admission-unverified");const{loadPropertyTestChoices:c}=await import("../private-execution/property-test-choices.js"),{propertyTestExecutionInput:p}=await import("../private-execution/property-test-plan.js"),m=c(s);if(!m)throw new Error("private-execution-property-admission-unverified");mt=m.choices,ze=m.plan,ke=p(m.plan)}catch{const c="private-execution-property-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let Qe;if($==="yoloop"&&!b&&!e.privateExecutionBeta)try{Qe=(e.hostCapacityProbe??ea)({platformTarget:k,env:M})}catch{Qe=void 0}let H={args:a,projectRoot:s.replace(Kt(),"~"),stateSnapshot:O,...V?{architectureAnswerReceipt:V}:{},...ye?{pactExecutionInput:ye}:{},...ee?{uxExecutionInput:ee}:{},...ke?{propertyTestExecutionInput:ke}:{},platformTarget:k,..._?{nativeHostAttestation:_}:{},...Qe?{hostCapacity:Qe}:{},...qe?{privateExecution:qe}:{},projectId:Te,inputEvidence:r,...d?{invocationRecovery:d}:{},idempotencyKey:Nt,registryVersion:dt,registryChecksum:st,compatibility:qn(),...e.releaseGate?{releaseGate:e.releaseGate}:{},...rt?{strictReadOnly:rt}:{}};const bn=Wt(H);if(!b&&e.inputSource&&e.inputSource!=="args"&&bn>=Wn)try{H={argsRef:(await Ma(I,"secondary-mutation",()=>xc(L,a,J.token,()=>J.client.forceRefresh()),async()=>{throw new Bt("readonly-physical-boundary-unsafe","boundary")})).argsRef,projectRoot:s.replace(Kt(),"~"),stateSnapshot:O,...V?{architectureAnswerReceipt:V}:{},platformTarget:k,..._?{nativeHostAttestation:_}:{},...Qe?{hostCapacity:Qe}:{},...qe?{privateExecution:qe}:{},projectId:Te,inputEvidence:r,...d?{invocationRecovery:d}:{},idempotencyKey:Nt,registryVersion:dt,registryChecksum:st,compatibility:qn(),...e.releaseGate?{releaseGate:e.releaseGate}:{},...rt?{strictReadOnly:rt}:{}}}catch(c){return c instanceof Bt?{success:!1,error:c.code,errorCode:c.code,exitCode:1}:{success:!1,error:`INVOKE_MATERIALIZATION_FAILED: ${c instanceof Error?c.message:String(c)}`,errorCode:"INVOKE_MATERIALIZATION_FAILED",exitCode:1}}let it;if($==="yolo"&&O.scope?.projectionMode==="yolo-story"){const c=O.scope?.targetStoryId,p=O.scope?.targetEpicId;if(!c||!p||!D||D.storyId!==c||D.epicId!==p)return{success:!1,error:"yolo-spec-envelope-target-mismatch",errorCode:"yolo-spec-envelope-target-mismatch",exitCode:1};try{let m=Wr(D);if(/\sbranchless-preparation\s*$/.test(a))H={...H,yoloSpecEnvelope:m};else{const{collectYoloChangeEvidence:A,reconcileYoloChangeEvidenceLease:B}=await import("../yolo/change-evidence-collector.js");it=await B({projectRoot:s,storyId:c,epicId:p}),it.repair==="applied"&&(m=Wr(D));const ne=A({projectRoot:s,defaultBranch:O.config.default_branch,expectedHeadSha:m.sourceRevision.headSha,storyId:c,epicId:p,reconciliation:it});H={...H,yoloSpecEnvelope:m,yoloChangeEvidence:ne}}H=Co(H,{projectRoot:s,supported:Y})}catch(m){const{yoloChangeEvidenceDiagnostic:A}=await import("../yolo/change-evidence-collector.js"),B=A(m),ne=Gr(m,!0);return{success:!1,error:ne,errorCode:ne,...B?{metadata:{yoloChangeEvidence:B}}:{},exitCode:1}}}try{const c=rr(H);if($==="migrate-state"&&c.degraded)return{success:!1,error:"state_migration_payload_degraded",errorCode:"state_migration_payload_degraded",exitCode:1};H=c.body,c.degraded?wi(H,c.telemetry):Lc(H)}catch(c){if(c instanceof zn||c instanceof Jn)return wi(H,c.telemetry),process.stderr.write(`[Neocortex] ${c.message}
|
|
56
|
-
`),{success:!1,error:c.message,errorCode:c.code,metadata:{invokePayload:c.telemetry},exitCode:1};throw c}if($==="yolo"&&H.yoloSpecEnvelope)try{const c=
|
|
52
|
+
`),{success:!1,error:ue.error??"Runner auto-bootstrap required but failed.",errorCode:ue.errorCode,exitCode:ue.exitCode??1};if(ue.metadata.command==="runner"&&(ue.metadata.operation==="status"||ue.metadata.operation==="doctor"))try{const c=e.runnerObserver??To;b.runnerOperationalStatus=await c(ue.metadata.operation,{projectRoot:s,env:e.environment??process.env,effectAuthority:E})}catch{}let O;try{const c=Io(Z,b);if(c&&!c.ok){const p=`${c.code}: structural projection failed closed; select a valid target or repair the dependency DAG.`;return process.stderr.write(`${p}
|
|
53
|
+
`),{success:!1,error:p,errorCode:c.code,metadata:{stateProjection:c,publicSafe:!0},exitCode:1}}O=c?.snapshot??kr(Z,b),hn(Z)==="migrate-state"&&(O={...O,migrationAuthority:_o(s)})}catch(c){if(c instanceof Ro)return{success:!1,error:c.reasonCode,errorCode:c.reasonCode,exitCode:1};if(c instanceof Nr){const p=`${c.code}: structural projection failed closed; select a valid target or repair the dependency DAG.`;return process.stderr.write(`${p}
|
|
54
|
+
`),{success:!1,error:p,errorCode:c.code,metadata:{structuralProjection:{...c.publicDetails,publicSafe:!0}},exitCode:1}}throw c}if(!x)try{const{openNativeAgentPrivateStore:c,resolveNativeAgentPrivateRuntimePaths:p}=await import("../continuity/native-agent-store.js"),y=p(s);if(jt(y.databasePath)){const A=await c(s);try{const B=A.store.listRecentNativeAgentDispatches(20);B.length>0&&(O.nativeAgentDispatches=B)}finally{A.store.close()}}}catch{}const $=hn(Z);let xe=!1;if($==="arch-plan"&&!x&&O.archPlan?.execution===void 0){const c=Ki(o);if(c)try{if(!Object.hasOwn(b.epics,c)||!Object.hasOwn(O.epics,c))throw new Error("architecture-root-epic-binding-invalid");const p=Yt(s,c);O={...O,archPlan:{execution:{schemaVersion:1,owner:"root",currentStageCommand:"arch-prd",continuationState:"delegate",evidencePolicy:"v2-required",targetEpicId:c,graphRevision:p,graphSource:"committed-epic-v1",acceptedStages:[]}}},xe=!0}catch{return{success:!1,error:"architecture-root-epic-binding-invalid",errorCode:"architecture-root-epic-binding-invalid",exitCode:1}}}if(($==="arch-plan"||$?.startsWith("arch-")||$==="generate-pacts"||$==="update-memory")&&O.archPlan?.execution?.graphSource==="committed-epic-v1")try{const c=O.archPlan.execution;if(typeof c.targetEpicId!="string"||typeof c.graphRevision!="string"||c.graphRevision!==Yt(s,c.targetEpicId))throw new Error("architecture-root-epic-binding-invalid")}catch{return{success:!1,error:"architecture-root-epic-binding-invalid",errorCode:"architecture-root-epic-binding-invalid",exitCode:1}}const Te=gt;if(($==="create-epic"||$==="idea-diagnose")&&!Te){const c='EPIC_PROJECT_ID_REQUIRED: run `neocortex-client invoke --args "*migrate-project-id"` and retry the planning command. No repository checkout or database credentials are required.';return process.stderr.write(`${c}
|
|
55
|
+
`),{success:!1,error:c,errorCode:"EPIC_PROJECT_ID_REQUIRED",exitCode:1}}let Pe;try{Pe=E.execute({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>$==="create-epic"||$==="idea-diagnose"?Da(s,Z,$):void 0,()=>{})}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const Nt=Pe?.key??($==="yolo"?ja(s,Z,Te,O):void 0);if(e.privateExecutionBeta&&$==="create-epic"&&Pe){const c=Ht(s).operations[Pe.fingerprint],p=c?.epicId?b.epics[c.epicId]:void 0,y=h(p?.createEpicPlanningPhysical)?p.createEpicPlanningPhysical:void 0;c?.claimId&&c.epicId&&p&&y?.claimId===c.claimId&&(O={...O,epics:{...O.epics,[c.epicId]:p},stories:{...O.stories,...Object.fromEntries((Array.isArray(p.stories)?p.stories:[]).filter(A=>typeof A=="string"&&b.stories[A]?.epic_id===c.epicId).map(A=>[A,b.stories[A]]))}})}const rt=x?{schemaVersion:1,invocationId:E.invocationId,intent:E.intent,clientProjection:$o(Br.map(c=>({...c,count:1})))}:void 0;let K,ve,he;if(e.privateExecutionBeta&&$==="idea-research")try{const c=O.scope?.targetEpicId,p=c?O.epics[c]:void 0,y=h(p?.createEpicPlanningPhysical)?p.createEpicPlanningPhysical:void 0;if(!c||!y||typeof y.claimId!="string"||typeof y.receiptId!="string")throw new Error("planning-research-predecessor-unavailable");const A=z(s,".neocortex/state.json"),B=Vt(A);if(!B.isFile()||B.isSymbolicLink()||B.size>8*1024*1024)throw new Error("planning-research-state-unavailable");const ne=Fe(A),ce=JSON.parse(ne.toString("utf8")),re=_r(ce,y.claimId,c),fe=h(ce)&&h(ce.epics)&&h(ce.epics[c])?ce.epics[c]:void 0,U=h(fe?.createEpicPlanningPhysical)?fe.createEpicPlanningPhysical:void 0;if(U?.receiptId!==y.receiptId||!C(U,y))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`],$e={...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 $e[me];for(const me of Ee){const He=Vt(z(s,me));if(!He.isFile()||He.isSymbolicLink()||He.size>8*1024*1024)throw new Error("planning-research-source-unavailable");const Xe=Be("git",["show",`HEAD:${me}`],{cwd:s,env:$e,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!Fe(z(s,me)).equals(Xe))throw new Error("planning-research-source-uncommitted")}ve={claimId:y.claimId,epicId:c,diagnosisReceiptId:re.diagnosisReceiptId,intakeRevision:re.intakeRevision,physicalAcceptanceReceiptId:y.receiptId,sourceStateSha256:Ne("sha256").update(ne).digest("hex")}}catch{return{success:!1,error:"private-execution-planning-predecessor-unavailable",errorCode:"private-execution-planning-predecessor-unavailable",exitCode:1}}if(e.privateExecutionBeta&&$==="generate-epic")try{const c=O.scope?.targetEpicId,p=c?O.epics[c]:void 0,y=h(p?.createEpicPlanningResearchPhysical)?p.createEpicPlanningResearchPhysical:void 0;if(!c||!y||typeof y.claimId!="string"||typeof y.receiptId!="string")throw new Error("planning-generation-predecessor-unavailable");const A=z(s,".neocortex/state.json"),B=Vt(A);if(!B.isFile()||B.isSymbolicLink()||B.size>8*1024*1024)throw new Error("planning-generation-state-unavailable");const ne=Fe(A),ce=JSON.parse(ne.toString("utf8")),re=Rr(ce,y.claimId,c),fe=h(ce)&&h(ce.epics)&&h(ce.epics[c])?ce.epics[c]:void 0,U=h(fe?.createEpicPlanningResearchPhysical)?fe.createEpicPlanningResearchPhysical:void 0;if(U?.receiptId!==y.receiptId||!C(U,y))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`],$e={...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 $e[me];for(const me of Ee){const He=Vt(z(s,me));if(!He.isFile()||He.isSymbolicLink()||He.size>8*1024*1024)throw new Error("planning-generation-source-unavailable");const Xe=Be("git",["show",`HEAD:${me}`],{cwd:s,env:$e,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!Fe(z(s,me)).equals(Xe))throw new Error("planning-generation-source-uncommitted")}he={claimId:y.claimId,epicId:c,diagnosisReceiptId:re.diagnosisReceiptId,researchReceiptId:re.researchReceiptId,intakeRevision:re.intakeRevision,physicalAcceptanceReceiptId:re.physicalAcceptanceReceiptId,sourceStateSha256:Ne("sha256").update(ne).digest("hex")}}catch{return{success:!1,error:"private-execution-planning-predecessor-unavailable",errorCode:"private-execution-planning-predecessor-unavailable",exitCode:1}}if(e.privateExecutionBeta)try{const{preflightPrivateCodexExecutor:c}=await import("../private-execution/codex-executor.js");K=await c(s)}catch(c){const p=c instanceof Error&&/^private-codex-[a-z-]+$/.test(c.message)?c.message:"private-codex-preflight-unavailable";return{success:!1,error:p,errorCode:p,exitCode:1}}const qe=K?{schemaVersion:1,hostKind:"codex-cli",hostVersion:K.hostVersion,sandboxProof:{schemaVersion:6,trust:"client-self-attested",credentialKind:"chatgpt-subscription",authIsolation:"passed",workspaceWrite:"passed",gitControlWriteDenied:"passed",gitLifecycleReadDenied:"passed",mcpIsolation:"passed",environmentIsolation:"passed",networkDenied:"passed",webSearchDisabled:"passed",observedAtMs:K.observedAtMs}}:void 0;let V;if($==="arch-plan"&&O.archPlan?.execution?.currentStageCommand==="generate-pacts"&&O.archPlan.execution.continuationState==="ask-user")try{if(V=vr(s),!V)throw new Error("architecture-answers-required")}catch(c){const p=c instanceof Error&&/^architecture-answers-[a-z-]+$/.test(c.message)?c.message:"architecture-answers-failed";return{success:!1,error:p,errorCode:p,exitCode:1}}let ft;if($==="arch-plan"&&O.archPlan?.execution?.currentStageCommand==="generate-pacts"&&O.archPlan.execution.continuationState==="delegate"&&O.archPlan.execution.childStatus==="succeeded")try{if(ft=vr(s),!ft||!C(O.archPlan.execution.pactAnswerReceipt,ft))throw new Error("architecture-answers-conflict")}catch{return{success:!1,error:"architecture-answers-conflict",errorCode:"architecture-answers-conflict",exitCode:1}}let ge,ae,ye;if(e.privateExecutionBeta&&$==="generate-pacts")try{const c=o.trim().match(/^\*?generate-pacts (P[1-9][0-9]{0,11})$/)?.[1],p=O.archPlan?.execution;if(ae=Ji(s),!c||!p||p.currentStageCommand!=="generate-pacts"||p.continuationState!=="delegate"||p.targetEpicId!==c||!ae||!C(p.pactAnswerReceipt,ae.receipt))throw new Error("private-execution-pact-admission-unverified");const y=Qi(s,ae.answers.generateProvider);if(y.outcome!=="ready")throw new Error("private-execution-pact-admission-unverified");ge=y.writeSet,ye={schemaVersion:1,targetEpicId:c,graphRevision:ae.receipt.graphRevision,answersSha256:ae.receipt.answersSha256,specSha256:ge.specSha256,pathsSha256:ge.pathsSha256,endpointCount:ge.endpointCount,pathCount:ge.paths.length,publicSafe:!0}}catch{const c="private-execution-pact-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let Ve,ee;if(e.privateExecutionBeta&&$==="arch-ux-design")try{const c=o.trim().match(/^\*?arch-ux-design (P[1-9][0-9]{0,11})$/)?.[1],p=O.archPlan?.execution;if(!c||!p||p.currentStageCommand!=="arch-ux-design"||p.continuationState!=="delegate"||p.targetEpicId!==c||typeof p.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(p.graphRevision))throw new Error("private-execution-ux-admission-unverified");const{deriveUxWriteSet:y}=await import("../private-execution/ux-write-set.js");Ve=y(s,c),ee={schemaVersion:1,targetEpicId:c,graphRevision:p.graphRevision,adapterId:Ve.adapterId,authoritySha256:Ve.authoritySha256,pathsSha256:Ve.pathsSha256,screenCount:Ve.screenCount,pathCount:Ve.pathCount,publicSafe:!0}}catch{const c="private-execution-ux-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let mt,ze,ke;if(e.privateExecutionBeta&&$==="property-test")try{if(a.selection.positionals.length!==0||a.selection.operationId!==void 0||Object.keys(a.selection.options).length!==0)throw new Error("private-execution-property-admission-unverified");const{loadPropertyTestChoices:c}=await import("../private-execution/property-test-choices.js"),{propertyTestExecutionInput:p}=await import("../private-execution/property-test-plan.js"),y=c(s);if(!y)throw new Error("private-execution-property-admission-unverified");mt=y.choices,ze=y.plan,ke=p(y.plan)}catch{const c="private-execution-property-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let Qe;if($==="yoloop"&&!x&&!e.privateExecutionBeta)try{Qe=(e.hostCapacityProbe??to)({platformTarget:k,env:M})}catch{Qe=void 0}let H={args:o,projectRoot:s.replace(Kt(),"~"),stateSnapshot:O,...V?{architectureAnswerReceipt:V}:{},...ye?{pactExecutionInput:ye}:{},...ee?{uxExecutionInput:ee}:{},...ke?{propertyTestExecutionInput:ke}:{},platformTarget:k,..._?{nativeHostAttestation:_}:{},...Qe?{hostCapacity:Qe}:{},...qe?{privateExecution:qe}:{},projectId:Te,inputEvidence:n,...d?{invocationRecovery:d}:{},idempotencyKey:Nt,registryVersion:dt,registryChecksum:st,compatibility:zn(),...e.releaseGate?{releaseGate:e.releaseGate}:{},...rt?{strictReadOnly:rt}:{}};const xn=Wt(H);if(!x&&e.inputSource&&e.inputSource!=="args"&&xn>=Gn)try{H={argsRef:(await Vo(E,"secondary-mutation",()=>Oc(L,o,J.token,()=>J.client.forceRefresh()),async()=>{throw new Bt("readonly-physical-boundary-unsafe","boundary")})).argsRef,projectRoot:s.replace(Kt(),"~"),stateSnapshot:O,...V?{architectureAnswerReceipt:V}:{},platformTarget:k,..._?{nativeHostAttestation:_}:{},...Qe?{hostCapacity:Qe}:{},...qe?{privateExecution:qe}:{},projectId:Te,inputEvidence:n,...d?{invocationRecovery:d}:{},idempotencyKey:Nt,registryVersion:dt,registryChecksum:st,compatibility:zn(),...e.releaseGate?{releaseGate:e.releaseGate}:{},...rt?{strictReadOnly:rt}:{}}}catch(c){return c instanceof Bt?{success:!1,error:c.code,errorCode:c.code,exitCode:1}:{success:!1,error:`INVOKE_MATERIALIZATION_FAILED: ${c instanceof Error?c.message:String(c)}`,errorCode:"INVOKE_MATERIALIZATION_FAILED",exitCode:1}}let it;if($==="yolo"&&O.scope?.projectionMode==="yolo-story"){const c=O.scope?.targetStoryId,p=O.scope?.targetEpicId;if(!c||!p||!D||D.storyId!==c||D.epicId!==p)return{success:!1,error:"yolo-spec-envelope-target-mismatch",errorCode:"yolo-spec-envelope-target-mismatch",exitCode:1};try{let y=Gr(D);if(/\sbranchless-preparation\s*$/.test(o))H={...H,yoloSpecEnvelope:y};else{const{collectYoloChangeEvidence:A,reconcileYoloChangeEvidenceLease:B}=await import("../yolo/change-evidence-collector.js");it=await B({projectRoot:s,storyId:c,epicId:p}),it.repair==="applied"&&(y=Gr(D));const ne=A({projectRoot:s,defaultBranch:O.config.default_branch,expectedHeadSha:y.sourceRevision.headSha,storyId:c,epicId:p,reconciliation:it});H={...H,yoloSpecEnvelope:y,yoloChangeEvidence:ne}}H=_a(H,{projectRoot:s,supported:Y})}catch(y){const{yoloChangeEvidenceDiagnostic:A}=await import("../yolo/change-evidence-collector.js"),B=A(y),ne=Fr(y,!0);return{success:!1,error:ne,errorCode:ne,...B?{metadata:{yoloChangeEvidence:B}}:{},exitCode:1}}}try{const c=ir(H);if($==="migrate-state"&&c.degraded)return{success:!1,error:"state_migration_payload_degraded",errorCode:"state_migration_payload_degraded",exitCode:1};H=c.body,c.degraded?Ai(H,c.telemetry):Vc(H)}catch(c){if(c instanceof Jn||c instanceof Kn)return Ai(H,c.telemetry),process.stderr.write(`[Neocortex] ${c.message}
|
|
56
|
+
`),{success:!1,error:c.message,errorCode:c.code,metadata:{invokePayload:c.telemetry},exitCode:1};throw c}if($==="yolo"&&H.yoloSpecEnvelope)try{const c=Wr({projectRoot:s,storyId:H.yoloSpecEnvelope.storyId,epicId:H.yoloSpecEnvelope.epicId,inputSha256:n.sha256,collectedAt:H.yoloSpecEnvelope.collectedAt});if(c.envelopeSha256!==H.yoloSpecEnvelope.envelopeSha256)throw new Error("yolo-spec-envelope-stale");if(H.yoloChangeEvidence){const{collectYoloChangeEvidence:p}=await import("../yolo/change-evidence-collector.js"),y=p({projectRoot:s,defaultBranch:O.config.default_branch,expectedHeadSha:c.sourceRevision.headSha,storyId:c.storyId,epicId:c.epicId,...it?{reconciliation:it}:{}});if(y.pathsSha256!==H.yoloChangeEvidence.pathsSha256||y.baseSha!==H.yoloChangeEvidence.baseSha)throw new Error("yolo-change-evidence-stale")}}catch(c){const p=c instanceof Error&&c.message==="yolo-change-evidence-stale"?c.message:"yolo-spec-envelope-stale",{yoloChangeEvidenceDiagnostic:y}=await import("../yolo/change-evidence-collector.js"),A=y(c);return{success:!1,error:p,errorCode:p,...A?{metadata:{yoloChangeEvidence:A}}:{},exitCode:1}}const N=$==="arch-plan"?H.stateSnapshot.archPlan?.execution:void 0;let Lt;if(N?.owner==="root"&&(N.currentStageCommand==="arch-prd"||N.currentStageCommand==="arch-architecture"||N.currentStageCommand==="arch-fitness-functions"||N.currentStageCommand==="arch-api-contracts"||N.currentStageCommand==="generate-pacts"||N.currentStageCommand==="arch-api-integrations"||N.currentStageCommand==="arch-database"||N.currentStageCommand==="arch-security"||N.currentStageCommand==="arch-design-system"||N.currentStageCommand==="arch-ux-design"||N.currentStageCommand==="arch-performance"||N.currentStageCommand==="arch-testing"||N.currentStageCommand==="arch-infrastructure"||N.currentStageCommand==="arch-review"||N.currentStageCommand==="update-memory")&&(N.continuationState==="delegate"||N.continuationState==="advance"||N.currentStageCommand==="update-memory"&&N.continuationState==="complete"||N.currentStageCommand==="arch-review"&&N.continuationState==="ask-user"||N.currentStageCommand==="generate-pacts"&&N.continuationState==="ask-user"))try{const c=Fe(z(s,".neocortex","state.json"),"utf8"),p=JSON.parse(c),y=h(p.archPlan)?p.archPlan.execution:void 0;if(xe?y!==void 0||!h(p.epics)||!Object.hasOwn(p.epics,String(N.targetEpicId))||N.graphSource!=="committed-epic-v1"||N.graphRevision!==Yt(s,String(N.targetEpicId)):!C(Sn(y),N))throw new Error("architecture-root-state-binding-invalid");if(Lt=Ne("sha256").update(c).digest("hex"),V&&V.stateSha256!==Lt)throw new Error("architecture-root-state-binding-invalid");if(N.currentStageCommand==="update-memory"&&N.childStatus==="succeeded"){const A=N.continuationState==="complete"&&Array.isArray(N.acceptedStages)?{...N,continuationState:"delegate",acceptedStages:N.acceptedStages.slice(0,Ir(N))}:N;if(!Ft(N.terminalMemoryCheckpoint,N)||!C(N.terminalMemoryCheckpoint,Dn(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 Un("invoke-query",()=>ur(L,H,J.token,{refreshToken:()=>J.client.forceRefresh()}));if($==="yoloop"&&!x&&f.ok&&f.data?.metadata?.errorCode==="YOLOOP_SPEC_NOT_READY"&&f.data.metadata.hint==="yoloop-session-invalidated"){const c=O.scope?.targetEpicId;if(!c)return{success:!1,error:"yoloop-causal-reconciliation-target-invalid",errorCode:"YOLOOP_CAUSAL_RECONCILIATION_BLOCKED",exitCode:1};const p=await As({projectRoot:s,snapshot:b,targetEpicId:c,originalInputSha256:n.sha256,canonicalInputSha256:d?.canonicalSha256??n.sha256});if(p.outcome!=="applied")return{success:!1,error:p.reasonCode,errorCode:"YOLOOP_CAUSAL_RECONCILIATION_BLOCKED",metadata:{yoloopCausalRecovery:p},exitCode:1};try{const{readYoloopForRequest:y}=await import("../yoloop/invoke-hooks.js"),A=await y(o,s);if(!A)throw new Error("yoloop-causal-reconciliation-postimage-unverified");H=ir({...H,stateSnapshot:{...H.stateSnapshot,yoloop:A}}).body}catch(y){const A=Bi(y);return{success:!1,error:A,errorCode:"YOLOOP_CAUSAL_RECONCILIATION_BLOCKED",metadata:{yoloopCausalRecovery:{outcome:"blocked",reasonCode:A,retryCount:0,publicSafe:!0}},exitCode:1}}f=await Un("invoke-query",()=>ur(L,H,J.token,{refreshToken:()=>J.client.forceRefresh()}))}let nn;if(x&&f.ok)try{if(g){const p=f.data?.metadata;if(p&&["stateUpdate","stateMutated","yoloopStateUpdate","continuityStateUpdate","checkpoint","schedulerStateUpdate","quotaCacheUpdate","projectIdentityMigration","epicClaim","gitLifecycleGraphAuthority"].some(A=>p[A]!==void 0))throw new Bt("readonly-response-conflict")}const c=f.data?.metadata.strictReadOnly;Wo(E,c),g&&Jo(f.data?.metadata.strictDiagnose,i,f.data?.instructions??""),nn=c.security}catch(c){const p=c instanceof Bt?c.code:"readonly-receipt-mismatch";return{success:!1,error:p,errorCode:p,exitCode:1}}if(!f.ok&&f.status===426){const c=f.errorBody,p=c?.upgrade_command??"npm install -g @ornexus/neocortex@latest",y=c?.min_version??"unknown";return process.stderr.write(`
|
|
57
57
|
`),process.stderr.write(`==================================================
|
|
58
58
|
`),process.stderr.write(` UPGRADE REQUIRED
|
|
59
59
|
`),process.stderr.write(`==================================================
|
|
60
60
|
`),process.stderr.write(`
|
|
61
61
|
Your Neocortex version (${Pt}) is no longer supported.
|
|
62
|
-
`),process.stderr.write(` Minimum required: ${
|
|
62
|
+
`),process.stderr.write(` Minimum required: ${y}
|
|
63
63
|
|
|
64
64
|
`),process.stderr.write(` Run this command to update:
|
|
65
65
|
|
|
@@ -68,11 +68,12 @@ The C04 barrier did not open within the bounded wait. Return this resumable rece
|
|
|
68
68
|
`),process.stderr.write(` After updating, re-run your command.
|
|
69
69
|
`),process.stderr.write(`==================================================
|
|
70
70
|
|
|
71
|
-
`),{success:!1,error:`UPGRADE_REQUIRED: Client version ${Pt} is below minimum ${
|
|
72
|
-
`),
|
|
73
|
-
`),{success:!1,error:p,errorCode:p,exitCode:1}}if(!Z&&f.data.metadata?.mode==="menu"&&Se&&await
|
|
74
|
-
`),{success:!1,error:p,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}catch(c){if(f.data.metadata?.stateMutationReason==="inline-yolo-materialized-synthetic-story"){const p=c instanceof Error?c.message:String(c),
|
|
75
|
-
`),{success:!1,error:
|
|
71
|
+
`),{success:!1,error:`UPGRADE_REQUIRED: Client version ${Pt} is below minimum ${y}. Run: ${p}`,exitCode:3}}if(!f.ok||!f.data){const c=f.status===401?2:(f.status===429||f.status>=500,1),p=Ac(f),y=Ba(p);if(y)return process.stderr.write(`[Neocortex] ${y.error}
|
|
72
|
+
`),y;try{if(p){const A=Pr(),B=xr(p,A);B&&process.stderr.write(Tr(B,A))}}catch{}return{success:!1,error:Je(f.error??"Unknown error from server",kt),...p?{errorCode:p}:{},...f.compatibility?{metadata:{compatibility:f.compatibility}}:{},exitCode:c}}const gr=Ua(f.data);if(gr)return E.complete(nn),gr;let Re;try{Re=e.privateExecutionBeta&&$==="create-epic"&&Pe?Ht(s).operations[Pe.fingerprint]:void 0}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const rn=Re?.planningProtocol==="root-staged-v1"&&typeof Re.claimId=="string"&&typeof Re.epicId=="string"&&ro(f.data,{claimId:Re.claimId,epicId:Re.epicId,...h(b.epics[Re.epicId]?.createEpicPlanningMemoryPhysical)?{memoryReceiptId:b.epics[Re.epicId].createEpicPlanningMemoryPhysical.receiptId}:{}});if(e.privateExecutionBeta&&!rn&&!no(f.data))return{success:!1,error:"private-execution-public-envelope-invalid",errorCode:"private-execution-public-envelope-invalid",exitCode:1};if(Lt&&N&&f.data.metadata?.mode==="arch-plan"&&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 E.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>ic({projectRoot:s,sourceStateSha256:Lt,requestExecution:N,initialBinding:xe,answerReceipt:V,pactRecordedReceipt:ft,metadata:f.data.metadata}),async()=>{throw new Error("architecture-root-writeback-effect-skipped")})}catch(c){const p=c instanceof Error&&/^architecture-root-[a-z-]+$/.test(c.message)?c.message:"architecture-root-writeback-failed";return process.stderr.write(`[Neocortex] ${p}. Root stage instruction was not released.
|
|
73
|
+
`),{success:!1,error:p,errorCode:p,exitCode:1}}if(!Z&&f.data.metadata?.mode==="menu"&&Se&&await E.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>Rc(Se,f.data.instructions,f.data.metadata),async()=>{}).catch(()=>{}),f.data.metadata&&await E.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"tier-cache",operation:"update"},()=>J.tierClient.updateQuotaFromResponse(f.data.metadata),async()=>{}).catch(()=>{}),f.data.metadata?.stateMutated===!0)try{const c=await E.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>{const{persistMigratedStateFromResponse:p}=await import("../yoloop/invoke-hooks.js");return p(f.data.metadata,s)},async()=>({applied:!1,blocking:!1,reasonCode:"state-writeback-effect-skipped"}));if(c.blocking){const p=`STATE_WRITEBACK_BLOCKED: ${c.reasonCode}. Canonical state was not replaced.`;return process.stderr.write(`${p}
|
|
74
|
+
`),{success:!1,error:p,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}catch(c){if(f.data.metadata?.stateMutationReason==="inline-yolo-materialized-synthetic-story"){const p=c instanceof Error?c.message:String(c),y=`STATE_WRITEBACK_BLOCKED: inline-yolo persistence failed (${Je(p,kt)}).`;return process.stderr.write(`${y}
|
|
75
|
+
`),{success:!1,error:y,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}const on=f.data.metadata?.yoloopStoryWorktreeFallback;if(h(on)&&typeof on.reasonCode=="string"&&/^story-worktree-[a-z0-9-]{1,64}$/.test(on.reasonCode)&&process.stderr.write(`[yoloop] v4 story-worktree plan not used: ${on.reasonCode}.
|
|
76
|
+
`),f.data.metadata?.gitLifecycleGraphAuthority)try{await E.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},()=>ha(s,f.data.metadata.gitLifecycleGraphAuthority),async()=>{throw new Error("git-lifecycle-graph-authority-effect-skipped")})}catch(c){const p=c instanceof Error&&/^git-lifecycle-/.test(c.message)?c.message:"git-lifecycle-graph-authority-persist-failed";return process.stderr.write(`[Neocortex] ${p}. Graph authority was not persisted; no YOLO checkpoint instruction was released.
|
|
76
77
|
`),{success:!1,error:p,errorCode:"GIT_LIFECYCLE_GRAPH_AUTHORITY_INVALID",exitCode:1}}if(f.data.metadata?.mode==="error"&&f.data.metadata?.errorCode==="CLIENT_UPGRADE_REQUIRED")return process.stderr.write(`
|
|
77
78
|
`),process.stderr.write(`==================================================
|
|
78
79
|
`),process.stderr.write(` YOLOOP CLIENT UPGRADE REQUIRED
|
|
@@ -88,55 +89,55 @@ The C04 barrier did not open within the bounded wait. Return this resumable rece
|
|
|
88
89
|
`),process.stderr.write(` After upgrading, re-run your yoloop command.
|
|
89
90
|
`),process.stderr.write(`==================================================
|
|
90
91
|
|
|
91
|
-
`),{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 p=(f.data.metadata.yoloopStateUpdate.operations??[]).some(
|
|
92
|
-
`),{success:!1,error:A,errorCode:A,exitCode:1}}}catch(
|
|
93
|
-
`),{success:!1,error:A,errorCode:A,exitCode:1}}}}if(f.data.metadata?.continuityStateUpdate)try{const c=await
|
|
92
|
+
`),{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 p=(f.data.metadata.yoloopStateUpdate.operations??[]).some(y=>y.type==="rollover_session");try{const y=await E.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(y&&y.ok===!1){const A=y.reasonCodes[0]??"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED";return process.stderr.write(`[Neocortex] ${A}. No yoloop continuation instructions were released.
|
|
93
|
+
`),{success:!1,error:A,errorCode:A,exitCode:1}}}catch(y){if(p){const A=y instanceof Error?y.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.
|
|
94
|
+
`),{success:!1,error:A,errorCode:A,exitCode:1}}}}if(f.data.metadata?.continuityStateUpdate)try{const c=await E.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"continuity-store",operation:"update"},async()=>{const{persistContinuityFromResponse:p}=await import("../continuity/invoke-hooks.js");return p(f.data.metadata,s)},async()=>({ok:!0,reasonCodes:[]}));if(!c.ok){const p=c.reasonCodes.join(",");return process.stderr.write(`[Neocortex] continuity persistence failed: ${p}. No continuity mutation was committed.
|
|
94
95
|
`),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${p}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}}catch(c){const p=c instanceof Error?c.message:String(c);return process.stderr.write(`[Neocortex] continuity persistence hook failed: ${p}. No continuity mutation was committed.
|
|
95
96
|
`),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${Je(p,kt)}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}if(f.data.metadata?.tier_changed){const c=f.data.metadata.current_tier;try{await J.client.forceRefresh()?(await J.tierClient.invalidateTierCache(),process.stderr.write(`[Neocortex] Token atualizado automaticamente para tier ${c}
|
|
96
97
|
`)):process.stderr.write(`[Neocortex] Seu tier foi atualizado para ${c}! Execute "neocortex activate" para obter um token atualizado.
|
|
97
98
|
`)}catch{process.stderr.write(`[Neocortex] Seu tier foi atualizado para ${c}! Execute "neocortex activate" para obter um token atualizado.
|
|
98
|
-
`)}}let te,
|
|
99
|
+
`)}}let te,fr=!1;if(e.privateExecutionBeta&&!rn)try{if(!K||!f.data.metadata?.privateExecution||!Te||f.data.metadata?.mode!=="yolo"&&f.data.metadata?.mode!=="step"&&f.data.metadata?.mode!=="pipeline"&&f.data.metadata?.mode!=="create-epic"&&f.data.metadata?.mode!=="utility"&&f.data.metadata?.mode!=="tech-debt"&&f.data.metadata?.mode!=="ui-ux-review"||typeof f.data.metadata.stepId!="string")throw new Error("private-execution-descriptor-unavailable");const{consumePrivateExecutionDelivery:c,privateExecutionStateSnapshotSha256:p}=await import("../private-execution/delivery.js"),{preflightPrivateCodexExecutor:y,runPrivateCodexStep:A}=await import("../private-execution/codex-executor.js"),B=f.data.metadata.mode==="yolo",ne=f.data.metadata.mode==="ui-ux-review"&&f.data.metadata.resolvedTrigger==="ui-ux-review",ce=f.data.metadata.mode==="create-epic",re=h(f.data.metadata.privateExecution)?f.data.metadata.privateExecution:void 0,fe=h(re?.binding)?re.binding:void 0,U=ce&&f.data.metadata.resolvedTrigger==="create-epic"&&fe?.writeSetId==="idea-diagnosis-v1"&&f.data.metadata.stepId==="step-acd455ed";if(ce&&!U)throw new Error("private-execution-planning-root-protocol-required");const Ee=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="idea-diagnose"||U,$e=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="idea-research",me=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="generate-epic",He=ce||Ee;if($e&&!ve||me&&!he)throw new Error("private-execution-planning-predecessor-unavailable");const Xe=f.data.metadata.mode==="utility"&&f.data.metadata.resolvedTrigger==="sync-openapi"||f.data.metadata.mode==="utility"&&f.data.metadata.resolvedTrigger==="chaos-plan"||S&&f.data.metadata.mode==="tech-debt"&&f.data.metadata.resolvedTrigger==="tech-debt",Ce=f.data.metadata.mode==="step"&&(f.data.metadata.resolvedTrigger==="arch-prd"||f.data.metadata.resolvedTrigger==="arch-architecture"||f.data.metadata.resolvedTrigger==="arch-fitness-functions"||f.data.metadata.resolvedTrigger==="arch-api-contracts"||f.data.metadata.resolvedTrigger==="arch-api-integrations"||f.data.metadata.resolvedTrigger==="arch-database"||f.data.metadata.resolvedTrigger==="arch-security"||f.data.metadata.resolvedTrigger==="arch-design-system"||f.data.metadata.resolvedTrigger==="arch-performance"||f.data.metadata.resolvedTrigger==="arch-testing"||f.data.metadata.resolvedTrigger==="arch-infrastructure"||f.data.metadata.resolvedTrigger==="arch-review"||f.data.metadata.resolvedTrigger==="update-memory")?f.data.metadata.resolvedTrigger:void 0,yt=Ce!==void 0,Pn=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",ot=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="generate-pacts",Et=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="arch-ux-design",It=f.data.metadata.mode==="utility"&&f.data.metadata.resolvedTrigger==="property-test",kn=S?"tech-debt":f.data.metadata.resolvedTrigger==="chaos-plan"?"chaos-plan":"sync-openapi",mr=S?"tech-debt-registry-v1":kn==="chaos-plan"?"chaos-quarterly-v1":"sync-openapi-contract-v1",Ye=O.archPlan?.execution,cn=Ye?.targetEpicId,sn=Ye?.graphRevision;if(yt&&(Ye?.currentStageCommand!==Ce||typeof cn!="string"||!/^P[1-9][0-9]{0,11}$/.test(cn)||typeof sn!="string"||!/^[a-f0-9]{64}$/.test(sn)))throw new Error("private-execution-architecture-admission-unverified");if(ot&&(!ye||!ge||!ae||Ye?.currentStageCommand!=="generate-pacts"||Ye.continuationState!=="delegate"||Ye.targetEpicId!==ye.targetEpicId||Ye.graphRevision!==ye.graphRevision||!C(Ye.pactAnswerReceipt,ae.receipt)))throw new Error("private-execution-pact-admission-unverified");if(Et&&(!ee||!Ve||Ye?.currentStageCommand!=="arch-ux-design"||Ye.continuationState!=="delegate"||Ye.targetEpicId!==ee.targetEpicId||Ye.graphRevision!==ee.graphRevision))throw new Error("private-execution-ux-admission-unverified");if(It&&(!ke||!mt||!ze||f.data.metadata.stepId!=="step-a8ce5c64"))throw new Error("private-execution-property-admission-unverified");let yr;if(ot){const{planPactToolchainManifest:oe,preparePactToolchainCandidate:le}=await import("../private-execution/pact-toolchain.js");try{oe(s,ae.answers.generateProvider),yr=le(s,ae.answers.generateProvider)}catch(W){if(W.message!=="pact-toolchain-manifest-unsupported")throw W}}let At,se,On;const ie=f.data.metadata.gitLifecycleGraphAuthority,bt=f.data.metadata.privateExecutionRootAction;let Ze;if(B){if(!ie||typeof ie.storyId!="string"||typeof ie.graphRevision!="string"||typeof ie.executionBranch!="string")throw new Error("private-execution-graph-unavailable");if(Ze=ie.storyId,bt?.action==="prepare-epic-checkout"){const{parsePrivateExecutionDescriptor:T}=await import("../private-execution/delivery.js"),{prepareDirectYoloSetup:Oe}=await import("../git/direct-yolo-checkpoint.js"),{acceptDirectYoloSetupCheckpoint:St}=await import("../git/direct-yolo-checkpoint.js"),{capturePrivateYoloCleanHead:Ge,recordPrivateYoloCleanBaseline:we}=await import("../private-execution/clean-baseline.js"),Ae=T(f.data.metadata.privateExecution,{projectId:Te,commandId:"yolo",stepId:f.data.metadata.stepId,graphRevision:ie.graphRevision,inputSha256:n.sha256,hostKind:"codex-cli",hostVersion:K.hostVersion}),ct=await J.client.getToken();if(!ct)throw new Error("private-execution-auth-unavailable");if(!await vs(L,{leaseId:Ae.leaseId,...Ae.binding},ct))throw new Error("private-execution-setup-lease-cancel-unverified");const Mt=Ge(s),dn=await Oe({projectRoot:s,storyId:bt.storyId});if(!dn.ok)throw new Error("private-execution-root-setup-denied");await we(s,dn.value,Mt);const{ensurePrivateYoloIsolatedSession:xt}=await import("../private-execution/isolated-session.js");await xt(s,bt.storyId,ie.graphRevision,e.privateExecutionWorkspaceParent);const Tt=await St({projectRoot:s,storyId:bt.storyId});if(!Tt.ok)throw new Error(`private-execution-root-setup-checkpoint-denied:${Tt.reasonCode}`);te={schemaVersion:1,outcome:"setup-accepted",executorOutcome:"not-run-root-only",setup:Tt.value,publicSafe:!0};const Nn=En(f.data.instructions,{...f.data.metadata,...f.compatibility?{compatibility:f.compatibility}:{}});return E.complete(nn),{success:!0,instructions:`# Setup do branch validado
|
|
99
100
|
|
|
100
|
-
O root confirmou o checkpoint C01 no branch do \xE9pico. Reexecute o mesmo YOLO para avan\xE7ar \xE0 pr\xF3xima etapa.`,metadata:{...
|
|
101
|
+
O root confirmou o checkpoint C01 no branch do \xE9pico. Reexecute o mesmo YOLO para avan\xE7ar \xE0 pr\xF3xima etapa.`,metadata:{...Nn.metadata,privateExecutionReceipt:te},exitCode:0}}let oe;try{oe=Be("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(oe!==ie.executionBranch)throw new Error("private-execution-execution-branch-mismatch");const le=mn(s,{required:!0}),W=typeof ie.epicId=="string"?le.epics[ie.epicId]:void 0,j=h(W?.branch_lease)?W.branch_lease:void 0;if(!W||W.graph_revision!==ie.graphRevision||!j||j.ownerStoryId!==ie.storyId||typeof j.expiresAt!="string"||!Number.isFinite(Date.parse(j.expiresAt))||Date.parse(j.expiresAt)<=Date.now())throw new Error("private-execution-writer-lease-unavailable")}else if(f.data.metadata.mode==="step"&&(f.data.metadata.resolvedTrigger==="research"||f.data.metadata.resolvedTrigger==="write-spec"||f.data.metadata.resolvedTrigger==="create-tasks"||f.data.metadata.resolvedTrigger==="implement")||f.data.metadata.mode==="pipeline"&&f.data.metadata.resolvedTrigger==="exec"||ce&&f.data.metadata.resolvedTrigger==="create-epic"||ne||Ee||$e||me||Xe||yt||ot||Et||It){if(!He&&!$e&&!me&&!Xe&&!ne&&!yt&&!ot&&!Et&&!It&&typeof f.data.metadata.storyId!="string")throw new Error("private-execution-descriptor-unavailable")}else throw new Error("private-execution-descriptor-unavailable");if(B){const{ensurePrivateYoloIsolatedSession:oe,reconcilePrivateYoloIsolatedSession:le}=await import("../private-execution/isolated-session.js");if(bt?.action==="checkpoint-epic-story")await le(s,Ze,ie.graphRevision);else{const W=await oe(s,Ze,ie.graphRevision,e.privateExecutionWorkspaceParent),j=await y(W.workspace.workspacePath);if(j.hostVersion!==K.hostVersion)throw new Error("private-codex-version-drift");K=j}}if(Date.now()-K.observedAtMs>2e4){const oe=await y(K.projectRoot);if(oe.hostVersion!==K.hostVersion)throw new Error("private-codex-version-drift");K=oe}const Er=await J.client.getToken();if(!Er)throw new Error("private-execution-auth-unavailable");const We=He?f.data.metadata.epicClaim:void 0;if(He&&(!We||typeof We.claimId!="string"||typeof We.epicId!="string"))throw new Error("private-execution-descriptor-unavailable");if(He){if(!Pe)throw new Error("private-execution-epic-claim-admission-unverified");E.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>ti(s,Pe.fingerprint,We.claimId,We.epicId,U?"root-staged-v1":void 0),()=>{}),fr=!0;const{preparePrivateYoloIsolatedWorkspace:oe,PRIVATE_EPIC_PENDING_SIDECAR:le}=await import("../private-execution/isolated-workspace.js"),W=e.privateExecutionWorkspaceParent??z(Kt(),".local","share","neocortex","private-epic-workspaces");e.privateExecutionWorkspaceParent||qt(W,{recursive:!0,mode:448}),At=oe(s,W,!0),On=Ne("sha256").update(Fe(z(s,le))).digest("hex");const j=await y(At.workspacePath);if(j.hostVersion!==K.hostVersion)throw new Error("private-codex-version-drift");K=j}else if(!B&&!ne){const{preparePrivateYoloIsolatedWorkspace:oe}=await import("../private-execution/isolated-workspace.js"),le=e.privateExecutionWorkspaceParent??z(Kt(),".local","share","neocortex","private-step-workspaces");if(e.privateExecutionWorkspaceParent||qt(le,{recursive:!0,mode:448}),se=oe(s,le,$e||me),Xe||yt||ot||Et||It){if(!pe)throw new Error("private-execution-project-snapshot-unverified");const{assertPrivateProjectStepBaseline:j}=await import("../private-execution/isolated-workspace.js");j(se,pe)}const W=await y(se.workspacePath);if(W.hostVersion!==K.hostVersion)throw new Error("private-codex-version-drift");K=W}const at=await c(f.data.metadata.privateExecution,{projectId:Te,commandId:B?"yolo":ce?"create-epic":yt?Ce:ot?"generate-pacts":Et?"arch-ux-design":It?"property-test":Xe?kn:f.data.metadata.mode==="pipeline"?"exec":f.data.metadata.resolvedTrigger,stepId:f.data.metadata.stepId,...B?{graphRevision:ie.graphRevision}:{...He?{claimId:We.claimId,epicId:We.epicId,...Ee?{writeSetId:"idea-diagnosis-v1"}:{}}:$e?{claimId:ve.claimId,epicId:ve.epicId,diagnosisReceiptId:ve.diagnosisReceiptId,intakeRevision:ve.intakeRevision,physicalAcceptanceReceiptId:ve.physicalAcceptanceReceiptId,writeSetId:"idea-research-v1"}:me?{claimId:he.claimId,epicId:he.epicId,diagnosisReceiptId:he.diagnosisReceiptId,researchReceiptId:he.researchReceiptId,intakeRevision:he.intakeRevision,physicalAcceptanceReceiptId:he.physicalAcceptanceReceiptId,writeSetId:"generate-epic-v1"}:Xe?{writeSetId:mr}:ne?{format:a.selection.uiUxReview?.json===!0?"json":"markdown"}:yt?{targetEpicId:cn,graphRevision:sn,writeSetId:Pn}:ot?{targetEpicId:ye.targetEpicId,graphRevision:ye.graphRevision,answersSha256:ye.answersSha256,specSha256:ye.specSha256,pathsSha256:ye.pathsSha256,endpointCount:ye.endpointCount,pathCount:ye.pathCount}:Et?{targetEpicId:ee.targetEpicId,graphRevision:ee.graphRevision,adapterId:ee.adapterId,authoritySha256:ee.authoritySha256,pathsSha256:ee.pathsSha256,screenCount:ee.screenCount,pathCount:ee.pathCount}:It?{prdPath:ke.prdPath,prdSha256:ke.prdSha256,planSha256:ke.planSha256,pathsSha256:ke.pathsSha256,aggregateCount:ke.aggregateCount,invariantCount:ke.invariantCount,pathCount:ke.pathCount,language:ke.language,numRuns:ke.numRuns}:{storyId:f.data.metadata.storyId},stateSnapshotSha256:p(O)},inputSha256:n.sha256,hostKind:"codex-cli",hostVersion:K.hostVersion},oe=>Ss(L,{...oe},Er));if(ne){const{parsePrivateExecutionDescriptor:oe}=await import("../private-execution/delivery.js"),le=oe(f.data.metadata.privateExecution);if(le.schemaVersion!==11||le.binding.commandId!=="ui-ux-review"||le.binding.format!==(a.selection.uiUxReview?.json===!0?"json":"markdown"))throw new Error("private-execution-report-binding-unverified");const{storePrivateUiUxReviewReport:W}=await import("../private-execution/private-report-store.js");te={schemaVersion:1,outcome:"report-stored",report:await W({projectRoot:s,material:at,format:le.binding.format,sha256:le.materialSha256}),publicSafe:!0}}else if(bt?.action==="checkpoint-epic-story"){const{runPrivateYoloRootCheckpoint:oe}=await import("../private-execution/root-checkpoint.js");te={...await oe(s,bt)}}else{const oe=Ee?`${at}
|
|
101
102
|
|
|
102
103
|
Private P01 handoff (local only):
|
|
103
|
-
The durable reserved epic ID is ${
|
|
104
|
-
|
|
104
|
+
The durable reserved epic ID is ${We.epicId}. Complete only the diagnosis for this exact ID. Write exactly .neocortex/planning/epic-${We.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.
|
|
105
|
+
`:$e?`${at}
|
|
105
106
|
|
|
106
107
|
Private P02 handoff (local only):
|
|
107
108
|
The admitted epic is ${ve.epicId}. Research only this exact diagnosed epic. Write exactly .neocortex/planning/epic-${ve.epicId}/research.md and its transition in .neocortex/planning/planning.json. Do not write state.json, Git controls, another epic, or P03 artifacts; do not auto-continue. The root will independently review and seal the research candidate.
|
|
108
|
-
`:me?`${
|
|
109
|
+
`:me?`${at}
|
|
109
110
|
|
|
110
111
|
Private P03 handoff (local only):
|
|
111
112
|
The admitted epic is ${he.epicId}. Generate exactly docs/epics/epic-${he.epicId}.md, 1 to 24 contiguous docs/stories/${he.epicId}.NN.story.md files (01 through 24), and the matching transition in .neocortex/planning/planning.json. The 1 to 24 range is a safety maximum, not a required count. Derive the implementation story count from the accepted research scope; keep later epic lifecycle gates out of implementation stories. Epic frontmatter must contain its exact id and stories_count matching the files, and the document must contain the exact section heading ## Stories. Story frontmatter must use exactly one canonical epic_id field for this epic, with status backlog; do not emit the legacy epic alias. Each story needs the exact heading ## Acceptance Criteria and Given/When/Then criteria. In planning.json preserve all other entries and fields; for this epic set status generated, append only the current generation step after the two accepted predecessors, set completed_at to a non-null ISO timestamp, and add output_files.epic plus the ordered output_files.stories list. Keep a valid ISO last_scan. This is completion of the candidate index only, not root QA, memory or epic completion. Do not write state.json, Git controls, another epic, or subsequent-stage artifacts; do not auto-continue. The root will independently review and seal the generated candidate.
|
|
112
|
-
`:yt?(await import("../private-execution/isolated-admission.js")).appendPrivateArchitectureHandoff(
|
|
113
|
+
`:yt?(await import("../private-execution/isolated-admission.js")).appendPrivateArchitectureHandoff(at,Ce,Pn,Sr(O.archPlan?.execution?.nonUiScopeReceipt)?"non-ui":"all"):ot?`${at}
|
|
113
114
|
|
|
114
115
|
Private A03.5 handoff (local only):
|
|
115
|
-
${JSON.stringify({consumer:
|
|
116
|
+
${JSON.stringify({consumer:ae.answers.consumer,provider:ae.answers.provider,matchersAggressive:ae.answers.matchersAggressive,generateProvider:ae.answers.generateProvider,brokerConfigured:ae.answers.brokerUrl!==null,allowedPaths:ge.paths})}
|
|
116
117
|
Read docs/api/openapi.yaml. Write only the listed new test files. Do not write package files, CI, Git, graph, or tracked configuration. Use describe and it from vitest for every consumer and provider test, plus expect for consumers. Consumer Pact imports are PactV3 and, only when matchersAggressive is true, MatchersV3. When false, use exact literal values and no matcher helpers or matchingRules. Provider imports Verifier. Do not import Node builtins, filesystem/path helpers or other packages; consumer application imports are allowed only for an existing tracked local client. Each consumer must use a literal HTTP method and concrete path in withRequest, willRespondWith and executeTest with actual response assertions. If no application client exists, label the direct fetch test a mock-only scaffold without claiming compatibility. If specifying a Pact output directory, use the literal pacts or pact-files without subdirectories. Never embed a broker URL. When brokerConfigured is false, verify only local pact files through literal pactUrls and never add broker configuration or token fields. When true, read PACT_BROKER_URL at runtime. Provider base URL may use PACT_PROVIDER_BASE_URL; missing runtime inputs must fail rather than skip. No network, install, provider startup, Git or QA authority is granted to the model.
|
|
117
|
-
`:
|
|
118
|
+
`:Et?`${at}
|
|
118
119
|
|
|
119
120
|
Private A08 handoff (local only):
|
|
120
121
|
${JSON.stringify({targetEpicId:ee.targetEpicId,graphRevision:ee.graphRevision,adapterId:ee.adapterId,approvedScreens:Ve.screens,allowedPaths:Ve.paths})}
|
|
121
122
|
Write only the approved paths. Keep synthetic fixtures and the canonical approved-story manifest. No Git, graph, QA or configuration effects.
|
|
122
|
-
`:
|
|
123
|
+
`:It?`${at}
|
|
123
124
|
|
|
124
125
|
Private property-test handoff (local only):
|
|
125
126
|
${JSON.stringify({language:ze.language,numRuns:ze.numRuns,aggregates:ze.aggregates.map(j=>({name:j.name,implementationFile:j.implementationFile,testFile:j.testFile,invariantCount:j.invariantCount}))})}
|
|
126
127
|
Read the PRD and implementation files inside this isolated clone. Write exactly the listed test files. Do not edit the PRD, state, Git, QA records or any other path. Scaffolds with unfinished assertions must fail explicitly; do not use skipped or todo tests. The root will write the confirmed PRD configuration and independently assess QA.
|
|
127
|
-
`:
|
|
128
|
+
`:at;let le=oe;if(B){const{readPrivateYoloFrozenWriteSet:j}=await import("../private-execution/clean-baseline.js"),{appendPrivateYoloFrozenHandoff:T}=await import("../private-execution/frozen-handoff.js"),Oe=await j(s,Ze,ie.executionBranch,ie.graphRevision);le=T(oe,Oe);const{resumePrivateYoloIsolatedSession:St}=await import("../private-execution/isolated-session.js"),Ge=await St(s,Ze,ie.graphRevision),we=_n(s,{epicAware:!0}).stories[Ze],Ae=O.stories[Ze];if(!we||!Ae||we.status!==Ae.status||JSON.stringify(we.steps_completed)!==JSON.stringify(Ae.steps_completed))throw new Error("private-execution-phase-snapshot-drift");const ct=Be("git",["rev-parse","HEAD"],{cwd:s,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();le+=`
|
|
128
129
|
Root physical dispatch observations (data, not phase completion):
|
|
129
|
-
`+JSON.stringify({storyId:Ze,graphRevision:ie.graphRevision,sourceHeadSha:ct,privateSnapshotSha:
|
|
130
|
+
`+JSON.stringify({storyId:Ze,graphRevision:ie.graphRevision,sourceHeadSha:ct,privateSnapshotSha:Ge.snapshotSha,effectiveStatus:we.status,hostKind:"codex-cli",hostVersion:K.hostVersion})+`
|
|
130
131
|
Use these observed revisions and runtime facts; do not infer Git metadata or substitute an invented revision.
|
|
131
|
-
`}const W=await A(le,K,{requireWorkspaceEffect:!0,...e.onPrivateExecutionWorkspaceFailure===void 0?{}:{onWorkspaceEffectFailure:e.onPrivateExecutionWorkspaceFailure},...e.privateExecutionModel===void 0?{}:{model:e.privateExecutionModel},...B?{expectedExecutionBranch:ie.executionBranch}:At?{expectedExecutionBranch:At.executionBranch}:se?{expectedExecutionBranch:se.executionBranch}:{}});if(B){const{admitPrivateYoloIsolatedSessionStep:j}=await import("../private-execution/isolated-session.js"),T=await j(s,Ze,ie.graphRevision);let Oe;if(f.data.metadata.stepId===
|
|
132
|
+
`}const W=await A(le,K,{requireWorkspaceEffect:!0,...e.onPrivateExecutionWorkspaceFailure===void 0?{}:{onWorkspaceEffectFailure:e.onPrivateExecutionWorkspaceFailure},...e.privateExecutionModel===void 0?{}:{model:e.privateExecutionModel},...B?{expectedExecutionBranch:ie.executionBranch}:At?{expectedExecutionBranch:At.executionBranch}:se?{expectedExecutionBranch:se.executionBranch}:{}});if(B){const{admitPrivateYoloIsolatedSessionStep:j}=await import("../private-execution/isolated-session.js"),T=await j(s,Ze,ie.graphRevision);let Oe;if(f.data.metadata.stepId===io){const Ge=f.data.metadata.mutationQaFeature;if(!Ge)throw new Error("private-execution-mutation-qa-authority-unavailable");if(!Ge.enabled)Oe={schemaVersion:1,status:"skipped-server-authority",publicSafe:!0};else{let we,Ae;try{const ct=T.session.workspace.workspacePath,Mt=`sha:${T.session.workspace.baseSha}`,{planMutationQa:dn}=await import("./mutation-qa.js"),xt=dn(ct,Mt);if(xt.headSha!==T.session.snapshotSha)throw new Error("private-execution-mutation-qa-snapshot-drift");let Tt="not-run";if(xt.outcome==="ready"){const{runAndRecordMutationQa:Ln}=await import("./mutation-qa-checkpoint.js");if(Tt=Ln(ct,Mt,xt.planSha256).result.outcome,Tt==="skipped-host-isolation-unavailable")throw new Error("private-execution-mutation-qa-host-isolation-unavailable")}const{classifyMutationQaGate:Nn}=await import("./mutation-qa-gate.js");if(we=Nn(ct,Mt,xt.planSha256),we.followUpDebtRequired){const{recordMutationQaFollowUpDebt:Ln}=await import("./mutation-qa-checkpoint.js");Ae=Ln(ct,Mt,xt.planSha256,we.status,Tt,s)}const{resumePrivateYoloIsolatedSession:qi}=await import("../private-execution/isolated-session.js");if((await qi(s,Ze,ie.graphRevision)).snapshotSha!==T.session.snapshotSha)throw new Error("private-execution-mutation-qa-snapshot-drift")}catch{throw new Error("private-execution-mutation-qa-unverified")}if(we.blocksLocalQa||!we.safeToContinueLocalQa&&!Ae)throw new Error(`private-execution-mutation-qa-${we.status}`);Oe={...we,...Ae?{followUpDebt:{status:"recorded",owner:Ae.owner,severity:Ae.severity,reasonCode:Ae.reasonCode,planSha256:Ae.planSha256,publicSafe:!0}}:{}}}}const St={schemaVersion:1,outcome:T.admission.outcome,sequence:T.session.sequence,snapshotSha:T.session.snapshotSha,patchSha256:T.admission.patchSha256,changedPathCount:T.admission.changedPaths.length};te={...W,isolation:St,...Oe?{mutationQa:Oe}:{}}}else if(At){const{admitPrivateEpicClaimWorkspace:j,admitPrivateIdeaDiagnosisWorkspace:T}=await import("../private-execution/isolated-admission.js"),Oe=Ee?T(At,We.claimId,We.epicId,Pe.fingerprint,On,a.selection.positionals.join(" ").replace(/^[-:–—]\s+/,"")):j(At,We.claimId,We.epicId,Pe.fingerprint,On);te={...W,isolation:{schemaVersion:1,outcome:Oe.outcome,baseSha:Oe.baseSha,patchSha256:Oe.patchSha256,changedPathCount:Oe.changedPaths.length}}}else if(se&&$e){const{admitPrivateIdeaResearchWorkspace:j}=await import("../private-execution/isolated-admission.js"),T=j(se,ve.claimId,ve.epicId,ve.diagnosisReceiptId,ve.intakeRevision,ve.sourceStateSha256);te={...W,isolation:{schemaVersion:1,outcome:T.outcome,baseSha:T.baseSha,patchSha256:T.patchSha256,changedPathCount:T.changedPaths.length}}}else if(se&&me){const{admitPrivateGenerateEpicWorkspace:j}=await import("../private-execution/isolated-admission.js"),T=j(se,he.claimId,he.epicId,he.diagnosisReceiptId,he.researchReceiptId,he.intakeRevision,he.sourceStateSha256);te={...W,isolation:{schemaVersion:1,outcome:T.outcome,baseSha:T.baseSha,patchSha256:T.patchSha256,changedPathCount:T.changedPaths.length}}}else if(se&&ot){const{admitPrivatePactWorkspace:j}=await import("../private-execution/isolated-admission.js"),{inspectPactToolchain:T}=await import("../private-execution/pact-toolchain.js"),{verifyPactConsumerRuntime:Oe}=await import("../private-execution/pact-consumer-runtime.js"),St=ae.answers.generateProvider,Ge=j(se,ye.targetEpicId,ye.graphRevision,ae.receipt,ge,yr),we=T(s,St),Ae=Oe(s,ge,St);te={...W,isolation:{schemaVersion:1,outcome:Ge.outcome,baseSha:Ge.baseSha,patchSha256:Ge.patchSha256,changedPathCount:Ge.changedPaths.length,consumerBindingCandidateCount:Ge.consumerBindingCandidateCount,consumerScaffoldCount:Ge.consumerScaffoldCount,toolchain:we,consumerRuntime:Ae}}}else if(se&&Et){const{admitPrivateUxWorkspace:j}=await import("../private-execution/isolated-admission.js"),T=j(se,ee.targetEpicId,ee.graphRevision,Ve);te={...W,isolation:{schemaVersion:1,outcome:T.outcome,baseSha:T.baseSha,patchSha256:T.patchSha256,changedPathCount:T.changedPaths.length}}}else if(se&&It){const{admitPrivatePropertyTestWorkspace:j}=await import("../private-execution/isolated-admission.js"),T=j(se,mt,ze);te={...W,isolation:{schemaVersion:1,outcome:T.outcome,baseSha:T.baseSha,patchSha256:T.patchSha256,changedPathCount:T.changedPaths.length,checkpointAccepted:!1,qaAccepted:!1,rootNextAction:"property-semantic-review-required"}}}else if(se&&yt){const{admitPrivateArchitectureStageWorkspace:j}=await import("../private-execution/isolated-admission.js"),T=j(se,Ce,Pn,cn,sn);te={...W,isolation:{schemaVersion:1,outcome:T.outcome,baseSha:T.baseSha,patchSha256:T.patchSha256,changedPathCount:T.changedPaths.length}}}else if(se&&Xe){const{admitPrivateProjectStepWorkspace:j}=await import("../private-execution/isolated-admission.js"),T=j(se,kn,mr);te={...W,isolation:{schemaVersion:1,outcome:T.outcome,baseSha:T.baseSha,patchSha256:T.patchSha256,changedPathCount:T.changedPaths.length}}}else if(se){const{admitPrivateStateBoundStepWorkspace:j}=await import("../private-execution/isolated-admission.js"),T=j(se,f.data.metadata.storyId);te={...W,isolation:{schemaVersion:1,outcome:T.outcome,baseSha:T.baseSha,patchSha256:T.patchSha256,changedPathCount:T.changedPaths.length}}}else te={...W}}}catch(c){const p=c instanceof Error&&/^(private-execution|private-codex)-[a-z-]+$/.test(c.message)?c.message:"private-execution-unverified";return{success:!1,error:p,errorCode:p,exitCode:1}}let Tn;if(rn&&h(f.data.metadata.planningRootContinuation)&&f.data.metadata.planningRootContinuation.planningComplete===!0)try{if(!Re?.claimId||!Re.epicId||!Te)throw new Error("missing-reservation");const c=wr(s,Re.claimId,Re.epicId);if(f.data.metadata.planningRootContinuation.memoryReceiptId!==c.receiptId)throw new Error("memory-receipt-conflict");const p=_n(s,{verifyPlanningGeneration:!0}),y=p.epics[Re.epicId];if(!h(y?.createEpicPlanningMemoryPhysical)||y.createEpicPlanningMemoryPhysical.receiptId!==c.receiptId)throw new Error("memory-recheck-failed");const A={config:{project_id:Te},epics:{[Re.epicId]:y},stories:Object.fromEntries((Array.isArray(y.stories)?y.stories:[]).map(ne=>[ne,p.stories[ne]])),epic_id_ledger:p.epic_id_ledger};if(!await E.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Di(L,J.token,{claimId:Re.claimId,projectId:Te,epicId:Re.epicId,status:"materialized",planningCheckpoint:{memoryReceiptId:c.receiptId,snapshot:A}},{refreshToken:()=>J.client.forceRefresh()}),async()=>!1))throw new Error("acknowledgement-unavailable");Tn={schemaVersion:1,acknowledged:!0,claimId:c.claimId,epicId:c.epicId,memoryReceiptId:c.receiptId,publicSafe:!0}}catch{return{success:!1,error:"planning-root-materialization-unavailable",errorCode:"planning-root-materialization-unavailable",exitCode:1}}const an=En(f.data.instructions,{...f.data.metadata,...f.compatibility?{compatibility:f.compatibility}:{}}),Dt=te?.isolation,Yi=an.metadata?.resolvedTrigger==="property-test"&&Dt!==null&&typeof Dt=="object"&&!Array.isArray(Dt)&&Dt.outcome==="admitted-unverified"&&Dt.checkpointAccepted===!1&&Dt.rootNextAction==="property-semantic-review-required";if(Pe&&!fr&&!rn&&f.data.metadata?.mode!=="error")try{const c=f.data.metadata?.epicClaim;if(!c||typeof c!="object"||Array.isArray(c))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const p=c;if(p.outcome!=="reserved"||typeof p.claimId!="string"||typeof p.epicId!="string")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");E.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>ti(s,Pe.fingerprint,p.claimId,p.epicId),()=>{})}catch{}return E.complete(nn),{success:!0,instructions:te?te.outcome==="checkpoint-validated"?`# Checkpoint da story validado
|
|
132
133
|
|
|
133
134
|
O root registrou o commit e a valida\xE7\xE3o f\xEDsica no branch do epic.`:te.outcome==="setup-accepted"?`# Setup do branch validado
|
|
134
135
|
|
|
135
136
|
O root confirmou o checkpoint C01 no branch do \xE9pico. Reexecute o mesmo YOLO para avan\xE7ar \xE0 pr\xF3xima etapa.`:te.outcome==="report-stored"?`# Relat\xF3rio privado salvo
|
|
136
137
|
|
|
137
|
-
Consulte o caminho local em metadata.privateExecutionReceipt.report.path. Nenhum agente foi executado ou projeto alterado.`:
|
|
138
|
+
Consulte o caminho local em metadata.privateExecutionReceipt.report.path. Nenhum agente foi executado ou projeto alterado.`:Yi?"# Property-test: candidato admitido, QA pendente\n\nO root deve inspecionar os arquivos locais, executar `neocortex-client property-qa review-plan --project-root . --format json` e comparar cada invariante do PRD com a implementa\xE7\xE3o e sua asser\xE7\xE3o. Somente uma revis\xE3o root independente, registrada fora do projeto e enviada por stdin a `property-qa review-accept --authorize-review`, pode autorizar o aceite; esse comando repete a execu\xE7\xE3o positiva e a falha causal no sandbox. Consulte `property-qa review-status` para revalidar o recibo. Se o toolchain ou a evid\xEAncia n\xE3o forem suportados, pare sem declarar QA aprovado. O agente privado n\xE3o recebe autoridade de revis\xE3o, Git ou checkpoint.":`# Execu\xE7\xE3o privada conclu\xEDda; valida\xE7\xE3o f\xEDsica pendente
|
|
138
139
|
|
|
139
|
-
O executor Codex retornou sem erro. Nenhum checkpoint ou aprova\xE7\xE3o da story foi emitido.`:an.instructions,metadata:te?{...an.metadata,privateExecutionReceipt:te}:{...an.metadata,...
|
|
140
|
+
O executor Codex retornou sem erro. Nenhum checkpoint ou aprova\xE7\xE3o da story foi emitido.`:an.instructions,metadata:te?{...an.metadata,privateExecutionReceipt:te}:{...an.metadata,...Tn?{planningMaterialization:Tn}:{}},exitCode:0}}function Ls(e){const[t]=e.trim().split(/\s+/,1);return t?/^@?epic-[a-z0-9][a-z0-9._-]*$/i.test(t)?"epic":hn(t):null}const Wi="Provide exactly one invoke input source: --args <string>, --stdin, or --args-file <path>.",Ds=`
|
|
140
141
|
neocortex-client invoke - Send orchestration request to server
|
|
141
142
|
|
|
142
143
|
Usage:
|
|
@@ -207,12 +208,12 @@ Safety:
|
|
|
207
208
|
Jobs console is Plane B/local-only: no hosted server call for raw output, no server-held stream, no raw persistence, and stdin requires explicit local confirmation.
|
|
208
209
|
Jobs, goal and loop watch use serverHeldStream=false and foreground local SQLite polling of public processing summaries only.
|
|
209
210
|
Unresolved targets disable polling with public reason codes; there is no all-jobs fallback.
|
|
210
|
-
`.trim();function
|
|
211
|
-
`);return}i.write(JSON.stringify({instructions:
|
|
212
|
-
`);return}const
|
|
213
|
-
`),r
|
|
214
|
-
`)}async function
|
|
215
|
-
`),0;let t;try{t=
|
|
216
|
-
`),1;throw
|
|
217
|
-
`),1):(await
|
|
218
|
-
`),i.exitCode}if(
|
|
211
|
+
`.trim();function Ms(e){return e.includes("--help")||e.includes("-h")||e.includes("help")}function je(e,t,i,r){return new In("INVOCATION_MALFORMED_INPUT",t,e,i,r)}function Ot(e){return je("missing-input-value",`${e} requires a value. ${Wi}`)}function js(e){try{if(!Xi(e).isFile())throw je("missing-input-value","--args-file must point to a readable UTF-8 text file.","args-file");return Fe(e)}catch(t){throw t instanceof In?t:je("missing-input-value","--args-file could not be read as UTF-8 text. Check the path and permissions.","args-file")}}function Vs(){try{if(process.stdin.isTTY)throw je("missing-input-value","--stdin requires piped UTF-8 text, for example: neocortex-client invoke --stdin < synthetic.story.md","stdin");return Fe(0)}catch(e){throw e instanceof In?e:je("missing-input-value","--stdin could not be read as UTF-8 text. Pipe command text into stdin and retry.","stdin")}}function Bs(e,t={}){let i,r=!1,o,n,a="plain",d=!1,s,l,m=!1,S=!1,u;for(let P=0;P<e.length;P++){const k=e[P];switch(k){case"--args":{const _=e[++P];if(_===void 0)throw Ot("--args");if(i!==void 0)throw je("multiple-input-sources","Provide --args only once. Use one explicit invoke input source.","args");i=_;break}case"--stdin":if(r)throw je("multiple-input-sources","Provide --stdin only once. Use one explicit invoke input source.","stdin");r=!0;break;case"--args-file":{const _=e[++P];if(_===void 0)throw Ot("--args-file");if(o!==void 0)throw je("multiple-input-sources","Provide --args-file only once. Use one explicit invoke input source.","args-file");o=_;break}case"--project-root":{const _=e[++P];if(_===void 0)throw Ot("--project-root");n=_;break}case"--format":{const _=e[++P];if(_===void 0)throw Ot("--format");if(_!=="json"&&_!=="plain")throw je("unexpected-cli-token","--format accepts only json or plain.");a=_;break}case"--watch":d=!0;break;case"--server-url":{const _=e[++P];if(_===void 0)throw Ot("--server-url");s=_;break}case"--platform-target":{const _=e[++P];if(_===void 0)throw Ot("--platform-target");l=_;break}case"--strict-read-only":m=!0;break;case"--private-execution-beta":S=!0;break;case"--private-execution-model":{const _=e[++P];if(_===void 0)throw Ot("--private-execution-model");if(u!==void 0||!/^gpt-[a-z0-9][a-z0-9.-]{0,63}$/.test(_))throw je("unexpected-cli-token","Invalid or duplicate private execution model.");u=_;break}default:if(i!==void 0&&k&&(!k.startsWith("-")||k==="-")){i+=` ${k}`;break}throw je("unexpected-cli-token","Unexpected top-level CLI token. Quote the complete --args payload or use --stdin/--args-file for multiline content.")}}if(u!==void 0&&(!S||m))throw je("unexpected-cli-token","A private execution model requires private beta without strict read-only.");const v=[i!==void 0?"args":void 0,r?"stdin":void 0,o!==void 0?"args-file":void 0].filter(P=>P!==void 0);if(v.length===0)throw je("missing-input-value",Wi);if(v.length>1)throw je("multiple-input-sources",`Choose only one invoke input source; received ${v.join(", ")}.`);const I=v[0],g=I==="args"?i:I==="stdin"?(t.readStdin??Vs)():(t.readArgsFile??js)(o);let E;try{E=Qt(I,g)}catch(P){throw P instanceof Ko?je("invalid-utf8",P.message,I):P}const x=I==="args"?ss(E.rawArgs):Me(E.rawArgs),M=x.args===E.rawArgs?E:Qt(I,x.args);return{args:x.args,inputSource:I,inputEnvelope:M,projectRoot:n,format:a,watch:d||x.watch,commandLevelWatch:x.metadata,serverUrl:s,platformTarget:l,strictReadOnly:m,privateExecutionBeta:S,...u===void 0?{}:{privateExecutionModel:u}}}function Gi(e,t){return t?.active?{...e??{},commandLevelWatch:t,serverHeldStream:!1}:e}function Fi(e,t,i=process.stdout,r=process.stderr){if(t.format==="json"){const a=En(e.instructions,e.metadata),d=Gi(a.metadata,t.commandLevelWatch);if(t.watch){i.write(JSON.stringify({type:"invoke_result",instructions:a.instructions,metadata:d,publicSafe:!0})+`
|
|
212
|
+
`);return}i.write(JSON.stringify({instructions:a.instructions,metadata:d})+`
|
|
213
|
+
`);return}const o=En(e.instructions,e.metadata),n=Gi(o.metadata,t.commandLevelWatch);i.write(o.instructions+`
|
|
214
|
+
`),n&&r.write(JSON.stringify(n)+`
|
|
215
|
+
`)}async function Kd(e=process.stdout,t=process.stderr){const i=o=>new Promise(n=>{let a=!1;const d=m=>{a||(a=!0,clearTimeout(l),setImmediate(()=>o.removeListener("error",s)),n(m))},s=()=>d(!1),l=setTimeout(()=>d(!1),1e4);o.once("error",s);try{o.write("",m=>d(!m))}catch{d(!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 Qd(e){if(Ms(e))return process.stdout.write(`${Ds}
|
|
216
|
+
`),0;let t;try{t=Bs(e)}catch(r){if(r instanceof In)return process.stderr.write(JSON.stringify({error_code:r.code,reason:r.reason,source:r.source,byte_length:r.byteLength,message:r.message,remediation:r.message})+`
|
|
217
|
+
`),1;throw r}if(ko(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."})+`
|
|
218
|
+
`),1):(await Oo({args:t.args,projectRoot:Yn(t.projectRoot),format:t.format,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})).exitCode;const i=await Ns({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 Fi(i,t),i.exitCode;if(!i.success){const r=i.metadata?.invocationInput,o=Ya(i.metadata?.yoloChangeEvidence),n=r&&typeof r=="object"&&!Array.isArray(r)?r:void 0;return process.stderr.write(JSON.stringify({error_code:i.errorCode??(i.exitCode===2?"NOT_CONFIGURED":"INVOKE_ERROR"),message:Je(i.error??"",kt),...typeof n?.reason=="string"?{reason:Je(n.reason,80)}:{},...typeof n?.source=="string"?{source:Je(n.source,20)}:{},...Number.isSafeInteger(n?.byteLength)?{byte_length:n.byteLength}:{},...typeof n?.remediation=="string"?{remediation:Je(n.remediation,kt)}:{},...o?{yolo_change_evidence:o}:{}})+`
|
|
219
|
+
`),i.exitCode}if(Fi(i,t),t.watch){const r=new AbortController,o=Us(r);try{const n=Is(i.metadata,t.args);n.disabled?Kc(n.reasonCodes??[_e.TARGET_UNRESOLVED],t.args,t.format,process.stdout,t.privateExecutionBeta):await Qc({projectRoot:Yn(t.projectRoot),format:t.format,strictReadOnly:t.strictReadOnly,protectedOutput:t.privateExecutionBeta,...n,signal:r.signal})}finally{o()}}return 0}export{Ds as INVOKE_HELP_TEXT,Kr as INVOKE_PAYLOAD_LIMIT_BYTES,Gn as INVOKE_PAYLOAD_WARNING_THRESHOLD_BYTES,In as InvokeCliInputError,Jn as InvokePayloadTooLargeError,Kn as InvokeStructuralContextTooLargeError,$i as STORY_WORKTREE_BARRIER_CLIENT_MAX_ATTEMPTS,Ui as STORY_WORKTREE_BARRIER_CLIENT_MAX_WAIT_MS,lt as StateSnapshotIntegrityError,zd as __resetSchemaDriftWarnedForTests,Cs as acknowledgeMaterializedPendingEpicClaims,ni as admitClientInvocation,Zn as assertEpicAwareStateShapeBeforeRepair,Ec as boundedP222PremergeCheckpointPositions,zn as buildInvokeCompatibilityOffer,Tc as buildSignedInvokeAttempt,Ma as clearPendingEpicIdempotencyKey,Sc as collectInvokeP205Authorities,_n as collectStateSnapshot,Wt as computeInvokeRequestBodySizeBytes,Jd as createFullStateSnapshotScope,rr as createInvokePayloadTelemetry,ja as deriveYoloLogicalIdempotencyKey,Qa as detectStateSchemaDrift,Ls as extractPreFlightTrigger,Kd as flushInvokeCliOutput,Da as getOrCreatePendingEpicIdempotencyKey,ir as guardInvokeRequestBodySize,Ns as invoke,Qd as invokeCliHandler,Ic as invokeP205ProjectionReasonCode,fi as isEpicAwareCommandId,Ts as isStoryWorktreePhaseOneInvocation,Vc as maybeEmitInvokePayloadSizeWarning,Bc as maybeRunInvokeRunnerAutoBootstrap,yc as observeStoryWorktreeReadiness,Bs as parseInvokeCliOptions,Os as persistStoryWorktreePhaseEvidence,ks as pollStoryWorktreeSpecBarrier,_i as postMaterializationJson,Ba as projectRegistryDriftInvokeFailure,Ua as projectReleaseBlockedInvokeResult,Ya as projectYoloChangeEvidenceCliDiagnostic,Fr as publicYoloSpecEnvelopeErrorCode,As as reconcileInvalidatedYoloopSession,ti as recordPendingEpicReservation,$a as recoverClientInvocation,ss as resolveInvokeCommandLevelWatch,Yn as resolveInvokeProjectRoot,Ac as resolveInvokeTransportErrorCode,Is as resolveInvokeWatchTarget,sc as sanitizeBranchModeConversionReceipt,En as sanitizeInvokeCliOutput,Di as sendEpicClaimAcknowledgement,ur as sendInvokeRequest,vs as sendPrivateExecutionCancelRequest,Ss as sendPrivateExecutionConsumeRequest,qa as shouldCollectProjectEvidenceForInvoke,mc as storyWorktreeReadinessTargetEpic,Qc as watchContinuityProcessingSummaries,Fi as writeInvokeCliSuccessOutput};
|