@ornexus/neocortex 4.66.50 → 4.66.52
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/release-source.json +1 -1
- package/dist/sbom.cdx.json +1190 -1190
- package/install.js +8 -8
- package/install.ps1 +188 -162
- package/install.sh +1 -1
- package/package.json +2 -2
- package/packages/client/dist/commands/activate.js +6 -7
- package/packages/client/dist/commands/invoke.js +82 -82
- package/packages/client/dist/config/secure-config.d.ts +4 -0
- package/packages/client/dist/config/secure-config.js +6 -6
- package/packages/client/dist/migrations/project-identity.d.ts +3 -0
- package/packages/client/dist/migrations/project-identity.js +7 -7
- package/packages/client/dist/private-execution/isolated-admission.js +11 -11
- package/packages/client/dist/private-execution/isolated-workspace.js +1 -1
- package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -5
- package/packages/client/dist/private-execution/planning-memory-checkpoint.js +3 -3
- package/packages/client/dist/runner/headless/run-yoloop.d.ts +2 -0
- package/packages/client/dist/runner/headless/run-yoloop.js +4 -4
- package/packages/shared/dist/invocation/semantic-gate-remediation.d.ts +45 -0
- package/packages/shared/dist/invocation/semantic-gate-remediation.js +51 -0
- package/targets-stubs/antigravity/gemini.md +1 -1
- package/targets-stubs/antigravity/neocortex.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-sentinel.md +1 -1
- 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/codex/neocortex.toml +1 -1
- package/targets-stubs/cursor/agent.md +2 -2
- package/targets-stubs/deepseek-harness/SKILL.md +1 -1
- package/targets-stubs/gemini-cli/agent.md +2 -2
- package/targets-stubs/gemini-cli/agents/neocortex.md +2 -2
- package/targets-stubs/grok/SKILL.md +1 -1
- package/targets-stubs/kimi/neocortex.md +1 -1
- package/targets-stubs/lib/managed-config-merge.js +12 -4
- package/targets-stubs/openclaw/SKILL.md +1 -1
- package/targets-stubs/opencode/neocortex-root.md +2 -2
- package/targets-stubs/opencode/neocortex.md +2 -2
- package/targets-stubs/vscode/neocortex.agent.md +2 -2
|
@@ -23,6 +23,10 @@ export interface SecureConfig {
|
|
|
23
23
|
/** Key type: 'license' (NX-...) or 'api_key' (nxk_...). undefined = legacy (treat as license). Story 29.04 */
|
|
24
24
|
readonly keyType?: KeyType;
|
|
25
25
|
}
|
|
26
|
+
export declare class SecureConfigError extends Error {
|
|
27
|
+
readonly code: 'AUTH_PROFILE_CONFIG_INVALID' | 'AUTH_PROFILE_CONFIG_CHANGED';
|
|
28
|
+
constructor(code: 'AUTH_PROFILE_CONFIG_INVALID' | 'AUTH_PROFILE_CONFIG_CHANGED');
|
|
29
|
+
}
|
|
26
30
|
/**
|
|
27
31
|
* Encrypt a license key using the machine fingerprint as passphrase.
|
|
28
32
|
* Returns the encrypted envelope string.
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import{existsSync as
|
|
1
|
+
import{existsSync as F,readFileSync as u,writeFileSync as N,mkdirSync as x,chmodSync as m,closeSync as h,constants as d,fstatSync as g,fsyncSync as A,lstatSync as K,openSync as I,renameSync as T,unlinkSync as k}from"node:fs";import{execFileSync as E}from"node:child_process";import{randomUUID as D}from"node:crypto";import{join as v,win32 as f}from"node:path";import{encrypt as G,decrypt as $}from"../cache/crypto-utils.js";import{getMachineFingerprint as p}from"../machine/fingerprint.js";import{DEFAULT_SERVER_URL as H}from"../constants.js";import{neocortexProfileDirectory as V}from"./profile-directory.js";const a=V(),s=v(a,"config.json"),j=["api","neocortex","ornexus","com"].join("."),w=1;class l extends Error{code;constructor(t){super(t),this.code=t}}function L(r){let t;try{t=JSON.parse(r.replace(/^\uFEFF/,""))}catch{throw new l("AUTH_PROFILE_CONFIG_INVALID")}if(!t||typeof t!="object"||Array.isArray(t))throw new l("AUTH_PROFILE_CONFIG_INVALID");return t}function O(r,t={}){const e=p(t);return G(r,e)}function W(r,t={}){try{const e=p(t);return $(r,e).plaintext}catch{return null}}let y;function S(r,t){const e=f.join(process.env.SystemRoot??"C:\\Windows","System32");if(!y){const o=E(f.join(e,"whoami.exe"),["/user","/fo","csv","/nh"],{encoding:"utf8",timeout:5e3,windowsHide:!0});y=/,\s*"(S-1-(?:\d+-)+\d+)"\s*$/i.exec(o.trim())?.[1]}y&&E(f.join(e,"icacls.exe"),[r,"/inheritance:r","/grant:r",`*${y}:${t}`],{stdio:"pipe",timeout:5e3,windowsHide:!0})}function P(r){try{process.platform==="win32"?S(r,"(F)"):m(r,384)}catch{}}function Y(r){try{process.platform==="win32"?S(r,"(OI)(CI)(F)"):m(r,448)}catch{}}let U=!1;function b(r){if(U)return;const t=r.serverUrl;if(!t)return;/^https?:\/\/(localhost|127\.0\.0\.1|0\.0\.0\.0)(:\d+)?/i.test(t)&&(U=!0,console.warn(`
|
|
2
2
|
[!] Warning: connected to local server (`+t+`).
|
|
3
3
|
To use production, run: neocortex activate YOUR-LICENSE-KEY
|
|
4
4
|
Get yours at https://neocortex.sh/portal/login
|
|
5
|
-
`))}function
|
|
6
|
-
[!] Machine fingerprint changed (was: ${e.machineId.slice(0,12)}..., now: ${
|
|
5
|
+
`))}function X(r){const t=r.match(/^(https?:\/\/)([^/]+)(.*)$/i);if(!t)return null;const[,e,o,n=""]=t;return o.toLowerCase()!==j?null:`${e}api.neocortex.sh${n}`}function re(r={}){try{if(!F(s))return null;const t=u(s,"utf-8"),e=L(t);if(e.licenseKey&&!e.encryptedLicenseKey){const i=O(e.licenseKey,r),c={...e},C=c.licenseKey;return delete c.licenseKey,c.encryptedLicenseKey=i,c.configVersion||(c.configVersion=w),r.strictReadOnly||R(c,t),{serverUrl:e.serverUrl,mode:e.mode,machineId:e.machineId,activatedAt:e.activatedAt,tier:e.tier,licenseKey:C,keyType:e.keyType}}let o;if(e.encryptedLicenseKey){const i=W(e.encryptedLicenseKey,r);i&&(o=i)}const n={serverUrl:e.serverUrl,mode:e.mode,machineId:e.machineId,activatedAt:e.activatedAt,tier:e.tier,licenseKey:o,keyType:e.keyType};if(e.machineId&&!o&&e.encryptedLicenseKey){const i=p(r);e.machineId!==i&&console.warn(`
|
|
6
|
+
[!] Machine fingerprint changed (was: ${e.machineId.slice(0,12)}..., now: ${i.slice(0,12)}...).
|
|
7
7
|
Your encrypted credentials are no longer valid.
|
|
8
8
|
Re-activate with: neocortex activate YOUR-LICENSE-KEY
|
|
9
|
-
`)}if(
|
|
9
|
+
`)}if(b(n),n.serverUrl&&!process.env.NEOCORTEX_SERVER_URL&&/^https?:\/\/(localhost|127\.0\.0\.1|0\.0\.0\.0)(:\d+)?/i.test(n.serverUrl)){const c=H;return console.warn(`[neocortex] Auto-repairing serverUrl: ${n.serverUrl} -> ${c}
|
|
10
10
|
[neocortex] To keep localhost, set NEOCORTEX_SERVER_URL=${n.serverUrl}
|
|
11
|
-
`),{...n,serverUrl:
|
|
12
|
-
`,"
|
|
11
|
+
`),{...n,serverUrl:c}}if(n.serverUrl&&!process.env.NEOCORTEX_SERVER_URL){const i=X(n.serverUrl);if(i)return{...n,serverUrl:i}}return n}catch{return null}}function _(){try{const r=K(s);if(!r.isFile()||r.isSymbolicLink())throw new l("AUTH_PROFILE_CONFIG_INVALID");const t=I(s,d.O_RDWR|d.O_NOFOLLOW|d.O_NONBLOCK);try{const e=g(t);if(!e.isFile()||e.dev!==r.dev||e.ino!==r.ino)throw new l("AUTH_PROFILE_CONFIG_CHANGED");return u(t,"utf8")}finally{h(t)}}catch(r){if(r.code==="ENOENT")return null;throw r}}function R(r,t){x(a,{recursive:!0,mode:448})!==void 0&&Y(a);const e=v(a,`.config.json.${D()}.tmp`),o=I(e,"wx",384);let n=!1;try{try{P(e),N(o,JSON.stringify(r,null,2)+`
|
|
12
|
+
`,"utf8"),A(o)}finally{h(o)}if(_()!==t)throw new l("AUTH_PROFILE_CONFIG_CHANGED");T(e,s),n=!0}finally{if(!n)try{k(e)}catch{}}}function te(r){const t=_(),e=t===null?{}:L(t),o=O(r.licenseKey),n=r.keyType??(r.licenseKey.startsWith("nxk_")?"api_key":"license"),i={...e,configVersion:w,serverUrl:r.serverUrl,mode:r.mode,machineId:r.machineId,activatedAt:r.activatedAt,tier:r.tier,encryptedLicenseKey:o,keyType:n};delete i.licenseKey,delete i.apiKey,R(i,t)}export{l as SecureConfigError,W as decryptLicenseKey,O as encryptLicenseKey,re as loadSecureConfig,te as saveSecureConfig,Y as setSecureDirPermissions,P as setSecureFilePermissions};
|
|
@@ -34,6 +34,9 @@ export declare function rollbackPreparedProjectIdentityMigration(projectRoot: st
|
|
|
34
34
|
* locally prepared project ID before its remote floor has been acknowledged.
|
|
35
35
|
*/
|
|
36
36
|
export declare function readProjectIdentityMigrationPhase(projectRoot: string): ProjectIdentityMigrationPhase | null;
|
|
37
|
+
/** Classify only the finalized migration's own untracked local recovery files. */
|
|
38
|
+
export declare function verifiedUntrackedProjectIdentityPaths(projectRoot: string, untrackedPaths: readonly string[]): ReadonlySet<string>;
|
|
39
|
+
export declare function withoutVerifiedProjectIdentityStatus(projectRoot: string, entries: readonly string[]): string[];
|
|
37
40
|
export declare function projectIdentityMigrationRelativePaths(projectRoot: string): {
|
|
38
41
|
readonly state: string;
|
|
39
42
|
readonly migration: string;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{createHash as
|
|
2
|
-
`);try{
|
|
3
|
-
`,state:t}}function
|
|
4
|
-
`}function
|
|
5
|
-
`),
|
|
6
|
-
`),c})}function
|
|
7
|
-
`),c})}function
|
|
1
|
+
import{createHash as ct,randomUUID as Y}from"node:crypto";import{closeSync as at,constants as b,existsSync as T,fstatSync as q,linkSync as st,lstatSync as _,mkdirSync as It,openSync as Tt,readFileSync as p,realpathSync as pt,statSync as ft,unlinkSync as N}from"node:fs";import{dirname as E,join as a,relative as W,resolve as dt}from"node:path";import{assertProjectIdentityMigrationReceiptV1 as k,PROJECT_ID_PATTERN as Q}from"../../../shared/dist/invocation/index.js";import{atomicReplaceUtf8 as l,durableCreateUtf8 as G,fsyncDirectoryBestEffort as O,recoverAtomicReplaceUtf8 as X}from"../fs/atomic-state-replace.js";const St=1,d=a(".neocortex","state.json"),u=a(".neocortex","project-identity-migration.json"),_t=a(".neocortex","project-identity-migration.lock"),Z=/^\.neocortex[\\/]state\.json\.project-identity-backup-(?:\d{8}T\d{9}Z-)?mig_[a-f0-9]{32}$/,x=".neocortex/project-identity-migration.json";class i extends Error{code;constructor(e,t=e){super(t),this.code=e,this.name="ProjectIdentityMigrationError"}}const f=n=>ct("sha256").update(n).digest("hex");function ut(){return`prj_${Y().replaceAll("-","")}`}function tt(){return`mig_${Y().replaceAll("-","")}`}function et(n){return n.toISOString().replace(/[-:.]/g,"")}function R(n){const e=dt(n);let t;try{t=pt(e)}catch{throw new i("PROJECT_IDENTITY_ROOT_INVALID")}if(!ft(t).isDirectory())throw new i("PROJECT_IDENTITY_ROOT_INVALID");const r=a(t,".neocortex");if(T(r)&&_(r).isSymbolicLink())throw new i("PROJECT_IDENTITY_SYMLINK_REJECTED");const o=a(t,d);if(T(o)){const s=_(o);if(s.isSymbolicLink()||!s.isFile())throw new i("PROJECT_IDENTITY_SYMLINK_REJECTED")}const c=a(t,u);if(T(c)){const s=_(c);if(s.isSymbolicLink()||!s.isFile())throw new i("PROJECT_IDENTITY_SYMLINK_REJECTED")}return t}function C(n,e){const t=a(n,_t);It(E(t),{recursive:!0,mode:448});const r=()=>{const o=`${t}.${process.pid}.${Y()}.owner`;G(o,`${process.pid}
|
|
2
|
+
`);try{st(o,t),O(E(t))}finally{try{N(o)}catch{}O(E(t))}};try{r()}catch(o){if(o.code!=="EEXIST")throw new i("PROJECT_IDENTITY_MIGRATION_LOCKED");const c=_(t);if(c.isSymbolicLink()||!c.isFile())throw new i("PROJECT_IDENTITY_SYMLINK_REJECTED");const s=p(t,"utf8");if(!/^[1-9][0-9]*\n$/.test(s)||s.length>24)throw new i("PROJECT_IDENTITY_MIGRATION_LOCK_CORRUPT");const I=Number(s.trim());let g=!0;try{process.kill(I,0)}catch(y){g=y.code!=="ESRCH"}if(g)throw new i("PROJECT_IDENTITY_MIGRATION_LOCKED");try{N(t),O(E(t)),r()}catch{throw new i("PROJECT_IDENTITY_MIGRATION_LOCKED")}}try{return e()}finally{try{N(t),O(E(t))}catch{}}}function h(n){let e;try{e=JSON.parse(n)}catch{throw new i("PROJECT_IDENTITY_STATE_CORRUPT")}if(!e||typeof e!="object"||Array.isArray(e))throw new i("PROJECT_IDENTITY_STATE_CORRUPT");return e}function A(n){const e=a(n,u);try{X(e),X(a(n,d))}catch{throw new i("PROJECT_IDENTITY_ATOMIC_RECOVERY_FAILED")}if(!T(e))return null;let t;try{t=p(e,"utf8")}catch{throw new i("PROJECT_IDENTITY_MIGRATION_STATE_CORRUPT")}return rt(t)}function rt(n){let e;try{e=JSON.parse(n)}catch{throw new i("PROJECT_IDENTITY_MIGRATION_STATE_CORRUPT")}if(!e||typeof e!="object"||Array.isArray(e))throw new i("PROJECT_IDENTITY_MIGRATION_STATE_CORRUPT");const t=e;if(t.schemaVersion!==1||typeof t.operationId!="string"||!/^mig_[a-f0-9]{32}$/.test(t.operationId)||typeof t.projectId!="string"||!Q.test(t.projectId)||!["prepared","remote-acknowledged","finalized"].includes(String(t.phase))||!Number.isSafeInteger(t.legacyEpicFloor)||(t.legacyEpicFloor??-1)<0||typeof t.originalStateExists!="boolean"||typeof t.originalStateDigest!="string"||!/^[a-f0-9]{64}$/.test(t.originalStateDigest)||typeof t.preparedStateDigest!="string"||!/^[a-f0-9]{64}$/.test(t.preparedStateDigest)||t.backupPath!==null&&(typeof t.backupPath!="string"||!Z.test(t.backupPath))||typeof t.createdAt!="string"||typeof t.updatedAt!="string")throw new i("PROJECT_IDENTITY_MIGRATION_STATE_CORRUPT");t.receipt!==void 0&&k(t.receipt);const r=t.phase==="remote-acknowledged"||t.phase==="finalized";if(t.phase==="prepared"&&t.receipt!==void 0||r&&t.receipt===void 0||t.receipt!==void 0&&(t.receipt.operationId!==t.operationId||t.receipt.projectId!==t.projectId||t.receipt.acceptedLegacyFloor<t.legacyEpicFloor))throw new i("PROJECT_IDENTITY_MIGRATION_STATE_CORRUPT");return t}function Et(n){const e=[];n.epics&&typeof n.epics=="object"&&!Array.isArray(n.epics)&&e.push(...Object.keys(n.epics));const t=n.epic_id_ledger;if(t&&typeof t=="object"&&!Array.isArray(t)){const r=t.reserved_ids;Array.isArray(r)&&e.push(...r.filter(o=>typeof o=="string"))}return e.reduce((r,o)=>{const c=o.match(/^P?(\d+)$/i);if(!c)return r;const s=Number(c[1]);return Number.isSafeInteger(s)?Math.max(r,s):r},0)}function S(n){return{version:1,operationId:n.operationId,projectId:n.projectId,localStateDigest:n.preparedStateDigest,legacyEpicFloor:n.legacyEpicFloor,phase:"seed"}}function L(n,e){const t=h(n),r=F(t),o=t[r]??{};return t[r]={...o,project_id:e},t.schema_version===void 0&&(t.schema_version=1),(!t.stories||typeof t.stories!="object"||Array.isArray(t.stories))&&(t.stories={}),(!t.epics||typeof t.epics!="object"||Array.isArray(t.epics))&&(t.epics={}),{raw:`${JSON.stringify(t,null,2)}
|
|
3
|
+
`,state:t}}function F(n){return n.config&&typeof n.config=="object"&&!Array.isArray(n.config)?"config":n.project&&typeof n.project=="object"&&!Array.isArray(n.project)?"project":"config"}function m(n){const e=n[F(n)];return e&&typeof e=="object"&&!Array.isArray(e)?e.project_id:void 0}function nt(n,e){if(!T(n))throw new i("PROJECT_IDENTITY_MIGRATION_STATE_DRIFT");const t=h(p(n,"utf8"));if(m(t)!==e.projectId)throw new i("PROJECT_IDENTITY_MIGRATION_STATE_DRIFT")}function lt(n,e,t,r){const o=h(t),c=m(o);if(c===r.projectId)return;if(c!==void 0)throw new i("PROJECT_IDENTITY_MIGRATION_STATE_DRIFT");const I=a(n,".neocortex",`state.json.project-identity-reconcile-backup-${et(new Date)}-${tt()}`);G(I,t),l(e,L(t,r.projectId).raw)}function ot(){return`${JSON.stringify({schema_version:1,config:{project_name:"neocortex-project",default_branch:"main",language:"pt-BR"},stories:{},epics:{}},null,2)}
|
|
4
|
+
`}function Rt(n,e){if(!e.originalStateExists)return;if(!e.backupPath)throw new i("PROJECT_IDENTITY_MIGRATION_BACKUP_MISSING");const t=a(n,e.backupPath);if(!T(t))throw new i("PROJECT_IDENTITY_MIGRATION_BACKUP_MISSING");const r=_(t);if(r.isSymbolicLink()||!r.isFile())throw new i("PROJECT_IDENTITY_SYMLINK_REJECTED");if(f(p(t))!==e.originalStateDigest)throw new i("PROJECT_IDENTITY_MIGRATION_BACKUP_CORRUPT")}function Dt(n){const e=R(n);return C(e,()=>{const t=A(e);if(t){const w=a(e,d);Rt(e,t);const D=T(w),P=D?p(w,"utf8"):null,V=P===null?null:f(P);if(V===t.preparedStateDigest)return{changed:!1,document:t,request:S(t)};if(t.phase==="finalized"&&P!==null)return m(h(P))===t.projectId?{changed:!1,document:t,request:S(t)}:(lt(e,w,P,t),{changed:!0,document:t,request:S(t)});if(!(t.phase==="prepared"&&(D&&V===t.originalStateDigest||!D&&!t.originalStateExists)))throw new i("PROJECT_IDENTITY_MIGRATION_STATE_DRIFT");const it=D?p(w,"utf8"):ot(),H=L(it,t.projectId).raw;if(f(H)!==t.preparedStateDigest)throw new i("PROJECT_IDENTITY_MIGRATION_STATE_DRIFT");return l(w,H),{changed:!0,document:t,request:S(t)}}const r=a(e,d),o=T(r),c=o?p(r,"utf8"):ot(),s=h(c),I=F(s),y=(s[I]??{}).project_id,K=typeof y=="string"&&Q.test(y)?y:ut(),U=L(c,K),j=U.raw,$=tt(),z=new Date,M=o?a(".neocortex",`state.json.project-identity-backup-${et(z)}-${$}`):null;M&&G(a(e,M),c);const B=z.toISOString(),J={schemaVersion:1,operationId:$,projectId:K,phase:"prepared",legacyEpicFloor:Et(U.state),originalStateExists:o,originalStateDigest:f(c),preparedStateDigest:f(j),backupPath:M,createdAt:B,updatedAt:B};return l(a(e,u),`${JSON.stringify(J,null,2)}
|
|
5
|
+
`),l(r,j),{changed:j!==c,document:J,request:S(J)}})}function Ct(n,e){k(e);const t=R(n);return C(t,()=>{const r=A(t);if(!r)throw new i("PROJECT_IDENTITY_MIGRATION_NOT_PREPARED");if(r.operationId!==e.operationId||r.projectId!==e.projectId)throw new i("PROJECT_IDENTITY_MIGRATION_RECEIPT_CONFLICT");const o=a(t,d);if(r.phase==="finalized"){if(!r.receipt||r.receipt.receiptDigest!==e.receiptDigest)throw new i("PROJECT_IDENTITY_MIGRATION_ACK_REQUIRED");return nt(o,r),r}if(!T(o)||f(p(o))!==r.preparedStateDigest)throw new i("PROJECT_IDENTITY_MIGRATION_STATE_DRIFT");if(r.phase==="prepared"||!r.receipt||r.receipt.receiptDigest!==e.receiptDigest)throw new i("PROJECT_IDENTITY_MIGRATION_ACK_REQUIRED");const c={...r,phase:"finalized",updatedAt:new Date().toISOString(),receipt:e};return l(a(t,u),`${JSON.stringify(c,null,2)}
|
|
6
|
+
`),c})}function mt(n,e){k(e);const t=R(n);return C(t,()=>{const r=A(t);if(!r)throw new i("PROJECT_IDENTITY_MIGRATION_NOT_PREPARED");if(r.operationId!==e.operationId||r.projectId!==e.projectId)throw new i("PROJECT_IDENTITY_MIGRATION_RECEIPT_CONFLICT");if(r.receipt&&r.receipt.receiptDigest!==e.receiptDigest)throw new i("PROJECT_IDENTITY_MIGRATION_RECEIPT_CONFLICT");const o=a(t,d);if(r.phase==="finalized")return nt(o,r),r;if(!T(o)||f(p(o))!==r.preparedStateDigest)throw new i("PROJECT_IDENTITY_MIGRATION_STATE_DRIFT");if(r.phase==="remote-acknowledged")return r;const c={...r,phase:"remote-acknowledged",updatedAt:new Date().toISOString(),receipt:e};return l(a(t,u),`${JSON.stringify(c,null,2)}
|
|
7
|
+
`),c})}function jt(n){const e=R(n);C(e,()=>{const t=A(e);if(!t)return;if(t.phase!=="prepared"||t.receipt)throw new i("PROJECT_IDENTITY_MIGRATION_ROLLBACK_AFTER_ACK_DENIED");const r=a(e,d);if(!T(r)||f(p(r))!==t.preparedStateDigest)throw new i("PROJECT_IDENTITY_MIGRATION_STATE_DRIFT");if(t.originalStateExists){if(!t.backupPath)throw new i("PROJECT_IDENTITY_MIGRATION_BACKUP_MISSING");const c=a(e,t.backupPath);if(!T(c))throw new i("PROJECT_IDENTITY_MIGRATION_BACKUP_MISSING");const s=_(c);if(s.isSymbolicLink()||!s.isFile())throw new i("PROJECT_IDENTITY_SYMLINK_REJECTED");const I=p(c,"utf8");if(f(I)!==t.originalStateDigest)throw new i("PROJECT_IDENTITY_MIGRATION_BACKUP_CORRUPT");l(r,I)}else N(r),O(E(r));const o=a(e,u);N(o),O(E(o))})}function Mt(n){const e=R(n);return A(e)?.phase??null}function v(n,e,t){const r=Tt(n,b.O_RDONLY|b.O_NOFOLLOW|b.O_NONBLOCK);try{const o=q(r),c=_(n);if(!c.isFile()||!o.isFile()||c.dev!==o.dev||c.ino!==o.ino||o.size<1||o.size>e||t&&process.platform!=="win32"&&(o.uid!==process.getuid?.()||(o.mode&63)!==0))throw new Error("project-identity-evidence-unverified");const s=p(r),I=q(r);if(s.length!==o.size||I.size!==o.size||I.mtimeMs!==o.mtimeMs||I.ctimeMs!==o.ctimeMs)throw new Error("project-identity-evidence-unverified");return s}finally{at(r)}}function Ot(n,e){const t=new Set;if(!e.some(r=>r===x||Z.test(r)))return t;try{const r=R(n),o=_(a(r,".neocortex"));if(!o.isDirectory()||o.isSymbolicLink()||process.platform!=="win32"&&(o.uid!==process.getuid?.()||(o.mode&18)!==0))return t;const c=rt(v(a(r,u),128*1024,!0).toString("utf8"));if(c.phase!=="finalized"||c.originalStateExists!==(c.backupPath!==null))return t;const s=h(v(a(r,d),8*1024*1024,!1).toString("utf8"));if(m(s)!==c.projectId)return t;if(c.backupPath!==null){const I=c.backupPath.replaceAll("\\","/");if(!I.endsWith(`-${c.operationId}`))return t;const g=v(a(r,I),8*1024*1024,!0);if(f(g)!==c.originalStateDigest)return t;e.includes(I)&&t.add(I)}e.includes(x)&&t.add(x)}catch{return new Set}return t}function Jt(n,e){const t=Ot(n,e.filter(r=>r.startsWith("?? ")).map(r=>r.slice(3)));return e.filter(r=>!r.startsWith("?? ")||!t.has(r.slice(3)))}function Yt(n){const e=R(n);return{state:W(e,a(e,d)),migration:W(e,a(e,u))}}export{i as ProjectIdentityMigrationError,mt as acknowledgeProjectIdentityMigration,Ct as finalizeProjectIdentityMigration,Dt as prepareProjectIdentityMigration,Yt as projectIdentityMigrationRelativePaths,Mt as readProjectIdentityMigrationPhase,jt as rollbackPreparedProjectIdentityMigration,Ot as verifiedUntrackedProjectIdentityPaths,Jt as withoutVerifiedProjectIdentityStatus};
|
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
import{execFileSync as Ft,spawnSync as vt}from"node:child_process";import{createHash as F}from"node:crypto";import{existsSync as nt,lstatSync as R,readFileSync as m,realpathSync as ht,writeFileSync as mt}from"node:fs";import{isAbsolute as ot,join as a,relative as dt,sep as wt}from"node:path";import{isDeepStrictEqual as S}from"node:util";import{readPrivateYoloFrozenWriteSet as Bt,verifyPrivateYoloCandidateWriteSet as Ct,verifyPrivateYoloCleanBaseline as zt}from"./clean-baseline.js";import{isPrivateIsolatedWorkspacePlatform as _t,PRIVATE_EPIC_PENDING_SIDECAR as et,privateIsolatedWorkspaceModeVerified as bt,privatePendingEpicSidecarVerified as Lt}from"./isolated-workspace.js";import{loadPactPrivateAnswers as Ht}from"../commands/architecture-answers.js";import{derivePactWriteSet as xt}from"./pact-write-set.js";import{deriveUxCandidateWriteSet as Jt,deriveUxWriteSet as Mt}from"./ux-write-set.js";import{validateUxCandidateSource as qt}from"./ux-source-validation.js";import{validatePactTestSource as Gt}from"./pact-test-source.js";import{classifyProjectMemoryUpdate as Wt}from"../memory/project-memory-writer.js";import{privateRootMemoryEffect as yt,privateRootMemorySourceMatches as
|
|
2
|
-
`)])));if(
|
|
1
|
+
import{execFileSync as Ft,spawnSync as vt}from"node:child_process";import{createHash as F}from"node:crypto";import{existsSync as nt,lstatSync as R,readFileSync as m,realpathSync as ht,writeFileSync as mt}from"node:fs";import{isAbsolute as ot,join as a,relative as dt,sep as wt}from"node:path";import{isDeepStrictEqual as S}from"node:util";import{readPrivateYoloFrozenWriteSet as Bt,verifyPrivateYoloCandidateWriteSet as Ct,verifyPrivateYoloCleanBaseline as zt}from"./clean-baseline.js";import{isPrivateIsolatedWorkspacePlatform as _t,PRIVATE_EPIC_PENDING_SIDECAR as et,privateIsolatedWorkspaceModeVerified as bt,privatePendingEpicSidecarVerified as Lt}from"./isolated-workspace.js";import{loadPactPrivateAnswers as Ht}from"../commands/architecture-answers.js";import{derivePactWriteSet as xt}from"./pact-write-set.js";import{deriveUxCandidateWriteSet as Jt,deriveUxWriteSet as Mt}from"./ux-write-set.js";import{validateUxCandidateSource as qt}from"./ux-source-validation.js";import{validatePactTestSource as Gt}from"./pact-test-source.js";import{classifyProjectMemoryUpdate as Wt}from"../memory/project-memory-writer.js";import{withoutVerifiedProjectIdentityStatus as Yt}from"../migrations/project-identity.js";import{privateRootMemoryEffect as yt,privateRootMemorySourceMatches as Ut,privateRootMemorySourceMatchReason as Vt}from"./root-memory-scope.js";import{inspectPactToolchain as Xt,planPactToolchainManifest as Kt}from"./pact-toolchain.js";import{acceptedPlanningDiagnosisPredecessor as Zt,planningPendingSidecarDigest as Rt}from"./planning-diagnosis-checkpoint.js";import{acceptedPlanningResearchPredecessor as Qt}from"./planning-research-checkpoint.js";import{confirmPropertyTestPlan as At,renderPropertyTestConfiguration as kt}from"./property-test-plan.js";import{validatePropertyTestTypeScriptSource as It}from"./property-test-source.js";const Z=16*1024*1024,st=1024,ut="acd455ed0e39d98b90fb57391db75e366e4c5604db043e03a89a20e33d643c3c",te="81f50aaa801c1660eabe46e645501acbfb3e9873410c991e1496c014ca75c369",St="fa2194f89c01f07e225fd6f39e98e679f628e072239b6cd0af3ee527f0722518",ee="8636f22ec5950410902448ee1e9cb4947359ac98df518742bddbbb367468e3ae";function tt(t,r){return typeof t=="string"&&t.length<=128&&F("sha256").update(t).digest("hex")===r}function Et(){const t={...process.env};for(const r of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete t[r];return t}function G(t,r){return Ft("git",[...r],{cwd:t,env:Et(),stdio:["ignore","pipe","pipe"],timeout:3e4,maxBuffer:Z})}function J(t,r){return G(t,r).toString("utf8").trim()}function B(t,r=!1){return G(t,["status","--porcelain=v1","-z","--untracked-files=all",...r?["--ignored=matching"]:[]])}function rt(t){return!!t&&!ot(t)&&!t.includes("\\")&&!t.includes("\0")&&!t.split("/").some(r=>!r||r==="."||r===".."||r===".git")}function P(t,r){const e=r.split("/");let o=t;for(const i of e.slice(0,-1)){o=a(o,i);try{const s=R(o);if(!s.isDirectory()||s.isSymbolicLink())throw new Error("path-boundary")}catch(s){if(s.code==="ENOENT")return;throw s}}try{const i=R(a(t,r));if(!i.isFile()||i.isSymbolicLink()||i.size>Z)throw new Error("path-boundary")}catch(i){if(i.code!=="ENOENT")throw i}}function $t(t){const r=[...t.matchAll(/\/\/\s*arch:keep-start[^\n]*\n[\s\S]*?\/\/\s*arch:keep-end[^\n]*/g)].map(i=>i[0]),e=(t.match(/arch:keep-start/g)??[]).length,o=(t.match(/arch:keep-end/g)??[]).length;if(e!==o||e!==r.length)throw new Error("architecture-keep-marker-invalid");return r}function M(t,r=!1,e=!1,o=[],i){const s=[],n=[],f=t.toString("utf8").split("\0").filter(Boolean),p=i?Yt(i,f):f;for(const c of p){if(c.length<4||c[2]!==" ")throw new Error("status-invalid");const d=c.slice(0,2),h=c.slice(3);if(!rt(h)||d!=="??"&&d!==" M"&&d!==" D"&&!(d===" T"&&o.includes(h))&&!(e&&d==="!!"&&h===et))throw new Error("status-invalid");s.push(h),d==="??"&&n.push(h)}if(!r&&s.length===0||s.length>st||new Set(s).size!==s.length)throw new Error("status-invalid");return{paths:s.sort(),untracked:n.sort()}}function ft(t,r,e,o){const i=G(r,["ls-tree","-z",e,"--",o]).toString("utf8");if(!i)try{return R(a(t,o)),!1}catch(n){return n.code==="ENOENT"}const s=/^([0-7]{6}) blob [a-f0-9]{40,64}\t([^\0]+)\0$/.exec(i);if(!s||s[2]!==o||!["100644","100755"].includes(s[1]))return!1;try{const n=R(a(t,o));return!n.isFile()||n.isSymbolicLink()||n.size>Z||!!(n.mode&73)!=(s[1]==="100755")?!1:m(a(t,o)).equals(G(r,["show",`${e}:${o}`]))}catch{return!1}}function Ae(t,r,e,o){return rt(o)&&/^[a-f0-9]{40,64}$/.test(e)&&ft(t,r,e,o)}function it(t,r){try{const e=a(t,et);return Lt(t)&&F("sha256").update(m(e)).digest("hex")===r}catch{return!1}}function lt(t,r,e,o,i,s){const n=new Set(o),f=s?yt(s).files.map(d=>d.path):[],p=M(B(t),!0,!!i,f,i?t:void 0),c=s?Vt(s,t,r,e):"matched";if(c!=="matched")throw new Error(`root-memory-${c}`);if(!p.paths.every(d=>n.has(d)||f.includes(d)||d===et&&!!i&&it(t,i)))throw new Error("source-unclaimed-delta");if(!o.every(d=>ft(t,r,e,d)))throw new Error("source-frozen-mismatch");return!i||it(t,i)}function re(t,r){const e=vt("git",["diff","--no-index","--binary","--no-ext-diff","--","/dev/null",r],{cwd:t,env:Et(),encoding:"buffer",timeout:3e4,maxBuffer:Z});if(e.error||e.status!==1||!Buffer.isBuffer(e.stdout)||e.stdout.byteLength===0)throw new Error("patch-invalid");return e.stdout}function Ot(t,r,e){const o=vt("git",["apply",...e?["--check"]:[],"--binary","-"],{cwd:t,env:Et(),input:r,encoding:"buffer",timeout:3e4,maxBuffer:Z});if(o.error||o.status!==0)throw new Error("apply-failed")}function pt(t,r,e){const o=a(t,e),i=a(r,e);try{const s=R(o),n=R(i);return s.isFile()&&n.isFile()&&(s.mode&73)===(n.mode&73)&&m(o).equals(m(i))}catch(s){if(s.code!=="ENOENT")return!1;try{return R(o),!1}catch(n){if(n.code!=="ENOENT")return!1}try{return R(i),!1}catch(n){return n.code==="ENOENT"}}}function Se(t,r,e,o){Tt(t,r,e,!0,o)}function $e(t,r,e,o){if(Tt(t,r,e,!1,o),G(t.workspacePath,["diff","--cached","--name-only"]).byteLength!==0)throw new Error("private-execution-isolated-snapshot-unverified")}function Tt(t,r,e,o,i){try{if(!_t()||t.schemaVersion!==1||!ot(t.sourceRoot)||!ot(t.workspacePath)||ht(t.sourceRoot)!==t.sourceRoot||ht(t.workspacePath)!==t.workspacePath||!R(t.workspacePath).isDirectory()||!bt(R(t.workspacePath))||dt(t.sourceRoot,t.workspacePath)===""||dt(t.sourceRoot,t.workspacePath).split(wt)[0]!==".."||!/^[a-f0-9]{40,64}$/.test(t.baseSha)||!/^[a-f0-9]{40,64}$/.test(e)||J(t.sourceRoot,["rev-parse","--show-toplevel"])!==t.sourceRoot||J(t.workspacePath,["rev-parse","--show-toplevel"])!==t.workspacePath||J(t.sourceRoot,["rev-parse","HEAD"])!==t.baseSha||J(t.workspacePath,["rev-parse","HEAD"])!==e||J(t.sourceRoot,["symbolic-ref","--short","HEAD"])!==t.executionBranch||J(t.workspacePath,["symbolic-ref","--short","HEAD"])!==t.executionBranch||nt(a(t.workspacePath,".git","objects","info","alternates"))||o&&B(t.workspacePath,!0).byteLength!==0||r.length===0||r.length>st||r.some(s=>!rt(s))||new Set(r).size!==r.length)throw new Error("boundary-invalid");if(G(t.workspacePath,["merge-base","--is-ancestor",t.baseSha,e]),!lt(t.sourceRoot,t.workspacePath,e,r,void 0,i))throw new Error("boundary-raced")}catch(s){const n=s instanceof Error&&(["boundary-invalid","boundary-raced","status-invalid","source-unclaimed-delta","source-frozen-mismatch"].includes(s.message)||/^root-memory-(scope-binding|snapshot-ancestry|snapshot-content|source-content|source-projection)(-unsafe)?$/.test(s.message))?s.message:"physical-inspection-failed";throw new Error("private-execution-isolated-snapshot-unverified",{cause:new Error(n)})}}function W(t,r,e,o,i,s=[],n){try{if(!_t()||t.schemaVersion!==1||!ot(t.sourceRoot)||!ot(t.workspacePath)||ht(t.sourceRoot)!==t.sourceRoot||ht(t.workspacePath)!==t.workspacePath||!R(t.workspacePath).isDirectory()||!bt(R(t.workspacePath))||dt(t.sourceRoot,t.workspacePath)===""||dt(t.sourceRoot,t.workspacePath).split(wt)[0]!==".."||J(t.sourceRoot,["rev-parse","--show-toplevel"])!==t.sourceRoot||J(t.workspacePath,["rev-parse","--show-toplevel"])!==t.workspacePath||J(t.sourceRoot,["rev-parse","HEAD"])!==t.baseSha||!/^[a-f0-9]{40,64}$/.test(e)||J(t.workspacePath,["rev-parse","HEAD"])!==e||J(t.sourceRoot,["symbolic-ref","--short","HEAD"])!==t.executionBranch||J(t.workspacePath,["symbolic-ref","--short","HEAD"])!==t.executionBranch||r.length===0||r.length>st||r.some(g=>!rt(g))||new Set(r).size!==r.length)throw new Error("authority-invalid");if(G(t.workspacePath,["merge-base","--is-ancestor",t.baseSha,e]),!lt(t.sourceRoot,t.workspacePath,e,r,o,n))throw new Error("source-snapshot-mismatch");const f=B(t.workspacePath,!0),p=M(f),c=new Set(r);if(p.paths.some(g=>!c.has(g)||s.includes(g)))throw new Error("path-unclaimed");if(i&&!i())throw new Error("candidate-raced");for(const g of p.paths)P(t.workspacePath,g),P(t.sourceRoot,g);const h=[G(t.workspacePath,["diff","--binary","--no-ext-diff","--no-textconv","HEAD","--"]),...p.untracked.map(g=>re(t.workspacePath,g))],l=Buffer.concat(h.map(g=>Buffer.concat([g,Buffer.from(`
|
|
2
|
+
`)])));if(l.byteLength===0||l.byteLength>Z||!B(t.workspacePath,!0).equals(f)||i&&!i()||!lt(t.sourceRoot,t.workspacePath,e,r,o,n))throw new Error("patch-raced");if(Ot(t.sourceRoot,l,!0),!B(t.workspacePath,!0).equals(f)||i&&!i()||!lt(t.sourceRoot,t.workspacePath,e,r,o,n))throw new Error("patch-raced");Ot(t.sourceRoot,l,!1);const w=n?yt(n).files.map(g=>g.path):[];if(M(B(t.sourceRoot),!0,!!o,w,o?t.sourceRoot:void 0).paths.some(g=>!c.has(g)&&!w.includes(g)&&g!==et)||n&&!Ut(n,t.sourceRoot)||o&&!it(t.sourceRoot,o)||r.some(g=>!pt(t.workspacePath,t.sourceRoot,g))||J(t.sourceRoot,["rev-parse","HEAD"])!==t.baseSha||J(t.sourceRoot,["symbolic-ref","--short","HEAD"])!==t.executionBranch)throw new Error("admission-raced");return Object.freeze({schemaVersion:1,outcome:"admitted-unverified",baseSha:t.baseSha,executionBranch:t.executionBranch,changedPaths:Object.freeze([...p.paths]),patchSha256:F("sha256").update(l).digest("hex")})}catch{throw new Error("private-execution-isolated-admission-unverified")}}async function Oe(t,r,e,o=t.baseSha,i=!1,s){try{const n=await Bt(t.sourceRoot,r,t.executionBranch,e);if(s){const d=yt(s);if(d.storyId!==r||d.childClaimRevision!==F("sha256").update([...n].sort().join("\0")).digest("hex"))throw new Error("root-memory-claim-mismatch")}const f=a(t.workspacePath,".neocortex","state.json"),p=R(f);if(!p.isFile()||p.isSymbolicLink()||p.size>Z)throw new Error("candidate-state-invalid");Ct(m(f,"utf8"),r,n);const c=W(t,n,o,void 0,void 0,i?[".neocortex/state.json"]:[],s);return await zt(t.sourceRoot,r,t.executionBranch,e),c}catch{throw new Error("private-execution-isolated-admission-unverified")}}const ne=new Set(["id","epic_id","title","description","status","steps_completed","last_step","branch_name","estimated_hours","complexity","priority","type","depends_on","created_at","updated_at","acceptance_criteria"]),oe=new Set(["id","title","description","status","stories","total_stories","completed_stories","estimated_hours","complexity","priority","created_at","updated_at","last_updated","source","tags"]);function jt(t){return["title","description","complexity","priority","type","created_at","updated_at","last_updated","source"].some(e=>t[e]!==void 0&&typeof t[e]!="string")||t.estimated_hours!==void 0&&(typeof t.estimated_hours!="number"||!Number.isFinite(t.estimated_hours)||t.estimated_hours<0)?!1:["depends_on","acceptance_criteria","tags"].every(e=>t[e]===void 0||Array.isArray(t[e])&&t[e].length<=256&&t[e].every(o=>typeof o=="string"))}function se(t){return Object.keys(t).every(r=>ne.has(r))&&t.status==="backlog"&&jt(t)&&(t.steps_completed===void 0||Array.isArray(t.steps_completed)&&t.steps_completed.length===0)&&(t.last_step===void 0||t.last_step===null)&&(t.branch_name===void 0||t.branch_name===null)}function Te(t,r,e,o,i){try{if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(r)||!/^P[1-9][0-9]*$/.test(e)||!/^[a-f0-9]{64}$/.test(o)||!/^[a-f0-9]{64}$/.test(i)||!it(t.sourceRoot,i))throw new Error("claim-invalid");const s=JSON.parse(m(a(t.sourceRoot,et),"utf8")),n=s&&typeof s=="object"&&!Array.isArray(s)?s.operations?.[o]:void 0;if(!n||typeof n!="object"||Array.isArray(n)||n.claimId!==r||n.epicId!==e)throw new Error("claim-sidecar-mismatch");const f=M(B(t.workspacePath,!0)),p=`docs/epics/epic-${e}.md`,c=".neocortex/state.json",d=new RegExp(`^docs/stories/${e}\\.[0-9]{2}\\.story\\.md$`),h=f.paths.filter(E=>d.test(E));if(!f.paths.includes(p)||!f.paths.includes(c)||h.length===0||h.length>99||f.paths.some(E=>E!==p&&E!==c&&E!=="NEOCORTEX.md"&&!d.test(E)))throw new Error("artifact-scope-invalid");const l=h.map(E=>E.slice(13,-9)).sort();if(l.some((E,T)=>E!==`${e}.${String(T+1).padStart(2,"0")}`))throw new Error("story-sequence-invalid");for(const E of[p,...h])try{throw R(a(t.sourceRoot,E)),new Error("artifact-already-exists")}catch(T){if(T.code!=="ENOENT")throw T}const w=(E,T)=>{P(t.workspacePath,E);const K=m(a(t.workspacePath,E),"utf8");return Buffer.byteLength(K)>Z?null:/^---\r?\n([\s\S]{1,8192}?)\r?\n---(?:\r?\n|$)/.exec(K)?.[1]?.split(/\r?\n/).find(ct=>ct.startsWith(`${T}:`))?.slice(T.length+1).trim()?.replace(/^(["'])(.*)\1$/,"$2")??null};if(w(p,"id")!==e||h.some((E,T)=>w(E,"id")!==l[T]||w(E,"epic_id")!==e))throw new Error("artifact-id-invalid");P(t.workspacePath,c);const u=JSON.parse(m(a(t.workspacePath,c),"utf8"));if(!u||typeof u!="object"||Array.isArray(u))throw new Error("state-invalid");const g=u,_=g.epics,j=g.stories,b=_?.[e],N=g.epic_id_ledger;if(g.schema_version!==1||!b||b.id!==e||b.status!=="memory-updated"||Object.keys(b).some(E=>!oe.has(E))||!jt(b)||b.completed_stories!==void 0&&b.completed_stories!==0||b.total_stories!==void 0&&b.total_stories!==l.length||!Array.isArray(b.stories)||b.stories.length!==l.length||b.stories.some((E,T)=>E!==l[T])||!j||l.some(E=>{const T=j[E];return!T||T.id!==E||T.epic_id!==e||!se(T)})||!N||!Array.isArray(N.reserved_ids)||!N.reserved_ids.includes(e))throw new Error("state-claim-mismatch");P(t.sourceRoot,c);const y=JSON.parse(m(a(t.sourceRoot,c),"utf8")),A=y.epics,x=y.stories;if(!A||!x||A[e]!==void 0||l.some(E=>x[E]!==void 0))throw new Error("state-claim-conflict");const{[e]:Y,...L}=_,$={...j};for(const E of l)delete $[E];const{epic_id_ledger:q,last_updated:C,...z}=y,{epic_id_ledger:V,last_updated:X,...Q}=g;if(!S(L,A)||!S($,x)||!S({...Q,epics:void 0,stories:void 0},{...z,epics:void 0,stories:void 0}))throw new Error("state-unrelated-drift");const O=y.epic_id_ledger&&typeof y.epic_id_ledger=="object"?y.epic_id_ledger.reserved_ids:void 0,{reserved_ids:U,...v}=N,D=y.epic_id_ledger&&typeof y.epic_id_ledger=="object"?y.epic_id_ledger:{schema_version:1},{reserved_ids:H,...k}=D;if(O!==void 0&&(!Array.isArray(O)||O.some(E=>typeof E!="string"||!/^P[1-9][0-9]*$/.test(E))||new Set(O).size!==O.length))throw new Error("ledger-drift");const I=[...Array.isArray(O)?O:[]];if(I.includes(e)||I.push(e),!S(N.reserved_ids,I)||!S(v,k))throw new Error("ledger-drift");return W(t,f.paths,t.baseSha,i)}catch{throw new Error("private-execution-epic-claim-admission-unverified")}}function je(t,r,e,o,i,s){try{if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(r)||!/^P[1-9][0-9]{0,11}$/.test(e)||!/^[a-f0-9]{64}$/.test(o)||!/^[a-f0-9]{64}$/.test(i)||typeof s!="string"||!s.trim()||s.length>16384||!it(t.sourceRoot,i))throw new Error("planning-claim-invalid");const n=JSON.parse(m(a(t.sourceRoot,et),"utf8")),f=n&&typeof n=="object"&&!Array.isArray(n)?n.operations?.[o]:void 0;if(!f||typeof f!="object"||Array.isArray(f)||f.claimId!==r||f.epicId!==e)throw new Error("planning-claim-sidecar-mismatch");const p=`.neocortex/planning/epic-${e}`,c=`${p}/idea.json`,d=`${p}/diagnosis.md`,h=`${p}/enriched-prompt.md`,l=".neocortex/planning/planning.json",w=[c,d,h,l],u=M(B(t.workspacePath,!0));if(u.paths.length!==w.length||u.paths.some(E=>!w.includes(E)))throw new Error("planning-artifact-scope-invalid");for(const E of[c,d,h]){P(t.workspacePath,E);try{throw R(a(t.sourceRoot,E)),new Error("planning-artifact-already-exists")}catch(T){if(T.code!=="ENOENT")throw T}}const g=(E,T)=>{const K=R(a(t.workspacePath,E));if(!K.isFile()||K.isSymbolicLink()||K.size<1||K.size>T)throw new Error("planning-artifact-invalid");return m(a(t.workspacePath,E),"utf8")},_=JSON.parse(g(c,32*1024));if(!_||typeof _!="object"||Array.isArray(_)||_.epic_id!==e||_.status!=="diagnosed"||typeof _.raw_input!="string"||_.raw_input!==s)throw new Error("planning-idea-invalid");const j=g(d,256*1024),b=g(h,256*1024),N=(E,T)=>{const K=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(E.replace(/\r\n/g,`
|
|
3
3
|
`))?.[1];if(!K)return!1;const Pt=K.split(`
|
|
4
|
-
`),at=gt=>{const ct=Pt.filter(Dt=>Dt.startsWith(`${gt}:`));return ct.length===1?ct[0].slice(gt.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0};return at("epic_id")===e&&tt(at("step"),T)&&at("status")==="completed"};if(!N(j,ut)||!N(b,
|
|
4
|
+
`),at=gt=>{const ct=Pt.filter(Dt=>Dt.startsWith(`${gt}:`));return ct.length===1?ct[0].slice(gt.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0};return at("epic_id")===e&&tt(at("step"),T)&&at("status")==="completed"};if(!N(j,ut)||!N(b,te))throw new Error("planning-document-identity-invalid");P(t.workspacePath,l),P(t.sourceRoot,l);const y=JSON.parse(g(l,128*1024)),A=nt(a(t.sourceRoot,l))?JSON.parse(m(a(t.sourceRoot,l),"utf8")):void 0;if(!y||typeof y!="object"||Array.isArray(y)||!("epics"in y)||!y.epics||typeof y.epics!="object"||Array.isArray(y.epics)||A!==void 0&&(!A||typeof A!="object"||Array.isArray(A)||!("epics"in A)||!A.epics||typeof A.epics!="object"||Array.isArray(A.epics)))throw new Error("planning-index-invalid");const x=y,Y=x.epics,L=Y[e],$=L,q=$?.output_files;if(!L||typeof L!="object"||Array.isArray(L)||$?.id!==e||$.status!=="diagnosed"||$.idea!==_.raw_input||!Array.isArray($.steps_completed)||$.steps_completed.length!==1||!tt($.steps_completed[0],ut)||typeof $.created_at!="string"||!Number.isFinite(Date.parse($.created_at))||$.completed_at!==null||!q||typeof q!="object"||Array.isArray(q)||!S(q,{diagnosis:`${p}/diagnosis.md`})||!S(Object.keys($).sort(),["id","idea","status","steps_completed","created_at","completed_at","output_files"].sort()))throw new Error("planning-index-epic-invalid");const{last_scan:C,epics:z,...V}=x,X=A,Q=X?.epics,{last_scan:O,epics:U,...v}=X??{},{[e]:D,...H}=Y;if(Q?.[e]!==void 0||!S(H,Q??{})||X!==void 0&&!S(V,v)||X===void 0&&(Object.keys(Y).length!==1||!S(Object.keys(x).sort(),["version","next_epic_id","last_scan","existing_epics_discovered","epics"].sort())||x.version!=="1.0.0"||x.next_epic_id!==1||!S(x.existing_epics_discovered,[]))||typeof x.last_scan!="string"||!Number.isFinite(Date.parse(x.last_scan)))throw new Error("planning-index-drift");const k=w.map(E=>F("sha256").update(m(a(t.workspacePath,E))).digest("hex")),I=()=>w.every((E,T)=>{try{return P(t.workspacePath,E),F("sha256").update(m(a(t.workspacePath,E))).digest("hex")===k[T]}catch{return!1}});return W(t,w,t.baseSha,i,I)}catch{throw new Error("private-execution-planning-diagnosis-admission-unverified")}}function Ne(t,r,e,o,i,s){try{if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(r)||!/^P[1-9][0-9]{0,11}$/.test(e)||!/^[a-f0-9]{64}$/.test(o)||!/^[a-f0-9]{64}$/.test(i)||!/^[a-f0-9]{64}$/.test(s))throw new Error("planning-research-binding-invalid");const n=".neocortex/state.json",f=".neocortex/planning/planning.json",p=`.neocortex/planning/epic-${e}`,c=`${p}/research.md`;if(P(t.sourceRoot,n),P(t.workspacePath,n),P(t.sourceRoot,f),P(t.workspacePath,f),P(t.sourceRoot,c),P(t.workspacePath,c),R(a(t.sourceRoot,n)).size>8*1024*1024||R(a(t.workspacePath,n)).size>8*1024*1024||R(a(t.sourceRoot,f)).size>128*1024||R(a(t.workspacePath,f)).size>128*1024)throw new Error("planning-research-source-size-invalid");const d=m(a(t.sourceRoot,n));if(F("sha256").update(d).digest("hex")!==s||!d.equals(m(a(t.workspacePath,n))))throw new Error("planning-research-state-drift");const h=JSON.parse(d.toString("utf8")),l=Zt(h,r,e);if(l.diagnosisReceiptId!==o||l.intakeRevision!==i)throw new Error("planning-research-predecessor-mismatch");const u=h.epics[e].createEpicPlanningPhysical.artifactDigests;for(const[O,U]of Object.entries({idea:`${p}/idea.json`,diagnosis:`${p}/diagnosis.md`,enrichment:`${p}/enriched-prompt.md`,index:f}))if(P(t.sourceRoot,U),F("sha256").update(m(a(t.sourceRoot,U))).digest("hex")!==u[O])throw new Error("planning-research-source-artifact-drift");try{throw R(a(t.sourceRoot,c)),new Error("planning-research-already-exists")}catch(O){if(O.code!=="ENOENT")throw O}const g=[c,f],_=M(B(t.workspacePath,!0));if(_.paths.length!==g.length||_.paths.some(O=>!g.includes(O)))throw new Error("planning-research-write-scope-invalid");const j=R(a(t.workspacePath,c));if(!j.isFile()||j.isSymbolicLink()||j.size<64||j.size>256*1024)throw new Error("planning-research-document-invalid");const b=m(a(t.workspacePath,c),"utf8"),N=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(b.replace(/\r\n/g,`
|
|
5
5
|
`))?.[1],y=O=>{const U=N?.split(`
|
|
6
|
-
`).filter(v=>v.startsWith(`${O}:`))??[];return U.length===1?U[0].slice(O.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0};if(!N||y("epic_id")!==e||y("status")!=="completed"||!tt(y("step"),St)||!b.slice(N.length+8).trim())throw new Error("planning-research-document-identity-invalid");const A=JSON.parse(m(a(t.sourceRoot,
|
|
6
|
+
`).filter(v=>v.startsWith(`${O}:`))??[];return U.length===1?U[0].slice(O.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0};if(!N||y("epic_id")!==e||y("status")!=="completed"||!tt(y("step"),St)||!b.slice(N.length+8).trim())throw new Error("planning-research-document-identity-invalid");const A=JSON.parse(m(a(t.sourceRoot,f),"utf8")),x=JSON.parse(m(a(t.workspacePath,f),"utf8"));if(!A||typeof A!="object"||Array.isArray(A)||!x||typeof x!="object"||Array.isArray(x))throw new Error("planning-research-index-invalid");const Y=A,L=x,$=Y.epics,q=L.epics,C=$?.[e];if(!$||Array.isArray($)||!q||Array.isArray(q)||!C||Array.isArray(C)||C.id!==e||C.idea!==l.rawIntent||C.status!=="diagnosed"||!Array.isArray(C.steps_completed)||C.steps_completed.length!==1||!tt(C.steps_completed[0],ut)||!S(C.output_files,{diagnosis:`${p}/diagnosis.md`})||typeof L.last_scan!="string"||!Number.isFinite(Date.parse(L.last_scan)))throw new Error("planning-research-index-predecessor-invalid");const z={...C,status:"researched",steps_completed:[...C.steps_completed,y("step")],output_files:{diagnosis:`${p}/diagnosis.md`,research:c}},V={...Y,last_scan:L.last_scan,epics:{...$,[e]:z}};if(!S(L,V))throw new Error("planning-research-index-drift");const X=g.map(O=>F("sha256").update(m(a(t.workspacePath,O))).digest("hex")),Q=()=>g.every((O,U)=>{try{return P(t.workspacePath,O),F("sha256").update(m(a(t.workspacePath,O))).digest("hex")===X[U]}catch{return!1}});return W(t,g,t.baseSha,Rt(t.sourceRoot),Q)}catch{throw new Error("private-execution-planning-research-admission-unverified")}}function De(t,r,e,o,i,s,n){try{if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(r)||!/^P[1-9][0-9]{0,11}$/.test(e)||[o,i,s,n].some(v=>!/^[a-f0-9]{64}$/.test(v)))throw new Error("planning-generation-binding-invalid");const f=".neocortex/state.json",p=".neocortex/planning/planning.json",c=`.neocortex/planning/epic-${e}`,d=`docs/epics/epic-${e}.md`;for(const v of[f,p,`${c}/idea.json`,`${c}/diagnosis.md`,`${c}/enriched-prompt.md`,`${c}/research.md`]){P(t.sourceRoot,v),P(t.workspacePath,v);const D=m(a(t.sourceRoot,v));if(v!==p&&!D.equals(m(a(t.workspacePath,v)))||!D.equals(G(t.sourceRoot,["show",`HEAD:${v}`])))throw new Error("planning-generation-predecessor-uncommitted")}const h=m(a(t.sourceRoot,f));if(h.byteLength>8*1024*1024||F("sha256").update(h).digest("hex")!==n)throw new Error("planning-generation-state-drift");const l=JSON.parse(h.toString("utf8")),w=Qt(l,r,e);if(w.diagnosisReceiptId!==o||w.researchReceiptId!==i||w.intakeRevision!==s)throw new Error("planning-generation-predecessor-mismatch");const u=l.epics[e],g=u.createEpicPlanningPhysical.artifactDigests,_=u.createEpicPlanningResearchPhysical.artifactDigests,j={idea:`${c}/idea.json`,diagnosis:`${c}/diagnosis.md`,enrichment:`${c}/enriched-prompt.md`,research:`${c}/research.md`};for(const[v,D]of Object.entries(j)){const H=v==="research"?_.research:g[v];if(F("sha256").update(m(a(t.sourceRoot,D))).digest("hex")!==H)throw new Error("planning-generation-artifact-drift")}if(F("sha256").update(m(a(t.sourceRoot,p))).digest("hex")!==_.index)throw new Error("planning-generation-index-drift");const b=M(B(t.workspacePath,!0)),N=new RegExp(`^docs/stories/${e}\\.([0-9]{2})\\.story\\.md$`),y=b.paths.filter(v=>N.test(v)).sort((v,D)=>Number(N.exec(v)[1])-Number(N.exec(D)[1]));if(y.length<1||y.length>24||y.some((v,D)=>N.exec(v)[1]!==String(D+1).padStart(2,"0"))||b.paths.length!==y.length+2||b.paths.some(v=>v!==d&&v!==p&&!N.test(v)))throw new Error("planning-generation-write-scope-invalid");const A=[d,p,...y];for(const v of[d,...y]){P(t.sourceRoot,v),P(t.workspacePath,v);try{throw R(a(t.sourceRoot,v)),new Error("planning-generation-path-collision")}catch(H){if(H.code!=="ENOENT")throw H}const D=R(a(t.workspacePath,v));if(!D.isFile()||D.isSymbolicLink()||D.size<128||D.size>(v===d?512:128)*1024)throw new Error("planning-generation-document-invalid")}const x=(v,D)=>{const k=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(v.replace(/\r\n/g,`
|
|
7
7
|
`))?.[1]?.split(`
|
|
8
|
-
`).filter(I=>I.startsWith(`${D}:`))??[];return k.length===1?k[0].slice(D.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0},Y=m(a(t.workspacePath,
|
|
9
|
-
`))?.[1]??"";if(x(H,"id")!==`${e}.${String(v+1).padStart(2,"0")}`||x(H,"epic_id")!==e||/^\s*epic\s*:/m.test(k)||x(H,"status")!=="backlog"||!H.includes("## Acceptance Criteria")||!/\bGiven\b[\s\S]*\bWhen\b[\s\S]*\bThen\b/.test(H))throw new Error("planning-generation-story-invalid")}const L=JSON.parse(m(a(t.sourceRoot,
|
|
8
|
+
`).filter(I=>I.startsWith(`${D}:`))??[];return k.length===1?k[0].slice(D.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0},Y=m(a(t.workspacePath,d),"utf8");if(x(Y,"id")!==e||x(Y,"stories_count")!==String(y.length)||!Y.includes("## Stories"))throw new Error("planning-generation-epic-invalid");for(const[v,D]of y.entries()){const H=m(a(t.workspacePath,D),"utf8"),k=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(H.replace(/\r\n/g,`
|
|
9
|
+
`))?.[1]??"";if(x(H,"id")!==`${e}.${String(v+1).padStart(2,"0")}`||x(H,"epic_id")!==e||/^\s*epic\s*:/m.test(k)||x(H,"status")!=="backlog"||!H.includes("## Acceptance Criteria")||!/\bGiven\b[\s\S]*\bWhen\b[\s\S]*\bThen\b/.test(H))throw new Error("planning-generation-story-invalid")}const L=JSON.parse(m(a(t.sourceRoot,p),"utf8")),$=JSON.parse(m(a(t.workspacePath,p),"utf8")),q=L.epics,C=$.epics,z=q?.[e],V=C?.[e];if(!q||!C||!z||!V||z.id!==e||z.status!=="researched"||!Array.isArray(z.steps_completed)||z.steps_completed.length!==2||!tt(z.steps_completed[0],ut)||!tt(z.steps_completed[1],St)||!S(z.output_files,{diagnosis:`${c}/diagnosis.md`,research:`${c}/research.md`})||typeof $.last_scan!="string"||!Number.isFinite(Date.parse($.last_scan))||typeof V.completed_at!="string"||!Number.isFinite(Date.parse(V.completed_at)))throw new Error("planning-generation-index-predecessor-invalid");const X=V.steps_completed?.[2];if(!tt(X,ee))throw new Error("planning-generation-index-transition-invalid");const Q={...L,last_scan:$.last_scan,epics:{...q,[e]:{...z,status:"generated",steps_completed:[...z.steps_completed,X],completed_at:V.completed_at,output_files:{...z.output_files,epic:d,stories:y}}}};if(!S($,Q))throw new Error("planning-generation-index-transition-invalid");const O=A.map(v=>F("sha256").update(m(a(t.workspacePath,v))).digest("hex")),U=()=>A.every((v,D)=>{try{return P(t.workspacePath,v),F("sha256").update(m(a(t.workspacePath,v))).digest("hex")===O[D]}catch{return!1}});return W(t,A,t.baseSha,Rt(t.sourceRoot),U)}catch{throw new Error("private-execution-planning-generation-admission-unverified")}}function Fe(t,r,e){try{if(!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e))throw new Error("story-id-invalid");const o=".neocortex/state.json";P(r.sourceRoot,o),P(r.workspacePath,o);const i=m(a(r.sourceRoot,o));if(!i.equals(m(a(r.workspacePath,o))))throw new Error("state-drift");const s=JSON.parse(i.toString("utf8")),n=s?.stories?.[e],f=n?.files_to_modify;if(s?.schema_version!==1||n?.id!==e||!Array.isArray(f)||f.length<1||f.length>st||f.some(d=>typeof d!="string"||!rt(d)||d.length>1024||/[\r\n]/.test(d))||new Set(f).size!==f.length)throw new Error("write-set-invalid");const p=f,c=p.filter(d=>{if(!d.startsWith("docs/stories/")||!d.endsWith(".story.md"))return!1;P(r.sourceRoot,d),P(r.workspacePath,d);const h=m(a(r.sourceRoot,d));if(!h.equals(m(a(r.workspacePath,d))))throw new Error("story-drift");const w=/^---\r?\n([\s\S]{1,8192}?)\r?\n---(?:\r?\n|$)/.exec(h.toString("utf8"))?.[1]?.split(/\r?\n/).filter(u=>u.startsWith("id:"))??[];return w.length===1&&w[0].slice(3).trim().replace(/^(["'])(.*)\1$/,"$2")===e});if(c.length!==1)throw new Error("story-target-ambiguous");return`${t}
|
|
10
10
|
|
|
11
11
|
Private story handoff (local only):
|
|
12
|
-
${JSON.stringify({storyId:e,storyPath:c[0],allowedPaths:[...
|
|
12
|
+
${JSON.stringify({storyId:e,storyPath:c[0],allowedPaths:[...p].sort()})}
|
|
13
13
|
Work from this isolated checkout's current directory. Use the exact storyPath above for the delivered current step; do not use an unresolved story-file placeholder or infer a filename. Persist the current step's actual result in the declared files; a final chat response alone is not a saved candidate. Modify only allowedPaths and preserve story identity and the write set. Do not operate Git, change unrelated stories, grant root QA/checkpoint authority, or declare the story, epic or pipeline complete. If required inputs are unavailable, report failure without inventing evidence or completion.
|
|
14
|
-
`}catch{throw new Error("private-execution-state-step-handoff-unverified")}}function
|
|
14
|
+
`}catch{throw new Error("private-execution-state-step-handoff-unverified")}}function Be(t,r){try{if(!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(r))throw new Error("story-id-invalid");const e=".neocortex/state.json";P(t.sourceRoot,e),P(t.workspacePath,e);const o=JSON.parse(m(a(t.sourceRoot,e),"utf8")),i=JSON.parse(m(a(t.workspacePath,e),"utf8"));if(!o||typeof o!="object"||Array.isArray(o)||!i||typeof i!="object"||Array.isArray(i))throw new Error("state-invalid");const s=o,n=i,f=s.stories,p=n.stories,c=f?.[r],d=p?.[r],h=c?.files_to_modify;if(s.schema_version!==1||n.schema_version!==1||!f||!p||!c||!d||c.id!==r||d.id!==r||d.epic_id!==c.epic_id||!Array.isArray(h)||h.length===0||h.length>st||h.some(x=>typeof x!="string"||!rt(x)||x.length>1024)||new Set(h).size!==h.length||!S(d.files_to_modify,h))throw new Error("write-set-invalid");const{[r]:l,...w}=f,{[r]:u,...g}=p,{stories:_,last_updated:j,...b}=s,{stories:N,last_updated:y,...A}=n;if(!S(g,w)||!S(A,b))throw new Error("state-unrelated-drift");return W(t,[...h].sort(),t.baseSha)}catch{throw new Error("private-execution-state-step-admission-unverified")}}function Ce(t,r,e){if(r==="chaos-plan"&&e==="chaos-quarterly-v1")try{const i=new Date,s=`Q${Math.floor(i.getUTCMonth()/3)+1}-${i.getUTCFullYear()}`,n=M(B(t.workspacePath,!0)).paths,f=`tools/chaos/${s}-plan.md`,p=`.neocortex/chaos-history/${s}.md`,c=n.filter(u=>u.startsWith("tools/chaos/experiments/")),d=c.map(u=>/^tools\/chaos\/experiments\/(chaos-mesh|litmus|aws-fis)-(?:PodKill|NetworkChaos|IOChaos|StressChaos|TimeChaos|pod-kill|network-chaos|io-chaos|stress-chaos|time-chaos)-([a-z0-9]+(?:-[a-z0-9]+)*)\.yaml$/.exec(u));if(!n.includes(f)||!n.includes(p)||c.length<5||c.length>10||n.length!==c.length+2||d.some(u=>!u)||new Set(d.map(u=>u[1])).size!==1)throw new Error("chaos-write-set-invalid");for(const u of n)if(P(t.workspacePath,u),R(a(t.workspacePath,u)).size===0)throw new Error("chaos-empty-artifact");const h=m(a(t.workspacePath,p),"utf8");if(!h.includes(s)||!/\bPLANNED\b/.test(h))throw new Error("chaos-history-invalid");const w=G(t.workspacePath,["ls-tree","-z","HEAD","--",p]).length>0?G(t.workspacePath,["show",`HEAD:${p}`]).toString("utf8"):"";if(w&&!h.startsWith(w))throw new Error("chaos-history-not-append-only");return W(t,n,t.baseSha)}catch{throw new Error("private-execution-project-step-admission-unverified")}const o=r==="sync-openapi"&&e==="sync-openapi-contract-v1"?["docs/architecture/api-contracts.md","docs/api/openapi.yaml"]:r==="tech-debt"&&e==="tech-debt-registry-v1"?[".neocortex/tech-debt-registry.json"]:void 0;if(!o)throw new Error("private-execution-project-step-admission-unverified");try{if(r==="tech-debt"){const i=".neocortex/tech-debt-registry.json";P(t.workspacePath,i);const s=JSON.parse(m(a(t.workspacePath,i),"utf8"));if(!s||typeof s!="object"||Array.isArray(s))throw new Error("registry-invalid");const n=s;if(n.schema_version!==2||n.version!==void 0&&n.version!==2||!Array.isArray(n.items))throw new Error("registry-invalid")}return W(t,o,t.baseSha)}catch{throw new Error("private-execution-project-step-admission-unverified")}}function Nt(t,r){const e=t==="arch-prd"&&r==="arch-prd-docs-v1"?["docs/architecture/prd.md","docs/architecture/product-experience.md"]:t==="arch-architecture"&&r==="arch-architecture-doc-v1"?["docs/architecture/architecture.md"]:t==="arch-fitness-functions"&&r==="arch-fitness-tools-v1"?["tools/architecture/dependency-cruiser.config.js","tools/architecture/archunit-test.ts","tools/architecture/.eslintrc.boundaries.js"]:t==="arch-api-contracts"&&r==="arch-api-contracts-docs-v1"?["docs/architecture/api-contracts.md","docs/api/openapi.yaml"]:t==="arch-api-integrations"&&r==="arch-api-integrations-doc-v1"?["docs/architecture/api-integrations.md"]:t==="arch-database"&&r==="arch-database-doc-v1"?["docs/architecture/database-schema.md"]:t==="arch-security"&&r==="arch-security-doc-v1"?["docs/architecture/cyber-security.md"]:t==="arch-design-system"&&r==="arch-design-system-doc-v1"?["docs/architecture/atomic-design-system.md"]:t==="arch-performance"&&r==="arch-performance-doc-v1"?["docs/architecture/performance-strategy.md"]:t==="arch-testing"&&r==="arch-testing-doc-v1"?["docs/architecture/testing-strategy.md"]:t==="arch-infrastructure"&&r==="arch-infrastructure-doc-v1"?["docs/architecture/infrastructure-deploy.md"]:t==="arch-review"&&r==="arch-review-doc-v1"?["docs/architecture/review-consolidation.md"]:t==="update-memory"&&r==="arch-memory-canonical-v1"?["NEOCORTEX.md"]:null;return e===null?null:Object.freeze(e)}function ze(t,r,e,o="all"){const i=Nt(r,e);if(!i)throw new Error("private-execution-architecture-admission-unverified");return`${t}
|
|
15
15
|
|
|
16
16
|
Private architecture handoff (local only):
|
|
17
|
-
${JSON.stringify({allowedPaths:
|
|
17
|
+
${JSON.stringify({allowedPaths:i})}
|
|
18
18
|
${o==="non-ui"?`The server admitted a signed non-UI scope for this snapshot. Preserve the backend-only scope: design-system and UX phases are not applicable. Do not require or generate interface artifacts.
|
|
19
19
|
`:""}Write exactly the listed nonempty artifacts inside this isolated clone. Existing compliant listed artifacts may remain unchanged; all listed artifacts must exist after execution. Place any necessary scope notes inside those artifacts. Do not edit README, package files, other documents, state, Git, QA records or configuration outside the listed paths. Do not install dependencies, use network, deploy or continue to another stage. Preserve existing arch:keep blocks byte-for-byte. Do not add new arch:keep markers. For managed memory, preserve all bytes outside its existing managed block. Root independently reviews artifacts and owns continuation, Git and acceptance.
|
|
20
|
-
`}function
|
|
20
|
+
`}function Le(t,r,e,o,i){const s=Nt(r,e);if(!s||!/^P[1-9][0-9]{0,11}$/.test(o)||!/^[a-f0-9]{64}$/.test(i))throw new Error("private-execution-architecture-admission-unverified");try{P(t.workspacePath,".neocortex/state.json");const n=JSON.parse(m(a(t.workspacePath,".neocortex/state.json"),"utf8"));if(!n||typeof n!="object"||Array.isArray(n))throw new Error("state-invalid");const f=n,c=f.archPlan?.execution,d=f.epics;if(!c||c.currentStageCommand!==r||c.targetEpicId!==o||c.graphRevision!==i||!d||!Object.hasOwn(d,o))throw new Error("state-binding-mismatch");if(r==="update-memory"){if(c.continuationState!=="delegate"||c.reviewDecision?.decision!=="approved")throw new Error("memory-root-review-missing");const h="NEOCORTEX.md";if(!M(B(t.workspacePath,!0)).paths.includes(h))throw new Error("memory-effect-missing");P(t.sourceRoot,h),P(t.workspacePath,h);const l=m(a(t.sourceRoot,h),"utf8"),w=m(a(t.workspacePath,h),"utf8"),u="<!-- NEOCORTEX-MEMORY-START -->",g="<!-- NEOCORTEX-MEMORY-END -->",_=y=>{if(y.split(u).length!==2||y.split(g).length!==2||y.indexOf(u)>=y.indexOf(g))throw new Error("memory-markers-invalid");const A=y.indexOf(u)+u.length,x=y.indexOf(g);return{before:y.slice(0,A),body:y.slice(A,x),after:y.slice(x)}},j=_(l),b=_(w);if(j.before!==b.before||j.after!==b.after||j.body===b.body||Buffer.byteLength(w,"utf8")>32768||w.split(`
|
|
21
21
|
`).length>240)throw new Error("memory-managed-block-invalid");const N=new Set(j.body.split(`
|
|
22
22
|
`));for(const y of b.body.split(`
|
|
23
|
-
`))N.has(y)||Wt(y)}if(r==="arch-prd"){const h="docs/architecture/prd.md";if(!M(B(t.workspacePath,!0)).paths.includes(h))throw new Error("prd-effect-missing");if(P(t.workspacePath,h),R(a(t.workspacePath,h)).size===0)throw new Error("prd-empty")}if(r==="arch-api-contracts"||r==="arch-fitness-functions"||r==="arch-api-integrations"||r==="arch-database"||r==="arch-security"||r==="arch-design-system"||r==="arch-performance"||r==="arch-testing"||r==="arch-infrastructure"||r==="arch-review"){const h=M(B(t.workspacePath,!0)).paths;for(const
|
|
23
|
+
`))N.has(y)||Wt(y)}if(r==="arch-prd"){const h="docs/architecture/prd.md";if(!M(B(t.workspacePath,!0)).paths.includes(h))throw new Error("prd-effect-missing");if(P(t.workspacePath,h),R(a(t.workspacePath,h)).size===0)throw new Error("prd-empty")}if(r==="arch-api-contracts"||r==="arch-fitness-functions"||r==="arch-api-integrations"||r==="arch-database"||r==="arch-security"||r==="arch-design-system"||r==="arch-performance"||r==="arch-testing"||r==="arch-infrastructure"||r==="arch-review"){const h=M(B(t.workspacePath,!0)).paths;for(const l of s){if(!h.includes(l)&&G(t.workspacePath,["cat-file","-t",`${t.baseSha}:${l}`]).toString("utf8").trim()!=="blob")throw new Error("architecture-required-effect-missing");if(P(t.workspacePath,l),R(a(t.workspacePath,l)).size===0)throw new Error("architecture-required-effect-empty");if(r==="arch-fitness-functions"){P(t.sourceRoot,l);const w=nt(a(t.sourceRoot,l))?m(a(t.sourceRoot,l),"utf8"):"",u=m(a(t.workspacePath,l),"utf8"),g=$t(w),_=$t(u);if(!S(_,g))throw new Error("architecture-keep-marker-changed")}}}return W(t,s,t.baseSha)}catch{throw new Error("private-execution-architecture-admission-unverified")}}function He(t,r,e,o){try{if(!/^P[1-9][0-9]{0,11}$/.test(r)||!/^[a-f0-9]{64}$/.test(e)||o.schemaVersion!==1||o.targetEpicId!==r)throw new Error("binding-invalid");const i=Mt(t.sourceRoot,r),s=Jt(t.workspacePath,r);if(!S(i,o)||!S(s,o))throw new Error("write-set-invalid");P(t.workspacePath,".neocortex/state.json");const n=JSON.parse(m(a(t.workspacePath,".neocortex/state.json"),"utf8"));if(!n||typeof n!="object"||Array.isArray(n))throw new Error("state-invalid");const f=n,c=f.archPlan?.execution,d=f.epics;if(!c||c.currentStageCommand!=="arch-ux-design"||c.continuationState!=="delegate"||c.targetEpicId!==r||c.graphRevision!==e||!d||!Object.hasOwn(d,r))throw new Error("stage-invalid");const h=M(B(t.workspacePath,!0)).paths;if(h.length!==o.pathCount||h.some(l=>!o.paths.includes(l)))throw new Error("agent-path-unclaimed");for(const l of o.paths){P(t.sourceRoot,l),P(t.workspacePath,l);const w=R(a(t.workspacePath,l));if(!w.isFile()||w.isSymbolicLink()||w.size<1)throw new Error("effect-empty");const u=new TextDecoder("utf-8",{fatal:!0}).decode(m(a(t.workspacePath,l)));if(!u.trim()||u.includes("\0"))throw new Error("effect-invalid")}return qt(t.workspacePath,o),W(t,o.paths,t.baseSha)}catch{throw new Error("private-execution-ux-admission-unverified")}}function Je(t,r,e,o,i,s){try{if(!/^P[1-9][0-9]{0,11}$/.test(r)||!/^[a-f0-9]{64}$/.test(e)||o.targetEpicId!==r||o.graphRevision!==e||i.schemaVersion!==1)throw new Error("binding-invalid");const n=Ht(t.sourceRoot);if(!n||!S(n.receipt,o))throw new Error("answers-invalid");const f=xt(t.sourceRoot,n.answers.generateProvider),p=xt(t.workspacePath,n.answers.generateProvider);if(f.outcome!=="ready"||p.outcome!=="ready"||!S(f.writeSet,i)||!S(p.writeSet,i))throw new Error("write-set-invalid");const c=M(B(t.workspacePath,!0)).paths;if(c.some(u=>!i.paths.includes(u)))throw new Error("agent-path-unclaimed");let d=0,h=0;for(const u of i.paths){if(P(t.sourceRoot,u),nt(a(t.sourceRoot,u))||!c.includes(u))throw new Error("effect-missing-or-overwrite");P(t.workspacePath,u);const g=R(a(t.workspacePath,u));if(!g.isFile()||g.size<1)throw new Error("effect-empty");const _=new TextDecoder("utf-8",{fatal:!0}).decode(m(a(t.workspacePath,u))),j=i.interactions.find(N=>N.filePath===u);if(u!==i.providerPath&&!j)throw new Error("private-execution-pact-interaction-missing");const b=Gt(u,_,n.answers.brokerUrl,j,t.workspacePath,n.answers.matchersAggressive);b.consumerBinding==="app-import-candidate"&&d++,b.consumerBinding==="mock-only-scaffold"&&h++}let l=i.paths;if(s){const u=Kt(t.sourceRoot,n.answers.generateProvider),g=_=>F("sha256").update(_).digest("hex");if(s.schemaVersion!==1||s.outcome!=="candidate-unverified"||s.executionVerified!==!1||s.sourceManifestSha256!==g(u.sourceText)||s.sourceLockSha256!==(u.sourceLockText===null?null:g(u.sourceLockText))||s.manifestText!==u.candidateText||!ft(t.sourceRoot,t.workspacePath,t.baseSha,"package.json")||!ft(t.sourceRoot,t.workspacePath,t.baseSha,"package-lock.json"))throw new Error("toolchain-binding-invalid");for(const _ of["package.json","package-lock.json"]){P(t.sourceRoot,_),P(t.workspacePath,_);const j=_==="package.json"?u.sourceText:u.sourceLockText,b=nt(a(t.workspacePath,_))?m(a(t.workspacePath,_),"utf8"):null;if(j!==b)throw new Error("toolchain-clone-raced")}if(mt(a(t.workspacePath,"package.json"),s.manifestText),mt(a(t.workspacePath,"package-lock.json"),s.lockText),Xt(t.workspacePath,n.answers.generateProvider).outcome!=="manifest-aligned")throw new Error("toolchain-candidate-invalid");l=[...i.paths,"package.json","package-lock.json"]}const w=W(t,l,t.baseSha);return Object.freeze({...w,consumerBindingCandidateCount:d,consumerScaffoldCount:h})}catch{throw new Error("private-execution-pact-admission-unverified")}}function Me(t,r,e,o=new Date().toISOString()){try{const i=At(t.sourceRoot,r);if(!S(i,e)||!pt(t.sourceRoot,t.workspacePath,e.prdPath)||e.aggregates.some(h=>!pt(t.sourceRoot,t.workspacePath,h.implementationFile))||e.writeSet.length===0)throw new Error("plan-drift");const s=M(B(t.workspacePath,!0)).paths;if(!S(s,e.writeSet))throw new Error("agent-path-unclaimed");const n=new Map;for(const h of e.aggregates){P(t.sourceRoot,h.testFile),P(t.workspacePath,h.testFile);const l=R(a(t.workspacePath,h.testFile));if(!l.isFile()||l.isSymbolicLink()||l.size<1||l.size>Z)throw new Error("test-invalid");const w=m(a(t.workspacePath,h.testFile)),u=new TextDecoder("utf-8",{fatal:!0}).decode(w),g=e.language==="typescript"?(u.match(/\b(?:it|test)\s*\(/g)??[]).length:(u.match(/^def\s+test_[A-Za-z0-9_]+\s*\(/gm)??[]).length;if(!u.trim()||u.includes("\0")||g<h.invariantCount||/\b(?:it|test|describe)\s*\.\s*(?:skip|todo|only)\s*\(/.test(u)||!u.includes(String(e.numRuns)))throw new Error("test-invalid");e.language==="typescript"&&It({source:u,testFile:h.testFile,implementationFile:h.implementationFile,invariantCount:h.invariantCount,numRuns:e.numRuns}),n.set(h.testFile,F("sha256").update(w).digest("hex"))}P(t.sourceRoot,e.prdPath),P(t.workspacePath,e.prdPath);const f=m(a(t.workspacePath,e.prdPath)),p=new TextDecoder("utf-8",{fatal:!0}).decode(f),c=kt(p,e,o);mt(a(t.workspacePath,e.prdPath),c);const d=F("sha256").update(c).digest("hex");return W(t,[...e.writeSet,e.prdPath],t.baseSha,void 0,()=>{try{return!S(At(t.sourceRoot,r),e)||e.aggregates.some(h=>!pt(t.sourceRoot,t.workspacePath,h.implementationFile))||F("sha256").update(m(a(t.workspacePath,e.prdPath))).digest("hex")!==d?!1:[...n].every(([h,l])=>F("sha256").update(m(a(t.workspacePath,h))).digest("hex")===l)}catch{return!1}})}catch{throw new Error("private-execution-property-admission-unverified")}}export{Le as admitPrivateArchitectureStageWorkspace,Te as admitPrivateEpicClaimWorkspace,De as admitPrivateGenerateEpicWorkspace,je as admitPrivateIdeaDiagnosisWorkspace,Ne as admitPrivateIdeaResearchWorkspace,Je as admitPrivatePactWorkspace,Ce as admitPrivateProjectStepWorkspace,Me as admitPrivatePropertyTestWorkspace,Be as admitPrivateStateBoundStepWorkspace,He as admitPrivateUxWorkspace,Oe as admitPrivateYoloFrozenWorkspace,ze as appendPrivateArchitectureHandoff,Fe as appendPrivateStateBoundStepHandoff,Nt as privateArchitectureStagePaths,Ae as privateYoloSourceFileMatchesSnapshot,$e as verifyPrivateYoloRejectedCandidateOrigin,Se as verifyPrivateYoloSnapshotBoundary};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{execFileSync as R}from"node:child_process";import{createHash as T}from"node:crypto";import{chmodSync as A,existsSync as C,lstatSync as f,mkdtempSync as g,readFileSync as L,realpathSync as b}from"node:fs";import{homedir as G}from"node:os";import{isAbsolute as m,join as d,relative as H,resolve as
|
|
1
|
+
import{execFileSync as R}from"node:child_process";import{createHash as T}from"node:crypto";import{chmodSync as A,existsSync as C,lstatSync as f,mkdtempSync as g,readFileSync as L,realpathSync as b}from"node:fs";import{homedir as G}from"node:os";import{isAbsolute as m,join as d,relative as H,resolve as v}from"node:path";import{withoutVerifiedProjectIdentityStatus as N}from"../migrations/project-identity.js";const I=".neocortex/pending-epic-claims.json",j=["/var","/tmp","/etc"],k=128*1024;function s(){throw new Error("path-invalid")}function O(e){return j.some(t=>e===t||e.startsWith(`${t}/`))?`/private${e}`:e}function y(e,t){const r=b(e);return r===e||t==="darwin"&&r===O(e)||t==="win32"&&r.toLowerCase()===e.toLowerCase()?r:s()}function B(e){const t=e.platform??process.platform;if(t==="linux"||t==="darwin")return typeof process.getuid!="function"&&s(),{platform:t};if(t==="win32"){const r=e.userProfileRoot??G();(typeof r!="string"||!m(r))&&s();const o=y(v(r),t);return f(o).isDirectory()||s(),{platform:t,profileRoot:o}}return s()}function w(e,t,r){return t.platform==="win32"?!0:e.uid===process.getuid?.()&&(e.mode&r)===0}function q(e,t){if(t.platform!=="win32")return!0;const r=H(t.profileRoot.toLowerCase(),e.toLowerCase());return r!==""&&!r.startsWith("..")&&!m(r)}function W(e,t){const r=f(e);(!r.isDirectory()||r.isSymbolicLink())&&s();const o=y(e,t.platform);return(!w(f(o),t,18)||!q(o,t))&&s(),o}function D(e){return e==="linux"||e==="darwin"||e==="win32"}function _(e=process.platform){return D(e)?e==="win32"||typeof process.getuid=="function":!1}function J(e,t=process.platform){return _(t)?t==="win32"||(e.mode&63)===0:!1}function K(e,t=process.platform){return!_(t)||!D(t)?!1:P(e,{platform:t})}function P(e,t){try{const r=f(d(e,".neocortex")),o=f(d(e,I));return r.isDirectory()&&!r.isSymbolicLink()&&w(r,t,18)&&o.isFile()&&!o.isSymbolicLink()&&w(o,t,63)&&o.size>0&&o.size<=k}catch{return!1}}function l(e,t){const r={...process.env};for(const o of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete r[o];return R("git",[...t],{cwd:e,env:r,stdio:["ignore","pipe","pipe"],timeout:3e4,maxBuffer:16*1024*1024})}function a(e,t){return l(e,t).toString("utf8").trim()}function x(e,t,r,o,c=!1){const h=l(e,["status","--porcelain=v1","-z","--untracked-files=all"]).toString("utf8").split("\0").filter(Boolean),i=c?N(e,h):h,E=!c||P(e,o);return a(e,["rev-parse","HEAD"])===t&&a(e,["symbolic-ref","--quiet","--short","HEAD"])===r&&E&&(i.length===0||c&&i.length===1&&i[0]===`?? ${I}`)}function S(e){const t=d(e,".neocortex","state.json"),r=f(t);if(!r.isFile()||r.isSymbolicLink())throw new Error("state-invalid");return T("sha256").update(L(t)).digest("hex")}function X(e){try{const t=a(e,["rev-parse","--verify","HEAD"]);if(!/^[a-f0-9]{40,64}$/.test(t))throw new Error("head-invalid");return Object.freeze({headSha:t,stateSha256:S(e)})}catch{throw new Error("private-execution-project-snapshot-unverified")}}function Q(e,t){try{if(e.baseSha!==t.headSha||a(e.sourceRoot,["rev-parse","--verify","HEAD"])!==t.headSha||S(e.sourceRoot)!==t.stateSha256||S(e.workspacePath)!==t.stateSha256)throw new Error("snapshot-mismatch")}catch{throw new Error("private-execution-project-snapshot-unverified")}}function U(e,t,r=!1,o={}){try{const c=B(o);(!m(e)||!m(t))&&s();const h=v(e);f(h).isDirectory()||s();const i=y(h,c.platform),E=W(v(t),c);a(i,["rev-parse","--show-toplevel"])!==i&&s();const u=a(i,["rev-parse","HEAD"]),p=a(i,["symbolic-ref","--quiet","--short","HEAD"]);if(!/^[a-f0-9]{40,64}$/.test(u)||!p||!x(i,u,p,c,r))throw new Error("source-dirty");const n=g(d(E,"p222-private-yolo-"));if(c.platform!=="win32"&&(A(n,448),(f(n).mode&511)!==448))throw new Error("physical-mismatch");if(l(n,["init","-q"]),l(n,["fetch","-q","--no-tags","--depth=1",i,u]),l(n,["checkout","-q","-b",p,"FETCH_HEAD"]),!x(i,u,p,c,r)||a(n,["rev-parse","HEAD"])!==u||a(n,["symbolic-ref","--quiet","--short","HEAD"])!==p||l(n,["status","--porcelain=v1","-z","--untracked-files=all"]).byteLength!==0||C(d(n,".git","objects","info","alternates")))throw new Error("physical-mismatch");return Object.freeze({schemaVersion:1,sourceRoot:i,workspacePath:n,baseSha:u,executionBranch:p})}catch{throw new Error("private-execution-isolated-workspace-unverified")}}export{I as PRIVATE_EPIC_PENDING_SIDECAR,Q as assertPrivateProjectStepBaseline,X as capturePrivateProjectStepBaseline,_ as isPrivateIsolatedWorkspacePlatform,U as preparePrivateYoloIsolatedWorkspace,J as privateIsolatedWorkspaceModeVerified,K as privatePendingEpicSidecarVerified};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{execFileSync as $,spawnSync as on}from"node:child_process";import{createHash as dn,createPublicKey as pn,randomUUID as gn,verify as fn}from"node:crypto";import{closeSync as j,fsyncSync as R,lstatSync as w,mkdirSync as ln,openSync as A,readFileSync as L,realpathSync as H,renameSync as hn,unlinkSync as G,writeFileSync as J}from"node:fs";import{isAbsolute as mn,join as u,resolve as N}from"node:path";import{isDeepStrictEqual as b}from"node:util";import{canonicalPlanningIntake as un,createPlanningReceiptV1 as T,planningIntakeRevision as M,preparePlanningIntake as Y,projectDiagnosedEpicState as Q}from"../../../shared/dist/planning/diagnosis-state.js";const S=/^[a-f0-9]{64}$/,
|
|
1
|
+
import{execFileSync as $,spawnSync as on}from"node:child_process";import{createHash as dn,createPublicKey as pn,randomUUID as gn,verify as fn}from"node:crypto";import{closeSync as j,fsyncSync as R,lstatSync as w,mkdirSync as ln,openSync as A,readFileSync as L,realpathSync as H,renameSync as hn,unlinkSync as G,writeFileSync as J}from"node:fs";import{isAbsolute as mn,join as u,resolve as N}from"node:path";import{isDeepStrictEqual as b}from"node:util";import{canonicalPlanningIntake as un,createPlanningReceiptV1 as T,planningIntakeRevision as M,preparePlanningIntake as Y,projectDiagnosedEpicState as Q}from"../../../shared/dist/planning/diagnosis-state.js";import{withoutVerifiedProjectIdentityStatus as yn}from"../migrations/project-identity.js";const S=/^[a-f0-9]{64}$/,In=/^P[1-9][0-9]{0,11}$/,Sn=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,B=["idea","diagnosis","enrichment","index"],V="acd455ed0e39d98b90fb57391db75e366e4c5604db043e03a89a20e33d643c3c",En="81f50aaa801c1660eabe46e645501acbfb3e9873410c991e1496c014ca75c369",kn=Object.freeze([Object.freeze({keyId:"oci-planning-step-2026-11",publicKeyPem:`-----BEGIN PUBLIC KEY-----
|
|
2
2
|
MCowBQYDK2VwAyEAgsdYlx3VXghDcKkYCf0YfhR07KEqtcgGrTtpf1vLy2g=
|
|
3
3
|
-----END PUBLIC KEY-----
|
|
4
|
-
`,state:"active"})]);let U;function
|
|
4
|
+
`,state:"active"})]);let U;function Fn(n){U=n?Object.freeze([...n]):void 0}function F(){return U??kn}const X=["schemaVersion","stage","epicId","stepId","claimId","revision","issuedAt","keyId","signature"],Pn="neocortex-planning-step-binding-v1\0";function wn(n){return y(`planning-step-binding-p01\0${n}`)}function xn(n){return d(n)&&Object.keys(n).sort().join("|")===[...X].sort().join("|")&&X.every(i=>typeof n[i]=="string"&&n[i].length>0&&Buffer.byteLength(n[i])<=256)&&n.schemaVersion==="PlanningStepBinding/1"&&["P01","P02","P03","memory"].includes(n.stage)&&/^[a-z0-9-]{1,64}$/.test(n.keyId)&&S.test(n.revision)&&Number.isFinite(Date.parse(n.issuedAt))}function bn(n,i,e=F()){if(!xn(n))throw new Error("planning-step-binding-missing");const t=e.filter(f=>f.keyId===n.keyId);if(t.length!==1||t[0].state!=="active"&&t[0].state!=="grace")throw new Error("planning-step-binding-key-unknown");let s;try{s=pn(t[0].publicKeyPem)}catch{throw new Error("planning-step-binding-key-unknown")}if(s.asymmetricKeyType!=="ed25519")throw new Error("planning-step-binding-key-unknown");const c=/^[a-f0-9]{128}$/.test(n.signature)?Buffer.from(n.signature,"hex"):void 0,o=Buffer.from(Pn+JSON.stringify({schemaVersion:n.schemaVersion,stage:n.stage,epicId:n.epicId,stepId:n.stepId,claimId:n.claimId,revision:n.revision,issuedAt:n.issuedAt,keyId:n.keyId}),"utf8");if(!c||c.length!==64||c.toString("hex")!==n.signature||!fn(null,o,s,c))throw new Error("planning-step-binding-tampered");if(n.stage!==i.stage||n.epicId!==i.epicId||n.claimId!==i.claimId||n.revision!==i.revision||n.stepId!==`step-${i.stepDigest.slice(0,8)}`)throw new Error("planning-step-binding-step-mismatch")}function Dn(n,i,e){n===void 0&&e.length===0||bn(n,i,e)}function jn(n){return n===void 0?{}:{stepBinding:n}}function An(n){return n.stepBinding===void 0?{}:{stepBinding:n.stepBinding}}function d(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function y(n){return dn("sha256").update(n).digest("hex")}const Bn=Object.freeze({diagnosis:"p01",research:"p02",generation:"p03"});function Z(n,i=0){return i>2||!d(n)?n:Object.fromEntries(Object.keys(n).sort().map(e=>[e,Z(n[e],i+1)]))}function W(n,i){const e=Bn[n];if(!e)throw new Error("planning-qa-phase-invalid");const t={schemaVersion:"PlanningQaEvidence/1",phase:n,claimId:i.claimId,epicId:i.epicId,sourceHead:i.sourceHead,admissionPatchSha256:i.admissionPatchSha256,artifactDigests:Z(i.artifactDigests)};return`qa-${e}-${y(JSON.stringify(t))}`}function v(n,i,e){try{return typeof i=="string"&&i===W(n,e)}catch{return!1}}function _(n,i){return $("git",[...i],{cwd:n,encoding:"utf8",stdio:["ignore","pipe","ignore"],maxBuffer:65536}).trim()}function E(n,i,e){const t=u(n,i),s=w(t);if(!s.isFile()||s.isSymbolicLink()||s.size<1||s.size>e)throw new Error("planning-diagnosis-physical-artifact-invalid");return L(t)}function nn(n,i){return typeof n=="string"&&n.length<=128&&y(n)===i}function en(n,i,e){const t=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(n.replace(/\r\n/g,`
|
|
5
5
|
`))?.[1];if(!t)return!1;const s=t.split(`
|
|
6
|
-
`),c=o=>{const f=s.filter(r=>r.startsWith(`${o}:`));return f.length===1?f[0].slice(o.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0};return c("epic_id")===i&&c("status")==="completed"&&nn(c("step"),e)}function
|
|
7
|
-
`)]))))}function tn(n){return{claimId:n.claimId,epicId:n.epicId,sourceHead:n.sourceHead,admissionPatchSha256:n.admission.patchSha256,artifactDigests:n.artifactDigests}}function sn(n,i){if(!d(n)||Object.keys(n).filter(e=>e!=="stepBinding").sort().join("|")!==["schemaVersion","verdict","claimId","epicId","logicalFingerprint","sourceHead","sourceBranch","sourceStateSha256","admission","artifactDigests","qaEvidenceId","intake","artifactSummary"].sort().join("|")||n.schemaVersion!=="PlanningDiagnosisRootReview/1"||n.verdict!=="accepted"||typeof n.claimId!="string"||!In.test(n.claimId)||typeof n.epicId!="string"||!yn.test(n.epicId)||typeof n.logicalFingerprint!="string"||!S.test(n.logicalFingerprint)||typeof n.sourceHead!="string"||!/^[a-f0-9]{40}$/.test(n.sourceHead)||typeof n.sourceBranch!="string"||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]{0,127}$/.test(n.sourceBranch)||typeof n.sourceStateSha256!="string"||!S.test(n.sourceStateSha256)||!d(n.admission)||n.admission.schemaVersion!==1||n.admission.outcome!=="admitted-unverified"||n.admission.baseSha!==n.sourceHead||n.admission.executionBranch!==n.sourceBranch||typeof n.admission.patchSha256!="string"||!S.test(n.admission.patchSha256)||typeof n.qaEvidenceId!="string"||!/^qa-[a-z0-9-]{8,80}$/.test(n.qaEvidenceId)||!d(n.artifactDigests)||Object.keys(n.artifactDigests).sort().join("|")!==[...B].sort().join("|")||B.some(e=>typeof n.artifactDigests[e]!="string"||!S.test(n.artifactDigests[e])))throw new Error("planning-diagnosis-review-invalid");if(T({kind:"diagnosis",epicId:n.epicId,intakeRevision:Y(n.intake).intakeRevision,artifactSummary:n.artifactSummary,accepted:!0}),bn(n.stepBinding,{stage:"P01",epicId:n.epicId,claimId:n.claimId,revision:Pn(n.claimId),stepDigest:F},i),!v("diagnosis",n.qaEvidenceId,tn(n)))throw new Error("planning-diagnosis-qa-evidence-unbound")}function cn(n,i,e,t){if(_(n,["rev-parse","HEAD"])!==i.sourceHead||_(n,["symbolic-ref","--quiet","--short","HEAD"])!==i.sourceBranch)throw new Error("planning-diagnosis-head-conflict");const s=w(u(n,".neocortex")),c=w(u(n,".neocortex/pending-epic-claims.json"));if(!s.isDirectory()||s.isSymbolicLink()||(s.mode&18)!==0||!c.isFile()||c.isSymbolicLink()||c.uid!==process.getuid?.()||(c.mode&63)!==0)throw new Error("planning-diagnosis-claim-boundary-invalid");const o=JSON.parse(E(n,".neocortex/pending-epic-claims.json",128*1024).toString("utf8")),f=d(o)&&d(o.operations)?o.operations[i.logicalFingerprint]:void 0;if(!d(f)||f.claimId!==i.claimId||f.epicId!==i.epicId)throw new Error("planning-diagnosis-claim-conflict");const r=`.neocortex/planning/epic-${i.epicId}`,h={idea:`${r}/idea.json`,diagnosis:`${r}/diagnosis.md`,enrichment:`${r}/enriched-prompt.md`,index:".neocortex/planning/planning.json"};if(!Array.isArray(i.admission.changedPaths)||[...i.admission.changedPaths].sort().join("|")!==Object.values(h).sort().join("|")||e&&Bn(n,h,t)!==i.admission.patchSha256)throw new Error("planning-diagnosis-admission-patch-conflict");const p={idea:E(n,h.idea,32*1024),diagnosis:E(n,h.diagnosis,256*1024),enrichment:E(n,h.enrichment,256*1024),index:E(n,h.index,128*1024)};for(const x of B)if(y(p[x])!==i.artifactDigests[x])throw new Error("planning-diagnosis-artifact-conflict");const g=JSON.parse(p.idea.toString("utf8")),l=JSON.parse(p.index.toString("utf8")),a=Y(i.intake).intake,m=d(l)&&d(l.epics)?l.epics[i.epicId]:void 0,I=d(m)?m.output_files:void 0;if(!d(g)||g.epic_id!==i.epicId||g.status!=="diagnosed"||g.raw_input!==a.rawIntent||!d(m)||m.id!==i.epicId||m.idea!==a.rawIntent||m.status!=="diagnosed"||!en(p.diagnosis.toString("utf8"),i.epicId,F)||!en(p.enrichment.toString("utf8"),i.epicId,Sn)||!Array.isArray(m.steps_completed)||m.steps_completed.length!==1||!nn(m.steps_completed[0],F)||!d(I)||!b(I,{diagnosis:h.diagnosis})||typeof m.created_at!="string"||!Number.isFinite(Date.parse(m.created_at))||m.completed_at!==null)throw new Error("planning-diagnosis-artifact-identity-conflict");if(typeof a.goal!="string"||!a.goal.trim()||typeof a.desiredOutcome!="string"||!a.desiredOutcome.trim()||!Array.isArray(a.users)||a.users.length===0||!Array.isArray(a.surfaces)||a.surfaces.length===0)throw new Error("planning-diagnosis-critical-intake-missing");const k=M(a),P=T({kind:"diagnosis",epicId:i.epicId,intakeRevision:k,artifactSummary:i.artifactSummary,accepted:!0});return{checkpoint:{schemaVersion:1,epicId:i.epicId,intake:a,intakeRevision:k,diagnosisReceipt:P},receiptId:P.receiptId}}function C(n,i,e){const t=cn(n,i,!0,e),s=E(n,".neocortex/state.json",8*1024*1024);if(y(s)!==i.sourceStateSha256)throw new Error("planning-diagnosis-state-conflict");const c=JSON.parse(s.toString("utf8"));if(!d(c)||d(c.scope)&&c.scope.kind==="projected")throw new Error("planning-diagnosis-state-invalid");return Q(c,{claimId:i.claimId,epicId:i.epicId,checkpoint:t.checkpoint}),{stateRaw:s,state:c,...t}}function rn(n,i){const e={schemaVersion:"PlanningDiagnosisPhysicalAcceptance/1",claimId:n.claimId,epicId:n.epicId,diagnosisReceiptId:i,qaEvidenceId:n.qaEvidenceId,sourceHead:n.sourceHead,sourceStateSha256:n.sourceStateSha256,admissionPatchSha256:n.admission.patchSha256,artifactDigests:n.artifactDigests,...Dn(n.stepBinding)};return{...e,receiptId:y(JSON.stringify(e)),publicSafe:!0}}function Vn(n,i,e,t=!1){const s=d(n)?n:void 0,o=(s&&d(s.epics)?s.epics:void 0)?.[e];if(!d(o)||o.id!==e||o.source!=="create-epic"||o.status!=="diagnosed"&&!(t&&o.status==="researched")||!d(o.createEpicPlanningClaim)||o.createEpicPlanningClaim.claimId!==i||o.createEpicPlanningClaim.epicId!==e||!d(o.createEpicPlanning)||!d(o.createEpicPlanningPhysical))throw new Error("planning-research-predecessor-invalid");const f=o.createEpicPlanning,r=o.createEpicPlanningPhysical,h=d(r.artifactDigests)?r.artifactDigests:void 0,p=un(f.intake),g=M(p),l=s&&d(s.epic_id_ledger)?s.epic_id_ledger:void 0,a=d(f.diagnosisReceipt)?f.diagnosisReceipt:void 0;if(f.schemaVersion!==1||f.epicId!==e||f.intakeRevision!==g||!t&&f.researchReceipt!==void 0||typeof p.goal!="string"||!p.goal.trim()||typeof p.desiredOutcome!="string"||!p.desiredOutcome.trim()||typeof p.rawIntent!="string"||!p.rawIntent.trim()||!Array.isArray(p.users)||p.users.length===0||!Array.isArray(p.surfaces)||p.surfaces.length===0||!Array.isArray(l?.reserved_ids)||!l.reserved_ids.includes(e)||!a||a.kind!=="diagnosis"||a.epicId!==e||a.intakeRevision!==g||a.accepted!==!0||typeof a.artifactSummary!="string"||!b(a,T({kind:"diagnosis",epicId:e,intakeRevision:g,artifactSummary:a.artifactSummary,accepted:!0}))||r.schemaVersion!=="PlanningDiagnosisPhysicalAcceptance/1"||r.claimId!==i||r.epicId!==e||r.diagnosisReceiptId!==a.receiptId||typeof r.qaEvidenceId!="string"||!/^qa-[a-z0-9-]{8,80}$/.test(r.qaEvidenceId)||typeof r.sourceHead!="string"||!/^[a-f0-9]{40}$/.test(r.sourceHead)||typeof r.sourceStateSha256!="string"||!S.test(r.sourceStateSha256)||typeof r.admissionPatchSha256!="string"||!S.test(r.admissionPatchSha256)||!h||Object.keys(h).sort().join("|")!==[...B].sort().join("|")||B.some(I=>typeof h[I]!="string"||!S.test(h[I]))||!v("diagnosis",r.qaEvidenceId,{claimId:i,epicId:e,sourceHead:r.sourceHead,admissionPatchSha256:r.admissionPatchSha256,artifactDigests:h}))throw new Error("planning-research-predecessor-invalid");const m={schemaVersion:r.schemaVersion,claimId:i,epicId:e,diagnosisReceiptId:a.receiptId,qaEvidenceId:r.qaEvidenceId,sourceHead:r.sourceHead,sourceStateSha256:r.sourceStateSha256,admissionPatchSha256:r.admissionPatchSha256,artifactDigests:h,...jn(r)};if(!b(r,{...m,receiptId:y(JSON.stringify(m)),publicSafe:!0}))throw new Error("planning-research-predecessor-invalid");return{intakeRevision:g,diagnosisReceiptId:a.receiptId,rawIntent:p.rawIntent}}function _n(n,i){const e=cn(n,i,!1),t=JSON.parse(E(n,".neocortex/state.json",8*1024*1024).toString("utf8")),c=(d(t)&&d(t.epics)?t.epics:void 0)?.[i.epicId],o=d(t)&&d(t.epic_id_ledger)?t.epic_id_ledger:void 0;if(!d(c)||!d(c.createEpicPlanning)||!d(c.createEpicPlanningClaim)||c.createEpicPlanningClaim.claimId!==i.claimId||c.createEpicPlanningClaim.epicId!==i.epicId||c.createEpicPlanning.epicId!==i.epicId||c.createEpicPlanning.intakeRevision!==e.checkpoint.intakeRevision||!b(c.createEpicPlanning.intake,e.checkpoint.intake)||!b(c.createEpicPlanning.diagnosisReceipt,e.checkpoint.diagnosisReceipt)||!b(c.createEpicPlanningPhysical,rn(i,e.receiptId))||!Array.isArray(o?.reserved_ids)||!o.reserved_ids.includes(i.epicId))throw new Error("planning-diagnosis-replay-conflict");return e.receiptId}function Cn(n,i,e={}){if(!d(i)||!d(i.admission))throw new Error("planning-diagnosis-review-invalid");const t={...i,qaEvidenceId:"qa-pending-record"};let s;try{s=W("diagnosis",tn(t))}catch{throw new Error("planning-diagnosis-review-invalid")}const c={...t,qaEvidenceId:s};sn(c,e.trustedKeys??V());const o=N(n);if(H(o)!==o||_(o,["rev-parse","--show-toplevel"])!==o)throw new Error("planning-diagnosis-root-invalid");return C(o,c),{epicId:c.epicId,qaEvidenceId:s}}function Kn(n,i,e={}){sn(i,e.trustedKeys??V());const t=i,s=N(n);if(H(s)!==s||_(s,["rev-parse","--show-toplevel"])!==s)throw new Error("planning-diagnosis-root-invalid");const c=u(s,".neocortex"),o=u(c,"state.json.planning.lock"),f=A(o,"wx",384);let r;try{const h=E(s,".neocortex/state.json",8388608);if(y(h)!==t.sourceStateSha256){const an=_n(s,t);return{epicId:t.epicId,diagnosisReceiptId:an,qaEvidenceId:t.qaEvidenceId}}const p=C(s,t),g=Q(p.state,{claimId:t.claimId,epicId:t.epicId,checkpoint:p.checkpoint});if(g===p.state)throw new Error("planning-diagnosis-already-sealed");const l=rn(t,p.receiptId),a=g.epics,m={...g,epics:{...a,[t.epicId]:{...a[t.epicId],createEpicPlanningPhysical:l}}},I=_(s,["rev-parse","--git-common-dir"]),k=mn(I)?N(I):N(s,I);if(H(k)!==k||w(k).isSymbolicLink())throw new Error("planning-diagnosis-backup-dir-invalid");const P=u(k,"neocortex-planning");ln(P,{recursive:!0,mode:448});const D=w(P);if(!D.isDirectory()||D.isSymbolicLink()||D.uid!==process.getuid?.()||(D.mode&63)!==0)throw new Error("planning-diagnosis-backup-dir-invalid");const x=gn(),O=A(u(P,`state-backup-${x}.json`),"wx",384);try{J(O,p.stateRaw),R(O)}finally{j(O)}const K=A(P,"r");try{R(K)}finally{j(K)}r=u(c,`state.json.planning-tmp-${x}`);const q=A(r,"wx",384);try{J(q,`${JSON.stringify(m,null,2)}
|
|
8
|
-
`),R(q)}finally{j(q)}if(!C(s,t,`.neocortex/state.json.planning-tmp-${x}`).stateRaw.equals(p.stateRaw))throw new Error("planning-diagnosis-state-conflict");hn(r,u(c,"state.json")),r=void 0;const z=A(c,"r");try{R(z)}finally{j(z)}return{epicId:t.epicId,diagnosisReceiptId:p.receiptId,qaEvidenceId:t.qaEvidenceId}}finally{if(r)try{G(r)}catch{}j(f),G(o)}}export{
|
|
6
|
+
`),c=o=>{const f=s.filter(r=>r.startsWith(`${o}:`));return f.length===1?f[0].slice(o.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0};return c("epic_id")===i&&c("status")==="completed"&&nn(c("step"),e)}function Cn(n){const i=u(n,".neocortex/pending-epic-claims.json");let e;try{e=w(i)}catch(c){if(c.code==="ENOENT")return;throw c}const t=w(u(n,".neocortex"));if(!t.isDirectory()||t.isSymbolicLink()||t.uid!==process.getuid?.()||(t.mode&18)!==0||!e.isFile()||e.isSymbolicLink()||e.uid!==process.getuid?.()||(e.mode&63)!==0||e.size<1||e.size>128*1024)throw new Error("planning-pending-sidecar-invalid");const s=L(i);if(s.length!==e.size)throw new Error("planning-pending-sidecar-invalid");return y(s)}function _n(n,i,e,t=!0){const s=new Set(Object.values(i)),c=new Set([".neocortex/state.json.planning.lock",...e?[e]:[]]),o=$("git",["status","--porcelain=v1","-z","--untracked-files=all"],{cwd:n,stdio:["ignore","pipe","ignore"],maxBuffer:128*1024}).toString("utf8").split("\0").filter(Boolean),f=yn(n,o),r=[],l=new Set;for(const h of f){const a=h.slice(0,2),g=h.slice(3);if(!(c.has(g)&&a==="??")){if(h[2]!==" "||!s.has(g)&&(!t||g!==".neocortex/pending-epic-claims.json")||g===".neocortex/pending-epic-claims.json"&&a!=="??"||g!==".neocortex/pending-epic-claims.json"&&a!=="??"&&a!==" M"||l.has(g))throw new Error("planning-diagnosis-write-scope-conflict");l.add(g),a==="??"&&s.has(g)&&r.push(g)}}if([...s].some(h=>!l.has(h)))throw new Error("planning-diagnosis-write-scope-conflict");const m=[$("git",["diff","--binary","--no-ext-diff","--no-textconv","HEAD","--"],{cwd:n,stdio:["ignore","pipe","ignore"],maxBuffer:2*1024*1024})];for(const h of r.sort()){const a=on("git",["diff","--no-index","--binary","--no-ext-diff","--","/dev/null",h],{cwd:n,encoding:"buffer",maxBuffer:2097152});if(a.status!==1||!Buffer.isBuffer(a.stdout))throw new Error("planning-diagnosis-patch-invalid");m.push(a.stdout)}return y(Buffer.concat(m.map(h=>Buffer.concat([h,Buffer.from(`
|
|
7
|
+
`)]))))}function tn(n){return{claimId:n.claimId,epicId:n.epicId,sourceHead:n.sourceHead,admissionPatchSha256:n.admission.patchSha256,artifactDigests:n.artifactDigests}}function sn(n,i){if(!d(n)||Object.keys(n).filter(e=>e!=="stepBinding").sort().join("|")!==["schemaVersion","verdict","claimId","epicId","logicalFingerprint","sourceHead","sourceBranch","sourceStateSha256","admission","artifactDigests","qaEvidenceId","intake","artifactSummary"].sort().join("|")||n.schemaVersion!=="PlanningDiagnosisRootReview/1"||n.verdict!=="accepted"||typeof n.claimId!="string"||!Sn.test(n.claimId)||typeof n.epicId!="string"||!In.test(n.epicId)||typeof n.logicalFingerprint!="string"||!S.test(n.logicalFingerprint)||typeof n.sourceHead!="string"||!/^[a-f0-9]{40}$/.test(n.sourceHead)||typeof n.sourceBranch!="string"||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]{0,127}$/.test(n.sourceBranch)||typeof n.sourceStateSha256!="string"||!S.test(n.sourceStateSha256)||!d(n.admission)||n.admission.schemaVersion!==1||n.admission.outcome!=="admitted-unverified"||n.admission.baseSha!==n.sourceHead||n.admission.executionBranch!==n.sourceBranch||typeof n.admission.patchSha256!="string"||!S.test(n.admission.patchSha256)||typeof n.qaEvidenceId!="string"||!/^qa-[a-z0-9-]{8,80}$/.test(n.qaEvidenceId)||!d(n.artifactDigests)||Object.keys(n.artifactDigests).sort().join("|")!==[...B].sort().join("|")||B.some(e=>typeof n.artifactDigests[e]!="string"||!S.test(n.artifactDigests[e])))throw new Error("planning-diagnosis-review-invalid");if(T({kind:"diagnosis",epicId:n.epicId,intakeRevision:Y(n.intake).intakeRevision,artifactSummary:n.artifactSummary,accepted:!0}),Dn(n.stepBinding,{stage:"P01",epicId:n.epicId,claimId:n.claimId,revision:wn(n.claimId),stepDigest:V},i),!v("diagnosis",n.qaEvidenceId,tn(n)))throw new Error("planning-diagnosis-qa-evidence-unbound")}function cn(n,i,e,t){if(_(n,["rev-parse","HEAD"])!==i.sourceHead||_(n,["symbolic-ref","--quiet","--short","HEAD"])!==i.sourceBranch)throw new Error("planning-diagnosis-head-conflict");const s=w(u(n,".neocortex")),c=w(u(n,".neocortex/pending-epic-claims.json"));if(!s.isDirectory()||s.isSymbolicLink()||(s.mode&18)!==0||!c.isFile()||c.isSymbolicLink()||c.uid!==process.getuid?.()||(c.mode&63)!==0)throw new Error("planning-diagnosis-claim-boundary-invalid");const o=JSON.parse(E(n,".neocortex/pending-epic-claims.json",128*1024).toString("utf8")),f=d(o)&&d(o.operations)?o.operations[i.logicalFingerprint]:void 0;if(!d(f)||f.claimId!==i.claimId||f.epicId!==i.epicId)throw new Error("planning-diagnosis-claim-conflict");const r=`.neocortex/planning/epic-${i.epicId}`,l={idea:`${r}/idea.json`,diagnosis:`${r}/diagnosis.md`,enrichment:`${r}/enriched-prompt.md`,index:".neocortex/planning/planning.json"};if(!Array.isArray(i.admission.changedPaths)||[...i.admission.changedPaths].sort().join("|")!==Object.values(l).sort().join("|")||e&&_n(n,l,t)!==i.admission.patchSha256)throw new Error("planning-diagnosis-admission-patch-conflict");const p={idea:E(n,l.idea,32*1024),diagnosis:E(n,l.diagnosis,256*1024),enrichment:E(n,l.enrichment,256*1024),index:E(n,l.index,128*1024)};for(const x of B)if(y(p[x])!==i.artifactDigests[x])throw new Error("planning-diagnosis-artifact-conflict");const m=JSON.parse(p.idea.toString("utf8")),h=JSON.parse(p.index.toString("utf8")),a=Y(i.intake).intake,g=d(h)&&d(h.epics)?h.epics[i.epicId]:void 0,I=d(g)?g.output_files:void 0;if(!d(m)||m.epic_id!==i.epicId||m.status!=="diagnosed"||m.raw_input!==a.rawIntent||!d(g)||g.id!==i.epicId||g.idea!==a.rawIntent||g.status!=="diagnosed"||!en(p.diagnosis.toString("utf8"),i.epicId,V)||!en(p.enrichment.toString("utf8"),i.epicId,En)||!Array.isArray(g.steps_completed)||g.steps_completed.length!==1||!nn(g.steps_completed[0],V)||!d(I)||!b(I,{diagnosis:l.diagnosis})||typeof g.created_at!="string"||!Number.isFinite(Date.parse(g.created_at))||g.completed_at!==null)throw new Error("planning-diagnosis-artifact-identity-conflict");if(typeof a.goal!="string"||!a.goal.trim()||typeof a.desiredOutcome!="string"||!a.desiredOutcome.trim()||!Array.isArray(a.users)||a.users.length===0||!Array.isArray(a.surfaces)||a.surfaces.length===0)throw new Error("planning-diagnosis-critical-intake-missing");const k=M(a),P=T({kind:"diagnosis",epicId:i.epicId,intakeRevision:k,artifactSummary:i.artifactSummary,accepted:!0});return{checkpoint:{schemaVersion:1,epicId:i.epicId,intake:a,intakeRevision:k,diagnosisReceipt:P},receiptId:P.receiptId}}function C(n,i,e){const t=cn(n,i,!0,e),s=E(n,".neocortex/state.json",8*1024*1024);if(y(s)!==i.sourceStateSha256)throw new Error("planning-diagnosis-state-conflict");const c=JSON.parse(s.toString("utf8"));if(!d(c)||d(c.scope)&&c.scope.kind==="projected")throw new Error("planning-diagnosis-state-invalid");return Q(c,{claimId:i.claimId,epicId:i.epicId,checkpoint:t.checkpoint}),{stateRaw:s,state:c,...t}}function rn(n,i){const e={schemaVersion:"PlanningDiagnosisPhysicalAcceptance/1",claimId:n.claimId,epicId:n.epicId,diagnosisReceiptId:i,qaEvidenceId:n.qaEvidenceId,sourceHead:n.sourceHead,sourceStateSha256:n.sourceStateSha256,admissionPatchSha256:n.admission.patchSha256,artifactDigests:n.artifactDigests,...jn(n.stepBinding)};return{...e,receiptId:y(JSON.stringify(e)),publicSafe:!0}}function Kn(n,i,e,t=!1){const s=d(n)?n:void 0,o=(s&&d(s.epics)?s.epics:void 0)?.[e];if(!d(o)||o.id!==e||o.source!=="create-epic"||o.status!=="diagnosed"&&!(t&&o.status==="researched")||!d(o.createEpicPlanningClaim)||o.createEpicPlanningClaim.claimId!==i||o.createEpicPlanningClaim.epicId!==e||!d(o.createEpicPlanning)||!d(o.createEpicPlanningPhysical))throw new Error("planning-research-predecessor-invalid");const f=o.createEpicPlanning,r=o.createEpicPlanningPhysical,l=d(r.artifactDigests)?r.artifactDigests:void 0,p=un(f.intake),m=M(p),h=s&&d(s.epic_id_ledger)?s.epic_id_ledger:void 0,a=d(f.diagnosisReceipt)?f.diagnosisReceipt:void 0;if(f.schemaVersion!==1||f.epicId!==e||f.intakeRevision!==m||!t&&f.researchReceipt!==void 0||typeof p.goal!="string"||!p.goal.trim()||typeof p.desiredOutcome!="string"||!p.desiredOutcome.trim()||typeof p.rawIntent!="string"||!p.rawIntent.trim()||!Array.isArray(p.users)||p.users.length===0||!Array.isArray(p.surfaces)||p.surfaces.length===0||!Array.isArray(h?.reserved_ids)||!h.reserved_ids.includes(e)||!a||a.kind!=="diagnosis"||a.epicId!==e||a.intakeRevision!==m||a.accepted!==!0||typeof a.artifactSummary!="string"||!b(a,T({kind:"diagnosis",epicId:e,intakeRevision:m,artifactSummary:a.artifactSummary,accepted:!0}))||r.schemaVersion!=="PlanningDiagnosisPhysicalAcceptance/1"||r.claimId!==i||r.epicId!==e||r.diagnosisReceiptId!==a.receiptId||typeof r.qaEvidenceId!="string"||!/^qa-[a-z0-9-]{8,80}$/.test(r.qaEvidenceId)||typeof r.sourceHead!="string"||!/^[a-f0-9]{40}$/.test(r.sourceHead)||typeof r.sourceStateSha256!="string"||!S.test(r.sourceStateSha256)||typeof r.admissionPatchSha256!="string"||!S.test(r.admissionPatchSha256)||!l||Object.keys(l).sort().join("|")!==[...B].sort().join("|")||B.some(I=>typeof l[I]!="string"||!S.test(l[I]))||!v("diagnosis",r.qaEvidenceId,{claimId:i,epicId:e,sourceHead:r.sourceHead,admissionPatchSha256:r.admissionPatchSha256,artifactDigests:l}))throw new Error("planning-research-predecessor-invalid");const g={schemaVersion:r.schemaVersion,claimId:i,epicId:e,diagnosisReceiptId:a.receiptId,qaEvidenceId:r.qaEvidenceId,sourceHead:r.sourceHead,sourceStateSha256:r.sourceStateSha256,admissionPatchSha256:r.admissionPatchSha256,artifactDigests:l,...An(r)};if(!b(r,{...g,receiptId:y(JSON.stringify(g)),publicSafe:!0}))throw new Error("planning-research-predecessor-invalid");return{intakeRevision:m,diagnosisReceiptId:a.receiptId,rawIntent:p.rawIntent}}function Rn(n,i){const e=cn(n,i,!1),t=JSON.parse(E(n,".neocortex/state.json",8*1024*1024).toString("utf8")),c=(d(t)&&d(t.epics)?t.epics:void 0)?.[i.epicId],o=d(t)&&d(t.epic_id_ledger)?t.epic_id_ledger:void 0;if(!d(c)||!d(c.createEpicPlanning)||!d(c.createEpicPlanningClaim)||c.createEpicPlanningClaim.claimId!==i.claimId||c.createEpicPlanningClaim.epicId!==i.epicId||c.createEpicPlanning.epicId!==i.epicId||c.createEpicPlanning.intakeRevision!==e.checkpoint.intakeRevision||!b(c.createEpicPlanning.intake,e.checkpoint.intake)||!b(c.createEpicPlanning.diagnosisReceipt,e.checkpoint.diagnosisReceipt)||!b(c.createEpicPlanningPhysical,rn(i,e.receiptId))||!Array.isArray(o?.reserved_ids)||!o.reserved_ids.includes(i.epicId))throw new Error("planning-diagnosis-replay-conflict");return e.receiptId}function zn(n,i,e={}){if(!d(i)||!d(i.admission))throw new Error("planning-diagnosis-review-invalid");const t={...i,qaEvidenceId:"qa-pending-record"};let s;try{s=W("diagnosis",tn(t))}catch{throw new Error("planning-diagnosis-review-invalid")}const c={...t,qaEvidenceId:s};sn(c,e.trustedKeys??F());const o=N(n);if(H(o)!==o||_(o,["rev-parse","--show-toplevel"])!==o)throw new Error("planning-diagnosis-root-invalid");return C(o,c),{epicId:c.epicId,qaEvidenceId:s}}function Ln(n,i,e={}){sn(i,e.trustedKeys??F());const t=i,s=N(n);if(H(s)!==s||_(s,["rev-parse","--show-toplevel"])!==s)throw new Error("planning-diagnosis-root-invalid");const c=u(s,".neocortex"),o=u(c,"state.json.planning.lock"),f=A(o,"wx",384);let r;try{const l=E(s,".neocortex/state.json",8388608);if(y(l)!==t.sourceStateSha256){const an=Rn(s,t);return{epicId:t.epicId,diagnosisReceiptId:an,qaEvidenceId:t.qaEvidenceId}}const p=C(s,t),m=Q(p.state,{claimId:t.claimId,epicId:t.epicId,checkpoint:p.checkpoint});if(m===p.state)throw new Error("planning-diagnosis-already-sealed");const h=rn(t,p.receiptId),a=m.epics,g={...m,epics:{...a,[t.epicId]:{...a[t.epicId],createEpicPlanningPhysical:h}}},I=_(s,["rev-parse","--git-common-dir"]),k=mn(I)?N(I):N(s,I);if(H(k)!==k||w(k).isSymbolicLink())throw new Error("planning-diagnosis-backup-dir-invalid");const P=u(k,"neocortex-planning");ln(P,{recursive:!0,mode:448});const D=w(P);if(!D.isDirectory()||D.isSymbolicLink()||D.uid!==process.getuid?.()||(D.mode&63)!==0)throw new Error("planning-diagnosis-backup-dir-invalid");const x=gn(),O=A(u(P,`state-backup-${x}.json`),"wx",384);try{J(O,p.stateRaw),R(O)}finally{j(O)}const K=A(P,"r");try{R(K)}finally{j(K)}r=u(c,`state.json.planning-tmp-${x}`);const q=A(r,"wx",384);try{J(q,`${JSON.stringify(g,null,2)}
|
|
8
|
+
`),R(q)}finally{j(q)}if(!C(s,t,`.neocortex/state.json.planning-tmp-${x}`).stateRaw.equals(p.stateRaw))throw new Error("planning-diagnosis-state-conflict");hn(r,u(c,"state.json")),r=void 0;const z=A(c,"r");try{R(z)}finally{j(z)}return{epicId:t.epicId,diagnosisReceiptId:p.receiptId,qaEvidenceId:t.qaEvidenceId}}finally{if(r)try{G(r)}catch{}j(f),G(o)}}export{kn as PLANNING_STEP_BINDING_PRODUCTION_KEYS,Kn as acceptedPlanningDiagnosisPredecessor,Dn as enforcePlanningStepBinding,Cn as planningPendingSidecarDigest,_n as planningPhysicalPatchDigest,v as planningQaEvidenceBound,W as planningQaEvidenceId,jn as planningStepBindingAcceptanceField,wn as planningStepBindingP01Revision,An as planningStepBindingReceiptField,F as planningStepBindingTrustedKeys,zn as recordPlanningDiagnosisQaEvidence,Ln as sealPlanningDiagnosis,Fn as setPlanningStepBindingTrustedKeysForTesting,bn as verifyPlanningStepBinding};
|