@ornexus/neocortex 4.61.6 → 4.62.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/release-source.json +1 -1
- package/dist/sbom.cdx.json +1193 -1193
- package/install.ps1 +31 -34
- package/install.sh +1 -1
- package/package.json +5 -2
- package/packages/client/dist/agent/update-description.d.ts +8 -1
- package/packages/client/dist/agent/update-description.js +2 -1
- package/packages/client/dist/commands/invoke.d.ts +17 -0
- package/packages/client/dist/commands/invoke.js +72 -72
- package/packages/client/dist/errors/frontmatter-diagnostics.d.ts +10 -1
- package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -1
- package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +24 -9
- package/packages/client/dist/git/direct-yolo-checkpoint.js +3 -4
- package/packages/client/dist/git/git-lifecycle-store.d.ts +66 -0
- package/packages/client/dist/git/git-lifecycle-store.js +8 -7
- package/packages/client/dist/git/release-gate-env.d.ts +62 -0
- package/packages/client/dist/git/release-gate-env.js +1 -0
- package/packages/client/dist/git/secure-filesystem-boundary.d.ts +24 -0
- package/packages/client/dist/git/secure-filesystem-boundary.js +20 -9
- package/packages/client/dist/runner/headless/child-env.d.ts +92 -0
- package/packages/client/dist/runner/headless/child-env.js +1 -0
- package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -11
- package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +1 -0
- package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -10
- package/packages/client/dist/runner/headless/run-yoloop.js +2 -2
- package/packages/client/dist/yolo/invoke-envelope-capability.d.ts +2 -0
- package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -1
- package/packages/client/dist/yolo/project-manifest-projection-collector.d.ts +28 -0
- package/packages/client/dist/yolo/project-manifest-projection-collector.js +1 -0
- package/packages/client/dist/yolo/spec-envelope-collector.d.ts +9 -0
- package/packages/client/dist/yolo/spec-envelope-collector.js +3 -3
- package/packages/client/dist/yoloop/shared-discover-epics.d.ts +16 -0
- package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1
- package/packages/shared/dist/frontmatter-context-contract.js +164 -52
- package/packages/shared/dist/project-manifest-projection.js +199 -0
- package/packages/shared/dist/project-validation-commands.js +14 -6
- package/packages/shared/dist/yolo/spec-envelope-rules.js +85 -0
- package/packages/shared/dist/yolo/spec-envelope.js +33 -7
- package/packages/shared/dist/yoloop/epic-terminal-git.js +94 -6
- package/packages/shared/dist/yoloop/story-write-scope.js +212 -0
- package/targets-stubs/antigravity/gemini.md +1 -1
- package/targets-stubs/antigravity/install-antigravity.sh +13 -4
- 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 +5 -5
- 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/lib/managed-config-merge.js +77 -1
- package/targets-stubs/lib/managed-profile.sh +7 -0
- package/targets-stubs/opencode/neocortex-root.md +1 -1
- package/targets-stubs/vscode/install-vscode.sh +21 -0
- package/targets-stubs/vscode/neocortex.agent.md +2 -2
|
@@ -1,59 +1,59 @@
|
|
|
1
|
-
import{classifyNonUiArchitectureTransition as Yi,architectureMemoryPredecessorCount as mr}from"./architecture-non-ui-continuation.js";import{parseArchitectureNonUiScopeReceipt as yr}from"./shared-architecture-non-ui.js";import{createHash as Pe,randomUUID as dn}from"node:crypto";import{loadPactAnswerReceipt as Ir,loadPactPrivateAnswers as Fi}from"./architecture-answers.js";import{acceptedArchitectureTerminalMemoryReceipt as Gt,deriveArchitectureTerminalMemoryReceipt as On}from"./architecture-memory-terminal.js";import{deriveCommittedArchitectureEpicGraphRevision as Yt,explicitArchitectureEpicTarget as qi}from"./architecture-root-binding.js";import{derivePactWriteSet as zi}from"../private-execution/pact-write-set.js";import{execFileSync as We}from"node:child_process";import{existsSync as Mt,readFileSync as Ge,renameSync as Er,unlinkSync as Nn,writeFileSync as pn,mkdirSync as Ft,statSync as Ji,openSync as qt,closeSync as zt,fsyncSync as ln,realpathSync as Ki,lstatSync as jt}from"node:fs";import{isDeepStrictEqual as v}from"node:util";import{join as Q,isAbsolute as Qi,resolve as Ln}from"node:path";import{homedir as Jt}from"node:os";import{probeYoloopHostCapacity as Xi}from"../runner/host-capacity.js";import{isPrivateExecutionPublicEnvelope as Zi,isPrivatePlanningRootPublicEnvelope as ea,PRIVATE_MUTATION_QA_GATE_STEP_TOKEN as ta}from"../private-execution/delivery.js";import{acceptedPlanningDiagnosisPredecessor as Sr}from"../private-execution/planning-diagnosis-checkpoint.js";import{acceptedPlanningResearchPredecessor as vr}from"../private-execution/planning-research-checkpoint.js";import{verifyCommittedPlanningMemory as Cr}from"../private-execution/planning-memory-checkpoint.js";import{verifyCommittedPlanningGeneration as na}from"../private-execution/planning-generation-checkpoint.js";import{PLANNING_RAW_INTENT_MAX_CHARS as ra}from"../../../shared/dist/planning/diagnosis-state.js";import{applyCrossEpicContinuationReconciliation as ia,buildCrossEpicContinuationPayloadHash as aa,classifyCrossEpicContinuationReconciliation as oa,epicOperationalHash as It,readEpicOperationalState as _r}from"../git/epic-operational-state.js";import{LicenseClient as ca}from"../license/license-client.js";import{EncryptedCache as Dn}from"../cache/encrypted-cache.js";import{NoOpCache as Rr}from"../types/index.js";import{resolveClientPreFlightTrigger as un,TierAwareClient as sa}from"../tier/tier-aware-client.js";import{COMMAND_REGISTRY_CHECKSUM as at,COMMAND_REGISTRY_VERSION as ot,GENERATED_CLIENT_COMMANDS as da}from"../generated/command-registry.generated.js";import{loadSecureConfig as Mn}from"../config/secure-config.js";import{neocortexProfileDirectory as pa}from"../config/profile-directory.js";import{DEFAULT_SERVER_URL as la}from"../constants.js";import{detectFirstRunLocale as ua,renderFirstRunMessage as ha}from"../i18n/first-run.js";import{humanizeError as wr,formatHumanizedError as Ar,detectErrorLocale as br}from"../errors/error-messages.js";import{degradeStateSnapshotForPayloadLimit as ga,projectStateSnapshotForInvoke as xr,projectStateSnapshotResultV2ForInvoke as fa}from"../state/project-state-snapshot.js";import{isInlineYoloMaterialization as Tr,maybeRepairStateJsonBeforeInvoke as ma,StateRepairHardStopError as ya}from"../state/state-json-repair.js";import{StructuralDagError as Pr}from"../state/structural-dag-projection.js";import{collectStateMigrationAuthority as Ia,StateMigrationApplyError as Ea}from"../migrations/state-json.js";import{RUNNER_BOOTSTRAP_POLICY_REASON_CODES as Sa,classifyRunnerBootstrapPolicyFromArgs as va}from"../continuity/runner-bootstrap-policy.js";import{RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES as Ca,ensureRunnerSchedulerBootstrap as _a,observeRunnerOperationalStatus as Ra}from"../runner/scheduler.js";import{CONTINUITY_INVOKE_WATCH_DEFAULT_LIMIT as kr,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_IDLE_POLLS as Or,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_POLLS as Nr,CONTINUITY_INVOKE_WATCH_DEFAULT_POLL_INTERVAL_MS as Lr,openContinuityClientStateStore as wa}from"../continuity/continuity-client-state-store.js";import{isLocalJobsConsoleArgs as Aa,runLocalJobsConsoleCommand as ba}from"../runner/local-console.js";import{detectNativeHostAttestation as xa,detectPlatform as Ta}from"../adapters/platform-detector.js";import{signNxInvokeRequest as Pa}from"../../../shared/dist/nx-invoke-signature.js";import{YOLO_INVOKE_ENVELOPE_CAPABILITY as ka}from"../../../shared/dist/yolo/spec-envelope.js";import{parseReleaseBlockedResult as Oa}from"../../../shared/dist/yoloop/release-blocked.js";import{CLIENT_VERSION as Pt}from"../version.js";import{createCapabilityCache as Dr,executeInvokeQueryTransport as jn,executeSecondaryNetworkMutation as Na}from"../effects/invoke-effect-gateways.js";import{STRICT_READ_ONLY_POLICY as La,STRICT_READ_ONLY_CLIENT_PROJECTION as Mr,STRICT_READ_ONLY_SERVER_PROJECTION as Da,StrictReadOnlyError as Vt,canonicalizeInvokeEffects as Ma,createInvokeEffectContext as ja,verifyStrictReadOnlyReceipt as Va}from"../../../shared/dist/strict-readonly.js";import{admitInvocation as Ba,assertInvokeInputEnvelopeV2 as Ua,assertProjectIdentityMigrationReceiptV1 as $a,buildProjectIdentityPublicDiagnostic as Bt,createInvocationAdmissionReceipt as Ha,projectInvokeInputEvidenceV1 as Vn,recoverExplicitInvocation as Wa,verifyStrictDiagnoseReceiptV1 as Ga}from"../../../shared/dist/invocation/index.js";import{buildInvokeInputEnvelope as Kt,InvokeInputDecodeError as Ya}from"../invocation/invoke-input.js";import{COMPATIBILITY_REASON_CODES as Ut,createCompatibilityOffer as Fa,createLegacyCompatibilityResult as qa,isCompatibilityResultV1 as za}from"../../../shared/dist/compatibility/index.js";import{acknowledgeProjectIdentityMigration as Ja,finalizeProjectIdentityMigration as Ka,prepareProjectIdentityMigration as Qa,ProjectIdentityMigrationError as Bn,readProjectIdentityMigrationPhase as Xa}from"../migrations/project-identity.js";import{probeProjectIdentityMigrationCapability as Za}from"../migrations/project-identity-capability.js";import{normalizeYoloopStoryPlanningEvidence as eo}from"../../../shared/dist/yoloop/planning-graph.js";import{normalizeContinuousWriteRef as hn}from"../../../shared/dist/yoloop/wave-decision-receipt.js";import{epicHeadReconciliationInputDigest as to,epicHeadReconciliationPathsDigest as jr,epicHeadReconciliationRangeDigest as no}from"../../../shared/dist/yoloop/epic-terminal-git.js";import{applyGitLifecycleRuntimeOverlay as Vr,classifyGitLifecycleStoryCheckpointProjectionSync as ro,ensureRuntimeEpic as io,ensureGitLifecycleRuntimeInitialized as ao,executeP205TransientAuthorities as oo,persistGitLifecycleGraphAuthority as co,P205_COMPLETE_COMMAND as Qt,gitLifecycleStoryWriteSet as Br,appendStoryWorktreeEvidence as so,isStoryWorktreeEvidenceContainer as po,mutateGitLifecycleRuntime as Ur,projectP205TransientExecutionEvidence as lo,readGitLifecycleRuntimeSync as gn,verifyLegacyCheckpointMigrationCandidateSync as uo}from"../git/git-lifecycle-store.js";import{verifyRootMemoryPhysicalWriteSet as ho}from"../private-execution/root-memory-git-evidence.js";import{isRootProjectMemoryEffect as go}from"../private-execution/shared-root-memory-types.js";import{probeYoloInvokeEnvelopeCapability as fo}from"../yolo/invoke-envelope-capability.js";import{collectYoloSpecEnvelope as $r,extractTargetedYoloStoryId as mo,refreshPrecollectedYoloSpecEnvelope as Hr}from"../yolo/spec-envelope-collector.js";const fn=pa(),Un=Q(fn,"cache"),Wr=Q(Un,"menu-cache.json"),Gr=1440*60*1e3,Yr=3e4,Fr=256*1024,qr=Fr,zr=.8,Et="[REDACTED]",yo=1e5,kt=2e3,Io=200,Eo=200,So=12,vo=/(?:promptBody|workflow|workflowGraph|stepBody|privateUrl|rawLog|secret|credential|licenseKey|apiKey|internalRouting|serverOnly|proprietary|protected)/i,Co=/(?:PRIVATE|PROTECTED|SERVER_ONLY)[-_\s]*(?:PROMPT|PROMPT_BODY|WORKFLOW|WORKFLOW_GRAPH|STEP_BODY|STEP|ROUTING)\s*[:=][^\n\r]*/gi,_o=/(?:https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|private|internal)[^\s"'<>]*|raw[_-]?log|transcript|stack\s*trace|stderr:|stdout:|system prompt|prompt body|workflow body|step body|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|VENDOR_CORPUS|P180[_-]?SYNTHETIC[_-]?CONTINUITY|P185[_-]?SYNTHETIC[_-]?CONTINUITY|P187[_-]?SYNTHETIC[_-]?(?:CONTINUITY|RUNNER|WATCH)|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=)/gi,$n=Math.floor(Fr*zr),Jr=Q(fn,".first-run-shown"),Ro="pending-epic-claims.json",Kr=64;function Qr(e){return Q(e,".neocortex",Ro)}function $t(e){const t=Qr(e);if(!Mt(t))return{schemaVersion:1,operations:{}};const i=JSON.parse(Ge(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>Kr)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");for(const[a,n]of Object.entries(r.operations)){if(!/^[a-f0-9]{64}$/.test(a)||!n||typeof n!="object"||Array.isArray(n))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const o=n;if(o.planningProtocol!==void 0&&o.planningProtocol!=="root-staged-v1")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(typeof o.idempotencyKey!="string"||!/^[0-9a-f-]{36}$/.test(o.idempotencyKey)||typeof o.createdAt!="string")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(o.claimId!==void 0&&(typeof o.claimId!="string"||!/^[0-9a-f-]{36}$/.test(o.claimId))||o.epicId!==void 0&&(typeof o.epicId!="string"||!/^P[1-9][0-9]*$/.test(o.epicId))||o.claimId===void 0!=(o.epicId===void 0))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE")}return i}function Hn(e,t){const i=Qr(e);Ft(Q(e,".neocortex"),{recursive:!0,mode:448});const r=`${i}.${process.pid}.${dn()}.tmp`;pn(r,`${JSON.stringify(t)}
|
|
2
|
-
`,{encoding:"utf8",mode:384,flag:"wx"}),
|
|
1
|
+
import{classifyNonUiArchitectureTransition as qi,architectureMemoryPredecessorCount as Ir}from"./architecture-non-ui-continuation.js";import{parseArchitectureNonUiScopeReceipt as Er}from"./shared-architecture-non-ui.js";import{createHash as Ne,randomUUID as dn}from"node:crypto";import{loadPactAnswerReceipt as Sr,loadPactPrivateAnswers as zi}from"./architecture-answers.js";import{acceptedArchitectureTerminalMemoryReceipt as Ft,deriveArchitectureTerminalMemoryReceipt as Ln}from"./architecture-memory-terminal.js";import{deriveCommittedArchitectureEpicGraphRevision as Yt,explicitArchitectureEpicTarget as Ji}from"./architecture-root-binding.js";import{derivePactWriteSet as Ki}from"../private-execution/pact-write-set.js";import{execFileSync as Ge}from"node:child_process";import{existsSync as jt,readFileSync as Fe,renameSync as vr,unlinkSync as Dn,writeFileSync as pn,mkdirSync as qt,statSync as Qi,openSync as zt,closeSync as Jt,fsyncSync as ln,realpathSync as Xi,lstatSync as Vt}from"node:fs";import{isDeepStrictEqual as v}from"node:util";import{join as z,isAbsolute as Zi,resolve as Mn}from"node:path";import{homedir as Kt}from"node:os";import{probeYoloopHostCapacity as ea}from"../runner/host-capacity.js";import{isPrivateExecutionPublicEnvelope as ta,isPrivatePlanningRootPublicEnvelope as na,PRIVATE_MUTATION_QA_GATE_STEP_TOKEN as ra}from"../private-execution/delivery.js";import{acceptedPlanningDiagnosisPredecessor as Cr}from"../private-execution/planning-diagnosis-checkpoint.js";import{acceptedPlanningResearchPredecessor as Rr}from"../private-execution/planning-research-checkpoint.js";import{verifyCommittedPlanningMemory as _r}from"../private-execution/planning-memory-checkpoint.js";import{verifyCommittedPlanningGeneration as ia}from"../private-execution/planning-generation-checkpoint.js";import{PLANNING_RAW_INTENT_MAX_CHARS as aa}from"../../../shared/dist/planning/diagnosis-state.js";import{applyCrossEpicContinuationReconciliation as oa,buildCrossEpicContinuationPayloadHash as ca,classifyCrossEpicContinuationReconciliation as sa,epicOperationalHash as vt,readEpicOperationalState as wr}from"../git/epic-operational-state.js";import{LicenseClient as da}from"../license/license-client.js";import{EncryptedCache as jn}from"../cache/encrypted-cache.js";import{NoOpCache as Ar}from"../types/index.js";import{resolveClientPreFlightTrigger as un,TierAwareClient as pa}from"../tier/tier-aware-client.js";import{COMMAND_REGISTRY_CHECKSUM as st,COMMAND_REGISTRY_VERSION as dt,GENERATED_CLIENT_COMMANDS as la}from"../generated/command-registry.generated.js";import{loadSecureConfig as Vn}from"../config/secure-config.js";import{neocortexProfileDirectory as ua}from"../config/profile-directory.js";import{DEFAULT_SERVER_URL as ha}from"../constants.js";import{detectFirstRunLocale as ga,renderFirstRunMessage as fa}from"../i18n/first-run.js";import{humanizeError as br,formatHumanizedError as xr,detectErrorLocale as Tr}from"../errors/error-messages.js";import{degradeStateSnapshotForPayloadLimit as ma,projectStateSnapshotForInvoke as Pr,projectStateSnapshotResultV2ForInvoke as ya}from"../state/project-state-snapshot.js";import{isInlineYoloMaterialization as kr,maybeRepairStateJsonBeforeInvoke as Ia,StateRepairHardStopError as Ea}from"../state/state-json-repair.js";import{StructuralDagError as Or}from"../state/structural-dag-projection.js";import{collectStateMigrationAuthority as Sa,StateMigrationApplyError as va}from"../migrations/state-json.js";import{RUNNER_BOOTSTRAP_POLICY_REASON_CODES as Ca,classifyRunnerBootstrapPolicyFromArgs as Ra}from"../continuity/runner-bootstrap-policy.js";import{RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES as _a,ensureRunnerSchedulerBootstrap as wa,observeRunnerOperationalStatus as Aa}from"../runner/scheduler.js";import{CONTINUITY_INVOKE_WATCH_DEFAULT_LIMIT as Nr,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_IDLE_POLLS as Lr,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_POLLS as Dr,CONTINUITY_INVOKE_WATCH_DEFAULT_POLL_INTERVAL_MS as Mr,openContinuityClientStateStore as ba}from"../continuity/continuity-client-state-store.js";import{isLocalJobsConsoleArgs as xa,runLocalJobsConsoleCommand as Ta}from"../runner/local-console.js";import{detectNativeHostAttestation as Pa,detectPlatform as ka}from"../adapters/platform-detector.js";import{signNxInvokeRequest as Oa}from"../../../shared/dist/nx-invoke-signature.js";import{YOLO_INVOKE_ENVELOPE_CAPABILITY as Na}from"../../../shared/dist/yolo/spec-envelope.js";import{parseReleaseBlockedResult as La}from"../../../shared/dist/yoloop/release-blocked.js";import{CLIENT_VERSION as Pt}from"../version.js";import{createCapabilityCache as jr,executeInvokeQueryTransport as Bn,executeSecondaryNetworkMutation as Da}from"../effects/invoke-effect-gateways.js";import{STRICT_READ_ONLY_POLICY as Ma,STRICT_READ_ONLY_CLIENT_PROJECTION as Vr,STRICT_READ_ONLY_SERVER_PROJECTION as ja,StrictReadOnlyError as Bt,canonicalizeInvokeEffects as Va,createInvokeEffectContext as Ba,verifyStrictReadOnlyReceipt as Ua}from"../../../shared/dist/strict-readonly.js";import{admitInvocation as $a,assertInvokeInputEnvelopeV2 as Ha,assertProjectIdentityMigrationReceiptV1 as Wa,buildProjectIdentityPublicDiagnostic as Ut,createInvocationAdmissionReceipt as Ga,projectInvokeInputEvidenceV1 as Un,recoverExplicitInvocation as Fa,verifyStrictDiagnoseReceiptV1 as Ya}from"../../../shared/dist/invocation/index.js";import{buildInvokeInputEnvelope as Qt,InvokeInputDecodeError as qa}from"../invocation/invoke-input.js";import{COMPATIBILITY_REASON_CODES as $t,createCompatibilityOffer as za,createLegacyCompatibilityResult as Ja,isCompatibilityResultV1 as Ka}from"../../../shared/dist/compatibility/index.js";import{acknowledgeProjectIdentityMigration as Qa,finalizeProjectIdentityMigration as Xa,prepareProjectIdentityMigration as Za,ProjectIdentityMigrationError as $n,readProjectIdentityMigrationPhase as eo}from"../migrations/project-identity.js";import{probeProjectIdentityMigrationCapability as to}from"../migrations/project-identity-capability.js";import{normalizeYoloopStoryPlanningEvidence as no}from"../../../shared/dist/yoloop/planning-graph.js";import{normalizeContinuousWriteRef as hn}from"../../../shared/dist/yoloop/wave-decision-receipt.js";import{epicHeadReconciliationInputDigest as ro,epicHeadReconciliationPathsDigest as gn,epicHeadReconciliationRangeDigest as io}from"../../../shared/dist/yoloop/epic-terminal-git.js";import{applyGitLifecycleRuntimeOverlay as Br,classifyGitLifecycleStoryCheckpointProjectionSync as ao,ensureRuntimeEpic as oo,ensureGitLifecycleRuntimeInitialized as co,executeP205TransientAuthorities as so,isP226GateReasonCode as po,persistGitLifecycleGraphAuthority as lo,P205_COMPLETE_COMMAND as Xt,gitLifecycleStoryWriteSet as Ur,gitLifecycleStoryClaimCandidates as uo,gitLifecycleWriteSetCovers as ho,appendStoryWorktreeEvidence as go,isStoryWorktreeEvidenceContainer as fo,mutateGitLifecycleRuntime as $r,projectP205TransientExecutionEvidence as mo,readGitLifecycleRuntimeSync as fn,verifyLegacyCheckpointMigrationCandidateSync as yo}from"../git/git-lifecycle-store.js";import{verifyRootMemoryPhysicalWriteSet as Io}from"../private-execution/root-memory-git-evidence.js";import{isRootProjectMemoryEffect as Eo}from"../private-execution/shared-root-memory-types.js";import{probeYoloInvokeEnvelopeCapability as So}from"../yolo/invoke-envelope-capability.js";import{attachProjectManifestProjection as vo}from"../yolo/project-manifest-projection-collector.js";import{collectYoloSpecEnvelope as Hr,extractTargetedYoloStoryId as Co,refreshPrecollectedYoloSpecEnvelope as Wr}from"../yolo/spec-envelope-collector.js";import{FRONTMATTER_LIST_TOO_LONG_DIAGNOSTIC_PATTERN as Ro}from"../errors/frontmatter-diagnostics.js";function Gr(e,t=!1){return e instanceof Error&&((t?/^yolo-(?:spec-envelope|change-evidence)-[a-z-]+$/:/^yolo-spec-envelope-[a-z-]+$/).test(e.message)||Ro.test(e.message))?e.message:"yolo-spec-envelope-unsafe"}const mn=ua(),Hn=z(mn,"cache"),Fr=z(Hn,"menu-cache.json"),Yr=1440*60*1e3,qr=3e4,zr=256*1024,Jr=zr,Kr=.8,Ct="[REDACTED]",_o=1e5,kt=2e3,wo=200,Ao=200,bo=12,xo=/(?:promptBody|workflow|workflowGraph|stepBody|privateUrl|rawLog|secret|credential|licenseKey|apiKey|internalRouting|serverOnly|proprietary|protected)/i,To=/(?:PRIVATE|PROTECTED|SERVER_ONLY)[-_\s]*(?:PROMPT|PROMPT_BODY|WORKFLOW|WORKFLOW_GRAPH|STEP_BODY|STEP|ROUTING)\s*[:=][^\n\r]*/gi,Po=/(?:https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|private|internal)[^\s"'<>]*|raw[_-]?log|transcript|stack\s*trace|stderr:|stdout:|system prompt|prompt body|workflow body|step body|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|VENDOR_CORPUS|P180[_-]?SYNTHETIC[_-]?CONTINUITY|P185[_-]?SYNTHETIC[_-]?CONTINUITY|P187[_-]?SYNTHETIC[_-]?(?:CONTINUITY|RUNNER|WATCH)|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=)/gi,Wn=Math.floor(zr*Kr),Qr=z(mn,".first-run-shown"),ko="pending-epic-claims.json",Xr=64;function Zr(e){return z(e,".neocortex",ko)}function Ht(e){const t=Zr(e);if(!jt(t))return{schemaVersion:1,operations:{}};const i=JSON.parse(Fe(t,"utf8"));if(!i||typeof i!="object"||Array.isArray(i))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const r=i;if(r.schemaVersion!==1||!r.operations||typeof r.operations!="object"||Array.isArray(r.operations))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(Object.keys(r.operations).length>Xr)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");for(const[a,n]of Object.entries(r.operations)){if(!/^[a-f0-9]{64}$/.test(a)||!n||typeof n!="object"||Array.isArray(n))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const o=n;if(o.planningProtocol!==void 0&&o.planningProtocol!=="root-staged-v1")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(typeof o.idempotencyKey!="string"||!/^[0-9a-f-]{36}$/.test(o.idempotencyKey)||typeof o.createdAt!="string")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(o.claimId!==void 0&&(typeof o.claimId!="string"||!/^[0-9a-f-]{36}$/.test(o.claimId))||o.epicId!==void 0&&(typeof o.epicId!="string"||!/^P[1-9][0-9]*$/.test(o.epicId))||o.claimId===void 0!=(o.epicId===void 0))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE")}return i}function Gn(e,t){const i=Zr(e);qt(z(e,".neocortex"),{recursive:!0,mode:448});const r=`${i}.${process.pid}.${dn()}.tmp`;pn(r,`${JSON.stringify(t)}
|
|
2
|
+
`,{encoding:"utf8",mode:384,flag:"wx"}),vr(r,i)}function Oo(e,t){return Ne("sha256").update(`nx-epic-logical-operation-v1\0${JSON.stringify({command:t,args:e})}`,"utf8").digest("hex")}function No(e,t,i="create-epic"){const r=Oo(t,i),a=Ht(e),n=a.operations[r];if(n)return{key:n.idempotencyKey,fingerprint:r};if(Object.keys(a.operations).length>=Xr)throw new Error("EPIC_CLAIM_CAPACITY_EXCEEDED");const o=dn(),d={...a.operations,[r]:{idempotencyKey:o,createdAt:new Date().toISOString()}};return Gn(e,{schemaVersion:1,operations:d}),{key:o,fingerprint:r}}function Lo(e,t){const i=Ht(e);if(!i.operations[t])return;const r={...i.operations};delete r[t],Gn(e,{schemaVersion:1,operations:r})}function Do(e,t,i,r){const a=r.scope?.targetStoryId??r.current_session?.active_story_id??null,n=r.scope?.targetEpicId??r.current_session?.active_epic_id??null,o=a?r.stories[a]:void 0,d=Array.isArray(o?.steps_completed)?o.steps_completed.filter(y=>typeof y=="string"):[],s=i??Ne("sha256").update(`nx-yolo-project-path-v1\0${Mn(e)}`,"utf8").digest("hex"),l=JSON.stringify({projectBinding:s,args:t,storyId:a,epicId:n,status:typeof o?.status=="string"?o.status:null,lastStep:typeof o?.last_step=="string"?o.last_step:null,stepsCompleted:d});return`yolo-${Ne("sha256").update(`nx-yolo-logical-operation-v1\0${l}`,"utf8").digest("hex")}`}function ei(e,t,i,r,a){if(!/^[0-9a-f-]{36}$/.test(i)||!/^P[1-9][0-9]*$/.test(r)||a!==void 0&&a!=="root-staged-v1")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const n=Ht(e),o=n.operations[t];if(!o)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(o.claimId!==void 0&&(o.claimId!==i||o.epicId!==r))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");Gn(e,{schemaVersion:1,operations:{...n.operations,[t]:{...o,claimId:i,epicId:r,...a?{planningProtocol:a}:{}}}})}function Mo(){try{if(jt(Qr))return;const e=ga(),t=fa(e);process.stderr.write(t);try{qt(mn,{recursive:!0}),pn(Qr,new Date().toISOString(),"utf-8")}catch{}}catch{}}function Fn(e,t=process.cwd()){return e&&e.trim().length>0?e:t}function jo(e){if(e==="REGISTRY_PROJECTION_DRIFT")return{success:!1,error:'REGISTRY_RECONCILIATION_REQUIRED: the installed client registry was rejected. Run `neocortex-client reconcile-registry --project-root "$(git rev-parse --show-toplevel 2>/dev/null || pwd -P)" --check-latest`, then retry.',errorCode:"REGISTRY_RECONCILIATION_REQUIRED",metadata:{registryReconciliation:{reasonCode:"REGISTRY_RECONCILIATION_REQUIRED",authority:"local-and-public-npm-only",publicSafe:!0}},exitCode:1}}function Vo(e){const t=e.metadata;if(!t||!(t.yoloopReleaseBlocked===!0||t.terminalClass==="release-blocked"||t.releaseBlocked!==void 0))return;const r=La(t.releaseBlocked);return!r||t.yoloopReleaseBlocked!==!0||t.terminalClass!=="release-blocked"||t.yoloopComplete!==!1||t.yoloopAborted!==!1?{success:!1,error:"YOLOOP_RELEASE_BLOCKED_INVALID: terminal evidence was inconsistent.",errorCode:"YOLOOP_RELEASE_BLOCKED_INVALID",metadata:t,exitCode:1}:{success:!1,instructions:e.instructions,metadata:{...t,releaseBlocked:r},error:"YOLOOP_RELEASE_BLOCKED: the current release attempt ended without success.",errorCode:"YOLOOP_RELEASE_BLOCKED",exitCode:1}}function ti(e){return $a(e,{registryVersion:dt,registryChecksum:st})}function Bo(e){return Fa(e,{registryVersion:dt,registryChecksum:st})}const Uo=new Set(["completed","aborted","cancelled"]),$o=new Set(["watch-target-missing","watch-target-malformed","watch-target-ambiguous","watch-target-multiple"]),Re=Object.freeze({COMPLETED:"invoke-watch-completed",CANCELLED:"invoke-watch-cancelled",IDLE_TIMEOUT:"invoke-watch-idle-timeout",MAX_POLLS:"invoke-watch-max-polls",STORE_UNAVAILABLE:"invoke-watch-store-unavailable",TARGET_UNRESOLVED:"invoke-watch-target-unresolved"}),Le=Object.freeze({MISSING:"watch-target-missing",MALFORMED:"watch-target-malformed",AMBIGUOUS:"watch-target-ambiguous",CONFLICT:"watch-target-conflicting-evidence",SERVER_HELD_STREAM:"watch-target-server-held-stream-unsupported"}),G=Object.freeze({OK:"continuity-ok",WATCH_NO_SUMMARIES_YET:"watch-no-summaries-yet",WATCH_CURSOR_ADVANCED:"watch-cursor-advanced",WATCH_CURSOR_UNCHANGED:"watch-cursor-unchanged",WATCH_RENDER_PENDING:"watch-render-pending",WATCH_STOP_IDLE_LIMIT_REACHED:"watch-stop-idle-limit-reached",WATCH_STOP_MAX_POLLS_REACHED:"watch-stop-max-polls-reached",WATCH_TARGET_UNRESOLVED:"watch-target-unresolved",WATCH_SNAPSHOT_UNAVAILABLE:"watch-snapshot-unavailable",WATCH_EVIDENCE_UNAVAILABLE:"watch-evidence-unavailable"}),ni=240,Ho=/(https?:\/\/\S+|ghp_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|-----BEGIN [A-Z ]*PRIVATE KEY-----|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=|raw[_-]?log|transcript|stack\s*trace|stderr:|stdout:|system prompt|prompt body|workflow body|step body|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|VENDOR_CORPUS|P180[_-]?SYNTHETIC[_-]?CONTINUITY|P185[_-]?SYNTHETIC[_-]?CONTINUITY|P187[_-]?SYNTHETIC[_-]?(?:CONTINUITY|RUNNER|WATCH))/i;function Wo(e){return e.replace(/[\w.+-]+@[\w-]+\.[\w.-]+/g,Ct).replace(/(?:sk|pk|whsec|nxk)[-_](?:test|live|ant|proj|pro|free|enterprise)?[-_]?[A-Za-z0-9_-]{16,}/g,Ct).replace(/NX-[FPE]-[a-f0-9]{24}-[a-f0-9]{4}/g,Ct).replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,Ct).replace(To,Ct).replace(Po,Ct)}function Je(e,t){const i=Wo(e);return i.length<=t?i:`${i.slice(0,t)}\u2026[TRUNCATED:${i.length-t}]`}function Yn(e,t=0,i=new WeakSet){if(t>bo)return"[MAX_DEPTH]";if(e==null)return e;if(typeof e=="string")return Je(e,kt);if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e=="boolean")return e;if(typeof e=="bigint")return String(e);if(!(typeof e=="function"||typeof e=="symbol")&&typeof e=="object"){if(i.has(e))return"[CIRCULAR]";i.add(e);try{if(Array.isArray(e))return e.slice(0,wo).map(a=>Yn(a,t+1,i));const r={};for(const[a,n]of Object.entries(e).slice(0,Ao)){if(xo.test(a)){r[a]=Ct;continue}const o=Yn(n,t+1,i);o!==void 0&&(r[a]=o)}return r}finally{i.delete(e)}}}function yn(e,t){return{instructions:Je(e??"",_o),metadata:t?Yn(t):void 0}}function Go(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e,i=typeof t.reason=="string"&&/^[a-z0-9-]{1,80}$/.test(t.reason)?t.reason:void 0,r=typeof t.baseSource=="string"&&["active-story-lease","published-execution-branch","local-default-branch","remote-default-branch","none"].includes(t.baseSource)?t.baseSource:void 0,a=typeof t.repair=="string"&&["not-eligible","not-attempted","applied"].includes(t.repair)?t.repair:void 0,n=typeof t.fallbackAction=="string"&&["reacquire-exact-story-setup","restore-verified-base-evidence","resolve-lease-conflict","inspect-repository-binding","none"].includes(t.fallbackAction)?t.fallbackAction:void 0,o=t.recollectionCount===0||t.recollectionCount===1?t.recollectionCount:void 0;if(!(!i||!r||!a||!n||o===void 0||t.publicSafe!==!0))return{reason:i,base_source:r,repair:a,recollection_count:o,fallback_action:n,public_safe:!0}}class In extends Error{reason;source;byteLength;code;constructor(t,i,r,a,n){super(i),this.reason=r,this.source=a,this.byteLength=n,this.name="InvokeCliInputError",this.code=t}}function Fo(e){const t=un(e);return(t==="arch-plan"||t==="ui-ux-review")&&Yo(e,"--project-evidence")}function Yo(e,t){let i=null,r=-1,a=!1,n=!1;for(let o=0;o<=e.length;o+=1){const d=e[o];if(o===e.length||!i&&/\s/.test(d??"")){if(r>=0&&!a&&e.slice(r,o)===t)return!0;r=-1,a=!1,n=!1;continue}if(r<0&&(r=o),n){n=!1;continue}if(d==="\\"){n=!0;continue}(d==='"'||d==="'")&&(a=!0,i=i===d?null:i??d)}return!1}const qo=/(?:^|\s)codex(?:-cli)?\s+([A-Za-z0-9][A-Za-z0-9._+-]{0,63})(?:\s|$)/i;function zo(e,t){if(e.targetId!=="codex")return null;const i=t.CODEX_VERSION?.trim();if(i&&/^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/.test(i))return i;try{return Ge("codex",["--version"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim().match(qo)?.[1]??null}catch{return null}}function qn(){return za({clientVersion:Pt,registryVersion:dt,registryChecksum:st})}class zn extends Error{code="PAYLOAD_TOO_LARGE";telemetry;constructor(t){super(`PAYLOAD_TOO_LARGE: invoke request is ${t.payloadBytes} bytes after deterministic degradation; limit is ${t.limitBytes}. Reduce command input or local state context and retry.`),this.name="InvokePayloadTooLargeError",this.telemetry=t}}class Jn extends Error{code="STRUCTURAL_CONTEXT_TOO_LARGE";telemetry;constructor(t){super(`STRUCTURAL_CONTEXT_TOO_LARGE: the bounded structural projection is ${t.payloadBytes} bytes; the request limit is strictly below ${t.limitBytes}. Select an explicit epic/story target or split the dependency graph.`),this.name="InvokeStructuralContextTooLargeError",this.telemetry=t}}let Kn=!1;function Jo(e){const t=[];if(!e||typeof e!="object")return t;const i=e,r=i.planning;if(r&&(r.current!==void 0||Array.isArray(r.history))&&t.push({code:"PLANNING_LEGACY",message:"legacy `planning.current`/`planning.history` detected (not read by v1 orchestrator)"}),Array.isArray(i.stories)&&t.push({code:"STORIES_AS_ARRAY",message:"`stories` is an Array (expected Object keyed by story ID)"}),i.epics&&typeof i.epics=="object"&&!Array.isArray(i.epics))for(const[n,o]of Object.entries(i.epics)){const d=o;if(d&&d.stories!==void 0&&!Array.isArray(d.stories)){t.push({code:"EPIC_STORIES_NOT_ARRAY",message:`epic "${n}" has non-array \`stories\` field (expected string[] of story IDs)`});break}}const a=i.epics&&typeof i.epics=="object"&&Object.keys(i.epics).length>0||i.stories&&typeof i.stories=="object"&&!Array.isArray(i.stories)&&Object.keys(i.stories).length>0||Array.isArray(i.stories)||r&&r.current!==void 0;return i.schema_version===void 0?a&&t.push({code:"SCHEMA_VERSION_MISSING",message:"`schema_version` field missing (expected: `schema_version: 1`)"}):i.schema_version!==1&&t.push({code:"SCHEMA_VERSION_OUTDATED",message:`schema_version=${String(i.schema_version)} (expected: 1)`}),t}function Ko(e){if(!(Kn||e.length===0)){Kn=!0;try{const t=e.map(i=>` - ${i.message}`).join(`
|
|
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 kd(){zn=!1}function ti(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Go(e){return e==="active"||e==="archived"||e==="rolled-back"||e==="synthetic"||e==="orphan"?e:void 0}const Yo=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"]),Fo=/(?:[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 qo(e,t){if(!g(e)||e.schemaVersion!==1||e.epicId!==t||!/^P\d+$/.test(t))return{};try{const i=JSON.stringify(e),r=Buffer.byteLength(i);if(r>16384)return{diagnostic:Object.freeze({schemaVersion:"CreateEpicPlanningProjectionDiagnostic/1.0",outcome:"omitted",reasonCode:"budget-omitted",byteLengthBucket:r<=32768?"16385-32768":"32769-plus",publicSafe:!0})};if(Fo.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=>!Yo.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"?ra:512))return{}}else if(typeof d!="boolean"||!["uiScope","remediationStory"].includes(o))return{};const n=["schemaVersion","kind","epicId","intakeRevision","artifactSummary","artifactDigest","predecessorReceiptId","accepted","receiptId"];for(const o of[e.diagnosisReceipt,e.researchReceipt])if(o!==void 0){if(!g(o))return{};if(a(o,n),Object.values(o).some(d=>typeof d=="string"&&d.length>1024))return{}}if(e.degradeAuthorization!==void 0){if(!g(e.degradeAuthorization))return{};a(e.degradeAuthorization,["approved","intakeRevision","reasonCodes","assumptionCodes"]);for(const o of["reasonCodes","assumptionCodes"]){const d=e.degradeAuthorization[o];if(!Array.isArray(d)||d.length>32||d.some(s=>typeof s!="string"||s.length>128))return{}}}return{checkpoint:JSON.parse(i)}}catch{return{}}}function ni(e){return e==="create-epic"||e==="discovered"?e:void 0}function Se(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function zo(e){const t={};let i=!1;for(const r of["contracts","contract_refs","shared_surfaces","adr_refs","nfr_refs","acceptance_depends_on"]){if(e[r]===void 0)continue;const a=e[r];if(!Array.isArray(a)||a.length>128||a.some(n=>hn(n)===void 0)){i=!0;continue}t[r]=a.map(n=>hn(n))}if(e.planning!==void 0)try{if(!g(e.planning))throw new Error("planning-shape");const r=e.planning;for(const o of["claims","semanticArtifacts"]){if(r[o]===void 0)continue;const d=r[o];if(!Array.isArray(d)||d.length>128||d.some(s=>!g(s)||hn(s.ref)===void 0))throw new Error("planning-refs")}if(r.attempts!==void 0&&(!Array.isArray(r.attempts)||r.attempts.length>32))throw new Error("planning-attempts");for(const o of r.attempts??[]){if(!g(o)||!Array.isArray(o.reasonCodes)||o.reasonCodes.length>32||o.reasonCodes.some(d=>typeof d!="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(d)))throw new Error("planning-attempt-reasons");if(o.discoveredClaims!==void 0&&(!Array.isArray(o.discoveredClaims)||o.discoveredClaims.length>128||o.discoveredClaims.some(d=>!g(d)||hn(d.ref)===void 0)))throw new Error("planning-attempt-claims")}const{graphRevision:a,...n}=eo(r);t.planning=n}catch{i=!0}return i&&(t.planning={schemaVersion:1,dependencyBasis:"unknown",claims:[],semanticArtifacts:[]}),t}function g(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function St(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function te(e){if(typeof e!="string")return;const t=e.trim();if(t)return t.replace(/[^a-z0-9_.:-]+/gi,"_").slice(0,120)}function K(e){if(typeof e!="string")return;const t=e.trim(),i=te(e);return i===t?i:void 0}function ve(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240)&&/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(t)&&!(t.includes("..")||t.includes("//")||t.includes("@{")||t.endsWith("/")||t.endsWith("."))&&!t.split("/").some(i=>!i||i.startsWith(".")||i.endsWith(".lock")))return t}function R(e){return typeof e=="string"&&/^[0-9a-f]{7,64}$/i.test(e)?e:void 0}function Oe(e){if(!(typeof e!="string"||e.length>64)&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/.test(e))return Number.isFinite(Date.parse(e))?e:void 0}function ct(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240||t.includes("..")))return/^[A-Za-z0-9._:/#\-[\]]+$/.test(t)?t:void 0}function In(e){if(!g(e))return;const t=u=>typeof u=="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,95}$/.test(u),i=u=>typeof u=="string"&&/^[a-f0-9]{64}$/.test(u),r=(u,C)=>Array.isArray(u)&&u.length<=C&&u.every(t)&&new Set(u).size===u.length?u:void 0,a=(u,C)=>{if(!(!g(u)||u.schemaVersion!==2||!t(u.requestId)||!t(u.stageCommand)||!i(u.requestHash)||!i(u.inputHash)||!i(u.stateHash)||!i(u.nonce)||!i(u.stageRevision)||!i(u.stageHash)||!i(u.catalogHash)||u.targetEpicId!==void 0&&!t(u.targetEpicId)||C&&(!i(u.outputHash)||!i(u.artifactHash))))return{schemaVersion:2,...u.targetEpicId?{targetEpicId:u.targetEpicId}:{},requestId:u.requestId,requestHash:u.requestHash,inputHash:u.inputHash,stateHash:u.stateHash,nonce:u.nonce,stageCommand:u.stageCommand,stageRevision:u.stageRevision,stageHash:u.stageHash,catalogHash:u.catalogHash,...C?{outputHash:u.outputHash,artifactHash:u.artifactHash}:{}}},n=(u,C)=>{if(!(!g(u)||u.schemaVersion!=="1.1"||u.kind!==C||!i(u.receiptId)||!i(u.graphHash)||!i(u.evidenceHash)||!t(u.elementId)||!t(u.caseId)||!t(u.category)))return{schemaVersion:"1.1",kind:C,receiptId:u.receiptId,graphHash:u.graphHash,elementId:u.elementId,caseId:u.caseId,category:u.category,evidenceHash:u.evidenceHash}},o=(u,C)=>{if(!g(u)||u.kind!==C||!i(u.receiptId)||!r(u.evidenceIds,24)||C==="architecture-stage-completion"&&!["succeeded","failed"].includes(String(u.status))||C==="architecture-stage-validation"&&!["passed","failed","pending"].includes(String(u.status)))return;const E=a(u,!0);if(!E)return;const h=C==="architecture-stage-validation"?n(u.isolated,"isolated"):void 0,I=C==="architecture-stage-validation"?n(u.regression,"regression"):void 0;if(!(C==="architecture-stage-validation"&&(!h||!I)))return{...E,kind:C,receiptId:u.receiptId,status:u.status,evidenceIds:u.evidenceIds,...h&&I?{isolated:h,regression:I}:{}}},d={};e.schemaVersion===1&&(d.schemaVersion=1),e.owner==="root"&&(d.owner="root"),t(e.currentStageCommand)&&(d.currentStageCommand=e.currentStageCommand),["ask-user","delegate","resume","advance","blocked","complete"].includes(String(e.continuationState))&&(d.continuationState=e.continuationState);const s=r(e.questionIds,16);if(s&&(d.questionIds=s),(e.childStatus==="succeeded"||e.childStatus==="failed")&&(d.childStatus=e.childStatus),(e.evidencePolicy==="legacy-compatible"||e.evidencePolicy==="v2-required")&&(d.evidencePolicy=e.evidencePolicy),t(e.targetEpicId)&&(d.targetEpicId=e.targetEpicId),i(e.graphRevision)&&(d.graphRevision=e.graphRevision),e.graphSource==="committed-epic-v1"&&(d.graphSource=e.graphSource),e.nonUiScopeReceipt!==void 0){const u=yr(e.nonUiScopeReceipt);if(!u||u.targetEpicId!==e.targetEpicId||u.graphRevision!==e.graphRevision||!g(e.accounting)||u.accountingId!==e.accounting.accountingId||!g(e.evidenceExpectation)||u.rootInputSha256!==e.evidenceExpectation.inputHash)throw new Error("architecture-non-ui-scope-invalid");d.nonUiScopeReceipt=u}g(e.pactAnswerReceipt)&&Object.keys(e.pactAnswerReceipt).sort().join(",")===["schemaVersion","targetEpicId","graphRevision","stateSha256","answersSha256","questionIds","publicSafe"].sort().join(",")&&e.pactAnswerReceipt.schemaVersion==="PactAnswerReceipt/1"&&e.pactAnswerReceipt.targetEpicId===e.targetEpicId&&e.pactAnswerReceipt.graphRevision===e.graphRevision&&i(e.pactAnswerReceipt.stateSha256)&&i(e.pactAnswerReceipt.answersSha256)&&v(e.pactAnswerReceipt.questionIds,["PACT-Q1-CONSUMER","PACT-Q2-PROVIDER","PACT-Q3-BROKER","PACT-Q4-MATCHERS","PACT-Q5-VERIFY"])&&e.pactAnswerReceipt.publicSafe===!0&&(d.pactAnswerReceipt=e.pactAnswerReceipt);const l=a(e.evidenceExpectation,!1);l&&(d.evidenceExpectation=l);const y=o(e.completionEvidence,"architecture-stage-completion"),S=o(e.validationEvidence,"architecture-stage-validation");if(y&&(d.completionEvidence=y),S&&(d.validationEvidence=S),g(e.reviewDecision)&&Object.keys(e.reviewDecision).sort().join(",")===["schemaVersion","targetEpicId","graphRevision","artifactHash","completionReceiptId","validationReceiptId","decision","evidenceIds","publicSafe"].sort().join(",")&&e.reviewDecision.schemaVersion==="ArchitectureReviewDecision/1"&&e.reviewDecision.targetEpicId===e.targetEpicId&&e.reviewDecision.graphRevision===e.graphRevision&&i(e.reviewDecision.graphRevision)&&i(e.reviewDecision.artifactHash)&&i(e.reviewDecision.completionReceiptId)&&i(e.reviewDecision.validationReceiptId)&&["approved","changes-requested"].includes(String(e.reviewDecision.decision))&&e.reviewDecision.publicSafe===!0){const u=r(e.reviewDecision.evidenceIds,24);u&&u.length>0&&(d.reviewDecision={...e.reviewDecision,evidenceIds:u})}if(Gt(e.terminalMemoryCheckpoint,e))d.terminalMemoryCheckpoint=e.terminalMemoryCheckpoint;else if(g(e.terminalMemoryCheckpoint)&&e.terminalMemoryCheckpoint.schemaVersion===void 0&&["passed","failed","pending"].includes(String(e.terminalMemoryCheckpoint.status))){const u=r(e.terminalMemoryCheckpoint.evidenceIds,24);u&&(d.terminalMemoryCheckpoint={status:e.terminalMemoryCheckpoint.status,evidenceIds:u})}if(Array.isArray(e.acceptedStages)&&e.acceptedStages.length<=15){const u=e.acceptedStages.map(C=>{if(!g(C)||!t(C.targetEpicId)||!t(C.stageCommand))return;const E=o(C.completionEvidence,"architecture-stage-completion"),h=o(C.validationEvidence,"architecture-stage-validation");return E&&h?{targetEpicId:C.targetEpicId,stageCommand:C.stageCommand,completionEvidence:E,validationEvidence:h}:void 0});u.every(C=>C!==void 0)&&(d.acceptedStages=u)}if(g(e.accounting)&&e.accounting.schemaVersion===1&&t(e.accounting.contractVersion)&&t(e.accounting.accountingId)&&typeof e.accounting.charged=="boolean"&&Number.isInteger(e.accounting.chargedQuotaUnits)&&typeof e.accounting.chargedQuotaUnits=="number"&&e.accounting.chargedQuotaUnits>=0&&e.accounting.chargedQuotaUnits<=13){const u=r(e.accounting.receiptIds,32);u&&(d.accounting={schemaVersion:1,contractVersion:e.accounting.contractVersion,accountingId:e.accounting.accountingId,charged:e.accounting.charged,chargedQuotaUnits:e.accounting.chargedQuotaUnits,receiptIds:u,...["in-progress","aborted","timed-out","failed","complete"].includes(String(e.accounting.lastOutcome))?{lastOutcome:e.accounting.lastOutcome}:{}})}return JSON.stringify(d).length<=96e3?d:void 0}function Jo(e){const t=g(e.metadata.archPlan)?e.metadata.archPlan.execution:void 0,i=g(t)?t.checkpoint:void 0,r=g(t)?t:void 0,a=g(i)?i:void 0,n=e.requestExecution,o=Array.isArray(a?.acceptedStages)?a.acceptedStages:[],d=n.currentStageCommand==="arch-prd"&&n.continuationState==="delegate"&&n.completionEvidence===void 0&&n.validationEvidence===void 0&&a?.currentStageCommand==="arch-prd"&&a.continuationState==="delegate"&&o.length===0&&r?.nextAction==="delegate",s=n.currentStageCommand==="arch-prd"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-architecture"&&a.continuationState==="advance"&&o.length===1&&g(o[0])&&o[0].stageCommand==="arch-prd"&&v(o[0].completionEvidence,n.completionEvidence)&&v(o[0].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",l=n.currentStageCommand==="arch-architecture"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-architecture"&&a.continuationState==="delegate"&&o.length===1&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",y=n.currentStageCommand==="arch-architecture"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-fitness-functions"&&a.continuationState==="advance"&&o.length===2&&g(o[0])&&g(o[1])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===1&&v(o[0],n.acceptedStages[0])&&v(o[1].completionEvidence,n.completionEvidence)&&v(o[1].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",S=n.currentStageCommand==="arch-fitness-functions"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-fitness-functions"&&a.continuationState==="delegate"&&o.length===2&&g(o[0])&&g(o[1])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",u=n.currentStageCommand==="arch-fitness-functions"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-api-contracts"&&a.continuationState==="advance"&&o.length===3&&g(o[0])&&g(o[1])&&g(o[2])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&o[2].stageCommand==="arch-fitness-functions"&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===2&&v(o.slice(0,2),n.acceptedStages)&&v(o[2].completionEvidence,n.completionEvidence)&&v(o[2].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",C=n.currentStageCommand==="arch-api-contracts"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-api-contracts"&&a.continuationState==="delegate"&&o.length===3&&g(o[0])&&g(o[1])&&g(o[2])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&o[2].stageCommand==="arch-fitness-functions"&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",E=["PACT-Q1-CONSUMER","PACT-Q2-PROVIDER","PACT-Q3-BROKER","PACT-Q4-MATCHERS","PACT-Q5-VERIFY"],h=n.currentStageCommand==="arch-api-contracts"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="generate-pacts"&&a.continuationState==="ask-user"&&o.length===4&&g(o[3])&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===3&&v(o.slice(0,3),n.acceptedStages)&&o[3].stageCommand==="arch-api-contracts"&&v(o[3].completionEvidence,n.completionEvidence)&&v(o[3].validationEvidence,n.validationEvidence)&&v(a.questionIds,E)&&v(r?.questionIds,E)&&r?.nextAction==="ask-user",I=n.currentStageCommand==="generate-pacts"&&n.continuationState==="ask-user"&&a?.currentStageCommand==="generate-pacts"&&a.continuationState==="delegate"&&o.length===4&&v(o,n.acceptedStages)&&v(n.questionIds,E)&&v(a.questionIds,[])&&v(a.pactAnswerReceipt,e.answerReceipt)&&v(r?.pactAnswerReceipt,e.answerReceipt)&&e.answerReceipt?.stateSha256===e.sourceStateSha256&&r?.nextAction==="resume",b=n.currentStageCommand==="generate-pacts"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&v(n.pactAnswerReceipt,e.pactRecordedReceipt)&&a?.currentStageCommand==="arch-api-integrations"&&a.continuationState==="advance"&&o.length===5&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===4&&v(o.slice(0,4),n.acceptedStages)&&o.map(B=>g(B)?B.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts"&&g(o[4])&&v(o[4].completionEvidence,n.completionEvidence)&&v(o[4].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",L=n.currentStageCommand==="arch-api-integrations"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-api-integrations"&&a.continuationState==="delegate"&&o.length===5&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",T=n.currentStageCommand==="arch-api-integrations"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-database"&&a.continuationState==="advance"&&o.length===6&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===5&&v(o.slice(0,5),n.acceptedStages)&&o.map(B=>g(B)?B.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations"&&g(o[5])&&v(o[5].completionEvidence,n.completionEvidence)&&v(o[5].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",P=n.currentStageCommand==="arch-database"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-database"&&a.continuationState==="delegate"&&o.length===6&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",_=n.currentStageCommand==="arch-database"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-security"&&a.continuationState==="advance"&&o.length===7&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===6&&v(o.slice(0,6),n.acceptedStages)&&o.map(B=>g(B)?B.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database"&&g(o[6])&&v(o[6].completionEvidence,n.completionEvidence)&&v(o[6].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",w=n.currentStageCommand==="arch-security"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-security"&&a.continuationState==="delegate"&&o.length===7&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",M=n.currentStageCommand==="arch-security"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-design-system"&&a.continuationState==="advance"&&o.length===8&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===7&&v(o.slice(0,7),n.acceptedStages)&&o.map(B=>g(B)?B.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security"&&g(o[7])&&v(o[7].completionEvidence,n.completionEvidence)&&v(o[7].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",N=n.currentStageCommand==="arch-design-system"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-design-system"&&a.continuationState==="delegate"&&o.length===8&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",z=n.currentStageCommand==="arch-design-system"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-ux-design"&&a.continuationState==="advance"&&o.length===9&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===8&&v(o.slice(0,8),n.acceptedStages)&&o.map(B=>g(B)?B.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system"&&g(o[8])&&v(o[8].completionEvidence,n.completionEvidence)&&v(o[8].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",Z=n.currentStageCommand==="arch-ux-design"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-ux-design"&&a.continuationState==="delegate"&&o.length===9&&v(o,n.acceptedStages)&&r?.nextAction==="blocked",j=n.currentStageCommand==="arch-ux-design"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-performance"&&a.continuationState==="advance"&&o.length===10&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===9&&v(o.slice(0,9),n.acceptedStages)&&o.map(B=>g(B)?B.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design"&&g(o[9])&&v(o[9].completionEvidence,n.completionEvidence)&&v(o[9].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",V=n.currentStageCommand==="arch-performance"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-performance"&&a.continuationState==="delegate"&&o.length===10&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",ee=n.currentStageCommand==="arch-performance"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-testing"&&a.continuationState==="advance"&&o.length===11&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===10&&v(o.slice(0,10),n.acceptedStages)&&o.map(B=>g(B)?B.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance"&&g(o[10])&&v(o[10].completionEvidence,n.completionEvidence)&&v(o[10].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",W=n.currentStageCommand==="arch-testing"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-testing"&&a.continuationState==="delegate"&&o.length===11&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",lt=n.currentStageCommand==="arch-testing"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-infrastructure"&&a.continuationState==="advance"&&o.length===12&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===11&&v(o.slice(0,11),n.acceptedStages)&&o.map(B=>g(B)?B.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance,arch-testing"&&g(o[11])&&v(o[11].completionEvidence,n.completionEvidence)&&v(o[11].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",Fe=n.currentStageCommand==="arch-infrastructure"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-infrastructure"&&a.continuationState==="delegate"&&o.length===12&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",he=n.currentStageCommand==="arch-infrastructure"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-review"&&a.continuationState==="advance"&&o.length===13&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===12&&v(o.slice(0,12),n.acceptedStages)&&o.map(B=>g(B)?B.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance,arch-testing,arch-infrastructure"&&g(o[12])&&v(o[12].completionEvidence,n.completionEvidence)&&v(o[12].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",O=n.currentStageCommand==="arch-review"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-review"&&a.continuationState==="delegate"&&o.length===13&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",H=n.currentStageCommand==="arch-review"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&n.reviewDecision===void 0&&a?.currentStageCommand==="arch-review"&&a.continuationState==="ask-user"&&o.length===13&&v(o,n.acceptedStages)&&v(a.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&v(a.completionEvidence,n.completionEvidence)&&v(a.validationEvidence,n.validationEvidence)&&r?.nextAction==="ask-user",Ct=n.currentStageCommand==="arch-review"&&n.continuationState==="ask-user"&&n.childStatus==="succeeded"&&g(n.reviewDecision)&&n.reviewDecision.decision==="approved"&&v(n.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&a?.currentStageCommand==="update-memory"&&a.continuationState==="advance"&&o.length===14&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===13&&v(o.slice(0,13),n.acceptedStages)&&g(o[13])&&o[13].stageCommand==="arch-review"&&v(o[13].completionEvidence,n.completionEvidence)&&v(o[13].validationEvidence,n.validationEvidence)&&v(a.reviewDecision,n.reviewDecision)&&r?.nextAction==="resume",De=n.currentStageCommand==="update-memory"&&n.continuationState==="advance"&&g(n.reviewDecision)&&n.reviewDecision.decision==="approved"&&a?.currentStageCommand==="update-memory"&&a.continuationState==="delegate"&&o.length===14&&v(o,n.acceptedStages)&&v(a.reviewDecision,n.reviewDecision)&&r?.nextAction==="delegate",se=n.currentStageCommand==="update-memory"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="update-memory"&&a.continuationState==="complete"&&o.length===15&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===14&&v(o.slice(0,14),n.acceptedStages)&&g(o[14])&&o[14].targetEpicId===n.targetEpicId&&o[14].stageCommand==="update-memory"&&v(o[14].completionEvidence,n.completionEvidence)&&v(o[14].validationEvidence,n.validationEvidence)&&v(a.reviewDecision,n.reviewDecision)&&v(a.completionEvidence,n.completionEvidence)&&v(a.validationEvidence,n.validationEvidence)&&Gt(a.terminalMemoryCheckpoint,n)!==null&&v(a.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)&&r?.nextAction==="complete",tt=n.currentStageCommand==="update-memory"&&n.continuationState==="complete"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="update-memory"&&a.continuationState==="complete"&&o.length===15&&v(o,n.acceptedStages)&&v(a.reviewDecision,n.reviewDecision)&&v(a.completionEvidence,n.completionEvidence)&&v(a.validationEvidence,n.validationEvidence)&&Gt(a.terminalMemoryCheckpoint,n)&&v(a.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)&&r?.nextAction==="complete",ut=r?Yi(n,r,Gt(n.terminalMemoryCheckpoint,n)&&v(a?.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)):void 0;if(e.metadata.mode!=="arch-plan"||e.metadata.resolvedTrigger!=="arch-plan"||!g(t)||!g(i)||t.owner!=="root"||t.currentStageCommand!==i.currentStageCommand||t.continuationState!==i.continuationState||i.owner!=="root"||i.evidencePolicy!=="v2-required"||i.targetEpicId!==n.targetEpicId||i.graphRevision!==n.graphRevision||i.graphSource!==n.graphSource||!/^P[1-9][0-9]{0,11}$/.test(String(i.targetEpicId))||!/^[a-f0-9]{64}$/.test(String(i.graphRevision))||!Array.isArray(i.acceptedStages)||!(ut||d||s||l||y||S||u||C||h||I||b||L||T||P||_||w||M||N||z||Z||j||V||ee||W||lt||Fe||he||O||H||Ct||De||se||tt)||!g(i.accounting)||i.accounting.charged!==!0||!v(In(i),i))throw new Error("architecture-root-checkpoint-invalid");const X=Q(e.projectRoot,".neocortex"),ye=Q(X,"state.json"),le=Q(X,"state.json.architecture.lock"),Nt=qt(le,"wx",384);let Re;try{const B=jt(ye);if(!B.isFile()||B.isSymbolicLink())throw new Error("architecture-root-state-binding-invalid");const je=Ge(ye,"utf8");if(Pe("sha256").update(je).digest("hex")!==e.sourceStateSha256)throw new Error("architecture-root-state-conflict");const J=JSON.parse(je),ge=g(J)&&g(J.archPlan)?J.archPlan:{};if(!g(J)||!g(J.epics)||!Object.hasOwn(J.epics,i.targetEpicId)||(e.initialBinding?ge.execution!==void 0||n.graphSource!=="committed-epic-v1":!v(In(ge.execution),n))||g(J.scope)&&J.scope.kind==="projected")throw new Error("architecture-root-state-binding-invalid");if(n.graphSource==="committed-epic-v1"&&n.graphRevision!==Yt(e.projectRoot,String(n.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");if(tt||ut==="complete-replay"){const f={...n,continuationState:"delegate",acceptedStages:n.acceptedStages.slice(0,mr(n))};if(!v(n.terminalMemoryCheckpoint,On(e.projectRoot,f)))throw new Error("architecture-root-state-conflict");return}const Ve=dn(),ne=We("git",["rev-parse","--git-common-dir"],{cwd:e.projectRoot,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),_t=Qi(ne)?Ln(ne):Ln(e.projectRoot,ne);if(Ki(_t)!==_t)throw new Error("architecture-root-backup-dir-invalid");const qe=Q(_t,"neocortex-architecture");Ft(qe,{recursive:!0,mode:448});const Ie=jt(qe);if(!Ie.isDirectory()||Ie.isSymbolicLink()||Ie.uid!==process.getuid?.()||(Ie.mode&63)!==0)throw new Error("architecture-root-backup-dir-invalid");const ht=Q(qe,`state-backup-${Ve}.json`),G=qt(ht,"wx",384);try{pn(G,je),ln(G)}finally{zt(G)}const tn=qt(qe,"r");try{ln(tn)}finally{zt(tn)}const Rt={...J,archPlan:{...ge,execution:i}};Re=Q(X,`state.json.architecture-tmp-${Ve}`);const k=qt(Re,"wx",384);try{pn(k,`${JSON.stringify(Rt,null,2)}
|
|
8
|
-
`),ln(k)}finally{zt(k)}if((se||ut==="complete")&&!v(n.terminalMemoryCheckpoint,On(e.projectRoot,n)))throw new Error("architecture-root-state-conflict");if(n.graphSource==="committed-epic-v1"&&n.graphRevision!==Yt(e.projectRoot,String(n.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");Er(Re,ye),Re=void 0;const wt=qt(X,"r");try{ln(wt)}finally{zt(wt)}}finally{if(Re)try{Nn(Re)}catch{}zt(Nt),Nn(le)}}function En(e,t){if(!g(e))return;const i={};for(const r of t){const a=e[r];if(typeof a=="boolean")i[r]=a;else if(typeof a=="number"&&Number.isFinite(a))i[r]=a;else if(typeof a=="string"){const n=te(a);n&&(i[r]=n)}}return Object.keys(i).length>0?i:void 0}function Sn(e){return e==="epic"||e==="story"?e:void 0}function ri(e){if(!g(e)||e.schemaVersion!==1)return;const t=K(e.ownerStoryId),i=K(e.sessionId),r=K(e.idempotencyKey),a=Oe(e.acquiredAt),n=Oe(e.expiresAt);if(!(!t||!i||!r||!a||!n||Date.parse(n)<=Date.parse(a)))return{schemaVersion:1,ownerStoryId:t,sessionId:i,idempotencyKey:r,acquiredAt:a,expiresAt:n}}function ii(e){if(!g(e)||e.schemaVersion!==1)return;const t=K(e.storyId),i=K(e.epicId),r=ve(e.branch),a=R(e.baseSha),n=R(e.headSha),o=K(e.idempotencyKey),d=Oe(e.recordedAt),s=Se(e.commits).map(R).filter(L=>!!L).slice(0,256),l=Se(e.receiptRefs).map(ct).filter(L=>!!L).slice(0,256),y=e.dispatchId===void 0?void 0:K(e.dispatchId),S=e.bundleId===void 0?void 0:K(e.bundleId),u=e.bundleDigest===void 0?void 0:R(e.bundleDigest),C=e.graphRevision===void 0?void 0:R(e.graphRevision),E=e.claimRevision===void 0?void 0:K(e.claimRevision),h=Ko(e.qaReceipt),I=Qo(e.reviewReceipt),b=e.rootMemoryEffect===void 0?void 0:go(e.rootMemoryEffect)?e.rootMemoryEffect:void 0;if(!(!t||!i||!t.startsWith(`${i}.`)||!r||!a||!n||a===n||!o||!d||s.length===0||l.length===0||!Array.isArray(e.commits)||s.length!==e.commits.length||e.commits.length>256||!Array.isArray(e.receiptRefs)||l.length!==e.receiptRefs.length||e.receiptRefs.length>256||e.dispatchId!==void 0&&!y||e.bundleId!==void 0&&!S||e.bundleDigest!==void 0&&(!u||u.length!==64)||e.graphRevision!==void 0&&(!C||C.length!==64)||e.claimRevision!==void 0&&!E||e.rootMemoryEffect!==void 0&&(!b||b.storyId!==t||b.epicId!==i||b.executionBranch!==r||b.sourceHeadSha!==a||b.childClaimRevision!==E)||e.qaVerdict!=="passed"&&e.qaVerdict!=="blocked"||!["approved","changes-requested","pending"].includes(String(e.reviewVerdict))||!h||e.reviewVerdict!=="pending"&&!I||e.reviewVerdict==="pending"&&I||h.verdict!==e.qaVerdict||I&&I.verdict!==e.reviewVerdict||!ci(h,{storyId:t,epicId:i,baseSha:a,headSha:n,bundleDigest:u,graphRevision:C})||I&&(!ci(I,{storyId:t,epicId:i,baseSha:a,headSha:n,bundleDigest:u,graphRevision:C})||I.qaReceiptRef!==h?.receiptRef||I.receiptRef===h?.receiptRef)||!l.includes(String(h.receiptRef))||I&&(!l.includes(String(I.receiptRef))||Date.parse(String(I.reviewedAt))<Date.parse(String(h.checkedAt)))))return{schemaVersion:1,storyId:t,epicId:i,branch:r,baseSha:a,headSha:n,idempotencyKey:o,...y?{dispatchId:y}:{},...S?{bundleId:S}:{},...u?{bundleDigest:u}:{},...C?{graphRevision:C}:{},...E?{claimRevision:E}:{},...b?{rootMemoryEffect:structuredClone(b)}:{},qaVerdict:e.qaVerdict,reviewVerdict:e.reviewVerdict,...h?{qaReceipt:h}:{},...I?{reviewReceipt:I}:{},recordedAt:d,commits:s,receiptRefs:l}}function Ko(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=K(e.storyId),i=K(e.epicId),r=R(e.baseSha),a=R(e.headSha),n=R(e.bundleDigest),o=R(e.graphRevision),d=R(e.sourceEvidenceDigest),s=Oe(e.checkedAt),l=ct(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"?Se(e.gateIds).map(K).filter(h=>!!h).slice(0,64):void 0;if(!(!t||!i||!r||!a||!n||n.length!==64||!o||o.length!==64||!d||d.length!==64||!s||!l||e.evidenceVersion==="p205-execution-v2"&&(!y||S!=="node scripts/test-root.mjs --gate complete"||!u||u.length!==64||!C||C.length!==64||!Array.isArray(e.gateIds)||!E||E.length===0||E.length!==e.gateIds.length)))return{schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",...e.evidenceVersion?{evidenceVersion:e.evidenceVersion}:{},storyId:t,epicId:i,...e.evidenceVersion==="p205-execution-v2"?{contract:y,command:S,manifestDigest:u,gateIds:E,resultDigest:C}:{},baseSha:r,headSha:a,bundleDigest:n,graphRevision:o,sourceEvidenceDigest:d,verdict:e.verdict,checkedAt:s,receiptRef:l}}function ai(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=K(e.storyId),i=K(e.epicId),r=ve(e.branch),a=R(e.baseSha),n=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=Se(e.gateIds).map(K).filter(P=>!!P).slice(0,64),E=R(e.resultDigest),h=R(e.graphRevision),I=R(e.executionEvidenceDigest),b=R(e.sourceEvidenceDigest),L=Oe(e.verifiedAt),T=Se(e.reasonCodes).map(K).filter(P=>!!P).slice(0,16);if(!(!t||!i||!r||!a||a.length<40||!n||n.length<40||!o||o.length<40||!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||!L||T.length===0||e.verdict==="verified"&&(C.length===0||!T.includes("checkpoint-p205-transient-verified"))))return{schemaVersion:1,kind:"story_checkpoint_physical_verification",producer:"client-p205-transient-v1",storyId:t,epicId:i,branch:r,baseSha:a,headSha:n,aggregateHeadSha:o,commitBodyDigest:d,changedPathsDigest:s,claimVerification:l,effectiveClaimRevision:y,command:S,manifestDigest:u,gateIds:C,resultDigest:E,graphRevision:h,executionEvidenceDigest:I,sourceEvidenceDigest:b,verifiedAt:L,verdict:e.verdict,reasonCodes:T,publicSafe:!0}}function oi(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=K(e.storyId),r=K(e.epicId),a=ve(e.branch),n=R(e.baseSha),o=R(e.headSha),d=R(e.graphRevision),s=R(e.effectiveClaimRevision),l=R(e.sourceEvidenceDigest),y=Oe(e.verifiedAt),S=Se(e.reasonCodes).map(K).filter(u=>!!u);if(!(!i||!r||!a||!n||n.length<40||!o||o.length<40||!d||d.length!==64||!s||s.length!==64||!l||l.length!==64||!y||!Array.isArray(e.reasonCodes)||S.length!==1||S[0]!=="checkpoint-git-scheduling-verified"))return{schemaVersion:1,kind:"story_scheduling_checkpoint_evidence",producer:"client-git-physical-v1",storyId:i,epicId:r,branch:a,baseSha:n,headSha:o,graphRevision:d,effectiveClaimRevision:s,sourceEvidenceDigest:l,verifiedAt:y,reasonCodes:S,integrationAuthorized:!1,publicSafe:!0}}function Qo(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=K(e.storyId),i=K(e.epicId),r=R(e.baseSha),a=R(e.headSha),n=R(e.bundleDigest),o=R(e.graphRevision),d=R(e.sourceEvidenceDigest),s=ct(e.qaReceiptRef),l=Oe(e.reviewedAt),y=ct(e.receiptRef);if(!(!t||!i||!r||!a||!n||n.length!==64||!o||o.length!==64||!d||d.length!==64||!s||!l||!y))return{schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:t,epicId:i,baseSha:r,headSha:a,bundleDigest:n,graphRevision:o,sourceEvidenceDigest:d,qaReceiptRef:s,verdict:e.verdict,reviewedAt:l,receiptRef:y}}function ci(e,t){return["storyId","epicId","baseSha","headSha","bundleDigest","graphRevision"].every(i=>e[i]===t[i])}function si(e){if(!g(e)||e.schemaVersion!==1||e.capturedFromCurrentCheckout!==!0)return;const t=ve(e.originBranch),i=R(e.originHeadSha),r=ve(e.executionBranch),a=Oe(e.capturedAt);if(!(!t||!i||i.length<40||!r||!a||t===r))return{schemaVersion:1,originBranch:t,originHeadSha:i,executionBranch:r,capturedFromCurrentCheckout:!0,capturedAt:a}}function di(e){if(!g(e)||e.schemaVersion!==1||e.verdict!=="passed")return;const t=R(e.executionHeadSha),i=R(e.graphRevision),r=Oe(e.checkedAt),a=ct(e.receiptRef),n=Se(e.gateIds).map(K).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||!r||!a||n.length===0||!Array.isArray(e.gateIds)||n.length!==e.gateIds.length||e.gateIds.length>128||!d&&!o||o&&(!s||s.length!==64||!l||l.length!==64)))return{schemaVersion:1,...o?{evidenceVersion:"p205-execution-v2",producer:"local-yolo-tdd",contract:"P205-CI-02",command:"node scripts/test-root.mjs --gate complete",manifestDigest:s,resultDigest:l}:{},verdict:"passed",executionHeadSha:t,graphRevision:i,checkedAt:r,receiptRef:a,gateIds:n}}function pi(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:K(e.epicId),executionBranch:ve(e.executionBranch),originBranch:ve(e.originBranch),graphRevision:R(e.graphRevision),originHeadSha:R(e.originHeadSha),lastAcceptedCheckpointHeadSha:R(e.lastAcceptedCheckpointHeadSha),executionHeadSha:R(e.executionHeadSha),acceptedCheckpointIds:Se(e.acceptedCheckpointIds),acceptedCheckpointHeads:Se(e.acceptedCheckpointHeads),reconciliationCommitShas:Se(e.reconciliationCommitShas),commitRangeDigest:R(e.commitRangeDigest),changedPaths:Se(e.changedPaths),changedPathsDigest:R(e.changedPathsDigest),allowedWriteSet:Se(e.allowedWriteSet),allowedWriteSetDigest:R(e.allowedWriteSetDigest),aggregateReceiptRef:ct(e.aggregateReceiptRef),aggregateManifestDigest:R(e.aggregateManifestDigest),aggregateResultDigest:R(e.aggregateResultDigest),producedAt:Oe(e.producedAt),revalidatedAt:Oe(e.revalidatedAt),publicSafe:!0};if(!t.epicId||!t.executionBranch||!t.originBranch||!t.graphRevision||t.graphRevision.length!==64||!t.originHeadSha||t.originHeadSha.length<40||!t.lastAcceptedCheckpointHeadSha||t.lastAcceptedCheckpointHeadSha.length<40||!t.executionHeadSha||t.executionHeadSha.length<40||t.acceptedCheckpointIds.length===0||t.acceptedCheckpointIds.length>2048||t.acceptedCheckpointIds.length!==t.acceptedCheckpointHeads.length||t.acceptedCheckpointHeads.some(a=>!/^[a-f0-9]{40,64}$/i.test(a))||t.reconciliationCommitShas.length>2048||t.reconciliationCommitShas.some(a=>!/^[a-f0-9]{40,64}$/i.test(a))||t.changedPaths.length>2048||(t.lastAcceptedCheckpointHeadSha===t.executionHeadSha?t.reconciliationCommitShas.length!==0||t.changedPaths.length!==0:t.reconciliationCommitShas.length===0||t.changedPaths.length===0)||t.allowedWriteSet.length===0||t.allowedWriteSet.length>2048||!t.commitRangeDigest||!t.changedPathsDigest||!t.allowedWriteSetDigest||!t.aggregateReceiptRef||!t.aggregateManifestDigest||!t.aggregateResultDigest||!t.producedAt||!t.revalidatedAt||t.commitRangeDigest!==no(t.lastAcceptedCheckpointHeadSha,t.executionHeadSha,t.reconciliationCommitShas)||t.changedPathsDigest!==jr(t.changedPaths)||t.allowedWriteSetDigest!==jr(t.allowedWriteSet))return;const i=t,r=R(e.inputDigest);if(!(!r||r.length!==64||r!==to(i)))return{...i,inputDigest:r}}function Jn(e){if(!g(e)||e.schemaVersion!==1)return;const t=En(e,["schemaVersion","kind","storyId","epicId","baseSha","headSha","originalBaseSha","originalHeadSha","gitPullRequest","preservesLaterCommits","historyRewrite","recordedAt"])??{},i=Se(e.receiptRefs).map(ct).filter(a=>!!a).slice(0,256),r=Se(e.revertCommits).map(te).filter(a=>!!a).slice(0,256);return{...t,...i.length?{receiptRefs:i}:{},...r.length?{revertCommits:r}:{}}}function Xo(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 li(e){if(!g(e)||e.schemaVersion!==1||e.publicSafe!==!0)return;const t=K(e.epicId),i=ve(e.executionBranch),r=ve(e.originBranch),a=R(e.baseSha),n=R(e.executionHeadSha),o=e.mergeSha===void 0?void 0:R(e.mergeSha),d=e.pushedSha===void 0?void 0:R(e.pushedSha),s=K(e.idempotencyKey),l=Oe(e.attemptStartedAt),y=e.completedAt===void 0?void 0:Oe(e.completedAt),S=Se(e.localGateReceiptRefs).map(ct).filter(h=>!!h).slice(0,256),u=Se(e.reasonCodes).map(K).filter(h=>!!h).slice(0,64),C=ec(e.candidateQa),E=Zo(e.providerGuard);if(!(!t||!i||!r||!a||!n||!s||!l||S.length===0||u.length===0||!["direct","single_pr"].includes(String(e.strategy))||!["prepared","merged","pushed","denied_external_gate","blocked_local_or_repo"].includes(String(e.physicalStatus))||typeof e.retryEligible!="boolean"||e.providerGuard!==void 0&&!E||E&&(e.strategy!=="single_pr"||e.physicalStatus!=="pushed"||E.prHeadSha!==o||E.originHeadSha!==a)))return{schemaVersion:1,epicId:t,executionBranch:i,originBranch:r,baseSha:a,executionHeadSha:n,...o?{mergeSha:o}:{},...d?{pushedSha:d}:{},strategy:e.strategy,...St(e.prNumber)?{prNumber:St(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 Zo(e){if(!g(e)||e.schemaVersion!==1||e.provider!=="github"||e.publicSafe!==!0)return;const t=String(e.mode),i=String(e.source),r=t==="recovered_exact_tree"?i==="physical_recovery":t==="strict_up_to_date_expected_head"&&["branch_protection","ruleset","branch_protection_and_ruleset"].includes(i),a=R(e.prHeadSha),n=R(e.originHeadSha),o=Oe(e.checkedAt);if(!(!r||!a||!n||!o))return{schemaVersion:1,provider:"github",mode:t,source:i,prHeadSha:a,originHeadSha:n,checkedAt:o,publicSafe:!0}}function ec(e){if(!g(e)||e.schemaVersion!==1||e.kind!=="epic_merge_candidate_qa"||e.contract!=="P205-CI-02"||e.command!==Qt)return;const i=Object.fromEntries(["originHeadSha","executionHeadSha","mergeSha","treeSha","graphRevision","manifestDigest","resultDigest"].map(o=>[o,R(e[o])])),r=Oe(e.checkedAt),a=ct(e.receiptRef),n=Se(e.gateIds).filter(o=>/^[a-z0-9-]+$/.test(o)).slice(0,128);if(!(Object.values(i).some(o=>!o)||!r||!a||n.length===0))return{schemaVersion:1,kind:e.kind,contract:e.contract,command:e.command,...i,checkedAt:r,receiptRef:a,gateIds:n}}function tc(e){if(!g(e))return;const t={...te(e.active_epic_id??e.activeEpicId)?{active_epic_id:te(e.active_epic_id??e.activeEpicId)}:{},...te(e.active_story_id??e.activeStoryId)?{active_story_id:te(e.active_story_id??e.activeStoryId)}:{},...te(e.active_step_id??e.activeStepId)?{active_step_id:te(e.active_step_id??e.activeStepId)}:{},...te(e.session_id??e.sessionId)?{session_id:te(e.session_id??e.sessionId)}:{},...te(e.started_at??e.startedAt)?{started_at:te(e.started_at??e.startedAt)}:{}};return Object.keys(t).length>0?t:void 0}function nc(e){const t=En(e.completionEvidence??e.completion_evidence,["prNumber","pr_number","prState","pr_state","pullRequestState","merged","mergedAt","issueNumber","issue_number","issueState","issue_state","closedAt"]),i=En(e.issueCloseAudit??e.issue_close_audit,["schema_version","event","storyId","epicId","issueNumber","closedAt","publicSafe","rawLogStorage"]),r=En(e.scopedCiEvidence??e.scoped_ci_evidence,["schema_version","storyId","epicId","prNumber","finalState","publicSafe","rawLogStorage"]);return{...typeof e.merged=="boolean"?{merged:e.merged}:{},...typeof e.safeToContinueYoloop=="boolean"?{safeToContinueYoloop:e.safeToContinueYoloop}:{},...typeof e.mergeBlockedRemotely=="boolean"?{mergeBlockedRemotely:e.mergeBlockedRemotely}:{},...te(e.physicalMergeStatus)?{physicalMergeStatus:te(e.physicalMergeStatus)}:{},...te(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)?{pr_state:te(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)}:{},...te(e.issue_state??e.issueState??e.workflow_issue_state)?{issue_state:te(e.issue_state??e.issueState??e.workflow_issue_state)}:{},...St(e.issue_number??e.issueNumber)?{issue_number:St(e.issue_number??e.issueNumber)}:{},...t?{completionEvidence:t}:{},...i?{issueCloseAudit:i}:{},...r?{scopedCiEvidence:r}:{}}}class st extends Error{reasonCode;constructor(t){super(t),this.name="StateSnapshotIntegrityError",this.reasonCode=t}}const rc=new Set(["yolo","yoloop","finalize-epic","audit"]);function ui(e){return typeof e=="string"&&rc.has(e)}function Kn(e,t={}){const i=Q(e,".neocortex","state.json");if(!Mt(i))throw new st("git-lifecycle-state-missing");let r;try{r=JSON.parse(Ge(i,"utf8"))}catch{throw new st("git-lifecycle-state-corrupt")}if(!g(r)||!g(r.epics)||!g(r.stories))throw new st("git-lifecycle-state-shape-invalid");const a=Object.values(r.epics).some(n=>g(n)&&(n.branch_mode==="epic"||ve(n.execution_branch)!==void 0));if(a)try{gn(e,{required:!0})}catch(n){const o=n instanceof Error&&/^git-lifecycle-/.test(n.message)?n.message:"git-lifecycle-runtime-invalid";if(t.allowMissingRuntime&&o==="git-lifecycle-runtime-missing")return{lifecycleDeclared:!0,runtimeMissing:!0};throw new st(o)}return{lifecycleDeclared:a,runtimeMissing:!1}}function vn(e,t={}){const i=Q(e,".neocortex","state.json");if(!Mt(i)){if(t.epicAware&&!t.projectless)throw new st("git-lifecycle-state-missing");return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}let r,a;try{const E=Ge(i,"utf-8");a=Pe("sha256").update(E).digest("hex");const h=JSON.parse(E),I=g(h.epics)?h.epics:{},b=Object.values(I).some(w=>g(w)&&(w.branch_mode==="epic"||ve(w.execution_branch)!==void 0)),L=gn(e,{required:!!(t.epicAware&&b&&!t.projectless)});r=Vr(h,L);const T=g(r.stories)?r.stories:{},P=g(r.epics)?r.epics:{},_=g(h.stories)?h.stories:{};for(const[w,M]of Object.entries(T)){const N=g(M)?M:void 0;if(!N?.checkpoint)continue;const z=typeof N.epic_id=="string"?N.epic_id:w.split(".")[0],Z=g(P[z])?P[z]:void 0,j=ve(Z?.execution_branch);if(!j)continue;const V=ro(e,N.checkpoint,w,z,j,t.p205Authorities?.[w],Br(w,N,g(N.checkpoint)?N.checkpoint:void 0));if(V.kind==="integration-authorized")N.checkpoint_verification=V.verification,delete N.scheduling_checkpoint_evidence;else if(V.kind==="scheduling-only")N.scheduling_checkpoint_evidence=V.evidence,delete N.checkpoint,delete N.checkpoint_verification;else if(V.kind==="rejected"){N.checkpoint_verification=V.verification,delete N.scheduling_checkpoint_evidence;const ee=g(_[w])?_[w]:void 0;if(delete N.checkpoint,L.stories[w]?.checkpoint!==void 0)for(const W of["status","last_step","steps_completed"])ee&&Object.prototype.hasOwnProperty.call(ee,W)?N[W]=structuredClone(ee[W]):delete N[W];["done","completed","merged"].includes(String(N.status).toLowerCase())&&(N.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 st(h)}return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}try{const E=Ho(r);E.length>0&&Wo(E)}catch{}const n=r.config??r.project??{},o=r.stories??{},d={};for(const[E,h]of Object.entries(o)){const I=g(h.review_request)&&h.review_request.kind==="git-pull-request"?Xo(h.review_request):Jn(h.review_request);d[E]={id:h.id??E,title:h.title,epic_id:h.epic_id,status:h.status??"backlog",...ni(h.source)?{source:ni(h.source)}:{},steps_completed:h.steps_completed??[],last_step:h.last_step??null,branch_name:h.branch_name??null,pr_number:h.pr_number,...Sn(h.branch_mode)?{branch_mode:Sn(h.branch_mode)}:{},...ii(h.checkpoint)?{checkpoint:ii(h.checkpoint)}:{},...ai(h.checkpoint_verification)?{checkpoint_verification:ai(h.checkpoint_verification)}:{},...oi(h.scheduling_checkpoint_evidence)?{scheduling_checkpoint_evidence:oi(h.scheduling_checkpoint_evidence)}:{},...I?{review_request:I}:{},...Jn(h.rollback_receipt)?{rollback_receipt:Jn(h.rollback_receipt)}:{},...St(h.workflow_issue)?{workflow_issue:St(h.workflow_issue)}:{},...nc(h),depends_on:ti(h.depends_on),files_to_modify:Se(h.files_to_modify),...zo(h),risk:typeof h.risk=="string"?h.risk:void 0,blast_radius:typeof h.blast_radius=="number"?h.blast_radius:void 0}}const s=r.epics??{},l={};for(const[E,h]of Object.entries(s)){const I=Go(h.lifecycle_classification),b=qo(h.createEpicPlanning,E),L=b.checkpoint;let T,P,_,w;if(L&&g(h.createEpicPlanningClaim)&&typeof h.createEpicPlanningClaim.claimId=="string"&&g(h.createEpicPlanningPhysical))try{Sr(r,h.createEpicPlanningClaim.claimId,E,!0),T=JSON.parse(JSON.stringify(h.createEpicPlanningPhysical))}catch{}if(T&&g(h.createEpicPlanningClaim)&&typeof h.createEpicPlanningClaim.claimId=="string"&&g(h.createEpicPlanningResearchPhysical))try{vr(r,h.createEpicPlanningClaim.claimId,E),P=JSON.parse(JSON.stringify(h.createEpicPlanningResearchPhysical))}catch{}if(t.verifyPlanningGeneration&&L&&h.status==="generated"&&g(h.createEpicPlanningClaim)&&typeof h.createEpicPlanningClaim.claimId=="string"&&g(h.createEpicPlanningGenerationPhysical))try{if(na(e,h.createEpicPlanningClaim.claimId,E).stateSha256!==a)throw new Error("planning-generation-snapshot-raced");_=JSON.parse(JSON.stringify(h.createEpicPlanningGenerationPhysical)),T=JSON.parse(JSON.stringify(h.createEpicPlanningPhysical)),P=JSON.parse(JSON.stringify(h.createEpicPlanningResearchPhysical))}catch{}if(_&&g(h.createEpicPlanningClaim)&&typeof h.createEpicPlanningClaim.claimId=="string")try{const M=Cr(e,h.createEpicPlanningClaim.claimId,E);if(M.stateSha256!==a)throw new Error("planning-memory-snapshot-raced");w=JSON.parse(JSON.stringify(M))}catch{}l[E]={id:h.id??E,title:h.title,...L?{createEpicPlanning:L}:{},...b.diagnostic?{createEpicPlanningProjection:b.diagnostic}:{},...T?{createEpicPlanningPhysical:T}:{},...P?{createEpicPlanningResearchPhysical:P}:{},..._?{createEpicPlanningGenerationPhysical:_}:{},...w?{createEpicPlanningMemoryPhysical:w}:{},status:h.status,stories:h.stories,total_stories:h.total_stories,completed_stories:h.completed_stories,depends_on:ti(h.depends_on),...Sn(h.branch_mode)?{branch_mode:Sn(h.branch_mode)}:{},...ve(h.execution_branch)?{execution_branch:ve(h.execution_branch)}:{},...ve(h.origin_branch)?{origin_branch:ve(h.origin_branch)}:{},...ri(h.branch_lease)?{branch_lease:ri(h.branch_lease)}:{},...si(h.origin_binding)?{origin_binding:si(h.origin_binding)}:{},...di(h.aggregate_qa_receipt)?{aggregate_qa_receipt:di(h.aggregate_qa_receipt)}:{},...pi(h.head_reconciliation_receipt)?{head_reconciliation_receipt:pi(h.head_reconciliation_receipt)}:{},...po(h.story_worktree_evidence)?{story_worktree_evidence:structuredClone(h.story_worktree_evidence)}:{},...St(h.pr_number)?{pr_number:St(h.pr_number)}:{},...te(h.physicalMergeStatus)?{physicalMergeStatus:te(h.physicalMergeStatus)}:{},...R(h.graph_revision)?{graph_revision:R(h.graph_revision)}:{},...li(h.terminal_git_receipt)?{terminal_git_receipt:li(h.terminal_git_receipt)}:{},...I?{lifecycle_classification:I}:{}}}const y=tc(r.current_session??r.currentSession),S=g(r.archPlan)?In(r.archPlan.execution):void 0,u=r.epic_id_ledger,C=Array.isArray(u?.reserved_ids)?[...new Set(u.reserved_ids.filter(E=>typeof E=="string"&&/^P\d+$/.test(E)))].slice(0,2048):[];return{schema_version:typeof r.schema_version=="number"?r.schema_version:void 0,config:{project_name:n.project_name??n.name??"unknown",default_branch:n.default_branch??"main",language:n.language??"pt-BR",yolo_mode:n.yolo_mode,user_name:n.user_name,worktree_base:n.worktree_base,max_parallel_stories:n.max_parallel_stories,project_id:typeof n.project_id=="string"?n.project_id:void 0},stories:d,epics:l,...C.length>0?{epic_id_ledger:{schema_version:1,reserved_ids:C}}:{},...y?{current_session:y}:{},...S?{archPlan:{execution:S}}:{}}}const Qn=[["P222.01","fbc3176b33687b13a8fadf8c7ea7cc06b6b6c500"],["P222.02","c7d3feb9a168f9e15b35516a972c767f3aa357da"],["P222.03","4d9bd4f2a1a3a1dc6399c572eb84b8b74c017806"],["P222.04","66590ef2f706c9d036f42edf5e517b237724f74f"],["P222.05","3ee2662538311e9788796340ed11b65864a8d8d5"],["P222.06","8660d07e3f68503a9ceb24dc138d24f62ab6cb45"],["P222.07","d99c80feacee8ea4033aa3322990147fffa2df91"],["P222.08","1f9e37dc922d87908efefb9595db32d32db30b00"],["P222.09","5ae12e485900992658e346cf3e38568fda1c2eeb"],["P222.10","6c5b8dc4f03d629fea4b62a33f4794af8e27e4f0"],["P222.11","cfe90f2f955c0027c57e4c621141d17912db65cc"],["P222.12","65f253c5cb600a8ee1dd94a1efdfef2fa5cd1629"],["P222.13","1e78c75b393515803a55d1a9b63a7fec23f710c9"],["P222.14","3f3e0bfd247a8581170df2a23c89497b5ae3641e"],["P222.15","1fd6dd25fffa5714d4ffa8b4303735e417f93de6"]],Xn="6a41a47ff2521f80c2296ed811b0f0b304c54750",Zn="dbc6d4670b2b7868a01973b1240e24589f1c5b7d",hi="30dccfff07f9c969be11ae1d28e62a09731a0768";function ic(e,t){try{const i=t.indexOf(hi);if(i<1||t[i-1]!==Xn)return new Map;const r=We("git",["show","--no-patch","--format=%P",hi],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim(),a=We("git",["show","--no-patch","--format=%P",Zn],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim();if(r!==`${Xn} ${Zn}`||a!==`${Qn.at(-1)[1]} ${Xn}`)return new Map;const n=We("git",["rev-list","--first-parent","--reverse",Zn],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
|
|
9
|
-
`),o=new Map;let d=-1;for(const[s,[l,y]]of
|
|
10
|
-
`).filter(Boolean),S=new Map(y.map((
|
|
11
|
-
`),{}}}async function
|
|
12
|
-
`),a=new
|
|
13
|
-
`),t}function
|
|
14
|
-
`)}async function
|
|
7
|
+
`)}catch{}}}function $d(){Kn=!1}function ri(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Qo(e){return e==="active"||e==="archived"||e==="rolled-back"||e==="synthetic"||e==="orphan"?e:void 0}const Xo=new Set(["goal","problem","desiredOutcome","rawIntent","context","users","surfaces","constraints","assumptions","risks","nonGoals","validationExpectations","debtRefs","repositoryEvidencePaths","journeyIds","screenIds","storybookStoryIds","backendContractIds","featureBlockerIds","remediationRefs","uiScope","remediationStory","examples","contracts"]),Zo=/(?:[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}|(?:token|api[_-]?key|secret|password|credential|license[_-]?key)\s*[:=]\s*\S+|https?:\/\/(?:localhost|127\.0\.0\.1|10\.\d+\.\d+\.\d+|192\.168\.\d+\.\d+|172\.(?:1[6-9]|2\d|3[0-1])\.\d+\.\d+|[^\s/]*internal[^\s/]*)\S*|private\s+prompt|raw\s+vendor\s+corpus|sk-[A-Za-z0-9_-]{12,})/i;function ec(e,t){if(!g(e)||e.schemaVersion!==1||e.epicId!==t||!/^P\d+$/.test(t))return{};try{const i=JSON.stringify(e),r=Buffer.byteLength(i);if(r>16384)return{diagnostic:Object.freeze({schemaVersion:"CreateEpicPlanningProjectionDiagnostic/1.0",outcome:"omitted",reasonCode:"budget-omitted",byteLengthBucket:r<=32768?"16385-32768":"32769-plus",publicSafe:!0})};if(Zo.test(i))return{};const a=(o,d)=>{if(Object.keys(o).some(s=>!d.includes(s)))throw new Error("planning-unknown-field")};if(a(e,["schemaVersion","epicId","intake","intakeRevision","diagnosisReceipt","researchReceipt","degradeAuthorization"]),!g(e.intake))return{};if(Object.keys(e.intake).some(o=>!Xo.has(o)))return{};for(const[o,d]of Object.entries(e.intake))if(["examples","contracts"].includes(o)){const s=o==="examples"?["id","title","actor","given","when","then","source","coveredRequirement","expectedValidation"]:["id","kind","description","path"];if(!Array.isArray(d)||d.length>16)return{};for(const l of d){if(!g(l))return{};if(a(l,s),Object.values(l).some(y=>typeof y!="string"||y.length>256))return{}}}else if(Array.isArray(d)){if(d.length>32||d.some(s=>typeof s!="string"||s.length>256))return{}}else if(typeof d=="string"){if(d.length>(o==="rawIntent"?aa:512))return{}}else if(typeof d!="boolean"||!["uiScope","remediationStory"].includes(o))return{};const n=["schemaVersion","kind","epicId","intakeRevision","artifactSummary","artifactDigest","predecessorReceiptId","accepted","receiptId"];for(const o of[e.diagnosisReceipt,e.researchReceipt])if(o!==void 0){if(!g(o))return{};if(a(o,n),Object.values(o).some(d=>typeof d=="string"&&d.length>1024))return{}}if(e.degradeAuthorization!==void 0){if(!g(e.degradeAuthorization))return{};a(e.degradeAuthorization,["approved","intakeRevision","reasonCodes","assumptionCodes"]);for(const o of["reasonCodes","assumptionCodes"]){const d=e.degradeAuthorization[o];if(!Array.isArray(d)||d.length>32||d.some(s=>typeof s!="string"||s.length>128))return{}}}return{checkpoint:JSON.parse(i)}}catch{return{}}}function ii(e){return e==="create-epic"||e==="discovered"?e:void 0}function de(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function tc(e){const t={};let i=!1;for(const r of["contracts","contract_refs","shared_surfaces","adr_refs","nfr_refs","acceptance_depends_on"]){if(e[r]===void 0)continue;const a=e[r];if(!Array.isArray(a)||a.length>128||a.some(n=>hn(n)===void 0)){i=!0;continue}t[r]=a.map(n=>hn(n))}if(e.planning!==void 0)try{if(!g(e.planning))throw new Error("planning-shape");const r=e.planning;for(const o of["claims","semanticArtifacts"]){if(r[o]===void 0)continue;const d=r[o];if(!Array.isArray(d)||d.length>128||d.some(s=>!g(s)||hn(s.ref)===void 0))throw new Error("planning-refs")}if(r.attempts!==void 0&&(!Array.isArray(r.attempts)||r.attempts.length>32))throw new Error("planning-attempts");for(const o of r.attempts??[]){if(!g(o)||!Array.isArray(o.reasonCodes)||o.reasonCodes.length>32||o.reasonCodes.some(d=>typeof d!="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(d)))throw new Error("planning-attempt-reasons");if(o.discoveredClaims!==void 0&&(!Array.isArray(o.discoveredClaims)||o.discoveredClaims.length>128||o.discoveredClaims.some(d=>!g(d)||hn(d.ref)===void 0)))throw new Error("planning-attempt-claims")}const{graphRevision:a,...n}=no(r);t.planning=n}catch{i=!0}return i&&(t.planning={schemaVersion:1,dependencyBasis:"unknown",claims:[],semanticArtifacts:[]}),t}function g(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Rt(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function Q(e){if(typeof e!="string")return;const t=e.trim();if(t)return t.replace(/[^a-z0-9_.:-]+/gi,"_").slice(0,120)}function q(e){if(typeof e!="string")return;const t=e.trim(),i=Q(e);return i===t?i:void 0}function Ee(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240)&&/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(t)&&!(t.includes("..")||t.includes("//")||t.includes("@{")||t.endsWith("/")||t.endsWith("."))&&!t.split("/").some(i=>!i||i.startsWith(".")||i.endsWith(".lock")))return t}function _(e){return typeof e=="string"&&/^[0-9a-f]{7,64}$/i.test(e)?e:void 0}function De(e){if(!(typeof e!="string"||e.length>64)&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/.test(e))return Number.isFinite(Date.parse(e))?e:void 0}function pt(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240||t.includes("..")))return/^[A-Za-z0-9._:/#\-[\]]+$/.test(t)?t:void 0}function En(e){if(!g(e))return;const t=u=>typeof u=="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,95}$/.test(u),i=u=>typeof u=="string"&&/^[a-f0-9]{64}$/.test(u),r=(u,C)=>Array.isArray(u)&&u.length<=C&&u.every(t)&&new Set(u).size===u.length?u:void 0,a=(u,C)=>{if(!(!g(u)||u.schemaVersion!==2||!t(u.requestId)||!t(u.stageCommand)||!i(u.requestHash)||!i(u.inputHash)||!i(u.stateHash)||!i(u.nonce)||!i(u.stageRevision)||!i(u.stageHash)||!i(u.catalogHash)||u.targetEpicId!==void 0&&!t(u.targetEpicId)||C&&(!i(u.outputHash)||!i(u.artifactHash))))return{schemaVersion:2,...u.targetEpicId?{targetEpicId:u.targetEpicId}:{},requestId:u.requestId,requestHash:u.requestHash,inputHash:u.inputHash,stateHash:u.stateHash,nonce:u.nonce,stageCommand:u.stageCommand,stageRevision:u.stageRevision,stageHash:u.stageHash,catalogHash:u.catalogHash,...C?{outputHash:u.outputHash,artifactHash:u.artifactHash}:{}}},n=(u,C)=>{if(!(!g(u)||u.schemaVersion!=="1.1"||u.kind!==C||!i(u.receiptId)||!i(u.graphHash)||!i(u.evidenceHash)||!t(u.elementId)||!t(u.caseId)||!t(u.category)))return{schemaVersion:"1.1",kind:C,receiptId:u.receiptId,graphHash:u.graphHash,elementId:u.elementId,caseId:u.caseId,category:u.category,evidenceHash:u.evidenceHash}},o=(u,C)=>{if(!g(u)||u.kind!==C||!i(u.receiptId)||!r(u.evidenceIds,24)||C==="architecture-stage-completion"&&!["succeeded","failed"].includes(String(u.status))||C==="architecture-stage-validation"&&!["passed","failed","pending"].includes(String(u.status)))return;const E=a(u,!0);if(!E)return;const h=C==="architecture-stage-validation"?n(u.isolated,"isolated"):void 0,I=C==="architecture-stage-validation"?n(u.regression,"regression"):void 0;if(!(C==="architecture-stage-validation"&&(!h||!I)))return{...E,kind:C,receiptId:u.receiptId,status:u.status,evidenceIds:u.evidenceIds,...h&&I?{isolated:h,regression:I}:{}}},d={};e.schemaVersion===1&&(d.schemaVersion=1),e.owner==="root"&&(d.owner="root"),t(e.currentStageCommand)&&(d.currentStageCommand=e.currentStageCommand),["ask-user","delegate","resume","advance","blocked","complete"].includes(String(e.continuationState))&&(d.continuationState=e.continuationState);const s=r(e.questionIds,16);if(s&&(d.questionIds=s),(e.childStatus==="succeeded"||e.childStatus==="failed")&&(d.childStatus=e.childStatus),(e.evidencePolicy==="legacy-compatible"||e.evidencePolicy==="v2-required")&&(d.evidencePolicy=e.evidencePolicy),t(e.targetEpicId)&&(d.targetEpicId=e.targetEpicId),i(e.graphRevision)&&(d.graphRevision=e.graphRevision),e.graphSource==="committed-epic-v1"&&(d.graphSource=e.graphSource),e.nonUiScopeReceipt!==void 0){const u=Er(e.nonUiScopeReceipt);if(!u||u.targetEpicId!==e.targetEpicId||u.graphRevision!==e.graphRevision||!g(e.accounting)||u.accountingId!==e.accounting.accountingId||!g(e.evidenceExpectation)||u.rootInputSha256!==e.evidenceExpectation.inputHash)throw new Error("architecture-non-ui-scope-invalid");d.nonUiScopeReceipt=u}g(e.pactAnswerReceipt)&&Object.keys(e.pactAnswerReceipt).sort().join(",")===["schemaVersion","targetEpicId","graphRevision","stateSha256","answersSha256","questionIds","publicSafe"].sort().join(",")&&e.pactAnswerReceipt.schemaVersion==="PactAnswerReceipt/1"&&e.pactAnswerReceipt.targetEpicId===e.targetEpicId&&e.pactAnswerReceipt.graphRevision===e.graphRevision&&i(e.pactAnswerReceipt.stateSha256)&&i(e.pactAnswerReceipt.answersSha256)&&v(e.pactAnswerReceipt.questionIds,["PACT-Q1-CONSUMER","PACT-Q2-PROVIDER","PACT-Q3-BROKER","PACT-Q4-MATCHERS","PACT-Q5-VERIFY"])&&e.pactAnswerReceipt.publicSafe===!0&&(d.pactAnswerReceipt=e.pactAnswerReceipt);const l=a(e.evidenceExpectation,!1);l&&(d.evidenceExpectation=l);const y=o(e.completionEvidence,"architecture-stage-completion"),S=o(e.validationEvidence,"architecture-stage-validation");if(y&&(d.completionEvidence=y),S&&(d.validationEvidence=S),g(e.reviewDecision)&&Object.keys(e.reviewDecision).sort().join(",")===["schemaVersion","targetEpicId","graphRevision","artifactHash","completionReceiptId","validationReceiptId","decision","evidenceIds","publicSafe"].sort().join(",")&&e.reviewDecision.schemaVersion==="ArchitectureReviewDecision/1"&&e.reviewDecision.targetEpicId===e.targetEpicId&&e.reviewDecision.graphRevision===e.graphRevision&&i(e.reviewDecision.graphRevision)&&i(e.reviewDecision.artifactHash)&&i(e.reviewDecision.completionReceiptId)&&i(e.reviewDecision.validationReceiptId)&&["approved","changes-requested"].includes(String(e.reviewDecision.decision))&&e.reviewDecision.publicSafe===!0){const u=r(e.reviewDecision.evidenceIds,24);u&&u.length>0&&(d.reviewDecision={...e.reviewDecision,evidenceIds:u})}if(Ft(e.terminalMemoryCheckpoint,e))d.terminalMemoryCheckpoint=e.terminalMemoryCheckpoint;else if(g(e.terminalMemoryCheckpoint)&&e.terminalMemoryCheckpoint.schemaVersion===void 0&&["passed","failed","pending"].includes(String(e.terminalMemoryCheckpoint.status))){const u=r(e.terminalMemoryCheckpoint.evidenceIds,24);u&&(d.terminalMemoryCheckpoint={status:e.terminalMemoryCheckpoint.status,evidenceIds:u})}if(Array.isArray(e.acceptedStages)&&e.acceptedStages.length<=15){const u=e.acceptedStages.map(C=>{if(!g(C)||!t(C.targetEpicId)||!t(C.stageCommand))return;const E=o(C.completionEvidence,"architecture-stage-completion"),h=o(C.validationEvidence,"architecture-stage-validation");return E&&h?{targetEpicId:C.targetEpicId,stageCommand:C.stageCommand,completionEvidence:E,validationEvidence:h}:void 0});u.every(C=>C!==void 0)&&(d.acceptedStages=u)}if(g(e.accounting)&&e.accounting.schemaVersion===1&&t(e.accounting.contractVersion)&&t(e.accounting.accountingId)&&typeof e.accounting.charged=="boolean"&&Number.isInteger(e.accounting.chargedQuotaUnits)&&typeof e.accounting.chargedQuotaUnits=="number"&&e.accounting.chargedQuotaUnits>=0&&e.accounting.chargedQuotaUnits<=13){const u=r(e.accounting.receiptIds,32);u&&(d.accounting={schemaVersion:1,contractVersion:e.accounting.contractVersion,accountingId:e.accounting.accountingId,charged:e.accounting.charged,chargedQuotaUnits:e.accounting.chargedQuotaUnits,receiptIds:u,...["in-progress","aborted","timed-out","failed","complete"].includes(String(e.accounting.lastOutcome))?{lastOutcome:e.accounting.lastOutcome}:{}})}return JSON.stringify(d).length<=96e3?d:void 0}function nc(e){const t=g(e.metadata.archPlan)?e.metadata.archPlan.execution:void 0,i=g(t)?t.checkpoint:void 0,r=g(t)?t:void 0,a=g(i)?i:void 0,n=e.requestExecution,o=Array.isArray(a?.acceptedStages)?a.acceptedStages:[],d=n.currentStageCommand==="arch-prd"&&n.continuationState==="delegate"&&n.completionEvidence===void 0&&n.validationEvidence===void 0&&a?.currentStageCommand==="arch-prd"&&a.continuationState==="delegate"&&o.length===0&&r?.nextAction==="delegate",s=n.currentStageCommand==="arch-prd"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-architecture"&&a.continuationState==="advance"&&o.length===1&&g(o[0])&&o[0].stageCommand==="arch-prd"&&v(o[0].completionEvidence,n.completionEvidence)&&v(o[0].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",l=n.currentStageCommand==="arch-architecture"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-architecture"&&a.continuationState==="delegate"&&o.length===1&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",y=n.currentStageCommand==="arch-architecture"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-fitness-functions"&&a.continuationState==="advance"&&o.length===2&&g(o[0])&&g(o[1])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===1&&v(o[0],n.acceptedStages[0])&&v(o[1].completionEvidence,n.completionEvidence)&&v(o[1].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",S=n.currentStageCommand==="arch-fitness-functions"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-fitness-functions"&&a.continuationState==="delegate"&&o.length===2&&g(o[0])&&g(o[1])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",u=n.currentStageCommand==="arch-fitness-functions"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-api-contracts"&&a.continuationState==="advance"&&o.length===3&&g(o[0])&&g(o[1])&&g(o[2])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&o[2].stageCommand==="arch-fitness-functions"&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===2&&v(o.slice(0,2),n.acceptedStages)&&v(o[2].completionEvidence,n.completionEvidence)&&v(o[2].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",C=n.currentStageCommand==="arch-api-contracts"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-api-contracts"&&a.continuationState==="delegate"&&o.length===3&&g(o[0])&&g(o[1])&&g(o[2])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&o[2].stageCommand==="arch-fitness-functions"&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",E=["PACT-Q1-CONSUMER","PACT-Q2-PROVIDER","PACT-Q3-BROKER","PACT-Q4-MATCHERS","PACT-Q5-VERIFY"],h=n.currentStageCommand==="arch-api-contracts"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="generate-pacts"&&a.continuationState==="ask-user"&&o.length===4&&g(o[3])&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===3&&v(o.slice(0,3),n.acceptedStages)&&o[3].stageCommand==="arch-api-contracts"&&v(o[3].completionEvidence,n.completionEvidence)&&v(o[3].validationEvidence,n.validationEvidence)&&v(a.questionIds,E)&&v(r?.questionIds,E)&&r?.nextAction==="ask-user",I=n.currentStageCommand==="generate-pacts"&&n.continuationState==="ask-user"&&a?.currentStageCommand==="generate-pacts"&&a.continuationState==="delegate"&&o.length===4&&v(o,n.acceptedStages)&&v(n.questionIds,E)&&v(a.questionIds,[])&&v(a.pactAnswerReceipt,e.answerReceipt)&&v(r?.pactAnswerReceipt,e.answerReceipt)&&e.answerReceipt?.stateSha256===e.sourceStateSha256&&r?.nextAction==="resume",b=n.currentStageCommand==="generate-pacts"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&v(n.pactAnswerReceipt,e.pactRecordedReceipt)&&a?.currentStageCommand==="arch-api-integrations"&&a.continuationState==="advance"&&o.length===5&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===4&&v(o.slice(0,4),n.acceptedStages)&&o.map(V=>g(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts"&&g(o[4])&&v(o[4].completionEvidence,n.completionEvidence)&&v(o[4].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",D=n.currentStageCommand==="arch-api-integrations"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-api-integrations"&&a.continuationState==="delegate"&&o.length===5&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",P=n.currentStageCommand==="arch-api-integrations"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-database"&&a.continuationState==="advance"&&o.length===6&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===5&&v(o.slice(0,5),n.acceptedStages)&&o.map(V=>g(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations"&&g(o[5])&&v(o[5].completionEvidence,n.completionEvidence)&&v(o[5].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",k=n.currentStageCommand==="arch-database"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-database"&&a.continuationState==="delegate"&&o.length===6&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",R=n.currentStageCommand==="arch-database"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-security"&&a.continuationState==="advance"&&o.length===7&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===6&&v(o.slice(0,6),n.acceptedStages)&&o.map(V=>g(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database"&&g(o[6])&&v(o[6].completionEvidence,n.completionEvidence)&&v(o[6].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",w=n.currentStageCommand==="arch-security"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-security"&&a.continuationState==="delegate"&&o.length===7&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",j=n.currentStageCommand==="arch-security"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-design-system"&&a.continuationState==="advance"&&o.length===8&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===7&&v(o.slice(0,7),n.acceptedStages)&&o.map(V=>g(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security"&&g(o[7])&&v(o[7].completionEvidence,n.completionEvidence)&&v(o[7].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",L=n.currentStageCommand==="arch-design-system"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-design-system"&&a.continuationState==="delegate"&&o.length===8&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",Y=n.currentStageCommand==="arch-design-system"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-ux-design"&&a.continuationState==="advance"&&o.length===9&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===8&&v(o.slice(0,8),n.acceptedStages)&&o.map(V=>g(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system"&&g(o[8])&&v(o[8].completionEvidence,n.completionEvidence)&&v(o[8].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",X=n.currentStageCommand==="arch-ux-design"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-ux-design"&&a.continuationState==="delegate"&&o.length===9&&v(o,n.acceptedStages)&&r?.nextAction==="blocked",pe=n.currentStageCommand==="arch-ux-design"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-performance"&&a.continuationState==="advance"&&o.length===10&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===9&&v(o.slice(0,9),n.acceptedStages)&&o.map(V=>g(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design"&&g(o[9])&&v(o[9].completionEvidence,n.completionEvidence)&&v(o[9].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",x=n.currentStageCommand==="arch-performance"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-performance"&&a.continuationState==="delegate"&&o.length===10&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",Se=n.currentStageCommand==="arch-performance"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-testing"&&a.continuationState==="advance"&&o.length===11&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===10&&v(o.slice(0,10),n.acceptedStages)&&o.map(V=>g(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance"&&g(o[10])&&v(o[10].completionEvidence,n.completionEvidence)&&v(o[10].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",Z=n.currentStageCommand==="arch-testing"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-testing"&&a.continuationState==="delegate"&&o.length===11&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",J=n.currentStageCommand==="arch-testing"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-infrastructure"&&a.continuationState==="advance"&&o.length===12&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===11&&v(o.slice(0,11),n.acceptedStages)&&o.map(V=>g(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance,arch-testing"&&g(o[11])&&v(o[11].completionEvidence,n.completionEvidence)&&v(o[11].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",gt=n.currentStageCommand==="arch-infrastructure"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-infrastructure"&&a.continuationState==="delegate"&&o.length===12&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",wt=n.currentStageCommand==="arch-infrastructure"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="arch-review"&&a.continuationState==="advance"&&o.length===13&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===12&&v(o.slice(0,12),n.acceptedStages)&&o.map(V=>g(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance,arch-testing,arch-infrastructure"&&g(o[12])&&v(o[12].completionEvidence,n.completionEvidence)&&v(o[12].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",ue=n.currentStageCommand==="arch-review"&&n.continuationState==="advance"&&a?.currentStageCommand==="arch-review"&&a.continuationState==="delegate"&&o.length===13&&v(o,n.acceptedStages)&&r?.nextAction==="delegate",O=n.currentStageCommand==="arch-review"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&n.reviewDecision===void 0&&a?.currentStageCommand==="arch-review"&&a.continuationState==="ask-user"&&o.length===13&&v(o,n.acceptedStages)&&v(a.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&v(a.completionEvidence,n.completionEvidence)&&v(a.validationEvidence,n.validationEvidence)&&r?.nextAction==="ask-user",$=n.currentStageCommand==="arch-review"&&n.continuationState==="ask-user"&&n.childStatus==="succeeded"&&g(n.reviewDecision)&&n.reviewDecision.decision==="approved"&&v(n.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&a?.currentStageCommand==="update-memory"&&a.continuationState==="advance"&&o.length===14&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===13&&v(o.slice(0,13),n.acceptedStages)&&g(o[13])&&o[13].stageCommand==="arch-review"&&v(o[13].completionEvidence,n.completionEvidence)&&v(o[13].validationEvidence,n.validationEvidence)&&v(a.reviewDecision,n.reviewDecision)&&r?.nextAction==="resume",xe=n.currentStageCommand==="update-memory"&&n.continuationState==="advance"&&g(n.reviewDecision)&&n.reviewDecision.decision==="approved"&&a?.currentStageCommand==="update-memory"&&a.continuationState==="delegate"&&o.length===14&&v(o,n.acceptedStages)&&v(a.reviewDecision,n.reviewDecision)&&r?.nextAction==="delegate",Te=n.currentStageCommand==="update-memory"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="update-memory"&&a.continuationState==="complete"&&o.length===15&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===14&&v(o.slice(0,14),n.acceptedStages)&&g(o[14])&&o[14].targetEpicId===n.targetEpicId&&o[14].stageCommand==="update-memory"&&v(o[14].completionEvidence,n.completionEvidence)&&v(o[14].validationEvidence,n.validationEvidence)&&v(a.reviewDecision,n.reviewDecision)&&v(a.completionEvidence,n.completionEvidence)&&v(a.validationEvidence,n.validationEvidence)&&Ft(a.terminalMemoryCheckpoint,n)!==null&&v(a.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)&&r?.nextAction==="complete",Pe=n.currentStageCommand==="update-memory"&&n.continuationState==="complete"&&n.childStatus==="succeeded"&&a?.currentStageCommand==="update-memory"&&a.continuationState==="complete"&&o.length===15&&v(o,n.acceptedStages)&&v(a.reviewDecision,n.reviewDecision)&&v(a.completionEvidence,n.completionEvidence)&&v(a.validationEvidence,n.validationEvidence)&&Ft(a.terminalMemoryCheckpoint,n)&&v(a.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)&&r?.nextAction==="complete",Nt=r?qi(n,r,Ft(n.terminalMemoryCheckpoint,n)&&v(a?.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)):void 0;if(e.metadata.mode!=="arch-plan"||e.metadata.resolvedTrigger!=="arch-plan"||!g(t)||!g(i)||t.owner!=="root"||t.currentStageCommand!==i.currentStageCommand||t.continuationState!==i.continuationState||i.owner!=="root"||i.evidencePolicy!=="v2-required"||i.targetEpicId!==n.targetEpicId||i.graphRevision!==n.graphRevision||i.graphSource!==n.graphSource||!/^P[1-9][0-9]{0,11}$/.test(String(i.targetEpicId))||!/^[a-f0-9]{64}$/.test(String(i.graphRevision))||!Array.isArray(i.acceptedStages)||!(Nt||d||s||l||y||S||u||C||h||I||b||D||P||k||R||w||j||L||Y||X||pe||x||Se||Z||J||gt||wt||ue||O||$||xe||Te||Pe)||!g(i.accounting)||i.accounting.charged!==!0||!v(En(i),i))throw new Error("architecture-root-checkpoint-invalid");const rt=z(e.projectRoot,".neocortex"),K=z(rt,"state.json"),ve=z(rt,"state.json.architecture.lock"),he=zt(ve,"wx",384);let qe;try{const V=Vt(K);if(!V.isFile()||V.isSymbolicLink())throw new Error("architecture-root-state-binding-invalid");const ft=Fe(K,"utf8");if(Ne("sha256").update(ft).digest("hex")!==e.sourceStateSha256)throw new Error("architecture-root-state-conflict");const ge=JSON.parse(ft),oe=g(ge)&&g(ge.archPlan)?ge.archPlan:{};if(!g(ge)||!g(ge.epics)||!Object.hasOwn(ge.epics,i.targetEpicId)||(e.initialBinding?oe.execution!==void 0||n.graphSource!=="committed-epic-v1":!v(En(oe.execution),n))||g(ge.scope)&&ge.scope.kind==="projected")throw new Error("architecture-root-state-binding-invalid");if(n.graphSource==="committed-epic-v1"&&n.graphRevision!==Yt(e.projectRoot,String(n.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");if(Pe||Nt==="complete-replay"){const Lt={...n,continuationState:"delegate",acceptedStages:n.acceptedStages.slice(0,Ir(n))};if(!v(n.terminalMemoryCheckpoint,Ln(e.projectRoot,Lt)))throw new Error("architecture-root-state-conflict");return}const ye=dn(),Ve=Ge("git",["rev-parse","--git-common-dir"],{cwd:e.projectRoot,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),ee=Zi(Ve)?Mn(Ve):Mn(e.projectRoot,Ve);if(Xi(ee)!==ee)throw new Error("architecture-root-backup-dir-invalid");const mt=z(ee,"neocortex-architecture");qt(mt,{recursive:!0,mode:448});const ze=Vt(mt);if(!ze.isDirectory()||ze.isSymbolicLink()||ze.uid!==process.getuid?.()||(ze.mode&63)!==0)throw new Error("architecture-root-backup-dir-invalid");const ke=z(mt,`state-backup-${ye}.json`),Qe=zt(ke,"wx",384);try{pn(Qe,ft),ln(Qe)}finally{Jt(Qe)}const H=zt(mt,"r");try{ln(H)}finally{Jt(H)}const bn={...ge,archPlan:{...oe,execution:i}};qe=z(rt,`state.json.architecture-tmp-${ye}`);const it=zt(qe,"wx",384);try{pn(it,`${JSON.stringify(bn,null,2)}
|
|
8
|
+
`),ln(it)}finally{Jt(it)}if((Te||Nt==="complete")&&!v(n.terminalMemoryCheckpoint,Ln(e.projectRoot,n)))throw new Error("architecture-root-state-conflict");if(n.graphSource==="committed-epic-v1"&&n.graphRevision!==Yt(e.projectRoot,String(n.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");vr(qe,K),qe=void 0;const N=zt(rt,"r");try{ln(N)}finally{Jt(N)}}finally{if(qe)try{Dn(qe)}catch{}Jt(he),Dn(ve)}}function Sn(e,t){if(!g(e))return;const i={};for(const r of t){const a=e[r];if(typeof a=="boolean")i[r]=a;else if(typeof a=="number"&&Number.isFinite(a))i[r]=a;else if(typeof a=="string"){const n=Q(a);n&&(i[r]=n)}}return Object.keys(i).length>0?i:void 0}function vn(e){return e==="epic"||e==="story"?e:void 0}function ai(e){if(!g(e)||e.schemaVersion!==1)return;const t=q(e.ownerStoryId),i=q(e.sessionId),r=q(e.idempotencyKey),a=De(e.acquiredAt),n=De(e.expiresAt);if(!(!t||!i||!r||!a||!n||Date.parse(n)<=Date.parse(a)))return{schemaVersion:1,ownerStoryId:t,sessionId:i,idempotencyKey:r,acquiredAt:a,expiresAt:n}}function oi(e){if(!g(e)||e.schemaVersion!==1)return;const t=q(e.storyId),i=q(e.epicId),r=Ee(e.branch),a=_(e.baseSha),n=_(e.headSha),o=q(e.idempotencyKey),d=De(e.recordedAt),s=de(e.commits).map(_).filter(D=>!!D).slice(0,256),l=de(e.receiptRefs).map(pt).filter(D=>!!D).slice(0,256),y=e.dispatchId===void 0?void 0:q(e.dispatchId),S=e.bundleId===void 0?void 0:q(e.bundleId),u=e.bundleDigest===void 0?void 0:_(e.bundleDigest),C=e.graphRevision===void 0?void 0:_(e.graphRevision),E=e.claimRevision===void 0?void 0:q(e.claimRevision),h=rc(e.qaReceipt),I=ic(e.reviewReceipt),b=e.rootMemoryEffect===void 0?void 0:Eo(e.rootMemoryEffect)?e.rootMemoryEffect:void 0;if(!(!t||!i||!t.startsWith(`${i}.`)||!r||!a||!n||a===n||!o||!d||s.length===0||l.length===0||!Array.isArray(e.commits)||s.length!==e.commits.length||e.commits.length>256||!Array.isArray(e.receiptRefs)||l.length!==e.receiptRefs.length||e.receiptRefs.length>256||e.dispatchId!==void 0&&!y||e.bundleId!==void 0&&!S||e.bundleDigest!==void 0&&(!u||u.length!==64)||e.graphRevision!==void 0&&(!C||C.length!==64)||e.claimRevision!==void 0&&!E||e.rootMemoryEffect!==void 0&&(!b||b.storyId!==t||b.epicId!==i||b.executionBranch!==r||b.sourceHeadSha!==a||b.childClaimRevision!==E)||e.qaVerdict!=="passed"&&e.qaVerdict!=="blocked"||!["approved","changes-requested","pending"].includes(String(e.reviewVerdict))||!h||e.reviewVerdict!=="pending"&&!I||e.reviewVerdict==="pending"&&I||h.verdict!==e.qaVerdict||I&&I.verdict!==e.reviewVerdict||!di(h,{storyId:t,epicId:i,baseSha:a,headSha:n,bundleDigest:u,graphRevision:C})||I&&(!di(I,{storyId:t,epicId:i,baseSha:a,headSha:n,bundleDigest:u,graphRevision:C})||I.qaReceiptRef!==h?.receiptRef||I.receiptRef===h?.receiptRef)||!l.includes(String(h.receiptRef))||I&&(!l.includes(String(I.receiptRef))||Date.parse(String(I.reviewedAt))<Date.parse(String(h.checkedAt)))))return{schemaVersion:1,storyId:t,epicId:i,branch:r,baseSha:a,headSha:n,idempotencyKey:o,...y?{dispatchId:y}:{},...S?{bundleId:S}:{},...u?{bundleDigest:u}:{},...C?{graphRevision:C}:{},...E?{claimRevision:E}:{},...b?{rootMemoryEffect:structuredClone(b)}:{},qaVerdict:e.qaVerdict,reviewVerdict:e.reviewVerdict,...h?{qaReceipt:h}:{},...I?{reviewReceipt:I}:{},recordedAt:d,commits:s,receiptRefs:l}}function rc(e){if(!g(e)||e.schemaVersion!==1||e.kind!=="story_qa_evidence"||e.producer!=="local-yolo-tdd"||e.evidenceVersion!==void 0&&e.evidenceVersion!=="git-immutable-v1"&&e.evidenceVersion!=="p205-execution-v2"||!["passed","blocked"].includes(String(e.verdict)))return;const t=q(e.storyId),i=q(e.epicId),r=_(e.baseSha),a=_(e.headSha),n=_(e.bundleDigest),o=_(e.graphRevision),d=_(e.sourceEvidenceDigest),s=De(e.checkedAt),l=pt(e.receiptRef),y=e.evidenceVersion==="p205-execution-v2"&&e.contract==="P205-CI-02"?e.contract:void 0,S=e.evidenceVersion==="p205-execution-v2"&&e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,u=e.evidenceVersion==="p205-execution-v2"?_(e.manifestDigest):void 0,C=e.evidenceVersion==="p205-execution-v2"?_(e.resultDigest):void 0,E=e.evidenceVersion==="p205-execution-v2"?de(e.gateIds).map(q).filter(h=>!!h).slice(0,64):void 0;if(!(!t||!i||!r||!a||!n||n.length!==64||!o||o.length!==64||!d||d.length!==64||!s||!l||e.evidenceVersion==="p205-execution-v2"&&(!y||S!=="node scripts/test-root.mjs --gate complete"||!u||u.length!==64||!C||C.length!==64||!Array.isArray(e.gateIds)||!E||E.length===0||E.length!==e.gateIds.length)))return{schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",...e.evidenceVersion?{evidenceVersion:e.evidenceVersion}:{},storyId:t,epicId:i,...e.evidenceVersion==="p205-execution-v2"?{contract:y,command:S,manifestDigest:u,gateIds:E,resultDigest:C}:{},baseSha:r,headSha:a,bundleDigest:n,graphRevision:o,sourceEvidenceDigest:d,verdict:e.verdict,checkedAt:s,receiptRef:l}}function ci(e){if(!g(e)||e.schemaVersion!==1||e.kind!=="story_checkpoint_physical_verification"||e.producer!=="client-p205-transient-v1"||e.publicSafe!==!0||e.verdict!=="verified"&&e.verdict!=="rejected")return;const t=q(e.storyId),i=q(e.epicId),r=Ee(e.branch),a=_(e.baseSha),n=_(e.headSha),o=_(e.aggregateHeadSha),d=_(e.commitBodyDigest),s=_(e.changedPathsDigest),l=e.claimVerification==="canonical"||e.claimVerification==="legacy-migration"?e.claimVerification:void 0,y=_(e.effectiveClaimRevision),S=e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,u=_(e.manifestDigest),C=de(e.gateIds).map(q).filter(k=>!!k).slice(0,64),E=_(e.resultDigest),h=_(e.graphRevision),I=_(e.executionEvidenceDigest),b=_(e.sourceEvidenceDigest),D=De(e.verifiedAt),P=de(e.reasonCodes).map(q).filter(k=>!!k).slice(0,16);if(!(!t||!i||!r||!a||a.length<40||!n||n.length<40||!o||o.length<40||!d||d.length!==64||!s||s.length!==64||!l||!y||y.length!==64||!S||!u||u.length!==64||!Array.isArray(e.gateIds)||C.length!==e.gateIds.length||!E||E.length!==64||!h||h.length!==64||!I||I.length!==64||!b||b.length!==64||!D||P.length===0||e.verdict==="verified"&&(C.length===0||!P.includes("checkpoint-p205-transient-verified"))))return{schemaVersion:1,kind:"story_checkpoint_physical_verification",producer:"client-p205-transient-v1",storyId:t,epicId:i,branch:r,baseSha:a,headSha:n,aggregateHeadSha:o,commitBodyDigest:d,changedPathsDigest:s,claimVerification:l,effectiveClaimRevision:y,command:S,manifestDigest:u,gateIds:C,resultDigest:E,graphRevision:h,executionEvidenceDigest:I,sourceEvidenceDigest:b,verifiedAt:D,verdict:e.verdict,reasonCodes:P,publicSafe:!0}}function si(e){const t=["schemaVersion","kind","producer","storyId","epicId","branch","baseSha","headSha","graphRevision","effectiveClaimRevision","sourceEvidenceDigest","verifiedAt","reasonCodes","integrationAuthorized","publicSafe"];if(!g(e)||Object.keys(e).some(u=>!t.includes(u))||e.schemaVersion!==1||e.kind!=="story_scheduling_checkpoint_evidence"||e.producer!=="client-git-physical-v1"||e.integrationAuthorized!==!1||e.publicSafe!==!0)return;const i=q(e.storyId),r=q(e.epicId),a=Ee(e.branch),n=_(e.baseSha),o=_(e.headSha),d=_(e.graphRevision),s=_(e.effectiveClaimRevision),l=_(e.sourceEvidenceDigest),y=De(e.verifiedAt),S=de(e.reasonCodes).map(q).filter(u=>!!u);if(!(!i||!r||!a||!n||n.length<40||!o||o.length<40||!d||d.length!==64||!s||s.length!==64||!l||l.length!==64||!y||!Array.isArray(e.reasonCodes)||S.length!==1||S[0]!=="checkpoint-git-scheduling-verified"))return{schemaVersion:1,kind:"story_scheduling_checkpoint_evidence",producer:"client-git-physical-v1",storyId:i,epicId:r,branch:a,baseSha:n,headSha:o,graphRevision:d,effectiveClaimRevision:s,sourceEvidenceDigest:l,verifiedAt:y,reasonCodes:S,integrationAuthorized:!1,publicSafe:!0}}function ic(e){if(!g(e)||e.schemaVersion!==1||e.kind!=="story_review_evidence"||e.producer!=="root-commit-range-review"||!["approved","changes-requested"].includes(String(e.verdict)))return;const t=q(e.storyId),i=q(e.epicId),r=_(e.baseSha),a=_(e.headSha),n=_(e.bundleDigest),o=_(e.graphRevision),d=_(e.sourceEvidenceDigest),s=pt(e.qaReceiptRef),l=De(e.reviewedAt),y=pt(e.receiptRef);if(!(!t||!i||!r||!a||!n||n.length!==64||!o||o.length!==64||!d||d.length!==64||!s||!l||!y))return{schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:t,epicId:i,baseSha:r,headSha:a,bundleDigest:n,graphRevision:o,sourceEvidenceDigest:d,qaReceiptRef:s,verdict:e.verdict,reviewedAt:l,receiptRef:y}}function di(e,t){return["storyId","epicId","baseSha","headSha","bundleDigest","graphRevision"].every(i=>e[i]===t[i])}function pi(e){if(!g(e))return;const t=e.schemaVersion===1&&e.capturedFromCurrentCheckout===!0&&e.capturedFrom===void 0,i=e.schemaVersion===2&&e.capturedFromCurrentCheckout===void 0&&(e.capturedFrom==="current-checkout"||e.capturedFrom==="branch-ref");if(!t&&!i)return;const r=Ee(e.originBranch),a=_(e.originHeadSha),n=Ee(e.executionBranch),o=De(e.capturedAt);if(!(!r||!a||a.length<40||!n||!o||r===n))return t?{schemaVersion:1,originBranch:r,originHeadSha:a,executionBranch:n,capturedFromCurrentCheckout:!0,capturedAt:o}:{schemaVersion:2,originBranch:r,originHeadSha:a,executionBranch:n,capturedFrom:e.capturedFrom,capturedAt:o}}function li(e){if(!g(e)||e.schemaVersion!==1||e.verdict!=="passed")return;const t=_(e.executionHeadSha),i=_(e.graphRevision),r=De(e.checkedAt),a=pt(e.receiptRef),n=de(e.gateIds).map(q).filter(y=>!!y).slice(0,128),o=e.evidenceVersion==="p205-execution-v2"&&e.producer==="local-yolo-tdd"&&e.contract==="P205-CI-02"&&e.command==="node scripts/test-root.mjs --gate complete",d=e.evidenceVersion===void 0&&e.producer===void 0&&e.contract===void 0&&e.command===void 0&&e.manifestDigest===void 0&&e.resultDigest===void 0,s=o?_(e.manifestDigest):void 0,l=o?_(e.resultDigest):void 0;if(!(!t||t.length<40||!i||i.length!==64||!r||!a||n.length===0||!Array.isArray(e.gateIds)||n.length!==e.gateIds.length||e.gateIds.length>128||!d&&!o||o&&(!s||s.length!==64||!l||l.length!==64)))return{schemaVersion:1,...o?{evidenceVersion:"p205-execution-v2",producer:"local-yolo-tdd",contract:"P205-CI-02",command:"node scripts/test-root.mjs --gate complete",manifestDigest:s,resultDigest:l}:{},verdict:"passed",executionHeadSha:t,graphRevision:i,checkedAt:r,receiptRef:a,gateIds:n}}function ui(e){if(!g(e)||e.schemaVersion!==1||e.kind!=="epic_head_reconciliation"||e.producer!=="client-p205-head-reconciliation-v1"||e.publicSafe!==!0)return;const t={schemaVersion:1,kind:"epic_head_reconciliation",producer:"client-p205-head-reconciliation-v1",epicId:q(e.epicId),executionBranch:Ee(e.executionBranch),originBranch:Ee(e.originBranch),graphRevision:_(e.graphRevision),originHeadSha:_(e.originHeadSha),lastAcceptedCheckpointHeadSha:_(e.lastAcceptedCheckpointHeadSha),executionHeadSha:_(e.executionHeadSha),acceptedCheckpointIds:de(e.acceptedCheckpointIds),acceptedCheckpointHeads:de(e.acceptedCheckpointHeads),reconciliationCommitShas:de(e.reconciliationCommitShas),commitRangeDigest:_(e.commitRangeDigest),changedPaths:de(e.changedPaths),changedPathsDigest:_(e.changedPathsDigest),allowedWriteSet:de(e.allowedWriteSet),allowedWriteSetDigest:_(e.allowedWriteSetDigest),aggregateReceiptRef:pt(e.aggregateReceiptRef),aggregateManifestDigest:_(e.aggregateManifestDigest),aggregateResultDigest:_(e.aggregateResultDigest),producedAt:De(e.producedAt),revalidatedAt:De(e.revalidatedAt),publicSafe:!0},i=["originSyncHeadSha","originSyncCommitShas","originSyncPaths","originSyncPathsDigest","originSyncResolvedPaths","originSyncResolvedPathsDigest"],r=i.filter(d=>e[d]!==void 0).length;if(r!==0&&r!==i.length)return;const a=r===0?void 0:{originSyncHeadSha:_(e.originSyncHeadSha),originSyncCommitShas:de(e.originSyncCommitShas),originSyncPaths:de(e.originSyncPaths),originSyncPathsDigest:_(e.originSyncPathsDigest),originSyncResolvedPaths:de(e.originSyncResolvedPaths),originSyncResolvedPathsDigest:_(e.originSyncResolvedPathsDigest)};if(a&&(!a.originSyncHeadSha||a.originSyncHeadSha.length<40||a.originSyncCommitShas.length===0||a.originSyncCommitShas.length>256||a.originSyncCommitShas.some(d=>!/^[a-f0-9]{40,64}$/i.test(d))||a.originSyncPaths.length>2048||a.originSyncResolvedPaths.length>64||a.originSyncPathsDigest!==gn(a.originSyncPaths)||a.originSyncResolvedPathsDigest!==gn(a.originSyncResolvedPaths))||!t.epicId||!t.executionBranch||!t.originBranch||!t.graphRevision||t.graphRevision.length!==64||!t.originHeadSha||t.originHeadSha.length<40||!t.lastAcceptedCheckpointHeadSha||t.lastAcceptedCheckpointHeadSha.length<40||!t.executionHeadSha||t.executionHeadSha.length<40||t.acceptedCheckpointIds.length===0||t.acceptedCheckpointIds.length>2048||t.acceptedCheckpointIds.length!==t.acceptedCheckpointHeads.length||t.acceptedCheckpointHeads.some(d=>!/^[a-f0-9]{40,64}$/i.test(d))||t.reconciliationCommitShas.length>2048||t.reconciliationCommitShas.some(d=>!/^[a-f0-9]{40,64}$/i.test(d))||t.changedPaths.length>2048||(t.lastAcceptedCheckpointHeadSha===t.executionHeadSha?t.reconciliationCommitShas.length!==0||t.changedPaths.length!==0:t.reconciliationCommitShas.length===0||t.changedPaths.length===0)||t.allowedWriteSet.length===0||t.allowedWriteSet.length>2048||!t.commitRangeDigest||!t.changedPathsDigest||!t.allowedWriteSetDigest||!t.aggregateReceiptRef||!t.aggregateManifestDigest||!t.aggregateResultDigest||!t.producedAt||!t.revalidatedAt||t.commitRangeDigest!==io(t.lastAcceptedCheckpointHeadSha,t.executionHeadSha,t.reconciliationCommitShas)||t.changedPathsDigest!==gn(t.changedPaths)||t.allowedWriteSetDigest!==gn(t.allowedWriteSet))return;const n={...t,...a??{}},o=_(e.inputDigest);if(!(!o||o.length!==64||o!==ro(n)))return{...n,inputDigest:o}}function Qn(e){if(!g(e)||e.schemaVersion!==1)return;const t=Sn(e,["schemaVersion","kind","storyId","epicId","baseSha","headSha","originalBaseSha","originalHeadSha","gitPullRequest","preservesLaterCommits","historyRewrite","recordedAt"])??{},i=de(e.receiptRefs).map(pt).filter(a=>!!a).slice(0,256),r=de(e.revertCommits).map(Q).filter(a=>!!a).slice(0,256);return{...t,...i.length?{receiptRefs:i}:{},...r.length?{revertCommits:r}:{}}}function ac(e){if(!(!g(e)||Object.keys(e).sort().join(",")!=="gitPullRequest,headSha,kind,prNumber,reviewEvidenceDigest,schemaVersion"||e.schemaVersion!==1||e.kind!=="git-pull-request"||e.gitPullRequest!==!0||!Number.isSafeInteger(e.prNumber)||Number(e.prNumber)<=0||typeof e.headSha!="string"||!/^[a-f0-9]{40}$/.test(e.headSha)||typeof e.reviewEvidenceDigest!="string"||!/^[a-f0-9]{64}$/.test(e.reviewEvidenceDigest)))return{schemaVersion:1,kind:"git-pull-request",gitPullRequest:!0,prNumber:e.prNumber,headSha:e.headSha,reviewEvidenceDigest:e.reviewEvidenceDigest}}function hi(e){if(!g(e)||e.schemaVersion!==1||e.publicSafe!==!0)return;const t=q(e.epicId),i=Ee(e.executionBranch),r=Ee(e.originBranch),a=_(e.baseSha),n=_(e.executionHeadSha),o=e.mergeSha===void 0?void 0:_(e.mergeSha),d=e.pushedSha===void 0?void 0:_(e.pushedSha),s=q(e.idempotencyKey),l=De(e.attemptStartedAt),y=e.completedAt===void 0?void 0:De(e.completedAt),S=de(e.localGateReceiptRefs).map(pt).filter(h=>!!h).slice(0,256),u=de(e.reasonCodes).map(q).filter(h=>!!h).slice(0,64),C=cc(e.candidateQa),E=oc(e.providerGuard);if(!(!t||!i||!r||!a||!n||!s||!l||S.length===0||u.length===0||!["direct","single_pr"].includes(String(e.strategy))||!["prepared","merged","pushed","denied_external_gate","blocked_local_or_repo"].includes(String(e.physicalStatus))||typeof e.retryEligible!="boolean"||e.providerGuard!==void 0&&!E||E&&(e.strategy!=="single_pr"||e.physicalStatus!=="pushed"||E.prHeadSha!==o||E.originHeadSha!==a)))return{schemaVersion:1,epicId:t,executionBranch:i,originBranch:r,baseSha:a,executionHeadSha:n,...o?{mergeSha:o}:{},...d?{pushedSha:d}:{},strategy:e.strategy,...Rt(e.prNumber)?{prNumber:Rt(e.prNumber)}:{},physicalStatus:e.physicalStatus,localGateReceiptRefs:S,idempotencyKey:s,attemptStartedAt:l,...C?{candidateQa:C}:{},...E?{providerGuard:E}:{},...y?{completedAt:y}:{},retryEligible:e.retryEligible,reasonCodes:u,publicSafe:!0}}function oc(e){if(!g(e)||e.schemaVersion!==1||e.provider!=="github"||e.publicSafe!==!0)return;const t=String(e.mode),i=String(e.source),r=t==="recovered_exact_tree"?i==="physical_recovery":t==="strict_up_to_date_expected_head"&&["branch_protection","ruleset","branch_protection_and_ruleset"].includes(i),a=_(e.prHeadSha),n=_(e.originHeadSha),o=De(e.checkedAt);if(!(!r||!a||!n||!o))return{schemaVersion:1,provider:"github",mode:t,source:i,prHeadSha:a,originHeadSha:n,checkedAt:o,publicSafe:!0}}function cc(e){if(!g(e)||e.schemaVersion!==1||e.kind!=="epic_merge_candidate_qa"||e.contract!=="P205-CI-02"||e.command!==Xt)return;const i=Object.fromEntries(["originHeadSha","executionHeadSha","mergeSha","treeSha","graphRevision","manifestDigest","resultDigest"].map(o=>[o,_(e[o])])),r=De(e.checkedAt),a=pt(e.receiptRef),n=de(e.gateIds).filter(o=>/^[a-z0-9-]+$/.test(o)).slice(0,128);if(!(Object.values(i).some(o=>!o)||!r||!a||n.length===0))return{schemaVersion:1,kind:e.kind,contract:e.contract,command:e.command,...i,checkedAt:r,receiptRef:a,gateIds:n}}function sc(e){if(!g(e))return;const t={...Q(e.active_epic_id??e.activeEpicId)?{active_epic_id:Q(e.active_epic_id??e.activeEpicId)}:{},...Q(e.active_story_id??e.activeStoryId)?{active_story_id:Q(e.active_story_id??e.activeStoryId)}:{},...Q(e.active_step_id??e.activeStepId)?{active_step_id:Q(e.active_step_id??e.activeStepId)}:{},...Q(e.session_id??e.sessionId)?{session_id:Q(e.session_id??e.sessionId)}:{},...Q(e.started_at??e.startedAt)?{started_at:Q(e.started_at??e.startedAt)}:{}};return Object.keys(t).length>0?t:void 0}function dc(e){const t=Sn(e.completionEvidence??e.completion_evidence,["prNumber","pr_number","prState","pr_state","pullRequestState","merged","mergedAt","issueNumber","issue_number","issueState","issue_state","closedAt"]),i=Sn(e.issueCloseAudit??e.issue_close_audit,["schema_version","event","storyId","epicId","issueNumber","closedAt","publicSafe","rawLogStorage"]),r=Sn(e.scopedCiEvidence??e.scoped_ci_evidence,["schema_version","storyId","epicId","prNumber","finalState","publicSafe","rawLogStorage"]);return{...typeof e.merged=="boolean"?{merged:e.merged}:{},...typeof e.safeToContinueYoloop=="boolean"?{safeToContinueYoloop:e.safeToContinueYoloop}:{},...typeof e.mergeBlockedRemotely=="boolean"?{mergeBlockedRemotely:e.mergeBlockedRemotely}:{},...Q(e.physicalMergeStatus)?{physicalMergeStatus:Q(e.physicalMergeStatus)}:{},...Q(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)?{pr_state:Q(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)}:{},...Q(e.issue_state??e.issueState??e.workflow_issue_state)?{issue_state:Q(e.issue_state??e.issueState??e.workflow_issue_state)}:{},...Rt(e.issue_number??e.issueNumber)?{issue_number:Rt(e.issue_number??e.issueNumber)}:{},...t?{completionEvidence:t}:{},...i?{issueCloseAudit:i}:{},...r?{scopedCiEvidence:r}:{}}}class lt extends Error{reasonCode;constructor(t){super(t),this.name="StateSnapshotIntegrityError",this.reasonCode=t}}const pc=new Set(["yolo","yoloop","finalize-epic","audit"]);function gi(e){return typeof e=="string"&&pc.has(e)}function Xn(e,t={}){const i=z(e,".neocortex","state.json");if(!jt(i))throw new lt("git-lifecycle-state-missing");let r;try{r=JSON.parse(Fe(i,"utf8"))}catch{throw new lt("git-lifecycle-state-corrupt")}if(!g(r)||!g(r.epics)||!g(r.stories))throw new lt("git-lifecycle-state-shape-invalid");const a=Object.values(r.epics).some(n=>g(n)&&(n.branch_mode==="epic"||Ee(n.execution_branch)!==void 0));if(a)try{fn(e,{required:!0})}catch(n){const o=n instanceof Error&&/^git-lifecycle-/.test(n.message)?n.message:"git-lifecycle-runtime-invalid";if(t.allowMissingRuntime&&o==="git-lifecycle-runtime-missing")return{lifecycleDeclared:!0,runtimeMissing:!0};throw new lt(o)}return{lifecycleDeclared:a,runtimeMissing:!1}}function Cn(e,t={}){const i=z(e,".neocortex","state.json");if(!jt(i)){if(t.epicAware&&!t.projectless)throw new lt("git-lifecycle-state-missing");return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}let r,a;try{const E=Fe(i,"utf-8");a=Ne("sha256").update(E).digest("hex");const h=JSON.parse(E),I=g(h.epics)?h.epics:{},b=Object.values(I).some(w=>g(w)&&(w.branch_mode==="epic"||Ee(w.execution_branch)!==void 0)),D=fn(e,{required:!!(t.epicAware&&b&&!t.projectless)});r=Br(h,D);const P=g(r.stories)?r.stories:{},k=g(r.epics)?r.epics:{},R=g(h.stories)?h.stories:{};for(const[w,j]of Object.entries(P)){const L=g(j)?j:void 0;if(!L?.checkpoint)continue;const Y=typeof L.epic_id=="string"?L.epic_id:w.split(".")[0],X=g(k[Y])?k[Y]:void 0,pe=Ee(X?.execution_branch);if(!pe)continue;const x=ao(e,L.checkpoint,w,Y,pe,t.p205Authorities?.[w],Ur(w,L,g(L.checkpoint)?L.checkpoint:void 0));if(x.kind==="integration-authorized")L.checkpoint_verification=x.verification,delete L.scheduling_checkpoint_evidence;else if(x.kind==="scheduling-only")L.scheduling_checkpoint_evidence=x.evidence,delete L.checkpoint,delete L.checkpoint_verification;else if(x.kind==="rejected"){L.checkpoint_verification=x.verification,delete L.scheduling_checkpoint_evidence;const Se=g(R[w])?R[w]:void 0;if(delete L.checkpoint,D.stories[w]?.checkpoint!==void 0)for(const Z of["status","last_step","steps_completed"])Se&&Object.prototype.hasOwnProperty.call(Se,Z)?L[Z]=structuredClone(Se[Z]):delete L[Z];["done","completed","merged"].includes(String(L.status).toLowerCase())&&(L.status="blocked")}}}catch(E){if(t.epicAware&&!t.projectless){const h=E instanceof Error&&/^git-lifecycle-/.test(E.message)?E.message:"git-lifecycle-state-corrupt";throw new lt(h)}return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}try{const E=Jo(r);E.length>0&&Ko(E)}catch{}const n=r.config??r.project??{},o=r.stories??{},d={};for(const[E,h]of Object.entries(o)){const I=g(h.review_request)&&h.review_request.kind==="git-pull-request"?ac(h.review_request):Qn(h.review_request);d[E]={id:h.id??E,title:h.title,epic_id:h.epic_id,status:h.status??"backlog",...ii(h.source)?{source:ii(h.source)}:{},steps_completed:h.steps_completed??[],last_step:h.last_step??null,branch_name:h.branch_name??null,pr_number:h.pr_number,...vn(h.branch_mode)?{branch_mode:vn(h.branch_mode)}:{},...oi(h.checkpoint)?{checkpoint:oi(h.checkpoint)}:{},...ci(h.checkpoint_verification)?{checkpoint_verification:ci(h.checkpoint_verification)}:{},...si(h.scheduling_checkpoint_evidence)?{scheduling_checkpoint_evidence:si(h.scheduling_checkpoint_evidence)}:{},...I?{review_request:I}:{},...Qn(h.rollback_receipt)?{rollback_receipt:Qn(h.rollback_receipt)}:{},...Rt(h.workflow_issue)?{workflow_issue:Rt(h.workflow_issue)}:{},...dc(h),depends_on:ri(h.depends_on),files_to_modify:de(h.files_to_modify),...tc(h),risk:typeof h.risk=="string"?h.risk:void 0,blast_radius:typeof h.blast_radius=="number"?h.blast_radius:void 0}}const s=r.epics??{},l={};for(const[E,h]of Object.entries(s)){const I=Qo(h.lifecycle_classification),b=ec(h.createEpicPlanning,E),D=b.checkpoint;let P,k,R,w;if(D&&g(h.createEpicPlanningClaim)&&typeof h.createEpicPlanningClaim.claimId=="string"&&g(h.createEpicPlanningPhysical))try{Cr(r,h.createEpicPlanningClaim.claimId,E,!0),P=JSON.parse(JSON.stringify(h.createEpicPlanningPhysical))}catch{}if(P&&g(h.createEpicPlanningClaim)&&typeof h.createEpicPlanningClaim.claimId=="string"&&g(h.createEpicPlanningResearchPhysical))try{Rr(r,h.createEpicPlanningClaim.claimId,E),k=JSON.parse(JSON.stringify(h.createEpicPlanningResearchPhysical))}catch{}if(t.verifyPlanningGeneration&&D&&h.status==="generated"&&g(h.createEpicPlanningClaim)&&typeof h.createEpicPlanningClaim.claimId=="string"&&g(h.createEpicPlanningGenerationPhysical))try{if(ia(e,h.createEpicPlanningClaim.claimId,E).stateSha256!==a)throw new Error("planning-generation-snapshot-raced");R=JSON.parse(JSON.stringify(h.createEpicPlanningGenerationPhysical)),P=JSON.parse(JSON.stringify(h.createEpicPlanningPhysical)),k=JSON.parse(JSON.stringify(h.createEpicPlanningResearchPhysical))}catch{}if(R&&g(h.createEpicPlanningClaim)&&typeof h.createEpicPlanningClaim.claimId=="string")try{const j=_r(e,h.createEpicPlanningClaim.claimId,E);if(j.stateSha256!==a)throw new Error("planning-memory-snapshot-raced");w=JSON.parse(JSON.stringify(j))}catch{}l[E]={id:h.id??E,title:h.title,...D?{createEpicPlanning:D}:{},...b.diagnostic?{createEpicPlanningProjection:b.diagnostic}:{},...P?{createEpicPlanningPhysical:P}:{},...k?{createEpicPlanningResearchPhysical:k}:{},...R?{createEpicPlanningGenerationPhysical:R}:{},...w?{createEpicPlanningMemoryPhysical:w}:{},status:h.status,stories:h.stories,total_stories:h.total_stories,completed_stories:h.completed_stories,depends_on:ri(h.depends_on),...vn(h.branch_mode)?{branch_mode:vn(h.branch_mode)}:{},...Ee(h.execution_branch)?{execution_branch:Ee(h.execution_branch)}:{},...Ee(h.origin_branch)?{origin_branch:Ee(h.origin_branch)}:{},...ai(h.branch_lease)?{branch_lease:ai(h.branch_lease)}:{},...pi(h.origin_binding)?{origin_binding:pi(h.origin_binding)}:{},...li(h.aggregate_qa_receipt)?{aggregate_qa_receipt:li(h.aggregate_qa_receipt)}:{},...ui(h.head_reconciliation_receipt)?{head_reconciliation_receipt:ui(h.head_reconciliation_receipt)}:{},...fo(h.story_worktree_evidence)?{story_worktree_evidence:structuredClone(h.story_worktree_evidence)}:{},...Rt(h.pr_number)?{pr_number:Rt(h.pr_number)}:{},...Q(h.physicalMergeStatus)?{physicalMergeStatus:Q(h.physicalMergeStatus)}:{},..._(h.graph_revision)?{graph_revision:_(h.graph_revision)}:{},...hi(h.terminal_git_receipt)?{terminal_git_receipt:hi(h.terminal_git_receipt)}:{},...I?{lifecycle_classification:I}:{}}}const y=sc(r.current_session??r.currentSession),S=g(r.archPlan)?En(r.archPlan.execution):void 0,u=r.epic_id_ledger,C=Array.isArray(u?.reserved_ids)?[...new Set(u.reserved_ids.filter(E=>typeof E=="string"&&/^P\d+$/.test(E)))].slice(0,2048):[];return{schema_version:typeof r.schema_version=="number"?r.schema_version:void 0,config:{project_name:n.project_name??n.name??"unknown",default_branch:n.default_branch??"main",language:n.language??"pt-BR",yolo_mode:n.yolo_mode,user_name:n.user_name,worktree_base:n.worktree_base,max_parallel_stories:n.max_parallel_stories,project_id:typeof n.project_id=="string"?n.project_id:void 0},stories:d,epics:l,...C.length>0?{epic_id_ledger:{schema_version:1,reserved_ids:C}}:{},...y?{current_session:y}:{},...S?{archPlan:{execution:S}}:{}}}const Zn=[["P222.01","fbc3176b33687b13a8fadf8c7ea7cc06b6b6c500"],["P222.02","c7d3feb9a168f9e15b35516a972c767f3aa357da"],["P222.03","4d9bd4f2a1a3a1dc6399c572eb84b8b74c017806"],["P222.04","66590ef2f706c9d036f42edf5e517b237724f74f"],["P222.05","3ee2662538311e9788796340ed11b65864a8d8d5"],["P222.06","8660d07e3f68503a9ceb24dc138d24f62ab6cb45"],["P222.07","d99c80feacee8ea4033aa3322990147fffa2df91"],["P222.08","1f9e37dc922d87908efefb9595db32d32db30b00"],["P222.09","5ae12e485900992658e346cf3e38568fda1c2eeb"],["P222.10","6c5b8dc4f03d629fea4b62a33f4794af8e27e4f0"],["P222.11","cfe90f2f955c0027c57e4c621141d17912db65cc"],["P222.12","65f253c5cb600a8ee1dd94a1efdfef2fa5cd1629"],["P222.13","1e78c75b393515803a55d1a9b63a7fec23f710c9"],["P222.14","3f3e0bfd247a8581170df2a23c89497b5ae3641e"],["P222.15","1fd6dd25fffa5714d4ffa8b4303735e417f93de6"]],er="6a41a47ff2521f80c2296ed811b0f0b304c54750",tr="dbc6d4670b2b7868a01973b1240e24589f1c5b7d",fi="30dccfff07f9c969be11ae1d28e62a09731a0768";function lc(e,t){try{const i=t.indexOf(fi);if(i<1||t[i-1]!==er)return new Map;const r=Ge("git",["show","--no-patch","--format=%P",fi],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim(),a=Ge("git",["show","--no-patch","--format=%P",tr],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim();if(r!==`${er} ${tr}`||a!==`${Zn.at(-1)[1]} ${er}`)return new Map;const n=Ge("git",["rev-list","--first-parent","--reverse",tr],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
|
|
9
|
+
`),o=new Map;let d=-1;for(const[s,[l,y]]of Zn.entries()){const S=n.indexOf(y);if(S<=d)return new Map;d=S,o.set(l,{headSha:y,position:s-Zn.length})}return o}catch{return new Map}}function uc(e){return e instanceof Error&&(po(e.message)||/^(?:p205|git-lifecycle)-[a-z0-9-]+$/.test(e.message))?e.message:"p205-transient-execution-failed"}async function hc(e,t,i){if(!gi(i))return{};if(i==="audit"||i==="yoloop")return{};if(kr(t,i))return{};try{const r=JSON.parse(Fe(z(e,".neocortex","state.json"),"utf8")),a=fn(e,{required:!0}),n=Br(r,a),o=g(n.stories)?n.stories:{},d=g(n.epics)?n.epics:{},s=Ge("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8"}).trim(),l=Ge("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8"}).trim(),y=Ge("git",["rev-list","--first-parent","--reverse",s],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
|
|
10
|
+
`).filter(Boolean),S=new Map(y.map((R,w)=>[R,w])),u=lc(e,y),C=t.match(/(?:^|\s)@?docs\/stories\/([A-Za-z][A-Za-z0-9._-]*)\.story\.md(?:\s|$)/)?.[1],E=i==="yoloop"?t.match(/(?:^|[\s/@])epic-(P[1-9][0-9]*)\.md(?:\s|$)/i)?.[1]?.toUpperCase():void 0,h=new Set,I=Object.entries(o).flatMap(([R,w])=>{if(C&&R!==C)return[];const j=g(w)?w:void 0,L=g(j?.checkpoint)?j.checkpoint:void 0;if(!L)return[];const Y=typeof j?.epic_id=="string"?j.epic_id:R.split(".")[0];if(E&&Y!==E)return[];const X=_(L?.headSha),pe=Y==="P222"?u.get(R):void 0,x=S.get(X??"")??(pe&&pe.headSha===X?pe.position:void 0);if(!X||X.length<40||x===void 0)return h.add(Y),[];const Se=g(d[Y])?d[Y]:void 0;if(Se?.branch_mode!=="epic"||Ee(Se.execution_branch)!==l||Ee(L.branch)!==l)return h.add(Y),[];const Z=_(L.graphRevision);if(!Z||Z.length!==64)return h.add(Y),[];const J=_(L.claimRevision),gt=[...Ur(R,j,L)].sort(),wt=yo(e,L,R,Y,l,gt);if(!wt&&J){if(gt.length===0)return h.add(Y),[];const ue=Ge("git",["diff-tree","--no-commit-id","--name-only","-r","-z",X],{cwd:e,encoding:"utf8"}).split("\0").filter(Boolean),O=uo(R,gt).map(xe=>[...xe].sort()).find(xe=>J===Ne("sha256").update(xe.join("\0")).digest("hex")||J===Ne("sha256").update(JSON.stringify(xe)).digest("hex"));if(!O)return h.add(Y),[];let $=[];if(L.rootMemoryEffect!==void 0)try{$=Io(e,L.rootMemoryEffect,{storyId:R,executionBranch:l,baseSha:String(L.baseSha),headRef:X,childPaths:O}).files.map(xe=>xe.path)}catch{return h.add(Y),[]}if(ue.length===0||ue.some(xe=>!O.some(Te=>ho(Te,xe))&&!$.includes(xe)))return h.add(Y),[]}else if(!wt)return h.add(Y),[];return Z?.length===64?[{storyId:R,epicId:Y,graphRevision:Z,checkpointHead:X,position:x}]:[]}),b=new Set(h);for(const[R,w]of Object.entries(d)){const j=g(w)?w:void 0,L=Array.isArray(j?.stories)?j.stories.filter(x=>typeof x=="string"):Object.keys(o).filter(x=>x.startsWith(`${R}.`)),Y=I.filter(x=>x.epicId===R),X=L.filter(x=>Y.some(Se=>Se.storyId===x)),pe=[...Y].sort((x,Se)=>x.position-Se.position).map(x=>x.storyId);(JSON.stringify(X)!==JSON.stringify(pe)||new Set(pe).size!==pe.length)&&b.add(R)}const D={},P=[...new Set(I.filter(R=>!b.has(R.epicId)).map(R=>R.graphRevision))],k=P.length>0?await so(e,{headSha:s,graphRevisions:P}):new Map;for(const R of I){if(b.has(R.epicId))continue;const w=k.get(R.graphRevision);if(!w)throw new Error("p205-transient-authority-missing");D[R.storyId]=w}return await gc({projectRoot:e,commandId:i,targetEpicId:E,currentHead:s,epics:d,candidates:I,authorities:D}),D}catch(r){const a=uc(r);return process.stderr.write(`[Neocortex] ${a}. Checkpoint projection remains fail-closed.
|
|
11
|
+
`),{}}}async function gc(e){if(e.commandId!=="yoloop"||!e.targetEpicId)return;const t=e.epics[e.targetEpicId],i=g(t)?t:void 0,r=g(i?.aggregate_qa_receipt)?i.aggregate_qa_receipt:void 0,a=_(i?.graph_revision);if(!r||!a||a.length!==64||r.schemaVersion!==1||r.evidenceVersion!=="p205-execution-v2"||r.producer!=="local-yolo-tdd"||r.contract!=="P205-CI-02"||r.command!==Xt||r.verdict!=="passed"||r.executionHeadSha!==e.currentHead||r.graphRevision!==a||!Array.isArray(r.gateIds)||r.gateIds.length===0||!r.gateIds.every(S=>typeof S=="string")||typeof r.manifestDigest!="string"||!/^[a-f0-9]{64}$/i.test(r.manifestDigest)||typeof r.resultDigest!="string"||!/^[a-f0-9]{64}$/i.test(r.resultDigest)||typeof r.receiptRef!="string"||!/^local-yolo-tdd:[a-f0-9]{64}$/i.test(r.receiptRef))return;const n=r.gateIds,o=`local-yolo-tdd:${Ne("sha256").update(["epic-aggregate-p205-execution-v2",Xt,e.currentHead,a,r.manifestDigest,n.join(","),r.resultDigest].join("\0")).digest("hex")}`;if(r.receiptRef!==o)return;const d=e.candidates.find(S=>S.epicId===e.targetEpicId&&S.graphRevision===a&&e.authorities[S.storyId]),s=d?mo(e.authorities[d.storyId]):void 0;if(!s||s.executionHeadSha!==e.currentHead||s.graphRevision!==a||s.manifestDigest!==r.manifestDigest||!fc(s.gateIds,n))return;const l=`local-yolo-tdd:${Ne("sha256").update(["epic-aggregate-p205-execution-v2",Xt,e.currentHead,a,s.manifestDigest,s.gateIds.join(","),s.resultDigest].join("\0")).digest("hex")}`,y=r.receiptRef;await $r(e.projectRoot,S=>{const u=oo(S,e.targetEpicId),C=g(u.aggregate_qa_receipt)?u.aggregate_qa_receipt:void 0;!C||C.executionHeadSha!==e.currentHead||C.graphRevision!==a||C.receiptRef!==y||(u.aggregate_qa_receipt={schemaVersion:1,evidenceVersion:"p205-execution-v2",producer:"local-yolo-tdd",contract:"P205-CI-02",command:Xt,verdict:"passed",executionHeadSha:e.currentHead,graphRevision:a,manifestDigest:s.manifestDigest,resultDigest:s.resultDigest,checkedAt:s.executedAt,receiptRef:l,gateIds:[...s.gateIds]})})}function fc(e,t){if(e.length!==t.length)return!1;const i=[...t].sort();return[...e].sort().every((r,a)=>r===i[a])}function Hd(e,t){return{kind:"full",trigger:e,targetEpicId:null,targetStoryId:null,includedStoryCount:Object.keys(t.stories).length,includedEpicCount:Object.keys(t.epics).length,omittedStoryCount:0,omittedEpicCount:0,reason:"full-state",projectionMode:"full-compatible"}}const mi="neocortex:menu:cache";async function mc(e){try{const t=await e.get(mi);if(!t)return null;const i=JSON.parse(t);return i.version!==Pt||Date.now()-i.cachedAt>Yr?null:i}catch{return null}}async function yc(e,t,i){try{const r={instructions:t,metadata:i,cachedAt:Date.now(),version:Pt};await e.set(mi,JSON.stringify(r),Yr),Ic()}catch{}}function Ic(){try{jt(Fr)&&Dn(Fr)}catch{}}function yi(e){return e.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>Vn(),()=>Vn({strictReadOnly:!0}))}async function Ii(e,t,i){const r=i.mode==="strict";try{let a;if(r&&t)a=new jn({cacheDir:Hn,passphrase:t,strictReadOnly:!0});else if(r)a=new Ar;else if(t){const y=z(mn,"cache");a=new jn({cacheDir:y,passphrase:t})}else process.stderr.write(`[neocortex] Warning: No license key in config. Run "neocortex activate" to re-authenticate.
|
|
12
|
+
`),a=new Ar;const n=jr(i,a,"auth-cache"),o=jr(i,a,"tier-cache"),d=new da({serverUrl:e,licenseKey:t??"",cacheProvider:n,strictReadOnly:r});let s;if(r){const y=await d.inspectToken();if(y.status!=="authenticated")return y;s=y.token}else s=await d.getToken();if(!s)return t?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"};const l=new pa({cacheProvider:o,licenseClient:d});return{status:"authenticated",token:s,client:d,tierClient:l}}catch{return t?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"}}}let Ei=!1;function Ec(e){const t=e.errorBody?.error_code;if(typeof t=="string"&&t.trim().length>0)return t;if(e.status===429)return"RATE_LIMITED";if(e.status>=500)return"SERVER_ERROR"}const Si=3,Rn=50;function Sc(e){return new Promise(t=>setTimeout(t,e))}function vc(e,t,i){return e.status>=500&&e.status<=599?!0:i&&e.status===409&&t.error_code==="SIGNATURE_REPLAYED"}async function Zt(e,t,i,r,a={}){const n=Math.max(1,Math.min(a.maxAttempts??Si,Si)),o=a.sleep??Sc;let d=r,s=!1,l=!1,y=0;for(let S=1;S<=n;S+=1){const u=Math.max(Math.floor(Date.now()/1e3),y+1);y=u;const C=Cc(t,i,d,{nowSeconds:u}),E=new AbortController,h=setTimeout(()=>E.abort(),qr);try{const I=await fetch(`${e}${t}`,{method:"POST",headers:C.headers,body:C.body,signal:E.signal});if(a.admitResponseBeforeBodyRead&&!a.admitResponseBeforeBodyRead(I))return{response:I,text:"",parsed:{},networkFailure:!1,responseAdmissionRejected:!0};const b=await I.text().catch(()=>""),D=I.ok&&a.deferSuccessfulJsonParsing?{}:(()=>{try{return b?JSON.parse(b):{}}catch{return{}}})();if(I.status===401&&!s&&a.refreshToken&&(D.fallback_action==="refresh_token"||D.fallback_action==="re_authenticate")){s=!0;const P=await a.refreshToken();if(P&&S<n){d=P,a.onTokenChanged?.(P),await o(Rn*S);continue}}if(I.status===401&&D.error_code==="SIGNATURE_EXPIRED"&&!l&&S<n){l=!0,await o(Rn*S);continue}if(S<n&&vc(I,D,a.allowReplayRetry===!0)){await o(Rn*S);continue}return{response:I,text:b,parsed:D,networkFailure:!1}}catch{if(S<n){await o(Rn*S);continue}return{text:"",parsed:{},networkFailure:!0}}finally{clearTimeout(h)}}return{text:"",parsed:{},networkFailure:!0}}function Cc(e,t,i,r={}){const a=Buffer.from(JSON.stringify(t),"utf8"),n=Oa({method:"POST",target:e,body:a,bearerToken:i,clientVersion:Pt,nowSeconds:r.nowSeconds,nonceBytes:r.nonceBytes});return{body:n.body,headers:{...n.headers,Authorization:`Bearer ${i}`}}}function vi(e){return Ne("sha256").update(e).digest("hex")}function Rc(){const e=Number(process.env.NEOCORTEX_INVOKE_CHUNK_BYTES??"49152");return Number.isFinite(e)&&e>=1024&&e<=98304?Math.floor(e):49152}function _c(e,t,i){return`args-${Ne("sha256").update("invoke-materialization:v1").update(e).update(String(t)).update(JSON.stringify(i)).digest("hex")}`}async function Ci(e,t,i,r,a={}){const n=await Zt(e,t,i,r,{...a,allowReplayRetry:!0});if(n.networkFailure||!n.response)throw new Error("NETWORK_ERROR: materialization request failed after bounded retries");const{response:o,parsed:d}=n;if(!o.ok){const s=typeof d.error_code=="string"?d.error_code:`HTTP_${o.status}`,l=typeof d.message=="string"?d.message:"materialization upload failed";throw new Error(`${s}: ${l}`)}return d}async function wc(e,t,i,r){const a=Buffer.from(t,"utf8"),n=Rc(),o=[];for(let E=0,h=0;E<a.byteLength;E+=n,h++){const I=a.subarray(E,Math.min(E+n,a.byteLength));o.push({index:h,sha256:vi(I),byteLength:I.byteLength})}const d=vi(a),s=_c(d,a.byteLength,o),l=Number(process.env.NEOCORTEX_INVOKE_CHUNK_TTL_SECONDS??"900");let y=i;const S={refreshToken:r,onTokenChanged(E){y=E}};for(const E of o){const h=E.index*n,I=a.subarray(h,h+E.byteLength);await Ci(e,"/api/v1/invoke/materialization/chunks",{manifestId:s,index:E.index,sha256:E.sha256,byteLength:E.byteLength,contentBase64:I.toString("base64"),ttlSeconds:l,idempotencyKey:`${s}:${E.index}:${E.sha256}`},y,S)}const C=(await Ci(e,"/api/v1/invoke/materialization/manifests",{manifestId:s,sha256:d,byteLength:a.byteLength,chunkCount:o.length,chunks:o,ttlSeconds:l,retry:{attempt:1,budget:3,idempotencyKey:s}},y,S)).argsRef;if(!C?.manifestId)throw new Error("MATERIALIZATION_RESPONSE_INVALID: missing argsRef");return{argsRef:C,chunks:o}}function Wt(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function Ac(...e){const t=new Set,i=[];for(const r of e)for(const a of r??[]){const n=Q(a);if(!(!n||t.has(n))&&(t.add(n),i.push(n),i.length>=16))return i}return i}function bc(e){const t=e.graphRetrieval;if(!g(t))return{accepted:!1,itemCount:0};const i=Array.isArray(t.items)?t.items.length:0;return{accepted:i>0||typeof t.retrievalId=="string"||t.accepted===!0,itemCount:i}}function nr(e,t=Wt(e),i=[],r={}){const a=e.stateSnapshot.scope,n=Object.keys(e.stateSnapshot.stories).length,o=Object.keys(e.stateSnapshot.epics).length,d=a?.kind??"full";return{schemaVersion:1,payloadBytes:t,limitBytes:r.limitBytes??Jr,warningThresholdBytes:r.warningThresholdBytes??Wn,scope:{kind:d,...a?.projectionMode?{projectionMode:a.projectionMode}:{},commandId:a?.commandId??null,stateProjectionPolicy:a?.stateProjectionPolicy??null},includedStories:a?.includedStoryCount??n,omittedStories:a?.omittedStoryCount??0,includedEpics:a?.includedEpicCount??o,omittedEpics:a?.omittedEpicCount??0,graphRetrieval:bc(e.stateSnapshot),reasonCodes:Ac(i,a?.reasonCodes),publicSafe:!0}}function xc(e){const t=g(e.budget)?e.budget:void 0,i=typeof t?.maxPayloadBytes=="number"&&Number.isFinite(t.maxPayloadBytes)?t.maxPayloadBytes:12*1024;return Math.max(1024,Math.min(i,12*1024))}function Tc(e){return g(e)?{stableId:Q(e.stableId)??"unknown",...g(e.source)?{source:e.source}:{},reasonCode:"budget_exceeded"}:{stableId:"unknown",reasonCode:"budget_exceeded"}}function Ri(e){const t=Array.isArray(e)?e.filter(i=>typeof i=="string"):[];return t.includes("budget_exceeded")?t:[...t,"budget_exceeded"]}function Pc(e){const t=e.graphRetrieval;if(!g(t)||!Array.isArray(t.items))return e;const i=xc(t);let r=[...t.items],a=Array.isArray(t.skipped)?[...t.skipped]:[],n=t;for(;Buffer.byteLength(JSON.stringify(n),"utf8")>i&&r.length>0;){const o=r.pop();a=[...a,Tc(o)].slice(-32),n={...t,items:r,skipped:a,warnings:Ri(t.warnings)}}return Buffer.byteLength(JSON.stringify(n),"utf8")>i&&(n={...t,query:typeof t.query=="string"?t.query.slice(0,240):t.query,items:[],skipped:[],warnings:Ri(t.warnings)}),n===t?e:{...e,graphRetrieval:n}}function rr(e,t={}){const i=t.limitBytes??Jr,r=t.warningThresholdBytes??Math.floor(i*Kr),a=Wt(e);if(a<i)return{body:e,degraded:!1,telemetry:nr(e,a,["payload-within-limit"],{limitBytes:i,warningThresholdBytes:r})};let n={...e,stateSnapshot:ma(e.stateSnapshot)},o=["payload-size-guardrail","state-degraded"],d=Wt(n);d>=i&&(n={...n,stateSnapshot:Pc(n.stateSnapshot)},o=[...o,"graph-retrieval-budget-enforced"],d=Wt(n));const s=nr(n,d,o,{limitBytes:i,warningThresholdBytes:r});if(d>=i){const l=n.stateSnapshot.scope?.projectionMode;throw l==="yolo-story"||l==="yoloop-target"||l==="yoloop-session"||l==="yoloop-discovery"||l==="structural-required"?new Jn(s):new zn(s)}return{body:n,degraded:!0,telemetry:s}}function _i(e){const t=e.stateSnapshot.scope?.commandId??"resolved-command";return e.args!==void 0?t:`${t}:argsRef`}function kc(e){const t=Wt(e);if(t<Wn)return t;const i=nr(e,t,["payload-warning-threshold"]);return process.stderr.write(`[Neocortex] invoke payload near server limit: trigger=${_i(e)} scope=${i.scope.kind} mode=${i.scope.projectionMode??i.scope.kind} payloadBytes=${i.payloadBytes} limit=${i.limitBytes} includedStories=${i.includedStories} omittedStories=${i.omittedStories} includedEpics=${i.includedEpics} omittedEpics=${i.omittedEpics} graphRetrieval.accepted=${i.graphRetrieval.accepted} graphRetrieval.itemCount=${i.graphRetrieval.itemCount} reasonCodes=${i.reasonCodes.join(",")||"none"}
|
|
13
|
+
`),t}function wi(e,t){process.stderr.write(`[Neocortex] invoke payload guardrail: trigger=${_i(e)} scope.kind=${t.scope.kind} payloadBytes=${t.payloadBytes} limit=${t.limitBytes} includedStories=${t.includedStories} omittedStories=${t.omittedStories} includedEpics=${t.includedEpics} omittedEpics=${t.omittedEpics} graphRetrieval.accepted=${t.graphRetrieval.accepted} graphRetrieval.itemCount=${t.graphRetrieval.itemCount} reasonCodes=${t.reasonCodes.join(",")||"none"}
|
|
14
|
+
`)}async function Oc(e){const t=Ra(e.args,{platformTarget:e.platformTarget,environment:e.environment??process.env});if(t.action==="skipped")return{shouldContinue:!0,attachToRequest:Nc(t),metadata:Ai(t)};const i=e.bootstrapper??wa;let r;try{r=await i({projectRoot:e.projectRoot,env:e.environment??process.env,effectAuthority:e.effectAuthority})}catch{r={ok:!1,attempted:!0,installed:!1,started:!1,cached:!1,projectKey:"unknown",reasonCodes:[_a.UNEXPECTED_ERROR],publicSummary:"runner scheduler bootstrap stopped unexpectedly.",publicSafe:!0}}const a=Ai(t,r);if(r.ok)return{shouldContinue:!0,attachToRequest:!0,metadata:a};const n=a.reasonCodes.slice(0,5).join(",");return t.failurePolicy==="fail-open"?{shouldContinue:!0,attachToRequest:!0,metadata:{...a,failOpenWarning:!0},warning:`Runner auto-bootstrap warning (${n}); continuing fail-open for operator command.`}:{shouldContinue:!1,attachToRequest:!1,metadata:a,errorCode:"RUNNER_BOOTSTRAP_REQUIRED_FAILED",error:`Runner auto-bootstrap required but failed (${n}). Run neocortex-runner doctor or retry after resolving scheduler setup.`,exitCode:1}}function Nc(e){return!e.reasonCodes.includes(Ca.SKIPPED_NON_CONTINUITY_COMMAND)}function Ai(e,t){return{schemaVersion:1,action:e.action,failurePolicy:e.failurePolicy,command:e.command,operation:e.operation,attempted:t?.attempted??!1,ok:t?.ok??!0,cached:t?.cached??!1,installed:t?.installed??!1,started:t?.started??!1,...t?.projectKey?{projectKey:t.projectKey}:{},reasonCodes:Be([...e.reasonCodes,...t?.reasonCodes??[]]),publicSummary:t?.publicSummary??e.publicSummary,publicSafe:!0}}function Be(e){return Array.from(new Set(e.map(t=>t.slice(0,120))))}function _n(e,t,i){const r=Math.floor(e??t);return Number.isFinite(r)?Math.max(1,Math.min(i,r)):t}function wn(e,t){const i=process.env[e];if(!i)return t;const r=Number(i);return Number.isFinite(r)?r:t}function F(e,t=ni){const i=typeof e=="string"&&e.trim().length>0?e.trim():"unknown",r=Je(i,t),a=Ho.test(r)?Ct:r;return a.length<=t?a:`${a.slice(0,t)}\u2026[TRUNCATED:${a.length-t}]`}function ir(e,t=ni){if(!(typeof e!="string"||e.trim().length===0))return F(e,t)}function ar(e,t,i,r){const a=ir(e?.targetId??t,120),n=e?.selectorKind??(a?cr(a):void 0),o=(e?.relatedJobIds??[]).map(d=>ir(d,120)).filter(d=>!!d);return{schemaVersion:1,contractVersion:"continuity-v1",targetResolutionState:i,...n?{targetKind:n}:{},...a?{targetId:a}:{},...t?{targetJobId:F(t,120)}:{},...e?.jobId?{jobId:F(e.jobId,120)}:{},...e?.goalId?{goalId:F(e.goalId,120)}:{},...e?.loopId?{loopId:F(e.loopId,120)}:{},...o.length>0?{relatedJobIds:o}:{},relatedJobCount:o.length,reasonCodes:Be(r.length>0?r:[G.OK]),publicSafe:!0}}function ut(e,t,i,r,a=[]){const n=(e?.redactions?.length??0)>0,o=e?n?"unsafe":i&&r===0?"empty":"available":"unavailable",d=ir(t[t.length-1]?.eventId,120),s=a.length>0?a:o==="unavailable"?[G.WATCH_SNAPSHOT_UNAVAILABLE]:o==="empty"?[G.WATCH_NO_SUMMARIES_YET]:[G.OK];return{schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:o,...e?.generatedAt?{generatedAt:F(e.generatedAt,80)}:{},renderedSummaryCount:r,...d?{latestEventId:d}:{},reasonCodes:Be(s),publicSafe:!0}}function et(e,t,i,r,a=[],n){const o=r[r.length-1],d=i??o?.cursor,s=!!(d&&d!==t&&r.length>0),l=n??(s?"advanced":t||d?"unchanged":"not_started"),y=a.length>0?a:l==="advanced"?[G.WATCH_CURSOR_ADVANCED]:l==="unavailable"?[G.WATCH_EVIDENCE_UNAVAILABLE]:[G.WATCH_CURSOR_UNCHANGED];return{schemaVersion:1,contractVersion:"continuity-v1",cursorState:l,...e?{initialCursor:F(e,200)}:{},...t?{currentCursor:F(t,200)}:{},...d?{nextCursor:F(d,200)}:{},cursorAdvanced:s,...o?.eventId?{eventId:F(o.eventId,120)}:{},reasonCodes:Be(y),publicSafe:!0}}function tt(e){const t=e.targetEvidence;return{type:"watch_status",schemaVersion:1,contractVersion:"continuity-v1",recordType:"watch_status",command:"invoke",operation:"watch",watchStatus:e.watchStatus,active:e.active,...t?.targetResolutionState?{targetResolutionState:t.targetResolutionState}:{},...t?.targetKind?{targetKind:t.targetKind}:{},...t?.targetId?{targetId:t.targetId}:{},...t?{targetEvidence:t}:{},...e.snapshotEvidence?{snapshotEvidence:e.snapshotEvidence}:{},...e.cursorEvidence?{cursorEvidence:e.cursorEvidence}:{},...e.stopReason?{stopReason:e.stopReason}:{},reasonCodes:Be([...e.reasonCodes??[],...t?.reasonCodes??[],...e.snapshotEvidence?.reasonCodes??[],...e.cursorEvidence?.reasonCodes??[]]),generatedAt:F(e.generatedAt??new Date().toISOString(),80),publicSafe:!0}}function Lc(e){const t=e.targetKind&&e.targetId?`${e.targetKind}/${e.targetId}`:e.targetId??"[unresolved]",i=e.snapshotEvidence?.renderedSummaryCount??0,r=e.targetEvidence?.relatedJobCount??0,a=e.cursorEvidence?.cursorState??"unavailable",n=e.cursorEvidence?.currentCursor??"[none]",o=e.cursorEvidence?.nextCursor??"[none]",d=e.snapshotEvidence?.snapshotStatus??"not_requested",s=e.snapshotEvidence?.generatedAt??e.generatedAt;return[`[watch-status] ${e.targetResolutionState==="unresolved"||e.stopReason==="target_unresolved"?"unresolved-target":i===0&&(e.watchStatus==="waiting"||e.watchStatus==="active")?"no-new-summary":e.watchStatus==="stopped"?"stopped":"lifecycle"}`,`status=${e.watchStatus}`,`active=${e.active}`,`target=${t}`,`resolution=${e.targetResolutionState??"unavailable"}`,`relatedJobs=${r}`,`summaries=${i}`,`snapshot=${d}`,`generatedAt=${s}`,`cursor=${a}`,`current=${F(n,200)}`,`next=${F(o,200)}`,`advanced=${e.cursorEvidence?.cursorAdvanced??!1}`,`stop=${e.stopReason??"not_stopped"}`,`reasons=${e.reasonCodes.join(",")}`].join(" ")}function nt(e,t,i,r=!1){if(r){const a={type:"watch_status",watchStatus:e.watchStatus,active:e.active,renderedSummaryCount:e.snapshotEvidence?.renderedSummaryCount??0,stopReason:e.stopReason??"not_stopped",protectedProjection:!0,publicSafe:!0};i.write(t==="json"?`${JSON.stringify(a)}
|
|
15
15
|
`:`[watch-status] status=${a.watchStatus} active=${a.active} summaries=${a.renderedSummaryCount} stop=${a.stopReason}
|
|
16
16
|
`);return}if(t==="json"){i.write(JSON.stringify(e)+`
|
|
17
|
-
`);return}i.write(
|
|
18
|
-
`)}function
|
|
17
|
+
`);return}i.write(Lc(e)+`
|
|
18
|
+
`)}function Dc(e,t,i){return{continuityInvokeWatch:{schemaVersion:1,contractVersion:"continuity-v1",command:"invoke",operation:"watch",watchStatus:e.watchStatus,stopReason:e.stopReason??"not_stopped",targetResolutionState:e.targetResolutionState,targetKind:e.targetKind,targetId:e.targetId,snapshotStatus:e.snapshotEvidence?.snapshotStatus,snapshotGeneratedAt:e.snapshotEvidence?.generatedAt,renderedSummaryCount:e.snapshotEvidence?.renderedSummaryCount??t,cursorState:e.cursorEvidence?.cursorState,cursorAdvanced:e.cursorEvidence?.cursorAdvanced,summariesEmitted:t,polls:i,statusRecord:e,publicSafe:!0}}}function ht(e,t,i,r,a=!1){return a?{status:e,summariesEmitted:t,polls:i,reasonCodes:[],watchStatus:r.watchStatus,stopReason:r.stopReason,metadata:{continuityInvokeWatch:{schemaVersion:1,contractVersion:"continuity-v1",command:"invoke",operation:"watch",watchStatus:r.watchStatus,stopReason:r.stopReason??"not_stopped",summariesEmitted:t,polls:i,protectedProjection:!0,publicSafe:!0}},publicSafe:!0}:{status:e,summariesEmitted:t,polls:i,reasonCodes:r.reasonCodes,watchStatus:r.watchStatus,stopReason:r.stopReason,targetEvidence:r.targetEvidence,snapshotEvidence:r.snapshotEvidence,cursorEvidence:r.cursorEvidence,statusRecord:r,metadata:Dc(r,t,i),publicSafe:!0}}function Mc(e){const t=e.reasonCode?` reason=${F(e.reasonCode,80)}`:"",i=e.goalId?` goal=${F(e.goalId,100)}`:"",r=e.loopId?` loop=${F(e.loopId,100)}`:"";return`[watch] ${F(e.createdAt,80)} event=${F(e.eventId,120)} job=${F(e.jobId,100)}${i}${r} execution=${F(e.executionId,120)}${t} -- ${F(e.publicSummary)}`}function jc(e){return{type:"processing_summary",source:"local_continuity_sqlite",eventId:F(e.eventId,120),jobId:F(e.jobId,100),...e.goalId?{goalId:F(e.goalId,100)}:{},...e.loopId?{loopId:F(e.loopId,100)}:{},executionId:F(e.executionId,120),...e.reasonCode?{reasonCode:F(e.reasonCode,80)}:{},createdAt:F(e.createdAt,80),publicSummary:F(e.publicSummary),publicSafe:!0}}function Vc(e,t,i,r=!1){if(r){i.write(t==="json"?`${JSON.stringify({type:"processing_summary",source:"local_continuity_sqlite",publicSummary:"A local processing update is available.",protectedProjection:!0,publicSafe:!0})}
|
|
19
19
|
`:`[watch] A local processing update is available.
|
|
20
|
-
`);return}if(t==="json"){i.write(JSON.stringify(
|
|
21
|
-
`);return}i.write(
|
|
22
|
-
`)}function ir(e){return No.has(e.status)}function kc(e,t,i){if(t){const a=e.find(n=>n.jobId===t);return!!(a&&ir(a))}return i<=0?!1:e.filter(a=>!ir(a)).length===0}function Oc(e,t,i,r){return i<r?!1:t?!e.some(a=>a.jobId===t&&!ir(a)):e.length===0}function Nc(e,t){return t?.aborted?Promise.resolve():new Promise(i=>{const r=setTimeout(a,e);function a(){clearTimeout(r),t?.removeEventListener("abort",a),i()}t?.addEventListener("abort",a,{once:!0})})}function Lc(e){return e.includes(ke.MALFORMED)?"malformed":e.includes(ke.AMBIGUOUS)?"ambiguous":e.includes("watch-target-multiple")?"multiple":e.includes("watch-evidence-unsafe")?"unsafe":e.includes(ke.MISSING)||e.includes(_e.TARGET_UNRESOLVED)?"unresolved":"unavailable"}function wi(e,t){const i=t?Zt(t):void 0,r=Me([...e,_e.TARGET_UNRESOLVED,F.WATCH_TARGET_UNRESOLVED]),a=rr(i,i?.targetId,Lc(r),r),n=dt({generatedAt:new Date().toISOString()},[],!1,0,[F.WATCH_TARGET_UNRESOLVED]),o=Xe(void 0,void 0,void 0,[],[F.WATCH_TARGET_UNRESOLVED],"unavailable");return Ze({watchStatus:"blocked",active:!1,targetEvidence:a,snapshotEvidence:n,cursorEvidence:o,stopReason:"target_unresolved",reasonCodes:r,generatedAt:n.generatedAt})}function Dc(e,t,i,r,a=!1){const n=wi(e,bi(t));return et(n,i,r,a),pt("target-unresolved",0,0,n,a)}async function Mc(e){if(e.signal?.aborted){const P=rr(e.target??Zt(e.targetJobId),e.targetJobId,e.target??e.targetJobId?"resolved":"unresolved",[_e.CANCELLED]),_=dt(void 0,[],!1,0),w=Xe(e.initialCursor,e.initialCursor,e.initialCursor,[],[_e.CANCELLED],"unavailable"),M=Ze({watchStatus:"stopped",active:!1,targetEvidence:P,snapshotEvidence:_,cursorEvidence:w,stopReason:"cancelled",reasonCodes:[_e.CANCELLED]});return pt("cancelled",0,0,M,e.protectedOutput)}const t=e.target??Zt(e.targetJobId),i=e.targetJobId??t?.targetId,r=e.stdout??process.stdout;if(!t){const P=wi([ke.MISSING,_e.TARGET_UNRESOLVED]);return et(P,e.format,r,e.protectedOutput),pt("target-unresolved",0,0,P,e.protectedOutput)}const a=_n(e.limit??Rn("NEOCORTEX_INVOKE_WATCH_LIMIT",kr),kr,50),n=Math.max(50,_n(e.pollIntervalMs??Rn("NEOCORTEX_INVOKE_WATCH_POLL_INTERVAL_MS",Lr),Lr,6e4)),o=_n(e.maxIdlePolls??Rn("NEOCORTEX_INVOKE_WATCH_MAX_IDLE_POLLS",Or),Or,120),d=_n(e.maxPolls??Rn("NEOCORTEX_INVOKE_WATCH_MAX_POLLS",Nr),Nr,86400),s=e.sleep??Nc;let l=e.initialCursor,y=0,S=0,u=0;const C=rr(t,i,"resolved",[F.OK]),E={schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:"pending",renderedSummaryCount:0,reasonCodes:[F.WATCH_RENDER_PENDING],publicSafe:!0},h=Xe(e.initialCursor,l,l,[],e.initialCursor?[F.WATCH_CURSOR_UNCHANGED]:[F.WATCH_NO_SUMMARIES_YET],e.initialCursor?"unchanged":"not_started");et(Ze({watchStatus:"active",active:!0,targetEvidence:C,snapshotEvidence:E,cursorEvidence:h,stopReason:"not_stopped",reasonCodes:[F.OK]}),e.format,r,e.protectedOutput);let I;try{I=await wa({projectRoot:e.projectRoot,strictReadOnly:e.strictReadOnly})}catch{const P=dt(void 0,[],!1,y,[F.WATCH_SNAPSHOT_UNAVAILABLE]),_=Xe(e.initialCursor,l,l,[],[F.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),w=Ze({watchStatus:"blocked",active:!1,targetEvidence:C,snapshotEvidence:P,cursorEvidence:_,stopReason:"unavailable_evidence",reasonCodes:[_e.STORE_UNAVAILABLE]});return et(w,e.format,r,e.protectedOutput),pt("store-unavailable",y,u,w,e.protectedOutput)}try{for(;!e.signal?.aborted&&u<d;){u+=1;const P=l,_=I.collectProcessingOutputSummaryCursor({...l?{cursor:l}:{},...t?{target:t}:{},...i?{jobId:i}:{},limit:a}),w=I.collectSnapshot({jobLimit:50,processingSummaryLimit:1}),M=w.jobs;if(_.summaries.length>0){for(const Z of _.summaries)Pc(Z,e.format,r,e.protectedOutput),y+=1;l=_.nextCursor??_.summaries[_.summaries.length-1]?.cursor??l,S=0}else l=_.nextCursor??l,S+=1;const N=dt(w,_.summaries,!0,_.summaries.length),z=Xe(e.initialCursor,P,l,_.summaries,_.summaries.length>0?[F.WATCH_CURSOR_ADVANCED]:[F.WATCH_NO_SUMMARIES_YET]);if(et(Ze({watchStatus:_.summaries.length>0?"polling":"waiting",active:!0,targetEvidence:C,snapshotEvidence:N,cursorEvidence:z,stopReason:"not_stopped",reasonCodes:_.summaries.length>0?[F.WATCH_CURSOR_ADVANCED]:[F.WATCH_NO_SUMMARIES_YET],generatedAt:w.generatedAt}),e.format,r,e.protectedOutput),!_.hasMore&&kc(M,i,y)){const Z=dt(w,_.summaries,!1,y,[_e.COMPLETED]),j=Xe(e.initialCursor,P,l,_.summaries,[_e.COMPLETED],"exhausted"),V=Ze({watchStatus:"stopped",active:!1,targetEvidence:C,snapshotEvidence:Z,cursorEvidence:j,stopReason:"not_stopped",reasonCodes:[_e.COMPLETED],generatedAt:w.generatedAt});return et(V,e.format,r,e.protectedOutput),pt("completed",y,u,V,e.protectedOutput)}if(!_.hasMore&&Oc(M,i,S,o)){const Z=dt(w,_.summaries,!1,y,[F.WATCH_STOP_IDLE_LIMIT_REACHED]),j=Xe(e.initialCursor,P,l,_.summaries,[F.WATCH_STOP_IDLE_LIMIT_REACHED],"exhausted"),V=Ze({watchStatus:"stopped",active:!1,targetEvidence:C,snapshotEvidence:Z,cursorEvidence:j,stopReason:"idle_limit_reached",reasonCodes:[_e.IDLE_TIMEOUT,F.WATCH_STOP_IDLE_LIMIT_REACHED],generatedAt:w.generatedAt});return et(V,e.format,r,e.protectedOutput),pt("idle-timeout",y,u,V,e.protectedOutput)}_.hasMore||await s(n,e.signal)}}catch{const P=dt(void 0,[],!1,y,[F.WATCH_SNAPSHOT_UNAVAILABLE]),_=Xe(e.initialCursor,l,l,[],[F.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),w=Ze({watchStatus:"blocked",active:!1,targetEvidence:C,snapshotEvidence:P,cursorEvidence:_,stopReason:"unavailable_evidence",reasonCodes:[_e.STORE_UNAVAILABLE]});return et(w,e.format,r,e.protectedOutput),pt("store-unavailable",y,u,w,e.protectedOutput)}finally{I.close()}if(e.signal?.aborted){const P=dt(void 0,[],!1,y,[_e.CANCELLED]),_=Xe(e.initialCursor,l,l,[],[_e.CANCELLED],"unavailable"),w=Ze({watchStatus:"stopped",active:!1,targetEvidence:C,snapshotEvidence:P,cursorEvidence:_,stopReason:"cancelled",reasonCodes:[_e.CANCELLED]});return et(w,e.format,r,e.protectedOutput),pt("cancelled",y,u,w,e.protectedOutput)}const b=dt(void 0,[],!1,y,[F.WATCH_STOP_MAX_POLLS_REACHED]),L=Xe(e.initialCursor,l,l,[],[F.WATCH_STOP_MAX_POLLS_REACHED],"exhausted"),T=Ze({watchStatus:"stopped",active:!1,targetEvidence:C,snapshotEvidence:b,cursorEvidence:L,stopReason:"max_polls_reached",reasonCodes:[_e.MAX_POLLS,F.WATCH_STOP_MAX_POLLS_REACHED]});return et(T,e.format,r,e.protectedOutput),pt("max-polls",y,u,T,e.protectedOutput)}function Je(e){const t=e.trim().replace(/^@/,"").match(/^(job|goal|loop)-([JGL])(\d{3,})$/i);if(!t)return;const i=t[1].toLowerCase(),r=t[2].toUpperCase();if(!(i==="job"&&r!=="J"||i==="goal"&&r!=="G"||i==="loop"&&r!=="L"))return`${i}-${r}${t[3]}`}function ar(e){if(e.startsWith("job-J"))return"job";if(e.startsWith("goal-G"))return"goal";if(e.startsWith("loop-L"))return"loop"}function Ai(e){const t=[],i=/(?:^|[\s"'([,{])@?(job-[Jj]\d{3,}|goal-[Gg]\d{3,}|loop-[Ll]\d{3,})(?=$|[\s"')\]},.;:!?])/g;let r;for(;(r=i.exec(e))!==null;){const a=Je(r[1]);a&&t.push(a)}return Me(t)}function bi(e){return Ai(e)[0]}function Zt(e){const t=e?Je(e):void 0;if(t){if(t.startsWith("job-J"))return{selectorKind:"job",targetId:t,jobId:t,publicSafe:!0};if(t.startsWith("goal-G"))return{selectorKind:"goal",targetId:t,goalId:t,publicSafe:!0};if(t.startsWith("loop-L"))return{selectorKind:"loop",targetId:t,loopId:t,publicSafe:!0}}}function or(e){return Me(e.filter(t=>typeof t=="string").map(t=>Je(t)).filter(t=>!!t?.startsWith("job-J")))}function jc(e,t){const i=or(t).filter(r=>r!==e.targetId&&r!==e.jobId);return i.length>0?{...e,relatedJobIds:i}:e}function Vc(e){if(!e)return;const t=g(e.target)?e.target:void 0,i=typeof e.selectorKind=="string"?e.selectorKind:typeof t?.selectorKind=="string"?t.selectorKind:void 0,r=typeof e.targetId=="string"?Je(e.targetId):typeof t?.targetId=="string"?Je(t.targetId):typeof e.targetJobId=="string"?Je(e.targetJobId):void 0,a=Zt(r);if(!a||i&&i!==a.selectorKind)return;const n=Array.isArray(e.relatedJobIds)?e.relatedJobIds:Array.isArray(t?.relatedJobIds)?t.relatedJobIds:void 0,o=or([...n??[],e.jobId,t?.jobId,e.targetJobId,t?.targetJobId]).filter(d=>d!==a.targetId&&d!==a.jobId);return{...a,...typeof(e.jobId??t?.jobId)=="string"?{jobId:Je(e.jobId??t?.jobId)??a.jobId}:{},...typeof(e.goalId??t?.goalId)=="string"?{goalId:Je(e.goalId??t?.goalId)??a.goalId}:{},...typeof(e.loopId??t?.loopId)=="string"?{loopId:Je(e.loopId??t?.loopId)??a.loopId}:{},...o.length>0?{relatedJobIds:o}:{}}}function xi(e){const t=e.trim().split(/\s+/).filter(Boolean),i=t[0]?.replace(/^\*/,"").toLowerCase(),r=t[1]?.replace(/^--/,"").toLowerCase();return(i==="jobs"||i==="job"||i==="continuity-jobs"||i==="61")&&r==="watch"}const xe=Object.freeze({ACTIVE:"command-level-watch-active",INACTIVE:"command-level-watch-inactive",DUPLICATE:"command-level-watch-duplicate",AMBIGUOUS:"command-level-watch-ambiguous",QUOTED:"command-level-watch-quoted",MALFORMED:"command-level-watch-malformed",NON_FINAL:"command-level-watch-non-final",UNRESOLVED:"command-level-watch-unresolved",UNSUPPORTED:"command-level-watch-unsupported",TARGET_INVALID:"command-level-watch-target-invalid"}),Bc=new Set(["create","start","resume"]),Uc=new Set(["create","resume","run-once"]);function cr(e,t,i,r,a){return{schemaVersion:1,contractVersion:"continuity-v1",...i?{command:i}:{},...r?{operation:r}:{},active:e,...a?{watchToken:a}:{},reasonCodes:Me(t),serverHeldStream:!1,allJobsPolling:!1,targetResolution:e?"required-after-dispatch":"inactive",publicSafe:!0}}function Ne(e,t=[],i,r){const a=t.length>0?t:[xe.INACTIVE];return{args:e,watch:!1,reasonCodes:a,metadata:cr(!1,a,i,r),publicSafe:!0}}function $c(e){const t=e.trim().split(/\s+/).filter(Boolean),i=t.slice(2).filter(n=>n==="--watch").length;if(i===0)return Ne(e,[],"jobs","watch");if(i!==1)return Ne(e,[xe.AMBIGUOUS],"jobs","watch");const r=t.filter((n,o)=>o<2||n!=="--watch").join(" ");return xi(r)?r.trim().split(/\s+/).filter(Boolean).slice(2).length!==1?Ne(e,[xe.AMBIGUOUS],"jobs","watch"):bi(r)?{args:r,watch:!0,reasonCodes:[xe.ACTIVE],metadata:cr(!0,[xe.ACTIVE],"jobs","watch"),publicSafe:!0}:Ne(e,[xe.TARGET_INVALID],"jobs","watch"):Ne(e,[xe.UNSUPPORTED],"jobs","watch")}function Hc(e){const t=[];let i=!1,r=0;for(;r<e.length;){for(;r<e.length&&/\s/.test(e[r]);)r+=1;if(r>=e.length)break;const a=r;let n="",o=!1,d=null;for(;r<e.length;){const s=e[r];if(d){if(s===d){o=!0,d=null,r+=1;continue}if(s==="\\"&&r+1<e.length){n+=e[r+1],r+=2;continue}n+=s,r+=1;continue}if(/\s/.test(s))break;if(s==='"'||s==="'"){o=!0,d=s,r+=1;continue}n+=s,r+=1}d&&(i=!0),t.push({value:n,start:a,end:r,quoted:o})}return{tokens:t,malformed:i}}function Wc(e){if(!e||e.quoted)return;const t=e.value.replace(/^\*/,"").toLowerCase();return t==="goal"||t==="loop"?t:void 0}function Gc(e,t){if(!e||e==="jobs"||!t||t.quoted)return;const i=t.value.toLowerCase();return(e==="goal"?Bc:Uc).has(i)?i:void 0}function Yc(e){return!e.quoted&&e.value!=="--watch"&&e.value.toLowerCase().startsWith("--watch")}function Fc(e){const{tokens:t,malformed:i}=Hc(e),r=Wc(t[0]),a=Gc(r,t[1]);if(i)return Ne(e,[xe.MALFORMED],r,a);const n=t.filter(u=>u.value==="--watch"&&!u.quoted),o=t.filter(u=>u.value==="--watch"&&u.quoted),d=t.filter(Yc);if(!(n.length>0||o.length>0||d.length>0))return Ne(e,[],r,a);if(n.length>1)return Ne(e,[xe.DUPLICATE],r,a);if(n.length===1&&(o.length>0||d.length>0))return Ne(e,[xe.AMBIGUOUS],r,a);if(o.length>0)return Ne(e,[xe.QUOTED],r,a);if(d.length>0)return Ne(e,[xe.MALFORMED],r,a);const l=n[0];if(!l)return Ne(e,[],r,a);if(t[t.length-1]!==l)return Ne(e,[xe.NON_FINAL],r,a);if(!r||!a)return Ne(e,[xe.UNRESOLVED],r,a);const 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:[xe.ACTIVE],metadata:cr(!0,[xe.ACTIVE],r,a,S),publicSafe:!0}}function qc(e){return xi(e)?$c(e):Fc(e)}function zc(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&Lo.has(t)):[]}function Wt(e){return{disabled:!0,reasonCodes:Me(e.length>0?e:[ke.MISSING])}}function sr(e,t,i=[],r){const a=Zt(t);if(a)return{source:e,target:jc(a,i),targetJobId:a.targetId,...r?{initialCursor:r}:{},serverHeldStream:!1}}function Jc(e){const t=new Map;for(const i of e){const r=`${i.target.selectorKind}:${i.target.targetId}`,a=t.get(r);if(!a){t.set(r,i);continue}const n=Me([...a.target.relatedJobIds??[],...i.target.relatedJobIds??[]]);t.set(r,{...a,target:n.length>0?{...a.target,relatedJobIds:n}:a.target,initialCursor:a.initialCursor??i.initialCursor})}return Array.from(t.values())}function vt(e,t,i,r){return{source:e,hasEvidence:t,candidates:Jc(i.filter(a=>!!a)),...r&&r.length>0?{disabledReasonCodes:Me(r)}:{}}}function Kc(e,t){return e.target.selectorKind===t.target.selectorKind&&e.target.targetId===t.target.targetId}function en(e,t){const i=Me(e.filter(r=>typeof r=="string").map(r=>Je(r)).filter(r=>!!r));if(t){const r=i.find(a=>ar(a)===t);if(r)return r}return i[0]}function wn(e,t){return Me(e.filter(i=>typeof i=="string").map(i=>Je(i)).filter(i=>!!i)).find(i=>ar(i)===t)}function Qc(e){const t=g(e?.continuity)?e.continuity:void 0,i=g(t?.jobs)?t.jobs:void 0,r=g(i?.watcher)?i.watcher:void 0,a=zc(r?.reasonCodes??i?.reasonCodes);if(!r)return vt("watcher-metadata",a.length>0,[],a);if(r.active===!1||a.length>0)return vt("watcher-metadata",!0,[],a.length>0?a:[ke.MALFORMED]);if(r.serverHeldStream!==!1)return vt("watcher-metadata",!0,[],[ke.SERVER_HELD_STREAM]);const n=Vc(r);if(!n)return vt("watcher-metadata",!0,[],[ke.MISSING]);const o=typeof r.initialCursor=="string"?r.initialCursor:void 0;return vt("watcher-metadata",!0,[{source:"watcher-metadata",target:n,targetJobId:n.targetId,...o?{initialCursor:o}:{},serverHeldStream:!1}])}function Ti(e,t){const i=g(e.loopJobPlan)?e.loopJobPlan:void 0,r=g(i?.metadata)?i.metadata:void 0,a=g(e.metadata)?e.metadata:void 0,o=(t==="goal"?en([e.goalId,e.targetGoalId,e.campaignId,e.jobId,e.targetJobId,a?.goalId,a?.campaignId,a?.jobId],"goal"):en([e.loopId,e.targetLoopId,e.jobId,e.targetJobId,a?.loopId,a?.jobId,r?.loopId,r?.jobId],"loop"))??en([e.jobId,e.targetJobId,a?.jobId,r?.jobId]);return sr("goal-loop-continuity-metadata",o,[e.jobId,e.targetJobId,a?.jobId,r?.jobId])}function Xc(e){const t=g(e?.continuity)?e.continuity:void 0,i=g(t?.goal)?t.goal:void 0,r=g(t?.loop)?t.loop:void 0,a=[i?Ti(i,"goal"):void 0,r?Ti(r,"loop"):void 0],n=!!(i||r);return vt("goal-loop-continuity-metadata",n,a,n&&a.every(o=>!o)?[ke.MISSING]:void 0)}function Zc(e){return Array.isArray(e)?e.filter(g):g(e)?Array.isArray(e.operationLogs)?e.operationLogs.filter(g):g(e.operationLog)?[e.operationLog]:Array.isArray(e.operations)?[e]:[]:[]}function Pi(e,t){const i=g(t.metadata)?t.metadata:void 0,r=wn([t.goalId,t.targetGoalId,t.campaignId,i?.goalId,i?.campaignId,t.jobId,i?.jobId],"goal"),a=wn([t.loopId,t.targetLoopId,i?.loopId,t.jobId,i?.jobId],"loop"),n=en([t.jobId,t.targetJobId,i?.jobId],"job"),o=r??a??n;if(!o)return;const d=e.get(o)??{targetId:o,relatedJobIds:[]};d.relatedJobIds.push(...or([n,t.jobId,t.targetJobId,i?.jobId])),e.set(o,d)}function es(e){const t=g(e.metadata)?e.metadata:void 0;return!!(wn([e.goalId,e.targetGoalId,e.campaignId,t?.goalId,t?.campaignId,e.jobId,t?.jobId],"goal")??wn([e.loopId,e.targetLoopId,t?.loopId,e.jobId,t?.jobId],"loop"))}function ts(e){const t=g(e.metadata)?e.metadata:void 0;return!!en([e.goalId,e.targetGoalId,e.campaignId,e.loopId,e.targetLoopId,e.jobId,e.targetJobId,t?.goalId,t?.campaignId,t?.loopId,t?.jobId])}function ki(e,t){const i=[];for(const o of["metadata","job","event","receipt","processingOutputSummary"]){const d=t[o];g(d)&&i.push(d)}const r=g(t.event)?t.event:void 0;g(r?.metadata)&&i.push(r.metadata),g(r?.processingOutputSummary)&&i.push(r.processingOutputSummary);const a=g(t.receipt)?t.receipt:void 0;g(a?.metadata)&&i.push(a.metadata);const n=i.some(ts);for(const o of i)Pi(e,o);(!n||es(t))&&Pi(e,t)}function ns(e){const t=Zc(e?.continuityStateUpdate),i=new Map;for(const a of t){ki(i,a);const n=Array.isArray(a.operations)?a.operations.filter(g):[];for(const o of n)ki(i,o)}const r=Array.from(i.values()).map(a=>sr("continuity-state-update-operation-log",a.targetId,a.relatedJobIds));return vt("continuity-state-update-operation-log",t.length>0,r,t.length>0&&r.every(a=>!a)?[ke.MISSING]:void 0)}function rs(e){const t=Ai(e);return vt("explicit-args",t.length>0,t.map(i=>sr("explicit-args",i)))}function is(e,t){const i=[Qc(e),Xc(e),ns(e),rs(t)];for(let r=0;r<i.length;r+=1){const a=i[r];if(!a.hasEvidence)continue;if(a.disabledReasonCodes&&a.disabledReasonCodes.length>0)return Wt(a.disabledReasonCodes);if(a.candidates.length!==1)return Wt([a.candidates.length>1?ke.AMBIGUOUS:ke.MISSING]);const n=a.candidates[0];for(const o of i.slice(r+1)){if(!o.hasEvidence)continue;if(o.disabledReasonCodes&&o.disabledReasonCodes.length>0)return Wt(o.disabledReasonCodes);if(o.candidates.length>1)return Wt([ke.AMBIGUOUS]);const d=o.candidates[0];if(d&&!Kc(n,d))return Wt([ke.CONFLICT])}return{target:n.target,targetJobId:n.targetJobId,...n.initialCursor?{initialCursor:n.initialCursor}:{},source:n.source,serverHeldStream:!1}}return Wt([ke.MISSING])}async function dr(e,t,i,r={}){const a="/api/v1/invoke";let n,o;const d=await Xt(e,a,t,i,{...r,deferSuccessfulJsonParsing:!0,...t.privateExecution?{maxAttempts:1,allowReplayRetry:!1}:{},admitResponseBeforeBodyRead:S=>{const u=S.headers.get("X-Neocortex-Compatibility");if(u!==null)try{if(u.length===0||u.length>8192)throw new Error("header-size");const C=JSON.parse(Buffer.from(u,"base64url").toString("utf8"));if(!za(C))throw new Error("header-shape");if(n=C,C.status==="incompatible")return o="incompatible",!1}catch{return o="malformed",!1}return r.admitResponseBeforeBodyRead?.(S)??!0}});if(d.networkFailure||!d.response)return{ok:!1,status:0,error:"Network error after bounded retries"};if(d.responseAdmissionRejected){const S=o==="malformed"?Ut.RESULT_MALFORMED:n?.reasonCodes[0]??Ut.OFFER_MALFORMED;return{ok:!1,status:d.response.status,error:`COMPATIBILITY_INCOMPATIBLE: ${S}`,errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:S,fallback_action:n?.remediationHint??"upgrade-client"},...n?{compatibility:n}:{}}}const{response:s,text:l}=d;let y=d.parsed;try{if(t.compatibility&&!n){if(/"(?:reviewReconciliation|review_reconciliation|reconciliationMetadata|releaseLifecycle|release_lifecycle|releaseBlocked|release_blocked|yoloopReleaseBlocked)"\s*:/u.test(l))return{ok:!1,status:s.status,error:`COMPATIBILITY_INCOMPATIBLE: ${Ut.UNNEGOTIATED_PROTECTED_FIELD}`,errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:Ut.UNNEGOTIATED_PROTECTED_FIELD,fallback_action:"upgrade-client"}};n=qa({clientVersion:t.compatibility.clientVersion,serverVersion:"0.0.0",registryVersion:t.registryVersion,registryChecksum:t.registryChecksum,reason:Ut.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:Ut.RESULT_MALFORMED},...n?{compatibility:n}:{}}}if(!s.ok)return t.privateExecution?{ok:!1,status:s.status,error:"private-execution-invoke-unavailable"}:{ok:!1,status:s.status,error:Object.keys(y).length>0?`${y.error_code??"ERROR"}: ${y.message??l}`:`HTTP ${s.status}: ${l}`,errorBody:Object.keys(y).length>0?y:void 0,...n?{compatibility:n}:{}};const S=y,u=s.headers.get("X-Client-Version-Warning");return u&&!yi&&(yi=!0,process.stderr.write(`
|
|
20
|
+
`);return}if(t==="json"){i.write(JSON.stringify(jc(e))+`
|
|
21
|
+
`);return}i.write(Mc(e)+`
|
|
22
|
+
`)}function or(e){return Uo.has(e.status)}function Bc(e,t,i){if(t){const a=e.find(n=>n.jobId===t);return!!(a&&or(a))}return i<=0?!1:e.filter(a=>!or(a)).length===0}function Uc(e,t,i,r){return i<r?!1:t?!e.some(a=>a.jobId===t&&!or(a)):e.length===0}function $c(e,t){return t?.aborted?Promise.resolve():new Promise(i=>{const r=setTimeout(a,e);function a(){clearTimeout(r),t?.removeEventListener("abort",a),i()}t?.addEventListener("abort",a,{once:!0})})}function Hc(e){return e.includes(Le.MALFORMED)?"malformed":e.includes(Le.AMBIGUOUS)?"ambiguous":e.includes("watch-target-multiple")?"multiple":e.includes("watch-evidence-unsafe")?"unsafe":e.includes(Le.MISSING)||e.includes(Re.TARGET_UNRESOLVED)?"unresolved":"unavailable"}function bi(e,t){const i=t?en(t):void 0,r=Be([...e,Re.TARGET_UNRESOLVED,G.WATCH_TARGET_UNRESOLVED]),a=ar(i,i?.targetId,Hc(r),r),n=ut({generatedAt:new Date().toISOString()},[],!1,0,[G.WATCH_TARGET_UNRESOLVED]),o=et(void 0,void 0,void 0,[],[G.WATCH_TARGET_UNRESOLVED],"unavailable");return tt({watchStatus:"blocked",active:!1,targetEvidence:a,snapshotEvidence:n,cursorEvidence:o,stopReason:"target_unresolved",reasonCodes:r,generatedAt:n.generatedAt})}function Wc(e,t,i,r,a=!1){const n=bi(e,Ti(t));return nt(n,i,r,a),ht("target-unresolved",0,0,n,a)}async function Gc(e){if(e.signal?.aborted){const k=ar(e.target??en(e.targetJobId),e.targetJobId,e.target??e.targetJobId?"resolved":"unresolved",[Re.CANCELLED]),R=ut(void 0,[],!1,0),w=et(e.initialCursor,e.initialCursor,e.initialCursor,[],[Re.CANCELLED],"unavailable"),j=tt({watchStatus:"stopped",active:!1,targetEvidence:k,snapshotEvidence:R,cursorEvidence:w,stopReason:"cancelled",reasonCodes:[Re.CANCELLED]});return ht("cancelled",0,0,j,e.protectedOutput)}const t=e.target??en(e.targetJobId),i=e.targetJobId??t?.targetId,r=e.stdout??process.stdout;if(!t){const k=bi([Le.MISSING,Re.TARGET_UNRESOLVED]);return nt(k,e.format,r,e.protectedOutput),ht("target-unresolved",0,0,k,e.protectedOutput)}const a=_n(e.limit??wn("NEOCORTEX_INVOKE_WATCH_LIMIT",Nr),Nr,50),n=Math.max(50,_n(e.pollIntervalMs??wn("NEOCORTEX_INVOKE_WATCH_POLL_INTERVAL_MS",Mr),Mr,6e4)),o=_n(e.maxIdlePolls??wn("NEOCORTEX_INVOKE_WATCH_MAX_IDLE_POLLS",Lr),Lr,120),d=_n(e.maxPolls??wn("NEOCORTEX_INVOKE_WATCH_MAX_POLLS",Dr),Dr,86400),s=e.sleep??$c;let l=e.initialCursor,y=0,S=0,u=0;const C=ar(t,i,"resolved",[G.OK]),E={schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:"pending",renderedSummaryCount:0,reasonCodes:[G.WATCH_RENDER_PENDING],publicSafe:!0},h=et(e.initialCursor,l,l,[],e.initialCursor?[G.WATCH_CURSOR_UNCHANGED]:[G.WATCH_NO_SUMMARIES_YET],e.initialCursor?"unchanged":"not_started");nt(tt({watchStatus:"active",active:!0,targetEvidence:C,snapshotEvidence:E,cursorEvidence:h,stopReason:"not_stopped",reasonCodes:[G.OK]}),e.format,r,e.protectedOutput);let I;try{I=await ba({projectRoot:e.projectRoot,strictReadOnly:e.strictReadOnly})}catch{const k=ut(void 0,[],!1,y,[G.WATCH_SNAPSHOT_UNAVAILABLE]),R=et(e.initialCursor,l,l,[],[G.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),w=tt({watchStatus:"blocked",active:!1,targetEvidence:C,snapshotEvidence:k,cursorEvidence:R,stopReason:"unavailable_evidence",reasonCodes:[Re.STORE_UNAVAILABLE]});return nt(w,e.format,r,e.protectedOutput),ht("store-unavailable",y,u,w,e.protectedOutput)}try{for(;!e.signal?.aborted&&u<d;){u+=1;const k=l,R=I.collectProcessingOutputSummaryCursor({...l?{cursor:l}:{},...t?{target:t}:{},...i?{jobId:i}:{},limit:a}),w=I.collectSnapshot({jobLimit:50,processingSummaryLimit:1}),j=w.jobs;if(R.summaries.length>0){for(const X of R.summaries)Vc(X,e.format,r,e.protectedOutput),y+=1;l=R.nextCursor??R.summaries[R.summaries.length-1]?.cursor??l,S=0}else l=R.nextCursor??l,S+=1;const L=ut(w,R.summaries,!0,R.summaries.length),Y=et(e.initialCursor,k,l,R.summaries,R.summaries.length>0?[G.WATCH_CURSOR_ADVANCED]:[G.WATCH_NO_SUMMARIES_YET]);if(nt(tt({watchStatus:R.summaries.length>0?"polling":"waiting",active:!0,targetEvidence:C,snapshotEvidence:L,cursorEvidence:Y,stopReason:"not_stopped",reasonCodes:R.summaries.length>0?[G.WATCH_CURSOR_ADVANCED]:[G.WATCH_NO_SUMMARIES_YET],generatedAt:w.generatedAt}),e.format,r,e.protectedOutput),!R.hasMore&&Bc(j,i,y)){const X=ut(w,R.summaries,!1,y,[Re.COMPLETED]),pe=et(e.initialCursor,k,l,R.summaries,[Re.COMPLETED],"exhausted"),x=tt({watchStatus:"stopped",active:!1,targetEvidence:C,snapshotEvidence:X,cursorEvidence:pe,stopReason:"not_stopped",reasonCodes:[Re.COMPLETED],generatedAt:w.generatedAt});return nt(x,e.format,r,e.protectedOutput),ht("completed",y,u,x,e.protectedOutput)}if(!R.hasMore&&Uc(j,i,S,o)){const X=ut(w,R.summaries,!1,y,[G.WATCH_STOP_IDLE_LIMIT_REACHED]),pe=et(e.initialCursor,k,l,R.summaries,[G.WATCH_STOP_IDLE_LIMIT_REACHED],"exhausted"),x=tt({watchStatus:"stopped",active:!1,targetEvidence:C,snapshotEvidence:X,cursorEvidence:pe,stopReason:"idle_limit_reached",reasonCodes:[Re.IDLE_TIMEOUT,G.WATCH_STOP_IDLE_LIMIT_REACHED],generatedAt:w.generatedAt});return nt(x,e.format,r,e.protectedOutput),ht("idle-timeout",y,u,x,e.protectedOutput)}R.hasMore||await s(n,e.signal)}}catch{const k=ut(void 0,[],!1,y,[G.WATCH_SNAPSHOT_UNAVAILABLE]),R=et(e.initialCursor,l,l,[],[G.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),w=tt({watchStatus:"blocked",active:!1,targetEvidence:C,snapshotEvidence:k,cursorEvidence:R,stopReason:"unavailable_evidence",reasonCodes:[Re.STORE_UNAVAILABLE]});return nt(w,e.format,r,e.protectedOutput),ht("store-unavailable",y,u,w,e.protectedOutput)}finally{I.close()}if(e.signal?.aborted){const k=ut(void 0,[],!1,y,[Re.CANCELLED]),R=et(e.initialCursor,l,l,[],[Re.CANCELLED],"unavailable"),w=tt({watchStatus:"stopped",active:!1,targetEvidence:C,snapshotEvidence:k,cursorEvidence:R,stopReason:"cancelled",reasonCodes:[Re.CANCELLED]});return nt(w,e.format,r,e.protectedOutput),ht("cancelled",y,u,w,e.protectedOutput)}const b=ut(void 0,[],!1,y,[G.WATCH_STOP_MAX_POLLS_REACHED]),D=et(e.initialCursor,l,l,[],[G.WATCH_STOP_MAX_POLLS_REACHED],"exhausted"),P=tt({watchStatus:"stopped",active:!1,targetEvidence:C,snapshotEvidence:b,cursorEvidence:D,stopReason:"max_polls_reached",reasonCodes:[Re.MAX_POLLS,G.WATCH_STOP_MAX_POLLS_REACHED]});return nt(P,e.format,r,e.protectedOutput),ht("max-polls",y,u,P,e.protectedOutput)}function Ke(e){const t=e.trim().replace(/^@/,"").match(/^(job|goal|loop)-([JGL])(\d{3,})$/i);if(!t)return;const i=t[1].toLowerCase(),r=t[2].toUpperCase();if(!(i==="job"&&r!=="J"||i==="goal"&&r!=="G"||i==="loop"&&r!=="L"))return`${i}-${r}${t[3]}`}function cr(e){if(e.startsWith("job-J"))return"job";if(e.startsWith("goal-G"))return"goal";if(e.startsWith("loop-L"))return"loop"}function xi(e){const t=[],i=/(?:^|[\s"'([,{])@?(job-[Jj]\d{3,}|goal-[Gg]\d{3,}|loop-[Ll]\d{3,})(?=$|[\s"')\]},.;:!?])/g;let r;for(;(r=i.exec(e))!==null;){const a=Ke(r[1]);a&&t.push(a)}return Be(t)}function Ti(e){return xi(e)[0]}function en(e){const t=e?Ke(e):void 0;if(t){if(t.startsWith("job-J"))return{selectorKind:"job",targetId:t,jobId:t,publicSafe:!0};if(t.startsWith("goal-G"))return{selectorKind:"goal",targetId:t,goalId:t,publicSafe:!0};if(t.startsWith("loop-L"))return{selectorKind:"loop",targetId:t,loopId:t,publicSafe:!0}}}function sr(e){return Be(e.filter(t=>typeof t=="string").map(t=>Ke(t)).filter(t=>!!t?.startsWith("job-J")))}function Fc(e,t){const i=sr(t).filter(r=>r!==e.targetId&&r!==e.jobId);return i.length>0?{...e,relatedJobIds:i}:e}function Yc(e){if(!e)return;const t=g(e.target)?e.target:void 0,i=typeof e.selectorKind=="string"?e.selectorKind:typeof t?.selectorKind=="string"?t.selectorKind:void 0,r=typeof e.targetId=="string"?Ke(e.targetId):typeof t?.targetId=="string"?Ke(t.targetId):typeof e.targetJobId=="string"?Ke(e.targetJobId):void 0,a=en(r);if(!a||i&&i!==a.selectorKind)return;const n=Array.isArray(e.relatedJobIds)?e.relatedJobIds:Array.isArray(t?.relatedJobIds)?t.relatedJobIds:void 0,o=sr([...n??[],e.jobId,t?.jobId,e.targetJobId,t?.targetJobId]).filter(d=>d!==a.targetId&&d!==a.jobId);return{...a,...typeof(e.jobId??t?.jobId)=="string"?{jobId:Ke(e.jobId??t?.jobId)??a.jobId}:{},...typeof(e.goalId??t?.goalId)=="string"?{goalId:Ke(e.goalId??t?.goalId)??a.goalId}:{},...typeof(e.loopId??t?.loopId)=="string"?{loopId:Ke(e.loopId??t?.loopId)??a.loopId}:{},...o.length>0?{relatedJobIds:o}:{}}}function Pi(e){const t=e.trim().split(/\s+/).filter(Boolean),i=t[0]?.replace(/^\*/,"").toLowerCase(),r=t[1]?.replace(/^--/,"").toLowerCase();return(i==="jobs"||i==="job"||i==="continuity-jobs"||i==="61")&&r==="watch"}const be=Object.freeze({ACTIVE:"command-level-watch-active",INACTIVE:"command-level-watch-inactive",DUPLICATE:"command-level-watch-duplicate",AMBIGUOUS:"command-level-watch-ambiguous",QUOTED:"command-level-watch-quoted",MALFORMED:"command-level-watch-malformed",NON_FINAL:"command-level-watch-non-final",UNRESOLVED:"command-level-watch-unresolved",UNSUPPORTED:"command-level-watch-unsupported",TARGET_INVALID:"command-level-watch-target-invalid"}),qc=new Set(["create","start","resume"]),zc=new Set(["create","resume","run-once"]);function dr(e,t,i,r,a){return{schemaVersion:1,contractVersion:"continuity-v1",...i?{command:i}:{},...r?{operation:r}:{},active:e,...a?{watchToken:a}:{},reasonCodes:Be(t),serverHeldStream:!1,allJobsPolling:!1,targetResolution:e?"required-after-dispatch":"inactive",publicSafe:!0}}function Me(e,t=[],i,r){const a=t.length>0?t:[be.INACTIVE];return{args:e,watch:!1,reasonCodes:a,metadata:dr(!1,a,i,r),publicSafe:!0}}function Jc(e){const t=e.trim().split(/\s+/).filter(Boolean),i=t.slice(2).filter(n=>n==="--watch").length;if(i===0)return Me(e,[],"jobs","watch");if(i!==1)return Me(e,[be.AMBIGUOUS],"jobs","watch");const r=t.filter((n,o)=>o<2||n!=="--watch").join(" ");return Pi(r)?r.trim().split(/\s+/).filter(Boolean).slice(2).length!==1?Me(e,[be.AMBIGUOUS],"jobs","watch"):Ti(r)?{args:r,watch:!0,reasonCodes:[be.ACTIVE],metadata:dr(!0,[be.ACTIVE],"jobs","watch"),publicSafe:!0}:Me(e,[be.TARGET_INVALID],"jobs","watch"):Me(e,[be.UNSUPPORTED],"jobs","watch")}function Kc(e){const t=[];let i=!1,r=0;for(;r<e.length;){for(;r<e.length&&/\s/.test(e[r]);)r+=1;if(r>=e.length)break;const a=r;let n="",o=!1,d=null;for(;r<e.length;){const s=e[r];if(d){if(s===d){o=!0,d=null,r+=1;continue}if(s==="\\"&&r+1<e.length){n+=e[r+1],r+=2;continue}n+=s,r+=1;continue}if(/\s/.test(s))break;if(s==='"'||s==="'"){o=!0,d=s,r+=1;continue}n+=s,r+=1}d&&(i=!0),t.push({value:n,start:a,end:r,quoted:o})}return{tokens:t,malformed:i}}function Qc(e){if(!e||e.quoted)return;const t=e.value.replace(/^\*/,"").toLowerCase();return t==="goal"||t==="loop"?t:void 0}function Xc(e,t){if(!e||e==="jobs"||!t||t.quoted)return;const i=t.value.toLowerCase();return(e==="goal"?qc:zc).has(i)?i:void 0}function Zc(e){return!e.quoted&&e.value!=="--watch"&&e.value.toLowerCase().startsWith("--watch")}function es(e){const{tokens:t,malformed:i}=Kc(e),r=Qc(t[0]),a=Xc(r,t[1]);if(i)return Me(e,[be.MALFORMED],r,a);const n=t.filter(u=>u.value==="--watch"&&!u.quoted),o=t.filter(u=>u.value==="--watch"&&u.quoted),d=t.filter(Zc);if(!(n.length>0||o.length>0||d.length>0))return Me(e,[],r,a);if(n.length>1)return Me(e,[be.DUPLICATE],r,a);if(n.length===1&&(o.length>0||d.length>0))return Me(e,[be.AMBIGUOUS],r,a);if(o.length>0)return Me(e,[be.QUOTED],r,a);if(d.length>0)return Me(e,[be.MALFORMED],r,a);const l=n[0];if(!l)return Me(e,[],r,a);if(t[t.length-1]!==l)return Me(e,[be.NON_FINAL],r,a);if(!r||!a)return Me(e,[be.UNRESOLVED],r,a);const y=`${e.slice(0,l.start)}${e.slice(l.end)}`.trim(),S={literal:"--watch",position:"final",start:l.start,end:l.end,quoted:!1,publicSafe:!0};return{args:y,watch:!0,reasonCodes:[be.ACTIVE],metadata:dr(!0,[be.ACTIVE],r,a,S),publicSafe:!0}}function ts(e){return Pi(e)?Jc(e):es(e)}function ns(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&$o.has(t)):[]}function Gt(e){return{disabled:!0,reasonCodes:Be(e.length>0?e:[Le.MISSING])}}function pr(e,t,i=[],r){const a=en(t);if(a)return{source:e,target:Fc(a,i),targetJobId:a.targetId,...r?{initialCursor:r}:{},serverHeldStream:!1}}function rs(e){const t=new Map;for(const i of e){const r=`${i.target.selectorKind}:${i.target.targetId}`,a=t.get(r);if(!a){t.set(r,i);continue}const n=Be([...a.target.relatedJobIds??[],...i.target.relatedJobIds??[]]);t.set(r,{...a,target:n.length>0?{...a.target,relatedJobIds:n}:a.target,initialCursor:a.initialCursor??i.initialCursor})}return Array.from(t.values())}function _t(e,t,i,r){return{source:e,hasEvidence:t,candidates:rs(i.filter(a=>!!a)),...r&&r.length>0?{disabledReasonCodes:Be(r)}:{}}}function is(e,t){return e.target.selectorKind===t.target.selectorKind&&e.target.targetId===t.target.targetId}function tn(e,t){const i=Be(e.filter(r=>typeof r=="string").map(r=>Ke(r)).filter(r=>!!r));if(t){const r=i.find(a=>cr(a)===t);if(r)return r}return i[0]}function An(e,t){return Be(e.filter(i=>typeof i=="string").map(i=>Ke(i)).filter(i=>!!i)).find(i=>cr(i)===t)}function as(e){const t=g(e?.continuity)?e.continuity:void 0,i=g(t?.jobs)?t.jobs:void 0,r=g(i?.watcher)?i.watcher:void 0,a=ns(r?.reasonCodes??i?.reasonCodes);if(!r)return _t("watcher-metadata",a.length>0,[],a);if(r.active===!1||a.length>0)return _t("watcher-metadata",!0,[],a.length>0?a:[Le.MALFORMED]);if(r.serverHeldStream!==!1)return _t("watcher-metadata",!0,[],[Le.SERVER_HELD_STREAM]);const n=Yc(r);if(!n)return _t("watcher-metadata",!0,[],[Le.MISSING]);const o=typeof r.initialCursor=="string"?r.initialCursor:void 0;return _t("watcher-metadata",!0,[{source:"watcher-metadata",target:n,targetJobId:n.targetId,...o?{initialCursor:o}:{},serverHeldStream:!1}])}function ki(e,t){const i=g(e.loopJobPlan)?e.loopJobPlan:void 0,r=g(i?.metadata)?i.metadata:void 0,a=g(e.metadata)?e.metadata:void 0,o=(t==="goal"?tn([e.goalId,e.targetGoalId,e.campaignId,e.jobId,e.targetJobId,a?.goalId,a?.campaignId,a?.jobId],"goal"):tn([e.loopId,e.targetLoopId,e.jobId,e.targetJobId,a?.loopId,a?.jobId,r?.loopId,r?.jobId],"loop"))??tn([e.jobId,e.targetJobId,a?.jobId,r?.jobId]);return pr("goal-loop-continuity-metadata",o,[e.jobId,e.targetJobId,a?.jobId,r?.jobId])}function os(e){const t=g(e?.continuity)?e.continuity:void 0,i=g(t?.goal)?t.goal:void 0,r=g(t?.loop)?t.loop:void 0,a=[i?ki(i,"goal"):void 0,r?ki(r,"loop"):void 0],n=!!(i||r);return _t("goal-loop-continuity-metadata",n,a,n&&a.every(o=>!o)?[Le.MISSING]:void 0)}function cs(e){return Array.isArray(e)?e.filter(g):g(e)?Array.isArray(e.operationLogs)?e.operationLogs.filter(g):g(e.operationLog)?[e.operationLog]:Array.isArray(e.operations)?[e]:[]:[]}function Oi(e,t){const i=g(t.metadata)?t.metadata:void 0,r=An([t.goalId,t.targetGoalId,t.campaignId,i?.goalId,i?.campaignId,t.jobId,i?.jobId],"goal"),a=An([t.loopId,t.targetLoopId,i?.loopId,t.jobId,i?.jobId],"loop"),n=tn([t.jobId,t.targetJobId,i?.jobId],"job"),o=r??a??n;if(!o)return;const d=e.get(o)??{targetId:o,relatedJobIds:[]};d.relatedJobIds.push(...sr([n,t.jobId,t.targetJobId,i?.jobId])),e.set(o,d)}function ss(e){const t=g(e.metadata)?e.metadata:void 0;return!!(An([e.goalId,e.targetGoalId,e.campaignId,t?.goalId,t?.campaignId,e.jobId,t?.jobId],"goal")??An([e.loopId,e.targetLoopId,t?.loopId,e.jobId,t?.jobId],"loop"))}function ds(e){const t=g(e.metadata)?e.metadata:void 0;return!!tn([e.goalId,e.targetGoalId,e.campaignId,e.loopId,e.targetLoopId,e.jobId,e.targetJobId,t?.goalId,t?.campaignId,t?.loopId,t?.jobId])}function Ni(e,t){const i=[];for(const o of["metadata","job","event","receipt","processingOutputSummary"]){const d=t[o];g(d)&&i.push(d)}const r=g(t.event)?t.event:void 0;g(r?.metadata)&&i.push(r.metadata),g(r?.processingOutputSummary)&&i.push(r.processingOutputSummary);const a=g(t.receipt)?t.receipt:void 0;g(a?.metadata)&&i.push(a.metadata);const n=i.some(ds);for(const o of i)Oi(e,o);(!n||ss(t))&&Oi(e,t)}function ps(e){const t=cs(e?.continuityStateUpdate),i=new Map;for(const a of t){Ni(i,a);const n=Array.isArray(a.operations)?a.operations.filter(g):[];for(const o of n)Ni(i,o)}const r=Array.from(i.values()).map(a=>pr("continuity-state-update-operation-log",a.targetId,a.relatedJobIds));return _t("continuity-state-update-operation-log",t.length>0,r,t.length>0&&r.every(a=>!a)?[Le.MISSING]:void 0)}function ls(e){const t=xi(e);return _t("explicit-args",t.length>0,t.map(i=>pr("explicit-args",i)))}function us(e,t){const i=[as(e),os(e),ps(e),ls(t)];for(let r=0;r<i.length;r+=1){const a=i[r];if(!a.hasEvidence)continue;if(a.disabledReasonCodes&&a.disabledReasonCodes.length>0)return Gt(a.disabledReasonCodes);if(a.candidates.length!==1)return Gt([a.candidates.length>1?Le.AMBIGUOUS:Le.MISSING]);const n=a.candidates[0];for(const o of i.slice(r+1)){if(!o.hasEvidence)continue;if(o.disabledReasonCodes&&o.disabledReasonCodes.length>0)return Gt(o.disabledReasonCodes);if(o.candidates.length>1)return Gt([Le.AMBIGUOUS]);const d=o.candidates[0];if(d&&!is(n,d))return Gt([Le.CONFLICT])}return{target:n.target,targetJobId:n.targetJobId,...n.initialCursor?{initialCursor:n.initialCursor}:{},source:n.source,serverHeldStream:!1}}return Gt([Le.MISSING])}async function lr(e,t,i,r={}){const a="/api/v1/invoke";let n,o;const d=await Zt(e,a,t,i,{...r,deferSuccessfulJsonParsing:!0,...t.privateExecution?{maxAttempts:1,allowReplayRetry:!1}:{},admitResponseBeforeBodyRead:S=>{const u=S.headers.get("X-Neocortex-Compatibility");if(u!==null)try{if(u.length===0||u.length>8192)throw new Error("header-size");const C=JSON.parse(Buffer.from(u,"base64url").toString("utf8"));if(!Ka(C))throw new Error("header-shape");if(n=C,C.status==="incompatible")return o="incompatible",!1}catch{return o="malformed",!1}return r.admitResponseBeforeBodyRead?.(S)??!0}});if(d.networkFailure||!d.response)return{ok:!1,status:0,error:"Network error after bounded retries"};if(d.responseAdmissionRejected){const S=o==="malformed"?$t.RESULT_MALFORMED:n?.reasonCodes[0]??$t.OFFER_MALFORMED;return{ok:!1,status:d.response.status,error:`COMPATIBILITY_INCOMPATIBLE: ${S}`,errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:S,fallback_action:n?.remediationHint??"upgrade-client"},...n?{compatibility:n}:{}}}const{response:s,text:l}=d;let y=d.parsed;try{if(t.compatibility&&!n){if(/"(?:reviewReconciliation|review_reconciliation|reconciliationMetadata|releaseLifecycle|release_lifecycle|releaseBlocked|release_blocked|yoloopReleaseBlocked)"\s*:/u.test(l))return{ok:!1,status:s.status,error:`COMPATIBILITY_INCOMPATIBLE: ${$t.UNNEGOTIATED_PROTECTED_FIELD}`,errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:$t.UNNEGOTIATED_PROTECTED_FIELD,fallback_action:"upgrade-client"}};n=Ja({clientVersion:t.compatibility.clientVersion,serverVersion:"0.0.0",registryVersion:t.registryVersion,registryChecksum:t.registryChecksum,reason:$t.SERVER_NEGOTIATION_MISSING})}if(s.ok)try{y=l?JSON.parse(l):{}}catch{return{ok:!1,status:s.status,error:"COMPATIBILITY_INCOMPATIBLE: response-json-malformed",errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:$t.RESULT_MALFORMED},...n?{compatibility:n}:{}}}if(!s.ok)return t.privateExecution?{ok:!1,status:s.status,error:"private-execution-invoke-unavailable"}:{ok:!1,status:s.status,error:Object.keys(y).length>0?`${y.error_code??"ERROR"}: ${y.message??l}`:`HTTP ${s.status}: ${l}`,errorBody:Object.keys(y).length>0?y:void 0,...n?{compatibility:n}:{}};const S=y,u=s.headers.get("X-Client-Version-Warning");return u&&!Ei&&(Ei=!0,process.stderr.write(`
|
|
23
23
|
[Neocortex] ${u}
|
|
24
24
|
|
|
25
|
-
`)),{ok:!0,status:s.status,data:S,...n?{compatibility:n}:{}}}catch(S){return{ok:!1,status:0,error:(S instanceof Error?S.message:String(S)).includes("abort")?`Request timeout after ${
|
|
25
|
+
`)),{ok:!0,status:s.status,data:S,...n?{compatibility:n}:{}}}catch(S){return{ok:!1,status:0,error:(S instanceof Error?S.message:String(S)).includes("abort")?`Request timeout after ${qr/1e3}s`:"Network error: invalid response"}}}async function hs(e,t,i){const r=await Zt(e,"/api/v1/invoke/private-execution/consume",t,i,{maxAttempts:1,allowReplayRetry:!1});if(r.networkFailure||!r.response||!r.response.ok)throw new Error("private-execution-delivery-unavailable");return r.parsed}async function gs(e,t,i){const r=await Zt(e,"/api/v1/invoke/private-execution/cancel",t,i,{maxAttempts:1,allowReplayRetry:!1});return!!r.response?.ok&&r.parsed.status==="cancelled"}async function Li(e,t,i,r={}){const a=await Zt(e,"/api/v1/invoke/epic-claims/acknowledge",{...i,registryVersion:dt,registryChecksum:st},t,r);return!!a.response?.ok&&a.parsed.status==="ok"&&a.parsed.claimOutcome===i.status&&(!i.planningCheckpoint||a.parsed.memoryReceiptId===i.planningCheckpoint.memoryReceiptId)}async function fs(e,t,i,r,a,n={}){if(!a)return 0;const o=Ht(e);let d=0;for(const[s,l]of Object.entries(o.operations))l.planningProtocol==="root-staged-v1"||!l.claimId||!l.epicId||!t.epics?.[l.epicId]||!await Li(i,r,{claimId:l.claimId,projectId:a,epicId:l.epicId,status:"materialized"},n)||(Lo(e,s),d+=1);return d}function ms(e,t){const i=t.state.pendingContinuationAuthorities,r=t.state.continuationSession;if(t.state.continuationPolicy!=="p205-finite-resume-v2"||i?.length!==1||!r)return;const a=i[0],n=a.certificate,o=n?.expectedTransition;if(a.storyIds!=="[CIRCULAR]"||n?.rank!=="[CIRCULAR]"||o?.selectedStoryIds!=="[CIRCULAR]")return;const d=typeof r.epicId=="string"?r.epicId:"",s=e.epics[d],l=Array.isArray(o.storyLifecycle)?o.storyLifecycle:[],y=l.length===1&&typeof l[0]?.storyId=="string"?l[0].storyId:"",u=e.stories[y]?.checkpoint;if(!s||s.branch_mode!=="epic"||typeof s.execution_branch!="string"||typeof s.origin_branch!="string"||s.branch_lease!==void 0&&s.branch_lease!==null||!u||u.qaVerdict!=="passed"||u.reviewVerdict!=="approved"||!Array.isArray(u.receiptRefs))return;const E=(Array.isArray(s.stories)?s.stories.filter(h=>typeof h=="string"):[]).find(h=>{const I=e.stories[h];return!I||["done","completed","merged"].includes(String(I.status))?!1:(Array.isArray(I.depends_on)?I.depends_on.filter(D=>typeof D=="string"):[]).every(D=>["done","completed","merged"].includes(String(e.stories[D]?.status)))});if(E)return{epicId:d,expectedNextStoryId:E,branchMode:"epic",executionBranch:s.execution_branch,originBranch:s.origin_branch,branchLeaseReleased:!0,checkpoint:{schemaVersion:1,storyId:u.storyId,epicId:u.epicId,branch:u.branch,baseSha:u.baseSha,headSha:u.headSha,receiptRefs:[...u.receiptRefs],qaVerdict:"passed",reviewVerdict:"approved"}}}const ur=["backlog","pending","ready","in-progress","branch-ready","diagnose","research","write-spec","create-tasks","implemented","refactor-suggest-done","property-tests-emitted","tests-validated","qa-gate-passed","memory-updated","committed","synced","pr-created","pr-reviewed","done"],Di=new Set(["done","completed","merged","cancelled","canceled","abandoned"]),Mi=new Set(["skipped-with-debt","documented"]);function ji(e){return typeof e=="string"?e.trim().toLowerCase().replace(/_/g,"-"):""}function ys(e){const t=ji(e);if(Di.has(t)||Mi.has(t))return 0;const i=ur.indexOf(t);return i<0?ur.length:ur.length-1-i}function Is(e,t){const i=e.epics[t];if(!i||!Array.isArray(i.stories)||i.stories.some(y=>typeof y!="string"||!/^P[1-9][0-9]*\.[0-9]+$/.test(y)))return null;const r=[...i.stories],a=[],n=[];let o=0,d=0;const s=[];for(const y of r){const S=e.stories[y];if(!S||!Array.isArray(S.depends_on)||S.depends_on.some(h=>typeof h!="string"))return null;const u=[...S.depends_on].sort(),C=ys(S.status),E=ji(S.status);a.push({id:y,dependsOn:u}),n.push({id:y,status:S.status,dependsOn:u}),s.push({storyId:y,remaining:C}),o+=C,!Di.has(E)&&!Mi.has(E)&&(d+=1)}const l={version:1,policy:"p205-finite-resume-v2",epicId:t,storyIds:r,queueEpicIds:[t],initialEpicIndex:0,graphFingerprint:vt("p205-yoloop-graph-v1",a),lifecycleVersion:"p205-lifecycle-v1",terminalPredicateVersion:"p205-terminal-v1",initialSnapshotFingerprint:vt("p205-yoloop-initial-snapshot-v1",{epicId:t,stories:n}),initialRank:{version:1,queue:0,epic:d,lifecycle:o},initialStoryLifecycle:s};return Object.freeze({...l,sessionId:vt("p205-yoloop-session-v1",l)})}function Vi(e){const t=e instanceof Error?e.message:"";return/^[a-z0-9][a-z0-9-]{0,79}$/.test(t)?t:"yoloop-causal-reconciliation-unavailable"}async function Es(e){try{if(!/^P[1-9][0-9]*$/.test(e.targetEpicId)||!/^[a-f0-9]{64}$/.test(e.originalInputSha256)||!/^[a-f0-9]{64}$/.test(e.canonicalInputSha256))throw new Error("yoloop-causal-reconciliation-binding-invalid");const t=Is(e.snapshot,e.targetEpicId);if(!t)throw new Error("yoloop-causal-reconciliation-target-invalid");const i=String(t.graphFingerprint),r=wr(e.projectRoot),a=Object.values(r.operational.identities).filter(j=>j.epicId===e.targetEpicId&&j.graphRevision===i);if(a.length!==1)throw new Error("epic-operational-identity-mismatch");const n=e.snapshot.yoloop,o=n?n.lock!==null||n.state.currentSession!==null?"active":"inactive":"unknown",d=sa({document:r.document,targetIdentityHash:a[0].identityHash,targetEpicId:e.targetEpicId,targetGraphRevision:i,legacyActivity:o});if(d.kind!=="eligible")throw new Error(d.reasonCodes[0]??"yoloop-causal-reconciliation-ineligible");const s=r.operational,l=s.yoloop.state.continuationSession,y=s.yoloop.state.pendingContinuationAuthorities??[],S=s.yoloop.state.runControl;if(!l||typeof l.sessionId!="string"||!S||!["success","exhausted"].includes(S.status)||y.length>1)throw new Error("yoloop-causal-reconciliation-preimage-invalid");const u=vt("p224-common-continuation-session-v1",s.yoloop.state.continuationSession??null),C=vt("p224-common-pending-authorities-v1",y),E=vt("p224-common-continuation-session-v1",t),h=vt("p224-invoke-session-recovery-v1",{identityHash:a[0].identityHash,originalInputSha256:e.originalInputSha256,canonicalInputSha256:e.canonicalInputSha256,expectedSessionHash:u,expectedPendingHash:C,nextSessionHash:E,runId:S.runId,runRevision:S.revision}),I={operationId:`p224rec-${h.slice(0,32)}`,idempotencyKey:`p224rec-${h.slice(0,32)}`,expectedCommonRevision:r.document.revision,expectedWriterEpoch:s.writerEpoch,expectedIdentityHash:a[0].identityHash,sourceEpicId:d.evidence.sourceEpicId,sourceGraphRevision:d.evidence.sourceGraphRevision,targetEpicId:e.targetEpicId,targetGraphRevision:i,expectedRunId:S.runId,expectedRunStatus:S.status,expectedRunRevision:S.revision,expectedSnapshotHash:S.latestSnapshotHash,sourceSessionId:l.sessionId,expectedSessionHash:u,expectedPendingHash:C,expectedPendingCount:y.length,nextSession:t,nextSessionHash:E},b=ca(I),D={schemaVersion:"YoloopCrossEpicReconciliationReceipt/1.0",operationId:I.operationId,idempotencyKey:I.idempotencyKey,payloadHash:b,sourceEpicId:I.sourceEpicId,sourceGraphRevision:I.sourceGraphRevision,targetEpicId:I.targetEpicId,targetGraphRevision:I.targetGraphRevision,runId:I.expectedRunId,previousSessionHash:u,nextSessionHash:E,retiredAuthorityHash:C,retiredAuthorityCount:I.expectedPendingCount,outcome:"cross-epic-reconciled",publicSafe:!0},P={type:"reconcile_cross_epic_continuation",...I,payloadHash:b,receipt:D};await oa(e.projectRoot,P);const k=wr(e.projectRoot),R=k.operational.yoloop.state.pendingContinuationAuthorities??[];if(!k.operational.reconciliationReceipts.find(j=>j.payloadHash===b)||R.length!==0||vt("p224-common-continuation-session-v1",k.operational.yoloop.state.continuationSession??null)!==E)throw new Error("yoloop-causal-reconciliation-postimage-unverified");return Object.freeze({outcome:"applied",payloadHash:b,retryCount:1,publicSafe:!0})}catch(t){return Object.freeze({outcome:"blocked",reasonCode:Vi(t),retryCount:0,publicSafe:!0})}}const Ss=/^\*yolo @docs\/stories\/[A-Za-z0-9][A-Za-z0-9._-]{0,79}\.story\.md story-worktree-phase-1$/,Bi=9e4,Ui=6,vs=1e3;function Cs(e){return typeof e=="string"&&Ss.test(e)&&!e.includes("..")}function Rs(e){const t=e.metadata?.storyWorktreePhase;if(!e.success||!t||typeof t!="object"||Array.isArray(t))return;const i=t;return i.decision==="spec-barrier-waiting"&&i.phase==="phase-1"?i:void 0}async function _s(e,t,i={}){const r=i.sleep??(l=>new Promise(y=>setTimeout(y,l))),a=i.now??Date.now,n=Math.max(1,Math.min(i.maxAttempts??Ui,Ui)),o=Math.max(0,Math.min(i.maxWaitMs??Bi,Bi)),d=a();let s=0;for(;;){const l=await t(e);s+=1;const y=Rs(l);if(!y)return l;const S=typeof y.maxWaitMs=="number"&&Number.isFinite(y.maxWaitMs)?y.maxWaitMs:0,u=Math.min(o,Math.max(0,S)),C=typeof y.retryAfterMs=="number"&&Number.isFinite(y.retryAfterMs)?y.retryAfterMs:0,E=Math.min(Math.max(C,vs),u),h=a()-d;if(s>=n||h+E>u)return{success:!0,instructions:`# Story-worktree spec barrier timeout
|
|
26
26
|
|
|
27
27
|
The C04 barrier did not open within the bounded wait. Return this resumable receipt to the root; the root re-dispatches the same phase-1 prompt, which resumes at C05. No C05 step was executed.
|
|
28
28
|
|
|
29
|
-
[STORY_WORKTREE_SPEC_BARRIER_TIMEOUT]`,metadata:{...l.metadata,storyWorktreePhase:{...y,decision:"spec-barrier-timeout",reasonCode:"spec-barrier-waiting",resumable:!0,attempts:s,waitedMs:Math.max(0,h),publicSafe:!0}},exitCode:0};await r(E)}}async function
|
|
30
|
-
`)}}async function
|
|
31
|
-
`),{success:!1,error:p,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}let w=y?
|
|
32
|
-
`)})}catch(p){const m=
|
|
29
|
+
[STORY_WORKTREE_SPEC_BARRIER_TIMEOUT]`,metadata:{...l.metadata,storyWorktreePhase:{...y,decision:"spec-barrier-timeout",reasonCode:"spec-barrier-waiting",resumable:!0,attempts:s,waitedMs:Math.max(0,h),publicSafe:!0}},exitCode:0};await r(E)}}async function ws(e,t){const i=t.metadata?.storyWorktreePhase;if(!t.success||!i||typeof i!="object"||Array.isArray(i))return;const r=i,a=r.specAcceptance,n=r.phaseOneReceipt,o=typeof r.storyId=="string"?r.storyId:void 0,d=o&&/^P[0-9]{1,12}\./.test(o)?o.split(".")[0]:void 0;if(!(!d||a===void 0&&n===void 0))try{await $r(e,s=>{go(s,d,{...a!==void 0?{specAcceptances:[a]}:{},...n!==void 0?{receipts:[n]}:{}})})}catch(s){const l=s instanceof Error&&/^[a-z0-9-]{1,80}$/.test(s.message)?s.message:"story-worktree-evidence-persist-failed";process.stderr.write(`[Neocortex] story-worktree evidence not persisted (${l}); the root must re-dispatch this phase-1 prompt.
|
|
30
|
+
`)}}async function As(e){if(!Cs(e.args))return $i(e);const t=e.projectRoot??process.cwd();return _s(e.args,async()=>{const i=await $i(e);return await ws(t,i),i})}async function $i(e){let t;try{if(t=e.inputEnvelope??Qt(e.inputSource??"args",e.args),Ha(t),t.rawArgs!==e.args)throw new Error("INVOKE_INPUT_ENVELOPE_ARGUMENT_CONFLICT")}catch{return{success:!1,error:"INVOCATION_MALFORMED_INPUT: explicit input integrity could not be verified.",errorCode:"INVOCATION_MALFORMED_INPUT",metadata:{invocationInput:{reason:"input-integrity-conflict",remediation:"Retry with exactly one of --args, --stdin or --args-file.",publicSafe:!0}},exitCode:1}}const i=t.rawArgs,r=Un(t);let a=i,n=r,o=ti(i),d;if(o.outcome!=="resolved"){const c=Bo(i);c.kind==="canonicalized"&&(a=c.canonicalArgs,n=Un(Qt(t.source,a)),d=c.binding,o=ti(a))}if(o.outcome!=="resolved"){const c=Ga(o,"client"),p=o.outcome==="malformed_input"?o.reason==="input_limit"||o.reason==="token_limit"||o.reason==="token_size_limit"?"input-limit-exceeded":o.reason==="invalid_control"||o.reason==="invalid_surrogate"?"invalid-control-character":o.reason==="unterminated_quote"||o.reason==="trailing_escape"||o.reason==="unsupported_escape"?"unterminated-quote":void 0:void 0,m=p?{code:"INVOCATION_MALFORMED_INPUT",reason:p,source:t.source,byteLength:t.byteLength,remediation:p==="input-limit-exceeded"?"Reduce the explicit command input or split the requested work into bounded invocations.":p==="invalid-control-character"?"Remove invalid control characters and retry with valid UTF-8 text.":"Close quotes and escapes, or use --stdin/--args-file for multiline content."}:void 0;return{success:!1,error:`INVOCATION_${o.outcome.toUpperCase()}`,errorCode:`INVOCATION_${o.outcome.toUpperCase()}`,metadata:{invocationAdmission:c,...m?{invocationInput:m}:{}},exitCode:1}}if(d&&(e={...e,args:a}),e.privateExecutionModel!==void 0&&(!e.privateExecutionBeta||e.strictReadOnly||!/^gpt-[a-z0-9][a-z0-9.-]{0,63}$/.test(e.privateExecutionModel)))return{success:!1,error:"private-codex-model-invalid",errorCode:"private-codex-model-invalid",exitCode:1};const s=Fn(e.projectRoot),l=o.selection.commandId,y=l==="yolo"&&!kr(a,l)?Co(a):null,S=l==="tech-debt"&&o.selection.positionals.length===0&&(o.selection.operationId==="scan"&&Object.keys(o.selection.options).length===0||o.selection.operationId===void 0&&o.selection.options.scan===!0&&Object.keys(o.selection.options).length===1),u=la.find(c=>c.id===l),C=u?.subcommands.find(c=>c.id===o.selection.operationId),E=C?C.policy.strictReadOnly==="allow":u?.policy.strictReadOnly==="allow",h=l==="diagnose";let I;try{I=Ba({invocationId:dn(),intent:e.strictReadOnly||h?{schemaVersion:1,policy:Ma,registryVersion:dt,registryChecksum:st}:void 0,registryVersion:dt,registryChecksum:st,registryAllowsStrict:E,requestCanonicalBytes:JSON.stringify({command:l})})}catch(c){if(c instanceof Bt)return{success:!1,error:c.code,errorCode:c.code,exitCode:1};throw c}{I.beginProjection();for(const c of Vr)I.project(c);for(const c of ja)I.project(c);I.seal()}const b=I.mode==="strict";if(l==="create-epic"||l==="idea-diagnose")try{const c=eo(s);if(c&&c!=="finalized")return{success:!1,error:'PROJECT_IDENTITY_MIGRATION_INCOMPLETE: retry `neocortex-client invoke --args "*migrate-project-id"` before create-epic.',errorCode:"PROJECT_IDENTITY_MIGRATION_INCOMPLETE",metadata:{projectIdentityMigration:{phase:c,publicSafe:!0}},exitCode:1}}catch(c){const p=c instanceof $n?c.code:"PROJECT_IDENTITY_MIGRATION_STATE_CORRUPT";return{success:!1,error:p,errorCode:p,exitCode:1}}const D=e.environment??process.env;if(e.privateExecutionBeta&&(l!=="yolo"&&l!=="research"&&l!=="write-spec"&&l!=="create-tasks"&&l!=="implement"&&l!=="exec"&&l!=="create-epic"&&l!=="idea-diagnose"&&l!=="idea-research"&&l!=="generate-epic"&&l!=="sync-openapi"&&l!=="chaos-plan"&&l!=="ui-ux-review"&&l!=="arch-prd"&&l!=="arch-architecture"&&l!=="arch-fitness-functions"&&l!=="arch-api-contracts"&&l!=="arch-api-integrations"&&l!=="arch-database"&&l!=="arch-security"&&l!=="arch-design-system"&&l!=="arch-performance"&&l!=="arch-testing"&&l!=="arch-infrastructure"&&l!=="arch-review"&&l!=="update-memory"&&l!=="arch-ux-design"&&l!=="generate-pacts"&&l!=="property-test"&&!S||b||e.platformTarget!==void 0&&e.platformTarget!=="codex"))return{success:!1,error:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",errorCode:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",exitCode:1};const P=ka({cwd:s,env:D,targetFlag:e.privateExecutionBeta?"codex":e.platformTarget}),k=P.targetId,R=e.privateExecutionBeta?void 0:Pa({cwd:s,env:D,targetFlag:e.platformTarget,nativeHostVersion:zo(P,D)},P);if(y)try{Xn(s,{allowMissingRuntime:!0})}catch(c){const p=c instanceof lt?c.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${p}. No request was sent; repair the canonical project state/runtime sidecar and retry.
|
|
31
|
+
`),{success:!1,error:p,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}let w=y?Vn({strictReadOnly:!0}):yi(I);const j=(e.serverUrl??w?.serverUrl??ha).replace(/\/+$/,"");let L,Y=!1;if(y){const c=await So(j);if(Y=c.supported&&c.projectManifestProjection===!0,!c.supported)return{success:!1,error:`YOLO_INVOKE_ENVELOPE_CAPABILITY_UNAVAILABLE: target server does not advertise ${Na}; Local YOLO/TDD Release Gate was not executed and no invoke request was sent.`,errorCode:"YOLO_INVOKE_ENVELOPE_CAPABILITY_UNAVAILABLE",metadata:{yoloInvokeEnvelopeCapability:c},exitCode:1};try{L=Hr({projectRoot:s,storyId:y,epicId:y.split(".")[0],inputSha256:n.sha256,onOmittedReferences:p=>process.stderr.write(`[Neocortex] yolo-spec-supporting-references-omitted count=${p}; core story artifacts preserved.
|
|
32
|
+
`)})}catch(p){const m=Gr(p);return{success:!1,error:m,errorCode:m,exitCode:1}}w=yi(I)}if(l!=="migrate-project-id"&&I.execute({phase:"client-preflight",domain:"client-persistence",category:"first-run-marker",operation:"create"},()=>Mo(),()=>{}),l==="migrate-project-id"){const c=await to(j);if(!c.supported)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_CAPABILITY_UNAVAILABLE: the server did not advertise the versioned migration capability; no local state was changed.",errorCode:"PROJECT_IDENTITY_MIGRATION_CAPABILITY_UNAVAILABLE",metadata:{projectIdentityMigrationCapability:c},exitCode:1};const p=[];let m;try{m=Za(s)}catch(U){const Ie=U instanceof $n?U.code:"PROJECT_IDENTITY_MIGRATION_PREPARE_FAILED";return{success:!1,error:Ie,errorCode:Ie,exitCode:1}}p.push(Ut({phase:"prepare",outcome:m.changed&&m.document.phase==="prepared"?"prepared":"retry",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId}));const A=Cn(s);if(A.config.project_id!==m.document.projectId)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",errorCode:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",metadata:{invocationDiagnostics:p},exitCode:1};const B=await Ii(j,w?.licenseKey,I);if(B.status!=="authenticated"){const U=B.status==="refresh-required";return{success:!1,error:U?"Authentication refresh required. Run: neocortex activate YOUR-LICENSE-KEY":"Not authenticated. Visit https://neocortex.sh/portal/login to get your license key, then run: neocortex activate YOUR-LICENSE-KEY",errorCode:U?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",metadata:{invocationDiagnostics:p},exitCode:U?1:2}}let ne;try{ne=Pr(e.args.trim(),A)}catch(U){const Ie=U instanceof Or?U.code:"PROJECT_IDENTITY_MIGRATION_PROJECTION_FAILED";return{success:!1,error:Ie,errorCode:Ie,metadata:{invocationDiagnostics:p},exitCode:1}}let ce={args:i,projectRoot:s.replace(Kt(),"~"),stateSnapshot:ne,platformTarget:k,...R?{nativeHostAttestation:R}:{},projectId:m.document.projectId,projectIdentityMigration:m.request,inputEvidence:r,idempotencyKey:m.document.operationId,registryVersion:dt,registryChecksum:st,compatibility:qn()};try{ce=rr(ce).body}catch(U){if(U instanceof zn||U instanceof Jn)return{success:!1,error:U.message,errorCode:U.code,metadata:{invokePayload:U.telemetry,invocationDiagnostics:p},exitCode:1};throw U}const re=await Bn("invoke-query",()=>lr(j,ce,B.token,{refreshToken:()=>B.client.forceRefresh()}));if(!re.ok||!re.data)return p.push(Ut({phase:"seed",outcome:"rejected",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId})),{success:!1,error:Je(re.error??"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",kt),errorCode:typeof re.errorBody?.error_code=="string"?re.errorBody.error_code:"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",metadata:{invocationDiagnostics:p},exitCode:re.status===401?2:1};const fe=re.data.metadata?.projectIdentityMigration;try{Wa(fe),p.push(Ut({phase:"seed",outcome:fe.status,floor:fe.acceptedLegacyFloor,licenseId:"local-client",projectId:fe.projectId})),Qa(s,fe),p.push(Ut({phase:"remote-acknowledged",outcome:fe.status,floor:fe.acceptedLegacyFloor,licenseId:"local-client",projectId:fe.projectId})),Xa(s,fe),p.push(Ut({phase:"finalize",outcome:"finalized",floor:fe.acceptedLegacyFloor,licenseId:"local-client",projectId:fe.projectId}))}catch(U){p.push(Ut({phase:"reconcile",outcome:"rejected",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId}));const Ie=U instanceof $n?U.code:U instanceof Error?U.message:"PROJECT_IDENTITY_MIGRATION_RECEIPT_INVALID";return{success:!1,error:Ie,errorCode:Ie,metadata:{invocationDiagnostics:p},exitCode:1}}return I.complete(),{success:!0,instructions:re.data.instructions,metadata:{...re.data.metadata,...re.compatibility?{compatibility:re.compatibility}:{},invocationDiagnostics:p},exitCode:0}}try{const{normalizeYoloopTargetArgs:c}=await import("../yoloop/target-normalization.js"),p=c(e.args,{projectRoot:s});if(!p.ok)return process.stderr.write(`${p.message} reason=${p.reasonCode}
|
|
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
|
|
36
|
-
`),{success:!1,error:p,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}if(l!=="migrate-state")try{I.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>
|
|
35
|
+
`),{success:!1,error:c,exitCode:1}}const X=gi(l);if(X)try{Xn(s,{allowMissingRuntime:!0}).runtimeMissing&&(await I.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},async()=>co(s),async()=>{}),Xn(s))}catch(c){const p=c instanceof lt?c.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${p}. No request was sent; repair the canonical project state and retry.
|
|
36
|
+
`),{success:!1,error:p,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}if(l!=="migrate-state")try{I.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>Ia(s,{args:e.args,canonicalCommandId:l}),()=>{})}catch(c){if(c instanceof Ea)return process.stderr.write(`${c.message}
|
|
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
|
|
38
|
+
`),{success:!1,error:p,exitCode:1}}let pe;if(e.privateExecutionBeta&&(l==="sync-openapi"||l==="chaos-plan"||l==="arch-prd"||l==="arch-architecture"||l==="arch-fitness-functions"||l==="arch-api-contracts"||l==="arch-api-integrations"||l==="arch-database"||l==="arch-security"||l==="arch-design-system"||l==="arch-performance"||l==="arch-testing"||l==="arch-infrastructure"||l==="arch-review"||l==="update-memory"||l==="arch-ux-design"||l==="generate-pacts"||l==="property-test"||S))try{const{capturePrivateProjectStepBaseline:c}=await import("../private-execution/isolated-workspace.js");pe=c(s)}catch{const c="private-execution-project-snapshot-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let x;try{const c=await hc(s,e.args,l);x=Cn(s,{epicAware:X,p205Authorities:c,verifyPlanningGeneration:e.privateExecutionBeta&&l==="create-epic"})}catch(c){const p=c instanceof lt?c.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${p}. No request was sent; repair the canonical project state/runtime sidecar and retry.
|
|
39
39
|
`),{success:!1,error:p,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}try{const{maybeAutoResolveYoloopArgs:c}=await import("../yoloop/invoke-hooks.js"),p={args:e.args,projectRoot:s,logger:{info:m=>process.stderr.write(`${m}
|
|
40
40
|
`),warn:m=>process.stderr.write(`${m}
|
|
41
|
-
`)}};c(p),p.args!==e.args&&(e={...e,args:p.args},a=p.args,n=
|
|
42
|
-
`)}try{const{readYoloopForRequest:c}=await import("../yoloop/invoke-hooks.js"),p=await c(e.args,s);if(p){const m=
|
|
43
|
-
`),{success:!1,error:m,errorCode:m,exitCode:1}}}try{const{readContinuityForRequest:c}=await import("../continuity/invoke-hooks.js"),p=await c(e.args,s,void 0,I,{includeExistingStore:!h});p&&(
|
|
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
|
-
`)}});m.applied&&m.metadata&&(
|
|
47
|
-
`)}try{if(
|
|
48
|
-
`)}try{const c=await I.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"checkpoint-consume",operation:"consume"},async()=>{const{readAndConsumeCheckpoint:p}=await import("../checkpoint/index.js");return p(s)},async()=>{});c&&(
|
|
49
|
-
`)}const
|
|
50
|
-
`),{success:!1,error:c.message??"Trigger not available on your plan",exitCode:1}}catch{}const
|
|
51
|
-
`),!
|
|
52
|
-
`),{success:!1,error:
|
|
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(!b)try{const{openNativeAgentPrivateStore:c,resolveNativeAgentPrivateRuntimePaths:p}=await import("../continuity/native-agent-store.js"),m=p(s);if(
|
|
55
|
-
`),{success:!1,error:c,errorCode:"EPIC_PROJECT_ID_REQUIRED",exitCode:1}}let se;try{se=I.execute({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>H==="create-epic"||H==="idea-diagnose"?Ao(s,ee,H):void 0,()=>{})}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const tt=se?.key??(H==="yolo"?xo(s,ee,De,O):void 0);if(e.privateExecutionBeta&&H==="create-epic"&&se){const c=$t(s).operations[se.fingerprint],p=c?.epicId?j.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"&&j.stories[A]?.epic_id===c.epicId).map(A=>[A,j.stories[A]]))}})}const ut=b?{schemaVersion:1,invocationId:I.invocationId,intent:I.intent,clientProjection:Ma(Mr.map(c=>({...c,count:1})))}:void 0;let X,ye,le;if(e.privateExecutionBeta&&H==="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=Q(s,".neocortex/state.json"),U=jt(A);if(!U.isFile()||U.isSymbolicLink()||U.size>8*1024*1024)throw new Error("planning-research-state-unavailable");const ie=Ge(A),de=JSON.parse(ie.toString("utf8")),ae=Sr(de,m.claimId,c),fe=g(de)&&g(de.epics)&&g(de.epics[c])?de.epics[c]:void 0,$=g(fe?.createEpicPlanningPhysical)?fe.createEpicPlanningPhysical:void 0;if($?.receiptId!==m.receiptId||!v($,m))throw new Error("planning-research-predecessor-drift");const Ee=[".neocortex/state.json",".neocortex/planning/planning.json",`.neocortex/planning/epic-${c}/idea.json`,`.neocortex/planning/epic-${c}/diagnosis.md`,`.neocortex/planning/epic-${c}/enriched-prompt.md`],Be={...process.env};for(const me of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete Be[me];for(const me of Ee){const Ue=jt(Q(s,me));if(!Ue.isFile()||Ue.isSymbolicLink()||Ue.size>8*1024*1024)throw new Error("planning-research-source-unavailable");const Ke=We("git",["show",`HEAD:${me}`],{cwd:s,env:Be,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!Ge(Q(s,me)).equals(Ke))throw new Error("planning-research-source-uncommitted")}ye={claimId:m.claimId,epicId:c,diagnosisReceiptId:ae.diagnosisReceiptId,intakeRevision:ae.intakeRevision,physicalAcceptanceReceiptId:m.receiptId,sourceStateSha256:Pe("sha256").update(ie).digest("hex")}}catch{return{success:!1,error:"private-execution-planning-predecessor-unavailable",errorCode:"private-execution-planning-predecessor-unavailable",exitCode:1}}if(e.privateExecutionBeta&&H==="generate-epic")try{const c=O.scope?.targetEpicId,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=Q(s,".neocortex/state.json"),U=jt(A);if(!U.isFile()||U.isSymbolicLink()||U.size>8*1024*1024)throw new Error("planning-generation-state-unavailable");const ie=Ge(A),de=JSON.parse(ie.toString("utf8")),ae=vr(de,m.claimId,c),fe=g(de)&&g(de.epics)&&g(de.epics[c])?de.epics[c]:void 0,$=g(fe?.createEpicPlanningResearchPhysical)?fe.createEpicPlanningResearchPhysical:void 0;if($?.receiptId!==m.receiptId||!v($,m))throw new Error("planning-generation-predecessor-drift");const Ee=[".neocortex/state.json",".neocortex/planning/planning.json",`.neocortex/planning/epic-${c}/idea.json`,`.neocortex/planning/epic-${c}/diagnosis.md`,`.neocortex/planning/epic-${c}/enriched-prompt.md`,`.neocortex/planning/epic-${c}/research.md`],Be={...process.env};for(const me of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete Be[me];for(const me of Ee){const Ue=jt(Q(s,me));if(!Ue.isFile()||Ue.isSymbolicLink()||Ue.size>8*1024*1024)throw new Error("planning-generation-source-unavailable");const Ke=We("git",["show",`HEAD:${me}`],{cwd:s,env:Be,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!Ge(Q(s,me)).equals(Ke))throw new Error("planning-generation-source-uncommitted")}le={claimId:m.claimId,epicId:c,diagnosisReceiptId:ae.diagnosisReceiptId,researchReceiptId:ae.researchReceiptId,intakeRevision:ae.intakeRevision,physicalAcceptanceReceiptId:ae.physicalAcceptanceReceiptId,sourceStateSha256:Pe("sha256").update(ie).digest("hex")}}catch{return{success:!1,error:"private-execution-planning-predecessor-unavailable",errorCode:"private-execution-planning-predecessor-unavailable",exitCode:1}}if(e.privateExecutionBeta)try{const{preflightPrivateCodexExecutor:c}=await import("../private-execution/codex-executor.js");X=await c(s)}catch(c){const 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 Nt=X?{schemaVersion:1,hostKind:"codex-cli",hostVersion:X.hostVersion,sandboxProof:{schemaVersion:6,trust:"client-self-attested",credentialKind:"chatgpt-subscription",authIsolation:"passed",workspaceWrite:"passed",gitControlWriteDenied:"passed",gitLifecycleReadDenied:"passed",mcpIsolation:"passed",environmentIsolation:"passed",networkDenied:"passed",webSearchDisabled:"passed",observedAtMs:X.observedAtMs}}:void 0;let Re;if(H==="arch-plan"&&O.archPlan?.execution?.currentStageCommand==="generate-pacts"&&O.archPlan.execution.continuationState==="ask-user")try{if(Re=Ir(s),!Re)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 B;if(H==="arch-plan"&&O.archPlan?.execution?.currentStageCommand==="generate-pacts"&&O.archPlan.execution.continuationState==="delegate"&&O.archPlan.execution.childStatus==="succeeded")try{if(B=Ir(s),!B||!v(O.archPlan.execution.pactAnswerReceipt,B))throw new Error("architecture-answers-conflict")}catch{return{success:!1,error:"architecture-answers-conflict",errorCode:"architecture-answers-conflict",exitCode:1}}let je,J,ge;if(e.privateExecutionBeta&&H==="generate-pacts")try{const c=a.trim().match(/^\*?generate-pacts (P[1-9][0-9]{0,11})$/)?.[1],p=O.archPlan?.execution;if(J=Fi(s),!c||!p||p.currentStageCommand!=="generate-pacts"||p.continuationState!=="delegate"||p.targetEpicId!==c||!J||!v(p.pactAnswerReceipt,J.receipt))throw new Error("private-execution-pact-admission-unverified");const m=zi(s,J.answers.generateProvider);if(m.outcome!=="ready")throw new Error("private-execution-pact-admission-unverified");je=m.writeSet,ge={schemaVersion:1,targetEpicId:c,graphRevision:J.receipt.graphRevision,answersSha256:J.receipt.answersSha256,specSha256:je.specSha256,pathsSha256:je.pathsSha256,endpointCount:je.endpointCount,pathCount:je.paths.length,publicSafe:!0}}catch{const c="private-execution-pact-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let Ve,ne;if(e.privateExecutionBeta&&H==="arch-ux-design")try{const c=a.trim().match(/^\*?arch-ux-design (P[1-9][0-9]{0,11})$/)?.[1],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),ne={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 _t,qe,Ie;if(e.privateExecutionBeta&&H==="property-test")try{if(o.selection.positionals.length!==0||o.selection.operationId!==void 0||Object.keys(o.selection.options).length!==0)throw new Error("private-execution-property-admission-unverified");const{loadPropertyTestChoices:c}=await import("../private-execution/property-test-choices.js"),{propertyTestExecutionInput:p}=await import("../private-execution/property-test-plan.js"),m=c(s);if(!m)throw new Error("private-execution-property-admission-unverified");_t=m.choices,qe=m.plan,Ie=p(m.plan)}catch{const c="private-execution-property-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let ht;if(H==="yoloop"&&!b&&!e.privateExecutionBeta)try{ht=(e.hostCapacityProbe??Xi)({platformTarget:P,env:L})}catch{ht=void 0}let G={args:a,projectRoot:s.replace(Jt(),"~"),stateSnapshot:O,...Re?{architectureAnswerReceipt:Re}:{},...ge?{pactExecutionInput:ge}:{},...ne?{uxExecutionInput:ne}:{},...Ie?{propertyTestExecutionInput:Ie}:{},platformTarget:P,..._?{nativeHostAttestation:_}:{},...ht?{hostCapacity:ht}:{},...Nt?{privateExecution:Nt}:{},projectId:De,inputEvidence:n,...d?{invocationRecovery:d}:{},idempotencyKey:tt,registryVersion:ot,registryChecksum:at,compatibility:Yn(),...e.releaseGate?{releaseGate:e.releaseGate}:{},...ut?{strictReadOnly:ut}:{}};const tn=Ht(G);if(!b&&e.inputSource&&e.inputSource!=="args"&&tn>=$n)try{G={argsRef:(await Na(I,"secondary-mutation",()=>yc(M,a,W.token,()=>W.client.forceRefresh()),async()=>{throw new Vt("readonly-physical-boundary-unsafe","boundary")})).argsRef,projectRoot:s.replace(Jt(),"~"),stateSnapshot:O,...Re?{architectureAnswerReceipt:Re}:{},platformTarget:P,..._?{nativeHostAttestation:_}:{},...ht?{hostCapacity:ht}:{},...Nt?{privateExecution:Nt}:{},projectId:De,inputEvidence:n,...d?{invocationRecovery:d}:{},idempotencyKey:tt,registryVersion:ot,registryChecksum:at,compatibility:Yn(),...e.releaseGate?{releaseGate:e.releaseGate}:{},...ut?{strictReadOnly:ut}:{}}}catch(c){return c instanceof Vt?{success:!1,error:c.code,errorCode:c.code,exitCode:1}:{success:!1,error:`INVOKE_MATERIALIZATION_FAILED: ${c instanceof Error?c.message:String(c)}`,errorCode:"INVOKE_MATERIALIZATION_FAILED",exitCode:1}}let Rt;if(H==="yolo"&&O.scope?.projectionMode==="yolo-story"){const c=O.scope?.targetStoryId,p=O.scope?.targetEpicId;if(!c||!p||!N||N.storyId!==c||N.epicId!==p)return{success:!1,error:"yolo-spec-envelope-target-mismatch",errorCode:"yolo-spec-envelope-target-mismatch",exitCode:1};try{let m=Hr(N);if(/\sbranchless-preparation\s*$/.test(a))G={...G,yoloSpecEnvelope:m};else{const{collectYoloChangeEvidence:A,reconcileYoloChangeEvidenceLease:U}=await import("../yolo/change-evidence-collector.js");Rt=await U({projectRoot:s,storyId:c,epicId:p}),Rt.repair==="applied"&&(m=Hr(N));const ie=A({projectRoot:s,defaultBranch:O.config.default_branch,expectedHeadSha:m.sourceRevision.headSha,storyId:c,epicId:p,reconciliation:Rt});G={...G,yoloSpecEnvelope:m,yoloChangeEvidence:ie}}}catch(m){const{yoloChangeEvidenceDiagnostic:A}=await import("../yolo/change-evidence-collector.js"),U=A(m),ie=m instanceof Error&&/^yolo-(?:spec-envelope|change-evidence)-[a-z-]+$/.test(m.message)?m.message:"yolo-spec-envelope-unsafe";return{success:!1,error:ie,errorCode:ie,...U?{metadata:{yoloChangeEvidence:U}}:{},exitCode:1}}}try{const c=tr(G);if(H==="migrate-state"&&c.degraded)return{success:!1,error:"state_migration_payload_degraded",errorCode:"state_migration_payload_degraded",exitCode:1};G=c.body,c.degraded?_i(G,c.telemetry):_c(G)}catch(c){if(c instanceof Fn||c instanceof qn)return _i(G,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(
|
|
41
|
+
`)}};c(p),p.args!==e.args&&(e={...e,args:p.args},a=p.args,n=Un(Qt(t.source,a)))}catch(c){const p=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] Auto-resolve hook (P121.05) failed: ${p}. Proceeding with raw args.
|
|
42
|
+
`)}try{const{readYoloopForRequest:c}=await import("../yoloop/invoke-hooks.js"),p=await c(e.args,s);if(p){const m=ms(x,p);x.yoloop=m?{...p,continuationRecoveryEvidence:m}:p}}catch(c){if(/^\s*\*?(?:yoloop|auto-yolo|epic-runner|story-runner|loop-yolo|auto-epic)\b/i.test(e.args)){const m=c instanceof Error?c.message.match(/\bYOLOOP_[A-Z0-9_]+\b/)?.[0]??"YOLOOP_STATE_READ_FAILED":"YOLOOP_STATE_READ_FAILED";return process.stderr.write(`[Neocortex] ${m}. No yoloop request was sent and no state was mutated.
|
|
43
|
+
`),{success:!1,error:m,errorCode:m,exitCode:1}}}try{const{readContinuityForRequest:c}=await import("../continuity/invoke-hooks.js"),p=await c(e.args,s,void 0,I,{includeExistingStore:!h});p&&(x.continuity=p)}catch(c){if(c instanceof Bt)return{success:!1,error:c.code,errorCode:c.code,exitCode:1};const p=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] continuity snapshot hook failed: ${p}. Proceeding without continuity state.
|
|
44
|
+
`)}try{const{maybeRunDiscoveryHook:c}=await import("../yoloop/invoke-hooks.js");await c({args:e.args,projectRoot:s,stateSnapshot:x,featureFlag:process.env.YOLOOP_AUTO_DISCOVERY!=="off",logger:{warn:p=>{console.warn(p)},info:p=>{console.error(p)}}})}catch(c){const p=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] discovery hook failed: ${p}. Proceeding without enrichment.
|
|
45
|
+
`)}try{const{readArchitecturePolicy:c}=await import("../policy/architecture-policy.js"),p=await c(s);p&&(x.architecture_policy=p)}catch(c){const p=c instanceof Error?c.message:String(c);console.warn(`[Neocortex] architecture-policy hook failed: ${p}. Proceeding without policy.`)}try{const c=/^(1|true|on|yes)$/i.test(process.env.NEOCORTEX_GRAPH_RETRIEVAL??""),{maybeRunGraphRetrievalHook:p}=await import("../yoloop/invoke-hooks.js"),m=await p({args:e.args,projectRoot:s,featureFlag:c,logger:{warn:A=>process.stderr.write(`${A}
|
|
46
|
+
`)}});m.applied&&m.metadata&&(x.graphRetrieval=m.metadata)}catch(c){const p=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] graph retrieval hook failed: ${p}. Proceeding without enrichment.
|
|
47
|
+
`)}try{if(Fo(e.args)){const{collectProjectEvidence:c}=await import("../evidence/collector.js"),p=o.selection.uiUxReview?.architectureDir,m=c({projectRoot:s,...p?{candidatePaths:[p],includeFallbackInventory:!0}:{}});(m.evidence.length>0||m.exclusions.length>0)&&(x.projectEvidence=m)}}catch(c){const p=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] project evidence collection failed: ${p}. Proceeding without local project evidence.
|
|
48
|
+
`)}try{const c=await I.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"checkpoint-consume",operation:"consume"},async()=>{const{readAndConsumeCheckpoint:p}=await import("../checkpoint/index.js");return p(s)},async()=>{});c&&(x.implementCheckpoint=c)}catch(c){const p=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] checkpoint hook failed: ${p}. Proceeding without checkpoint.
|
|
49
|
+
`)}const Se=w?.licenseKey?new jn({cacheDir:Hn,passphrase:w.licenseKey,strictReadOnly:b}):null,Z=a.trim();if(!Z&&Se){const c=await I.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>mc(Se),async()=>null);if(c)return I.complete(),{success:!0,instructions:c.instructions,metadata:c.metadata,exitCode:0}}const J=await Ii(j,w?.licenseKey,I);if(J.status!=="authenticated"){const c=J.status==="refresh-required",p=!c&&w&&!w.licenseKey?" This may be caused by a machine fingerprint change (e.g., hardware or hostname change).":"";try{const m=Tr(),A=br(c?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",m);A&&process.stderr.write(xr(A,m))}catch{}return{success:!1,error:c?"Authentication refresh required. Run: neocortex activate YOUR-LICENSE-KEY":`Not authenticated.${p} Visit https://neocortex.sh/portal/login to get your license key, then run: neocortex activate YOUR-LICENSE-KEY`,errorCode:c?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",exitCode:c?1:2}}const gt=x.config.project_id;try{await I.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>fs(s,x,j,J.token,gt,{refreshToken:()=>J.client.forceRefresh()}),async()=>0)}catch{}const wt=bs(Z);if(wt&&!h)try{const c=await J.tierClient.preFlightCheck(wt);if(!c.allowed)return process.stderr.write(`[neocortex] ${c.message}
|
|
50
|
+
`),{success:!1,error:c.message??"Trigger not available on your plan",exitCode:1}}catch{}const ue=await Oc({args:Z,projectRoot:s,platformTarget:k,environment:e.environment??process.env,bootstrapper:e.runnerBootstrapper,effectAuthority:I});if(ue.attachToRequest&&(x.runnerBootstrap=ue.metadata),ue.warning&&process.stderr.write(`[Neocortex] ${ue.warning}
|
|
51
|
+
`),!ue.shouldContinue)return ue.error&&process.stderr.write(`[Neocortex] ${ue.error}
|
|
52
|
+
`),{success:!1,error:ue.error??"Runner auto-bootstrap required but failed.",errorCode:ue.errorCode,exitCode:ue.exitCode??1};if(ue.metadata.command==="runner"&&(ue.metadata.operation==="status"||ue.metadata.operation==="doctor"))try{const c=e.runnerObserver??Aa;x.runnerOperationalStatus=await c(ue.metadata.operation,{projectRoot:s,env:e.environment??process.env,effectAuthority:I})}catch{}let O;try{const c=ya(Z,x);if(c&&!c.ok){const p=`${c.code}: structural projection failed closed; select a valid target or repair the dependency DAG.`;return process.stderr.write(`${p}
|
|
53
|
+
`),{success:!1,error:p,errorCode:c.code,metadata:{stateProjection:c,publicSafe:!0},exitCode:1}}O=c?.snapshot??Pr(Z,x),un(Z)==="migrate-state"&&(O={...O,migrationAuthority:Sa(s)})}catch(c){if(c instanceof va)return{success:!1,error:c.reasonCode,errorCode:c.reasonCode,exitCode:1};if(c instanceof Or){const p=`${c.code}: structural projection failed closed; select a valid target or repair the dependency DAG.`;return process.stderr.write(`${p}
|
|
54
|
+
`),{success:!1,error:p,errorCode:c.code,metadata:{structuralProjection:{...c.publicDetails,publicSafe:!0}},exitCode:1}}throw c}if(!b)try{const{openNativeAgentPrivateStore:c,resolveNativeAgentPrivateRuntimePaths:p}=await import("../continuity/native-agent-store.js"),m=p(s);if(jt(m.databasePath)){const A=await c(s);try{const B=A.store.listRecentNativeAgentDispatches(20);B.length>0&&(O.nativeAgentDispatches=B)}finally{A.store.close()}}}catch{}const $=un(Z);let xe=!1;if($==="arch-plan"&&!b&&O.archPlan?.execution===void 0){const c=Ji(a);if(c)try{if(!Object.hasOwn(x.epics,c)||!Object.hasOwn(O.epics,c))throw new Error("architecture-root-epic-binding-invalid");const p=Yt(s,c);O={...O,archPlan:{execution:{schemaVersion:1,owner:"root",currentStageCommand:"arch-prd",continuationState:"delegate",evidencePolicy:"v2-required",targetEpicId:c,graphRevision:p,graphSource:"committed-epic-v1",acceptedStages:[]}}},xe=!0}catch{return{success:!1,error:"architecture-root-epic-binding-invalid",errorCode:"architecture-root-epic-binding-invalid",exitCode:1}}}if(($==="arch-plan"||$?.startsWith("arch-")||$==="generate-pacts"||$==="update-memory")&&O.archPlan?.execution?.graphSource==="committed-epic-v1")try{const c=O.archPlan.execution;if(typeof c.targetEpicId!="string"||typeof c.graphRevision!="string"||c.graphRevision!==Yt(s,c.targetEpicId))throw new Error("architecture-root-epic-binding-invalid")}catch{return{success:!1,error:"architecture-root-epic-binding-invalid",errorCode:"architecture-root-epic-binding-invalid",exitCode:1}}const Te=gt;if(($==="create-epic"||$==="idea-diagnose")&&!Te){const c='EPIC_PROJECT_ID_REQUIRED: run `neocortex-client invoke --args "*migrate-project-id"` and retry the planning command. No repository checkout or database credentials are required.';return process.stderr.write(`${c}
|
|
55
|
+
`),{success:!1,error:c,errorCode:"EPIC_PROJECT_ID_REQUIRED",exitCode:1}}let Pe;try{Pe=I.execute({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>$==="create-epic"||$==="idea-diagnose"?No(s,Z,$):void 0,()=>{})}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const Nt=Pe?.key??($==="yolo"?Do(s,Z,Te,O):void 0);if(e.privateExecutionBeta&&$==="create-epic"&&Pe){const c=Ht(s).operations[Pe.fingerprint],p=c?.epicId?x.epics[c.epicId]:void 0,m=g(p?.createEpicPlanningPhysical)?p.createEpicPlanningPhysical:void 0;c?.claimId&&c.epicId&&p&&m?.claimId===c.claimId&&(O={...O,epics:{...O.epics,[c.epicId]:p},stories:{...O.stories,...Object.fromEntries((Array.isArray(p.stories)?p.stories:[]).filter(A=>typeof A=="string"&&x.stories[A]?.epic_id===c.epicId).map(A=>[A,x.stories[A]]))}})}const rt=b?{schemaVersion:1,invocationId:I.invocationId,intent:I.intent,clientProjection:Va(Vr.map(c=>({...c,count:1})))}:void 0;let K,ve,he;if(e.privateExecutionBeta&&$==="idea-research")try{const c=O.scope?.targetEpicId,p=c?O.epics[c]:void 0,m=g(p?.createEpicPlanningPhysical)?p.createEpicPlanningPhysical:void 0;if(!c||!m||typeof m.claimId!="string"||typeof m.receiptId!="string")throw new Error("planning-research-predecessor-unavailable");const A=z(s,".neocortex/state.json"),B=Vt(A);if(!B.isFile()||B.isSymbolicLink()||B.size>8*1024*1024)throw new Error("planning-research-state-unavailable");const ne=Fe(A),ce=JSON.parse(ne.toString("utf8")),re=Cr(ce,m.claimId,c),fe=g(ce)&&g(ce.epics)&&g(ce.epics[c])?ce.epics[c]:void 0,U=g(fe?.createEpicPlanningPhysical)?fe.createEpicPlanningPhysical:void 0;if(U?.receiptId!==m.receiptId||!v(U,m))throw new Error("planning-research-predecessor-drift");const Ie=[".neocortex/state.json",".neocortex/planning/planning.json",`.neocortex/planning/epic-${c}/idea.json`,`.neocortex/planning/epic-${c}/diagnosis.md`,`.neocortex/planning/epic-${c}/enriched-prompt.md`],Ue={...process.env};for(const me of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete Ue[me];for(const me of Ie){const $e=Vt(z(s,me));if(!$e.isFile()||$e.isSymbolicLink()||$e.size>8*1024*1024)throw new Error("planning-research-source-unavailable");const Xe=Ge("git",["show",`HEAD:${me}`],{cwd:s,env:Ue,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!Fe(z(s,me)).equals(Xe))throw new Error("planning-research-source-uncommitted")}ve={claimId:m.claimId,epicId:c,diagnosisReceiptId:re.diagnosisReceiptId,intakeRevision:re.intakeRevision,physicalAcceptanceReceiptId:m.receiptId,sourceStateSha256:Ne("sha256").update(ne).digest("hex")}}catch{return{success:!1,error:"private-execution-planning-predecessor-unavailable",errorCode:"private-execution-planning-predecessor-unavailable",exitCode:1}}if(e.privateExecutionBeta&&$==="generate-epic")try{const c=O.scope?.targetEpicId,p=c?O.epics[c]:void 0,m=g(p?.createEpicPlanningResearchPhysical)?p.createEpicPlanningResearchPhysical:void 0;if(!c||!m||typeof m.claimId!="string"||typeof m.receiptId!="string")throw new Error("planning-generation-predecessor-unavailable");const A=z(s,".neocortex/state.json"),B=Vt(A);if(!B.isFile()||B.isSymbolicLink()||B.size>8*1024*1024)throw new Error("planning-generation-state-unavailable");const ne=Fe(A),ce=JSON.parse(ne.toString("utf8")),re=Rr(ce,m.claimId,c),fe=g(ce)&&g(ce.epics)&&g(ce.epics[c])?ce.epics[c]:void 0,U=g(fe?.createEpicPlanningResearchPhysical)?fe.createEpicPlanningResearchPhysical:void 0;if(U?.receiptId!==m.receiptId||!v(U,m))throw new Error("planning-generation-predecessor-drift");const Ie=[".neocortex/state.json",".neocortex/planning/planning.json",`.neocortex/planning/epic-${c}/idea.json`,`.neocortex/planning/epic-${c}/diagnosis.md`,`.neocortex/planning/epic-${c}/enriched-prompt.md`,`.neocortex/planning/epic-${c}/research.md`],Ue={...process.env};for(const me of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete Ue[me];for(const me of Ie){const $e=Vt(z(s,me));if(!$e.isFile()||$e.isSymbolicLink()||$e.size>8*1024*1024)throw new Error("planning-generation-source-unavailable");const Xe=Ge("git",["show",`HEAD:${me}`],{cwd:s,env:Ue,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!Fe(z(s,me)).equals(Xe))throw new Error("planning-generation-source-uncommitted")}he={claimId:m.claimId,epicId:c,diagnosisReceiptId:re.diagnosisReceiptId,researchReceiptId:re.researchReceiptId,intakeRevision:re.intakeRevision,physicalAcceptanceReceiptId:re.physicalAcceptanceReceiptId,sourceStateSha256:Ne("sha256").update(ne).digest("hex")}}catch{return{success:!1,error:"private-execution-planning-predecessor-unavailable",errorCode:"private-execution-planning-predecessor-unavailable",exitCode:1}}if(e.privateExecutionBeta)try{const{preflightPrivateCodexExecutor:c}=await import("../private-execution/codex-executor.js");K=await c(s)}catch(c){const p=c instanceof Error&&/^private-codex-[a-z-]+$/.test(c.message)?c.message:"private-codex-preflight-unavailable";return{success:!1,error:p,errorCode:p,exitCode:1}}const qe=K?{schemaVersion:1,hostKind:"codex-cli",hostVersion:K.hostVersion,sandboxProof:{schemaVersion:6,trust:"client-self-attested",credentialKind:"chatgpt-subscription",authIsolation:"passed",workspaceWrite:"passed",gitControlWriteDenied:"passed",gitLifecycleReadDenied:"passed",mcpIsolation:"passed",environmentIsolation:"passed",networkDenied:"passed",webSearchDisabled:"passed",observedAtMs:K.observedAtMs}}:void 0;let V;if($==="arch-plan"&&O.archPlan?.execution?.currentStageCommand==="generate-pacts"&&O.archPlan.execution.continuationState==="ask-user")try{if(V=Sr(s),!V)throw new Error("architecture-answers-required")}catch(c){const p=c instanceof Error&&/^architecture-answers-[a-z-]+$/.test(c.message)?c.message:"architecture-answers-failed";return{success:!1,error:p,errorCode:p,exitCode:1}}let ft;if($==="arch-plan"&&O.archPlan?.execution?.currentStageCommand==="generate-pacts"&&O.archPlan.execution.continuationState==="delegate"&&O.archPlan.execution.childStatus==="succeeded")try{if(ft=Sr(s),!ft||!v(O.archPlan.execution.pactAnswerReceipt,ft))throw new Error("architecture-answers-conflict")}catch{return{success:!1,error:"architecture-answers-conflict",errorCode:"architecture-answers-conflict",exitCode:1}}let ge,oe,ye;if(e.privateExecutionBeta&&$==="generate-pacts")try{const c=a.trim().match(/^\*?generate-pacts (P[1-9][0-9]{0,11})$/)?.[1],p=O.archPlan?.execution;if(oe=zi(s),!c||!p||p.currentStageCommand!=="generate-pacts"||p.continuationState!=="delegate"||p.targetEpicId!==c||!oe||!v(p.pactAnswerReceipt,oe.receipt))throw new Error("private-execution-pact-admission-unverified");const m=Ki(s,oe.answers.generateProvider);if(m.outcome!=="ready")throw new Error("private-execution-pact-admission-unverified");ge=m.writeSet,ye={schemaVersion:1,targetEpicId:c,graphRevision:oe.receipt.graphRevision,answersSha256:oe.receipt.answersSha256,specSha256:ge.specSha256,pathsSha256:ge.pathsSha256,endpointCount:ge.endpointCount,pathCount:ge.paths.length,publicSafe:!0}}catch{const c="private-execution-pact-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let Ve,ee;if(e.privateExecutionBeta&&$==="arch-ux-design")try{const c=a.trim().match(/^\*?arch-ux-design (P[1-9][0-9]{0,11})$/)?.[1],p=O.archPlan?.execution;if(!c||!p||p.currentStageCommand!=="arch-ux-design"||p.continuationState!=="delegate"||p.targetEpicId!==c||typeof p.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(p.graphRevision))throw new Error("private-execution-ux-admission-unverified");const{deriveUxWriteSet:m}=await import("../private-execution/ux-write-set.js");Ve=m(s,c),ee={schemaVersion:1,targetEpicId:c,graphRevision:p.graphRevision,adapterId:Ve.adapterId,authoritySha256:Ve.authoritySha256,pathsSha256:Ve.pathsSha256,screenCount:Ve.screenCount,pathCount:Ve.pathCount,publicSafe:!0}}catch{const c="private-execution-ux-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let mt,ze,ke;if(e.privateExecutionBeta&&$==="property-test")try{if(o.selection.positionals.length!==0||o.selection.operationId!==void 0||Object.keys(o.selection.options).length!==0)throw new Error("private-execution-property-admission-unverified");const{loadPropertyTestChoices:c}=await import("../private-execution/property-test-choices.js"),{propertyTestExecutionInput:p}=await import("../private-execution/property-test-plan.js"),m=c(s);if(!m)throw new Error("private-execution-property-admission-unverified");mt=m.choices,ze=m.plan,ke=p(m.plan)}catch{const c="private-execution-property-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let Qe;if($==="yoloop"&&!b&&!e.privateExecutionBeta)try{Qe=(e.hostCapacityProbe??ea)({platformTarget:k,env:D})}catch{Qe=void 0}let H={args:a,projectRoot:s.replace(Kt(),"~"),stateSnapshot:O,...V?{architectureAnswerReceipt:V}:{},...ye?{pactExecutionInput:ye}:{},...ee?{uxExecutionInput:ee}:{},...ke?{propertyTestExecutionInput:ke}:{},platformTarget:k,...R?{nativeHostAttestation:R}:{},...Qe?{hostCapacity:Qe}:{},...qe?{privateExecution:qe}:{},projectId:Te,inputEvidence:n,...d?{invocationRecovery:d}:{},idempotencyKey:Nt,registryVersion:dt,registryChecksum:st,compatibility:qn(),...e.releaseGate?{releaseGate:e.releaseGate}:{},...rt?{strictReadOnly:rt}:{}};const bn=Wt(H);if(!b&&e.inputSource&&e.inputSource!=="args"&&bn>=Wn)try{H={argsRef:(await Da(I,"secondary-mutation",()=>wc(j,a,J.token,()=>J.client.forceRefresh()),async()=>{throw new Bt("readonly-physical-boundary-unsafe","boundary")})).argsRef,projectRoot:s.replace(Kt(),"~"),stateSnapshot:O,...V?{architectureAnswerReceipt:V}:{},platformTarget:k,...R?{nativeHostAttestation:R}:{},...Qe?{hostCapacity:Qe}:{},...qe?{privateExecution:qe}:{},projectId:Te,inputEvidence:n,...d?{invocationRecovery:d}:{},idempotencyKey:Nt,registryVersion:dt,registryChecksum:st,compatibility:qn(),...e.releaseGate?{releaseGate:e.releaseGate}:{},...rt?{strictReadOnly:rt}:{}}}catch(c){return c instanceof Bt?{success:!1,error:c.code,errorCode:c.code,exitCode:1}:{success:!1,error:`INVOKE_MATERIALIZATION_FAILED: ${c instanceof Error?c.message:String(c)}`,errorCode:"INVOKE_MATERIALIZATION_FAILED",exitCode:1}}let it;if($==="yolo"&&O.scope?.projectionMode==="yolo-story"){const c=O.scope?.targetStoryId,p=O.scope?.targetEpicId;if(!c||!p||!L||L.storyId!==c||L.epicId!==p)return{success:!1,error:"yolo-spec-envelope-target-mismatch",errorCode:"yolo-spec-envelope-target-mismatch",exitCode:1};try{let m=Wr(L);if(/\sbranchless-preparation\s*$/.test(a))H={...H,yoloSpecEnvelope:m};else{const{collectYoloChangeEvidence:A,reconcileYoloChangeEvidenceLease:B}=await import("../yolo/change-evidence-collector.js");it=await B({projectRoot:s,storyId:c,epicId:p}),it.repair==="applied"&&(m=Wr(L));const ne=A({projectRoot:s,defaultBranch:O.config.default_branch,expectedHeadSha:m.sourceRevision.headSha,storyId:c,epicId:p,reconciliation:it});H={...H,yoloSpecEnvelope:m,yoloChangeEvidence:ne}}H=vo(H,{projectRoot:s,supported:Y})}catch(m){const{yoloChangeEvidenceDiagnostic:A}=await import("../yolo/change-evidence-collector.js"),B=A(m),ne=Gr(m,!0);return{success:!1,error:ne,errorCode:ne,...B?{metadata:{yoloChangeEvidence:B}}:{},exitCode:1}}}try{const c=rr(H);if($==="migrate-state"&&c.degraded)return{success:!1,error:"state_migration_payload_degraded",errorCode:"state_migration_payload_degraded",exitCode:1};H=c.body,c.degraded?wi(H,c.telemetry):kc(H)}catch(c){if(c instanceof zn||c instanceof Jn)return wi(H,c.telemetry),process.stderr.write(`[Neocortex] ${c.message}
|
|
56
|
+
`),{success:!1,error:c.message,errorCode:c.code,metadata:{invokePayload:c.telemetry},exitCode:1};throw c}if($==="yolo"&&H.yoloSpecEnvelope)try{const c=Hr({projectRoot:s,storyId:H.yoloSpecEnvelope.storyId,epicId:H.yoloSpecEnvelope.epicId,inputSha256:n.sha256,collectedAt:H.yoloSpecEnvelope.collectedAt});if(c.envelopeSha256!==H.yoloSpecEnvelope.envelopeSha256)throw new Error("yolo-spec-envelope-stale");if(H.yoloChangeEvidence){const{collectYoloChangeEvidence:p}=await import("../yolo/change-evidence-collector.js"),m=p({projectRoot:s,defaultBranch:O.config.default_branch,expectedHeadSha:c.sourceRevision.headSha,storyId:c.storyId,epicId:c.epicId,...it?{reconciliation:it}:{}});if(m.pathsSha256!==H.yoloChangeEvidence.pathsSha256||m.baseSha!==H.yoloChangeEvidence.baseSha)throw new Error("yolo-change-evidence-stale")}}catch(c){const p=c instanceof Error&&c.message==="yolo-change-evidence-stale"?c.message:"yolo-spec-envelope-stale",{yoloChangeEvidenceDiagnostic:m}=await import("../yolo/change-evidence-collector.js"),A=m(c);return{success:!1,error:p,errorCode:p,...A?{metadata:{yoloChangeEvidence:A}}:{},exitCode:1}}const N=$==="arch-plan"?H.stateSnapshot.archPlan?.execution:void 0;let Lt;if(N?.owner==="root"&&(N.currentStageCommand==="arch-prd"||N.currentStageCommand==="arch-architecture"||N.currentStageCommand==="arch-fitness-functions"||N.currentStageCommand==="arch-api-contracts"||N.currentStageCommand==="generate-pacts"||N.currentStageCommand==="arch-api-integrations"||N.currentStageCommand==="arch-database"||N.currentStageCommand==="arch-security"||N.currentStageCommand==="arch-design-system"||N.currentStageCommand==="arch-ux-design"||N.currentStageCommand==="arch-performance"||N.currentStageCommand==="arch-testing"||N.currentStageCommand==="arch-infrastructure"||N.currentStageCommand==="arch-review"||N.currentStageCommand==="update-memory")&&(N.continuationState==="delegate"||N.continuationState==="advance"||N.currentStageCommand==="update-memory"&&N.continuationState==="complete"||N.currentStageCommand==="arch-review"&&N.continuationState==="ask-user"||N.currentStageCommand==="generate-pacts"&&N.continuationState==="ask-user"))try{const c=Fe(z(s,".neocortex","state.json"),"utf8"),p=JSON.parse(c),m=g(p.archPlan)?p.archPlan.execution:void 0;if(xe?m!==void 0||!g(p.epics)||!Object.hasOwn(p.epics,String(N.targetEpicId))||N.graphSource!=="committed-epic-v1"||N.graphRevision!==Yt(s,String(N.targetEpicId)):!v(En(m),N))throw new Error("architecture-root-state-binding-invalid");if(Lt=Ne("sha256").update(c).digest("hex"),V&&V.stateSha256!==Lt)throw new Error("architecture-root-state-binding-invalid");if(N.currentStageCommand==="update-memory"&&N.childStatus==="succeeded"){const A=N.continuationState==="complete"&&Array.isArray(N.acceptedStages)?{...N,continuationState:"delegate",acceptedStages:N.acceptedStages.slice(0,Ir(N))}:N;if(!Ft(N.terminalMemoryCheckpoint,N)||!v(N.terminalMemoryCheckpoint,Ln(s,A)))throw new Error("architecture-terminal-memory-physical-invalid")}}catch{return{success:!1,error:"architecture-root-state-binding-invalid",errorCode:"architecture-root-state-binding-invalid",exitCode:1}}let f=await Bn("invoke-query",()=>lr(j,H,J.token,{refreshToken:()=>J.client.forceRefresh()}));if($==="yoloop"&&!b&&f.ok&&f.data?.metadata?.errorCode==="YOLOOP_SPEC_NOT_READY"&&f.data.metadata.hint==="yoloop-session-invalidated"){const c=O.scope?.targetEpicId;if(!c)return{success:!1,error:"yoloop-causal-reconciliation-target-invalid",errorCode:"YOLOOP_CAUSAL_RECONCILIATION_BLOCKED",exitCode:1};const p=await Es({projectRoot:s,snapshot:x,targetEpicId:c,originalInputSha256:n.sha256,canonicalInputSha256:d?.canonicalSha256??n.sha256});if(p.outcome!=="applied")return{success:!1,error:p.reasonCode,errorCode:"YOLOOP_CAUSAL_RECONCILIATION_BLOCKED",metadata:{yoloopCausalRecovery:p},exitCode:1};try{const{readYoloopForRequest:m}=await import("../yoloop/invoke-hooks.js"),A=await m(a,s);if(!A)throw new Error("yoloop-causal-reconciliation-postimage-unverified");H=rr({...H,stateSnapshot:{...H.stateSnapshot,yoloop:A}}).body}catch(m){const A=Vi(m);return{success:!1,error:A,errorCode:"YOLOOP_CAUSAL_RECONCILIATION_BLOCKED",metadata:{yoloopCausalRecovery:{outcome:"blocked",reasonCode:A,retryCount:0,publicSafe:!0}},exitCode:1}}f=await Bn("invoke-query",()=>lr(j,H,J.token,{refreshToken:()=>J.client.forceRefresh()}))}let nn;if(b&&f.ok)try{if(h){const p=f.data?.metadata;if(p&&["stateUpdate","stateMutated","yoloopStateUpdate","continuityStateUpdate","checkpoint","schedulerStateUpdate","quotaCacheUpdate","projectIdentityMigration","epicClaim","gitLifecycleGraphAuthority"].some(A=>p[A]!==void 0))throw new Bt("readonly-response-conflict")}const c=f.data?.metadata.strictReadOnly;Ua(I,c),h&&Ya(f.data?.metadata.strictDiagnose,i,f.data?.instructions??""),nn=c.security}catch(c){const p=c instanceof Bt?c.code:"readonly-receipt-mismatch";return{success:!1,error:p,errorCode:p,exitCode:1}}if(!f.ok&&f.status===426){const c=f.errorBody,p=c?.upgrade_command??"npm install -g @ornexus/neocortex@latest",m=c?.min_version??"unknown";return process.stderr.write(`
|
|
57
57
|
`),process.stderr.write(`==================================================
|
|
58
58
|
`),process.stderr.write(` UPGRADE REQUIRED
|
|
59
59
|
`),process.stderr.write(`==================================================
|
|
@@ -68,11 +68,11 @@ The C04 barrier did not open within the bounded wait. Return this resumable rece
|
|
|
68
68
|
`),process.stderr.write(` After updating, re-run your command.
|
|
69
69
|
`),process.stderr.write(`==================================================
|
|
70
70
|
|
|
71
|
-
`),{success:!1,error:`UPGRADE_REQUIRED: Client version ${Pt} is below minimum ${m}. Run: ${p}`,exitCode:3}}if(!f.ok||!f.data){const c=f.status===401?2:(f.status===429||f.status>=500,1),p=
|
|
72
|
-
`),m;try{if(p){const A=
|
|
73
|
-
`),{success:!1,error:p,errorCode:p,exitCode:1}}if(!
|
|
74
|
-
`),{success:!1,error:p,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}catch(c){if(f.data.metadata?.stateMutationReason==="inline-yolo-materialized-synthetic-story"){const p=c instanceof Error?c.message:String(c),m=`STATE_WRITEBACK_BLOCKED: inline-yolo persistence failed (${
|
|
75
|
-
`),{success:!1,error:m,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}if(f.data.metadata?.gitLifecycleGraphAuthority)try{await I.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},()=>
|
|
71
|
+
`),{success:!1,error:`UPGRADE_REQUIRED: Client version ${Pt} is below minimum ${m}. Run: ${p}`,exitCode:3}}if(!f.ok||!f.data){const c=f.status===401?2:(f.status===429||f.status>=500,1),p=Ec(f),m=jo(p);if(m)return process.stderr.write(`[Neocortex] ${m.error}
|
|
72
|
+
`),m;try{if(p){const A=Tr(),B=br(p,A);B&&process.stderr.write(xr(B,A))}}catch{}return{success:!1,error:Je(f.error??"Unknown error from server",kt),...p?{errorCode:p}:{},...f.compatibility?{metadata:{compatibility:f.compatibility}}:{},exitCode:c}}const hr=Vo(f.data);if(hr)return I.complete(nn),hr;let _e;try{_e=e.privateExecutionBeta&&$==="create-epic"&&Pe?Ht(s).operations[Pe.fingerprint]:void 0}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const rn=_e?.planningProtocol==="root-staged-v1"&&typeof _e.claimId=="string"&&typeof _e.epicId=="string"&&na(f.data,{claimId:_e.claimId,epicId:_e.epicId,...g(x.epics[_e.epicId]?.createEpicPlanningMemoryPhysical)?{memoryReceiptId:x.epics[_e.epicId].createEpicPlanningMemoryPhysical.receiptId}:{}});if(e.privateExecutionBeta&&!rn&&!ta(f.data))return{success:!1,error:"private-execution-public-envelope-invalid",errorCode:"private-execution-public-envelope-invalid",exitCode:1};if(Lt&&N&&f.data.metadata?.mode==="arch-plan"&&g(f.data.metadata.archPlan)&&g(f.data.metadata.archPlan.execution)&&(f.data.metadata.archPlan.execution.nextAction==="delegate"||f.data.metadata.archPlan.execution.nextAction==="resume"||f.data.metadata.archPlan.execution.nextAction==="ask-user"||f.data.metadata.archPlan.execution.nextAction==="complete"&&f.data.metadata.archPlan.execution.currentStageCommand==="update-memory"||f.data.metadata.archPlan.execution.nextAction==="blocked"&&(f.data.metadata.archPlan.execution.currentStageCommand==="arch-ux-design"||f.data.metadata.archPlan.execution.currentStageCommand==="arch-performance"||f.data.metadata.archPlan.execution.currentStageCommand==="arch-testing"||f.data.metadata.archPlan.execution.currentStageCommand==="arch-infrastructure"||f.data.metadata.archPlan.execution.currentStageCommand==="arch-review")))try{await I.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>nc({projectRoot:s,sourceStateSha256:Lt,requestExecution:N,initialBinding:xe,answerReceipt:V,pactRecordedReceipt:ft,metadata:f.data.metadata}),async()=>{throw new Error("architecture-root-writeback-effect-skipped")})}catch(c){const p=c instanceof Error&&/^architecture-root-[a-z-]+$/.test(c.message)?c.message:"architecture-root-writeback-failed";return process.stderr.write(`[Neocortex] ${p}. Root stage instruction was not released.
|
|
73
|
+
`),{success:!1,error:p,errorCode:p,exitCode:1}}if(!Z&&f.data.metadata?.mode==="menu"&&Se&&await I.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>yc(Se,f.data.instructions,f.data.metadata),async()=>{}).catch(()=>{}),f.data.metadata&&await I.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"tier-cache",operation:"update"},()=>J.tierClient.updateQuotaFromResponse(f.data.metadata),async()=>{}).catch(()=>{}),f.data.metadata?.stateMutated===!0)try{const c=await I.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>{const{persistMigratedStateFromResponse:p}=await import("../yoloop/invoke-hooks.js");return p(f.data.metadata,s)},async()=>({applied:!1,blocking:!1,reasonCode:"state-writeback-effect-skipped"}));if(c.blocking){const p=`STATE_WRITEBACK_BLOCKED: ${c.reasonCode}. Canonical state was not replaced.`;return process.stderr.write(`${p}
|
|
74
|
+
`),{success:!1,error:p,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}catch(c){if(f.data.metadata?.stateMutationReason==="inline-yolo-materialized-synthetic-story"){const p=c instanceof Error?c.message:String(c),m=`STATE_WRITEBACK_BLOCKED: inline-yolo persistence failed (${Je(p,kt)}).`;return process.stderr.write(`${m}
|
|
75
|
+
`),{success:!1,error:m,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}if(f.data.metadata?.gitLifecycleGraphAuthority)try{await I.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},()=>lo(s,f.data.metadata.gitLifecycleGraphAuthority),async()=>{throw new Error("git-lifecycle-graph-authority-effect-skipped")})}catch(c){const p=c instanceof Error&&/^git-lifecycle-/.test(c.message)?c.message:"git-lifecycle-graph-authority-persist-failed";return process.stderr.write(`[Neocortex] ${p}. Graph authority was not persisted; no YOLO checkpoint instruction was released.
|
|
76
76
|
`),{success:!1,error:p,errorCode:"GIT_LIFECYCLE_GRAPH_AUTHORITY_INVALID",exitCode:1}}if(f.data.metadata?.mode==="error"&&f.data.metadata?.errorCode==="CLIENT_UPGRADE_REQUIRED")return process.stderr.write(`
|
|
77
77
|
`),process.stderr.write(`==================================================
|
|
78
78
|
`),process.stderr.write(` YOLOOP CLIENT UPGRADE REQUIRED
|
|
@@ -92,51 +92,51 @@ The C04 barrier did not open within the bounded wait. Return this resumable rece
|
|
|
92
92
|
`),{success:!1,error:A,errorCode:A,exitCode:1}}}catch(m){if(p){const A=m instanceof Error?m.message.match(/\bYOLOOP_[A-Z0-9_]+\b/)?.[0]??"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED":"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED";return process.stderr.write(`[Neocortex] ${A}. No yoloop continuation instructions were released.
|
|
93
93
|
`),{success:!1,error:A,errorCode:A,exitCode:1}}}}if(f.data.metadata?.continuityStateUpdate)try{const c=await I.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
94
|
`),{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
|
-
`),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${
|
|
95
|
+
`),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${Je(p,kt)}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}if(f.data.metadata?.tier_changed){const c=f.data.metadata.current_tier;try{await J.client.forceRefresh()?(await J.tierClient.invalidateTierCache(),process.stderr.write(`[Neocortex] Token atualizado automaticamente para tier ${c}
|
|
96
96
|
`)):process.stderr.write(`[Neocortex] Seu tier foi atualizado para ${c}! Execute "neocortex activate" para obter um token atualizado.
|
|
97
97
|
`)}catch{process.stderr.write(`[Neocortex] Seu tier foi atualizado para ${c}! Execute "neocortex activate" para obter um token atualizado.
|
|
98
|
-
`)}}let
|
|
98
|
+
`)}}let te,gr=!1;if(e.privateExecutionBeta&&!rn)try{if(!K||!f.data.metadata?.privateExecution||!Te||f.data.metadata?.mode!=="yolo"&&f.data.metadata?.mode!=="step"&&f.data.metadata?.mode!=="pipeline"&&f.data.metadata?.mode!=="create-epic"&&f.data.metadata?.mode!=="utility"&&f.data.metadata?.mode!=="tech-debt"&&f.data.metadata?.mode!=="ui-ux-review"||typeof f.data.metadata.stepId!="string")throw new Error("private-execution-descriptor-unavailable");const{consumePrivateExecutionDelivery:c,privateExecutionStateSnapshotSha256:p}=await import("../private-execution/delivery.js"),{preflightPrivateCodexExecutor:m,runPrivateCodexStep:A}=await import("../private-execution/codex-executor.js"),B=f.data.metadata.mode==="yolo",ne=f.data.metadata.mode==="ui-ux-review"&&f.data.metadata.resolvedTrigger==="ui-ux-review",ce=f.data.metadata.mode==="create-epic",re=g(f.data.metadata.privateExecution)?f.data.metadata.privateExecution:void 0,fe=g(re?.binding)?re.binding:void 0,U=ce&&f.data.metadata.resolvedTrigger==="create-epic"&&fe?.writeSetId==="idea-diagnosis-v1"&&f.data.metadata.stepId==="step-acd455ed";if(ce&&!U)throw new Error("private-execution-planning-root-protocol-required");const Ie=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="idea-diagnose"||U,Ue=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="idea-research",me=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="generate-epic",$e=ce||Ie;if(Ue&&!ve||me&&!he)throw new Error("private-execution-planning-predecessor-unavailable");const Xe=f.data.metadata.mode==="utility"&&f.data.metadata.resolvedTrigger==="sync-openapi"||f.data.metadata.mode==="utility"&&f.data.metadata.resolvedTrigger==="chaos-plan"||S&&f.data.metadata.mode==="tech-debt"&&f.data.metadata.resolvedTrigger==="tech-debt",Ce=f.data.metadata.mode==="step"&&(f.data.metadata.resolvedTrigger==="arch-prd"||f.data.metadata.resolvedTrigger==="arch-architecture"||f.data.metadata.resolvedTrigger==="arch-fitness-functions"||f.data.metadata.resolvedTrigger==="arch-api-contracts"||f.data.metadata.resolvedTrigger==="arch-api-integrations"||f.data.metadata.resolvedTrigger==="arch-database"||f.data.metadata.resolvedTrigger==="arch-security"||f.data.metadata.resolvedTrigger==="arch-design-system"||f.data.metadata.resolvedTrigger==="arch-performance"||f.data.metadata.resolvedTrigger==="arch-testing"||f.data.metadata.resolvedTrigger==="arch-infrastructure"||f.data.metadata.resolvedTrigger==="arch-review"||f.data.metadata.resolvedTrigger==="update-memory")?f.data.metadata.resolvedTrigger:void 0,yt=Ce!==void 0,Tn=Ce==="arch-prd"?"arch-prd-docs-v1":Ce==="update-memory"?"arch-memory-canonical-v1":Ce==="arch-review"?"arch-review-doc-v1":Ce==="arch-infrastructure"?"arch-infrastructure-doc-v1":Ce==="arch-testing"?"arch-testing-doc-v1":Ce==="arch-performance"?"arch-performance-doc-v1":Ce==="arch-design-system"?"arch-design-system-doc-v1":Ce==="arch-security"?"arch-security-doc-v1":Ce==="arch-database"?"arch-database-doc-v1":Ce==="arch-api-integrations"?"arch-api-integrations-doc-v1":Ce==="arch-api-contracts"?"arch-api-contracts-docs-v1":Ce==="arch-fitness-functions"?"arch-fitness-tools-v1":"arch-architecture-doc-v1",at=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="generate-pacts",It=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="arch-ux-design",Et=f.data.metadata.mode==="utility"&&f.data.metadata.resolvedTrigger==="property-test",Pn=S?"tech-debt":f.data.metadata.resolvedTrigger==="chaos-plan"?"chaos-plan":"sync-openapi",fr=S?"tech-debt-registry-v1":Pn==="chaos-plan"?"chaos-quarterly-v1":"sync-openapi-contract-v1",Ye=O.archPlan?.execution,on=Ye?.targetEpicId,cn=Ye?.graphRevision;if(yt&&(Ye?.currentStageCommand!==Ce||typeof on!="string"||!/^P[1-9][0-9]{0,11}$/.test(on)||typeof cn!="string"||!/^[a-f0-9]{64}$/.test(cn)))throw new Error("private-execution-architecture-admission-unverified");if(at&&(!ye||!ge||!oe||Ye?.currentStageCommand!=="generate-pacts"||Ye.continuationState!=="delegate"||Ye.targetEpicId!==ye.targetEpicId||Ye.graphRevision!==ye.graphRevision||!v(Ye.pactAnswerReceipt,oe.receipt)))throw new Error("private-execution-pact-admission-unverified");if(It&&(!ee||!Ve||Ye?.currentStageCommand!=="arch-ux-design"||Ye.continuationState!=="delegate"||Ye.targetEpicId!==ee.targetEpicId||Ye.graphRevision!==ee.graphRevision))throw new Error("private-execution-ux-admission-unverified");if(Et&&(!ke||!mt||!ze||f.data.metadata.stepId!=="step-a8ce5c64"))throw new Error("private-execution-property-admission-unverified");let mr;if(at){const{planPactToolchainManifest:ae,preparePactToolchainCandidate:le}=await import("../private-execution/pact-toolchain.js");try{ae(s,oe.answers.generateProvider),mr=le(s,oe.answers.generateProvider)}catch(W){if(W.message!=="pact-toolchain-manifest-unsupported")throw W}}let At,se,kn;const ie=f.data.metadata.gitLifecycleGraphAuthority,bt=f.data.metadata.privateExecutionRootAction;let Ze;if(B){if(!ie||typeof ie.storyId!="string"||typeof ie.graphRevision!="string"||typeof ie.executionBranch!="string")throw new Error("private-execution-graph-unavailable");if(Ze=ie.storyId,bt?.action==="prepare-epic-checkout"){const{parsePrivateExecutionDescriptor:T}=await import("../private-execution/delivery.js"),{prepareDirectYoloSetup:Oe}=await import("../git/direct-yolo-checkpoint.js"),{acceptDirectYoloSetupCheckpoint:St}=await import("../git/direct-yolo-checkpoint.js"),{capturePrivateYoloCleanHead:We,recordPrivateYoloCleanBaseline:we}=await import("../private-execution/clean-baseline.js"),Ae=T(f.data.metadata.privateExecution,{projectId:Te,commandId:"yolo",stepId:f.data.metadata.stepId,graphRevision:ie.graphRevision,inputSha256:n.sha256,hostKind:"codex-cli",hostVersion:K.hostVersion}),ct=await J.client.getToken();if(!ct)throw new Error("private-execution-auth-unavailable");if(!await gs(j,{leaseId:Ae.leaseId,...Ae.binding},ct))throw new Error("private-execution-setup-lease-cancel-unverified");const Mt=We(s),sn=await Oe({projectRoot:s,storyId:bt.storyId});if(!sn.ok)throw new Error("private-execution-root-setup-denied");await we(s,sn.value,Mt);const{ensurePrivateYoloIsolatedSession:xt}=await import("../private-execution/isolated-session.js");await xt(s,bt.storyId,ie.graphRevision,e.privateExecutionWorkspaceParent);const Tt=await St({projectRoot:s,storyId:bt.storyId});if(!Tt.ok)throw new Error(`private-execution-root-setup-checkpoint-denied:${Tt.reasonCode}`);te={schemaVersion:1,outcome:"setup-accepted",executorOutcome:"not-run-root-only",setup:Tt.value,publicSafe:!0};const On=yn(f.data.instructions,{...f.data.metadata,...f.compatibility?{compatibility:f.compatibility}:{}});return I.complete(nn),{success:!0,instructions:`# Setup do branch validado
|
|
99
99
|
|
|
100
|
-
O root confirmou o checkpoint C01 no branch do \xE9pico. Reexecute o mesmo YOLO para avan\xE7ar \xE0 pr\xF3xima etapa.`,metadata:{...
|
|
100
|
+
O root confirmou o checkpoint C01 no branch do \xE9pico. Reexecute o mesmo YOLO para avan\xE7ar \xE0 pr\xF3xima etapa.`,metadata:{...On.metadata,privateExecutionReceipt:te},exitCode:0}}let ae;try{ae=Ge("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:s,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{throw new Error("private-execution-execution-branch-mismatch")}if(ae!==ie.executionBranch)throw new Error("private-execution-execution-branch-mismatch");const le=fn(s,{required:!0}),W=typeof ie.epicId=="string"?le.epics[ie.epicId]:void 0,M=g(W?.branch_lease)?W.branch_lease:void 0;if(!W||W.graph_revision!==ie.graphRevision||!M||M.ownerStoryId!==ie.storyId||typeof M.expiresAt!="string"||!Number.isFinite(Date.parse(M.expiresAt))||Date.parse(M.expiresAt)<=Date.now())throw new Error("private-execution-writer-lease-unavailable")}else if(f.data.metadata.mode==="step"&&(f.data.metadata.resolvedTrigger==="research"||f.data.metadata.resolvedTrigger==="write-spec"||f.data.metadata.resolvedTrigger==="create-tasks"||f.data.metadata.resolvedTrigger==="implement")||f.data.metadata.mode==="pipeline"&&f.data.metadata.resolvedTrigger==="exec"||ce&&f.data.metadata.resolvedTrigger==="create-epic"||ne||Ie||Ue||me||Xe||yt||at||It||Et){if(!$e&&!Ue&&!me&&!Xe&&!ne&&!yt&&!at&&!It&&!Et&&typeof f.data.metadata.storyId!="string")throw new Error("private-execution-descriptor-unavailable")}else throw new Error("private-execution-descriptor-unavailable");if(B){const{ensurePrivateYoloIsolatedSession:ae,reconcilePrivateYoloIsolatedSession:le}=await import("../private-execution/isolated-session.js");if(bt?.action==="checkpoint-epic-story")await le(s,Ze,ie.graphRevision);else{const W=await ae(s,Ze,ie.graphRevision,e.privateExecutionWorkspaceParent),M=await m(W.workspace.workspacePath);if(M.hostVersion!==K.hostVersion)throw new Error("private-codex-version-drift");K=M}}if(Date.now()-K.observedAtMs>2e4){const ae=await m(K.projectRoot);if(ae.hostVersion!==K.hostVersion)throw new Error("private-codex-version-drift");K=ae}const yr=await J.client.getToken();if(!yr)throw new Error("private-execution-auth-unavailable");const He=$e?f.data.metadata.epicClaim:void 0;if($e&&(!He||typeof He.claimId!="string"||typeof He.epicId!="string"))throw new Error("private-execution-descriptor-unavailable");if($e){if(!Pe)throw new Error("private-execution-epic-claim-admission-unverified");I.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>ei(s,Pe.fingerprint,He.claimId,He.epicId,U?"root-staged-v1":void 0),()=>{}),gr=!0;const{preparePrivateYoloIsolatedWorkspace:ae,PRIVATE_EPIC_PENDING_SIDECAR:le}=await import("../private-execution/isolated-workspace.js"),W=e.privateExecutionWorkspaceParent??z(Kt(),".local","share","neocortex","private-epic-workspaces");e.privateExecutionWorkspaceParent||qt(W,{recursive:!0,mode:448}),At=ae(s,W,!0),kn=Ne("sha256").update(Fe(z(s,le))).digest("hex");const M=await m(At.workspacePath);if(M.hostVersion!==K.hostVersion)throw new Error("private-codex-version-drift");K=M}else if(!B&&!ne){const{preparePrivateYoloIsolatedWorkspace:ae}=await import("../private-execution/isolated-workspace.js"),le=e.privateExecutionWorkspaceParent??z(Kt(),".local","share","neocortex","private-step-workspaces");if(e.privateExecutionWorkspaceParent||qt(le,{recursive:!0,mode:448}),se=ae(s,le,Ue||me),Xe||yt||at||It||Et){if(!pe)throw new Error("private-execution-project-snapshot-unverified");const{assertPrivateProjectStepBaseline:M}=await import("../private-execution/isolated-workspace.js");M(se,pe)}const W=await m(se.workspacePath);if(W.hostVersion!==K.hostVersion)throw new Error("private-codex-version-drift");K=W}const ot=await c(f.data.metadata.privateExecution,{projectId:Te,commandId:B?"yolo":ce?"create-epic":yt?Ce:at?"generate-pacts":It?"arch-ux-design":Et?"property-test":Xe?Pn:f.data.metadata.mode==="pipeline"?"exec":f.data.metadata.resolvedTrigger,stepId:f.data.metadata.stepId,...B?{graphRevision:ie.graphRevision}:{...$e?{claimId:He.claimId,epicId:He.epicId,...Ie?{writeSetId:"idea-diagnosis-v1"}:{}}:Ue?{claimId:ve.claimId,epicId:ve.epicId,diagnosisReceiptId:ve.diagnosisReceiptId,intakeRevision:ve.intakeRevision,physicalAcceptanceReceiptId:ve.physicalAcceptanceReceiptId,writeSetId:"idea-research-v1"}:me?{claimId:he.claimId,epicId:he.epicId,diagnosisReceiptId:he.diagnosisReceiptId,researchReceiptId:he.researchReceiptId,intakeRevision:he.intakeRevision,physicalAcceptanceReceiptId:he.physicalAcceptanceReceiptId,writeSetId:"generate-epic-v1"}:Xe?{writeSetId:fr}:ne?{format:o.selection.uiUxReview?.json===!0?"json":"markdown"}:yt?{targetEpicId:on,graphRevision:cn,writeSetId:Tn}:at?{targetEpicId:ye.targetEpicId,graphRevision:ye.graphRevision,answersSha256:ye.answersSha256,specSha256:ye.specSha256,pathsSha256:ye.pathsSha256,endpointCount:ye.endpointCount,pathCount:ye.pathCount}:It?{targetEpicId:ee.targetEpicId,graphRevision:ee.graphRevision,adapterId:ee.adapterId,authoritySha256:ee.authoritySha256,pathsSha256:ee.pathsSha256,screenCount:ee.screenCount,pathCount:ee.pathCount}:Et?{prdPath:ke.prdPath,prdSha256:ke.prdSha256,planSha256:ke.planSha256,pathsSha256:ke.pathsSha256,aggregateCount:ke.aggregateCount,invariantCount:ke.invariantCount,pathCount:ke.pathCount,language:ke.language,numRuns:ke.numRuns}:{storyId:f.data.metadata.storyId},stateSnapshotSha256:p(O)},inputSha256:n.sha256,hostKind:"codex-cli",hostVersion:K.hostVersion},ae=>hs(j,{...ae},yr));if(ne){const{parsePrivateExecutionDescriptor:ae}=await import("../private-execution/delivery.js"),le=ae(f.data.metadata.privateExecution);if(le.schemaVersion!==11||le.binding.commandId!=="ui-ux-review"||le.binding.format!==(o.selection.uiUxReview?.json===!0?"json":"markdown"))throw new Error("private-execution-report-binding-unverified");const{storePrivateUiUxReviewReport:W}=await import("../private-execution/private-report-store.js");te={schemaVersion:1,outcome:"report-stored",report:await W({projectRoot:s,material:ot,format:le.binding.format,sha256:le.materialSha256}),publicSafe:!0}}else if(bt?.action==="checkpoint-epic-story"){const{runPrivateYoloRootCheckpoint:ae}=await import("../private-execution/root-checkpoint.js");te={...await ae(s,bt)}}else{const ae=Ie?`${ot}
|
|
101
101
|
|
|
102
102
|
Private P01 handoff (local only):
|
|
103
|
-
The durable reserved epic ID is ${
|
|
104
|
-
`:
|
|
103
|
+
The durable reserved epic ID is ${He.epicId}. Complete only the diagnosis for this exact ID. Write exactly .neocortex/planning/epic-${He.epicId}/idea.json, diagnosis.md, enriched-prompt.md and the matching entry in .neocortex/planning/planning.json. Do not write state.json, Git controls, another epic, or P02/P03 artifacts; do not auto-continue to the next step. The root will independently review and persist the accepted planning checkpoint.
|
|
104
|
+
`:Ue?`${ot}
|
|
105
105
|
|
|
106
106
|
Private P02 handoff (local only):
|
|
107
|
-
The admitted epic is ${
|
|
108
|
-
`:me?`${
|
|
107
|
+
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?`${ot}
|
|
109
109
|
|
|
110
110
|
Private P03 handoff (local only):
|
|
111
|
-
The admitted epic is ${
|
|
112
|
-
`:
|
|
111
|
+
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(ot,Ce,Tn,Er(O.archPlan?.execution?.nonUiScopeReceipt)?"non-ui":"all"):at?`${ot}
|
|
113
113
|
|
|
114
114
|
Private A03.5 handoff (local only):
|
|
115
|
-
${JSON.stringify({consumer:
|
|
115
|
+
${JSON.stringify({consumer:oe.answers.consumer,provider:oe.answers.provider,matchersAggressive:oe.answers.matchersAggressive,generateProvider:oe.answers.generateProvider,brokerConfigured:oe.answers.brokerUrl!==null,allowedPaths:ge.paths})}
|
|
116
116
|
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
|
-
`:
|
|
117
|
+
`:It?`${ot}
|
|
118
118
|
|
|
119
119
|
Private A08 handoff (local only):
|
|
120
|
-
${JSON.stringify({targetEpicId:
|
|
120
|
+
${JSON.stringify({targetEpicId:ee.targetEpicId,graphRevision:ee.graphRevision,adapterId:ee.adapterId,approvedScreens:Ve.screens,allowedPaths:Ve.paths})}
|
|
121
121
|
Write only the approved paths. Keep synthetic fixtures and the canonical approved-story manifest. No Git, graph, QA or configuration effects.
|
|
122
|
-
`:
|
|
122
|
+
`:Et?`${ot}
|
|
123
123
|
|
|
124
124
|
Private property-test handoff (local only):
|
|
125
|
-
${JSON.stringify({language:
|
|
125
|
+
${JSON.stringify({language:ze.language,numRuns:ze.numRuns,aggregates:ze.aggregates.map(M=>({name:M.name,implementationFile:M.implementationFile,testFile:M.testFile,invariantCount:M.invariantCount}))})}
|
|
126
126
|
Read the PRD and implementation files inside this isolated clone. Write exactly the listed test files. Do not edit the PRD, state, Git, QA records or any other path. Scaffolds with unfinished assertions must fail explicitly; do not use skipped or todo tests. The root will write the confirmed PRD configuration and independently assess QA.
|
|
127
|
-
`:
|
|
127
|
+
`:ot;let le=ae;if(B){const{readPrivateYoloFrozenWriteSet:M}=await import("../private-execution/clean-baseline.js"),{appendPrivateYoloFrozenHandoff:T}=await import("../private-execution/frozen-handoff.js"),Oe=await M(s,Ze,ie.executionBranch,ie.graphRevision);le=T(ae,Oe);const{resumePrivateYoloIsolatedSession:St}=await import("../private-execution/isolated-session.js"),We=await St(s,Ze,ie.graphRevision),we=Cn(s,{epicAware:!0}).stories[Ze],Ae=O.stories[Ze];if(!we||!Ae||we.status!==Ae.status||JSON.stringify(we.steps_completed)!==JSON.stringify(Ae.steps_completed))throw new Error("private-execution-phase-snapshot-drift");const ct=Ge("git",["rev-parse","HEAD"],{cwd:s,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();le+=`
|
|
128
128
|
Root physical dispatch observations (data, not phase completion):
|
|
129
|
-
`+JSON.stringify({storyId:
|
|
129
|
+
`+JSON.stringify({storyId:Ze,graphRevision:ie.graphRevision,sourceHeadSha:ct,privateSnapshotSha:We.snapshotSha,effectiveStatus:we.status,hostKind:"codex-cli",hostVersion:K.hostVersion})+`
|
|
130
130
|
Use these observed revisions and runtime facts; do not infer Git metadata or substitute an invented revision.
|
|
131
|
-
`}const
|
|
131
|
+
`}const W=await A(le,K,{requireWorkspaceEffect:!0,...e.onPrivateExecutionWorkspaceFailure===void 0?{}:{onWorkspaceEffectFailure:e.onPrivateExecutionWorkspaceFailure},...e.privateExecutionModel===void 0?{}:{model:e.privateExecutionModel},...B?{expectedExecutionBranch:ie.executionBranch}:At?{expectedExecutionBranch:At.executionBranch}:se?{expectedExecutionBranch:se.executionBranch}:{}});if(B){const{admitPrivateYoloIsolatedSessionStep:M}=await import("../private-execution/isolated-session.js"),T=await M(s,Ze,ie.graphRevision);let Oe;if(f.data.metadata.stepId===ra){const We=f.data.metadata.mutationQaFeature;if(!We)throw new Error("private-execution-mutation-qa-authority-unavailable");if(!We.enabled)Oe={schemaVersion:1,status:"skipped-server-authority",publicSafe:!0};else{let we,Ae;try{const ct=T.session.workspace.workspacePath,Mt=`sha:${T.session.workspace.baseSha}`,{planMutationQa:sn}=await import("./mutation-qa.js"),xt=sn(ct,Mt);if(xt.headSha!==T.session.snapshotSha)throw new Error("private-execution-mutation-qa-snapshot-drift");let Tt="not-run";if(xt.outcome==="ready"){const{runAndRecordMutationQa:Nn}=await import("./mutation-qa-checkpoint.js");if(Tt=Nn(ct,Mt,xt.planSha256).result.outcome,Tt==="skipped-host-isolation-unavailable")throw new Error("private-execution-mutation-qa-host-isolation-unavailable")}const{classifyMutationQaGate:On}=await import("./mutation-qa-gate.js");if(we=On(ct,Mt,xt.planSha256),we.followUpDebtRequired){const{recordMutationQaFollowUpDebt:Nn}=await import("./mutation-qa-checkpoint.js");Ae=Nn(ct,Mt,xt.planSha256,we.status,Tt,s)}const{resumePrivateYoloIsolatedSession:Yi}=await import("../private-execution/isolated-session.js");if((await Yi(s,Ze,ie.graphRevision)).snapshotSha!==T.session.snapshotSha)throw new Error("private-execution-mutation-qa-snapshot-drift")}catch{throw new Error("private-execution-mutation-qa-unverified")}if(we.blocksLocalQa||!we.safeToContinueLocalQa&&!Ae)throw new Error(`private-execution-mutation-qa-${we.status}`);Oe={...we,...Ae?{followUpDebt:{status:"recorded",owner:Ae.owner,severity:Ae.severity,reasonCode:Ae.reasonCode,planSha256:Ae.planSha256,publicSafe:!0}}:{}}}}const St={schemaVersion:1,outcome:T.admission.outcome,sequence:T.session.sequence,snapshotSha:T.session.snapshotSha,patchSha256:T.admission.patchSha256,changedPathCount:T.admission.changedPaths.length};te={...W,isolation:St,...Oe?{mutationQa:Oe}:{}}}else if(At){const{admitPrivateEpicClaimWorkspace:M,admitPrivateIdeaDiagnosisWorkspace:T}=await import("../private-execution/isolated-admission.js"),Oe=Ie?T(At,He.claimId,He.epicId,Pe.fingerprint,kn,o.selection.positionals.join(" ").replace(/^[-:–—]\s+/,"")):M(At,He.claimId,He.epicId,Pe.fingerprint,kn);te={...W,isolation:{schemaVersion:1,outcome:Oe.outcome,baseSha:Oe.baseSha,patchSha256:Oe.patchSha256,changedPathCount:Oe.changedPaths.length}}}else if(se&&Ue){const{admitPrivateIdeaResearchWorkspace:M}=await import("../private-execution/isolated-admission.js"),T=M(se,ve.claimId,ve.epicId,ve.diagnosisReceiptId,ve.intakeRevision,ve.sourceStateSha256);te={...W,isolation:{schemaVersion:1,outcome:T.outcome,baseSha:T.baseSha,patchSha256:T.patchSha256,changedPathCount:T.changedPaths.length}}}else if(se&&me){const{admitPrivateGenerateEpicWorkspace:M}=await import("../private-execution/isolated-admission.js"),T=M(se,he.claimId,he.epicId,he.diagnosisReceiptId,he.researchReceiptId,he.intakeRevision,he.sourceStateSha256);te={...W,isolation:{schemaVersion:1,outcome:T.outcome,baseSha:T.baseSha,patchSha256:T.patchSha256,changedPathCount:T.changedPaths.length}}}else if(se&&at){const{admitPrivatePactWorkspace:M}=await import("../private-execution/isolated-admission.js"),{inspectPactToolchain:T}=await import("../private-execution/pact-toolchain.js"),{verifyPactConsumerRuntime:Oe}=await import("../private-execution/pact-consumer-runtime.js"),St=oe.answers.generateProvider,We=M(se,ye.targetEpicId,ye.graphRevision,oe.receipt,ge,mr),we=T(s,St),Ae=Oe(s,ge,St);te={...W,isolation:{schemaVersion:1,outcome:We.outcome,baseSha:We.baseSha,patchSha256:We.patchSha256,changedPathCount:We.changedPaths.length,consumerBindingCandidateCount:We.consumerBindingCandidateCount,consumerScaffoldCount:We.consumerScaffoldCount,toolchain:we,consumerRuntime:Ae}}}else if(se&&It){const{admitPrivateUxWorkspace:M}=await import("../private-execution/isolated-admission.js"),T=M(se,ee.targetEpicId,ee.graphRevision,Ve);te={...W,isolation:{schemaVersion:1,outcome:T.outcome,baseSha:T.baseSha,patchSha256:T.patchSha256,changedPathCount:T.changedPaths.length}}}else if(se&&Et){const{admitPrivatePropertyTestWorkspace:M}=await import("../private-execution/isolated-admission.js"),T=M(se,mt,ze);te={...W,isolation:{schemaVersion:1,outcome:T.outcome,baseSha:T.baseSha,patchSha256:T.patchSha256,changedPathCount:T.changedPaths.length,checkpointAccepted:!1,qaAccepted:!1,rootNextAction:"property-semantic-review-required"}}}else if(se&&yt){const{admitPrivateArchitectureStageWorkspace:M}=await import("../private-execution/isolated-admission.js"),T=M(se,Ce,Tn,on,cn);te={...W,isolation:{schemaVersion:1,outcome:T.outcome,baseSha:T.baseSha,patchSha256:T.patchSha256,changedPathCount:T.changedPaths.length}}}else if(se&&Xe){const{admitPrivateProjectStepWorkspace:M}=await import("../private-execution/isolated-admission.js"),T=M(se,Pn,fr);te={...W,isolation:{schemaVersion:1,outcome:T.outcome,baseSha:T.baseSha,patchSha256:T.patchSha256,changedPathCount:T.changedPaths.length}}}else if(se){const{admitPrivateStateBoundStepWorkspace:M}=await import("../private-execution/isolated-admission.js"),T=M(se,f.data.metadata.storyId);te={...W,isolation:{schemaVersion:1,outcome:T.outcome,baseSha:T.baseSha,patchSha256:T.patchSha256,changedPathCount:T.changedPaths.length}}}else te={...W}}}catch(c){const p=c instanceof Error&&/^(private-execution|private-codex)-[a-z-]+$/.test(c.message)?c.message:"private-execution-unverified";return{success:!1,error:p,errorCode:p,exitCode:1}}let xn;if(rn&&g(f.data.metadata.planningRootContinuation)&&f.data.metadata.planningRootContinuation.planningComplete===!0)try{if(!_e?.claimId||!_e.epicId||!Te)throw new Error("missing-reservation");const c=_r(s,_e.claimId,_e.epicId);if(f.data.metadata.planningRootContinuation.memoryReceiptId!==c.receiptId)throw new Error("memory-receipt-conflict");const p=Cn(s,{verifyPlanningGeneration:!0}),m=p.epics[_e.epicId];if(!g(m?.createEpicPlanningMemoryPhysical)||m.createEpicPlanningMemoryPhysical.receiptId!==c.receiptId)throw new Error("memory-recheck-failed");const A={config:{project_id:Te},epics:{[_e.epicId]:m},stories:Object.fromEntries((Array.isArray(m.stories)?m.stories:[]).map(ne=>[ne,p.stories[ne]])),epic_id_ledger:p.epic_id_ledger};if(!await I.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Li(j,J.token,{claimId:_e.claimId,projectId:Te,epicId:_e.epicId,status:"materialized",planningCheckpoint:{memoryReceiptId:c.receiptId,snapshot:A}},{refreshToken:()=>J.client.forceRefresh()}),async()=>!1))throw new Error("acknowledgement-unavailable");xn={schemaVersion:1,acknowledged:!0,claimId:c.claimId,epicId:c.epicId,memoryReceiptId:c.receiptId,publicSafe:!0}}catch{return{success:!1,error:"planning-root-materialization-unavailable",errorCode:"planning-root-materialization-unavailable",exitCode:1}}const an=yn(f.data.instructions,{...f.data.metadata,...f.compatibility?{compatibility:f.compatibility}:{}}),Dt=te?.isolation,Fi=an.metadata?.resolvedTrigger==="property-test"&&Dt!==null&&typeof Dt=="object"&&!Array.isArray(Dt)&&Dt.outcome==="admitted-unverified"&&Dt.checkpointAccepted===!1&&Dt.rootNextAction==="property-semantic-review-required";if(Pe&&!gr&&!rn&&f.data.metadata?.mode!=="error")try{const c=f.data.metadata?.epicClaim;if(!c||typeof c!="object"||Array.isArray(c))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const p=c;if(p.outcome!=="reserved"||typeof p.claimId!="string"||typeof p.epicId!="string")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");I.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>ei(s,Pe.fingerprint,p.claimId,p.epicId),()=>{})}catch{}return I.complete(nn),{success:!0,instructions:te?te.outcome==="checkpoint-validated"?`# Checkpoint da story validado
|
|
132
132
|
|
|
133
|
-
O root registrou o commit e a valida\xE7\xE3o f\xEDsica no branch do epic.`:
|
|
133
|
+
O root registrou o commit e a valida\xE7\xE3o f\xEDsica no branch do epic.`:te.outcome==="setup-accepted"?`# Setup do branch validado
|
|
134
134
|
|
|
135
|
-
O root confirmou o checkpoint C01 no branch do \xE9pico. Reexecute o mesmo YOLO para avan\xE7ar \xE0 pr\xF3xima etapa.`:
|
|
135
|
+
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
136
|
|
|
137
|
-
Consulte o caminho local em metadata.privateExecutionReceipt.report.path. Nenhum agente foi executado ou projeto alterado.`:
|
|
137
|
+
Consulte o caminho local em metadata.privateExecutionReceipt.report.path. Nenhum agente foi executado ou projeto alterado.`:Fi?"# Property-test: candidato admitido, QA pendente\n\nO root deve inspecionar os arquivos locais, executar `neocortex-client property-qa review-plan --project-root . --format json` e comparar cada invariante do PRD com a implementa\xE7\xE3o e sua asser\xE7\xE3o. Somente uma revis\xE3o root independente, registrada fora do projeto e enviada por stdin a `property-qa review-accept --authorize-review`, pode autorizar o aceite; esse comando repete a execu\xE7\xE3o positiva e a falha causal no sandbox. Consulte `property-qa review-status` para revalidar o recibo. Se o toolchain ou a evid\xEAncia n\xE3o forem suportados, pare sem declarar QA aprovado. O agente privado n\xE3o recebe autoridade de revis\xE3o, Git ou checkpoint.":`# Execu\xE7\xE3o privada conclu\xEDda; valida\xE7\xE3o f\xEDsica pendente
|
|
138
138
|
|
|
139
|
-
O executor Codex retornou sem erro. Nenhum checkpoint ou aprova\xE7\xE3o da story foi emitido.`:an.instructions,metadata:
|
|
139
|
+
O executor Codex retornou sem erro. Nenhum checkpoint ou aprova\xE7\xE3o da story foi emitido.`:an.instructions,metadata:te?{...an.metadata,privateExecutionReceipt:te}:{...an.metadata,...xn?{planningMaterialization:xn}:{}},exitCode:0}}function bs(e){const[t]=e.trim().split(/\s+/,1);return t?/^@?epic-[a-z0-9][a-z0-9._-]*$/i.test(t)?"epic":un(t):null}const Hi="Provide exactly one invoke input source: --args <string>, --stdin, or --args-file <path>.",xs=`
|
|
140
140
|
neocortex-client invoke - Send orchestration request to server
|
|
141
141
|
|
|
142
142
|
Usage:
|
|
@@ -207,12 +207,12 @@ Safety:
|
|
|
207
207
|
Jobs console is Plane B/local-only: no hosted server call for raw output, no server-held stream, no raw persistence, and stdin requires explicit local confirmation.
|
|
208
208
|
Jobs, goal and loop watch use serverHeldStream=false and foreground local SQLite polling of public processing summaries only.
|
|
209
209
|
Unresolved targets disable polling with public reason codes; there is no all-jobs fallback.
|
|
210
|
-
`.trim();function
|
|
210
|
+
`.trim();function Ts(e){return e.includes("--help")||e.includes("-h")||e.includes("help")}function je(e,t,i,r){return new In("INVOCATION_MALFORMED_INPUT",t,e,i,r)}function Ot(e){return je("missing-input-value",`${e} requires a value. ${Hi}`)}function Ps(e){try{if(!Qi(e).isFile())throw je("missing-input-value","--args-file must point to a readable UTF-8 text file.","args-file");return Fe(e)}catch(t){throw t instanceof In?t:je("missing-input-value","--args-file could not be read as UTF-8 text. Check the path and permissions.","args-file")}}function ks(){try{if(process.stdin.isTTY)throw je("missing-input-value","--stdin requires piped UTF-8 text, for example: neocortex-client invoke --stdin < synthetic.story.md","stdin");return Fe(0)}catch(e){throw e instanceof In?e:je("missing-input-value","--stdin could not be read as UTF-8 text. Pipe command text into stdin and retry.","stdin")}}function Os(e,t={}){let i,r=!1,a,n,o="plain",d=!1,s,l,y=!1,S=!1,u;for(let P=0;P<e.length;P++){const k=e[P];switch(k){case"--args":{const R=e[++P];if(R===void 0)throw Ot("--args");if(i!==void 0)throw je("multiple-input-sources","Provide --args only once. Use one explicit invoke input source.","args");i=R;break}case"--stdin":if(r)throw je("multiple-input-sources","Provide --stdin only once. Use one explicit invoke input source.","stdin");r=!0;break;case"--args-file":{const R=e[++P];if(R===void 0)throw Ot("--args-file");if(a!==void 0)throw je("multiple-input-sources","Provide --args-file only once. Use one explicit invoke input source.","args-file");a=R;break}case"--project-root":{const R=e[++P];if(R===void 0)throw Ot("--project-root");n=R;break}case"--format":{const R=e[++P];if(R===void 0)throw Ot("--format");if(R!=="json"&&R!=="plain")throw je("unexpected-cli-token","--format accepts only json or plain.");o=R;break}case"--watch":d=!0;break;case"--server-url":{const R=e[++P];if(R===void 0)throw Ot("--server-url");s=R;break}case"--platform-target":{const R=e[++P];if(R===void 0)throw Ot("--platform-target");l=R;break}case"--strict-read-only":y=!0;break;case"--private-execution-beta":S=!0;break;case"--private-execution-model":{const R=e[++P];if(R===void 0)throw Ot("--private-execution-model");if(u!==void 0||!/^gpt-[a-z0-9][a-z0-9.-]{0,63}$/.test(R))throw je("unexpected-cli-token","Invalid or duplicate private execution model.");u=R;break}default:if(i!==void 0&&k&&(!k.startsWith("-")||k==="-")){i+=` ${k}`;break}throw je("unexpected-cli-token","Unexpected top-level CLI token. Quote the complete --args payload or use --stdin/--args-file for multiline content.")}}if(u!==void 0&&(!S||y))throw je("unexpected-cli-token","A private execution model requires private beta without strict read-only.");const C=[i!==void 0?"args":void 0,r?"stdin":void 0,a!==void 0?"args-file":void 0].filter(P=>P!==void 0);if(C.length===0)throw je("missing-input-value",Hi);if(C.length>1)throw je("multiple-input-sources",`Choose only one invoke input source; received ${C.join(", ")}.`);const E=C[0],h=E==="args"?i:E==="stdin"?(t.readStdin??ks)():(t.readArgsFile??Ps)(a);let I;try{I=Qt(E,h)}catch(P){throw P instanceof qa?je("invalid-utf8",P.message,E):P}const b=E==="args"?ts(I.rawArgs):Me(I.rawArgs),D=b.args===I.rawArgs?I:Qt(E,b.args);return{args:b.args,inputSource:E,inputEnvelope:D,projectRoot:n,format:o,watch:d||b.watch,commandLevelWatch:b.metadata,serverUrl:s,platformTarget:l,strictReadOnly:y,privateExecutionBeta:S,...u===void 0?{}:{privateExecutionModel:u}}}function Wi(e,t){return t?.active?{...e??{},commandLevelWatch:t,serverHeldStream:!1}:e}function Gi(e,t,i=process.stdout,r=process.stderr){if(t.format==="json"){const o=yn(e.instructions,e.metadata),d=Wi(o.metadata,t.commandLevelWatch);if(t.watch){i.write(JSON.stringify({type:"invoke_result",instructions:o.instructions,metadata:d,publicSafe:!0})+`
|
|
211
211
|
`);return}i.write(JSON.stringify({instructions:o.instructions,metadata:d})+`
|
|
212
|
-
`);return}const a=
|
|
212
|
+
`);return}const a=yn(e.instructions,e.metadata),n=Wi(a.metadata,t.commandLevelWatch);i.write(a.instructions+`
|
|
213
213
|
`),n&&r.write(JSON.stringify(n)+`
|
|
214
|
-
`)}async function
|
|
215
|
-
`),0;let t;try{t=
|
|
216
|
-
`),1;throw r}if(
|
|
217
|
-
`),1):(await
|
|
218
|
-
`),i.exitCode}if(
|
|
214
|
+
`)}async function Wd(e=process.stdout,t=process.stderr){const i=a=>new Promise(n=>{let o=!1;const d=y=>{o||(o=!0,clearTimeout(l),setImmediate(()=>a.removeListener("error",s)),n(y))},s=()=>d(!1),l=setTimeout(()=>d(!1),1e4);a.once("error",s);try{a.write("",y=>d(!y))}catch{d(!1)}});return(await Promise.all([i(e),i(t)])).every(Boolean)}function Ns(e){const t=()=>e.abort();return process.once("SIGINT",t),process.once("SIGTERM",t),()=>{process.removeListener("SIGINT",t),process.removeListener("SIGTERM",t)}}async function Gd(e){if(Ts(e))return process.stdout.write(`${xs}
|
|
215
|
+
`),0;let t;try{t=Os(e)}catch(r){if(r instanceof In)return process.stderr.write(JSON.stringify({error_code:r.code,reason:r.reason,source:r.source,byte_length:r.byteLength,message:r.message,remediation:r.message})+`
|
|
216
|
+
`),1;throw r}if(xa(t.args))return t.strictReadOnly?(process.stderr.write(JSON.stringify({error_code:"readonly-registry-denied",message:"Strict read-only policy is not eligible for the local jobs console."})+`
|
|
217
|
+
`),1):(await Ta({args:t.args,projectRoot:Fn(t.projectRoot),format:t.format,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})).exitCode;const i=await As({args:t.args,inputSource:t.inputSource,inputEnvelope:t.inputEnvelope,watch:t.watch,projectRoot:t.projectRoot,format:t.format,serverUrl:t.serverUrl,platformTarget:t.platformTarget,strictReadOnly:t.strictReadOnly,privateExecutionBeta:t.privateExecutionBeta,...t.privateExecutionModel===void 0?{}:{privateExecutionModel:t.privateExecutionModel}});if(!i.success&&i.errorCode==="YOLOOP_RELEASE_BLOCKED"&&i.instructions&&i.metadata)return Gi(i,t),i.exitCode;if(!i.success){const r=i.metadata?.invocationInput,a=Go(i.metadata?.yoloChangeEvidence),n=r&&typeof r=="object"&&!Array.isArray(r)?r:void 0;return process.stderr.write(JSON.stringify({error_code:i.errorCode??(i.exitCode===2?"NOT_CONFIGURED":"INVOKE_ERROR"),message:Je(i.error??"",kt),...typeof n?.reason=="string"?{reason:Je(n.reason,80)}:{},...typeof n?.source=="string"?{source:Je(n.source,20)}:{},...Number.isSafeInteger(n?.byteLength)?{byte_length:n.byteLength}:{},...typeof n?.remediation=="string"?{remediation:Je(n.remediation,kt)}:{},...a?{yolo_change_evidence:a}:{}})+`
|
|
218
|
+
`),i.exitCode}if(Gi(i,t),t.watch){const r=new AbortController,a=Ns(r);try{const n=us(i.metadata,t.args);n.disabled?Wc(n.reasonCodes??[Re.TARGET_UNRESOLVED],t.args,t.format,process.stdout,t.privateExecutionBeta):await Gc({projectRoot:Fn(t.projectRoot),format:t.format,strictReadOnly:t.strictReadOnly,protectedOutput:t.privateExecutionBeta,...n,signal:r.signal})}finally{a()}}return 0}export{xs as INVOKE_HELP_TEXT,Jr as INVOKE_PAYLOAD_LIMIT_BYTES,Wn as INVOKE_PAYLOAD_WARNING_THRESHOLD_BYTES,In as InvokeCliInputError,zn as InvokePayloadTooLargeError,Jn as InvokeStructuralContextTooLargeError,Ui as STORY_WORKTREE_BARRIER_CLIENT_MAX_ATTEMPTS,Bi as STORY_WORKTREE_BARRIER_CLIENT_MAX_WAIT_MS,lt as StateSnapshotIntegrityError,$d as __resetSchemaDriftWarnedForTests,fs as acknowledgeMaterializedPendingEpicClaims,ti as admitClientInvocation,Xn as assertEpicAwareStateShapeBeforeRepair,lc as boundedP222PremergeCheckpointPositions,qn as buildInvokeCompatibilityOffer,Cc as buildSignedInvokeAttempt,Lo as clearPendingEpicIdempotencyKey,hc as collectInvokeP205Authorities,Cn as collectStateSnapshot,Wt as computeInvokeRequestBodySizeBytes,Hd as createFullStateSnapshotScope,nr as createInvokePayloadTelemetry,Do as deriveYoloLogicalIdempotencyKey,Jo as detectStateSchemaDrift,bs as extractPreFlightTrigger,Wd as flushInvokeCliOutput,No as getOrCreatePendingEpicIdempotencyKey,rr as guardInvokeRequestBodySize,As as invoke,Gd as invokeCliHandler,uc as invokeP205ProjectionReasonCode,gi as isEpicAwareCommandId,Cs as isStoryWorktreePhaseOneInvocation,kc as maybeEmitInvokePayloadSizeWarning,Oc as maybeRunInvokeRunnerAutoBootstrap,Os as parseInvokeCliOptions,ws as persistStoryWorktreePhaseEvidence,_s as pollStoryWorktreeSpecBarrier,Ci as postMaterializationJson,jo as projectRegistryDriftInvokeFailure,Vo as projectReleaseBlockedInvokeResult,Go as projectYoloChangeEvidenceCliDiagnostic,Gr as publicYoloSpecEnvelopeErrorCode,Es as reconcileInvalidatedYoloopSession,ei as recordPendingEpicReservation,Bo as recoverClientInvocation,ts as resolveInvokeCommandLevelWatch,Fn as resolveInvokeProjectRoot,Ec as resolveInvokeTransportErrorCode,us as resolveInvokeWatchTarget,yn as sanitizeInvokeCliOutput,Li as sendEpicClaimAcknowledgement,lr as sendInvokeRequest,gs as sendPrivateExecutionCancelRequest,hs as sendPrivateExecutionConsumeRequest,Fo as shouldCollectProjectEvidenceForInvoke,Gc as watchContinuityProcessingSummaries,Gi as writeInvokeCliSuccessOutput};
|