@ornexus/neocortex 4.60.18 → 4.60.19

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 (88) hide show
  1. package/dist/sbom.cdx.json +6504 -6410
  2. package/docs/install/installer-diagnostics.md +52 -0
  3. package/install.ps1 +1 -1
  4. package/install.sh +1 -1
  5. package/package.json +27 -4
  6. package/packages/client/dist/agent/refresh-stubs.d.ts +7 -0
  7. package/packages/client/dist/agent/refresh-stubs.js +2 -2
  8. package/packages/client/dist/cache/encrypted-cache.d.ts +3 -0
  9. package/packages/client/dist/cache/encrypted-cache.js +1 -1
  10. package/packages/client/dist/checkpoint/checkpoint-client-reader.js +2 -2
  11. package/packages/client/dist/cli.js +3 -3
  12. package/packages/client/dist/commands/activate.js +7 -7
  13. package/packages/client/dist/commands/config.js +1 -1
  14. package/packages/client/dist/commands/invoke.d.ts +64 -0
  15. package/packages/client/dist/commands/invoke.js +54 -47
  16. package/packages/client/dist/config/secure-config.d.ts +9 -3
  17. package/packages/client/dist/config/secure-config.js +8 -8
  18. package/packages/client/dist/config.d.ts +1 -1
  19. package/packages/client/dist/config.js +1 -1
  20. package/packages/client/dist/continuity/continuity-client-state-store.d.ts +1 -0
  21. package/packages/client/dist/continuity/continuity-client-state-store.js +1 -1
  22. package/packages/client/dist/continuity/invoke-hooks.d.ts +2 -1
  23. package/packages/client/dist/continuity/invoke-hooks.js +1 -1
  24. package/packages/client/dist/continuity/sqlite-store.d.ts +21 -0
  25. package/packages/client/dist/continuity/sqlite-store.js +49 -49
  26. package/packages/client/dist/effects/invoke-effect-gateways.d.ts +22 -0
  27. package/packages/client/dist/effects/invoke-effect-gateways.js +1 -0
  28. package/packages/client/dist/errors/frontmatter-diagnostics.d.ts +20 -0
  29. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -0
  30. package/packages/client/dist/generated/command-registry.generated.d.ts +2836 -0
  31. package/packages/client/dist/generated/command-registry.generated.js +1 -0
  32. package/packages/client/dist/graph-retrieval/pre-command-hook.d.ts +2 -0
  33. package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -1
  34. package/packages/client/dist/index.d.ts +1 -0
  35. package/packages/client/dist/index.js +1 -1
  36. package/packages/client/dist/license/license-client.d.ts +3 -0
  37. package/packages/client/dist/license/license-client.js +1 -1
  38. package/packages/client/dist/machine/fingerprint.d.ts +3 -1
  39. package/packages/client/dist/machine/fingerprint.js +2 -2
  40. package/packages/client/dist/memory/project-memory-writer.js +19 -15
  41. package/packages/client/dist/{subagent-approval-policy.d.ts → policy/subagent-approval-policy.d.ts} +8 -3
  42. package/packages/client/dist/policy/subagent-approval-policy.js +1 -0
  43. package/packages/client/dist/resolvers/local-resolver.d.ts +3 -0
  44. package/packages/client/dist/resolvers/local-resolver.js +4 -4
  45. package/packages/client/dist/runner/cli.d.ts +1 -0
  46. package/packages/client/dist/runner/cli.js +1 -1
  47. package/packages/client/dist/runner/headless/prepared-story-bundle.d.ts +20 -0
  48. package/packages/client/dist/runner/headless/prepared-story-bundle.js +1 -0
  49. package/packages/client/dist/runner/headless/run-yoloop.d.ts +2 -0
  50. package/packages/client/dist/runner/headless/run-yoloop.js +1 -1
  51. package/packages/client/dist/runner/portal-sync-worker.js +1 -1
  52. package/packages/client/dist/runner/scheduler.d.ts +3 -0
  53. package/packages/client/dist/runner/scheduler.js +7 -7
  54. package/packages/client/dist/state/project-state-snapshot.js +1 -1
  55. package/packages/client/dist/tier/tier-aware-client.js +1 -1
  56. package/packages/client/dist/version.d.ts +3 -0
  57. package/packages/client/dist/version.js +1 -0
  58. package/packages/client/dist/yoloop/discovery-hook.js +2 -2
  59. package/packages/client/dist/yoloop/invoke-hooks.js +4 -4
  60. package/packages/client/dist/yoloop/shared-discover-epics.d.ts +9 -3
  61. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1
  62. package/packages/client/dist/yoloop/shared-yoloop-types.d.ts +24 -0
  63. package/packages/client/dist/yoloop/target-normalization.d.ts +24 -0
  64. package/packages/client/dist/yoloop/target-normalization.js +1 -0
  65. package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +4 -0
  66. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1
  67. package/packages/shared/dist/command-registry-contract.js +382 -0
  68. package/packages/shared/dist/generated/command-registry.generated.js +4216 -0
  69. package/packages/shared/dist/generated/invocation-schema.generated.js +1850 -0
  70. package/packages/shared/dist/invocation/index.d.ts +175 -0
  71. package/packages/shared/dist/invocation/index.js +587 -0
  72. package/packages/shared/dist/nx-invoke-signature.js +233 -0
  73. package/packages/shared/dist/strict-readonly.js +381 -0
  74. package/packages/shared/dist/yoloop/wave-decision-receipt.js +77 -0
  75. package/targets-stubs/antigravity/gemini.md +1 -1
  76. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  77. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  78. package/targets-stubs/claude-code/neocortex-root.md +5 -2
  79. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  80. package/targets-stubs/claude-code/neocortex.md +7 -2
  81. package/targets-stubs/codex/AGENTS.md +4 -1
  82. package/targets-stubs/codex/neocortex.toml +4 -0
  83. package/targets-stubs/cursor/agent.md +2 -2
  84. package/targets-stubs/gemini-cli/agent.md +2 -2
  85. package/targets-stubs/opencode/neocortex-root.md +4 -1
  86. package/targets-stubs/opencode/neocortex.md +3 -0
  87. package/targets-stubs/vscode/neocortex.agent.md +2 -2
  88. package/packages/client/dist/subagent-approval-policy.js +0 -1
@@ -1,55 +1,60 @@
1
- import{createHash as Ce}from"node:crypto";import{existsSync as z,readFileSync as Q,unlinkSync as dt,writeFileSync as lt,mkdirSync as ut,statSync as pt}from"node:fs";import{join as U}from"node:path";import{homedir as se}from"node:os";import{LicenseClient as ft}from"../license/license-client.js";import{EncryptedCache as ye}from"../cache/encrypted-cache.js";import{NoOpCache as mt}from"../types/index.js";import{resolveClientPreFlightTrigger as gt,TierAwareClient as ht}from"../tier/tier-aware-client.js";import{loadSecureConfig as Et}from"../config/secure-config.js";import{DEFAULT_SERVER_URL as _t}from"../constants.js";import{detectFirstRunLocale as It,renderFirstRunMessage as St}from"../i18n/first-run.js";import{humanizeError as Ae,formatHumanizedError as Te,detectErrorLocale as ve}from"../errors/error-messages.js";import{degradeStateSnapshotForPayloadLimit as Ct,projectStateSnapshotForInvoke as yt}from"../state/project-state-snapshot.js";import{maybeRepairStateJsonBeforeInvoke as At,StateRepairHardStopError as Tt}from"../state/state-json-repair.js";import{bootstrapArchitectureMemory as vt}from"../memory/project-memory-writer.js";import{RUNNER_BOOTSTRAP_POLICY_REASON_CODES as wt,classifyRunnerBootstrapPolicyFromArgs as Rt}from"../continuity/runner-bootstrap-policy.js";import{RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES as bt,ensureRunnerSchedulerBootstrap as Nt}from"../runner/scheduler.js";import{CONTINUITY_INVOKE_WATCH_DEFAULT_LIMIT as we,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_IDLE_POLLS as Re,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_POLLS as be,CONTINUITY_INVOKE_WATCH_DEFAULT_POLL_INTERVAL_MS as Ne,openContinuityClientStateStore as Ot}from"../continuity/continuity-client-state-store.js";import{isLocalJobsConsoleArgs as Lt,runLocalJobsConsoleCommand as kt}from"../runner/local-console.js";import{detectPlatform as xt}from"../adapters/platform-detector.js";const Z=U(se(),".neocortex"),Oe=U(Z,"cache"),Le=U(Oe,"menu-cache.json"),ke=1440*60*1e3,xe=3e4,B="3.9.62",Pe=256*1024,je=Pe,De=.8,M="[REDACTED]",Pt=1e5,ee=2e3,jt=200,Dt=200,Ut=12,Mt=/(?:promptBody|workflow|workflowGraph|stepBody|privateUrl|rawLog|secret|credential|licenseKey|apiKey|internalRouting|serverOnly|proprietary|protected)/i,Wt=/(?:PRIVATE|PROTECTED|SERVER_ONLY)[-_\s]*(?:PROMPT|PROMPT_BODY|WORKFLOW|WORKFLOW_GRAPH|STEP_BODY|STEP|ROUTING)\s*[:=][^\n\r]*/gi,$t=/(?: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,ie=Math.floor(Pe*De),Ue=U(Z,".first-run-shown"),Bt="<!-- NEOCORTEX-MEMORY-START -->";function Ht(e){return/^\s*\*?init(?:\s|$)/i.test(e)}function Vt(e){const t=U(e,"NEOCORTEX.md"),n=z(t)?Q(t,"utf8"):void 0,r=n===void 0?["missing_canonical_memory"]:[n.includes(Bt)?void 0:"missing_managed_memory_block",n.length>18e3?"canonical_memory_over_budget":void 0,/api[-_ ]?key|license[-_ ]?key|password\s*[:=]|secret\s*[:=]/i.test(n)?"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=>z(U(e,p))),s=r.includes("possible_secret_shape_detected")?"low":r.length===0?"high":a.length>0?"medium":"low",c=vt(e);return{canonical:{path:"NEOCORTEX.md",exists:n!==void 0,incompleteReasons:r,confidence:s},permittedSources:{packageBuildFiles:c.repositoryMap?.find(p=>p.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: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 Ft(){try{if(z(Ue))return;const e=It(),t=St(e);process.stderr.write(t);try{ut(Z,{recursive:!0}),lt(Ue,new Date().toISOString(),"utf-8")}catch{}}catch{}}function ce(e,t=process.cwd()){return e&&e.trim().length>0?e:t}const Jt=new Set(["completed","aborted","cancelled"]),Gt=new Set(["watch-target-missing","watch-target-malformed","watch-target-ambiguous","watch-target-multiple"]),T=Object.freeze({COMPLETED:"invoke-watch-completed",CANCELLED:"invoke-watch-cancelled",IDLE_TIMEOUT:"invoke-watch-idle-timeout",MAX_POLLS:"invoke-watch-max-polls",STORE_UNAVAILABLE:"invoke-watch-store-unavailable",TARGET_UNRESOLVED:"invoke-watch-target-unresolved"}),w=Object.freeze({MISSING:"watch-target-missing",MALFORMED:"watch-target-malformed",AMBIGUOUS:"watch-target-ambiguous",CONFLICT:"watch-target-conflicting-evidence",SERVER_HELD_STREAM:"watch-target-server-held-stream-unsupported"}),h=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"}),Me=240,Kt=/(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 zt(e){return e.replace(/[\w.+-]+@[\w-]+\.[\w.-]+/g,M).replace(/(?:sk|pk|whsec|nxk)[-_](?:test|live|ant|proj|pro|free|enterprise)?[-_]?[A-Za-z0-9_-]{16,}/g,M).replace(/NX-[FPE]-[a-f0-9]{24}-[a-f0-9]{4}/g,M).replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,M).replace(Wt,M).replace($t,M)}function H(e,t){const n=zt(e);return n.length<=t?n:`${n.slice(0,t)}\u2026[TRUNCATED:${n.length-t}]`}function de(e,t=0,n=new WeakSet){if(t>Ut)return"[MAX_DEPTH]";if(e==null)return e;if(typeof e=="string")return H(e,ee);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")return;if(n.has(e))return"[CIRCULAR]";if(n.add(e),Array.isArray(e))return e.slice(0,jt).map(o=>de(o,t+1,n));const r={};for(const[o,a]of Object.entries(e).slice(0,Dt)){if(Mt.test(o)){r[o]=M;continue}const s=de(a,t+1,n);s!==void 0&&(r[o]=s)}return r}function le(e,t){return{instructions:H(e??"",Pt),metadata:t?de(t):void 0}}class L extends Error{code;constructor(t,n){super(n),this.name="InvokeCliInputError",this.code=t}}function Yt(e){return/^\s*\*?(?:arch-plan|ui-ux-review)(?:\s|$)/i.test(e)&&qt(e,"--project-evidence")}function qt(e,t){let n=null,r=-1,o=!1,a=!1;for(let s=0;s<=e.length;s+=1){const c=e[s];if(s===e.length||!n&&/\s/.test(c??"")){if(r>=0&&!o&&e.slice(r,s)===t)return!0;r=-1,o=!1,a=!1;continue}if(r<0&&(r=s),a){a=!1;continue}if(c==="\\"){a=!0;continue}(c==='"'||c==="'")&&(o=!0,n=n===c?null:n??c)}return!1}class We 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 ue=!1;function Xt(e){const t=[];if(!e||typeof e!="object")return t;const n=e,r=n.planning;if(r&&(r.current!==void 0||Array.isArray(r.history))&&t.push({code:"PLANNING_LEGACY",message:"legacy `planning.current`/`planning.history` detected (not read by v1 orchestrator)"}),Array.isArray(n.stories)&&t.push({code:"STORIES_AS_ARRAY",message:"`stories` is an Array (expected Object keyed by story ID)"}),n.epics&&typeof n.epics=="object"&&!Array.isArray(n.epics))for(const[a,s]of Object.entries(n.epics)){const c=s;if(c&&c.stories!==void 0&&!Array.isArray(c.stories)){t.push({code:"EPIC_STORIES_NOT_ARRAY",message:`epic "${a}" has non-array \`stories\` field (expected string[] of story IDs)`});break}}const o=n.epics&&typeof n.epics=="object"&&Object.keys(n.epics).length>0||n.stories&&typeof n.stories=="object"&&!Array.isArray(n.stories)&&Object.keys(n.stories).length>0||Array.isArray(n.stories)||r&&r.current!==void 0;return n.schema_version===void 0?o&&t.push({code:"SCHEMA_VERSION_MISSING",message:"`schema_version` field missing (expected: `schema_version: 1`)"}):n.schema_version!==1&&t.push({code:"SCHEMA_VERSION_OUTDATED",message:`schema_version=${String(n.schema_version)} (expected: 1)`}),t}function Qt(e){if(!(ue||e.length===0)){ue=!0;try{const t=e.map(n=>` - ${n.message}`).join(`
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(`
2
3
  `);process.stderr.write(`[Neocortex] state.json schema drift detected:
3
4
  ${t}
4
5
  Run \`neocortex *migrate-state --preview\` to inspect or \`neocortex *migrate-state --apply\` to migrate.
5
6
  See docs/arquitetura-software/STATE-JSON-SCHEMA.md for the schema contract.
6
- `)}catch{}}}function Nr(){ue=!1}function $e(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Zt(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function g(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function te(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function y(e){if(typeof e!="string")return;const t=e.trim();if(t)return t.replace(/[^a-z0-9_.:-]+/gi,"_").slice(0,120)}function pe(e,t){if(!g(e))return;const n={};for(const r of t){const o=e[r];if(typeof o=="boolean")n[r]=o;else if(typeof o=="number"&&Number.isFinite(o))n[r]=o;else if(typeof o=="string"){const a=y(o);a&&(n[r]=a)}}return Object.keys(n).length>0?n:void 0}function en(e){if(!g(e))return;const t={...y(e.active_epic_id??e.activeEpicId)?{active_epic_id:y(e.active_epic_id??e.activeEpicId)}:{},...y(e.active_story_id??e.activeStoryId)?{active_story_id:y(e.active_story_id??e.activeStoryId)}:{},...y(e.active_step_id??e.activeStepId)?{active_step_id:y(e.active_step_id??e.activeStepId)}:{},...y(e.session_id??e.sessionId)?{session_id:y(e.session_id??e.sessionId)}:{},...y(e.started_at??e.startedAt)?{started_at:y(e.started_at??e.startedAt)}:{}};return Object.keys(t).length>0?t:void 0}function tn(e){const t=pe(e.completionEvidence??e.completion_evidence,["prNumber","pr_number","prState","pr_state","pullRequestState","merged","mergedAt","issueNumber","issue_number","issueState","issue_state","closedAt"]),n=pe(e.issueCloseAudit??e.issue_close_audit,["schema_version","event","storyId","epicId","issueNumber","closedAt","publicSafe","rawLogStorage"]),r=pe(e.scopedCiEvidence??e.scoped_ci_evidence,["schema_version","storyId","epicId","prNumber","finalState","publicSafe","rawLogStorage"]);return{...typeof e.merged=="boolean"?{merged:e.merged}:{},...typeof e.safeToContinueYoloop=="boolean"?{safeToContinueYoloop:e.safeToContinueYoloop}:{},...typeof e.mergeBlockedRemotely=="boolean"?{mergeBlockedRemotely:e.mergeBlockedRemotely}:{},...y(e.physicalMergeStatus)?{physicalMergeStatus:y(e.physicalMergeStatus)}:{},...y(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)?{pr_state:y(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)}:{},...y(e.issue_state??e.issueState??e.workflow_issue_state)?{issue_state:y(e.issue_state??e.issueState??e.workflow_issue_state)}:{},...te(e.issue_number??e.issueNumber)?{issue_number:te(e.issue_number??e.issueNumber)}:{},...t?{completionEvidence:t}:{},...n?{issueCloseAudit:n}:{},...r?{scopedCiEvidence:r}:{}}}function nn(e){const t=U(e,".neocortex","state.json");if(!z(t))return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}};let n;try{const u=Q(t,"utf-8");n=JSON.parse(u)}catch{return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}try{const u=Xt(n);u.length>0&&Qt(u)}catch{}const r=n.config??n.project??{},o=n.stories??{},a={};for(const[u,d]of Object.entries(o))a[u]={id:d.id??u,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,...te(d.workflow_issue)?{workflow_issue:te(d.workflow_issue)}:{},...tn(d),depends_on:$e(d.depends_on),files_to_modify:Zt(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 s=n.epics??{},c={};for(const[u,d]of Object.entries(s))c[u]={id:d.id??u,title:d.title,status:d.status,stories:d.stories,total_stories:d.total_stories,completed_stories:d.completed_stories,depends_on:$e(d.depends_on)};const p=en(n.current_session??n.currentSession);return{schema_version:typeof n.schema_version=="number"?n.schema_version:void 0,config:{project_name:r.project_name??r.name??"unknown",default_branch:r.default_branch??"main",language:r.language??"pt-BR",yolo_mode:r.yolo_mode,user_name:r.user_name,worktree_base:r.worktree_base,max_parallel_stories:r.max_parallel_stories},stories:a,epics:c,...p?{current_session:p}:{}}}function Or(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 Be="neocortex:menu:cache";async function rn(e){try{const t=await e.get(Be);if(!t)return null;const n=JSON.parse(t);return n.version!==B||Date.now()-n.cachedAt>ke?null:n}catch{return null}}async function on(e,t,n){try{const r={instructions:t,metadata:n,cachedAt:Date.now(),version:B};await e.set(Be,JSON.stringify(r),ke),an()}catch{}}function an(){try{z(Le)&&dt(Le)}catch{}}function sn(){return Et()}async function cn(e,t){try{let n;if(t){const s=U(Z,"cache");n=new ye({cacheDir:s,passphrase:t})}else process.stderr.write(`[neocortex] Warning: No license key in config. Run "neocortex activate" to re-authenticate.
7
- `),n=new mt;const r=new ft({serverUrl:e,licenseKey:t??"",cacheProvider:n}),o=await r.getToken();if(!o)return null;const a=new ht({cacheProvider:n,licenseClient:r});return{token:o,client:r,tierClient:a}}catch{return null}}let He=!1;function Ve(e){return Ce("sha256").update(e).digest("hex")}function dn(){const e=Number(process.env.NEOCORTEX_INVOKE_CHUNK_BYTES??"49152");return Number.isFinite(e)&&e>=1024&&e<=98304?Math.floor(e):49152}function ln(e,t,n){return`args-${Ce("sha256").update("invoke-materialization:v1").update(e).update(String(t)).update(JSON.stringify(n)).digest("hex")}`}async function Fe(e,t,n,r){const o=await fetch(`${e}${t}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`,"X-Client-Version":B},body:JSON.stringify(n)}),a=await o.text().catch(()=>""),s=(()=>{try{return a?JSON.parse(a):{}}catch{return{}}})();if(!o.ok){const c=typeof s.error_code=="string"?s.error_code:`HTTP_${o.status}`,p=typeof s.message=="string"?s.message:"materialization upload failed";throw new Error(`${c}: ${p}`)}return s}async function un(e,t,n){const r=Buffer.from(t,"utf8"),o=dn(),a=[];for(let I=0,m=0;I<r.byteLength;I+=o,m++){const C=r.subarray(I,Math.min(I+o,r.byteLength));a.push({index:m,sha256:Ve(C),byteLength:C.byteLength})}const s=Ve(r),c=ln(s,r.byteLength,a),p=Number(process.env.NEOCORTEX_INVOKE_CHUNK_TTL_SECONDS??"900");for(const I of a){const m=I.index*o,C=r.subarray(m,m+I.byteLength);await Fe(e,"/api/v1/invoke/materialization/chunks",{manifestId:c,index:I.index,sha256:I.sha256,byteLength:I.byteLength,contentBase64:C.toString("base64"),ttlSeconds:p,idempotencyKey:`${c}:${I.index}:${I.sha256}`},n)}const d=(await Fe(e,"/api/v1/invoke/materialization/manifests",{manifestId:c,sha256:s,byteLength:r.byteLength,chunkCount:a.length,chunks:a,ttlSeconds:p,retry:{attempt:1,budget:3,idempotencyKey:c}},n)).argsRef;if(!d?.manifestId)throw new Error("MATERIALIZATION_RESPONSE_INVALID: missing argsRef");return{argsRef:d,chunks:a}}function V(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function pn(...e){const t=new Set,n=[];for(const r of e)for(const o of r??[]){const a=y(o);if(!(!a||t.has(a))&&(t.add(a),n.push(a),n.length>=16))return n}return n}function fn(e){const t=e.graphRetrieval;if(!g(t))return{accepted:!1,itemCount:0};const n=Array.isArray(t.items)?t.items.length:0;return{accepted:n>0||typeof t.retrievalId=="string"||t.accepted===!0,itemCount:n}}function fe(e,t=V(e),n=[],r={}){const o=e.stateSnapshot.scope,a=Object.keys(e.stateSnapshot.stories).length,s=Object.keys(e.stateSnapshot.epics).length,c=o?.kind??"full";return{schemaVersion:1,payloadBytes:t,limitBytes:r.limitBytes??je,warningThresholdBytes:r.warningThresholdBytes??ie,scope:{kind:c,...o?.projectionMode?{projectionMode:o.projectionMode}:{},commandId:o?.commandId??null,stateProjectionPolicy:o?.stateProjectionPolicy??null},includedStories:o?.includedStoryCount??a,omittedStories:o?.omittedStoryCount??0,includedEpics:o?.includedEpicCount??s,omittedEpics:o?.omittedEpicCount??0,graphRetrieval:fn(e.stateSnapshot),reasonCodes:pn(n,o?.reasonCodes),publicSafe:!0}}function mn(e){const t=g(e.budget)?e.budget:void 0,n=typeof t?.maxPayloadBytes=="number"&&Number.isFinite(t.maxPayloadBytes)?t.maxPayloadBytes:12*1024;return Math.max(1024,Math.min(n,12*1024))}function gn(e){return g(e)?{stableId:y(e.stableId)??"unknown",...g(e.source)?{source:e.source}:{},reasonCode:"budget_exceeded"}:{stableId:"unknown",reasonCode:"budget_exceeded"}}function Je(e){const t=Array.isArray(e)?e.filter(n=>typeof n=="string"):[];return t.includes("budget_exceeded")?t:[...t,"budget_exceeded"]}function hn(e){const t=e.graphRetrieval;if(!g(t)||!Array.isArray(t.items))return e;const n=mn(t);let r=[...t.items],o=Array.isArray(t.skipped)?[...t.skipped]:[],a=t;for(;Buffer.byteLength(JSON.stringify(a),"utf8")>n&&r.length>0;){const s=r.pop();o=[...o,gn(s)].slice(-32),a={...t,items:r,skipped:o,warnings:Je(t.warnings)}}return Buffer.byteLength(JSON.stringify(a),"utf8")>n&&(a={...t,query:typeof t.query=="string"?t.query.slice(0,240):t.query,items:[],skipped:[],warnings:Je(t.warnings)}),a===t?e:{...e,graphRetrieval:a}}function En(e,t={}){const n=t.limitBytes??je,r=t.warningThresholdBytes??Math.floor(n*De),o=V(e);if(o<=n)return{body:e,degraded:!1,telemetry:fe(e,o,["payload-within-limit"],{limitBytes:n,warningThresholdBytes:r})};let a={...e,stateSnapshot:Ct(e.stateSnapshot)},s=["payload-size-guardrail","state-degraded"],c=V(a);c>n&&(a={...a,stateSnapshot:hn(a.stateSnapshot)},s=[...s,"graph-retrieval-budget-enforced"],c=V(a));const p=fe(a,c,s,{limitBytes:n,warningThresholdBytes:r});if(c>n)throw new We(p);return{body:a,degraded:!0,telemetry:p}}function _n(e){return rt(e)??e.trim().split(/\s+/,1)[0]?.slice(0,80)??"(empty)"}function Ge(e){return e.args!==void 0?_n(e.args):`argsRef:${e.argsRef.manifestId.slice(0,80)}`}function In(e){const t=V(e);if(t<ie)return t;const n=fe(e,t,["payload-warning-threshold"]);return process.stderr.write(`[Neocortex] invoke payload near server limit: trigger=${Ge(e)} scope=${n.scope.kind} mode=${n.scope.projectionMode??n.scope.kind} payloadBytes=${n.payloadBytes} limit=${n.limitBytes} includedStories=${n.includedStories} omittedStories=${n.omittedStories} includedEpics=${n.includedEpics} omittedEpics=${n.omittedEpics} graphRetrieval.accepted=${n.graphRetrieval.accepted} graphRetrieval.itemCount=${n.graphRetrieval.itemCount} reasonCodes=${n.reasonCodes.join(",")||"none"}
8
- `),t}function Ke(e,t){process.stderr.write(`[Neocortex] invoke payload guardrail: trigger=${Ge(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"}
9
- `)}async function Sn(e){const t=Rt(e.args,{platformTarget:e.platformTarget,environment:e.environment??process.env});if(t.action==="skipped")return{shouldContinue:!0,attachToRequest:Cn(t),metadata:ze(t)};const n=e.bootstrapper??Nt;let r;try{r=await n({projectRoot:e.projectRoot,env:e.environment??process.env})}catch{r={ok:!1,attempted:!0,installed:!1,started:!1,cached:!1,projectKey:"unknown",reasonCodes:[bt.UNEXPECTED_ERROR],publicSummary:"runner scheduler bootstrap stopped unexpectedly.",publicSafe:!0}}const o=ze(t,r);if(r.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 Cn(e){return!e.reasonCodes.includes(wt.SKIPPED_NON_CONTINUITY_COMMAND)}function ze(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:N([...e.reasonCodes,...t?.reasonCodes??[]]),publicSummary:t?.publicSummary??e.publicSummary,publicSafe:!0}}function N(e){return Array.from(new Set(e.map(t=>t.slice(0,120))))}function ne(e,t,n){const r=Math.floor(e??t);return Number.isFinite(r)?Math.max(1,Math.min(n,r)):t}function re(e,t){const n=process.env[e];if(!n)return t;const r=Number(n);return Number.isFinite(r)?r:t}function E(e,t=Me){const n=typeof e=="string"&&e.trim().length>0?e.trim():"unknown",r=H(n,t),o=Kt.test(r)?M:r;return o.length<=t?o:`${o.slice(0,t)}\u2026[TRUNCATED:${o.length-t}]`}function me(e,t=Me){if(!(typeof e!="string"||e.trim().length===0))return E(e,t)}function ge(e,t,n,r){const o=me(e?.targetId??t,120),a=e?.selectorKind??(o?Ee(o):void 0),s=(e?.relatedJobIds??[]).map(c=>me(c,120)).filter(c=>!!c);return{schemaVersion:1,contractVersion:"continuity-v1",targetResolutionState:n,...a?{targetKind:a}:{},...o?{targetId:o}:{},...t?{targetJobId:E(t,120)}:{},...e?.jobId?{jobId:E(e.jobId,120)}:{},...e?.goalId?{goalId:E(e.goalId,120)}:{},...e?.loopId?{loopId:E(e.loopId,120)}:{},...s.length>0?{relatedJobIds:s}:{},relatedJobCount:s.length,reasonCodes:N(r.length>0?r:[h.OK]),publicSafe:!0}}function j(e,t,n,r,o=[]){const a=(e?.redactions?.length??0)>0,s=e?a?"unsafe":n&&r===0?"empty":"available":"unavailable",c=me(t[t.length-1]?.eventId,120),p=o.length>0?o:s==="unavailable"?[h.WATCH_SNAPSHOT_UNAVAILABLE]:s==="empty"?[h.WATCH_NO_SUMMARIES_YET]:[h.OK];return{schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:s,...e?.generatedAt?{generatedAt:E(e.generatedAt,80)}:{},renderedSummaryCount:r,...c?{latestEventId:c}:{},reasonCodes:N(p),publicSafe:!0}}function k(e,t,n,r,o=[],a){const s=r[r.length-1],c=n??s?.cursor,p=!!(c&&c!==t&&r.length>0),u=a??(p?"advanced":t||c?"unchanged":"not_started"),d=o.length>0?o:u==="advanced"?[h.WATCH_CURSOR_ADVANCED]:u==="unavailable"?[h.WATCH_EVIDENCE_UNAVAILABLE]:[h.WATCH_CURSOR_UNCHANGED];return{schemaVersion:1,contractVersion:"continuity-v1",cursorState:u,...e?{initialCursor:E(e,200)}:{},...t?{currentCursor:E(t,200)}:{},...c?{nextCursor:E(c,200)}:{},cursorAdvanced:p,...s?.eventId?{eventId:E(s.eventId,120)}:{},reasonCodes:N(d),publicSafe:!0}}function x(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:N([...e.reasonCodes??[],...t?.reasonCodes??[],...e.snapshotEvidence?.reasonCodes??[],...e.cursorEvidence?.reasonCodes??[]]),generatedAt:E(e.generatedAt??new Date().toISOString(),80),publicSafe:!0}}function yn(e){const t=e.targetKind&&e.targetId?`${e.targetKind}/${e.targetId}`:e.targetId??"[unresolved]",n=e.snapshotEvidence?.renderedSummaryCount??0,r=e.targetEvidence?.relatedJobCount??0,o=e.cursorEvidence?.cursorState??"unavailable",a=e.cursorEvidence?.currentCursor??"[none]",s=e.cursorEvidence?.nextCursor??"[none]",c=e.snapshotEvidence?.snapshotStatus??"not_requested",p=e.snapshotEvidence?.generatedAt??e.generatedAt;return[`[watch-status] ${e.targetResolutionState==="unresolved"||e.stopReason==="target_unresolved"?"unresolved-target":n===0&&(e.watchStatus==="waiting"||e.watchStatus==="active")?"no-new-summary":e.watchStatus==="stopped"?"stopped":"lifecycle"}`,`status=${e.watchStatus}`,`active=${e.active}`,`target=${t}`,`resolution=${e.targetResolutionState??"unavailable"}`,`relatedJobs=${r}`,`summaries=${n}`,`snapshot=${c}`,`generatedAt=${p}`,`cursor=${o}`,`current=${E(a,200)}`,`next=${E(s,200)}`,`advanced=${e.cursorEvidence?.cursorAdvanced??!1}`,`stop=${e.stopReason??"not_stopped"}`,`reasons=${e.reasonCodes.join(",")}`].join(" ")}function P(e,t,n){if(t==="json"){n.write(JSON.stringify(e)+`
10
- `);return}n.write(yn(e)+`
11
- `)}function An(e,t,n){return{continuityInvokeWatch:{schemaVersion:1,contractVersion:"continuity-v1",command:"invoke",operation:"watch",watchStatus:e.watchStatus,stopReason:e.stopReason??"not_stopped",targetResolutionState:e.targetResolutionState,targetKind:e.targetKind,targetId:e.targetId,snapshotStatus:e.snapshotEvidence?.snapshotStatus,snapshotGeneratedAt:e.snapshotEvidence?.generatedAt,renderedSummaryCount:e.snapshotEvidence?.renderedSummaryCount??t,cursorState:e.cursorEvidence?.cursorState,cursorAdvanced:e.cursorEvidence?.cursorAdvanced,summariesEmitted:t,polls:n,statusRecord:e,publicSafe:!0}}}function D(e,t,n,r){return{status:e,summariesEmitted:t,polls:n,reasonCodes:r.reasonCodes,watchStatus:r.watchStatus,stopReason:r.stopReason,targetEvidence:r.targetEvidence,snapshotEvidence:r.snapshotEvidence,cursorEvidence:r.cursorEvidence,statusRecord:r,metadata:An(r,t,n),publicSafe:!0}}function Tn(e){const t=e.reasonCode?` reason=${E(e.reasonCode,80)}`:"",n=e.goalId?` goal=${E(e.goalId,100)}`:"",r=e.loopId?` loop=${E(e.loopId,100)}`:"";return`[watch] ${E(e.createdAt,80)} event=${E(e.eventId,120)} job=${E(e.jobId,100)}${n}${r} execution=${E(e.executionId,120)}${t} -- ${E(e.publicSummary)}`}function vn(e){return{type:"processing_summary",source:"local_continuity_sqlite",eventId:E(e.eventId,120),jobId:E(e.jobId,100),...e.goalId?{goalId:E(e.goalId,100)}:{},...e.loopId?{loopId:E(e.loopId,100)}:{},executionId:E(e.executionId,120),...e.reasonCode?{reasonCode:E(e.reasonCode,80)}:{},createdAt:E(e.createdAt,80),publicSummary:E(e.publicSummary),publicSafe:!0}}function wn(e,t,n){if(t==="json"){n.write(JSON.stringify(vn(e))+`
12
- `);return}n.write(Tn(e)+`
13
- `)}function he(e){return Jt.has(e.status)}function Rn(e,t,n){if(t){const o=e.find(a=>a.jobId===t);return!!(o&&he(o))}return n<=0?!1:e.filter(o=>!he(o)).length===0}function bn(e,t,n,r){return n<r?!1:t?!e.some(o=>o.jobId===t&&!he(o)):e.length===0}function Nn(e,t){return t?.aborted?Promise.resolve():new Promise(n=>{const r=setTimeout(o,e);function o(){clearTimeout(r),t?.removeEventListener("abort",o),n()}t?.addEventListener("abort",o,{once:!0})})}function On(e){return e.includes(w.MALFORMED)?"malformed":e.includes(w.AMBIGUOUS)?"ambiguous":e.includes("watch-target-multiple")?"multiple":e.includes("watch-evidence-unsafe")?"unsafe":e.includes(w.MISSING)||e.includes(T.TARGET_UNRESOLVED)?"unresolved":"unavailable"}function Ye(e,t){const n=t?Y(t):void 0,r=N([...e,T.TARGET_UNRESOLVED,h.WATCH_TARGET_UNRESOLVED]),o=ge(n,n?.targetId,On(r),r),a=j({generatedAt:new Date().toISOString()},[],!1,0,[h.WATCH_TARGET_UNRESOLVED]),s=k(void 0,void 0,void 0,[],[h.WATCH_TARGET_UNRESOLVED],"unavailable");return x({watchStatus:"blocked",active:!1,targetEvidence:o,snapshotEvidence:a,cursorEvidence:s,stopReason:"target_unresolved",reasonCodes:r,generatedAt:a.generatedAt})}function Ln(e,t,n,r){const o=Ye(e,Xe(t));return P(o,n,r),D("target-unresolved",0,0,o)}async function kn(e){if(e.signal?.aborted){const b=ge(e.target??Y(e.targetJobId),e.targetJobId,e.target??e.targetJobId?"resolved":"unresolved",[T.CANCELLED]),_=j(void 0,[],!1,0),A=k(e.initialCursor,e.initialCursor,e.initialCursor,[],[T.CANCELLED],"unavailable"),X=x({watchStatus:"stopped",active:!1,targetEvidence:b,snapshotEvidence:_,cursorEvidence:A,stopReason:"cancelled",reasonCodes:[T.CANCELLED]});return D("cancelled",0,0,X)}const t=e.target??Y(e.targetJobId),n=e.targetJobId??t?.targetId,r=e.stdout??process.stdout;if(!t){const b=Ye([w.MISSING,T.TARGET_UNRESOLVED]);return P(b,e.format,r),D("target-unresolved",0,0,b)}const o=ne(e.limit??re("NEOCORTEX_INVOKE_WATCH_LIMIT",we),we,50),a=Math.max(50,ne(e.pollIntervalMs??re("NEOCORTEX_INVOKE_WATCH_POLL_INTERVAL_MS",Ne),Ne,6e4)),s=ne(e.maxIdlePolls??re("NEOCORTEX_INVOKE_WATCH_MAX_IDLE_POLLS",Re),Re,120),c=ne(e.maxPolls??re("NEOCORTEX_INVOKE_WATCH_MAX_POLLS",be),be,86400),p=e.sleep??Nn;let u=e.initialCursor,d=0,I=0,m=0;const C=ge(t,n,"resolved",[h.OK]),f={schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:"pending",renderedSummaryCount:0,reasonCodes:[h.WATCH_RENDER_PENDING],publicSafe:!0},J=k(e.initialCursor,u,u,[],e.initialCursor?[h.WATCH_CURSOR_UNCHANGED]:[h.WATCH_NO_SUMMARIES_YET],e.initialCursor?"unchanged":"not_started");P(x({watchStatus:"active",active:!0,targetEvidence:C,snapshotEvidence:f,cursorEvidence:J,stopReason:"not_stopped",reasonCodes:[h.OK]}),e.format,r);let i;try{i=await Ot({projectRoot:e.projectRoot})}catch{const b=j(void 0,[],!1,d,[h.WATCH_SNAPSHOT_UNAVAILABLE]),_=k(e.initialCursor,u,u,[],[h.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),A=x({watchStatus:"blocked",active:!1,targetEvidence:C,snapshotEvidence:b,cursorEvidence:_,stopReason:"unavailable_evidence",reasonCodes:[T.STORE_UNAVAILABLE]});return P(A,e.format,r),D("store-unavailable",d,m,A)}try{for(;!e.signal?.aborted&&m<c;){m+=1;const b=u,_=i.collectProcessingOutputSummaryCursor({...u?{cursor:u}:{},...t?{target:t}:{},...n?{jobId:n}:{},limit:o}),A=i.collectSnapshot({jobLimit:50,processingSummaryLimit:1}),X=A.jobs;if(_.summaries.length>0){for(const G of _.summaries)wn(G,e.format,r),d+=1;u=_.nextCursor??_.summaries[_.summaries.length-1]?.cursor??u,I=0}else u=_.nextCursor??u,I+=1;const it=j(A,_.summaries,!0,_.summaries.length),ct=k(e.initialCursor,b,u,_.summaries,_.summaries.length>0?[h.WATCH_CURSOR_ADVANCED]:[h.WATCH_NO_SUMMARIES_YET]);if(P(x({watchStatus:_.summaries.length>0?"polling":"waiting",active:!0,targetEvidence:C,snapshotEvidence:it,cursorEvidence:ct,stopReason:"not_stopped",reasonCodes:_.summaries.length>0?[h.WATCH_CURSOR_ADVANCED]:[h.WATCH_NO_SUMMARIES_YET],generatedAt:A.generatedAt}),e.format,r),!_.hasMore&&Rn(X,n,d)){const G=j(A,_.summaries,!1,d,[T.COMPLETED]),ae=k(e.initialCursor,b,u,_.summaries,[T.COMPLETED],"exhausted"),K=x({watchStatus:"stopped",active:!1,targetEvidence:C,snapshotEvidence:G,cursorEvidence:ae,stopReason:"not_stopped",reasonCodes:[T.COMPLETED],generatedAt:A.generatedAt});return P(K,e.format,r),D("completed",d,m,K)}if(!_.hasMore&&bn(X,n,I,s)){const G=j(A,_.summaries,!1,d,[h.WATCH_STOP_IDLE_LIMIT_REACHED]),ae=k(e.initialCursor,b,u,_.summaries,[h.WATCH_STOP_IDLE_LIMIT_REACHED],"exhausted"),K=x({watchStatus:"stopped",active:!1,targetEvidence:C,snapshotEvidence:G,cursorEvidence:ae,stopReason:"idle_limit_reached",reasonCodes:[T.IDLE_TIMEOUT,h.WATCH_STOP_IDLE_LIMIT_REACHED],generatedAt:A.generatedAt});return P(K,e.format,r),D("idle-timeout",d,m,K)}_.hasMore||await p(a,e.signal)}}catch{const b=j(void 0,[],!1,d,[h.WATCH_SNAPSHOT_UNAVAILABLE]),_=k(e.initialCursor,u,u,[],[h.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),A=x({watchStatus:"blocked",active:!1,targetEvidence:C,snapshotEvidence:b,cursorEvidence:_,stopReason:"unavailable_evidence",reasonCodes:[T.STORE_UNAVAILABLE]});return P(A,e.format,r),D("store-unavailable",d,m,A)}finally{i.close()}if(e.signal?.aborted){const b=j(void 0,[],!1,d,[T.CANCELLED]),_=k(e.initialCursor,u,u,[],[T.CANCELLED],"unavailable"),A=x({watchStatus:"stopped",active:!1,targetEvidence:C,snapshotEvidence:b,cursorEvidence:_,stopReason:"cancelled",reasonCodes:[T.CANCELLED]});return P(A,e.format,r),D("cancelled",d,m,A)}const l=j(void 0,[],!1,d,[h.WATCH_STOP_MAX_POLLS_REACHED]),S=k(e.initialCursor,u,u,[],[h.WATCH_STOP_MAX_POLLS_REACHED],"exhausted"),$=x({watchStatus:"stopped",active:!1,targetEvidence:C,snapshotEvidence:l,cursorEvidence:S,stopReason:"max_polls_reached",reasonCodes:[T.MAX_POLLS,h.WATCH_STOP_MAX_POLLS_REACHED]});return P($,e.format,r),D("max-polls",d,m,$)}function O(e){const t=e.trim().replace(/^@/,"").match(/^(job|goal|loop)-([JGL])(\d{3,})$/i);if(!t)return;const n=t[1].toLowerCase(),r=t[2].toUpperCase();if(!(n==="job"&&r!=="J"||n==="goal"&&r!=="G"||n==="loop"&&r!=="L"))return`${n}-${r}${t[3]}`}function Ee(e){if(e.startsWith("job-J"))return"job";if(e.startsWith("goal-G"))return"goal";if(e.startsWith("loop-L"))return"loop"}function qe(e){const t=[],n=/(?:^|[\s"'([,{])@?(job-[Jj]\d{3,}|goal-[Gg]\d{3,}|loop-[Ll]\d{3,})(?=$|[\s"')\]},.;:!?])/g;let r;for(;(r=n.exec(e))!==null;){const o=O(r[1]);o&&t.push(o)}return N(t)}function Xe(e){return qe(e)[0]}function Y(e){const t=e?O(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 _e(e){return N(e.filter(t=>typeof t=="string").map(t=>O(t)).filter(t=>!!t?.startsWith("job-J")))}function xn(e,t){const n=_e(t).filter(r=>r!==e.targetId&&r!==e.jobId);return n.length>0?{...e,relatedJobIds:n}:e}function Pn(e){if(!e)return;const t=g(e.target)?e.target:void 0,n=typeof e.selectorKind=="string"?e.selectorKind:typeof t?.selectorKind=="string"?t.selectorKind:void 0,r=typeof e.targetId=="string"?O(e.targetId):typeof t?.targetId=="string"?O(t.targetId):typeof e.targetJobId=="string"?O(e.targetJobId):void 0,o=Y(r);if(!o||n&&n!==o.selectorKind)return;const a=Array.isArray(e.relatedJobIds)?e.relatedJobIds:Array.isArray(t?.relatedJobIds)?t.relatedJobIds:void 0,s=_e([...a??[],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:O(e.jobId??t?.jobId)??o.jobId}:{},...typeof(e.goalId??t?.goalId)=="string"?{goalId:O(e.goalId??t?.goalId)??o.goalId}:{},...typeof(e.loopId??t?.loopId)=="string"?{loopId:O(e.loopId??t?.loopId)??o.loopId}:{},...s.length>0?{relatedJobIds:s}:{}}}function Qe(e){const t=e.trim().split(/\s+/).filter(Boolean),n=t[0]?.replace(/^\*/,"").toLowerCase(),r=t[1]?.replace(/^--/,"").toLowerCase();return(n==="jobs"||n==="job"||n==="continuity-jobs"||n==="61")&&r==="watch"}const v=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"}),jn=new Set(["create","start","resume"]),Dn=new Set(["create","resume","run-once"]);function Ie(e,t,n,r,o){return{schemaVersion:1,contractVersion:"continuity-v1",...n?{command:n}:{},...r?{operation:r}:{},active:e,...o?{watchToken:o}:{},reasonCodes:N(t),serverHeldStream:!1,allJobsPolling:!1,targetResolution:e?"required-after-dispatch":"inactive",publicSafe:!0}}function R(e,t=[],n,r){const o=t.length>0?t:[v.INACTIVE];return{args:e,watch:!1,reasonCodes:o,metadata:Ie(!1,o,n,r),publicSafe:!0}}function Un(e){const t=e.trim().split(/\s+/).filter(Boolean),n=t.slice(2).filter(a=>a==="--watch").length;if(n===0)return R(e,[],"jobs","watch");if(n!==1)return R(e,[v.AMBIGUOUS],"jobs","watch");const r=t.filter((a,s)=>s<2||a!=="--watch").join(" ");return Qe(r)?r.trim().split(/\s+/).filter(Boolean).slice(2).length!==1?R(e,[v.AMBIGUOUS],"jobs","watch"):Xe(r)?{args:r,watch:!0,reasonCodes:[v.ACTIVE],metadata:Ie(!0,[v.ACTIVE],"jobs","watch"),publicSafe:!0}:R(e,[v.TARGET_INVALID],"jobs","watch"):R(e,[v.UNSUPPORTED],"jobs","watch")}function Mn(e){const t=[];let n=!1,r=0;for(;r<e.length;){for(;r<e.length&&/\s/.test(e[r]);)r+=1;if(r>=e.length)break;const o=r;let a="",s=!1,c=null;for(;r<e.length;){const p=e[r];if(c){if(p===c){s=!0,c=null,r+=1;continue}if(p==="\\"&&r+1<e.length){a+=e[r+1],r+=2;continue}a+=p,r+=1;continue}if(/\s/.test(p))break;if(p==='"'||p==="'"){s=!0,c=p,r+=1;continue}a+=p,r+=1}c&&(n=!0),t.push({value:a,start:o,end:r,quoted:s})}return{tokens:t,malformed:n}}function Wn(e){if(!e||e.quoted)return;const t=e.value.replace(/^\*/,"").toLowerCase();return t==="goal"||t==="loop"?t:void 0}function $n(e,t){if(!e||e==="jobs"||!t||t.quoted)return;const n=t.value.toLowerCase();return(e==="goal"?jn:Dn).has(n)?n:void 0}function Bn(e){return!e.quoted&&e.value!=="--watch"&&e.value.toLowerCase().startsWith("--watch")}function Hn(e){const{tokens:t,malformed:n}=Mn(e),r=Wn(t[0]),o=$n(r,t[1]);if(n)return R(e,[v.MALFORMED],r,o);const a=t.filter(m=>m.value==="--watch"&&!m.quoted),s=t.filter(m=>m.value==="--watch"&&m.quoted),c=t.filter(Bn);if(!(a.length>0||s.length>0||c.length>0))return R(e,[],r,o);if(a.length>1)return R(e,[v.DUPLICATE],r,o);if(a.length===1&&(s.length>0||c.length>0))return R(e,[v.AMBIGUOUS],r,o);if(s.length>0)return R(e,[v.QUOTED],r,o);if(c.length>0)return R(e,[v.MALFORMED],r,o);const u=a[0];if(!u)return R(e,[],r,o);if(t[t.length-1]!==u)return R(e,[v.NON_FINAL],r,o);if(!r||!o)return R(e,[v.UNRESOLVED],r,o);const d=`${e.slice(0,u.start)}${e.slice(u.end)}`.trim(),I={literal:"--watch",position:"final",start:u.start,end:u.end,quoted:!1,publicSafe:!0};return{args:d,watch:!0,reasonCodes:[v.ACTIVE],metadata:Ie(!0,[v.ACTIVE],r,o,I),publicSafe:!0}}function Vn(e){return Qe(e)?Un(e):Hn(e)}function Fn(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&Gt.has(t)):[]}function F(e){return{disabled:!0,reasonCodes:N(e.length>0?e:[w.MISSING])}}function Se(e,t,n=[],r){const o=Y(t);if(o)return{source:e,target:xn(o,n),targetJobId:o.targetId,...r?{initialCursor:r}:{},serverHeldStream:!1}}function Jn(e){const t=new Map;for(const n of e){const r=`${n.target.selectorKind}:${n.target.targetId}`,o=t.get(r);if(!o){t.set(r,n);continue}const a=N([...o.target.relatedJobIds??[],...n.target.relatedJobIds??[]]);t.set(r,{...o,target:a.length>0?{...o.target,relatedJobIds:a}:o.target,initialCursor:o.initialCursor??n.initialCursor})}return Array.from(t.values())}function W(e,t,n,r){return{source:e,hasEvidence:t,candidates:Jn(n.filter(o=>!!o)),...r&&r.length>0?{disabledReasonCodes:N(r)}:{}}}function Gn(e,t){return e.target.selectorKind===t.target.selectorKind&&e.target.targetId===t.target.targetId}function q(e,t){const n=N(e.filter(r=>typeof r=="string").map(r=>O(r)).filter(r=>!!r));if(t){const r=n.find(o=>Ee(o)===t);if(r)return r}return n[0]}function oe(e,t){return N(e.filter(n=>typeof n=="string").map(n=>O(n)).filter(n=>!!n)).find(n=>Ee(n)===t)}function Kn(e){const t=g(e?.continuity)?e.continuity:void 0,n=g(t?.jobs)?t.jobs:void 0,r=g(n?.watcher)?n.watcher:void 0,o=Fn(r?.reasonCodes??n?.reasonCodes);if(!r)return W("watcher-metadata",o.length>0,[],o);if(r.active===!1||o.length>0)return W("watcher-metadata",!0,[],o.length>0?o:[w.MALFORMED]);if(r.serverHeldStream!==!1)return W("watcher-metadata",!0,[],[w.SERVER_HELD_STREAM]);const a=Pn(r);if(!a)return W("watcher-metadata",!0,[],[w.MISSING]);const s=typeof r.initialCursor=="string"?r.initialCursor:void 0;return W("watcher-metadata",!0,[{source:"watcher-metadata",target:a,targetJobId:a.targetId,...s?{initialCursor:s}:{},serverHeldStream:!1}])}function Ze(e,t){const n=g(e.loopJobPlan)?e.loopJobPlan:void 0,r=g(n?.metadata)?n.metadata:void 0,o=g(e.metadata)?e.metadata:void 0,s=(t==="goal"?q([e.goalId,e.targetGoalId,e.campaignId,e.jobId,e.targetJobId,o?.goalId,o?.campaignId,o?.jobId],"goal"):q([e.loopId,e.targetLoopId,e.jobId,e.targetJobId,o?.loopId,o?.jobId,r?.loopId,r?.jobId],"loop"))??q([e.jobId,e.targetJobId,o?.jobId,r?.jobId]);return Se("goal-loop-continuity-metadata",s,[e.jobId,e.targetJobId,o?.jobId,r?.jobId])}function zn(e){const t=g(e?.continuity)?e.continuity:void 0,n=g(t?.goal)?t.goal:void 0,r=g(t?.loop)?t.loop:void 0,o=[n?Ze(n,"goal"):void 0,r?Ze(r,"loop"):void 0],a=!!(n||r);return W("goal-loop-continuity-metadata",a,o,a&&o.every(s=>!s)?[w.MISSING]:void 0)}function Yn(e){return Array.isArray(e)?e.filter(g):g(e)?Array.isArray(e.operationLogs)?e.operationLogs.filter(g):g(e.operationLog)?[e.operationLog]:Array.isArray(e.operations)?[e]:[]:[]}function et(e,t){const n=g(t.metadata)?t.metadata:void 0,r=oe([t.goalId,t.targetGoalId,t.campaignId,n?.goalId,n?.campaignId,t.jobId,n?.jobId],"goal"),o=oe([t.loopId,t.targetLoopId,n?.loopId,t.jobId,n?.jobId],"loop"),a=q([t.jobId,t.targetJobId,n?.jobId],"job"),s=r??o??a;if(!s)return;const c=e.get(s)??{targetId:s,relatedJobIds:[]};c.relatedJobIds.push(..._e([a,t.jobId,t.targetJobId,n?.jobId])),e.set(s,c)}function qn(e){const t=g(e.metadata)?e.metadata:void 0;return!!(oe([e.goalId,e.targetGoalId,e.campaignId,t?.goalId,t?.campaignId,e.jobId,t?.jobId],"goal")??oe([e.loopId,e.targetLoopId,t?.loopId,e.jobId,t?.jobId],"loop"))}function Xn(e){const t=g(e.metadata)?e.metadata:void 0;return!!q([e.goalId,e.targetGoalId,e.campaignId,e.loopId,e.targetLoopId,e.jobId,e.targetJobId,t?.goalId,t?.campaignId,t?.loopId,t?.jobId])}function tt(e,t){const n=[];for(const s of["metadata","job","event","receipt","processingOutputSummary"]){const c=t[s];g(c)&&n.push(c)}const r=g(t.event)?t.event:void 0;g(r?.metadata)&&n.push(r.metadata),g(r?.processingOutputSummary)&&n.push(r.processingOutputSummary);const o=g(t.receipt)?t.receipt:void 0;g(o?.metadata)&&n.push(o.metadata);const a=n.some(Xn);for(const s of n)et(e,s);(!a||qn(t))&&et(e,t)}function Qn(e){const t=Yn(e?.continuityStateUpdate),n=new Map;for(const o of t){tt(n,o);const a=Array.isArray(o.operations)?o.operations.filter(g):[];for(const s of a)tt(n,s)}const r=Array.from(n.values()).map(o=>Se("continuity-state-update-operation-log",o.targetId,o.relatedJobIds));return W("continuity-state-update-operation-log",t.length>0,r,t.length>0&&r.every(o=>!o)?[w.MISSING]:void 0)}function Zn(e){const t=qe(e);return W("explicit-args",t.length>0,t.map(n=>Se("explicit-args",n)))}function er(e,t){const n=[Kn(e),zn(e),Qn(e),Zn(t)];for(let r=0;r<n.length;r+=1){const o=n[r];if(!o.hasEvidence)continue;if(o.disabledReasonCodes&&o.disabledReasonCodes.length>0)return F(o.disabledReasonCodes);if(o.candidates.length!==1)return F([o.candidates.length>1?w.AMBIGUOUS:w.MISSING]);const a=o.candidates[0];for(const s of n.slice(r+1)){if(!s.hasEvidence)continue;if(s.disabledReasonCodes&&s.disabledReasonCodes.length>0)return F(s.disabledReasonCodes);if(s.candidates.length>1)return F([w.AMBIGUOUS]);const c=s.candidates[0];if(c&&!Gn(a,c))return F([w.CONFLICT])}return{target:a.target,targetJobId:a.targetJobId,...a.initialCursor?{initialCursor:a.initialCursor}:{},source:a.source,serverHeldStream:!1}}return F([w.MISSING])}async function nt(e,t,n){const r=`${e}/api/v1/invoke`,o=new AbortController,a=setTimeout(()=>o.abort(),xe);try{const s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`,"X-Client-Version":B},body:JSON.stringify(t),signal:o.signal});if(clearTimeout(a),!s.ok){const u=await s.text().catch(()=>"Unknown error");let d;try{d=JSON.parse(u)}catch{}return{ok:!1,status:s.status,error:d?`${d.error_code??"ERROR"}: ${d.message??u}`:`HTTP ${s.status}: ${u}`,errorBody:d}}const c=await s.json(),p=s.headers.get("X-Client-Version-Warning");return p&&!He&&(He=!0,process.stderr.write(`
14
- [Neocortex] ${p}
15
-
16
- `)),{ok:!0,status:s.status,data:c}}catch(s){clearTimeout(a);const c=s instanceof Error?s.message:String(s);return{ok:!1,status:0,error:c.includes("abort")?`Request timeout after ${xe/1e3}s`:`Network error: ${c}`}}}async function tr(e){const t=ce(e.projectRoot),n=xt({cwd:t,env:e.environment??process.env,targetFlag:e.platformTarget}).targetId;Ft();const r=sn(),o=(e.serverUrl??r?.serverUrl??_t).replace(/\/+$/,"");try{At(t,{args:e.args})}catch(i){if(i instanceof Tt)return process.stderr.write(`${i.message}
17
- `),{success:!1,error:i.message,exitCode:1};const l=i instanceof Error?i.message:String(i);return process.stderr.write(`[Neocortex] state.json repair stopped unexpectedly: ${l}. No request was sent; inspect .neocortex/state.json and rerun.
18
- `),{success:!1,error:l,exitCode:1}}const a=nn(t);try{const{maybeAutoResolveYoloopArgs:i}=await import("../yoloop/invoke-hooks.js"),l={args:e.args,projectRoot:t,logger:{info:S=>process.stderr.write(`${S}
19
- `),warn:S=>process.stderr.write(`${S}
20
- `)}};i(l),l.args!==e.args&&(e={...e,args:l.args})}catch(i){const l=i instanceof Error?i.message:String(i);process.stderr.write(`[Neocortex] Auto-resolve hook (P121.05) failed: ${l}. Proceeding with raw args.
21
- `)}try{const{readYoloopForRequest:i}=await import("../yoloop/invoke-hooks.js"),l=await i(e.args,t);l&&(a.yoloop=l)}catch{}try{const{readContinuityForRequest:i}=await import("../continuity/invoke-hooks.js"),l=await i(e.args,t);l&&(a.continuity=l)}catch(i){const l=i instanceof Error?i.message:String(i);process.stderr.write(`[Neocortex] continuity snapshot hook failed: ${l}. Proceeding without continuity state.
22
- `)}try{const{maybeRunDiscoveryHook:i}=await import("../yoloop/invoke-hooks.js");await i({args:e.args,projectRoot:t,stateSnapshot:a,featureFlag:process.env.YOLOOP_AUTO_DISCOVERY!=="off",logger:{warn:l=>{console.warn(l)},info:l=>{console.error(l)}}})}catch(i){const l=i instanceof Error?i.message:String(i);process.stderr.write(`[Neocortex] discovery hook failed: ${l}. Proceeding without enrichment.
23
- `)}try{const{readArchitecturePolicy:i}=await import("../policy/architecture-policy.js"),l=await i(t);l&&(a.architecture_policy=l)}catch(i){const l=i instanceof Error?i.message:String(i);console.warn(`[Neocortex] architecture-policy hook failed: ${l}. Proceeding without policy.`)}try{const i=/^(1|true|on|yes)$/i.test(process.env.NEOCORTEX_GRAPH_RETRIEVAL??""),{maybeRunGraphRetrievalHook:l}=await import("../yoloop/invoke-hooks.js"),S=await l({args:e.args,projectRoot:t,featureFlag:i,logger:{warn:$=>process.stderr.write(`${$}
24
- `)}});S.applied&&S.metadata&&(a.graphRetrieval=S.metadata)}catch(i){const l=i instanceof Error?i.message:String(i);process.stderr.write(`[Neocortex] graph retrieval hook failed: ${l}. Proceeding without enrichment.
25
- `)}try{if(Yt(e.args)){const{collectProjectEvidence:i}=await import("../evidence/collector.js"),l=i({projectRoot:t});(l.evidence.length>0||l.exclusions.length>0)&&(a.projectEvidence=l)}}catch(i){const l=i instanceof Error?i.message:String(i);process.stderr.write(`[Neocortex] project evidence collection failed: ${l}. Proceeding without local project evidence.
26
- `)}try{const{readAndConsumeCheckpoint:i}=await import("../checkpoint/index.js"),l=await i(t);l&&(a.implementCheckpoint=l)}catch(i){const l=i instanceof Error?i.message:String(i);process.stderr.write(`[Neocortex] checkpoint hook failed: ${l}. Proceeding without checkpoint.
27
- `)}const s=r?.licenseKey?new ye({cacheDir:Oe,passphrase:r.licenseKey}):null,c=e.args.trim();if(Ht(c))try{a.projectMemoryBootstrap=Vt(t)}catch(i){const l=i instanceof Error?i.message:String(i);process.stderr.write(`[Neocortex] project-memory bootstrap diagnosis failed: ${l}. Proceeding without local memory snapshot.
28
- `)}if(!c&&s){const i=await rn(s);if(i)return{success:!0,instructions:i.instructions,metadata:i.metadata,exitCode:0}}const p=await cn(o,r?.licenseKey);if(!p){const i=r&&!r.licenseKey?" This may be caused by a machine fingerprint change (e.g., hardware or hostname change).":"";try{const l=ve(),S=Ae("NOT_CONFIGURED",l);S&&process.stderr.write(Te(S,l))}catch{}return{success:!1,error:`Not authenticated.${i} Visit https://neocortex.sh/portal/login to get your license key, then run: neocortex activate YOUR-LICENSE-KEY`,exitCode:2}}const u=rt(c);if(u)try{const i=await p.tierClient.preFlightCheck(u);if(!i.allowed)return process.stderr.write(`[neocortex] ${i.message}
29
- `),{success:!1,error:i.message??"Trigger not available on your plan",exitCode:1}}catch{}const d=await Sn({args:c,projectRoot:t,platformTarget:n,environment:e.environment??process.env,bootstrapper:e.runnerBootstrapper});if(d.attachToRequest&&(a.runnerBootstrap=d.metadata),d.warning&&process.stderr.write(`[Neocortex] ${d.warning}
30
- `),!d.shouldContinue)return d.error&&process.stderr.write(`[Neocortex] ${d.error}
31
- `),{success:!1,error:d.error??"Runner auto-bootstrap required but failed.",errorCode:d.errorCode,exitCode:d.exitCode??1};const I=yt(c,a);let m={args:c,projectRoot:t.replace(se(),"~"),stateSnapshot:I,platformTarget:n};const C=V(m);if(e.inputSource&&e.inputSource!=="args"&&C>=ie)try{m={argsRef:(await un(o,c,p.token)).argsRef,projectRoot:t.replace(se(),"~"),stateSnapshot:I,platformTarget:n}}catch(i){return{success:!1,error:`INVOKE_MATERIALIZATION_FAILED: ${i instanceof Error?i.message:String(i)}`,errorCode:"INVOKE_MATERIALIZATION_FAILED",exitCode:1}}try{const i=En(m);m=i.body,i.degraded?Ke(m,i.telemetry):In(m)}catch(i){if(i instanceof We)return Ke(m,i.telemetry),process.stderr.write(`[Neocortex] ${i.message}
32
- `),{success:!1,error:i.message,errorCode:i.code,metadata:{invokePayload:i.telemetry},exitCode:1};throw i}let f=await nt(o,m,p.token);if(!f.ok&&f.status===401){const i=f.errorBody?.fallback_action;if(i==="refresh_token"||i==="re_authenticate"){const l=await p.client.forceRefresh();l&&(f=await nt(o,m,l))}}if(!f.ok&&f.status===426){const i=f.errorBody,l=i?.upgrade_command??"npm install -g @ornexus/neocortex@latest",S=i?.min_version??"unknown";return process.stderr.write(`
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(`
33
38
  `),process.stderr.write(`==================================================
34
39
  `),process.stderr.write(` UPGRADE REQUIRED
35
40
  `),process.stderr.write(`==================================================
36
41
  `),process.stderr.write(`
37
- Your Neocortex version (${B}) is no longer supported.
38
- `),process.stderr.write(` Minimum required: ${S}
42
+ Your Neocortex version (${ee}) is no longer supported.
43
+ `),process.stderr.write(` Minimum required: ${b}
39
44
 
40
45
  `),process.stderr.write(` Run this command to update:
41
46
 
42
- `),process.stderr.write(` ${l}
47
+ `),process.stderr.write(` ${u}
43
48
 
44
49
  `),process.stderr.write(` After updating, re-run your command.
45
50
  `),process.stderr.write(`==================================================
46
51
 
47
- `),{success:!1,error:`UPGRADE_REQUIRED: Client version ${B} is below minimum ${S}. Run: ${l}`,exitCode:3}}if(!f.ok||!f.data){const i=f.status===401?2:(f.status===429||f.status>=500,1);try{const l=f.errorBody?.error_code??(f.status===429?"RATE_LIMITED":f.status>=500?"SERVER_ERROR":void 0);if(l){const S=ve(),$=Ae(l,S);$&&process.stderr.write(Te($,S))}}catch{}return{success:!1,error:H(f.error??"Unknown error from server",ee),exitCode:i}}if(!c&&f.data.metadata?.mode==="menu"&&s&&on(s,f.data.instructions,f.data.metadata).catch(()=>{}),f.data.metadata&&p.tierClient.updateQuotaFromResponse(f.data.metadata).catch(()=>{}),f.data.metadata?.mode==="error"&&f.data.metadata?.errorCode==="CLIENT_UPGRADE_REQUIRED")return process.stderr.write(`
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(`
48
53
  `),process.stderr.write(`==================================================
49
54
  `),process.stderr.write(` YOLOOP CLIENT UPGRADE REQUIRED
50
55
  `),process.stderr.write(`==================================================
51
56
  `),process.stderr.write(`
52
- Your Neocortex client version (${B}) does not
57
+ Your Neocortex client version (${ee}) does not
53
58
  `),process.stderr.write(` support client-side yoloop state persistence.
54
59
 
55
60
  `),process.stderr.write(` Run this command to upgrade:
@@ -59,12 +64,12 @@ ${t}
59
64
  `),process.stderr.write(` After upgrading, re-run your yoloop command.
60
65
  `),process.stderr.write(`==================================================
61
66
 
62
- `),{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(f.data.metadata?.yoloopStateUpdate)try{const{persistYoloopFromResponse:i}=await import("../yoloop/invoke-hooks.js");await i(f.data.metadata,t)}catch{}if(f.data.metadata?.continuityStateUpdate)try{const{persistContinuityFromResponse:i}=await import("../continuity/invoke-hooks.js"),l=await i(f.data.metadata,t);if(!l.ok){const S=l.reasonCodes.join(",");return process.stderr.write(`[Neocortex] continuity persistence failed: ${S}. No continuity mutation was committed.
63
- `),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${S}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}}catch(i){const l=i instanceof Error?i.message:String(i);return process.stderr.write(`[Neocortex] continuity persistence hook failed: ${l}. No continuity mutation was committed.
64
- `),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${H(l,ee)}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}if(f.data.metadata?.stateMutated===!0)try{const{persistMigratedStateFromResponse:i}=await import("../yoloop/invoke-hooks.js");await i(f.data.metadata,t)}catch{}if(f.data.metadata?.tier_changed){const i=f.data.metadata.current_tier;try{await p.client.forceRefresh()?(await p.tierClient.invalidateTierCache(),process.stderr.write(`[Neocortex] Token atualizado automaticamente para tier ${i}
65
- `)):process.stderr.write(`[Neocortex] Seu tier foi atualizado para ${i}! Execute "neocortex activate" para obter um token atualizado.
66
- `)}catch{process.stderr.write(`[Neocortex] Seu tier foi atualizado para ${i}! Execute "neocortex activate" para obter um token atualizado.
67
- `)}}const J=le(f.data.instructions,f.data.metadata);return{success:!0,instructions:J.instructions,metadata:J.metadata,exitCode:0}}function rt(e){const[t]=e.trim().split(/\s+/,1);return t?/^@?epic-[a-z0-9][a-z0-9._-]*$/i.test(t)?"epic":gt(t):null}const ot="Provide exactly one invoke input source: --args <string>, --stdin, or --args-file <path>.",nr=`
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=`
68
73
  neocortex-client invoke - Send orchestration request to server
69
74
 
70
75
  Usage:
@@ -86,6 +91,7 @@ Options:
86
91
  --watch Keep the foreground client polling local continuity summaries
87
92
  --server-url <url> Server URL override
88
93
  --platform-target <id> Explicit platform target override (default: runtime detection; unknown on no match)
94
+ --strict-read-only Request exact signed strict-read-only-v1 execution (registry-gated)
89
95
 
90
96
  Invocation payload boundary:
91
97
  Select only the explicit user-intended Neocortex command and arguments after
@@ -132,11 +138,12 @@ Safety:
132
138
  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.
133
139
  Jobs, goal and loop watch use serverHeldStream=false and foreground local SQLite polling of public processing summaries only.
134
140
  Unresolved targets disable polling with public reason codes; there is no all-jobs fallback.
135
- `.trim();function rr(e){return e.includes("--help")||e.includes("-h")||e.includes("help")}function at(e){return new L("INVOKE_INPUT_VALUE_MISSING",`${e} requires a value. ${ot}`)}function or(e){try{if(!pt(e).isFile())throw new L("INVOKE_ARGS_FILE_NOT_FILE","--args-file must point to a readable UTF-8 text file.");return Q(e,"utf8")}catch(t){throw t instanceof L?t:new L("INVOKE_ARGS_FILE_READ_FAILED","--args-file could not be read as UTF-8 text. Check the path and permissions.")}}function ar(){try{if(process.stdin.isTTY)throw new L("INVOKE_STDIN_EMPTY","--stdin requires piped UTF-8 text, for example: neocortex-client invoke --stdin < synthetic.story.md");return Q(0,"utf8")}catch(e){throw e instanceof L?e:new L("INVOKE_STDIN_READ_FAILED","--stdin could not be read as UTF-8 text. Pipe command text into stdin and retry.")}}function sr(e,t={}){let n,r=!1,o,a,s="plain",c=!1,p,u;for(let f=0;f<e.length;f++)switch(e[f]){case"--args":{const i=e[++f];if(i===void 0)throw at("--args");n=i;break}case"--stdin":r=!0;break;case"--args-file":{const i=e[++f];if(i===void 0)throw at("--args-file");o=i;break}case"--project-root":a=e[++f];break;case"--format":s=e[++f]??"plain";break;case"--watch":c=!0;break;case"--server-url":p=e[++f];break;case"--platform-target":u=e[++f];break}const d=[n!==void 0?"args":void 0,r?"stdin":void 0,o!==void 0?"args-file":void 0].filter(f=>f!==void 0);if(d.length===0)throw new L("INVOKE_INPUT_SOURCE_MISSING",ot);if(d.length>1)throw new L("INVOKE_INPUT_SOURCE_CONFLICT",`Choose only one invoke input source; received ${d.join(", ")}.`);const I=d[0],m=I==="args"?n:I==="stdin"?(t.readStdin??ar)():(t.readArgsFile??or)(o),C=I==="args"?Vn(m):R(m);return{args:C.args,inputSource:I,projectRoot:a,format:s,watch:c||C.watch,commandLevelWatch:C.metadata,serverUrl:p,platformTarget:u}}function st(e,t){return t?.active?{...e??{},commandLevelWatch:t,serverHeldStream:!1}:e}function ir(e,t,n=process.stdout,r=process.stderr){if(t.format==="json"){const s=le(e.instructions,e.metadata),c=st(s.metadata,t.commandLevelWatch);if(t.watch){n.write(JSON.stringify({type:"invoke_result",instructions:s.instructions,metadata:c,publicSafe:!0})+`
136
- `);return}n.write(JSON.stringify({instructions:s.instructions,metadata:c})+`
137
- `);return}const o=le(e.instructions,e.metadata),a=st(o.metadata,t.commandLevelWatch);n.write(o.instructions+`
138
- `),a&&r.write(JSON.stringify(a)+`
139
- `)}function cr(e){const t=()=>e.abort();return process.once("SIGINT",t),process.once("SIGTERM",t),()=>{process.removeListener("SIGINT",t),process.removeListener("SIGTERM",t)}}async function Lr(e){if(rr(e))return process.stdout.write(`${nr}
140
- `),0;let t;try{t=sr(e)}catch(r){if(r instanceof L)return process.stderr.write(JSON.stringify({error_code:r.code,message:r.message})+`
141
- `),1;throw r}if(Lt(t.args))return(await kt({args:t.args,projectRoot:ce(t.projectRoot),format:t.format,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})).exitCode;const n=await tr({args:t.args,inputSource:t.inputSource,watch:t.watch,projectRoot:t.projectRoot,format:t.format,serverUrl:t.serverUrl,platformTarget:t.platformTarget});if(!n.success)return process.stderr.write(JSON.stringify({error_code:n.errorCode??(n.exitCode===2?"NOT_CONFIGURED":"INVOKE_ERROR"),message:H(n.error??"",ee)})+`
142
- `),n.exitCode;if(ir(n,t),t.watch){const r=new AbortController,o=cr(r);try{const a=er(n.metadata,t.args);a.disabled?Ln(a.reasonCodes??[T.TARGET_UNRESOLVED],t.args,t.format,process.stdout):await kn({projectRoot:ce(t.projectRoot),format:t.format,...a,signal:r.signal})}finally{o()}}return 0}export{nr as INVOKE_HELP_TEXT,je as INVOKE_PAYLOAD_LIMIT_BYTES,ie as INVOKE_PAYLOAD_WARNING_THRESHOLD_BYTES,L as InvokeCliInputError,We as InvokePayloadTooLargeError,Nr as __resetSchemaDriftWarnedForTests,Vt as collectInitProjectMemoryBootstrapSnapshot,nn as collectStateSnapshot,V as computeInvokeRequestBodySizeBytes,Or as createFullStateSnapshotScope,fe as createInvokePayloadTelemetry,Xt as detectStateSchemaDrift,rt as extractPreFlightTrigger,En as guardInvokeRequestBodySize,tr as invoke,Lr as invokeCliHandler,Ht as isInitTrigger,In as maybeEmitInvokePayloadSizeWarning,Sn as maybeRunInvokeRunnerAutoBootstrap,sr as parseInvokeCliOptions,Vn as resolveInvokeCommandLevelWatch,ce as resolveInvokeProjectRoot,er as resolveInvokeWatchTarget,le as sanitizeInvokeCliOutput,Yt as shouldCollectProjectEvidenceForInvoke,kn as watchContinuityProcessingSummaries,ir as writeInvokeCliSuccessOutput};
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};
@@ -27,12 +27,16 @@ export interface SecureConfig {
27
27
  * Encrypt a license key using the machine fingerprint as passphrase.
28
28
  * Returns the encrypted envelope string.
29
29
  */
30
- export declare function encryptLicenseKey(licenseKey: string): string;
30
+ export declare function encryptLicenseKey(licenseKey: string, options?: {
31
+ readonly strictReadOnly?: boolean;
32
+ }): string;
31
33
  /**
32
34
  * Decrypt a license key using the machine fingerprint as passphrase.
33
35
  * Returns the plaintext key or null if decryption fails (hardware changed).
34
36
  */
35
- export declare function decryptLicenseKey(encryptedKey: string): string | null;
37
+ export declare function decryptLicenseKey(encryptedKey: string, options?: {
38
+ readonly strictReadOnly?: boolean;
39
+ }): string | null;
36
40
  /**
37
41
  * Set restrictive file permissions on config files.
38
42
  * Unix: chmod 600 (owner read/write only).
@@ -61,7 +65,9 @@ export declare function setSecureDirPermissions(dirPath: string): void;
61
65
  * If decryption of `encryptedLicenseKey` fails (hardware change),
62
66
  * returns config with licenseKey = undefined.
63
67
  */
64
- export declare function loadSecureConfig(): SecureConfig | null;
68
+ export declare function loadSecureConfig(options?: {
69
+ readonly strictReadOnly?: boolean;
70
+ }): SecureConfig | null;
65
71
  /**
66
72
  * Save config after activation with encrypted license key.
67
73
  * This is the primary write path called from activate.ts.
@@ -1,12 +1,12 @@
1
- import{existsSync as p,readFileSync as U,writeFileSync as R,mkdirSync as S,chmodSync as u}from"node:fs";import{execSync as y}from"node:child_process";import{join as a}from"node:path";import{homedir as L}from"node:os";import{encrypt as I,decrypt as g}from"../cache/crypto-utils.js";import{getMachineFingerprint as l}from"../machine/fingerprint.js";import{DEFAULT_SERVER_URL as x}from"../constants.js";const o=a(L(),".neocortex"),s=a(o,"config.json"),K=["api","neocortex","ornexus","com"].join("."),d=1;function f(r){const e=l();return I(r,e)}function C(r){try{const e=l();return g(r,e).plaintext}catch{return null}}function O(r){try{if(process.platform==="win32"){const e=process.env.USERNAME||process.env.USER||"";if(!e)return;y(`icacls "${r}" /inheritance:r /grant:r "${e}:(F)"`,{stdio:"pipe",timeout:5e3})}else u(r,384)}catch{}}function m(r){try{if(process.platform==="win32"){const e=process.env.USERNAME||process.env.USER||"";if(!e)return;y(`icacls "${r}" /inheritance:r /grant:r "${e}:(OI)(CI)(F)"`,{stdio:"pipe",timeout:5e3})}else u(r,448)}catch{}}let h=!1;function _(r){if(h)return;const e=r.serverUrl;if(!e)return;/^https?:\/\/(localhost|127\.0\.0\.1|0\.0\.0\.0)(:\d+)?/i.test(e)&&(h=!0,console.warn(`
2
- [!] Warning: connected to local server (`+e+`).
1
+ import{existsSync as u,readFileSync as R,writeFileSync as S,mkdirSync as L,chmodSync as y}from"node:fs";import{execSync as d}from"node:child_process";import{join as l}from"node:path";import{homedir as I}from"node:os";import{encrypt as g,decrypt as x}from"../cache/crypto-utils.js";import{getMachineFingerprint as p}from"../machine/fingerprint.js";import{DEFAULT_SERVER_URL as K}from"../constants.js";const s=l(I(),".neocortex"),a=l(s,"config.json"),C=["api","neocortex","ornexus","com"].join("."),f=1;function m(r,t={}){const e=p(t);return g(r,e)}function O(r,t={}){try{const e=p(t);return x(r,e).plaintext}catch{return null}}function _(r){try{if(process.platform==="win32"){const t=process.env.USERNAME||process.env.USER||"";if(!t)return;d(`icacls "${r}" /inheritance:r /grant:r "${t}:(F)"`,{stdio:"pipe",timeout:5e3})}else y(r,384)}catch{}}function h(r){try{if(process.platform==="win32"){const t=process.env.USERNAME||process.env.USER||"";if(!t)return;d(`icacls "${r}" /inheritance:r /grant:r "${t}:(OI)(CI)(F)"`,{stdio:"pipe",timeout:5e3})}else y(r,448)}catch{}}let v=!1;function F(r){if(v)return;const t=r.serverUrl;if(!t)return;/^https?:\/\/(localhost|127\.0\.0\.1|0\.0\.0\.0)(:\d+)?/i.test(t)&&(v=!0,console.warn(`
2
+ [!] Warning: connected to local server (`+t+`).
3
3
  To use production, run: neocortex activate YOUR-LICENSE-KEY
4
4
  Get yours at https://neocortex.sh/portal/login
5
- `))}function F(r){const e=r.match(/^(https?:\/\/)([^/]+)(.*)$/i);if(!e)return null;const[,c,t,n=""]=e;return t.toLowerCase()!==K?null:`${c}api.neocortex.sh${n}`}function Y(){try{if(!p(s))return null;const r=U(s,"utf-8"),e=JSON.parse(r.replace(/^\uFEFF/,""));if(e.licenseKey&&!e.encryptedLicenseKey){const n=f(e.licenseKey),i={...e},E=i.licenseKey;return delete i.licenseKey,i.encryptedLicenseKey=n,i.configVersion||(i.configVersion=d),v(i),{serverUrl:e.serverUrl,mode:e.mode,machineId:e.machineId,activatedAt:e.activatedAt,tier:e.tier,licenseKey:E,keyType:e.keyType}}let c;if(e.encryptedLicenseKey){const n=C(e.encryptedLicenseKey);n&&(c=n)}const t={serverUrl:e.serverUrl,mode:e.mode,machineId:e.machineId,activatedAt:e.activatedAt,tier:e.tier,licenseKey:c,keyType:e.keyType};if(e.machineId&&!c&&e.encryptedLicenseKey){const n=l();e.machineId!==n&&console.warn(`
6
- [!] Machine fingerprint changed (was: ${e.machineId.slice(0,12)}..., now: ${n.slice(0,12)}...).
5
+ `))}function w(r){const t=r.match(/^(https?:\/\/)([^/]+)(.*)$/i);if(!t)return null;const[,e,o,n=""]=t;return o.toLowerCase()!==C?null:`${e}api.neocortex.sh${n}`}function G(r={}){try{if(!u(a))return null;const t=R(a,"utf-8"),e=JSON.parse(t.replace(/^\uFEFF/,""));if(e.licenseKey&&!e.encryptedLicenseKey){const c=m(e.licenseKey,r),i={...e},U=i.licenseKey;return delete i.licenseKey,i.encryptedLicenseKey=c,i.configVersion||(i.configVersion=f),r.strictReadOnly||E(i),{serverUrl:e.serverUrl,mode:e.mode,machineId:e.machineId,activatedAt:e.activatedAt,tier:e.tier,licenseKey:U,keyType:e.keyType}}let o;if(e.encryptedLicenseKey){const c=O(e.encryptedLicenseKey,r);c&&(o=c)}const n={serverUrl:e.serverUrl,mode:e.mode,machineId:e.machineId,activatedAt:e.activatedAt,tier:e.tier,licenseKey:o,keyType:e.keyType};if(e.machineId&&!o&&e.encryptedLicenseKey){const c=p();e.machineId!==c&&console.warn(`
6
+ [!] Machine fingerprint changed (was: ${e.machineId.slice(0,12)}..., now: ${c.slice(0,12)}...).
7
7
  Your encrypted credentials are no longer valid.
8
8
  Re-activate with: neocortex activate YOUR-LICENSE-KEY
9
- `)}if(_(t),t.serverUrl&&!process.env.NEOCORTEX_SERVER_URL&&/^https?:\/\/(localhost|127\.0\.0\.1|0\.0\.0\.0)(:\d+)?/i.test(t.serverUrl)){const i=x;return console.warn(`[neocortex] Auto-repairing serverUrl: ${t.serverUrl} -> ${i}
10
- [neocortex] To keep localhost, set NEOCORTEX_SERVER_URL=${t.serverUrl}
11
- `),{...t,serverUrl:i}}if(t.serverUrl&&!process.env.NEOCORTEX_SERVER_URL){const n=F(t.serverUrl);if(n)return{...t,serverUrl:n}}return t}catch{return null}}function v(r){S(o,{recursive:!0}),m(o);const e=a(o,"cache");p(e)&&m(e),R(s,JSON.stringify(r,null,2)+`
12
- `,"utf-8"),O(s)}function G(r){const e=f(r.licenseKey),c=r.keyType??(r.licenseKey.startsWith("nxk_")?"api_key":"license"),t={configVersion:d,serverUrl:r.serverUrl,mode:r.mode,machineId:r.machineId,activatedAt:r.activatedAt,tier:r.tier,encryptedLicenseKey:e,keyType:c};v(t)}export{C as decryptLicenseKey,f as encryptLicenseKey,Y as loadSecureConfig,G as saveSecureConfig,m as setSecureDirPermissions,O as setSecureFilePermissions};
9
+ `)}if(F(n),n.serverUrl&&!process.env.NEOCORTEX_SERVER_URL&&/^https?:\/\/(localhost|127\.0\.0\.1|0\.0\.0\.0)(:\d+)?/i.test(n.serverUrl)){const i=K;return console.warn(`[neocortex] Auto-repairing serverUrl: ${n.serverUrl} -> ${i}
10
+ [neocortex] To keep localhost, set NEOCORTEX_SERVER_URL=${n.serverUrl}
11
+ `),{...n,serverUrl:i}}if(n.serverUrl&&!process.env.NEOCORTEX_SERVER_URL){const c=w(n.serverUrl);if(c)return{...n,serverUrl:c}}return n}catch{return null}}function E(r){L(s,{recursive:!0}),h(s);const t=l(s,"cache");u(t)&&h(t),S(a,JSON.stringify(r,null,2)+`
12
+ `,"utf-8"),_(a)}function D(r){const t=m(r.licenseKey),e=r.keyType??(r.licenseKey.startsWith("nxk_")?"api_key":"license"),o={configVersion:f,serverUrl:r.serverUrl,mode:r.mode,machineId:r.machineId,activatedAt:r.activatedAt,tier:r.tier,encryptedLicenseKey:t,keyType:e};E(o)}export{O as decryptLicenseKey,m as encryptLicenseKey,G as loadSecureConfig,D as saveSecureConfig,h as setSecureDirPermissions,_ as setSecureFilePermissions};