@ornexus/neocortex 4.60.40 → 4.60.42

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