@ornexus/neocortex 4.66.53 → 4.66.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/release-source.json +1 -0
  2. package/dist/sbom.cdx.json +1190 -1190
  3. package/install.ps1 +1 -1
  4. package/install.sh +1 -1
  5. package/package.json +2 -2
  6. package/packages/client/dist/cli.js +2 -2
  7. package/packages/client/dist/commands/invoke.js +1 -1
  8. package/packages/client/dist/commands/story-worktree.d.ts +4 -1
  9. package/packages/client/dist/commands/story-worktree.js +4 -4
  10. package/packages/client/dist/git/epic-origin-rebind.d.ts +20 -0
  11. package/packages/client/dist/git/epic-origin-rebind.js +1 -0
  12. package/targets-stubs/antigravity/gemini.md +1 -1
  13. package/targets-stubs/antigravity/neocortex.md +1 -1
  14. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  15. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  16. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  17. package/targets-stubs/claude-code/neocortex-sentinel.md +1 -1
  18. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  19. package/targets-stubs/claude-code/neocortex.md +2 -2
  20. package/targets-stubs/codex/AGENTS.md +1 -1
  21. package/targets-stubs/codex/neocortex.toml +1 -1
  22. package/targets-stubs/cursor/agent.md +2 -2
  23. package/targets-stubs/deepseek-harness/SKILL.md +1 -1
  24. package/targets-stubs/gemini-cli/agent.md +2 -2
  25. package/targets-stubs/gemini-cli/agents/neocortex.md +2 -2
  26. package/targets-stubs/grok/SKILL.md +1 -1
  27. package/targets-stubs/kimi/neocortex.md +1 -1
  28. package/targets-stubs/openclaw/SKILL.md +1 -1
  29. package/targets-stubs/opencode/neocortex-root.md +2 -2
  30. package/targets-stubs/opencode/neocortex.md +2 -2
  31. package/targets-stubs/vscode/neocortex.agent.md +2 -2
package/install.ps1 CHANGED
@@ -19,7 +19,7 @@ param(
19
19
  [string]$ServerUrl = ('https://{0}.{1}.{2}' -f 'api','neocortex','sh')
20
20
  )
21
21
 
22
- $VERSION = "4.66.53"
22
+ $VERSION = "4.66.54"
23
23
 
24
24
  # =============================================================================
25
25
  # CONFIGURACOES
package/install.sh CHANGED
@@ -4,7 +4,7 @@
4
4
  # Development Orchestrator
5
5
 
6
6
  # Versao do instalador
7
- VERSION="4.66.53"
7
+ VERSION="4.66.54"
8
8
 
9
9
  # Flags
10
10
  MIGRATION_DETECTED=false
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ornexus/neocortex",
3
- "version": "4.66.53",
4
- "description": "Neocortex v4.66.53",
3
+ "version": "4.66.54",
4
+ "description": "Neocortex v4.66.54",
5
5
  "keywords": [
6
6
  "claude",
7
7
  "claude-code",
@@ -17,7 +17,7 @@ Commands:
17
17
  planning-qa record Record digest-bound QA evidence for an admitted P01-P03 checkpoint from stdin
18
18
  private-session <inspect-rejected|discard-rejected|renew-lease|accept-diagnosis|accept-research|accept-specification|accept-tasks|validate-implementation|accept-implementation|accept-refactor-advisory|accept-test-validation|accept-qa|accept-project-memory> Root recovery and phase validation
19
19
  story-checkpoint Root-owned direct-*yolo commit/checkpoint boundary
20
- story-worktree <create|adopt|sync|status|release> P225 temporary story worktree lifecycle (public-safe JSON)
20
+ story-worktree <create|adopt|sync|status|release|rebind-origin> P225 temporary story worktree lifecycle (public-safe JSON)
21
21
  legacy-story-branch Root-owned setup and C01 checkpoint for recorded story-branch projects
22
22
  legacy-story-pr Root-owned legacy C08/C09 checkpoint, C10 PR, C11 review and C12 merge boundary
23
23
  legacy-epic-terminal Physical C12 preflight and root QA acceptance; never releases quota
@@ -232,4 +232,4 @@ License:
232
232
  `);return}process.stderr.write(`[Neocortex] ${y.ARTIFACT_UNAVAILABLE}: registry reconciliation could not be completed safely; no invoke request was sent.
233
233
  `)}function v(){return{version:u,checksum:m}}function S(r){const a=k(r);return!a||a.version===u&&a.checksum===m}function A(r,a){const o=d(a,"--project-root")||process.cwd();try{if(process.env.NEOCORTEX_REGISTRY_REEXECUTED==="1"&&!S(o))throw new h(y.ARTIFACT_MISMATCH,"The reinstalled client still does not match the trusted local projection; no invoke request was sent.");if(f({projectRoot:o,installedVersion:p(),installedIdentity:v()}).status!=="updated")return;const t=b(process.execPath,[process.argv[1],...r],{stdio:"inherit",env:{...process.env,NEOCORTEX_REGISTRY_REEXECUTED:"1"},shell:!1});return t.error?1:t.status??1}catch(e){return x(e),1}}function R(r,a){const o=[...r],e=o.indexOf("--project-root");return e>=0?o[e+1]=a:o.push("--project-root",a),o}function P(r){const a=r instanceof Error&&/^project-root-[a-z-]+$/.test(r.message)?r.message:"project-root-resolution-failed";process.stderr.write(`[Neocortex] ${a}: project root could not be resolved safely; no invoke request was sent.
234
234
  `)}async function q(){const r=process.argv.slice(2),a=r[0];a&&C.has(a.toLowerCase())&&process.exit(0),(!a||a==="--help"||a==="-h")&&(console.log(g),process.exit(0)),(a==="--version"||a==="-v")&&(console.log(p()),process.stderr.write(`Licensed under BSL-1.1 (Business Source License 1.1)
235
- `),process.exit(0));const o=r.slice(1);switch(a){case"invoke":{const e=await import("./commands/invoke.js");let t;try{const l=typeof e.resolveInvokeCliProjectRoot=="function"?await e.resolveInvokeCliProjectRoot(d(o,"--project-root")):void 0;t=l?R(o,l):[...o]}catch(l){P(l),process.exitCode=1;break}const c=["invoke",...t],s=A(c,t);if(s!==void 0){process.exitCode=s;break}const{invokeCliHandler:n,flushInvokeCliOutput:i}=e,j=await n(t),w=await i();process.exitCode=w?j:1;break}case"reconcile-registry":{const e=d(o,"--project-root")||process.cwd();try{f({projectRoot:e,installedVersion:p(),installedIdentity:v(),checkLatest:o.includes("--check-latest")}),process.exitCode=0}catch(t){x(t),process.exitCode=1}break}case"activate":{const{activate:e}=await import("./commands/activate.js");let t,c,s=!1;for(let n=0;n<o.length;n++){const i=o[n];i==="--server-url"?c=o[++n]:i==="--non-interactive"?s=!0:i==="--help"||i==="-h"?(console.log(g),process.exit(0)):i.startsWith("-")||(t=i)}t||(console.error("Error: License key is required."),console.error("Usage: neocortex-client activate <license-key>"),console.error("Example: neocortex-client activate NX-PRO-ABC-123"),process.exit(1));try{const n=await e({licenseKey:t,serverUrl:c,nonInteractive:s});n.success?(console.log(n.message),process.exit(0)):(console.error(n.message),process.exit(1))}catch(n){const i=n instanceof Error?n.message:String(n);console.error(`Activation failed: ${i}`),process.exit(1)}break}case"cache-status":{console.log("Cache status requires an active client session."),console.log("Use this command within a running Neocortex client context."),process.exit(0);break}case"doctor":{const{doctorCliHandler:e}=await import("./commands/doctor.js"),t=await e(o);process.exit(t);break}case"auth-doctor":{const{authDoctorCliHandler:e}=await import("./commands/auth-doctor.js"),t=await e(o);process.exitCode=t;break}case"config":{const{configCliHandler:e}=await import("./commands/config.js"),t=await e(o);process.exit(t);break}case"refresh-memory":{const{refreshMemoryCliHandler:e}=await import("./commands/refresh-memory.js"),t=await e(o);process.exit(t);break}case"architecture-memory":{const{architectureMemoryTerminalCliHandler:e}=await import("./commands/architecture-memory-terminal.js"),t=await e(o);process.exit(t);break}case"planning-diagnosis":{const{planningDiagnosisCliHandler:e}=await import("./commands/planning-diagnosis.js"),t=await e(o);process.exit(t);break}case"planning-research":{const{planningResearchCliHandler:e}=await import("./commands/planning-research.js"),t=await e(o);process.exit(t);break}case"private-session":{const{privateSessionCliHandler:e}=await import("./commands/private-session.js"),t=await e(o);process.exit(t);break}case"planning-memory":{const{planningMemoryCliHandler:e}=await import("./commands/planning-memory.js"),t=await e(o);process.exit(t);break}case"planning-generation":{const{planningGenerationCliHandler:e}=await import("./commands/planning-generation.js"),t=await e(o);process.exit(t);break}case"planning-qa":{const{planningQaCliHandler:e}=await import("./commands/planning-qa.js"),t=await e(o);process.exit(t);break}case"story-checkpoint":{const{storyCheckpointCliHandler:e}=await import("./commands/story-checkpoint.js"),t=await e(o);process.exit(t);break}case"story-worktree":{const{storyWorktreeCliHandler:e}=await import("./commands/story-worktree.js"),t=await e(o);process.exit(t);break}case"legacy-story-branch":{const{legacyStoryBranchCliHandler:e}=await import("./commands/legacy-story-branch.js"),t=await e(o);process.exit(t);break}case"legacy-story-pr":{const{legacyStoryPrCliHandler:e}=await import("./commands/legacy-story-pr.js"),t=await e(o);process.exit(t);break}case"legacy-epic-terminal":{const{legacyEpicTerminalCliHandler:e}=await import("./commands/legacy-epic-terminal.js"),t=await e(o);process.exit(t);break}case"mutation-qa":{const{mutationQaCliHandler:e}=await import("./commands/mutation-qa.js"),t=await e(o);process.exit(t);break}case"property-qa":{const{propertyQaCliHandler:e}=await import("./commands/property-qa.js"),t=await e(o);process.exit(t);break}case"qa-synthetic-backend":{const{syntheticBackendCliHandler:e}=await import("./commands/qa-synthetic-backend.js");process.exitCode=await e(r.slice(1));break}case"qa-scan-review":{const{qaScanReviewCliHandler:e}=await import("./commands/qa-scan-review.js"),t=await e(o);process.exit(t);break}case"qa-root":{const{qaControlCliHandler:e}=await import("./commands/qa-control.js");process.exit(await e(o));break}case"refactor-root":{if(o[0]==="control"){const{refactorControlCliHandler:c}=await import("./commands/refactor-control.js");process.exit(await c(o))}if(o[0]==="characterize"){const{refactorCharacterizationCliHandler:c}=await import("./commands/refactor-characterization.js");process.exit(c(o))}if(o[0]==="review-accept"||o[0]==="review-status"){const{refactorReviewCliHandler:c}=await import("./commands/refactor-review.js");process.exit(await c(o))}if(o[0]?.startsWith("commit-")){const{refactorCommitCliHandler:c}=await import("./commands/refactor-commit.js");process.exit(c(o))}const{refactorRootCliHandler:e}=await import("./commands/refactor-root.js"),t=e(o);process.exit(t);break}case"native-agent":{const{nativeAgentCliHandler:e}=await import("./commands/native-agent.js"),t=await e(o);process.exit(t);break}case"architecture-answers":{const{architectureAnswersCliHandler:e}=await import("./commands/architecture-answers.js"),t=await e(o);process.exit(t);break}case"update":{console.log("To update Neocortex, run:"),console.log(" neocortex update"),console.log(""),console.log("Or manually:"),console.log(" npm install -g @ornexus/neocortex@latest"),process.exit(0);break}default:console.error(`Unknown command: ${a}`),console.error('Run "neocortex-client --help" for usage information.'),process.exit(1)}}q().catch(r=>{console.error(`Fatal error: ${r instanceof Error?r.message:String(r)}`),process.exit(1)});
235
+ `),process.exit(0));const o=r.slice(1);switch(a){case"invoke":{const e=await import("./commands/invoke.js");let t;try{const l=typeof e.resolveInvokeCliProjectRoot=="function"?await e.resolveInvokeCliProjectRoot(d(o,"--project-root")):void 0;t=l?R(o,l):[...o]}catch(l){P(l),process.exitCode=1;break}const i=["invoke",...t],s=A(i,t);if(s!==void 0){process.exitCode=s;break}const{invokeCliHandler:n,flushInvokeCliOutput:c}=e,j=await n(t),w=await c();process.exitCode=w?j:1;break}case"reconcile-registry":{const e=d(o,"--project-root")||process.cwd();try{f({projectRoot:e,installedVersion:p(),installedIdentity:v(),checkLatest:o.includes("--check-latest")}),process.exitCode=0}catch(t){x(t),process.exitCode=1}break}case"activate":{const{activate:e}=await import("./commands/activate.js");let t,i,s=!1;for(let n=0;n<o.length;n++){const c=o[n];c==="--server-url"?i=o[++n]:c==="--non-interactive"?s=!0:c==="--help"||c==="-h"?(console.log(g),process.exit(0)):c.startsWith("-")||(t=c)}t||(console.error("Error: License key is required."),console.error("Usage: neocortex-client activate <license-key>"),console.error("Example: neocortex-client activate NX-PRO-ABC-123"),process.exit(1));try{const n=await e({licenseKey:t,serverUrl:i,nonInteractive:s});n.success?(console.log(n.message),process.exit(0)):(console.error(n.message),process.exit(1))}catch(n){const c=n instanceof Error?n.message:String(n);console.error(`Activation failed: ${c}`),process.exit(1)}break}case"cache-status":{console.log("Cache status requires an active client session."),console.log("Use this command within a running Neocortex client context."),process.exit(0);break}case"doctor":{const{doctorCliHandler:e}=await import("./commands/doctor.js"),t=await e(o);process.exit(t);break}case"auth-doctor":{const{authDoctorCliHandler:e}=await import("./commands/auth-doctor.js"),t=await e(o);process.exitCode=t;break}case"config":{const{configCliHandler:e}=await import("./commands/config.js"),t=await e(o);process.exit(t);break}case"refresh-memory":{const{refreshMemoryCliHandler:e}=await import("./commands/refresh-memory.js"),t=await e(o);process.exit(t);break}case"architecture-memory":{const{architectureMemoryTerminalCliHandler:e}=await import("./commands/architecture-memory-terminal.js"),t=await e(o);process.exit(t);break}case"planning-diagnosis":{const{planningDiagnosisCliHandler:e}=await import("./commands/planning-diagnosis.js"),t=await e(o);process.exit(t);break}case"planning-research":{const{planningResearchCliHandler:e}=await import("./commands/planning-research.js"),t=await e(o);process.exit(t);break}case"private-session":{const{privateSessionCliHandler:e}=await import("./commands/private-session.js"),t=await e(o);process.exit(t);break}case"planning-memory":{const{planningMemoryCliHandler:e}=await import("./commands/planning-memory.js"),t=await e(o);process.exit(t);break}case"planning-generation":{const{planningGenerationCliHandler:e}=await import("./commands/planning-generation.js"),t=await e(o);process.exit(t);break}case"planning-qa":{const{planningQaCliHandler:e}=await import("./commands/planning-qa.js"),t=await e(o);process.exit(t);break}case"story-checkpoint":{const{storyCheckpointCliHandler:e}=await import("./commands/story-checkpoint.js"),t=await e(o);process.exit(t);break}case"story-worktree":{const{storyWorktreeCliHandler:e}=await import("./commands/story-worktree.js"),t=await e(o);process.exit(t);break}case"legacy-story-branch":{const{legacyStoryBranchCliHandler:e}=await import("./commands/legacy-story-branch.js"),t=await e(o);process.exit(t);break}case"legacy-story-pr":{const{legacyStoryPrCliHandler:e}=await import("./commands/legacy-story-pr.js"),t=await e(o);process.exit(t);break}case"legacy-epic-terminal":{const{legacyEpicTerminalCliHandler:e}=await import("./commands/legacy-epic-terminal.js"),t=await e(o);process.exit(t);break}case"mutation-qa":{const{mutationQaCliHandler:e}=await import("./commands/mutation-qa.js"),t=await e(o);process.exit(t);break}case"property-qa":{const{propertyQaCliHandler:e}=await import("./commands/property-qa.js"),t=await e(o);process.exit(t);break}case"qa-synthetic-backend":{const{syntheticBackendCliHandler:e}=await import("./commands/qa-synthetic-backend.js");process.exitCode=await e(r.slice(1));break}case"qa-scan-review":{const{qaScanReviewCliHandler:e}=await import("./commands/qa-scan-review.js"),t=await e(o);process.exit(t);break}case"qa-root":{const{qaControlCliHandler:e}=await import("./commands/qa-control.js");process.exit(await e(o));break}case"refactor-root":{if(o[0]==="control"){const{refactorControlCliHandler:i}=await import("./commands/refactor-control.js");process.exit(await i(o))}if(o[0]==="characterize"){const{refactorCharacterizationCliHandler:i}=await import("./commands/refactor-characterization.js");process.exit(i(o))}if(o[0]==="review-accept"||o[0]==="review-status"){const{refactorReviewCliHandler:i}=await import("./commands/refactor-review.js");process.exit(await i(o))}if(o[0]?.startsWith("commit-")){const{refactorCommitCliHandler:i}=await import("./commands/refactor-commit.js");process.exit(i(o))}const{refactorRootCliHandler:e}=await import("./commands/refactor-root.js"),t=e(o);process.exit(t);break}case"native-agent":{const{nativeAgentCliHandler:e}=await import("./commands/native-agent.js"),t=await e(o);process.exit(t);break}case"architecture-answers":{const{architectureAnswersCliHandler:e}=await import("./commands/architecture-answers.js"),t=await e(o);process.exit(t);break}case"update":{console.log("To update Neocortex, run:"),console.log(" neocortex update"),console.log(""),console.log("Or manually:"),console.log(" npm install -g @ornexus/neocortex@latest"),process.exit(0);break}default:console.error(`Unknown command: ${a}`),console.error('Run "neocortex-client --help" for usage information.'),process.exit(1)}}q().catch(r=>{console.error(`Fatal error: ${r instanceof Error?r.message:String(r)}`),process.exit(1)});
@@ -1,5 +1,5 @@
1
1
  import{classifyNonUiArchitectureTransition as fa,architectureMemoryPredecessorCount as yi}from"./architecture-non-ui-continuation.js";import{parseArchitectureNonUiScopeReceipt as Ii}from"./shared-architecture-non-ui.js";import{createHash as je,randomUUID as Mr}from"node:crypto";import{loadPactAnswerReceipt as Ei,loadPactPrivateAnswers as ga}from"./architecture-answers.js";import{acceptedArchitectureTerminalMemoryReceipt as hr,deriveArchitectureTerminalMemoryReceipt as yn}from"./architecture-memory-terminal.js";import{deriveCommittedArchitectureEpicGraphRevision as fr,explicitArchitectureEpicTarget as ma}from"./architecture-root-binding.js";import{derivePactWriteSet as ya}from"../private-execution/pact-write-set.js";import{execFileSync as Ae}from"node:child_process";import{existsSync as Ct,readFileSync as Ue,renameSync as Si,unlinkSync as gr,writeFileSync as Vr,mkdirSync as rr,statSync as Ia,openSync as Ht,closeSync as Gt,fsyncSync as mr,realpathSync as In,lstatSync as nr}from"node:fs";import{isDeepStrictEqual as C}from"node:util";import{join as J,isAbsolute as Ea,resolve as En}from"node:path";import{homedir as yr}from"node:os";import{probeYoloopHostCapacity as Sa}from"../runner/host-capacity.js";import{normalizeWorkflowTargetArgs as vi,normalizeYoloStoryTargetArgs as va}from"../yoloop/target-normalization.js";import{reconcileMissingTrackedEpicState as Ci}from"../git/epic-state-recovery.js";import{PrivateIsolatedWorkspaceError as Ca}from"../private-execution/isolated-workspace.js";import{isPrivateExecutionPublicEnvelope as _a,isPrivatePlanningRootPublicEnvelope as wa,PRIVATE_MUTATION_QA_GATE_STEP_TOKEN as Ra}from"../private-execution/delivery.js";import{acceptedPlanningDiagnosisPredecessor as _i}from"../private-execution/planning-diagnosis-checkpoint.js";import{acceptedPlanningResearchPredecessor as wi}from"../private-execution/planning-research-checkpoint.js";import{verifyCommittedPlanningMemory as Ri}from"../private-execution/planning-memory-checkpoint.js";import{verifyCommittedPlanningGeneration as Aa}from"../private-execution/planning-generation-checkpoint.js";import{PLANNING_CHECKPOINT_MAX_BYTES as Ai,PLANNING_RAW_INTENT_MAX_CHARS as ba}from"../../../shared/dist/planning/diagnosis-state.js";import{applyCrossEpicContinuationReconciliation as xa,buildCrossEpicContinuationPayloadHash as Ta,classifyCrossEpicContinuationReconciliation as Pa,epicOperationalHash as _t,readEpicOperationalState as Sn,registerEpicOperationalIdentity as ka}from"../git/epic-operational-state.js";import{applyEpicLifecycleBackfillWithoutClientDrift as Oa,previewEpicLifecycleBackfill as Na}from"../migrations/epic-lifecycle-backfill.js";import{LicenseClient as vn}from"../license/license-client.js";import{EncryptedCache as Ir}from"../cache/encrypted-cache.js";import{NoOpCache as bi}from"../types/index.js";import{resolveClientPreFlightTrigger as Br,TierAwareClient as Da}from"../tier/tier-aware-client.js";import{COMMAND_REGISTRY_CHECKSUM as wt,COMMAND_REGISTRY_VERSION as Rt,GENERATED_CLIENT_COMMANDS as La}from"../generated/command-registry.generated.js";import{loadSecureConfig as $r}from"../config/secure-config.js";import{neocortexProfileDirectory as ja}from"../config/profile-directory.js";import{normalizeInvokeProjectRoot as Ma,resolveEffectiveProjectRoot as Va}from"../config/project-root.js";import{DEFAULT_SERVER_URL as xi}from"../constants.js";import{detectFirstRunLocale as Ba,renderFirstRunMessage as $a}from"../i18n/first-run.js";import{humanizeAuthRefreshRequired as Ti,humanizeError as Cn,formatHumanizedError as _n,detectErrorLocale as Ur}from"../errors/error-messages.js";import{classifyTransportFailure as Pi}from"../errors/transport-failure.js";import{degradeStateSnapshotForPayloadLimit as Ua,projectStateSnapshotForInvoke as ki,projectStateSnapshotResultV2ForInvoke as Ha}from"../state/project-state-snapshot.js";import{isInlineYoloMaterialization as Oi,maybeRepairStateJsonBeforeInvoke as Ga,readStoryWorktreeRepairOverlay as Wa,StateRepairHardStopError as Fa}from"../state/state-json-repair.js";import{StructuralDagError as Ni}from"../state/structural-dag-projection.js";import{collectStateMigrationAuthority as za,StateMigrationApplyError as Ya}from"../migrations/state-json.js";import{RUNNER_BOOTSTRAP_POLICY_REASON_CODES as qa,classifyRunnerBootstrapPolicyFromArgs as Ka}from"../continuity/runner-bootstrap-policy.js";import{RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES as Ja,ensureRunnerSchedulerBootstrap as Qa,observeRunnerOperationalStatus as Xa}from"../runner/scheduler.js";import{CONTINUITY_INVOKE_WATCH_DEFAULT_LIMIT as Di,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_IDLE_POLLS as Li,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_POLLS as ji,CONTINUITY_INVOKE_WATCH_DEFAULT_POLL_INTERVAL_MS as Mi,openContinuityClientStateStore as Za}from"../continuity/continuity-client-state-store.js";import{isLocalJobsConsoleArgs as ec,runLocalJobsConsoleCommand as tc}from"../runner/local-console.js";import{detectNativeHostAttestation as rc,detectPlatform as Vi}from"../adapters/platform-detector.js";import{signNxInvokeRequest as nc}from"../../../shared/dist/nx-invoke-signature.js";import{YOLO_INVOKE_ENVELOPE_CAPABILITY as ic}from"../../../shared/dist/yolo/spec-envelope.js";import{parseReleaseBlockedResult as oc}from"../../../shared/dist/yoloop/release-blocked.js";import{CLIENT_VERSION as Dt}from"../version.js";import{createCapabilityCache as Bi,executeInvokeQueryTransport as wn,executeSecondaryNetworkMutation as ac}from"../effects/invoke-effect-gateways.js";import{STRICT_READ_ONLY_POLICY as cc,STRICT_READ_ONLY_CLIENT_PROJECTION as $i,STRICT_READ_ONLY_SERVER_PROJECTION as sc,StrictReadOnlyError as Wt,canonicalizeInvokeEffects as dc,createInvokeEffectContext as pc,verifyStrictReadOnlyReceipt as uc}from"../../../shared/dist/strict-readonly.js";import{admitInvocation as lc,assertDiagnoseDegradedContinuation as hc,assertInvokeInputEnvelopeV2 as fc,assertProjectIdentityMigrationReceiptV1 as gc,buildSemanticGateRemediation as mc,projectInvokeValidationFailure as Rn,buildPrivateExecutionWorkspaceFailure as yc,buildProjectIdentityPublicDiagnostic as ir,createInvocationAdmissionReceipt as Ic,materializeSemanticGateBoilerplate as Ec,parseSemanticGateRemediation as Hr,projectInvokeInputEvidenceV1 as Er,projectPrivateExecutionHostFailure as Ui,projectPrivateExecutionWorkspaceFailure as Hi,PRIVATE_EXECUTION_WORKSPACE_GATE as Gi,recoverExplicitInvocation as Sc,semanticGatePrivateClaimSessionId as vc,semanticGateRequestSha256 as Wi,validateSemanticGateRemediationBinding as Fi,verifyStrictDiagnoseReceiptV1 as Cc}from"../../../shared/dist/invocation/index.js";import{buildInvokeInputEnvelope as Ft,InvokeInputDecodeError as _c}from"../invocation/invoke-input.js";import{COMPATIBILITY_CAPABILITIES as Gr,COMPATIBILITY_REASON_CODES as or,COMPATIBILITY_SCHEMAS as Wr,createCompatibilityOffer as wc,createLegacyCompatibilityResult as Rc,hostKindForPlatformTarget as An,isCompatibilityResultV1 as zi,PRIVATE_EXECUTION_CODEX_HOST_KIND as bn}from"../../../shared/dist/compatibility/index.js";import{acknowledgeProjectIdentityMigration as Ac,finalizeProjectIdentityMigration as bc,prepareProjectIdentityMigration as xc,ProjectIdentityMigrationError as xn,readProjectIdentityMigrationPhase as Tc}from"../migrations/project-identity.js";import{probeProjectIdentityMigrationCapability as Pc}from"../migrations/project-identity-capability.js";import{normalizeYoloopStoryPlanningEvidence as kc}from"../../../shared/dist/yoloop/planning-graph.js";import{normalizeContinuousWriteRef as Fr}from"../../../shared/dist/yoloop/wave-decision-receipt.js";import{epicHeadReconciliationInputDigest as Oc,epicHeadReconciliationPathsDigest as zr,epicHeadReconciliationRangeDigest as Nc}from"../../../shared/dist/yoloop/epic-terminal-git.js";import{applyGitLifecycleRuntimeOverlay as Tn,classifyGitLifecycleStoryCheckpointProjectionSync as Dc,ensureRuntimeEpic as Lc,ensureGitLifecycleRuntimeInitialized as jc,executeP205TransientAuthorities as Mc,isP226GateReasonCode as Vc,persistGitLifecycleGraphAuthority as Bc,P205_COMPLETE_COMMAND as Sr,gitLifecycleStoryWriteSet as Yi,gitLifecycleStoryClaimCandidates as $c,gitLifecycleWriteSetCovers as Uc,appendStoryWorktreeEvidence as Hc,isStoryWorktreeEvidenceContainer as Gc,mutateGitLifecycleRuntime as qi,projectP205TransientExecutionEvidence as Wc,projectStoryWorktreeEvidenceForSnapshot as Fc,readGitLifecycleRuntimeSync as ar,verifyLegacyCheckpointMigrationCandidateSync as zc}from"../git/git-lifecycle-store.js";import{detectGovernanceModeSync as Yc,readGovernanceStateSourceSync as qc,writeProjectStateMirrorSync as Kc}from"../git/governance-runtime-store.js";import{verifyRootMemoryPhysicalWriteSet as Jc}from"../private-execution/root-memory-git-evidence.js";import{isRootProjectMemoryEffect as Qc}from"../private-execution/shared-root-memory-types.js";import{probeYoloInvokeEnvelopeCapability as Xc}from"../yolo/invoke-envelope-capability.js";import{attachProjectManifestProjection as Zc}from"../yolo/project-manifest-projection-collector.js";import{collectYoloSpecEnvelope as Ki,extractTargetedYoloStoryId as es,refreshPrecollectedYoloSpecEnvelope as Ji}from"../yolo/spec-envelope-collector.js";import{FRONTMATTER_LIST_TOO_LONG_DIAGNOSTIC_PATTERN as ts}from"../errors/frontmatter-diagnostics.js";function Qi(e,t=!1){return e instanceof Error&&((t?/^yolo-(?:spec-envelope|change-evidence)-[a-z-]+$/:/^yolo-spec-envelope-[a-z-]+$/).test(e.message)||ts.test(e.message))?e.message:"yolo-spec-envelope-unsafe"}function rs(e){const t=Fi(e.remediation,e);return t?.reasonCode==="yoloop-session-invalidated"&&t.repairKind==="reconcile-deterministic-state"&&t.authority.operation==="cas-reconcile-yoloop-session"&&t.boilerplate.templateId==="gate-deterministic-reconciliation-v1"&&t.retry.limit===1?t:null}const Yr=ja(),vr=J(Yr,"cache"),Xi=J(vr,"menu-cache.json"),Zi=1440*60*1e3,eo=3e4,to=256*1024,ro=to,no=.8,Lt="[REDACTED]",ns=1e5,zt=2e3,is=200,os=200,as=12,cs=/(?:promptBody|workflow|workflowGraph|stepBody|privateUrl|rawLog|secret|credential|licenseKey|apiKey|internalRouting|serverOnly|proprietary|protected)/i,ss=/(?:PRIVATE|PROTECTED|SERVER_ONLY)[-_\s]*(?:PROMPT|PROMPT_BODY|WORKFLOW|WORKFLOW_GRAPH|STEP_BODY|STEP|ROUTING)\s*[:=][^\n\r]*/gi,ds=/(?: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,Pn=Math.floor(to*no),io=J(Yr,".first-run-shown"),ps="pending-epic-claims.json",oo=64;function kn(e){return J(e,".neocortex",ps)}function Yt(e){const t=kn(e);if(!Ct(t))return{schemaVersion:1,operations:{}};const n=JSON.parse(Ue(t,"utf8"));if(!n||typeof n!="object"||Array.isArray(n))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const o=n;if(o.schemaVersion!==1||!o.operations||typeof o.operations!="object"||Array.isArray(o.operations))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(Object.keys(o.operations).length>oo)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");for(const[i,r]of Object.entries(o.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 n}function On(e,t){const n=kn(e);rr(J(e,".neocortex"),{recursive:!0,mode:448});const o=`${n}.${process.pid}.${Mr()}.tmp`,i=Ht(o,"wx",384);try{try{Vr(i,`${JSON.stringify(t)}
2
- `,"utf8"),mr(i)}finally{Gt(i)}Si(o,n)}catch(r){try{gr(o)}catch{}throw r}}function Nn(e,t){const n=`${kn(e)}.lock`;rr(J(e,".neocortex"),{recursive:!0,mode:448});let o;try{o=Ht(n,"wx",384)}catch(i){throw i.code==="EEXIST"?new Error("EPIC_CLAIM_WRITE_LOCKED"):i}try{return t()}finally{Gt(o),gr(n)}}function us(e,t){return je("sha256").update(`nx-epic-logical-operation-v1\0${JSON.stringify({command:t,args:e})}`,"utf8").digest("hex")}function ls(e,t,n="create-epic"){const o=us(t,n);return Nn(e,()=>{const i=Yt(e),r=i.operations[o];if(r)return{key:r.idempotencyKey,fingerprint:o};if(Object.keys(i.operations).length>=oo)throw new Error("EPIC_CLAIM_CAPACITY_EXCEEDED");const a=Mr(),s={...i.operations,[o]:{idempotencyKey:a,createdAt:new Date().toISOString()}};return On(e,{schemaVersion:1,operations:s}),{key:a,fingerprint:o}})}function hs(e,t,n){return Nn(e,()=>{const o=Yt(e),i=o.operations[t];if(!i||n&&(i.idempotencyKey!==n.idempotencyKey||i.createdAt!==n.createdAt||i.claimId!==n.claimId||i.epicId!==n.epicId||i.planningProtocol!==n.planningProtocol))return!1;const r={...o.operations};return delete r[t],On(e,{schemaVersion:1,operations:r}),!0})}function fs(e,t,n,o){const i=o.scope?.targetStoryId??o.current_session?.active_story_id??null,r=o.scope?.targetEpicId??o.current_session?.active_epic_id??null,a=i?o.stories[i]:void 0,s=Array.isArray(a?.steps_completed)?a.steps_completed.filter(d=>typeof d=="string"):[],u=n??je("sha256").update(`nx-yolo-project-path-v1\0${En(e)}`,"utf8").digest("hex"),g=JSON.stringify({projectBinding:u,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:s});return`yolo-${je("sha256").update(`nx-yolo-logical-operation-v1\0${g}`,"utf8").digest("hex")}`}function Dn(e,t,n,o,i){if(!/^[0-9a-f-]{36}$/.test(n)||!/^P[1-9][0-9]*$/.test(o)||i!==void 0&&i!=="root-staged-v1")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");Nn(e,()=>{const r=Yt(e),a=r.operations[t];if(!a)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(a.claimId!==void 0&&(a.claimId!==n||a.epicId!==o))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");On(e,{schemaVersion:1,operations:{...r.operations,[t]:{...a,claimId:n,epicId:o,...i?{planningProtocol:i}:{}}}})})}function gs(){try{if(Ct(io))return;const e=Ba(),t=$a(e);process.stderr.write(t);try{rr(Yr,{recursive:!0}),Vr(io,new Date().toISOString(),"utf-8")}catch{}}catch{}}const ao=["linux","darwin","win32"],ms=["executor-returned-unverified","private-executor-timeout","private-executor-output-exceeded","private-executor-exit-nonzero"],ys=["schemaVersion","kind","hostKind","os","outcome","stdoutSha256","stderrSha256","stdoutBytes","stderrBytes","publicSafe"],Ln=/^private-executor-[a-z-]+$/;function Is(e,t){return e===bn&&t==="linux"}async function co(e,t){const{createPrivateHarnessExecutorPort:n}=await import("../private-execution/harness-adapters/index.js");return n(e,{cwd:t.cwd})}async function so(e,t,n=co){let o;try{o=await n(e,{cwd:t})}catch{o=void 0}if(!o||typeof o!="object"||o.hostKind!==e||typeof o.preflight!="function"||typeof o.run!="function")throw new Error("private-executor-headless-unavailable");return o}function Es(e,t){if(!f(e)||Object.keys(e).sort().join(",")!=="hostKind,hostVersion,observedAtMs,os"||e.hostKind!==t||typeof e.hostVersion!="string"||!/^[0-9]+\.[0-9]+\.[0-9]+$/.test(e.hostVersion)||typeof e.os!="string"||!ao.includes(e.os)||typeof e.observedAtMs!="number"||!Number.isSafeInteger(e.observedAtMs)||e.observedAtMs<=0)throw new Error("private-executor-proof-invalid");return e}async function po(e,t){let n;try{n=await e.preflight()}catch(o){throw new Error(o instanceof Error&&Ln.test(o.message)?o.message:"private-executor-proof-invalid")}return Es(n,t)}function Ss(e,t){const n=o=>typeof o=="number"&&Number.isSafeInteger(o)&&o>=0;if(!f(e)||Object.keys(e).sort().join(",")!==[...ys].sort().join(",")||e.schemaVersion!==2||e.kind!=="PrivateHarnessExecutionReceipt/2"||e.hostKind!==t||typeof e.os!="string"||!ao.includes(e.os)||typeof e.outcome!="string"||!ms.includes(e.outcome)||typeof e.stdoutSha256!="string"||!/^[a-f0-9]{64}$/.test(e.stdoutSha256)||typeof e.stderrSha256!="string"||!/^[a-f0-9]{64}$/.test(e.stderrSha256)||!n(e.stdoutBytes)||!n(e.stderrBytes)||e.publicSafe!==!0)throw new Error("private-executor-receipt-invalid");return e}function vs(e){return{schemaVersion:1,hostKind:e.hostKind,hostVersion:e.hostVersion,executorProof:{schemaVersion:7,preflight:"passed",hostVersion:"passed",stdinOnly:"passed",ephemeralHome:"passed",nativeNoPersistence:"passed",os:"passed"}}}function uo(e){return{schemaVersion:1,hostKind:"codex-cli",hostVersion:e.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:e.observedAtMs}}}async function Cs(e,t,n){const{captureDirectYoloCheckoutEvidence:o}=await import("../git/direct-yolo-checkpoint.js"),i=()=>new Error("private-executor-workspace-effect-unverified"),r=n.requireWorkspaceEffect?await o(n.workspaceRoot).catch(()=>{throw i()}):void 0;if(r&&n.expectedExecutionBranch!==void 0&&r.branch!==n.expectedExecutionBranch)throw i();let a;try{a=await e.run(t)}catch(u){throw new Error(u instanceof Error&&Ln.test(u.message)?u.message:"private-executor-run-failed")}const s=Ss(a,n.hostKind);if(s.outcome!=="executor-returned-unverified")throw new Error(s.outcome);if(r){const u=await o(n.workspaceRoot).catch(()=>{throw i()});if(u.headSha!==r.headSha||u.branch!==r.branch||u.payloadDigest===r.payloadDigest)throw i()}return s}function _s(e){if(e.writeSetId==="idea-diagnosis-v1"&&e.stepId==="step-acd455ed")return"diagnosis";throw new Error(e.codexV6?"private-execution-planning-root-protocol-required":"private-execution-planning-step-unsupported")}function al(e,t=process.cwd()){return Ma(e,t)}async function lo(e){return(await Va({explicitRoot:e})).root}const ws=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,Rs="Reinstall Neocortex with optional dependencies and lifecycle scripts enabled, or run `npm rebuild better-sqlite3` from the installed package root before retrying the same request.";function ho(e){const t=f(e)&&e.code==="sqlite-adapter-unavailable"?"sqlite-adapter-unavailable":"native-custody-observation-failed";return Object.freeze({schemaVersion:1,reasonCode:t,remediation:t==="sqlite-adapter-unavailable"?Rs:"Run the Neocortex doctor, repair the reported local continuity-store condition, then retry the same yoloop request.",retrySafeAfterRepair:!0,publicSafe:!0})}function As(e){if(!f(e)||e.schemaVersion!==1||e.reasonCode!=="sqlite-adapter-unavailable"&&e.reasonCode!=="native-custody-observation-failed"||e.retrySafeAfterRepair!==!0||e.publicSafe!==!0)return;const t=ho(e.reasonCode==="sqlite-adapter-unavailable"?{code:"sqlite-adapter-unavailable"}:void 0);if(e.remediation===t.remediation)return Object.freeze({schemaVersion:1,reasonCode:e.reasonCode,remediation:t.remediation,retrySafeAfterRepair:!0,publicSafe:!0})}function fo(e,t){if(t.success||Hr(t.metadata?.semanticGateRemediation))return t;const o=(t.errorCode===Gi?Hi(t.metadata?.privateExecutionWorkspaceFailure):void 0)?.reason_code??(t.errorCode&&ws.test(t.errorCode)?t.errorCode:"INVOKE_ERROR"),i=mc({templateId:"gate-manual-resolution-v1",reasonCode:o,requestSha256:Wi(e)});return{...t,metadata:{...t.metadata,semanticGateRemediation:i}}}function bs(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 xs(e){const t=e.metadata;if(!t||!(t.yoloopReleaseBlocked===!0||t.terminalClass==="release-blocked"||t.releaseBlocked!==void 0))return;const o=oc(t.releaseBlocked);return!o||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:o},error:"YOLOOP_RELEASE_BLOCKED: the current release attempt ended without success.",errorCode:"YOLOOP_RELEASE_BLOCKED",exitCode:1}}function jn(e){return lc(e,{registryVersion:Rt,registryChecksum:wt})}function Ts(e){return Sc(e,{registryVersion:Rt,registryChecksum:wt})}const Ps=new Set(["completed","aborted","cancelled"]),ks=new Set(["watch-target-missing","watch-target-malformed","watch-target-ambiguous","watch-target-multiple"]),Ne=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"}),He=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"}),Q=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"}),go=240,Os=/(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 Ns(e){return e.replace(/[\w.+-]+@[\w-]+\.[\w.-]+/g,Lt).replace(/(?:sk|pk|whsec|nxk)[-_](?:test|live|ant|proj|pro|free|enterprise)?[-_]?[A-Za-z0-9_-]{16,}/g,Lt).replace(/NX-[FPE]-[a-f0-9]{24}-[a-f0-9]{4}/g,Lt).replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,Lt).replace(ss,Lt).replace(ds,Lt)}function nt(e,t){const n=Ns(e);return n.length<=t?n:`${n.slice(0,t)}\u2026[TRUNCATED:${n.length-t}]`}function Mn(e,t=0,n=new WeakSet){if(t>as)return"[MAX_DEPTH]";if(e==null)return e;if(typeof e=="string")return nt(e,zt);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(n.has(e))return"[CIRCULAR]";n.add(e);try{if(Array.isArray(e))return e.slice(0,is).map(i=>Mn(i,t+1,n));const o={};for(const[i,r]of Object.entries(e).slice(0,os)){if(cs.test(i)){o[i]=Lt;continue}const a=Mn(r,t+1,n);a!==void 0&&(o[i]=a)}return o}finally{n.delete(e)}}}function qr(e,t){return{instructions:nt(e??"",ns),metadata:t?Mn(t):void 0}}function Ds(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e,n=typeof t.reason=="string"&&/^[a-z0-9-]{1,80}$/.test(t.reason)?t.reason:void 0,o=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(!(!n||!o||!i||!r||a===void 0||t.publicSafe!==!0))return{reason:n,base_source:o,repair:i,recollection_count:a,fallback_action:r,public_safe:!0}}class Kr extends Error{reason;source;byteLength;code;constructor(t,n,o,i,r){super(n),this.reason=o,this.source=i,this.byteLength=r,this.name="InvokeCliInputError",this.code=t}}function Ls(e){const t=Br(e);return(t==="arch-plan"||t==="ui-ux-review")&&js(e,"--project-evidence")}function js(e,t){let n=null,o=-1,i=!1,r=!1;for(let a=0;a<=e.length;a+=1){const s=e[a];if(a===e.length||!n&&/\s/.test(s??"")){if(o>=0&&!i&&e.slice(o,a)===t)return!0;o=-1,i=!1,r=!1;continue}if(o<0&&(o=a),r){r=!1;continue}if(s==="\\"){r=!0;continue}(s==='"'||s==="'")&&(i=!0,n=n===s?null:n??s)}return!1}const Ms=/(?:^|\s)codex(?:-cli)?\s+([A-Za-z0-9][A-Za-z0-9._+-]{0,63})(?:\s|$)/i;function Vs(e,t){if(e.targetId!=="codex")return null;const n=t.CODEX_VERSION?.trim();if(n&&/^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/.test(n))return n;try{return Ae("codex",["--version"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim().match(Ms)?.[1]??null}catch{return null}}function Vn(e=!1){return wc({clientVersion:Dt,registryVersion:Rt,registryChecksum:wt,capabilityIds:Object.values(Gr).filter(t=>e||t!==Gr.DIAGNOSE_SCOPED_CONTINUATION),schemaVersions:Object.values(Wr).filter(t=>e||t!==Wr.DIAGNOSE_SCOPED_CONTINUATION)})}class Bn 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 $n 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 Un=!1;function Bs(e){const t=[];if(!e||typeof e!="object")return t;const n=e,o=n.planning;if(o&&(o.current!==void 0||Array.isArray(o.history))&&t.push({code:"PLANNING_LEGACY",message:"legacy `planning.current`/`planning.history` detected (not read by v1 orchestrator)"}),Array.isArray(n.stories)&&t.push({code:"STORIES_AS_ARRAY",message:"`stories` is an Array (expected Object keyed by story ID)"}),n.epics&&typeof n.epics=="object"&&!Array.isArray(n.epics))for(const[r,a]of Object.entries(n.epics)){const s=a;if(s&&s.stories!==void 0&&!Array.isArray(s.stories)){t.push({code:"EPIC_STORIES_NOT_ARRAY",message:`epic "${r}" has non-array \`stories\` field (expected string[] of story IDs)`});break}}const i=n.epics&&typeof n.epics=="object"&&Object.keys(n.epics).length>0||n.stories&&typeof n.stories=="object"&&!Array.isArray(n.stories)&&Object.keys(n.stories).length>0||Array.isArray(n.stories)||o&&o.current!==void 0;return n.schema_version===void 0?i&&t.push({code:"SCHEMA_VERSION_MISSING",message:"`schema_version` field missing (expected: `schema_version: 1`)"}):n.schema_version!==1&&t.push({code:"SCHEMA_VERSION_OUTDATED",message:`schema_version=${String(n.schema_version)} (expected: 1)`}),t}function $s(e){if(!(Un||e.length===0)){Un=!0;try{const t=e.map(n=>` - ${n.message}`).join(`
2
+ `,"utf8"),mr(i)}finally{Gt(i)}Si(o,n)}catch(r){try{gr(o)}catch{}throw r}}function Nn(e,t){const n=`${kn(e)}.lock`;rr(J(e,".neocortex"),{recursive:!0,mode:448});let o;try{o=Ht(n,"wx",384)}catch(i){throw i.code==="EEXIST"?new Error("EPIC_CLAIM_WRITE_LOCKED"):i}try{return t()}finally{Gt(o),gr(n)}}function us(e,t){return je("sha256").update(`nx-epic-logical-operation-v1\0${JSON.stringify({command:t,args:e})}`,"utf8").digest("hex")}function ls(e,t,n="create-epic"){const o=us(t,n);return Nn(e,()=>{const i=Yt(e),r=i.operations[o];if(r)return{key:r.idempotencyKey,fingerprint:o};if(Object.keys(i.operations).length>=oo)throw new Error("EPIC_CLAIM_CAPACITY_EXCEEDED");const a=Mr(),s={...i.operations,[o]:{idempotencyKey:a,createdAt:new Date().toISOString()}};return On(e,{schemaVersion:1,operations:s}),{key:a,fingerprint:o}})}function hs(e,t,n){return Nn(e,()=>{const o=Yt(e),i=o.operations[t];if(!i||n&&(i.idempotencyKey!==n.idempotencyKey||i.createdAt!==n.createdAt||i.claimId!==n.claimId||i.epicId!==n.epicId||i.planningProtocol!==n.planningProtocol))return!1;const r={...o.operations};return delete r[t],On(e,{schemaVersion:1,operations:r}),!0})}function fs(e,t,n,o){const i=o.scope?.targetStoryId??o.current_session?.active_story_id??null,r=o.scope?.targetEpicId??o.current_session?.active_epic_id??null,a=i?o.stories[i]:void 0,s=Array.isArray(a?.steps_completed)?a.steps_completed.filter(d=>typeof d=="string"):[],u=n??je("sha256").update(`nx-yolo-project-path-v1\0${En(e)}`,"utf8").digest("hex"),g=JSON.stringify({projectBinding:u,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:s});return`yolo-${je("sha256").update(`nx-yolo-logical-operation-v1\0${g}`,"utf8").digest("hex")}`}function Dn(e,t,n,o,i){if(!/^[0-9a-f-]{36}$/.test(n)||!/^P[1-9][0-9]*$/.test(o)||i!==void 0&&i!=="root-staged-v1")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");Nn(e,()=>{const r=Yt(e),a=r.operations[t];if(!a)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(a.claimId!==void 0&&(a.claimId!==n||a.epicId!==o))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");On(e,{schemaVersion:1,operations:{...r.operations,[t]:{...a,claimId:n,epicId:o,...i?{planningProtocol:i}:{}}}})})}function gs(){try{if(Ct(io))return;const e=Ba(),t=$a(e);process.stderr.write(t);try{rr(Yr,{recursive:!0}),Vr(io,new Date().toISOString(),"utf-8")}catch{}}catch{}}const ao=["linux","darwin","win32"],ms=["executor-returned-unverified","private-executor-timeout","private-executor-output-exceeded","private-executor-exit-nonzero"],ys=["schemaVersion","kind","hostKind","os","outcome","stdoutSha256","stderrSha256","stdoutBytes","stderrBytes","publicSafe"],Ln=/^private-executor-[a-z-]+$/;function Is(e,t){return e===bn&&t==="linux"}async function co(e,t){const{createPrivateHarnessExecutorPort:n}=await import("../private-execution/harness-adapters/index.js");return n(e,{cwd:t.cwd})}async function so(e,t,n=co){let o;try{o=await n(e,{cwd:t})}catch{o=void 0}if(!o||typeof o!="object"||o.hostKind!==e||typeof o.preflight!="function"||typeof o.run!="function")throw new Error("private-executor-headless-unavailable");return o}function Es(e,t){if(!f(e)||Object.keys(e).sort().join(",")!=="hostKind,hostVersion,observedAtMs,os"||e.hostKind!==t||typeof e.hostVersion!="string"||!/^[0-9]+\.[0-9]+\.[0-9]+$/.test(e.hostVersion)||typeof e.os!="string"||!ao.includes(e.os)||typeof e.observedAtMs!="number"||!Number.isSafeInteger(e.observedAtMs)||e.observedAtMs<=0)throw new Error("private-executor-proof-invalid");return e}async function po(e,t){let n;try{n=await e.preflight()}catch(o){throw new Error(o instanceof Error&&Ln.test(o.message)?o.message:"private-executor-proof-invalid")}return Es(n,t)}function Ss(e,t){const n=o=>typeof o=="number"&&Number.isSafeInteger(o)&&o>=0;if(!f(e)||Object.keys(e).sort().join(",")!==[...ys].sort().join(",")||e.schemaVersion!==2||e.kind!=="PrivateHarnessExecutionReceipt/2"||e.hostKind!==t||typeof e.os!="string"||!ao.includes(e.os)||typeof e.outcome!="string"||!ms.includes(e.outcome)||typeof e.stdoutSha256!="string"||!/^[a-f0-9]{64}$/.test(e.stdoutSha256)||typeof e.stderrSha256!="string"||!/^[a-f0-9]{64}$/.test(e.stderrSha256)||!n(e.stdoutBytes)||!n(e.stderrBytes)||e.publicSafe!==!0)throw new Error("private-executor-receipt-invalid");return e}function vs(e){return{schemaVersion:1,hostKind:e.hostKind,hostVersion:e.hostVersion,executorProof:{schemaVersion:7,preflight:"passed",hostVersion:"passed",stdinOnly:"passed",ephemeralHome:"passed",nativeNoPersistence:"passed",os:"passed"}}}function uo(e){return{schemaVersion:1,hostKind:"codex-cli",hostVersion:e.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:e.observedAtMs}}}async function Cs(e,t,n){const{captureDirectYoloCheckoutEvidence:o}=await import("../git/direct-yolo-checkpoint.js"),i=()=>new Error("private-executor-workspace-effect-unverified"),r=n.requireWorkspaceEffect?await o(n.workspaceRoot).catch(()=>{throw i()}):void 0;if(r&&n.expectedExecutionBranch!==void 0&&r.branch!==n.expectedExecutionBranch)throw i();let a;try{a=await e.run(t)}catch(u){throw new Error(u instanceof Error&&Ln.test(u.message)?u.message:"private-executor-run-failed")}const s=Ss(a,n.hostKind);if(s.outcome!=="executor-returned-unverified")throw new Error(s.outcome);if(r){const u=await o(n.workspaceRoot).catch(()=>{throw i()});if(u.headSha!==r.headSha||u.branch!==r.branch||u.payloadDigest===r.payloadDigest)throw i()}return s}function _s(e){if(e.writeSetId==="idea-diagnosis-v1"&&e.stepId==="step-acd455ed")return"diagnosis";throw new Error(e.codexV6?"private-execution-planning-root-protocol-required":"private-execution-planning-step-unsupported")}function al(e,t=process.cwd()){return Ma(e,t)}async function lo(e){return(await Va({explicitRoot:e})).root}const ws=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,Rs="Reinstall Neocortex with optional dependencies and lifecycle scripts enabled, or run `npm rebuild better-sqlite3` from the installed package root before retrying the same request.";function ho(e){const t=f(e)&&e.code==="sqlite-adapter-unavailable"?"sqlite-adapter-unavailable":"native-custody-observation-failed";return Object.freeze({schemaVersion:1,reasonCode:t,remediation:t==="sqlite-adapter-unavailable"?Rs:"Run the Neocortex doctor, repair the reported local continuity-store condition, then retry the same yoloop request.",retrySafeAfterRepair:!0,publicSafe:!0})}function As(e){if(!f(e)||e.schemaVersion!==1||e.reasonCode!=="sqlite-adapter-unavailable"&&e.reasonCode!=="native-custody-observation-failed"||e.retrySafeAfterRepair!==!0||e.publicSafe!==!0)return;const t=ho(e.reasonCode==="sqlite-adapter-unavailable"?{code:"sqlite-adapter-unavailable"}:void 0);if(e.remediation===t.remediation)return Object.freeze({schemaVersion:1,reasonCode:e.reasonCode,remediation:t.remediation,retrySafeAfterRepair:!0,publicSafe:!0})}function fo(e,t){if(t.success||Hr(t.metadata?.semanticGateRemediation))return t;const o=(t.errorCode===Gi?Hi(t.metadata?.privateExecutionWorkspaceFailure):void 0)?.reason_code??(t.errorCode&&ws.test(t.errorCode)?t.errorCode:"INVOKE_ERROR"),i=mc({templateId:"gate-manual-resolution-v1",reasonCode:o,requestSha256:Wi(e)});return{...t,...o==="story-worktree-base-divergent"?{error:"The admitted story base is outside the execution branch history. For an unstarted epic moved to a verified origin, audit the origin binding with story-worktree rebind-origin --dry-run. Epics with story progress require reconciliation of their existing dispatches."}:{},metadata:{...t.metadata,semanticGateRemediation:i}}}function bs(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 xs(e){const t=e.metadata;if(!t||!(t.yoloopReleaseBlocked===!0||t.terminalClass==="release-blocked"||t.releaseBlocked!==void 0))return;const o=oc(t.releaseBlocked);return!o||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:o},error:"YOLOOP_RELEASE_BLOCKED: the current release attempt ended without success.",errorCode:"YOLOOP_RELEASE_BLOCKED",exitCode:1}}function jn(e){return lc(e,{registryVersion:Rt,registryChecksum:wt})}function Ts(e){return Sc(e,{registryVersion:Rt,registryChecksum:wt})}const Ps=new Set(["completed","aborted","cancelled"]),ks=new Set(["watch-target-missing","watch-target-malformed","watch-target-ambiguous","watch-target-multiple"]),Ne=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"}),He=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"}),Q=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"}),go=240,Os=/(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 Ns(e){return e.replace(/[\w.+-]+@[\w-]+\.[\w.-]+/g,Lt).replace(/(?:sk|pk|whsec|nxk)[-_](?:test|live|ant|proj|pro|free|enterprise)?[-_]?[A-Za-z0-9_-]{16,}/g,Lt).replace(/NX-[FPE]-[a-f0-9]{24}-[a-f0-9]{4}/g,Lt).replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,Lt).replace(ss,Lt).replace(ds,Lt)}function nt(e,t){const n=Ns(e);return n.length<=t?n:`${n.slice(0,t)}\u2026[TRUNCATED:${n.length-t}]`}function Mn(e,t=0,n=new WeakSet){if(t>as)return"[MAX_DEPTH]";if(e==null)return e;if(typeof e=="string")return nt(e,zt);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(n.has(e))return"[CIRCULAR]";n.add(e);try{if(Array.isArray(e))return e.slice(0,is).map(i=>Mn(i,t+1,n));const o={};for(const[i,r]of Object.entries(e).slice(0,os)){if(cs.test(i)){o[i]=Lt;continue}const a=Mn(r,t+1,n);a!==void 0&&(o[i]=a)}return o}finally{n.delete(e)}}}function qr(e,t){return{instructions:nt(e??"",ns),metadata:t?Mn(t):void 0}}function Ds(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e,n=typeof t.reason=="string"&&/^[a-z0-9-]{1,80}$/.test(t.reason)?t.reason:void 0,o=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(!(!n||!o||!i||!r||a===void 0||t.publicSafe!==!0))return{reason:n,base_source:o,repair:i,recollection_count:a,fallback_action:r,public_safe:!0}}class Kr extends Error{reason;source;byteLength;code;constructor(t,n,o,i,r){super(n),this.reason=o,this.source=i,this.byteLength=r,this.name="InvokeCliInputError",this.code=t}}function Ls(e){const t=Br(e);return(t==="arch-plan"||t==="ui-ux-review")&&js(e,"--project-evidence")}function js(e,t){let n=null,o=-1,i=!1,r=!1;for(let a=0;a<=e.length;a+=1){const s=e[a];if(a===e.length||!n&&/\s/.test(s??"")){if(o>=0&&!i&&e.slice(o,a)===t)return!0;o=-1,i=!1,r=!1;continue}if(o<0&&(o=a),r){r=!1;continue}if(s==="\\"){r=!0;continue}(s==='"'||s==="'")&&(i=!0,n=n===s?null:n??s)}return!1}const Ms=/(?:^|\s)codex(?:-cli)?\s+([A-Za-z0-9][A-Za-z0-9._+-]{0,63})(?:\s|$)/i;function Vs(e,t){if(e.targetId!=="codex")return null;const n=t.CODEX_VERSION?.trim();if(n&&/^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/.test(n))return n;try{return Ae("codex",["--version"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim().match(Ms)?.[1]??null}catch{return null}}function Vn(e=!1){return wc({clientVersion:Dt,registryVersion:Rt,registryChecksum:wt,capabilityIds:Object.values(Gr).filter(t=>e||t!==Gr.DIAGNOSE_SCOPED_CONTINUATION),schemaVersions:Object.values(Wr).filter(t=>e||t!==Wr.DIAGNOSE_SCOPED_CONTINUATION)})}class Bn 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 $n 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 Un=!1;function Bs(e){const t=[];if(!e||typeof e!="object")return t;const n=e,o=n.planning;if(o&&(o.current!==void 0||Array.isArray(o.history))&&t.push({code:"PLANNING_LEGACY",message:"legacy `planning.current`/`planning.history` detected (not read by v1 orchestrator)"}),Array.isArray(n.stories)&&t.push({code:"STORIES_AS_ARRAY",message:"`stories` is an Array (expected Object keyed by story ID)"}),n.epics&&typeof n.epics=="object"&&!Array.isArray(n.epics))for(const[r,a]of Object.entries(n.epics)){const s=a;if(s&&s.stories!==void 0&&!Array.isArray(s.stories)){t.push({code:"EPIC_STORIES_NOT_ARRAY",message:`epic "${r}" has non-array \`stories\` field (expected string[] of story IDs)`});break}}const i=n.epics&&typeof n.epics=="object"&&Object.keys(n.epics).length>0||n.stories&&typeof n.stories=="object"&&!Array.isArray(n.stories)&&Object.keys(n.stories).length>0||Array.isArray(n.stories)||o&&o.current!==void 0;return n.schema_version===void 0?i&&t.push({code:"SCHEMA_VERSION_MISSING",message:"`schema_version` field missing (expected: `schema_version: 1`)"}):n.schema_version!==1&&t.push({code:"SCHEMA_VERSION_OUTDATED",message:`schema_version=${String(n.schema_version)} (expected: 1)`}),t}function $s(e){if(!(Un||e.length===0)){Un=!0;try{const t=e.map(n=>` - ${n.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.
@@ -12,7 +12,7 @@
12
12
  */
13
13
  import { StoryWorktreeCleanup } from '../git/story-worktree-cleanup.js';
14
14
  import { StoryWorktreeManager } from '../git/story-worktree-manager.js';
15
- export declare const STORY_WORKTREE_ACTIONS: readonly ["create", "adopt", "sync", "status", "release", "cleanup", "recover", "record-push", "assert-phase-two"];
15
+ export declare const STORY_WORKTREE_ACTIONS: readonly ["create", "adopt", "sync", "status", "release", "cleanup", "recover", "record-push", "assert-phase-two", "rebind-origin"];
16
16
  export type StoryWorktreeAction = (typeof STORY_WORKTREE_ACTIONS)[number];
17
17
  export interface StoryWorktreeCliOptions {
18
18
  readonly action: StoryWorktreeAction;
@@ -32,6 +32,9 @@ export interface StoryWorktreeCliOptions {
32
32
  readonly trigger?: string;
33
33
  readonly remote?: string;
34
34
  readonly dryRun?: boolean;
35
+ readonly originBranch?: string;
36
+ readonly executionHeadSha?: string;
37
+ readonly apply?: boolean;
35
38
  }
36
39
  export declare class StoryWorktreeArgumentError extends Error {
37
40
  readonly reasonCode: string;
@@ -1,5 +1,5 @@
1
- import{readFile as g,stat as f,writeFile as m}from"node:fs/promises";import{dirname as b,isAbsolute as S,resolve as C}from"node:path";import{STORY_WORKTREE_CLEANUP_TRIGGERS as j,StoryWorktreeCleanup as F}from"../git/story-worktree-cleanup.js";import{StoryWorktreeManager as O}from"../git/story-worktree-manager.js";const y=Object.freeze(["create","adopt","sync","status","release","cleanup","recover","record-push","assert-phase-two"]),x=j.filter(e=>e!=="orphan-recovery"),E=Object.freeze({"--project-root":"projectRoot","--format":"format","--epic":"epicId","--story":"storyId","--dispatch":"dispatchId","--base-sha":"baseSha","--graph-revision":"graphRevision","--owner":"ownerId","--lease":"leaseId","--sha":"sha","--directive-file":"directiveFile","--worktree-path":"worktreePath","--path-file":"pathFile","--trigger":"trigger","--remote":"remote"}),P=Object.freeze({"--dry-run":"dryRun"}),u=Object.freeze({create:["epicId","storyId","dispatchId","baseSha","graphRevision"],adopt:["epicId","storyId","dispatchId","baseSha","graphRevision","worktreePath"],sync:["leaseId"],status:[],release:["leaseId"],cleanup:["leaseId","trigger"],recover:[],"record-push":["leaseId","remote"],"assert-phase-two":["storyId"]}),A=Object.freeze({create:[...u.create,"ownerId","pathFile"],adopt:[...u.adopt,"ownerId","pathFile"],sync:["leaseId","sha","directiveFile"],status:["leaseId","epicId","storyId"],release:["leaseId"],cleanup:["leaseId","trigger","dryRun"],recover:["epicId","dryRun"],"record-push":["leaseId","remote"],"assert-phase-two":["storyId"]});class o extends Error{reasonCode;constructor(t){super(t),this.reasonCode=t}}function W(e,t=process.cwd()){const a=e[0];if(!y.includes(a))throw new o("story-worktree-action-invalid");const r={};for(let s=1;s<e.length;s++){const d=e[s],l=P[d];if(l){if(r[l]!==void 0)throw new o("story-worktree-argument-invalid");r[l]="true";continue}const c=d.indexOf("="),R=c>0?d.slice(0,c):d,w=E[R];if(!w)throw new o("story-worktree-argument-invalid");const h=c>0?d.slice(c+1):e[++s];if(h===void 0||h===""||r[w]!==void 0)throw new o("story-worktree-argument-invalid");r[w]=h}const i=a,p=new Set([...A[i],"projectRoot","format"]);if(Object.keys(r).some(s=>!p.has(s)))throw new o("story-worktree-option-invalid");if(u[i].some(s=>r[s]===void 0))throw new o("story-worktree-option-required");if(i==="sync"&&r.sha===void 0==(r.directiveFile===void 0))throw new o("story-worktree-sync-source-invalid");if(i==="status"&&[r.leaseId,r.epicId,r.storyId].filter(s=>s!==void 0).length!==1)throw new o("story-worktree-status-selector-invalid");if(i==="cleanup"&&!x.includes(r.trigger))throw new o("story-worktree-trigger-invalid");const n=r.format??"json";if(n!=="json"&&n!=="plain")throw new o("story-worktree-format-invalid");for(const s of["directiveFile","worktreePath","pathFile"])if(r[s]!==void 0&&!S(r[s]))throw new o("story-worktree-path-argument-invalid");const{dryRun:k,...v}=r;return{...v,...k?{dryRun:!0}:{},action:i,projectRoot:C(t,r.projectRoot??"."),format:n}}async function L(e){try{await f(e)}catch{try{if((await f(b(e))).isDirectory())return}catch{}throw new o("story-worktree-path-file-invalid")}throw new o("story-worktree-path-file-exists")}async function _(e,t=new O({projectRoot:e.projectRoot}),a=new F({projectRoot:e.projectRoot,manager:t})){e.pathFile&&await L(e.pathFile);let r;switch(e.action){case"create":r=await t.create({epicId:e.epicId,storyId:e.storyId,dispatchId:e.dispatchId,baseSha:e.baseSha,graphRevision:e.graphRevision,...e.ownerId?{ownerId:e.ownerId}:{}});break;case"adopt":r=await t.adopt({epicId:e.epicId,storyId:e.storyId,dispatchId:e.dispatchId,baseSha:e.baseSha,graphRevision:e.graphRevision,worktreePath:e.worktreePath,...e.ownerId?{ownerId:e.ownerId}:{}});break;case"sync":{let i;if(e.directiveFile)try{i=JSON.parse(await g(e.directiveFile,"utf8"))}catch{return{exitCode:1,payload:{action:"sync",ok:!1,reasonCode:"story-worktree-directive-invalid"}}}r=await t.sync({leaseId:e.leaseId,...e.sha?{integratedSha:e.sha}:{},...i!==void 0?{directive:i}:{}});break}case"status":r=await t.status(e.leaseId?{leaseId:e.leaseId}:e.storyId?{storyId:e.storyId}:{epicId:e.epicId});break;case"release":r=await t.release({leaseId:e.leaseId});break;case"cleanup":r=await a.cleanup({leaseId:e.leaseId,trigger:e.trigger,...e.dryRun?{dryRun:!0}:{}});break;case"recover":r=await a.sweep({...e.epicId?{epicId:e.epicId}:{},...e.dryRun?{dryRun:!0}:{}});break;case"record-push":r=await a.recordPush({leaseId:e.leaseId,remote:e.remote});break;case"assert-phase-two":r=await t.assertPhaseTwo({storyId:e.storyId});break}if(!r.ok)return{exitCode:1,payload:{action:e.action,ok:!1,reasonCode:r.reasonCode,...r.conflictPaths?{conflictPaths:r.conflictPaths}:{}}};if(e.pathFile&&r.privatePath)try{await m(e.pathFile,`${r.privatePath}
2
- `,{flag:"wx",mode:384})}catch{return{exitCode:1,payload:{action:e.action,ok:!1,reasonCode:"story-worktree-path-file-invalid"}}}return{exitCode:0,payload:{action:e.action,ok:!0,value:r.value}}}function I(e,t){if(t==="json")return JSON.stringify(e,null,2);const a=[`story-worktree ${String(e.action)}: ${e.ok?"ok":"refused"}`];return e.reasonCode&&a.push(`reason=${String(e.reasonCode)}`),a.join(" ")}async function z(e){let t;try{t=W(e)}catch(a){const r=a instanceof o?a.reasonCode:"story-worktree-argument-invalid",i=y.includes(e[0])?e[0]:null;return process.stdout.write(`${JSON.stringify({action:i,ok:!1,reasonCode:r})}
3
- `),2}try{const{exitCode:a,payload:r}=await _(t);return process.stdout.write(`${I(r,t.format)}
1
+ import{readFile as b,stat as y,writeFile as S}from"node:fs/promises";import{dirname as m,isAbsolute as C,resolve as j}from"node:path";import{STORY_WORKTREE_CLEANUP_TRIGGERS as x,StoryWorktreeCleanup as O}from"../git/story-worktree-cleanup.js";import{StoryWorktreeManager as F}from"../git/story-worktree-manager.js";const f=Object.freeze(["create","adopt","sync","status","release","cleanup","recover","record-push","assert-phase-two","rebind-origin"]),E=x.filter(e=>e!=="orphan-recovery"),P=Object.freeze({"--project-root":"projectRoot","--format":"format","--epic":"epicId","--story":"storyId","--dispatch":"dispatchId","--base-sha":"baseSha","--graph-revision":"graphRevision","--owner":"ownerId","--lease":"leaseId","--sha":"sha","--origin-branch":"originBranch","--execution-head":"executionHeadSha","--directive-file":"directiveFile","--worktree-path":"worktreePath","--path-file":"pathFile","--trigger":"trigger","--remote":"remote"}),A=Object.freeze({"--dry-run":"dryRun","--apply":"apply"}),c=Object.freeze({create:["epicId","storyId","dispatchId","baseSha","graphRevision"],adopt:["epicId","storyId","dispatchId","baseSha","graphRevision","worktreePath"],sync:["leaseId"],status:[],release:["leaseId"],cleanup:["leaseId","trigger"],recover:[],"record-push":["leaseId","remote"],"assert-phase-two":["storyId"],"rebind-origin":["epicId","originBranch","baseSha","sha","executionHeadSha"]}),W=Object.freeze({create:[...c.create,"ownerId","pathFile"],adopt:[...c.adopt,"ownerId","pathFile"],sync:["leaseId","sha","directiveFile"],status:["leaseId","epicId","storyId"],release:["leaseId"],cleanup:["leaseId","trigger","dryRun"],recover:["epicId","dryRun"],"record-push":["leaseId","remote"],"assert-phase-two":["storyId"],"rebind-origin":[...c["rebind-origin"],"apply","dryRun"]});class o extends Error{reasonCode;constructor(t){super(t),this.reasonCode=t}}function L(e,t=process.cwd()){const a=e[0];if(!f.includes(a))throw new o("story-worktree-action-invalid");const r={};for(let s=1;s<e.length;s++){const n=e[s],h=A[n];if(h){if(r[h]!==void 0)throw new o("story-worktree-argument-invalid");r[h]="true";continue}const d=n.indexOf("="),R=d>0?n.slice(0,d):n,u=P[R];if(!u)throw new o("story-worktree-argument-invalid");const w=d>0?n.slice(d+1):e[++s];if(w===void 0||w===""||r[u]!==void 0)throw new o("story-worktree-argument-invalid");r[u]=w}const i=a,p=new Set([...W[i],"projectRoot","format"]);if(Object.keys(r).some(s=>!p.has(s)))throw new o("story-worktree-option-invalid");if(c[i].some(s=>r[s]===void 0))throw new o("story-worktree-option-required");if(i==="sync"&&r.sha===void 0==(r.directiveFile===void 0))throw new o("story-worktree-sync-source-invalid");if(i==="status"&&[r.leaseId,r.epicId,r.storyId].filter(s=>s!==void 0).length!==1)throw new o("story-worktree-status-selector-invalid");if(i==="cleanup"&&!E.includes(r.trigger))throw new o("story-worktree-trigger-invalid");if(i==="rebind-origin"&&r.apply&&r.dryRun)throw new o("story-worktree-option-invalid");const l=r.format??"json";if(l!=="json"&&l!=="plain")throw new o("story-worktree-format-invalid");for(const s of["directiveFile","worktreePath","pathFile"])if(r[s]!==void 0&&!C(r[s]))throw new o("story-worktree-path-argument-invalid");const{dryRun:k,apply:g,...v}=r;return{...v,...k?{dryRun:!0}:{},...g?{apply:!0}:{},action:i,projectRoot:j(t,r.projectRoot??"."),format:l}}async function _(e){try{await y(e)}catch{try{if((await y(m(e))).isDirectory())return}catch{}throw new o("story-worktree-path-file-invalid")}throw new o("story-worktree-path-file-exists")}async function T(e,t=new F({projectRoot:e.projectRoot}),a=new O({projectRoot:e.projectRoot,manager:t})){e.pathFile&&await _(e.pathFile);let r;switch(e.action){case"create":r=await t.create({epicId:e.epicId,storyId:e.storyId,dispatchId:e.dispatchId,baseSha:e.baseSha,graphRevision:e.graphRevision,...e.ownerId?{ownerId:e.ownerId}:{}});break;case"adopt":r=await t.adopt({epicId:e.epicId,storyId:e.storyId,dispatchId:e.dispatchId,baseSha:e.baseSha,graphRevision:e.graphRevision,worktreePath:e.worktreePath,...e.ownerId?{ownerId:e.ownerId}:{}});break;case"sync":{let i;if(e.directiveFile)try{i=JSON.parse(await b(e.directiveFile,"utf8"))}catch{return{exitCode:1,payload:{action:"sync",ok:!1,reasonCode:"story-worktree-directive-invalid"}}}r=await t.sync({leaseId:e.leaseId,...e.sha?{integratedSha:e.sha}:{},...i!==void 0?{directive:i}:{}});break}case"status":r=await t.status(e.leaseId?{leaseId:e.leaseId}:e.storyId?{storyId:e.storyId}:{epicId:e.epicId});break;case"release":r=await t.release({leaseId:e.leaseId});break;case"cleanup":r=await a.cleanup({leaseId:e.leaseId,trigger:e.trigger,...e.dryRun?{dryRun:!0}:{}});break;case"recover":r=await a.sweep({...e.epicId?{epicId:e.epicId}:{},...e.dryRun?{dryRun:!0}:{}});break;case"record-push":r=await a.recordPush({leaseId:e.leaseId,remote:e.remote});break;case"rebind-origin":{const{rebindEpicOrigin:i}=await import("../git/epic-origin-rebind.js");r=await i({projectRoot:e.projectRoot,epicId:e.epicId,originBranch:e.originBranch,previousOriginSha:e.baseSha,originSha:e.sha,executionHeadSha:e.executionHeadSha,...e.apply?{apply:!0}:{}});break}case"assert-phase-two":r=await t.assertPhaseTwo({storyId:e.storyId});break}if(!r.ok)return{exitCode:1,payload:{action:e.action,ok:!1,reasonCode:r.reasonCode,...r.conflictPaths?{conflictPaths:r.conflictPaths}:{}}};if(e.pathFile&&r.privatePath)try{await S(e.pathFile,`${r.privatePath}
2
+ `,{flag:"wx",mode:384})}catch{return{exitCode:1,payload:{action:e.action,ok:!1,reasonCode:"story-worktree-path-file-invalid"}}}return{exitCode:0,payload:{action:e.action,ok:!0,value:r.value}}}function I(e,t){if(t==="json")return JSON.stringify(e,null,2);const a=[`story-worktree ${String(e.action)}: ${e.ok?"ok":"refused"}`];return e.reasonCode&&a.push(`reason=${String(e.reasonCode)}`),a.join(" ")}async function B(e){let t;try{t=L(e)}catch(a){const r=a instanceof o?a.reasonCode:"story-worktree-argument-invalid",i=f.includes(e[0])?e[0]:null;return process.stdout.write(`${JSON.stringify({action:i,ok:!1,reasonCode:r})}
3
+ `),2}try{const{exitCode:a,payload:r}=await T(t);return process.stdout.write(`${I(r,t.format)}
4
4
  `),a}catch(a){const r=a instanceof o?a.reasonCode:"story-worktree-internal-error";return process.stdout.write(`${I({action:t.action,ok:!1,reasonCode:r},t.format)}
5
- `),a instanceof o?2:1}}export{y as STORY_WORKTREE_ACTIONS,o as StoryWorktreeArgumentError,W as parseStoryWorktreeArgs,_ as runStoryWorktreeCommand,z as storyWorktreeCliHandler};
5
+ `),a instanceof o?2:1}}export{f as STORY_WORKTREE_ACTIONS,o as StoryWorktreeArgumentError,L as parseStoryWorktreeArgs,T as runStoryWorktreeCommand,B as storyWorktreeCliHandler};
@@ -0,0 +1,20 @@
1
+ export interface EpicOriginRebindInput {
2
+ readonly projectRoot: string;
3
+ readonly epicId: string;
4
+ readonly originBranch: string;
5
+ readonly previousOriginSha: string;
6
+ readonly originSha: string;
7
+ readonly executionHeadSha: string;
8
+ readonly apply?: boolean;
9
+ }
10
+ type RebindReason = `epic-origin-rebind-${string}`;
11
+ type RebindResult = {
12
+ readonly ok: false;
13
+ readonly reasonCode: RebindReason;
14
+ } | {
15
+ readonly ok: true;
16
+ readonly value: Readonly<Record<string, unknown>>;
17
+ };
18
+ /** Explicit root operation for a planning-only epic moved to a different origin. */
19
+ export declare function rebindEpicOrigin(input: EpicOriginRebindInput): Promise<RebindResult>;
20
+ export {};
@@ -0,0 +1 @@
1
+ import{execFile as W}from"node:child_process";import{lstat as F,mkdtemp as G,readFile as M,realpath as B,rm as z,writeFile as C}from"node:fs/promises";import{hostname as J,tmpdir as V}from"node:os";import{join as A,resolve as X}from"node:path";import{isDeepStrictEqual as K,promisify as Z}from"node:util";import{resolveNativeAgentPrivateRuntimePaths as U}from"../continuity/native-agent-store.js";import{loadBetterSqlite3Adapter as Y}from"../continuity/sqlite-store.js";import{applyGitLifecycleRuntimeOverlay as Q,ensureRuntimeEpic as ee,mutateGitLifecycleRuntime as ie,readGitLifecycleRuntime as te}from"./git-lifecycle-store.js";const re=Z(W),ne=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,oe=/^[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/,ae=new Set(["backlog","planned","pending","ready","draft","planning"]),E=64*1024*1024;class T extends Error{reasonCode;constructor(e){super(e),this.reasonCode=e}}function t(r){throw new T(r)}function m(r){return r&&typeof r=="object"&&!Array.isArray(r)?r:void 0}function se(r){return r?.code==="ENOENT"}async function w(r,e){try{const n=await F(r);(!n.isFile()||n.size>e)&&t("epic-origin-rebind-local-evidence-unverified");const s=await M(r);return s.length>e&&t("epic-origin-rebind-local-evidence-unverified"),s}catch(n){if(se(n))return;throw n}}async function P(r,e){const n=await w(A(r,".neocortex","yoloop.lock"),65536);if(n){const i=m(JSON.parse(n.toString("utf8")));(!i||i.ownerKind!=="client"||i.hostname!==J()||!Number.isSafeInteger(i.pid)||Number(i.pid)<=0)&&t("epic-origin-rebind-run-active");try{process.kill(Number(i.pid),0),t("epic-origin-rebind-run-active")}catch(a){if(a.code!=="ESRCH")throw a}}const s=await w(A(r,".neocortex","yoloop-state.json"),4*1024*1024);if(s){const i=m(JSON.parse(s.toString("utf8")));i||t("epic-origin-rebind-local-evidence-unverified");const a=i.pendingContinuationAuthorities;a!==void 0&&(!Array.isArray(a)||a.some(l=>{const c=m(l);return!c||c.epicId===e||typeof c.storyId=="string"&&c.storyId.startsWith(`${e}.`)}))&&t("epic-origin-rebind-authority-pending")}}async function j(r,e){const n=U(r).databasePath,s=await w(n,E),i=await w(`${n}-wal`,E);if(!s){i&&t("epic-origin-rebind-native-evidence-unverified");return}const a=await G(A(V(),"nx-epic-origin-proof-"));try{const l=A(a,"continuity.sqlite");await C(l,s,{mode:384}),i?.length&&await C(`${l}-wal`,i,{mode:384});const c=await Y();c.ok||t("epic-origin-rebind-native-evidence-unverified");const g=c.adapter.open(l,{fileMustExist:!0,readonly:!0});try{g.pragma("quick_check",{simple:!0})!=="ok"&&t("epic-origin-rebind-native-evidence-unverified"),g.prepare(`SELECT 1 FROM native_agent_dispatches WHERE story_id IN (${e.map(()=>"?").join(",")}) LIMIT 1`).get(...e)&&t("epic-origin-rebind-dispatch-exists")}finally{g.close()}const R=await w(n,E),v=await w(`${n}-wal`,E);(!R?.equals(s)||(i?!v?.equals(i):v!==void 0))&&t("epic-origin-rebind-raced")}finally{await z(a,{recursive:!0,force:!0})}}async function be(r){const{epicId:e,originBranch:n,previousOriginSha:s,originSha:i,executionHeadSha:a}=r,l=`epic/${e}`,c=X(r.projectRoot),g=`refs/heads/${n}`,R=`refs/remotes/origin/${n}`,v=`refs/heads/${l}`,d=async(...f)=>(await re("git",f,{cwd:c,timeout:3e4,maxBuffer:4*1024*1024,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_OPTIONAL_LOCKS:"0",GIT_NO_REPLACE_OBJECTS:"1"}})).stdout.trim(),k=async(f,_)=>{try{return await d("merge-base","--is-ancestor",f,_),!0}catch(x){if(x.code===1)return!1;throw x}};try{(!/^P[1-9][0-9]*$/.test(e)||!oe.test(n)||n===l||![s,i,a].every(o=>ne.test(o))||s===i)&&t("epic-origin-rebind-input-invalid"),await d("check-ref-format",g);const f=".neocortex/state.json",_=async()=>{const[o,p,H,L,D]=await Promise.all([d("rev-parse","--show-toplevel"),d("symbolic-ref","--quiet","HEAD"),d("rev-parse","HEAD"),d("rev-parse","--verify",`${R}^{commit}`),d("rev-parse","--is-shallow-repository")]);(await B(o)!==await B(c)||p!==v||D!=="false")&&t("epic-origin-rebind-root-required"),(H!==a||L!==i)&&t("epic-origin-rebind-ref-changed"),await d("for-each-ref","--format=%(refname)",`refs/heads/nx/${e}/`,`refs/remotes/origin/nx/${e}/`,`refs/remotes/origin/${l}`)&&t("epic-origin-rebind-execution-ref-exists"),await d("diff","--name-only","HEAD","--",".",":(exclude).neocortex/continuity/",":(exclude).neocortex/yoloop-state.json",":(exclude).neocortex/yoloop-successor-transition.json",":(exclude).neocortex/yoloop-session-rollover.json")&&t("epic-origin-rebind-checkout-dirty")};await _(),await P(c,e);const x=await d("show",`${a}:${f}`),S=m(JSON.parse(x));S||t("epic-origin-rebind-state-unverified");const h=await te(c,{required:!0});h.schemaVersion!==1&&t("epic-origin-rebind-operational-authority");const q=h.epics[e],O=Q(S,h),u=m(m(O.epics)?.[e]),b=m(q?.origin_binding);(!u||!b||u.branch_mode!=="epic"||u.execution_branch!==l||b.executionBranch!==l||b.originHeadSha!==s||typeof b.originBranch!="string"||u.origin_branch!==b.originBranch)&&t("epic-origin-rebind-binding-mismatch"),await d("cat-file","-e",`${s}^{commit}`),(await k(s,a)||!await k(i,a))&&t("epic-origin-rebind-ancestry-unverified");const $=(await d("diff","--name-only","-z",i,a)).split("\0").filter(Boolean);(!$.includes(`docs/epics/epic-${e}.md`)||$.some(o=>o!==f&&o!=="NEOCORTEX.md"&&!o.startsWith("docs/")))&&t("epic-origin-rebind-planning-only-required");const N=m(O.stories),y=Object.keys(N??{}).filter(o=>o.startsWith(`${e}.`));(y.length===0||y.length>256||!Array.isArray(u.stories)||!K([...u.stories].sort(),[...y].sort())||y.some(o=>{const p=m(N?.[o]);return!p||!ae.has(String(p.status))||p.checkpoint!=null||p.scheduling_checkpoint_evidence!=null||p.last_step!=null||p.pr_number!=null||Array.isArray(p.steps_completed)&&p.steps_completed.length>0||h.stories[o]!==void 0})||u.branch_lease!=null||u.pr_number!=null||Number(u.completed_stories??0)!==0||u.aggregate_qa_receipt!=null||u.head_reconciliation_receipt!=null||u.terminal_git_receipt!=null||u.story_worktree_evidence!=null||Object.values(h.storyWorktrees?.entries??{}).some(o=>o.epicId===e)||h.storyWorktrees?.cleanupReceipts.some(o=>o.epicId===e))&&t("epic-origin-rebind-story-progress"),await j(c,y);const I={schemaVersion:1,kind:"epic-origin-rebind",epicId:e,executionBranch:l,executionHeadSha:a,previousOriginBranch:b.originBranch,previousOriginSha:s,originBranch:n,originSha:i,storyCount:y.length,publicSafe:!0};return r.apply?(await ie(c,o=>{const p=ee(o,e);p.origin_branch=n,p.origin_binding={schemaVersion:2,originBranch:n,originHeadSha:i,executionBranch:l,capturedFrom:"branch-ref",capturedAt:new Date().toISOString()}},{expectedRevision:h.revision,preCommit:async()=>{await d("ls-remote","--exit-code","origin",g,v)!==`${i} ${g}`&&t("epic-origin-rebind-remote-ref-mismatch"),await _(),await j(c,y),await P(c,e)}}),{ok:!0,value:{...I,outcome:"rebound"}}):{ok:!0,value:{...I,outcome:"eligible"}}}catch(f){return f instanceof T?{ok:!1,reasonCode:f.reasonCode}:{ok:!1,reasonCode:f instanceof Error&&f.message==="git-lifecycle-runtime-revision-conflict"?"epic-origin-rebind-raced":"epic-origin-rebind-local-evidence-unverified"}}}export{be as rebindEpicOrigin};
@@ -1,4 +1,4 @@
1
- # 🧠 Neocortex v4.66.53 | OrNexus Team
1
+ # 🧠 Neocortex v4.66.54 | OrNexus Team
2
2
 
3
3
  This project uses Neocortex, a Development Orchestrator.
4
4
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.66.53 | OrNexus Team — Development orchestrator candidate (native-needs-validation)."
3
+ description: "🧠 Neocortex v4.66.54 | OrNexus Team — Development orchestrator candidate (native-needs-validation)."
4
4
  status: native-needs-validation
5
5
  source: https://antigravity.google/docs/subagents
6
6
  tools:
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.66.53 | OrNexus Team"
3
+ description: "🧠 Neocortex v4.66.54 | OrNexus Team"
4
4
  ---
5
5
 
6
6
  <!--
@@ -4,7 +4,7 @@ agent:
4
4
  name: 'Neocortex Root Agent'
5
5
  title: 'Development Orchestrator (Root alias of neocortex)'
6
6
  icon: '>'
7
- version: '4.66.53'
7
+ version: '4.66.54'
8
8
  architecture: 'thin-client'
9
9
  module: stand-alone
10
10
  hasSidecar: false
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex-root
3
- description: "🧠 Neocortex Root Agent v4.66.53 | OrNexus Team"
3
+ description: "🧠 Neocortex Root Agent v4.66.54 | OrNexus Team"
4
4
  color: blue
5
5
  tools:
6
6
  # File operations
@@ -112,7 +112,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
112
112
  ┌────────────────────────────────────────────────────────────┐
113
113
  │ │
114
114
  │ ####### N E O C O R T E X │
115
- │ ### ######## v4.66.53 │
115
+ │ ### ######## v4.66.54 │
116
116
  │ ######### ##### │
117
117
  │ ## ############## Development Orchestrator │
118
118
  │ ## ### ###### ## OrNexus Team │
@@ -101,7 +101,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
101
101
  ┌────────────────────────────────────────────────────────────┐
102
102
  │ │
103
103
  │ ####### N E O C O R T E X │
104
- │ ### ######## v4.66.53 │
104
+ │ ### ######## v4.66.54 │
105
105
  │ ######### ##### │
106
106
  │ ## ############## Development Orchestrator │
107
107
  │ ## ### ###### ## OrNexus Team │
@@ -4,7 +4,7 @@ agent:
4
4
  name: 'Neocortex'
5
5
  title: 'Development Orchestrator'
6
6
  icon: '>'
7
- version: '4.66.53'
7
+ version: '4.66.54'
8
8
  architecture: 'thin-client'
9
9
  module: stand-alone
10
10
  hasSidecar: false
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.66.53 | OrNexus Team"
3
+ description: "🧠 Neocortex v4.66.54 | OrNexus Team"
4
4
  color: blue
5
5
  permissionMode: bypassPermissions
6
6
  tools:
@@ -112,7 +112,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
112
112
  ┌────────────────────────────────────────────────────────────┐
113
113
  │ │
114
114
  │ ####### N E O C O R T E X │
115
- │ ### ######## v4.66.53 │
115
+ │ ### ######## v4.66.54 │
116
116
  │ ######### ##### │
117
117
  │ ## ############## Development Orchestrator │
118
118
  │ ## ### ###### ## OrNexus Team │
@@ -28,7 +28,7 @@ returned instructions.
28
28
 
29
29
  <!-- END: Plugin Conflict Prevention -->
30
30
 
31
- # Neocortex v4.66.53 | OrNexus Team
31
+ # Neocortex v4.66.54 | OrNexus Team
32
32
 
33
33
  You are a Development Orchestrator. All orchestration logic is delivered by the remote Neocortex server.
34
34
 
@@ -1,7 +1,7 @@
1
1
  # Codex custom agent reference:
2
2
  # https://developers.openai.com/codex/subagents
3
3
  name = "neocortex"
4
- description = "🧠 Neocortex v4.66.53 | OrNexus Team — Development orchestrator for direct @neocortex requests."
4
+ description = "🧠 Neocortex v4.66.54 | OrNexus Team — Development orchestrator for direct @neocortex requests."
5
5
  # [P201-EV-CODEX-GEMINI] Approval and sandbox keys are intentionally omitted.
6
6
  # Codex reapplies the parent turn's live sandbox/approval settings, including
7
7
  # --yolo, when spawning this profile. This profile must not claim child-only max.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.66.53 | OrNexus Team"
3
+ description: "🧠 Neocortex v4.66.54 | OrNexus Team"
4
4
  model: inherit
5
5
  readonly: false
6
6
  is_background: false
@@ -115,7 +115,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
115
115
  ┌────────────────────────────────────────────────────────────┐
116
116
  │ │
117
117
  │ ####### N E O C O R T E X │
118
- │ ### ######## v4.66.53 │
118
+ │ ### ######## v4.66.54 │
119
119
  │ ######### ##### │
120
120
  │ ## ############## Development Orchestrator │
121
121
  │ ## ### ###### ## OrNexus Team │
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.66.53 | OrNexus Team — Route explicit Neocortex *commands through the public thin client in DeepSeek Harness."
3
+ description: "🧠 Neocortex v4.66.54 | OrNexus Team — Route explicit Neocortex *commands through the public thin client in DeepSeek Harness."
4
4
  user-invocable: true
5
5
  disable-model-invocation: false
6
6
  ---
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex-root
3
- description: "🧠 Neocortex v4.66.53 | OrNexus Team"
3
+ description: "🧠 Neocortex v4.66.54 | OrNexus Team"
4
4
  kind: local
5
5
  tools:
6
6
  # File operations (Gemini CLI built-ins)
@@ -73,7 +73,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
73
73
  ┌────────────────────────────────────────────────────────────┐
74
74
  │ │
75
75
  │ ####### N E O C O R T E X │
76
- │ ### ######## v4.66.53 │
76
+ │ ### ######## v4.66.54 │
77
77
  │ ######### ##### │
78
78
  │ ## ############## Development Orchestrator │
79
79
  │ ## ### ###### ## OrNexus Team │
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.66.53 | OrNexus Team"
3
+ description: "🧠 Neocortex v4.66.54 | OrNexus Team"
4
4
  kind: local
5
5
  tools:
6
6
  # File operations (Gemini CLI built-ins)
@@ -72,7 +72,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
72
72
  ┌────────────────────────────────────────────────────────────┐
73
73
  │ │
74
74
  │ ####### N E O C O R T E X │
75
- │ ### ######## v4.66.53 │
75
+ │ ### ######## v4.66.54 │
76
76
  │ ######### ##### │
77
77
  │ ## ############## Development Orchestrator │
78
78
  │ ## ### ###### ## OrNexus Team │
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.66.53 | OrNexus Team — Run development orchestration commands through the public thin client."
3
+ description: "🧠 Neocortex v4.66.54 | OrNexus Team — Run development orchestration commands through the public thin client."
4
4
  ---
5
5
 
6
6
  # Neocortex for Grok Build
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.66.53 | OrNexus Team — Development orchestrator candidate (native-needs-validation)."
3
+ description: "🧠 Neocortex v4.66.54 | OrNexus Team — Development orchestrator candidate (native-needs-validation)."
4
4
  status: native-needs-validation
5
5
  source: https://www.kimi.com/code/docs/en/kimi-code-cli/customization/agents.html
6
6
  model_preference: primary
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.66.53 | OrNexus Team — Run Neocortex commands through the public thin client in OpenClaw."
3
+ description: "🧠 Neocortex v4.66.54 | OrNexus Team — Run Neocortex commands through the public thin client in OpenClaw."
4
4
  status: skill-fallback
5
5
  user-invocable: true
6
6
  ---
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex-root
3
- description: "🧠 Neocortex Root Agent v4.66.53 (Pro) | OrNexus Team — Development orchestrator for *yoloop."
3
+ description: "🧠 Neocortex Root Agent v4.66.54 (Pro) | OrNexus Team — Development orchestrator for *yoloop."
4
4
  mode: primary
5
5
  color: "#00B4FF"
6
6
  permission:
@@ -74,7 +74,7 @@ user's own `*yolo @docs/stories/<id>.story.md` is never refused.
74
74
  ┌────────────────────────────────────────────────────────────┐
75
75
  │ │
76
76
  │ ####### N E O C O R T E X │
77
- │ ### ######## v4.66.53 │
77
+ │ ### ######## v4.66.54 │
78
78
  │ ######### ##### │
79
79
  │ ## ############## Development Orchestrator │
80
80
  │ ## ### ###### ## OrNexus Team │
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.66.53 (Pro) | OrNexus Team — Development orchestrator for *yoloop."
3
+ description: "🧠 Neocortex v4.66.54 (Pro) | OrNexus Team — Development orchestrator for *yoloop."
4
4
  mode: primary
5
5
  color: "#00B4FF"
6
6
  permission:
@@ -73,7 +73,7 @@ user's own `*yolo @docs/stories/<id>.story.md` is never refused.
73
73
  ┌────────────────────────────────────────────────────────────┐
74
74
  │ │
75
75
  │ ####### N E O C O R T E X │
76
- │ ### ######## v4.66.53 │
76
+ │ ### ######## v4.66.54 │
77
77
  │ ######### ##### │
78
78
  │ ## ############## Development Orchestrator │
79
79
  │ ## ### ###### ## OrNexus Team │
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: "neocortex"
3
- description: "Neocortex v4.66.53 | OrNexus Team"
3
+ description: "Neocortex v4.66.54 | OrNexus Team"
4
4
  tools:
5
5
  # Read / Edit (built-in tool sets)
6
6
  - read
@@ -82,7 +82,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
82
82
  ┌────────────────────────────────────────────────────────────┐
83
83
  │ │
84
84
  │ ####### N E O C O R T E X │
85
- │ ### ######## v4.66.53 │
85
+ │ ### ######## v4.66.54 │
86
86
  │ ######### ##### │
87
87
  │ ## ############## Development Orchestrator │
88
88
  │ ## ### ###### ## OrNexus Team │