@ornexus/neocortex 4.60.58 → 4.60.59
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/sbom.cdx.json +23 -23
- package/install.ps1 +1 -1
- package/install.sh +1 -1
- package/package.json +2 -2
- package/packages/client/dist/commands/invoke.js +26 -26
- package/packages/client/dist/private-execution/delivery.js +1 -1
- package/packages/client/dist/yoloop/shared-yoloop-types.d.ts +15 -1
- package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +5 -1
- package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1
- 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
package/dist/sbom.cdx.json
CHANGED
|
@@ -984,7 +984,7 @@
|
|
|
984
984
|
"version": "1.26.0"
|
|
985
985
|
},
|
|
986
986
|
{
|
|
987
|
-
"bom-ref": "@neocortex/client@4.60.
|
|
987
|
+
"bom-ref": "@neocortex/client@4.60.59",
|
|
988
988
|
"group": "@neocortex",
|
|
989
989
|
"name": "client",
|
|
990
990
|
"properties": [
|
|
@@ -993,9 +993,9 @@
|
|
|
993
993
|
"value": "node_modules/@neocortex/client"
|
|
994
994
|
}
|
|
995
995
|
],
|
|
996
|
-
"purl": "pkg:npm/%40neocortex/client@4.60.
|
|
996
|
+
"purl": "pkg:npm/%40neocortex/client@4.60.59",
|
|
997
997
|
"type": "library",
|
|
998
|
-
"version": "4.60.
|
|
998
|
+
"version": "4.60.59"
|
|
999
999
|
},
|
|
1000
1000
|
{
|
|
1001
1001
|
"bom-ref": "@neocortex/core@0.1.0",
|
|
@@ -1012,7 +1012,7 @@
|
|
|
1012
1012
|
"version": "0.1.0"
|
|
1013
1013
|
},
|
|
1014
1014
|
{
|
|
1015
|
-
"bom-ref": "@neocortex/server@4.60.
|
|
1015
|
+
"bom-ref": "@neocortex/server@4.60.59",
|
|
1016
1016
|
"group": "@neocortex",
|
|
1017
1017
|
"name": "server",
|
|
1018
1018
|
"properties": [
|
|
@@ -1021,12 +1021,12 @@
|
|
|
1021
1021
|
"value": "node_modules/@neocortex/server"
|
|
1022
1022
|
}
|
|
1023
1023
|
],
|
|
1024
|
-
"purl": "pkg:npm/%40neocortex/server@4.60.
|
|
1024
|
+
"purl": "pkg:npm/%40neocortex/server@4.60.59",
|
|
1025
1025
|
"type": "library",
|
|
1026
|
-
"version": "4.60.
|
|
1026
|
+
"version": "4.60.59"
|
|
1027
1027
|
},
|
|
1028
1028
|
{
|
|
1029
|
-
"bom-ref": "@neocortex/shared@4.60.
|
|
1029
|
+
"bom-ref": "@neocortex/shared@4.60.59",
|
|
1030
1030
|
"group": "@neocortex",
|
|
1031
1031
|
"name": "shared",
|
|
1032
1032
|
"properties": [
|
|
@@ -1035,9 +1035,9 @@
|
|
|
1035
1035
|
"value": "node_modules/@neocortex/shared"
|
|
1036
1036
|
}
|
|
1037
1037
|
],
|
|
1038
|
-
"purl": "pkg:npm/%40neocortex/shared@4.60.
|
|
1038
|
+
"purl": "pkg:npm/%40neocortex/shared@4.60.59",
|
|
1039
1039
|
"type": "library",
|
|
1040
|
-
"version": "4.60.
|
|
1040
|
+
"version": "4.60.59"
|
|
1041
1041
|
},
|
|
1042
1042
|
{
|
|
1043
1043
|
"bom-ref": "@opentelemetry/api-logs@0.214.0",
|
|
@@ -9405,17 +9405,17 @@
|
|
|
9405
9405
|
"dependsOn": [
|
|
9406
9406
|
"@clack/prompts@1.0.1",
|
|
9407
9407
|
"@modelcontextprotocol/sdk@1.26.0",
|
|
9408
|
-
"@neocortex/client@4.60.
|
|
9408
|
+
"@neocortex/client@4.60.59",
|
|
9409
9409
|
"@neocortex/core@0.1.0",
|
|
9410
|
-
"@neocortex/server@4.60.
|
|
9411
|
-
"@neocortex/shared@4.60.
|
|
9410
|
+
"@neocortex/server@4.60.59",
|
|
9411
|
+
"@neocortex/shared@4.60.59",
|
|
9412
9412
|
"better-sqlite3@12.11.1",
|
|
9413
9413
|
"execa@9.6.1",
|
|
9414
9414
|
"node-cache@5.1.2",
|
|
9415
9415
|
"picocolors@1.1.1",
|
|
9416
9416
|
"zod@4.4.3"
|
|
9417
9417
|
],
|
|
9418
|
-
"ref": "@ornexus/neocortex@4.60.
|
|
9418
|
+
"ref": "@ornexus/neocortex@4.60.59"
|
|
9419
9419
|
},
|
|
9420
9420
|
{
|
|
9421
9421
|
"dependsOn": [
|
|
@@ -9456,7 +9456,7 @@
|
|
|
9456
9456
|
"@fastify/jwt@10.2.2",
|
|
9457
9457
|
"@fastify/rate-limit@10.3.0",
|
|
9458
9458
|
"@fastify/static@10.1.3",
|
|
9459
|
-
"@neocortex/shared@4.60.
|
|
9459
|
+
"@neocortex/shared@4.60.59",
|
|
9460
9460
|
"@sentry/node@10.62.0",
|
|
9461
9461
|
"bcryptjs@3.0.3",
|
|
9462
9462
|
"drizzle-orm@0.45.2",
|
|
@@ -9469,7 +9469,7 @@
|
|
|
9469
9469
|
"stripe@20.4.1",
|
|
9470
9470
|
"yaml@2.9.0"
|
|
9471
9471
|
],
|
|
9472
|
-
"ref": "@neocortex/server@4.60.
|
|
9472
|
+
"ref": "@neocortex/server@4.60.59"
|
|
9473
9473
|
},
|
|
9474
9474
|
{
|
|
9475
9475
|
"dependsOn": [
|
|
@@ -9590,16 +9590,16 @@
|
|
|
9590
9590
|
},
|
|
9591
9591
|
{
|
|
9592
9592
|
"dependsOn": [
|
|
9593
|
-
"@neocortex/shared@4.60.
|
|
9593
|
+
"@neocortex/shared@4.60.59",
|
|
9594
9594
|
"better-sqlite3@12.11.1",
|
|
9595
9595
|
"jose@6.2.2",
|
|
9596
9596
|
"keytar@7.9.0"
|
|
9597
9597
|
],
|
|
9598
|
-
"ref": "@neocortex/client@4.60.
|
|
9598
|
+
"ref": "@neocortex/client@4.60.59"
|
|
9599
9599
|
},
|
|
9600
9600
|
{
|
|
9601
9601
|
"dependsOn": [
|
|
9602
|
-
"@neocortex/shared@4.60.
|
|
9602
|
+
"@neocortex/shared@4.60.59"
|
|
9603
9603
|
],
|
|
9604
9604
|
"ref": "@neocortex/core@0.1.0"
|
|
9605
9605
|
},
|
|
@@ -10653,7 +10653,7 @@
|
|
|
10653
10653
|
"ref": "@lukeed/ms@2.0.2"
|
|
10654
10654
|
},
|
|
10655
10655
|
{
|
|
10656
|
-
"ref": "@neocortex/shared@4.60.
|
|
10656
|
+
"ref": "@neocortex/shared@4.60.59"
|
|
10657
10657
|
},
|
|
10658
10658
|
{
|
|
10659
10659
|
"ref": "@opentelemetry/api@1.9.1"
|
|
@@ -11136,8 +11136,8 @@
|
|
|
11136
11136
|
"metadata": {
|
|
11137
11137
|
"component": {
|
|
11138
11138
|
"author": "OrNexus Team",
|
|
11139
|
-
"bom-ref": "@ornexus/neocortex@4.60.
|
|
11140
|
-
"description": "Neocortex v4.60.
|
|
11139
|
+
"bom-ref": "@ornexus/neocortex@4.60.59",
|
|
11140
|
+
"description": "Neocortex v4.60.59 - Orquestrador de Desenvolvimento de Epics & Stories para Claude Code",
|
|
11141
11141
|
"externalReferences": [
|
|
11142
11142
|
{
|
|
11143
11143
|
"comment": "as detected from PackageJson property \"bugs.url\"",
|
|
@@ -11170,9 +11170,9 @@
|
|
|
11170
11170
|
"value": ""
|
|
11171
11171
|
}
|
|
11172
11172
|
],
|
|
11173
|
-
"purl": "pkg:npm/%40ornexus/neocortex@4.60.
|
|
11173
|
+
"purl": "pkg:npm/%40ornexus/neocortex@4.60.59?vcs_url=git%2Bhttps%3A%2F%2Fgithub.com%2FOrNexus-AI%2Fneocortex.git",
|
|
11174
11174
|
"type": "application",
|
|
11175
|
-
"version": "4.60.
|
|
11175
|
+
"version": "4.60.59"
|
|
11176
11176
|
},
|
|
11177
11177
|
"tools": {
|
|
11178
11178
|
"components": [
|
package/install.ps1
CHANGED
package/install.sh
CHANGED
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ornexus/neocortex",
|
|
3
|
-
"version": "4.60.
|
|
4
|
-
"description": "Neocortex v4.60.
|
|
3
|
+
"version": "4.60.59",
|
|
4
|
+
"description": "Neocortex v4.60.59 - Orquestrador de Desenvolvimento de Epics & Stories para Claude Code",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"claude",
|
|
7
7
|
"claude-code",
|
|
@@ -4,8 +4,8 @@ import{createHash as Ne,randomUUID as dt}from"node:crypto";import{execFileSync a
|
|
|
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 ms(){_t=!1}function dr(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function go(e){return e==="active"||e==="archived"||e==="rolled-back"||e==="synthetic"||e==="orphan"?e:void 0}function ur(e){return e==="create-epic"||e==="discovered"?e:void 0}function oe(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function mo(e){const t={};let r=!1;for(const n of["contracts","contract_refs","shared_surfaces","adr_refs","nfr_refs","acceptance_depends_on"]){if(e[n]===void 0)continue;const o=e[n];if(!Array.isArray(o)||o.length>128||o.some(i=>Ke(i)===void 0)){r=!0;continue}t[n]=o.map(i=>Ke(i))}if(e.planning!==void 0)try{if(!y(e.planning))throw new Error("planning-shape");const n=e.planning;for(const a of["claims","semanticArtifacts"]){if(n[a]===void 0)continue;const c=n[a];if(!Array.isArray(c)||c.length>128||c.some(l=>!y(l)||Ke(l.ref)===void 0))throw new Error("planning-refs")}if(n.attempts!==void 0&&(!Array.isArray(n.attempts)||n.attempts.length>32))throw new Error("planning-attempts");for(const a of n.attempts??[]){if(!y(a)||!Array.isArray(a.reasonCodes)||a.reasonCodes.length>32||a.reasonCodes.some(c=>typeof c!="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(c)))throw new Error("planning-attempt-reasons");if(a.discoveredClaims!==void 0&&(!Array.isArray(a.discoveredClaims)||a.discoveredClaims.length>128||a.discoveredClaims.some(c=>!y(c)||Ke(c.ref)===void 0)))throw new Error("planning-attempt-claims")}const{graphRevision:o,...i}=Un(n);t.planning=i}catch{r=!0}return r&&(t.planning={schemaVersion:1,dependencyBasis:"unknown",claims:[],semanticArtifacts:[]}),t}function y(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Se(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function B(e){if(typeof e!="string")return;const t=e.trim();if(t)return t.replace(/[^a-z0-9_.:-]+/gi,"_").slice(0,120)}function M(e){if(typeof e!="string")return;const t=e.trim(),r=B(e);return r===t?r:void 0}function q(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240)&&/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(t)&&!(t.includes("..")||t.includes("//")||t.includes("@{")||t.endsWith("/")||t.endsWith("."))&&!t.split("/").some(r=>!r||r.startsWith(".")||r.endsWith(".lock")))return t}function S(e){return typeof e=="string"&&/^[0-9a-f]{7,64}$/i.test(e)?e:void 0}function ie(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 Ae(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 tt(e,t){if(!y(e))return;const r={};for(const n of t){const o=e[n];if(typeof o=="boolean")r[n]=o;else if(typeof o=="number"&&Number.isFinite(o))r[n]=o;else if(typeof o=="string"){const i=B(o);i&&(r[n]=i)}}return Object.keys(r).length>0?r:void 0}function rt(e){return e==="epic"||e==="story"?e:void 0}function lr(e){if(!y(e)||e.schemaVersion!==1)return;const t=M(e.ownerStoryId),r=M(e.sessionId),n=M(e.idempotencyKey),o=ie(e.acquiredAt),i=ie(e.expiresAt);if(!(!t||!r||!n||!o||!i||Date.parse(i)<=Date.parse(o)))return{schemaVersion:1,ownerStoryId:t,sessionId:r,idempotencyKey:n,acquiredAt:o,expiresAt:i}}function pr(e){if(!y(e)||e.schemaVersion!==1)return;const t=M(e.storyId),r=M(e.epicId),n=q(e.branch),o=S(e.baseSha),i=S(e.headSha),a=M(e.idempotencyKey),c=ie(e.recordedAt),l=oe(e.commits).map(S).filter(j=>!!j).slice(0,256),p=oe(e.receiptRefs).map(Ae).filter(j=>!!j).slice(0,256),m=e.dispatchId===void 0?void 0:M(e.dispatchId),w=e.bundleId===void 0?void 0:M(e.bundleId),f=e.bundleDigest===void 0?void 0:S(e.bundleDigest),d=e.graphRevision===void 0?void 0:S(e.graphRevision),I=e.claimRevision===void 0?void 0:M(e.claimRevision),A=yo(e.qaReceipt),C=Io(e.reviewReceipt);if(!(!t||!r||!t.startsWith(`${r}.`)||!n||!o||!i||o===i||!a||!c||l.length===0||p.length===0||!Array.isArray(e.commits)||l.length!==e.commits.length||e.commits.length>256||!Array.isArray(e.receiptRefs)||p.length!==e.receiptRefs.length||e.receiptRefs.length>256||e.dispatchId!==void 0&&!m||e.bundleId!==void 0&&!w||e.bundleDigest!==void 0&&(!f||f.length!==64)||e.graphRevision!==void 0&&(!d||d.length!==64)||e.claimRevision!==void 0&&!I||e.qaVerdict!=="passed"&&e.qaVerdict!=="blocked"||!["approved","changes-requested","pending"].includes(String(e.reviewVerdict))||!A||e.reviewVerdict!=="pending"&&!C||e.reviewVerdict==="pending"&&C||A.verdict!==e.qaVerdict||C&&C.verdict!==e.reviewVerdict||!gr(A,{storyId:t,epicId:r,baseSha:o,headSha:i,bundleDigest:f,graphRevision:d})||C&&(!gr(C,{storyId:t,epicId:r,baseSha:o,headSha:i,bundleDigest:f,graphRevision:d})||C.qaReceiptRef!==A?.receiptRef||C.receiptRef===A?.receiptRef)||!p.includes(String(A.receiptRef))||C&&(!p.includes(String(C.receiptRef))||Date.parse(String(C.reviewedAt))<Date.parse(String(A.checkedAt)))))return{schemaVersion:1,storyId:t,epicId:r,branch:n,baseSha:o,headSha:i,idempotencyKey:a,...m?{dispatchId:m}:{},...w?{bundleId:w}:{},...f?{bundleDigest:f}:{},...d?{graphRevision:d}:{},...I?{claimRevision:I}:{},qaVerdict:e.qaVerdict,reviewVerdict:e.reviewVerdict,...A?{qaReceipt:A}:{},...C?{reviewReceipt:C}:{},recordedAt:c,commits:l,receiptRefs:p}}function yo(e){if(!y(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=M(e.storyId),r=M(e.epicId),n=S(e.baseSha),o=S(e.headSha),i=S(e.bundleDigest),a=S(e.graphRevision),c=S(e.sourceEvidenceDigest),l=ie(e.checkedAt),p=Ae(e.receiptRef),m=e.evidenceVersion==="p205-execution-v2"&&e.contract==="P205-CI-02"?e.contract:void 0,w=e.evidenceVersion==="p205-execution-v2"&&e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,f=e.evidenceVersion==="p205-execution-v2"?S(e.manifestDigest):void 0,d=e.evidenceVersion==="p205-execution-v2"?S(e.resultDigest):void 0,I=e.evidenceVersion==="p205-execution-v2"?oe(e.gateIds).map(M).filter(A=>!!A).slice(0,64):void 0;if(!(!t||!r||!n||!o||!i||i.length!==64||!a||a.length!==64||!c||c.length!==64||!l||!p||e.evidenceVersion==="p205-execution-v2"&&(!m||w!=="node scripts/test-root.mjs --gate complete"||!f||f.length!==64||!d||d.length!==64||!Array.isArray(e.gateIds)||!I||I.length===0||I.length!==e.gateIds.length)))return{schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",...e.evidenceVersion?{evidenceVersion:e.evidenceVersion}:{},storyId:t,epicId:r,...e.evidenceVersion==="p205-execution-v2"?{contract:m,command:w,manifestDigest:f,gateIds:I,resultDigest:d}:{},baseSha:n,headSha:o,bundleDigest:i,graphRevision:a,sourceEvidenceDigest:c,verdict:e.verdict,checkedAt:l,receiptRef:p}}function fr(e){if(!y(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=M(e.storyId),r=M(e.epicId),n=q(e.branch),o=S(e.baseSha),i=S(e.headSha),a=S(e.aggregateHeadSha),c=S(e.commitBodyDigest),l=S(e.changedPathsDigest),p=e.claimVerification==="canonical"||e.claimVerification==="legacy-migration"?e.claimVerification:void 0,m=S(e.effectiveClaimRevision),w=e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,f=S(e.manifestDigest),d=oe(e.gateIds).map(M).filter(h=>!!h).slice(0,64),I=S(e.resultDigest),A=S(e.graphRevision),C=S(e.executionEvidenceDigest),j=S(e.sourceEvidenceDigest),v=ie(e.verifiedAt),U=oe(e.reasonCodes).map(M).filter(h=>!!h).slice(0,16);if(!(!t||!r||!n||!o||o.length<40||!i||i.length<40||!a||a.length<40||!c||c.length!==64||!l||l.length!==64||!p||!m||m.length!==64||!w||!f||f.length!==64||!Array.isArray(e.gateIds)||d.length!==e.gateIds.length||!I||I.length!==64||!A||A.length!==64||!C||C.length!==64||!j||j.length!==64||!v||U.length===0||e.verdict==="verified"&&(d.length===0||!U.includes("checkpoint-p205-transient-verified"))))return{schemaVersion:1,kind:"story_checkpoint_physical_verification",producer:"client-p205-transient-v1",storyId:t,epicId:r,branch:n,baseSha:o,headSha:i,aggregateHeadSha:a,commitBodyDigest:c,changedPathsDigest:l,claimVerification:p,effectiveClaimRevision:m,command:w,manifestDigest:f,gateIds:d,resultDigest:I,graphRevision:A,executionEvidenceDigest:C,sourceEvidenceDigest:j,verifiedAt:v,verdict:e.verdict,reasonCodes:U,publicSafe:!0}}function hr(e){const t=["schemaVersion","kind","producer","storyId","epicId","branch","baseSha","headSha","graphRevision","effectiveClaimRevision","sourceEvidenceDigest","verifiedAt","reasonCodes","integrationAuthorized","publicSafe"];if(!y(e)||Object.keys(e).some(f=>!t.includes(f))||e.schemaVersion!==1||e.kind!=="story_scheduling_checkpoint_evidence"||e.producer!=="client-git-physical-v1"||e.integrationAuthorized!==!1||e.publicSafe!==!0)return;const r=M(e.storyId),n=M(e.epicId),o=q(e.branch),i=S(e.baseSha),a=S(e.headSha),c=S(e.graphRevision),l=S(e.effectiveClaimRevision),p=S(e.sourceEvidenceDigest),m=ie(e.verifiedAt),w=oe(e.reasonCodes).map(M).filter(f=>!!f);if(!(!r||!n||!o||!i||i.length<40||!a||a.length<40||!c||c.length!==64||!l||l.length!==64||!p||p.length!==64||!m||!Array.isArray(e.reasonCodes)||w.length!==1||w[0]!=="checkpoint-git-scheduling-verified"))return{schemaVersion:1,kind:"story_scheduling_checkpoint_evidence",producer:"client-git-physical-v1",storyId:r,epicId:n,branch:o,baseSha:i,headSha:a,graphRevision:c,effectiveClaimRevision:l,sourceEvidenceDigest:p,verifiedAt:m,reasonCodes:w,integrationAuthorized:!1,publicSafe:!0}}function Io(e){if(!y(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=M(e.storyId),r=M(e.epicId),n=S(e.baseSha),o=S(e.headSha),i=S(e.bundleDigest),a=S(e.graphRevision),c=S(e.sourceEvidenceDigest),l=Ae(e.qaReceiptRef),p=ie(e.reviewedAt),m=Ae(e.receiptRef);if(!(!t||!r||!n||!o||!i||i.length!==64||!a||a.length!==64||!c||c.length!==64||!l||!p||!m))return{schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:t,epicId:r,baseSha:n,headSha:o,bundleDigest:i,graphRevision:a,sourceEvidenceDigest:c,qaReceiptRef:l,verdict:e.verdict,reviewedAt:p,receiptRef:m}}function gr(e,t){return["storyId","epicId","baseSha","headSha","bundleDigest","graphRevision"].every(r=>e[r]===t[r])}function mr(e){if(!y(e)||e.schemaVersion!==1||e.capturedFromCurrentCheckout!==!0)return;const t=q(e.originBranch),r=S(e.originHeadSha),n=q(e.executionBranch),o=ie(e.capturedAt);if(!(!t||!r||r.length<40||!n||!o||t===n))return{schemaVersion:1,originBranch:t,originHeadSha:r,executionBranch:n,capturedFromCurrentCheckout:!0,capturedAt:o}}function yr(e){if(!y(e)||e.schemaVersion!==1||e.verdict!=="passed")return;const t=S(e.executionHeadSha),r=S(e.graphRevision),n=ie(e.checkedAt),o=Ae(e.receiptRef),i=oe(e.gateIds).map(M).filter(m=>!!m).slice(0,128),a=e.evidenceVersion==="p205-execution-v2"&&e.producer==="local-yolo-tdd"&&e.contract==="P205-CI-02"&&e.command==="node scripts/test-root.mjs --gate complete",c=e.evidenceVersion===void 0&&e.producer===void 0&&e.contract===void 0&&e.command===void 0&&e.manifestDigest===void 0&&e.resultDigest===void 0,l=a?S(e.manifestDigest):void 0,p=a?S(e.resultDigest):void 0;if(!(!t||t.length<40||!r||r.length!==64||!n||!o||i.length===0||!Array.isArray(e.gateIds)||i.length!==e.gateIds.length||e.gateIds.length>128||!c&&!a||a&&(!l||l.length!==64||!p||p.length!==64)))return{schemaVersion:1,...a?{evidenceVersion:"p205-execution-v2",producer:"local-yolo-tdd",contract:"P205-CI-02",command:"node scripts/test-root.mjs --gate complete",manifestDigest:l,resultDigest:p}:{},verdict:"passed",executionHeadSha:t,graphRevision:r,checkedAt:n,receiptRef:o,gateIds:i}}function nt(e){if(!y(e)||e.schemaVersion!==1)return;const t=tt(e,["schemaVersion","kind","storyId","epicId","baseSha","headSha","originalBaseSha","originalHeadSha","gitPullRequest","preservesLaterCommits","historyRewrite","recordedAt"])??{},r=oe(e.receiptRefs).map(Ae).filter(o=>!!o).slice(0,256),n=oe(e.revertCommits).map(B).filter(o=>!!o).slice(0,256);return{...t,...r.length?{receiptRefs:r}:{},...n.length?{revertCommits:n}:{}}}function Ir(e){if(!y(e)||e.schemaVersion!==1||e.publicSafe!==!0)return;const t=M(e.epicId),r=q(e.executionBranch),n=q(e.originBranch),o=S(e.baseSha),i=S(e.executionHeadSha),a=e.mergeSha===void 0?void 0:S(e.mergeSha),c=e.pushedSha===void 0?void 0:S(e.pushedSha),l=M(e.idempotencyKey),p=ie(e.attemptStartedAt),m=e.completedAt===void 0?void 0:ie(e.completedAt),w=oe(e.localGateReceiptRefs).map(Ae).filter(A=>!!A).slice(0,256),f=oe(e.reasonCodes).map(M).filter(A=>!!A).slice(0,64),d=_o(e.candidateQa),I=Eo(e.providerGuard);if(!(!t||!r||!n||!o||!i||!l||!p||w.length===0||f.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&&!I||I&&(e.strategy!=="single_pr"||e.physicalStatus!=="pushed"||I.prHeadSha!==a||I.originHeadSha!==o)))return{schemaVersion:1,epicId:t,executionBranch:r,originBranch:n,baseSha:o,executionHeadSha:i,...a?{mergeSha:a}:{},...c?{pushedSha:c}:{},strategy:e.strategy,...Se(e.prNumber)?{prNumber:Se(e.prNumber)}:{},physicalStatus:e.physicalStatus,localGateReceiptRefs:w,idempotencyKey:l,attemptStartedAt:p,...d?{candidateQa:d}:{},...I?{providerGuard:I}:{},...m?{completedAt:m}:{},retryEligible:e.retryEligible,reasonCodes:f,publicSafe:!0}}function Eo(e){if(!y(e)||e.schemaVersion!==1||e.provider!=="github"||e.publicSafe!==!0)return;const t=String(e.mode),r=String(e.source),n=t==="recovered_exact_tree"?r==="physical_recovery":t==="strict_up_to_date_expected_head"&&["branch_protection","ruleset","branch_protection_and_ruleset"].includes(r),o=S(e.prHeadSha),i=S(e.originHeadSha),a=ie(e.checkedAt);if(!(!n||!o||!i||!a))return{schemaVersion:1,provider:"github",mode:t,source:r,prHeadSha:o,originHeadSha:i,checkedAt:a,publicSafe:!0}}function _o(e){if(!y(e)||e.schemaVersion!==1||e.kind!=="epic_merge_candidate_qa"||e.contract!=="P205-CI-02"||e.command!==Hn)return;const r=Object.fromEntries(["originHeadSha","executionHeadSha","mergeSha","treeSha","graphRevision","manifestDigest","resultDigest"].map(a=>[a,S(e[a])])),n=ie(e.checkedAt),o=Ae(e.receiptRef),i=oe(e.gateIds).filter(a=>/^[a-z0-9-]+$/.test(a)).slice(0,128);if(!(Object.values(r).some(a=>!a)||!n||!o||i.length===0))return{schemaVersion:1,kind:e.kind,contract:e.contract,command:e.command,...r,checkedAt:n,receiptRef:o,gateIds:i}}function Co(e){if(!y(e))return;const t={...B(e.active_epic_id??e.activeEpicId)?{active_epic_id:B(e.active_epic_id??e.activeEpicId)}:{},...B(e.active_story_id??e.activeStoryId)?{active_story_id:B(e.active_story_id??e.activeStoryId)}:{},...B(e.active_step_id??e.activeStepId)?{active_step_id:B(e.active_step_id??e.activeStepId)}:{},...B(e.session_id??e.sessionId)?{session_id:B(e.session_id??e.sessionId)}:{},...B(e.started_at??e.startedAt)?{started_at:B(e.started_at??e.startedAt)}:{}};return Object.keys(t).length>0?t:void 0}function So(e){const t=tt(e.completionEvidence??e.completion_evidence,["prNumber","pr_number","prState","pr_state","pullRequestState","merged","mergedAt","issueNumber","issue_number","issueState","issue_state","closedAt"]),r=tt(e.issueCloseAudit??e.issue_close_audit,["schema_version","event","storyId","epicId","issueNumber","closedAt","publicSafe","rawLogStorage"]),n=tt(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}:{},...B(e.physicalMergeStatus)?{physicalMergeStatus:B(e.physicalMergeStatus)}:{},...B(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)?{pr_state:B(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)}:{},...B(e.issue_state??e.issueState??e.workflow_issue_state)?{issue_state:B(e.issue_state??e.issueState??e.workflow_issue_state)}:{},...Se(e.issue_number??e.issueNumber)?{issue_number:Se(e.issue_number??e.issueNumber)}:{},...t?{completionEvidence:t}:{},...r?{issueCloseAudit:r}:{},...n?{scopedCiEvidence:n}:{}}}class we extends Error{reasonCode;constructor(t){super(t),this.name="StateSnapshotIntegrityError",this.reasonCode=t}}const Ao=new Set(["yolo","yoloop","finalize-epic","audit"]);function Er(e){return typeof e=="string"&&Ao.has(e)}function _r(e,t={}){const r=ne(e,".neocortex","state.json");if(!Pe(r))throw new we("git-lifecycle-state-missing");let n;try{n=JSON.parse(Te(r,"utf8"))}catch{throw new we("git-lifecycle-state-corrupt")}if(!y(n)||!y(n.epics)||!y(n.stories))throw new we("git-lifecycle-state-shape-invalid");const o=Object.values(n.epics).some(i=>y(i)&&(i.branch_mode==="epic"||q(i.execution_branch)!==void 0));if(o)try{Xe(e,{required:!0})}catch(i){const a=i instanceof Error&&/^git-lifecycle-/.test(i.message)?i.message:"git-lifecycle-runtime-invalid";if(t.allowMissingRuntime&&a==="git-lifecycle-runtime-missing")return{lifecycleDeclared:!0,runtimeMissing:!0};throw new we(a)}return{lifecycleDeclared:o,runtimeMissing:!1}}function Cr(e,t={}){const r=ne(e,".neocortex","state.json");if(!Pe(r)){if(t.epicAware&&!t.projectless)throw new we("git-lifecycle-state-missing");return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}let n;try{const f=Te(r,"utf-8"),d=JSON.parse(f),I=y(d.epics)?d.epics:{},A=Object.values(I).some(h=>y(h)&&(h.branch_mode==="epic"||q(h.execution_branch)!==void 0)),C=Xe(e,{required:!!(t.epicAware&&A&&!t.projectless)});n=Kt(d,C);const j=y(n.stories)?n.stories:{},v=y(n.epics)?n.epics:{},U=y(d.stories)?d.stories:{};for(const[h,R]of Object.entries(j)){const E=y(R)?R:void 0;if(!E?.checkpoint)continue;const V=typeof E.epic_id=="string"?E.epic_id:h.split(".")[0],N=y(v[V])?v[V]:void 0,P=q(N?.execution_branch);if(!P)continue;const $=Vn(e,E.checkpoint,h,V,P,t.p205Authorities?.[h],Xt(h,E,y(E.checkpoint)?E.checkpoint:void 0));if($.kind==="integration-authorized")E.checkpoint_verification=$.verification,delete E.scheduling_checkpoint_evidence;else if($.kind==="scheduling-only")E.scheduling_checkpoint_evidence=$.evidence,delete E.checkpoint,delete E.checkpoint_verification;else if($.kind==="rejected"){E.checkpoint_verification=$.verification,delete E.scheduling_checkpoint_evidence;const D=y(U[h])?U[h]:void 0;if(delete E.checkpoint,C.stories[h]?.checkpoint!==void 0)for(const O of["status","last_step","steps_completed"])D&&Object.prototype.hasOwnProperty.call(D,O)?E[O]=structuredClone(D[O]):delete E[O];["done","completed","merged"].includes(String(E.status).toLowerCase())&&(E.status="blocked")}}}catch(f){if(t.epicAware&&!t.projectless){const d=f instanceof Error&&/^git-lifecycle-/.test(f.message)?f.message:"git-lifecycle-state-corrupt";throw new we(d)}return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}try{const f=fo(n);f.length>0&&ho(f)}catch{}const o=n.config??n.project??{},i=n.stories??{},a={};for(const[f,d]of Object.entries(i))a[f]={id:d.id??f,title:d.title,epic_id:d.epic_id,status:d.status??"backlog",...ur(d.source)?{source:ur(d.source)}:{},steps_completed:d.steps_completed??[],last_step:d.last_step??null,branch_name:d.branch_name??null,pr_number:d.pr_number,...rt(d.branch_mode)?{branch_mode:rt(d.branch_mode)}:{},...pr(d.checkpoint)?{checkpoint:pr(d.checkpoint)}:{},...fr(d.checkpoint_verification)?{checkpoint_verification:fr(d.checkpoint_verification)}:{},...hr(d.scheduling_checkpoint_evidence)?{scheduling_checkpoint_evidence:hr(d.scheduling_checkpoint_evidence)}:{},...nt(d.review_request)?{review_request:nt(d.review_request)}:{},...nt(d.rollback_receipt)?{rollback_receipt:nt(d.rollback_receipt)}:{},...Se(d.workflow_issue)?{workflow_issue:Se(d.workflow_issue)}:{},...So(d),depends_on:dr(d.depends_on),files_to_modify:oe(d.files_to_modify),...mo(d),risk:typeof d.risk=="string"?d.risk:void 0,blast_radius:typeof d.blast_radius=="number"?d.blast_radius:void 0};const c=n.epics??{},l={};for(const[f,d]of Object.entries(c)){const I=go(d.lifecycle_classification);l[f]={id:d.id??f,title:d.title,status:d.status,stories:d.stories,total_stories:d.total_stories,completed_stories:d.completed_stories,depends_on:dr(d.depends_on),...rt(d.branch_mode)?{branch_mode:rt(d.branch_mode)}:{},...q(d.execution_branch)?{execution_branch:q(d.execution_branch)}:{},...q(d.origin_branch)?{origin_branch:q(d.origin_branch)}:{},...lr(d.branch_lease)?{branch_lease:lr(d.branch_lease)}:{},...mr(d.origin_binding)?{origin_binding:mr(d.origin_binding)}:{},...yr(d.aggregate_qa_receipt)?{aggregate_qa_receipt:yr(d.aggregate_qa_receipt)}:{},...Se(d.pr_number)?{pr_number:Se(d.pr_number)}:{},...B(d.physicalMergeStatus)?{physicalMergeStatus:B(d.physicalMergeStatus)}:{},...S(d.graph_revision)?{graph_revision:S(d.graph_revision)}:{},...Ir(d.terminal_git_receipt)?{terminal_git_receipt:Ir(d.terminal_git_receipt)}:{},...I?{lifecycle_classification:I}:{}}}const p=Co(n.current_session??n.currentSession),m=n.epic_id_ledger,w=Array.isArray(m?.reserved_ids)?[...new Set(m.reserved_ids.filter(f=>typeof f=="string"&&/^P\d+$/.test(f)))].slice(0,2048):[];return{schema_version:typeof n.schema_version=="number"?n.schema_version:void 0,config:{project_name:o.project_name??o.name??"unknown",default_branch:o.default_branch??"main",language:o.language??"pt-BR",yolo_mode:o.yolo_mode,user_name:o.user_name,worktree_base:o.worktree_base,max_parallel_stories:o.max_parallel_stories,project_id:typeof o.project_id=="string"?o.project_id:void 0},stories:a,epics:l,...w.length>0?{epic_id_ledger:{schema_version:1,reserved_ids:w}}:{},...p?{current_session:p}:{}}}async function wo(e,t,r){if(!Er(r))return{};if(cn(t,r))return{};try{const n=JSON.parse(Te(ne(e,".neocortex","state.json"),"utf8")),o=Xe(e,{required:!0}),i=Kt(n,o),a=y(i.stories)?i.stories:{},c=y(i.epics)?i.epics:{},l=Le("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8"}).trim(),p=Le("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8"}).trim(),m=Le("git",["rev-list","--first-parent","--reverse",l],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
|
|
8
|
-
`).filter(Boolean),w=new Map(m.map((h,R)=>[h,R])),f=t.match(/(?:^|\s)@?docs\/stories\/([A-Za-z][A-Za-z0-9._-]*)\.story\.md(?:\s|$)/)?.[1],d=r==="yoloop"?t.match(/(?:^|[\s/@])epic-(P[1-9][0-9]*)\.md(?:\s|$)/i)?.[1]?.toUpperCase():void 0,I=new Set,A=Object.entries(a).flatMap(([h,R])=>{if(f&&h!==f)return[];const
|
|
7
|
+
`)}catch{}}}function ms(){_t=!1}function dr(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function go(e){return e==="active"||e==="archived"||e==="rolled-back"||e==="synthetic"||e==="orphan"?e:void 0}function ur(e){return e==="create-epic"||e==="discovered"?e:void 0}function oe(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function mo(e){const t={};let r=!1;for(const n of["contracts","contract_refs","shared_surfaces","adr_refs","nfr_refs","acceptance_depends_on"]){if(e[n]===void 0)continue;const o=e[n];if(!Array.isArray(o)||o.length>128||o.some(i=>Ke(i)===void 0)){r=!0;continue}t[n]=o.map(i=>Ke(i))}if(e.planning!==void 0)try{if(!y(e.planning))throw new Error("planning-shape");const n=e.planning;for(const a of["claims","semanticArtifacts"]){if(n[a]===void 0)continue;const c=n[a];if(!Array.isArray(c)||c.length>128||c.some(l=>!y(l)||Ke(l.ref)===void 0))throw new Error("planning-refs")}if(n.attempts!==void 0&&(!Array.isArray(n.attempts)||n.attempts.length>32))throw new Error("planning-attempts");for(const a of n.attempts??[]){if(!y(a)||!Array.isArray(a.reasonCodes)||a.reasonCodes.length>32||a.reasonCodes.some(c=>typeof c!="string"||!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(c)))throw new Error("planning-attempt-reasons");if(a.discoveredClaims!==void 0&&(!Array.isArray(a.discoveredClaims)||a.discoveredClaims.length>128||a.discoveredClaims.some(c=>!y(c)||Ke(c.ref)===void 0)))throw new Error("planning-attempt-claims")}const{graphRevision:o,...i}=Un(n);t.planning=i}catch{r=!0}return r&&(t.planning={schemaVersion:1,dependencyBasis:"unknown",claims:[],semanticArtifacts:[]}),t}function y(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Se(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function B(e){if(typeof e!="string")return;const t=e.trim();if(t)return t.replace(/[^a-z0-9_.:-]+/gi,"_").slice(0,120)}function M(e){if(typeof e!="string")return;const t=e.trim(),r=B(e);return r===t?r:void 0}function q(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t.length>240)&&/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(t)&&!(t.includes("..")||t.includes("//")||t.includes("@{")||t.endsWith("/")||t.endsWith("."))&&!t.split("/").some(r=>!r||r.startsWith(".")||r.endsWith(".lock")))return t}function S(e){return typeof e=="string"&&/^[0-9a-f]{7,64}$/i.test(e)?e:void 0}function ie(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 Ae(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 tt(e,t){if(!y(e))return;const r={};for(const n of t){const o=e[n];if(typeof o=="boolean")r[n]=o;else if(typeof o=="number"&&Number.isFinite(o))r[n]=o;else if(typeof o=="string"){const i=B(o);i&&(r[n]=i)}}return Object.keys(r).length>0?r:void 0}function rt(e){return e==="epic"||e==="story"?e:void 0}function lr(e){if(!y(e)||e.schemaVersion!==1)return;const t=M(e.ownerStoryId),r=M(e.sessionId),n=M(e.idempotencyKey),o=ie(e.acquiredAt),i=ie(e.expiresAt);if(!(!t||!r||!n||!o||!i||Date.parse(i)<=Date.parse(o)))return{schemaVersion:1,ownerStoryId:t,sessionId:r,idempotencyKey:n,acquiredAt:o,expiresAt:i}}function pr(e){if(!y(e)||e.schemaVersion!==1)return;const t=M(e.storyId),r=M(e.epicId),n=q(e.branch),o=S(e.baseSha),i=S(e.headSha),a=M(e.idempotencyKey),c=ie(e.recordedAt),l=oe(e.commits).map(S).filter(j=>!!j).slice(0,256),p=oe(e.receiptRefs).map(Ae).filter(j=>!!j).slice(0,256),m=e.dispatchId===void 0?void 0:M(e.dispatchId),w=e.bundleId===void 0?void 0:M(e.bundleId),f=e.bundleDigest===void 0?void 0:S(e.bundleDigest),d=e.graphRevision===void 0?void 0:S(e.graphRevision),I=e.claimRevision===void 0?void 0:M(e.claimRevision),A=yo(e.qaReceipt),C=Io(e.reviewReceipt);if(!(!t||!r||!t.startsWith(`${r}.`)||!n||!o||!i||o===i||!a||!c||l.length===0||p.length===0||!Array.isArray(e.commits)||l.length!==e.commits.length||e.commits.length>256||!Array.isArray(e.receiptRefs)||p.length!==e.receiptRefs.length||e.receiptRefs.length>256||e.dispatchId!==void 0&&!m||e.bundleId!==void 0&&!w||e.bundleDigest!==void 0&&(!f||f.length!==64)||e.graphRevision!==void 0&&(!d||d.length!==64)||e.claimRevision!==void 0&&!I||e.qaVerdict!=="passed"&&e.qaVerdict!=="blocked"||!["approved","changes-requested","pending"].includes(String(e.reviewVerdict))||!A||e.reviewVerdict!=="pending"&&!C||e.reviewVerdict==="pending"&&C||A.verdict!==e.qaVerdict||C&&C.verdict!==e.reviewVerdict||!gr(A,{storyId:t,epicId:r,baseSha:o,headSha:i,bundleDigest:f,graphRevision:d})||C&&(!gr(C,{storyId:t,epicId:r,baseSha:o,headSha:i,bundleDigest:f,graphRevision:d})||C.qaReceiptRef!==A?.receiptRef||C.receiptRef===A?.receiptRef)||!p.includes(String(A.receiptRef))||C&&(!p.includes(String(C.receiptRef))||Date.parse(String(C.reviewedAt))<Date.parse(String(A.checkedAt)))))return{schemaVersion:1,storyId:t,epicId:r,branch:n,baseSha:o,headSha:i,idempotencyKey:a,...m?{dispatchId:m}:{},...w?{bundleId:w}:{},...f?{bundleDigest:f}:{},...d?{graphRevision:d}:{},...I?{claimRevision:I}:{},qaVerdict:e.qaVerdict,reviewVerdict:e.reviewVerdict,...A?{qaReceipt:A}:{},...C?{reviewReceipt:C}:{},recordedAt:c,commits:l,receiptRefs:p}}function yo(e){if(!y(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=M(e.storyId),r=M(e.epicId),n=S(e.baseSha),o=S(e.headSha),i=S(e.bundleDigest),a=S(e.graphRevision),c=S(e.sourceEvidenceDigest),l=ie(e.checkedAt),p=Ae(e.receiptRef),m=e.evidenceVersion==="p205-execution-v2"&&e.contract==="P205-CI-02"?e.contract:void 0,w=e.evidenceVersion==="p205-execution-v2"&&e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,f=e.evidenceVersion==="p205-execution-v2"?S(e.manifestDigest):void 0,d=e.evidenceVersion==="p205-execution-v2"?S(e.resultDigest):void 0,I=e.evidenceVersion==="p205-execution-v2"?oe(e.gateIds).map(M).filter(A=>!!A).slice(0,64):void 0;if(!(!t||!r||!n||!o||!i||i.length!==64||!a||a.length!==64||!c||c.length!==64||!l||!p||e.evidenceVersion==="p205-execution-v2"&&(!m||w!=="node scripts/test-root.mjs --gate complete"||!f||f.length!==64||!d||d.length!==64||!Array.isArray(e.gateIds)||!I||I.length===0||I.length!==e.gateIds.length)))return{schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",...e.evidenceVersion?{evidenceVersion:e.evidenceVersion}:{},storyId:t,epicId:r,...e.evidenceVersion==="p205-execution-v2"?{contract:m,command:w,manifestDigest:f,gateIds:I,resultDigest:d}:{},baseSha:n,headSha:o,bundleDigest:i,graphRevision:a,sourceEvidenceDigest:c,verdict:e.verdict,checkedAt:l,receiptRef:p}}function fr(e){if(!y(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=M(e.storyId),r=M(e.epicId),n=q(e.branch),o=S(e.baseSha),i=S(e.headSha),a=S(e.aggregateHeadSha),c=S(e.commitBodyDigest),l=S(e.changedPathsDigest),p=e.claimVerification==="canonical"||e.claimVerification==="legacy-migration"?e.claimVerification:void 0,m=S(e.effectiveClaimRevision),w=e.command==="node scripts/test-root.mjs --gate complete"?e.command:void 0,f=S(e.manifestDigest),d=oe(e.gateIds).map(M).filter(h=>!!h).slice(0,64),I=S(e.resultDigest),A=S(e.graphRevision),C=S(e.executionEvidenceDigest),j=S(e.sourceEvidenceDigest),v=ie(e.verifiedAt),U=oe(e.reasonCodes).map(M).filter(h=>!!h).slice(0,16);if(!(!t||!r||!n||!o||o.length<40||!i||i.length<40||!a||a.length<40||!c||c.length!==64||!l||l.length!==64||!p||!m||m.length!==64||!w||!f||f.length!==64||!Array.isArray(e.gateIds)||d.length!==e.gateIds.length||!I||I.length!==64||!A||A.length!==64||!C||C.length!==64||!j||j.length!==64||!v||U.length===0||e.verdict==="verified"&&(d.length===0||!U.includes("checkpoint-p205-transient-verified"))))return{schemaVersion:1,kind:"story_checkpoint_physical_verification",producer:"client-p205-transient-v1",storyId:t,epicId:r,branch:n,baseSha:o,headSha:i,aggregateHeadSha:a,commitBodyDigest:c,changedPathsDigest:l,claimVerification:p,effectiveClaimRevision:m,command:w,manifestDigest:f,gateIds:d,resultDigest:I,graphRevision:A,executionEvidenceDigest:C,sourceEvidenceDigest:j,verifiedAt:v,verdict:e.verdict,reasonCodes:U,publicSafe:!0}}function hr(e){const t=["schemaVersion","kind","producer","storyId","epicId","branch","baseSha","headSha","graphRevision","effectiveClaimRevision","sourceEvidenceDigest","verifiedAt","reasonCodes","integrationAuthorized","publicSafe"];if(!y(e)||Object.keys(e).some(f=>!t.includes(f))||e.schemaVersion!==1||e.kind!=="story_scheduling_checkpoint_evidence"||e.producer!=="client-git-physical-v1"||e.integrationAuthorized!==!1||e.publicSafe!==!0)return;const r=M(e.storyId),n=M(e.epicId),o=q(e.branch),i=S(e.baseSha),a=S(e.headSha),c=S(e.graphRevision),l=S(e.effectiveClaimRevision),p=S(e.sourceEvidenceDigest),m=ie(e.verifiedAt),w=oe(e.reasonCodes).map(M).filter(f=>!!f);if(!(!r||!n||!o||!i||i.length<40||!a||a.length<40||!c||c.length!==64||!l||l.length!==64||!p||p.length!==64||!m||!Array.isArray(e.reasonCodes)||w.length!==1||w[0]!=="checkpoint-git-scheduling-verified"))return{schemaVersion:1,kind:"story_scheduling_checkpoint_evidence",producer:"client-git-physical-v1",storyId:r,epicId:n,branch:o,baseSha:i,headSha:a,graphRevision:c,effectiveClaimRevision:l,sourceEvidenceDigest:p,verifiedAt:m,reasonCodes:w,integrationAuthorized:!1,publicSafe:!0}}function Io(e){if(!y(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=M(e.storyId),r=M(e.epicId),n=S(e.baseSha),o=S(e.headSha),i=S(e.bundleDigest),a=S(e.graphRevision),c=S(e.sourceEvidenceDigest),l=Ae(e.qaReceiptRef),p=ie(e.reviewedAt),m=Ae(e.receiptRef);if(!(!t||!r||!n||!o||!i||i.length!==64||!a||a.length!==64||!c||c.length!==64||!l||!p||!m))return{schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:t,epicId:r,baseSha:n,headSha:o,bundleDigest:i,graphRevision:a,sourceEvidenceDigest:c,qaReceiptRef:l,verdict:e.verdict,reviewedAt:p,receiptRef:m}}function gr(e,t){return["storyId","epicId","baseSha","headSha","bundleDigest","graphRevision"].every(r=>e[r]===t[r])}function mr(e){if(!y(e)||e.schemaVersion!==1||e.capturedFromCurrentCheckout!==!0)return;const t=q(e.originBranch),r=S(e.originHeadSha),n=q(e.executionBranch),o=ie(e.capturedAt);if(!(!t||!r||r.length<40||!n||!o||t===n))return{schemaVersion:1,originBranch:t,originHeadSha:r,executionBranch:n,capturedFromCurrentCheckout:!0,capturedAt:o}}function yr(e){if(!y(e)||e.schemaVersion!==1||e.verdict!=="passed")return;const t=S(e.executionHeadSha),r=S(e.graphRevision),n=ie(e.checkedAt),o=Ae(e.receiptRef),i=oe(e.gateIds).map(M).filter(m=>!!m).slice(0,128),a=e.evidenceVersion==="p205-execution-v2"&&e.producer==="local-yolo-tdd"&&e.contract==="P205-CI-02"&&e.command==="node scripts/test-root.mjs --gate complete",c=e.evidenceVersion===void 0&&e.producer===void 0&&e.contract===void 0&&e.command===void 0&&e.manifestDigest===void 0&&e.resultDigest===void 0,l=a?S(e.manifestDigest):void 0,p=a?S(e.resultDigest):void 0;if(!(!t||t.length<40||!r||r.length!==64||!n||!o||i.length===0||!Array.isArray(e.gateIds)||i.length!==e.gateIds.length||e.gateIds.length>128||!c&&!a||a&&(!l||l.length!==64||!p||p.length!==64)))return{schemaVersion:1,...a?{evidenceVersion:"p205-execution-v2",producer:"local-yolo-tdd",contract:"P205-CI-02",command:"node scripts/test-root.mjs --gate complete",manifestDigest:l,resultDigest:p}:{},verdict:"passed",executionHeadSha:t,graphRevision:r,checkedAt:n,receiptRef:o,gateIds:i}}function nt(e){if(!y(e)||e.schemaVersion!==1)return;const t=tt(e,["schemaVersion","kind","storyId","epicId","baseSha","headSha","originalBaseSha","originalHeadSha","gitPullRequest","preservesLaterCommits","historyRewrite","recordedAt"])??{},r=oe(e.receiptRefs).map(Ae).filter(o=>!!o).slice(0,256),n=oe(e.revertCommits).map(B).filter(o=>!!o).slice(0,256);return{...t,...r.length?{receiptRefs:r}:{},...n.length?{revertCommits:n}:{}}}function Ir(e){if(!y(e)||e.schemaVersion!==1||e.publicSafe!==!0)return;const t=M(e.epicId),r=q(e.executionBranch),n=q(e.originBranch),o=S(e.baseSha),i=S(e.executionHeadSha),a=e.mergeSha===void 0?void 0:S(e.mergeSha),c=e.pushedSha===void 0?void 0:S(e.pushedSha),l=M(e.idempotencyKey),p=ie(e.attemptStartedAt),m=e.completedAt===void 0?void 0:ie(e.completedAt),w=oe(e.localGateReceiptRefs).map(Ae).filter(A=>!!A).slice(0,256),f=oe(e.reasonCodes).map(M).filter(A=>!!A).slice(0,64),d=_o(e.candidateQa),I=Eo(e.providerGuard);if(!(!t||!r||!n||!o||!i||!l||!p||w.length===0||f.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&&!I||I&&(e.strategy!=="single_pr"||e.physicalStatus!=="pushed"||I.prHeadSha!==a||I.originHeadSha!==o)))return{schemaVersion:1,epicId:t,executionBranch:r,originBranch:n,baseSha:o,executionHeadSha:i,...a?{mergeSha:a}:{},...c?{pushedSha:c}:{},strategy:e.strategy,...Se(e.prNumber)?{prNumber:Se(e.prNumber)}:{},physicalStatus:e.physicalStatus,localGateReceiptRefs:w,idempotencyKey:l,attemptStartedAt:p,...d?{candidateQa:d}:{},...I?{providerGuard:I}:{},...m?{completedAt:m}:{},retryEligible:e.retryEligible,reasonCodes:f,publicSafe:!0}}function Eo(e){if(!y(e)||e.schemaVersion!==1||e.provider!=="github"||e.publicSafe!==!0)return;const t=String(e.mode),r=String(e.source),n=t==="recovered_exact_tree"?r==="physical_recovery":t==="strict_up_to_date_expected_head"&&["branch_protection","ruleset","branch_protection_and_ruleset"].includes(r),o=S(e.prHeadSha),i=S(e.originHeadSha),a=ie(e.checkedAt);if(!(!n||!o||!i||!a))return{schemaVersion:1,provider:"github",mode:t,source:r,prHeadSha:o,originHeadSha:i,checkedAt:a,publicSafe:!0}}function _o(e){if(!y(e)||e.schemaVersion!==1||e.kind!=="epic_merge_candidate_qa"||e.contract!=="P205-CI-02"||e.command!==Hn)return;const r=Object.fromEntries(["originHeadSha","executionHeadSha","mergeSha","treeSha","graphRevision","manifestDigest","resultDigest"].map(a=>[a,S(e[a])])),n=ie(e.checkedAt),o=Ae(e.receiptRef),i=oe(e.gateIds).filter(a=>/^[a-z0-9-]+$/.test(a)).slice(0,128);if(!(Object.values(r).some(a=>!a)||!n||!o||i.length===0))return{schemaVersion:1,kind:e.kind,contract:e.contract,command:e.command,...r,checkedAt:n,receiptRef:o,gateIds:i}}function Co(e){if(!y(e))return;const t={...B(e.active_epic_id??e.activeEpicId)?{active_epic_id:B(e.active_epic_id??e.activeEpicId)}:{},...B(e.active_story_id??e.activeStoryId)?{active_story_id:B(e.active_story_id??e.activeStoryId)}:{},...B(e.active_step_id??e.activeStepId)?{active_step_id:B(e.active_step_id??e.activeStepId)}:{},...B(e.session_id??e.sessionId)?{session_id:B(e.session_id??e.sessionId)}:{},...B(e.started_at??e.startedAt)?{started_at:B(e.started_at??e.startedAt)}:{}};return Object.keys(t).length>0?t:void 0}function So(e){const t=tt(e.completionEvidence??e.completion_evidence,["prNumber","pr_number","prState","pr_state","pullRequestState","merged","mergedAt","issueNumber","issue_number","issueState","issue_state","closedAt"]),r=tt(e.issueCloseAudit??e.issue_close_audit,["schema_version","event","storyId","epicId","issueNumber","closedAt","publicSafe","rawLogStorage"]),n=tt(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}:{},...B(e.physicalMergeStatus)?{physicalMergeStatus:B(e.physicalMergeStatus)}:{},...B(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)?{pr_state:B(e.pr_state??e.prState??e.pull_request_state??e.pullRequestState)}:{},...B(e.issue_state??e.issueState??e.workflow_issue_state)?{issue_state:B(e.issue_state??e.issueState??e.workflow_issue_state)}:{},...Se(e.issue_number??e.issueNumber)?{issue_number:Se(e.issue_number??e.issueNumber)}:{},...t?{completionEvidence:t}:{},...r?{issueCloseAudit:r}:{},...n?{scopedCiEvidence:n}:{}}}class we extends Error{reasonCode;constructor(t){super(t),this.name="StateSnapshotIntegrityError",this.reasonCode=t}}const Ao=new Set(["yolo","yoloop","finalize-epic","audit"]);function Er(e){return typeof e=="string"&&Ao.has(e)}function _r(e,t={}){const r=ne(e,".neocortex","state.json");if(!Pe(r))throw new we("git-lifecycle-state-missing");let n;try{n=JSON.parse(Te(r,"utf8"))}catch{throw new we("git-lifecycle-state-corrupt")}if(!y(n)||!y(n.epics)||!y(n.stories))throw new we("git-lifecycle-state-shape-invalid");const o=Object.values(n.epics).some(i=>y(i)&&(i.branch_mode==="epic"||q(i.execution_branch)!==void 0));if(o)try{Xe(e,{required:!0})}catch(i){const a=i instanceof Error&&/^git-lifecycle-/.test(i.message)?i.message:"git-lifecycle-runtime-invalid";if(t.allowMissingRuntime&&a==="git-lifecycle-runtime-missing")return{lifecycleDeclared:!0,runtimeMissing:!0};throw new we(a)}return{lifecycleDeclared:o,runtimeMissing:!1}}function Cr(e,t={}){const r=ne(e,".neocortex","state.json");if(!Pe(r)){if(t.epicAware&&!t.projectless)throw new we("git-lifecycle-state-missing");return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}let n;try{const f=Te(r,"utf-8"),d=JSON.parse(f),I=y(d.epics)?d.epics:{},A=Object.values(I).some(h=>y(h)&&(h.branch_mode==="epic"||q(h.execution_branch)!==void 0)),C=Xe(e,{required:!!(t.epicAware&&A&&!t.projectless)});n=Kt(d,C);const j=y(n.stories)?n.stories:{},v=y(n.epics)?n.epics:{},U=y(d.stories)?d.stories:{};for(const[h,R]of Object.entries(j)){const _=y(R)?R:void 0;if(!_?.checkpoint)continue;const V=typeof _.epic_id=="string"?_.epic_id:h.split(".")[0],N=y(v[V])?v[V]:void 0,P=q(N?.execution_branch);if(!P)continue;const $=Vn(e,_.checkpoint,h,V,P,t.p205Authorities?.[h],Xt(h,_,y(_.checkpoint)?_.checkpoint:void 0));if($.kind==="integration-authorized")_.checkpoint_verification=$.verification,delete _.scheduling_checkpoint_evidence;else if($.kind==="scheduling-only")_.scheduling_checkpoint_evidence=$.evidence,delete _.checkpoint,delete _.checkpoint_verification;else if($.kind==="rejected"){_.checkpoint_verification=$.verification,delete _.scheduling_checkpoint_evidence;const D=y(U[h])?U[h]:void 0;if(delete _.checkpoint,C.stories[h]?.checkpoint!==void 0)for(const O of["status","last_step","steps_completed"])D&&Object.prototype.hasOwnProperty.call(D,O)?_[O]=structuredClone(D[O]):delete _[O];["done","completed","merged"].includes(String(_.status).toLowerCase())&&(_.status="blocked")}}}catch(f){if(t.epicAware&&!t.projectless){const d=f instanceof Error&&/^git-lifecycle-/.test(f.message)?f.message:"git-lifecycle-state-corrupt";throw new we(d)}return{config:{project_name:"unknown",default_branch:"main",language:"pt-BR"},stories:{},epics:{}}}try{const f=fo(n);f.length>0&&ho(f)}catch{}const o=n.config??n.project??{},i=n.stories??{},a={};for(const[f,d]of Object.entries(i))a[f]={id:d.id??f,title:d.title,epic_id:d.epic_id,status:d.status??"backlog",...ur(d.source)?{source:ur(d.source)}:{},steps_completed:d.steps_completed??[],last_step:d.last_step??null,branch_name:d.branch_name??null,pr_number:d.pr_number,...rt(d.branch_mode)?{branch_mode:rt(d.branch_mode)}:{},...pr(d.checkpoint)?{checkpoint:pr(d.checkpoint)}:{},...fr(d.checkpoint_verification)?{checkpoint_verification:fr(d.checkpoint_verification)}:{},...hr(d.scheduling_checkpoint_evidence)?{scheduling_checkpoint_evidence:hr(d.scheduling_checkpoint_evidence)}:{},...nt(d.review_request)?{review_request:nt(d.review_request)}:{},...nt(d.rollback_receipt)?{rollback_receipt:nt(d.rollback_receipt)}:{},...Se(d.workflow_issue)?{workflow_issue:Se(d.workflow_issue)}:{},...So(d),depends_on:dr(d.depends_on),files_to_modify:oe(d.files_to_modify),...mo(d),risk:typeof d.risk=="string"?d.risk:void 0,blast_radius:typeof d.blast_radius=="number"?d.blast_radius:void 0};const c=n.epics??{},l={};for(const[f,d]of Object.entries(c)){const I=go(d.lifecycle_classification);l[f]={id:d.id??f,title:d.title,status:d.status,stories:d.stories,total_stories:d.total_stories,completed_stories:d.completed_stories,depends_on:dr(d.depends_on),...rt(d.branch_mode)?{branch_mode:rt(d.branch_mode)}:{},...q(d.execution_branch)?{execution_branch:q(d.execution_branch)}:{},...q(d.origin_branch)?{origin_branch:q(d.origin_branch)}:{},...lr(d.branch_lease)?{branch_lease:lr(d.branch_lease)}:{},...mr(d.origin_binding)?{origin_binding:mr(d.origin_binding)}:{},...yr(d.aggregate_qa_receipt)?{aggregate_qa_receipt:yr(d.aggregate_qa_receipt)}:{},...Se(d.pr_number)?{pr_number:Se(d.pr_number)}:{},...B(d.physicalMergeStatus)?{physicalMergeStatus:B(d.physicalMergeStatus)}:{},...S(d.graph_revision)?{graph_revision:S(d.graph_revision)}:{},...Ir(d.terminal_git_receipt)?{terminal_git_receipt:Ir(d.terminal_git_receipt)}:{},...I?{lifecycle_classification:I}:{}}}const p=Co(n.current_session??n.currentSession),m=n.epic_id_ledger,w=Array.isArray(m?.reserved_ids)?[...new Set(m.reserved_ids.filter(f=>typeof f=="string"&&/^P\d+$/.test(f)))].slice(0,2048):[];return{schema_version:typeof n.schema_version=="number"?n.schema_version:void 0,config:{project_name:o.project_name??o.name??"unknown",default_branch:o.default_branch??"main",language:o.language??"pt-BR",yolo_mode:o.yolo_mode,user_name:o.user_name,worktree_base:o.worktree_base,max_parallel_stories:o.max_parallel_stories,project_id:typeof o.project_id=="string"?o.project_id:void 0},stories:a,epics:l,...w.length>0?{epic_id_ledger:{schema_version:1,reserved_ids:w}}:{},...p?{current_session:p}:{}}}async function wo(e,t,r){if(!Er(r))return{};if(cn(t,r))return{};try{const n=JSON.parse(Te(ne(e,".neocortex","state.json"),"utf8")),o=Xe(e,{required:!0}),i=Kt(n,o),a=y(i.stories)?i.stories:{},c=y(i.epics)?i.epics:{},l=Le("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8"}).trim(),p=Le("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8"}).trim(),m=Le("git",["rev-list","--first-parent","--reverse",l],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024}).trim().split(`
|
|
8
|
+
`).filter(Boolean),w=new Map(m.map((h,R)=>[h,R])),f=t.match(/(?:^|\s)@?docs\/stories\/([A-Za-z][A-Za-z0-9._-]*)\.story\.md(?:\s|$)/)?.[1],d=r==="yoloop"?t.match(/(?:^|[\s/@])epic-(P[1-9][0-9]*)\.md(?:\s|$)/i)?.[1]?.toUpperCase():void 0,I=new Set,A=Object.entries(a).flatMap(([h,R])=>{if(f&&h!==f)return[];const _=y(R)?R:void 0,V=y(_?.checkpoint)?_.checkpoint:void 0;if(!V)return[];const N=typeof _?.epic_id=="string"?_.epic_id:h.split(".")[0];if(d&&N!==d)return[];const P=S(V?.headSha);if(!P||P.length<40||w.get(P)===void 0)return I.add(N),[];const $=y(c[N])?c[N]:void 0;if($?.branch_mode!=="epic"||q($.execution_branch)!==p||q(V.branch)!==p)return I.add(N),[];const D=S(V.graphRevision);if(!D||D.length!==64)return I.add(N),[];const O=S(V.claimRevision),J=[...Xt(h,_,V)].sort(),ve=Fn(e,V,h,N,p,J);if(!ve&&O){if(J.length===0)return I.add(N),[];const _e=Le("git",["diff-tree","--no-commit-id","--name-only","-r","-z",P],{cwd:e,encoding:"utf8"}).split("\0").filter(Boolean);if(_e.length===0||_e.some(be=>!J.some(W=>W===be||W.endsWith("/")&&be.startsWith(W))))return I.add(N),[];const ge=Ne("sha256").update(J.join("\0")).digest("hex"),Ge=Ne("sha256").update(JSON.stringify(J)).digest("hex");if(O!==ge&&O!==Ge)return I.add(N),[]}else if(!ve)return I.add(N),[];return D?.length===64?[{storyId:h,epicId:N,graphRevision:D,checkpointHead:P,position:w.get(P)}]:[]}),C=new Set(I);for(const[h,R]of Object.entries(c)){const _=y(R)?R:void 0,V=Array.isArray(_?.stories)?_.stories.filter(D=>typeof D=="string"):Object.keys(a).filter(D=>D.startsWith(`${h}.`)),N=A.filter(D=>D.epicId===h),P=V.filter(D=>N.some(O=>O.storyId===D)),$=[...N].sort((D,O)=>D.position-O.position).map(D=>D.storyId);(JSON.stringify(P)!==JSON.stringify($)||new Set($).size!==$.length)&&C.add(h)}const j={},v=[...new Set(A.filter(h=>!C.has(h.epicId)).map(h=>h.graphRevision))],U=v.length>0?await $n(e,{headSha:l,graphRevisions:v}):new Map;for(const h of A){if(C.has(h.epicId))continue;const R=U.get(h.graphRevision);if(!R)throw new Error("p205-transient-authority-missing");j[h.storyId]=R}return j}catch(n){const o=n instanceof Error&&/^(?:p205|git-lifecycle)-[a-z0-9-]+$/.test(n.message)?n.message:"p205-transient-execution-failed";return process.stderr.write(`[Neocortex] ${o}. Checkpoint projection remains fail-closed.
|
|
9
9
|
`),{}}}function ys(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 Sr="neocortex:menu:cache";async function Ro(e){try{const t=await e.get(Sr);if(!t)return null;const r=JSON.parse(t);return r.version!==je||Date.now()-r.cachedAt>Qt?null:r}catch{return null}}async function vo(e,t,r){try{const n={instructions:t,metadata:r,cachedAt:Date.now(),version:je};await e.set(Sr,JSON.stringify(n),Qt),bo()}catch{}}function bo(){try{Pe(Zt)&&Kr(Zt)}catch{}}function To(e){return e.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>jt(),()=>jt({strictReadOnly:!0}))}async function Ar(e,t,r){const n=r.mode==="strict";try{let o;if(n&&t)o=new ut({cacheDir:pt,passphrase:t,strictReadOnly:!0});else if(n)o=new Pt;else if(t){const m=ne(Ze,"cache");o=new ut({cacheDir:m,passphrase:t})}else process.stderr.write(`[neocortex] Warning: No license key in config. Run "neocortex activate" to re-authenticate.
|
|
10
10
|
`),o=new Pt;const i=Yt(r,o,"auth-cache"),a=Yt(r,o,"tier-cache"),c=new Qr({serverUrl:e,licenseKey:t??"",cacheProvider:i,strictReadOnly:n});let l;if(n){const m=await c.inspectToken();if(m.status!=="authenticated")return m;l=m.token}else l=await c.getToken();if(!l)return{status:"not-configured"};const p=new en({cacheProvider:a,licenseClient:c});return{status:"authenticated",token:l,client:c,tierClient:p}}catch{return n&&t?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"}}}let wr=!1;function Oo(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 Rr=3,ot=50;function xo(e){return new Promise(t=>setTimeout(t,e))}function ko(e,t,r){return e.status>=500&&e.status<=599?!0:r&&e.status===409&&t.error_code==="SIGNATURE_REPLAYED"}async function We(e,t,r,n,o={}){const i=Math.max(1,Math.min(o.maxAttempts??Rr,Rr)),a=o.sleep??xo;let c=n,l=!1,p=!1,m=0;for(let w=1;w<=i;w+=1){const f=Math.max(Math.floor(Date.now()/1e3),m+1);m=f;const d=No(t,r,c,{nowSeconds:f}),I=new AbortController,A=setTimeout(()=>I.abort(),er);try{const C=await fetch(`${e}${t}`,{method:"POST",headers:d.headers,body:d.body,signal:I.signal}),j=await C.text().catch(()=>""),v=(()=>{try{return j?JSON.parse(j):{}}catch{return{}}})();if(C.status===401&&!l&&o.refreshToken&&(v.fallback_action==="refresh_token"||v.fallback_action==="re_authenticate")){l=!0;const U=await o.refreshToken();if(U&&w<i){c=U,o.onTokenChanged?.(U),await a(ot*w);continue}}if(C.status===401&&v.error_code==="SIGNATURE_EXPIRED"&&!p&&w<i){p=!0,await a(ot*w);continue}if(w<i&&ko(C,v,o.allowReplayRetry===!0)){await a(ot*w);continue}return{response:C,text:j,parsed:v,networkFailure:!1}}catch{if(w<i){await a(ot*w);continue}return{text:"",parsed:{},networkFailure:!0}}finally{clearTimeout(A)}}return{text:"",parsed:{},networkFailure:!0}}function No(e,t,r,n={}){const o=Buffer.from(JSON.stringify(t),"utf8"),i=_n({method:"POST",target:e,body:o,bearerToken:r,clientVersion:je,nowSeconds:n.nowSeconds,nonceBytes:n.nonceBytes});return{body:i.body,headers:{...i.headers,Authorization:`Bearer ${r}`}}}function vr(e){return Ne("sha256").update(e).digest("hex")}function Lo(){const e=Number(process.env.NEOCORTEX_INVOKE_CHUNK_BYTES??"49152");return Number.isFinite(e)&&e>=1024&&e<=98304?Math.floor(e):49152}function Po(e,t,r){return`args-${Ne("sha256").update("invoke-materialization:v1").update(e).update(String(t)).update(JSON.stringify(r)).digest("hex")}`}async function br(e,t,r,n,o={}){const i=await We(e,t,r,n,{...o,allowReplayRetry:!0});if(i.networkFailure||!i.response)throw new Error("NETWORK_ERROR: materialization request failed after bounded retries");const{response:a,parsed:c}=i;if(!a.ok){const l=typeof c.error_code=="string"?c.error_code:`HTTP_${a.status}`,p=typeof c.message=="string"?c.message:"materialization upload failed";throw new Error(`${l}: ${p}`)}return c}async function Do(e,t,r,n){const o=Buffer.from(t,"utf8"),i=Lo(),a=[];for(let I=0,A=0;I<o.byteLength;I+=i,A++){const C=o.subarray(I,Math.min(I+i,o.byteLength));a.push({index:A,sha256:vr(C),byteLength:C.byteLength})}const c=vr(o),l=Po(c,o.byteLength,a),p=Number(process.env.NEOCORTEX_INVOKE_CHUNK_TTL_SECONDS??"900");let m=r;const w={refreshToken:n,onTokenChanged(I){m=I}};for(const I of a){const A=I.index*i,C=o.subarray(A,A+I.byteLength);await br(e,"/api/v1/invoke/materialization/chunks",{manifestId:l,index:I.index,sha256:I.sha256,byteLength:I.byteLength,contentBase64:C.toString("base64"),ttlSeconds:p,idempotencyKey:`${l}:${I.index}:${I.sha256}`},m,w)}const d=(await br(e,"/api/v1/invoke/materialization/manifests",{manifestId:l,sha256:c,byteLength:o.byteLength,chunkCount:a.length,chunks:a,ttlSeconds:p,retry:{attempt:1,budget:3,idempotencyKey:l}},m,w)).argsRef;if(!d?.manifestId)throw new Error("MATERIALIZATION_RESPONSE_INVALID: missing argsRef");return{argsRef:d,chunks:a}}function Ve(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function jo(...e){const t=new Set,r=[];for(const n of e)for(const o of n??[]){const i=B(o);if(!(!i||t.has(i))&&(t.add(i),r.push(i),r.length>=16))return r}return r}function Mo(e){const t=e.graphRetrieval;if(!y(t))return{accepted:!1,itemCount:0};const r=Array.isArray(t.items)?t.items.length:0;return{accepted:r>0||typeof t.retrievalId=="string"||t.accepted===!0,itemCount:r}}function Ct(e,t=Ve(e),r=[],n={}){const o=e.stateSnapshot.scope,i=Object.keys(e.stateSnapshot.stories).length,a=Object.keys(e.stateSnapshot.epics).length,c=o?.kind??"full";return{schemaVersion:1,payloadBytes:t,limitBytes:n.limitBytes??rr,warningThresholdBytes:n.warningThresholdBytes??ft,scope:{kind:c,...o?.projectionMode?{projectionMode:o.projectionMode}:{},commandId:o?.commandId??null,stateProjectionPolicy:o?.stateProjectionPolicy??null},includedStories:o?.includedStoryCount??i,omittedStories:o?.omittedStoryCount??0,includedEpics:o?.includedEpicCount??a,omittedEpics:o?.omittedEpicCount??0,graphRetrieval:Mo(e.stateSnapshot),reasonCodes:jo(r,o?.reasonCodes),publicSafe:!0}}function Uo(e){const t=y(e.budget)?e.budget:void 0,r=typeof t?.maxPayloadBytes=="number"&&Number.isFinite(t.maxPayloadBytes)?t.maxPayloadBytes:12*1024;return Math.max(1024,Math.min(r,12*1024))}function Vo(e){return y(e)?{stableId:B(e.stableId)??"unknown",...y(e.source)?{source:e.source}:{},reasonCode:"budget_exceeded"}:{stableId:"unknown",reasonCode:"budget_exceeded"}}function Tr(e){const t=Array.isArray(e)?e.filter(r=>typeof r=="string"):[];return t.includes("budget_exceeded")?t:[...t,"budget_exceeded"]}function Bo(e){const t=e.graphRetrieval;if(!y(t)||!Array.isArray(t.items))return e;const r=Uo(t);let n=[...t.items],o=Array.isArray(t.skipped)?[...t.skipped]:[],i=t;for(;Buffer.byteLength(JSON.stringify(i),"utf8")>r&&n.length>0;){const a=n.pop();o=[...o,Vo(a)].slice(-32),i={...t,items:n,skipped:o,warnings:Tr(t.warnings)}}return Buffer.byteLength(JSON.stringify(i),"utf8")>r&&(i={...t,query:typeof t.query=="string"?t.query.slice(0,240):t.query,items:[],skipped:[],warnings:Tr(t.warnings)}),i===t?e:{...e,graphRetrieval:i}}function Or(e,t={}){const r=t.limitBytes??rr,n=t.warningThresholdBytes??Math.floor(r*nr),o=Ve(e);if(o<r)return{body:e,degraded:!1,telemetry:Ct(e,o,["payload-within-limit"],{limitBytes:r,warningThresholdBytes:n})};let i={...e,stateSnapshot:sn(e.stateSnapshot)},a=["payload-size-guardrail","state-degraded"],c=Ve(i);c>=r&&(i={...i,stateSnapshot:Bo(i.stateSnapshot)},a=[...a,"graph-retrieval-budget-enforced"],c=Ve(i));const l=Ct(i,c,a,{limitBytes:r,warningThresholdBytes:n});if(c>=r){const p=i.stateSnapshot.scope?.projectionMode;throw p==="yolo-story"||p==="yoloop-target"||p==="yoloop-session"||p==="yoloop-discovery"||p==="structural-required"?new Et(l):new It(l)}return{body:i,degraded:!0,telemetry:l}}function xr(e){const t=e.stateSnapshot.scope?.commandId??"resolved-command";return e.args!==void 0?t:`${t}:argsRef`}function $o(e){const t=Ve(e);if(t<ft)return t;const r=Ct(e,t,["payload-warning-threshold"]);return process.stderr.write(`[Neocortex] invoke payload near server limit: trigger=${xr(e)} scope=${r.scope.kind} mode=${r.scope.projectionMode??r.scope.kind} payloadBytes=${r.payloadBytes} limit=${r.limitBytes} includedStories=${r.includedStories} omittedStories=${r.omittedStories} includedEpics=${r.includedEpics} omittedEpics=${r.omittedEpics} graphRetrieval.accepted=${r.graphRetrieval.accepted} graphRetrieval.itemCount=${r.graphRetrieval.itemCount} reasonCodes=${r.reasonCodes.join(",")||"none"}
|
|
11
11
|
`),t}function kr(e,t){process.stderr.write(`[Neocortex] invoke payload guardrail: trigger=${xr(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"}
|
|
@@ -17,34 +17,34 @@ ${t}
|
|
|
17
17
|
`:`[watch] A local processing update is available.
|
|
18
18
|
`);return}if(t==="json"){r.write(JSON.stringify(Jo(e))+`
|
|
19
19
|
`);return}r.write(Yo(e)+`
|
|
20
|
-
`)}function wt(e){return oo.has(e.status)}function qo(e,t,r){if(t){const o=e.find(i=>i.jobId===t);return!!(o&&wt(o))}return r<=0?!1:e.filter(o=>!wt(o)).length===0}function Ko(e,t,r,n){return r<n?!1:t?!e.some(o=>o.jobId===t&&!wt(o)):e.length===0}function Xo(e,t){return t?.aborted?Promise.resolve():new Promise(r=>{const n=setTimeout(o,e);function o(){clearTimeout(n),t?.removeEventListener("abort",o),r()}t?.addEventListener("abort",o,{once:!0})})}function Zo(e){return e.includes(X.MALFORMED)?"malformed":e.includes(X.AMBIGUOUS)?"ambiguous":e.includes("watch-target-multiple")?"multiple":e.includes("watch-evidence-unsafe")?"unsafe":e.includes(X.MISSING)||e.includes(Y.TARGET_UNRESOLVED)?"unresolved":"unavailable"}function Lr(e,t){const r=t?He(t):void 0,n=re([...e,Y.TARGET_UNRESOLVED,x.WATCH_TARGET_UNRESOLVED]),o=At(r,r?.targetId,Zo(n),n),i=Ie({generatedAt:new Date().toISOString()},[],!1,0,[x.WATCH_TARGET_UNRESOLVED]),a=pe(void 0,void 0,void 0,[],[x.WATCH_TARGET_UNRESOLVED],"unavailable");return fe({watchStatus:"blocked",active:!1,targetEvidence:o,snapshotEvidence:i,cursorEvidence:a,stopReason:"target_unresolved",reasonCodes:n,generatedAt:i.generatedAt})}function Qo(e,t,r,n,o=!1){const i=Lr(e,Dr(t));return he(i,r,n,o),Ee("target-unresolved",0,0,i,o)}async function ei(e){if(e.signal?.aborted){const h=At(e.target??He(e.targetJobId),e.targetJobId,e.target??e.targetJobId?"resolved":"unresolved",[Y.CANCELLED]),R=Ie(void 0,[],!1,0),E=pe(e.initialCursor,e.initialCursor,e.initialCursor,[],[Y.CANCELLED],"unavailable"),V=fe({watchStatus:"stopped",active:!1,targetEvidence:h,snapshotEvidence:R,cursorEvidence:E,stopReason:"cancelled",reasonCodes:[Y.CANCELLED]});return Ee("cancelled",0,0,V,e.protectedOutput)}const t=e.target??He(e.targetJobId),r=e.targetJobId??t?.targetId,n=e.stdout??process.stdout;if(!t){const h=Lr([X.MISSING,Y.TARGET_UNRESOLVED]);return he(h,e.format,n,e.protectedOutput),Ee("target-unresolved",0,0,h,e.protectedOutput)}const o=it(e.limit??st("NEOCORTEX_INVOKE_WATCH_LIMIT",Wt),Wt,50),i=Math.max(50,it(e.pollIntervalMs??st("NEOCORTEX_INVOKE_WATCH_POLL_INTERVAL_MS",Gt),Gt,6e4)),a=it(e.maxIdlePolls??st("NEOCORTEX_INVOKE_WATCH_MAX_IDLE_POLLS",Ht),Ht,120),c=it(e.maxPolls??st("NEOCORTEX_INVOKE_WATCH_MAX_POLLS",Ft),Ft,86400),l=e.sleep??Xo;let p=e.initialCursor,m=0,w=0,f=0;const d=At(t,r,"resolved",[x.OK]),I={schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:"pending",renderedSummaryCount:0,reasonCodes:[x.WATCH_RENDER_PENDING],publicSafe:!0},A=pe(e.initialCursor,p,p,[],e.initialCursor?[x.WATCH_CURSOR_UNCHANGED]:[x.WATCH_NO_SUMMARIES_YET],e.initialCursor?"unchanged":"not_started");he(fe({watchStatus:"active",active:!0,targetEvidence:d,snapshotEvidence:I,cursorEvidence:A,stopReason:"not_stopped",reasonCodes:[x.OK]}),e.format,n,e.protectedOutput);let C;try{C=await gn({projectRoot:e.projectRoot,strictReadOnly:e.strictReadOnly})}catch{const h=Ie(void 0,[],!1,m,[x.WATCH_SNAPSHOT_UNAVAILABLE]),R=pe(e.initialCursor,p,p,[],[x.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),E=fe({watchStatus:"blocked",active:!1,targetEvidence:d,snapshotEvidence:h,cursorEvidence:R,stopReason:"unavailable_evidence",reasonCodes:[Y.STORE_UNAVAILABLE]});return he(E,e.format,n,e.protectedOutput),Ee("store-unavailable",m,f,E,e.protectedOutput)}try{for(;!e.signal?.aborted&&f<c;){f+=1;const h=p,R=C.collectProcessingOutputSummaryCursor({...p?{cursor:p}:{},...t?{target:t}:{},...r?{jobId:r}:{},limit:o}),E=C.collectSnapshot({jobLimit:50,processingSummaryLimit:1}),V=E.jobs;if(R.summaries.length>0){for(const $ of R.summaries)zo($,e.format,n,e.protectedOutput),m+=1;p=R.nextCursor??R.summaries[R.summaries.length-1]?.cursor??p,w=0}else p=R.nextCursor??p,w+=1;const N=Ie(E,R.summaries,!0,R.summaries.length),P=pe(e.initialCursor,h,p,R.summaries,R.summaries.length>0?[x.WATCH_CURSOR_ADVANCED]:[x.WATCH_NO_SUMMARIES_YET]);if(he(fe({watchStatus:R.summaries.length>0?"polling":"waiting",active:!0,targetEvidence:d,snapshotEvidence:N,cursorEvidence:P,stopReason:"not_stopped",reasonCodes:R.summaries.length>0?[x.WATCH_CURSOR_ADVANCED]:[x.WATCH_NO_SUMMARIES_YET],generatedAt:E.generatedAt}),e.format,n,e.protectedOutput),!R.hasMore&&qo(V,r,m)){const $=Ie(E,R.summaries,!1,m,[Y.COMPLETED]),D=pe(e.initialCursor,h,p,R.summaries,[Y.COMPLETED],"exhausted"),O=fe({watchStatus:"stopped",active:!1,targetEvidence:d,snapshotEvidence:$,cursorEvidence:D,stopReason:"not_stopped",reasonCodes:[Y.COMPLETED],generatedAt:E.generatedAt});return he(O,e.format,n,e.protectedOutput),Ee("completed",m,f,O,e.protectedOutput)}if(!R.hasMore&&Ko(V,r,w,a)){const $=Ie(E,R.summaries,!1,m,[x.WATCH_STOP_IDLE_LIMIT_REACHED]),D=pe(e.initialCursor,h,p,R.summaries,[x.WATCH_STOP_IDLE_LIMIT_REACHED],"exhausted"),O=fe({watchStatus:"stopped",active:!1,targetEvidence:d,snapshotEvidence:$,cursorEvidence:D,stopReason:"idle_limit_reached",reasonCodes:[Y.IDLE_TIMEOUT,x.WATCH_STOP_IDLE_LIMIT_REACHED],generatedAt:E.generatedAt});return he(O,e.format,n,e.protectedOutput),Ee("idle-timeout",m,f,O,e.protectedOutput)}R.hasMore||await l(i,e.signal)}}catch{const h=Ie(void 0,[],!1,m,[x.WATCH_SNAPSHOT_UNAVAILABLE]),R=pe(e.initialCursor,p,p,[],[x.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),E=fe({watchStatus:"blocked",active:!1,targetEvidence:d,snapshotEvidence:h,cursorEvidence:R,stopReason:"unavailable_evidence",reasonCodes:[Y.STORE_UNAVAILABLE]});return he(E,e.format,n,e.protectedOutput),Ee("store-unavailable",m,f,E,e.protectedOutput)}finally{C.close()}if(e.signal?.aborted){const h=Ie(void 0,[],!1,m,[Y.CANCELLED]),R=pe(e.initialCursor,p,p,[],[Y.CANCELLED],"unavailable"),E=fe({watchStatus:"stopped",active:!1,targetEvidence:d,snapshotEvidence:h,cursorEvidence:R,stopReason:"cancelled",reasonCodes:[Y.CANCELLED]});return he(E,e.format,n,e.protectedOutput),Ee("cancelled",m,f,E,e.protectedOutput)}const j=Ie(void 0,[],!1,m,[x.WATCH_STOP_MAX_POLLS_REACHED]),v=pe(e.initialCursor,p,p,[],[x.WATCH_STOP_MAX_POLLS_REACHED],"exhausted"),U=fe({watchStatus:"stopped",active:!1,targetEvidence:d,snapshotEvidence:j,cursorEvidence:v,stopReason:"max_polls_reached",reasonCodes:[Y.MAX_POLLS,x.WATCH_STOP_MAX_POLLS_REACHED]});return he(U,e.format,n,e.protectedOutput),Ee("max-polls",m,f,U,e.protectedOutput)}function ue(e){const t=e.trim().replace(/^@/,"").match(/^(job|goal|loop)-([JGL])(\d{3,})$/i);if(!t)return;const r=t[1].toLowerCase(),n=t[2].toUpperCase();if(!(r==="job"&&n!=="J"||r==="goal"&&n!=="G"||r==="loop"&&n!=="L"))return`${r}-${n}${t[3]}`}function Rt(e){if(e.startsWith("job-J"))return"job";if(e.startsWith("goal-G"))return"goal";if(e.startsWith("loop-L"))return"loop"}function Pr(e){const t=[],r=/(?:^|[\s"'([,{])@?(job-[Jj]\d{3,}|goal-[Gg]\d{3,}|loop-[Ll]\d{3,})(?=$|[\s"')\]},.;:!?])/g;let n;for(;(n=r.exec(e))!==null;){const o=ue(n[1]);o&&t.push(o)}return re(t)}function Dr(e){return Pr(e)[0]}function He(e){const t=e?ue(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 vt(e){return re(e.filter(t=>typeof t=="string").map(t=>ue(t)).filter(t=>!!t?.startsWith("job-J")))}function ti(e,t){const r=vt(t).filter(n=>n!==e.targetId&&n!==e.jobId);return r.length>0?{...e,relatedJobIds:r}:e}function ri(e){if(!e)return;const t=y(e.target)?e.target:void 0,r=typeof e.selectorKind=="string"?e.selectorKind:typeof t?.selectorKind=="string"?t.selectorKind:void 0,n=typeof e.targetId=="string"?ue(e.targetId):typeof t?.targetId=="string"?ue(t.targetId):typeof e.targetJobId=="string"?ue(e.targetJobId):void 0,o=He(n);if(!o||r&&r!==o.selectorKind)return;const i=Array.isArray(e.relatedJobIds)?e.relatedJobIds:Array.isArray(t?.relatedJobIds)?t.relatedJobIds:void 0,a=vt([...i??[],e.jobId,t?.jobId,e.targetJobId,t?.targetJobId]).filter(c=>c!==o.targetId&&c!==o.jobId);return{...o,...typeof(e.jobId??t?.jobId)=="string"?{jobId:ue(e.jobId??t?.jobId)??o.jobId}:{},...typeof(e.goalId??t?.goalId)=="string"?{goalId:ue(e.goalId??t?.goalId)??o.goalId}:{},...typeof(e.loopId??t?.loopId)=="string"?{loopId:ue(e.loopId??t?.loopId)??o.loopId}:{},...a.length>0?{relatedJobIds:a}:{}}}function jr(e){const t=e.trim().split(/\s+/).filter(Boolean),r=t[0]?.replace(/^\*/,"").toLowerCase(),n=t[1]?.replace(/^--/,"").toLowerCase();return(r==="jobs"||r==="job"||r==="continuity-jobs"||r==="61")&&n==="watch"}const K=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"}),ni=new Set(["create","start","resume"]),oi=new Set(["create","resume","run-once"]);function bt(e,t,r,n,o){return{schemaVersion:1,contractVersion:"continuity-v1",...r?{command:r}:{},...n?{operation:n}:{},active:e,...o?{watchToken:o}:{},reasonCodes:re(t),serverHeldStream:!1,allJobsPolling:!1,targetResolution:e?"required-after-dispatch":"inactive",publicSafe:!0}}function Z(e,t=[],r,n){const o=t.length>0?t:[K.INACTIVE];return{args:e,watch:!1,reasonCodes:o,metadata:bt(!1,o,r,n),publicSafe:!0}}function ii(e){const t=e.trim().split(/\s+/).filter(Boolean),r=t.slice(2).filter(i=>i==="--watch").length;if(r===0)return Z(e,[],"jobs","watch");if(r!==1)return Z(e,[K.AMBIGUOUS],"jobs","watch");const n=t.filter((i,a)=>a<2||i!=="--watch").join(" ");return jr(n)?n.trim().split(/\s+/).filter(Boolean).slice(2).length!==1?Z(e,[K.AMBIGUOUS],"jobs","watch"):Dr(n)?{args:n,watch:!0,reasonCodes:[K.ACTIVE],metadata:bt(!0,[K.ACTIVE],"jobs","watch"),publicSafe:!0}:Z(e,[K.TARGET_INVALID],"jobs","watch"):Z(e,[K.UNSUPPORTED],"jobs","watch")}function si(e){const t=[];let r=!1,n=0;for(;n<e.length;){for(;n<e.length&&/\s/.test(e[n]);)n+=1;if(n>=e.length)break;const o=n;let i="",a=!1,c=null;for(;n<e.length;){const l=e[n];if(c){if(l===c){a=!0,c=null,n+=1;continue}if(l==="\\"&&n+1<e.length){i+=e[n+1],n+=2;continue}i+=l,n+=1;continue}if(/\s/.test(l))break;if(l==='"'||l==="'"){a=!0,c=l,n+=1;continue}i+=l,n+=1}c&&(r=!0),t.push({value:i,start:o,end:n,quoted:a})}return{tokens:t,malformed:r}}function ai(e){if(!e||e.quoted)return;const t=e.value.replace(/^\*/,"").toLowerCase();return t==="goal"||t==="loop"?t:void 0}function ci(e,t){if(!e||e==="jobs"||!t||t.quoted)return;const r=t.value.toLowerCase();return(e==="goal"?ni:oi).has(r)?r:void 0}function di(e){return!e.quoted&&e.value!=="--watch"&&e.value.toLowerCase().startsWith("--watch")}function ui(e){const{tokens:t,malformed:r}=si(e),n=ai(t[0]),o=ci(n,t[1]);if(r)return Z(e,[K.MALFORMED],n,o);const i=t.filter(f=>f.value==="--watch"&&!f.quoted),a=t.filter(f=>f.value==="--watch"&&f.quoted),c=t.filter(di);if(!(i.length>0||a.length>0||c.length>0))return Z(e,[],n,o);if(i.length>1)return Z(e,[K.DUPLICATE],n,o);if(i.length===1&&(a.length>0||c.length>0))return Z(e,[K.AMBIGUOUS],n,o);if(a.length>0)return Z(e,[K.QUOTED],n,o);if(c.length>0)return Z(e,[K.MALFORMED],n,o);const p=i[0];if(!p)return Z(e,[],n,o);if(t[t.length-1]!==p)return Z(e,[K.NON_FINAL],n,o);if(!n||!o)return Z(e,[K.UNRESOLVED],n,o);const m=`${e.slice(0,p.start)}${e.slice(p.end)}`.trim(),w={literal:"--watch",position:"final",start:p.start,end:p.end,quoted:!1,publicSafe:!0};return{args:m,watch:!0,reasonCodes:[K.ACTIVE],metadata:bt(!0,[K.ACTIVE],n,o,w),publicSafe:!0}}function li(e){return jr(e)?ii(e):ui(e)}function pi(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&io.has(t)):[]}function Be(e){return{disabled:!0,reasonCodes:re(e.length>0?e:[X.MISSING])}}function Tt(e,t,r=[],n){const o=He(t);if(o)return{source:e,target:ti(o,r),targetJobId:o.targetId,...n?{initialCursor:n}:{},serverHeldStream:!1}}function fi(e){const t=new Map;for(const r of e){const n=`${r.target.selectorKind}:${r.target.targetId}`,o=t.get(n);if(!o){t.set(n,r);continue}const i=re([...o.target.relatedJobIds??[],...r.target.relatedJobIds??[]]);t.set(n,{...o,target:i.length>0?{...o.target,relatedJobIds:i}:o.target,initialCursor:o.initialCursor??r.initialCursor})}return Array.from(t.values())}function Re(e,t,r,n){return{source:e,hasEvidence:t,candidates:fi(r.filter(o=>!!o)),...n&&n.length>0?{disabledReasonCodes:re(n)}:{}}}function hi(e,t){return e.target.selectorKind===t.target.selectorKind&&e.target.targetId===t.target.targetId}function Fe(e,t){const r=re(e.filter(n=>typeof n=="string").map(n=>ue(n)).filter(n=>!!n));if(t){const n=r.find(o=>Rt(o)===t);if(n)return n}return r[0]}function at(e,t){return re(e.filter(r=>typeof r=="string").map(r=>ue(r)).filter(r=>!!r)).find(r=>Rt(r)===t)}function gi(e){const t=y(e?.continuity)?e.continuity:void 0,r=y(t?.jobs)?t.jobs:void 0,n=y(r?.watcher)?r.watcher:void 0,o=pi(n?.reasonCodes??r?.reasonCodes);if(!n)return Re("watcher-metadata",o.length>0,[],o);if(n.active===!1||o.length>0)return Re("watcher-metadata",!0,[],o.length>0?o:[X.MALFORMED]);if(n.serverHeldStream!==!1)return Re("watcher-metadata",!0,[],[X.SERVER_HELD_STREAM]);const i=ri(n);if(!i)return Re("watcher-metadata",!0,[],[X.MISSING]);const a=typeof n.initialCursor=="string"?n.initialCursor:void 0;return Re("watcher-metadata",!0,[{source:"watcher-metadata",target:i,targetJobId:i.targetId,...a?{initialCursor:a}:{},serverHeldStream:!1}])}function Mr(e,t){const r=y(e.loopJobPlan)?e.loopJobPlan:void 0,n=y(r?.metadata)?r.metadata:void 0,o=y(e.metadata)?e.metadata:void 0,a=(t==="goal"?Fe([e.goalId,e.targetGoalId,e.campaignId,e.jobId,e.targetJobId,o?.goalId,o?.campaignId,o?.jobId],"goal"):Fe([e.loopId,e.targetLoopId,e.jobId,e.targetJobId,o?.loopId,o?.jobId,n?.loopId,n?.jobId],"loop"))??Fe([e.jobId,e.targetJobId,o?.jobId,n?.jobId]);return Tt("goal-loop-continuity-metadata",a,[e.jobId,e.targetJobId,o?.jobId,n?.jobId])}function mi(e){const t=y(e?.continuity)?e.continuity:void 0,r=y(t?.goal)?t.goal:void 0,n=y(t?.loop)?t.loop:void 0,o=[r?Mr(r,"goal"):void 0,n?Mr(n,"loop"):void 0],i=!!(r||n);return Re("goal-loop-continuity-metadata",i,o,i&&o.every(a=>!a)?[X.MISSING]:void 0)}function yi(e){return Array.isArray(e)?e.filter(y):y(e)?Array.isArray(e.operationLogs)?e.operationLogs.filter(y):y(e.operationLog)?[e.operationLog]:Array.isArray(e.operations)?[e]:[]:[]}function Ur(e,t){const r=y(t.metadata)?t.metadata:void 0,n=at([t.goalId,t.targetGoalId,t.campaignId,r?.goalId,r?.campaignId,t.jobId,r?.jobId],"goal"),o=at([t.loopId,t.targetLoopId,r?.loopId,t.jobId,r?.jobId],"loop"),i=Fe([t.jobId,t.targetJobId,r?.jobId],"job"),a=n??o??i;if(!a)return;const c=e.get(a)??{targetId:a,relatedJobIds:[]};c.relatedJobIds.push(...vt([i,t.jobId,t.targetJobId,r?.jobId])),e.set(a,c)}function Ii(e){const t=y(e.metadata)?e.metadata:void 0;return!!(at([e.goalId,e.targetGoalId,e.campaignId,t?.goalId,t?.campaignId,e.jobId,t?.jobId],"goal")??at([e.loopId,e.targetLoopId,t?.loopId,e.jobId,t?.jobId],"loop"))}function Ei(e){const t=y(e.metadata)?e.metadata:void 0;return!!Fe([e.goalId,e.targetGoalId,e.campaignId,e.loopId,e.targetLoopId,e.jobId,e.targetJobId,t?.goalId,t?.campaignId,t?.loopId,t?.jobId])}function Vr(e,t){const r=[];for(const a of["metadata","job","event","receipt","processingOutputSummary"]){const c=t[a];y(c)&&r.push(c)}const n=y(t.event)?t.event:void 0;y(n?.metadata)&&r.push(n.metadata),y(n?.processingOutputSummary)&&r.push(n.processingOutputSummary);const o=y(t.receipt)?t.receipt:void 0;y(o?.metadata)&&r.push(o.metadata);const i=r.some(Ei);for(const a of r)Ur(e,a);(!i||Ii(t))&&Ur(e,t)}function _i(e){const t=yi(e?.continuityStateUpdate),r=new Map;for(const o of t){Vr(r,o);const i=Array.isArray(o.operations)?o.operations.filter(y):[];for(const a of i)Vr(r,a)}const n=Array.from(r.values()).map(o=>Tt("continuity-state-update-operation-log",o.targetId,o.relatedJobIds));return Re("continuity-state-update-operation-log",t.length>0,n,t.length>0&&n.every(o=>!o)?[X.MISSING]:void 0)}function Ci(e){const t=Pr(e);return Re("explicit-args",t.length>0,t.map(r=>Tt("explicit-args",r)))}function Si(e,t){const r=[gi(e),mi(e),_i(e),Ci(t)];for(let n=0;n<r.length;n+=1){const o=r[n];if(!o.hasEvidence)continue;if(o.disabledReasonCodes&&o.disabledReasonCodes.length>0)return Be(o.disabledReasonCodes);if(o.candidates.length!==1)return Be([o.candidates.length>1?X.AMBIGUOUS:X.MISSING]);const i=o.candidates[0];for(const a of r.slice(n+1)){if(!a.hasEvidence)continue;if(a.disabledReasonCodes&&a.disabledReasonCodes.length>0)return Be(a.disabledReasonCodes);if(a.candidates.length>1)return Be([X.AMBIGUOUS]);const c=a.candidates[0];if(c&&!hi(i,c))return Be([X.CONFLICT])}return{target:i.target,targetJobId:i.targetJobId,...i.initialCursor?{initialCursor:i.initialCursor}:{},source:i.source,serverHeldStream:!1}}return Be([X.MISSING])}async function Br(e,t,r,n={}){const i=await We(e,"/api/v1/invoke",t,r,t.privateExecution?{...n,maxAttempts:1,allowReplayRetry:!1}:n);if(i.networkFailure||!i.response)return{ok:!1,status:0,error:"Network error after bounded retries"};const{response:a,text:c,parsed:l}=i;try{if(!a.ok)return t.privateExecution?{ok:!1,status:a.status,error:"private-execution-invoke-unavailable"}:{ok:!1,status:a.status,error:Object.keys(l).length>0?`${l.error_code??"ERROR"}: ${l.message??c}`:`HTTP ${a.status}: ${c}`,errorBody:Object.keys(l).length>0?l:void 0};const p=l,m=a.headers.get("X-Client-Version-Warning");return m&&!wr&&(wr=!0,process.stderr.write(`
|
|
20
|
+
`)}function wt(e){return oo.has(e.status)}function qo(e,t,r){if(t){const o=e.find(i=>i.jobId===t);return!!(o&&wt(o))}return r<=0?!1:e.filter(o=>!wt(o)).length===0}function Ko(e,t,r,n){return r<n?!1:t?!e.some(o=>o.jobId===t&&!wt(o)):e.length===0}function Xo(e,t){return t?.aborted?Promise.resolve():new Promise(r=>{const n=setTimeout(o,e);function o(){clearTimeout(n),t?.removeEventListener("abort",o),r()}t?.addEventListener("abort",o,{once:!0})})}function Zo(e){return e.includes(X.MALFORMED)?"malformed":e.includes(X.AMBIGUOUS)?"ambiguous":e.includes("watch-target-multiple")?"multiple":e.includes("watch-evidence-unsafe")?"unsafe":e.includes(X.MISSING)||e.includes(Y.TARGET_UNRESOLVED)?"unresolved":"unavailable"}function Lr(e,t){const r=t?He(t):void 0,n=re([...e,Y.TARGET_UNRESOLVED,x.WATCH_TARGET_UNRESOLVED]),o=At(r,r?.targetId,Zo(n),n),i=Ie({generatedAt:new Date().toISOString()},[],!1,0,[x.WATCH_TARGET_UNRESOLVED]),a=pe(void 0,void 0,void 0,[],[x.WATCH_TARGET_UNRESOLVED],"unavailable");return fe({watchStatus:"blocked",active:!1,targetEvidence:o,snapshotEvidence:i,cursorEvidence:a,stopReason:"target_unresolved",reasonCodes:n,generatedAt:i.generatedAt})}function Qo(e,t,r,n,o=!1){const i=Lr(e,Dr(t));return he(i,r,n,o),Ee("target-unresolved",0,0,i,o)}async function ei(e){if(e.signal?.aborted){const h=At(e.target??He(e.targetJobId),e.targetJobId,e.target??e.targetJobId?"resolved":"unresolved",[Y.CANCELLED]),R=Ie(void 0,[],!1,0),_=pe(e.initialCursor,e.initialCursor,e.initialCursor,[],[Y.CANCELLED],"unavailable"),V=fe({watchStatus:"stopped",active:!1,targetEvidence:h,snapshotEvidence:R,cursorEvidence:_,stopReason:"cancelled",reasonCodes:[Y.CANCELLED]});return Ee("cancelled",0,0,V,e.protectedOutput)}const t=e.target??He(e.targetJobId),r=e.targetJobId??t?.targetId,n=e.stdout??process.stdout;if(!t){const h=Lr([X.MISSING,Y.TARGET_UNRESOLVED]);return he(h,e.format,n,e.protectedOutput),Ee("target-unresolved",0,0,h,e.protectedOutput)}const o=it(e.limit??st("NEOCORTEX_INVOKE_WATCH_LIMIT",Wt),Wt,50),i=Math.max(50,it(e.pollIntervalMs??st("NEOCORTEX_INVOKE_WATCH_POLL_INTERVAL_MS",Gt),Gt,6e4)),a=it(e.maxIdlePolls??st("NEOCORTEX_INVOKE_WATCH_MAX_IDLE_POLLS",Ht),Ht,120),c=it(e.maxPolls??st("NEOCORTEX_INVOKE_WATCH_MAX_POLLS",Ft),Ft,86400),l=e.sleep??Xo;let p=e.initialCursor,m=0,w=0,f=0;const d=At(t,r,"resolved",[x.OK]),I={schemaVersion:1,contractVersion:"continuity-v1",snapshotStatus:"pending",renderedSummaryCount:0,reasonCodes:[x.WATCH_RENDER_PENDING],publicSafe:!0},A=pe(e.initialCursor,p,p,[],e.initialCursor?[x.WATCH_CURSOR_UNCHANGED]:[x.WATCH_NO_SUMMARIES_YET],e.initialCursor?"unchanged":"not_started");he(fe({watchStatus:"active",active:!0,targetEvidence:d,snapshotEvidence:I,cursorEvidence:A,stopReason:"not_stopped",reasonCodes:[x.OK]}),e.format,n,e.protectedOutput);let C;try{C=await gn({projectRoot:e.projectRoot,strictReadOnly:e.strictReadOnly})}catch{const h=Ie(void 0,[],!1,m,[x.WATCH_SNAPSHOT_UNAVAILABLE]),R=pe(e.initialCursor,p,p,[],[x.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),_=fe({watchStatus:"blocked",active:!1,targetEvidence:d,snapshotEvidence:h,cursorEvidence:R,stopReason:"unavailable_evidence",reasonCodes:[Y.STORE_UNAVAILABLE]});return he(_,e.format,n,e.protectedOutput),Ee("store-unavailable",m,f,_,e.protectedOutput)}try{for(;!e.signal?.aborted&&f<c;){f+=1;const h=p,R=C.collectProcessingOutputSummaryCursor({...p?{cursor:p}:{},...t?{target:t}:{},...r?{jobId:r}:{},limit:o}),_=C.collectSnapshot({jobLimit:50,processingSummaryLimit:1}),V=_.jobs;if(R.summaries.length>0){for(const $ of R.summaries)zo($,e.format,n,e.protectedOutput),m+=1;p=R.nextCursor??R.summaries[R.summaries.length-1]?.cursor??p,w=0}else p=R.nextCursor??p,w+=1;const N=Ie(_,R.summaries,!0,R.summaries.length),P=pe(e.initialCursor,h,p,R.summaries,R.summaries.length>0?[x.WATCH_CURSOR_ADVANCED]:[x.WATCH_NO_SUMMARIES_YET]);if(he(fe({watchStatus:R.summaries.length>0?"polling":"waiting",active:!0,targetEvidence:d,snapshotEvidence:N,cursorEvidence:P,stopReason:"not_stopped",reasonCodes:R.summaries.length>0?[x.WATCH_CURSOR_ADVANCED]:[x.WATCH_NO_SUMMARIES_YET],generatedAt:_.generatedAt}),e.format,n,e.protectedOutput),!R.hasMore&&qo(V,r,m)){const $=Ie(_,R.summaries,!1,m,[Y.COMPLETED]),D=pe(e.initialCursor,h,p,R.summaries,[Y.COMPLETED],"exhausted"),O=fe({watchStatus:"stopped",active:!1,targetEvidence:d,snapshotEvidence:$,cursorEvidence:D,stopReason:"not_stopped",reasonCodes:[Y.COMPLETED],generatedAt:_.generatedAt});return he(O,e.format,n,e.protectedOutput),Ee("completed",m,f,O,e.protectedOutput)}if(!R.hasMore&&Ko(V,r,w,a)){const $=Ie(_,R.summaries,!1,m,[x.WATCH_STOP_IDLE_LIMIT_REACHED]),D=pe(e.initialCursor,h,p,R.summaries,[x.WATCH_STOP_IDLE_LIMIT_REACHED],"exhausted"),O=fe({watchStatus:"stopped",active:!1,targetEvidence:d,snapshotEvidence:$,cursorEvidence:D,stopReason:"idle_limit_reached",reasonCodes:[Y.IDLE_TIMEOUT,x.WATCH_STOP_IDLE_LIMIT_REACHED],generatedAt:_.generatedAt});return he(O,e.format,n,e.protectedOutput),Ee("idle-timeout",m,f,O,e.protectedOutput)}R.hasMore||await l(i,e.signal)}}catch{const h=Ie(void 0,[],!1,m,[x.WATCH_SNAPSHOT_UNAVAILABLE]),R=pe(e.initialCursor,p,p,[],[x.WATCH_EVIDENCE_UNAVAILABLE],"unavailable"),_=fe({watchStatus:"blocked",active:!1,targetEvidence:d,snapshotEvidence:h,cursorEvidence:R,stopReason:"unavailable_evidence",reasonCodes:[Y.STORE_UNAVAILABLE]});return he(_,e.format,n,e.protectedOutput),Ee("store-unavailable",m,f,_,e.protectedOutput)}finally{C.close()}if(e.signal?.aborted){const h=Ie(void 0,[],!1,m,[Y.CANCELLED]),R=pe(e.initialCursor,p,p,[],[Y.CANCELLED],"unavailable"),_=fe({watchStatus:"stopped",active:!1,targetEvidence:d,snapshotEvidence:h,cursorEvidence:R,stopReason:"cancelled",reasonCodes:[Y.CANCELLED]});return he(_,e.format,n,e.protectedOutput),Ee("cancelled",m,f,_,e.protectedOutput)}const j=Ie(void 0,[],!1,m,[x.WATCH_STOP_MAX_POLLS_REACHED]),v=pe(e.initialCursor,p,p,[],[x.WATCH_STOP_MAX_POLLS_REACHED],"exhausted"),U=fe({watchStatus:"stopped",active:!1,targetEvidence:d,snapshotEvidence:j,cursorEvidence:v,stopReason:"max_polls_reached",reasonCodes:[Y.MAX_POLLS,x.WATCH_STOP_MAX_POLLS_REACHED]});return he(U,e.format,n,e.protectedOutput),Ee("max-polls",m,f,U,e.protectedOutput)}function ue(e){const t=e.trim().replace(/^@/,"").match(/^(job|goal|loop)-([JGL])(\d{3,})$/i);if(!t)return;const r=t[1].toLowerCase(),n=t[2].toUpperCase();if(!(r==="job"&&n!=="J"||r==="goal"&&n!=="G"||r==="loop"&&n!=="L"))return`${r}-${n}${t[3]}`}function Rt(e){if(e.startsWith("job-J"))return"job";if(e.startsWith("goal-G"))return"goal";if(e.startsWith("loop-L"))return"loop"}function Pr(e){const t=[],r=/(?:^|[\s"'([,{])@?(job-[Jj]\d{3,}|goal-[Gg]\d{3,}|loop-[Ll]\d{3,})(?=$|[\s"')\]},.;:!?])/g;let n;for(;(n=r.exec(e))!==null;){const o=ue(n[1]);o&&t.push(o)}return re(t)}function Dr(e){return Pr(e)[0]}function He(e){const t=e?ue(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 vt(e){return re(e.filter(t=>typeof t=="string").map(t=>ue(t)).filter(t=>!!t?.startsWith("job-J")))}function ti(e,t){const r=vt(t).filter(n=>n!==e.targetId&&n!==e.jobId);return r.length>0?{...e,relatedJobIds:r}:e}function ri(e){if(!e)return;const t=y(e.target)?e.target:void 0,r=typeof e.selectorKind=="string"?e.selectorKind:typeof t?.selectorKind=="string"?t.selectorKind:void 0,n=typeof e.targetId=="string"?ue(e.targetId):typeof t?.targetId=="string"?ue(t.targetId):typeof e.targetJobId=="string"?ue(e.targetJobId):void 0,o=He(n);if(!o||r&&r!==o.selectorKind)return;const i=Array.isArray(e.relatedJobIds)?e.relatedJobIds:Array.isArray(t?.relatedJobIds)?t.relatedJobIds:void 0,a=vt([...i??[],e.jobId,t?.jobId,e.targetJobId,t?.targetJobId]).filter(c=>c!==o.targetId&&c!==o.jobId);return{...o,...typeof(e.jobId??t?.jobId)=="string"?{jobId:ue(e.jobId??t?.jobId)??o.jobId}:{},...typeof(e.goalId??t?.goalId)=="string"?{goalId:ue(e.goalId??t?.goalId)??o.goalId}:{},...typeof(e.loopId??t?.loopId)=="string"?{loopId:ue(e.loopId??t?.loopId)??o.loopId}:{},...a.length>0?{relatedJobIds:a}:{}}}function jr(e){const t=e.trim().split(/\s+/).filter(Boolean),r=t[0]?.replace(/^\*/,"").toLowerCase(),n=t[1]?.replace(/^--/,"").toLowerCase();return(r==="jobs"||r==="job"||r==="continuity-jobs"||r==="61")&&n==="watch"}const K=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"}),ni=new Set(["create","start","resume"]),oi=new Set(["create","resume","run-once"]);function bt(e,t,r,n,o){return{schemaVersion:1,contractVersion:"continuity-v1",...r?{command:r}:{},...n?{operation:n}:{},active:e,...o?{watchToken:o}:{},reasonCodes:re(t),serverHeldStream:!1,allJobsPolling:!1,targetResolution:e?"required-after-dispatch":"inactive",publicSafe:!0}}function Z(e,t=[],r,n){const o=t.length>0?t:[K.INACTIVE];return{args:e,watch:!1,reasonCodes:o,metadata:bt(!1,o,r,n),publicSafe:!0}}function ii(e){const t=e.trim().split(/\s+/).filter(Boolean),r=t.slice(2).filter(i=>i==="--watch").length;if(r===0)return Z(e,[],"jobs","watch");if(r!==1)return Z(e,[K.AMBIGUOUS],"jobs","watch");const n=t.filter((i,a)=>a<2||i!=="--watch").join(" ");return jr(n)?n.trim().split(/\s+/).filter(Boolean).slice(2).length!==1?Z(e,[K.AMBIGUOUS],"jobs","watch"):Dr(n)?{args:n,watch:!0,reasonCodes:[K.ACTIVE],metadata:bt(!0,[K.ACTIVE],"jobs","watch"),publicSafe:!0}:Z(e,[K.TARGET_INVALID],"jobs","watch"):Z(e,[K.UNSUPPORTED],"jobs","watch")}function si(e){const t=[];let r=!1,n=0;for(;n<e.length;){for(;n<e.length&&/\s/.test(e[n]);)n+=1;if(n>=e.length)break;const o=n;let i="",a=!1,c=null;for(;n<e.length;){const l=e[n];if(c){if(l===c){a=!0,c=null,n+=1;continue}if(l==="\\"&&n+1<e.length){i+=e[n+1],n+=2;continue}i+=l,n+=1;continue}if(/\s/.test(l))break;if(l==='"'||l==="'"){a=!0,c=l,n+=1;continue}i+=l,n+=1}c&&(r=!0),t.push({value:i,start:o,end:n,quoted:a})}return{tokens:t,malformed:r}}function ai(e){if(!e||e.quoted)return;const t=e.value.replace(/^\*/,"").toLowerCase();return t==="goal"||t==="loop"?t:void 0}function ci(e,t){if(!e||e==="jobs"||!t||t.quoted)return;const r=t.value.toLowerCase();return(e==="goal"?ni:oi).has(r)?r:void 0}function di(e){return!e.quoted&&e.value!=="--watch"&&e.value.toLowerCase().startsWith("--watch")}function ui(e){const{tokens:t,malformed:r}=si(e),n=ai(t[0]),o=ci(n,t[1]);if(r)return Z(e,[K.MALFORMED],n,o);const i=t.filter(f=>f.value==="--watch"&&!f.quoted),a=t.filter(f=>f.value==="--watch"&&f.quoted),c=t.filter(di);if(!(i.length>0||a.length>0||c.length>0))return Z(e,[],n,o);if(i.length>1)return Z(e,[K.DUPLICATE],n,o);if(i.length===1&&(a.length>0||c.length>0))return Z(e,[K.AMBIGUOUS],n,o);if(a.length>0)return Z(e,[K.QUOTED],n,o);if(c.length>0)return Z(e,[K.MALFORMED],n,o);const p=i[0];if(!p)return Z(e,[],n,o);if(t[t.length-1]!==p)return Z(e,[K.NON_FINAL],n,o);if(!n||!o)return Z(e,[K.UNRESOLVED],n,o);const m=`${e.slice(0,p.start)}${e.slice(p.end)}`.trim(),w={literal:"--watch",position:"final",start:p.start,end:p.end,quoted:!1,publicSafe:!0};return{args:m,watch:!0,reasonCodes:[K.ACTIVE],metadata:bt(!0,[K.ACTIVE],n,o,w),publicSafe:!0}}function li(e){return jr(e)?ii(e):ui(e)}function pi(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&io.has(t)):[]}function Be(e){return{disabled:!0,reasonCodes:re(e.length>0?e:[X.MISSING])}}function Tt(e,t,r=[],n){const o=He(t);if(o)return{source:e,target:ti(o,r),targetJobId:o.targetId,...n?{initialCursor:n}:{},serverHeldStream:!1}}function fi(e){const t=new Map;for(const r of e){const n=`${r.target.selectorKind}:${r.target.targetId}`,o=t.get(n);if(!o){t.set(n,r);continue}const i=re([...o.target.relatedJobIds??[],...r.target.relatedJobIds??[]]);t.set(n,{...o,target:i.length>0?{...o.target,relatedJobIds:i}:o.target,initialCursor:o.initialCursor??r.initialCursor})}return Array.from(t.values())}function Re(e,t,r,n){return{source:e,hasEvidence:t,candidates:fi(r.filter(o=>!!o)),...n&&n.length>0?{disabledReasonCodes:re(n)}:{}}}function hi(e,t){return e.target.selectorKind===t.target.selectorKind&&e.target.targetId===t.target.targetId}function Fe(e,t){const r=re(e.filter(n=>typeof n=="string").map(n=>ue(n)).filter(n=>!!n));if(t){const n=r.find(o=>Rt(o)===t);if(n)return n}return r[0]}function at(e,t){return re(e.filter(r=>typeof r=="string").map(r=>ue(r)).filter(r=>!!r)).find(r=>Rt(r)===t)}function gi(e){const t=y(e?.continuity)?e.continuity:void 0,r=y(t?.jobs)?t.jobs:void 0,n=y(r?.watcher)?r.watcher:void 0,o=pi(n?.reasonCodes??r?.reasonCodes);if(!n)return Re("watcher-metadata",o.length>0,[],o);if(n.active===!1||o.length>0)return Re("watcher-metadata",!0,[],o.length>0?o:[X.MALFORMED]);if(n.serverHeldStream!==!1)return Re("watcher-metadata",!0,[],[X.SERVER_HELD_STREAM]);const i=ri(n);if(!i)return Re("watcher-metadata",!0,[],[X.MISSING]);const a=typeof n.initialCursor=="string"?n.initialCursor:void 0;return Re("watcher-metadata",!0,[{source:"watcher-metadata",target:i,targetJobId:i.targetId,...a?{initialCursor:a}:{},serverHeldStream:!1}])}function Mr(e,t){const r=y(e.loopJobPlan)?e.loopJobPlan:void 0,n=y(r?.metadata)?r.metadata:void 0,o=y(e.metadata)?e.metadata:void 0,a=(t==="goal"?Fe([e.goalId,e.targetGoalId,e.campaignId,e.jobId,e.targetJobId,o?.goalId,o?.campaignId,o?.jobId],"goal"):Fe([e.loopId,e.targetLoopId,e.jobId,e.targetJobId,o?.loopId,o?.jobId,n?.loopId,n?.jobId],"loop"))??Fe([e.jobId,e.targetJobId,o?.jobId,n?.jobId]);return Tt("goal-loop-continuity-metadata",a,[e.jobId,e.targetJobId,o?.jobId,n?.jobId])}function mi(e){const t=y(e?.continuity)?e.continuity:void 0,r=y(t?.goal)?t.goal:void 0,n=y(t?.loop)?t.loop:void 0,o=[r?Mr(r,"goal"):void 0,n?Mr(n,"loop"):void 0],i=!!(r||n);return Re("goal-loop-continuity-metadata",i,o,i&&o.every(a=>!a)?[X.MISSING]:void 0)}function yi(e){return Array.isArray(e)?e.filter(y):y(e)?Array.isArray(e.operationLogs)?e.operationLogs.filter(y):y(e.operationLog)?[e.operationLog]:Array.isArray(e.operations)?[e]:[]:[]}function Ur(e,t){const r=y(t.metadata)?t.metadata:void 0,n=at([t.goalId,t.targetGoalId,t.campaignId,r?.goalId,r?.campaignId,t.jobId,r?.jobId],"goal"),o=at([t.loopId,t.targetLoopId,r?.loopId,t.jobId,r?.jobId],"loop"),i=Fe([t.jobId,t.targetJobId,r?.jobId],"job"),a=n??o??i;if(!a)return;const c=e.get(a)??{targetId:a,relatedJobIds:[]};c.relatedJobIds.push(...vt([i,t.jobId,t.targetJobId,r?.jobId])),e.set(a,c)}function Ii(e){const t=y(e.metadata)?e.metadata:void 0;return!!(at([e.goalId,e.targetGoalId,e.campaignId,t?.goalId,t?.campaignId,e.jobId,t?.jobId],"goal")??at([e.loopId,e.targetLoopId,t?.loopId,e.jobId,t?.jobId],"loop"))}function Ei(e){const t=y(e.metadata)?e.metadata:void 0;return!!Fe([e.goalId,e.targetGoalId,e.campaignId,e.loopId,e.targetLoopId,e.jobId,e.targetJobId,t?.goalId,t?.campaignId,t?.loopId,t?.jobId])}function Vr(e,t){const r=[];for(const a of["metadata","job","event","receipt","processingOutputSummary"]){const c=t[a];y(c)&&r.push(c)}const n=y(t.event)?t.event:void 0;y(n?.metadata)&&r.push(n.metadata),y(n?.processingOutputSummary)&&r.push(n.processingOutputSummary);const o=y(t.receipt)?t.receipt:void 0;y(o?.metadata)&&r.push(o.metadata);const i=r.some(Ei);for(const a of r)Ur(e,a);(!i||Ii(t))&&Ur(e,t)}function _i(e){const t=yi(e?.continuityStateUpdate),r=new Map;for(const o of t){Vr(r,o);const i=Array.isArray(o.operations)?o.operations.filter(y):[];for(const a of i)Vr(r,a)}const n=Array.from(r.values()).map(o=>Tt("continuity-state-update-operation-log",o.targetId,o.relatedJobIds));return Re("continuity-state-update-operation-log",t.length>0,n,t.length>0&&n.every(o=>!o)?[X.MISSING]:void 0)}function Ci(e){const t=Pr(e);return Re("explicit-args",t.length>0,t.map(r=>Tt("explicit-args",r)))}function Si(e,t){const r=[gi(e),mi(e),_i(e),Ci(t)];for(let n=0;n<r.length;n+=1){const o=r[n];if(!o.hasEvidence)continue;if(o.disabledReasonCodes&&o.disabledReasonCodes.length>0)return Be(o.disabledReasonCodes);if(o.candidates.length!==1)return Be([o.candidates.length>1?X.AMBIGUOUS:X.MISSING]);const i=o.candidates[0];for(const a of r.slice(n+1)){if(!a.hasEvidence)continue;if(a.disabledReasonCodes&&a.disabledReasonCodes.length>0)return Be(a.disabledReasonCodes);if(a.candidates.length>1)return Be([X.AMBIGUOUS]);const c=a.candidates[0];if(c&&!hi(i,c))return Be([X.CONFLICT])}return{target:i.target,targetJobId:i.targetJobId,...i.initialCursor?{initialCursor:i.initialCursor}:{},source:i.source,serverHeldStream:!1}}return Be([X.MISSING])}async function Br(e,t,r,n={}){const i=await We(e,"/api/v1/invoke",t,r,t.privateExecution?{...n,maxAttempts:1,allowReplayRetry:!1}:n);if(i.networkFailure||!i.response)return{ok:!1,status:0,error:"Network error after bounded retries"};const{response:a,text:c,parsed:l}=i;try{if(!a.ok)return t.privateExecution?{ok:!1,status:a.status,error:"private-execution-invoke-unavailable"}:{ok:!1,status:a.status,error:Object.keys(l).length>0?`${l.error_code??"ERROR"}: ${l.message??c}`:`HTTP ${a.status}: ${c}`,errorBody:Object.keys(l).length>0?l:void 0};const p=l,m=a.headers.get("X-Client-Version-Warning");return m&&!wr&&(wr=!0,process.stderr.write(`
|
|
21
21
|
[Neocortex] ${m}
|
|
22
22
|
|
|
23
|
-
`)),{ok:!0,status:a.status,data:p}}catch(p){return{ok:!1,status:0,error:(p instanceof Error?p.message:String(p)).includes("abort")?`Request timeout after ${er/1e3}s`:"Network error: invalid response"}}}async function Ai(e,t,r){const n=await We(e,"/api/v1/invoke/private-execution/consume",t,r,{maxAttempts:1,allowReplayRetry:!1});if(n.networkFailure||!n.response||!n.response.ok)throw new Error("private-execution-delivery-unavailable");return n.parsed}async function Is(e,t,r){const n=await We(e,"/api/v1/invoke/private-execution/cancel",t,r,{maxAttempts:1,allowReplayRetry:!1});return!!n.response?.ok&&n.parsed.status==="cancelled"}async function wi(e,t,r,n={}){const o=await We(e,"/api/v1/invoke/epic-claims/acknowledge",{...r,registryVersion:xe,registryChecksum:Oe},t,n);return!!o.response?.ok&&o.parsed.status==="ok"&&o.parsed.claimOutcome===r.status}async function Ri(e,t,r,n,o,i={}){if(!o)return 0;const a=Qe(e);let c=0;for(const[l,p]of Object.entries(a.operations))!p.claimId||!p.epicId||!t.epics?.[p.epicId]||!await wi(r,n,{claimId:p.claimId,projectId:o,epicId:p.epicId,status:"materialized"},i)||(to(e,l),c+=1);return c}function vi(e,t){const r=t.state.pendingContinuationAuthorities,n=t.state.continuationSession;if(t.state.continuationPolicy!=="p205-finite-resume-v2"||r?.length!==1||!n)return;const o=r[0],i=o.certificate,a=i?.expectedTransition;if(o.storyIds!=="[CIRCULAR]"||i?.rank!=="[CIRCULAR]"||a?.selectedStoryIds!=="[CIRCULAR]")return;const c=typeof n.epicId=="string"?n.epicId:"",l=e.epics[c],p=Array.isArray(a.storyLifecycle)?a.storyLifecycle:[],m=p.length===1&&typeof p[0]?.storyId=="string"?p[0].storyId:"",f=e.stories[m]?.checkpoint;if(!l||l.branch_mode!=="epic"||typeof l.execution_branch!="string"||typeof l.origin_branch!="string"||l.branch_lease!==void 0&&l.branch_lease!==null||!f||f.qaVerdict!=="passed"||f.reviewVerdict!=="approved"||!Array.isArray(f.receiptRefs))return;const I=(Array.isArray(l.stories)?l.stories.filter(A=>typeof A=="string"):[]).find(A=>{const C=e.stories[A];return!C||["done","completed","merged"].includes(String(C.status))?!1:(Array.isArray(C.depends_on)?C.depends_on.filter(v=>typeof v=="string"):[]).every(v=>["done","completed","merged"].includes(String(e.stories[v]?.status)))});if(I)return{epicId:c,expectedNextStoryId:I,branchMode:"epic",executionBranch:l.execution_branch,originBranch:l.origin_branch,branchLeaseReleased:!0,checkpoint:{schemaVersion:1,storyId:f.storyId,epicId:f.epicId,branch:f.branch,baseSha:f.baseSha,headSha:f.headSha,receiptRefs:[...f.receiptRefs],qaVerdict:"passed",reviewVerdict:"approved"}}}async function bi(e){let t;try{if(t=e.inputEnvelope??qe(e.inputSource??"args",e.args),Tn(t),t.rawArgs!==e.args)throw new Error("INVOKE_INPUT_ENVELOPE_ARGUMENT_CONFLICT")}catch{return{success:!1,error:"INVOCATION_MALFORMED_INPUT: explicit input integrity could not be verified.",errorCode:"INVOCATION_MALFORMED_INPUT",metadata:{invocationInput:{reason:"input-integrity-conflict",remediation:"Retry with exactly one of --args, --stdin or --args-file.",publicSafe:!0}},exitCode:1}}const r=t.rawArgs,n=qt(t);let o=r,i=n;const a=no(r);if(a.outcome!=="resolved"){const s=xn(a,"client"),u=a.outcome==="malformed_input"?a.reason==="input_limit"||a.reason==="token_limit"||a.reason==="token_size_limit"?"input-limit-exceeded":a.reason==="invalid_control"||a.reason==="invalid_surrogate"?"invalid-control-character":a.reason==="unterminated_quote"||a.reason==="trailing_escape"||a.reason==="unsupported_escape"?"unterminated-quote":void 0:void 0,g=u?{code:"INVOCATION_MALFORMED_INPUT",reason:u,source:t.source,byteLength:t.byteLength,remediation:u==="input-limit-exceeded"?"Reduce the explicit command input or split the requested work into bounded invocations.":u==="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_${a.outcome.toUpperCase()}`,errorCode:`INVOCATION_${a.outcome.toUpperCase()}`,metadata:{invocationAdmission:s,...g?{invocationInput:g}:{}},exitCode:1}}const c=gt(e.projectRoot),l=a.selection.commandId,p=tn.find(s=>s.id===l),m=p?.subcommands.find(s=>s.id===a.selection.operationId),w=m?m.policy.strictReadOnly==="allow":p?.policy.strictReadOnly==="allow",f=l==="diagnose";let d;try{d=Rn({invocationId:dt(),intent:e.strictReadOnly||f?{schemaVersion:1,policy:Sn,registryVersion:xe,registryChecksum:Oe}:void 0,registryVersion:xe,registryChecksum:Oe,registryAllowsStrict:w,requestCanonicalBytes:JSON.stringify({command:l})})}catch(s){if(s instanceof Me)return{success:!1,error:s.code,errorCode:s.code,exitCode:1};throw s}{d.beginProjection();for(const s of zt)d.project(s);for(const s of An)d.project(s);d.seal()}const I=d.mode==="strict";if(l==="create-epic")try{const s=jn(c);if(s&&s!=="finalized")return{success:!1,error:'PROJECT_IDENTITY_MIGRATION_INCOMPLETE: retry `neocortex-client invoke --args "*migrate-project-id"` before create-epic.',errorCode:"PROJECT_IDENTITY_MIGRATION_INCOMPLETE",metadata:{projectIdentityMigration:{phase:s,publicSafe:!0}},exitCode:1}}catch(s){const u=s instanceof lt?s.code:"PROJECT_IDENTITY_MIGRATION_STATE_CORRUPT";return{success:!1,error:u,errorCode:u,exitCode:1}}const A=e.environment??process.env;if(e.privateExecutionBeta&&(l!=="yolo"&&l!=="research"&&l!=="exec"&&l!=="create-epic"||I||e.platformTarget!==void 0&&e.platformTarget!=="codex"))return{success:!1,error:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",errorCode:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",exitCode:1};const C=En({cwd:c,env:A,targetFlag:e.privateExecutionBeta?"codex":e.platformTarget}),j=C.targetId,v=e.privateExecutionBeta?void 0:In({cwd:c,env:A,targetFlag:e.platformTarget,nativeHostVersion:po(C,A)},C);l!=="migrate-project-id"&&d.execute({phase:"client-preflight",domain:"client-persistence",category:"first-run-marker",operation:"create"},()=>ro(),()=>{});const U=To(d),h=(e.serverUrl??U?.serverUrl??rn).replace(/\/+$/,"");if(l==="migrate-project-id"){const s=await Mn(h);if(!s.supported)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_CAPABILITY_UNAVAILABLE: the server did not advertise the versioned migration capability; no local state was changed.",errorCode:"PROJECT_IDENTITY_MIGRATION_CAPABILITY_UNAVAILABLE",metadata:{projectIdentityMigrationCapability:s},exitCode:1};const u=[];let g;try{g=Dn(c)}catch(b){const ee=b instanceof lt?b.code:"PROJECT_IDENTITY_MIGRATION_PREPARE_FAILED";return{success:!1,error:ee,errorCode:ee,exitCode:1}}u.push(Ue({phase:"prepare",outcome:g.changed&&g.document.phase==="prepared"?"prepared":"retry",floor:g.document.legacyEpicFloor,licenseId:"local-client",projectId:g.document.projectId}));const T=Cr(c);if(T.config.project_id!==g.document.projectId)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",errorCode:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",metadata:{invocationDiagnostics:u},exitCode:1};const G=await Ar(h,U?.licenseKey,d);if(G.status!=="authenticated"){const b=G.status==="refresh-required";return{success:!1,error:b?"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:b?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",metadata:{invocationDiagnostics:u},exitCode:b?1:2}}let ae;try{ae=Bt(e.args.trim(),T)}catch(b){const ee=b instanceof $t?b.code:"PROJECT_IDENTITY_MIGRATION_PROJECTION_FAILED";return{success:!1,error:ee,errorCode:ee,metadata:{invocationDiagnostics:u},exitCode:1}}let le={args:r,projectRoot:c.replace(De(),"~"),stateSnapshot:ae,platformTarget:j,...v?{nativeHostAttestation:v}:{},projectId:g.document.projectId,projectIdentityMigration:g.request,inputEvidence:n,idempotencyKey:g.document.operationId,registryVersion:xe,registryChecksum:Oe};try{le=Or(le).body}catch(b){if(b instanceof It||b instanceof Et)return{success:!1,error:b.message,errorCode:b.code,metadata:{invokePayload:b.telemetry,invocationDiagnostics:u},exitCode:1};throw b}const z=await Jt("invoke-query",()=>Br(h,le,G.token,{refreshToken:()=>G.client.forceRefresh()}));if(!z.ok||!z.data)return u.push(Ue({phase:"seed",outcome:"rejected",floor:g.document.legacyEpicFloor,licenseId:"local-client",projectId:g.document.projectId})),{success:!1,error:de(z.error??"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",ke),errorCode:typeof z.errorBody?.error_code=="string"?z.errorBody.error_code:"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",metadata:{invocationDiagnostics:u},exitCode:z.status===401?2:1};const Q=z.data.metadata?.projectIdentityMigration;try{On(Q),u.push(Ue({phase:"seed",outcome:Q.status,floor:Q.acceptedLegacyFloor,licenseId:"local-client",projectId:Q.projectId})),Ln(c,Q),u.push(Ue({phase:"remote-acknowledged",outcome:Q.status,floor:Q.acceptedLegacyFloor,licenseId:"local-client",projectId:Q.projectId})),Pn(c,Q),u.push(Ue({phase:"finalize",outcome:"finalized",floor:Q.acceptedLegacyFloor,licenseId:"local-client",projectId:Q.projectId}))}catch(b){u.push(Ue({phase:"reconcile",outcome:"rejected",floor:g.document.legacyEpicFloor,licenseId:"local-client",projectId:g.document.projectId}));const ee=b instanceof lt?b.code:b instanceof Error?b.message:"PROJECT_IDENTITY_MIGRATION_RECEIPT_INVALID";return{success:!1,error:ee,errorCode:ee,metadata:{invocationDiagnostics:u},exitCode:1}}return d.complete(),{success:!0,instructions:z.data.instructions,metadata:{...z.data.metadata,invocationDiagnostics:u},exitCode:0}}try{const{normalizeYoloopTargetArgs:s}=await import("../yoloop/target-normalization.js"),u=s(e.args,{projectRoot:c});if(!u.ok)return process.stderr.write(`${u.message} reason=${u.reasonCode}
|
|
23
|
+
`)),{ok:!0,status:a.status,data:p}}catch(p){return{ok:!1,status:0,error:(p instanceof Error?p.message:String(p)).includes("abort")?`Request timeout after ${er/1e3}s`:"Network error: invalid response"}}}async function Ai(e,t,r){const n=await We(e,"/api/v1/invoke/private-execution/consume",t,r,{maxAttempts:1,allowReplayRetry:!1});if(n.networkFailure||!n.response||!n.response.ok)throw new Error("private-execution-delivery-unavailable");return n.parsed}async function Is(e,t,r){const n=await We(e,"/api/v1/invoke/private-execution/cancel",t,r,{maxAttempts:1,allowReplayRetry:!1});return!!n.response?.ok&&n.parsed.status==="cancelled"}async function wi(e,t,r,n={}){const o=await We(e,"/api/v1/invoke/epic-claims/acknowledge",{...r,registryVersion:xe,registryChecksum:Oe},t,n);return!!o.response?.ok&&o.parsed.status==="ok"&&o.parsed.claimOutcome===r.status}async function Ri(e,t,r,n,o,i={}){if(!o)return 0;const a=Qe(e);let c=0;for(const[l,p]of Object.entries(a.operations))!p.claimId||!p.epicId||!t.epics?.[p.epicId]||!await wi(r,n,{claimId:p.claimId,projectId:o,epicId:p.epicId,status:"materialized"},i)||(to(e,l),c+=1);return c}function vi(e,t){const r=t.state.pendingContinuationAuthorities,n=t.state.continuationSession;if(t.state.continuationPolicy!=="p205-finite-resume-v2"||r?.length!==1||!n)return;const o=r[0],i=o.certificate,a=i?.expectedTransition;if(o.storyIds!=="[CIRCULAR]"||i?.rank!=="[CIRCULAR]"||a?.selectedStoryIds!=="[CIRCULAR]")return;const c=typeof n.epicId=="string"?n.epicId:"",l=e.epics[c],p=Array.isArray(a.storyLifecycle)?a.storyLifecycle:[],m=p.length===1&&typeof p[0]?.storyId=="string"?p[0].storyId:"",f=e.stories[m]?.checkpoint;if(!l||l.branch_mode!=="epic"||typeof l.execution_branch!="string"||typeof l.origin_branch!="string"||l.branch_lease!==void 0&&l.branch_lease!==null||!f||f.qaVerdict!=="passed"||f.reviewVerdict!=="approved"||!Array.isArray(f.receiptRefs))return;const I=(Array.isArray(l.stories)?l.stories.filter(A=>typeof A=="string"):[]).find(A=>{const C=e.stories[A];return!C||["done","completed","merged"].includes(String(C.status))?!1:(Array.isArray(C.depends_on)?C.depends_on.filter(v=>typeof v=="string"):[]).every(v=>["done","completed","merged"].includes(String(e.stories[v]?.status)))});if(I)return{epicId:c,expectedNextStoryId:I,branchMode:"epic",executionBranch:l.execution_branch,originBranch:l.origin_branch,branchLeaseReleased:!0,checkpoint:{schemaVersion:1,storyId:f.storyId,epicId:f.epicId,branch:f.branch,baseSha:f.baseSha,headSha:f.headSha,receiptRefs:[...f.receiptRefs],qaVerdict:"passed",reviewVerdict:"approved"}}}async function bi(e){let t;try{if(t=e.inputEnvelope??qe(e.inputSource??"args",e.args),Tn(t),t.rawArgs!==e.args)throw new Error("INVOKE_INPUT_ENVELOPE_ARGUMENT_CONFLICT")}catch{return{success:!1,error:"INVOCATION_MALFORMED_INPUT: explicit input integrity could not be verified.",errorCode:"INVOCATION_MALFORMED_INPUT",metadata:{invocationInput:{reason:"input-integrity-conflict",remediation:"Retry with exactly one of --args, --stdin or --args-file.",publicSafe:!0}},exitCode:1}}const r=t.rawArgs,n=qt(t);let o=r,i=n;const a=no(r);if(a.outcome!=="resolved"){const s=xn(a,"client"),u=a.outcome==="malformed_input"?a.reason==="input_limit"||a.reason==="token_limit"||a.reason==="token_size_limit"?"input-limit-exceeded":a.reason==="invalid_control"||a.reason==="invalid_surrogate"?"invalid-control-character":a.reason==="unterminated_quote"||a.reason==="trailing_escape"||a.reason==="unsupported_escape"?"unterminated-quote":void 0:void 0,g=u?{code:"INVOCATION_MALFORMED_INPUT",reason:u,source:t.source,byteLength:t.byteLength,remediation:u==="input-limit-exceeded"?"Reduce the explicit command input or split the requested work into bounded invocations.":u==="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_${a.outcome.toUpperCase()}`,errorCode:`INVOCATION_${a.outcome.toUpperCase()}`,metadata:{invocationAdmission:s,...g?{invocationInput:g}:{}},exitCode:1}}const c=gt(e.projectRoot),l=a.selection.commandId,p=tn.find(s=>s.id===l),m=p?.subcommands.find(s=>s.id===a.selection.operationId),w=m?m.policy.strictReadOnly==="allow":p?.policy.strictReadOnly==="allow",f=l==="diagnose";let d;try{d=Rn({invocationId:dt(),intent:e.strictReadOnly||f?{schemaVersion:1,policy:Sn,registryVersion:xe,registryChecksum:Oe}:void 0,registryVersion:xe,registryChecksum:Oe,registryAllowsStrict:w,requestCanonicalBytes:JSON.stringify({command:l})})}catch(s){if(s instanceof Me)return{success:!1,error:s.code,errorCode:s.code,exitCode:1};throw s}{d.beginProjection();for(const s of zt)d.project(s);for(const s of An)d.project(s);d.seal()}const I=d.mode==="strict";if(l==="create-epic")try{const s=jn(c);if(s&&s!=="finalized")return{success:!1,error:'PROJECT_IDENTITY_MIGRATION_INCOMPLETE: retry `neocortex-client invoke --args "*migrate-project-id"` before create-epic.',errorCode:"PROJECT_IDENTITY_MIGRATION_INCOMPLETE",metadata:{projectIdentityMigration:{phase:s,publicSafe:!0}},exitCode:1}}catch(s){const u=s instanceof lt?s.code:"PROJECT_IDENTITY_MIGRATION_STATE_CORRUPT";return{success:!1,error:u,errorCode:u,exitCode:1}}const A=e.environment??process.env;if(e.privateExecutionBeta&&(l!=="yolo"&&l!=="research"&&l!=="write-spec"&&l!=="exec"&&l!=="create-epic"||I||e.platformTarget!==void 0&&e.platformTarget!=="codex"))return{success:!1,error:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",errorCode:"PRIVATE_EXECUTION_BETA_UNSUPPORTED",exitCode:1};const C=En({cwd:c,env:A,targetFlag:e.privateExecutionBeta?"codex":e.platformTarget}),j=C.targetId,v=e.privateExecutionBeta?void 0:In({cwd:c,env:A,targetFlag:e.platformTarget,nativeHostVersion:po(C,A)},C);l!=="migrate-project-id"&&d.execute({phase:"client-preflight",domain:"client-persistence",category:"first-run-marker",operation:"create"},()=>ro(),()=>{});const U=To(d),h=(e.serverUrl??U?.serverUrl??rn).replace(/\/+$/,"");if(l==="migrate-project-id"){const s=await Mn(h);if(!s.supported)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_CAPABILITY_UNAVAILABLE: the server did not advertise the versioned migration capability; no local state was changed.",errorCode:"PROJECT_IDENTITY_MIGRATION_CAPABILITY_UNAVAILABLE",metadata:{projectIdentityMigrationCapability:s},exitCode:1};const u=[];let g;try{g=Dn(c)}catch(b){const ee=b instanceof lt?b.code:"PROJECT_IDENTITY_MIGRATION_PREPARE_FAILED";return{success:!1,error:ee,errorCode:ee,exitCode:1}}u.push(Ue({phase:"prepare",outcome:g.changed&&g.document.phase==="prepared"?"prepared":"retry",floor:g.document.legacyEpicFloor,licenseId:"local-client",projectId:g.document.projectId}));const T=Cr(c);if(T.config.project_id!==g.document.projectId)return{success:!1,error:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",errorCode:"PROJECT_IDENTITY_MIGRATION_STATE_DRIFT",metadata:{invocationDiagnostics:u},exitCode:1};const G=await Ar(h,U?.licenseKey,d);if(G.status!=="authenticated"){const b=G.status==="refresh-required";return{success:!1,error:b?"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:b?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",metadata:{invocationDiagnostics:u},exitCode:b?1:2}}let ae;try{ae=Bt(e.args.trim(),T)}catch(b){const ee=b instanceof $t?b.code:"PROJECT_IDENTITY_MIGRATION_PROJECTION_FAILED";return{success:!1,error:ee,errorCode:ee,metadata:{invocationDiagnostics:u},exitCode:1}}let le={args:r,projectRoot:c.replace(De(),"~"),stateSnapshot:ae,platformTarget:j,...v?{nativeHostAttestation:v}:{},projectId:g.document.projectId,projectIdentityMigration:g.request,inputEvidence:n,idempotencyKey:g.document.operationId,registryVersion:xe,registryChecksum:Oe};try{le=Or(le).body}catch(b){if(b instanceof It||b instanceof Et)return{success:!1,error:b.message,errorCode:b.code,metadata:{invokePayload:b.telemetry,invocationDiagnostics:u},exitCode:1};throw b}const z=await Jt("invoke-query",()=>Br(h,le,G.token,{refreshToken:()=>G.client.forceRefresh()}));if(!z.ok||!z.data)return u.push(Ue({phase:"seed",outcome:"rejected",floor:g.document.legacyEpicFloor,licenseId:"local-client",projectId:g.document.projectId})),{success:!1,error:de(z.error??"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",ke),errorCode:typeof z.errorBody?.error_code=="string"?z.errorBody.error_code:"PROJECT_IDENTITY_MIGRATION_REMOTE_FAILED",metadata:{invocationDiagnostics:u},exitCode:z.status===401?2:1};const Q=z.data.metadata?.projectIdentityMigration;try{On(Q),u.push(Ue({phase:"seed",outcome:Q.status,floor:Q.acceptedLegacyFloor,licenseId:"local-client",projectId:Q.projectId})),Ln(c,Q),u.push(Ue({phase:"remote-acknowledged",outcome:Q.status,floor:Q.acceptedLegacyFloor,licenseId:"local-client",projectId:Q.projectId})),Pn(c,Q),u.push(Ue({phase:"finalize",outcome:"finalized",floor:Q.acceptedLegacyFloor,licenseId:"local-client",projectId:Q.projectId}))}catch(b){u.push(Ue({phase:"reconcile",outcome:"rejected",floor:g.document.legacyEpicFloor,licenseId:"local-client",projectId:g.document.projectId}));const ee=b instanceof lt?b.code:b instanceof Error?b.message:"PROJECT_IDENTITY_MIGRATION_RECEIPT_INVALID";return{success:!1,error:ee,errorCode:ee,metadata:{invocationDiagnostics:u},exitCode:1}}return d.complete(),{success:!0,instructions:z.data.instructions,metadata:{...z.data.metadata,invocationDiagnostics:u},exitCode:0}}try{const{normalizeYoloopTargetArgs:s}=await import("../yoloop/target-normalization.js"),u=s(e.args,{projectRoot:c});if(!u.ok)return process.stderr.write(`${u.message} reason=${u.reasonCode}
|
|
24
24
|
`),{success:!1,error:u.message,exitCode:1};u.changed&&(e={...e,args:u.args},process.stderr.write(`[Neocortex] yoloop target normalized: ${u.reasonCodes.join(",")}
|
|
25
25
|
`))}catch{const s="INVALID_YOLOOP_TARGET: yoloop target normalization was unavailable; no request was sent.";return process.stderr.write(`${s}
|
|
26
26
|
`),{success:!1,error:s,exitCode:1}}const R=Er(l);if(R)try{_r(c,{allowMissingRuntime:!0}).runtimeMissing&&(await d.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},async()=>Bn(c),async()=>{}),_r(c))}catch(s){const u=s instanceof we?s.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${u}. No request was sent; repair the canonical project state and retry.
|
|
27
27
|
`),{success:!1,error:u,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}try{d.execute({phase:"client-preflight",domain:"client-persistence",category:"state-repair",operation:"update"},()=>dn(c,{args:e.args,canonicalCommandId:l}),()=>{})}catch(s){if(s instanceof un)return process.stderr.write(`${s.message}
|
|
28
28
|
`),{success:!1,error:s.message,exitCode:1};const u=s instanceof Error?s.message:String(s);return process.stderr.write(`[Neocortex] state.json repair stopped unexpectedly: ${u}. No request was sent; inspect .neocortex/state.json and rerun.
|
|
29
|
-
`),{success:!1,error:u,exitCode:1}}let
|
|
29
|
+
`),{success:!1,error:u,exitCode:1}}let _;try{const s=await wo(c,e.args,l);_=Cr(c,{epicAware:R,p205Authorities:s})}catch(s){const u=s instanceof we?s.reasonCode:"git-lifecycle-state-corrupt";return process.stderr.write(`[Neocortex] ${u}. No request was sent; repair the canonical project state/runtime sidecar and retry.
|
|
30
30
|
`),{success:!1,error:u,errorCode:"GIT_LIFECYCLE_STATE_INVALID",exitCode:1}}try{const{maybeAutoResolveYoloopArgs:s}=await import("../yoloop/invoke-hooks.js"),u={args:e.args,projectRoot:c,logger:{info:g=>process.stderr.write(`${g}
|
|
31
31
|
`),warn:g=>process.stderr.write(`${g}
|
|
32
32
|
`)}};s(u),u.args!==e.args&&(e={...e,args:u.args},o=u.args,i=qt(qe(t.source,o)))}catch(s){const u=s instanceof Error?s.message:String(s);process.stderr.write(`[Neocortex] Auto-resolve hook (P121.05) failed: ${u}. Proceeding with raw args.
|
|
33
|
-
`)}try{const{readYoloopForRequest:s}=await import("../yoloop/invoke-hooks.js"),u=await s(e.args,c);if(u){const g=vi(
|
|
34
|
-
`),{success:!1,error:g,errorCode:g,exitCode:1}}}try{const{readContinuityForRequest:s}=await import("../continuity/invoke-hooks.js"),u=await s(e.args,c,void 0,d,{includeExistingStore:!f});u&&(
|
|
35
|
-
`)}try{const{maybeRunDiscoveryHook:s}=await import("../yoloop/invoke-hooks.js");await s({args:e.args,projectRoot:c,stateSnapshot:
|
|
36
|
-
`)}try{const{readArchitecturePolicy:s}=await import("../policy/architecture-policy.js"),u=await s(c);u&&(
|
|
37
|
-
`)}});g.applied&&g.metadata&&(
|
|
38
|
-
`)}try{if(co(e.args)){const{collectProjectEvidence:s}=await import("../evidence/collector.js"),u=a.selection.uiUxReview?.architectureDir,g=s({projectRoot:c,...u?{candidatePaths:[u],includeFallbackInventory:!0}:{}});(g.evidence.length>0||g.exclusions.length>0)&&(
|
|
39
|
-
`)}try{const s=await d.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"checkpoint-consume",operation:"consume"},async()=>{const{readAndConsumeCheckpoint:u}=await import("../checkpoint/index.js");return u(c)},async()=>{});s&&(
|
|
40
|
-
`)}const V=U?.licenseKey?new ut({cacheDir:pt,passphrase:U.licenseKey,strictReadOnly:I}):null,N=o.trim();if(!N&&V){const s=await d.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>Ro(V),async()=>null);if(s)return d.complete(),{success:!0,instructions:s.instructions,metadata:s.metadata,exitCode:0}}const P=await Ar(h,U?.licenseKey,d);if(P.status!=="authenticated"){const s=P.status==="refresh-required",u=!s&&U&&!U.licenseKey?" This may be caused by a machine fingerprint change (e.g., hardware or hostname change).":"";try{const g=Vt(),T=Mt(s?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",g);T&&process.stderr.write(Ut(T,g))}catch{}return{success:!1,error:s?"Authentication refresh required. Run: neocortex activate YOUR-LICENSE-KEY":`Not authenticated.${u} Visit https://neocortex.sh/portal/login to get your license key, then run: neocortex activate YOUR-LICENSE-KEY`,errorCode:s?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",exitCode:s?1:2}}const $=
|
|
41
|
-
`),{success:!1,error:s.message??"Trigger not available on your plan",exitCode:1}}catch{}const O=await Wo({args:N,projectRoot:c,platformTarget:j,environment:e.environment??process.env,bootstrapper:e.runnerBootstrapper,effectAuthority:d});if(O.attachToRequest&&(
|
|
33
|
+
`)}try{const{readYoloopForRequest:s}=await import("../yoloop/invoke-hooks.js"),u=await s(e.args,c);if(u){const g=vi(_,u);_.yoloop=g?{...u,continuationRecoveryEvidence:g}:u}}catch(s){if(/^\s*\*?(?:yoloop|auto-yolo|epic-runner|story-runner|loop-yolo|auto-epic)\b/i.test(e.args)){const g=s instanceof Error?s.message.match(/\bYOLOOP_[A-Z0-9_]+\b/)?.[0]??"YOLOOP_STATE_READ_FAILED":"YOLOOP_STATE_READ_FAILED";return process.stderr.write(`[Neocortex] ${g}. No yoloop request was sent and no state was mutated.
|
|
34
|
+
`),{success:!1,error:g,errorCode:g,exitCode:1}}}try{const{readContinuityForRequest:s}=await import("../continuity/invoke-hooks.js"),u=await s(e.args,c,void 0,d,{includeExistingStore:!f});u&&(_.continuity=u)}catch(s){if(s instanceof Me)return{success:!1,error:s.code,errorCode:s.code,exitCode:1};const u=s instanceof Error?s.message:String(s);process.stderr.write(`[Neocortex] continuity snapshot hook failed: ${u}. Proceeding without continuity state.
|
|
35
|
+
`)}try{const{maybeRunDiscoveryHook:s}=await import("../yoloop/invoke-hooks.js");await s({args:e.args,projectRoot:c,stateSnapshot:_,featureFlag:process.env.YOLOOP_AUTO_DISCOVERY!=="off",logger:{warn:u=>{console.warn(u)},info:u=>{console.error(u)}}})}catch(s){const u=s instanceof Error?s.message:String(s);process.stderr.write(`[Neocortex] discovery hook failed: ${u}. Proceeding without enrichment.
|
|
36
|
+
`)}try{const{readArchitecturePolicy:s}=await import("../policy/architecture-policy.js"),u=await s(c);u&&(_.architecture_policy=u)}catch(s){const u=s instanceof Error?s.message:String(s);console.warn(`[Neocortex] architecture-policy hook failed: ${u}. Proceeding without policy.`)}try{const s=/^(1|true|on|yes)$/i.test(process.env.NEOCORTEX_GRAPH_RETRIEVAL??""),{maybeRunGraphRetrievalHook:u}=await import("../yoloop/invoke-hooks.js"),g=await u({args:e.args,projectRoot:c,featureFlag:s,logger:{warn:T=>process.stderr.write(`${T}
|
|
37
|
+
`)}});g.applied&&g.metadata&&(_.graphRetrieval=g.metadata)}catch(s){const u=s instanceof Error?s.message:String(s);process.stderr.write(`[Neocortex] graph retrieval hook failed: ${u}. Proceeding without enrichment.
|
|
38
|
+
`)}try{if(co(e.args)){const{collectProjectEvidence:s}=await import("../evidence/collector.js"),u=a.selection.uiUxReview?.architectureDir,g=s({projectRoot:c,...u?{candidatePaths:[u],includeFallbackInventory:!0}:{}});(g.evidence.length>0||g.exclusions.length>0)&&(_.projectEvidence=g)}}catch(s){const u=s instanceof Error?s.message:String(s);process.stderr.write(`[Neocortex] project evidence collection failed: ${u}. Proceeding without local project evidence.
|
|
39
|
+
`)}try{const s=await d.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"checkpoint-consume",operation:"consume"},async()=>{const{readAndConsumeCheckpoint:u}=await import("../checkpoint/index.js");return u(c)},async()=>{});s&&(_.implementCheckpoint=s)}catch(s){const u=s instanceof Error?s.message:String(s);process.stderr.write(`[Neocortex] checkpoint hook failed: ${u}. Proceeding without checkpoint.
|
|
40
|
+
`)}const V=U?.licenseKey?new ut({cacheDir:pt,passphrase:U.licenseKey,strictReadOnly:I}):null,N=o.trim();if(!N&&V){const s=await d.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>Ro(V),async()=>null);if(s)return d.complete(),{success:!0,instructions:s.instructions,metadata:s.metadata,exitCode:0}}const P=await Ar(h,U?.licenseKey,d);if(P.status!=="authenticated"){const s=P.status==="refresh-required",u=!s&&U&&!U.licenseKey?" This may be caused by a machine fingerprint change (e.g., hardware or hostname change).":"";try{const g=Vt(),T=Mt(s?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",g);T&&process.stderr.write(Ut(T,g))}catch{}return{success:!1,error:s?"Authentication refresh required. Run: neocortex activate YOUR-LICENSE-KEY":`Not authenticated.${u} Visit https://neocortex.sh/portal/login to get your license key, then run: neocortex activate YOUR-LICENSE-KEY`,errorCode:s?"AUTH_REFRESH_REQUIRED":"NOT_CONFIGURED",exitCode:s?1:2}}const $=_.config.project_id;try{await d.executeAsync({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>Ri(c,_,h,P.token,$,{refreshToken:()=>P.client.forceRefresh()}),async()=>0)}catch{}const D=Ti(N);if(D&&!f)try{const s=await P.tierClient.preFlightCheck(D);if(!s.allowed)return process.stderr.write(`[neocortex] ${s.message}
|
|
41
|
+
`),{success:!1,error:s.message??"Trigger not available on your plan",exitCode:1}}catch{}const O=await Wo({args:N,projectRoot:c,platformTarget:j,environment:e.environment??process.env,bootstrapper:e.runnerBootstrapper,effectAuthority:d});if(O.attachToRequest&&(_.runnerBootstrap=O.metadata),O.warning&&process.stderr.write(`[Neocortex] ${O.warning}
|
|
42
42
|
`),!O.shouldContinue)return O.error&&process.stderr.write(`[Neocortex] ${O.error}
|
|
43
|
-
`),{success:!1,error:O.error??"Runner auto-bootstrap required but failed.",errorCode:O.errorCode,exitCode:O.exitCode??1};let J;try{const s=an(N,
|
|
44
|
-
`),{success:!1,error:u,errorCode:s.code,metadata:{stateProjection:s,publicSafe:!0},exitCode:1}}J=s?.snapshot??Bt(N,
|
|
43
|
+
`),{success:!1,error:O.error??"Runner auto-bootstrap required but failed.",errorCode:O.errorCode,exitCode:O.exitCode??1};let J;try{const s=an(N,_);if(s&&!s.ok){const u=`${s.code}: structural projection failed closed; select a valid target or repair the dependency DAG.`;return process.stderr.write(`${u}
|
|
44
|
+
`),{success:!1,error:u,errorCode:s.code,metadata:{stateProjection:s,publicSafe:!0},exitCode:1}}J=s?.snapshot??Bt(N,_)}catch(s){if(s instanceof $t){const u=`${s.code}: structural projection failed closed; select a valid target or repair the dependency DAG.`;return process.stderr.write(`${u}
|
|
45
45
|
`),{success:!1,error:u,errorCode:s.code,metadata:{structuralProjection:{...s.publicDetails,publicSafe:!0}},exitCode:1}}throw s}if(!I)try{const{openNativeAgentPrivateStore:s,resolveNativeAgentPrivateRuntimePaths:u}=await import("../continuity/native-agent-store.js"),g=u(c);if(Pe(g.databasePath)){const T=await s(c);try{const G=T.store.listRecentNativeAgentDispatches(20);G.length>0&&(J.nativeAgentDispatches=G)}finally{T.store.close()}}}catch{}const ve=Dt(N),_e=$;if(ve==="create-epic"&&!_e){const s='EPIC_PROJECT_ID_REQUIRED: run `neocortex-client invoke --args "*migrate-project-id"` and retry create-epic. No repository checkout or database credentials are required.';return process.stderr.write(`${s}
|
|
46
46
|
`),{success:!1,error:s,errorCode:"EPIC_PROJECT_ID_REQUIRED",exitCode:1}}let ge;try{ge=d.execute({phase:"client-preflight",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>ve==="create-epic"?eo(c,N):void 0,()=>{})}catch{return{success:!1,error:"EPIC_CLAIM_INTEGRITY_FAILURE",errorCode:"EPIC_CLAIM_INTEGRITY_FAILURE",exitCode:1}}const Ge=ge?.key,be=I?{schemaVersion:1,invocationId:d.invocationId,intent:d.intent,clientProjection:wn(zt.map(s=>({...s,count:1})))}:void 0;let W;if(e.privateExecutionBeta)try{const{preflightPrivateCodexExecutor:s}=await import("../private-execution/codex-executor.js");W=await s(c)}catch(s){const u=s instanceof Error&&/^private-codex-[a-z-]+$/.test(s.message)?s.message:"private-codex-preflight-unavailable";return{success:!1,error:u,errorCode:u,exitCode:1}}const Ye=W?{schemaVersion:1,hostKind:"codex-cli",hostVersion:W.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:W.observedAtMs}}:void 0;let H={args:o,projectRoot:c.replace(De(),"~"),stateSnapshot:J,platformTarget:j,...v?{nativeHostAttestation:v}:{},...Ye?{privateExecution:Ye}:{},projectId:_e,inputEvidence:i,idempotencyKey:Ge,registryVersion:xe,registryChecksum:Oe,...be?{strictReadOnly:be}:{}};const Hr=Ve(H);if(!I&&e.inputSource&&e.inputSource!=="args"&&Hr>=ft)try{H={argsRef:(await Cn(d,"secondary-mutation",()=>Do(h,o,P.token,()=>P.client.forceRefresh()),async()=>{throw new Me("readonly-physical-boundary-unsafe","boundary")})).argsRef,projectRoot:c.replace(De(),"~"),stateSnapshot:J,platformTarget:j,...v?{nativeHostAttestation:v}:{},...Ye?{privateExecution:Ye}:{},projectId:_e,inputEvidence:i,idempotencyKey:Ge,registryVersion:xe,registryChecksum:Oe,...be?{strictReadOnly:be}:{}}}catch(s){return s instanceof Me?{success:!1,error:s.code,errorCode:s.code,exitCode:1}:{success:!1,error:`INVOKE_MATERIALIZATION_FAILED: ${s instanceof Error?s.message:String(s)}`,errorCode:"INVOKE_MATERIALIZATION_FAILED",exitCode:1}}if(ve==="yolo"&&J.scope?.projectionMode==="yolo-story"){const s=J.scope?.targetStoryId,u=J.scope?.targetEpicId;if(!s||!u)return{success:!1,error:"yolo-spec-envelope-target-mismatch",errorCode:"yolo-spec-envelope-target-mismatch",exitCode:1};try{const{collectYoloSpecEnvelope:g}=await import("../yolo/spec-envelope-collector.js"),T=g({projectRoot:c,storyId:s,epicId:u,inputSha256:i.sha256});if(/\sbranchless-preparation\s*$/.test(o))H={...H,yoloSpecEnvelope:T};else{const{collectYoloChangeEvidence:G}=await import("../yolo/change-evidence-collector.js"),ae=G({projectRoot:c,defaultBranch:J.config.default_branch,expectedHeadSha:T.sourceRevision.headSha});H={...H,yoloSpecEnvelope:T,yoloChangeEvidence:ae}}}catch(g){const T=g instanceof Error&&/^yolo-(?:spec-envelope|change-evidence)-[a-z-]+$/.test(g.message)?g.message:"yolo-spec-envelope-unsafe";return{success:!1,error:T,errorCode:T,exitCode:1}}}try{const s=Or(H);H=s.body,s.degraded?kr(H,s.telemetry):$o(H)}catch(s){if(s instanceof It||s instanceof Et)return kr(H,s.telemetry),process.stderr.write(`[Neocortex] ${s.message}
|
|
47
|
-
`),{success:!1,error:s.message,errorCode:s.code,metadata:{invokePayload:s.telemetry},exitCode:1};throw s}if(ve==="yolo"&&H.yoloSpecEnvelope)try{const{collectYoloSpecEnvelope:s}=await import("../yolo/spec-envelope-collector.js"),u=s({projectRoot:c,storyId:H.yoloSpecEnvelope.storyId,epicId:H.yoloSpecEnvelope.epicId,inputSha256:i.sha256,collectedAt:H.yoloSpecEnvelope.collectedAt});if(u.envelopeSha256!==H.yoloSpecEnvelope.envelopeSha256)throw new Error("yolo-spec-envelope-stale");if(H.yoloChangeEvidence){const{collectYoloChangeEvidence:g}=await import("../yolo/change-evidence-collector.js"),T=g({projectRoot:c,defaultBranch:J.config.default_branch,expectedHeadSha:u.sourceRevision.headSha});if(T.pathsSha256!==H.yoloChangeEvidence.pathsSha256||T.baseSha!==H.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}}let
|
|
47
|
+
`),{success:!1,error:s.message,errorCode:s.code,metadata:{invokePayload:s.telemetry},exitCode:1};throw s}if(ve==="yolo"&&H.yoloSpecEnvelope)try{const{collectYoloSpecEnvelope:s}=await import("../yolo/spec-envelope-collector.js"),u=s({projectRoot:c,storyId:H.yoloSpecEnvelope.storyId,epicId:H.yoloSpecEnvelope.epicId,inputSha256:i.sha256,collectedAt:H.yoloSpecEnvelope.collectedAt});if(u.envelopeSha256!==H.yoloSpecEnvelope.envelopeSha256)throw new Error("yolo-spec-envelope-stale");if(H.yoloChangeEvidence){const{collectYoloChangeEvidence:g}=await import("../yolo/change-evidence-collector.js"),T=g({projectRoot:c,defaultBranch:J.config.default_branch,expectedHeadSha:u.sourceRevision.headSha});if(T.pathsSha256!==H.yoloChangeEvidence.pathsSha256||T.baseSha!==H.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}}let E=await Jt("invoke-query",()=>Br(h,H,P.token,{refreshToken:()=>P.client.forceRefresh()})),Ot;if(I&&E.ok)try{if(f){const u=E.data?.metadata;if(u&&["stateUpdate","stateMutated","yoloopStateUpdate","continuityStateUpdate","checkpoint","schedulerStateUpdate","quotaCacheUpdate","projectIdentityMigration","epicClaim","gitLifecycleGraphAuthority"].some(T=>u[T]!==void 0))throw new Me("readonly-response-conflict")}const s=E.data?.metadata.strictReadOnly;vn(d,s),f&&kn(E.data?.metadata.strictDiagnose,r,E.data?.instructions??""),Ot=s.security}catch(s){const u=s instanceof Me?s.code:"readonly-receipt-mismatch";return{success:!1,error:u,errorCode:u,exitCode:1}}if(!E.ok&&E.status===426){const s=E.errorBody,u=s?.upgrade_command??"npm install -g @ornexus/neocortex@latest",g=s?.min_version??"unknown";return process.stderr.write(`
|
|
48
48
|
`),process.stderr.write(`==================================================
|
|
49
49
|
`),process.stderr.write(` UPGRADE REQUIRED
|
|
50
50
|
`),process.stderr.write(`==================================================
|
|
@@ -59,10 +59,10 @@ ${t}
|
|
|
59
59
|
`),process.stderr.write(` After updating, re-run your command.
|
|
60
60
|
`),process.stderr.write(`==================================================
|
|
61
61
|
|
|
62
|
-
`),{success:!1,error:`UPGRADE_REQUIRED: Client version ${je} is below minimum ${g}. Run: ${u}`,exitCode:3}}if(!
|
|
63
|
-
`),{success:!1,error:u,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}catch(s){if(
|
|
64
|
-
`),{success:!1,error:g,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}if(
|
|
65
|
-
`),{success:!1,error:u,errorCode:"GIT_LIFECYCLE_GRAPH_AUTHORITY_INVALID",exitCode:1}}if(
|
|
62
|
+
`),{success:!1,error:`UPGRADE_REQUIRED: Client version ${je} is below minimum ${g}. Run: ${u}`,exitCode:3}}if(!E.ok||!E.data){const s=E.status===401?2:(E.status===429||E.status>=500,1),u=Oo(E);try{if(u){const g=Vt(),T=Mt(u,g);T&&process.stderr.write(Ut(T,g))}}catch{}return{success:!1,error:de(E.error??"Unknown error from server",ke),...u?{errorCode:u}:{},exitCode:s}}if(e.privateExecutionBeta&&!Zr(E.data))return{success:!1,error:"private-execution-public-envelope-invalid",errorCode:"private-execution-public-envelope-invalid",exitCode:1};if(!N&&E.data.metadata?.mode==="menu"&&V&&await d.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"auth-cache",operation:"update"},()=>vo(V,E.data.instructions,E.data.metadata),async()=>{}).catch(()=>{}),E.data.metadata&&await d.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"tier-cache",operation:"update"},()=>P.tierClient.updateQuotaFromResponse(E.data.metadata),async()=>{}).catch(()=>{}),E.data.metadata?.stateMutated===!0)try{const s=await d.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>{const{persistMigratedStateFromResponse:u}=await import("../yoloop/invoke-hooks.js");return u(E.data.metadata,c)},async()=>({applied:!1,blocking:!1,reasonCode:"state-writeback-effect-skipped"}));if(s.blocking){const u=`STATE_WRITEBACK_BLOCKED: ${s.reasonCode}. Canonical state was not replaced.`;return process.stderr.write(`${u}
|
|
63
|
+
`),{success:!1,error:u,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}catch(s){if(E.data.metadata?.stateMutationReason==="inline-yolo-materialized-synthetic-story"){const u=s instanceof Error?s.message:String(s),g=`STATE_WRITEBACK_BLOCKED: inline-yolo persistence failed (${de(u,ke)}).`;return process.stderr.write(`${g}
|
|
64
|
+
`),{success:!1,error:g,errorCode:"STATE_WRITEBACK_BLOCKED",exitCode:1}}}if(E.data.metadata?.gitLifecycleGraphAuthority)try{await d.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},()=>Wn(c,E.data.metadata.gitLifecycleGraphAuthority),async()=>{throw new Error("git-lifecycle-graph-authority-effect-skipped")})}catch(s){const u=s instanceof Error&&/^git-lifecycle-/.test(s.message)?s.message:"git-lifecycle-graph-authority-persist-failed";return process.stderr.write(`[Neocortex] ${u}. Graph authority was not persisted; no YOLO checkpoint instruction was released.
|
|
65
|
+
`),{success:!1,error:u,errorCode:"GIT_LIFECYCLE_GRAPH_AUTHORITY_INVALID",exitCode:1}}if(E.data.metadata?.mode==="error"&&E.data.metadata?.errorCode==="CLIENT_UPGRADE_REQUIRED")return process.stderr.write(`
|
|
66
66
|
`),process.stderr.write(`==================================================
|
|
67
67
|
`),process.stderr.write(` YOLOOP CLIENT UPGRADE REQUIRED
|
|
68
68
|
`),process.stderr.write(`==================================================
|
|
@@ -77,14 +77,14 @@ ${t}
|
|
|
77
77
|
`),process.stderr.write(` After upgrading, re-run your yoloop command.
|
|
78
78
|
`),process.stderr.write(`==================================================
|
|
79
79
|
|
|
80
|
-
`),{success:!1,error:"CLIENT_UPGRADE_REQUIRED: This client does not support yoloop client-side persistence. Run: npm install -g @ornexus/neocortex@latest",exitCode:3};if(
|
|
80
|
+
`),{success:!1,error:"CLIENT_UPGRADE_REQUIRED: This client does not support yoloop client-side persistence. Run: npm install -g @ornexus/neocortex@latest",exitCode:3};if(E.data.metadata?.yoloopStateUpdate){const u=(E.data.metadata.yoloopStateUpdate.operations??[]).some(g=>g.type==="rollover_session");try{const g=await d.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"state-writeback",operation:"update"},async()=>{const{persistYoloopFromResponse:T}=await import("../yoloop/invoke-hooks.js");return T(E.data.metadata,c)},async()=>({ok:!0,authoritative:!1,reasonCodes:[]}));if(g&&g.ok===!1){const T=g.reasonCodes[0]??"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED";return process.stderr.write(`[Neocortex] ${T}. No yoloop continuation instructions were released.
|
|
81
81
|
`),{success:!1,error:T,errorCode:T,exitCode:1}}}catch(g){if(u){const T=g instanceof Error?g.message.match(/\bYOLOOP_[A-Z0-9_]+\b/)?.[0]??"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED":"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED";return process.stderr.write(`[Neocortex] ${T}. No yoloop continuation instructions were released.
|
|
82
|
-
`),{success:!1,error:T,errorCode:T,exitCode:1}}}}if(
|
|
82
|
+
`),{success:!1,error:T,errorCode:T,exitCode:1}}}}if(E.data.metadata?.continuityStateUpdate)try{const s=await d.executeAsync({phase:"client-writeback",domain:"client-persistence",category:"continuity-store",operation:"update"},async()=>{const{persistContinuityFromResponse:u}=await import("../continuity/invoke-hooks.js");return u(E.data.metadata,c)},async()=>({ok:!0,reasonCodes:[]}));if(!s.ok){const u=s.reasonCodes.join(",");return process.stderr.write(`[Neocortex] continuity persistence failed: ${u}. No continuity mutation was committed.
|
|
83
83
|
`),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${u}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}}catch(s){const u=s instanceof Error?s.message:String(s);return process.stderr.write(`[Neocortex] continuity persistence hook failed: ${u}. No continuity mutation was committed.
|
|
84
|
-
`),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${de(u,ke)}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}if(
|
|
84
|
+
`),{success:!1,error:`CONTINUITY_PERSISTENCE_FAILED: ${de(u,ke)}`,errorCode:"CONTINUITY_PERSISTENCE_FAILED",exitCode:1}}if(E.data.metadata?.tier_changed){const s=E.data.metadata.current_tier;try{await P.client.forceRefresh()?(await P.tierClient.invalidateTierCache(),process.stderr.write(`[Neocortex] Token atualizado automaticamente para tier ${s}
|
|
85
85
|
`)):process.stderr.write(`[Neocortex] Seu tier foi atualizado para ${s}! Execute "neocortex activate" para obter um token atualizado.
|
|
86
86
|
`)}catch{process.stderr.write(`[Neocortex] Seu tier foi atualizado para ${s}! Execute "neocortex activate" para obter um token atualizado.
|
|
87
|
-
`)}}let me,xt=!1;if(e.privateExecutionBeta)try{if(!W||!
|
|
87
|
+
`)}}let me,xt=!1;if(e.privateExecutionBeta)try{if(!W||!E.data.metadata?.privateExecution||!_e||E.data.metadata?.mode!=="yolo"&&E.data.metadata?.mode!=="step"&&E.data.metadata?.mode!=="pipeline"&&E.data.metadata?.mode!=="create-epic"||typeof E.data.metadata.stepId!="string")throw new Error("private-execution-descriptor-unavailable");const{consumePrivateExecutionDelivery:s,privateExecutionStateSnapshotSha256:u}=await import("../private-execution/delivery.js"),{preflightPrivateCodexExecutor:g,runPrivateCodexStep:T}=await import("../private-execution/codex-executor.js"),G=E.data.metadata.mode==="yolo",ae=E.data.metadata.mode==="create-epic";let le,z,Q;const b=E.data.metadata.gitLifecycleGraphAuthority,ee=E.data.metadata.privateExecutionRootAction;let Je;if(G){if(!b||typeof b.storyId!="string"||typeof b.graphRevision!="string"||typeof b.executionBranch!="string")throw new Error("private-execution-graph-unavailable");if(Je=b.storyId,ee?.action==="prepare-epic-checkout"){const{prepareDirectYoloSetup:Gr}=await import("../git/direct-yolo-checkpoint.js"),{capturePrivateYoloCleanHead:Yr,recordPrivateYoloCleanBaseline:Jr}=await import("../private-execution/clean-baseline.js"),zr=Yr(c),Nt=await Gr({projectRoot:c,storyId:ee.storyId});if(!Nt.ok)throw new Error("private-execution-root-setup-denied");await Jr(c,Nt.value,zr)}let F;try{F=Le("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:c,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{throw new Error("private-execution-execution-branch-mismatch")}if(F!==b.executionBranch)throw new Error("private-execution-execution-branch-mismatch");const te=Xe(c,{required:!0}),L=typeof b.epicId=="string"?te.epics[b.epicId]:void 0,ce=y(L?.branch_lease)?L.branch_lease:void 0;if(!L||L.graph_revision!==b.graphRevision||!ce||ce.ownerStoryId!==b.storyId||typeof ce.expiresAt!="string"||!Number.isFinite(Date.parse(ce.expiresAt))||Date.parse(ce.expiresAt)<=Date.now())throw new Error("private-execution-writer-lease-unavailable")}else if(E.data.metadata.mode==="step"&&(E.data.metadata.resolvedTrigger==="research"||E.data.metadata.resolvedTrigger==="write-spec")||E.data.metadata.mode==="pipeline"&&E.data.metadata.resolvedTrigger==="exec"||ae&&E.data.metadata.resolvedTrigger==="create-epic"){if(!ae&&typeof E.data.metadata.storyId!="string")throw new Error("private-execution-descriptor-unavailable")}else throw new Error("private-execution-descriptor-unavailable");if(G){const{ensurePrivateYoloIsolatedSession:F,reconcilePrivateYoloIsolatedSession:te}=await import("../private-execution/isolated-session.js");if(ee?.action==="checkpoint-epic-story")await te(c,Je,b.graphRevision);else{const L=await F(c,Je,b.graphRevision,e.privateExecutionWorkspaceParent),ce=await g(L.workspace.workspacePath);if(ce.hostVersion!==W.hostVersion)throw new Error("private-codex-version-drift");W=ce}}if(Date.now()-W.observedAtMs>2e4){const F=await g(W.projectRoot);if(F.hostVersion!==W.hostVersion)throw new Error("private-codex-version-drift");W=F}const kt=await P.client.getToken();if(!kt)throw new Error("private-execution-auth-unavailable");const ye=ae?E.data.metadata.epicClaim:void 0;if(ae&&(!ye||typeof ye.claimId!="string"||typeof ye.epicId!="string"))throw new Error("private-execution-descriptor-unavailable");if(ae){if(!ge)throw new Error("private-execution-epic-claim-admission-unverified");d.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>ar(c,ge.fingerprint,ye.claimId,ye.epicId),()=>{}),xt=!0;const{preparePrivateYoloIsolatedWorkspace:F,PRIVATE_EPIC_PENDING_SIDECAR:te}=await import("../private-execution/isolated-workspace.js"),L=e.privateExecutionWorkspaceParent??ne(De(),".local","share","neocortex","private-epic-workspaces");e.privateExecutionWorkspaceParent||ze(L,{recursive:!0,mode:448}),le=F(c,L,!0),Q=Ne("sha256").update(Te(ne(c,te))).digest("hex");const ce=await g(le.workspacePath);if(ce.hostVersion!==W.hostVersion)throw new Error("private-codex-version-drift");W=ce}else if(!G){const{preparePrivateYoloIsolatedWorkspace:F}=await import("../private-execution/isolated-workspace.js"),te=e.privateExecutionWorkspaceParent??ne(De(),".local","share","neocortex","private-step-workspaces");e.privateExecutionWorkspaceParent||ze(te,{recursive:!0,mode:448}),z=F(c,te);const L=await g(z.workspacePath);if(L.hostVersion!==W.hostVersion)throw new Error("private-codex-version-drift");W=L}const Fr=await s(E.data.metadata.privateExecution,{projectId:_e,commandId:G?"yolo":ae?"create-epic":E.data.metadata.mode==="pipeline"?"exec":E.data.metadata.resolvedTrigger==="write-spec"?"write-spec":"research",stepId:E.data.metadata.stepId,...G?{graphRevision:b.graphRevision}:{...ae?{claimId:ye.claimId,epicId:ye.epicId}:{storyId:E.data.metadata.storyId},stateSnapshotSha256:u(J)},inputSha256:i.sha256,hostKind:"codex-cli",hostVersion:W.hostVersion},F=>Ai(h,{...F},kt));if(ee?.action==="checkpoint-epic-story"){const{runPrivateYoloRootCheckpoint:F}=await import("../private-execution/root-checkpoint.js");me={...await F(c,ee)}}else{const F=await T(Fr,W,{requireWorkspaceEffect:!0,...G?{expectedExecutionBranch:b.executionBranch}:le?{expectedExecutionBranch:le.executionBranch}:z?{expectedExecutionBranch:z.executionBranch}:{}});if(G){const{admitPrivateYoloIsolatedSessionStep:te}=await import("../private-execution/isolated-session.js"),L=await te(c,Je,b.graphRevision);me={...F,isolation:{schemaVersion:1,outcome:L.admission.outcome,sequence:L.session.sequence,snapshotSha:L.session.snapshotSha,patchSha256:L.admission.patchSha256,changedPathCount:L.admission.changedPaths.length}}}else if(le){const{admitPrivateEpicClaimWorkspace:te}=await import("../private-execution/isolated-admission.js"),L=te(le,ye.claimId,ye.epicId,ge.fingerprint,Q);me={...F,isolation:{schemaVersion:1,outcome:L.outcome,baseSha:L.baseSha,patchSha256:L.patchSha256,changedPathCount:L.changedPaths.length}}}else if(z){const{admitPrivateStateBoundStepWorkspace:te}=await import("../private-execution/isolated-admission.js"),L=te(z,E.data.metadata.storyId);me={...F,isolation:{schemaVersion:1,outcome:L.outcome,baseSha:L.baseSha,patchSha256:L.patchSha256,changedPathCount:L.changedPaths.length}}}else me={...F}}}catch(s){const u=s instanceof Error&&/^(private-execution|private-codex)-[a-z-]+$/.test(s.message)?s.message:"private-execution-unverified";return{success:!1,error:u,errorCode:u,exitCode:1}}const ct=yt(E.data.instructions,E.data.metadata);if(ge&&!xt&&E.data.metadata?.mode!=="error")try{const s=E.data.metadata?.epicClaim;if(!s||typeof s!="object"||Array.isArray(s))throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");const u=s;if(u.outcome!=="reserved"||typeof u.claimId!="string"||typeof u.epicId!="string")throw new Error("EPIC_CLAIM_INTEGRITY_FAILURE");d.execute({phase:"client-writeback",domain:"client-persistence",category:"pending-claim",operation:"update"},()=>ar(c,ge.fingerprint,u.claimId,u.epicId),()=>{})}catch{}return d.complete(Ot),{success:!0,instructions:me?me.outcome==="checkpoint-validated"?`# Checkpoint da story validado
|
|
88
88
|
|
|
89
89
|
O root registrou o commit e a valida\xE7\xE3o f\xEDsica no branch do epic.`:`# Execu\xE7\xE3o privada conclu\xEDda; valida\xE7\xE3o f\xEDsica pendente
|
|
90
90
|
|
|
@@ -111,7 +111,7 @@ Options:
|
|
|
111
111
|
--server-url <url> Server URL override
|
|
112
112
|
--platform-target <id> Explicit platform target override (default: runtime detection; unknown on no match)
|
|
113
113
|
--strict-read-only Request exact signed strict-read-only-v1 execution (registry-gated)
|
|
114
|
-
--private-execution-beta Run an explicit *yolo, *exec, *research or *create-epic step through the isolated Codex CLI beta executor
|
|
114
|
+
--private-execution-beta Run an explicit *yolo, *exec, *research, *write-spec or *create-epic step through the isolated Codex CLI beta executor
|
|
115
115
|
|
|
116
116
|
Invocation payload boundary:
|
|
117
117
|
Select only the explicit user-intended Neocortex command and arguments after
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import{createHash as m}from"node:crypto";const g=`# Neocortex private execution pending
|
|
2
2
|
|
|
3
|
-
The authorized Codex CLI executor must consume the one-time delivery and produce a physical receipt.`;function l(r){if(!r||typeof r!="object"||Array.isArray(r))return!1;const o=r,t=o.metadata;if(Object.keys(o).sort().join(",")!=="instructions,metadata"||o.instructions!==g||!t||typeof t!="object"||Array.isArray(t))return!1;const e=t,s=e.privateExecution;let i;try{i=u(s)}catch{return!1}if(i.schemaVersion===2)return Object.keys(e).sort().join(",")===["mode","storyId","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&(e.mode==="step"&&e.resolvedTrigger==="research"&&i.binding.commandId===
|
|
3
|
+
The authorized Codex CLI executor must consume the one-time delivery and produce a physical receipt.`;function l(r){if(!r||typeof r!="object"||Array.isArray(r))return!1;const o=r,t=o.metadata;if(Object.keys(o).sort().join(",")!=="instructions,metadata"||o.instructions!==g||!t||typeof t!="object"||Array.isArray(t))return!1;const e=t,s=e.privateExecution;let i;try{i=u(s)}catch{return!1}if(i.schemaVersion===2)return Object.keys(e).sort().join(",")===["mode","storyId","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&(e.mode==="step"&&(e.resolvedTrigger==="research"||e.resolvedTrigger==="write-spec")&&i.binding.commandId===e.resolvedTrigger||e.mode==="pipeline"&&e.resolvedTrigger==="exec"&&i.binding.commandId==="exec")&&e.storyId===i.binding.storyId&&e.stepId===i.binding.stepId;if(i.schemaVersion===3){const y=e.epicClaim,d=y&&typeof y=="object"&&!Array.isArray(y)?y:void 0;return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution","epicClaim"].sort().join(",")&&e.mode==="create-epic"&&e.resolvedTrigger==="create-epic"&&e.stepId===i.binding.stepId&&i.binding.commandId==="create-epic"&&!!d&&Object.keys(d).sort().join(",")===["schemaVersion","claimId","epicId","outcome","publicSafe"].sort().join(",")&&d.schemaVersion===1&&d.outcome==="reserved"&&d.publicSafe===!0&&d.claimId===i.binding.claimId&&d.epicId===i.binding.epicId}const a=e.privateExecutionRootAction,c=["mode","storyId","stepId","resolvedTrigger","gitLifecycleGraphAuthority","privateExecution",...a===void 0?[]:["privateExecutionRootAction"]],h=e.gitLifecycleGraphAuthority,p=h&&typeof h=="object"&&!Array.isArray(h)?h:void 0,n=a&&typeof a=="object"&&!Array.isArray(a)?a:void 0;return Object.keys(e).sort().join(",")===c.sort().join(",")&&e.mode==="yolo"&&e.resolvedTrigger==="yolo"&&typeof e.storyId=="string"&&typeof e.stepId=="string"&&!!p&&p.storyId===e.storyId&&p.graphRevision===i.binding.graphRevision&&i.binding.commandId==="yolo"&&i.binding.stepId===e.stepId&&(a===void 0||!!n&&Object.keys(n).sort().join(",")===["schemaVersion","action","storyId","executionBranch","graphRevision","publicSafe",...n.action==="checkpoint-epic-story"?["stepId"]:[]].sort().join(",")&&n.schemaVersion===1&&(n.action==="prepare-epic-checkout"||n.action==="checkpoint-epic-story")&&(n.action!=="checkpoint-epic-story"||n.stepId===e.stepId)&&n.publicSafe===!0&&n.storyId===e.storyId&&n.storyId===p.storyId&&n.executionBranch===p.executionBranch&&n.graphRevision===p.graphRevision)}function b(r){return m("sha256").update("private-step-state-v1\0").update(JSON.stringify(r)).digest("hex")}function u(r,o){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("private-execution-descriptor-invalid");const t=r,e=t.binding,s=t.schemaVersion===2||t.schemaVersion===3,i=s?["schemaVersion","authorityKind","projectId","commandId","stepId",...t.schemaVersion===3?["claimId","epicId"]:["storyId"],"stateSnapshotSha256","generationId","inputSha256","hostKind","hostVersion"]:["commandId","generationId","graphRevision","hostKind","hostVersion","inputSha256","projectId","stepId"];if(Object.keys(t).sort().join(",")!==["schemaVersion","leaseId","materialSha256","byteLength","expiresAt","delivery","publicSafe","binding"].sort().join(",")||t.schemaVersion!==1&&!s||t.delivery!=="private-one-time"||t.publicSafe!==!0||typeof t.leaseId!="string"||!/^px_[a-f0-9]{48}$/.test(t.leaseId)||typeof t.materialSha256!="string"||!/^[a-f0-9]{64}$/.test(t.materialSha256)||!Number.isSafeInteger(t.byteLength)||t.byteLength<1||t.byteLength>256*1024||typeof t.expiresAt!="string"||!Number.isFinite(Date.parse(t.expiresAt))||!e||Object.keys(e).sort().join(",")!==i.sort().join(",")||Object.entries(e).some(([a,c])=>a!=="schemaVersion"&&(typeof c!="string"||c.length<1||c.length>256))||!/^[a-f0-9]{64}$/.test(String(e.inputSha256))||e.hostKind!=="codex-cli"||s&&!/^[a-f0-9]{64}$/.test(String(e.stateSnapshotSha256))||t.schemaVersion===2&&(e.schemaVersion!==2||e.authorityKind!=="state-snapshot"||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(String(e.storyId)))||t.schemaVersion===3&&(e.schemaVersion!==3||e.authorityKind!=="epic-claim"||e.commandId!=="create-epic"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(String(e.claimId))||!/^P[1-9][0-9]*$/.test(String(e.epicId)))||o&&Object.entries(o).some(([a,c])=>e[a]!==c))throw new Error("private-execution-descriptor-invalid");return t}function I(r,o,t=Date.now()){if(typeof o!="string"||t>=Date.parse(r.expiresAt)||Buffer.byteLength(o,"utf8")!==r.byteLength||m("sha256").update(o,"utf8").digest("hex")!==r.materialSha256)throw new Error("private-execution-material-invalid");return o}async function v(r,o,t,e=Date.now()){const s=u(r,o);if(e>=Date.parse(s.expiresAt))throw new Error("private-execution-material-expired");const i=await t({leaseId:s.leaseId,...s.binding});if(!i||typeof i!="object"||Array.isArray(i)||Object.keys(i).sort().join(",")!=="material,schemaVersion"||i.schemaVersion!==1)throw new Error("private-execution-delivery-invalid");return I(s,i.material,Math.max(e,Date.now()))}export{g as PRIVATE_EXECUTION_PUBLIC_INSTRUCTION_V1,v as consumePrivateExecutionDelivery,l as isPrivateExecutionPublicEnvelope,u as parsePrivateExecutionDescriptor,b as privateExecutionStateSnapshotSha256,I as verifyPrivateExecutionMaterial};
|
|
@@ -27,7 +27,7 @@ export type YoloopSessionMode = 'directory' | 'epic-file' | 'epic-id';
|
|
|
27
27
|
export type YoloopLockOwnerKind = 'client' | 'server';
|
|
28
28
|
export type YoloopLockOwnerPidState = 'live' | 'stale' | 'unknown';
|
|
29
29
|
export type YoloopLockLeaseState = 'active' | 'expired' | 'unknown';
|
|
30
|
-
export type YoloopPersistenceCapability = 'rollover-session-v1' | 'successor-transition-v1';
|
|
30
|
+
export type YoloopPersistenceCapability = 'rollover-session-v1' | 'successor-transition-v1' | 'continuation-replan-v1';
|
|
31
31
|
/** Lock file payload. Mirrors server-internal `LockMetadata` (v1.1 schema). */
|
|
32
32
|
export interface YoloopPersistedLock {
|
|
33
33
|
readonly pid: number;
|
|
@@ -226,6 +226,8 @@ export interface YoloopPersistedCounters {
|
|
|
226
226
|
readonly pendingContinuationAuthorities?: readonly Readonly<Record<string, unknown>>[];
|
|
227
227
|
readonly continuationReceipts?: readonly Readonly<Record<string, unknown>>[];
|
|
228
228
|
readonly continuationRecoveryReceipts?: readonly Readonly<Record<string, unknown>>[];
|
|
229
|
+
/** Auditable retirement of an undelegated authority when an explicit new run changes the graph. */
|
|
230
|
+
readonly continuationReplanReceipts?: readonly Readonly<Record<string, unknown>>[];
|
|
229
231
|
/**
|
|
230
232
|
* P104.06: FIFO bounded audit trail of self-healing recovery attempts.
|
|
231
233
|
* Optional for backward compat (clients pre-P104.06 omit the field; readers
|
|
@@ -336,6 +338,18 @@ export type YoloopStateOperation = {
|
|
|
336
338
|
readonly payloadHash: string;
|
|
337
339
|
readonly next: YoloopPersistedCounters;
|
|
338
340
|
readonly receipt: YoloopSessionRolloverReceiptV1;
|
|
341
|
+
} | {
|
|
342
|
+
readonly type: 'replan_continuation_session';
|
|
343
|
+
readonly operationId: string;
|
|
344
|
+
readonly idempotencyKey: string;
|
|
345
|
+
readonly expectedRunId: string;
|
|
346
|
+
readonly expectedRevision: number;
|
|
347
|
+
readonly expectedSnapshotHash: string | null;
|
|
348
|
+
readonly expectedSessionHash: string;
|
|
349
|
+
readonly expectedPendingHash: string;
|
|
350
|
+
readonly nextSession: Readonly<Record<string, unknown>>;
|
|
351
|
+
readonly payloadHash: string;
|
|
352
|
+
readonly receipt: Readonly<Record<string, unknown>>;
|
|
339
353
|
} | {
|
|
340
354
|
readonly type: 'recovery_attempted';
|
|
341
355
|
readonly attempt: YoloopRecoveryAttemptRef;
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
* setSecureFilePermissions helper from secure-config.ts.
|
|
24
24
|
*/
|
|
25
25
|
import type { YoloopPersistedCounters, YoloopPersistedState, YoloopRecoveryAttemptRef, YoloopRunControlV1, YoloopRunTransitionReceiptV1, YoloopStateOperation, YoloopStateUpdate } from './shared-yoloop-types.js';
|
|
26
|
-
export declare const YOLOOP_PERSISTENCE_CAPABILITIES: readonly ["rollover-session-v1", "successor-transition-v1"];
|
|
26
|
+
export declare const YOLOOP_PERSISTENCE_CAPABILITIES: readonly ["rollover-session-v1", "successor-transition-v1", "continuation-replan-v1"];
|
|
27
27
|
type YoloopSessionRolloverOperation = Extract<YoloopStateOperation, {
|
|
28
28
|
readonly type: 'rollover_session';
|
|
29
29
|
}>;
|
|
@@ -82,6 +82,7 @@ export declare class YoloopClientStateStore {
|
|
|
82
82
|
private acknowledgeContinuationAuthority;
|
|
83
83
|
private repairContinuationAuthority;
|
|
84
84
|
private switchContinuationPolicy;
|
|
85
|
+
private replanContinuationSession;
|
|
85
86
|
/**
|
|
86
87
|
* Append a new recovery attempt to `state.recovery_history[]`. FIFO cap
|
|
87
88
|
* via `capRecoveryHistory`. Idempotent against retry storms: duplicate
|
|
@@ -168,6 +169,9 @@ export declare class YoloopClientStateStore {
|
|
|
168
169
|
/** Remove `yoloop-state.json.tmp.*` orphans from crashed writes. */
|
|
169
170
|
private cleanupOrphanTempFiles;
|
|
170
171
|
}
|
|
172
|
+
export declare function buildYoloopContinuationReplanPayloadHash(payload: Omit<Extract<YoloopStateOperation, {
|
|
173
|
+
readonly type: 'replan_continuation_session';
|
|
174
|
+
}>, 'type' | 'payloadHash' | 'receipt'>): string;
|
|
171
175
|
export declare function fingerprintYoloopSession(session: NonNullable<YoloopPersistedCounters['currentSession']>): string;
|
|
172
176
|
export declare function buildYoloopSessionRolloverPayloadHash(operation: Omit<YoloopSessionRolloverOperation, 'type' | 'payloadHash' | 'receipt'>): string;
|
|
173
177
|
export declare function buildYoloopSuccessorRunPayloadHash(operation: Omit<Extract<YoloopStateOperation, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{promises as u}from"node:fs";import{createHash as b}from"node:crypto";import{join as _,dirname as V}from"node:path";import{hostname as S}from"node:os";import{setSecureFilePermissions as $,setSecureDirPermissions as q}from"../config/secure-config.js";import{RECOVERY_HISTORY_CAP as C}from"./shared-yoloop-types.js";const B=".neocortex",g="yoloop-state.json",j="yoloop.lock",J="yoloop-state.mutation.lock",P="yoloop-session-rollover.json",A="yoloop-successor-transition.json",z=360*60*1e3,W=3e4,G=200,x=Object.freeze(["rollover-session-v1","successor-transition-v1"]),X={warn:()=>{},info:()=>{},error:()=>{}};function w(t){const e=t.slice(0,10);return{version:"1.1",lastResetAt:t,storiesRunToday:0,iterationsToday:0,iterationsTodayDate:e,tokensUsedToday:0,lastRunAt:null,coolDownUntil:null,totalRunsAllTime:0,totalStoriesAllTime:0,currentSession:null,continuationPolicy:"p205-finite-resume-v2",pendingContinuationAuthorities:[],continuationReceipts:[],continuationRecoveryReceipts:[]}}function we(t){return{lock:null,state:w(t),capabilities:x}}class fe{stateDir;statePath;lockPath;mutationLockPath;rolloverManifestPath;successorTransitionManifestPath;logger;constructor(e,s=X){this.stateDir=_(e,B),this.statePath=_(this.stateDir,g),this.lockPath=_(this.stateDir,j),this.mutationLockPath=_(this.stateDir,J),this.rolloverManifestPath=_(this.stateDir,P),this.successorTransitionManifestPath=_(this.stateDir,A),this.logger=s}async readAll(e){const s=e??new Date().toISOString();await this.cleanupOrphanTempFiles(),await this.recoverSessionRolloverIfPresent(s),await this.recoverSuccessorTransitionIfPresent(s);const[n,r]=await Promise.all([this.readLock(),this.readState(s)]);return{lock:await this.prepareLockForSnapshot(n,s),state:r,capabilities:x}}async applyUpdate(e,s){const n=s??new Date().toISOString();await this.ensureDir(),await this.recoverSessionRolloverIfPresent(n),await this.recoverSuccessorTransitionIfPresent(n);for(const r of e.operations)await this.applyOperation(r,n)}async requestRunTransition(e,s){const n=s??new Date().toISOString();return await this.ensureDir(),this.withMutationLock(()=>this.transitionRun(e,n))}async requestLifecycleAction(e,s={},n){const r=n??new Date().toISOString();return await this.ensureDir(),this.withMutationLock(async()=>{const i=(await this.readState(r)).runControl;if(!i)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");const a=Date.parse(r).toString(36),c=s.operationId??`op-${e}-${a}`,l=s.idempotencyKey??`idem-${e}-${a}`,h=i.receipts.find(O=>O.operationId===c||O.idempotencyKey===l);if(h){if(h.operationId===c&&h.idempotencyKey===l)return h;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}const y=ae(i.status,e);if(!y)throw new Error(E.has(i.status)?"YOLOOP_RUN_TERMINAL":"YOLOOP_RUN_TRANSITION_INVALID");return this.transitionRun(ce({current:i,action:e,target:y,operationId:c,idempotencyKey:l,occurredAt:r}),r)})}async applyOperation(e,s){switch(e.type){case"acquire_lock":await this.acquireLock(e.lock,s);return;case"release_lock":await this.releaseLock(e);return;case"write_state":await this.withMutationLock(async()=>{const n=await this.readState(s),{runControl:r,...o}=e.state;await this.writeState({...o,...n.runControl?{version:"1.2",runControl:n.runControl}:{}})});return;case"advance_epic":await this.advanceEpic(e.nextEpicIndex,e.nextEpicId,s);return;case"no_op":this.logger.info({event:"yoloop_noop"},"yoloop server sent no-op");return;case"reserve_continuation_authority":await this.reserveContinuationAuthority(e.authority,s);return;case"acknowledge_continuation_authority":await this.acknowledgeContinuationAuthority(e.idempotencyKey,e.receipt,s);return;case"repair_continuation_authority":await this.repairContinuationAuthority(e.beforeHash,e.authority,e.receipt,s);return;case"switch_continuation_policy":await this.switchContinuationPolicy(e.policy,e.session,s);return;case"transition_run":await this.requestRunTransition(e,s);return;case"start_successor_run":await this.withMutationLock(()=>this.startSuccessorRun(e,s));return;case"commit_successor_transition":await this.withMutationLock(()=>this.commitSuccessorTransition(e,s));return;case"rollover_session":await this.withMutationLock(()=>this.rolloverSession(e,s));return;case"recovery_attempted":await this.appendRecoveryAttempt(e.attempt,s);return;case"recovery_resolved":await this.resolveRecoveryAttempt(e.attempt_id,e.outcome,s);return;default:{const n=e;throw this.logger.error({event:"yoloop_unknown_op",op:n},"unknown yoloop operation rejected"),new Error("YOLOOP_STATE_OPERATION_UNSUPPORTED")}}}async reserveContinuationAuthority(e,s){const n=await this.readState(s),r=n.pendingContinuationAuthorities??[],o=typeof e.idempotencyKey=="string"?e.idempotencyKey:"";if(!o)throw new Error("YOLOOP_CONTINUATION_AUTHORITY_INVALID");const i=r.find(a=>a.idempotencyKey===o);if(i){if(d(i)===d(e))return;throw new Error("YOLOOP_CONTINUATION_AUTHORITY_CONFLICT")}if(r.length>=64)throw new Error("YOLOOP_PENDING_AUTHORITY_CAPACITY_EXCEEDED");await this.writeState({...n,pendingContinuationAuthorities:[...r,e]})}async acknowledgeContinuationAuthority(e,s,n){const r=await this.readState(n),o=r.pendingContinuationAuthorities??[],i=o.findIndex(h=>h.idempotencyKey===e);if(i<0)throw new Error("YOLOOP_CONTINUATION_RECEIPT_ORPHAN");const a=o[i];if(s.idempotencyKey!==e||s.sessionId!==a.sessionId||JSON.stringify(s.storyIds)!==JSON.stringify(a.storyIds))throw new Error("YOLOOP_CONTINUATION_RECEIPT_MISMATCH");const c=o.filter((h,y)=>y!==i),l=r.continuationReceipts??[];await this.writeState({...r,pendingContinuationAuthorities:c,continuationReceipts:[...l.slice(-63),s]})}async repairContinuationAuthority(e,s,n,r){const o=await this.readState(r),i=o.pendingContinuationAuthorities??[],a=o.continuationRecoveryReceipts??[],c=typeof n.idempotencyKey=="string"?n.idempotencyKey:"",l=a.find(O=>O.idempotencyKey===c);if(l){if(d(l)===d(n))return;throw new Error("YOLOOP_CONTINUATION_RECOVERY_RECEIPT_CONFLICT")}if(i.length!==1||p("p208-legacy-authority-before-v1",i[0])!==e)throw new Error("YOLOOP_CONTINUATION_RECOVERY_BEFORE_MISMATCH");const h=p("p208-legacy-authority-after-v1",s);if(n.beforeHash!==e||n.afterHash!==h)throw new Error("YOLOOP_CONTINUATION_RECOVERY_HASH_MISMATCH");const y={...n};if(delete y.idempotencyKey,!c||p("p208-legacy-authority-recovery-receipt-v1",y)!==c)throw new Error("YOLOOP_CONTINUATION_RECOVERY_RECEIPT_INVALID");await this.writeState({...o,pendingContinuationAuthorities:[s],continuationRecoveryReceipts:[...a.slice(-63),n]})}async switchContinuationPolicy(e,s,n){const r=await this.readState(n);if(r.currentSession||(r.pendingContinuationAuthorities?.length??0)>0)throw new Error("YOLOOP_POLICY_SWITCH_ACTIVE");try{await u.copyFile(this.statePath,`${this.statePath}.policy-backup`)}catch(o){if(o.code!=="ENOENT")throw o}await this.writeState({...r,continuationPolicy:e,continuationSession:s})}async appendRecoveryAttempt(e,s){const n=await this.readState(s),r=n.recovery_history??[];if(r.some(c=>c.attempted_at===e.attempted_at&&c.story_id===e.story_id)){this.logger.warn({event:"recovery_attempted_duplicate",story_id:e.story_id},"duplicate recovery_attempted op; skipping");return}const i=K([...r,e]),a={...n,recovery_history:i};await this.writeState(a),this.logger.info({event:"recovery_attempted_persisted",story_id:e.story_id,history_size:i.length},"recovery attempt persisted")}async resolveRecoveryAttempt(e,s,n){const r=await this.readState(n),o=r.recovery_history??[],i=o.findIndex(h=>h.recovery_step_id_tokenized===e);if(i===-1){this.logger.warn({event:"recovery_resolve_orphan",attempt_id:e},"recovery_resolved op had no matching attempt; skipping");return}const a=o[i];if(a.outcome===s&&a.finished_at){this.logger.info({event:"recovery_resolved_duplicate",attempt_id:e,outcome:s},"duplicate recovery_resolved op; skipping");return}const c=o.slice();c[i]={...a,outcome:s,finished_at:n};const l={...r,recovery_history:c};await this.writeState(l),this.logger.info({event:"recovery_resolved_persisted",attempt_id:e,outcome:s},"recovery attempt resolved")}async acquireLock(e,s){const n={...e,pid:process.pid,hostname:S(),ownerKind:"client",startedAt:e.startedAt||s,leaseId:e.leaseId??le(e.sessionId,s),leaseState:"active",leaseAcquiredAt:e.leaseAcquiredAt??s,leaseDurationMs:e.leaseDurationMs??z,leaseExpiresAt:e.leaseExpiresAt??e.ttlExpiresAt},r=JSON.stringify(n,null,2);try{const o=await u.open(this.lockPath,"wx");try{await o.writeFile(r,"utf8")}finally{await o.close()}this.trySetFilePerms(this.lockPath),this.logger.info({event:"yoloop_lock_acquired",pid:n.pid,sessionId:n.sessionId},"yoloop lock acquired");return}catch(o){const i=o;if(i.code!=="EEXIST")throw this.logger.error({event:"yoloop_lock_acquire_error",err:i.message},"failed to acquire yoloop lock"),o;const a=await this.readLock();if(a&&this.isSameClientSessionLock(a,n)){this.logger.info({event:"yoloop_lock_acquire_duplicate",sessionId:n.sessionId},"duplicate acquire_lock for current yoloop session; treating as no-op");return}if(!await this.maybeRecoverOrphanLock(s))throw this.logger.warn({event:"yoloop_lock_held"},"yoloop lock held by another live process"),o;const l=await u.open(this.lockPath,"wx");try{await l.writeFile(r,"utf8")}finally{await l.close()}this.trySetFilePerms(this.lockPath),this.logger.info({event:"yoloop_lock_acquired_after_recovery",pid:n.pid},"yoloop lock acquired after orphan recovery")}}async releaseLock(e){const s=await this.readState(new Date().toISOString()),n=await this.readLock();if(s.runControl){if(!e.expectedRunId||!e.expectedSessionId||!e.expectedLeaseId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(e.expectedRunId!==s.runControl.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(!n||e.expectedSessionId!==n.sessionId||e.expectedLeaseId!==n.leaseId)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}try{await u.unlink(this.lockPath),this.logger.info({event:"yoloop_lock_released"},"yoloop lock released")}catch(r){const o=r;if(o.code==="ENOENT"){this.logger.info({event:"yoloop_lock_release_noop"},"yoloop lock release noop (file absent)");return}this.logger.warn({event:"yoloop_lock_release_error",err:o.message},"unexpected error releasing yoloop lock")}}async readLock(){try{const e=await u.readFile(this.lockPath,"utf8"),s=JSON.parse(e),n=s.currentEpicId??s.epicId??"";return{pid:s.pid??0,hostname:s.hostname??"",...s.ownerKind?{ownerKind:s.ownerKind}:{},...s.ownerPidState?{ownerPidState:s.ownerPidState}:{},...typeof s.leaseId=="string"?{leaseId:s.leaseId}:{},...s.leaseState?{leaseState:s.leaseState}:{},...typeof s.leaseAcquiredAt=="string"?{leaseAcquiredAt:s.leaseAcquiredAt}:{},...typeof s.leaseDurationMs=="number"?{leaseDurationMs:s.leaseDurationMs}:{},...typeof s.leaseExpiresAt=="string"?{leaseExpiresAt:s.leaseExpiresAt}:{},startedAt:s.startedAt??"",sessionId:s.sessionId??"",mode:s.mode??"epic-id",inputPath:s.inputPath??"",epicQueue:s.epicQueue??(n?[n]:[]),currentEpicIndex:s.currentEpicIndex??0,currentEpicId:n,ttlExpiresAt:s.ttlExpiresAt??"",epicId:s.epicId??n}}catch{return null}}async readState(e){try{const s=await u.readFile(this.statePath,"utf8"),n=JSON.parse(s);return he(n,e)}catch(s){const n=s;return n.code!=="ENOENT"&&this.logger.warn({event:"yoloop_state_read_error",err:n.message},"yoloop state file unreadable; using defaults"),w(e)}}async writeState(e){const s=`${this.statePath}.tmp.${process.pid}.${Date.now()}`,n=JSON.stringify(e,null,2);try{const r=await u.open(s,"w",384);try{await r.writeFile(n,"utf8"),await r.sync()}finally{await r.close()}this.trySetFilePerms(s),await u.rename(s,this.statePath),await this.syncStateDirectory()}catch(r){const o=r;this.logger.error({event:"yoloop_state_write_error",err:o.message},"failed to write yoloop state");try{await u.unlink(s)}catch{}throw r}}async rolloverSession(e,s){v(e);const n=await this.readRolloverManifest();if(n){if(oe(n.operation,e)){if(n.operation.payloadHash!==e.payloadHash)throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT");if(n.phase==="applied")return;await this.completePreparedSessionRollover(n.operation,s);return}else if(n.phase==="prepared")throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT")}const r=await this.readState(s),o=await this.readLock();H(e,r,o),await this.writeRolloverManifest({schemaVersion:"YoloopSessionRolloverManifest/1.0",phase:"prepared",operation:e}),await this.completePreparedSessionRollover(e,s)}async completePreparedSessionRollover(e,s){const n=await this.readState(s);let r=d(n)===d(e.next);if(!r){const i=await this.readLock();H(e,n,i),await this.writeState(e.next),r=!0}const o=await this.readLock();if(e.expectedSessionId===null||e.expectedLeaseId===null){if(e.expectedSessionId!==null||e.expectedLeaseId!==null||o)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}else if(o){if(o.sessionId!==e.expectedSessionId||o.leaseId!==e.expectedLeaseId)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");await u.unlink(this.lockPath),await this.syncStateDirectory()}else if(!r)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");await this.writeRolloverManifest({schemaVersion:"YoloopSessionRolloverManifest/1.0",phase:"applied",operation:e}),this.logger.info({event:"yoloop_session_rollover_applied",runId:e.runId,operationId:e.operationId,coolDownUntil:e.coolDownUntil},"yoloop per-run-cap session rollover applied")}async recoverSessionRolloverIfPresent(e){try{await u.access(this.rolloverManifestPath)}catch(s){if(s.code==="ENOENT")return;throw s}await this.ensureDir(),await this.withMutationLock(async()=>{const s=await this.readRolloverManifest();s?.phase==="prepared"&&await this.completePreparedSessionRollover(s.operation,e)})}async readRolloverManifest(){try{const e=JSON.parse(await u.readFile(this.rolloverManifestPath,"utf8"));if(e.schemaVersion!=="YoloopSessionRolloverManifest/1.0"||e.phase!=="prepared"&&e.phase!=="applied"||!e.operation||e.operation.type!=="rollover_session")throw new Error("YOLOOP_SESSION_ROLLOVER_MANIFEST_CORRUPT");return v(e.operation),e}catch(e){if(e.code==="ENOENT")return null;throw e.message==="YOLOOP_SESSION_ROLLOVER_MANIFEST_CORRUPT"?e:new Error("YOLOOP_SESSION_ROLLOVER_MANIFEST_CORRUPT")}}async writeRolloverManifest(e){const s=`${this.rolloverManifestPath}.tmp.${process.pid}.${Date.now()}`,n=await u.open(s,"w",384);try{await n.writeFile(JSON.stringify(e,null,2),"utf8"),await n.sync()}finally{await n.close()}this.trySetFilePerms(s),await u.rename(s,this.rolloverManifestPath),await this.syncStateDirectory()}async commitSuccessorTransition(e,s){f(e);const n=await this.readSuccessorTransitionManifest();if(n){if(se(n.operation,e)){if(n.operation.payloadHash!==e.payloadHash)throw new Error("YOLOOP_SUCCESSOR_TRANSITION_CONFLICT");if(n.phase==="applied")return;await this.completePreparedSuccessorTransition(n.operation,s);return}if(n.phase==="prepared")throw new Error("YOLOOP_SUCCESSOR_TRANSITION_CONFLICT")}const r=await this.readState(s);if(R(e,r)){await this.writeSuccessorTransitionManifest({schemaVersion:"YoloopSuccessorTransitionManifest/1.0",phase:"applied",operation:e});return}k(e,r),await this.writeSuccessorTransitionManifest({schemaVersion:"YoloopSuccessorTransitionManifest/1.0",phase:"prepared",operation:e}),await this.completePreparedSuccessorTransition(e,s)}async completePreparedSuccessorTransition(e,s){let n=await this.readState(s);if(!R(e,n)){d(n.runControl)===d(e.successor.next)||(await this.startSuccessorRun(e.successor,s),n=await this.readState(s));const o=re(e,n);await this.writeState(o),n=await this.readState(s)}if(!R(e,n))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_STATE_CONFLICT");await this.writeSuccessorTransitionManifest({schemaVersion:"YoloopSuccessorTransitionManifest/1.0",phase:"applied",operation:e}),this.logger.info({event:"yoloop_successor_transition_applied",runId:e.successor.runId,operationId:e.operationId},"yoloop successor transition applied")}async recoverSuccessorTransitionIfPresent(e){try{await u.access(this.successorTransitionManifestPath)}catch(s){if(s.code==="ENOENT")return;throw s}await this.ensureDir(),await this.withMutationLock(async()=>{const s=await this.readSuccessorTransitionManifest();s?.phase==="prepared"&&await this.completePreparedSuccessorTransition(s.operation,e)})}async readSuccessorTransitionManifest(){try{const e=JSON.parse(await u.readFile(this.successorTransitionManifestPath,"utf8"));if(e.schemaVersion!=="YoloopSuccessorTransitionManifest/1.0"||e.phase!=="prepared"&&e.phase!=="applied"||!e.operation||e.operation.type!=="commit_successor_transition")throw new Error("YOLOOP_SUCCESSOR_TRANSITION_MANIFEST_CORRUPT");return f(e.operation),e}catch(e){if(e.code==="ENOENT")return null;throw e.message==="YOLOOP_SUCCESSOR_TRANSITION_MANIFEST_CORRUPT"?e:new Error("YOLOOP_SUCCESSOR_TRANSITION_MANIFEST_CORRUPT")}}async writeSuccessorTransitionManifest(e){const s=`${this.successorTransitionManifestPath}.tmp.${process.pid}.${Date.now()}`,n=await u.open(s,"w",384);try{await n.writeFile(JSON.stringify(e,null,2),"utf8"),await n.sync()}finally{await n.close()}this.trySetFilePerms(s),await u.rename(s,this.successorTransitionManifestPath),await this.syncStateDirectory()}async advanceEpic(e,s,n){const r=await this.readState(n);if(!r.currentSession){this.logger.warn({event:"yoloop_advance_no_session",nextEpicId:s},"advance_epic with no active session; skipping");return}const o={...r,currentSession:{...r.currentSession,currentEpicIndex:e}};await this.writeState(o),this.logger.info({event:"yoloop_epic_advance",nextEpicId:s,nextIndex:e},"yoloop advanced to next epic")}async ensureDir(){try{await u.mkdir(this.stateDir,{recursive:!0}),this.trySetDirPerms(this.stateDir)}catch(e){const s=e;throw this.logger.error({event:"yoloop_mkdir_error",err:s.message,path:this.stateDir},"failed to ensure .neocortex/ directory"),e}}async syncStateDirectory(){try{const e=await u.open(this.stateDir,"r");try{await e.sync()}finally{await e.close()}}catch(e){const s=e.code;if(s!=="EINVAL"&&s!=="EISDIR"&&s!=="ENOTSUP"&&s!=="EPERM")throw e}}async withMutationLock(e){let s=null;for(let n=0;n<G;n+=1)try{s=await u.open(this.mutationLockPath,"wx",384),await s.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await s.sync();break}catch(r){if(r.code!=="EEXIST")throw r;try{const o=await u.stat(this.mutationLockPath);if(Date.now()-o.mtimeMs>W){await u.unlink(this.mutationLockPath);continue}}catch{continue}await new Promise(o=>setTimeout(o,5))}if(!s)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");try{return await e()}finally{await s.close().catch(()=>{}),await u.unlink(this.mutationLockPath).catch(()=>{})}}async transitionRun(e,s){T(e);const n=await this.readState(s),r=n.runControl,o=r?.receipts.find(l=>l.operationId===e.operationId||l.idempotencyKey===e.idempotencyKey);if(o){if(o.operationId===e.operationId&&o.idempotencyKey===e.idempotencyKey&&o.payloadHash===e.payloadHash)return o;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}if(r&&r.runId!==e.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if((r?.revision??0)!==e.expectedRevision)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if((r?.latestSnapshotHash??null)!==e.expectedSnapshotHash)throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT");L(r,e);const c=e.next.receipts.at(-1);if(!c)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");return await this.writeState({...n,version:"1.2",runControl:e.next}),this.logger.info({event:"yoloop_run_transition_committed",runId:e.runId,operationId:e.operationId,revision:c.revision,status:c.status},"yoloop run transition committed"),c}async startSuccessorRun(e,s){Y(e);const n=await this.readState(s),r=n.runControl,o={schemaVersion:"YoloopRunPredecessor/1.0",runId:e.previousRunId,revision:e.expectedRevision,snapshotHash:e.expectedSnapshotHash,successorOperationId:e.operationId,publicSafe:!0},i=r?.receipts.find(l=>l.operationId===e.operationId||l.idempotencyKey===e.idempotencyKey);if(i){if(i.operationId===e.operationId&&i.idempotencyKey===e.idempotencyKey&&e.next.receipts.at(-1)?.payloadHash===i.payloadHash&&d(r?.predecessor)===d(o))return i;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}if(!r||r.runId!==e.previousRunId||!["exhausted","success"].includes(r.status)||r.revision!==e.expectedRevision||r.latestSnapshotHash!==e.expectedSnapshotHash||n.currentSession!==null)throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT");const a=e.next.receipts.at(-1);if(!a||d(e.next.predecessor)!==d(o))throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT");const c={type:"transition_run",runId:e.runId,operationId:e.operationId,idempotencyKey:e.idempotencyKey,expectedRevision:0,expectedSnapshotHash:null,payloadHash:a.payloadHash,next:e.next};return T(c),L(void 0,c),await this.writeState({...n,version:"1.2",runControl:e.next}),a}trySetFilePerms(e){try{$(e)}catch{}}trySetDirPerms(e){try{q(e)}catch{}}async prepareLockForSnapshot(e,s){if(!e)return null;if(e.ownerKind!=="client")return e;const n=F(e,s),r={...e,leaseState:n};if(n==="expired")return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_client_lock_recovered",reason:"lease_expired"},"expired client-owned yoloop lock lease recovered before snapshot echo"),null;if(!r.pid||r.pid<=0)return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_client_lock_recovered",reason:"invalid_pid"},"invalid PID in client-owned yoloop lock; recovered"),null;if(r.hostname&&r.hostname!==S())return{...r,ownerPidState:"unknown"};try{return process.kill(r.pid,0),{...r,ownerPidState:"live"}}catch{return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_client_lock_recovered",reason:"dead_pid"},"stale client-owned yoloop lock recovered before snapshot echo"),null}}async maybeRecoverOrphanLock(e){const s=await this.readLock();if(!s)return!0;if(F(s,e)==="expired")return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"lease_expired"},"expired yoloop lock lease recovered"),!0;if(!s.pid||s.pid<=0)return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"invalid_pid"},"invalid PID in lock file; recovered"),!0;if(s.hostname&&s.hostname!==S())return this.logger.warn({event:"yoloop_lock_remote_host",ownerKind:s.ownerKind??"server",ownerPidState:"unknown"},"lock held by a remote host; honoring"),!1;try{return process.kill(s.pid,0),!1}catch{return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"dead_pid"},"orphan yoloop lock recovered"),!0}}async deleteLockBestEffort(){try{await u.unlink(this.lockPath)}catch{}}isSameClientSessionLock(e,s){return e.ownerKind==="client"&&e.sessionId===s.sessionId&&e.pid===process.pid&&e.hostname===S()}async cleanupOrphanTempFiles(){try{const e=V(this.statePath),s=await u.readdir(e),n=[`${g}.tmp.`,`${P}.tmp.`,`${A}.tmp.`],r=s.filter(o=>n.some(i=>o.startsWith(i)));for(const o of r)try{await u.unlink(_(e,o))}catch{}}catch{}}}function d(t){return t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?`[${t.map(d).join(",")}]`:`{${Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[s])=>e.localeCompare(s)).map(([e,s])=>`${JSON.stringify(e)}:${d(s)}`).join(",")}}`}function p(t,e){return b("sha256").update(`${t}\0${d(e)}`).digest("hex")}function Z(t){return p("p9390812898200217364-yoloop-session-v1",t)}function Q(t){return p("p9390812898200217364-yoloop-rollover-v1",t)}function ee(t){return p("p9390812898200217364-yoloop-successor-run-v1",t)}function te(t){return p("p9046281030721413419-yoloop-successor-transition-v1",t)}function se(t,e){return t.operationId===e.operationId&&t.idempotencyKey===e.idempotencyKey}function f(t){const e=/^[A-Za-z0-9._:-]{1,128}$/;Y(t.successor);const s={operationId:t.operationId,idempotencyKey:t.idempotencyKey,successor:t.successor,state:t.state,...t.acknowledgement?{acknowledgement:t.acknowledgement}:{},...t.reservation?{reservation:t.reservation}:{}},n=t.acknowledgement?.idempotencyKey,r=t.acknowledgement?.receipt.idempotencyKey,o=t.reservation?.authority.idempotencyKey;if(t.successor.type!=="start_successor_run"||!e.test(t.operationId)||!e.test(t.idempotencyKey)||t.operationId!==t.successor.operationId||t.idempotencyKey!==t.successor.idempotencyKey||!/^[a-f0-9]{64}$/.test(t.payloadHash)||t.payloadHash!==te(s)||Buffer.byteLength(d(s),"utf8")>1048576||t.acknowledgement!==void 0&&(t.acknowledgement.type!=="acknowledge_continuation_authority"||typeof n!="string"||!e.test(n)||r!==n)||t.reservation!==void 0&&(t.reservation.type!=="reserve_continuation_authority"||typeof o!="string"||!e.test(o))||n!==void 0&&o===n)throw new Error("YOLOOP_SUCCESSOR_TRANSITION_CONFLICT")}function k(t,e){if(f(t),!(d(e.runControl)===d(t.successor.next))){const n=e.runControl;if(!n||n.runId!==t.successor.previousRunId||!["exhausted","success"].includes(n.status)||n.revision!==t.successor.expectedRevision||n.latestSnapshotHash!==t.successor.expectedSnapshotHash||e.currentSession!==null)throw new Error("YOLOOP_SUCCESSOR_TRANSITION_STATE_CONFLICT")}ne(t,e)}function ne(t,e){const s=e.pendingContinuationAuthorities??[],n=e.continuationReceipts??[],r=t.acknowledgement;if(r){const l=s.find(O=>O.idempotencyKey===r.idempotencyKey);if(!l||r.receipt.sessionId!==l.sessionId||d(r.receipt.storyIds)!==d(l.storyIds))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");const h=s.filter(O=>O.idempotencyKey!==r.idempotencyKey),y=[...n.slice(-63),r.receipt];if(d(t.state.pendingContinuationAuthorities??[])!==d(h)||d(t.state.continuationReceipts??[])!==d(y))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT")}else if(d(t.state.pendingContinuationAuthorities??[])!==d(s)||d(t.state.continuationReceipts??[])!==d(n))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");const o=t.reservation?.authority;if(!o)return;const i=String(o.idempotencyKey??""),a=t.state.pendingContinuationAuthorities??[],c=a.find(l=>l.idempotencyKey===i);if(c&&d(c)!==d(o))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");if(!c&&a.length>=64)throw new Error("YOLOOP_PENDING_AUTHORITY_CAPACITY_EXCEEDED")}function re(t,e){k(t,e);const s=t.reservation?.authority,n=[...t.state.pendingContinuationAuthorities??[]];return s&&!n.some(r=>r.idempotencyKey===s.idempotencyKey)&&n.push(s),{...t.state,version:"1.2",runControl:t.successor.next,...s||t.state.pendingContinuationAuthorities!==void 0?{pendingContinuationAuthorities:n}:{}}}function R(t,e){const s=t.reservation?.authority,n=[...t.state.pendingContinuationAuthorities??[]];s&&!n.some(o=>o.idempotencyKey===s.idempotencyKey)&&n.push(s);const r={...t.state,version:"1.2",runControl:t.successor.next,...s||t.state.pendingContinuationAuthorities!==void 0?{pendingContinuationAuthorities:n}:{}};return d(e)===d(r)}function oe(t,e){return t.operationId===e.operationId&&t.idempotencyKey===e.idempotencyKey}function v(t){const e=/^[A-Za-z0-9._:-]{1,128}$/,s={runId:t.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,expectedSessionId:t.expectedSessionId,expectedSessionFingerprint:t.expectedSessionFingerprint,expectedLeaseId:t.expectedLeaseId,coolDownUntil:t.coolDownUntil,reason:t.reason,exhaustedRun:t.exhaustedRun,next:t.next};if(!e.test(t.runId)||!e.test(t.operationId)||!e.test(t.idempotencyKey)||!/^[a-f0-9]{64}$/.test(t.expectedSessionFingerprint)||!/^[a-f0-9]{64}$/.test(t.payloadHash)||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<0||!Number.isFinite(Date.parse(t.coolDownUntil))||!["YOLOOP_PER_RUN_CAP_REACHED","YOLOOP_SESSION_TIMEOUT"].includes(t.reason)||t.payloadHash!==Q(s)||t.receipt.schemaVersion!=="YoloopSessionRolloverReceipt/1.0"||t.receipt.runId!==t.runId||t.receipt.operationId!==t.operationId||t.receipt.idempotencyKey!==t.idempotencyKey||t.receipt.payloadHash!==t.payloadHash||t.receipt.coolDownUntil!==t.coolDownUntil||t.receipt.revision!==(t.exhaustedRun?.revision??0)||t.receipt.snapshotHash!==(t.exhaustedRun?.latestSnapshotHash??null)||t.receipt.status!=="exhausted"||t.receipt.publicSafe!==!0)throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT");if(t.expectedSessionId===null!=(t.expectedLeaseId===null)||t.expectedSessionId!==null&&!e.test(t.expectedSessionId)||t.expectedLeaseId!==null&&!e.test(t.expectedLeaseId))throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}function Y(t){const e=/^[A-Za-z0-9._:-]{1,128}$/,s={runId:t.runId,previousRunId:t.previousRunId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,next:t.next};if(!e.test(t.runId)||!e.test(t.previousRunId)||t.runId===t.previousRunId||!e.test(t.operationId)||!e.test(t.idempotencyKey)||!/^[a-f0-9]{64}$/.test(t.payloadHash)||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<1||t.payloadHash!==ee(s))throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT")}function H(t,e,s){v(t);const n=e.currentSession;if(!n||Z(n)!==t.expectedSessionFingerprint)throw new Error("YOLOOP_SESSION_ROLLOVER_SESSION_CONFLICT");const r=e.runControl;if((r?.revision??0)!==t.expectedRevision||(r?.latestSnapshotHash??null)!==t.expectedSnapshotHash||r&&r.runId!==t.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(t.expectedSessionId===null||t.expectedLeaseId===null){if(s)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}else if(!s||s.sessionId!==t.expectedSessionId||s.leaseId!==t.expectedLeaseId)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");const o=t.exhaustedRun;if(r)if(r.status==="exhausted"){if(d(o)!==d(r))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}else{if(!o||o.status!=="exhausted")throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT");const a=o.receipts.at(-1);if(!a)throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT");const c={type:"transition_run",runId:r.runId,operationId:a.operationId,idempotencyKey:a.idempotencyKey,expectedRevision:r.revision,expectedSnapshotHash:r.latestSnapshotHash,payloadHash:a.payloadHash,next:o};T(c),L(r,c)}else{const a=o?.receipts[0],c=o?.receipts[1];if(o&&(o.runId!==t.runId||o.status!=="exhausted"||o.revision!==2||o.events.length!==2||o.progressSnapshots.length!==4||o.receipts.length!==2||a?.runId!==t.runId||a.revision!==1||a.status!=="created"||c?.runId!==t.runId||c.revision!==2||c.status!=="exhausted"||c.operationId!==`${t.operationId}:run`||c.idempotencyKey!==`${t.idempotencyKey}:run`||o.latestSnapshotHash!==c.snapshotHash||o.predecessor!==void 0))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}const i={...e,version:"1.2",coolDownUntil:t.coolDownUntil,currentSession:null,...o?{runControl:o}:{}};if(d(i)!==d(t.next))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}function U(t){const{receipts:e,...s}=t.next;return p("p220-yoloop-run-transition-payload-v1",{runId:t.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,next:s})}const E=new Set(["success","partial","blocked","failure","exhausted","cancelled"]),ie={created:["running","cancelling","exhausted"],running:["pausing","cancelling","success","partial","blocked","failure","exhausted"],pausing:["paused","cancelling","failure","exhausted"],paused:["resuming","cancelling","exhausted"],resuming:["running","cancelling","failure","exhausted"],cancelling:["cancelled","failure","exhausted"]};function ae(t,e){return e==="pause"?t==="running"?"pausing":null:e==="resume"?t==="paused"?"resuming":null:E.has(t)||t==="cancelling"?null:"cancelling"}function ce(t){const e=t.current.revision+1,s=t.action==="cancel"?["YOLOOP_RUN_CANCEL_REQUESTED"]:[],n={schemaVersion:"YoloopOperationalBudgetSummary/1.0",limits:t.current.operationalBudget.limits,usage:t.current.usage,exhaustedDimension:null},r={schemaVersion:"ProgressSnapshot/1.0",runId:t.current.runId,sequence:t.current.progressSnapshots.length+1,revision:e,operationId:t.operationId,boundary:t.action,phase:"before",status:t.current.status,occurredAt:t.occurredAt,parentSnapshotHash:t.current.latestSnapshotHash,budget:n,reasonCodes:s,publicSafe:!0},o=p("p220-yoloop-progress-snapshot-id-v1",{runId:r.runId,operationId:r.operationId,sequence:r.sequence,phase:r.phase}),i={...r,snapshotId:o,snapshotHash:p("p220-yoloop-progress-snapshot-v1",{...r,snapshotId:o})},a={...r,sequence:i.sequence+1,phase:"after",status:t.target,parentSnapshotHash:i.snapshotHash},c=p("p220-yoloop-progress-snapshot-id-v1",{runId:a.runId,operationId:a.operationId,sequence:a.sequence,phase:a.phase}),l={...a,snapshotId:c,snapshotHash:p("p220-yoloop-progress-snapshot-v1",{...a,snapshotId:c})},h={schemaVersion:"YoloopRunEvent/1.0",runId:t.current.runId,operationId:t.operationId,kind:"intent",sequence:t.current.events.length+1,revision:e,occurredAt:t.occurredAt,fromStatus:t.current.status,toStatus:t.target,reasonCodes:s,budgetDimension:null,parentEventHash:t.current.events.at(-1)?.eventHash??null,publicSafe:!0},y=p("p220-yoloop-run-event-id-v1",{runId:h.runId,operationId:h.operationId,sequence:h.sequence}),O={...h,eventId:y,eventHash:p("p220-yoloop-run-event-v1",{...h,eventId:y})},I={...t.current,revision:e,status:t.target,events:[...t.current.events,O],progressSnapshots:[...t.current.progressSnapshots,i,l],latestSnapshotHash:l.snapshotHash,receipts:[...t.current.receipts]},N={runId:t.current.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.current.revision,expectedSnapshotHash:t.current.latestSnapshotHash,next:I},m=U(N),M={schemaVersion:"YoloopRunTransitionReceipt/1.0",runId:t.current.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,payloadHash:m,revision:e,snapshotHash:l.snapshotHash,status:t.target};return{type:"transition_run",...N,payloadHash:m,next:{...I,receipts:[...I.receipts,M]}}}function T(t){const e=/^[A-Za-z0-9._:-]{1,128}$/;if(!e.test(t.runId)||!e.test(t.operationId)||!e.test(t.idempotencyKey)||!/^[a-f0-9]{64}$/.test(t.payloadHash)||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<0)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");if(t.payloadHash!==U(t))throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}function L(t,e){const s=e.next,n=t?.events??[],r=t?.progressSnapshots??[],o=t?.receipts??[];if(s.schemaVersion!=="YoloopRunControl/1.0"||s.runId!==e.runId||s.revision!==e.expectedRevision+1||s.events.length!==n.length+1||s.progressSnapshots.length!==r.length+2||s.receipts.length!==o.length+1||d(s.events.slice(0,n.length))!==d(n)||d(s.progressSnapshots.slice(0,r.length))!==d(r)||d(s.receipts.slice(0,o.length))!==d(o))throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(t){if(E.has(t.status))throw new Error("YOLOOP_RUN_TERMINAL");const h=s.progressSnapshots.at(-2)?.boundary,y=t.status===s.status&&(h==="budget"||h==="retry");if(!(ie[t.status]??[]).includes(s.status)&&!y)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(t.startedAt!==s.startedAt||t.deadlineAt!==s.deadlineAt)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(d(t.predecessor)!==d(s.predecessor))throw new Error("YOLOOP_RUN_TRANSITION_INVALID")}else if(s.status!=="created")throw new Error("YOLOOP_RUN_TRANSITION_INVALID");const i=s.progressSnapshots.at(-2),a=s.progressSnapshots.at(-1),c=s.events.at(-1),l=s.receipts.at(-1);if(!i||!a||!c||!l||i.phase!=="before"||a.phase!=="after"||i.operationId!==e.operationId||a.operationId!==e.operationId||c.operationId!==e.operationId||i.runId!==e.runId||a.runId!==e.runId||c.runId!==e.runId||i.revision!==s.revision||a.revision!==s.revision||c.revision!==s.revision||i.parentSnapshotHash!==(t?.latestSnapshotHash??null)||a.parentSnapshotHash!==i.snapshotHash||s.latestSnapshotHash!==a.snapshotHash||l.schemaVersion!=="YoloopRunTransitionReceipt/1.0"||l.runId!==e.runId||l.operationId!==e.operationId||l.idempotencyKey!==e.idempotencyKey||l.payloadHash!==e.payloadHash||l.revision!==s.revision||l.snapshotHash!==s.latestSnapshotHash||l.status!==s.status||Date.parse(s.deadlineAt)<=Date.parse(s.startedAt))throw new Error("YOLOOP_RUN_TRANSITION_INVALID");D(i),D(a),de(c,n.at(-1)?.eventHash??null)}function D(t){const{snapshotHash:e,...s}=t;if(e!==p("p220-yoloop-progress-snapshot-v1",s))throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT")}function de(t,e){const{eventHash:s,...n}=t;if(t.parentEventHash!==e||s!==p("p220-yoloop-run-event-v1",n))throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT")}function le(t,e){return`lease-${ue(`${t}:${e}`)}`}function ue(t){let e=2166136261;for(let s=0;s<t.length;s+=1)e^=t.charCodeAt(s),e=Math.imul(e,16777619)>>>0;return e.toString(36).padStart(7,"0")}function F(t,e){const s=t.leaseExpiresAt??t.ttlExpiresAt,n=Date.parse(s),r=Date.parse(e);return!Number.isFinite(n)||!Number.isFinite(r)?"unknown":n<=r?"expired":"active"}function he(t,e){const s=w(e);return{...t,version:t.version==="1.2"?"1.2":"1.1",lastResetAt:t.lastResetAt??s.lastResetAt,storiesRunToday:t.storiesRunToday??0,iterationsToday:t.iterationsToday??0,iterationsTodayDate:t.iterationsTodayDate??s.iterationsTodayDate,tokensUsedToday:t.tokensUsedToday??0,lastRunAt:t.lastRunAt??null,coolDownUntil:t.coolDownUntil??null,totalRunsAllTime:t.totalRunsAllTime??0,totalStoriesAllTime:t.totalStoriesAllTime??0,currentSession:t.currentSession??null,...t.runControl!==void 0?{runControl:t.runControl}:{},...t.continuationPolicy!==void 0?{continuationPolicy:t.continuationPolicy}:{},...t.continuationSession!==void 0?{continuationSession:t.continuationSession}:{},...t.pendingContinuationAuthorities!==void 0?{pendingContinuationAuthorities:t.pendingContinuationAuthorities}:{},...t.continuationReceipts!==void 0?{continuationReceipts:t.continuationReceipts}:{},...t.continuationRecoveryReceipts!==void 0?{continuationRecoveryReceipts:t.continuationRecoveryReceipts}:{},recovery_history:Array.isArray(t.recovery_history)?K(t.recovery_history):[]}}function K(t){return t.length<=C?t:t.slice(t.length-C)}export{x as YOLOOP_PERSISTENCE_CAPABILITIES,fe as YoloopClientStateStore,U as buildYoloopRunTransitionPayloadHash,Q as buildYoloopSessionRolloverPayloadHash,ee as buildYoloopSuccessorRunPayloadHash,te as buildYoloopSuccessorTransitionPayloadHash,K as capRecoveryHistory,w as createDefaultCounters,we as createDefaultState,Z as fingerprintYoloopSession};
|
|
1
|
+
import{promises as u}from"node:fs";import{createHash as V}from"node:crypto";import{join as S,dirname as $}from"node:path";import{hostname as w}from"node:os";import{setSecureFilePermissions as q,setSecureDirPermissions as B}from"../config/secure-config.js";import{RECOVERY_HISTORY_CAP as m}from"./shared-yoloop-types.js";const j=".neocortex",g="yoloop-state.json",J="yoloop.lock",z="yoloop-state.mutation.lock",A="yoloop-session-rollover.json",P="yoloop-successor-transition.json",W=360*60*1e3,G=3e4,X=200,x=Object.freeze(["rollover-session-v1","successor-transition-v1","continuation-replan-v1"]),Z={warn:()=>{},info:()=>{},error:()=>{}};function f(t){const e=t.slice(0,10);return{version:"1.1",lastResetAt:t,storiesRunToday:0,iterationsToday:0,iterationsTodayDate:e,tokensUsedToday:0,lastRunAt:null,coolDownUntil:null,totalRunsAllTime:0,totalStoriesAllTime:0,currentSession:null,continuationPolicy:"p205-finite-resume-v2",pendingContinuationAuthorities:[],continuationReceipts:[],continuationRecoveryReceipts:[]}}function Re(t){return{lock:null,state:f(t),capabilities:x}}class ve{stateDir;statePath;lockPath;mutationLockPath;rolloverManifestPath;successorTransitionManifestPath;logger;constructor(e,s=Z){this.stateDir=S(e,j),this.statePath=S(this.stateDir,g),this.lockPath=S(this.stateDir,J),this.mutationLockPath=S(this.stateDir,z),this.rolloverManifestPath=S(this.stateDir,A),this.successorTransitionManifestPath=S(this.stateDir,P),this.logger=s}async readAll(e){const s=e??new Date().toISOString();await this.cleanupOrphanTempFiles(),await this.recoverSessionRolloverIfPresent(s),await this.recoverSuccessorTransitionIfPresent(s);const[n,o]=await Promise.all([this.readLock(),this.readState(s)]);return{lock:await this.prepareLockForSnapshot(n,s),state:o,capabilities:x}}async applyUpdate(e,s){const n=s??new Date().toISOString();await this.ensureDir(),await this.recoverSessionRolloverIfPresent(n),await this.recoverSuccessorTransitionIfPresent(n);for(const o of e.operations)await this.applyOperation(o,n)}async requestRunTransition(e,s){const n=s??new Date().toISOString();return await this.ensureDir(),this.withMutationLock(()=>this.transitionRun(e,n))}async requestLifecycleAction(e,s={},n){const o=n??new Date().toISOString();return await this.ensureDir(),this.withMutationLock(async()=>{const c=(await this.readState(o)).runControl;if(!c)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");const a=Date.parse(o).toString(36),i=s.operationId??`op-${e}-${a}`,l=s.idempotencyKey??`idem-${e}-${a}`,h=c.receipts.find(y=>y.operationId===i||y.idempotencyKey===l);if(h){if(h.operationId===i&&h.idempotencyKey===l)return h;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}const O=de(c.status,e);if(!O)throw new Error(T.has(c.status)?"YOLOOP_RUN_TERMINAL":"YOLOOP_RUN_TRANSITION_INVALID");return this.transitionRun(le({current:c,action:e,target:O,operationId:i,idempotencyKey:l,occurredAt:o}),o)})}async applyOperation(e,s){switch(e.type){case"acquire_lock":await this.withMutationLock(()=>this.acquireLock(e.lock,s));return;case"release_lock":await this.withMutationLock(()=>this.releaseLock(e));return;case"write_state":await this.withMutationLock(async()=>{const n=await this.readState(s),{runControl:o,...r}=e.state;await this.writeState({...r,...n.runControl?{version:"1.2",runControl:n.runControl}:{}})});return;case"advance_epic":await this.advanceEpic(e.nextEpicIndex,e.nextEpicId,s);return;case"no_op":this.logger.info({event:"yoloop_noop"},"yoloop server sent no-op");return;case"reserve_continuation_authority":await this.reserveContinuationAuthority(e.authority,s);return;case"acknowledge_continuation_authority":await this.acknowledgeContinuationAuthority(e.idempotencyKey,e.receipt,s);return;case"repair_continuation_authority":await this.repairContinuationAuthority(e.beforeHash,e.authority,e.receipt,s);return;case"switch_continuation_policy":await this.switchContinuationPolicy(e.policy,e.session,s);return;case"transition_run":await this.requestRunTransition(e,s);return;case"start_successor_run":await this.withMutationLock(()=>this.startSuccessorRun(e,s));return;case"commit_successor_transition":await this.withMutationLock(()=>this.commitSuccessorTransition(e,s));return;case"rollover_session":await this.withMutationLock(()=>this.rolloverSession(e,s));return;case"replan_continuation_session":await this.withMutationLock(()=>this.replanContinuationSession(e,s));return;case"recovery_attempted":await this.appendRecoveryAttempt(e.attempt,s);return;case"recovery_resolved":await this.resolveRecoveryAttempt(e.attempt_id,e.outcome,s);return;default:{const n=e;throw this.logger.error({event:"yoloop_unknown_op",op:n},"unknown yoloop operation rejected"),new Error("YOLOOP_STATE_OPERATION_UNSUPPORTED")}}}async reserveContinuationAuthority(e,s){const n=await this.readState(s),o=n.pendingContinuationAuthorities??[],r=typeof e.idempotencyKey=="string"?e.idempotencyKey:"";if(!r)throw new Error("YOLOOP_CONTINUATION_AUTHORITY_INVALID");const c=o.find(a=>a.idempotencyKey===r);if(c){if(d(c)===d(e))return;throw new Error("YOLOOP_CONTINUATION_AUTHORITY_CONFLICT")}if(o.length>=64)throw new Error("YOLOOP_PENDING_AUTHORITY_CAPACITY_EXCEEDED");await this.writeState({...n,pendingContinuationAuthorities:[...o,e]})}async acknowledgeContinuationAuthority(e,s,n){const o=await this.readState(n),r=o.pendingContinuationAuthorities??[],c=r.findIndex(h=>h.idempotencyKey===e);if(c<0)throw new Error("YOLOOP_CONTINUATION_RECEIPT_ORPHAN");const a=r[c];if(s.idempotencyKey!==e||s.sessionId!==a.sessionId||JSON.stringify(s.storyIds)!==JSON.stringify(a.storyIds))throw new Error("YOLOOP_CONTINUATION_RECEIPT_MISMATCH");const i=r.filter((h,O)=>O!==c),l=o.continuationReceipts??[];await this.writeState({...o,pendingContinuationAuthorities:i,continuationReceipts:[...l.slice(-63),s]})}async repairContinuationAuthority(e,s,n,o){const r=await this.readState(o),c=r.pendingContinuationAuthorities??[],a=r.continuationRecoveryReceipts??[],i=typeof n.idempotencyKey=="string"?n.idempotencyKey:"",l=a.find(y=>y.idempotencyKey===i);if(l){if(d(l)===d(n))return;throw new Error("YOLOOP_CONTINUATION_RECOVERY_RECEIPT_CONFLICT")}if(c.length!==1||p("p208-legacy-authority-before-v1",c[0])!==e)throw new Error("YOLOOP_CONTINUATION_RECOVERY_BEFORE_MISMATCH");const h=p("p208-legacy-authority-after-v1",s);if(n.beforeHash!==e||n.afterHash!==h)throw new Error("YOLOOP_CONTINUATION_RECOVERY_HASH_MISMATCH");const O={...n};if(delete O.idempotencyKey,!i||p("p208-legacy-authority-recovery-receipt-v1",O)!==i)throw new Error("YOLOOP_CONTINUATION_RECOVERY_RECEIPT_INVALID");await this.writeState({...r,pendingContinuationAuthorities:[s],continuationRecoveryReceipts:[...a.slice(-63),n]})}async switchContinuationPolicy(e,s,n){const o=await this.readState(n);if(o.currentSession||(o.pendingContinuationAuthorities?.length??0)>0)throw new Error("YOLOOP_POLICY_SWITCH_ACTIVE");try{await u.copyFile(this.statePath,`${this.statePath}.policy-backup`)}catch(r){if(r.code!=="ENOENT")throw r}await this.writeState({...o,continuationPolicy:e,continuationSession:s})}async replanContinuationSession(e,s){const{type:n,payloadHash:o,receipt:r,...c}=e;if(Q(c)!==e.payloadHash||!k(e.nextSession))throw new Error("YOLOOP_CONTINUATION_REPLAN_PAYLOAD_INVALID");const a={schemaVersion:"YoloopContinuationReplanReceipt/1.0",operationId:e.operationId,idempotencyKey:e.idempotencyKey,runId:e.expectedRunId,previousSessionHash:e.expectedSessionHash,nextSessionHash:p("p222-yoloop-replan-session-v1",e.nextSession),retiredAuthorityHash:e.expectedPendingHash,retiredAuthorityCount:e.expectedPendingHash===p("p222-yoloop-replan-pending-v1",[])?0:1,payloadHash:e.payloadHash,outcome:"graph-replanned",publicSafe:!0};if(d(e.receipt)!==d(a))throw new Error("YOLOOP_CONTINUATION_REPLAN_RECEIPT_INVALID");const i=await this.readState(s);if(await this.readLock()||i.currentSession!==null)throw new Error("YOLOOP_CONTINUATION_REPLAN_ACTIVE");const l=i.runControl;if(!l||l.runId!==e.expectedRunId||!["success","exhausted"].includes(l.status)||l.revision!==e.expectedRevision||l.latestSnapshotHash!==e.expectedSnapshotHash||i.continuationPolicy!=="p205-finite-resume-v2")throw new Error("YOLOOP_CONTINUATION_REPLAN_RUN_CONFLICT");const h=i.continuationReplanReceipts??[],O=h.find(_=>_.idempotencyKey===e.idempotencyKey||_.operationId===e.operationId);if(O){if(d(O)===d(a)&&d(i.continuationSession)===d(e.nextSession)&&(i.pendingContinuationAuthorities?.length??0)===0)return;throw new Error("YOLOOP_CONTINUATION_REPLAN_REPLAY_CONFLICT")}const y=i.continuationSession,I=i.pendingContinuationAuthorities??[];if(!k(y)||p("p222-yoloop-replan-session-v1",y)!==e.expectedSessionHash||p("p222-yoloop-replan-pending-v1",I)!==e.expectedPendingHash||I.length>1||I.some(_=>_.delegated!==!1||_.sessionId!==y.sessionId||!_.certificate||_.certificate.sessionId!==y.sessionId))throw new Error("YOLOOP_CONTINUATION_REPLAN_AUTHORITY_CONFLICT");await this.writeState({...i,continuationSession:e.nextSession,pendingContinuationAuthorities:[],continuationReplanReceipts:[...h.slice(-63),a]})}async appendRecoveryAttempt(e,s){const n=await this.readState(s),o=n.recovery_history??[];if(o.some(i=>i.attempted_at===e.attempted_at&&i.story_id===e.story_id)){this.logger.warn({event:"recovery_attempted_duplicate",story_id:e.story_id},"duplicate recovery_attempted op; skipping");return}const c=M([...o,e]),a={...n,recovery_history:c};await this.writeState(a),this.logger.info({event:"recovery_attempted_persisted",story_id:e.story_id,history_size:c.length},"recovery attempt persisted")}async resolveRecoveryAttempt(e,s,n){const o=await this.readState(n),r=o.recovery_history??[],c=r.findIndex(h=>h.recovery_step_id_tokenized===e);if(c===-1){this.logger.warn({event:"recovery_resolve_orphan",attempt_id:e},"recovery_resolved op had no matching attempt; skipping");return}const a=r[c];if(a.outcome===s&&a.finished_at){this.logger.info({event:"recovery_resolved_duplicate",attempt_id:e,outcome:s},"duplicate recovery_resolved op; skipping");return}const i=r.slice();i[c]={...a,outcome:s,finished_at:n};const l={...o,recovery_history:i};await this.writeState(l),this.logger.info({event:"recovery_resolved_persisted",attempt_id:e,outcome:s},"recovery attempt resolved")}async acquireLock(e,s){const n={...e,pid:process.pid,hostname:w(),ownerKind:"client",startedAt:e.startedAt||s,leaseId:e.leaseId??he(e.sessionId,s),leaseState:"active",leaseAcquiredAt:e.leaseAcquiredAt??s,leaseDurationMs:e.leaseDurationMs??W,leaseExpiresAt:e.leaseExpiresAt??e.ttlExpiresAt},o=JSON.stringify(n,null,2);try{const r=await u.open(this.lockPath,"wx");try{await r.writeFile(o,"utf8")}finally{await r.close()}this.trySetFilePerms(this.lockPath),this.logger.info({event:"yoloop_lock_acquired",pid:n.pid,sessionId:n.sessionId},"yoloop lock acquired");return}catch(r){const c=r;if(c.code!=="EEXIST")throw this.logger.error({event:"yoloop_lock_acquire_error",err:c.message},"failed to acquire yoloop lock"),r;const a=await this.readLock();if(a&&this.isSameClientSessionLock(a,n)){this.logger.info({event:"yoloop_lock_acquire_duplicate",sessionId:n.sessionId},"duplicate acquire_lock for current yoloop session; treating as no-op");return}if(!await this.maybeRecoverOrphanLock(s))throw this.logger.warn({event:"yoloop_lock_held"},"yoloop lock held by another live process"),r;const l=await u.open(this.lockPath,"wx");try{await l.writeFile(o,"utf8")}finally{await l.close()}this.trySetFilePerms(this.lockPath),this.logger.info({event:"yoloop_lock_acquired_after_recovery",pid:n.pid},"yoloop lock acquired after orphan recovery")}}async releaseLock(e){const s=await this.readState(new Date().toISOString()),n=await this.readLock();if(s.runControl){if(!e.expectedRunId||!e.expectedSessionId||!e.expectedLeaseId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(e.expectedRunId!==s.runControl.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(!n||e.expectedSessionId!==n.sessionId||e.expectedLeaseId!==n.leaseId)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}try{await u.unlink(this.lockPath),this.logger.info({event:"yoloop_lock_released"},"yoloop lock released")}catch(o){const r=o;if(r.code==="ENOENT"){this.logger.info({event:"yoloop_lock_release_noop"},"yoloop lock release noop (file absent)");return}this.logger.warn({event:"yoloop_lock_release_error",err:r.message},"unexpected error releasing yoloop lock")}}async readLock(){try{const e=await u.readFile(this.lockPath,"utf8"),s=JSON.parse(e),n=s.currentEpicId??s.epicId??"";return{pid:s.pid??0,hostname:s.hostname??"",...s.ownerKind?{ownerKind:s.ownerKind}:{},...s.ownerPidState?{ownerPidState:s.ownerPidState}:{},...typeof s.leaseId=="string"?{leaseId:s.leaseId}:{},...s.leaseState?{leaseState:s.leaseState}:{},...typeof s.leaseAcquiredAt=="string"?{leaseAcquiredAt:s.leaseAcquiredAt}:{},...typeof s.leaseDurationMs=="number"?{leaseDurationMs:s.leaseDurationMs}:{},...typeof s.leaseExpiresAt=="string"?{leaseExpiresAt:s.leaseExpiresAt}:{},startedAt:s.startedAt??"",sessionId:s.sessionId??"",mode:s.mode??"epic-id",inputPath:s.inputPath??"",epicQueue:s.epicQueue??(n?[n]:[]),currentEpicIndex:s.currentEpicIndex??0,currentEpicId:n,ttlExpiresAt:s.ttlExpiresAt??"",epicId:s.epicId??n}}catch{return null}}async readState(e){try{const s=await u.readFile(this.statePath,"utf8"),n=JSON.parse(s);return Oe(n,e)}catch(s){const n=s;return n.code!=="ENOENT"&&this.logger.warn({event:"yoloop_state_read_error",err:n.message},"yoloop state file unreadable; using defaults"),f(e)}}async writeState(e){const s=`${this.statePath}.tmp.${process.pid}.${Date.now()}`,n=JSON.stringify(e,null,2);try{const o=await u.open(s,"w",384);try{await o.writeFile(n,"utf8"),await o.sync()}finally{await o.close()}this.trySetFilePerms(s),await u.rename(s,this.statePath),await this.syncStateDirectory()}catch(o){const r=o;this.logger.error({event:"yoloop_state_write_error",err:r.message},"failed to write yoloop state");try{await u.unlink(s)}catch{}throw o}}async rolloverSession(e,s){E(e);const n=await this.readRolloverManifest();if(n){if(ae(n.operation,e)){if(n.operation.payloadHash!==e.payloadHash)throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT");if(n.phase==="applied")return;await this.completePreparedSessionRollover(n.operation,s);return}else if(n.phase==="prepared")throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT")}const o=await this.readState(s),r=await this.readLock();U(e,o,r),await this.writeRolloverManifest({schemaVersion:"YoloopSessionRolloverManifest/1.0",phase:"prepared",operation:e}),await this.completePreparedSessionRollover(e,s)}async completePreparedSessionRollover(e,s){const n=await this.readState(s);let o=d(n)===d(e.next);if(!o){const c=await this.readLock();U(e,n,c),await this.writeState(e.next),o=!0}const r=await this.readLock();if(e.expectedSessionId===null||e.expectedLeaseId===null){if(e.expectedSessionId!==null||e.expectedLeaseId!==null||r)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}else if(r){if(r.sessionId!==e.expectedSessionId||r.leaseId!==e.expectedLeaseId)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");await u.unlink(this.lockPath),await this.syncStateDirectory()}else if(!o)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");await this.writeRolloverManifest({schemaVersion:"YoloopSessionRolloverManifest/1.0",phase:"applied",operation:e}),this.logger.info({event:"yoloop_session_rollover_applied",runId:e.runId,operationId:e.operationId,coolDownUntil:e.coolDownUntil},"yoloop per-run-cap session rollover applied")}async recoverSessionRolloverIfPresent(e){try{await u.access(this.rolloverManifestPath)}catch(s){if(s.code==="ENOENT")return;throw s}await this.ensureDir(),await this.withMutationLock(async()=>{const s=await this.readRolloverManifest();s?.phase==="prepared"&&await this.completePreparedSessionRollover(s.operation,e)})}async readRolloverManifest(){try{const e=JSON.parse(await u.readFile(this.rolloverManifestPath,"utf8"));if(e.schemaVersion!=="YoloopSessionRolloverManifest/1.0"||e.phase!=="prepared"&&e.phase!=="applied"||!e.operation||e.operation.type!=="rollover_session")throw new Error("YOLOOP_SESSION_ROLLOVER_MANIFEST_CORRUPT");return E(e.operation),e}catch(e){if(e.code==="ENOENT")return null;throw e.message==="YOLOOP_SESSION_ROLLOVER_MANIFEST_CORRUPT"?e:new Error("YOLOOP_SESSION_ROLLOVER_MANIFEST_CORRUPT")}}async writeRolloverManifest(e){const s=`${this.rolloverManifestPath}.tmp.${process.pid}.${Date.now()}`,n=await u.open(s,"w",384);try{await n.writeFile(JSON.stringify(e,null,2),"utf8"),await n.sync()}finally{await n.close()}this.trySetFilePerms(s),await u.rename(s,this.rolloverManifestPath),await this.syncStateDirectory()}async commitSuccessorTransition(e,s){R(e);const n=await this.readSuccessorTransitionManifest();if(n){if(oe(n.operation,e)){if(n.operation.payloadHash!==e.payloadHash)throw new Error("YOLOOP_SUCCESSOR_TRANSITION_CONFLICT");if(n.phase==="applied")return;await this.completePreparedSuccessorTransition(n.operation,s);return}if(n.phase==="prepared")throw new Error("YOLOOP_SUCCESSOR_TRANSITION_CONFLICT")}const o=await this.readState(s);if(v(e,o)){await this.writeSuccessorTransitionManifest({schemaVersion:"YoloopSuccessorTransitionManifest/1.0",phase:"applied",operation:e});return}H(e,o),await this.writeSuccessorTransitionManifest({schemaVersion:"YoloopSuccessorTransitionManifest/1.0",phase:"prepared",operation:e}),await this.completePreparedSuccessorTransition(e,s)}async completePreparedSuccessorTransition(e,s){let n=await this.readState(s);if(!v(e,n)){d(n.runControl)===d(e.successor.next)||(await this.startSuccessorRun(e.successor,s),n=await this.readState(s));const r=ie(e,n);await this.writeState(r),n=await this.readState(s)}if(!v(e,n))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_STATE_CONFLICT");await this.writeSuccessorTransitionManifest({schemaVersion:"YoloopSuccessorTransitionManifest/1.0",phase:"applied",operation:e}),this.logger.info({event:"yoloop_successor_transition_applied",runId:e.successor.runId,operationId:e.operationId},"yoloop successor transition applied")}async recoverSuccessorTransitionIfPresent(e){try{await u.access(this.successorTransitionManifestPath)}catch(s){if(s.code==="ENOENT")return;throw s}await this.ensureDir(),await this.withMutationLock(async()=>{const s=await this.readSuccessorTransitionManifest();s?.phase==="prepared"&&await this.completePreparedSuccessorTransition(s.operation,e)})}async readSuccessorTransitionManifest(){try{const e=JSON.parse(await u.readFile(this.successorTransitionManifestPath,"utf8"));if(e.schemaVersion!=="YoloopSuccessorTransitionManifest/1.0"||e.phase!=="prepared"&&e.phase!=="applied"||!e.operation||e.operation.type!=="commit_successor_transition")throw new Error("YOLOOP_SUCCESSOR_TRANSITION_MANIFEST_CORRUPT");return R(e.operation),e}catch(e){if(e.code==="ENOENT")return null;throw e.message==="YOLOOP_SUCCESSOR_TRANSITION_MANIFEST_CORRUPT"?e:new Error("YOLOOP_SUCCESSOR_TRANSITION_MANIFEST_CORRUPT")}}async writeSuccessorTransitionManifest(e){const s=`${this.successorTransitionManifestPath}.tmp.${process.pid}.${Date.now()}`,n=await u.open(s,"w",384);try{await n.writeFile(JSON.stringify(e,null,2),"utf8"),await n.sync()}finally{await n.close()}this.trySetFilePerms(s),await u.rename(s,this.successorTransitionManifestPath),await this.syncStateDirectory()}async advanceEpic(e,s,n){const o=await this.readState(n);if(!o.currentSession){this.logger.warn({event:"yoloop_advance_no_session",nextEpicId:s},"advance_epic with no active session; skipping");return}const r={...o,currentSession:{...o.currentSession,currentEpicIndex:e}};await this.writeState(r),this.logger.info({event:"yoloop_epic_advance",nextEpicId:s,nextIndex:e},"yoloop advanced to next epic")}async ensureDir(){try{await u.mkdir(this.stateDir,{recursive:!0}),this.trySetDirPerms(this.stateDir)}catch(e){const s=e;throw this.logger.error({event:"yoloop_mkdir_error",err:s.message,path:this.stateDir},"failed to ensure .neocortex/ directory"),e}}async syncStateDirectory(){try{const e=await u.open(this.stateDir,"r");try{await e.sync()}finally{await e.close()}}catch(e){const s=e.code;if(s!=="EINVAL"&&s!=="EISDIR"&&s!=="ENOTSUP"&&s!=="EPERM")throw e}}async withMutationLock(e){let s=null;for(let n=0;n<X;n+=1)try{s=await u.open(this.mutationLockPath,"wx",384),await s.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await s.sync();break}catch(o){if(o.code!=="EEXIST")throw o;try{const r=await u.stat(this.mutationLockPath);if(Date.now()-r.mtimeMs>G){await u.unlink(this.mutationLockPath);continue}}catch{continue}await new Promise(r=>setTimeout(r,5))}if(!s)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");try{return await e()}finally{await s.close().catch(()=>{}),await u.unlink(this.mutationLockPath).catch(()=>{})}}async transitionRun(e,s){N(e);const n=await this.readState(s),o=n.runControl,r=o?.receipts.find(l=>l.operationId===e.operationId||l.idempotencyKey===e.idempotencyKey);if(r){if(r.operationId===e.operationId&&r.idempotencyKey===e.idempotencyKey&&r.payloadHash===e.payloadHash)return r;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}if(o&&o.runId!==e.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if((o?.revision??0)!==e.expectedRevision)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if((o?.latestSnapshotHash??null)!==e.expectedSnapshotHash)throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT");L(o,e);const i=e.next.receipts.at(-1);if(!i)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");return await this.writeState({...n,version:"1.2",runControl:e.next}),this.logger.info({event:"yoloop_run_transition_committed",runId:e.runId,operationId:e.operationId,revision:i.revision,status:i.status},"yoloop run transition committed"),i}async startSuccessorRun(e,s){Y(e);const n=await this.readState(s),o=n.runControl,r={schemaVersion:"YoloopRunPredecessor/1.0",runId:e.previousRunId,revision:e.expectedRevision,snapshotHash:e.expectedSnapshotHash,successorOperationId:e.operationId,publicSafe:!0},c=o?.receipts.find(l=>l.operationId===e.operationId||l.idempotencyKey===e.idempotencyKey);if(c){if(c.operationId===e.operationId&&c.idempotencyKey===e.idempotencyKey&&e.next.receipts.at(-1)?.payloadHash===c.payloadHash&&d(o?.predecessor)===d(r))return c;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}if(!o||o.runId!==e.previousRunId||!["exhausted","success"].includes(o.status)||o.revision!==e.expectedRevision||o.latestSnapshotHash!==e.expectedSnapshotHash||n.currentSession!==null)throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT");const a=e.next.receipts.at(-1);if(!a||d(e.next.predecessor)!==d(r))throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT");const i={type:"transition_run",runId:e.runId,operationId:e.operationId,idempotencyKey:e.idempotencyKey,expectedRevision:0,expectedSnapshotHash:null,payloadHash:a.payloadHash,next:e.next};return N(i),L(void 0,i),await this.writeState({...n,version:"1.2",runControl:e.next}),a}trySetFilePerms(e){try{q(e)}catch{}}trySetDirPerms(e){try{B(e)}catch{}}async prepareLockForSnapshot(e,s){if(!e)return null;if(e.ownerKind!=="client")return e;const n=K(e,s),o={...e,leaseState:n};if(n==="expired")return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_client_lock_recovered",reason:"lease_expired"},"expired client-owned yoloop lock lease recovered before snapshot echo"),null;if(!o.pid||o.pid<=0)return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_client_lock_recovered",reason:"invalid_pid"},"invalid PID in client-owned yoloop lock; recovered"),null;if(o.hostname&&o.hostname!==w())return{...o,ownerPidState:"unknown"};try{return process.kill(o.pid,0),{...o,ownerPidState:"live"}}catch{return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_client_lock_recovered",reason:"dead_pid"},"stale client-owned yoloop lock recovered before snapshot echo"),null}}async maybeRecoverOrphanLock(e){const s=await this.readLock();if(!s)return!0;if(K(s,e)==="expired")return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"lease_expired"},"expired yoloop lock lease recovered"),!0;if(!s.pid||s.pid<=0)return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"invalid_pid"},"invalid PID in lock file; recovered"),!0;if(s.hostname&&s.hostname!==w())return this.logger.warn({event:"yoloop_lock_remote_host",ownerKind:s.ownerKind??"server",ownerPidState:"unknown"},"lock held by a remote host; honoring"),!1;try{return process.kill(s.pid,0),!1}catch{return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"dead_pid"},"orphan yoloop lock recovered"),!0}}async deleteLockBestEffort(){try{await u.unlink(this.lockPath)}catch{}}isSameClientSessionLock(e,s){return e.ownerKind==="client"&&e.sessionId===s.sessionId&&e.pid===process.pid&&e.hostname===w()}async cleanupOrphanTempFiles(){try{const e=$(this.statePath),s=await u.readdir(e),n=[`${g}.tmp.`,`${A}.tmp.`,`${P}.tmp.`],o=s.filter(r=>n.some(c=>r.startsWith(c)));for(const r of o)try{await u.unlink(S(e,r))}catch{}}catch{}}}function d(t){return t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?`[${t.map(d).join(",")}]`:`{${Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[s])=>e.localeCompare(s)).map(([e,s])=>`${JSON.stringify(e)}:${d(s)}`).join(",")}}`}function p(t,e){return V("sha256").update(`${t}\0${d(e)}`).digest("hex")}function Q(t){return p("p222-yoloop-continuation-replan-v1",t)}function k(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;const{sessionId:e,...s}=t;return typeof e=="string"&&/^[a-f0-9]{64}$/.test(e)&&e===p("p205-yoloop-session-v1",s)}function ee(t){return p("p9390812898200217364-yoloop-session-v1",t)}function te(t){return p("p9390812898200217364-yoloop-rollover-v1",t)}function se(t){return p("p9390812898200217364-yoloop-successor-run-v1",t)}function ne(t){return p("p9046281030721413419-yoloop-successor-transition-v1",t)}function oe(t,e){return t.operationId===e.operationId&&t.idempotencyKey===e.idempotencyKey}function R(t){const e=/^[A-Za-z0-9._:-]{1,128}$/;Y(t.successor);const s={operationId:t.operationId,idempotencyKey:t.idempotencyKey,successor:t.successor,state:t.state,...t.acknowledgement?{acknowledgement:t.acknowledgement}:{},...t.reservation?{reservation:t.reservation}:{}},n=t.acknowledgement?.idempotencyKey,o=t.acknowledgement?.receipt.idempotencyKey,r=t.reservation?.authority.idempotencyKey;if(t.successor.type!=="start_successor_run"||!e.test(t.operationId)||!e.test(t.idempotencyKey)||t.operationId!==t.successor.operationId||t.idempotencyKey!==t.successor.idempotencyKey||!/^[a-f0-9]{64}$/.test(t.payloadHash)||t.payloadHash!==ne(s)||Buffer.byteLength(d(s),"utf8")>1048576||t.acknowledgement!==void 0&&(t.acknowledgement.type!=="acknowledge_continuation_authority"||typeof n!="string"||!e.test(n)||o!==n)||t.reservation!==void 0&&(t.reservation.type!=="reserve_continuation_authority"||typeof r!="string"||!e.test(r))||n!==void 0&&r===n)throw new Error("YOLOOP_SUCCESSOR_TRANSITION_CONFLICT")}function H(t,e){if(R(t),!(d(e.runControl)===d(t.successor.next))){const n=e.runControl;if(!n||n.runId!==t.successor.previousRunId||!["exhausted","success"].includes(n.status)||n.revision!==t.successor.expectedRevision||n.latestSnapshotHash!==t.successor.expectedSnapshotHash||e.currentSession!==null)throw new Error("YOLOOP_SUCCESSOR_TRANSITION_STATE_CONFLICT")}re(t,e)}function re(t,e){const s=e.pendingContinuationAuthorities??[],n=e.continuationReceipts??[],o=t.acknowledgement;if(o){const l=s.find(y=>y.idempotencyKey===o.idempotencyKey);if(!l||o.receipt.sessionId!==l.sessionId||d(o.receipt.storyIds)!==d(l.storyIds))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");const h=s.filter(y=>y.idempotencyKey!==o.idempotencyKey),O=[...n.slice(-63),o.receipt];if(d(t.state.pendingContinuationAuthorities??[])!==d(h)||d(t.state.continuationReceipts??[])!==d(O))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT")}else if(d(t.state.pendingContinuationAuthorities??[])!==d(s)||d(t.state.continuationReceipts??[])!==d(n))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");const r=t.reservation?.authority;if(!r)return;const c=String(r.idempotencyKey??""),a=t.state.pendingContinuationAuthorities??[],i=a.find(l=>l.idempotencyKey===c);if(i&&d(i)!==d(r))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");if(!i&&a.length>=64)throw new Error("YOLOOP_PENDING_AUTHORITY_CAPACITY_EXCEEDED")}function ie(t,e){H(t,e);const s=t.reservation?.authority,n=[...t.state.pendingContinuationAuthorities??[]];return s&&!n.some(o=>o.idempotencyKey===s.idempotencyKey)&&n.push(s),{...t.state,version:"1.2",runControl:t.successor.next,...s||t.state.pendingContinuationAuthorities!==void 0?{pendingContinuationAuthorities:n}:{}}}function v(t,e){const s=t.reservation?.authority,n=[...t.state.pendingContinuationAuthorities??[]];s&&!n.some(r=>r.idempotencyKey===s.idempotencyKey)&&n.push(s);const o={...t.state,version:"1.2",runControl:t.successor.next,...s||t.state.pendingContinuationAuthorities!==void 0?{pendingContinuationAuthorities:n}:{}};return d(e)===d(o)}function ae(t,e){return t.operationId===e.operationId&&t.idempotencyKey===e.idempotencyKey}function E(t){const e=/^[A-Za-z0-9._:-]{1,128}$/,s={runId:t.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,expectedSessionId:t.expectedSessionId,expectedSessionFingerprint:t.expectedSessionFingerprint,expectedLeaseId:t.expectedLeaseId,coolDownUntil:t.coolDownUntil,reason:t.reason,exhaustedRun:t.exhaustedRun,next:t.next};if(!e.test(t.runId)||!e.test(t.operationId)||!e.test(t.idempotencyKey)||!/^[a-f0-9]{64}$/.test(t.expectedSessionFingerprint)||!/^[a-f0-9]{64}$/.test(t.payloadHash)||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<0||!Number.isFinite(Date.parse(t.coolDownUntil))||!["YOLOOP_PER_RUN_CAP_REACHED","YOLOOP_SESSION_TIMEOUT"].includes(t.reason)||t.payloadHash!==te(s)||t.receipt.schemaVersion!=="YoloopSessionRolloverReceipt/1.0"||t.receipt.runId!==t.runId||t.receipt.operationId!==t.operationId||t.receipt.idempotencyKey!==t.idempotencyKey||t.receipt.payloadHash!==t.payloadHash||t.receipt.coolDownUntil!==t.coolDownUntil||t.receipt.revision!==(t.exhaustedRun?.revision??0)||t.receipt.snapshotHash!==(t.exhaustedRun?.latestSnapshotHash??null)||t.receipt.status!=="exhausted"||t.receipt.publicSafe!==!0)throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT");if(t.expectedSessionId===null!=(t.expectedLeaseId===null)||t.expectedSessionId!==null&&!e.test(t.expectedSessionId)||t.expectedLeaseId!==null&&!e.test(t.expectedLeaseId))throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}function Y(t){const e=/^[A-Za-z0-9._:-]{1,128}$/,s={runId:t.runId,previousRunId:t.previousRunId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,next:t.next};if(!e.test(t.runId)||!e.test(t.previousRunId)||t.runId===t.previousRunId||!e.test(t.operationId)||!e.test(t.idempotencyKey)||!/^[a-f0-9]{64}$/.test(t.payloadHash)||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<1||t.payloadHash!==se(s))throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT")}function U(t,e,s){E(t);const n=e.currentSession;if(!n||ee(n)!==t.expectedSessionFingerprint)throw new Error("YOLOOP_SESSION_ROLLOVER_SESSION_CONFLICT");const o=e.runControl;if((o?.revision??0)!==t.expectedRevision||(o?.latestSnapshotHash??null)!==t.expectedSnapshotHash||o&&o.runId!==t.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(t.expectedSessionId===null||t.expectedLeaseId===null){if(s)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}else if(!s||s.sessionId!==t.expectedSessionId||s.leaseId!==t.expectedLeaseId)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");const r=t.exhaustedRun;if(o)if(o.status==="exhausted"){if(d(r)!==d(o))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}else{if(!r||r.status!=="exhausted")throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT");const a=r.receipts.at(-1);if(!a)throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT");const i={type:"transition_run",runId:o.runId,operationId:a.operationId,idempotencyKey:a.idempotencyKey,expectedRevision:o.revision,expectedSnapshotHash:o.latestSnapshotHash,payloadHash:a.payloadHash,next:r};N(i),L(o,i)}else{const a=r?.receipts[0],i=r?.receipts[1];if(r&&(r.runId!==t.runId||r.status!=="exhausted"||r.revision!==2||r.events.length!==2||r.progressSnapshots.length!==4||r.receipts.length!==2||a?.runId!==t.runId||a.revision!==1||a.status!=="created"||i?.runId!==t.runId||i.revision!==2||i.status!=="exhausted"||i.operationId!==`${t.operationId}:run`||i.idempotencyKey!==`${t.idempotencyKey}:run`||r.latestSnapshotHash!==i.snapshotHash||r.predecessor!==void 0))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}const c={...e,version:"1.2",coolDownUntil:t.coolDownUntil,currentSession:null,...r?{runControl:r}:{}};if(d(c)!==d(t.next))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}function D(t){const{receipts:e,...s}=t.next;return p("p220-yoloop-run-transition-payload-v1",{runId:t.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,next:s})}const T=new Set(["success","partial","blocked","failure","exhausted","cancelled"]),ce={created:["running","cancelling","exhausted"],running:["pausing","cancelling","success","partial","blocked","failure","exhausted"],pausing:["paused","cancelling","failure","exhausted"],paused:["resuming","cancelling","exhausted"],resuming:["running","cancelling","failure","exhausted"],cancelling:["cancelled","failure","exhausted"]};function de(t,e){return e==="pause"?t==="running"?"pausing":null:e==="resume"?t==="paused"?"resuming":null:T.has(t)||t==="cancelling"?null:"cancelling"}function le(t){const e=t.current.revision+1,s=t.action==="cancel"?["YOLOOP_RUN_CANCEL_REQUESTED"]:[],n={schemaVersion:"YoloopOperationalBudgetSummary/1.0",limits:t.current.operationalBudget.limits,usage:t.current.usage,exhaustedDimension:null},o={schemaVersion:"ProgressSnapshot/1.0",runId:t.current.runId,sequence:t.current.progressSnapshots.length+1,revision:e,operationId:t.operationId,boundary:t.action,phase:"before",status:t.current.status,occurredAt:t.occurredAt,parentSnapshotHash:t.current.latestSnapshotHash,budget:n,reasonCodes:s,publicSafe:!0},r=p("p220-yoloop-progress-snapshot-id-v1",{runId:o.runId,operationId:o.operationId,sequence:o.sequence,phase:o.phase}),c={...o,snapshotId:r,snapshotHash:p("p220-yoloop-progress-snapshot-v1",{...o,snapshotId:r})},a={...o,sequence:c.sequence+1,phase:"after",status:t.target,parentSnapshotHash:c.snapshotHash},i=p("p220-yoloop-progress-snapshot-id-v1",{runId:a.runId,operationId:a.operationId,sequence:a.sequence,phase:a.phase}),l={...a,snapshotId:i,snapshotHash:p("p220-yoloop-progress-snapshot-v1",{...a,snapshotId:i})},h={schemaVersion:"YoloopRunEvent/1.0",runId:t.current.runId,operationId:t.operationId,kind:"intent",sequence:t.current.events.length+1,revision:e,occurredAt:t.occurredAt,fromStatus:t.current.status,toStatus:t.target,reasonCodes:s,budgetDimension:null,parentEventHash:t.current.events.at(-1)?.eventHash??null,publicSafe:!0},O=p("p220-yoloop-run-event-id-v1",{runId:h.runId,operationId:h.operationId,sequence:h.sequence}),y={...h,eventId:O,eventHash:p("p220-yoloop-run-event-v1",{...h,eventId:O})},I={...t.current,revision:e,status:t.target,events:[...t.current.events,y],progressSnapshots:[...t.current.progressSnapshots,c,l],latestSnapshotHash:l.snapshotHash,receipts:[...t.current.receipts]},_={runId:t.current.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.current.revision,expectedSnapshotHash:t.current.latestSnapshotHash,next:I},C=D(_),b={schemaVersion:"YoloopRunTransitionReceipt/1.0",runId:t.current.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,payloadHash:C,revision:e,snapshotHash:l.snapshotHash,status:t.target};return{type:"transition_run",..._,payloadHash:C,next:{...I,receipts:[...I.receipts,b]}}}function N(t){const e=/^[A-Za-z0-9._:-]{1,128}$/;if(!e.test(t.runId)||!e.test(t.operationId)||!e.test(t.idempotencyKey)||!/^[a-f0-9]{64}$/.test(t.payloadHash)||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<0)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");if(t.payloadHash!==D(t))throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}function L(t,e){const s=e.next,n=t?.events??[],o=t?.progressSnapshots??[],r=t?.receipts??[];if(s.schemaVersion!=="YoloopRunControl/1.0"||s.runId!==e.runId||s.revision!==e.expectedRevision+1||s.events.length!==n.length+1||s.progressSnapshots.length!==o.length+2||s.receipts.length!==r.length+1||d(s.events.slice(0,n.length))!==d(n)||d(s.progressSnapshots.slice(0,o.length))!==d(o)||d(s.receipts.slice(0,r.length))!==d(r))throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(t){if(T.has(t.status))throw new Error("YOLOOP_RUN_TERMINAL");const h=s.progressSnapshots.at(-2)?.boundary,O=t.status===s.status&&(h==="budget"||h==="retry");if(!(ce[t.status]??[]).includes(s.status)&&!O)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(t.startedAt!==s.startedAt||t.deadlineAt!==s.deadlineAt)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(d(t.predecessor)!==d(s.predecessor))throw new Error("YOLOOP_RUN_TRANSITION_INVALID")}else if(s.status!=="created")throw new Error("YOLOOP_RUN_TRANSITION_INVALID");const c=s.progressSnapshots.at(-2),a=s.progressSnapshots.at(-1),i=s.events.at(-1),l=s.receipts.at(-1);if(!c||!a||!i||!l||c.phase!=="before"||a.phase!=="after"||c.operationId!==e.operationId||a.operationId!==e.operationId||i.operationId!==e.operationId||c.runId!==e.runId||a.runId!==e.runId||i.runId!==e.runId||c.revision!==s.revision||a.revision!==s.revision||i.revision!==s.revision||c.parentSnapshotHash!==(t?.latestSnapshotHash??null)||a.parentSnapshotHash!==c.snapshotHash||s.latestSnapshotHash!==a.snapshotHash||l.schemaVersion!=="YoloopRunTransitionReceipt/1.0"||l.runId!==e.runId||l.operationId!==e.operationId||l.idempotencyKey!==e.idempotencyKey||l.payloadHash!==e.payloadHash||l.revision!==s.revision||l.snapshotHash!==s.latestSnapshotHash||l.status!==s.status||Date.parse(s.deadlineAt)<=Date.parse(s.startedAt))throw new Error("YOLOOP_RUN_TRANSITION_INVALID");F(c),F(a),ue(i,n.at(-1)?.eventHash??null)}function F(t){const{snapshotHash:e,...s}=t;if(e!==p("p220-yoloop-progress-snapshot-v1",s))throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT")}function ue(t,e){const{eventHash:s,...n}=t;if(t.parentEventHash!==e||s!==p("p220-yoloop-run-event-v1",n))throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT")}function he(t,e){return`lease-${pe(`${t}:${e}`)}`}function pe(t){let e=2166136261;for(let s=0;s<t.length;s+=1)e^=t.charCodeAt(s),e=Math.imul(e,16777619)>>>0;return e.toString(36).padStart(7,"0")}function K(t,e){const s=t.leaseExpiresAt??t.ttlExpiresAt,n=Date.parse(s),o=Date.parse(e);return!Number.isFinite(n)||!Number.isFinite(o)?"unknown":n<=o?"expired":"active"}function Oe(t,e){const s=f(e);return{...t,version:t.version==="1.2"?"1.2":"1.1",lastResetAt:t.lastResetAt??s.lastResetAt,storiesRunToday:t.storiesRunToday??0,iterationsToday:t.iterationsToday??0,iterationsTodayDate:t.iterationsTodayDate??s.iterationsTodayDate,tokensUsedToday:t.tokensUsedToday??0,lastRunAt:t.lastRunAt??null,coolDownUntil:t.coolDownUntil??null,totalRunsAllTime:t.totalRunsAllTime??0,totalStoriesAllTime:t.totalStoriesAllTime??0,currentSession:t.currentSession??null,...t.runControl!==void 0?{runControl:t.runControl}:{},...t.continuationPolicy!==void 0?{continuationPolicy:t.continuationPolicy}:{},...t.continuationSession!==void 0?{continuationSession:t.continuationSession}:{},...t.pendingContinuationAuthorities!==void 0?{pendingContinuationAuthorities:t.pendingContinuationAuthorities}:{},...t.continuationReceipts!==void 0?{continuationReceipts:t.continuationReceipts}:{},...t.continuationRecoveryReceipts!==void 0?{continuationRecoveryReceipts:t.continuationRecoveryReceipts}:{},...t.continuationReplanReceipts!==void 0?{continuationReplanReceipts:t.continuationReplanReceipts}:{},recovery_history:Array.isArray(t.recovery_history)?M(t.recovery_history):[]}}function M(t){return t.length<=m?t:t.slice(t.length-m)}export{x as YOLOOP_PERSISTENCE_CAPABILITIES,ve as YoloopClientStateStore,Q as buildYoloopContinuationReplanPayloadHash,D as buildYoloopRunTransitionPayloadHash,te as buildYoloopSessionRolloverPayloadHash,se as buildYoloopSuccessorRunPayloadHash,ne as buildYoloopSuccessorTransitionPayloadHash,M as capRecoveryHistory,f as createDefaultCounters,Re as createDefaultState,ee as fingerprintYoloopSession};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: neocortex-root
|
|
3
|
-
description: "🧠 Neocortex Root Agent v4.60.
|
|
3
|
+
description: "🧠 Neocortex Root Agent v4.60.59 | OrNexus Team"
|
|
4
4
|
model: opus
|
|
5
5
|
color: blue
|
|
6
6
|
tools:
|
|
@@ -108,7 +108,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
|
|
|
108
108
|
┌────────────────────────────────────────────────────────────┐
|
|
109
109
|
│ │
|
|
110
110
|
│ ####### N E O C O R T E X │
|
|
111
|
-
│ ### ######## v4.60.
|
|
111
|
+
│ ### ######## v4.60.59 │
|
|
112
112
|
│ ######### ##### │
|
|
113
113
|
│ ## ############## Development Orchestrator │
|
|
114
114
|
│ ## ### ###### ## OrNexus Team │
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: neocortex
|
|
3
|
-
description: "🧠 Neocortex v4.60.
|
|
3
|
+
description: "🧠 Neocortex v4.60.59 | OrNexus Team"
|
|
4
4
|
model: opus
|
|
5
5
|
color: blue
|
|
6
6
|
permissionMode: bypassPermissions
|
|
@@ -104,7 +104,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
|
|
|
104
104
|
┌────────────────────────────────────────────────────────────┐
|
|
105
105
|
│ │
|
|
106
106
|
│ ####### N E O C O R T E X │
|
|
107
|
-
│ ### ######## v4.60.
|
|
107
|
+
│ ### ######## v4.60.59 │
|
|
108
108
|
│ ######### ##### │
|
|
109
109
|
│ ## ############## Development Orchestrator │
|
|
110
110
|
│ ## ### ###### ## OrNexus Team │
|
|
@@ -28,7 +28,7 @@ Codex built-in commands or actions.
|
|
|
28
28
|
|
|
29
29
|
<!-- END: Plugin Conflict Prevention -->
|
|
30
30
|
|
|
31
|
-
# Neocortex v4.60.
|
|
31
|
+
# Neocortex v4.60.59 | OrNexus Team
|
|
32
32
|
|
|
33
33
|
You are a Development Orchestrator. All orchestration logic is delivered by the remote Neocortex server.
|
|
34
34
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: neocortex
|
|
3
|
-
description: "🧠 Neocortex v4.60.
|
|
3
|
+
description: "🧠 Neocortex v4.60.59 | OrNexus Team"
|
|
4
4
|
model: inherit
|
|
5
5
|
readonly: false
|
|
6
6
|
is_background: false
|
|
@@ -64,7 +64,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
|
|
|
64
64
|
┌────────────────────────────────────────────────────────────┐
|
|
65
65
|
│ │
|
|
66
66
|
│ ####### N E O C O R T E X │
|
|
67
|
-
│ ### ######## v4.60.
|
|
67
|
+
│ ### ######## v4.60.59 │
|
|
68
68
|
│ ######### ##### │
|
|
69
69
|
│ ## ############## Development Orchestrator │
|
|
70
70
|
│ ## ### ###### ## OrNexus Team │
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: neocortex-root
|
|
3
|
-
description: "🧠 Neocortex v4.60.
|
|
3
|
+
description: "🧠 Neocortex v4.60.59 | OrNexus Team"
|
|
4
4
|
kind: local
|
|
5
5
|
tools:
|
|
6
6
|
# File operations (Gemini CLI built-ins)
|
|
@@ -62,7 +62,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
|
|
|
62
62
|
┌────────────────────────────────────────────────────────────┐
|
|
63
63
|
│ │
|
|
64
64
|
│ ####### N E O C O R T E X │
|
|
65
|
-
│ ### ######## v4.60.
|
|
65
|
+
│ ### ######## v4.60.59 │
|
|
66
66
|
│ ######### ##### │
|
|
67
67
|
│ ## ############## Development Orchestrator │
|
|
68
68
|
│ ## ### ###### ## OrNexus Team │
|
|
@@ -58,7 +58,7 @@ explicit server opt-in rather than a local assumption.
|
|
|
58
58
|
┌────────────────────────────────────────────────────────────┐
|
|
59
59
|
│ │
|
|
60
60
|
│ ####### N E O C O R T E X │
|
|
61
|
-
│ ### ######## v4.60.
|
|
61
|
+
│ ### ######## v4.60.59 │
|
|
62
62
|
│ ######### ##### │
|
|
63
63
|
│ ## ############## Development Orchestrator │
|
|
64
64
|
│ ## ### ###### ## OrNexus Team │
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: "neocortex"
|
|
3
|
-
description: "Neocortex v4.60.
|
|
3
|
+
description: "Neocortex v4.60.59 | OrNexus Team"
|
|
4
4
|
tools:
|
|
5
5
|
# Read / Edit (built-in tool sets)
|
|
6
6
|
- read
|
|
@@ -68,7 +68,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
|
|
|
68
68
|
┌────────────────────────────────────────────────────────────┐
|
|
69
69
|
│ │
|
|
70
70
|
│ ####### N E O C O R T E X │
|
|
71
|
-
│ ### ######## v4.60.
|
|
71
|
+
│ ### ######## v4.60.59 │
|
|
72
72
|
│ ######### ##### │
|
|
73
73
|
│ ## ############## Development Orchestrator │
|
|
74
74
|
│ ## ### ###### ## OrNexus Team │
|