@ornexus/neocortex 4.60.56 → 4.60.58

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.
@@ -1,56 +1,56 @@
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(`
1
+ import{createHash as Ne,randomUUID as dt}from"node:crypto";import{execFileSync as Le}from"node:child_process";import{existsSync as Pe,readFileSync as Te,renameSync as qr,unlinkSync as Kr,writeFileSync as Lt,mkdirSync as ze,statSync as Xr}from"node:fs";import{join as ne}from"node:path";import{homedir as De}from"node:os";import{isPrivateExecutionPublicEnvelope as Zr}from"../private-execution/delivery.js";import{LicenseClient as Qr}from"../license/license-client.js";import{EncryptedCache as ut}from"../cache/encrypted-cache.js";import{NoOpCache as Pt}from"../types/index.js";import{resolveClientPreFlightTrigger as Dt,TierAwareClient as en}from"../tier/tier-aware-client.js";import{COMMAND_REGISTRY_CHECKSUM as Oe,COMMAND_REGISTRY_VERSION as xe,GENERATED_CLIENT_COMMANDS as tn}from"../generated/command-registry.generated.js";import{loadSecureConfig as jt}from"../config/secure-config.js";import{DEFAULT_SERVER_URL as rn}from"../constants.js";import{detectFirstRunLocale as nn,renderFirstRunMessage as on}from"../i18n/first-run.js";import{humanizeError as Mt,formatHumanizedError as Ut,detectErrorLocale as Vt}from"../errors/error-messages.js";import{degradeStateSnapshotForPayloadLimit as sn,projectStateSnapshotForInvoke as Bt,projectStateSnapshotResultV2ForInvoke as an}from"../state/project-state-snapshot.js";import{isInlineYoloMaterialization as cn,maybeRepairStateJsonBeforeInvoke as dn,StateRepairHardStopError as un}from"../state/state-json-repair.js";import{StructuralDagError as $t}from"../state/structural-dag-projection.js";import{RUNNER_BOOTSTRAP_POLICY_REASON_CODES as ln,classifyRunnerBootstrapPolicyFromArgs as pn}from"../continuity/runner-bootstrap-policy.js";import{RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES as fn,ensureRunnerSchedulerBootstrap as hn}from"../runner/scheduler.js";import{CONTINUITY_INVOKE_WATCH_DEFAULT_LIMIT as Wt,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_IDLE_POLLS as Ht,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_POLLS as Ft,CONTINUITY_INVOKE_WATCH_DEFAULT_POLL_INTERVAL_MS as Gt,openContinuityClientStateStore as gn}from"../continuity/continuity-client-state-store.js";import{isLocalJobsConsoleArgs as mn,runLocalJobsConsoleCommand as yn}from"../runner/local-console.js";import{detectNativeHostAttestation as In,detectPlatform as En}from"../adapters/platform-detector.js";import{signNxInvokeRequest as _n}from"../../../shared/dist/nx-invoke-signature.js";import{CLIENT_VERSION as je}from"../version.js";import{createCapabilityCache as Yt,executeInvokeQueryTransport as Jt,executeSecondaryNetworkMutation as Cn}from"../effects/invoke-effect-gateways.js";import{STRICT_READ_ONLY_POLICY as Sn,STRICT_READ_ONLY_CLIENT_PROJECTION as zt,STRICT_READ_ONLY_SERVER_PROJECTION as An,StrictReadOnlyError as Me,canonicalizeInvokeEffects as wn,createInvokeEffectContext as Rn,verifyStrictReadOnlyReceipt as vn}from"../../../shared/dist/strict-readonly.js";import{admitInvocation as bn,assertInvokeInputEnvelopeV2 as Tn,assertProjectIdentityMigrationReceiptV1 as On,buildProjectIdentityPublicDiagnostic as Ue,createInvocationAdmissionReceipt as xn,projectInvokeInputEvidenceV1 as qt,verifyStrictDiagnoseReceiptV1 as kn}from"../../../shared/dist/invocation/index.js";import{buildInvokeInputEnvelope as qe,InvokeInputDecodeError as Nn}from"../invocation/invoke-input.js";import{acknowledgeProjectIdentityMigration as Ln,finalizeProjectIdentityMigration as Pn,prepareProjectIdentityMigration as Dn,ProjectIdentityMigrationError as lt,readProjectIdentityMigrationPhase as jn}from"../migrations/project-identity.js";import{probeProjectIdentityMigrationCapability as Mn}from"../migrations/project-identity-capability.js";import{normalizeYoloopStoryPlanningEvidence as Un}from"../../../shared/dist/yoloop/planning-graph.js";import{normalizeContinuousWriteRef as Ke}from"../../../shared/dist/yoloop/wave-decision-receipt.js";import{applyGitLifecycleRuntimeOverlay as Kt,classifyGitLifecycleStoryCheckpointProjectionSync as Vn,ensureGitLifecycleRuntimeInitialized as Bn,executeP205TransientAuthorities as $n,persistGitLifecycleGraphAuthority as Wn,P205_COMPLETE_COMMAND as Hn,gitLifecycleStoryWriteSet as Xt,readGitLifecycleRuntimeSync as Xe,verifyLegacyCheckpointMigrationCandidateSync as Fn}from"../git/git-lifecycle-store.js";const Ze=ne(De(),".neocortex"),pt=ne(Ze,"cache"),Zt=ne(pt,"menu-cache.json"),Qt=1440*60*1e3,er=3e4,tr=256*1024,rr=tr,nr=.8,Ce="[REDACTED]",Gn=1e5,ke=2e3,Yn=200,Jn=200,zn=12,qn=/(?:promptBody|workflow|workflowGraph|stepBody|privateUrl|rawLog|secret|credential|licenseKey|apiKey|internalRouting|serverOnly|proprietary|protected)/i,Kn=/(?:PRIVATE|PROTECTED|SERVER_ONLY)[-_\s]*(?:PROMPT|PROMPT_BODY|WORKFLOW|WORKFLOW_GRAPH|STEP_BODY|STEP|ROUTING)\s*[:=][^\n\r]*/gi,Xn=/(?: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,ft=Math.floor(tr*nr),or=ne(Ze,".first-run-shown"),Zn="pending-epic-claims.json",ir=64;function sr(e){return ne(e,".neocortex",Zn)}function Qe(e){const t=sr(e);if(!Pe(t))return{schemaVersion:1,operations:{}};const r=JSON.parse(Te(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>ir)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 ht(e,t){const r=sr(e);ze(ne(e,".neocortex"),{recursive:!0,mode:448});const n=`${r}.${process.pid}.${dt()}.tmp`;Lt(n,`${JSON.stringify(t)}
2
+ `,{encoding:"utf8",mode:384,flag:"wx"}),qr(n,r)}function Qn(e){return Ne("sha256").update(`nx-epic-logical-operation-v1\0${JSON.stringify({command:"create-epic",args:e})}`,"utf8").digest("hex")}function eo(e,t){const r=Qn(t),n=Qe(e),o=n.operations[r];if(o)return{key:o.idempotencyKey,fingerprint:r};if(Object.keys(n.operations).length>=ir)throw new Error("EPIC_CLAIM_CAPACITY_EXCEEDED");const i=dt(),a={...n.operations,[r]:{idempotencyKey:i,createdAt:new Date().toISOString()}};return ht(e,{schemaVersion:1,operations:a}),{key:i,fingerprint:r}}function to(e,t){const r=Qe(e);if(!r.operations[t])return;const n={...r.operations};delete n[t],ht(e,{schemaVersion:1,operations:n})}function ar(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");if(i.claimId!==void 0&&(i.claimId!==r||i.epicId!==n))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");ht(e,{schemaVersion:1,operations:{...o.operations,[t]:{...i,claimId:r,epicId:n}}})}function ro(){try{if(Pe(or))return;const e=nn(),t=on(e);process.stderr.write(t);try{ze(Ze,{recursive:!0}),Lt(or,new Date().toISOString(),"utf-8")}catch{}}catch{}}function gt(e,t=process.cwd()){return e&&e.trim().length>0?e:t}function no(e){return bn(e,{registryVersion:xe,registryChecksum:Oe})}const oo=new Set(["completed","aborted","cancelled"]),io=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"}),X=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"}),x=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"}),cr=240,so=/(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 ao(e){return e.replace(/[\w.+-]+@[\w-]+\.[\w.-]+/g,Ce).replace(/(?:sk|pk|whsec|nxk)[-_](?:test|live|ant|proj|pro|free|enterprise)?[-_]?[A-Za-z0-9_-]{16,}/g,Ce).replace(/NX-[FPE]-[a-f0-9]{24}-[a-f0-9]{4}/g,Ce).replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,Ce).replace(Kn,Ce).replace(Xn,Ce)}function de(e,t){const r=ao(e);return r.length<=t?r:`${r.slice(0,t)}\u2026[TRUNCATED:${r.length-t}]`}function mt(e,t=0,r=new WeakSet){if(t>zn)return"[MAX_DEPTH]";if(e==null)return e;if(typeof e=="string")return de(e,ke);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,Yn).map(o=>mt(o,t+1,r));const n={};for(const[o,i]of Object.entries(e).slice(0,Jn)){if(qn.test(o)){n[o]=Ce;continue}const a=mt(i,t+1,r);a!==void 0&&(n[o]=a)}return n}finally{r.delete(e)}}}function yt(e,t){return{instructions:de(e??"",Gn),metadata:t?mt(t):void 0}}class et 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 co(e){return/^\s*\*?(?:arch-plan|ui-ux-review)(?:\s|$)/i.test(e)&&uo(e,"--project-evidence")}function uo(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 lo=/(?:^|\s)codex(?:-cli)?\s+([A-Za-z0-9][A-Za-z0-9._+-]{0,63})(?:\s|$)/i;function po(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 Le("codex",["--version"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim().match(lo)?.[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 Et 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 _t=!1;function fo(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 ho(e){if(!(_t||e.length===0)){_t=!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 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)}
7
+ `)}catch{}}}function ms(){_t=!1}function dr(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function go(e){return e==="active"||e==="archived"||e==="rolled-back"||e==="synthetic"||e==="orphan"?e:void 0}function ur(e){return e==="create-epic"||e==="discovered"?e:void 0}function oe(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function mo(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=>Ke(i)===void 0)){r=!0;continue}t[n]=o.map(i=>Ke(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)||Ke(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)||Ke(c.ref)===void 0)))throw new Error("planning-attempt-claims")}const{graphRevision:o,...i}=Un(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 Se(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 M(e){if(typeof e!="string")return;const t=e.trim(),r=B(e);return r===t?r:void 0}function q(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 ie(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 Ae(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 tt(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 rt(e){return e==="epic"||e==="story"?e:void 0}function lr(e){if(!y(e)||e.schemaVersion!==1)return;const t=M(e.ownerStoryId),r=M(e.sessionId),n=M(e.idempotencyKey),o=ie(e.acquiredAt),i=ie(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 pr(e){if(!y(e)||e.schemaVersion!==1)return;const t=M(e.storyId),r=M(e.epicId),n=q(e.branch),o=S(e.baseSha),i=S(e.headSha),a=M(e.idempotencyKey),c=ie(e.recordedAt),l=oe(e.commits).map(S).filter(j=>!!j).slice(0,256),p=oe(e.receiptRefs).map(Ae).filter(j=>!!j).slice(0,256),m=e.dispatchId===void 0?void 0:M(e.dispatchId),w=e.bundleId===void 0?void 0:M(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:M(e.claimRevision),A=yo(e.qaReceipt),C=Io(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&&!m||e.bundleId!==void 0&&!w||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||!gr(A,{storyId:t,epicId:r,baseSha:o,headSha:i,bundleDigest:f,graphRevision:d})||C&&(!gr(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,...m?{dispatchId:m}:{},...w?{bundleId:w}:{},...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 yo(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=M(e.storyId),r=M(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.checkedAt),p=Ae(e.receiptRef),m=e.evidenceVersion==="p205-execution-v2"&&e.contract==="P205-CI-02"?e.contract:void 0,w=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"?oe(e.gateIds).map(M).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"&&(!m||w!=="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:m,command:w,manifestDigest:f,gateIds:I,resultDigest:d}:{},baseSha:n,headSha:o,bundleDigest:i,graphRevision:a,sourceEvidenceDigest:c,verdict:e.verdict,checkedAt:l,receiptRef:p}}function fr(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=M(e.storyId),r=M(e.epicId),n=q(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,m=S(e.effectiveClaimRevision),w=e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,f=S(e.manifestDigest),d=oe(e.gateIds).map(M).filter(h=>!!h).slice(0,64),I=S(e.resultDigest),A=S(e.graphRevision),C=S(e.executionEvidenceDigest),j=S(e.sourceEvidenceDigest),v=ie(e.verifiedAt),U=oe(e.reasonCodes).map(M).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||!m||m.length!==64||!w||!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||!j||j.length!==64||!v||U.length===0||e.verdict==="verified"&&(d.length===0||!U.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:m,command:w,manifestDigest:f,gateIds:d,resultDigest:I,graphRevision:A,executionEvidenceDigest:C,sourceEvidenceDigest:j,verifiedAt:v,verdict:e.verdict,reasonCodes:U,publicSafe:!0}}function hr(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=M(e.storyId),n=M(e.epicId),o=q(e.branch),i=S(e.baseSha),a=S(e.headSha),c=S(e.graphRevision),l=S(e.effectiveClaimRevision),p=S(e.sourceEvidenceDigest),m=ie(e.verifiedAt),w=oe(e.reasonCodes).map(M).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||!m||!Array.isArray(e.reasonCodes)||w.length!==1||w[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:m,reasonCodes:w,integrationAuthorized:!1,publicSafe:!0}}function Io(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=M(e.storyId),r=M(e.epicId),n=S(e.baseSha),o=S(e.headSha),i=S(e.bundleDigest),a=S(e.graphRevision),c=S(e.sourceEvidenceDigest),l=Ae(e.qaReceiptRef),p=ie(e.reviewedAt),m=Ae(e.receiptRef);if(!(!t||!r||!n||!o||!i||i.length!==64||!a||a.length!==64||!c||c.length!==64||!l||!p||!m))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:m}}function gr(e,t){return["storyId","epicId","baseSha","headSha","bundleDigest","graphRevision"].every(r=>e[r]===t[r])}function mr(e){if(!y(e)||e.schemaVersion!==1||e.capturedFromCurrentCheckout!==!0)return;const t=q(e.originBranch),r=S(e.originHeadSha),n=q(e.executionBranch),o=ie(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 yr(e){if(!y(e)||e.schemaVersion!==1||e.verdict!=="passed")return;const t=S(e.executionHeadSha),r=S(e.graphRevision),n=ie(e.checkedAt),o=Ae(e.receiptRef),i=oe(e.gateIds).map(M).filter(m=>!!m).slice(0,128),a=e.evidenceVersion==="p205-execution-v2"&&e.producer==="local-yolo-tdd"&&e.contract==="P205-CI-02"&&e.command==="node scripts/test-root.mjs --gate complete",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 nt(e){if(!y(e)||e.schemaVersion!==1)return;const t=tt(e,["schemaVersion","kind","storyId","epicId","baseSha","headSha","originalBaseSha","originalHeadSha","gitPullRequest","preservesLaterCommits","historyRewrite","recordedAt"])??{},r=oe(e.receiptRefs).map(Ae).filter(o=>!!o).slice(0,256),n=oe(e.revertCommits).map(B).filter(o=>!!o).slice(0,256);return{...t,...r.length?{receiptRefs:r}:{},...n.length?{revertCommits:n}:{}}}function Ir(e){if(!y(e)||e.schemaVersion!==1||e.publicSafe!==!0)return;const t=M(e.epicId),r=q(e.executionBranch),n=q(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=M(e.idempotencyKey),p=ie(e.attemptStartedAt),m=e.completedAt===void 0?void 0:ie(e.completedAt),w=oe(e.localGateReceiptRefs).map(Ae).filter(A=>!!A).slice(0,256),f=oe(e.reasonCodes).map(M).filter(A=>!!A).slice(0,64),d=_o(e.candidateQa),I=Eo(e.providerGuard);if(!(!t||!r||!n||!o||!i||!l||!p||w.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,...Se(e.prNumber)?{prNumber:Se(e.prNumber)}:{},physicalStatus:e.physicalStatus,localGateReceiptRefs:w,idempotencyKey:l,attemptStartedAt:p,...d?{candidateQa:d}:{},...I?{providerGuard:I}:{},...m?{completedAt:m}:{},retryEligible:e.retryEligible,reasonCodes:f,publicSafe:!0}}function Eo(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=ie(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 _o(e){if(!y(e)||e.schemaVersion!==1||e.kind!=="epic_merge_candidate_qa"||e.contract!=="P205-CI-02"||e.command!==Hn)return;const r=Object.fromEntries(["originHeadSha","executionHeadSha","mergeSha","treeSha","graphRevision","manifestDigest","resultDigest"].map(a=>[a,S(e[a])])),n=ie(e.checkedAt),o=Ae(e.receiptRef),i=oe(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 Co(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 So(e){const t=tt(e.completionEvidence??e.completion_evidence,["prNumber","pr_number","prState","pr_state","pullRequestState","merged","mergedAt","issueNumber","issue_number","issueState","issue_state","closedAt"]),r=tt(e.issueCloseAudit??e.issue_close_audit,["schema_version","event","storyId","epicId","issueNumber","closedAt","publicSafe","rawLogStorage"]),n=tt(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)}:{},...Se(e.issue_number??e.issueNumber)?{issue_number:Se(e.issue_number??e.issueNumber)}:{},...t?{completionEvidence:t}:{},...r?{issueCloseAudit:r}:{},...n?{scopedCiEvidence:n}:{}}}class we extends Error{reasonCode;constructor(t){super(t),this.name="StateSnapshotIntegrityError",this.reasonCode=t}}const Ao=new Set(["yolo","yoloop","finalize-epic","audit"]);function Er(e){return typeof e=="string"&&Ao.has(e)}function _r(e,t={}){const r=ne(e,".neocortex","state.json");if(!Pe(r))throw new we("git-lifecycle-state-missing");let n;try{n=JSON.parse(Te(r,"utf8"))}catch{throw new we("git-lifecycle-state-corrupt")}if(!y(n)||!y(n.epics)||!y(n.stories))throw new we("git-lifecycle-state-shape-invalid");const o=Object.values(n.epics).some(i=>y(i)&&(i.branch_mode==="epic"||q(i.execution_branch)!==void 0));if(o)try{Xe(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 we(a)}return{lifecycleDeclared:o,runtimeMissing:!1}}function Cr(e,t={}){const r=ne(e,".neocortex","state.json");if(!Pe(r)){if(t.epicAware&&!t.projectless)throw new we("git-lifecycle-state-missing");return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}let n;try{const f=Te(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"||q(h.execution_branch)!==void 0)),C=Xe(e,{required:!!(t.epicAware&&A&&!t.projectless)});n=Kt(d,C);const j=y(n.stories)?n.stories:{},v=y(n.epics)?n.epics:{},U=y(d.stories)?d.stories:{};for(const[h,R]of Object.entries(j)){const E=y(R)?R:void 0;if(!E?.checkpoint)continue;const V=typeof E.epic_id=="string"?E.epic_id:h.split(".")[0],N=y(v[V])?v[V]:void 0,P=q(N?.execution_branch);if(!P)continue;const $=Vn(e,E.checkpoint,h,V,P,t.p205Authorities?.[h],Xt(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 D=y(U[h])?U[h]:void 0;if(delete E.checkpoint,C.stories[h]?.checkpoint!==void 0)for(const O of["status","last_step","steps_completed"])D&&Object.prototype.hasOwnProperty.call(D,O)?E[O]=structuredClone(D[O]):delete E[O];["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 we(d)}return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}try{const f=fo(n);f.length>0&&ho(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",...ur(d.source)?{source:ur(d.source)}:{},steps_completed:d.steps_completed??[],last_step:d.last_step??null,branch_name:d.branch_name??null,pr_number:d.pr_number,...rt(d.branch_mode)?{branch_mode:rt(d.branch_mode)}:{},...pr(d.checkpoint)?{checkpoint:pr(d.checkpoint)}:{},...fr(d.checkpoint_verification)?{checkpoint_verification:fr(d.checkpoint_verification)}:{},...hr(d.scheduling_checkpoint_evidence)?{scheduling_checkpoint_evidence:hr(d.scheduling_checkpoint_evidence)}:{},...nt(d.review_request)?{review_request:nt(d.review_request)}:{},...nt(d.rollback_receipt)?{rollback_receipt:nt(d.rollback_receipt)}:{},...Se(d.workflow_issue)?{workflow_issue:Se(d.workflow_issue)}:{},...So(d),depends_on:dr(d.depends_on),files_to_modify:oe(d.files_to_modify),...mo(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=go(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:dr(d.depends_on),...rt(d.branch_mode)?{branch_mode:rt(d.branch_mode)}:{},...q(d.execution_branch)?{execution_branch:q(d.execution_branch)}:{},...q(d.origin_branch)?{origin_branch:q(d.origin_branch)}:{},...lr(d.branch_lease)?{branch_lease:lr(d.branch_lease)}:{},...mr(d.origin_binding)?{origin_binding:mr(d.origin_binding)}:{},...yr(d.aggregate_qa_receipt)?{aggregate_qa_receipt:yr(d.aggregate_qa_receipt)}:{},...Se(d.pr_number)?{pr_number:Se(d.pr_number)}:{},...B(d.physicalMergeStatus)?{physicalMergeStatus:B(d.physicalMergeStatus)}:{},...S(d.graph_revision)?{graph_revision:S(d.graph_revision)}:{},...Ir(d.terminal_git_receipt)?{terminal_git_receipt:Ir(d.terminal_git_receipt)}:{},...I?{lifecycle_classification:I}:{}}}const p=Co(n.current_session??n.currentSession),m=n.epic_id_ledger,w=Array.isArray(m?.reserved_ids)?[...new Set(m.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,...w.length>0?{epic_id_ledger:{schema_version:1,reserved_ids:w}}:{},...p?{current_session:p}:{}}}async function wo(e,t,r){if(!Er(r))return{};if(cn(t,r))return{};try{const n=JSON.parse(Te(ne(e,".neocortex","state.json"),"utf8")),o=Xe(e,{required:!0}),i=Kt(n,o),a=y(i.stories)?i.stories:{},c=y(i.epics)?i.epics:{},l=Le("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8"}).trim(),p=Le("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8"}).trim(),m=Le("git",["rev-list","--first-parent","--reverse",l],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
8
+ `).filter(Boolean),w=new Map(m.map((h,R)=>[h,R])),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,R])=>{if(f&&h!==f)return[];const E=y(R)?R:void 0,V=y(E?.checkpoint)?E.checkpoint:void 0;if(!V)return[];const N=typeof E?.epic_id=="string"?E.epic_id:h.split(".")[0];if(d&&N!==d)return[];const P=S(V?.headSha);if(!P||P.length<40||w.get(P)===void 0)return I.add(N),[];const $=y(c[N])?c[N]:void 0;if($?.branch_mode!=="epic"||q($.execution_branch)!==p||q(V.branch)!==p)return I.add(N),[];const D=S(V.graphRevision);if(!D||D.length!==64)return I.add(N),[];const O=S(V.claimRevision),J=[...Xt(h,E,V)].sort(),ve=Fn(e,V,h,N,p,J);if(!ve&&O){if(J.length===0)return I.add(N),[];const _e=Le("git",["diff-tree","--no-commit-id","--name-only","-r","-z",P],{cwd:e,encoding:"utf8"}).split("\0").filter(Boolean);if(_e.length===0||_e.some(be=>!J.some(W=>W===be||W.endsWith("/")&&be.startsWith(W))))return I.add(N),[];const ge=Ne("sha256").update(J.join("\0")).digest("hex"),Ge=Ne("sha256").update(JSON.stringify(J)).digest("hex");if(O!==ge&&O!==Ge)return I.add(N),[]}else if(!ve)return I.add(N),[];return D?.length===64?[{storyId:h,epicId:N,graphRevision:D,checkpointHead:P,position:w.get(P)}]:[]}),C=new Set(I);for(const[h,R]of Object.entries(c)){const E=y(R)?R:void 0,V=Array.isArray(E?.stories)?E.stories.filter(D=>typeof D=="string"):Object.keys(a).filter(D=>D.startsWith(`${h}.`)),N=A.filter(D=>D.epicId===h),P=V.filter(D=>N.some(O=>O.storyId===D)),$=[...N].sort((D,O)=>D.position-O.position).map(D=>D.storyId);(JSON.stringify(P)!==JSON.stringify($)||new Set($).size!==$.length)&&C.add(h)}const j={},v=[...new Set(A.filter(h=>!C.has(h.epicId)).map(h=>h.graphRevision))],U=v.length>0?await $n(e,{headSha:l,graphRevisions:v}):new Map;for(const h of A){if(C.has(h.epicId))continue;const R=U.get(h.graphRevision);if(!R)throw new Error("p205-transient-authority-missing");j[h.storyId]=R}return j}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 ys(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 Sr="neocortex:menu:cache";async function Ro(e){try{const t=await e.get(Sr);if(!t)return null;const r=JSON.parse(t);return r.version!==je||Date.now()-r.cachedAt>Qt?null:r}catch{return null}}async function vo(e,t,r){try{const n={instructions:t,metadata:r,cachedAt:Date.now(),version:je};await e.set(Sr,JSON.stringify(n),Qt),bo()}catch{}}function bo(){try{Pe(Zt)&&Kr(Zt)}catch{}}function To(e){return e.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>jt(),()=>jt({strictReadOnly:!0}))}async function Ar(e,t,r){const n=r.mode==="strict";try{let o;if(n&&t)o=new ut({cacheDir:pt,passphrase:t,strictReadOnly:!0});else if(n)o=new Pt;else if(t){const m=ne(Ze,"cache");o=new ut({cacheDir:m,passphrase:t})}else process.stderr.write(`[neocortex] Warning: No license key in config. Run "neocortex activate" to re-authenticate.
10
+ `),o=new Pt;const i=Yt(r,o,"auth-cache"),a=Yt(r,o,"tier-cache"),c=new Qr({serverUrl:e,licenseKey:t??"",cacheProvider:i,strictReadOnly:n});let l;if(n){const m=await c.inspectToken();if(m.status!=="authenticated")return m;l=m.token}else l=await c.getToken();if(!l)return{status:"not-configured"};const p=new en({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 wr=!1;function Oo(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 Rr=3,ot=50;function xo(e){return new Promise(t=>setTimeout(t,e))}function ko(e,t,r){return e.status>=500&&e.status<=599?!0:r&&e.status===409&&t.error_code==="SIGNATURE_REPLAYED"}async function We(e,t,r,n,o={}){const i=Math.max(1,Math.min(o.maxAttempts??Rr,Rr)),a=o.sleep??xo;let c=n,l=!1,p=!1,m=0;for(let w=1;w<=i;w+=1){const f=Math.max(Math.floor(Date.now()/1e3),m+1);m=f;const d=No(t,r,c,{nowSeconds:f}),I=new AbortController,A=setTimeout(()=>I.abort(),er);try{const C=await fetch(`${e}${t}`,{method:"POST",headers:d.headers,body:d.body,signal:I.signal}),j=await C.text().catch(()=>""),v=(()=>{try{return j?JSON.parse(j):{}}catch{return{}}})();if(C.status===401&&!l&&o.refreshToken&&(v.fallback_action==="refresh_token"||v.fallback_action==="re_authenticate")){l=!0;const U=await o.refreshToken();if(U&&w<i){c=U,o.onTokenChanged?.(U),await a(ot*w);continue}}if(C.status===401&&v.error_code==="SIGNATURE_EXPIRED"&&!p&&w<i){p=!0,await a(ot*w);continue}if(w<i&&ko(C,v,o.allowReplayRetry===!0)){await a(ot*w);continue}return{response:C,text:j,parsed:v,networkFailure:!1}}catch{if(w<i){await a(ot*w);continue}return{text:"",parsed:{},networkFailure:!0}}finally{clearTimeout(A)}}return{text:"",parsed:{},networkFailure:!0}}function No(e,t,r,n={}){const o=Buffer.from(JSON.stringify(t),"utf8"),i=_n({method:"POST",target:e,body:o,bearerToken:r,clientVersion:je,nowSeconds:n.nowSeconds,nonceBytes:n.nonceBytes});return{body:i.body,headers:{...i.headers,Authorization:`Bearer ${r}`}}}function vr(e){return Ne("sha256").update(e).digest("hex")}function Lo(){const e=Number(process.env.NEOCORTEX_INVOKE_CHUNK_BYTES??"49152");return Number.isFinite(e)&&e>=1024&&e<=98304?Math.floor(e):49152}function Po(e,t,r){return`args-${Ne("sha256").update("invoke-materialization:v1").update(e).update(String(t)).update(JSON.stringify(r)).digest("hex")}`}async function br(e,t,r,n,o={}){const i=await We(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 Do(e,t,r,n){const o=Buffer.from(t,"utf8"),i=Lo(),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:vr(C),byteLength:C.byteLength})}const c=vr(o),l=Po(c,o.byteLength,a),p=Number(process.env.NEOCORTEX_INVOKE_CHUNK_TTL_SECONDS??"900");let m=r;const w={refreshToken:n,onTokenChanged(I){m=I}};for(const I of a){const A=I.index*i,C=o.subarray(A,A+I.byteLength);await br(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}`},m,w)}const d=(await br(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}},m,w)).argsRef;if(!d?.manifestId)throw new Error("MATERIALIZATION_RESPONSE_INVALID: missing argsRef");return{argsRef:d,chunks:a}}function Ve(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function jo(...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 Mo(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 Ct(e,t=Ve(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??rr,warningThresholdBytes:n.warningThresholdBytes??ft,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:Mo(e.stateSnapshot),reasonCodes:jo(r,o?.reasonCodes),publicSafe:!0}}function Uo(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 Vo(e){return y(e)?{stableId:B(e.stableId)??"unknown",...y(e.source)?{source:e.source}:{},reasonCode:"budget_exceeded"}:{stableId:"unknown",reasonCode:"budget_exceeded"}}function Tr(e){const t=Array.isArray(e)?e.filter(r=>typeof r=="string"):[];return t.includes("budget_exceeded")?t:[...t,"budget_exceeded"]}function Bo(e){const t=e.graphRetrieval;if(!y(t)||!Array.isArray(t.items))return e;const r=Uo(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,Vo(a)].slice(-32),i={...t,items:n,skipped:o,warnings:Tr(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:Tr(t.warnings)}),i===t?e:{...e,graphRetrieval:i}}function Or(e,t={}){const r=t.limitBytes??rr,n=t.warningThresholdBytes??Math.floor(r*nr),o=Ve(e);if(o<r)return{body:e,degraded:!1,telemetry:Ct(e,o,["payload-within-limit"],{limitBytes:r,warningThresholdBytes:n})};let i={...e,stateSnapshot:sn(e.stateSnapshot)},a=["payload-size-guardrail","state-degraded"],c=Ve(i);c>=r&&(i={...i,stateSnapshot:Bo(i.stateSnapshot)},a=[...a,"graph-retrieval-budget-enforced"],c=Ve(i));const l=Ct(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 Et(l):new It(l)}return{body:i,degraded:!0,telemetry:l}}function xr(e){const t=e.stateSnapshot.scope?.commandId??"resolved-command";return e.args!==void 0?t:`${t}:argsRef`}function $o(e){const t=Ve(e);if(t<ft)return t;const r=Ct(e,t,["payload-warning-threshold"]);return process.stderr.write(`[Neocortex] invoke payload near server limit: trigger=${xr(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 kr(e,t){process.stderr.write(`[Neocortex] invoke payload guardrail: trigger=${xr(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 Wo(e){const t=pn(e.args,{platformTarget:e.platformTarget,environment:e.environment??process.env});if(t.action==="skipped")return{shouldContinue:!0,attachToRequest:Ho(t),metadata:Nr(t)};const r=e.bootstrapper??hn;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:[fn.UNEXPECTED_ERROR],publicSummary:"runner scheduler bootstrap stopped unexpectedly.",publicSafe:!0}}const o=Nr(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 Ho(e){return!e.reasonCodes.includes(ln.SKIPPED_NON_CONTINUITY_COMMAND)}function Nr(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:re([...e.reasonCodes,...t?.reasonCodes??[]]),publicSummary:t?.publicSummary??e.publicSummary,publicSafe:!0}}function re(e){return Array.from(new Set(e.map(t=>t.slice(0,120))))}function it(e,t,r){const n=Math.floor(e??t);return Number.isFinite(n)?Math.max(1,Math.min(r,n)):t}function st(e,t){const r=process.env[e];if(!r)return t;const n=Number(r);return Number.isFinite(n)?n:t}function k(e,t=cr){const r=typeof e=="string"&&e.trim().length>0?e.trim():"unknown",n=de(r,t),o=so.test(n)?Ce:n;return o.length<=t?o:`${o.slice(0,t)}\u2026[TRUNCATED:${o.length-t}]`}function St(e,t=cr){if(!(typeof e!="string"||e.trim().length===0))return k(e,t)}function At(e,t,r,n){const o=St(e?.targetId??t,120),i=e?.selectorKind??(o?Rt(o):void 0),a=(e?.relatedJobIds??[]).map(c=>St(c,120)).filter(c=>!!c);return{schemaVersion:1,contractVersion:"continuity-v1",targetResolutionState:r,...i?{targetKind:i}:{},...o?{targetId:o}:{},...t?{targetJobId:k(t,120)}:{},...e?.jobId?{jobId:k(e.jobId,120)}:{},...e?.goalId?{goalId:k(e.goalId,120)}:{},...e?.loopId?{loopId:k(e.loopId,120)}:{},...a.length>0?{relatedJobIds:a}:{},relatedJobCount:a.length,reasonCodes:re(n.length>0?n:[x.OK]),publicSafe:!0}}function Ie(e,t,r,n,o=[]){const i=(e?.redactions?.length??0)>0,a=e?i?"unsafe":r&&n===0?"empty":"available":"unavailable",c=St(t[t.length-1]?.eventId,120),l=o.length>0?o:a==="unavailable"?[x.WATCH_SNAPSHOT_UNAVAILABLE]:a==="empty"?[x.WATCH_NO_SUMMARIES_YET]:[x.OK];return{schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:a,...e?.generatedAt?{generatedAt:k(e.generatedAt,80)}:{},renderedSummaryCount:n,...c?{latestEventId:c}:{},reasonCodes:re(l),publicSafe:!0}}function pe(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"),m=o.length>0?o:p==="advanced"?[x.WATCH_CURSOR_ADVANCED]:p==="unavailable"?[x.WATCH_EVIDENCE_UNAVAILABLE]:[x.WATCH_CURSOR_UNCHANGED];return{schemaVersion:1,contractVersion:"continuity-v1",cursorState:p,...e?{initialCursor:k(e,200)}:{},...t?{currentCursor:k(t,200)}:{},...c?{nextCursor:k(c,200)}:{},cursorAdvanced:l,...a?.eventId?{eventId:k(a.eventId,120)}:{},reasonCodes:re(m),publicSafe:!0}}function fe(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:re([...e.reasonCodes??[],...t?.reasonCodes??[],...e.snapshotEvidence?.reasonCodes??[],...e.cursorEvidence?.reasonCodes??[]]),generatedAt:k(e.generatedAt??new Date().toISOString(),80),publicSafe:!0}}function Fo(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=${k(i,200)}`,`next=${k(a,200)}`,`advanced=${e.cursorEvidence?.cursorAdvanced??!1}`,`stop=${e.stopReason??"not_stopped"}`,`reasons=${e.reasonCodes.join(",")}`].join(" ")}function he(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
13
  `:`[watch-status] status=${o.watchStatus} active=${o.active} summaries=${o.renderedSummaryCount} stop=${o.stopReason}
14
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})}
15
+ `);return}r.write(Fo(e)+`
16
+ `)}function Go(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 Ee(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:Go(n,t,r),publicSafe:!0}}function Yo(e){const t=e.reasonCode?` reason=${k(e.reasonCode,80)}`:"",r=e.goalId?` goal=${k(e.goalId,100)}`:"",n=e.loopId?` loop=${k(e.loopId,100)}`:"";return`[watch] ${k(e.createdAt,80)} event=${k(e.eventId,120)} job=${k(e.jobId,100)}${r}${n} execution=${k(e.executionId,120)}${t} -- ${k(e.publicSummary)}`}function Jo(e){return{type:"processing_summary",source:"local_continuity_sqlite",eventId:k(e.eventId,120),jobId:k(e.jobId,100),...e.goalId?{goalId:k(e.goalId,100)}:{},...e.loopId?{loopId:k(e.loopId,100)}:{},executionId:k(e.executionId,120),...e.reasonCode?{reasonCode:k(e.reasonCode,80)}:{},createdAt:k(e.createdAt,80),publicSummary:k(e.publicSummary),publicSafe:!0}}function zo(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
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(`
21
- [Neocortex] ${g}
18
+ `);return}if(t==="json"){r.write(JSON.stringify(Jo(e))+`
19
+ `);return}r.write(Yo(e)+`
20
+ `)}function wt(e){return oo.has(e.status)}function qo(e,t,r){if(t){const o=e.find(i=>i.jobId===t);return!!(o&&wt(o))}return r<=0?!1:e.filter(o=>!wt(o)).length===0}function Ko(e,t,r,n){return r<n?!1:t?!e.some(o=>o.jobId===t&&!wt(o)):e.length===0}function Xo(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 Zo(e){return e.includes(X.MALFORMED)?"malformed":e.includes(X.AMBIGUOUS)?"ambiguous":e.includes("watch-target-multiple")?"multiple":e.includes("watch-evidence-unsafe")?"unsafe":e.includes(X.MISSING)||e.includes(Y.TARGET_UNRESOLVED)?"unresolved":"unavailable"}function Lr(e,t){const r=t?He(t):void 0,n=re([...e,Y.TARGET_UNRESOLVED,x.WATCH_TARGET_UNRESOLVED]),o=At(r,r?.targetId,Zo(n),n),i=Ie({generatedAt:new Date().toISOString()},[],!1,0,[x.WATCH_TARGET_UNRESOLVED]),a=pe(void 0,void 0,void 0,[],[x.WATCH_TARGET_UNRESOLVED],"unavailable");return fe({watchStatus:"blocked",active:!1,targetEvidence:o,snapshotEvidence:i,cursorEvidence:a,stopReason:"target_unresolved",reasonCodes:n,generatedAt:i.generatedAt})}function Qo(e,t,r,n,o=!1){const i=Lr(e,Dr(t));return he(i,r,n,o),Ee("target-unresolved",0,0,i,o)}async function ei(e){if(e.signal?.aborted){const h=At(e.target??He(e.targetJobId),e.targetJobId,e.target??e.targetJobId?"resolved":"unresolved",[Y.CANCELLED]),R=Ie(void 0,[],!1,0),E=pe(e.initialCursor,e.initialCursor,e.initialCursor,[],[Y.CANCELLED],"unavailable"),V=fe({watchStatus:"stopped",active:!1,targetEvidence:h,snapshotEvidence:R,cursorEvidence:E,stopReason:"cancelled",reasonCodes:[Y.CANCELLED]});return Ee("cancelled",0,0,V,e.protectedOutput)}const t=e.target??He(e.targetJobId),r=e.targetJobId??t?.targetId,n=e.stdout??process.stdout;if(!t){const h=Lr([X.MISSING,Y.TARGET_UNRESOLVED]);return he(h,e.format,n,e.protectedOutput),Ee("target-unresolved",0,0,h,e.protectedOutput)}const o=it(e.limit??st("NEOCORTEX_INVOKE_WATCH_LIMIT",Wt),Wt,50),i=Math.max(50,it(e.pollIntervalMs??st("NEOCORTEX_INVOKE_WATCH_POLL_INTERVAL_MS",Gt),Gt,6e4)),a=it(e.maxIdlePolls??st("NEOCORTEX_INVOKE_WATCH_MAX_IDLE_POLLS",Ht),Ht,120),c=it(e.maxPolls??st("NEOCORTEX_INVOKE_WATCH_MAX_POLLS",Ft),Ft,86400),l=e.sleep??Xo;let p=e.initialCursor,m=0,w=0,f=0;const d=At(t,r,"resolved",[x.OK]),I={schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:"pending",renderedSummaryCount:0,reasonCodes:[x.WATCH_RENDER_PENDING],publicSafe:!0},A=pe(e.initialCursor,p,p,[],e.initialCursor?[x.WATCH_CURSOR_UNCHANGED]:[x.WATCH_NO_SUMMARIES_YET],e.initialCursor?"unchanged":"not_started");he(fe({watchStatus:"active",active:!0,targetEvidence:d,snapshotEvidence:I,cursorEvidence:A,stopReason:"not_stopped",reasonCodes:[x.OK]}),e.format,n,e.protectedOutput);let C;try{C=await gn({projectRoot:e.projectRoot,strictReadOnly:e.strictReadOnly})}catch{const h=Ie(void 0,[],!1,m,[x.WATCH_SNAPSHOT_UNAVAILABLE]),R=pe(e.initialCursor,p,p,[],[x.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),E=fe({watchStatus:"blocked",active:!1,targetEvidence:d,snapshotEvidence:h,cursorEvidence:R,stopReason:"unavailable_evidence",reasonCodes:[Y.STORE_UNAVAILABLE]});return he(E,e.format,n,e.protectedOutput),Ee("store-unavailable",m,f,E,e.protectedOutput)}try{for(;!e.signal?.aborted&&f<c;){f+=1;const h=p,R=C.collectProcessingOutputSummaryCursor({...p?{cursor:p}:{},...t?{target:t}:{},...r?{jobId:r}:{},limit:o}),E=C.collectSnapshot({jobLimit:50,processingSummaryLimit:1}),V=E.jobs;if(R.summaries.length>0){for(const $ of R.summaries)zo($,e.format,n,e.protectedOutput),m+=1;p=R.nextCursor??R.summaries[R.summaries.length-1]?.cursor??p,w=0}else p=R.nextCursor??p,w+=1;const N=Ie(E,R.summaries,!0,R.summaries.length),P=pe(e.initialCursor,h,p,R.summaries,R.summaries.length>0?[x.WATCH_CURSOR_ADVANCED]:[x.WATCH_NO_SUMMARIES_YET]);if(he(fe({watchStatus:R.summaries.length>0?"polling":"waiting",active:!0,targetEvidence:d,snapshotEvidence:N,cursorEvidence:P,stopReason:"not_stopped",reasonCodes:R.summaries.length>0?[x.WATCH_CURSOR_ADVANCED]:[x.WATCH_NO_SUMMARIES_YET],generatedAt:E.generatedAt}),e.format,n,e.protectedOutput),!R.hasMore&&qo(V,r,m)){const $=Ie(E,R.summaries,!1,m,[Y.COMPLETED]),D=pe(e.initialCursor,h,p,R.summaries,[Y.COMPLETED],"exhausted"),O=fe({watchStatus:"stopped",active:!1,targetEvidence:d,snapshotEvidence:$,cursorEvidence:D,stopReason:"not_stopped",reasonCodes:[Y.COMPLETED],generatedAt:E.generatedAt});return he(O,e.format,n,e.protectedOutput),Ee("completed",m,f,O,e.protectedOutput)}if(!R.hasMore&&Ko(V,r,w,a)){const $=Ie(E,R.summaries,!1,m,[x.WATCH_STOP_IDLE_LIMIT_REACHED]),D=pe(e.initialCursor,h,p,R.summaries,[x.WATCH_STOP_IDLE_LIMIT_REACHED],"exhausted"),O=fe({watchStatus:"stopped",active:!1,targetEvidence:d,snapshotEvidence:$,cursorEvidence:D,stopReason:"idle_limit_reached",reasonCodes:[Y.IDLE_TIMEOUT,x.WATCH_STOP_IDLE_LIMIT_REACHED],generatedAt:E.generatedAt});return he(O,e.format,n,e.protectedOutput),Ee("idle-timeout",m,f,O,e.protectedOutput)}R.hasMore||await l(i,e.signal)}}catch{const h=Ie(void 0,[],!1,m,[x.WATCH_SNAPSHOT_UNAVAILABLE]),R=pe(e.initialCursor,p,p,[],[x.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),E=fe({watchStatus:"blocked",active:!1,targetEvidence:d,snapshotEvidence:h,cursorEvidence:R,stopReason:"unavailable_evidence",reasonCodes:[Y.STORE_UNAVAILABLE]});return he(E,e.format,n,e.protectedOutput),Ee("store-unavailable",m,f,E,e.protectedOutput)}finally{C.close()}if(e.signal?.aborted){const h=Ie(void 0,[],!1,m,[Y.CANCELLED]),R=pe(e.initialCursor,p,p,[],[Y.CANCELLED],"unavailable"),E=fe({watchStatus:"stopped",active:!1,targetEvidence:d,snapshotEvidence:h,cursorEvidence:R,stopReason:"cancelled",reasonCodes:[Y.CANCELLED]});return he(E,e.format,n,e.protectedOutput),Ee("cancelled",m,f,E,e.protectedOutput)}const j=Ie(void 0,[],!1,m,[x.WATCH_STOP_MAX_POLLS_REACHED]),v=pe(e.initialCursor,p,p,[],[x.WATCH_STOP_MAX_POLLS_REACHED],"exhausted"),U=fe({watchStatus:"stopped",active:!1,targetEvidence:d,snapshotEvidence:j,cursorEvidence:v,stopReason:"max_polls_reached",reasonCodes:[Y.MAX_POLLS,x.WATCH_STOP_MAX_POLLS_REACHED]});return he(U,e.format,n,e.protectedOutput),Ee("max-polls",m,f,U,e.protectedOutput)}function ue(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 Rt(e){if(e.startsWith("job-J"))return"job";if(e.startsWith("goal-G"))return"goal";if(e.startsWith("loop-L"))return"loop"}function Pr(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=ue(n[1]);o&&t.push(o)}return re(t)}function Dr(e){return Pr(e)[0]}function He(e){const t=e?ue(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 vt(e){return re(e.filter(t=>typeof t=="string").map(t=>ue(t)).filter(t=>!!t?.startsWith("job-J")))}function ti(e,t){const r=vt(t).filter(n=>n!==e.targetId&&n!==e.jobId);return r.length>0?{...e,relatedJobIds:r}:e}function ri(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"?ue(e.targetId):typeof t?.targetId=="string"?ue(t.targetId):typeof e.targetJobId=="string"?ue(e.targetJobId):void 0,o=He(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=vt([...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:ue(e.jobId??t?.jobId)??o.jobId}:{},...typeof(e.goalId??t?.goalId)=="string"?{goalId:ue(e.goalId??t?.goalId)??o.goalId}:{},...typeof(e.loopId??t?.loopId)=="string"?{loopId:ue(e.loopId??t?.loopId)??o.loopId}:{},...a.length>0?{relatedJobIds:a}:{}}}function jr(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 K=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"}),ni=new Set(["create","start","resume"]),oi=new Set(["create","resume","run-once"]);function bt(e,t,r,n,o){return{schemaVersion:1,contractVersion:"continuity-v1",...r?{command:r}:{},...n?{operation:n}:{},active:e,...o?{watchToken:o}:{},reasonCodes:re(t),serverHeldStream:!1,allJobsPolling:!1,targetResolution:e?"required-after-dispatch":"inactive",publicSafe:!0}}function Z(e,t=[],r,n){const o=t.length>0?t:[K.INACTIVE];return{args:e,watch:!1,reasonCodes:o,metadata:bt(!1,o,r,n),publicSafe:!0}}function ii(e){const t=e.trim().split(/\s+/).filter(Boolean),r=t.slice(2).filter(i=>i==="--watch").length;if(r===0)return Z(e,[],"jobs","watch");if(r!==1)return Z(e,[K.AMBIGUOUS],"jobs","watch");const n=t.filter((i,a)=>a<2||i!=="--watch").join(" ");return jr(n)?n.trim().split(/\s+/).filter(Boolean).slice(2).length!==1?Z(e,[K.AMBIGUOUS],"jobs","watch"):Dr(n)?{args:n,watch:!0,reasonCodes:[K.ACTIVE],metadata:bt(!0,[K.ACTIVE],"jobs","watch"),publicSafe:!0}:Z(e,[K.TARGET_INVALID],"jobs","watch"):Z(e,[K.UNSUPPORTED],"jobs","watch")}function si(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 ai(e){if(!e||e.quoted)return;const t=e.value.replace(/^\*/,"").toLowerCase();return t==="goal"||t==="loop"?t:void 0}function ci(e,t){if(!e||e==="jobs"||!t||t.quoted)return;const r=t.value.toLowerCase();return(e==="goal"?ni:oi).has(r)?r:void 0}function di(e){return!e.quoted&&e.value!=="--watch"&&e.value.toLowerCase().startsWith("--watch")}function ui(e){const{tokens:t,malformed:r}=si(e),n=ai(t[0]),o=ci(n,t[1]);if(r)return Z(e,[K.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(di);if(!(i.length>0||a.length>0||c.length>0))return Z(e,[],n,o);if(i.length>1)return Z(e,[K.DUPLICATE],n,o);if(i.length===1&&(a.length>0||c.length>0))return Z(e,[K.AMBIGUOUS],n,o);if(a.length>0)return Z(e,[K.QUOTED],n,o);if(c.length>0)return Z(e,[K.MALFORMED],n,o);const p=i[0];if(!p)return Z(e,[],n,o);if(t[t.length-1]!==p)return Z(e,[K.NON_FINAL],n,o);if(!n||!o)return Z(e,[K.UNRESOLVED],n,o);const m=`${e.slice(0,p.start)}${e.slice(p.end)}`.trim(),w={literal:"--watch",position:"final",start:p.start,end:p.end,quoted:!1,publicSafe:!0};return{args:m,watch:!0,reasonCodes:[K.ACTIVE],metadata:bt(!0,[K.ACTIVE],n,o,w),publicSafe:!0}}function li(e){return jr(e)?ii(e):ui(e)}function pi(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&io.has(t)):[]}function Be(e){return{disabled:!0,reasonCodes:re(e.length>0?e:[X.MISSING])}}function Tt(e,t,r=[],n){const o=He(t);if(o)return{source:e,target:ti(o,r),targetJobId:o.targetId,...n?{initialCursor:n}:{},serverHeldStream:!1}}function fi(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=re([...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 Re(e,t,r,n){return{source:e,hasEvidence:t,candidates:fi(r.filter(o=>!!o)),...n&&n.length>0?{disabledReasonCodes:re(n)}:{}}}function hi(e,t){return e.target.selectorKind===t.target.selectorKind&&e.target.targetId===t.target.targetId}function Fe(e,t){const r=re(e.filter(n=>typeof n=="string").map(n=>ue(n)).filter(n=>!!n));if(t){const n=r.find(o=>Rt(o)===t);if(n)return n}return r[0]}function at(e,t){return re(e.filter(r=>typeof r=="string").map(r=>ue(r)).filter(r=>!!r)).find(r=>Rt(r)===t)}function gi(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=pi(n?.reasonCodes??r?.reasonCodes);if(!n)return Re("watcher-metadata",o.length>0,[],o);if(n.active===!1||o.length>0)return Re("watcher-metadata",!0,[],o.length>0?o:[X.MALFORMED]);if(n.serverHeldStream!==!1)return Re("watcher-metadata",!0,[],[X.SERVER_HELD_STREAM]);const i=ri(n);if(!i)return Re("watcher-metadata",!0,[],[X.MISSING]);const a=typeof n.initialCursor=="string"?n.initialCursor:void 0;return Re("watcher-metadata",!0,[{source:"watcher-metadata",target:i,targetJobId:i.targetId,...a?{initialCursor:a}:{},serverHeldStream:!1}])}function Mr(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"?Fe([e.goalId,e.targetGoalId,e.campaignId,e.jobId,e.targetJobId,o?.goalId,o?.campaignId,o?.jobId],"goal"):Fe([e.loopId,e.targetLoopId,e.jobId,e.targetJobId,o?.loopId,o?.jobId,n?.loopId,n?.jobId],"loop"))??Fe([e.jobId,e.targetJobId,o?.jobId,n?.jobId]);return Tt("goal-loop-continuity-metadata",a,[e.jobId,e.targetJobId,o?.jobId,n?.jobId])}function mi(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?Mr(r,"goal"):void 0,n?Mr(n,"loop"):void 0],i=!!(r||n);return Re("goal-loop-continuity-metadata",i,o,i&&o.every(a=>!a)?[X.MISSING]:void 0)}function yi(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 Ur(e,t){const r=y(t.metadata)?t.metadata:void 0,n=at([t.goalId,t.targetGoalId,t.campaignId,r?.goalId,r?.campaignId,t.jobId,r?.jobId],"goal"),o=at([t.loopId,t.targetLoopId,r?.loopId,t.jobId,r?.jobId],"loop"),i=Fe([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(...vt([i,t.jobId,t.targetJobId,r?.jobId])),e.set(a,c)}function Ii(e){const t=y(e.metadata)?e.metadata:void 0;return!!(at([e.goalId,e.targetGoalId,e.campaignId,t?.goalId,t?.campaignId,e.jobId,t?.jobId],"goal")??at([e.loopId,e.targetLoopId,t?.loopId,e.jobId,t?.jobId],"loop"))}function Ei(e){const t=y(e.metadata)?e.metadata:void 0;return!!Fe([e.goalId,e.targetGoalId,e.campaignId,e.loopId,e.targetLoopId,e.jobId,e.targetJobId,t?.goalId,t?.campaignId,t?.loopId,t?.jobId])}function Vr(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(Ei);for(const a of r)Ur(e,a);(!i||Ii(t))&&Ur(e,t)}function _i(e){const t=yi(e?.continuityStateUpdate),r=new Map;for(const o of t){Vr(r,o);const i=Array.isArray(o.operations)?o.operations.filter(y):[];for(const a of i)Vr(r,a)}const n=Array.from(r.values()).map(o=>Tt("continuity-state-update-operation-log",o.targetId,o.relatedJobIds));return Re("continuity-state-update-operation-log",t.length>0,n,t.length>0&&n.every(o=>!o)?[X.MISSING]:void 0)}function Ci(e){const t=Pr(e);return Re("explicit-args",t.length>0,t.map(r=>Tt("explicit-args",r)))}function Si(e,t){const r=[gi(e),mi(e),_i(e),Ci(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 Be(o.disabledReasonCodes);if(o.candidates.length!==1)return Be([o.candidates.length>1?X.AMBIGUOUS:X.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 Be(a.disabledReasonCodes);if(a.candidates.length>1)return Be([X.AMBIGUOUS]);const c=a.candidates[0];if(c&&!hi(i,c))return Be([X.CONFLICT])}return{target:i.target,targetJobId:i.targetJobId,...i.initialCursor?{initialCursor:i.initialCursor}:{},source:i.source,serverHeldStream:!1}}return Be([X.MISSING])}async function Br(e,t,r,n={}){const i=await We(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,m=a.headers.get("X-Client-Version-Warning");return m&&!wr&&(wr=!0,process.stderr.write(`
21
+ [Neocortex] ${m}
22
22
 
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}
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 ${er/1e3}s`:"Network error: invalid response"}}}async function Ai(e,t,r){const n=await We(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 Is(e,t,r){const n=await We(e,"/api/v1/invoke/private-execution/cancel",t,r,{maxAttempts:1,allowReplayRetry:!1});return!!n.response?.ok&&n.parsed.status==="cancelled"}async function wi(e,t,r,n={}){const o=await We(e,"/api/v1/invoke/epic-claims/acknowledge",{...r,registryVersion:xe,registryChecksum:Oe},t,n);return!!o.response?.ok&&o.parsed.status==="ok"&&o.parsed.claimOutcome===r.status}async function Ri(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 wi(r,n,{claimId:p.claimId,projectId:o,epicId:p.epicId,status:"materialized"},i)||(to(e,l),c+=1);return c}function vi(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:[],m=p.length===1&&typeof p[0]?.storyId=="string"?p[0].storyId:"",f=e.stories[m]?.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 bi(e){let t;try{if(t=e.inputEnvelope??qe(e.inputSource??"args",e.args),Tn(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=qt(t);let o=r,i=n;const a=no(r);if(a.outcome!=="resolved"){const s=xn(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,g=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,...g?{invocationInput:g}:{}},exitCode:1}}const c=gt(e.projectRoot),l=a.selection.commandId,p=tn.find(s=>s.id===l),m=p?.subcommands.find(s=>s.id===a.selection.operationId),w=m?m.policy.strictReadOnly==="allow":p?.policy.strictReadOnly==="allow",f=l==="diagnose";let d;try{d=Rn({invocationId:dt(),intent:e.strictReadOnly||f?{schemaVersion:1,policy:Sn,registryVersion:xe,registryChecksum:Oe}:void 0,registryVersion:xe,registryChecksum:Oe,registryAllowsStrict:w,requestCanonicalBytes:JSON.stringify({command:l})})}catch(s){if(s instanceof Me)return{success:!1,error:s.code,errorCode:s.code,exitCode:1};throw s}{d.beginProjection();for(const s of zt)d.project(s);for(const s of An)d.project(s);d.seal()}const I=d.mode==="strict";if(l==="create-epic")try{const s=jn(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 lt?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"&&l!=="create-epic"||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=En({cwd:c,env:A,targetFlag:e.privateExecutionBeta?"codex":e.platformTarget}),j=C.targetId,v=e.privateExecutionBeta?void 0:In({cwd:c,env:A,targetFlag:e.platformTarget,nativeHostVersion:po(C,A)},C);l!=="migrate-project-id"&&d.execute({phase:"client-preflight",domain:"client-persistence",category:"first-run-marker",operation:"create"},()=>ro(),()=>{});const U=To(d),h=(e.serverUrl??U?.serverUrl??rn).replace(/\/+$/,"");if(l==="migrate-project-id"){const s=await Mn(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 g;try{g=Dn(c)}catch(b){const ee=b instanceof lt?b.code:"PROJECT_IDENTITY_MIGRATION_PREPARE_FAILED";return{success:!1,error:ee,errorCode:ee,exitCode:1}}u.push(Ue({phase:"prepare",outcome:g.changed&&g.document.phase==="prepared"?"prepared":"retry",floor:g.document.legacyEpicFloor,licenseId:"local-client",projectId:g.document.projectId}));const T=Cr(c);if(T.config.project_id!==g.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 Ar(h,U?.licenseKey,d);if(G.status!=="authenticated"){const b=G.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 ae;try{ae=Bt(e.args.trim(),T)}catch(b){const ee=b instanceof $t?b.code:"PROJECT_IDENTITY_MIGRATION_PROJECTION_FAILED";return{success:!1,error:ee,errorCode:ee,metadata:{invocationDiagnostics:u},exitCode:1}}let le={args:r,projectRoot:c.replace(De(),"~"),stateSnapshot:ae,platformTarget:j,...v?{nativeHostAttestation:v}:{},projectId:g.document.projectId,projectIdentityMigration:g.request,inputEvidence:n,idempotencyKey:g.document.operationId,registryVersion:xe,registryChecksum:Oe};try{le=Or(le).body}catch(b){if(b instanceof It||b instanceof Et)return{success:!1,error:b.message,errorCode:b.code,metadata:{invokePayload:b.telemetry,invocationDiagnostics:u},exitCode:1};throw b}const z=await Jt("invoke-query",()=>Br(h,le,G.token,{refreshToken:()=>G.client.forceRefresh()}));if(!z.ok||!z.data)return u.push(Ue({phase:"seed",outcome:"rejected",floor:g.document.legacyEpicFloor,licenseId:"local-client",projectId:g.document.projectId})),{success:!1,error:de(z.error??"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",ke),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{On(Q),u.push(Ue({phase:"seed",outcome:Q.status,floor:Q.acceptedLegacyFloor,licenseId:"local-client",projectId:Q.projectId})),Ln(c,Q),u.push(Ue({phase:"remote-acknowledged",outcome:Q.status,floor:Q.acceptedLegacyFloor,licenseId:"local-client",projectId:Q.projectId})),Pn(c,Q),u.push(Ue({phase:"finalize",outcome:"finalized",floor:Q.acceptedLegacyFloor,licenseId:"local-client",projectId:Q.projectId}))}catch(b){u.push(Ue({phase:"reconcile",outcome:"rejected",floor:g.document.legacyEpicFloor,licenseId:"local-client",projectId:g.document.projectId}));const ee=b instanceof lt?b.code:b instanceof Error?b.message:"PROJECT_IDENTITY_MIGRATION_RECEIPT_INVALID";return{success:!1,error:ee,errorCode:ee,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}
24
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(",")}
25
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}
26
+ `),{success:!1,error:s,exitCode:1}}const R=Er(l);if(R)try{_r(c,{allowMissingRuntime:!0}).runtimeMissing&&(await d.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},async()=>Bn(c),async()=>{}),_r(c))}catch(s){const u=s instanceof we?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"},()=>dn(c,{args:e.args,canonicalCommandId:l}),()=>{})}catch(s){if(s instanceof un)return process.stderr.write(`${s.message}
28
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.
29
+ `),{success:!1,error:u,exitCode:1}}let E;try{const s=await wo(c,e.args,l);E=Cr(c,{epicAware:R,p205Authorities:s})}catch(s){const u=s instanceof we?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:g=>process.stderr.write(`${g}
31
+ `),warn:g=>process.stderr.write(`${g}
32
+ `)}};s(u),u.args!==e.args&&(e={...e,args:u.args},o=u.args,i=qt(qe(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 g=vi(E,u);E.yoloop=g?{...u,continuationRecoveryEvidence:g}:u}}catch(s){if(/^\s*\*?(?:yoloop|auto-yolo|epic-runner|story-runner|loop-yolo|auto-epic)\b/i.test(e.args)){const g=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] ${g}. No yoloop request was sent and no state was mutated.
34
+ `),{success:!1,error:g,errorCode:g,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 Me)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
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.
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"),g=await u({args:e.args,projectRoot:c,featureFlag:s,logger:{warn:T=>process.stderr.write(`${T}
37
+ `)}});g.applied&&g.metadata&&(E.graphRetrieval=g.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(co(e.args)){const{collectProjectEvidence:s}=await import("../evidence/collector.js"),u=a.selection.uiUxReview?.architectureDir,g=s({projectRoot:c,...u?{candidatePaths:[u],includeFallbackInventory:!0}:{}});(g.evidence.length>0||g.exclusions.length>0)&&(E.projectEvidence=g)}}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
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(`
40
+ `)}const V=U?.licenseKey?new ut({cacheDir:pt,passphrase:U.licenseKey,strictReadOnly:I}):null,N=o.trim();if(!N&&V){const s=await d.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>Ro(V),async()=>null);if(s)return d.complete(),{success:!0,instructions:s.instructions,metadata:s.metadata,exitCode:0}}const P=await Ar(h,U?.licenseKey,d);if(P.status!=="authenticated"){const s=P.status==="refresh-required",u=!s&&U&&!U.licenseKey?" This may be caused by a machine fingerprint change (e.g., hardware or hostname change).":"";try{const g=Vt(),T=Mt(s?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",g);T&&process.stderr.write(Ut(T,g))}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"},()=>Ri(c,E,h,P.token,$,{refreshToken:()=>P.client.forceRefresh()}),async()=>0)}catch{}const D=Ti(N);if(D&&!f)try{const s=await P.tierClient.preFlightCheck(D);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 O=await Wo({args:N,projectRoot:c,platformTarget:j,environment:e.environment??process.env,bootstrapper:e.runnerBootstrapper,effectAuthority:d});if(O.attachToRequest&&(E.runnerBootstrap=O.metadata),O.warning&&process.stderr.write(`[Neocortex] ${O.warning}
42
+ `),!O.shouldContinue)return O.error&&process.stderr.write(`[Neocortex] ${O.error}
43
+ `),{success:!1,error:O.error??"Runner auto-bootstrap required but failed.",errorCode:O.errorCode,exitCode:O.exitCode??1};let J;try{const s=an(N,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??Bt(N,E)}catch(s){if(s instanceof $t){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"),g=u(c);if(Pe(g.databasePath)){const T=await s(c);try{const G=T.store.listRecentNativeAgentDispatches(20);G.length>0&&(J.nativeAgentDispatches=G)}finally{T.store.close()}}}catch{}const ve=Dt(N),_e=$;if(ve==="create-epic"&&!_e){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 ge;try{ge=d.execute({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>ve==="create-epic"?eo(c,N):void 0,()=>{})}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const Ge=ge?.key,be=I?{schemaVersion:1,invocationId:d.invocationId,intent:d.intent,clientProjection:wn(zt.map(s=>({...s,count:1})))}:void 0;let W;if(e.privateExecutionBeta)try{const{preflightPrivateCodexExecutor:s}=await import("../private-execution/codex-executor.js");W=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 Ye=W?{schemaVersion:1,hostKind:"codex-cli",hostVersion:W.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:W.observedAtMs}}:void 0;let H={args:o,projectRoot:c.replace(De(),"~"),stateSnapshot:J,platformTarget:j,...v?{nativeHostAttestation:v}:{},...Ye?{privateExecution:Ye}:{},projectId:_e,inputEvidence:i,idempotencyKey:Ge,registryVersion:xe,registryChecksum:Oe,...be?{strictReadOnly:be}:{}};const Hr=Ve(H);if(!I&&e.inputSource&&e.inputSource!=="args"&&Hr>=ft)try{H={argsRef:(await Cn(d,"secondary-mutation",()=>Do(h,o,P.token,()=>P.client.forceRefresh()),async()=>{throw new Me("readonly-physical-boundary-unsafe","boundary")})).argsRef,projectRoot:c.replace(De(),"~"),stateSnapshot:J,platformTarget:j,...v?{nativeHostAttestation:v}:{},...Ye?{privateExecution:Ye}:{},projectId:_e,inputEvidence:i,idempotencyKey:Ge,registryVersion:xe,registryChecksum:Oe,...be?{strictReadOnly:be}:{}}}catch(s){return s instanceof Me?{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(ve==="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:g}=await import("../yolo/spec-envelope-collector.js"),T=g({projectRoot:c,storyId:s,epicId:u,inputSha256:i.sha256});if(/\sbranchless-preparation\s*$/.test(o))H={...H,yoloSpecEnvelope:T};else{const{collectYoloChangeEvidence:G}=await import("../yolo/change-evidence-collector.js"),ae=G({projectRoot:c,defaultBranch:J.config.default_branch,expectedHeadSha:T.sourceRevision.headSha});H={...H,yoloSpecEnvelope:T,yoloChangeEvidence:ae}}}catch(g){const T=g instanceof Error&&/^yolo-(?:spec-envelope|change-evidence)-[a-z-]+$/.test(g.message)?g.message:"yolo-spec-envelope-unsafe";return{success:!1,error:T,errorCode:T,exitCode:1}}}try{const s=Or(H);H=s.body,s.degraded?kr(H,s.telemetry):$o(H)}catch(s){if(s instanceof It||s instanceof Et)return kr(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(ve==="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:g}=await import("../yolo/change-evidence-collector.js"),T=g({projectRoot:c,defaultBranch:J.config.default_branch,expectedHeadSha:u.sourceRevision.headSha});if(T.pathsSha256!==H.yoloChangeEvidence.pathsSha256||T.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 Jt("invoke-query",()=>Br(h,H,P.token,{refreshToken:()=>P.client.forceRefresh()})),Ot;if(I&&_.ok)try{if(f){const u=_.data?.metadata;if(u&&["stateUpdate","stateMutated","yoloopStateUpdate","continuityStateUpdate","checkpoint","schedulerStateUpdate","quotaCacheUpdate","projectIdentityMigration","epicClaim","gitLifecycleGraphAuthority"].some(T=>u[T]!==void 0))throw new Me("readonly-response-conflict")}const s=_.data?.metadata.strictReadOnly;vn(d,s),f&&kn(_.data?.metadata.strictDiagnose,r,_.data?.instructions??""),Ot=s.security}catch(s){const u=s instanceof Me?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",g=s?.min_version??"unknown";return process.stderr.write(`
48
48
  `),process.stderr.write(`==================================================
49
49
  `),process.stderr.write(` UPGRADE REQUIRED
50
50
  `),process.stderr.write(`==================================================
51
51
  `),process.stderr.write(`
52
- Your Neocortex version (${ke}) is no longer supported.
53
- `),process.stderr.write(` Minimum required: ${m}
52
+ Your Neocortex version (${je}) is no longer supported.
53
+ `),process.stderr.write(` Minimum required: ${g}
54
54
 
55
55
  `),process.stderr.write(` Run this command to update:
56
56
 
@@ -59,15 +59,15 @@ ${t}
59
59
  `),process.stderr.write(` After updating, re-run your command.
60
60
  `),process.stderr.write(`==================================================
61
61
 
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.
62
+ `),{success:!1,error:`UPGRADE_REQUIRED: Client version ${je} is below minimum ${g}. Run: ${u}`,exitCode:3}}if(!_.ok||!_.data){const s=_.status===401?2:(_.status===429||_.status>=500,1),u=Oo(_);try{if(u){const g=Vt(),T=Mt(u,g);T&&process.stderr.write(Ut(T,g))}}catch{}return{success:!1,error:de(_.error??"Unknown error from server",ke),...u?{errorCode:u}:{},exitCode:s}}if(e.privateExecutionBeta&&!Zr(_.data))return{success:!1,error:"private-execution-public-envelope-invalid",errorCode:"private-execution-public-envelope-invalid",exitCode:1};if(!N&&_.data.metadata?.mode==="menu"&&V&&await d.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>vo(V,_.data.instructions,_.data.metadata),async()=>{}).catch(()=>{}),_.data.metadata&&await d.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"tier-cache",operation:"update"},()=>P.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),g=`STATE_WRITEBACK_BLOCKED: inline-yolo persistence failed (${de(u,ke)}).`;return process.stderr.write(`${g}
64
+ `),{success:!1,error:g,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"},()=>Wn(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
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(`
66
66
  `),process.stderr.write(`==================================================
67
67
  `),process.stderr.write(` YOLOOP CLIENT UPGRADE REQUIRED
68
68
  `),process.stderr.write(`==================================================
69
69
  `),process.stderr.write(`
70
- Your Neocortex client version (${ke}) does not
70
+ Your Neocortex client version (${je}) does not
71
71
  `),process.stderr.write(` support client-side yoloop state persistence.
72
72
 
73
73
  `),process.stderr.write(` Run this command to upgrade:
@@ -77,18 +77,18 @@ ${t}
77
77
  `),process.stderr.write(` After upgrading, re-run your yoloop command.
78
78
  `),process.stderr.write(`==================================================
79
79
 
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.
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(g=>g.type==="rollover_session");try{const g=await d.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>{const{persistYoloopFromResponse:T}=await import("../yoloop/invoke-hooks.js");return T(_.data.metadata,c)},async()=>({ok:!0,authoritative:!1,reasonCodes:[]}));if(g&&g.ok===!1){const T=g.reasonCodes[0]??"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED";return process.stderr.write(`[Neocortex] ${T}. No yoloop continuation instructions were released.
81
+ `),{success:!1,error:T,errorCode:T,exitCode:1}}}catch(g){if(u){const T=g instanceof Error?g.message.match(/\bYOLOOP_[A-Z0-9_]+\b/)?.[0]??"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED":"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED";return process.stderr.write(`[Neocortex] ${T}. No yoloop continuation instructions were released.
82
+ `),{success:!1,error:T,errorCode:T,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
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}
84
+ `),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${de(u,ke)}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}if(_.data.metadata?.tier_changed){const s=_.data.metadata.current_tier;try{await P.client.forceRefresh()?(await P.tierClient.invalidateTierCache(),process.stderr.write(`[Neocortex] Token atualizado automaticamente para tier ${s}
85
85
  `)):process.stderr.write(`[Neocortex] Seu tier foi atualizado para ${s}! Execute "neocortex activate" para obter um token atualizado.
86
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
87
+ `)}}let me,xt=!1;if(e.privateExecutionBeta)try{if(!W||!_.data.metadata?.privateExecution||!_e||_.data.metadata?.mode!=="yolo"&&_.data.metadata?.mode!=="step"&&_.data.metadata?.mode!=="pipeline"&&_.data.metadata?.mode!=="create-epic"||typeof _.data.metadata.stepId!="string")throw new Error("private-execution-descriptor-unavailable");const{consumePrivateExecutionDelivery:s,privateExecutionStateSnapshotSha256:u}=await import("../private-execution/delivery.js"),{preflightPrivateCodexExecutor:g,runPrivateCodexStep:T}=await import("../private-execution/codex-executor.js"),G=_.data.metadata.mode==="yolo",ae=_.data.metadata.mode==="create-epic";let le,z,Q;const b=_.data.metadata.gitLifecycleGraphAuthority,ee=_.data.metadata.privateExecutionRootAction;let Je;if(G){if(!b||typeof b.storyId!="string"||typeof b.graphRevision!="string"||typeof b.executionBranch!="string")throw new Error("private-execution-graph-unavailable");if(Je=b.storyId,ee?.action==="prepare-epic-checkout"){const{prepareDirectYoloSetup:Gr}=await import("../git/direct-yolo-checkpoint.js"),{capturePrivateYoloCleanHead:Yr,recordPrivateYoloCleanBaseline:Jr}=await import("../private-execution/clean-baseline.js"),zr=Yr(c),Nt=await Gr({projectRoot:c,storyId:ee.storyId});if(!Nt.ok)throw new Error("private-execution-root-setup-denied");await Jr(c,Nt.value,zr)}let F;try{F=Le("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(F!==b.executionBranch)throw new Error("private-execution-execution-branch-mismatch");const te=Xe(c,{required:!0}),L=typeof b.epicId=="string"?te.epics[b.epicId]:void 0,ce=y(L?.branch_lease)?L.branch_lease:void 0;if(!L||L.graph_revision!==b.graphRevision||!ce||ce.ownerStoryId!==b.storyId||typeof ce.expiresAt!="string"||!Number.isFinite(Date.parse(ce.expiresAt))||Date.parse(ce.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"||ae&&_.data.metadata.resolvedTrigger==="create-epic"){if(!ae&&typeof _.data.metadata.storyId!="string")throw new Error("private-execution-descriptor-unavailable")}else throw new Error("private-execution-descriptor-unavailable");if(G){const{ensurePrivateYoloIsolatedSession:F,reconcilePrivateYoloIsolatedSession:te}=await import("../private-execution/isolated-session.js");if(ee?.action==="checkpoint-epic-story")await te(c,Je,b.graphRevision);else{const L=await F(c,Je,b.graphRevision,e.privateExecutionWorkspaceParent),ce=await g(L.workspace.workspacePath);if(ce.hostVersion!==W.hostVersion)throw new Error("private-codex-version-drift");W=ce}}if(Date.now()-W.observedAtMs>2e4){const F=await g(W.projectRoot);if(F.hostVersion!==W.hostVersion)throw new Error("private-codex-version-drift");W=F}const kt=await P.client.getToken();if(!kt)throw new Error("private-execution-auth-unavailable");const ye=ae?_.data.metadata.epicClaim:void 0;if(ae&&(!ye||typeof ye.claimId!="string"||typeof ye.epicId!="string"))throw new Error("private-execution-descriptor-unavailable");if(ae){if(!ge)throw new Error("private-execution-epic-claim-admission-unverified");d.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>ar(c,ge.fingerprint,ye.claimId,ye.epicId),()=>{}),xt=!0;const{preparePrivateYoloIsolatedWorkspace:F,PRIVATE_EPIC_PENDING_SIDECAR:te}=await import("../private-execution/isolated-workspace.js"),L=e.privateExecutionWorkspaceParent??ne(De(),".local","share","neocortex","private-epic-workspaces");e.privateExecutionWorkspaceParent||ze(L,{recursive:!0,mode:448}),le=F(c,L,!0),Q=Ne("sha256").update(Te(ne(c,te))).digest("hex");const ce=await g(le.workspacePath);if(ce.hostVersion!==W.hostVersion)throw new Error("private-codex-version-drift");W=ce}else if(!G){const{preparePrivateYoloIsolatedWorkspace:F}=await import("../private-execution/isolated-workspace.js"),te=e.privateExecutionWorkspaceParent??ne(De(),".local","share","neocortex","private-step-workspaces");e.privateExecutionWorkspaceParent||ze(te,{recursive:!0,mode:448}),z=F(c,te);const L=await g(z.workspacePath);if(L.hostVersion!==W.hostVersion)throw new Error("private-codex-version-drift");W=L}const Fr=await s(_.data.metadata.privateExecution,{projectId:_e,commandId:G?"yolo":ae?"create-epic":_.data.metadata.mode==="pipeline"?"exec":"research",stepId:_.data.metadata.stepId,...G?{graphRevision:b.graphRevision}:{...ae?{claimId:ye.claimId,epicId:ye.epicId}:{storyId:_.data.metadata.storyId},stateSnapshotSha256:u(J)},inputSha256:i.sha256,hostKind:"codex-cli",hostVersion:W.hostVersion},F=>Ai(h,{...F},kt));if(ee?.action==="checkpoint-epic-story"){const{runPrivateYoloRootCheckpoint:F}=await import("../private-execution/root-checkpoint.js");me={...await F(c,ee)}}else{const F=await T(Fr,W,{requireWorkspaceEffect:!0,...G?{expectedExecutionBranch:b.executionBranch}:le?{expectedExecutionBranch:le.executionBranch}:z?{expectedExecutionBranch:z.executionBranch}:{}});if(G){const{admitPrivateYoloIsolatedSessionStep:te}=await import("../private-execution/isolated-session.js"),L=await te(c,Je,b.graphRevision);me={...F,isolation:{schemaVersion:1,outcome:L.admission.outcome,sequence:L.session.sequence,snapshotSha:L.session.snapshotSha,patchSha256:L.admission.patchSha256,changedPathCount:L.admission.changedPaths.length}}}else if(le){const{admitPrivateEpicClaimWorkspace:te}=await import("../private-execution/isolated-admission.js"),L=te(le,ye.claimId,ye.epicId,ge.fingerprint,Q);me={...F,isolation:{schemaVersion:1,outcome:L.outcome,baseSha:L.baseSha,patchSha256:L.patchSha256,changedPathCount:L.changedPaths.length}}}else if(z){const{admitPrivateStateBoundStepWorkspace:te}=await import("../private-execution/isolated-admission.js"),L=te(z,_.data.metadata.storyId);me={...F,isolation:{schemaVersion:1,outcome:L.outcome,baseSha:L.baseSha,patchSha256:L.patchSha256,changedPathCount:L.changedPaths.length}}}else me={...F}}}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 ct=yt(_.data.instructions,_.data.metadata);if(ge&&!xt&&_.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"},()=>ar(c,ge.fingerprint,u.claimId,u.epicId),()=>{})}catch{}return d.complete(Ot),{success:!0,instructions:me?me.outcome==="checkpoint-validated"?`# Checkpoint da story validado
88
88
 
89
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
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=`
91
+ O executor Codex retornou sem erro. Nenhum checkpoint ou aprova\xE7\xE3o da story foi emitido.`:ct.instructions,metadata:me?{...ct.metadata,privateExecutionReceipt:me}:ct.metadata,exitCode:0}}function Ti(e){const[t]=e.trim().split(/\s+/,1);return t?/^@?epic-[a-z0-9][a-z0-9._-]*$/i.test(t)?"epic":Dt(t):null}const $r="Provide exactly one invoke input source: --args <string>, --stdin, or --args-file <path>.",Oi=`
92
92
  neocortex-client invoke - Send orchestration request to server
93
93
 
94
94
  Usage:
@@ -111,7 +111,7 @@ Options:
111
111
  --server-url <url> Server URL override
112
112
  --platform-target <id> Explicit platform target override (default: runtime detection; unknown on no match)
113
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
114
+ --private-execution-beta Run an explicit *yolo, *exec, *research or *create-epic step through the isolated Codex CLI beta executor
115
115
 
116
116
  Invocation payload boundary:
117
117
  Select only the explicit user-intended Neocortex command and arguments after
@@ -158,12 +158,12 @@ Safety:
158
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.
159
159
  Jobs, goal and loop watch use serverHeldStream=false and foreground local SQLite polling of public processing summaries only.
160
160
  Unresolved targets disable polling with public reason codes; there is no all-jobs fallback.
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})+`
161
+ `.trim();function xi(e){return e.includes("--help")||e.includes("-h")||e.includes("help")}function se(e,t,r,n){return new et("INVOCATION_MALFORMED_INPUT",t,e,r,n)}function $e(e){return se("missing-input-value",`${e} requires a value. ${$r}`)}function ki(e){try{if(!Xr(e).isFile())throw se("missing-input-value","--args-file must point to a readable UTF-8 text file.","args-file");return Te(e)}catch(t){throw t instanceof et?t:se("missing-input-value","--args-file could not be read as UTF-8 text. Check the path and permissions.","args-file")}}function Ni(){try{if(process.stdin.isTTY)throw se("missing-input-value","--stdin requires piped UTF-8 text, for example: neocortex-client invoke --stdin < synthetic.story.md","stdin");return Te(0)}catch(e){throw e instanceof et?e:se("missing-input-value","--stdin could not be read as UTF-8 text. Pipe command text into stdin and retry.","stdin")}}function Li(e,t={}){let r,n=!1,o,i,a="plain",c=!1,l,p,m=!1,w=!1;for(let v=0;v<e.length;v++)switch(e[v]){case"--args":{const h=e[++v];if(h===void 0)throw $e("--args");if(r!==void 0)throw se("multiple-input-sources","Provide --args only once. Use one explicit invoke input source.","args");r=h;break}case"--stdin":if(n)throw se("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 $e("--args-file");if(o!==void 0)throw se("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 $e("--project-root");i=h;break}case"--format":{const h=e[++v];if(h===void 0)throw $e("--format");if(h!=="json"&&h!=="plain")throw se("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 $e("--server-url");l=h;break}case"--platform-target":{const h=e[++v];if(h===void 0)throw $e("--platform-target");p=h;break}case"--strict-read-only":m=!0;break;case"--private-execution-beta":w=!0;break;default:throw se("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 se("missing-input-value",$r);if(f.length>1)throw se("multiple-input-sources",`Choose only one invoke input source; received ${f.join(", ")}.`);const d=f[0],I=d==="args"?r:d==="stdin"?(t.readStdin??Ni)():(t.readArgsFile??ki)(o);let A;try{A=qe(d,I)}catch(v){throw v instanceof Nn?se("invalid-utf8",v.message,d):v}const C=d==="args"?li(A.rawArgs):Z(A.rawArgs),j=C.args===A.rawArgs?A:qe(d,C.args);return{args:C.args,inputSource:d,inputEnvelope:j,projectRoot:i,format:a,watch:c||C.watch,commandLevelWatch:C.metadata,serverUrl:l,platformTarget:p,strictReadOnly:m,privateExecutionBeta:w}}function Wr(e,t){return t?.active?{...e??{},commandLevelWatch:t,serverHeldStream:!1}:e}function Pi(e,t,r=process.stdout,n=process.stderr){if(t.format==="json"){const a=yt(e.instructions,e.metadata),c=Wr(a.metadata,t.commandLevelWatch);if(t.watch){r.write(JSON.stringify({type:"invoke_result",instructions:a.instructions,metadata:c,publicSafe:!0})+`
162
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+`
163
+ `);return}const o=yt(e.instructions,e.metadata),i=Wr(o.metadata,t.commandLevelWatch);r.write(o.instructions+`
164
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};
165
+ `)}function Di(e){const t=()=>e.abort();return process.once("SIGINT",t),process.once("SIGTERM",t),()=>{process.removeListener("SIGINT",t),process.removeListener("SIGTERM",t)}}async function Es(e){if(xi(e))return process.stdout.write(`${Oi}
166
+ `),0;let t;try{t=Li(e)}catch(n){if(n instanceof et)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(mn(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 yn({args:t.args,projectRoot:gt(t.projectRoot),format:t.format,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})).exitCode;const r=await bi({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:de(r.error??"",ke),...typeof o?.reason=="string"?{reason:de(o.reason,80)}:{},...typeof o?.source=="string"?{source:de(o.source,20)}:{},...Number.isSafeInteger(o?.byteLength)?{byte_length:o.byteLength}:{},...typeof o?.remediation=="string"?{remediation:de(o.remediation,ke)}:{}})+`
169
+ `),r.exitCode}if(Pi(r,t),t.watch){const n=new AbortController,o=Di(n);try{const i=Si(r.metadata,t.args);i.disabled?Qo(i.reasonCodes??[Y.TARGET_UNRESOLVED],t.args,t.format,process.stdout,t.privateExecutionBeta):await ei({projectRoot:gt(t.projectRoot),format:t.format,strictReadOnly:t.strictReadOnly,protectedOutput:t.privateExecutionBeta,...i,signal:n.signal})}finally{o()}}return 0}export{Oi as INVOKE_HELP_TEXT,rr as INVOKE_PAYLOAD_LIMIT_BYTES,ft as INVOKE_PAYLOAD_WARNING_THRESHOLD_BYTES,et as InvokeCliInputError,It as InvokePayloadTooLargeError,Et as InvokeStructuralContextTooLargeError,we as StateSnapshotIntegrityError,ms as __resetSchemaDriftWarnedForTests,Ri as acknowledgeMaterializedPendingEpicClaims,no as admitClientInvocation,_r as assertEpicAwareStateShapeBeforeRepair,No as buildSignedInvokeAttempt,to as clearPendingEpicIdempotencyKey,wo as collectInvokeP205Authorities,Cr as collectStateSnapshot,Ve as computeInvokeRequestBodySizeBytes,ys as createFullStateSnapshotScope,Ct as createInvokePayloadTelemetry,fo as detectStateSchemaDrift,Ti as extractPreFlightTrigger,eo as getOrCreatePendingEpicIdempotencyKey,Or as guardInvokeRequestBodySize,bi as invoke,Es as invokeCliHandler,Er as isEpicAwareCommandId,$o as maybeEmitInvokePayloadSizeWarning,Wo as maybeRunInvokeRunnerAutoBootstrap,Li as parseInvokeCliOptions,br as postMaterializationJson,ar as recordPendingEpicReservation,li as resolveInvokeCommandLevelWatch,gt as resolveInvokeProjectRoot,Oo as resolveInvokeTransportErrorCode,Si as resolveInvokeWatchTarget,yt as sanitizeInvokeCliOutput,wi as sendEpicClaimAcknowledgement,Br as sendInvokeRequest,Is as sendPrivateExecutionCancelRequest,Ai as sendPrivateExecutionConsumeRequest,co as shouldCollectProjectEvidenceForInvoke,ei as watchContinuityProcessingSummaries,Pi as writeInvokeCliSuccessOutput};