@ornexus/neocortex 4.60.16 → 4.63.4

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 (69) hide show
  1. package/dist/sbom.cdx.json +29 -29
  2. package/docs/install/installer-diagnostics.md +33 -0
  3. package/install.ps1 +49 -229
  4. package/install.sh +30 -92
  5. package/package.json +5 -2
  6. package/packages/client/dist/adapters/platform-detector.d.ts +7 -6
  7. package/packages/client/dist/adapters/platform-detector.js +1 -1
  8. package/packages/client/dist/agent/refresh-stubs.js +1 -1
  9. package/packages/client/dist/cache/encrypted-cache.d.ts +10 -4
  10. package/packages/client/dist/cache/encrypted-cache.js +1 -1
  11. package/packages/client/dist/cache/in-memory-asset-cache.d.ts +5 -4
  12. package/packages/client/dist/cache/in-memory-asset-cache.js +1 -1
  13. package/packages/client/dist/cache/protected-pi-boundary.d.ts +6 -2
  14. package/packages/client/dist/cache/protected-pi-boundary.js +1 -1
  15. package/packages/client/dist/checkpoint/checkpoint-client-reader.d.ts +31 -30
  16. package/packages/client/dist/checkpoint/checkpoint-client-reader.js +2 -2
  17. package/packages/client/dist/checkpoint/shared-checkpoint-types.d.ts +2 -0
  18. package/packages/client/dist/cli.js +3 -3
  19. package/packages/client/dist/commands/invoke.d.ts +77 -1
  20. package/packages/client/dist/commands/invoke.js +44 -59
  21. package/packages/client/dist/config/resolver-selection.d.ts +12 -31
  22. package/packages/client/dist/config/resolver-selection.js +1 -1
  23. package/packages/client/dist/errors/error-messages.js +1 -1
  24. package/packages/client/dist/evidence/collector.d.ts +18 -0
  25. package/packages/client/dist/evidence/collector.js +1 -0
  26. package/packages/client/dist/evidence/index.d.ts +3 -0
  27. package/packages/client/dist/evidence/index.js +1 -0
  28. package/packages/client/dist/evidence/types.d.ts +59 -0
  29. package/packages/client/dist/evidence/types.js +0 -0
  30. package/packages/client/dist/graph-retrieval/pre-command-hook.d.ts +21 -0
  31. package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -1
  32. package/packages/client/dist/index.d.ts +10 -11
  33. package/packages/client/dist/index.js +1 -1
  34. package/packages/client/dist/license/license-client.d.ts +17 -0
  35. package/packages/client/dist/license/license-client.js +1 -1
  36. package/packages/client/dist/memory/project-memory-writer.js +13 -13
  37. package/packages/client/dist/memory/shared-project-memory-types.d.ts +1 -1
  38. package/packages/client/dist/memory/shared-project-memory-types.js +2 -2
  39. package/packages/client/dist/resolvers/asset-resolver.d.ts +8 -71
  40. package/packages/client/dist/resolvers/remote-resolver.d.ts +7 -69
  41. package/packages/client/dist/resolvers/remote-resolver.js +1 -1
  42. package/packages/client/dist/runner-cli.js +0 -0
  43. package/packages/client/dist/state/project-state-snapshot.js +1 -1
  44. package/packages/client/dist/telemetry/index.d.ts +1 -1
  45. package/packages/client/dist/telemetry/index.js +1 -1
  46. package/packages/client/dist/telemetry/offline-queue.d.ts +12 -2
  47. package/packages/client/dist/telemetry/offline-queue.js +1 -1
  48. package/packages/client/dist/types/index.d.ts +26 -8
  49. package/packages/client/dist/types/index.js +1 -1
  50. package/packages/client/dist/types/shared-public-execution-contract.d.ts +175 -0
  51. package/packages/client/dist/types/shared-public-execution-contract.js +2 -0
  52. package/targets-stubs/antigravity/gemini.md +1 -1
  53. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  54. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  55. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  56. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  57. package/targets-stubs/claude-code/neocortex.md +2 -2
  58. package/targets-stubs/codex/AGENTS.md +16 -6
  59. package/targets-stubs/codex/README.md +24 -0
  60. package/targets-stubs/codex/install-codex.sh +70 -1
  61. package/targets-stubs/codex/neocortex-local.config.toml +17 -0
  62. package/targets-stubs/codex/neocortex.toml +10 -1
  63. package/targets-stubs/cursor/agent.md +2 -2
  64. package/targets-stubs/gemini-cli/agent.md +2 -2
  65. package/targets-stubs/opencode/neocortex-root.md +4 -4
  66. package/targets-stubs/opencode/neocortex.md +1 -1
  67. package/targets-stubs/vscode/neocortex.agent.md +2 -2
  68. package/packages/client/dist/resolvers/local-resolver.d.ts +0 -26
  69. package/packages/client/dist/resolvers/local-resolver.js +0 -8
@@ -14,7 +14,9 @@ import type { YoloopPersistedState } from '../yoloop/shared-yoloop-types.js';
14
14
  import { type RunnerBootstrapPolicyDecision } from '../continuity/runner-bootstrap-policy.js';
15
15
  import { type RunnerSchedulerBootstrapOptions, type RunnerSchedulerBootstrapResult } from '../runner/scheduler.js';
16
16
  import { type ContinuityProcessingSummaryCursorTarget } from '../continuity/continuity-client-state-store.js';
17
+ import { type PublicExecutionResponse, type PublicNativeTaskDirective, type PublicRootExecutionDirective, type PublicServerExecutionDirective } from '../types/index.js';
17
18
  export declare const INVOKE_PAYLOAD_LIMIT_BYTES: number;
19
+ export declare const CODEX_AUTH_SANDBOX_ERROR_CODE = "CODEX_AUTH_SANDBOX";
18
20
  export declare const INVOKE_PAYLOAD_WARNING_THRESHOLD_BYTES: number;
19
21
  interface InitProjectMemoryBootstrapSnapshot {
20
22
  readonly canonical: {
@@ -45,7 +47,7 @@ export interface InvokeOptions {
45
47
  readonly format?: 'json' | 'plain';
46
48
  /** Server URL override */
47
49
  readonly serverUrl?: string;
48
- /** Platform target (default: 'claude-code') */
50
+ /** Internal platform target override; otherwise detected with a claude-code fallback. */
49
51
  readonly platformTarget?: string;
50
52
  /** CLI input source, used to decide when stdin/args-file need chunk transport. */
51
53
  readonly inputSource?: InvokeCliInputSource;
@@ -68,14 +70,78 @@ export interface InvokeOptions {
68
70
  * Neocortex commands.
69
71
  */
70
72
  export declare function resolveInvokeProjectRoot(projectRoot: string | undefined, fallbackRoot?: string): string;
73
+ export declare function resolveInvokePlatformTarget(options: Pick<InvokeOptions, 'platformTarget' | 'environment'>, projectRoot: string): string;
71
74
  export interface InvokeResult {
72
75
  readonly success: boolean;
73
76
  readonly instructions?: string;
74
77
  readonly metadata?: Record<string, unknown>;
75
78
  readonly error?: string;
76
79
  readonly errorCode?: string;
80
+ readonly reasonCode?: string;
77
81
  readonly exitCode: number;
78
82
  }
83
+ export type CodexAuthEnvironmentStatus = 'not-codex' | 'missing' | 'activation-present' | 'sandbox-blocked' | 'config-unreadable' | 'cache-unreadable';
84
+ export type CodexAuthEnvironmentRemediation = 'none' | 'activate' | 'codex-sandbox';
85
+ export type CodexAuthEnvironmentReasonCode = 'codex-runtime-not-detected' | 'codex-config-missing' | 'codex-activation-present' | 'codex-config-inaccessible' | 'codex-config-unreadable' | 'codex-cache-unreadable' | 'codex-auth-network-denied';
86
+ export type CodexAuthPublicPath = '~/.neocortex' | '~/.neocortex/config.json' | '~/.neocortex/cache';
87
+ export interface CodexAuthEnvironmentDiagnosis {
88
+ readonly codexCli: boolean;
89
+ readonly status: CodexAuthEnvironmentStatus;
90
+ readonly reasonCode: CodexAuthEnvironmentReasonCode;
91
+ readonly remediation: CodexAuthEnvironmentRemediation;
92
+ readonly publicPath?: CodexAuthPublicPath;
93
+ }
94
+ export interface CodexAuthFailureDiagnosis {
95
+ readonly errorCode: 'NOT_CONFIGURED' | 'CODEX_AUTH_SANDBOX';
96
+ readonly reasonCode: CodexAuthEnvironmentReasonCode;
97
+ readonly error: string;
98
+ readonly humanizedErrorCode: 'NOT_CONFIGURED' | 'CODEX_AUTH_SANDBOX';
99
+ }
100
+ interface CodexAuthEnvironmentFsProbe {
101
+ readonly statSync: (path: string) => unknown;
102
+ readonly readFileSync: (path: string, encoding: BufferEncoding) => string;
103
+ }
104
+ interface CodexAuthEnvironmentClassifierOptions {
105
+ readonly env?: NodeJS.ProcessEnv;
106
+ readonly platformTarget?: string;
107
+ readonly configDir?: string;
108
+ readonly configFile?: string;
109
+ readonly cacheDir?: string;
110
+ readonly fs?: CodexAuthEnvironmentFsProbe;
111
+ }
112
+ export declare function classifyCodexAuthEnvironment(options?: CodexAuthEnvironmentClassifierOptions): CodexAuthEnvironmentDiagnosis;
113
+ export declare function resolveCodexAuthFailureDiagnosis(diagnosis: CodexAuthEnvironmentDiagnosis): CodexAuthFailureDiagnosis | null;
114
+ export interface PublicExecutionTaskDirective {
115
+ readonly kind: 'task';
116
+ readonly subagentType: 'neocortex';
117
+ readonly promptTemplate: string;
118
+ readonly promptTemplates: readonly string[];
119
+ readonly storyIds: readonly string[];
120
+ readonly rationale: string;
121
+ readonly directiveId: string;
122
+ readonly taskId: string;
123
+ readonly acceptanceRefs: readonly string[];
124
+ }
125
+ export interface PublicExecutionDispatchMetadata {
126
+ readonly schemaVersion: 1;
127
+ readonly executionId: string;
128
+ readonly status: PublicExecutionResponse['status'];
129
+ readonly dispatchable: boolean;
130
+ readonly rootDirectives: readonly PublicRootExecutionDirective[];
131
+ readonly nativeTaskDirectives: readonly PublicNativeTaskDirective[];
132
+ readonly serverDirectives: readonly PublicServerExecutionDirective[];
133
+ readonly reasonCodes: readonly string[];
134
+ readonly publicSafe: true;
135
+ }
136
+ export interface PublicExecutionDispatchResult {
137
+ readonly instructions: string;
138
+ readonly metadata: Record<string, unknown>;
139
+ }
140
+ export declare class PublicExecutionResponseError extends Error {
141
+ readonly code = "PUBLIC_EXECUTION_UPGRADE_REQUIRED";
142
+ constructor();
143
+ }
144
+ export declare function buildPublicExecutionRequestHeaders(authToken: string): Record<string, string>;
79
145
  type InvokeWatchFormat = 'plain' | 'json';
80
146
  interface InvokeWatchWritable {
81
147
  write(chunk: string): unknown;
@@ -219,6 +285,12 @@ export declare function sanitizeInvokeCliOutput(instructions: string | undefined
219
285
  instructions: string;
220
286
  metadata: Record<string, unknown> | undefined;
221
287
  };
288
+ /**
289
+ * Validate and project the V2 public response into explicit local dispatch
290
+ * metadata. Summaries/prose never create authority: only discriminated,
291
+ * contract-valid root/native directives can enter executable views.
292
+ */
293
+ export declare function dispatchPublicExecutionResponse(value: unknown): PublicExecutionDispatchResult;
222
294
  type InvokeCliInputSource = 'args' | 'stdin' | 'args-file';
223
295
  export interface InvokeCliParsedOptions {
224
296
  readonly args: string;
@@ -409,6 +481,8 @@ export interface StateSnapshot {
409
481
  * decides workflow locally and is omitted when disabled or unavailable.
410
482
  */
411
483
  readonly graphRetrieval?: unknown;
484
+ /** P201.12 request-only, locally collected and bounded project evidence. */
485
+ readonly projectEvidence?: unknown;
412
486
  /**
413
487
  * P181.04 -- request-only runner auto-bootstrap summary. Public-safe only;
414
488
  * never persisted to `.neocortex/state.json` and omitted for unrelated
@@ -494,6 +568,7 @@ export declare function __resetSchemaDriftWarnedForTests(): void;
494
568
  */
495
569
  export declare function collectStateSnapshot(projectRoot: string): StateSnapshot;
496
570
  export declare function createFullStateSnapshotScope(trigger: string, snapshot: Pick<StateSnapshot, 'stories' | 'epics'>): FullStateSnapshotScope;
571
+ export declare function sanitizePublicInvokeErrorBody(value: unknown): Record<string, unknown> | undefined;
497
572
  export declare function computeInvokeRequestBodySizeBytes(body: InvokeRequestBody): number;
498
573
  export declare function createInvokePayloadTelemetry(body: InvokeRequestBody, payloadBytes?: number, reasonCodes?: readonly string[], options?: {
499
574
  readonly limitBytes?: number;
@@ -530,6 +605,7 @@ export declare function extractPreFlightTrigger(args: string): string | null;
530
605
  export declare const INVOKE_HELP_TEXT: string;
531
606
  export declare function parseInvokeCliOptions(argv: string[], readers?: InvokeCliInputReaders): InvokeCliParsedOptions;
532
607
  export declare function writeInvokeCliSuccessOutput(result: InvokeResult, parsed: Pick<InvokeCliParsedOptions, 'format' | 'watch' | 'commandLevelWatch'>, stdout?: InvokeWatchWritable, stderr?: InvokeWatchWritable): void;
608
+ export declare function buildInvokeCliErrorPayload(result: Pick<InvokeResult, 'errorCode' | 'reasonCode' | 'error' | 'exitCode'>): Record<string, string>;
533
609
  /**
534
610
  * CLI handler for the invoke command.
535
611
  * Parses CLI args and delegates to invoke().
@@ -1,69 +1,54 @@
1
- import{createHash as Ce}from"node:crypto";import{existsSync as z,readFileSync as Q,unlinkSync as dt,writeFileSync as ut,mkdirSync as lt,statSync as pt}from"node:fs";import{join as M}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";const Z=M(se(),".neocortex"),Oe=M(Z,"cache"),Le=M(Oe,"menu-cache.json"),ke=1440*60*1e3,xe=3e4,H="3.9.62",Pe=256*1024,je=Pe,De=.8,W="[REDACTED]",xt=1e5,ee=2e3,Pt=200,jt=200,Dt=12,Ut=/(?:promptBody|workflow|workflowGraph|stepBody|privateUrl|rawLog|secret|credential|licenseKey|apiKey|internalRouting|serverOnly|proprietary|protected)/i,Mt=/(?:PRIVATE|PROTECTED|SERVER_ONLY)[-_\s]*(?:PROMPT|PROMPT_BODY|WORKFLOW|WORKFLOW_GRAPH|STEP_BODY|STEP|ROUTING)\s*[:=][^\n\r]*/gi,Wt=/(?: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=M(Z,".first-run-shown"),$t="<!-- NEOCORTEX-MEMORY-START -->";function Bt(e){return/^\s*\*?init(?:\s|$)/i.test(e)}function Ht(e){const t=M(e,"NEOCORTEX.md"),n=z(t)?Q(t,"utf8"):void 0,r=n===void 0?["missing_canonical_memory"]:[n.includes($t)?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(M(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 Vt(){try{if(z(Ue))return;const e=It(),t=St(e);process.stderr.write(t);try{lt(Z,{recursive:!0}),ut(Ue,new Date().toISOString(),"utf-8")}catch{}}catch{}}function ce(e,t=process.cwd()){return e&&e.trim().length>0?e:t}const Ft=new Set(["completed","aborted","cancelled"]),Jt=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,Gt=/(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 Kt(e){return e.replace(/[\w.+-]+@[\w-]+\.[\w.-]+/g,W).replace(/(?:sk|pk|whsec|nxk)[-_](?:test|live|ant|proj|pro|free|enterprise)?[-_]?[A-Za-z0-9_-]{16,}/g,W).replace(/NX-[FPE]-[a-f0-9]{24}-[a-f0-9]{4}/g,W).replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,W).replace(Mt,W).replace(Wt,W)}function V(e,t){const n=Kt(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>Dt)return"[MAX_DEPTH]";if(e==null)return e;if(typeof e=="string")return V(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,Pt).map(o=>de(o,t+1,n));const r={};for(const[o,a]of Object.entries(e).slice(0,jt)){if(Ut.test(o)){r[o]=W;continue}const s=de(a,t+1,n);s!==void 0&&(r[o]=s)}return r}function ue(e,t){return{instructions:V(e??"",xt),metadata:t?de(t):void 0}}class k extends Error{code;constructor(t,n){super(n),this.name="InvokeCliInputError",this.code=t}}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 le=!1;function zt(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 Yt(e){if(!(le||e.length===0)){le=!0;try{const t=e.map(n=>` - ${n.message}`).join(`
1
+ import{createHash as Ae}from"node:crypto";import{existsSync as ee,readFileSync as z,writeFileSync as ht,mkdirSync as Et,statSync as Re}from"node:fs";import{join as j}from"node:path";import{homedir as se}from"node:os";import{LicenseClient as _t}from"../license/license-client.js";import{EncryptedCache as It}from"../cache/encrypted-cache.js";import{NoOpCache as Ct}from"../types/index.js";import{resolveClientPreFlightTrigger as St,TierAwareClient as bt}from"../tier/tier-aware-client.js";import{loadSecureConfig as yt}from"../config/secure-config.js";import{DEFAULT_SERVER_URL as vt}from"../constants.js";import{detectFirstRunLocale as At,renderFirstRunMessage as Rt}from"../i18n/first-run.js";import{humanizeError as Te,formatHumanizedError as we,detectErrorLocale as Oe}from"../errors/error-messages.js";import{degradeStateSnapshotForPayloadLimit as Tt,projectStateSnapshotForInvoke as wt}from"../state/project-state-snapshot.js";import{maybeRepairStateJsonBeforeInvoke as Ot,StateRepairHardStopError as Nt}from"../state/state-json-repair.js";import{bootstrapArchitectureMemory as xt}from"../memory/project-memory-writer.js";import{detectPlatform as Lt}from"../adapters/platform-detector.js";import{RUNNER_BOOTSTRAP_POLICY_REASON_CODES as kt,classifyRunnerBootstrapPolicyFromArgs as Pt}from"../continuity/runner-bootstrap-policy.js";import{RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES as Dt,ensureRunnerSchedulerBootstrap as Ut}from"../runner/scheduler.js";import{CONTINUITY_INVOKE_WATCH_DEFAULT_LIMIT as Ne,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_IDLE_POLLS as xe,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_POLLS as Le,CONTINUITY_INVOKE_WATCH_DEFAULT_POLL_INTERVAL_MS as ke,openContinuityClientStateStore as jt}from"../continuity/continuity-client-state-store.js";import{isLocalJobsConsoleArgs as Mt,runLocalJobsConsoleCommand as $t}from"../runner/local-console.js";import{PUBLIC_EXECUTION_MIN_SECURE_CLIENT_VERSION as ie,PUBLIC_EXECUTION_SCHEMA_HEADER as Bt,PUBLIC_EXECUTION_SCHEMA_VERSION as Pe,validatePublicExecutionResponse as De}from"../types/index.js";const V=j(se(),".neocortex"),Wt=j(V,"config.json"),Ht=j(V,"cache"),M="~/.neocortex",Y="~/.neocortex/config.json",Vt="~/.neocortex/cache",Ue=3e4,je=ie,Me=256*1024,$e=Me,Be=.8,$="[REDACTED]",Ft=1e5,ce=2e3,Gt=200,Jt=200,Kt=12,zt=/(?:promptBody|workflow|workflowGraph|stepBody|privateUrl|rawLog|secret|credential|licenseKey|apiKey|internalRouting|serverOnly|proprietary|protected)/i,Yt=/(?:PRIVATE|PROTECTED|SERVER_ONLY)[-_\s]*(?:PROMPT|PROMPT_BODY|WORKFLOW|WORKFLOW_GRAPH|STEP_BODY|STEP|ROUTING)\s*[:=][^\n\r]*/gi,Xt=/(?:https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|private|internal)[^\s"'<>]*|(?:^|\s)(?:\/(?:Users|home|private|tmp|var|etc|mnt|media)\/[^\s"'<>]+|[A-Za-z]:\\[^\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*:\s*[^\s"'<>]+|password\s*=\s*[^\s"'<>]+|token\s*=\s*[^\s"'<>]+|api[_-]?key\s*=\s*[^\s"'<>]+|license[_-]?key\s*=\s*[^\s"'<>]+)/gi,qt=new Set(["zero-pi-api-payload-rejected"]),We="CODEX_AUTH_SANDBOX",de=Math.floor(Me*Be),He=j(V,".first-run-shown"),Zt="<!-- NEOCORTEX-MEMORY-START -->";function Qt(e){return/^\s*\*?init(?:\s|$)/i.test(e)}function en(e){const t=j(e,"NEOCORTEX.md"),n=ee(t)?z(t,"utf8"):void 0,o=n===void 0?["missing_canonical_memory"]:[n.includes(Zt)?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=>ee(j(e,p))),s=o.includes("possible_secret_shape_detected")?"low":o.length===0?"high":a.length>0?"medium":"low",c=xt(e);return{canonical:{path:"NEOCORTEX.md",exists:n!==void 0,incompleteReasons:o,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 tn(){try{if(ee(He))return;const e=At(),t=Rt(e);process.stderr.write(t);try{Et(V,{recursive:!0}),ht(He,new Date().toISOString(),"utf-8")}catch{}}catch{}}function ue(e,t=process.cwd()){return e&&e.trim().length>0?e:t}function nn(e,t){if(e.platformTarget!==void 0)return e.platformTarget;try{return Lt({cwd:t,env:e.environment??process.env}).targetId}catch{return"claude-code"}}function on(e=process.env,t){return t==="codex"||/^(?:1|true|yes|on)$/i.test(e.CODEX_CLI??"")||!!e.CODEX_THREAD_ID?.trim()}function Ve(e){return e&&typeof e=="object"&&typeof e.code=="string"?e.code:void 0}function le(e,t){try{return e.statSync(t),"present"}catch(n){const o=Ve(n);return o==="ENOENT"||o==="ENOTDIR"?"missing":o==="EACCES"||o==="EPERM"?"inaccessible":"unreadable"}}function rn(e){try{const t=JSON.parse(e.replace(/^\uFEFF/,""));return typeof t.encryptedLicenseKey=="string"&&t.encryptedLicenseKey.length>0||typeof t.licenseKey=="string"&&t.licenseKey.length>0}catch{return null}}function an(e={}){const t=e.env??process.env;if(!on(t,e.platformTarget))return{codexCli:!1,status:"not-codex",reasonCode:"codex-runtime-not-detected",remediation:"none"};const n=e.fs??{statSync:Re,readFileSync:z},o=e.configDir??V,r=e.configFile??Wt,a=e.cacheDir??Ht,s=le(n,o);if(s==="missing")return{codexCli:!0,status:"missing",reasonCode:"codex-config-missing",remediation:"activate",publicPath:M};if(s!=="present")return{codexCli:!0,status:s==="inaccessible"?"sandbox-blocked":"config-unreadable",reasonCode:s==="inaccessible"?"codex-config-inaccessible":"codex-config-unreadable",remediation:"codex-sandbox",publicPath:M};const c=le(n,r);if(c==="missing")return{codexCli:!0,status:"missing",reasonCode:"codex-config-missing",remediation:"activate",publicPath:Y};if(c!=="present")return{codexCli:!0,status:c==="inaccessible"?"sandbox-blocked":"config-unreadable",reasonCode:c==="inaccessible"?"codex-config-inaccessible":"codex-config-unreadable",remediation:"codex-sandbox",publicPath:Y};let p;try{p=rn(n.readFileSync(r,"utf-8"))}catch(d){const f=Ve(d);return{codexCli:!0,status:f==="EACCES"||f==="EPERM"?"sandbox-blocked":"config-unreadable",reasonCode:f==="EACCES"||f==="EPERM"?"codex-config-inaccessible":"codex-config-unreadable",remediation:"codex-sandbox",publicPath:Y}}if(p===null)return{codexCli:!0,status:"config-unreadable",reasonCode:"codex-config-unreadable",remediation:"codex-sandbox",publicPath:Y};if(!p)return{codexCli:!0,status:"missing",reasonCode:"codex-config-missing",remediation:"activate",publicPath:Y};const u=le(n,a);return u==="inaccessible"||u==="unreadable"?{codexCli:!0,status:"cache-unreadable",reasonCode:"codex-cache-unreadable",remediation:"codex-sandbox",publicPath:Vt}:{codexCli:!0,status:"activation-present",reasonCode:"codex-activation-present",remediation:"none",publicPath:M}}function sn(e){if(!e.codexCli)return null;if(e.remediation==="activate")return{errorCode:"NOT_CONFIGURED",reasonCode:e.reasonCode,humanizedErrorCode:"NOT_CONFIGURED",error:`Not authenticated. Codex auth diagnosis: reason=${e.reasonCode}; checked ${e.publicPath??M}. Visit https://neocortex.sh/portal/login to get your license key, then run: neocortex activate YOUR-LICENSE-KEY`};const t=e.status==="activation-present"?"codex-auth-network-denied":e.reasonCode;return{errorCode:We,reasonCode:t,humanizedErrorCode:We,error:`Codex auth diagnosis: reason=${t}; checked ${e.publicPath??M}. Codex could not access or use the local Neocortex activation under ${M}. Use a trusted local Codex profile/session with Full access to ${M} and outbound auth network access, or run from a local terminal. Do not paste license or API keys into prompts; activate an isolated Codex environment only if you intentionally want a separate activation.`}}class Fe extends Error{code="PUBLIC_EXECUTION_UPGRADE_REQUIRED";constructor(){super("Secure public execution response required. Upgrade the Neocortex client and server, then retry. Legacy response fallback is disabled."),this.name="PublicExecutionResponseError"}}function cn(e){return{"Content-Type":"application/json",Authorization:`Bearer ${e}`,"X-Client-Version":je,[Bt]:String(Pe)}}const dn=new Set(["completed","aborted","cancelled"]),un=new Set(["watch-target-missing","watch-target-malformed","watch-target-ambiguous","watch-target-multiple"]),v=Object.freeze({COMPLETED:"invoke-watch-completed",CANCELLED:"invoke-watch-cancelled",IDLE_TIMEOUT:"invoke-watch-idle-timeout",MAX_POLLS:"invoke-watch-max-polls",STORE_UNAVAILABLE:"invoke-watch-store-unavailable",TARGET_UNRESOLVED:"invoke-watch-target-unresolved"}),R=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"}),C=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"}),Ge=240,ln=/(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 pn(e){return e.replace(/[\w.+-]+@[\w-]+\.[\w.-]+/g,$).replace(/(?:sk|pk|whsec|nxk)[-_](?:test|live|ant|proj|pro|free|enterprise)?[-_]?[A-Za-z0-9_-]{16,}/g,$).replace(/NX-[FPE]-[a-f0-9]{24}-[a-f0-9]{4}/g,$).replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,$).replace(Yt,$).replace(Xt,$)}function H(e,t){const n=pn(e);return n.length<=t?n:`${n.slice(0,t)}\u2026[TRUNCATED:${n.length-t}]`}function pe(e,t=0,n=new WeakSet){if(t>Kt)return"[MAX_DEPTH]";if(e==null)return e;if(typeof e=="string")return H(e,ce);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,Gt).map(r=>pe(r,t+1,n));const o={};for(const[r,a]of Object.entries(e).slice(0,Jt)){if(zt.test(r)){o[r]=$;continue}const s=pe(a,t+1,n);s!==void 0&&(o[r]=s)}return o}function fe(e,t){return{instructions:H(e??"",Ft),metadata:t?pe(t):void 0}}function fn(e){return e==="running"||e==="completed"}function ge(e){return e.kind==="root-execution"?{...e,contractIds:[...e.contractIds],projectPaths:[...e.projectPaths]}:e.kind==="native-task"?{...e,acceptanceRefs:[...e.acceptanceRefs]}:{...e}}function gn(e){return e.slice(13,-9)}function mn(e,t){const n=["# Neocortex Public Execution","",`- Execution: ${e.executionId}`,`- Status: ${e.status}`,`- Authority: ${e.authority}`,`- Local dispatch: ${t.dispatchable?"ready":"withheld"}`];for(const o of t.rootDirectives){const r=o.projectPaths.length>0?` paths=${o.projectPaths.join(",")}`:"";n.push(`- Root action: ${o.operation} task=${o.taskId}${r}`)}for(const o of t.nativeTaskDirectives)n.push(`- Native task: *${o.command} @${o.storyPath}`);for(const o of t.serverDirectives)n.push(`- Server observation: ${o.operation} contract=${o.contractId}`);for(const o of e.blockers)n.push(`- Blocker: ${o.reasonCode}`);for(const o of e.validation)n.push(`- Validation: ${o.checkId}=${o.status}`);return n.push("","Execution authority is defined only by the structured public execution metadata."),n.join(`
2
+ `)}function hn(e){const t=De(e);if(!t.ok)throw new Fe;const n=t.value,o=fn(n.status),r=o?n.directives.filter(f=>f.kind==="root-execution").map(ge):[],a=o?n.directives.filter(f=>f.kind==="native-task").map(ge):[],s=n.directives.filter(f=>f.kind==="server-execution").map(ge),c=n.status==="waiting"?["public-execution-waiting-evidence"]:n.status==="blocked"?["public-execution-blocked"]:o&&(r.length>0||a.length>0)?["public-execution-dispatch-ready"]:o?["public-execution-no-local-directive"]:["public-execution-terminal-no-dispatch"],p={schemaVersion:1,executionId:n.executionId,status:n.status,dispatchable:o,rootDirectives:r,nativeTaskDirectives:a,serverDirectives:s,reasonCodes:c,publicSafe:!0},u=a.map(f=>{const h=gn(f.storyPath),g=`*${f.command} @${f.storyPath}`;return{kind:"task",subagentType:f.subagentType,promptTemplate:g,promptTemplates:[g],storyIds:[h],rationale:"Execute the explicit validated public native task directive.",directiveId:f.directiveId,taskId:f.taskId,acceptanceRefs:[...f.acceptanceRefs]}}),d={mode:"public-execution",publicExecution:n,publicExecutionDispatch:p,...u.length>0?{skillDirectives:u}:{},...u.length===1?{nextStoryId:u[0].storyIds[0]}:{},publicSafe:!0};return{instructions:mn(n,p),metadata:d}}class N extends Error{code;constructor(t,n){super(n),this.name="InvokeCliInputError",this.code=t}}class Je extends Error{code="PAYLOAD_TOO_LARGE";telemetry;constructor(t){super(`PAYLOAD_TOO_LARGE: invoke request is ${t.payloadBytes} bytes after deterministic degradation; limit is ${t.limitBytes}. Reduce command input or local state context and retry.`),this.name="InvokePayloadTooLargeError",this.telemetry=t}}let me=!1;function En(e){const t=[];if(!e||typeof e!="object")return t;const n=e,o=n.planning;if(o&&(o.current!==void 0||Array.isArray(o.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 r=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)||o&&o.current!==void 0;return n.schema_version===void 0?r&&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 _n(e){if(!(me||e.length===0)){me=!0;try{const t=e.map(n=>` - ${n.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 vr(){le=!1}function $e(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function qt(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 Xt(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 Qt(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 Zt(e){const t=M(e,".neocortex","state.json");if(!z(t))return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}};let n;try{const l=Q(t,"utf-8");n=JSON.parse(l)}catch{return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}try{const l=zt(n);l.length>0&&Yt(l)}catch{}const r=n.config??n.project??{},o=n.stories??{},a={};for(const[l,d]of Object.entries(o))a[l]={id:d.id??l,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)}:{},...Qt(d),depends_on:$e(d.depends_on),files_to_modify:qt(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[l,d]of Object.entries(s))c[l]={id:d.id??l,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=Xt(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 wr(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 en(e){try{const t=await e.get(Be);if(!t)return null;const n=JSON.parse(t);return n.version!==H||Date.now()-n.cachedAt>ke?null:n}catch{return null}}async function tn(e,t,n){try{const r={instructions:t,metadata:n,cachedAt:Date.now(),version:H};await e.set(Be,JSON.stringify(r),ke),nn()}catch{}}function nn(){try{z(Le)&&dt(Le)}catch{}}function rn(){return Et()}async function on(e,t){try{let n;if(t){const s=M(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 an(){const e=Number(process.env.NEOCORTEX_INVOKE_CHUNK_BYTES??"49152");return Number.isFinite(e)&&e>=1024&&e<=98304?Math.floor(e):49152}function sn(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":H},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 cn(e,t,n){const r=Buffer.from(t,"utf8"),o=an(),a=[];for(let S=0,m=0;S<r.byteLength;S+=o,m++){const I=r.subarray(S,Math.min(S+o,r.byteLength));a.push({index:m,sha256:Ve(I),byteLength:I.byteLength})}const s=Ve(r),c=sn(s,r.byteLength,a),p=Number(process.env.NEOCORTEX_INVOKE_CHUNK_TTL_SECONDS??"900");for(const S of a){const m=S.index*o,I=r.subarray(m,m+S.byteLength);await Fe(e,"/api/v1/invoke/materialization/chunks",{manifestId:c,index:S.index,sha256:S.sha256,byteLength:S.byteLength,contentBase64:I.toString("base64"),ttlSeconds:p,idempotencyKey:`${c}:${S.index}:${S.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 F(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function dn(...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 un(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=F(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:un(e.stateSnapshot),reasonCodes:dn(n,o?.reasonCodes),publicSafe:!0}}function ln(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 pn(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 fn(e){const t=e.graphRetrieval;if(!g(t)||!Array.isArray(t.items))return e;const n=ln(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,pn(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 mn(e,t={}){const n=t.limitBytes??je,r=t.warningThresholdBytes??Math.floor(n*De),o=F(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=F(a);c>n&&(a={...a,stateSnapshot:fn(a.stateSnapshot)},s=[...s,"graph-retrieval-budget-enforced"],c=F(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 gn(e){return rt(e)??e.trim().split(/\s+/,1)[0]?.slice(0,80)??"(empty)"}function Ge(e){return e.args!==void 0?gn(e.args):`argsRef:${e.argsRef.manifestId.slice(0,80)}`}function hn(e){const t=F(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 En(e){const t=Rt(e.args,{platformTarget:e.platformTarget,environment:e.environment??process.env});if(t.action==="skipped")return{shouldContinue:!0,attachToRequest:_n(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 _n(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=V(n,t),o=Gt.test(r)?W: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 D(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 x(e,t,n,r,o=[],a){const s=r[r.length-1],c=n??s?.cursor,p=!!(c&&c!==t&&r.length>0),l=a??(p?"advanced":t||c?"unchanged":"not_started"),d=o.length>0?o:l==="advanced"?[h.WATCH_CURSOR_ADVANCED]:l==="unavailable"?[h.WATCH_EVIDENCE_UNAVAILABLE]:[h.WATCH_CURSOR_UNCHANGED];return{schemaVersion:1,contractVersion:"continuity-v1",cursorState:l,...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 P(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 In(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 j(e,t,n){if(t==="json"){n.write(JSON.stringify(e)+`
10
- `);return}n.write(In(e)+`
11
- `)}function Sn(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 U(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:Sn(r,t,n),publicSafe:!0}}function Cn(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 yn(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 An(e,t,n){if(t==="json"){n.write(JSON.stringify(yn(e))+`
12
- `);return}n.write(Cn(e)+`
13
- `)}function he(e){return Ft.has(e.status)}function Tn(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 vn(e,t,n,r){return n<r?!1:t?!e.some(o=>o.jobId===t&&!he(o)):e.length===0}function wn(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 Rn(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,Rn(r),r),a=D({generatedAt:new Date().toISOString()},[],!1,0,[h.WATCH_TARGET_UNRESOLVED]),s=x(void 0,void 0,void 0,[],[h.WATCH_TARGET_UNRESOLVED],"unavailable");return P({watchStatus:"blocked",active:!1,targetEvidence:o,snapshotEvidence:a,cursorEvidence:s,stopReason:"target_unresolved",reasonCodes:r,generatedAt:a.generatedAt})}function bn(e,t,n,r){const o=Ye(e,Xe(t));return j(o,n,r),U("target-unresolved",0,0,o)}async function Nn(e){if(e.signal?.aborted){const b=ge(e.target??Y(e.targetJobId),e.targetJobId,e.target??e.targetJobId?"resolved":"unresolved",[T.CANCELLED]),_=D(void 0,[],!1,0),A=x(e.initialCursor,e.initialCursor,e.initialCursor,[],[T.CANCELLED],"unavailable"),X=P({watchStatus:"stopped",active:!1,targetEvidence:b,snapshotEvidence:_,cursorEvidence:A,stopReason:"cancelled",reasonCodes:[T.CANCELLED]});return U("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 j(b,e.format,r),U("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??wn;let l=e.initialCursor,d=0,S=0,m=0;const I=ge(t,n,"resolved",[h.OK]),f={schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:"pending",renderedSummaryCount:0,reasonCodes:[h.WATCH_RENDER_PENDING],publicSafe:!0},L=x(e.initialCursor,l,l,[],e.initialCursor?[h.WATCH_CURSOR_UNCHANGED]:[h.WATCH_NO_SUMMARIES_YET],e.initialCursor?"unchanged":"not_started");j(P({watchStatus:"active",active:!0,targetEvidence:I,snapshotEvidence:f,cursorEvidence:L,stopReason:"not_stopped",reasonCodes:[h.OK]}),e.format,r);let i;try{i=await Ot({projectRoot:e.projectRoot})}catch{const b=D(void 0,[],!1,d,[h.WATCH_SNAPSHOT_UNAVAILABLE]),_=x(e.initialCursor,l,l,[],[h.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),A=P({watchStatus:"blocked",active:!1,targetEvidence:I,snapshotEvidence:b,cursorEvidence:_,stopReason:"unavailable_evidence",reasonCodes:[T.STORE_UNAVAILABLE]});return j(A,e.format,r),U("store-unavailable",d,m,A)}try{for(;!e.signal?.aborted&&m<c;){m+=1;const b=l,_=i.collectProcessingOutputSummaryCursor({...l?{cursor:l}:{},...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)An(G,e.format,r),d+=1;l=_.nextCursor??_.summaries[_.summaries.length-1]?.cursor??l,S=0}else l=_.nextCursor??l,S+=1;const it=D(A,_.summaries,!0,_.summaries.length),ct=x(e.initialCursor,b,l,_.summaries,_.summaries.length>0?[h.WATCH_CURSOR_ADVANCED]:[h.WATCH_NO_SUMMARIES_YET]);if(j(P({watchStatus:_.summaries.length>0?"polling":"waiting",active:!0,targetEvidence:I,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&&Tn(X,n,d)){const G=D(A,_.summaries,!1,d,[T.COMPLETED]),ae=x(e.initialCursor,b,l,_.summaries,[T.COMPLETED],"exhausted"),K=P({watchStatus:"stopped",active:!1,targetEvidence:I,snapshotEvidence:G,cursorEvidence:ae,stopReason:"not_stopped",reasonCodes:[T.COMPLETED],generatedAt:A.generatedAt});return j(K,e.format,r),U("completed",d,m,K)}if(!_.hasMore&&vn(X,n,S,s)){const G=D(A,_.summaries,!1,d,[h.WATCH_STOP_IDLE_LIMIT_REACHED]),ae=x(e.initialCursor,b,l,_.summaries,[h.WATCH_STOP_IDLE_LIMIT_REACHED],"exhausted"),K=P({watchStatus:"stopped",active:!1,targetEvidence:I,snapshotEvidence:G,cursorEvidence:ae,stopReason:"idle_limit_reached",reasonCodes:[T.IDLE_TIMEOUT,h.WATCH_STOP_IDLE_LIMIT_REACHED],generatedAt:A.generatedAt});return j(K,e.format,r),U("idle-timeout",d,m,K)}_.hasMore||await p(a,e.signal)}}catch{const b=D(void 0,[],!1,d,[h.WATCH_SNAPSHOT_UNAVAILABLE]),_=x(e.initialCursor,l,l,[],[h.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),A=P({watchStatus:"blocked",active:!1,targetEvidence:I,snapshotEvidence:b,cursorEvidence:_,stopReason:"unavailable_evidence",reasonCodes:[T.STORE_UNAVAILABLE]});return j(A,e.format,r),U("store-unavailable",d,m,A)}finally{i.close()}if(e.signal?.aborted){const b=D(void 0,[],!1,d,[T.CANCELLED]),_=x(e.initialCursor,l,l,[],[T.CANCELLED],"unavailable"),A=P({watchStatus:"stopped",active:!1,targetEvidence:I,snapshotEvidence:b,cursorEvidence:_,stopReason:"cancelled",reasonCodes:[T.CANCELLED]});return j(A,e.format,r),U("cancelled",d,m,A)}const u=D(void 0,[],!1,d,[h.WATCH_STOP_MAX_POLLS_REACHED]),C=x(e.initialCursor,l,l,[],[h.WATCH_STOP_MAX_POLLS_REACHED],"exhausted"),B=P({watchStatus:"stopped",active:!1,targetEvidence:I,snapshotEvidence:u,cursorEvidence:C,stopReason:"max_polls_reached",reasonCodes:[T.MAX_POLLS,h.WATCH_STOP_MAX_POLLS_REACHED]});return j(B,e.format,r),U("max-polls",d,m,B)}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 On(e,t){const n=_e(t).filter(r=>r!==e.targetId&&r!==e.jobId);return n.length>0?{...e,relatedJobIds:n}:e}function Ln(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"}),kn=new Set(["create","start","resume"]),xn=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 Pn(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 jn(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 Dn(e){if(!e||e.quoted)return;const t=e.value.replace(/^\*/,"").toLowerCase();return t==="goal"||t==="loop"?t:void 0}function Un(e,t){if(!e||e==="jobs"||!t||t.quoted)return;const n=t.value.toLowerCase();return(e==="goal"?kn:xn).has(n)?n:void 0}function Mn(e){return!e.quoted&&e.value!=="--watch"&&e.value.toLowerCase().startsWith("--watch")}function Wn(e){const{tokens:t,malformed:n}=jn(e),r=Dn(t[0]),o=Un(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(Mn);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 l=a[0];if(!l)return R(e,[],r,o);if(t[t.length-1]!==l)return R(e,[v.NON_FINAL],r,o);if(!r||!o)return R(e,[v.UNRESOLVED],r,o);const d=`${e.slice(0,l.start)}${e.slice(l.end)}`.trim(),S={literal:"--watch",position:"final",start:l.start,end:l.end,quoted:!1,publicSafe:!0};return{args:d,watch:!0,reasonCodes:[v.ACTIVE],metadata:Ie(!0,[v.ACTIVE],r,o,S),publicSafe:!0}}function $n(e){return Qe(e)?Pn(e):Wn(e)}function Bn(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&Jt.has(t)):[]}function J(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:On(o,n),targetJobId:o.targetId,...r?{initialCursor:r}:{},serverHeldStream:!1}}function Hn(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 $(e,t,n,r){return{source:e,hasEvidence:t,candidates:Hn(n.filter(o=>!!o)),...r&&r.length>0?{disabledReasonCodes:N(r)}:{}}}function Vn(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 Fn(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=Bn(r?.reasonCodes??n?.reasonCodes);if(!r)return $("watcher-metadata",o.length>0,[],o);if(r.active===!1||o.length>0)return $("watcher-metadata",!0,[],o.length>0?o:[w.MALFORMED]);if(r.serverHeldStream!==!1)return $("watcher-metadata",!0,[],[w.SERVER_HELD_STREAM]);const a=Ln(r);if(!a)return $("watcher-metadata",!0,[],[w.MISSING]);const s=typeof r.initialCursor=="string"?r.initialCursor:void 0;return $("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 Jn(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 $("goal-loop-continuity-metadata",a,o,a&&o.every(s=>!s)?[w.MISSING]:void 0)}function Gn(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 Kn(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 zn(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(zn);for(const s of n)et(e,s);(!a||Kn(t))&&et(e,t)}function Yn(e){const t=Gn(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 $("continuity-state-update-operation-log",t.length>0,r,t.length>0&&r.every(o=>!o)?[w.MISSING]:void 0)}function qn(e){const t=qe(e);return $("explicit-args",t.length>0,t.map(n=>Se("explicit-args",n)))}function Xn(e,t){const n=[Fn(e),Jn(e),Yn(e),qn(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 J(o.disabledReasonCodes);if(o.candidates.length!==1)return J([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 J(s.disabledReasonCodes);if(s.candidates.length>1)return J([w.AMBIGUOUS]);const c=s.candidates[0];if(c&&!Vn(a,c))return J([w.CONFLICT])}return{target:a.target,targetJobId:a.targetJobId,...a.initialCursor?{initialCursor:a.initialCursor}:{},source:a.source,serverHeldStream:!1}}return J([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":H},body:JSON.stringify(t),signal:o.signal});if(clearTimeout(a),!s.ok){const l=await s.text().catch(()=>"Unknown error");let d;try{d=JSON.parse(l)}catch{}return{ok:!1,status:s.status,error:d?`${d.error_code??"ERROR"}: ${d.message??l}`:`HTTP ${s.status}: ${l}`,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 Qn(e){const t=ce(e.projectRoot),n=e.platformTarget??"claude-code";Vt();const r=rn(),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 u=i instanceof Error?i.message:String(i);return process.stderr.write(`[Neocortex] state.json repair stopped unexpectedly: ${u}. No request was sent; inspect .neocortex/state.json and rerun.
18
- `),{success:!1,error:u,exitCode:1}}const a=Zt(t);try{const{maybeAutoResolveYoloopArgs:i}=await import("../yoloop/invoke-hooks.js"),u={args:e.args,projectRoot:t,logger:{info:C=>process.stderr.write(`${C}
19
- `),warn:C=>process.stderr.write(`${C}
20
- `)}};i(u),u.args!==e.args&&(e={...e,args:u.args})}catch(i){const u=i instanceof Error?i.message:String(i);process.stderr.write(`[Neocortex] Auto-resolve hook (P121.05) failed: ${u}. Proceeding with raw args.
21
- `)}try{const{readYoloopForRequest:i}=await import("../yoloop/invoke-hooks.js"),u=await i(e.args,t);u&&(a.yoloop=u)}catch{}try{const{readContinuityForRequest:i}=await import("../continuity/invoke-hooks.js"),u=await i(e.args,t);u&&(a.continuity=u)}catch(i){const u=i instanceof Error?i.message:String(i);process.stderr.write(`[Neocortex] continuity snapshot hook failed: ${u}. 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:u=>{console.warn(u)},info:u=>{console.error(u)}}})}catch(i){const u=i instanceof Error?i.message:String(i);process.stderr.write(`[Neocortex] discovery hook failed: ${u}. Proceeding without enrichment.
23
- `)}try{const{readArchitecturePolicy:i}=await import("../policy/architecture-policy.js"),u=await i(t);u&&(a.architecture_policy=u)}catch(i){const u=i instanceof Error?i.message:String(i);console.warn(`[Neocortex] architecture-policy hook failed: ${u}. Proceeding without policy.`)}try{const i=/^(1|true|on|yes)$/i.test(process.env.NEOCORTEX_GRAPH_RETRIEVAL??""),{maybeRunGraphRetrievalHook:u}=await import("../yoloop/invoke-hooks.js"),C=await u({args:e.args,projectRoot:t,featureFlag:i,logger:{warn:B=>process.stderr.write(`${B}
24
- `)}});C.applied&&C.metadata&&(a.graphRetrieval=C.metadata)}catch(i){const u=i instanceof Error?i.message:String(i);process.stderr.write(`[Neocortex] graph retrieval hook failed: ${u}. Proceeding without enrichment.
25
- `)}try{const{readAndConsumeCheckpoint:i}=await import("../checkpoint/index.js"),u=await i(t);u&&(a.implementCheckpoint=u)}catch(i){const u=i instanceof Error?i.message:String(i);process.stderr.write(`[Neocortex] checkpoint hook failed: ${u}. Proceeding without checkpoint.
26
- `)}const s=r?.licenseKey?new ye({cacheDir:Oe,passphrase:r.licenseKey}):null,c=e.args.trim();if(Bt(c))try{a.projectMemoryBootstrap=Ht(t)}catch(i){const u=i instanceof Error?i.message:String(i);process.stderr.write(`[Neocortex] project-memory bootstrap diagnosis failed: ${u}. Proceeding without local memory snapshot.
27
- `)}if(!c&&s){const i=await en(s);if(i)return{success:!0,instructions:i.instructions,metadata:i.metadata,exitCode:0}}const p=await on(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 u=ve(),C=Ae("NOT_CONFIGURED",u);C&&process.stderr.write(Te(C,u))}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 l=rt(c);if(l)try{const i=await p.tierClient.preFlightCheck(l);if(!i.allowed)return process.stderr.write(`[neocortex] ${i.message}
28
- `),{success:!1,error:i.message??"Trigger not available on your plan",exitCode:1}}catch{}const d=await En({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}
7
+ `)}catch{}}}function Yo(){me=!1}function Ke(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function In(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 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 he(e,t){if(!_(e))return;const n={};for(const o of t){const r=e[o];if(typeof r=="boolean")n[o]=r;else if(typeof r=="number"&&Number.isFinite(r))n[o]=r;else if(typeof r=="string"){const a=y(r);a&&(n[o]=a)}}return Object.keys(n).length>0?n:void 0}function Cn(e){if(!_(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 Sn(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"]),n=he(e.issueCloseAudit??e.issue_close_audit,["schema_version","event","storyId","epicId","issueNumber","closedAt","publicSafe","rawLogStorage"]),o=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}:{},...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}:{},...o?{scopedCiEvidence:o}:{}}}function bn(e){const t=j(e,".neocortex","state.json");if(!ee(t))return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}};let n;try{const u=z(t,"utf-8");n=JSON.parse(u)}catch{return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}try{const u=En(n);u.length>0&&_n(u)}catch{}const o=n.config??n.project??{},r=n.stories??{},a={};for(const[u,d]of Object.entries(r))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)}:{},...Sn(d),depends_on:Ke(d.depends_on),files_to_modify:In(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:Ke(d.depends_on)};const p=Cn(n.current_session??n.currentSession);return{schema_version:typeof n.schema_version=="number"?n.schema_version:void 0,config:{project_name:o.project_name??o.name??"unknown",default_branch:o.default_branch??"main",language:o.language??"pt-BR",yolo_mode:o.yolo_mode,user_name:o.user_name,worktree_base:o.worktree_base,max_parallel_stories:o.max_parallel_stories},stories:a,epics:c,...p?{current_session:p}:{}}}function Xo(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"}}function yn(){return yt()}async function vn(e,t,n={}){try{let o;if(t){const c=j(V,"cache");o=new It({cacheDir:c,passphrase:t})}else n.suppressMissingLicenseWarning||process.stderr.write(`[neocortex] Warning: No license key in config. Run "neocortex activate" to re-authenticate.
8
+ `),o=new Ct;const r=new _t({serverUrl:e,licenseKey:t??"",cacheProvider:o}),a=await r.getToken();if(!a)return null;const s=new bt({cacheProvider:o,licenseClient:r});return{token:a,client:r,tierClient:s}}catch{return null}}let ze=!1;function Ye(e){return{ok:!1,status:426,error:"PUBLIC_EXECUTION_UPGRADE_REQUIRED: Secure public execution response required.",errorBody:{error_code:"PUBLIC_EXECUTION_UPGRADE_REQUIRED",reason_code:e,supported_schema_version:Pe,min_secure_client_version:ie,fallback_action:"upgrade_client"}}}function An(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e,n={};typeof t.error_code=="string"&&(/^[A-Z0-9_]{1,96}$/.test(t.error_code)||qt.has(t.error_code))&&(n.error_code=t.error_code),typeof t.reason_code=="string"&&/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(t.reason_code)&&(n.reason_code=t.reason_code),typeof t.fallback_action=="string"&&/^[a-z0-9]+(?:_[a-z0-9]+)*$/.test(t.fallback_action)&&(n.fallback_action=t.fallback_action);for(const o of["min_secure_client_version","min_version"])typeof t[o]=="string"&&/^\d+\.\d+\.\d+$/.test(t[o])&&(n[o]=t[o]);return Number.isSafeInteger(t.supported_schema_version)&&Number(t.supported_schema_version)>0&&Number(t.supported_schema_version)<=100&&(n.supported_schema_version=t.supported_schema_version),Object.keys(n).length>0?n:void 0}function Xe(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 Tn(e,t,n){return`args-${Ae("sha256").update("invoke-materialization:v1").update(e).update(String(t)).update(JSON.stringify(n)).digest("hex")}`}async function qe(e,t,n,o){const r=await fetch(`${e}${t}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`,"X-Client-Version":je},body:JSON.stringify(n)}),a=await r.text().catch(()=>""),s=(()=>{try{return a?JSON.parse(a):{}}catch{return{}}})();if(!r.ok){const c=typeof s.error_code=="string"?s.error_code:`HTTP_${r.status}`,p=typeof s.message=="string"?s.message:"materialization upload failed";throw new Error(`${c}: ${p}`)}return s}async function wn(e,t,n){const o=Buffer.from(t,"utf8"),r=Rn(),a=[];for(let f=0,h=0;f<o.byteLength;f+=r,h++){const g=o.subarray(f,Math.min(f+r,o.byteLength));a.push({index:h,sha256:Xe(g),byteLength:g.byteLength})}const s=Xe(o),c=Tn(s,o.byteLength,a),p=Number(process.env.NEOCORTEX_INVOKE_CHUNK_TTL_SECONDS??"900");for(const f of a){const h=f.index*r,g=o.subarray(h,h+f.byteLength);await qe(e,"/api/v1/invoke/materialization/chunks",{manifestId:c,index:f.index,sha256:f.sha256,byteLength:f.byteLength,contentBase64:g.toString("base64"),ttlSeconds:p,idempotencyKey:`${c}:${f.index}:${f.sha256}`},n)}const d=(await qe(e,"/api/v1/invoke/materialization/manifests",{manifestId:c,sha256:s,byteLength:o.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 F(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function On(...e){const t=new Set,n=[];for(const o of e)for(const r of o??[]){const a=y(r);if(!(!a||t.has(a))&&(t.add(a),n.push(a),n.length>=16))return n}return n}function Nn(e){const t=e.graphRetrieval;if(!_(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 Ee(e,t=F(e),n=[],o={}){const r=e.stateSnapshot.scope,a=Object.keys(e.stateSnapshot.stories).length,s=Object.keys(e.stateSnapshot.epics).length,c=r?.kind??"full";return{schemaVersion:1,payloadBytes:t,limitBytes:o.limitBytes??$e,warningThresholdBytes:o.warningThresholdBytes??de,scope:{kind:c,...r?.projectionMode?{projectionMode:r.projectionMode}:{},commandId:r?.commandId??null,stateProjectionPolicy:r?.stateProjectionPolicy??null},includedStories:r?.includedStoryCount??a,omittedStories:r?.omittedStoryCount??0,includedEpics:r?.includedEpicCount??s,omittedEpics:r?.omittedEpicCount??0,graphRetrieval:Nn(e.stateSnapshot),reasonCodes:On(n,r?.reasonCodes),publicSafe:!0}}function xn(e){const t=_(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 Ln(e){return _(e)?{stableId:y(e.stableId)??"unknown",..._(e.source)?{source:e.source}:{},reasonCode:"budget_exceeded"}:{stableId:"unknown",reasonCode:"budget_exceeded"}}function Ze(e){const t=Array.isArray(e)?e.filter(n=>typeof n=="string"):[];return t.includes("budget_exceeded")?t:[...t,"budget_exceeded"]}function kn(e){const t=e.graphRetrieval;if(!_(t)||!Array.isArray(t.items))return e;const n=xn(t);let o=[...t.items],r=Array.isArray(t.skipped)?[...t.skipped]:[],a=t;for(;Buffer.byteLength(JSON.stringify(a),"utf8")>n&&o.length>0;){const s=o.pop();r=[...r,Ln(s)].slice(-32),a={...t,items:o,skipped:r,warnings:Ze(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:Ze(t.warnings)}),a===t?e:{...e,graphRetrieval:a}}function Pn(e,t={}){const n=t.limitBytes??$e,o=t.warningThresholdBytes??Math.floor(n*Be),r=F(e);if(r<=n)return{body:e,degraded:!1,telemetry:Ee(e,r,["payload-within-limit"],{limitBytes:n,warningThresholdBytes:o})};let a={...e,stateSnapshot:Tt(e.stateSnapshot)},s=["payload-size-guardrail","state-degraded"],c=F(a);c>n&&(a={...a,stateSnapshot:kn(a.stateSnapshot)},s=[...s,"graph-retrieval-budget-enforced"],c=F(a));const p=Ee(a,c,s,{limitBytes:n,warningThresholdBytes:o});if(c>n)throw new Je(p);return{body:a,degraded:!0,telemetry:p}}function Dn(e){return ut(e)??e.trim().split(/\s+/,1)[0]?.slice(0,80)??"(empty)"}function Qe(e){return e.args!==void 0?Dn(e.args):`argsRef:${e.argsRef.manifestId.slice(0,80)}`}function Un(e){const t=F(e);if(t<de)return t;const n=Ee(e,t,["payload-warning-threshold"]);return process.stderr.write(`[Neocortex] invoke payload near server limit: trigger=${Qe(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"}
9
+ `),t}function et(e,t){process.stderr.write(`[Neocortex] invoke payload guardrail: trigger=${Qe(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 jn(e){const t=Pt(e.args,{platformTarget:e.platformTarget,environment:e.environment??process.env});if(t.action==="skipped")return{shouldContinue:!0,attachToRequest:Mn(t),metadata:tt(t)};const n=e.bootstrapper??Ut;let o;try{o=await n({projectRoot:e.projectRoot,env:e.environment??process.env})}catch{o={ok:!1,attempted:!0,installed:!1,started:!1,cached:!1,projectKey:"unknown",reasonCodes:[Dt.UNEXPECTED_ERROR],publicSummary:"runner scheduler bootstrap stopped unexpectedly.",publicSafe:!0}}const r=tt(t,o);if(o.ok)return{shouldContinue:!0,attachToRequest:!0,metadata:r};const a=r.reasonCodes.slice(0,5).join(",");return t.failurePolicy==="fail-open"?{shouldContinue:!0,attachToRequest:!0,metadata:{...r,failOpenWarning:!0},warning:`Runner auto-bootstrap warning (${a}); continuing fail-open for operator command.`}:{shouldContinue:!1,attachToRequest:!1,metadata:r,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 Mn(e){return!e.reasonCodes.includes(kt.SKIPPED_NON_CONTINUITY_COMMAND)}function tt(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:w([...e.reasonCodes,...t?.reasonCodes??[]]),publicSummary:t?.publicSummary??e.publicSummary,publicSafe:!0}}function w(e){return Array.from(new Set(e.map(t=>t.slice(0,120))))}function ne(e,t,n){const o=Math.floor(e??t);return Number.isFinite(o)?Math.max(1,Math.min(n,o)):t}function oe(e,t){const n=process.env[e];if(!n)return t;const o=Number(n);return Number.isFinite(o)?o:t}function S(e,t=Ge){const n=typeof e=="string"&&e.trim().length>0?e.trim():"unknown",o=H(n,t),r=ln.test(o)?$:o;return r.length<=t?r:`${r.slice(0,t)}\u2026[TRUNCATED:${r.length-t}]`}function _e(e,t=Ge){if(!(typeof e!="string"||e.trim().length===0))return S(e,t)}function Ie(e,t,n,o){const r=_e(e?.targetId??t,120),a=e?.selectorKind??(r?Se(r):void 0),s=(e?.relatedJobIds??[]).map(c=>_e(c,120)).filter(c=>!!c);return{schemaVersion:1,contractVersion:"continuity-v1",targetResolutionState:n,...a?{targetKind:a}:{},...r?{targetId:r}:{},...t?{targetJobId:S(t,120)}:{},...e?.jobId?{jobId:S(e.jobId,120)}:{},...e?.goalId?{goalId:S(e.goalId,120)}:{},...e?.loopId?{loopId:S(e.loopId,120)}:{},...s.length>0?{relatedJobIds:s}:{},relatedJobCount:s.length,reasonCodes:w(o.length>0?o:[C.OK]),publicSafe:!0}}function P(e,t,n,o,r=[]){const a=(e?.redactions?.length??0)>0,s=e?a?"unsafe":n&&o===0?"empty":"available":"unavailable",c=_e(t[t.length-1]?.eventId,120),p=r.length>0?r:s==="unavailable"?[C.WATCH_SNAPSHOT_UNAVAILABLE]:s==="empty"?[C.WATCH_NO_SUMMARIES_YET]:[C.OK];return{schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:s,...e?.generatedAt?{generatedAt:S(e.generatedAt,80)}:{},renderedSummaryCount:o,...c?{latestEventId:c}:{},reasonCodes:w(p),publicSafe:!0}}function x(e,t,n,o,r=[],a){const s=o[o.length-1],c=n??s?.cursor,p=!!(c&&c!==t&&o.length>0),u=a??(p?"advanced":t||c?"unchanged":"not_started"),d=r.length>0?r:u==="advanced"?[C.WATCH_CURSOR_ADVANCED]:u==="unavailable"?[C.WATCH_EVIDENCE_UNAVAILABLE]:[C.WATCH_CURSOR_UNCHANGED];return{schemaVersion:1,contractVersion:"continuity-v1",cursorState:u,...e?{initialCursor:S(e,200)}:{},...t?{currentCursor:S(t,200)}:{},...c?{nextCursor:S(c,200)}:{},cursorAdvanced:p,...s?.eventId?{eventId:S(s.eventId,120)}:{},reasonCodes:w(d),publicSafe:!0}}function L(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:w([...e.reasonCodes??[],...t?.reasonCodes??[],...e.snapshotEvidence?.reasonCodes??[],...e.cursorEvidence?.reasonCodes??[]]),generatedAt:S(e.generatedAt??new Date().toISOString(),80),publicSafe:!0}}function $n(e){const t=e.targetKind&&e.targetId?`${e.targetKind}/${e.targetId}`:e.targetId??"[unresolved]",n=e.snapshotEvidence?.renderedSummaryCount??0,o=e.targetEvidence?.relatedJobCount??0,r=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=${o}`,`summaries=${n}`,`snapshot=${c}`,`generatedAt=${p}`,`cursor=${r}`,`current=${S(a,200)}`,`next=${S(s,200)}`,`advanced=${e.cursorEvidence?.cursorAdvanced??!1}`,`stop=${e.stopReason??"not_stopped"}`,`reasons=${e.reasonCodes.join(",")}`].join(" ")}function k(e,t,n){if(t==="json"){n.write(JSON.stringify(e)+`
11
+ `);return}n.write($n(e)+`
12
+ `)}function Bn(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,o){return{status:e,summariesEmitted:t,polls:n,reasonCodes:o.reasonCodes,watchStatus:o.watchStatus,stopReason:o.stopReason,targetEvidence:o.targetEvidence,snapshotEvidence:o.snapshotEvidence,cursorEvidence:o.cursorEvidence,statusRecord:o,metadata:Bn(o,t,n),publicSafe:!0}}function Wn(e){const t=e.reasonCode?` reason=${S(e.reasonCode,80)}`:"",n=e.goalId?` goal=${S(e.goalId,100)}`:"",o=e.loopId?` loop=${S(e.loopId,100)}`:"";return`[watch] ${S(e.createdAt,80)} event=${S(e.eventId,120)} job=${S(e.jobId,100)}${n}${o} execution=${S(e.executionId,120)}${t} -- ${S(e.publicSummary)}`}function Hn(e){return{type:"processing_summary",source:"local_continuity_sqlite",eventId:S(e.eventId,120),jobId:S(e.jobId,100),...e.goalId?{goalId:S(e.goalId,100)}:{},...e.loopId?{loopId:S(e.loopId,100)}:{},executionId:S(e.executionId,120),...e.reasonCode?{reasonCode:S(e.reasonCode,80)}:{},createdAt:S(e.createdAt,80),publicSummary:S(e.publicSummary),publicSafe:!0}}function Vn(e,t,n){if(t==="json"){n.write(JSON.stringify(Hn(e))+`
13
+ `);return}n.write(Wn(e)+`
14
+ `)}function Ce(e){return dn.has(e.status)}function Fn(e,t,n){if(t){const r=e.find(a=>a.jobId===t);return!!(r&&Ce(r))}return n<=0?!1:e.filter(r=>!Ce(r)).length===0}function Gn(e,t,n,o){return n<o?!1:t?!e.some(r=>r.jobId===t&&!Ce(r)):e.length===0}function Jn(e,t){return t?.aborted?Promise.resolve():new Promise(n=>{const o=setTimeout(r,e);function r(){clearTimeout(o),t?.removeEventListener("abort",r),n()}t?.addEventListener("abort",r,{once:!0})})}function Kn(e){return e.includes(R.MALFORMED)?"malformed":e.includes(R.AMBIGUOUS)?"ambiguous":e.includes("watch-target-multiple")?"multiple":e.includes("watch-evidence-unsafe")?"unsafe":e.includes(R.MISSING)||e.includes(v.TARGET_UNRESOLVED)?"unresolved":"unavailable"}function nt(e,t){const n=t?X(t):void 0,o=w([...e,v.TARGET_UNRESOLVED,C.WATCH_TARGET_UNRESOLVED]),r=Ie(n,n?.targetId,Kn(o),o),a=P({generatedAt:new Date().toISOString()},[],!1,0,[C.WATCH_TARGET_UNRESOLVED]),s=x(void 0,void 0,void 0,[],[C.WATCH_TARGET_UNRESOLVED],"unavailable");return L({watchStatus:"blocked",active:!1,targetEvidence:r,snapshotEvidence:a,cursorEvidence:s,stopReason:"target_unresolved",reasonCodes:o,generatedAt:a.generatedAt})}function zn(e,t,n,o){const r=nt(e,rt(t));return k(r,n,o),D("target-unresolved",0,0,r)}async function Yn(e){if(e.signal?.aborted){const E=Ie(e.target??X(e.targetJobId),e.targetJobId,e.target??e.targetJobId?"resolved":"unresolved",[v.CANCELLED]),m=P(void 0,[],!1,0),b=x(e.initialCursor,e.initialCursor,e.initialCursor,[],[v.CANCELLED],"unavailable"),W=L({watchStatus:"stopped",active:!1,targetEvidence:E,snapshotEvidence:m,cursorEvidence:b,stopReason:"cancelled",reasonCodes:[v.CANCELLED]});return D("cancelled",0,0,W)}const t=e.target??X(e.targetJobId),n=e.targetJobId??t?.targetId,o=e.stdout??process.stdout;if(!t){const E=nt([R.MISSING,v.TARGET_UNRESOLVED]);return k(E,e.format,o),D("target-unresolved",0,0,E)}const r=ne(e.limit??oe("NEOCORTEX_INVOKE_WATCH_LIMIT",Ne),Ne,50),a=Math.max(50,ne(e.pollIntervalMs??oe("NEOCORTEX_INVOKE_WATCH_POLL_INTERVAL_MS",ke),ke,6e4)),s=ne(e.maxIdlePolls??oe("NEOCORTEX_INVOKE_WATCH_MAX_IDLE_POLLS",xe),xe,120),c=ne(e.maxPolls??oe("NEOCORTEX_INVOKE_WATCH_MAX_POLLS",Le),Le,86400),p=e.sleep??Jn;let u=e.initialCursor,d=0,f=0,h=0;const g=Ie(t,n,"resolved",[C.OK]),Z={schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:"pending",renderedSummaryCount:0,reasonCodes:[C.WATCH_RENDER_PENDING],publicSafe:!0},I=x(e.initialCursor,u,u,[],e.initialCursor?[C.WATCH_CURSOR_UNCHANGED]:[C.WATCH_NO_SUMMARIES_YET],e.initialCursor?"unchanged":"not_started");k(L({watchStatus:"active",active:!0,targetEvidence:g,snapshotEvidence:Z,cursorEvidence:I,stopReason:"not_stopped",reasonCodes:[C.OK]}),e.format,o);let U;try{U=await jt({projectRoot:e.projectRoot})}catch{const E=P(void 0,[],!1,d,[C.WATCH_SNAPSHOT_UNAVAILABLE]),m=x(e.initialCursor,u,u,[],[C.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),b=L({watchStatus:"blocked",active:!1,targetEvidence:g,snapshotEvidence:E,cursorEvidence:m,stopReason:"unavailable_evidence",reasonCodes:[v.STORE_UNAVAILABLE]});return k(b,e.format,o),D("store-unavailable",d,h,b)}try{for(;!e.signal?.aborted&&h<c;){h+=1;const E=u,m=U.collectProcessingOutputSummaryCursor({...u?{cursor:u}:{},...t?{target:t}:{},...n?{jobId:n}:{},limit:r}),b=U.collectSnapshot({jobLimit:50,processingSummaryLimit:1}),W=b.jobs;if(m.summaries.length>0){for(const J of m.summaries)Vn(J,e.format,o),d+=1;u=m.nextCursor??m.summaries[m.summaries.length-1]?.cursor??u,f=0}else u=m.nextCursor??u,f+=1;const gt=P(b,m.summaries,!0,m.summaries.length),mt=x(e.initialCursor,E,u,m.summaries,m.summaries.length>0?[C.WATCH_CURSOR_ADVANCED]:[C.WATCH_NO_SUMMARIES_YET]);if(k(L({watchStatus:m.summaries.length>0?"polling":"waiting",active:!0,targetEvidence:g,snapshotEvidence:gt,cursorEvidence:mt,stopReason:"not_stopped",reasonCodes:m.summaries.length>0?[C.WATCH_CURSOR_ADVANCED]:[C.WATCH_NO_SUMMARIES_YET],generatedAt:b.generatedAt}),e.format,o),!m.hasMore&&Fn(W,n,d)){const J=P(b,m.summaries,!1,d,[v.COMPLETED]),ae=x(e.initialCursor,E,u,m.summaries,[v.COMPLETED],"exhausted"),K=L({watchStatus:"stopped",active:!1,targetEvidence:g,snapshotEvidence:J,cursorEvidence:ae,stopReason:"not_stopped",reasonCodes:[v.COMPLETED],generatedAt:b.generatedAt});return k(K,e.format,o),D("completed",d,h,K)}if(!m.hasMore&&Gn(W,n,f,s)){const J=P(b,m.summaries,!1,d,[C.WATCH_STOP_IDLE_LIMIT_REACHED]),ae=x(e.initialCursor,E,u,m.summaries,[C.WATCH_STOP_IDLE_LIMIT_REACHED],"exhausted"),K=L({watchStatus:"stopped",active:!1,targetEvidence:g,snapshotEvidence:J,cursorEvidence:ae,stopReason:"idle_limit_reached",reasonCodes:[v.IDLE_TIMEOUT,C.WATCH_STOP_IDLE_LIMIT_REACHED],generatedAt:b.generatedAt});return k(K,e.format,o),D("idle-timeout",d,h,K)}m.hasMore||await p(a,e.signal)}}catch{const E=P(void 0,[],!1,d,[C.WATCH_SNAPSHOT_UNAVAILABLE]),m=x(e.initialCursor,u,u,[],[C.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),b=L({watchStatus:"blocked",active:!1,targetEvidence:g,snapshotEvidence:E,cursorEvidence:m,stopReason:"unavailable_evidence",reasonCodes:[v.STORE_UNAVAILABLE]});return k(b,e.format,o),D("store-unavailable",d,h,b)}finally{U.close()}if(e.signal?.aborted){const E=P(void 0,[],!1,d,[v.CANCELLED]),m=x(e.initialCursor,u,u,[],[v.CANCELLED],"unavailable"),b=L({watchStatus:"stopped",active:!1,targetEvidence:g,snapshotEvidence:E,cursorEvidence:m,stopReason:"cancelled",reasonCodes:[v.CANCELLED]});return k(b,e.format,o),D("cancelled",d,h,b)}const Q=P(void 0,[],!1,d,[C.WATCH_STOP_MAX_POLLS_REACHED]),i=x(e.initialCursor,u,u,[],[C.WATCH_STOP_MAX_POLLS_REACHED],"exhausted"),l=L({watchStatus:"stopped",active:!1,targetEvidence:g,snapshotEvidence:Q,cursorEvidence:i,stopReason:"max_polls_reached",reasonCodes:[v.MAX_POLLS,C.WATCH_STOP_MAX_POLLS_REACHED]});return k(l,e.format,o),D("max-polls",d,h,l)}function O(e){const t=e.trim().replace(/^@/,"").match(/^(job|goal|loop)-([JGL])(\d{3,})$/i);if(!t)return;const n=t[1].toLowerCase(),o=t[2].toUpperCase();if(!(n==="job"&&o!=="J"||n==="goal"&&o!=="G"||n==="loop"&&o!=="L"))return`${n}-${o}${t[3]}`}function Se(e){if(e.startsWith("job-J"))return"job";if(e.startsWith("goal-G"))return"goal";if(e.startsWith("loop-L"))return"loop"}function ot(e){const t=[],n=/(?:^|[\s"'([,{])@?(job-[Jj]\d{3,}|goal-[Gg]\d{3,}|loop-[Ll]\d{3,})(?=$|[\s"')\]},.;:!?])/g;let o;for(;(o=n.exec(e))!==null;){const r=O(o[1]);r&&t.push(r)}return w(t)}function rt(e){return ot(e)[0]}function X(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 be(e){return w(e.filter(t=>typeof t=="string").map(t=>O(t)).filter(t=>!!t?.startsWith("job-J")))}function Xn(e,t){const n=be(t).filter(o=>o!==e.targetId&&o!==e.jobId);return n.length>0?{...e,relatedJobIds:n}:e}function qn(e){if(!e)return;const t=_(e.target)?e.target:void 0,n=typeof e.selectorKind=="string"?e.selectorKind:typeof t?.selectorKind=="string"?t.selectorKind:void 0,o=typeof e.targetId=="string"?O(e.targetId):typeof t?.targetId=="string"?O(t.targetId):typeof e.targetJobId=="string"?O(e.targetJobId):void 0,r=X(o);if(!r||n&&n!==r.selectorKind)return;const a=Array.isArray(e.relatedJobIds)?e.relatedJobIds:Array.isArray(t?.relatedJobIds)?t.relatedJobIds:void 0,s=be([...a??[],e.jobId,t?.jobId,e.targetJobId,t?.targetJobId]).filter(c=>c!==r.targetId&&c!==r.jobId);return{...r,...typeof(e.jobId??t?.jobId)=="string"?{jobId:O(e.jobId??t?.jobId)??r.jobId}:{},...typeof(e.goalId??t?.goalId)=="string"?{goalId:O(e.goalId??t?.goalId)??r.goalId}:{},...typeof(e.loopId??t?.loopId)=="string"?{loopId:O(e.loopId??t?.loopId)??r.loopId}:{},...s.length>0?{relatedJobIds:s}:{}}}function at(e){const t=e.trim().split(/\s+/).filter(Boolean),n=t[0]?.replace(/^\*/,"").toLowerCase(),o=t[1]?.replace(/^--/,"").toLowerCase();return(n==="jobs"||n==="job"||n==="continuity-jobs"||n==="61")&&o==="watch"}const A=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"}),Zn=new Set(["create","start","resume"]),Qn=new Set(["create","resume","run-once"]);function ye(e,t,n,o,r){return{schemaVersion:1,contractVersion:"continuity-v1",...n?{command:n}:{},...o?{operation:o}:{},active:e,...r?{watchToken:r}:{},reasonCodes:w(t),serverHeldStream:!1,allJobsPolling:!1,targetResolution:e?"required-after-dispatch":"inactive",publicSafe:!0}}function T(e,t=[],n,o){const r=t.length>0?t:[A.INACTIVE];return{args:e,watch:!1,reasonCodes:r,metadata:ye(!1,r,n,o),publicSafe:!0}}function eo(e){const t=e.trim().split(/\s+/).filter(Boolean),n=t.slice(2).filter(a=>a==="--watch").length;if(n===0)return T(e,[],"jobs","watch");if(n!==1)return T(e,[A.AMBIGUOUS],"jobs","watch");const o=t.filter((a,s)=>s<2||a!=="--watch").join(" ");return at(o)?o.trim().split(/\s+/).filter(Boolean).slice(2).length!==1?T(e,[A.AMBIGUOUS],"jobs","watch"):rt(o)?{args:o,watch:!0,reasonCodes:[A.ACTIVE],metadata:ye(!0,[A.ACTIVE],"jobs","watch"),publicSafe:!0}:T(e,[A.TARGET_INVALID],"jobs","watch"):T(e,[A.UNSUPPORTED],"jobs","watch")}function to(e){const t=[];let n=!1,o=0;for(;o<e.length;){for(;o<e.length&&/\s/.test(e[o]);)o+=1;if(o>=e.length)break;const r=o;let a="",s=!1,c=null;for(;o<e.length;){const p=e[o];if(c){if(p===c){s=!0,c=null,o+=1;continue}if(p==="\\"&&o+1<e.length){a+=e[o+1],o+=2;continue}a+=p,o+=1;continue}if(/\s/.test(p))break;if(p==='"'||p==="'"){s=!0,c=p,o+=1;continue}a+=p,o+=1}c&&(n=!0),t.push({value:a,start:r,end:o,quoted:s})}return{tokens:t,malformed:n}}function no(e){if(!e||e.quoted)return;const t=e.value.replace(/^\*/,"").toLowerCase();return t==="goal"||t==="loop"?t:void 0}function oo(e,t){if(!e||e==="jobs"||!t||t.quoted)return;const n=t.value.toLowerCase();return(e==="goal"?Zn:Qn).has(n)?n:void 0}function ro(e){return!e.quoted&&e.value!=="--watch"&&e.value.toLowerCase().startsWith("--watch")}function ao(e){const{tokens:t,malformed:n}=to(e),o=no(t[0]),r=oo(o,t[1]);if(n)return T(e,[A.MALFORMED],o,r);const a=t.filter(h=>h.value==="--watch"&&!h.quoted),s=t.filter(h=>h.value==="--watch"&&h.quoted),c=t.filter(ro);if(!(a.length>0||s.length>0||c.length>0))return T(e,[],o,r);if(a.length>1)return T(e,[A.DUPLICATE],o,r);if(a.length===1&&(s.length>0||c.length>0))return T(e,[A.AMBIGUOUS],o,r);if(s.length>0)return T(e,[A.QUOTED],o,r);if(c.length>0)return T(e,[A.MALFORMED],o,r);const u=a[0];if(!u)return T(e,[],o,r);if(t[t.length-1]!==u)return T(e,[A.NON_FINAL],o,r);if(!o||!r)return T(e,[A.UNRESOLVED],o,r);const d=`${e.slice(0,u.start)}${e.slice(u.end)}`.trim(),f={literal:"--watch",position:"final",start:u.start,end:u.end,quoted:!1,publicSafe:!0};return{args:d,watch:!0,reasonCodes:[A.ACTIVE],metadata:ye(!0,[A.ACTIVE],o,r,f),publicSafe:!0}}function so(e){return at(e)?eo(e):ao(e)}function io(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&un.has(t)):[]}function G(e){return{disabled:!0,reasonCodes:w(e.length>0?e:[R.MISSING])}}function ve(e,t,n=[],o){const r=X(t);if(r)return{source:e,target:Xn(r,n),targetJobId:r.targetId,...o?{initialCursor:o}:{},serverHeldStream:!1}}function co(e){const t=new Map;for(const n of e){const o=`${n.target.selectorKind}:${n.target.targetId}`,r=t.get(o);if(!r){t.set(o,n);continue}const a=w([...r.target.relatedJobIds??[],...n.target.relatedJobIds??[]]);t.set(o,{...r,target:a.length>0?{...r.target,relatedJobIds:a}:r.target,initialCursor:r.initialCursor??n.initialCursor})}return Array.from(t.values())}function B(e,t,n,o){return{source:e,hasEvidence:t,candidates:co(n.filter(r=>!!r)),...o&&o.length>0?{disabledReasonCodes:w(o)}:{}}}function uo(e,t){return e.target.selectorKind===t.target.selectorKind&&e.target.targetId===t.target.targetId}function q(e,t){const n=w(e.filter(o=>typeof o=="string").map(o=>O(o)).filter(o=>!!o));if(t){const o=n.find(r=>Se(r)===t);if(o)return o}return n[0]}function re(e,t){return w(e.filter(n=>typeof n=="string").map(n=>O(n)).filter(n=>!!n)).find(n=>Se(n)===t)}function lo(e){const t=_(e?.continuity)?e.continuity:void 0,n=_(t?.jobs)?t.jobs:void 0,o=_(n?.watcher)?n.watcher:void 0,r=io(o?.reasonCodes??n?.reasonCodes);if(!o)return B("watcher-metadata",r.length>0,[],r);if(o.active===!1||r.length>0)return B("watcher-metadata",!0,[],r.length>0?r:[R.MALFORMED]);if(o.serverHeldStream!==!1)return B("watcher-metadata",!0,[],[R.SERVER_HELD_STREAM]);const a=qn(o);if(!a)return B("watcher-metadata",!0,[],[R.MISSING]);const s=typeof o.initialCursor=="string"?o.initialCursor:void 0;return B("watcher-metadata",!0,[{source:"watcher-metadata",target:a,targetJobId:a.targetId,...s?{initialCursor:s}:{},serverHeldStream:!1}])}function st(e,t){const n=_(e.loopJobPlan)?e.loopJobPlan:void 0,o=_(n?.metadata)?n.metadata:void 0,r=_(e.metadata)?e.metadata:void 0,s=(t==="goal"?q([e.goalId,e.targetGoalId,e.campaignId,e.jobId,e.targetJobId,r?.goalId,r?.campaignId,r?.jobId],"goal"):q([e.loopId,e.targetLoopId,e.jobId,e.targetJobId,r?.loopId,r?.jobId,o?.loopId,o?.jobId],"loop"))??q([e.jobId,e.targetJobId,r?.jobId,o?.jobId]);return ve("goal-loop-continuity-metadata",s,[e.jobId,e.targetJobId,r?.jobId,o?.jobId])}function po(e){const t=_(e?.continuity)?e.continuity:void 0,n=_(t?.goal)?t.goal:void 0,o=_(t?.loop)?t.loop:void 0,r=[n?st(n,"goal"):void 0,o?st(o,"loop"):void 0],a=!!(n||o);return B("goal-loop-continuity-metadata",a,r,a&&r.every(s=>!s)?[R.MISSING]:void 0)}function fo(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 it(e,t){const n=_(t.metadata)?t.metadata:void 0,o=re([t.goalId,t.targetGoalId,t.campaignId,n?.goalId,n?.campaignId,t.jobId,n?.jobId],"goal"),r=re([t.loopId,t.targetLoopId,n?.loopId,t.jobId,n?.jobId],"loop"),a=q([t.jobId,t.targetJobId,n?.jobId],"job"),s=o??r??a;if(!s)return;const c=e.get(s)??{targetId:s,relatedJobIds:[]};c.relatedJobIds.push(...be([a,t.jobId,t.targetJobId,n?.jobId])),e.set(s,c)}function go(e){const t=_(e.metadata)?e.metadata:void 0;return!!(re([e.goalId,e.targetGoalId,e.campaignId,t?.goalId,t?.campaignId,e.jobId,t?.jobId],"goal")??re([e.loopId,e.targetLoopId,t?.loopId,e.jobId,t?.jobId],"loop"))}function mo(e){const t=_(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 ct(e,t){const n=[];for(const s of["metadata","job","event","receipt","processingOutputSummary"]){const c=t[s];_(c)&&n.push(c)}const o=_(t.event)?t.event:void 0;_(o?.metadata)&&n.push(o.metadata),_(o?.processingOutputSummary)&&n.push(o.processingOutputSummary);const r=_(t.receipt)?t.receipt:void 0;_(r?.metadata)&&n.push(r.metadata);const a=n.some(mo);for(const s of n)it(e,s);(!a||go(t))&&it(e,t)}function ho(e){const t=fo(e?.continuityStateUpdate),n=new Map;for(const r of t){ct(n,r);const a=Array.isArray(r.operations)?r.operations.filter(_):[];for(const s of a)ct(n,s)}const o=Array.from(n.values()).map(r=>ve("continuity-state-update-operation-log",r.targetId,r.relatedJobIds));return B("continuity-state-update-operation-log",t.length>0,o,t.length>0&&o.every(r=>!r)?[R.MISSING]:void 0)}function Eo(e){const t=ot(e);return B("explicit-args",t.length>0,t.map(n=>ve("explicit-args",n)))}function _o(e,t){const n=[lo(e),po(e),ho(e),Eo(t)];for(let o=0;o<n.length;o+=1){const r=n[o];if(!r.hasEvidence)continue;if(r.disabledReasonCodes&&r.disabledReasonCodes.length>0)return G(r.disabledReasonCodes);if(r.candidates.length!==1)return G([r.candidates.length>1?R.AMBIGUOUS:R.MISSING]);const a=r.candidates[0];for(const s of n.slice(o+1)){if(!s.hasEvidence)continue;if(s.disabledReasonCodes&&s.disabledReasonCodes.length>0)return G(s.disabledReasonCodes);if(s.candidates.length>1)return G([R.AMBIGUOUS]);const c=s.candidates[0];if(c&&!uo(a,c))return G([R.CONFLICT])}return{target:a.target,targetJobId:a.targetJobId,...a.initialCursor?{initialCursor:a.initialCursor}:{},source:a.source,serverHeldStream:!1}}return G([R.MISSING])}async function dt(e,t,n){const o=`${e}/api/v1/invoke`,r=new AbortController,a=setTimeout(()=>r.abort(),Ue);try{const s=await fetch(o,{method:"POST",headers:cn(n),body:JSON.stringify(t),signal:r.signal});if(clearTimeout(a),!s.ok){const f=await s.text().catch(()=>"Unknown error");let h;try{h=An(JSON.parse(f))}catch{}const g=typeof h?.error_code=="string"?h.error_code:"HTTP_ERROR";return{ok:!1,status:s.status,error:`${g}: Request rejected with HTTP ${s.status}.`,errorBody:h}}let c;try{c=await s.json()}catch{return Ye("public-execution-invalid-envelope")}const p=De(c);if(!p.ok)return Ye(p.issues[0]?.reasonCode??"public-execution-invalid-envelope");const u=s.headers.get("X-Client-Version-Warning");u&&!ze&&(ze=!0,process.stderr.write(`
15
+ [Neocortex] ${u}
16
+
17
+ `));const d=s.headers.get("X-Neocortex-Checkpoint-Ack")??void 0;return{ok:!0,status:s.status,data:p.value,...d&&/^ckpt-[a-f0-9]{64}$/.test(d)?{checkpointAck:d}:{}}}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 ${Ue/1e3}s`:`Network error: ${c}`}}}async function Io(e){const t=ue(e.projectRoot),n=nn(e,t);tn();const o=an({env:e.environment??process.env,platformTarget:n}),r=yn(),a=(e.serverUrl??r?.serverUrl??vt).replace(/\/+$/,"");try{Ot(t,{args:e.args})}catch(i){if(i instanceof Nt)return process.stderr.write(`${i.message}
18
+ `),{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.
19
+ `),{success:!1,error:l,exitCode:1}}const s=bn(t);try{const{maybeAutoResolveYoloopArgs:i}=await import("../yoloop/invoke-hooks.js"),l={args:e.args,projectRoot:t,logger:{info:E=>process.stderr.write(`${E}
20
+ `),warn:E=>process.stderr.write(`${E}
21
+ `)}};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.
22
+ `)}try{const{readYoloopForRequest:i}=await import("../yoloop/invoke-hooks.js"),l=await i(e.args,t);l&&(s.yoloop=l)}catch{}try{const{readContinuityForRequest:i}=await import("../continuity/invoke-hooks.js"),l=await i(e.args,t);l&&(s.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.
23
+ `)}try{const{maybeRunDiscoveryHook:i}=await import("../yoloop/invoke-hooks.js");await i({args:e.args,projectRoot:t,stateSnapshot:s,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.
24
+ `)}try{const{readArchitecturePolicy:i}=await import("../policy/architecture-policy.js"),l=await i(t);l&&(s.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"),E=await l({args:e.args,projectRoot:t,featureFlag:i,logger:{warn:m=>process.stderr.write(`${m}
25
+ `)}});E.applied&&E.metadata&&(s.graphRetrieval=E.metadata)}catch(i){const l=i instanceof Error?i.message:String(i);process.stderr.write(`[Neocortex] graph retrieval hook failed: ${l}. Proceeding without enrichment.
26
+ `)}try{const{runProjectEvidenceHook:i}=await import("../graph-retrieval/pre-command-hook.js"),l=await i({args:e.args,projectRoot:t,enabled:process.env.NEOCORTEX_PROJECT_EVIDENCE!=="off",logger:{warn:E=>process.stderr.write(`${E}
27
+ `)}});l.applied&&l.envelope&&(s.projectEvidence=l.envelope)}catch{process.stderr.write(`[Neocortex] local project evidence collection failed; proceeding without project evidence.
28
+ `)}const c=e.args.trim();if(Qt(c))try{s.projectMemoryBootstrap=en(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.
29
+ `)}const p=await vn(a,r?.licenseKey,{suppressMissingLicenseWarning:o.codexCli&&o.remediation!=="activate"});if(!p){const i=sn(o),l=r&&!r.licenseKey?" This may be caused by a machine fingerprint change (e.g., hardware or hostname change).":"";try{const E=Oe(),m=Te(i?.humanizedErrorCode??"NOT_CONFIGURED",E);m&&process.stderr.write(we(m,E))}catch{}return i?(process.stderr.write(`[Neocortex] Codex auth diagnosis reason=${i.reasonCode}; checked ${o.publicPath??M}.
30
+ `),{success:!1,error:i.error,errorCode:i.errorCode,reasonCode:i.reasonCode,exitCode:2}):{success:!1,error:`Not authenticated.${l} Visit https://neocortex.sh/portal/login to get your license key, then run: neocortex activate YOUR-LICENSE-KEY`,exitCode:2}}const u=ut(c);if(u)try{const i=await p.tierClient.preFlightCheck(u);if(!i.allowed)return process.stderr.write(`[neocortex] ${i.message}
31
+ `),{success:!1,error:i.message??"Trigger not available on your plan",exitCode:1}}catch{}const d=await jn({args:c,projectRoot:t,platformTarget:n,environment:e.environment??process.env,bootstrapper:e.runnerBootstrapper});if(d.attachToRequest&&(s.runnerBootstrap=d.metadata),d.warning&&process.stderr.write(`[Neocortex] ${d.warning}
29
32
  `),!d.shouldContinue)return d.error&&process.stderr.write(`[Neocortex] ${d.error}
30
- `),{success:!1,error:d.error??"Runner auto-bootstrap required but failed.",errorCode:d.errorCode,exitCode:d.exitCode??1};const S=yt(c,a);let m={args:c,projectRoot:t.replace(se(),"~"),stateSnapshot:S,platformTarget:n};const I=F(m);if(e.inputSource&&e.inputSource!=="args"&&I>=ie)try{m={argsRef:(await cn(o,c,p.token)).argsRef,projectRoot:t.replace(se(),"~"),stateSnapshot:S,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=mn(m);m=i.body,i.degraded?Ke(m,i.telemetry):hn(m)}catch(i){if(i instanceof We)return Ke(m,i.telemetry),process.stderr.write(`[Neocortex] ${i.message}
31
- `),{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 u=await p.client.forceRefresh();u&&(f=await nt(o,m,u))}}if(!f.ok&&f.status===426){const i=f.errorBody,u=i?.upgrade_command??"npm install -g @ornexus/neocortex@latest",C=i?.min_version??"unknown";return process.stderr.write(`
33
+ `),{success:!1,error:d.error??"Runner auto-bootstrap required but failed.",errorCode:d.errorCode,exitCode:d.exitCode??1};let f;try{const{claimCheckpoint:i}=await import("../checkpoint/index.js");f=await i(t),f&&(s.implementCheckpoint=f.snapshot)}catch(i){const l=i instanceof Error?i.message:String(i);process.stderr.write(`[Neocortex] checkpoint claim failed: ${l}. Proceeding without checkpoint.
34
+ `)}let h;try{h=wt(c,s)}catch(i){throw await f?.release().catch(()=>{}),i}let g={args:c,projectRoot:t.replace(se(),"~"),stateSnapshot:h,platformTarget:n};const Z=F(g);if(e.inputSource&&e.inputSource!=="args"&&Z>=de)try{g={argsRef:(await wn(a,c,p.token)).argsRef,projectRoot:t.replace(se(),"~"),stateSnapshot:h,platformTarget:n}}catch(i){const l=i instanceof Error?i.message:String(i);return await f?.release().catch(()=>{}),{success:!1,error:`INVOKE_MATERIALIZATION_FAILED: ${l}`,errorCode:"INVOKE_MATERIALIZATION_FAILED",exitCode:1}}try{const i=Pn(g);g=i.body,i.degraded?et(g,i.telemetry):Un(g)}catch(i){if(i instanceof Je)return et(g,i.telemetry),process.stderr.write(`[Neocortex] ${i.message}
35
+ `),await f?.release().catch(()=>{}),{success:!1,error:i.message,errorCode:i.code,metadata:{invokePayload:i.telemetry},exitCode:1};throw await f?.release().catch(()=>{}),i}let I=await dt(a,g,p.token);if(!I.ok&&I.status===401){const i=I.errorBody?.fallback_action;if(i==="refresh_token"||i==="re_authenticate"){const l=await p.client.forceRefresh();l&&(I=await dt(a,g,l))}}if(f)try{I.ok&&I.checkpointAck===f.deliveryId?await f.ack():await f.release()}catch(i){const l=i instanceof Error?i.message:String(i);process.stderr.write(`[Neocortex] checkpoint disposition failed: ${l}. Any remaining claim stays lease-recoverable.
36
+ `)}if(!I.ok&&I.status===426){const i=I.errorBody,l=i?.min_secure_client_version??i?.min_version,E=typeof l=="string"&&/^\d+\.\d+\.\d+$/.test(l)?l:ie,m=i?.reason_code,b=typeof m=="string"&&/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(m)?m:"public-execution-upgrade-required",W="npm install -g @ornexus/neocortex@latest";return process.stderr.write(`
32
37
  `),process.stderr.write(`==================================================
33
- `),process.stderr.write(` UPGRADE REQUIRED
38
+ `),process.stderr.write(` PUBLIC EXECUTION UPGRADE REQUIRED
34
39
  `),process.stderr.write(`==================================================
35
40
  `),process.stderr.write(`
36
- Your Neocortex version (${H}) is no longer supported.
37
- `),process.stderr.write(` Minimum required: ${C}
41
+ Reason: ${b}
42
+ `),process.stderr.write(` Secure minimum: ${E}
38
43
 
39
44
  `),process.stderr.write(` Run this command to update:
40
45
 
41
- `),process.stderr.write(` ${u}
42
-
43
- `),process.stderr.write(` After updating, re-run your command.
44
- `),process.stderr.write(`==================================================
45
-
46
- `),{success:!1,error:`UPGRADE_REQUIRED: Client version ${H} is below minimum ${C}. Run: ${u}`,exitCode:3}}if(!f.ok||!f.data){const i=f.status===401?2:(f.status===429||f.status>=500,1);try{const u=f.errorBody?.error_code??(f.status===429?"RATE_LIMITED":f.status>=500?"SERVER_ERROR":void 0);if(u){const C=ve(),B=Ae(u,C);B&&process.stderr.write(Te(B,C))}}catch{}return{success:!1,error:V(f.error??"Unknown error from server",ee),exitCode:i}}if(!c&&f.data.metadata?.mode==="menu"&&s&&tn(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(`
47
- `),process.stderr.write(`==================================================
48
- `),process.stderr.write(` YOLOOP CLIENT UPGRADE REQUIRED
49
- `),process.stderr.write(`==================================================
50
- `),process.stderr.write(`
51
- Your Neocortex client version (${H}) does not
52
- `),process.stderr.write(` support client-side yoloop state persistence.
53
-
54
- `),process.stderr.write(` Run this command to upgrade:
55
-
56
- `),process.stderr.write(` npm install -g @ornexus/neocortex@latest
46
+ `),process.stderr.write(` ${W}
57
47
 
58
- `),process.stderr.write(` After upgrading, re-run your yoloop command.
48
+ `),process.stderr.write(` Update the client/server pair and re-run the command.
59
49
  `),process.stderr.write(`==================================================
60
50
 
61
- `),{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"),u=await i(f.data.metadata,t);if(!u.ok){const C=u.reasonCodes.join(",");return process.stderr.write(`[Neocortex] continuity persistence failed: ${C}. No continuity mutation was committed.
62
- `),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${C}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}}catch(i){const u=i instanceof Error?i.message:String(i);return process.stderr.write(`[Neocortex] continuity persistence hook failed: ${u}. No continuity mutation was committed.
63
- `),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${V(u,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}
64
- `)):process.stderr.write(`[Neocortex] Seu tier foi atualizado para ${i}! Execute "neocortex activate" para obter um token atualizado.
65
- `)}catch{process.stderr.write(`[Neocortex] Seu tier foi atualizado para ${i}! Execute "neocortex activate" para obter um token atualizado.
66
- `)}}const L=ue(f.data.instructions,f.data.metadata);return{success:!0,instructions:L.instructions,metadata:L.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>.",Zn=`
51
+ `),{success:!1,error:`PUBLIC_EXECUTION_UPGRADE_REQUIRED: ${b}. Secure minimum ${E}. Run: ${W}`,errorCode:"PUBLIC_EXECUTION_UPGRADE_REQUIRED",exitCode:3}}if(!I.ok||!I.data){const i=I.status===401?2:(I.status===429||I.status>=500,1);try{const l=I.errorBody?.error_code??(I.status===429?"RATE_LIMITED":I.status>=500?"SERVER_ERROR":void 0);if(l){const E=Oe(),m=Te(l,E);m&&process.stderr.write(we(m,E))}}catch{}return{success:!1,error:H(I.error??"Unknown error from server",ce),errorCode:typeof I.errorBody?.error_code=="string"?H(I.errorBody.error_code,96):void 0,exitCode:i}}let U;try{U=hn(I.data)}catch{return{success:!1,error:new Fe().message,errorCode:"PUBLIC_EXECUTION_UPGRADE_REQUIRED",exitCode:3}}const Q=fe(U.instructions,U.metadata);return{success:!0,instructions:Q.instructions,metadata:Q.metadata,exitCode:0}}function ut(e){const[t]=e.trim().split(/\s+/,1);return t?/^@?epic-[a-z0-9][a-z0-9._-]*$/i.test(t)?"epic":St(t):null}const lt="Provide exactly one invoke input source: --args <string>, --stdin, or --args-file <path>.",Co=`
67
52
  neocortex-client invoke - Send orchestration request to server
68
53
 
69
54
  Usage:
@@ -130,11 +115,11 @@ Safety:
130
115
  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.
131
116
  Jobs, goal and loop watch use serverHeldStream=false and foreground local SQLite polling of public processing summaries only.
132
117
  Unresolved targets disable polling with public reason codes; there is no all-jobs fallback.
133
- `.trim();function er(e){return e.includes("--help")||e.includes("-h")||e.includes("help")}function at(e){return new k("INVOKE_INPUT_VALUE_MISSING",`${e} requires a value. ${ot}`)}function tr(e){try{if(!pt(e).isFile())throw new k("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 k?t:new k("INVOKE_ARGS_FILE_READ_FAILED","--args-file could not be read as UTF-8 text. Check the path and permissions.")}}function nr(){try{if(process.stdin.isTTY)throw new k("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 k?e:new k("INVOKE_STDIN_READ_FAILED","--stdin could not be read as UTF-8 text. Pipe command text into stdin and retry.")}}function rr(e,t={}){let n,r=!1,o,a,s="plain",c=!1,p;for(let I=0;I<e.length;I++)switch(e[I]){case"--args":{const L=e[++I];if(L===void 0)throw at("--args");n=L;break}case"--stdin":r=!0;break;case"--args-file":{const L=e[++I];if(L===void 0)throw at("--args-file");o=L;break}case"--project-root":a=e[++I];break;case"--format":s=e[++I]??"plain";break;case"--watch":c=!0;break;case"--server-url":p=e[++I];break}const l=[n!==void 0?"args":void 0,r?"stdin":void 0,o!==void 0?"args-file":void 0].filter(I=>I!==void 0);if(l.length===0)throw new k("INVOKE_INPUT_SOURCE_MISSING",ot);if(l.length>1)throw new k("INVOKE_INPUT_SOURCE_CONFLICT",`Choose only one invoke input source; received ${l.join(", ")}.`);const d=l[0],S=d==="args"?n:d==="stdin"?(t.readStdin??nr)():(t.readArgsFile??tr)(o),m=d==="args"?$n(S):R(S);return{args:m.args,inputSource:d,projectRoot:a,format:s,watch:c||m.watch,commandLevelWatch:m.metadata,serverUrl:p}}function st(e,t){return t?.active?{...e??{},commandLevelWatch:t,serverHeldStream:!1}:e}function or(e,t,n=process.stdout,r=process.stderr){if(t.format==="json"){const s=ue(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})+`
118
+ `.trim();function So(e){return e.includes("--help")||e.includes("-h")||e.includes("help")}function pt(e){return new N("INVOKE_INPUT_VALUE_MISSING",`${e} requires a value. ${lt}`)}function bo(e){try{if(!Re(e).isFile())throw new N("INVOKE_ARGS_FILE_NOT_FILE","--args-file must point to a readable UTF-8 text file.");return z(e,"utf8")}catch(t){throw t instanceof N?t:new N("INVOKE_ARGS_FILE_READ_FAILED","--args-file could not be read as UTF-8 text. Check the path and permissions.")}}function yo(){try{if(process.stdin.isTTY)throw new N("INVOKE_STDIN_EMPTY","--stdin requires piped UTF-8 text, for example: neocortex-client invoke --stdin < synthetic.story.md");return z(0,"utf8")}catch(e){throw e instanceof N?e:new N("INVOKE_STDIN_READ_FAILED","--stdin could not be read as UTF-8 text. Pipe command text into stdin and retry.")}}function vo(e,t={}){let n,o=!1,r,a,s="plain",c=!1,p;for(let g=0;g<e.length;g++)switch(e[g]){case"--args":{const I=e[++g];if(I===void 0)throw pt("--args");n=I;break}case"--stdin":o=!0;break;case"--args-file":{const I=e[++g];if(I===void 0)throw pt("--args-file");r=I;break}case"--project-root":a=e[++g];break;case"--format":s=e[++g]??"plain";break;case"--watch":c=!0;break;case"--server-url":p=e[++g];break}const u=[n!==void 0?"args":void 0,o?"stdin":void 0,r!==void 0?"args-file":void 0].filter(g=>g!==void 0);if(u.length===0)throw new N("INVOKE_INPUT_SOURCE_MISSING",lt);if(u.length>1)throw new N("INVOKE_INPUT_SOURCE_CONFLICT",`Choose only one invoke input source; received ${u.join(", ")}.`);const d=u[0],f=d==="args"?n:d==="stdin"?(t.readStdin??yo)():(t.readArgsFile??bo)(r),h=d==="args"?so(f):T(f);return{args:h.args,inputSource:d,projectRoot:a,format:s,watch:c||h.watch,commandLevelWatch:h.metadata,serverUrl:p}}function ft(e,t){return t?.active?{...e??{},commandLevelWatch:t,serverHeldStream:!1}:e}function Ao(e,t,n=process.stdout,o=process.stderr){if(t.format==="json"){const s=fe(e.instructions,e.metadata),c=ft(s.metadata,t.commandLevelWatch);if(t.watch){n.write(JSON.stringify({type:"invoke_result",instructions:s.instructions,metadata:c,publicSafe:!0})+`
134
119
  `);return}n.write(JSON.stringify({instructions:s.instructions,metadata:c})+`
135
- `);return}const o=ue(e.instructions,e.metadata),a=st(o.metadata,t.commandLevelWatch);n.write(o.instructions+`
136
- `),a&&r.write(JSON.stringify(a)+`
137
- `)}function ar(e){const t=()=>e.abort();return process.once("SIGINT",t),process.once("SIGTERM",t),()=>{process.removeListener("SIGINT",t),process.removeListener("SIGTERM",t)}}async function Rr(e){if(er(e))return process.stdout.write(`${Zn}
138
- `),0;let t;try{t=rr(e)}catch(r){if(r instanceof k)return process.stderr.write(JSON.stringify({error_code:r.code,message:r.message})+`
139
- `),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 Qn({args:t.args,inputSource:t.inputSource,watch:t.watch,projectRoot:t.projectRoot,format:t.format,serverUrl:t.serverUrl});if(!n.success)return process.stderr.write(JSON.stringify({error_code:n.errorCode??(n.exitCode===2?"NOT_CONFIGURED":"INVOKE_ERROR"),message:V(n.error??"",ee)})+`
140
- `),n.exitCode;if(or(n,t),t.watch){const r=new AbortController,o=ar(r);try{const a=Xn(n.metadata,t.args);a.disabled?bn(a.reasonCodes??[T.TARGET_UNRESOLVED],t.args,t.format,process.stdout):await Nn({projectRoot:ce(t.projectRoot),format:t.format,...a,signal:r.signal})}finally{o()}}return 0}export{Zn as INVOKE_HELP_TEXT,je as INVOKE_PAYLOAD_LIMIT_BYTES,ie as INVOKE_PAYLOAD_WARNING_THRESHOLD_BYTES,k as InvokeCliInputError,We as InvokePayloadTooLargeError,vr as __resetSchemaDriftWarnedForTests,Ht as collectInitProjectMemoryBootstrapSnapshot,Zt as collectStateSnapshot,F as computeInvokeRequestBodySizeBytes,wr as createFullStateSnapshotScope,fe as createInvokePayloadTelemetry,zt as detectStateSchemaDrift,rt as extractPreFlightTrigger,mn as guardInvokeRequestBodySize,Qn as invoke,Rr as invokeCliHandler,Bt as isInitTrigger,hn as maybeEmitInvokePayloadSizeWarning,En as maybeRunInvokeRunnerAutoBootstrap,rr as parseInvokeCliOptions,$n as resolveInvokeCommandLevelWatch,ce as resolveInvokeProjectRoot,Xn as resolveInvokeWatchTarget,ue as sanitizeInvokeCliOutput,Nn as watchContinuityProcessingSummaries,or as writeInvokeCliSuccessOutput};
120
+ `);return}const r=fe(e.instructions,e.metadata),a=ft(r.metadata,t.commandLevelWatch);n.write(r.instructions+`
121
+ `),a&&o.write(JSON.stringify(a)+`
122
+ `)}function Ro(e){const t={error_code:e.errorCode??(e.exitCode===2?"NOT_CONFIGURED":"INVOKE_ERROR"),message:H(e.error??"",ce)};return e.reasonCode&&(t.reason_code=H(e.reasonCode,96)),t}function To(e){const t=()=>e.abort();return process.once("SIGINT",t),process.once("SIGTERM",t),()=>{process.removeListener("SIGINT",t),process.removeListener("SIGTERM",t)}}async function qo(e){if(So(e))return process.stdout.write(`${Co}
123
+ `),0;let t;try{t=vo(e)}catch(o){if(o instanceof N)return process.stderr.write(JSON.stringify({error_code:o.code,message:o.message})+`
124
+ `),1;throw o}if(Mt(t.args))return(await $t({args:t.args,projectRoot:ue(t.projectRoot),format:t.format,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})).exitCode;const n=await Io({args:t.args,inputSource:t.inputSource,watch:t.watch,projectRoot:t.projectRoot,format:t.format,serverUrl:t.serverUrl});if(!n.success)return process.stderr.write(JSON.stringify(Ro(n))+`
125
+ `),n.exitCode;if(Ao(n,t),t.watch){const o=new AbortController,r=To(o);try{const a=_o(n.metadata,t.args);a.disabled?zn(a.reasonCodes??[v.TARGET_UNRESOLVED],t.args,t.format,process.stdout):await Yn({projectRoot:ue(t.projectRoot),format:t.format,...a,signal:o.signal})}finally{r()}}return 0}export{We as CODEX_AUTH_SANDBOX_ERROR_CODE,Co as INVOKE_HELP_TEXT,$e as INVOKE_PAYLOAD_LIMIT_BYTES,de as INVOKE_PAYLOAD_WARNING_THRESHOLD_BYTES,N as InvokeCliInputError,Je as InvokePayloadTooLargeError,Fe as PublicExecutionResponseError,Yo as __resetSchemaDriftWarnedForTests,Ro as buildInvokeCliErrorPayload,cn as buildPublicExecutionRequestHeaders,an as classifyCodexAuthEnvironment,en as collectInitProjectMemoryBootstrapSnapshot,bn as collectStateSnapshot,F as computeInvokeRequestBodySizeBytes,Xo as createFullStateSnapshotScope,Ee as createInvokePayloadTelemetry,En as detectStateSchemaDrift,hn as dispatchPublicExecutionResponse,ut as extractPreFlightTrigger,Pn as guardInvokeRequestBodySize,Io as invoke,qo as invokeCliHandler,Qt as isInitTrigger,Un as maybeEmitInvokePayloadSizeWarning,jn as maybeRunInvokeRunnerAutoBootstrap,vo as parseInvokeCliOptions,sn as resolveCodexAuthFailureDiagnosis,so as resolveInvokeCommandLevelWatch,nn as resolveInvokePlatformTarget,ue as resolveInvokeProjectRoot,_o as resolveInvokeWatchTarget,fe as sanitizeInvokeCliOutput,An as sanitizePublicInvokeErrorBody,Yn as watchContinuityProcessingSummaries,Ao as writeInvokeCliSuccessOutput};