@ornexus/neocortex 4.60.62 → 4.60.63
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/release-source.json +1 -1
- package/dist/sbom.cdx.json +77 -50
- package/install.ps1 +1 -1
- package/install.sh +1 -1
- package/package.json +7 -5
- package/packages/client/dist/commands/invoke.js +53 -51
- package/packages/client/dist/package.json +1 -0
- package/packages/client/dist/private-execution/clean-baseline.d.ts +1 -0
- package/packages/client/dist/private-execution/clean-baseline.js +2 -2
- package/packages/client/dist/private-execution/isolated-session.js +2 -2
- package/packages/shared/dist/package.json +1 -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 +1 -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 +1 -1
- package/targets-stubs/vscode/neocortex.agent.md +2 -2
|
@@ -1,58 +1,58 @@
|
|
|
1
|
-
import{createHash as Ge,randomUUID as
|
|
2
|
-
`,{encoding:"utf8",mode:384,flag:"wx"}),
|
|
1
|
+
import{createHash as Ge,randomUUID as Ft}from"node:crypto";import{loadPactAnswerReceipt as Gn,loadPactPrivateAnswers as ia}from"./architecture-answers.js";import{acceptedArchitectureTerminalMemoryReceipt as Yt,deriveArchitectureTerminalMemoryReceipt as mn}from"./architecture-memory-terminal.js";import{deriveCommittedArchitectureEpicGraphRevision as jt,explicitArchitectureEpicTarget as oa}from"./architecture-root-binding.js";import{derivePactWriteSet as ca}from"../private-execution/pact-write-set.js";import{execFileSync as je}from"node:child_process";import{existsSync as wt,readFileSync as Te,renameSync as qn,unlinkSync as yn,writeFileSync as zt,mkdirSync as Mt,statSync as sa,openSync as Vt,closeSync as Ut,fsyncSync as Jt,realpathSync as da,lstatSync as _t}from"node:fs";import{isDeepStrictEqual as E}from"node:util";import{join as X,isAbsolute as pa,resolve as Fn}from"node:path";import{homedir as $t}from"node:os";import{isPrivateExecutionPublicEnvelope as ua,PRIVATE_MUTATION_QA_GATE_STEP_TOKEN as la}from"../private-execution/delivery.js";import{acceptedPlanningDiagnosisPredecessor as Yn}from"../private-execution/planning-diagnosis-checkpoint.js";import{acceptedPlanningResearchPredecessor as zn}from"../private-execution/planning-research-checkpoint.js";import{LicenseClient as ha}from"../license/license-client.js";import{EncryptedCache as En}from"../cache/encrypted-cache.js";import{NoOpCache as Jn}from"../types/index.js";import{resolveClientPreFlightTrigger as Sn,TierAwareClient as ga}from"../tier/tier-aware-client.js";import{COMMAND_REGISTRY_CHECKSUM as ht,COMMAND_REGISTRY_VERSION as gt,GENERATED_CLIENT_COMMANDS as fa}from"../generated/command-registry.generated.js";import{loadSecureConfig as Kn}from"../config/secure-config.js";import{neocortexProfileDirectory as ma}from"../config/profile-directory.js";import{DEFAULT_SERVER_URL as ya}from"../constants.js";import{detectFirstRunLocale as Ea,renderFirstRunMessage as Sa}from"../i18n/first-run.js";import{humanizeError as Qn,formatHumanizedError as Xn,detectErrorLocale as Zn}from"../errors/error-messages.js";import{degradeStateSnapshotForPayloadLimit as Ia,projectStateSnapshotForInvoke as er,projectStateSnapshotResultV2ForInvoke as va}from"../state/project-state-snapshot.js";import{isInlineYoloMaterialization as Ca,maybeRepairStateJsonBeforeInvoke as wa,StateRepairHardStopError as _a}from"../state/state-json-repair.js";import{StructuralDagError as tr}from"../state/structural-dag-projection.js";import{collectStateMigrationAuthority as Ra,StateMigrationApplyError as Aa}from"../migrations/state-json.js";import{RUNNER_BOOTSTRAP_POLICY_REASON_CODES as ba,classifyRunnerBootstrapPolicyFromArgs as Ta}from"../continuity/runner-bootstrap-policy.js";import{RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES as xa,ensureRunnerSchedulerBootstrap as ka,observeRunnerOperationalStatus as Pa}from"../runner/scheduler.js";import{CONTINUITY_INVOKE_WATCH_DEFAULT_LIMIT as nr,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_IDLE_POLLS as rr,CONTINUITY_INVOKE_WATCH_DEFAULT_MAX_POLLS as ar,CONTINUITY_INVOKE_WATCH_DEFAULT_POLL_INTERVAL_MS as ir,openContinuityClientStateStore as Oa}from"../continuity/continuity-client-state-store.js";import{isLocalJobsConsoleArgs as Na,runLocalJobsConsoleCommand as Da}from"../runner/local-console.js";import{detectNativeHostAttestation as La,detectPlatform as ja}from"../adapters/platform-detector.js";import{signNxInvokeRequest as Ma}from"../../../shared/dist/nx-invoke-signature.js";import{CLIENT_VERSION as Rt}from"../version.js";import{createCapabilityCache as or,executeInvokeQueryTransport as cr,executeSecondaryNetworkMutation as Va}from"../effects/invoke-effect-gateways.js";import{STRICT_READ_ONLY_POLICY as Ua,STRICT_READ_ONLY_CLIENT_PROJECTION as sr,STRICT_READ_ONLY_SERVER_PROJECTION as $a,StrictReadOnlyError as At,canonicalizeInvokeEffects as Ba,createInvokeEffectContext as Ha,verifyStrictReadOnlyReceipt as Wa}from"../../../shared/dist/strict-readonly.js";import{admitInvocation as Ga,assertInvokeInputEnvelopeV2 as qa,assertProjectIdentityMigrationReceiptV1 as Fa,buildProjectIdentityPublicDiagnostic as bt,createInvocationAdmissionReceipt as Ya,projectInvokeInputEvidenceV1 as dr,verifyStrictDiagnoseReceiptV1 as za}from"../../../shared/dist/invocation/index.js";import{buildInvokeInputEnvelope as Kt,InvokeInputDecodeError as Ja}from"../invocation/invoke-input.js";import{acknowledgeProjectIdentityMigration as Ka,finalizeProjectIdentityMigration as Qa,prepareProjectIdentityMigration as Xa,ProjectIdentityMigrationError as In,readProjectIdentityMigrationPhase as Za}from"../migrations/project-identity.js";import{probeProjectIdentityMigrationCapability as ei}from"../migrations/project-identity-capability.js";import{normalizeYoloopStoryPlanningEvidence as ti}from"../../../shared/dist/yoloop/planning-graph.js";import{normalizeContinuousWriteRef as Qt}from"../../../shared/dist/yoloop/wave-decision-receipt.js";import{applyGitLifecycleRuntimeOverlay as pr,classifyGitLifecycleStoryCheckpointProjectionSync as ni,ensureGitLifecycleRuntimeInitialized as ri,executeP205TransientAuthorities as ai,persistGitLifecycleGraphAuthority as ii,P205_COMPLETE_COMMAND as oi,gitLifecycleStoryWriteSet as ur,readGitLifecycleRuntimeSync as Xt,verifyLegacyCheckpointMigrationCandidateSync as ci}from"../git/git-lifecycle-store.js";const Zt=ma(),vn=X(Zt,"cache"),lr=X(vn,"menu-cache.json"),hr=1440*60*1e3,gr=3e4,fr=256*1024,mr=fr,yr=.8,at="[REDACTED]",si=1e5,ft=2e3,di=200,pi=200,ui=12,li=/(?:promptBody|workflow|workflowGraph|stepBody|privateUrl|rawLog|secret|credential|licenseKey|apiKey|internalRouting|serverOnly|proprietary|protected)/i,hi=/(?:PRIVATE|PROTECTED|SERVER_ONLY)[-_\s]*(?:PROMPT|PROMPT_BODY|WORKFLOW|WORKFLOW_GRAPH|STEP_BODY|STEP|ROUTING)\s*[:=][^\n\r]*/gi,gi=/(?: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,Cn=Math.floor(fr*yr),Er=X(Zt,".first-run-shown"),fi="pending-epic-claims.json",Sr=64;function Ir(e){return X(e,".neocortex",fi)}function en(e){const t=Ir(e);if(!wt(t))return{schemaVersion:1,operations:{}};const a=JSON.parse(Te(t,"utf8"));if(!a||typeof a!="object"||Array.isArray(a))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const r=a;if(r.schemaVersion!==1||!r.operations||typeof r.operations!="object"||Array.isArray(r.operations))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(Object.keys(r.operations).length>Sr)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");for(const[i,n]of Object.entries(r.operations)){if(!/^[a-f0-9]{64}$/.test(i)||!n||typeof n!="object"||Array.isArray(n))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const o=n;if(typeof o.idempotencyKey!="string"||!/^[0-9a-f-]{36}$/.test(o.idempotencyKey)||typeof o.createdAt!="string")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(o.claimId!==void 0&&(typeof o.claimId!="string"||!/^[0-9a-f-]{36}$/.test(o.claimId))||o.epicId!==void 0&&(typeof o.epicId!="string"||!/^P[1-9][0-9]*$/.test(o.epicId))||o.claimId===void 0!=(o.epicId===void 0))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE")}return a}function wn(e,t){const a=Ir(e);Mt(X(e,".neocortex"),{recursive:!0,mode:448});const r=`${a}.${process.pid}.${Ft()}.tmp`;zt(r,`${JSON.stringify(t)}
|
|
2
|
+
`,{encoding:"utf8",mode:384,flag:"wx"}),qn(r,a)}function mi(e,t){return Ge("sha256").update(`nx-epic-logical-operation-v1\0${JSON.stringify({command:t,args:e})}`,"utf8").digest("hex")}function yi(e,t,a="create-epic"){const r=mi(t,a),i=en(e),n=i.operations[r];if(n)return{key:n.idempotencyKey,fingerprint:r};if(Object.keys(i.operations).length>=Sr)throw new Error("EPIC_CLAIM_CAPACITY_EXCEEDED");const o=Ft(),s={...i.operations,[r]:{idempotencyKey:o,createdAt:new Date().toISOString()}};return wn(e,{schemaVersion:1,operations:s}),{key:o,fingerprint:r}}function Ei(e,t){const a=en(e);if(!a.operations[t])return;const r={...a.operations};delete r[t],wn(e,{schemaVersion:1,operations:r})}function vr(e,t,a,r){if(!/^[0-9a-f-]{36}$/.test(a)||!/^P[1-9][0-9]*$/.test(r))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const i=en(e),n=i.operations[t];if(!n)throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");if(n.claimId!==void 0&&(n.claimId!==a||n.epicId!==r))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");wn(e,{schemaVersion:1,operations:{...i.operations,[t]:{...n,claimId:a,epicId:r}}})}function Si(){try{if(wt(Er))return;const e=Ea(),t=Sa(e);process.stderr.write(t);try{Mt(Zt,{recursive:!0}),zt(Er,new Date().toISOString(),"utf-8")}catch{}}catch{}}function _n(e,t=process.cwd()){return e&&e.trim().length>0?e:t}function Ii(e){return Ga(e,{registryVersion:gt,registryChecksum:ht})}const vi=new Set(["completed","aborted","cancelled"]),Ci=new Set(["watch-target-missing","watch-target-malformed","watch-target-ambiguous","watch-target-multiple"]),fe=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"}),Ce=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"}),W=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"}),Cr=240,wi=/(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 _i(e){return e.replace(/[\w.+-]+@[\w-]+\.[\w.-]+/g,at).replace(/(?:sk|pk|whsec|nxk)[-_](?:test|live|ant|proj|pro|free|enterprise)?[-_]?[A-Za-z0-9_-]{16,}/g,at).replace(/NX-[FPE]-[a-f0-9]{24}-[a-f0-9]{4}/g,at).replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,at).replace(hi,at).replace(gi,at)}function Be(e,t){const a=_i(e);return a.length<=t?a:`${a.slice(0,t)}\u2026[TRUNCATED:${a.length-t}]`}function Rn(e,t=0,a=new WeakSet){if(t>ui)return"[MAX_DEPTH]";if(e==null)return e;if(typeof e=="string")return Be(e,ft);if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e=="boolean")return e;if(typeof e=="bigint")return String(e);if(!(typeof e=="function"||typeof e=="symbol")&&typeof e=="object"){if(a.has(e))return"[CIRCULAR]";a.add(e);try{if(Array.isArray(e))return e.slice(0,di).map(i=>Rn(i,t+1,a));const r={};for(const[i,n]of Object.entries(e).slice(0,pi)){if(li.test(i)){r[i]=at;continue}const o=Rn(n,t+1,a);o!==void 0&&(r[i]=o)}return r}finally{a.delete(e)}}}function tn(e,t){return{instructions:Be(e??"",si),metadata:t?Rn(t):void 0}}class nn extends Error{reason;source;byteLength;code;constructor(t,a,r,i,n){super(a),this.reason=r,this.source=i,this.byteLength=n,this.name="InvokeCliInputError",this.code=t}}function Ri(e){return/^\s*\*?(?:arch-plan|ui-ux-review)(?:\s|$)/i.test(e)&&Ai(e,"--project-evidence")}function Ai(e,t){let a=null,r=-1,i=!1,n=!1;for(let o=0;o<=e.length;o+=1){const s=e[o];if(o===e.length||!a&&/\s/.test(s??"")){if(r>=0&&!i&&e.slice(r,o)===t)return!0;r=-1,i=!1,n=!1;continue}if(r<0&&(r=o),n){n=!1;continue}if(s==="\\"){n=!0;continue}(s==='"'||s==="'")&&(i=!0,a=a===s?null:a??s)}return!1}const bi=/(?:^|\s)codex(?:-cli)?\s+([A-Za-z0-9][A-Za-z0-9._+-]{0,63})(?:\s|$)/i;function Ti(e,t){if(e.targetId!=="codex")return null;const a=t.CODEX_VERSION?.trim();if(a&&/^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/.test(a))return a;try{return je("codex",["--version"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim().match(bi)?.[1]??null}catch{return null}}class An extends Error{code="PAYLOAD_TOO_LARGE";telemetry;constructor(t){super(`PAYLOAD_TOO_LARGE: invoke request is ${t.payloadBytes} bytes after deterministic degradation; limit is ${t.limitBytes}. Reduce command input or local state context and retry.`),this.name="InvokePayloadTooLargeError",this.telemetry=t}}class bn extends Error{code="STRUCTURAL_CONTEXT_TOO_LARGE";telemetry;constructor(t){super(`STRUCTURAL_CONTEXT_TOO_LARGE: the bounded structural projection is ${t.payloadBytes} bytes; the request limit is strictly below ${t.limitBytes}. Select an explicit epic/story target or split the dependency graph.`),this.name="InvokeStructuralContextTooLargeError",this.telemetry=t}}let Tn=!1;function xi(e){const t=[];if(!e||typeof e!="object")return t;const a=e,r=a.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(a.stories)&&t.push({code:"STORIES_AS_ARRAY",message:"`stories` is an Array (expected Object keyed by story ID)"}),a.epics&&typeof a.epics=="object"&&!Array.isArray(a.epics))for(const[n,o]of Object.entries(a.epics)){const s=o;if(s&&s.stories!==void 0&&!Array.isArray(s.stories)){t.push({code:"EPIC_STORIES_NOT_ARRAY",message:`epic "${n}" has non-array \`stories\` field (expected string[] of story IDs)`});break}}const i=a.epics&&typeof a.epics=="object"&&Object.keys(a.epics).length>0||a.stories&&typeof a.stories=="object"&&!Array.isArray(a.stories)&&Object.keys(a.stories).length>0||Array.isArray(a.stories)||r&&r.current!==void 0;return a.schema_version===void 0?i&&t.push({code:"SCHEMA_VERSION_MISSING",message:"`schema_version` field missing (expected: `schema_version: 1`)"}):a.schema_version!==1&&t.push({code:"SCHEMA_VERSION_OUTDATED",message:`schema_version=${String(a.schema_version)} (expected: 1)`}),t}function ki(e){if(!(Tn||e.length===0)){Tn=!0;try{const t=e.map(a=>` - ${a.message}`).join(`
|
|
3
3
|
`);process.stderr.write(`[Neocortex] state.json schema drift detected:
|
|
4
4
|
${t}
|
|
5
5
|
Run \`neocortex *migrate-state --preview\` to inspect or \`neocortex *migrate-state --apply\` to migrate.
|
|
6
6
|
See docs/arquitetura-software/STATE-JSON-SCHEMA.md for the schema contract.
|
|
7
|
-
`)}catch{}}}function Jc(){An=!1}function Ir(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Pi(e){return e==="active"||e==="archived"||e==="rolled-back"||e==="synthetic"||e==="orphan"?e:void 0}const Oi=new Set(["goal","problem","desiredOutcome","rawIntent","context","users","surfaces","constraints","assumptions","risks","nonGoals","validationExpectations","debtRefs","repositoryEvidencePaths","journeyIds","screenIds","storybookStoryIds","backendContractIds","featureBlockerIds","remediationRefs","uiScope","remediationStory","examples","contracts"]),Ni=/(?:[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}|(?:token|api[_-]?key|secret|password|credential|license[_-]?key)\s*[:=]\s*\S+|https?:\/\/(?:localhost|127\.0\.0\.1|10\.\d+\.\d+\.\d+|192\.168\.\d+\.\d+|172\.(?:1[6-9]|2\d|3[0-1])\.\d+\.\d+|[^\s/]*internal[^\s/]*)\S*|private\s+prompt|raw\s+vendor\s+corpus|sk-[A-Za-z0-9_-]{12,})/i;function Di(e,t){if(!(!h(e)||e.schemaVersion!==1||e.epicId!==t||!/^P\d+$/.test(t)))try{const a=JSON.stringify(e);if(Buffer.byteLength(a)>16384||Ni.test(a))return;const r=(n,o)=>{if(Object.keys(n).some(s=>!o.includes(s)))throw new Error("planning-unknown-field")};if(r(e,["schemaVersion","epicId","intake","intakeRevision","diagnosisReceipt","researchReceipt","degradeAuthorization"]),!h(e.intake)||Object.keys(e.intake).some(n=>!Oi.has(n)))return;for(const[n,o]of Object.entries(e.intake))if(["examples","contracts"].includes(n)){const s=n==="examples"?["id","title","actor","given","when","then","source","coveredRequirement","expectedValidation"]:["id","kind","description","path"];if(!Array.isArray(o)||o.length>16)return;for(const u of o)if(!h(u)||(r(u,s),Object.values(u).some(f=>typeof f!="string"||f.length>256)))return}else if(Array.isArray(o)){if(o.length>32||o.some(s=>typeof s!="string"||s.length>256))return}else if(typeof o=="string"){if(o.length>512)return}else if(typeof o!="boolean"||!["uiScope","remediationStory"].includes(n))return;const i=["schemaVersion","kind","epicId","intakeRevision","artifactSummary","artifactDigest","predecessorReceiptId","accepted","receiptId"];for(const n of[e.diagnosisReceipt,e.researchReceipt])if(n!==void 0&&(!h(n)||(r(n,i),Object.values(n).some(o=>typeof o=="string"&&o.length>1024))))return;if(e.degradeAuthorization!==void 0){if(!h(e.degradeAuthorization))return;r(e.degradeAuthorization,["approved","intakeRevision","reasonCodes","assumptionCodes"]);for(const n of["reasonCodes","assumptionCodes"]){const o=e.degradeAuthorization[n];if(!Array.isArray(o)||o.length>32||o.some(s=>typeof s!="string"||s.length>128))return}}return JSON.parse(a)}catch{return}}function vr(e){return e==="create-epic"||e==="discovered"?e:void 0}function Pe(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Li(e){const t={};let a=!1;for(const r of["contracts","contract_refs","shared_surfaces","adr_refs","nfr_refs","acceptance_depends_on"]){if(e[r]===void 0)continue;const i=e[r];if(!Array.isArray(i)||i.length>128||i.some(n=>Jt(n)===void 0)){a=!0;continue}t[r]=i.map(n=>Jt(n))}if(e.planning!==void 0)try{if(!h(e.planning))throw new Error("planning-shape");const r=e.planning;for(const o of["claims","semanticArtifacts"]){if(r[o]===void 0)continue;const s=r[o];if(!Array.isArray(s)||s.length>128||s.some(u=>!h(u)||Jt(u.ref)===void 0))throw new Error("planning-refs")}if(r.attempts!==void 0&&(!Array.isArray(r.attempts)||r.attempts.length>32))throw new Error("planning-attempts");for(const o of r.attempts??[]){if(!h(o)||!Array.isArray(o.reasonCodes)||o.reasonCodes.length>32||o.reasonCodes.some(s=>typeof s!="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(s)))throw new Error("planning-attempt-reasons");if(o.discoveredClaims!==void 0&&(!Array.isArray(o.discoveredClaims)||o.discoveredClaims.length>128||o.discoveredClaims.some(s=>!h(s)||Jt(s.ref)===void 0)))throw new Error("planning-attempt-claims")}const{graphRevision:i,...n}=ti(r);t.planning=n}catch{a=!0}return a&&(t.planning={schemaVersion:1,dependencyBasis:"unknown",claims:[],semanticArtifacts:[]}),t}function h(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function at(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function ne(e){if(typeof e!="string")return;const t=e.trim();if(t)return t.replace(/[^a-z0-9_.:-]+/gi,"_").slice(0,120)}function X(e){if(typeof e!="string")return;const t=e.trim(),a=ne(e);return a===t?a:void 0}function Se(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240)&&/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(t)&&!(t.includes("..")||t.includes("//")||t.includes("@{")||t.endsWith("/")||t.endsWith("."))&&!t.split("/").some(a=>!a||a.startsWith(".")||a.endsWith(".lock")))return t}function R(e){return typeof e=="string"&&/^[0-9a-f]{7,64}$/i.test(e)?e:void 0}function Oe(e){if(!(typeof e!="string"||e.length>64)&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/.test(e))return Number.isFinite(Date.parse(e))?e:void 0}function it(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240||t.includes("..")))return/^[A-Za-z0-9._:/#\-[\]]+$/.test(t)?t:void 0}function en(e){if(!h(e))return;const t=l=>typeof l=="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,95}$/.test(l),a=l=>typeof l=="string"&&/^[a-f0-9]{64}$/.test(l),r=(l,y)=>Array.isArray(l)&&l.length<=y&&l.every(t)&&new Set(l).size===l.length?l:void 0,i=(l,y)=>{if(!(!h(l)||l.schemaVersion!==2||!t(l.requestId)||!t(l.stageCommand)||!a(l.requestHash)||!a(l.inputHash)||!a(l.stateHash)||!a(l.nonce)||!a(l.stageRevision)||!a(l.stageHash)||!a(l.catalogHash)||l.targetEpicId!==void 0&&!t(l.targetEpicId)||y&&(!a(l.outputHash)||!a(l.artifactHash))))return{schemaVersion:2,...l.targetEpicId?{targetEpicId:l.targetEpicId}:{},requestId:l.requestId,requestHash:l.requestHash,inputHash:l.inputHash,stateHash:l.stateHash,nonce:l.nonce,stageCommand:l.stageCommand,stageRevision:l.stageRevision,stageHash:l.stageHash,catalogHash:l.catalogHash,...y?{outputHash:l.outputHash,artifactHash:l.artifactHash}:{}}},n=(l,y)=>{if(!(!h(l)||l.schemaVersion!=="1.1"||l.kind!==y||!a(l.receiptId)||!a(l.graphHash)||!a(l.evidenceHash)||!t(l.elementId)||!t(l.caseId)||!t(l.category)))return{schemaVersion:"1.1",kind:y,receiptId:l.receiptId,graphHash:l.graphHash,elementId:l.elementId,caseId:l.caseId,category:l.category,evidenceHash:l.evidenceHash}},o=(l,y)=>{if(!h(l)||l.kind!==y||!a(l.receiptId)||!r(l.evidenceIds,24)||y==="architecture-stage-completion"&&!["succeeded","failed"].includes(String(l.status))||y==="architecture-stage-validation"&&!["passed","failed","pending"].includes(String(l.status)))return;const p=i(l,!0);if(!p)return;const I=y==="architecture-stage-validation"?n(l.isolated,"isolated"):void 0,C=y==="architecture-stage-validation"?n(l.regression,"regression"):void 0;if(!(y==="architecture-stage-validation"&&(!I||!C)))return{...p,kind:y,receiptId:l.receiptId,status:l.status,evidenceIds:l.evidenceIds,...I&&C?{isolated:I,regression:C}:{}}},s={};e.schemaVersion===1&&(s.schemaVersion=1),e.owner==="root"&&(s.owner="root"),t(e.currentStageCommand)&&(s.currentStageCommand=e.currentStageCommand),["ask-user","delegate","resume","advance","blocked","complete"].includes(String(e.continuationState))&&(s.continuationState=e.continuationState);const u=r(e.questionIds,16);u&&(s.questionIds=u),(e.childStatus==="succeeded"||e.childStatus==="failed")&&(s.childStatus=e.childStatus),(e.evidencePolicy==="legacy-compatible"||e.evidencePolicy==="v2-required")&&(s.evidencePolicy=e.evidencePolicy),t(e.targetEpicId)&&(s.targetEpicId=e.targetEpicId),a(e.graphRevision)&&(s.graphRevision=e.graphRevision),e.graphSource==="committed-epic-v1"&&(s.graphSource=e.graphSource),h(e.pactAnswerReceipt)&&Object.keys(e.pactAnswerReceipt).sort().join(",")===["schemaVersion","targetEpicId","graphRevision","stateSha256","answersSha256","questionIds","publicSafe"].sort().join(",")&&e.pactAnswerReceipt.schemaVersion==="PactAnswerReceipt/1"&&e.pactAnswerReceipt.targetEpicId===e.targetEpicId&&e.pactAnswerReceipt.graphRevision===e.graphRevision&&a(e.pactAnswerReceipt.stateSha256)&&a(e.pactAnswerReceipt.answersSha256)&&E(e.pactAnswerReceipt.questionIds,["PACT-Q1-CONSUMER","PACT-Q2-PROVIDER","PACT-Q3-BROKER","PACT-Q4-MATCHERS","PACT-Q5-VERIFY"])&&e.pactAnswerReceipt.publicSafe===!0&&(s.pactAnswerReceipt=e.pactAnswerReceipt);const f=i(e.evidenceExpectation,!1);f&&(s.evidenceExpectation=f);const S=o(e.completionEvidence,"architecture-stage-completion"),_=o(e.validationEvidence,"architecture-stage-validation");if(S&&(s.completionEvidence=S),_&&(s.validationEvidence=_),h(e.reviewDecision)&&Object.keys(e.reviewDecision).sort().join(",")===["schemaVersion","targetEpicId","graphRevision","artifactHash","completionReceiptId","validationReceiptId","decision","evidenceIds","publicSafe"].sort().join(",")&&e.reviewDecision.schemaVersion==="ArchitectureReviewDecision/1"&&e.reviewDecision.targetEpicId===e.targetEpicId&&e.reviewDecision.graphRevision===e.graphRevision&&a(e.reviewDecision.graphRevision)&&a(e.reviewDecision.artifactHash)&&a(e.reviewDecision.completionReceiptId)&&a(e.reviewDecision.validationReceiptId)&&["approved","changes-requested"].includes(String(e.reviewDecision.decision))&&e.reviewDecision.publicSafe===!0){const l=r(e.reviewDecision.evidenceIds,24);l&&l.length>0&&(s.reviewDecision={...e.reviewDecision,evidenceIds:l})}if(qt(e.terminalMemoryCheckpoint,e))s.terminalMemoryCheckpoint=e.terminalMemoryCheckpoint;else if(h(e.terminalMemoryCheckpoint)&&e.terminalMemoryCheckpoint.schemaVersion===void 0&&["passed","failed","pending"].includes(String(e.terminalMemoryCheckpoint.status))){const l=r(e.terminalMemoryCheckpoint.evidenceIds,24);l&&(s.terminalMemoryCheckpoint={status:e.terminalMemoryCheckpoint.status,evidenceIds:l})}if(Array.isArray(e.acceptedStages)&&e.acceptedStages.length<=15){const l=e.acceptedStages.map(y=>{if(!h(y)||!t(y.targetEpicId)||!t(y.stageCommand))return;const p=o(y.completionEvidence,"architecture-stage-completion"),I=o(y.validationEvidence,"architecture-stage-validation");return p&&I?{targetEpicId:y.targetEpicId,stageCommand:y.stageCommand,completionEvidence:p,validationEvidence:I}:void 0});l.every(y=>y!==void 0)&&(s.acceptedStages=l)}if(h(e.accounting)&&e.accounting.schemaVersion===1&&t(e.accounting.contractVersion)&&t(e.accounting.accountingId)&&typeof e.accounting.charged=="boolean"&&Number.isInteger(e.accounting.chargedQuotaUnits)&&typeof e.accounting.chargedQuotaUnits=="number"&&e.accounting.chargedQuotaUnits>=0&&e.accounting.chargedQuotaUnits<=13){const l=r(e.accounting.receiptIds,32);l&&(s.accounting={schemaVersion:1,contractVersion:e.accounting.contractVersion,accountingId:e.accounting.accountingId,charged:e.accounting.charged,chargedQuotaUnits:e.accounting.chargedQuotaUnits,receiptIds:l,...["in-progress","aborted","timed-out","failed","complete"].includes(String(e.accounting.lastOutcome))?{lastOutcome:e.accounting.lastOutcome}:{}})}return JSON.stringify(s).length<=96e3?s:void 0}function ji(e){const t=h(e.metadata.archPlan)?e.metadata.archPlan.execution:void 0,a=h(t)?t.checkpoint:void 0,r=h(t)?t:void 0,i=h(a)?a:void 0,n=e.requestExecution,o=Array.isArray(i?.acceptedStages)?i.acceptedStages:[],s=n.currentStageCommand==="arch-prd"&&n.continuationState==="delegate"&&n.completionEvidence===void 0&&n.validationEvidence===void 0&&i?.currentStageCommand==="arch-prd"&&i.continuationState==="delegate"&&o.length===0&&r?.nextAction==="delegate",u=n.currentStageCommand==="arch-prd"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-architecture"&&i.continuationState==="advance"&&o.length===1&&h(o[0])&&o[0].stageCommand==="arch-prd"&&E(o[0].completionEvidence,n.completionEvidence)&&E(o[0].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",f=n.currentStageCommand==="arch-architecture"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-architecture"&&i.continuationState==="delegate"&&o.length===1&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",S=n.currentStageCommand==="arch-architecture"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-fitness-functions"&&i.continuationState==="advance"&&o.length===2&&h(o[0])&&h(o[1])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===1&&E(o[0],n.acceptedStages[0])&&E(o[1].completionEvidence,n.completionEvidence)&&E(o[1].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",_=n.currentStageCommand==="arch-fitness-functions"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-fitness-functions"&&i.continuationState==="delegate"&&o.length===2&&h(o[0])&&h(o[1])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",l=n.currentStageCommand==="arch-fitness-functions"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-api-contracts"&&i.continuationState==="advance"&&o.length===3&&h(o[0])&&h(o[1])&&h(o[2])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&o[2].stageCommand==="arch-fitness-functions"&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===2&&E(o.slice(0,2),n.acceptedStages)&&E(o[2].completionEvidence,n.completionEvidence)&&E(o[2].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",y=n.currentStageCommand==="arch-api-contracts"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-api-contracts"&&i.continuationState==="delegate"&&o.length===3&&h(o[0])&&h(o[1])&&h(o[2])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&o[2].stageCommand==="arch-fitness-functions"&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",p=["PACT-Q1-CONSUMER","PACT-Q2-PROVIDER","PACT-Q3-BROKER","PACT-Q4-MATCHERS","PACT-Q5-VERIFY"],I=n.currentStageCommand==="arch-api-contracts"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="generate-pacts"&&i.continuationState==="ask-user"&&o.length===4&&h(o[3])&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===3&&E(o.slice(0,3),n.acceptedStages)&&o[3].stageCommand==="arch-api-contracts"&&E(o[3].completionEvidence,n.completionEvidence)&&E(o[3].validationEvidence,n.validationEvidence)&&E(i.questionIds,p)&&E(r?.questionIds,p)&&r?.nextAction==="ask-user",C=n.currentStageCommand==="generate-pacts"&&n.continuationState==="ask-user"&&i?.currentStageCommand==="generate-pacts"&&i.continuationState==="delegate"&&o.length===4&&E(o,n.acceptedStages)&&E(n.questionIds,p)&&E(i.questionIds,[])&&E(i.pactAnswerReceipt,e.answerReceipt)&&E(r?.pactAnswerReceipt,e.answerReceipt)&&e.answerReceipt?.stateSha256===e.sourceStateSha256&&r?.nextAction==="resume",M=n.currentStageCommand==="generate-pacts"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&E(n.pactAnswerReceipt,e.pactRecordedReceipt)&&i?.currentStageCommand==="arch-api-integrations"&&i.continuationState==="advance"&&o.length===5&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===4&&E(o.slice(0,4),n.acceptedStages)&&o.map(b=>h(b)?b.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts"&&h(o[4])&&E(o[4].completionEvidence,n.completionEvidence)&&E(o[4].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",T=n.currentStageCommand==="arch-api-integrations"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-api-integrations"&&i.continuationState==="delegate"&&o.length===5&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",z=n.currentStageCommand==="arch-api-integrations"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-database"&&i.continuationState==="advance"&&o.length===6&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===5&&E(o.slice(0,5),n.acceptedStages)&&o.map(b=>h(b)?b.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations"&&h(o[5])&&E(o[5].completionEvidence,n.completionEvidence)&&E(o[5].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",A=n.currentStageCommand==="arch-database"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-database"&&i.continuationState==="delegate"&&o.length===6&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",v=n.currentStageCommand==="arch-database"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-security"&&i.continuationState==="advance"&&o.length===7&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===6&&E(o.slice(0,6),n.acceptedStages)&&o.map(b=>h(b)?b.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database"&&h(o[6])&&E(o[6].completionEvidence,n.completionEvidence)&&E(o[6].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",D=n.currentStageCommand==="arch-security"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-security"&&i.continuationState==="delegate"&&o.length===7&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",N=n.currentStageCommand==="arch-security"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-design-system"&&i.continuationState==="advance"&&o.length===8&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===7&&E(o.slice(0,7),n.acceptedStages)&&o.map(b=>h(b)?b.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security"&&h(o[7])&&E(o[7].completionEvidence,n.completionEvidence)&&E(o[7].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",V=n.currentStageCommand==="arch-design-system"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-design-system"&&i.continuationState==="delegate"&&o.length===8&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",F=n.currentStageCommand==="arch-design-system"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-ux-design"&&i.continuationState==="advance"&&o.length===9&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===8&&E(o.slice(0,8),n.acceptedStages)&&o.map(b=>h(b)?b.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system"&&h(o[8])&&E(o[8].completionEvidence,n.completionEvidence)&&E(o[8].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",B=n.currentStageCommand==="arch-ux-design"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-ux-design"&&i.continuationState==="delegate"&&o.length===9&&E(o,n.acceptedStages)&&r?.nextAction==="blocked",U=n.currentStageCommand==="arch-ux-design"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-performance"&&i.continuationState==="advance"&&o.length===10&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===9&&E(o.slice(0,9),n.acceptedStages)&&o.map(b=>h(b)?b.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design"&&h(o[9])&&E(o[9].completionEvidence,n.completionEvidence)&&E(o[9].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",H=n.currentStageCommand==="arch-performance"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-performance"&&i.continuationState==="delegate"&&o.length===10&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",fe=n.currentStageCommand==="arch-performance"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-testing"&&i.continuationState==="advance"&&o.length===11&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===10&&E(o.slice(0,10),n.acceptedStages)&&o.map(b=>h(b)?b.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance"&&h(o[10])&&E(o[10].completionEvidence,n.completionEvidence)&&E(o[10].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",ie=n.currentStageCommand==="arch-testing"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-testing"&&i.continuationState==="delegate"&&o.length===11&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",L=n.currentStageCommand==="arch-testing"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-infrastructure"&&i.continuationState==="advance"&&o.length===12&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===11&&E(o.slice(0,11),n.acceptedStages)&&o.map(b=>h(b)?b.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance,arch-testing"&&h(o[11])&&E(o[11].completionEvidence,n.completionEvidence)&&E(o[11].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",W=n.currentStageCommand==="arch-infrastructure"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-infrastructure"&&i.continuationState==="delegate"&&o.length===12&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",Qe=n.currentStageCommand==="arch-infrastructure"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-review"&&i.continuationState==="advance"&&o.length===13&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===12&&E(o.slice(0,12),n.acceptedStages)&&o.map(b=>h(b)?b.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance,arch-testing,arch-infrastructure"&&h(o[12])&&E(o[12].completionEvidence,n.completionEvidence)&&E(o[12].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",He=n.currentStageCommand==="arch-review"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-review"&&i.continuationState==="delegate"&&o.length===13&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",De=n.currentStageCommand==="arch-review"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&n.reviewDecision===void 0&&i?.currentStageCommand==="arch-review"&&i.continuationState==="ask-user"&&o.length===13&&E(o,n.acceptedStages)&&E(i.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&E(i.completionEvidence,n.completionEvidence)&&E(i.validationEvidence,n.validationEvidence)&&r?.nextAction==="ask-user",gt=n.currentStageCommand==="arch-review"&&n.continuationState==="ask-user"&&n.childStatus==="succeeded"&&h(n.reviewDecision)&&n.reviewDecision.decision==="approved"&&E(n.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&i?.currentStageCommand==="update-memory"&&i.continuationState==="advance"&&o.length===14&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===13&&E(o.slice(0,13),n.acceptedStages)&&h(o[13])&&o[13].stageCommand==="arch-review"&&E(o[13].completionEvidence,n.completionEvidence)&&E(o[13].validationEvidence,n.validationEvidence)&&E(i.reviewDecision,n.reviewDecision)&&r?.nextAction==="resume",ze=n.currentStageCommand==="update-memory"&&n.continuationState==="advance"&&h(n.reviewDecision)&&n.reviewDecision.decision==="approved"&&i?.currentStageCommand==="update-memory"&&i.continuationState==="delegate"&&o.length===14&&E(o,n.acceptedStages)&&E(i.reviewDecision,n.reviewDecision)&&r?.nextAction==="delegate",Z=n.currentStageCommand==="update-memory"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="update-memory"&&i.continuationState==="complete"&&o.length===15&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===14&&E(o.slice(0,14),n.acceptedStages)&&h(o[14])&&o[14].targetEpicId===n.targetEpicId&&o[14].stageCommand==="update-memory"&&E(o[14].completionEvidence,n.completionEvidence)&&E(o[14].validationEvidence,n.validationEvidence)&&E(i.reviewDecision,n.reviewDecision)&&E(i.completionEvidence,n.completionEvidence)&&E(i.validationEvidence,n.validationEvidence)&&qt(i.terminalMemoryCheckpoint,n)!==null&&E(i.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)&&r?.nextAction==="complete",le=n.currentStageCommand==="update-memory"&&n.continuationState==="complete"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="update-memory"&&i.continuationState==="complete"&&o.length===15&&E(o,n.acceptedStages)&&E(i.reviewDecision,n.reviewDecision)&&E(i.completionEvidence,n.completionEvidence)&&E(i.validationEvidence,n.validationEvidence)&&qt(i.terminalMemoryCheckpoint,n)&&E(i.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)&&r?.nextAction==="complete";if(e.metadata.mode!=="arch-plan"||e.metadata.resolvedTrigger!=="arch-plan"||!h(t)||!h(a)||t.owner!=="root"||t.currentStageCommand!==a.currentStageCommand||t.continuationState!==a.continuationState||a.owner!=="root"||a.evidencePolicy!=="v2-required"||a.targetEpicId!==n.targetEpicId||a.graphRevision!==n.graphRevision||a.graphSource!==n.graphSource||!/^P[1-9][0-9]{0,11}$/.test(String(a.targetEpicId))||!/^[a-f0-9]{64}$/.test(String(a.graphRevision))||!Array.isArray(a.acceptedStages)||!(s||u||f||S||_||l||y||I||C||M||T||z||A||v||D||N||V||F||B||U||H||fe||ie||L||W||Qe||He||De||gt||ze||Z||le)||!h(a.accounting)||a.accounting.charged!==!0||!E(en(a),a))throw new Error("architecture-root-checkpoint-invalid");const re=Q(e.projectRoot,".neocortex"),Xe=Q(re,"state.json"),Le=Q(re,"state.json.architecture.lock"),ft=Nt(Le,"wx",384);let me;try{const b=vt(Xe);if(!b.isFile()||b.isSymbolicLink())throw new Error("architecture-root-state-binding-invalid");const pe=ke(Xe,"utf8");if(Ge("sha256").update(pe).digest("hex")!==e.sourceStateSha256)throw new Error("architecture-root-state-conflict");const de=JSON.parse(pe),ae=h(de)&&h(de.archPlan)?de.archPlan:{};if(!h(de)||!h(de.epics)||!Object.hasOwn(de.epics,a.targetEpicId)||(e.initialBinding?ae.execution!==void 0||n.graphSource!=="committed-epic-v1":!E(en(ae.execution),n))||h(de.scope)&&de.scope.kind==="projected")throw new Error("architecture-root-state-binding-invalid");if(n.graphSource==="committed-epic-v1"&&n.graphRevision!==Pt(e.projectRoot,String(n.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");if(le){const Et={...n,continuationState:"delegate",acceptedStages:n.acceptedStages.slice(0,14)};if(!E(n.terminalMemoryCheckpoint,ln(e.projectRoot,Et)))throw new Error("architecture-root-state-conflict");return}const mt=Gt(),We=Ue("git",["rev-parse","--git-common-dir"],{cwd:e.projectRoot,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),he=pa(We)?Wn(We):Wn(e.projectRoot,We);if(da(he)!==he)throw new Error("architecture-root-backup-dir-invalid");const J=Q(he,"neocortex-architecture");Ot(J,{recursive:!0,mode:448});const yt=vt(J);if(!yt.isDirectory()||yt.isSymbolicLink()||yt.uid!==process.getuid?.()||(yt.mode&63)!==0)throw new Error("architecture-root-backup-dir-invalid");const k=Q(J,`state-backup-${mt}.json`),Ze=Nt(k,"wx",384);try{Ft(Ze,pe),Yt(Ze)}finally{Dt(Ze)}const g=Nt(J,"r");try{Yt(g)}finally{Dt(g)}const Ut={...de,archPlan:{...ae,execution:a}};me=Q(re,`state.json.architecture-tmp-${mt}`);const K=Nt(me,"wx",384);try{Ft(K,`${JSON.stringify(Ut,null,2)}
|
|
8
|
-
`),Yt(K)}finally{Dt(K)}if(Z&&!E(n.terminalMemoryCheckpoint,ln(e.projectRoot,n)))throw new Error("architecture-root-state-conflict");if(n.graphSource==="committed-epic-v1"&&n.graphRevision!==Pt(e.projectRoot,String(n.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");Hn(me,Xe),me=void 0;const Tt=Nt(re,"r");try{Yt(Tt)}finally{Dt(Tt)}}finally{if(me)try{hn(me)}catch{}Dt(ft),hn(Le)}}function tn(e,t){if(!h(e))return;const a={};for(const r of t){const i=e[r];if(typeof i=="boolean")a[r]=i;else if(typeof i=="number"&&Number.isFinite(i))a[r]=i;else if(typeof i=="string"){const n=ne(i);n&&(a[r]=n)}}return Object.keys(a).length>0?a:void 0}function nn(e){return e==="epic"||e==="story"?e:void 0}function Cr(e){if(!h(e)||e.schemaVersion!==1)return;const t=X(e.ownerStoryId),a=X(e.sessionId),r=X(e.idempotencyKey),i=Oe(e.acquiredAt),n=Oe(e.expiresAt);if(!(!t||!a||!r||!i||!n||Date.parse(n)<=Date.parse(i)))return{schemaVersion:1,ownerStoryId:t,sessionId:a,idempotencyKey:r,acquiredAt:i,expiresAt:n}}function wr(e){if(!h(e)||e.schemaVersion!==1)return;const t=X(e.storyId),a=X(e.epicId),r=Se(e.branch),i=R(e.baseSha),n=R(e.headSha),o=X(e.idempotencyKey),s=Oe(e.recordedAt),u=Pe(e.commits).map(R).filter(M=>!!M).slice(0,256),f=Pe(e.receiptRefs).map(it).filter(M=>!!M).slice(0,256),S=e.dispatchId===void 0?void 0:X(e.dispatchId),_=e.bundleId===void 0?void 0:X(e.bundleId),l=e.bundleDigest===void 0?void 0:R(e.bundleDigest),y=e.graphRevision===void 0?void 0:R(e.graphRevision),p=e.claimRevision===void 0?void 0:X(e.claimRevision),I=Mi(e.qaReceipt),C=Vi(e.reviewReceipt);if(!(!t||!a||!t.startsWith(`${a}.`)||!r||!i||!n||i===n||!o||!s||u.length===0||f.length===0||!Array.isArray(e.commits)||u.length!==e.commits.length||e.commits.length>256||!Array.isArray(e.receiptRefs)||f.length!==e.receiptRefs.length||e.receiptRefs.length>256||e.dispatchId!==void 0&&!S||e.bundleId!==void 0&&!_||e.bundleDigest!==void 0&&(!l||l.length!==64)||e.graphRevision!==void 0&&(!y||y.length!==64)||e.claimRevision!==void 0&&!p||e.qaVerdict!=="passed"&&e.qaVerdict!=="blocked"||!["approved","changes-requested","pending"].includes(String(e.reviewVerdict))||!I||e.reviewVerdict!=="pending"&&!C||e.reviewVerdict==="pending"&&C||I.verdict!==e.qaVerdict||C&&C.verdict!==e.reviewVerdict||!Rr(I,{storyId:t,epicId:a,baseSha:i,headSha:n,bundleDigest:l,graphRevision:y})||C&&(!Rr(C,{storyId:t,epicId:a,baseSha:i,headSha:n,bundleDigest:l,graphRevision:y})||C.qaReceiptRef!==I?.receiptRef||C.receiptRef===I?.receiptRef)||!f.includes(String(I.receiptRef))||C&&(!f.includes(String(C.receiptRef))||Date.parse(String(C.reviewedAt))<Date.parse(String(I.checkedAt)))))return{schemaVersion:1,storyId:t,epicId:a,branch:r,baseSha:i,headSha:n,idempotencyKey:o,...S?{dispatchId:S}:{},..._?{bundleId:_}:{},...l?{bundleDigest:l}:{},...y?{graphRevision:y}:{},...p?{claimRevision:p}:{},qaVerdict:e.qaVerdict,reviewVerdict:e.reviewVerdict,...I?{qaReceipt:I}:{},...C?{reviewReceipt:C}:{},recordedAt:s,commits:u,receiptRefs:f}}function Mi(e){if(!h(e)||e.schemaVersion!==1||e.kind!=="story_qa_evidence"||e.producer!=="local-yolo-tdd"||e.evidenceVersion!==void 0&&e.evidenceVersion!=="git-immutable-v1"&&e.evidenceVersion!=="p205-execution-v2"||!["passed","blocked"].includes(String(e.verdict)))return;const t=X(e.storyId),a=X(e.epicId),r=R(e.baseSha),i=R(e.headSha),n=R(e.bundleDigest),o=R(e.graphRevision),s=R(e.sourceEvidenceDigest),u=Oe(e.checkedAt),f=it(e.receiptRef),S=e.evidenceVersion==="p205-execution-v2"&&e.contract==="P205-CI-02"?e.contract:void 0,_=e.evidenceVersion==="p205-execution-v2"&&e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,l=e.evidenceVersion==="p205-execution-v2"?R(e.manifestDigest):void 0,y=e.evidenceVersion==="p205-execution-v2"?R(e.resultDigest):void 0,p=e.evidenceVersion==="p205-execution-v2"?Pe(e.gateIds).map(X).filter(I=>!!I).slice(0,64):void 0;if(!(!t||!a||!r||!i||!n||n.length!==64||!o||o.length!==64||!s||s.length!==64||!u||!f||e.evidenceVersion==="p205-execution-v2"&&(!S||_!=="node scripts/test-root.mjs --gate complete"||!l||l.length!==64||!y||y.length!==64||!Array.isArray(e.gateIds)||!p||p.length===0||p.length!==e.gateIds.length)))return{schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",...e.evidenceVersion?{evidenceVersion:e.evidenceVersion}:{},storyId:t,epicId:a,...e.evidenceVersion==="p205-execution-v2"?{contract:S,command:_,manifestDigest:l,gateIds:p,resultDigest:y}:{},baseSha:r,headSha:i,bundleDigest:n,graphRevision:o,sourceEvidenceDigest:s,verdict:e.verdict,checkedAt:u,receiptRef:f}}function _r(e){if(!h(e)||e.schemaVersion!==1||e.kind!=="story_checkpoint_physical_verification"||e.producer!=="client-p205-transient-v1"||e.publicSafe!==!0||e.verdict!=="verified"&&e.verdict!=="rejected")return;const t=X(e.storyId),a=X(e.epicId),r=Se(e.branch),i=R(e.baseSha),n=R(e.headSha),o=R(e.aggregateHeadSha),s=R(e.commitBodyDigest),u=R(e.changedPathsDigest),f=e.claimVerification==="canonical"||e.claimVerification==="legacy-migration"?e.claimVerification:void 0,S=R(e.effectiveClaimRevision),_=e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,l=R(e.manifestDigest),y=Pe(e.gateIds).map(X).filter(A=>!!A).slice(0,64),p=R(e.resultDigest),I=R(e.graphRevision),C=R(e.executionEvidenceDigest),M=R(e.sourceEvidenceDigest),T=Oe(e.verifiedAt),z=Pe(e.reasonCodes).map(X).filter(A=>!!A).slice(0,16);if(!(!t||!a||!r||!i||i.length<40||!n||n.length<40||!o||o.length<40||!s||s.length!==64||!u||u.length!==64||!f||!S||S.length!==64||!_||!l||l.length!==64||!Array.isArray(e.gateIds)||y.length!==e.gateIds.length||!p||p.length!==64||!I||I.length!==64||!C||C.length!==64||!M||M.length!==64||!T||z.length===0||e.verdict==="verified"&&(y.length===0||!z.includes("checkpoint-p205-transient-verified"))))return{schemaVersion:1,kind:"story_checkpoint_physical_verification",producer:"client-p205-transient-v1",storyId:t,epicId:a,branch:r,baseSha:i,headSha:n,aggregateHeadSha:o,commitBodyDigest:s,changedPathsDigest:u,claimVerification:f,effectiveClaimRevision:S,command:_,manifestDigest:l,gateIds:y,resultDigest:p,graphRevision:I,executionEvidenceDigest:C,sourceEvidenceDigest:M,verifiedAt:T,verdict:e.verdict,reasonCodes:z,publicSafe:!0}}function Ar(e){const t=["schemaVersion","kind","producer","storyId","epicId","branch","baseSha","headSha","graphRevision","effectiveClaimRevision","sourceEvidenceDigest","verifiedAt","reasonCodes","integrationAuthorized","publicSafe"];if(!h(e)||Object.keys(e).some(l=>!t.includes(l))||e.schemaVersion!==1||e.kind!=="story_scheduling_checkpoint_evidence"||e.producer!=="client-git-physical-v1"||e.integrationAuthorized!==!1||e.publicSafe!==!0)return;const a=X(e.storyId),r=X(e.epicId),i=Se(e.branch),n=R(e.baseSha),o=R(e.headSha),s=R(e.graphRevision),u=R(e.effectiveClaimRevision),f=R(e.sourceEvidenceDigest),S=Oe(e.verifiedAt),_=Pe(e.reasonCodes).map(X).filter(l=>!!l);if(!(!a||!r||!i||!n||n.length<40||!o||o.length<40||!s||s.length!==64||!u||u.length!==64||!f||f.length!==64||!S||!Array.isArray(e.reasonCodes)||_.length!==1||_[0]!=="checkpoint-git-scheduling-verified"))return{schemaVersion:1,kind:"story_scheduling_checkpoint_evidence",producer:"client-git-physical-v1",storyId:a,epicId:r,branch:i,baseSha:n,headSha:o,graphRevision:s,effectiveClaimRevision:u,sourceEvidenceDigest:f,verifiedAt:S,reasonCodes:_,integrationAuthorized:!1,publicSafe:!0}}function Vi(e){if(!h(e)||e.schemaVersion!==1||e.kind!=="story_review_evidence"||e.producer!=="root-commit-range-review"||!["approved","changes-requested"].includes(String(e.verdict)))return;const t=X(e.storyId),a=X(e.epicId),r=R(e.baseSha),i=R(e.headSha),n=R(e.bundleDigest),o=R(e.graphRevision),s=R(e.sourceEvidenceDigest),u=it(e.qaReceiptRef),f=Oe(e.reviewedAt),S=it(e.receiptRef);if(!(!t||!a||!r||!i||!n||n.length!==64||!o||o.length!==64||!s||s.length!==64||!u||!f||!S))return{schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:t,epicId:a,baseSha:r,headSha:i,bundleDigest:n,graphRevision:o,sourceEvidenceDigest:s,qaReceiptRef:u,verdict:e.verdict,reviewedAt:f,receiptRef:S}}function Rr(e,t){return["storyId","epicId","baseSha","headSha","bundleDigest","graphRevision"].every(a=>e[a]===t[a])}function br(e){if(!h(e)||e.schemaVersion!==1||e.capturedFromCurrentCheckout!==!0)return;const t=Se(e.originBranch),a=R(e.originHeadSha),r=Se(e.executionBranch),i=Oe(e.capturedAt);if(!(!t||!a||a.length<40||!r||!i||t===r))return{schemaVersion:1,originBranch:t,originHeadSha:a,executionBranch:r,capturedFromCurrentCheckout:!0,capturedAt:i}}function Tr(e){if(!h(e)||e.schemaVersion!==1||e.verdict!=="passed")return;const t=R(e.executionHeadSha),a=R(e.graphRevision),r=Oe(e.checkedAt),i=it(e.receiptRef),n=Pe(e.gateIds).map(X).filter(S=>!!S).slice(0,128),o=e.evidenceVersion==="p205-execution-v2"&&e.producer==="local-yolo-tdd"&&e.contract==="P205-CI-02"&&e.command==="node scripts/test-root.mjs --gate complete",s=e.evidenceVersion===void 0&&e.producer===void 0&&e.contract===void 0&&e.command===void 0&&e.manifestDigest===void 0&&e.resultDigest===void 0,u=o?R(e.manifestDigest):void 0,f=o?R(e.resultDigest):void 0;if(!(!t||t.length<40||!a||a.length!==64||!r||!i||n.length===0||!Array.isArray(e.gateIds)||n.length!==e.gateIds.length||e.gateIds.length>128||!s&&!o||o&&(!u||u.length!==64||!f||f.length!==64)))return{schemaVersion:1,...o?{evidenceVersion:"p205-execution-v2",producer:"local-yolo-tdd",contract:"P205-CI-02",command:"node scripts/test-root.mjs --gate complete",manifestDigest:u,resultDigest:f}:{},verdict:"passed",executionHeadSha:t,graphRevision:a,checkedAt:r,receiptRef:i,gateIds:n}}function Rn(e){if(!h(e)||e.schemaVersion!==1)return;const t=tn(e,["schemaVersion","kind","storyId","epicId","baseSha","headSha","originalBaseSha","originalHeadSha","gitPullRequest","preservesLaterCommits","historyRewrite","recordedAt"])??{},a=Pe(e.receiptRefs).map(it).filter(i=>!!i).slice(0,256),r=Pe(e.revertCommits).map(ne).filter(i=>!!i).slice(0,256);return{...t,...a.length?{receiptRefs:a}:{},...r.length?{revertCommits:r}:{}}}function Ui(e){if(!(!h(e)||Object.keys(e).sort().join(",")!=="gitPullRequest,headSha,kind,prNumber,reviewEvidenceDigest,schemaVersion"||e.schemaVersion!==1||e.kind!=="git-pull-request"||e.gitPullRequest!==!0||!Number.isSafeInteger(e.prNumber)||Number(e.prNumber)<=0||typeof e.headSha!="string"||!/^[a-f0-9]{40}$/.test(e.headSha)||typeof e.reviewEvidenceDigest!="string"||!/^[a-f0-9]{64}$/.test(e.reviewEvidenceDigest)))return{schemaVersion:1,kind:"git-pull-request",gitPullRequest:!0,prNumber:e.prNumber,headSha:e.headSha,reviewEvidenceDigest:e.reviewEvidenceDigest}}function xr(e){if(!h(e)||e.schemaVersion!==1||e.publicSafe!==!0)return;const t=X(e.epicId),a=Se(e.executionBranch),r=Se(e.originBranch),i=R(e.baseSha),n=R(e.executionHeadSha),o=e.mergeSha===void 0?void 0:R(e.mergeSha),s=e.pushedSha===void 0?void 0:R(e.pushedSha),u=X(e.idempotencyKey),f=Oe(e.attemptStartedAt),S=e.completedAt===void 0?void 0:Oe(e.completedAt),_=Pe(e.localGateReceiptRefs).map(it).filter(I=>!!I).slice(0,256),l=Pe(e.reasonCodes).map(X).filter(I=>!!I).slice(0,64),y=Bi(e.candidateQa),p=$i(e.providerGuard);if(!(!t||!a||!r||!i||!n||!u||!f||_.length===0||l.length===0||!["direct","single_pr"].includes(String(e.strategy))||!["prepared","merged","pushed","denied_external_gate","blocked_local_or_repo"].includes(String(e.physicalStatus))||typeof e.retryEligible!="boolean"||e.providerGuard!==void 0&&!p||p&&(e.strategy!=="single_pr"||e.physicalStatus!=="pushed"||p.prHeadSha!==o||p.originHeadSha!==i)))return{schemaVersion:1,epicId:t,executionBranch:a,originBranch:r,baseSha:i,executionHeadSha:n,...o?{mergeSha:o}:{},...s?{pushedSha:s}:{},strategy:e.strategy,...at(e.prNumber)?{prNumber:at(e.prNumber)}:{},physicalStatus:e.physicalStatus,localGateReceiptRefs:_,idempotencyKey:u,attemptStartedAt:f,...y?{candidateQa:y}:{},...p?{providerGuard:p}:{},...S?{completedAt:S}:{},retryEligible:e.retryEligible,reasonCodes:l,publicSafe:!0}}function $i(e){if(!h(e)||e.schemaVersion!==1||e.provider!=="github"||e.publicSafe!==!0)return;const t=String(e.mode),a=String(e.source),r=t==="recovered_exact_tree"?a==="physical_recovery":t==="strict_up_to_date_expected_head"&&["branch_protection","ruleset","branch_protection_and_ruleset"].includes(a),i=R(e.prHeadSha),n=R(e.originHeadSha),o=Oe(e.checkedAt);if(!(!r||!i||!n||!o))return{schemaVersion:1,provider:"github",mode:t,source:a,prHeadSha:i,originHeadSha:n,checkedAt:o,publicSafe:!0}}function Bi(e){if(!h(e)||e.schemaVersion!==1||e.kind!=="epic_merge_candidate_qa"||e.contract!=="P205-CI-02"||e.command!==oi)return;const a=Object.fromEntries(["originHeadSha","executionHeadSha","mergeSha","treeSha","graphRevision","manifestDigest","resultDigest"].map(o=>[o,R(e[o])])),r=Oe(e.checkedAt),i=it(e.receiptRef),n=Pe(e.gateIds).filter(o=>/^[a-z0-9-]+$/.test(o)).slice(0,128);if(!(Object.values(a).some(o=>!o)||!r||!i||n.length===0))return{schemaVersion:1,kind:e.kind,contract:e.contract,command:e.command,...a,checkedAt:r,receiptRef:i,gateIds:n}}function Hi(e){if(!h(e))return;const t={...ne(e.active_epic_id??e.activeEpicId)?{active_epic_id:ne(e.active_epic_id??e.activeEpicId)}:{},...ne(e.active_story_id??e.activeStoryId)?{active_story_id:ne(e.active_story_id??e.activeStoryId)}:{},...ne(e.active_step_id??e.activeStepId)?{active_step_id:ne(e.active_step_id??e.activeStepId)}:{},...ne(e.session_id??e.sessionId)?{session_id:ne(e.session_id??e.sessionId)}:{},...ne(e.started_at??e.startedAt)?{started_at:ne(e.started_at??e.startedAt)}:{}};return Object.keys(t).length>0?t:void 0}function Wi(e){const t=tn(e.completionEvidence??e.completion_evidence,["prNumber","pr_number","prState","pr_state","pullRequestState","merged","mergedAt","issueNumber","issue_number","issueState","issue_state","closedAt"]),a=tn(e.issueCloseAudit??e.issue_close_audit,["schema_version","event","storyId","epicId","issueNumber","closedAt","publicSafe","rawLogStorage"]),r=tn(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}:{},...ne(e.physicalMergeStatus)?{physicalMergeStatus:ne(e.physicalMergeStatus)}:{},...ne(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)?{pr_state:ne(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)}:{},...ne(e.issue_state??e.issueState??e.workflow_issue_state)?{issue_state:ne(e.issue_state??e.issueState??e.workflow_issue_state)}:{},...at(e.issue_number??e.issueNumber)?{issue_number:at(e.issue_number??e.issueNumber)}:{},...t?{completionEvidence:t}:{},...a?{issueCloseAudit:a}:{},...r?{scopedCiEvidence:r}:{}}}class ot extends Error{reasonCode;constructor(t){super(t),this.name="StateSnapshotIntegrityError",this.reasonCode=t}}const Gi=new Set(["yolo","yoloop","finalize-epic","audit"]);function kr(e){return typeof e=="string"&&Gi.has(e)}function Pr(e,t={}){const a=Q(e,".neocortex","state.json");if(!It(a))throw new ot("git-lifecycle-state-missing");let r;try{r=JSON.parse(ke(a,"utf8"))}catch{throw new ot("git-lifecycle-state-corrupt")}if(!h(r)||!h(r.epics)||!h(r.stories))throw new ot("git-lifecycle-state-shape-invalid");const i=Object.values(r.epics).some(n=>h(n)&&(n.branch_mode==="epic"||Se(n.execution_branch)!==void 0));if(i)try{Kt(e,{required:!0})}catch(n){const o=n instanceof Error&&/^git-lifecycle-/.test(n.message)?n.message:"git-lifecycle-runtime-invalid";if(t.allowMissingRuntime&&o==="git-lifecycle-runtime-missing")return{lifecycleDeclared:!0,runtimeMissing:!0};throw new ot(o)}return{lifecycleDeclared:i,runtimeMissing:!1}}function Or(e,t={}){const a=Q(e,".neocortex","state.json");if(!It(a)){if(t.epicAware&&!t.projectless)throw new ot("git-lifecycle-state-missing");return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}let r;try{const y=ke(a,"utf-8"),p=JSON.parse(y),I=h(p.epics)?p.epics:{},C=Object.values(I).some(v=>h(v)&&(v.branch_mode==="epic"||Se(v.execution_branch)!==void 0)),M=Kt(e,{required:!!(t.epicAware&&C&&!t.projectless)});r=cr(p,M);const T=h(r.stories)?r.stories:{},z=h(r.epics)?r.epics:{},A=h(p.stories)?p.stories:{};for(const[v,D]of Object.entries(T)){const N=h(D)?D:void 0;if(!N?.checkpoint)continue;const V=typeof N.epic_id=="string"?N.epic_id:v.split(".")[0],F=h(z[V])?z[V]:void 0,B=Se(F?.execution_branch);if(!B)continue;const U=ni(e,N.checkpoint,v,V,B,t.p205Authorities?.[v],sr(v,N,h(N.checkpoint)?N.checkpoint:void 0));if(U.kind==="integration-authorized")N.checkpoint_verification=U.verification,delete N.scheduling_checkpoint_evidence;else if(U.kind==="scheduling-only")N.scheduling_checkpoint_evidence=U.evidence,delete N.checkpoint,delete N.checkpoint_verification;else if(U.kind==="rejected"){N.checkpoint_verification=U.verification,delete N.scheduling_checkpoint_evidence;const H=h(A[v])?A[v]:void 0;if(delete N.checkpoint,M.stories[v]?.checkpoint!==void 0)for(const fe of["status","last_step","steps_completed"])H&&Object.prototype.hasOwnProperty.call(H,fe)?N[fe]=structuredClone(H[fe]):delete N[fe];["done","completed","merged"].includes(String(N.status).toLowerCase())&&(N.status="blocked")}}}catch(y){if(t.epicAware&&!t.projectless){const p=y instanceof Error&&/^git-lifecycle-/.test(y.message)?y.message:"git-lifecycle-state-corrupt";throw new ot(p)}return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}try{const y=xi(r);y.length>0&&ki(y)}catch{}const i=r.config??r.project??{},n=r.stories??{},o={};for(const[y,p]of Object.entries(n)){const I=h(p.review_request)&&p.review_request.kind==="git-pull-request"?Ui(p.review_request):Rn(p.review_request);o[y]={id:p.id??y,title:p.title,epic_id:p.epic_id,status:p.status??"backlog",...vr(p.source)?{source:vr(p.source)}:{},steps_completed:p.steps_completed??[],last_step:p.last_step??null,branch_name:p.branch_name??null,pr_number:p.pr_number,...nn(p.branch_mode)?{branch_mode:nn(p.branch_mode)}:{},...wr(p.checkpoint)?{checkpoint:wr(p.checkpoint)}:{},..._r(p.checkpoint_verification)?{checkpoint_verification:_r(p.checkpoint_verification)}:{},...Ar(p.scheduling_checkpoint_evidence)?{scheduling_checkpoint_evidence:Ar(p.scheduling_checkpoint_evidence)}:{},...I?{review_request:I}:{},...Rn(p.rollback_receipt)?{rollback_receipt:Rn(p.rollback_receipt)}:{},...at(p.workflow_issue)?{workflow_issue:at(p.workflow_issue)}:{},...Wi(p),depends_on:Ir(p.depends_on),files_to_modify:Pe(p.files_to_modify),...Li(p),risk:typeof p.risk=="string"?p.risk:void 0,blast_radius:typeof p.blast_radius=="number"?p.blast_radius:void 0}}const s=r.epics??{},u={};for(const[y,p]of Object.entries(s)){const I=Pi(p.lifecycle_classification),C=Di(p.createEpicPlanning,y);let M,T;if(C&&h(p.createEpicPlanningClaim)&&typeof p.createEpicPlanningClaim.claimId=="string"&&h(p.createEpicPlanningPhysical))try{Gn(r,p.createEpicPlanningClaim.claimId,y,!0),M=JSON.parse(JSON.stringify(p.createEpicPlanningPhysical))}catch{}if(M&&h(p.createEpicPlanningClaim)&&typeof p.createEpicPlanningClaim.claimId=="string"&&h(p.createEpicPlanningResearchPhysical))try{qn(r,p.createEpicPlanningClaim.claimId,y),T=JSON.parse(JSON.stringify(p.createEpicPlanningResearchPhysical))}catch{}u[y]={id:p.id??y,title:p.title,...C?{createEpicPlanning:C}:{},...M?{createEpicPlanningPhysical:M}:{},...T?{createEpicPlanningResearchPhysical:T}:{},status:p.status,stories:p.stories,total_stories:p.total_stories,completed_stories:p.completed_stories,depends_on:Ir(p.depends_on),...nn(p.branch_mode)?{branch_mode:nn(p.branch_mode)}:{},...Se(p.execution_branch)?{execution_branch:Se(p.execution_branch)}:{},...Se(p.origin_branch)?{origin_branch:Se(p.origin_branch)}:{},...Cr(p.branch_lease)?{branch_lease:Cr(p.branch_lease)}:{},...br(p.origin_binding)?{origin_binding:br(p.origin_binding)}:{},...Tr(p.aggregate_qa_receipt)?{aggregate_qa_receipt:Tr(p.aggregate_qa_receipt)}:{},...at(p.pr_number)?{pr_number:at(p.pr_number)}:{},...ne(p.physicalMergeStatus)?{physicalMergeStatus:ne(p.physicalMergeStatus)}:{},...R(p.graph_revision)?{graph_revision:R(p.graph_revision)}:{},...xr(p.terminal_git_receipt)?{terminal_git_receipt:xr(p.terminal_git_receipt)}:{},...I?{lifecycle_classification:I}:{}}}const f=Hi(r.current_session??r.currentSession),S=h(r.archPlan)?en(r.archPlan.execution):void 0,_=r.epic_id_ledger,l=Array.isArray(_?.reserved_ids)?[...new Set(_.reserved_ids.filter(y=>typeof y=="string"&&/^P\d+$/.test(y)))].slice(0,2048):[];return{schema_version:typeof r.schema_version=="number"?r.schema_version:void 0,config:{project_name:i.project_name??i.name??"unknown",default_branch:i.default_branch??"main",language:i.language??"pt-BR",yolo_mode:i.yolo_mode,user_name:i.user_name,worktree_base:i.worktree_base,max_parallel_stories:i.max_parallel_stories,project_id:typeof i.project_id=="string"?i.project_id:void 0},stories:o,epics:u,...l.length>0?{epic_id_ledger:{schema_version:1,reserved_ids:l}}:{},...f?{current_session:f}:{},...S?{archPlan:{execution:S}}:{}}}const bn=[["P222.01","fbc3176b33687b13a8fadf8c7ea7cc06b6b6c500"],["P222.02","c7d3feb9a168f9e15b35516a972c767f3aa357da"],["P222.03","4d9bd4f2a1a3a1dc6399c572eb84b8b74c017806"],["P222.04","66590ef2f706c9d036f42edf5e517b237724f74f"],["P222.05","3ee2662538311e9788796340ed11b65864a8d8d5"],["P222.06","8660d07e3f68503a9ceb24dc138d24f62ab6cb45"],["P222.07","d99c80feacee8ea4033aa3322990147fffa2df91"],["P222.08","1f9e37dc922d87908efefb9595db32d32db30b00"],["P222.09","5ae12e485900992658e346cf3e38568fda1c2eeb"],["P222.10","6c5b8dc4f03d629fea4b62a33f4794af8e27e4f0"],["P222.11","cfe90f2f955c0027c57e4c621141d17912db65cc"],["P222.12","65f253c5cb600a8ee1dd94a1efdfef2fa5cd1629"],["P222.13","1e78c75b393515803a55d1a9b63a7fec23f710c9"],["P222.14","3f3e0bfd247a8581170df2a23c89497b5ae3641e"],["P222.15","1fd6dd25fffa5714d4ffa8b4303735e417f93de6"]],Tn="6a41a47ff2521f80c2296ed811b0f0b304c54750",xn="dbc6d4670b2b7868a01973b1240e24589f1c5b7d",Nr="30dccfff07f9c969be11ae1d28e62a09731a0768";function qi(e,t){try{const a=t.indexOf(Nr);if(a<1||t[a-1]!==Tn)return new Map;const r=Ue("git",["show","--no-patch","--format=%P",Nr],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim(),i=Ue("git",["show","--no-patch","--format=%P",xn],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim();if(r!==`${Tn} ${xn}`||i!==`${bn.at(-1)[1]} ${Tn}`)return new Map;const n=Ue("git",["rev-list","--first-parent","--reverse",xn],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
|
|
9
|
-
`),o=new Map;let s=-1;for(const[u,[f,S]]of
|
|
10
|
-
`).filter(Boolean),_=new Map(S.map((v,D)=>[v,D])),l=qi(e,S),y=t.match(/(?:^|\s)@?docs\/stories\/([A-Za-z][A-Za-z0-9._-]*)\.story\.md(?:\s|$)/)?.[1],p=a==="yoloop"?t.match(/(?:^|[\s/@])epic-(P[1-9][0-9]*)\.md(?:\s|$)/i)?.[1]?.toUpperCase():void 0,I=new Set,C=Object.entries(o).flatMap(([v,D])=>{if(y&&v!==y)return[];const N=h(D)?D:void 0,
|
|
11
|
-
`),{}}}function
|
|
12
|
-
`),i=new
|
|
13
|
-
`),t}function
|
|
14
|
-
`)}async function uo(e){const t=Ta(e.args,{platformTarget:e.platformTarget,environment:e.environment??process.env});if(t.action==="skipped")return{shouldContinue:!0,attachToRequest:lo(t),metadata:
|
|
7
|
+
`)}catch{}}}function Kc(){Tn=!1}function wr(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Pi(e){return e==="active"||e==="archived"||e==="rolled-back"||e==="synthetic"||e==="orphan"?e:void 0}const Oi=new Set(["goal","problem","desiredOutcome","rawIntent","context","users","surfaces","constraints","assumptions","risks","nonGoals","validationExpectations","debtRefs","repositoryEvidencePaths","journeyIds","screenIds","storybookStoryIds","backendContractIds","featureBlockerIds","remediationRefs","uiScope","remediationStory","examples","contracts"]),Ni=/(?:[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}|(?:token|api[_-]?key|secret|password|credential|license[_-]?key)\s*[:=]\s*\S+|https?:\/\/(?:localhost|127\.0\.0\.1|10\.\d+\.\d+\.\d+|192\.168\.\d+\.\d+|172\.(?:1[6-9]|2\d|3[0-1])\.\d+\.\d+|[^\s/]*internal[^\s/]*)\S*|private\s+prompt|raw\s+vendor\s+corpus|sk-[A-Za-z0-9_-]{12,})/i;function Di(e,t){if(!(!h(e)||e.schemaVersion!==1||e.epicId!==t||!/^P\d+$/.test(t)))try{const a=JSON.stringify(e);if(Buffer.byteLength(a)>16384||Ni.test(a))return;const r=(n,o)=>{if(Object.keys(n).some(s=>!o.includes(s)))throw new Error("planning-unknown-field")};if(r(e,["schemaVersion","epicId","intake","intakeRevision","diagnosisReceipt","researchReceipt","degradeAuthorization"]),!h(e.intake)||Object.keys(e.intake).some(n=>!Oi.has(n)))return;for(const[n,o]of Object.entries(e.intake))if(["examples","contracts"].includes(n)){const s=n==="examples"?["id","title","actor","given","when","then","source","coveredRequirement","expectedValidation"]:["id","kind","description","path"];if(!Array.isArray(o)||o.length>16)return;for(const u of o)if(!h(u)||(r(u,s),Object.values(u).some(f=>typeof f!="string"||f.length>256)))return}else if(Array.isArray(o)){if(o.length>32||o.some(s=>typeof s!="string"||s.length>256))return}else if(typeof o=="string"){if(o.length>512)return}else if(typeof o!="boolean"||!["uiScope","remediationStory"].includes(n))return;const i=["schemaVersion","kind","epicId","intakeRevision","artifactSummary","artifactDigest","predecessorReceiptId","accepted","receiptId"];for(const n of[e.diagnosisReceipt,e.researchReceipt])if(n!==void 0&&(!h(n)||(r(n,i),Object.values(n).some(o=>typeof o=="string"&&o.length>1024))))return;if(e.degradeAuthorization!==void 0){if(!h(e.degradeAuthorization))return;r(e.degradeAuthorization,["approved","intakeRevision","reasonCodes","assumptionCodes"]);for(const n of["reasonCodes","assumptionCodes"]){const o=e.degradeAuthorization[n];if(!Array.isArray(o)||o.length>32||o.some(s=>typeof s!="string"||s.length>128))return}}return JSON.parse(a)}catch{return}}function _r(e){return e==="create-epic"||e==="discovered"?e:void 0}function xe(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Li(e){const t={};let a=!1;for(const r of["contracts","contract_refs","shared_surfaces","adr_refs","nfr_refs","acceptance_depends_on"]){if(e[r]===void 0)continue;const i=e[r];if(!Array.isArray(i)||i.length>128||i.some(n=>Qt(n)===void 0)){a=!0;continue}t[r]=i.map(n=>Qt(n))}if(e.planning!==void 0)try{if(!h(e.planning))throw new Error("planning-shape");const r=e.planning;for(const o of["claims","semanticArtifacts"]){if(r[o]===void 0)continue;const s=r[o];if(!Array.isArray(s)||s.length>128||s.some(u=>!h(u)||Qt(u.ref)===void 0))throw new Error("planning-refs")}if(r.attempts!==void 0&&(!Array.isArray(r.attempts)||r.attempts.length>32))throw new Error("planning-attempts");for(const o of r.attempts??[]){if(!h(o)||!Array.isArray(o.reasonCodes)||o.reasonCodes.length>32||o.reasonCodes.some(s=>typeof s!="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(s)))throw new Error("planning-attempt-reasons");if(o.discoveredClaims!==void 0&&(!Array.isArray(o.discoveredClaims)||o.discoveredClaims.length>128||o.discoveredClaims.some(s=>!h(s)||Qt(s.ref)===void 0)))throw new Error("planning-attempt-claims")}const{graphRevision:i,...n}=ti(r);t.planning=n}catch{a=!0}return a&&(t.planning={schemaVersion:1,dependencyBasis:"unknown",claims:[],semanticArtifacts:[]}),t}function h(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function it(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function ne(e){if(typeof e!="string")return;const t=e.trim();if(t)return t.replace(/[^a-z0-9_.:-]+/gi,"_").slice(0,120)}function Z(e){if(typeof e!="string")return;const t=e.trim(),a=ne(e);return a===t?a:void 0}function Se(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240)&&/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(t)&&!(t.includes("..")||t.includes("//")||t.includes("@{")||t.endsWith("/")||t.endsWith("."))&&!t.split("/").some(a=>!a||a.startsWith(".")||a.endsWith(".lock")))return t}function A(e){return typeof e=="string"&&/^[0-9a-f]{7,64}$/i.test(e)?e:void 0}function ke(e){if(!(typeof e!="string"||e.length>64)&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/.test(e))return Number.isFinite(Date.parse(e))?e:void 0}function ot(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240||t.includes("..")))return/^[A-Za-z0-9._:/#\-[\]]+$/.test(t)?t:void 0}function rn(e){if(!h(e))return;const t=l=>typeof l=="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,95}$/.test(l),a=l=>typeof l=="string"&&/^[a-f0-9]{64}$/.test(l),r=(l,y)=>Array.isArray(l)&&l.length<=y&&l.every(t)&&new Set(l).size===l.length?l:void 0,i=(l,y)=>{if(!(!h(l)||l.schemaVersion!==2||!t(l.requestId)||!t(l.stageCommand)||!a(l.requestHash)||!a(l.inputHash)||!a(l.stateHash)||!a(l.nonce)||!a(l.stageRevision)||!a(l.stageHash)||!a(l.catalogHash)||l.targetEpicId!==void 0&&!t(l.targetEpicId)||y&&(!a(l.outputHash)||!a(l.artifactHash))))return{schemaVersion:2,...l.targetEpicId?{targetEpicId:l.targetEpicId}:{},requestId:l.requestId,requestHash:l.requestHash,inputHash:l.inputHash,stateHash:l.stateHash,nonce:l.nonce,stageCommand:l.stageCommand,stageRevision:l.stageRevision,stageHash:l.stageHash,catalogHash:l.catalogHash,...y?{outputHash:l.outputHash,artifactHash:l.artifactHash}:{}}},n=(l,y)=>{if(!(!h(l)||l.schemaVersion!=="1.1"||l.kind!==y||!a(l.receiptId)||!a(l.graphHash)||!a(l.evidenceHash)||!t(l.elementId)||!t(l.caseId)||!t(l.category)))return{schemaVersion:"1.1",kind:y,receiptId:l.receiptId,graphHash:l.graphHash,elementId:l.elementId,caseId:l.caseId,category:l.category,evidenceHash:l.evidenceHash}},o=(l,y)=>{if(!h(l)||l.kind!==y||!a(l.receiptId)||!r(l.evidenceIds,24)||y==="architecture-stage-completion"&&!["succeeded","failed"].includes(String(l.status))||y==="architecture-stage-validation"&&!["passed","failed","pending"].includes(String(l.status)))return;const p=i(l,!0);if(!p)return;const I=y==="architecture-stage-validation"?n(l.isolated,"isolated"):void 0,C=y==="architecture-stage-validation"?n(l.regression,"regression"):void 0;if(!(y==="architecture-stage-validation"&&(!I||!C)))return{...p,kind:y,receiptId:l.receiptId,status:l.status,evidenceIds:l.evidenceIds,...I&&C?{isolated:I,regression:C}:{}}},s={};e.schemaVersion===1&&(s.schemaVersion=1),e.owner==="root"&&(s.owner="root"),t(e.currentStageCommand)&&(s.currentStageCommand=e.currentStageCommand),["ask-user","delegate","resume","advance","blocked","complete"].includes(String(e.continuationState))&&(s.continuationState=e.continuationState);const u=r(e.questionIds,16);u&&(s.questionIds=u),(e.childStatus==="succeeded"||e.childStatus==="failed")&&(s.childStatus=e.childStatus),(e.evidencePolicy==="legacy-compatible"||e.evidencePolicy==="v2-required")&&(s.evidencePolicy=e.evidencePolicy),t(e.targetEpicId)&&(s.targetEpicId=e.targetEpicId),a(e.graphRevision)&&(s.graphRevision=e.graphRevision),e.graphSource==="committed-epic-v1"&&(s.graphSource=e.graphSource),h(e.pactAnswerReceipt)&&Object.keys(e.pactAnswerReceipt).sort().join(",")===["schemaVersion","targetEpicId","graphRevision","stateSha256","answersSha256","questionIds","publicSafe"].sort().join(",")&&e.pactAnswerReceipt.schemaVersion==="PactAnswerReceipt/1"&&e.pactAnswerReceipt.targetEpicId===e.targetEpicId&&e.pactAnswerReceipt.graphRevision===e.graphRevision&&a(e.pactAnswerReceipt.stateSha256)&&a(e.pactAnswerReceipt.answersSha256)&&E(e.pactAnswerReceipt.questionIds,["PACT-Q1-CONSUMER","PACT-Q2-PROVIDER","PACT-Q3-BROKER","PACT-Q4-MATCHERS","PACT-Q5-VERIFY"])&&e.pactAnswerReceipt.publicSafe===!0&&(s.pactAnswerReceipt=e.pactAnswerReceipt);const f=i(e.evidenceExpectation,!1);f&&(s.evidenceExpectation=f);const S=o(e.completionEvidence,"architecture-stage-completion"),_=o(e.validationEvidence,"architecture-stage-validation");if(S&&(s.completionEvidence=S),_&&(s.validationEvidence=_),h(e.reviewDecision)&&Object.keys(e.reviewDecision).sort().join(",")===["schemaVersion","targetEpicId","graphRevision","artifactHash","completionReceiptId","validationReceiptId","decision","evidenceIds","publicSafe"].sort().join(",")&&e.reviewDecision.schemaVersion==="ArchitectureReviewDecision/1"&&e.reviewDecision.targetEpicId===e.targetEpicId&&e.reviewDecision.graphRevision===e.graphRevision&&a(e.reviewDecision.graphRevision)&&a(e.reviewDecision.artifactHash)&&a(e.reviewDecision.completionReceiptId)&&a(e.reviewDecision.validationReceiptId)&&["approved","changes-requested"].includes(String(e.reviewDecision.decision))&&e.reviewDecision.publicSafe===!0){const l=r(e.reviewDecision.evidenceIds,24);l&&l.length>0&&(s.reviewDecision={...e.reviewDecision,evidenceIds:l})}if(Yt(e.terminalMemoryCheckpoint,e))s.terminalMemoryCheckpoint=e.terminalMemoryCheckpoint;else if(h(e.terminalMemoryCheckpoint)&&e.terminalMemoryCheckpoint.schemaVersion===void 0&&["passed","failed","pending"].includes(String(e.terminalMemoryCheckpoint.status))){const l=r(e.terminalMemoryCheckpoint.evidenceIds,24);l&&(s.terminalMemoryCheckpoint={status:e.terminalMemoryCheckpoint.status,evidenceIds:l})}if(Array.isArray(e.acceptedStages)&&e.acceptedStages.length<=15){const l=e.acceptedStages.map(y=>{if(!h(y)||!t(y.targetEpicId)||!t(y.stageCommand))return;const p=o(y.completionEvidence,"architecture-stage-completion"),I=o(y.validationEvidence,"architecture-stage-validation");return p&&I?{targetEpicId:y.targetEpicId,stageCommand:y.stageCommand,completionEvidence:p,validationEvidence:I}:void 0});l.every(y=>y!==void 0)&&(s.acceptedStages=l)}if(h(e.accounting)&&e.accounting.schemaVersion===1&&t(e.accounting.contractVersion)&&t(e.accounting.accountingId)&&typeof e.accounting.charged=="boolean"&&Number.isInteger(e.accounting.chargedQuotaUnits)&&typeof e.accounting.chargedQuotaUnits=="number"&&e.accounting.chargedQuotaUnits>=0&&e.accounting.chargedQuotaUnits<=13){const l=r(e.accounting.receiptIds,32);l&&(s.accounting={schemaVersion:1,contractVersion:e.accounting.contractVersion,accountingId:e.accounting.accountingId,charged:e.accounting.charged,chargedQuotaUnits:e.accounting.chargedQuotaUnits,receiptIds:l,...["in-progress","aborted","timed-out","failed","complete"].includes(String(e.accounting.lastOutcome))?{lastOutcome:e.accounting.lastOutcome}:{}})}return JSON.stringify(s).length<=96e3?s:void 0}function ji(e){const t=h(e.metadata.archPlan)?e.metadata.archPlan.execution:void 0,a=h(t)?t.checkpoint:void 0,r=h(t)?t:void 0,i=h(a)?a:void 0,n=e.requestExecution,o=Array.isArray(i?.acceptedStages)?i.acceptedStages:[],s=n.currentStageCommand==="arch-prd"&&n.continuationState==="delegate"&&n.completionEvidence===void 0&&n.validationEvidence===void 0&&i?.currentStageCommand==="arch-prd"&&i.continuationState==="delegate"&&o.length===0&&r?.nextAction==="delegate",u=n.currentStageCommand==="arch-prd"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-architecture"&&i.continuationState==="advance"&&o.length===1&&h(o[0])&&o[0].stageCommand==="arch-prd"&&E(o[0].completionEvidence,n.completionEvidence)&&E(o[0].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",f=n.currentStageCommand==="arch-architecture"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-architecture"&&i.continuationState==="delegate"&&o.length===1&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",S=n.currentStageCommand==="arch-architecture"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-fitness-functions"&&i.continuationState==="advance"&&o.length===2&&h(o[0])&&h(o[1])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===1&&E(o[0],n.acceptedStages[0])&&E(o[1].completionEvidence,n.completionEvidence)&&E(o[1].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",_=n.currentStageCommand==="arch-fitness-functions"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-fitness-functions"&&i.continuationState==="delegate"&&o.length===2&&h(o[0])&&h(o[1])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",l=n.currentStageCommand==="arch-fitness-functions"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-api-contracts"&&i.continuationState==="advance"&&o.length===3&&h(o[0])&&h(o[1])&&h(o[2])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&o[2].stageCommand==="arch-fitness-functions"&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===2&&E(o.slice(0,2),n.acceptedStages)&&E(o[2].completionEvidence,n.completionEvidence)&&E(o[2].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",y=n.currentStageCommand==="arch-api-contracts"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-api-contracts"&&i.continuationState==="delegate"&&o.length===3&&h(o[0])&&h(o[1])&&h(o[2])&&o[0].stageCommand==="arch-prd"&&o[1].stageCommand==="arch-architecture"&&o[2].stageCommand==="arch-fitness-functions"&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",p=["PACT-Q1-CONSUMER","PACT-Q2-PROVIDER","PACT-Q3-BROKER","PACT-Q4-MATCHERS","PACT-Q5-VERIFY"],I=n.currentStageCommand==="arch-api-contracts"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="generate-pacts"&&i.continuationState==="ask-user"&&o.length===4&&h(o[3])&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===3&&E(o.slice(0,3),n.acceptedStages)&&o[3].stageCommand==="arch-api-contracts"&&E(o[3].completionEvidence,n.completionEvidence)&&E(o[3].validationEvidence,n.validationEvidence)&&E(i.questionIds,p)&&E(r?.questionIds,p)&&r?.nextAction==="ask-user",C=n.currentStageCommand==="generate-pacts"&&n.continuationState==="ask-user"&&i?.currentStageCommand==="generate-pacts"&&i.continuationState==="delegate"&&o.length===4&&E(o,n.acceptedStages)&&E(n.questionIds,p)&&E(i.questionIds,[])&&E(i.pactAnswerReceipt,e.answerReceipt)&&E(r?.pactAnswerReceipt,e.answerReceipt)&&e.answerReceipt?.stateSha256===e.sourceStateSha256&&r?.nextAction==="resume",V=n.currentStageCommand==="generate-pacts"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&E(n.pactAnswerReceipt,e.pactRecordedReceipt)&&i?.currentStageCommand==="arch-api-integrations"&&i.continuationState==="advance"&&o.length===5&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===4&&E(o.slice(0,4),n.acceptedStages)&&o.map(b=>h(b)?b.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts"&&h(o[4])&&E(o[4].completionEvidence,n.completionEvidence)&&E(o[4].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",T=n.currentStageCommand==="arch-api-integrations"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-api-integrations"&&i.continuationState==="delegate"&&o.length===5&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",z=n.currentStageCommand==="arch-api-integrations"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-database"&&i.continuationState==="advance"&&o.length===6&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===5&&E(o.slice(0,5),n.acceptedStages)&&o.map(b=>h(b)?b.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations"&&h(o[5])&&E(o[5].completionEvidence,n.completionEvidence)&&E(o[5].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",R=n.currentStageCommand==="arch-database"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-database"&&i.continuationState==="delegate"&&o.length===6&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",v=n.currentStageCommand==="arch-database"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-security"&&i.continuationState==="advance"&&o.length===7&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===6&&E(o.slice(0,6),n.acceptedStages)&&o.map(b=>h(b)?b.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database"&&h(o[6])&&E(o[6].completionEvidence,n.completionEvidence)&&E(o[6].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",D=n.currentStageCommand==="arch-security"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-security"&&i.continuationState==="delegate"&&o.length===7&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",N=n.currentStageCommand==="arch-security"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-design-system"&&i.continuationState==="advance"&&o.length===8&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===7&&E(o.slice(0,7),n.acceptedStages)&&o.map(b=>h(b)?b.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security"&&h(o[7])&&E(o[7].completionEvidence,n.completionEvidence)&&E(o[7].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",U=n.currentStageCommand==="arch-design-system"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-design-system"&&i.continuationState==="delegate"&&o.length===8&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",F=n.currentStageCommand==="arch-design-system"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-ux-design"&&i.continuationState==="advance"&&o.length===9&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===8&&E(o.slice(0,8),n.acceptedStages)&&o.map(b=>h(b)?b.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system"&&h(o[8])&&E(o[8].completionEvidence,n.completionEvidence)&&E(o[8].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",$=n.currentStageCommand==="arch-ux-design"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-ux-design"&&i.continuationState==="delegate"&&o.length===9&&E(o,n.acceptedStages)&&r?.nextAction==="blocked",j=n.currentStageCommand==="arch-ux-design"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-performance"&&i.continuationState==="advance"&&o.length===10&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===9&&E(o.slice(0,9),n.acceptedStages)&&o.map(b=>h(b)?b.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design"&&h(o[9])&&E(o[9].completionEvidence,n.completionEvidence)&&E(o[9].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",B=n.currentStageCommand==="arch-performance"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-performance"&&i.continuationState==="delegate"&&o.length===10&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",me=n.currentStageCommand==="arch-performance"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-testing"&&i.continuationState==="advance"&&o.length===11&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===10&&E(o.slice(0,10),n.acceptedStages)&&o.map(b=>h(b)?b.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance"&&h(o[10])&&E(o[10].completionEvidence,n.completionEvidence)&&E(o[10].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",ie=n.currentStageCommand==="arch-testing"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-testing"&&i.continuationState==="delegate"&&o.length===11&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",L=n.currentStageCommand==="arch-testing"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-infrastructure"&&i.continuationState==="advance"&&o.length===12&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===11&&E(o.slice(0,11),n.acceptedStages)&&o.map(b=>h(b)?b.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance,arch-testing"&&h(o[11])&&E(o[11].completionEvidence,n.completionEvidence)&&E(o[11].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",H=n.currentStageCommand==="arch-infrastructure"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-infrastructure"&&i.continuationState==="delegate"&&o.length===12&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",Qe=n.currentStageCommand==="arch-infrastructure"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="arch-review"&&i.continuationState==="advance"&&o.length===13&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===12&&E(o.slice(0,12),n.acceptedStages)&&o.map(b=>h(b)?b.stageCommand:null).join(",")==="arch-prd,arch-architecture,arch-fitness-functions,arch-api-contracts,generate-pacts,arch-api-integrations,arch-database,arch-security,arch-design-system,arch-ux-design,arch-performance,arch-testing,arch-infrastructure"&&h(o[12])&&E(o[12].completionEvidence,n.completionEvidence)&&E(o[12].validationEvidence,n.validationEvidence)&&r?.nextAction==="resume",Me=n.currentStageCommand==="arch-review"&&n.continuationState==="advance"&&i?.currentStageCommand==="arch-review"&&i.continuationState==="delegate"&&o.length===13&&E(o,n.acceptedStages)&&r?.nextAction==="delegate",Oe=n.currentStageCommand==="arch-review"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&n.reviewDecision===void 0&&i?.currentStageCommand==="arch-review"&&i.continuationState==="ask-user"&&o.length===13&&E(o,n.acceptedStages)&&E(i.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&E(i.completionEvidence,n.completionEvidence)&&E(i.validationEvidence,n.validationEvidence)&&r?.nextAction==="ask-user",mt=n.currentStageCommand==="arch-review"&&n.continuationState==="ask-user"&&n.childStatus==="succeeded"&&h(n.reviewDecision)&&n.reviewDecision.decision==="approved"&&E(n.questionIds,["ARCH-REVIEW-A09-APPROVAL"])&&i?.currentStageCommand==="update-memory"&&i.continuationState==="advance"&&o.length===14&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===13&&E(o.slice(0,13),n.acceptedStages)&&h(o[13])&&o[13].stageCommand==="arch-review"&&E(o[13].completionEvidence,n.completionEvidence)&&E(o[13].validationEvidence,n.validationEvidence)&&E(i.reviewDecision,n.reviewDecision)&&r?.nextAction==="resume",ze=n.currentStageCommand==="update-memory"&&n.continuationState==="advance"&&h(n.reviewDecision)&&n.reviewDecision.decision==="approved"&&i?.currentStageCommand==="update-memory"&&i.continuationState==="delegate"&&o.length===14&&E(o,n.acceptedStages)&&E(i.reviewDecision,n.reviewDecision)&&r?.nextAction==="delegate",Q=n.currentStageCommand==="update-memory"&&n.continuationState==="delegate"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="update-memory"&&i.continuationState==="complete"&&o.length===15&&Array.isArray(n.acceptedStages)&&n.acceptedStages.length===14&&E(o.slice(0,14),n.acceptedStages)&&h(o[14])&&o[14].targetEpicId===n.targetEpicId&&o[14].stageCommand==="update-memory"&&E(o[14].completionEvidence,n.completionEvidence)&&E(o[14].validationEvidence,n.validationEvidence)&&E(i.reviewDecision,n.reviewDecision)&&E(i.completionEvidence,n.completionEvidence)&&E(i.validationEvidence,n.validationEvidence)&&Yt(i.terminalMemoryCheckpoint,n)!==null&&E(i.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)&&r?.nextAction==="complete",he=n.currentStageCommand==="update-memory"&&n.continuationState==="complete"&&n.childStatus==="succeeded"&&i?.currentStageCommand==="update-memory"&&i.continuationState==="complete"&&o.length===15&&E(o,n.acceptedStages)&&E(i.reviewDecision,n.reviewDecision)&&E(i.completionEvidence,n.completionEvidence)&&E(i.validationEvidence,n.validationEvidence)&&Yt(i.terminalMemoryCheckpoint,n)&&E(i.terminalMemoryCheckpoint,n.terminalMemoryCheckpoint)&&r?.nextAction==="complete";if(e.metadata.mode!=="arch-plan"||e.metadata.resolvedTrigger!=="arch-plan"||!h(t)||!h(a)||t.owner!=="root"||t.currentStageCommand!==a.currentStageCommand||t.continuationState!==a.continuationState||a.owner!=="root"||a.evidencePolicy!=="v2-required"||a.targetEpicId!==n.targetEpicId||a.graphRevision!==n.graphRevision||a.graphSource!==n.graphSource||!/^P[1-9][0-9]{0,11}$/.test(String(a.targetEpicId))||!/^[a-f0-9]{64}$/.test(String(a.graphRevision))||!Array.isArray(a.acceptedStages)||!(s||u||f||S||_||l||y||I||C||V||T||z||R||v||D||N||U||F||$||j||B||me||ie||L||H||Qe||Me||Oe||mt||ze||Q||he)||!h(a.accounting)||a.accounting.charged!==!0||!E(rn(a),a))throw new Error("architecture-root-checkpoint-invalid");const re=X(e.projectRoot,".neocortex"),Xe=X(re,"state.json"),Ne=X(re,"state.json.architecture.lock"),yt=Vt(Ne,"wx",384);let ye;try{const b=_t(Xe);if(!b.isFile()||b.isSymbolicLink())throw new Error("architecture-root-state-binding-invalid");const pe=Te(Xe,"utf8");if(Ge("sha256").update(pe).digest("hex")!==e.sourceStateSha256)throw new Error("architecture-root-state-conflict");const de=JSON.parse(pe),ae=h(de)&&h(de.archPlan)?de.archPlan:{};if(!h(de)||!h(de.epics)||!Object.hasOwn(de.epics,a.targetEpicId)||(e.initialBinding?ae.execution!==void 0||n.graphSource!=="committed-epic-v1":!E(rn(ae.execution),n))||h(de.scope)&&de.scope.kind==="projected")throw new Error("architecture-root-state-binding-invalid");if(n.graphSource==="committed-epic-v1"&&n.graphRevision!==jt(e.projectRoot,String(n.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");if(he){const It={...n,continuationState:"delegate",acceptedStages:n.acceptedStages.slice(0,14)};if(!E(n.terminalMemoryCheckpoint,mn(e.projectRoot,It)))throw new Error("architecture-root-state-conflict");return}const Et=Ft(),We=je("git",["rev-parse","--git-common-dir"],{cwd:e.projectRoot,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),ge=pa(We)?Fn(We):Fn(e.projectRoot,We);if(da(ge)!==ge)throw new Error("architecture-root-backup-dir-invalid");const J=X(ge,"neocortex-architecture");Mt(J,{recursive:!0,mode:448});const St=_t(J);if(!St.isDirectory()||St.isSymbolicLink()||St.uid!==process.getuid?.()||(St.mode&63)!==0)throw new Error("architecture-root-backup-dir-invalid");const k=X(J,`state-backup-${Et}.json`),Ze=Vt(k,"wx",384);try{zt(Ze,pe),Jt(Ze)}finally{Ut(Ze)}const g=Vt(J,"r");try{Jt(g)}finally{Ut(g)}const Pt={...de,archPlan:{...ae,execution:a}};ye=X(re,`state.json.architecture-tmp-${Et}`);const K=Vt(ye,"wx",384);try{zt(K,`${JSON.stringify(Pt,null,2)}
|
|
8
|
+
`),Jt(K)}finally{Ut(K)}if(Q&&!E(n.terminalMemoryCheckpoint,mn(e.projectRoot,n)))throw new Error("architecture-root-state-conflict");if(n.graphSource==="committed-epic-v1"&&n.graphRevision!==jt(e.projectRoot,String(n.targetEpicId)))throw new Error("architecture-root-epic-binding-invalid");qn(ye,Xe),ye=void 0;const Ot=Vt(re,"r");try{Jt(Ot)}finally{Ut(Ot)}}finally{if(ye)try{yn(ye)}catch{}Ut(yt),yn(Ne)}}function an(e,t){if(!h(e))return;const a={};for(const r of t){const i=e[r];if(typeof i=="boolean")a[r]=i;else if(typeof i=="number"&&Number.isFinite(i))a[r]=i;else if(typeof i=="string"){const n=ne(i);n&&(a[r]=n)}}return Object.keys(a).length>0?a:void 0}function on(e){return e==="epic"||e==="story"?e:void 0}function Rr(e){if(!h(e)||e.schemaVersion!==1)return;const t=Z(e.ownerStoryId),a=Z(e.sessionId),r=Z(e.idempotencyKey),i=ke(e.acquiredAt),n=ke(e.expiresAt);if(!(!t||!a||!r||!i||!n||Date.parse(n)<=Date.parse(i)))return{schemaVersion:1,ownerStoryId:t,sessionId:a,idempotencyKey:r,acquiredAt:i,expiresAt:n}}function Ar(e){if(!h(e)||e.schemaVersion!==1)return;const t=Z(e.storyId),a=Z(e.epicId),r=Se(e.branch),i=A(e.baseSha),n=A(e.headSha),o=Z(e.idempotencyKey),s=ke(e.recordedAt),u=xe(e.commits).map(A).filter(V=>!!V).slice(0,256),f=xe(e.receiptRefs).map(ot).filter(V=>!!V).slice(0,256),S=e.dispatchId===void 0?void 0:Z(e.dispatchId),_=e.bundleId===void 0?void 0:Z(e.bundleId),l=e.bundleDigest===void 0?void 0:A(e.bundleDigest),y=e.graphRevision===void 0?void 0:A(e.graphRevision),p=e.claimRevision===void 0?void 0:Z(e.claimRevision),I=Mi(e.qaReceipt),C=Vi(e.reviewReceipt);if(!(!t||!a||!t.startsWith(`${a}.`)||!r||!i||!n||i===n||!o||!s||u.length===0||f.length===0||!Array.isArray(e.commits)||u.length!==e.commits.length||e.commits.length>256||!Array.isArray(e.receiptRefs)||f.length!==e.receiptRefs.length||e.receiptRefs.length>256||e.dispatchId!==void 0&&!S||e.bundleId!==void 0&&!_||e.bundleDigest!==void 0&&(!l||l.length!==64)||e.graphRevision!==void 0&&(!y||y.length!==64)||e.claimRevision!==void 0&&!p||e.qaVerdict!=="passed"&&e.qaVerdict!=="blocked"||!["approved","changes-requested","pending"].includes(String(e.reviewVerdict))||!I||e.reviewVerdict!=="pending"&&!C||e.reviewVerdict==="pending"&&C||I.verdict!==e.qaVerdict||C&&C.verdict!==e.reviewVerdict||!xr(I,{storyId:t,epicId:a,baseSha:i,headSha:n,bundleDigest:l,graphRevision:y})||C&&(!xr(C,{storyId:t,epicId:a,baseSha:i,headSha:n,bundleDigest:l,graphRevision:y})||C.qaReceiptRef!==I?.receiptRef||C.receiptRef===I?.receiptRef)||!f.includes(String(I.receiptRef))||C&&(!f.includes(String(C.receiptRef))||Date.parse(String(C.reviewedAt))<Date.parse(String(I.checkedAt)))))return{schemaVersion:1,storyId:t,epicId:a,branch:r,baseSha:i,headSha:n,idempotencyKey:o,...S?{dispatchId:S}:{},..._?{bundleId:_}:{},...l?{bundleDigest:l}:{},...y?{graphRevision:y}:{},...p?{claimRevision:p}:{},qaVerdict:e.qaVerdict,reviewVerdict:e.reviewVerdict,...I?{qaReceipt:I}:{},...C?{reviewReceipt:C}:{},recordedAt:s,commits:u,receiptRefs:f}}function Mi(e){if(!h(e)||e.schemaVersion!==1||e.kind!=="story_qa_evidence"||e.producer!=="local-yolo-tdd"||e.evidenceVersion!==void 0&&e.evidenceVersion!=="git-immutable-v1"&&e.evidenceVersion!=="p205-execution-v2"||!["passed","blocked"].includes(String(e.verdict)))return;const t=Z(e.storyId),a=Z(e.epicId),r=A(e.baseSha),i=A(e.headSha),n=A(e.bundleDigest),o=A(e.graphRevision),s=A(e.sourceEvidenceDigest),u=ke(e.checkedAt),f=ot(e.receiptRef),S=e.evidenceVersion==="p205-execution-v2"&&e.contract==="P205-CI-02"?e.contract:void 0,_=e.evidenceVersion==="p205-execution-v2"&&e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,l=e.evidenceVersion==="p205-execution-v2"?A(e.manifestDigest):void 0,y=e.evidenceVersion==="p205-execution-v2"?A(e.resultDigest):void 0,p=e.evidenceVersion==="p205-execution-v2"?xe(e.gateIds).map(Z).filter(I=>!!I).slice(0,64):void 0;if(!(!t||!a||!r||!i||!n||n.length!==64||!o||o.length!==64||!s||s.length!==64||!u||!f||e.evidenceVersion==="p205-execution-v2"&&(!S||_!=="node scripts/test-root.mjs --gate complete"||!l||l.length!==64||!y||y.length!==64||!Array.isArray(e.gateIds)||!p||p.length===0||p.length!==e.gateIds.length)))return{schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",...e.evidenceVersion?{evidenceVersion:e.evidenceVersion}:{},storyId:t,epicId:a,...e.evidenceVersion==="p205-execution-v2"?{contract:S,command:_,manifestDigest:l,gateIds:p,resultDigest:y}:{},baseSha:r,headSha:i,bundleDigest:n,graphRevision:o,sourceEvidenceDigest:s,verdict:e.verdict,checkedAt:u,receiptRef:f}}function br(e){if(!h(e)||e.schemaVersion!==1||e.kind!=="story_checkpoint_physical_verification"||e.producer!=="client-p205-transient-v1"||e.publicSafe!==!0||e.verdict!=="verified"&&e.verdict!=="rejected")return;const t=Z(e.storyId),a=Z(e.epicId),r=Se(e.branch),i=A(e.baseSha),n=A(e.headSha),o=A(e.aggregateHeadSha),s=A(e.commitBodyDigest),u=A(e.changedPathsDigest),f=e.claimVerification==="canonical"||e.claimVerification==="legacy-migration"?e.claimVerification:void 0,S=A(e.effectiveClaimRevision),_=e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,l=A(e.manifestDigest),y=xe(e.gateIds).map(Z).filter(R=>!!R).slice(0,64),p=A(e.resultDigest),I=A(e.graphRevision),C=A(e.executionEvidenceDigest),V=A(e.sourceEvidenceDigest),T=ke(e.verifiedAt),z=xe(e.reasonCodes).map(Z).filter(R=>!!R).slice(0,16);if(!(!t||!a||!r||!i||i.length<40||!n||n.length<40||!o||o.length<40||!s||s.length!==64||!u||u.length!==64||!f||!S||S.length!==64||!_||!l||l.length!==64||!Array.isArray(e.gateIds)||y.length!==e.gateIds.length||!p||p.length!==64||!I||I.length!==64||!C||C.length!==64||!V||V.length!==64||!T||z.length===0||e.verdict==="verified"&&(y.length===0||!z.includes("checkpoint-p205-transient-verified"))))return{schemaVersion:1,kind:"story_checkpoint_physical_verification",producer:"client-p205-transient-v1",storyId:t,epicId:a,branch:r,baseSha:i,headSha:n,aggregateHeadSha:o,commitBodyDigest:s,changedPathsDigest:u,claimVerification:f,effectiveClaimRevision:S,command:_,manifestDigest:l,gateIds:y,resultDigest:p,graphRevision:I,executionEvidenceDigest:C,sourceEvidenceDigest:V,verifiedAt:T,verdict:e.verdict,reasonCodes:z,publicSafe:!0}}function Tr(e){const t=["schemaVersion","kind","producer","storyId","epicId","branch","baseSha","headSha","graphRevision","effectiveClaimRevision","sourceEvidenceDigest","verifiedAt","reasonCodes","integrationAuthorized","publicSafe"];if(!h(e)||Object.keys(e).some(l=>!t.includes(l))||e.schemaVersion!==1||e.kind!=="story_scheduling_checkpoint_evidence"||e.producer!=="client-git-physical-v1"||e.integrationAuthorized!==!1||e.publicSafe!==!0)return;const a=Z(e.storyId),r=Z(e.epicId),i=Se(e.branch),n=A(e.baseSha),o=A(e.headSha),s=A(e.graphRevision),u=A(e.effectiveClaimRevision),f=A(e.sourceEvidenceDigest),S=ke(e.verifiedAt),_=xe(e.reasonCodes).map(Z).filter(l=>!!l);if(!(!a||!r||!i||!n||n.length<40||!o||o.length<40||!s||s.length!==64||!u||u.length!==64||!f||f.length!==64||!S||!Array.isArray(e.reasonCodes)||_.length!==1||_[0]!=="checkpoint-git-scheduling-verified"))return{schemaVersion:1,kind:"story_scheduling_checkpoint_evidence",producer:"client-git-physical-v1",storyId:a,epicId:r,branch:i,baseSha:n,headSha:o,graphRevision:s,effectiveClaimRevision:u,sourceEvidenceDigest:f,verifiedAt:S,reasonCodes:_,integrationAuthorized:!1,publicSafe:!0}}function Vi(e){if(!h(e)||e.schemaVersion!==1||e.kind!=="story_review_evidence"||e.producer!=="root-commit-range-review"||!["approved","changes-requested"].includes(String(e.verdict)))return;const t=Z(e.storyId),a=Z(e.epicId),r=A(e.baseSha),i=A(e.headSha),n=A(e.bundleDigest),o=A(e.graphRevision),s=A(e.sourceEvidenceDigest),u=ot(e.qaReceiptRef),f=ke(e.reviewedAt),S=ot(e.receiptRef);if(!(!t||!a||!r||!i||!n||n.length!==64||!o||o.length!==64||!s||s.length!==64||!u||!f||!S))return{schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:t,epicId:a,baseSha:r,headSha:i,bundleDigest:n,graphRevision:o,sourceEvidenceDigest:s,qaReceiptRef:u,verdict:e.verdict,reviewedAt:f,receiptRef:S}}function xr(e,t){return["storyId","epicId","baseSha","headSha","bundleDigest","graphRevision"].every(a=>e[a]===t[a])}function kr(e){if(!h(e)||e.schemaVersion!==1||e.capturedFromCurrentCheckout!==!0)return;const t=Se(e.originBranch),a=A(e.originHeadSha),r=Se(e.executionBranch),i=ke(e.capturedAt);if(!(!t||!a||a.length<40||!r||!i||t===r))return{schemaVersion:1,originBranch:t,originHeadSha:a,executionBranch:r,capturedFromCurrentCheckout:!0,capturedAt:i}}function Pr(e){if(!h(e)||e.schemaVersion!==1||e.verdict!=="passed")return;const t=A(e.executionHeadSha),a=A(e.graphRevision),r=ke(e.checkedAt),i=ot(e.receiptRef),n=xe(e.gateIds).map(Z).filter(S=>!!S).slice(0,128),o=e.evidenceVersion==="p205-execution-v2"&&e.producer==="local-yolo-tdd"&&e.contract==="P205-CI-02"&&e.command==="node scripts/test-root.mjs --gate complete",s=e.evidenceVersion===void 0&&e.producer===void 0&&e.contract===void 0&&e.command===void 0&&e.manifestDigest===void 0&&e.resultDigest===void 0,u=o?A(e.manifestDigest):void 0,f=o?A(e.resultDigest):void 0;if(!(!t||t.length<40||!a||a.length!==64||!r||!i||n.length===0||!Array.isArray(e.gateIds)||n.length!==e.gateIds.length||e.gateIds.length>128||!s&&!o||o&&(!u||u.length!==64||!f||f.length!==64)))return{schemaVersion:1,...o?{evidenceVersion:"p205-execution-v2",producer:"local-yolo-tdd",contract:"P205-CI-02",command:"node scripts/test-root.mjs --gate complete",manifestDigest:u,resultDigest:f}:{},verdict:"passed",executionHeadSha:t,graphRevision:a,checkedAt:r,receiptRef:i,gateIds:n}}function xn(e){if(!h(e)||e.schemaVersion!==1)return;const t=an(e,["schemaVersion","kind","storyId","epicId","baseSha","headSha","originalBaseSha","originalHeadSha","gitPullRequest","preservesLaterCommits","historyRewrite","recordedAt"])??{},a=xe(e.receiptRefs).map(ot).filter(i=>!!i).slice(0,256),r=xe(e.revertCommits).map(ne).filter(i=>!!i).slice(0,256);return{...t,...a.length?{receiptRefs:a}:{},...r.length?{revertCommits:r}:{}}}function Ui(e){if(!(!h(e)||Object.keys(e).sort().join(",")!=="gitPullRequest,headSha,kind,prNumber,reviewEvidenceDigest,schemaVersion"||e.schemaVersion!==1||e.kind!=="git-pull-request"||e.gitPullRequest!==!0||!Number.isSafeInteger(e.prNumber)||Number(e.prNumber)<=0||typeof e.headSha!="string"||!/^[a-f0-9]{40}$/.test(e.headSha)||typeof e.reviewEvidenceDigest!="string"||!/^[a-f0-9]{64}$/.test(e.reviewEvidenceDigest)))return{schemaVersion:1,kind:"git-pull-request",gitPullRequest:!0,prNumber:e.prNumber,headSha:e.headSha,reviewEvidenceDigest:e.reviewEvidenceDigest}}function Or(e){if(!h(e)||e.schemaVersion!==1||e.publicSafe!==!0)return;const t=Z(e.epicId),a=Se(e.executionBranch),r=Se(e.originBranch),i=A(e.baseSha),n=A(e.executionHeadSha),o=e.mergeSha===void 0?void 0:A(e.mergeSha),s=e.pushedSha===void 0?void 0:A(e.pushedSha),u=Z(e.idempotencyKey),f=ke(e.attemptStartedAt),S=e.completedAt===void 0?void 0:ke(e.completedAt),_=xe(e.localGateReceiptRefs).map(ot).filter(I=>!!I).slice(0,256),l=xe(e.reasonCodes).map(Z).filter(I=>!!I).slice(0,64),y=Bi(e.candidateQa),p=$i(e.providerGuard);if(!(!t||!a||!r||!i||!n||!u||!f||_.length===0||l.length===0||!["direct","single_pr"].includes(String(e.strategy))||!["prepared","merged","pushed","denied_external_gate","blocked_local_or_repo"].includes(String(e.physicalStatus))||typeof e.retryEligible!="boolean"||e.providerGuard!==void 0&&!p||p&&(e.strategy!=="single_pr"||e.physicalStatus!=="pushed"||p.prHeadSha!==o||p.originHeadSha!==i)))return{schemaVersion:1,epicId:t,executionBranch:a,originBranch:r,baseSha:i,executionHeadSha:n,...o?{mergeSha:o}:{},...s?{pushedSha:s}:{},strategy:e.strategy,...it(e.prNumber)?{prNumber:it(e.prNumber)}:{},physicalStatus:e.physicalStatus,localGateReceiptRefs:_,idempotencyKey:u,attemptStartedAt:f,...y?{candidateQa:y}:{},...p?{providerGuard:p}:{},...S?{completedAt:S}:{},retryEligible:e.retryEligible,reasonCodes:l,publicSafe:!0}}function $i(e){if(!h(e)||e.schemaVersion!==1||e.provider!=="github"||e.publicSafe!==!0)return;const t=String(e.mode),a=String(e.source),r=t==="recovered_exact_tree"?a==="physical_recovery":t==="strict_up_to_date_expected_head"&&["branch_protection","ruleset","branch_protection_and_ruleset"].includes(a),i=A(e.prHeadSha),n=A(e.originHeadSha),o=ke(e.checkedAt);if(!(!r||!i||!n||!o))return{schemaVersion:1,provider:"github",mode:t,source:a,prHeadSha:i,originHeadSha:n,checkedAt:o,publicSafe:!0}}function Bi(e){if(!h(e)||e.schemaVersion!==1||e.kind!=="epic_merge_candidate_qa"||e.contract!=="P205-CI-02"||e.command!==oi)return;const a=Object.fromEntries(["originHeadSha","executionHeadSha","mergeSha","treeSha","graphRevision","manifestDigest","resultDigest"].map(o=>[o,A(e[o])])),r=ke(e.checkedAt),i=ot(e.receiptRef),n=xe(e.gateIds).filter(o=>/^[a-z0-9-]+$/.test(o)).slice(0,128);if(!(Object.values(a).some(o=>!o)||!r||!i||n.length===0))return{schemaVersion:1,kind:e.kind,contract:e.contract,command:e.command,...a,checkedAt:r,receiptRef:i,gateIds:n}}function Hi(e){if(!h(e))return;const t={...ne(e.active_epic_id??e.activeEpicId)?{active_epic_id:ne(e.active_epic_id??e.activeEpicId)}:{},...ne(e.active_story_id??e.activeStoryId)?{active_story_id:ne(e.active_story_id??e.activeStoryId)}:{},...ne(e.active_step_id??e.activeStepId)?{active_step_id:ne(e.active_step_id??e.activeStepId)}:{},...ne(e.session_id??e.sessionId)?{session_id:ne(e.session_id??e.sessionId)}:{},...ne(e.started_at??e.startedAt)?{started_at:ne(e.started_at??e.startedAt)}:{}};return Object.keys(t).length>0?t:void 0}function Wi(e){const t=an(e.completionEvidence??e.completion_evidence,["prNumber","pr_number","prState","pr_state","pullRequestState","merged","mergedAt","issueNumber","issue_number","issueState","issue_state","closedAt"]),a=an(e.issueCloseAudit??e.issue_close_audit,["schema_version","event","storyId","epicId","issueNumber","closedAt","publicSafe","rawLogStorage"]),r=an(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}:{},...ne(e.physicalMergeStatus)?{physicalMergeStatus:ne(e.physicalMergeStatus)}:{},...ne(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)?{pr_state:ne(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)}:{},...ne(e.issue_state??e.issueState??e.workflow_issue_state)?{issue_state:ne(e.issue_state??e.issueState??e.workflow_issue_state)}:{},...it(e.issue_number??e.issueNumber)?{issue_number:it(e.issue_number??e.issueNumber)}:{},...t?{completionEvidence:t}:{},...a?{issueCloseAudit:a}:{},...r?{scopedCiEvidence:r}:{}}}class ct extends Error{reasonCode;constructor(t){super(t),this.name="StateSnapshotIntegrityError",this.reasonCode=t}}const Gi=new Set(["yolo","yoloop","finalize-epic","audit"]);function Nr(e){return typeof e=="string"&&Gi.has(e)}function Dr(e,t={}){const a=X(e,".neocortex","state.json");if(!wt(a))throw new ct("git-lifecycle-state-missing");let r;try{r=JSON.parse(Te(a,"utf8"))}catch{throw new ct("git-lifecycle-state-corrupt")}if(!h(r)||!h(r.epics)||!h(r.stories))throw new ct("git-lifecycle-state-shape-invalid");const i=Object.values(r.epics).some(n=>h(n)&&(n.branch_mode==="epic"||Se(n.execution_branch)!==void 0));if(i)try{Xt(e,{required:!0})}catch(n){const o=n instanceof Error&&/^git-lifecycle-/.test(n.message)?n.message:"git-lifecycle-runtime-invalid";if(t.allowMissingRuntime&&o==="git-lifecycle-runtime-missing")return{lifecycleDeclared:!0,runtimeMissing:!0};throw new ct(o)}return{lifecycleDeclared:i,runtimeMissing:!1}}function Lr(e,t={}){const a=X(e,".neocortex","state.json");if(!wt(a)){if(t.epicAware&&!t.projectless)throw new ct("git-lifecycle-state-missing");return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}let r;try{const y=Te(a,"utf-8"),p=JSON.parse(y),I=h(p.epics)?p.epics:{},C=Object.values(I).some(v=>h(v)&&(v.branch_mode==="epic"||Se(v.execution_branch)!==void 0)),V=Xt(e,{required:!!(t.epicAware&&C&&!t.projectless)});r=pr(p,V);const T=h(r.stories)?r.stories:{},z=h(r.epics)?r.epics:{},R=h(p.stories)?p.stories:{};for(const[v,D]of Object.entries(T)){const N=h(D)?D:void 0;if(!N?.checkpoint)continue;const U=typeof N.epic_id=="string"?N.epic_id:v.split(".")[0],F=h(z[U])?z[U]:void 0,$=Se(F?.execution_branch);if(!$)continue;const j=ni(e,N.checkpoint,v,U,$,t.p205Authorities?.[v],ur(v,N,h(N.checkpoint)?N.checkpoint:void 0));if(j.kind==="integration-authorized")N.checkpoint_verification=j.verification,delete N.scheduling_checkpoint_evidence;else if(j.kind==="scheduling-only")N.scheduling_checkpoint_evidence=j.evidence,delete N.checkpoint,delete N.checkpoint_verification;else if(j.kind==="rejected"){N.checkpoint_verification=j.verification,delete N.scheduling_checkpoint_evidence;const B=h(R[v])?R[v]:void 0;if(delete N.checkpoint,V.stories[v]?.checkpoint!==void 0)for(const me of["status","last_step","steps_completed"])B&&Object.prototype.hasOwnProperty.call(B,me)?N[me]=structuredClone(B[me]):delete N[me];["done","completed","merged"].includes(String(N.status).toLowerCase())&&(N.status="blocked")}}}catch(y){if(t.epicAware&&!t.projectless){const p=y instanceof Error&&/^git-lifecycle-/.test(y.message)?y.message:"git-lifecycle-state-corrupt";throw new ct(p)}return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}try{const y=xi(r);y.length>0&&ki(y)}catch{}const i=r.config??r.project??{},n=r.stories??{},o={};for(const[y,p]of Object.entries(n)){const I=h(p.review_request)&&p.review_request.kind==="git-pull-request"?Ui(p.review_request):xn(p.review_request);o[y]={id:p.id??y,title:p.title,epic_id:p.epic_id,status:p.status??"backlog",..._r(p.source)?{source:_r(p.source)}:{},steps_completed:p.steps_completed??[],last_step:p.last_step??null,branch_name:p.branch_name??null,pr_number:p.pr_number,...on(p.branch_mode)?{branch_mode:on(p.branch_mode)}:{},...Ar(p.checkpoint)?{checkpoint:Ar(p.checkpoint)}:{},...br(p.checkpoint_verification)?{checkpoint_verification:br(p.checkpoint_verification)}:{},...Tr(p.scheduling_checkpoint_evidence)?{scheduling_checkpoint_evidence:Tr(p.scheduling_checkpoint_evidence)}:{},...I?{review_request:I}:{},...xn(p.rollback_receipt)?{rollback_receipt:xn(p.rollback_receipt)}:{},...it(p.workflow_issue)?{workflow_issue:it(p.workflow_issue)}:{},...Wi(p),depends_on:wr(p.depends_on),files_to_modify:xe(p.files_to_modify),...Li(p),risk:typeof p.risk=="string"?p.risk:void 0,blast_radius:typeof p.blast_radius=="number"?p.blast_radius:void 0}}const s=r.epics??{},u={};for(const[y,p]of Object.entries(s)){const I=Pi(p.lifecycle_classification),C=Di(p.createEpicPlanning,y);let V,T;if(C&&h(p.createEpicPlanningClaim)&&typeof p.createEpicPlanningClaim.claimId=="string"&&h(p.createEpicPlanningPhysical))try{Yn(r,p.createEpicPlanningClaim.claimId,y,!0),V=JSON.parse(JSON.stringify(p.createEpicPlanningPhysical))}catch{}if(V&&h(p.createEpicPlanningClaim)&&typeof p.createEpicPlanningClaim.claimId=="string"&&h(p.createEpicPlanningResearchPhysical))try{zn(r,p.createEpicPlanningClaim.claimId,y),T=JSON.parse(JSON.stringify(p.createEpicPlanningResearchPhysical))}catch{}u[y]={id:p.id??y,title:p.title,...C?{createEpicPlanning:C}:{},...V?{createEpicPlanningPhysical:V}:{},...T?{createEpicPlanningResearchPhysical:T}:{},status:p.status,stories:p.stories,total_stories:p.total_stories,completed_stories:p.completed_stories,depends_on:wr(p.depends_on),...on(p.branch_mode)?{branch_mode:on(p.branch_mode)}:{},...Se(p.execution_branch)?{execution_branch:Se(p.execution_branch)}:{},...Se(p.origin_branch)?{origin_branch:Se(p.origin_branch)}:{},...Rr(p.branch_lease)?{branch_lease:Rr(p.branch_lease)}:{},...kr(p.origin_binding)?{origin_binding:kr(p.origin_binding)}:{},...Pr(p.aggregate_qa_receipt)?{aggregate_qa_receipt:Pr(p.aggregate_qa_receipt)}:{},...it(p.pr_number)?{pr_number:it(p.pr_number)}:{},...ne(p.physicalMergeStatus)?{physicalMergeStatus:ne(p.physicalMergeStatus)}:{},...A(p.graph_revision)?{graph_revision:A(p.graph_revision)}:{},...Or(p.terminal_git_receipt)?{terminal_git_receipt:Or(p.terminal_git_receipt)}:{},...I?{lifecycle_classification:I}:{}}}const f=Hi(r.current_session??r.currentSession),S=h(r.archPlan)?rn(r.archPlan.execution):void 0,_=r.epic_id_ledger,l=Array.isArray(_?.reserved_ids)?[...new Set(_.reserved_ids.filter(y=>typeof y=="string"&&/^P\d+$/.test(y)))].slice(0,2048):[];return{schema_version:typeof r.schema_version=="number"?r.schema_version:void 0,config:{project_name:i.project_name??i.name??"unknown",default_branch:i.default_branch??"main",language:i.language??"pt-BR",yolo_mode:i.yolo_mode,user_name:i.user_name,worktree_base:i.worktree_base,max_parallel_stories:i.max_parallel_stories,project_id:typeof i.project_id=="string"?i.project_id:void 0},stories:o,epics:u,...l.length>0?{epic_id_ledger:{schema_version:1,reserved_ids:l}}:{},...f?{current_session:f}:{},...S?{archPlan:{execution:S}}:{}}}const kn=[["P222.01","fbc3176b33687b13a8fadf8c7ea7cc06b6b6c500"],["P222.02","c7d3feb9a168f9e15b35516a972c767f3aa357da"],["P222.03","4d9bd4f2a1a3a1dc6399c572eb84b8b74c017806"],["P222.04","66590ef2f706c9d036f42edf5e517b237724f74f"],["P222.05","3ee2662538311e9788796340ed11b65864a8d8d5"],["P222.06","8660d07e3f68503a9ceb24dc138d24f62ab6cb45"],["P222.07","d99c80feacee8ea4033aa3322990147fffa2df91"],["P222.08","1f9e37dc922d87908efefb9595db32d32db30b00"],["P222.09","5ae12e485900992658e346cf3e38568fda1c2eeb"],["P222.10","6c5b8dc4f03d629fea4b62a33f4794af8e27e4f0"],["P222.11","cfe90f2f955c0027c57e4c621141d17912db65cc"],["P222.12","65f253c5cb600a8ee1dd94a1efdfef2fa5cd1629"],["P222.13","1e78c75b393515803a55d1a9b63a7fec23f710c9"],["P222.14","3f3e0bfd247a8581170df2a23c89497b5ae3641e"],["P222.15","1fd6dd25fffa5714d4ffa8b4303735e417f93de6"]],Pn="6a41a47ff2521f80c2296ed811b0f0b304c54750",On="dbc6d4670b2b7868a01973b1240e24589f1c5b7d",jr="30dccfff07f9c969be11ae1d28e62a09731a0768";function qi(e,t){try{const a=t.indexOf(jr);if(a<1||t[a-1]!==Pn)return new Map;const r=je("git",["show","--no-patch","--format=%P",jr],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim(),i=je("git",["show","--no-patch","--format=%P",On],{cwd:e,encoding:"utf8",maxBuffer:1024}).trim();if(r!==`${Pn} ${On}`||i!==`${kn.at(-1)[1]} ${Pn}`)return new Map;const n=je("git",["rev-list","--first-parent","--reverse",On],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
|
|
9
|
+
`),o=new Map;let s=-1;for(const[u,[f,S]]of kn.entries()){const _=n.indexOf(S);if(_<=s)return new Map;s=_,o.set(f,{headSha:S,position:u-kn.length})}return o}catch{return new Map}}async function Fi(e,t,a){if(!Nr(a))return{};if(Ca(t,a))return{};try{const r=JSON.parse(Te(X(e,".neocortex","state.json"),"utf8")),i=Xt(e,{required:!0}),n=pr(r,i),o=h(n.stories)?n.stories:{},s=h(n.epics)?n.epics:{},u=je("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8"}).trim(),f=je("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8"}).trim(),S=je("git",["rev-list","--first-parent","--reverse",u],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
|
|
10
|
+
`).filter(Boolean),_=new Map(S.map((v,D)=>[v,D])),l=qi(e,S),y=t.match(/(?:^|\s)@?docs\/stories\/([A-Za-z][A-Za-z0-9._-]*)\.story\.md(?:\s|$)/)?.[1],p=a==="yoloop"?t.match(/(?:^|[\s/@])epic-(P[1-9][0-9]*)\.md(?:\s|$)/i)?.[1]?.toUpperCase():void 0,I=new Set,C=Object.entries(o).flatMap(([v,D])=>{if(y&&v!==y)return[];const N=h(D)?D:void 0,U=h(N?.checkpoint)?N.checkpoint:void 0;if(!U)return[];const F=typeof N?.epic_id=="string"?N.epic_id:v.split(".")[0];if(p&&F!==p)return[];const $=A(U?.headSha),j=F==="P222"?l.get(v):void 0,B=_.get($??"")??(j&&j.headSha===$?j.position:void 0);if(!$||$.length<40||B===void 0)return I.add(F),[];const me=h(s[F])?s[F]:void 0;if(me?.branch_mode!=="epic"||Se(me.execution_branch)!==f||Se(U.branch)!==f)return I.add(F),[];const ie=A(U.graphRevision);if(!ie||ie.length!==64)return I.add(F),[];const L=A(U.claimRevision),H=[...ur(v,N,U)].sort(),Qe=ci(e,U,v,F,f,H);if(!Qe&&L){if(H.length===0)return I.add(F),[];const Me=je("git",["diff-tree","--no-commit-id","--name-only","-r","-z",$],{cwd:e,encoding:"utf8"}).split("\0").filter(Boolean);if(Me.length===0||Me.some(ze=>!H.some(Q=>Q===ze||Q.endsWith("/")&&ze.startsWith(Q))))return I.add(F),[];const Oe=Ge("sha256").update(H.join("\0")).digest("hex"),mt=Ge("sha256").update(JSON.stringify(H)).digest("hex");if(L!==Oe&&L!==mt)return I.add(F),[]}else if(!Qe)return I.add(F),[];return ie?.length===64?[{storyId:v,epicId:F,graphRevision:ie,checkpointHead:$,position:B}]:[]}),V=new Set(I);for(const[v,D]of Object.entries(s)){const N=h(D)?D:void 0,U=Array.isArray(N?.stories)?N.stories.filter(B=>typeof B=="string"):Object.keys(o).filter(B=>B.startsWith(`${v}.`)),F=C.filter(B=>B.epicId===v),$=U.filter(B=>F.some(me=>me.storyId===B)),j=[...F].sort((B,me)=>B.position-me.position).map(B=>B.storyId);(JSON.stringify($)!==JSON.stringify(j)||new Set(j).size!==j.length)&&V.add(v)}const T={},z=[...new Set(C.filter(v=>!V.has(v.epicId)).map(v=>v.graphRevision))],R=z.length>0?await ai(e,{headSha:u,graphRevisions:z}):new Map;for(const v of C){if(V.has(v.epicId))continue;const D=R.get(v.graphRevision);if(!D)throw new Error("p205-transient-authority-missing");T[v.storyId]=D}return T}catch(r){const i=r instanceof Error&&/^(?:p205|git-lifecycle)-[a-z0-9-]+$/.test(r.message)?r.message:"p205-transient-execution-failed";return process.stderr.write(`[Neocortex] ${i}. Checkpoint projection remains fail-closed.
|
|
11
|
+
`),{}}}function Qc(e,t){return{kind:"full",trigger:e,targetEpicId:null,targetStoryId:null,includedStoryCount:Object.keys(t.stories).length,includedEpicCount:Object.keys(t.epics).length,omittedStoryCount:0,omittedEpicCount:0,reason:"full-state",projectionMode:"full-compatible"}}const Mr="neocortex:menu:cache";async function Yi(e){try{const t=await e.get(Mr);if(!t)return null;const a=JSON.parse(t);return a.version!==Rt||Date.now()-a.cachedAt>hr?null:a}catch{return null}}async function zi(e,t,a){try{const r={instructions:t,metadata:a,cachedAt:Date.now(),version:Rt};await e.set(Mr,JSON.stringify(r),hr),Ji()}catch{}}function Ji(){try{wt(lr)&&yn(lr)}catch{}}function Ki(e){return e.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>Kn(),()=>Kn({strictReadOnly:!0}))}async function Vr(e,t,a){const r=a.mode==="strict";try{let i;if(r&&t)i=new En({cacheDir:vn,passphrase:t,strictReadOnly:!0});else if(r)i=new Jn;else if(t){const S=X(Zt,"cache");i=new En({cacheDir:S,passphrase:t})}else process.stderr.write(`[neocortex] Warning: No license key in config. Run "neocortex activate" to re-authenticate.
|
|
12
|
+
`),i=new Jn;const n=or(a,i,"auth-cache"),o=or(a,i,"tier-cache"),s=new ha({serverUrl:e,licenseKey:t??"",cacheProvider:n,strictReadOnly:r});let u;if(r){const S=await s.inspectToken();if(S.status!=="authenticated")return S;u=S.token}else u=await s.getToken();if(!u)return{status:"not-configured"};const f=new ga({cacheProvider:o,licenseClient:s});return{status:"authenticated",token:u,client:s,tierClient:f}}catch{return r&&t?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"}}}let Ur=!1;function Qi(e){const t=e.errorBody?.error_code;if(typeof t=="string"&&t.trim().length>0)return t;if(e.status===429)return"RATE_LIMITED";if(e.status>=500)return"SERVER_ERROR"}const $r=3,cn=50;function Xi(e){return new Promise(t=>setTimeout(t,e))}function Zi(e,t,a){return e.status>=500&&e.status<=599?!0:a&&e.status===409&&t.error_code==="SIGNATURE_REPLAYED"}async function Bt(e,t,a,r,i={}){const n=Math.max(1,Math.min(i.maxAttempts??$r,$r)),o=i.sleep??Xi;let s=r,u=!1,f=!1,S=0;for(let _=1;_<=n;_+=1){const l=Math.max(Math.floor(Date.now()/1e3),S+1);S=l;const y=eo(t,a,s,{nowSeconds:l}),p=new AbortController,I=setTimeout(()=>p.abort(),gr);try{const C=await fetch(`${e}${t}`,{method:"POST",headers:y.headers,body:y.body,signal:p.signal}),V=await C.text().catch(()=>""),T=(()=>{try{return V?JSON.parse(V):{}}catch{return{}}})();if(C.status===401&&!u&&i.refreshToken&&(T.fallback_action==="refresh_token"||T.fallback_action==="re_authenticate")){u=!0;const z=await i.refreshToken();if(z&&_<n){s=z,i.onTokenChanged?.(z),await o(cn*_);continue}}if(C.status===401&&T.error_code==="SIGNATURE_EXPIRED"&&!f&&_<n){f=!0,await o(cn*_);continue}if(_<n&&Zi(C,T,i.allowReplayRetry===!0)){await o(cn*_);continue}return{response:C,text:V,parsed:T,networkFailure:!1}}catch{if(_<n){await o(cn*_);continue}return{text:"",parsed:{},networkFailure:!0}}finally{clearTimeout(I)}}return{text:"",parsed:{},networkFailure:!0}}function eo(e,t,a,r={}){const i=Buffer.from(JSON.stringify(t),"utf8"),n=Ma({method:"POST",target:e,body:i,bearerToken:a,clientVersion:Rt,nowSeconds:r.nowSeconds,nonceBytes:r.nonceBytes});return{body:n.body,headers:{...n.headers,Authorization:`Bearer ${a}`}}}function Br(e){return Ge("sha256").update(e).digest("hex")}function to(){const e=Number(process.env.NEOCORTEX_INVOKE_CHUNK_BYTES??"49152");return Number.isFinite(e)&&e>=1024&&e<=98304?Math.floor(e):49152}function no(e,t,a){return`args-${Ge("sha256").update("invoke-materialization:v1").update(e).update(String(t)).update(JSON.stringify(a)).digest("hex")}`}async function Hr(e,t,a,r,i={}){const n=await Bt(e,t,a,r,{...i,allowReplayRetry:!0});if(n.networkFailure||!n.response)throw new Error("NETWORK_ERROR: materialization request failed after bounded retries");const{response:o,parsed:s}=n;if(!o.ok){const u=typeof s.error_code=="string"?s.error_code:`HTTP_${o.status}`,f=typeof s.message=="string"?s.message:"materialization upload failed";throw new Error(`${u}: ${f}`)}return s}async function ro(e,t,a,r){const i=Buffer.from(t,"utf8"),n=to(),o=[];for(let p=0,I=0;p<i.byteLength;p+=n,I++){const C=i.subarray(p,Math.min(p+n,i.byteLength));o.push({index:I,sha256:Br(C),byteLength:C.byteLength})}const s=Br(i),u=no(s,i.byteLength,o),f=Number(process.env.NEOCORTEX_INVOKE_CHUNK_TTL_SECONDS??"900");let S=a;const _={refreshToken:r,onTokenChanged(p){S=p}};for(const p of o){const I=p.index*n,C=i.subarray(I,I+p.byteLength);await Hr(e,"/api/v1/invoke/materialization/chunks",{manifestId:u,index:p.index,sha256:p.sha256,byteLength:p.byteLength,contentBase64:C.toString("base64"),ttlSeconds:f,idempotencyKey:`${u}:${p.index}:${p.sha256}`},S,_)}const y=(await Hr(e,"/api/v1/invoke/materialization/manifests",{manifestId:u,sha256:s,byteLength:i.byteLength,chunkCount:o.length,chunks:o,ttlSeconds:f,retry:{attempt:1,budget:3,idempotencyKey:u}},S,_)).argsRef;if(!y?.manifestId)throw new Error("MATERIALIZATION_RESPONSE_INVALID: missing argsRef");return{argsRef:y,chunks:o}}function Tt(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function ao(...e){const t=new Set,a=[];for(const r of e)for(const i of r??[]){const n=ne(i);if(!(!n||t.has(n))&&(t.add(n),a.push(n),a.length>=16))return a}return a}function io(e){const t=e.graphRetrieval;if(!h(t))return{accepted:!1,itemCount:0};const a=Array.isArray(t.items)?t.items.length:0;return{accepted:a>0||typeof t.retrievalId=="string"||t.accepted===!0,itemCount:a}}function Nn(e,t=Tt(e),a=[],r={}){const i=e.stateSnapshot.scope,n=Object.keys(e.stateSnapshot.stories).length,o=Object.keys(e.stateSnapshot.epics).length,s=i?.kind??"full";return{schemaVersion:1,payloadBytes:t,limitBytes:r.limitBytes??mr,warningThresholdBytes:r.warningThresholdBytes??Cn,scope:{kind:s,...i?.projectionMode?{projectionMode:i.projectionMode}:{},commandId:i?.commandId??null,stateProjectionPolicy:i?.stateProjectionPolicy??null},includedStories:i?.includedStoryCount??n,omittedStories:i?.omittedStoryCount??0,includedEpics:i?.includedEpicCount??o,omittedEpics:i?.omittedEpicCount??0,graphRetrieval:io(e.stateSnapshot),reasonCodes:ao(a,i?.reasonCodes),publicSafe:!0}}function oo(e){const t=h(e.budget)?e.budget:void 0,a=typeof t?.maxPayloadBytes=="number"&&Number.isFinite(t.maxPayloadBytes)?t.maxPayloadBytes:12*1024;return Math.max(1024,Math.min(a,12*1024))}function co(e){return h(e)?{stableId:ne(e.stableId)??"unknown",...h(e.source)?{source:e.source}:{},reasonCode:"budget_exceeded"}:{stableId:"unknown",reasonCode:"budget_exceeded"}}function Wr(e){const t=Array.isArray(e)?e.filter(a=>typeof a=="string"):[];return t.includes("budget_exceeded")?t:[...t,"budget_exceeded"]}function so(e){const t=e.graphRetrieval;if(!h(t)||!Array.isArray(t.items))return e;const a=oo(t);let r=[...t.items],i=Array.isArray(t.skipped)?[...t.skipped]:[],n=t;for(;Buffer.byteLength(JSON.stringify(n),"utf8")>a&&r.length>0;){const o=r.pop();i=[...i,co(o)].slice(-32),n={...t,items:r,skipped:i,warnings:Wr(t.warnings)}}return Buffer.byteLength(JSON.stringify(n),"utf8")>a&&(n={...t,query:typeof t.query=="string"?t.query.slice(0,240):t.query,items:[],skipped:[],warnings:Wr(t.warnings)}),n===t?e:{...e,graphRetrieval:n}}function Gr(e,t={}){const a=t.limitBytes??mr,r=t.warningThresholdBytes??Math.floor(a*yr),i=Tt(e);if(i<a)return{body:e,degraded:!1,telemetry:Nn(e,i,["payload-within-limit"],{limitBytes:a,warningThresholdBytes:r})};let n={...e,stateSnapshot:Ia(e.stateSnapshot)},o=["payload-size-guardrail","state-degraded"],s=Tt(n);s>=a&&(n={...n,stateSnapshot:so(n.stateSnapshot)},o=[...o,"graph-retrieval-budget-enforced"],s=Tt(n));const u=Nn(n,s,o,{limitBytes:a,warningThresholdBytes:r});if(s>=a){const f=n.stateSnapshot.scope?.projectionMode;throw f==="yolo-story"||f==="yoloop-target"||f==="yoloop-session"||f==="yoloop-discovery"||f==="structural-required"?new bn(u):new An(u)}return{body:n,degraded:!0,telemetry:u}}function qr(e){const t=e.stateSnapshot.scope?.commandId??"resolved-command";return e.args!==void 0?t:`${t}:argsRef`}function po(e){const t=Tt(e);if(t<Cn)return t;const a=Nn(e,t,["payload-warning-threshold"]);return process.stderr.write(`[Neocortex] invoke payload near server limit: trigger=${qr(e)} scope=${a.scope.kind} mode=${a.scope.projectionMode??a.scope.kind} payloadBytes=${a.payloadBytes} limit=${a.limitBytes} includedStories=${a.includedStories} omittedStories=${a.omittedStories} includedEpics=${a.includedEpics} omittedEpics=${a.omittedEpics} graphRetrieval.accepted=${a.graphRetrieval.accepted} graphRetrieval.itemCount=${a.graphRetrieval.itemCount} reasonCodes=${a.reasonCodes.join(",")||"none"}
|
|
13
|
+
`),t}function Fr(e,t){process.stderr.write(`[Neocortex] invoke payload guardrail: trigger=${qr(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"}
|
|
14
|
+
`)}async function uo(e){const t=Ta(e.args,{platformTarget:e.platformTarget,environment:e.environment??process.env});if(t.action==="skipped")return{shouldContinue:!0,attachToRequest:lo(t),metadata:Yr(t)};const a=e.bootstrapper??ka;let r;try{r=await a({projectRoot:e.projectRoot,env:e.environment??process.env,effectAuthority:e.effectAuthority})}catch{r={ok:!1,attempted:!0,installed:!1,started:!1,cached:!1,projectKey:"unknown",reasonCodes:[xa.UNEXPECTED_ERROR],publicSummary:"runner scheduler bootstrap stopped unexpectedly.",publicSafe:!0}}const i=Yr(t,r);if(r.ok)return{shouldContinue:!0,attachToRequest:!0,metadata:i};const n=i.reasonCodes.slice(0,5).join(",");return t.failurePolicy==="fail-open"?{shouldContinue:!0,attachToRequest:!0,metadata:{...i,failOpenWarning:!0},warning:`Runner auto-bootstrap warning (${n}); continuing fail-open for operator command.`}:{shouldContinue:!1,attachToRequest:!1,metadata:i,errorCode:"RUNNER_BOOTSTRAP_REQUIRED_FAILED",error:`Runner auto-bootstrap required but failed (${n}). Run neocortex-runner doctor or retry after resolving scheduler setup.`,exitCode:1}}function lo(e){return!e.reasonCodes.includes(ba.SKIPPED_NON_CONTINUITY_COMMAND)}function Yr(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:_e([...e.reasonCodes,...t?.reasonCodes??[]]),publicSummary:t?.publicSummary??e.publicSummary,publicSafe:!0}}function _e(e){return Array.from(new Set(e.map(t=>t.slice(0,120))))}function sn(e,t,a){const r=Math.floor(e??t);return Number.isFinite(r)?Math.max(1,Math.min(a,r)):t}function dn(e,t){const a=process.env[e];if(!a)return t;const r=Number(a);return Number.isFinite(r)?r:t}function G(e,t=Cr){const a=typeof e=="string"&&e.trim().length>0?e.trim():"unknown",r=Be(a,t),i=wi.test(r)?at:r;return i.length<=t?i:`${i.slice(0,t)}\u2026[TRUNCATED:${i.length-t}]`}function Dn(e,t=Cr){if(!(typeof e!="string"||e.trim().length===0))return G(e,t)}function Ln(e,t,a,r){const i=Dn(e?.targetId??t,120),n=e?.selectorKind??(i?Mn(i):void 0),o=(e?.relatedJobIds??[]).map(s=>Dn(s,120)).filter(s=>!!s);return{schemaVersion:1,contractVersion:"continuity-v1",targetResolutionState:a,...n?{targetKind:n}:{},...i?{targetId:i}:{},...t?{targetJobId:G(t,120)}:{},...e?.jobId?{jobId:G(e.jobId,120)}:{},...e?.goalId?{goalId:G(e.goalId,120)}:{},...e?.loopId?{loopId:G(e.loopId,120)}:{},...o.length>0?{relatedJobIds:o}:{},relatedJobCount:o.length,reasonCodes:_e(r.length>0?r:[W.OK]),publicSafe:!0}}function Je(e,t,a,r,i=[]){const n=(e?.redactions?.length??0)>0,o=e?n?"unsafe":a&&r===0?"empty":"available":"unavailable",s=Dn(t[t.length-1]?.eventId,120),u=i.length>0?i:o==="unavailable"?[W.WATCH_SNAPSHOT_UNAVAILABLE]:o==="empty"?[W.WATCH_NO_SUMMARIES_YET]:[W.OK];return{schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:o,...e?.generatedAt?{generatedAt:G(e.generatedAt,80)}:{},renderedSummaryCount:r,...s?{latestEventId:s}:{},reasonCodes:_e(u),publicSafe:!0}}function qe(e,t,a,r,i=[],n){const o=r[r.length-1],s=a??o?.cursor,u=!!(s&&s!==t&&r.length>0),f=n??(u?"advanced":t||s?"unchanged":"not_started"),S=i.length>0?i:f==="advanced"?[W.WATCH_CURSOR_ADVANCED]:f==="unavailable"?[W.WATCH_EVIDENCE_UNAVAILABLE]:[W.WATCH_CURSOR_UNCHANGED];return{schemaVersion:1,contractVersion:"continuity-v1",cursorState:f,...e?{initialCursor:G(e,200)}:{},...t?{currentCursor:G(t,200)}:{},...s?{nextCursor:G(s,200)}:{},cursorAdvanced:u,...o?.eventId?{eventId:G(o.eventId,120)}:{},reasonCodes:_e(S),publicSafe:!0}}function Fe(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:_e([...e.reasonCodes??[],...t?.reasonCodes??[],...e.snapshotEvidence?.reasonCodes??[],...e.cursorEvidence?.reasonCodes??[]]),generatedAt:G(e.generatedAt??new Date().toISOString(),80),publicSafe:!0}}function ho(e){const t=e.targetKind&&e.targetId?`${e.targetKind}/${e.targetId}`:e.targetId??"[unresolved]",a=e.snapshotEvidence?.renderedSummaryCount??0,r=e.targetEvidence?.relatedJobCount??0,i=e.cursorEvidence?.cursorState??"unavailable",n=e.cursorEvidence?.currentCursor??"[none]",o=e.cursorEvidence?.nextCursor??"[none]",s=e.snapshotEvidence?.snapshotStatus??"not_requested",u=e.snapshotEvidence?.generatedAt??e.generatedAt;return[`[watch-status] ${e.targetResolutionState==="unresolved"||e.stopReason==="target_unresolved"?"unresolved-target":a===0&&(e.watchStatus==="waiting"||e.watchStatus==="active")?"no-new-summary":e.watchStatus==="stopped"?"stopped":"lifecycle"}`,`status=${e.watchStatus}`,`active=${e.active}`,`target=${t}`,`resolution=${e.targetResolutionState??"unavailable"}`,`relatedJobs=${r}`,`summaries=${a}`,`snapshot=${s}`,`generatedAt=${u}`,`cursor=${i}`,`current=${G(n,200)}`,`next=${G(o,200)}`,`advanced=${e.cursorEvidence?.cursorAdvanced??!1}`,`stop=${e.stopReason??"not_stopped"}`,`reasons=${e.reasonCodes.join(",")}`].join(" ")}function Ye(e,t,a,r=!1){if(r){const i={type:"watch_status",watchStatus:e.watchStatus,active:e.active,renderedSummaryCount:e.snapshotEvidence?.renderedSummaryCount??0,stopReason:e.stopReason??"not_stopped",protectedProjection:!0,publicSafe:!0};a.write(t==="json"?`${JSON.stringify(i)}
|
|
15
15
|
`:`[watch-status] status=${i.watchStatus} active=${i.active} summaries=${i.renderedSummaryCount} stop=${i.stopReason}
|
|
16
16
|
`);return}if(t==="json"){a.write(JSON.stringify(e)+`
|
|
17
17
|
`);return}a.write(ho(e)+`
|
|
18
|
-
`)}function go(e,t,a){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:a,statusRecord:e,publicSafe:!0}}}function Ke(e,t,a,r,i=!1){return i?{status:e,summariesEmitted:t,polls:a,reasonCodes:[],watchStatus:r.watchStatus,stopReason:r.stopReason,metadata:{continuityInvokeWatch:{schemaVersion:1,contractVersion:"continuity-v1",command:"invoke",operation:"watch",watchStatus:r.watchStatus,stopReason:r.stopReason??"not_stopped",summariesEmitted:t,polls:a,protectedProjection:!0,publicSafe:!0}},publicSafe:!0}:{status:e,summariesEmitted:t,polls:a,reasonCodes:r.reasonCodes,watchStatus:r.watchStatus,stopReason:r.stopReason,targetEvidence:r.targetEvidence,snapshotEvidence:r.snapshotEvidence,cursorEvidence:r.cursorEvidence,statusRecord:r,metadata:go(r,t,a),publicSafe:!0}}function fo(e){const t=e.reasonCode?` reason=${
|
|
18
|
+
`)}function go(e,t,a){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:a,statusRecord:e,publicSafe:!0}}}function Ke(e,t,a,r,i=!1){return i?{status:e,summariesEmitted:t,polls:a,reasonCodes:[],watchStatus:r.watchStatus,stopReason:r.stopReason,metadata:{continuityInvokeWatch:{schemaVersion:1,contractVersion:"continuity-v1",command:"invoke",operation:"watch",watchStatus:r.watchStatus,stopReason:r.stopReason??"not_stopped",summariesEmitted:t,polls:a,protectedProjection:!0,publicSafe:!0}},publicSafe:!0}:{status:e,summariesEmitted:t,polls:a,reasonCodes:r.reasonCodes,watchStatus:r.watchStatus,stopReason:r.stopReason,targetEvidence:r.targetEvidence,snapshotEvidence:r.snapshotEvidence,cursorEvidence:r.cursorEvidence,statusRecord:r,metadata:go(r,t,a),publicSafe:!0}}function fo(e){const t=e.reasonCode?` reason=${G(e.reasonCode,80)}`:"",a=e.goalId?` goal=${G(e.goalId,100)}`:"",r=e.loopId?` loop=${G(e.loopId,100)}`:"";return`[watch] ${G(e.createdAt,80)} event=${G(e.eventId,120)} job=${G(e.jobId,100)}${a}${r} execution=${G(e.executionId,120)}${t} -- ${G(e.publicSummary)}`}function mo(e){return{type:"processing_summary",source:"local_continuity_sqlite",eventId:G(e.eventId,120),jobId:G(e.jobId,100),...e.goalId?{goalId:G(e.goalId,100)}:{},...e.loopId?{loopId:G(e.loopId,100)}:{},executionId:G(e.executionId,120),...e.reasonCode?{reasonCode:G(e.reasonCode,80)}:{},createdAt:G(e.createdAt,80),publicSummary:G(e.publicSummary),publicSafe:!0}}function yo(e,t,a,r=!1){if(r){a.write(t==="json"?`${JSON.stringify({type:"processing_summary",source:"local_continuity_sqlite",publicSummary:"A local processing update is available.",protectedProjection:!0,publicSafe:!0})}
|
|
19
19
|
`:`[watch] A local processing update is available.
|
|
20
20
|
`);return}if(t==="json"){a.write(JSON.stringify(mo(e))+`
|
|
21
21
|
`);return}a.write(fo(e)+`
|
|
22
|
-
`)}function Nn(e){return vi.has(e.status)}function Eo(e,t,a){if(t){const i=e.find(n=>n.jobId===t);return!!(i&&Nn(i))}return a<=0?!1:e.filter(i=>!Nn(i)).length===0}function So(e,t,a,r){return a<r?!1:t?!e.some(i=>i.jobId===t&&!Nn(i)):e.length===0}function Io(e,t){return t?.aborted?Promise.resolve():new Promise(a=>{const r=setTimeout(i,e);function i(){clearTimeout(r),t?.removeEventListener("abort",i),a()}t?.addEventListener("abort",i,{once:!0})})}function vo(e){return e.includes(we.MALFORMED)?"malformed":e.includes(we.AMBIGUOUS)?"ambiguous":e.includes("watch-target-multiple")?"multiple":e.includes("watch-evidence-unsafe")?"unsafe":e.includes(we.MISSING)||e.includes(ge.TARGET_UNRESOLVED)?"unresolved":"unavailable"}function qr(e,t){const a=t?Mt(t):void 0,r=Ae([...e,ge.TARGET_UNRESOLVED,G.WATCH_TARGET_UNRESOLVED]),i=On(a,a?.targetId,vo(r),r),n=Je({generatedAt:new Date().toISOString()},[],!1,0,[G.WATCH_TARGET_UNRESOLVED]),o=qe(void 0,void 0,void 0,[],[G.WATCH_TARGET_UNRESOLVED],"unavailable");return Fe({watchStatus:"blocked",active:!1,targetEvidence:i,snapshotEvidence:n,cursorEvidence:o,stopReason:"target_unresolved",reasonCodes:r,generatedAt:n.generatedAt})}function Co(e,t,a,r,i=!1){const n=qr(e,Yr(t));return Ye(n,a,r,i),Ke("target-unresolved",0,0,n,i)}async function wo(e){if(e.signal?.aborted){const A=On(e.target??Mt(e.targetJobId),e.targetJobId,e.target??e.targetJobId?"resolved":"unresolved",[ge.CANCELLED]),v=Je(void 0,[],!1,0),D=qe(e.initialCursor,e.initialCursor,e.initialCursor,[],[ge.CANCELLED],"unavailable"),N=Fe({watchStatus:"stopped",active:!1,targetEvidence:A,snapshotEvidence:v,cursorEvidence:D,stopReason:"cancelled",reasonCodes:[ge.CANCELLED]});return Ke("cancelled",0,0,N,e.protectedOutput)}const t=e.target??Mt(e.targetJobId),a=e.targetJobId??t?.targetId,r=e.stdout??process.stdout;if(!t){const A=qr([we.MISSING,ge.TARGET_UNRESOLVED]);return Ye(A,e.format,r,e.protectedOutput),Ke("target-unresolved",0,0,A,e.protectedOutput)}const i=an(e.limit??on("NEOCORTEX_INVOKE_WATCH_LIMIT",Zn),Zn,50),n=Math.max(50,an(e.pollIntervalMs??on("NEOCORTEX_INVOKE_WATCH_POLL_INTERVAL_MS",nr),nr,6e4)),o=an(e.maxIdlePolls??on("NEOCORTEX_INVOKE_WATCH_MAX_IDLE_POLLS",er),er,120),s=an(e.maxPolls??on("NEOCORTEX_INVOKE_WATCH_MAX_POLLS",tr),tr,86400),u=e.sleep??Io;let f=e.initialCursor,S=0,_=0,l=0;const y=On(t,a,"resolved",[G.OK]),p={schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:"pending",renderedSummaryCount:0,reasonCodes:[G.WATCH_RENDER_PENDING],publicSafe:!0},I=qe(e.initialCursor,f,f,[],e.initialCursor?[G.WATCH_CURSOR_UNCHANGED]:[G.WATCH_NO_SUMMARIES_YET],e.initialCursor?"unchanged":"not_started");Ye(Fe({watchStatus:"active",active:!0,targetEvidence:y,snapshotEvidence:p,cursorEvidence:I,stopReason:"not_stopped",reasonCodes:[G.OK]}),e.format,r,e.protectedOutput);let C;try{C=await Oa({projectRoot:e.projectRoot,strictReadOnly:e.strictReadOnly})}catch{const A=Je(void 0,[],!1,S,[G.WATCH_SNAPSHOT_UNAVAILABLE]),v=qe(e.initialCursor,f,f,[],[G.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),D=Fe({watchStatus:"blocked",active:!1,targetEvidence:y,snapshotEvidence:A,cursorEvidence:v,stopReason:"unavailable_evidence",reasonCodes:[ge.STORE_UNAVAILABLE]});return Ye(D,e.format,r,e.protectedOutput),Ke("store-unavailable",S,l,D,e.protectedOutput)}try{for(;!e.signal?.aborted&&l<s;){l+=1;const A=f,v=C.collectProcessingOutputSummaryCursor({...f?{cursor:f}:{},...t?{target:t}:{},...a?{jobId:a}:{},limit:i}),D=C.collectSnapshot({jobLimit:50,processingSummaryLimit:1}),N=D.jobs;if(v.summaries.length>0){for(const B of v.summaries)yo(B,e.format,r,e.protectedOutput),S+=1;f=v.nextCursor??v.summaries[v.summaries.length-1]?.cursor??f,_=0}else f=v.nextCursor??f,_+=1;const V=Je(D,v.summaries,!0,v.summaries.length),F=qe(e.initialCursor,A,f,v.summaries,v.summaries.length>0?[G.WATCH_CURSOR_ADVANCED]:[G.WATCH_NO_SUMMARIES_YET]);if(Ye(Fe({watchStatus:v.summaries.length>0?"polling":"waiting",active:!0,targetEvidence:y,snapshotEvidence:V,cursorEvidence:F,stopReason:"not_stopped",reasonCodes:v.summaries.length>0?[G.WATCH_CURSOR_ADVANCED]:[G.WATCH_NO_SUMMARIES_YET],generatedAt:D.generatedAt}),e.format,r,e.protectedOutput),!v.hasMore&&Eo(N,a,S)){const B=Je(D,v.summaries,!1,S,[ge.COMPLETED]),U=qe(e.initialCursor,A,f,v.summaries,[ge.COMPLETED],"exhausted"),H=Fe({watchStatus:"stopped",active:!1,targetEvidence:y,snapshotEvidence:B,cursorEvidence:U,stopReason:"not_stopped",reasonCodes:[ge.COMPLETED],generatedAt:D.generatedAt});return Ye(H,e.format,r,e.protectedOutput),Ke("completed",S,l,H,e.protectedOutput)}if(!v.hasMore&&So(N,a,_,o)){const B=Je(D,v.summaries,!1,S,[G.WATCH_STOP_IDLE_LIMIT_REACHED]),U=qe(e.initialCursor,A,f,v.summaries,[G.WATCH_STOP_IDLE_LIMIT_REACHED],"exhausted"),H=Fe({watchStatus:"stopped",active:!1,targetEvidence:y,snapshotEvidence:B,cursorEvidence:U,stopReason:"idle_limit_reached",reasonCodes:[ge.IDLE_TIMEOUT,G.WATCH_STOP_IDLE_LIMIT_REACHED],generatedAt:D.generatedAt});return Ye(H,e.format,r,e.protectedOutput),Ke("idle-timeout",S,l,H,e.protectedOutput)}v.hasMore||await u(n,e.signal)}}catch{const A=Je(void 0,[],!1,S,[G.WATCH_SNAPSHOT_UNAVAILABLE]),v=qe(e.initialCursor,f,f,[],[G.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),D=Fe({watchStatus:"blocked",active:!1,targetEvidence:y,snapshotEvidence:A,cursorEvidence:v,stopReason:"unavailable_evidence",reasonCodes:[ge.STORE_UNAVAILABLE]});return Ye(D,e.format,r,e.protectedOutput),Ke("store-unavailable",S,l,D,e.protectedOutput)}finally{C.close()}if(e.signal?.aborted){const A=Je(void 0,[],!1,S,[ge.CANCELLED]),v=qe(e.initialCursor,f,f,[],[ge.CANCELLED],"unavailable"),D=Fe({watchStatus:"stopped",active:!1,targetEvidence:y,snapshotEvidence:A,cursorEvidence:v,stopReason:"cancelled",reasonCodes:[ge.CANCELLED]});return Ye(D,e.format,r,e.protectedOutput),Ke("cancelled",S,l,D,e.protectedOutput)}const M=Je(void 0,[],!1,S,[G.WATCH_STOP_MAX_POLLS_REACHED]),T=qe(e.initialCursor,f,f,[],[G.WATCH_STOP_MAX_POLLS_REACHED],"exhausted"),z=Fe({watchStatus:"stopped",active:!1,targetEvidence:y,snapshotEvidence:M,cursorEvidence:T,stopReason:"max_polls_reached",reasonCodes:[ge.MAX_POLLS,G.WATCH_STOP_MAX_POLLS_REACHED]});return Ye(z,e.format,r,e.protectedOutput),Ke("max-polls",S,l,z,e.protectedOutput)}function Be(e){const t=e.trim().replace(/^@/,"").match(/^(job|goal|loop)-([JGL])(\d{3,})$/i);if(!t)return;const a=t[1].toLowerCase(),r=t[2].toUpperCase();if(!(a==="job"&&r!=="J"||a==="goal"&&r!=="G"||a==="loop"&&r!=="L"))return`${a}-${r}${t[3]}`}function Dn(e){if(e.startsWith("job-J"))return"job";if(e.startsWith("goal-G"))return"goal";if(e.startsWith("loop-L"))return"loop"}function Fr(e){const t=[],a=/(?:^|[\s"'([,{])@?(job-[Jj]\d{3,}|goal-[Gg]\d{3,}|loop-[Ll]\d{3,})(?=$|[\s"')\]},.;:!?])/g;let r;for(;(r=a.exec(e))!==null;){const i=Be(r[1]);i&&t.push(i)}return Ae(t)}function Yr(e){return Fr(e)[0]}function Mt(e){const t=e?Be(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 Ln(e){return Ae(e.filter(t=>typeof t=="string").map(t=>Be(t)).filter(t=>!!t?.startsWith("job-J")))}function _o(e,t){const a=Ln(t).filter(r=>r!==e.targetId&&r!==e.jobId);return a.length>0?{...e,relatedJobIds:a}:e}function Ao(e){if(!e)return;const t=h(e.target)?e.target:void 0,a=typeof e.selectorKind=="string"?e.selectorKind:typeof t?.selectorKind=="string"?t.selectorKind:void 0,r=typeof e.targetId=="string"?Be(e.targetId):typeof t?.targetId=="string"?Be(t.targetId):typeof e.targetJobId=="string"?Be(e.targetJobId):void 0,i=Mt(r);if(!i||a&&a!==i.selectorKind)return;const n=Array.isArray(e.relatedJobIds)?e.relatedJobIds:Array.isArray(t?.relatedJobIds)?t.relatedJobIds:void 0,o=Ln([...n??[],e.jobId,t?.jobId,e.targetJobId,t?.targetJobId]).filter(s=>s!==i.targetId&&s!==i.jobId);return{...i,...typeof(e.jobId??t?.jobId)=="string"?{jobId:Be(e.jobId??t?.jobId)??i.jobId}:{},...typeof(e.goalId??t?.goalId)=="string"?{goalId:Be(e.goalId??t?.goalId)??i.goalId}:{},...typeof(e.loopId??t?.loopId)=="string"?{loopId:Be(e.loopId??t?.loopId)??i.loopId}:{},...o.length>0?{relatedJobIds:o}:{}}}function zr(e){const t=e.trim().split(/\s+/).filter(Boolean),a=t[0]?.replace(/^\*/,"").toLowerCase(),r=t[1]?.replace(/^--/,"").toLowerCase();return(a==="jobs"||a==="job"||a==="continuity-jobs"||a==="61")&&r==="watch"}const Ie=Object.freeze({ACTIVE:"command-level-watch-active",INACTIVE:"command-level-watch-inactive",DUPLICATE:"command-level-watch-duplicate",AMBIGUOUS:"command-level-watch-ambiguous",QUOTED:"command-level-watch-quoted",MALFORMED:"command-level-watch-malformed",NON_FINAL:"command-level-watch-non-final",UNRESOLVED:"command-level-watch-unresolved",UNSUPPORTED:"command-level-watch-unsupported",TARGET_INVALID:"command-level-watch-target-invalid"}),Ro=new Set(["create","start","resume"]),bo=new Set(["create","resume","run-once"]);function jn(e,t,a,r,i){return{schemaVersion:1,contractVersion:"continuity-v1",...a?{command:a}:{},...r?{operation:r}:{},active:e,...i?{watchToken:i}:{},reasonCodes:Ae(t),serverHeldStream:!1,allJobsPolling:!1,targetResolution:e?"required-after-dispatch":"inactive",publicSafe:!0}}function _e(e,t=[],a,r){const i=t.length>0?t:[Ie.INACTIVE];return{args:e,watch:!1,reasonCodes:i,metadata:jn(!1,i,a,r),publicSafe:!0}}function To(e){const t=e.trim().split(/\s+/).filter(Boolean),a=t.slice(2).filter(n=>n==="--watch").length;if(a===0)return _e(e,[],"jobs","watch");if(a!==1)return _e(e,[Ie.AMBIGUOUS],"jobs","watch");const r=t.filter((n,o)=>o<2||n!=="--watch").join(" ");return zr(r)?r.trim().split(/\s+/).filter(Boolean).slice(2).length!==1?_e(e,[Ie.AMBIGUOUS],"jobs","watch"):Yr(r)?{args:r,watch:!0,reasonCodes:[Ie.ACTIVE],metadata:jn(!0,[Ie.ACTIVE],"jobs","watch"),publicSafe:!0}:_e(e,[Ie.TARGET_INVALID],"jobs","watch"):_e(e,[Ie.UNSUPPORTED],"jobs","watch")}function xo(e){const t=[];let a=!1,r=0;for(;r<e.length;){for(;r<e.length&&/\s/.test(e[r]);)r+=1;if(r>=e.length)break;const i=r;let n="",o=!1,s=null;for(;r<e.length;){const u=e[r];if(s){if(u===s){o=!0,s=null,r+=1;continue}if(u==="\\"&&r+1<e.length){n+=e[r+1],r+=2;continue}n+=u,r+=1;continue}if(/\s/.test(u))break;if(u==='"'||u==="'"){o=!0,s=u,r+=1;continue}n+=u,r+=1}s&&(a=!0),t.push({value:n,start:i,end:r,quoted:o})}return{tokens:t,malformed:a}}function ko(e){if(!e||e.quoted)return;const t=e.value.replace(/^\*/,"").toLowerCase();return t==="goal"||t==="loop"?t:void 0}function Po(e,t){if(!e||e==="jobs"||!t||t.quoted)return;const a=t.value.toLowerCase();return(e==="goal"?Ro:bo).has(a)?a:void 0}function Oo(e){return!e.quoted&&e.value!=="--watch"&&e.value.toLowerCase().startsWith("--watch")}function No(e){const{tokens:t,malformed:a}=xo(e),r=ko(t[0]),i=Po(r,t[1]);if(a)return _e(e,[Ie.MALFORMED],r,i);const n=t.filter(l=>l.value==="--watch"&&!l.quoted),o=t.filter(l=>l.value==="--watch"&&l.quoted),s=t.filter(Oo);if(!(n.length>0||o.length>0||s.length>0))return _e(e,[],r,i);if(n.length>1)return _e(e,[Ie.DUPLICATE],r,i);if(n.length===1&&(o.length>0||s.length>0))return _e(e,[Ie.AMBIGUOUS],r,i);if(o.length>0)return _e(e,[Ie.QUOTED],r,i);if(s.length>0)return _e(e,[Ie.MALFORMED],r,i);const f=n[0];if(!f)return _e(e,[],r,i);if(t[t.length-1]!==f)return _e(e,[Ie.NON_FINAL],r,i);if(!r||!i)return _e(e,[Ie.UNRESOLVED],r,i);const S=`${e.slice(0,f.start)}${e.slice(f.end)}`.trim(),_={literal:"--watch",position:"final",start:f.start,end:f.end,quoted:!1,publicSafe:!0};return{args:S,watch:!0,reasonCodes:[Ie.ACTIVE],metadata:jn(!0,[Ie.ACTIVE],r,i,_),publicSafe:!0}}function Do(e){return zr(e)?To(e):No(e)}function Lo(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&Ci.has(t)):[]}function Rt(e){return{disabled:!0,reasonCodes:Ae(e.length>0?e:[we.MISSING])}}function Mn(e,t,a=[],r){const i=Mt(t);if(i)return{source:e,target:_o(i,a),targetJobId:i.targetId,...r?{initialCursor:r}:{},serverHeldStream:!1}}function jo(e){const t=new Map;for(const a of e){const r=`${a.target.selectorKind}:${a.target.targetId}`,i=t.get(r);if(!i){t.set(r,a);continue}const n=Ae([...i.target.relatedJobIds??[],...a.target.relatedJobIds??[]]);t.set(r,{...i,target:n.length>0?{...i.target,relatedJobIds:n}:i.target,initialCursor:i.initialCursor??a.initialCursor})}return Array.from(t.values())}function ct(e,t,a,r){return{source:e,hasEvidence:t,candidates:jo(a.filter(i=>!!i)),...r&&r.length>0?{disabledReasonCodes:Ae(r)}:{}}}function Mo(e,t){return e.target.selectorKind===t.target.selectorKind&&e.target.targetId===t.target.targetId}function Vt(e,t){const a=Ae(e.filter(r=>typeof r=="string").map(r=>Be(r)).filter(r=>!!r));if(t){const r=a.find(i=>Dn(i)===t);if(r)return r}return a[0]}function cn(e,t){return Ae(e.filter(a=>typeof a=="string").map(a=>Be(a)).filter(a=>!!a)).find(a=>Dn(a)===t)}function Vo(e){const t=h(e?.continuity)?e.continuity:void 0,a=h(t?.jobs)?t.jobs:void 0,r=h(a?.watcher)?a.watcher:void 0,i=Lo(r?.reasonCodes??a?.reasonCodes);if(!r)return ct("watcher-metadata",i.length>0,[],i);if(r.active===!1||i.length>0)return ct("watcher-metadata",!0,[],i.length>0?i:[we.MALFORMED]);if(r.serverHeldStream!==!1)return ct("watcher-metadata",!0,[],[we.SERVER_HELD_STREAM]);const n=Ao(r);if(!n)return ct("watcher-metadata",!0,[],[we.MISSING]);const o=typeof r.initialCursor=="string"?r.initialCursor:void 0;return ct("watcher-metadata",!0,[{source:"watcher-metadata",target:n,targetJobId:n.targetId,...o?{initialCursor:o}:{},serverHeldStream:!1}])}function Jr(e,t){const a=h(e.loopJobPlan)?e.loopJobPlan:void 0,r=h(a?.metadata)?a.metadata:void 0,i=h(e.metadata)?e.metadata:void 0,o=(t==="goal"?Vt([e.goalId,e.targetGoalId,e.campaignId,e.jobId,e.targetJobId,i?.goalId,i?.campaignId,i?.jobId],"goal"):Vt([e.loopId,e.targetLoopId,e.jobId,e.targetJobId,i?.loopId,i?.jobId,r?.loopId,r?.jobId],"loop"))??Vt([e.jobId,e.targetJobId,i?.jobId,r?.jobId]);return Mn("goal-loop-continuity-metadata",o,[e.jobId,e.targetJobId,i?.jobId,r?.jobId])}function Uo(e){const t=h(e?.continuity)?e.continuity:void 0,a=h(t?.goal)?t.goal:void 0,r=h(t?.loop)?t.loop:void 0,i=[a?Jr(a,"goal"):void 0,r?Jr(r,"loop"):void 0],n=!!(a||r);return ct("goal-loop-continuity-metadata",n,i,n&&i.every(o=>!o)?[we.MISSING]:void 0)}function $o(e){return Array.isArray(e)?e.filter(h):h(e)?Array.isArray(e.operationLogs)?e.operationLogs.filter(h):h(e.operationLog)?[e.operationLog]:Array.isArray(e.operations)?[e]:[]:[]}function Kr(e,t){const a=h(t.metadata)?t.metadata:void 0,r=cn([t.goalId,t.targetGoalId,t.campaignId,a?.goalId,a?.campaignId,t.jobId,a?.jobId],"goal"),i=cn([t.loopId,t.targetLoopId,a?.loopId,t.jobId,a?.jobId],"loop"),n=Vt([t.jobId,t.targetJobId,a?.jobId],"job"),o=r??i??n;if(!o)return;const s=e.get(o)??{targetId:o,relatedJobIds:[]};s.relatedJobIds.push(...Ln([n,t.jobId,t.targetJobId,a?.jobId])),e.set(o,s)}function Bo(e){const t=h(e.metadata)?e.metadata:void 0;return!!(cn([e.goalId,e.targetGoalId,e.campaignId,t?.goalId,t?.campaignId,e.jobId,t?.jobId],"goal")??cn([e.loopId,e.targetLoopId,t?.loopId,e.jobId,t?.jobId],"loop"))}function Ho(e){const t=h(e.metadata)?e.metadata:void 0;return!!Vt([e.goalId,e.targetGoalId,e.campaignId,e.loopId,e.targetLoopId,e.jobId,e.targetJobId,t?.goalId,t?.campaignId,t?.loopId,t?.jobId])}function Qr(e,t){const a=[];for(const o of["metadata","job","event","receipt","processingOutputSummary"]){const s=t[o];h(s)&&a.push(s)}const r=h(t.event)?t.event:void 0;h(r?.metadata)&&a.push(r.metadata),h(r?.processingOutputSummary)&&a.push(r.processingOutputSummary);const i=h(t.receipt)?t.receipt:void 0;h(i?.metadata)&&a.push(i.metadata);const n=a.some(Ho);for(const o of a)Kr(e,o);(!n||Bo(t))&&Kr(e,t)}function Wo(e){const t=$o(e?.continuityStateUpdate),a=new Map;for(const i of t){Qr(a,i);const n=Array.isArray(i.operations)?i.operations.filter(h):[];for(const o of n)Qr(a,o)}const r=Array.from(a.values()).map(i=>Mn("continuity-state-update-operation-log",i.targetId,i.relatedJobIds));return ct("continuity-state-update-operation-log",t.length>0,r,t.length>0&&r.every(i=>!i)?[we.MISSING]:void 0)}function Go(e){const t=Fr(e);return ct("explicit-args",t.length>0,t.map(a=>Mn("explicit-args",a)))}function qo(e,t){const a=[Vo(e),Uo(e),Wo(e),Go(t)];for(let r=0;r<a.length;r+=1){const i=a[r];if(!i.hasEvidence)continue;if(i.disabledReasonCodes&&i.disabledReasonCodes.length>0)return Rt(i.disabledReasonCodes);if(i.candidates.length!==1)return Rt([i.candidates.length>1?we.AMBIGUOUS:we.MISSING]);const n=i.candidates[0];for(const o of a.slice(r+1)){if(!o.hasEvidence)continue;if(o.disabledReasonCodes&&o.disabledReasonCodes.length>0)return Rt(o.disabledReasonCodes);if(o.candidates.length>1)return Rt([we.AMBIGUOUS]);const s=o.candidates[0];if(s&&!Mo(n,s))return Rt([we.CONFLICT])}return{target:n.target,targetJobId:n.targetJobId,...n.initialCursor?{initialCursor:n.initialCursor}:{},source:n.source,serverHeldStream:!1}}return Rt([we.MISSING])}async function Xr(e,t,a,r={}){const n=await jt(e,"/api/v1/invoke",t,a,t.privateExecution?{...r,maxAttempts:1,allowReplayRetry:!1}:r);if(n.networkFailure||!n.response)return{ok:!1,status:0,error:"Network error after bounded retries"};const{response:o,text:s,parsed:u}=n;try{if(!o.ok)return t.privateExecution?{ok:!1,status:o.status,error:"private-execution-invoke-unavailable"}:{ok:!1,status:o.status,error:Object.keys(u).length>0?`${u.error_code??"ERROR"}: ${u.message??s}`:`HTTP ${o.status}: ${s}`,errorBody:Object.keys(u).length>0?u:void 0};const f=u,S=o.headers.get("X-Client-Version-Warning");return S&&!jr&&(jr=!0,process.stderr.write(`
|
|
22
|
+
`)}function jn(e){return vi.has(e.status)}function Eo(e,t,a){if(t){const i=e.find(n=>n.jobId===t);return!!(i&&jn(i))}return a<=0?!1:e.filter(i=>!jn(i)).length===0}function So(e,t,a,r){return a<r?!1:t?!e.some(i=>i.jobId===t&&!jn(i)):e.length===0}function Io(e,t){return t?.aborted?Promise.resolve():new Promise(a=>{const r=setTimeout(i,e);function i(){clearTimeout(r),t?.removeEventListener("abort",i),a()}t?.addEventListener("abort",i,{once:!0})})}function vo(e){return e.includes(Ce.MALFORMED)?"malformed":e.includes(Ce.AMBIGUOUS)?"ambiguous":e.includes("watch-target-multiple")?"multiple":e.includes("watch-evidence-unsafe")?"unsafe":e.includes(Ce.MISSING)||e.includes(fe.TARGET_UNRESOLVED)?"unresolved":"unavailable"}function zr(e,t){const a=t?Ht(t):void 0,r=_e([...e,fe.TARGET_UNRESOLVED,W.WATCH_TARGET_UNRESOLVED]),i=Ln(a,a?.targetId,vo(r),r),n=Je({generatedAt:new Date().toISOString()},[],!1,0,[W.WATCH_TARGET_UNRESOLVED]),o=qe(void 0,void 0,void 0,[],[W.WATCH_TARGET_UNRESOLVED],"unavailable");return Fe({watchStatus:"blocked",active:!1,targetEvidence:i,snapshotEvidence:n,cursorEvidence:o,stopReason:"target_unresolved",reasonCodes:r,generatedAt:n.generatedAt})}function Co(e,t,a,r,i=!1){const n=zr(e,Kr(t));return Ye(n,a,r,i),Ke("target-unresolved",0,0,n,i)}async function wo(e){if(e.signal?.aborted){const R=Ln(e.target??Ht(e.targetJobId),e.targetJobId,e.target??e.targetJobId?"resolved":"unresolved",[fe.CANCELLED]),v=Je(void 0,[],!1,0),D=qe(e.initialCursor,e.initialCursor,e.initialCursor,[],[fe.CANCELLED],"unavailable"),N=Fe({watchStatus:"stopped",active:!1,targetEvidence:R,snapshotEvidence:v,cursorEvidence:D,stopReason:"cancelled",reasonCodes:[fe.CANCELLED]});return Ke("cancelled",0,0,N,e.protectedOutput)}const t=e.target??Ht(e.targetJobId),a=e.targetJobId??t?.targetId,r=e.stdout??process.stdout;if(!t){const R=zr([Ce.MISSING,fe.TARGET_UNRESOLVED]);return Ye(R,e.format,r,e.protectedOutput),Ke("target-unresolved",0,0,R,e.protectedOutput)}const i=sn(e.limit??dn("NEOCORTEX_INVOKE_WATCH_LIMIT",nr),nr,50),n=Math.max(50,sn(e.pollIntervalMs??dn("NEOCORTEX_INVOKE_WATCH_POLL_INTERVAL_MS",ir),ir,6e4)),o=sn(e.maxIdlePolls??dn("NEOCORTEX_INVOKE_WATCH_MAX_IDLE_POLLS",rr),rr,120),s=sn(e.maxPolls??dn("NEOCORTEX_INVOKE_WATCH_MAX_POLLS",ar),ar,86400),u=e.sleep??Io;let f=e.initialCursor,S=0,_=0,l=0;const y=Ln(t,a,"resolved",[W.OK]),p={schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:"pending",renderedSummaryCount:0,reasonCodes:[W.WATCH_RENDER_PENDING],publicSafe:!0},I=qe(e.initialCursor,f,f,[],e.initialCursor?[W.WATCH_CURSOR_UNCHANGED]:[W.WATCH_NO_SUMMARIES_YET],e.initialCursor?"unchanged":"not_started");Ye(Fe({watchStatus:"active",active:!0,targetEvidence:y,snapshotEvidence:p,cursorEvidence:I,stopReason:"not_stopped",reasonCodes:[W.OK]}),e.format,r,e.protectedOutput);let C;try{C=await Oa({projectRoot:e.projectRoot,strictReadOnly:e.strictReadOnly})}catch{const R=Je(void 0,[],!1,S,[W.WATCH_SNAPSHOT_UNAVAILABLE]),v=qe(e.initialCursor,f,f,[],[W.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),D=Fe({watchStatus:"blocked",active:!1,targetEvidence:y,snapshotEvidence:R,cursorEvidence:v,stopReason:"unavailable_evidence",reasonCodes:[fe.STORE_UNAVAILABLE]});return Ye(D,e.format,r,e.protectedOutput),Ke("store-unavailable",S,l,D,e.protectedOutput)}try{for(;!e.signal?.aborted&&l<s;){l+=1;const R=f,v=C.collectProcessingOutputSummaryCursor({...f?{cursor:f}:{},...t?{target:t}:{},...a?{jobId:a}:{},limit:i}),D=C.collectSnapshot({jobLimit:50,processingSummaryLimit:1}),N=D.jobs;if(v.summaries.length>0){for(const $ of v.summaries)yo($,e.format,r,e.protectedOutput),S+=1;f=v.nextCursor??v.summaries[v.summaries.length-1]?.cursor??f,_=0}else f=v.nextCursor??f,_+=1;const U=Je(D,v.summaries,!0,v.summaries.length),F=qe(e.initialCursor,R,f,v.summaries,v.summaries.length>0?[W.WATCH_CURSOR_ADVANCED]:[W.WATCH_NO_SUMMARIES_YET]);if(Ye(Fe({watchStatus:v.summaries.length>0?"polling":"waiting",active:!0,targetEvidence:y,snapshotEvidence:U,cursorEvidence:F,stopReason:"not_stopped",reasonCodes:v.summaries.length>0?[W.WATCH_CURSOR_ADVANCED]:[W.WATCH_NO_SUMMARIES_YET],generatedAt:D.generatedAt}),e.format,r,e.protectedOutput),!v.hasMore&&Eo(N,a,S)){const $=Je(D,v.summaries,!1,S,[fe.COMPLETED]),j=qe(e.initialCursor,R,f,v.summaries,[fe.COMPLETED],"exhausted"),B=Fe({watchStatus:"stopped",active:!1,targetEvidence:y,snapshotEvidence:$,cursorEvidence:j,stopReason:"not_stopped",reasonCodes:[fe.COMPLETED],generatedAt:D.generatedAt});return Ye(B,e.format,r,e.protectedOutput),Ke("completed",S,l,B,e.protectedOutput)}if(!v.hasMore&&So(N,a,_,o)){const $=Je(D,v.summaries,!1,S,[W.WATCH_STOP_IDLE_LIMIT_REACHED]),j=qe(e.initialCursor,R,f,v.summaries,[W.WATCH_STOP_IDLE_LIMIT_REACHED],"exhausted"),B=Fe({watchStatus:"stopped",active:!1,targetEvidence:y,snapshotEvidence:$,cursorEvidence:j,stopReason:"idle_limit_reached",reasonCodes:[fe.IDLE_TIMEOUT,W.WATCH_STOP_IDLE_LIMIT_REACHED],generatedAt:D.generatedAt});return Ye(B,e.format,r,e.protectedOutput),Ke("idle-timeout",S,l,B,e.protectedOutput)}v.hasMore||await u(n,e.signal)}}catch{const R=Je(void 0,[],!1,S,[W.WATCH_SNAPSHOT_UNAVAILABLE]),v=qe(e.initialCursor,f,f,[],[W.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),D=Fe({watchStatus:"blocked",active:!1,targetEvidence:y,snapshotEvidence:R,cursorEvidence:v,stopReason:"unavailable_evidence",reasonCodes:[fe.STORE_UNAVAILABLE]});return Ye(D,e.format,r,e.protectedOutput),Ke("store-unavailable",S,l,D,e.protectedOutput)}finally{C.close()}if(e.signal?.aborted){const R=Je(void 0,[],!1,S,[fe.CANCELLED]),v=qe(e.initialCursor,f,f,[],[fe.CANCELLED],"unavailable"),D=Fe({watchStatus:"stopped",active:!1,targetEvidence:y,snapshotEvidence:R,cursorEvidence:v,stopReason:"cancelled",reasonCodes:[fe.CANCELLED]});return Ye(D,e.format,r,e.protectedOutput),Ke("cancelled",S,l,D,e.protectedOutput)}const V=Je(void 0,[],!1,S,[W.WATCH_STOP_MAX_POLLS_REACHED]),T=qe(e.initialCursor,f,f,[],[W.WATCH_STOP_MAX_POLLS_REACHED],"exhausted"),z=Fe({watchStatus:"stopped",active:!1,targetEvidence:y,snapshotEvidence:V,cursorEvidence:T,stopReason:"max_polls_reached",reasonCodes:[fe.MAX_POLLS,W.WATCH_STOP_MAX_POLLS_REACHED]});return Ye(z,e.format,r,e.protectedOutput),Ke("max-polls",S,l,z,e.protectedOutput)}function He(e){const t=e.trim().replace(/^@/,"").match(/^(job|goal|loop)-([JGL])(\d{3,})$/i);if(!t)return;const a=t[1].toLowerCase(),r=t[2].toUpperCase();if(!(a==="job"&&r!=="J"||a==="goal"&&r!=="G"||a==="loop"&&r!=="L"))return`${a}-${r}${t[3]}`}function Mn(e){if(e.startsWith("job-J"))return"job";if(e.startsWith("goal-G"))return"goal";if(e.startsWith("loop-L"))return"loop"}function Jr(e){const t=[],a=/(?:^|[\s"'([,{])@?(job-[Jj]\d{3,}|goal-[Gg]\d{3,}|loop-[Ll]\d{3,})(?=$|[\s"')\]},.;:!?])/g;let r;for(;(r=a.exec(e))!==null;){const i=He(r[1]);i&&t.push(i)}return _e(t)}function Kr(e){return Jr(e)[0]}function Ht(e){const t=e?He(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 Vn(e){return _e(e.filter(t=>typeof t=="string").map(t=>He(t)).filter(t=>!!t?.startsWith("job-J")))}function _o(e,t){const a=Vn(t).filter(r=>r!==e.targetId&&r!==e.jobId);return a.length>0?{...e,relatedJobIds:a}:e}function Ro(e){if(!e)return;const t=h(e.target)?e.target:void 0,a=typeof e.selectorKind=="string"?e.selectorKind:typeof t?.selectorKind=="string"?t.selectorKind:void 0,r=typeof e.targetId=="string"?He(e.targetId):typeof t?.targetId=="string"?He(t.targetId):typeof e.targetJobId=="string"?He(e.targetJobId):void 0,i=Ht(r);if(!i||a&&a!==i.selectorKind)return;const n=Array.isArray(e.relatedJobIds)?e.relatedJobIds:Array.isArray(t?.relatedJobIds)?t.relatedJobIds:void 0,o=Vn([...n??[],e.jobId,t?.jobId,e.targetJobId,t?.targetJobId]).filter(s=>s!==i.targetId&&s!==i.jobId);return{...i,...typeof(e.jobId??t?.jobId)=="string"?{jobId:He(e.jobId??t?.jobId)??i.jobId}:{},...typeof(e.goalId??t?.goalId)=="string"?{goalId:He(e.goalId??t?.goalId)??i.goalId}:{},...typeof(e.loopId??t?.loopId)=="string"?{loopId:He(e.loopId??t?.loopId)??i.loopId}:{},...o.length>0?{relatedJobIds:o}:{}}}function Qr(e){const t=e.trim().split(/\s+/).filter(Boolean),a=t[0]?.replace(/^\*/,"").toLowerCase(),r=t[1]?.replace(/^--/,"").toLowerCase();return(a==="jobs"||a==="job"||a==="continuity-jobs"||a==="61")&&r==="watch"}const Ie=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"}),Ao=new Set(["create","start","resume"]),bo=new Set(["create","resume","run-once"]);function Un(e,t,a,r,i){return{schemaVersion:1,contractVersion:"continuity-v1",...a?{command:a}:{},...r?{operation:r}:{},active:e,...i?{watchToken:i}:{},reasonCodes:_e(t),serverHeldStream:!1,allJobsPolling:!1,targetResolution:e?"required-after-dispatch":"inactive",publicSafe:!0}}function we(e,t=[],a,r){const i=t.length>0?t:[Ie.INACTIVE];return{args:e,watch:!1,reasonCodes:i,metadata:Un(!1,i,a,r),publicSafe:!0}}function To(e){const t=e.trim().split(/\s+/).filter(Boolean),a=t.slice(2).filter(n=>n==="--watch").length;if(a===0)return we(e,[],"jobs","watch");if(a!==1)return we(e,[Ie.AMBIGUOUS],"jobs","watch");const r=t.filter((n,o)=>o<2||n!=="--watch").join(" ");return Qr(r)?r.trim().split(/\s+/).filter(Boolean).slice(2).length!==1?we(e,[Ie.AMBIGUOUS],"jobs","watch"):Kr(r)?{args:r,watch:!0,reasonCodes:[Ie.ACTIVE],metadata:Un(!0,[Ie.ACTIVE],"jobs","watch"),publicSafe:!0}:we(e,[Ie.TARGET_INVALID],"jobs","watch"):we(e,[Ie.UNSUPPORTED],"jobs","watch")}function xo(e){const t=[];let a=!1,r=0;for(;r<e.length;){for(;r<e.length&&/\s/.test(e[r]);)r+=1;if(r>=e.length)break;const i=r;let n="",o=!1,s=null;for(;r<e.length;){const u=e[r];if(s){if(u===s){o=!0,s=null,r+=1;continue}if(u==="\\"&&r+1<e.length){n+=e[r+1],r+=2;continue}n+=u,r+=1;continue}if(/\s/.test(u))break;if(u==='"'||u==="'"){o=!0,s=u,r+=1;continue}n+=u,r+=1}s&&(a=!0),t.push({value:n,start:i,end:r,quoted:o})}return{tokens:t,malformed:a}}function ko(e){if(!e||e.quoted)return;const t=e.value.replace(/^\*/,"").toLowerCase();return t==="goal"||t==="loop"?t:void 0}function Po(e,t){if(!e||e==="jobs"||!t||t.quoted)return;const a=t.value.toLowerCase();return(e==="goal"?Ao:bo).has(a)?a:void 0}function Oo(e){return!e.quoted&&e.value!=="--watch"&&e.value.toLowerCase().startsWith("--watch")}function No(e){const{tokens:t,malformed:a}=xo(e),r=ko(t[0]),i=Po(r,t[1]);if(a)return we(e,[Ie.MALFORMED],r,i);const n=t.filter(l=>l.value==="--watch"&&!l.quoted),o=t.filter(l=>l.value==="--watch"&&l.quoted),s=t.filter(Oo);if(!(n.length>0||o.length>0||s.length>0))return we(e,[],r,i);if(n.length>1)return we(e,[Ie.DUPLICATE],r,i);if(n.length===1&&(o.length>0||s.length>0))return we(e,[Ie.AMBIGUOUS],r,i);if(o.length>0)return we(e,[Ie.QUOTED],r,i);if(s.length>0)return we(e,[Ie.MALFORMED],r,i);const f=n[0];if(!f)return we(e,[],r,i);if(t[t.length-1]!==f)return we(e,[Ie.NON_FINAL],r,i);if(!r||!i)return we(e,[Ie.UNRESOLVED],r,i);const S=`${e.slice(0,f.start)}${e.slice(f.end)}`.trim(),_={literal:"--watch",position:"final",start:f.start,end:f.end,quoted:!1,publicSafe:!0};return{args:S,watch:!0,reasonCodes:[Ie.ACTIVE],metadata:Un(!0,[Ie.ACTIVE],r,i,_),publicSafe:!0}}function Do(e){return Qr(e)?To(e):No(e)}function Lo(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&Ci.has(t)):[]}function xt(e){return{disabled:!0,reasonCodes:_e(e.length>0?e:[Ce.MISSING])}}function $n(e,t,a=[],r){const i=Ht(t);if(i)return{source:e,target:_o(i,a),targetJobId:i.targetId,...r?{initialCursor:r}:{},serverHeldStream:!1}}function jo(e){const t=new Map;for(const a of e){const r=`${a.target.selectorKind}:${a.target.targetId}`,i=t.get(r);if(!i){t.set(r,a);continue}const n=_e([...i.target.relatedJobIds??[],...a.target.relatedJobIds??[]]);t.set(r,{...i,target:n.length>0?{...i.target,relatedJobIds:n}:i.target,initialCursor:i.initialCursor??a.initialCursor})}return Array.from(t.values())}function st(e,t,a,r){return{source:e,hasEvidence:t,candidates:jo(a.filter(i=>!!i)),...r&&r.length>0?{disabledReasonCodes:_e(r)}:{}}}function Mo(e,t){return e.target.selectorKind===t.target.selectorKind&&e.target.targetId===t.target.targetId}function Wt(e,t){const a=_e(e.filter(r=>typeof r=="string").map(r=>He(r)).filter(r=>!!r));if(t){const r=a.find(i=>Mn(i)===t);if(r)return r}return a[0]}function pn(e,t){return _e(e.filter(a=>typeof a=="string").map(a=>He(a)).filter(a=>!!a)).find(a=>Mn(a)===t)}function Vo(e){const t=h(e?.continuity)?e.continuity:void 0,a=h(t?.jobs)?t.jobs:void 0,r=h(a?.watcher)?a.watcher:void 0,i=Lo(r?.reasonCodes??a?.reasonCodes);if(!r)return st("watcher-metadata",i.length>0,[],i);if(r.active===!1||i.length>0)return st("watcher-metadata",!0,[],i.length>0?i:[Ce.MALFORMED]);if(r.serverHeldStream!==!1)return st("watcher-metadata",!0,[],[Ce.SERVER_HELD_STREAM]);const n=Ro(r);if(!n)return st("watcher-metadata",!0,[],[Ce.MISSING]);const o=typeof r.initialCursor=="string"?r.initialCursor:void 0;return st("watcher-metadata",!0,[{source:"watcher-metadata",target:n,targetJobId:n.targetId,...o?{initialCursor:o}:{},serverHeldStream:!1}])}function Xr(e,t){const a=h(e.loopJobPlan)?e.loopJobPlan:void 0,r=h(a?.metadata)?a.metadata:void 0,i=h(e.metadata)?e.metadata:void 0,o=(t==="goal"?Wt([e.goalId,e.targetGoalId,e.campaignId,e.jobId,e.targetJobId,i?.goalId,i?.campaignId,i?.jobId],"goal"):Wt([e.loopId,e.targetLoopId,e.jobId,e.targetJobId,i?.loopId,i?.jobId,r?.loopId,r?.jobId],"loop"))??Wt([e.jobId,e.targetJobId,i?.jobId,r?.jobId]);return $n("goal-loop-continuity-metadata",o,[e.jobId,e.targetJobId,i?.jobId,r?.jobId])}function Uo(e){const t=h(e?.continuity)?e.continuity:void 0,a=h(t?.goal)?t.goal:void 0,r=h(t?.loop)?t.loop:void 0,i=[a?Xr(a,"goal"):void 0,r?Xr(r,"loop"):void 0],n=!!(a||r);return st("goal-loop-continuity-metadata",n,i,n&&i.every(o=>!o)?[Ce.MISSING]:void 0)}function $o(e){return Array.isArray(e)?e.filter(h):h(e)?Array.isArray(e.operationLogs)?e.operationLogs.filter(h):h(e.operationLog)?[e.operationLog]:Array.isArray(e.operations)?[e]:[]:[]}function Zr(e,t){const a=h(t.metadata)?t.metadata:void 0,r=pn([t.goalId,t.targetGoalId,t.campaignId,a?.goalId,a?.campaignId,t.jobId,a?.jobId],"goal"),i=pn([t.loopId,t.targetLoopId,a?.loopId,t.jobId,a?.jobId],"loop"),n=Wt([t.jobId,t.targetJobId,a?.jobId],"job"),o=r??i??n;if(!o)return;const s=e.get(o)??{targetId:o,relatedJobIds:[]};s.relatedJobIds.push(...Vn([n,t.jobId,t.targetJobId,a?.jobId])),e.set(o,s)}function Bo(e){const t=h(e.metadata)?e.metadata:void 0;return!!(pn([e.goalId,e.targetGoalId,e.campaignId,t?.goalId,t?.campaignId,e.jobId,t?.jobId],"goal")??pn([e.loopId,e.targetLoopId,t?.loopId,e.jobId,t?.jobId],"loop"))}function Ho(e){const t=h(e.metadata)?e.metadata:void 0;return!!Wt([e.goalId,e.targetGoalId,e.campaignId,e.loopId,e.targetLoopId,e.jobId,e.targetJobId,t?.goalId,t?.campaignId,t?.loopId,t?.jobId])}function ea(e,t){const a=[];for(const o of["metadata","job","event","receipt","processingOutputSummary"]){const s=t[o];h(s)&&a.push(s)}const r=h(t.event)?t.event:void 0;h(r?.metadata)&&a.push(r.metadata),h(r?.processingOutputSummary)&&a.push(r.processingOutputSummary);const i=h(t.receipt)?t.receipt:void 0;h(i?.metadata)&&a.push(i.metadata);const n=a.some(Ho);for(const o of a)Zr(e,o);(!n||Bo(t))&&Zr(e,t)}function Wo(e){const t=$o(e?.continuityStateUpdate),a=new Map;for(const i of t){ea(a,i);const n=Array.isArray(i.operations)?i.operations.filter(h):[];for(const o of n)ea(a,o)}const r=Array.from(a.values()).map(i=>$n("continuity-state-update-operation-log",i.targetId,i.relatedJobIds));return st("continuity-state-update-operation-log",t.length>0,r,t.length>0&&r.every(i=>!i)?[Ce.MISSING]:void 0)}function Go(e){const t=Jr(e);return st("explicit-args",t.length>0,t.map(a=>$n("explicit-args",a)))}function qo(e,t){const a=[Vo(e),Uo(e),Wo(e),Go(t)];for(let r=0;r<a.length;r+=1){const i=a[r];if(!i.hasEvidence)continue;if(i.disabledReasonCodes&&i.disabledReasonCodes.length>0)return xt(i.disabledReasonCodes);if(i.candidates.length!==1)return xt([i.candidates.length>1?Ce.AMBIGUOUS:Ce.MISSING]);const n=i.candidates[0];for(const o of a.slice(r+1)){if(!o.hasEvidence)continue;if(o.disabledReasonCodes&&o.disabledReasonCodes.length>0)return xt(o.disabledReasonCodes);if(o.candidates.length>1)return xt([Ce.AMBIGUOUS]);const s=o.candidates[0];if(s&&!Mo(n,s))return xt([Ce.CONFLICT])}return{target:n.target,targetJobId:n.targetJobId,...n.initialCursor?{initialCursor:n.initialCursor}:{},source:n.source,serverHeldStream:!1}}return xt([Ce.MISSING])}async function ta(e,t,a,r={}){const n=await Bt(e,"/api/v1/invoke",t,a,t.privateExecution?{...r,maxAttempts:1,allowReplayRetry:!1}:r);if(n.networkFailure||!n.response)return{ok:!1,status:0,error:"Network error after bounded retries"};const{response:o,text:s,parsed:u}=n;try{if(!o.ok)return t.privateExecution?{ok:!1,status:o.status,error:"private-execution-invoke-unavailable"}:{ok:!1,status:o.status,error:Object.keys(u).length>0?`${u.error_code??"ERROR"}: ${u.message??s}`:`HTTP ${o.status}: ${s}`,errorBody:Object.keys(u).length>0?u:void 0};const f=u,S=o.headers.get("X-Client-Version-Warning");return S&&!Ur&&(Ur=!0,process.stderr.write(`
|
|
23
23
|
[Neocortex] ${S}
|
|
24
24
|
|
|
25
|
-
`)),{ok:!0,status:o.status,data:f}}catch(f){return{ok:!1,status:0,error:(f instanceof Error?f.message:String(f)).includes("abort")?`Request timeout after ${ur/1e3}s`:"Network error: invalid response"}}}async function Fo(e,t,a){const r=await jt(e,"/api/v1/invoke/private-execution/consume",t,a,{maxAttempts:1,allowReplayRetry:!1});if(r.networkFailure||!r.response||!r.response.ok)throw new Error("private-execution-delivery-unavailable");return r.parsed}async function Qc(e,t,a){const r=await jt(e,"/api/v1/invoke/private-execution/cancel",t,a,{maxAttempts:1,allowReplayRetry:!1});return!!r.response?.ok&&r.parsed.status==="cancelled"}async function Yo(e,t,a,r={}){const i=await jt(e,"/api/v1/invoke/epic-claims/acknowledge",{...a,registryVersion:lt,registryChecksum:ut},t,r);return!!i.response?.ok&&i.parsed.status==="ok"&&i.parsed.claimOutcome===a.status}async function zo(e,t,a,r,i,n={}){if(!i)return 0;const o=Xt(e);let s=0;for(const[u,f]of Object.entries(o.operations))!f.claimId||!f.epicId||!t.epics?.[f.epicId]||!await Yo(a,r,{claimId:f.claimId,projectId:i,epicId:f.epicId,status:"materialized"},n)||(Ei(e,u),s+=1);return s}function Jo(e,t){const a=t.state.pendingContinuationAuthorities,r=t.state.continuationSession;if(t.state.continuationPolicy!=="p205-finite-resume-v2"||a?.length!==1||!r)return;const i=a[0],n=i.certificate,o=n?.expectedTransition;if(i.storyIds!=="[CIRCULAR]"||n?.rank!=="[CIRCULAR]"||o?.selectedStoryIds!=="[CIRCULAR]")return;const s=typeof r.epicId=="string"?r.epicId:"",u=e.epics[s],f=Array.isArray(o.storyLifecycle)?o.storyLifecycle:[],S=f.length===1&&typeof f[0]?.storyId=="string"?f[0].storyId:"",l=e.stories[S]?.checkpoint;if(!u||u.branch_mode!=="epic"||typeof u.execution_branch!="string"||typeof u.origin_branch!="string"||u.branch_lease!==void 0&&u.branch_lease!==null||!l||l.qaVerdict!=="passed"||l.reviewVerdict!=="approved"||!Array.isArray(l.receiptRefs))return;const p=(Array.isArray(u.stories)?u.stories.filter(I=>typeof I=="string"):[]).find(I=>{const C=e.stories[I];return!C||["done","completed","merged"].includes(String(C.status))?!1:(Array.isArray(C.depends_on)?C.depends_on.filter(T=>typeof T=="string"):[]).every(T=>["done","completed","merged"].includes(String(e.stories[T]?.status)))});if(p)return{epicId:s,expectedNextStoryId:p,branchMode:"epic",executionBranch:u.execution_branch,originBranch:u.origin_branch,branchLeaseReleased:!0,checkpoint:{schemaVersion:1,storyId:l.storyId,epicId:l.epicId,branch:l.branch,baseSha:l.baseSha,headSha:l.headSha,receiptRefs:[...l.receiptRefs],qaVerdict:"passed",reviewVerdict:"approved"}}}async function Ko(e){let t;try{if(t=e.inputEnvelope??zt(e.inputSource??"args",e.args),qa(t),t.rawArgs!==e.args)throw new Error("INVOKE_INPUT_ENVELOPE_ARGUMENT_CONFLICT")}catch{return{success:!1,error:"INVOCATION_MALFORMED_INPUT: explicit input integrity could not be verified.",errorCode:"INVOCATION_MALFORMED_INPUT",metadata:{invocationInput:{reason:"input-integrity-conflict",remediation:"Retry with exactly one of --args, --stdin or --args-file.",publicSafe:!0}},exitCode:1}}const a=t.rawArgs,r=or(t);let i=a,n=r;const o=Ii(a);if(o.outcome!=="resolved"){const c=Ya(o,"client"),d=o.outcome==="malformed_input"?o.reason==="input_limit"||o.reason==="token_limit"||o.reason==="token_size_limit"?"input-limit-exceeded":o.reason==="invalid_control"||o.reason==="invalid_surrogate"?"invalid-control-character":o.reason==="unterminated_quote"||o.reason==="trailing_escape"||o.reason==="unsupported_escape"?"unterminated-quote":void 0:void 0,m=d?{code:"INVOCATION_MALFORMED_INPUT",reason:d,source:t.source,byteLength:t.byteLength,remediation:d==="input-limit-exceeded"?"Reduce the explicit command input or split the requested work into bounded invocations.":d==="invalid-control-character"?"Remove invalid control characters and retry with valid UTF-8 text.":"Close quotes and escapes, or use --stdin/--args-file for multiline content."}:void 0;return{success:!1,error:`INVOCATION_${o.outcome.toUpperCase()}`,errorCode:`INVOCATION_${o.outcome.toUpperCase()}`,metadata:{invocationAdmission:c,...m?{invocationInput:m}:{}},exitCode:1}}const s=In(e.projectRoot),u=o.selection.commandId,f=u==="tech-debt"&&o.selection.positionals.length===0&&(o.selection.operationId==="scan"&&Object.keys(o.selection.options).length===0||o.selection.operationId===void 0&&o.selection.options.scan===!0&&Object.keys(o.selection.options).length===1),S=fa.find(c=>c.id===u),_=S?.subcommands.find(c=>c.id===o.selection.operationId),l=_?_.policy.strictReadOnly==="allow":S?.policy.strictReadOnly==="allow",y=u==="diagnose";let p;try{p=Ha({invocationId:Gt(),intent:e.strictReadOnly||y?{schemaVersion:1,policy:Ua,registryVersion:lt,registryChecksum:ut}:void 0,registryVersion:lt,registryChecksum:ut,registryAllowsStrict:l,requestCanonicalBytes:JSON.stringify({command:u})})}catch(c){if(c instanceof wt)return{success:!1,error:c.code,errorCode:c.code,exitCode:1};throw c}{p.beginProjection();for(const c of ir)p.project(c);for(const c of $a)p.project(c);p.seal()}const I=p.mode==="strict";if(u==="create-epic"||u==="idea-diagnose")try{const c=Za(s);if(c&&c!=="finalized")return{success:!1,error:'PROJECT_IDENTITY_MIGRATION_INCOMPLETE: retry `neocortex-client invoke --args "*migrate-project-id"` before create-epic.',errorCode:"PROJECT_IDENTITY_MIGRATION_INCOMPLETE",metadata:{projectIdentityMigration:{phase:c,publicSafe:!0}},exitCode:1}}catch(c){const d=c instanceof mn?c.code:"PROJECT_IDENTITY_MIGRATION_STATE_CORRUPT";return{success:!1,error:d,errorCode:d,exitCode:1}}const C=e.environment??process.env;if(e.privateExecutionBeta&&(u!=="yolo"&&u!=="research"&&u!=="write-spec"&&u!=="create-tasks"&&u!=="implement"&&u!=="exec"&&u!=="create-epic"&&u!=="idea-diagnose"&&u!=="idea-research"&&u!=="generate-epic"&&u!=="sync-openapi"&&u!=="chaos-plan"&&u!=="ui-ux-review"&&u!=="arch-prd"&&u!=="arch-architecture"&&u!=="arch-fitness-functions"&&u!=="arch-api-contracts"&&u!=="arch-api-integrations"&&u!=="arch-database"&&u!=="arch-security"&&u!=="arch-design-system"&&u!=="arch-performance"&&u!=="arch-testing"&&u!=="arch-infrastructure"&&u!=="arch-review"&&u!=="update-memory"&&u!=="arch-ux-design"&&u!=="generate-pacts"&&u!=="property-test"&&!f||I||e.platformTarget!==void 0&&e.platformTarget!=="codex"))return{success:!1,error:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",errorCode:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",exitCode:1};const M=ja({cwd:s,env:C,targetFlag:e.privateExecutionBeta?"codex":e.platformTarget}),T=M.targetId,z=e.privateExecutionBeta?void 0:La({cwd:s,env:C,targetFlag:e.platformTarget,nativeHostVersion:Ti(M,C)},M);u!=="migrate-project-id"&&p.execute({phase:"client-preflight",domain:"client-persistence",category:"first-run-marker",operation:"create"},()=>Si(),()=>{});const A=Ki(p),v=(e.serverUrl??A?.serverUrl??ya).replace(/\/+$/,"");if(u==="migrate-project-id"){const c=await ei(v);if(!c.supported)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_CAPABILITY_UNAVAILABLE: the server did not advertise the versioned migration capability; no local state was changed.",errorCode:"PROJECT_IDENTITY_MIGRATION_CAPABILITY_UNAVAILABLE",metadata:{projectIdentityMigrationCapability:c},exitCode:1};const d=[];let m;try{m=Xa(s)}catch(j){const ue=j instanceof mn?j.code:"PROJECT_IDENTITY_MIGRATION_PREPARE_FAILED";return{success:!1,error:ue,errorCode:ue,exitCode:1}}d.push(_t({phase:"prepare",outcome:m.changed&&m.document.phase==="prepared"?"prepared":"retry",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId}));const x=Or(s);if(x.config.project_id!==m.document.projectId)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",errorCode:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",metadata:{invocationDiagnostics:d},exitCode:1};const Y=await Lr(v,A?.licenseKey,p);if(Y.status!=="authenticated"){const j=Y.status==="refresh-required";return{success:!1,error:j?"Authentication refresh required. Run: neocortex activate YOUR-LICENSE-KEY":"Not authenticated. Visit https://neocortex.sh/portal/login to get your license key, then run: neocortex activate YOUR-LICENSE-KEY",errorCode:j?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",metadata:{invocationDiagnostics:d},exitCode:j?1:2}}let ye;try{ye=Qn(e.args.trim(),x)}catch(j){const ue=j instanceof Xn?j.code:"PROJECT_IDENTITY_MIGRATION_PROJECTION_FAILED";return{success:!1,error:ue,errorCode:ue,metadata:{invocationDiagnostics:d},exitCode:1}}let oe={args:a,projectRoot:s.replace(Lt(),"~"),stateSnapshot:ye,platformTarget:T,...z?{nativeHostAttestation:z}:{},projectId:m.document.projectId,projectIdentityMigration:m.request,inputEvidence:r,idempotencyKey:m.document.operationId,registryVersion:lt,registryChecksum:ut};try{oe=Br(oe).body}catch(j){if(j instanceof wn||j instanceof _n)return{success:!1,error:j.message,errorCode:j.code,metadata:{invokePayload:j.telemetry,invocationDiagnostics:d},exitCode:1};throw j}const te=await ar("invoke-query",()=>Xr(v,oe,Y.token,{refreshToken:()=>Y.client.forceRefresh()}));if(!te.ok||!te.data)return d.push(_t({phase:"seed",outcome:"rejected",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId})),{success:!1,error:$e(te.error??"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",ht),errorCode:typeof te.errorBody?.error_code=="string"?te.errorBody.error_code:"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",metadata:{invocationDiagnostics:d},exitCode:te.status===401?2:1};const ee=te.data.metadata?.projectIdentityMigration;try{Fa(ee),d.push(_t({phase:"seed",outcome:ee.status,floor:ee.acceptedLegacyFloor,licenseId:"local-client",projectId:ee.projectId})),Ka(s,ee),d.push(_t({phase:"remote-acknowledged",outcome:ee.status,floor:ee.acceptedLegacyFloor,licenseId:"local-client",projectId:ee.projectId})),Qa(s,ee),d.push(_t({phase:"finalize",outcome:"finalized",floor:ee.acceptedLegacyFloor,licenseId:"local-client",projectId:ee.projectId}))}catch(j){d.push(_t({phase:"reconcile",outcome:"rejected",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId}));const ue=j instanceof mn?j.code:j instanceof Error?j.message:"PROJECT_IDENTITY_MIGRATION_RECEIPT_INVALID";return{success:!1,error:ue,errorCode:ue,metadata:{invocationDiagnostics:d},exitCode:1}}return p.complete(),{success:!0,instructions:te.data.instructions,metadata:{...te.data.metadata,invocationDiagnostics:d},exitCode:0}}try{const{normalizeYoloopTargetArgs:c}=await import("../yoloop/target-normalization.js"),d=c(e.args,{projectRoot:s});if(!d.ok)return process.stderr.write(`${d.message} reason=${d.reasonCode}
|
|
25
|
+
`)),{ok:!0,status:o.status,data:f}}catch(f){return{ok:!1,status:0,error:(f instanceof Error?f.message:String(f)).includes("abort")?`Request timeout after ${gr/1e3}s`:"Network error: invalid response"}}}async function Fo(e,t,a){const r=await Bt(e,"/api/v1/invoke/private-execution/consume",t,a,{maxAttempts:1,allowReplayRetry:!1});if(r.networkFailure||!r.response||!r.response.ok)throw new Error("private-execution-delivery-unavailable");return r.parsed}async function Yo(e,t,a){const r=await Bt(e,"/api/v1/invoke/private-execution/cancel",t,a,{maxAttempts:1,allowReplayRetry:!1});return!!r.response?.ok&&r.parsed.status==="cancelled"}async function zo(e,t,a,r={}){const i=await Bt(e,"/api/v1/invoke/epic-claims/acknowledge",{...a,registryVersion:gt,registryChecksum:ht},t,r);return!!i.response?.ok&&i.parsed.status==="ok"&&i.parsed.claimOutcome===a.status}async function Jo(e,t,a,r,i,n={}){if(!i)return 0;const o=en(e);let s=0;for(const[u,f]of Object.entries(o.operations))!f.claimId||!f.epicId||!t.epics?.[f.epicId]||!await zo(a,r,{claimId:f.claimId,projectId:i,epicId:f.epicId,status:"materialized"},n)||(Ei(e,u),s+=1);return s}function Ko(e,t){const a=t.state.pendingContinuationAuthorities,r=t.state.continuationSession;if(t.state.continuationPolicy!=="p205-finite-resume-v2"||a?.length!==1||!r)return;const i=a[0],n=i.certificate,o=n?.expectedTransition;if(i.storyIds!=="[CIRCULAR]"||n?.rank!=="[CIRCULAR]"||o?.selectedStoryIds!=="[CIRCULAR]")return;const s=typeof r.epicId=="string"?r.epicId:"",u=e.epics[s],f=Array.isArray(o.storyLifecycle)?o.storyLifecycle:[],S=f.length===1&&typeof f[0]?.storyId=="string"?f[0].storyId:"",l=e.stories[S]?.checkpoint;if(!u||u.branch_mode!=="epic"||typeof u.execution_branch!="string"||typeof u.origin_branch!="string"||u.branch_lease!==void 0&&u.branch_lease!==null||!l||l.qaVerdict!=="passed"||l.reviewVerdict!=="approved"||!Array.isArray(l.receiptRefs))return;const p=(Array.isArray(u.stories)?u.stories.filter(I=>typeof I=="string"):[]).find(I=>{const C=e.stories[I];return!C||["done","completed","merged"].includes(String(C.status))?!1:(Array.isArray(C.depends_on)?C.depends_on.filter(T=>typeof T=="string"):[]).every(T=>["done","completed","merged"].includes(String(e.stories[T]?.status)))});if(p)return{epicId:s,expectedNextStoryId:p,branchMode:"epic",executionBranch:u.execution_branch,originBranch:u.origin_branch,branchLeaseReleased:!0,checkpoint:{schemaVersion:1,storyId:l.storyId,epicId:l.epicId,branch:l.branch,baseSha:l.baseSha,headSha:l.headSha,receiptRefs:[...l.receiptRefs],qaVerdict:"passed",reviewVerdict:"approved"}}}async function Qo(e){let t;try{if(t=e.inputEnvelope??Kt(e.inputSource??"args",e.args),qa(t),t.rawArgs!==e.args)throw new Error("INVOKE_INPUT_ENVELOPE_ARGUMENT_CONFLICT")}catch{return{success:!1,error:"INVOCATION_MALFORMED_INPUT: explicit input integrity could not be verified.",errorCode:"INVOCATION_MALFORMED_INPUT",metadata:{invocationInput:{reason:"input-integrity-conflict",remediation:"Retry with exactly one of --args, --stdin or --args-file.",publicSafe:!0}},exitCode:1}}const a=t.rawArgs,r=dr(t);let i=a,n=r;const o=Ii(a);if(o.outcome!=="resolved"){const c=Ya(o,"client"),d=o.outcome==="malformed_input"?o.reason==="input_limit"||o.reason==="token_limit"||o.reason==="token_size_limit"?"input-limit-exceeded":o.reason==="invalid_control"||o.reason==="invalid_surrogate"?"invalid-control-character":o.reason==="unterminated_quote"||o.reason==="trailing_escape"||o.reason==="unsupported_escape"?"unterminated-quote":void 0:void 0,m=d?{code:"INVOCATION_MALFORMED_INPUT",reason:d,source:t.source,byteLength:t.byteLength,remediation:d==="input-limit-exceeded"?"Reduce the explicit command input or split the requested work into bounded invocations.":d==="invalid-control-character"?"Remove invalid control characters and retry with valid UTF-8 text.":"Close quotes and escapes, or use --stdin/--args-file for multiline content."}:void 0;return{success:!1,error:`INVOCATION_${o.outcome.toUpperCase()}`,errorCode:`INVOCATION_${o.outcome.toUpperCase()}`,metadata:{invocationAdmission:c,...m?{invocationInput:m}:{}},exitCode:1}}const s=_n(e.projectRoot),u=o.selection.commandId,f=u==="tech-debt"&&o.selection.positionals.length===0&&(o.selection.operationId==="scan"&&Object.keys(o.selection.options).length===0||o.selection.operationId===void 0&&o.selection.options.scan===!0&&Object.keys(o.selection.options).length===1),S=fa.find(c=>c.id===u),_=S?.subcommands.find(c=>c.id===o.selection.operationId),l=_?_.policy.strictReadOnly==="allow":S?.policy.strictReadOnly==="allow",y=u==="diagnose";let p;try{p=Ha({invocationId:Ft(),intent:e.strictReadOnly||y?{schemaVersion:1,policy:Ua,registryVersion:gt,registryChecksum:ht}:void 0,registryVersion:gt,registryChecksum:ht,registryAllowsStrict:l,requestCanonicalBytes:JSON.stringify({command:u})})}catch(c){if(c instanceof At)return{success:!1,error:c.code,errorCode:c.code,exitCode:1};throw c}{p.beginProjection();for(const c of sr)p.project(c);for(const c of $a)p.project(c);p.seal()}const I=p.mode==="strict";if(u==="create-epic"||u==="idea-diagnose")try{const c=Za(s);if(c&&c!=="finalized")return{success:!1,error:'PROJECT_IDENTITY_MIGRATION_INCOMPLETE: retry `neocortex-client invoke --args "*migrate-project-id"` before create-epic.',errorCode:"PROJECT_IDENTITY_MIGRATION_INCOMPLETE",metadata:{projectIdentityMigration:{phase:c,publicSafe:!0}},exitCode:1}}catch(c){const d=c instanceof In?c.code:"PROJECT_IDENTITY_MIGRATION_STATE_CORRUPT";return{success:!1,error:d,errorCode:d,exitCode:1}}const C=e.environment??process.env;if(e.privateExecutionBeta&&(u!=="yolo"&&u!=="research"&&u!=="write-spec"&&u!=="create-tasks"&&u!=="implement"&&u!=="exec"&&u!=="create-epic"&&u!=="idea-diagnose"&&u!=="idea-research"&&u!=="generate-epic"&&u!=="sync-openapi"&&u!=="chaos-plan"&&u!=="ui-ux-review"&&u!=="arch-prd"&&u!=="arch-architecture"&&u!=="arch-fitness-functions"&&u!=="arch-api-contracts"&&u!=="arch-api-integrations"&&u!=="arch-database"&&u!=="arch-security"&&u!=="arch-design-system"&&u!=="arch-performance"&&u!=="arch-testing"&&u!=="arch-infrastructure"&&u!=="arch-review"&&u!=="update-memory"&&u!=="arch-ux-design"&&u!=="generate-pacts"&&u!=="property-test"&&!f||I||e.platformTarget!==void 0&&e.platformTarget!=="codex"))return{success:!1,error:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",errorCode:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",exitCode:1};const V=ja({cwd:s,env:C,targetFlag:e.privateExecutionBeta?"codex":e.platformTarget}),T=V.targetId,z=e.privateExecutionBeta?void 0:La({cwd:s,env:C,targetFlag:e.platformTarget,nativeHostVersion:Ti(V,C)},V);u!=="migrate-project-id"&&p.execute({phase:"client-preflight",domain:"client-persistence",category:"first-run-marker",operation:"create"},()=>Si(),()=>{});const R=Ki(p),v=(e.serverUrl??R?.serverUrl??ya).replace(/\/+$/,"");if(u==="migrate-project-id"){const c=await ei(v);if(!c.supported)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_CAPABILITY_UNAVAILABLE: the server did not advertise the versioned migration capability; no local state was changed.",errorCode:"PROJECT_IDENTITY_MIGRATION_CAPABILITY_UNAVAILABLE",metadata:{projectIdentityMigrationCapability:c},exitCode:1};const d=[];let m;try{m=Xa(s)}catch(M){const ue=M instanceof In?M.code:"PROJECT_IDENTITY_MIGRATION_PREPARE_FAILED";return{success:!1,error:ue,errorCode:ue,exitCode:1}}d.push(bt({phase:"prepare",outcome:m.changed&&m.document.phase==="prepared"?"prepared":"retry",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId}));const x=Lr(s);if(x.config.project_id!==m.document.projectId)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",errorCode:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",metadata:{invocationDiagnostics:d},exitCode:1};const Y=await Vr(v,R?.licenseKey,p);if(Y.status!=="authenticated"){const M=Y.status==="refresh-required";return{success:!1,error:M?"Authentication refresh required. Run: neocortex activate YOUR-LICENSE-KEY":"Not authenticated. Visit https://neocortex.sh/portal/login to get your license key, then run: neocortex activate YOUR-LICENSE-KEY",errorCode:M?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",metadata:{invocationDiagnostics:d},exitCode:M?1:2}}let Ee;try{Ee=er(e.args.trim(),x)}catch(M){const ue=M instanceof tr?M.code:"PROJECT_IDENTITY_MIGRATION_PROJECTION_FAILED";return{success:!1,error:ue,errorCode:ue,metadata:{invocationDiagnostics:d},exitCode:1}}let oe={args:a,projectRoot:s.replace($t(),"~"),stateSnapshot:Ee,platformTarget:T,...z?{nativeHostAttestation:z}:{},projectId:m.document.projectId,projectIdentityMigration:m.request,inputEvidence:r,idempotencyKey:m.document.operationId,registryVersion:gt,registryChecksum:ht};try{oe=Gr(oe).body}catch(M){if(M instanceof An||M instanceof bn)return{success:!1,error:M.message,errorCode:M.code,metadata:{invokePayload:M.telemetry,invocationDiagnostics:d},exitCode:1};throw M}const te=await cr("invoke-query",()=>ta(v,oe,Y.token,{refreshToken:()=>Y.client.forceRefresh()}));if(!te.ok||!te.data)return d.push(bt({phase:"seed",outcome:"rejected",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId})),{success:!1,error:Be(te.error??"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",ft),errorCode:typeof te.errorBody?.error_code=="string"?te.errorBody.error_code:"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",metadata:{invocationDiagnostics:d},exitCode:te.status===401?2:1};const ee=te.data.metadata?.projectIdentityMigration;try{Fa(ee),d.push(bt({phase:"seed",outcome:ee.status,floor:ee.acceptedLegacyFloor,licenseId:"local-client",projectId:ee.projectId})),Ka(s,ee),d.push(bt({phase:"remote-acknowledged",outcome:ee.status,floor:ee.acceptedLegacyFloor,licenseId:"local-client",projectId:ee.projectId})),Qa(s,ee),d.push(bt({phase:"finalize",outcome:"finalized",floor:ee.acceptedLegacyFloor,licenseId:"local-client",projectId:ee.projectId}))}catch(M){d.push(bt({phase:"reconcile",outcome:"rejected",floor:m.document.legacyEpicFloor,licenseId:"local-client",projectId:m.document.projectId}));const ue=M instanceof In?M.code:M instanceof Error?M.message:"PROJECT_IDENTITY_MIGRATION_RECEIPT_INVALID";return{success:!1,error:ue,errorCode:ue,metadata:{invocationDiagnostics:d},exitCode:1}}return p.complete(),{success:!0,instructions:te.data.instructions,metadata:{...te.data.metadata,invocationDiagnostics:d},exitCode:0}}try{const{normalizeYoloopTargetArgs:c}=await import("../yoloop/target-normalization.js"),d=c(e.args,{projectRoot:s});if(!d.ok)return process.stderr.write(`${d.message} reason=${d.reasonCode}
|
|
26
26
|
`),{success:!1,error:d.message,exitCode:1};d.changed&&(e={...e,args:d.args},process.stderr.write(`[Neocortex] yoloop target normalized: ${d.reasonCodes.join(",")}
|
|
27
27
|
`))}catch{const c="INVALID_YOLOOP_TARGET: yoloop target normalization was unavailable; no request was sent.";return process.stderr.write(`${c}
|
|
28
|
-
`),{success:!1,error:c,exitCode:1}}const D=
|
|
28
|
+
`),{success:!1,error:c,exitCode:1}}const D=Nr(u);if(D)try{Dr(s,{allowMissingRuntime:!0}).runtimeMissing&&(await p.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},async()=>ri(s),async()=>{}),Dr(s))}catch(c){const d=c instanceof ct?c.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${d}. No request was sent; repair the canonical project state and retry.
|
|
29
29
|
`),{success:!1,error:d,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}if(u!=="migrate-state")try{p.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>wa(s,{args:e.args,canonicalCommandId:u}),()=>{})}catch(c){if(c instanceof _a)return process.stderr.write(`${c.message}
|
|
30
30
|
`),{success:!1,error:c.message,exitCode:1};const d=c instanceof Error?c.message:String(c);return process.stderr.write(`[Neocortex] state.json repair stopped unexpectedly: ${d}. No request was sent; inspect .neocortex/state.json and rerun.
|
|
31
|
-
`),{success:!1,error:d,exitCode:1}}let N;if(e.privateExecutionBeta&&(u==="sync-openapi"||u==="chaos-plan"||u==="arch-prd"||u==="arch-architecture"||u==="arch-fitness-functions"||u==="arch-api-contracts"||u==="arch-api-integrations"||u==="arch-database"||u==="arch-security"||u==="arch-design-system"||u==="arch-performance"||u==="arch-testing"||u==="arch-infrastructure"||u==="arch-review"||u==="update-memory"||u==="arch-ux-design"||u==="generate-pacts"||u==="property-test"||f))try{const{capturePrivateProjectStepBaseline:c}=await import("../private-execution/isolated-workspace.js");N=c(s)}catch{const c="private-execution-project-snapshot-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let
|
|
31
|
+
`),{success:!1,error:d,exitCode:1}}let N;if(e.privateExecutionBeta&&(u==="sync-openapi"||u==="chaos-plan"||u==="arch-prd"||u==="arch-architecture"||u==="arch-fitness-functions"||u==="arch-api-contracts"||u==="arch-api-integrations"||u==="arch-database"||u==="arch-security"||u==="arch-design-system"||u==="arch-performance"||u==="arch-testing"||u==="arch-infrastructure"||u==="arch-review"||u==="update-memory"||u==="arch-ux-design"||u==="generate-pacts"||u==="property-test"||f))try{const{capturePrivateProjectStepBaseline:c}=await import("../private-execution/isolated-workspace.js");N=c(s)}catch{const c="private-execution-project-snapshot-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let U;try{const c=await Fi(s,e.args,u);U=Lr(s,{epicAware:D,p205Authorities:c})}catch(c){const d=c instanceof ct?c.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${d}. No request was sent; repair the canonical project state/runtime sidecar and retry.
|
|
32
32
|
`),{success:!1,error:d,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}try{const{maybeAutoResolveYoloopArgs:c}=await import("../yoloop/invoke-hooks.js"),d={args:e.args,projectRoot:s,logger:{info:m=>process.stderr.write(`${m}
|
|
33
33
|
`),warn:m=>process.stderr.write(`${m}
|
|
34
|
-
`)}};c(d),d.args!==e.args&&(e={...e,args:d.args},i=d.args,n=
|
|
35
|
-
`)}try{const{readYoloopForRequest:c}=await import("../yoloop/invoke-hooks.js"),d=await c(e.args,s);if(d){const m=
|
|
36
|
-
`),{success:!1,error:m,errorCode:m,exitCode:1}}}try{const{readContinuityForRequest:c}=await import("../continuity/invoke-hooks.js"),d=await c(e.args,s,void 0,p,{includeExistingStore:!y});d&&(
|
|
37
|
-
`)}try{const{maybeRunDiscoveryHook:c}=await import("../yoloop/invoke-hooks.js");await c({args:e.args,projectRoot:s,stateSnapshot:
|
|
38
|
-
`)}try{const{readArchitecturePolicy:c}=await import("../policy/architecture-policy.js"),d=await c(s);d&&(
|
|
39
|
-
`)}});m.applied&&m.metadata&&(
|
|
40
|
-
`)}try{if(
|
|
41
|
-
`)}try{const c=await p.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"checkpoint-consume",operation:"consume"},async()=>{const{readAndConsumeCheckpoint:d}=await import("../checkpoint/index.js");return d(s)},async()=>{});c&&(
|
|
42
|
-
`)}const F=
|
|
43
|
-
`),{success:!1,error:c.message??"Trigger not available on your plan",exitCode:1}}catch{}const ie=await uo({args
|
|
34
|
+
`)}};c(d),d.args!==e.args&&(e={...e,args:d.args},i=d.args,n=dr(Kt(t.source,i)))}catch(c){const d=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] Auto-resolve hook (P121.05) failed: ${d}. Proceeding with raw args.
|
|
35
|
+
`)}try{const{readYoloopForRequest:c}=await import("../yoloop/invoke-hooks.js"),d=await c(e.args,s);if(d){const m=Ko(U,d);U.yoloop=m?{...d,continuationRecoveryEvidence:m}:d}}catch(c){if(/^\s*\*?(?:yoloop|auto-yolo|epic-runner|story-runner|loop-yolo|auto-epic)\b/i.test(e.args)){const m=c instanceof Error?c.message.match(/\bYOLOOP_[A-Z0-9_]+\b/)?.[0]??"YOLOOP_STATE_READ_FAILED":"YOLOOP_STATE_READ_FAILED";return process.stderr.write(`[Neocortex] ${m}. No yoloop request was sent and no state was mutated.
|
|
36
|
+
`),{success:!1,error:m,errorCode:m,exitCode:1}}}try{const{readContinuityForRequest:c}=await import("../continuity/invoke-hooks.js"),d=await c(e.args,s,void 0,p,{includeExistingStore:!y});d&&(U.continuity=d)}catch(c){if(c instanceof At)return{success:!1,error:c.code,errorCode:c.code,exitCode:1};const d=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] continuity snapshot hook failed: ${d}. Proceeding without continuity state.
|
|
37
|
+
`)}try{const{maybeRunDiscoveryHook:c}=await import("../yoloop/invoke-hooks.js");await c({args:e.args,projectRoot:s,stateSnapshot:U,featureFlag:process.env.YOLOOP_AUTO_DISCOVERY!=="off",logger:{warn:d=>{console.warn(d)},info:d=>{console.error(d)}}})}catch(c){const d=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] discovery hook failed: ${d}. Proceeding without enrichment.
|
|
38
|
+
`)}try{const{readArchitecturePolicy:c}=await import("../policy/architecture-policy.js"),d=await c(s);d&&(U.architecture_policy=d)}catch(c){const d=c instanceof Error?c.message:String(c);console.warn(`[Neocortex] architecture-policy hook failed: ${d}. Proceeding without policy.`)}try{const c=/^(1|true|on|yes)$/i.test(process.env.NEOCORTEX_GRAPH_RETRIEVAL??""),{maybeRunGraphRetrievalHook:d}=await import("../yoloop/invoke-hooks.js"),m=await d({args:e.args,projectRoot:s,featureFlag:c,logger:{warn:x=>process.stderr.write(`${x}
|
|
39
|
+
`)}});m.applied&&m.metadata&&(U.graphRetrieval=m.metadata)}catch(c){const d=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] graph retrieval hook failed: ${d}. Proceeding without enrichment.
|
|
40
|
+
`)}try{if(Ri(e.args)){const{collectProjectEvidence:c}=await import("../evidence/collector.js"),d=o.selection.uiUxReview?.architectureDir,m=c({projectRoot:s,...d?{candidatePaths:[d],includeFallbackInventory:!0}:{}});(m.evidence.length>0||m.exclusions.length>0)&&(U.projectEvidence=m)}}catch(c){const d=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] project evidence collection failed: ${d}. Proceeding without local project evidence.
|
|
41
|
+
`)}try{const c=await p.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"checkpoint-consume",operation:"consume"},async()=>{const{readAndConsumeCheckpoint:d}=await import("../checkpoint/index.js");return d(s)},async()=>{});c&&(U.implementCheckpoint=c)}catch(c){const d=c instanceof Error?c.message:String(c);process.stderr.write(`[Neocortex] checkpoint hook failed: ${d}. Proceeding without checkpoint.
|
|
42
|
+
`)}const F=R?.licenseKey?new En({cacheDir:vn,passphrase:R.licenseKey,strictReadOnly:I}):null,$=i.trim();if(!$&&F){const c=await p.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>Yi(F),async()=>null);if(c)return p.complete(),{success:!0,instructions:c.instructions,metadata:c.metadata,exitCode:0}}const j=await Vr(v,R?.licenseKey,p);if(j.status!=="authenticated"){const c=j.status==="refresh-required",d=!c&&R&&!R.licenseKey?" This may be caused by a machine fingerprint change (e.g., hardware or hostname change).":"";try{const m=Zn(),x=Qn(c?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",m);x&&process.stderr.write(Xn(x,m))}catch{}return{success:!1,error:c?"Authentication refresh required. Run: neocortex activate YOUR-LICENSE-KEY":`Not authenticated.${d} Visit https://neocortex.sh/portal/login to get your license key, then run: neocortex activate YOUR-LICENSE-KEY`,errorCode:c?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",exitCode:c?1:2}}const B=U.config.project_id;try{await p.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Jo(s,U,v,j.token,B,{refreshToken:()=>j.client.forceRefresh()}),async()=>0)}catch{}const me=Xo($);if(me&&!y)try{const c=await j.tierClient.preFlightCheck(me);if(!c.allowed)return process.stderr.write(`[neocortex] ${c.message}
|
|
43
|
+
`),{success:!1,error:c.message??"Trigger not available on your plan",exitCode:1}}catch{}const ie=await uo({args:$,projectRoot:s,platformTarget:T,environment:e.environment??process.env,bootstrapper:e.runnerBootstrapper,effectAuthority:p});if(ie.attachToRequest&&(U.runnerBootstrap=ie.metadata),ie.warning&&process.stderr.write(`[Neocortex] ${ie.warning}
|
|
44
44
|
`),!ie.shouldContinue)return ie.error&&process.stderr.write(`[Neocortex] ${ie.error}
|
|
45
|
-
`),{success:!1,error:ie.error??"Runner auto-bootstrap required but failed.",errorCode:ie.errorCode,exitCode:ie.exitCode??1};if(ie.metadata.command==="runner"&&(ie.metadata.operation==="status"||ie.metadata.operation==="doctor"))try{const c=e.runnerObserver??Pa;
|
|
46
|
-
`),{success:!1,error:d,errorCode:c.code,metadata:{stateProjection:c,publicSafe:!0},exitCode:1}}L=c?.snapshot??
|
|
47
|
-
`),{success:!1,error:d,errorCode:c.code,metadata:{structuralProjection:{...c.publicDetails,publicSafe:!0}},exitCode:1}}throw c}if(!I)try{const{openNativeAgentPrivateStore:c,resolveNativeAgentPrivateRuntimePaths:d}=await import("../continuity/native-agent-store.js"),m=d(s);if(
|
|
48
|
-
`),{success:!1,error:c,errorCode:"EPIC_PROJECT_ID_REQUIRED",exitCode:1}}let
|
|
49
|
-
`)});if(/\sbranchless-preparation\s*$/.test(i))J={...J,yoloSpecEnvelope:x};else{const{collectYoloChangeEvidence:Y,reconcileYoloChangeEvidenceLease:
|
|
50
|
-
`),{success:!1,error:c.message,errorCode:c.code,metadata:{invokePayload:c.telemetry},exitCode:1};throw c}if(
|
|
45
|
+
`),{success:!1,error:ie.error??"Runner auto-bootstrap required but failed.",errorCode:ie.errorCode,exitCode:ie.exitCode??1};if(ie.metadata.command==="runner"&&(ie.metadata.operation==="status"||ie.metadata.operation==="doctor"))try{const c=e.runnerObserver??Pa;U.runnerOperationalStatus=await c(ie.metadata.operation,{projectRoot:s,env:e.environment??process.env,effectAuthority:p})}catch{}let L;try{const c=va($,U);if(c&&!c.ok){const d=`${c.code}: structural projection failed closed; select a valid target or repair the dependency DAG.`;return process.stderr.write(`${d}
|
|
46
|
+
`),{success:!1,error:d,errorCode:c.code,metadata:{stateProjection:c,publicSafe:!0},exitCode:1}}L=c?.snapshot??er($,U),Sn($)==="migrate-state"&&(L={...L,migrationAuthority:Ra(s)})}catch(c){if(c instanceof Aa)return{success:!1,error:c.reasonCode,errorCode:c.reasonCode,exitCode:1};if(c instanceof tr){const d=`${c.code}: structural projection failed closed; select a valid target or repair the dependency DAG.`;return process.stderr.write(`${d}
|
|
47
|
+
`),{success:!1,error:d,errorCode:c.code,metadata:{structuralProjection:{...c.publicDetails,publicSafe:!0}},exitCode:1}}throw c}if(!I)try{const{openNativeAgentPrivateStore:c,resolveNativeAgentPrivateRuntimePaths:d}=await import("../continuity/native-agent-store.js"),m=d(s);if(wt(m.databasePath)){const x=await c(s);try{const Y=x.store.listRecentNativeAgentDispatches(20);Y.length>0&&(L.nativeAgentDispatches=Y)}finally{x.store.close()}}}catch{}const H=Sn($);let Qe=!1;if(H==="arch-plan"&&!I&&L.archPlan?.execution===void 0){const c=oa(i);if(c)try{if(!Object.hasOwn(U.epics,c)||!Object.hasOwn(L.epics,c))throw new Error("architecture-root-epic-binding-invalid");const d=jt(s,c);L={...L,archPlan:{execution:{schemaVersion:1,owner:"root",currentStageCommand:"arch-prd",continuationState:"delegate",evidencePolicy:"v2-required",targetEpicId:c,graphRevision:d,graphSource:"committed-epic-v1",acceptedStages:[]}}},Qe=!0}catch{return{success:!1,error:"architecture-root-epic-binding-invalid",errorCode:"architecture-root-epic-binding-invalid",exitCode:1}}}if((H==="arch-plan"||H?.startsWith("arch-")||H==="generate-pacts"||H==="update-memory")&&L.archPlan?.execution?.graphSource==="committed-epic-v1")try{const c=L.archPlan.execution;if(typeof c.targetEpicId!="string"||typeof c.graphRevision!="string"||c.graphRevision!==jt(s,c.targetEpicId))throw new Error("architecture-root-epic-binding-invalid")}catch{return{success:!1,error:"architecture-root-epic-binding-invalid",errorCode:"architecture-root-epic-binding-invalid",exitCode:1}}const Me=B;if((H==="create-epic"||H==="idea-diagnose")&&!Me){const c='EPIC_PROJECT_ID_REQUIRED: run `neocortex-client invoke --args "*migrate-project-id"` and retry the planning command. No repository checkout or database credentials are required.';return process.stderr.write(`${c}
|
|
48
|
+
`),{success:!1,error:c,errorCode:"EPIC_PROJECT_ID_REQUIRED",exitCode:1}}let Oe;try{Oe=p.execute({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>H==="create-epic"||H==="idea-diagnose"?yi(s,$,H):void 0,()=>{})}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const mt=Oe?.key,ze=I?{schemaVersion:1,invocationId:p.invocationId,intent:p.intent,clientProjection:Ba(sr.map(c=>({...c,count:1})))}:void 0;let Q,he,re;if(e.privateExecutionBeta&&H==="idea-research")try{const c=L.scope?.targetEpicId,d=c?L.epics[c]:void 0,m=h(d?.createEpicPlanningPhysical)?d.createEpicPlanningPhysical:void 0;if(!c||!m||typeof m.claimId!="string"||typeof m.receiptId!="string")throw new Error("planning-research-predecessor-unavailable");const x=X(s,".neocortex/state.json"),Y=_t(x);if(!Y.isFile()||Y.isSymbolicLink()||Y.size>8*1024*1024)throw new Error("planning-research-state-unavailable");const Ee=Te(x),oe=JSON.parse(Ee.toString("utf8")),te=Yn(oe,m.claimId,c),ee=h(oe)&&h(oe.epics)&&h(oe.epics[c])?oe.epics[c]:void 0,M=h(ee?.createEpicPlanningPhysical)?ee.createEpicPlanningPhysical:void 0;if(M?.receiptId!==m.receiptId||!E(M,m))throw new Error("planning-research-predecessor-drift");const ue=[".neocortex/state.json",".neocortex/planning/planning.json",`.neocortex/planning/epic-${c}/idea.json`,`.neocortex/planning/epic-${c}/diagnosis.md`,`.neocortex/planning/epic-${c}/enriched-prompt.md`],De={...process.env};for(const O of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete De[O];for(const O of ue){const ve=_t(X(s,O));if(!ve.isFile()||ve.isSymbolicLink()||ve.size>8*1024*1024)throw new Error("planning-research-source-unavailable");const Re=je("git",["show",`HEAD:${O}`],{cwd:s,env:De,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!Te(X(s,O)).equals(Re))throw new Error("planning-research-source-uncommitted")}he={claimId:m.claimId,epicId:c,diagnosisReceiptId:te.diagnosisReceiptId,intakeRevision:te.intakeRevision,physicalAcceptanceReceiptId:m.receiptId,sourceStateSha256:Ge("sha256").update(Ee).digest("hex")}}catch{return{success:!1,error:"private-execution-planning-predecessor-unavailable",errorCode:"private-execution-planning-predecessor-unavailable",exitCode:1}}if(e.privateExecutionBeta&&H==="generate-epic")try{const c=L.scope?.targetEpicId,d=c?L.epics[c]:void 0,m=h(d?.createEpicPlanningResearchPhysical)?d.createEpicPlanningResearchPhysical:void 0;if(!c||!m||typeof m.claimId!="string"||typeof m.receiptId!="string")throw new Error("planning-generation-predecessor-unavailable");const x=X(s,".neocortex/state.json"),Y=_t(x);if(!Y.isFile()||Y.isSymbolicLink()||Y.size>8*1024*1024)throw new Error("planning-generation-state-unavailable");const Ee=Te(x),oe=JSON.parse(Ee.toString("utf8")),te=zn(oe,m.claimId,c),ee=h(oe)&&h(oe.epics)&&h(oe.epics[c])?oe.epics[c]:void 0,M=h(ee?.createEpicPlanningResearchPhysical)?ee.createEpicPlanningResearchPhysical:void 0;if(M?.receiptId!==m.receiptId||!E(M,m))throw new Error("planning-generation-predecessor-drift");const ue=[".neocortex/state.json",".neocortex/planning/planning.json",`.neocortex/planning/epic-${c}/idea.json`,`.neocortex/planning/epic-${c}/diagnosis.md`,`.neocortex/planning/epic-${c}/enriched-prompt.md`,`.neocortex/planning/epic-${c}/research.md`],De={...process.env};for(const O of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete De[O];for(const O of ue){const ve=_t(X(s,O));if(!ve.isFile()||ve.isSymbolicLink()||ve.size>8*1024*1024)throw new Error("planning-generation-source-unavailable");const Re=je("git",["show",`HEAD:${O}`],{cwd:s,env:De,stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:8*1024*1024});if(!Te(X(s,O)).equals(Re))throw new Error("planning-generation-source-uncommitted")}re={claimId:m.claimId,epicId:c,diagnosisReceiptId:te.diagnosisReceiptId,researchReceiptId:te.researchReceiptId,intakeRevision:te.intakeRevision,physicalAcceptanceReceiptId:te.physicalAcceptanceReceiptId,sourceStateSha256:Ge("sha256").update(Ee).digest("hex")}}catch{return{success:!1,error:"private-execution-planning-predecessor-unavailable",errorCode:"private-execution-planning-predecessor-unavailable",exitCode:1}}if(e.privateExecutionBeta)try{const{preflightPrivateCodexExecutor:c}=await import("../private-execution/codex-executor.js");Q=await c(s)}catch(c){const d=c instanceof Error&&/^private-codex-[a-z-]+$/.test(c.message)?c.message:"private-codex-preflight-unavailable";return{success:!1,error:d,errorCode:d,exitCode:1}}const Xe=Q?{schemaVersion:1,hostKind:"codex-cli",hostVersion:Q.hostVersion,sandboxProof:{schemaVersion:5,trust:"client-self-attested",credentialKind:"chatgpt-subscription",authIsolation:"passed",workspaceWrite:"passed",gitControlWriteDenied:"passed",gitLifecycleReadDenied:"passed",mcpIsolation:"passed",environmentIsolation:"passed",networkDenied:"passed",observedAtMs:Q.observedAtMs}}:void 0;let Ne;if(H==="arch-plan"&&L.archPlan?.execution?.currentStageCommand==="generate-pacts"&&L.archPlan.execution.continuationState==="ask-user")try{if(Ne=Gn(s),!Ne)throw new Error("architecture-answers-required")}catch(c){const d=c instanceof Error&&/^architecture-answers-[a-z-]+$/.test(c.message)?c.message:"architecture-answers-failed";return{success:!1,error:d,errorCode:d,exitCode:1}}let yt;if(H==="arch-plan"&&L.archPlan?.execution?.currentStageCommand==="generate-pacts"&&L.archPlan.execution.continuationState==="delegate"&&L.archPlan.execution.childStatus==="succeeded")try{if(yt=Gn(s),!yt||!E(L.archPlan.execution.pactAnswerReceipt,yt))throw new Error("architecture-answers-conflict")}catch{return{success:!1,error:"architecture-answers-conflict",errorCode:"architecture-answers-conflict",exitCode:1}}let ye,b,pe;if(e.privateExecutionBeta&&H==="generate-pacts")try{const c=i.trim().match(/^\*?generate-pacts (P[1-9][0-9]{0,11})$/)?.[1],d=L.archPlan?.execution;if(b=ia(s),!c||!d||d.currentStageCommand!=="generate-pacts"||d.continuationState!=="delegate"||d.targetEpicId!==c||!b||!E(d.pactAnswerReceipt,b.receipt))throw new Error("private-execution-pact-admission-unverified");const m=ca(s,b.answers.generateProvider);if(m.outcome!=="ready")throw new Error("private-execution-pact-admission-unverified");ye=m.writeSet,pe={schemaVersion:1,targetEpicId:c,graphRevision:b.receipt.graphRevision,answersSha256:b.receipt.answersSha256,specSha256:ye.specSha256,pathsSha256:ye.pathsSha256,endpointCount:ye.endpointCount,pathCount:ye.paths.length,publicSafe:!0}}catch{const c="private-execution-pact-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let de,ae;if(e.privateExecutionBeta&&H==="arch-ux-design")try{const c=i.trim().match(/^\*?arch-ux-design (P[1-9][0-9]{0,11})$/)?.[1],d=L.archPlan?.execution;if(!c||!d||d.currentStageCommand!=="arch-ux-design"||d.continuationState!=="delegate"||d.targetEpicId!==c||typeof d.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(d.graphRevision))throw new Error("private-execution-ux-admission-unverified");const{deriveUxWriteSet:m}=await import("../private-execution/ux-write-set.js");de=m(s,c),ae={schemaVersion:1,targetEpicId:c,graphRevision:d.graphRevision,adapterId:de.adapterId,authoritySha256:de.authoritySha256,pathsSha256:de.pathsSha256,screenCount:de.screenCount,pathCount:de.pathCount,publicSafe:!0}}catch{const c="private-execution-ux-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let Et,We,ge;if(e.privateExecutionBeta&&H==="property-test")try{if(o.selection.positionals.length!==0||o.selection.operationId!==void 0||Object.keys(o.selection.options).length!==0)throw new Error("private-execution-property-admission-unverified");const{loadPropertyTestChoices:c}=await import("../private-execution/property-test-choices.js"),{propertyTestExecutionInput:d}=await import("../private-execution/property-test-plan.js"),m=c(s);if(!m)throw new Error("private-execution-property-admission-unverified");Et=m.choices,We=m.plan,ge=d(m.plan)}catch{const c="private-execution-property-admission-unverified";return{success:!1,error:c,errorCode:c,exitCode:1}}let J={args:i,projectRoot:s.replace($t(),"~"),stateSnapshot:L,...Ne?{architectureAnswerReceipt:Ne}:{},...pe?{pactExecutionInput:pe}:{},...ae?{uxExecutionInput:ae}:{},...ge?{propertyTestExecutionInput:ge}:{},platformTarget:T,...z?{nativeHostAttestation:z}:{},...Xe?{privateExecution:Xe}:{},projectId:Me,inputEvidence:n,idempotencyKey:mt,registryVersion:gt,registryChecksum:ht,...ze?{strictReadOnly:ze}:{}};const St=Tt(J);if(!I&&e.inputSource&&e.inputSource!=="args"&&St>=Cn)try{J={argsRef:(await Va(p,"secondary-mutation",()=>ro(v,i,j.token,()=>j.client.forceRefresh()),async()=>{throw new At("readonly-physical-boundary-unsafe","boundary")})).argsRef,projectRoot:s.replace($t(),"~"),stateSnapshot:L,...Ne?{architectureAnswerReceipt:Ne}:{},platformTarget:T,...z?{nativeHostAttestation:z}:{},...Xe?{privateExecution:Xe}:{},projectId:Me,inputEvidence:n,idempotencyKey:mt,registryVersion:gt,registryChecksum:ht,...ze?{strictReadOnly:ze}:{}}}catch(c){return c instanceof At?{success:!1,error:c.code,errorCode:c.code,exitCode:1}:{success:!1,error:`INVOKE_MATERIALIZATION_FAILED: ${c instanceof Error?c.message:String(c)}`,errorCode:"INVOKE_MATERIALIZATION_FAILED",exitCode:1}}if(H==="yolo"&&L.scope?.projectionMode==="yolo-story"){const c=L.scope?.targetStoryId,d=L.scope?.targetEpicId;if(!c||!d)return{success:!1,error:"yolo-spec-envelope-target-mismatch",errorCode:"yolo-spec-envelope-target-mismatch",exitCode:1};try{const{collectYoloSpecEnvelope:m}=await import("../yolo/spec-envelope-collector.js"),x=m({projectRoot:s,storyId:c,epicId:d,inputSha256:n.sha256,onOmittedReferences:Y=>process.stderr.write(`[Neocortex] yolo-spec-supporting-references-omitted count=${Y}; core story artifacts preserved.
|
|
49
|
+
`)});if(/\sbranchless-preparation\s*$/.test(i))J={...J,yoloSpecEnvelope:x};else{const{collectYoloChangeEvidence:Y,reconcileYoloChangeEvidenceLease:Ee}=await import("../yolo/change-evidence-collector.js");await Ee({projectRoot:s,storyId:c,epicId:d});const oe=Y({projectRoot:s,defaultBranch:L.config.default_branch,expectedHeadSha:x.sourceRevision.headSha,storyId:c,epicId:d});J={...J,yoloSpecEnvelope:x,yoloChangeEvidence:oe}}}catch(m){const x=m instanceof Error&&/^yolo-(?:spec-envelope|change-evidence)-[a-z-]+$/.test(m.message)?m.message:"yolo-spec-envelope-unsafe";return{success:!1,error:x,errorCode:x,exitCode:1}}}try{const c=Gr(J);if(H==="migrate-state"&&c.degraded)return{success:!1,error:"state_migration_payload_degraded",errorCode:"state_migration_payload_degraded",exitCode:1};J=c.body,c.degraded?Fr(J,c.telemetry):po(J)}catch(c){if(c instanceof An||c instanceof bn)return Fr(J,c.telemetry),process.stderr.write(`[Neocortex] ${c.message}
|
|
50
|
+
`),{success:!1,error:c.message,errorCode:c.code,metadata:{invokePayload:c.telemetry},exitCode:1};throw c}if(H==="yolo"&&J.yoloSpecEnvelope)try{const{collectYoloSpecEnvelope:c}=await import("../yolo/spec-envelope-collector.js"),d=c({projectRoot:s,storyId:J.yoloSpecEnvelope.storyId,epicId:J.yoloSpecEnvelope.epicId,inputSha256:n.sha256,collectedAt:J.yoloSpecEnvelope.collectedAt});if(d.envelopeSha256!==J.yoloSpecEnvelope.envelopeSha256)throw new Error("yolo-spec-envelope-stale");if(J.yoloChangeEvidence){const{collectYoloChangeEvidence:m}=await import("../yolo/change-evidence-collector.js"),x=m({projectRoot:s,defaultBranch:L.config.default_branch,expectedHeadSha:d.sourceRevision.headSha,storyId:d.storyId,epicId:d.epicId});if(x.pathsSha256!==J.yoloChangeEvidence.pathsSha256||x.baseSha!==J.yoloChangeEvidence.baseSha)throw new Error("yolo-spec-envelope-stale")}}catch{return{success:!1,error:"yolo-spec-envelope-stale",errorCode:"yolo-spec-envelope-stale",exitCode:1}}const k=H==="arch-plan"?J.stateSnapshot.archPlan?.execution:void 0;let Ze;if(k?.owner==="root"&&(k.currentStageCommand==="arch-prd"||k.currentStageCommand==="arch-architecture"||k.currentStageCommand==="arch-fitness-functions"||k.currentStageCommand==="arch-api-contracts"||k.currentStageCommand==="generate-pacts"||k.currentStageCommand==="arch-api-integrations"||k.currentStageCommand==="arch-database"||k.currentStageCommand==="arch-security"||k.currentStageCommand==="arch-design-system"||k.currentStageCommand==="arch-ux-design"||k.currentStageCommand==="arch-performance"||k.currentStageCommand==="arch-testing"||k.currentStageCommand==="arch-infrastructure"||k.currentStageCommand==="arch-review"||k.currentStageCommand==="update-memory")&&(k.continuationState==="delegate"||k.continuationState==="advance"||k.currentStageCommand==="update-memory"&&k.continuationState==="complete"||k.currentStageCommand==="arch-review"&&k.continuationState==="ask-user"||k.currentStageCommand==="generate-pacts"&&k.continuationState==="ask-user"))try{const c=Te(X(s,".neocortex","state.json"),"utf8"),d=JSON.parse(c),m=h(d.archPlan)?d.archPlan.execution:void 0;if(Qe?m!==void 0||!h(d.epics)||!Object.hasOwn(d.epics,String(k.targetEpicId))||k.graphSource!=="committed-epic-v1"||k.graphRevision!==jt(s,String(k.targetEpicId)):!E(rn(m),k))throw new Error("architecture-root-state-binding-invalid");if(Ze=Ge("sha256").update(c).digest("hex"),Ne&&Ne.stateSha256!==Ze)throw new Error("architecture-root-state-binding-invalid");if(k.currentStageCommand==="update-memory"&&k.childStatus==="succeeded"){const x=k.continuationState==="complete"&&Array.isArray(k.acceptedStages)?{...k,continuationState:"delegate",acceptedStages:k.acceptedStages.slice(0,14)}:k;if(!Yt(k.terminalMemoryCheckpoint,k)||!E(k.terminalMemoryCheckpoint,mn(s,x)))throw new Error("architecture-terminal-memory-physical-invalid")}}catch{return{success:!1,error:"architecture-root-state-binding-invalid",errorCode:"architecture-root-state-binding-invalid",exitCode:1}}let g=await cr("invoke-query",()=>ta(v,J,j.token,{refreshToken:()=>j.client.forceRefresh()})),Pt;if(I&&g.ok)try{if(y){const d=g.data?.metadata;if(d&&["stateUpdate","stateMutated","yoloopStateUpdate","continuityStateUpdate","checkpoint","schedulerStateUpdate","quotaCacheUpdate","projectIdentityMigration","epicClaim","gitLifecycleGraphAuthority"].some(x=>d[x]!==void 0))throw new At("readonly-response-conflict")}const c=g.data?.metadata.strictReadOnly;Wa(p,c),y&&za(g.data?.metadata.strictDiagnose,a,g.data?.instructions??""),Pt=c.security}catch(c){const d=c instanceof At?c.code:"readonly-receipt-mismatch";return{success:!1,error:d,errorCode:d,exitCode:1}}if(!g.ok&&g.status===426){const c=g.errorBody,d=c?.upgrade_command??"npm install -g @ornexus/neocortex@latest",m=c?.min_version??"unknown";return process.stderr.write(`
|
|
51
51
|
`),process.stderr.write(`==================================================
|
|
52
52
|
`),process.stderr.write(` UPGRADE REQUIRED
|
|
53
53
|
`),process.stderr.write(`==================================================
|
|
54
54
|
`),process.stderr.write(`
|
|
55
|
-
Your Neocortex version (${
|
|
55
|
+
Your Neocortex version (${Rt}) is no longer supported.
|
|
56
56
|
`),process.stderr.write(` Minimum required: ${m}
|
|
57
57
|
|
|
58
58
|
`),process.stderr.write(` Run this command to update:
|
|
@@ -62,16 +62,16 @@ ${t}
|
|
|
62
62
|
`),process.stderr.write(` After updating, re-run your command.
|
|
63
63
|
`),process.stderr.write(`==================================================
|
|
64
64
|
|
|
65
|
-
`),{success:!1,error:`UPGRADE_REQUIRED: Client version ${
|
|
66
|
-
`),{success:!1,error:d,errorCode:d,exitCode:1}}if(
|
|
67
|
-
`),{success:!1,error:d,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}catch(c){if(g.data.metadata?.stateMutationReason==="inline-yolo-materialized-synthetic-story"){const d=c instanceof Error?c.message:String(c),m=`STATE_WRITEBACK_BLOCKED: inline-yolo persistence failed (${
|
|
65
|
+
`),{success:!1,error:`UPGRADE_REQUIRED: Client version ${Rt} is below minimum ${m}. Run: ${d}`,exitCode:3}}if(!g.ok||!g.data){const c=g.status===401?2:(g.status===429||g.status>=500,1),d=Qi(g);try{if(d){const m=Zn(),x=Qn(d,m);x&&process.stderr.write(Xn(x,m))}}catch{}return{success:!1,error:Be(g.error??"Unknown error from server",ft),...d?{errorCode:d}:{},exitCode:c}}if(e.privateExecutionBeta&&!ua(g.data))return{success:!1,error:"private-execution-public-envelope-invalid",errorCode:"private-execution-public-envelope-invalid",exitCode:1};if(Ze&&k&&g.data.metadata?.mode==="arch-plan"&&h(g.data.metadata.archPlan)&&h(g.data.metadata.archPlan.execution)&&(g.data.metadata.archPlan.execution.nextAction==="delegate"||g.data.metadata.archPlan.execution.nextAction==="resume"||g.data.metadata.archPlan.execution.nextAction==="ask-user"||g.data.metadata.archPlan.execution.nextAction==="complete"&&g.data.metadata.archPlan.execution.currentStageCommand==="update-memory"||g.data.metadata.archPlan.execution.nextAction==="blocked"&&(g.data.metadata.archPlan.execution.currentStageCommand==="arch-ux-design"||g.data.metadata.archPlan.execution.currentStageCommand==="arch-performance"||g.data.metadata.archPlan.execution.currentStageCommand==="arch-testing"||g.data.metadata.archPlan.execution.currentStageCommand==="arch-infrastructure"||g.data.metadata.archPlan.execution.currentStageCommand==="arch-review")))try{await p.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>ji({projectRoot:s,sourceStateSha256:Ze,requestExecution:k,initialBinding:Qe,answerReceipt:Ne,pactRecordedReceipt:yt,metadata:g.data.metadata}),async()=>{throw new Error("architecture-root-writeback-effect-skipped")})}catch(c){const d=c instanceof Error&&/^architecture-root-[a-z-]+$/.test(c.message)?c.message:"architecture-root-writeback-failed";return process.stderr.write(`[Neocortex] ${d}. Root stage instruction was not released.
|
|
66
|
+
`),{success:!1,error:d,errorCode:d,exitCode:1}}if(!$&&g.data.metadata?.mode==="menu"&&F&&await p.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>zi(F,g.data.instructions,g.data.metadata),async()=>{}).catch(()=>{}),g.data.metadata&&await p.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"tier-cache",operation:"update"},()=>j.tierClient.updateQuotaFromResponse(g.data.metadata),async()=>{}).catch(()=>{}),g.data.metadata?.stateMutated===!0)try{const c=await p.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>{const{persistMigratedStateFromResponse:d}=await import("../yoloop/invoke-hooks.js");return d(g.data.metadata,s)},async()=>({applied:!1,blocking:!1,reasonCode:"state-writeback-effect-skipped"}));if(c.blocking){const d=`STATE_WRITEBACK_BLOCKED: ${c.reasonCode}. Canonical state was not replaced.`;return process.stderr.write(`${d}
|
|
67
|
+
`),{success:!1,error:d,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}catch(c){if(g.data.metadata?.stateMutationReason==="inline-yolo-materialized-synthetic-story"){const d=c instanceof Error?c.message:String(c),m=`STATE_WRITEBACK_BLOCKED: inline-yolo persistence failed (${Be(d,ft)}).`;return process.stderr.write(`${m}
|
|
68
68
|
`),{success:!1,error:m,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}if(g.data.metadata?.gitLifecycleGraphAuthority)try{await p.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},()=>ii(s,g.data.metadata.gitLifecycleGraphAuthority),async()=>{throw new Error("git-lifecycle-graph-authority-effect-skipped")})}catch(c){const d=c instanceof Error&&/^git-lifecycle-/.test(c.message)?c.message:"git-lifecycle-graph-authority-persist-failed";return process.stderr.write(`[Neocortex] ${d}. Graph authority was not persisted; no YOLO checkpoint instruction was released.
|
|
69
69
|
`),{success:!1,error:d,errorCode:"GIT_LIFECYCLE_GRAPH_AUTHORITY_INVALID",exitCode:1}}if(g.data.metadata?.mode==="error"&&g.data.metadata?.errorCode==="CLIENT_UPGRADE_REQUIRED")return process.stderr.write(`
|
|
70
70
|
`),process.stderr.write(`==================================================
|
|
71
71
|
`),process.stderr.write(` YOLOOP CLIENT UPGRADE REQUIRED
|
|
72
72
|
`),process.stderr.write(`==================================================
|
|
73
73
|
`),process.stderr.write(`
|
|
74
|
-
Your Neocortex client version (${
|
|
74
|
+
Your Neocortex client version (${Rt}) does not
|
|
75
75
|
`),process.stderr.write(` support client-side yoloop state persistence.
|
|
76
76
|
|
|
77
77
|
`),process.stderr.write(` Run this command to upgrade:
|
|
@@ -85,25 +85,27 @@ ${t}
|
|
|
85
85
|
`),{success:!1,error:x,errorCode:x,exitCode:1}}}catch(m){if(d){const x=m instanceof Error?m.message.match(/\bYOLOOP_[A-Z0-9_]+\b/)?.[0]??"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED":"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED";return process.stderr.write(`[Neocortex] ${x}. No yoloop continuation instructions were released.
|
|
86
86
|
`),{success:!1,error:x,errorCode:x,exitCode:1}}}}if(g.data.metadata?.continuityStateUpdate)try{const c=await p.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"continuity-store",operation:"update"},async()=>{const{persistContinuityFromResponse:d}=await import("../continuity/invoke-hooks.js");return d(g.data.metadata,s)},async()=>({ok:!0,reasonCodes:[]}));if(!c.ok){const d=c.reasonCodes.join(",");return process.stderr.write(`[Neocortex] continuity persistence failed: ${d}. No continuity mutation was committed.
|
|
87
87
|
`),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${d}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}}catch(c){const d=c instanceof Error?c.message:String(c);return process.stderr.write(`[Neocortex] continuity persistence hook failed: ${d}. No continuity mutation was committed.
|
|
88
|
-
`),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${
|
|
88
|
+
`),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${Be(d,ft)}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}if(g.data.metadata?.tier_changed){const c=g.data.metadata.current_tier;try{await j.client.forceRefresh()?(await j.tierClient.invalidateTierCache(),process.stderr.write(`[Neocortex] Token atualizado automaticamente para tier ${c}
|
|
89
89
|
`)):process.stderr.write(`[Neocortex] Seu tier foi atualizado para ${c}! Execute "neocortex activate" para obter um token atualizado.
|
|
90
90
|
`)}catch{process.stderr.write(`[Neocortex] Seu tier foi atualizado para ${c}! Execute "neocortex activate" para obter um token atualizado.
|
|
91
|
-
`)}}let K,Tt=!1;if(e.privateExecutionBeta)try{if(!Z||!g.data.metadata?.privateExecution||!He||g.data.metadata?.mode!=="yolo"&&g.data.metadata?.mode!=="step"&&g.data.metadata?.mode!=="pipeline"&&g.data.metadata?.mode!=="create-epic"&&g.data.metadata?.mode!=="utility"&&g.data.metadata?.mode!=="tech-debt"&&g.data.metadata?.mode!=="ui-ux-review"||typeof g.data.metadata.stepId!="string")throw new Error("private-execution-descriptor-unavailable");const{consumePrivateExecutionDelivery:c,privateExecutionStateSnapshotSha256:d}=await import("../private-execution/delivery.js"),{preflightPrivateCodexExecutor:m,runPrivateCodexStep:x}=await import("../private-execution/codex-executor.js"),Y=g.data.metadata.mode==="yolo",ye=g.data.metadata.mode==="ui-ux-review"&&g.data.metadata.resolvedTrigger==="ui-ux-review",oe=g.data.metadata.mode==="create-epic",te=g.data.metadata.mode==="step"&&g.data.metadata.resolvedTrigger==="idea-diagnose",ee=g.data.metadata.mode==="step"&&g.data.metadata.resolvedTrigger==="idea-research",j=g.data.metadata.mode==="step"&&g.data.metadata.resolvedTrigger==="generate-epic",ue=oe||te;if(ee&&!le||j&&!re)throw new Error("private-execution-planning-predecessor-unavailable");const je=g.data.metadata.mode==="utility"&&g.data.metadata.resolvedTrigger==="sync-openapi"||g.data.metadata.mode==="utility"&&g.data.metadata.resolvedTrigger==="chaos-plan"||f&&g.data.metadata.mode==="tech-debt"&&g.data.metadata.resolvedTrigger==="tech-debt",O=g.data.metadata.mode==="step"&&(g.data.metadata.resolvedTrigger==="arch-prd"||g.data.metadata.resolvedTrigger==="arch-architecture"||g.data.metadata.resolvedTrigger==="arch-fitness-functions"||g.data.metadata.resolvedTrigger==="arch-api-contracts"||g.data.metadata.resolvedTrigger==="arch-api-integrations"||g.data.metadata.resolvedTrigger==="arch-database"||g.data.metadata.resolvedTrigger==="arch-security"||g.data.metadata.resolvedTrigger==="arch-design-system"||g.data.metadata.resolvedTrigger==="arch-performance"||g.data.metadata.resolvedTrigger==="arch-testing"||g.data.metadata.resolvedTrigger==="arch-infrastructure"||g.data.metadata.resolvedTrigger==="arch-review"||g.data.metadata.resolvedTrigger==="update-memory")?g.data.metadata.resolvedTrigger:void 0,ve=O!==void 0,Re=g.data.metadata.mode==="step"&&g.data.metadata.resolvedTrigger==="generate-pacts",et=g.data.metadata.mode==="step"&&g.data.metadata.resolvedTrigger==="arch-ux-design",tt=g.data.metadata.mode==="utility"&&g.data.metadata.resolvedTrigger==="property-test",sn=f?"tech-debt":g.data.metadata.resolvedTrigger==="chaos-plan"?"chaos-plan":"sync-openapi",Vn=f?"tech-debt-registry-v1":sn==="chaos-plan"?"chaos-quarterly-v1":"sync-openapi-contract-v1",Me=L.archPlan?.execution,$t=Me?.targetEpicId,Bt=Me?.graphRevision;if(ve&&(Me?.currentStageCommand!==O||typeof $t!="string"||!/^P[1-9][0-9]{0,11}$/.test($t)||typeof Bt!="string"||!/^[a-f0-9]{64}$/.test(Bt)))throw new Error("private-execution-architecture-admission-unverified");if(Re&&(!pe||!me||!b||Me?.currentStageCommand!=="generate-pacts"||Me.continuationState!=="delegate"||Me.targetEpicId!==pe.targetEpicId||Me.graphRevision!==pe.graphRevision||!E(Me.pactAnswerReceipt,b.receipt)))throw new Error("private-execution-pact-admission-unverified");if(et&&(!ae||!de||Me?.currentStageCommand!=="arch-ux-design"||Me.continuationState!=="delegate"||Me.targetEpicId!==ae.targetEpicId||Me.graphRevision!==ae.graphRevision))throw new Error("private-execution-ux-admission-unverified");if(tt&&(!he||!mt||!We||g.data.metadata.stepId!=="step-a8ce5c64"))throw new Error("private-execution-property-admission-unverified");let Un;if(Re){const{planPactToolchainManifest:se,preparePactToolchainCandidate:$}=await import("../private-execution/pact-toolchain.js");try{se(s,b.answers.generateProvider),Un=$(s,b.answers.generateProvider)}catch(P){if(P.message!=="pact-toolchain-manifest-unsupported")throw P}}let st,ce,dn;const Ee=g.data.metadata.gitLifecycleGraphAuthority,dt=g.data.metadata.privateExecutionRootAction;let xt;if(Y){if(!Ee||typeof Ee.storyId!="string"||typeof Ee.graphRevision!="string"||typeof Ee.executionBranch!="string")throw new Error("private-execution-graph-unavailable");if(xt=Ee.storyId,dt?.action==="prepare-epic-checkout"){const{prepareDirectYoloSetup:Te}=await import("../git/direct-yolo-checkpoint.js"),{capturePrivateYoloCleanHead:pt,recordPrivateYoloCleanBaseline:xe}=await import("../private-execution/clean-baseline.js"),Ce=pt(s),Ve=await Te({projectRoot:s,storyId:dt.storyId});if(!Ve.ok)throw new Error("private-execution-root-setup-denied");await xe(s,Ve.value,Ce)}let se;try{se=Ue("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:s,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{throw new Error("private-execution-execution-branch-mismatch")}if(se!==Ee.executionBranch)throw new Error("private-execution-execution-branch-mismatch");const $=Kt(s,{required:!0}),P=typeof Ee.epicId=="string"?$.epics[Ee.epicId]:void 0,w=h(P?.branch_lease)?P.branch_lease:void 0;if(!P||P.graph_revision!==Ee.graphRevision||!w||w.ownerStoryId!==Ee.storyId||typeof w.expiresAt!="string"||!Number.isFinite(Date.parse(w.expiresAt))||Date.parse(w.expiresAt)<=Date.now())throw new Error("private-execution-writer-lease-unavailable")}else if(g.data.metadata.mode==="step"&&(g.data.metadata.resolvedTrigger==="research"||g.data.metadata.resolvedTrigger==="write-spec"||g.data.metadata.resolvedTrigger==="create-tasks"||g.data.metadata.resolvedTrigger==="implement")||g.data.metadata.mode==="pipeline"&&g.data.metadata.resolvedTrigger==="exec"||oe&&g.data.metadata.resolvedTrigger==="create-epic"||ye||te||ee||j||je||ve||Re||et||tt){if(!ue&&!ee&&!j&&!je&&!ye&&!ve&&!Re&&!et&&!tt&&typeof g.data.metadata.storyId!="string")throw new Error("private-execution-descriptor-unavailable")}else throw new Error("private-execution-descriptor-unavailable");if(Y){const{ensurePrivateYoloIsolatedSession:se,reconcilePrivateYoloIsolatedSession:$}=await import("../private-execution/isolated-session.js");if(dt?.action==="checkpoint-epic-story")await $(s,xt,Ee.graphRevision);else{const P=await se(s,xt,Ee.graphRevision,e.privateExecutionWorkspaceParent),w=await m(P.workspace.workspacePath);if(w.hostVersion!==Z.hostVersion)throw new Error("private-codex-version-drift");Z=w}}if(Date.now()-Z.observedAtMs>2e4){const se=await m(Z.projectRoot);if(se.hostVersion!==Z.hostVersion)throw new Error("private-codex-version-drift");Z=se}const $n=await U.client.getToken();if(!$n)throw new Error("private-execution-auth-unavailable");const be=ue?g.data.metadata.epicClaim:void 0;if(ue&&(!be||typeof be.claimId!="string"||typeof be.epicId!="string"))throw new Error("private-execution-descriptor-unavailable");if(ue){if(!De)throw new Error("private-execution-epic-claim-admission-unverified");p.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Er(s,De.fingerprint,be.claimId,be.epicId),()=>{}),Tt=!0;const{preparePrivateYoloIsolatedWorkspace:se,PRIVATE_EPIC_PENDING_SIDECAR:$}=await import("../private-execution/isolated-workspace.js"),P=e.privateExecutionWorkspaceParent??Q(Lt(),".local","share","neocortex","private-epic-workspaces");e.privateExecutionWorkspaceParent||Ot(P,{recursive:!0,mode:448}),st=se(s,P,!0),dn=Ge("sha256").update(ke(Q(s,$))).digest("hex");const w=await m(st.workspacePath);if(w.hostVersion!==Z.hostVersion)throw new Error("private-codex-version-drift");Z=w}else if(!Y&&!ye){const{preparePrivateYoloIsolatedWorkspace:se}=await import("../private-execution/isolated-workspace.js"),$=e.privateExecutionWorkspaceParent??Q(Lt(),".local","share","neocortex","private-step-workspaces");if(e.privateExecutionWorkspaceParent||Ot($,{recursive:!0,mode:448}),ce=se(s,$),je||ve||Re||et||tt){if(!N)throw new Error("private-execution-project-snapshot-unverified");const{assertPrivateProjectStepBaseline:w}=await import("../private-execution/isolated-workspace.js");w(ce,N)}const P=await m(ce.workspacePath);if(P.hostVersion!==Z.hostVersion)throw new Error("private-codex-version-drift");Z=P}const nt=await c(g.data.metadata.privateExecution,{projectId:He,commandId:Y?"yolo":oe?"create-epic":ve?O:Re?"generate-pacts":et?"arch-ux-design":tt?"property-test":je?sn:g.data.metadata.mode==="pipeline"?"exec":g.data.metadata.resolvedTrigger,stepId:g.data.metadata.stepId,...Y?{graphRevision:Ee.graphRevision}:{...ue?{claimId:be.claimId,epicId:be.epicId,...te?{writeSetId:"idea-diagnosis-v1"}:{}}:ee?{claimId:le.claimId,epicId:le.epicId,diagnosisReceiptId:le.diagnosisReceiptId,intakeRevision:le.intakeRevision,physicalAcceptanceReceiptId:le.physicalAcceptanceReceiptId,writeSetId:"idea-research-v1"}:j?{claimId:re.claimId,epicId:re.epicId,diagnosisReceiptId:re.diagnosisReceiptId,researchReceiptId:re.researchReceiptId,intakeRevision:re.intakeRevision,physicalAcceptanceReceiptId:re.physicalAcceptanceReceiptId,writeSetId:"generate-epic-v1"}:je?{writeSetId:Vn}:ye?{format:o.selection.uiUxReview?.json===!0?"json":"markdown"}:ve?{targetEpicId:$t,graphRevision:Bt,writeSetId:O==="arch-prd"?"arch-prd-docs-v1":O==="update-memory"?"arch-memory-canonical-v1":O==="arch-review"?"arch-review-doc-v1":O==="arch-infrastructure"?"arch-infrastructure-doc-v1":O==="arch-testing"?"arch-testing-doc-v1":O==="arch-performance"?"arch-performance-doc-v1":O==="arch-design-system"?"arch-design-system-doc-v1":O==="arch-security"?"arch-security-doc-v1":O==="arch-database"?"arch-database-doc-v1":O==="arch-api-integrations"?"arch-api-integrations-doc-v1":O==="arch-api-contracts"?"arch-api-contracts-docs-v1":O==="arch-fitness-functions"?"arch-fitness-tools-v1":"arch-architecture-doc-v1"}:Re?{targetEpicId:pe.targetEpicId,graphRevision:pe.graphRevision,answersSha256:pe.answersSha256,specSha256:pe.specSha256,pathsSha256:pe.pathsSha256,endpointCount:pe.endpointCount,pathCount:pe.pathCount}:et?{targetEpicId:ae.targetEpicId,graphRevision:ae.graphRevision,adapterId:ae.adapterId,authoritySha256:ae.authoritySha256,pathsSha256:ae.pathsSha256,screenCount:ae.screenCount,pathCount:ae.pathCount}:tt?{prdPath:he.prdPath,prdSha256:he.prdSha256,planSha256:he.planSha256,pathsSha256:he.pathsSha256,aggregateCount:he.aggregateCount,invariantCount:he.invariantCount,pathCount:he.pathCount,language:he.language,numRuns:he.numRuns}:{storyId:g.data.metadata.storyId},stateSnapshotSha256:d(L)},inputSha256:n.sha256,hostKind:"codex-cli",hostVersion:Z.hostVersion},se=>Fo(v,{...se},$n));if(ye){const{parsePrivateExecutionDescriptor:se}=await import("../private-execution/delivery.js"),$=se(g.data.metadata.privateExecution);if($.schemaVersion!==11||$.binding.commandId!=="ui-ux-review"||$.binding.format!==(o.selection.uiUxReview?.json===!0?"json":"markdown"))throw new Error("private-execution-report-binding-unverified");const{storePrivateUiUxReviewReport:P}=await import("../private-execution/private-report-store.js");K={schemaVersion:1,outcome:"report-stored",report:await P({projectRoot:s,material:nt,format:$.binding.format,sha256:$.materialSha256}),publicSafe:!0}}else if(dt?.action==="checkpoint-epic-story"){const{runPrivateYoloRootCheckpoint:se}=await import("../private-execution/root-checkpoint.js");K={...await se(s,dt)}}else{const se=te?`${nt}
|
|
91
|
+
`)}}let K,Ot=!1;if(e.privateExecutionBeta)try{if(!Q||!g.data.metadata?.privateExecution||!Me||g.data.metadata?.mode!=="yolo"&&g.data.metadata?.mode!=="step"&&g.data.metadata?.mode!=="pipeline"&&g.data.metadata?.mode!=="create-epic"&&g.data.metadata?.mode!=="utility"&&g.data.metadata?.mode!=="tech-debt"&&g.data.metadata?.mode!=="ui-ux-review"||typeof g.data.metadata.stepId!="string")throw new Error("private-execution-descriptor-unavailable");const{consumePrivateExecutionDelivery:c,privateExecutionStateSnapshotSha256:d}=await import("../private-execution/delivery.js"),{preflightPrivateCodexExecutor:m,runPrivateCodexStep:x}=await import("../private-execution/codex-executor.js"),Y=g.data.metadata.mode==="yolo",Ee=g.data.metadata.mode==="ui-ux-review"&&g.data.metadata.resolvedTrigger==="ui-ux-review",oe=g.data.metadata.mode==="create-epic",te=g.data.metadata.mode==="step"&&g.data.metadata.resolvedTrigger==="idea-diagnose",ee=g.data.metadata.mode==="step"&&g.data.metadata.resolvedTrigger==="idea-research",M=g.data.metadata.mode==="step"&&g.data.metadata.resolvedTrigger==="generate-epic",ue=oe||te;if(ee&&!he||M&&!re)throw new Error("private-execution-planning-predecessor-unavailable");const De=g.data.metadata.mode==="utility"&&g.data.metadata.resolvedTrigger==="sync-openapi"||g.data.metadata.mode==="utility"&&g.data.metadata.resolvedTrigger==="chaos-plan"||f&&g.data.metadata.mode==="tech-debt"&&g.data.metadata.resolvedTrigger==="tech-debt",O=g.data.metadata.mode==="step"&&(g.data.metadata.resolvedTrigger==="arch-prd"||g.data.metadata.resolvedTrigger==="arch-architecture"||g.data.metadata.resolvedTrigger==="arch-fitness-functions"||g.data.metadata.resolvedTrigger==="arch-api-contracts"||g.data.metadata.resolvedTrigger==="arch-api-integrations"||g.data.metadata.resolvedTrigger==="arch-database"||g.data.metadata.resolvedTrigger==="arch-security"||g.data.metadata.resolvedTrigger==="arch-design-system"||g.data.metadata.resolvedTrigger==="arch-performance"||g.data.metadata.resolvedTrigger==="arch-testing"||g.data.metadata.resolvedTrigger==="arch-infrastructure"||g.data.metadata.resolvedTrigger==="arch-review"||g.data.metadata.resolvedTrigger==="update-memory")?g.data.metadata.resolvedTrigger:void 0,ve=O!==void 0,Re=g.data.metadata.mode==="step"&&g.data.metadata.resolvedTrigger==="generate-pacts",et=g.data.metadata.mode==="step"&&g.data.metadata.resolvedTrigger==="arch-ux-design",tt=g.data.metadata.mode==="utility"&&g.data.metadata.resolvedTrigger==="property-test",un=f?"tech-debt":g.data.metadata.resolvedTrigger==="chaos-plan"?"chaos-plan":"sync-openapi",Bn=f?"tech-debt-registry-v1":un==="chaos-plan"?"chaos-quarterly-v1":"sync-openapi-contract-v1",Le=L.archPlan?.execution,Gt=Le?.targetEpicId,qt=Le?.graphRevision;if(ve&&(Le?.currentStageCommand!==O||typeof Gt!="string"||!/^P[1-9][0-9]{0,11}$/.test(Gt)||typeof qt!="string"||!/^[a-f0-9]{64}$/.test(qt)))throw new Error("private-execution-architecture-admission-unverified");if(Re&&(!pe||!ye||!b||Le?.currentStageCommand!=="generate-pacts"||Le.continuationState!=="delegate"||Le.targetEpicId!==pe.targetEpicId||Le.graphRevision!==pe.graphRevision||!E(Le.pactAnswerReceipt,b.receipt)))throw new Error("private-execution-pact-admission-unverified");if(et&&(!ae||!de||Le?.currentStageCommand!=="arch-ux-design"||Le.continuationState!=="delegate"||Le.targetEpicId!==ae.targetEpicId||Le.graphRevision!==ae.graphRevision))throw new Error("private-execution-ux-admission-unverified");if(tt&&(!ge||!Et||!We||g.data.metadata.stepId!=="step-a8ce5c64"))throw new Error("private-execution-property-admission-unverified");let Hn;if(Re){const{planPactToolchainManifest:se,preparePactToolchainCandidate:q}=await import("../private-execution/pact-toolchain.js");try{se(s,b.answers.generateProvider),Hn=q(s,b.answers.generateProvider)}catch(P){if(P.message!=="pact-toolchain-manifest-unsupported")throw P}}let dt,ce,ln;const le=g.data.metadata.gitLifecycleGraphAuthority,pt=g.data.metadata.privateExecutionRootAction;let Nt;if(Y){if(!le||typeof le.storyId!="string"||typeof le.graphRevision!="string"||typeof le.executionBranch!="string")throw new Error("private-execution-graph-unavailable");if(Nt=le.storyId,pt?.action==="prepare-epic-checkout"){const{parsePrivateExecutionDescriptor:be}=await import("../private-execution/delivery.js"),{prepareDirectYoloSetup:Ct}=await import("../git/direct-yolo-checkpoint.js"),{acceptDirectYoloSetupCheckpoint:Ve}=await import("../git/direct-yolo-checkpoint.js"),{capturePrivateYoloCleanHead:Ue,recordPrivateYoloCleanBaseline:$e}=await import("../private-execution/clean-baseline.js"),ut=be(g.data.metadata.privateExecution,{projectId:Me,commandId:"yolo",stepId:g.data.metadata.stepId,graphRevision:le.graphRevision,inputSha256:n.sha256,hostKind:"codex-cli",hostVersion:Q.hostVersion}),lt=await j.client.getToken();if(!lt)throw new Error("private-execution-auth-unavailable");if(!await Yo(v,{leaseId:ut.leaseId,...ut.binding},lt))throw new Error("private-execution-setup-lease-cancel-unverified");const hn=Ue(s),rt=await Ct({projectRoot:s,storyId:pt.storyId});if(!rt.ok)throw new Error("private-execution-root-setup-denied");await $e(s,rt.value,hn);const{ensurePrivateYoloIsolatedSession:Dt}=await import("../private-execution/isolated-session.js");await Dt(s,pt.storyId,le.graphRevision,e.privateExecutionWorkspaceParent);const Lt=await Ve({projectRoot:s,storyId:pt.storyId});if(!Lt.ok)throw new Error(`private-execution-root-setup-checkpoint-denied:${Lt.reasonCode}`);K={schemaVersion:1,outcome:"setup-accepted",executorOutcome:"not-run-root-only",setup:Lt.value,publicSafe:!0};const gn=tn(g.data.instructions,g.data.metadata);return p.complete(Pt),{success:!0,instructions:`# Setup do branch validado
|
|
92
|
+
|
|
93
|
+
O root confirmou o checkpoint C01 no branch do \xE9pico. Reexecute o mesmo YOLO para avan\xE7ar \xE0 pr\xF3xima etapa.`,metadata:{...gn.metadata,privateExecutionReceipt:K},exitCode:0}}let se;try{se=je("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:s,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{throw new Error("private-execution-execution-branch-mismatch")}if(se!==le.executionBranch)throw new Error("private-execution-execution-branch-mismatch");const q=Xt(s,{required:!0}),P=typeof le.epicId=="string"?q.epics[le.epicId]:void 0,w=h(P?.branch_lease)?P.branch_lease:void 0;if(!P||P.graph_revision!==le.graphRevision||!w||w.ownerStoryId!==le.storyId||typeof w.expiresAt!="string"||!Number.isFinite(Date.parse(w.expiresAt))||Date.parse(w.expiresAt)<=Date.now())throw new Error("private-execution-writer-lease-unavailable")}else if(g.data.metadata.mode==="step"&&(g.data.metadata.resolvedTrigger==="research"||g.data.metadata.resolvedTrigger==="write-spec"||g.data.metadata.resolvedTrigger==="create-tasks"||g.data.metadata.resolvedTrigger==="implement")||g.data.metadata.mode==="pipeline"&&g.data.metadata.resolvedTrigger==="exec"||oe&&g.data.metadata.resolvedTrigger==="create-epic"||Ee||te||ee||M||De||ve||Re||et||tt){if(!ue&&!ee&&!M&&!De&&!Ee&&!ve&&!Re&&!et&&!tt&&typeof g.data.metadata.storyId!="string")throw new Error("private-execution-descriptor-unavailable")}else throw new Error("private-execution-descriptor-unavailable");if(Y){const{ensurePrivateYoloIsolatedSession:se,reconcilePrivateYoloIsolatedSession:q}=await import("../private-execution/isolated-session.js");if(pt?.action==="checkpoint-epic-story")await q(s,Nt,le.graphRevision);else{const P=await se(s,Nt,le.graphRevision,e.privateExecutionWorkspaceParent),w=await m(P.workspace.workspacePath);if(w.hostVersion!==Q.hostVersion)throw new Error("private-codex-version-drift");Q=w}}if(Date.now()-Q.observedAtMs>2e4){const se=await m(Q.projectRoot);if(se.hostVersion!==Q.hostVersion)throw new Error("private-codex-version-drift");Q=se}const Wn=await j.client.getToken();if(!Wn)throw new Error("private-execution-auth-unavailable");const Ae=ue?g.data.metadata.epicClaim:void 0;if(ue&&(!Ae||typeof Ae.claimId!="string"||typeof Ae.epicId!="string"))throw new Error("private-execution-descriptor-unavailable");if(ue){if(!Oe)throw new Error("private-execution-epic-claim-admission-unverified");p.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>vr(s,Oe.fingerprint,Ae.claimId,Ae.epicId),()=>{}),Ot=!0;const{preparePrivateYoloIsolatedWorkspace:se,PRIVATE_EPIC_PENDING_SIDECAR:q}=await import("../private-execution/isolated-workspace.js"),P=e.privateExecutionWorkspaceParent??X($t(),".local","share","neocortex","private-epic-workspaces");e.privateExecutionWorkspaceParent||Mt(P,{recursive:!0,mode:448}),dt=se(s,P,!0),ln=Ge("sha256").update(Te(X(s,q))).digest("hex");const w=await m(dt.workspacePath);if(w.hostVersion!==Q.hostVersion)throw new Error("private-codex-version-drift");Q=w}else if(!Y&&!Ee){const{preparePrivateYoloIsolatedWorkspace:se}=await import("../private-execution/isolated-workspace.js"),q=e.privateExecutionWorkspaceParent??X($t(),".local","share","neocortex","private-step-workspaces");if(e.privateExecutionWorkspaceParent||Mt(q,{recursive:!0,mode:448}),ce=se(s,q),De||ve||Re||et||tt){if(!N)throw new Error("private-execution-project-snapshot-unverified");const{assertPrivateProjectStepBaseline:w}=await import("../private-execution/isolated-workspace.js");w(ce,N)}const P=await m(ce.workspacePath);if(P.hostVersion!==Q.hostVersion)throw new Error("private-codex-version-drift");Q=P}const nt=await c(g.data.metadata.privateExecution,{projectId:Me,commandId:Y?"yolo":oe?"create-epic":ve?O:Re?"generate-pacts":et?"arch-ux-design":tt?"property-test":De?un:g.data.metadata.mode==="pipeline"?"exec":g.data.metadata.resolvedTrigger,stepId:g.data.metadata.stepId,...Y?{graphRevision:le.graphRevision}:{...ue?{claimId:Ae.claimId,epicId:Ae.epicId,...te?{writeSetId:"idea-diagnosis-v1"}:{}}:ee?{claimId:he.claimId,epicId:he.epicId,diagnosisReceiptId:he.diagnosisReceiptId,intakeRevision:he.intakeRevision,physicalAcceptanceReceiptId:he.physicalAcceptanceReceiptId,writeSetId:"idea-research-v1"}:M?{claimId:re.claimId,epicId:re.epicId,diagnosisReceiptId:re.diagnosisReceiptId,researchReceiptId:re.researchReceiptId,intakeRevision:re.intakeRevision,physicalAcceptanceReceiptId:re.physicalAcceptanceReceiptId,writeSetId:"generate-epic-v1"}:De?{writeSetId:Bn}:Ee?{format:o.selection.uiUxReview?.json===!0?"json":"markdown"}:ve?{targetEpicId:Gt,graphRevision:qt,writeSetId:O==="arch-prd"?"arch-prd-docs-v1":O==="update-memory"?"arch-memory-canonical-v1":O==="arch-review"?"arch-review-doc-v1":O==="arch-infrastructure"?"arch-infrastructure-doc-v1":O==="arch-testing"?"arch-testing-doc-v1":O==="arch-performance"?"arch-performance-doc-v1":O==="arch-design-system"?"arch-design-system-doc-v1":O==="arch-security"?"arch-security-doc-v1":O==="arch-database"?"arch-database-doc-v1":O==="arch-api-integrations"?"arch-api-integrations-doc-v1":O==="arch-api-contracts"?"arch-api-contracts-docs-v1":O==="arch-fitness-functions"?"arch-fitness-tools-v1":"arch-architecture-doc-v1"}:Re?{targetEpicId:pe.targetEpicId,graphRevision:pe.graphRevision,answersSha256:pe.answersSha256,specSha256:pe.specSha256,pathsSha256:pe.pathsSha256,endpointCount:pe.endpointCount,pathCount:pe.pathCount}:et?{targetEpicId:ae.targetEpicId,graphRevision:ae.graphRevision,adapterId:ae.adapterId,authoritySha256:ae.authoritySha256,pathsSha256:ae.pathsSha256,screenCount:ae.screenCount,pathCount:ae.pathCount}:tt?{prdPath:ge.prdPath,prdSha256:ge.prdSha256,planSha256:ge.planSha256,pathsSha256:ge.pathsSha256,aggregateCount:ge.aggregateCount,invariantCount:ge.invariantCount,pathCount:ge.pathCount,language:ge.language,numRuns:ge.numRuns}:{storyId:g.data.metadata.storyId},stateSnapshotSha256:d(L)},inputSha256:n.sha256,hostKind:"codex-cli",hostVersion:Q.hostVersion},se=>Fo(v,{...se},Wn));if(Ee){const{parsePrivateExecutionDescriptor:se}=await import("../private-execution/delivery.js"),q=se(g.data.metadata.privateExecution);if(q.schemaVersion!==11||q.binding.commandId!=="ui-ux-review"||q.binding.format!==(o.selection.uiUxReview?.json===!0?"json":"markdown"))throw new Error("private-execution-report-binding-unverified");const{storePrivateUiUxReviewReport:P}=await import("../private-execution/private-report-store.js");K={schemaVersion:1,outcome:"report-stored",report:await P({projectRoot:s,material:nt,format:q.binding.format,sha256:q.materialSha256}),publicSafe:!0}}else if(pt?.action==="checkpoint-epic-story"){const{runPrivateYoloRootCheckpoint:se}=await import("../private-execution/root-checkpoint.js");K={...await se(s,pt)}}else{const se=te?`${nt}
|
|
92
94
|
|
|
93
95
|
Private P01 handoff (local only):
|
|
94
|
-
The durable reserved epic ID is ${
|
|
96
|
+
The durable reserved epic ID is ${Ae.epicId}. Complete only the diagnosis for this exact ID. Write exactly .neocortex/planning/epic-${Ae.epicId}/idea.json, diagnosis.md, enriched-prompt.md and the matching entry in .neocortex/planning/planning.json. Do not write state.json, Git controls, another epic, or P02/P03 artifacts; do not auto-continue to the next step. The root will independently review and persist the accepted planning checkpoint.
|
|
95
97
|
`:ee?`${nt}
|
|
96
98
|
|
|
97
99
|
Private P02 handoff (local only):
|
|
98
|
-
The admitted epic is ${
|
|
99
|
-
`:
|
|
100
|
+
The admitted epic is ${he.epicId}. Research only this exact diagnosed epic. Write exactly .neocortex/planning/epic-${he.epicId}/research.md and its transition in .neocortex/planning/planning.json. Do not write state.json, Git controls, another epic, or P03 artifacts; do not auto-continue. The root will independently review and seal the research candidate.
|
|
101
|
+
`:M?`${nt}
|
|
100
102
|
|
|
101
103
|
Private P03 handoff (local only):
|
|
102
104
|
The admitted epic is ${re.epicId}. Generate exactly docs/epics/epic-${re.epicId}.md, 1 to 24 contiguous docs/stories/${re.epicId}.NN.story.md files (01 through 24), and the matching transition in .neocortex/planning/planning.json. Do not write state.json, Git controls, another epic, or subsequent-stage artifacts; do not auto-continue. The root will independently review and seal the generated candidate.
|
|
103
105
|
`:Re?`${nt}
|
|
104
106
|
|
|
105
107
|
Private A03.5 handoff (local only):
|
|
106
|
-
${JSON.stringify({consumer:b.answers.consumer,provider:b.answers.provider,matchersAggressive:b.answers.matchersAggressive,generateProvider:b.answers.generateProvider,brokerConfigured:b.answers.brokerUrl!==null,allowedPaths:
|
|
108
|
+
${JSON.stringify({consumer:b.answers.consumer,provider:b.answers.provider,matchersAggressive:b.answers.matchersAggressive,generateProvider:b.answers.generateProvider,brokerConfigured:b.answers.brokerUrl!==null,allowedPaths:ye.paths})}
|
|
107
109
|
Read docs/api/openapi.yaml. Write only the listed new test files. Do not write package files, CI, Git, graph, or tracked configuration. Never embed a broker URL; provider verification must read PACT_BROKER_URL at runtime.
|
|
108
110
|
`:et?`${nt}
|
|
109
111
|
|
|
@@ -115,15 +117,15 @@ Write only the approved paths. Keep synthetic fixtures and the canonical approve
|
|
|
115
117
|
Private property-test handoff (local only):
|
|
116
118
|
${JSON.stringify({language:We.language,numRuns:We.numRuns,aggregates:We.aggregates.map(P=>({name:P.name,implementationFile:P.implementationFile,testFile:P.testFile,invariantCount:P.invariantCount}))})}
|
|
117
119
|
Read the PRD and implementation files inside this isolated clone. Write exactly the listed test files. Do not edit the PRD, state, Git, QA records or any other path. Scaffolds with unfinished assertions must fail explicitly; do not use skipped or todo tests. The root will write the confirmed PRD configuration and independently assess QA.
|
|
118
|
-
`:nt
|
|
120
|
+
`:nt,q=await x(se,Q,{requireWorkspaceEffect:!0,...Y?{expectedExecutionBranch:le.executionBranch}:dt?{expectedExecutionBranch:dt.executionBranch}:ce?{expectedExecutionBranch:ce.executionBranch}:{}});if(Y){const{admitPrivateYoloIsolatedSessionStep:P}=await import("../private-execution/isolated-session.js"),w=await P(s,Nt,le.graphRevision);let be;if(g.data.metadata.stepId===la){const Ve=g.data.metadata.mutationQaFeature;if(!Ve)throw new Error("private-execution-mutation-qa-authority-unavailable");if(!Ve.enabled)be={schemaVersion:1,status:"skipped-server-authority",publicSafe:!0};else{let Ue,$e;try{const ut=w.session.workspace.workspacePath,lt=`sha:${w.session.workspace.baseSha}`,{planMutationQa:hn}=await import("./mutation-qa.js"),rt=hn(ut,lt);if(rt.headSha!==w.session.snapshotSha)throw new Error("private-execution-mutation-qa-snapshot-drift");let Dt="not-run";if(rt.outcome==="ready"){const{runAndRecordMutationQa:fn}=await import("./mutation-qa-checkpoint.js");if(Dt=fn(ut,lt,rt.planSha256).result.outcome,Dt==="skipped-host-isolation-unavailable")throw new Error("private-execution-mutation-qa-host-isolation-unavailable")}const{classifyMutationQaGate:Lt}=await import("./mutation-qa-gate.js");if(Ue=Lt(ut,lt,rt.planSha256),Ue.followUpDebtRequired){const{recordMutationQaFollowUpDebt:fn}=await import("./mutation-qa-checkpoint.js");$e=fn(ut,lt,rt.planSha256,Ue.status,Dt,s)}const{resumePrivateYoloIsolatedSession:gn}=await import("../private-execution/isolated-session.js");if((await gn(s,Nt,le.graphRevision)).snapshotSha!==w.session.snapshotSha)throw new Error("private-execution-mutation-qa-snapshot-drift")}catch{throw new Error("private-execution-mutation-qa-unverified")}if(Ue.blocksLocalQa||!Ue.safeToContinueLocalQa&&!$e)throw new Error(`private-execution-mutation-qa-${Ue.status}`);be={...Ue,...$e?{followUpDebt:{status:"recorded",owner:$e.owner,severity:$e.severity,reasonCode:$e.reasonCode,planSha256:$e.planSha256,publicSafe:!0}}:{}}}}const Ct={schemaVersion:1,outcome:w.admission.outcome,sequence:w.session.sequence,snapshotSha:w.session.snapshotSha,patchSha256:w.admission.patchSha256,changedPathCount:w.admission.changedPaths.length};K={...q,isolation:Ct,...be?{mutationQa:be}:{}}}else if(dt){const{admitPrivateEpicClaimWorkspace:P,admitPrivateIdeaDiagnosisWorkspace:w}=await import("../private-execution/isolated-admission.js"),be=te?w(dt,Ae.claimId,Ae.epicId,Oe.fingerprint,ln,o.selection.positionals.join(" ").replace(/^[-:–—]\s+/,"")):P(dt,Ae.claimId,Ae.epicId,Oe.fingerprint,ln);K={...q,isolation:{schemaVersion:1,outcome:be.outcome,baseSha:be.baseSha,patchSha256:be.patchSha256,changedPathCount:be.changedPaths.length}}}else if(ce&&ee){const{admitPrivateIdeaResearchWorkspace:P}=await import("../private-execution/isolated-admission.js"),w=P(ce,he.claimId,he.epicId,he.diagnosisReceiptId,he.intakeRevision,he.sourceStateSha256);K={...q,isolation:{schemaVersion:1,outcome:w.outcome,baseSha:w.baseSha,patchSha256:w.patchSha256,changedPathCount:w.changedPaths.length}}}else if(ce&&M){const{admitPrivateGenerateEpicWorkspace:P}=await import("../private-execution/isolated-admission.js"),w=P(ce,re.claimId,re.epicId,re.diagnosisReceiptId,re.researchReceiptId,re.intakeRevision,re.sourceStateSha256);K={...q,isolation:{schemaVersion:1,outcome:w.outcome,baseSha:w.baseSha,patchSha256:w.patchSha256,changedPathCount:w.changedPaths.length}}}else if(ce&&Re){const{admitPrivatePactWorkspace:P}=await import("../private-execution/isolated-admission.js"),{inspectPactToolchain:w}=await import("../private-execution/pact-toolchain.js"),{verifyPactConsumerRuntime:be}=await import("../private-execution/pact-consumer-runtime.js"),Ct=b.answers.generateProvider,Ve=P(ce,pe.targetEpicId,pe.graphRevision,b.receipt,ye,Hn),Ue=w(s,Ct),$e=be(s,ye,Ct);K={...q,isolation:{schemaVersion:1,outcome:Ve.outcome,baseSha:Ve.baseSha,patchSha256:Ve.patchSha256,changedPathCount:Ve.changedPaths.length,consumerBindingCandidateCount:Ve.consumerBindingCandidateCount,consumerScaffoldCount:Ve.consumerScaffoldCount,toolchain:Ue,consumerRuntime:$e}}}else if(ce&&et){const{admitPrivateUxWorkspace:P}=await import("../private-execution/isolated-admission.js"),w=P(ce,ae.targetEpicId,ae.graphRevision,de);K={...q,isolation:{schemaVersion:1,outcome:w.outcome,baseSha:w.baseSha,patchSha256:w.patchSha256,changedPathCount:w.changedPaths.length}}}else if(ce&&tt){const{admitPrivatePropertyTestWorkspace:P}=await import("../private-execution/isolated-admission.js"),w=P(ce,Et,We);K={...q,isolation:{schemaVersion:1,outcome:w.outcome,baseSha:w.baseSha,patchSha256:w.patchSha256,changedPathCount:w.changedPaths.length,checkpointAccepted:!1,qaAccepted:!1,rootNextAction:"property-semantic-review-required"}}}else if(ce&&ve){const{admitPrivateArchitectureStageWorkspace:P}=await import("../private-execution/isolated-admission.js"),w=P(ce,O,O==="arch-prd"?"arch-prd-docs-v1":O==="update-memory"?"arch-memory-canonical-v1":O==="arch-review"?"arch-review-doc-v1":O==="arch-infrastructure"?"arch-infrastructure-doc-v1":O==="arch-testing"?"arch-testing-doc-v1":O==="arch-performance"?"arch-performance-doc-v1":O==="arch-design-system"?"arch-design-system-doc-v1":O==="arch-security"?"arch-security-doc-v1":O==="arch-database"?"arch-database-doc-v1":O==="arch-api-integrations"?"arch-api-integrations-doc-v1":O==="arch-api-contracts"?"arch-api-contracts-docs-v1":O==="arch-fitness-functions"?"arch-fitness-tools-v1":"arch-architecture-doc-v1",Gt,qt);K={...q,isolation:{schemaVersion:1,outcome:w.outcome,baseSha:w.baseSha,patchSha256:w.patchSha256,changedPathCount:w.changedPaths.length}}}else if(ce&&De){const{admitPrivateProjectStepWorkspace:P}=await import("../private-execution/isolated-admission.js"),w=P(ce,un,Bn);K={...q,isolation:{schemaVersion:1,outcome:w.outcome,baseSha:w.baseSha,patchSha256:w.patchSha256,changedPathCount:w.changedPaths.length}}}else if(ce){const{admitPrivateStateBoundStepWorkspace:P}=await import("../private-execution/isolated-admission.js"),w=P(ce,g.data.metadata.storyId);K={...q,isolation:{schemaVersion:1,outcome:w.outcome,baseSha:w.baseSha,patchSha256:w.patchSha256,changedPathCount:w.changedPaths.length}}}else K={...q}}}catch(c){const d=c instanceof Error&&/^(private-execution|private-codex)-[a-z-]+$/.test(c.message)?c.message:"private-execution-unverified";return{success:!1,error:d,errorCode:d,exitCode:1}}const It=tn(g.data.instructions,g.data.metadata),vt=K?.isolation,aa=It.metadata?.resolvedTrigger==="property-test"&&vt!==null&&typeof vt=="object"&&!Array.isArray(vt)&&vt.outcome==="admitted-unverified"&&vt.checkpointAccepted===!1&&vt.rootNextAction==="property-semantic-review-required";if(Oe&&!Ot&&g.data.metadata?.mode!=="error")try{const c=g.data.metadata?.epicClaim;if(!c||typeof c!="object"||Array.isArray(c))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const d=c;if(d.outcome!=="reserved"||typeof d.claimId!="string"||typeof d.epicId!="string")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");p.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>vr(s,Oe.fingerprint,d.claimId,d.epicId),()=>{})}catch{}return p.complete(Pt),{success:!0,instructions:K?K.outcome==="checkpoint-validated"?`# Checkpoint da story validado
|
|
119
121
|
|
|
120
122
|
O root registrou o commit e a valida\xE7\xE3o f\xEDsica no branch do epic.`:K.outcome==="setup-accepted"?`# Setup do branch validado
|
|
121
123
|
|
|
122
124
|
O root confirmou o checkpoint C01 no branch do \xE9pico. Reexecute o mesmo YOLO para avan\xE7ar \xE0 pr\xF3xima etapa.`:K.outcome==="report-stored"?`# Relat\xF3rio privado salvo
|
|
123
125
|
|
|
124
|
-
Consulte o caminho local em metadata.privateExecutionReceipt.report.path. Nenhum agente foi executado ou projeto alterado.`:
|
|
126
|
+
Consulte o caminho local em metadata.privateExecutionReceipt.report.path. Nenhum agente foi executado ou projeto alterado.`:aa?"# Property-test: candidato admitido, QA pendente\n\nO root deve inspecionar os arquivos locais, executar `neocortex-client property-qa review-plan --project-root . --format json` e comparar cada invariante do PRD com a implementa\xE7\xE3o e sua asser\xE7\xE3o. Somente uma revis\xE3o root independente, registrada fora do projeto e enviada por stdin a `property-qa review-accept --authorize-review`, pode autorizar o aceite; esse comando repete a execu\xE7\xE3o positiva e a falha causal no sandbox. Consulte `property-qa review-status` para revalidar o recibo. Se o toolchain ou a evid\xEAncia n\xE3o forem suportados, pare sem declarar QA aprovado. O agente privado n\xE3o recebe autoridade de revis\xE3o, Git ou checkpoint.":`# Execu\xE7\xE3o privada conclu\xEDda; valida\xE7\xE3o f\xEDsica pendente
|
|
125
127
|
|
|
126
|
-
O executor Codex retornou sem erro. Nenhum checkpoint ou aprova\xE7\xE3o da story foi emitido.`:
|
|
128
|
+
O executor Codex retornou sem erro. Nenhum checkpoint ou aprova\xE7\xE3o da story foi emitido.`:It.instructions,metadata:K?{...It.metadata,privateExecutionReceipt:K}:It.metadata,exitCode:0}}function Xo(e){const[t]=e.trim().split(/\s+/,1);return t?/^@?epic-[a-z0-9][a-z0-9._-]*$/i.test(t)?"epic":Sn(t):null}const na="Provide exactly one invoke input source: --args <string>, --stdin, or --args-file <path>.",Zo=`
|
|
127
129
|
neocortex-client invoke - Send orchestration request to server
|
|
128
130
|
|
|
129
131
|
Usage:
|
|
@@ -193,12 +195,12 @@ Safety:
|
|
|
193
195
|
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.
|
|
194
196
|
Jobs, goal and loop watch use serverHeldStream=false and foreground local SQLite polling of public processing summaries only.
|
|
195
197
|
Unresolved targets disable polling with public reason codes; there is no all-jobs fallback.
|
|
196
|
-
`.trim();function
|
|
198
|
+
`.trim();function ec(e){return e.includes("--help")||e.includes("-h")||e.includes("help")}function Pe(e,t,a,r){return new nn("INVOCATION_MALFORMED_INPUT",t,e,a,r)}function kt(e){return Pe("missing-input-value",`${e} requires a value. ${na}`)}function tc(e){try{if(!sa(e).isFile())throw Pe("missing-input-value","--args-file must point to a readable UTF-8 text file.","args-file");return Te(e)}catch(t){throw t instanceof nn?t:Pe("missing-input-value","--args-file could not be read as UTF-8 text. Check the path and permissions.","args-file")}}function nc(){try{if(process.stdin.isTTY)throw Pe("missing-input-value","--stdin requires piped UTF-8 text, for example: neocortex-client invoke --stdin < synthetic.story.md","stdin");return Te(0)}catch(e){throw e instanceof nn?e:Pe("missing-input-value","--stdin could not be read as UTF-8 text. Pipe command text into stdin and retry.","stdin")}}function rc(e,t={}){let a,r=!1,i,n,o="plain",s=!1,u,f,S=!1,_=!1;for(let T=0;T<e.length;T++)switch(e[T]){case"--args":{const R=e[++T];if(R===void 0)throw kt("--args");if(a!==void 0)throw Pe("multiple-input-sources","Provide --args only once. Use one explicit invoke input source.","args");a=R;break}case"--stdin":if(r)throw Pe("multiple-input-sources","Provide --stdin only once. Use one explicit invoke input source.","stdin");r=!0;break;case"--args-file":{const R=e[++T];if(R===void 0)throw kt("--args-file");if(i!==void 0)throw Pe("multiple-input-sources","Provide --args-file only once. Use one explicit invoke input source.","args-file");i=R;break}case"--project-root":{const R=e[++T];if(R===void 0)throw kt("--project-root");n=R;break}case"--format":{const R=e[++T];if(R===void 0)throw kt("--format");if(R!=="json"&&R!=="plain")throw Pe("unexpected-cli-token","--format accepts only json or plain.");o=R;break}case"--watch":s=!0;break;case"--server-url":{const R=e[++T];if(R===void 0)throw kt("--server-url");u=R;break}case"--platform-target":{const R=e[++T];if(R===void 0)throw kt("--platform-target");f=R;break}case"--strict-read-only":S=!0;break;case"--private-execution-beta":_=!0;break;default:throw Pe("unexpected-cli-token","Unexpected top-level CLI token. Quote the complete --args payload or use --stdin/--args-file for multiline content.")}const l=[a!==void 0?"args":void 0,r?"stdin":void 0,i!==void 0?"args-file":void 0].filter(T=>T!==void 0);if(l.length===0)throw Pe("missing-input-value",na);if(l.length>1)throw Pe("multiple-input-sources",`Choose only one invoke input source; received ${l.join(", ")}.`);const y=l[0],p=y==="args"?a:y==="stdin"?(t.readStdin??nc)():(t.readArgsFile??tc)(i);let I;try{I=Kt(y,p)}catch(T){throw T instanceof Ja?Pe("invalid-utf8",T.message,y):T}const C=y==="args"?Do(I.rawArgs):we(I.rawArgs),V=C.args===I.rawArgs?I:Kt(y,C.args);return{args:C.args,inputSource:y,inputEnvelope:V,projectRoot:n,format:o,watch:s||C.watch,commandLevelWatch:C.metadata,serverUrl:u,platformTarget:f,strictReadOnly:S,privateExecutionBeta:_}}function ra(e,t){return t?.active?{...e??{},commandLevelWatch:t,serverHeldStream:!1}:e}function ac(e,t,a=process.stdout,r=process.stderr){if(t.format==="json"){const o=tn(e.instructions,e.metadata),s=ra(o.metadata,t.commandLevelWatch);if(t.watch){a.write(JSON.stringify({type:"invoke_result",instructions:o.instructions,metadata:s,publicSafe:!0})+`
|
|
197
199
|
`);return}a.write(JSON.stringify({instructions:o.instructions,metadata:s})+`
|
|
198
|
-
`);return}const i=
|
|
200
|
+
`);return}const i=tn(e.instructions,e.metadata),n=ra(i.metadata,t.commandLevelWatch);a.write(i.instructions+`
|
|
199
201
|
`),n&&r.write(JSON.stringify(n)+`
|
|
200
|
-
`)}function
|
|
201
|
-
`),0;let t;try{t=
|
|
202
|
+
`)}function ic(e){const t=()=>e.abort();return process.once("SIGINT",t),process.once("SIGTERM",t),()=>{process.removeListener("SIGINT",t),process.removeListener("SIGTERM",t)}}async function Xc(e){if(ec(e))return process.stdout.write(`${Zo}
|
|
203
|
+
`),0;let t;try{t=rc(e)}catch(r){if(r instanceof nn)return process.stderr.write(JSON.stringify({error_code:r.code,reason:r.reason,source:r.source,byte_length:r.byteLength,message:r.message,remediation:r.message})+`
|
|
202
204
|
`),1;throw r}if(Na(t.args))return t.strictReadOnly?(process.stderr.write(JSON.stringify({error_code:"readonly-registry-denied",message:"Strict read-only policy is not eligible for the local jobs console."})+`
|
|
203
|
-
`),1):(await Da({args:t.args,projectRoot:
|
|
204
|
-
`),a.exitCode}if(
|
|
205
|
+
`),1):(await Da({args:t.args,projectRoot:_n(t.projectRoot),format:t.format,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})).exitCode;const a=await Qo({args:t.args,inputSource:t.inputSource,inputEnvelope:t.inputEnvelope,watch:t.watch,projectRoot:t.projectRoot,format:t.format,serverUrl:t.serverUrl,platformTarget:t.platformTarget,strictReadOnly:t.strictReadOnly,privateExecutionBeta:t.privateExecutionBeta});if(!a.success){const r=a.metadata?.invocationInput,i=r&&typeof r=="object"&&!Array.isArray(r)?r:void 0;return process.stderr.write(JSON.stringify({error_code:a.errorCode??(a.exitCode===2?"NOT_CONFIGURED":"INVOKE_ERROR"),message:Be(a.error??"",ft),...typeof i?.reason=="string"?{reason:Be(i.reason,80)}:{},...typeof i?.source=="string"?{source:Be(i.source,20)}:{},...Number.isSafeInteger(i?.byteLength)?{byte_length:i.byteLength}:{},...typeof i?.remediation=="string"?{remediation:Be(i.remediation,ft)}:{}})+`
|
|
206
|
+
`),a.exitCode}if(ac(a,t),t.watch){const r=new AbortController,i=ic(r);try{const n=qo(a.metadata,t.args);n.disabled?Co(n.reasonCodes??[fe.TARGET_UNRESOLVED],t.args,t.format,process.stdout,t.privateExecutionBeta):await wo({projectRoot:_n(t.projectRoot),format:t.format,strictReadOnly:t.strictReadOnly,protectedOutput:t.privateExecutionBeta,...n,signal:r.signal})}finally{i()}}return 0}export{Zo as INVOKE_HELP_TEXT,mr as INVOKE_PAYLOAD_LIMIT_BYTES,Cn as INVOKE_PAYLOAD_WARNING_THRESHOLD_BYTES,nn as InvokeCliInputError,An as InvokePayloadTooLargeError,bn as InvokeStructuralContextTooLargeError,ct as StateSnapshotIntegrityError,Kc as __resetSchemaDriftWarnedForTests,Jo as acknowledgeMaterializedPendingEpicClaims,Ii as admitClientInvocation,Dr as assertEpicAwareStateShapeBeforeRepair,qi as boundedP222PremergeCheckpointPositions,eo as buildSignedInvokeAttempt,Ei as clearPendingEpicIdempotencyKey,Fi as collectInvokeP205Authorities,Lr as collectStateSnapshot,Tt as computeInvokeRequestBodySizeBytes,Qc as createFullStateSnapshotScope,Nn as createInvokePayloadTelemetry,xi as detectStateSchemaDrift,Xo as extractPreFlightTrigger,yi as getOrCreatePendingEpicIdempotencyKey,Gr as guardInvokeRequestBodySize,Qo as invoke,Xc as invokeCliHandler,Nr as isEpicAwareCommandId,po as maybeEmitInvokePayloadSizeWarning,uo as maybeRunInvokeRunnerAutoBootstrap,rc as parseInvokeCliOptions,Hr as postMaterializationJson,vr as recordPendingEpicReservation,Do as resolveInvokeCommandLevelWatch,_n as resolveInvokeProjectRoot,Qi as resolveInvokeTransportErrorCode,qo as resolveInvokeWatchTarget,tn as sanitizeInvokeCliOutput,zo as sendEpicClaimAcknowledgement,ta as sendInvokeRequest,Yo as sendPrivateExecutionCancelRequest,Fo as sendPrivateExecutionConsumeRequest,Ri as shouldCollectProjectEvidenceForInvoke,wo as watchContinuityProcessingSummaries,ac as writeInvokeCliSuccessOutput};
|