@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.
- package/dist/sbom.cdx.json +29 -29
- package/docs/install/installer-diagnostics.md +33 -0
- package/install.ps1 +49 -229
- package/install.sh +30 -92
- package/package.json +5 -2
- package/packages/client/dist/adapters/platform-detector.d.ts +7 -6
- package/packages/client/dist/adapters/platform-detector.js +1 -1
- package/packages/client/dist/agent/refresh-stubs.js +1 -1
- package/packages/client/dist/cache/encrypted-cache.d.ts +10 -4
- package/packages/client/dist/cache/encrypted-cache.js +1 -1
- package/packages/client/dist/cache/in-memory-asset-cache.d.ts +5 -4
- package/packages/client/dist/cache/in-memory-asset-cache.js +1 -1
- package/packages/client/dist/cache/protected-pi-boundary.d.ts +6 -2
- package/packages/client/dist/cache/protected-pi-boundary.js +1 -1
- package/packages/client/dist/checkpoint/checkpoint-client-reader.d.ts +31 -30
- package/packages/client/dist/checkpoint/checkpoint-client-reader.js +2 -2
- package/packages/client/dist/checkpoint/shared-checkpoint-types.d.ts +2 -0
- package/packages/client/dist/cli.js +3 -3
- package/packages/client/dist/commands/invoke.d.ts +77 -1
- package/packages/client/dist/commands/invoke.js +44 -59
- package/packages/client/dist/config/resolver-selection.d.ts +12 -31
- package/packages/client/dist/config/resolver-selection.js +1 -1
- package/packages/client/dist/errors/error-messages.js +1 -1
- package/packages/client/dist/evidence/collector.d.ts +18 -0
- package/packages/client/dist/evidence/collector.js +1 -0
- package/packages/client/dist/evidence/index.d.ts +3 -0
- package/packages/client/dist/evidence/index.js +1 -0
- package/packages/client/dist/evidence/types.d.ts +59 -0
- package/packages/client/dist/evidence/types.js +0 -0
- package/packages/client/dist/graph-retrieval/pre-command-hook.d.ts +21 -0
- package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -1
- package/packages/client/dist/index.d.ts +10 -11
- package/packages/client/dist/index.js +1 -1
- package/packages/client/dist/license/license-client.d.ts +17 -0
- package/packages/client/dist/license/license-client.js +1 -1
- package/packages/client/dist/memory/project-memory-writer.js +13 -13
- package/packages/client/dist/memory/shared-project-memory-types.d.ts +1 -1
- package/packages/client/dist/memory/shared-project-memory-types.js +2 -2
- package/packages/client/dist/resolvers/asset-resolver.d.ts +8 -71
- package/packages/client/dist/resolvers/remote-resolver.d.ts +7 -69
- package/packages/client/dist/resolvers/remote-resolver.js +1 -1
- package/packages/client/dist/runner-cli.js +0 -0
- package/packages/client/dist/state/project-state-snapshot.js +1 -1
- package/packages/client/dist/telemetry/index.d.ts +1 -1
- package/packages/client/dist/telemetry/index.js +1 -1
- package/packages/client/dist/telemetry/offline-queue.d.ts +12 -2
- package/packages/client/dist/telemetry/offline-queue.js +1 -1
- package/packages/client/dist/types/index.d.ts +26 -8
- package/packages/client/dist/types/index.js +1 -1
- package/packages/client/dist/types/shared-public-execution-contract.d.ts +175 -0
- package/packages/client/dist/types/shared-public-execution-contract.js +2 -0
- package/targets-stubs/antigravity/gemini.md +1 -1
- package/targets-stubs/antigravity/skill/SKILL.md +1 -1
- package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex-root.md +2 -2
- package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex.md +2 -2
- package/targets-stubs/codex/AGENTS.md +16 -6
- package/targets-stubs/codex/README.md +24 -0
- package/targets-stubs/codex/install-codex.sh +70 -1
- package/targets-stubs/codex/neocortex-local.config.toml +17 -0
- package/targets-stubs/codex/neocortex.toml +10 -1
- package/targets-stubs/cursor/agent.md +2 -2
- package/targets-stubs/gemini-cli/agent.md +2 -2
- package/targets-stubs/opencode/neocortex-root.md +4 -4
- package/targets-stubs/opencode/neocortex.md +1 -1
- package/targets-stubs/vscode/neocortex.agent.md +2 -2
- package/packages/client/dist/resolvers/local-resolver.d.ts +0 -26
- 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
|
-
/**
|
|
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
|
|
7
|
-
`),
|
|
8
|
-
`),t}function
|
|
9
|
-
`)}async function
|
|
10
|
-
`);return}n.write(
|
|
11
|
-
`)}function
|
|
12
|
-
`);return}n.write(
|
|
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] ${
|
|
15
|
-
|
|
16
|
-
`))
|
|
17
|
-
`),{success:!1,error:i.message,exitCode:1};const
|
|
18
|
-
`),{success:!1,error:
|
|
19
|
-
`),warn:
|
|
20
|
-
`)}};i(
|
|
21
|
-
`)}try{const{readYoloopForRequest:i}=await import("../yoloop/invoke-hooks.js"),
|
|
22
|
-
`)}try{const{maybeRunDiscoveryHook:i}=await import("../yoloop/invoke-hooks.js");await i({args:e.args,projectRoot:t,stateSnapshot:
|
|
23
|
-
`)}try{const{readArchitecturePolicy:i}=await import("../policy/architecture-policy.js"),
|
|
24
|
-
`)}});
|
|
25
|
-
`)}try{const{
|
|
26
|
-
`)}
|
|
27
|
-
`)}
|
|
28
|
-
`),{
|
|
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};
|
|
31
|
-
`)
|
|
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
|
-
|
|
37
|
-
`),process.stderr.write(`
|
|
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(` ${
|
|
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(`
|
|
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:
|
|
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
|
|
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
|
|
136
|
-
`),a&&
|
|
137
|
-
`)}function
|
|
138
|
-
`),0;let t;try{t=
|
|
139
|
-
`),1;throw
|
|
140
|
-
`),n.exitCode;if(
|
|
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};
|