@ornexus/neocortex 4.60.50 → 4.60.52

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,22 +1,22 @@
1
- import{createHash as Ne,randomUUID as qe}from"node:crypto";import{execFileSync as ke}from"node:child_process";import{existsSync as Ce,readFileSync as Ae,renameSync as Ln,unlinkSync as xn,writeFileSync as Et,mkdirSync as Ct,statSync as Dn}from"node:fs";import{join as te}from"node:path";import{homedir as Pe}from"node:os";import{LicenseClient as Pn}from"../license/license-client.js";import{EncryptedCache as Ke}from"../cache/encrypted-cache.js";import{NoOpCache as At}from"../types/index.js";import{resolveClientPreFlightTrigger as St,TierAwareClient as jn}from"../tier/tier-aware-client.js";import{COMMAND_REGISTRY_CHECKSUM as me,COMMAND_REGISTRY_VERSION as Ie,GENERATED_CLIENT_COMMANDS as Mn}from"../generated/command-registry.generated.js";import{loadSecureConfig as Rt}from"../config/secure-config.js";import{DEFAULT_SERVER_URL as Un}from"../constants.js";import{detectFirstRunLocale as Vn,renderFirstRunMessage as Bn}from"../i18n/first-run.js";import{humanizeError as wt,formatHumanizedError as Tt,detectErrorLocale as bt}from"../errors/error-messages.js";import{degradeStateSnapshotForPayloadLimit as $n,projectStateSnapshotForInvoke as vt,projectStateSnapshotResultV2ForInvoke as Hn}from"../state/project-state-snapshot.js";import{isInlineYoloMaterialization as Wn,maybeRepairStateJsonBeforeInvoke as Fn,StateRepairHardStopError as Gn}from"../state/state-json-repair.js";import{StructuralDagError as Ot}from"../state/structural-dag-projection.js";import{RUNNER_BOOTSTRAP_POLICY_REASON_CODES as Yn,classifyRunnerBootstrapPolicyFromArgs as Jn}from"../continuity/runner-bootstrap-policy.js";import{RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES as zn,ensureRunnerSchedulerBootstrap as qn}from"../runner/scheduler.js";import{CONTINUITY_INVOKE_WATCH_DEFAULT_LIMIT as Nt,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_IDLE_POLLS as kt,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_POLLS as Lt,CONTINUITY_INVOKE_WATCH_DEFAULT_POLL_INTERVAL_MS as xt,openContinuityClientStateStore as Kn}from"../continuity/continuity-client-state-store.js";import{isLocalJobsConsoleArgs as Xn,runLocalJobsConsoleCommand as Zn}from"../runner/local-console.js";import{detectNativeHostAttestation as Qn,detectPlatform as er}from"../adapters/platform-detector.js";import{signNxInvokeRequest as tr}from"../../../shared/dist/nx-invoke-signature.js";import{CLIENT_VERSION as Se}from"../version.js";import{createCapabilityCache as Dt,executeInvokeQueryTransport as Pt,executeSecondaryNetworkMutation as nr}from"../effects/invoke-effect-gateways.js";import{STRICT_READ_ONLY_POLICY as rr,STRICT_READ_ONLY_CLIENT_PROJECTION as jt,STRICT_READ_ONLY_SERVER_PROJECTION as or,StrictReadOnlyError as Re,canonicalizeInvokeEffects as ir,createInvokeEffectContext as sr,verifyStrictReadOnlyReceipt as ar}from"../../../shared/dist/strict-readonly.js";import{admitInvocation as cr,assertInvokeInputEnvelopeV2 as dr,assertProjectIdentityMigrationReceiptV1 as ur,buildProjectIdentityPublicDiagnostic as we,createInvocationAdmissionReceipt as lr,projectInvokeInputEvidenceV1 as Mt,verifyStrictDiagnoseReceiptV1 as pr}from"../../../shared/dist/invocation/index.js";import{buildInvokeInputEnvelope as je,InvokeInputDecodeError as fr}from"../invocation/invoke-input.js";import{acknowledgeProjectIdentityMigration as gr,finalizeProjectIdentityMigration as hr,prepareProjectIdentityMigration as mr,ProjectIdentityMigrationError as Xe,readProjectIdentityMigrationPhase as Ir}from"../migrations/project-identity.js";import{probeProjectIdentityMigrationCapability as yr}from"../migrations/project-identity-capability.js";import{normalizeYoloopStoryPlanningEvidence as _r}from"../../../shared/dist/yoloop/planning-graph.js";import{normalizeContinuousWriteRef as Me}from"../../../shared/dist/yoloop/wave-decision-receipt.js";import{applyGitLifecycleRuntimeOverlay as Ut,classifyGitLifecycleStoryCheckpointProjectionSync as Er,ensureGitLifecycleRuntimeInitialized as Cr,executeP205TransientAuthorities as Ar,persistGitLifecycleGraphAuthority as Sr,P205_COMPLETE_COMMAND as Rr,gitLifecycleStoryWriteSet as Vt,readGitLifecycleRuntimeSync as Ze,verifyLegacyCheckpointMigrationCandidateSync as wr}from"../git/git-lifecycle-store.js";const Ue=te(Pe(),".neocortex"),Qe=te(Ue,"cache"),Bt=te(Qe,"menu-cache.json"),$t=1440*60*1e3,Ht=3e4,Wt=256*1024,Ft=Wt,Gt=.8,de="[REDACTED]",Tr=1e5,ye=2e3,br=200,vr=200,Or=12,Nr=/(?:promptBody|workflow|workflowGraph|stepBody|privateUrl|rawLog|secret|credential|licenseKey|apiKey|internalRouting|serverOnly|proprietary|protected)/i,kr=/(?:PRIVATE|PROTECTED|SERVER_ONLY)[-_\s]*(?:PROMPT|PROMPT_BODY|WORKFLOW|WORKFLOW_GRAPH|STEP_BODY|STEP|ROUTING)\s*[:=][^\n\r]*/gi,Lr=/(?:https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|private|internal)[^\s"'<>]*|raw[_-]?log|transcript|stack\s*trace|stderr:|stdout:|system prompt|prompt body|workflow body|step body|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|VENDOR_CORPUS|P180[_-]?SYNTHETIC[_-]?CONTINUITY|P185[_-]?SYNTHETIC[_-]?CONTINUITY|P187[_-]?SYNTHETIC[_-]?(?:CONTINUITY|RUNNER|WATCH)|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=)/gi,et=Math.floor(Wt*Gt),Yt=te(Ue,".first-run-shown"),xr="pending-epic-claims.json",Jt=64;function zt(e){return te(e,".neocortex",xr)}function Ve(e){const t=zt(e);if(!Ce(t))return{schemaVersion:1,operations:{}};const n=JSON.parse(Ae(t,"utf8"));if(!n||typeof n!="object"||Array.isArray(n))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const r=n;if(r.schemaVersion!==1||!r.operations||typeof r.operations!="object"||Array.isArray(r.operations))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(Object.keys(r.operations).length>Jt)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");for(const[o,i]of Object.entries(r.operations)){if(!/^[a-f0-9]{64}$/.test(o)||!i||typeof i!="object"||Array.isArray(i))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const s=i;if(typeof s.idempotencyKey!="string"||!/^[0-9a-f-]{36}$/.test(s.idempotencyKey)||typeof s.createdAt!="string")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(s.claimId!==void 0&&(typeof s.claimId!="string"||!/^[0-9a-f-]{36}$/.test(s.claimId))||s.epicId!==void 0&&(typeof s.epicId!="string"||!/^P[1-9][0-9]*$/.test(s.epicId))||s.claimId===void 0!=(s.epicId===void 0))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE")}return n}function tt(e,t){const n=zt(e);Ct(te(e,".neocortex"),{recursive:!0,mode:448});const r=`${n}.${process.pid}.${qe()}.tmp`;Et(r,`${JSON.stringify(t)}
2
- `,{encoding:"utf8",mode:384,flag:"wx"}),Ln(r,n)}function Dr(e){return Ne("sha256").update(`nx-epic-logical-operation-v1\0${JSON.stringify({command:"create-epic",args:e})}`,"utf8").digest("hex")}function Pr(e,t){const n=Dr(t),r=Ve(e),o=r.operations[n];if(o)return{key:o.idempotencyKey,fingerprint:n};if(Object.keys(r.operations).length>=Jt)throw new Error("EPIC_CLAIM_CAPACITY_EXCEEDED");const i=qe(),s={...r.operations,[n]:{idempotencyKey:i,createdAt:new Date().toISOString()}};return tt(e,{schemaVersion:1,operations:s}),{key:i,fingerprint:n}}function jr(e,t){const n=Ve(e);if(!n.operations[t])return;const r={...n.operations};delete r[t],tt(e,{schemaVersion:1,operations:r})}function Mr(e,t,n,r){if(!/^[0-9a-f-]{36}$/.test(n)||!/^P[1-9][0-9]*$/.test(r))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const o=Ve(e),i=o.operations[t];if(!i)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");tt(e,{schemaVersion:1,operations:{...o.operations,[t]:{...i,claimId:n,epicId:r}}})}function Ur(){try{if(Ce(Yt))return;const e=Vn(),t=Bn(e);process.stderr.write(t);try{Ct(Ue,{recursive:!0}),Et(Yt,new Date().toISOString(),"utf-8")}catch{}}catch{}}function nt(e,t=process.cwd()){return e&&e.trim().length>0?e:t}function Vr(e){return cr(e,{registryVersion:Ie,registryChecksum:me})}const Br=new Set(["completed","aborted","cancelled"]),$r=new Set(["watch-target-missing","watch-target-malformed","watch-target-ambiguous","watch-target-multiple"]),$=Object.freeze({COMPLETED:"invoke-watch-completed",CANCELLED:"invoke-watch-cancelled",IDLE_TIMEOUT:"invoke-watch-idle-timeout",MAX_POLLS:"invoke-watch-max-polls",STORE_UNAVAILABLE:"invoke-watch-store-unavailable",TARGET_UNRESOLVED:"invoke-watch-target-unresolved"}),F=Object.freeze({MISSING:"watch-target-missing",MALFORMED:"watch-target-malformed",AMBIGUOUS:"watch-target-ambiguous",CONFLICT:"watch-target-conflicting-evidence",SERVER_HELD_STREAM:"watch-target-server-held-stream-unsupported"}),O=Object.freeze({OK:"continuity-ok",WATCH_NO_SUMMARIES_YET:"watch-no-summaries-yet",WATCH_CURSOR_ADVANCED:"watch-cursor-advanced",WATCH_CURSOR_UNCHANGED:"watch-cursor-unchanged",WATCH_RENDER_PENDING:"watch-render-pending",WATCH_STOP_IDLE_LIMIT_REACHED:"watch-stop-idle-limit-reached",WATCH_STOP_MAX_POLLS_REACHED:"watch-stop-max-polls-reached",WATCH_TARGET_UNRESOLVED:"watch-target-unresolved",WATCH_SNAPSHOT_UNAVAILABLE:"watch-snapshot-unavailable",WATCH_EVIDENCE_UNAVAILABLE:"watch-evidence-unavailable"}),qt=240,Hr=/(https?:\/\/\S+|ghp_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|-----BEGIN [A-Z ]*PRIVATE KEY-----|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=|raw[_-]?log|transcript|stack\s*trace|stderr:|stdout:|system prompt|prompt body|workflow body|step body|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|VENDOR_CORPUS|P180[_-]?SYNTHETIC[_-]?CONTINUITY|P185[_-]?SYNTHETIC[_-]?CONTINUITY|P187[_-]?SYNTHETIC[_-]?(?:CONTINUITY|RUNNER|WATCH))/i;function Wr(e){return e.replace(/[\w.+-]+@[\w-]+\.[\w.-]+/g,de).replace(/(?:sk|pk|whsec|nxk)[-_](?:test|live|ant|proj|pro|free|enterprise)?[-_]?[A-Za-z0-9_-]{16,}/g,de).replace(/NX-[FPE]-[a-f0-9]{24}-[a-f0-9]{4}/g,de).replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,de).replace(kr,de).replace(Lr,de)}function Z(e,t){const n=Wr(e);return n.length<=t?n:`${n.slice(0,t)}\u2026[TRUNCATED:${n.length-t}]`}function rt(e,t=0,n=new WeakSet){if(t>Or)return"[MAX_DEPTH]";if(e==null)return e;if(typeof e=="string")return Z(e,ye);if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e=="boolean")return e;if(typeof e=="bigint")return String(e);if(!(typeof e=="function"||typeof e=="symbol")&&typeof e=="object"){if(n.has(e))return"[CIRCULAR]";n.add(e);try{if(Array.isArray(e))return e.slice(0,br).map(o=>rt(o,t+1,n));const r={};for(const[o,i]of Object.entries(e).slice(0,vr)){if(Nr.test(o)){r[o]=de;continue}const s=rt(i,t+1,n);s!==void 0&&(r[o]=s)}return r}finally{n.delete(e)}}}function ot(e,t){return{instructions:Z(e??"",Tr),metadata:t?rt(t):void 0}}class Be extends Error{reason;source;byteLength;code;constructor(t,n,r,o,i){super(n),this.reason=r,this.source=o,this.byteLength=i,this.name="InvokeCliInputError",this.code=t}}function Fr(e){return/^\s*\*?(?:arch-plan|ui-ux-review)(?:\s|$)/i.test(e)&&Gr(e,"--project-evidence")}function Gr(e,t){let n=null,r=-1,o=!1,i=!1;for(let s=0;s<=e.length;s+=1){const c=e[s];if(s===e.length||!n&&/\s/.test(c??"")){if(r>=0&&!o&&e.slice(r,s)===t)return!0;r=-1,o=!1,i=!1;continue}if(r<0&&(r=s),i){i=!1;continue}if(c==="\\"){i=!0;continue}(c==='"'||c==="'")&&(o=!0,n=n===c?null:n??c)}return!1}const Yr=/(?:^|\s)codex(?:-cli)?\s+([A-Za-z0-9][A-Za-z0-9._+-]{0,63})(?:\s|$)/i;function Jr(e,t){if(e.targetId!=="codex")return null;const n=t.CODEX_VERSION?.trim();if(n&&/^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/.test(n))return n;try{return ke("codex",["--version"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim().match(Yr)?.[1]??null}catch{return null}}class it extends Error{code="PAYLOAD_TOO_LARGE";telemetry;constructor(t){super(`PAYLOAD_TOO_LARGE: invoke request is ${t.payloadBytes} bytes after deterministic degradation; limit is ${t.limitBytes}. Reduce command input or local state context and retry.`),this.name="InvokePayloadTooLargeError",this.telemetry=t}}class st extends Error{code="STRUCTURAL_CONTEXT_TOO_LARGE";telemetry;constructor(t){super(`STRUCTURAL_CONTEXT_TOO_LARGE: the bounded structural projection is ${t.payloadBytes} bytes; the request limit is strictly below ${t.limitBytes}. Select an explicit epic/story target or split the dependency graph.`),this.name="InvokeStructuralContextTooLargeError",this.telemetry=t}}let at=!1;function zr(e){const t=[];if(!e||typeof e!="object")return t;const n=e,r=n.planning;if(r&&(r.current!==void 0||Array.isArray(r.history))&&t.push({code:"PLANNING_LEGACY",message:"legacy `planning.current`/`planning.history` detected (not read by v1 orchestrator)"}),Array.isArray(n.stories)&&t.push({code:"STORIES_AS_ARRAY",message:"`stories` is an Array (expected Object keyed by story ID)"}),n.epics&&typeof n.epics=="object"&&!Array.isArray(n.epics))for(const[i,s]of Object.entries(n.epics)){const c=s;if(c&&c.stories!==void 0&&!Array.isArray(c.stories)){t.push({code:"EPIC_STORIES_NOT_ARRAY",message:`epic "${i}" has non-array \`stories\` field (expected string[] of story IDs)`});break}}const o=n.epics&&typeof n.epics=="object"&&Object.keys(n.epics).length>0||n.stories&&typeof n.stories=="object"&&!Array.isArray(n.stories)&&Object.keys(n.stories).length>0||Array.isArray(n.stories)||r&&r.current!==void 0;return n.schema_version===void 0?o&&t.push({code:"SCHEMA_VERSION_MISSING",message:"`schema_version` field missing (expected: `schema_version: 1`)"}):n.schema_version!==1&&t.push({code:"SCHEMA_VERSION_OUTDATED",message:`schema_version=${String(n.schema_version)} (expected: 1)`}),t}function qr(e){if(!(at||e.length===0)){at=!0;try{const t=e.map(n=>` - ${n.message}`).join(`
1
+ import{createHash as Ne,randomUUID as qe}from"node:crypto";import{execFileSync as ke}from"node:child_process";import{existsSync as Ce,readFileSync as Ae,renameSync as Ln,unlinkSync as xn,writeFileSync as Et,mkdirSync as Ct,statSync as Dn}from"node:fs";import{join as te}from"node:path";import{homedir as Pe}from"node:os";import{LicenseClient as Pn}from"../license/license-client.js";import{EncryptedCache as Ke}from"../cache/encrypted-cache.js";import{NoOpCache as At}from"../types/index.js";import{resolveClientPreFlightTrigger as St,TierAwareClient as jn}from"../tier/tier-aware-client.js";import{COMMAND_REGISTRY_CHECKSUM as me,COMMAND_REGISTRY_VERSION as Ie,GENERATED_CLIENT_COMMANDS as Mn}from"../generated/command-registry.generated.js";import{loadSecureConfig as Rt}from"../config/secure-config.js";import{DEFAULT_SERVER_URL as Un}from"../constants.js";import{detectFirstRunLocale as Vn,renderFirstRunMessage as Bn}from"../i18n/first-run.js";import{humanizeError as wt,formatHumanizedError as Tt,detectErrorLocale as bt}from"../errors/error-messages.js";import{degradeStateSnapshotForPayloadLimit as $n,projectStateSnapshotForInvoke as vt,projectStateSnapshotResultV2ForInvoke as Wn}from"../state/project-state-snapshot.js";import{isInlineYoloMaterialization as Hn,maybeRepairStateJsonBeforeInvoke as Fn,StateRepairHardStopError as Gn}from"../state/state-json-repair.js";import{StructuralDagError as Ot}from"../state/structural-dag-projection.js";import{RUNNER_BOOTSTRAP_POLICY_REASON_CODES as Yn,classifyRunnerBootstrapPolicyFromArgs as Jn}from"../continuity/runner-bootstrap-policy.js";import{RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES as zn,ensureRunnerSchedulerBootstrap as qn}from"../runner/scheduler.js";import{CONTINUITY_INVOKE_WATCH_DEFAULT_LIMIT as Nt,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_IDLE_POLLS as kt,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_POLLS as Lt,CONTINUITY_INVOKE_WATCH_DEFAULT_POLL_INTERVAL_MS as xt,openContinuityClientStateStore as Kn}from"../continuity/continuity-client-state-store.js";import{isLocalJobsConsoleArgs as Xn,runLocalJobsConsoleCommand as Zn}from"../runner/local-console.js";import{detectNativeHostAttestation as Qn,detectPlatform as er}from"../adapters/platform-detector.js";import{signNxInvokeRequest as tr}from"../../../shared/dist/nx-invoke-signature.js";import{CLIENT_VERSION as Se}from"../version.js";import{createCapabilityCache as Dt,executeInvokeQueryTransport as Pt,executeSecondaryNetworkMutation as nr}from"../effects/invoke-effect-gateways.js";import{STRICT_READ_ONLY_POLICY as rr,STRICT_READ_ONLY_CLIENT_PROJECTION as jt,STRICT_READ_ONLY_SERVER_PROJECTION as or,StrictReadOnlyError as Re,canonicalizeInvokeEffects as ir,createInvokeEffectContext as sr,verifyStrictReadOnlyReceipt as ar}from"../../../shared/dist/strict-readonly.js";import{admitInvocation as cr,assertInvokeInputEnvelopeV2 as dr,assertProjectIdentityMigrationReceiptV1 as ur,buildProjectIdentityPublicDiagnostic as we,createInvocationAdmissionReceipt as lr,projectInvokeInputEvidenceV1 as Mt,verifyStrictDiagnoseReceiptV1 as pr}from"../../../shared/dist/invocation/index.js";import{buildInvokeInputEnvelope as je,InvokeInputDecodeError as fr}from"../invocation/invoke-input.js";import{acknowledgeProjectIdentityMigration as gr,finalizeProjectIdentityMigration as hr,prepareProjectIdentityMigration as mr,ProjectIdentityMigrationError as Xe,readProjectIdentityMigrationPhase as Ir}from"../migrations/project-identity.js";import{probeProjectIdentityMigrationCapability as yr}from"../migrations/project-identity-capability.js";import{normalizeYoloopStoryPlanningEvidence as _r}from"../../../shared/dist/yoloop/planning-graph.js";import{normalizeContinuousWriteRef as Me}from"../../../shared/dist/yoloop/wave-decision-receipt.js";import{applyGitLifecycleRuntimeOverlay as Ut,classifyGitLifecycleStoryCheckpointProjectionSync as Er,ensureGitLifecycleRuntimeInitialized as Cr,executeP205TransientAuthorities as Ar,persistGitLifecycleGraphAuthority as Sr,P205_COMPLETE_COMMAND as Rr,gitLifecycleStoryWriteSet as Vt,readGitLifecycleRuntimeSync as Ze,verifyLegacyCheckpointMigrationCandidateSync as wr}from"../git/git-lifecycle-store.js";const Ue=te(Pe(),".neocortex"),Qe=te(Ue,"cache"),Bt=te(Qe,"menu-cache.json"),$t=1440*60*1e3,Wt=3e4,Ht=256*1024,Ft=Ht,Gt=.8,de="[REDACTED]",Tr=1e5,ye=2e3,br=200,vr=200,Or=12,Nr=/(?:promptBody|workflow|workflowGraph|stepBody|privateUrl|rawLog|secret|credential|licenseKey|apiKey|internalRouting|serverOnly|proprietary|protected)/i,kr=/(?:PRIVATE|PROTECTED|SERVER_ONLY)[-_\s]*(?:PROMPT|PROMPT_BODY|WORKFLOW|WORKFLOW_GRAPH|STEP_BODY|STEP|ROUTING)\s*[:=][^\n\r]*/gi,Lr=/(?:https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|private|internal)[^\s"'<>]*|raw[_-]?log|transcript|stack\s*trace|stderr:|stdout:|system prompt|prompt body|workflow body|step body|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|VENDOR_CORPUS|P180[_-]?SYNTHETIC[_-]?CONTINUITY|P185[_-]?SYNTHETIC[_-]?CONTINUITY|P187[_-]?SYNTHETIC[_-]?(?:CONTINUITY|RUNNER|WATCH)|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=)/gi,et=Math.floor(Ht*Gt),Yt=te(Ue,".first-run-shown"),xr="pending-epic-claims.json",Jt=64;function zt(e){return te(e,".neocortex",xr)}function Ve(e){const t=zt(e);if(!Ce(t))return{schemaVersion:1,operations:{}};const n=JSON.parse(Ae(t,"utf8"));if(!n||typeof n!="object"||Array.isArray(n))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const r=n;if(r.schemaVersion!==1||!r.operations||typeof r.operations!="object"||Array.isArray(r.operations))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(Object.keys(r.operations).length>Jt)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");for(const[o,i]of Object.entries(r.operations)){if(!/^[a-f0-9]{64}$/.test(o)||!i||typeof i!="object"||Array.isArray(i))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const s=i;if(typeof s.idempotencyKey!="string"||!/^[0-9a-f-]{36}$/.test(s.idempotencyKey)||typeof s.createdAt!="string")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(s.claimId!==void 0&&(typeof s.claimId!="string"||!/^[0-9a-f-]{36}$/.test(s.claimId))||s.epicId!==void 0&&(typeof s.epicId!="string"||!/^P[1-9][0-9]*$/.test(s.epicId))||s.claimId===void 0!=(s.epicId===void 0))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE")}return n}function tt(e,t){const n=zt(e);Ct(te(e,".neocortex"),{recursive:!0,mode:448});const r=`${n}.${process.pid}.${qe()}.tmp`;Et(r,`${JSON.stringify(t)}
2
+ `,{encoding:"utf8",mode:384,flag:"wx"}),Ln(r,n)}function Dr(e){return Ne("sha256").update(`nx-epic-logical-operation-v1\0${JSON.stringify({command:"create-epic",args:e})}`,"utf8").digest("hex")}function Pr(e,t){const n=Dr(t),r=Ve(e),o=r.operations[n];if(o)return{key:o.idempotencyKey,fingerprint:n};if(Object.keys(r.operations).length>=Jt)throw new Error("EPIC_CLAIM_CAPACITY_EXCEEDED");const i=qe(),s={...r.operations,[n]:{idempotencyKey:i,createdAt:new Date().toISOString()}};return tt(e,{schemaVersion:1,operations:s}),{key:i,fingerprint:n}}function jr(e,t){const n=Ve(e);if(!n.operations[t])return;const r={...n.operations};delete r[t],tt(e,{schemaVersion:1,operations:r})}function Mr(e,t,n,r){if(!/^[0-9a-f-]{36}$/.test(n)||!/^P[1-9][0-9]*$/.test(r))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const o=Ve(e),i=o.operations[t];if(!i)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");tt(e,{schemaVersion:1,operations:{...o.operations,[t]:{...i,claimId:n,epicId:r}}})}function Ur(){try{if(Ce(Yt))return;const e=Vn(),t=Bn(e);process.stderr.write(t);try{Ct(Ue,{recursive:!0}),Et(Yt,new Date().toISOString(),"utf-8")}catch{}}catch{}}function nt(e,t=process.cwd()){return e&&e.trim().length>0?e:t}function Vr(e){return cr(e,{registryVersion:Ie,registryChecksum:me})}const Br=new Set(["completed","aborted","cancelled"]),$r=new Set(["watch-target-missing","watch-target-malformed","watch-target-ambiguous","watch-target-multiple"]),$=Object.freeze({COMPLETED:"invoke-watch-completed",CANCELLED:"invoke-watch-cancelled",IDLE_TIMEOUT:"invoke-watch-idle-timeout",MAX_POLLS:"invoke-watch-max-polls",STORE_UNAVAILABLE:"invoke-watch-store-unavailable",TARGET_UNRESOLVED:"invoke-watch-target-unresolved"}),F=Object.freeze({MISSING:"watch-target-missing",MALFORMED:"watch-target-malformed",AMBIGUOUS:"watch-target-ambiguous",CONFLICT:"watch-target-conflicting-evidence",SERVER_HELD_STREAM:"watch-target-server-held-stream-unsupported"}),N=Object.freeze({OK:"continuity-ok",WATCH_NO_SUMMARIES_YET:"watch-no-summaries-yet",WATCH_CURSOR_ADVANCED:"watch-cursor-advanced",WATCH_CURSOR_UNCHANGED:"watch-cursor-unchanged",WATCH_RENDER_PENDING:"watch-render-pending",WATCH_STOP_IDLE_LIMIT_REACHED:"watch-stop-idle-limit-reached",WATCH_STOP_MAX_POLLS_REACHED:"watch-stop-max-polls-reached",WATCH_TARGET_UNRESOLVED:"watch-target-unresolved",WATCH_SNAPSHOT_UNAVAILABLE:"watch-snapshot-unavailable",WATCH_EVIDENCE_UNAVAILABLE:"watch-evidence-unavailable"}),qt=240,Wr=/(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 Hr(e){return e.replace(/[\w.+-]+@[\w-]+\.[\w.-]+/g,de).replace(/(?:sk|pk|whsec|nxk)[-_](?:test|live|ant|proj|pro|free|enterprise)?[-_]?[A-Za-z0-9_-]{16,}/g,de).replace(/NX-[FPE]-[a-f0-9]{24}-[a-f0-9]{4}/g,de).replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,de).replace(kr,de).replace(Lr,de)}function Z(e,t){const n=Hr(e);return n.length<=t?n:`${n.slice(0,t)}\u2026[TRUNCATED:${n.length-t}]`}function rt(e,t=0,n=new WeakSet){if(t>Or)return"[MAX_DEPTH]";if(e==null)return e;if(typeof e=="string")return Z(e,ye);if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e=="boolean")return e;if(typeof e=="bigint")return String(e);if(!(typeof e=="function"||typeof e=="symbol")&&typeof e=="object"){if(n.has(e))return"[CIRCULAR]";n.add(e);try{if(Array.isArray(e))return e.slice(0,br).map(o=>rt(o,t+1,n));const r={};for(const[o,i]of Object.entries(e).slice(0,vr)){if(Nr.test(o)){r[o]=de;continue}const s=rt(i,t+1,n);s!==void 0&&(r[o]=s)}return r}finally{n.delete(e)}}}function ot(e,t){return{instructions:Z(e??"",Tr),metadata:t?rt(t):void 0}}class Be extends Error{reason;source;byteLength;code;constructor(t,n,r,o,i){super(n),this.reason=r,this.source=o,this.byteLength=i,this.name="InvokeCliInputError",this.code=t}}function Fr(e){return/^\s*\*?(?:arch-plan|ui-ux-review)(?:\s|$)/i.test(e)&&Gr(e,"--project-evidence")}function Gr(e,t){let n=null,r=-1,o=!1,i=!1;for(let s=0;s<=e.length;s+=1){const c=e[s];if(s===e.length||!n&&/\s/.test(c??"")){if(r>=0&&!o&&e.slice(r,s)===t)return!0;r=-1,o=!1,i=!1;continue}if(r<0&&(r=s),i){i=!1;continue}if(c==="\\"){i=!0;continue}(c==='"'||c==="'")&&(o=!0,n=n===c?null:n??c)}return!1}const Yr=/(?:^|\s)codex(?:-cli)?\s+([A-Za-z0-9][A-Za-z0-9._+-]{0,63})(?:\s|$)/i;function Jr(e,t){if(e.targetId!=="codex")return null;const n=t.CODEX_VERSION?.trim();if(n&&/^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/.test(n))return n;try{return ke("codex",["--version"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim().match(Yr)?.[1]??null}catch{return null}}class it extends Error{code="PAYLOAD_TOO_LARGE";telemetry;constructor(t){super(`PAYLOAD_TOO_LARGE: invoke request is ${t.payloadBytes} bytes after deterministic degradation; limit is ${t.limitBytes}. Reduce command input or local state context and retry.`),this.name="InvokePayloadTooLargeError",this.telemetry=t}}class st extends Error{code="STRUCTURAL_CONTEXT_TOO_LARGE";telemetry;constructor(t){super(`STRUCTURAL_CONTEXT_TOO_LARGE: the bounded structural projection is ${t.payloadBytes} bytes; the request limit is strictly below ${t.limitBytes}. Select an explicit epic/story target or split the dependency graph.`),this.name="InvokeStructuralContextTooLargeError",this.telemetry=t}}let at=!1;function zr(e){const t=[];if(!e||typeof e!="object")return t;const n=e,r=n.planning;if(r&&(r.current!==void 0||Array.isArray(r.history))&&t.push({code:"PLANNING_LEGACY",message:"legacy `planning.current`/`planning.history` detected (not read by v1 orchestrator)"}),Array.isArray(n.stories)&&t.push({code:"STORIES_AS_ARRAY",message:"`stories` is an Array (expected Object keyed by story ID)"}),n.epics&&typeof n.epics=="object"&&!Array.isArray(n.epics))for(const[i,s]of Object.entries(n.epics)){const c=s;if(c&&c.stories!==void 0&&!Array.isArray(c.stories)){t.push({code:"EPIC_STORIES_NOT_ARRAY",message:`epic "${i}" has non-array \`stories\` field (expected string[] of story IDs)`});break}}const o=n.epics&&typeof n.epics=="object"&&Object.keys(n.epics).length>0||n.stories&&typeof n.stories=="object"&&!Array.isArray(n.stories)&&Object.keys(n.stories).length>0||Array.isArray(n.stories)||r&&r.current!==void 0;return n.schema_version===void 0?o&&t.push({code:"SCHEMA_VERSION_MISSING",message:"`schema_version` field missing (expected: `schema_version: 1`)"}):n.schema_version!==1&&t.push({code:"SCHEMA_VERSION_OUTDATED",message:`schema_version=${String(n.schema_version)} (expected: 1)`}),t}function qr(e){if(!(at||e.length===0)){at=!0;try{const t=e.map(n=>` - ${n.message}`).join(`
3
3
  `);process.stderr.write(`[Neocortex] state.json schema drift detected:
4
4
  ${t}
5
5
  Run \`neocortex *migrate-state --preview\` to inspect or \`neocortex *migrate-state --apply\` to migrate.
6
6
  See docs/arquitetura-software/STATE-JSON-SCHEMA.md for the schema contract.
7
- `)}catch{}}}function Ki(){at=!1}function Kt(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Kr(e){return e==="active"||e==="archived"||e==="rolled-back"||e==="synthetic"||e==="orphan"?e:void 0}function Xt(e){return e==="create-epic"||e==="discovered"?e:void 0}function J(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Xr(e){const t={};let n=!1;for(const r of["contracts","contract_refs","shared_surfaces","adr_refs","nfr_refs","acceptance_depends_on"]){if(e[r]===void 0)continue;const o=e[r];if(!Array.isArray(o)||o.length>128||o.some(i=>Me(i)===void 0)){n=!0;continue}t[r]=o.map(i=>Me(i))}if(e.planning!==void 0)try{if(!m(e.planning))throw new Error("planning-shape");const r=e.planning;for(const s of["claims","semanticArtifacts"]){if(r[s]===void 0)continue;const c=r[s];if(!Array.isArray(c)||c.length>128||c.some(l=>!m(l)||Me(l.ref)===void 0))throw new Error("planning-refs")}if(r.attempts!==void 0&&(!Array.isArray(r.attempts)||r.attempts.length>32))throw new Error("planning-attempts");for(const s of r.attempts??[]){if(!m(s)||!Array.isArray(s.reasonCodes)||s.reasonCodes.length>32||s.reasonCodes.some(c=>typeof c!="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(c)))throw new Error("planning-attempt-reasons");if(s.discoveredClaims!==void 0&&(!Array.isArray(s.discoveredClaims)||s.discoveredClaims.length>128||s.discoveredClaims.some(c=>!m(c)||Me(c.ref)===void 0)))throw new Error("planning-attempt-claims")}const{graphRevision:o,...i}=_r(r);t.planning=i}catch{n=!0}return n&&(t.planning={schemaVersion:1,dependencyBasis:"unknown",claims:[],semanticArtifacts:[]}),t}function m(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ue(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function U(e){if(typeof e!="string")return;const t=e.trim();if(t)return t.replace(/[^a-z0-9_.:-]+/gi,"_").slice(0,120)}function j(e){if(typeof e!="string")return;const t=e.trim(),n=U(e);return n===t?n:void 0}function H(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240)&&/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(t)&&!(t.includes("..")||t.includes("//")||t.includes("@{")||t.endsWith("/")||t.endsWith("."))&&!t.split("/").some(n=>!n||n.startsWith(".")||n.endsWith(".lock")))return t}function A(e){return typeof e=="string"&&/^[0-9a-f]{7,64}$/i.test(e)?e:void 0}function z(e){if(!(typeof e!="string"||e.length>64)&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/.test(e))return Number.isFinite(Date.parse(e))?e:void 0}function le(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240||t.includes("..")))return/^[A-Za-z0-9._:/#\-[\]]+$/.test(t)?t:void 0}function $e(e,t){if(!m(e))return;const n={};for(const r of t){const o=e[r];if(typeof o=="boolean")n[r]=o;else if(typeof o=="number"&&Number.isFinite(o))n[r]=o;else if(typeof o=="string"){const i=U(o);i&&(n[r]=i)}}return Object.keys(n).length>0?n:void 0}function He(e){return e==="epic"||e==="story"?e:void 0}function Zt(e){if(!m(e)||e.schemaVersion!==1)return;const t=j(e.ownerStoryId),n=j(e.sessionId),r=j(e.idempotencyKey),o=z(e.acquiredAt),i=z(e.expiresAt);if(!(!t||!n||!r||!o||!i||Date.parse(i)<=Date.parse(o)))return{schemaVersion:1,ownerStoryId:t,sessionId:n,idempotencyKey:r,acquiredAt:o,expiresAt:i}}function Qt(e){if(!m(e)||e.schemaVersion!==1)return;const t=j(e.storyId),n=j(e.epicId),r=H(e.branch),o=A(e.baseSha),i=A(e.headSha),s=j(e.idempotencyKey),c=z(e.recordedAt),l=J(e.commits).map(A).filter(T=>!!T).slice(0,256),p=J(e.receiptRefs).map(le).filter(T=>!!T).slice(0,256),g=e.dispatchId===void 0?void 0:j(e.dispatchId),C=e.bundleId===void 0?void 0:j(e.bundleId),f=e.bundleDigest===void 0?void 0:A(e.bundleDigest),d=e.graphRevision===void 0?void 0:A(e.graphRevision),h=e.claimRevision===void 0?void 0:j(e.claimRevision),S=Zr(e.qaReceipt),E=Qr(e.reviewReceipt);if(!(!t||!n||!t.startsWith(`${n}.`)||!r||!o||!i||o===i||!s||!c||l.length===0||p.length===0||!Array.isArray(e.commits)||l.length!==e.commits.length||e.commits.length>256||!Array.isArray(e.receiptRefs)||p.length!==e.receiptRefs.length||e.receiptRefs.length>256||e.dispatchId!==void 0&&!g||e.bundleId!==void 0&&!C||e.bundleDigest!==void 0&&(!f||f.length!==64)||e.graphRevision!==void 0&&(!d||d.length!==64)||e.claimRevision!==void 0&&!h||e.qaVerdict!=="passed"&&e.qaVerdict!=="blocked"||!["approved","changes-requested","pending"].includes(String(e.reviewVerdict))||!S||e.reviewVerdict!=="pending"&&!E||e.reviewVerdict==="pending"&&E||S.verdict!==e.qaVerdict||E&&E.verdict!==e.reviewVerdict||!nn(S,{storyId:t,epicId:n,baseSha:o,headSha:i,bundleDigest:f,graphRevision:d})||E&&(!nn(E,{storyId:t,epicId:n,baseSha:o,headSha:i,bundleDigest:f,graphRevision:d})||E.qaReceiptRef!==S?.receiptRef||E.receiptRef===S?.receiptRef)||!p.includes(String(S.receiptRef))||E&&(!p.includes(String(E.receiptRef))||Date.parse(String(E.reviewedAt))<Date.parse(String(S.checkedAt)))))return{schemaVersion:1,storyId:t,epicId:n,branch:r,baseSha:o,headSha:i,idempotencyKey:s,...g?{dispatchId:g}:{},...C?{bundleId:C}:{},...f?{bundleDigest:f}:{},...d?{graphRevision:d}:{},...h?{claimRevision:h}:{},qaVerdict:e.qaVerdict,reviewVerdict:e.reviewVerdict,...S?{qaReceipt:S}:{},...E?{reviewReceipt:E}:{},recordedAt:c,commits:l,receiptRefs:p}}function Zr(e){if(!m(e)||e.schemaVersion!==1||e.kind!=="story_qa_evidence"||e.producer!=="local-yolo-tdd"||e.evidenceVersion!==void 0&&e.evidenceVersion!=="git-immutable-v1"&&e.evidenceVersion!=="p205-execution-v2"||!["passed","blocked"].includes(String(e.verdict)))return;const t=j(e.storyId),n=j(e.epicId),r=A(e.baseSha),o=A(e.headSha),i=A(e.bundleDigest),s=A(e.graphRevision),c=A(e.sourceEvidenceDigest),l=z(e.checkedAt),p=le(e.receiptRef),g=e.evidenceVersion==="p205-execution-v2"&&e.contract==="P205-CI-02"?e.contract:void 0,C=e.evidenceVersion==="p205-execution-v2"&&e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,f=e.evidenceVersion==="p205-execution-v2"?A(e.manifestDigest):void 0,d=e.evidenceVersion==="p205-execution-v2"?A(e.resultDigest):void 0,h=e.evidenceVersion==="p205-execution-v2"?J(e.gateIds).map(j).filter(S=>!!S).slice(0,64):void 0;if(!(!t||!n||!r||!o||!i||i.length!==64||!s||s.length!==64||!c||c.length!==64||!l||!p||e.evidenceVersion==="p205-execution-v2"&&(!g||C!=="node scripts/test-root.mjs --gate complete"||!f||f.length!==64||!d||d.length!==64||!Array.isArray(e.gateIds)||!h||h.length===0||h.length!==e.gateIds.length)))return{schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",...e.evidenceVersion?{evidenceVersion:e.evidenceVersion}:{},storyId:t,epicId:n,...e.evidenceVersion==="p205-execution-v2"?{contract:g,command:C,manifestDigest:f,gateIds:h,resultDigest:d}:{},baseSha:r,headSha:o,bundleDigest:i,graphRevision:s,sourceEvidenceDigest:c,verdict:e.verdict,checkedAt:l,receiptRef:p}}function en(e){if(!m(e)||e.schemaVersion!==1||e.kind!=="story_checkpoint_physical_verification"||e.producer!=="client-p205-transient-v1"||e.publicSafe!==!0||e.verdict!=="verified"&&e.verdict!=="rejected")return;const t=j(e.storyId),n=j(e.epicId),r=H(e.branch),o=A(e.baseSha),i=A(e.headSha),s=A(e.aggregateHeadSha),c=A(e.commitBodyDigest),l=A(e.changedPathsDigest),p=e.claimVerification==="canonical"||e.claimVerification==="legacy-migration"?e.claimVerification:void 0,g=A(e.effectiveClaimRevision),C=e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,f=A(e.manifestDigest),d=J(e.gateIds).map(j).filter(_=>!!_).slice(0,64),h=A(e.resultDigest),S=A(e.graphRevision),E=A(e.executionEvidenceDigest),T=A(e.sourceEvidenceDigest),k=z(e.verifiedAt),w=J(e.reasonCodes).map(j).filter(_=>!!_).slice(0,16);if(!(!t||!n||!r||!o||o.length<40||!i||i.length<40||!s||s.length<40||!c||c.length!==64||!l||l.length!==64||!p||!g||g.length!==64||!C||!f||f.length!==64||!Array.isArray(e.gateIds)||d.length!==e.gateIds.length||!h||h.length!==64||!S||S.length!==64||!E||E.length!==64||!T||T.length!==64||!k||w.length===0||e.verdict==="verified"&&(d.length===0||!w.includes("checkpoint-p205-transient-verified"))))return{schemaVersion:1,kind:"story_checkpoint_physical_verification",producer:"client-p205-transient-v1",storyId:t,epicId:n,branch:r,baseSha:o,headSha:i,aggregateHeadSha:s,commitBodyDigest:c,changedPathsDigest:l,claimVerification:p,effectiveClaimRevision:g,command:C,manifestDigest:f,gateIds:d,resultDigest:h,graphRevision:S,executionEvidenceDigest:E,sourceEvidenceDigest:T,verifiedAt:k,verdict:e.verdict,reasonCodes:w,publicSafe:!0}}function tn(e){const t=["schemaVersion","kind","producer","storyId","epicId","branch","baseSha","headSha","graphRevision","effectiveClaimRevision","sourceEvidenceDigest","verifiedAt","reasonCodes","integrationAuthorized","publicSafe"];if(!m(e)||Object.keys(e).some(f=>!t.includes(f))||e.schemaVersion!==1||e.kind!=="story_scheduling_checkpoint_evidence"||e.producer!=="client-git-physical-v1"||e.integrationAuthorized!==!1||e.publicSafe!==!0)return;const n=j(e.storyId),r=j(e.epicId),o=H(e.branch),i=A(e.baseSha),s=A(e.headSha),c=A(e.graphRevision),l=A(e.effectiveClaimRevision),p=A(e.sourceEvidenceDigest),g=z(e.verifiedAt),C=J(e.reasonCodes).map(j).filter(f=>!!f);if(!(!n||!r||!o||!i||i.length<40||!s||s.length<40||!c||c.length!==64||!l||l.length!==64||!p||p.length!==64||!g||!Array.isArray(e.reasonCodes)||C.length!==1||C[0]!=="checkpoint-git-scheduling-verified"))return{schemaVersion:1,kind:"story_scheduling_checkpoint_evidence",producer:"client-git-physical-v1",storyId:n,epicId:r,branch:o,baseSha:i,headSha:s,graphRevision:c,effectiveClaimRevision:l,sourceEvidenceDigest:p,verifiedAt:g,reasonCodes:C,integrationAuthorized:!1,publicSafe:!0}}function Qr(e){if(!m(e)||e.schemaVersion!==1||e.kind!=="story_review_evidence"||e.producer!=="root-commit-range-review"||!["approved","changes-requested"].includes(String(e.verdict)))return;const t=j(e.storyId),n=j(e.epicId),r=A(e.baseSha),o=A(e.headSha),i=A(e.bundleDigest),s=A(e.graphRevision),c=A(e.sourceEvidenceDigest),l=le(e.qaReceiptRef),p=z(e.reviewedAt),g=le(e.receiptRef);if(!(!t||!n||!r||!o||!i||i.length!==64||!s||s.length!==64||!c||c.length!==64||!l||!p||!g))return{schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:t,epicId:n,baseSha:r,headSha:o,bundleDigest:i,graphRevision:s,sourceEvidenceDigest:c,qaReceiptRef:l,verdict:e.verdict,reviewedAt:p,receiptRef:g}}function nn(e,t){return["storyId","epicId","baseSha","headSha","bundleDigest","graphRevision"].every(n=>e[n]===t[n])}function rn(e){if(!m(e)||e.schemaVersion!==1||e.capturedFromCurrentCheckout!==!0)return;const t=H(e.originBranch),n=A(e.originHeadSha),r=H(e.executionBranch),o=z(e.capturedAt);if(!(!t||!n||n.length<40||!r||!o||t===r))return{schemaVersion:1,originBranch:t,originHeadSha:n,executionBranch:r,capturedFromCurrentCheckout:!0,capturedAt:o}}function on(e){if(!m(e)||e.schemaVersion!==1||e.verdict!=="passed")return;const t=A(e.executionHeadSha),n=A(e.graphRevision),r=z(e.checkedAt),o=le(e.receiptRef),i=J(e.gateIds).map(j).filter(g=>!!g).slice(0,128),s=e.evidenceVersion==="p205-execution-v2"&&e.producer==="local-yolo-tdd"&&e.contract==="P205-CI-02"&&e.command==="node scripts/test-root.mjs --gate complete",c=e.evidenceVersion===void 0&&e.producer===void 0&&e.contract===void 0&&e.command===void 0&&e.manifestDigest===void 0&&e.resultDigest===void 0,l=s?A(e.manifestDigest):void 0,p=s?A(e.resultDigest):void 0;if(!(!t||t.length<40||!n||n.length!==64||!r||!o||i.length===0||!Array.isArray(e.gateIds)||i.length!==e.gateIds.length||e.gateIds.length>128||!c&&!s||s&&(!l||l.length!==64||!p||p.length!==64)))return{schemaVersion:1,...s?{evidenceVersion:"p205-execution-v2",producer:"local-yolo-tdd",contract:"P205-CI-02",command:"node scripts/test-root.mjs --gate complete",manifestDigest:l,resultDigest:p}:{},verdict:"passed",executionHeadSha:t,graphRevision:n,checkedAt:r,receiptRef:o,gateIds:i}}function We(e){if(!m(e)||e.schemaVersion!==1)return;const t=$e(e,["schemaVersion","kind","storyId","epicId","baseSha","headSha","originalBaseSha","originalHeadSha","gitPullRequest","preservesLaterCommits","historyRewrite","recordedAt"])??{},n=J(e.receiptRefs).map(le).filter(o=>!!o).slice(0,256),r=J(e.revertCommits).map(U).filter(o=>!!o).slice(0,256);return{...t,...n.length?{receiptRefs:n}:{},...r.length?{revertCommits:r}:{}}}function sn(e){if(!m(e)||e.schemaVersion!==1||e.publicSafe!==!0)return;const t=j(e.epicId),n=H(e.executionBranch),r=H(e.originBranch),o=A(e.baseSha),i=A(e.executionHeadSha),s=e.mergeSha===void 0?void 0:A(e.mergeSha),c=e.pushedSha===void 0?void 0:A(e.pushedSha),l=j(e.idempotencyKey),p=z(e.attemptStartedAt),g=e.completedAt===void 0?void 0:z(e.completedAt),C=J(e.localGateReceiptRefs).map(le).filter(S=>!!S).slice(0,256),f=J(e.reasonCodes).map(j).filter(S=>!!S).slice(0,64),d=to(e.candidateQa),h=eo(e.providerGuard);if(!(!t||!n||!r||!o||!i||!l||!p||C.length===0||f.length===0||!["direct","single_pr"].includes(String(e.strategy))||!["prepared","merged","pushed","denied_external_gate","blocked_local_or_repo"].includes(String(e.physicalStatus))||typeof e.retryEligible!="boolean"||e.providerGuard!==void 0&&!h||h&&(e.strategy!=="single_pr"||e.physicalStatus!=="pushed"||h.prHeadSha!==s||h.originHeadSha!==o)))return{schemaVersion:1,epicId:t,executionBranch:n,originBranch:r,baseSha:o,executionHeadSha:i,...s?{mergeSha:s}:{},...c?{pushedSha:c}:{},strategy:e.strategy,...ue(e.prNumber)?{prNumber:ue(e.prNumber)}:{},physicalStatus:e.physicalStatus,localGateReceiptRefs:C,idempotencyKey:l,attemptStartedAt:p,...d?{candidateQa:d}:{},...h?{providerGuard:h}:{},...g?{completedAt:g}:{},retryEligible:e.retryEligible,reasonCodes:f,publicSafe:!0}}function eo(e){if(!m(e)||e.schemaVersion!==1||e.provider!=="github"||e.publicSafe!==!0)return;const t=String(e.mode),n=String(e.source),r=t==="recovered_exact_tree"?n==="physical_recovery":t==="strict_up_to_date_expected_head"&&["branch_protection","ruleset","branch_protection_and_ruleset"].includes(n),o=A(e.prHeadSha),i=A(e.originHeadSha),s=z(e.checkedAt);if(!(!r||!o||!i||!s))return{schemaVersion:1,provider:"github",mode:t,source:n,prHeadSha:o,originHeadSha:i,checkedAt:s,publicSafe:!0}}function to(e){if(!m(e)||e.schemaVersion!==1||e.kind!=="epic_merge_candidate_qa"||e.contract!=="P205-CI-02"||e.command!==Rr)return;const n=Object.fromEntries(["originHeadSha","executionHeadSha","mergeSha","treeSha","graphRevision","manifestDigest","resultDigest"].map(s=>[s,A(e[s])])),r=z(e.checkedAt),o=le(e.receiptRef),i=J(e.gateIds).filter(s=>/^[a-z0-9-]+$/.test(s)).slice(0,128);if(!(Object.values(n).some(s=>!s)||!r||!o||i.length===0))return{schemaVersion:1,kind:e.kind,contract:e.contract,command:e.command,...n,checkedAt:r,receiptRef:o,gateIds:i}}function no(e){if(!m(e))return;const t={...U(e.active_epic_id??e.activeEpicId)?{active_epic_id:U(e.active_epic_id??e.activeEpicId)}:{},...U(e.active_story_id??e.activeStoryId)?{active_story_id:U(e.active_story_id??e.activeStoryId)}:{},...U(e.active_step_id??e.activeStepId)?{active_step_id:U(e.active_step_id??e.activeStepId)}:{},...U(e.session_id??e.sessionId)?{session_id:U(e.session_id??e.sessionId)}:{},...U(e.started_at??e.startedAt)?{started_at:U(e.started_at??e.startedAt)}:{}};return Object.keys(t).length>0?t:void 0}function ro(e){const t=$e(e.completionEvidence??e.completion_evidence,["prNumber","pr_number","prState","pr_state","pullRequestState","merged","mergedAt","issueNumber","issue_number","issueState","issue_state","closedAt"]),n=$e(e.issueCloseAudit??e.issue_close_audit,["schema_version","event","storyId","epicId","issueNumber","closedAt","publicSafe","rawLogStorage"]),r=$e(e.scopedCiEvidence??e.scoped_ci_evidence,["schema_version","storyId","epicId","prNumber","finalState","publicSafe","rawLogStorage"]);return{...typeof e.merged=="boolean"?{merged:e.merged}:{},...typeof e.safeToContinueYoloop=="boolean"?{safeToContinueYoloop:e.safeToContinueYoloop}:{},...typeof e.mergeBlockedRemotely=="boolean"?{mergeBlockedRemotely:e.mergeBlockedRemotely}:{},...U(e.physicalMergeStatus)?{physicalMergeStatus:U(e.physicalMergeStatus)}:{},...U(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)?{pr_state:U(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)}:{},...U(e.issue_state??e.issueState??e.workflow_issue_state)?{issue_state:U(e.issue_state??e.issueState??e.workflow_issue_state)}:{},...ue(e.issue_number??e.issueNumber)?{issue_number:ue(e.issue_number??e.issueNumber)}:{},...t?{completionEvidence:t}:{},...n?{issueCloseAudit:n}:{},...r?{scopedCiEvidence:r}:{}}}class pe extends Error{reasonCode;constructor(t){super(t),this.name="StateSnapshotIntegrityError",this.reasonCode=t}}const oo=new Set(["yolo","yoloop","finalize-epic","audit"]);function an(e){return typeof e=="string"&&oo.has(e)}function cn(e,t={}){const n=te(e,".neocortex","state.json");if(!Ce(n))throw new pe("git-lifecycle-state-missing");let r;try{r=JSON.parse(Ae(n,"utf8"))}catch{throw new pe("git-lifecycle-state-corrupt")}if(!m(r)||!m(r.epics)||!m(r.stories))throw new pe("git-lifecycle-state-shape-invalid");const o=Object.values(r.epics).some(i=>m(i)&&(i.branch_mode==="epic"||H(i.execution_branch)!==void 0));if(o)try{Ze(e,{required:!0})}catch(i){const s=i instanceof Error&&/^git-lifecycle-/.test(i.message)?i.message:"git-lifecycle-runtime-invalid";if(t.allowMissingRuntime&&s==="git-lifecycle-runtime-missing")return{lifecycleDeclared:!0,runtimeMissing:!0};throw new pe(s)}return{lifecycleDeclared:o,runtimeMissing:!1}}function dn(e,t={}){const n=te(e,".neocortex","state.json");if(!Ce(n)){if(t.epicAware&&!t.projectless)throw new pe("git-lifecycle-state-missing");return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}let r;try{const f=Ae(n,"utf-8"),d=JSON.parse(f),h=m(d.epics)?d.epics:{},S=Object.values(h).some(_=>m(_)&&(_.branch_mode==="epic"||H(_.execution_branch)!==void 0)),E=Ze(e,{required:!!(t.epicAware&&S&&!t.projectless)});r=Ut(d,E);const T=m(r.stories)?r.stories:{},k=m(r.epics)?r.epics:{},w=m(d.stories)?d.stories:{};for(const[_,R]of Object.entries(T)){const I=m(R)?R:void 0;if(!I?.checkpoint)continue;const M=typeof I.epic_id=="string"?I.epic_id:_.split(".")[0],L=m(k[M])?k[M]:void 0,D=H(L?.execution_branch);if(!D)continue;const V=Er(e,I.checkpoint,_,M,D,t.p205Authorities?.[_],Vt(_,I,m(I.checkpoint)?I.checkpoint:void 0));if(V.kind==="integration-authorized")I.checkpoint_verification=V.verification,delete I.scheduling_checkpoint_evidence;else if(V.kind==="scheduling-only")I.scheduling_checkpoint_evidence=V.evidence,delete I.checkpoint,delete I.checkpoint_verification;else if(V.kind==="rejected"){I.checkpoint_verification=V.verification,delete I.scheduling_checkpoint_evidence;const x=m(w[_])?w[_]:void 0;if(delete I.checkpoint,E.stories[_]?.checkpoint!==void 0)for(const v of["status","last_step","steps_completed"])x&&Object.prototype.hasOwnProperty.call(x,v)?I[v]=structuredClone(x[v]):delete I[v];["done","completed","merged"].includes(String(I.status).toLowerCase())&&(I.status="blocked")}}}catch(f){if(t.epicAware&&!t.projectless){const d=f instanceof Error&&/^git-lifecycle-/.test(f.message)?f.message:"git-lifecycle-state-corrupt";throw new pe(d)}return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}try{const f=zr(r);f.length>0&&qr(f)}catch{}const o=r.config??r.project??{},i=r.stories??{},s={};for(const[f,d]of Object.entries(i))s[f]={id:d.id??f,title:d.title,epic_id:d.epic_id,status:d.status??"backlog",...Xt(d.source)?{source:Xt(d.source)}:{},steps_completed:d.steps_completed??[],last_step:d.last_step??null,branch_name:d.branch_name??null,pr_number:d.pr_number,...He(d.branch_mode)?{branch_mode:He(d.branch_mode)}:{},...Qt(d.checkpoint)?{checkpoint:Qt(d.checkpoint)}:{},...en(d.checkpoint_verification)?{checkpoint_verification:en(d.checkpoint_verification)}:{},...tn(d.scheduling_checkpoint_evidence)?{scheduling_checkpoint_evidence:tn(d.scheduling_checkpoint_evidence)}:{},...We(d.review_request)?{review_request:We(d.review_request)}:{},...We(d.rollback_receipt)?{rollback_receipt:We(d.rollback_receipt)}:{},...ue(d.workflow_issue)?{workflow_issue:ue(d.workflow_issue)}:{},...ro(d),depends_on:Kt(d.depends_on),files_to_modify:J(d.files_to_modify),...Xr(d),risk:typeof d.risk=="string"?d.risk:void 0,blast_radius:typeof d.blast_radius=="number"?d.blast_radius:void 0};const c=r.epics??{},l={};for(const[f,d]of Object.entries(c)){const h=Kr(d.lifecycle_classification);l[f]={id:d.id??f,title:d.title,status:d.status,stories:d.stories,total_stories:d.total_stories,completed_stories:d.completed_stories,depends_on:Kt(d.depends_on),...He(d.branch_mode)?{branch_mode:He(d.branch_mode)}:{},...H(d.execution_branch)?{execution_branch:H(d.execution_branch)}:{},...H(d.origin_branch)?{origin_branch:H(d.origin_branch)}:{},...Zt(d.branch_lease)?{branch_lease:Zt(d.branch_lease)}:{},...rn(d.origin_binding)?{origin_binding:rn(d.origin_binding)}:{},...on(d.aggregate_qa_receipt)?{aggregate_qa_receipt:on(d.aggregate_qa_receipt)}:{},...ue(d.pr_number)?{pr_number:ue(d.pr_number)}:{},...U(d.physicalMergeStatus)?{physicalMergeStatus:U(d.physicalMergeStatus)}:{},...A(d.graph_revision)?{graph_revision:A(d.graph_revision)}:{},...sn(d.terminal_git_receipt)?{terminal_git_receipt:sn(d.terminal_git_receipt)}:{},...h?{lifecycle_classification:h}:{}}}const p=no(r.current_session??r.currentSession),g=r.epic_id_ledger,C=Array.isArray(g?.reserved_ids)?[...new Set(g.reserved_ids.filter(f=>typeof f=="string"&&/^P\d+$/.test(f)))].slice(0,2048):[];return{schema_version:typeof r.schema_version=="number"?r.schema_version:void 0,config:{project_name:o.project_name??o.name??"unknown",default_branch:o.default_branch??"main",language:o.language??"pt-BR",yolo_mode:o.yolo_mode,user_name:o.user_name,worktree_base:o.worktree_base,max_parallel_stories:o.max_parallel_stories,project_id:typeof o.project_id=="string"?o.project_id:void 0},stories:s,epics:l,...C.length>0?{epic_id_ledger:{schema_version:1,reserved_ids:C}}:{},...p?{current_session:p}:{}}}async function io(e,t,n){if(!an(n))return{};if(Wn(t,n))return{};try{const r=JSON.parse(Ae(te(e,".neocortex","state.json"),"utf8")),o=Ze(e,{required:!0}),i=Ut(r,o),s=m(i.stories)?i.stories:{},c=m(i.epics)?i.epics:{},l=ke("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8"}).trim(),p=ke("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8"}).trim(),g=ke("git",["rev-list","--first-parent","--reverse",l],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
8
- `).filter(Boolean),C=new Map(g.map((_,R)=>[_,R])),f=t.match(/(?:^|\s)@?docs\/stories\/([A-Za-z][A-Za-z0-9._-]*)\.story\.md(?:\s|$)/)?.[1],d=n==="yoloop"?t.match(/(?:^|[\s/@])epic-(P[1-9][0-9]*)\.md(?:\s|$)/i)?.[1]?.toUpperCase():void 0,h=new Set,S=Object.entries(s).flatMap(([_,R])=>{if(f&&_!==f)return[];const I=m(R)?R:void 0,M=m(I?.checkpoint)?I.checkpoint:void 0;if(!M)return[];const L=typeof I?.epic_id=="string"?I.epic_id:_.split(".")[0];if(d&&L!==d)return[];const D=A(M?.headSha);if(!D||D.length<40||C.get(D)===void 0)return h.add(L),[];const V=m(c[L])?c[L]:void 0;if(V?.branch_mode!=="epic"||H(V.execution_branch)!==p||H(M.branch)!==p)return h.add(L),[];const x=A(M.graphRevision);if(!x||x.length!==64)return h.add(L),[];const v=A(M.claimRevision),ee=[...Vt(_,I,M)].sort(),Oe=wr(e,M,_,L,p,ee);if(!Oe&&v){if(ee.length===0)return h.add(L),[];const _e=ke("git",["diff-tree","--no-commit-id","--name-only","-r","-z",D],{cwd:e,encoding:"utf8"}).split("\0").filter(Boolean);if(_e.length===0||_e.some(ge=>!ee.some(K=>K===ge||K.endsWith("/")&&ge.startsWith(K))))return h.add(L),[];const Ee=Ne("sha256").update(ee.join("\0")).digest("hex"),De=Ne("sha256").update(JSON.stringify(ee)).digest("hex");if(v!==Ee&&v!==De)return h.add(L),[]}else if(!Oe)return h.add(L),[];return x?.length===64?[{storyId:_,epicId:L,graphRevision:x,checkpointHead:D,position:C.get(D)}]:[]}),E=new Set(h);for(const[_,R]of Object.entries(c)){const I=m(R)?R:void 0,M=Array.isArray(I?.stories)?I.stories.filter(x=>typeof x=="string"):Object.keys(s).filter(x=>x.startsWith(`${_}.`)),L=S.filter(x=>x.epicId===_),D=M.filter(x=>L.some(v=>v.storyId===x)),V=[...L].sort((x,v)=>x.position-v.position).map(x=>x.storyId);(JSON.stringify(D)!==JSON.stringify(V)||new Set(V).size!==V.length)&&E.add(_)}const T={},k=[...new Set(S.filter(_=>!E.has(_.epicId)).map(_=>_.graphRevision))],w=k.length>0?await Ar(e,{headSha:l,graphRevisions:k}):new Map;for(const _ of S){if(E.has(_.epicId))continue;const R=w.get(_.graphRevision);if(!R)throw new Error("p205-transient-authority-missing");T[_.storyId]=R}return T}catch(r){const o=r instanceof Error&&/^(?:p205|git-lifecycle)-[a-z0-9-]+$/.test(r.message)?r.message:"p205-transient-execution-failed";return process.stderr.write(`[Neocortex] ${o}. Checkpoint projection remains fail-closed.
7
+ `)}catch{}}}function Ki(){at=!1}function Kt(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Kr(e){return e==="active"||e==="archived"||e==="rolled-back"||e==="synthetic"||e==="orphan"?e:void 0}function Xt(e){return e==="create-epic"||e==="discovered"?e:void 0}function J(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Xr(e){const t={};let n=!1;for(const r of["contracts","contract_refs","shared_surfaces","adr_refs","nfr_refs","acceptance_depends_on"]){if(e[r]===void 0)continue;const o=e[r];if(!Array.isArray(o)||o.length>128||o.some(i=>Me(i)===void 0)){n=!0;continue}t[r]=o.map(i=>Me(i))}if(e.planning!==void 0)try{if(!m(e.planning))throw new Error("planning-shape");const r=e.planning;for(const s of["claims","semanticArtifacts"]){if(r[s]===void 0)continue;const c=r[s];if(!Array.isArray(c)||c.length>128||c.some(l=>!m(l)||Me(l.ref)===void 0))throw new Error("planning-refs")}if(r.attempts!==void 0&&(!Array.isArray(r.attempts)||r.attempts.length>32))throw new Error("planning-attempts");for(const s of r.attempts??[]){if(!m(s)||!Array.isArray(s.reasonCodes)||s.reasonCodes.length>32||s.reasonCodes.some(c=>typeof c!="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(c)))throw new Error("planning-attempt-reasons");if(s.discoveredClaims!==void 0&&(!Array.isArray(s.discoveredClaims)||s.discoveredClaims.length>128||s.discoveredClaims.some(c=>!m(c)||Me(c.ref)===void 0)))throw new Error("planning-attempt-claims")}const{graphRevision:o,...i}=_r(r);t.planning=i}catch{n=!0}return n&&(t.planning={schemaVersion:1,dependencyBasis:"unknown",claims:[],semanticArtifacts:[]}),t}function m(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ue(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function U(e){if(typeof e!="string")return;const t=e.trim();if(t)return t.replace(/[^a-z0-9_.:-]+/gi,"_").slice(0,120)}function j(e){if(typeof e!="string")return;const t=e.trim(),n=U(e);return n===t?n:void 0}function W(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240)&&/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(t)&&!(t.includes("..")||t.includes("//")||t.includes("@{")||t.endsWith("/")||t.endsWith("."))&&!t.split("/").some(n=>!n||n.startsWith(".")||n.endsWith(".lock")))return t}function A(e){return typeof e=="string"&&/^[0-9a-f]{7,64}$/i.test(e)?e:void 0}function z(e){if(!(typeof e!="string"||e.length>64)&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/.test(e))return Number.isFinite(Date.parse(e))?e:void 0}function le(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240||t.includes("..")))return/^[A-Za-z0-9._:/#\-[\]]+$/.test(t)?t:void 0}function $e(e,t){if(!m(e))return;const n={};for(const r of t){const o=e[r];if(typeof o=="boolean")n[r]=o;else if(typeof o=="number"&&Number.isFinite(o))n[r]=o;else if(typeof o=="string"){const i=U(o);i&&(n[r]=i)}}return Object.keys(n).length>0?n:void 0}function We(e){return e==="epic"||e==="story"?e:void 0}function Zt(e){if(!m(e)||e.schemaVersion!==1)return;const t=j(e.ownerStoryId),n=j(e.sessionId),r=j(e.idempotencyKey),o=z(e.acquiredAt),i=z(e.expiresAt);if(!(!t||!n||!r||!o||!i||Date.parse(i)<=Date.parse(o)))return{schemaVersion:1,ownerStoryId:t,sessionId:n,idempotencyKey:r,acquiredAt:o,expiresAt:i}}function Qt(e){if(!m(e)||e.schemaVersion!==1)return;const t=j(e.storyId),n=j(e.epicId),r=W(e.branch),o=A(e.baseSha),i=A(e.headSha),s=j(e.idempotencyKey),c=z(e.recordedAt),l=J(e.commits).map(A).filter(T=>!!T).slice(0,256),p=J(e.receiptRefs).map(le).filter(T=>!!T).slice(0,256),g=e.dispatchId===void 0?void 0:j(e.dispatchId),C=e.bundleId===void 0?void 0:j(e.bundleId),f=e.bundleDigest===void 0?void 0:A(e.bundleDigest),d=e.graphRevision===void 0?void 0:A(e.graphRevision),h=e.claimRevision===void 0?void 0:j(e.claimRevision),S=Zr(e.qaReceipt),E=Qr(e.reviewReceipt);if(!(!t||!n||!t.startsWith(`${n}.`)||!r||!o||!i||o===i||!s||!c||l.length===0||p.length===0||!Array.isArray(e.commits)||l.length!==e.commits.length||e.commits.length>256||!Array.isArray(e.receiptRefs)||p.length!==e.receiptRefs.length||e.receiptRefs.length>256||e.dispatchId!==void 0&&!g||e.bundleId!==void 0&&!C||e.bundleDigest!==void 0&&(!f||f.length!==64)||e.graphRevision!==void 0&&(!d||d.length!==64)||e.claimRevision!==void 0&&!h||e.qaVerdict!=="passed"&&e.qaVerdict!=="blocked"||!["approved","changes-requested","pending"].includes(String(e.reviewVerdict))||!S||e.reviewVerdict!=="pending"&&!E||e.reviewVerdict==="pending"&&E||S.verdict!==e.qaVerdict||E&&E.verdict!==e.reviewVerdict||!nn(S,{storyId:t,epicId:n,baseSha:o,headSha:i,bundleDigest:f,graphRevision:d})||E&&(!nn(E,{storyId:t,epicId:n,baseSha:o,headSha:i,bundleDigest:f,graphRevision:d})||E.qaReceiptRef!==S?.receiptRef||E.receiptRef===S?.receiptRef)||!p.includes(String(S.receiptRef))||E&&(!p.includes(String(E.receiptRef))||Date.parse(String(E.reviewedAt))<Date.parse(String(S.checkedAt)))))return{schemaVersion:1,storyId:t,epicId:n,branch:r,baseSha:o,headSha:i,idempotencyKey:s,...g?{dispatchId:g}:{},...C?{bundleId:C}:{},...f?{bundleDigest:f}:{},...d?{graphRevision:d}:{},...h?{claimRevision:h}:{},qaVerdict:e.qaVerdict,reviewVerdict:e.reviewVerdict,...S?{qaReceipt:S}:{},...E?{reviewReceipt:E}:{},recordedAt:c,commits:l,receiptRefs:p}}function Zr(e){if(!m(e)||e.schemaVersion!==1||e.kind!=="story_qa_evidence"||e.producer!=="local-yolo-tdd"||e.evidenceVersion!==void 0&&e.evidenceVersion!=="git-immutable-v1"&&e.evidenceVersion!=="p205-execution-v2"||!["passed","blocked"].includes(String(e.verdict)))return;const t=j(e.storyId),n=j(e.epicId),r=A(e.baseSha),o=A(e.headSha),i=A(e.bundleDigest),s=A(e.graphRevision),c=A(e.sourceEvidenceDigest),l=z(e.checkedAt),p=le(e.receiptRef),g=e.evidenceVersion==="p205-execution-v2"&&e.contract==="P205-CI-02"?e.contract:void 0,C=e.evidenceVersion==="p205-execution-v2"&&e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,f=e.evidenceVersion==="p205-execution-v2"?A(e.manifestDigest):void 0,d=e.evidenceVersion==="p205-execution-v2"?A(e.resultDigest):void 0,h=e.evidenceVersion==="p205-execution-v2"?J(e.gateIds).map(j).filter(S=>!!S).slice(0,64):void 0;if(!(!t||!n||!r||!o||!i||i.length!==64||!s||s.length!==64||!c||c.length!==64||!l||!p||e.evidenceVersion==="p205-execution-v2"&&(!g||C!=="node scripts/test-root.mjs --gate complete"||!f||f.length!==64||!d||d.length!==64||!Array.isArray(e.gateIds)||!h||h.length===0||h.length!==e.gateIds.length)))return{schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",...e.evidenceVersion?{evidenceVersion:e.evidenceVersion}:{},storyId:t,epicId:n,...e.evidenceVersion==="p205-execution-v2"?{contract:g,command:C,manifestDigest:f,gateIds:h,resultDigest:d}:{},baseSha:r,headSha:o,bundleDigest:i,graphRevision:s,sourceEvidenceDigest:c,verdict:e.verdict,checkedAt:l,receiptRef:p}}function en(e){if(!m(e)||e.schemaVersion!==1||e.kind!=="story_checkpoint_physical_verification"||e.producer!=="client-p205-transient-v1"||e.publicSafe!==!0||e.verdict!=="verified"&&e.verdict!=="rejected")return;const t=j(e.storyId),n=j(e.epicId),r=W(e.branch),o=A(e.baseSha),i=A(e.headSha),s=A(e.aggregateHeadSha),c=A(e.commitBodyDigest),l=A(e.changedPathsDigest),p=e.claimVerification==="canonical"||e.claimVerification==="legacy-migration"?e.claimVerification:void 0,g=A(e.effectiveClaimRevision),C=e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,f=A(e.manifestDigest),d=J(e.gateIds).map(j).filter(_=>!!_).slice(0,64),h=A(e.resultDigest),S=A(e.graphRevision),E=A(e.executionEvidenceDigest),T=A(e.sourceEvidenceDigest),v=z(e.verifiedAt),w=J(e.reasonCodes).map(j).filter(_=>!!_).slice(0,16);if(!(!t||!n||!r||!o||o.length<40||!i||i.length<40||!s||s.length<40||!c||c.length!==64||!l||l.length!==64||!p||!g||g.length!==64||!C||!f||f.length!==64||!Array.isArray(e.gateIds)||d.length!==e.gateIds.length||!h||h.length!==64||!S||S.length!==64||!E||E.length!==64||!T||T.length!==64||!v||w.length===0||e.verdict==="verified"&&(d.length===0||!w.includes("checkpoint-p205-transient-verified"))))return{schemaVersion:1,kind:"story_checkpoint_physical_verification",producer:"client-p205-transient-v1",storyId:t,epicId:n,branch:r,baseSha:o,headSha:i,aggregateHeadSha:s,commitBodyDigest:c,changedPathsDigest:l,claimVerification:p,effectiveClaimRevision:g,command:C,manifestDigest:f,gateIds:d,resultDigest:h,graphRevision:S,executionEvidenceDigest:E,sourceEvidenceDigest:T,verifiedAt:v,verdict:e.verdict,reasonCodes:w,publicSafe:!0}}function tn(e){const t=["schemaVersion","kind","producer","storyId","epicId","branch","baseSha","headSha","graphRevision","effectiveClaimRevision","sourceEvidenceDigest","verifiedAt","reasonCodes","integrationAuthorized","publicSafe"];if(!m(e)||Object.keys(e).some(f=>!t.includes(f))||e.schemaVersion!==1||e.kind!=="story_scheduling_checkpoint_evidence"||e.producer!=="client-git-physical-v1"||e.integrationAuthorized!==!1||e.publicSafe!==!0)return;const n=j(e.storyId),r=j(e.epicId),o=W(e.branch),i=A(e.baseSha),s=A(e.headSha),c=A(e.graphRevision),l=A(e.effectiveClaimRevision),p=A(e.sourceEvidenceDigest),g=z(e.verifiedAt),C=J(e.reasonCodes).map(j).filter(f=>!!f);if(!(!n||!r||!o||!i||i.length<40||!s||s.length<40||!c||c.length!==64||!l||l.length!==64||!p||p.length!==64||!g||!Array.isArray(e.reasonCodes)||C.length!==1||C[0]!=="checkpoint-git-scheduling-verified"))return{schemaVersion:1,kind:"story_scheduling_checkpoint_evidence",producer:"client-git-physical-v1",storyId:n,epicId:r,branch:o,baseSha:i,headSha:s,graphRevision:c,effectiveClaimRevision:l,sourceEvidenceDigest:p,verifiedAt:g,reasonCodes:C,integrationAuthorized:!1,publicSafe:!0}}function Qr(e){if(!m(e)||e.schemaVersion!==1||e.kind!=="story_review_evidence"||e.producer!=="root-commit-range-review"||!["approved","changes-requested"].includes(String(e.verdict)))return;const t=j(e.storyId),n=j(e.epicId),r=A(e.baseSha),o=A(e.headSha),i=A(e.bundleDigest),s=A(e.graphRevision),c=A(e.sourceEvidenceDigest),l=le(e.qaReceiptRef),p=z(e.reviewedAt),g=le(e.receiptRef);if(!(!t||!n||!r||!o||!i||i.length!==64||!s||s.length!==64||!c||c.length!==64||!l||!p||!g))return{schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:t,epicId:n,baseSha:r,headSha:o,bundleDigest:i,graphRevision:s,sourceEvidenceDigest:c,qaReceiptRef:l,verdict:e.verdict,reviewedAt:p,receiptRef:g}}function nn(e,t){return["storyId","epicId","baseSha","headSha","bundleDigest","graphRevision"].every(n=>e[n]===t[n])}function rn(e){if(!m(e)||e.schemaVersion!==1||e.capturedFromCurrentCheckout!==!0)return;const t=W(e.originBranch),n=A(e.originHeadSha),r=W(e.executionBranch),o=z(e.capturedAt);if(!(!t||!n||n.length<40||!r||!o||t===r))return{schemaVersion:1,originBranch:t,originHeadSha:n,executionBranch:r,capturedFromCurrentCheckout:!0,capturedAt:o}}function on(e){if(!m(e)||e.schemaVersion!==1||e.verdict!=="passed")return;const t=A(e.executionHeadSha),n=A(e.graphRevision),r=z(e.checkedAt),o=le(e.receiptRef),i=J(e.gateIds).map(j).filter(g=>!!g).slice(0,128),s=e.evidenceVersion==="p205-execution-v2"&&e.producer==="local-yolo-tdd"&&e.contract==="P205-CI-02"&&e.command==="node scripts/test-root.mjs --gate complete",c=e.evidenceVersion===void 0&&e.producer===void 0&&e.contract===void 0&&e.command===void 0&&e.manifestDigest===void 0&&e.resultDigest===void 0,l=s?A(e.manifestDigest):void 0,p=s?A(e.resultDigest):void 0;if(!(!t||t.length<40||!n||n.length!==64||!r||!o||i.length===0||!Array.isArray(e.gateIds)||i.length!==e.gateIds.length||e.gateIds.length>128||!c&&!s||s&&(!l||l.length!==64||!p||p.length!==64)))return{schemaVersion:1,...s?{evidenceVersion:"p205-execution-v2",producer:"local-yolo-tdd",contract:"P205-CI-02",command:"node scripts/test-root.mjs --gate complete",manifestDigest:l,resultDigest:p}:{},verdict:"passed",executionHeadSha:t,graphRevision:n,checkedAt:r,receiptRef:o,gateIds:i}}function He(e){if(!m(e)||e.schemaVersion!==1)return;const t=$e(e,["schemaVersion","kind","storyId","epicId","baseSha","headSha","originalBaseSha","originalHeadSha","gitPullRequest","preservesLaterCommits","historyRewrite","recordedAt"])??{},n=J(e.receiptRefs).map(le).filter(o=>!!o).slice(0,256),r=J(e.revertCommits).map(U).filter(o=>!!o).slice(0,256);return{...t,...n.length?{receiptRefs:n}:{},...r.length?{revertCommits:r}:{}}}function sn(e){if(!m(e)||e.schemaVersion!==1||e.publicSafe!==!0)return;const t=j(e.epicId),n=W(e.executionBranch),r=W(e.originBranch),o=A(e.baseSha),i=A(e.executionHeadSha),s=e.mergeSha===void 0?void 0:A(e.mergeSha),c=e.pushedSha===void 0?void 0:A(e.pushedSha),l=j(e.idempotencyKey),p=z(e.attemptStartedAt),g=e.completedAt===void 0?void 0:z(e.completedAt),C=J(e.localGateReceiptRefs).map(le).filter(S=>!!S).slice(0,256),f=J(e.reasonCodes).map(j).filter(S=>!!S).slice(0,64),d=to(e.candidateQa),h=eo(e.providerGuard);if(!(!t||!n||!r||!o||!i||!l||!p||C.length===0||f.length===0||!["direct","single_pr"].includes(String(e.strategy))||!["prepared","merged","pushed","denied_external_gate","blocked_local_or_repo"].includes(String(e.physicalStatus))||typeof e.retryEligible!="boolean"||e.providerGuard!==void 0&&!h||h&&(e.strategy!=="single_pr"||e.physicalStatus!=="pushed"||h.prHeadSha!==s||h.originHeadSha!==o)))return{schemaVersion:1,epicId:t,executionBranch:n,originBranch:r,baseSha:o,executionHeadSha:i,...s?{mergeSha:s}:{},...c?{pushedSha:c}:{},strategy:e.strategy,...ue(e.prNumber)?{prNumber:ue(e.prNumber)}:{},physicalStatus:e.physicalStatus,localGateReceiptRefs:C,idempotencyKey:l,attemptStartedAt:p,...d?{candidateQa:d}:{},...h?{providerGuard:h}:{},...g?{completedAt:g}:{},retryEligible:e.retryEligible,reasonCodes:f,publicSafe:!0}}function eo(e){if(!m(e)||e.schemaVersion!==1||e.provider!=="github"||e.publicSafe!==!0)return;const t=String(e.mode),n=String(e.source),r=t==="recovered_exact_tree"?n==="physical_recovery":t==="strict_up_to_date_expected_head"&&["branch_protection","ruleset","branch_protection_and_ruleset"].includes(n),o=A(e.prHeadSha),i=A(e.originHeadSha),s=z(e.checkedAt);if(!(!r||!o||!i||!s))return{schemaVersion:1,provider:"github",mode:t,source:n,prHeadSha:o,originHeadSha:i,checkedAt:s,publicSafe:!0}}function to(e){if(!m(e)||e.schemaVersion!==1||e.kind!=="epic_merge_candidate_qa"||e.contract!=="P205-CI-02"||e.command!==Rr)return;const n=Object.fromEntries(["originHeadSha","executionHeadSha","mergeSha","treeSha","graphRevision","manifestDigest","resultDigest"].map(s=>[s,A(e[s])])),r=z(e.checkedAt),o=le(e.receiptRef),i=J(e.gateIds).filter(s=>/^[a-z0-9-]+$/.test(s)).slice(0,128);if(!(Object.values(n).some(s=>!s)||!r||!o||i.length===0))return{schemaVersion:1,kind:e.kind,contract:e.contract,command:e.command,...n,checkedAt:r,receiptRef:o,gateIds:i}}function no(e){if(!m(e))return;const t={...U(e.active_epic_id??e.activeEpicId)?{active_epic_id:U(e.active_epic_id??e.activeEpicId)}:{},...U(e.active_story_id??e.activeStoryId)?{active_story_id:U(e.active_story_id??e.activeStoryId)}:{},...U(e.active_step_id??e.activeStepId)?{active_step_id:U(e.active_step_id??e.activeStepId)}:{},...U(e.session_id??e.sessionId)?{session_id:U(e.session_id??e.sessionId)}:{},...U(e.started_at??e.startedAt)?{started_at:U(e.started_at??e.startedAt)}:{}};return Object.keys(t).length>0?t:void 0}function ro(e){const t=$e(e.completionEvidence??e.completion_evidence,["prNumber","pr_number","prState","pr_state","pullRequestState","merged","mergedAt","issueNumber","issue_number","issueState","issue_state","closedAt"]),n=$e(e.issueCloseAudit??e.issue_close_audit,["schema_version","event","storyId","epicId","issueNumber","closedAt","publicSafe","rawLogStorage"]),r=$e(e.scopedCiEvidence??e.scoped_ci_evidence,["schema_version","storyId","epicId","prNumber","finalState","publicSafe","rawLogStorage"]);return{...typeof e.merged=="boolean"?{merged:e.merged}:{},...typeof e.safeToContinueYoloop=="boolean"?{safeToContinueYoloop:e.safeToContinueYoloop}:{},...typeof e.mergeBlockedRemotely=="boolean"?{mergeBlockedRemotely:e.mergeBlockedRemotely}:{},...U(e.physicalMergeStatus)?{physicalMergeStatus:U(e.physicalMergeStatus)}:{},...U(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)?{pr_state:U(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)}:{},...U(e.issue_state??e.issueState??e.workflow_issue_state)?{issue_state:U(e.issue_state??e.issueState??e.workflow_issue_state)}:{},...ue(e.issue_number??e.issueNumber)?{issue_number:ue(e.issue_number??e.issueNumber)}:{},...t?{completionEvidence:t}:{},...n?{issueCloseAudit:n}:{},...r?{scopedCiEvidence:r}:{}}}class pe extends Error{reasonCode;constructor(t){super(t),this.name="StateSnapshotIntegrityError",this.reasonCode=t}}const oo=new Set(["yolo","yoloop","finalize-epic","audit"]);function an(e){return typeof e=="string"&&oo.has(e)}function cn(e,t={}){const n=te(e,".neocortex","state.json");if(!Ce(n))throw new pe("git-lifecycle-state-missing");let r;try{r=JSON.parse(Ae(n,"utf8"))}catch{throw new pe("git-lifecycle-state-corrupt")}if(!m(r)||!m(r.epics)||!m(r.stories))throw new pe("git-lifecycle-state-shape-invalid");const o=Object.values(r.epics).some(i=>m(i)&&(i.branch_mode==="epic"||W(i.execution_branch)!==void 0));if(o)try{Ze(e,{required:!0})}catch(i){const s=i instanceof Error&&/^git-lifecycle-/.test(i.message)?i.message:"git-lifecycle-runtime-invalid";if(t.allowMissingRuntime&&s==="git-lifecycle-runtime-missing")return{lifecycleDeclared:!0,runtimeMissing:!0};throw new pe(s)}return{lifecycleDeclared:o,runtimeMissing:!1}}function dn(e,t={}){const n=te(e,".neocortex","state.json");if(!Ce(n)){if(t.epicAware&&!t.projectless)throw new pe("git-lifecycle-state-missing");return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}let r;try{const f=Ae(n,"utf-8"),d=JSON.parse(f),h=m(d.epics)?d.epics:{},S=Object.values(h).some(_=>m(_)&&(_.branch_mode==="epic"||W(_.execution_branch)!==void 0)),E=Ze(e,{required:!!(t.epicAware&&S&&!t.projectless)});r=Ut(d,E);const T=m(r.stories)?r.stories:{},v=m(r.epics)?r.epics:{},w=m(d.stories)?d.stories:{};for(const[_,R]of Object.entries(T)){const I=m(R)?R:void 0;if(!I?.checkpoint)continue;const M=typeof I.epic_id=="string"?I.epic_id:_.split(".")[0],L=m(v[M])?v[M]:void 0,D=W(L?.execution_branch);if(!D)continue;const V=Er(e,I.checkpoint,_,M,D,t.p205Authorities?.[_],Vt(_,I,m(I.checkpoint)?I.checkpoint:void 0));if(V.kind==="integration-authorized")I.checkpoint_verification=V.verification,delete I.scheduling_checkpoint_evidence;else if(V.kind==="scheduling-only")I.scheduling_checkpoint_evidence=V.evidence,delete I.checkpoint,delete I.checkpoint_verification;else if(V.kind==="rejected"){I.checkpoint_verification=V.verification,delete I.scheduling_checkpoint_evidence;const x=m(w[_])?w[_]:void 0;if(delete I.checkpoint,E.stories[_]?.checkpoint!==void 0)for(const O of["status","last_step","steps_completed"])x&&Object.prototype.hasOwnProperty.call(x,O)?I[O]=structuredClone(x[O]):delete I[O];["done","completed","merged"].includes(String(I.status).toLowerCase())&&(I.status="blocked")}}}catch(f){if(t.epicAware&&!t.projectless){const d=f instanceof Error&&/^git-lifecycle-/.test(f.message)?f.message:"git-lifecycle-state-corrupt";throw new pe(d)}return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}try{const f=zr(r);f.length>0&&qr(f)}catch{}const o=r.config??r.project??{},i=r.stories??{},s={};for(const[f,d]of Object.entries(i))s[f]={id:d.id??f,title:d.title,epic_id:d.epic_id,status:d.status??"backlog",...Xt(d.source)?{source:Xt(d.source)}:{},steps_completed:d.steps_completed??[],last_step:d.last_step??null,branch_name:d.branch_name??null,pr_number:d.pr_number,...We(d.branch_mode)?{branch_mode:We(d.branch_mode)}:{},...Qt(d.checkpoint)?{checkpoint:Qt(d.checkpoint)}:{},...en(d.checkpoint_verification)?{checkpoint_verification:en(d.checkpoint_verification)}:{},...tn(d.scheduling_checkpoint_evidence)?{scheduling_checkpoint_evidence:tn(d.scheduling_checkpoint_evidence)}:{},...He(d.review_request)?{review_request:He(d.review_request)}:{},...He(d.rollback_receipt)?{rollback_receipt:He(d.rollback_receipt)}:{},...ue(d.workflow_issue)?{workflow_issue:ue(d.workflow_issue)}:{},...ro(d),depends_on:Kt(d.depends_on),files_to_modify:J(d.files_to_modify),...Xr(d),risk:typeof d.risk=="string"?d.risk:void 0,blast_radius:typeof d.blast_radius=="number"?d.blast_radius:void 0};const c=r.epics??{},l={};for(const[f,d]of Object.entries(c)){const h=Kr(d.lifecycle_classification);l[f]={id:d.id??f,title:d.title,status:d.status,stories:d.stories,total_stories:d.total_stories,completed_stories:d.completed_stories,depends_on:Kt(d.depends_on),...We(d.branch_mode)?{branch_mode:We(d.branch_mode)}:{},...W(d.execution_branch)?{execution_branch:W(d.execution_branch)}:{},...W(d.origin_branch)?{origin_branch:W(d.origin_branch)}:{},...Zt(d.branch_lease)?{branch_lease:Zt(d.branch_lease)}:{},...rn(d.origin_binding)?{origin_binding:rn(d.origin_binding)}:{},...on(d.aggregate_qa_receipt)?{aggregate_qa_receipt:on(d.aggregate_qa_receipt)}:{},...ue(d.pr_number)?{pr_number:ue(d.pr_number)}:{},...U(d.physicalMergeStatus)?{physicalMergeStatus:U(d.physicalMergeStatus)}:{},...A(d.graph_revision)?{graph_revision:A(d.graph_revision)}:{},...sn(d.terminal_git_receipt)?{terminal_git_receipt:sn(d.terminal_git_receipt)}:{},...h?{lifecycle_classification:h}:{}}}const p=no(r.current_session??r.currentSession),g=r.epic_id_ledger,C=Array.isArray(g?.reserved_ids)?[...new Set(g.reserved_ids.filter(f=>typeof f=="string"&&/^P\d+$/.test(f)))].slice(0,2048):[];return{schema_version:typeof r.schema_version=="number"?r.schema_version:void 0,config:{project_name:o.project_name??o.name??"unknown",default_branch:o.default_branch??"main",language:o.language??"pt-BR",yolo_mode:o.yolo_mode,user_name:o.user_name,worktree_base:o.worktree_base,max_parallel_stories:o.max_parallel_stories,project_id:typeof o.project_id=="string"?o.project_id:void 0},stories:s,epics:l,...C.length>0?{epic_id_ledger:{schema_version:1,reserved_ids:C}}:{},...p?{current_session:p}:{}}}async function io(e,t,n){if(!an(n))return{};if(Hn(t,n))return{};try{const r=JSON.parse(Ae(te(e,".neocortex","state.json"),"utf8")),o=Ze(e,{required:!0}),i=Ut(r,o),s=m(i.stories)?i.stories:{},c=m(i.epics)?i.epics:{},l=ke("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8"}).trim(),p=ke("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8"}).trim(),g=ke("git",["rev-list","--first-parent","--reverse",l],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
8
+ `).filter(Boolean),C=new Map(g.map((_,R)=>[_,R])),f=t.match(/(?:^|\s)@?docs\/stories\/([A-Za-z][A-Za-z0-9._-]*)\.story\.md(?:\s|$)/)?.[1],d=n==="yoloop"?t.match(/(?:^|[\s/@])epic-(P[1-9][0-9]*)\.md(?:\s|$)/i)?.[1]?.toUpperCase():void 0,h=new Set,S=Object.entries(s).flatMap(([_,R])=>{if(f&&_!==f)return[];const I=m(R)?R:void 0,M=m(I?.checkpoint)?I.checkpoint:void 0;if(!M)return[];const L=typeof I?.epic_id=="string"?I.epic_id:_.split(".")[0];if(d&&L!==d)return[];const D=A(M?.headSha);if(!D||D.length<40||C.get(D)===void 0)return h.add(L),[];const V=m(c[L])?c[L]:void 0;if(V?.branch_mode!=="epic"||W(V.execution_branch)!==p||W(M.branch)!==p)return h.add(L),[];const x=A(M.graphRevision);if(!x||x.length!==64)return h.add(L),[];const O=A(M.claimRevision),ee=[...Vt(_,I,M)].sort(),Oe=wr(e,M,_,L,p,ee);if(!Oe&&O){if(ee.length===0)return h.add(L),[];const _e=ke("git",["diff-tree","--no-commit-id","--name-only","-r","-z",D],{cwd:e,encoding:"utf8"}).split("\0").filter(Boolean);if(_e.length===0||_e.some(ge=>!ee.some(K=>K===ge||K.endsWith("/")&&ge.startsWith(K))))return h.add(L),[];const Ee=Ne("sha256").update(ee.join("\0")).digest("hex"),De=Ne("sha256").update(JSON.stringify(ee)).digest("hex");if(O!==Ee&&O!==De)return h.add(L),[]}else if(!Oe)return h.add(L),[];return x?.length===64?[{storyId:_,epicId:L,graphRevision:x,checkpointHead:D,position:C.get(D)}]:[]}),E=new Set(h);for(const[_,R]of Object.entries(c)){const I=m(R)?R:void 0,M=Array.isArray(I?.stories)?I.stories.filter(x=>typeof x=="string"):Object.keys(s).filter(x=>x.startsWith(`${_}.`)),L=S.filter(x=>x.epicId===_),D=M.filter(x=>L.some(O=>O.storyId===x)),V=[...L].sort((x,O)=>x.position-O.position).map(x=>x.storyId);(JSON.stringify(D)!==JSON.stringify(V)||new Set(V).size!==V.length)&&E.add(_)}const T={},v=[...new Set(S.filter(_=>!E.has(_.epicId)).map(_=>_.graphRevision))],w=v.length>0?await Ar(e,{headSha:l,graphRevisions:v}):new Map;for(const _ of S){if(E.has(_.epicId))continue;const R=w.get(_.graphRevision);if(!R)throw new Error("p205-transient-authority-missing");T[_.storyId]=R}return T}catch(r){const o=r instanceof Error&&/^(?:p205|git-lifecycle)-[a-z0-9-]+$/.test(r.message)?r.message:"p205-transient-execution-failed";return process.stderr.write(`[Neocortex] ${o}. Checkpoint projection remains fail-closed.
9
9
  `),{}}}function Xi(e,t){return{kind:"full",trigger:e,targetEpicId:null,targetStoryId:null,includedStoryCount:Object.keys(t.stories).length,includedEpicCount:Object.keys(t.epics).length,omittedStoryCount:0,omittedEpicCount:0,reason:"full-state",projectionMode:"full-compatible"}}const un="neocortex:menu:cache";async function so(e){try{const t=await e.get(un);if(!t)return null;const n=JSON.parse(t);return n.version!==Se||Date.now()-n.cachedAt>$t?null:n}catch{return null}}async function ao(e,t,n){try{const r={instructions:t,metadata:n,cachedAt:Date.now(),version:Se};await e.set(un,JSON.stringify(r),$t),co()}catch{}}function co(){try{Ce(Bt)&&xn(Bt)}catch{}}function uo(e){return e.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>Rt(),()=>Rt({strictReadOnly:!0}))}async function ln(e,t,n){const r=n.mode==="strict";try{let o;if(r&&t)o=new Ke({cacheDir:Qe,passphrase:t,strictReadOnly:!0});else if(r)o=new At;else if(t){const g=te(Ue,"cache");o=new Ke({cacheDir:g,passphrase:t})}else process.stderr.write(`[neocortex] Warning: No license key in config. Run "neocortex activate" to re-authenticate.
10
- `),o=new At;const i=Dt(n,o,"auth-cache"),s=Dt(n,o,"tier-cache"),c=new Pn({serverUrl:e,licenseKey:t??"",cacheProvider:i,strictReadOnly:r});let l;if(r){const g=await c.inspectToken();if(g.status!=="authenticated")return g;l=g.token}else l=await c.getToken();if(!l)return{status:"not-configured"};const p=new jn({cacheProvider:s,licenseClient:c});return{status:"authenticated",token:l,client:c,tierClient:p}}catch{return r&&t?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"}}}let pn=!1;function lo(e){const t=e.errorBody?.error_code;if(typeof t=="string"&&t.trim().length>0)return t;if(e.status===429)return"RATE_LIMITED";if(e.status>=500)return"SERVER_ERROR"}const fn=3,Fe=50;function po(e){return new Promise(t=>setTimeout(t,e))}function fo(e,t,n){return e.status>=500&&e.status<=599?!0:n&&e.status===409&&t.error_code==="SIGNATURE_REPLAYED"}async function ct(e,t,n,r,o={}){const i=Math.max(1,Math.min(o.maxAttempts??fn,fn)),s=o.sleep??po;let c=r,l=!1,p=!1,g=0;for(let C=1;C<=i;C+=1){const f=Math.max(Math.floor(Date.now()/1e3),g+1);g=f;const d=go(t,n,c,{nowSeconds:f}),h=new AbortController,S=setTimeout(()=>h.abort(),Ht);try{const E=await fetch(`${e}${t}`,{method:"POST",headers:d.headers,body:d.body,signal:h.signal}),T=await E.text().catch(()=>""),k=(()=>{try{return T?JSON.parse(T):{}}catch{return{}}})();if(E.status===401&&!l&&o.refreshToken&&(k.fallback_action==="refresh_token"||k.fallback_action==="re_authenticate")){l=!0;const w=await o.refreshToken();if(w&&C<i){c=w,o.onTokenChanged?.(w),await s(Fe*C);continue}}if(E.status===401&&k.error_code==="SIGNATURE_EXPIRED"&&!p&&C<i){p=!0,await s(Fe*C);continue}if(C<i&&fo(E,k,o.allowReplayRetry===!0)){await s(Fe*C);continue}return{response:E,text:T,parsed:k,networkFailure:!1}}catch{if(C<i){await s(Fe*C);continue}return{text:"",parsed:{},networkFailure:!0}}finally{clearTimeout(S)}}return{text:"",parsed:{},networkFailure:!0}}function go(e,t,n,r={}){const o=Buffer.from(JSON.stringify(t),"utf8"),i=tr({method:"POST",target:e,body:o,bearerToken:n,clientVersion:Se,nowSeconds:r.nowSeconds,nonceBytes:r.nonceBytes});return{body:i.body,headers:{...i.headers,Authorization:`Bearer ${n}`}}}function gn(e){return Ne("sha256").update(e).digest("hex")}function ho(){const e=Number(process.env.NEOCORTEX_INVOKE_CHUNK_BYTES??"49152");return Number.isFinite(e)&&e>=1024&&e<=98304?Math.floor(e):49152}function mo(e,t,n){return`args-${Ne("sha256").update("invoke-materialization:v1").update(e).update(String(t)).update(JSON.stringify(n)).digest("hex")}`}async function hn(e,t,n,r,o={}){const i=await ct(e,t,n,r,{...o,allowReplayRetry:!0});if(i.networkFailure||!i.response)throw new Error("NETWORK_ERROR: materialization request failed after bounded retries");const{response:s,parsed:c}=i;if(!s.ok){const l=typeof c.error_code=="string"?c.error_code:`HTTP_${s.status}`,p=typeof c.message=="string"?c.message:"materialization upload failed";throw new Error(`${l}: ${p}`)}return c}async function Io(e,t,n,r){const o=Buffer.from(t,"utf8"),i=ho(),s=[];for(let h=0,S=0;h<o.byteLength;h+=i,S++){const E=o.subarray(h,Math.min(h+i,o.byteLength));s.push({index:S,sha256:gn(E),byteLength:E.byteLength})}const c=gn(o),l=mo(c,o.byteLength,s),p=Number(process.env.NEOCORTEX_INVOKE_CHUNK_TTL_SECONDS??"900");let g=n;const C={refreshToken:r,onTokenChanged(h){g=h}};for(const h of s){const S=h.index*i,E=o.subarray(S,S+h.byteLength);await hn(e,"/api/v1/invoke/materialization/chunks",{manifestId:l,index:h.index,sha256:h.sha256,byteLength:h.byteLength,contentBase64:E.toString("base64"),ttlSeconds:p,idempotencyKey:`${l}:${h.index}:${h.sha256}`},g,C)}const d=(await hn(e,"/api/v1/invoke/materialization/manifests",{manifestId:l,sha256:c,byteLength:o.byteLength,chunkCount:s.length,chunks:s,ttlSeconds:p,retry:{attempt:1,budget:3,idempotencyKey:l}},g,C)).argsRef;if(!d?.manifestId)throw new Error("MATERIALIZATION_RESPONSE_INVALID: missing argsRef");return{argsRef:d,chunks:s}}function Te(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function yo(...e){const t=new Set,n=[];for(const r of e)for(const o of r??[]){const i=U(o);if(!(!i||t.has(i))&&(t.add(i),n.push(i),n.length>=16))return n}return n}function _o(e){const t=e.graphRetrieval;if(!m(t))return{accepted:!1,itemCount:0};const n=Array.isArray(t.items)?t.items.length:0;return{accepted:n>0||typeof t.retrievalId=="string"||t.accepted===!0,itemCount:n}}function dt(e,t=Te(e),n=[],r={}){const o=e.stateSnapshot.scope,i=Object.keys(e.stateSnapshot.stories).length,s=Object.keys(e.stateSnapshot.epics).length,c=o?.kind??"full";return{schemaVersion:1,payloadBytes:t,limitBytes:r.limitBytes??Ft,warningThresholdBytes:r.warningThresholdBytes??et,scope:{kind:c,...o?.projectionMode?{projectionMode:o.projectionMode}:{},commandId:o?.commandId??null,stateProjectionPolicy:o?.stateProjectionPolicy??null},includedStories:o?.includedStoryCount??i,omittedStories:o?.omittedStoryCount??0,includedEpics:o?.includedEpicCount??s,omittedEpics:o?.omittedEpicCount??0,graphRetrieval:_o(e.stateSnapshot),reasonCodes:yo(n,o?.reasonCodes),publicSafe:!0}}function Eo(e){const t=m(e.budget)?e.budget:void 0,n=typeof t?.maxPayloadBytes=="number"&&Number.isFinite(t.maxPayloadBytes)?t.maxPayloadBytes:12*1024;return Math.max(1024,Math.min(n,12*1024))}function Co(e){return m(e)?{stableId:U(e.stableId)??"unknown",...m(e.source)?{source:e.source}:{},reasonCode:"budget_exceeded"}:{stableId:"unknown",reasonCode:"budget_exceeded"}}function mn(e){const t=Array.isArray(e)?e.filter(n=>typeof n=="string"):[];return t.includes("budget_exceeded")?t:[...t,"budget_exceeded"]}function Ao(e){const t=e.graphRetrieval;if(!m(t)||!Array.isArray(t.items))return e;const n=Eo(t);let r=[...t.items],o=Array.isArray(t.skipped)?[...t.skipped]:[],i=t;for(;Buffer.byteLength(JSON.stringify(i),"utf8")>n&&r.length>0;){const s=r.pop();o=[...o,Co(s)].slice(-32),i={...t,items:r,skipped:o,warnings:mn(t.warnings)}}return Buffer.byteLength(JSON.stringify(i),"utf8")>n&&(i={...t,query:typeof t.query=="string"?t.query.slice(0,240):t.query,items:[],skipped:[],warnings:mn(t.warnings)}),i===t?e:{...e,graphRetrieval:i}}function In(e,t={}){const n=t.limitBytes??Ft,r=t.warningThresholdBytes??Math.floor(n*Gt),o=Te(e);if(o<n)return{body:e,degraded:!1,telemetry:dt(e,o,["payload-within-limit"],{limitBytes:n,warningThresholdBytes:r})};let i={...e,stateSnapshot:$n(e.stateSnapshot)},s=["payload-size-guardrail","state-degraded"],c=Te(i);c>=n&&(i={...i,stateSnapshot:Ao(i.stateSnapshot)},s=[...s,"graph-retrieval-budget-enforced"],c=Te(i));const l=dt(i,c,s,{limitBytes:n,warningThresholdBytes:r});if(c>=n){const p=i.stateSnapshot.scope?.projectionMode;throw p==="yolo-story"||p==="yoloop-target"||p==="yoloop-session"||p==="yoloop-discovery"||p==="structural-required"?new st(l):new it(l)}return{body:i,degraded:!0,telemetry:l}}function yn(e){const t=e.stateSnapshot.scope?.commandId??"resolved-command";return e.args!==void 0?t:`${t}:argsRef`}function So(e){const t=Te(e);if(t<et)return t;const n=dt(e,t,["payload-warning-threshold"]);return process.stderr.write(`[Neocortex] invoke payload near server limit: trigger=${yn(e)} scope=${n.scope.kind} mode=${n.scope.projectionMode??n.scope.kind} payloadBytes=${n.payloadBytes} limit=${n.limitBytes} includedStories=${n.includedStories} omittedStories=${n.omittedStories} includedEpics=${n.includedEpics} omittedEpics=${n.omittedEpics} graphRetrieval.accepted=${n.graphRetrieval.accepted} graphRetrieval.itemCount=${n.graphRetrieval.itemCount} reasonCodes=${n.reasonCodes.join(",")||"none"}
10
+ `),o=new At;const i=Dt(n,o,"auth-cache"),s=Dt(n,o,"tier-cache"),c=new Pn({serverUrl:e,licenseKey:t??"",cacheProvider:i,strictReadOnly:r});let l;if(r){const g=await c.inspectToken();if(g.status!=="authenticated")return g;l=g.token}else l=await c.getToken();if(!l)return{status:"not-configured"};const p=new jn({cacheProvider:s,licenseClient:c});return{status:"authenticated",token:l,client:c,tierClient:p}}catch{return r&&t?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"}}}let pn=!1;function lo(e){const t=e.errorBody?.error_code;if(typeof t=="string"&&t.trim().length>0)return t;if(e.status===429)return"RATE_LIMITED";if(e.status>=500)return"SERVER_ERROR"}const fn=3,Fe=50;function po(e){return new Promise(t=>setTimeout(t,e))}function fo(e,t,n){return e.status>=500&&e.status<=599?!0:n&&e.status===409&&t.error_code==="SIGNATURE_REPLAYED"}async function ct(e,t,n,r,o={}){const i=Math.max(1,Math.min(o.maxAttempts??fn,fn)),s=o.sleep??po;let c=r,l=!1,p=!1,g=0;for(let C=1;C<=i;C+=1){const f=Math.max(Math.floor(Date.now()/1e3),g+1);g=f;const d=go(t,n,c,{nowSeconds:f}),h=new AbortController,S=setTimeout(()=>h.abort(),Wt);try{const E=await fetch(`${e}${t}`,{method:"POST",headers:d.headers,body:d.body,signal:h.signal}),T=await E.text().catch(()=>""),v=(()=>{try{return T?JSON.parse(T):{}}catch{return{}}})();if(E.status===401&&!l&&o.refreshToken&&(v.fallback_action==="refresh_token"||v.fallback_action==="re_authenticate")){l=!0;const w=await o.refreshToken();if(w&&C<i){c=w,o.onTokenChanged?.(w),await s(Fe*C);continue}}if(E.status===401&&v.error_code==="SIGNATURE_EXPIRED"&&!p&&C<i){p=!0,await s(Fe*C);continue}if(C<i&&fo(E,v,o.allowReplayRetry===!0)){await s(Fe*C);continue}return{response:E,text:T,parsed:v,networkFailure:!1}}catch{if(C<i){await s(Fe*C);continue}return{text:"",parsed:{},networkFailure:!0}}finally{clearTimeout(S)}}return{text:"",parsed:{},networkFailure:!0}}function go(e,t,n,r={}){const o=Buffer.from(JSON.stringify(t),"utf8"),i=tr({method:"POST",target:e,body:o,bearerToken:n,clientVersion:Se,nowSeconds:r.nowSeconds,nonceBytes:r.nonceBytes});return{body:i.body,headers:{...i.headers,Authorization:`Bearer ${n}`}}}function gn(e){return Ne("sha256").update(e).digest("hex")}function ho(){const e=Number(process.env.NEOCORTEX_INVOKE_CHUNK_BYTES??"49152");return Number.isFinite(e)&&e>=1024&&e<=98304?Math.floor(e):49152}function mo(e,t,n){return`args-${Ne("sha256").update("invoke-materialization:v1").update(e).update(String(t)).update(JSON.stringify(n)).digest("hex")}`}async function hn(e,t,n,r,o={}){const i=await ct(e,t,n,r,{...o,allowReplayRetry:!0});if(i.networkFailure||!i.response)throw new Error("NETWORK_ERROR: materialization request failed after bounded retries");const{response:s,parsed:c}=i;if(!s.ok){const l=typeof c.error_code=="string"?c.error_code:`HTTP_${s.status}`,p=typeof c.message=="string"?c.message:"materialization upload failed";throw new Error(`${l}: ${p}`)}return c}async function Io(e,t,n,r){const o=Buffer.from(t,"utf8"),i=ho(),s=[];for(let h=0,S=0;h<o.byteLength;h+=i,S++){const E=o.subarray(h,Math.min(h+i,o.byteLength));s.push({index:S,sha256:gn(E),byteLength:E.byteLength})}const c=gn(o),l=mo(c,o.byteLength,s),p=Number(process.env.NEOCORTEX_INVOKE_CHUNK_TTL_SECONDS??"900");let g=n;const C={refreshToken:r,onTokenChanged(h){g=h}};for(const h of s){const S=h.index*i,E=o.subarray(S,S+h.byteLength);await hn(e,"/api/v1/invoke/materialization/chunks",{manifestId:l,index:h.index,sha256:h.sha256,byteLength:h.byteLength,contentBase64:E.toString("base64"),ttlSeconds:p,idempotencyKey:`${l}:${h.index}:${h.sha256}`},g,C)}const d=(await hn(e,"/api/v1/invoke/materialization/manifests",{manifestId:l,sha256:c,byteLength:o.byteLength,chunkCount:s.length,chunks:s,ttlSeconds:p,retry:{attempt:1,budget:3,idempotencyKey:l}},g,C)).argsRef;if(!d?.manifestId)throw new Error("MATERIALIZATION_RESPONSE_INVALID: missing argsRef");return{argsRef:d,chunks:s}}function Te(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function yo(...e){const t=new Set,n=[];for(const r of e)for(const o of r??[]){const i=U(o);if(!(!i||t.has(i))&&(t.add(i),n.push(i),n.length>=16))return n}return n}function _o(e){const t=e.graphRetrieval;if(!m(t))return{accepted:!1,itemCount:0};const n=Array.isArray(t.items)?t.items.length:0;return{accepted:n>0||typeof t.retrievalId=="string"||t.accepted===!0,itemCount:n}}function dt(e,t=Te(e),n=[],r={}){const o=e.stateSnapshot.scope,i=Object.keys(e.stateSnapshot.stories).length,s=Object.keys(e.stateSnapshot.epics).length,c=o?.kind??"full";return{schemaVersion:1,payloadBytes:t,limitBytes:r.limitBytes??Ft,warningThresholdBytes:r.warningThresholdBytes??et,scope:{kind:c,...o?.projectionMode?{projectionMode:o.projectionMode}:{},commandId:o?.commandId??null,stateProjectionPolicy:o?.stateProjectionPolicy??null},includedStories:o?.includedStoryCount??i,omittedStories:o?.omittedStoryCount??0,includedEpics:o?.includedEpicCount??s,omittedEpics:o?.omittedEpicCount??0,graphRetrieval:_o(e.stateSnapshot),reasonCodes:yo(n,o?.reasonCodes),publicSafe:!0}}function Eo(e){const t=m(e.budget)?e.budget:void 0,n=typeof t?.maxPayloadBytes=="number"&&Number.isFinite(t.maxPayloadBytes)?t.maxPayloadBytes:12*1024;return Math.max(1024,Math.min(n,12*1024))}function Co(e){return m(e)?{stableId:U(e.stableId)??"unknown",...m(e.source)?{source:e.source}:{},reasonCode:"budget_exceeded"}:{stableId:"unknown",reasonCode:"budget_exceeded"}}function mn(e){const t=Array.isArray(e)?e.filter(n=>typeof n=="string"):[];return t.includes("budget_exceeded")?t:[...t,"budget_exceeded"]}function Ao(e){const t=e.graphRetrieval;if(!m(t)||!Array.isArray(t.items))return e;const n=Eo(t);let r=[...t.items],o=Array.isArray(t.skipped)?[...t.skipped]:[],i=t;for(;Buffer.byteLength(JSON.stringify(i),"utf8")>n&&r.length>0;){const s=r.pop();o=[...o,Co(s)].slice(-32),i={...t,items:r,skipped:o,warnings:mn(t.warnings)}}return Buffer.byteLength(JSON.stringify(i),"utf8")>n&&(i={...t,query:typeof t.query=="string"?t.query.slice(0,240):t.query,items:[],skipped:[],warnings:mn(t.warnings)}),i===t?e:{...e,graphRetrieval:i}}function In(e,t={}){const n=t.limitBytes??Ft,r=t.warningThresholdBytes??Math.floor(n*Gt),o=Te(e);if(o<n)return{body:e,degraded:!1,telemetry:dt(e,o,["payload-within-limit"],{limitBytes:n,warningThresholdBytes:r})};let i={...e,stateSnapshot:$n(e.stateSnapshot)},s=["payload-size-guardrail","state-degraded"],c=Te(i);c>=n&&(i={...i,stateSnapshot:Ao(i.stateSnapshot)},s=[...s,"graph-retrieval-budget-enforced"],c=Te(i));const l=dt(i,c,s,{limitBytes:n,warningThresholdBytes:r});if(c>=n){const p=i.stateSnapshot.scope?.projectionMode;throw p==="yolo-story"||p==="yoloop-target"||p==="yoloop-session"||p==="yoloop-discovery"||p==="structural-required"?new st(l):new it(l)}return{body:i,degraded:!0,telemetry:l}}function yn(e){const t=e.stateSnapshot.scope?.commandId??"resolved-command";return e.args!==void 0?t:`${t}:argsRef`}function So(e){const t=Te(e);if(t<et)return t;const n=dt(e,t,["payload-warning-threshold"]);return process.stderr.write(`[Neocortex] invoke payload near server limit: trigger=${yn(e)} scope=${n.scope.kind} mode=${n.scope.projectionMode??n.scope.kind} payloadBytes=${n.payloadBytes} limit=${n.limitBytes} includedStories=${n.includedStories} omittedStories=${n.omittedStories} includedEpics=${n.includedEpics} omittedEpics=${n.omittedEpics} graphRetrieval.accepted=${n.graphRetrieval.accepted} graphRetrieval.itemCount=${n.graphRetrieval.itemCount} reasonCodes=${n.reasonCodes.join(",")||"none"}
11
11
  `),t}function _n(e,t){process.stderr.write(`[Neocortex] invoke payload guardrail: trigger=${yn(e)} scope.kind=${t.scope.kind} payloadBytes=${t.payloadBytes} limit=${t.limitBytes} includedStories=${t.includedStories} omittedStories=${t.omittedStories} includedEpics=${t.includedEpics} omittedEpics=${t.omittedEpics} graphRetrieval.accepted=${t.graphRetrieval.accepted} graphRetrieval.itemCount=${t.graphRetrieval.itemCount} reasonCodes=${t.reasonCodes.join(",")||"none"}
12
- `)}async function Ro(e){const t=Jn(e.args,{platformTarget:e.platformTarget,environment:e.environment??process.env});if(t.action==="skipped")return{shouldContinue:!0,attachToRequest:wo(t),metadata:En(t)};const n=e.bootstrapper??qn;let r;try{r=await n({projectRoot:e.projectRoot,env:e.environment??process.env,effectAuthority:e.effectAuthority})}catch{r={ok:!1,attempted:!0,installed:!1,started:!1,cached:!1,projectKey:"unknown",reasonCodes:[zn.UNEXPECTED_ERROR],publicSummary:"runner scheduler bootstrap stopped unexpectedly.",publicSafe:!0}}const o=En(t,r);if(r.ok)return{shouldContinue:!0,attachToRequest:!0,metadata:o};const i=o.reasonCodes.slice(0,5).join(",");return t.failurePolicy==="fail-open"?{shouldContinue:!0,attachToRequest:!0,metadata:{...o,failOpenWarning:!0},warning:`Runner auto-bootstrap warning (${i}); continuing fail-open for operator command.`}:{shouldContinue:!1,attachToRequest:!1,metadata:o,errorCode:"RUNNER_BOOTSTRAP_REQUIRED_FAILED",error:`Runner auto-bootstrap required but failed (${i}). Run neocortex-runner doctor or retry after resolving scheduler setup.`,exitCode:1}}function wo(e){return!e.reasonCodes.includes(Yn.SKIPPED_NON_CONTINUITY_COMMAND)}function En(e,t){return{schemaVersion:1,action:e.action,failurePolicy:e.failurePolicy,command:e.command,operation:e.operation,attempted:t?.attempted??!1,ok:t?.ok??!0,cached:t?.cached??!1,installed:t?.installed??!1,started:t?.started??!1,...t?.projectKey?{projectKey:t.projectKey}:{},reasonCodes:Y([...e.reasonCodes,...t?.reasonCodes??[]]),publicSummary:t?.publicSummary??e.publicSummary,publicSafe:!0}}function Y(e){return Array.from(new Set(e.map(t=>t.slice(0,120))))}function Ge(e,t,n){const r=Math.floor(e??t);return Number.isFinite(r)?Math.max(1,Math.min(n,r)):t}function Ye(e,t){const n=process.env[e];if(!n)return t;const r=Number(n);return Number.isFinite(r)?r:t}function N(e,t=qt){const n=typeof e=="string"&&e.trim().length>0?e.trim():"unknown",r=Z(n,t),o=Hr.test(r)?de:r;return o.length<=t?o:`${o.slice(0,t)}\u2026[TRUNCATED:${o.length-t}]`}function ut(e,t=qt){if(!(typeof e!="string"||e.trim().length===0))return N(e,t)}function lt(e,t,n,r){const o=ut(e?.targetId??t,120),i=e?.selectorKind??(o?ft(o):void 0),s=(e?.relatedJobIds??[]).map(c=>ut(c,120)).filter(c=>!!c);return{schemaVersion:1,contractVersion:"continuity-v1",targetResolutionState:n,...i?{targetKind:i}:{},...o?{targetId:o}:{},...t?{targetJobId:N(t,120)}:{},...e?.jobId?{jobId:N(e.jobId,120)}:{},...e?.goalId?{goalId:N(e.goalId,120)}:{},...e?.loopId?{loopId:N(e.loopId,120)}:{},...s.length>0?{relatedJobIds:s}:{},relatedJobCount:s.length,reasonCodes:Y(r.length>0?r:[O.OK]),publicSafe:!0}}function se(e,t,n,r,o=[]){const i=(e?.redactions?.length??0)>0,s=e?i?"unsafe":n&&r===0?"empty":"available":"unavailable",c=ut(t[t.length-1]?.eventId,120),l=o.length>0?o:s==="unavailable"?[O.WATCH_SNAPSHOT_UNAVAILABLE]:s==="empty"?[O.WATCH_NO_SUMMARIES_YET]:[O.OK];return{schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:s,...e?.generatedAt?{generatedAt:N(e.generatedAt,80)}:{},renderedSummaryCount:r,...c?{latestEventId:c}:{},reasonCodes:Y(l),publicSafe:!0}}function ne(e,t,n,r,o=[],i){const s=r[r.length-1],c=n??s?.cursor,l=!!(c&&c!==t&&r.length>0),p=i??(l?"advanced":t||c?"unchanged":"not_started"),g=o.length>0?o:p==="advanced"?[O.WATCH_CURSOR_ADVANCED]:p==="unavailable"?[O.WATCH_EVIDENCE_UNAVAILABLE]:[O.WATCH_CURSOR_UNCHANGED];return{schemaVersion:1,contractVersion:"continuity-v1",cursorState:p,...e?{initialCursor:N(e,200)}:{},...t?{currentCursor:N(t,200)}:{},...c?{nextCursor:N(c,200)}:{},cursorAdvanced:l,...s?.eventId?{eventId:N(s.eventId,120)}:{},reasonCodes:Y(g),publicSafe:!0}}function re(e){const t=e.targetEvidence;return{type:"watch_status",schemaVersion:1,contractVersion:"continuity-v1",recordType:"watch_status",command:"invoke",operation:"watch",watchStatus:e.watchStatus,active:e.active,...t?.targetResolutionState?{targetResolutionState:t.targetResolutionState}:{},...t?.targetKind?{targetKind:t.targetKind}:{},...t?.targetId?{targetId:t.targetId}:{},...t?{targetEvidence:t}:{},...e.snapshotEvidence?{snapshotEvidence:e.snapshotEvidence}:{},...e.cursorEvidence?{cursorEvidence:e.cursorEvidence}:{},...e.stopReason?{stopReason:e.stopReason}:{},reasonCodes:Y([...e.reasonCodes??[],...t?.reasonCodes??[],...e.snapshotEvidence?.reasonCodes??[],...e.cursorEvidence?.reasonCodes??[]]),generatedAt:N(e.generatedAt??new Date().toISOString(),80),publicSafe:!0}}function To(e){const t=e.targetKind&&e.targetId?`${e.targetKind}/${e.targetId}`:e.targetId??"[unresolved]",n=e.snapshotEvidence?.renderedSummaryCount??0,r=e.targetEvidence?.relatedJobCount??0,o=e.cursorEvidence?.cursorState??"unavailable",i=e.cursorEvidence?.currentCursor??"[none]",s=e.cursorEvidence?.nextCursor??"[none]",c=e.snapshotEvidence?.snapshotStatus??"not_requested",l=e.snapshotEvidence?.generatedAt??e.generatedAt;return[`[watch-status] ${e.targetResolutionState==="unresolved"||e.stopReason==="target_unresolved"?"unresolved-target":n===0&&(e.watchStatus==="waiting"||e.watchStatus==="active")?"no-new-summary":e.watchStatus==="stopped"?"stopped":"lifecycle"}`,`status=${e.watchStatus}`,`active=${e.active}`,`target=${t}`,`resolution=${e.targetResolutionState??"unavailable"}`,`relatedJobs=${r}`,`summaries=${n}`,`snapshot=${c}`,`generatedAt=${l}`,`cursor=${o}`,`current=${N(i,200)}`,`next=${N(s,200)}`,`advanced=${e.cursorEvidence?.cursorAdvanced??!1}`,`stop=${e.stopReason??"not_stopped"}`,`reasons=${e.reasonCodes.join(",")}`].join(" ")}function oe(e,t,n){if(t==="json"){n.write(JSON.stringify(e)+`
12
+ `)}async function Ro(e){const t=Jn(e.args,{platformTarget:e.platformTarget,environment:e.environment??process.env});if(t.action==="skipped")return{shouldContinue:!0,attachToRequest:wo(t),metadata:En(t)};const n=e.bootstrapper??qn;let r;try{r=await n({projectRoot:e.projectRoot,env:e.environment??process.env,effectAuthority:e.effectAuthority})}catch{r={ok:!1,attempted:!0,installed:!1,started:!1,cached:!1,projectKey:"unknown",reasonCodes:[zn.UNEXPECTED_ERROR],publicSummary:"runner scheduler bootstrap stopped unexpectedly.",publicSafe:!0}}const o=En(t,r);if(r.ok)return{shouldContinue:!0,attachToRequest:!0,metadata:o};const i=o.reasonCodes.slice(0,5).join(",");return t.failurePolicy==="fail-open"?{shouldContinue:!0,attachToRequest:!0,metadata:{...o,failOpenWarning:!0},warning:`Runner auto-bootstrap warning (${i}); continuing fail-open for operator command.`}:{shouldContinue:!1,attachToRequest:!1,metadata:o,errorCode:"RUNNER_BOOTSTRAP_REQUIRED_FAILED",error:`Runner auto-bootstrap required but failed (${i}). Run neocortex-runner doctor or retry after resolving scheduler setup.`,exitCode:1}}function wo(e){return!e.reasonCodes.includes(Yn.SKIPPED_NON_CONTINUITY_COMMAND)}function En(e,t){return{schemaVersion:1,action:e.action,failurePolicy:e.failurePolicy,command:e.command,operation:e.operation,attempted:t?.attempted??!1,ok:t?.ok??!0,cached:t?.cached??!1,installed:t?.installed??!1,started:t?.started??!1,...t?.projectKey?{projectKey:t.projectKey}:{},reasonCodes:Y([...e.reasonCodes,...t?.reasonCodes??[]]),publicSummary:t?.publicSummary??e.publicSummary,publicSafe:!0}}function Y(e){return Array.from(new Set(e.map(t=>t.slice(0,120))))}function Ge(e,t,n){const r=Math.floor(e??t);return Number.isFinite(r)?Math.max(1,Math.min(n,r)):t}function Ye(e,t){const n=process.env[e];if(!n)return t;const r=Number(n);return Number.isFinite(r)?r:t}function k(e,t=qt){const n=typeof e=="string"&&e.trim().length>0?e.trim():"unknown",r=Z(n,t),o=Wr.test(r)?de:r;return o.length<=t?o:`${o.slice(0,t)}\u2026[TRUNCATED:${o.length-t}]`}function ut(e,t=qt){if(!(typeof e!="string"||e.trim().length===0))return k(e,t)}function lt(e,t,n,r){const o=ut(e?.targetId??t,120),i=e?.selectorKind??(o?ft(o):void 0),s=(e?.relatedJobIds??[]).map(c=>ut(c,120)).filter(c=>!!c);return{schemaVersion:1,contractVersion:"continuity-v1",targetResolutionState:n,...i?{targetKind:i}:{},...o?{targetId:o}:{},...t?{targetJobId:k(t,120)}:{},...e?.jobId?{jobId:k(e.jobId,120)}:{},...e?.goalId?{goalId:k(e.goalId,120)}:{},...e?.loopId?{loopId:k(e.loopId,120)}:{},...s.length>0?{relatedJobIds:s}:{},relatedJobCount:s.length,reasonCodes:Y(r.length>0?r:[N.OK]),publicSafe:!0}}function se(e,t,n,r,o=[]){const i=(e?.redactions?.length??0)>0,s=e?i?"unsafe":n&&r===0?"empty":"available":"unavailable",c=ut(t[t.length-1]?.eventId,120),l=o.length>0?o:s==="unavailable"?[N.WATCH_SNAPSHOT_UNAVAILABLE]:s==="empty"?[N.WATCH_NO_SUMMARIES_YET]:[N.OK];return{schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:s,...e?.generatedAt?{generatedAt:k(e.generatedAt,80)}:{},renderedSummaryCount:r,...c?{latestEventId:c}:{},reasonCodes:Y(l),publicSafe:!0}}function ne(e,t,n,r,o=[],i){const s=r[r.length-1],c=n??s?.cursor,l=!!(c&&c!==t&&r.length>0),p=i??(l?"advanced":t||c?"unchanged":"not_started"),g=o.length>0?o:p==="advanced"?[N.WATCH_CURSOR_ADVANCED]:p==="unavailable"?[N.WATCH_EVIDENCE_UNAVAILABLE]:[N.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,...s?.eventId?{eventId:k(s.eventId,120)}:{},reasonCodes:Y(g),publicSafe:!0}}function re(e){const t=e.targetEvidence;return{type:"watch_status",schemaVersion:1,contractVersion:"continuity-v1",recordType:"watch_status",command:"invoke",operation:"watch",watchStatus:e.watchStatus,active:e.active,...t?.targetResolutionState?{targetResolutionState:t.targetResolutionState}:{},...t?.targetKind?{targetKind:t.targetKind}:{},...t?.targetId?{targetId:t.targetId}:{},...t?{targetEvidence:t}:{},...e.snapshotEvidence?{snapshotEvidence:e.snapshotEvidence}:{},...e.cursorEvidence?{cursorEvidence:e.cursorEvidence}:{},...e.stopReason?{stopReason:e.stopReason}:{},reasonCodes:Y([...e.reasonCodes??[],...t?.reasonCodes??[],...e.snapshotEvidence?.reasonCodes??[],...e.cursorEvidence?.reasonCodes??[]]),generatedAt:k(e.generatedAt??new Date().toISOString(),80),publicSafe:!0}}function To(e){const t=e.targetKind&&e.targetId?`${e.targetKind}/${e.targetId}`:e.targetId??"[unresolved]",n=e.snapshotEvidence?.renderedSummaryCount??0,r=e.targetEvidence?.relatedJobCount??0,o=e.cursorEvidence?.cursorState??"unavailable",i=e.cursorEvidence?.currentCursor??"[none]",s=e.cursorEvidence?.nextCursor??"[none]",c=e.snapshotEvidence?.snapshotStatus??"not_requested",l=e.snapshotEvidence?.generatedAt??e.generatedAt;return[`[watch-status] ${e.targetResolutionState==="unresolved"||e.stopReason==="target_unresolved"?"unresolved-target":n===0&&(e.watchStatus==="waiting"||e.watchStatus==="active")?"no-new-summary":e.watchStatus==="stopped"?"stopped":"lifecycle"}`,`status=${e.watchStatus}`,`active=${e.active}`,`target=${t}`,`resolution=${e.targetResolutionState??"unavailable"}`,`relatedJobs=${r}`,`summaries=${n}`,`snapshot=${c}`,`generatedAt=${l}`,`cursor=${o}`,`current=${k(i,200)}`,`next=${k(s,200)}`,`advanced=${e.cursorEvidence?.cursorAdvanced??!1}`,`stop=${e.stopReason??"not_stopped"}`,`reasons=${e.reasonCodes.join(",")}`].join(" ")}function oe(e,t,n){if(t==="json"){n.write(JSON.stringify(e)+`
13
13
  `);return}n.write(To(e)+`
14
- `)}function bo(e,t,n){return{continuityInvokeWatch:{schemaVersion:1,contractVersion:"continuity-v1",command:"invoke",operation:"watch",watchStatus:e.watchStatus,stopReason:e.stopReason??"not_stopped",targetResolutionState:e.targetResolutionState,targetKind:e.targetKind,targetId:e.targetId,snapshotStatus:e.snapshotEvidence?.snapshotStatus,snapshotGeneratedAt:e.snapshotEvidence?.generatedAt,renderedSummaryCount:e.snapshotEvidence?.renderedSummaryCount??t,cursorState:e.cursorEvidence?.cursorState,cursorAdvanced:e.cursorEvidence?.cursorAdvanced,summariesEmitted:t,polls:n,statusRecord:e,publicSafe:!0}}}function ae(e,t,n,r){return{status:e,summariesEmitted:t,polls:n,reasonCodes:r.reasonCodes,watchStatus:r.watchStatus,stopReason:r.stopReason,targetEvidence:r.targetEvidence,snapshotEvidence:r.snapshotEvidence,cursorEvidence:r.cursorEvidence,statusRecord:r,metadata:bo(r,t,n),publicSafe:!0}}function vo(e){const t=e.reasonCode?` reason=${N(e.reasonCode,80)}`:"",n=e.goalId?` goal=${N(e.goalId,100)}`:"",r=e.loopId?` loop=${N(e.loopId,100)}`:"";return`[watch] ${N(e.createdAt,80)} event=${N(e.eventId,120)} job=${N(e.jobId,100)}${n}${r} execution=${N(e.executionId,120)}${t} -- ${N(e.publicSummary)}`}function Oo(e){return{type:"processing_summary",source:"local_continuity_sqlite",eventId:N(e.eventId,120),jobId:N(e.jobId,100),...e.goalId?{goalId:N(e.goalId,100)}:{},...e.loopId?{loopId:N(e.loopId,100)}:{},executionId:N(e.executionId,120),...e.reasonCode?{reasonCode:N(e.reasonCode,80)}:{},createdAt:N(e.createdAt,80),publicSummary:N(e.publicSummary),publicSafe:!0}}function No(e,t,n){if(t==="json"){n.write(JSON.stringify(Oo(e))+`
14
+ `)}function bo(e,t,n){return{continuityInvokeWatch:{schemaVersion:1,contractVersion:"continuity-v1",command:"invoke",operation:"watch",watchStatus:e.watchStatus,stopReason:e.stopReason??"not_stopped",targetResolutionState:e.targetResolutionState,targetKind:e.targetKind,targetId:e.targetId,snapshotStatus:e.snapshotEvidence?.snapshotStatus,snapshotGeneratedAt:e.snapshotEvidence?.generatedAt,renderedSummaryCount:e.snapshotEvidence?.renderedSummaryCount??t,cursorState:e.cursorEvidence?.cursorState,cursorAdvanced:e.cursorEvidence?.cursorAdvanced,summariesEmitted:t,polls:n,statusRecord:e,publicSafe:!0}}}function ae(e,t,n,r){return{status:e,summariesEmitted:t,polls:n,reasonCodes:r.reasonCodes,watchStatus:r.watchStatus,stopReason:r.stopReason,targetEvidence:r.targetEvidence,snapshotEvidence:r.snapshotEvidence,cursorEvidence:r.cursorEvidence,statusRecord:r,metadata:bo(r,t,n),publicSafe:!0}}function vo(e){const t=e.reasonCode?` reason=${k(e.reasonCode,80)}`:"",n=e.goalId?` goal=${k(e.goalId,100)}`:"",r=e.loopId?` loop=${k(e.loopId,100)}`:"";return`[watch] ${k(e.createdAt,80)} event=${k(e.eventId,120)} job=${k(e.jobId,100)}${n}${r} execution=${k(e.executionId,120)}${t} -- ${k(e.publicSummary)}`}function Oo(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 No(e,t,n){if(t==="json"){n.write(JSON.stringify(Oo(e))+`
15
15
  `);return}n.write(vo(e)+`
16
- `)}function pt(e){return Br.has(e.status)}function ko(e,t,n){if(t){const o=e.find(i=>i.jobId===t);return!!(o&&pt(o))}return n<=0?!1:e.filter(o=>!pt(o)).length===0}function Lo(e,t,n,r){return n<r?!1:t?!e.some(o=>o.jobId===t&&!pt(o)):e.length===0}function xo(e,t){return t?.aborted?Promise.resolve():new Promise(n=>{const r=setTimeout(o,e);function o(){clearTimeout(r),t?.removeEventListener("abort",o),n()}t?.addEventListener("abort",o,{once:!0})})}function Do(e){return e.includes(F.MALFORMED)?"malformed":e.includes(F.AMBIGUOUS)?"ambiguous":e.includes("watch-target-multiple")?"multiple":e.includes("watch-evidence-unsafe")?"unsafe":e.includes(F.MISSING)||e.includes($.TARGET_UNRESOLVED)?"unresolved":"unavailable"}function Cn(e,t){const n=t?Le(t):void 0,r=Y([...e,$.TARGET_UNRESOLVED,O.WATCH_TARGET_UNRESOLVED]),o=lt(n,n?.targetId,Do(r),r),i=se({generatedAt:new Date().toISOString()},[],!1,0,[O.WATCH_TARGET_UNRESOLVED]),s=ne(void 0,void 0,void 0,[],[O.WATCH_TARGET_UNRESOLVED],"unavailable");return re({watchStatus:"blocked",active:!1,targetEvidence:o,snapshotEvidence:i,cursorEvidence:s,stopReason:"target_unresolved",reasonCodes:r,generatedAt:i.generatedAt})}function Po(e,t,n,r){const o=Cn(e,Sn(t));return oe(o,n,r),ae("target-unresolved",0,0,o)}async function jo(e){if(e.signal?.aborted){const _=lt(e.target??Le(e.targetJobId),e.targetJobId,e.target??e.targetJobId?"resolved":"unresolved",[$.CANCELLED]),R=se(void 0,[],!1,0),I=ne(e.initialCursor,e.initialCursor,e.initialCursor,[],[$.CANCELLED],"unavailable"),M=re({watchStatus:"stopped",active:!1,targetEvidence:_,snapshotEvidence:R,cursorEvidence:I,stopReason:"cancelled",reasonCodes:[$.CANCELLED]});return ae("cancelled",0,0,M)}const t=e.target??Le(e.targetJobId),n=e.targetJobId??t?.targetId,r=e.stdout??process.stdout;if(!t){const _=Cn([F.MISSING,$.TARGET_UNRESOLVED]);return oe(_,e.format,r),ae("target-unresolved",0,0,_)}const o=Ge(e.limit??Ye("NEOCORTEX_INVOKE_WATCH_LIMIT",Nt),Nt,50),i=Math.max(50,Ge(e.pollIntervalMs??Ye("NEOCORTEX_INVOKE_WATCH_POLL_INTERVAL_MS",xt),xt,6e4)),s=Ge(e.maxIdlePolls??Ye("NEOCORTEX_INVOKE_WATCH_MAX_IDLE_POLLS",kt),kt,120),c=Ge(e.maxPolls??Ye("NEOCORTEX_INVOKE_WATCH_MAX_POLLS",Lt),Lt,86400),l=e.sleep??xo;let p=e.initialCursor,g=0,C=0,f=0;const d=lt(t,n,"resolved",[O.OK]),h={schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:"pending",renderedSummaryCount:0,reasonCodes:[O.WATCH_RENDER_PENDING],publicSafe:!0},S=ne(e.initialCursor,p,p,[],e.initialCursor?[O.WATCH_CURSOR_UNCHANGED]:[O.WATCH_NO_SUMMARIES_YET],e.initialCursor?"unchanged":"not_started");oe(re({watchStatus:"active",active:!0,targetEvidence:d,snapshotEvidence:h,cursorEvidence:S,stopReason:"not_stopped",reasonCodes:[O.OK]}),e.format,r);let E;try{E=await Kn({projectRoot:e.projectRoot,strictReadOnly:e.strictReadOnly})}catch{const _=se(void 0,[],!1,g,[O.WATCH_SNAPSHOT_UNAVAILABLE]),R=ne(e.initialCursor,p,p,[],[O.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),I=re({watchStatus:"blocked",active:!1,targetEvidence:d,snapshotEvidence:_,cursorEvidence:R,stopReason:"unavailable_evidence",reasonCodes:[$.STORE_UNAVAILABLE]});return oe(I,e.format,r),ae("store-unavailable",g,f,I)}try{for(;!e.signal?.aborted&&f<c;){f+=1;const _=p,R=E.collectProcessingOutputSummaryCursor({...p?{cursor:p}:{},...t?{target:t}:{},...n?{jobId:n}:{},limit:o}),I=E.collectSnapshot({jobLimit:50,processingSummaryLimit:1}),M=I.jobs;if(R.summaries.length>0){for(const V of R.summaries)No(V,e.format,r),g+=1;p=R.nextCursor??R.summaries[R.summaries.length-1]?.cursor??p,C=0}else p=R.nextCursor??p,C+=1;const L=se(I,R.summaries,!0,R.summaries.length),D=ne(e.initialCursor,_,p,R.summaries,R.summaries.length>0?[O.WATCH_CURSOR_ADVANCED]:[O.WATCH_NO_SUMMARIES_YET]);if(oe(re({watchStatus:R.summaries.length>0?"polling":"waiting",active:!0,targetEvidence:d,snapshotEvidence:L,cursorEvidence:D,stopReason:"not_stopped",reasonCodes:R.summaries.length>0?[O.WATCH_CURSOR_ADVANCED]:[O.WATCH_NO_SUMMARIES_YET],generatedAt:I.generatedAt}),e.format,r),!R.hasMore&&ko(M,n,g)){const V=se(I,R.summaries,!1,g,[$.COMPLETED]),x=ne(e.initialCursor,_,p,R.summaries,[$.COMPLETED],"exhausted"),v=re({watchStatus:"stopped",active:!1,targetEvidence:d,snapshotEvidence:V,cursorEvidence:x,stopReason:"not_stopped",reasonCodes:[$.COMPLETED],generatedAt:I.generatedAt});return oe(v,e.format,r),ae("completed",g,f,v)}if(!R.hasMore&&Lo(M,n,C,s)){const V=se(I,R.summaries,!1,g,[O.WATCH_STOP_IDLE_LIMIT_REACHED]),x=ne(e.initialCursor,_,p,R.summaries,[O.WATCH_STOP_IDLE_LIMIT_REACHED],"exhausted"),v=re({watchStatus:"stopped",active:!1,targetEvidence:d,snapshotEvidence:V,cursorEvidence:x,stopReason:"idle_limit_reached",reasonCodes:[$.IDLE_TIMEOUT,O.WATCH_STOP_IDLE_LIMIT_REACHED],generatedAt:I.generatedAt});return oe(v,e.format,r),ae("idle-timeout",g,f,v)}R.hasMore||await l(i,e.signal)}}catch{const _=se(void 0,[],!1,g,[O.WATCH_SNAPSHOT_UNAVAILABLE]),R=ne(e.initialCursor,p,p,[],[O.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),I=re({watchStatus:"blocked",active:!1,targetEvidence:d,snapshotEvidence:_,cursorEvidence:R,stopReason:"unavailable_evidence",reasonCodes:[$.STORE_UNAVAILABLE]});return oe(I,e.format,r),ae("store-unavailable",g,f,I)}finally{E.close()}if(e.signal?.aborted){const _=se(void 0,[],!1,g,[$.CANCELLED]),R=ne(e.initialCursor,p,p,[],[$.CANCELLED],"unavailable"),I=re({watchStatus:"stopped",active:!1,targetEvidence:d,snapshotEvidence:_,cursorEvidence:R,stopReason:"cancelled",reasonCodes:[$.CANCELLED]});return oe(I,e.format,r),ae("cancelled",g,f,I)}const T=se(void 0,[],!1,g,[O.WATCH_STOP_MAX_POLLS_REACHED]),k=ne(e.initialCursor,p,p,[],[O.WATCH_STOP_MAX_POLLS_REACHED],"exhausted"),w=re({watchStatus:"stopped",active:!1,targetEvidence:d,snapshotEvidence:T,cursorEvidence:k,stopReason:"max_polls_reached",reasonCodes:[$.MAX_POLLS,O.WATCH_STOP_MAX_POLLS_REACHED]});return oe(w,e.format,r),ae("max-polls",g,f,w)}function Q(e){const t=e.trim().replace(/^@/,"").match(/^(job|goal|loop)-([JGL])(\d{3,})$/i);if(!t)return;const n=t[1].toLowerCase(),r=t[2].toUpperCase();if(!(n==="job"&&r!=="J"||n==="goal"&&r!=="G"||n==="loop"&&r!=="L"))return`${n}-${r}${t[3]}`}function ft(e){if(e.startsWith("job-J"))return"job";if(e.startsWith("goal-G"))return"goal";if(e.startsWith("loop-L"))return"loop"}function An(e){const t=[],n=/(?:^|[\s"'([,{])@?(job-[Jj]\d{3,}|goal-[Gg]\d{3,}|loop-[Ll]\d{3,})(?=$|[\s"')\]},.;:!?])/g;let r;for(;(r=n.exec(e))!==null;){const o=Q(r[1]);o&&t.push(o)}return Y(t)}function Sn(e){return An(e)[0]}function Le(e){const t=e?Q(e):void 0;if(t){if(t.startsWith("job-J"))return{selectorKind:"job",targetId:t,jobId:t,publicSafe:!0};if(t.startsWith("goal-G"))return{selectorKind:"goal",targetId:t,goalId:t,publicSafe:!0};if(t.startsWith("loop-L"))return{selectorKind:"loop",targetId:t,loopId:t,publicSafe:!0}}}function gt(e){return Y(e.filter(t=>typeof t=="string").map(t=>Q(t)).filter(t=>!!t?.startsWith("job-J")))}function Mo(e,t){const n=gt(t).filter(r=>r!==e.targetId&&r!==e.jobId);return n.length>0?{...e,relatedJobIds:n}:e}function Uo(e){if(!e)return;const t=m(e.target)?e.target:void 0,n=typeof e.selectorKind=="string"?e.selectorKind:typeof t?.selectorKind=="string"?t.selectorKind:void 0,r=typeof e.targetId=="string"?Q(e.targetId):typeof t?.targetId=="string"?Q(t.targetId):typeof e.targetJobId=="string"?Q(e.targetJobId):void 0,o=Le(r);if(!o||n&&n!==o.selectorKind)return;const i=Array.isArray(e.relatedJobIds)?e.relatedJobIds:Array.isArray(t?.relatedJobIds)?t.relatedJobIds:void 0,s=gt([...i??[],e.jobId,t?.jobId,e.targetJobId,t?.targetJobId]).filter(c=>c!==o.targetId&&c!==o.jobId);return{...o,...typeof(e.jobId??t?.jobId)=="string"?{jobId:Q(e.jobId??t?.jobId)??o.jobId}:{},...typeof(e.goalId??t?.goalId)=="string"?{goalId:Q(e.goalId??t?.goalId)??o.goalId}:{},...typeof(e.loopId??t?.loopId)=="string"?{loopId:Q(e.loopId??t?.loopId)??o.loopId}:{},...s.length>0?{relatedJobIds:s}:{}}}function Rn(e){const t=e.trim().split(/\s+/).filter(Boolean),n=t[0]?.replace(/^\*/,"").toLowerCase(),r=t[1]?.replace(/^--/,"").toLowerCase();return(n==="jobs"||n==="job"||n==="continuity-jobs"||n==="61")&&r==="watch"}const W=Object.freeze({ACTIVE:"command-level-watch-active",INACTIVE:"command-level-watch-inactive",DUPLICATE:"command-level-watch-duplicate",AMBIGUOUS:"command-level-watch-ambiguous",QUOTED:"command-level-watch-quoted",MALFORMED:"command-level-watch-malformed",NON_FINAL:"command-level-watch-non-final",UNRESOLVED:"command-level-watch-unresolved",UNSUPPORTED:"command-level-watch-unsupported",TARGET_INVALID:"command-level-watch-target-invalid"}),Vo=new Set(["create","start","resume"]),Bo=new Set(["create","resume","run-once"]);function ht(e,t,n,r,o){return{schemaVersion:1,contractVersion:"continuity-v1",...n?{command:n}:{},...r?{operation:r}:{},active:e,...o?{watchToken:o}:{},reasonCodes:Y(t),serverHeldStream:!1,allJobsPolling:!1,targetResolution:e?"required-after-dispatch":"inactive",publicSafe:!0}}function G(e,t=[],n,r){const o=t.length>0?t:[W.INACTIVE];return{args:e,watch:!1,reasonCodes:o,metadata:ht(!1,o,n,r),publicSafe:!0}}function $o(e){const t=e.trim().split(/\s+/).filter(Boolean),n=t.slice(2).filter(i=>i==="--watch").length;if(n===0)return G(e,[],"jobs","watch");if(n!==1)return G(e,[W.AMBIGUOUS],"jobs","watch");const r=t.filter((i,s)=>s<2||i!=="--watch").join(" ");return Rn(r)?r.trim().split(/\s+/).filter(Boolean).slice(2).length!==1?G(e,[W.AMBIGUOUS],"jobs","watch"):Sn(r)?{args:r,watch:!0,reasonCodes:[W.ACTIVE],metadata:ht(!0,[W.ACTIVE],"jobs","watch"),publicSafe:!0}:G(e,[W.TARGET_INVALID],"jobs","watch"):G(e,[W.UNSUPPORTED],"jobs","watch")}function Ho(e){const t=[];let n=!1,r=0;for(;r<e.length;){for(;r<e.length&&/\s/.test(e[r]);)r+=1;if(r>=e.length)break;const o=r;let i="",s=!1,c=null;for(;r<e.length;){const l=e[r];if(c){if(l===c){s=!0,c=null,r+=1;continue}if(l==="\\"&&r+1<e.length){i+=e[r+1],r+=2;continue}i+=l,r+=1;continue}if(/\s/.test(l))break;if(l==='"'||l==="'"){s=!0,c=l,r+=1;continue}i+=l,r+=1}c&&(n=!0),t.push({value:i,start:o,end:r,quoted:s})}return{tokens:t,malformed:n}}function Wo(e){if(!e||e.quoted)return;const t=e.value.replace(/^\*/,"").toLowerCase();return t==="goal"||t==="loop"?t:void 0}function Fo(e,t){if(!e||e==="jobs"||!t||t.quoted)return;const n=t.value.toLowerCase();return(e==="goal"?Vo:Bo).has(n)?n:void 0}function Go(e){return!e.quoted&&e.value!=="--watch"&&e.value.toLowerCase().startsWith("--watch")}function Yo(e){const{tokens:t,malformed:n}=Ho(e),r=Wo(t[0]),o=Fo(r,t[1]);if(n)return G(e,[W.MALFORMED],r,o);const i=t.filter(f=>f.value==="--watch"&&!f.quoted),s=t.filter(f=>f.value==="--watch"&&f.quoted),c=t.filter(Go);if(!(i.length>0||s.length>0||c.length>0))return G(e,[],r,o);if(i.length>1)return G(e,[W.DUPLICATE],r,o);if(i.length===1&&(s.length>0||c.length>0))return G(e,[W.AMBIGUOUS],r,o);if(s.length>0)return G(e,[W.QUOTED],r,o);if(c.length>0)return G(e,[W.MALFORMED],r,o);const p=i[0];if(!p)return G(e,[],r,o);if(t[t.length-1]!==p)return G(e,[W.NON_FINAL],r,o);if(!r||!o)return G(e,[W.UNRESOLVED],r,o);const g=`${e.slice(0,p.start)}${e.slice(p.end)}`.trim(),C={literal:"--watch",position:"final",start:p.start,end:p.end,quoted:!1,publicSafe:!0};return{args:g,watch:!0,reasonCodes:[W.ACTIVE],metadata:ht(!0,[W.ACTIVE],r,o,C),publicSafe:!0}}function Jo(e){return Rn(e)?$o(e):Yo(e)}function zo(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&$r.has(t)):[]}function be(e){return{disabled:!0,reasonCodes:Y(e.length>0?e:[F.MISSING])}}function mt(e,t,n=[],r){const o=Le(t);if(o)return{source:e,target:Mo(o,n),targetJobId:o.targetId,...r?{initialCursor:r}:{},serverHeldStream:!1}}function qo(e){const t=new Map;for(const n of e){const r=`${n.target.selectorKind}:${n.target.targetId}`,o=t.get(r);if(!o){t.set(r,n);continue}const i=Y([...o.target.relatedJobIds??[],...n.target.relatedJobIds??[]]);t.set(r,{...o,target:i.length>0?{...o.target,relatedJobIds:i}:o.target,initialCursor:o.initialCursor??n.initialCursor})}return Array.from(t.values())}function fe(e,t,n,r){return{source:e,hasEvidence:t,candidates:qo(n.filter(o=>!!o)),...r&&r.length>0?{disabledReasonCodes:Y(r)}:{}}}function Ko(e,t){return e.target.selectorKind===t.target.selectorKind&&e.target.targetId===t.target.targetId}function xe(e,t){const n=Y(e.filter(r=>typeof r=="string").map(r=>Q(r)).filter(r=>!!r));if(t){const r=n.find(o=>ft(o)===t);if(r)return r}return n[0]}function Je(e,t){return Y(e.filter(n=>typeof n=="string").map(n=>Q(n)).filter(n=>!!n)).find(n=>ft(n)===t)}function Xo(e){const t=m(e?.continuity)?e.continuity:void 0,n=m(t?.jobs)?t.jobs:void 0,r=m(n?.watcher)?n.watcher:void 0,o=zo(r?.reasonCodes??n?.reasonCodes);if(!r)return fe("watcher-metadata",o.length>0,[],o);if(r.active===!1||o.length>0)return fe("watcher-metadata",!0,[],o.length>0?o:[F.MALFORMED]);if(r.serverHeldStream!==!1)return fe("watcher-metadata",!0,[],[F.SERVER_HELD_STREAM]);const i=Uo(r);if(!i)return fe("watcher-metadata",!0,[],[F.MISSING]);const s=typeof r.initialCursor=="string"?r.initialCursor:void 0;return fe("watcher-metadata",!0,[{source:"watcher-metadata",target:i,targetJobId:i.targetId,...s?{initialCursor:s}:{},serverHeldStream:!1}])}function wn(e,t){const n=m(e.loopJobPlan)?e.loopJobPlan:void 0,r=m(n?.metadata)?n.metadata:void 0,o=m(e.metadata)?e.metadata:void 0,s=(t==="goal"?xe([e.goalId,e.targetGoalId,e.campaignId,e.jobId,e.targetJobId,o?.goalId,o?.campaignId,o?.jobId],"goal"):xe([e.loopId,e.targetLoopId,e.jobId,e.targetJobId,o?.loopId,o?.jobId,r?.loopId,r?.jobId],"loop"))??xe([e.jobId,e.targetJobId,o?.jobId,r?.jobId]);return mt("goal-loop-continuity-metadata",s,[e.jobId,e.targetJobId,o?.jobId,r?.jobId])}function Zo(e){const t=m(e?.continuity)?e.continuity:void 0,n=m(t?.goal)?t.goal:void 0,r=m(t?.loop)?t.loop:void 0,o=[n?wn(n,"goal"):void 0,r?wn(r,"loop"):void 0],i=!!(n||r);return fe("goal-loop-continuity-metadata",i,o,i&&o.every(s=>!s)?[F.MISSING]:void 0)}function Qo(e){return Array.isArray(e)?e.filter(m):m(e)?Array.isArray(e.operationLogs)?e.operationLogs.filter(m):m(e.operationLog)?[e.operationLog]:Array.isArray(e.operations)?[e]:[]:[]}function Tn(e,t){const n=m(t.metadata)?t.metadata:void 0,r=Je([t.goalId,t.targetGoalId,t.campaignId,n?.goalId,n?.campaignId,t.jobId,n?.jobId],"goal"),o=Je([t.loopId,t.targetLoopId,n?.loopId,t.jobId,n?.jobId],"loop"),i=xe([t.jobId,t.targetJobId,n?.jobId],"job"),s=r??o??i;if(!s)return;const c=e.get(s)??{targetId:s,relatedJobIds:[]};c.relatedJobIds.push(...gt([i,t.jobId,t.targetJobId,n?.jobId])),e.set(s,c)}function ei(e){const t=m(e.metadata)?e.metadata:void 0;return!!(Je([e.goalId,e.targetGoalId,e.campaignId,t?.goalId,t?.campaignId,e.jobId,t?.jobId],"goal")??Je([e.loopId,e.targetLoopId,t?.loopId,e.jobId,t?.jobId],"loop"))}function ti(e){const t=m(e.metadata)?e.metadata:void 0;return!!xe([e.goalId,e.targetGoalId,e.campaignId,e.loopId,e.targetLoopId,e.jobId,e.targetJobId,t?.goalId,t?.campaignId,t?.loopId,t?.jobId])}function bn(e,t){const n=[];for(const s of["metadata","job","event","receipt","processingOutputSummary"]){const c=t[s];m(c)&&n.push(c)}const r=m(t.event)?t.event:void 0;m(r?.metadata)&&n.push(r.metadata),m(r?.processingOutputSummary)&&n.push(r.processingOutputSummary);const o=m(t.receipt)?t.receipt:void 0;m(o?.metadata)&&n.push(o.metadata);const i=n.some(ti);for(const s of n)Tn(e,s);(!i||ei(t))&&Tn(e,t)}function ni(e){const t=Qo(e?.continuityStateUpdate),n=new Map;for(const o of t){bn(n,o);const i=Array.isArray(o.operations)?o.operations.filter(m):[];for(const s of i)bn(n,s)}const r=Array.from(n.values()).map(o=>mt("continuity-state-update-operation-log",o.targetId,o.relatedJobIds));return fe("continuity-state-update-operation-log",t.length>0,r,t.length>0&&r.every(o=>!o)?[F.MISSING]:void 0)}function ri(e){const t=An(e);return fe("explicit-args",t.length>0,t.map(n=>mt("explicit-args",n)))}function oi(e,t){const n=[Xo(e),Zo(e),ni(e),ri(t)];for(let r=0;r<n.length;r+=1){const o=n[r];if(!o.hasEvidence)continue;if(o.disabledReasonCodes&&o.disabledReasonCodes.length>0)return be(o.disabledReasonCodes);if(o.candidates.length!==1)return be([o.candidates.length>1?F.AMBIGUOUS:F.MISSING]);const i=o.candidates[0];for(const s of n.slice(r+1)){if(!s.hasEvidence)continue;if(s.disabledReasonCodes&&s.disabledReasonCodes.length>0)return be(s.disabledReasonCodes);if(s.candidates.length>1)return be([F.AMBIGUOUS]);const c=s.candidates[0];if(c&&!Ko(i,c))return be([F.CONFLICT])}return{target:i.target,targetJobId:i.targetJobId,...i.initialCursor?{initialCursor:i.initialCursor}:{},source:i.source,serverHeldStream:!1}}return be([F.MISSING])}async function vn(e,t,n,r={}){const i=await ct(e,"/api/v1/invoke",t,n,r);if(i.networkFailure||!i.response)return{ok:!1,status:0,error:"Network error after bounded retries"};const{response:s,text:c,parsed:l}=i;try{if(!s.ok)return{ok:!1,status:s.status,error:Object.keys(l).length>0?`${l.error_code??"ERROR"}: ${l.message??c}`:`HTTP ${s.status}: ${c}`,errorBody:Object.keys(l).length>0?l:void 0};const p=l,g=s.headers.get("X-Client-Version-Warning");return g&&!pn&&(pn=!0,process.stderr.write(`
16
+ `)}function pt(e){return Br.has(e.status)}function ko(e,t,n){if(t){const o=e.find(i=>i.jobId===t);return!!(o&&pt(o))}return n<=0?!1:e.filter(o=>!pt(o)).length===0}function Lo(e,t,n,r){return n<r?!1:t?!e.some(o=>o.jobId===t&&!pt(o)):e.length===0}function xo(e,t){return t?.aborted?Promise.resolve():new Promise(n=>{const r=setTimeout(o,e);function o(){clearTimeout(r),t?.removeEventListener("abort",o),n()}t?.addEventListener("abort",o,{once:!0})})}function Do(e){return e.includes(F.MALFORMED)?"malformed":e.includes(F.AMBIGUOUS)?"ambiguous":e.includes("watch-target-multiple")?"multiple":e.includes("watch-evidence-unsafe")?"unsafe":e.includes(F.MISSING)||e.includes($.TARGET_UNRESOLVED)?"unresolved":"unavailable"}function Cn(e,t){const n=t?Le(t):void 0,r=Y([...e,$.TARGET_UNRESOLVED,N.WATCH_TARGET_UNRESOLVED]),o=lt(n,n?.targetId,Do(r),r),i=se({generatedAt:new Date().toISOString()},[],!1,0,[N.WATCH_TARGET_UNRESOLVED]),s=ne(void 0,void 0,void 0,[],[N.WATCH_TARGET_UNRESOLVED],"unavailable");return re({watchStatus:"blocked",active:!1,targetEvidence:o,snapshotEvidence:i,cursorEvidence:s,stopReason:"target_unresolved",reasonCodes:r,generatedAt:i.generatedAt})}function Po(e,t,n,r){const o=Cn(e,Sn(t));return oe(o,n,r),ae("target-unresolved",0,0,o)}async function jo(e){if(e.signal?.aborted){const _=lt(e.target??Le(e.targetJobId),e.targetJobId,e.target??e.targetJobId?"resolved":"unresolved",[$.CANCELLED]),R=se(void 0,[],!1,0),I=ne(e.initialCursor,e.initialCursor,e.initialCursor,[],[$.CANCELLED],"unavailable"),M=re({watchStatus:"stopped",active:!1,targetEvidence:_,snapshotEvidence:R,cursorEvidence:I,stopReason:"cancelled",reasonCodes:[$.CANCELLED]});return ae("cancelled",0,0,M)}const t=e.target??Le(e.targetJobId),n=e.targetJobId??t?.targetId,r=e.stdout??process.stdout;if(!t){const _=Cn([F.MISSING,$.TARGET_UNRESOLVED]);return oe(_,e.format,r),ae("target-unresolved",0,0,_)}const o=Ge(e.limit??Ye("NEOCORTEX_INVOKE_WATCH_LIMIT",Nt),Nt,50),i=Math.max(50,Ge(e.pollIntervalMs??Ye("NEOCORTEX_INVOKE_WATCH_POLL_INTERVAL_MS",xt),xt,6e4)),s=Ge(e.maxIdlePolls??Ye("NEOCORTEX_INVOKE_WATCH_MAX_IDLE_POLLS",kt),kt,120),c=Ge(e.maxPolls??Ye("NEOCORTEX_INVOKE_WATCH_MAX_POLLS",Lt),Lt,86400),l=e.sleep??xo;let p=e.initialCursor,g=0,C=0,f=0;const d=lt(t,n,"resolved",[N.OK]),h={schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:"pending",renderedSummaryCount:0,reasonCodes:[N.WATCH_RENDER_PENDING],publicSafe:!0},S=ne(e.initialCursor,p,p,[],e.initialCursor?[N.WATCH_CURSOR_UNCHANGED]:[N.WATCH_NO_SUMMARIES_YET],e.initialCursor?"unchanged":"not_started");oe(re({watchStatus:"active",active:!0,targetEvidence:d,snapshotEvidence:h,cursorEvidence:S,stopReason:"not_stopped",reasonCodes:[N.OK]}),e.format,r);let E;try{E=await Kn({projectRoot:e.projectRoot,strictReadOnly:e.strictReadOnly})}catch{const _=se(void 0,[],!1,g,[N.WATCH_SNAPSHOT_UNAVAILABLE]),R=ne(e.initialCursor,p,p,[],[N.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),I=re({watchStatus:"blocked",active:!1,targetEvidence:d,snapshotEvidence:_,cursorEvidence:R,stopReason:"unavailable_evidence",reasonCodes:[$.STORE_UNAVAILABLE]});return oe(I,e.format,r),ae("store-unavailable",g,f,I)}try{for(;!e.signal?.aborted&&f<c;){f+=1;const _=p,R=E.collectProcessingOutputSummaryCursor({...p?{cursor:p}:{},...t?{target:t}:{},...n?{jobId:n}:{},limit:o}),I=E.collectSnapshot({jobLimit:50,processingSummaryLimit:1}),M=I.jobs;if(R.summaries.length>0){for(const V of R.summaries)No(V,e.format,r),g+=1;p=R.nextCursor??R.summaries[R.summaries.length-1]?.cursor??p,C=0}else p=R.nextCursor??p,C+=1;const L=se(I,R.summaries,!0,R.summaries.length),D=ne(e.initialCursor,_,p,R.summaries,R.summaries.length>0?[N.WATCH_CURSOR_ADVANCED]:[N.WATCH_NO_SUMMARIES_YET]);if(oe(re({watchStatus:R.summaries.length>0?"polling":"waiting",active:!0,targetEvidence:d,snapshotEvidence:L,cursorEvidence:D,stopReason:"not_stopped",reasonCodes:R.summaries.length>0?[N.WATCH_CURSOR_ADVANCED]:[N.WATCH_NO_SUMMARIES_YET],generatedAt:I.generatedAt}),e.format,r),!R.hasMore&&ko(M,n,g)){const V=se(I,R.summaries,!1,g,[$.COMPLETED]),x=ne(e.initialCursor,_,p,R.summaries,[$.COMPLETED],"exhausted"),O=re({watchStatus:"stopped",active:!1,targetEvidence:d,snapshotEvidence:V,cursorEvidence:x,stopReason:"not_stopped",reasonCodes:[$.COMPLETED],generatedAt:I.generatedAt});return oe(O,e.format,r),ae("completed",g,f,O)}if(!R.hasMore&&Lo(M,n,C,s)){const V=se(I,R.summaries,!1,g,[N.WATCH_STOP_IDLE_LIMIT_REACHED]),x=ne(e.initialCursor,_,p,R.summaries,[N.WATCH_STOP_IDLE_LIMIT_REACHED],"exhausted"),O=re({watchStatus:"stopped",active:!1,targetEvidence:d,snapshotEvidence:V,cursorEvidence:x,stopReason:"idle_limit_reached",reasonCodes:[$.IDLE_TIMEOUT,N.WATCH_STOP_IDLE_LIMIT_REACHED],generatedAt:I.generatedAt});return oe(O,e.format,r),ae("idle-timeout",g,f,O)}R.hasMore||await l(i,e.signal)}}catch{const _=se(void 0,[],!1,g,[N.WATCH_SNAPSHOT_UNAVAILABLE]),R=ne(e.initialCursor,p,p,[],[N.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),I=re({watchStatus:"blocked",active:!1,targetEvidence:d,snapshotEvidence:_,cursorEvidence:R,stopReason:"unavailable_evidence",reasonCodes:[$.STORE_UNAVAILABLE]});return oe(I,e.format,r),ae("store-unavailable",g,f,I)}finally{E.close()}if(e.signal?.aborted){const _=se(void 0,[],!1,g,[$.CANCELLED]),R=ne(e.initialCursor,p,p,[],[$.CANCELLED],"unavailable"),I=re({watchStatus:"stopped",active:!1,targetEvidence:d,snapshotEvidence:_,cursorEvidence:R,stopReason:"cancelled",reasonCodes:[$.CANCELLED]});return oe(I,e.format,r),ae("cancelled",g,f,I)}const T=se(void 0,[],!1,g,[N.WATCH_STOP_MAX_POLLS_REACHED]),v=ne(e.initialCursor,p,p,[],[N.WATCH_STOP_MAX_POLLS_REACHED],"exhausted"),w=re({watchStatus:"stopped",active:!1,targetEvidence:d,snapshotEvidence:T,cursorEvidence:v,stopReason:"max_polls_reached",reasonCodes:[$.MAX_POLLS,N.WATCH_STOP_MAX_POLLS_REACHED]});return oe(w,e.format,r),ae("max-polls",g,f,w)}function Q(e){const t=e.trim().replace(/^@/,"").match(/^(job|goal|loop)-([JGL])(\d{3,})$/i);if(!t)return;const n=t[1].toLowerCase(),r=t[2].toUpperCase();if(!(n==="job"&&r!=="J"||n==="goal"&&r!=="G"||n==="loop"&&r!=="L"))return`${n}-${r}${t[3]}`}function ft(e){if(e.startsWith("job-J"))return"job";if(e.startsWith("goal-G"))return"goal";if(e.startsWith("loop-L"))return"loop"}function An(e){const t=[],n=/(?:^|[\s"'([,{])@?(job-[Jj]\d{3,}|goal-[Gg]\d{3,}|loop-[Ll]\d{3,})(?=$|[\s"')\]},.;:!?])/g;let r;for(;(r=n.exec(e))!==null;){const o=Q(r[1]);o&&t.push(o)}return Y(t)}function Sn(e){return An(e)[0]}function Le(e){const t=e?Q(e):void 0;if(t){if(t.startsWith("job-J"))return{selectorKind:"job",targetId:t,jobId:t,publicSafe:!0};if(t.startsWith("goal-G"))return{selectorKind:"goal",targetId:t,goalId:t,publicSafe:!0};if(t.startsWith("loop-L"))return{selectorKind:"loop",targetId:t,loopId:t,publicSafe:!0}}}function gt(e){return Y(e.filter(t=>typeof t=="string").map(t=>Q(t)).filter(t=>!!t?.startsWith("job-J")))}function Mo(e,t){const n=gt(t).filter(r=>r!==e.targetId&&r!==e.jobId);return n.length>0?{...e,relatedJobIds:n}:e}function Uo(e){if(!e)return;const t=m(e.target)?e.target:void 0,n=typeof e.selectorKind=="string"?e.selectorKind:typeof t?.selectorKind=="string"?t.selectorKind:void 0,r=typeof e.targetId=="string"?Q(e.targetId):typeof t?.targetId=="string"?Q(t.targetId):typeof e.targetJobId=="string"?Q(e.targetJobId):void 0,o=Le(r);if(!o||n&&n!==o.selectorKind)return;const i=Array.isArray(e.relatedJobIds)?e.relatedJobIds:Array.isArray(t?.relatedJobIds)?t.relatedJobIds:void 0,s=gt([...i??[],e.jobId,t?.jobId,e.targetJobId,t?.targetJobId]).filter(c=>c!==o.targetId&&c!==o.jobId);return{...o,...typeof(e.jobId??t?.jobId)=="string"?{jobId:Q(e.jobId??t?.jobId)??o.jobId}:{},...typeof(e.goalId??t?.goalId)=="string"?{goalId:Q(e.goalId??t?.goalId)??o.goalId}:{},...typeof(e.loopId??t?.loopId)=="string"?{loopId:Q(e.loopId??t?.loopId)??o.loopId}:{},...s.length>0?{relatedJobIds:s}:{}}}function Rn(e){const t=e.trim().split(/\s+/).filter(Boolean),n=t[0]?.replace(/^\*/,"").toLowerCase(),r=t[1]?.replace(/^--/,"").toLowerCase();return(n==="jobs"||n==="job"||n==="continuity-jobs"||n==="61")&&r==="watch"}const H=Object.freeze({ACTIVE:"command-level-watch-active",INACTIVE:"command-level-watch-inactive",DUPLICATE:"command-level-watch-duplicate",AMBIGUOUS:"command-level-watch-ambiguous",QUOTED:"command-level-watch-quoted",MALFORMED:"command-level-watch-malformed",NON_FINAL:"command-level-watch-non-final",UNRESOLVED:"command-level-watch-unresolved",UNSUPPORTED:"command-level-watch-unsupported",TARGET_INVALID:"command-level-watch-target-invalid"}),Vo=new Set(["create","start","resume"]),Bo=new Set(["create","resume","run-once"]);function ht(e,t,n,r,o){return{schemaVersion:1,contractVersion:"continuity-v1",...n?{command:n}:{},...r?{operation:r}:{},active:e,...o?{watchToken:o}:{},reasonCodes:Y(t),serverHeldStream:!1,allJobsPolling:!1,targetResolution:e?"required-after-dispatch":"inactive",publicSafe:!0}}function G(e,t=[],n,r){const o=t.length>0?t:[H.INACTIVE];return{args:e,watch:!1,reasonCodes:o,metadata:ht(!1,o,n,r),publicSafe:!0}}function $o(e){const t=e.trim().split(/\s+/).filter(Boolean),n=t.slice(2).filter(i=>i==="--watch").length;if(n===0)return G(e,[],"jobs","watch");if(n!==1)return G(e,[H.AMBIGUOUS],"jobs","watch");const r=t.filter((i,s)=>s<2||i!=="--watch").join(" ");return Rn(r)?r.trim().split(/\s+/).filter(Boolean).slice(2).length!==1?G(e,[H.AMBIGUOUS],"jobs","watch"):Sn(r)?{args:r,watch:!0,reasonCodes:[H.ACTIVE],metadata:ht(!0,[H.ACTIVE],"jobs","watch"),publicSafe:!0}:G(e,[H.TARGET_INVALID],"jobs","watch"):G(e,[H.UNSUPPORTED],"jobs","watch")}function Wo(e){const t=[];let n=!1,r=0;for(;r<e.length;){for(;r<e.length&&/\s/.test(e[r]);)r+=1;if(r>=e.length)break;const o=r;let i="",s=!1,c=null;for(;r<e.length;){const l=e[r];if(c){if(l===c){s=!0,c=null,r+=1;continue}if(l==="\\"&&r+1<e.length){i+=e[r+1],r+=2;continue}i+=l,r+=1;continue}if(/\s/.test(l))break;if(l==='"'||l==="'"){s=!0,c=l,r+=1;continue}i+=l,r+=1}c&&(n=!0),t.push({value:i,start:o,end:r,quoted:s})}return{tokens:t,malformed:n}}function Ho(e){if(!e||e.quoted)return;const t=e.value.replace(/^\*/,"").toLowerCase();return t==="goal"||t==="loop"?t:void 0}function Fo(e,t){if(!e||e==="jobs"||!t||t.quoted)return;const n=t.value.toLowerCase();return(e==="goal"?Vo:Bo).has(n)?n:void 0}function Go(e){return!e.quoted&&e.value!=="--watch"&&e.value.toLowerCase().startsWith("--watch")}function Yo(e){const{tokens:t,malformed:n}=Wo(e),r=Ho(t[0]),o=Fo(r,t[1]);if(n)return G(e,[H.MALFORMED],r,o);const i=t.filter(f=>f.value==="--watch"&&!f.quoted),s=t.filter(f=>f.value==="--watch"&&f.quoted),c=t.filter(Go);if(!(i.length>0||s.length>0||c.length>0))return G(e,[],r,o);if(i.length>1)return G(e,[H.DUPLICATE],r,o);if(i.length===1&&(s.length>0||c.length>0))return G(e,[H.AMBIGUOUS],r,o);if(s.length>0)return G(e,[H.QUOTED],r,o);if(c.length>0)return G(e,[H.MALFORMED],r,o);const p=i[0];if(!p)return G(e,[],r,o);if(t[t.length-1]!==p)return G(e,[H.NON_FINAL],r,o);if(!r||!o)return G(e,[H.UNRESOLVED],r,o);const g=`${e.slice(0,p.start)}${e.slice(p.end)}`.trim(),C={literal:"--watch",position:"final",start:p.start,end:p.end,quoted:!1,publicSafe:!0};return{args:g,watch:!0,reasonCodes:[H.ACTIVE],metadata:ht(!0,[H.ACTIVE],r,o,C),publicSafe:!0}}function Jo(e){return Rn(e)?$o(e):Yo(e)}function zo(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&$r.has(t)):[]}function be(e){return{disabled:!0,reasonCodes:Y(e.length>0?e:[F.MISSING])}}function mt(e,t,n=[],r){const o=Le(t);if(o)return{source:e,target:Mo(o,n),targetJobId:o.targetId,...r?{initialCursor:r}:{},serverHeldStream:!1}}function qo(e){const t=new Map;for(const n of e){const r=`${n.target.selectorKind}:${n.target.targetId}`,o=t.get(r);if(!o){t.set(r,n);continue}const i=Y([...o.target.relatedJobIds??[],...n.target.relatedJobIds??[]]);t.set(r,{...o,target:i.length>0?{...o.target,relatedJobIds:i}:o.target,initialCursor:o.initialCursor??n.initialCursor})}return Array.from(t.values())}function fe(e,t,n,r){return{source:e,hasEvidence:t,candidates:qo(n.filter(o=>!!o)),...r&&r.length>0?{disabledReasonCodes:Y(r)}:{}}}function Ko(e,t){return e.target.selectorKind===t.target.selectorKind&&e.target.targetId===t.target.targetId}function xe(e,t){const n=Y(e.filter(r=>typeof r=="string").map(r=>Q(r)).filter(r=>!!r));if(t){const r=n.find(o=>ft(o)===t);if(r)return r}return n[0]}function Je(e,t){return Y(e.filter(n=>typeof n=="string").map(n=>Q(n)).filter(n=>!!n)).find(n=>ft(n)===t)}function Xo(e){const t=m(e?.continuity)?e.continuity:void 0,n=m(t?.jobs)?t.jobs:void 0,r=m(n?.watcher)?n.watcher:void 0,o=zo(r?.reasonCodes??n?.reasonCodes);if(!r)return fe("watcher-metadata",o.length>0,[],o);if(r.active===!1||o.length>0)return fe("watcher-metadata",!0,[],o.length>0?o:[F.MALFORMED]);if(r.serverHeldStream!==!1)return fe("watcher-metadata",!0,[],[F.SERVER_HELD_STREAM]);const i=Uo(r);if(!i)return fe("watcher-metadata",!0,[],[F.MISSING]);const s=typeof r.initialCursor=="string"?r.initialCursor:void 0;return fe("watcher-metadata",!0,[{source:"watcher-metadata",target:i,targetJobId:i.targetId,...s?{initialCursor:s}:{},serverHeldStream:!1}])}function wn(e,t){const n=m(e.loopJobPlan)?e.loopJobPlan:void 0,r=m(n?.metadata)?n.metadata:void 0,o=m(e.metadata)?e.metadata:void 0,s=(t==="goal"?xe([e.goalId,e.targetGoalId,e.campaignId,e.jobId,e.targetJobId,o?.goalId,o?.campaignId,o?.jobId],"goal"):xe([e.loopId,e.targetLoopId,e.jobId,e.targetJobId,o?.loopId,o?.jobId,r?.loopId,r?.jobId],"loop"))??xe([e.jobId,e.targetJobId,o?.jobId,r?.jobId]);return mt("goal-loop-continuity-metadata",s,[e.jobId,e.targetJobId,o?.jobId,r?.jobId])}function Zo(e){const t=m(e?.continuity)?e.continuity:void 0,n=m(t?.goal)?t.goal:void 0,r=m(t?.loop)?t.loop:void 0,o=[n?wn(n,"goal"):void 0,r?wn(r,"loop"):void 0],i=!!(n||r);return fe("goal-loop-continuity-metadata",i,o,i&&o.every(s=>!s)?[F.MISSING]:void 0)}function Qo(e){return Array.isArray(e)?e.filter(m):m(e)?Array.isArray(e.operationLogs)?e.operationLogs.filter(m):m(e.operationLog)?[e.operationLog]:Array.isArray(e.operations)?[e]:[]:[]}function Tn(e,t){const n=m(t.metadata)?t.metadata:void 0,r=Je([t.goalId,t.targetGoalId,t.campaignId,n?.goalId,n?.campaignId,t.jobId,n?.jobId],"goal"),o=Je([t.loopId,t.targetLoopId,n?.loopId,t.jobId,n?.jobId],"loop"),i=xe([t.jobId,t.targetJobId,n?.jobId],"job"),s=r??o??i;if(!s)return;const c=e.get(s)??{targetId:s,relatedJobIds:[]};c.relatedJobIds.push(...gt([i,t.jobId,t.targetJobId,n?.jobId])),e.set(s,c)}function ei(e){const t=m(e.metadata)?e.metadata:void 0;return!!(Je([e.goalId,e.targetGoalId,e.campaignId,t?.goalId,t?.campaignId,e.jobId,t?.jobId],"goal")??Je([e.loopId,e.targetLoopId,t?.loopId,e.jobId,t?.jobId],"loop"))}function ti(e){const t=m(e.metadata)?e.metadata:void 0;return!!xe([e.goalId,e.targetGoalId,e.campaignId,e.loopId,e.targetLoopId,e.jobId,e.targetJobId,t?.goalId,t?.campaignId,t?.loopId,t?.jobId])}function bn(e,t){const n=[];for(const s of["metadata","job","event","receipt","processingOutputSummary"]){const c=t[s];m(c)&&n.push(c)}const r=m(t.event)?t.event:void 0;m(r?.metadata)&&n.push(r.metadata),m(r?.processingOutputSummary)&&n.push(r.processingOutputSummary);const o=m(t.receipt)?t.receipt:void 0;m(o?.metadata)&&n.push(o.metadata);const i=n.some(ti);for(const s of n)Tn(e,s);(!i||ei(t))&&Tn(e,t)}function ni(e){const t=Qo(e?.continuityStateUpdate),n=new Map;for(const o of t){bn(n,o);const i=Array.isArray(o.operations)?o.operations.filter(m):[];for(const s of i)bn(n,s)}const r=Array.from(n.values()).map(o=>mt("continuity-state-update-operation-log",o.targetId,o.relatedJobIds));return fe("continuity-state-update-operation-log",t.length>0,r,t.length>0&&r.every(o=>!o)?[F.MISSING]:void 0)}function ri(e){const t=An(e);return fe("explicit-args",t.length>0,t.map(n=>mt("explicit-args",n)))}function oi(e,t){const n=[Xo(e),Zo(e),ni(e),ri(t)];for(let r=0;r<n.length;r+=1){const o=n[r];if(!o.hasEvidence)continue;if(o.disabledReasonCodes&&o.disabledReasonCodes.length>0)return be(o.disabledReasonCodes);if(o.candidates.length!==1)return be([o.candidates.length>1?F.AMBIGUOUS:F.MISSING]);const i=o.candidates[0];for(const s of n.slice(r+1)){if(!s.hasEvidence)continue;if(s.disabledReasonCodes&&s.disabledReasonCodes.length>0)return be(s.disabledReasonCodes);if(s.candidates.length>1)return be([F.AMBIGUOUS]);const c=s.candidates[0];if(c&&!Ko(i,c))return be([F.CONFLICT])}return{target:i.target,targetJobId:i.targetJobId,...i.initialCursor?{initialCursor:i.initialCursor}:{},source:i.source,serverHeldStream:!1}}return be([F.MISSING])}async function vn(e,t,n,r={}){const i=await ct(e,"/api/v1/invoke",t,n,r);if(i.networkFailure||!i.response)return{ok:!1,status:0,error:"Network error after bounded retries"};const{response:s,text:c,parsed:l}=i;try{if(!s.ok)return{ok:!1,status:s.status,error:Object.keys(l).length>0?`${l.error_code??"ERROR"}: ${l.message??c}`:`HTTP ${s.status}: ${c}`,errorBody:Object.keys(l).length>0?l:void 0};const p=l,g=s.headers.get("X-Client-Version-Warning");return g&&!pn&&(pn=!0,process.stderr.write(`
17
17
  [Neocortex] ${g}
18
18
 
19
- `)),{ok:!0,status:s.status,data:p}}catch(p){return{ok:!1,status:0,error:(p instanceof Error?p.message:String(p)).includes("abort")?`Request timeout after ${Ht/1e3}s`:"Network error: invalid response"}}}async function ii(e,t,n,r={}){const o=await ct(e,"/api/v1/invoke/epic-claims/acknowledge",{...n,registryVersion:Ie,registryChecksum:me},t,r);return!!o.response?.ok&&o.parsed.status==="ok"&&o.parsed.claimOutcome===n.status}async function si(e,t,n,r,o,i={}){if(!o)return 0;const s=Ve(e);let c=0;for(const[l,p]of Object.entries(s.operations))!p.claimId||!p.epicId||!t.epics?.[p.epicId]||!await ii(n,r,{claimId:p.claimId,projectId:o,epicId:p.epicId,status:"materialized"},i)||(jr(e,l),c+=1);return c}function ai(e,t){const n=t.state.pendingContinuationAuthorities,r=t.state.continuationSession;if(t.state.continuationPolicy!=="p205-finite-resume-v2"||n?.length!==1||!r)return;const o=n[0],i=o.certificate,s=i?.expectedTransition;if(o.storyIds!=="[CIRCULAR]"||i?.rank!=="[CIRCULAR]"||s?.selectedStoryIds!=="[CIRCULAR]")return;const c=typeof r.epicId=="string"?r.epicId:"",l=e.epics[c],p=Array.isArray(s.storyLifecycle)?s.storyLifecycle:[],g=p.length===1&&typeof p[0]?.storyId=="string"?p[0].storyId:"",f=e.stories[g]?.checkpoint;if(!l||l.branch_mode!=="epic"||typeof l.execution_branch!="string"||typeof l.origin_branch!="string"||l.branch_lease!==void 0&&l.branch_lease!==null||!f||f.qaVerdict!=="passed"||f.reviewVerdict!=="approved"||!Array.isArray(f.receiptRefs))return;const h=(Array.isArray(l.stories)?l.stories.filter(S=>typeof S=="string"):[]).find(S=>{const E=e.stories[S];return!E||["done","completed","merged"].includes(String(E.status))?!1:(Array.isArray(E.depends_on)?E.depends_on.filter(k=>typeof k=="string"):[]).every(k=>["done","completed","merged"].includes(String(e.stories[k]?.status)))});if(h)return{epicId:c,expectedNextStoryId:h,branchMode:"epic",executionBranch:l.execution_branch,originBranch:l.origin_branch,branchLeaseReleased:!0,checkpoint:{schemaVersion:1,storyId:f.storyId,epicId:f.epicId,branch:f.branch,baseSha:f.baseSha,headSha:f.headSha,receiptRefs:[...f.receiptRefs],qaVerdict:"passed",reviewVerdict:"approved"}}}async function ci(e){let t;try{if(t=e.inputEnvelope??je(e.inputSource??"args",e.args),dr(t),t.rawArgs!==e.args)throw new Error("INVOKE_INPUT_ENVELOPE_ARGUMENT_CONFLICT")}catch{return{success:!1,error:"INVOCATION_MALFORMED_INPUT: explicit input integrity could not be verified.",errorCode:"INVOCATION_MALFORMED_INPUT",metadata:{invocationInput:{reason:"input-integrity-conflict",remediation:"Retry with exactly one of --args, --stdin or --args-file.",publicSafe:!0}},exitCode:1}}const n=t.rawArgs,r=Mt(t);let o=n,i=r;const s=Vr(n);if(s.outcome!=="resolved"){const a=lr(s,"client"),u=s.outcome==="malformed_input"?s.reason==="input_limit"||s.reason==="token_limit"||s.reason==="token_size_limit"?"input-limit-exceeded":s.reason==="invalid_control"||s.reason==="invalid_surrogate"?"invalid-control-character":s.reason==="unterminated_quote"||s.reason==="trailing_escape"||s.reason==="unsupported_escape"?"unterminated-quote":void 0:void 0,y=u?{code:"INVOCATION_MALFORMED_INPUT",reason:u,source:t.source,byteLength:t.byteLength,remediation:u==="input-limit-exceeded"?"Reduce the explicit command input or split the requested work into bounded invocations.":u==="invalid-control-character"?"Remove invalid control characters and retry with valid UTF-8 text.":"Close quotes and escapes, or use --stdin/--args-file for multiline content."}:void 0;return{success:!1,error:`INVOCATION_${s.outcome.toUpperCase()}`,errorCode:`INVOCATION_${s.outcome.toUpperCase()}`,metadata:{invocationAdmission:a,...y?{invocationInput:y}:{}},exitCode:1}}const c=nt(e.projectRoot),l=s.selection.commandId,p=Mn.find(a=>a.id===l),g=p?.subcommands.find(a=>a.id===s.selection.operationId),C=g?g.policy.strictReadOnly==="allow":p?.policy.strictReadOnly==="allow",f=l==="diagnose";let d;try{d=sr({invocationId:qe(),intent:e.strictReadOnly||f?{schemaVersion:1,policy:rr,registryVersion:Ie,registryChecksum:me}:void 0,registryVersion:Ie,registryChecksum:me,registryAllowsStrict:C,requestCanonicalBytes:JSON.stringify({command:l})})}catch(a){if(a instanceof Re)return{success:!1,error:a.code,errorCode:a.code,exitCode:1};throw a}{d.beginProjection();for(const a of jt)d.project(a);for(const a of or)d.project(a);d.seal()}const h=d.mode==="strict";if(l==="create-epic")try{const a=Ir(c);if(a&&a!=="finalized")return{success:!1,error:'PROJECT_IDENTITY_MIGRATION_INCOMPLETE: retry `neocortex-client invoke --args "*migrate-project-id"` before create-epic.',errorCode:"PROJECT_IDENTITY_MIGRATION_INCOMPLETE",metadata:{projectIdentityMigration:{phase:a,publicSafe:!0}},exitCode:1}}catch(a){const u=a instanceof Xe?a.code:"PROJECT_IDENTITY_MIGRATION_STATE_CORRUPT";return{success:!1,error:u,errorCode:u,exitCode:1}}const S=e.environment??process.env,E=er({cwd:c,env:S,targetFlag:e.platformTarget}),T=E.targetId,k=Qn({cwd:c,env:S,targetFlag:e.platformTarget,nativeHostVersion:Jr(E,S)},E);l!=="migrate-project-id"&&d.execute({phase:"client-preflight",domain:"client-persistence",category:"first-run-marker",operation:"create"},()=>Ur(),()=>{});const w=uo(d),_=(e.serverUrl??w?.serverUrl??Un).replace(/\/+$/,"");if(l==="migrate-project-id"){const a=await yr(_);if(!a.supported)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_CAPABILITY_UNAVAILABLE: the server did not advertise the versioned migration capability; no local state was changed.",errorCode:"PROJECT_IDENTITY_MIGRATION_CAPABILITY_UNAVAILABLE",metadata:{projectIdentityMigrationCapability:a},exitCode:1};const u=[];let y;try{y=mr(c)}catch(B){const ce=B instanceof Xe?B.code:"PROJECT_IDENTITY_MIGRATION_PREPARE_FAILED";return{success:!1,error:ce,errorCode:ce,exitCode:1}}u.push(we({phase:"prepare",outcome:y.changed&&y.document.phase==="prepared"?"prepared":"retry",floor:y.document.legacyEpicFloor,licenseId:"local-client",projectId:y.document.projectId}));const P=dn(c);if(P.config.project_id!==y.document.projectId)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",errorCode:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",metadata:{invocationDiagnostics:u},exitCode:1};const he=await ln(_,w?.licenseKey,d);if(he.status!=="authenticated"){const B=he.status==="refresh-required";return{success:!1,error:B?"Authentication refresh required. Run: neocortex activate YOUR-LICENSE-KEY":"Not authenticated. Visit https://neocortex.sh/portal/login to get your license key, then run: neocortex activate YOUR-LICENSE-KEY",errorCode:B?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",metadata:{invocationDiagnostics:u},exitCode:B?1:2}}let _t;try{_t=vt(e.args.trim(),P)}catch(B){const ce=B instanceof Ot?B.code:"PROJECT_IDENTITY_MIGRATION_PROJECTION_FAILED";return{success:!1,error:ce,errorCode:ce,metadata:{invocationDiagnostics:u},exitCode:1}}let ze={args:n,projectRoot:c.replace(Pe(),"~"),stateSnapshot:_t,platformTarget:T,...k?{nativeHostAttestation:k}:{},projectId:y.document.projectId,projectIdentityMigration:y.request,inputEvidence:r,idempotencyKey:y.document.operationId,registryVersion:Ie,registryChecksum:me};try{ze=In(ze).body}catch(B){if(B instanceof it||B instanceof st)return{success:!1,error:B.message,errorCode:B.code,metadata:{invokePayload:B.telemetry,invocationDiagnostics:u},exitCode:1};throw B}const ie=await Pt("invoke-query",()=>vn(_,ze,he.token,{refreshToken:()=>he.client.forceRefresh()}));if(!ie.ok||!ie.data)return u.push(we({phase:"seed",outcome:"rejected",floor:y.document.legacyEpicFloor,licenseId:"local-client",projectId:y.document.projectId})),{success:!1,error:Z(ie.error??"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",ye),errorCode:typeof ie.errorBody?.error_code=="string"?ie.errorBody.error_code:"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",metadata:{invocationDiagnostics:u},exitCode:ie.status===401?2:1};const X=ie.data.metadata?.projectIdentityMigration;try{ur(X),u.push(we({phase:"seed",outcome:X.status,floor:X.acceptedLegacyFloor,licenseId:"local-client",projectId:X.projectId})),gr(c,X),u.push(we({phase:"remote-acknowledged",outcome:X.status,floor:X.acceptedLegacyFloor,licenseId:"local-client",projectId:X.projectId})),hr(c,X),u.push(we({phase:"finalize",outcome:"finalized",floor:X.acceptedLegacyFloor,licenseId:"local-client",projectId:X.projectId}))}catch(B){u.push(we({phase:"reconcile",outcome:"rejected",floor:y.document.legacyEpicFloor,licenseId:"local-client",projectId:y.document.projectId}));const ce=B instanceof Xe?B.code:B instanceof Error?B.message:"PROJECT_IDENTITY_MIGRATION_RECEIPT_INVALID";return{success:!1,error:ce,errorCode:ce,metadata:{invocationDiagnostics:u},exitCode:1}}return d.complete(),{success:!0,instructions:ie.data.instructions,metadata:{...ie.data.metadata,invocationDiagnostics:u},exitCode:0}}try{const{normalizeYoloopTargetArgs:a}=await import("../yoloop/target-normalization.js"),u=a(e.args,{projectRoot:c});if(!u.ok)return process.stderr.write(`${u.message} reason=${u.reasonCode}
19
+ `)),{ok:!0,status:s.status,data:p}}catch(p){return{ok:!1,status:0,error:(p instanceof Error?p.message:String(p)).includes("abort")?`Request timeout after ${Wt/1e3}s`:"Network error: invalid response"}}}async function ii(e,t,n,r={}){const o=await ct(e,"/api/v1/invoke/epic-claims/acknowledge",{...n,registryVersion:Ie,registryChecksum:me},t,r);return!!o.response?.ok&&o.parsed.status==="ok"&&o.parsed.claimOutcome===n.status}async function si(e,t,n,r,o,i={}){if(!o)return 0;const s=Ve(e);let c=0;for(const[l,p]of Object.entries(s.operations))!p.claimId||!p.epicId||!t.epics?.[p.epicId]||!await ii(n,r,{claimId:p.claimId,projectId:o,epicId:p.epicId,status:"materialized"},i)||(jr(e,l),c+=1);return c}function ai(e,t){const n=t.state.pendingContinuationAuthorities,r=t.state.continuationSession;if(t.state.continuationPolicy!=="p205-finite-resume-v2"||n?.length!==1||!r)return;const o=n[0],i=o.certificate,s=i?.expectedTransition;if(o.storyIds!=="[CIRCULAR]"||i?.rank!=="[CIRCULAR]"||s?.selectedStoryIds!=="[CIRCULAR]")return;const c=typeof r.epicId=="string"?r.epicId:"",l=e.epics[c],p=Array.isArray(s.storyLifecycle)?s.storyLifecycle:[],g=p.length===1&&typeof p[0]?.storyId=="string"?p[0].storyId:"",f=e.stories[g]?.checkpoint;if(!l||l.branch_mode!=="epic"||typeof l.execution_branch!="string"||typeof l.origin_branch!="string"||l.branch_lease!==void 0&&l.branch_lease!==null||!f||f.qaVerdict!=="passed"||f.reviewVerdict!=="approved"||!Array.isArray(f.receiptRefs))return;const h=(Array.isArray(l.stories)?l.stories.filter(S=>typeof S=="string"):[]).find(S=>{const E=e.stories[S];return!E||["done","completed","merged"].includes(String(E.status))?!1:(Array.isArray(E.depends_on)?E.depends_on.filter(v=>typeof v=="string"):[]).every(v=>["done","completed","merged"].includes(String(e.stories[v]?.status)))});if(h)return{epicId:c,expectedNextStoryId:h,branchMode:"epic",executionBranch:l.execution_branch,originBranch:l.origin_branch,branchLeaseReleased:!0,checkpoint:{schemaVersion:1,storyId:f.storyId,epicId:f.epicId,branch:f.branch,baseSha:f.baseSha,headSha:f.headSha,receiptRefs:[...f.receiptRefs],qaVerdict:"passed",reviewVerdict:"approved"}}}async function ci(e){let t;try{if(t=e.inputEnvelope??je(e.inputSource??"args",e.args),dr(t),t.rawArgs!==e.args)throw new Error("INVOKE_INPUT_ENVELOPE_ARGUMENT_CONFLICT")}catch{return{success:!1,error:"INVOCATION_MALFORMED_INPUT: explicit input integrity could not be verified.",errorCode:"INVOCATION_MALFORMED_INPUT",metadata:{invocationInput:{reason:"input-integrity-conflict",remediation:"Retry with exactly one of --args, --stdin or --args-file.",publicSafe:!0}},exitCode:1}}const n=t.rawArgs,r=Mt(t);let o=n,i=r;const s=Vr(n);if(s.outcome!=="resolved"){const a=lr(s,"client"),u=s.outcome==="malformed_input"?s.reason==="input_limit"||s.reason==="token_limit"||s.reason==="token_size_limit"?"input-limit-exceeded":s.reason==="invalid_control"||s.reason==="invalid_surrogate"?"invalid-control-character":s.reason==="unterminated_quote"||s.reason==="trailing_escape"||s.reason==="unsupported_escape"?"unterminated-quote":void 0:void 0,y=u?{code:"INVOCATION_MALFORMED_INPUT",reason:u,source:t.source,byteLength:t.byteLength,remediation:u==="input-limit-exceeded"?"Reduce the explicit command input or split the requested work into bounded invocations.":u==="invalid-control-character"?"Remove invalid control characters and retry with valid UTF-8 text.":"Close quotes and escapes, or use --stdin/--args-file for multiline content."}:void 0;return{success:!1,error:`INVOCATION_${s.outcome.toUpperCase()}`,errorCode:`INVOCATION_${s.outcome.toUpperCase()}`,metadata:{invocationAdmission:a,...y?{invocationInput:y}:{}},exitCode:1}}const c=nt(e.projectRoot),l=s.selection.commandId,p=Mn.find(a=>a.id===l),g=p?.subcommands.find(a=>a.id===s.selection.operationId),C=g?g.policy.strictReadOnly==="allow":p?.policy.strictReadOnly==="allow",f=l==="diagnose";let d;try{d=sr({invocationId:qe(),intent:e.strictReadOnly||f?{schemaVersion:1,policy:rr,registryVersion:Ie,registryChecksum:me}:void 0,registryVersion:Ie,registryChecksum:me,registryAllowsStrict:C,requestCanonicalBytes:JSON.stringify({command:l})})}catch(a){if(a instanceof Re)return{success:!1,error:a.code,errorCode:a.code,exitCode:1};throw a}{d.beginProjection();for(const a of jt)d.project(a);for(const a of or)d.project(a);d.seal()}const h=d.mode==="strict";if(l==="create-epic")try{const a=Ir(c);if(a&&a!=="finalized")return{success:!1,error:'PROJECT_IDENTITY_MIGRATION_INCOMPLETE: retry `neocortex-client invoke --args "*migrate-project-id"` before create-epic.',errorCode:"PROJECT_IDENTITY_MIGRATION_INCOMPLETE",metadata:{projectIdentityMigration:{phase:a,publicSafe:!0}},exitCode:1}}catch(a){const u=a instanceof Xe?a.code:"PROJECT_IDENTITY_MIGRATION_STATE_CORRUPT";return{success:!1,error:u,errorCode:u,exitCode:1}}const S=e.environment??process.env,E=er({cwd:c,env:S,targetFlag:e.platformTarget}),T=E.targetId,v=Qn({cwd:c,env:S,targetFlag:e.platformTarget,nativeHostVersion:Jr(E,S)},E);l!=="migrate-project-id"&&d.execute({phase:"client-preflight",domain:"client-persistence",category:"first-run-marker",operation:"create"},()=>Ur(),()=>{});const w=uo(d),_=(e.serverUrl??w?.serverUrl??Un).replace(/\/+$/,"");if(l==="migrate-project-id"){const a=await yr(_);if(!a.supported)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_CAPABILITY_UNAVAILABLE: the server did not advertise the versioned migration capability; no local state was changed.",errorCode:"PROJECT_IDENTITY_MIGRATION_CAPABILITY_UNAVAILABLE",metadata:{projectIdentityMigrationCapability:a},exitCode:1};const u=[];let y;try{y=mr(c)}catch(B){const ce=B instanceof Xe?B.code:"PROJECT_IDENTITY_MIGRATION_PREPARE_FAILED";return{success:!1,error:ce,errorCode:ce,exitCode:1}}u.push(we({phase:"prepare",outcome:y.changed&&y.document.phase==="prepared"?"prepared":"retry",floor:y.document.legacyEpicFloor,licenseId:"local-client",projectId:y.document.projectId}));const P=dn(c);if(P.config.project_id!==y.document.projectId)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",errorCode:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",metadata:{invocationDiagnostics:u},exitCode:1};const he=await ln(_,w?.licenseKey,d);if(he.status!=="authenticated"){const B=he.status==="refresh-required";return{success:!1,error:B?"Authentication refresh required. Run: neocortex activate YOUR-LICENSE-KEY":"Not authenticated. Visit https://neocortex.sh/portal/login to get your license key, then run: neocortex activate YOUR-LICENSE-KEY",errorCode:B?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",metadata:{invocationDiagnostics:u},exitCode:B?1:2}}let _t;try{_t=vt(e.args.trim(),P)}catch(B){const ce=B instanceof Ot?B.code:"PROJECT_IDENTITY_MIGRATION_PROJECTION_FAILED";return{success:!1,error:ce,errorCode:ce,metadata:{invocationDiagnostics:u},exitCode:1}}let ze={args:n,projectRoot:c.replace(Pe(),"~"),stateSnapshot:_t,platformTarget:T,...v?{nativeHostAttestation:v}:{},projectId:y.document.projectId,projectIdentityMigration:y.request,inputEvidence:r,idempotencyKey:y.document.operationId,registryVersion:Ie,registryChecksum:me};try{ze=In(ze).body}catch(B){if(B instanceof it||B instanceof st)return{success:!1,error:B.message,errorCode:B.code,metadata:{invokePayload:B.telemetry,invocationDiagnostics:u},exitCode:1};throw B}const ie=await Pt("invoke-query",()=>vn(_,ze,he.token,{refreshToken:()=>he.client.forceRefresh()}));if(!ie.ok||!ie.data)return u.push(we({phase:"seed",outcome:"rejected",floor:y.document.legacyEpicFloor,licenseId:"local-client",projectId:y.document.projectId})),{success:!1,error:Z(ie.error??"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",ye),errorCode:typeof ie.errorBody?.error_code=="string"?ie.errorBody.error_code:"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",metadata:{invocationDiagnostics:u},exitCode:ie.status===401?2:1};const X=ie.data.metadata?.projectIdentityMigration;try{ur(X),u.push(we({phase:"seed",outcome:X.status,floor:X.acceptedLegacyFloor,licenseId:"local-client",projectId:X.projectId})),gr(c,X),u.push(we({phase:"remote-acknowledged",outcome:X.status,floor:X.acceptedLegacyFloor,licenseId:"local-client",projectId:X.projectId})),hr(c,X),u.push(we({phase:"finalize",outcome:"finalized",floor:X.acceptedLegacyFloor,licenseId:"local-client",projectId:X.projectId}))}catch(B){u.push(we({phase:"reconcile",outcome:"rejected",floor:y.document.legacyEpicFloor,licenseId:"local-client",projectId:y.document.projectId}));const ce=B instanceof Xe?B.code:B instanceof Error?B.message:"PROJECT_IDENTITY_MIGRATION_RECEIPT_INVALID";return{success:!1,error:ce,errorCode:ce,metadata:{invocationDiagnostics:u},exitCode:1}}return d.complete(),{success:!0,instructions:ie.data.instructions,metadata:{...ie.data.metadata,invocationDiagnostics:u},exitCode:0}}try{const{normalizeYoloopTargetArgs:a}=await import("../yoloop/target-normalization.js"),u=a(e.args,{projectRoot:c});if(!u.ok)return process.stderr.write(`${u.message} reason=${u.reasonCode}
20
20
  `),{success:!1,error:u.message,exitCode:1};u.changed&&(e={...e,args:u.args},process.stderr.write(`[Neocortex] yoloop target normalized: ${u.reasonCodes.join(",")}
21
21
  `))}catch{const a="INVALID_YOLOOP_TARGET: yoloop target normalization was unavailable; no request was sent.";return process.stderr.write(`${a}
22
22
  `),{success:!1,error:a,exitCode:1}}const R=an(l);if(R)try{cn(c,{allowMissingRuntime:!0}).runtimeMissing&&(await d.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},async()=>Cr(c),async()=>{}),cn(c))}catch(a){const u=a instanceof pe?a.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${u}. No request was sent; repair the canonical project state and retry.
@@ -34,12 +34,12 @@ ${t}
34
34
  `)}try{if(Fr(e.args)){const{collectProjectEvidence:a}=await import("../evidence/collector.js"),u=s.selection.uiUxReview?.architectureDir,y=a({projectRoot:c,...u?{candidatePaths:[u],includeFallbackInventory:!0}:{}});(y.evidence.length>0||y.exclusions.length>0)&&(I.projectEvidence=y)}}catch(a){const u=a instanceof Error?a.message:String(a);process.stderr.write(`[Neocortex] project evidence collection failed: ${u}. Proceeding without local project evidence.
35
35
  `)}try{const a=await d.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"checkpoint-consume",operation:"consume"},async()=>{const{readAndConsumeCheckpoint:u}=await import("../checkpoint/index.js");return u(c)},async()=>{});a&&(I.implementCheckpoint=a)}catch(a){const u=a instanceof Error?a.message:String(a);process.stderr.write(`[Neocortex] checkpoint hook failed: ${u}. Proceeding without checkpoint.
36
36
  `)}const M=w?.licenseKey?new Ke({cacheDir:Qe,passphrase:w.licenseKey,strictReadOnly:h}):null,L=o.trim();if(!L&&M){const a=await d.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>so(M),async()=>null);if(a)return d.complete(),{success:!0,instructions:a.instructions,metadata:a.metadata,exitCode:0}}const D=await ln(_,w?.licenseKey,d);if(D.status!=="authenticated"){const a=D.status==="refresh-required",u=!a&&w&&!w.licenseKey?" This may be caused by a machine fingerprint change (e.g., hardware or hostname change).":"";try{const y=bt(),P=wt(a?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",y);P&&process.stderr.write(Tt(P,y))}catch{}return{success:!1,error:a?"Authentication refresh required. Run: neocortex activate YOUR-LICENSE-KEY":`Not authenticated.${u} Visit https://neocortex.sh/portal/login to get your license key, then run: neocortex activate YOUR-LICENSE-KEY`,errorCode:a?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",exitCode:a?1:2}}const V=I.config.project_id;try{await d.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>si(c,I,_,D.token,V,{refreshToken:()=>D.client.forceRefresh()}),async()=>0)}catch{}const x=di(L);if(x&&!f)try{const a=await D.tierClient.preFlightCheck(x);if(!a.allowed)return process.stderr.write(`[neocortex] ${a.message}
37
- `),{success:!1,error:a.message??"Trigger not available on your plan",exitCode:1}}catch{}const v=await Ro({args:L,projectRoot:c,platformTarget:T,environment:e.environment??process.env,bootstrapper:e.runnerBootstrapper,effectAuthority:d});if(v.attachToRequest&&(I.runnerBootstrap=v.metadata),v.warning&&process.stderr.write(`[Neocortex] ${v.warning}
38
- `),!v.shouldContinue)return v.error&&process.stderr.write(`[Neocortex] ${v.error}
39
- `),{success:!1,error:v.error??"Runner auto-bootstrap required but failed.",errorCode:v.errorCode,exitCode:v.exitCode??1};let ee;try{const a=Hn(L,I);if(a&&!a.ok){const u=`${a.code}: structural projection failed closed; select a valid target or repair the dependency DAG.`;return process.stderr.write(`${u}
37
+ `),{success:!1,error:a.message??"Trigger not available on your plan",exitCode:1}}catch{}const O=await Ro({args:L,projectRoot:c,platformTarget:T,environment:e.environment??process.env,bootstrapper:e.runnerBootstrapper,effectAuthority:d});if(O.attachToRequest&&(I.runnerBootstrap=O.metadata),O.warning&&process.stderr.write(`[Neocortex] ${O.warning}
38
+ `),!O.shouldContinue)return O.error&&process.stderr.write(`[Neocortex] ${O.error}
39
+ `),{success:!1,error:O.error??"Runner auto-bootstrap required but failed.",errorCode:O.errorCode,exitCode:O.exitCode??1};let ee;try{const a=Wn(L,I);if(a&&!a.ok){const u=`${a.code}: structural projection failed closed; select a valid target or repair the dependency DAG.`;return process.stderr.write(`${u}
40
40
  `),{success:!1,error:u,errorCode:a.code,metadata:{stateProjection:a,publicSafe:!0},exitCode:1}}ee=a?.snapshot??vt(L,I)}catch(a){if(a instanceof Ot){const u=`${a.code}: structural projection failed closed; select a valid target or repair the dependency DAG.`;return process.stderr.write(`${u}
41
41
  `),{success:!1,error:u,errorCode:a.code,metadata:{structuralProjection:{...a.publicDetails,publicSafe:!0}},exitCode:1}}throw a}if(!h)try{const{openNativeAgentPrivateStore:a,resolveNativeAgentPrivateRuntimePaths:u}=await import("../continuity/native-agent-store.js"),y=u(c);if(Ce(y.databasePath)){const P=await a(c);try{const he=P.store.listRecentNativeAgentDispatches(20);he.length>0&&(ee.nativeAgentDispatches=he)}finally{P.store.close()}}}catch{}const Oe=St(L),_e=V;if(Oe==="create-epic"&&!_e){const a='EPIC_PROJECT_ID_REQUIRED: run `neocortex-client invoke --args "*migrate-project-id"` and retry create-epic. No repository checkout or database credentials are required.';return process.stderr.write(`${a}
42
- `),{success:!1,error:a,errorCode:"EPIC_PROJECT_ID_REQUIRED",exitCode:1}}let Ee;try{Ee=d.execute({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Oe==="create-epic"?Pr(c,L):void 0,()=>{})}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const De=Ee?.key,ge=h?{schemaVersion:1,invocationId:d.invocationId,intent:d.intent,clientProjection:ir(jt.map(a=>({...a,count:1})))}:void 0;let K={args:o,projectRoot:c.replace(Pe(),"~"),stateSnapshot:ee,platformTarget:T,...k?{nativeHostAttestation:k}:{},projectId:_e,inputEvidence:i,idempotencyKey:De,registryVersion:Ie,registryChecksum:me,...ge?{strictReadOnly:ge}:{}};const kn=Te(K);if(!h&&e.inputSource&&e.inputSource!=="args"&&kn>=et)try{K={argsRef:(await nr(d,"secondary-mutation",()=>Io(_,o,D.token,()=>D.client.forceRefresh()),async()=>{throw new Re("readonly-physical-boundary-unsafe","boundary")})).argsRef,projectRoot:c.replace(Pe(),"~"),stateSnapshot:ee,platformTarget:T,...k?{nativeHostAttestation:k}:{},projectId:_e,inputEvidence:i,idempotencyKey:De,registryVersion:Ie,registryChecksum:me,...ge?{strictReadOnly:ge}:{}}}catch(a){return a instanceof Re?{success:!1,error:a.code,errorCode:a.code,exitCode:1}:{success:!1,error:`INVOKE_MATERIALIZATION_FAILED: ${a instanceof Error?a.message:String(a)}`,errorCode:"INVOKE_MATERIALIZATION_FAILED",exitCode:1}}try{const a=In(K);K=a.body,a.degraded?_n(K,a.telemetry):So(K)}catch(a){if(a instanceof it||a instanceof st)return _n(K,a.telemetry),process.stderr.write(`[Neocortex] ${a.message}
42
+ `),{success:!1,error:a,errorCode:"EPIC_PROJECT_ID_REQUIRED",exitCode:1}}let Ee;try{Ee=d.execute({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Oe==="create-epic"?Pr(c,L):void 0,()=>{})}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const De=Ee?.key,ge=h?{schemaVersion:1,invocationId:d.invocationId,intent:d.intent,clientProjection:ir(jt.map(a=>({...a,count:1})))}:void 0;let K={args:o,projectRoot:c.replace(Pe(),"~"),stateSnapshot:ee,platformTarget:T,...v?{nativeHostAttestation:v}:{},projectId:_e,inputEvidence:i,idempotencyKey:De,registryVersion:Ie,registryChecksum:me,...ge?{strictReadOnly:ge}:{}};const kn=Te(K);if(!h&&e.inputSource&&e.inputSource!=="args"&&kn>=et)try{K={argsRef:(await nr(d,"secondary-mutation",()=>Io(_,o,D.token,()=>D.client.forceRefresh()),async()=>{throw new Re("readonly-physical-boundary-unsafe","boundary")})).argsRef,projectRoot:c.replace(Pe(),"~"),stateSnapshot:ee,platformTarget:T,...v?{nativeHostAttestation:v}:{},projectId:_e,inputEvidence:i,idempotencyKey:De,registryVersion:Ie,registryChecksum:me,...ge?{strictReadOnly:ge}:{}}}catch(a){return a instanceof Re?{success:!1,error:a.code,errorCode:a.code,exitCode:1}:{success:!1,error:`INVOKE_MATERIALIZATION_FAILED: ${a instanceof Error?a.message:String(a)}`,errorCode:"INVOKE_MATERIALIZATION_FAILED",exitCode:1}}try{const a=In(K);K=a.body,a.degraded?_n(K,a.telemetry):So(K)}catch(a){if(a instanceof it||a instanceof st)return _n(K,a.telemetry),process.stderr.write(`[Neocortex] ${a.message}
43
43
  `),{success:!1,error:a.message,errorCode:a.code,metadata:{invokePayload:a.telemetry},exitCode:1};throw a}let b=await Pt("invoke-query",()=>vn(_,K,D.token,{refreshToken:()=>D.client.forceRefresh()})),It;if(h&&b.ok)try{if(f){const u=b.data?.metadata;if(u&&["stateUpdate","stateMutated","yoloopStateUpdate","continuityStateUpdate","checkpoint","schedulerStateUpdate","quotaCacheUpdate","projectIdentityMigration","epicClaim","gitLifecycleGraphAuthority"].some(P=>u[P]!==void 0))throw new Re("readonly-response-conflict")}const a=b.data?.metadata.strictReadOnly;ar(d,a),f&&pr(b.data?.metadata.strictDiagnose,n,b.data?.instructions??""),It=a.security}catch(a){const u=a instanceof Re?a.code:"readonly-receipt-mismatch";return{success:!1,error:u,errorCode:u,exitCode:1}}if(!b.ok&&b.status===426){const a=b.errorBody,u=a?.upgrade_command??"npm install -g @ornexus/neocortex@latest",y=a?.min_version??"unknown";return process.stderr.write(`
44
44
  `),process.stderr.write(`==================================================
45
45
  `),process.stderr.write(` UPGRADE REQUIRED
@@ -149,7 +149,7 @@ Safety:
149
149
  Jobs console is Plane B/local-only: no hosted server call for raw output, no server-held stream, no raw persistence, and stdin requires explicit local confirmation.
150
150
  Jobs, goal and loop watch use serverHeldStream=false and foreground local SQLite polling of public processing summaries only.
151
151
  Unresolved targets disable polling with public reason codes; there is no all-jobs fallback.
152
- `.trim();function li(e){return e.includes("--help")||e.includes("-h")||e.includes("help")}function q(e,t,n,r){return new Be("INVOCATION_MALFORMED_INPUT",t,e,n,r)}function ve(e){return q("missing-input-value",`${e} requires a value. ${On}`)}function pi(e){try{if(!Dn(e).isFile())throw q("missing-input-value","--args-file must point to a readable UTF-8 text file.","args-file");return Ae(e)}catch(t){throw t instanceof Be?t:q("missing-input-value","--args-file could not be read as UTF-8 text. Check the path and permissions.","args-file")}}function fi(){try{if(process.stdin.isTTY)throw q("missing-input-value","--stdin requires piped UTF-8 text, for example: neocortex-client invoke --stdin < synthetic.story.md","stdin");return Ae(0)}catch(e){throw e instanceof Be?e:q("missing-input-value","--stdin could not be read as UTF-8 text. Pipe command text into stdin and retry.","stdin")}}function gi(e,t={}){let n,r=!1,o,i,s="plain",c=!1,l,p,g=!1;for(let T=0;T<e.length;T++)switch(e[T]){case"--args":{const w=e[++T];if(w===void 0)throw ve("--args");if(n!==void 0)throw q("multiple-input-sources","Provide --args only once. Use one explicit invoke input source.","args");n=w;break}case"--stdin":if(r)throw q("multiple-input-sources","Provide --stdin only once. Use one explicit invoke input source.","stdin");r=!0;break;case"--args-file":{const w=e[++T];if(w===void 0)throw ve("--args-file");if(o!==void 0)throw q("multiple-input-sources","Provide --args-file only once. Use one explicit invoke input source.","args-file");o=w;break}case"--project-root":{const w=e[++T];if(w===void 0)throw ve("--project-root");i=w;break}case"--format":{const w=e[++T];if(w===void 0)throw ve("--format");if(w!=="json"&&w!=="plain")throw q("unexpected-cli-token","--format accepts only json or plain.");s=w;break}case"--watch":c=!0;break;case"--server-url":{const w=e[++T];if(w===void 0)throw ve("--server-url");l=w;break}case"--platform-target":{const w=e[++T];if(w===void 0)throw ve("--platform-target");p=w;break}case"--strict-read-only":g=!0;break;default:throw q("unexpected-cli-token","Unexpected top-level CLI token. Quote the complete --args payload or use --stdin/--args-file for multiline content.")}const C=[n!==void 0?"args":void 0,r?"stdin":void 0,o!==void 0?"args-file":void 0].filter(T=>T!==void 0);if(C.length===0)throw q("missing-input-value",On);if(C.length>1)throw q("multiple-input-sources",`Choose only one invoke input source; received ${C.join(", ")}.`);const f=C[0],d=f==="args"?n:f==="stdin"?(t.readStdin??fi)():(t.readArgsFile??pi)(o);let h;try{h=je(f,d)}catch(T){throw T instanceof fr?q("invalid-utf8",T.message,f):T}const S=f==="args"?Jo(h.rawArgs):G(h.rawArgs),E=S.args===h.rawArgs?h:je(f,S.args);return{args:S.args,inputSource:f,inputEnvelope:E,projectRoot:i,format:s,watch:c||S.watch,commandLevelWatch:S.metadata,serverUrl:l,platformTarget:p,strictReadOnly:g}}function Nn(e,t){return t?.active?{...e??{},commandLevelWatch:t,serverHeldStream:!1}:e}function hi(e,t,n=process.stdout,r=process.stderr){if(t.format==="json"){const s=ot(e.instructions,e.metadata),c=Nn(s.metadata,t.commandLevelWatch);if(t.watch){n.write(JSON.stringify({type:"invoke_result",instructions:s.instructions,metadata:c,publicSafe:!0})+`
152
+ `.trim();function li(e){return e.includes("--help")||e.includes("-h")||e.includes("help")}function q(e,t,n,r){return new Be("INVOCATION_MALFORMED_INPUT",t,e,n,r)}function ve(e){return q("missing-input-value",`${e} requires a value. ${On}`)}function pi(e){try{if(!Dn(e).isFile())throw q("missing-input-value","--args-file must point to a readable UTF-8 text file.","args-file");return Ae(e)}catch(t){throw t instanceof Be?t:q("missing-input-value","--args-file could not be read as UTF-8 text. Check the path and permissions.","args-file")}}function fi(){try{if(process.stdin.isTTY)throw q("missing-input-value","--stdin requires piped UTF-8 text, for example: neocortex-client invoke --stdin < synthetic.story.md","stdin");return Ae(0)}catch(e){throw e instanceof Be?e:q("missing-input-value","--stdin could not be read as UTF-8 text. Pipe command text into stdin and retry.","stdin")}}function gi(e,t={}){let n,r=!1,o,i,s="plain",c=!1,l,p,g=!1;for(let T=0;T<e.length;T++){const v=e[T];switch(v){case"--args":{const w=e[++T];if(w===void 0)throw ve("--args");if(n!==void 0)throw q("multiple-input-sources","Provide --args only once. Use one explicit invoke input source.","args");n=w;break}case"--stdin":if(r)throw q("multiple-input-sources","Provide --stdin only once. Use one explicit invoke input source.","stdin");r=!0;break;case"--args-file":{const w=e[++T];if(w===void 0)throw ve("--args-file");if(o!==void 0)throw q("multiple-input-sources","Provide --args-file only once. Use one explicit invoke input source.","args-file");o=w;break}case"--project-root":{const w=e[++T];if(w===void 0)throw ve("--project-root");i=w;break}case"--format":{const w=e[++T];if(w===void 0)throw ve("--format");if(w!=="json"&&w!=="plain")throw q("unexpected-cli-token","--format accepts only json or plain.");s=w;break}case"--watch":c=!0;break;case"--server-url":{const w=e[++T];if(w===void 0)throw ve("--server-url");l=w;break}case"--platform-target":{const w=e[++T];if(w===void 0)throw ve("--platform-target");p=w;break}case"--strict-read-only":g=!0;break;default:if(n!==void 0&&v&&(!v.startsWith("-")||v==="-")){n+=` ${v}`;break}throw q("unexpected-cli-token","Unexpected top-level CLI token. Quote the complete --args payload or use --stdin/--args-file for multiline content.")}}const C=[n!==void 0?"args":void 0,r?"stdin":void 0,o!==void 0?"args-file":void 0].filter(T=>T!==void 0);if(C.length===0)throw q("missing-input-value",On);if(C.length>1)throw q("multiple-input-sources",`Choose only one invoke input source; received ${C.join(", ")}.`);const f=C[0],d=f==="args"?n:f==="stdin"?(t.readStdin??fi)():(t.readArgsFile??pi)(o);let h;try{h=je(f,d)}catch(T){throw T instanceof fr?q("invalid-utf8",T.message,f):T}const S=f==="args"?Jo(h.rawArgs):G(h.rawArgs),E=S.args===h.rawArgs?h:je(f,S.args);return{args:S.args,inputSource:f,inputEnvelope:E,projectRoot:i,format:s,watch:c||S.watch,commandLevelWatch:S.metadata,serverUrl:l,platformTarget:p,strictReadOnly:g}}function Nn(e,t){return t?.active?{...e??{},commandLevelWatch:t,serverHeldStream:!1}:e}function hi(e,t,n=process.stdout,r=process.stderr){if(t.format==="json"){const s=ot(e.instructions,e.metadata),c=Nn(s.metadata,t.commandLevelWatch);if(t.watch){n.write(JSON.stringify({type:"invoke_result",instructions:s.instructions,metadata:c,publicSafe:!0})+`
153
153
  `);return}n.write(JSON.stringify({instructions:s.instructions,metadata:c})+`
154
154
  `);return}const o=ot(e.instructions,e.metadata),i=Nn(o.metadata,t.commandLevelWatch);n.write(o.instructions+`
155
155
  `),i&&r.write(JSON.stringify(i)+`
File without changes
@@ -7,7 +7,7 @@
7
7
  * Returns undefined (no-op) for non-yoloop invocations to avoid I/O.
8
8
  * - `persistYoloopFromResponse(metadata, projectRoot)` — post-response;
9
9
  * if the server returned `yoloopStateUpdate`, apply operations locally.
10
- * Authoritative rollover failures are returned to the invoke boundary;
10
+ * Authoritative rollover/successor-transition failures are returned to the invoke boundary;
11
11
  * auxiliary legacy updates retain bounded fail-soft compatibility.
12
12
  *
13
13
  * Trigger detection is regex-based over the first token of `args`, aligned
@@ -87,8 +87,9 @@ export declare function readYoloopForRequest(args: string, projectRoot: string,
87
87
  /**
88
88
  * Post-response hook: apply server-provided operations to local state.
89
89
  * Safe to call for any response — no-op if no yoloopStateUpdate present.
90
- * A `rollover_session` update is authoritative: failure is returned to the
91
- * caller so instructions cannot be released before durable state exists.
90
+ * A `rollover_session` or `commit_successor_transition` update is
91
+ * authoritative: failure is returned to the caller so instructions cannot be
92
+ * released before durable state exists.
92
93
  * Non-rollover legacy operations retain fail-soft compatibility.
93
94
  */
94
95
  export declare function persistYoloopFromResponse(metadata: Record<string, unknown> | undefined, projectRoot: string, nowIso?: string): Promise<YoloopPersistenceResult>;