@ornexus/neocortex 4.60.22 → 4.60.23

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 (53) hide show
  1. package/dist/sbom.cdx.json +24 -24
  2. package/install.ps1 +1 -1
  3. package/install.sh +1 -1
  4. package/package.json +6 -3
  5. package/packages/client/dist/cli.js +0 -0
  6. package/packages/client/dist/commands/invoke.d.ts +19 -5
  7. package/packages/client/dist/commands/invoke.js +55 -53
  8. package/packages/client/dist/continuity/invoke-hooks.js +1 -1
  9. package/packages/client/dist/fs/atomic-state-replace.d.ts +16 -0
  10. package/packages/client/dist/fs/atomic-state-replace.js +1 -0
  11. package/packages/client/dist/generated/command-registry.generated.d.ts +53 -19
  12. package/packages/client/dist/generated/command-registry.generated.js +1 -1
  13. package/packages/client/dist/graph-retrieval/pre-command-hook.d.ts +11 -0
  14. package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -1
  15. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +1 -1
  16. package/packages/client/dist/invocation/invoke-input.d.ts +9 -0
  17. package/packages/client/dist/invocation/invoke-input.js +1 -0
  18. package/packages/client/dist/migrations/project-identity-capability.d.ts +13 -0
  19. package/packages/client/dist/migrations/project-identity-capability.js +1 -0
  20. package/packages/client/dist/migrations/project-identity.d.ts +41 -0
  21. package/packages/client/dist/migrations/project-identity.js +7 -0
  22. package/packages/client/dist/runner-cli.js +0 -0
  23. package/packages/client/dist/state/invocation-shape.d.ts +9 -0
  24. package/packages/client/dist/state/invocation-shape.js +1 -0
  25. package/packages/client/dist/state/project-state-snapshot.d.ts +9 -3
  26. package/packages/client/dist/state/project-state-snapshot.js +1 -1
  27. package/packages/client/dist/state/structural-dag-projection.d.ts +24 -0
  28. package/packages/client/dist/state/structural-dag-projection.js +1 -0
  29. package/packages/shared/dist/generated/command-registry.generated.js +66 -19
  30. package/packages/shared/dist/generated/invocation-schema.generated.js +16 -4
  31. package/packages/shared/dist/invocation/index.d.ts +6 -2
  32. package/packages/shared/dist/invocation/index.js +5 -0
  33. package/packages/shared/dist/invocation/input-envelope.d.ts +37 -0
  34. package/packages/shared/dist/invocation/input-envelope.js +98 -0
  35. package/packages/shared/dist/invocation/project-identity-migration.d.ts +28 -0
  36. package/packages/shared/dist/invocation/project-identity-migration.js +83 -0
  37. package/packages/shared/dist/invocation/public-diagnostics.d.ts +87 -0
  38. package/packages/shared/dist/invocation/public-diagnostics.js +181 -0
  39. package/packages/shared/dist/invocation/state-projection.d.ts +21 -0
  40. package/packages/shared/dist/invocation/state-projection.js +1 -0
  41. package/packages/shared/dist/invocation/strict-effect-receipt.d.ts +12 -0
  42. package/packages/shared/dist/invocation/strict-effect-receipt.js +43 -0
  43. package/targets-stubs/antigravity/gemini.md +1 -1
  44. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  45. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  46. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  47. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  48. package/targets-stubs/claude-code/neocortex.md +2 -2
  49. package/targets-stubs/codex/AGENTS.md +1 -1
  50. package/targets-stubs/cursor/agent.md +2 -2
  51. package/targets-stubs/gemini-cli/agent.md +2 -2
  52. package/targets-stubs/opencode/neocortex-root.md +1 -1
  53. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,60 +1,62 @@
1
- import{createHash as Ae,randomUUID as Re}from"node:crypto";import{existsSync as X,readFileSync as ae,renameSync as Wt,unlinkSync as Bt,writeFileSync as Je,mkdirSync as Ke,statSync as Ft}from"node:fs";import{join as M}from"node:path";import{homedir as we}from"node:os";import{LicenseClient as Ht}from"../license/license-client.js";import{EncryptedCache as Te}from"../cache/encrypted-cache.js";import{NoOpCache as Ye}from"../types/index.js";import{resolveClientPreFlightTrigger as ze,TierAwareClient as Gt}from"../tier/tier-aware-client.js";import{COMMAND_REGISTRY_CHECKSUM as Q,COMMAND_REGISTRY_VERSION as Z,GENERATED_CLIENT_COMMANDS as Jt}from"../generated/command-registry.generated.js";import{loadSecureConfig as qe}from"../config/secure-config.js";import{DEFAULT_SERVER_URL as Kt}from"../constants.js";import{detectFirstRunLocale as Yt,renderFirstRunMessage as zt}from"../i18n/first-run.js";import{humanizeError as Xe,formatHumanizedError as Qe,detectErrorLocale as Ze}from"../errors/error-messages.js";import{degradeStateSnapshotForPayloadLimit as qt,projectStateSnapshotForInvoke as Xt}from"../state/project-state-snapshot.js";import{maybeRepairStateJsonBeforeInvoke as Qt,StateRepairHardStopError as Zt}from"../state/state-json-repair.js";import{bootstrapArchitectureMemory as er}from"../memory/project-memory-writer.js";import{RUNNER_BOOTSTRAP_POLICY_REASON_CODES as tr,classifyRunnerBootstrapPolicyFromArgs as rr}from"../continuity/runner-bootstrap-policy.js";import{RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES as nr,ensureRunnerSchedulerBootstrap as or}from"../runner/scheduler.js";import{CONTINUITY_INVOKE_WATCH_DEFAULT_LIMIT as et,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_IDLE_POLLS as tt,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_POLLS as rt,CONTINUITY_INVOKE_WATCH_DEFAULT_POLL_INTERVAL_MS as nt,openContinuityClientStateStore as sr}from"../continuity/continuity-client-state-store.js";import{isLocalJobsConsoleArgs as ar,runLocalJobsConsoleCommand as ir}from"../runner/local-console.js";import{detectPlatform as cr}from"../adapters/platform-detector.js";import{signNxInvokeRequest as dr}from"../../../shared/dist/nx-invoke-signature.js";import{CLIENT_VERSION as ee}from"../version.js";import{createCapabilityCache as ot,executeInvokeQueryTransport as ur,executeSecondaryNetworkMutation as lr}from"../effects/invoke-effect-gateways.js";import{STRICT_READ_ONLY_POLICY as pr,STRICT_READ_ONLY_CLIENT_PROJECTION as st,STRICT_READ_ONLY_SERVER_PROJECTION as fr,StrictReadOnlyError as ie,canonicalizeInvokeEffects as mr,createInvokeEffectContext as gr,verifyStrictReadOnlyReceipt as hr}from"../../../shared/dist/strict-readonly.js";import{admitInvocation as Ir,createInvocationAdmissionReceipt as _r}from"../../../shared/dist/invocation/index.js";const fe=M(we(),".neocortex"),be=M(fe,"cache"),at=M(be,"menu-cache.json"),it=1440*60*1e3,ct=3e4,dt=256*1024,ut=dt,lt=.8,J="[REDACTED]",Er=1e5,me=2e3,yr=200,Cr=200,Sr=12,Ar=/(?:promptBody|workflow|workflowGraph|stepBody|privateUrl|rawLog|secret|credential|licenseKey|apiKey|internalRouting|serverOnly|proprietary|protected)/i,Rr=/(?:PRIVATE|PROTECTED|SERVER_ONLY)[-_\s]*(?:PROMPT|PROMPT_BODY|WORKFLOW|WORKFLOW_GRAPH|STEP_BODY|STEP|ROUTING)\s*[:=][^\n\r]*/gi,wr=/(?: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,ve=Math.floor(dt*lt),pt=M(fe,".first-run-shown"),Tr="<!-- NEOCORTEX-MEMORY-START -->",br="pending-epic-claims.json",ft=64;function mt(e){return M(e,".neocortex",br)}function ge(e){const t=mt(e);if(!X(t))return{schemaVersion:1,operations:{}};const r=JSON.parse(ae(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>ft)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");for(const[o,s]of Object.entries(n.operations)){if(!/^[a-f0-9]{64}$/.test(o)||!s||typeof s!="object"||Array.isArray(s))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const i=s;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 Oe(e,t){const r=mt(e);Ke(M(e,".neocortex"),{recursive:!0,mode:448});const n=`${r}.${process.pid}.${Re()}.tmp`;Je(n,`${JSON.stringify(t)}
2
- `,{encoding:"utf8",mode:384,flag:"wx"}),Wt(n,r)}function vr(e){return Ae("sha256").update(`nx-epic-logical-operation-v1\0${JSON.stringify({command:"create-epic",args:e})}`,"utf8").digest("hex")}function Or(e,t){const r=vr(t),n=ge(e),o=n.operations[r];if(o)return{key:o.idempotencyKey,fingerprint:r};if(Object.keys(n.operations).length>=ft)throw new Error("EPIC_CLAIM_CAPACITY_EXCEEDED");const s=Re(),i={...n.operations,[r]:{idempotencyKey:s,createdAt:new Date().toISOString()}};return Oe(e,{schemaVersion:1,operations:i}),{key:s,fingerprint:r}}function Nr(e,t){const r=ge(e);if(!r.operations[t])return;const n={...r.operations};delete n[t],Oe(e,{schemaVersion:1,operations:n})}function Lr(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=ge(e),s=o.operations[t];if(!s)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");Oe(e,{schemaVersion:1,operations:{...o.operations,[t]:{...s,claimId:r,epicId:n}}})}function kr(e){return/^\s*\*?init(?:\s|$)/i.test(e)}function xr(e){const t=M(e,"NEOCORTEX.md"),r=X(t)?ae(t,"utf8"):void 0,n=r===void 0?["missing_canonical_memory"]:[r.includes(Tr)?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(l=>!!l),s=["AGENTS.md","CLAUDE.md","GEMINI.md",".opencode/AGENTS.md",".cursor/rules/neocortex.mdc",".github/copilot-instructions.md"].filter(l=>X(M(e,l))),i=n.includes("possible_secret_shape_detected")?"low":n.length===0?"high":s.length>0?"medium":"low",c=er(e);return{canonical:{path:"NEOCORTEX.md",exists:r!==void 0,incompleteReasons:n,confidence:i},permittedSources:{packageBuildFiles:c.repositoryMap?.find(l=>l.startsWith("Package/build files:"))?.split(",").length??0,architectureReadmeDocs:c.architectureReferences?.length??0,runtimeConfigTemplates:c.environmentPractices?.[0]?.startsWith("Runtime/config templates:")?c.environmentPractices[0].split(",").length:0,platformWrappers:s.length},wrapperFiles:s,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 Pr(){try{if(X(pt))return;const e=Yt(),t=zt(e);process.stderr.write(t);try{Ke(fe,{recursive:!0}),Je(pt,new Date().toISOString(),"utf-8")}catch{}}catch{}}function Ne(e,t=process.cwd()){return e&&e.trim().length>0?e:t}function jr(e){return Ir(e,{registryVersion:Z,registryChecksum:Q})}const Dr=new Set(["completed","aborted","cancelled"]),Mr=new Set(["watch-target-missing","watch-target-malformed","watch-target-ambiguous","watch-target-multiple"]),O=Object.freeze({COMPLETED:"invoke-watch-completed",CANCELLED:"invoke-watch-cancelled",IDLE_TIMEOUT:"invoke-watch-idle-timeout",MAX_POLLS:"invoke-watch-max-polls",STORE_UNAVAILABLE:"invoke-watch-store-unavailable",TARGET_UNRESOLVED:"invoke-watch-target-unresolved"}),k=Object.freeze({MISSING:"watch-target-missing",MALFORMED:"watch-target-malformed",AMBIGUOUS:"watch-target-ambiguous",CONFLICT:"watch-target-conflicting-evidence",SERVER_HELD_STREAM:"watch-target-server-held-stream-unsupported"}),y=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"}),gt=240,Ur=/(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 $r(e){return e.replace(/[\w.+-]+@[\w-]+\.[\w.-]+/g,J).replace(/(?:sk|pk|whsec|nxk)[-_](?:test|live|ant|proj|pro|free|enterprise)?[-_]?[A-Za-z0-9_-]{16,}/g,J).replace(/NX-[FPE]-[a-f0-9]{24}-[a-f0-9]{4}/g,J).replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,J).replace(Rr,J).replace(wr,J)}function te(e,t){const r=$r(e);return r.length<=t?r:`${r.slice(0,t)}\u2026[TRUNCATED:${r.length-t}]`}function Le(e,t=0,r=new WeakSet){if(t>Sr)return"[MAX_DEPTH]";if(e==null)return e;if(typeof e=="string")return te(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(r.has(e))return"[CIRCULAR]";r.add(e);try{if(Array.isArray(e))return e.slice(0,yr).map(o=>Le(o,t+1,r));const n={};for(const[o,s]of Object.entries(e).slice(0,Cr)){if(Ar.test(o)){n[o]=J;continue}const i=Le(s,t+1,r);i!==void 0&&(n[o]=i)}return n}finally{r.delete(e)}}}function ke(e,t){return{instructions:te(e??"",Er),metadata:t?Le(t):void 0}}class U extends Error{code;constructor(t,r){super(r),this.name="InvokeCliInputError",this.code=t}}function Vr(e){return/^\s*\*?(?:arch-plan|ui-ux-review)(?:\s|$)/i.test(e)&&Wr(e,"--project-evidence")}function Wr(e,t){let r=null,n=-1,o=!1,s=!1;for(let i=0;i<=e.length;i+=1){const c=e[i];if(i===e.length||!r&&/\s/.test(c??"")){if(n>=0&&!o&&e.slice(n,i)===t)return!0;n=-1,o=!1,s=!1;continue}if(n<0&&(n=i),s){s=!1;continue}if(c==="\\"){s=!0;continue}(c==='"'||c==="'")&&(o=!0,r=r===c?null:r??c)}return!1}class ht extends Error{code="PAYLOAD_TOO_LARGE";telemetry;constructor(t){super(`PAYLOAD_TOO_LARGE: invoke request is ${t.payloadBytes} bytes after deterministic degradation; limit is ${t.limitBytes}. Reduce command input or local state context and retry.`),this.name="InvokePayloadTooLargeError",this.telemetry=t}}let xe=!1;function Br(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[s,i]of Object.entries(r.epics)){const c=i;if(c&&c.stories!==void 0&&!Array.isArray(c.stories)){t.push({code:"EPIC_STORIES_NOT_ARRAY",message:`epic "${s}" 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 Fr(e){if(!(xe||e.length===0)){xe=!0;try{const t=e.map(r=>` - ${r.message}`).join(`
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(`
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 Po(){xe=!1}function It(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Hr(e){return e==="active"||e==="archived"||e==="rolled-back"||e==="synthetic"||e==="orphan"?e:void 0}function ce(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 re(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function w(e){if(typeof e!="string")return;const t=e.trim();if(t)return t.replace(/[^a-z0-9_.:-]+/gi,"_").slice(0,120)}function ne(e){if(typeof e!="string")return;const t=e.trim(),r=w(e);return r===t?r:void 0}function de(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 Pe(e){return typeof e=="string"&&/^[0-9a-f]{7,64}$/i.test(e)?e:void 0}function je(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 _t(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 he(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 s=w(o);s&&(r[n]=s)}}return Object.keys(r).length>0?r:void 0}function Ie(e){return e==="epic"||e==="story"?e:void 0}function Et(e){if(!_(e)||e.schemaVersion!==1)return;const t=ne(e.ownerStoryId),r=ne(e.sessionId),n=ne(e.idempotencyKey),o=je(e.acquiredAt),s=je(e.expiresAt);if(!(!t||!r||!n||!o||!s||Date.parse(s)<=Date.parse(o)))return{schemaVersion:1,ownerStoryId:t,sessionId:r,idempotencyKey:n,acquiredAt:o,expiresAt:s}}function yt(e){if(!_(e)||e.schemaVersion!==1)return;const t=ne(e.storyId),r=ne(e.epicId),n=de(e.branch),o=Pe(e.baseSha),s=Pe(e.headSha),i=ne(e.idempotencyKey),c=je(e.recordedAt),l=ce(e.commits).map(Pe).filter(f=>!!f).slice(0,256),p=ce(e.receiptRefs).map(_t).filter(f=>!!f).slice(0,256);if(!(!t||!r||!t.startsWith(`${r}.`)||!n||!o||!s||o===s||!i||!c||l.length===0||p.length===0||!Array.isArray(e.commits)||l.length!==e.commits.length||e.commits.length>256||!Array.isArray(e.receiptRefs)||p.length!==e.receiptRefs.length||e.receiptRefs.length>256||e.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:s,idempotencyKey:i,qaVerdict:e.qaVerdict,reviewVerdict:e.reviewVerdict,recordedAt:c,commits:l,receiptRefs:p}}function _e(e){if(!_(e)||e.schemaVersion!==1)return;const t=he(e,["schemaVersion","kind","storyId","epicId","baseSha","headSha","originalBaseSha","originalHeadSha","gitPullRequest","preservesLaterCommits","historyRewrite","recordedAt"])??{},r=ce(e.receiptRefs).map(_t).filter(o=>!!o).slice(0,256),n=ce(e.revertCommits).map(w).filter(o=>!!o).slice(0,256);return{...t,...r.length?{receiptRefs:r}:{},...n.length?{revertCommits:n}:{}}}function Gr(e){if(!_(e))return;const t={...w(e.active_epic_id??e.activeEpicId)?{active_epic_id:w(e.active_epic_id??e.activeEpicId)}:{},...w(e.active_story_id??e.activeStoryId)?{active_story_id:w(e.active_story_id??e.activeStoryId)}:{},...w(e.active_step_id??e.activeStepId)?{active_step_id:w(e.active_step_id??e.activeStepId)}:{},...w(e.session_id??e.sessionId)?{session_id:w(e.session_id??e.sessionId)}:{},...w(e.started_at??e.startedAt)?{started_at:w(e.started_at??e.startedAt)}:{}};return Object.keys(t).length>0?t:void 0}function Jr(e){const t=he(e.completionEvidence??e.completion_evidence,["prNumber","pr_number","prState","pr_state","pullRequestState","merged","mergedAt","issueNumber","issue_number","issueState","issue_state","closedAt"]),r=he(e.issueCloseAudit??e.issue_close_audit,["schema_version","event","storyId","epicId","issueNumber","closedAt","publicSafe","rawLogStorage"]),n=he(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}:{},...w(e.physicalMergeStatus)?{physicalMergeStatus:w(e.physicalMergeStatus)}:{},...w(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)?{pr_state:w(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)}:{},...w(e.issue_state??e.issueState??e.workflow_issue_state)?{issue_state:w(e.issue_state??e.issueState??e.workflow_issue_state)}:{},...re(e.issue_number??e.issueNumber)?{issue_number:re(e.issue_number??e.issueNumber)}:{},...t?{completionEvidence:t}:{},...r?{issueCloseAudit:r}:{},...n?{scopedCiEvidence:n}:{}}}function Kr(e){const t=M(e,".neocortex","state.json");if(!X(t))return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}};let r;try{const m=ae(t,"utf-8");r=JSON.parse(m)}catch{return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}try{const m=Br(r);m.length>0&&Fr(m)}catch{}const n=r.config??r.project??{},o=r.stories??{},s={};for(const[m,d]of Object.entries(o))s[m]={id:d.id??m,title:d.title,epic_id:d.epic_id,status:d.status??"backlog",steps_completed:d.steps_completed??[],last_step:d.last_step??null,branch_name:d.branch_name??null,pr_number:d.pr_number,...Ie(d.branch_mode)?{branch_mode:Ie(d.branch_mode)}:{},...yt(d.checkpoint)?{checkpoint:yt(d.checkpoint)}:{},..._e(d.review_request)?{review_request:_e(d.review_request)}:{},..._e(d.rollback_receipt)?{rollback_receipt:_e(d.rollback_receipt)}:{},...re(d.workflow_issue)?{workflow_issue:re(d.workflow_issue)}:{},...Jr(d),depends_on:It(d.depends_on),files_to_modify:ce(d.files_to_modify),risk:typeof d.risk=="string"?d.risk:void 0,blast_radius:typeof d.blast_radius=="number"?d.blast_radius:void 0};const i=r.epics??{},c={};for(const[m,d]of Object.entries(i)){const S=Hr(d.lifecycle_classification);c[m]={id:d.id??m,title:d.title,status:d.status,stories:d.stories,total_stories:d.total_stories,completed_stories:d.completed_stories,depends_on:It(d.depends_on),...Ie(d.branch_mode)?{branch_mode:Ie(d.branch_mode)}:{},...de(d.execution_branch)?{execution_branch:de(d.execution_branch)}:{},...de(d.origin_branch)?{origin_branch:de(d.origin_branch)}:{},...Et(d.branch_lease)?{branch_lease:Et(d.branch_lease)}:{},...re(d.pr_number)?{pr_number:re(d.pr_number)}:{},...w(d.physicalMergeStatus)?{physicalMergeStatus:w(d.physicalMergeStatus)}:{},...S?{lifecycle_classification:S}:{}}}const l=Gr(r.current_session??r.currentSession),p=r.epic_id_ledger,f=Array.isArray(p?.reserved_ids)?[...new Set(p.reserved_ids.filter(m=>typeof m=="string"&&/^P\d+$/.test(m)))].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:s,epics:c,...f.length>0?{epic_id_ledger:{schema_version:1,reserved_ids:f}}:{},...l?{current_session:l}:{}}}function jo(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 Ct="neocortex:menu:cache";async function Yr(e){try{const t=await e.get(Ct);if(!t)return null;const r=JSON.parse(t);return r.version!==ee||Date.now()-r.cachedAt>it?null:r}catch{return null}}async function zr(e,t,r){try{const n={instructions:t,metadata:r,cachedAt:Date.now(),version:ee};await e.set(Ct,JSON.stringify(n),it),qr()}catch{}}function qr(){try{X(at)&&Bt(at)}catch{}}function Xr(e){return e.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>qe(),()=>qe({strictReadOnly:!0}))}async function Qr(e,t,r){try{let n;const o=r.mode==="strict";if(o&&t)n=new Te({cacheDir:be,passphrase:t,strictReadOnly:!0});else if(o)n=new Ye;else if(t){const f=M(fe,"cache");n=new Te({cacheDir:f,passphrase:t})}else process.stderr.write(`[neocortex] Warning: No license key in config. Run "neocortex activate" to re-authenticate.
8
- `),n=new Ye;const s=ot(r,n,"auth-cache"),i=ot(r,n,"tier-cache"),c=new Ht({serverUrl:e,licenseKey:t??"",cacheProvider:s,strictReadOnly:o}),l=await c.getToken();if(!l)return null;const p=new Gt({cacheProvider:i,licenseClient:c});return{token:l,client:c,tierClient:p}}catch{return null}}let St=!1;const At=3,Ee=50;function Zr(e){return new Promise(t=>setTimeout(t,e))}function en(e,t,r){return e.status>=500&&e.status<=599?!0:r&&e.status===409&&t.error_code==="SIGNATURE_REPLAYED"}async function De(e,t,r,n,o={}){const s=Math.max(1,Math.min(o.maxAttempts??At,At)),i=o.sleep??Zr;let c=n,l=!1,p=!1,f=0;for(let m=1;m<=s;m+=1){const d=Math.max(Math.floor(Date.now()/1e3),f+1);f=d;const S=tn(t,r,c,{nowSeconds:d}),g=new AbortController,h=setTimeout(()=>g.abort(),ct);try{const A=await fetch(`${e}${t}`,{method:"POST",headers:S.headers,body:S.body,signal:g.signal}),L=await A.text().catch(()=>""),T=(()=>{try{return L?JSON.parse(L):{}}catch{return{}}})();if(A.status===401&&!l&&o.refreshToken&&(T.fallback_action==="refresh_token"||T.fallback_action==="re_authenticate")){l=!0;const B=await o.refreshToken();if(B&&m<s){c=B,o.onTokenChanged?.(B),await i(Ee*m);continue}}if(A.status===401&&T.error_code==="SIGNATURE_EXPIRED"&&!p&&m<s){p=!0,await i(Ee*m);continue}if(m<s&&en(A,T,o.allowReplayRetry===!0)){await i(Ee*m);continue}return{response:A,text:L,parsed:T,networkFailure:!1}}catch{if(m<s){await i(Ee*m);continue}return{text:"",parsed:{},networkFailure:!0}}finally{clearTimeout(h)}}return{text:"",parsed:{},networkFailure:!0}}function tn(e,t,r,n={}){const o=Buffer.from(JSON.stringify(t),"utf8"),s=dr({method:"POST",target:e,body:o,bearerToken:r,clientVersion:ee,nowSeconds:n.nowSeconds,nonceBytes:n.nonceBytes});return{body:s.body,headers:{...s.headers,Authorization:`Bearer ${r}`}}}function Rt(e){return Ae("sha256").update(e).digest("hex")}function rn(){const e=Number(process.env.NEOCORTEX_INVOKE_CHUNK_BYTES??"49152");return Number.isFinite(e)&&e>=1024&&e<=98304?Math.floor(e):49152}function nn(e,t,r){return`args-${Ae("sha256").update("invoke-materialization:v1").update(e).update(String(t)).update(JSON.stringify(r)).digest("hex")}`}async function wt(e,t,r,n,o={}){const s=await De(e,t,r,n,{...o,allowReplayRetry:!0});if(s.networkFailure||!s.response)throw new Error("NETWORK_ERROR: materialization request failed after bounded retries");const{response:i,parsed:c}=s;if(!i.ok){const l=typeof c.error_code=="string"?c.error_code:`HTTP_${i.status}`,p=typeof c.message=="string"?c.message:"materialization upload failed";throw new Error(`${l}: ${p}`)}return c}async function on(e,t,r,n){const o=Buffer.from(t,"utf8"),s=rn(),i=[];for(let g=0,h=0;g<o.byteLength;g+=s,h++){const A=o.subarray(g,Math.min(g+s,o.byteLength));i.push({index:h,sha256:Rt(A),byteLength:A.byteLength})}const c=Rt(o),l=nn(c,o.byteLength,i),p=Number(process.env.NEOCORTEX_INVOKE_CHUNK_TTL_SECONDS??"900");let f=r;const m={refreshToken:n,onTokenChanged(g){f=g}};for(const g of i){const h=g.index*s,A=o.subarray(h,h+g.byteLength);await wt(e,"/api/v1/invoke/materialization/chunks",{manifestId:l,index:g.index,sha256:g.sha256,byteLength:g.byteLength,contentBase64:A.toString("base64"),ttlSeconds:p,idempotencyKey:`${l}:${g.index}:${g.sha256}`},f,m)}const S=(await wt(e,"/api/v1/invoke/materialization/manifests",{manifestId:l,sha256:c,byteLength:o.byteLength,chunkCount:i.length,chunks:i,ttlSeconds:p,retry:{attempt:1,budget:3,idempotencyKey:l}},f,m)).argsRef;if(!S?.manifestId)throw new Error("MATERIALIZATION_RESPONSE_INVALID: missing argsRef");return{argsRef:S,chunks:i}}function oe(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function sn(...e){const t=new Set,r=[];for(const n of e)for(const o of n??[]){const s=w(o);if(!(!s||t.has(s))&&(t.add(s),r.push(s),r.length>=16))return r}return r}function an(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 Me(e,t=oe(e),r=[],n={}){const o=e.stateSnapshot.scope,s=Object.keys(e.stateSnapshot.stories).length,i=Object.keys(e.stateSnapshot.epics).length,c=o?.kind??"full";return{schemaVersion:1,payloadBytes:t,limitBytes:n.limitBytes??ut,warningThresholdBytes:n.warningThresholdBytes??ve,scope:{kind:c,...o?.projectionMode?{projectionMode:o.projectionMode}:{},commandId:o?.commandId??null,stateProjectionPolicy:o?.stateProjectionPolicy??null},includedStories:o?.includedStoryCount??s,omittedStories:o?.omittedStoryCount??0,includedEpics:o?.includedEpicCount??i,omittedEpics:o?.omittedEpicCount??0,graphRetrieval:an(e.stateSnapshot),reasonCodes:sn(r,o?.reasonCodes),publicSafe:!0}}function cn(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 dn(e){return _(e)?{stableId:w(e.stableId)??"unknown",..._(e.source)?{source:e.source}:{},reasonCode:"budget_exceeded"}:{stableId:"unknown",reasonCode:"budget_exceeded"}}function Tt(e){const t=Array.isArray(e)?e.filter(r=>typeof r=="string"):[];return t.includes("budget_exceeded")?t:[...t,"budget_exceeded"]}function un(e){const t=e.graphRetrieval;if(!_(t)||!Array.isArray(t.items))return e;const r=cn(t);let n=[...t.items],o=Array.isArray(t.skipped)?[...t.skipped]:[],s=t;for(;Buffer.byteLength(JSON.stringify(s),"utf8")>r&&n.length>0;){const i=n.pop();o=[...o,dn(i)].slice(-32),s={...t,items:n,skipped:o,warnings:Tt(t.warnings)}}return Buffer.byteLength(JSON.stringify(s),"utf8")>r&&(s={...t,query:typeof t.query=="string"?t.query.slice(0,240):t.query,items:[],skipped:[],warnings:Tt(t.warnings)}),s===t?e:{...e,graphRetrieval:s}}function ln(e,t={}){const r=t.limitBytes??ut,n=t.warningThresholdBytes??Math.floor(r*lt),o=oe(e);if(o<=r)return{body:e,degraded:!1,telemetry:Me(e,o,["payload-within-limit"],{limitBytes:r,warningThresholdBytes:n})};let s={...e,stateSnapshot:qt(e.stateSnapshot)},i=["payload-size-guardrail","state-degraded"],c=oe(s);c>r&&(s={...s,stateSnapshot:un(s.stateSnapshot)},i=[...i,"graph-retrieval-budget-enforced"],c=oe(s));const l=Me(s,c,i,{limitBytes:r,warningThresholdBytes:n});if(c>r)throw new ht(l);return{body:s,degraded:!0,telemetry:l}}function pn(e){return Mt(e)??e.trim().split(/\s+/,1)[0]?.slice(0,80)??"(empty)"}function bt(e){return e.args!==void 0?pn(e.args):`argsRef:${e.argsRef.manifestId.slice(0,80)}`}function fn(e){const t=oe(e);if(t<ve)return t;const r=Me(e,t,["payload-warning-threshold"]);return process.stderr.write(`[Neocortex] invoke payload near server limit: trigger=${bt(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 vt(e,t){process.stderr.write(`[Neocortex] invoke payload guardrail: trigger=${bt(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 mn(e){const t=rr(e.args,{platformTarget:e.platformTarget,environment:e.environment??process.env});if(t.action==="skipped")return{shouldContinue:!0,attachToRequest:gn(t),metadata:Ot(t)};const r=e.bootstrapper??or;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:[nr.UNEXPECTED_ERROR],publicSummary:"runner scheduler bootstrap stopped unexpectedly.",publicSafe:!0}}const o=Ot(t,n);if(n.ok)return{shouldContinue:!0,attachToRequest:!0,metadata:o};const s=o.reasonCodes.slice(0,5).join(",");return t.failurePolicy==="fail-open"?{shouldContinue:!0,attachToRequest:!0,metadata:{...o,failOpenWarning:!0},warning:`Runner auto-bootstrap warning (${s}); continuing fail-open for operator command.`}:{shouldContinue:!1,attachToRequest:!1,metadata:o,errorCode:"RUNNER_BOOTSTRAP_REQUIRED_FAILED",error:`Runner auto-bootstrap required but failed (${s}). Run neocortex-runner doctor or retry after resolving scheduler setup.`,exitCode:1}}function gn(e){return!e.reasonCodes.includes(tr.SKIPPED_NON_CONTINUITY_COMMAND)}function Ot(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:P([...e.reasonCodes,...t?.reasonCodes??[]]),publicSummary:t?.publicSummary??e.publicSummary,publicSafe:!0}}function P(e){return Array.from(new Set(e.map(t=>t.slice(0,120))))}function ye(e,t,r){const n=Math.floor(e??t);return Number.isFinite(n)?Math.max(1,Math.min(r,n)):t}function Ce(e,t){const r=process.env[e];if(!r)return t;const n=Number(r);return Number.isFinite(n)?n:t}function C(e,t=gt){const r=typeof e=="string"&&e.trim().length>0?e.trim():"unknown",n=te(r,t),o=Ur.test(n)?J:n;return o.length<=t?o:`${o.slice(0,t)}\u2026[TRUNCATED:${o.length-t}]`}function Ue(e,t=gt){if(!(typeof e!="string"||e.trim().length===0))return C(e,t)}function $e(e,t,r,n){const o=Ue(e?.targetId??t,120),s=e?.selectorKind??(o?We(o):void 0),i=(e?.relatedJobIds??[]).map(c=>Ue(c,120)).filter(c=>!!c);return{schemaVersion:1,contractVersion:"continuity-v1",targetResolutionState:r,...s?{targetKind:s}:{},...o?{targetId:o}:{},...t?{targetJobId:C(t,120)}:{},...e?.jobId?{jobId:C(e.jobId,120)}:{},...e?.goalId?{goalId:C(e.goalId,120)}:{},...e?.loopId?{loopId:C(e.loopId,120)}:{},...i.length>0?{relatedJobIds:i}:{},relatedJobCount:i.length,reasonCodes:P(n.length>0?n:[y.OK]),publicSafe:!0}}function F(e,t,r,n,o=[]){const s=(e?.redactions?.length??0)>0,i=e?s?"unsafe":r&&n===0?"empty":"available":"unavailable",c=Ue(t[t.length-1]?.eventId,120),l=o.length>0?o:i==="unavailable"?[y.WATCH_SNAPSHOT_UNAVAILABLE]:i==="empty"?[y.WATCH_NO_SUMMARIES_YET]:[y.OK];return{schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:i,...e?.generatedAt?{generatedAt:C(e.generatedAt,80)}:{},renderedSummaryCount:n,...c?{latestEventId:c}:{},reasonCodes:P(l),publicSafe:!0}}function $(e,t,r,n,o=[],s){const i=n[n.length-1],c=r??i?.cursor,l=!!(c&&c!==t&&n.length>0),p=s??(l?"advanced":t||c?"unchanged":"not_started"),f=o.length>0?o:p==="advanced"?[y.WATCH_CURSOR_ADVANCED]:p==="unavailable"?[y.WATCH_EVIDENCE_UNAVAILABLE]:[y.WATCH_CURSOR_UNCHANGED];return{schemaVersion:1,contractVersion:"continuity-v1",cursorState:p,...e?{initialCursor:C(e,200)}:{},...t?{currentCursor:C(t,200)}:{},...c?{nextCursor:C(c,200)}:{},cursorAdvanced:l,...i?.eventId?{eventId:C(i.eventId,120)}:{},reasonCodes:P(f),publicSafe:!0}}function V(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:P([...e.reasonCodes??[],...t?.reasonCodes??[],...e.snapshotEvidence?.reasonCodes??[],...e.cursorEvidence?.reasonCodes??[]]),generatedAt:C(e.generatedAt??new Date().toISOString(),80),publicSafe:!0}}function hn(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",s=e.cursorEvidence?.currentCursor??"[none]",i=e.cursorEvidence?.nextCursor??"[none]",c=e.snapshotEvidence?.snapshotStatus??"not_requested",l=e.snapshotEvidence?.generatedAt??e.generatedAt;return[`[watch-status] ${e.targetResolutionState==="unresolved"||e.stopReason==="target_unresolved"?"unresolved-target":r===0&&(e.watchStatus==="waiting"||e.watchStatus==="active")?"no-new-summary":e.watchStatus==="stopped"?"stopped":"lifecycle"}`,`status=${e.watchStatus}`,`active=${e.active}`,`target=${t}`,`resolution=${e.targetResolutionState??"unavailable"}`,`relatedJobs=${n}`,`summaries=${r}`,`snapshot=${c}`,`generatedAt=${l}`,`cursor=${o}`,`current=${C(s,200)}`,`next=${C(i,200)}`,`advanced=${e.cursorEvidence?.cursorAdvanced??!1}`,`stop=${e.stopReason??"not_stopped"}`,`reasons=${e.reasonCodes.join(",")}`].join(" ")}function W(e,t,r){if(t==="json"){r.write(JSON.stringify(e)+`
11
- `);return}r.write(hn(e)+`
12
- `)}function In(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 H(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:In(n,t,r),publicSafe:!0}}function _n(e){const t=e.reasonCode?` reason=${C(e.reasonCode,80)}`:"",r=e.goalId?` goal=${C(e.goalId,100)}`:"",n=e.loopId?` loop=${C(e.loopId,100)}`:"";return`[watch] ${C(e.createdAt,80)} event=${C(e.eventId,120)} job=${C(e.jobId,100)}${r}${n} execution=${C(e.executionId,120)}${t} -- ${C(e.publicSummary)}`}function En(e){return{type:"processing_summary",source:"local_continuity_sqlite",eventId:C(e.eventId,120),jobId:C(e.jobId,100),...e.goalId?{goalId:C(e.goalId,100)}:{},...e.loopId?{loopId:C(e.loopId,100)}:{},executionId:C(e.executionId,120),...e.reasonCode?{reasonCode:C(e.reasonCode,80)}:{},createdAt:C(e.createdAt,80),publicSummary:C(e.publicSummary),publicSafe:!0}}function yn(e,t,r){if(t==="json"){r.write(JSON.stringify(En(e))+`
13
- `);return}r.write(_n(e)+`
14
- `)}function Ve(e){return Dr.has(e.status)}function Cn(e,t,r){if(t){const o=e.find(s=>s.jobId===t);return!!(o&&Ve(o))}return r<=0?!1:e.filter(o=>!Ve(o)).length===0}function Sn(e,t,r,n){return r<n?!1:t?!e.some(o=>o.jobId===t&&!Ve(o)):e.length===0}function An(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 Rn(e){return e.includes(k.MALFORMED)?"malformed":e.includes(k.AMBIGUOUS)?"ambiguous":e.includes("watch-target-multiple")?"multiple":e.includes("watch-evidence-unsafe")?"unsafe":e.includes(k.MISSING)||e.includes(O.TARGET_UNRESOLVED)?"unresolved":"unavailable"}function Nt(e,t){const r=t?ue(t):void 0,n=P([...e,O.TARGET_UNRESOLVED,y.WATCH_TARGET_UNRESOLVED]),o=$e(r,r?.targetId,Rn(n),n),s=F({generatedAt:new Date().toISOString()},[],!1,0,[y.WATCH_TARGET_UNRESOLVED]),i=$(void 0,void 0,void 0,[],[y.WATCH_TARGET_UNRESOLVED],"unavailable");return V({watchStatus:"blocked",active:!1,targetEvidence:o,snapshotEvidence:s,cursorEvidence:i,stopReason:"target_unresolved",reasonCodes:n,generatedAt:s.generatedAt})}function wn(e,t,r,n){const o=Nt(e,kt(t));return W(o,r,n),H("target-unresolved",0,0,o)}async function Tn(e){if(e.signal?.aborted){const v=$e(e.target??ue(e.targetJobId),e.targetJobId,e.target??e.targetJobId?"resolved":"unresolved",[O.CANCELLED]),E=F(void 0,[],!1,0),R=$(e.initialCursor,e.initialCursor,e.initialCursor,[],[O.CANCELLED],"unavailable"),Y=V({watchStatus:"stopped",active:!1,targetEvidence:v,snapshotEvidence:E,cursorEvidence:R,stopReason:"cancelled",reasonCodes:[O.CANCELLED]});return H("cancelled",0,0,Y)}const t=e.target??ue(e.targetJobId),r=e.targetJobId??t?.targetId,n=e.stdout??process.stdout;if(!t){const v=Nt([k.MISSING,O.TARGET_UNRESOLVED]);return W(v,e.format,n),H("target-unresolved",0,0,v)}const o=ye(e.limit??Ce("NEOCORTEX_INVOKE_WATCH_LIMIT",et),et,50),s=Math.max(50,ye(e.pollIntervalMs??Ce("NEOCORTEX_INVOKE_WATCH_POLL_INTERVAL_MS",nt),nt,6e4)),i=ye(e.maxIdlePolls??Ce("NEOCORTEX_INVOKE_WATCH_MAX_IDLE_POLLS",tt),tt,120),c=ye(e.maxPolls??Ce("NEOCORTEX_INVOKE_WATCH_MAX_POLLS",rt),rt,86400),l=e.sleep??An;let p=e.initialCursor,f=0,m=0,d=0;const S=$e(t,r,"resolved",[y.OK]),g={schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:"pending",renderedSummaryCount:0,reasonCodes:[y.WATCH_RENDER_PENDING],publicSafe:!0},h=$(e.initialCursor,p,p,[],e.initialCursor?[y.WATCH_CURSOR_UNCHANGED]:[y.WATCH_NO_SUMMARIES_YET],e.initialCursor?"unchanged":"not_started");W(V({watchStatus:"active",active:!0,targetEvidence:S,snapshotEvidence:g,cursorEvidence:h,stopReason:"not_stopped",reasonCodes:[y.OK]}),e.format,n);let A;try{A=await sr({projectRoot:e.projectRoot,strictReadOnly:e.strictReadOnly})}catch{const v=F(void 0,[],!1,f,[y.WATCH_SNAPSHOT_UNAVAILABLE]),E=$(e.initialCursor,p,p,[],[y.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),R=V({watchStatus:"blocked",active:!1,targetEvidence:S,snapshotEvidence:v,cursorEvidence:E,stopReason:"unavailable_evidence",reasonCodes:[O.STORE_UNAVAILABLE]});return W(R,e.format,n),H("store-unavailable",f,d,R)}try{for(;!e.signal?.aborted&&d<c;){d+=1;const v=p,E=A.collectProcessingOutputSummaryCursor({...p?{cursor:p}:{},...t?{target:t}:{},...r?{jobId:r}:{},limit:o}),R=A.collectSnapshot({jobLimit:50,processingSummaryLimit:1}),Y=R.jobs;if(E.summaries.length>0){for(const z of E.summaries)yn(z,e.format,n),f+=1;p=E.nextCursor??E.summaries[E.summaries.length-1]?.cursor??p,m=0}else p=E.nextCursor??p,m+=1;const q=F(R,E.summaries,!0,E.summaries.length),D=$(e.initialCursor,v,p,E.summaries,E.summaries.length>0?[y.WATCH_CURSOR_ADVANCED]:[y.WATCH_NO_SUMMARIES_YET]);if(W(V({watchStatus:E.summaries.length>0?"polling":"waiting",active:!0,targetEvidence:S,snapshotEvidence:q,cursorEvidence:D,stopReason:"not_stopped",reasonCodes:E.summaries.length>0?[y.WATCH_CURSOR_ADVANCED]:[y.WATCH_NO_SUMMARIES_YET],generatedAt:R.generatedAt}),e.format,n),!E.hasMore&&Cn(Y,r,f)){const z=F(R,E.summaries,!1,f,[O.COMPLETED]),I=$(e.initialCursor,v,p,E.summaries,[O.COMPLETED],"exhausted"),G=V({watchStatus:"stopped",active:!1,targetEvidence:S,snapshotEvidence:z,cursorEvidence:I,stopReason:"not_stopped",reasonCodes:[O.COMPLETED],generatedAt:R.generatedAt});return W(G,e.format,n),H("completed",f,d,G)}if(!E.hasMore&&Sn(Y,r,m,i)){const z=F(R,E.summaries,!1,f,[y.WATCH_STOP_IDLE_LIMIT_REACHED]),I=$(e.initialCursor,v,p,E.summaries,[y.WATCH_STOP_IDLE_LIMIT_REACHED],"exhausted"),G=V({watchStatus:"stopped",active:!1,targetEvidence:S,snapshotEvidence:z,cursorEvidence:I,stopReason:"idle_limit_reached",reasonCodes:[O.IDLE_TIMEOUT,y.WATCH_STOP_IDLE_LIMIT_REACHED],generatedAt:R.generatedAt});return W(G,e.format,n),H("idle-timeout",f,d,G)}E.hasMore||await l(s,e.signal)}}catch{const v=F(void 0,[],!1,f,[y.WATCH_SNAPSHOT_UNAVAILABLE]),E=$(e.initialCursor,p,p,[],[y.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),R=V({watchStatus:"blocked",active:!1,targetEvidence:S,snapshotEvidence:v,cursorEvidence:E,stopReason:"unavailable_evidence",reasonCodes:[O.STORE_UNAVAILABLE]});return W(R,e.format,n),H("store-unavailable",f,d,R)}finally{A.close()}if(e.signal?.aborted){const v=F(void 0,[],!1,f,[O.CANCELLED]),E=$(e.initialCursor,p,p,[],[O.CANCELLED],"unavailable"),R=V({watchStatus:"stopped",active:!1,targetEvidence:S,snapshotEvidence:v,cursorEvidence:E,stopReason:"cancelled",reasonCodes:[O.CANCELLED]});return W(R,e.format,n),H("cancelled",f,d,R)}const L=F(void 0,[],!1,f,[y.WATCH_STOP_MAX_POLLS_REACHED]),T=$(e.initialCursor,p,p,[],[y.WATCH_STOP_MAX_POLLS_REACHED],"exhausted"),B=V({watchStatus:"stopped",active:!1,targetEvidence:S,snapshotEvidence:L,cursorEvidence:T,stopReason:"max_polls_reached",reasonCodes:[O.MAX_POLLS,y.WATCH_STOP_MAX_POLLS_REACHED]});return W(B,e.format,n),H("max-polls",f,d,B)}function j(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 We(e){if(e.startsWith("job-J"))return"job";if(e.startsWith("goal-G"))return"goal";if(e.startsWith("loop-L"))return"loop"}function Lt(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=j(n[1]);o&&t.push(o)}return P(t)}function kt(e){return Lt(e)[0]}function ue(e){const t=e?j(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 Be(e){return P(e.filter(t=>typeof t=="string").map(t=>j(t)).filter(t=>!!t?.startsWith("job-J")))}function bn(e,t){const r=Be(t).filter(n=>n!==e.targetId&&n!==e.jobId);return r.length>0?{...e,relatedJobIds:r}:e}function vn(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"?j(e.targetId):typeof t?.targetId=="string"?j(t.targetId):typeof e.targetJobId=="string"?j(e.targetJobId):void 0,o=ue(n);if(!o||r&&r!==o.selectorKind)return;const s=Array.isArray(e.relatedJobIds)?e.relatedJobIds:Array.isArray(t?.relatedJobIds)?t.relatedJobIds:void 0,i=Be([...s??[],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:j(e.jobId??t?.jobId)??o.jobId}:{},...typeof(e.goalId??t?.goalId)=="string"?{goalId:j(e.goalId??t?.goalId)??o.goalId}:{},...typeof(e.loopId??t?.loopId)=="string"?{loopId:j(e.loopId??t?.loopId)??o.loopId}:{},...i.length>0?{relatedJobIds:i}:{}}}function xt(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 N=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"}),On=new Set(["create","start","resume"]),Nn=new Set(["create","resume","run-once"]);function Fe(e,t,r,n,o){return{schemaVersion:1,contractVersion:"continuity-v1",...r?{command:r}:{},...n?{operation:n}:{},active:e,...o?{watchToken:o}:{},reasonCodes:P(t),serverHeldStream:!1,allJobsPolling:!1,targetResolution:e?"required-after-dispatch":"inactive",publicSafe:!0}}function x(e,t=[],r,n){const o=t.length>0?t:[N.INACTIVE];return{args:e,watch:!1,reasonCodes:o,metadata:Fe(!1,o,r,n),publicSafe:!0}}function Ln(e){const t=e.trim().split(/\s+/).filter(Boolean),r=t.slice(2).filter(s=>s==="--watch").length;if(r===0)return x(e,[],"jobs","watch");if(r!==1)return x(e,[N.AMBIGUOUS],"jobs","watch");const n=t.filter((s,i)=>i<2||s!=="--watch").join(" ");return xt(n)?n.trim().split(/\s+/).filter(Boolean).slice(2).length!==1?x(e,[N.AMBIGUOUS],"jobs","watch"):kt(n)?{args:n,watch:!0,reasonCodes:[N.ACTIVE],metadata:Fe(!0,[N.ACTIVE],"jobs","watch"),publicSafe:!0}:x(e,[N.TARGET_INVALID],"jobs","watch"):x(e,[N.UNSUPPORTED],"jobs","watch")}function kn(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 s="",i=!1,c=null;for(;n<e.length;){const l=e[n];if(c){if(l===c){i=!0,c=null,n+=1;continue}if(l==="\\"&&n+1<e.length){s+=e[n+1],n+=2;continue}s+=l,n+=1;continue}if(/\s/.test(l))break;if(l==='"'||l==="'"){i=!0,c=l,n+=1;continue}s+=l,n+=1}c&&(r=!0),t.push({value:s,start:o,end:n,quoted:i})}return{tokens:t,malformed:r}}function xn(e){if(!e||e.quoted)return;const t=e.value.replace(/^\*/,"").toLowerCase();return t==="goal"||t==="loop"?t:void 0}function Pn(e,t){if(!e||e==="jobs"||!t||t.quoted)return;const r=t.value.toLowerCase();return(e==="goal"?On:Nn).has(r)?r:void 0}function jn(e){return!e.quoted&&e.value!=="--watch"&&e.value.toLowerCase().startsWith("--watch")}function Dn(e){const{tokens:t,malformed:r}=kn(e),n=xn(t[0]),o=Pn(n,t[1]);if(r)return x(e,[N.MALFORMED],n,o);const s=t.filter(d=>d.value==="--watch"&&!d.quoted),i=t.filter(d=>d.value==="--watch"&&d.quoted),c=t.filter(jn);if(!(s.length>0||i.length>0||c.length>0))return x(e,[],n,o);if(s.length>1)return x(e,[N.DUPLICATE],n,o);if(s.length===1&&(i.length>0||c.length>0))return x(e,[N.AMBIGUOUS],n,o);if(i.length>0)return x(e,[N.QUOTED],n,o);if(c.length>0)return x(e,[N.MALFORMED],n,o);const p=s[0];if(!p)return x(e,[],n,o);if(t[t.length-1]!==p)return x(e,[N.NON_FINAL],n,o);if(!n||!o)return x(e,[N.UNRESOLVED],n,o);const f=`${e.slice(0,p.start)}${e.slice(p.end)}`.trim(),m={literal:"--watch",position:"final",start:p.start,end:p.end,quoted:!1,publicSafe:!0};return{args:f,watch:!0,reasonCodes:[N.ACTIVE],metadata:Fe(!0,[N.ACTIVE],n,o,m),publicSafe:!0}}function Mn(e){return xt(e)?Ln(e):Dn(e)}function Un(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&Mr.has(t)):[]}function se(e){return{disabled:!0,reasonCodes:P(e.length>0?e:[k.MISSING])}}function He(e,t,r=[],n){const o=ue(t);if(o)return{source:e,target:bn(o,r),targetJobId:o.targetId,...n?{initialCursor:n}:{},serverHeldStream:!1}}function $n(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 s=P([...o.target.relatedJobIds??[],...r.target.relatedJobIds??[]]);t.set(n,{...o,target:s.length>0?{...o.target,relatedJobIds:s}:o.target,initialCursor:o.initialCursor??r.initialCursor})}return Array.from(t.values())}function K(e,t,r,n){return{source:e,hasEvidence:t,candidates:$n(r.filter(o=>!!o)),...n&&n.length>0?{disabledReasonCodes:P(n)}:{}}}function Vn(e,t){return e.target.selectorKind===t.target.selectorKind&&e.target.targetId===t.target.targetId}function le(e,t){const r=P(e.filter(n=>typeof n=="string").map(n=>j(n)).filter(n=>!!n));if(t){const n=r.find(o=>We(o)===t);if(n)return n}return r[0]}function Se(e,t){return P(e.filter(r=>typeof r=="string").map(r=>j(r)).filter(r=>!!r)).find(r=>We(r)===t)}function Wn(e){const t=_(e?.continuity)?e.continuity:void 0,r=_(t?.jobs)?t.jobs:void 0,n=_(r?.watcher)?r.watcher:void 0,o=Un(n?.reasonCodes??r?.reasonCodes);if(!n)return K("watcher-metadata",o.length>0,[],o);if(n.active===!1||o.length>0)return K("watcher-metadata",!0,[],o.length>0?o:[k.MALFORMED]);if(n.serverHeldStream!==!1)return K("watcher-metadata",!0,[],[k.SERVER_HELD_STREAM]);const s=vn(n);if(!s)return K("watcher-metadata",!0,[],[k.MISSING]);const i=typeof n.initialCursor=="string"?n.initialCursor:void 0;return K("watcher-metadata",!0,[{source:"watcher-metadata",target:s,targetJobId:s.targetId,...i?{initialCursor:i}:{},serverHeldStream:!1}])}function Pt(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"?le([e.goalId,e.targetGoalId,e.campaignId,e.jobId,e.targetJobId,o?.goalId,o?.campaignId,o?.jobId],"goal"):le([e.loopId,e.targetLoopId,e.jobId,e.targetJobId,o?.loopId,o?.jobId,n?.loopId,n?.jobId],"loop"))??le([e.jobId,e.targetJobId,o?.jobId,n?.jobId]);return He("goal-loop-continuity-metadata",i,[e.jobId,e.targetJobId,o?.jobId,n?.jobId])}function Bn(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?Pt(r,"goal"):void 0,n?Pt(n,"loop"):void 0],s=!!(r||n);return K("goal-loop-continuity-metadata",s,o,s&&o.every(i=>!i)?[k.MISSING]:void 0)}function Fn(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 jt(e,t){const r=_(t.metadata)?t.metadata:void 0,n=Se([t.goalId,t.targetGoalId,t.campaignId,r?.goalId,r?.campaignId,t.jobId,r?.jobId],"goal"),o=Se([t.loopId,t.targetLoopId,r?.loopId,t.jobId,r?.jobId],"loop"),s=le([t.jobId,t.targetJobId,r?.jobId],"job"),i=n??o??s;if(!i)return;const c=e.get(i)??{targetId:i,relatedJobIds:[]};c.relatedJobIds.push(...Be([s,t.jobId,t.targetJobId,r?.jobId])),e.set(i,c)}function Hn(e){const t=_(e.metadata)?e.metadata:void 0;return!!(Se([e.goalId,e.targetGoalId,e.campaignId,t?.goalId,t?.campaignId,e.jobId,t?.jobId],"goal")??Se([e.loopId,e.targetLoopId,t?.loopId,e.jobId,t?.jobId],"loop"))}function Gn(e){const t=_(e.metadata)?e.metadata:void 0;return!!le([e.goalId,e.targetGoalId,e.campaignId,e.loopId,e.targetLoopId,e.jobId,e.targetJobId,t?.goalId,t?.campaignId,t?.loopId,t?.jobId])}function Dt(e,t){const r=[];for(const i of["metadata","job","event","receipt","processingOutputSummary"]){const c=t[i];_(c)&&r.push(c)}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 s=r.some(Gn);for(const i of r)jt(e,i);(!s||Hn(t))&&jt(e,t)}function Jn(e){const t=Fn(e?.continuityStateUpdate),r=new Map;for(const o of t){Dt(r,o);const s=Array.isArray(o.operations)?o.operations.filter(_):[];for(const i of s)Dt(r,i)}const n=Array.from(r.values()).map(o=>He("continuity-state-update-operation-log",o.targetId,o.relatedJobIds));return K("continuity-state-update-operation-log",t.length>0,n,t.length>0&&n.every(o=>!o)?[k.MISSING]:void 0)}function Kn(e){const t=Lt(e);return K("explicit-args",t.length>0,t.map(r=>He("explicit-args",r)))}function Yn(e,t){const r=[Wn(e),Bn(e),Jn(e),Kn(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 se(o.disabledReasonCodes);if(o.candidates.length!==1)return se([o.candidates.length>1?k.AMBIGUOUS:k.MISSING]);const s=o.candidates[0];for(const i of r.slice(n+1)){if(!i.hasEvidence)continue;if(i.disabledReasonCodes&&i.disabledReasonCodes.length>0)return se(i.disabledReasonCodes);if(i.candidates.length>1)return se([k.AMBIGUOUS]);const c=i.candidates[0];if(c&&!Vn(s,c))return se([k.CONFLICT])}return{target:s.target,targetJobId:s.targetJobId,...s.initialCursor?{initialCursor:s.initialCursor}:{},source:s.source,serverHeldStream:!1}}return se([k.MISSING])}async function zn(e,t,r,n={}){const s=await De(e,"/api/v1/invoke",t,r,n);if(s.networkFailure||!s.response)return{ok:!1,status:0,error:"Network error after bounded retries"};const{response:i,text:c,parsed:l}=s;try{if(!i.ok)return{ok:!1,status:i.status,error:Object.keys(l).length>0?`${l.error_code??"ERROR"}: ${l.message??c}`:`HTTP ${i.status}: ${c}`,errorBody:Object.keys(l).length>0?l:void 0};const p=l,f=i.headers.get("X-Client-Version-Warning");return f&&!St&&(St=!0,process.stderr.write(`
15
- [Neocortex] ${f}
16
-
17
- `)),{ok:!0,status:i.status,data:p}}catch(p){return{ok:!1,status:0,error:(p instanceof Error?p.message:String(p)).includes("abort")?`Request timeout after ${ct/1e3}s`:"Network error: invalid response"}}}async function qn(e,t,r,n={}){const o=await De(e,"/api/v1/invoke/epic-claims/acknowledge",{...r,registryVersion:Z,registryChecksum:Q},t,n);return!!o.response?.ok&&o.parsed.status==="ok"&&o.parsed.claimOutcome===r.status}async function Xn(e,t,r,n,o,s={}){if(!o)return 0;const i=ge(e);let c=0;for(const[l,p]of Object.entries(i.operations))!p.claimId||!p.epicId||!t.epics?.[p.epicId]||!await qn(r,n,{claimId:p.claimId,projectId:o,epicId:p.epicId,status:"materialized"},s)||(Nr(e,l),c+=1);return c}function Qn(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],s=o.certificate,i=s?.expectedTransition;if(o.storyIds!=="[CIRCULAR]"||s?.rank!=="[CIRCULAR]"||i?.selectedStoryIds!=="[CIRCULAR]")return;const c=typeof n.epicId=="string"?n.epicId:"",l=e.epics[c],p=Array.isArray(i.storyLifecycle)?i.storyLifecycle:[],f=p.length===1&&typeof p[0]?.storyId=="string"?p[0].storyId:"",d=e.stories[f]?.checkpoint;if(!l||l.branch_mode!=="epic"||typeof l.execution_branch!="string"||typeof l.origin_branch!="string"||l.branch_lease!==void 0&&l.branch_lease!==null||!d||d.qaVerdict!=="passed"||d.reviewVerdict!=="approved"||!Array.isArray(d.receiptRefs))return;const g=(Array.isArray(l.stories)?l.stories.filter(h=>typeof h=="string"):[]).find(h=>{const A=e.stories[h];return!A||["done","completed","merged"].includes(String(A.status))?!1:(Array.isArray(A.depends_on)?A.depends_on.filter(T=>typeof T=="string"):[]).every(T=>["done","completed","merged"].includes(String(e.stories[T]?.status)))});if(g)return{epicId:c,expectedNextStoryId:g,branchMode:"epic",executionBranch:l.execution_branch,originBranch:l.origin_branch,branchLeaseReleased:!0,checkpoint:{schemaVersion:1,storyId:d.storyId,epicId:d.epicId,branch:d.branch,baseSha:d.baseSha,headSha:d.headSha,receiptRefs:[...d.receiptRefs],qaVerdict:"passed",reviewVerdict:"approved"}}}async function Zn(e){const t=jr(e.args);if(t.outcome!=="resolved"){const a=_r(t,"client");return{success:!1,error:`INVOCATION_${t.outcome.toUpperCase()}`,errorCode:`INVOCATION_${t.outcome.toUpperCase()}`,metadata:{invocationAdmission:a},exitCode:1}}const r=Ne(e.projectRoot),n=t.selection.commandId,o=Jt.find(a=>a.id===n),s=o?.subcommands.find(a=>a.id===t.selection.operationId),i=s?s.policy.strictReadOnly==="allow":o?.policy.strictReadOnly==="allow";let c;try{c=gr({invocationId:Re(),intent:e.strictReadOnly?{schemaVersion:1,policy:pr,registryVersion:Z,registryChecksum:Q}:void 0,registryVersion:Z,registryChecksum:Q,registryAllowsStrict:i,requestCanonicalBytes:JSON.stringify({command:n})})}catch(a){if(a instanceof ie)return{success:!1,error:a.code,errorCode:a.code,exitCode:1};throw a}{c.beginProjection();for(const a of st)c.project(a);for(const a of fr)c.project(a);c.seal()}const l=c.mode==="strict",p=cr({cwd:r,env:e.environment??process.env,targetFlag:e.platformTarget}).targetId;c.execute({phase:"client-preflight",domain:"client-persistence",category:"first-run-marker",operation:"create"},()=>Pr(),()=>{});const f=Xr(c),m=(e.serverUrl??f?.serverUrl??Kt).replace(/\/+$/,"");try{const{normalizeYoloopTargetArgs:a}=await import("../yoloop/target-normalization.js"),u=a(e.args,{projectRoot:r});if(!u.ok)return process.stderr.write(`${u.message} reason=${u.reasonCode}
18
- `),{success:!1,error:u.message,exitCode:1};u.changed&&(e={...e,args:u.args},process.stderr.write(`[Neocortex] yoloop target normalized: ${u.reasonCodes.join(",")}
19
- `))}catch{const a="INVALID_YOLOOP_TARGET: yoloop target normalization was unavailable; no request was sent.";return process.stderr.write(`${a}
20
- `),{success:!1,error:a,exitCode:1}}try{c.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>Qt(r,{args:e.args}),()=>{})}catch(a){if(a instanceof Zt)return process.stderr.write(`${a.message}
21
- `),{success:!1,error:a.message,exitCode:1};const u=a instanceof Error?a.message:String(a);return process.stderr.write(`[Neocortex] state.json repair stopped unexpectedly: ${u}. No request was sent; inspect .neocortex/state.json and rerun.
22
- `),{success:!1,error:u,exitCode:1}}const d=Kr(r);try{const{maybeAutoResolveYoloopArgs:a}=await import("../yoloop/invoke-hooks.js"),u={args:e.args,projectRoot:r,logger:{info:b=>process.stderr.write(`${b}
23
- `),warn:b=>process.stderr.write(`${b}
24
- `)}};a(u),u.args!==e.args&&(e={...e,args:u.args})}catch(a){const u=a instanceof Error?a.message:String(a);process.stderr.write(`[Neocortex] Auto-resolve hook (P121.05) failed: ${u}. Proceeding with raw args.
25
- `)}try{const{readYoloopForRequest:a}=await import("../yoloop/invoke-hooks.js"),u=await a(e.args,r);if(u){const b=Qn(d,u);d.yoloop=b?{...u,continuationRecoveryEvidence:b}:u}}catch{}try{const{readContinuityForRequest:a}=await import("../continuity/invoke-hooks.js"),u=await a(e.args,r,void 0,c);u&&(d.continuity=u)}catch(a){if(a instanceof ie)return{success:!1,error:a.code,errorCode:a.code,exitCode:1};const u=a instanceof Error?a.message:String(a);process.stderr.write(`[Neocortex] continuity snapshot hook failed: ${u}. Proceeding without continuity state.
26
- `)}try{const{maybeRunDiscoveryHook:a}=await import("../yoloop/invoke-hooks.js");await a({args:e.args,projectRoot:r,stateSnapshot:d,featureFlag:process.env.YOLOOP_AUTO_DISCOVERY!=="off",logger:{warn:u=>{console.warn(u)},info:u=>{console.error(u)}}})}catch(a){const u=a instanceof Error?a.message:String(a);process.stderr.write(`[Neocortex] discovery hook failed: ${u}. Proceeding without enrichment.
27
- `)}try{const{readArchitecturePolicy:a}=await import("../policy/architecture-policy.js"),u=await a(r);u&&(d.architecture_policy=u)}catch(a){const u=a instanceof Error?a.message:String(a);console.warn(`[Neocortex] architecture-policy hook failed: ${u}. Proceeding without policy.`)}try{const a=/^(1|true|on|yes)$/i.test(process.env.NEOCORTEX_GRAPH_RETRIEVAL??""),{maybeRunGraphRetrievalHook:u}=await import("../yoloop/invoke-hooks.js"),b=await u({args:e.args,projectRoot:r,featureFlag:a,logger:{warn:pe=>process.stderr.write(`${pe}
28
- `)}});b.applied&&b.metadata&&(d.graphRetrieval=b.metadata)}catch(a){const u=a instanceof Error?a.message:String(a);process.stderr.write(`[Neocortex] graph retrieval hook failed: ${u}. Proceeding without enrichment.
29
- `)}try{if(Vr(e.args)){const{collectProjectEvidence:a}=await import("../evidence/collector.js"),u=a({projectRoot:r});(u.evidence.length>0||u.exclusions.length>0)&&(d.projectEvidence=u)}}catch(a){const u=a instanceof Error?a.message:String(a);process.stderr.write(`[Neocortex] project evidence collection failed: ${u}. Proceeding without local project evidence.
30
- `)}try{const a=await c.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"checkpoint-consume",operation:"consume"},async()=>{const{readAndConsumeCheckpoint:u}=await import("../checkpoint/index.js");return u(r)},async()=>{});a&&(d.implementCheckpoint=a)}catch(a){const u=a instanceof Error?a.message:String(a);process.stderr.write(`[Neocortex] checkpoint hook failed: ${u}. Proceeding without checkpoint.
31
- `)}const S=f?.licenseKey?new Te({cacheDir:be,passphrase:f.licenseKey,strictReadOnly:l}):null,g=e.args.trim();if(kr(g))try{d.projectMemoryBootstrap=xr(r)}catch(a){const u=a instanceof Error?a.message:String(a);process.stderr.write(`[Neocortex] project-memory bootstrap diagnosis failed: ${u}. Proceeding without local memory snapshot.
32
- `)}if(!g&&S){const a=await c.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>Yr(S),async()=>null);if(a)return c.complete(),{success:!0,instructions:a.instructions,metadata:a.metadata,exitCode:0}}const h=await Qr(m,f?.licenseKey,c);if(!h){const a=f&&!f.licenseKey?" This may be caused by a machine fingerprint change (e.g., hardware or hostname change).":"";try{const u=Ze(),b=Xe("NOT_CONFIGURED",u);b&&process.stderr.write(Qe(b,u))}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 A=d.config.project_id;try{await c.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Xn(r,d,m,h.token,A,{refreshToken:()=>h.client.forceRefresh()}),async()=>0)}catch{}const L=Mt(g);if(L)try{const a=await h.tierClient.preFlightCheck(L);if(!a.allowed)return process.stderr.write(`[neocortex] ${a.message}
33
- `),{success:!1,error:a.message??"Trigger not available on your plan",exitCode:1}}catch{}const T=await mn({args:g,projectRoot:r,platformTarget:p,environment:e.environment??process.env,bootstrapper:e.runnerBootstrapper,effectAuthority:c});if(T.attachToRequest&&(d.runnerBootstrap=T.metadata),T.warning&&process.stderr.write(`[Neocortex] ${T.warning}
34
- `),!T.shouldContinue)return T.error&&process.stderr.write(`[Neocortex] ${T.error}
35
- `),{success:!1,error:T.error??"Runner auto-bootstrap required but failed.",errorCode:T.errorCode,exitCode:T.exitCode??1};const B=Xt(g,d),v=ze(g),E=A;if(v==="create-epic"&&!E){const a="EPIC_PROJECT_ID_REQUIRED: run the offline project identity migration before creating an epic.";return process.stderr.write(`${a}
36
- `),{success:!1,error:a,errorCode:"EPIC_PROJECT_ID_REQUIRED",exitCode:1}}let R;try{R=c.execute({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>v==="create-epic"?Or(r,g):void 0,()=>{})}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const Y=R?.key,q=l?{schemaVersion:1,invocationId:c.invocationId,intent:c.intent,clientProjection:mr(st.map(a=>({...a,count:1})))}:void 0;let D={args:g,projectRoot:r.replace(we(),"~"),stateSnapshot:B,platformTarget:p,projectId:E,idempotencyKey:Y,registryVersion:Z,registryChecksum:Q,...q?{strictReadOnly:q}:{}};const z=oe(D);if(e.inputSource&&e.inputSource!=="args"&&z>=ve)try{D={argsRef:(await lr(c,"secondary-mutation",()=>on(m,g,h.token,()=>h.client.forceRefresh()),async()=>{throw new ie("readonly-physical-boundary-unsafe","boundary")})).argsRef,projectRoot:r.replace(we(),"~"),stateSnapshot:B,platformTarget:p,projectId:E,idempotencyKey:Y,registryVersion:Z,registryChecksum:Q,...q?{strictReadOnly:q}:{}}}catch(a){return a instanceof ie?{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=ln(D);D=a.body,a.degraded?vt(D,a.telemetry):fn(D)}catch(a){if(a instanceof ht)return vt(D,a.telemetry),process.stderr.write(`[Neocortex] ${a.message}
37
- `),{success:!1,error:a.message,errorCode:a.code,metadata:{invokePayload:a.telemetry},exitCode:1};throw a}let I=await ur("invoke-query",()=>zn(m,D,h.token,{refreshToken:()=>h.client.forceRefresh()})),G;if(l&&I.ok)try{const a=I.data?.metadata.strictReadOnly;hr(c,a),G=a.security}catch(a){const u=a instanceof ie?a.code:"readonly-receipt-mismatch";return{success:!1,error:u,errorCode:u,exitCode:1}}if(!I.ok&&I.status===426){const a=I.errorBody,u=a?.upgrade_command??"npm install -g @ornexus/neocortex@latest",b=a?.min_version??"unknown";return process.stderr.write(`
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(`
38
40
  `),process.stderr.write(`==================================================
39
41
  `),process.stderr.write(` UPGRADE REQUIRED
40
42
  `),process.stderr.write(`==================================================
41
43
  `),process.stderr.write(`
42
- Your Neocortex version (${ee}) is no longer supported.
43
- `),process.stderr.write(` Minimum required: ${b}
44
+ Your Neocortex version (${se}) is no longer supported.
45
+ `),process.stderr.write(` Minimum required: ${I}
44
46
 
45
47
  `),process.stderr.write(` Run this command to update:
46
48
 
47
- `),process.stderr.write(` ${u}
49
+ `),process.stderr.write(` ${c}
48
50
 
49
51
  `),process.stderr.write(` After updating, re-run your command.
50
52
  `),process.stderr.write(`==================================================
51
53
 
52
- `),{success:!1,error:`UPGRADE_REQUIRED: Client version ${ee} is below minimum ${b}. Run: ${u}`,exitCode:3}}if(!I.ok||!I.data){const a=I.status===401?2:(I.status===429||I.status>=500,1);try{const u=I.errorBody?.error_code??(I.status===429?"RATE_LIMITED":I.status>=500?"SERVER_ERROR":void 0);if(u){const b=Ze(),pe=Xe(u,b);pe&&process.stderr.write(Qe(pe,b))}}catch{}return{success:!1,error:te(I.error??"Unknown error from server",me),exitCode:a}}if(!g&&I.data.metadata?.mode==="menu"&&S&&await c.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>zr(S,I.data.instructions,I.data.metadata),async()=>{}).catch(()=>{}),I.data.metadata&&await c.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"tier-cache",operation:"update"},()=>h.tierClient.updateQuotaFromResponse(I.data.metadata),async()=>{}).catch(()=>{}),I.data.metadata?.mode==="error"&&I.data.metadata?.errorCode==="CLIENT_UPGRADE_REQUIRED")return process.stderr.write(`
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(`
53
55
  `),process.stderr.write(`==================================================
54
56
  `),process.stderr.write(` YOLOOP CLIENT UPGRADE REQUIRED
55
57
  `),process.stderr.write(`==================================================
56
58
  `),process.stderr.write(`
57
- Your Neocortex client version (${ee}) does not
59
+ Your Neocortex client version (${se}) does not
58
60
  `),process.stderr.write(` support client-side yoloop state persistence.
59
61
 
60
62
  `),process.stderr.write(` Run this command to upgrade:
@@ -64,12 +66,12 @@ ${t}
64
66
  `),process.stderr.write(` After upgrading, re-run your yoloop command.
65
67
  `),process.stderr.write(`==================================================
66
68
 
67
- `),{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(I.data.metadata?.yoloopStateUpdate)try{await c.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>{const{persistYoloopFromResponse:a}=await import("../yoloop/invoke-hooks.js");await a(I.data.metadata,r)},async()=>{})}catch{}if(I.data.metadata?.continuityStateUpdate)try{const a=await c.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"continuity-store",operation:"update"},async()=>{const{persistContinuityFromResponse:u}=await import("../continuity/invoke-hooks.js");return u(I.data.metadata,r)},async()=>({ok:!0,reasonCodes:[]}));if(!a.ok){const u=a.reasonCodes.join(",");return process.stderr.write(`[Neocortex] continuity persistence failed: ${u}. No continuity mutation was committed.
68
- `),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${u}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}}catch(a){const u=a instanceof Error?a.message:String(a);return process.stderr.write(`[Neocortex] continuity persistence hook failed: ${u}. No continuity mutation was committed.
69
- `),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${te(u,me)}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}if(I.data.metadata?.stateMutated===!0)try{await c.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>{const{persistMigratedStateFromResponse:a}=await import("../yoloop/invoke-hooks.js");await a(I.data.metadata,r)},async()=>{})}catch{}if(I.data.metadata?.tier_changed){const a=I.data.metadata.current_tier;try{await h.client.forceRefresh()?(await h.tierClient.invalidateTierCache(),process.stderr.write(`[Neocortex] Token atualizado automaticamente para tier ${a}
70
- `)):process.stderr.write(`[Neocortex] Seu tier foi atualizado para ${a}! Execute "neocortex activate" para obter um token atualizado.
71
- `)}catch{process.stderr.write(`[Neocortex] Seu tier foi atualizado para ${a}! Execute "neocortex activate" para obter um token atualizado.
72
- `)}}const Ge=ke(I.data.instructions,I.data.metadata);if(R&&I.data.metadata?.mode!=="error")try{const a=I.data.metadata?.epicClaim;if(!a||typeof a!="object"||Array.isArray(a))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const u=a;if(u.outcome!=="reserved"||typeof u.claimId!="string"||typeof u.epicId!="string")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");c.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Lr(r,R.fingerprint,u.claimId,u.epicId),()=>{})}catch{}return c.complete(G),{success:!0,instructions:Ge.instructions,metadata:Ge.metadata,exitCode:0}}function Mt(e){const[t]=e.trim().split(/\s+/,1);return t?/^@?epic-[a-z0-9][a-z0-9._-]*$/i.test(t)?"epic":ze(t):null}const Ut="Provide exactly one invoke input source: --args <string>, --stdin, or --args-file <path>.",eo=`
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=`
73
75
  neocortex-client invoke - Send orchestration request to server
74
76
 
75
77
  Usage:
@@ -138,12 +140,12 @@ Safety:
138
140
  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.
139
141
  Jobs, goal and loop watch use serverHeldStream=false and foreground local SQLite polling of public processing summaries only.
140
142
  Unresolved targets disable polling with public reason codes; there is no all-jobs fallback.
141
- `.trim();function to(e){return e.includes("--help")||e.includes("-h")||e.includes("help")}function $t(e){return new U("INVOKE_INPUT_VALUE_MISSING",`${e} requires a value. ${Ut}`)}function ro(e){try{if(!Ft(e).isFile())throw new U("INVOKE_ARGS_FILE_NOT_FILE","--args-file must point to a readable UTF-8 text file.");return ae(e,"utf8")}catch(t){throw t instanceof U?t:new U("INVOKE_ARGS_FILE_READ_FAILED","--args-file could not be read as UTF-8 text. Check the path and permissions.")}}function no(){try{if(process.stdin.isTTY)throw new U("INVOKE_STDIN_EMPTY","--stdin requires piped UTF-8 text, for example: neocortex-client invoke --stdin < synthetic.story.md");return ae(0,"utf8")}catch(e){throw e instanceof U?e:new U("INVOKE_STDIN_READ_FAILED","--stdin could not be read as UTF-8 text. Pipe command text into stdin and retry.")}}function oo(e,t={}){let r,n=!1,o,s,i="plain",c=!1,l,p,f=!1;for(let h=0;h<e.length;h++)switch(e[h]){case"--args":{const L=e[++h];if(L===void 0)throw $t("--args");r=L;break}case"--stdin":n=!0;break;case"--args-file":{const L=e[++h];if(L===void 0)throw $t("--args-file");o=L;break}case"--project-root":s=e[++h];break;case"--format":i=e[++h]??"plain";break;case"--watch":c=!0;break;case"--server-url":l=e[++h];break;case"--platform-target":p=e[++h];break;case"--strict-read-only":f=!0;break}const m=[r!==void 0?"args":void 0,n?"stdin":void 0,o!==void 0?"args-file":void 0].filter(h=>h!==void 0);if(m.length===0)throw new U("INVOKE_INPUT_SOURCE_MISSING",Ut);if(m.length>1)throw new U("INVOKE_INPUT_SOURCE_CONFLICT",`Choose only one invoke input source; received ${m.join(", ")}.`);const d=m[0],S=d==="args"?r:d==="stdin"?(t.readStdin??no)():(t.readArgsFile??ro)(o),g=d==="args"?Mn(S):x(S);return{args:g.args,inputSource:d,projectRoot:s,format:i,watch:c||g.watch,commandLevelWatch:g.metadata,serverUrl:l,platformTarget:p,strictReadOnly:f}}function Vt(e,t){return t?.active?{...e??{},commandLevelWatch:t,serverHeldStream:!1}:e}function so(e,t,r=process.stdout,n=process.stderr){if(t.format==="json"){const i=ke(e.instructions,e.metadata),c=Vt(i.metadata,t.commandLevelWatch);if(t.watch){r.write(JSON.stringify({type:"invoke_result",instructions:i.instructions,metadata:c,publicSafe:!0})+`
142
- `);return}r.write(JSON.stringify({instructions:i.instructions,metadata:c})+`
143
- `);return}const o=ke(e.instructions,e.metadata),s=Vt(o.metadata,t.commandLevelWatch);r.write(o.instructions+`
144
- `),s&&n.write(JSON.stringify(s)+`
145
- `)}function ao(e){const t=()=>e.abort();return process.once("SIGINT",t),process.once("SIGTERM",t),()=>{process.removeListener("SIGINT",t),process.removeListener("SIGTERM",t)}}async function Do(e){if(to(e))return process.stdout.write(`${eo}
146
- `),0;let t;try{t=oo(e)}catch(n){if(n instanceof U)return process.stderr.write(JSON.stringify({error_code:n.code,message:n.message})+`
147
- `),1;throw n}if(ar(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."})+`
148
- `),1):(await ir({args:t.args,projectRoot:Ne(t.projectRoot),format:t.format,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})).exitCode;const r=await Zn({args:t.args,inputSource:t.inputSource,watch:t.watch,projectRoot:t.projectRoot,format:t.format,serverUrl:t.serverUrl,platformTarget:t.platformTarget,strictReadOnly:t.strictReadOnly});if(!r.success)return process.stderr.write(JSON.stringify({error_code:r.errorCode??(r.exitCode===2?"NOT_CONFIGURED":"INVOKE_ERROR"),message:te(r.error??"",me)})+`
149
- `),r.exitCode;if(so(r,t),t.watch){const n=new AbortController,o=ao(n);try{const s=Yn(r.metadata,t.args);s.disabled?wn(s.reasonCodes??[O.TARGET_UNRESOLVED],t.args,t.format,process.stdout):await Tn({projectRoot:Ne(t.projectRoot),format:t.format,strictReadOnly:t.strictReadOnly,...s,signal:n.signal})}finally{o()}}return 0}export{eo as INVOKE_HELP_TEXT,ut as INVOKE_PAYLOAD_LIMIT_BYTES,ve as INVOKE_PAYLOAD_WARNING_THRESHOLD_BYTES,U as InvokeCliInputError,ht as InvokePayloadTooLargeError,Po as __resetSchemaDriftWarnedForTests,Xn as acknowledgeMaterializedPendingEpicClaims,jr as admitClientInvocation,tn as buildSignedInvokeAttempt,Nr as clearPendingEpicIdempotencyKey,xr as collectInitProjectMemoryBootstrapSnapshot,Kr as collectStateSnapshot,oe as computeInvokeRequestBodySizeBytes,jo as createFullStateSnapshotScope,Me as createInvokePayloadTelemetry,Br as detectStateSchemaDrift,Mt as extractPreFlightTrigger,Or as getOrCreatePendingEpicIdempotencyKey,ln as guardInvokeRequestBodySize,Zn as invoke,Do as invokeCliHandler,kr as isInitTrigger,fn as maybeEmitInvokePayloadSizeWarning,mn as maybeRunInvokeRunnerAutoBootstrap,oo as parseInvokeCliOptions,wt as postMaterializationJson,Lr as recordPendingEpicReservation,Mn as resolveInvokeCommandLevelWatch,Ne as resolveInvokeProjectRoot,Yn as resolveInvokeWatchTarget,ke as sanitizeInvokeCliOutput,qn as sendEpicClaimAcknowledgement,zn as sendInvokeRequest,Vr as shouldCollectProjectEvidenceForInvoke,Tn as watchContinuityProcessingSummaries,so as writeInvokeCliSuccessOutput};
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};