@ornexus/neocortex 4.60.62 → 4.60.64

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 (137) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +77 -50
  3. package/install.ps1 +1 -1
  4. package/install.sh +1 -1
  5. package/package.json +12 -5
  6. package/packages/client/dist/cli.js +8 -3
  7. package/packages/client/dist/commands/activate.js +8 -8
  8. package/packages/client/dist/commands/architecture-memory-terminal.js +4 -2
  9. package/packages/client/dist/commands/architecture-non-ui-continuation.d.ts +3 -0
  10. package/packages/client/dist/commands/architecture-non-ui-continuation.js +1 -0
  11. package/packages/client/dist/commands/invoke.d.ts +19 -16
  12. package/packages/client/dist/commands/invoke.js +86 -79
  13. package/packages/client/dist/commands/planning-generation.js +1 -1
  14. package/packages/client/dist/commands/planning-memory.d.ts +1 -0
  15. package/packages/client/dist/commands/planning-memory.js +1 -0
  16. package/packages/client/dist/commands/private-session.d.ts +1 -0
  17. package/packages/client/dist/commands/private-session.js +1 -0
  18. package/packages/client/dist/commands/qa-control.d.ts +4 -0
  19. package/packages/client/dist/commands/qa-control.js +1 -0
  20. package/packages/client/dist/commands/qa-scan-browser-launch.d.ts +8 -0
  21. package/packages/client/dist/commands/qa-scan-browser-launch.js +1 -0
  22. package/packages/client/dist/commands/qa-scan-browser-route.d.ts +3 -0
  23. package/packages/client/dist/commands/qa-scan-browser-route.js +1 -0
  24. package/packages/client/dist/commands/qa-scan-capture.d.ts +43 -0
  25. package/packages/client/dist/commands/qa-scan-capture.js +5 -5
  26. package/packages/client/dist/commands/qa-scan-discovery.d.ts +7 -0
  27. package/packages/client/dist/commands/qa-scan-discovery.js +3 -3
  28. package/packages/client/dist/commands/qa-scan-review.d.ts +8 -1
  29. package/packages/client/dist/commands/qa-scan-review.js +5 -5
  30. package/packages/client/dist/commands/qa-synthetic-backend-capture.d.ts +62 -0
  31. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +1 -0
  32. package/packages/client/dist/commands/qa-synthetic-backend-review.d.ts +104 -0
  33. package/packages/client/dist/commands/qa-synthetic-backend-review.js +1 -0
  34. package/packages/client/dist/commands/qa-synthetic-backend.d.ts +52 -0
  35. package/packages/client/dist/commands/qa-synthetic-backend.js +7 -0
  36. package/packages/client/dist/commands/qa-synthetic-broker-port.d.ts +30 -0
  37. package/packages/client/dist/commands/qa-synthetic-broker-port.js +1 -0
  38. package/packages/client/dist/commands/qa-synthetic-browser.d.ts +1 -0
  39. package/packages/client/dist/commands/qa-synthetic-browser.js +1 -0
  40. package/packages/client/dist/commands/refactor-characterization.d.ts +12 -3
  41. package/packages/client/dist/commands/refactor-characterization.js +21 -12
  42. package/packages/client/dist/commands/refactor-control.d.ts +17 -0
  43. package/packages/client/dist/commands/refactor-control.js +3 -0
  44. package/packages/client/dist/commands/refactor-cpp-assertions.d.ts +4 -0
  45. package/packages/client/dist/commands/refactor-cpp-assertions.js +3 -0
  46. package/packages/client/dist/commands/refactor-review.d.ts +13 -0
  47. package/packages/client/dist/commands/refactor-review.js +6 -5
  48. package/packages/client/dist/commands/refactor-root.d.ts +165 -1
  49. package/packages/client/dist/commands/refactor-root.js +12 -7
  50. package/packages/client/dist/commands/refresh-memory.d.ts +1 -0
  51. package/packages/client/dist/commands/refresh-memory.js +3 -3
  52. package/packages/client/dist/commands/shared-architecture-non-ui-contract.d.ts +19 -0
  53. package/packages/client/dist/commands/shared-architecture-non-ui-contract.js +1 -0
  54. package/packages/client/dist/errors/error-messages.js +1 -1
  55. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -4
  56. package/packages/client/dist/git/git-lifecycle-store.js +7 -7
  57. package/packages/client/dist/license/license-client.d.ts +3 -1
  58. package/packages/client/dist/license/license-client.js +1 -1
  59. package/packages/client/dist/memory/project-memory-path-scope.d.ts +4 -0
  60. package/packages/client/dist/memory/project-memory-path-scope.js +1 -0
  61. package/packages/client/dist/memory/project-memory-writer.d.ts +4 -1
  62. package/packages/client/dist/memory/project-memory-writer.js +16 -16
  63. package/packages/client/dist/package.json +1 -0
  64. package/packages/client/dist/private-execution/clean-baseline.d.ts +7 -0
  65. package/packages/client/dist/private-execution/clean-baseline.js +2 -2
  66. package/packages/client/dist/private-execution/codex-executor.d.ts +48 -4
  67. package/packages/client/dist/private-execution/codex-executor.js +9 -2
  68. package/packages/client/dist/private-execution/codex-host-runtime.d.ts +10 -0
  69. package/packages/client/dist/private-execution/codex-host-runtime.js +1 -0
  70. package/packages/client/dist/private-execution/codex-lifecycle-guard.d.ts +4 -0
  71. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +1 -0
  72. package/packages/client/dist/private-execution/codex-scoped-permissions.d.ts +8 -0
  73. package/packages/client/dist/private-execution/codex-scoped-permissions.js +1 -0
  74. package/packages/client/dist/private-execution/delivery.d.ts +18 -1
  75. package/packages/client/dist/private-execution/delivery.js +11 -3
  76. package/packages/client/dist/private-execution/diagnosis-root-review.d.ts +112 -0
  77. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -0
  78. package/packages/client/dist/private-execution/frozen-handoff.d.ts +2 -0
  79. package/packages/client/dist/private-execution/frozen-handoff.js +7 -0
  80. package/packages/client/dist/private-execution/implementation-validation.d.ts +24 -0
  81. package/packages/client/dist/private-execution/implementation-validation.js +2 -0
  82. package/packages/client/dist/private-execution/isolated-admission.d.ts +11 -7
  83. package/packages/client/dist/private-execution/isolated-admission.js +17 -10
  84. package/packages/client/dist/private-execution/isolated-session.d.ts +68 -0
  85. package/packages/client/dist/private-execution/isolated-session.js +5 -2
  86. package/packages/client/dist/private-execution/pact-test-source.d.ts +1 -1
  87. package/packages/client/dist/private-execution/pact-test-source.js +1 -1
  88. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.d.ts +2 -0
  89. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -5
  90. package/packages/client/dist/private-execution/planning-generation-checkpoint.d.ts +13 -0
  91. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +4 -3
  92. package/packages/client/dist/private-execution/planning-memory-checkpoint.d.ts +32 -0
  93. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +3 -0
  94. package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -4
  95. package/packages/client/dist/private-execution/root-checkpoint.js +1 -1
  96. package/packages/client/dist/private-execution/root-memory-git-evidence.d.ts +30 -0
  97. package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -0
  98. package/packages/client/dist/private-execution/root-memory-recovery.d.ts +16 -0
  99. package/packages/client/dist/private-execution/root-memory-recovery.js +1 -0
  100. package/packages/client/dist/private-execution/root-memory-request.d.ts +28 -0
  101. package/packages/client/dist/private-execution/root-memory-request.js +1 -0
  102. package/packages/client/dist/private-execution/root-memory-scope.d.ts +28 -0
  103. package/packages/client/dist/private-execution/root-memory-scope.js +1 -0
  104. package/packages/client/dist/private-execution/root-memory-writer.d.ts +22 -0
  105. package/packages/client/dist/private-execution/root-memory-writer.js +1 -0
  106. package/packages/client/dist/private-execution/session-lease.d.ts +19 -0
  107. package/packages/client/dist/private-execution/session-lease.js +1 -0
  108. package/packages/client/dist/private-execution/ux-source-validation.js +1 -1
  109. package/packages/client/dist/runner-cli.js +0 -0
  110. package/packages/client/dist/yolo/change-evidence-collector.d.ts +2 -2
  111. package/packages/client/dist/yolo/change-evidence-collector.js +1 -1
  112. package/packages/client/dist/yolo/spec-envelope-collector.js +2 -2
  113. package/packages/shared/dist/invocation/index.js +4 -2
  114. package/packages/shared/dist/invocation/packed-invoke.d.ts +12 -0
  115. package/packages/shared/dist/invocation/packed-invoke.js +58 -0
  116. package/packages/shared/dist/invocation/packed-invoke.test.d.ts +1 -0
  117. package/packages/shared/dist/invocation/packed-invoke.test.js +21 -0
  118. package/packages/shared/dist/package.json +1 -0
  119. package/packages/shared/dist/planning/diagnosis-state.js +5 -2
  120. package/packages/shared/dist/private-qa-structural-admission.js +14 -0
  121. package/packages/shared/dist/private-yolo-predecessor-decision.js +32 -0
  122. package/packages/shared/dist/project-memory-targets.js +243 -0
  123. package/packages/shared/dist/project-validation-commands.js +96 -0
  124. package/packages/shared/dist/yolo/change-evidence.js +35 -0
  125. package/packages/shared/dist/yoloop/branch-unit.js +10 -1
  126. package/packages/shared/dist/yoloop/root-memory-effect.js +57 -0
  127. package/targets-stubs/antigravity/gemini.md +1 -1
  128. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  129. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  130. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  131. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  132. package/targets-stubs/claude-code/neocortex.md +2 -2
  133. package/targets-stubs/codex/AGENTS.md +1 -1
  134. package/targets-stubs/cursor/agent.md +2 -2
  135. package/targets-stubs/gemini-cli/agent.md +2 -2
  136. package/targets-stubs/opencode/neocortex-root.md +1 -1
  137. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,11 +1,18 @@
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,`
1
+ import{execFileSync as Nt,spawnSync as wt}from"node:child_process";import{createHash as F}from"node:crypto";import{existsSync as rt,lstatSync as x,readFileSync as g,realpathSync as ct,writeFileSync as mt}from"node:fs";import{isAbsolute as nt,join as a,relative as ht,sep as vt}from"node:path";import{isDeepStrictEqual as S}from"node:util";import{readPrivateYoloFrozenWriteSet as Dt,verifyPrivateYoloCandidateWriteSet as Ft,verifyPrivateYoloCleanBaseline as Ct}from"./clean-baseline.js";import{PRIVATE_EPIC_PENDING_SIDECAR as et}from"./isolated-workspace.js";import{loadPactPrivateAnswers as Bt}from"../commands/architecture-answers.js";import{derivePactWriteSet as _t}from"./pact-write-set.js";import{deriveUxCandidateWriteSet as zt,deriveUxWriteSet as Lt}from"./ux-write-set.js";import{validateUxCandidateSource as Ht}from"./ux-source-validation.js";import{validatePactTestSource as Jt}from"./pact-test-source.js";import{classifyProjectMemoryUpdate as Mt}from"../memory/project-memory-writer.js";import{privateRootMemoryEffect as yt,privateRootMemorySourceMatches as Gt,privateRootMemorySourceMatchReason as Yt}from"./root-memory-scope.js";import{inspectPactToolchain as qt,planPactToolchainManifest as Ut}from"./pact-toolchain.js";import{acceptedPlanningDiagnosisPredecessor as Vt,planningPendingSidecarDigest as bt}from"./planning-diagnosis-checkpoint.js";import{acceptedPlanningResearchPredecessor as Wt}from"./planning-research-checkpoint.js";import{confirmPropertyTestPlan as xt,renderPropertyTestConfiguration as Xt}from"./property-test-plan.js";import{validatePropertyTestTypeScriptSource as Kt}from"./property-test-source.js";const Z=16*1024*1024,dt=1024,ut="acd455ed0e39d98b90fb57391db75e366e4c5604db043e03a89a20e33d643c3c",Zt="81f50aaa801c1660eabe46e645501acbfb3e9873410c991e1496c014ca75c369",Rt="fa2194f89c01f07e225fd6f39e98e679f628e072239b6cd0af3ee527f0722518",Qt="8636f22ec5950410902448ee1e9cb4947359ac98df518742bddbbb367468e3ae";function tt(t,r){return typeof t=="string"&&t.length<=128&&F("sha256").update(t).digest("hex")===r}function Et(){const t={...process.env};for(const r of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete t[r];return t}function Y(t,r){return Nt("git",[...r],{cwd:t,env:Et(),stdio:["ignore","pipe","pipe"],timeout:3e4,maxBuffer:Z})}function J(t,r){return Y(t,r).toString("utf8").trim()}function C(t,r=!1){return Y(t,["status","--porcelain=v1","-z","--untracked-files=all",...r?["--ignored=matching"]:[]])}function ot(t){return!!t&&!nt(t)&&!t.includes("\\")&&!t.includes("\0")&&!t.split("/").some(r=>!r||r==="."||r===".."||r===".git")}function P(t,r){const e=r.split("/");let s=t;for(const n of e.slice(0,-1)){s=a(s,n);try{const i=x(s);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("path-boundary")}catch(i){if(i.code==="ENOENT")return;throw i}}try{const n=x(a(t,r));if(!n.isFile()||n.isSymbolicLink()||n.size>Z)throw new Error("path-boundary")}catch(n){if(n.code!=="ENOENT")throw n}}function At(t){const r=[...t.matchAll(/\/\/\s*arch:keep-start[^\n]*\n[\s\S]*?\/\/\s*arch:keep-end[^\n]*/g)].map(n=>n[0]),e=(t.match(/arch:keep-start/g)??[]).length,s=(t.match(/arch:keep-end/g)??[]).length;if(e!==s||e!==r.length)throw new Error("architecture-keep-marker-invalid");return r}function M(t,r=!1,e=!1,s=[]){const n=[],i=[];for(const o of t.toString("utf8").split("\0").filter(Boolean)){if(o.length<4||o[2]!==" ")throw new Error("status-invalid");const f=o.slice(0,2),l=o.slice(3);if(!ot(l)||f!=="??"&&f!==" M"&&f!==" D"&&!(f===" T"&&s.includes(l))&&!(e&&f==="!!"&&l===et))throw new Error("status-invalid");n.push(l),f==="??"&&i.push(l)}if(!r&&n.length===0||n.length>dt||new Set(n).size!==n.length)throw new Error("status-invalid");return{paths:n.sort(),untracked:i.sort()}}function ft(t,r,e,s){const n=Y(r,["ls-tree","-z",e,"--",s]).toString("utf8");if(!n)try{return x(a(t,s)),!1}catch(o){return o.code==="ENOENT"}const i=/^([0-7]{6}) blob [a-f0-9]{40,64}\t([^\0]+)\0$/.exec(n);if(!i||i[2]!==s||!["100644","100755"].includes(i[1]))return!1;try{const o=x(a(t,s));return!o.isFile()||o.isSymbolicLink()||o.size>Z||!!(o.mode&73)!=(i[1]==="100755")?!1:g(a(t,s)).equals(Y(r,["show",`${e}:${s}`]))}catch{return!1}}function ve(t,r,e,s){return ot(s)&&/^[a-f0-9]{40,64}$/.test(e)&&ft(t,r,e,s)}function st(t,r){try{const e=a(t,et),s=x(a(t,".neocortex")),n=x(e);return s.isDirectory()&&!s.isSymbolicLink()&&s.uid===process.getuid?.()&&(s.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(g(e)).digest("hex")===r}catch{return!1}}function lt(t,r,e,s,n,i){const o=new Set(s),f=i?yt(i).files.map(m=>m.path):[],l=M(C(t),!0,!!n,f),c=i?Yt(i,t,r,e):"matched";if(c!=="matched")throw new Error(`root-memory-${c}`);if(!l.paths.every(m=>o.has(m)||f.includes(m)||m===et&&!!n&&st(t,n)))throw new Error("source-unclaimed-delta");if(!s.every(m=>ft(t,r,e,m)))throw new Error("source-frozen-mismatch");return!n||st(t,n)}function kt(t,r){const e=wt("git",["diff","--no-index","--binary","--no-ext-diff","--","/dev/null",r],{cwd:t,env:Et(),encoding:"buffer",timeout:3e4,maxBuffer:Z});if(e.error||e.status!==1||!Buffer.isBuffer(e.stdout)||e.stdout.byteLength===0)throw new Error("patch-invalid");return e.stdout}function St(t,r,e){const s=wt("git",["apply",...e?["--check"]:[],"--binary","-"],{cwd:t,env:Et(),input:r,encoding:"buffer",timeout:3e4,maxBuffer:Z});if(s.error||s.status!==0)throw new Error("apply-failed")}function pt(t,r,e){const s=a(t,e),n=a(r,e);try{const i=x(s),o=x(n);return i.isFile()&&o.isFile()&&(i.mode&73)===(o.mode&73)&&g(s).equals(g(n))}catch(i){if(i.code!=="ENOENT")return!1;try{return x(s),!1}catch(o){if(o.code!=="ENOENT")return!1}try{return x(n),!1}catch(o){return o.code==="ENOENT"}}}function _e(t,r,e,s){$t(t,r,e,!0,s)}function be(t,r,e,s){if($t(t,r,e,!1,s),Y(t.workspacePath,["diff","--cached","--name-only"]).byteLength!==0)throw new Error("private-execution-isolated-snapshot-unverified")}function $t(t,r,e,s,n){try{if(process.platform!=="linux"||t.schemaVersion!==1||!nt(t.sourceRoot)||!nt(t.workspacePath)||ct(t.sourceRoot)!==t.sourceRoot||ct(t.workspacePath)!==t.workspacePath||!x(t.workspacePath).isDirectory()||(x(t.workspacePath).mode&63)!==0||ht(t.sourceRoot,t.workspacePath)===""||ht(t.sourceRoot,t.workspacePath).split(vt)[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(a(t.workspacePath,".git","objects","info","alternates"))||s&&C(t.workspacePath,!0).byteLength!==0||r.length===0||r.length>dt||r.some(i=>!ot(i))||new Set(r).size!==r.length)throw new Error("boundary-invalid");if(Y(t.workspacePath,["merge-base","--is-ancestor",t.baseSha,e]),!lt(t.sourceRoot,t.workspacePath,e,r,void 0,n))throw new Error("boundary-raced")}catch(i){const o=i instanceof Error&&(["boundary-invalid","boundary-raced","status-invalid","source-unclaimed-delta","source-frozen-mismatch"].includes(i.message)||/^root-memory-(scope-binding|snapshot-ancestry|snapshot-content|source-content|source-projection)(-unsafe)?$/.test(i.message))?i.message:"physical-inspection-failed";throw new Error("private-execution-isolated-snapshot-unverified",{cause:new Error(o)})}}function q(t,r,e,s,n,i=[],o){try{if(process.platform!=="linux"||t.schemaVersion!==1||!nt(t.sourceRoot)||!nt(t.workspacePath)||ct(t.sourceRoot)!==t.sourceRoot||ct(t.workspacePath)!==t.workspacePath||!x(t.workspacePath).isDirectory()||(x(t.workspacePath).mode&63)!==0||ht(t.sourceRoot,t.workspacePath)===""||ht(t.sourceRoot,t.workspacePath).split(vt)[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>dt||r.some(p=>!ot(p))||new Set(r).size!==r.length)throw new Error("authority-invalid");if(Y(t.workspacePath,["merge-base","--is-ancestor",t.baseSha,e]),!lt(t.sourceRoot,t.workspacePath,e,r,s,o))throw new Error("source-snapshot-mismatch");const f=C(t.workspacePath,!0),l=M(f),c=new Set(r);if(l.paths.some(p=>!c.has(p)||i.includes(p)))throw new Error("path-unclaimed");if(n&&!n())throw new Error("candidate-raced");for(const p of l.paths)P(t.workspacePath,p),P(t.sourceRoot,p);const h=[Y(t.workspacePath,["diff","--binary","--no-ext-diff","--no-textconv","HEAD","--"]),...l.untracked.map(p=>kt(t.workspacePath,p))],u=Buffer.concat(h.map(p=>Buffer.concat([p,Buffer.from(`
2
+ `)])));if(u.byteLength===0||u.byteLength>Z||!C(t.workspacePath,!0).equals(f)||n&&!n()||!lt(t.sourceRoot,t.workspacePath,e,r,s,o))throw new Error("patch-raced");if(St(t.sourceRoot,u,!0),!C(t.workspacePath,!0).equals(f)||n&&!n()||!lt(t.sourceRoot,t.workspacePath,e,r,s,o))throw new Error("patch-raced");St(t.sourceRoot,u,!1);const v=o?yt(o).files.map(p=>p.path):[];if(M(C(t.sourceRoot),!0,!!s,v).paths.some(p=>!c.has(p)&&!v.includes(p)&&p!==et)||o&&!Gt(o,t.sourceRoot)||s&&!st(t.sourceRoot,s)||r.some(p=>!pt(t.workspacePath,t.sourceRoot,p))||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([...l.paths]),patchSha256:F("sha256").update(u).digest("hex")})}catch{throw new Error("private-execution-isolated-admission-unverified")}}async function xe(t,r,e,s=t.baseSha,n=!1,i){try{const o=await Dt(t.sourceRoot,r,t.executionBranch,e);if(i){const m=yt(i);if(m.storyId!==r||m.childClaimRevision!==F("sha256").update([...o].sort().join("\0")).digest("hex"))throw new Error("root-memory-claim-mismatch")}const f=a(t.workspacePath,".neocortex","state.json"),l=x(f);if(!l.isFile()||l.isSymbolicLink()||l.size>Z)throw new Error("candidate-state-invalid");Ft(g(f,"utf8"),r,o);const c=q(t,o,s,void 0,void 0,n?[".neocortex/state.json"]:[],i);return await Ct(t.sourceRoot,r,t.executionBranch,e),c}catch{throw new Error("private-execution-isolated-admission-unverified")}}const It=new Set(["id","epic_id","title","description","status","steps_completed","last_step","branch_name","estimated_hours","complexity","priority","type","depends_on","created_at","updated_at","acceptance_criteria"]),te=new Set(["id","title","description","status","stories","total_stories","completed_stories","estimated_hours","complexity","priority","created_at","updated_at","last_updated","source","tags"]);function Ot(t){return["title","description","complexity","priority","type","created_at","updated_at","last_updated","source"].some(e=>t[e]!==void 0&&typeof t[e]!="string")||t.estimated_hours!==void 0&&(typeof t.estimated_hours!="number"||!Number.isFinite(t.estimated_hours)||t.estimated_hours<0)?!1:["depends_on","acceptance_criteria","tags"].every(e=>t[e]===void 0||Array.isArray(t[e])&&t[e].length<=256&&t[e].every(s=>typeof s=="string"))}function ee(t){return Object.keys(t).every(r=>It.has(r))&&t.status==="backlog"&&Ot(t)&&(t.steps_completed===void 0||Array.isArray(t.steps_completed)&&t.steps_completed.length===0)&&(t.last_step===void 0||t.last_step===null)&&(t.branch_name===void 0||t.branch_name===null)}function Re(t,r,e,s,n){try{if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(r)||!/^P[1-9][0-9]*$/.test(e)||!/^[a-f0-9]{64}$/.test(s)||!/^[a-f0-9]{64}$/.test(n)||!st(t.sourceRoot,n))throw new Error("claim-invalid");const i=JSON.parse(g(a(t.sourceRoot,et),"utf8")),o=i&&typeof i=="object"&&!Array.isArray(i)?i.operations?.[s]:void 0;if(!o||typeof o!="object"||Array.isArray(o)||o.claimId!==r||o.epicId!==e)throw new Error("claim-sidecar-mismatch");const f=M(C(t.workspacePath,!0)),l=`docs/epics/epic-${e}.md`,c=".neocortex/state.json",m=new RegExp(`^docs/stories/${e}\\.[0-9]{2}\\.story\\.md$`),h=f.paths.filter(E=>m.test(E));if(!f.paths.includes(l)||!f.paths.includes(c)||h.length===0||h.length>99||f.paths.some(E=>E!==l&&E!==c&&E!=="NEOCORTEX.md"&&!m.test(E)))throw new Error("artifact-scope-invalid");const u=h.map(E=>E.slice(13,-9)).sort();if(u.some((E,T)=>E!==`${e}.${String(T+1).padStart(2,"0")}`))throw new Error("story-sequence-invalid");for(const E of[l,...h])try{throw x(a(t.sourceRoot,E)),new Error("artifact-already-exists")}catch(T){if(T.code!=="ENOENT")throw T}const v=(E,T)=>{P(t.workspacePath,E);const K=g(a(t.workspacePath,E),"utf8");return Buffer.byteLength(K)>Z?null:/^---\r?\n([\s\S]{1,8192}?)\r?\n---(?:\r?\n|$)/.exec(K)?.[1]?.split(/\r?\n/).find(at=>at.startsWith(`${T}:`))?.slice(T.length+1).trim()?.replace(/^(["'])(.*)\1$/,"$2")??null};if(v(l,"id")!==e||h.some((E,T)=>v(E,"id")!==u[T]||v(E,"epic_id")!==e))throw new Error("artifact-id-invalid");P(t.workspacePath,c);const d=JSON.parse(g(a(t.workspacePath,c),"utf8"));if(!d||typeof d!="object"||Array.isArray(d))throw new Error("state-invalid");const p=d,_=p.epics,j=p.stories,b=_?.[e],N=p.epic_id_ledger;if(p.schema_version!==1||!b||b.id!==e||b.status!=="memory-updated"||Object.keys(b).some(E=>!te.has(E))||!Ot(b)||b.completed_stories!==void 0&&b.completed_stories!==0||b.total_stories!==void 0&&b.total_stories!==u.length||!Array.isArray(b.stories)||b.stories.length!==u.length||b.stories.some((E,T)=>E!==u[T])||!j||u.some(E=>{const T=j[E];return!T||T.id!==E||T.epic_id!==e||!ee(T)})||!N||!Array.isArray(N.reserved_ids)||!N.reserved_ids.includes(e))throw new Error("state-claim-mismatch");P(t.sourceRoot,c);const y=JSON.parse(g(a(t.sourceRoot,c),"utf8")),A=y.epics,R=y.stories;if(!A||!R||A[e]!==void 0||u.some(E=>R[E]!==void 0))throw new Error("state-claim-conflict");const{[e]:U,...L}=_,$={...j};for(const E of u)delete $[E];const{epic_id_ledger:G,last_updated:B,...z}=y,{epic_id_ledger:W,last_updated:X,...Q}=p;if(!S(L,A)||!S($,R)||!S({...Q,epics:void 0,stories:void 0},{...z,epics:void 0,stories:void 0}))throw new Error("state-unrelated-drift");const O=y.epic_id_ledger&&typeof y.epic_id_ledger=="object"?y.epic_id_ledger.reserved_ids:void 0,{reserved_ids:V,...w}=N,D=y.epic_id_ledger&&typeof y.epic_id_ledger=="object"?y.epic_id_ledger:{schema_version:1},{reserved_ids:H,...k}=D;if(O!==void 0&&(!Array.isArray(O)||O.some(E=>typeof E!="string"||!/^P[1-9][0-9]*$/.test(E))||new Set(O).size!==O.length))throw new Error("ledger-drift");const I=[...Array.isArray(O)?O:[]];if(I.includes(e)||I.push(e),!S(N.reserved_ids,I)||!S(w,k))throw new Error("ledger-drift");return q(t,f.paths,t.baseSha,n)}catch{throw new Error("private-execution-epic-claim-admission-unverified")}}function Ae(t,r,e,s,n,i){try{if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(r)||!/^P[1-9][0-9]{0,11}$/.test(e)||!/^[a-f0-9]{64}$/.test(s)||!/^[a-f0-9]{64}$/.test(n)||typeof i!="string"||!i.trim()||i.length>16384||!st(t.sourceRoot,n))throw new Error("planning-claim-invalid");const o=JSON.parse(g(a(t.sourceRoot,et),"utf8")),f=o&&typeof o=="object"&&!Array.isArray(o)?o.operations?.[s]:void 0;if(!f||typeof f!="object"||Array.isArray(f)||f.claimId!==r||f.epicId!==e)throw new Error("planning-claim-sidecar-mismatch");const l=`.neocortex/planning/epic-${e}`,c=`${l}/idea.json`,m=`${l}/diagnosis.md`,h=`${l}/enriched-prompt.md`,u=".neocortex/planning/planning.json",v=[c,m,h,u],d=M(C(t.workspacePath,!0));if(d.paths.length!==v.length||d.paths.some(E=>!v.includes(E)))throw new Error("planning-artifact-scope-invalid");for(const E of[c,m,h]){P(t.workspacePath,E);try{throw x(a(t.sourceRoot,E)),new Error("planning-artifact-already-exists")}catch(T){if(T.code!=="ENOENT")throw T}}const p=(E,T)=>{const K=x(a(t.workspacePath,E));if(!K.isFile()||K.isSymbolicLink()||K.size<1||K.size>T)throw new Error("planning-artifact-invalid");return g(a(t.workspacePath,E),"utf8")},_=JSON.parse(p(c,32*1024));if(!_||typeof _!="object"||Array.isArray(_)||_.epic_id!==e||_.status!=="diagnosed"||typeof _.raw_input!="string"||_.raw_input!==i)throw new Error("planning-idea-invalid");const j=p(m,256*1024),b=p(h,256*1024),N=(E,T)=>{const K=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(E.replace(/\r\n/g,`
3
+ `))?.[1];if(!K)return!1;const Pt=K.split(`
4
+ `),it=gt=>{const at=Pt.filter(jt=>jt.startsWith(`${gt}:`));return at.length===1?at[0].slice(gt.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0};return it("epic_id")===e&&tt(it("step"),T)&&it("status")==="completed"};if(!N(j,ut)||!N(b,Zt))throw new Error("planning-document-identity-invalid");P(t.workspacePath,u),P(t.sourceRoot,u);const y=JSON.parse(p(u,128*1024)),A=rt(a(t.sourceRoot,u))?JSON.parse(g(a(t.sourceRoot,u),"utf8")):void 0;if(!y||typeof y!="object"||Array.isArray(y)||!("epics"in y)||!y.epics||typeof y.epics!="object"||Array.isArray(y.epics)||A!==void 0&&(!A||typeof A!="object"||Array.isArray(A)||!("epics"in A)||!A.epics||typeof A.epics!="object"||Array.isArray(A.epics)))throw new Error("planning-index-invalid");const R=y,U=R.epics,L=U[e],$=L,G=$?.output_files;if(!L||typeof L!="object"||Array.isArray(L)||$?.id!==e||$.status!=="diagnosed"||$.idea!==_.raw_input||!Array.isArray($.steps_completed)||$.steps_completed.length!==1||!tt($.steps_completed[0],ut)||typeof $.created_at!="string"||!Number.isFinite(Date.parse($.created_at))||$.completed_at!==null||!G||typeof G!="object"||Array.isArray(G)||!S(G,{diagnosis:`${l}/diagnosis.md`})||!S(Object.keys($).sort(),["id","idea","status","steps_completed","created_at","completed_at","output_files"].sort()))throw new Error("planning-index-epic-invalid");const{last_scan:B,epics:z,...W}=R,X=A,Q=X?.epics,{last_scan:O,epics:V,...w}=X??{},{[e]:D,...H}=U;if(Q?.[e]!==void 0||!S(H,Q??{})||X!==void 0&&!S(W,w)||X===void 0&&(Object.keys(U).length!==1||!S(Object.keys(R).sort(),["version","next_epic_id","last_scan","existing_epics_discovered","epics"].sort())||R.version!=="1.0.0"||R.next_epic_id!==1||!S(R.existing_epics_discovered,[]))||typeof R.last_scan!="string"||!Number.isFinite(Date.parse(R.last_scan)))throw new Error("planning-index-drift");const k=v.map(E=>F("sha256").update(g(a(t.workspacePath,E))).digest("hex")),I=()=>v.every((E,T)=>{try{return P(t.workspacePath,E),F("sha256").update(g(a(t.workspacePath,E))).digest("hex")===k[T]}catch{return!1}});return q(t,v,t.baseSha,n,I)}catch{throw new Error("private-execution-planning-diagnosis-admission-unverified")}}function Se(t,r,e,s,n,i){try{if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(r)||!/^P[1-9][0-9]{0,11}$/.test(e)||!/^[a-f0-9]{64}$/.test(s)||!/^[a-f0-9]{64}$/.test(n)||!/^[a-f0-9]{64}$/.test(i))throw new Error("planning-research-binding-invalid");const o=".neocortex/state.json",f=".neocortex/planning/planning.json",l=`.neocortex/planning/epic-${e}`,c=`${l}/research.md`;if(P(t.sourceRoot,o),P(t.workspacePath,o),P(t.sourceRoot,f),P(t.workspacePath,f),P(t.sourceRoot,c),P(t.workspacePath,c),x(a(t.sourceRoot,o)).size>8*1024*1024||x(a(t.workspacePath,o)).size>8*1024*1024||x(a(t.sourceRoot,f)).size>128*1024||x(a(t.workspacePath,f)).size>128*1024)throw new Error("planning-research-source-size-invalid");const m=g(a(t.sourceRoot,o));if(F("sha256").update(m).digest("hex")!==i||!m.equals(g(a(t.workspacePath,o))))throw new Error("planning-research-state-drift");const h=JSON.parse(m.toString("utf8")),u=Vt(h,r,e);if(u.diagnosisReceiptId!==s||u.intakeRevision!==n)throw new Error("planning-research-predecessor-mismatch");const d=h.epics[e].createEpicPlanningPhysical.artifactDigests;for(const[O,V]of Object.entries({idea:`${l}/idea.json`,diagnosis:`${l}/diagnosis.md`,enrichment:`${l}/enriched-prompt.md`,index:f}))if(P(t.sourceRoot,V),F("sha256").update(g(a(t.sourceRoot,V))).digest("hex")!==d[O])throw new Error("planning-research-source-artifact-drift");try{throw x(a(t.sourceRoot,c)),new Error("planning-research-already-exists")}catch(O){if(O.code!=="ENOENT")throw O}const p=[c,f],_=M(C(t.workspacePath,!0));if(_.paths.length!==p.length||_.paths.some(O=>!p.includes(O)))throw new Error("planning-research-write-scope-invalid");const j=x(a(t.workspacePath,c));if(!j.isFile()||j.isSymbolicLink()||j.size<64||j.size>256*1024)throw new Error("planning-research-document-invalid");const b=g(a(t.workspacePath,c),"utf8"),N=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(b.replace(/\r\n/g,`
5
+ `))?.[1],y=O=>{const V=N?.split(`
6
+ `).filter(w=>w.startsWith(`${O}:`))??[];return V.length===1?V[0].slice(O.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0};if(!N||y("epic_id")!==e||y("status")!=="completed"||!tt(y("step"),Rt)||!b.slice(N.length+8).trim())throw new Error("planning-research-document-identity-invalid");const A=JSON.parse(g(a(t.sourceRoot,f),"utf8")),R=JSON.parse(g(a(t.workspacePath,f),"utf8"));if(!A||typeof A!="object"||Array.isArray(A)||!R||typeof R!="object"||Array.isArray(R))throw new Error("planning-research-index-invalid");const U=A,L=R,$=U.epics,G=L.epics,B=$?.[e];if(!$||Array.isArray($)||!G||Array.isArray(G)||!B||Array.isArray(B)||B.id!==e||B.idea!==u.rawIntent||B.status!=="diagnosed"||!Array.isArray(B.steps_completed)||B.steps_completed.length!==1||!tt(B.steps_completed[0],ut)||!S(B.output_files,{diagnosis:`${l}/diagnosis.md`})||typeof L.last_scan!="string"||!Number.isFinite(Date.parse(L.last_scan)))throw new Error("planning-research-index-predecessor-invalid");const z={...B,status:"researched",steps_completed:[...B.steps_completed,y("step")],output_files:{diagnosis:`${l}/diagnosis.md`,research:c}},W={...U,last_scan:L.last_scan,epics:{...$,[e]:z}};if(!S(L,W))throw new Error("planning-research-index-drift");const X=p.map(O=>F("sha256").update(g(a(t.workspacePath,O))).digest("hex")),Q=()=>p.every((O,V)=>{try{return P(t.workspacePath,O),F("sha256").update(g(a(t.workspacePath,O))).digest("hex")===X[V]}catch{return!1}});return q(t,p,t.baseSha,bt(t.sourceRoot),Q)}catch{throw new Error("private-execution-planning-research-admission-unverified")}}function $e(t,r,e,s,n,i,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)||[s,n,i,o].some(w=>!/^[a-f0-9]{64}$/.test(w)))throw new Error("planning-generation-binding-invalid");const f=".neocortex/state.json",l=".neocortex/planning/planning.json",c=`.neocortex/planning/epic-${e}`,m=`docs/epics/epic-${e}.md`;for(const w of[f,l,`${c}/idea.json`,`${c}/diagnosis.md`,`${c}/enriched-prompt.md`,`${c}/research.md`]){P(t.sourceRoot,w),P(t.workspacePath,w);const D=g(a(t.sourceRoot,w));if(w!==l&&!D.equals(g(a(t.workspacePath,w)))||!D.equals(Y(t.sourceRoot,["show",`HEAD:${w}`])))throw new Error("planning-generation-predecessor-uncommitted")}const h=g(a(t.sourceRoot,f));if(h.byteLength>8*1024*1024||F("sha256").update(h).digest("hex")!==o)throw new Error("planning-generation-state-drift");const u=JSON.parse(h.toString("utf8")),v=Wt(u,r,e);if(v.diagnosisReceiptId!==s||v.researchReceiptId!==n||v.intakeRevision!==i)throw new Error("planning-generation-predecessor-mismatch");const d=u.epics[e],p=d.createEpicPlanningPhysical.artifactDigests,_=d.createEpicPlanningResearchPhysical.artifactDigests,j={idea:`${c}/idea.json`,diagnosis:`${c}/diagnosis.md`,enrichment:`${c}/enriched-prompt.md`,research:`${c}/research.md`};for(const[w,D]of Object.entries(j)){const H=w==="research"?_.research:p[w];if(F("sha256").update(g(a(t.sourceRoot,D))).digest("hex")!==H)throw new Error("planning-generation-artifact-drift")}if(F("sha256").update(g(a(t.sourceRoot,l))).digest("hex")!==_.index)throw new Error("planning-generation-index-drift");const b=M(C(t.workspacePath,!0)),N=new RegExp(`^docs/stories/${e}\\.([0-9]{2})\\.story\\.md$`),y=b.paths.filter(w=>N.test(w)).sort((w,D)=>Number(N.exec(w)[1])-Number(N.exec(D)[1]));if(y.length<1||y.length>24||y.some((w,D)=>N.exec(w)[1]!==String(D+1).padStart(2,"0"))||b.paths.length!==y.length+2||b.paths.some(w=>w!==m&&w!==l&&!N.test(w)))throw new Error("planning-generation-write-scope-invalid");const A=[m,l,...y];for(const w of[m,...y]){P(t.sourceRoot,w),P(t.workspacePath,w);try{throw x(a(t.sourceRoot,w)),new Error("planning-generation-path-collision")}catch(H){if(H.code!=="ENOENT")throw H}const D=x(a(t.workspacePath,w));if(!D.isFile()||D.isSymbolicLink()||D.size<128||D.size>(w===m?512:128)*1024)throw new Error("planning-generation-document-invalid")}const R=(w,D)=>{const k=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(w.replace(/\r\n/g,`
7
7
  `))?.[1]?.split(`
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};
8
+ `).filter(I=>I.startsWith(`${D}:`))??[];return k.length===1?k[0].slice(D.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0},U=g(a(t.workspacePath,m),"utf8");if(R(U,"id")!==e||R(U,"stories_count")!==String(y.length)||!U.includes("## Stories"))throw new Error("planning-generation-epic-invalid");for(const[w,D]of y.entries()){const H=g(a(t.workspacePath,D),"utf8"),k=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(H.replace(/\r\n/g,`
9
+ `))?.[1]??"";if(R(H,"id")!==`${e}.${String(w+1).padStart(2,"0")}`||R(H,"epic_id")!==e||/^\s*epic\s*:/m.test(k)||R(H,"status")!=="backlog"||!H.includes("## Acceptance Criteria")||!/\bGiven\b[\s\S]*\bWhen\b[\s\S]*\bThen\b/.test(H))throw new Error("planning-generation-story-invalid")}const L=JSON.parse(g(a(t.sourceRoot,l),"utf8")),$=JSON.parse(g(a(t.workspacePath,l),"utf8")),G=L.epics,B=$.epics,z=G?.[e],W=B?.[e];if(!G||!B||!z||!W||z.id!==e||z.status!=="researched"||!Array.isArray(z.steps_completed)||z.steps_completed.length!==2||!tt(z.steps_completed[0],ut)||!tt(z.steps_completed[1],Rt)||!S(z.output_files,{diagnosis:`${c}/diagnosis.md`,research:`${c}/research.md`})||typeof $.last_scan!="string"||!Number.isFinite(Date.parse($.last_scan))||typeof W.completed_at!="string"||!Number.isFinite(Date.parse(W.completed_at)))throw new Error("planning-generation-index-predecessor-invalid");const X=W.steps_completed?.[2];if(!tt(X,Qt))throw new Error("planning-generation-index-transition-invalid");const Q={...L,last_scan:$.last_scan,epics:{...G,[e]:{...z,status:"generated",steps_completed:[...z.steps_completed,X],completed_at:W.completed_at,output_files:{...z.output_files,epic:m,stories:y}}}};if(!S($,Q))throw new Error("planning-generation-index-transition-invalid");const O=A.map(w=>F("sha256").update(g(a(t.workspacePath,w))).digest("hex")),V=()=>A.every((w,D)=>{try{return P(t.workspacePath,w),F("sha256").update(g(a(t.workspacePath,w))).digest("hex")===O[D]}catch{return!1}});return q(t,A,t.baseSha,bt(t.sourceRoot),V)}catch{throw new Error("private-execution-planning-generation-admission-unverified")}}function Oe(t,r){try{if(!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(r))throw new Error("story-id-invalid");const e=".neocortex/state.json";P(t.sourceRoot,e),P(t.workspacePath,e);const s=JSON.parse(g(a(t.sourceRoot,e),"utf8")),n=JSON.parse(g(a(t.workspacePath,e),"utf8"));if(!s||typeof s!="object"||Array.isArray(s)||!n||typeof n!="object"||Array.isArray(n))throw new Error("state-invalid");const i=s,o=n,f=i.stories,l=o.stories,c=f?.[r],m=l?.[r],h=c?.files_to_modify;if(i.schema_version!==1||o.schema_version!==1||!f||!l||!c||!m||c.id!==r||m.id!==r||m.epic_id!==c.epic_id||!Array.isArray(h)||h.length===0||h.length>dt||h.some(R=>typeof R!="string"||!ot(R)||R.length>1024)||new Set(h).size!==h.length||!S(m.files_to_modify,h))throw new Error("write-set-invalid");const{[r]:u,...v}=f,{[r]:d,...p}=l,{stories:_,last_updated:j,...b}=i,{stories:N,last_updated:y,...A}=o;if(!S(p,v)||!S(A,b))throw new Error("state-unrelated-drift");return q(t,[...h].sort(),t.baseSha)}catch{throw new Error("private-execution-state-step-admission-unverified")}}function Te(t,r,e){if(r==="chaos-plan"&&e==="chaos-quarterly-v1")try{const n=new Date,i=`Q${Math.floor(n.getUTCMonth()/3)+1}-${n.getUTCFullYear()}`,o=M(C(t.workspacePath,!0)).paths,f=`tools/chaos/${i}-plan.md`,l=`.neocortex/chaos-history/${i}.md`,c=o.filter(d=>d.startsWith("tools/chaos/experiments/")),m=c.map(d=>/^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(d));if(!o.includes(f)||!o.includes(l)||c.length<5||c.length>10||o.length!==c.length+2||m.some(d=>!d)||new Set(m.map(d=>d[1])).size!==1)throw new Error("chaos-write-set-invalid");for(const d of o)if(P(t.workspacePath,d),x(a(t.workspacePath,d)).size===0)throw new Error("chaos-empty-artifact");const h=g(a(t.workspacePath,l),"utf8");if(!h.includes(i)||!/\bPLANNED\b/.test(h))throw new Error("chaos-history-invalid");const v=Y(t.workspacePath,["ls-tree","-z","HEAD","--",l]).length>0?Y(t.workspacePath,["show",`HEAD:${l}`]).toString("utf8"):"";if(v&&!h.startsWith(v))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 s=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(!s)throw new Error("private-execution-project-step-admission-unverified");try{if(r==="tech-debt"){const n=".neocortex/tech-debt-registry.json";P(t.workspacePath,n);const i=JSON.parse(g(a(t.workspacePath,n),"utf8"));if(!i||typeof i!="object"||Array.isArray(i))throw new Error("registry-invalid");const o=i;if(o.schema_version!==2||o.version!==void 0&&o.version!==2||!Array.isArray(o.items))throw new Error("registry-invalid")}return q(t,s,t.baseSha)}catch{throw new Error("private-execution-project-step-admission-unverified")}}function Tt(t,r){const e=t==="arch-prd"&&r==="arch-prd-docs-v1"?["docs/architecture/prd.md","docs/architecture/product-experience.md"]:t==="arch-architecture"&&r==="arch-architecture-doc-v1"?["docs/architecture/architecture.md"]:t==="arch-fitness-functions"&&r==="arch-fitness-tools-v1"?["tools/architecture/dependency-cruiser.config.js","tools/architecture/archunit-test.ts","tools/architecture/.eslintrc.boundaries.js"]:t==="arch-api-contracts"&&r==="arch-api-contracts-docs-v1"?["docs/architecture/api-contracts.md","docs/api/openapi.yaml"]:t==="arch-api-integrations"&&r==="arch-api-integrations-doc-v1"?["docs/architecture/api-integrations.md"]:t==="arch-database"&&r==="arch-database-doc-v1"?["docs/architecture/database-schema.md"]:t==="arch-security"&&r==="arch-security-doc-v1"?["docs/architecture/cyber-security.md"]:t==="arch-design-system"&&r==="arch-design-system-doc-v1"?["docs/architecture/atomic-design-system.md"]:t==="arch-performance"&&r==="arch-performance-doc-v1"?["docs/architecture/performance-strategy.md"]:t==="arch-testing"&&r==="arch-testing-doc-v1"?["docs/architecture/testing-strategy.md"]:t==="arch-infrastructure"&&r==="arch-infrastructure-doc-v1"?["docs/architecture/infrastructure-deploy.md"]:t==="arch-review"&&r==="arch-review-doc-v1"?["docs/architecture/review-consolidation.md"]:t==="update-memory"&&r==="arch-memory-canonical-v1"?["NEOCORTEX.md"]:null;return e===null?null:Object.freeze(e)}function je(t,r,e,s="all"){const n=Tt(r,e);if(!n)throw new Error("private-execution-architecture-admission-unverified");return`${t}
10
+
11
+ Private architecture handoff (local only):
12
+ ${JSON.stringify({allowedPaths:n})}
13
+ ${s==="non-ui"?`The server admitted a signed non-UI scope for this snapshot. Preserve the backend-only scope: design-system and UX phases are not applicable. Do not require or generate interface artifacts.
14
+ `:""}Write exactly the listed nonempty artifacts inside this isolated clone. Existing compliant listed artifacts may remain unchanged; all listed artifacts must exist after execution. Place any necessary scope notes inside those artifacts. Do not edit README, package files, other documents, state, Git, QA records or configuration outside the listed paths. Do not install dependencies, use network, deploy or continue to another stage. Preserve existing arch:keep blocks byte-for-byte. Do not add new arch:keep markers. For managed memory, preserve all bytes outside its existing managed block. Root independently reviews artifacts and owns continuation, Git and acceptance.
15
+ `}function Ne(t,r,e,s,n){const i=Tt(r,e);if(!i||!/^P[1-9][0-9]{0,11}$/.test(s)||!/^[a-f0-9]{64}$/.test(n))throw new Error("private-execution-architecture-admission-unverified");try{P(t.workspacePath,".neocortex/state.json");const o=JSON.parse(g(a(t.workspacePath,".neocortex/state.json"),"utf8"));if(!o||typeof o!="object"||Array.isArray(o))throw new Error("state-invalid");const f=o,c=f.archPlan?.execution,m=f.epics;if(!c||c.currentStageCommand!==r||c.targetEpicId!==s||c.graphRevision!==n||!m||!Object.hasOwn(m,s))throw new Error("state-binding-mismatch");if(r==="update-memory"){if(c.continuationState!=="delegate"||c.reviewDecision?.decision!=="approved")throw new Error("memory-root-review-missing");const h="NEOCORTEX.md";if(!M(C(t.workspacePath,!0)).paths.includes(h))throw new Error("memory-effect-missing");P(t.sourceRoot,h),P(t.workspacePath,h);const u=g(a(t.sourceRoot,h),"utf8"),v=g(a(t.workspacePath,h),"utf8"),d="<!-- NEOCORTEX-MEMORY-START -->",p="<!-- NEOCORTEX-MEMORY-END -->",_=y=>{if(y.split(d).length!==2||y.split(p).length!==2||y.indexOf(d)>=y.indexOf(p))throw new Error("memory-markers-invalid");const A=y.indexOf(d)+d.length,R=y.indexOf(p);return{before:y.slice(0,A),body:y.slice(A,R),after:y.slice(R)}},j=_(u),b=_(v);if(j.before!==b.before||j.after!==b.after||j.body===b.body||Buffer.byteLength(v,"utf8")>32768||v.split(`
16
+ `).length>240)throw new Error("memory-managed-block-invalid");const N=new Set(j.body.split(`
17
+ `));for(const y of b.body.split(`
18
+ `))N.has(y)||Mt(y)}if(r==="arch-prd"){const h="docs/architecture/prd.md";if(!M(C(t.workspacePath,!0)).paths.includes(h))throw new Error("prd-effect-missing");if(P(t.workspacePath,h),x(a(t.workspacePath,h)).size===0)throw new Error("prd-empty")}if(r==="arch-api-contracts"||r==="arch-fitness-functions"||r==="arch-api-integrations"||r==="arch-database"||r==="arch-security"||r==="arch-design-system"||r==="arch-performance"||r==="arch-testing"||r==="arch-infrastructure"||r==="arch-review"){const h=M(C(t.workspacePath,!0)).paths;for(const u of i){if(!h.includes(u)&&Y(t.workspacePath,["cat-file","-t",`${t.baseSha}:${u}`]).toString("utf8").trim()!=="blob")throw new Error("architecture-required-effect-missing");if(P(t.workspacePath,u),x(a(t.workspacePath,u)).size===0)throw new Error("architecture-required-effect-empty");if(r==="arch-fitness-functions"){P(t.sourceRoot,u);const v=rt(a(t.sourceRoot,u))?g(a(t.sourceRoot,u),"utf8"):"",d=g(a(t.workspacePath,u),"utf8"),p=At(v),_=At(d);if(!S(_,p))throw new Error("architecture-keep-marker-changed")}}}return q(t,i,t.baseSha)}catch{throw new Error("private-execution-architecture-admission-unverified")}}function De(t,r,e,s){try{if(!/^P[1-9][0-9]{0,11}$/.test(r)||!/^[a-f0-9]{64}$/.test(e)||s.schemaVersion!==1||s.targetEpicId!==r)throw new Error("binding-invalid");const n=Lt(t.sourceRoot,r),i=zt(t.workspacePath,r);if(!S(n,s)||!S(i,s))throw new Error("write-set-invalid");P(t.workspacePath,".neocortex/state.json");const o=JSON.parse(g(a(t.workspacePath,".neocortex/state.json"),"utf8"));if(!o||typeof o!="object"||Array.isArray(o))throw new Error("state-invalid");const f=o,c=f.archPlan?.execution,m=f.epics;if(!c||c.currentStageCommand!=="arch-ux-design"||c.continuationState!=="delegate"||c.targetEpicId!==r||c.graphRevision!==e||!m||!Object.hasOwn(m,r))throw new Error("stage-invalid");const h=M(C(t.workspacePath,!0)).paths;if(h.length!==s.pathCount||h.some(u=>!s.paths.includes(u)))throw new Error("agent-path-unclaimed");for(const u of s.paths){P(t.sourceRoot,u),P(t.workspacePath,u);const v=x(a(t.workspacePath,u));if(!v.isFile()||v.isSymbolicLink()||v.size<1)throw new Error("effect-empty");const d=new TextDecoder("utf-8",{fatal:!0}).decode(g(a(t.workspacePath,u)));if(!d.trim()||d.includes("\0"))throw new Error("effect-invalid")}return Ht(t.workspacePath,s),q(t,s.paths,t.baseSha)}catch{throw new Error("private-execution-ux-admission-unverified")}}function Fe(t,r,e,s,n,i){try{if(!/^P[1-9][0-9]{0,11}$/.test(r)||!/^[a-f0-9]{64}$/.test(e)||s.targetEpicId!==r||s.graphRevision!==e||n.schemaVersion!==1)throw new Error("binding-invalid");const o=Bt(t.sourceRoot);if(!o||!S(o.receipt,s))throw new Error("answers-invalid");const f=_t(t.sourceRoot,o.answers.generateProvider),l=_t(t.workspacePath,o.answers.generateProvider);if(f.outcome!=="ready"||l.outcome!=="ready"||!S(f.writeSet,n)||!S(l.writeSet,n))throw new Error("write-set-invalid");const c=M(C(t.workspacePath,!0)).paths;if(c.some(d=>!n.paths.includes(d)))throw new Error("agent-path-unclaimed");let m=0,h=0;for(const d of n.paths){if(P(t.sourceRoot,d),rt(a(t.sourceRoot,d))||!c.includes(d))throw new Error("effect-missing-or-overwrite");P(t.workspacePath,d);const p=x(a(t.workspacePath,d));if(!p.isFile()||p.size<1)throw new Error("effect-empty");const _=new TextDecoder("utf-8",{fatal:!0}).decode(g(a(t.workspacePath,d))),j=n.interactions.find(N=>N.filePath===d);if(d!==n.providerPath&&!j)throw new Error("private-execution-pact-interaction-missing");const b=Jt(d,_,o.answers.brokerUrl,j,t.workspacePath,o.answers.matchersAggressive);b.consumerBinding==="app-import-candidate"&&m++,b.consumerBinding==="mock-only-scaffold"&&h++}let u=n.paths;if(i){const d=Ut(t.sourceRoot,o.answers.generateProvider),p=_=>F("sha256").update(_).digest("hex");if(i.schemaVersion!==1||i.outcome!=="candidate-unverified"||i.executionVerified!==!1||i.sourceManifestSha256!==p(d.sourceText)||i.sourceLockSha256!==(d.sourceLockText===null?null:p(d.sourceLockText))||i.manifestText!==d.candidateText||!ft(t.sourceRoot,t.workspacePath,t.baseSha,"package.json")||!ft(t.sourceRoot,t.workspacePath,t.baseSha,"package-lock.json"))throw new Error("toolchain-binding-invalid");for(const _ of["package.json","package-lock.json"]){P(t.sourceRoot,_),P(t.workspacePath,_);const j=_==="package.json"?d.sourceText:d.sourceLockText,b=rt(a(t.workspacePath,_))?g(a(t.workspacePath,_),"utf8"):null;if(j!==b)throw new Error("toolchain-clone-raced")}if(mt(a(t.workspacePath,"package.json"),i.manifestText),mt(a(t.workspacePath,"package-lock.json"),i.lockText),qt(t.workspacePath,o.answers.generateProvider).outcome!=="manifest-aligned")throw new Error("toolchain-candidate-invalid");u=[...n.paths,"package.json","package-lock.json"]}const v=q(t,u,t.baseSha);return Object.freeze({...v,consumerBindingCandidateCount:m,consumerScaffoldCount:h})}catch{throw new Error("private-execution-pact-admission-unverified")}}function Ce(t,r,e,s=new Date().toISOString()){try{const n=xt(t.sourceRoot,r);if(!S(n,e)||!pt(t.sourceRoot,t.workspacePath,e.prdPath)||e.aggregates.some(h=>!pt(t.sourceRoot,t.workspacePath,h.implementationFile))||e.writeSet.length===0)throw new Error("plan-drift");const i=M(C(t.workspacePath,!0)).paths;if(!S(i,e.writeSet))throw new Error("agent-path-unclaimed");const o=new Map;for(const h of e.aggregates){P(t.sourceRoot,h.testFile),P(t.workspacePath,h.testFile);const u=x(a(t.workspacePath,h.testFile));if(!u.isFile()||u.isSymbolicLink()||u.size<1||u.size>Z)throw new Error("test-invalid");const v=g(a(t.workspacePath,h.testFile)),d=new TextDecoder("utf-8",{fatal:!0}).decode(v),p=e.language==="typescript"?(d.match(/\b(?:it|test)\s*\(/g)??[]).length:(d.match(/^def\s+test_[A-Za-z0-9_]+\s*\(/gm)??[]).length;if(!d.trim()||d.includes("\0")||p<h.invariantCount||/\b(?:it|test|describe)\s*\.\s*(?:skip|todo|only)\s*\(/.test(d)||!d.includes(String(e.numRuns)))throw new Error("test-invalid");e.language==="typescript"&&Kt({source:d,testFile:h.testFile,implementationFile:h.implementationFile,invariantCount:h.invariantCount,numRuns:e.numRuns}),o.set(h.testFile,F("sha256").update(v).digest("hex"))}P(t.sourceRoot,e.prdPath),P(t.workspacePath,e.prdPath);const f=g(a(t.workspacePath,e.prdPath)),l=new TextDecoder("utf-8",{fatal:!0}).decode(f),c=Xt(l,e,s);mt(a(t.workspacePath,e.prdPath),c);const m=F("sha256").update(c).digest("hex");return q(t,[...e.writeSet,e.prdPath],t.baseSha,void 0,()=>{try{return!S(xt(t.sourceRoot,r),e)||e.aggregates.some(h=>!pt(t.sourceRoot,t.workspacePath,h.implementationFile))||F("sha256").update(g(a(t.workspacePath,e.prdPath))).digest("hex")!==m?!1:[...o].every(([h,u])=>F("sha256").update(g(a(t.workspacePath,h))).digest("hex")===u)}catch{return!1}})}catch{throw new Error("private-execution-property-admission-unverified")}}export{Ne as admitPrivateArchitectureStageWorkspace,Re as admitPrivateEpicClaimWorkspace,$e as admitPrivateGenerateEpicWorkspace,Ae as admitPrivateIdeaDiagnosisWorkspace,Se as admitPrivateIdeaResearchWorkspace,Fe as admitPrivatePactWorkspace,Te as admitPrivateProjectStepWorkspace,Ce as admitPrivatePropertyTestWorkspace,Oe as admitPrivateStateBoundStepWorkspace,De as admitPrivateUxWorkspace,xe as admitPrivateYoloFrozenWorkspace,je as appendPrivateArchitectureHandoff,Tt as privateArchitectureStagePaths,ve as privateYoloSourceFileMatchesSnapshot,be as verifyPrivateYoloRejectedCandidateOrigin,_e as verifyPrivateYoloSnapshotBoundary};
@@ -1,3 +1,4 @@
1
+ import { type RootProjectMemoryEffect } from '../../../shared/dist/yoloop/root-memory-effect.js';
1
2
  import { type PrivateYoloIsolatedAdmissionV1 } from './isolated-admission.js';
2
3
  import { type PrivateYoloIsolatedWorkspaceV1 } from './isolated-workspace.js';
3
4
  export interface PrivateYoloIsolatedSessionV1 {
@@ -12,7 +13,43 @@ export interface PrivateYoloIsolatedSessionV1 {
12
13
  readonly snapshotSha: string;
13
14
  readonly sequence: number;
14
15
  readonly lastPatchSha256: string | null;
16
+ readonly rootMemoryEffect?: RootProjectMemoryEffect;
15
17
  }
18
+ /** Root-owned C07. The child may propose notes; only this controller runs the writer. */
19
+ export declare function acceptPrivateYoloProjectMemoryRootReview(projectRoot: string, request: unknown, options?: {
20
+ /** Root fault observation only; never replaces the writer, proof or accepted result. */
21
+ readonly fault?: (point: 'after-prepared-journal' | 'after-source-admission' | 'before-session-pin') => void | Promise<void>;
22
+ }): Promise<{
23
+ schemaVersion: number;
24
+ outcome: string;
25
+ storyId: string;
26
+ graphRevision: string;
27
+ receiptId: string;
28
+ snapshotSha: string;
29
+ reused: boolean;
30
+ sourceStateUnchanged: boolean;
31
+ phaseRecovered: boolean;
32
+ independentStoryQaAccepted: boolean;
33
+ terminalAccepted: boolean;
34
+ publicSafe: boolean;
35
+ preparedRecovered?: undefined;
36
+ sourceWriteReused?: undefined;
37
+ } | {
38
+ schemaVersion: number;
39
+ outcome: string;
40
+ storyId: string;
41
+ graphRevision: string;
42
+ receiptId: string;
43
+ snapshotSha: string;
44
+ reused: boolean;
45
+ sourceStateUnchanged: boolean;
46
+ preparedRecovered: boolean;
47
+ sourceWriteReused: boolean;
48
+ independentStoryQaAccepted: boolean;
49
+ terminalAccepted: boolean;
50
+ publicSafe: boolean;
51
+ phaseRecovered?: undefined;
52
+ }>;
16
53
  /** Reserve one clone for the exact C01 session, without launching an agent. */
17
54
  export declare function beginPrivateYoloIsolatedSession(workspace: PrivateYoloIsolatedWorkspaceV1, storyId: string, graphRevision: string): Promise<PrivateYoloIsolatedSessionV1>;
18
55
  /** Require a previously admitted patch before accepting a new server graph. */
@@ -39,3 +76,34 @@ export interface PrivateYoloStagedBundleV1 {
39
76
  * immutable base-to-snapshot patch. QA and checkpoint remain separate gates.
40
77
  */
41
78
  export declare function stagePrivateYoloIsolatedSessionBundle(projectRoot: string, storyId: string, graphRevision: string): Promise<PrivateYoloStagedBundleV1>;
79
+ export interface PrivateYoloRejectedCandidateInspectionV1 {
80
+ readonly schemaVersion: 'PrivateYoloRejectedCandidateInspection/1';
81
+ readonly storyId: string;
82
+ readonly graphRevision: string;
83
+ readonly snapshotSha: string;
84
+ readonly sourceHead: string;
85
+ readonly sequence: number;
86
+ readonly candidateDigest: string;
87
+ readonly changedPaths: readonly string[];
88
+ readonly publicSafe: true;
89
+ }
90
+ /** The parent must first observe executor termination. Never resets a source or changes a pin. */
91
+ export declare function inspectPrivateYoloRejectedCandidate(projectRoot: string, storyId: string, graphRevision: string, executorStopped: boolean): Promise<PrivateYoloRejectedCandidateInspectionV1>;
92
+ /** Discard only the explicitly inspected unaccepted delta, after encrypted custody. */
93
+ export declare function discardPrivateYoloRejectedCandidate(projectRoot: string, storyId: string, graphRevision: string, input: {
94
+ readonly expectedCandidateDigest: string;
95
+ readonly executorStopped: true;
96
+ readonly authorizeDiscard: true;
97
+ }): Promise<{
98
+ readonly schemaVersion: 'PrivateYoloRejectedCandidateRecovery/1';
99
+ readonly outcome: 'candidate-discarded';
100
+ readonly archiveId: string;
101
+ readonly archiveSha256: string;
102
+ readonly candidateDigest: string;
103
+ readonly snapshotSha: string;
104
+ readonly sourceHead: string;
105
+ readonly sessionPinPreserved: true;
106
+ readonly sourcePreserved: true;
107
+ readonly checkpointAccepted: false;
108
+ readonly publicSafe: true;
109
+ }>;
@@ -1,2 +1,5 @@
1
- import{execFileSync as k,spawnSync as A}from"node:child_process";import{createHash as x}from"node:crypto";import{existsSync as q,mkdirSync as C,readFileSync as D}from"node:fs";import{homedir as z}from"node:os";import{join as T,resolve as p}from"node:path";import{acquireGitLifecyclePhysicalIntegrationLock as N,assertGitLifecyclePrivateFile as B,ensureGitLifecyclePrivateChildDirectory as j,gitLifecycleRuntimeDirectory as H,readGitLifecycleRuntimeSync as L,releaseGitLifecyclePhysicalIntegrationLock as $}from"../git/git-lifecycle-store.js";import{anchoredAtomicWriteFile as Y}from"../git/secure-filesystem-boundary.js";import{readPrivateYoloFrozenWriteSet as d,readPrivateYoloFrozenWriteSetForTransition as F}from"./clean-baseline.js";import{admitPrivateYoloFrozenWorkspace as M,verifyPrivateYoloSnapshotBoundary as m}from"./isolated-admission.js";import{preparePrivateYoloIsolatedWorkspace as J}from"./isolated-workspace.js";function l(n,t){const e={...process.env};for(const s 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[s];return k("git",[...t],{cwd:n,env:e,encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:3e4,maxBuffer:16*1024*1024}).trim()}function y(n,t){const e={...process.env};for(const s 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[s];return k("git",[...t],{cwd:n,env:e,stdio:["ignore","pipe","pipe"],timeout:3e4,maxBuffer:16*1024*1024})}function b(n,t){const e={...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 e[o];const s=A("git",[...t],{cwd:n,env:e,stdio:"ignore",timeout:3e4});if(s.error||s.signal)throw new Error("git-unverified");return s.status===0}async function P(n,t){const e=await H(n),s=await j(e,"private-execution"),o=`session-${x("sha256").update(t).digest("hex")}.json`;return{parent:s,name:o,path:T(s,o)}}function h(n,t){const e=t.split(".")[0],o=L(n,{required:!0}).epics[e]?.branch_lease,i=o&&typeof o=="object"&&!Array.isArray(o)?o:void 0,r=i?.sessionId;if(i?.ownerStoryId!==t||typeof r!="string"||!/^setup-[a-f0-9]{64}$/.test(r)||r!==i.idempotencyKey)throw new Error("session-lease-invalid");return r}function W(n){const t=JSON.parse(n);if(!t||typeof t!="object"||Array.isArray(t))throw new Error("session-invalid");const e=t,s=e.workspace;if(Object.keys(e).sort().join(",")!==["schemaVersion","kind","storyId","initialGraphRevision","graphRevision","graphHistory","setupSessionId","workspace","snapshotSha","sequence","lastPatchSha256"].sort().join(",")||e.schemaVersion!==1||e.kind!=="private-yolo-isolated-session"||typeof e.storyId!="string"||!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(e.storyId)||typeof e.initialGraphRevision!="string"||!/^[a-f0-9]{64}$/.test(e.initialGraphRevision)||typeof e.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(e.graphRevision)||!Array.isArray(e.graphHistory)||e.graphHistory.length<1||e.graphHistory.length>65||e.graphHistory.some(i=>typeof i!="string"||!/^[a-f0-9]{64}$/.test(i))||new Set(e.graphHistory).size!==e.graphHistory.length||e.graphHistory[0]!==e.initialGraphRevision||e.graphHistory[e.graphHistory.length-1]!==e.graphRevision||typeof e.setupSessionId!="string"||!/^setup-[a-f0-9]{64}$/.test(e.setupSessionId)||typeof e.snapshotSha!="string"||!/^[a-f0-9]{40,64}$/.test(e.snapshotSha)||!Number.isSafeInteger(e.sequence)||Number(e.sequence)<0||Number(e.sequence)>64||Number(e.sequence)===0&&e.initialGraphRevision!==e.graphRevision||Number(e.sequence)===0&&e.lastPatchSha256!==null||Number(e.sequence)>0&&e.lastPatchSha256===null||e.lastPatchSha256!==null&&(typeof e.lastPatchSha256!="string"||!/^[a-f0-9]{64}$/.test(e.lastPatchSha256))||!s||typeof s!="object"||Array.isArray(s))throw new Error("session-invalid");const o=s;if(Object.keys(o).sort().join(",")!==["schemaVersion","sourceRoot","workspacePath","baseSha","executionBranch"].sort().join(",")||o.schemaVersion!==1||typeof o.sourceRoot!="string"||typeof o.workspacePath!="string"||typeof o.baseSha!="string"||!/^[a-f0-9]{40,64}$/.test(o.baseSha)||typeof o.executionBranch!="string"||!o.executionBranch)throw new Error("session-invalid");return e}async function f(n,t){const e=await P(n,t);if(q(e.path))return await B(e.path,e.parent),W(D(e.path,"utf8"))}async function v(n,t){const e=await P(n,t.storyId);await Y(e.parent,e.name,`${JSON.stringify(t)}
2
- `)}async function E(n,t,e,s){const o=await N(n,{kind:"direct",storyId:t,sessionId:e,idempotencyKey:e,expiresAt:new Date(Date.now()+3e5).toISOString(),persistent:!1});if(!o.ok)throw new Error("private-execution-isolated-session-backpressure");try{return await s()}finally{if(!await $(o.path,o.owner))throw new Error("private-execution-isolated-session-lock-unverified")}}async function g(n,t,e,s){G(n,t,e,s);const o=await d(t,e,n.workspace.executionBranch,s);m(n.workspace,o,n.snapshotSha)}function G(n,t,e,s){if(n.storyId!==e||n.graphRevision!==s||n.workspace.sourceRoot!==t||n.setupSessionId!==h(t,e)||n.sequence===0&&n.snapshotSha!==n.workspace.baseSha||n.sequence>0&&n.snapshotSha===n.workspace.baseSha)throw new Error("session-binding-invalid")}async function ie(n,t,e){const s=p(n.sourceRoot);try{const o=h(s,t);return await E(s,t,o,async()=>{const i=await f(s,t);if(i){if(await g(i,s,t,e),i.workspace.workspacePath!==n.workspacePath)throw new Error("session-replacement-denied");return i}const r=await d(s,t,n.executionBranch,e);m(n,r,n.baseSha);const c=Object.freeze({schemaVersion:1,kind:"private-yolo-isolated-session",storyId:t,initialGraphRevision:e,graphRevision:e,graphHistory:[e],setupSessionId:o,workspace:n,snapshotSha:n.baseSha,sequence:0,lastPatchSha256:null});return await v(s,c),c})}catch{throw new Error("private-execution-isolated-session-unverified")}}async function R(n,t,e,s){if(n.graphRevision===s)return await g(n,t,e,s),n;if(n.storyId!==e||n.workspace.sourceRoot!==t||n.setupSessionId!==h(t,e)||n.sequence===0||n.lastPatchSha256===null||n.graphHistory.includes(s)||n.graphHistory.length>=65)throw new Error("session-graph-transition-invalid");const o=await F(t,e,n.workspace.executionBranch,n.initialGraphRevision,s);m(n.workspace,o,n.snapshotSha);const i=Object.freeze({...n,graphRevision:s,graphHistory:Object.freeze([...n.graphHistory,s])});return await v(t,i),await g(i,t,e,s),i}async function oe(n,t,e){const s=p(n);try{const o=h(s,t);return await E(s,t,o,async()=>{const i=await f(s,t);if(!i)throw new Error("session-missing");return R(i,s,t,e)})}catch{throw new Error("private-execution-isolated-session-unverified")}}async function ae(n,t,e,s){const o=p(n);try{const i=h(o,t);return await E(o,t,i,async()=>{const r=await f(o,t);if(r)return R(r,o,t,e);const c=s??T(z(),".local","share","neocortex","private-yolo-workspaces");s===void 0&&C(c,{recursive:!0,mode:448});const a=J(o,c),u=await d(o,t,a.executionBranch,e);m(a,u,a.baseSha);const w=Object.freeze({schemaVersion:1,kind:"private-yolo-isolated-session",storyId:t,initialGraphRevision:e,graphRevision:e,graphHistory:[e],setupSessionId:i,workspace:a,snapshotSha:a.baseSha,sequence:0,lastPatchSha256:null});return await v(o,w),w})}catch{throw new Error("private-execution-isolated-session-unverified")}}async function re(n,t,e){const s=p(n);try{const o=await f(s,t);if(!o)throw new Error("session-missing");return await g(o,s,t,e),o}catch{throw new Error("private-execution-isolated-session-unverified")}}async function ce(n,t,e){const s=p(n);try{const o=h(s,t);return await E(s,t,o,async()=>{const i=await f(s,t);if(!i)throw new Error("session-missing");G(i,s,t,e);const r=await M(i.workspace,t,e,i.snapshotSha,i.sequence===0);l(i.workspace.workspacePath,["add","-A","--",...r.changedPaths]),l(i.workspace.workspacePath,["-c","core.hooksPath=/dev/null","-c","commit.gpgsign=false","-c","user.name=Neocortex Private Session","-c","user.email=private-session@neocortex.invalid","commit","-q","-m",`private snapshot ${t} ${i.sequence+1}`]);const c=l(i.workspace.workspacePath,["rev-parse","HEAD"]),a=await d(s,t,i.workspace.executionBranch,e);m(i.workspace,a,c);const u=Object.freeze({...i,snapshotSha:c,sequence:i.sequence+1,lastPatchSha256:r.patchSha256});return await v(s,u),{session:u,admission:r}})}catch{throw new Error("private-execution-isolated-session-unverified")}}async function he(n,t,e){const s=p(n);try{const o=h(s,t);return await E(s,t,o,async()=>{const i=await f(s,t);if(!i||i.sequence<1)throw new Error("session-incomplete");await g(i,s,t,e);const r=await d(s,t,i.workspace.executionBranch,e),c=i.workspace.workspacePath,a=y(c,["diff","--name-only","-z",i.workspace.baseSha,i.snapshotSha]).toString("utf8").split("\0").filter(Boolean).sort(),u=[".neocortex/state.json",`docs/stories/${t}.story.md`,`.neocortex/stories/${t}/qa-gate-result.json`,`.neocortex/stories/${t}/validation-evidence.md`,`.neocortex/stories/${t}/review.md`];if(a.length===0||a.length>1024||new Set(a).size!==a.length||a.some(S=>!r.includes(S))||u.some(S=>!a.includes(S)))throw new Error("bundle-incomplete");if(!b(s,["diff","--cached","--quiet"])||y(s,["ls-files","-u","-z"]).byteLength!==0)throw new Error("index-not-clean");const w=y(c,["diff","--binary","--full-index",i.workspace.baseSha,i.snapshotSha]);if(w.byteLength===0)throw new Error("bundle-empty");l(s,["add","-A","--",...a]);const I=y(s,["diff","--cached","--binary","--full-index"]),_=y(s,["diff","--cached","--name-only","-z"]).toString("utf8").split("\0").filter(Boolean).sort();if(!I.equals(w)||_.length!==a.length||_.some((S,O)=>S!==a[O])||!b(s,["diff","--quiet"])||l(s,["rev-parse","HEAD"])!==i.workspace.baseSha||l(s,["symbolic-ref","--quiet","--short","HEAD"])!==i.workspace.executionBranch)throw new Error("bundle-raced");return Object.freeze({schemaVersion:1,outcome:"staged-unverified",snapshotSha:i.snapshotSha,bundleSha256:x("sha256").update(I).digest("hex"),changedPaths:Object.freeze(a)})})}catch{throw new Error("private-execution-root-stage-unverified")}}export{ce as admitPrivateYoloIsolatedSessionStep,ie as beginPrivateYoloIsolatedSession,ae as ensurePrivateYoloIsolatedSession,oe as reconcilePrivateYoloIsolatedSession,re as resumePrivateYoloIsolatedSession,he as stagePrivateYoloIsolatedSessionBundle};
1
+ import{execFileSync as ge,spawnSync as je}from"node:child_process";import{createCipheriv as _e,createHash as C,randomBytes as Ee,randomUUID as Ae}from"node:crypto";import{existsSync as Y,lstatSync as U,mkdirSync as Oe,readFileSync as R,unlinkSync as qe}from"node:fs";import{homedir as Te}from"node:os";import{basename as De,dirname as Ge,join as x,resolve as _}from"node:path";import{isRootProjectMemoryEffect as Be,rootProjectMemoryPaths as Ce}from"../../../shared/dist/yoloop/root-memory-effect.js";import{readPrivateRootMemoryScope as Me,privateRootMemoryEffect as Re}from"./root-memory-scope.js";import{executeRootMemoryWriter as Ne,rootMemoryFileState as xe,verifyRootMemoryWriterExecution as ze}from"./root-memory-writer.js";import{rootMemoryGitFileState as He,verifyRootMemoryEffectGitEvidence as $e}from"./root-memory-git-evidence.js";import{parsePrivateRootMemoryRequest as Le}from"./root-memory-request.js";import{rootMemoryOperationJournalName as Ye,readVerifiedPreparedRootMemory as Je}from"./root-memory-recovery.js";import{assertProjectMemoryPaths as Ve}from"../memory/project-memory-path-scope.js";import{isDeepStrictEqual as J}from"node:util";import{acquireGitLifecyclePhysicalIntegrationLock as Fe,applyGitLifecycleRuntimeOverlay as We,assertGitLifecyclePrivateFile as X,ensureGitLifecyclePrivateChildDirectory as he,gitLifecycleRuntimeDirectory as Qe,mutateGitLifecycleRuntime as Ke,readGitLifecycleRuntimeSync as fe,releaseGitLifecyclePhysicalIntegrationLock as Ue}from"../git/git-lifecycle-store.js";import{anchoredAtomicWriteFile as z,anchoredDirectoryIdentity as Xe,anchoredExecuteGit as Ze}from"../git/secure-filesystem-boundary.js";import{privateYoloRecordLocation as et,privateYoloRootOnlySetupReady as tt,readPrivateYoloFrozenWriteSet as M,readPrivateYoloFrozenWriteSetForTransition as at}from"./clean-baseline.js";import{admitPrivateYoloFrozenWorkspace as ot,verifyPrivateYoloSnapshotBoundary as V,verifyPrivateYoloRejectedCandidateOrigin as st}from"./isolated-admission.js";import{preparePrivateYoloIsolatedWorkspace as rt}from"./isolated-workspace.js";async function Pt(t,a,e={}){const o=Le(a),{directive:r,review:s}=o,i=_(t),n=r.storyId,u=n.split(".")[0],p=d=>C("sha256").update(d).digest("hex");let h="session";const f=()=>{throw new Error(`private-root-memory-acceptance-${h}-unverified`)};try{return await D(i,n,b(i,n),async()=>{const d=fe(i,{required:!0}),m=d.epics[u],l=m?.branch_lease,c=await T(i,n);if(!c||m?.graph_revision!==r.graphRevision||l?.ownerStoryId!==n||typeof l.expiresAt!="string"||Date.parse(l.expiresAt)<=Date.now()||c.workspace.executionBranch!==r.executionBranch)return f();ee(c,i,n,r.graphRevision);const S=await he(await Qe(i),"private-execution"),H=Ye(c,o),G=c.rootMemoryEffect===void 0&&Y(x(S,H));G||await A(c,i,n,r.graphRevision);const W=await Xe(i);h="source-evidence",Ve(i,[".neocortex/state.json",`.neocortex/stories/${n}/validation-evidence.md`]);const g=R(x(i,".neocortex/state.json"));if(p(g)!==s.sourceStateSha256)return f();const y=We(JSON.parse(g.toString("utf8")),d).stories?.[n];if(!y||y.checkpoint!==void 0||!Array.isArray(y.steps_completed))return f();const te=[...y.steps_completed],ae=`.neocortex/stories/${n}/validation-evidence.md`,$=U(x(i,ae));if(!$.isFile()||$.isSymbolicLink()||$.nlink!==1||$.size<128||$.size>256*1024||p(R(x(i,ae)))!==s.proposalSha256)return f();const we=x(S,`qa-review-${s.rootQaReceiptId}.json`);h="qa-predecessor",await X(we,S);const oe=R(we);if(oe.length>16384||p(oe)!==s.rootQaReceiptId)return f();const q=JSON.parse(oe.toString("utf8"));if(q.kind!=="private-qa-root-review"||q.storyId!==n||q.sourceHeadSha!==c.workspace.baseSha||q.precommitQaAccepted!==!0||q.independentStoryQaAccepted!==!1||q.terminalAccepted!==!1)return f();const se=p(JSON.stringify(s.notes)),re=w=>`memory-review-${p(JSON.stringify(w))}.json`,me=y.status==="qa-gate-passed"&&typeof y.last_step=="string"&&p(y.last_step)==="8721319de90ade506bc9b72a908d8296856b34a11bc640629178bed3fe32e373"&&te.at(-1)===y.last_step,Se=async w=>{await Ke(i,j=>{if(!J(j.epics[u],m)||!J(j.stories[n],d.stories[n]))return f();j.stories[n]={...j.stories[n],status:"memory-updated",last_step:s.rawStepId,steps_completed:[...te,s.rawStepId]}},{expectedRevision:d.revision,preCommit:async()=>{await A(w,i,n,r.graphRevision)}})};if(c.rootMemoryEffect){if(h="replay",c.rootMemoryEffect.sourceSnapshotSha!==s.snapshotSha||c.rootMemoryEffect.proposalSha256!==se||c.rootMemoryEffect.rootQaReceiptId!==s.rootQaReceiptId)return f();const w=x(S,re(c.rootMemoryEffect));await X(w,S);const j=R(w),k=JSON.parse(j.toString("utf8"));if(k.proposalSha256!==s.proposalSha256||k.notesSha256!==se||!J(k.rootMemoryEffect,c.rootMemoryEffect))return f();const B=y.status==="memory-updated"&&y.last_step===s.rawStepId&&te.at(-1)===s.rawStepId;return!B&&!me?f():(B||(h="phase-recovery",await Se(c)),{schemaVersion:1,outcome:"project-memory-root-accepted",storyId:n,graphRevision:r.graphRevision,receiptId:p(j),snapshotSha:c.snapshotSha,reused:!0,sourceStateUnchanged:!0,phaseRecovered:!B,independentStoryQaAccepted:!1,terminalAccepted:!1,publicSafe:!0})}if(c.snapshotSha!==s.snapshotSha||!me)return f();const I=c.workspace.workspacePath;v(I,["merge-base","--is-ancestor",q.snapshotSha,c.snapshotSha]);const Pe=[`.neocortex/stories/${n}/qa-gate-result.json`,ae,`.neocortex/stories/${n}/tdd-evidence.md`,`docs/stories/${n}.rtm.md`];if(P(I,["diff","--name-only","-z",q.snapshotSha,c.snapshotSha]).toString("utf8").split("\0").filter(Boolean).some(w=>!Pe.includes(w)))return f();const ie=await M(i,n,r.executionBranch,r.graphRevision);if(!ue(i,["diff","--cached","--quiet"]))return f();const Ie=P(i,["status","--porcelain=v1","-z","--untracked-files=all"]);let E,Q,N,K=!1;if(G){h="prepared-recovery";const w=await Je({projectRoot:i,parent:S,current:c,request:o,childPaths:ie});E=w.effect,Q=w.receipt,N=w.patch,K=w.sourceAlreadyApplied}else{for(const L of Ce())if(ie.includes(L)||!J(xe(i,L),He(I,c.snapshotSha,L)))return f();h="writer";const w=await he(S,"memory-backups"),j=Ne({snapshotRoot:I,expectedSnapshotSha:c.snapshotSha,notes:s.notes,backupDirectory:w}),k=ze(j);h="writer-snapshot",k.files.length&&(v(I,["add","-A","--",...k.files.map(L=>L.path)]),v(I,["-c","core.hooksPath=/dev/null","-c","commit.gpgsign=false","-c","user.name=Neocortex Private Session","-c","user.email=private-session@neocortex.invalid","commit","-q","-m",`private root memory ${n} ${c.sequence+1}`]));const B=v(I,["rev-parse","HEAD"]);E={schemaVersion:"RootProjectMemoryEffect/1",producer:"root-project-memory",storyId:n,epicId:u,executionBranch:r.executionBranch,sourceHeadSha:c.workspace.baseSha,sourceSnapshotSha:c.snapshotSha,memorySnapshotSha:B,graphRevision:r.graphRevision,childClaimRevision:p([...ie].sort().join("\0")),setupSessionId:c.setupSessionId,rootQaReceiptId:s.rootQaReceiptId,proposalSha256:k.notesSha256,canonicalSha256:k.verification.canonicalSha256,projectionSha256:k.verification.projectionSha256,projectionFileCount:k.verification.fileCount,files:k.files,recordedAt:s.reviewedAt,publicSafe:!0},h="git-evidence",$e(I,E,{storyId:n,graphRevision:r.graphRevision,childClaimRevision:E.childClaimRevision,setupSessionId:c.setupSessionId,sourceHeadSha:c.workspace.baseSha,executionBranch:r.executionBranch}),N=P(I,["diff","--binary","--full-index",c.snapshotSha,B]),Q={schemaVersion:1,kind:"private-project-memory-root-review",storyId:n,graphRevision:r.graphRevision,sourceHeadSha:c.workspace.baseSha,snapshotSha:B,proposalSha256:s.proposalSha256,notesSha256:se,sourceStateSha256:s.sourceStateSha256,checks:s.checks,reviewedAt:s.reviewedAt,rootMemoryEffect:E,independentStoryQaAccepted:!1,terminalAccepted:!1},h="prepared-journal",await z(S,H,JSON.stringify({schemaVersion:1,kind:"prepared-root-memory-effect",previousSession:c,receipt:Q,patchSha256:p(N)})+`
2
+ `),await e.fault?.("after-prepared-journal")}const ne=JSON.stringify(Q)+`
3
+ `,ye=E.memorySnapshotSha;if(h="source-admission",!P(i,["status","--porcelain=v1","-z","--untracked-files=all"]).equals(Ie)||v(i,["rev-parse","HEAD"])!==c.workspace.baseSha||v(i,["symbolic-ref","--short","HEAD"])!==r.executionBranch)return f();if(!K){for(const w of E.files)if(!J(xe(i,w.path),w.before))return f()}const ve=w=>Ze(Ge(i),De(i),W,["apply",...w?["--check"]:[],"--binary","-"],N);if(N.length&&!K&&(await ve(!0),await ve(!1)),await e.fault?.("after-source-admission"),!R(x(i,".neocortex/state.json")).equals(g))return f();const ce=x(S,re(E));if(Y(ce)){if(await X(ce,S),R(ce,"utf8")!==ne)return f()}else await z(S,re(E),ne);const pe=Object.freeze({...c,snapshotSha:ye,sequence:c.sequence+(E.files.length?1:0),lastPatchSha256:E.files.length?p(N):c.lastPatchSha256,rootMemoryEffect:E});return h="session-pin",await e.fault?.("before-session-pin"),await F(i,pe),await A(pe,i,n,r.graphRevision),h="phase-transition",await Se(pe),{schemaVersion:1,outcome:"project-memory-root-accepted",storyId:n,graphRevision:r.graphRevision,receiptId:p(ne),snapshotSha:ye,reused:G,sourceStateUnchanged:!0,preparedRecovered:G,sourceWriteReused:K,independentStoryQaAccepted:!1,terminalAccepted:!1,publicSafe:!0}})}catch(d){if(d instanceof Error&&/^(private-root-memory|private-execution-isolated)-[a-z0-9-]+$/.test(d.message)?d.message:void 0)throw new Error(`private-root-memory-acceptance-${h}-unverified`,{cause:d});return f()}}function v(t,a){const e={...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 e[o];return ge("git",[...a],{cwd:t,env:e,encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:3e4,maxBuffer:16*1024*1024}).trim()}function P(t,a){const e={...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 e[o];return ge("git",[...a],{cwd:t,env:e,stdio:["ignore","pipe","pipe"],timeout:3e4,maxBuffer:16*1024*1024})}function ue(t,a){const e={...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 e[r];const o=je("git",[...a],{cwd:t,env:e,stdio:"ignore",timeout:3e4});if(o.error||o.signal)throw new Error("git-unverified");return o.status===0}async function de(t,a){return et(t,a,"session",b(t,a))}function b(t,a){const e=a.split(".")[0],r=fe(t,{required:!0}).epics[e]?.branch_lease,s=r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,i=s?.sessionId;if(s?.ownerStoryId!==a||typeof i!="string"||!/^setup-[a-f0-9]{64}$/.test(i)||i!==s.idempotencyKey)throw new Error("session-lease-invalid");return i}function ke(t,a){const e=fe(t,{required:!0}).stories[a];return tt(e)}function it(t){const a=JSON.parse(t);if(!a||typeof a!="object"||Array.isArray(a))throw new Error("session-invalid");const e=a,o=e.workspace;if(Object.keys(e).sort().join(",")!==["schemaVersion","kind","storyId","initialGraphRevision","graphRevision","graphHistory","setupSessionId","workspace","snapshotSha","sequence","lastPatchSha256",...e.rootMemoryEffect===void 0?[]:["rootMemoryEffect"]].sort().join(",")||e.schemaVersion!==1||e.kind!=="private-yolo-isolated-session"||typeof e.storyId!="string"||!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(e.storyId)||typeof e.initialGraphRevision!="string"||!/^[a-f0-9]{64}$/.test(e.initialGraphRevision)||typeof e.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(e.graphRevision)||!Array.isArray(e.graphHistory)||e.graphHistory.length<1||e.graphHistory.length>65||e.graphHistory.some(s=>typeof s!="string"||!/^[a-f0-9]{64}$/.test(s))||new Set(e.graphHistory).size!==e.graphHistory.length||e.graphHistory[0]!==e.initialGraphRevision||e.graphHistory[e.graphHistory.length-1]!==e.graphRevision||typeof e.setupSessionId!="string"||!/^setup-[a-f0-9]{64}$/.test(e.setupSessionId)||typeof e.snapshotSha!="string"||!/^[a-f0-9]{40,64}$/.test(e.snapshotSha)||!Number.isSafeInteger(e.sequence)||Number(e.sequence)<0||Number(e.sequence)>64||Number(e.sequence)===0&&e.initialGraphRevision!==e.graphRevision&&e.graphHistory.length!==2||Number(e.sequence)===0&&e.lastPatchSha256!==null||Number(e.sequence)>0&&e.lastPatchSha256===null||e.lastPatchSha256!==null&&(typeof e.lastPatchSha256!="string"||!/^[a-f0-9]{64}$/.test(e.lastPatchSha256))||e.rootMemoryEffect!==void 0&&!Be(e.rootMemoryEffect)||!o||typeof o!="object"||Array.isArray(o))throw new Error("session-invalid");const r=o;if(Object.keys(r).sort().join(",")!==["schemaVersion","sourceRoot","workspacePath","baseSha","executionBranch"].sort().join(",")||r.schemaVersion!==1||typeof r.sourceRoot!="string"||typeof r.workspacePath!="string"||typeof r.baseSha!="string"||!/^[a-f0-9]{40,64}$/.test(r.baseSha)||typeof r.executionBranch!="string"||!r.executionBranch)throw new Error("session-invalid");return e}async function T(t,a){const e=await de(t,a);if(Y(e.path))return await X(e.path,e.parent),it(R(e.path,"utf8"))}async function F(t,a){const e=await de(t,a.storyId);await z(e.parent,e.name,`${JSON.stringify(a)}
4
+ `)}async function D(t,a,e,o){const r=await Fe(t,{kind:"direct",storyId:a,sessionId:e,idempotencyKey:e,expiresAt:new Date(Date.now()+3e5).toISOString(),persistent:!1});if(!r.ok)throw new Error("private-execution-isolated-session-backpressure");try{return await o()}finally{if(!await Ue(r.path,r.owner))throw new Error("private-execution-isolated-session-lock-unverified")}}async function A(t,a,e,o){ee(t,a,e,o);const r=await M(a,e,t.workspace.executionBranch,o),s=await Z(t,r);return V(t.workspace,r,t.snapshotSha,s),s}async function Z(t,a){if(t.rootMemoryEffect===void 0)return;const e=await Me({projectRoot:t.workspace.sourceRoot,storyId:t.storyId,snapshotRoot:t.workspace.workspacePath,snapshotSha:t.snapshotSha,sourceHeadSha:t.workspace.baseSha,executionBranch:t.workspace.executionBranch,graphRevision:t.graphRevision,setupSessionId:t.setupSessionId,childPaths:a});if(!e||JSON.stringify(Re(e))!==JSON.stringify(t.rootMemoryEffect))throw new Error("private-root-memory-scope-unverified");return e}function ee(t,a,e,o){if(t.storyId!==e||t.graphRevision!==o||t.workspace.sourceRoot!==a||t.setupSessionId!==b(a,e)||t.sequence===0&&t.snapshotSha!==t.workspace.baseSha||t.sequence===0&&t.graphHistory.length>1&&!ke(a,e)||t.sequence>0&&t.snapshotSha===t.workspace.baseSha)throw new Error("session-binding-invalid")}async function It(t,a,e){const o=_(t.sourceRoot);try{const r=b(o,a);return await D(o,a,r,async()=>{const s=await T(o,a);if(s){if(await A(s,o,a,e),s.workspace.workspacePath!==t.workspacePath)throw new Error("session-replacement-denied");return s}const i=await M(o,a,t.executionBranch,e);V(t,i,t.baseSha);const n=Object.freeze({schemaVersion:1,kind:"private-yolo-isolated-session",storyId:a,initialGraphRevision:e,graphRevision:e,graphHistory:[e],setupSessionId:r,workspace:t,snapshotSha:t.baseSha,sequence:0,lastPatchSha256:null});return await F(o,n),n})}catch{throw new Error("private-execution-isolated-session-unverified")}}async function be(t,a,e,o){if(t.graphRevision===o)return await A(t,a,e,o),t;if(t.storyId!==e||t.workspace.sourceRoot!==a||t.setupSessionId!==b(a,e)||t.sequence===0&&(t.graphHistory.length!==1||t.lastPatchSha256!==null||!ke(a,e))||t.sequence>0&&t.lastPatchSha256===null||t.graphHistory.includes(o)||t.graphHistory.length>=65)throw new Error("session-graph-transition-invalid");const r=await at(a,e,t.workspace.executionBranch,t.initialGraphRevision,o);V(t.workspace,r,t.snapshotSha,await Z(t,r));const s=Object.freeze({...t,graphRevision:o,graphHistory:Object.freeze([...t.graphHistory,o])});return await F(a,s),await A(s,a,e,o),s}async function jt(t,a,e){const o=_(t);try{const r=b(o,a);return await D(o,a,r,async()=>{const s=await T(o,a);if(!s)throw new Error("session-missing");return be(s,o,a,e)})}catch{throw new Error("private-execution-isolated-session-unverified")}}async function _t(t,a,e,o){const r=_(t);try{const s=b(r,a);return await D(r,a,s,async()=>{const i=await T(r,a);if(i)return be(i,r,a,e);const n=o??x(Te(),".local","share","neocortex","private-yolo-workspaces");o===void 0&&Oe(n,{recursive:!0,mode:448});const u=rt(r,n),p=await M(r,a,u.executionBranch,e);V(u,p,u.baseSha);const h=Object.freeze({schemaVersion:1,kind:"private-yolo-isolated-session",storyId:a,initialGraphRevision:e,graphRevision:e,graphHistory:[e],setupSessionId:s,workspace:u,snapshotSha:u.baseSha,sequence:0,lastPatchSha256:null});return await F(r,h),h})}catch{throw new Error("private-execution-isolated-session-unverified")}}async function At(t,a,e){const o=_(t);try{const r=await T(o,a);if(!r)throw new Error("session-missing");return await A(r,o,a,e),r}catch{throw new Error("private-execution-isolated-session-unverified")}}async function Ot(t,a,e){const o=_(t);try{const r=b(o,a);return await D(o,a,r,async()=>{const s=await T(o,a);if(!s)throw new Error("session-missing");ee(s,o,a,e);const i=await M(o,a,s.workspace.executionBranch,e),n=await Z(s,i),u=await ot(s.workspace,a,e,s.snapshotSha,!1,n);v(s.workspace.workspacePath,["add","-A","--",...u.changedPaths]),v(s.workspace.workspacePath,["-c","core.hooksPath=/dev/null","-c","commit.gpgsign=false","-c","user.name=Neocortex Private Session","-c","user.email=private-session@neocortex.invalid","commit","-q","-m",`private snapshot ${a} ${s.sequence+1}`]);const p=v(s.workspace.workspacePath,["rev-parse","HEAD"]);V(s.workspace,i,p,n);const h=Object.freeze({...s,snapshotSha:p,sequence:s.sequence+1,lastPatchSha256:u.patchSha256});return await F(o,h),{session:h,admission:u}})}catch{throw new Error("private-execution-isolated-session-unverified")}}async function qt(t,a,e){const o=_(t);try{const r=b(o,a);return await D(o,a,r,async()=>{const s=await T(o,a);if(!s||s.sequence<1)throw new Error("session-incomplete");const i=await A(s,o,a,e),n=await M(o,a,s.workspace.executionBranch,e),u=s.workspace.workspacePath,p=P(u,["diff","--name-only","-z",s.workspace.baseSha,s.snapshotSha]).toString("utf8").split("\0").filter(Boolean).sort(),h=[".neocortex/state.json",`docs/stories/${a}.story.md`,`.neocortex/stories/${a}/qa-gate-result.json`,`.neocortex/stories/${a}/validation-evidence.md`,`.neocortex/stories/${a}/review.md`];if(p.length===0||p.length>1024||new Set(p).size!==p.length||p.some(l=>!n.includes(l)&&!(i&&Re(i).files.some(c=>c.path===l)))||h.some(l=>!p.includes(l)))throw new Error("bundle-incomplete");if(!ue(o,["diff","--cached","--quiet"])||P(o,["ls-files","-u","-z"]).byteLength!==0)throw new Error("index-not-clean");const f=P(u,["diff","--binary","--full-index",s.workspace.baseSha,s.snapshotSha]);if(f.byteLength===0)throw new Error("bundle-empty");v(o,["add","-A","--",...p]);const d=P(o,["diff","--cached","--binary","--full-index"]),m=P(o,["diff","--cached","--name-only","-z"]).toString("utf8").split("\0").filter(Boolean).sort();if(!d.equals(f)||m.length!==p.length||m.some((l,c)=>l!==p[c])||!ue(o,["diff","--quiet"])||v(o,["rev-parse","HEAD"])!==s.workspace.baseSha||v(o,["symbolic-ref","--quiet","--short","HEAD"])!==s.workspace.executionBranch)throw new Error("bundle-raced");return Object.freeze({schemaVersion:1,outcome:"staged-unverified",snapshotSha:s.snapshotSha,bundleSha256:C("sha256").update(d).digest("hex"),changedPaths:Object.freeze(p)})})}catch{throw new Error("private-execution-root-stage-unverified")}}function nt(t){const a=t.workspace.workspacePath,e=P(a,["status","--porcelain=v1","-z","-uall"]),o=e.toString("utf8").split("\0").filter(Boolean);if(o.length<1||o.length>1024)throw new Error("rejected-candidate-invalid");let r=0;const s=o.map(n=>{const u=n.slice(0,2),p=n.slice(3);if(![" M"," D","??"].includes(u)||p.length<1||p.length>1024||p.startsWith("/")||/[\\\x00-\x1f\x7f]/.test(p)||p.split("/").some(l=>!l||l==="."||l===".."||l===".git"))throw new Error("rejected-candidate-path-invalid");const h=p.split("/");for(let l=1;l<h.length;l++){const c=x(a,...h.slice(0,l));if(!Y(c))break;const S=U(c);if(!S.isDirectory()||S.isSymbolicLink()||S.uid!==process.getuid?.())throw new Error("rejected-candidate-parent-invalid")}const f=x(a,p);if(u===" D"){if(Y(f))throw new Error("rejected-candidate-raced");return{path:p,code:u,mode:null,sha256:null,content:null}}const d=U(f);if(!d.isFile()||d.isSymbolicLink()||d.nlink!==1||d.uid!==process.getuid?.()||d.size>16*1024*1024)throw new Error("rejected-candidate-file-invalid");const m=R(f);if(r+=m.byteLength,r>16*1024*1024)throw new Error("rejected-candidate-too-large");return{path:p,code:u,mode:d.mode&511,sha256:C("sha256").update(m).digest("hex"),content:m}});if(new Set(s.map(n=>n.path)).size!==s.length)throw new Error("rejected-candidate-path-invalid");const i={schemaVersion:"PrivateYoloRejectedCandidateInspection/1",storyId:t.storyId,graphRevision:t.graphRevision,snapshotSha:t.snapshotSha,sourceHead:t.workspace.baseSha,sequence:t.sequence,statusSha256:C("sha256").update(e).digest("hex"),files:s.map(({content:n,...u})=>u)};return{files:s,inspection:{schemaVersion:i.schemaVersion,storyId:i.storyId,graphRevision:i.graphRevision,snapshotSha:i.snapshotSha,sourceHead:i.sourceHead,sequence:i.sequence,candidateDigest:C("sha256").update(JSON.stringify(i)).digest("hex"),changedPaths:s.map(n=>n.path),publicSafe:!0}}}async function le(t,a,e){const o=await T(t,a);if(!o)throw new Error("session-missing");ee(o,t,a,e);const r=await M(t,a,o.workspace.executionBranch,e);return st(o.workspace,r,o.snapshotSha,await Z(o,r)),{record:o,...nt(o)}}async function Tt(t,a,e,o){if(o!==!0)throw new Error("private-execution-rejected-candidate-executor-not-stopped");const r=_(t);try{return await D(r,a,b(r,a),async()=>(await le(r,a,e)).inspection)}catch{throw new Error("private-execution-rejected-candidate-unverified")}}async function Dt(t,a,e,o){if(o.executorStopped!==!0||o.authorizeDiscard!==!0||!/^[a-f0-9]{64}$/.test(o.expectedCandidateDigest))throw new Error("private-execution-rejected-candidate-input-invalid");const r=_(t);try{return await D(r,a,b(r,a),async()=>{const s=await le(r,a,e);if(s.inspection.candidateDigest!==o.expectedCandidateDigest)throw new Error("candidate-review-stale");const i=await de(r,a),n=R(i.path),u=`rejected-${Ae()}`,p=await he(i.parent,u),h=Ee(32),f=Ee(12),d=Buffer.from(JSON.stringify({schemaVersion:"PrivateYoloRejectedCandidateArchive/1",inspection:s.inspection,files:s.files.map(({content:g,...O})=>({...O,contentBase64:g?.toString("base64")??null}))})),m=_e("aes-256-gcm",h,f);m.setAAD(Buffer.from("private-yolo-rejected-candidate-v1"));const l=Buffer.concat([m.update(d),m.final()]);d.fill(0);const c=Buffer.concat([f,m.getAuthTag(),l]);try{await z(p,"candidate.key",h),await z(p,"candidate.aesgcm",c)}finally{h.fill(0)}if((await le(r,a,e)).inspection.candidateDigest!==o.expectedCandidateDigest||!R(i.path).equals(n))throw new Error("candidate-raced");const H=s.record.workspace.workspacePath,G=s.files.filter(g=>g.code!=="??").map(g=>g.path);G.length&&v(H,["restore","--source",s.record.snapshotSha,"--worktree","--",...G]);for(const g of s.files.filter(O=>O.code==="??")){const O=x(H,g.path),y=U(O);if(!y.isFile()||y.isSymbolicLink()||y.nlink!==1||C("sha256").update(R(O)).digest("hex")!==g.sha256)throw new Error("candidate-raced");qe(O)}if(await A(s.record,r,a,e),!R(i.path).equals(n))throw new Error("session-pin-raced");const W={schemaVersion:"PrivateYoloRejectedCandidateRecovery/1",outcome:"candidate-discarded",archiveId:u,archiveSha256:C("sha256").update(c).digest("hex"),candidateDigest:o.expectedCandidateDigest,snapshotSha:s.record.snapshotSha,sourceHead:s.record.workspace.baseSha,sessionPinPreserved:!0,sourcePreserved:!0,checkpointAccepted:!1,publicSafe:!0};return await z(p,"recovery.json",`${JSON.stringify(W)}
5
+ `),W})}catch{throw new Error("private-execution-rejected-candidate-recovery-unverified")}}export{Pt as acceptPrivateYoloProjectMemoryRootReview,Ot as admitPrivateYoloIsolatedSessionStep,It as beginPrivateYoloIsolatedSession,Dt as discardPrivateYoloRejectedCandidate,_t as ensurePrivateYoloIsolatedSession,Tt as inspectPrivateYoloRejectedCandidate,jt as reconcilePrivateYoloIsolatedSession,At as resumePrivateYoloIsolatedSession,qt as stagePrivateYoloIsolatedSessionBundle};
@@ -6,4 +6,4 @@ export interface PactSourceInspectionV1 {
6
6
  readonly publicSafe: true;
7
7
  }
8
8
  /** Reject comment-only, malformed and non-Pact files before a root patch effect. */
9
- export declare function validatePactTestSource(path: string, source: string, brokerUrl: string | null, expectedInteraction?: PactInteractionV1, projectRoot?: string): PactSourceInspectionV1;
9
+ export declare function validatePactTestSource(path: string, source: string, brokerUrl: string | null, expectedInteraction?: PactInteractionV1, projectRoot?: string, matchersAggressive?: boolean): PactSourceInspectionV1;
@@ -1 +1 @@
1
- import{parse as T}from"@babel/parser";import{lstatSync as S,realpathSync as C}from"node:fs";import{join as P,posix as j,resolve as k}from"node:path";const I=256*1024,V=1e5;function c(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function _(e){const n=new Set;if(!Array.isArray(e.specifiers))return n;for(const s of e.specifiers)!c(s)||s.type!=="ImportSpecifier"||!c(s.imported)||typeof s.imported.name!="string"||n.add(s.imported.name);return n}function O(e,n,s){const t=c(e.source)?e.source.value:void 0;if(typeof t!="string"||t.length>240||!/^\.\.?\/[A-Za-z0-9_./-]+$/.test(t)||e.importKind==="type"||!Array.isArray(e.specifiers)||e.specifiers.length<1||e.specifiers.length>16)throw new Error("private-execution-pact-source-invalid");const r=j.normalize(j.join(j.dirname(n),t));if(!/^(?:src|app|lib|packages|clients)\/[A-Za-z0-9_./-]+$/.test(r)||r.split("/").some(o=>o===".."||o==="."))throw new Error("private-execution-pact-source-invalid");const a=k(s);if(C(a)!==a||!S(a).isDirectory())throw new Error("private-execution-pact-source-invalid");const d=/\.(?:ts|tsx|js|mjs)$/.test(r)?[r,...r.endsWith(".js")?[`${r.slice(0,-3)}.ts`,`${r.slice(0,-3)}.tsx`]:[]]:[`${r}.ts`,`${r}.tsx`,`${r}.js`,`${r}.mjs`,`${r}/index.ts`,`${r}/index.tsx`,`${r}/index.js`],l=[];for(const o of d){let h=a;try{const v=o.split("/");for(const[w,E]of v.entries()){h=P(h,E);const m=S(h);if(m.isSymbolicLink()||(w===v.length-1?!m.isFile()||m.size<1||m.size>1024*1024:!m.isDirectory()))throw new Error("private-execution-pact-source-invalid")}l.push(o)}catch(v){if(v.code!=="ENOENT")throw new Error("private-execution-pact-source-invalid")}}if(l.length!==1)throw new Error("private-execution-pact-source-invalid");const y=new Set;for(const o of e.specifiers){if(!c(o)||!["ImportSpecifier","ImportDefaultSpecifier"].includes(o.type)||o.importKind==="type"||!c(o.local)||o.local.type!=="Identifier"||typeof o.local.name!="string")throw new Error("private-execution-pact-source-invalid");y.add(o.local.name)}return y}function b(e){if(!(!c(e)||e.type!=="MemberExpression"||e.computed===!0||!c(e.property)||e.property.type!=="Identifier"))return typeof e.property.name=="string"?e.property.name:void 0}function q(e){if(!c(e)||e.type!=="ObjectExpression"||!Array.isArray(e.properties))return;let n,s;for(const t of e.properties){if(!c(t)||t.type!=="ObjectProperty"||t.computed===!0||!c(t.key)||!c(t.value))return;const r=t.key.type==="Identifier"?t.key.name:t.key.type==="StringLiteral"?t.key.value:void 0;if(r==="method"||r==="path"){if(t.value.type!=="StringLiteral"||typeof t.value.value!="string")return;if(r==="method"){if(n!==void 0)return;n=t.value.value}else{if(s!==void 0)return;s=t.value.value}}}return n!==void 0&&s!==void 0?{method:n,path:s}:void 0}function z(e,n){if(e.length>180||n.length>2048||/[?#]/.test(n))return!1;const s=e.split("/"),t=n.split("/");return s.length!==t.length?!1:s.every((r,a)=>{const d=t[a];if(!r.includes("{")&&!r.includes("}"))return r===d;const l=/^([^{}]*)\{[^{}]+\}([^{}]*)$/.exec(r);return!l||!d.startsWith(l[1])||!d.endsWith(l[2])?!1:d.length>l[1].length+l[2].length})}function D(e,n,s,t,r){const a=e==="tests/pact/provider/verify.test.ts"?"provider":"consumer";if(a==="consumer"&&!/^tests\/pact\/consumer\/[a-z0-9-]+\.test\.ts$/.test(e)||typeof n!="string"||Buffer.byteLength(n,"utf8")<80||Buffer.byteLength(n,"utf8")>I||s!==null&&n.includes(s))throw new Error("private-execution-pact-source-invalid");let d;try{d=T(n,{sourceType:"module",plugins:["typescript"]})}catch{throw new Error("private-execution-pact-source-invalid")}const l=new Set,y=new Set,o=new Set;for(const u of d.program.body){if(u.type!=="ImportDeclaration")continue;const i=u.source.value;if(i!=="@pact-foundation/pact"&&i!=="vitest"){if(a!=="consumer"||!r)throw new Error("private-execution-pact-source-invalid");for(const f of O(u,e,r)){if(o.has(f)||["fetch","describe","it","expect","PactV3","MatchersV3","Verifier"].includes(f))throw new Error("private-execution-pact-source-invalid");o.add(f)}continue}const p=_(u);for(const f of p)(i==="@pact-foundation/pact"?l:y).add(f)}if(!y.has("describe")||!y.has("it")||a==="consumer"&&(!l.has("PactV3")||!y.has("expect"))||a==="provider"&&!l.has("Verifier")||[...o].some(u=>l.has(u)||y.has(u)))throw new Error("private-execution-pact-source-invalid");const h=new Set,v=new Set;let w=!1,E=!1,m=!1;const g=[{node:d.program,inExecuteTest:!1}];let A=0;for(;g.length>0;){const u=g.pop(),i=u.node;if(c(i)){if(++A>V)throw new Error("private-execution-pact-source-invalid");if(i.type==="NewExpression"&&c(i.callee)&&i.callee.type==="Identifier"&&typeof i.callee.name=="string"&&(v.add(i.callee.name),u.inExecuteTest&&o.has(i.callee.name)&&(m=!0)),i.type==="CallExpression"){const p=i.callee;c(p)&&p.type==="Identifier"&&typeof p.name=="string"&&(h.add(p.name),u.inExecuteTest&&o.has(p.name)&&(m=!0));const f=b(p);if(f&&h.add(f),f==="withRequest"&&t&&Array.isArray(i.arguments)){const x=q(i.arguments[0]);E||=x?.method.toUpperCase()===t.method&&z(t.endpointPath,x?.path??"")}}i.type==="MemberExpression"&&b(i)==="PACT_BROKER_URL"&&c(i.object)&&b(i.object)==="env"&&c(i.object.object)&&i.object.object.type==="Identifier"&&i.object.object.name==="process"&&(w=!0);for(const[p,f]of Object.entries(i)){if(p==="loc"||p==="extra"||p==="comments"||p==="leadingComments"||p==="trailingComments"||p==="innerComments")continue;const x=u.inExecuteTest||i.type==="CallExpression"&&b(i.callee)==="executeTest"&&p==="arguments";if(Array.isArray(f))for(const $ of f)g.push({node:$,inExecuteTest:x});else c(f)&&g.push({node:f,inExecuteTest:x})}}}if((a==="consumer"?["describe","it","withRequest","willRespondWith","executeTest","expect"]:["describe","it","verifyProvider"]).some(u=>!h.has(u))||!v.has(a==="consumer"?"PactV3":"Verifier")||a==="consumer"&&t!==void 0&&(t.filePath!==e||!E)||a==="provider"&&s!==null&&!w)throw new Error("private-execution-pact-source-invalid");return Object.freeze({schemaVersion:1,consumerBinding:a==="provider"?"provider-template":m?"app-import-candidate":"mock-only-scaffold",executionVerified:!1,publicSafe:!0})}export{D as validatePactTestSource};
1
+ import{parse as T}from"@babel/parser";import{lstatSync as A,realpathSync as C}from"node:fs";import{join as k,posix as S,resolve as I}from"node:path";const V=256*1024,_=1e5;function a(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function O(e){const n=new Set;if(!Array.isArray(e.specifiers))return n;for(const s of e.specifiers)!a(s)||s.type!=="ImportSpecifier"||!a(s.imported)||typeof s.imported.name!="string"||n.add(s.imported.name);return n}function q(e,n,s){const t=a(e.source)?e.source.value:void 0;if(typeof t!="string"||t.length>240||!/^\.\.?\/[A-Za-z0-9_./-]+$/.test(t)||e.importKind==="type"||!Array.isArray(e.specifiers)||e.specifiers.length<1||e.specifiers.length>16)throw new Error("private-execution-pact-source-invalid");const r=S.normalize(S.join(S.dirname(n),t));if(!/^(?:src|app|lib|packages|clients)\/[A-Za-z0-9_./-]+$/.test(r)||r.split("/").some(o=>o===".."||o==="."))throw new Error("private-execution-pact-source-invalid");const m=I(s);if(C(m)!==m||!A(m).isDirectory())throw new Error("private-execution-pact-source-invalid");const c=/\.(?:ts|tsx|js|mjs)$/.test(r)?[r,...r.endsWith(".js")?[`${r.slice(0,-3)}.ts`,`${r.slice(0,-3)}.tsx`]:[]]:[`${r}.ts`,`${r}.tsx`,`${r}.js`,`${r}.mjs`,`${r}/index.ts`,`${r}/index.tsx`,`${r}/index.js`],l=[];for(const o of c){let d=m;try{const y=o.split("/");for(const[x,E]of y.entries()){d=k(d,E);const v=A(d);if(v.isSymbolicLink()||(x===y.length-1?!v.isFile()||v.size<1||v.size>1024*1024:!v.isDirectory()))throw new Error("private-execution-pact-source-invalid")}l.push(o)}catch(y){if(y.code!=="ENOENT")throw new Error("private-execution-pact-source-invalid")}}if(l.length!==1)throw new Error("private-execution-pact-source-invalid");const h=new Set;for(const o of e.specifiers){if(!a(o)||!["ImportSpecifier","ImportDefaultSpecifier"].includes(o.type)||o.importKind==="type"||!a(o.local)||o.local.type!=="Identifier"||typeof o.local.name!="string")throw new Error("private-execution-pact-source-invalid");h.add(o.local.name)}return h}function b(e){if(!(!a(e)||e.type!=="MemberExpression"||e.computed===!0||!a(e.property)||e.property.type!=="Identifier"))return typeof e.property.name=="string"?e.property.name:void 0}function z(e){if(!a(e)||e.type!=="ObjectExpression"||!Array.isArray(e.properties))return;let n,s;for(const t of e.properties){if(!a(t)||t.type!=="ObjectProperty"||t.computed===!0||!a(t.key)||!a(t.value))return;const r=t.key.type==="Identifier"?t.key.name:t.key.type==="StringLiteral"?t.key.value:void 0;if(r==="method"||r==="path"){if(t.value.type!=="StringLiteral"||typeof t.value.value!="string")return;if(r==="method"){if(n!==void 0)return;n=t.value.value}else{if(s!==void 0)return;s=t.value.value}}}return n!==void 0&&s!==void 0?{method:n,path:s}:void 0}function L(e,n){if(e.length>180||n.length>2048||/[?#]/.test(n))return!1;const s=e.split("/"),t=n.split("/");return s.length!==t.length?!1:s.every((r,m)=>{const c=t[m];if(!r.includes("{")&&!r.includes("}"))return r===c;const l=/^([^{}]*)\{[^{}]+\}([^{}]*)$/.exec(r);return!l||!c.startsWith(l[1])||!c.endsWith(l[2])?!1:c.length>l[1].length+l[2].length})}function M(e,n,s,t,r,m){const c=e==="tests/pact/provider/verify.test.ts"?"provider":"consumer";if(c==="consumer"&&!/^tests\/pact\/consumer\/[a-z0-9-]+\.test\.ts$/.test(e)||typeof n!="string"||Buffer.byteLength(n,"utf8")<80||Buffer.byteLength(n,"utf8")>V||s!==null&&n.includes(s))throw new Error("private-execution-pact-source-invalid");let l;try{l=T(n,{sourceType:"module",plugins:["typescript"]})}catch{throw new Error("private-execution-pact-source-invalid")}const h=new Set,o=new Set,d=new Set;for(const p of l.program.body){if(p.type!=="ImportDeclaration")continue;const i=p.source.value;if(i!=="@pact-foundation/pact"&&i!=="vitest"){if(c!=="consumer"||!r)throw new Error("private-execution-pact-source-invalid");for(const f of q(p,e,r)){if(d.has(f)||["fetch","describe","it","expect","PactV3","MatchersV3","Verifier"].includes(f))throw new Error("private-execution-pact-source-invalid");d.add(f)}continue}const u=O(p);for(const f of u)(i==="@pact-foundation/pact"?h:o).add(f)}if(!o.has("describe")||!o.has("it")||c==="consumer"&&(!h.has("PactV3")||!o.has("expect"))||c==="provider"&&!h.has("Verifier")||[...d].some(p=>h.has(p)||o.has(p)))throw new Error("private-execution-pact-source-invalid");if(c==="consumer"&&m===!1&&[...h].some(p=>p!=="PactV3"))throw new Error("private-execution-pact-source-invalid");const y=new Set,x=new Set;let E=!1,v=!1,j=!1;const g=[{node:l.program,inExecuteTest:!1}];let $=0;for(;g.length>0;){const p=g.pop(),i=p.node;if(a(i)){if(++$>_)throw new Error("private-execution-pact-source-invalid");if(i.type==="NewExpression"&&a(i.callee)&&i.callee.type==="Identifier"&&typeof i.callee.name=="string"&&(x.add(i.callee.name),p.inExecuteTest&&d.has(i.callee.name)&&(j=!0)),i.type==="CallExpression"){const u=i.callee;a(u)&&u.type==="Identifier"&&typeof u.name=="string"&&(y.add(u.name),p.inExecuteTest&&d.has(u.name)&&(j=!0));const f=b(u);if(f&&y.add(f),f==="withRequest"&&t&&Array.isArray(i.arguments)){const w=z(i.arguments[0]);v||=w?.method.toUpperCase()===t.method&&L(t.endpointPath,w?.path??"")}}i.type==="MemberExpression"&&b(i)==="PACT_BROKER_URL"&&a(i.object)&&b(i.object)==="env"&&a(i.object.object)&&i.object.object.type==="Identifier"&&i.object.object.name==="process"&&(E=!0);for(const[u,f]of Object.entries(i)){if(u==="loc"||u==="extra"||u==="comments"||u==="leadingComments"||u==="trailingComments"||u==="innerComments")continue;const w=p.inExecuteTest||i.type==="CallExpression"&&b(i.callee)==="executeTest"&&u==="arguments";if(Array.isArray(f))for(const P of f)g.push({node:P,inExecuteTest:w});else a(f)&&g.push({node:f,inExecuteTest:w})}}}if((c==="consumer"?["describe","it","withRequest","willRespondWith","executeTest","expect"]:["describe","it","verifyProvider"]).some(p=>!y.has(p))||!x.has(c==="consumer"?"PactV3":"Verifier")||c==="consumer"&&t!==void 0&&(t.filePath!==e||!v)||c==="provider"&&s!==null&&!E)throw new Error("private-execution-pact-source-invalid");return Object.freeze({schemaVersion:1,consumerBinding:c==="provider"?"provider-template":j?"app-import-candidate":"mock-only-scaffold",executionVerified:!1,publicSafe:!0})}export{M as validatePactTestSource};
@@ -22,6 +22,8 @@ export interface PlanningDiagnosisRootReviewV1 {
22
22
  readonly intake: Readonly<Record<string, unknown>>;
23
23
  readonly artifactSummary: string;
24
24
  }
25
+ /** Read only an owner-private pending claim file; absence is an explicit snapshot. */
26
+ export declare function planningPendingSidecarDigest(root: string): string | undefined;
25
27
  export declare function planningPhysicalPatchDigest(root: string, paths: Readonly<Record<string, string>>, ownTemporaryPath?: string, allowPendingSidecar?: boolean): string;
26
28
  /** P02 may consume only a physically sealed P01 for the same durable claim. */
27
29
  export declare function acceptedPlanningDiagnosisPredecessor(stateInput: unknown, claimId: string, epicId: string, allowResearched?: boolean): {