@ornexus/neocortex 4.60.23 → 4.60.24

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