@ornexus/neocortex 4.60.61 → 4.60.63

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/dist/release-source.json +1 -0
  2. package/dist/sbom.cdx.json +196 -66
  3. package/install.ps1 +1 -1
  4. package/install.sh +1 -1
  5. package/package.json +13 -6
  6. package/packages/client/dist/cli.js +52 -2
  7. package/packages/client/dist/commands/invoke.d.ts +1 -0
  8. package/packages/client/dist/commands/invoke.js +81 -72
  9. package/packages/client/dist/commands/legacy-epic-terminal.d.ts +9 -0
  10. package/packages/client/dist/commands/legacy-epic-terminal.js +1 -0
  11. package/packages/client/dist/commands/legacy-story-pr.d.ts +2 -1
  12. package/packages/client/dist/commands/legacy-story-pr.js +1 -1
  13. package/packages/client/dist/commands/mutation-qa-checkpoint.d.ts +39 -0
  14. package/packages/client/dist/commands/mutation-qa-checkpoint.js +5 -0
  15. package/packages/client/dist/commands/mutation-qa-gate.d.ts +35 -0
  16. package/packages/client/dist/commands/mutation-qa-gate.js +1 -0
  17. package/packages/client/dist/commands/mutation-qa-git.d.ts +2 -0
  18. package/packages/client/dist/commands/mutation-qa-git.js +1 -0
  19. package/packages/client/dist/commands/mutation-qa-policy.d.ts +15 -0
  20. package/packages/client/dist/commands/mutation-qa-policy.js +1 -0
  21. package/packages/client/dist/commands/mutation-qa-run.d.ts +14 -0
  22. package/packages/client/dist/commands/mutation-qa-run.js +3 -0
  23. package/packages/client/dist/commands/mutation-qa-verdict.d.ts +21 -0
  24. package/packages/client/dist/commands/mutation-qa-verdict.js +1 -0
  25. package/packages/client/dist/commands/mutation-qa.d.ts +22 -0
  26. package/packages/client/dist/commands/mutation-qa.js +1 -0
  27. package/packages/client/dist/commands/property-qa.d.ts +1 -0
  28. package/packages/client/dist/commands/property-qa.js +1 -0
  29. package/packages/client/dist/commands/qa-scan-capture.d.ts +52 -0
  30. package/packages/client/dist/commands/qa-scan-capture.js +11 -0
  31. package/packages/client/dist/commands/qa-scan-discovery.d.ts +36 -0
  32. package/packages/client/dist/commands/qa-scan-discovery.js +3 -0
  33. package/packages/client/dist/commands/qa-scan-review.d.ts +119 -0
  34. package/packages/client/dist/commands/qa-scan-review.js +5 -0
  35. package/packages/client/dist/commands/refactor-characterization.d.ts +47 -0
  36. package/packages/client/dist/commands/refactor-characterization.js +12 -0
  37. package/packages/client/dist/commands/refactor-commit.d.ts +45 -0
  38. package/packages/client/dist/commands/refactor-commit.js +13 -0
  39. package/packages/client/dist/commands/refactor-review.d.ts +37 -0
  40. package/packages/client/dist/commands/refactor-review.js +5 -0
  41. package/packages/client/dist/commands/refactor-root.d.ts +85 -0
  42. package/packages/client/dist/commands/refactor-root.js +7 -0
  43. package/packages/client/dist/generated/command-registry.generated.d.ts +9 -9
  44. package/packages/client/dist/generated/command-registry.generated.js +1 -1
  45. package/packages/client/dist/generated/public-projections.generated.d.ts +20 -20
  46. package/packages/client/dist/generated/public-projections.generated.js +1 -1
  47. package/packages/client/dist/git/legacy-story-pr.d.ts +137 -6
  48. package/packages/client/dist/git/legacy-story-pr.js +51 -43
  49. package/packages/client/dist/license/license-client.js +1 -1
  50. package/packages/client/dist/package.json +1 -0
  51. package/packages/client/dist/private-execution/clean-baseline.d.ts +1 -0
  52. package/packages/client/dist/private-execution/clean-baseline.js +2 -2
  53. package/packages/client/dist/private-execution/delivery.d.ts +49 -4
  54. package/packages/client/dist/private-execution/delivery.js +4 -2
  55. package/packages/client/dist/private-execution/isolated-admission.d.ts +7 -0
  56. package/packages/client/dist/private-execution/isolated-admission.js +10 -10
  57. package/packages/client/dist/private-execution/isolated-session.js +2 -2
  58. package/packages/client/dist/private-execution/private-report-store.d.ts +17 -0
  59. package/packages/client/dist/private-execution/private-report-store.js +1 -0
  60. package/packages/client/dist/private-execution/property-test-candidate.d.ts +14 -0
  61. package/packages/client/dist/private-execution/property-test-candidate.js +1 -0
  62. package/packages/client/dist/private-execution/property-test-choices.d.ts +15 -0
  63. package/packages/client/dist/private-execution/property-test-choices.js +3 -0
  64. package/packages/client/dist/private-execution/property-test-plan.d.ts +65 -0
  65. package/packages/client/dist/private-execution/property-test-plan.js +7 -0
  66. package/packages/client/dist/private-execution/property-test-review.d.ts +58 -0
  67. package/packages/client/dist/private-execution/property-test-review.js +4 -0
  68. package/packages/client/dist/private-execution/property-test-runtime.d.ts +18 -0
  69. package/packages/client/dist/private-execution/property-test-runtime.js +9 -0
  70. package/packages/client/dist/private-execution/property-test-source.d.ts +8 -0
  71. package/packages/client/dist/private-execution/property-test-source.js +1 -0
  72. package/packages/client/dist/state/project-state-snapshot.js +1 -1
  73. package/packages/shared/dist/generated/command-registry.generated.js +9 -9
  74. package/packages/shared/dist/generated/invocation-schema.generated.js +2 -2
  75. package/packages/shared/dist/generated/public-projections.generated.js +18 -18
  76. package/packages/shared/dist/invocation/index.d.ts +1 -1
  77. package/packages/shared/dist/invocation/index.js +13 -0
  78. package/packages/shared/dist/merge-readiness/c12-registry-projection.js +111 -0
  79. package/packages/shared/dist/merge-readiness/c12-remote-observation.js +60 -0
  80. package/packages/shared/dist/package.json +1 -0
  81. package/targets-stubs/antigravity/gemini.md +1 -1
  82. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  83. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  84. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  85. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  86. package/targets-stubs/claude-code/neocortex.md +2 -2
  87. package/targets-stubs/codex/AGENTS.md +1 -1
  88. package/targets-stubs/cursor/agent.md +2 -2
  89. package/targets-stubs/gemini-cli/agent.md +2 -2
  90. package/targets-stubs/opencode/neocortex-root.md +1 -1
  91. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1 +1 @@
1
- import{decodeJwt as h}from"jose";import{NoOpCache as c}from"../types/index.js";import{getMachineFingerprint as o}from"../machine/fingerprint.js";const i="neocortex:jwt:token",s="neocortex:jwt:refresh_token",l=300,a=10080*60*1e3,u="0.1.0";class T{serverUrl;licenseKey;cache;clientVersion;machineId;strictReadOnly;token=null;refreshToken=null;constructor(e){this.serverUrl=e.serverUrl.replace(/\/+$/,""),this.licenseKey=e.licenseKey,this.cache=e.cacheProvider??new c,this.clientVersion=e.clientVersion??u,this.strictReadOnly=e.strictReadOnly??!1,this.machineId=o({strictReadOnly:this.strictReadOnly})}async getToken(){try{if(this.strictReadOnly){const r=await this.inspectToken();return r.status==="authenticated"?r.token:null}if(this.token){const r=this.checkTokenValidity(this.token);if(r==="valid")return this.token;if(r==="needs-refresh")return this.strictReadOnly?this.token:(await this.refresh())?.token??this.token;this.token=null}const e=await this.loadFromCache();if(e){this.token=e;const r=this.checkTokenValidity(e);if(r==="valid")return e;if(r==="needs-refresh")return this.strictReadOnly?e:(await this.refresh())?.token??e;this.token=null}if(this.strictReadOnly)return null;if(this.refreshToken||(this.refreshToken=await this.loadRefreshTokenFromCache()),this.refreshToken){const r=await this.refresh();if(r?.token)return r.token}return(await this.activate())?.token??null}catch{return null}}async inspectToken(){try{const e=this.token??await this.loadFromCache();if(e){const t=this.checkTokenValidity(e);return t==="valid"?{status:"authenticated",token:e}:{status:"refresh-required",reason:t==="needs-refresh"?"near-expiry":"expired"}}return this.licenseKey?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"}}catch{return this.licenseKey?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"}}}async activate(){if(this.strictReadOnly)return null;try{const e=await fetch(`${this.serverUrl}/api/v1/license/activate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:this.licenseKey,machine_id:this.machineId,client_version:this.clientVersion})});if(!e.ok)return null;const t=await e.json();return this.token=t.token,this.refreshToken=t.refresh_token??null,await this.cache.set(i,t.token,t.expires_in*1e3).catch(()=>{}),t.refresh_token&&await this.cache.set(s,t.refresh_token,a).catch(()=>{}),{token:t.token,expiresIn:t.expires_in,refreshToken:t.refresh_token}}catch{return null}}async refresh(e){if(this.strictReadOnly)return null;try{const t=this.refreshToken??await this.loadRefreshTokenFromCache();if(!t)return null;const r=await fetch(`${this.serverUrl}/api/v1/license/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:t})});if(!r.ok)return this.refreshToken=null,await this.cache.set(s,"",1).catch(()=>{}),null;const n=await r.json();return this.token=n.token,this.refreshToken=n.refresh_token??null,await this.cache.set(i,n.token,n.expires_in*1e3).catch(()=>{}),n.refresh_token&&await this.cache.set(s,n.refresh_token,a).catch(()=>{}),{token:n.token,expiresIn:n.expires_in,refreshToken:n.refresh_token}}catch{return null}}async forceRefresh(){if(this.strictReadOnly)return null;try{const e=await this.refresh();return e?.token?e.token:(this.token=null,this.refreshToken=null,await this.cache.clear().catch(()=>{}),(await this.activate())?.token??null)}catch{return null}}checkTokenValidity(e){try{const t=h(e);if(!t.exp)return"expired";const r=Math.floor(Date.now()/1e3);return t.exp<=r?"expired":t.exp-r<=l?"needs-refresh":"valid"}catch{return"expired"}}async loadFromCache(){try{return await this.cache.get(i)}catch{return null}}async loadRefreshTokenFromCache(){try{const e=await this.cache.get(s);return e&&e.length>0?e:null}catch{return null}}}export{T as LicenseClient};
1
+ import{decodeJwt as h}from"jose";import{NoOpCache as c}from"../types/index.js";import{getMachineFingerprint as o}from"../machine/fingerprint.js";import{CLIENT_VERSION as l}from"../version.js";const i="neocortex:jwt:token",s="neocortex:jwt:refresh_token",u=300,a=10080*60*1e3;class T{serverUrl;licenseKey;cache;clientVersion;machineId;strictReadOnly;token=null;refreshToken=null;constructor(e){this.serverUrl=e.serverUrl.replace(/\/+$/,""),this.licenseKey=e.licenseKey,this.cache=e.cacheProvider??new c,this.clientVersion=e.clientVersion??l,this.strictReadOnly=e.strictReadOnly??!1,this.machineId=o({strictReadOnly:this.strictReadOnly})}async getToken(){try{if(this.strictReadOnly){const r=await this.inspectToken();return r.status==="authenticated"?r.token:null}if(this.token){const r=this.checkTokenValidity(this.token);if(r==="valid")return this.token;if(r==="needs-refresh")return this.strictReadOnly?this.token:(await this.refresh())?.token??this.token;this.token=null}const e=await this.loadFromCache();if(e){this.token=e;const r=this.checkTokenValidity(e);if(r==="valid")return e;if(r==="needs-refresh")return this.strictReadOnly?e:(await this.refresh())?.token??e;this.token=null}if(this.strictReadOnly)return null;if(this.refreshToken||(this.refreshToken=await this.loadRefreshTokenFromCache()),this.refreshToken){const r=await this.refresh();if(r?.token)return r.token}return(await this.activate())?.token??null}catch{return null}}async inspectToken(){try{const e=this.token??await this.loadFromCache();if(e){const t=this.checkTokenValidity(e);return t==="valid"?{status:"authenticated",token:e}:{status:"refresh-required",reason:t==="needs-refresh"?"near-expiry":"expired"}}return this.licenseKey?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"}}catch{return this.licenseKey?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"}}}async activate(){if(this.strictReadOnly)return null;try{const e=await fetch(`${this.serverUrl}/api/v1/license/activate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:this.licenseKey,machine_id:this.machineId,client_version:this.clientVersion})});if(!e.ok)return null;const t=await e.json();return this.token=t.token,this.refreshToken=t.refresh_token??null,await this.cache.set(i,t.token,t.expires_in*1e3).catch(()=>{}),t.refresh_token&&await this.cache.set(s,t.refresh_token,a).catch(()=>{}),{token:t.token,expiresIn:t.expires_in,refreshToken:t.refresh_token}}catch{return null}}async refresh(e){if(this.strictReadOnly)return null;try{const t=this.refreshToken??await this.loadRefreshTokenFromCache();if(!t)return null;const r=await fetch(`${this.serverUrl}/api/v1/license/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:t})});if(!r.ok)return this.refreshToken=null,await this.cache.set(s,"",1).catch(()=>{}),null;const n=await r.json();return this.token=n.token,this.refreshToken=n.refresh_token??null,await this.cache.set(i,n.token,n.expires_in*1e3).catch(()=>{}),n.refresh_token&&await this.cache.set(s,n.refresh_token,a).catch(()=>{}),{token:n.token,expiresIn:n.expires_in,refreshToken:n.refresh_token}}catch{return null}}async forceRefresh(){if(this.strictReadOnly)return null;try{const e=await this.refresh();return e?.token?e.token:(this.token=null,this.refreshToken=null,await this.cache.clear().catch(()=>{}),(await this.activate())?.token??null)}catch{return null}}checkTokenValidity(e){try{const t=h(e);if(!t.exp)return"expired";const r=Math.floor(Date.now()/1e3);return t.exp<=r?"expired":t.exp-r<=u?"needs-refresh":"valid"}catch{return"expired"}}async loadFromCache(){try{return await this.cache.get(i)}catch{return null}}async loadRefreshTokenFromCache(){try{const e=await this.cache.get(s);return e&&e.length>0?e:null}catch{return null}}}export{T as LicenseClient};
@@ -0,0 +1 @@
1
+ {"type":"module"}
@@ -1,4 +1,5 @@
1
1
  import type { DirectYoloSetupReceipt } from '../git/direct-yolo-checkpoint.js';
2
+ export declare function privateYoloRootOnlySetupReady(story: unknown): boolean;
2
3
  /** Call immediately before root C01 setup; a dirty or ambiguous checkout fails closed. */
3
4
  export declare function capturePrivateYoloCleanHead(projectRoot: string): string;
4
5
  /** Persist only after physical setup succeeded without changing the clean HEAD. */
@@ -1,2 +1,2 @@
1
- import{execFileSync as j}from"node:child_process";import{createHash as y}from"node:crypto";import{existsSync as D,lstatSync as W,readFileSync as w}from"node:fs";import{join as v,resolve as f}from"node:path";import{assertGitLifecyclePrivateFile as S,ensureGitLifecyclePrivateChildDirectory as x,gitLifecycleRuntimeDirectory as E,readGitLifecycleRuntimeSync as g}from"../git/git-lifecycle-store.js";import{anchoredAtomicWriteFile as z}from"../git/secure-filesystem-boundary.js";function d(i,e){const t=JSON.parse(i);if(!t||typeof t!="object"||Array.isArray(t))throw new Error("private-execution-clean-baseline-write-set-invalid");const r=t.stories,o=r&&typeof r=="object"&&!Array.isArray(r)?r[e]:void 0,n=o&&typeof o=="object"&&!Array.isArray(o)?o.files_to_modify:void 0;if(n!==void 0&&(!Array.isArray(n)||n.length>1024||n.some(c=>typeof c!="string"||c.length===0||c.length>1024||c.startsWith("/")||c.includes("\\")||c.includes("\0")||c.startsWith(".git/")||c.split("/").includes(".."))))throw new Error("private-execution-clean-baseline-write-set-invalid");if(!o)throw new Error("private-execution-clean-baseline-write-set-invalid");return[...new Set(n??[])].sort()}function m(i,e){const t=d(i,e);return y("sha256").update("private-yolo-authorized-write-set-v1\0").update(JSON.stringify(t)).digest("hex")}function I(i,e){const t=v(i,".neocortex","state.json"),r=W(t);if(!r.isFile()||r.isSymbolicLink())throw new Error("private-execution-clean-baseline-write-set-invalid");return m(w(t,"utf8"),e)}function b(i,e){return m(p(i,["show","HEAD:.neocortex/state.json"],16*1024*1024).toString("utf8"),e)}function p(i,e,t=1024*1024){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 j("git",[...e],{cwd:i,env:r,stdio:["ignore","pipe","pipe"],timeout:15e3,maxBuffer:t})}function l(i){return p(i,["rev-parse","HEAD"]).toString("utf8").trim()}function A(i){return p(i,["symbolic-ref","--quiet","--short","HEAD"]).toString("utf8").trim()}function _(i,e,t){const o=g(i,{required:!0}).epics[e]?.branch_lease,n=o&&typeof o=="object"&&!Array.isArray(o)?o:void 0,c=n?.ownerStoryId===t?n.sessionId:void 0;if(typeof c!="string"||!/^setup-[a-f0-9]{64}$/.test(c)||c!==n?.idempotencyKey||typeof n?.expiresAt!="string"||!Number.isFinite(Date.parse(n.expiresAt))||Date.parse(n.expiresAt)<=Date.now())throw new Error("private-execution-clean-baseline-lease-invalid");return c}async function R(i,e){const t=await E(i),r=await x(t,"private-execution"),o=`baseline-${y("sha256").update(e).digest("hex")}.json`;return{parent:r,name:o,path:v(r,o)}}async function O(i,e,t,r){try{const o=await E(i),n=await x(o,"private-execution"),c=`session-${y("sha256").update(e).digest("hex")}.json`,h=v(n,c);if(!D(h))return!1;await S(h,n);const s=JSON.parse(w(h,"utf8"));if(!s||typeof s!="object"||Array.isArray(s))return!1;const a=s,u=a.workspace&&typeof a.workspace=="object"&&!Array.isArray(a.workspace)?a.workspace:void 0;return a.schemaVersion===1&&a.kind==="private-yolo-isolated-session"&&a.storyId===e&&a.initialGraphRevision===t.graphRevision&&a.graphRevision===r&&a.setupSessionId===t.setupSessionId&&Array.isArray(a.graphHistory)&&a.graphHistory.length>1&&a.graphHistory.length<=65&&a.graphHistory[0]===t.graphRevision&&a.graphHistory[a.graphHistory.length-1]===r&&new Set(a.graphHistory).size===a.graphHistory.length&&Number.isSafeInteger(a.sequence)&&Number(a.sequence)>0&&typeof a.snapshotSha=="string"&&/^[a-f0-9]{40,64}$/.test(a.snapshotSha)&&u?.sourceRoot===i&&u.baseSha===t.headSha&&u.executionBranch===t.executionBranch}catch{return!1}}function L(i){const e=f(i);try{const t=l(e);if(p(e,["status","--porcelain=v1","-z","--untracked-files=all"]).byteLength!==0)throw new Error("private-execution-checkout-dirty");if(l(e)!==t)throw new Error("private-execution-checkout-raced");return t}catch(t){throw t instanceof Error&&/^private-execution-[a-z-]+$/.test(t.message)?t:new Error("private-execution-checkout-unverified")}}async function $(i,e,t){const r=f(i);if(!/^[a-f0-9]{40,64}$/.test(t)||e.kind!=="direct-yolo-setup-receipt"||e.originHeadSha!==t||l(r)!==t||A(r)!==e.executionBranch||p(r,["status","--porcelain=v1","-z","--untracked-files=all"]).byteLength!==0)throw new Error("private-execution-clean-baseline-raced");const o=b(r,e.storyId);if(o!==I(r,e.storyId)||l(r)!==t)throw new Error("private-execution-clean-baseline-raced");const n=g(r,{required:!0}).epics[e.epicId]?.graph_revision;if(typeof n!="string"||!/^[a-f0-9]{64}$/.test(n))throw new Error("private-execution-clean-baseline-graph-invalid");const c=Object.freeze({schemaVersion:3,kind:"private-yolo-clean-baseline",storyId:e.storyId,epicId:e.epicId,executionBranch:e.executionBranch,headSha:t,setupSessionId:_(r,e.epicId,e.storyId),graphRevision:n,authorizedWriteSetSha256:o}),h=await R(r,e.storyId);await z(h.parent,h.name,`${JSON.stringify(c)}
2
- `)}async function k(i,e,t,r,o){const n=f(i);try{const c=await R(n,e);await S(c.path,c.parent);const h=JSON.parse(w(c.path,"utf8"));if(!h||typeof h!="object"||Array.isArray(h))throw new Error("private-execution-clean-baseline-invalid");const s=h,a=g(n,{required:!0}).epics[s.epicId]?.graph_revision,u=a===s.graphRevision||o===s.graphRevision&&a===r||typeof a=="string"&&await O(n,e,s,a);if(Object.keys(s).sort().join(",")!==["schemaVersion","kind","storyId","epicId","executionBranch","headSha","setupSessionId","graphRevision","authorizedWriteSetSha256"].sort().join(",")||s.schemaVersion!==3||s.kind!=="private-yolo-clean-baseline"||s.storyId!==e||s.executionBranch!==t||s.epicId!==e.split(".")[0]||typeof s.headSha!="string"||!/^[a-f0-9]{40,64}$/.test(s.headSha)||typeof s.authorizedWriteSetSha256!="string"||!/^[a-f0-9]{64}$/.test(s.authorizedWriteSetSha256)||typeof s.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(s.graphRevision)||r!==void 0&&a!==r||!u||s.authorizedWriteSetSha256!==b(n,e)||s.authorizedWriteSetSha256!==I(n,e)||s.setupSessionId!==_(n,s.epicId,e)||l(n)!==s.headSha||A(n)!==t)throw new Error("private-execution-clean-baseline-invalid")}catch{throw new Error("private-execution-clean-baseline-unverified")}}async function T(i,e,t,r){return k(i,e,t,r)}async function P(i,e,t,r){await T(i,e,t,r);try{const o=d(p(f(i),["show","HEAD:.neocortex/state.json"],16777216).toString("utf8"),e);if(o.length===0)throw new Error("write-set-empty");return Object.freeze([...o])}catch{throw new Error("private-execution-clean-baseline-unverified")}}async function Y(i,e,t,r,o){await k(i,e,t,o,r);try{const n=d(p(f(i),["show","HEAD:.neocortex/state.json"],16777216).toString("utf8"),e);if(n.length===0)throw new Error("write-set-empty");return Object.freeze([...n])}catch{throw new Error("private-execution-clean-baseline-unverified")}}function J(i,e,t){try{const r=d(i,e);if(r.length!==t.length||r.some((o,n)=>o!==t[n]))throw new Error("write-set-drift")}catch{throw new Error("private-execution-clean-baseline-write-set-unverified")}}export{L as capturePrivateYoloCleanHead,P as readPrivateYoloFrozenWriteSet,Y as readPrivateYoloFrozenWriteSetForTransition,$ as recordPrivateYoloCleanBaseline,J as verifyPrivateYoloCandidateWriteSet,T as verifyPrivateYoloCleanBaseline};
1
+ import{execFileSync as D}from"node:child_process";import{createHash as d}from"node:crypto";import{existsSync as W,lstatSync as z,readFileSync as g}from"node:fs";import{join as v,resolve as l}from"node:path";import{assertGitLifecyclePrivateFile as x,ensureGitLifecyclePrivateChildDirectory as E,gitLifecycleRuntimeDirectory as b,readGitLifecycleRuntimeSync as y}from"../git/git-lifecycle-store.js";import{anchoredAtomicWriteFile as H}from"../git/secure-filesystem-boundary.js";const C="809db253d486b5d2620d318666219e8a2b4df05016174ba3c8a33fa17b65802a";function N(r){if(!r||typeof r!="object"||Array.isArray(r))return!1;const e=r,t=e.steps_completed;return e.status!=="branch-ready"||typeof e.last_step!="string"||!Array.isArray(t)||t.length!==1||typeof t[0]!="string"||e.last_step.length>128||t[0].length>128||e.last_step!==t[0]?!1:d("sha256").update(e.last_step).digest("hex")===C}function w(r,e){const t=JSON.parse(r);if(!t||typeof t!="object"||Array.isArray(t))throw new Error("private-execution-clean-baseline-write-set-invalid");const i=t.stories,a=i&&typeof i=="object"&&!Array.isArray(i)?i[e]:void 0,n=a&&typeof a=="object"&&!Array.isArray(a)?a.files_to_modify:void 0;if(n!==void 0&&(!Array.isArray(n)||n.length>1024||n.some(c=>typeof c!="string"||c.length===0||c.length>1024||c.startsWith("/")||c.includes("\\")||c.includes("\0")||c.startsWith(".git/")||c.split("/").includes(".."))))throw new Error("private-execution-clean-baseline-write-set-invalid");if(!a)throw new Error("private-execution-clean-baseline-write-set-invalid");return[...new Set(n??[])].sort()}function m(r,e){const t=w(r,e);return d("sha256").update("private-yolo-authorized-write-set-v1\0").update(JSON.stringify(t)).digest("hex")}function A(r,e){const t=v(r,".neocortex","state.json"),i=z(t);if(!i.isFile()||i.isSymbolicLink())throw new Error("private-execution-clean-baseline-write-set-invalid");return m(g(t,"utf8"),e)}function I(r,e){return m(p(r,["show","HEAD:.neocortex/state.json"],16*1024*1024).toString("utf8"),e)}function p(r,e,t=1024*1024){const i={...process.env};for(const a 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 i[a];return D("git",[...e],{cwd:r,env:i,stdio:["ignore","pipe","pipe"],timeout:15e3,maxBuffer:t})}function f(r){return p(r,["rev-parse","HEAD"]).toString("utf8").trim()}function _(r){return p(r,["symbolic-ref","--quiet","--short","HEAD"]).toString("utf8").trim()}function R(r,e,t){const a=y(r,{required:!0}).epics[e]?.branch_lease,n=a&&typeof a=="object"&&!Array.isArray(a)?a:void 0,c=n?.ownerStoryId===t?n.sessionId:void 0;if(typeof c!="string"||!/^setup-[a-f0-9]{64}$/.test(c)||c!==n?.idempotencyKey||typeof n?.expiresAt!="string"||!Number.isFinite(Date.parse(n.expiresAt))||Date.parse(n.expiresAt)<=Date.now())throw new Error("private-execution-clean-baseline-lease-invalid");return c}async function O(r,e){const t=await b(r),i=await E(t,"private-execution"),a=`baseline-${d("sha256").update(e).digest("hex")}.json`;return{parent:i,name:a,path:v(i,a)}}async function G(r,e,t,i){try{const a=await b(r),n=await E(a,"private-execution"),c=`session-${d("sha256").update(e).digest("hex")}.json`,h=v(n,c);if(!W(h))return!1;await x(h,n);const s=JSON.parse(g(h,"utf8"));if(!s||typeof s!="object"||Array.isArray(s))return!1;const o=s,u=o.workspace&&typeof o.workspace=="object"&&!Array.isArray(o.workspace)?o.workspace:void 0,S=Number(o.sequence),j=y(r,{required:!0}).stories[e],k=S===0&&o.lastPatchSha256===null&&o.snapshotSha===u?.baseSha&&Array.isArray(o.graphHistory)&&o.graphHistory.length===2&&N(j);return o.schemaVersion===1&&o.kind==="private-yolo-isolated-session"&&o.storyId===e&&o.initialGraphRevision===t.graphRevision&&o.graphRevision===i&&o.setupSessionId===t.setupSessionId&&Array.isArray(o.graphHistory)&&o.graphHistory.length>1&&o.graphHistory.length<=65&&o.graphHistory[0]===t.graphRevision&&o.graphHistory[o.graphHistory.length-1]===i&&new Set(o.graphHistory).size===o.graphHistory.length&&Number.isSafeInteger(o.sequence)&&(S>0||k)&&typeof o.snapshotSha=="string"&&/^[a-f0-9]{40,64}$/.test(o.snapshotSha)&&u?.sourceRoot===r&&u.baseSha===t.headSha&&u.executionBranch===t.executionBranch}catch{return!1}}function J(r){const e=l(r);try{const t=f(e);if(p(e,["status","--porcelain=v1","-z","--untracked-files=all"]).byteLength!==0)throw new Error("private-execution-checkout-dirty");if(f(e)!==t)throw new Error("private-execution-checkout-raced");return t}catch(t){throw t instanceof Error&&/^private-execution-[a-z-]+$/.test(t.message)?t:new Error("private-execution-checkout-unverified")}}async function M(r,e,t){const i=l(r);if(!/^[a-f0-9]{40,64}$/.test(t)||e.kind!=="direct-yolo-setup-receipt"||e.originHeadSha!==t||f(i)!==t||_(i)!==e.executionBranch||p(i,["status","--porcelain=v1","-z","--untracked-files=all"]).byteLength!==0)throw new Error("private-execution-clean-baseline-raced");const a=I(i,e.storyId);if(a!==A(i,e.storyId)||f(i)!==t)throw new Error("private-execution-clean-baseline-raced");const n=y(i,{required:!0}).epics[e.epicId]?.graph_revision;if(typeof n!="string"||!/^[a-f0-9]{64}$/.test(n))throw new Error("private-execution-clean-baseline-graph-invalid");const c=Object.freeze({schemaVersion:3,kind:"private-yolo-clean-baseline",storyId:e.storyId,epicId:e.epicId,executionBranch:e.executionBranch,headSha:t,setupSessionId:R(i,e.epicId,e.storyId),graphRevision:n,authorizedWriteSetSha256:a}),h=await O(i,e.storyId);await H(h.parent,h.name,`${JSON.stringify(c)}
2
+ `)}async function T(r,e,t,i,a){const n=l(r);try{const c=await O(n,e);await x(c.path,c.parent);const h=JSON.parse(g(c.path,"utf8"));if(!h||typeof h!="object"||Array.isArray(h))throw new Error("private-execution-clean-baseline-invalid");const s=h,o=y(n,{required:!0}).epics[s.epicId]?.graph_revision,u=o===s.graphRevision||a===s.graphRevision&&o===i||typeof o=="string"&&await G(n,e,s,o);if(Object.keys(s).sort().join(",")!==["schemaVersion","kind","storyId","epicId","executionBranch","headSha","setupSessionId","graphRevision","authorizedWriteSetSha256"].sort().join(",")||s.schemaVersion!==3||s.kind!=="private-yolo-clean-baseline"||s.storyId!==e||s.executionBranch!==t||s.epicId!==e.split(".")[0]||typeof s.headSha!="string"||!/^[a-f0-9]{40,64}$/.test(s.headSha)||typeof s.authorizedWriteSetSha256!="string"||!/^[a-f0-9]{64}$/.test(s.authorizedWriteSetSha256)||typeof s.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(s.graphRevision)||i!==void 0&&o!==i||!u||s.authorizedWriteSetSha256!==I(n,e)||s.authorizedWriteSetSha256!==A(n,e)||s.setupSessionId!==R(n,s.epicId,e)||f(n)!==s.headSha||_(n)!==t)throw new Error("private-execution-clean-baseline-invalid")}catch{throw new Error("private-execution-clean-baseline-unverified")}}async function P(r,e,t,i){return T(r,e,t,i)}async function V(r,e,t,i){await P(r,e,t,i);try{const a=w(p(l(r),["show","HEAD:.neocortex/state.json"],16777216).toString("utf8"),e);if(a.length===0)throw new Error("write-set-empty");return Object.freeze([...a])}catch{throw new Error("private-execution-clean-baseline-unverified")}}async function K(r,e,t,i,a){await T(r,e,t,a,i);try{const n=w(p(l(r),["show","HEAD:.neocortex/state.json"],16777216).toString("utf8"),e);if(n.length===0)throw new Error("write-set-empty");return Object.freeze([...n])}catch{throw new Error("private-execution-clean-baseline-unverified")}}function U(r,e,t){try{const i=w(r,e);if(i.length!==t.length||i.some((a,n)=>a!==t[n]))throw new Error("write-set-drift")}catch{throw new Error("private-execution-clean-baseline-write-set-unverified")}}export{J as capturePrivateYoloCleanHead,N as privateYoloRootOnlySetupReady,V as readPrivateYoloFrozenWriteSet,K as readPrivateYoloFrozenWriteSetForTransition,M as recordPrivateYoloCleanBaseline,U as verifyPrivateYoloCandidateWriteSet,P as verifyPrivateYoloCleanBaseline};
@@ -1,4 +1,7 @@
1
1
  export declare const PRIVATE_EXECUTION_PUBLIC_INSTRUCTION_V1 = "# Neocortex private execution pending\n\nThe authorized Codex CLI executor must consume the one-time delivery and produce a physical receipt.";
2
+ export declare const PRIVATE_REPORT_PUBLIC_INSTRUCTION_V1 = "# Private review report ready\n\nThe compatible local client must consume the one-time report and save it in owner-private storage. No report content is included in this public response.";
3
+ /** Public token only; the protected QA step identifier never ships in the client. */
4
+ export declare const PRIVATE_MUTATION_QA_GATE_STEP_TOKEN = "step-8721319d";
2
5
  export interface PrivateExecutionSetupRootActionV1 {
3
6
  readonly schemaVersion: 1;
4
7
  readonly action: 'prepare-epic-checkout';
@@ -61,9 +64,9 @@ export interface PrivateExecutionPublicProjectStepBindingV4 {
61
64
  readonly schemaVersion: 4;
62
65
  readonly authorityKind: 'project-snapshot';
63
66
  readonly projectId: string;
64
- readonly commandId: 'sync-openapi' | 'tech-debt';
67
+ readonly commandId: 'sync-openapi' | 'tech-debt' | 'chaos-plan';
65
68
  readonly stepId: string;
66
- readonly writeSetId: 'sync-openapi-contract-v1' | 'tech-debt-registry-v1';
69
+ readonly writeSetId: 'sync-openapi-contract-v1' | 'tech-debt-registry-v1' | 'chaos-quarterly-v1';
67
70
  readonly stateSnapshotSha256: string;
68
71
  readonly generationId: string;
69
72
  readonly inputSha256: string;
@@ -160,7 +163,41 @@ export interface PrivateExecutionPublicPlanningGenerationBindingV9 {
160
163
  readonly hostKind: 'codex-cli';
161
164
  readonly hostVersion: string;
162
165
  }
163
- export type PrivateExecutionPublicBinding = PrivateExecutionPublicBindingV1 | PrivateExecutionPublicStepBindingV2 | PrivateExecutionPublicEpicClaimBindingV3 | PrivateExecutionPublicProjectStepBindingV4 | PrivateExecutionPublicArchitectureStageBindingV5 | PrivateExecutionPublicPactStageBindingV6 | PrivateExecutionPublicUxStageBindingV7 | PrivateExecutionPublicPlanningStageBindingV8 | PrivateExecutionPublicPlanningGenerationBindingV9;
166
+ export interface PrivateExecutionPublicPropertyTestBindingV10 {
167
+ readonly schemaVersion: 10;
168
+ readonly authorityKind: 'property-test-plan';
169
+ readonly projectId: string;
170
+ readonly commandId: 'property-test';
171
+ readonly stepId: string;
172
+ readonly prdPath: 'prd.md' | 'docs/architecture/prd.md';
173
+ readonly prdSha256: string;
174
+ readonly planSha256: string;
175
+ readonly pathsSha256: string;
176
+ readonly aggregateCount: number;
177
+ readonly invariantCount: number;
178
+ readonly pathCount: number;
179
+ readonly language: 'typescript' | 'python';
180
+ readonly numRuns: 100 | 1000 | 10000;
181
+ readonly stateSnapshotSha256: string;
182
+ readonly generationId: string;
183
+ readonly inputSha256: string;
184
+ readonly hostKind: 'codex-cli';
185
+ readonly hostVersion: string;
186
+ }
187
+ export interface PrivateExecutionPublicReportBindingV11 {
188
+ readonly schemaVersion: 11;
189
+ readonly authorityKind: 'private-report';
190
+ readonly projectId: string;
191
+ readonly commandId: 'ui-ux-review';
192
+ readonly stepId: string;
193
+ readonly format: 'markdown' | 'json';
194
+ readonly stateSnapshotSha256: string;
195
+ readonly generationId: string;
196
+ readonly inputSha256: string;
197
+ readonly hostKind: 'codex-cli';
198
+ readonly hostVersion: string;
199
+ }
200
+ export type PrivateExecutionPublicBinding = PrivateExecutionPublicBindingV1 | PrivateExecutionPublicStepBindingV2 | PrivateExecutionPublicEpicClaimBindingV3 | PrivateExecutionPublicProjectStepBindingV4 | PrivateExecutionPublicArchitectureStageBindingV5 | PrivateExecutionPublicPactStageBindingV6 | PrivateExecutionPublicUxStageBindingV7 | PrivateExecutionPublicPlanningStageBindingV8 | PrivateExecutionPublicPlanningGenerationBindingV9 | PrivateExecutionPublicPropertyTestBindingV10 | PrivateExecutionPublicReportBindingV11;
164
201
  export interface PrivateExecutionDescriptorV1 {
165
202
  readonly schemaVersion: 1;
166
203
  readonly leaseId: string;
@@ -203,7 +240,15 @@ export interface PrivateExecutionDescriptorV9 extends Omit<PrivateExecutionDescr
203
240
  readonly schemaVersion: 9;
204
241
  readonly binding: PrivateExecutionPublicPlanningGenerationBindingV9;
205
242
  }
206
- export type PrivateExecutionDescriptor = PrivateExecutionDescriptorV1 | PrivateExecutionDescriptorV2 | PrivateExecutionDescriptorV3 | PrivateExecutionDescriptorV4 | PrivateExecutionDescriptorV5 | PrivateExecutionDescriptorV6 | PrivateExecutionDescriptorV7 | PrivateExecutionDescriptorV8 | PrivateExecutionDescriptorV9;
243
+ export interface PrivateExecutionDescriptorV10 extends Omit<PrivateExecutionDescriptorV1, 'schemaVersion' | 'binding'> {
244
+ readonly schemaVersion: 10;
245
+ readonly binding: PrivateExecutionPublicPropertyTestBindingV10;
246
+ }
247
+ export interface PrivateExecutionDescriptorV11 extends Omit<PrivateExecutionDescriptorV1, 'schemaVersion' | 'binding'> {
248
+ readonly schemaVersion: 11;
249
+ readonly binding: PrivateExecutionPublicReportBindingV11;
250
+ }
251
+ export type PrivateExecutionDescriptor = PrivateExecutionDescriptorV1 | PrivateExecutionDescriptorV2 | PrivateExecutionDescriptorV3 | PrivateExecutionDescriptorV4 | PrivateExecutionDescriptorV5 | PrivateExecutionDescriptorV6 | PrivateExecutionDescriptorV7 | PrivateExecutionDescriptorV8 | PrivateExecutionDescriptorV9 | PrivateExecutionDescriptorV10 | PrivateExecutionDescriptorV11;
207
252
  export declare function privateExecutionStateSnapshotSha256(stateSnapshot: unknown): string;
208
253
  export declare function parsePrivateExecutionDescriptor(value: unknown, expected?: Readonly<Record<string, unknown>>): PrivateExecutionDescriptor;
209
254
  export declare function verifyPrivateExecutionMaterial(descriptor: PrivateExecutionDescriptor, material: unknown, nowMs?: number): string;
@@ -1,3 +1,5 @@
1
- import{createHash as g}from"node:crypto";const u=`# Neocortex private execution pending
1
+ import{createHash as u}from"node:crypto";const v=`# Neocortex private execution pending
2
2
 
3
- The authorized Codex CLI executor must consume the one-time delivery and produce a physical receipt.`;function b(r){if(!r||typeof r!="object"||Array.isArray(r))return!1;const a=r,i=a.metadata;if(Object.keys(a).sort().join(",")!=="instructions,metadata"||a.instructions!==u||!i||typeof i!="object"||Array.isArray(i))return!1;const e=i,s=e.privateExecution;let t;try{t=I(s)}catch{return!1}if(t.schemaVersion===2)return Object.keys(e).sort().join(",")===["mode","storyId","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&(e.mode==="step"&&(e.resolvedTrigger==="research"||e.resolvedTrigger==="write-spec"||e.resolvedTrigger==="create-tasks"||e.resolvedTrigger==="implement")&&t.binding.commandId===e.resolvedTrigger||e.mode==="pipeline"&&e.resolvedTrigger==="exec"&&t.binding.commandId==="exec")&&e.storyId===t.binding.storyId&&e.stepId===t.binding.stepId;if(t.schemaVersion===3){const h=e.epicClaim,c=h&&typeof h=="object"&&!Array.isArray(h)?h:void 0;return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution","epicClaim"].sort().join(",")&&(e.mode==="create-epic"&&e.resolvedTrigger==="create-epic"&&t.binding.commandId==="create-epic"&&t.binding.writeSetId===void 0||e.mode==="step"&&e.resolvedTrigger==="idea-diagnose"&&t.binding.commandId==="idea-diagnose"&&t.binding.writeSetId==="idea-diagnosis-v1")&&e.stepId===t.binding.stepId&&!!c&&Object.keys(c).sort().join(",")===["schemaVersion","claimId","epicId","outcome","publicSafe"].sort().join(",")&&c.schemaVersion===1&&c.outcome==="reserved"&&c.publicSafe===!0&&c.claimId===t.binding.claimId&&c.epicId===t.binding.epicId}if(t.schemaVersion===4){const h=e.mode==="utility"&&e.resolvedTrigger==="sync-openapi"&&t.binding.commandId==="sync-openapi"&&t.binding.writeSetId==="sync-openapi-contract-v1"||e.mode==="tech-debt"&&e.resolvedTrigger==="tech-debt"&&t.binding.commandId==="tech-debt"&&t.binding.writeSetId==="tech-debt-registry-v1";return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&e.stepId===t.binding.stepId&&h}if(t.schemaVersion===5)return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&e.mode==="step"&&e.resolvedTrigger===t.binding.commandId&&e.stepId===t.binding.stepId&&(t.binding.commandId==="arch-prd"&&t.binding.writeSetId==="arch-prd-docs-v1"||t.binding.commandId==="arch-architecture"&&t.binding.writeSetId==="arch-architecture-doc-v1"||t.binding.commandId==="arch-fitness-functions"&&t.binding.writeSetId==="arch-fitness-tools-v1"||t.binding.commandId==="arch-api-contracts"&&t.binding.writeSetId==="arch-api-contracts-docs-v1"||t.binding.commandId==="arch-api-integrations"&&t.binding.writeSetId==="arch-api-integrations-doc-v1"||t.binding.commandId==="arch-database"&&t.binding.writeSetId==="arch-database-doc-v1"||t.binding.commandId==="arch-security"&&t.binding.writeSetId==="arch-security-doc-v1"||t.binding.commandId==="arch-design-system"&&t.binding.writeSetId==="arch-design-system-doc-v1"||t.binding.commandId==="arch-performance"&&t.binding.writeSetId==="arch-performance-doc-v1"||t.binding.commandId==="arch-testing"&&t.binding.writeSetId==="arch-testing-doc-v1"||t.binding.commandId==="arch-infrastructure"&&t.binding.writeSetId==="arch-infrastructure-doc-v1"||t.binding.commandId==="arch-review"&&t.binding.writeSetId==="arch-review-doc-v1"||t.binding.commandId==="update-memory"&&t.binding.writeSetId==="arch-memory-canonical-v1");if(t.schemaVersion===6)return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&e.mode==="step"&&e.resolvedTrigger==="generate-pacts"&&e.stepId===t.binding.stepId;if(t.schemaVersion===7)return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&e.mode==="step"&&e.resolvedTrigger==="arch-ux-design"&&e.stepId===t.binding.stepId;if(t.schemaVersion===8)return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&e.mode==="step"&&e.resolvedTrigger==="idea-research"&&e.stepId===t.binding.stepId&&t.binding.commandId==="idea-research"&&t.binding.writeSetId==="idea-research-v1";if(t.schemaVersion===9)return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&e.mode==="step"&&e.resolvedTrigger==="generate-epic"&&e.stepId===t.binding.stepId&&t.binding.commandId==="generate-epic"&&t.binding.writeSetId==="generate-epic-v1";const n=e.privateExecutionRootAction,d=["mode","storyId","stepId","resolvedTrigger","gitLifecycleGraphAuthority","privateExecution",...n===void 0?[]:["privateExecutionRootAction"]],m=e.gitLifecycleGraphAuthority,p=m&&typeof m=="object"&&!Array.isArray(m)?m:void 0,o=n&&typeof n=="object"&&!Array.isArray(n)?n:void 0;return Object.keys(e).sort().join(",")===d.sort().join(",")&&e.mode==="yolo"&&e.resolvedTrigger==="yolo"&&typeof e.storyId=="string"&&typeof e.stepId=="string"&&!!p&&p.storyId===e.storyId&&p.graphRevision===t.binding.graphRevision&&t.binding.commandId==="yolo"&&t.binding.stepId===e.stepId&&(n===void 0||!!o&&Object.keys(o).sort().join(",")===["schemaVersion","action","storyId","executionBranch","graphRevision","publicSafe",...o.action==="checkpoint-epic-story"?["stepId"]:[]].sort().join(",")&&o.schemaVersion===1&&(o.action==="prepare-epic-checkout"||o.action==="checkpoint-epic-story")&&(o.action!=="checkpoint-epic-story"||o.stepId===e.stepId)&&o.publicSafe===!0&&o.storyId===e.storyId&&o.storyId===p.storyId&&o.executionBranch===p.executionBranch&&o.graphRevision===p.graphRevision)}function f(r){return g("sha256").update("private-step-state-v1\0").update(JSON.stringify(r)).digest("hex")}function I(r,a){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("private-execution-descriptor-invalid");const i=r,e=i.binding,s=i.schemaVersion===2||i.schemaVersion===3||i.schemaVersion===4||i.schemaVersion===5||i.schemaVersion===6||i.schemaVersion===7||i.schemaVersion===8||i.schemaVersion===9,t=s?["schemaVersion","authorityKind","projectId","commandId","stepId",...i.schemaVersion===3?["claimId","epicId",...e?.commandId==="idea-diagnose"?["writeSetId"]:[]]:i.schemaVersion===4?["writeSetId"]:i.schemaVersion===5?["targetEpicId","graphRevision","writeSetId"]:i.schemaVersion===6?["targetEpicId","graphRevision","answersSha256","specSha256","pathsSha256","endpointCount","pathCount"]:i.schemaVersion===7?["targetEpicId","graphRevision","adapterId","authoritySha256","pathsSha256","screenCount","pathCount"]:i.schemaVersion===8?["claimId","epicId","diagnosisReceiptId","intakeRevision","physicalAcceptanceReceiptId","writeSetId"]:i.schemaVersion===9?["claimId","epicId","diagnosisReceiptId","researchReceiptId","intakeRevision","physicalAcceptanceReceiptId","writeSetId"]:["storyId"],"stateSnapshotSha256","generationId","inputSha256","hostKind","hostVersion"]:["commandId","generationId","graphRevision","hostKind","hostVersion","inputSha256","projectId","stepId"];if(Object.keys(i).sort().join(",")!==["schemaVersion","leaseId","materialSha256","byteLength","expiresAt","delivery","publicSafe","binding"].sort().join(",")||i.schemaVersion!==1&&!s||i.delivery!=="private-one-time"||i.publicSafe!==!0||typeof i.leaseId!="string"||!/^px_[a-f0-9]{48}$/.test(i.leaseId)||typeof i.materialSha256!="string"||!/^[a-f0-9]{64}$/.test(i.materialSha256)||!Number.isSafeInteger(i.byteLength)||i.byteLength<1||i.byteLength>256*1024||typeof i.expiresAt!="string"||!Number.isFinite(Date.parse(i.expiresAt))||!e||Object.keys(e).sort().join(",")!==t.sort().join(",")||Object.entries(e).some(([n,d])=>n!=="schemaVersion"&&n!=="endpointCount"&&n!=="screenCount"&&n!=="pathCount"&&(typeof d!="string"||d.length<1||d.length>256))||!/^[a-f0-9]{64}$/.test(String(e.inputSha256))||e.hostKind!=="codex-cli"||s&&!/^[a-f0-9]{64}$/.test(String(e.stateSnapshotSha256))||i.schemaVersion===2&&(e.schemaVersion!==2||e.authorityKind!=="state-snapshot"||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(String(e.storyId)))||i.schemaVersion===3&&(e.schemaVersion!==3||e.authorityKind!=="epic-claim"||!(e.commandId==="create-epic"&&e.writeSetId===void 0||e.commandId==="idea-diagnose"&&e.writeSetId==="idea-diagnosis-v1")||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(String(e.claimId))||!/^P[1-9][0-9]*$/.test(String(e.epicId)))||i.schemaVersion===4&&(e.schemaVersion!==4||e.authorityKind!=="project-snapshot"||!(e.commandId==="sync-openapi"&&e.writeSetId==="sync-openapi-contract-v1"||e.commandId==="tech-debt"&&e.writeSetId==="tech-debt-registry-v1"))||i.schemaVersion===5&&(e.schemaVersion!==5||e.authorityKind!=="architecture-stage"||!(e.commandId==="arch-prd"&&e.writeSetId==="arch-prd-docs-v1"||e.commandId==="arch-architecture"&&e.writeSetId==="arch-architecture-doc-v1"||e.commandId==="arch-fitness-functions"&&e.writeSetId==="arch-fitness-tools-v1"||e.commandId==="arch-api-contracts"&&e.writeSetId==="arch-api-contracts-docs-v1"||e.commandId==="arch-api-integrations"&&e.writeSetId==="arch-api-integrations-doc-v1"||e.commandId==="arch-database"&&e.writeSetId==="arch-database-doc-v1"||e.commandId==="arch-security"&&e.writeSetId==="arch-security-doc-v1"||e.commandId==="arch-design-system"&&e.writeSetId==="arch-design-system-doc-v1"||e.commandId==="arch-performance"&&e.writeSetId==="arch-performance-doc-v1"||e.commandId==="arch-testing"&&e.writeSetId==="arch-testing-doc-v1"||e.commandId==="arch-infrastructure"&&e.writeSetId==="arch-infrastructure-doc-v1"||e.commandId==="arch-review"&&e.writeSetId==="arch-review-doc-v1"||e.commandId==="update-memory"&&e.writeSetId==="arch-memory-canonical-v1")||!/^P[1-9][0-9]{0,11}$/.test(String(e.targetEpicId))||!/^[a-f0-9]{64}$/.test(String(e.graphRevision)))||i.schemaVersion===6&&(e.schemaVersion!==6||e.authorityKind!=="pact-stage"||e.commandId!=="generate-pacts"||!/^P[1-9][0-9]{0,11}$/.test(String(e.targetEpicId))||!/^[a-f0-9]{64}$/.test(String(e.graphRevision))||!/^[a-f0-9]{64}$/.test(String(e.answersSha256))||!/^[a-f0-9]{64}$/.test(String(e.specSha256))||!/^[a-f0-9]{64}$/.test(String(e.pathsSha256))||!Number.isSafeInteger(e.endpointCount)||e.endpointCount<1||e.endpointCount>256||!Number.isSafeInteger(e.pathCount)||e.pathCount<e.endpointCount||e.pathCount>e.endpointCount+1)||i.schemaVersion===7&&(e.schemaVersion!==7||e.authorityKind!=="ux-stage"||e.commandId!=="arch-ux-design"||!/^P[1-9][0-9]{0,11}$/.test(String(e.targetEpicId))||!/^[a-f0-9]{64}$/.test(String(e.graphRevision))||!["storybook-react-vite","storybook-nextjs-vite"].includes(String(e.adapterId))||!/^[a-f0-9]{64}$/.test(String(e.authoritySha256))||!/^[a-f0-9]{64}$/.test(String(e.pathsSha256))||!Number.isSafeInteger(e.screenCount)||e.screenCount<1||e.screenCount>48||!Number.isSafeInteger(e.pathCount)||e.pathCount!==e.screenCount*6+3)||i.schemaVersion===8&&(e.schemaVersion!==8||e.authorityKind!=="planning-stage"||e.commandId!=="idea-research"||e.writeSetId!=="idea-research-v1"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(String(e.claimId))||!/^P[1-9][0-9]{0,11}$/.test(String(e.epicId))||[e.diagnosisReceiptId,e.intakeRevision,e.physicalAcceptanceReceiptId].some(n=>!/^[a-f0-9]{64}$/.test(String(n))))||i.schemaVersion===9&&(e.schemaVersion!==9||e.authorityKind!=="planning-generation"||e.commandId!=="generate-epic"||e.writeSetId!=="generate-epic-v1"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(String(e.claimId))||!/^P[1-9][0-9]{0,11}$/.test(String(e.epicId))||[e.diagnosisReceiptId,e.researchReceiptId,e.intakeRevision,e.physicalAcceptanceReceiptId].some(n=>!/^[a-f0-9]{64}$/.test(String(n))))||a&&Object.entries(a).some(([n,d])=>e[n]!==d))throw new Error("private-execution-descriptor-invalid");return i}function y(r,a,i=Date.now()){if(typeof a!="string"||i>=Date.parse(r.expiresAt)||Buffer.byteLength(a,"utf8")!==r.byteLength||g("sha256").update(a,"utf8").digest("hex")!==r.materialSha256)throw new Error("private-execution-material-invalid");return a}async function S(r,a,i,e=Date.now()){const s=I(r,a);if(e>=Date.parse(s.expiresAt))throw new Error("private-execution-material-expired");const t=await i({leaseId:s.leaseId,...s.binding});if(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).sort().join(",")!=="material,schemaVersion"||t.schemaVersion!==1)throw new Error("private-execution-delivery-invalid");return y(s,t.material,Math.max(e,Date.now()))}export{u as PRIVATE_EXECUTION_PUBLIC_INSTRUCTION_V1,S as consumePrivateExecutionDelivery,b as isPrivateExecutionPublicEnvelope,I as parsePrivateExecutionDescriptor,f as privateExecutionStateSnapshotSha256,y as verifyPrivateExecutionMaterial};
3
+ The authorized Codex CLI executor must consume the one-time delivery and produce a physical receipt.`,y=`# Private review report ready
4
+
5
+ The compatible local client must consume the one-time report and save it in owner-private storage. No report content is included in this public response.`,S="step-8721319d";function V(n){if(!n||typeof n!="object"||Array.isArray(n))return!1;const a=n,i=a.metadata;if(Object.keys(a).sort().join(",")!=="instructions,metadata"||a.instructions!==v&&a.instructions!==y||!i||typeof i!="object"||Array.isArray(i))return!1;const e=i,s=e.privateExecution;let t;try{t=b(s)}catch{return!1}if(t.schemaVersion!==11&&a.instructions!==v)return!1;if(t.schemaVersion===2)return Object.keys(e).sort().join(",")===["mode","storyId","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&(e.mode==="step"&&(e.resolvedTrigger==="research"||e.resolvedTrigger==="write-spec"||e.resolvedTrigger==="create-tasks"||e.resolvedTrigger==="implement")&&t.binding.commandId===e.resolvedTrigger||e.mode==="pipeline"&&e.resolvedTrigger==="exec"&&t.binding.commandId==="exec")&&e.storyId===t.binding.storyId&&e.stepId===t.binding.stepId;if(t.schemaVersion===3){const m=e.epicClaim,c=m&&typeof m=="object"&&!Array.isArray(m)?m:void 0;return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution","epicClaim"].sort().join(",")&&(e.mode==="create-epic"&&e.resolvedTrigger==="create-epic"&&t.binding.commandId==="create-epic"&&t.binding.writeSetId===void 0||e.mode==="step"&&e.resolvedTrigger==="idea-diagnose"&&t.binding.commandId==="idea-diagnose"&&t.binding.writeSetId==="idea-diagnosis-v1")&&e.stepId===t.binding.stepId&&!!c&&Object.keys(c).sort().join(",")===["schemaVersion","claimId","epicId","outcome","publicSafe"].sort().join(",")&&c.schemaVersion===1&&c.outcome==="reserved"&&c.publicSafe===!0&&c.claimId===t.binding.claimId&&c.epicId===t.binding.epicId}if(t.schemaVersion===4){const m=e.mode==="utility"&&e.resolvedTrigger==="sync-openapi"&&t.binding.commandId==="sync-openapi"&&t.binding.writeSetId==="sync-openapi-contract-v1"||e.mode==="utility"&&e.resolvedTrigger==="chaos-plan"&&t.binding.commandId==="chaos-plan"&&t.binding.writeSetId==="chaos-quarterly-v1"||e.mode==="tech-debt"&&e.resolvedTrigger==="tech-debt"&&t.binding.commandId==="tech-debt"&&t.binding.writeSetId==="tech-debt-registry-v1";return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&e.stepId===t.binding.stepId&&m}if(t.schemaVersion===11)return a.instructions===y&&Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&e.mode==="ui-ux-review"&&e.resolvedTrigger==="ui-ux-review"&&e.stepId===t.binding.stepId;if(t.schemaVersion===5)return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&e.mode==="step"&&e.resolvedTrigger===t.binding.commandId&&e.stepId===t.binding.stepId&&(t.binding.commandId==="arch-prd"&&t.binding.writeSetId==="arch-prd-docs-v1"||t.binding.commandId==="arch-architecture"&&t.binding.writeSetId==="arch-architecture-doc-v1"||t.binding.commandId==="arch-fitness-functions"&&t.binding.writeSetId==="arch-fitness-tools-v1"||t.binding.commandId==="arch-api-contracts"&&t.binding.writeSetId==="arch-api-contracts-docs-v1"||t.binding.commandId==="arch-api-integrations"&&t.binding.writeSetId==="arch-api-integrations-doc-v1"||t.binding.commandId==="arch-database"&&t.binding.writeSetId==="arch-database-doc-v1"||t.binding.commandId==="arch-security"&&t.binding.writeSetId==="arch-security-doc-v1"||t.binding.commandId==="arch-design-system"&&t.binding.writeSetId==="arch-design-system-doc-v1"||t.binding.commandId==="arch-performance"&&t.binding.writeSetId==="arch-performance-doc-v1"||t.binding.commandId==="arch-testing"&&t.binding.writeSetId==="arch-testing-doc-v1"||t.binding.commandId==="arch-infrastructure"&&t.binding.writeSetId==="arch-infrastructure-doc-v1"||t.binding.commandId==="arch-review"&&t.binding.writeSetId==="arch-review-doc-v1"||t.binding.commandId==="update-memory"&&t.binding.writeSetId==="arch-memory-canonical-v1");if(t.schemaVersion===6)return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&e.mode==="step"&&e.resolvedTrigger==="generate-pacts"&&e.stepId===t.binding.stepId;if(t.schemaVersion===7)return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&e.mode==="step"&&e.resolvedTrigger==="arch-ux-design"&&e.stepId===t.binding.stepId;if(t.schemaVersion===8)return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&e.mode==="step"&&e.resolvedTrigger==="idea-research"&&e.stepId===t.binding.stepId&&t.binding.commandId==="idea-research"&&t.binding.writeSetId==="idea-research-v1";if(t.schemaVersion===9)return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&e.mode==="step"&&e.resolvedTrigger==="generate-epic"&&e.stepId===t.binding.stepId&&t.binding.commandId==="generate-epic"&&t.binding.writeSetId==="generate-epic-v1";if(t.schemaVersion===10)return Object.keys(e).sort().join(",")===["mode","stepId","resolvedTrigger","privateExecution"].sort().join(",")&&e.mode==="utility"&&e.resolvedTrigger==="property-test"&&e.stepId===t.binding.stepId&&t.binding.commandId==="property-test";const r=e.privateExecutionRootAction,d=e.stepId===S,h=e.mutationQaFeature,p=h&&typeof h=="object"&&!Array.isArray(h)?h:void 0,l=["mode","storyId","stepId","resolvedTrigger","gitLifecycleGraphAuthority","privateExecution",...d?["mutationQaFeature"]:[],...r===void 0?[]:["privateExecutionRootAction"]],I=e.gitLifecycleGraphAuthority,g=I&&typeof I=="object"&&!Array.isArray(I)?I:void 0,o=r&&typeof r=="object"&&!Array.isArray(r)?r:void 0;return(!d||!!p&&Object.keys(p).sort().join(",")===["schemaVersion","id","enabled","publicSafe"].sort().join(",")&&p.schemaVersion===1&&p.id==="mutation-testing"&&typeof p.enabled=="boolean"&&p.publicSafe===!0)&&Object.keys(e).sort().join(",")===l.sort().join(",")&&e.mode==="yolo"&&e.resolvedTrigger==="yolo"&&typeof e.storyId=="string"&&typeof e.stepId=="string"&&!!g&&g.storyId===e.storyId&&g.graphRevision===t.binding.graphRevision&&t.binding.commandId==="yolo"&&t.binding.stepId===e.stepId&&(r===void 0||!!o&&Object.keys(o).sort().join(",")===["schemaVersion","action","storyId","executionBranch","graphRevision","publicSafe",...o.action==="checkpoint-epic-story"?["stepId"]:[]].sort().join(",")&&o.schemaVersion===1&&(o.action==="prepare-epic-checkout"||o.action==="checkpoint-epic-story")&&(o.action!=="checkpoint-epic-story"||o.stepId===e.stepId)&&o.publicSafe===!0&&o.storyId===e.storyId&&o.storyId===g.storyId&&o.executionBranch===g.executionBranch&&o.graphRevision===g.graphRevision)}function j(n){return u("sha256").update("private-step-state-v1\0").update(JSON.stringify(n)).digest("hex")}function b(n,a){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("private-execution-descriptor-invalid");const i=n,e=i.binding,s=i.schemaVersion===2||i.schemaVersion===3||i.schemaVersion===4||i.schemaVersion===5||i.schemaVersion===6||i.schemaVersion===7||i.schemaVersion===8||i.schemaVersion===9||i.schemaVersion===10||i.schemaVersion===11,t=s?["schemaVersion","authorityKind","projectId","commandId","stepId",...i.schemaVersion===3?["claimId","epicId",...e?.commandId==="idea-diagnose"?["writeSetId"]:[]]:i.schemaVersion===4?["writeSetId"]:i.schemaVersion===5?["targetEpicId","graphRevision","writeSetId"]:i.schemaVersion===6?["targetEpicId","graphRevision","answersSha256","specSha256","pathsSha256","endpointCount","pathCount"]:i.schemaVersion===7?["targetEpicId","graphRevision","adapterId","authoritySha256","pathsSha256","screenCount","pathCount"]:i.schemaVersion===8?["claimId","epicId","diagnosisReceiptId","intakeRevision","physicalAcceptanceReceiptId","writeSetId"]:i.schemaVersion===9?["claimId","epicId","diagnosisReceiptId","researchReceiptId","intakeRevision","physicalAcceptanceReceiptId","writeSetId"]:i.schemaVersion===10?["prdPath","prdSha256","planSha256","pathsSha256","aggregateCount","invariantCount","pathCount","language","numRuns"]:i.schemaVersion===11?["format"]:["storyId"],"stateSnapshotSha256","generationId","inputSha256","hostKind","hostVersion"]:["commandId","generationId","graphRevision","hostKind","hostVersion","inputSha256","projectId","stepId"];if(Object.keys(i).sort().join(",")!==["schemaVersion","leaseId","materialSha256","byteLength","expiresAt","delivery","publicSafe","binding"].sort().join(",")||i.schemaVersion!==1&&!s||i.delivery!=="private-one-time"||i.publicSafe!==!0||typeof i.leaseId!="string"||!/^px_[a-f0-9]{48}$/.test(i.leaseId)||typeof i.materialSha256!="string"||!/^[a-f0-9]{64}$/.test(i.materialSha256)||!Number.isSafeInteger(i.byteLength)||i.byteLength<1||i.byteLength>256*1024||typeof i.expiresAt!="string"||!Number.isFinite(Date.parse(i.expiresAt))||!e||Object.keys(e).sort().join(",")!==t.sort().join(",")||Object.entries(e).some(([r,d])=>r!=="schemaVersion"&&r!=="endpointCount"&&r!=="screenCount"&&r!=="pathCount"&&r!=="aggregateCount"&&r!=="invariantCount"&&r!=="numRuns"&&(typeof d!="string"||d.length<1||d.length>256))||!/^[a-f0-9]{64}$/.test(String(e.inputSha256))||e.hostKind!=="codex-cli"||s&&!/^[a-f0-9]{64}$/.test(String(e.stateSnapshotSha256))||i.schemaVersion===2&&(e.schemaVersion!==2||e.authorityKind!=="state-snapshot"||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(String(e.storyId)))||i.schemaVersion===3&&(e.schemaVersion!==3||e.authorityKind!=="epic-claim"||!(e.commandId==="create-epic"&&e.writeSetId===void 0||e.commandId==="idea-diagnose"&&e.writeSetId==="idea-diagnosis-v1")||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(String(e.claimId))||!/^P[1-9][0-9]*$/.test(String(e.epicId)))||i.schemaVersion===4&&(e.schemaVersion!==4||e.authorityKind!=="project-snapshot"||!(e.commandId==="sync-openapi"&&e.writeSetId==="sync-openapi-contract-v1"||e.commandId==="tech-debt"&&e.writeSetId==="tech-debt-registry-v1"||e.commandId==="chaos-plan"&&e.writeSetId==="chaos-quarterly-v1"))||i.schemaVersion===11&&(e.schemaVersion!==11||e.authorityKind!=="private-report"||e.commandId!=="ui-ux-review"||!["markdown","json"].includes(String(e.format))||!/^sha256:[a-f0-9]{64}$/.test(String(e.generationId))||i.materialSha256!==String(e.generationId).slice(7))||i.schemaVersion===5&&(e.schemaVersion!==5||e.authorityKind!=="architecture-stage"||!(e.commandId==="arch-prd"&&e.writeSetId==="arch-prd-docs-v1"||e.commandId==="arch-architecture"&&e.writeSetId==="arch-architecture-doc-v1"||e.commandId==="arch-fitness-functions"&&e.writeSetId==="arch-fitness-tools-v1"||e.commandId==="arch-api-contracts"&&e.writeSetId==="arch-api-contracts-docs-v1"||e.commandId==="arch-api-integrations"&&e.writeSetId==="arch-api-integrations-doc-v1"||e.commandId==="arch-database"&&e.writeSetId==="arch-database-doc-v1"||e.commandId==="arch-security"&&e.writeSetId==="arch-security-doc-v1"||e.commandId==="arch-design-system"&&e.writeSetId==="arch-design-system-doc-v1"||e.commandId==="arch-performance"&&e.writeSetId==="arch-performance-doc-v1"||e.commandId==="arch-testing"&&e.writeSetId==="arch-testing-doc-v1"||e.commandId==="arch-infrastructure"&&e.writeSetId==="arch-infrastructure-doc-v1"||e.commandId==="arch-review"&&e.writeSetId==="arch-review-doc-v1"||e.commandId==="update-memory"&&e.writeSetId==="arch-memory-canonical-v1")||!/^P[1-9][0-9]{0,11}$/.test(String(e.targetEpicId))||!/^[a-f0-9]{64}$/.test(String(e.graphRevision)))||i.schemaVersion===6&&(e.schemaVersion!==6||e.authorityKind!=="pact-stage"||e.commandId!=="generate-pacts"||!/^P[1-9][0-9]{0,11}$/.test(String(e.targetEpicId))||!/^[a-f0-9]{64}$/.test(String(e.graphRevision))||!/^[a-f0-9]{64}$/.test(String(e.answersSha256))||!/^[a-f0-9]{64}$/.test(String(e.specSha256))||!/^[a-f0-9]{64}$/.test(String(e.pathsSha256))||!Number.isSafeInteger(e.endpointCount)||e.endpointCount<1||e.endpointCount>256||!Number.isSafeInteger(e.pathCount)||e.pathCount<e.endpointCount||e.pathCount>e.endpointCount+1)||i.schemaVersion===7&&(e.schemaVersion!==7||e.authorityKind!=="ux-stage"||e.commandId!=="arch-ux-design"||!/^P[1-9][0-9]{0,11}$/.test(String(e.targetEpicId))||!/^[a-f0-9]{64}$/.test(String(e.graphRevision))||!["storybook-react-vite","storybook-nextjs-vite"].includes(String(e.adapterId))||!/^[a-f0-9]{64}$/.test(String(e.authoritySha256))||!/^[a-f0-9]{64}$/.test(String(e.pathsSha256))||!Number.isSafeInteger(e.screenCount)||e.screenCount<1||e.screenCount>48||!Number.isSafeInteger(e.pathCount)||e.pathCount!==e.screenCount*6+3)||i.schemaVersion===8&&(e.schemaVersion!==8||e.authorityKind!=="planning-stage"||e.commandId!=="idea-research"||e.writeSetId!=="idea-research-v1"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(String(e.claimId))||!/^P[1-9][0-9]{0,11}$/.test(String(e.epicId))||[e.diagnosisReceiptId,e.intakeRevision,e.physicalAcceptanceReceiptId].some(r=>!/^[a-f0-9]{64}$/.test(String(r))))||i.schemaVersion===9&&(e.schemaVersion!==9||e.authorityKind!=="planning-generation"||e.commandId!=="generate-epic"||e.writeSetId!=="generate-epic-v1"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(String(e.claimId))||!/^P[1-9][0-9]{0,11}$/.test(String(e.epicId))||[e.diagnosisReceiptId,e.researchReceiptId,e.intakeRevision,e.physicalAcceptanceReceiptId].some(r=>!/^[a-f0-9]{64}$/.test(String(r))))||i.schemaVersion===10&&(e.schemaVersion!==10||e.authorityKind!=="property-test-plan"||e.commandId!=="property-test"||!["prd.md","docs/architecture/prd.md"].includes(String(e.prdPath))||[e.prdSha256,e.planSha256,e.pathsSha256].some(r=>!/^[a-f0-9]{64}$/.test(String(r)))||!Number.isSafeInteger(e.aggregateCount)||e.aggregateCount<1||e.aggregateCount>64||!Number.isSafeInteger(e.invariantCount)||e.invariantCount<e.aggregateCount||e.invariantCount>1024||e.pathCount!==e.aggregateCount||!["typescript","python"].includes(String(e.language))||![100,1e3,1e4].includes(e.numRuns))||a&&Object.entries(a).some(([r,d])=>e[r]!==d))throw new Error("private-execution-descriptor-invalid");return i}function f(n,a,i=Date.now()){if(typeof a!="string"||i>=Date.parse(n.expiresAt)||Buffer.byteLength(a,"utf8")!==n.byteLength||u("sha256").update(a,"utf8").digest("hex")!==n.materialSha256)throw new Error("private-execution-material-invalid");return a}async function x(n,a,i,e=Date.now()){const s=b(n,a);if(e>=Date.parse(s.expiresAt))throw new Error("private-execution-material-expired");const t=await i({leaseId:s.leaseId,...s.binding});if(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).sort().join(",")!=="material,schemaVersion"||t.schemaVersion!==1)throw new Error("private-execution-delivery-invalid");return f(s,t.material,Math.max(e,Date.now()))}export{v as PRIVATE_EXECUTION_PUBLIC_INSTRUCTION_V1,S as PRIVATE_MUTATION_QA_GATE_STEP_TOKEN,y as PRIVATE_REPORT_PUBLIC_INSTRUCTION_V1,x as consumePrivateExecutionDelivery,V as isPrivateExecutionPublicEnvelope,b as parsePrivateExecutionDescriptor,j as privateExecutionStateSnapshotSha256,f as verifyPrivateExecutionMaterial};
@@ -3,6 +3,7 @@ import { type PactAnswerReceipt } from '../commands/architecture-answers.js';
3
3
  import { type PactWriteSetV1 } from './pact-write-set.js';
4
4
  import { type UxWriteSetV1 } from './ux-write-set.js';
5
5
  import { type PactToolchainCandidateV1 } from './pact-toolchain.js';
6
+ import { type PropertyTestChoices, type PropertyTestPlan } from './property-test-plan.js';
6
7
  export interface PrivateYoloIsolatedAdmissionV1 {
7
8
  readonly schemaVersion: 1;
8
9
  readonly outcome: 'admitted-unverified';
@@ -46,3 +47,9 @@ export declare function admitPrivateUxWorkspace(workspace: PrivateYoloIsolatedWo
46
47
  * then admitted in the same exact patch. This still proves no test execution.
47
48
  */
48
49
  export declare function admitPrivatePactWorkspace(workspace: PrivateYoloIsolatedWorkspaceV1, targetEpicId: string, graphRevision: string, expectedAnswers: PactAnswerReceipt, expectedWriteSet: PactWriteSetV1, toolchainCandidate?: PactToolchainCandidateV1): PrivatePactAdmissionV1;
50
+ /**
51
+ * Admit only plan-bound property-test candidates. The agent cannot edit the
52
+ * PRD: the root appends the operator-confirmed configuration in the clone only
53
+ * after checking the complete test write set. This is not a QA verdict.
54
+ */
55
+ export declare function admitPrivatePropertyTestWorkspace(workspace: PrivateYoloIsolatedWorkspaceV1, choices: PropertyTestChoices, expectedPlan: PropertyTestPlan, generatedAt?: string): PrivateYoloIsolatedAdmissionV1;
@@ -1,11 +1,11 @@
1
- import{execFileSync as Re,spawnSync as ye}from"node:child_process";import{createHash as F}from"node:crypto";import{existsSync as re,lstatSync as R,readFileSync as l,realpathSync as ae,writeFileSync as Ee}from"node:fs";import{isAbsolute as oe,join as i,relative as ce,sep as Pe}from"node:path";import{isDeepStrictEqual as T}from"node:util";import{readPrivateYoloFrozenWriteSet as Ae,verifyPrivateYoloCandidateWriteSet as Se,verifyPrivateYoloCleanBaseline as $e}from"./clean-baseline.js";import{PRIVATE_EPIC_PENDING_SIDECAR as te}from"./isolated-workspace.js";import{loadPactPrivateAnswers as Oe}from"../commands/architecture-answers.js";import{derivePactWriteSet as ve}from"./pact-write-set.js";import{deriveUxCandidateWriteSet as je,deriveUxWriteSet as Ne}from"./ux-write-set.js";import{validateUxCandidateSource as Te}from"./ux-source-validation.js";import{validatePactTestSource as De}from"./pact-test-source.js";import{classifyProjectMemoryUpdate as Be}from"../memory/project-memory-writer.js";import{inspectPactToolchain as Le,planPactToolchainManifest as Ce}from"./pact-toolchain.js";import{acceptedPlanningDiagnosisPredecessor as Fe}from"./planning-diagnosis-checkpoint.js";import{acceptedPlanningResearchPredecessor as ze}from"./planning-research-checkpoint.js";const Q=16*1024*1024,he=1024,de="acd455ed0e39d98b90fb57391db75e366e4c5604db043e03a89a20e33d643c3c",He="81f50aaa801c1660eabe46e645501acbfb3e9873410c991e1496c014ca75c369",we="fa2194f89c01f07e225fd6f39e98e679f628e072239b6cd0af3ee527f0722518",Je="8636f22ec5950410902448ee1e9cb4947359ac98df518742bddbbb367468e3ae";function I(e,t){return typeof e=="string"&&e.length<=128&&F("sha256").update(e).digest("hex")===t}function le(){const e={...process.env};for(const t 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 e[t];return e}function k(e,t){return Re("git",[...t],{cwd:e,env:le(),stdio:["ignore","pipe","pipe"],timeout:3e4,maxBuffer:Q})}function J(e,t){return k(e,t).toString("utf8").trim()}function z(e,t=!1){return k(e,["status","--porcelain=v1","-z","--untracked-files=all",...t?["--ignored=matching"]:[]])}function ue(e){return!!e&&!oe(e)&&!e.includes("\\")&&!e.includes("\0")&&!e.split("/").some(t=>!t||t==="."||t===".."||t===".git")}function E(e,t){const r=t.split("/");let o=e;for(const n of r.slice(0,-1)){o=i(o,n);try{const a=R(o);if(!a.isDirectory()||a.isSymbolicLink())throw new Error("path-boundary")}catch(a){if(a.code==="ENOENT")return;throw a}}try{const n=R(i(e,t));if(!n.isFile()||n.isSymbolicLink()||n.size>Q)throw new Error("path-boundary")}catch(n){if(n.code!=="ENOENT")throw n}}function _e(e){const t=[...e.matchAll(/\/\/\s*arch:keep-start[^\n]*\n[\s\S]*?\/\/\s*arch:keep-end[^\n]*/g)].map(n=>n[0]),r=(e.match(/arch:keep-start/g)??[]).length,o=(e.match(/arch:keep-end/g)??[]).length;if(r!==o||r!==t.length)throw new Error("architecture-keep-marker-invalid");return t}function G(e,t=!1,r=!1){const o=[],n=[];for(const a of e.toString("utf8").split("\0").filter(Boolean)){if(a.length<4||a[2]!==" ")throw new Error("status-invalid");const s=a.slice(0,2),c=a.slice(3);if(!ue(c)||s!=="??"&&s!==" M"&&s!==" D"&&!(r&&s==="!!"&&c===te))throw new Error("status-invalid");o.push(c),s==="??"&&n.push(c)}if(!t&&o.length===0||o.length>he||new Set(o).size!==o.length)throw new Error("status-invalid");return{paths:o.sort(),untracked:n.sort()}}function pe(e,t,r,o){const n=k(t,["ls-tree","-z",r,"--",o]).toString("utf8");if(!n)try{return R(i(e,o)),!1}catch(s){return s.code==="ENOENT"}const a=/^([0-7]{6}) blob [a-f0-9]{40,64}\t([^\0]+)\0$/.exec(n);if(!a||a[2]!==o||!["100644","100755"].includes(a[1]))return!1;try{const s=R(i(e,o));return!s.isFile()||s.isSymbolicLink()||s.size>Q||!!(s.mode&73)!=(a[1]==="100755")?!1:l(i(e,o)).equals(k(t,["show",`${r}:${o}`]))}catch{return!1}}function ne(e,t){try{const r=i(e,te),o=R(i(e,".neocortex")),n=R(r);return o.isDirectory()&&!o.isSymbolicLink()&&o.uid===process.getuid?.()&&(o.mode&18)===0&&n.isFile()&&!n.isSymbolicLink()&&n.uid===process.getuid?.()&&(n.mode&63)===0&&n.size>0&&n.size<=128*1024&&F("sha256").update(l(r)).digest("hex")===t}catch{return!1}}function fe(e,t,r,o,n){const a=new Set(o),s=G(z(e),!0,!!n);return(!n||ne(e,n))&&s.paths.every(c=>a.has(c)||c===te&&!!n&&ne(e,n))&&o.every(c=>pe(e,t,r,c))}function Me(e,t){const r=ye("git",["diff","--no-index","--binary","--no-ext-diff","--","/dev/null",t],{cwd:e,env:le(),encoding:"buffer",timeout:3e4,maxBuffer:Q});if(r.error||r.status!==1||!Buffer.isBuffer(r.stdout)||r.stdout.byteLength===0)throw new Error("patch-invalid");return r.stdout}function be(e,t,r){const o=ye("git",["apply",...r?["--check"]:[],"--binary","-"],{cwd:e,env:le(),input:t,encoding:"buffer",timeout:3e4,maxBuffer:Q});if(o.error||o.status!==0)throw new Error("apply-failed")}function Ge(e,t,r){const o=i(e,r),n=i(t,r);try{const a=R(o),s=R(n);return a.isFile()&&s.isFile()&&(a.mode&73)===(s.mode&73)&&l(o).equals(l(n))}catch(a){if(a.code!=="ENOENT")return!1;try{return R(o),!1}catch(s){if(s.code!=="ENOENT")return!1}try{return R(n),!1}catch(s){return s.code==="ENOENT"}}}function st(e,t,r){try{if(process.platform!=="linux"||e.schemaVersion!==1||!oe(e.sourceRoot)||!oe(e.workspacePath)||ae(e.sourceRoot)!==e.sourceRoot||ae(e.workspacePath)!==e.workspacePath||!R(e.workspacePath).isDirectory()||(R(e.workspacePath).mode&63)!==0||ce(e.sourceRoot,e.workspacePath)===""||ce(e.sourceRoot,e.workspacePath).split(Pe)[0]!==".."||!/^[a-f0-9]{40,64}$/.test(e.baseSha)||!/^[a-f0-9]{40,64}$/.test(r)||J(e.sourceRoot,["rev-parse","--show-toplevel"])!==e.sourceRoot||J(e.workspacePath,["rev-parse","--show-toplevel"])!==e.workspacePath||J(e.sourceRoot,["rev-parse","HEAD"])!==e.baseSha||J(e.workspacePath,["rev-parse","HEAD"])!==r||J(e.sourceRoot,["symbolic-ref","--short","HEAD"])!==e.executionBranch||J(e.workspacePath,["symbolic-ref","--short","HEAD"])!==e.executionBranch||re(i(e.workspacePath,".git","objects","info","alternates"))||z(e.workspacePath,!0).byteLength!==0||t.length===0||t.length>he||t.some(o=>!ue(o))||new Set(t).size!==t.length)throw new Error("boundary-invalid");if(k(e.workspacePath,["merge-base","--is-ancestor",e.baseSha,r]),!fe(e.sourceRoot,e.workspacePath,r,t))throw new Error("boundary-raced")}catch{throw new Error("private-execution-isolated-snapshot-unverified")}}function W(e,t,r,o,n,a=[]){try{if(process.platform!=="linux"||e.schemaVersion!==1||!oe(e.sourceRoot)||!oe(e.workspacePath)||ae(e.sourceRoot)!==e.sourceRoot||ae(e.workspacePath)!==e.workspacePath||!R(e.workspacePath).isDirectory()||(R(e.workspacePath).mode&63)!==0||ce(e.sourceRoot,e.workspacePath)===""||ce(e.sourceRoot,e.workspacePath).split(Pe)[0]!==".."||J(e.sourceRoot,["rev-parse","--show-toplevel"])!==e.sourceRoot||J(e.workspacePath,["rev-parse","--show-toplevel"])!==e.workspacePath||J(e.sourceRoot,["rev-parse","HEAD"])!==e.baseSha||!/^[a-f0-9]{40,64}$/.test(r)||J(e.workspacePath,["rev-parse","HEAD"])!==r||J(e.sourceRoot,["symbolic-ref","--short","HEAD"])!==e.executionBranch||J(e.workspacePath,["symbolic-ref","--short","HEAD"])!==e.executionBranch||t.length===0||t.length>he||t.some(f=>!ue(f))||new Set(t).size!==t.length)throw new Error("authority-invalid");if(k(e.workspacePath,["merge-base","--is-ancestor",e.baseSha,r]),!fe(e.sourceRoot,e.workspacePath,r,t,o))throw new Error("source-snapshot-mismatch");const s=z(e.workspacePath,!0),c=G(s),y=new Set(t);if(c.paths.some(f=>!y.has(f)||a.includes(f)))throw new Error("path-unclaimed");if(n&&!n())throw new Error("candidate-raced");for(const f of c.paths)E(e.workspacePath,f),E(e.sourceRoot,f);const P=[k(e.workspacePath,["diff","--binary","--no-ext-diff","--no-textconv","HEAD","--"]),...c.untracked.map(f=>Me(e.workspacePath,f))],d=Buffer.concat(P.map(f=>Buffer.concat([f,Buffer.from(`
2
- `)])));if(d.byteLength===0||d.byteLength>Q||!z(e.workspacePath,!0).equals(s)||n&&!n()||!fe(e.sourceRoot,e.workspacePath,r,t,o))throw new Error("patch-raced");if(be(e.sourceRoot,d,!0),!z(e.workspacePath,!0).equals(s)||n&&!n()||!fe(e.sourceRoot,e.workspacePath,r,t,o))throw new Error("patch-raced");if(be(e.sourceRoot,d,!1),G(z(e.sourceRoot),!0,!!o).paths.some(f=>!y.has(f)&&f!==te)||o&&!ne(e.sourceRoot,o)||t.some(f=>!Ge(e.workspacePath,e.sourceRoot,f))||J(e.sourceRoot,["rev-parse","HEAD"])!==e.baseSha||J(e.sourceRoot,["symbolic-ref","--short","HEAD"])!==e.executionBranch)throw new Error("admission-raced");return Object.freeze({schemaVersion:1,outcome:"admitted-unverified",baseSha:e.baseSha,executionBranch:e.executionBranch,changedPaths:Object.freeze([...c.paths]),patchSha256:F("sha256").update(d).digest("hex")})}catch{throw new Error("private-execution-isolated-admission-unverified")}}async function it(e,t,r,o=e.baseSha,n=!1){try{const a=await Ae(e.sourceRoot,t,e.executionBranch,r),s=i(e.workspacePath,".neocortex","state.json"),c=R(s);if(!c.isFile()||c.isSymbolicLink()||c.size>Q)throw new Error("candidate-state-invalid");Se(l(s,"utf8"),t,a);const y=W(e,a,o,void 0,void 0,n?[".neocortex/state.json"]:[]);return await $e(e.sourceRoot,t,e.executionBranch,r),y}catch{throw new Error("private-execution-isolated-admission-unverified")}}function at(e,t,r,o,n){try{if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(t)||!/^P[1-9][0-9]*$/.test(r)||!/^[a-f0-9]{64}$/.test(o)||!/^[a-f0-9]{64}$/.test(n)||!ne(e.sourceRoot,n))throw new Error("claim-invalid");const a=JSON.parse(l(i(e.sourceRoot,te),"utf8")),s=a&&typeof a=="object"&&!Array.isArray(a)?a.operations?.[o]:void 0;if(!s||typeof s!="object"||Array.isArray(s)||s.claimId!==t||s.epicId!==r)throw new Error("claim-sidecar-mismatch");const c=G(z(e.workspacePath,!0)),y=`docs/epics/epic-${r}.md`,h=".neocortex/state.json",P=new RegExp(`^docs/stories/${r}\\.[0-9]{2}\\.story\\.md$`),d=c.paths.filter(w=>P.test(w));if(!c.paths.includes(y)||!c.paths.includes(h)||d.length===0||d.length>99||c.paths.some(w=>w!==y&&w!==h&&w!=="NEOCORTEX.md"&&!P.test(w)))throw new Error("artifact-scope-invalid");const p=d.map(w=>w.slice(13,-9)).sort();if(p.some((w,x)=>w!==`${r}.${String(x+1).padStart(2,"0")}`))throw new Error("story-sequence-invalid");for(const w of[y,...d])try{throw R(i(e.sourceRoot,w)),new Error("artifact-already-exists")}catch(x){if(x.code!=="ENOENT")throw x}const f=(w,x)=>{E(e.workspacePath,w);const Y=l(i(e.workspacePath,w),"utf8");return Buffer.byteLength(Y)>Q?null:/^---\r?\n([\s\S]{1,8192}?)\r?\n---(?:\r?\n|$)/.exec(Y)?.[1]?.split(/\r?\n/).find(ie=>ie.startsWith(`${x}:`))?.slice(x.length+1).trim()?.replace(/^(["'])(.*)\1$/,"$2")??null};if(f(y,"id")!==r||d.some((w,x)=>f(w,"id")!==p[x]||f(w,"epic_id")!==r))throw new Error("artifact-id-invalid");E(e.workspacePath,h);const g=JSON.parse(l(i(e.workspacePath,h),"utf8"));if(!g||typeof g!="object"||Array.isArray(g))throw new Error("state-invalid");const _=g,v=_.epics,O=_.stories,A=v?.[r],j=_.epic_id_ledger;if(_.schema_version!==1||!A||A.id!==r||A.status!=="memory-updated"||!Array.isArray(A.stories)||A.stories.length!==p.length||A.stories.some((w,x)=>w!==p[x])||!O||p.some(w=>{const x=O[w];return!x||x.id!==w||x.epic_id!==r})||!j||!Array.isArray(j.reserved_ids)||!j.reserved_ids.includes(r))throw new Error("state-claim-mismatch");E(e.sourceRoot,h);const u=JSON.parse(l(i(e.sourceRoot,h),"utf8")),S=u.epics,b=u.stories;if(!S||!b||S[r]!==void 0||p.some(w=>b[w]!==void 0))throw new Error("state-claim-conflict");const{[r]:q,...C}=v,$={...O};for(const w of p)delete $[w];const{epic_id_ledger:M,last_updated:B,...L}=u,{epic_id_ledger:V,last_updated:X,...K}=_;if(!T(C,S)||!T($,b)||!T({...K,epics:void 0,stories:void 0},{...L,epics:void 0,stories:void 0}))throw new Error("state-unrelated-drift");const D=u.epic_id_ledger&&typeof u.epic_id_ledger=="object"?u.epic_id_ledger.reserved_ids:void 0,{reserved_ids:U,...m}=j,N=u.epic_id_ledger&&typeof u.epic_id_ledger=="object"?u.epic_id_ledger:{schema_version:1},{reserved_ids:H,...ee}=N;if(D!==void 0&&(!Array.isArray(D)||D.some(w=>!j.reserved_ids.includes(w)))||!T(m,ee))throw new Error("ledger-drift");return W(e,c.paths,e.baseSha,n)}catch{throw new Error("private-execution-epic-claim-admission-unverified")}}function ct(e,t,r,o,n,a){try{if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(t)||!/^P[1-9][0-9]{0,11}$/.test(r)||!/^[a-f0-9]{64}$/.test(o)||!/^[a-f0-9]{64}$/.test(n)||typeof a!="string"||!a.trim()||a.length>16384||!ne(e.sourceRoot,n))throw new Error("planning-claim-invalid");const s=JSON.parse(l(i(e.sourceRoot,te),"utf8")),c=s&&typeof s=="object"&&!Array.isArray(s)?s.operations?.[o]:void 0;if(!c||typeof c!="object"||Array.isArray(c)||c.claimId!==t||c.epicId!==r)throw new Error("planning-claim-sidecar-mismatch");const y=`.neocortex/planning/epic-${r}`,h=`${y}/idea.json`,P=`${y}/diagnosis.md`,d=`${y}/enriched-prompt.md`,p=".neocortex/planning/planning.json",f=[h,P,d,p],g=G(z(e.workspacePath,!0));if(g.paths.length!==f.length||g.paths.some(x=>!f.includes(x)))throw new Error("planning-artifact-scope-invalid");for(const x of[h,P,d]){E(e.workspacePath,x);try{throw R(i(e.sourceRoot,x)),new Error("planning-artifact-already-exists")}catch(Y){if(Y.code!=="ENOENT")throw Y}}const _=(x,Y)=>{const Z=R(i(e.workspacePath,x));if(!Z.isFile()||Z.isSymbolicLink()||Z.size<1||Z.size>Y)throw new Error("planning-artifact-invalid");return l(i(e.workspacePath,x),"utf8")},v=JSON.parse(_(h,32*1024));if(!v||typeof v!="object"||Array.isArray(v)||v.epic_id!==r||v.status!=="diagnosed"||typeof v.raw_input!="string"||v.raw_input!==a)throw new Error("planning-idea-invalid");const O=_(P,256*1024),A=_(d,256*1024),j=(x,Y)=>{const Z=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(x.replace(/\r\n/g,`
3
- `))?.[1];if(!Z)return!1;const ge=Z.split(`
4
- `),se=ie=>{const me=ge.filter(xe=>xe.startsWith(`${ie}:`));return me.length===1?me[0].slice(ie.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0};return se("epic_id")===r&&I(se("step"),Y)&&se("status")==="completed"};if(!j(O,de)||!j(A,He))throw new Error("planning-document-identity-invalid");E(e.workspacePath,p),E(e.sourceRoot,p);const u=JSON.parse(_(p,128*1024)),S=re(i(e.sourceRoot,p))?JSON.parse(l(i(e.sourceRoot,p),"utf8")):void 0;if(!u||typeof u!="object"||Array.isArray(u)||!("epics"in u)||!u.epics||typeof u.epics!="object"||Array.isArray(u.epics)||S!==void 0&&(!S||typeof S!="object"||Array.isArray(S)||!("epics"in S)||!S.epics||typeof S.epics!="object"||Array.isArray(S.epics)))throw new Error("planning-index-invalid");const b=u,q=b.epics,C=q[r],$=C,M=$?.output_files;if(!C||typeof C!="object"||Array.isArray(C)||$?.id!==r||$.status!=="diagnosed"||$.idea!==v.raw_input||!Array.isArray($.steps_completed)||$.steps_completed.length!==1||!I($.steps_completed[0],de)||typeof $.created_at!="string"||!Number.isFinite(Date.parse($.created_at))||$.completed_at!==null||!M||typeof M!="object"||Array.isArray(M)||!T(M,{diagnosis:`${y}/diagnosis.md`})||!T(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:B,epics:L,...V}=b,X=S,K=X?.epics,{last_scan:D,epics:U,...m}=X??{},{[r]:N,...H}=q;if(K?.[r]!==void 0||!T(H,K??{})||X!==void 0&&!T(V,m)||X===void 0&&(Object.keys(q).length!==1||!T(Object.keys(b).sort(),["version","next_epic_id","last_scan","existing_epics_discovered","epics"].sort())||b.version!=="1.0.0"||b.next_epic_id!==1||!T(b.existing_epics_discovered,[]))||typeof b.last_scan!="string"||!Number.isFinite(Date.parse(b.last_scan)))throw new Error("planning-index-drift");const ee=f.map(x=>F("sha256").update(l(i(e.workspacePath,x))).digest("hex")),w=()=>f.every((x,Y)=>{try{return E(e.workspacePath,x),F("sha256").update(l(i(e.workspacePath,x))).digest("hex")===ee[Y]}catch{return!1}});return W(e,f,e.baseSha,n,w)}catch{throw new Error("private-execution-planning-diagnosis-admission-unverified")}}function ht(e,t,r,o,n,a){try{if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(t)||!/^P[1-9][0-9]{0,11}$/.test(r)||!/^[a-f0-9]{64}$/.test(o)||!/^[a-f0-9]{64}$/.test(n)||!/^[a-f0-9]{64}$/.test(a))throw new Error("planning-research-binding-invalid");const s=".neocortex/state.json",c=".neocortex/planning/planning.json",y=`.neocortex/planning/epic-${r}`,h=`${y}/research.md`;if(E(e.sourceRoot,s),E(e.workspacePath,s),E(e.sourceRoot,c),E(e.workspacePath,c),E(e.sourceRoot,h),E(e.workspacePath,h),R(i(e.sourceRoot,s)).size>8*1024*1024||R(i(e.workspacePath,s)).size>8*1024*1024||R(i(e.sourceRoot,c)).size>128*1024||R(i(e.workspacePath,c)).size>128*1024)throw new Error("planning-research-source-size-invalid");const P=l(i(e.sourceRoot,s));if(F("sha256").update(P).digest("hex")!==a||!P.equals(l(i(e.workspacePath,s))))throw new Error("planning-research-state-drift");const d=JSON.parse(P.toString("utf8")),p=Fe(d,t,r);if(p.diagnosisReceiptId!==o||p.intakeRevision!==n)throw new Error("planning-research-predecessor-mismatch");const g=d.epics[r].createEpicPlanningPhysical.artifactDigests;for(const[D,U]of Object.entries({idea:`${y}/idea.json`,diagnosis:`${y}/diagnosis.md`,enrichment:`${y}/enriched-prompt.md`,index:c}))if(E(e.sourceRoot,U),F("sha256").update(l(i(e.sourceRoot,U))).digest("hex")!==g[D])throw new Error("planning-research-source-artifact-drift");try{throw R(i(e.sourceRoot,h)),new Error("planning-research-already-exists")}catch(D){if(D.code!=="ENOENT")throw D}const _=[h,c],v=G(z(e.workspacePath,!0));if(v.paths.length!==_.length||v.paths.some(D=>!_.includes(D)))throw new Error("planning-research-write-scope-invalid");const O=R(i(e.workspacePath,h));if(!O.isFile()||O.isSymbolicLink()||O.size<64||O.size>256*1024)throw new Error("planning-research-document-invalid");const A=l(i(e.workspacePath,h),"utf8"),j=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(A.replace(/\r\n/g,`
5
- `))?.[1],u=D=>{const U=j?.split(`
6
- `).filter(m=>m.startsWith(`${D}:`))??[];return U.length===1?U[0].slice(D.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0};if(!j||u("epic_id")!==r||u("status")!=="completed"||!I(u("step"),we)||!A.slice(j.length+8).trim())throw new Error("planning-research-document-identity-invalid");const S=JSON.parse(l(i(e.sourceRoot,c),"utf8")),b=JSON.parse(l(i(e.workspacePath,c),"utf8"));if(!S||typeof S!="object"||Array.isArray(S)||!b||typeof b!="object"||Array.isArray(b))throw new Error("planning-research-index-invalid");const q=S,C=b,$=q.epics,M=C.epics,B=$?.[r];if(!$||Array.isArray($)||!M||Array.isArray(M)||!B||Array.isArray(B)||B.id!==r||B.idea!==p.rawIntent||B.status!=="diagnosed"||!Array.isArray(B.steps_completed)||B.steps_completed.length!==1||!I(B.steps_completed[0],de)||!T(B.output_files,{diagnosis:`${y}/diagnosis.md`})||typeof C.last_scan!="string"||!Number.isFinite(Date.parse(C.last_scan)))throw new Error("planning-research-index-predecessor-invalid");const L={...B,status:"researched",steps_completed:[...B.steps_completed,u("step")],output_files:{diagnosis:`${y}/diagnosis.md`,research:h}},V={...q,last_scan:C.last_scan,epics:{...$,[r]:L}};if(!T(C,V))throw new Error("planning-research-index-drift");const X=_.map(D=>F("sha256").update(l(i(e.workspacePath,D))).digest("hex")),K=()=>_.every((D,U)=>{try{return E(e.workspacePath,D),F("sha256").update(l(i(e.workspacePath,D))).digest("hex")===X[U]}catch{return!1}});return W(e,_,e.baseSha,void 0,K)}catch{throw new Error("private-execution-planning-research-admission-unverified")}}function dt(e,t,r,o,n,a,s){try{if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(t)||!/^P[1-9][0-9]{0,11}$/.test(r)||[o,n,a,s].some(m=>!/^[a-f0-9]{64}$/.test(m)))throw new Error("planning-generation-binding-invalid");const c=".neocortex/state.json",y=".neocortex/planning/planning.json",h=`.neocortex/planning/epic-${r}`,P=`docs/epics/epic-${r}.md`;for(const m of[c,y,`${h}/idea.json`,`${h}/diagnosis.md`,`${h}/enriched-prompt.md`,`${h}/research.md`]){E(e.sourceRoot,m),E(e.workspacePath,m);const N=l(i(e.sourceRoot,m));if(m!==y&&!N.equals(l(i(e.workspacePath,m)))||!N.equals(k(e.sourceRoot,["show",`HEAD:${m}`])))throw new Error("planning-generation-predecessor-uncommitted")}const d=l(i(e.sourceRoot,c));if(d.byteLength>8*1024*1024||F("sha256").update(d).digest("hex")!==s)throw new Error("planning-generation-state-drift");const p=JSON.parse(d.toString("utf8")),f=ze(p,t,r);if(f.diagnosisReceiptId!==o||f.researchReceiptId!==n||f.intakeRevision!==a)throw new Error("planning-generation-predecessor-mismatch");const g=p.epics[r],_=g.createEpicPlanningPhysical.artifactDigests,v=g.createEpicPlanningResearchPhysical.artifactDigests,O={idea:`${h}/idea.json`,diagnosis:`${h}/diagnosis.md`,enrichment:`${h}/enriched-prompt.md`,research:`${h}/research.md`};for(const[m,N]of Object.entries(O)){const H=m==="research"?v.research:_[m];if(F("sha256").update(l(i(e.sourceRoot,N))).digest("hex")!==H)throw new Error("planning-generation-artifact-drift")}if(F("sha256").update(l(i(e.sourceRoot,y))).digest("hex")!==v.index)throw new Error("planning-generation-index-drift");const A=G(z(e.workspacePath,!0)),j=new RegExp(`^docs/stories/${r}\\.([0-9]{2})\\.story\\.md$`),u=A.paths.filter(m=>j.test(m)).sort((m,N)=>Number(j.exec(m)[1])-Number(j.exec(N)[1]));if(u.length<1||u.length>24||u.some((m,N)=>j.exec(m)[1]!==String(N+1).padStart(2,"0"))||A.paths.length!==u.length+2||A.paths.some(m=>m!==P&&m!==y&&!j.test(m)))throw new Error("planning-generation-write-scope-invalid");const S=[P,y,...u];for(const m of[P,...u]){E(e.sourceRoot,m),E(e.workspacePath,m);try{throw R(i(e.sourceRoot,m)),new Error("planning-generation-path-collision")}catch(H){if(H.code!=="ENOENT")throw H}const N=R(i(e.workspacePath,m));if(!N.isFile()||N.isSymbolicLink()||N.size<128||N.size>(m===P?512:128)*1024)throw new Error("planning-generation-document-invalid")}const b=(m,N)=>{const ee=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(m.replace(/\r\n/g,`
1
+ import{execFileSync as St,spawnSync as Pt}from"node:child_process";import{createHash as B}from"node:crypto";import{existsSync as rt,lstatSync as b,readFileSync as p,realpathSync as at,writeFileSync as pt}from"node:fs";import{isAbsolute as ot,join as i,relative as ct,sep as wt}from"node:path";import{isDeepStrictEqual as $}from"node:util";import{readPrivateYoloFrozenWriteSet as $t,verifyPrivateYoloCandidateWriteSet as Ot,verifyPrivateYoloCleanBaseline as Tt}from"./clean-baseline.js";import{PRIVATE_EPIC_PENDING_SIDECAR as et}from"./isolated-workspace.js";import{loadPactPrivateAnswers as jt}from"../commands/architecture-answers.js";import{derivePactWriteSet as vt}from"./pact-write-set.js";import{deriveUxCandidateWriteSet as Nt,deriveUxWriteSet as Dt}from"./ux-write-set.js";import{validateUxCandidateSource as Bt}from"./ux-source-validation.js";import{validatePactTestSource as Ft}from"./pact-test-source.js";import{classifyProjectMemoryUpdate as Ct}from"../memory/project-memory-writer.js";import{inspectPactToolchain as Lt,planPactToolchainManifest as zt}from"./pact-toolchain.js";import{acceptedPlanningDiagnosisPredecessor as Ht}from"./planning-diagnosis-checkpoint.js";import{acceptedPlanningResearchPredecessor as Jt}from"./planning-research-checkpoint.js";import{confirmPropertyTestPlan as _t,renderPropertyTestConfiguration as Mt}from"./property-test-plan.js";import{validatePropertyTestTypeScriptSource as Gt}from"./property-test-source.js";const Z=16*1024*1024,ht=1024,dt="acd455ed0e39d98b90fb57391db75e366e4c5604db043e03a89a20e33d643c3c",qt="81f50aaa801c1660eabe46e645501acbfb3e9873410c991e1496c014ca75c369",bt="fa2194f89c01f07e225fd6f39e98e679f628e072239b6cd0af3ee527f0722518",Ut="8636f22ec5950410902448ee1e9cb4947359ac98df518742bddbbb367468e3ae";function I(t,r){return typeof t=="string"&&t.length<=128&&B("sha256").update(t).digest("hex")===r}function gt(){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 K(t,r){return St("git",[...r],{cwd:t,env:gt(),stdio:["ignore","pipe","pipe"],timeout:3e4,maxBuffer:Z})}function J(t,r){return K(t,r).toString("utf8").trim()}function F(t,r=!1){return K(t,["status","--porcelain=v1","-z","--untracked-files=all",...r?["--ignored=matching"]:[]])}function ut(t){return!!t&&!ot(t)&&!t.includes("\\")&&!t.includes("\0")&&!t.split("/").some(r=>!r||r==="."||r===".."||r===".git")}function y(t,r){const e=r.split("/");let n=t;for(const s of e.slice(0,-1)){n=i(n,s);try{const a=b(n);if(!a.isDirectory()||a.isSymbolicLink())throw new Error("path-boundary")}catch(a){if(a.code==="ENOENT")return;throw a}}try{const s=b(i(t,r));if(!s.isFile()||s.isSymbolicLink()||s.size>Z)throw new Error("path-boundary")}catch(s){if(s.code!=="ENOENT")throw s}}function xt(t){const r=[...t.matchAll(/\/\/\s*arch:keep-start[^\n]*\n[\s\S]*?\/\/\s*arch:keep-end[^\n]*/g)].map(s=>s[0]),e=(t.match(/arch:keep-start/g)??[]).length,n=(t.match(/arch:keep-end/g)??[]).length;if(e!==n||e!==r.length)throw new Error("architecture-keep-marker-invalid");return r}function M(t,r=!1,e=!1){const n=[],s=[];for(const a of t.toString("utf8").split("\0").filter(Boolean)){if(a.length<4||a[2]!==" ")throw new Error("status-invalid");const o=a.slice(0,2),d=a.slice(3);if(!ut(d)||o!=="??"&&o!==" M"&&o!==" D"&&!(e&&o==="!!"&&d===et))throw new Error("status-invalid");n.push(d),o==="??"&&s.push(d)}if(!r&&n.length===0||n.length>ht||new Set(n).size!==n.length)throw new Error("status-invalid");return{paths:n.sort(),untracked:s.sort()}}function mt(t,r,e,n){const s=K(r,["ls-tree","-z",e,"--",n]).toString("utf8");if(!s)try{return b(i(t,n)),!1}catch(o){return o.code==="ENOENT"}const a=/^([0-7]{6}) blob [a-f0-9]{40,64}\t([^\0]+)\0$/.exec(s);if(!a||a[2]!==n||!["100644","100755"].includes(a[1]))return!1;try{const o=b(i(t,n));return!o.isFile()||o.isSymbolicLink()||o.size>Z||!!(o.mode&73)!=(a[1]==="100755")?!1:p(i(t,n)).equals(K(r,["show",`${e}:${n}`]))}catch{return!1}}function nt(t,r){try{const e=i(t,et),n=b(i(t,".neocortex")),s=b(e);return n.isDirectory()&&!n.isSymbolicLink()&&n.uid===process.getuid?.()&&(n.mode&18)===0&&s.isFile()&&!s.isSymbolicLink()&&s.uid===process.getuid?.()&&(s.mode&63)===0&&s.size>0&&s.size<=128*1024&&B("sha256").update(p(e)).digest("hex")===r}catch{return!1}}function ft(t,r,e,n,s){const a=new Set(n),o=M(F(t),!0,!!s);return(!s||nt(t,s))&&o.paths.every(d=>a.has(d)||d===et&&!!s&&nt(t,s))&&n.every(d=>mt(t,r,e,d))}function Yt(t,r){const e=Pt("git",["diff","--no-index","--binary","--no-ext-diff","--","/dev/null",r],{cwd:t,env:gt(),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 Rt(t,r,e){const n=Pt("git",["apply",...e?["--check"]:[],"--binary","-"],{cwd:t,env:gt(),input:r,encoding:"buffer",timeout:3e4,maxBuffer:Z});if(n.error||n.status!==0)throw new Error("apply-failed")}function lt(t,r,e){const n=i(t,e),s=i(r,e);try{const a=b(n),o=b(s);return a.isFile()&&o.isFile()&&(a.mode&73)===(o.mode&73)&&p(n).equals(p(s))}catch(a){if(a.code!=="ENOENT")return!1;try{return b(n),!1}catch(o){if(o.code!=="ENOENT")return!1}try{return b(s),!1}catch(o){return o.code==="ENOENT"}}}function de(t,r,e){try{if(process.platform!=="linux"||t.schemaVersion!==1||!ot(t.sourceRoot)||!ot(t.workspacePath)||at(t.sourceRoot)!==t.sourceRoot||at(t.workspacePath)!==t.workspacePath||!b(t.workspacePath).isDirectory()||(b(t.workspacePath).mode&63)!==0||ct(t.sourceRoot,t.workspacePath)===""||ct(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||rt(i(t.workspacePath,".git","objects","info","alternates"))||F(t.workspacePath,!0).byteLength!==0||r.length===0||r.length>ht||r.some(n=>!ut(n))||new Set(r).size!==r.length)throw new Error("boundary-invalid");if(K(t.workspacePath,["merge-base","--is-ancestor",t.baseSha,e]),!ft(t.sourceRoot,t.workspacePath,e,r))throw new Error("boundary-raced")}catch{throw new Error("private-execution-isolated-snapshot-unverified")}}function q(t,r,e,n,s,a=[]){try{if(process.platform!=="linux"||t.schemaVersion!==1||!ot(t.sourceRoot)||!ot(t.workspacePath)||at(t.sourceRoot)!==t.sourceRoot||at(t.workspacePath)!==t.workspacePath||!b(t.workspacePath).isDirectory()||(b(t.workspacePath).mode&63)!==0||ct(t.sourceRoot,t.workspacePath)===""||ct(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>ht||r.some(l=>!ut(l))||new Set(r).size!==r.length)throw new Error("authority-invalid");if(K(t.workspacePath,["merge-base","--is-ancestor",t.baseSha,e]),!ft(t.sourceRoot,t.workspacePath,e,r,n))throw new Error("source-snapshot-mismatch");const o=F(t.workspacePath,!0),d=M(o),m=new Set(r);if(d.paths.some(l=>!m.has(l)||a.includes(l)))throw new Error("path-unclaimed");if(s&&!s())throw new Error("candidate-raced");for(const l of d.paths)y(t.workspacePath,l),y(t.sourceRoot,l);const P=[K(t.workspacePath,["diff","--binary","--no-ext-diff","--no-textconv","HEAD","--"]),...d.untracked.map(l=>Yt(t.workspacePath,l))],c=Buffer.concat(P.map(l=>Buffer.concat([l,Buffer.from(`
2
+ `)])));if(c.byteLength===0||c.byteLength>Z||!F(t.workspacePath,!0).equals(o)||s&&!s()||!ft(t.sourceRoot,t.workspacePath,e,r,n))throw new Error("patch-raced");if(Rt(t.sourceRoot,c,!0),!F(t.workspacePath,!0).equals(o)||s&&!s()||!ft(t.sourceRoot,t.workspacePath,e,r,n))throw new Error("patch-raced");if(Rt(t.sourceRoot,c,!1),M(F(t.sourceRoot),!0,!!n).paths.some(l=>!m.has(l)&&l!==et)||n&&!nt(t.sourceRoot,n)||r.some(l=>!lt(t.workspacePath,t.sourceRoot,l))||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([...d.paths]),patchSha256:B("sha256").update(c).digest("hex")})}catch{throw new Error("private-execution-isolated-admission-unverified")}}async function ue(t,r,e,n=t.baseSha,s=!1){try{const a=await $t(t.sourceRoot,r,t.executionBranch,e),o=i(t.workspacePath,".neocortex","state.json"),d=b(o);if(!d.isFile()||d.isSymbolicLink()||d.size>Z)throw new Error("candidate-state-invalid");Ot(p(o,"utf8"),r,a);const m=q(t,a,n,void 0,void 0,s?[".neocortex/state.json"]:[]);return await Tt(t.sourceRoot,r,t.executionBranch,e),m}catch{throw new Error("private-execution-isolated-admission-unverified")}}function fe(t,r,e,n,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]*$/.test(e)||!/^[a-f0-9]{64}$/.test(n)||!/^[a-f0-9]{64}$/.test(s)||!nt(t.sourceRoot,s))throw new Error("claim-invalid");const a=JSON.parse(p(i(t.sourceRoot,et),"utf8")),o=a&&typeof a=="object"&&!Array.isArray(a)?a.operations?.[n]:void 0;if(!o||typeof o!="object"||Array.isArray(o)||o.claimId!==r||o.epicId!==e)throw new Error("claim-sidecar-mismatch");const d=M(F(t.workspacePath,!0)),m=`docs/epics/epic-${e}.md`,u=".neocortex/state.json",P=new RegExp(`^docs/stories/${e}\\.[0-9]{2}\\.story\\.md$`),c=d.paths.filter(_=>P.test(_));if(!d.paths.includes(m)||!d.paths.includes(u)||c.length===0||c.length>99||d.paths.some(_=>_!==m&&_!==u&&_!=="NEOCORTEX.md"&&!P.test(_)))throw new Error("artifact-scope-invalid");const f=c.map(_=>_.slice(13,-9)).sort();if(f.some((_,R)=>_!==`${e}.${String(R+1).padStart(2,"0")}`))throw new Error("story-sequence-invalid");for(const _ of[m,...c])try{throw b(i(t.sourceRoot,_)),new Error("artifact-already-exists")}catch(R){if(R.code!=="ENOENT")throw R}const l=(_,R)=>{y(t.workspacePath,_);const W=p(i(t.workspacePath,_),"utf8");return Buffer.byteLength(W)>Z?null:/^---\r?\n([\s\S]{1,8192}?)\r?\n---(?:\r?\n|$)/.exec(W)?.[1]?.split(/\r?\n/).find(it=>it.startsWith(`${R}:`))?.slice(R.length+1).trim()?.replace(/^(["'])(.*)\1$/,"$2")??null};if(l(m,"id")!==e||c.some((_,R)=>l(_,"id")!==f[R]||l(_,"epic_id")!==e))throw new Error("artifact-id-invalid");y(t.workspacePath,u);const h=JSON.parse(p(i(t.workspacePath,u),"utf8"));if(!h||typeof h!="object"||Array.isArray(h))throw new Error("state-invalid");const w=h,v=w.epics,T=w.stories,A=v?.[e],j=w.epic_id_ledger;if(w.schema_version!==1||!A||A.id!==e||A.status!=="memory-updated"||!Array.isArray(A.stories)||A.stories.length!==f.length||A.stories.some((_,R)=>_!==f[R])||!T||f.some(_=>{const R=T[_];return!R||R.id!==_||R.epic_id!==e})||!j||!Array.isArray(j.reserved_ids)||!j.reserved_ids.includes(e))throw new Error("state-claim-mismatch");y(t.sourceRoot,u);const g=JSON.parse(p(i(t.sourceRoot,u),"utf8")),S=g.epics,x=g.stories;if(!S||!x||S[e]!==void 0||f.some(_=>x[_]!==void 0))throw new Error("state-claim-conflict");const{[e]:U,...z}=v,O={...T};for(const _ of f)delete O[_];const{epic_id_ledger:G,last_updated:C,...L}=g,{epic_id_ledger:V,last_updated:X,...Q}=w;if(!$(z,S)||!$(O,x)||!$({...Q,epics:void 0,stories:void 0},{...L,epics:void 0,stories:void 0}))throw new Error("state-unrelated-drift");const D=g.epic_id_ledger&&typeof g.epic_id_ledger=="object"?g.epic_id_ledger.reserved_ids:void 0,{reserved_ids:Y,...E}=j,N=g.epic_id_ledger&&typeof g.epic_id_ledger=="object"?g.epic_id_ledger:{schema_version:1},{reserved_ids:H,...tt}=N;if(D!==void 0&&(!Array.isArray(D)||D.some(_=>!j.reserved_ids.includes(_)))||!$(E,tt))throw new Error("ledger-drift");return q(t,d.paths,t.baseSha,s)}catch{throw new Error("private-execution-epic-claim-admission-unverified")}}function le(t,r,e,n,s,a){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(n)||!/^[a-f0-9]{64}$/.test(s)||typeof a!="string"||!a.trim()||a.length>16384||!nt(t.sourceRoot,s))throw new Error("planning-claim-invalid");const o=JSON.parse(p(i(t.sourceRoot,et),"utf8")),d=o&&typeof o=="object"&&!Array.isArray(o)?o.operations?.[n]:void 0;if(!d||typeof d!="object"||Array.isArray(d)||d.claimId!==r||d.epicId!==e)throw new Error("planning-claim-sidecar-mismatch");const m=`.neocortex/planning/epic-${e}`,u=`${m}/idea.json`,P=`${m}/diagnosis.md`,c=`${m}/enriched-prompt.md`,f=".neocortex/planning/planning.json",l=[u,P,c,f],h=M(F(t.workspacePath,!0));if(h.paths.length!==l.length||h.paths.some(R=>!l.includes(R)))throw new Error("planning-artifact-scope-invalid");for(const R of[u,P,c]){y(t.workspacePath,R);try{throw b(i(t.sourceRoot,R)),new Error("planning-artifact-already-exists")}catch(W){if(W.code!=="ENOENT")throw W}}const w=(R,W)=>{const k=b(i(t.workspacePath,R));if(!k.isFile()||k.isSymbolicLink()||k.size<1||k.size>W)throw new Error("planning-artifact-invalid");return p(i(t.workspacePath,R),"utf8")},v=JSON.parse(w(u,32*1024));if(!v||typeof v!="object"||Array.isArray(v)||v.epic_id!==e||v.status!=="diagnosed"||typeof v.raw_input!="string"||v.raw_input!==a)throw new Error("planning-idea-invalid");const T=w(P,256*1024),A=w(c,256*1024),j=(R,W)=>{const k=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(R.replace(/\r\n/g,`
3
+ `))?.[1];if(!k)return!1;const yt=k.split(`
4
+ `),st=it=>{const Et=yt.filter(At=>At.startsWith(`${it}:`));return Et.length===1?Et[0].slice(it.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0};return st("epic_id")===e&&I(st("step"),W)&&st("status")==="completed"};if(!j(T,dt)||!j(A,qt))throw new Error("planning-document-identity-invalid");y(t.workspacePath,f),y(t.sourceRoot,f);const g=JSON.parse(w(f,128*1024)),S=rt(i(t.sourceRoot,f))?JSON.parse(p(i(t.sourceRoot,f),"utf8")):void 0;if(!g||typeof g!="object"||Array.isArray(g)||!("epics"in g)||!g.epics||typeof g.epics!="object"||Array.isArray(g.epics)||S!==void 0&&(!S||typeof S!="object"||Array.isArray(S)||!("epics"in S)||!S.epics||typeof S.epics!="object"||Array.isArray(S.epics)))throw new Error("planning-index-invalid");const x=g,U=x.epics,z=U[e],O=z,G=O?.output_files;if(!z||typeof z!="object"||Array.isArray(z)||O?.id!==e||O.status!=="diagnosed"||O.idea!==v.raw_input||!Array.isArray(O.steps_completed)||O.steps_completed.length!==1||!I(O.steps_completed[0],dt)||typeof O.created_at!="string"||!Number.isFinite(Date.parse(O.created_at))||O.completed_at!==null||!G||typeof G!="object"||Array.isArray(G)||!$(G,{diagnosis:`${m}/diagnosis.md`})||!$(Object.keys(O).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:L,...V}=x,X=S,Q=X?.epics,{last_scan:D,epics:Y,...E}=X??{},{[e]:N,...H}=U;if(Q?.[e]!==void 0||!$(H,Q??{})||X!==void 0&&!$(V,E)||X===void 0&&(Object.keys(U).length!==1||!$(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||!$(x.existing_epics_discovered,[]))||typeof x.last_scan!="string"||!Number.isFinite(Date.parse(x.last_scan)))throw new Error("planning-index-drift");const tt=l.map(R=>B("sha256").update(p(i(t.workspacePath,R))).digest("hex")),_=()=>l.every((R,W)=>{try{return y(t.workspacePath,R),B("sha256").update(p(i(t.workspacePath,R))).digest("hex")===tt[W]}catch{return!1}});return q(t,l,t.baseSha,s,_)}catch{throw new Error("private-execution-planning-diagnosis-admission-unverified")}}function pe(t,r,e,n,s,a){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(n)||!/^[a-f0-9]{64}$/.test(s)||!/^[a-f0-9]{64}$/.test(a))throw new Error("planning-research-binding-invalid");const o=".neocortex/state.json",d=".neocortex/planning/planning.json",m=`.neocortex/planning/epic-${e}`,u=`${m}/research.md`;if(y(t.sourceRoot,o),y(t.workspacePath,o),y(t.sourceRoot,d),y(t.workspacePath,d),y(t.sourceRoot,u),y(t.workspacePath,u),b(i(t.sourceRoot,o)).size>8*1024*1024||b(i(t.workspacePath,o)).size>8*1024*1024||b(i(t.sourceRoot,d)).size>128*1024||b(i(t.workspacePath,d)).size>128*1024)throw new Error("planning-research-source-size-invalid");const P=p(i(t.sourceRoot,o));if(B("sha256").update(P).digest("hex")!==a||!P.equals(p(i(t.workspacePath,o))))throw new Error("planning-research-state-drift");const c=JSON.parse(P.toString("utf8")),f=Ht(c,r,e);if(f.diagnosisReceiptId!==n||f.intakeRevision!==s)throw new Error("planning-research-predecessor-mismatch");const h=c.epics[e].createEpicPlanningPhysical.artifactDigests;for(const[D,Y]of Object.entries({idea:`${m}/idea.json`,diagnosis:`${m}/diagnosis.md`,enrichment:`${m}/enriched-prompt.md`,index:d}))if(y(t.sourceRoot,Y),B("sha256").update(p(i(t.sourceRoot,Y))).digest("hex")!==h[D])throw new Error("planning-research-source-artifact-drift");try{throw b(i(t.sourceRoot,u)),new Error("planning-research-already-exists")}catch(D){if(D.code!=="ENOENT")throw D}const w=[u,d],v=M(F(t.workspacePath,!0));if(v.paths.length!==w.length||v.paths.some(D=>!w.includes(D)))throw new Error("planning-research-write-scope-invalid");const T=b(i(t.workspacePath,u));if(!T.isFile()||T.isSymbolicLink()||T.size<64||T.size>256*1024)throw new Error("planning-research-document-invalid");const A=p(i(t.workspacePath,u),"utf8"),j=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(A.replace(/\r\n/g,`
5
+ `))?.[1],g=D=>{const Y=j?.split(`
6
+ `).filter(E=>E.startsWith(`${D}:`))??[];return Y.length===1?Y[0].slice(D.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0};if(!j||g("epic_id")!==e||g("status")!=="completed"||!I(g("step"),bt)||!A.slice(j.length+8).trim())throw new Error("planning-research-document-identity-invalid");const S=JSON.parse(p(i(t.sourceRoot,d),"utf8")),x=JSON.parse(p(i(t.workspacePath,d),"utf8"));if(!S||typeof S!="object"||Array.isArray(S)||!x||typeof x!="object"||Array.isArray(x))throw new Error("planning-research-index-invalid");const U=S,z=x,O=U.epics,G=z.epics,C=O?.[e];if(!O||Array.isArray(O)||!G||Array.isArray(G)||!C||Array.isArray(C)||C.id!==e||C.idea!==f.rawIntent||C.status!=="diagnosed"||!Array.isArray(C.steps_completed)||C.steps_completed.length!==1||!I(C.steps_completed[0],dt)||!$(C.output_files,{diagnosis:`${m}/diagnosis.md`})||typeof z.last_scan!="string"||!Number.isFinite(Date.parse(z.last_scan)))throw new Error("planning-research-index-predecessor-invalid");const L={...C,status:"researched",steps_completed:[...C.steps_completed,g("step")],output_files:{diagnosis:`${m}/diagnosis.md`,research:u}},V={...U,last_scan:z.last_scan,epics:{...O,[e]:L}};if(!$(z,V))throw new Error("planning-research-index-drift");const X=w.map(D=>B("sha256").update(p(i(t.workspacePath,D))).digest("hex")),Q=()=>w.every((D,Y)=>{try{return y(t.workspacePath,D),B("sha256").update(p(i(t.workspacePath,D))).digest("hex")===X[Y]}catch{return!1}});return q(t,w,t.baseSha,void 0,Q)}catch{throw new Error("private-execution-planning-research-admission-unverified")}}function ge(t,r,e,n,s,a,o){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)||[n,s,a,o].some(E=>!/^[a-f0-9]{64}$/.test(E)))throw new Error("planning-generation-binding-invalid");const d=".neocortex/state.json",m=".neocortex/planning/planning.json",u=`.neocortex/planning/epic-${e}`,P=`docs/epics/epic-${e}.md`;for(const E of[d,m,`${u}/idea.json`,`${u}/diagnosis.md`,`${u}/enriched-prompt.md`,`${u}/research.md`]){y(t.sourceRoot,E),y(t.workspacePath,E);const N=p(i(t.sourceRoot,E));if(E!==m&&!N.equals(p(i(t.workspacePath,E)))||!N.equals(K(t.sourceRoot,["show",`HEAD:${E}`])))throw new Error("planning-generation-predecessor-uncommitted")}const c=p(i(t.sourceRoot,d));if(c.byteLength>8*1024*1024||B("sha256").update(c).digest("hex")!==o)throw new Error("planning-generation-state-drift");const f=JSON.parse(c.toString("utf8")),l=Jt(f,r,e);if(l.diagnosisReceiptId!==n||l.researchReceiptId!==s||l.intakeRevision!==a)throw new Error("planning-generation-predecessor-mismatch");const h=f.epics[e],w=h.createEpicPlanningPhysical.artifactDigests,v=h.createEpicPlanningResearchPhysical.artifactDigests,T={idea:`${u}/idea.json`,diagnosis:`${u}/diagnosis.md`,enrichment:`${u}/enriched-prompt.md`,research:`${u}/research.md`};for(const[E,N]of Object.entries(T)){const H=E==="research"?v.research:w[E];if(B("sha256").update(p(i(t.sourceRoot,N))).digest("hex")!==H)throw new Error("planning-generation-artifact-drift")}if(B("sha256").update(p(i(t.sourceRoot,m))).digest("hex")!==v.index)throw new Error("planning-generation-index-drift");const A=M(F(t.workspacePath,!0)),j=new RegExp(`^docs/stories/${e}\\.([0-9]{2})\\.story\\.md$`),g=A.paths.filter(E=>j.test(E)).sort((E,N)=>Number(j.exec(E)[1])-Number(j.exec(N)[1]));if(g.length<1||g.length>24||g.some((E,N)=>j.exec(E)[1]!==String(N+1).padStart(2,"0"))||A.paths.length!==g.length+2||A.paths.some(E=>E!==P&&E!==m&&!j.test(E)))throw new Error("planning-generation-write-scope-invalid");const S=[P,m,...g];for(const E of[P,...g]){y(t.sourceRoot,E),y(t.workspacePath,E);try{throw b(i(t.sourceRoot,E)),new Error("planning-generation-path-collision")}catch(H){if(H.code!=="ENOENT")throw H}const N=b(i(t.workspacePath,E));if(!N.isFile()||N.isSymbolicLink()||N.size<128||N.size>(E===P?512:128)*1024)throw new Error("planning-generation-document-invalid")}const x=(E,N)=>{const tt=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(E.replace(/\r\n/g,`
7
7
  `))?.[1]?.split(`
8
- `).filter(w=>w.startsWith(`${N}:`))??[];return ee.length===1?ee[0].slice(N.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0},q=l(i(e.workspacePath,P),"utf8");if(b(q,"id")!==r||b(q,"stories_count")!==String(u.length)||!q.includes("## Stories"))throw new Error("planning-generation-epic-invalid");for(const[m,N]of u.entries()){const H=l(i(e.workspacePath,N),"utf8");if(b(H,"id")!==`${r}.${String(m+1).padStart(2,"0")}`||b(H,"epic")!==r||b(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 C=JSON.parse(l(i(e.sourceRoot,y),"utf8")),$=JSON.parse(l(i(e.workspacePath,y),"utf8")),M=C.epics,B=$.epics,L=M?.[r],V=B?.[r];if(!M||!B||!L||!V||L.id!==r||L.status!=="researched"||!Array.isArray(L.steps_completed)||L.steps_completed.length!==2||!I(L.steps_completed[0],de)||!I(L.steps_completed[1],we)||!T(L.output_files,{diagnosis:`${h}/diagnosis.md`,research:`${h}/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(!I(X,Je))throw new Error("planning-generation-index-transition-invalid");const K={...C,last_scan:$.last_scan,epics:{...M,[r]:{...L,status:"generated",steps_completed:[...L.steps_completed,X],completed_at:V.completed_at,output_files:{...L.output_files,epic:P,stories:u}}}};if(!T($,K))throw new Error("planning-generation-index-transition-invalid");const D=S.map(m=>F("sha256").update(l(i(e.workspacePath,m))).digest("hex")),U=()=>S.every((m,N)=>{try{return E(e.workspacePath,m),F("sha256").update(l(i(e.workspacePath,m))).digest("hex")===D[N]}catch{return!1}});return W(e,S,e.baseSha,void 0,U)}catch{throw new Error("private-execution-planning-generation-admission-unverified")}}function ut(e,t){try{if(!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(t))throw new Error("story-id-invalid");const r=".neocortex/state.json";E(e.sourceRoot,r),E(e.workspacePath,r);const o=JSON.parse(l(i(e.sourceRoot,r),"utf8")),n=JSON.parse(l(i(e.workspacePath,r),"utf8"));if(!o||typeof o!="object"||Array.isArray(o)||!n||typeof n!="object"||Array.isArray(n))throw new Error("state-invalid");const a=o,s=n,c=a.stories,y=s.stories,h=c?.[t],P=y?.[t],d=h?.files_to_modify;if(a.schema_version!==1||s.schema_version!==1||!c||!y||!h||!P||h.id!==t||P.id!==t||P.epic_id!==h.epic_id||!Array.isArray(d)||d.length===0||d.length>he||d.some(b=>typeof b!="string"||!ue(b)||b.length>1024)||new Set(d).size!==d.length||!T(P.files_to_modify,d))throw new Error("write-set-invalid");const{[t]:p,...f}=c,{[t]:g,..._}=y,{stories:v,last_updated:O,...A}=a,{stories:j,last_updated:u,...S}=s;if(!T(_,f)||!T(S,A))throw new Error("state-unrelated-drift");return W(e,[...d].sort(),e.baseSha)}catch{throw new Error("private-execution-state-step-admission-unverified")}}function ft(e,t,r){const o=t==="sync-openapi"&&r==="sync-openapi-contract-v1"?["docs/architecture/api-contracts.md","docs/api/openapi.yaml"]:t==="tech-debt"&&r==="tech-debt-registry-v1"?[".neocortex/tech-debt-registry.json"]:void 0;if(!o)throw new Error("private-execution-project-step-admission-unverified");try{if(t==="tech-debt"){const n=".neocortex/tech-debt-registry.json";E(e.workspacePath,n);const a=JSON.parse(l(i(e.workspacePath,n),"utf8"));if(!a||typeof a!="object"||Array.isArray(a))throw new Error("registry-invalid");const s=a;if(s.schema_version!==2||s.version!==void 0&&s.version!==2||!Array.isArray(s.items))throw new Error("registry-invalid")}return W(e,o,e.baseSha)}catch{throw new Error("private-execution-project-step-admission-unverified")}}function lt(e,t,r,o,n){const a=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;if(!a||!/^P[1-9][0-9]{0,11}$/.test(o)||!/^[a-f0-9]{64}$/.test(n))throw new Error("private-execution-architecture-admission-unverified");try{E(e.workspacePath,".neocortex/state.json");const s=JSON.parse(l(i(e.workspacePath,".neocortex/state.json"),"utf8"));if(!s||typeof s!="object"||Array.isArray(s))throw new Error("state-invalid");const c=s,h=c.archPlan?.execution,P=c.epics;if(!h||h.currentStageCommand!==t||h.targetEpicId!==o||h.graphRevision!==n||!P||!Object.hasOwn(P,o))throw new Error("state-binding-mismatch");if(t==="update-memory"){if(h.continuationState!=="delegate"||h.reviewDecision?.decision!=="approved")throw new Error("memory-root-review-missing");const d="NEOCORTEX.md";if(!G(z(e.workspacePath,!0)).paths.includes(d))throw new Error("memory-effect-missing");E(e.sourceRoot,d),E(e.workspacePath,d);const p=l(i(e.sourceRoot,d),"utf8"),f=l(i(e.workspacePath,d),"utf8"),g="<!-- NEOCORTEX-MEMORY-START -->",_="<!-- NEOCORTEX-MEMORY-END -->",v=u=>{if(u.split(g).length!==2||u.split(_).length!==2||u.indexOf(g)>=u.indexOf(_))throw new Error("memory-markers-invalid");const S=u.indexOf(g)+g.length,b=u.indexOf(_);return{before:u.slice(0,S),body:u.slice(S,b),after:u.slice(b)}},O=v(p),A=v(f);if(O.before!==A.before||O.after!==A.after||O.body===A.body||Buffer.byteLength(f,"utf8")>32768||f.split(`
9
- `).length>240)throw new Error("memory-managed-block-invalid");const j=new Set(O.body.split(`
10
- `));for(const u of A.body.split(`
11
- `))j.has(u)||Be(u)}if(t==="arch-prd"){const d="docs/architecture/prd.md";if(!G(z(e.workspacePath,!0)).paths.includes(d))throw new Error("prd-effect-missing");if(E(e.workspacePath,d),R(i(e.workspacePath,d)).size===0)throw new Error("prd-empty")}if(t==="arch-api-contracts"||t==="arch-fitness-functions"||t==="arch-api-integrations"||t==="arch-database"||t==="arch-security"||t==="arch-design-system"||t==="arch-performance"||t==="arch-testing"||t==="arch-infrastructure"||t==="arch-review"){const d=G(z(e.workspacePath,!0)).paths;for(const p of a){if(!d.includes(p))throw new Error("architecture-required-effect-missing");if(E(e.workspacePath,p),R(i(e.workspacePath,p)).size===0)throw new Error("architecture-required-effect-empty");if(t==="arch-fitness-functions"){E(e.sourceRoot,p);const f=re(i(e.sourceRoot,p))?l(i(e.sourceRoot,p),"utf8"):"",g=l(i(e.workspacePath,p),"utf8"),_=_e(f),v=_e(g);if(!T(v,_))throw new Error("architecture-keep-marker-changed")}}}return W(e,a,e.baseSha)}catch{throw new Error("private-execution-architecture-admission-unverified")}}function pt(e,t,r,o){try{if(!/^P[1-9][0-9]{0,11}$/.test(t)||!/^[a-f0-9]{64}$/.test(r)||o.schemaVersion!==1||o.targetEpicId!==t)throw new Error("binding-invalid");const n=Ne(e.sourceRoot,t),a=je(e.workspacePath,t);if(!T(n,o)||!T(a,o))throw new Error("write-set-invalid");E(e.workspacePath,".neocortex/state.json");const s=JSON.parse(l(i(e.workspacePath,".neocortex/state.json"),"utf8"));if(!s||typeof s!="object"||Array.isArray(s))throw new Error("state-invalid");const c=s,h=c.archPlan?.execution,P=c.epics;if(!h||h.currentStageCommand!=="arch-ux-design"||h.continuationState!=="delegate"||h.targetEpicId!==t||h.graphRevision!==r||!P||!Object.hasOwn(P,t))throw new Error("stage-invalid");const d=G(z(e.workspacePath,!0)).paths;if(d.length!==o.pathCount||d.some(p=>!o.paths.includes(p)))throw new Error("agent-path-unclaimed");for(const p of o.paths){E(e.sourceRoot,p),E(e.workspacePath,p);const f=R(i(e.workspacePath,p));if(!f.isFile()||f.isSymbolicLink()||f.size<1)throw new Error("effect-empty");const g=new TextDecoder("utf-8",{fatal:!0}).decode(l(i(e.workspacePath,p)));if(!g.trim()||g.includes("\0"))throw new Error("effect-invalid")}return Te(e.workspacePath,o),W(e,o.paths,e.baseSha)}catch{throw new Error("private-execution-ux-admission-unverified")}}function gt(e,t,r,o,n,a){try{if(!/^P[1-9][0-9]{0,11}$/.test(t)||!/^[a-f0-9]{64}$/.test(r)||o.targetEpicId!==t||o.graphRevision!==r||n.schemaVersion!==1)throw new Error("binding-invalid");const s=Oe(e.sourceRoot);if(!s||!T(s.receipt,o))throw new Error("answers-invalid");const c=ve(e.sourceRoot,s.answers.generateProvider),y=ve(e.workspacePath,s.answers.generateProvider);if(c.outcome!=="ready"||y.outcome!=="ready"||!T(c.writeSet,n)||!T(y.writeSet,n))throw new Error("write-set-invalid");const h=G(z(e.workspacePath,!0)).paths;if(h.some(g=>!n.paths.includes(g)))throw new Error("agent-path-unclaimed");let P=0,d=0;for(const g of n.paths){if(E(e.sourceRoot,g),re(i(e.sourceRoot,g))||!h.includes(g))throw new Error("effect-missing-or-overwrite");E(e.workspacePath,g);const _=R(i(e.workspacePath,g));if(!_.isFile()||_.size<1)throw new Error("effect-empty");const v=new TextDecoder("utf-8",{fatal:!0}).decode(l(i(e.workspacePath,g))),O=n.interactions.find(j=>j.filePath===g);if(g!==n.providerPath&&!O)throw new Error("private-execution-pact-interaction-missing");const A=De(g,v,s.answers.brokerUrl,O,e.workspacePath);A.consumerBinding==="app-import-candidate"&&P++,A.consumerBinding==="mock-only-scaffold"&&d++}let p=n.paths;if(a){const g=Ce(e.sourceRoot,s.answers.generateProvider),_=v=>F("sha256").update(v).digest("hex");if(a.schemaVersion!==1||a.outcome!=="candidate-unverified"||a.executionVerified!==!1||a.sourceManifestSha256!==_(g.sourceText)||a.sourceLockSha256!==(g.sourceLockText===null?null:_(g.sourceLockText))||a.manifestText!==g.candidateText||!pe(e.sourceRoot,e.workspacePath,e.baseSha,"package.json")||!pe(e.sourceRoot,e.workspacePath,e.baseSha,"package-lock.json"))throw new Error("toolchain-binding-invalid");for(const v of["package.json","package-lock.json"]){E(e.sourceRoot,v),E(e.workspacePath,v);const O=v==="package.json"?g.sourceText:g.sourceLockText,A=re(i(e.workspacePath,v))?l(i(e.workspacePath,v),"utf8"):null;if(O!==A)throw new Error("toolchain-clone-raced")}if(Ee(i(e.workspacePath,"package.json"),a.manifestText),Ee(i(e.workspacePath,"package-lock.json"),a.lockText),Le(e.workspacePath,s.answers.generateProvider).outcome!=="manifest-aligned")throw new Error("toolchain-candidate-invalid");p=[...n.paths,"package.json","package-lock.json"]}const f=W(e,p,e.baseSha);return Object.freeze({...f,consumerBindingCandidateCount:P,consumerScaffoldCount:d})}catch{throw new Error("private-execution-pact-admission-unverified")}}export{lt as admitPrivateArchitectureStageWorkspace,at as admitPrivateEpicClaimWorkspace,dt as admitPrivateGenerateEpicWorkspace,ct as admitPrivateIdeaDiagnosisWorkspace,ht as admitPrivateIdeaResearchWorkspace,gt as admitPrivatePactWorkspace,ft as admitPrivateProjectStepWorkspace,ut as admitPrivateStateBoundStepWorkspace,pt as admitPrivateUxWorkspace,it as admitPrivateYoloFrozenWorkspace,st as verifyPrivateYoloSnapshotBoundary};
8
+ `).filter(_=>_.startsWith(`${N}:`))??[];return tt.length===1?tt[0].slice(N.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0},U=p(i(t.workspacePath,P),"utf8");if(x(U,"id")!==e||x(U,"stories_count")!==String(g.length)||!U.includes("## Stories"))throw new Error("planning-generation-epic-invalid");for(const[E,N]of g.entries()){const H=p(i(t.workspacePath,N),"utf8");if(x(H,"id")!==`${e}.${String(E+1).padStart(2,"0")}`||x(H,"epic")!==e||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 z=JSON.parse(p(i(t.sourceRoot,m),"utf8")),O=JSON.parse(p(i(t.workspacePath,m),"utf8")),G=z.epics,C=O.epics,L=G?.[e],V=C?.[e];if(!G||!C||!L||!V||L.id!==e||L.status!=="researched"||!Array.isArray(L.steps_completed)||L.steps_completed.length!==2||!I(L.steps_completed[0],dt)||!I(L.steps_completed[1],bt)||!$(L.output_files,{diagnosis:`${u}/diagnosis.md`,research:`${u}/research.md`})||typeof O.last_scan!="string"||!Number.isFinite(Date.parse(O.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(!I(X,Ut))throw new Error("planning-generation-index-transition-invalid");const Q={...z,last_scan:O.last_scan,epics:{...G,[e]:{...L,status:"generated",steps_completed:[...L.steps_completed,X],completed_at:V.completed_at,output_files:{...L.output_files,epic:P,stories:g}}}};if(!$(O,Q))throw new Error("planning-generation-index-transition-invalid");const D=S.map(E=>B("sha256").update(p(i(t.workspacePath,E))).digest("hex")),Y=()=>S.every((E,N)=>{try{return y(t.workspacePath,E),B("sha256").update(p(i(t.workspacePath,E))).digest("hex")===D[N]}catch{return!1}});return q(t,S,t.baseSha,void 0,Y)}catch{throw new Error("private-execution-planning-generation-admission-unverified")}}function me(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";y(t.sourceRoot,e),y(t.workspacePath,e);const n=JSON.parse(p(i(t.sourceRoot,e),"utf8")),s=JSON.parse(p(i(t.workspacePath,e),"utf8"));if(!n||typeof n!="object"||Array.isArray(n)||!s||typeof s!="object"||Array.isArray(s))throw new Error("state-invalid");const a=n,o=s,d=a.stories,m=o.stories,u=d?.[r],P=m?.[r],c=u?.files_to_modify;if(a.schema_version!==1||o.schema_version!==1||!d||!m||!u||!P||u.id!==r||P.id!==r||P.epic_id!==u.epic_id||!Array.isArray(c)||c.length===0||c.length>ht||c.some(x=>typeof x!="string"||!ut(x)||x.length>1024)||new Set(c).size!==c.length||!$(P.files_to_modify,c))throw new Error("write-set-invalid");const{[r]:f,...l}=d,{[r]:h,...w}=m,{stories:v,last_updated:T,...A}=a,{stories:j,last_updated:g,...S}=o;if(!$(w,l)||!$(S,A))throw new Error("state-unrelated-drift");return q(t,[...c].sort(),t.baseSha)}catch{throw new Error("private-execution-state-step-admission-unverified")}}function ye(t,r,e){if(r==="chaos-plan"&&e==="chaos-quarterly-v1")try{const s=new Date,a=`Q${Math.floor(s.getUTCMonth()/3)+1}-${s.getUTCFullYear()}`,o=M(F(t.workspacePath,!0)).paths,d=`tools/chaos/${a}-plan.md`,m=`.neocortex/chaos-history/${a}.md`,u=o.filter(h=>h.startsWith("tools/chaos/experiments/")),P=u.map(h=>/^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(h));if(!o.includes(d)||!o.includes(m)||u.length<5||u.length>10||o.length!==u.length+2||P.some(h=>!h)||new Set(P.map(h=>h[1])).size!==1)throw new Error("chaos-write-set-invalid");for(const h of o)if(y(t.workspacePath,h),b(i(t.workspacePath,h)).size===0)throw new Error("chaos-empty-artifact");const c=p(i(t.workspacePath,m),"utf8");if(!c.includes(a)||!/\bPLANNED\b/.test(c))throw new Error("chaos-history-invalid");const l=K(t.workspacePath,["ls-tree","-z","HEAD","--",m]).length>0?K(t.workspacePath,["show",`HEAD:${m}`]).toString("utf8"):"";if(l&&!c.startsWith(l))throw new Error("chaos-history-not-append-only");return q(t,o,t.baseSha)}catch{throw new Error("private-execution-project-step-admission-unverified")}const n=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(!n)throw new Error("private-execution-project-step-admission-unverified");try{if(r==="tech-debt"){const s=".neocortex/tech-debt-registry.json";y(t.workspacePath,s);const a=JSON.parse(p(i(t.workspacePath,s),"utf8"));if(!a||typeof a!="object"||Array.isArray(a))throw new Error("registry-invalid");const o=a;if(o.schema_version!==2||o.version!==void 0&&o.version!==2||!Array.isArray(o.items))throw new Error("registry-invalid")}return q(t,n,t.baseSha)}catch{throw new Error("private-execution-project-step-admission-unverified")}}function Ee(t,r,e,n,s){const a=r==="arch-prd"&&e==="arch-prd-docs-v1"?["docs/architecture/prd.md","docs/architecture/product-experience.md"]:r==="arch-architecture"&&e==="arch-architecture-doc-v1"?["docs/architecture/architecture.md"]:r==="arch-fitness-functions"&&e==="arch-fitness-tools-v1"?["tools/architecture/dependency-cruiser.config.js","tools/architecture/archunit-test.ts","tools/architecture/.eslintrc.boundaries.js"]:r==="arch-api-contracts"&&e==="arch-api-contracts-docs-v1"?["docs/architecture/api-contracts.md","docs/api/openapi.yaml"]:r==="arch-api-integrations"&&e==="arch-api-integrations-doc-v1"?["docs/architecture/api-integrations.md"]:r==="arch-database"&&e==="arch-database-doc-v1"?["docs/architecture/database-schema.md"]:r==="arch-security"&&e==="arch-security-doc-v1"?["docs/architecture/cyber-security.md"]:r==="arch-design-system"&&e==="arch-design-system-doc-v1"?["docs/architecture/atomic-design-system.md"]:r==="arch-performance"&&e==="arch-performance-doc-v1"?["docs/architecture/performance-strategy.md"]:r==="arch-testing"&&e==="arch-testing-doc-v1"?["docs/architecture/testing-strategy.md"]:r==="arch-infrastructure"&&e==="arch-infrastructure-doc-v1"?["docs/architecture/infrastructure-deploy.md"]:r==="arch-review"&&e==="arch-review-doc-v1"?["docs/architecture/review-consolidation.md"]:r==="update-memory"&&e==="arch-memory-canonical-v1"?["NEOCORTEX.md"]:null;if(!a||!/^P[1-9][0-9]{0,11}$/.test(n)||!/^[a-f0-9]{64}$/.test(s))throw new Error("private-execution-architecture-admission-unverified");try{y(t.workspacePath,".neocortex/state.json");const o=JSON.parse(p(i(t.workspacePath,".neocortex/state.json"),"utf8"));if(!o||typeof o!="object"||Array.isArray(o))throw new Error("state-invalid");const d=o,u=d.archPlan?.execution,P=d.epics;if(!u||u.currentStageCommand!==r||u.targetEpicId!==n||u.graphRevision!==s||!P||!Object.hasOwn(P,n))throw new Error("state-binding-mismatch");if(r==="update-memory"){if(u.continuationState!=="delegate"||u.reviewDecision?.decision!=="approved")throw new Error("memory-root-review-missing");const c="NEOCORTEX.md";if(!M(F(t.workspacePath,!0)).paths.includes(c))throw new Error("memory-effect-missing");y(t.sourceRoot,c),y(t.workspacePath,c);const f=p(i(t.sourceRoot,c),"utf8"),l=p(i(t.workspacePath,c),"utf8"),h="<!-- NEOCORTEX-MEMORY-START -->",w="<!-- NEOCORTEX-MEMORY-END -->",v=g=>{if(g.split(h).length!==2||g.split(w).length!==2||g.indexOf(h)>=g.indexOf(w))throw new Error("memory-markers-invalid");const S=g.indexOf(h)+h.length,x=g.indexOf(w);return{before:g.slice(0,S),body:g.slice(S,x),after:g.slice(x)}},T=v(f),A=v(l);if(T.before!==A.before||T.after!==A.after||T.body===A.body||Buffer.byteLength(l,"utf8")>32768||l.split(`
9
+ `).length>240)throw new Error("memory-managed-block-invalid");const j=new Set(T.body.split(`
10
+ `));for(const g of A.body.split(`
11
+ `))j.has(g)||Ct(g)}if(r==="arch-prd"){const c="docs/architecture/prd.md";if(!M(F(t.workspacePath,!0)).paths.includes(c))throw new Error("prd-effect-missing");if(y(t.workspacePath,c),b(i(t.workspacePath,c)).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 c=M(F(t.workspacePath,!0)).paths;for(const f of a){if(!c.includes(f))throw new Error("architecture-required-effect-missing");if(y(t.workspacePath,f),b(i(t.workspacePath,f)).size===0)throw new Error("architecture-required-effect-empty");if(r==="arch-fitness-functions"){y(t.sourceRoot,f);const l=rt(i(t.sourceRoot,f))?p(i(t.sourceRoot,f),"utf8"):"",h=p(i(t.workspacePath,f),"utf8"),w=xt(l),v=xt(h);if(!$(v,w))throw new Error("architecture-keep-marker-changed")}}}return q(t,a,t.baseSha)}catch{throw new Error("private-execution-architecture-admission-unverified")}}function Pe(t,r,e,n){try{if(!/^P[1-9][0-9]{0,11}$/.test(r)||!/^[a-f0-9]{64}$/.test(e)||n.schemaVersion!==1||n.targetEpicId!==r)throw new Error("binding-invalid");const s=Dt(t.sourceRoot,r),a=Nt(t.workspacePath,r);if(!$(s,n)||!$(a,n))throw new Error("write-set-invalid");y(t.workspacePath,".neocortex/state.json");const o=JSON.parse(p(i(t.workspacePath,".neocortex/state.json"),"utf8"));if(!o||typeof o!="object"||Array.isArray(o))throw new Error("state-invalid");const d=o,u=d.archPlan?.execution,P=d.epics;if(!u||u.currentStageCommand!=="arch-ux-design"||u.continuationState!=="delegate"||u.targetEpicId!==r||u.graphRevision!==e||!P||!Object.hasOwn(P,r))throw new Error("stage-invalid");const c=M(F(t.workspacePath,!0)).paths;if(c.length!==n.pathCount||c.some(f=>!n.paths.includes(f)))throw new Error("agent-path-unclaimed");for(const f of n.paths){y(t.sourceRoot,f),y(t.workspacePath,f);const l=b(i(t.workspacePath,f));if(!l.isFile()||l.isSymbolicLink()||l.size<1)throw new Error("effect-empty");const h=new TextDecoder("utf-8",{fatal:!0}).decode(p(i(t.workspacePath,f)));if(!h.trim()||h.includes("\0"))throw new Error("effect-invalid")}return Bt(t.workspacePath,n),q(t,n.paths,t.baseSha)}catch{throw new Error("private-execution-ux-admission-unverified")}}function we(t,r,e,n,s,a){try{if(!/^P[1-9][0-9]{0,11}$/.test(r)||!/^[a-f0-9]{64}$/.test(e)||n.targetEpicId!==r||n.graphRevision!==e||s.schemaVersion!==1)throw new Error("binding-invalid");const o=jt(t.sourceRoot);if(!o||!$(o.receipt,n))throw new Error("answers-invalid");const d=vt(t.sourceRoot,o.answers.generateProvider),m=vt(t.workspacePath,o.answers.generateProvider);if(d.outcome!=="ready"||m.outcome!=="ready"||!$(d.writeSet,s)||!$(m.writeSet,s))throw new Error("write-set-invalid");const u=M(F(t.workspacePath,!0)).paths;if(u.some(h=>!s.paths.includes(h)))throw new Error("agent-path-unclaimed");let P=0,c=0;for(const h of s.paths){if(y(t.sourceRoot,h),rt(i(t.sourceRoot,h))||!u.includes(h))throw new Error("effect-missing-or-overwrite");y(t.workspacePath,h);const w=b(i(t.workspacePath,h));if(!w.isFile()||w.size<1)throw new Error("effect-empty");const v=new TextDecoder("utf-8",{fatal:!0}).decode(p(i(t.workspacePath,h))),T=s.interactions.find(j=>j.filePath===h);if(h!==s.providerPath&&!T)throw new Error("private-execution-pact-interaction-missing");const A=Ft(h,v,o.answers.brokerUrl,T,t.workspacePath);A.consumerBinding==="app-import-candidate"&&P++,A.consumerBinding==="mock-only-scaffold"&&c++}let f=s.paths;if(a){const h=zt(t.sourceRoot,o.answers.generateProvider),w=v=>B("sha256").update(v).digest("hex");if(a.schemaVersion!==1||a.outcome!=="candidate-unverified"||a.executionVerified!==!1||a.sourceManifestSha256!==w(h.sourceText)||a.sourceLockSha256!==(h.sourceLockText===null?null:w(h.sourceLockText))||a.manifestText!==h.candidateText||!mt(t.sourceRoot,t.workspacePath,t.baseSha,"package.json")||!mt(t.sourceRoot,t.workspacePath,t.baseSha,"package-lock.json"))throw new Error("toolchain-binding-invalid");for(const v of["package.json","package-lock.json"]){y(t.sourceRoot,v),y(t.workspacePath,v);const T=v==="package.json"?h.sourceText:h.sourceLockText,A=rt(i(t.workspacePath,v))?p(i(t.workspacePath,v),"utf8"):null;if(T!==A)throw new Error("toolchain-clone-raced")}if(pt(i(t.workspacePath,"package.json"),a.manifestText),pt(i(t.workspacePath,"package-lock.json"),a.lockText),Lt(t.workspacePath,o.answers.generateProvider).outcome!=="manifest-aligned")throw new Error("toolchain-candidate-invalid");f=[...s.paths,"package.json","package-lock.json"]}const l=q(t,f,t.baseSha);return Object.freeze({...l,consumerBindingCandidateCount:P,consumerScaffoldCount:c})}catch{throw new Error("private-execution-pact-admission-unverified")}}function ve(t,r,e,n=new Date().toISOString()){try{const s=_t(t.sourceRoot,r);if(!$(s,e)||!lt(t.sourceRoot,t.workspacePath,e.prdPath)||e.aggregates.some(c=>!lt(t.sourceRoot,t.workspacePath,c.implementationFile))||e.writeSet.length===0)throw new Error("plan-drift");const a=M(F(t.workspacePath,!0)).paths;if(!$(a,e.writeSet))throw new Error("agent-path-unclaimed");const o=new Map;for(const c of e.aggregates){y(t.sourceRoot,c.testFile),y(t.workspacePath,c.testFile);const f=b(i(t.workspacePath,c.testFile));if(!f.isFile()||f.isSymbolicLink()||f.size<1||f.size>Z)throw new Error("test-invalid");const l=p(i(t.workspacePath,c.testFile)),h=new TextDecoder("utf-8",{fatal:!0}).decode(l),w=e.language==="typescript"?(h.match(/\b(?:it|test)\s*\(/g)??[]).length:(h.match(/^def\s+test_[A-Za-z0-9_]+\s*\(/gm)??[]).length;if(!h.trim()||h.includes("\0")||w<c.invariantCount||/\b(?:it|test|describe)\s*\.\s*(?:skip|todo|only)\s*\(/.test(h)||!h.includes(String(e.numRuns)))throw new Error("test-invalid");e.language==="typescript"&&Gt({source:h,testFile:c.testFile,implementationFile:c.implementationFile,invariantCount:c.invariantCount,numRuns:e.numRuns}),o.set(c.testFile,B("sha256").update(l).digest("hex"))}y(t.sourceRoot,e.prdPath),y(t.workspacePath,e.prdPath);const d=p(i(t.workspacePath,e.prdPath)),m=new TextDecoder("utf-8",{fatal:!0}).decode(d),u=Mt(m,e,n);pt(i(t.workspacePath,e.prdPath),u);const P=B("sha256").update(u).digest("hex");return q(t,[...e.writeSet,e.prdPath],t.baseSha,void 0,()=>{try{return!$(_t(t.sourceRoot,r),e)||e.aggregates.some(c=>!lt(t.sourceRoot,t.workspacePath,c.implementationFile))||B("sha256").update(p(i(t.workspacePath,e.prdPath))).digest("hex")!==P?!1:[...o].every(([c,f])=>B("sha256").update(p(i(t.workspacePath,c))).digest("hex")===f)}catch{return!1}})}catch{throw new Error("private-execution-property-admission-unverified")}}export{Ee as admitPrivateArchitectureStageWorkspace,fe as admitPrivateEpicClaimWorkspace,ge as admitPrivateGenerateEpicWorkspace,le as admitPrivateIdeaDiagnosisWorkspace,pe as admitPrivateIdeaResearchWorkspace,we as admitPrivatePactWorkspace,ye as admitPrivateProjectStepWorkspace,ve as admitPrivatePropertyTestWorkspace,me as admitPrivateStateBoundStepWorkspace,Pe as admitPrivateUxWorkspace,ue as admitPrivateYoloFrozenWorkspace,de as verifyPrivateYoloSnapshotBoundary};