@ornexus/neocortex 4.60.45 → 4.60.47

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