@ornexus/neocortex 4.64.4 → 4.65.1
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 +7 -1
- package/install.sh +7 -1
- package/package.json +2 -2
- package/packages/client/dist/agent/claude-worktree-base.d.ts +18 -0
- package/packages/client/dist/agent/claude-worktree-base.js +1 -0
- package/packages/client/dist/agent/refresh-stubs.js +2 -2
- package/packages/client/dist/commands/doctor.d.ts +4 -0
- package/packages/client/dist/commands/doctor.js +2 -2
- package/packages/client/dist/commands/invoke.js +79 -77
- package/packages/client/dist/git/story-worktree-cleanup.d.ts +44 -1
- package/packages/client/dist/git/story-worktree-cleanup.js +4 -4
- package/packages/client/dist/state/project-state-snapshot.js +1 -1
- package/targets-stubs/antigravity/gemini.md +1 -1
- package/targets-stubs/antigravity/skill/SKILL.md +1 -1
- package/targets-stubs/claude-code/README.md +6 -3
- package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex-root.md +2 -2
- package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex.md +2 -2
- package/targets-stubs/codex/AGENTS.md +1 -1
- package/targets-stubs/cursor/agent.md +2 -2
- package/targets-stubs/gemini-cli/agent.md +2 -2
- package/targets-stubs/lib/claude-worktree-setting.js +87 -0
- package/targets-stubs/lib/managed-config-merge.js +4 -0
- package/targets-stubs/opencode/neocortex-root.md +1 -1
- package/targets-stubs/vscode/neocortex.agent.md +2 -2
|
@@ -1,59 +1,61 @@
|
|
|
1
|
-
import{classifyNonUiArchitectureTransition as zi,architectureMemoryPredecessorCount as Ir}from"./architecture-non-ui-continuation.js";import{parseArchitectureNonUiScopeReceipt as Sr}from"./shared-architecture-non-ui.js";import{createHash as Ne,randomUUID as pn}from"node:crypto";import{loadPactAnswerReceipt as vr,loadPactPrivateAnswers as Ji}from"./architecture-answers.js";import{acceptedArchitectureTerminalMemoryReceipt as Ft,deriveArchitectureTerminalMemoryReceipt as Dn}from"./architecture-memory-terminal.js";import{deriveCommittedArchitectureEpicGraphRevision as Yt,explicitArchitectureEpicTarget as Ki}from"./architecture-root-binding.js";import{derivePactWriteSet as Qi}from"../private-execution/pact-write-set.js";import{execFileSync as Be}from"node:child_process";import{existsSync as jt,readFileSync as Fe,renameSync as Cr,unlinkSync as Mn,writeFileSync as ln,mkdirSync as qt,statSync as Xi,openSync as zt,closeSync as Jt,fsyncSync as un,realpathSync as Zi,lstatSync as Vt}from"node:fs";import{isDeepStrictEqual as C}from"node:util";import{join as z,isAbsolute as eo,resolve as jn}from"node:path";import{homedir as Kt}from"node:os";import{probeYoloopHostCapacity as to}from"../runner/host-capacity.js";import{isPrivateExecutionPublicEnvelope as no,isPrivatePlanningRootPublicEnvelope as ro,PRIVATE_MUTATION_QA_GATE_STEP_TOKEN as io}from"../private-execution/delivery.js";import{acceptedPlanningDiagnosisPredecessor as _r}from"../private-execution/planning-diagnosis-checkpoint.js";import{acceptedPlanningResearchPredecessor as Rr}from"../private-execution/planning-research-checkpoint.js";import{verifyCommittedPlanningMemory as wr}from"../private-execution/planning-memory-checkpoint.js";import{verifyCommittedPlanningGeneration as oo}from"../private-execution/planning-generation-checkpoint.js";import{PLANNING_RAW_INTENT_MAX_CHARS as ao}from"../../../shared/dist/planning/diagnosis-state.js";import{applyCrossEpicContinuationReconciliation as co,buildCrossEpicContinuationPayloadHash as so,classifyCrossEpicContinuationReconciliation as po,epicOperationalHash as vt,readEpicOperationalState as Ar}from"../git/epic-operational-state.js";import{LicenseClient as lo}from"../license/license-client.js";import{EncryptedCache as Vn}from"../cache/encrypted-cache.js";import{NoOpCache as br}from"../types/index.js";import{resolveClientPreFlightTrigger as hn,TierAwareClient as uo}from"../tier/tier-aware-client.js";import{COMMAND_REGISTRY_CHECKSUM as st,COMMAND_REGISTRY_VERSION as dt,GENERATED_CLIENT_COMMANDS as ho}from"../generated/command-registry.generated.js";import{loadSecureConfig as Bn}from"../config/secure-config.js";import{neocortexProfileDirectory as go}from"../config/profile-directory.js";import{DEFAULT_SERVER_URL as fo}from"../constants.js";import{detectFirstRunLocale as mo,renderFirstRunMessage as yo}from"../i18n/first-run.js";import{humanizeError as xr,formatHumanizedError as Tr,detectErrorLocale as Pr}from"../errors/error-messages.js";import{degradeStateSnapshotForPayloadLimit as Eo,projectStateSnapshotForInvoke as kr,projectStateSnapshotResultV2ForInvoke as Io}from"../state/project-state-snapshot.js";import{isInlineYoloMaterialization as Or,maybeRepairStateJsonBeforeInvoke as So,readStoryWorktreeRepairOverlay as vo,StateRepairHardStopError as Co}from"../state/state-json-repair.js";import{StructuralDagError as Nr}from"../state/structural-dag-projection.js";import{collectStateMigrationAuthority as _o,StateMigrationApplyError as Ro}from"../migrations/state-json.js";import{RUNNER_BOOTSTRAP_POLICY_REASON_CODES as wo,classifyRunnerBootstrapPolicyFromArgs as Ao}from"../continuity/runner-bootstrap-policy.js";import{RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES as bo,ensureRunnerSchedulerBootstrap as xo,observeRunnerOperationalStatus as To}from"../runner/scheduler.js";import{CONTINUITY_INVOKE_WATCH_DEFAULT_LIMIT as Lr,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_IDLE_POLLS as Dr,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_POLLS as Mr,CONTINUITY_INVOKE_WATCH_DEFAULT_POLL_INTERVAL_MS as jr,openContinuityClientStateStore as Po}from"../continuity/continuity-client-state-store.js";import{isLocalJobsConsoleArgs as ko,runLocalJobsConsoleCommand as Oo}from"../runner/local-console.js";import{detectNativeHostAttestation as No,detectPlatform as Lo}from"../adapters/platform-detector.js";import{signNxInvokeRequest as Do}from"../../../shared/dist/nx-invoke-signature.js";import{YOLO_INVOKE_ENVELOPE_CAPABILITY as Mo}from"../../../shared/dist/yolo/spec-envelope.js";import{parseReleaseBlockedResult as jo}from"../../../shared/dist/yoloop/release-blocked.js";import{CLIENT_VERSION as Pt}from"../version.js";import{createCapabilityCache as Vr,executeInvokeQueryTransport as Un,executeSecondaryNetworkMutation as Vo}from"../effects/invoke-effect-gateways.js";import{STRICT_READ_ONLY_POLICY as Bo,STRICT_READ_ONLY_CLIENT_PROJECTION as Br,STRICT_READ_ONLY_SERVER_PROJECTION as Uo,StrictReadOnlyError as Bt,canonicalizeInvokeEffects as $o,createInvokeEffectContext as Ho,verifyStrictReadOnlyReceipt as Wo}from"../../../shared/dist/strict-readonly.js";import{admitInvocation as Go,assertInvokeInputEnvelopeV2 as Fo,assertProjectIdentityMigrationReceiptV1 as Yo,buildProjectIdentityPublicDiagnostic as Ut,createInvocationAdmissionReceipt as qo,projectInvokeInputEvidenceV1 as $n,recoverExplicitInvocation as zo,verifyStrictDiagnoseReceiptV1 as Jo}from"../../../shared/dist/invocation/index.js";import{buildInvokeInputEnvelope as Qt,InvokeInputDecodeError as Ko}from"../invocation/invoke-input.js";import{COMPATIBILITY_REASON_CODES as $t,createCompatibilityOffer as Qo,createLegacyCompatibilityResult as Xo,isCompatibilityResultV1 as Zo}from"../../../shared/dist/compatibility/index.js";import{acknowledgeProjectIdentityMigration as ea,finalizeProjectIdentityMigration as ta,prepareProjectIdentityMigration as na,ProjectIdentityMigrationError as Hn,readProjectIdentityMigrationPhase as ra}from"../migrations/project-identity.js";import{probeProjectIdentityMigrationCapability as ia}from"../migrations/project-identity-capability.js";import{normalizeYoloopStoryPlanningEvidence as oa}from"../../../shared/dist/yoloop/planning-graph.js";import{normalizeContinuousWriteRef as gn}from"../../../shared/dist/yoloop/wave-decision-receipt.js";import{epicHeadReconciliationInputDigest as aa,epicHeadReconciliationPathsDigest as fn,epicHeadReconciliationRangeDigest as ca}from"../../../shared/dist/yoloop/epic-terminal-git.js";import{applyGitLifecycleRuntimeOverlay as Ur,classifyGitLifecycleStoryCheckpointProjectionSync as sa,ensureRuntimeEpic as da,ensureGitLifecycleRuntimeInitialized as pa,executeP205TransientAuthorities as la,isP226GateReasonCode as ua,persistGitLifecycleGraphAuthority as ha,P205_COMPLETE_COMMAND as Xt,gitLifecycleStoryWriteSet as $r,gitLifecycleStoryClaimCandidates as ga,gitLifecycleWriteSetCovers as fa,appendStoryWorktreeEvidence as ma,isStoryWorktreeEvidenceContainer as ya,mutateGitLifecycleRuntime as Hr,projectP205TransientExecutionEvidence as Ea,readGitLifecycleRuntimeSync as mn,verifyLegacyCheckpointMigrationCandidateSync as Ia}from"../git/git-lifecycle-store.js";import{verifyRootMemoryPhysicalWriteSet as Sa}from"../private-execution/root-memory-git-evidence.js";import{isRootProjectMemoryEffect as va}from"../private-execution/shared-root-memory-types.js";import{probeYoloInvokeEnvelopeCapability as Ca}from"../yolo/invoke-envelope-capability.js";import{attachProjectManifestProjection as _a}from"../yolo/project-manifest-projection-collector.js";import{collectYoloSpecEnvelope as Wr,extractTargetedYoloStoryId as Ra,refreshPrecollectedYoloSpecEnvelope as Gr}from"../yolo/spec-envelope-collector.js";import{FRONTMATTER_LIST_TOO_LONG_DIAGNOSTIC_PATTERN as wa}from"../errors/frontmatter-diagnostics.js";function Fr(e,t=!1){return e instanceof Error&&((t?/^yolo-(?:spec-envelope|change-evidence)-[a-z-]+$/:/^yolo-spec-envelope-[a-z-]+$/).test(e.message)||wa.test(e.message))?e.message:"yolo-spec-envelope-unsafe"}const yn=go(),Wn=z(yn,"cache"),Yr=z(Wn,"menu-cache.json"),qr=1440*60*1e3,zr=3e4,Jr=256*1024,Kr=Jr,Qr=.8,Ct="[REDACTED]",Aa=1e5,kt=2e3,ba=200,xa=200,Ta=12,Pa=/(?:promptBody|workflow|workflowGraph|stepBody|privateUrl|rawLog|secret|credential|licenseKey|apiKey|internalRouting|serverOnly|proprietary|protected)/i,ka=/(?:PRIVATE|PROTECTED|SERVER_ONLY)[-_\s]*(?:PROMPT|PROMPT_BODY|WORKFLOW|WORKFLOW_GRAPH|STEP_BODY|STEP|ROUTING)\s*[:=][^\n\r]*/gi,Oa=/(?:https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|private|internal)[^\s"'<>]*|raw[_-]?log|transcript|stack\s*trace|stderr:|stdout:|system prompt|prompt body|workflow body|step body|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|VENDOR_CORPUS|P180[_-]?SYNTHETIC[_-]?CONTINUITY|P185[_-]?SYNTHETIC[_-]?CONTINUITY|P187[_-]?SYNTHETIC[_-]?(?:CONTINUITY|RUNNER|WATCH)|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=)/gi,Gn=Math.floor(Jr*Qr),Xr=z(yn,".first-run-shown"),Na="pending-epic-claims.json",Zr=64;function ei(e){return z(e,".neocortex",Na)}function Ht(e){const t=ei(e);if(!jt(t))return{schemaVersion:1,operations:{}};const i=JSON.parse(Fe(t,"utf8"));if(!i||typeof i!="object"||Array.isArray(i))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const r=i;if(r.schemaVersion!==1||!r.operations||typeof r.operations!="object"||Array.isArray(r.operations))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(Object.keys(r.operations).length>Zr)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");for(const[o,n]of Object.entries(r.operations)){if(!/^[a-f0-9]{64}$/.test(o)||!n||typeof n!="object"||Array.isArray(n))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const a=n;if(a.planningProtocol!==void 0&&a.planningProtocol!=="root-staged-v1")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(typeof a.idempotencyKey!="string"||!/^[0-9a-f-]{36}$/.test(a.idempotencyKey)||typeof a.createdAt!="string")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(a.claimId!==void 0&&(typeof a.claimId!="string"||!/^[0-9a-f-]{36}$/.test(a.claimId))||a.epicId!==void 0&&(typeof a.epicId!="string"||!/^P[1-9][0-9]*$/.test(a.epicId))||a.claimId===void 0!=(a.epicId===void 0))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE")}return i}function Fn(e,t){const i=ei(e);qt(z(e,".neocortex"),{recursive:!0,mode:448});const r=`${i}.${process.pid}.${pn()}.tmp`;ln(r,`${JSON.stringify(t)}
|
|
2
|
-
`,{encoding:"utf8",mode:384,flag:"wx"}),Cr(
|
|
1
|
+
import{classifyNonUiArchitectureTransition as Ji,architectureMemoryPredecessorCount as Er}from"./architecture-non-ui-continuation.js";import{parseArchitectureNonUiScopeReceipt as Sr}from"./shared-architecture-non-ui.js";import{createHash as Ne,randomUUID as pn}from"node:crypto";import{loadPactAnswerReceipt as vr,loadPactPrivateAnswers as Ki}from"./architecture-answers.js";import{acceptedArchitectureTerminalMemoryReceipt as Ft,deriveArchitectureTerminalMemoryReceipt as Dn}from"./architecture-memory-terminal.js";import{deriveCommittedArchitectureEpicGraphRevision as Yt,explicitArchitectureEpicTarget as Qi}from"./architecture-root-binding.js";import{derivePactWriteSet as Xi}from"../private-execution/pact-write-set.js";import{execFileSync as Be}from"node:child_process";import{existsSync as jt,readFileSync as Fe,renameSync as Cr,unlinkSync as Mn,writeFileSync as ln,mkdirSync as qt,statSync as Zi,openSync as zt,closeSync as Jt,fsyncSync as un,realpathSync as eo,lstatSync as Vt}from"node:fs";import{isDeepStrictEqual as v}from"node:util";import{join as J,isAbsolute as to,resolve as jn}from"node:path";import{homedir as Kt}from"node:os";import{probeYoloopHostCapacity as no}from"../runner/host-capacity.js";import{isPrivateExecutionPublicEnvelope as ro,isPrivatePlanningRootPublicEnvelope as io,PRIVATE_MUTATION_QA_GATE_STEP_TOKEN as oo}from"../private-execution/delivery.js";import{acceptedPlanningDiagnosisPredecessor as _r}from"../private-execution/planning-diagnosis-checkpoint.js";import{acceptedPlanningResearchPredecessor as Rr}from"../private-execution/planning-research-checkpoint.js";import{verifyCommittedPlanningMemory as wr}from"../private-execution/planning-memory-checkpoint.js";import{verifyCommittedPlanningGeneration as ao}from"../private-execution/planning-generation-checkpoint.js";import{PLANNING_RAW_INTENT_MAX_CHARS as co}from"../../../shared/dist/planning/diagnosis-state.js";import{applyCrossEpicContinuationReconciliation as so,buildCrossEpicContinuationPayloadHash as po,classifyCrossEpicContinuationReconciliation as lo,epicOperationalHash as vt,readEpicOperationalState as Ar}from"../git/epic-operational-state.js";import{LicenseClient as uo}from"../license/license-client.js";import{EncryptedCache as Vn}from"../cache/encrypted-cache.js";import{NoOpCache as br}from"../types/index.js";import{resolveClientPreFlightTrigger as hn,TierAwareClient as ho}from"../tier/tier-aware-client.js";import{COMMAND_REGISTRY_CHECKSUM as st,COMMAND_REGISTRY_VERSION as dt,GENERATED_CLIENT_COMMANDS as go}from"../generated/command-registry.generated.js";import{loadSecureConfig as Bn}from"../config/secure-config.js";import{neocortexProfileDirectory as fo}from"../config/profile-directory.js";import{DEFAULT_SERVER_URL as mo}from"../constants.js";import{detectFirstRunLocale as yo,renderFirstRunMessage as Io}from"../i18n/first-run.js";import{humanizeError as xr,formatHumanizedError as Tr,detectErrorLocale as Pr}from"../errors/error-messages.js";import{degradeStateSnapshotForPayloadLimit as Eo,projectStateSnapshotForInvoke as kr,projectStateSnapshotResultV2ForInvoke as So}from"../state/project-state-snapshot.js";import{isInlineYoloMaterialization as Or,maybeRepairStateJsonBeforeInvoke as vo,readStoryWorktreeRepairOverlay as Co,StateRepairHardStopError as _o}from"../state/state-json-repair.js";import{StructuralDagError as Nr}from"../state/structural-dag-projection.js";import{collectStateMigrationAuthority as Ro,StateMigrationApplyError as wo}from"../migrations/state-json.js";import{RUNNER_BOOTSTRAP_POLICY_REASON_CODES as Ao,classifyRunnerBootstrapPolicyFromArgs as bo}from"../continuity/runner-bootstrap-policy.js";import{RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES as xo,ensureRunnerSchedulerBootstrap as To,observeRunnerOperationalStatus as Po}from"../runner/scheduler.js";import{CONTINUITY_INVOKE_WATCH_DEFAULT_LIMIT as Lr,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_IDLE_POLLS as Dr,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_POLLS as Mr,CONTINUITY_INVOKE_WATCH_DEFAULT_POLL_INTERVAL_MS as jr,openContinuityClientStateStore as ko}from"../continuity/continuity-client-state-store.js";import{isLocalJobsConsoleArgs as Oo,runLocalJobsConsoleCommand as No}from"../runner/local-console.js";import{detectNativeHostAttestation as Lo,detectPlatform as Do}from"../adapters/platform-detector.js";import{signNxInvokeRequest as Mo}from"../../../shared/dist/nx-invoke-signature.js";import{YOLO_INVOKE_ENVELOPE_CAPABILITY as jo}from"../../../shared/dist/yolo/spec-envelope.js";import{parseReleaseBlockedResult as Vo}from"../../../shared/dist/yoloop/release-blocked.js";import{CLIENT_VERSION as Pt}from"../version.js";import{createCapabilityCache as Vr,executeInvokeQueryTransport as Un,executeSecondaryNetworkMutation as Bo}from"../effects/invoke-effect-gateways.js";import{STRICT_READ_ONLY_POLICY as Uo,STRICT_READ_ONLY_CLIENT_PROJECTION as Br,STRICT_READ_ONLY_SERVER_PROJECTION as $o,StrictReadOnlyError as Bt,canonicalizeInvokeEffects as Ho,createInvokeEffectContext as Wo,verifyStrictReadOnlyReceipt as Go}from"../../../shared/dist/strict-readonly.js";import{admitInvocation as Fo,assertInvokeInputEnvelopeV2 as Yo,assertProjectIdentityMigrationReceiptV1 as qo,buildProjectIdentityPublicDiagnostic as Ut,createInvocationAdmissionReceipt as zo,projectInvokeInputEvidenceV1 as $n,recoverExplicitInvocation as Jo,verifyStrictDiagnoseReceiptV1 as Ko}from"../../../shared/dist/invocation/index.js";import{buildInvokeInputEnvelope as Qt,InvokeInputDecodeError as Qo}from"../invocation/invoke-input.js";import{COMPATIBILITY_REASON_CODES as $t,createCompatibilityOffer as Xo,createLegacyCompatibilityResult as Zo,isCompatibilityResultV1 as ea}from"../../../shared/dist/compatibility/index.js";import{acknowledgeProjectIdentityMigration as ta,finalizeProjectIdentityMigration as na,prepareProjectIdentityMigration as ra,ProjectIdentityMigrationError as Hn,readProjectIdentityMigrationPhase as ia}from"../migrations/project-identity.js";import{probeProjectIdentityMigrationCapability as oa}from"../migrations/project-identity-capability.js";import{normalizeYoloopStoryPlanningEvidence as aa}from"../../../shared/dist/yoloop/planning-graph.js";import{normalizeContinuousWriteRef as gn}from"../../../shared/dist/yoloop/wave-decision-receipt.js";import{epicHeadReconciliationInputDigest as ca,epicHeadReconciliationPathsDigest as fn,epicHeadReconciliationRangeDigest as sa}from"../../../shared/dist/yoloop/epic-terminal-git.js";import{applyGitLifecycleRuntimeOverlay as Ur,classifyGitLifecycleStoryCheckpointProjectionSync as da,ensureRuntimeEpic as pa,ensureGitLifecycleRuntimeInitialized as la,executeP205TransientAuthorities as ua,isP226GateReasonCode as ha,persistGitLifecycleGraphAuthority as ga,P205_COMPLETE_COMMAND as Xt,gitLifecycleStoryWriteSet as $r,gitLifecycleStoryClaimCandidates as fa,gitLifecycleWriteSetCovers as ma,appendStoryWorktreeEvidence as ya,isStoryWorktreeEvidenceContainer as Ia,mutateGitLifecycleRuntime as Hr,projectP205TransientExecutionEvidence as Ea,readGitLifecycleRuntimeSync as mn,verifyLegacyCheckpointMigrationCandidateSync as Sa}from"../git/git-lifecycle-store.js";import{verifyRootMemoryPhysicalWriteSet as va}from"../private-execution/root-memory-git-evidence.js";import{isRootProjectMemoryEffect as Ca}from"../private-execution/shared-root-memory-types.js";import{probeYoloInvokeEnvelopeCapability as _a}from"../yolo/invoke-envelope-capability.js";import{attachProjectManifestProjection as Ra}from"../yolo/project-manifest-projection-collector.js";import{collectYoloSpecEnvelope as Wr,extractTargetedYoloStoryId as wa,refreshPrecollectedYoloSpecEnvelope as Gr}from"../yolo/spec-envelope-collector.js";import{FRONTMATTER_LIST_TOO_LONG_DIAGNOSTIC_PATTERN as Aa}from"../errors/frontmatter-diagnostics.js";function Fr(e,t=!1){return e instanceof Error&&((t?/^yolo-(?:spec-envelope|change-evidence)-[a-z-]+$/:/^yolo-spec-envelope-[a-z-]+$/).test(e.message)||Aa.test(e.message))?e.message:"yolo-spec-envelope-unsafe"}const yn=fo(),Wn=J(yn,"cache"),Yr=J(Wn,"menu-cache.json"),qr=1440*60*1e3,zr=3e4,Jr=256*1024,Kr=Jr,Qr=.8,Ct="[REDACTED]",ba=1e5,kt=2e3,xa=200,Ta=200,Pa=12,ka=/(?:promptBody|workflow|workflowGraph|stepBody|privateUrl|rawLog|secret|credential|licenseKey|apiKey|internalRouting|serverOnly|proprietary|protected)/i,Oa=/(?:PRIVATE|PROTECTED|SERVER_ONLY)[-_\s]*(?:PROMPT|PROMPT_BODY|WORKFLOW|WORKFLOW_GRAPH|STEP_BODY|STEP|ROUTING)\s*[:=][^\n\r]*/gi,Na=/(?:https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|private|internal)[^\s"'<>]*|raw[_-]?log|transcript|stack\s*trace|stderr:|stdout:|system prompt|prompt body|workflow body|step body|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|VENDOR_CORPUS|P180[_-]?SYNTHETIC[_-]?CONTINUITY|P185[_-]?SYNTHETIC[_-]?CONTINUITY|P187[_-]?SYNTHETIC[_-]?(?:CONTINUITY|RUNNER|WATCH)|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=)/gi,Gn=Math.floor(Jr*Qr),Xr=J(yn,".first-run-shown"),La="pending-epic-claims.json",Zr=64;function ei(e){return J(e,".neocortex",La)}function Ht(e){const t=ei(e);if(!jt(t))return{schemaVersion:1,operations:{}};const o=JSON.parse(Fe(t,"utf8"));if(!o||typeof o!="object"||Array.isArray(o))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const n=o;if(n.schemaVersion!==1||!n.operations||typeof n.operations!="object"||Array.isArray(n.operations))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(Object.keys(n.operations).length>Zr)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");for(const[i,r]of Object.entries(n.operations)){if(!/^[a-f0-9]{64}$/.test(i)||!r||typeof r!="object"||Array.isArray(r))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const a=r;if(a.planningProtocol!==void 0&&a.planningProtocol!=="root-staged-v1")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(typeof a.idempotencyKey!="string"||!/^[0-9a-f-]{36}$/.test(a.idempotencyKey)||typeof a.createdAt!="string")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(a.claimId!==void 0&&(typeof a.claimId!="string"||!/^[0-9a-f-]{36}$/.test(a.claimId))||a.epicId!==void 0&&(typeof a.epicId!="string"||!/^P[1-9][0-9]*$/.test(a.epicId))||a.claimId===void 0!=(a.epicId===void 0))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE")}return o}function Fn(e,t){const o=ei(e);qt(J(e,".neocortex"),{recursive:!0,mode:448});const n=`${o}.${process.pid}.${pn()}.tmp`;ln(n,`${JSON.stringify(t)}
|
|
2
|
+
`,{encoding:"utf8",mode:384,flag:"wx"}),Cr(n,o)}function Da(e,t){return Ne("sha256").update(`nx-epic-logical-operation-v1\0${JSON.stringify({command:t,args:e})}`,"utf8").digest("hex")}function Ma(e,t,o="create-epic"){const n=Da(t,o),i=Ht(e),r=i.operations[n];if(r)return{key:r.idempotencyKey,fingerprint:n};if(Object.keys(i.operations).length>=Zr)throw new Error("EPIC_CLAIM_CAPACITY_EXCEEDED");const a=pn(),d={...i.operations,[n]:{idempotencyKey:a,createdAt:new Date().toISOString()}};return Fn(e,{schemaVersion:1,operations:d}),{key:a,fingerprint:n}}function ja(e,t){const o=Ht(e);if(!o.operations[t])return;const n={...o.operations};delete n[t],Fn(e,{schemaVersion:1,operations:n})}function Va(e,t,o,n){const i=n.scope?.targetStoryId??n.current_session?.active_story_id??null,r=n.scope?.targetEpicId??n.current_session?.active_epic_id??null,a=i?n.stories[i]:void 0,d=Array.isArray(a?.steps_completed)?a.steps_completed.filter(m=>typeof m=="string"):[],s=o??Ne("sha256").update(`nx-yolo-project-path-v1\0${jn(e)}`,"utf8").digest("hex"),u=JSON.stringify({projectBinding:s,args:t,storyId:i,epicId:r,status:typeof a?.status=="string"?a.status:null,lastStep:typeof a?.last_step=="string"?a.last_step:null,stepsCompleted:d});return`yolo-${Ne("sha256").update(`nx-yolo-logical-operation-v1\0${u}`,"utf8").digest("hex")}`}function ti(e,t,o,n,i){if(!/^[0-9a-f-]{36}$/.test(o)||!/^P[1-9][0-9]*$/.test(n)||i!==void 0&&i!=="root-staged-v1")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const r=Ht(e),a=r.operations[t];if(!a)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(a.claimId!==void 0&&(a.claimId!==o||a.epicId!==n))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");Fn(e,{schemaVersion:1,operations:{...r.operations,[t]:{...a,claimId:o,epicId:n,...i?{planningProtocol:i}:{}}}})}function Ba(){try{if(jt(Xr))return;const e=yo(),t=Io(e);process.stderr.write(t);try{qt(yn,{recursive:!0}),ln(Xr,new Date().toISOString(),"utf-8")}catch{}}catch{}}function Yn(e,t=process.cwd()){return e&&e.trim().length>0?e:t}function Ua(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 $a(e){const t=e.metadata;if(!t||!(t.yoloopReleaseBlocked===!0||t.terminalClass==="release-blocked"||t.releaseBlocked!==void 0))return;const n=Vo(t.releaseBlocked);return!n||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:n},error:"YOLOOP_RELEASE_BLOCKED: the current release attempt ended without success.",errorCode:"YOLOOP_RELEASE_BLOCKED",exitCode:1}}function ni(e){return Fo(e,{registryVersion:dt,registryChecksum:st})}function Ha(e){return Jo(e,{registryVersion:dt,registryChecksum:st})}const Wa=new Set(["completed","aborted","cancelled"]),Ga=new Set(["watch-target-missing","watch-target-malformed","watch-target-ambiguous","watch-target-multiple"]),_e=Object.freeze({COMPLETED:"invoke-watch-completed",CANCELLED:"invoke-watch-cancelled",IDLE_TIMEOUT:"invoke-watch-idle-timeout",MAX_POLLS:"invoke-watch-max-polls",STORE_UNAVAILABLE:"invoke-watch-store-unavailable",TARGET_UNRESOLVED:"invoke-watch-target-unresolved"}),Le=Object.freeze({MISSING:"watch-target-missing",MALFORMED:"watch-target-malformed",AMBIGUOUS:"watch-target-ambiguous",CONFLICT:"watch-target-conflicting-evidence",SERVER_HELD_STREAM:"watch-target-server-held-stream-unsupported"}),Y=Object.freeze({OK:"continuity-ok",WATCH_NO_SUMMARIES_YET:"watch-no-summaries-yet",WATCH_CURSOR_ADVANCED:"watch-cursor-advanced",WATCH_CURSOR_UNCHANGED:"watch-cursor-unchanged",WATCH_RENDER_PENDING:"watch-render-pending",WATCH_STOP_IDLE_LIMIT_REACHED:"watch-stop-idle-limit-reached",WATCH_STOP_MAX_POLLS_REACHED:"watch-stop-max-polls-reached",WATCH_TARGET_UNRESOLVED:"watch-target-unresolved",WATCH_SNAPSHOT_UNAVAILABLE:"watch-snapshot-unavailable",WATCH_EVIDENCE_UNAVAILABLE:"watch-evidence-unavailable"}),ri=240,Fa=/(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 Ya(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(Oa,Ct).replace(Na,Ct)}function Je(e,t){const o=Ya(e);return o.length<=t?o:`${o.slice(0,t)}\u2026[TRUNCATED:${o.length-t}]`}function qn(e,t=0,o=new WeakSet){if(t>Pa)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(o.has(e))return"[CIRCULAR]";o.add(e);try{if(Array.isArray(e))return e.slice(0,xa).map(i=>qn(i,t+1,o));const n={};for(const[i,r]of Object.entries(e).slice(0,Ta)){if(ka.test(i)){n[i]=Ct;continue}const a=qn(r,t+1,o);a!==void 0&&(n[i]=a)}return n}finally{o.delete(e)}}}function In(e,t){return{instructions:Je(e??"",ba),metadata:t?qn(t):void 0}}function qa(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e,o=typeof t.reason=="string"&&/^[a-z0-9-]{1,80}$/.test(t.reason)?t.reason:void 0,n=typeof t.baseSource=="string"&&["active-story-lease","published-execution-branch","local-default-branch","remote-default-branch","none"].includes(t.baseSource)?t.baseSource:void 0,i=typeof t.repair=="string"&&["not-eligible","not-attempted","applied"].includes(t.repair)?t.repair:void 0,r=typeof t.fallbackAction=="string"&&["reacquire-exact-story-setup","restore-verified-base-evidence","resolve-lease-conflict","inspect-repository-binding","none"].includes(t.fallbackAction)?t.fallbackAction:void 0,a=t.recollectionCount===0||t.recollectionCount===1?t.recollectionCount:void 0;if(!(!o||!n||!i||!r||a===void 0||t.publicSafe!==!0))return{reason:o,base_source:n,repair:i,recollection_count:a,fallback_action:r,public_safe:!0}}class En extends Error{reason;source;byteLength;code;constructor(t,o,n,i,r){super(o),this.reason=n,this.source=i,this.byteLength=r,this.name="InvokeCliInputError",this.code=t}}function za(e){const t=hn(e);return(t==="arch-plan"||t==="ui-ux-review")&&Ja(e,"--project-evidence")}function Ja(e,t){let o=null,n=-1,i=!1,r=!1;for(let a=0;a<=e.length;a+=1){const d=e[a];if(a===e.length||!o&&/\s/.test(d??"")){if(n>=0&&!i&&e.slice(n,a)===t)return!0;n=-1,i=!1,r=!1;continue}if(n<0&&(n=a),r){r=!1;continue}if(d==="\\"){r=!0;continue}(d==='"'||d==="'")&&(i=!0,o=o===d?null:o??d)}return!1}const Ka=/(?:^|\s)codex(?:-cli)?\s+([A-Za-z0-9][A-Za-z0-9._+-]{0,63})(?:\s|$)/i;function Qa(e,t){if(e.targetId!=="codex")return null;const o=t.CODEX_VERSION?.trim();if(o&&/^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/.test(o))return o;try{return Be("codex",["--version"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim().match(Ka)?.[1]??null}catch{return null}}function zn(){return Xo({clientVersion:Pt,registryVersion:dt,registryChecksum:st})}class Jn extends Error{code="PAYLOAD_TOO_LARGE";telemetry;constructor(t){super(`PAYLOAD_TOO_LARGE: invoke request is ${t.payloadBytes} bytes after deterministic degradation; limit is ${t.limitBytes}. Reduce command input or local state context and retry.`),this.name="InvokePayloadTooLargeError",this.telemetry=t}}class Kn extends Error{code="STRUCTURAL_CONTEXT_TOO_LARGE";telemetry;constructor(t){super(`STRUCTURAL_CONTEXT_TOO_LARGE: the bounded structural projection is ${t.payloadBytes} bytes; the request limit is strictly below ${t.limitBytes}. Select an explicit epic/story target or split the dependency graph.`),this.name="InvokeStructuralContextTooLargeError",this.telemetry=t}}let Qn=!1;function Xa(e){const t=[];if(!e||typeof e!="object")return t;const o=e,n=o.planning;if(n&&(n.current!==void 0||Array.isArray(n.history))&&t.push({code:"PLANNING_LEGACY",message:"legacy `planning.current`/`planning.history` detected (not read by v1 orchestrator)"}),Array.isArray(o.stories)&&t.push({code:"STORIES_AS_ARRAY",message:"`stories` is an Array (expected Object keyed by story ID)"}),o.epics&&typeof o.epics=="object"&&!Array.isArray(o.epics))for(const[r,a]of Object.entries(o.epics)){const d=a;if(d&&d.stories!==void 0&&!Array.isArray(d.stories)){t.push({code:"EPIC_STORIES_NOT_ARRAY",message:`epic "${r}" has non-array \`stories\` field (expected string[] of story IDs)`});break}}const i=o.epics&&typeof o.epics=="object"&&Object.keys(o.epics).length>0||o.stories&&typeof o.stories=="object"&&!Array.isArray(o.stories)&&Object.keys(o.stories).length>0||Array.isArray(o.stories)||n&&n.current!==void 0;return o.schema_version===void 0?i&&t.push({code:"SCHEMA_VERSION_MISSING",message:"`schema_version` field missing (expected: `schema_version: 1`)"}):o.schema_version!==1&&t.push({code:"SCHEMA_VERSION_OUTDATED",message:`schema_version=${String(o.schema_version)} (expected: 1)`}),t}function Za(e){if(!(Qn||e.length===0)){Qn=!0;try{const t=e.map(o=>` - ${o.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 zd(){Qn=!1}function ii(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Za(e){return e==="active"||e==="archived"||e==="rolled-back"||e==="synthetic"||e==="orphan"?e:void 0}const ec=new Set(["goal","problem","desiredOutcome","rawIntent","context","users","surfaces","constraints","assumptions","risks","nonGoals","validationExpectations","debtRefs","repositoryEvidencePaths","journeyIds","screenIds","storybookStoryIds","backendContractIds","featureBlockerIds","remediationRefs","uiScope","remediationStory","examples","contracts"]),tc=/(?:[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}|(?:token|api[_-]?key|secret|password|credential|license[_-]?key)\s*[:=]\s*\S+|https?:\/\/(?:localhost|127\.0\.0\.1|10\.\d+\.\d+\.\d+|192\.168\.\d+\.\d+|172\.(?:1[6-9]|2\d|3[0-1])\.\d+\.\d+|[^\s/]*internal[^\s/]*)\S*|private\s+prompt|raw\s+vendor\s+corpus|sk-[A-Za-z0-9_-]{12,})/i;function nc(e,t){if(!h(e)||e.schemaVersion!==1||e.epicId!==t||!/^P\d+$/.test(t))return{};try{const i=JSON.stringify(e),r=Buffer.byteLength(i);if(r>16384)return{diagnostic:Object.freeze({schemaVersion:"CreateEpicPlanningProjectionDiagnostic/1.0",outcome:"omitted",reasonCode:"budget-omitted",byteLengthBucket:r<=32768?"16385-32768":"32769-plus",publicSafe:!0})};if(tc.test(i))return{};const o=(a,d)=>{if(Object.keys(a).some(s=>!d.includes(s)))throw new Error("planning-unknown-field")};if(o(e,["schemaVersion","epicId","intake","intakeRevision","diagnosisReceipt","researchReceipt","degradeAuthorization"]),!h(e.intake))return{};if(Object.keys(e.intake).some(a=>!ec.has(a)))return{};for(const[a,d]of Object.entries(e.intake))if(["examples","contracts"].includes(a)){const s=a==="examples"?["id","title","actor","given","when","then","source","coveredRequirement","expectedValidation"]:["id","kind","description","path"];if(!Array.isArray(d)||d.length>16)return{};for(const l of d){if(!h(l))return{};if(o(l,s),Object.values(l).some(m=>typeof m!="string"||m.length>256))return{}}}else if(Array.isArray(d)){if(d.length>32||d.some(s=>typeof s!="string"||s.length>256))return{}}else if(typeof d=="string"){if(d.length>(a==="rawIntent"?ao:512))return{}}else if(typeof d!="boolean"||!["uiScope","remediationStory"].includes(a))return{};const n=["schemaVersion","kind","epicId","intakeRevision","artifactSummary","artifactDigest","predecessorReceiptId","accepted","receiptId"];for(const a of[e.diagnosisReceipt,e.researchReceipt])if(a!==void 0){if(!h(a))return{};if(o(a,n),Object.values(a).some(d=>typeof d=="string"&&d.length>1024))return{}}if(e.degradeAuthorization!==void 0){if(!h(e.degradeAuthorization))return{};o(e.degradeAuthorization,["approved","intakeRevision","reasonCodes","assumptionCodes"]);for(const a of["reasonCodes","assumptionCodes"]){const d=e.degradeAuthorization[a];if(!Array.isArray(d)||d.length>32||d.some(s=>typeof s!="string"||s.length>128))return{}}}return{checkpoint:JSON.parse(i)}}catch{return{}}}function oi(e){return e==="create-epic"||e==="discovered"?e:void 0}function de(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function rc(e){const t={};let i=!1;for(const r of["contracts","contract_refs","shared_surfaces","adr_refs","nfr_refs","acceptance_depends_on"]){if(e[r]===void 0)continue;const o=e[r];if(!Array.isArray(o)||o.length>128||o.some(n=>gn(n)===void 0)){i=!0;continue}t[r]=o.map(n=>gn(n))}if(e.planning!==void 0)try{if(!h(e.planning))throw new Error("planning-shape");const r=e.planning;for(const a of["claims","semanticArtifacts"]){if(r[a]===void 0)continue;const d=r[a];if(!Array.isArray(d)||d.length>128||d.some(s=>!h(s)||gn(s.ref)===void 0))throw new Error("planning-refs")}if(r.attempts!==void 0&&(!Array.isArray(r.attempts)||r.attempts.length>32))throw new Error("planning-attempts");for(const a of r.attempts??[]){if(!h(a)||!Array.isArray(a.reasonCodes)||a.reasonCodes.length>32||a.reasonCodes.some(d=>typeof d!="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(d)))throw new Error("planning-attempt-reasons");if(a.discoveredClaims!==void 0&&(!Array.isArray(a.discoveredClaims)||a.discoveredClaims.length>128||a.discoveredClaims.some(d=>!h(d)||gn(d.ref)===void 0)))throw new Error("planning-attempt-claims")}const{graphRevision:o,...n}=oa(r);t.planning=n}catch{i=!0}return i&&(t.planning={schemaVersion:1,dependencyBasis:"unknown",claims:[],semanticArtifacts:[]}),t}function h(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function _t(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function Q(e){if(typeof e!="string")return;const t=e.trim();if(t)return t.replace(/[^a-z0-9_.:-]+/gi,"_").slice(0,120)}function q(e){if(typeof e!="string")return;const t=e.trim(),i=Q(e);return i===t?i:void 0}function Ie(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240)&&/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(t)&&!(t.includes("..")||t.includes("//")||t.includes("@{")||t.endsWith("/")||t.endsWith("."))&&!t.split("/").some(i=>!i||i.startsWith(".")||i.endsWith(".lock")))return t}function R(e){return typeof e=="string"&&/^[0-9a-f]{7,64}$/i.test(e)?e:void 0}function De(e){if(!(typeof e!="string"||e.length>64)&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/.test(e))return Number.isFinite(Date.parse(e))?e:void 0}function pt(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240||t.includes("..")))return/^[A-Za-z0-9._:/#\-[\]]+$/.test(t)?t:void 0}function Sn(e){if(!h(e))return;const t=u=>typeof u=="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,95}$/.test(u),i=u=>typeof u=="string"&&/^[a-f0-9]{64}$/.test(u),r=(u,v)=>Array.isArray(u)&&u.length<=v&&u.every(t)&&new Set(u).size===u.length?u:void 0,o=(u,v)=>{if(!(!h(u)||u.schemaVersion!==2||!t(u.requestId)||!t(u.stageCommand)||!i(u.requestHash)||!i(u.inputHash)||!i(u.stateHash)||!i(u.nonce)||!i(u.stageRevision)||!i(u.stageHash)||!i(u.catalogHash)||u.targetEpicId!==void 0&&!t(u.targetEpicId)||v&&(!i(u.outputHash)||!i(u.artifactHash))))return{schemaVersion:2,...u.targetEpicId?{targetEpicId:u.targetEpicId}:{},requestId:u.requestId,requestHash:u.requestHash,inputHash:u.inputHash,stateHash:u.stateHash,nonce:u.nonce,stageCommand:u.stageCommand,stageRevision:u.stageRevision,stageHash:u.stageHash,catalogHash:u.catalogHash,...v?{outputHash:u.outputHash,artifactHash:u.artifactHash}:{}}},n=(u,v)=>{if(!(!h(u)||u.schemaVersion!=="1.1"||u.kind!==v||!i(u.receiptId)||!i(u.graphHash)||!i(u.evidenceHash)||!t(u.elementId)||!t(u.caseId)||!t(u.category)))return{schemaVersion:"1.1",kind:v,receiptId:u.receiptId,graphHash:u.graphHash,elementId:u.elementId,caseId:u.caseId,category:u.category,evidenceHash:u.evidenceHash}},a=(u,v)=>{if(!h(u)||u.kind!==v||!i(u.receiptId)||!r(u.evidenceIds,24)||v==="architecture-stage-completion"&&!["succeeded","failed"].includes(String(u.status))||v==="architecture-stage-validation"&&!["passed","failed","pending"].includes(String(u.status)))return;const I=o(u,!0);if(!I)return;const g=v==="architecture-stage-validation"?n(u.isolated,"isolated"):void 0,E=v==="architecture-stage-validation"?n(u.regression,"regression"):void 0;if(!(v==="architecture-stage-validation"&&(!g||!E)))return{...I,kind:v,receiptId:u.receiptId,status:u.status,evidenceIds:u.evidenceIds,...g&&E?{isolated:g,regression:E}:{}}},d={};e.schemaVersion===1&&(d.schemaVersion=1),e.owner==="root"&&(d.owner="root"),t(e.currentStageCommand)&&(d.currentStageCommand=e.currentStageCommand),["ask-user","delegate","resume","advance","blocked","complete"].includes(String(e.continuationState))&&(d.continuationState=e.continuationState);const s=r(e.questionIds,16);if(s&&(d.questionIds=s),(e.childStatus==="succeeded"||e.childStatus==="failed")&&(d.childStatus=e.childStatus),(e.evidencePolicy==="legacy-compatible"||e.evidencePolicy==="v2-required")&&(d.evidencePolicy=e.evidencePolicy),t(e.targetEpicId)&&(d.targetEpicId=e.targetEpicId),i(e.graphRevision)&&(d.graphRevision=e.graphRevision),e.graphSource==="committed-epic-v1"&&(d.graphSource=e.graphSource),e.nonUiScopeReceipt!==void 0){const u=Sr(e.nonUiScopeReceipt);if(!u||u.targetEpicId!==e.targetEpicId||u.graphRevision!==e.graphRevision||!h(e.accounting)||u.accountingId!==e.accounting.accountingId||!h(e.evidenceExpectation)||u.rootInputSha256!==e.evidenceExpectation.inputHash)throw new Error("architecture-non-ui-scope-invalid");d.nonUiScopeReceipt=u}h(e.pactAnswerReceipt)&&Object.keys(e.pactAnswerReceipt).sort().join(",")===["schemaVersion","targetEpicId","graphRevision","stateSha256","answersSha256","questionIds","publicSafe"].sort().join(",")&&e.pactAnswerReceipt.schemaVersion==="PactAnswerReceipt/1"&&e.pactAnswerReceipt.targetEpicId===e.targetEpicId&&e.pactAnswerReceipt.graphRevision===e.graphRevision&&i(e.pactAnswerReceipt.stateSha256)&&i(e.pactAnswerReceipt.answersSha256)&&C(e.pactAnswerReceipt.questionIds,["PACT-Q1-CONSUMER","PACT-Q2-PROVIDER","PACT-Q3-BROKER","PACT-Q4-MATCHERS","PACT-Q5-VERIFY"])&&e.pactAnswerReceipt.publicSafe===!0&&(d.pactAnswerReceipt=e.pactAnswerReceipt);const l=o(e.evidenceExpectation,!1);l&&(d.evidenceExpectation=l);const m=a(e.completionEvidence,"architecture-stage-completion"),S=a(e.validationEvidence,"architecture-stage-validation");if(m&&(d.completionEvidence=m),S&&(d.validationEvidence=S),h(e.reviewDecision)&&Object.keys(e.reviewDecision).sort().join(",")===["schemaVersion","targetEpicId","graphRevision","artifactHash","completionReceiptId","validationReceiptId","decision","evidenceIds","publicSafe"].sort().join(",")&&e.reviewDecision.schemaVersion==="ArchitectureReviewDecision/1"&&e.reviewDecision.targetEpicId===e.targetEpicId&&e.reviewDecision.graphRevision===e.graphRevision&&i(e.reviewDecision.graphRevision)&&i(e.reviewDecision.artifactHash)&&i(e.reviewDecision.completionReceiptId)&&i(e.reviewDecision.validationReceiptId)&&["approved","changes-requested"].includes(String(e.reviewDecision.decision))&&e.reviewDecision.publicSafe===!0){const u=r(e.reviewDecision.evidenceIds,24);u&&u.length>0&&(d.reviewDecision={...e.reviewDecision,evidenceIds:u})}if(Ft(e.terminalMemoryCheckpoint,e))d.terminalMemoryCheckpoint=e.terminalMemoryCheckpoint;else if(h(e.terminalMemoryCheckpoint)&&e.terminalMemoryCheckpoint.schemaVersion===void 0&&["passed","failed","pending"].includes(String(e.terminalMemoryCheckpoint.status))){const u=r(e.terminalMemoryCheckpoint.evidenceIds,24);u&&(d.terminalMemoryCheckpoint={status:e.terminalMemoryCheckpoint.status,evidenceIds:u})}if(Array.isArray(e.acceptedStages)&&e.acceptedStages.length<=15){const u=e.acceptedStages.map(v=>{if(!h(v)||!t(v.targetEpicId)||!t(v.stageCommand))return;const I=a(v.completionEvidence,"architecture-stage-completion"),g=a(v.validationEvidence,"architecture-stage-validation");return I&&g?{targetEpicId:v.targetEpicId,stageCommand:v.stageCommand,completionEvidence:I,validationEvidence:g}:void 0});u.every(v=>v!==void 0)&&(d.acceptedStages=u)}if(h(e.accounting)&&e.accounting.schemaVersion===1&&t(e.accounting.contractVersion)&&t(e.accounting.accountingId)&&typeof e.accounting.charged=="boolean"&&Number.isInteger(e.accounting.chargedQuotaUnits)&&typeof e.accounting.chargedQuotaUnits=="number"&&e.accounting.chargedQuotaUnits>=0&&e.accounting.chargedQuotaUnits<=13){const u=r(e.accounting.receiptIds,32);u&&(d.accounting={schemaVersion:1,contractVersion:e.accounting.contractVersion,accountingId:e.accounting.accountingId,charged:e.accounting.charged,chargedQuotaUnits:e.accounting.chargedQuotaUnits,receiptIds:u,...["in-progress","aborted","timed-out","failed","complete"].includes(String(e.accounting.lastOutcome))?{lastOutcome:e.accounting.lastOutcome}:{}})}return JSON.stringify(d).length<=96e3?d:void 0}function ic(e){const t=h(e.metadata.archPlan)?e.metadata.archPlan.execution:void 0,i=h(t)?t.checkpoint:void 0,r=h(t)?t:void 0,o=h(i)?i:void 0,n=e.requestExecution,a=Array.isArray(o?.acceptedStages)?o.acceptedStages:[],d=n.currentStageCommand==="arch-prd"&&n.continuationState==="delegate"&&n.completionEvidence===void 0&&n.validationEvidence===void 0&&o?.currentStageCommand==="arch-prd"&&o.continuationState==="delegate"&&a.length===0&&r?.nextAction==="delegate",s=n.currentStageCommand==="arch-prd"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&o?.currentStageCommand==="arch-architecture"&&o.continuationState==="advance"&&a.length===1&&h(a[0])&&a[0].stageCommand==="arch-prd"&&C(a[0].completionEvidence,n.completionEvidence)&&C(a[0].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",l=n.currentStageCommand==="arch-architecture"&&n.continuationState==="advance"&&o?.currentStageCommand==="arch-architecture"&&o.continuationState==="delegate"&&a.length===1&&C(a,n.acceptedStages)&&r?.nextAction==="delegate",m=n.currentStageCommand==="arch-architecture"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&o?.currentStageCommand==="arch-fitness-functions"&&o.continuationState==="advance"&&a.length===2&&h(a[0])&&h(a[1])&&a[0].stageCommand==="arch-prd"&&a[1].stageCommand==="arch-architecture"&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===1&&C(a[0],n.acceptedStages[0])&&C(a[1].completionEvidence,n.completionEvidence)&&C(a[1].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",S=n.currentStageCommand==="arch-fitness-functions"&&n.continuationState==="advance"&&o?.currentStageCommand==="arch-fitness-functions"&&o.continuationState==="delegate"&&a.length===2&&h(a[0])&&h(a[1])&&a[0].stageCommand==="arch-prd"&&a[1].stageCommand==="arch-architecture"&&C(a,n.acceptedStages)&&r?.nextAction==="delegate",u=n.currentStageCommand==="arch-fitness-functions"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&o?.currentStageCommand==="arch-api-contracts"&&o.continuationState==="advance"&&a.length===3&&h(a[0])&&h(a[1])&&h(a[2])&&a[0].stageCommand==="arch-prd"&&a[1].stageCommand==="arch-architecture"&&a[2].stageCommand==="arch-fitness-functions"&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===2&&C(a.slice(0,2),n.acceptedStages)&&C(a[2].completionEvidence,n.completionEvidence)&&C(a[2].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",v=n.currentStageCommand==="arch-api-contracts"&&n.continuationState==="advance"&&o?.currentStageCommand==="arch-api-contracts"&&o.continuationState==="delegate"&&a.length===3&&h(a[0])&&h(a[1])&&h(a[2])&&a[0].stageCommand==="arch-prd"&&a[1].stageCommand==="arch-architecture"&&a[2].stageCommand==="arch-fitness-functions"&&C(a,n.acceptedStages)&&r?.nextAction==="delegate",I=["PACT-Q1-CONSUMER","PACT-Q2-PROVIDER","PACT-Q3-BROKER","PACT-Q4-MATCHERS","PACT-Q5-VERIFY"],g=n.currentStageCommand==="arch-api-contracts"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&o?.currentStageCommand==="generate-pacts"&&o.continuationState==="ask-user"&&a.length===4&&h(a[3])&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===3&&C(a.slice(0,3),n.acceptedStages)&&a[3].stageCommand==="arch-api-contracts"&&C(a[3].completionEvidence,n.completionEvidence)&&C(a[3].validationEvidence,n.validationEvidence)&&C(o.questionIds,I)&&C(r?.questionIds,I)&&r?.nextAction==="ask-user",E=n.currentStageCommand==="generate-pacts"&&n.continuationState==="ask-user"&&o?.currentStageCommand==="generate-pacts"&&o.continuationState==="delegate"&&a.length===4&&C(a,n.acceptedStages)&&C(n.questionIds,I)&&C(o.questionIds,[])&&C(o.pactAnswerReceipt,e.answerReceipt)&&C(r?.pactAnswerReceipt,e.answerReceipt)&&e.answerReceipt?.stateSha256===e.sourceStateSha256&&r?.nextAction==="resume",x=n.currentStageCommand==="generate-pacts"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&C(n.pactAnswerReceipt,e.pactRecordedReceipt)&&o?.currentStageCommand==="arch-api-integrations"&&o.continuationState==="advance"&&a.length===5&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===4&&C(a.slice(0,4),n.acceptedStages)&&a.map(V=>h(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts"&&h(a[4])&&C(a[4].completionEvidence,n.completionEvidence)&&C(a[4].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",M=n.currentStageCommand==="arch-api-integrations"&&n.continuationState==="advance"&&o?.currentStageCommand==="arch-api-integrations"&&o.continuationState==="delegate"&&a.length===5&&C(a,n.acceptedStages)&&r?.nextAction==="delegate",P=n.currentStageCommand==="arch-api-integrations"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&o?.currentStageCommand==="arch-database"&&o.continuationState==="advance"&&a.length===6&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===5&&C(a.slice(0,5),n.acceptedStages)&&a.map(V=>h(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations"&&h(a[5])&&C(a[5].completionEvidence,n.completionEvidence)&&C(a[5].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",k=n.currentStageCommand==="arch-database"&&n.continuationState==="advance"&&o?.currentStageCommand==="arch-database"&&o.continuationState==="delegate"&&a.length===6&&C(a,n.acceptedStages)&&r?.nextAction==="delegate",_=n.currentStageCommand==="arch-database"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&o?.currentStageCommand==="arch-security"&&o.continuationState==="advance"&&a.length===7&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===6&&C(a.slice(0,6),n.acceptedStages)&&a.map(V=>h(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database"&&h(a[6])&&C(a[6].completionEvidence,n.completionEvidence)&&C(a[6].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",w=n.currentStageCommand==="arch-security"&&n.continuationState==="advance"&&o?.currentStageCommand==="arch-security"&&o.continuationState==="delegate"&&a.length===7&&C(a,n.acceptedStages)&&r?.nextAction==="delegate",L=n.currentStageCommand==="arch-security"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&o?.currentStageCommand==="arch-design-system"&&o.continuationState==="advance"&&a.length===8&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===7&&C(a.slice(0,7),n.acceptedStages)&&a.map(V=>h(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security"&&h(a[7])&&C(a[7].completionEvidence,n.completionEvidence)&&C(a[7].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",D=n.currentStageCommand==="arch-design-system"&&n.continuationState==="advance"&&o?.currentStageCommand==="arch-design-system"&&o.continuationState==="delegate"&&a.length===8&&C(a,n.acceptedStages)&&r?.nextAction==="delegate",Y=n.currentStageCommand==="arch-design-system"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&o?.currentStageCommand==="arch-ux-design"&&o.continuationState==="advance"&&a.length===9&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===8&&C(a.slice(0,8),n.acceptedStages)&&a.map(V=>h(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system"&&h(a[8])&&C(a[8].completionEvidence,n.completionEvidence)&&C(a[8].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",X=n.currentStageCommand==="arch-ux-design"&&n.continuationState==="advance"&&o?.currentStageCommand==="arch-ux-design"&&o.continuationState==="delegate"&&a.length===9&&C(a,n.acceptedStages)&&r?.nextAction==="blocked",pe=n.currentStageCommand==="arch-ux-design"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&o?.currentStageCommand==="arch-performance"&&o.continuationState==="advance"&&a.length===10&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===9&&C(a.slice(0,9),n.acceptedStages)&&a.map(V=>h(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design"&&h(a[9])&&C(a[9].completionEvidence,n.completionEvidence)&&C(a[9].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",b=n.currentStageCommand==="arch-performance"&&n.continuationState==="advance"&&o?.currentStageCommand==="arch-performance"&&o.continuationState==="delegate"&&a.length===10&&C(a,n.acceptedStages)&&r?.nextAction==="delegate",Se=n.currentStageCommand==="arch-performance"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&o?.currentStageCommand==="arch-testing"&&o.continuationState==="advance"&&a.length===11&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===10&&C(a.slice(0,10),n.acceptedStages)&&a.map(V=>h(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance"&&h(a[10])&&C(a[10].completionEvidence,n.completionEvidence)&&C(a[10].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",Z=n.currentStageCommand==="arch-testing"&&n.continuationState==="advance"&&o?.currentStageCommand==="arch-testing"&&o.continuationState==="delegate"&&a.length===11&&C(a,n.acceptedStages)&&r?.nextAction==="delegate",J=n.currentStageCommand==="arch-testing"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&o?.currentStageCommand==="arch-infrastructure"&&o.continuationState==="advance"&&a.length===12&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===11&&C(a.slice(0,11),n.acceptedStages)&&a.map(V=>h(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance,arch-testing"&&h(a[11])&&C(a[11].completionEvidence,n.completionEvidence)&&C(a[11].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",gt=n.currentStageCommand==="arch-infrastructure"&&n.continuationState==="advance"&&o?.currentStageCommand==="arch-infrastructure"&&o.continuationState==="delegate"&&a.length===12&&C(a,n.acceptedStages)&&r?.nextAction==="delegate",wt=n.currentStageCommand==="arch-infrastructure"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&o?.currentStageCommand==="arch-review"&&o.continuationState==="advance"&&a.length===13&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===12&&C(a.slice(0,12),n.acceptedStages)&&a.map(V=>h(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance,arch-testing,arch-infrastructure"&&h(a[12])&&C(a[12].completionEvidence,n.completionEvidence)&&C(a[12].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",ue=n.currentStageCommand==="arch-review"&&n.continuationState==="advance"&&o?.currentStageCommand==="arch-review"&&o.continuationState==="delegate"&&a.length===13&&C(a,n.acceptedStages)&&r?.nextAction==="delegate",O=n.currentStageCommand==="arch-review"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&n.reviewDecision===void 0&&o?.currentStageCommand==="arch-review"&&o.continuationState==="ask-user"&&a.length===13&&C(a,n.acceptedStages)&&C(o.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&C(o.completionEvidence,n.completionEvidence)&&C(o.validationEvidence,n.validationEvidence)&&r?.nextAction==="ask-user",$=n.currentStageCommand==="arch-review"&&n.continuationState==="ask-user"&&n.childStatus==="succeeded"&&h(n.reviewDecision)&&n.reviewDecision.decision==="approved"&&C(n.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&o?.currentStageCommand==="update-memory"&&o.continuationState==="advance"&&a.length===14&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===13&&C(a.slice(0,13),n.acceptedStages)&&h(a[13])&&a[13].stageCommand==="arch-review"&&C(a[13].completionEvidence,n.completionEvidence)&&C(a[13].validationEvidence,n.validationEvidence)&&C(o.reviewDecision,n.reviewDecision)&&r?.nextAction==="resume",xe=n.currentStageCommand==="update-memory"&&n.continuationState==="advance"&&h(n.reviewDecision)&&n.reviewDecision.decision==="approved"&&o?.currentStageCommand==="update-memory"&&o.continuationState==="delegate"&&a.length===14&&C(a,n.acceptedStages)&&C(o.reviewDecision,n.reviewDecision)&&r?.nextAction==="delegate",Te=n.currentStageCommand==="update-memory"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&o?.currentStageCommand==="update-memory"&&o.continuationState==="complete"&&a.length===15&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===14&&C(a.slice(0,14),n.acceptedStages)&&h(a[14])&&a[14].targetEpicId===n.targetEpicId&&a[14].stageCommand==="update-memory"&&C(a[14].completionEvidence,n.completionEvidence)&&C(a[14].validationEvidence,n.validationEvidence)&&C(o.reviewDecision,n.reviewDecision)&&C(o.completionEvidence,n.completionEvidence)&&C(o.validationEvidence,n.validationEvidence)&&Ft(o.terminalMemoryCheckpoint,n)!==null&&C(o.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)&&r?.nextAction==="complete",Pe=n.currentStageCommand==="update-memory"&&n.continuationState==="complete"&&n.childStatus==="succeeded"&&o?.currentStageCommand==="update-memory"&&o.continuationState==="complete"&&a.length===15&&C(a,n.acceptedStages)&&C(o.reviewDecision,n.reviewDecision)&&C(o.completionEvidence,n.completionEvidence)&&C(o.validationEvidence,n.validationEvidence)&&Ft(o.terminalMemoryCheckpoint,n)&&C(o.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)&&r?.nextAction==="complete",Nt=r?zi(n,r,Ft(n.terminalMemoryCheckpoint,n)&&C(o?.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)):void 0;if(e.metadata.mode!=="arch-plan"||e.metadata.resolvedTrigger!=="arch-plan"||!h(t)||!h(i)||t.owner!=="root"||t.currentStageCommand!==i.currentStageCommand||t.continuationState!==i.continuationState||i.owner!=="root"||i.evidencePolicy!=="v2-required"||i.targetEpicId!==n.targetEpicId||i.graphRevision!==n.graphRevision||i.graphSource!==n.graphSource||!/^P[1-9][0-9]{0,11}$/.test(String(i.targetEpicId))||!/^[a-f0-9]{64}$/.test(String(i.graphRevision))||!Array.isArray(i.acceptedStages)||!(Nt||d||s||l||m||S||u||v||g||E||x||M||P||k||_||w||L||D||Y||X||pe||b||Se||Z||J||gt||wt||ue||O||$||xe||Te||Pe)||!h(i.accounting)||i.accounting.charged!==!0||!C(Sn(i),i))throw new Error("architecture-root-checkpoint-invalid");const rt=z(e.projectRoot,".neocortex"),K=z(rt,"state.json"),ve=z(rt,"state.json.architecture.lock"),he=zt(ve,"wx",384);let qe;try{const V=Vt(K);if(!V.isFile()||V.isSymbolicLink())throw new Error("architecture-root-state-binding-invalid");const ft=Fe(K,"utf8");if(Ne("sha256").update(ft).digest("hex")!==e.sourceStateSha256)throw new Error("architecture-root-state-conflict");const ge=JSON.parse(ft),ae=h(ge)&&h(ge.archPlan)?ge.archPlan:{};if(!h(ge)||!h(ge.epics)||!Object.hasOwn(ge.epics,i.targetEpicId)||(e.initialBinding?ae.execution!==void 0||n.graphSource!=="committed-epic-v1":!C(Sn(ae.execution),n))||h(ge.scope)&&ge.scope.kind==="projected")throw new Error("architecture-root-state-binding-invalid");if(n.graphSource==="committed-epic-v1"&&n.graphRevision!==Yt(e.projectRoot,String(n.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");if(Pe||Nt==="complete-replay"){const Lt={...n,continuationState:"delegate",acceptedStages:n.acceptedStages.slice(0,Ir(n))};if(!C(n.terminalMemoryCheckpoint,Dn(e.projectRoot,Lt)))throw new Error("architecture-root-state-conflict");return}const ye=pn(),Ve=Be("git",["rev-parse","--git-common-dir"],{cwd:e.projectRoot,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),ee=eo(Ve)?jn(Ve):jn(e.projectRoot,Ve);if(Zi(ee)!==ee)throw new Error("architecture-root-backup-dir-invalid");const mt=z(ee,"neocortex-architecture");qt(mt,{recursive:!0,mode:448});const ze=Vt(mt);if(!ze.isDirectory()||ze.isSymbolicLink()||ze.uid!==process.getuid?.()||(ze.mode&63)!==0)throw new Error("architecture-root-backup-dir-invalid");const ke=z(mt,`state-backup-${ye}.json`),Qe=zt(ke,"wx",384);try{ln(Qe,ft),un(Qe)}finally{Jt(Qe)}const H=zt(mt,"r");try{un(H)}finally{Jt(H)}const xn={...ge,archPlan:{...ae,execution:i}};qe=z(rt,`state.json.architecture-tmp-${ye}`);const it=zt(qe,"wx",384);try{ln(it,`${JSON.stringify(xn,null,2)}
|
|
8
|
-
`),un(it)}finally{Jt(it)}if((Te||Nt==="complete")&&!C(n.terminalMemoryCheckpoint,Dn(e.projectRoot,n)))throw new Error("architecture-root-state-conflict");if(n.graphSource==="committed-epic-v1"&&n.graphRevision!==Yt(e.projectRoot,String(n.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");Cr(qe,K),qe=void 0;const N=zt(rt,"r");try{un(N)}finally{Jt(N)}}finally{if(qe)try{Mn(qe)}catch{}Jt(he),Mn(ve)}}function vn(e,t){if(!h(e))return;const i={};for(const r of t){const o=e[r];if(typeof o=="boolean")i[r]=o;else if(typeof o=="number"&&Number.isFinite(o))i[r]=o;else if(typeof o=="string"){const n=Q(o);n&&(i[r]=n)}}return Object.keys(i).length>0?i:void 0}function Cn(e){return e==="epic"||e==="story"?e:void 0}function ai(e){if(!h(e)||e.schemaVersion!==1)return;const t=q(e.ownerStoryId),i=q(e.sessionId),r=q(e.idempotencyKey),o=De(e.acquiredAt),n=De(e.expiresAt);if(!(!t||!i||!r||!o||!n||Date.parse(n)<=Date.parse(o)))return{schemaVersion:1,ownerStoryId:t,sessionId:i,idempotencyKey:r,acquiredAt:o,expiresAt:n}}function ci(e){if(!h(e)||e.schemaVersion!==1)return;const t=q(e.storyId),i=q(e.epicId),r=Ie(e.branch),o=R(e.baseSha),n=R(e.headSha),a=q(e.idempotencyKey),d=De(e.recordedAt),s=de(e.commits).map(R).filter(M=>!!M).slice(0,256),l=de(e.receiptRefs).map(pt).filter(M=>!!M).slice(0,256),m=e.dispatchId===void 0?void 0:q(e.dispatchId),S=e.bundleId===void 0?void 0:q(e.bundleId),u=e.bundleDigest===void 0?void 0:R(e.bundleDigest),v=e.graphRevision===void 0?void 0:R(e.graphRevision),I=e.claimRevision===void 0?void 0:q(e.claimRevision),g=oc(e.qaReceipt),E=ac(e.reviewReceipt),x=e.rootMemoryEffect===void 0?void 0:va(e.rootMemoryEffect)?e.rootMemoryEffect:void 0;if(!(!t||!i||!t.startsWith(`${i}.`)||!r||!o||!n||o===n||!a||!d||s.length===0||l.length===0||!Array.isArray(e.commits)||s.length!==e.commits.length||e.commits.length>256||!Array.isArray(e.receiptRefs)||l.length!==e.receiptRefs.length||e.receiptRefs.length>256||e.dispatchId!==void 0&&!m||e.bundleId!==void 0&&!S||e.bundleDigest!==void 0&&(!u||u.length!==64)||e.graphRevision!==void 0&&(!v||v.length!==64)||e.claimRevision!==void 0&&!I||e.rootMemoryEffect!==void 0&&(!x||x.storyId!==t||x.epicId!==i||x.executionBranch!==r||x.sourceHeadSha!==o||x.childClaimRevision!==I)||e.qaVerdict!=="passed"&&e.qaVerdict!=="blocked"||!["approved","changes-requested","pending"].includes(String(e.reviewVerdict))||!g||e.reviewVerdict!=="pending"&&!E||e.reviewVerdict==="pending"&&E||g.verdict!==e.qaVerdict||E&&E.verdict!==e.reviewVerdict||!pi(g,{storyId:t,epicId:i,baseSha:o,headSha:n,bundleDigest:u,graphRevision:v})||E&&(!pi(E,{storyId:t,epicId:i,baseSha:o,headSha:n,bundleDigest:u,graphRevision:v})||E.qaReceiptRef!==g?.receiptRef||E.receiptRef===g?.receiptRef)||!l.includes(String(g.receiptRef))||E&&(!l.includes(String(E.receiptRef))||Date.parse(String(E.reviewedAt))<Date.parse(String(g.checkedAt)))))return{schemaVersion:1,storyId:t,epicId:i,branch:r,baseSha:o,headSha:n,idempotencyKey:a,...m?{dispatchId:m}:{},...S?{bundleId:S}:{},...u?{bundleDigest:u}:{},...v?{graphRevision:v}:{},...I?{claimRevision:I}:{},...x?{rootMemoryEffect:structuredClone(x)}:{},qaVerdict:e.qaVerdict,reviewVerdict:e.reviewVerdict,...g?{qaReceipt:g}:{},...E?{reviewReceipt:E}:{},recordedAt:d,commits:s,receiptRefs:l}}function oc(e){if(!h(e)||e.schemaVersion!==1||e.kind!=="story_qa_evidence"||e.producer!=="local-yolo-tdd"||e.evidenceVersion!==void 0&&e.evidenceVersion!=="git-immutable-v1"&&e.evidenceVersion!=="p205-execution-v2"||!["passed","blocked"].includes(String(e.verdict)))return;const t=q(e.storyId),i=q(e.epicId),r=R(e.baseSha),o=R(e.headSha),n=R(e.bundleDigest),a=R(e.graphRevision),d=R(e.sourceEvidenceDigest),s=De(e.checkedAt),l=pt(e.receiptRef),m=e.evidenceVersion==="p205-execution-v2"&&e.contract==="P205-CI-02"?e.contract:void 0,S=e.evidenceVersion==="p205-execution-v2"&&e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,u=e.evidenceVersion==="p205-execution-v2"?R(e.manifestDigest):void 0,v=e.evidenceVersion==="p205-execution-v2"?R(e.resultDigest):void 0,I=e.evidenceVersion==="p205-execution-v2"?de(e.gateIds).map(q).filter(g=>!!g).slice(0,64):void 0;if(!(!t||!i||!r||!o||!n||n.length!==64||!a||a.length!==64||!d||d.length!==64||!s||!l||e.evidenceVersion==="p205-execution-v2"&&(!m||S!=="node scripts/test-root.mjs --gate complete"||!u||u.length!==64||!v||v.length!==64||!Array.isArray(e.gateIds)||!I||I.length===0||I.length!==e.gateIds.length)))return{schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",...e.evidenceVersion?{evidenceVersion:e.evidenceVersion}:{},storyId:t,epicId:i,...e.evidenceVersion==="p205-execution-v2"?{contract:m,command:S,manifestDigest:u,gateIds:I,resultDigest:v}:{},baseSha:r,headSha:o,bundleDigest:n,graphRevision:a,sourceEvidenceDigest:d,verdict:e.verdict,checkedAt:s,receiptRef:l}}function si(e){if(!h(e)||e.schemaVersion!==1||e.kind!=="story_checkpoint_physical_verification"||e.producer!=="client-p205-transient-v1"||e.publicSafe!==!0||e.verdict!=="verified"&&e.verdict!=="rejected")return;const t=q(e.storyId),i=q(e.epicId),r=Ie(e.branch),o=R(e.baseSha),n=R(e.headSha),a=R(e.aggregateHeadSha),d=R(e.commitBodyDigest),s=R(e.changedPathsDigest),l=e.claimVerification==="canonical"||e.claimVerification==="legacy-migration"?e.claimVerification:void 0,m=R(e.effectiveClaimRevision),S=e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,u=R(e.manifestDigest),v=de(e.gateIds).map(q).filter(k=>!!k).slice(0,64),I=R(e.resultDigest),g=R(e.graphRevision),E=R(e.executionEvidenceDigest),x=R(e.sourceEvidenceDigest),M=De(e.verifiedAt),P=de(e.reasonCodes).map(q).filter(k=>!!k).slice(0,16);if(!(!t||!i||!r||!o||o.length<40||!n||n.length<40||!a||a.length<40||!d||d.length!==64||!s||s.length!==64||!l||!m||m.length!==64||!S||!u||u.length!==64||!Array.isArray(e.gateIds)||v.length!==e.gateIds.length||!I||I.length!==64||!g||g.length!==64||!E||E.length!==64||!x||x.length!==64||!M||P.length===0||e.verdict==="verified"&&(v.length===0||!P.includes("checkpoint-p205-transient-verified"))))return{schemaVersion:1,kind:"story_checkpoint_physical_verification",producer:"client-p205-transient-v1",storyId:t,epicId:i,branch:r,baseSha:o,headSha:n,aggregateHeadSha:a,commitBodyDigest:d,changedPathsDigest:s,claimVerification:l,effectiveClaimRevision:m,command:S,manifestDigest:u,gateIds:v,resultDigest:I,graphRevision:g,executionEvidenceDigest:E,sourceEvidenceDigest:x,verifiedAt:M,verdict:e.verdict,reasonCodes:P,publicSafe:!0}}function di(e){const t=["schemaVersion","kind","producer","storyId","epicId","branch","baseSha","headSha","graphRevision","effectiveClaimRevision","sourceEvidenceDigest","verifiedAt","reasonCodes","integrationAuthorized","publicSafe"];if(!h(e)||Object.keys(e).some(u=>!t.includes(u))||e.schemaVersion!==1||e.kind!=="story_scheduling_checkpoint_evidence"||e.producer!=="client-git-physical-v1"||e.integrationAuthorized!==!1||e.publicSafe!==!0)return;const i=q(e.storyId),r=q(e.epicId),o=Ie(e.branch),n=R(e.baseSha),a=R(e.headSha),d=R(e.graphRevision),s=R(e.effectiveClaimRevision),l=R(e.sourceEvidenceDigest),m=De(e.verifiedAt),S=de(e.reasonCodes).map(q).filter(u=>!!u);if(!(!i||!r||!o||!n||n.length<40||!a||a.length<40||!d||d.length!==64||!s||s.length!==64||!l||l.length!==64||!m||!Array.isArray(e.reasonCodes)||S.length!==1||S[0]!=="checkpoint-git-scheduling-verified"))return{schemaVersion:1,kind:"story_scheduling_checkpoint_evidence",producer:"client-git-physical-v1",storyId:i,epicId:r,branch:o,baseSha:n,headSha:a,graphRevision:d,effectiveClaimRevision:s,sourceEvidenceDigest:l,verifiedAt:m,reasonCodes:S,integrationAuthorized:!1,publicSafe:!0}}function ac(e){if(!h(e)||e.schemaVersion!==1||e.kind!=="story_review_evidence"||e.producer!=="root-commit-range-review"||!["approved","changes-requested"].includes(String(e.verdict)))return;const t=q(e.storyId),i=q(e.epicId),r=R(e.baseSha),o=R(e.headSha),n=R(e.bundleDigest),a=R(e.graphRevision),d=R(e.sourceEvidenceDigest),s=pt(e.qaReceiptRef),l=De(e.reviewedAt),m=pt(e.receiptRef);if(!(!t||!i||!r||!o||!n||n.length!==64||!a||a.length!==64||!d||d.length!==64||!s||!l||!m))return{schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:t,epicId:i,baseSha:r,headSha:o,bundleDigest:n,graphRevision:a,sourceEvidenceDigest:d,qaReceiptRef:s,verdict:e.verdict,reviewedAt:l,receiptRef:m}}function pi(e,t){return["storyId","epicId","baseSha","headSha","bundleDigest","graphRevision"].every(i=>e[i]===t[i])}function li(e){if(!h(e))return;const t=e.schemaVersion===1&&e.capturedFromCurrentCheckout===!0&&e.capturedFrom===void 0,i=e.schemaVersion===2&&e.capturedFromCurrentCheckout===void 0&&(e.capturedFrom==="current-checkout"||e.capturedFrom==="branch-ref");if(!t&&!i)return;const r=Ie(e.originBranch),o=R(e.originHeadSha),n=Ie(e.executionBranch),a=De(e.capturedAt);if(!(!r||!o||o.length<40||!n||!a||r===n))return t?{schemaVersion:1,originBranch:r,originHeadSha:o,executionBranch:n,capturedFromCurrentCheckout:!0,capturedAt:a}:{schemaVersion:2,originBranch:r,originHeadSha:o,executionBranch:n,capturedFrom:e.capturedFrom,capturedAt:a}}function ui(e){if(!h(e)||e.schemaVersion!==1||e.verdict!=="passed")return;const t=R(e.executionHeadSha),i=R(e.graphRevision),r=De(e.checkedAt),o=pt(e.receiptRef),n=de(e.gateIds).map(q).filter(m=>!!m).slice(0,128),a=e.evidenceVersion==="p205-execution-v2"&&e.producer==="local-yolo-tdd"&&e.contract==="P205-CI-02"&&e.command==="node scripts/test-root.mjs --gate complete",d=e.evidenceVersion===void 0&&e.producer===void 0&&e.contract===void 0&&e.command===void 0&&e.manifestDigest===void 0&&e.resultDigest===void 0,s=a?R(e.manifestDigest):void 0,l=a?R(e.resultDigest):void 0;if(!(!t||t.length<40||!i||i.length!==64||!r||!o||n.length===0||!Array.isArray(e.gateIds)||n.length!==e.gateIds.length||e.gateIds.length>128||!d&&!a||a&&(!s||s.length!==64||!l||l.length!==64)))return{schemaVersion:1,...a?{evidenceVersion:"p205-execution-v2",producer:"local-yolo-tdd",contract:"P205-CI-02",command:"node scripts/test-root.mjs --gate complete",manifestDigest:s,resultDigest:l}:{},verdict:"passed",executionHeadSha:t,graphRevision:i,checkedAt:r,receiptRef:o,gateIds:n}}const cc=16384;function sc(e){if(!h(e))return;const t=(r,o)=>r===null||typeof r=="boolean"?!0:typeof r=="number"?Number.isFinite(r):typeof r=="string"?r.length<=512&&!r.startsWith("/")&&!/^[A-Za-z]:[\\/]/.test(r)&&!r.includes("\\")&&!/:\/\//.test(r)&&!/[\u0000-\u001f]/.test(r):o>=4?!1:Array.isArray(r)?r.length<=256&&r.every(n=>t(n,o+1)):h(r)?Object.keys(r).length<=64&&Object.entries(r).every(([n,a])=>/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(n)&&t(a,o+1)):!1;if(!t(e,0))return;const i=JSON.stringify(e);if(!(Buffer.byteLength(i,"utf8")>cc))return JSON.parse(i)}function hi(e){if(!h(e)||e.schemaVersion!==1||e.kind!=="epic_head_reconciliation"||e.producer!=="client-p205-head-reconciliation-v1"||e.publicSafe!==!0)return;const t={schemaVersion:1,kind:"epic_head_reconciliation",producer:"client-p205-head-reconciliation-v1",epicId:q(e.epicId),executionBranch:Ie(e.executionBranch),originBranch:Ie(e.originBranch),graphRevision:R(e.graphRevision),originHeadSha:R(e.originHeadSha),lastAcceptedCheckpointHeadSha:R(e.lastAcceptedCheckpointHeadSha),executionHeadSha:R(e.executionHeadSha),acceptedCheckpointIds:de(e.acceptedCheckpointIds),acceptedCheckpointHeads:de(e.acceptedCheckpointHeads),reconciliationCommitShas:de(e.reconciliationCommitShas),commitRangeDigest:R(e.commitRangeDigest),changedPaths:de(e.changedPaths),changedPathsDigest:R(e.changedPathsDigest),allowedWriteSet:de(e.allowedWriteSet),allowedWriteSetDigest:R(e.allowedWriteSetDigest),aggregateReceiptRef:pt(e.aggregateReceiptRef),aggregateManifestDigest:R(e.aggregateManifestDigest),aggregateResultDigest:R(e.aggregateResultDigest),producedAt:De(e.producedAt),revalidatedAt:De(e.revalidatedAt),publicSafe:!0},i=["originSyncHeadSha","originSyncCommitShas","originSyncPaths","originSyncPathsDigest","originSyncResolvedPaths","originSyncResolvedPathsDigest"],r=i.filter(d=>e[d]!==void 0).length;if(r!==0&&r!==i.length)return;const o=r===0?void 0:{originSyncHeadSha:R(e.originSyncHeadSha),originSyncCommitShas:de(e.originSyncCommitShas),originSyncPaths:de(e.originSyncPaths),originSyncPathsDigest:R(e.originSyncPathsDigest),originSyncResolvedPaths:de(e.originSyncResolvedPaths),originSyncResolvedPathsDigest:R(e.originSyncResolvedPathsDigest)};if(o&&(!o.originSyncHeadSha||o.originSyncHeadSha.length<40||o.originSyncCommitShas.length===0||o.originSyncCommitShas.length>256||o.originSyncCommitShas.some(d=>!/^[a-f0-9]{40,64}$/i.test(d))||o.originSyncPaths.length>2048||o.originSyncResolvedPaths.length>64||o.originSyncPathsDigest!==fn(o.originSyncPaths)||o.originSyncResolvedPathsDigest!==fn(o.originSyncResolvedPaths))||!t.epicId||!t.executionBranch||!t.originBranch||!t.graphRevision||t.graphRevision.length!==64||!t.originHeadSha||t.originHeadSha.length<40||!t.lastAcceptedCheckpointHeadSha||t.lastAcceptedCheckpointHeadSha.length<40||!t.executionHeadSha||t.executionHeadSha.length<40||t.acceptedCheckpointIds.length===0||t.acceptedCheckpointIds.length>2048||t.acceptedCheckpointIds.length!==t.acceptedCheckpointHeads.length||t.acceptedCheckpointHeads.some(d=>!/^[a-f0-9]{40,64}$/i.test(d))||t.reconciliationCommitShas.length>2048||t.reconciliationCommitShas.some(d=>!/^[a-f0-9]{40,64}$/i.test(d))||t.changedPaths.length>2048||(t.lastAcceptedCheckpointHeadSha===t.executionHeadSha?t.reconciliationCommitShas.length!==0||t.changedPaths.length!==0:t.reconciliationCommitShas.length===0||t.changedPaths.length===0)||t.allowedWriteSet.length===0||t.allowedWriteSet.length>2048||!t.commitRangeDigest||!t.changedPathsDigest||!t.allowedWriteSetDigest||!t.aggregateReceiptRef||!t.aggregateManifestDigest||!t.aggregateResultDigest||!t.producedAt||!t.revalidatedAt||t.commitRangeDigest!==ca(t.lastAcceptedCheckpointHeadSha,t.executionHeadSha,t.reconciliationCommitShas)||t.changedPathsDigest!==fn(t.changedPaths)||t.allowedWriteSetDigest!==fn(t.allowedWriteSet))return;const n={...t,...o??{}},a=R(e.inputDigest);if(!(!a||a.length!==64||a!==aa(n)))return{...n,inputDigest:a}}function Xn(e){if(!h(e)||e.schemaVersion!==1)return;const t=vn(e,["schemaVersion","kind","storyId","epicId","baseSha","headSha","originalBaseSha","originalHeadSha","gitPullRequest","preservesLaterCommits","historyRewrite","recordedAt"])??{},i=de(e.receiptRefs).map(pt).filter(o=>!!o).slice(0,256),r=de(e.revertCommits).map(Q).filter(o=>!!o).slice(0,256);return{...t,...i.length?{receiptRefs:i}:{},...r.length?{revertCommits:r}:{}}}function dc(e){if(!(!h(e)||Object.keys(e).sort().join(",")!=="gitPullRequest,headSha,kind,prNumber,reviewEvidenceDigest,schemaVersion"||e.schemaVersion!==1||e.kind!=="git-pull-request"||e.gitPullRequest!==!0||!Number.isSafeInteger(e.prNumber)||Number(e.prNumber)<=0||typeof e.headSha!="string"||!/^[a-f0-9]{40}$/.test(e.headSha)||typeof e.reviewEvidenceDigest!="string"||!/^[a-f0-9]{64}$/.test(e.reviewEvidenceDigest)))return{schemaVersion:1,kind:"git-pull-request",gitPullRequest:!0,prNumber:e.prNumber,headSha:e.headSha,reviewEvidenceDigest:e.reviewEvidenceDigest}}function gi(e){if(!h(e)||e.schemaVersion!==1||e.publicSafe!==!0)return;const t=q(e.epicId),i=Ie(e.executionBranch),r=Ie(e.originBranch),o=R(e.baseSha),n=R(e.executionHeadSha),a=e.mergeSha===void 0?void 0:R(e.mergeSha),d=e.pushedSha===void 0?void 0:R(e.pushedSha),s=q(e.idempotencyKey),l=De(e.attemptStartedAt),m=e.completedAt===void 0?void 0:De(e.completedAt),S=de(e.localGateReceiptRefs).map(pt).filter(g=>!!g).slice(0,256),u=de(e.reasonCodes).map(q).filter(g=>!!g).slice(0,64),v=lc(e.candidateQa),I=pc(e.providerGuard);if(!(!t||!i||!r||!o||!n||!s||!l||S.length===0||u.length===0||!["direct","single_pr"].includes(String(e.strategy))||!["prepared","merged","pushed","denied_external_gate","blocked_local_or_repo"].includes(String(e.physicalStatus))||typeof e.retryEligible!="boolean"||e.providerGuard!==void 0&&!I||I&&(e.strategy!=="single_pr"||e.physicalStatus!=="pushed"||I.prHeadSha!==a||I.originHeadSha!==o)))return{schemaVersion:1,epicId:t,executionBranch:i,originBranch:r,baseSha:o,executionHeadSha:n,...a?{mergeSha:a}:{},...d?{pushedSha:d}:{},strategy:e.strategy,..._t(e.prNumber)?{prNumber:_t(e.prNumber)}:{},physicalStatus:e.physicalStatus,localGateReceiptRefs:S,idempotencyKey:s,attemptStartedAt:l,...v?{candidateQa:v}:{},...I?{providerGuard:I}:{},...m?{completedAt:m}:{},retryEligible:e.retryEligible,reasonCodes:u,publicSafe:!0}}function pc(e){if(!h(e)||e.schemaVersion!==1||e.provider!=="github"||e.publicSafe!==!0)return;const t=String(e.mode),i=String(e.source),r=t==="recovered_exact_tree"?i==="physical_recovery":t==="strict_up_to_date_expected_head"&&["branch_protection","ruleset","branch_protection_and_ruleset"].includes(i),o=R(e.prHeadSha),n=R(e.originHeadSha),a=De(e.checkedAt);if(!(!r||!o||!n||!a))return{schemaVersion:1,provider:"github",mode:t,source:i,prHeadSha:o,originHeadSha:n,checkedAt:a,publicSafe:!0}}function lc(e){if(!h(e)||e.schemaVersion!==1||e.kind!=="epic_merge_candidate_qa"||e.contract!=="P205-CI-02"||e.command!==Xt)return;const i=Object.fromEntries(["originHeadSha","executionHeadSha","mergeSha","treeSha","graphRevision","manifestDigest","resultDigest"].map(a=>[a,R(e[a])])),r=De(e.checkedAt),o=pt(e.receiptRef),n=de(e.gateIds).filter(a=>/^[a-z0-9-]+$/.test(a)).slice(0,128);if(!(Object.values(i).some(a=>!a)||!r||!o||n.length===0))return{schemaVersion:1,kind:e.kind,contract:e.contract,command:e.command,...i,checkedAt:r,receiptRef:o,gateIds:n}}function uc(e){if(!h(e))return;const t={...Q(e.active_epic_id??e.activeEpicId)?{active_epic_id:Q(e.active_epic_id??e.activeEpicId)}:{},...Q(e.active_story_id??e.activeStoryId)?{active_story_id:Q(e.active_story_id??e.activeStoryId)}:{},...Q(e.active_step_id??e.activeStepId)?{active_step_id:Q(e.active_step_id??e.activeStepId)}:{},...Q(e.session_id??e.sessionId)?{session_id:Q(e.session_id??e.sessionId)}:{},...Q(e.started_at??e.startedAt)?{started_at:Q(e.started_at??e.startedAt)}:{}};return Object.keys(t).length>0?t:void 0}function hc(e){const t=vn(e.completionEvidence??e.completion_evidence,["prNumber","pr_number","prState","pr_state","pullRequestState","merged","mergedAt","issueNumber","issue_number","issueState","issue_state","closedAt"]),i=vn(e.issueCloseAudit??e.issue_close_audit,["schema_version","event","storyId","epicId","issueNumber","closedAt","publicSafe","rawLogStorage"]),r=vn(e.scopedCiEvidence??e.scoped_ci_evidence,["schema_version","storyId","epicId","prNumber","finalState","publicSafe","rawLogStorage"]);return{...typeof e.merged=="boolean"?{merged:e.merged}:{},...typeof e.safeToContinueYoloop=="boolean"?{safeToContinueYoloop:e.safeToContinueYoloop}:{},...typeof e.mergeBlockedRemotely=="boolean"?{mergeBlockedRemotely:e.mergeBlockedRemotely}:{},...Q(e.physicalMergeStatus)?{physicalMergeStatus:Q(e.physicalMergeStatus)}:{},...Q(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)?{pr_state:Q(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)}:{},...Q(e.issue_state??e.issueState??e.workflow_issue_state)?{issue_state:Q(e.issue_state??e.issueState??e.workflow_issue_state)}:{},..._t(e.issue_number??e.issueNumber)?{issue_number:_t(e.issue_number??e.issueNumber)}:{},...t?{completionEvidence:t}:{},...i?{issueCloseAudit:i}:{},...r?{scopedCiEvidence:r}:{}}}class lt extends Error{reasonCode;constructor(t){super(t),this.name="StateSnapshotIntegrityError",this.reasonCode=t}}const gc=new Set(["yolo","yoloop","finalize-epic","audit"]),fc=8;function mc(e){return/docs\/epics\/epic-(P[1-9][0-9]*)\.md\b/.exec(e)?.[1]??/docs\/stories\/(P[1-9][0-9]*)\.[0-9]+\.story\.md\b/.exec(e)?.[1]}function yc(e,t={},i={},r){const o=d=>{try{return String(Be("git",[...d],{cwd:e,stdio:["ignore","pipe","ignore"],timeout:1e4,encoding:"utf8"})).trim()}catch{return}};if(o(["rev-parse","--is-inside-work-tree"])!=="true")return;const n=[],a=Object.entries(t).sort(([d],[s])=>+(s===r)-+(d===r));for(const[d,s]of a){if(n.length>=fc)break;if(!h(s)||!h(s.origin_binding))continue;const l=s.execution_branch,m=s.origin_binding;if(typeof l!="string"||m.executionBranch!==l||typeof m.originHeadSha!="string"||!/^[a-f0-9]{40,64}$/.test(m.originHeadSha)||!/^[A-Za-z0-9][A-Za-z0-9._/-]{0,239}$/.test(l)||l.includes(".."))continue;const S=o(["rev-parse","--verify","--quiet",`refs/heads/${l}^{commit}`]);if(!S||!/^[a-f0-9]{40,64}$/.test(S)||o(["merge-base","--is-ancestor",m.originHeadSha,S])===void 0)continue;const u=[];for(const v of Object.values(i)){if(u.length>=128)break;if(!h(v)||(v.epic_id??v.epic)!==d)continue;const I=h(v.checkpoint)&&typeof v.checkpoint.headSha=="string"?v.checkpoint.headSha:h(v.scheduling_checkpoint_evidence)&&typeof v.scheduling_checkpoint_evidence.headSha=="string"?v.scheduling_checkpoint_evidence.headSha:void 0;!I||!/^[a-f0-9]{40,64}$/.test(I)||u.includes(I)||o(["merge-base","--is-ancestor",I,S])!==void 0&&u.push(I)}n.push(Object.freeze({epicId:d,executionBranch:l,originHeadSha:m.originHeadSha,executionHeadSha:S,...u.length>0?{containedHeadShas:Object.freeze(u)}:{}}))}return Object.freeze({schemaVersion:1,stateFileTracked:o(["ls-files","--error-unmatch","--",".neocortex/state.json"])!==void 0,...n.length>0?{executionBases:Object.freeze(n)}:{}})}function fi(e){return typeof e=="string"&&gc.has(e)}function Zn(e,t={}){const i=z(e,".neocortex","state.json");if(!jt(i))throw new lt("git-lifecycle-state-missing");let r;try{r=JSON.parse(Fe(i,"utf8"))}catch{throw new lt("git-lifecycle-state-corrupt")}if(!h(r)||!h(r.epics)||!h(r.stories))throw new lt("git-lifecycle-state-shape-invalid");const o=Object.values(r.epics).some(n=>h(n)&&(n.branch_mode==="epic"||Ie(n.execution_branch)!==void 0));if(o)try{mn(e,{required:!0})}catch(n){const a=n instanceof Error&&/^git-lifecycle-/.test(n.message)?n.message:"git-lifecycle-runtime-invalid";if(t.allowMissingRuntime&&a==="git-lifecycle-runtime-missing")return{lifecycleDeclared:!0,runtimeMissing:!0};throw new lt(a)}return{lifecycleDeclared:o,runtimeMissing:!1}}function _n(e,t={}){const i=z(e,".neocortex","state.json");if(!jt(i)){if(t.epicAware&&!t.projectless)throw new lt("git-lifecycle-state-missing");return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}let r,o;try{const I=Fe(i,"utf-8");o=Ne("sha256").update(I).digest("hex");const g=vo(e,o)??JSON.parse(I),E=h(g.epics)?g.epics:{},x=Object.values(E).some(w=>h(w)&&(w.branch_mode==="epic"||Ie(w.execution_branch)!==void 0)),M=mn(e,{required:!!(t.epicAware&&x&&!t.projectless)});r=Ur(g,M);const P=h(r.stories)?r.stories:{},k=h(r.epics)?r.epics:{},_=h(g.stories)?g.stories:{};for(const[w,L]of Object.entries(P)){const D=h(L)?L:void 0;if(!D?.checkpoint)continue;const Y=typeof D.epic_id=="string"?D.epic_id:w.split(".")[0],X=h(k[Y])?k[Y]:void 0,pe=Ie(X?.execution_branch);if(!pe)continue;const b=sa(e,D.checkpoint,w,Y,pe,t.p205Authorities?.[w],$r(w,D,h(D.checkpoint)?D.checkpoint:void 0));if(b.kind==="integration-authorized")D.checkpoint_verification=b.verification,delete D.scheduling_checkpoint_evidence;else if(b.kind==="scheduling-only")D.scheduling_checkpoint_evidence=b.evidence,delete D.checkpoint,delete D.checkpoint_verification;else if(b.kind==="rejected"){D.checkpoint_verification=b.verification,delete D.scheduling_checkpoint_evidence;const Se=h(_[w])?_[w]:void 0;if(delete D.checkpoint,M.stories[w]?.checkpoint!==void 0)for(const Z of["status","last_step","steps_completed"])Se&&Object.prototype.hasOwnProperty.call(Se,Z)?D[Z]=structuredClone(Se[Z]):delete D[Z];["done","completed","merged"].includes(String(D.status).toLowerCase())&&(D.status="blocked")}}}catch(I){if(t.epicAware&&!t.projectless){const g=I instanceof Error&&/^git-lifecycle-/.test(I.message)?I.message:"git-lifecycle-state-corrupt";throw new lt(g)}return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}try{const I=Qa(r);I.length>0&&Xa(I)}catch{}const n=r.config??r.project??{},a=r.stories??{},d={};for(const[I,g]of Object.entries(a)){const E=h(g.review_request)&&g.review_request.kind==="git-pull-request"?dc(g.review_request):Xn(g.review_request);d[I]={id:g.id??I,title:g.title,epic_id:g.epic_id,status:g.status??"backlog",...oi(g.source)?{source:oi(g.source)}:{},steps_completed:g.steps_completed??[],last_step:g.last_step??null,branch_name:g.branch_name??null,pr_number:g.pr_number,...Cn(g.branch_mode)?{branch_mode:Cn(g.branch_mode)}:{},...ci(g.checkpoint)?{checkpoint:ci(g.checkpoint)}:{},...si(g.checkpoint_verification)?{checkpoint_verification:si(g.checkpoint_verification)}:{},...di(g.scheduling_checkpoint_evidence)?{scheduling_checkpoint_evidence:di(g.scheduling_checkpoint_evidence)}:{},...E?{review_request:E}:{},...Xn(g.rollback_receipt)?{rollback_receipt:Xn(g.rollback_receipt)}:{},..._t(g.workflow_issue)?{workflow_issue:_t(g.workflow_issue)}:{},...hc(g),...Array.isArray(g.depends_on)?{depends_on:ii(g.depends_on)}:{},files_to_modify:de(g.files_to_modify),...rc(g),risk:typeof g.risk=="string"?g.risk:void 0,blast_radius:typeof g.blast_radius=="number"?g.blast_radius:void 0}}const s=r.epics??{},l={};for(const[I,g]of Object.entries(s)){const E=Za(g.lifecycle_classification),x=nc(g.createEpicPlanning,I),M=x.checkpoint;let P,k,_,w;if(M&&h(g.createEpicPlanningClaim)&&typeof g.createEpicPlanningClaim.claimId=="string"&&h(g.createEpicPlanningPhysical))try{_r(r,g.createEpicPlanningClaim.claimId,I,!0),P=JSON.parse(JSON.stringify(g.createEpicPlanningPhysical))}catch{}if(P&&h(g.createEpicPlanningClaim)&&typeof g.createEpicPlanningClaim.claimId=="string"&&h(g.createEpicPlanningResearchPhysical))try{Rr(r,g.createEpicPlanningClaim.claimId,I),k=JSON.parse(JSON.stringify(g.createEpicPlanningResearchPhysical))}catch{}if(t.verifyPlanningGeneration&&M&&g.status==="generated"&&h(g.createEpicPlanningClaim)&&typeof g.createEpicPlanningClaim.claimId=="string"&&h(g.createEpicPlanningGenerationPhysical))try{if(oo(e,g.createEpicPlanningClaim.claimId,I).stateSha256!==o)throw new Error("planning-generation-snapshot-raced");_=JSON.parse(JSON.stringify(g.createEpicPlanningGenerationPhysical)),P=JSON.parse(JSON.stringify(g.createEpicPlanningPhysical)),k=JSON.parse(JSON.stringify(g.createEpicPlanningResearchPhysical))}catch{}if(_&&h(g.createEpicPlanningClaim)&&typeof g.createEpicPlanningClaim.claimId=="string")try{const L=wr(e,g.createEpicPlanningClaim.claimId,I);if(L.stateSha256!==o)throw new Error("planning-memory-snapshot-raced");w=JSON.parse(JSON.stringify(L))}catch{}l[I]={id:g.id??I,title:g.title,...M?{createEpicPlanning:M}:{},...x.diagnostic?{createEpicPlanningProjection:x.diagnostic}:{},...P?{createEpicPlanningPhysical:P}:{},...k?{createEpicPlanningResearchPhysical:k}:{},..._?{createEpicPlanningGenerationPhysical:_}:{},...w?{createEpicPlanningMemoryPhysical:w}:{},status:g.status,stories:g.stories,total_stories:g.total_stories,completed_stories:g.completed_stories,depends_on:ii(g.depends_on),...Cn(g.branch_mode)?{branch_mode:Cn(g.branch_mode)}:{},...Ie(g.execution_branch)?{execution_branch:Ie(g.execution_branch)}:{},...Ie(g.origin_branch)?{origin_branch:Ie(g.origin_branch)}:{},...ai(g.branch_lease)?{branch_lease:ai(g.branch_lease)}:{},...li(g.origin_binding)?{origin_binding:li(g.origin_binding)}:{},...ui(g.aggregate_qa_receipt)?{aggregate_qa_receipt:ui(g.aggregate_qa_receipt)}:{},...hi(g.head_reconciliation_receipt)?{head_reconciliation_receipt:hi(g.head_reconciliation_receipt)}:{},...ya(g.story_worktree_evidence)?{story_worktree_evidence:structuredClone(g.story_worktree_evidence)}:{},...(L=>L?{branch_mode_conversion_receipt:L}:{})(sc(g.branch_mode_conversion_receipt)),..._t(g.pr_number)?{pr_number:_t(g.pr_number)}:{},...Q(g.physicalMergeStatus)?{physicalMergeStatus:Q(g.physicalMergeStatus)}:{},...R(g.graph_revision)?{graph_revision:R(g.graph_revision)}:{},...gi(g.terminal_git_receipt)?{terminal_git_receipt:gi(g.terminal_git_receipt)}:{},...E?{lifecycle_classification:E}:{}}}const m=uc(r.current_session??r.currentSession),S=h(r.archPlan)?Sn(r.archPlan.execution):void 0,u=r.epic_id_ledger,v=Array.isArray(u?.reserved_ids)?[...new Set(u.reserved_ids.filter(I=>typeof I=="string"&&/^P\d+$/.test(I)))].slice(0,2048):[];return{schema_version:typeof r.schema_version=="number"?r.schema_version:void 0,config:{project_name:n.project_name??n.name??"unknown",default_branch:n.default_branch??"main",language:n.language??"pt-BR",yolo_mode:n.yolo_mode,user_name:n.user_name,worktree_base:n.worktree_base,max_parallel_stories:n.max_parallel_stories,project_id:typeof n.project_id=="string"?n.project_id:void 0},stories:d,epics:l,...v.length>0?{epic_id_ledger:{schema_version:1,reserved_ids:v}}:{},...m?{current_session:m}:{},...S?{archPlan:{execution:S}}:{}}}const er=[["P222.01","fbc3176b33687b13a8fadf8c7ea7cc06b6b6c500"],["P222.02","c7d3feb9a168f9e15b35516a972c767f3aa357da"],["P222.03","4d9bd4f2a1a3a1dc6399c572eb84b8b74c017806"],["P222.04","66590ef2f706c9d036f42edf5e517b237724f74f"],["P222.05","3ee2662538311e9788796340ed11b65864a8d8d5"],["P222.06","8660d07e3f68503a9ceb24dc138d24f62ab6cb45"],["P222.07","d99c80feacee8ea4033aa3322990147fffa2df91"],["P222.08","1f9e37dc922d87908efefb9595db32d32db30b00"],["P222.09","5ae12e485900992658e346cf3e38568fda1c2eeb"],["P222.10","6c5b8dc4f03d629fea4b62a33f4794af8e27e4f0"],["P222.11","cfe90f2f955c0027c57e4c621141d17912db65cc"],["P222.12","65f253c5cb600a8ee1dd94a1efdfef2fa5cd1629"],["P222.13","1e78c75b393515803a55d1a9b63a7fec23f710c9"],["P222.14","3f3e0bfd247a8581170df2a23c89497b5ae3641e"],["P222.15","1fd6dd25fffa5714d4ffa8b4303735e417f93de6"]],tr="6a41a47ff2521f80c2296ed811b0f0b304c54750",nr="dbc6d4670b2b7868a01973b1240e24589f1c5b7d",mi="30dccfff07f9c969be11ae1d28e62a09731a0768";function Ec(e,t){try{const i=t.indexOf(mi);if(i<1||t[i-1]!==tr)return new Map;const r=Be("git",["show","--no-patch","--format=%P",mi],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim(),o=Be("git",["show","--no-patch","--format=%P",nr],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim();if(r!==`${tr} ${nr}`||o!==`${er.at(-1)[1]} ${tr}`)return new Map;const n=Be("git",["rev-list","--first-parent","--reverse",nr],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
|
|
9
|
-
`),a=new Map;let d=-1;for(const[s,[
|
|
10
|
-
`).filter(Boolean),
|
|
11
|
-
`),{}}}async function
|
|
12
|
-
`),
|
|
13
|
-
`),t}function
|
|
14
|
-
`)}async function
|
|
15
|
-
`:`[watch-status] status=${
|
|
16
|
-
`);return}if(t==="json"){
|
|
17
|
-
`);return}
|
|
18
|
-
`)}function
|
|
7
|
+
`)}catch{}}}function Zd(){Qn=!1}function ii(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function ec(e){return e==="active"||e==="archived"||e==="rolled-back"||e==="synthetic"||e==="orphan"?e:void 0}const tc=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"]),nc=/(?:[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 rc(e,t){if(!g(e)||e.schemaVersion!==1||e.epicId!==t||!/^P\d+$/.test(t))return{};try{const o=JSON.stringify(e),n=Buffer.byteLength(o);if(n>16384)return{diagnostic:Object.freeze({schemaVersion:"CreateEpicPlanningProjectionDiagnostic/1.0",outcome:"omitted",reasonCode:"budget-omitted",byteLengthBucket:n<=32768?"16385-32768":"32769-plus",publicSafe:!0})};if(nc.test(o))return{};const i=(a,d)=>{if(Object.keys(a).some(s=>!d.includes(s)))throw new Error("planning-unknown-field")};if(i(e,["schemaVersion","epicId","intake","intakeRevision","diagnosisReceipt","researchReceipt","degradeAuthorization"]),!g(e.intake))return{};if(Object.keys(e.intake).some(a=>!tc.has(a)))return{};for(const[a,d]of Object.entries(e.intake))if(["examples","contracts"].includes(a)){const s=a==="examples"?["id","title","actor","given","when","then","source","coveredRequirement","expectedValidation"]:["id","kind","description","path"];if(!Array.isArray(d)||d.length>16)return{};for(const u of d){if(!g(u))return{};if(i(u,s),Object.values(u).some(m=>typeof m!="string"||m.length>256))return{}}}else if(Array.isArray(d)){if(d.length>32||d.some(s=>typeof s!="string"||s.length>256))return{}}else if(typeof d=="string"){if(d.length>(a==="rawIntent"?co:512))return{}}else if(typeof d!="boolean"||!["uiScope","remediationStory"].includes(a))return{};const r=["schemaVersion","kind","epicId","intakeRevision","artifactSummary","artifactDigest","predecessorReceiptId","accepted","receiptId"];for(const a of[e.diagnosisReceipt,e.researchReceipt])if(a!==void 0){if(!g(a))return{};if(i(a,r),Object.values(a).some(d=>typeof d=="string"&&d.length>1024))return{}}if(e.degradeAuthorization!==void 0){if(!g(e.degradeAuthorization))return{};i(e.degradeAuthorization,["approved","intakeRevision","reasonCodes","assumptionCodes"]);for(const a of["reasonCodes","assumptionCodes"]){const d=e.degradeAuthorization[a];if(!Array.isArray(d)||d.length>32||d.some(s=>typeof s!="string"||s.length>128))return{}}}return{checkpoint:JSON.parse(o)}}catch{return{}}}function oi(e){return e==="create-epic"||e==="discovered"?e:void 0}function de(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function ai(e){if(!g(e))return;const t=/^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/;if(Object.keys(e).some(a=>!["epicId","storyId","integrationReceiptId","mergedCommit"].includes(a)))return;const n=a=>typeof a=="string"&&t.test(a)&&!a.includes("..");if(!n(e.epicId)||e.storyId!==void 0&&!n(e.storyId))return;const i=e.integrationReceiptId,r=e.mergedCommit;if(!(i===void 0&&r===void 0)&&!(i!==void 0&&(typeof i!="string"||!/^[A-Za-z0-9][A-Za-z0-9_-]{7,95}$/.test(i)))&&!(r!==void 0&&(typeof r!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(r))))return{epicId:e.epicId,...e.storyId!==void 0?{storyId:e.storyId}:{},...i!==void 0?{integrationReceiptId:i}:{},...r!==void 0?{mergedCommit:r}:{}}}function ic(e){const t={};let o=!1;for(const n of["contracts","contract_refs","shared_surfaces","adr_refs","nfr_refs","acceptance_depends_on"]){if(e[n]===void 0)continue;const i=e[n];if(!Array.isArray(i)||i.length>128||i.some(r=>gn(r)===void 0)){o=!0;continue}t[n]=i.map(r=>gn(r))}if(e.planning!==void 0)try{if(!g(e.planning))throw new Error("planning-shape");const n=e.planning;for(const a of["claims","semanticArtifacts"]){if(n[a]===void 0)continue;const d=n[a];if(!Array.isArray(d)||d.length>128||d.some(s=>!g(s)||gn(s.ref)===void 0))throw new Error("planning-refs")}if(n.attempts!==void 0&&(!Array.isArray(n.attempts)||n.attempts.length>32))throw new Error("planning-attempts");for(const a of n.attempts??[]){if(!g(a)||!Array.isArray(a.reasonCodes)||a.reasonCodes.length>32||a.reasonCodes.some(d=>typeof d!="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(d)))throw new Error("planning-attempt-reasons");if(a.discoveredClaims!==void 0&&(!Array.isArray(a.discoveredClaims)||a.discoveredClaims.length>128||a.discoveredClaims.some(d=>!g(d)||gn(d.ref)===void 0)))throw new Error("planning-attempt-claims")}const{graphRevision:i,...r}=aa(n);t.planning=r}catch{o=!0}return o&&(t.planning={schemaVersion:1,dependencyBasis:"unknown",claims:[],semanticArtifacts:[]}),t}function g(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function _t(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function X(e){if(typeof e!="string")return;const t=e.trim();if(t)return t.replace(/[^a-z0-9_.:-]+/gi,"_").slice(0,120)}function z(e){if(typeof e!="string")return;const t=e.trim(),o=X(e);return o===t?o:void 0}function Se(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240)&&/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(t)&&!(t.includes("..")||t.includes("//")||t.includes("@{")||t.endsWith("/")||t.endsWith("."))&&!t.split("/").some(o=>!o||o.startsWith(".")||o.endsWith(".lock")))return t}function R(e){return typeof e=="string"&&/^[0-9a-f]{7,64}$/i.test(e)?e:void 0}function De(e){if(!(typeof e!="string"||e.length>64)&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/.test(e))return Number.isFinite(Date.parse(e))?e:void 0}function pt(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240||t.includes("..")))return/^[A-Za-z0-9._:/#\-[\]]+$/.test(t)?t:void 0}function Sn(e){if(!g(e))return;const t=h=>typeof h=="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,95}$/.test(h),o=h=>typeof h=="string"&&/^[a-f0-9]{64}$/.test(h),n=(h,E)=>Array.isArray(h)&&h.length<=E&&h.every(t)&&new Set(h).size===h.length?h:void 0,i=(h,E)=>{if(!(!g(h)||h.schemaVersion!==2||!t(h.requestId)||!t(h.stageCommand)||!o(h.requestHash)||!o(h.inputHash)||!o(h.stateHash)||!o(h.nonce)||!o(h.stageRevision)||!o(h.stageHash)||!o(h.catalogHash)||h.targetEpicId!==void 0&&!t(h.targetEpicId)||E&&(!o(h.outputHash)||!o(h.artifactHash))))return{schemaVersion:2,...h.targetEpicId?{targetEpicId:h.targetEpicId}:{},requestId:h.requestId,requestHash:h.requestHash,inputHash:h.inputHash,stateHash:h.stateHash,nonce:h.nonce,stageCommand:h.stageCommand,stageRevision:h.stageRevision,stageHash:h.stageHash,catalogHash:h.catalogHash,...E?{outputHash:h.outputHash,artifactHash:h.artifactHash}:{}}},r=(h,E)=>{if(!(!g(h)||h.schemaVersion!=="1.1"||h.kind!==E||!o(h.receiptId)||!o(h.graphHash)||!o(h.evidenceHash)||!t(h.elementId)||!t(h.caseId)||!t(h.category)))return{schemaVersion:"1.1",kind:E,receiptId:h.receiptId,graphHash:h.graphHash,elementId:h.elementId,caseId:h.caseId,category:h.category,evidenceHash:h.evidenceHash}},a=(h,E)=>{if(!g(h)||h.kind!==E||!o(h.receiptId)||!n(h.evidenceIds,24)||E==="architecture-stage-completion"&&!["succeeded","failed"].includes(String(h.status))||E==="architecture-stage-validation"&&!["passed","failed","pending"].includes(String(h.status)))return;const _=i(h,!0);if(!_)return;const S=E==="architecture-stage-validation"?r(h.isolated,"isolated"):void 0,l=E==="architecture-stage-validation"?r(h.regression,"regression"):void 0;if(!(E==="architecture-stage-validation"&&(!S||!l)))return{..._,kind:E,receiptId:h.receiptId,status:h.status,evidenceIds:h.evidenceIds,...S&&l?{isolated:S,regression:l}:{}}},d={};e.schemaVersion===1&&(d.schemaVersion=1),e.owner==="root"&&(d.owner="root"),t(e.currentStageCommand)&&(d.currentStageCommand=e.currentStageCommand),["ask-user","delegate","resume","advance","blocked","complete"].includes(String(e.continuationState))&&(d.continuationState=e.continuationState);const s=n(e.questionIds,16);if(s&&(d.questionIds=s),(e.childStatus==="succeeded"||e.childStatus==="failed")&&(d.childStatus=e.childStatus),(e.evidencePolicy==="legacy-compatible"||e.evidencePolicy==="v2-required")&&(d.evidencePolicy=e.evidencePolicy),t(e.targetEpicId)&&(d.targetEpicId=e.targetEpicId),o(e.graphRevision)&&(d.graphRevision=e.graphRevision),e.graphSource==="committed-epic-v1"&&(d.graphSource=e.graphSource),e.nonUiScopeReceipt!==void 0){const h=Sr(e.nonUiScopeReceipt);if(!h||h.targetEpicId!==e.targetEpicId||h.graphRevision!==e.graphRevision||!g(e.accounting)||h.accountingId!==e.accounting.accountingId||!g(e.evidenceExpectation)||h.rootInputSha256!==e.evidenceExpectation.inputHash)throw new Error("architecture-non-ui-scope-invalid");d.nonUiScopeReceipt=h}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&&o(e.pactAnswerReceipt.stateSha256)&&o(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 u=i(e.evidenceExpectation,!1);u&&(d.evidenceExpectation=u);const m=a(e.completionEvidence,"architecture-stage-completion"),I=a(e.validationEvidence,"architecture-stage-validation");if(m&&(d.completionEvidence=m),I&&(d.validationEvidence=I),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&&o(e.reviewDecision.graphRevision)&&o(e.reviewDecision.artifactHash)&&o(e.reviewDecision.completionReceiptId)&&o(e.reviewDecision.validationReceiptId)&&["approved","changes-requested"].includes(String(e.reviewDecision.decision))&&e.reviewDecision.publicSafe===!0){const h=n(e.reviewDecision.evidenceIds,24);h&&h.length>0&&(d.reviewDecision={...e.reviewDecision,evidenceIds:h})}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 h=n(e.terminalMemoryCheckpoint.evidenceIds,24);h&&(d.terminalMemoryCheckpoint={status:e.terminalMemoryCheckpoint.status,evidenceIds:h})}if(Array.isArray(e.acceptedStages)&&e.acceptedStages.length<=15){const h=e.acceptedStages.map(E=>{if(!g(E)||!t(E.targetEpicId)||!t(E.stageCommand))return;const _=a(E.completionEvidence,"architecture-stage-completion"),S=a(E.validationEvidence,"architecture-stage-validation");return _&&S?{targetEpicId:E.targetEpicId,stageCommand:E.stageCommand,completionEvidence:_,validationEvidence:S}:void 0});h.every(E=>E!==void 0)&&(d.acceptedStages=h)}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 h=n(e.accounting.receiptIds,32);h&&(d.accounting={schemaVersion:1,contractVersion:e.accounting.contractVersion,accountingId:e.accounting.accountingId,charged:e.accounting.charged,chargedQuotaUnits:e.accounting.chargedQuotaUnits,receiptIds:h,...["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 oc(e){const t=g(e.metadata.archPlan)?e.metadata.archPlan.execution:void 0,o=g(t)?t.checkpoint:void 0,n=g(t)?t:void 0,i=g(o)?o:void 0,r=e.requestExecution,a=Array.isArray(i?.acceptedStages)?i.acceptedStages:[],d=r.currentStageCommand==="arch-prd"&&r.continuationState==="delegate"&&r.completionEvidence===void 0&&r.validationEvidence===void 0&&i?.currentStageCommand==="arch-prd"&&i.continuationState==="delegate"&&a.length===0&&n?.nextAction==="delegate",s=r.currentStageCommand==="arch-prd"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&i?.currentStageCommand==="arch-architecture"&&i.continuationState==="advance"&&a.length===1&&g(a[0])&&a[0].stageCommand==="arch-prd"&&v(a[0].completionEvidence,r.completionEvidence)&&v(a[0].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",u=r.currentStageCommand==="arch-architecture"&&r.continuationState==="advance"&&i?.currentStageCommand==="arch-architecture"&&i.continuationState==="delegate"&&a.length===1&&v(a,r.acceptedStages)&&n?.nextAction==="delegate",m=r.currentStageCommand==="arch-architecture"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&i?.currentStageCommand==="arch-fitness-functions"&&i.continuationState==="advance"&&a.length===2&&g(a[0])&&g(a[1])&&a[0].stageCommand==="arch-prd"&&a[1].stageCommand==="arch-architecture"&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===1&&v(a[0],r.acceptedStages[0])&&v(a[1].completionEvidence,r.completionEvidence)&&v(a[1].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",I=r.currentStageCommand==="arch-fitness-functions"&&r.continuationState==="advance"&&i?.currentStageCommand==="arch-fitness-functions"&&i.continuationState==="delegate"&&a.length===2&&g(a[0])&&g(a[1])&&a[0].stageCommand==="arch-prd"&&a[1].stageCommand==="arch-architecture"&&v(a,r.acceptedStages)&&n?.nextAction==="delegate",h=r.currentStageCommand==="arch-fitness-functions"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&i?.currentStageCommand==="arch-api-contracts"&&i.continuationState==="advance"&&a.length===3&&g(a[0])&&g(a[1])&&g(a[2])&&a[0].stageCommand==="arch-prd"&&a[1].stageCommand==="arch-architecture"&&a[2].stageCommand==="arch-fitness-functions"&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===2&&v(a.slice(0,2),r.acceptedStages)&&v(a[2].completionEvidence,r.completionEvidence)&&v(a[2].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",E=r.currentStageCommand==="arch-api-contracts"&&r.continuationState==="advance"&&i?.currentStageCommand==="arch-api-contracts"&&i.continuationState==="delegate"&&a.length===3&&g(a[0])&&g(a[1])&&g(a[2])&&a[0].stageCommand==="arch-prd"&&a[1].stageCommand==="arch-architecture"&&a[2].stageCommand==="arch-fitness-functions"&&v(a,r.acceptedStages)&&n?.nextAction==="delegate",_=["PACT-Q1-CONSUMER","PACT-Q2-PROVIDER","PACT-Q3-BROKER","PACT-Q4-MATCHERS","PACT-Q5-VERIFY"],S=r.currentStageCommand==="arch-api-contracts"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&i?.currentStageCommand==="generate-pacts"&&i.continuationState==="ask-user"&&a.length===4&&g(a[3])&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===3&&v(a.slice(0,3),r.acceptedStages)&&a[3].stageCommand==="arch-api-contracts"&&v(a[3].completionEvidence,r.completionEvidence)&&v(a[3].validationEvidence,r.validationEvidence)&&v(i.questionIds,_)&&v(n?.questionIds,_)&&n?.nextAction==="ask-user",l=r.currentStageCommand==="generate-pacts"&&r.continuationState==="ask-user"&&i?.currentStageCommand==="generate-pacts"&&i.continuationState==="delegate"&&a.length===4&&v(a,r.acceptedStages)&&v(r.questionIds,_)&&v(i.questionIds,[])&&v(i.pactAnswerReceipt,e.answerReceipt)&&v(n?.pactAnswerReceipt,e.answerReceipt)&&e.answerReceipt?.stateSha256===e.sourceStateSha256&&n?.nextAction==="resume",A=r.currentStageCommand==="generate-pacts"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&v(r.pactAnswerReceipt,e.pactRecordedReceipt)&&i?.currentStageCommand==="arch-api-integrations"&&i.continuationState==="advance"&&a.length===5&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===4&&v(a.slice(0,4),r.acceptedStages)&&a.map(V=>g(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts"&&g(a[4])&&v(a[4].completionEvidence,r.completionEvidence)&&v(a[4].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",j=r.currentStageCommand==="arch-api-integrations"&&r.continuationState==="advance"&&i?.currentStageCommand==="arch-api-integrations"&&i.continuationState==="delegate"&&a.length===5&&v(a,r.acceptedStages)&&n?.nextAction==="delegate",k=r.currentStageCommand==="arch-api-integrations"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&i?.currentStageCommand==="arch-database"&&i.continuationState==="advance"&&a.length===6&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===5&&v(a.slice(0,5),r.acceptedStages)&&a.map(V=>g(V)?V.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations"&&g(a[5])&&v(a[5].completionEvidence,r.completionEvidence)&&v(a[5].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",O=r.currentStageCommand==="arch-database"&&r.continuationState==="advance"&&i?.currentStageCommand==="arch-database"&&i.continuationState==="delegate"&&a.length===6&&v(a,r.acceptedStages)&&n?.nextAction==="delegate",C=r.currentStageCommand==="arch-database"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&i?.currentStageCommand==="arch-security"&&i.continuationState==="advance"&&a.length===7&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===6&&v(a.slice(0,6),r.acceptedStages)&&a.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(a[6])&&v(a[6].completionEvidence,r.completionEvidence)&&v(a[6].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",T=r.currentStageCommand==="arch-security"&&r.continuationState==="advance"&&i?.currentStageCommand==="arch-security"&&i.continuationState==="delegate"&&a.length===7&&v(a,r.acceptedStages)&&n?.nextAction==="delegate",P=r.currentStageCommand==="arch-security"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&i?.currentStageCommand==="arch-design-system"&&i.continuationState==="advance"&&a.length===8&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===7&&v(a.slice(0,7),r.acceptedStages)&&a.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(a[7])&&v(a[7].completionEvidence,r.completionEvidence)&&v(a[7].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",B=r.currentStageCommand==="arch-design-system"&&r.continuationState==="advance"&&i?.currentStageCommand==="arch-design-system"&&i.continuationState==="delegate"&&a.length===8&&v(a,r.acceptedStages)&&n?.nextAction==="delegate",D=r.currentStageCommand==="arch-design-system"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&i?.currentStageCommand==="arch-ux-design"&&i.continuationState==="advance"&&a.length===9&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===8&&v(a.slice(0,8),r.acceptedStages)&&a.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(a[8])&&v(a[8].completionEvidence,r.completionEvidence)&&v(a[8].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",K=r.currentStageCommand==="arch-ux-design"&&r.continuationState==="advance"&&i?.currentStageCommand==="arch-ux-design"&&i.continuationState==="delegate"&&a.length===9&&v(a,r.acceptedStages)&&n?.nextAction==="blocked",ue=r.currentStageCommand==="arch-ux-design"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&i?.currentStageCommand==="arch-performance"&&i.continuationState==="advance"&&a.length===10&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===9&&v(a.slice(0,9),r.acceptedStages)&&a.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(a[9])&&v(a[9].completionEvidence,r.completionEvidence)&&v(a[9].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",x=r.currentStageCommand==="arch-performance"&&r.continuationState==="advance"&&i?.currentStageCommand==="arch-performance"&&i.continuationState==="delegate"&&a.length===10&&v(a,r.acceptedStages)&&n?.nextAction==="delegate",pe=r.currentStageCommand==="arch-performance"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&i?.currentStageCommand==="arch-testing"&&i.continuationState==="advance"&&a.length===11&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===10&&v(a.slice(0,10),r.acceptedStages)&&a.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(a[10])&&v(a[10].completionEvidence,r.completionEvidence)&&v(a[10].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",oe=r.currentStageCommand==="arch-testing"&&r.continuationState==="advance"&&i?.currentStageCommand==="arch-testing"&&i.continuationState==="delegate"&&a.length===11&&v(a,r.acceptedStages)&&n?.nextAction==="delegate",G=r.currentStageCommand==="arch-testing"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&i?.currentStageCommand==="arch-infrastructure"&&i.continuationState==="advance"&&a.length===12&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===11&&v(a.slice(0,11),r.acceptedStages)&&a.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(a[11])&&v(a[11].completionEvidence,r.completionEvidence)&&v(a[11].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",gt=r.currentStageCommand==="arch-infrastructure"&&r.continuationState==="advance"&&i?.currentStageCommand==="arch-infrastructure"&&i.continuationState==="delegate"&&a.length===12&&v(a,r.acceptedStages)&&n?.nextAction==="delegate",wt=r.currentStageCommand==="arch-infrastructure"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&i?.currentStageCommand==="arch-review"&&i.continuationState==="advance"&&a.length===13&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===12&&v(a.slice(0,12),r.acceptedStages)&&a.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(a[12])&&v(a[12].completionEvidence,r.completionEvidence)&&v(a[12].validationEvidence,r.validationEvidence)&&n?.nextAction==="resume",he=r.currentStageCommand==="arch-review"&&r.continuationState==="advance"&&i?.currentStageCommand==="arch-review"&&i.continuationState==="delegate"&&a.length===13&&v(a,r.acceptedStages)&&n?.nextAction==="delegate",N=r.currentStageCommand==="arch-review"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&r.reviewDecision===void 0&&i?.currentStageCommand==="arch-review"&&i.continuationState==="ask-user"&&a.length===13&&v(a,r.acceptedStages)&&v(i.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&v(i.completionEvidence,r.completionEvidence)&&v(i.validationEvidence,r.validationEvidence)&&n?.nextAction==="ask-user",H=r.currentStageCommand==="arch-review"&&r.continuationState==="ask-user"&&r.childStatus==="succeeded"&&g(r.reviewDecision)&&r.reviewDecision.decision==="approved"&&v(r.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&i?.currentStageCommand==="update-memory"&&i.continuationState==="advance"&&a.length===14&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===13&&v(a.slice(0,13),r.acceptedStages)&&g(a[13])&&a[13].stageCommand==="arch-review"&&v(a[13].completionEvidence,r.completionEvidence)&&v(a[13].validationEvidence,r.validationEvidence)&&v(i.reviewDecision,r.reviewDecision)&&n?.nextAction==="resume",xe=r.currentStageCommand==="update-memory"&&r.continuationState==="advance"&&g(r.reviewDecision)&&r.reviewDecision.decision==="approved"&&i?.currentStageCommand==="update-memory"&&i.continuationState==="delegate"&&a.length===14&&v(a,r.acceptedStages)&&v(i.reviewDecision,r.reviewDecision)&&n?.nextAction==="delegate",Te=r.currentStageCommand==="update-memory"&&r.continuationState==="delegate"&&r.childStatus==="succeeded"&&i?.currentStageCommand==="update-memory"&&i.continuationState==="complete"&&a.length===15&&Array.isArray(r.acceptedStages)&&r.acceptedStages.length===14&&v(a.slice(0,14),r.acceptedStages)&&g(a[14])&&a[14].targetEpicId===r.targetEpicId&&a[14].stageCommand==="update-memory"&&v(a[14].completionEvidence,r.completionEvidence)&&v(a[14].validationEvidence,r.validationEvidence)&&v(i.reviewDecision,r.reviewDecision)&&v(i.completionEvidence,r.completionEvidence)&&v(i.validationEvidence,r.validationEvidence)&&Ft(i.terminalMemoryCheckpoint,r)!==null&&v(i.terminalMemoryCheckpoint,r.terminalMemoryCheckpoint)&&n?.nextAction==="complete",Pe=r.currentStageCommand==="update-memory"&&r.continuationState==="complete"&&r.childStatus==="succeeded"&&i?.currentStageCommand==="update-memory"&&i.continuationState==="complete"&&a.length===15&&v(a,r.acceptedStages)&&v(i.reviewDecision,r.reviewDecision)&&v(i.completionEvidence,r.completionEvidence)&&v(i.validationEvidence,r.validationEvidence)&&Ft(i.terminalMemoryCheckpoint,r)&&v(i.terminalMemoryCheckpoint,r.terminalMemoryCheckpoint)&&n?.nextAction==="complete",Nt=n?Ji(r,n,Ft(r.terminalMemoryCheckpoint,r)&&v(i?.terminalMemoryCheckpoint,r.terminalMemoryCheckpoint)):void 0;if(e.metadata.mode!=="arch-plan"||e.metadata.resolvedTrigger!=="arch-plan"||!g(t)||!g(o)||t.owner!=="root"||t.currentStageCommand!==o.currentStageCommand||t.continuationState!==o.continuationState||o.owner!=="root"||o.evidencePolicy!=="v2-required"||o.targetEpicId!==r.targetEpicId||o.graphRevision!==r.graphRevision||o.graphSource!==r.graphSource||!/^P[1-9][0-9]{0,11}$/.test(String(o.targetEpicId))||!/^[a-f0-9]{64}$/.test(String(o.graphRevision))||!Array.isArray(o.acceptedStages)||!(Nt||d||s||u||m||I||h||E||S||l||A||j||k||O||C||T||P||B||D||K||ue||x||pe||oe||G||gt||wt||he||N||H||xe||Te||Pe)||!g(o.accounting)||o.accounting.charged!==!0||!v(Sn(o),o))throw new Error("architecture-root-checkpoint-invalid");const rt=J(e.projectRoot,".neocortex"),Q=J(rt,"state.json"),ve=J(rt,"state.json.architecture.lock"),ge=zt(ve,"wx",384);let qe;try{const V=Vt(Q);if(!V.isFile()||V.isSymbolicLink())throw new Error("architecture-root-state-binding-invalid");const ft=Fe(Q,"utf8");if(Ne("sha256").update(ft).digest("hex")!==e.sourceStateSha256)throw new Error("architecture-root-state-conflict");const fe=JSON.parse(ft),ae=g(fe)&&g(fe.archPlan)?fe.archPlan:{};if(!g(fe)||!g(fe.epics)||!Object.hasOwn(fe.epics,o.targetEpicId)||(e.initialBinding?ae.execution!==void 0||r.graphSource!=="committed-epic-v1":!v(Sn(ae.execution),r))||g(fe.scope)&&fe.scope.kind==="projected")throw new Error("architecture-root-state-binding-invalid");if(r.graphSource==="committed-epic-v1"&&r.graphRevision!==Yt(e.projectRoot,String(r.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");if(Pe||Nt==="complete-replay"){const Lt={...r,continuationState:"delegate",acceptedStages:r.acceptedStages.slice(0,Er(r))};if(!v(r.terminalMemoryCheckpoint,Dn(e.projectRoot,Lt)))throw new Error("architecture-root-state-conflict");return}const Ie=pn(),Ve=Be("git",["rev-parse","--git-common-dir"],{cwd:e.projectRoot,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),Z=to(Ve)?jn(Ve):jn(e.projectRoot,Ve);if(eo(Z)!==Z)throw new Error("architecture-root-backup-dir-invalid");const mt=J(Z,"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=J(mt,`state-backup-${Ie}.json`),Qe=zt(ke,"wx",384);try{ln(Qe,ft),un(Qe)}finally{Jt(Qe)}const W=zt(mt,"r");try{un(W)}finally{Jt(W)}const xn={...fe,archPlan:{...ae,execution:o}};qe=J(rt,`state.json.architecture-tmp-${Ie}`);const it=zt(qe,"wx",384);try{ln(it,`${JSON.stringify(xn,null,2)}
|
|
8
|
+
`),un(it)}finally{Jt(it)}if((Te||Nt==="complete")&&!v(r.terminalMemoryCheckpoint,Dn(e.projectRoot,r)))throw new Error("architecture-root-state-conflict");if(r.graphSource==="committed-epic-v1"&&r.graphRevision!==Yt(e.projectRoot,String(r.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");Cr(qe,Q),qe=void 0;const L=zt(rt,"r");try{un(L)}finally{Jt(L)}}finally{if(qe)try{Mn(qe)}catch{}Jt(ge),Mn(ve)}}function vn(e,t){if(!g(e))return;const o={};for(const n of t){const i=e[n];if(typeof i=="boolean")o[n]=i;else if(typeof i=="number"&&Number.isFinite(i))o[n]=i;else if(typeof i=="string"){const r=X(i);r&&(o[n]=r)}}return Object.keys(o).length>0?o:void 0}function Cn(e){return e==="epic"||e==="story"?e:void 0}function ci(e){if(!g(e)||e.schemaVersion!==1)return;const t=z(e.ownerStoryId),o=z(e.sessionId),n=z(e.idempotencyKey),i=De(e.acquiredAt),r=De(e.expiresAt);if(!(!t||!o||!n||!i||!r||Date.parse(r)<=Date.parse(i)))return{schemaVersion:1,ownerStoryId:t,sessionId:o,idempotencyKey:n,acquiredAt:i,expiresAt:r}}function si(e){if(!g(e)||e.schemaVersion!==1)return;const t=z(e.storyId),o=z(e.epicId),n=Se(e.branch),i=R(e.baseSha),r=R(e.headSha),a=z(e.idempotencyKey),d=De(e.recordedAt),s=de(e.commits).map(R).filter(j=>!!j).slice(0,256),u=de(e.receiptRefs).map(pt).filter(j=>!!j).slice(0,256),m=e.dispatchId===void 0?void 0:z(e.dispatchId),I=e.bundleId===void 0?void 0:z(e.bundleId),h=e.bundleDigest===void 0?void 0:R(e.bundleDigest),E=e.graphRevision===void 0?void 0:R(e.graphRevision),_=e.claimRevision===void 0?void 0:z(e.claimRevision),S=ac(e.qaReceipt),l=cc(e.reviewReceipt),A=e.rootMemoryEffect===void 0?void 0:Ca(e.rootMemoryEffect)?e.rootMemoryEffect:void 0;if(!(!t||!o||!t.startsWith(`${o}.`)||!n||!i||!r||i===r||!a||!d||s.length===0||u.length===0||!Array.isArray(e.commits)||s.length!==e.commits.length||e.commits.length>256||!Array.isArray(e.receiptRefs)||u.length!==e.receiptRefs.length||e.receiptRefs.length>256||e.dispatchId!==void 0&&!m||e.bundleId!==void 0&&!I||e.bundleDigest!==void 0&&(!h||h.length!==64)||e.graphRevision!==void 0&&(!E||E.length!==64)||e.claimRevision!==void 0&&!_||e.rootMemoryEffect!==void 0&&(!A||A.storyId!==t||A.epicId!==o||A.executionBranch!==n||A.sourceHeadSha!==i||A.childClaimRevision!==_)||e.qaVerdict!=="passed"&&e.qaVerdict!=="blocked"||!["approved","changes-requested","pending"].includes(String(e.reviewVerdict))||!S||e.reviewVerdict!=="pending"&&!l||e.reviewVerdict==="pending"&&l||S.verdict!==e.qaVerdict||l&&l.verdict!==e.reviewVerdict||!li(S,{storyId:t,epicId:o,baseSha:i,headSha:r,bundleDigest:h,graphRevision:E})||l&&(!li(l,{storyId:t,epicId:o,baseSha:i,headSha:r,bundleDigest:h,graphRevision:E})||l.qaReceiptRef!==S?.receiptRef||l.receiptRef===S?.receiptRef)||!u.includes(String(S.receiptRef))||l&&(!u.includes(String(l.receiptRef))||Date.parse(String(l.reviewedAt))<Date.parse(String(S.checkedAt)))))return{schemaVersion:1,storyId:t,epicId:o,branch:n,baseSha:i,headSha:r,idempotencyKey:a,...m?{dispatchId:m}:{},...I?{bundleId:I}:{},...h?{bundleDigest:h}:{},...E?{graphRevision:E}:{},..._?{claimRevision:_}:{},...A?{rootMemoryEffect:structuredClone(A)}:{},qaVerdict:e.qaVerdict,reviewVerdict:e.reviewVerdict,...S?{qaReceipt:S}:{},...l?{reviewReceipt:l}:{},recordedAt:d,commits:s,receiptRefs:u}}function ac(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=z(e.storyId),o=z(e.epicId),n=R(e.baseSha),i=R(e.headSha),r=R(e.bundleDigest),a=R(e.graphRevision),d=R(e.sourceEvidenceDigest),s=De(e.checkedAt),u=pt(e.receiptRef),m=e.evidenceVersion==="p205-execution-v2"&&e.contract==="P205-CI-02"?e.contract:void 0,I=e.evidenceVersion==="p205-execution-v2"&&e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,h=e.evidenceVersion==="p205-execution-v2"?R(e.manifestDigest):void 0,E=e.evidenceVersion==="p205-execution-v2"?R(e.resultDigest):void 0,_=e.evidenceVersion==="p205-execution-v2"?de(e.gateIds).map(z).filter(S=>!!S).slice(0,64):void 0;if(!(!t||!o||!n||!i||!r||r.length!==64||!a||a.length!==64||!d||d.length!==64||!s||!u||e.evidenceVersion==="p205-execution-v2"&&(!m||I!=="node scripts/test-root.mjs --gate complete"||!h||h.length!==64||!E||E.length!==64||!Array.isArray(e.gateIds)||!_||_.length===0||_.length!==e.gateIds.length)))return{schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",...e.evidenceVersion?{evidenceVersion:e.evidenceVersion}:{},storyId:t,epicId:o,...e.evidenceVersion==="p205-execution-v2"?{contract:m,command:I,manifestDigest:h,gateIds:_,resultDigest:E}:{},baseSha:n,headSha:i,bundleDigest:r,graphRevision:a,sourceEvidenceDigest:d,verdict:e.verdict,checkedAt:s,receiptRef:u}}function di(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=z(e.storyId),o=z(e.epicId),n=Se(e.branch),i=R(e.baseSha),r=R(e.headSha),a=R(e.aggregateHeadSha),d=R(e.commitBodyDigest),s=R(e.changedPathsDigest),u=e.claimVerification==="canonical"||e.claimVerification==="legacy-migration"?e.claimVerification:void 0,m=R(e.effectiveClaimRevision),I=e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,h=R(e.manifestDigest),E=de(e.gateIds).map(z).filter(O=>!!O).slice(0,64),_=R(e.resultDigest),S=R(e.graphRevision),l=R(e.executionEvidenceDigest),A=R(e.sourceEvidenceDigest),j=De(e.verifiedAt),k=de(e.reasonCodes).map(z).filter(O=>!!O).slice(0,16);if(!(!t||!o||!n||!i||i.length<40||!r||r.length<40||!a||a.length<40||!d||d.length!==64||!s||s.length!==64||!u||!m||m.length!==64||!I||!h||h.length!==64||!Array.isArray(e.gateIds)||E.length!==e.gateIds.length||!_||_.length!==64||!S||S.length!==64||!l||l.length!==64||!A||A.length!==64||!j||k.length===0||e.verdict==="verified"&&(E.length===0||!k.includes("checkpoint-p205-transient-verified"))))return{schemaVersion:1,kind:"story_checkpoint_physical_verification",producer:"client-p205-transient-v1",storyId:t,epicId:o,branch:n,baseSha:i,headSha:r,aggregateHeadSha:a,commitBodyDigest:d,changedPathsDigest:s,claimVerification:u,effectiveClaimRevision:m,command:I,manifestDigest:h,gateIds:E,resultDigest:_,graphRevision:S,executionEvidenceDigest:l,sourceEvidenceDigest:A,verifiedAt:j,verdict:e.verdict,reasonCodes:k,publicSafe:!0}}function pi(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(h=>!t.includes(h))||e.schemaVersion!==1||e.kind!=="story_scheduling_checkpoint_evidence"||e.producer!=="client-git-physical-v1"||e.integrationAuthorized!==!1||e.publicSafe!==!0)return;const o=z(e.storyId),n=z(e.epicId),i=Se(e.branch),r=R(e.baseSha),a=R(e.headSha),d=R(e.graphRevision),s=R(e.effectiveClaimRevision),u=R(e.sourceEvidenceDigest),m=De(e.verifiedAt),I=de(e.reasonCodes).map(z).filter(h=>!!h);if(!(!o||!n||!i||!r||r.length<40||!a||a.length<40||!d||d.length!==64||!s||s.length!==64||!u||u.length!==64||!m||!Array.isArray(e.reasonCodes)||I.length!==1||I[0]!=="checkpoint-git-scheduling-verified"))return{schemaVersion:1,kind:"story_scheduling_checkpoint_evidence",producer:"client-git-physical-v1",storyId:o,epicId:n,branch:i,baseSha:r,headSha:a,graphRevision:d,effectiveClaimRevision:s,sourceEvidenceDigest:u,verifiedAt:m,reasonCodes:I,integrationAuthorized:!1,publicSafe:!0}}function cc(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=z(e.storyId),o=z(e.epicId),n=R(e.baseSha),i=R(e.headSha),r=R(e.bundleDigest),a=R(e.graphRevision),d=R(e.sourceEvidenceDigest),s=pt(e.qaReceiptRef),u=De(e.reviewedAt),m=pt(e.receiptRef);if(!(!t||!o||!n||!i||!r||r.length!==64||!a||a.length!==64||!d||d.length!==64||!s||!u||!m))return{schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:t,epicId:o,baseSha:n,headSha:i,bundleDigest:r,graphRevision:a,sourceEvidenceDigest:d,qaReceiptRef:s,verdict:e.verdict,reviewedAt:u,receiptRef:m}}function li(e,t){return["storyId","epicId","baseSha","headSha","bundleDigest","graphRevision"].every(o=>e[o]===t[o])}function ui(e){if(!g(e))return;const t=e.schemaVersion===1&&e.capturedFromCurrentCheckout===!0&&e.capturedFrom===void 0,o=e.schemaVersion===2&&e.capturedFromCurrentCheckout===void 0&&(e.capturedFrom==="current-checkout"||e.capturedFrom==="branch-ref");if(!t&&!o)return;const n=Se(e.originBranch),i=R(e.originHeadSha),r=Se(e.executionBranch),a=De(e.capturedAt);if(!(!n||!i||i.length<40||!r||!a||n===r))return t?{schemaVersion:1,originBranch:n,originHeadSha:i,executionBranch:r,capturedFromCurrentCheckout:!0,capturedAt:a}:{schemaVersion:2,originBranch:n,originHeadSha:i,executionBranch:r,capturedFrom:e.capturedFrom,capturedAt:a}}function hi(e){if(!g(e)||e.schemaVersion!==1||e.verdict!=="passed")return;const t=R(e.executionHeadSha),o=R(e.graphRevision),n=De(e.checkedAt),i=pt(e.receiptRef),r=de(e.gateIds).map(z).filter(m=>!!m).slice(0,128),a=e.evidenceVersion==="p205-execution-v2"&&e.producer==="local-yolo-tdd"&&e.contract==="P205-CI-02"&&e.command==="node scripts/test-root.mjs --gate complete",d=e.evidenceVersion===void 0&&e.producer===void 0&&e.contract===void 0&&e.command===void 0&&e.manifestDigest===void 0&&e.resultDigest===void 0,s=a?R(e.manifestDigest):void 0,u=a?R(e.resultDigest):void 0;if(!(!t||t.length<40||!o||o.length!==64||!n||!i||r.length===0||!Array.isArray(e.gateIds)||r.length!==e.gateIds.length||e.gateIds.length>128||!d&&!a||a&&(!s||s.length!==64||!u||u.length!==64)))return{schemaVersion:1,...a?{evidenceVersion:"p205-execution-v2",producer:"local-yolo-tdd",contract:"P205-CI-02",command:"node scripts/test-root.mjs --gate complete",manifestDigest:s,resultDigest:u}:{},verdict:"passed",executionHeadSha:t,graphRevision:o,checkedAt:n,receiptRef:i,gateIds:r}}const sc=16384;function dc(e){if(!g(e))return;const t=(n,i)=>n===null||typeof n=="boolean"?!0:typeof n=="number"?Number.isFinite(n):typeof n=="string"?n.length<=512&&!n.startsWith("/")&&!/^[A-Za-z]:[\\/]/.test(n)&&!n.includes("\\")&&!/:\/\//.test(n)&&!/[\u0000-\u001f]/.test(n):i>=4?!1:Array.isArray(n)?n.length<=256&&n.every(r=>t(r,i+1)):g(n)?Object.keys(n).length<=64&&Object.entries(n).every(([r,a])=>/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(r)&&t(a,i+1)):!1;if(!t(e,0))return;const o=JSON.stringify(e);if(!(Buffer.byteLength(o,"utf8")>sc))return JSON.parse(o)}function gi(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:z(e.epicId),executionBranch:Se(e.executionBranch),originBranch:Se(e.originBranch),graphRevision:R(e.graphRevision),originHeadSha:R(e.originHeadSha),lastAcceptedCheckpointHeadSha:R(e.lastAcceptedCheckpointHeadSha),executionHeadSha:R(e.executionHeadSha),acceptedCheckpointIds:de(e.acceptedCheckpointIds),acceptedCheckpointHeads:de(e.acceptedCheckpointHeads),reconciliationCommitShas:de(e.reconciliationCommitShas),commitRangeDigest:R(e.commitRangeDigest),changedPaths:de(e.changedPaths),changedPathsDigest:R(e.changedPathsDigest),allowedWriteSet:de(e.allowedWriteSet),allowedWriteSetDigest:R(e.allowedWriteSetDigest),aggregateReceiptRef:pt(e.aggregateReceiptRef),aggregateManifestDigest:R(e.aggregateManifestDigest),aggregateResultDigest:R(e.aggregateResultDigest),producedAt:De(e.producedAt),revalidatedAt:De(e.revalidatedAt),publicSafe:!0},o=["originSyncHeadSha","originSyncCommitShas","originSyncPaths","originSyncPathsDigest","originSyncResolvedPaths","originSyncResolvedPathsDigest"],n=o.filter(d=>e[d]!==void 0).length;if(n!==0&&n!==o.length)return;const i=n===0?void 0:{originSyncHeadSha:R(e.originSyncHeadSha),originSyncCommitShas:de(e.originSyncCommitShas),originSyncPaths:de(e.originSyncPaths),originSyncPathsDigest:R(e.originSyncPathsDigest),originSyncResolvedPaths:de(e.originSyncResolvedPaths),originSyncResolvedPathsDigest:R(e.originSyncResolvedPathsDigest)};if(i&&(!i.originSyncHeadSha||i.originSyncHeadSha.length<40||i.originSyncCommitShas.length===0||i.originSyncCommitShas.length>256||i.originSyncCommitShas.some(d=>!/^[a-f0-9]{40,64}$/i.test(d))||i.originSyncPaths.length>2048||i.originSyncResolvedPaths.length>64||i.originSyncPathsDigest!==fn(i.originSyncPaths)||i.originSyncResolvedPathsDigest!==fn(i.originSyncResolvedPaths))||!t.epicId||!t.executionBranch||!t.originBranch||!t.graphRevision||t.graphRevision.length!==64||!t.originHeadSha||t.originHeadSha.length<40||!t.lastAcceptedCheckpointHeadSha||t.lastAcceptedCheckpointHeadSha.length<40||!t.executionHeadSha||t.executionHeadSha.length<40||t.acceptedCheckpointIds.length===0||t.acceptedCheckpointIds.length>2048||t.acceptedCheckpointIds.length!==t.acceptedCheckpointHeads.length||t.acceptedCheckpointHeads.some(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!==sa(t.lastAcceptedCheckpointHeadSha,t.executionHeadSha,t.reconciliationCommitShas)||t.changedPathsDigest!==fn(t.changedPaths)||t.allowedWriteSetDigest!==fn(t.allowedWriteSet))return;const r={...t,...i??{}},a=R(e.inputDigest);if(!(!a||a.length!==64||a!==ca(r)))return{...r,inputDigest:a}}function Xn(e){if(!g(e)||e.schemaVersion!==1)return;const t=vn(e,["schemaVersion","kind","storyId","epicId","baseSha","headSha","originalBaseSha","originalHeadSha","gitPullRequest","preservesLaterCommits","historyRewrite","recordedAt"])??{},o=de(e.receiptRefs).map(pt).filter(i=>!!i).slice(0,256),n=de(e.revertCommits).map(X).filter(i=>!!i).slice(0,256);return{...t,...o.length?{receiptRefs:o}:{},...n.length?{revertCommits:n}:{}}}function pc(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 fi(e){if(!g(e)||e.schemaVersion!==1||e.publicSafe!==!0)return;const t=z(e.epicId),o=Se(e.executionBranch),n=Se(e.originBranch),i=R(e.baseSha),r=R(e.executionHeadSha),a=e.mergeSha===void 0?void 0:R(e.mergeSha),d=e.pushedSha===void 0?void 0:R(e.pushedSha),s=z(e.idempotencyKey),u=De(e.attemptStartedAt),m=e.completedAt===void 0?void 0:De(e.completedAt),I=de(e.localGateReceiptRefs).map(pt).filter(S=>!!S).slice(0,256),h=de(e.reasonCodes).map(z).filter(S=>!!S).slice(0,64),E=uc(e.candidateQa),_=lc(e.providerGuard);if(!(!t||!o||!n||!i||!r||!s||!u||I.length===0||h.length===0||!["direct","single_pr"].includes(String(e.strategy))||!["prepared","merged","pushed","denied_external_gate","blocked_local_or_repo"].includes(String(e.physicalStatus))||typeof e.retryEligible!="boolean"||e.providerGuard!==void 0&&!_||_&&(e.strategy!=="single_pr"||e.physicalStatus!=="pushed"||_.prHeadSha!==a||_.originHeadSha!==i)))return{schemaVersion:1,epicId:t,executionBranch:o,originBranch:n,baseSha:i,executionHeadSha:r,...a?{mergeSha:a}:{},...d?{pushedSha:d}:{},strategy:e.strategy,..._t(e.prNumber)?{prNumber:_t(e.prNumber)}:{},physicalStatus:e.physicalStatus,localGateReceiptRefs:I,idempotencyKey:s,attemptStartedAt:u,...E?{candidateQa:E}:{},..._?{providerGuard:_}:{},...m?{completedAt:m}:{},retryEligible:e.retryEligible,reasonCodes:h,publicSafe:!0}}function lc(e){if(!g(e)||e.schemaVersion!==1||e.provider!=="github"||e.publicSafe!==!0)return;const t=String(e.mode),o=String(e.source),n=t==="recovered_exact_tree"?o==="physical_recovery":t==="strict_up_to_date_expected_head"&&["branch_protection","ruleset","branch_protection_and_ruleset"].includes(o),i=R(e.prHeadSha),r=R(e.originHeadSha),a=De(e.checkedAt);if(!(!n||!i||!r||!a))return{schemaVersion:1,provider:"github",mode:t,source:o,prHeadSha:i,originHeadSha:r,checkedAt:a,publicSafe:!0}}function uc(e){if(!g(e)||e.schemaVersion!==1||e.kind!=="epic_merge_candidate_qa"||e.contract!=="P205-CI-02"||e.command!==Xt)return;const o=Object.fromEntries(["originHeadSha","executionHeadSha","mergeSha","treeSha","graphRevision","manifestDigest","resultDigest"].map(a=>[a,R(e[a])])),n=De(e.checkedAt),i=pt(e.receiptRef),r=de(e.gateIds).filter(a=>/^[a-z0-9-]+$/.test(a)).slice(0,128);if(!(Object.values(o).some(a=>!a)||!n||!i||r.length===0))return{schemaVersion:1,kind:e.kind,contract:e.contract,command:e.command,...o,checkedAt:n,receiptRef:i,gateIds:r}}function hc(e){if(!g(e))return;const t={...X(e.active_epic_id??e.activeEpicId)?{active_epic_id:X(e.active_epic_id??e.activeEpicId)}:{},...X(e.active_story_id??e.activeStoryId)?{active_story_id:X(e.active_story_id??e.activeStoryId)}:{},...X(e.active_step_id??e.activeStepId)?{active_step_id:X(e.active_step_id??e.activeStepId)}:{},...X(e.session_id??e.sessionId)?{session_id:X(e.session_id??e.sessionId)}:{},...X(e.started_at??e.startedAt)?{started_at:X(e.started_at??e.startedAt)}:{}};return Object.keys(t).length>0?t:void 0}function gc(e){const t=vn(e.completionEvidence??e.completion_evidence,["prNumber","pr_number","prState","pr_state","pullRequestState","merged","mergedAt","issueNumber","issue_number","issueState","issue_state","closedAt"]),o=vn(e.issueCloseAudit??e.issue_close_audit,["schema_version","event","storyId","epicId","issueNumber","closedAt","publicSafe","rawLogStorage"]),n=vn(e.scopedCiEvidence??e.scoped_ci_evidence,["schema_version","storyId","epicId","prNumber","finalState","publicSafe","rawLogStorage"]);return{...typeof e.merged=="boolean"?{merged:e.merged}:{},...typeof e.safeToContinueYoloop=="boolean"?{safeToContinueYoloop:e.safeToContinueYoloop}:{},...typeof e.mergeBlockedRemotely=="boolean"?{mergeBlockedRemotely:e.mergeBlockedRemotely}:{},...X(e.physicalMergeStatus)?{physicalMergeStatus:X(e.physicalMergeStatus)}:{},...X(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)?{pr_state:X(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)}:{},...X(e.issue_state??e.issueState??e.workflow_issue_state)?{issue_state:X(e.issue_state??e.issueState??e.workflow_issue_state)}:{},..._t(e.issue_number??e.issueNumber)?{issue_number:_t(e.issue_number??e.issueNumber)}:{},...t?{completionEvidence:t}:{},...o?{issueCloseAudit:o}:{},...n?{scopedCiEvidence:n}:{}}}class lt extends Error{reasonCode;constructor(t){super(t),this.name="StateSnapshotIntegrityError",this.reasonCode=t}}const fc=new Set(["yolo","yoloop","finalize-epic","audit"]),mc=8;function yc(e){return/docs\/epics\/epic-(P[1-9][0-9]*)\.md\b/.exec(e)?.[1]??/docs\/stories\/(P[1-9][0-9]*)\.[0-9]+\.story\.md\b/.exec(e)?.[1]}function Ic(e,t={},o={},n){const i=d=>{try{return String(Be("git",[...d],{cwd:e,stdio:["ignore","pipe","ignore"],timeout:1e4,encoding:"utf8"})).trim()}catch{return}};if(i(["rev-parse","--is-inside-work-tree"])!=="true")return;const r=[],a=Object.entries(t).sort(([d],[s])=>+(s===n)-+(d===n));for(const[d,s]of a){if(r.length>=mc)break;if(!g(s)||!g(s.origin_binding))continue;const u=s.execution_branch,m=s.origin_binding;if(typeof u!="string"||m.executionBranch!==u||typeof m.originHeadSha!="string"||!/^[a-f0-9]{40,64}$/.test(m.originHeadSha)||!/^[A-Za-z0-9][A-Za-z0-9._/-]{0,239}$/.test(u)||u.includes(".."))continue;const I=i(["rev-parse","--verify","--quiet",`refs/heads/${u}^{commit}`]);if(!I||!/^[a-f0-9]{40,64}$/.test(I)||i(["merge-base","--is-ancestor",m.originHeadSha,I])===void 0)continue;const h=[];for(const E of Object.values(o)){if(h.length>=128)break;if(!g(E)||(E.epic_id??E.epic)!==d)continue;const _=g(E.checkpoint)&&typeof E.checkpoint.headSha=="string"?E.checkpoint.headSha:g(E.scheduling_checkpoint_evidence)&&typeof E.scheduling_checkpoint_evidence.headSha=="string"?E.scheduling_checkpoint_evidence.headSha:void 0;!_||!/^[a-f0-9]{40,64}$/.test(_)||h.includes(_)||i(["merge-base","--is-ancestor",_,I])!==void 0&&h.push(_)}r.push(Object.freeze({epicId:d,executionBranch:u,originHeadSha:m.originHeadSha,executionHeadSha:I,...h.length>0?{containedHeadShas:Object.freeze(h)}:{}}))}return Object.freeze({schemaVersion:1,stateFileTracked:i(["ls-files","--error-unmatch","--",".neocortex/state.json"])!==void 0,...r.length>0?{executionBases:Object.freeze(r)}:{}})}function mi(e){return typeof e=="string"&&fc.has(e)}function Zn(e,t={}){const o=J(e,".neocortex","state.json");if(!jt(o))throw new lt("git-lifecycle-state-missing");let n;try{n=JSON.parse(Fe(o,"utf8"))}catch{throw new lt("git-lifecycle-state-corrupt")}if(!g(n)||!g(n.epics)||!g(n.stories))throw new lt("git-lifecycle-state-shape-invalid");const i=Object.values(n.epics).some(r=>g(r)&&(r.branch_mode==="epic"||Se(r.execution_branch)!==void 0));if(i)try{mn(e,{required:!0})}catch(r){const a=r instanceof Error&&/^git-lifecycle-/.test(r.message)?r.message:"git-lifecycle-runtime-invalid";if(t.allowMissingRuntime&&a==="git-lifecycle-runtime-missing")return{lifecycleDeclared:!0,runtimeMissing:!0};throw new lt(a)}return{lifecycleDeclared:i,runtimeMissing:!1}}const Ec=256,Sc=/^[A-Za-z0-9][A-Za-z0-9_-]{7,95}$/,vc=/^[a-f0-9]{64}$/;function Cc(e){const t=Date.now(),o={};for(const n of Object.values(e.storyWorktrees?.entries??{})){if(!g(n)||n.state!=="active")continue;const{epicId:i,storyId:r,leaseId:a,graphRevision:d,expiresAt:s}=n;typeof i!="string"||typeof r!="string"||!r.startsWith(`${i}.`)||typeof a!="string"||!Sc.test(a)||typeof d!="string"||!vc.test(d)||typeof s!="string"||!(Date.parse(s)>t)||(o[i]??=[]).push({schemaVersion:1,storyId:r,leaseId:a,graphRevision:d,expiresAt:s})}for(const[n,i]of Object.entries(o))i.length>Ec?delete o[n]:i.sort((r,a)=>String(r.storyId).localeCompare(String(a.storyId))||String(r.leaseId).localeCompare(String(a.leaseId)));return o}function _n(e,t={}){const o=J(e,".neocortex","state.json");if(!jt(o)){if(t.epicAware&&!t.projectless)throw new lt("git-lifecycle-state-missing");return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}let n,i,r={};try{const S=Fe(o,"utf-8");i=Ne("sha256").update(S).digest("hex");const l=Co(e,i)??JSON.parse(S),A=g(l.epics)?l.epics:{},j=Object.values(A).some(P=>g(P)&&(P.branch_mode==="epic"||Se(P.execution_branch)!==void 0)),k=mn(e,{required:!!(t.epicAware&&j&&!t.projectless)});n=Ur(l,k),r=Cc(k);const O=g(n.stories)?n.stories:{},C=g(n.epics)?n.epics:{},T=g(l.stories)?l.stories:{};for(const[P,B]of Object.entries(O)){const D=g(B)?B:void 0;if(!D?.checkpoint)continue;const K=typeof D.epic_id=="string"?D.epic_id:P.split(".")[0],ue=g(C[K])?C[K]:void 0,x=Se(ue?.execution_branch);if(!x)continue;const pe=da(e,D.checkpoint,P,K,x,t.p205Authorities?.[P],$r(P,D,g(D.checkpoint)?D.checkpoint:void 0));if(pe.kind==="integration-authorized")D.checkpoint_verification=pe.verification,delete D.scheduling_checkpoint_evidence;else if(pe.kind==="scheduling-only")D.scheduling_checkpoint_evidence=pe.evidence,delete D.checkpoint,delete D.checkpoint_verification;else if(pe.kind==="rejected"){D.checkpoint_verification=pe.verification,delete D.scheduling_checkpoint_evidence;const oe=g(T[P])?T[P]:void 0;if(delete D.checkpoint,k.stories[P]?.checkpoint!==void 0)for(const G of["status","last_step","steps_completed"])oe&&Object.prototype.hasOwnProperty.call(oe,G)?D[G]=structuredClone(oe[G]):delete D[G];["done","completed","merged"].includes(String(D.status).toLowerCase())&&(D.status="blocked")}}}catch(S){if(t.epicAware&&!t.projectless){const l=S instanceof Error&&/^git-lifecycle-/.test(S.message)?S.message:"git-lifecycle-state-corrupt";throw new lt(l)}return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}try{const S=Xa(n);S.length>0&&Za(S)}catch{}const a=n.config??n.project??{},d=n.stories??{},s={};for(const[S,l]of Object.entries(d)){const A=g(l.review_request)&&l.review_request.kind==="git-pull-request"?pc(l.review_request):Xn(l.review_request);s[S]={id:l.id??S,title:l.title,epic_id:l.epic_id,status:l.status??"backlog",...oi(l.source)?{source:oi(l.source)}:{},steps_completed:l.steps_completed??[],last_step:l.last_step??null,branch_name:l.branch_name??null,pr_number:l.pr_number,...Cn(l.branch_mode)?{branch_mode:Cn(l.branch_mode)}:{},...si(l.checkpoint)?{checkpoint:si(l.checkpoint)}:{},...di(l.checkpoint_verification)?{checkpoint_verification:di(l.checkpoint_verification)}:{},...pi(l.scheduling_checkpoint_evidence)?{scheduling_checkpoint_evidence:pi(l.scheduling_checkpoint_evidence)}:{},...A?{review_request:A}:{},...Xn(l.rollback_receipt)?{rollback_receipt:Xn(l.rollback_receipt)}:{},..._t(l.workflow_issue)?{workflow_issue:_t(l.workflow_issue)}:{},...gc(l),...Array.isArray(l.depends_on)?{depends_on:ii(l.depends_on)}:{},files_to_modify:de(l.files_to_modify),...ic(l),...ai(l.supersededBy)?{supersededBy:ai(l.supersededBy)}:{},risk:typeof l.risk=="string"?l.risk:void 0,blast_radius:typeof l.blast_radius=="number"?l.blast_radius:void 0}}const u=n.epics??{},m={};for(const[S,l]of Object.entries(u)){const A=ec(l.lifecycle_classification),j=rc(l.createEpicPlanning,S),k=j.checkpoint;let O,C,T,P;if(k&&g(l.createEpicPlanningClaim)&&typeof l.createEpicPlanningClaim.claimId=="string"&&g(l.createEpicPlanningPhysical))try{_r(n,l.createEpicPlanningClaim.claimId,S,!0),O=JSON.parse(JSON.stringify(l.createEpicPlanningPhysical))}catch{}if(O&&g(l.createEpicPlanningClaim)&&typeof l.createEpicPlanningClaim.claimId=="string"&&g(l.createEpicPlanningResearchPhysical))try{Rr(n,l.createEpicPlanningClaim.claimId,S),C=JSON.parse(JSON.stringify(l.createEpicPlanningResearchPhysical))}catch{}if(t.verifyPlanningGeneration&&k&&l.status==="generated"&&g(l.createEpicPlanningClaim)&&typeof l.createEpicPlanningClaim.claimId=="string"&&g(l.createEpicPlanningGenerationPhysical))try{if(ao(e,l.createEpicPlanningClaim.claimId,S).stateSha256!==i)throw new Error("planning-generation-snapshot-raced");T=JSON.parse(JSON.stringify(l.createEpicPlanningGenerationPhysical)),O=JSON.parse(JSON.stringify(l.createEpicPlanningPhysical)),C=JSON.parse(JSON.stringify(l.createEpicPlanningResearchPhysical))}catch{}if(T&&g(l.createEpicPlanningClaim)&&typeof l.createEpicPlanningClaim.claimId=="string")try{const B=wr(e,l.createEpicPlanningClaim.claimId,S);if(B.stateSha256!==i)throw new Error("planning-memory-snapshot-raced");P=JSON.parse(JSON.stringify(B))}catch{}m[S]={id:l.id??S,title:l.title,...k?{createEpicPlanning:k}:{},...j.diagnostic?{createEpicPlanningProjection:j.diagnostic}:{},...O?{createEpicPlanningPhysical:O}:{},...C?{createEpicPlanningResearchPhysical:C}:{},...T?{createEpicPlanningGenerationPhysical:T}:{},...P?{createEpicPlanningMemoryPhysical:P}:{},status:l.status,stories:l.stories,total_stories:l.total_stories,completed_stories:l.completed_stories,depends_on:ii(l.depends_on),...Cn(l.branch_mode)?{branch_mode:Cn(l.branch_mode)}:{},...Se(l.execution_branch)?{execution_branch:Se(l.execution_branch)}:{},...Se(l.origin_branch)?{origin_branch:Se(l.origin_branch)}:{},...ci(l.branch_lease)?{branch_lease:ci(l.branch_lease)}:{},...ui(l.origin_binding)?{origin_binding:ui(l.origin_binding)}:{},...hi(l.aggregate_qa_receipt)?{aggregate_qa_receipt:hi(l.aggregate_qa_receipt)}:{},...gi(l.head_reconciliation_receipt)?{head_reconciliation_receipt:gi(l.head_reconciliation_receipt)}:{},...Ia(l.story_worktree_evidence)?{story_worktree_evidence:structuredClone(l.story_worktree_evidence)}:{},...(r[S]?.length??0)>0?{story_worktree_leases:structuredClone(r[S])}:{},...(B=>B?{branch_mode_conversion_receipt:B}:{})(dc(l.branch_mode_conversion_receipt)),..._t(l.pr_number)?{pr_number:_t(l.pr_number)}:{},...X(l.physicalMergeStatus)?{physicalMergeStatus:X(l.physicalMergeStatus)}:{},...R(l.graph_revision)?{graph_revision:R(l.graph_revision)}:{},...fi(l.terminal_git_receipt)?{terminal_git_receipt:fi(l.terminal_git_receipt)}:{},...A?{lifecycle_classification:A}:{}}}const I=hc(n.current_session??n.currentSession),h=g(n.archPlan)?Sn(n.archPlan.execution):void 0,E=n.epic_id_ledger,_=Array.isArray(E?.reserved_ids)?[...new Set(E.reserved_ids.filter(S=>typeof S=="string"&&/^P\d+$/.test(S)))].slice(0,2048):[];return{schema_version:typeof n.schema_version=="number"?n.schema_version:void 0,config:{project_name:a.project_name??a.name??"unknown",default_branch:a.default_branch??"main",language:a.language??"pt-BR",yolo_mode:a.yolo_mode,user_name:a.user_name,worktree_base:a.worktree_base,max_parallel_stories:a.max_parallel_stories,project_id:typeof a.project_id=="string"?a.project_id:void 0},stories:s,epics:m,..._.length>0?{epic_id_ledger:{schema_version:1,reserved_ids:_}}:{},...I?{current_session:I}:{},...h?{archPlan:{execution:h}}:{}}}const er=[["P222.01","fbc3176b33687b13a8fadf8c7ea7cc06b6b6c500"],["P222.02","c7d3feb9a168f9e15b35516a972c767f3aa357da"],["P222.03","4d9bd4f2a1a3a1dc6399c572eb84b8b74c017806"],["P222.04","66590ef2f706c9d036f42edf5e517b237724f74f"],["P222.05","3ee2662538311e9788796340ed11b65864a8d8d5"],["P222.06","8660d07e3f68503a9ceb24dc138d24f62ab6cb45"],["P222.07","d99c80feacee8ea4033aa3322990147fffa2df91"],["P222.08","1f9e37dc922d87908efefb9595db32d32db30b00"],["P222.09","5ae12e485900992658e346cf3e38568fda1c2eeb"],["P222.10","6c5b8dc4f03d629fea4b62a33f4794af8e27e4f0"],["P222.11","cfe90f2f955c0027c57e4c621141d17912db65cc"],["P222.12","65f253c5cb600a8ee1dd94a1efdfef2fa5cd1629"],["P222.13","1e78c75b393515803a55d1a9b63a7fec23f710c9"],["P222.14","3f3e0bfd247a8581170df2a23c89497b5ae3641e"],["P222.15","1fd6dd25fffa5714d4ffa8b4303735e417f93de6"]],tr="6a41a47ff2521f80c2296ed811b0f0b304c54750",nr="dbc6d4670b2b7868a01973b1240e24589f1c5b7d",yi="30dccfff07f9c969be11ae1d28e62a09731a0768";function _c(e,t){try{const o=t.indexOf(yi);if(o<1||t[o-1]!==tr)return new Map;const n=Be("git",["show","--no-patch","--format=%P",yi],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim(),i=Be("git",["show","--no-patch","--format=%P",nr],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim();if(n!==`${tr} ${nr}`||i!==`${er.at(-1)[1]} ${tr}`)return new Map;const r=Be("git",["rev-list","--first-parent","--reverse",nr],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
|
|
9
|
+
`),a=new Map;let d=-1;for(const[s,[u,m]]of er.entries()){const I=r.indexOf(m);if(I<=d)return new Map;d=I,a.set(u,{headSha:m,position:s-er.length})}return a}catch{return new Map}}function Rc(e){return e instanceof Error&&(ha(e.message)||/^(?:p205|git-lifecycle)-[a-z0-9-]+$/.test(e.message))?e.message:"p205-transient-execution-failed"}async function wc(e,t,o){if(!mi(o))return{};if(o==="audit"||o==="yoloop")return{};if(Or(t,o))return{};try{const n=JSON.parse(Fe(J(e,".neocortex","state.json"),"utf8")),i=mn(e,{required:!0}),r=Ur(n,i),a=g(r.stories)?r.stories:{},d=g(r.epics)?r.epics:{},s=Be("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8"}).trim(),u=Be("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8"}).trim(),m=Be("git",["rev-list","--first-parent","--reverse",s],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
|
|
10
|
+
`).filter(Boolean),I=new Map(m.map((C,T)=>[C,T])),h=_c(e,m),E=t.match(/(?:^|\s)@?docs\/stories\/([A-Za-z][A-Za-z0-9._-]*)\.story\.md(?:\s|$)/)?.[1],_=o==="yoloop"?t.match(/(?:^|[\s/@])epic-(P[1-9][0-9]*)\.md(?:\s|$)/i)?.[1]?.toUpperCase():void 0,S=new Set,l=Object.entries(a).flatMap(([C,T])=>{if(E&&C!==E)return[];const P=g(T)?T:void 0,B=g(P?.checkpoint)?P.checkpoint:void 0;if(!B)return[];const D=typeof P?.epic_id=="string"?P.epic_id:C.split(".")[0];if(_&&D!==_)return[];const K=R(B?.headSha),ue=D==="P222"?h.get(C):void 0,x=I.get(K??"")??(ue&&ue.headSha===K?ue.position:void 0);if(!K||K.length<40||x===void 0)return S.add(D),[];const pe=g(d[D])?d[D]:void 0;if(pe?.branch_mode!=="epic"||Se(pe.execution_branch)!==u||Se(B.branch)!==u)return S.add(D),[];const oe=R(B.graphRevision);if(!oe||oe.length!==64)return S.add(D),[];const G=R(B.claimRevision),gt=[...$r(C,P,B)].sort(),wt=Sa(e,B,C,D,u,gt);if(!wt&&G){if(gt.length===0)return S.add(D),[];const he=Be("git",["diff-tree","--no-commit-id","--name-only","-r","-z",K],{cwd:e,encoding:"utf8"}).split("\0").filter(Boolean),N=fa(C,gt).map(xe=>[...xe].sort()).find(xe=>G===Ne("sha256").update(xe.join("\0")).digest("hex")||G===Ne("sha256").update(JSON.stringify(xe)).digest("hex"));if(!N)return S.add(D),[];let H=[];if(B.rootMemoryEffect!==void 0)try{H=va(e,B.rootMemoryEffect,{storyId:C,executionBranch:u,baseSha:String(B.baseSha),headRef:K,childPaths:N}).files.map(xe=>xe.path)}catch{return S.add(D),[]}if(he.length===0||he.some(xe=>!N.some(Te=>ma(Te,xe))&&!H.includes(xe)))return S.add(D),[]}else if(!wt)return S.add(D),[];return oe?.length===64?[{storyId:C,epicId:D,graphRevision:oe,checkpointHead:K,position:x}]:[]}),A=new Set(S);for(const[C,T]of Object.entries(d)){const P=g(T)?T:void 0,B=Array.isArray(P?.stories)?P.stories.filter(x=>typeof x=="string"):Object.keys(a).filter(x=>x.startsWith(`${C}.`)),D=l.filter(x=>x.epicId===C),K=B.filter(x=>D.some(pe=>pe.storyId===x)),ue=[...D].sort((x,pe)=>x.position-pe.position).map(x=>x.storyId);(JSON.stringify(K)!==JSON.stringify(ue)||new Set(ue).size!==ue.length)&&A.add(C)}const j={},k=[...new Set(l.filter(C=>!A.has(C.epicId)).map(C=>C.graphRevision))],O=k.length>0?await ua(e,{headSha:s,graphRevisions:k}):new Map;for(const C of l){if(A.has(C.epicId))continue;const T=O.get(C.graphRevision);if(!T)throw new Error("p205-transient-authority-missing");j[C.storyId]=T}return await Ac({projectRoot:e,commandId:o,targetEpicId:_,currentHead:s,epics:d,candidates:l,authorities:j}),j}catch(n){const i=Rc(n);return process.stderr.write(`[Neocortex] ${i}. Checkpoint projection remains fail-closed.
|
|
11
|
+
`),{}}}async function Ac(e){if(e.commandId!=="yoloop"||!e.targetEpicId)return;const t=e.epics[e.targetEpicId],o=g(t)?t:void 0,n=g(o?.aggregate_qa_receipt)?o.aggregate_qa_receipt:void 0,i=R(o?.graph_revision);if(!n||!i||i.length!==64||n.schemaVersion!==1||n.evidenceVersion!=="p205-execution-v2"||n.producer!=="local-yolo-tdd"||n.contract!=="P205-CI-02"||n.command!==Xt||n.verdict!=="passed"||n.executionHeadSha!==e.currentHead||n.graphRevision!==i||!Array.isArray(n.gateIds)||n.gateIds.length===0||!n.gateIds.every(I=>typeof I=="string")||typeof n.manifestDigest!="string"||!/^[a-f0-9]{64}$/i.test(n.manifestDigest)||typeof n.resultDigest!="string"||!/^[a-f0-9]{64}$/i.test(n.resultDigest)||typeof n.receiptRef!="string"||!/^local-yolo-tdd:[a-f0-9]{64}$/i.test(n.receiptRef))return;const r=n.gateIds,a=`local-yolo-tdd:${Ne("sha256").update(["epic-aggregate-p205-execution-v2",Xt,e.currentHead,i,n.manifestDigest,r.join(","),n.resultDigest].join("\0")).digest("hex")}`;if(n.receiptRef!==a)return;const d=e.candidates.find(I=>I.epicId===e.targetEpicId&&I.graphRevision===i&&e.authorities[I.storyId]),s=d?Ea(e.authorities[d.storyId]):void 0;if(!s||s.executionHeadSha!==e.currentHead||s.graphRevision!==i||s.manifestDigest!==n.manifestDigest||!bc(s.gateIds,r))return;const u=`local-yolo-tdd:${Ne("sha256").update(["epic-aggregate-p205-execution-v2",Xt,e.currentHead,i,s.manifestDigest,s.gateIds.join(","),s.resultDigest].join("\0")).digest("hex")}`,m=n.receiptRef;await Hr(e.projectRoot,I=>{const h=pa(I,e.targetEpicId),E=g(h.aggregate_qa_receipt)?h.aggregate_qa_receipt:void 0;!E||E.executionHeadSha!==e.currentHead||E.graphRevision!==i||E.receiptRef!==m||(h.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:i,manifestDigest:s.manifestDigest,resultDigest:s.resultDigest,checkedAt:s.executedAt,receiptRef:u,gateIds:[...s.gateIds]})})}function bc(e,t){if(e.length!==t.length)return!1;const o=[...t].sort();return[...e].sort().every((n,i)=>n===o[i])}function ep(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 Ii="neocortex:menu:cache";async function xc(e){try{const t=await e.get(Ii);if(!t)return null;const o=JSON.parse(t);return o.version!==Pt||Date.now()-o.cachedAt>qr?null:o}catch{return null}}async function Tc(e,t,o){try{const n={instructions:t,metadata:o,cachedAt:Date.now(),version:Pt};await e.set(Ii,JSON.stringify(n),qr),Pc()}catch{}}function Pc(){try{jt(Yr)&&Mn(Yr)}catch{}}function Ei(e){return e.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>Bn(),()=>Bn({strictReadOnly:!0}))}async function Si(e,t,o){const n=o.mode==="strict";try{let i;if(n&&t)i=new Vn({cacheDir:Wn,passphrase:t,strictReadOnly:!0});else if(n)i=new br;else if(t){const m=J(yn,"cache");i=new Vn({cacheDir:m,passphrase:t})}else process.stderr.write(`[neocortex] Warning: No license key in config. Run "neocortex activate" to re-authenticate.
|
|
12
|
+
`),i=new br;const r=Vr(o,i,"auth-cache"),a=Vr(o,i,"tier-cache"),d=new uo({serverUrl:e,licenseKey:t??"",cacheProvider:r,strictReadOnly:n});let s;if(n){const m=await d.inspectToken();if(m.status!=="authenticated")return m;s=m.token}else s=await d.getToken();if(!s)return t?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"};const u=new ho({cacheProvider:a,licenseClient:d});return{status:"authenticated",token:s,client:d,tierClient:u}}catch{return t?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"}}}let vi=!1;function kc(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 Ci=3,Rn=50;function Oc(e){return new Promise(t=>setTimeout(t,e))}function Nc(e,t,o){return e.status>=500&&e.status<=599?!0:o&&e.status===409&&t.error_code==="SIGNATURE_REPLAYED"}async function Zt(e,t,o,n,i={}){const r=Math.max(1,Math.min(i.maxAttempts??Ci,Ci)),a=i.sleep??Oc;let d=n,s=!1,u=!1,m=0;for(let I=1;I<=r;I+=1){const h=Math.max(Math.floor(Date.now()/1e3),m+1);m=h;const E=Lc(t,o,d,{nowSeconds:h}),_=new AbortController,S=setTimeout(()=>_.abort(),zr);try{const l=await fetch(`${e}${t}`,{method:"POST",headers:E.headers,body:E.body,signal:_.signal});if(i.admitResponseBeforeBodyRead&&!i.admitResponseBeforeBodyRead(l))return{response:l,text:"",parsed:{},networkFailure:!1,responseAdmissionRejected:!0};const A=await l.text().catch(()=>""),j=l.ok&&i.deferSuccessfulJsonParsing?{}:(()=>{try{return A?JSON.parse(A):{}}catch{return{}}})();if(l.status===401&&!s&&i.refreshToken&&(j.fallback_action==="refresh_token"||j.fallback_action==="re_authenticate")){s=!0;const k=await i.refreshToken();if(k&&I<r){d=k,i.onTokenChanged?.(k),await a(Rn*I);continue}}if(l.status===401&&j.error_code==="SIGNATURE_EXPIRED"&&!u&&I<r){u=!0,await a(Rn*I);continue}if(I<r&&Nc(l,j,i.allowReplayRetry===!0)){await a(Rn*I);continue}return{response:l,text:A,parsed:j,networkFailure:!1}}catch{if(I<r){await a(Rn*I);continue}return{text:"",parsed:{},networkFailure:!0}}finally{clearTimeout(S)}}return{text:"",parsed:{},networkFailure:!0}}function Lc(e,t,o,n={}){const i=Buffer.from(JSON.stringify(t),"utf8"),r=Mo({method:"POST",target:e,body:i,bearerToken:o,clientVersion:Pt,nowSeconds:n.nowSeconds,nonceBytes:n.nonceBytes});return{body:r.body,headers:{...r.headers,Authorization:`Bearer ${o}`}}}function _i(e){return Ne("sha256").update(e).digest("hex")}function Dc(){const e=Number(process.env.NEOCORTEX_INVOKE_CHUNK_BYTES??"49152");return Number.isFinite(e)&&e>=1024&&e<=98304?Math.floor(e):49152}function Mc(e,t,o){return`args-${Ne("sha256").update("invoke-materialization:v1").update(e).update(String(t)).update(JSON.stringify(o)).digest("hex")}`}async function Ri(e,t,o,n,i={}){const r=await Zt(e,t,o,n,{...i,allowReplayRetry:!0});if(r.networkFailure||!r.response)throw new Error("NETWORK_ERROR: materialization request failed after bounded retries");const{response:a,parsed:d}=r;if(!a.ok){const s=typeof d.error_code=="string"?d.error_code:`HTTP_${a.status}`,u=typeof d.message=="string"?d.message:"materialization upload failed";throw new Error(`${s}: ${u}`)}return d}async function jc(e,t,o,n){const i=Buffer.from(t,"utf8"),r=Dc(),a=[];for(let _=0,S=0;_<i.byteLength;_+=r,S++){const l=i.subarray(_,Math.min(_+r,i.byteLength));a.push({index:S,sha256:_i(l),byteLength:l.byteLength})}const d=_i(i),s=Mc(d,i.byteLength,a),u=Number(process.env.NEOCORTEX_INVOKE_CHUNK_TTL_SECONDS??"900");let m=o;const I={refreshToken:n,onTokenChanged(_){m=_}};for(const _ of a){const S=_.index*r,l=i.subarray(S,S+_.byteLength);await Ri(e,"/api/v1/invoke/materialization/chunks",{manifestId:s,index:_.index,sha256:_.sha256,byteLength:_.byteLength,contentBase64:l.toString("base64"),ttlSeconds:u,idempotencyKey:`${s}:${_.index}:${_.sha256}`},m,I)}const E=(await Ri(e,"/api/v1/invoke/materialization/manifests",{manifestId:s,sha256:d,byteLength:i.byteLength,chunkCount:a.length,chunks:a,ttlSeconds:u,retry:{attempt:1,budget:3,idempotencyKey:s}},m,I)).argsRef;if(!E?.manifestId)throw new Error("MATERIALIZATION_RESPONSE_INVALID: missing argsRef");return{argsRef:E,chunks:a}}function Wt(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function Vc(...e){const t=new Set,o=[];for(const n of e)for(const i of n??[]){const r=X(i);if(!(!r||t.has(r))&&(t.add(r),o.push(r),o.length>=16))return o}return o}function Bc(e){const t=e.graphRetrieval;if(!g(t))return{accepted:!1,itemCount:0};const o=Array.isArray(t.items)?t.items.length:0;return{accepted:o>0||typeof t.retrievalId=="string"||t.accepted===!0,itemCount:o}}function rr(e,t=Wt(e),o=[],n={}){const i=e.stateSnapshot.scope,r=Object.keys(e.stateSnapshot.stories).length,a=Object.keys(e.stateSnapshot.epics).length,d=i?.kind??"full";return{schemaVersion:1,payloadBytes:t,limitBytes:n.limitBytes??Kr,warningThresholdBytes:n.warningThresholdBytes??Gn,scope:{kind:d,...i?.projectionMode?{projectionMode:i.projectionMode}:{},commandId:i?.commandId??null,stateProjectionPolicy:i?.stateProjectionPolicy??null},includedStories:i?.includedStoryCount??r,omittedStories:i?.omittedStoryCount??0,includedEpics:i?.includedEpicCount??a,omittedEpics:i?.omittedEpicCount??0,graphRetrieval:Bc(e.stateSnapshot),reasonCodes:Vc(o,i?.reasonCodes),publicSafe:!0}}function Uc(e){const t=g(e.budget)?e.budget:void 0,o=typeof t?.maxPayloadBytes=="number"&&Number.isFinite(t.maxPayloadBytes)?t.maxPayloadBytes:12*1024;return Math.max(1024,Math.min(o,12*1024))}function $c(e){return g(e)?{stableId:X(e.stableId)??"unknown",...g(e.source)?{source:e.source}:{},reasonCode:"budget_exceeded"}:{stableId:"unknown",reasonCode:"budget_exceeded"}}function wi(e){const t=Array.isArray(e)?e.filter(o=>typeof o=="string"):[];return t.includes("budget_exceeded")?t:[...t,"budget_exceeded"]}function Hc(e){const t=e.graphRetrieval;if(!g(t)||!Array.isArray(t.items))return e;const o=Uc(t);let n=[...t.items],i=Array.isArray(t.skipped)?[...t.skipped]:[],r=t;for(;Buffer.byteLength(JSON.stringify(r),"utf8")>o&&n.length>0;){const a=n.pop();i=[...i,$c(a)].slice(-32),r={...t,items:n,skipped:i,warnings:wi(t.warnings)}}return Buffer.byteLength(JSON.stringify(r),"utf8")>o&&(r={...t,query:typeof t.query=="string"?t.query.slice(0,240):t.query,items:[],skipped:[],warnings:wi(t.warnings)}),r===t?e:{...e,graphRetrieval:r}}function ir(e,t={}){const o=t.limitBytes??Kr,n=t.warningThresholdBytes??Math.floor(o*Qr),i=Wt(e);if(i<o)return{body:e,degraded:!1,telemetry:rr(e,i,["payload-within-limit"],{limitBytes:o,warningThresholdBytes:n})};let r={...e,stateSnapshot:Eo(e.stateSnapshot)},a=["payload-size-guardrail","state-degraded"],d=Wt(r);d>=o&&(r={...r,stateSnapshot:Hc(r.stateSnapshot)},a=[...a,"graph-retrieval-budget-enforced"],d=Wt(r));const s=rr(r,d,a,{limitBytes:o,warningThresholdBytes:n});if(d>=o){const u=r.stateSnapshot.scope?.projectionMode;throw u==="yolo-story"||u==="yoloop-target"||u==="yoloop-session"||u==="yoloop-discovery"||u==="structural-required"?new Kn(s):new Jn(s)}return{body:r,degraded:!0,telemetry:s}}function Ai(e){const t=e.stateSnapshot.scope?.commandId??"resolved-command";return e.args!==void 0?t:`${t}:argsRef`}function Wc(e){const t=Wt(e);if(t<Gn)return t;const o=rr(e,t,["payload-warning-threshold"]);return process.stderr.write(`[Neocortex] invoke payload near server limit: trigger=${Ai(e)} scope=${o.scope.kind} mode=${o.scope.projectionMode??o.scope.kind} payloadBytes=${o.payloadBytes} limit=${o.limitBytes} includedStories=${o.includedStories} omittedStories=${o.omittedStories} includedEpics=${o.includedEpics} omittedEpics=${o.omittedEpics} graphRetrieval.accepted=${o.graphRetrieval.accepted} graphRetrieval.itemCount=${o.graphRetrieval.itemCount} reasonCodes=${o.reasonCodes.join(",")||"none"}
|
|
13
|
+
`),t}function bi(e,t){process.stderr.write(`[Neocortex] invoke payload guardrail: trigger=${Ai(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 Gc(e){const t=bo(e.args,{platformTarget:e.platformTarget,environment:e.environment??process.env});if(t.action==="skipped")return{shouldContinue:!0,attachToRequest:Fc(t),metadata:xi(t)};const o=e.bootstrapper??To;let n;try{n=await o({projectRoot:e.projectRoot,env:e.environment??process.env,effectAuthority:e.effectAuthority})}catch{n={ok:!1,attempted:!0,installed:!1,started:!1,cached:!1,projectKey:"unknown",reasonCodes:[xo.UNEXPECTED_ERROR],publicSummary:"runner scheduler bootstrap stopped unexpectedly.",publicSafe:!0}}const i=xi(t,n);if(n.ok)return{shouldContinue:!0,attachToRequest:!0,metadata:i};const r=i.reasonCodes.slice(0,5).join(",");return t.failurePolicy==="fail-open"?{shouldContinue:!0,attachToRequest:!0,metadata:{...i,failOpenWarning:!0},warning:`Runner auto-bootstrap warning (${r}); continuing fail-open for operator command.`}:{shouldContinue:!1,attachToRequest:!1,metadata:i,errorCode:"RUNNER_BOOTSTRAP_REQUIRED_FAILED",error:`Runner auto-bootstrap required but failed (${r}). Run neocortex-runner doctor or retry after resolving scheduler setup.`,exitCode:1}}function Fc(e){return!e.reasonCodes.includes(Ao.SKIPPED_NON_CONTINUITY_COMMAND)}function xi(e,t){return{schemaVersion:1,action:e.action,failurePolicy:e.failurePolicy,command:e.command,operation:e.operation,attempted:t?.attempted??!1,ok:t?.ok??!0,cached:t?.cached??!1,installed:t?.installed??!1,started:t?.started??!1,...t?.projectKey?{projectKey:t.projectKey}:{},reasonCodes:Ue([...e.reasonCodes,...t?.reasonCodes??[]]),publicSummary:t?.publicSummary??e.publicSummary,publicSafe:!0}}function Ue(e){return Array.from(new Set(e.map(t=>t.slice(0,120))))}function wn(e,t,o){const n=Math.floor(e??t);return Number.isFinite(n)?Math.max(1,Math.min(o,n)):t}function An(e,t){const o=process.env[e];if(!o)return t;const n=Number(o);return Number.isFinite(n)?n:t}function q(e,t=ri){const o=typeof e=="string"&&e.trim().length>0?e.trim():"unknown",n=Je(o,t),i=Fa.test(n)?Ct:n;return i.length<=t?i:`${i.slice(0,t)}\u2026[TRUNCATED:${i.length-t}]`}function or(e,t=ri){if(!(typeof e!="string"||e.trim().length===0))return q(e,t)}function ar(e,t,o,n){const i=or(e?.targetId??t,120),r=e?.selectorKind??(i?sr(i):void 0),a=(e?.relatedJobIds??[]).map(d=>or(d,120)).filter(d=>!!d);return{schemaVersion:1,contractVersion:"continuity-v1",targetResolutionState:o,...r?{targetKind:r}:{},...i?{targetId:i}:{},...t?{targetJobId:q(t,120)}:{},...e?.jobId?{jobId:q(e.jobId,120)}:{},...e?.goalId?{goalId:q(e.goalId,120)}:{},...e?.loopId?{loopId:q(e.loopId,120)}:{},...a.length>0?{relatedJobIds:a}:{},relatedJobCount:a.length,reasonCodes:Ue(n.length>0?n:[Y.OK]),publicSafe:!0}}function ut(e,t,o,n,i=[]){const r=(e?.redactions?.length??0)>0,a=e?r?"unsafe":o&&n===0?"empty":"available":"unavailable",d=or(t[t.length-1]?.eventId,120),s=i.length>0?i:a==="unavailable"?[Y.WATCH_SNAPSHOT_UNAVAILABLE]:a==="empty"?[Y.WATCH_NO_SUMMARIES_YET]:[Y.OK];return{schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:a,...e?.generatedAt?{generatedAt:q(e.generatedAt,80)}:{},renderedSummaryCount:n,...d?{latestEventId:d}:{},reasonCodes:Ue(s),publicSafe:!0}}function et(e,t,o,n,i=[],r){const a=n[n.length-1],d=o??a?.cursor,s=!!(d&&d!==t&&n.length>0),u=r??(s?"advanced":t||d?"unchanged":"not_started"),m=i.length>0?i:u==="advanced"?[Y.WATCH_CURSOR_ADVANCED]:u==="unavailable"?[Y.WATCH_EVIDENCE_UNAVAILABLE]:[Y.WATCH_CURSOR_UNCHANGED];return{schemaVersion:1,contractVersion:"continuity-v1",cursorState:u,...e?{initialCursor:q(e,200)}:{},...t?{currentCursor:q(t,200)}:{},...d?{nextCursor:q(d,200)}:{},cursorAdvanced:s,...a?.eventId?{eventId:q(a.eventId,120)}:{},reasonCodes:Ue(m),publicSafe:!0}}function tt(e){const t=e.targetEvidence;return{type:"watch_status",schemaVersion:1,contractVersion:"continuity-v1",recordType:"watch_status",command:"invoke",operation:"watch",watchStatus:e.watchStatus,active:e.active,...t?.targetResolutionState?{targetResolutionState:t.targetResolutionState}:{},...t?.targetKind?{targetKind:t.targetKind}:{},...t?.targetId?{targetId:t.targetId}:{},...t?{targetEvidence:t}:{},...e.snapshotEvidence?{snapshotEvidence:e.snapshotEvidence}:{},...e.cursorEvidence?{cursorEvidence:e.cursorEvidence}:{},...e.stopReason?{stopReason:e.stopReason}:{},reasonCodes:Ue([...e.reasonCodes??[],...t?.reasonCodes??[],...e.snapshotEvidence?.reasonCodes??[],...e.cursorEvidence?.reasonCodes??[]]),generatedAt:q(e.generatedAt??new Date().toISOString(),80),publicSafe:!0}}function Yc(e){const t=e.targetKind&&e.targetId?`${e.targetKind}/${e.targetId}`:e.targetId??"[unresolved]",o=e.snapshotEvidence?.renderedSummaryCount??0,n=e.targetEvidence?.relatedJobCount??0,i=e.cursorEvidence?.cursorState??"unavailable",r=e.cursorEvidence?.currentCursor??"[none]",a=e.cursorEvidence?.nextCursor??"[none]",d=e.snapshotEvidence?.snapshotStatus??"not_requested",s=e.snapshotEvidence?.generatedAt??e.generatedAt;return[`[watch-status] ${e.targetResolutionState==="unresolved"||e.stopReason==="target_unresolved"?"unresolved-target":o===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=${n}`,`summaries=${o}`,`snapshot=${d}`,`generatedAt=${s}`,`cursor=${i}`,`current=${q(r,200)}`,`next=${q(a,200)}`,`advanced=${e.cursorEvidence?.cursorAdvanced??!1}`,`stop=${e.stopReason??"not_stopped"}`,`reasons=${e.reasonCodes.join(",")}`].join(" ")}function nt(e,t,o,n=!1){if(n){const i={type:"watch_status",watchStatus:e.watchStatus,active:e.active,renderedSummaryCount:e.snapshotEvidence?.renderedSummaryCount??0,stopReason:e.stopReason??"not_stopped",protectedProjection:!0,publicSafe:!0};o.write(t==="json"?`${JSON.stringify(i)}
|
|
15
|
+
`:`[watch-status] status=${i.watchStatus} active=${i.active} summaries=${i.renderedSummaryCount} stop=${i.stopReason}
|
|
16
|
+
`);return}if(t==="json"){o.write(JSON.stringify(e)+`
|
|
17
|
+
`);return}o.write(Yc(e)+`
|
|
18
|
+
`)}function qc(e,t,o){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:o,statusRecord:e,publicSafe:!0}}}function ht(e,t,o,n,i=!1){return i?{status:e,summariesEmitted:t,polls:o,reasonCodes:[],watchStatus:n.watchStatus,stopReason:n.stopReason,metadata:{continuityInvokeWatch:{schemaVersion:1,contractVersion:"continuity-v1",command:"invoke",operation:"watch",watchStatus:n.watchStatus,stopReason:n.stopReason??"not_stopped",summariesEmitted:t,polls:o,protectedProjection:!0,publicSafe:!0}},publicSafe:!0}:{status:e,summariesEmitted:t,polls:o,reasonCodes:n.reasonCodes,watchStatus:n.watchStatus,stopReason:n.stopReason,targetEvidence:n.targetEvidence,snapshotEvidence:n.snapshotEvidence,cursorEvidence:n.cursorEvidence,statusRecord:n,metadata:qc(n,t,o),publicSafe:!0}}function zc(e){const t=e.reasonCode?` reason=${q(e.reasonCode,80)}`:"",o=e.goalId?` goal=${q(e.goalId,100)}`:"",n=e.loopId?` loop=${q(e.loopId,100)}`:"";return`[watch] ${q(e.createdAt,80)} event=${q(e.eventId,120)} job=${q(e.jobId,100)}${o}${n} execution=${q(e.executionId,120)}${t} -- ${q(e.publicSummary)}`}function Jc(e){return{type:"processing_summary",source:"local_continuity_sqlite",eventId:q(e.eventId,120),jobId:q(e.jobId,100),...e.goalId?{goalId:q(e.goalId,100)}:{},...e.loopId?{loopId:q(e.loopId,100)}:{},executionId:q(e.executionId,120),...e.reasonCode?{reasonCode:q(e.reasonCode,80)}:{},createdAt:q(e.createdAt,80),publicSummary:q(e.publicSummary),publicSafe:!0}}function Kc(e,t,o,n=!1){if(n){o.write(t==="json"?`${JSON.stringify({type:"processing_summary",source:"local_continuity_sqlite",publicSummary:"A local processing update is available.",protectedProjection:!0,publicSafe:!0})}
|
|
19
19
|
`:`[watch] A local processing update is available.
|
|
20
|
-
`);return}if(t==="json"){
|
|
21
|
-
`);return}
|
|
22
|
-
`)}function cr(e){return Ha.has(e.status)}function Yc(e,t,i){if(t){const o=e.find(n=>n.jobId===t);return!!(o&&cr(o))}return i<=0?!1:e.filter(o=>!cr(o)).length===0}function qc(e,t,i,r){return i<r?!1:t?!e.some(o=>o.jobId===t&&!cr(o)):e.length===0}function zc(e,t){return t?.aborted?Promise.resolve():new Promise(i=>{const r=setTimeout(o,e);function o(){clearTimeout(r),t?.removeEventListener("abort",o),i()}t?.addEventListener("abort",o,{once:!0})})}function Jc(e){return e.includes(Le.MALFORMED)?"malformed":e.includes(Le.AMBIGUOUS)?"ambiguous":e.includes("watch-target-multiple")?"multiple":e.includes("watch-evidence-unsafe")?"unsafe":e.includes(Le.MISSING)||e.includes(_e.TARGET_UNRESOLVED)?"unresolved":"unavailable"}function xi(e,t){const i=t?en(t):void 0,r=Ue([...e,_e.TARGET_UNRESOLVED,G.WATCH_TARGET_UNRESOLVED]),o=ar(i,i?.targetId,Jc(r),r),n=ut({generatedAt:new Date().toISOString()},[],!1,0,[G.WATCH_TARGET_UNRESOLVED]),a=et(void 0,void 0,void 0,[],[G.WATCH_TARGET_UNRESOLVED],"unavailable");return tt({watchStatus:"blocked",active:!1,targetEvidence:o,snapshotEvidence:n,cursorEvidence:a,stopReason:"target_unresolved",reasonCodes:r,generatedAt:n.generatedAt})}function Kc(e,t,i,r,o=!1){const n=xi(e,Pi(t));return nt(n,i,r,o),ht("target-unresolved",0,0,n,o)}async function Qc(e){if(e.signal?.aborted){const k=ar(e.target??en(e.targetJobId),e.targetJobId,e.target??e.targetJobId?"resolved":"unresolved",[_e.CANCELLED]),_=ut(void 0,[],!1,0),w=et(e.initialCursor,e.initialCursor,e.initialCursor,[],[_e.CANCELLED],"unavailable"),L=tt({watchStatus:"stopped",active:!1,targetEvidence:k,snapshotEvidence:_,cursorEvidence:w,stopReason:"cancelled",reasonCodes:[_e.CANCELLED]});return ht("cancelled",0,0,L,e.protectedOutput)}const t=e.target??en(e.targetJobId),i=e.targetJobId??t?.targetId,r=e.stdout??process.stdout;if(!t){const k=xi([Le.MISSING,_e.TARGET_UNRESOLVED]);return nt(k,e.format,r,e.protectedOutput),ht("target-unresolved",0,0,k,e.protectedOutput)}const o=wn(e.limit??An("NEOCORTEX_INVOKE_WATCH_LIMIT",Lr),Lr,50),n=Math.max(50,wn(e.pollIntervalMs??An("NEOCORTEX_INVOKE_WATCH_POLL_INTERVAL_MS",jr),jr,6e4)),a=wn(e.maxIdlePolls??An("NEOCORTEX_INVOKE_WATCH_MAX_IDLE_POLLS",Dr),Dr,120),d=wn(e.maxPolls??An("NEOCORTEX_INVOKE_WATCH_MAX_POLLS",Mr),Mr,86400),s=e.sleep??zc;let l=e.initialCursor,m=0,S=0,u=0;const v=ar(t,i,"resolved",[G.OK]),I={schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:"pending",renderedSummaryCount:0,reasonCodes:[G.WATCH_RENDER_PENDING],publicSafe:!0},g=et(e.initialCursor,l,l,[],e.initialCursor?[G.WATCH_CURSOR_UNCHANGED]:[G.WATCH_NO_SUMMARIES_YET],e.initialCursor?"unchanged":"not_started");nt(tt({watchStatus:"active",active:!0,targetEvidence:v,snapshotEvidence:I,cursorEvidence:g,stopReason:"not_stopped",reasonCodes:[G.OK]}),e.format,r,e.protectedOutput);let E;try{E=await Po({projectRoot:e.projectRoot,strictReadOnly:e.strictReadOnly})}catch{const k=ut(void 0,[],!1,m,[G.WATCH_SNAPSHOT_UNAVAILABLE]),_=et(e.initialCursor,l,l,[],[G.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),w=tt({watchStatus:"blocked",active:!1,targetEvidence:v,snapshotEvidence:k,cursorEvidence:_,stopReason:"unavailable_evidence",reasonCodes:[_e.STORE_UNAVAILABLE]});return nt(w,e.format,r,e.protectedOutput),ht("store-unavailable",m,u,w,e.protectedOutput)}try{for(;!e.signal?.aborted&&u<d;){u+=1;const k=l,_=E.collectProcessingOutputSummaryCursor({...l?{cursor:l}:{},...t?{target:t}:{},...i?{jobId:i}:{},limit:o}),w=E.collectSnapshot({jobLimit:50,processingSummaryLimit:1}),L=w.jobs;if(_.summaries.length>0){for(const X of _.summaries)Fc(X,e.format,r,e.protectedOutput),m+=1;l=_.nextCursor??_.summaries[_.summaries.length-1]?.cursor??l,S=0}else l=_.nextCursor??l,S+=1;const D=ut(w,_.summaries,!0,_.summaries.length),Y=et(e.initialCursor,k,l,_.summaries,_.summaries.length>0?[G.WATCH_CURSOR_ADVANCED]:[G.WATCH_NO_SUMMARIES_YET]);if(nt(tt({watchStatus:_.summaries.length>0?"polling":"waiting",active:!0,targetEvidence:v,snapshotEvidence:D,cursorEvidence:Y,stopReason:"not_stopped",reasonCodes:_.summaries.length>0?[G.WATCH_CURSOR_ADVANCED]:[G.WATCH_NO_SUMMARIES_YET],generatedAt:w.generatedAt}),e.format,r,e.protectedOutput),!_.hasMore&&Yc(L,i,m)){const X=ut(w,_.summaries,!1,m,[_e.COMPLETED]),pe=et(e.initialCursor,k,l,_.summaries,[_e.COMPLETED],"exhausted"),b=tt({watchStatus:"stopped",active:!1,targetEvidence:v,snapshotEvidence:X,cursorEvidence:pe,stopReason:"not_stopped",reasonCodes:[_e.COMPLETED],generatedAt:w.generatedAt});return nt(b,e.format,r,e.protectedOutput),ht("completed",m,u,b,e.protectedOutput)}if(!_.hasMore&&qc(L,i,S,a)){const X=ut(w,_.summaries,!1,m,[G.WATCH_STOP_IDLE_LIMIT_REACHED]),pe=et(e.initialCursor,k,l,_.summaries,[G.WATCH_STOP_IDLE_LIMIT_REACHED],"exhausted"),b=tt({watchStatus:"stopped",active:!1,targetEvidence:v,snapshotEvidence:X,cursorEvidence:pe,stopReason:"idle_limit_reached",reasonCodes:[_e.IDLE_TIMEOUT,G.WATCH_STOP_IDLE_LIMIT_REACHED],generatedAt:w.generatedAt});return nt(b,e.format,r,e.protectedOutput),ht("idle-timeout",m,u,b,e.protectedOutput)}_.hasMore||await s(n,e.signal)}}catch{const k=ut(void 0,[],!1,m,[G.WATCH_SNAPSHOT_UNAVAILABLE]),_=et(e.initialCursor,l,l,[],[G.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),w=tt({watchStatus:"blocked",active:!1,targetEvidence:v,snapshotEvidence:k,cursorEvidence:_,stopReason:"unavailable_evidence",reasonCodes:[_e.STORE_UNAVAILABLE]});return nt(w,e.format,r,e.protectedOutput),ht("store-unavailable",m,u,w,e.protectedOutput)}finally{E.close()}if(e.signal?.aborted){const k=ut(void 0,[],!1,m,[_e.CANCELLED]),_=et(e.initialCursor,l,l,[],[_e.CANCELLED],"unavailable"),w=tt({watchStatus:"stopped",active:!1,targetEvidence:v,snapshotEvidence:k,cursorEvidence:_,stopReason:"cancelled",reasonCodes:[_e.CANCELLED]});return nt(w,e.format,r,e.protectedOutput),ht("cancelled",m,u,w,e.protectedOutput)}const x=ut(void 0,[],!1,m,[G.WATCH_STOP_MAX_POLLS_REACHED]),M=et(e.initialCursor,l,l,[],[G.WATCH_STOP_MAX_POLLS_REACHED],"exhausted"),P=tt({watchStatus:"stopped",active:!1,targetEvidence:v,snapshotEvidence:x,cursorEvidence:M,stopReason:"max_polls_reached",reasonCodes:[_e.MAX_POLLS,G.WATCH_STOP_MAX_POLLS_REACHED]});return nt(P,e.format,r,e.protectedOutput),ht("max-polls",m,u,P,e.protectedOutput)}function Ke(e){const t=e.trim().replace(/^@/,"").match(/^(job|goal|loop)-([JGL])(\d{3,})$/i);if(!t)return;const i=t[1].toLowerCase(),r=t[2].toUpperCase();if(!(i==="job"&&r!=="J"||i==="goal"&&r!=="G"||i==="loop"&&r!=="L"))return`${i}-${r}${t[3]}`}function sr(e){if(e.startsWith("job-J"))return"job";if(e.startsWith("goal-G"))return"goal";if(e.startsWith("loop-L"))return"loop"}function Ti(e){const t=[],i=/(?:^|[\s"'([,{])@?(job-[Jj]\d{3,}|goal-[Gg]\d{3,}|loop-[Ll]\d{3,})(?=$|[\s"')\]},.;:!?])/g;let r;for(;(r=i.exec(e))!==null;){const o=Ke(r[1]);o&&t.push(o)}return Ue(t)}function Pi(e){return Ti(e)[0]}function en(e){const t=e?Ke(e):void 0;if(t){if(t.startsWith("job-J"))return{selectorKind:"job",targetId:t,jobId:t,publicSafe:!0};if(t.startsWith("goal-G"))return{selectorKind:"goal",targetId:t,goalId:t,publicSafe:!0};if(t.startsWith("loop-L"))return{selectorKind:"loop",targetId:t,loopId:t,publicSafe:!0}}}function dr(e){return Ue(e.filter(t=>typeof t=="string").map(t=>Ke(t)).filter(t=>!!t?.startsWith("job-J")))}function Xc(e,t){const i=dr(t).filter(r=>r!==e.targetId&&r!==e.jobId);return i.length>0?{...e,relatedJobIds:i}:e}function Zc(e){if(!e)return;const t=h(e.target)?e.target:void 0,i=typeof e.selectorKind=="string"?e.selectorKind:typeof t?.selectorKind=="string"?t.selectorKind:void 0,r=typeof e.targetId=="string"?Ke(e.targetId):typeof t?.targetId=="string"?Ke(t.targetId):typeof e.targetJobId=="string"?Ke(e.targetJobId):void 0,o=en(r);if(!o||i&&i!==o.selectorKind)return;const n=Array.isArray(e.relatedJobIds)?e.relatedJobIds:Array.isArray(t?.relatedJobIds)?t.relatedJobIds:void 0,a=dr([...n??[],e.jobId,t?.jobId,e.targetJobId,t?.targetJobId]).filter(d=>d!==o.targetId&&d!==o.jobId);return{...o,...typeof(e.jobId??t?.jobId)=="string"?{jobId:Ke(e.jobId??t?.jobId)??o.jobId}:{},...typeof(e.goalId??t?.goalId)=="string"?{goalId:Ke(e.goalId??t?.goalId)??o.goalId}:{},...typeof(e.loopId??t?.loopId)=="string"?{loopId:Ke(e.loopId??t?.loopId)??o.loopId}:{},...a.length>0?{relatedJobIds:a}:{}}}function ki(e){const t=e.trim().split(/\s+/).filter(Boolean),i=t[0]?.replace(/^\*/,"").toLowerCase(),r=t[1]?.replace(/^--/,"").toLowerCase();return(i==="jobs"||i==="job"||i==="continuity-jobs"||i==="61")&&r==="watch"}const be=Object.freeze({ACTIVE:"command-level-watch-active",INACTIVE:"command-level-watch-inactive",DUPLICATE:"command-level-watch-duplicate",AMBIGUOUS:"command-level-watch-ambiguous",QUOTED:"command-level-watch-quoted",MALFORMED:"command-level-watch-malformed",NON_FINAL:"command-level-watch-non-final",UNRESOLVED:"command-level-watch-unresolved",UNSUPPORTED:"command-level-watch-unsupported",TARGET_INVALID:"command-level-watch-target-invalid"}),es=new Set(["create","start","resume"]),ts=new Set(["create","resume","run-once"]);function pr(e,t,i,r,o){return{schemaVersion:1,contractVersion:"continuity-v1",...i?{command:i}:{},...r?{operation:r}:{},active:e,...o?{watchToken:o}:{},reasonCodes:Ue(t),serverHeldStream:!1,allJobsPolling:!1,targetResolution:e?"required-after-dispatch":"inactive",publicSafe:!0}}function Me(e,t=[],i,r){const o=t.length>0?t:[be.INACTIVE];return{args:e,watch:!1,reasonCodes:o,metadata:pr(!1,o,i,r),publicSafe:!0}}function ns(e){const t=e.trim().split(/\s+/).filter(Boolean),i=t.slice(2).filter(n=>n==="--watch").length;if(i===0)return Me(e,[],"jobs","watch");if(i!==1)return Me(e,[be.AMBIGUOUS],"jobs","watch");const r=t.filter((n,a)=>a<2||n!=="--watch").join(" ");return ki(r)?r.trim().split(/\s+/).filter(Boolean).slice(2).length!==1?Me(e,[be.AMBIGUOUS],"jobs","watch"):Pi(r)?{args:r,watch:!0,reasonCodes:[be.ACTIVE],metadata:pr(!0,[be.ACTIVE],"jobs","watch"),publicSafe:!0}:Me(e,[be.TARGET_INVALID],"jobs","watch"):Me(e,[be.UNSUPPORTED],"jobs","watch")}function rs(e){const t=[];let i=!1,r=0;for(;r<e.length;){for(;r<e.length&&/\s/.test(e[r]);)r+=1;if(r>=e.length)break;const o=r;let n="",a=!1,d=null;for(;r<e.length;){const s=e[r];if(d){if(s===d){a=!0,d=null,r+=1;continue}if(s==="\\"&&r+1<e.length){n+=e[r+1],r+=2;continue}n+=s,r+=1;continue}if(/\s/.test(s))break;if(s==='"'||s==="'"){a=!0,d=s,r+=1;continue}n+=s,r+=1}d&&(i=!0),t.push({value:n,start:o,end:r,quoted:a})}return{tokens:t,malformed:i}}function is(e){if(!e||e.quoted)return;const t=e.value.replace(/^\*/,"").toLowerCase();return t==="goal"||t==="loop"?t:void 0}function os(e,t){if(!e||e==="jobs"||!t||t.quoted)return;const i=t.value.toLowerCase();return(e==="goal"?es:ts).has(i)?i:void 0}function as(e){return!e.quoted&&e.value!=="--watch"&&e.value.toLowerCase().startsWith("--watch")}function cs(e){const{tokens:t,malformed:i}=rs(e),r=is(t[0]),o=os(r,t[1]);if(i)return Me(e,[be.MALFORMED],r,o);const n=t.filter(u=>u.value==="--watch"&&!u.quoted),a=t.filter(u=>u.value==="--watch"&&u.quoted),d=t.filter(as);if(!(n.length>0||a.length>0||d.length>0))return Me(e,[],r,o);if(n.length>1)return Me(e,[be.DUPLICATE],r,o);if(n.length===1&&(a.length>0||d.length>0))return Me(e,[be.AMBIGUOUS],r,o);if(a.length>0)return Me(e,[be.QUOTED],r,o);if(d.length>0)return Me(e,[be.MALFORMED],r,o);const l=n[0];if(!l)return Me(e,[],r,o);if(t[t.length-1]!==l)return Me(e,[be.NON_FINAL],r,o);if(!r||!o)return Me(e,[be.UNRESOLVED],r,o);const m=`${e.slice(0,l.start)}${e.slice(l.end)}`.trim(),S={literal:"--watch",position:"final",start:l.start,end:l.end,quoted:!1,publicSafe:!0};return{args:m,watch:!0,reasonCodes:[be.ACTIVE],metadata:pr(!0,[be.ACTIVE],r,o,S),publicSafe:!0}}function ss(e){return ki(e)?ns(e):cs(e)}function ds(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&Wa.has(t)):[]}function Gt(e){return{disabled:!0,reasonCodes:Ue(e.length>0?e:[Le.MISSING])}}function lr(e,t,i=[],r){const o=en(t);if(o)return{source:e,target:Xc(o,i),targetJobId:o.targetId,...r?{initialCursor:r}:{},serverHeldStream:!1}}function ps(e){const t=new Map;for(const i of e){const r=`${i.target.selectorKind}:${i.target.targetId}`,o=t.get(r);if(!o){t.set(r,i);continue}const n=Ue([...o.target.relatedJobIds??[],...i.target.relatedJobIds??[]]);t.set(r,{...o,target:n.length>0?{...o.target,relatedJobIds:n}:o.target,initialCursor:o.initialCursor??i.initialCursor})}return Array.from(t.values())}function Rt(e,t,i,r){return{source:e,hasEvidence:t,candidates:ps(i.filter(o=>!!o)),...r&&r.length>0?{disabledReasonCodes:Ue(r)}:{}}}function ls(e,t){return e.target.selectorKind===t.target.selectorKind&&e.target.targetId===t.target.targetId}function tn(e,t){const i=Ue(e.filter(r=>typeof r=="string").map(r=>Ke(r)).filter(r=>!!r));if(t){const r=i.find(o=>sr(o)===t);if(r)return r}return i[0]}function bn(e,t){return Ue(e.filter(i=>typeof i=="string").map(i=>Ke(i)).filter(i=>!!i)).find(i=>sr(i)===t)}function us(e){const t=h(e?.continuity)?e.continuity:void 0,i=h(t?.jobs)?t.jobs:void 0,r=h(i?.watcher)?i.watcher:void 0,o=ds(r?.reasonCodes??i?.reasonCodes);if(!r)return Rt("watcher-metadata",o.length>0,[],o);if(r.active===!1||o.length>0)return Rt("watcher-metadata",!0,[],o.length>0?o:[Le.MALFORMED]);if(r.serverHeldStream!==!1)return Rt("watcher-metadata",!0,[],[Le.SERVER_HELD_STREAM]);const n=Zc(r);if(!n)return Rt("watcher-metadata",!0,[],[Le.MISSING]);const a=typeof r.initialCursor=="string"?r.initialCursor:void 0;return Rt("watcher-metadata",!0,[{source:"watcher-metadata",target:n,targetJobId:n.targetId,...a?{initialCursor:a}:{},serverHeldStream:!1}])}function Oi(e,t){const i=h(e.loopJobPlan)?e.loopJobPlan:void 0,r=h(i?.metadata)?i.metadata:void 0,o=h(e.metadata)?e.metadata:void 0,a=(t==="goal"?tn([e.goalId,e.targetGoalId,e.campaignId,e.jobId,e.targetJobId,o?.goalId,o?.campaignId,o?.jobId],"goal"):tn([e.loopId,e.targetLoopId,e.jobId,e.targetJobId,o?.loopId,o?.jobId,r?.loopId,r?.jobId],"loop"))??tn([e.jobId,e.targetJobId,o?.jobId,r?.jobId]);return lr("goal-loop-continuity-metadata",a,[e.jobId,e.targetJobId,o?.jobId,r?.jobId])}function hs(e){const t=h(e?.continuity)?e.continuity:void 0,i=h(t?.goal)?t.goal:void 0,r=h(t?.loop)?t.loop:void 0,o=[i?Oi(i,"goal"):void 0,r?Oi(r,"loop"):void 0],n=!!(i||r);return Rt("goal-loop-continuity-metadata",n,o,n&&o.every(a=>!a)?[Le.MISSING]:void 0)}function gs(e){return Array.isArray(e)?e.filter(h):h(e)?Array.isArray(e.operationLogs)?e.operationLogs.filter(h):h(e.operationLog)?[e.operationLog]:Array.isArray(e.operations)?[e]:[]:[]}function Ni(e,t){const i=h(t.metadata)?t.metadata:void 0,r=bn([t.goalId,t.targetGoalId,t.campaignId,i?.goalId,i?.campaignId,t.jobId,i?.jobId],"goal"),o=bn([t.loopId,t.targetLoopId,i?.loopId,t.jobId,i?.jobId],"loop"),n=tn([t.jobId,t.targetJobId,i?.jobId],"job"),a=r??o??n;if(!a)return;const d=e.get(a)??{targetId:a,relatedJobIds:[]};d.relatedJobIds.push(...dr([n,t.jobId,t.targetJobId,i?.jobId])),e.set(a,d)}function fs(e){const t=h(e.metadata)?e.metadata:void 0;return!!(bn([e.goalId,e.targetGoalId,e.campaignId,t?.goalId,t?.campaignId,e.jobId,t?.jobId],"goal")??bn([e.loopId,e.targetLoopId,t?.loopId,e.jobId,t?.jobId],"loop"))}function ms(e){const t=h(e.metadata)?e.metadata:void 0;return!!tn([e.goalId,e.targetGoalId,e.campaignId,e.loopId,e.targetLoopId,e.jobId,e.targetJobId,t?.goalId,t?.campaignId,t?.loopId,t?.jobId])}function Li(e,t){const i=[];for(const a of["metadata","job","event","receipt","processingOutputSummary"]){const d=t[a];h(d)&&i.push(d)}const r=h(t.event)?t.event:void 0;h(r?.metadata)&&i.push(r.metadata),h(r?.processingOutputSummary)&&i.push(r.processingOutputSummary);const o=h(t.receipt)?t.receipt:void 0;h(o?.metadata)&&i.push(o.metadata);const n=i.some(ms);for(const a of i)Ni(e,a);(!n||fs(t))&&Ni(e,t)}function ys(e){const t=gs(e?.continuityStateUpdate),i=new Map;for(const o of t){Li(i,o);const n=Array.isArray(o.operations)?o.operations.filter(h):[];for(const a of n)Li(i,a)}const r=Array.from(i.values()).map(o=>lr("continuity-state-update-operation-log",o.targetId,o.relatedJobIds));return Rt("continuity-state-update-operation-log",t.length>0,r,t.length>0&&r.every(o=>!o)?[Le.MISSING]:void 0)}function Es(e){const t=Ti(e);return Rt("explicit-args",t.length>0,t.map(i=>lr("explicit-args",i)))}function Is(e,t){const i=[us(e),hs(e),ys(e),Es(t)];for(let r=0;r<i.length;r+=1){const o=i[r];if(!o.hasEvidence)continue;if(o.disabledReasonCodes&&o.disabledReasonCodes.length>0)return Gt(o.disabledReasonCodes);if(o.candidates.length!==1)return Gt([o.candidates.length>1?Le.AMBIGUOUS:Le.MISSING]);const n=o.candidates[0];for(const a of i.slice(r+1)){if(!a.hasEvidence)continue;if(a.disabledReasonCodes&&a.disabledReasonCodes.length>0)return Gt(a.disabledReasonCodes);if(a.candidates.length>1)return Gt([Le.AMBIGUOUS]);const d=a.candidates[0];if(d&&!ls(n,d))return Gt([Le.CONFLICT])}return{target:n.target,targetJobId:n.targetJobId,...n.initialCursor?{initialCursor:n.initialCursor}:{},source:n.source,serverHeldStream:!1}}return Gt([Le.MISSING])}async function ur(e,t,i,r={}){const o="/api/v1/invoke";let n,a;const d=await Zt(e,o,t,i,{...r,deferSuccessfulJsonParsing:!0,...t.privateExecution?{maxAttempts:1,allowReplayRetry:!1}:{},admitResponseBeforeBodyRead:S=>{const u=S.headers.get("X-Neocortex-Compatibility");if(u!==null)try{if(u.length===0||u.length>8192)throw new Error("header-size");const v=JSON.parse(Buffer.from(u,"base64url").toString("utf8"));if(!Zo(v))throw new Error("header-shape");if(n=v,v.status==="incompatible")return a="incompatible",!1}catch{return a="malformed",!1}return r.admitResponseBeforeBodyRead?.(S)??!0}});if(d.networkFailure||!d.response)return{ok:!1,status:0,error:"Network error after bounded retries"};if(d.responseAdmissionRejected){const S=a==="malformed"?$t.RESULT_MALFORMED:n?.reasonCodes[0]??$t.OFFER_MALFORMED;return{ok:!1,status:d.response.status,error:`COMPATIBILITY_INCOMPATIBLE: ${S}`,errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:S,fallback_action:n?.remediationHint??"upgrade-client"},...n?{compatibility:n}:{}}}const{response:s,text:l}=d;let m=d.parsed;try{if(t.compatibility&&!n){if(/"(?:reviewReconciliation|review_reconciliation|reconciliationMetadata|releaseLifecycle|release_lifecycle|releaseBlocked|release_blocked|yoloopReleaseBlocked)"\s*:/u.test(l))return{ok:!1,status:s.status,error:`COMPATIBILITY_INCOMPATIBLE: ${$t.UNNEGOTIATED_PROTECTED_FIELD}`,errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:$t.UNNEGOTIATED_PROTECTED_FIELD,fallback_action:"upgrade-client"}};n=Xo({clientVersion:t.compatibility.clientVersion,serverVersion:"0.0.0",registryVersion:t.registryVersion,registryChecksum:t.registryChecksum,reason:$t.SERVER_NEGOTIATION_MISSING})}if(s.ok)try{m=l?JSON.parse(l):{}}catch{return{ok:!1,status:s.status,error:"COMPATIBILITY_INCOMPATIBLE: response-json-malformed",errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:$t.RESULT_MALFORMED},...n?{compatibility:n}:{}}}if(!s.ok)return t.privateExecution?{ok:!1,status:s.status,error:"private-execution-invoke-unavailable"}:{ok:!1,status:s.status,error:Object.keys(m).length>0?`${m.error_code??"ERROR"}: ${m.message??l}`:`HTTP ${s.status}: ${l}`,errorBody:Object.keys(m).length>0?m:void 0,...n?{compatibility:n}:{}};const S=m,u=s.headers.get("X-Client-Version-Warning");return u&&!Si&&(Si=!0,process.stderr.write(`
|
|
23
|
-
[Neocortex] ${
|
|
20
|
+
`);return}if(t==="json"){o.write(JSON.stringify(Jc(e))+`
|
|
21
|
+
`);return}o.write(zc(e)+`
|
|
22
|
+
`)}function cr(e){return Wa.has(e.status)}function Qc(e,t,o){if(t){const i=e.find(r=>r.jobId===t);return!!(i&&cr(i))}return o<=0?!1:e.filter(i=>!cr(i)).length===0}function Xc(e,t,o,n){return o<n?!1:t?!e.some(i=>i.jobId===t&&!cr(i)):e.length===0}function Zc(e,t){return t?.aborted?Promise.resolve():new Promise(o=>{const n=setTimeout(i,e);function i(){clearTimeout(n),t?.removeEventListener("abort",i),o()}t?.addEventListener("abort",i,{once:!0})})}function es(e){return e.includes(Le.MALFORMED)?"malformed":e.includes(Le.AMBIGUOUS)?"ambiguous":e.includes("watch-target-multiple")?"multiple":e.includes("watch-evidence-unsafe")?"unsafe":e.includes(Le.MISSING)||e.includes(_e.TARGET_UNRESOLVED)?"unresolved":"unavailable"}function Ti(e,t){const o=t?en(t):void 0,n=Ue([...e,_e.TARGET_UNRESOLVED,Y.WATCH_TARGET_UNRESOLVED]),i=ar(o,o?.targetId,es(n),n),r=ut({generatedAt:new Date().toISOString()},[],!1,0,[Y.WATCH_TARGET_UNRESOLVED]),a=et(void 0,void 0,void 0,[],[Y.WATCH_TARGET_UNRESOLVED],"unavailable");return tt({watchStatus:"blocked",active:!1,targetEvidence:i,snapshotEvidence:r,cursorEvidence:a,stopReason:"target_unresolved",reasonCodes:n,generatedAt:r.generatedAt})}function ts(e,t,o,n,i=!1){const r=Ti(e,ki(t));return nt(r,o,n,i),ht("target-unresolved",0,0,r,i)}async function ns(e){if(e.signal?.aborted){const O=ar(e.target??en(e.targetJobId),e.targetJobId,e.target??e.targetJobId?"resolved":"unresolved",[_e.CANCELLED]),C=ut(void 0,[],!1,0),T=et(e.initialCursor,e.initialCursor,e.initialCursor,[],[_e.CANCELLED],"unavailable"),P=tt({watchStatus:"stopped",active:!1,targetEvidence:O,snapshotEvidence:C,cursorEvidence:T,stopReason:"cancelled",reasonCodes:[_e.CANCELLED]});return ht("cancelled",0,0,P,e.protectedOutput)}const t=e.target??en(e.targetJobId),o=e.targetJobId??t?.targetId,n=e.stdout??process.stdout;if(!t){const O=Ti([Le.MISSING,_e.TARGET_UNRESOLVED]);return nt(O,e.format,n,e.protectedOutput),ht("target-unresolved",0,0,O,e.protectedOutput)}const i=wn(e.limit??An("NEOCORTEX_INVOKE_WATCH_LIMIT",Lr),Lr,50),r=Math.max(50,wn(e.pollIntervalMs??An("NEOCORTEX_INVOKE_WATCH_POLL_INTERVAL_MS",jr),jr,6e4)),a=wn(e.maxIdlePolls??An("NEOCORTEX_INVOKE_WATCH_MAX_IDLE_POLLS",Dr),Dr,120),d=wn(e.maxPolls??An("NEOCORTEX_INVOKE_WATCH_MAX_POLLS",Mr),Mr,86400),s=e.sleep??Zc;let u=e.initialCursor,m=0,I=0,h=0;const E=ar(t,o,"resolved",[Y.OK]),_={schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:"pending",renderedSummaryCount:0,reasonCodes:[Y.WATCH_RENDER_PENDING],publicSafe:!0},S=et(e.initialCursor,u,u,[],e.initialCursor?[Y.WATCH_CURSOR_UNCHANGED]:[Y.WATCH_NO_SUMMARIES_YET],e.initialCursor?"unchanged":"not_started");nt(tt({watchStatus:"active",active:!0,targetEvidence:E,snapshotEvidence:_,cursorEvidence:S,stopReason:"not_stopped",reasonCodes:[Y.OK]}),e.format,n,e.protectedOutput);let l;try{l=await ko({projectRoot:e.projectRoot,strictReadOnly:e.strictReadOnly})}catch{const O=ut(void 0,[],!1,m,[Y.WATCH_SNAPSHOT_UNAVAILABLE]),C=et(e.initialCursor,u,u,[],[Y.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),T=tt({watchStatus:"blocked",active:!1,targetEvidence:E,snapshotEvidence:O,cursorEvidence:C,stopReason:"unavailable_evidence",reasonCodes:[_e.STORE_UNAVAILABLE]});return nt(T,e.format,n,e.protectedOutput),ht("store-unavailable",m,h,T,e.protectedOutput)}try{for(;!e.signal?.aborted&&h<d;){h+=1;const O=u,C=l.collectProcessingOutputSummaryCursor({...u?{cursor:u}:{},...t?{target:t}:{},...o?{jobId:o}:{},limit:i}),T=l.collectSnapshot({jobLimit:50,processingSummaryLimit:1}),P=T.jobs;if(C.summaries.length>0){for(const K of C.summaries)Kc(K,e.format,n,e.protectedOutput),m+=1;u=C.nextCursor??C.summaries[C.summaries.length-1]?.cursor??u,I=0}else u=C.nextCursor??u,I+=1;const B=ut(T,C.summaries,!0,C.summaries.length),D=et(e.initialCursor,O,u,C.summaries,C.summaries.length>0?[Y.WATCH_CURSOR_ADVANCED]:[Y.WATCH_NO_SUMMARIES_YET]);if(nt(tt({watchStatus:C.summaries.length>0?"polling":"waiting",active:!0,targetEvidence:E,snapshotEvidence:B,cursorEvidence:D,stopReason:"not_stopped",reasonCodes:C.summaries.length>0?[Y.WATCH_CURSOR_ADVANCED]:[Y.WATCH_NO_SUMMARIES_YET],generatedAt:T.generatedAt}),e.format,n,e.protectedOutput),!C.hasMore&&Qc(P,o,m)){const K=ut(T,C.summaries,!1,m,[_e.COMPLETED]),ue=et(e.initialCursor,O,u,C.summaries,[_e.COMPLETED],"exhausted"),x=tt({watchStatus:"stopped",active:!1,targetEvidence:E,snapshotEvidence:K,cursorEvidence:ue,stopReason:"not_stopped",reasonCodes:[_e.COMPLETED],generatedAt:T.generatedAt});return nt(x,e.format,n,e.protectedOutput),ht("completed",m,h,x,e.protectedOutput)}if(!C.hasMore&&Xc(P,o,I,a)){const K=ut(T,C.summaries,!1,m,[Y.WATCH_STOP_IDLE_LIMIT_REACHED]),ue=et(e.initialCursor,O,u,C.summaries,[Y.WATCH_STOP_IDLE_LIMIT_REACHED],"exhausted"),x=tt({watchStatus:"stopped",active:!1,targetEvidence:E,snapshotEvidence:K,cursorEvidence:ue,stopReason:"idle_limit_reached",reasonCodes:[_e.IDLE_TIMEOUT,Y.WATCH_STOP_IDLE_LIMIT_REACHED],generatedAt:T.generatedAt});return nt(x,e.format,n,e.protectedOutput),ht("idle-timeout",m,h,x,e.protectedOutput)}C.hasMore||await s(r,e.signal)}}catch{const O=ut(void 0,[],!1,m,[Y.WATCH_SNAPSHOT_UNAVAILABLE]),C=et(e.initialCursor,u,u,[],[Y.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),T=tt({watchStatus:"blocked",active:!1,targetEvidence:E,snapshotEvidence:O,cursorEvidence:C,stopReason:"unavailable_evidence",reasonCodes:[_e.STORE_UNAVAILABLE]});return nt(T,e.format,n,e.protectedOutput),ht("store-unavailable",m,h,T,e.protectedOutput)}finally{l.close()}if(e.signal?.aborted){const O=ut(void 0,[],!1,m,[_e.CANCELLED]),C=et(e.initialCursor,u,u,[],[_e.CANCELLED],"unavailable"),T=tt({watchStatus:"stopped",active:!1,targetEvidence:E,snapshotEvidence:O,cursorEvidence:C,stopReason:"cancelled",reasonCodes:[_e.CANCELLED]});return nt(T,e.format,n,e.protectedOutput),ht("cancelled",m,h,T,e.protectedOutput)}const A=ut(void 0,[],!1,m,[Y.WATCH_STOP_MAX_POLLS_REACHED]),j=et(e.initialCursor,u,u,[],[Y.WATCH_STOP_MAX_POLLS_REACHED],"exhausted"),k=tt({watchStatus:"stopped",active:!1,targetEvidence:E,snapshotEvidence:A,cursorEvidence:j,stopReason:"max_polls_reached",reasonCodes:[_e.MAX_POLLS,Y.WATCH_STOP_MAX_POLLS_REACHED]});return nt(k,e.format,n,e.protectedOutput),ht("max-polls",m,h,k,e.protectedOutput)}function Ke(e){const t=e.trim().replace(/^@/,"").match(/^(job|goal|loop)-([JGL])(\d{3,})$/i);if(!t)return;const o=t[1].toLowerCase(),n=t[2].toUpperCase();if(!(o==="job"&&n!=="J"||o==="goal"&&n!=="G"||o==="loop"&&n!=="L"))return`${o}-${n}${t[3]}`}function sr(e){if(e.startsWith("job-J"))return"job";if(e.startsWith("goal-G"))return"goal";if(e.startsWith("loop-L"))return"loop"}function Pi(e){const t=[],o=/(?:^|[\s"'([,{])@?(job-[Jj]\d{3,}|goal-[Gg]\d{3,}|loop-[Ll]\d{3,})(?=$|[\s"')\]},.;:!?])/g;let n;for(;(n=o.exec(e))!==null;){const i=Ke(n[1]);i&&t.push(i)}return Ue(t)}function ki(e){return Pi(e)[0]}function en(e){const t=e?Ke(e):void 0;if(t){if(t.startsWith("job-J"))return{selectorKind:"job",targetId:t,jobId:t,publicSafe:!0};if(t.startsWith("goal-G"))return{selectorKind:"goal",targetId:t,goalId:t,publicSafe:!0};if(t.startsWith("loop-L"))return{selectorKind:"loop",targetId:t,loopId:t,publicSafe:!0}}}function dr(e){return Ue(e.filter(t=>typeof t=="string").map(t=>Ke(t)).filter(t=>!!t?.startsWith("job-J")))}function rs(e,t){const o=dr(t).filter(n=>n!==e.targetId&&n!==e.jobId);return o.length>0?{...e,relatedJobIds:o}:e}function is(e){if(!e)return;const t=g(e.target)?e.target:void 0,o=typeof e.selectorKind=="string"?e.selectorKind:typeof t?.selectorKind=="string"?t.selectorKind:void 0,n=typeof e.targetId=="string"?Ke(e.targetId):typeof t?.targetId=="string"?Ke(t.targetId):typeof e.targetJobId=="string"?Ke(e.targetJobId):void 0,i=en(n);if(!i||o&&o!==i.selectorKind)return;const r=Array.isArray(e.relatedJobIds)?e.relatedJobIds:Array.isArray(t?.relatedJobIds)?t.relatedJobIds:void 0,a=dr([...r??[],e.jobId,t?.jobId,e.targetJobId,t?.targetJobId]).filter(d=>d!==i.targetId&&d!==i.jobId);return{...i,...typeof(e.jobId??t?.jobId)=="string"?{jobId:Ke(e.jobId??t?.jobId)??i.jobId}:{},...typeof(e.goalId??t?.goalId)=="string"?{goalId:Ke(e.goalId??t?.goalId)??i.goalId}:{},...typeof(e.loopId??t?.loopId)=="string"?{loopId:Ke(e.loopId??t?.loopId)??i.loopId}:{},...a.length>0?{relatedJobIds:a}:{}}}function Oi(e){const t=e.trim().split(/\s+/).filter(Boolean),o=t[0]?.replace(/^\*/,"").toLowerCase(),n=t[1]?.replace(/^--/,"").toLowerCase();return(o==="jobs"||o==="job"||o==="continuity-jobs"||o==="61")&&n==="watch"}const be=Object.freeze({ACTIVE:"command-level-watch-active",INACTIVE:"command-level-watch-inactive",DUPLICATE:"command-level-watch-duplicate",AMBIGUOUS:"command-level-watch-ambiguous",QUOTED:"command-level-watch-quoted",MALFORMED:"command-level-watch-malformed",NON_FINAL:"command-level-watch-non-final",UNRESOLVED:"command-level-watch-unresolved",UNSUPPORTED:"command-level-watch-unsupported",TARGET_INVALID:"command-level-watch-target-invalid"}),os=new Set(["create","start","resume"]),as=new Set(["create","resume","run-once"]);function pr(e,t,o,n,i){return{schemaVersion:1,contractVersion:"continuity-v1",...o?{command:o}:{},...n?{operation:n}:{},active:e,...i?{watchToken:i}:{},reasonCodes:Ue(t),serverHeldStream:!1,allJobsPolling:!1,targetResolution:e?"required-after-dispatch":"inactive",publicSafe:!0}}function Me(e,t=[],o,n){const i=t.length>0?t:[be.INACTIVE];return{args:e,watch:!1,reasonCodes:i,metadata:pr(!1,i,o,n),publicSafe:!0}}function cs(e){const t=e.trim().split(/\s+/).filter(Boolean),o=t.slice(2).filter(r=>r==="--watch").length;if(o===0)return Me(e,[],"jobs","watch");if(o!==1)return Me(e,[be.AMBIGUOUS],"jobs","watch");const n=t.filter((r,a)=>a<2||r!=="--watch").join(" ");return Oi(n)?n.trim().split(/\s+/).filter(Boolean).slice(2).length!==1?Me(e,[be.AMBIGUOUS],"jobs","watch"):ki(n)?{args:n,watch:!0,reasonCodes:[be.ACTIVE],metadata:pr(!0,[be.ACTIVE],"jobs","watch"),publicSafe:!0}:Me(e,[be.TARGET_INVALID],"jobs","watch"):Me(e,[be.UNSUPPORTED],"jobs","watch")}function ss(e){const t=[];let o=!1,n=0;for(;n<e.length;){for(;n<e.length&&/\s/.test(e[n]);)n+=1;if(n>=e.length)break;const i=n;let r="",a=!1,d=null;for(;n<e.length;){const s=e[n];if(d){if(s===d){a=!0,d=null,n+=1;continue}if(s==="\\"&&n+1<e.length){r+=e[n+1],n+=2;continue}r+=s,n+=1;continue}if(/\s/.test(s))break;if(s==='"'||s==="'"){a=!0,d=s,n+=1;continue}r+=s,n+=1}d&&(o=!0),t.push({value:r,start:i,end:n,quoted:a})}return{tokens:t,malformed:o}}function ds(e){if(!e||e.quoted)return;const t=e.value.replace(/^\*/,"").toLowerCase();return t==="goal"||t==="loop"?t:void 0}function ps(e,t){if(!e||e==="jobs"||!t||t.quoted)return;const o=t.value.toLowerCase();return(e==="goal"?os:as).has(o)?o:void 0}function ls(e){return!e.quoted&&e.value!=="--watch"&&e.value.toLowerCase().startsWith("--watch")}function us(e){const{tokens:t,malformed:o}=ss(e),n=ds(t[0]),i=ps(n,t[1]);if(o)return Me(e,[be.MALFORMED],n,i);const r=t.filter(h=>h.value==="--watch"&&!h.quoted),a=t.filter(h=>h.value==="--watch"&&h.quoted),d=t.filter(ls);if(!(r.length>0||a.length>0||d.length>0))return Me(e,[],n,i);if(r.length>1)return Me(e,[be.DUPLICATE],n,i);if(r.length===1&&(a.length>0||d.length>0))return Me(e,[be.AMBIGUOUS],n,i);if(a.length>0)return Me(e,[be.QUOTED],n,i);if(d.length>0)return Me(e,[be.MALFORMED],n,i);const u=r[0];if(!u)return Me(e,[],n,i);if(t[t.length-1]!==u)return Me(e,[be.NON_FINAL],n,i);if(!n||!i)return Me(e,[be.UNRESOLVED],n,i);const m=`${e.slice(0,u.start)}${e.slice(u.end)}`.trim(),I={literal:"--watch",position:"final",start:u.start,end:u.end,quoted:!1,publicSafe:!0};return{args:m,watch:!0,reasonCodes:[be.ACTIVE],metadata:pr(!0,[be.ACTIVE],n,i,I),publicSafe:!0}}function hs(e){return Oi(e)?cs(e):us(e)}function gs(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&Ga.has(t)):[]}function Gt(e){return{disabled:!0,reasonCodes:Ue(e.length>0?e:[Le.MISSING])}}function lr(e,t,o=[],n){const i=en(t);if(i)return{source:e,target:rs(i,o),targetJobId:i.targetId,...n?{initialCursor:n}:{},serverHeldStream:!1}}function fs(e){const t=new Map;for(const o of e){const n=`${o.target.selectorKind}:${o.target.targetId}`,i=t.get(n);if(!i){t.set(n,o);continue}const r=Ue([...i.target.relatedJobIds??[],...o.target.relatedJobIds??[]]);t.set(n,{...i,target:r.length>0?{...i.target,relatedJobIds:r}:i.target,initialCursor:i.initialCursor??o.initialCursor})}return Array.from(t.values())}function Rt(e,t,o,n){return{source:e,hasEvidence:t,candidates:fs(o.filter(i=>!!i)),...n&&n.length>0?{disabledReasonCodes:Ue(n)}:{}}}function ms(e,t){return e.target.selectorKind===t.target.selectorKind&&e.target.targetId===t.target.targetId}function tn(e,t){const o=Ue(e.filter(n=>typeof n=="string").map(n=>Ke(n)).filter(n=>!!n));if(t){const n=o.find(i=>sr(i)===t);if(n)return n}return o[0]}function bn(e,t){return Ue(e.filter(o=>typeof o=="string").map(o=>Ke(o)).filter(o=>!!o)).find(o=>sr(o)===t)}function ys(e){const t=g(e?.continuity)?e.continuity:void 0,o=g(t?.jobs)?t.jobs:void 0,n=g(o?.watcher)?o.watcher:void 0,i=gs(n?.reasonCodes??o?.reasonCodes);if(!n)return Rt("watcher-metadata",i.length>0,[],i);if(n.active===!1||i.length>0)return Rt("watcher-metadata",!0,[],i.length>0?i:[Le.MALFORMED]);if(n.serverHeldStream!==!1)return Rt("watcher-metadata",!0,[],[Le.SERVER_HELD_STREAM]);const r=is(n);if(!r)return Rt("watcher-metadata",!0,[],[Le.MISSING]);const a=typeof n.initialCursor=="string"?n.initialCursor:void 0;return Rt("watcher-metadata",!0,[{source:"watcher-metadata",target:r,targetJobId:r.targetId,...a?{initialCursor:a}:{},serverHeldStream:!1}])}function Ni(e,t){const o=g(e.loopJobPlan)?e.loopJobPlan:void 0,n=g(o?.metadata)?o.metadata:void 0,i=g(e.metadata)?e.metadata:void 0,a=(t==="goal"?tn([e.goalId,e.targetGoalId,e.campaignId,e.jobId,e.targetJobId,i?.goalId,i?.campaignId,i?.jobId],"goal"):tn([e.loopId,e.targetLoopId,e.jobId,e.targetJobId,i?.loopId,i?.jobId,n?.loopId,n?.jobId],"loop"))??tn([e.jobId,e.targetJobId,i?.jobId,n?.jobId]);return lr("goal-loop-continuity-metadata",a,[e.jobId,e.targetJobId,i?.jobId,n?.jobId])}function Is(e){const t=g(e?.continuity)?e.continuity:void 0,o=g(t?.goal)?t.goal:void 0,n=g(t?.loop)?t.loop:void 0,i=[o?Ni(o,"goal"):void 0,n?Ni(n,"loop"):void 0],r=!!(o||n);return Rt("goal-loop-continuity-metadata",r,i,r&&i.every(a=>!a)?[Le.MISSING]:void 0)}function Es(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 Li(e,t){const o=g(t.metadata)?t.metadata:void 0,n=bn([t.goalId,t.targetGoalId,t.campaignId,o?.goalId,o?.campaignId,t.jobId,o?.jobId],"goal"),i=bn([t.loopId,t.targetLoopId,o?.loopId,t.jobId,o?.jobId],"loop"),r=tn([t.jobId,t.targetJobId,o?.jobId],"job"),a=n??i??r;if(!a)return;const d=e.get(a)??{targetId:a,relatedJobIds:[]};d.relatedJobIds.push(...dr([r,t.jobId,t.targetJobId,o?.jobId])),e.set(a,d)}function Ss(e){const t=g(e.metadata)?e.metadata:void 0;return!!(bn([e.goalId,e.targetGoalId,e.campaignId,t?.goalId,t?.campaignId,e.jobId,t?.jobId],"goal")??bn([e.loopId,e.targetLoopId,t?.loopId,e.jobId,t?.jobId],"loop"))}function vs(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 Di(e,t){const o=[];for(const a of["metadata","job","event","receipt","processingOutputSummary"]){const d=t[a];g(d)&&o.push(d)}const n=g(t.event)?t.event:void 0;g(n?.metadata)&&o.push(n.metadata),g(n?.processingOutputSummary)&&o.push(n.processingOutputSummary);const i=g(t.receipt)?t.receipt:void 0;g(i?.metadata)&&o.push(i.metadata);const r=o.some(vs);for(const a of o)Li(e,a);(!r||Ss(t))&&Li(e,t)}function Cs(e){const t=Es(e?.continuityStateUpdate),o=new Map;for(const i of t){Di(o,i);const r=Array.isArray(i.operations)?i.operations.filter(g):[];for(const a of r)Di(o,a)}const n=Array.from(o.values()).map(i=>lr("continuity-state-update-operation-log",i.targetId,i.relatedJobIds));return Rt("continuity-state-update-operation-log",t.length>0,n,t.length>0&&n.every(i=>!i)?[Le.MISSING]:void 0)}function _s(e){const t=Pi(e);return Rt("explicit-args",t.length>0,t.map(o=>lr("explicit-args",o)))}function Rs(e,t){const o=[ys(e),Is(e),Cs(e),_s(t)];for(let n=0;n<o.length;n+=1){const i=o[n];if(!i.hasEvidence)continue;if(i.disabledReasonCodes&&i.disabledReasonCodes.length>0)return Gt(i.disabledReasonCodes);if(i.candidates.length!==1)return Gt([i.candidates.length>1?Le.AMBIGUOUS:Le.MISSING]);const r=i.candidates[0];for(const a of o.slice(n+1)){if(!a.hasEvidence)continue;if(a.disabledReasonCodes&&a.disabledReasonCodes.length>0)return Gt(a.disabledReasonCodes);if(a.candidates.length>1)return Gt([Le.AMBIGUOUS]);const d=a.candidates[0];if(d&&!ms(r,d))return Gt([Le.CONFLICT])}return{target:r.target,targetJobId:r.targetJobId,...r.initialCursor?{initialCursor:r.initialCursor}:{},source:r.source,serverHeldStream:!1}}return Gt([Le.MISSING])}async function ur(e,t,o,n={}){const i="/api/v1/invoke";let r,a;const d=await Zt(e,i,t,o,{...n,deferSuccessfulJsonParsing:!0,...t.privateExecution?{maxAttempts:1,allowReplayRetry:!1}:{},admitResponseBeforeBodyRead:I=>{const h=I.headers.get("X-Neocortex-Compatibility");if(h!==null)try{if(h.length===0||h.length>8192)throw new Error("header-size");const E=JSON.parse(Buffer.from(h,"base64url").toString("utf8"));if(!ea(E))throw new Error("header-shape");if(r=E,E.status==="incompatible")return a="incompatible",!1}catch{return a="malformed",!1}return n.admitResponseBeforeBodyRead?.(I)??!0}});if(d.networkFailure||!d.response)return{ok:!1,status:0,error:"Network error after bounded retries"};if(d.responseAdmissionRejected){const I=a==="malformed"?$t.RESULT_MALFORMED:r?.reasonCodes[0]??$t.OFFER_MALFORMED;return{ok:!1,status:d.response.status,error:`COMPATIBILITY_INCOMPATIBLE: ${I}`,errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:I,fallback_action:r?.remediationHint??"upgrade-client"},...r?{compatibility:r}:{}}}const{response:s,text:u}=d;let m=d.parsed;try{if(t.compatibility&&!r){if(/"(?:reviewReconciliation|review_reconciliation|reconciliationMetadata|releaseLifecycle|release_lifecycle|releaseBlocked|release_blocked|yoloopReleaseBlocked)"\s*:/u.test(u))return{ok:!1,status:s.status,error:`COMPATIBILITY_INCOMPATIBLE: ${$t.UNNEGOTIATED_PROTECTED_FIELD}`,errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:$t.UNNEGOTIATED_PROTECTED_FIELD,fallback_action:"upgrade-client"}};r=Zo({clientVersion:t.compatibility.clientVersion,serverVersion:"0.0.0",registryVersion:t.registryVersion,registryChecksum:t.registryChecksum,reason:$t.SERVER_NEGOTIATION_MISSING})}if(s.ok)try{m=u?JSON.parse(u):{}}catch{return{ok:!1,status:s.status,error:"COMPATIBILITY_INCOMPATIBLE: response-json-malformed",errorBody:{error_code:"COMPATIBILITY_INCOMPATIBLE",reason_code:$t.RESULT_MALFORMED},...r?{compatibility:r}:{}}}if(!s.ok)return t.privateExecution?{ok:!1,status:s.status,error:"private-execution-invoke-unavailable"}:{ok:!1,status:s.status,error:Object.keys(m).length>0?`${m.error_code??"ERROR"}: ${m.message??u}`:`HTTP ${s.status}: ${u}`,errorBody:Object.keys(m).length>0?m:void 0,...r?{compatibility:r}:{}};const I=m,h=s.headers.get("X-Client-Version-Warning");return h&&!vi&&(vi=!0,process.stderr.write(`
|
|
23
|
+
[Neocortex] ${h}
|
|
24
24
|
|
|
25
|
-
`)),{ok:!0,status:s.status,data:
|
|
25
|
+
`)),{ok:!0,status:s.status,data:I,...r?{compatibility:r}:{}}}catch(I){return{ok:!1,status:0,error:(I instanceof Error?I.message:String(I)).includes("abort")?`Request timeout after ${zr/1e3}s`:"Network error: invalid response"}}}async function ws(e,t,o){const n=await Zt(e,"/api/v1/invoke/private-execution/consume",t,o,{maxAttempts:1,allowReplayRetry:!1});if(n.networkFailure||!n.response||!n.response.ok)throw new Error("private-execution-delivery-unavailable");return n.parsed}async function As(e,t,o){const n=await Zt(e,"/api/v1/invoke/private-execution/cancel",t,o,{maxAttempts:1,allowReplayRetry:!1});return!!n.response?.ok&&n.parsed.status==="cancelled"}async function Mi(e,t,o,n={}){const i=await Zt(e,"/api/v1/invoke/epic-claims/acknowledge",{...o,registryVersion:dt,registryChecksum:st},t,n);return!!i.response?.ok&&i.parsed.status==="ok"&&i.parsed.claimOutcome===o.status&&(!o.planningCheckpoint||i.parsed.memoryReceiptId===o.planningCheckpoint.memoryReceiptId)}async function bs(e,t,o,n,i,r={}){if(!i)return 0;const a=Ht(e);let d=0;for(const[s,u]of Object.entries(a.operations))u.planningProtocol==="root-staged-v1"||!u.claimId||!u.epicId||!t.epics?.[u.epicId]||!await Mi(o,n,{claimId:u.claimId,projectId:i,epicId:u.epicId,status:"materialized"},r)||(ja(e,s),d+=1);return d}function xs(e,t){const o=t.state.pendingContinuationAuthorities,n=t.state.continuationSession;if(t.state.continuationPolicy!=="p205-finite-resume-v2"||o?.length!==1||!n)return;const i=o[0],r=i.certificate,a=r?.expectedTransition;if(i.storyIds!=="[CIRCULAR]"||r?.rank!=="[CIRCULAR]"||a?.selectedStoryIds!=="[CIRCULAR]")return;const d=typeof n.epicId=="string"?n.epicId:"",s=e.epics[d],u=Array.isArray(a.storyLifecycle)?a.storyLifecycle:[],m=u.length===1&&typeof u[0]?.storyId=="string"?u[0].storyId:"",h=e.stories[m]?.checkpoint;if(!s||s.branch_mode!=="epic"||typeof s.execution_branch!="string"||typeof s.origin_branch!="string"||s.branch_lease!==void 0&&s.branch_lease!==null||!h||h.qaVerdict!=="passed"||h.reviewVerdict!=="approved"||!Array.isArray(h.receiptRefs))return;const _=(Array.isArray(s.stories)?s.stories.filter(S=>typeof S=="string"):[]).find(S=>{const l=e.stories[S];return!l||["done","completed","merged"].includes(String(l.status))?!1:(Array.isArray(l.depends_on)?l.depends_on.filter(j=>typeof j=="string"):[]).every(j=>["done","completed","merged"].includes(String(e.stories[j]?.status)))});if(_)return{epicId:d,expectedNextStoryId:_,branchMode:"epic",executionBranch:s.execution_branch,originBranch:s.origin_branch,branchLeaseReleased:!0,checkpoint:{schemaVersion:1,storyId:h.storyId,epicId:h.epicId,branch:h.branch,baseSha:h.baseSha,headSha:h.headSha,receiptRefs:[...h.receiptRefs],qaVerdict:"passed",reviewVerdict:"approved"}}}const hr=["backlog","pending","ready","in-progress","branch-ready","diagnose","research","write-spec","create-tasks","implemented","refactor-suggest-done","property-tests-emitted","tests-validated","qa-gate-passed","memory-updated","committed","synced","pr-created","pr-reviewed","done"],ji=new Set(["done","completed","merged","cancelled","canceled","abandoned"]),Vi=new Set(["skipped-with-debt","documented"]);function Bi(e){return typeof e=="string"?e.trim().toLowerCase().replace(/_/g,"-"):""}function Ts(e){const t=Bi(e);if(ji.has(t)||Vi.has(t))return 0;const o=hr.indexOf(t);return o<0?hr.length:hr.length-1-o}function Ps(e,t){const o=e.epics[t];if(!o||!Array.isArray(o.stories)||o.stories.some(m=>typeof m!="string"||!/^P[1-9][0-9]*\.[0-9]+$/.test(m)))return null;const n=[...o.stories],i=[],r=[];let a=0,d=0;const s=[];for(const m of n){const I=e.stories[m];if(!I||!Array.isArray(I.depends_on)||I.depends_on.some(S=>typeof S!="string"))return null;const h=[...I.depends_on].sort(),E=Ts(I.status),_=Bi(I.status);i.push({id:m,dependsOn:h}),r.push({id:m,status:I.status,dependsOn:h}),s.push({storyId:m,remaining:E}),a+=E,!ji.has(_)&&!Vi.has(_)&&(d+=1)}const u={version:1,policy:"p205-finite-resume-v2",epicId:t,storyIds:n,queueEpicIds:[t],initialEpicIndex:0,graphFingerprint:vt("p205-yoloop-graph-v1",i),lifecycleVersion:"p205-lifecycle-v1",terminalPredicateVersion:"p205-terminal-v1",initialSnapshotFingerprint:vt("p205-yoloop-initial-snapshot-v1",{epicId:t,stories:r}),initialRank:{version:1,queue:0,epic:d,lifecycle:a},initialStoryLifecycle:s};return Object.freeze({...u,sessionId:vt("p205-yoloop-session-v1",u)})}function Ui(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 ks(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=Ps(e.snapshot,e.targetEpicId);if(!t)throw new Error("yoloop-causal-reconciliation-target-invalid");const o=String(t.graphFingerprint),n=Ar(e.projectRoot),i=Object.values(n.operational.identities).filter(P=>P.epicId===e.targetEpicId&&P.graphRevision===o);if(i.length!==1)throw new Error("epic-operational-identity-mismatch");const r=e.snapshot.yoloop,a=r?r.lock!==null||r.state.currentSession!==null?"active":"inactive":"unknown",d=lo({document:n.document,targetIdentityHash:i[0].identityHash,targetEpicId:e.targetEpicId,targetGraphRevision:o,legacyActivity:a});if(d.kind!=="eligible")throw new Error(d.reasonCodes[0]??"yoloop-causal-reconciliation-ineligible");const s=n.operational,u=s.yoloop.state.continuationSession,m=s.yoloop.state.pendingContinuationAuthorities??[],I=s.yoloop.state.runControl;if(!u||typeof u.sessionId!="string"||!I||!["success","exhausted"].includes(I.status)||m.length>1)throw new Error("yoloop-causal-reconciliation-preimage-invalid");const h=vt("p224-common-continuation-session-v1",s.yoloop.state.continuationSession??null),E=vt("p224-common-pending-authorities-v1",m),_=vt("p224-common-continuation-session-v1",t),S=vt("p224-invoke-session-recovery-v1",{identityHash:i[0].identityHash,originalInputSha256:e.originalInputSha256,canonicalInputSha256:e.canonicalInputSha256,expectedSessionHash:h,expectedPendingHash:E,nextSessionHash:_,runId:I.runId,runRevision:I.revision}),l={operationId:`p224rec-${S.slice(0,32)}`,idempotencyKey:`p224rec-${S.slice(0,32)}`,expectedCommonRevision:n.document.revision,expectedWriterEpoch:s.writerEpoch,expectedIdentityHash:i[0].identityHash,sourceEpicId:d.evidence.sourceEpicId,sourceGraphRevision:d.evidence.sourceGraphRevision,targetEpicId:e.targetEpicId,targetGraphRevision:o,expectedRunId:I.runId,expectedRunStatus:I.status,expectedRunRevision:I.revision,expectedSnapshotHash:I.latestSnapshotHash,sourceSessionId:u.sessionId,expectedSessionHash:h,expectedPendingHash:E,expectedPendingCount:m.length,nextSession:t,nextSessionHash:_},A=po(l),j={schemaVersion:"YoloopCrossEpicReconciliationReceipt/1.0",operationId:l.operationId,idempotencyKey:l.idempotencyKey,payloadHash:A,sourceEpicId:l.sourceEpicId,sourceGraphRevision:l.sourceGraphRevision,targetEpicId:l.targetEpicId,targetGraphRevision:l.targetGraphRevision,runId:l.expectedRunId,previousSessionHash:h,nextSessionHash:_,retiredAuthorityHash:E,retiredAuthorityCount:l.expectedPendingCount,outcome:"cross-epic-reconciled",publicSafe:!0},k={type:"reconcile_cross_epic_continuation",...l,payloadHash:A,receipt:j};await so(e.projectRoot,k);const O=Ar(e.projectRoot),C=O.operational.yoloop.state.pendingContinuationAuthorities??[];if(!O.operational.reconciliationReceipts.find(P=>P.payloadHash===A)||C.length!==0||vt("p224-common-continuation-session-v1",O.operational.yoloop.state.continuationSession??null)!==_)throw new Error("yoloop-causal-reconciliation-postimage-unverified");return Object.freeze({outcome:"applied",payloadHash:A,retryCount:1,publicSafe:!0})}catch(t){return Object.freeze({outcome:"blocked",reasonCode:Ui(t),retryCount:0,publicSafe:!0})}}const Os=/^\*yolo @docs\/stories\/[A-Za-z0-9][A-Za-z0-9._-]{0,79}\.story\.md story-worktree-phase-1$/,$i=9e4,Hi=6,Ns=1e3;function Ls(e){return typeof e=="string"&&Os.test(e)&&!e.includes("..")}function Ds(e){const t=e.metadata?.storyWorktreePhase;if(!e.success||!t||typeof t!="object"||Array.isArray(t))return;const o=t;return o.decision==="spec-barrier-waiting"&&o.phase==="phase-1"?o:void 0}async function Ms(e,t,o={}){const n=o.sleep??(u=>new Promise(m=>setTimeout(m,u))),i=o.now??Date.now,r=Math.max(1,Math.min(o.maxAttempts??Hi,Hi)),a=Math.max(0,Math.min(o.maxWaitMs??$i,$i)),d=i();let s=0;for(;;){const u=await t(e);s+=1;const m=Ds(u);if(!m)return u;const I=typeof m.maxWaitMs=="number"&&Number.isFinite(m.maxWaitMs)?m.maxWaitMs:0,h=Math.min(a,Math.max(0,I)),E=typeof m.retryAfterMs=="number"&&Number.isFinite(m.retryAfterMs)?m.retryAfterMs:0,_=Math.min(Math.max(E,Ns),h),S=i()-d;if(s>=r||S+_>h)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:{...
|
|
30
|
-
`)}}async function
|
|
31
|
-
`),{success:!1,error:p,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}let
|
|
32
|
-
`)})}catch(p){const y=Fr(p);return{success:!1,error:y,errorCode:y,exitCode:1}}
|
|
29
|
+
[STORY_WORKTREE_SPEC_BARRIER_TIMEOUT]`,metadata:{...u.metadata,storyWorktreePhase:{...m,decision:"spec-barrier-timeout",reasonCode:"spec-barrier-waiting",resumable:!0,attempts:s,waitedMs:Math.max(0,S),publicSafe:!0}},exitCode:0};await n(_)}}async function js(e,t){const o=t.metadata?.storyWorktreePhase;if(!t.success||!o||typeof o!="object"||Array.isArray(o))return;const n=o,i=n.specAcceptance,r=n.phaseOneReceipt,a=typeof n.storyId=="string"?n.storyId:void 0,d=a&&/^P[0-9]{1,12}\./.test(a)?a.split(".")[0]:void 0;if(!(!d||i===void 0&&r===void 0))try{await Hr(e,s=>{ya(s,d,{...i!==void 0?{specAcceptances:[i]}:{},...r!==void 0?{receipts:[r]}:{}})})}catch(s){const u=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 (${u}); the root must re-dispatch this phase-1 prompt.
|
|
30
|
+
`)}}async function Vs(e){if(!Ls(e.args))return Wi(e);const t=e.projectRoot??process.cwd();return Ms(e.args,async()=>{const o=await Wi(e);return await js(t,o),o})}async function Wi(e){let t;try{if(t=e.inputEnvelope??Qt(e.inputSource??"args",e.args),Yo(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 o=t.rawArgs,n=$n(t);let i=o,r=n,a=ni(o),d;if(a.outcome!=="resolved"){const c=Ha(o);c.kind==="canonicalized"&&(i=c.canonicalArgs,r=$n(Qt(t.source,i)),d=c.binding,a=ni(i))}if(a.outcome!=="resolved"){const c=zo(a,"client"),p=a.outcome==="malformed_input"?a.reason==="input_limit"||a.reason==="token_limit"||a.reason==="token_size_limit"?"input-limit-exceeded":a.reason==="invalid_control"||a.reason==="invalid_surrogate"?"invalid-control-character":a.reason==="unterminated_quote"||a.reason==="trailing_escape"||a.reason==="unsupported_escape"?"unterminated-quote":void 0:void 0,y=p?{code:"INVOCATION_MALFORMED_INPUT",reason:p,source:t.source,byteLength:t.byteLength,remediation:p==="input-limit-exceeded"?"Reduce the explicit command input or split the requested work into bounded invocations.":p==="invalid-control-character"?"Remove invalid control characters and retry with valid UTF-8 text.":"Close quotes and escapes, or use --stdin/--args-file for multiline content."}:void 0;return{success:!1,error:`INVOCATION_${a.outcome.toUpperCase()}`,errorCode:`INVOCATION_${a.outcome.toUpperCase()}`,metadata:{invocationAdmission:c,...y?{invocationInput:y}:{}},exitCode:1}}if(d&&(e={...e,args:i}),e.privateExecutionModel!==void 0&&(!e.privateExecutionBeta||e.strictReadOnly||!/^gpt-[a-z0-9][a-z0-9.-]{0,63}$/.test(e.privateExecutionModel)))return{success:!1,error:"private-codex-model-invalid",errorCode:"private-codex-model-invalid",exitCode:1};const s=Yn(e.projectRoot),u=a.selection.commandId,m=u==="yolo"&&!Or(i,u)?wa(i):null,I=u==="tech-debt"&&a.selection.positionals.length===0&&(a.selection.operationId==="scan"&&Object.keys(a.selection.options).length===0||a.selection.operationId===void 0&&a.selection.options.scan===!0&&Object.keys(a.selection.options).length===1),h=go.find(c=>c.id===u),E=h?.subcommands.find(c=>c.id===a.selection.operationId),_=E?E.policy.strictReadOnly==="allow":h?.policy.strictReadOnly==="allow",S=u==="diagnose";let l;try{l=Wo({invocationId:pn(),intent:e.strictReadOnly||S?{schemaVersion:1,policy:Uo,registryVersion:dt,registryChecksum:st}:void 0,registryVersion:dt,registryChecksum:st,registryAllowsStrict:_,requestCanonicalBytes:JSON.stringify({command:u})})}catch(c){if(c instanceof Bt)return{success:!1,error:c.code,errorCode:c.code,exitCode:1};throw c}{l.beginProjection();for(const c of Br)l.project(c);for(const c of $o)l.project(c);l.seal()}const A=l.mode==="strict";if(u==="create-epic"||u==="idea-diagnose")try{const c=ia(s);if(c&&c!=="finalized")return{success:!1,error:'PROJECT_IDENTITY_MIGRATION_INCOMPLETE: retry `neocortex-client invoke --args "*migrate-project-id"` before create-epic.',errorCode:"PROJECT_IDENTITY_MIGRATION_INCOMPLETE",metadata:{projectIdentityMigration:{phase:c,publicSafe:!0}},exitCode:1}}catch(c){const p=c instanceof Hn?c.code:"PROJECT_IDENTITY_MIGRATION_STATE_CORRUPT";return{success:!1,error:p,errorCode:p,exitCode:1}}const j=e.environment??process.env;if(e.privateExecutionBeta&&(u!=="yolo"&&u!=="research"&&u!=="write-spec"&&u!=="create-tasks"&&u!=="implement"&&u!=="exec"&&u!=="create-epic"&&u!=="idea-diagnose"&&u!=="idea-research"&&u!=="generate-epic"&&u!=="sync-openapi"&&u!=="chaos-plan"&&u!=="ui-ux-review"&&u!=="arch-prd"&&u!=="arch-architecture"&&u!=="arch-fitness-functions"&&u!=="arch-api-contracts"&&u!=="arch-api-integrations"&&u!=="arch-database"&&u!=="arch-security"&&u!=="arch-design-system"&&u!=="arch-performance"&&u!=="arch-testing"&&u!=="arch-infrastructure"&&u!=="arch-review"&&u!=="update-memory"&&u!=="arch-ux-design"&&u!=="generate-pacts"&&u!=="property-test"&&!I||A||e.platformTarget!==void 0&&e.platformTarget!=="codex"))return{success:!1,error:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",errorCode:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",exitCode:1};const k=Do({cwd:s,env:j,targetFlag:e.privateExecutionBeta?"codex":e.platformTarget}),O=k.targetId,C=e.privateExecutionBeta?void 0:Lo({cwd:s,env:j,targetFlag:e.platformTarget,nativeHostVersion:Qa(k,j)},k);if(m)try{Zn(s,{allowMissingRuntime:!0})}catch(c){const p=c instanceof lt?c.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${p}. No request was sent; repair the canonical project state/runtime sidecar and retry.
|
|
31
|
+
`),{success:!1,error:p,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}let T=m?Bn({strictReadOnly:!0}):Ei(l);const P=(e.serverUrl??T?.serverUrl??mo).replace(/\/+$/,"");let B,D=!1;if(m){const c=await _a(P);if(D=c.supported&&c.projectManifestProjection===!0,!c.supported)return{success:!1,error:`YOLO_INVOKE_ENVELOPE_CAPABILITY_UNAVAILABLE: target server does not advertise ${jo}; 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{B=Wr({projectRoot:s,storyId:m,epicId:m.split(".")[0],inputSha256:r.sha256,onOmittedReferences:p=>process.stderr.write(`[Neocortex] yolo-spec-supporting-references-omitted count=${p}; core story artifacts preserved.
|
|
32
|
+
`)})}catch(p){const y=Fr(p);return{success:!1,error:y,errorCode:y,exitCode:1}}T=Ei(l)}if(u!=="migrate-project-id"&&l.execute({phase:"client-preflight",domain:"client-persistence",category:"first-run-marker",operation:"create"},()=>Ba(),()=>{}),u==="migrate-project-id"){const c=await oa(P);if(!c.supported)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_CAPABILITY_UNAVAILABLE: the server did not advertise the versioned migration capability; no local state was changed.",errorCode:"PROJECT_IDENTITY_MIGRATION_CAPABILITY_UNAVAILABLE",metadata:{projectIdentityMigrationCapability:c},exitCode:1};const p=[];let y;try{y=ra(s)}catch($){const Ee=$ instanceof Hn?$.code:"PROJECT_IDENTITY_MIGRATION_PREPARE_FAILED";return{success:!1,error:Ee,errorCode:Ee,exitCode:1}}p.push(Ut({phase:"prepare",outcome:y.changed&&y.document.phase==="prepared"?"prepared":"retry",floor:y.document.legacyEpicFloor,licenseId:"local-client",projectId:y.document.projectId}));const w=_n(s);if(w.config.project_id!==y.document.projectId)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",errorCode:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",metadata:{invocationDiagnostics:p},exitCode:1};const U=await Si(P,T?.licenseKey,l);if(U.status!=="authenticated"){const $=U.status==="refresh-required";return{success:!1,error:$?"Authentication refresh required. Run: neocortex activate YOUR-LICENSE-KEY":"Not authenticated. Visit https://neocortex.sh/portal/login to get your license key, then run: neocortex activate YOUR-LICENSE-KEY",errorCode:$?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",metadata:{invocationDiagnostics:p},exitCode:$?1:2}}let te;try{te=kr(e.args.trim(),w)}catch($){const Ee=$ instanceof Nr?$.code:"PROJECT_IDENTITY_MIGRATION_PROJECTION_FAILED";return{success:!1,error:Ee,errorCode:Ee,metadata:{invocationDiagnostics:p},exitCode:1}}let ce={args:o,projectRoot:s.replace(Kt(),"~"),stateSnapshot:te,platformTarget:O,...C?{nativeHostAttestation:C}:{},projectId:y.document.projectId,projectIdentityMigration:y.request,inputEvidence:n,idempotencyKey:y.document.operationId,registryVersion:dt,registryChecksum:st,compatibility:zn()};try{ce=ir(ce).body}catch($){if($ instanceof Jn||$ instanceof Kn)return{success:!1,error:$.message,errorCode:$.code,metadata:{invokePayload:$.telemetry,invocationDiagnostics:p},exitCode:1};throw $}const ne=await Un("invoke-query",()=>ur(P,ce,U.token,{refreshToken:()=>U.client.forceRefresh()}));if(!ne.ok||!ne.data)return p.push(Ut({phase:"seed",outcome:"rejected",floor:y.document.legacyEpicFloor,licenseId:"local-client",projectId:y.document.projectId})),{success:!1,error:Je(ne.error??"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",kt),errorCode:typeof ne.errorBody?.error_code=="string"?ne.errorBody.error_code:"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",metadata:{invocationDiagnostics:p},exitCode:ne.status===401?2:1};const me=ne.data.metadata?.projectIdentityMigration;try{qo(me),p.push(Ut({phase:"seed",outcome:me.status,floor:me.acceptedLegacyFloor,licenseId:"local-client",projectId:me.projectId})),ta(s,me),p.push(Ut({phase:"remote-acknowledged",outcome:me.status,floor:me.acceptedLegacyFloor,licenseId:"local-client",projectId:me.projectId})),na(s,me),p.push(Ut({phase:"finalize",outcome:"finalized",floor:me.acceptedLegacyFloor,licenseId:"local-client",projectId:me.projectId}))}catch($){p.push(Ut({phase:"reconcile",outcome:"rejected",floor:y.document.legacyEpicFloor,licenseId:"local-client",projectId:y.document.projectId}));const Ee=$ instanceof Hn?$.code:$ instanceof Error?$.message:"PROJECT_IDENTITY_MIGRATION_RECEIPT_INVALID";return{success:!1,error:Ee,errorCode:Ee,metadata:{invocationDiagnostics:p},exitCode:1}}return l.complete(),{success:!0,instructions:ne.data.instructions,metadata:{...ne.data.metadata,...ne.compatibility?{compatibility:ne.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(
|
|
35
|
+
`),{success:!1,error:c,exitCode:1}}const K=mi(u);if(K)try{Zn(s,{allowMissingRuntime:!0}).runtimeMissing&&(await l.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},async()=>la(s),async()=>{}),Zn(s))}catch(c){const p=c instanceof lt?c.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${p}. No request was sent; repair the canonical project state and retry.
|
|
36
|
+
`),{success:!1,error:p,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}if(u!=="migrate-state")try{l.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>vo(s,{args:e.args,canonicalCommandId:u}),()=>{})}catch(c){if(c instanceof _o)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 ue;if(e.privateExecutionBeta&&(u==="sync-openapi"||u==="chaos-plan"||u==="arch-prd"||u==="arch-architecture"||u==="arch-fitness-functions"||u==="arch-api-contracts"||u==="arch-api-integrations"||u==="arch-database"||u==="arch-security"||u==="arch-design-system"||u==="arch-performance"||u==="arch-testing"||u==="arch-infrastructure"||u==="arch-review"||u==="update-memory"||u==="arch-ux-design"||u==="generate-pacts"||u==="property-test"||I))try{const{capturePrivateProjectStepBaseline:c}=await import("../private-execution/isolated-workspace.js");ue=c(s)}catch{const c="private-execution-project-snapshot-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}if(/^\s*\*?(?:yoloop|auto-yolo|epic-runner|story-runner|loop-yolo|auto-epic)\b/i.test(e.args))try{await(await import("../yoloop/invoke-hooks.js")).maybeCaptureYoloopStartOriginBinding(e.args,s)}catch{}let x;try{const c=await wc(s,e.args,u);x=_n(s,{epicAware:K,p205Authorities:c,verifyPlanningGeneration:e.privateExecutionBeta&&u==="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:y=>process.stderr.write(`${y}
|
|
40
40
|
`),warn:y=>process.stderr.write(`${y}
|
|
41
|
-
`)}};c(p),p.args!==e.args&&(e={...e,args:p.args},
|
|
42
|
-
`)}try{const{readYoloopForRequest:c}=await import("../yoloop/invoke-hooks.js"),p=await c(e.args,s);if(p){const y=
|
|
43
|
-
`),{success:!1,error:y,errorCode:y,exitCode:1}}}try{const{readContinuityForRequest:c}=await import("../continuity/invoke-hooks.js"),p=await c(e.args,s,void 0,
|
|
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
|
-
`)}});y.applied&&y.metadata&&(
|
|
47
|
-
`)}try{if(
|
|
48
|
-
`)}if(
|
|
49
|
-
`)
|
|
50
|
-
`),{
|
|
51
|
-
`)
|
|
52
|
-
`),{success:!1,error:
|
|
53
|
-
`)
|
|
54
|
-
`),{success:!1,error:
|
|
55
|
-
`),{success:!1,error:c,errorCode:"EPIC_PROJECT_ID_REQUIRED",exitCode:1}}let Pe;try{Pe=E.execute({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>$==="create-epic"||$==="idea-diagnose"?Da(s,Z,$):void 0,()=>{})}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const Nt=Pe?.key??($==="yolo"?ja(s,Z,Te,O):void 0);if(e.privateExecutionBeta&&$==="create-epic"&&Pe){const c=Ht(s).operations[Pe.fingerprint],p=c?.epicId?b.epics[c.epicId]:void 0,y=h(p?.createEpicPlanningPhysical)?p.createEpicPlanningPhysical:void 0;c?.claimId&&c.epicId&&p&&y?.claimId===c.claimId&&(O={...O,epics:{...O.epics,[c.epicId]:p},stories:{...O.stories,...Object.fromEntries((Array.isArray(p.stories)?p.stories:[]).filter(A=>typeof A=="string"&&b.stories[A]?.epic_id===c.epicId).map(A=>[A,b.stories[A]]))}})}const rt=x?{schemaVersion:1,invocationId:E.invocationId,intent:E.intent,clientProjection:$o(Br.map(c=>({...c,count:1})))}:void 0;let K,ve,he;if(e.privateExecutionBeta&&$==="idea-research")try{const c=O.scope?.targetEpicId,p=c?O.epics[c]:void 0,y=h(p?.createEpicPlanningPhysical)?p.createEpicPlanningPhysical:void 0;if(!c||!y||typeof y.claimId!="string"||typeof y.receiptId!="string")throw new Error("planning-research-predecessor-unavailable");const A=z(s,".neocortex/state.json"),B=Vt(A);if(!B.isFile()||B.isSymbolicLink()||B.size>8*1024*1024)throw new Error("planning-research-state-unavailable");const ne=Fe(A),ce=JSON.parse(ne.toString("utf8")),re=_r(ce,y.claimId,c),fe=h(ce)&&h(ce.epics)&&h(ce.epics[c])?ce.epics[c]:void 0,U=h(fe?.createEpicPlanningPhysical)?fe.createEpicPlanningPhysical:void 0;if(U?.receiptId!==y.receiptId||!C(U,y))throw new Error("planning-research-predecessor-drift");const Ee=[".neocortex/state.json",".neocortex/planning/planning.json",`.neocortex/planning/epic-${c}/idea.json`,`.neocortex/planning/epic-${c}/diagnosis.md`,`.neocortex/planning/epic-${c}/enriched-prompt.md`],$e={...process.env};for(const me of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete $e[me];for(const me of Ee){const He=Vt(z(s,me));if(!He.isFile()||He.isSymbolicLink()||He.size>8*1024*1024)throw new Error("planning-research-source-unavailable");const Xe=Be("git",["show",`HEAD:${me}`],{cwd:s,env:$e,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!Fe(z(s,me)).equals(Xe))throw new Error("planning-research-source-uncommitted")}ve={claimId:y.claimId,epicId:c,diagnosisReceiptId:re.diagnosisReceiptId,intakeRevision:re.intakeRevision,physicalAcceptanceReceiptId:y.receiptId,sourceStateSha256:Ne("sha256").update(ne).digest("hex")}}catch{return{success:!1,error:"private-execution-planning-predecessor-unavailable",errorCode:"private-execution-planning-predecessor-unavailable",exitCode:1}}if(e.privateExecutionBeta&&$==="generate-epic")try{const c=O.scope?.targetEpicId,p=c?O.epics[c]:void 0,y=h(p?.createEpicPlanningResearchPhysical)?p.createEpicPlanningResearchPhysical:void 0;if(!c||!y||typeof y.claimId!="string"||typeof y.receiptId!="string")throw new Error("planning-generation-predecessor-unavailable");const A=z(s,".neocortex/state.json"),B=Vt(A);if(!B.isFile()||B.isSymbolicLink()||B.size>8*1024*1024)throw new Error("planning-generation-state-unavailable");const ne=Fe(A),ce=JSON.parse(ne.toString("utf8")),re=Rr(ce,y.claimId,c),fe=h(ce)&&h(ce.epics)&&h(ce.epics[c])?ce.epics[c]:void 0,U=h(fe?.createEpicPlanningResearchPhysical)?fe.createEpicPlanningResearchPhysical:void 0;if(U?.receiptId!==y.receiptId||!C(U,y))throw new Error("planning-generation-predecessor-drift");const Ee=[".neocortex/state.json",".neocortex/planning/planning.json",`.neocortex/planning/epic-${c}/idea.json`,`.neocortex/planning/epic-${c}/diagnosis.md`,`.neocortex/planning/epic-${c}/enriched-prompt.md`,`.neocortex/planning/epic-${c}/research.md`],$e={...process.env};for(const me of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete $e[me];for(const me of Ee){const He=Vt(z(s,me));if(!He.isFile()||He.isSymbolicLink()||He.size>8*1024*1024)throw new Error("planning-generation-source-unavailable");const Xe=Be("git",["show",`HEAD:${me}`],{cwd:s,env:$e,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!Fe(z(s,me)).equals(Xe))throw new Error("planning-generation-source-uncommitted")}he={claimId:y.claimId,epicId:c,diagnosisReceiptId:re.diagnosisReceiptId,researchReceiptId:re.researchReceiptId,intakeRevision:re.intakeRevision,physicalAcceptanceReceiptId:re.physicalAcceptanceReceiptId,sourceStateSha256:Ne("sha256").update(ne).digest("hex")}}catch{return{success:!1,error:"private-execution-planning-predecessor-unavailable",errorCode:"private-execution-planning-predecessor-unavailable",exitCode:1}}if(e.privateExecutionBeta)try{const{preflightPrivateCodexExecutor:c}=await import("../private-execution/codex-executor.js");K=await c(s)}catch(c){const p=c instanceof Error&&/^private-codex-[a-z-]+$/.test(c.message)?c.message:"private-codex-preflight-unavailable";return{success:!1,error:p,errorCode:p,exitCode:1}}const qe=K?{schemaVersion:1,hostKind:"codex-cli",hostVersion:K.hostVersion,sandboxProof:{schemaVersion:6,trust:"client-self-attested",credentialKind:"chatgpt-subscription",authIsolation:"passed",workspaceWrite:"passed",gitControlWriteDenied:"passed",gitLifecycleReadDenied:"passed",mcpIsolation:"passed",environmentIsolation:"passed",networkDenied:"passed",webSearchDisabled:"passed",observedAtMs:K.observedAtMs}}:void 0;let V;if($==="arch-plan"&&O.archPlan?.execution?.currentStageCommand==="generate-pacts"&&O.archPlan.execution.continuationState==="ask-user")try{if(V=vr(s),!V)throw new Error("architecture-answers-required")}catch(c){const p=c instanceof Error&&/^architecture-answers-[a-z-]+$/.test(c.message)?c.message:"architecture-answers-failed";return{success:!1,error:p,errorCode:p,exitCode:1}}let ft;if($==="arch-plan"&&O.archPlan?.execution?.currentStageCommand==="generate-pacts"&&O.archPlan.execution.continuationState==="delegate"&&O.archPlan.execution.childStatus==="succeeded")try{if(ft=vr(s),!ft||!C(O.archPlan.execution.pactAnswerReceipt,ft))throw new Error("architecture-answers-conflict")}catch{return{success:!1,error:"architecture-answers-conflict",errorCode:"architecture-answers-conflict",exitCode:1}}let ge,ae,ye;if(e.privateExecutionBeta&&$==="generate-pacts")try{const c=o.trim().match(/^\*?generate-pacts (P[1-9][0-9]{0,11})$/)?.[1],p=O.archPlan?.execution;if(ae=Ji(s),!c||!p||p.currentStageCommand!=="generate-pacts"||p.continuationState!=="delegate"||p.targetEpicId!==c||!ae||!C(p.pactAnswerReceipt,ae.receipt))throw new Error("private-execution-pact-admission-unverified");const y=Qi(s,ae.answers.generateProvider);if(y.outcome!=="ready")throw new Error("private-execution-pact-admission-unverified");ge=y.writeSet,ye={schemaVersion:1,targetEpicId:c,graphRevision:ae.receipt.graphRevision,answersSha256:ae.receipt.answersSha256,specSha256:ge.specSha256,pathsSha256:ge.pathsSha256,endpointCount:ge.endpointCount,pathCount:ge.paths.length,publicSafe:!0}}catch{const c="private-execution-pact-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let Ve,ee;if(e.privateExecutionBeta&&$==="arch-ux-design")try{const c=o.trim().match(/^\*?arch-ux-design (P[1-9][0-9]{0,11})$/)?.[1],p=O.archPlan?.execution;if(!c||!p||p.currentStageCommand!=="arch-ux-design"||p.continuationState!=="delegate"||p.targetEpicId!==c||typeof p.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(p.graphRevision))throw new Error("private-execution-ux-admission-unverified");const{deriveUxWriteSet:y}=await import("../private-execution/ux-write-set.js");Ve=y(s,c),ee={schemaVersion:1,targetEpicId:c,graphRevision:p.graphRevision,adapterId:Ve.adapterId,authoritySha256:Ve.authoritySha256,pathsSha256:Ve.pathsSha256,screenCount:Ve.screenCount,pathCount:Ve.pathCount,publicSafe:!0}}catch{const c="private-execution-ux-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let mt,ze,ke;if(e.privateExecutionBeta&&$==="property-test")try{if(a.selection.positionals.length!==0||a.selection.operationId!==void 0||Object.keys(a.selection.options).length!==0)throw new Error("private-execution-property-admission-unverified");const{loadPropertyTestChoices:c}=await import("../private-execution/property-test-choices.js"),{propertyTestExecutionInput:p}=await import("../private-execution/property-test-plan.js"),y=c(s);if(!y)throw new Error("private-execution-property-admission-unverified");mt=y.choices,ze=y.plan,ke=p(y.plan)}catch{const c="private-execution-property-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let Qe;if($==="yoloop"&&!x&&!e.privateExecutionBeta)try{Qe=(e.hostCapacityProbe??to)({platformTarget:k,env:M})}catch{Qe=void 0}let H={args:o,projectRoot:s.replace(Kt(),"~"),stateSnapshot:O,...V?{architectureAnswerReceipt:V}:{},...ye?{pactExecutionInput:ye}:{},...ee?{uxExecutionInput:ee}:{},...ke?{propertyTestExecutionInput:ke}:{},platformTarget:k,..._?{nativeHostAttestation:_}:{},...Qe?{hostCapacity:Qe}:{},...qe?{privateExecution:qe}:{},projectId:Te,inputEvidence:n,...d?{invocationRecovery:d}:{},idempotencyKey:Nt,registryVersion:dt,registryChecksum:st,compatibility:zn(),...e.releaseGate?{releaseGate:e.releaseGate}:{},...rt?{strictReadOnly:rt}:{}};const xn=Wt(H);if(!x&&e.inputSource&&e.inputSource!=="args"&&xn>=Gn)try{H={argsRef:(await Vo(E,"secondary-mutation",()=>Oc(L,o,J.token,()=>J.client.forceRefresh()),async()=>{throw new Bt("readonly-physical-boundary-unsafe","boundary")})).argsRef,projectRoot:s.replace(Kt(),"~"),stateSnapshot:O,...V?{architectureAnswerReceipt:V}:{},platformTarget:k,..._?{nativeHostAttestation:_}:{},...Qe?{hostCapacity:Qe}:{},...qe?{privateExecution:qe}:{},projectId:Te,inputEvidence:n,...d?{invocationRecovery:d}:{},idempotencyKey:Nt,registryVersion:dt,registryChecksum:st,compatibility:zn(),...e.releaseGate?{releaseGate:e.releaseGate}:{},...rt?{strictReadOnly:rt}:{}}}catch(c){return c instanceof Bt?{success:!1,error:c.code,errorCode:c.code,exitCode:1}:{success:!1,error:`INVOKE_MATERIALIZATION_FAILED: ${c instanceof Error?c.message:String(c)}`,errorCode:"INVOKE_MATERIALIZATION_FAILED",exitCode:1}}let it;if($==="yolo"&&O.scope?.projectionMode==="yolo-story"){const c=O.scope?.targetStoryId,p=O.scope?.targetEpicId;if(!c||!p||!D||D.storyId!==c||D.epicId!==p)return{success:!1,error:"yolo-spec-envelope-target-mismatch",errorCode:"yolo-spec-envelope-target-mismatch",exitCode:1};try{let y=Gr(D);if(/\sbranchless-preparation\s*$/.test(o))H={...H,yoloSpecEnvelope:y};else{const{collectYoloChangeEvidence:A,reconcileYoloChangeEvidenceLease:B}=await import("../yolo/change-evidence-collector.js");it=await B({projectRoot:s,storyId:c,epicId:p}),it.repair==="applied"&&(y=Gr(D));const ne=A({projectRoot:s,defaultBranch:O.config.default_branch,expectedHeadSha:y.sourceRevision.headSha,storyId:c,epicId:p,reconciliation:it});H={...H,yoloSpecEnvelope:y,yoloChangeEvidence:ne}}H=_a(H,{projectRoot:s,supported:Y})}catch(y){const{yoloChangeEvidenceDiagnostic:A}=await import("../yolo/change-evidence-collector.js"),B=A(y),ne=Fr(y,!0);return{success:!1,error:ne,errorCode:ne,...B?{metadata:{yoloChangeEvidence:B}}:{},exitCode:1}}}try{const c=ir(H);if($==="migrate-state"&&c.degraded)return{success:!1,error:"state_migration_payload_degraded",errorCode:"state_migration_payload_degraded",exitCode:1};H=c.body,c.degraded?Ai(H,c.telemetry):Vc(H)}catch(c){if(c instanceof Jn||c instanceof Kn)return Ai(H,c.telemetry),process.stderr.write(`[Neocortex] ${c.message}
|
|
56
|
-
`),{success:!1,error:
|
|
41
|
+
`)}};c(p),p.args!==e.args&&(e={...e,args:p.args},i=p.args,r=$n(Qt(t.source,i)))}catch(c){const p=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] Auto-resolve hook (P121.05) failed: ${p}. Proceeding with raw args.
|
|
42
|
+
`)}try{const{readYoloopForRequest:c}=await import("../yoloop/invoke-hooks.js"),p=await c(e.args,s);if(p){const y=xs(x,p);x.yoloop=y?{...p,continuationRecoveryEvidence:y}:p}}catch(c){if(/^\s*\*?(?:yoloop|auto-yolo|epic-runner|story-runner|loop-yolo|auto-epic)\b/i.test(e.args)){const y=c instanceof Error?c.message.match(/\bYOLOOP_[A-Z0-9_]+\b/)?.[0]??"YOLOOP_STATE_READ_FAILED":"YOLOOP_STATE_READ_FAILED";return process.stderr.write(`[Neocortex] ${y}. No yoloop request was sent.
|
|
43
|
+
`),{success:!1,error:y,errorCode:y,exitCode:1}}}try{const{readContinuityForRequest:c}=await import("../continuity/invoke-hooks.js"),p=await c(e.args,s,void 0,l,{includeExistingStore:!S});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"),y=await p({args:e.args,projectRoot:s,featureFlag:c,logger:{warn:w=>process.stderr.write(`${w}
|
|
46
|
+
`)}});y.applied&&y.metadata&&(x.graphRetrieval=y.metadata)}catch(c){const p=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] graph retrieval hook failed: ${p}. Proceeding without enrichment.
|
|
47
|
+
`)}try{if(za(e.args)){const{collectProjectEvidence:c}=await import("../evidence/collector.js"),p=a.selection.uiUxReview?.architectureDir,y=c({projectRoot:s,...p?{candidatePaths:[p],includeFallbackInventory:!0}:{}});(y.evidence.length>0||y.exclusions.length>0)&&(x.projectEvidence=y)}}catch(c){const p=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] project evidence collection failed: ${p}. Proceeding without local project evidence.
|
|
48
|
+
`)}if(u==="yoloop"&&O==="claude-code"){const{ensureClaudeWorktreeBaseRef:c}=await import("../agent/claude-worktree-base.js"),p=c();p.action==="applied"?process.stderr.write(`[yoloop] claude-worktree-baseref-applied: Claude Code worktree.baseRef set to "head" for v4 story worktrees.
|
|
49
|
+
`):(p.reasonCode==="claude-worktree-baseref-user-value-kept"||p.reasonCode==="claude-settings-invalid")&&process.stderr.write(`[yoloop] ${p.reasonCode}: v4 story worktrees start from the remote default branch; set Claude Code worktree.baseRef to "head".
|
|
50
|
+
`)}if(u==="yoloop"||u==="yolo"){const c=Ic(s,x.epics??{},x.stories??{},yc(i));c&&(x.storyWorktreeReadiness=c)}try{const c=await l.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.
|
|
51
|
+
`)}const pe=T?.licenseKey?new Vn({cacheDir:Wn,passphrase:T.licenseKey,strictReadOnly:A}):null,oe=i.trim();if(!oe&&pe){const c=await l.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>xc(pe),async()=>null);if(c)return l.complete(),{success:!0,instructions:c.instructions,metadata:c.metadata,exitCode:0}}const G=await Si(P,T?.licenseKey,l);if(G.status!=="authenticated"){const c=G.status==="refresh-required",p=!c&&T&&!T.licenseKey?" This may be caused by a machine fingerprint change (e.g., hardware or hostname change).":"";try{const y=Pr(),w=xr(c?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",y);w&&process.stderr.write(Tr(w,y))}catch{}return{success:!1,error:c?"Authentication refresh required. Run: neocortex activate YOUR-LICENSE-KEY":`Not authenticated.${p} Visit https://neocortex.sh/portal/login to get your license key, then run: neocortex activate YOUR-LICENSE-KEY`,errorCode:c?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",exitCode:c?1:2}}const gt=x.config.project_id;try{await l.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>bs(s,x,P,G.token,gt,{refreshToken:()=>G.client.forceRefresh()}),async()=>0)}catch{}const wt=Bs(oe);if(wt&&!S)try{const c=await G.tierClient.preFlightCheck(wt);if(!c.allowed)return process.stderr.write(`[neocortex] ${c.message}
|
|
52
|
+
`),{success:!1,error:c.message??"Trigger not available on your plan",exitCode:1}}catch{}const he=await Gc({args:oe,projectRoot:s,platformTarget:O,environment:e.environment??process.env,bootstrapper:e.runnerBootstrapper,effectAuthority:l});if(he.attachToRequest&&(x.runnerBootstrap=he.metadata),he.warning&&process.stderr.write(`[Neocortex] ${he.warning}
|
|
53
|
+
`),!he.shouldContinue)return he.error&&process.stderr.write(`[Neocortex] ${he.error}
|
|
54
|
+
`),{success:!1,error:he.error??"Runner auto-bootstrap required but failed.",errorCode:he.errorCode,exitCode:he.exitCode??1};if(he.metadata.command==="runner"&&(he.metadata.operation==="status"||he.metadata.operation==="doctor"))try{const c=e.runnerObserver??Po;x.runnerOperationalStatus=await c(he.metadata.operation,{projectRoot:s,env:e.environment??process.env,effectAuthority:l})}catch{}let N;try{const c=So(oe,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}
|
|
55
|
+
`),{success:!1,error:p,errorCode:c.code,metadata:{stateProjection:c,publicSafe:!0},exitCode:1}}N=c?.snapshot??kr(oe,x),hn(oe)==="migrate-state"&&(N={...N,migrationAuthority:Ro(s)})}catch(c){if(c instanceof wo)return{success:!1,error:c.reasonCode,errorCode:c.reasonCode,exitCode:1};if(c instanceof Nr){const p=`${c.code}: structural projection failed closed; select a valid target or repair the dependency DAG.`;return process.stderr.write(`${p}
|
|
56
|
+
`),{success:!1,error:p,errorCode:c.code,metadata:{structuralProjection:{...c.publicDetails,publicSafe:!0}},exitCode:1}}throw c}if(!A)try{const{openNativeAgentPrivateStore:c,resolveNativeAgentPrivateRuntimePaths:p}=await import("../continuity/native-agent-store.js"),y=p(s);if(jt(y.databasePath)){const w=await c(s);try{const U=w.store.listRecentNativeAgentDispatches(20);U.length>0&&(N.nativeAgentDispatches=U)}finally{w.store.close()}}}catch{}const H=hn(oe);let xe=!1;if(H==="arch-plan"&&!A&&N.archPlan?.execution===void 0){const c=Qi(i);if(c)try{if(!Object.hasOwn(x.epics,c)||!Object.hasOwn(N.epics,c))throw new Error("architecture-root-epic-binding-invalid");const p=Yt(s,c);N={...N,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((H==="arch-plan"||H?.startsWith("arch-")||H==="generate-pacts"||H==="update-memory")&&N.archPlan?.execution?.graphSource==="committed-epic-v1")try{const c=N.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((H==="create-epic"||H==="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}
|
|
57
|
+
`),{success:!1,error:c,errorCode:"EPIC_PROJECT_ID_REQUIRED",exitCode:1}}let Pe;try{Pe=l.execute({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>H==="create-epic"||H==="idea-diagnose"?Ma(s,oe,H):void 0,()=>{})}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const Nt=Pe?.key??(H==="yolo"?Va(s,oe,Te,N):void 0);if(e.privateExecutionBeta&&H==="create-epic"&&Pe){const c=Ht(s).operations[Pe.fingerprint],p=c?.epicId?x.epics[c.epicId]:void 0,y=g(p?.createEpicPlanningPhysical)?p.createEpicPlanningPhysical:void 0;c?.claimId&&c.epicId&&p&&y?.claimId===c.claimId&&(N={...N,epics:{...N.epics,[c.epicId]:p},stories:{...N.stories,...Object.fromEntries((Array.isArray(p.stories)?p.stories:[]).filter(w=>typeof w=="string"&&x.stories[w]?.epic_id===c.epicId).map(w=>[w,x.stories[w]]))}})}const rt=A?{schemaVersion:1,invocationId:l.invocationId,intent:l.intent,clientProjection:Ho(Br.map(c=>({...c,count:1})))}:void 0;let Q,ve,ge;if(e.privateExecutionBeta&&H==="idea-research")try{const c=N.scope?.targetEpicId,p=c?N.epics[c]:void 0,y=g(p?.createEpicPlanningPhysical)?p.createEpicPlanningPhysical:void 0;if(!c||!y||typeof y.claimId!="string"||typeof y.receiptId!="string")throw new Error("planning-research-predecessor-unavailable");const w=J(s,".neocortex/state.json"),U=Vt(w);if(!U.isFile()||U.isSymbolicLink()||U.size>8*1024*1024)throw new Error("planning-research-state-unavailable");const te=Fe(w),ce=JSON.parse(te.toString("utf8")),ne=_r(ce,y.claimId,c),me=g(ce)&&g(ce.epics)&&g(ce.epics[c])?ce.epics[c]:void 0,$=g(me?.createEpicPlanningPhysical)?me.createEpicPlanningPhysical:void 0;if($?.receiptId!==y.receiptId||!v($,y))throw new Error("planning-research-predecessor-drift");const Ee=[".neocortex/state.json",".neocortex/planning/planning.json",`.neocortex/planning/epic-${c}/idea.json`,`.neocortex/planning/epic-${c}/diagnosis.md`,`.neocortex/planning/epic-${c}/enriched-prompt.md`],$e={...process.env};for(const ye of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete $e[ye];for(const ye of Ee){const He=Vt(J(s,ye));if(!He.isFile()||He.isSymbolicLink()||He.size>8*1024*1024)throw new Error("planning-research-source-unavailable");const Xe=Be("git",["show",`HEAD:${ye}`],{cwd:s,env:$e,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!Fe(J(s,ye)).equals(Xe))throw new Error("planning-research-source-uncommitted")}ve={claimId:y.claimId,epicId:c,diagnosisReceiptId:ne.diagnosisReceiptId,intakeRevision:ne.intakeRevision,physicalAcceptanceReceiptId:y.receiptId,sourceStateSha256:Ne("sha256").update(te).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=N.scope?.targetEpicId,p=c?N.epics[c]:void 0,y=g(p?.createEpicPlanningResearchPhysical)?p.createEpicPlanningResearchPhysical:void 0;if(!c||!y||typeof y.claimId!="string"||typeof y.receiptId!="string")throw new Error("planning-generation-predecessor-unavailable");const w=J(s,".neocortex/state.json"),U=Vt(w);if(!U.isFile()||U.isSymbolicLink()||U.size>8*1024*1024)throw new Error("planning-generation-state-unavailable");const te=Fe(w),ce=JSON.parse(te.toString("utf8")),ne=Rr(ce,y.claimId,c),me=g(ce)&&g(ce.epics)&&g(ce.epics[c])?ce.epics[c]:void 0,$=g(me?.createEpicPlanningResearchPhysical)?me.createEpicPlanningResearchPhysical:void 0;if($?.receiptId!==y.receiptId||!v($,y))throw new Error("planning-generation-predecessor-drift");const Ee=[".neocortex/state.json",".neocortex/planning/planning.json",`.neocortex/planning/epic-${c}/idea.json`,`.neocortex/planning/epic-${c}/diagnosis.md`,`.neocortex/planning/epic-${c}/enriched-prompt.md`,`.neocortex/planning/epic-${c}/research.md`],$e={...process.env};for(const ye of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete $e[ye];for(const ye of Ee){const He=Vt(J(s,ye));if(!He.isFile()||He.isSymbolicLink()||He.size>8*1024*1024)throw new Error("planning-generation-source-unavailable");const Xe=Be("git",["show",`HEAD:${ye}`],{cwd:s,env:$e,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!Fe(J(s,ye)).equals(Xe))throw new Error("planning-generation-source-uncommitted")}ge={claimId:y.claimId,epicId:c,diagnosisReceiptId:ne.diagnosisReceiptId,researchReceiptId:ne.researchReceiptId,intakeRevision:ne.intakeRevision,physicalAcceptanceReceiptId:ne.physicalAcceptanceReceiptId,sourceStateSha256:Ne("sha256").update(te).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");Q=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=Q?{schemaVersion:1,hostKind:"codex-cli",hostVersion:Q.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:Q.observedAtMs}}:void 0;let V;if(H==="arch-plan"&&N.archPlan?.execution?.currentStageCommand==="generate-pacts"&&N.archPlan.execution.continuationState==="ask-user")try{if(V=vr(s),!V)throw new Error("architecture-answers-required")}catch(c){const p=c instanceof Error&&/^architecture-answers-[a-z-]+$/.test(c.message)?c.message:"architecture-answers-failed";return{success:!1,error:p,errorCode:p,exitCode:1}}let ft;if(H==="arch-plan"&&N.archPlan?.execution?.currentStageCommand==="generate-pacts"&&N.archPlan.execution.continuationState==="delegate"&&N.archPlan.execution.childStatus==="succeeded")try{if(ft=vr(s),!ft||!v(N.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 fe,ae,Ie;if(e.privateExecutionBeta&&H==="generate-pacts")try{const c=i.trim().match(/^\*?generate-pacts (P[1-9][0-9]{0,11})$/)?.[1],p=N.archPlan?.execution;if(ae=Ki(s),!c||!p||p.currentStageCommand!=="generate-pacts"||p.continuationState!=="delegate"||p.targetEpicId!==c||!ae||!v(p.pactAnswerReceipt,ae.receipt))throw new Error("private-execution-pact-admission-unverified");const y=Xi(s,ae.answers.generateProvider);if(y.outcome!=="ready")throw new Error("private-execution-pact-admission-unverified");fe=y.writeSet,Ie={schemaVersion:1,targetEpicId:c,graphRevision:ae.receipt.graphRevision,answersSha256:ae.receipt.answersSha256,specSha256:fe.specSha256,pathsSha256:fe.pathsSha256,endpointCount:fe.endpointCount,pathCount:fe.paths.length,publicSafe:!0}}catch{const c="private-execution-pact-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let Ve,Z;if(e.privateExecutionBeta&&H==="arch-ux-design")try{const c=i.trim().match(/^\*?arch-ux-design (P[1-9][0-9]{0,11})$/)?.[1],p=N.archPlan?.execution;if(!c||!p||p.currentStageCommand!=="arch-ux-design"||p.continuationState!=="delegate"||p.targetEpicId!==c||typeof p.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(p.graphRevision))throw new Error("private-execution-ux-admission-unverified");const{deriveUxWriteSet:y}=await import("../private-execution/ux-write-set.js");Ve=y(s,c),Z={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&&H==="property-test")try{if(a.selection.positionals.length!==0||a.selection.operationId!==void 0||Object.keys(a.selection.options).length!==0)throw new Error("private-execution-property-admission-unverified");const{loadPropertyTestChoices:c}=await import("../private-execution/property-test-choices.js"),{propertyTestExecutionInput:p}=await import("../private-execution/property-test-plan.js"),y=c(s);if(!y)throw new Error("private-execution-property-admission-unverified");mt=y.choices,ze=y.plan,ke=p(y.plan)}catch{const c="private-execution-property-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let Qe;if(H==="yoloop"&&!A&&!e.privateExecutionBeta)try{Qe=(e.hostCapacityProbe??no)({platformTarget:O,env:j})}catch{Qe=void 0}let W={args:i,projectRoot:s.replace(Kt(),"~"),stateSnapshot:N,...V?{architectureAnswerReceipt:V}:{},...Ie?{pactExecutionInput:Ie}:{},...Z?{uxExecutionInput:Z}:{},...ke?{propertyTestExecutionInput:ke}:{},platformTarget:O,...C?{nativeHostAttestation:C}:{},...Qe?{hostCapacity:Qe}:{},...qe?{privateExecution:qe}:{},projectId:Te,inputEvidence:r,...d?{invocationRecovery:d}:{},idempotencyKey:Nt,registryVersion:dt,registryChecksum:st,compatibility:zn(),...e.releaseGate?{releaseGate:e.releaseGate}:{},...rt?{strictReadOnly:rt}:{}};const xn=Wt(W);if(!A&&e.inputSource&&e.inputSource!=="args"&&xn>=Gn)try{W={argsRef:(await Bo(l,"secondary-mutation",()=>jc(P,i,G.token,()=>G.client.forceRefresh()),async()=>{throw new Bt("readonly-physical-boundary-unsafe","boundary")})).argsRef,projectRoot:s.replace(Kt(),"~"),stateSnapshot:N,...V?{architectureAnswerReceipt:V}:{},platformTarget:O,...C?{nativeHostAttestation:C}:{},...Qe?{hostCapacity:Qe}:{},...qe?{privateExecution:qe}:{},projectId:Te,inputEvidence:r,...d?{invocationRecovery:d}:{},idempotencyKey:Nt,registryVersion:dt,registryChecksum:st,compatibility:zn(),...e.releaseGate?{releaseGate:e.releaseGate}:{},...rt?{strictReadOnly:rt}:{}}}catch(c){return c instanceof Bt?{success:!1,error:c.code,errorCode:c.code,exitCode:1}:{success:!1,error:`INVOKE_MATERIALIZATION_FAILED: ${c instanceof Error?c.message:String(c)}`,errorCode:"INVOKE_MATERIALIZATION_FAILED",exitCode:1}}let it;if(H==="yolo"&&N.scope?.projectionMode==="yolo-story"){const c=N.scope?.targetStoryId,p=N.scope?.targetEpicId;if(!c||!p||!B||B.storyId!==c||B.epicId!==p)return{success:!1,error:"yolo-spec-envelope-target-mismatch",errorCode:"yolo-spec-envelope-target-mismatch",exitCode:1};try{let y=Gr(B);if(/\sbranchless-preparation\s*$/.test(i))W={...W,yoloSpecEnvelope:y};else{const{collectYoloChangeEvidence:w,reconcileYoloChangeEvidenceLease:U}=await import("../yolo/change-evidence-collector.js");it=await U({projectRoot:s,storyId:c,epicId:p}),it.repair==="applied"&&(y=Gr(B));const te=w({projectRoot:s,defaultBranch:N.config.default_branch,expectedHeadSha:y.sourceRevision.headSha,storyId:c,epicId:p,reconciliation:it});W={...W,yoloSpecEnvelope:y,yoloChangeEvidence:te}}W=Ra(W,{projectRoot:s,supported:D})}catch(y){const{yoloChangeEvidenceDiagnostic:w}=await import("../yolo/change-evidence-collector.js"),U=w(y),te=Fr(y,!0);return{success:!1,error:te,errorCode:te,...U?{metadata:{yoloChangeEvidence:U}}:{},exitCode:1}}}try{const c=ir(W);if(H==="migrate-state"&&c.degraded)return{success:!1,error:"state_migration_payload_degraded",errorCode:"state_migration_payload_degraded",exitCode:1};W=c.body,c.degraded?bi(W,c.telemetry):Wc(W)}catch(c){if(c instanceof Jn||c instanceof Kn)return bi(W,c.telemetry),process.stderr.write(`[Neocortex] ${c.message}
|
|
58
|
+
`),{success:!1,error:c.message,errorCode:c.code,metadata:{invokePayload:c.telemetry},exitCode:1};throw c}if(H==="yolo"&&W.yoloSpecEnvelope)try{const c=Wr({projectRoot:s,storyId:W.yoloSpecEnvelope.storyId,epicId:W.yoloSpecEnvelope.epicId,inputSha256:r.sha256,collectedAt:W.yoloSpecEnvelope.collectedAt});if(c.envelopeSha256!==W.yoloSpecEnvelope.envelopeSha256)throw new Error("yolo-spec-envelope-stale");if(W.yoloChangeEvidence){const{collectYoloChangeEvidence:p}=await import("../yolo/change-evidence-collector.js"),y=p({projectRoot:s,defaultBranch:N.config.default_branch,expectedHeadSha:c.sourceRevision.headSha,storyId:c.storyId,epicId:c.epicId,...it?{reconciliation:it}:{}});if(y.pathsSha256!==W.yoloChangeEvidence.pathsSha256||y.baseSha!==W.yoloChangeEvidence.baseSha)throw new Error("yolo-change-evidence-stale")}}catch(c){const p=c instanceof Error&&c.message==="yolo-change-evidence-stale"?c.message:"yolo-spec-envelope-stale",{yoloChangeEvidenceDiagnostic:y}=await import("../yolo/change-evidence-collector.js"),w=y(c);return{success:!1,error:p,errorCode:p,...w?{metadata:{yoloChangeEvidence:w}}:{},exitCode:1}}const L=H==="arch-plan"?W.stateSnapshot.archPlan?.execution:void 0;let Lt;if(L?.owner==="root"&&(L.currentStageCommand==="arch-prd"||L.currentStageCommand==="arch-architecture"||L.currentStageCommand==="arch-fitness-functions"||L.currentStageCommand==="arch-api-contracts"||L.currentStageCommand==="generate-pacts"||L.currentStageCommand==="arch-api-integrations"||L.currentStageCommand==="arch-database"||L.currentStageCommand==="arch-security"||L.currentStageCommand==="arch-design-system"||L.currentStageCommand==="arch-ux-design"||L.currentStageCommand==="arch-performance"||L.currentStageCommand==="arch-testing"||L.currentStageCommand==="arch-infrastructure"||L.currentStageCommand==="arch-review"||L.currentStageCommand==="update-memory")&&(L.continuationState==="delegate"||L.continuationState==="advance"||L.currentStageCommand==="update-memory"&&L.continuationState==="complete"||L.currentStageCommand==="arch-review"&&L.continuationState==="ask-user"||L.currentStageCommand==="generate-pacts"&&L.continuationState==="ask-user"))try{const c=Fe(J(s,".neocortex","state.json"),"utf8"),p=JSON.parse(c),y=g(p.archPlan)?p.archPlan.execution:void 0;if(xe?y!==void 0||!g(p.epics)||!Object.hasOwn(p.epics,String(L.targetEpicId))||L.graphSource!=="committed-epic-v1"||L.graphRevision!==Yt(s,String(L.targetEpicId)):!v(Sn(y),L))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(L.currentStageCommand==="update-memory"&&L.childStatus==="succeeded"){const w=L.continuationState==="complete"&&Array.isArray(L.acceptedStages)?{...L,continuationState:"delegate",acceptedStages:L.acceptedStages.slice(0,Er(L))}:L;if(!Ft(L.terminalMemoryCheckpoint,L)||!v(L.terminalMemoryCheckpoint,Dn(s,w)))throw new Error("architecture-terminal-memory-physical-invalid")}}catch{return{success:!1,error:"architecture-root-state-binding-invalid",errorCode:"architecture-root-state-binding-invalid",exitCode:1}}let f=await Un("invoke-query",()=>ur(P,W,G.token,{refreshToken:()=>G.client.forceRefresh()}));if(H==="yoloop"&&!A&&f.ok&&f.data?.metadata?.errorCode==="YOLOOP_SPEC_NOT_READY"&&f.data.metadata.hint==="yoloop-session-invalidated"){const c=N.scope?.targetEpicId;if(!c)return{success:!1,error:"yoloop-causal-reconciliation-target-invalid",errorCode:"YOLOOP_CAUSAL_RECONCILIATION_BLOCKED",exitCode:1};const p=await ks({projectRoot:s,snapshot:x,targetEpicId:c,originalInputSha256:r.sha256,canonicalInputSha256:d?.canonicalSha256??r.sha256});if(p.outcome!=="applied")return{success:!1,error:p.reasonCode,errorCode:"YOLOOP_CAUSAL_RECONCILIATION_BLOCKED",metadata:{yoloopCausalRecovery:p},exitCode:1};try{const{readYoloopForRequest:y}=await import("../yoloop/invoke-hooks.js"),w=await y(i,s);if(!w)throw new Error("yoloop-causal-reconciliation-postimage-unverified");W=ir({...W,stateSnapshot:{...W.stateSnapshot,yoloop:w}}).body}catch(y){const w=Ui(y);return{success:!1,error:w,errorCode:"YOLOOP_CAUSAL_RECONCILIATION_BLOCKED",metadata:{yoloopCausalRecovery:{outcome:"blocked",reasonCode:w,retryCount:0,publicSafe:!0}},exitCode:1}}f=await Un("invoke-query",()=>ur(P,W,G.token,{refreshToken:()=>G.client.forceRefresh()}))}let nn;if(A&&f.ok)try{if(S){const p=f.data?.metadata;if(p&&["stateUpdate","stateMutated","yoloopStateUpdate","continuityStateUpdate","checkpoint","schedulerStateUpdate","quotaCacheUpdate","projectIdentityMigration","epicClaim","gitLifecycleGraphAuthority"].some(w=>p[w]!==void 0))throw new Bt("readonly-response-conflict")}const c=f.data?.metadata.strictReadOnly;Go(l,c),S&&Ko(f.data?.metadata.strictDiagnose,o,f.data?.instructions??""),nn=c.security}catch(c){const p=c instanceof Bt?c.code:"readonly-receipt-mismatch";return{success:!1,error:p,errorCode:p,exitCode:1}}if(!f.ok&&f.status===426){const c=f.errorBody,p=c?.upgrade_command??"npm install -g @ornexus/neocortex@latest",y=c?.min_version??"unknown";return process.stderr.write(`
|
|
57
59
|
`),process.stderr.write(`==================================================
|
|
58
60
|
`),process.stderr.write(` UPGRADE REQUIRED
|
|
59
61
|
`),process.stderr.write(`==================================================
|
|
@@ -68,12 +70,12 @@ The C04 barrier did not open within the bounded wait. Return this resumable rece
|
|
|
68
70
|
`),process.stderr.write(` After updating, re-run your command.
|
|
69
71
|
`),process.stderr.write(`==================================================
|
|
70
72
|
|
|
71
|
-
`),{success:!1,error:`UPGRADE_REQUIRED: Client version ${Pt} is below minimum ${y}. Run: ${p}`,exitCode:3}}if(!f.ok||!f.data){const c=f.status===401?2:(f.status===429||f.status>=500,1),p=
|
|
72
|
-
`),y;try{if(p){const
|
|
73
|
-
`),{success:!1,error:p,errorCode:p,exitCode:1}}if(!
|
|
73
|
+
`),{success:!1,error:`UPGRADE_REQUIRED: Client version ${Pt} is below minimum ${y}. Run: ${p}`,exitCode:3}}if(!f.ok||!f.data){const c=f.status===401?2:(f.status===429||f.status>=500,1),p=kc(f),y=Ua(p);if(y)return process.stderr.write(`[Neocortex] ${y.error}
|
|
74
|
+
`),y;try{if(p){const w=Pr(),U=xr(p,w);U&&process.stderr.write(Tr(U,w))}}catch{}return{success:!1,error:Je(f.error??"Unknown error from server",kt),...p?{errorCode:p}:{},...f.compatibility?{metadata:{compatibility:f.compatibility}}:{},exitCode:c}}const gr=$a(f.data);if(gr)return l.complete(nn),gr;let Re;try{Re=e.privateExecutionBeta&&H==="create-epic"&&Pe?Ht(s).operations[Pe.fingerprint]:void 0}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const rn=Re?.planningProtocol==="root-staged-v1"&&typeof Re.claimId=="string"&&typeof Re.epicId=="string"&&io(f.data,{claimId:Re.claimId,epicId:Re.epicId,...g(x.epics[Re.epicId]?.createEpicPlanningMemoryPhysical)?{memoryReceiptId:x.epics[Re.epicId].createEpicPlanningMemoryPhysical.receiptId}:{}});if(e.privateExecutionBeta&&!rn&&!ro(f.data))return{success:!1,error:"private-execution-public-envelope-invalid",errorCode:"private-execution-public-envelope-invalid",exitCode:1};if(Lt&&L&&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 l.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>oc({projectRoot:s,sourceStateSha256:Lt,requestExecution:L,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.
|
|
75
|
+
`),{success:!1,error:p,errorCode:p,exitCode:1}}if(!oe&&f.data.metadata?.mode==="menu"&&pe&&await l.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>Tc(pe,f.data.instructions,f.data.metadata),async()=>{}).catch(()=>{}),f.data.metadata&&await l.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"tier-cache",operation:"update"},()=>G.tierClient.updateQuotaFromResponse(f.data.metadata),async()=>{}).catch(()=>{}),f.data.metadata?.stateMutated===!0)try{const c=await l.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
76
|
`),{success:!1,error:p,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}catch(c){if(f.data.metadata?.stateMutationReason==="inline-yolo-materialized-synthetic-story"){const p=c instanceof Error?c.message:String(c),y=`STATE_WRITEBACK_BLOCKED: inline-yolo persistence failed (${Je(p,kt)}).`;return process.stderr.write(`${y}
|
|
75
|
-
`),{success:!1,error:y,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}const on=f.data.metadata?.yoloopStoryWorktreeFallback;if(
|
|
76
|
-
`),f.data.metadata?.gitLifecycleGraphAuthority)try{await
|
|
77
|
+
`),{success:!1,error:y,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}const on=f.data.metadata?.yoloopStoryWorktreeFallback;if(g(on)&&typeof on.reasonCode=="string"&&/^story-worktree-[a-z0-9-]{1,64}$/.test(on.reasonCode)&&process.stderr.write(`[yoloop] v4 story-worktree plan not used: ${on.reasonCode}.
|
|
78
|
+
`),f.data.metadata?.gitLifecycleGraphAuthority)try{await l.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},()=>ga(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.
|
|
77
79
|
`),{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(`
|
|
78
80
|
`),process.stderr.write(`==================================================
|
|
79
81
|
`),process.stderr.write(` YOLOOP CLIENT UPGRADE REQUIRED
|
|
@@ -89,16 +91,16 @@ The C04 barrier did not open within the bounded wait. Return this resumable rece
|
|
|
89
91
|
`),process.stderr.write(` After upgrading, re-run your yoloop command.
|
|
90
92
|
`),process.stderr.write(`==================================================
|
|
91
93
|
|
|
92
|
-
`),{success:!1,error:"CLIENT_UPGRADE_REQUIRED: This client does not support yoloop client-side persistence. Run: npm install -g @ornexus/neocortex@latest",exitCode:3};if(f.data.metadata?.yoloopStateUpdate){const p=(f.data.metadata.yoloopStateUpdate.operations??[]).some(y=>y.type==="rollover_session");try{const y=await
|
|
93
|
-
`),{success:!1,error:
|
|
94
|
-
`),{success:!1,error:
|
|
94
|
+
`),{success:!1,error:"CLIENT_UPGRADE_REQUIRED: This client does not support yoloop client-side persistence. Run: npm install -g @ornexus/neocortex@latest",exitCode:3};if(f.data.metadata?.yoloopStateUpdate){const p=(f.data.metadata.yoloopStateUpdate.operations??[]).some(y=>y.type==="rollover_session");try{const y=await l.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>{const{persistYoloopFromResponse:w}=await import("../yoloop/invoke-hooks.js");return w(f.data.metadata,s)},async()=>({ok:!0,authoritative:!1,reasonCodes:[]}));if(y&&y.ok===!1){const w=y.reasonCodes[0]??"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED";return process.stderr.write(`[Neocortex] ${w}. No yoloop continuation instructions were released.
|
|
95
|
+
`),{success:!1,error:w,errorCode:w,exitCode:1}}}catch(y){if(p){const w=y instanceof Error?y.message.match(/\bYOLOOP_[A-Z0-9_]+\b/)?.[0]??"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED":"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED";return process.stderr.write(`[Neocortex] ${w}. No yoloop continuation instructions were released.
|
|
96
|
+
`),{success:!1,error:w,errorCode:w,exitCode:1}}}}if(f.data.metadata?.continuityStateUpdate)try{const c=await l.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.
|
|
95
97
|
`),{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.
|
|
96
|
-
`),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${Je(p,kt)}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}if(f.data.metadata?.tier_changed){const c=f.data.metadata.current_tier;try{await
|
|
98
|
+
`),{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 G.client.forceRefresh()?(await G.tierClient.invalidateTierCache(),process.stderr.write(`[Neocortex] Token atualizado automaticamente para tier ${c}
|
|
97
99
|
`)):process.stderr.write(`[Neocortex] Seu tier foi atualizado para ${c}! Execute "neocortex activate" para obter um token atualizado.
|
|
98
100
|
`)}catch{process.stderr.write(`[Neocortex] Seu tier foi atualizado para ${c}! Execute "neocortex activate" para obter um token atualizado.
|
|
99
|
-
`)}}let
|
|
101
|
+
`)}}let ee,fr=!1;if(e.privateExecutionBeta&&!rn)try{if(!Q||!f.data.metadata?.privateExecution||!Te||f.data.metadata?.mode!=="yolo"&&f.data.metadata?.mode!=="step"&&f.data.metadata?.mode!=="pipeline"&&f.data.metadata?.mode!=="create-epic"&&f.data.metadata?.mode!=="utility"&&f.data.metadata?.mode!=="tech-debt"&&f.data.metadata?.mode!=="ui-ux-review"||typeof f.data.metadata.stepId!="string")throw new Error("private-execution-descriptor-unavailable");const{consumePrivateExecutionDelivery:c,privateExecutionStateSnapshotSha256:p}=await import("../private-execution/delivery.js"),{preflightPrivateCodexExecutor:y,runPrivateCodexStep:w}=await import("../private-execution/codex-executor.js"),U=f.data.metadata.mode==="yolo",te=f.data.metadata.mode==="ui-ux-review"&&f.data.metadata.resolvedTrigger==="ui-ux-review",ce=f.data.metadata.mode==="create-epic",ne=g(f.data.metadata.privateExecution)?f.data.metadata.privateExecution:void 0,me=g(ne?.binding)?ne.binding:void 0,$=ce&&f.data.metadata.resolvedTrigger==="create-epic"&&me?.writeSetId==="idea-diagnosis-v1"&&f.data.metadata.stepId==="step-acd455ed";if(ce&&!$)throw new Error("private-execution-planning-root-protocol-required");const Ee=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="idea-diagnose"||$,$e=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="idea-research",ye=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="generate-epic",He=ce||Ee;if($e&&!ve||ye&&!ge)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"||I&&f.data.metadata.mode==="tech-debt"&&f.data.metadata.resolvedTrigger==="tech-debt",Ce=f.data.metadata.mode==="step"&&(f.data.metadata.resolvedTrigger==="arch-prd"||f.data.metadata.resolvedTrigger==="arch-architecture"||f.data.metadata.resolvedTrigger==="arch-fitness-functions"||f.data.metadata.resolvedTrigger==="arch-api-contracts"||f.data.metadata.resolvedTrigger==="arch-api-integrations"||f.data.metadata.resolvedTrigger==="arch-database"||f.data.metadata.resolvedTrigger==="arch-security"||f.data.metadata.resolvedTrigger==="arch-design-system"||f.data.metadata.resolvedTrigger==="arch-performance"||f.data.metadata.resolvedTrigger==="arch-testing"||f.data.metadata.resolvedTrigger==="arch-infrastructure"||f.data.metadata.resolvedTrigger==="arch-review"||f.data.metadata.resolvedTrigger==="update-memory")?f.data.metadata.resolvedTrigger:void 0,yt=Ce!==void 0,Pn=Ce==="arch-prd"?"arch-prd-docs-v1":Ce==="update-memory"?"arch-memory-canonical-v1":Ce==="arch-review"?"arch-review-doc-v1":Ce==="arch-infrastructure"?"arch-infrastructure-doc-v1":Ce==="arch-testing"?"arch-testing-doc-v1":Ce==="arch-performance"?"arch-performance-doc-v1":Ce==="arch-design-system"?"arch-design-system-doc-v1":Ce==="arch-security"?"arch-security-doc-v1":Ce==="arch-database"?"arch-database-doc-v1":Ce==="arch-api-integrations"?"arch-api-integrations-doc-v1":Ce==="arch-api-contracts"?"arch-api-contracts-docs-v1":Ce==="arch-fitness-functions"?"arch-fitness-tools-v1":"arch-architecture-doc-v1",ot=f.data.metadata.mode==="step"&&f.data.metadata.resolvedTrigger==="generate-pacts",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",kn=I?"tech-debt":f.data.metadata.resolvedTrigger==="chaos-plan"?"chaos-plan":"sync-openapi",mr=I?"tech-debt-registry-v1":kn==="chaos-plan"?"chaos-quarterly-v1":"sync-openapi-contract-v1",Ye=N.archPlan?.execution,cn=Ye?.targetEpicId,sn=Ye?.graphRevision;if(yt&&(Ye?.currentStageCommand!==Ce||typeof cn!="string"||!/^P[1-9][0-9]{0,11}$/.test(cn)||typeof sn!="string"||!/^[a-f0-9]{64}$/.test(sn)))throw new Error("private-execution-architecture-admission-unverified");if(ot&&(!Ie||!fe||!ae||Ye?.currentStageCommand!=="generate-pacts"||Ye.continuationState!=="delegate"||Ye.targetEpicId!==Ie.targetEpicId||Ye.graphRevision!==Ie.graphRevision||!v(Ye.pactAnswerReceipt,ae.receipt)))throw new Error("private-execution-pact-admission-unverified");if(It&&(!Z||!Ve||Ye?.currentStageCommand!=="arch-ux-design"||Ye.continuationState!=="delegate"||Ye.targetEpicId!==Z.targetEpicId||Ye.graphRevision!==Z.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 yr;if(ot){const{planPactToolchainManifest:ie,preparePactToolchainCandidate:le}=await import("../private-execution/pact-toolchain.js");try{ie(s,ae.answers.generateProvider),yr=le(s,ae.answers.generateProvider)}catch(F){if(F.message!=="pact-toolchain-manifest-unsupported")throw F}}let At,se,On;const re=f.data.metadata.gitLifecycleGraphAuthority,bt=f.data.metadata.privateExecutionRootAction;let Ze;if(U){if(!re||typeof re.storyId!="string"||typeof re.graphRevision!="string"||typeof re.executionBranch!="string")throw new Error("private-execution-graph-unavailable");if(Ze=re.storyId,bt?.action==="prepare-epic-checkout"){const{parsePrivateExecutionDescriptor:b}=await import("../private-execution/delivery.js"),{prepareDirectYoloSetup:Oe}=await import("../git/direct-yolo-checkpoint.js"),{acceptDirectYoloSetupCheckpoint:St}=await import("../git/direct-yolo-checkpoint.js"),{capturePrivateYoloCleanHead:Ge,recordPrivateYoloCleanBaseline:we}=await import("../private-execution/clean-baseline.js"),Ae=b(f.data.metadata.privateExecution,{projectId:Te,commandId:"yolo",stepId:f.data.metadata.stepId,graphRevision:re.graphRevision,inputSha256:r.sha256,hostKind:"codex-cli",hostVersion:Q.hostVersion}),ct=await G.client.getToken();if(!ct)throw new Error("private-execution-auth-unavailable");if(!await As(P,{leaseId:Ae.leaseId,...Ae.binding},ct))throw new Error("private-execution-setup-lease-cancel-unverified");const Mt=Ge(s),dn=await Oe({projectRoot:s,storyId:bt.storyId});if(!dn.ok)throw new Error("private-execution-root-setup-denied");await we(s,dn.value,Mt);const{ensurePrivateYoloIsolatedSession:xt}=await import("../private-execution/isolated-session.js");await xt(s,bt.storyId,re.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}`);ee={schemaVersion:1,outcome:"setup-accepted",executorOutcome:"not-run-root-only",setup:Tt.value,publicSafe:!0};const Nn=In(f.data.instructions,{...f.data.metadata,...f.compatibility?{compatibility:f.compatibility}:{}});return l.complete(nn),{success:!0,instructions:`# Setup do branch validado
|
|
100
102
|
|
|
101
|
-
O root confirmou o checkpoint C01 no branch do \xE9pico. Reexecute o mesmo YOLO para avan\xE7ar \xE0 pr\xF3xima etapa.`,metadata:{...Nn.metadata,privateExecutionReceipt:
|
|
103
|
+
O root confirmou o checkpoint C01 no branch do \xE9pico. Reexecute o mesmo YOLO para avan\xE7ar \xE0 pr\xF3xima etapa.`,metadata:{...Nn.metadata,privateExecutionReceipt:ee},exitCode:0}}let ie;try{ie=Be("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:s,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{throw new Error("private-execution-execution-branch-mismatch")}if(ie!==re.executionBranch)throw new Error("private-execution-execution-branch-mismatch");const le=mn(s,{required:!0}),F=typeof re.epicId=="string"?le.epics[re.epicId]:void 0,M=g(F?.branch_lease)?F.branch_lease:void 0;if(!F||F.graph_revision!==re.graphRevision||!M||M.ownerStoryId!==re.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"||te||Ee||$e||ye||Xe||yt||ot||It||Et){if(!He&&!$e&&!ye&&!Xe&&!te&&!yt&&!ot&&!It&&!Et&&typeof f.data.metadata.storyId!="string")throw new Error("private-execution-descriptor-unavailable")}else throw new Error("private-execution-descriptor-unavailable");if(U){const{ensurePrivateYoloIsolatedSession:ie,reconcilePrivateYoloIsolatedSession:le}=await import("../private-execution/isolated-session.js");if(bt?.action==="checkpoint-epic-story")await le(s,Ze,re.graphRevision);else{const F=await ie(s,Ze,re.graphRevision,e.privateExecutionWorkspaceParent),M=await y(F.workspace.workspacePath);if(M.hostVersion!==Q.hostVersion)throw new Error("private-codex-version-drift");Q=M}}if(Date.now()-Q.observedAtMs>2e4){const ie=await y(Q.projectRoot);if(ie.hostVersion!==Q.hostVersion)throw new Error("private-codex-version-drift");Q=ie}const Ir=await G.client.getToken();if(!Ir)throw new Error("private-execution-auth-unavailable");const We=He?f.data.metadata.epicClaim:void 0;if(He&&(!We||typeof We.claimId!="string"||typeof We.epicId!="string"))throw new Error("private-execution-descriptor-unavailable");if(He){if(!Pe)throw new Error("private-execution-epic-claim-admission-unverified");l.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>ti(s,Pe.fingerprint,We.claimId,We.epicId,$?"root-staged-v1":void 0),()=>{}),fr=!0;const{preparePrivateYoloIsolatedWorkspace:ie,PRIVATE_EPIC_PENDING_SIDECAR:le}=await import("../private-execution/isolated-workspace.js"),F=e.privateExecutionWorkspaceParent??J(Kt(),".local","share","neocortex","private-epic-workspaces");e.privateExecutionWorkspaceParent||qt(F,{recursive:!0,mode:448}),At=ie(s,F,!0),On=Ne("sha256").update(Fe(J(s,le))).digest("hex");const M=await y(At.workspacePath);if(M.hostVersion!==Q.hostVersion)throw new Error("private-codex-version-drift");Q=M}else if(!U&&!te){const{preparePrivateYoloIsolatedWorkspace:ie}=await import("../private-execution/isolated-workspace.js"),le=e.privateExecutionWorkspaceParent??J(Kt(),".local","share","neocortex","private-step-workspaces");if(e.privateExecutionWorkspaceParent||qt(le,{recursive:!0,mode:448}),se=ie(s,le,$e||ye),Xe||yt||ot||It||Et){if(!ue)throw new Error("private-execution-project-snapshot-unverified");const{assertPrivateProjectStepBaseline:M}=await import("../private-execution/isolated-workspace.js");M(se,ue)}const F=await y(se.workspacePath);if(F.hostVersion!==Q.hostVersion)throw new Error("private-codex-version-drift");Q=F}const at=await c(f.data.metadata.privateExecution,{projectId:Te,commandId:U?"yolo":ce?"create-epic":yt?Ce:ot?"generate-pacts":It?"arch-ux-design":Et?"property-test":Xe?kn:f.data.metadata.mode==="pipeline"?"exec":f.data.metadata.resolvedTrigger,stepId:f.data.metadata.stepId,...U?{graphRevision:re.graphRevision}:{...He?{claimId:We.claimId,epicId:We.epicId,...Ee?{writeSetId:"idea-diagnosis-v1"}:{}}:$e?{claimId:ve.claimId,epicId:ve.epicId,diagnosisReceiptId:ve.diagnosisReceiptId,intakeRevision:ve.intakeRevision,physicalAcceptanceReceiptId:ve.physicalAcceptanceReceiptId,writeSetId:"idea-research-v1"}:ye?{claimId:ge.claimId,epicId:ge.epicId,diagnosisReceiptId:ge.diagnosisReceiptId,researchReceiptId:ge.researchReceiptId,intakeRevision:ge.intakeRevision,physicalAcceptanceReceiptId:ge.physicalAcceptanceReceiptId,writeSetId:"generate-epic-v1"}:Xe?{writeSetId:mr}:te?{format:a.selection.uiUxReview?.json===!0?"json":"markdown"}:yt?{targetEpicId:cn,graphRevision:sn,writeSetId:Pn}:ot?{targetEpicId:Ie.targetEpicId,graphRevision:Ie.graphRevision,answersSha256:Ie.answersSha256,specSha256:Ie.specSha256,pathsSha256:Ie.pathsSha256,endpointCount:Ie.endpointCount,pathCount:Ie.pathCount}:It?{targetEpicId:Z.targetEpicId,graphRevision:Z.graphRevision,adapterId:Z.adapterId,authoritySha256:Z.authoritySha256,pathsSha256:Z.pathsSha256,screenCount:Z.screenCount,pathCount:Z.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(N)},inputSha256:r.sha256,hostKind:"codex-cli",hostVersion:Q.hostVersion},ie=>ws(P,{...ie},Ir));if(te){const{parsePrivateExecutionDescriptor:ie}=await import("../private-execution/delivery.js"),le=ie(f.data.metadata.privateExecution);if(le.schemaVersion!==11||le.binding.commandId!=="ui-ux-review"||le.binding.format!==(a.selection.uiUxReview?.json===!0?"json":"markdown"))throw new Error("private-execution-report-binding-unverified");const{storePrivateUiUxReviewReport:F}=await import("../private-execution/private-report-store.js");ee={schemaVersion:1,outcome:"report-stored",report:await F({projectRoot:s,material:at,format:le.binding.format,sha256:le.materialSha256}),publicSafe:!0}}else if(bt?.action==="checkpoint-epic-story"){const{runPrivateYoloRootCheckpoint:ie}=await import("../private-execution/root-checkpoint.js");ee={...await ie(s,bt)}}else{const ie=Ee?`${at}
|
|
102
104
|
|
|
103
105
|
Private P01 handoff (local only):
|
|
104
106
|
The durable reserved epic ID is ${We.epicId}. Complete only the diagnosis for this exact ID. Write exactly .neocortex/planning/epic-${We.epicId}/idea.json, diagnosis.md, enriched-prompt.md and the matching entry in .neocortex/planning/planning.json. Do not write state.json, Git controls, another epic, or P02/P03 artifacts; do not auto-continue to the next step. The root will independently review and persist the accepted planning checkpoint.
|
|
@@ -106,38 +108,38 @@ The durable reserved epic ID is ${We.epicId}. Complete only the diagnosis for th
|
|
|
106
108
|
|
|
107
109
|
Private P02 handoff (local only):
|
|
108
110
|
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.
|
|
109
|
-
`:
|
|
111
|
+
`:ye?`${at}
|
|
110
112
|
|
|
111
113
|
Private P03 handoff (local only):
|
|
112
|
-
The admitted epic is ${
|
|
113
|
-
`:yt?(await import("../private-execution/isolated-admission.js")).appendPrivateArchitectureHandoff(at,Ce,Pn,Sr(
|
|
114
|
+
The admitted epic is ${ge.epicId}. Generate exactly docs/epics/epic-${ge.epicId}.md, 1 to 24 contiguous docs/stories/${ge.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.
|
|
115
|
+
`:yt?(await import("../private-execution/isolated-admission.js")).appendPrivateArchitectureHandoff(at,Ce,Pn,Sr(N.archPlan?.execution?.nonUiScopeReceipt)?"non-ui":"all"):ot?`${at}
|
|
114
116
|
|
|
115
117
|
Private A03.5 handoff (local only):
|
|
116
|
-
${JSON.stringify({consumer:ae.answers.consumer,provider:ae.answers.provider,matchersAggressive:ae.answers.matchersAggressive,generateProvider:ae.answers.generateProvider,brokerConfigured:ae.answers.brokerUrl!==null,allowedPaths:
|
|
118
|
+
${JSON.stringify({consumer:ae.answers.consumer,provider:ae.answers.provider,matchersAggressive:ae.answers.matchersAggressive,generateProvider:ae.answers.generateProvider,brokerConfigured:ae.answers.brokerUrl!==null,allowedPaths:fe.paths})}
|
|
117
119
|
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.
|
|
118
|
-
`:
|
|
120
|
+
`:It?`${at}
|
|
119
121
|
|
|
120
122
|
Private A08 handoff (local only):
|
|
121
|
-
${JSON.stringify({targetEpicId:
|
|
123
|
+
${JSON.stringify({targetEpicId:Z.targetEpicId,graphRevision:Z.graphRevision,adapterId:Z.adapterId,approvedScreens:Ve.screens,allowedPaths:Ve.paths})}
|
|
122
124
|
Write only the approved paths. Keep synthetic fixtures and the canonical approved-story manifest. No Git, graph, QA or configuration effects.
|
|
123
|
-
`:
|
|
125
|
+
`:Et?`${at}
|
|
124
126
|
|
|
125
127
|
Private property-test handoff (local only):
|
|
126
|
-
${JSON.stringify({language:ze.language,numRuns:ze.numRuns,aggregates:ze.aggregates.map(
|
|
128
|
+
${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}))})}
|
|
127
129
|
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.
|
|
128
|
-
`:at;let le=
|
|
130
|
+
`:at;let le=ie;if(U){const{readPrivateYoloFrozenWriteSet:M}=await import("../private-execution/clean-baseline.js"),{appendPrivateYoloFrozenHandoff:b}=await import("../private-execution/frozen-handoff.js"),Oe=await M(s,Ze,re.executionBranch,re.graphRevision);le=b(ie,Oe);const{resumePrivateYoloIsolatedSession:St}=await import("../private-execution/isolated-session.js"),Ge=await St(s,Ze,re.graphRevision),we=_n(s,{epicAware:!0}).stories[Ze],Ae=N.stories[Ze];if(!we||!Ae||we.status!==Ae.status||JSON.stringify(we.steps_completed)!==JSON.stringify(Ae.steps_completed))throw new Error("private-execution-phase-snapshot-drift");const ct=Be("git",["rev-parse","HEAD"],{cwd:s,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();le+=`
|
|
129
131
|
Root physical dispatch observations (data, not phase completion):
|
|
130
|
-
`+JSON.stringify({storyId:Ze,graphRevision:
|
|
132
|
+
`+JSON.stringify({storyId:Ze,graphRevision:re.graphRevision,sourceHeadSha:ct,privateSnapshotSha:Ge.snapshotSha,effectiveStatus:we.status,hostKind:"codex-cli",hostVersion:Q.hostVersion})+`
|
|
131
133
|
Use these observed revisions and runtime facts; do not infer Git metadata or substitute an invented revision.
|
|
132
|
-
`}const
|
|
134
|
+
`}const F=await w(le,Q,{requireWorkspaceEffect:!0,...e.onPrivateExecutionWorkspaceFailure===void 0?{}:{onWorkspaceEffectFailure:e.onPrivateExecutionWorkspaceFailure},...e.privateExecutionModel===void 0?{}:{model:e.privateExecutionModel},...U?{expectedExecutionBranch:re.executionBranch}:At?{expectedExecutionBranch:At.executionBranch}:se?{expectedExecutionBranch:se.executionBranch}:{}});if(U){const{admitPrivateYoloIsolatedSessionStep:M}=await import("../private-execution/isolated-session.js"),b=await M(s,Ze,re.graphRevision);let Oe;if(f.data.metadata.stepId===oo){const Ge=f.data.metadata.mutationQaFeature;if(!Ge)throw new Error("private-execution-mutation-qa-authority-unavailable");if(!Ge.enabled)Oe={schemaVersion:1,status:"skipped-server-authority",publicSafe:!0};else{let we,Ae;try{const ct=b.session.workspace.workspacePath,Mt=`sha:${b.session.workspace.baseSha}`,{planMutationQa:dn}=await import("./mutation-qa.js"),xt=dn(ct,Mt);if(xt.headSha!==b.session.snapshotSha)throw new Error("private-execution-mutation-qa-snapshot-drift");let Tt="not-run";if(xt.outcome==="ready"){const{runAndRecordMutationQa:Ln}=await import("./mutation-qa-checkpoint.js");if(Tt=Ln(ct,Mt,xt.planSha256).result.outcome,Tt==="skipped-host-isolation-unavailable")throw new Error("private-execution-mutation-qa-host-isolation-unavailable")}const{classifyMutationQaGate:Nn}=await import("./mutation-qa-gate.js");if(we=Nn(ct,Mt,xt.planSha256),we.followUpDebtRequired){const{recordMutationQaFollowUpDebt:Ln}=await import("./mutation-qa-checkpoint.js");Ae=Ln(ct,Mt,xt.planSha256,we.status,Tt,s)}const{resumePrivateYoloIsolatedSession:zi}=await import("../private-execution/isolated-session.js");if((await zi(s,Ze,re.graphRevision)).snapshotSha!==b.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:b.admission.outcome,sequence:b.session.sequence,snapshotSha:b.session.snapshotSha,patchSha256:b.admission.patchSha256,changedPathCount:b.admission.changedPaths.length};ee={...F,isolation:St,...Oe?{mutationQa:Oe}:{}}}else if(At){const{admitPrivateEpicClaimWorkspace:M,admitPrivateIdeaDiagnosisWorkspace:b}=await import("../private-execution/isolated-admission.js"),Oe=Ee?b(At,We.claimId,We.epicId,Pe.fingerprint,On,a.selection.positionals.join(" ").replace(/^[-:–—]\s+/,"")):M(At,We.claimId,We.epicId,Pe.fingerprint,On);ee={...F,isolation:{schemaVersion:1,outcome:Oe.outcome,baseSha:Oe.baseSha,patchSha256:Oe.patchSha256,changedPathCount:Oe.changedPaths.length}}}else if(se&&$e){const{admitPrivateIdeaResearchWorkspace:M}=await import("../private-execution/isolated-admission.js"),b=M(se,ve.claimId,ve.epicId,ve.diagnosisReceiptId,ve.intakeRevision,ve.sourceStateSha256);ee={...F,isolation:{schemaVersion:1,outcome:b.outcome,baseSha:b.baseSha,patchSha256:b.patchSha256,changedPathCount:b.changedPaths.length}}}else if(se&&ye){const{admitPrivateGenerateEpicWorkspace:M}=await import("../private-execution/isolated-admission.js"),b=M(se,ge.claimId,ge.epicId,ge.diagnosisReceiptId,ge.researchReceiptId,ge.intakeRevision,ge.sourceStateSha256);ee={...F,isolation:{schemaVersion:1,outcome:b.outcome,baseSha:b.baseSha,patchSha256:b.patchSha256,changedPathCount:b.changedPaths.length}}}else if(se&&ot){const{admitPrivatePactWorkspace:M}=await import("../private-execution/isolated-admission.js"),{inspectPactToolchain:b}=await import("../private-execution/pact-toolchain.js"),{verifyPactConsumerRuntime:Oe}=await import("../private-execution/pact-consumer-runtime.js"),St=ae.answers.generateProvider,Ge=M(se,Ie.targetEpicId,Ie.graphRevision,ae.receipt,fe,yr),we=b(s,St),Ae=Oe(s,fe,St);ee={...F,isolation:{schemaVersion:1,outcome:Ge.outcome,baseSha:Ge.baseSha,patchSha256:Ge.patchSha256,changedPathCount:Ge.changedPaths.length,consumerBindingCandidateCount:Ge.consumerBindingCandidateCount,consumerScaffoldCount:Ge.consumerScaffoldCount,toolchain:we,consumerRuntime:Ae}}}else if(se&&It){const{admitPrivateUxWorkspace:M}=await import("../private-execution/isolated-admission.js"),b=M(se,Z.targetEpicId,Z.graphRevision,Ve);ee={...F,isolation:{schemaVersion:1,outcome:b.outcome,baseSha:b.baseSha,patchSha256:b.patchSha256,changedPathCount:b.changedPaths.length}}}else if(se&&Et){const{admitPrivatePropertyTestWorkspace:M}=await import("../private-execution/isolated-admission.js"),b=M(se,mt,ze);ee={...F,isolation:{schemaVersion:1,outcome:b.outcome,baseSha:b.baseSha,patchSha256:b.patchSha256,changedPathCount:b.changedPaths.length,checkpointAccepted:!1,qaAccepted:!1,rootNextAction:"property-semantic-review-required"}}}else if(se&&yt){const{admitPrivateArchitectureStageWorkspace:M}=await import("../private-execution/isolated-admission.js"),b=M(se,Ce,Pn,cn,sn);ee={...F,isolation:{schemaVersion:1,outcome:b.outcome,baseSha:b.baseSha,patchSha256:b.patchSha256,changedPathCount:b.changedPaths.length}}}else if(se&&Xe){const{admitPrivateProjectStepWorkspace:M}=await import("../private-execution/isolated-admission.js"),b=M(se,kn,mr);ee={...F,isolation:{schemaVersion:1,outcome:b.outcome,baseSha:b.baseSha,patchSha256:b.patchSha256,changedPathCount:b.changedPaths.length}}}else if(se){const{admitPrivateStateBoundStepWorkspace:M}=await import("../private-execution/isolated-admission.js"),b=M(se,f.data.metadata.storyId);ee={...F,isolation:{schemaVersion:1,outcome:b.outcome,baseSha:b.baseSha,patchSha256:b.patchSha256,changedPathCount:b.changedPaths.length}}}else ee={...F}}}catch(c){const p=c instanceof Error&&/^(private-execution|private-codex)-[a-z-]+$/.test(c.message)?c.message:"private-execution-unverified";return{success:!1,error:p,errorCode:p,exitCode:1}}let Tn;if(rn&&g(f.data.metadata.planningRootContinuation)&&f.data.metadata.planningRootContinuation.planningComplete===!0)try{if(!Re?.claimId||!Re.epicId||!Te)throw new Error("missing-reservation");const c=wr(s,Re.claimId,Re.epicId);if(f.data.metadata.planningRootContinuation.memoryReceiptId!==c.receiptId)throw new Error("memory-receipt-conflict");const p=_n(s,{verifyPlanningGeneration:!0}),y=p.epics[Re.epicId];if(!g(y?.createEpicPlanningMemoryPhysical)||y.createEpicPlanningMemoryPhysical.receiptId!==c.receiptId)throw new Error("memory-recheck-failed");const w={config:{project_id:Te},epics:{[Re.epicId]:y},stories:Object.fromEntries((Array.isArray(y.stories)?y.stories:[]).map(te=>[te,p.stories[te]])),epic_id_ledger:p.epic_id_ledger};if(!await l.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Mi(P,G.token,{claimId:Re.claimId,projectId:Te,epicId:Re.epicId,status:"materialized",planningCheckpoint:{memoryReceiptId:c.receiptId,snapshot:w}},{refreshToken:()=>G.client.forceRefresh()}),async()=>!1))throw new Error("acknowledgement-unavailable");Tn={schemaVersion:1,acknowledged:!0,claimId:c.claimId,epicId:c.epicId,memoryReceiptId:c.receiptId,publicSafe:!0}}catch{return{success:!1,error:"planning-root-materialization-unavailable",errorCode:"planning-root-materialization-unavailable",exitCode:1}}const an=In(f.data.instructions,{...f.data.metadata,...f.compatibility?{compatibility:f.compatibility}:{}}),Dt=ee?.isolation,qi=an.metadata?.resolvedTrigger==="property-test"&&Dt!==null&&typeof Dt=="object"&&!Array.isArray(Dt)&&Dt.outcome==="admitted-unverified"&&Dt.checkpointAccepted===!1&&Dt.rootNextAction==="property-semantic-review-required";if(Pe&&!fr&&!rn&&f.data.metadata?.mode!=="error")try{const c=f.data.metadata?.epicClaim;if(!c||typeof c!="object"||Array.isArray(c))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const p=c;if(p.outcome!=="reserved"||typeof p.claimId!="string"||typeof p.epicId!="string")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");l.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>ti(s,Pe.fingerprint,p.claimId,p.epicId),()=>{})}catch{}return l.complete(nn),{success:!0,instructions:ee?ee.outcome==="checkpoint-validated"?`# Checkpoint da story validado
|
|
133
135
|
|
|
134
|
-
O root registrou o commit e a valida\xE7\xE3o f\xEDsica no branch do epic.`:
|
|
136
|
+
O root registrou o commit e a valida\xE7\xE3o f\xEDsica no branch do epic.`:ee.outcome==="setup-accepted"?`# Setup do branch validado
|
|
135
137
|
|
|
136
|
-
O root confirmou o checkpoint C01 no branch do \xE9pico. Reexecute o mesmo YOLO para avan\xE7ar \xE0 pr\xF3xima etapa.`:
|
|
138
|
+
O root confirmou o checkpoint C01 no branch do \xE9pico. Reexecute o mesmo YOLO para avan\xE7ar \xE0 pr\xF3xima etapa.`:ee.outcome==="report-stored"?`# Relat\xF3rio privado salvo
|
|
137
139
|
|
|
138
|
-
Consulte o caminho local em metadata.privateExecutionReceipt.report.path. Nenhum agente foi executado ou projeto alterado.`:
|
|
140
|
+
Consulte o caminho local em metadata.privateExecutionReceipt.report.path. Nenhum agente foi executado ou projeto alterado.`:qi?"# 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
|
|
139
141
|
|
|
140
|
-
O executor Codex retornou sem erro. Nenhum checkpoint ou aprova\xE7\xE3o da story foi emitido.`:an.instructions,metadata:
|
|
142
|
+
O executor Codex retornou sem erro. Nenhum checkpoint ou aprova\xE7\xE3o da story foi emitido.`:an.instructions,metadata:ee?{...an.metadata,privateExecutionReceipt:ee}:{...an.metadata,...Tn?{planningMaterialization:Tn}:{}},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":hn(t):null}const Gi="Provide exactly one invoke input source: --args <string>, --stdin, or --args-file <path>.",Us=`
|
|
141
143
|
neocortex-client invoke - Send orchestration request to server
|
|
142
144
|
|
|
143
145
|
Usage:
|
|
@@ -208,12 +210,12 @@ Safety:
|
|
|
208
210
|
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.
|
|
209
211
|
Jobs, goal and loop watch use serverHeldStream=false and foreground local SQLite polling of public processing summaries only.
|
|
210
212
|
Unresolved targets disable polling with public reason codes; there is no all-jobs fallback.
|
|
211
|
-
`.trim();function
|
|
212
|
-
`);return}
|
|
213
|
-
`);return}const
|
|
214
|
-
`),n
|
|
215
|
-
`)}async function
|
|
216
|
-
`),0;let t;try{t=
|
|
217
|
-
`),1;throw
|
|
218
|
-
`),1):(await
|
|
219
|
-
`),
|
|
213
|
+
`.trim();function $s(e){return e.includes("--help")||e.includes("-h")||e.includes("help")}function je(e,t,o,n){return new En("INVOCATION_MALFORMED_INPUT",t,e,o,n)}function Ot(e){return je("missing-input-value",`${e} requires a value. ${Gi}`)}function Hs(e){try{if(!Zi(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 En?t:je("missing-input-value","--args-file could not be read as UTF-8 text. Check the path and permissions.","args-file")}}function Ws(){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 En?e:je("missing-input-value","--stdin could not be read as UTF-8 text. Pipe command text into stdin and retry.","stdin")}}function Gs(e,t={}){let o,n=!1,i,r,a="plain",d=!1,s,u,m=!1,I=!1,h;for(let k=0;k<e.length;k++){const O=e[k];switch(O){case"--args":{const C=e[++k];if(C===void 0)throw Ot("--args");if(o!==void 0)throw je("multiple-input-sources","Provide --args only once. Use one explicit invoke input source.","args");o=C;break}case"--stdin":if(n)throw je("multiple-input-sources","Provide --stdin only once. Use one explicit invoke input source.","stdin");n=!0;break;case"--args-file":{const C=e[++k];if(C===void 0)throw Ot("--args-file");if(i!==void 0)throw je("multiple-input-sources","Provide --args-file only once. Use one explicit invoke input source.","args-file");i=C;break}case"--project-root":{const C=e[++k];if(C===void 0)throw Ot("--project-root");r=C;break}case"--format":{const C=e[++k];if(C===void 0)throw Ot("--format");if(C!=="json"&&C!=="plain")throw je("unexpected-cli-token","--format accepts only json or plain.");a=C;break}case"--watch":d=!0;break;case"--server-url":{const C=e[++k];if(C===void 0)throw Ot("--server-url");s=C;break}case"--platform-target":{const C=e[++k];if(C===void 0)throw Ot("--platform-target");u=C;break}case"--strict-read-only":m=!0;break;case"--private-execution-beta":I=!0;break;case"--private-execution-model":{const C=e[++k];if(C===void 0)throw Ot("--private-execution-model");if(h!==void 0||!/^gpt-[a-z0-9][a-z0-9.-]{0,63}$/.test(C))throw je("unexpected-cli-token","Invalid or duplicate private execution model.");h=C;break}default:if(o!==void 0&&O&&(!O.startsWith("-")||O==="-")){o+=` ${O}`;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(h!==void 0&&(!I||m))throw je("unexpected-cli-token","A private execution model requires private beta without strict read-only.");const E=[o!==void 0?"args":void 0,n?"stdin":void 0,i!==void 0?"args-file":void 0].filter(k=>k!==void 0);if(E.length===0)throw je("missing-input-value",Gi);if(E.length>1)throw je("multiple-input-sources",`Choose only one invoke input source; received ${E.join(", ")}.`);const _=E[0],S=_==="args"?o:_==="stdin"?(t.readStdin??Ws)():(t.readArgsFile??Hs)(i);let l;try{l=Qt(_,S)}catch(k){throw k instanceof Qo?je("invalid-utf8",k.message,_):k}const A=_==="args"?hs(l.rawArgs):Me(l.rawArgs),j=A.args===l.rawArgs?l:Qt(_,A.args);return{args:A.args,inputSource:_,inputEnvelope:j,projectRoot:r,format:a,watch:d||A.watch,commandLevelWatch:A.metadata,serverUrl:s,platformTarget:u,strictReadOnly:m,privateExecutionBeta:I,...h===void 0?{}:{privateExecutionModel:h}}}function Fi(e,t){return t?.active?{...e??{},commandLevelWatch:t,serverHeldStream:!1}:e}function Yi(e,t,o=process.stdout,n=process.stderr){if(t.format==="json"){const a=In(e.instructions,e.metadata),d=Fi(a.metadata,t.commandLevelWatch);if(t.watch){o.write(JSON.stringify({type:"invoke_result",instructions:a.instructions,metadata:d,publicSafe:!0})+`
|
|
214
|
+
`);return}o.write(JSON.stringify({instructions:a.instructions,metadata:d})+`
|
|
215
|
+
`);return}const i=In(e.instructions,e.metadata),r=Fi(i.metadata,t.commandLevelWatch);o.write(i.instructions+`
|
|
216
|
+
`),r&&n.write(JSON.stringify(r)+`
|
|
217
|
+
`)}async function tp(e=process.stdout,t=process.stderr){const o=i=>new Promise(r=>{let a=!1;const d=m=>{a||(a=!0,clearTimeout(u),setImmediate(()=>i.removeListener("error",s)),r(m))},s=()=>d(!1),u=setTimeout(()=>d(!1),1e4);i.once("error",s);try{i.write("",m=>d(!m))}catch{d(!1)}});return(await Promise.all([o(e),o(t)])).every(Boolean)}function Fs(e){const t=()=>e.abort();return process.once("SIGINT",t),process.once("SIGTERM",t),()=>{process.removeListener("SIGINT",t),process.removeListener("SIGTERM",t)}}async function np(e){if($s(e))return process.stdout.write(`${Us}
|
|
218
|
+
`),0;let t;try{t=Gs(e)}catch(n){if(n instanceof En)return process.stderr.write(JSON.stringify({error_code:n.code,reason:n.reason,source:n.source,byte_length:n.byteLength,message:n.message,remediation:n.message})+`
|
|
219
|
+
`),1;throw n}if(Oo(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."})+`
|
|
220
|
+
`),1):(await No({args:t.args,projectRoot:Yn(t.projectRoot),format:t.format,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})).exitCode;const o=await Vs({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(!o.success&&o.errorCode==="YOLOOP_RELEASE_BLOCKED"&&o.instructions&&o.metadata)return Yi(o,t),o.exitCode;if(!o.success){const n=o.metadata?.invocationInput,i=qa(o.metadata?.yoloChangeEvidence),r=n&&typeof n=="object"&&!Array.isArray(n)?n:void 0;return process.stderr.write(JSON.stringify({error_code:o.errorCode??(o.exitCode===2?"NOT_CONFIGURED":"INVOKE_ERROR"),message:Je(o.error??"",kt),...typeof r?.reason=="string"?{reason:Je(r.reason,80)}:{},...typeof r?.source=="string"?{source:Je(r.source,20)}:{},...Number.isSafeInteger(r?.byteLength)?{byte_length:r.byteLength}:{},...typeof r?.remediation=="string"?{remediation:Je(r.remediation,kt)}:{},...i?{yolo_change_evidence:i}:{}})+`
|
|
221
|
+
`),o.exitCode}if(Yi(o,t),t.watch){const n=new AbortController,i=Fs(n);try{const r=Rs(o.metadata,t.args);r.disabled?ts(r.reasonCodes??[_e.TARGET_UNRESOLVED],t.args,t.format,process.stdout,t.privateExecutionBeta):await ns({projectRoot:Yn(t.projectRoot),format:t.format,strictReadOnly:t.strictReadOnly,protectedOutput:t.privateExecutionBeta,...r,signal:n.signal})}finally{i()}}return 0}export{Us as INVOKE_HELP_TEXT,Kr as INVOKE_PAYLOAD_LIMIT_BYTES,Gn as INVOKE_PAYLOAD_WARNING_THRESHOLD_BYTES,En as InvokeCliInputError,Jn as InvokePayloadTooLargeError,Kn as InvokeStructuralContextTooLargeError,Hi as STORY_WORKTREE_BARRIER_CLIENT_MAX_ATTEMPTS,$i as STORY_WORKTREE_BARRIER_CLIENT_MAX_WAIT_MS,lt as StateSnapshotIntegrityError,Zd as __resetSchemaDriftWarnedForTests,bs as acknowledgeMaterializedPendingEpicClaims,ni as admitClientInvocation,Zn as assertEpicAwareStateShapeBeforeRepair,_c as boundedP222PremergeCheckpointPositions,zn as buildInvokeCompatibilityOffer,Lc as buildSignedInvokeAttempt,ja as clearPendingEpicIdempotencyKey,wc as collectInvokeP205Authorities,_n as collectStateSnapshot,Wt as computeInvokeRequestBodySizeBytes,ep as createFullStateSnapshotScope,rr as createInvokePayloadTelemetry,Va as deriveYoloLogicalIdempotencyKey,Xa as detectStateSchemaDrift,Bs as extractPreFlightTrigger,tp as flushInvokeCliOutput,Ma as getOrCreatePendingEpicIdempotencyKey,ir as guardInvokeRequestBodySize,Vs as invoke,np as invokeCliHandler,Rc as invokeP205ProjectionReasonCode,mi as isEpicAwareCommandId,Ls as isStoryWorktreePhaseOneInvocation,Wc as maybeEmitInvokePayloadSizeWarning,Gc as maybeRunInvokeRunnerAutoBootstrap,Ic as observeStoryWorktreeReadiness,Gs as parseInvokeCliOptions,js as persistStoryWorktreePhaseEvidence,Ms as pollStoryWorktreeSpecBarrier,Ri as postMaterializationJson,Ua as projectRegistryDriftInvokeFailure,$a as projectReleaseBlockedInvokeResult,qa as projectYoloChangeEvidenceCliDiagnostic,Fr as publicYoloSpecEnvelopeErrorCode,ks as reconcileInvalidatedYoloopSession,ti as recordPendingEpicReservation,Ha as recoverClientInvocation,hs as resolveInvokeCommandLevelWatch,Yn as resolveInvokeProjectRoot,kc as resolveInvokeTransportErrorCode,Rs as resolveInvokeWatchTarget,dc as sanitizeBranchModeConversionReceipt,In as sanitizeInvokeCliOutput,Mi as sendEpicClaimAcknowledgement,ur as sendInvokeRequest,As as sendPrivateExecutionCancelRequest,ws as sendPrivateExecutionConsumeRequest,za as shouldCollectProjectEvidenceForInvoke,yc as storyWorktreeReadinessTargetEpic,ns as watchContinuityProcessingSummaries,Yi as writeInvokeCliSuccessOutput};
|