@ornexus/neocortex 4.60.54 → 4.60.56

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 (53) hide show
  1. package/dist/sbom.cdx.json +23 -23
  2. package/install.ps1 +1 -1
  3. package/install.sh +1 -1
  4. package/package.json +5 -2
  5. package/packages/client/dist/cli.js +0 -0
  6. package/packages/client/dist/commands/invoke.d.ts +32 -0
  7. package/packages/client/dist/commands/invoke.js +69 -60
  8. package/packages/client/dist/generated/command-registry.generated.d.ts +2 -2
  9. package/packages/client/dist/generated/command-registry.generated.js +1 -1
  10. package/packages/client/dist/generated/public-projections.generated.d.ts +20 -20
  11. package/packages/client/dist/generated/public-projections.generated.js +1 -1
  12. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +6 -0
  13. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -4
  14. package/packages/client/dist/private-execution/clean-baseline.d.ts +12 -0
  15. package/packages/client/dist/private-execution/clean-baseline.js +2 -0
  16. package/packages/client/dist/private-execution/codex-executor.d.ts +65 -0
  17. package/packages/client/dist/private-execution/codex-executor.js +2 -0
  18. package/packages/client/dist/private-execution/delivery.d.ts +74 -0
  19. package/packages/client/dist/private-execution/delivery.js +3 -0
  20. package/packages/client/dist/private-execution/isolated-admission.d.ts +13 -0
  21. package/packages/client/dist/private-execution/isolated-admission.js +2 -0
  22. package/packages/client/dist/private-execution/isolated-session.d.ts +41 -0
  23. package/packages/client/dist/private-execution/isolated-session.js +2 -0
  24. package/packages/client/dist/private-execution/isolated-workspace.d.ts +13 -0
  25. package/packages/client/dist/private-execution/isolated-workspace.js +1 -0
  26. package/packages/client/dist/private-execution/root-checkpoint.d.ts +15 -0
  27. package/packages/client/dist/private-execution/root-checkpoint.js +1 -0
  28. package/packages/client/dist/resolvers/remote-resolver.js +1 -1
  29. package/packages/client/dist/runner-cli.js +0 -0
  30. package/packages/client/dist/yolo/change-evidence-collector.d.ts +6 -0
  31. package/packages/client/dist/yolo/change-evidence-collector.js +1 -0
  32. package/packages/client/dist/yolo/spec-envelope-collector.d.ts +11 -0
  33. package/packages/client/dist/yolo/spec-envelope-collector.js +5 -0
  34. package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +1 -1
  35. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1
  36. package/packages/shared/dist/frontmatter-context-contract.js +326 -0
  37. package/packages/shared/dist/generated/command-registry.generated.js +2 -2
  38. package/packages/shared/dist/generated/invocation-schema.generated.js +16 -4
  39. package/packages/shared/dist/generated/public-projections.generated.js +18 -18
  40. package/packages/shared/dist/invocation/index.d.ts +1 -1
  41. package/packages/shared/dist/yolo/change-evidence.js +44 -0
  42. package/packages/shared/dist/yolo/spec-envelope.js +161 -0
  43. package/targets-stubs/antigravity/gemini.md +1 -1
  44. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  45. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  46. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  47. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  48. package/targets-stubs/claude-code/neocortex.md +2 -2
  49. package/targets-stubs/codex/AGENTS.md +1 -1
  50. package/targets-stubs/cursor/agent.md +2 -2
  51. package/targets-stubs/gemini-cli/agent.md +2 -2
  52. package/targets-stubs/opencode/neocortex-root.md +1 -1
  53. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,52 +1,56 @@
1
- import{createHash as Ne,randomUUID as qe}from"node:crypto";import{execFileSync as ke}from"node:child_process";import{existsSync as Ce,readFileSync as Ae,renameSync as Ln,unlinkSync as xn,writeFileSync as Et,mkdirSync as Ct,statSync as Dn}from"node:fs";import{join as te}from"node:path";import{homedir as Pe}from"node:os";import{LicenseClient as Pn}from"../license/license-client.js";import{EncryptedCache as Ke}from"../cache/encrypted-cache.js";import{NoOpCache as At}from"../types/index.js";import{resolveClientPreFlightTrigger as St,TierAwareClient as jn}from"../tier/tier-aware-client.js";import{COMMAND_REGISTRY_CHECKSUM as me,COMMAND_REGISTRY_VERSION as Ie,GENERATED_CLIENT_COMMANDS as Mn}from"../generated/command-registry.generated.js";import{loadSecureConfig as Rt}from"../config/secure-config.js";import{DEFAULT_SERVER_URL as Un}from"../constants.js";import{detectFirstRunLocale as Vn,renderFirstRunMessage as Bn}from"../i18n/first-run.js";import{humanizeError as wt,formatHumanizedError as Tt,detectErrorLocale as bt}from"../errors/error-messages.js";import{degradeStateSnapshotForPayloadLimit as $n,projectStateSnapshotForInvoke as vt,projectStateSnapshotResultV2ForInvoke as Hn}from"../state/project-state-snapshot.js";import{isInlineYoloMaterialization as Wn,maybeRepairStateJsonBeforeInvoke as Fn,StateRepairHardStopError as Gn}from"../state/state-json-repair.js";import{StructuralDagError as Ot}from"../state/structural-dag-projection.js";import{RUNNER_BOOTSTRAP_POLICY_REASON_CODES as Yn,classifyRunnerBootstrapPolicyFromArgs as Jn}from"../continuity/runner-bootstrap-policy.js";import{RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES as zn,ensureRunnerSchedulerBootstrap as qn}from"../runner/scheduler.js";import{CONTINUITY_INVOKE_WATCH_DEFAULT_LIMIT as Nt,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_IDLE_POLLS as kt,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_POLLS as Lt,CONTINUITY_INVOKE_WATCH_DEFAULT_POLL_INTERVAL_MS as xt,openContinuityClientStateStore as Kn}from"../continuity/continuity-client-state-store.js";import{isLocalJobsConsoleArgs as Xn,runLocalJobsConsoleCommand as Zn}from"../runner/local-console.js";import{detectNativeHostAttestation as Qn,detectPlatform as er}from"../adapters/platform-detector.js";import{signNxInvokeRequest as tr}from"../../../shared/dist/nx-invoke-signature.js";import{CLIENT_VERSION as Se}from"../version.js";import{createCapabilityCache as Dt,executeInvokeQueryTransport as Pt,executeSecondaryNetworkMutation as nr}from"../effects/invoke-effect-gateways.js";import{STRICT_READ_ONLY_POLICY as rr,STRICT_READ_ONLY_CLIENT_PROJECTION as jt,STRICT_READ_ONLY_SERVER_PROJECTION as or,StrictReadOnlyError as Re,canonicalizeInvokeEffects as ir,createInvokeEffectContext as sr,verifyStrictReadOnlyReceipt as ar}from"../../../shared/dist/strict-readonly.js";import{admitInvocation as cr,assertInvokeInputEnvelopeV2 as dr,assertProjectIdentityMigrationReceiptV1 as ur,buildProjectIdentityPublicDiagnostic as we,createInvocationAdmissionReceipt as lr,projectInvokeInputEvidenceV1 as Mt,verifyStrictDiagnoseReceiptV1 as pr}from"../../../shared/dist/invocation/index.js";import{buildInvokeInputEnvelope as je,InvokeInputDecodeError as fr}from"../invocation/invoke-input.js";import{acknowledgeProjectIdentityMigration as gr,finalizeProjectIdentityMigration as hr,prepareProjectIdentityMigration as mr,ProjectIdentityMigrationError as Xe,readProjectIdentityMigrationPhase as Ir}from"../migrations/project-identity.js";import{probeProjectIdentityMigrationCapability as yr}from"../migrations/project-identity-capability.js";import{normalizeYoloopStoryPlanningEvidence as _r}from"../../../shared/dist/yoloop/planning-graph.js";import{normalizeContinuousWriteRef as Me}from"../../../shared/dist/yoloop/wave-decision-receipt.js";import{applyGitLifecycleRuntimeOverlay as Ut,classifyGitLifecycleStoryCheckpointProjectionSync as Er,ensureGitLifecycleRuntimeInitialized as Cr,executeP205TransientAuthorities as Ar,persistGitLifecycleGraphAuthority as Sr,P205_COMPLETE_COMMAND as Rr,gitLifecycleStoryWriteSet as Vt,readGitLifecycleRuntimeSync as Ze,verifyLegacyCheckpointMigrationCandidateSync as wr}from"../git/git-lifecycle-store.js";const Ue=te(Pe(),".neocortex"),Qe=te(Ue,"cache"),Bt=te(Qe,"menu-cache.json"),$t=1440*60*1e3,Ht=3e4,Wt=256*1024,Ft=Wt,Gt=.8,de="[REDACTED]",Tr=1e5,ye=2e3,br=200,vr=200,Or=12,Nr=/(?:promptBody|workflow|workflowGraph|stepBody|privateUrl|rawLog|secret|credential|licenseKey|apiKey|internalRouting|serverOnly|proprietary|protected)/i,kr=/(?:PRIVATE|PROTECTED|SERVER_ONLY)[-_\s]*(?:PROMPT|PROMPT_BODY|WORKFLOW|WORKFLOW_GRAPH|STEP_BODY|STEP|ROUTING)\s*[:=][^\n\r]*/gi,Lr=/(?: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,et=Math.floor(Wt*Gt),Yt=te(Ue,".first-run-shown"),xr="pending-epic-claims.json",Jt=64;function zt(e){return te(e,".neocortex",xr)}function Ve(e){const t=zt(e);if(!Ce(t))return{schemaVersion:1,operations:{}};const n=JSON.parse(Ae(t,"utf8"));if(!n||typeof n!="object"||Array.isArray(n))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const r=n;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>Jt)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");for(const[o,i]of Object.entries(r.operations)){if(!/^[a-f0-9]{64}$/.test(o)||!i||typeof i!="object"||Array.isArray(i))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const s=i;if(typeof s.idempotencyKey!="string"||!/^[0-9a-f-]{36}$/.test(s.idempotencyKey)||typeof s.createdAt!="string")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(s.claimId!==void 0&&(typeof s.claimId!="string"||!/^[0-9a-f-]{36}$/.test(s.claimId))||s.epicId!==void 0&&(typeof s.epicId!="string"||!/^P[1-9][0-9]*$/.test(s.epicId))||s.claimId===void 0!=(s.epicId===void 0))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE")}return n}function tt(e,t){const n=zt(e);Ct(te(e,".neocortex"),{recursive:!0,mode:448});const r=`${n}.${process.pid}.${qe()}.tmp`;Et(r,`${JSON.stringify(t)}
2
- `,{encoding:"utf8",mode:384,flag:"wx"}),Ln(r,n)}function Dr(e){return Ne("sha256").update(`nx-epic-logical-operation-v1\0${JSON.stringify({command:"create-epic",args:e})}`,"utf8").digest("hex")}function Pr(e,t){const n=Dr(t),r=Ve(e),o=r.operations[n];if(o)return{key:o.idempotencyKey,fingerprint:n};if(Object.keys(r.operations).length>=Jt)throw new Error("EPIC_CLAIM_CAPACITY_EXCEEDED");const i=qe(),s={...r.operations,[n]:{idempotencyKey:i,createdAt:new Date().toISOString()}};return tt(e,{schemaVersion:1,operations:s}),{key:i,fingerprint:n}}function jr(e,t){const n=Ve(e);if(!n.operations[t])return;const r={...n.operations};delete r[t],tt(e,{schemaVersion:1,operations:r})}function Mr(e,t,n,r){if(!/^[0-9a-f-]{36}$/.test(n)||!/^P[1-9][0-9]*$/.test(r))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const o=Ve(e),i=o.operations[t];if(!i)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");tt(e,{schemaVersion:1,operations:{...o.operations,[t]:{...i,claimId:n,epicId:r}}})}function Ur(){try{if(Ce(Yt))return;const e=Vn(),t=Bn(e);process.stderr.write(t);try{Ct(Ue,{recursive:!0}),Et(Yt,new Date().toISOString(),"utf-8")}catch{}}catch{}}function nt(e,t=process.cwd()){return e&&e.trim().length>0?e:t}function Vr(e){return cr(e,{registryVersion:Ie,registryChecksum:me})}const Br=new Set(["completed","aborted","cancelled"]),$r=new Set(["watch-target-missing","watch-target-malformed","watch-target-ambiguous","watch-target-multiple"]),$=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"}),F=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"}),O=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"}),qt=240,Hr=/(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 Wr(e){return e.replace(/[\w.+-]+@[\w-]+\.[\w.-]+/g,de).replace(/(?:sk|pk|whsec|nxk)[-_](?:test|live|ant|proj|pro|free|enterprise)?[-_]?[A-Za-z0-9_-]{16,}/g,de).replace(/NX-[FPE]-[a-f0-9]{24}-[a-f0-9]{4}/g,de).replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,de).replace(kr,de).replace(Lr,de)}function Z(e,t){const n=Wr(e);return n.length<=t?n:`${n.slice(0,t)}\u2026[TRUNCATED:${n.length-t}]`}function rt(e,t=0,n=new WeakSet){if(t>Or)return"[MAX_DEPTH]";if(e==null)return e;if(typeof e=="string")return Z(e,ye);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,br).map(o=>rt(o,t+1,n));const r={};for(const[o,i]of Object.entries(e).slice(0,vr)){if(Nr.test(o)){r[o]=de;continue}const s=rt(i,t+1,n);s!==void 0&&(r[o]=s)}return r}finally{n.delete(e)}}}function ot(e,t){return{instructions:Z(e??"",Tr),metadata:t?rt(t):void 0}}class Be extends Error{reason;source;byteLength;code;constructor(t,n,r,o,i){super(n),this.reason=r,this.source=o,this.byteLength=i,this.name="InvokeCliInputError",this.code=t}}function Fr(e){return/^\s*\*?(?:arch-plan|ui-ux-review)(?:\s|$)/i.test(e)&&Gr(e,"--project-evidence")}function Gr(e,t){let n=null,r=-1,o=!1,i=!1;for(let s=0;s<=e.length;s+=1){const c=e[s];if(s===e.length||!n&&/\s/.test(c??"")){if(r>=0&&!o&&e.slice(r,s)===t)return!0;r=-1,o=!1,i=!1;continue}if(r<0&&(r=s),i){i=!1;continue}if(c==="\\"){i=!0;continue}(c==='"'||c==="'")&&(o=!0,n=n===c?null:n??c)}return!1}const Yr=/(?:^|\s)codex(?:-cli)?\s+([A-Za-z0-9][A-Za-z0-9._+-]{0,63})(?:\s|$)/i;function Jr(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 ke("codex",["--version"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim().match(Yr)?.[1]??null}catch{return null}}class it 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 st 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 at=!1;function zr(e){const t=[];if(!e||typeof e!="object")return t;const n=e,r=n.planning;if(r&&(r.current!==void 0||Array.isArray(r.history))&&t.push({code:"PLANNING_LEGACY",message:"legacy `planning.current`/`planning.history` detected (not read by v1 orchestrator)"}),Array.isArray(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[i,s]of Object.entries(n.epics)){const c=s;if(c&&c.stories!==void 0&&!Array.isArray(c.stories)){t.push({code:"EPIC_STORIES_NOT_ARRAY",message:`epic "${i}" has non-array \`stories\` field (expected string[] of story IDs)`});break}}const o=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)||r&&r.current!==void 0;return n.schema_version===void 0?o&&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 qr(e){if(!(at||e.length===0)){at=!0;try{const t=e.map(n=>` - ${n.message}`).join(`
1
+ import{createHash as Ue,randomUUID as it}from"node:crypto";import{execFileSync as Te}from"node:child_process";import{existsSync as Oe,readFileSync as xe,renameSync as Hr,unlinkSync as Wr,writeFileSync as bt,mkdirSync as Tt,statSync as Fr}from"node:fs";import{join as ae}from"node:path";import{homedir as Fe}from"node:os";import{isPrivateExecutionPublicEnvelope as Gr}from"../private-execution/delivery.js";import{LicenseClient as Yr}from"../license/license-client.js";import{EncryptedCache as st}from"../cache/encrypted-cache.js";import{NoOpCache as Ot}from"../types/index.js";import{resolveClientPreFlightTrigger as xt,TierAwareClient as Jr}from"../tier/tier-aware-client.js";import{COMMAND_REGISTRY_CHECKSUM as Re,COMMAND_REGISTRY_VERSION as we,GENERATED_CLIENT_COMMANDS as zr}from"../generated/command-registry.generated.js";import{loadSecureConfig as kt}from"../config/secure-config.js";import{DEFAULT_SERVER_URL as qr}from"../constants.js";import{detectFirstRunLocale as Kr,renderFirstRunMessage as Xr}from"../i18n/first-run.js";import{humanizeError as Nt,formatHumanizedError as Lt,detectErrorLocale as Pt}from"../errors/error-messages.js";import{degradeStateSnapshotForPayloadLimit as Zr,projectStateSnapshotForInvoke as Dt,projectStateSnapshotResultV2ForInvoke as Qr}from"../state/project-state-snapshot.js";import{isInlineYoloMaterialization as en,maybeRepairStateJsonBeforeInvoke as tn,StateRepairHardStopError as rn}from"../state/state-json-repair.js";import{StructuralDagError as jt}from"../state/structural-dag-projection.js";import{RUNNER_BOOTSTRAP_POLICY_REASON_CODES as nn,classifyRunnerBootstrapPolicyFromArgs as on}from"../continuity/runner-bootstrap-policy.js";import{RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES as sn,ensureRunnerSchedulerBootstrap as an}from"../runner/scheduler.js";import{CONTINUITY_INVOKE_WATCH_DEFAULT_LIMIT as Mt,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_IDLE_POLLS as Ut,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_POLLS as Vt,CONTINUITY_INVOKE_WATCH_DEFAULT_POLL_INTERVAL_MS as Bt,openContinuityClientStateStore as cn}from"../continuity/continuity-client-state-store.js";import{isLocalJobsConsoleArgs as dn,runLocalJobsConsoleCommand as un}from"../runner/local-console.js";import{detectNativeHostAttestation as ln,detectPlatform as pn}from"../adapters/platform-detector.js";import{signNxInvokeRequest as fn}from"../../../shared/dist/nx-invoke-signature.js";import{CLIENT_VERSION as ke}from"../version.js";import{createCapabilityCache as $t,executeInvokeQueryTransport as Ht,executeSecondaryNetworkMutation as hn}from"../effects/invoke-effect-gateways.js";import{STRICT_READ_ONLY_POLICY as gn,STRICT_READ_ONLY_CLIENT_PROJECTION as Wt,STRICT_READ_ONLY_SERVER_PROJECTION as mn,StrictReadOnlyError as Ne,canonicalizeInvokeEffects as yn,createInvokeEffectContext as In,verifyStrictReadOnlyReceipt as En}from"../../../shared/dist/strict-readonly.js";import{admitInvocation as _n,assertInvokeInputEnvelopeV2 as Cn,assertProjectIdentityMigrationReceiptV1 as Sn,buildProjectIdentityPublicDiagnostic as Le,createInvocationAdmissionReceipt as An,projectInvokeInputEvidenceV1 as Ft,verifyStrictDiagnoseReceiptV1 as Rn}from"../../../shared/dist/invocation/index.js";import{buildInvokeInputEnvelope as Ge,InvokeInputDecodeError as wn}from"../invocation/invoke-input.js";import{acknowledgeProjectIdentityMigration as vn,finalizeProjectIdentityMigration as bn,prepareProjectIdentityMigration as Tn,ProjectIdentityMigrationError as at,readProjectIdentityMigrationPhase as On}from"../migrations/project-identity.js";import{probeProjectIdentityMigrationCapability as xn}from"../migrations/project-identity-capability.js";import{normalizeYoloopStoryPlanningEvidence as kn}from"../../../shared/dist/yoloop/planning-graph.js";import{normalizeContinuousWriteRef as Ye}from"../../../shared/dist/yoloop/wave-decision-receipt.js";import{applyGitLifecycleRuntimeOverlay as Gt,classifyGitLifecycleStoryCheckpointProjectionSync as Nn,ensureGitLifecycleRuntimeInitialized as Ln,executeP205TransientAuthorities as Pn,persistGitLifecycleGraphAuthority as Dn,P205_COMPLETE_COMMAND as jn,gitLifecycleStoryWriteSet as Yt,readGitLifecycleRuntimeSync as Je,verifyLegacyCheckpointMigrationCandidateSync as Mn}from"../git/git-lifecycle-store.js";const ze=ae(Fe(),".neocortex"),ct=ae(ze,"cache"),Jt=ae(ct,"menu-cache.json"),zt=1440*60*1e3,qt=3e4,Kt=256*1024,Xt=Kt,Zt=.8,me="[REDACTED]",Un=1e5,ve=2e3,Vn=200,Bn=200,$n=12,Hn=/(?:promptBody|workflow|workflowGraph|stepBody|privateUrl|rawLog|secret|credential|licenseKey|apiKey|internalRouting|serverOnly|proprietary|protected)/i,Wn=/(?:PRIVATE|PROTECTED|SERVER_ONLY)[-_\s]*(?:PROMPT|PROMPT_BODY|WORKFLOW|WORKFLOW_GRAPH|STEP_BODY|STEP|ROUTING)\s*[:=][^\n\r]*/gi,Fn=/(?: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,dt=Math.floor(Kt*Zt),Qt=ae(ze,".first-run-shown"),Gn="pending-epic-claims.json",er=64;function tr(e){return ae(e,".neocortex",Gn)}function qe(e){const t=tr(e);if(!Oe(t))return{schemaVersion:1,operations:{}};const r=JSON.parse(xe(t,"utf8"));if(!r||typeof r!="object"||Array.isArray(r))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const n=r;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>er)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");for(const[o,i]of Object.entries(n.operations)){if(!/^[a-f0-9]{64}$/.test(o)||!i||typeof i!="object"||Array.isArray(i))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const a=i;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 r}function ut(e,t){const r=tr(e);Tt(ae(e,".neocortex"),{recursive:!0,mode:448});const n=`${r}.${process.pid}.${it()}.tmp`;bt(n,`${JSON.stringify(t)}
2
+ `,{encoding:"utf8",mode:384,flag:"wx"}),Hr(n,r)}function Yn(e){return Ue("sha256").update(`nx-epic-logical-operation-v1\0${JSON.stringify({command:"create-epic",args:e})}`,"utf8").digest("hex")}function Jn(e,t){const r=Yn(t),n=qe(e),o=n.operations[r];if(o)return{key:o.idempotencyKey,fingerprint:r};if(Object.keys(n.operations).length>=er)throw new Error("EPIC_CLAIM_CAPACITY_EXCEEDED");const i=it(),a={...n.operations,[r]:{idempotencyKey:i,createdAt:new Date().toISOString()}};return ut(e,{schemaVersion:1,operations:a}),{key:i,fingerprint:r}}function zn(e,t){const r=qe(e);if(!r.operations[t])return;const n={...r.operations};delete n[t],ut(e,{schemaVersion:1,operations:n})}function qn(e,t,r,n){if(!/^[0-9a-f-]{36}$/.test(r)||!/^P[1-9][0-9]*$/.test(n))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const o=qe(e),i=o.operations[t];if(!i)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");ut(e,{schemaVersion:1,operations:{...o.operations,[t]:{...i,claimId:r,epicId:n}}})}function Kn(){try{if(Oe(Qt))return;const e=Kr(),t=Xr(e);process.stderr.write(t);try{Tt(ze,{recursive:!0}),bt(Qt,new Date().toISOString(),"utf-8")}catch{}}catch{}}function lt(e,t=process.cwd()){return e&&e.trim().length>0?e:t}function Xn(e){return _n(e,{registryVersion:we,registryChecksum:Re})}const Zn=new Set(["completed","aborted","cancelled"]),Qn=new Set(["watch-target-missing","watch-target-malformed","watch-target-ambiguous","watch-target-multiple"]),Y=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"}),K=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"}),O=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"}),rr=240,eo=/(https?:\/\/\S+|ghp_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|-----BEGIN [A-Z ]*PRIVATE KEY-----|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=|raw[_-]?log|transcript|stack\s*trace|stderr:|stdout:|system prompt|prompt body|workflow body|step body|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|VENDOR_CORPUS|P180[_-]?SYNTHETIC[_-]?CONTINUITY|P185[_-]?SYNTHETIC[_-]?CONTINUITY|P187[_-]?SYNTHETIC[_-]?(?:CONTINUITY|RUNNER|WATCH))/i;function to(e){return e.replace(/[\w.+-]+@[\w-]+\.[\w.-]+/g,me).replace(/(?:sk|pk|whsec|nxk)[-_](?:test|live|ant|proj|pro|free|enterprise)?[-_]?[A-Za-z0-9_-]{16,}/g,me).replace(/NX-[FPE]-[a-f0-9]{24}-[a-f0-9]{4}/g,me).replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,me).replace(Wn,me).replace(Fn,me)}function ie(e,t){const r=to(e);return r.length<=t?r:`${r.slice(0,t)}\u2026[TRUNCATED:${r.length-t}]`}function pt(e,t=0,r=new WeakSet){if(t>$n)return"[MAX_DEPTH]";if(e==null)return e;if(typeof e=="string")return ie(e,ve);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(r.has(e))return"[CIRCULAR]";r.add(e);try{if(Array.isArray(e))return e.slice(0,Vn).map(o=>pt(o,t+1,r));const n={};for(const[o,i]of Object.entries(e).slice(0,Bn)){if(Hn.test(o)){n[o]=me;continue}const a=pt(i,t+1,r);a!==void 0&&(n[o]=a)}return n}finally{r.delete(e)}}}function ft(e,t){return{instructions:ie(e??"",Un),metadata:t?pt(t):void 0}}class Ke extends Error{reason;source;byteLength;code;constructor(t,r,n,o,i){super(r),this.reason=n,this.source=o,this.byteLength=i,this.name="InvokeCliInputError",this.code=t}}function ro(e){return/^\s*\*?(?:arch-plan|ui-ux-review)(?:\s|$)/i.test(e)&&no(e,"--project-evidence")}function no(e,t){let r=null,n=-1,o=!1,i=!1;for(let a=0;a<=e.length;a+=1){const c=e[a];if(a===e.length||!r&&/\s/.test(c??"")){if(n>=0&&!o&&e.slice(n,a)===t)return!0;n=-1,o=!1,i=!1;continue}if(n<0&&(n=a),i){i=!1;continue}if(c==="\\"){i=!0;continue}(c==='"'||c==="'")&&(o=!0,r=r===c?null:r??c)}return!1}const oo=/(?:^|\s)codex(?:-cli)?\s+([A-Za-z0-9][A-Za-z0-9._+-]{0,63})(?:\s|$)/i;function io(e,t){if(e.targetId!=="codex")return null;const r=t.CODEX_VERSION?.trim();if(r&&/^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/.test(r))return r;try{return Te("codex",["--version"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim().match(oo)?.[1]??null}catch{return null}}class ht 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 gt 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 mt=!1;function so(e){const t=[];if(!e||typeof e!="object")return t;const r=e,n=r.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(r.stories)&&t.push({code:"STORIES_AS_ARRAY",message:"`stories` is an Array (expected Object keyed by story ID)"}),r.epics&&typeof r.epics=="object"&&!Array.isArray(r.epics))for(const[i,a]of Object.entries(r.epics)){const c=a;if(c&&c.stories!==void 0&&!Array.isArray(c.stories)){t.push({code:"EPIC_STORIES_NOT_ARRAY",message:`epic "${i}" has non-array \`stories\` field (expected string[] of story IDs)`});break}}const o=r.epics&&typeof r.epics=="object"&&Object.keys(r.epics).length>0||r.stories&&typeof r.stories=="object"&&!Array.isArray(r.stories)&&Object.keys(r.stories).length>0||Array.isArray(r.stories)||n&&n.current!==void 0;return r.schema_version===void 0?o&&t.push({code:"SCHEMA_VERSION_MISSING",message:"`schema_version` field missing (expected: `schema_version: 1`)"}):r.schema_version!==1&&t.push({code:"SCHEMA_VERSION_OUTDATED",message:`schema_version=${String(r.schema_version)} (expected: 1)`}),t}function ao(e){if(!(mt||e.length===0)){mt=!0;try{const t=e.map(r=>` - ${r.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 Ki(){at=!1}function Kt(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Kr(e){return e==="active"||e==="archived"||e==="rolled-back"||e==="synthetic"||e==="orphan"?e:void 0}function Xt(e){return e==="create-epic"||e==="discovered"?e:void 0}function J(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Xr(e){const t={};let n=!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(i=>Me(i)===void 0)){n=!0;continue}t[r]=o.map(i=>Me(i))}if(e.planning!==void 0)try{if(!m(e.planning))throw new Error("planning-shape");const r=e.planning;for(const s of["claims","semanticArtifacts"]){if(r[s]===void 0)continue;const c=r[s];if(!Array.isArray(c)||c.length>128||c.some(l=>!m(l)||Me(l.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 s of r.attempts??[]){if(!m(s)||!Array.isArray(s.reasonCodes)||s.reasonCodes.length>32||s.reasonCodes.some(c=>typeof c!="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(c)))throw new Error("planning-attempt-reasons");if(s.discoveredClaims!==void 0&&(!Array.isArray(s.discoveredClaims)||s.discoveredClaims.length>128||s.discoveredClaims.some(c=>!m(c)||Me(c.ref)===void 0)))throw new Error("planning-attempt-claims")}const{graphRevision:o,...i}=_r(r);t.planning=i}catch{n=!0}return n&&(t.planning={schemaVersion:1,dependencyBasis:"unknown",claims:[],semanticArtifacts:[]}),t}function m(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ue(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function U(e){if(typeof e!="string")return;const t=e.trim();if(t)return t.replace(/[^a-z0-9_.:-]+/gi,"_").slice(0,120)}function j(e){if(typeof e!="string")return;const t=e.trim(),n=U(e);return n===t?n:void 0}function H(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(n=>!n||n.startsWith(".")||n.endsWith(".lock")))return t}function A(e){return typeof e=="string"&&/^[0-9a-f]{7,64}$/i.test(e)?e:void 0}function z(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 le(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 $e(e,t){if(!m(e))return;const n={};for(const r of t){const o=e[r];if(typeof o=="boolean")n[r]=o;else if(typeof o=="number"&&Number.isFinite(o))n[r]=o;else if(typeof o=="string"){const i=U(o);i&&(n[r]=i)}}return Object.keys(n).length>0?n:void 0}function He(e){return e==="epic"||e==="story"?e:void 0}function Zt(e){if(!m(e)||e.schemaVersion!==1)return;const t=j(e.ownerStoryId),n=j(e.sessionId),r=j(e.idempotencyKey),o=z(e.acquiredAt),i=z(e.expiresAt);if(!(!t||!n||!r||!o||!i||Date.parse(i)<=Date.parse(o)))return{schemaVersion:1,ownerStoryId:t,sessionId:n,idempotencyKey:r,acquiredAt:o,expiresAt:i}}function Qt(e){if(!m(e)||e.schemaVersion!==1)return;const t=j(e.storyId),n=j(e.epicId),r=H(e.branch),o=A(e.baseSha),i=A(e.headSha),s=j(e.idempotencyKey),c=z(e.recordedAt),l=J(e.commits).map(A).filter(T=>!!T).slice(0,256),p=J(e.receiptRefs).map(le).filter(T=>!!T).slice(0,256),g=e.dispatchId===void 0?void 0:j(e.dispatchId),C=e.bundleId===void 0?void 0:j(e.bundleId),f=e.bundleDigest===void 0?void 0:A(e.bundleDigest),d=e.graphRevision===void 0?void 0:A(e.graphRevision),h=e.claimRevision===void 0?void 0:j(e.claimRevision),S=Zr(e.qaReceipt),E=Qr(e.reviewReceipt);if(!(!t||!n||!t.startsWith(`${n}.`)||!r||!o||!i||o===i||!s||!c||l.length===0||p.length===0||!Array.isArray(e.commits)||l.length!==e.commits.length||e.commits.length>256||!Array.isArray(e.receiptRefs)||p.length!==e.receiptRefs.length||e.receiptRefs.length>256||e.dispatchId!==void 0&&!g||e.bundleId!==void 0&&!C||e.bundleDigest!==void 0&&(!f||f.length!==64)||e.graphRevision!==void 0&&(!d||d.length!==64)||e.claimRevision!==void 0&&!h||e.qaVerdict!=="passed"&&e.qaVerdict!=="blocked"||!["approved","changes-requested","pending"].includes(String(e.reviewVerdict))||!S||e.reviewVerdict!=="pending"&&!E||e.reviewVerdict==="pending"&&E||S.verdict!==e.qaVerdict||E&&E.verdict!==e.reviewVerdict||!nn(S,{storyId:t,epicId:n,baseSha:o,headSha:i,bundleDigest:f,graphRevision:d})||E&&(!nn(E,{storyId:t,epicId:n,baseSha:o,headSha:i,bundleDigest:f,graphRevision:d})||E.qaReceiptRef!==S?.receiptRef||E.receiptRef===S?.receiptRef)||!p.includes(String(S.receiptRef))||E&&(!p.includes(String(E.receiptRef))||Date.parse(String(E.reviewedAt))<Date.parse(String(S.checkedAt)))))return{schemaVersion:1,storyId:t,epicId:n,branch:r,baseSha:o,headSha:i,idempotencyKey:s,...g?{dispatchId:g}:{},...C?{bundleId:C}:{},...f?{bundleDigest:f}:{},...d?{graphRevision:d}:{},...h?{claimRevision:h}:{},qaVerdict:e.qaVerdict,reviewVerdict:e.reviewVerdict,...S?{qaReceipt:S}:{},...E?{reviewReceipt:E}:{},recordedAt:c,commits:l,receiptRefs:p}}function Zr(e){if(!m(e)||e.schemaVersion!==1||e.kind!=="story_qa_evidence"||e.producer!=="local-yolo-tdd"||e.evidenceVersion!==void 0&&e.evidenceVersion!=="git-immutable-v1"&&e.evidenceVersion!=="p205-execution-v2"||!["passed","blocked"].includes(String(e.verdict)))return;const t=j(e.storyId),n=j(e.epicId),r=A(e.baseSha),o=A(e.headSha),i=A(e.bundleDigest),s=A(e.graphRevision),c=A(e.sourceEvidenceDigest),l=z(e.checkedAt),p=le(e.receiptRef),g=e.evidenceVersion==="p205-execution-v2"&&e.contract==="P205-CI-02"?e.contract:void 0,C=e.evidenceVersion==="p205-execution-v2"&&e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,f=e.evidenceVersion==="p205-execution-v2"?A(e.manifestDigest):void 0,d=e.evidenceVersion==="p205-execution-v2"?A(e.resultDigest):void 0,h=e.evidenceVersion==="p205-execution-v2"?J(e.gateIds).map(j).filter(S=>!!S).slice(0,64):void 0;if(!(!t||!n||!r||!o||!i||i.length!==64||!s||s.length!==64||!c||c.length!==64||!l||!p||e.evidenceVersion==="p205-execution-v2"&&(!g||C!=="node scripts/test-root.mjs --gate complete"||!f||f.length!==64||!d||d.length!==64||!Array.isArray(e.gateIds)||!h||h.length===0||h.length!==e.gateIds.length)))return{schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",...e.evidenceVersion?{evidenceVersion:e.evidenceVersion}:{},storyId:t,epicId:n,...e.evidenceVersion==="p205-execution-v2"?{contract:g,command:C,manifestDigest:f,gateIds:h,resultDigest:d}:{},baseSha:r,headSha:o,bundleDigest:i,graphRevision:s,sourceEvidenceDigest:c,verdict:e.verdict,checkedAt:l,receiptRef:p}}function en(e){if(!m(e)||e.schemaVersion!==1||e.kind!=="story_checkpoint_physical_verification"||e.producer!=="client-p205-transient-v1"||e.publicSafe!==!0||e.verdict!=="verified"&&e.verdict!=="rejected")return;const t=j(e.storyId),n=j(e.epicId),r=H(e.branch),o=A(e.baseSha),i=A(e.headSha),s=A(e.aggregateHeadSha),c=A(e.commitBodyDigest),l=A(e.changedPathsDigest),p=e.claimVerification==="canonical"||e.claimVerification==="legacy-migration"?e.claimVerification:void 0,g=A(e.effectiveClaimRevision),C=e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,f=A(e.manifestDigest),d=J(e.gateIds).map(j).filter(_=>!!_).slice(0,64),h=A(e.resultDigest),S=A(e.graphRevision),E=A(e.executionEvidenceDigest),T=A(e.sourceEvidenceDigest),k=z(e.verifiedAt),w=J(e.reasonCodes).map(j).filter(_=>!!_).slice(0,16);if(!(!t||!n||!r||!o||o.length<40||!i||i.length<40||!s||s.length<40||!c||c.length!==64||!l||l.length!==64||!p||!g||g.length!==64||!C||!f||f.length!==64||!Array.isArray(e.gateIds)||d.length!==e.gateIds.length||!h||h.length!==64||!S||S.length!==64||!E||E.length!==64||!T||T.length!==64||!k||w.length===0||e.verdict==="verified"&&(d.length===0||!w.includes("checkpoint-p205-transient-verified"))))return{schemaVersion:1,kind:"story_checkpoint_physical_verification",producer:"client-p205-transient-v1",storyId:t,epicId:n,branch:r,baseSha:o,headSha:i,aggregateHeadSha:s,commitBodyDigest:c,changedPathsDigest:l,claimVerification:p,effectiveClaimRevision:g,command:C,manifestDigest:f,gateIds:d,resultDigest:h,graphRevision:S,executionEvidenceDigest:E,sourceEvidenceDigest:T,verifiedAt:k,verdict:e.verdict,reasonCodes:w,publicSafe:!0}}function tn(e){const t=["schemaVersion","kind","producer","storyId","epicId","branch","baseSha","headSha","graphRevision","effectiveClaimRevision","sourceEvidenceDigest","verifiedAt","reasonCodes","integrationAuthorized","publicSafe"];if(!m(e)||Object.keys(e).some(f=>!t.includes(f))||e.schemaVersion!==1||e.kind!=="story_scheduling_checkpoint_evidence"||e.producer!=="client-git-physical-v1"||e.integrationAuthorized!==!1||e.publicSafe!==!0)return;const n=j(e.storyId),r=j(e.epicId),o=H(e.branch),i=A(e.baseSha),s=A(e.headSha),c=A(e.graphRevision),l=A(e.effectiveClaimRevision),p=A(e.sourceEvidenceDigest),g=z(e.verifiedAt),C=J(e.reasonCodes).map(j).filter(f=>!!f);if(!(!n||!r||!o||!i||i.length<40||!s||s.length<40||!c||c.length!==64||!l||l.length!==64||!p||p.length!==64||!g||!Array.isArray(e.reasonCodes)||C.length!==1||C[0]!=="checkpoint-git-scheduling-verified"))return{schemaVersion:1,kind:"story_scheduling_checkpoint_evidence",producer:"client-git-physical-v1",storyId:n,epicId:r,branch:o,baseSha:i,headSha:s,graphRevision:c,effectiveClaimRevision:l,sourceEvidenceDigest:p,verifiedAt:g,reasonCodes:C,integrationAuthorized:!1,publicSafe:!0}}function Qr(e){if(!m(e)||e.schemaVersion!==1||e.kind!=="story_review_evidence"||e.producer!=="root-commit-range-review"||!["approved","changes-requested"].includes(String(e.verdict)))return;const t=j(e.storyId),n=j(e.epicId),r=A(e.baseSha),o=A(e.headSha),i=A(e.bundleDigest),s=A(e.graphRevision),c=A(e.sourceEvidenceDigest),l=le(e.qaReceiptRef),p=z(e.reviewedAt),g=le(e.receiptRef);if(!(!t||!n||!r||!o||!i||i.length!==64||!s||s.length!==64||!c||c.length!==64||!l||!p||!g))return{schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:t,epicId:n,baseSha:r,headSha:o,bundleDigest:i,graphRevision:s,sourceEvidenceDigest:c,qaReceiptRef:l,verdict:e.verdict,reviewedAt:p,receiptRef:g}}function nn(e,t){return["storyId","epicId","baseSha","headSha","bundleDigest","graphRevision"].every(n=>e[n]===t[n])}function rn(e){if(!m(e)||e.schemaVersion!==1||e.capturedFromCurrentCheckout!==!0)return;const t=H(e.originBranch),n=A(e.originHeadSha),r=H(e.executionBranch),o=z(e.capturedAt);if(!(!t||!n||n.length<40||!r||!o||t===r))return{schemaVersion:1,originBranch:t,originHeadSha:n,executionBranch:r,capturedFromCurrentCheckout:!0,capturedAt:o}}function on(e){if(!m(e)||e.schemaVersion!==1||e.verdict!=="passed")return;const t=A(e.executionHeadSha),n=A(e.graphRevision),r=z(e.checkedAt),o=le(e.receiptRef),i=J(e.gateIds).map(j).filter(g=>!!g).slice(0,128),s=e.evidenceVersion==="p205-execution-v2"&&e.producer==="local-yolo-tdd"&&e.contract==="P205-CI-02"&&e.command==="node scripts/test-root.mjs --gate complete",c=e.evidenceVersion===void 0&&e.producer===void 0&&e.contract===void 0&&e.command===void 0&&e.manifestDigest===void 0&&e.resultDigest===void 0,l=s?A(e.manifestDigest):void 0,p=s?A(e.resultDigest):void 0;if(!(!t||t.length<40||!n||n.length!==64||!r||!o||i.length===0||!Array.isArray(e.gateIds)||i.length!==e.gateIds.length||e.gateIds.length>128||!c&&!s||s&&(!l||l.length!==64||!p||p.length!==64)))return{schemaVersion:1,...s?{evidenceVersion:"p205-execution-v2",producer:"local-yolo-tdd",contract:"P205-CI-02",command:"node scripts/test-root.mjs --gate complete",manifestDigest:l,resultDigest:p}:{},verdict:"passed",executionHeadSha:t,graphRevision:n,checkedAt:r,receiptRef:o,gateIds:i}}function We(e){if(!m(e)||e.schemaVersion!==1)return;const t=$e(e,["schemaVersion","kind","storyId","epicId","baseSha","headSha","originalBaseSha","originalHeadSha","gitPullRequest","preservesLaterCommits","historyRewrite","recordedAt"])??{},n=J(e.receiptRefs).map(le).filter(o=>!!o).slice(0,256),r=J(e.revertCommits).map(U).filter(o=>!!o).slice(0,256);return{...t,...n.length?{receiptRefs:n}:{},...r.length?{revertCommits:r}:{}}}function sn(e){if(!m(e)||e.schemaVersion!==1||e.publicSafe!==!0)return;const t=j(e.epicId),n=H(e.executionBranch),r=H(e.originBranch),o=A(e.baseSha),i=A(e.executionHeadSha),s=e.mergeSha===void 0?void 0:A(e.mergeSha),c=e.pushedSha===void 0?void 0:A(e.pushedSha),l=j(e.idempotencyKey),p=z(e.attemptStartedAt),g=e.completedAt===void 0?void 0:z(e.completedAt),C=J(e.localGateReceiptRefs).map(le).filter(S=>!!S).slice(0,256),f=J(e.reasonCodes).map(j).filter(S=>!!S).slice(0,64),d=to(e.candidateQa),h=eo(e.providerGuard);if(!(!t||!n||!r||!o||!i||!l||!p||C.length===0||f.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&&!h||h&&(e.strategy!=="single_pr"||e.physicalStatus!=="pushed"||h.prHeadSha!==s||h.originHeadSha!==o)))return{schemaVersion:1,epicId:t,executionBranch:n,originBranch:r,baseSha:o,executionHeadSha:i,...s?{mergeSha:s}:{},...c?{pushedSha:c}:{},strategy:e.strategy,...ue(e.prNumber)?{prNumber:ue(e.prNumber)}:{},physicalStatus:e.physicalStatus,localGateReceiptRefs:C,idempotencyKey:l,attemptStartedAt:p,...d?{candidateQa:d}:{},...h?{providerGuard:h}:{},...g?{completedAt:g}:{},retryEligible:e.retryEligible,reasonCodes:f,publicSafe:!0}}function eo(e){if(!m(e)||e.schemaVersion!==1||e.provider!=="github"||e.publicSafe!==!0)return;const t=String(e.mode),n=String(e.source),r=t==="recovered_exact_tree"?n==="physical_recovery":t==="strict_up_to_date_expected_head"&&["branch_protection","ruleset","branch_protection_and_ruleset"].includes(n),o=A(e.prHeadSha),i=A(e.originHeadSha),s=z(e.checkedAt);if(!(!r||!o||!i||!s))return{schemaVersion:1,provider:"github",mode:t,source:n,prHeadSha:o,originHeadSha:i,checkedAt:s,publicSafe:!0}}function to(e){if(!m(e)||e.schemaVersion!==1||e.kind!=="epic_merge_candidate_qa"||e.contract!=="P205-CI-02"||e.command!==Rr)return;const n=Object.fromEntries(["originHeadSha","executionHeadSha","mergeSha","treeSha","graphRevision","manifestDigest","resultDigest"].map(s=>[s,A(e[s])])),r=z(e.checkedAt),o=le(e.receiptRef),i=J(e.gateIds).filter(s=>/^[a-z0-9-]+$/.test(s)).slice(0,128);if(!(Object.values(n).some(s=>!s)||!r||!o||i.length===0))return{schemaVersion:1,kind:e.kind,contract:e.contract,command:e.command,...n,checkedAt:r,receiptRef:o,gateIds:i}}function no(e){if(!m(e))return;const t={...U(e.active_epic_id??e.activeEpicId)?{active_epic_id:U(e.active_epic_id??e.activeEpicId)}:{},...U(e.active_story_id??e.activeStoryId)?{active_story_id:U(e.active_story_id??e.activeStoryId)}:{},...U(e.active_step_id??e.activeStepId)?{active_step_id:U(e.active_step_id??e.activeStepId)}:{},...U(e.session_id??e.sessionId)?{session_id:U(e.session_id??e.sessionId)}:{},...U(e.started_at??e.startedAt)?{started_at:U(e.started_at??e.startedAt)}:{}};return Object.keys(t).length>0?t:void 0}function ro(e){const t=$e(e.completionEvidence??e.completion_evidence,["prNumber","pr_number","prState","pr_state","pullRequestState","merged","mergedAt","issueNumber","issue_number","issueState","issue_state","closedAt"]),n=$e(e.issueCloseAudit??e.issue_close_audit,["schema_version","event","storyId","epicId","issueNumber","closedAt","publicSafe","rawLogStorage"]),r=$e(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}:{},...U(e.physicalMergeStatus)?{physicalMergeStatus:U(e.physicalMergeStatus)}:{},...U(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)?{pr_state:U(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)}:{},...U(e.issue_state??e.issueState??e.workflow_issue_state)?{issue_state:U(e.issue_state??e.issueState??e.workflow_issue_state)}:{},...ue(e.issue_number??e.issueNumber)?{issue_number:ue(e.issue_number??e.issueNumber)}:{},...t?{completionEvidence:t}:{},...n?{issueCloseAudit:n}:{},...r?{scopedCiEvidence:r}:{}}}class pe extends Error{reasonCode;constructor(t){super(t),this.name="StateSnapshotIntegrityError",this.reasonCode=t}}const oo=new Set(["yolo","yoloop","finalize-epic","audit"]);function an(e){return typeof e=="string"&&oo.has(e)}function cn(e,t={}){const n=te(e,".neocortex","state.json");if(!Ce(n))throw new pe("git-lifecycle-state-missing");let r;try{r=JSON.parse(Ae(n,"utf8"))}catch{throw new pe("git-lifecycle-state-corrupt")}if(!m(r)||!m(r.epics)||!m(r.stories))throw new pe("git-lifecycle-state-shape-invalid");const o=Object.values(r.epics).some(i=>m(i)&&(i.branch_mode==="epic"||H(i.execution_branch)!==void 0));if(o)try{Ze(e,{required:!0})}catch(i){const s=i instanceof Error&&/^git-lifecycle-/.test(i.message)?i.message:"git-lifecycle-runtime-invalid";if(t.allowMissingRuntime&&s==="git-lifecycle-runtime-missing")return{lifecycleDeclared:!0,runtimeMissing:!0};throw new pe(s)}return{lifecycleDeclared:o,runtimeMissing:!1}}function dn(e,t={}){const n=te(e,".neocortex","state.json");if(!Ce(n)){if(t.epicAware&&!t.projectless)throw new pe("git-lifecycle-state-missing");return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}let r;try{const f=Ae(n,"utf-8"),d=JSON.parse(f),h=m(d.epics)?d.epics:{},S=Object.values(h).some(_=>m(_)&&(_.branch_mode==="epic"||H(_.execution_branch)!==void 0)),E=Ze(e,{required:!!(t.epicAware&&S&&!t.projectless)});r=Ut(d,E);const T=m(r.stories)?r.stories:{},k=m(r.epics)?r.epics:{},w=m(d.stories)?d.stories:{};for(const[_,R]of Object.entries(T)){const I=m(R)?R:void 0;if(!I?.checkpoint)continue;const M=typeof I.epic_id=="string"?I.epic_id:_.split(".")[0],L=m(k[M])?k[M]:void 0,D=H(L?.execution_branch);if(!D)continue;const V=Er(e,I.checkpoint,_,M,D,t.p205Authorities?.[_],Vt(_,I,m(I.checkpoint)?I.checkpoint:void 0));if(V.kind==="integration-authorized")I.checkpoint_verification=V.verification,delete I.scheduling_checkpoint_evidence;else if(V.kind==="scheduling-only")I.scheduling_checkpoint_evidence=V.evidence,delete I.checkpoint,delete I.checkpoint_verification;else if(V.kind==="rejected"){I.checkpoint_verification=V.verification,delete I.scheduling_checkpoint_evidence;const x=m(w[_])?w[_]:void 0;if(delete I.checkpoint,E.stories[_]?.checkpoint!==void 0)for(const v of["status","last_step","steps_completed"])x&&Object.prototype.hasOwnProperty.call(x,v)?I[v]=structuredClone(x[v]):delete I[v];["done","completed","merged"].includes(String(I.status).toLowerCase())&&(I.status="blocked")}}}catch(f){if(t.epicAware&&!t.projectless){const d=f instanceof Error&&/^git-lifecycle-/.test(f.message)?f.message:"git-lifecycle-state-corrupt";throw new pe(d)}return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}try{const f=zr(r);f.length>0&&qr(f)}catch{}const o=r.config??r.project??{},i=r.stories??{},s={};for(const[f,d]of Object.entries(i))s[f]={id:d.id??f,title:d.title,epic_id:d.epic_id,status:d.status??"backlog",...Xt(d.source)?{source:Xt(d.source)}:{},steps_completed:d.steps_completed??[],last_step:d.last_step??null,branch_name:d.branch_name??null,pr_number:d.pr_number,...He(d.branch_mode)?{branch_mode:He(d.branch_mode)}:{},...Qt(d.checkpoint)?{checkpoint:Qt(d.checkpoint)}:{},...en(d.checkpoint_verification)?{checkpoint_verification:en(d.checkpoint_verification)}:{},...tn(d.scheduling_checkpoint_evidence)?{scheduling_checkpoint_evidence:tn(d.scheduling_checkpoint_evidence)}:{},...We(d.review_request)?{review_request:We(d.review_request)}:{},...We(d.rollback_receipt)?{rollback_receipt:We(d.rollback_receipt)}:{},...ue(d.workflow_issue)?{workflow_issue:ue(d.workflow_issue)}:{},...ro(d),depends_on:Kt(d.depends_on),files_to_modify:J(d.files_to_modify),...Xr(d),risk:typeof d.risk=="string"?d.risk:void 0,blast_radius:typeof d.blast_radius=="number"?d.blast_radius:void 0};const c=r.epics??{},l={};for(const[f,d]of Object.entries(c)){const h=Kr(d.lifecycle_classification);l[f]={id:d.id??f,title:d.title,status:d.status,stories:d.stories,total_stories:d.total_stories,completed_stories:d.completed_stories,depends_on:Kt(d.depends_on),...He(d.branch_mode)?{branch_mode:He(d.branch_mode)}:{},...H(d.execution_branch)?{execution_branch:H(d.execution_branch)}:{},...H(d.origin_branch)?{origin_branch:H(d.origin_branch)}:{},...Zt(d.branch_lease)?{branch_lease:Zt(d.branch_lease)}:{},...rn(d.origin_binding)?{origin_binding:rn(d.origin_binding)}:{},...on(d.aggregate_qa_receipt)?{aggregate_qa_receipt:on(d.aggregate_qa_receipt)}:{},...ue(d.pr_number)?{pr_number:ue(d.pr_number)}:{},...U(d.physicalMergeStatus)?{physicalMergeStatus:U(d.physicalMergeStatus)}:{},...A(d.graph_revision)?{graph_revision:A(d.graph_revision)}:{},...sn(d.terminal_git_receipt)?{terminal_git_receipt:sn(d.terminal_git_receipt)}:{},...h?{lifecycle_classification:h}:{}}}const p=no(r.current_session??r.currentSession),g=r.epic_id_ledger,C=Array.isArray(g?.reserved_ids)?[...new Set(g.reserved_ids.filter(f=>typeof f=="string"&&/^P\d+$/.test(f)))].slice(0,2048):[];return{schema_version:typeof r.schema_version=="number"?r.schema_version:void 0,config:{project_name:o.project_name??o.name??"unknown",default_branch:o.default_branch??"main",language:o.language??"pt-BR",yolo_mode:o.yolo_mode,user_name:o.user_name,worktree_base:o.worktree_base,max_parallel_stories:o.max_parallel_stories,project_id:typeof o.project_id=="string"?o.project_id:void 0},stories:s,epics:l,...C.length>0?{epic_id_ledger:{schema_version:1,reserved_ids:C}}:{},...p?{current_session:p}:{}}}async function io(e,t,n){if(!an(n))return{};if(Wn(t,n))return{};try{const r=JSON.parse(Ae(te(e,".neocortex","state.json"),"utf8")),o=Ze(e,{required:!0}),i=Ut(r,o),s=m(i.stories)?i.stories:{},c=m(i.epics)?i.epics:{},l=ke("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8"}).trim(),p=ke("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8"}).trim(),g=ke("git",["rev-list","--first-parent","--reverse",l],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
8
- `).filter(Boolean),C=new Map(g.map((_,R)=>[_,R])),f=t.match(/(?:^|\s)@?docs\/stories\/([A-Za-z][A-Za-z0-9._-]*)\.story\.md(?:\s|$)/)?.[1],d=n==="yoloop"?t.match(/(?:^|[\s/@])epic-(P[1-9][0-9]*)\.md(?:\s|$)/i)?.[1]?.toUpperCase():void 0,h=new Set,S=Object.entries(s).flatMap(([_,R])=>{if(f&&_!==f)return[];const I=m(R)?R:void 0,M=m(I?.checkpoint)?I.checkpoint:void 0;if(!M)return[];const L=typeof I?.epic_id=="string"?I.epic_id:_.split(".")[0];if(d&&L!==d)return[];const D=A(M?.headSha);if(!D||D.length<40||C.get(D)===void 0)return h.add(L),[];const V=m(c[L])?c[L]:void 0;if(V?.branch_mode!=="epic"||H(V.execution_branch)!==p||H(M.branch)!==p)return h.add(L),[];const x=A(M.graphRevision);if(!x||x.length!==64)return h.add(L),[];const v=A(M.claimRevision),ee=[...Vt(_,I,M)].sort(),Oe=wr(e,M,_,L,p,ee);if(!Oe&&v){if(ee.length===0)return h.add(L),[];const _e=ke("git",["diff-tree","--no-commit-id","--name-only","-r","-z",D],{cwd:e,encoding:"utf8"}).split("\0").filter(Boolean);if(_e.length===0||_e.some(ge=>!ee.some(K=>K===ge||K.endsWith("/")&&ge.startsWith(K))))return h.add(L),[];const Ee=Ne("sha256").update(ee.join("\0")).digest("hex"),De=Ne("sha256").update(JSON.stringify(ee)).digest("hex");if(v!==Ee&&v!==De)return h.add(L),[]}else if(!Oe)return h.add(L),[];return x?.length===64?[{storyId:_,epicId:L,graphRevision:x,checkpointHead:D,position:C.get(D)}]:[]}),E=new Set(h);for(const[_,R]of Object.entries(c)){const I=m(R)?R:void 0,M=Array.isArray(I?.stories)?I.stories.filter(x=>typeof x=="string"):Object.keys(s).filter(x=>x.startsWith(`${_}.`)),L=S.filter(x=>x.epicId===_),D=M.filter(x=>L.some(v=>v.storyId===x)),V=[...L].sort((x,v)=>x.position-v.position).map(x=>x.storyId);(JSON.stringify(D)!==JSON.stringify(V)||new Set(V).size!==V.length)&&E.add(_)}const T={},k=[...new Set(S.filter(_=>!E.has(_.epicId)).map(_=>_.graphRevision))],w=k.length>0?await Ar(e,{headSha:l,graphRevisions:k}):new Map;for(const _ of S){if(E.has(_.epicId))continue;const R=w.get(_.graphRevision);if(!R)throw new Error("p205-transient-authority-missing");T[_.storyId]=R}return T}catch(r){const o=r instanceof Error&&/^(?:p205|git-lifecycle)-[a-z0-9-]+$/.test(r.message)?r.message:"p205-transient-execution-failed";return process.stderr.write(`[Neocortex] ${o}. Checkpoint projection remains fail-closed.
9
- `),{}}}function Xi(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 un="neocortex:menu:cache";async function so(e){try{const t=await e.get(un);if(!t)return null;const n=JSON.parse(t);return n.version!==Se||Date.now()-n.cachedAt>$t?null:n}catch{return null}}async function ao(e,t,n){try{const r={instructions:t,metadata:n,cachedAt:Date.now(),version:Se};await e.set(un,JSON.stringify(r),$t),co()}catch{}}function co(){try{Ce(Bt)&&xn(Bt)}catch{}}function uo(e){return e.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>Rt(),()=>Rt({strictReadOnly:!0}))}async function ln(e,t,n){const r=n.mode==="strict";try{let o;if(r&&t)o=new Ke({cacheDir:Qe,passphrase:t,strictReadOnly:!0});else if(r)o=new At;else if(t){const g=te(Ue,"cache");o=new Ke({cacheDir:g,passphrase:t})}else process.stderr.write(`[neocortex] Warning: No license key in config. Run "neocortex activate" to re-authenticate.
10
- `),o=new At;const i=Dt(n,o,"auth-cache"),s=Dt(n,o,"tier-cache"),c=new Pn({serverUrl:e,licenseKey:t??"",cacheProvider:i,strictReadOnly:r});let l;if(r){const g=await c.inspectToken();if(g.status!=="authenticated")return g;l=g.token}else l=await c.getToken();if(!l)return{status:"not-configured"};const p=new jn({cacheProvider:s,licenseClient:c});return{status:"authenticated",token:l,client:c,tierClient:p}}catch{return r&&t?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"}}}let pn=!1;function lo(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 fn=3,Fe=50;function po(e){return new Promise(t=>setTimeout(t,e))}function fo(e,t,n){return e.status>=500&&e.status<=599?!0:n&&e.status===409&&t.error_code==="SIGNATURE_REPLAYED"}async function ct(e,t,n,r,o={}){const i=Math.max(1,Math.min(o.maxAttempts??fn,fn)),s=o.sleep??po;let c=r,l=!1,p=!1,g=0;for(let C=1;C<=i;C+=1){const f=Math.max(Math.floor(Date.now()/1e3),g+1);g=f;const d=go(t,n,c,{nowSeconds:f}),h=new AbortController,S=setTimeout(()=>h.abort(),Ht);try{const E=await fetch(`${e}${t}`,{method:"POST",headers:d.headers,body:d.body,signal:h.signal}),T=await E.text().catch(()=>""),k=(()=>{try{return T?JSON.parse(T):{}}catch{return{}}})();if(E.status===401&&!l&&o.refreshToken&&(k.fallback_action==="refresh_token"||k.fallback_action==="re_authenticate")){l=!0;const w=await o.refreshToken();if(w&&C<i){c=w,o.onTokenChanged?.(w),await s(Fe*C);continue}}if(E.status===401&&k.error_code==="SIGNATURE_EXPIRED"&&!p&&C<i){p=!0,await s(Fe*C);continue}if(C<i&&fo(E,k,o.allowReplayRetry===!0)){await s(Fe*C);continue}return{response:E,text:T,parsed:k,networkFailure:!1}}catch{if(C<i){await s(Fe*C);continue}return{text:"",parsed:{},networkFailure:!0}}finally{clearTimeout(S)}}return{text:"",parsed:{},networkFailure:!0}}function go(e,t,n,r={}){const o=Buffer.from(JSON.stringify(t),"utf8"),i=tr({method:"POST",target:e,body:o,bearerToken:n,clientVersion:Se,nowSeconds:r.nowSeconds,nonceBytes:r.nonceBytes});return{body:i.body,headers:{...i.headers,Authorization:`Bearer ${n}`}}}function gn(e){return Ne("sha256").update(e).digest("hex")}function ho(){const e=Number(process.env.NEOCORTEX_INVOKE_CHUNK_BYTES??"49152");return Number.isFinite(e)&&e>=1024&&e<=98304?Math.floor(e):49152}function mo(e,t,n){return`args-${Ne("sha256").update("invoke-materialization:v1").update(e).update(String(t)).update(JSON.stringify(n)).digest("hex")}`}async function hn(e,t,n,r,o={}){const i=await ct(e,t,n,r,{...o,allowReplayRetry:!0});if(i.networkFailure||!i.response)throw new Error("NETWORK_ERROR: materialization request failed after bounded retries");const{response:s,parsed:c}=i;if(!s.ok){const l=typeof c.error_code=="string"?c.error_code:`HTTP_${s.status}`,p=typeof c.message=="string"?c.message:"materialization upload failed";throw new Error(`${l}: ${p}`)}return c}async function Io(e,t,n,r){const o=Buffer.from(t,"utf8"),i=ho(),s=[];for(let h=0,S=0;h<o.byteLength;h+=i,S++){const E=o.subarray(h,Math.min(h+i,o.byteLength));s.push({index:S,sha256:gn(E),byteLength:E.byteLength})}const c=gn(o),l=mo(c,o.byteLength,s),p=Number(process.env.NEOCORTEX_INVOKE_CHUNK_TTL_SECONDS??"900");let g=n;const C={refreshToken:r,onTokenChanged(h){g=h}};for(const h of s){const S=h.index*i,E=o.subarray(S,S+h.byteLength);await hn(e,"/api/v1/invoke/materialization/chunks",{manifestId:l,index:h.index,sha256:h.sha256,byteLength:h.byteLength,contentBase64:E.toString("base64"),ttlSeconds:p,idempotencyKey:`${l}:${h.index}:${h.sha256}`},g,C)}const d=(await hn(e,"/api/v1/invoke/materialization/manifests",{manifestId:l,sha256:c,byteLength:o.byteLength,chunkCount:s.length,chunks:s,ttlSeconds:p,retry:{attempt:1,budget:3,idempotencyKey:l}},g,C)).argsRef;if(!d?.manifestId)throw new Error("MATERIALIZATION_RESPONSE_INVALID: missing argsRef");return{argsRef:d,chunks:s}}function Te(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function yo(...e){const t=new Set,n=[];for(const r of e)for(const o of r??[]){const i=U(o);if(!(!i||t.has(i))&&(t.add(i),n.push(i),n.length>=16))return n}return n}function _o(e){const t=e.graphRetrieval;if(!m(t))return{accepted:!1,itemCount:0};const n=Array.isArray(t.items)?t.items.length:0;return{accepted:n>0||typeof t.retrievalId=="string"||t.accepted===!0,itemCount:n}}function dt(e,t=Te(e),n=[],r={}){const o=e.stateSnapshot.scope,i=Object.keys(e.stateSnapshot.stories).length,s=Object.keys(e.stateSnapshot.epics).length,c=o?.kind??"full";return{schemaVersion:1,payloadBytes:t,limitBytes:r.limitBytes??Ft,warningThresholdBytes:r.warningThresholdBytes??et,scope:{kind:c,...o?.projectionMode?{projectionMode:o.projectionMode}:{},commandId:o?.commandId??null,stateProjectionPolicy:o?.stateProjectionPolicy??null},includedStories:o?.includedStoryCount??i,omittedStories:o?.omittedStoryCount??0,includedEpics:o?.includedEpicCount??s,omittedEpics:o?.omittedEpicCount??0,graphRetrieval:_o(e.stateSnapshot),reasonCodes:yo(n,o?.reasonCodes),publicSafe:!0}}function Eo(e){const t=m(e.budget)?e.budget:void 0,n=typeof t?.maxPayloadBytes=="number"&&Number.isFinite(t.maxPayloadBytes)?t.maxPayloadBytes:12*1024;return Math.max(1024,Math.min(n,12*1024))}function Co(e){return m(e)?{stableId:U(e.stableId)??"unknown",...m(e.source)?{source:e.source}:{},reasonCode:"budget_exceeded"}:{stableId:"unknown",reasonCode:"budget_exceeded"}}function mn(e){const t=Array.isArray(e)?e.filter(n=>typeof n=="string"):[];return t.includes("budget_exceeded")?t:[...t,"budget_exceeded"]}function Ao(e){const t=e.graphRetrieval;if(!m(t)||!Array.isArray(t.items))return e;const n=Eo(t);let r=[...t.items],o=Array.isArray(t.skipped)?[...t.skipped]:[],i=t;for(;Buffer.byteLength(JSON.stringify(i),"utf8")>n&&r.length>0;){const s=r.pop();o=[...o,Co(s)].slice(-32),i={...t,items:r,skipped:o,warnings:mn(t.warnings)}}return Buffer.byteLength(JSON.stringify(i),"utf8")>n&&(i={...t,query:typeof t.query=="string"?t.query.slice(0,240):t.query,items:[],skipped:[],warnings:mn(t.warnings)}),i===t?e:{...e,graphRetrieval:i}}function In(e,t={}){const n=t.limitBytes??Ft,r=t.warningThresholdBytes??Math.floor(n*Gt),o=Te(e);if(o<n)return{body:e,degraded:!1,telemetry:dt(e,o,["payload-within-limit"],{limitBytes:n,warningThresholdBytes:r})};let i={...e,stateSnapshot:$n(e.stateSnapshot)},s=["payload-size-guardrail","state-degraded"],c=Te(i);c>=n&&(i={...i,stateSnapshot:Ao(i.stateSnapshot)},s=[...s,"graph-retrieval-budget-enforced"],c=Te(i));const l=dt(i,c,s,{limitBytes:n,warningThresholdBytes:r});if(c>=n){const p=i.stateSnapshot.scope?.projectionMode;throw p==="yolo-story"||p==="yoloop-target"||p==="yoloop-session"||p==="yoloop-discovery"||p==="structural-required"?new st(l):new it(l)}return{body:i,degraded:!0,telemetry:l}}function yn(e){const t=e.stateSnapshot.scope?.commandId??"resolved-command";return e.args!==void 0?t:`${t}:argsRef`}function So(e){const t=Te(e);if(t<et)return t;const n=dt(e,t,["payload-warning-threshold"]);return process.stderr.write(`[Neocortex] invoke payload near server limit: trigger=${yn(e)} scope=${n.scope.kind} mode=${n.scope.projectionMode??n.scope.kind} payloadBytes=${n.payloadBytes} limit=${n.limitBytes} includedStories=${n.includedStories} omittedStories=${n.omittedStories} includedEpics=${n.includedEpics} omittedEpics=${n.omittedEpics} graphRetrieval.accepted=${n.graphRetrieval.accepted} graphRetrieval.itemCount=${n.graphRetrieval.itemCount} reasonCodes=${n.reasonCodes.join(",")||"none"}
11
- `),t}function _n(e,t){process.stderr.write(`[Neocortex] invoke payload guardrail: trigger=${yn(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"}
12
- `)}async function Ro(e){const t=Jn(e.args,{platformTarget:e.platformTarget,environment:e.environment??process.env});if(t.action==="skipped")return{shouldContinue:!0,attachToRequest:wo(t),metadata:En(t)};const n=e.bootstrapper??qn;let r;try{r=await n({projectRoot:e.projectRoot,env:e.environment??process.env,effectAuthority:e.effectAuthority})}catch{r={ok:!1,attempted:!0,installed:!1,started:!1,cached:!1,projectKey:"unknown",reasonCodes:[zn.UNEXPECTED_ERROR],publicSummary:"runner scheduler bootstrap stopped unexpectedly.",publicSafe:!0}}const o=En(t,r);if(r.ok)return{shouldContinue:!0,attachToRequest:!0,metadata:o};const i=o.reasonCodes.slice(0,5).join(",");return t.failurePolicy==="fail-open"?{shouldContinue:!0,attachToRequest:!0,metadata:{...o,failOpenWarning:!0},warning:`Runner auto-bootstrap warning (${i}); continuing fail-open for operator command.`}:{shouldContinue:!1,attachToRequest:!1,metadata:o,errorCode:"RUNNER_BOOTSTRAP_REQUIRED_FAILED",error:`Runner auto-bootstrap required but failed (${i}). Run neocortex-runner doctor or retry after resolving scheduler setup.`,exitCode:1}}function wo(e){return!e.reasonCodes.includes(Yn.SKIPPED_NON_CONTINUITY_COMMAND)}function En(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:Y([...e.reasonCodes,...t?.reasonCodes??[]]),publicSummary:t?.publicSummary??e.publicSummary,publicSafe:!0}}function Y(e){return Array.from(new Set(e.map(t=>t.slice(0,120))))}function Ge(e,t,n){const r=Math.floor(e??t);return Number.isFinite(r)?Math.max(1,Math.min(n,r)):t}function Ye(e,t){const n=process.env[e];if(!n)return t;const r=Number(n);return Number.isFinite(r)?r:t}function N(e,t=qt){const n=typeof e=="string"&&e.trim().length>0?e.trim():"unknown",r=Z(n,t),o=Hr.test(r)?de:r;return o.length<=t?o:`${o.slice(0,t)}\u2026[TRUNCATED:${o.length-t}]`}function ut(e,t=qt){if(!(typeof e!="string"||e.trim().length===0))return N(e,t)}function lt(e,t,n,r){const o=ut(e?.targetId??t,120),i=e?.selectorKind??(o?ft(o):void 0),s=(e?.relatedJobIds??[]).map(c=>ut(c,120)).filter(c=>!!c);return{schemaVersion:1,contractVersion:"continuity-v1",targetResolutionState:n,...i?{targetKind:i}:{},...o?{targetId:o}:{},...t?{targetJobId:N(t,120)}:{},...e?.jobId?{jobId:N(e.jobId,120)}:{},...e?.goalId?{goalId:N(e.goalId,120)}:{},...e?.loopId?{loopId:N(e.loopId,120)}:{},...s.length>0?{relatedJobIds:s}:{},relatedJobCount:s.length,reasonCodes:Y(r.length>0?r:[O.OK]),publicSafe:!0}}function se(e,t,n,r,o=[]){const i=(e?.redactions?.length??0)>0,s=e?i?"unsafe":n&&r===0?"empty":"available":"unavailable",c=ut(t[t.length-1]?.eventId,120),l=o.length>0?o:s==="unavailable"?[O.WATCH_SNAPSHOT_UNAVAILABLE]:s==="empty"?[O.WATCH_NO_SUMMARIES_YET]:[O.OK];return{schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:s,...e?.generatedAt?{generatedAt:N(e.generatedAt,80)}:{},renderedSummaryCount:r,...c?{latestEventId:c}:{},reasonCodes:Y(l),publicSafe:!0}}function ne(e,t,n,r,o=[],i){const s=r[r.length-1],c=n??s?.cursor,l=!!(c&&c!==t&&r.length>0),p=i??(l?"advanced":t||c?"unchanged":"not_started"),g=o.length>0?o:p==="advanced"?[O.WATCH_CURSOR_ADVANCED]:p==="unavailable"?[O.WATCH_EVIDENCE_UNAVAILABLE]:[O.WATCH_CURSOR_UNCHANGED];return{schemaVersion:1,contractVersion:"continuity-v1",cursorState:p,...e?{initialCursor:N(e,200)}:{},...t?{currentCursor:N(t,200)}:{},...c?{nextCursor:N(c,200)}:{},cursorAdvanced:l,...s?.eventId?{eventId:N(s.eventId,120)}:{},reasonCodes:Y(g),publicSafe:!0}}function re(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:Y([...e.reasonCodes??[],...t?.reasonCodes??[],...e.snapshotEvidence?.reasonCodes??[],...e.cursorEvidence?.reasonCodes??[]]),generatedAt:N(e.generatedAt??new Date().toISOString(),80),publicSafe:!0}}function To(e){const t=e.targetKind&&e.targetId?`${e.targetKind}/${e.targetId}`:e.targetId??"[unresolved]",n=e.snapshotEvidence?.renderedSummaryCount??0,r=e.targetEvidence?.relatedJobCount??0,o=e.cursorEvidence?.cursorState??"unavailable",i=e.cursorEvidence?.currentCursor??"[none]",s=e.cursorEvidence?.nextCursor??"[none]",c=e.snapshotEvidence?.snapshotStatus??"not_requested",l=e.snapshotEvidence?.generatedAt??e.generatedAt;return[`[watch-status] ${e.targetResolutionState==="unresolved"||e.stopReason==="target_unresolved"?"unresolved-target":n===0&&(e.watchStatus==="waiting"||e.watchStatus==="active")?"no-new-summary":e.watchStatus==="stopped"?"stopped":"lifecycle"}`,`status=${e.watchStatus}`,`active=${e.active}`,`target=${t}`,`resolution=${e.targetResolutionState??"unavailable"}`,`relatedJobs=${r}`,`summaries=${n}`,`snapshot=${c}`,`generatedAt=${l}`,`cursor=${o}`,`current=${N(i,200)}`,`next=${N(s,200)}`,`advanced=${e.cursorEvidence?.cursorAdvanced??!1}`,`stop=${e.stopReason??"not_stopped"}`,`reasons=${e.reasonCodes.join(",")}`].join(" ")}function oe(e,t,n){if(t==="json"){n.write(JSON.stringify(e)+`
13
- `);return}n.write(To(e)+`
14
- `)}function bo(e,t,n){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:n,statusRecord:e,publicSafe:!0}}}function ae(e,t,n,r){return{status:e,summariesEmitted:t,polls:n,reasonCodes:r.reasonCodes,watchStatus:r.watchStatus,stopReason:r.stopReason,targetEvidence:r.targetEvidence,snapshotEvidence:r.snapshotEvidence,cursorEvidence:r.cursorEvidence,statusRecord:r,metadata:bo(r,t,n),publicSafe:!0}}function vo(e){const t=e.reasonCode?` reason=${N(e.reasonCode,80)}`:"",n=e.goalId?` goal=${N(e.goalId,100)}`:"",r=e.loopId?` loop=${N(e.loopId,100)}`:"";return`[watch] ${N(e.createdAt,80)} event=${N(e.eventId,120)} job=${N(e.jobId,100)}${n}${r} execution=${N(e.executionId,120)}${t} -- ${N(e.publicSummary)}`}function Oo(e){return{type:"processing_summary",source:"local_continuity_sqlite",eventId:N(e.eventId,120),jobId:N(e.jobId,100),...e.goalId?{goalId:N(e.goalId,100)}:{},...e.loopId?{loopId:N(e.loopId,100)}:{},executionId:N(e.executionId,120),...e.reasonCode?{reasonCode:N(e.reasonCode,80)}:{},createdAt:N(e.createdAt,80),publicSummary:N(e.publicSummary),publicSafe:!0}}function No(e,t,n){if(t==="json"){n.write(JSON.stringify(Oo(e))+`
15
- `);return}n.write(vo(e)+`
16
- `)}function pt(e){return Br.has(e.status)}function ko(e,t,n){if(t){const o=e.find(i=>i.jobId===t);return!!(o&&pt(o))}return n<=0?!1:e.filter(o=>!pt(o)).length===0}function Lo(e,t,n,r){return n<r?!1:t?!e.some(o=>o.jobId===t&&!pt(o)):e.length===0}function xo(e,t){return t?.aborted?Promise.resolve():new Promise(n=>{const r=setTimeout(o,e);function o(){clearTimeout(r),t?.removeEventListener("abort",o),n()}t?.addEventListener("abort",o,{once:!0})})}function Do(e){return e.includes(F.MALFORMED)?"malformed":e.includes(F.AMBIGUOUS)?"ambiguous":e.includes("watch-target-multiple")?"multiple":e.includes("watch-evidence-unsafe")?"unsafe":e.includes(F.MISSING)||e.includes($.TARGET_UNRESOLVED)?"unresolved":"unavailable"}function Cn(e,t){const n=t?Le(t):void 0,r=Y([...e,$.TARGET_UNRESOLVED,O.WATCH_TARGET_UNRESOLVED]),o=lt(n,n?.targetId,Do(r),r),i=se({generatedAt:new Date().toISOString()},[],!1,0,[O.WATCH_TARGET_UNRESOLVED]),s=ne(void 0,void 0,void 0,[],[O.WATCH_TARGET_UNRESOLVED],"unavailable");return re({watchStatus:"blocked",active:!1,targetEvidence:o,snapshotEvidence:i,cursorEvidence:s,stopReason:"target_unresolved",reasonCodes:r,generatedAt:i.generatedAt})}function Po(e,t,n,r){const o=Cn(e,Sn(t));return oe(o,n,r),ae("target-unresolved",0,0,o)}async function jo(e){if(e.signal?.aborted){const _=lt(e.target??Le(e.targetJobId),e.targetJobId,e.target??e.targetJobId?"resolved":"unresolved",[$.CANCELLED]),R=se(void 0,[],!1,0),I=ne(e.initialCursor,e.initialCursor,e.initialCursor,[],[$.CANCELLED],"unavailable"),M=re({watchStatus:"stopped",active:!1,targetEvidence:_,snapshotEvidence:R,cursorEvidence:I,stopReason:"cancelled",reasonCodes:[$.CANCELLED]});return ae("cancelled",0,0,M)}const t=e.target??Le(e.targetJobId),n=e.targetJobId??t?.targetId,r=e.stdout??process.stdout;if(!t){const _=Cn([F.MISSING,$.TARGET_UNRESOLVED]);return oe(_,e.format,r),ae("target-unresolved",0,0,_)}const o=Ge(e.limit??Ye("NEOCORTEX_INVOKE_WATCH_LIMIT",Nt),Nt,50),i=Math.max(50,Ge(e.pollIntervalMs??Ye("NEOCORTEX_INVOKE_WATCH_POLL_INTERVAL_MS",xt),xt,6e4)),s=Ge(e.maxIdlePolls??Ye("NEOCORTEX_INVOKE_WATCH_MAX_IDLE_POLLS",kt),kt,120),c=Ge(e.maxPolls??Ye("NEOCORTEX_INVOKE_WATCH_MAX_POLLS",Lt),Lt,86400),l=e.sleep??xo;let p=e.initialCursor,g=0,C=0,f=0;const d=lt(t,n,"resolved",[O.OK]),h={schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:"pending",renderedSummaryCount:0,reasonCodes:[O.WATCH_RENDER_PENDING],publicSafe:!0},S=ne(e.initialCursor,p,p,[],e.initialCursor?[O.WATCH_CURSOR_UNCHANGED]:[O.WATCH_NO_SUMMARIES_YET],e.initialCursor?"unchanged":"not_started");oe(re({watchStatus:"active",active:!0,targetEvidence:d,snapshotEvidence:h,cursorEvidence:S,stopReason:"not_stopped",reasonCodes:[O.OK]}),e.format,r);let E;try{E=await Kn({projectRoot:e.projectRoot,strictReadOnly:e.strictReadOnly})}catch{const _=se(void 0,[],!1,g,[O.WATCH_SNAPSHOT_UNAVAILABLE]),R=ne(e.initialCursor,p,p,[],[O.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),I=re({watchStatus:"blocked",active:!1,targetEvidence:d,snapshotEvidence:_,cursorEvidence:R,stopReason:"unavailable_evidence",reasonCodes:[$.STORE_UNAVAILABLE]});return oe(I,e.format,r),ae("store-unavailable",g,f,I)}try{for(;!e.signal?.aborted&&f<c;){f+=1;const _=p,R=E.collectProcessingOutputSummaryCursor({...p?{cursor:p}:{},...t?{target:t}:{},...n?{jobId:n}:{},limit:o}),I=E.collectSnapshot({jobLimit:50,processingSummaryLimit:1}),M=I.jobs;if(R.summaries.length>0){for(const V of R.summaries)No(V,e.format,r),g+=1;p=R.nextCursor??R.summaries[R.summaries.length-1]?.cursor??p,C=0}else p=R.nextCursor??p,C+=1;const L=se(I,R.summaries,!0,R.summaries.length),D=ne(e.initialCursor,_,p,R.summaries,R.summaries.length>0?[O.WATCH_CURSOR_ADVANCED]:[O.WATCH_NO_SUMMARIES_YET]);if(oe(re({watchStatus:R.summaries.length>0?"polling":"waiting",active:!0,targetEvidence:d,snapshotEvidence:L,cursorEvidence:D,stopReason:"not_stopped",reasonCodes:R.summaries.length>0?[O.WATCH_CURSOR_ADVANCED]:[O.WATCH_NO_SUMMARIES_YET],generatedAt:I.generatedAt}),e.format,r),!R.hasMore&&ko(M,n,g)){const V=se(I,R.summaries,!1,g,[$.COMPLETED]),x=ne(e.initialCursor,_,p,R.summaries,[$.COMPLETED],"exhausted"),v=re({watchStatus:"stopped",active:!1,targetEvidence:d,snapshotEvidence:V,cursorEvidence:x,stopReason:"not_stopped",reasonCodes:[$.COMPLETED],generatedAt:I.generatedAt});return oe(v,e.format,r),ae("completed",g,f,v)}if(!R.hasMore&&Lo(M,n,C,s)){const V=se(I,R.summaries,!1,g,[O.WATCH_STOP_IDLE_LIMIT_REACHED]),x=ne(e.initialCursor,_,p,R.summaries,[O.WATCH_STOP_IDLE_LIMIT_REACHED],"exhausted"),v=re({watchStatus:"stopped",active:!1,targetEvidence:d,snapshotEvidence:V,cursorEvidence:x,stopReason:"idle_limit_reached",reasonCodes:[$.IDLE_TIMEOUT,O.WATCH_STOP_IDLE_LIMIT_REACHED],generatedAt:I.generatedAt});return oe(v,e.format,r),ae("idle-timeout",g,f,v)}R.hasMore||await l(i,e.signal)}}catch{const _=se(void 0,[],!1,g,[O.WATCH_SNAPSHOT_UNAVAILABLE]),R=ne(e.initialCursor,p,p,[],[O.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),I=re({watchStatus:"blocked",active:!1,targetEvidence:d,snapshotEvidence:_,cursorEvidence:R,stopReason:"unavailable_evidence",reasonCodes:[$.STORE_UNAVAILABLE]});return oe(I,e.format,r),ae("store-unavailable",g,f,I)}finally{E.close()}if(e.signal?.aborted){const _=se(void 0,[],!1,g,[$.CANCELLED]),R=ne(e.initialCursor,p,p,[],[$.CANCELLED],"unavailable"),I=re({watchStatus:"stopped",active:!1,targetEvidence:d,snapshotEvidence:_,cursorEvidence:R,stopReason:"cancelled",reasonCodes:[$.CANCELLED]});return oe(I,e.format,r),ae("cancelled",g,f,I)}const T=se(void 0,[],!1,g,[O.WATCH_STOP_MAX_POLLS_REACHED]),k=ne(e.initialCursor,p,p,[],[O.WATCH_STOP_MAX_POLLS_REACHED],"exhausted"),w=re({watchStatus:"stopped",active:!1,targetEvidence:d,snapshotEvidence:T,cursorEvidence:k,stopReason:"max_polls_reached",reasonCodes:[$.MAX_POLLS,O.WATCH_STOP_MAX_POLLS_REACHED]});return oe(w,e.format,r),ae("max-polls",g,f,w)}function Q(e){const t=e.trim().replace(/^@/,"").match(/^(job|goal|loop)-([JGL])(\d{3,})$/i);if(!t)return;const n=t[1].toLowerCase(),r=t[2].toUpperCase();if(!(n==="job"&&r!=="J"||n==="goal"&&r!=="G"||n==="loop"&&r!=="L"))return`${n}-${r}${t[3]}`}function ft(e){if(e.startsWith("job-J"))return"job";if(e.startsWith("goal-G"))return"goal";if(e.startsWith("loop-L"))return"loop"}function An(e){const t=[],n=/(?:^|[\s"'([,{])@?(job-[Jj]\d{3,}|goal-[Gg]\d{3,}|loop-[Ll]\d{3,})(?=$|[\s"')\]},.;:!?])/g;let r;for(;(r=n.exec(e))!==null;){const o=Q(r[1]);o&&t.push(o)}return Y(t)}function Sn(e){return An(e)[0]}function Le(e){const t=e?Q(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 gt(e){return Y(e.filter(t=>typeof t=="string").map(t=>Q(t)).filter(t=>!!t?.startsWith("job-J")))}function Mo(e,t){const n=gt(t).filter(r=>r!==e.targetId&&r!==e.jobId);return n.length>0?{...e,relatedJobIds:n}:e}function Uo(e){if(!e)return;const t=m(e.target)?e.target:void 0,n=typeof e.selectorKind=="string"?e.selectorKind:typeof t?.selectorKind=="string"?t.selectorKind:void 0,r=typeof e.targetId=="string"?Q(e.targetId):typeof t?.targetId=="string"?Q(t.targetId):typeof e.targetJobId=="string"?Q(e.targetJobId):void 0,o=Le(r);if(!o||n&&n!==o.selectorKind)return;const i=Array.isArray(e.relatedJobIds)?e.relatedJobIds:Array.isArray(t?.relatedJobIds)?t.relatedJobIds:void 0,s=gt([...i??[],e.jobId,t?.jobId,e.targetJobId,t?.targetJobId]).filter(c=>c!==o.targetId&&c!==o.jobId);return{...o,...typeof(e.jobId??t?.jobId)=="string"?{jobId:Q(e.jobId??t?.jobId)??o.jobId}:{},...typeof(e.goalId??t?.goalId)=="string"?{goalId:Q(e.goalId??t?.goalId)??o.goalId}:{},...typeof(e.loopId??t?.loopId)=="string"?{loopId:Q(e.loopId??t?.loopId)??o.loopId}:{},...s.length>0?{relatedJobIds:s}:{}}}function Rn(e){const t=e.trim().split(/\s+/).filter(Boolean),n=t[0]?.replace(/^\*/,"").toLowerCase(),r=t[1]?.replace(/^--/,"").toLowerCase();return(n==="jobs"||n==="job"||n==="continuity-jobs"||n==="61")&&r==="watch"}const W=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"}),Vo=new Set(["create","start","resume"]),Bo=new Set(["create","resume","run-once"]);function ht(e,t,n,r,o){return{schemaVersion:1,contractVersion:"continuity-v1",...n?{command:n}:{},...r?{operation:r}:{},active:e,...o?{watchToken:o}:{},reasonCodes:Y(t),serverHeldStream:!1,allJobsPolling:!1,targetResolution:e?"required-after-dispatch":"inactive",publicSafe:!0}}function G(e,t=[],n,r){const o=t.length>0?t:[W.INACTIVE];return{args:e,watch:!1,reasonCodes:o,metadata:ht(!1,o,n,r),publicSafe:!0}}function $o(e){const t=e.trim().split(/\s+/).filter(Boolean),n=t.slice(2).filter(i=>i==="--watch").length;if(n===0)return G(e,[],"jobs","watch");if(n!==1)return G(e,[W.AMBIGUOUS],"jobs","watch");const r=t.filter((i,s)=>s<2||i!=="--watch").join(" ");return Rn(r)?r.trim().split(/\s+/).filter(Boolean).slice(2).length!==1?G(e,[W.AMBIGUOUS],"jobs","watch"):Sn(r)?{args:r,watch:!0,reasonCodes:[W.ACTIVE],metadata:ht(!0,[W.ACTIVE],"jobs","watch"),publicSafe:!0}:G(e,[W.TARGET_INVALID],"jobs","watch"):G(e,[W.UNSUPPORTED],"jobs","watch")}function Ho(e){const t=[];let n=!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 i="",s=!1,c=null;for(;r<e.length;){const l=e[r];if(c){if(l===c){s=!0,c=null,r+=1;continue}if(l==="\\"&&r+1<e.length){i+=e[r+1],r+=2;continue}i+=l,r+=1;continue}if(/\s/.test(l))break;if(l==='"'||l==="'"){s=!0,c=l,r+=1;continue}i+=l,r+=1}c&&(n=!0),t.push({value:i,start:o,end:r,quoted:s})}return{tokens:t,malformed:n}}function Wo(e){if(!e||e.quoted)return;const t=e.value.replace(/^\*/,"").toLowerCase();return t==="goal"||t==="loop"?t:void 0}function Fo(e,t){if(!e||e==="jobs"||!t||t.quoted)return;const n=t.value.toLowerCase();return(e==="goal"?Vo:Bo).has(n)?n:void 0}function Go(e){return!e.quoted&&e.value!=="--watch"&&e.value.toLowerCase().startsWith("--watch")}function Yo(e){const{tokens:t,malformed:n}=Ho(e),r=Wo(t[0]),o=Fo(r,t[1]);if(n)return G(e,[W.MALFORMED],r,o);const i=t.filter(f=>f.value==="--watch"&&!f.quoted),s=t.filter(f=>f.value==="--watch"&&f.quoted),c=t.filter(Go);if(!(i.length>0||s.length>0||c.length>0))return G(e,[],r,o);if(i.length>1)return G(e,[W.DUPLICATE],r,o);if(i.length===1&&(s.length>0||c.length>0))return G(e,[W.AMBIGUOUS],r,o);if(s.length>0)return G(e,[W.QUOTED],r,o);if(c.length>0)return G(e,[W.MALFORMED],r,o);const p=i[0];if(!p)return G(e,[],r,o);if(t[t.length-1]!==p)return G(e,[W.NON_FINAL],r,o);if(!r||!o)return G(e,[W.UNRESOLVED],r,o);const g=`${e.slice(0,p.start)}${e.slice(p.end)}`.trim(),C={literal:"--watch",position:"final",start:p.start,end:p.end,quoted:!1,publicSafe:!0};return{args:g,watch:!0,reasonCodes:[W.ACTIVE],metadata:ht(!0,[W.ACTIVE],r,o,C),publicSafe:!0}}function Jo(e){return Rn(e)?$o(e):Yo(e)}function zo(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&$r.has(t)):[]}function be(e){return{disabled:!0,reasonCodes:Y(e.length>0?e:[F.MISSING])}}function mt(e,t,n=[],r){const o=Le(t);if(o)return{source:e,target:Mo(o,n),targetJobId:o.targetId,...r?{initialCursor:r}:{},serverHeldStream:!1}}function qo(e){const t=new Map;for(const n of e){const r=`${n.target.selectorKind}:${n.target.targetId}`,o=t.get(r);if(!o){t.set(r,n);continue}const i=Y([...o.target.relatedJobIds??[],...n.target.relatedJobIds??[]]);t.set(r,{...o,target:i.length>0?{...o.target,relatedJobIds:i}:o.target,initialCursor:o.initialCursor??n.initialCursor})}return Array.from(t.values())}function fe(e,t,n,r){return{source:e,hasEvidence:t,candidates:qo(n.filter(o=>!!o)),...r&&r.length>0?{disabledReasonCodes:Y(r)}:{}}}function Ko(e,t){return e.target.selectorKind===t.target.selectorKind&&e.target.targetId===t.target.targetId}function xe(e,t){const n=Y(e.filter(r=>typeof r=="string").map(r=>Q(r)).filter(r=>!!r));if(t){const r=n.find(o=>ft(o)===t);if(r)return r}return n[0]}function Je(e,t){return Y(e.filter(n=>typeof n=="string").map(n=>Q(n)).filter(n=>!!n)).find(n=>ft(n)===t)}function Xo(e){const t=m(e?.continuity)?e.continuity:void 0,n=m(t?.jobs)?t.jobs:void 0,r=m(n?.watcher)?n.watcher:void 0,o=zo(r?.reasonCodes??n?.reasonCodes);if(!r)return fe("watcher-metadata",o.length>0,[],o);if(r.active===!1||o.length>0)return fe("watcher-metadata",!0,[],o.length>0?o:[F.MALFORMED]);if(r.serverHeldStream!==!1)return fe("watcher-metadata",!0,[],[F.SERVER_HELD_STREAM]);const i=Uo(r);if(!i)return fe("watcher-metadata",!0,[],[F.MISSING]);const s=typeof r.initialCursor=="string"?r.initialCursor:void 0;return fe("watcher-metadata",!0,[{source:"watcher-metadata",target:i,targetJobId:i.targetId,...s?{initialCursor:s}:{},serverHeldStream:!1}])}function wn(e,t){const n=m(e.loopJobPlan)?e.loopJobPlan:void 0,r=m(n?.metadata)?n.metadata:void 0,o=m(e.metadata)?e.metadata:void 0,s=(t==="goal"?xe([e.goalId,e.targetGoalId,e.campaignId,e.jobId,e.targetJobId,o?.goalId,o?.campaignId,o?.jobId],"goal"):xe([e.loopId,e.targetLoopId,e.jobId,e.targetJobId,o?.loopId,o?.jobId,r?.loopId,r?.jobId],"loop"))??xe([e.jobId,e.targetJobId,o?.jobId,r?.jobId]);return mt("goal-loop-continuity-metadata",s,[e.jobId,e.targetJobId,o?.jobId,r?.jobId])}function Zo(e){const t=m(e?.continuity)?e.continuity:void 0,n=m(t?.goal)?t.goal:void 0,r=m(t?.loop)?t.loop:void 0,o=[n?wn(n,"goal"):void 0,r?wn(r,"loop"):void 0],i=!!(n||r);return fe("goal-loop-continuity-metadata",i,o,i&&o.every(s=>!s)?[F.MISSING]:void 0)}function Qo(e){return Array.isArray(e)?e.filter(m):m(e)?Array.isArray(e.operationLogs)?e.operationLogs.filter(m):m(e.operationLog)?[e.operationLog]:Array.isArray(e.operations)?[e]:[]:[]}function Tn(e,t){const n=m(t.metadata)?t.metadata:void 0,r=Je([t.goalId,t.targetGoalId,t.campaignId,n?.goalId,n?.campaignId,t.jobId,n?.jobId],"goal"),o=Je([t.loopId,t.targetLoopId,n?.loopId,t.jobId,n?.jobId],"loop"),i=xe([t.jobId,t.targetJobId,n?.jobId],"job"),s=r??o??i;if(!s)return;const c=e.get(s)??{targetId:s,relatedJobIds:[]};c.relatedJobIds.push(...gt([i,t.jobId,t.targetJobId,n?.jobId])),e.set(s,c)}function ei(e){const t=m(e.metadata)?e.metadata:void 0;return!!(Je([e.goalId,e.targetGoalId,e.campaignId,t?.goalId,t?.campaignId,e.jobId,t?.jobId],"goal")??Je([e.loopId,e.targetLoopId,t?.loopId,e.jobId,t?.jobId],"loop"))}function ti(e){const t=m(e.metadata)?e.metadata:void 0;return!!xe([e.goalId,e.targetGoalId,e.campaignId,e.loopId,e.targetLoopId,e.jobId,e.targetJobId,t?.goalId,t?.campaignId,t?.loopId,t?.jobId])}function bn(e,t){const n=[];for(const s of["metadata","job","event","receipt","processingOutputSummary"]){const c=t[s];m(c)&&n.push(c)}const r=m(t.event)?t.event:void 0;m(r?.metadata)&&n.push(r.metadata),m(r?.processingOutputSummary)&&n.push(r.processingOutputSummary);const o=m(t.receipt)?t.receipt:void 0;m(o?.metadata)&&n.push(o.metadata);const i=n.some(ti);for(const s of n)Tn(e,s);(!i||ei(t))&&Tn(e,t)}function ni(e){const t=Qo(e?.continuityStateUpdate),n=new Map;for(const o of t){bn(n,o);const i=Array.isArray(o.operations)?o.operations.filter(m):[];for(const s of i)bn(n,s)}const r=Array.from(n.values()).map(o=>mt("continuity-state-update-operation-log",o.targetId,o.relatedJobIds));return fe("continuity-state-update-operation-log",t.length>0,r,t.length>0&&r.every(o=>!o)?[F.MISSING]:void 0)}function ri(e){const t=An(e);return fe("explicit-args",t.length>0,t.map(n=>mt("explicit-args",n)))}function oi(e,t){const n=[Xo(e),Zo(e),ni(e),ri(t)];for(let r=0;r<n.length;r+=1){const o=n[r];if(!o.hasEvidence)continue;if(o.disabledReasonCodes&&o.disabledReasonCodes.length>0)return be(o.disabledReasonCodes);if(o.candidates.length!==1)return be([o.candidates.length>1?F.AMBIGUOUS:F.MISSING]);const i=o.candidates[0];for(const s of n.slice(r+1)){if(!s.hasEvidence)continue;if(s.disabledReasonCodes&&s.disabledReasonCodes.length>0)return be(s.disabledReasonCodes);if(s.candidates.length>1)return be([F.AMBIGUOUS]);const c=s.candidates[0];if(c&&!Ko(i,c))return be([F.CONFLICT])}return{target:i.target,targetJobId:i.targetJobId,...i.initialCursor?{initialCursor:i.initialCursor}:{},source:i.source,serverHeldStream:!1}}return be([F.MISSING])}async function vn(e,t,n,r={}){const i=await ct(e,"/api/v1/invoke",t,n,r);if(i.networkFailure||!i.response)return{ok:!1,status:0,error:"Network error after bounded retries"};const{response:s,text:c,parsed:l}=i;try{if(!s.ok)return{ok:!1,status:s.status,error:Object.keys(l).length>0?`${l.error_code??"ERROR"}: ${l.message??c}`:`HTTP ${s.status}: ${c}`,errorBody:Object.keys(l).length>0?l:void 0};const p=l,g=s.headers.get("X-Client-Version-Warning");return g&&!pn&&(pn=!0,process.stderr.write(`
7
+ `)}catch{}}}function us(){mt=!1}function nr(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function co(e){return e==="active"||e==="archived"||e==="rolled-back"||e==="synthetic"||e==="orphan"?e:void 0}function or(e){return e==="create-epic"||e==="discovered"?e:void 0}function te(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function uo(e){const t={};let r=!1;for(const n of["contracts","contract_refs","shared_surfaces","adr_refs","nfr_refs","acceptance_depends_on"]){if(e[n]===void 0)continue;const o=e[n];if(!Array.isArray(o)||o.length>128||o.some(i=>Ye(i)===void 0)){r=!0;continue}t[n]=o.map(i=>Ye(i))}if(e.planning!==void 0)try{if(!y(e.planning))throw new Error("planning-shape");const n=e.planning;for(const a of["claims","semanticArtifacts"]){if(n[a]===void 0)continue;const c=n[a];if(!Array.isArray(c)||c.length>128||c.some(l=>!y(l)||Ye(l.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(!y(a)||!Array.isArray(a.reasonCodes)||a.reasonCodes.length>32||a.reasonCodes.some(c=>typeof c!="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(c)))throw new Error("planning-attempt-reasons");if(a.discoveredClaims!==void 0&&(!Array.isArray(a.discoveredClaims)||a.discoveredClaims.length>128||a.discoveredClaims.some(c=>!y(c)||Ye(c.ref)===void 0)))throw new Error("planning-attempt-claims")}const{graphRevision:o,...i}=kn(n);t.planning=i}catch{r=!0}return r&&(t.planning={schemaVersion:1,dependencyBasis:"unknown",claims:[],semanticArtifacts:[]}),t}function y(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ye(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function B(e){if(typeof e!="string")return;const t=e.trim();if(t)return t.replace(/[^a-z0-9_.:-]+/gi,"_").slice(0,120)}function D(e){if(typeof e!="string")return;const t=e.trim(),r=B(e);return r===t?r:void 0}function z(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240)&&/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(t)&&!(t.includes("..")||t.includes("//")||t.includes("@{")||t.endsWith("/")||t.endsWith("."))&&!t.split("/").some(r=>!r||r.startsWith(".")||r.endsWith(".lock")))return t}function S(e){return typeof e=="string"&&/^[0-9a-f]{7,64}$/i.test(e)?e:void 0}function re(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 Ie(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 Xe(e,t){if(!y(e))return;const r={};for(const n of t){const o=e[n];if(typeof o=="boolean")r[n]=o;else if(typeof o=="number"&&Number.isFinite(o))r[n]=o;else if(typeof o=="string"){const i=B(o);i&&(r[n]=i)}}return Object.keys(r).length>0?r:void 0}function Ze(e){return e==="epic"||e==="story"?e:void 0}function ir(e){if(!y(e)||e.schemaVersion!==1)return;const t=D(e.ownerStoryId),r=D(e.sessionId),n=D(e.idempotencyKey),o=re(e.acquiredAt),i=re(e.expiresAt);if(!(!t||!r||!n||!o||!i||Date.parse(i)<=Date.parse(o)))return{schemaVersion:1,ownerStoryId:t,sessionId:r,idempotencyKey:n,acquiredAt:o,expiresAt:i}}function sr(e){if(!y(e)||e.schemaVersion!==1)return;const t=D(e.storyId),r=D(e.epicId),n=z(e.branch),o=S(e.baseSha),i=S(e.headSha),a=D(e.idempotencyKey),c=re(e.recordedAt),l=te(e.commits).map(S).filter(P=>!!P).slice(0,256),p=te(e.receiptRefs).map(Ie).filter(P=>!!P).slice(0,256),g=e.dispatchId===void 0?void 0:D(e.dispatchId),R=e.bundleId===void 0?void 0:D(e.bundleId),f=e.bundleDigest===void 0?void 0:S(e.bundleDigest),d=e.graphRevision===void 0?void 0:S(e.graphRevision),I=e.claimRevision===void 0?void 0:D(e.claimRevision),A=lo(e.qaReceipt),C=po(e.reviewReceipt);if(!(!t||!r||!t.startsWith(`${r}.`)||!n||!o||!i||o===i||!a||!c||l.length===0||p.length===0||!Array.isArray(e.commits)||l.length!==e.commits.length||e.commits.length>256||!Array.isArray(e.receiptRefs)||p.length!==e.receiptRefs.length||e.receiptRefs.length>256||e.dispatchId!==void 0&&!g||e.bundleId!==void 0&&!R||e.bundleDigest!==void 0&&(!f||f.length!==64)||e.graphRevision!==void 0&&(!d||d.length!==64)||e.claimRevision!==void 0&&!I||e.qaVerdict!=="passed"&&e.qaVerdict!=="blocked"||!["approved","changes-requested","pending"].includes(String(e.reviewVerdict))||!A||e.reviewVerdict!=="pending"&&!C||e.reviewVerdict==="pending"&&C||A.verdict!==e.qaVerdict||C&&C.verdict!==e.reviewVerdict||!dr(A,{storyId:t,epicId:r,baseSha:o,headSha:i,bundleDigest:f,graphRevision:d})||C&&(!dr(C,{storyId:t,epicId:r,baseSha:o,headSha:i,bundleDigest:f,graphRevision:d})||C.qaReceiptRef!==A?.receiptRef||C.receiptRef===A?.receiptRef)||!p.includes(String(A.receiptRef))||C&&(!p.includes(String(C.receiptRef))||Date.parse(String(C.reviewedAt))<Date.parse(String(A.checkedAt)))))return{schemaVersion:1,storyId:t,epicId:r,branch:n,baseSha:o,headSha:i,idempotencyKey:a,...g?{dispatchId:g}:{},...R?{bundleId:R}:{},...f?{bundleDigest:f}:{},...d?{graphRevision:d}:{},...I?{claimRevision:I}:{},qaVerdict:e.qaVerdict,reviewVerdict:e.reviewVerdict,...A?{qaReceipt:A}:{},...C?{reviewReceipt:C}:{},recordedAt:c,commits:l,receiptRefs:p}}function lo(e){if(!y(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=D(e.storyId),r=D(e.epicId),n=S(e.baseSha),o=S(e.headSha),i=S(e.bundleDigest),a=S(e.graphRevision),c=S(e.sourceEvidenceDigest),l=re(e.checkedAt),p=Ie(e.receiptRef),g=e.evidenceVersion==="p205-execution-v2"&&e.contract==="P205-CI-02"?e.contract:void 0,R=e.evidenceVersion==="p205-execution-v2"&&e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,f=e.evidenceVersion==="p205-execution-v2"?S(e.manifestDigest):void 0,d=e.evidenceVersion==="p205-execution-v2"?S(e.resultDigest):void 0,I=e.evidenceVersion==="p205-execution-v2"?te(e.gateIds).map(D).filter(A=>!!A).slice(0,64):void 0;if(!(!t||!r||!n||!o||!i||i.length!==64||!a||a.length!==64||!c||c.length!==64||!l||!p||e.evidenceVersion==="p205-execution-v2"&&(!g||R!=="node scripts/test-root.mjs --gate complete"||!f||f.length!==64||!d||d.length!==64||!Array.isArray(e.gateIds)||!I||I.length===0||I.length!==e.gateIds.length)))return{schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",...e.evidenceVersion?{evidenceVersion:e.evidenceVersion}:{},storyId:t,epicId:r,...e.evidenceVersion==="p205-execution-v2"?{contract:g,command:R,manifestDigest:f,gateIds:I,resultDigest:d}:{},baseSha:n,headSha:o,bundleDigest:i,graphRevision:a,sourceEvidenceDigest:c,verdict:e.verdict,checkedAt:l,receiptRef:p}}function ar(e){if(!y(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=D(e.storyId),r=D(e.epicId),n=z(e.branch),o=S(e.baseSha),i=S(e.headSha),a=S(e.aggregateHeadSha),c=S(e.commitBodyDigest),l=S(e.changedPathsDigest),p=e.claimVerification==="canonical"||e.claimVerification==="legacy-migration"?e.claimVerification:void 0,g=S(e.effectiveClaimRevision),R=e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,f=S(e.manifestDigest),d=te(e.gateIds).map(D).filter(h=>!!h).slice(0,64),I=S(e.resultDigest),A=S(e.graphRevision),C=S(e.executionEvidenceDigest),P=S(e.sourceEvidenceDigest),v=re(e.verifiedAt),j=te(e.reasonCodes).map(D).filter(h=>!!h).slice(0,16);if(!(!t||!r||!n||!o||o.length<40||!i||i.length<40||!a||a.length<40||!c||c.length!==64||!l||l.length!==64||!p||!g||g.length!==64||!R||!f||f.length!==64||!Array.isArray(e.gateIds)||d.length!==e.gateIds.length||!I||I.length!==64||!A||A.length!==64||!C||C.length!==64||!P||P.length!==64||!v||j.length===0||e.verdict==="verified"&&(d.length===0||!j.includes("checkpoint-p205-transient-verified"))))return{schemaVersion:1,kind:"story_checkpoint_physical_verification",producer:"client-p205-transient-v1",storyId:t,epicId:r,branch:n,baseSha:o,headSha:i,aggregateHeadSha:a,commitBodyDigest:c,changedPathsDigest:l,claimVerification:p,effectiveClaimRevision:g,command:R,manifestDigest:f,gateIds:d,resultDigest:I,graphRevision:A,executionEvidenceDigest:C,sourceEvidenceDigest:P,verifiedAt:v,verdict:e.verdict,reasonCodes:j,publicSafe:!0}}function cr(e){const t=["schemaVersion","kind","producer","storyId","epicId","branch","baseSha","headSha","graphRevision","effectiveClaimRevision","sourceEvidenceDigest","verifiedAt","reasonCodes","integrationAuthorized","publicSafe"];if(!y(e)||Object.keys(e).some(f=>!t.includes(f))||e.schemaVersion!==1||e.kind!=="story_scheduling_checkpoint_evidence"||e.producer!=="client-git-physical-v1"||e.integrationAuthorized!==!1||e.publicSafe!==!0)return;const r=D(e.storyId),n=D(e.epicId),o=z(e.branch),i=S(e.baseSha),a=S(e.headSha),c=S(e.graphRevision),l=S(e.effectiveClaimRevision),p=S(e.sourceEvidenceDigest),g=re(e.verifiedAt),R=te(e.reasonCodes).map(D).filter(f=>!!f);if(!(!r||!n||!o||!i||i.length<40||!a||a.length<40||!c||c.length!==64||!l||l.length!==64||!p||p.length!==64||!g||!Array.isArray(e.reasonCodes)||R.length!==1||R[0]!=="checkpoint-git-scheduling-verified"))return{schemaVersion:1,kind:"story_scheduling_checkpoint_evidence",producer:"client-git-physical-v1",storyId:r,epicId:n,branch:o,baseSha:i,headSha:a,graphRevision:c,effectiveClaimRevision:l,sourceEvidenceDigest:p,verifiedAt:g,reasonCodes:R,integrationAuthorized:!1,publicSafe:!0}}function po(e){if(!y(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=D(e.storyId),r=D(e.epicId),n=S(e.baseSha),o=S(e.headSha),i=S(e.bundleDigest),a=S(e.graphRevision),c=S(e.sourceEvidenceDigest),l=Ie(e.qaReceiptRef),p=re(e.reviewedAt),g=Ie(e.receiptRef);if(!(!t||!r||!n||!o||!i||i.length!==64||!a||a.length!==64||!c||c.length!==64||!l||!p||!g))return{schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:t,epicId:r,baseSha:n,headSha:o,bundleDigest:i,graphRevision:a,sourceEvidenceDigest:c,qaReceiptRef:l,verdict:e.verdict,reviewedAt:p,receiptRef:g}}function dr(e,t){return["storyId","epicId","baseSha","headSha","bundleDigest","graphRevision"].every(r=>e[r]===t[r])}function ur(e){if(!y(e)||e.schemaVersion!==1||e.capturedFromCurrentCheckout!==!0)return;const t=z(e.originBranch),r=S(e.originHeadSha),n=z(e.executionBranch),o=re(e.capturedAt);if(!(!t||!r||r.length<40||!n||!o||t===n))return{schemaVersion:1,originBranch:t,originHeadSha:r,executionBranch:n,capturedFromCurrentCheckout:!0,capturedAt:o}}function lr(e){if(!y(e)||e.schemaVersion!==1||e.verdict!=="passed")return;const t=S(e.executionHeadSha),r=S(e.graphRevision),n=re(e.checkedAt),o=Ie(e.receiptRef),i=te(e.gateIds).map(D).filter(g=>!!g).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",c=e.evidenceVersion===void 0&&e.producer===void 0&&e.contract===void 0&&e.command===void 0&&e.manifestDigest===void 0&&e.resultDigest===void 0,l=a?S(e.manifestDigest):void 0,p=a?S(e.resultDigest):void 0;if(!(!t||t.length<40||!r||r.length!==64||!n||!o||i.length===0||!Array.isArray(e.gateIds)||i.length!==e.gateIds.length||e.gateIds.length>128||!c&&!a||a&&(!l||l.length!==64||!p||p.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:l,resultDigest:p}:{},verdict:"passed",executionHeadSha:t,graphRevision:r,checkedAt:n,receiptRef:o,gateIds:i}}function Qe(e){if(!y(e)||e.schemaVersion!==1)return;const t=Xe(e,["schemaVersion","kind","storyId","epicId","baseSha","headSha","originalBaseSha","originalHeadSha","gitPullRequest","preservesLaterCommits","historyRewrite","recordedAt"])??{},r=te(e.receiptRefs).map(Ie).filter(o=>!!o).slice(0,256),n=te(e.revertCommits).map(B).filter(o=>!!o).slice(0,256);return{...t,...r.length?{receiptRefs:r}:{},...n.length?{revertCommits:n}:{}}}function pr(e){if(!y(e)||e.schemaVersion!==1||e.publicSafe!==!0)return;const t=D(e.epicId),r=z(e.executionBranch),n=z(e.originBranch),o=S(e.baseSha),i=S(e.executionHeadSha),a=e.mergeSha===void 0?void 0:S(e.mergeSha),c=e.pushedSha===void 0?void 0:S(e.pushedSha),l=D(e.idempotencyKey),p=re(e.attemptStartedAt),g=e.completedAt===void 0?void 0:re(e.completedAt),R=te(e.localGateReceiptRefs).map(Ie).filter(A=>!!A).slice(0,256),f=te(e.reasonCodes).map(D).filter(A=>!!A).slice(0,64),d=ho(e.candidateQa),I=fo(e.providerGuard);if(!(!t||!r||!n||!o||!i||!l||!p||R.length===0||f.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:r,originBranch:n,baseSha:o,executionHeadSha:i,...a?{mergeSha:a}:{},...c?{pushedSha:c}:{},strategy:e.strategy,...ye(e.prNumber)?{prNumber:ye(e.prNumber)}:{},physicalStatus:e.physicalStatus,localGateReceiptRefs:R,idempotencyKey:l,attemptStartedAt:p,...d?{candidateQa:d}:{},...I?{providerGuard:I}:{},...g?{completedAt:g}:{},retryEligible:e.retryEligible,reasonCodes:f,publicSafe:!0}}function fo(e){if(!y(e)||e.schemaVersion!==1||e.provider!=="github"||e.publicSafe!==!0)return;const t=String(e.mode),r=String(e.source),n=t==="recovered_exact_tree"?r==="physical_recovery":t==="strict_up_to_date_expected_head"&&["branch_protection","ruleset","branch_protection_and_ruleset"].includes(r),o=S(e.prHeadSha),i=S(e.originHeadSha),a=re(e.checkedAt);if(!(!n||!o||!i||!a))return{schemaVersion:1,provider:"github",mode:t,source:r,prHeadSha:o,originHeadSha:i,checkedAt:a,publicSafe:!0}}function ho(e){if(!y(e)||e.schemaVersion!==1||e.kind!=="epic_merge_candidate_qa"||e.contract!=="P205-CI-02"||e.command!==jn)return;const r=Object.fromEntries(["originHeadSha","executionHeadSha","mergeSha","treeSha","graphRevision","manifestDigest","resultDigest"].map(a=>[a,S(e[a])])),n=re(e.checkedAt),o=Ie(e.receiptRef),i=te(e.gateIds).filter(a=>/^[a-z0-9-]+$/.test(a)).slice(0,128);if(!(Object.values(r).some(a=>!a)||!n||!o||i.length===0))return{schemaVersion:1,kind:e.kind,contract:e.contract,command:e.command,...r,checkedAt:n,receiptRef:o,gateIds:i}}function go(e){if(!y(e))return;const t={...B(e.active_epic_id??e.activeEpicId)?{active_epic_id:B(e.active_epic_id??e.activeEpicId)}:{},...B(e.active_story_id??e.activeStoryId)?{active_story_id:B(e.active_story_id??e.activeStoryId)}:{},...B(e.active_step_id??e.activeStepId)?{active_step_id:B(e.active_step_id??e.activeStepId)}:{},...B(e.session_id??e.sessionId)?{session_id:B(e.session_id??e.sessionId)}:{},...B(e.started_at??e.startedAt)?{started_at:B(e.started_at??e.startedAt)}:{}};return Object.keys(t).length>0?t:void 0}function mo(e){const t=Xe(e.completionEvidence??e.completion_evidence,["prNumber","pr_number","prState","pr_state","pullRequestState","merged","mergedAt","issueNumber","issue_number","issueState","issue_state","closedAt"]),r=Xe(e.issueCloseAudit??e.issue_close_audit,["schema_version","event","storyId","epicId","issueNumber","closedAt","publicSafe","rawLogStorage"]),n=Xe(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}:{},...B(e.physicalMergeStatus)?{physicalMergeStatus:B(e.physicalMergeStatus)}:{},...B(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)?{pr_state:B(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)}:{},...B(e.issue_state??e.issueState??e.workflow_issue_state)?{issue_state:B(e.issue_state??e.issueState??e.workflow_issue_state)}:{},...ye(e.issue_number??e.issueNumber)?{issue_number:ye(e.issue_number??e.issueNumber)}:{},...t?{completionEvidence:t}:{},...r?{issueCloseAudit:r}:{},...n?{scopedCiEvidence:n}:{}}}class Ee extends Error{reasonCode;constructor(t){super(t),this.name="StateSnapshotIntegrityError",this.reasonCode=t}}const yo=new Set(["yolo","yoloop","finalize-epic","audit"]);function fr(e){return typeof e=="string"&&yo.has(e)}function hr(e,t={}){const r=ae(e,".neocortex","state.json");if(!Oe(r))throw new Ee("git-lifecycle-state-missing");let n;try{n=JSON.parse(xe(r,"utf8"))}catch{throw new Ee("git-lifecycle-state-corrupt")}if(!y(n)||!y(n.epics)||!y(n.stories))throw new Ee("git-lifecycle-state-shape-invalid");const o=Object.values(n.epics).some(i=>y(i)&&(i.branch_mode==="epic"||z(i.execution_branch)!==void 0));if(o)try{Je(e,{required:!0})}catch(i){const a=i instanceof Error&&/^git-lifecycle-/.test(i.message)?i.message:"git-lifecycle-runtime-invalid";if(t.allowMissingRuntime&&a==="git-lifecycle-runtime-missing")return{lifecycleDeclared:!0,runtimeMissing:!0};throw new Ee(a)}return{lifecycleDeclared:o,runtimeMissing:!1}}function gr(e,t={}){const r=ae(e,".neocortex","state.json");if(!Oe(r)){if(t.epicAware&&!t.projectless)throw new Ee("git-lifecycle-state-missing");return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}let n;try{const f=xe(r,"utf-8"),d=JSON.parse(f),I=y(d.epics)?d.epics:{},A=Object.values(I).some(h=>y(h)&&(h.branch_mode==="epic"||z(h.execution_branch)!==void 0)),C=Je(e,{required:!!(t.epicAware&&A&&!t.projectless)});n=Gt(d,C);const P=y(n.stories)?n.stories:{},v=y(n.epics)?n.epics:{},j=y(d.stories)?d.stories:{};for(const[h,w]of Object.entries(P)){const E=y(w)?w:void 0;if(!E?.checkpoint)continue;const U=typeof E.epic_id=="string"?E.epic_id:h.split(".")[0],k=y(v[U])?v[U]:void 0,N=z(k?.execution_branch);if(!N)continue;const $=Nn(e,E.checkpoint,h,U,N,t.p205Authorities?.[h],Yt(h,E,y(E.checkpoint)?E.checkpoint:void 0));if($.kind==="integration-authorized")E.checkpoint_verification=$.verification,delete E.scheduling_checkpoint_evidence;else if($.kind==="scheduling-only")E.scheduling_checkpoint_evidence=$.evidence,delete E.checkpoint,delete E.checkpoint_verification;else if($.kind==="rejected"){E.checkpoint_verification=$.verification,delete E.scheduling_checkpoint_evidence;const L=y(j[h])?j[h]:void 0;if(delete E.checkpoint,C.stories[h]?.checkpoint!==void 0)for(const T of["status","last_step","steps_completed"])L&&Object.prototype.hasOwnProperty.call(L,T)?E[T]=structuredClone(L[T]):delete E[T];["done","completed","merged"].includes(String(E.status).toLowerCase())&&(E.status="blocked")}}}catch(f){if(t.epicAware&&!t.projectless){const d=f instanceof Error&&/^git-lifecycle-/.test(f.message)?f.message:"git-lifecycle-state-corrupt";throw new Ee(d)}return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}try{const f=so(n);f.length>0&&ao(f)}catch{}const o=n.config??n.project??{},i=n.stories??{},a={};for(const[f,d]of Object.entries(i))a[f]={id:d.id??f,title:d.title,epic_id:d.epic_id,status:d.status??"backlog",...or(d.source)?{source:or(d.source)}:{},steps_completed:d.steps_completed??[],last_step:d.last_step??null,branch_name:d.branch_name??null,pr_number:d.pr_number,...Ze(d.branch_mode)?{branch_mode:Ze(d.branch_mode)}:{},...sr(d.checkpoint)?{checkpoint:sr(d.checkpoint)}:{},...ar(d.checkpoint_verification)?{checkpoint_verification:ar(d.checkpoint_verification)}:{},...cr(d.scheduling_checkpoint_evidence)?{scheduling_checkpoint_evidence:cr(d.scheduling_checkpoint_evidence)}:{},...Qe(d.review_request)?{review_request:Qe(d.review_request)}:{},...Qe(d.rollback_receipt)?{rollback_receipt:Qe(d.rollback_receipt)}:{},...ye(d.workflow_issue)?{workflow_issue:ye(d.workflow_issue)}:{},...mo(d),depends_on:nr(d.depends_on),files_to_modify:te(d.files_to_modify),...uo(d),risk:typeof d.risk=="string"?d.risk:void 0,blast_radius:typeof d.blast_radius=="number"?d.blast_radius:void 0};const c=n.epics??{},l={};for(const[f,d]of Object.entries(c)){const I=co(d.lifecycle_classification);l[f]={id:d.id??f,title:d.title,status:d.status,stories:d.stories,total_stories:d.total_stories,completed_stories:d.completed_stories,depends_on:nr(d.depends_on),...Ze(d.branch_mode)?{branch_mode:Ze(d.branch_mode)}:{},...z(d.execution_branch)?{execution_branch:z(d.execution_branch)}:{},...z(d.origin_branch)?{origin_branch:z(d.origin_branch)}:{},...ir(d.branch_lease)?{branch_lease:ir(d.branch_lease)}:{},...ur(d.origin_binding)?{origin_binding:ur(d.origin_binding)}:{},...lr(d.aggregate_qa_receipt)?{aggregate_qa_receipt:lr(d.aggregate_qa_receipt)}:{},...ye(d.pr_number)?{pr_number:ye(d.pr_number)}:{},...B(d.physicalMergeStatus)?{physicalMergeStatus:B(d.physicalMergeStatus)}:{},...S(d.graph_revision)?{graph_revision:S(d.graph_revision)}:{},...pr(d.terminal_git_receipt)?{terminal_git_receipt:pr(d.terminal_git_receipt)}:{},...I?{lifecycle_classification:I}:{}}}const p=go(n.current_session??n.currentSession),g=n.epic_id_ledger,R=Array.isArray(g?.reserved_ids)?[...new Set(g.reserved_ids.filter(f=>typeof f=="string"&&/^P\d+$/.test(f)))].slice(0,2048):[];return{schema_version:typeof n.schema_version=="number"?n.schema_version:void 0,config:{project_name:o.project_name??o.name??"unknown",default_branch:o.default_branch??"main",language:o.language??"pt-BR",yolo_mode:o.yolo_mode,user_name:o.user_name,worktree_base:o.worktree_base,max_parallel_stories:o.max_parallel_stories,project_id:typeof o.project_id=="string"?o.project_id:void 0},stories:a,epics:l,...R.length>0?{epic_id_ledger:{schema_version:1,reserved_ids:R}}:{},...p?{current_session:p}:{}}}async function Io(e,t,r){if(!fr(r))return{};if(en(t,r))return{};try{const n=JSON.parse(xe(ae(e,".neocortex","state.json"),"utf8")),o=Je(e,{required:!0}),i=Gt(n,o),a=y(i.stories)?i.stories:{},c=y(i.epics)?i.epics:{},l=Te("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8"}).trim(),p=Te("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8"}).trim(),g=Te("git",["rev-list","--first-parent","--reverse",l],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
8
+ `).filter(Boolean),R=new Map(g.map((h,w)=>[h,w])),f=t.match(/(?:^|\s)@?docs\/stories\/([A-Za-z][A-Za-z0-9._-]*)\.story\.md(?:\s|$)/)?.[1],d=r==="yoloop"?t.match(/(?:^|[\s/@])epic-(P[1-9][0-9]*)\.md(?:\s|$)/i)?.[1]?.toUpperCase():void 0,I=new Set,A=Object.entries(a).flatMap(([h,w])=>{if(f&&h!==f)return[];const E=y(w)?w:void 0,U=y(E?.checkpoint)?E.checkpoint:void 0;if(!U)return[];const k=typeof E?.epic_id=="string"?E.epic_id:h.split(".")[0];if(d&&k!==d)return[];const N=S(U?.headSha);if(!N||N.length<40||R.get(N)===void 0)return I.add(k),[];const $=y(c[k])?c[k]:void 0;if($?.branch_mode!=="epic"||z($.execution_branch)!==p||z(U.branch)!==p)return I.add(k),[];const L=S(U.graphRevision);if(!L||L.length!==64)return I.add(k),[];const T=S(U.claimRevision),J=[...Yt(h,E,U)].sort(),Ce=Mn(e,U,h,k,p,J);if(!Ce&&T){if(J.length===0)return I.add(k),[];const he=Te("git",["diff-tree","--no-commit-id","--name-only","-r","-z",N],{cwd:e,encoding:"utf8"}).split("\0").filter(Boolean);if(he.length===0||he.some(Se=>!J.some(F=>F===Se||F.endsWith("/")&&Se.startsWith(F))))return I.add(k),[];const be=Ue("sha256").update(J.join("\0")).digest("hex"),He=Ue("sha256").update(JSON.stringify(J)).digest("hex");if(T!==be&&T!==He)return I.add(k),[]}else if(!Ce)return I.add(k),[];return L?.length===64?[{storyId:h,epicId:k,graphRevision:L,checkpointHead:N,position:R.get(N)}]:[]}),C=new Set(I);for(const[h,w]of Object.entries(c)){const E=y(w)?w:void 0,U=Array.isArray(E?.stories)?E.stories.filter(L=>typeof L=="string"):Object.keys(a).filter(L=>L.startsWith(`${h}.`)),k=A.filter(L=>L.epicId===h),N=U.filter(L=>k.some(T=>T.storyId===L)),$=[...k].sort((L,T)=>L.position-T.position).map(L=>L.storyId);(JSON.stringify(N)!==JSON.stringify($)||new Set($).size!==$.length)&&C.add(h)}const P={},v=[...new Set(A.filter(h=>!C.has(h.epicId)).map(h=>h.graphRevision))],j=v.length>0?await Pn(e,{headSha:l,graphRevisions:v}):new Map;for(const h of A){if(C.has(h.epicId))continue;const w=j.get(h.graphRevision);if(!w)throw new Error("p205-transient-authority-missing");P[h.storyId]=w}return P}catch(n){const o=n instanceof Error&&/^(?:p205|git-lifecycle)-[a-z0-9-]+$/.test(n.message)?n.message:"p205-transient-execution-failed";return process.stderr.write(`[Neocortex] ${o}. Checkpoint projection remains fail-closed.
9
+ `),{}}}function ls(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 mr="neocortex:menu:cache";async function Eo(e){try{const t=await e.get(mr);if(!t)return null;const r=JSON.parse(t);return r.version!==ke||Date.now()-r.cachedAt>zt?null:r}catch{return null}}async function _o(e,t,r){try{const n={instructions:t,metadata:r,cachedAt:Date.now(),version:ke};await e.set(mr,JSON.stringify(n),zt),Co()}catch{}}function Co(){try{Oe(Jt)&&Wr(Jt)}catch{}}function So(e){return e.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>kt(),()=>kt({strictReadOnly:!0}))}async function yr(e,t,r){const n=r.mode==="strict";try{let o;if(n&&t)o=new st({cacheDir:ct,passphrase:t,strictReadOnly:!0});else if(n)o=new Ot;else if(t){const g=ae(ze,"cache");o=new st({cacheDir:g,passphrase:t})}else process.stderr.write(`[neocortex] Warning: No license key in config. Run "neocortex activate" to re-authenticate.
10
+ `),o=new Ot;const i=$t(r,o,"auth-cache"),a=$t(r,o,"tier-cache"),c=new Yr({serverUrl:e,licenseKey:t??"",cacheProvider:i,strictReadOnly:n});let l;if(n){const g=await c.inspectToken();if(g.status!=="authenticated")return g;l=g.token}else l=await c.getToken();if(!l)return{status:"not-configured"};const p=new Jr({cacheProvider:a,licenseClient:c});return{status:"authenticated",token:l,client:c,tierClient:p}}catch{return n&&t?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"}}}let Ir=!1;function Ao(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 Er=3,et=50;function Ro(e){return new Promise(t=>setTimeout(t,e))}function wo(e,t,r){return e.status>=500&&e.status<=599?!0:r&&e.status===409&&t.error_code==="SIGNATURE_REPLAYED"}async function Ve(e,t,r,n,o={}){const i=Math.max(1,Math.min(o.maxAttempts??Er,Er)),a=o.sleep??Ro;let c=n,l=!1,p=!1,g=0;for(let R=1;R<=i;R+=1){const f=Math.max(Math.floor(Date.now()/1e3),g+1);g=f;const d=vo(t,r,c,{nowSeconds:f}),I=new AbortController,A=setTimeout(()=>I.abort(),qt);try{const C=await fetch(`${e}${t}`,{method:"POST",headers:d.headers,body:d.body,signal:I.signal}),P=await C.text().catch(()=>""),v=(()=>{try{return P?JSON.parse(P):{}}catch{return{}}})();if(C.status===401&&!l&&o.refreshToken&&(v.fallback_action==="refresh_token"||v.fallback_action==="re_authenticate")){l=!0;const j=await o.refreshToken();if(j&&R<i){c=j,o.onTokenChanged?.(j),await a(et*R);continue}}if(C.status===401&&v.error_code==="SIGNATURE_EXPIRED"&&!p&&R<i){p=!0,await a(et*R);continue}if(R<i&&wo(C,v,o.allowReplayRetry===!0)){await a(et*R);continue}return{response:C,text:P,parsed:v,networkFailure:!1}}catch{if(R<i){await a(et*R);continue}return{text:"",parsed:{},networkFailure:!0}}finally{clearTimeout(A)}}return{text:"",parsed:{},networkFailure:!0}}function vo(e,t,r,n={}){const o=Buffer.from(JSON.stringify(t),"utf8"),i=fn({method:"POST",target:e,body:o,bearerToken:r,clientVersion:ke,nowSeconds:n.nowSeconds,nonceBytes:n.nonceBytes});return{body:i.body,headers:{...i.headers,Authorization:`Bearer ${r}`}}}function _r(e){return Ue("sha256").update(e).digest("hex")}function bo(){const e=Number(process.env.NEOCORTEX_INVOKE_CHUNK_BYTES??"49152");return Number.isFinite(e)&&e>=1024&&e<=98304?Math.floor(e):49152}function To(e,t,r){return`args-${Ue("sha256").update("invoke-materialization:v1").update(e).update(String(t)).update(JSON.stringify(r)).digest("hex")}`}async function Cr(e,t,r,n,o={}){const i=await Ve(e,t,r,n,{...o,allowReplayRetry:!0});if(i.networkFailure||!i.response)throw new Error("NETWORK_ERROR: materialization request failed after bounded retries");const{response:a,parsed:c}=i;if(!a.ok){const l=typeof c.error_code=="string"?c.error_code:`HTTP_${a.status}`,p=typeof c.message=="string"?c.message:"materialization upload failed";throw new Error(`${l}: ${p}`)}return c}async function Oo(e,t,r,n){const o=Buffer.from(t,"utf8"),i=bo(),a=[];for(let I=0,A=0;I<o.byteLength;I+=i,A++){const C=o.subarray(I,Math.min(I+i,o.byteLength));a.push({index:A,sha256:_r(C),byteLength:C.byteLength})}const c=_r(o),l=To(c,o.byteLength,a),p=Number(process.env.NEOCORTEX_INVOKE_CHUNK_TTL_SECONDS??"900");let g=r;const R={refreshToken:n,onTokenChanged(I){g=I}};for(const I of a){const A=I.index*i,C=o.subarray(A,A+I.byteLength);await Cr(e,"/api/v1/invoke/materialization/chunks",{manifestId:l,index:I.index,sha256:I.sha256,byteLength:I.byteLength,contentBase64:C.toString("base64"),ttlSeconds:p,idempotencyKey:`${l}:${I.index}:${I.sha256}`},g,R)}const d=(await Cr(e,"/api/v1/invoke/materialization/manifests",{manifestId:l,sha256:c,byteLength:o.byteLength,chunkCount:a.length,chunks:a,ttlSeconds:p,retry:{attempt:1,budget:3,idempotencyKey:l}},g,R)).argsRef;if(!d?.manifestId)throw new Error("MATERIALIZATION_RESPONSE_INVALID: missing argsRef");return{argsRef:d,chunks:a}}function Pe(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function xo(...e){const t=new Set,r=[];for(const n of e)for(const o of n??[]){const i=B(o);if(!(!i||t.has(i))&&(t.add(i),r.push(i),r.length>=16))return r}return r}function ko(e){const t=e.graphRetrieval;if(!y(t))return{accepted:!1,itemCount:0};const r=Array.isArray(t.items)?t.items.length:0;return{accepted:r>0||typeof t.retrievalId=="string"||t.accepted===!0,itemCount:r}}function yt(e,t=Pe(e),r=[],n={}){const o=e.stateSnapshot.scope,i=Object.keys(e.stateSnapshot.stories).length,a=Object.keys(e.stateSnapshot.epics).length,c=o?.kind??"full";return{schemaVersion:1,payloadBytes:t,limitBytes:n.limitBytes??Xt,warningThresholdBytes:n.warningThresholdBytes??dt,scope:{kind:c,...o?.projectionMode?{projectionMode:o.projectionMode}:{},commandId:o?.commandId??null,stateProjectionPolicy:o?.stateProjectionPolicy??null},includedStories:o?.includedStoryCount??i,omittedStories:o?.omittedStoryCount??0,includedEpics:o?.includedEpicCount??a,omittedEpics:o?.omittedEpicCount??0,graphRetrieval:ko(e.stateSnapshot),reasonCodes:xo(r,o?.reasonCodes),publicSafe:!0}}function No(e){const t=y(e.budget)?e.budget:void 0,r=typeof t?.maxPayloadBytes=="number"&&Number.isFinite(t.maxPayloadBytes)?t.maxPayloadBytes:12*1024;return Math.max(1024,Math.min(r,12*1024))}function Lo(e){return y(e)?{stableId:B(e.stableId)??"unknown",...y(e.source)?{source:e.source}:{},reasonCode:"budget_exceeded"}:{stableId:"unknown",reasonCode:"budget_exceeded"}}function Sr(e){const t=Array.isArray(e)?e.filter(r=>typeof r=="string"):[];return t.includes("budget_exceeded")?t:[...t,"budget_exceeded"]}function Po(e){const t=e.graphRetrieval;if(!y(t)||!Array.isArray(t.items))return e;const r=No(t);let n=[...t.items],o=Array.isArray(t.skipped)?[...t.skipped]:[],i=t;for(;Buffer.byteLength(JSON.stringify(i),"utf8")>r&&n.length>0;){const a=n.pop();o=[...o,Lo(a)].slice(-32),i={...t,items:n,skipped:o,warnings:Sr(t.warnings)}}return Buffer.byteLength(JSON.stringify(i),"utf8")>r&&(i={...t,query:typeof t.query=="string"?t.query.slice(0,240):t.query,items:[],skipped:[],warnings:Sr(t.warnings)}),i===t?e:{...e,graphRetrieval:i}}function Ar(e,t={}){const r=t.limitBytes??Xt,n=t.warningThresholdBytes??Math.floor(r*Zt),o=Pe(e);if(o<r)return{body:e,degraded:!1,telemetry:yt(e,o,["payload-within-limit"],{limitBytes:r,warningThresholdBytes:n})};let i={...e,stateSnapshot:Zr(e.stateSnapshot)},a=["payload-size-guardrail","state-degraded"],c=Pe(i);c>=r&&(i={...i,stateSnapshot:Po(i.stateSnapshot)},a=[...a,"graph-retrieval-budget-enforced"],c=Pe(i));const l=yt(i,c,a,{limitBytes:r,warningThresholdBytes:n});if(c>=r){const p=i.stateSnapshot.scope?.projectionMode;throw p==="yolo-story"||p==="yoloop-target"||p==="yoloop-session"||p==="yoloop-discovery"||p==="structural-required"?new gt(l):new ht(l)}return{body:i,degraded:!0,telemetry:l}}function Rr(e){const t=e.stateSnapshot.scope?.commandId??"resolved-command";return e.args!==void 0?t:`${t}:argsRef`}function Do(e){const t=Pe(e);if(t<dt)return t;const r=yt(e,t,["payload-warning-threshold"]);return process.stderr.write(`[Neocortex] invoke payload near server limit: trigger=${Rr(e)} scope=${r.scope.kind} mode=${r.scope.projectionMode??r.scope.kind} payloadBytes=${r.payloadBytes} limit=${r.limitBytes} includedStories=${r.includedStories} omittedStories=${r.omittedStories} includedEpics=${r.includedEpics} omittedEpics=${r.omittedEpics} graphRetrieval.accepted=${r.graphRetrieval.accepted} graphRetrieval.itemCount=${r.graphRetrieval.itemCount} reasonCodes=${r.reasonCodes.join(",")||"none"}
11
+ `),t}function wr(e,t){process.stderr.write(`[Neocortex] invoke payload guardrail: trigger=${Rr(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"}
12
+ `)}async function jo(e){const t=on(e.args,{platformTarget:e.platformTarget,environment:e.environment??process.env});if(t.action==="skipped")return{shouldContinue:!0,attachToRequest:Mo(t),metadata:vr(t)};const r=e.bootstrapper??an;let n;try{n=await r({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:[sn.UNEXPECTED_ERROR],publicSummary:"runner scheduler bootstrap stopped unexpectedly.",publicSafe:!0}}const o=vr(t,n);if(n.ok)return{shouldContinue:!0,attachToRequest:!0,metadata:o};const i=o.reasonCodes.slice(0,5).join(",");return t.failurePolicy==="fail-open"?{shouldContinue:!0,attachToRequest:!0,metadata:{...o,failOpenWarning:!0},warning:`Runner auto-bootstrap warning (${i}); continuing fail-open for operator command.`}:{shouldContinue:!1,attachToRequest:!1,metadata:o,errorCode:"RUNNER_BOOTSTRAP_REQUIRED_FAILED",error:`Runner auto-bootstrap required but failed (${i}). Run neocortex-runner doctor or retry after resolving scheduler setup.`,exitCode:1}}function Mo(e){return!e.reasonCodes.includes(nn.SKIPPED_NON_CONTINUITY_COMMAND)}function vr(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:ee([...e.reasonCodes,...t?.reasonCodes??[]]),publicSummary:t?.publicSummary??e.publicSummary,publicSafe:!0}}function ee(e){return Array.from(new Set(e.map(t=>t.slice(0,120))))}function tt(e,t,r){const n=Math.floor(e??t);return Number.isFinite(n)?Math.max(1,Math.min(r,n)):t}function rt(e,t){const r=process.env[e];if(!r)return t;const n=Number(r);return Number.isFinite(n)?n:t}function x(e,t=rr){const r=typeof e=="string"&&e.trim().length>0?e.trim():"unknown",n=ie(r,t),o=eo.test(n)?me:n;return o.length<=t?o:`${o.slice(0,t)}\u2026[TRUNCATED:${o.length-t}]`}function It(e,t=rr){if(!(typeof e!="string"||e.trim().length===0))return x(e,t)}function Et(e,t,r,n){const o=It(e?.targetId??t,120),i=e?.selectorKind??(o?Ct(o):void 0),a=(e?.relatedJobIds??[]).map(c=>It(c,120)).filter(c=>!!c);return{schemaVersion:1,contractVersion:"continuity-v1",targetResolutionState:r,...i?{targetKind:i}:{},...o?{targetId:o}:{},...t?{targetJobId:x(t,120)}:{},...e?.jobId?{jobId:x(e.jobId,120)}:{},...e?.goalId?{goalId:x(e.goalId,120)}:{},...e?.loopId?{loopId:x(e.loopId,120)}:{},...a.length>0?{relatedJobIds:a}:{},relatedJobCount:a.length,reasonCodes:ee(n.length>0?n:[O.OK]),publicSafe:!0}}function pe(e,t,r,n,o=[]){const i=(e?.redactions?.length??0)>0,a=e?i?"unsafe":r&&n===0?"empty":"available":"unavailable",c=It(t[t.length-1]?.eventId,120),l=o.length>0?o:a==="unavailable"?[O.WATCH_SNAPSHOT_UNAVAILABLE]:a==="empty"?[O.WATCH_NO_SUMMARIES_YET]:[O.OK];return{schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:a,...e?.generatedAt?{generatedAt:x(e.generatedAt,80)}:{},renderedSummaryCount:n,...c?{latestEventId:c}:{},reasonCodes:ee(l),publicSafe:!0}}function ce(e,t,r,n,o=[],i){const a=n[n.length-1],c=r??a?.cursor,l=!!(c&&c!==t&&n.length>0),p=i??(l?"advanced":t||c?"unchanged":"not_started"),g=o.length>0?o:p==="advanced"?[O.WATCH_CURSOR_ADVANCED]:p==="unavailable"?[O.WATCH_EVIDENCE_UNAVAILABLE]:[O.WATCH_CURSOR_UNCHANGED];return{schemaVersion:1,contractVersion:"continuity-v1",cursorState:p,...e?{initialCursor:x(e,200)}:{},...t?{currentCursor:x(t,200)}:{},...c?{nextCursor:x(c,200)}:{},cursorAdvanced:l,...a?.eventId?{eventId:x(a.eventId,120)}:{},reasonCodes:ee(g),publicSafe:!0}}function de(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:ee([...e.reasonCodes??[],...t?.reasonCodes??[],...e.snapshotEvidence?.reasonCodes??[],...e.cursorEvidence?.reasonCodes??[]]),generatedAt:x(e.generatedAt??new Date().toISOString(),80),publicSafe:!0}}function Uo(e){const t=e.targetKind&&e.targetId?`${e.targetKind}/${e.targetId}`:e.targetId??"[unresolved]",r=e.snapshotEvidence?.renderedSummaryCount??0,n=e.targetEvidence?.relatedJobCount??0,o=e.cursorEvidence?.cursorState??"unavailable",i=e.cursorEvidence?.currentCursor??"[none]",a=e.cursorEvidence?.nextCursor??"[none]",c=e.snapshotEvidence?.snapshotStatus??"not_requested",l=e.snapshotEvidence?.generatedAt??e.generatedAt;return[`[watch-status] ${e.targetResolutionState==="unresolved"||e.stopReason==="target_unresolved"?"unresolved-target":r===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=${r}`,`snapshot=${c}`,`generatedAt=${l}`,`cursor=${o}`,`current=${x(i,200)}`,`next=${x(a,200)}`,`advanced=${e.cursorEvidence?.cursorAdvanced??!1}`,`stop=${e.stopReason??"not_stopped"}`,`reasons=${e.reasonCodes.join(",")}`].join(" ")}function ue(e,t,r,n=!1){if(n){const o={type:"watch_status",watchStatus:e.watchStatus,active:e.active,renderedSummaryCount:e.snapshotEvidence?.renderedSummaryCount??0,stopReason:e.stopReason??"not_stopped",protectedProjection:!0,publicSafe:!0};r.write(t==="json"?`${JSON.stringify(o)}
13
+ `:`[watch-status] status=${o.watchStatus} active=${o.active} summaries=${o.renderedSummaryCount} stop=${o.stopReason}
14
+ `);return}if(t==="json"){r.write(JSON.stringify(e)+`
15
+ `);return}r.write(Uo(e)+`
16
+ `)}function Vo(e,t,r){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:r,statusRecord:e,publicSafe:!0}}}function fe(e,t,r,n,o=!1){return o?{status:e,summariesEmitted:t,polls:r,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:r,protectedProjection:!0,publicSafe:!0}},publicSafe:!0}:{status:e,summariesEmitted:t,polls:r,reasonCodes:n.reasonCodes,watchStatus:n.watchStatus,stopReason:n.stopReason,targetEvidence:n.targetEvidence,snapshotEvidence:n.snapshotEvidence,cursorEvidence:n.cursorEvidence,statusRecord:n,metadata:Vo(n,t,r),publicSafe:!0}}function Bo(e){const t=e.reasonCode?` reason=${x(e.reasonCode,80)}`:"",r=e.goalId?` goal=${x(e.goalId,100)}`:"",n=e.loopId?` loop=${x(e.loopId,100)}`:"";return`[watch] ${x(e.createdAt,80)} event=${x(e.eventId,120)} job=${x(e.jobId,100)}${r}${n} execution=${x(e.executionId,120)}${t} -- ${x(e.publicSummary)}`}function $o(e){return{type:"processing_summary",source:"local_continuity_sqlite",eventId:x(e.eventId,120),jobId:x(e.jobId,100),...e.goalId?{goalId:x(e.goalId,100)}:{},...e.loopId?{loopId:x(e.loopId,100)}:{},executionId:x(e.executionId,120),...e.reasonCode?{reasonCode:x(e.reasonCode,80)}:{},createdAt:x(e.createdAt,80),publicSummary:x(e.publicSummary),publicSafe:!0}}function Ho(e,t,r,n=!1){if(n){r.write(t==="json"?`${JSON.stringify({type:"processing_summary",source:"local_continuity_sqlite",publicSummary:"A local processing update is available.",protectedProjection:!0,publicSafe:!0})}
17
+ `:`[watch] A local processing update is available.
18
+ `);return}if(t==="json"){r.write(JSON.stringify($o(e))+`
19
+ `);return}r.write(Bo(e)+`
20
+ `)}function _t(e){return Zn.has(e.status)}function Wo(e,t,r){if(t){const o=e.find(i=>i.jobId===t);return!!(o&&_t(o))}return r<=0?!1:e.filter(o=>!_t(o)).length===0}function Fo(e,t,r,n){return r<n?!1:t?!e.some(o=>o.jobId===t&&!_t(o)):e.length===0}function Go(e,t){return t?.aborted?Promise.resolve():new Promise(r=>{const n=setTimeout(o,e);function o(){clearTimeout(n),t?.removeEventListener("abort",o),r()}t?.addEventListener("abort",o,{once:!0})})}function Yo(e){return e.includes(K.MALFORMED)?"malformed":e.includes(K.AMBIGUOUS)?"ambiguous":e.includes("watch-target-multiple")?"multiple":e.includes("watch-evidence-unsafe")?"unsafe":e.includes(K.MISSING)||e.includes(Y.TARGET_UNRESOLVED)?"unresolved":"unavailable"}function br(e,t){const r=t?Be(t):void 0,n=ee([...e,Y.TARGET_UNRESOLVED,O.WATCH_TARGET_UNRESOLVED]),o=Et(r,r?.targetId,Yo(n),n),i=pe({generatedAt:new Date().toISOString()},[],!1,0,[O.WATCH_TARGET_UNRESOLVED]),a=ce(void 0,void 0,void 0,[],[O.WATCH_TARGET_UNRESOLVED],"unavailable");return de({watchStatus:"blocked",active:!1,targetEvidence:o,snapshotEvidence:i,cursorEvidence:a,stopReason:"target_unresolved",reasonCodes:n,generatedAt:i.generatedAt})}function Jo(e,t,r,n,o=!1){const i=br(e,Or(t));return ue(i,r,n,o),fe("target-unresolved",0,0,i,o)}async function zo(e){if(e.signal?.aborted){const h=Et(e.target??Be(e.targetJobId),e.targetJobId,e.target??e.targetJobId?"resolved":"unresolved",[Y.CANCELLED]),w=pe(void 0,[],!1,0),E=ce(e.initialCursor,e.initialCursor,e.initialCursor,[],[Y.CANCELLED],"unavailable"),U=de({watchStatus:"stopped",active:!1,targetEvidence:h,snapshotEvidence:w,cursorEvidence:E,stopReason:"cancelled",reasonCodes:[Y.CANCELLED]});return fe("cancelled",0,0,U,e.protectedOutput)}const t=e.target??Be(e.targetJobId),r=e.targetJobId??t?.targetId,n=e.stdout??process.stdout;if(!t){const h=br([K.MISSING,Y.TARGET_UNRESOLVED]);return ue(h,e.format,n,e.protectedOutput),fe("target-unresolved",0,0,h,e.protectedOutput)}const o=tt(e.limit??rt("NEOCORTEX_INVOKE_WATCH_LIMIT",Mt),Mt,50),i=Math.max(50,tt(e.pollIntervalMs??rt("NEOCORTEX_INVOKE_WATCH_POLL_INTERVAL_MS",Bt),Bt,6e4)),a=tt(e.maxIdlePolls??rt("NEOCORTEX_INVOKE_WATCH_MAX_IDLE_POLLS",Ut),Ut,120),c=tt(e.maxPolls??rt("NEOCORTEX_INVOKE_WATCH_MAX_POLLS",Vt),Vt,86400),l=e.sleep??Go;let p=e.initialCursor,g=0,R=0,f=0;const d=Et(t,r,"resolved",[O.OK]),I={schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:"pending",renderedSummaryCount:0,reasonCodes:[O.WATCH_RENDER_PENDING],publicSafe:!0},A=ce(e.initialCursor,p,p,[],e.initialCursor?[O.WATCH_CURSOR_UNCHANGED]:[O.WATCH_NO_SUMMARIES_YET],e.initialCursor?"unchanged":"not_started");ue(de({watchStatus:"active",active:!0,targetEvidence:d,snapshotEvidence:I,cursorEvidence:A,stopReason:"not_stopped",reasonCodes:[O.OK]}),e.format,n,e.protectedOutput);let C;try{C=await cn({projectRoot:e.projectRoot,strictReadOnly:e.strictReadOnly})}catch{const h=pe(void 0,[],!1,g,[O.WATCH_SNAPSHOT_UNAVAILABLE]),w=ce(e.initialCursor,p,p,[],[O.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),E=de({watchStatus:"blocked",active:!1,targetEvidence:d,snapshotEvidence:h,cursorEvidence:w,stopReason:"unavailable_evidence",reasonCodes:[Y.STORE_UNAVAILABLE]});return ue(E,e.format,n,e.protectedOutput),fe("store-unavailable",g,f,E,e.protectedOutput)}try{for(;!e.signal?.aborted&&f<c;){f+=1;const h=p,w=C.collectProcessingOutputSummaryCursor({...p?{cursor:p}:{},...t?{target:t}:{},...r?{jobId:r}:{},limit:o}),E=C.collectSnapshot({jobLimit:50,processingSummaryLimit:1}),U=E.jobs;if(w.summaries.length>0){for(const $ of w.summaries)Ho($,e.format,n,e.protectedOutput),g+=1;p=w.nextCursor??w.summaries[w.summaries.length-1]?.cursor??p,R=0}else p=w.nextCursor??p,R+=1;const k=pe(E,w.summaries,!0,w.summaries.length),N=ce(e.initialCursor,h,p,w.summaries,w.summaries.length>0?[O.WATCH_CURSOR_ADVANCED]:[O.WATCH_NO_SUMMARIES_YET]);if(ue(de({watchStatus:w.summaries.length>0?"polling":"waiting",active:!0,targetEvidence:d,snapshotEvidence:k,cursorEvidence:N,stopReason:"not_stopped",reasonCodes:w.summaries.length>0?[O.WATCH_CURSOR_ADVANCED]:[O.WATCH_NO_SUMMARIES_YET],generatedAt:E.generatedAt}),e.format,n,e.protectedOutput),!w.hasMore&&Wo(U,r,g)){const $=pe(E,w.summaries,!1,g,[Y.COMPLETED]),L=ce(e.initialCursor,h,p,w.summaries,[Y.COMPLETED],"exhausted"),T=de({watchStatus:"stopped",active:!1,targetEvidence:d,snapshotEvidence:$,cursorEvidence:L,stopReason:"not_stopped",reasonCodes:[Y.COMPLETED],generatedAt:E.generatedAt});return ue(T,e.format,n,e.protectedOutput),fe("completed",g,f,T,e.protectedOutput)}if(!w.hasMore&&Fo(U,r,R,a)){const $=pe(E,w.summaries,!1,g,[O.WATCH_STOP_IDLE_LIMIT_REACHED]),L=ce(e.initialCursor,h,p,w.summaries,[O.WATCH_STOP_IDLE_LIMIT_REACHED],"exhausted"),T=de({watchStatus:"stopped",active:!1,targetEvidence:d,snapshotEvidence:$,cursorEvidence:L,stopReason:"idle_limit_reached",reasonCodes:[Y.IDLE_TIMEOUT,O.WATCH_STOP_IDLE_LIMIT_REACHED],generatedAt:E.generatedAt});return ue(T,e.format,n,e.protectedOutput),fe("idle-timeout",g,f,T,e.protectedOutput)}w.hasMore||await l(i,e.signal)}}catch{const h=pe(void 0,[],!1,g,[O.WATCH_SNAPSHOT_UNAVAILABLE]),w=ce(e.initialCursor,p,p,[],[O.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),E=de({watchStatus:"blocked",active:!1,targetEvidence:d,snapshotEvidence:h,cursorEvidence:w,stopReason:"unavailable_evidence",reasonCodes:[Y.STORE_UNAVAILABLE]});return ue(E,e.format,n,e.protectedOutput),fe("store-unavailable",g,f,E,e.protectedOutput)}finally{C.close()}if(e.signal?.aborted){const h=pe(void 0,[],!1,g,[Y.CANCELLED]),w=ce(e.initialCursor,p,p,[],[Y.CANCELLED],"unavailable"),E=de({watchStatus:"stopped",active:!1,targetEvidence:d,snapshotEvidence:h,cursorEvidence:w,stopReason:"cancelled",reasonCodes:[Y.CANCELLED]});return ue(E,e.format,n,e.protectedOutput),fe("cancelled",g,f,E,e.protectedOutput)}const P=pe(void 0,[],!1,g,[O.WATCH_STOP_MAX_POLLS_REACHED]),v=ce(e.initialCursor,p,p,[],[O.WATCH_STOP_MAX_POLLS_REACHED],"exhausted"),j=de({watchStatus:"stopped",active:!1,targetEvidence:d,snapshotEvidence:P,cursorEvidence:v,stopReason:"max_polls_reached",reasonCodes:[Y.MAX_POLLS,O.WATCH_STOP_MAX_POLLS_REACHED]});return ue(j,e.format,n,e.protectedOutput),fe("max-polls",g,f,j,e.protectedOutput)}function se(e){const t=e.trim().replace(/^@/,"").match(/^(job|goal|loop)-([JGL])(\d{3,})$/i);if(!t)return;const r=t[1].toLowerCase(),n=t[2].toUpperCase();if(!(r==="job"&&n!=="J"||r==="goal"&&n!=="G"||r==="loop"&&n!=="L"))return`${r}-${n}${t[3]}`}function Ct(e){if(e.startsWith("job-J"))return"job";if(e.startsWith("goal-G"))return"goal";if(e.startsWith("loop-L"))return"loop"}function Tr(e){const t=[],r=/(?:^|[\s"'([,{])@?(job-[Jj]\d{3,}|goal-[Gg]\d{3,}|loop-[Ll]\d{3,})(?=$|[\s"')\]},.;:!?])/g;let n;for(;(n=r.exec(e))!==null;){const o=se(n[1]);o&&t.push(o)}return ee(t)}function Or(e){return Tr(e)[0]}function Be(e){const t=e?se(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 St(e){return ee(e.filter(t=>typeof t=="string").map(t=>se(t)).filter(t=>!!t?.startsWith("job-J")))}function qo(e,t){const r=St(t).filter(n=>n!==e.targetId&&n!==e.jobId);return r.length>0?{...e,relatedJobIds:r}:e}function Ko(e){if(!e)return;const t=y(e.target)?e.target:void 0,r=typeof e.selectorKind=="string"?e.selectorKind:typeof t?.selectorKind=="string"?t.selectorKind:void 0,n=typeof e.targetId=="string"?se(e.targetId):typeof t?.targetId=="string"?se(t.targetId):typeof e.targetJobId=="string"?se(e.targetJobId):void 0,o=Be(n);if(!o||r&&r!==o.selectorKind)return;const i=Array.isArray(e.relatedJobIds)?e.relatedJobIds:Array.isArray(t?.relatedJobIds)?t.relatedJobIds:void 0,a=St([...i??[],e.jobId,t?.jobId,e.targetJobId,t?.targetJobId]).filter(c=>c!==o.targetId&&c!==o.jobId);return{...o,...typeof(e.jobId??t?.jobId)=="string"?{jobId:se(e.jobId??t?.jobId)??o.jobId}:{},...typeof(e.goalId??t?.goalId)=="string"?{goalId:se(e.goalId??t?.goalId)??o.goalId}:{},...typeof(e.loopId??t?.loopId)=="string"?{loopId:se(e.loopId??t?.loopId)??o.loopId}:{},...a.length>0?{relatedJobIds:a}:{}}}function xr(e){const t=e.trim().split(/\s+/).filter(Boolean),r=t[0]?.replace(/^\*/,"").toLowerCase(),n=t[1]?.replace(/^--/,"").toLowerCase();return(r==="jobs"||r==="job"||r==="continuity-jobs"||r==="61")&&n==="watch"}const q=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"}),Xo=new Set(["create","start","resume"]),Zo=new Set(["create","resume","run-once"]);function At(e,t,r,n,o){return{schemaVersion:1,contractVersion:"continuity-v1",...r?{command:r}:{},...n?{operation:n}:{},active:e,...o?{watchToken:o}:{},reasonCodes:ee(t),serverHeldStream:!1,allJobsPolling:!1,targetResolution:e?"required-after-dispatch":"inactive",publicSafe:!0}}function X(e,t=[],r,n){const o=t.length>0?t:[q.INACTIVE];return{args:e,watch:!1,reasonCodes:o,metadata:At(!1,o,r,n),publicSafe:!0}}function Qo(e){const t=e.trim().split(/\s+/).filter(Boolean),r=t.slice(2).filter(i=>i==="--watch").length;if(r===0)return X(e,[],"jobs","watch");if(r!==1)return X(e,[q.AMBIGUOUS],"jobs","watch");const n=t.filter((i,a)=>a<2||i!=="--watch").join(" ");return xr(n)?n.trim().split(/\s+/).filter(Boolean).slice(2).length!==1?X(e,[q.AMBIGUOUS],"jobs","watch"):Or(n)?{args:n,watch:!0,reasonCodes:[q.ACTIVE],metadata:At(!0,[q.ACTIVE],"jobs","watch"),publicSafe:!0}:X(e,[q.TARGET_INVALID],"jobs","watch"):X(e,[q.UNSUPPORTED],"jobs","watch")}function ei(e){const t=[];let r=!1,n=0;for(;n<e.length;){for(;n<e.length&&/\s/.test(e[n]);)n+=1;if(n>=e.length)break;const o=n;let i="",a=!1,c=null;for(;n<e.length;){const l=e[n];if(c){if(l===c){a=!0,c=null,n+=1;continue}if(l==="\\"&&n+1<e.length){i+=e[n+1],n+=2;continue}i+=l,n+=1;continue}if(/\s/.test(l))break;if(l==='"'||l==="'"){a=!0,c=l,n+=1;continue}i+=l,n+=1}c&&(r=!0),t.push({value:i,start:o,end:n,quoted:a})}return{tokens:t,malformed:r}}function ti(e){if(!e||e.quoted)return;const t=e.value.replace(/^\*/,"").toLowerCase();return t==="goal"||t==="loop"?t:void 0}function ri(e,t){if(!e||e==="jobs"||!t||t.quoted)return;const r=t.value.toLowerCase();return(e==="goal"?Xo:Zo).has(r)?r:void 0}function ni(e){return!e.quoted&&e.value!=="--watch"&&e.value.toLowerCase().startsWith("--watch")}function oi(e){const{tokens:t,malformed:r}=ei(e),n=ti(t[0]),o=ri(n,t[1]);if(r)return X(e,[q.MALFORMED],n,o);const i=t.filter(f=>f.value==="--watch"&&!f.quoted),a=t.filter(f=>f.value==="--watch"&&f.quoted),c=t.filter(ni);if(!(i.length>0||a.length>0||c.length>0))return X(e,[],n,o);if(i.length>1)return X(e,[q.DUPLICATE],n,o);if(i.length===1&&(a.length>0||c.length>0))return X(e,[q.AMBIGUOUS],n,o);if(a.length>0)return X(e,[q.QUOTED],n,o);if(c.length>0)return X(e,[q.MALFORMED],n,o);const p=i[0];if(!p)return X(e,[],n,o);if(t[t.length-1]!==p)return X(e,[q.NON_FINAL],n,o);if(!n||!o)return X(e,[q.UNRESOLVED],n,o);const g=`${e.slice(0,p.start)}${e.slice(p.end)}`.trim(),R={literal:"--watch",position:"final",start:p.start,end:p.end,quoted:!1,publicSafe:!0};return{args:g,watch:!0,reasonCodes:[q.ACTIVE],metadata:At(!0,[q.ACTIVE],n,o,R),publicSafe:!0}}function ii(e){return xr(e)?Qo(e):oi(e)}function si(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&Qn.has(t)):[]}function De(e){return{disabled:!0,reasonCodes:ee(e.length>0?e:[K.MISSING])}}function Rt(e,t,r=[],n){const o=Be(t);if(o)return{source:e,target:qo(o,r),targetJobId:o.targetId,...n?{initialCursor:n}:{},serverHeldStream:!1}}function ai(e){const t=new Map;for(const r of e){const n=`${r.target.selectorKind}:${r.target.targetId}`,o=t.get(n);if(!o){t.set(n,r);continue}const i=ee([...o.target.relatedJobIds??[],...r.target.relatedJobIds??[]]);t.set(n,{...o,target:i.length>0?{...o.target,relatedJobIds:i}:o.target,initialCursor:o.initialCursor??r.initialCursor})}return Array.from(t.values())}function _e(e,t,r,n){return{source:e,hasEvidence:t,candidates:ai(r.filter(o=>!!o)),...n&&n.length>0?{disabledReasonCodes:ee(n)}:{}}}function ci(e,t){return e.target.selectorKind===t.target.selectorKind&&e.target.targetId===t.target.targetId}function $e(e,t){const r=ee(e.filter(n=>typeof n=="string").map(n=>se(n)).filter(n=>!!n));if(t){const n=r.find(o=>Ct(o)===t);if(n)return n}return r[0]}function nt(e,t){return ee(e.filter(r=>typeof r=="string").map(r=>se(r)).filter(r=>!!r)).find(r=>Ct(r)===t)}function di(e){const t=y(e?.continuity)?e.continuity:void 0,r=y(t?.jobs)?t.jobs:void 0,n=y(r?.watcher)?r.watcher:void 0,o=si(n?.reasonCodes??r?.reasonCodes);if(!n)return _e("watcher-metadata",o.length>0,[],o);if(n.active===!1||o.length>0)return _e("watcher-metadata",!0,[],o.length>0?o:[K.MALFORMED]);if(n.serverHeldStream!==!1)return _e("watcher-metadata",!0,[],[K.SERVER_HELD_STREAM]);const i=Ko(n);if(!i)return _e("watcher-metadata",!0,[],[K.MISSING]);const a=typeof n.initialCursor=="string"?n.initialCursor:void 0;return _e("watcher-metadata",!0,[{source:"watcher-metadata",target:i,targetJobId:i.targetId,...a?{initialCursor:a}:{},serverHeldStream:!1}])}function kr(e,t){const r=y(e.loopJobPlan)?e.loopJobPlan:void 0,n=y(r?.metadata)?r.metadata:void 0,o=y(e.metadata)?e.metadata:void 0,a=(t==="goal"?$e([e.goalId,e.targetGoalId,e.campaignId,e.jobId,e.targetJobId,o?.goalId,o?.campaignId,o?.jobId],"goal"):$e([e.loopId,e.targetLoopId,e.jobId,e.targetJobId,o?.loopId,o?.jobId,n?.loopId,n?.jobId],"loop"))??$e([e.jobId,e.targetJobId,o?.jobId,n?.jobId]);return Rt("goal-loop-continuity-metadata",a,[e.jobId,e.targetJobId,o?.jobId,n?.jobId])}function ui(e){const t=y(e?.continuity)?e.continuity:void 0,r=y(t?.goal)?t.goal:void 0,n=y(t?.loop)?t.loop:void 0,o=[r?kr(r,"goal"):void 0,n?kr(n,"loop"):void 0],i=!!(r||n);return _e("goal-loop-continuity-metadata",i,o,i&&o.every(a=>!a)?[K.MISSING]:void 0)}function li(e){return Array.isArray(e)?e.filter(y):y(e)?Array.isArray(e.operationLogs)?e.operationLogs.filter(y):y(e.operationLog)?[e.operationLog]:Array.isArray(e.operations)?[e]:[]:[]}function Nr(e,t){const r=y(t.metadata)?t.metadata:void 0,n=nt([t.goalId,t.targetGoalId,t.campaignId,r?.goalId,r?.campaignId,t.jobId,r?.jobId],"goal"),o=nt([t.loopId,t.targetLoopId,r?.loopId,t.jobId,r?.jobId],"loop"),i=$e([t.jobId,t.targetJobId,r?.jobId],"job"),a=n??o??i;if(!a)return;const c=e.get(a)??{targetId:a,relatedJobIds:[]};c.relatedJobIds.push(...St([i,t.jobId,t.targetJobId,r?.jobId])),e.set(a,c)}function pi(e){const t=y(e.metadata)?e.metadata:void 0;return!!(nt([e.goalId,e.targetGoalId,e.campaignId,t?.goalId,t?.campaignId,e.jobId,t?.jobId],"goal")??nt([e.loopId,e.targetLoopId,t?.loopId,e.jobId,t?.jobId],"loop"))}function fi(e){const t=y(e.metadata)?e.metadata:void 0;return!!$e([e.goalId,e.targetGoalId,e.campaignId,e.loopId,e.targetLoopId,e.jobId,e.targetJobId,t?.goalId,t?.campaignId,t?.loopId,t?.jobId])}function Lr(e,t){const r=[];for(const a of["metadata","job","event","receipt","processingOutputSummary"]){const c=t[a];y(c)&&r.push(c)}const n=y(t.event)?t.event:void 0;y(n?.metadata)&&r.push(n.metadata),y(n?.processingOutputSummary)&&r.push(n.processingOutputSummary);const o=y(t.receipt)?t.receipt:void 0;y(o?.metadata)&&r.push(o.metadata);const i=r.some(fi);for(const a of r)Nr(e,a);(!i||pi(t))&&Nr(e,t)}function hi(e){const t=li(e?.continuityStateUpdate),r=new Map;for(const o of t){Lr(r,o);const i=Array.isArray(o.operations)?o.operations.filter(y):[];for(const a of i)Lr(r,a)}const n=Array.from(r.values()).map(o=>Rt("continuity-state-update-operation-log",o.targetId,o.relatedJobIds));return _e("continuity-state-update-operation-log",t.length>0,n,t.length>0&&n.every(o=>!o)?[K.MISSING]:void 0)}function gi(e){const t=Tr(e);return _e("explicit-args",t.length>0,t.map(r=>Rt("explicit-args",r)))}function mi(e,t){const r=[di(e),ui(e),hi(e),gi(t)];for(let n=0;n<r.length;n+=1){const o=r[n];if(!o.hasEvidence)continue;if(o.disabledReasonCodes&&o.disabledReasonCodes.length>0)return De(o.disabledReasonCodes);if(o.candidates.length!==1)return De([o.candidates.length>1?K.AMBIGUOUS:K.MISSING]);const i=o.candidates[0];for(const a of r.slice(n+1)){if(!a.hasEvidence)continue;if(a.disabledReasonCodes&&a.disabledReasonCodes.length>0)return De(a.disabledReasonCodes);if(a.candidates.length>1)return De([K.AMBIGUOUS]);const c=a.candidates[0];if(c&&!ci(i,c))return De([K.CONFLICT])}return{target:i.target,targetJobId:i.targetJobId,...i.initialCursor?{initialCursor:i.initialCursor}:{},source:i.source,serverHeldStream:!1}}return De([K.MISSING])}async function Pr(e,t,r,n={}){const i=await Ve(e,"/api/v1/invoke",t,r,t.privateExecution?{...n,maxAttempts:1,allowReplayRetry:!1}:n);if(i.networkFailure||!i.response)return{ok:!1,status:0,error:"Network error after bounded retries"};const{response:a,text:c,parsed:l}=i;try{if(!a.ok)return t.privateExecution?{ok:!1,status:a.status,error:"private-execution-invoke-unavailable"}:{ok:!1,status:a.status,error:Object.keys(l).length>0?`${l.error_code??"ERROR"}: ${l.message??c}`:`HTTP ${a.status}: ${c}`,errorBody:Object.keys(l).length>0?l:void 0};const p=l,g=a.headers.get("X-Client-Version-Warning");return g&&!Ir&&(Ir=!0,process.stderr.write(`
17
21
  [Neocortex] ${g}
18
22
 
19
- `)),{ok:!0,status:s.status,data:p}}catch(p){return{ok:!1,status:0,error:(p instanceof Error?p.message:String(p)).includes("abort")?`Request timeout after ${Ht/1e3}s`:"Network error: invalid response"}}}async function ii(e,t,n,r={}){const o=await ct(e,"/api/v1/invoke/epic-claims/acknowledge",{...n,registryVersion:Ie,registryChecksum:me},t,r);return!!o.response?.ok&&o.parsed.status==="ok"&&o.parsed.claimOutcome===n.status}async function si(e,t,n,r,o,i={}){if(!o)return 0;const s=Ve(e);let c=0;for(const[l,p]of Object.entries(s.operations))!p.claimId||!p.epicId||!t.epics?.[p.epicId]||!await ii(n,r,{claimId:p.claimId,projectId:o,epicId:p.epicId,status:"materialized"},i)||(jr(e,l),c+=1);return c}function ai(e,t){const n=t.state.pendingContinuationAuthorities,r=t.state.continuationSession;if(t.state.continuationPolicy!=="p205-finite-resume-v2"||n?.length!==1||!r)return;const o=n[0],i=o.certificate,s=i?.expectedTransition;if(o.storyIds!=="[CIRCULAR]"||i?.rank!=="[CIRCULAR]"||s?.selectedStoryIds!=="[CIRCULAR]")return;const c=typeof r.epicId=="string"?r.epicId:"",l=e.epics[c],p=Array.isArray(s.storyLifecycle)?s.storyLifecycle:[],g=p.length===1&&typeof p[0]?.storyId=="string"?p[0].storyId:"",f=e.stories[g]?.checkpoint;if(!l||l.branch_mode!=="epic"||typeof l.execution_branch!="string"||typeof l.origin_branch!="string"||l.branch_lease!==void 0&&l.branch_lease!==null||!f||f.qaVerdict!=="passed"||f.reviewVerdict!=="approved"||!Array.isArray(f.receiptRefs))return;const h=(Array.isArray(l.stories)?l.stories.filter(S=>typeof S=="string"):[]).find(S=>{const E=e.stories[S];return!E||["done","completed","merged"].includes(String(E.status))?!1:(Array.isArray(E.depends_on)?E.depends_on.filter(k=>typeof k=="string"):[]).every(k=>["done","completed","merged"].includes(String(e.stories[k]?.status)))});if(h)return{epicId:c,expectedNextStoryId:h,branchMode:"epic",executionBranch:l.execution_branch,originBranch:l.origin_branch,branchLeaseReleased:!0,checkpoint:{schemaVersion:1,storyId:f.storyId,epicId:f.epicId,branch:f.branch,baseSha:f.baseSha,headSha:f.headSha,receiptRefs:[...f.receiptRefs],qaVerdict:"passed",reviewVerdict:"approved"}}}async function ci(e){let t;try{if(t=e.inputEnvelope??je(e.inputSource??"args",e.args),dr(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 n=t.rawArgs,r=Mt(t);let o=n,i=r;const s=Vr(n);if(s.outcome!=="resolved"){const a=lr(s,"client"),u=s.outcome==="malformed_input"?s.reason==="input_limit"||s.reason==="token_limit"||s.reason==="token_size_limit"?"input-limit-exceeded":s.reason==="invalid_control"||s.reason==="invalid_surrogate"?"invalid-control-character":s.reason==="unterminated_quote"||s.reason==="trailing_escape"||s.reason==="unsupported_escape"?"unterminated-quote":void 0:void 0,y=u?{code:"INVOCATION_MALFORMED_INPUT",reason:u,source:t.source,byteLength:t.byteLength,remediation:u==="input-limit-exceeded"?"Reduce the explicit command input or split the requested work into bounded invocations.":u==="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_${s.outcome.toUpperCase()}`,errorCode:`INVOCATION_${s.outcome.toUpperCase()}`,metadata:{invocationAdmission:a,...y?{invocationInput:y}:{}},exitCode:1}}const c=nt(e.projectRoot),l=s.selection.commandId,p=Mn.find(a=>a.id===l),g=p?.subcommands.find(a=>a.id===s.selection.operationId),C=g?g.policy.strictReadOnly==="allow":p?.policy.strictReadOnly==="allow",f=l==="diagnose";let d;try{d=sr({invocationId:qe(),intent:e.strictReadOnly||f?{schemaVersion:1,policy:rr,registryVersion:Ie,registryChecksum:me}:void 0,registryVersion:Ie,registryChecksum:me,registryAllowsStrict:C,requestCanonicalBytes:JSON.stringify({command:l})})}catch(a){if(a instanceof Re)return{success:!1,error:a.code,errorCode:a.code,exitCode:1};throw a}{d.beginProjection();for(const a of jt)d.project(a);for(const a of or)d.project(a);d.seal()}const h=d.mode==="strict";if(l==="create-epic")try{const a=Ir(c);if(a&&a!=="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:a,publicSafe:!0}},exitCode:1}}catch(a){const u=a instanceof Xe?a.code:"PROJECT_IDENTITY_MIGRATION_STATE_CORRUPT";return{success:!1,error:u,errorCode:u,exitCode:1}}const S=e.environment??process.env,E=er({cwd:c,env:S,targetFlag:e.platformTarget}),T=E.targetId,k=Qn({cwd:c,env:S,targetFlag:e.platformTarget,nativeHostVersion:Jr(E,S)},E);l!=="migrate-project-id"&&d.execute({phase:"client-preflight",domain:"client-persistence",category:"first-run-marker",operation:"create"},()=>Ur(),()=>{});const w=uo(d),_=(e.serverUrl??w?.serverUrl??Un).replace(/\/+$/,"");if(l==="migrate-project-id"){const a=await yr(_);if(!a.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:a},exitCode:1};const u=[];let y;try{y=mr(c)}catch(B){const ce=B instanceof Xe?B.code:"PROJECT_IDENTITY_MIGRATION_PREPARE_FAILED";return{success:!1,error:ce,errorCode:ce,exitCode:1}}u.push(we({phase:"prepare",outcome:y.changed&&y.document.phase==="prepared"?"prepared":"retry",floor:y.document.legacyEpicFloor,licenseId:"local-client",projectId:y.document.projectId}));const P=dn(c);if(P.config.project_id!==y.document.projectId)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",errorCode:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",metadata:{invocationDiagnostics:u},exitCode:1};const he=await ln(_,w?.licenseKey,d);if(he.status!=="authenticated"){const B=he.status==="refresh-required";return{success:!1,error:B?"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:B?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",metadata:{invocationDiagnostics:u},exitCode:B?1:2}}let _t;try{_t=vt(e.args.trim(),P)}catch(B){const ce=B instanceof Ot?B.code:"PROJECT_IDENTITY_MIGRATION_PROJECTION_FAILED";return{success:!1,error:ce,errorCode:ce,metadata:{invocationDiagnostics:u},exitCode:1}}let ze={args:n,projectRoot:c.replace(Pe(),"~"),stateSnapshot:_t,platformTarget:T,...k?{nativeHostAttestation:k}:{},projectId:y.document.projectId,projectIdentityMigration:y.request,inputEvidence:r,idempotencyKey:y.document.operationId,registryVersion:Ie,registryChecksum:me};try{ze=In(ze).body}catch(B){if(B instanceof it||B instanceof st)return{success:!1,error:B.message,errorCode:B.code,metadata:{invokePayload:B.telemetry,invocationDiagnostics:u},exitCode:1};throw B}const ie=await Pt("invoke-query",()=>vn(_,ze,he.token,{refreshToken:()=>he.client.forceRefresh()}));if(!ie.ok||!ie.data)return u.push(we({phase:"seed",outcome:"rejected",floor:y.document.legacyEpicFloor,licenseId:"local-client",projectId:y.document.projectId})),{success:!1,error:Z(ie.error??"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",ye),errorCode:typeof ie.errorBody?.error_code=="string"?ie.errorBody.error_code:"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",metadata:{invocationDiagnostics:u},exitCode:ie.status===401?2:1};const X=ie.data.metadata?.projectIdentityMigration;try{ur(X),u.push(we({phase:"seed",outcome:X.status,floor:X.acceptedLegacyFloor,licenseId:"local-client",projectId:X.projectId})),gr(c,X),u.push(we({phase:"remote-acknowledged",outcome:X.status,floor:X.acceptedLegacyFloor,licenseId:"local-client",projectId:X.projectId})),hr(c,X),u.push(we({phase:"finalize",outcome:"finalized",floor:X.acceptedLegacyFloor,licenseId:"local-client",projectId:X.projectId}))}catch(B){u.push(we({phase:"reconcile",outcome:"rejected",floor:y.document.legacyEpicFloor,licenseId:"local-client",projectId:y.document.projectId}));const ce=B instanceof Xe?B.code:B instanceof Error?B.message:"PROJECT_IDENTITY_MIGRATION_RECEIPT_INVALID";return{success:!1,error:ce,errorCode:ce,metadata:{invocationDiagnostics:u},exitCode:1}}return d.complete(),{success:!0,instructions:ie.data.instructions,metadata:{...ie.data.metadata,invocationDiagnostics:u},exitCode:0}}try{const{normalizeYoloopTargetArgs:a}=await import("../yoloop/target-normalization.js"),u=a(e.args,{projectRoot:c});if(!u.ok)return process.stderr.write(`${u.message} reason=${u.reasonCode}
23
+ `)),{ok:!0,status:a.status,data:p}}catch(p){return{ok:!1,status:0,error:(p instanceof Error?p.message:String(p)).includes("abort")?`Request timeout after ${qt/1e3}s`:"Network error: invalid response"}}}async function yi(e,t,r){const n=await Ve(e,"/api/v1/invoke/private-execution/consume",t,r,{maxAttempts:1,allowReplayRetry:!1});if(n.networkFailure||!n.response||!n.response.ok)throw new Error("private-execution-delivery-unavailable");return n.parsed}async function ps(e,t,r){const n=await Ve(e,"/api/v1/invoke/private-execution/cancel",t,r,{maxAttempts:1,allowReplayRetry:!1});return!!n.response?.ok&&n.parsed.status==="cancelled"}async function Ii(e,t,r,n={}){const o=await Ve(e,"/api/v1/invoke/epic-claims/acknowledge",{...r,registryVersion:we,registryChecksum:Re},t,n);return!!o.response?.ok&&o.parsed.status==="ok"&&o.parsed.claimOutcome===r.status}async function Ei(e,t,r,n,o,i={}){if(!o)return 0;const a=qe(e);let c=0;for(const[l,p]of Object.entries(a.operations))!p.claimId||!p.epicId||!t.epics?.[p.epicId]||!await Ii(r,n,{claimId:p.claimId,projectId:o,epicId:p.epicId,status:"materialized"},i)||(zn(e,l),c+=1);return c}function _i(e,t){const r=t.state.pendingContinuationAuthorities,n=t.state.continuationSession;if(t.state.continuationPolicy!=="p205-finite-resume-v2"||r?.length!==1||!n)return;const o=r[0],i=o.certificate,a=i?.expectedTransition;if(o.storyIds!=="[CIRCULAR]"||i?.rank!=="[CIRCULAR]"||a?.selectedStoryIds!=="[CIRCULAR]")return;const c=typeof n.epicId=="string"?n.epicId:"",l=e.epics[c],p=Array.isArray(a.storyLifecycle)?a.storyLifecycle:[],g=p.length===1&&typeof p[0]?.storyId=="string"?p[0].storyId:"",f=e.stories[g]?.checkpoint;if(!l||l.branch_mode!=="epic"||typeof l.execution_branch!="string"||typeof l.origin_branch!="string"||l.branch_lease!==void 0&&l.branch_lease!==null||!f||f.qaVerdict!=="passed"||f.reviewVerdict!=="approved"||!Array.isArray(f.receiptRefs))return;const I=(Array.isArray(l.stories)?l.stories.filter(A=>typeof A=="string"):[]).find(A=>{const C=e.stories[A];return!C||["done","completed","merged"].includes(String(C.status))?!1:(Array.isArray(C.depends_on)?C.depends_on.filter(v=>typeof v=="string"):[]).every(v=>["done","completed","merged"].includes(String(e.stories[v]?.status)))});if(I)return{epicId:c,expectedNextStoryId:I,branchMode:"epic",executionBranch:l.execution_branch,originBranch:l.origin_branch,branchLeaseReleased:!0,checkpoint:{schemaVersion:1,storyId:f.storyId,epicId:f.epicId,branch:f.branch,baseSha:f.baseSha,headSha:f.headSha,receiptRefs:[...f.receiptRefs],qaVerdict:"passed",reviewVerdict:"approved"}}}async function Ci(e){let t;try{if(t=e.inputEnvelope??Ge(e.inputSource??"args",e.args),Cn(t),t.rawArgs!==e.args)throw new Error("INVOKE_INPUT_ENVELOPE_ARGUMENT_CONFLICT")}catch{return{success:!1,error:"INVOCATION_MALFORMED_INPUT: explicit input integrity could not be verified.",errorCode:"INVOCATION_MALFORMED_INPUT",metadata:{invocationInput:{reason:"input-integrity-conflict",remediation:"Retry with exactly one of --args, --stdin or --args-file.",publicSafe:!0}},exitCode:1}}const r=t.rawArgs,n=Ft(t);let o=r,i=n;const a=Xn(r);if(a.outcome!=="resolved"){const s=An(a,"client"),u=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,m=u?{code:"INVOCATION_MALFORMED_INPUT",reason:u,source:t.source,byteLength:t.byteLength,remediation:u==="input-limit-exceeded"?"Reduce the explicit command input or split the requested work into bounded invocations.":u==="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:s,...m?{invocationInput:m}:{}},exitCode:1}}const c=lt(e.projectRoot),l=a.selection.commandId,p=zr.find(s=>s.id===l),g=p?.subcommands.find(s=>s.id===a.selection.operationId),R=g?g.policy.strictReadOnly==="allow":p?.policy.strictReadOnly==="allow",f=l==="diagnose";let d;try{d=In({invocationId:it(),intent:e.strictReadOnly||f?{schemaVersion:1,policy:gn,registryVersion:we,registryChecksum:Re}:void 0,registryVersion:we,registryChecksum:Re,registryAllowsStrict:R,requestCanonicalBytes:JSON.stringify({command:l})})}catch(s){if(s instanceof Ne)return{success:!1,error:s.code,errorCode:s.code,exitCode:1};throw s}{d.beginProjection();for(const s of Wt)d.project(s);for(const s of mn)d.project(s);d.seal()}const I=d.mode==="strict";if(l==="create-epic")try{const s=On(c);if(s&&s!=="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:s,publicSafe:!0}},exitCode:1}}catch(s){const u=s instanceof at?s.code:"PROJECT_IDENTITY_MIGRATION_STATE_CORRUPT";return{success:!1,error:u,errorCode:u,exitCode:1}}const A=e.environment??process.env;if(e.privateExecutionBeta&&(l!=="yolo"&&l!=="research"&&l!=="exec"||I||e.platformTarget!==void 0&&e.platformTarget!=="codex"))return{success:!1,error:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",errorCode:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",exitCode:1};const C=pn({cwd:c,env:A,targetFlag:e.privateExecutionBeta?"codex":e.platformTarget}),P=C.targetId,v=e.privateExecutionBeta?void 0:ln({cwd:c,env:A,targetFlag:e.platformTarget,nativeHostVersion:io(C,A)},C);l!=="migrate-project-id"&&d.execute({phase:"client-preflight",domain:"client-persistence",category:"first-run-marker",operation:"create"},()=>Kn(),()=>{});const j=So(d),h=(e.serverUrl??j?.serverUrl??qr).replace(/\/+$/,"");if(l==="migrate-project-id"){const s=await xn(h);if(!s.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:s},exitCode:1};const u=[];let m;try{m=Tn(c)}catch(M){const V=M instanceof at?M.code:"PROJECT_IDENTITY_MIGRATION_PREPARE_FAILED";return{success:!1,error:V,errorCode:V,exitCode:1}}u.push(Le({phase:"prepare",outcome:m.changed&&m.document.phase==="prepared"?"prepared":"retry",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId}));const b=gr(c);if(b.config.project_id!==m.document.projectId)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",errorCode:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",metadata:{invocationDiagnostics:u},exitCode:1};const G=await yr(h,j?.licenseKey,d);if(G.status!=="authenticated"){const M=G.status==="refresh-required";return{success:!1,error:M?"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:M?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",metadata:{invocationDiagnostics:u},exitCode:M?1:2}}let W;try{W=Dt(e.args.trim(),b)}catch(M){const V=M instanceof jt?M.code:"PROJECT_IDENTITY_MIGRATION_PROJECTION_FAILED";return{success:!1,error:V,errorCode:V,metadata:{invocationDiagnostics:u},exitCode:1}}let le={args:r,projectRoot:c.replace(Fe(),"~"),stateSnapshot:W,platformTarget:P,...v?{nativeHostAttestation:v}:{},projectId:m.document.projectId,projectIdentityMigration:m.request,inputEvidence:n,idempotencyKey:m.document.operationId,registryVersion:we,registryChecksum:Re};try{le=Ar(le).body}catch(M){if(M instanceof ht||M instanceof gt)return{success:!1,error:M.message,errorCode:M.code,metadata:{invokePayload:M.telemetry,invocationDiagnostics:u},exitCode:1};throw M}const Z=await Ht("invoke-query",()=>Pr(h,le,G.token,{refreshToken:()=>G.client.forceRefresh()}));if(!Z.ok||!Z.data)return u.push(Le({phase:"seed",outcome:"rejected",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId})),{success:!1,error:ie(Z.error??"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",ve),errorCode:typeof Z.errorBody?.error_code=="string"?Z.errorBody.error_code:"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",metadata:{invocationDiagnostics:u},exitCode:Z.status===401?2:1};const Q=Z.data.metadata?.projectIdentityMigration;try{Sn(Q),u.push(Le({phase:"seed",outcome:Q.status,floor:Q.acceptedLegacyFloor,licenseId:"local-client",projectId:Q.projectId})),vn(c,Q),u.push(Le({phase:"remote-acknowledged",outcome:Q.status,floor:Q.acceptedLegacyFloor,licenseId:"local-client",projectId:Q.projectId})),bn(c,Q),u.push(Le({phase:"finalize",outcome:"finalized",floor:Q.acceptedLegacyFloor,licenseId:"local-client",projectId:Q.projectId}))}catch(M){u.push(Le({phase:"reconcile",outcome:"rejected",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId}));const V=M instanceof at?M.code:M instanceof Error?M.message:"PROJECT_IDENTITY_MIGRATION_RECEIPT_INVALID";return{success:!1,error:V,errorCode:V,metadata:{invocationDiagnostics:u},exitCode:1}}return d.complete(),{success:!0,instructions:Z.data.instructions,metadata:{...Z.data.metadata,invocationDiagnostics:u},exitCode:0}}try{const{normalizeYoloopTargetArgs:s}=await import("../yoloop/target-normalization.js"),u=s(e.args,{projectRoot:c});if(!u.ok)return process.stderr.write(`${u.message} reason=${u.reasonCode}
20
24
  `),{success:!1,error:u.message,exitCode:1};u.changed&&(e={...e,args:u.args},process.stderr.write(`[Neocortex] yoloop target normalized: ${u.reasonCodes.join(",")}
21
- `))}catch{const a="INVALID_YOLOOP_TARGET: yoloop target normalization was unavailable; no request was sent.";return process.stderr.write(`${a}
22
- `),{success:!1,error:a,exitCode:1}}const R=an(l);if(R)try{cn(c,{allowMissingRuntime:!0}).runtimeMissing&&(await d.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},async()=>Cr(c),async()=>{}),cn(c))}catch(a){const u=a instanceof pe?a.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${u}. No request was sent; repair the canonical project state and retry.
23
- `),{success:!1,error:u,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}try{d.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>Fn(c,{args:e.args,canonicalCommandId:l}),()=>{})}catch(a){if(a instanceof Gn)return process.stderr.write(`${a.message}
24
- `),{success:!1,error:a.message,exitCode:1};const u=a instanceof Error?a.message:String(a);return process.stderr.write(`[Neocortex] state.json repair stopped unexpectedly: ${u}. No request was sent; inspect .neocortex/state.json and rerun.
25
- `),{success:!1,error:u,exitCode:1}}let I;try{const a=await io(c,e.args,l);I=dn(c,{epicAware:R,p205Authorities:a})}catch(a){const u=a instanceof pe?a.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${u}. No request was sent; repair the canonical project state/runtime sidecar and retry.
26
- `),{success:!1,error:u,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}try{const{maybeAutoResolveYoloopArgs:a}=await import("../yoloop/invoke-hooks.js"),u={args:e.args,projectRoot:c,logger:{info:y=>process.stderr.write(`${y}
27
- `),warn:y=>process.stderr.write(`${y}
28
- `)}};a(u),u.args!==e.args&&(e={...e,args:u.args},o=u.args,i=Mt(je(t.source,o)))}catch(a){const u=a instanceof Error?a.message:String(a);process.stderr.write(`[Neocortex] Auto-resolve hook (P121.05) failed: ${u}. Proceeding with raw args.
29
- `)}try{const{readYoloopForRequest:a}=await import("../yoloop/invoke-hooks.js"),u=await a(e.args,c);if(u){const y=ai(I,u);I.yoloop=y?{...u,continuationRecoveryEvidence:y}:u}}catch(a){if(/^\s*\*?(?:yoloop|auto-yolo|epic-runner|story-runner|loop-yolo|auto-epic)\b/i.test(e.args)){const y=a instanceof Error?a.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 and no state was mutated.
30
- `),{success:!1,error:y,errorCode:y,exitCode:1}}}try{const{readContinuityForRequest:a}=await import("../continuity/invoke-hooks.js"),u=await a(e.args,c,void 0,d,{includeExistingStore:!f});u&&(I.continuity=u)}catch(a){if(a instanceof Re)return{success:!1,error:a.code,errorCode:a.code,exitCode:1};const u=a instanceof Error?a.message:String(a);process.stderr.write(`[Neocortex] continuity snapshot hook failed: ${u}. Proceeding without continuity state.
31
- `)}try{const{maybeRunDiscoveryHook:a}=await import("../yoloop/invoke-hooks.js");await a({args:e.args,projectRoot:c,stateSnapshot:I,featureFlag:process.env.YOLOOP_AUTO_DISCOVERY!=="off",logger:{warn:u=>{console.warn(u)},info:u=>{console.error(u)}}})}catch(a){const u=a instanceof Error?a.message:String(a);process.stderr.write(`[Neocortex] discovery hook failed: ${u}. Proceeding without enrichment.
32
- `)}try{const{readArchitecturePolicy:a}=await import("../policy/architecture-policy.js"),u=await a(c);u&&(I.architecture_policy=u)}catch(a){const u=a instanceof Error?a.message:String(a);console.warn(`[Neocortex] architecture-policy hook failed: ${u}. Proceeding without policy.`)}try{const a=/^(1|true|on|yes)$/i.test(process.env.NEOCORTEX_GRAPH_RETRIEVAL??""),{maybeRunGraphRetrievalHook:u}=await import("../yoloop/invoke-hooks.js"),y=await u({args:e.args,projectRoot:c,featureFlag:a,logger:{warn:P=>process.stderr.write(`${P}
33
- `)}});y.applied&&y.metadata&&(I.graphRetrieval=y.metadata)}catch(a){const u=a instanceof Error?a.message:String(a);process.stderr.write(`[Neocortex] graph retrieval hook failed: ${u}. Proceeding without enrichment.
34
- `)}try{if(Fr(e.args)){const{collectProjectEvidence:a}=await import("../evidence/collector.js"),u=s.selection.uiUxReview?.architectureDir,y=a({projectRoot:c,...u?{candidatePaths:[u],includeFallbackInventory:!0}:{}});(y.evidence.length>0||y.exclusions.length>0)&&(I.projectEvidence=y)}}catch(a){const u=a instanceof Error?a.message:String(a);process.stderr.write(`[Neocortex] project evidence collection failed: ${u}. Proceeding without local project evidence.
35
- `)}try{const a=await d.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"checkpoint-consume",operation:"consume"},async()=>{const{readAndConsumeCheckpoint:u}=await import("../checkpoint/index.js");return u(c)},async()=>{});a&&(I.implementCheckpoint=a)}catch(a){const u=a instanceof Error?a.message:String(a);process.stderr.write(`[Neocortex] checkpoint hook failed: ${u}. Proceeding without checkpoint.
36
- `)}const M=w?.licenseKey?new Ke({cacheDir:Qe,passphrase:w.licenseKey,strictReadOnly:h}):null,L=o.trim();if(!L&&M){const a=await d.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>so(M),async()=>null);if(a)return d.complete(),{success:!0,instructions:a.instructions,metadata:a.metadata,exitCode:0}}const D=await ln(_,w?.licenseKey,d);if(D.status!=="authenticated"){const a=D.status==="refresh-required",u=!a&&w&&!w.licenseKey?" This may be caused by a machine fingerprint change (e.g., hardware or hostname change).":"";try{const y=bt(),P=wt(a?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",y);P&&process.stderr.write(Tt(P,y))}catch{}return{success:!1,error:a?"Authentication refresh required. Run: neocortex activate YOUR-LICENSE-KEY":`Not authenticated.${u} Visit https://neocortex.sh/portal/login to get your license key, then run: neocortex activate YOUR-LICENSE-KEY`,errorCode:a?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",exitCode:a?1:2}}const V=I.config.project_id;try{await d.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>si(c,I,_,D.token,V,{refreshToken:()=>D.client.forceRefresh()}),async()=>0)}catch{}const x=di(L);if(x&&!f)try{const a=await D.tierClient.preFlightCheck(x);if(!a.allowed)return process.stderr.write(`[neocortex] ${a.message}
37
- `),{success:!1,error:a.message??"Trigger not available on your plan",exitCode:1}}catch{}const v=await Ro({args:L,projectRoot:c,platformTarget:T,environment:e.environment??process.env,bootstrapper:e.runnerBootstrapper,effectAuthority:d});if(v.attachToRequest&&(I.runnerBootstrap=v.metadata),v.warning&&process.stderr.write(`[Neocortex] ${v.warning}
38
- `),!v.shouldContinue)return v.error&&process.stderr.write(`[Neocortex] ${v.error}
39
- `),{success:!1,error:v.error??"Runner auto-bootstrap required but failed.",errorCode:v.errorCode,exitCode:v.exitCode??1};let ee;try{const a=Hn(L,I);if(a&&!a.ok){const u=`${a.code}: structural projection failed closed; select a valid target or repair the dependency DAG.`;return process.stderr.write(`${u}
40
- `),{success:!1,error:u,errorCode:a.code,metadata:{stateProjection:a,publicSafe:!0},exitCode:1}}ee=a?.snapshot??vt(L,I)}catch(a){if(a instanceof Ot){const u=`${a.code}: structural projection failed closed; select a valid target or repair the dependency DAG.`;return process.stderr.write(`${u}
41
- `),{success:!1,error:u,errorCode:a.code,metadata:{structuralProjection:{...a.publicDetails,publicSafe:!0}},exitCode:1}}throw a}if(!h)try{const{openNativeAgentPrivateStore:a,resolveNativeAgentPrivateRuntimePaths:u}=await import("../continuity/native-agent-store.js"),y=u(c);if(Ce(y.databasePath)){const P=await a(c);try{const he=P.store.listRecentNativeAgentDispatches(20);he.length>0&&(ee.nativeAgentDispatches=he)}finally{P.store.close()}}}catch{}const Oe=St(L),_e=V;if(Oe==="create-epic"&&!_e){const a='EPIC_PROJECT_ID_REQUIRED: run `neocortex-client invoke --args "*migrate-project-id"` and retry create-epic. No repository checkout or database credentials are required.';return process.stderr.write(`${a}
42
- `),{success:!1,error:a,errorCode:"EPIC_PROJECT_ID_REQUIRED",exitCode:1}}let Ee;try{Ee=d.execute({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Oe==="create-epic"?Pr(c,L):void 0,()=>{})}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const De=Ee?.key,ge=h?{schemaVersion:1,invocationId:d.invocationId,intent:d.intent,clientProjection:ir(jt.map(a=>({...a,count:1})))}:void 0;let K={args:o,projectRoot:c.replace(Pe(),"~"),stateSnapshot:ee,platformTarget:T,...k?{nativeHostAttestation:k}:{},projectId:_e,inputEvidence:i,idempotencyKey:De,registryVersion:Ie,registryChecksum:me,...ge?{strictReadOnly:ge}:{}};const kn=Te(K);if(!h&&e.inputSource&&e.inputSource!=="args"&&kn>=et)try{K={argsRef:(await nr(d,"secondary-mutation",()=>Io(_,o,D.token,()=>D.client.forceRefresh()),async()=>{throw new Re("readonly-physical-boundary-unsafe","boundary")})).argsRef,projectRoot:c.replace(Pe(),"~"),stateSnapshot:ee,platformTarget:T,...k?{nativeHostAttestation:k}:{},projectId:_e,inputEvidence:i,idempotencyKey:De,registryVersion:Ie,registryChecksum:me,...ge?{strictReadOnly:ge}:{}}}catch(a){return a instanceof Re?{success:!1,error:a.code,errorCode:a.code,exitCode:1}:{success:!1,error:`INVOKE_MATERIALIZATION_FAILED: ${a instanceof Error?a.message:String(a)}`,errorCode:"INVOKE_MATERIALIZATION_FAILED",exitCode:1}}try{const a=In(K);K=a.body,a.degraded?_n(K,a.telemetry):So(K)}catch(a){if(a instanceof it||a instanceof st)return _n(K,a.telemetry),process.stderr.write(`[Neocortex] ${a.message}
43
- `),{success:!1,error:a.message,errorCode:a.code,metadata:{invokePayload:a.telemetry},exitCode:1};throw a}let b=await Pt("invoke-query",()=>vn(_,K,D.token,{refreshToken:()=>D.client.forceRefresh()})),It;if(h&&b.ok)try{if(f){const u=b.data?.metadata;if(u&&["stateUpdate","stateMutated","yoloopStateUpdate","continuityStateUpdate","checkpoint","schedulerStateUpdate","quotaCacheUpdate","projectIdentityMigration","epicClaim","gitLifecycleGraphAuthority"].some(P=>u[P]!==void 0))throw new Re("readonly-response-conflict")}const a=b.data?.metadata.strictReadOnly;ar(d,a),f&&pr(b.data?.metadata.strictDiagnose,n,b.data?.instructions??""),It=a.security}catch(a){const u=a instanceof Re?a.code:"readonly-receipt-mismatch";return{success:!1,error:u,errorCode:u,exitCode:1}}if(!b.ok&&b.status===426){const a=b.errorBody,u=a?.upgrade_command??"npm install -g @ornexus/neocortex@latest",y=a?.min_version??"unknown";return process.stderr.write(`
25
+ `))}catch{const s="INVALID_YOLOOP_TARGET: yoloop target normalization was unavailable; no request was sent.";return process.stderr.write(`${s}
26
+ `),{success:!1,error:s,exitCode:1}}const w=fr(l);if(w)try{hr(c,{allowMissingRuntime:!0}).runtimeMissing&&(await d.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},async()=>Ln(c),async()=>{}),hr(c))}catch(s){const u=s instanceof Ee?s.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${u}. No request was sent; repair the canonical project state and retry.
27
+ `),{success:!1,error:u,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}try{d.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>tn(c,{args:e.args,canonicalCommandId:l}),()=>{})}catch(s){if(s instanceof rn)return process.stderr.write(`${s.message}
28
+ `),{success:!1,error:s.message,exitCode:1};const u=s instanceof Error?s.message:String(s);return process.stderr.write(`[Neocortex] state.json repair stopped unexpectedly: ${u}. No request was sent; inspect .neocortex/state.json and rerun.
29
+ `),{success:!1,error:u,exitCode:1}}let E;try{const s=await Io(c,e.args,l);E=gr(c,{epicAware:w,p205Authorities:s})}catch(s){const u=s instanceof Ee?s.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${u}. No request was sent; repair the canonical project state/runtime sidecar and retry.
30
+ `),{success:!1,error:u,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}try{const{maybeAutoResolveYoloopArgs:s}=await import("../yoloop/invoke-hooks.js"),u={args:e.args,projectRoot:c,logger:{info:m=>process.stderr.write(`${m}
31
+ `),warn:m=>process.stderr.write(`${m}
32
+ `)}};s(u),u.args!==e.args&&(e={...e,args:u.args},o=u.args,i=Ft(Ge(t.source,o)))}catch(s){const u=s instanceof Error?s.message:String(s);process.stderr.write(`[Neocortex] Auto-resolve hook (P121.05) failed: ${u}. Proceeding with raw args.
33
+ `)}try{const{readYoloopForRequest:s}=await import("../yoloop/invoke-hooks.js"),u=await s(e.args,c);if(u){const m=_i(E,u);E.yoloop=m?{...u,continuationRecoveryEvidence:m}:u}}catch(s){if(/^\s*\*?(?:yoloop|auto-yolo|epic-runner|story-runner|loop-yolo|auto-epic)\b/i.test(e.args)){const m=s instanceof Error?s.message.match(/\bYOLOOP_[A-Z0-9_]+\b/)?.[0]??"YOLOOP_STATE_READ_FAILED":"YOLOOP_STATE_READ_FAILED";return process.stderr.write(`[Neocortex] ${m}. No yoloop request was sent and no state was mutated.
34
+ `),{success:!1,error:m,errorCode:m,exitCode:1}}}try{const{readContinuityForRequest:s}=await import("../continuity/invoke-hooks.js"),u=await s(e.args,c,void 0,d,{includeExistingStore:!f});u&&(E.continuity=u)}catch(s){if(s instanceof Ne)return{success:!1,error:s.code,errorCode:s.code,exitCode:1};const u=s instanceof Error?s.message:String(s);process.stderr.write(`[Neocortex] continuity snapshot hook failed: ${u}. Proceeding without continuity state.
35
+ `)}try{const{maybeRunDiscoveryHook:s}=await import("../yoloop/invoke-hooks.js");await s({args:e.args,projectRoot:c,stateSnapshot:E,featureFlag:process.env.YOLOOP_AUTO_DISCOVERY!=="off",logger:{warn:u=>{console.warn(u)},info:u=>{console.error(u)}}})}catch(s){const u=s instanceof Error?s.message:String(s);process.stderr.write(`[Neocortex] discovery hook failed: ${u}. Proceeding without enrichment.
36
+ `)}try{const{readArchitecturePolicy:s}=await import("../policy/architecture-policy.js"),u=await s(c);u&&(E.architecture_policy=u)}catch(s){const u=s instanceof Error?s.message:String(s);console.warn(`[Neocortex] architecture-policy hook failed: ${u}. Proceeding without policy.`)}try{const s=/^(1|true|on|yes)$/i.test(process.env.NEOCORTEX_GRAPH_RETRIEVAL??""),{maybeRunGraphRetrievalHook:u}=await import("../yoloop/invoke-hooks.js"),m=await u({args:e.args,projectRoot:c,featureFlag:s,logger:{warn:b=>process.stderr.write(`${b}
37
+ `)}});m.applied&&m.metadata&&(E.graphRetrieval=m.metadata)}catch(s){const u=s instanceof Error?s.message:String(s);process.stderr.write(`[Neocortex] graph retrieval hook failed: ${u}. Proceeding without enrichment.
38
+ `)}try{if(ro(e.args)){const{collectProjectEvidence:s}=await import("../evidence/collector.js"),u=a.selection.uiUxReview?.architectureDir,m=s({projectRoot:c,...u?{candidatePaths:[u],includeFallbackInventory:!0}:{}});(m.evidence.length>0||m.exclusions.length>0)&&(E.projectEvidence=m)}}catch(s){const u=s instanceof Error?s.message:String(s);process.stderr.write(`[Neocortex] project evidence collection failed: ${u}. Proceeding without local project evidence.
39
+ `)}try{const s=await d.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"checkpoint-consume",operation:"consume"},async()=>{const{readAndConsumeCheckpoint:u}=await import("../checkpoint/index.js");return u(c)},async()=>{});s&&(E.implementCheckpoint=s)}catch(s){const u=s instanceof Error?s.message:String(s);process.stderr.write(`[Neocortex] checkpoint hook failed: ${u}. Proceeding without checkpoint.
40
+ `)}const U=j?.licenseKey?new st({cacheDir:ct,passphrase:j.licenseKey,strictReadOnly:I}):null,k=o.trim();if(!k&&U){const s=await d.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>Eo(U),async()=>null);if(s)return d.complete(),{success:!0,instructions:s.instructions,metadata:s.metadata,exitCode:0}}const N=await yr(h,j?.licenseKey,d);if(N.status!=="authenticated"){const s=N.status==="refresh-required",u=!s&&j&&!j.licenseKey?" This may be caused by a machine fingerprint change (e.g., hardware or hostname change).":"";try{const m=Pt(),b=Nt(s?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",m);b&&process.stderr.write(Lt(b,m))}catch{}return{success:!1,error:s?"Authentication refresh required. Run: neocortex activate YOUR-LICENSE-KEY":`Not authenticated.${u} Visit https://neocortex.sh/portal/login to get your license key, then run: neocortex activate YOUR-LICENSE-KEY`,errorCode:s?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",exitCode:s?1:2}}const $=E.config.project_id;try{await d.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Ei(c,E,h,N.token,$,{refreshToken:()=>N.client.forceRefresh()}),async()=>0)}catch{}const L=Si(k);if(L&&!f)try{const s=await N.tierClient.preFlightCheck(L);if(!s.allowed)return process.stderr.write(`[neocortex] ${s.message}
41
+ `),{success:!1,error:s.message??"Trigger not available on your plan",exitCode:1}}catch{}const T=await jo({args:k,projectRoot:c,platformTarget:P,environment:e.environment??process.env,bootstrapper:e.runnerBootstrapper,effectAuthority:d});if(T.attachToRequest&&(E.runnerBootstrap=T.metadata),T.warning&&process.stderr.write(`[Neocortex] ${T.warning}
42
+ `),!T.shouldContinue)return T.error&&process.stderr.write(`[Neocortex] ${T.error}
43
+ `),{success:!1,error:T.error??"Runner auto-bootstrap required but failed.",errorCode:T.errorCode,exitCode:T.exitCode??1};let J;try{const s=Qr(k,E);if(s&&!s.ok){const u=`${s.code}: structural projection failed closed; select a valid target or repair the dependency DAG.`;return process.stderr.write(`${u}
44
+ `),{success:!1,error:u,errorCode:s.code,metadata:{stateProjection:s,publicSafe:!0},exitCode:1}}J=s?.snapshot??Dt(k,E)}catch(s){if(s instanceof jt){const u=`${s.code}: structural projection failed closed; select a valid target or repair the dependency DAG.`;return process.stderr.write(`${u}
45
+ `),{success:!1,error:u,errorCode:s.code,metadata:{structuralProjection:{...s.publicDetails,publicSafe:!0}},exitCode:1}}throw s}if(!I)try{const{openNativeAgentPrivateStore:s,resolveNativeAgentPrivateRuntimePaths:u}=await import("../continuity/native-agent-store.js"),m=u(c);if(Oe(m.databasePath)){const b=await s(c);try{const G=b.store.listRecentNativeAgentDispatches(20);G.length>0&&(J.nativeAgentDispatches=G)}finally{b.store.close()}}}catch{}const Ce=xt(k),he=$;if(Ce==="create-epic"&&!he){const s='EPIC_PROJECT_ID_REQUIRED: run `neocortex-client invoke --args "*migrate-project-id"` and retry create-epic. No repository checkout or database credentials are required.';return process.stderr.write(`${s}
46
+ `),{success:!1,error:s,errorCode:"EPIC_PROJECT_ID_REQUIRED",exitCode:1}}let be;try{be=d.execute({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Ce==="create-epic"?Jn(c,k):void 0,()=>{})}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const He=be?.key,Se=I?{schemaVersion:1,invocationId:d.invocationId,intent:d.intent,clientProjection:yn(Wt.map(s=>({...s,count:1})))}:void 0;let F;if(e.privateExecutionBeta)try{const{preflightPrivateCodexExecutor:s}=await import("../private-execution/codex-executor.js");F=await s(c)}catch(s){const u=s instanceof Error&&/^private-codex-[a-z-]+$/.test(s.message)?s.message:"private-codex-preflight-unavailable";return{success:!1,error:u,errorCode:u,exitCode:1}}const We=F?{schemaVersion:1,hostKind:"codex-cli",hostVersion:F.hostVersion,sandboxProof:{schemaVersion:5,trust:"client-self-attested",credentialKind:"chatgpt-subscription",authIsolation:"passed",workspaceWrite:"passed",gitControlWriteDenied:"passed",gitLifecycleReadDenied:"passed",mcpIsolation:"passed",environmentIsolation:"passed",networkDenied:"passed",observedAtMs:F.observedAtMs}}:void 0;let H={args:o,projectRoot:c.replace(Fe(),"~"),stateSnapshot:J,platformTarget:P,...v?{nativeHostAttestation:v}:{},...We?{privateExecution:We}:{},projectId:he,inputEvidence:i,idempotencyKey:He,registryVersion:we,registryChecksum:Re,...Se?{strictReadOnly:Se}:{}};const Mr=Pe(H);if(!I&&e.inputSource&&e.inputSource!=="args"&&Mr>=dt)try{H={argsRef:(await hn(d,"secondary-mutation",()=>Oo(h,o,N.token,()=>N.client.forceRefresh()),async()=>{throw new Ne("readonly-physical-boundary-unsafe","boundary")})).argsRef,projectRoot:c.replace(Fe(),"~"),stateSnapshot:J,platformTarget:P,...v?{nativeHostAttestation:v}:{},...We?{privateExecution:We}:{},projectId:he,inputEvidence:i,idempotencyKey:He,registryVersion:we,registryChecksum:Re,...Se?{strictReadOnly:Se}:{}}}catch(s){return s instanceof Ne?{success:!1,error:s.code,errorCode:s.code,exitCode:1}:{success:!1,error:`INVOKE_MATERIALIZATION_FAILED: ${s instanceof Error?s.message:String(s)}`,errorCode:"INVOKE_MATERIALIZATION_FAILED",exitCode:1}}if(Ce==="yolo"&&J.scope?.projectionMode==="yolo-story"){const s=J.scope?.targetStoryId,u=J.scope?.targetEpicId;if(!s||!u)return{success:!1,error:"yolo-spec-envelope-target-mismatch",errorCode:"yolo-spec-envelope-target-mismatch",exitCode:1};try{const{collectYoloSpecEnvelope:m}=await import("../yolo/spec-envelope-collector.js"),b=m({projectRoot:c,storyId:s,epicId:u,inputSha256:i.sha256});if(/\sbranchless-preparation\s*$/.test(o))H={...H,yoloSpecEnvelope:b};else{const{collectYoloChangeEvidence:G}=await import("../yolo/change-evidence-collector.js"),W=G({projectRoot:c,defaultBranch:J.config.default_branch,expectedHeadSha:b.sourceRevision.headSha});H={...H,yoloSpecEnvelope:b,yoloChangeEvidence:W}}}catch(m){const b=m instanceof Error&&/^yolo-(?:spec-envelope|change-evidence)-[a-z-]+$/.test(m.message)?m.message:"yolo-spec-envelope-unsafe";return{success:!1,error:b,errorCode:b,exitCode:1}}}try{const s=Ar(H);H=s.body,s.degraded?wr(H,s.telemetry):Do(H)}catch(s){if(s instanceof ht||s instanceof gt)return wr(H,s.telemetry),process.stderr.write(`[Neocortex] ${s.message}
47
+ `),{success:!1,error:s.message,errorCode:s.code,metadata:{invokePayload:s.telemetry},exitCode:1};throw s}if(Ce==="yolo"&&H.yoloSpecEnvelope)try{const{collectYoloSpecEnvelope:s}=await import("../yolo/spec-envelope-collector.js"),u=s({projectRoot:c,storyId:H.yoloSpecEnvelope.storyId,epicId:H.yoloSpecEnvelope.epicId,inputSha256:i.sha256,collectedAt:H.yoloSpecEnvelope.collectedAt});if(u.envelopeSha256!==H.yoloSpecEnvelope.envelopeSha256)throw new Error("yolo-spec-envelope-stale");if(H.yoloChangeEvidence){const{collectYoloChangeEvidence:m}=await import("../yolo/change-evidence-collector.js"),b=m({projectRoot:c,defaultBranch:J.config.default_branch,expectedHeadSha:u.sourceRevision.headSha});if(b.pathsSha256!==H.yoloChangeEvidence.pathsSha256||b.baseSha!==H.yoloChangeEvidence.baseSha)throw new Error("yolo-spec-envelope-stale")}}catch{return{success:!1,error:"yolo-spec-envelope-stale",errorCode:"yolo-spec-envelope-stale",exitCode:1}}let _=await Ht("invoke-query",()=>Pr(h,H,N.token,{refreshToken:()=>N.client.forceRefresh()})),wt;if(I&&_.ok)try{if(f){const u=_.data?.metadata;if(u&&["stateUpdate","stateMutated","yoloopStateUpdate","continuityStateUpdate","checkpoint","schedulerStateUpdate","quotaCacheUpdate","projectIdentityMigration","epicClaim","gitLifecycleGraphAuthority"].some(b=>u[b]!==void 0))throw new Ne("readonly-response-conflict")}const s=_.data?.metadata.strictReadOnly;En(d,s),f&&Rn(_.data?.metadata.strictDiagnose,r,_.data?.instructions??""),wt=s.security}catch(s){const u=s instanceof Ne?s.code:"readonly-receipt-mismatch";return{success:!1,error:u,errorCode:u,exitCode:1}}if(!_.ok&&_.status===426){const s=_.errorBody,u=s?.upgrade_command??"npm install -g @ornexus/neocortex@latest",m=s?.min_version??"unknown";return process.stderr.write(`
44
48
  `),process.stderr.write(`==================================================
45
49
  `),process.stderr.write(` UPGRADE REQUIRED
46
50
  `),process.stderr.write(`==================================================
47
51
  `),process.stderr.write(`
48
- Your Neocortex version (${Se}) is no longer supported.
49
- `),process.stderr.write(` Minimum required: ${y}
52
+ Your Neocortex version (${ke}) is no longer supported.
53
+ `),process.stderr.write(` Minimum required: ${m}
50
54
 
51
55
  `),process.stderr.write(` Run this command to update:
52
56
 
@@ -55,15 +59,15 @@ ${t}
55
59
  `),process.stderr.write(` After updating, re-run your command.
56
60
  `),process.stderr.write(`==================================================
57
61
 
58
- `),{success:!1,error:`UPGRADE_REQUIRED: Client version ${Se} is below minimum ${y}. Run: ${u}`,exitCode:3}}if(!b.ok||!b.data){const a=b.status===401?2:(b.status===429||b.status>=500,1),u=lo(b);try{if(u){const y=bt(),P=wt(u,y);P&&process.stderr.write(Tt(P,y))}}catch{}return{success:!1,error:Z(b.error??"Unknown error from server",ye),...u?{errorCode:u}:{},exitCode:a}}if(!L&&b.data.metadata?.mode==="menu"&&M&&await d.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>ao(M,b.data.instructions,b.data.metadata),async()=>{}).catch(()=>{}),b.data.metadata&&await d.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"tier-cache",operation:"update"},()=>D.tierClient.updateQuotaFromResponse(b.data.metadata),async()=>{}).catch(()=>{}),b.data.metadata?.stateMutated===!0)try{const a=await d.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>{const{persistMigratedStateFromResponse:u}=await import("../yoloop/invoke-hooks.js");return u(b.data.metadata,c)},async()=>({applied:!1,blocking:!1,reasonCode:"state-writeback-effect-skipped"}));if(a.blocking){const u=`STATE_WRITEBACK_BLOCKED: ${a.reasonCode}. Canonical state was not replaced.`;return process.stderr.write(`${u}
59
- `),{success:!1,error:u,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}catch(a){if(b.data.metadata?.stateMutationReason==="inline-yolo-materialized-synthetic-story"){const u=a instanceof Error?a.message:String(a),y=`STATE_WRITEBACK_BLOCKED: inline-yolo persistence failed (${Z(u,ye)}).`;return process.stderr.write(`${y}
60
- `),{success:!1,error:y,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}if(b.data.metadata?.gitLifecycleGraphAuthority)try{await d.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},()=>Sr(c,b.data.metadata.gitLifecycleGraphAuthority),async()=>{throw new Error("git-lifecycle-graph-authority-effect-skipped")})}catch(a){const u=a instanceof Error&&/^git-lifecycle-/.test(a.message)?a.message:"git-lifecycle-graph-authority-persist-failed";return process.stderr.write(`[Neocortex] ${u}. Graph authority was not persisted; no YOLO checkpoint instruction was released.
61
- `),{success:!1,error:u,errorCode:"GIT_LIFECYCLE_GRAPH_AUTHORITY_INVALID",exitCode:1}}if(b.data.metadata?.mode==="error"&&b.data.metadata?.errorCode==="CLIENT_UPGRADE_REQUIRED")return process.stderr.write(`
62
+ `),{success:!1,error:`UPGRADE_REQUIRED: Client version ${ke} is below minimum ${m}. Run: ${u}`,exitCode:3}}if(!_.ok||!_.data){const s=_.status===401?2:(_.status===429||_.status>=500,1),u=Ao(_);try{if(u){const m=Pt(),b=Nt(u,m);b&&process.stderr.write(Lt(b,m))}}catch{}return{success:!1,error:ie(_.error??"Unknown error from server",ve),...u?{errorCode:u}:{},exitCode:s}}if(e.privateExecutionBeta&&!Gr(_.data))return{success:!1,error:"private-execution-public-envelope-invalid",errorCode:"private-execution-public-envelope-invalid",exitCode:1};if(!k&&_.data.metadata?.mode==="menu"&&U&&await d.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>_o(U,_.data.instructions,_.data.metadata),async()=>{}).catch(()=>{}),_.data.metadata&&await d.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"tier-cache",operation:"update"},()=>N.tierClient.updateQuotaFromResponse(_.data.metadata),async()=>{}).catch(()=>{}),_.data.metadata?.stateMutated===!0)try{const s=await d.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>{const{persistMigratedStateFromResponse:u}=await import("../yoloop/invoke-hooks.js");return u(_.data.metadata,c)},async()=>({applied:!1,blocking:!1,reasonCode:"state-writeback-effect-skipped"}));if(s.blocking){const u=`STATE_WRITEBACK_BLOCKED: ${s.reasonCode}. Canonical state was not replaced.`;return process.stderr.write(`${u}
63
+ `),{success:!1,error:u,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}catch(s){if(_.data.metadata?.stateMutationReason==="inline-yolo-materialized-synthetic-story"){const u=s instanceof Error?s.message:String(s),m=`STATE_WRITEBACK_BLOCKED: inline-yolo persistence failed (${ie(u,ve)}).`;return process.stderr.write(`${m}
64
+ `),{success:!1,error:m,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}if(_.data.metadata?.gitLifecycleGraphAuthority)try{await d.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},()=>Dn(c,_.data.metadata.gitLifecycleGraphAuthority),async()=>{throw new Error("git-lifecycle-graph-authority-effect-skipped")})}catch(s){const u=s instanceof Error&&/^git-lifecycle-/.test(s.message)?s.message:"git-lifecycle-graph-authority-persist-failed";return process.stderr.write(`[Neocortex] ${u}. Graph authority was not persisted; no YOLO checkpoint instruction was released.
65
+ `),{success:!1,error:u,errorCode:"GIT_LIFECYCLE_GRAPH_AUTHORITY_INVALID",exitCode:1}}if(_.data.metadata?.mode==="error"&&_.data.metadata?.errorCode==="CLIENT_UPGRADE_REQUIRED")return process.stderr.write(`
62
66
  `),process.stderr.write(`==================================================
63
67
  `),process.stderr.write(` YOLOOP CLIENT UPGRADE REQUIRED
64
68
  `),process.stderr.write(`==================================================
65
69
  `),process.stderr.write(`
66
- Your Neocortex client version (${Se}) does not
70
+ Your Neocortex client version (${ke}) does not
67
71
  `),process.stderr.write(` support client-side yoloop state persistence.
68
72
 
69
73
  `),process.stderr.write(` Run this command to upgrade:
@@ -73,14 +77,18 @@ ${t}
73
77
  `),process.stderr.write(` After upgrading, re-run your yoloop command.
74
78
  `),process.stderr.write(`==================================================
75
79
 
76
- `),{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(b.data.metadata?.yoloopStateUpdate){const u=(b.data.metadata.yoloopStateUpdate.operations??[]).some(y=>y.type==="rollover_session");try{const y=await d.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>{const{persistYoloopFromResponse:P}=await import("../yoloop/invoke-hooks.js");return P(b.data.metadata,c)},async()=>({ok:!0,authoritative:!1,reasonCodes:[]}));if(y&&y.ok===!1){const P=y.reasonCodes[0]??"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED";return process.stderr.write(`[Neocortex] ${P}. No yoloop continuation instructions were released.
77
- `),{success:!1,error:P,errorCode:P,exitCode:1}}}catch(y){if(u){const P=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] ${P}. No yoloop continuation instructions were released.
78
- `),{success:!1,error:P,errorCode:P,exitCode:1}}}}if(b.data.metadata?.continuityStateUpdate)try{const a=await d.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"continuity-store",operation:"update"},async()=>{const{persistContinuityFromResponse:u}=await import("../continuity/invoke-hooks.js");return u(b.data.metadata,c)},async()=>({ok:!0,reasonCodes:[]}));if(!a.ok){const u=a.reasonCodes.join(",");return process.stderr.write(`[Neocortex] continuity persistence failed: ${u}. No continuity mutation was committed.
79
- `),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${u}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}}catch(a){const u=a instanceof Error?a.message:String(a);return process.stderr.write(`[Neocortex] continuity persistence hook failed: ${u}. No continuity mutation was committed.
80
- `),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${Z(u,ye)}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}if(b.data.metadata?.tier_changed){const a=b.data.metadata.current_tier;try{await D.client.forceRefresh()?(await D.tierClient.invalidateTierCache(),process.stderr.write(`[Neocortex] Token atualizado automaticamente para tier ${a}
81
- `)):process.stderr.write(`[Neocortex] Seu tier foi atualizado para ${a}! Execute "neocortex activate" para obter um token atualizado.
82
- `)}catch{process.stderr.write(`[Neocortex] Seu tier foi atualizado para ${a}! Execute "neocortex activate" para obter um token atualizado.
83
- `)}}const yt=ot(b.data.instructions,b.data.metadata);if(Ee&&b.data.metadata?.mode!=="error")try{const a=b.data.metadata?.epicClaim;if(!a||typeof a!="object"||Array.isArray(a))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const u=a;if(u.outcome!=="reserved"||typeof u.claimId!="string"||typeof u.epicId!="string")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");d.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Mr(c,Ee.fingerprint,u.claimId,u.epicId),()=>{})}catch{}return d.complete(It),{success:!0,instructions:yt.instructions,metadata:yt.metadata,exitCode:0}}function di(e){const[t]=e.trim().split(/\s+/,1);return t?/^@?epic-[a-z0-9][a-z0-9._-]*$/i.test(t)?"epic":St(t):null}const On="Provide exactly one invoke input source: --args <string>, --stdin, or --args-file <path>.",ui=`
80
+ `),{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(_.data.metadata?.yoloopStateUpdate){const u=(_.data.metadata.yoloopStateUpdate.operations??[]).some(m=>m.type==="rollover_session");try{const m=await d.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>{const{persistYoloopFromResponse:b}=await import("../yoloop/invoke-hooks.js");return b(_.data.metadata,c)},async()=>({ok:!0,authoritative:!1,reasonCodes:[]}));if(m&&m.ok===!1){const b=m.reasonCodes[0]??"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED";return process.stderr.write(`[Neocortex] ${b}. No yoloop continuation instructions were released.
81
+ `),{success:!1,error:b,errorCode:b,exitCode:1}}}catch(m){if(u){const b=m instanceof Error?m.message.match(/\bYOLOOP_[A-Z0-9_]+\b/)?.[0]??"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED":"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED";return process.stderr.write(`[Neocortex] ${b}. No yoloop continuation instructions were released.
82
+ `),{success:!1,error:b,errorCode:b,exitCode:1}}}}if(_.data.metadata?.continuityStateUpdate)try{const s=await d.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"continuity-store",operation:"update"},async()=>{const{persistContinuityFromResponse:u}=await import("../continuity/invoke-hooks.js");return u(_.data.metadata,c)},async()=>({ok:!0,reasonCodes:[]}));if(!s.ok){const u=s.reasonCodes.join(",");return process.stderr.write(`[Neocortex] continuity persistence failed: ${u}. No continuity mutation was committed.
83
+ `),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${u}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}}catch(s){const u=s instanceof Error?s.message:String(s);return process.stderr.write(`[Neocortex] continuity persistence hook failed: ${u}. No continuity mutation was committed.
84
+ `),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${ie(u,ve)}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}if(_.data.metadata?.tier_changed){const s=_.data.metadata.current_tier;try{await N.client.forceRefresh()?(await N.tierClient.invalidateTierCache(),process.stderr.write(`[Neocortex] Token atualizado automaticamente para tier ${s}
85
+ `)):process.stderr.write(`[Neocortex] Seu tier foi atualizado para ${s}! Execute "neocortex activate" para obter um token atualizado.
86
+ `)}catch{process.stderr.write(`[Neocortex] Seu tier foi atualizado para ${s}! Execute "neocortex activate" para obter um token atualizado.
87
+ `)}}let Ae;if(e.privateExecutionBeta)try{if(!F||!_.data.metadata?.privateExecution||!he||_.data.metadata?.mode!=="yolo"&&_.data.metadata?.mode!=="step"&&_.data.metadata?.mode!=="pipeline"||typeof _.data.metadata.stepId!="string")throw new Error("private-execution-descriptor-unavailable");const{consumePrivateExecutionDelivery:s,privateExecutionStateSnapshotSha256:u}=await import("../private-execution/delivery.js"),{preflightPrivateCodexExecutor:m,runPrivateCodexStep:b}=await import("../private-execution/codex-executor.js"),G=_.data.metadata.mode==="yolo",W=_.data.metadata.gitLifecycleGraphAuthority,le=_.data.metadata.privateExecutionRootAction;let Z;if(G){if(!W||typeof W.storyId!="string"||typeof W.graphRevision!="string"||typeof W.executionBranch!="string")throw new Error("private-execution-graph-unavailable");if(Z=W.storyId,le?.action==="prepare-epic-checkout"){const{prepareDirectYoloSetup:Ur}=await import("../git/direct-yolo-checkpoint.js"),{capturePrivateYoloCleanHead:Vr,recordPrivateYoloCleanBaseline:Br}=await import("../private-execution/clean-baseline.js"),$r=Vr(c),vt=await Ur({projectRoot:c,storyId:le.storyId});if(!vt.ok)throw new Error("private-execution-root-setup-denied");await Br(c,vt.value,$r)}let V;try{V=Te("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:c,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{throw new Error("private-execution-execution-branch-mismatch")}if(V!==W.executionBranch)throw new Error("private-execution-execution-branch-mismatch");const Me=Je(c,{required:!0}),oe=typeof W.epicId=="string"?Me.epics[W.epicId]:void 0,ge=y(oe?.branch_lease)?oe.branch_lease:void 0;if(!oe||oe.graph_revision!==W.graphRevision||!ge||ge.ownerStoryId!==W.storyId||typeof ge.expiresAt!="string"||!Number.isFinite(Date.parse(ge.expiresAt))||Date.parse(ge.expiresAt)<=Date.now())throw new Error("private-execution-writer-lease-unavailable")}else if(_.data.metadata.mode==="step"&&_.data.metadata.resolvedTrigger==="research"||_.data.metadata.mode==="pipeline"&&_.data.metadata.resolvedTrigger==="exec"){if(typeof _.data.metadata.storyId!="string")throw new Error("private-execution-descriptor-unavailable")}else throw new Error("private-execution-descriptor-unavailable");if(G){const{ensurePrivateYoloIsolatedSession:V,reconcilePrivateYoloIsolatedSession:Me}=await import("../private-execution/isolated-session.js");if(le?.action==="checkpoint-epic-story")await Me(c,Z,W.graphRevision);else{const oe=await V(c,Z,W.graphRevision,e.privateExecutionWorkspaceParent),ge=await m(oe.workspace.workspacePath);if(ge.hostVersion!==F.hostVersion)throw new Error("private-codex-version-drift");F=ge}}if(Date.now()-F.observedAtMs>2e4){const V=await m(F.projectRoot);if(V.hostVersion!==F.hostVersion)throw new Error("private-codex-version-drift");F=V}const Q=await N.client.getToken();if(!Q)throw new Error("private-execution-auth-unavailable");const M=await s(_.data.metadata.privateExecution,{projectId:he,commandId:G?"yolo":_.data.metadata.mode==="pipeline"?"exec":"research",stepId:_.data.metadata.stepId,...G?{graphRevision:W.graphRevision}:{storyId:_.data.metadata.storyId,stateSnapshotSha256:u(J)},inputSha256:i.sha256,hostKind:"codex-cli",hostVersion:F.hostVersion},V=>yi(h,{...V},Q));if(le?.action==="checkpoint-epic-story"){const{runPrivateYoloRootCheckpoint:V}=await import("../private-execution/root-checkpoint.js");Ae={...await V(c,le)}}else{const V=await b(M,F,{requireWorkspaceEffect:G,...G?{expectedExecutionBranch:W.executionBranch}:{}});if(G){const{admitPrivateYoloIsolatedSessionStep:Me}=await import("../private-execution/isolated-session.js"),oe=await Me(c,Z,W.graphRevision);Ae={...V,isolation:{schemaVersion:1,outcome:oe.admission.outcome,sequence:oe.session.sequence,snapshotSha:oe.session.snapshotSha,patchSha256:oe.admission.patchSha256,changedPathCount:oe.admission.changedPaths.length}}}else Ae={...V}}}catch(s){const u=s instanceof Error&&/^(private-execution|private-codex)-[a-z-]+$/.test(s.message)?s.message:"private-execution-unverified";return{success:!1,error:u,errorCode:u,exitCode:1}}const ot=ft(_.data.instructions,_.data.metadata);if(be&&_.data.metadata?.mode!=="error")try{const s=_.data.metadata?.epicClaim;if(!s||typeof s!="object"||Array.isArray(s))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const u=s;if(u.outcome!=="reserved"||typeof u.claimId!="string"||typeof u.epicId!="string")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");d.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>qn(c,be.fingerprint,u.claimId,u.epicId),()=>{})}catch{}return d.complete(wt),{success:!0,instructions:Ae?Ae.outcome==="checkpoint-validated"?`# Checkpoint da story validado
88
+
89
+ O root registrou o commit e a valida\xE7\xE3o f\xEDsica no branch do epic.`:`# Execu\xE7\xE3o privada conclu\xEDda; valida\xE7\xE3o f\xEDsica pendente
90
+
91
+ O executor Codex retornou sem erro. Nenhum checkpoint ou aprova\xE7\xE3o da story foi emitido.`:ot.instructions,metadata:Ae?{...ot.metadata,privateExecutionReceipt:Ae}:ot.metadata,exitCode:0}}function Si(e){const[t]=e.trim().split(/\s+/,1);return t?/^@?epic-[a-z0-9][a-z0-9._-]*$/i.test(t)?"epic":xt(t):null}const Dr="Provide exactly one invoke input source: --args <string>, --stdin, or --args-file <path>.",Ai=`
84
92
  neocortex-client invoke - Send orchestration request to server
85
93
 
86
94
  Usage:
@@ -103,6 +111,7 @@ Options:
103
111
  --server-url <url> Server URL override
104
112
  --platform-target <id> Explicit platform target override (default: runtime detection; unknown on no match)
105
113
  --strict-read-only Request exact signed strict-read-only-v1 execution (registry-gated)
114
+ --private-execution-beta Run an explicit *yolo, *exec or *research step through the isolated Codex CLI beta executor
106
115
 
107
116
  Invocation payload boundary:
108
117
  Select only the explicit user-intended Neocortex command and arguments after
@@ -149,12 +158,12 @@ Safety:
149
158
  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.
150
159
  Jobs, goal and loop watch use serverHeldStream=false and foreground local SQLite polling of public processing summaries only.
151
160
  Unresolved targets disable polling with public reason codes; there is no all-jobs fallback.
152
- `.trim();function li(e){return e.includes("--help")||e.includes("-h")||e.includes("help")}function q(e,t,n,r){return new Be("INVOCATION_MALFORMED_INPUT",t,e,n,r)}function ve(e){return q("missing-input-value",`${e} requires a value. ${On}`)}function pi(e){try{if(!Dn(e).isFile())throw q("missing-input-value","--args-file must point to a readable UTF-8 text file.","args-file");return Ae(e)}catch(t){throw t instanceof Be?t:q("missing-input-value","--args-file could not be read as UTF-8 text. Check the path and permissions.","args-file")}}function fi(){try{if(process.stdin.isTTY)throw q("missing-input-value","--stdin requires piped UTF-8 text, for example: neocortex-client invoke --stdin < synthetic.story.md","stdin");return Ae(0)}catch(e){throw e instanceof Be?e:q("missing-input-value","--stdin could not be read as UTF-8 text. Pipe command text into stdin and retry.","stdin")}}function gi(e,t={}){let n,r=!1,o,i,s="plain",c=!1,l,p,g=!1;for(let T=0;T<e.length;T++)switch(e[T]){case"--args":{const w=e[++T];if(w===void 0)throw ve("--args");if(n!==void 0)throw q("multiple-input-sources","Provide --args only once. Use one explicit invoke input source.","args");n=w;break}case"--stdin":if(r)throw q("multiple-input-sources","Provide --stdin only once. Use one explicit invoke input source.","stdin");r=!0;break;case"--args-file":{const w=e[++T];if(w===void 0)throw ve("--args-file");if(o!==void 0)throw q("multiple-input-sources","Provide --args-file only once. Use one explicit invoke input source.","args-file");o=w;break}case"--project-root":{const w=e[++T];if(w===void 0)throw ve("--project-root");i=w;break}case"--format":{const w=e[++T];if(w===void 0)throw ve("--format");if(w!=="json"&&w!=="plain")throw q("unexpected-cli-token","--format accepts only json or plain.");s=w;break}case"--watch":c=!0;break;case"--server-url":{const w=e[++T];if(w===void 0)throw ve("--server-url");l=w;break}case"--platform-target":{const w=e[++T];if(w===void 0)throw ve("--platform-target");p=w;break}case"--strict-read-only":g=!0;break;default:throw q("unexpected-cli-token","Unexpected top-level CLI token. Quote the complete --args payload or use --stdin/--args-file for multiline content.")}const C=[n!==void 0?"args":void 0,r?"stdin":void 0,o!==void 0?"args-file":void 0].filter(T=>T!==void 0);if(C.length===0)throw q("missing-input-value",On);if(C.length>1)throw q("multiple-input-sources",`Choose only one invoke input source; received ${C.join(", ")}.`);const f=C[0],d=f==="args"?n:f==="stdin"?(t.readStdin??fi)():(t.readArgsFile??pi)(o);let h;try{h=je(f,d)}catch(T){throw T instanceof fr?q("invalid-utf8",T.message,f):T}const S=f==="args"?Jo(h.rawArgs):G(h.rawArgs),E=S.args===h.rawArgs?h:je(f,S.args);return{args:S.args,inputSource:f,inputEnvelope:E,projectRoot:i,format:s,watch:c||S.watch,commandLevelWatch:S.metadata,serverUrl:l,platformTarget:p,strictReadOnly:g}}function Nn(e,t){return t?.active?{...e??{},commandLevelWatch:t,serverHeldStream:!1}:e}function hi(e,t,n=process.stdout,r=process.stderr){if(t.format==="json"){const s=ot(e.instructions,e.metadata),c=Nn(s.metadata,t.commandLevelWatch);if(t.watch){n.write(JSON.stringify({type:"invoke_result",instructions:s.instructions,metadata:c,publicSafe:!0})+`
153
- `);return}n.write(JSON.stringify({instructions:s.instructions,metadata:c})+`
154
- `);return}const o=ot(e.instructions,e.metadata),i=Nn(o.metadata,t.commandLevelWatch);n.write(o.instructions+`
155
- `),i&&r.write(JSON.stringify(i)+`
156
- `)}function mi(e){const t=()=>e.abort();return process.once("SIGINT",t),process.once("SIGTERM",t),()=>{process.removeListener("SIGINT",t),process.removeListener("SIGTERM",t)}}async function Zi(e){if(li(e))return process.stdout.write(`${ui}
157
- `),0;let t;try{t=gi(e)}catch(r){if(r instanceof Be)return process.stderr.write(JSON.stringify({error_code:r.code,reason:r.reason,source:r.source,byte_length:r.byteLength,message:r.message,remediation:r.message})+`
158
- `),1;throw r}if(Xn(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."})+`
159
- `),1):(await Zn({args:t.args,projectRoot:nt(t.projectRoot),format:t.format,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})).exitCode;const n=await ci({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});if(!n.success){const r=n.metadata?.invocationInput,o=r&&typeof r=="object"&&!Array.isArray(r)?r:void 0;return process.stderr.write(JSON.stringify({error_code:n.errorCode??(n.exitCode===2?"NOT_CONFIGURED":"INVOKE_ERROR"),message:Z(n.error??"",ye),...typeof o?.reason=="string"?{reason:Z(o.reason,80)}:{},...typeof o?.source=="string"?{source:Z(o.source,20)}:{},...Number.isSafeInteger(o?.byteLength)?{byte_length:o.byteLength}:{},...typeof o?.remediation=="string"?{remediation:Z(o.remediation,ye)}:{}})+`
160
- `),n.exitCode}if(hi(n,t),t.watch){const r=new AbortController,o=mi(r);try{const i=oi(n.metadata,t.args);i.disabled?Po(i.reasonCodes??[$.TARGET_UNRESOLVED],t.args,t.format,process.stdout):await jo({projectRoot:nt(t.projectRoot),format:t.format,strictReadOnly:t.strictReadOnly,...i,signal:r.signal})}finally{o()}}return 0}export{ui as INVOKE_HELP_TEXT,Ft as INVOKE_PAYLOAD_LIMIT_BYTES,et as INVOKE_PAYLOAD_WARNING_THRESHOLD_BYTES,Be as InvokeCliInputError,it as InvokePayloadTooLargeError,st as InvokeStructuralContextTooLargeError,pe as StateSnapshotIntegrityError,Ki as __resetSchemaDriftWarnedForTests,si as acknowledgeMaterializedPendingEpicClaims,Vr as admitClientInvocation,cn as assertEpicAwareStateShapeBeforeRepair,go as buildSignedInvokeAttempt,jr as clearPendingEpicIdempotencyKey,io as collectInvokeP205Authorities,dn as collectStateSnapshot,Te as computeInvokeRequestBodySizeBytes,Xi as createFullStateSnapshotScope,dt as createInvokePayloadTelemetry,zr as detectStateSchemaDrift,di as extractPreFlightTrigger,Pr as getOrCreatePendingEpicIdempotencyKey,In as guardInvokeRequestBodySize,ci as invoke,Zi as invokeCliHandler,an as isEpicAwareCommandId,So as maybeEmitInvokePayloadSizeWarning,Ro as maybeRunInvokeRunnerAutoBootstrap,gi as parseInvokeCliOptions,hn as postMaterializationJson,Mr as recordPendingEpicReservation,Jo as resolveInvokeCommandLevelWatch,nt as resolveInvokeProjectRoot,lo as resolveInvokeTransportErrorCode,oi as resolveInvokeWatchTarget,ot as sanitizeInvokeCliOutput,ii as sendEpicClaimAcknowledgement,vn as sendInvokeRequest,Fr as shouldCollectProjectEvidenceForInvoke,jo as watchContinuityProcessingSummaries,hi as writeInvokeCliSuccessOutput};
161
+ `.trim();function Ri(e){return e.includes("--help")||e.includes("-h")||e.includes("help")}function ne(e,t,r,n){return new Ke("INVOCATION_MALFORMED_INPUT",t,e,r,n)}function je(e){return ne("missing-input-value",`${e} requires a value. ${Dr}`)}function wi(e){try{if(!Fr(e).isFile())throw ne("missing-input-value","--args-file must point to a readable UTF-8 text file.","args-file");return xe(e)}catch(t){throw t instanceof Ke?t:ne("missing-input-value","--args-file could not be read as UTF-8 text. Check the path and permissions.","args-file")}}function vi(){try{if(process.stdin.isTTY)throw ne("missing-input-value","--stdin requires piped UTF-8 text, for example: neocortex-client invoke --stdin < synthetic.story.md","stdin");return xe(0)}catch(e){throw e instanceof Ke?e:ne("missing-input-value","--stdin could not be read as UTF-8 text. Pipe command text into stdin and retry.","stdin")}}function bi(e,t={}){let r,n=!1,o,i,a="plain",c=!1,l,p,g=!1,R=!1;for(let v=0;v<e.length;v++)switch(e[v]){case"--args":{const h=e[++v];if(h===void 0)throw je("--args");if(r!==void 0)throw ne("multiple-input-sources","Provide --args only once. Use one explicit invoke input source.","args");r=h;break}case"--stdin":if(n)throw ne("multiple-input-sources","Provide --stdin only once. Use one explicit invoke input source.","stdin");n=!0;break;case"--args-file":{const h=e[++v];if(h===void 0)throw je("--args-file");if(o!==void 0)throw ne("multiple-input-sources","Provide --args-file only once. Use one explicit invoke input source.","args-file");o=h;break}case"--project-root":{const h=e[++v];if(h===void 0)throw je("--project-root");i=h;break}case"--format":{const h=e[++v];if(h===void 0)throw je("--format");if(h!=="json"&&h!=="plain")throw ne("unexpected-cli-token","--format accepts only json or plain.");a=h;break}case"--watch":c=!0;break;case"--server-url":{const h=e[++v];if(h===void 0)throw je("--server-url");l=h;break}case"--platform-target":{const h=e[++v];if(h===void 0)throw je("--platform-target");p=h;break}case"--strict-read-only":g=!0;break;case"--private-execution-beta":R=!0;break;default:throw ne("unexpected-cli-token","Unexpected top-level CLI token. Quote the complete --args payload or use --stdin/--args-file for multiline content.")}const f=[r!==void 0?"args":void 0,n?"stdin":void 0,o!==void 0?"args-file":void 0].filter(v=>v!==void 0);if(f.length===0)throw ne("missing-input-value",Dr);if(f.length>1)throw ne("multiple-input-sources",`Choose only one invoke input source; received ${f.join(", ")}.`);const d=f[0],I=d==="args"?r:d==="stdin"?(t.readStdin??vi)():(t.readArgsFile??wi)(o);let A;try{A=Ge(d,I)}catch(v){throw v instanceof wn?ne("invalid-utf8",v.message,d):v}const C=d==="args"?ii(A.rawArgs):X(A.rawArgs),P=C.args===A.rawArgs?A:Ge(d,C.args);return{args:C.args,inputSource:d,inputEnvelope:P,projectRoot:i,format:a,watch:c||C.watch,commandLevelWatch:C.metadata,serverUrl:l,platformTarget:p,strictReadOnly:g,privateExecutionBeta:R}}function jr(e,t){return t?.active?{...e??{},commandLevelWatch:t,serverHeldStream:!1}:e}function Ti(e,t,r=process.stdout,n=process.stderr){if(t.format==="json"){const a=ft(e.instructions,e.metadata),c=jr(a.metadata,t.commandLevelWatch);if(t.watch){r.write(JSON.stringify({type:"invoke_result",instructions:a.instructions,metadata:c,publicSafe:!0})+`
162
+ `);return}r.write(JSON.stringify({instructions:a.instructions,metadata:c})+`
163
+ `);return}const o=ft(e.instructions,e.metadata),i=jr(o.metadata,t.commandLevelWatch);r.write(o.instructions+`
164
+ `),i&&n.write(JSON.stringify(i)+`
165
+ `)}function Oi(e){const t=()=>e.abort();return process.once("SIGINT",t),process.once("SIGTERM",t),()=>{process.removeListener("SIGINT",t),process.removeListener("SIGTERM",t)}}async function fs(e){if(Ri(e))return process.stdout.write(`${Ai}
166
+ `),0;let t;try{t=bi(e)}catch(n){if(n instanceof Ke)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})+`
167
+ `),1;throw n}if(dn(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."})+`
168
+ `),1):(await un({args:t.args,projectRoot:lt(t.projectRoot),format:t.format,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})).exitCode;const r=await Ci({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});if(!r.success){const n=r.metadata?.invocationInput,o=n&&typeof n=="object"&&!Array.isArray(n)?n:void 0;return process.stderr.write(JSON.stringify({error_code:r.errorCode??(r.exitCode===2?"NOT_CONFIGURED":"INVOKE_ERROR"),message:ie(r.error??"",ve),...typeof o?.reason=="string"?{reason:ie(o.reason,80)}:{},...typeof o?.source=="string"?{source:ie(o.source,20)}:{},...Number.isSafeInteger(o?.byteLength)?{byte_length:o.byteLength}:{},...typeof o?.remediation=="string"?{remediation:ie(o.remediation,ve)}:{}})+`
169
+ `),r.exitCode}if(Ti(r,t),t.watch){const n=new AbortController,o=Oi(n);try{const i=mi(r.metadata,t.args);i.disabled?Jo(i.reasonCodes??[Y.TARGET_UNRESOLVED],t.args,t.format,process.stdout,t.privateExecutionBeta):await zo({projectRoot:lt(t.projectRoot),format:t.format,strictReadOnly:t.strictReadOnly,protectedOutput:t.privateExecutionBeta,...i,signal:n.signal})}finally{o()}}return 0}export{Ai as INVOKE_HELP_TEXT,Xt as INVOKE_PAYLOAD_LIMIT_BYTES,dt as INVOKE_PAYLOAD_WARNING_THRESHOLD_BYTES,Ke as InvokeCliInputError,ht as InvokePayloadTooLargeError,gt as InvokeStructuralContextTooLargeError,Ee as StateSnapshotIntegrityError,us as __resetSchemaDriftWarnedForTests,Ei as acknowledgeMaterializedPendingEpicClaims,Xn as admitClientInvocation,hr as assertEpicAwareStateShapeBeforeRepair,vo as buildSignedInvokeAttempt,zn as clearPendingEpicIdempotencyKey,Io as collectInvokeP205Authorities,gr as collectStateSnapshot,Pe as computeInvokeRequestBodySizeBytes,ls as createFullStateSnapshotScope,yt as createInvokePayloadTelemetry,so as detectStateSchemaDrift,Si as extractPreFlightTrigger,Jn as getOrCreatePendingEpicIdempotencyKey,Ar as guardInvokeRequestBodySize,Ci as invoke,fs as invokeCliHandler,fr as isEpicAwareCommandId,Do as maybeEmitInvokePayloadSizeWarning,jo as maybeRunInvokeRunnerAutoBootstrap,bi as parseInvokeCliOptions,Cr as postMaterializationJson,qn as recordPendingEpicReservation,ii as resolveInvokeCommandLevelWatch,lt as resolveInvokeProjectRoot,Ao as resolveInvokeTransportErrorCode,mi as resolveInvokeWatchTarget,ft as sanitizeInvokeCliOutput,Ii as sendEpicClaimAcknowledgement,Pr as sendInvokeRequest,ps as sendPrivateExecutionCancelRequest,yi as sendPrivateExecutionConsumeRequest,ro as shouldCollectProjectEvidenceForInvoke,zo as watchContinuityProcessingSummaries,Ti as writeInvokeCliSuccessOutput};