@ornexus/neocortex 4.60.64 → 4.60.66

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 (87) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +31 -38
  3. package/install.js +1 -0
  4. package/install.ps1 +34 -3
  5. package/install.sh +35 -3
  6. package/package.json +9 -5
  7. package/packages/client/dist/cli.js +1 -1
  8. package/packages/client/dist/commands/architecture-non-ui-continuation.js +1 -1
  9. package/packages/client/dist/commands/architecture-root-binding.js +1 -1
  10. package/packages/client/dist/commands/invoke.d.ts +1 -1
  11. package/packages/client/dist/commands/invoke.js +79 -78
  12. package/packages/client/dist/commands/mutation-qa-run.js +2 -2
  13. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +1 -1
  14. package/packages/client/dist/commands/refactor-characterization.d.ts +3 -10
  15. package/packages/client/dist/commands/refactor-characterization.js +16 -16
  16. package/packages/client/dist/commands/refactor-control.d.ts +3 -11
  17. package/packages/client/dist/commands/refactor-control.js +3 -3
  18. package/packages/client/dist/commands/refactor-review.d.ts +0 -13
  19. package/packages/client/dist/commands/refactor-review.js +5 -6
  20. package/packages/client/dist/commands/refactor-root.d.ts +0 -157
  21. package/packages/client/dist/commands/refactor-root.js +7 -12
  22. package/packages/client/dist/commands/shared-architecture-non-ui.d.ts +18 -0
  23. package/packages/client/dist/commands/shared-architecture-non-ui.js +1 -0
  24. package/packages/client/dist/commands/story-checkpoint.d.ts +3 -1
  25. package/packages/client/dist/commands/story-checkpoint.js +1 -1
  26. package/packages/client/dist/git/direct-yolo-c01-retry.d.ts +21 -0
  27. package/packages/client/dist/git/direct-yolo-c01-retry.js +4 -0
  28. package/packages/client/dist/git/git-lifecycle-store.js +1 -1
  29. package/packages/client/dist/private-execution/clean-baseline.d.ts +2 -9
  30. package/packages/client/dist/private-execution/clean-baseline.js +2 -2
  31. package/packages/client/dist/private-execution/codex-executor.d.ts +1 -25
  32. package/packages/client/dist/private-execution/codex-executor.js +4 -9
  33. package/packages/client/dist/private-execution/delivery.d.ts +1 -2
  34. package/packages/client/dist/private-execution/delivery.js +3 -3
  35. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -2
  36. package/packages/client/dist/private-execution/frozen-handoff.js +4 -5
  37. package/packages/client/dist/private-execution/implementation-validation.d.ts +1 -10
  38. package/packages/client/dist/private-execution/implementation-validation.js +2 -2
  39. package/packages/client/dist/private-execution/isolated-admission.d.ts +2 -0
  40. package/packages/client/dist/private-execution/isolated-admission.js +16 -11
  41. package/packages/client/dist/private-execution/isolated-session.d.ts +1 -1
  42. package/packages/client/dist/private-execution/isolated-session.js +5 -5
  43. package/packages/client/dist/private-execution/root-memory-git-evidence.d.ts +1 -1
  44. package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -3
  45. package/packages/client/dist/private-execution/root-memory-recovery.d.ts +1 -1
  46. package/packages/client/dist/private-execution/root-memory-recovery.js +1 -1
  47. package/packages/client/dist/private-execution/root-memory-scope.d.ts +1 -1
  48. package/packages/client/dist/private-execution/root-memory-scope.js +1 -1
  49. package/packages/client/dist/private-execution/root-memory-writer.d.ts +1 -1
  50. package/packages/client/dist/private-execution/root-memory-writer.js +1 -1
  51. package/packages/client/dist/private-execution/shared-private-admission-types.d.ts +34 -0
  52. package/packages/client/dist/private-execution/shared-private-admission-types.js +1 -0
  53. package/packages/client/dist/private-execution/shared-project-validation.d.ts +17 -0
  54. package/packages/client/dist/private-execution/shared-project-validation.js +1 -0
  55. package/packages/client/dist/private-execution/shared-root-memory-types.d.ts +37 -0
  56. package/packages/client/dist/private-execution/shared-root-memory-types.js +1 -0
  57. package/packages/client/dist/private-execution/ux-source-validation.js +1 -1
  58. package/packages/client/dist/runner/binary.d.ts +1 -1
  59. package/packages/client/dist/runner/binary.js +1 -1
  60. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -2
  61. package/packages/client/dist/runner-cli.js +0 -0
  62. package/packages/client/dist/yolo/invoke-envelope-capability.d.ts +16 -0
  63. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -0
  64. package/packages/client/dist/yolo/spec-envelope-collector.d.ts +7 -0
  65. package/packages/client/dist/yolo/spec-envelope-collector.js +3 -3
  66. package/packages/shared/dist/architecture-non-ui-scope.js +22 -0
  67. package/packages/shared/dist/architecture-public-topology.js +11 -0
  68. package/packages/shared/dist/project-validation-commands.js +10 -32
  69. package/packages/shared/dist/yolo/spec-envelope.js +2 -0
  70. package/targets-stubs/antigravity/gemini.md +1 -1
  71. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  72. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  73. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  74. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  75. package/targets-stubs/claude-code/neocortex.md +2 -2
  76. package/targets-stubs/codex/AGENTS.md +1 -1
  77. package/targets-stubs/cursor/agent.md +2 -2
  78. package/targets-stubs/deepseek-harness/SKILL.md +64 -0
  79. package/targets-stubs/gemini-cli/agent.md +2 -2
  80. package/targets-stubs/opencode/neocortex-root.md +1 -1
  81. package/targets-stubs/vscode/neocortex.agent.md +2 -2
  82. package/packages/client/dist/commands/shared-architecture-non-ui-contract.d.ts +0 -19
  83. package/packages/client/dist/commands/shared-architecture-non-ui-contract.js +0 -1
  84. package/packages/shared/dist/invocation/packed-invoke.d.ts +0 -12
  85. package/packages/shared/dist/invocation/packed-invoke.js +0 -58
  86. package/packages/shared/dist/invocation/packed-invoke.test.d.ts +0 -1
  87. package/packages/shared/dist/invocation/packed-invoke.test.js +0 -21
@@ -1,18 +1,23 @@
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,`
1
+ import{execFileSync as Nt,spawnSync as wt}from"node:child_process";import{createHash as F}from"node:crypto";import{existsSync as nt,lstatSync as x,readFileSync as m,realpathSync as ht,writeFileSync as mt}from"node:fs";import{isAbsolute as ot,join as a,relative as dt,sep as vt}from"node:path";import{isDeepStrictEqual as S}from"node:util";import{readPrivateYoloFrozenWriteSet as Dt,verifyPrivateYoloCandidateWriteSet as Ft,verifyPrivateYoloCleanBaseline as Bt}from"./clean-baseline.js";import{PRIVATE_EPIC_PENDING_SIDECAR as et}from"./isolated-workspace.js";import{loadPactPrivateAnswers as Ct}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 qt,privateRootMemorySourceMatchReason as Gt}from"./root-memory-scope.js";import{inspectPactToolchain as Yt,planPactToolchainManifest as Ut}from"./pact-toolchain.js";import{acceptedPlanningDiagnosisPredecessor as Wt,planningPendingSidecarDigest as bt}from"./planning-diagnosis-checkpoint.js";import{acceptedPlanningResearchPredecessor as Vt}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,st=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 G(t,r){return Nt("git",[...r],{cwd:t,env:Et(),stdio:["ignore","pipe","pipe"],timeout:3e4,maxBuffer:Z})}function J(t,r){return G(t,r).toString("utf8").trim()}function B(t,r=!1){return G(t,["status","--porcelain=v1","-z","--untracked-files=all",...r?["--ignored=matching"]:[]])}function rt(t){return!!t&&!ot(t)&&!t.includes("\\")&&!t.includes("\0")&&!t.split("/").some(r=>!r||r==="."||r===".."||r===".git")}function P(t,r){const e=r.split("/");let n=t;for(const o of e.slice(0,-1)){n=a(n,o);try{const i=x(n);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("path-boundary")}catch(i){if(i.code==="ENOENT")return;throw i}}try{const o=x(a(t,r));if(!o.isFile()||o.isSymbolicLink()||o.size>Z)throw new Error("path-boundary")}catch(o){if(o.code!=="ENOENT")throw o}}function At(t){const r=[...t.matchAll(/\/\/\s*arch:keep-start[^\n]*\n[\s\S]*?\/\/\s*arch:keep-end[^\n]*/g)].map(o=>o[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,n=[]){const o=[],i=[];for(const s of t.toString("utf8").split("\0").filter(Boolean)){if(s.length<4||s[2]!==" ")throw new Error("status-invalid");const d=s.slice(0,2),l=s.slice(3);if(!rt(l)||d!=="??"&&d!==" M"&&d!==" D"&&!(d===" T"&&n.includes(l))&&!(e&&d==="!!"&&l===et))throw new Error("status-invalid");o.push(l),d==="??"&&i.push(l)}if(!r&&o.length===0||o.length>st||new Set(o).size!==o.length)throw new Error("status-invalid");return{paths:o.sort(),untracked:i.sort()}}function lt(t,r,e,n){const o=G(r,["ls-tree","-z",e,"--",n]).toString("utf8");if(!o)try{return x(a(t,n)),!1}catch(s){return s.code==="ENOENT"}const i=/^([0-7]{6}) blob [a-f0-9]{40,64}\t([^\0]+)\0$/.exec(o);if(!i||i[2]!==n||!["100644","100755"].includes(i[1]))return!1;try{const s=x(a(t,n));return!s.isFile()||s.isSymbolicLink()||s.size>Z||!!(s.mode&73)!=(i[1]==="100755")?!1:m(a(t,n)).equals(G(r,["show",`${e}:${n}`]))}catch{return!1}}function ve(t,r,e,n){return rt(n)&&/^[a-f0-9]{40,64}$/.test(e)&&lt(t,r,e,n)}function it(t,r){try{const e=a(t,et),n=x(a(t,".neocortex")),o=x(e);return n.isDirectory()&&!n.isSymbolicLink()&&n.uid===process.getuid?.()&&(n.mode&18)===0&&o.isFile()&&!o.isSymbolicLink()&&o.uid===process.getuid?.()&&(o.mode&63)===0&&o.size>0&&o.size<=128*1024&&F("sha256").update(m(e)).digest("hex")===r}catch{return!1}}function ft(t,r,e,n,o,i){const s=new Set(n),d=i?yt(i).files.map(f=>f.path):[],l=M(B(t),!0,!!o,d),c=i?Gt(i,t,r,e):"matched";if(c!=="matched")throw new Error(`root-memory-${c}`);if(!l.paths.every(f=>s.has(f)||d.includes(f)||f===et&&!!o&&it(t,o)))throw new Error("source-unclaimed-delta");if(!n.every(f=>lt(t,r,e,f)))throw new Error("source-frozen-mismatch");return!o||it(t,o)}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 n=wt("git",["apply",...e?["--check"]:[],"--binary","-"],{cwd:t,env:Et(),input:r,encoding:"buffer",timeout:3e4,maxBuffer:Z});if(n.error||n.status!==0)throw new Error("apply-failed")}function pt(t,r,e){const n=a(t,e),o=a(r,e);try{const i=x(n),s=x(o);return i.isFile()&&s.isFile()&&(i.mode&73)===(s.mode&73)&&m(n).equals(m(o))}catch(i){if(i.code!=="ENOENT")return!1;try{return x(n),!1}catch(s){if(s.code!=="ENOENT")return!1}try{return x(o),!1}catch(s){return s.code==="ENOENT"}}}function _e(t,r,e,n){$t(t,r,e,!0,n)}function be(t,r,e,n){if($t(t,r,e,!1,n),G(t.workspacePath,["diff","--cached","--name-only"]).byteLength!==0)throw new Error("private-execution-isolated-snapshot-unverified")}function $t(t,r,e,n,o){try{if(process.platform!=="linux"||t.schemaVersion!==1||!ot(t.sourceRoot)||!ot(t.workspacePath)||ht(t.sourceRoot)!==t.sourceRoot||ht(t.workspacePath)!==t.workspacePath||!x(t.workspacePath).isDirectory()||(x(t.workspacePath).mode&63)!==0||dt(t.sourceRoot,t.workspacePath)===""||dt(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||nt(a(t.workspacePath,".git","objects","info","alternates"))||n&&B(t.workspacePath,!0).byteLength!==0||r.length===0||r.length>st||r.some(i=>!rt(i))||new Set(r).size!==r.length)throw new Error("boundary-invalid");if(G(t.workspacePath,["merge-base","--is-ancestor",t.baseSha,e]),!ft(t.sourceRoot,t.workspacePath,e,r,void 0,o))throw new Error("boundary-raced")}catch(i){const s=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(s)})}}function Y(t,r,e,n,o,i=[],s){try{if(process.platform!=="linux"||t.schemaVersion!==1||!ot(t.sourceRoot)||!ot(t.workspacePath)||ht(t.sourceRoot)!==t.sourceRoot||ht(t.workspacePath)!==t.workspacePath||!x(t.workspacePath).isDirectory()||(x(t.workspacePath).mode&63)!==0||dt(t.sourceRoot,t.workspacePath)===""||dt(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>st||r.some(g=>!rt(g))||new Set(r).size!==r.length)throw new Error("authority-invalid");if(G(t.workspacePath,["merge-base","--is-ancestor",t.baseSha,e]),!ft(t.sourceRoot,t.workspacePath,e,r,n,s))throw new Error("source-snapshot-mismatch");const d=B(t.workspacePath,!0),l=M(d),c=new Set(r);if(l.paths.some(g=>!c.has(g)||i.includes(g)))throw new Error("path-unclaimed");if(o&&!o())throw new Error("candidate-raced");for(const g of l.paths)P(t.workspacePath,g),P(t.sourceRoot,g);const h=[G(t.workspacePath,["diff","--binary","--no-ext-diff","--no-textconv","HEAD","--"]),...l.untracked.map(g=>kt(t.workspacePath,g))],p=Buffer.concat(h.map(g=>Buffer.concat([g,Buffer.from(`
2
+ `)])));if(p.byteLength===0||p.byteLength>Z||!B(t.workspacePath,!0).equals(d)||o&&!o()||!ft(t.sourceRoot,t.workspacePath,e,r,n,s))throw new Error("patch-raced");if(St(t.sourceRoot,p,!0),!B(t.workspacePath,!0).equals(d)||o&&!o()||!ft(t.sourceRoot,t.workspacePath,e,r,n,s))throw new Error("patch-raced");St(t.sourceRoot,p,!1);const v=s?yt(s).files.map(g=>g.path):[];if(M(B(t.sourceRoot),!0,!!n,v).paths.some(g=>!c.has(g)&&!v.includes(g)&&g!==et)||s&&!qt(s,t.sourceRoot)||n&&!it(t.sourceRoot,n)||r.some(g=>!pt(t.workspacePath,t.sourceRoot,g))||J(t.sourceRoot,["rev-parse","HEAD"])!==t.baseSha||J(t.sourceRoot,["symbolic-ref","--short","HEAD"])!==t.executionBranch)throw new Error("admission-raced");return Object.freeze({schemaVersion:1,outcome:"admitted-unverified",baseSha:t.baseSha,executionBranch:t.executionBranch,changedPaths:Object.freeze([...l.paths]),patchSha256:F("sha256").update(p).digest("hex")})}catch{throw new Error("private-execution-isolated-admission-unverified")}}async function xe(t,r,e,n=t.baseSha,o=!1,i){try{const s=await Dt(t.sourceRoot,r,t.executionBranch,e);if(i){const f=yt(i);if(f.storyId!==r||f.childClaimRevision!==F("sha256").update([...s].sort().join("\0")).digest("hex"))throw new Error("root-memory-claim-mismatch")}const d=a(t.workspacePath,".neocortex","state.json"),l=x(d);if(!l.isFile()||l.isSymbolicLink()||l.size>Z)throw new Error("candidate-state-invalid");Ft(m(d,"utf8"),r,s);const c=Y(t,s,n,void 0,void 0,o?[".neocortex/state.json"]:[],i);return await Bt(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(n=>typeof n=="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,n,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]*$/.test(e)||!/^[a-f0-9]{64}$/.test(n)||!/^[a-f0-9]{64}$/.test(o)||!it(t.sourceRoot,o))throw new Error("claim-invalid");const i=JSON.parse(m(a(t.sourceRoot,et),"utf8")),s=i&&typeof i=="object"&&!Array.isArray(i)?i.operations?.[n]:void 0;if(!s||typeof s!="object"||Array.isArray(s)||s.claimId!==r||s.epicId!==e)throw new Error("claim-sidecar-mismatch");const d=M(B(t.workspacePath,!0)),l=`docs/epics/epic-${e}.md`,c=".neocortex/state.json",f=new RegExp(`^docs/stories/${e}\\.[0-9]{2}\\.story\\.md$`),h=d.paths.filter(E=>f.test(E));if(!d.paths.includes(l)||!d.paths.includes(c)||h.length===0||h.length>99||d.paths.some(E=>E!==l&&E!==c&&E!=="NEOCORTEX.md"&&!f.test(E)))throw new Error("artifact-scope-invalid");const p=h.map(E=>E.slice(13,-9)).sort();if(p.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=m(a(t.workspacePath,E),"utf8");return Buffer.byteLength(K)>Z?null:/^---\r?\n([\s\S]{1,8192}?)\r?\n---(?:\r?\n|$)/.exec(K)?.[1]?.split(/\r?\n/).find(ct=>ct.startsWith(`${T}:`))?.slice(T.length+1).trim()?.replace(/^(["'])(.*)\1$/,"$2")??null};if(v(l,"id")!==e||h.some((E,T)=>v(E,"id")!==p[T]||v(E,"epic_id")!==e))throw new Error("artifact-id-invalid");P(t.workspacePath,c);const u=JSON.parse(m(a(t.workspacePath,c),"utf8"));if(!u||typeof u!="object"||Array.isArray(u))throw new Error("state-invalid");const g=u,_=g.epics,j=g.stories,b=_?.[e],N=g.epic_id_ledger;if(g.schema_version!==1||!b||b.id!==e||b.status!=="memory-updated"||Object.keys(b).some(E=>!te.has(E))||!Ot(b)||b.completed_stories!==void 0&&b.completed_stories!==0||b.total_stories!==void 0&&b.total_stories!==p.length||!Array.isArray(b.stories)||b.stories.length!==p.length||b.stories.some((E,T)=>E!==p[T])||!j||p.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(m(a(t.sourceRoot,c),"utf8")),A=y.epics,R=y.stories;if(!A||!R||A[e]!==void 0||p.some(E=>R[E]!==void 0))throw new Error("state-claim-conflict");const{[e]:U,...L}=_,$={...j};for(const E of p)delete $[E];const{epic_id_ledger:q,last_updated:C,...z}=y,{epic_id_ledger:V,last_updated:X,...Q}=g;if(!S(L,A)||!S($,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:W,...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 Y(t,d.paths,t.baseSha,o)}catch{throw new Error("private-execution-epic-claim-admission-unverified")}}function Ae(t,r,e,n,o,i){try{if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(r)||!/^P[1-9][0-9]{0,11}$/.test(e)||!/^[a-f0-9]{64}$/.test(n)||!/^[a-f0-9]{64}$/.test(o)||typeof i!="string"||!i.trim()||i.length>16384||!it(t.sourceRoot,o))throw new Error("planning-claim-invalid");const s=JSON.parse(m(a(t.sourceRoot,et),"utf8")),d=s&&typeof s=="object"&&!Array.isArray(s)?s.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 l=`.neocortex/planning/epic-${e}`,c=`${l}/idea.json`,f=`${l}/diagnosis.md`,h=`${l}/enriched-prompt.md`,p=".neocortex/planning/planning.json",v=[c,f,h,p],u=M(B(t.workspacePath,!0));if(u.paths.length!==v.length||u.paths.some(E=>!v.includes(E)))throw new Error("planning-artifact-scope-invalid");for(const E of[c,f,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 g=(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 m(a(t.workspacePath,E),"utf8")},_=JSON.parse(g(c,32*1024));if(!_||typeof _!="object"||Array.isArray(_)||_.epic_id!==e||_.status!=="diagnosed"||typeof _.raw_input!="string"||_.raw_input!==i)throw new Error("planning-idea-invalid");const j=g(f,256*1024),b=g(h,256*1024),N=(E,T)=>{const K=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(E.replace(/\r\n/g,`
3
3
  `))?.[1];if(!K)return!1;const Pt=K.split(`
4
- `),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,`
4
+ `),at=gt=>{const ct=Pt.filter(jt=>jt.startsWith(`${gt}:`));return ct.length===1?ct[0].slice(gt.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0};return at("epic_id")===e&&tt(at("step"),T)&&at("status")==="completed"};if(!N(j,ut)||!N(b,Zt))throw new Error("planning-document-identity-invalid");P(t.workspacePath,p),P(t.sourceRoot,p);const y=JSON.parse(g(p,128*1024)),A=nt(a(t.sourceRoot,p))?JSON.parse(m(a(t.sourceRoot,p),"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,q=$?.output_files;if(!L||typeof L!="object"||Array.isArray(L)||$?.id!==e||$.status!=="diagnosed"||$.idea!==_.raw_input||!Array.isArray($.steps_completed)||$.steps_completed.length!==1||!tt($.steps_completed[0],ut)||typeof $.created_at!="string"||!Number.isFinite(Date.parse($.created_at))||$.completed_at!==null||!q||typeof q!="object"||Array.isArray(q)||!S(q,{diagnosis:`${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:C,epics:z,...V}=R,X=A,Q=X?.epics,{last_scan:O,epics:W,...w}=X??{},{[e]:D,...H}=U;if(Q?.[e]!==void 0||!S(H,Q??{})||X!==void 0&&!S(V,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(m(a(t.workspacePath,E))).digest("hex")),I=()=>v.every((E,T)=>{try{return P(t.workspacePath,E),F("sha256").update(m(a(t.workspacePath,E))).digest("hex")===k[T]}catch{return!1}});return Y(t,v,t.baseSha,o,I)}catch{throw new Error("private-execution-planning-diagnosis-admission-unverified")}}function Se(t,r,e,n,o,i){try{if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(r)||!/^P[1-9][0-9]{0,11}$/.test(e)||!/^[a-f0-9]{64}$/.test(n)||!/^[a-f0-9]{64}$/.test(o)||!/^[a-f0-9]{64}$/.test(i))throw new Error("planning-research-binding-invalid");const s=".neocortex/state.json",d=".neocortex/planning/planning.json",l=`.neocortex/planning/epic-${e}`,c=`${l}/research.md`;if(P(t.sourceRoot,s),P(t.workspacePath,s),P(t.sourceRoot,d),P(t.workspacePath,d),P(t.sourceRoot,c),P(t.workspacePath,c),x(a(t.sourceRoot,s)).size>8*1024*1024||x(a(t.workspacePath,s)).size>8*1024*1024||x(a(t.sourceRoot,d)).size>128*1024||x(a(t.workspacePath,d)).size>128*1024)throw new Error("planning-research-source-size-invalid");const f=m(a(t.sourceRoot,s));if(F("sha256").update(f).digest("hex")!==i||!f.equals(m(a(t.workspacePath,s))))throw new Error("planning-research-state-drift");const h=JSON.parse(f.toString("utf8")),p=Wt(h,r,e);if(p.diagnosisReceiptId!==n||p.intakeRevision!==o)throw new Error("planning-research-predecessor-mismatch");const u=h.epics[e].createEpicPlanningPhysical.artifactDigests;for(const[O,W]of Object.entries({idea:`${l}/idea.json`,diagnosis:`${l}/diagnosis.md`,enrichment:`${l}/enriched-prompt.md`,index:d}))if(P(t.sourceRoot,W),F("sha256").update(m(a(t.sourceRoot,W))).digest("hex")!==u[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 g=[c,d],_=M(B(t.workspacePath,!0));if(_.paths.length!==g.length||_.paths.some(O=>!g.includes(O)))throw new Error("planning-research-write-scope-invalid");const j=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=m(a(t.workspacePath,c),"utf8"),N=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(b.replace(/\r\n/g,`
5
+ `))?.[1],y=O=>{const W=N?.split(`
6
+ `).filter(w=>w.startsWith(`${O}:`))??[];return W.length===1?W[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(m(a(t.sourceRoot,d),"utf8")),R=JSON.parse(m(a(t.workspacePath,d),"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,q=L.epics,C=$?.[e];if(!$||Array.isArray($)||!q||Array.isArray(q)||!C||Array.isArray(C)||C.id!==e||C.idea!==p.rawIntent||C.status!=="diagnosed"||!Array.isArray(C.steps_completed)||C.steps_completed.length!==1||!tt(C.steps_completed[0],ut)||!S(C.output_files,{diagnosis:`${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={...C,status:"researched",steps_completed:[...C.steps_completed,y("step")],output_files:{diagnosis:`${l}/diagnosis.md`,research:c}},V={...U,last_scan:L.last_scan,epics:{...$,[e]:z}};if(!S(L,V))throw new Error("planning-research-index-drift");const X=g.map(O=>F("sha256").update(m(a(t.workspacePath,O))).digest("hex")),Q=()=>g.every((O,W)=>{try{return P(t.workspacePath,O),F("sha256").update(m(a(t.workspacePath,O))).digest("hex")===X[W]}catch{return!1}});return Y(t,g,t.baseSha,bt(t.sourceRoot),Q)}catch{throw new Error("private-execution-planning-research-admission-unverified")}}function $e(t,r,e,n,o,i,s){try{if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(r)||!/^P[1-9][0-9]{0,11}$/.test(e)||[n,o,i,s].some(w=>!/^[a-f0-9]{64}$/.test(w)))throw new Error("planning-generation-binding-invalid");const d=".neocortex/state.json",l=".neocortex/planning/planning.json",c=`.neocortex/planning/epic-${e}`,f=`docs/epics/epic-${e}.md`;for(const w of[d,l,`${c}/idea.json`,`${c}/diagnosis.md`,`${c}/enriched-prompt.md`,`${c}/research.md`]){P(t.sourceRoot,w),P(t.workspacePath,w);const D=m(a(t.sourceRoot,w));if(w!==l&&!D.equals(m(a(t.workspacePath,w)))||!D.equals(G(t.sourceRoot,["show",`HEAD:${w}`])))throw new Error("planning-generation-predecessor-uncommitted")}const h=m(a(t.sourceRoot,d));if(h.byteLength>8*1024*1024||F("sha256").update(h).digest("hex")!==s)throw new Error("planning-generation-state-drift");const p=JSON.parse(h.toString("utf8")),v=Vt(p,r,e);if(v.diagnosisReceiptId!==n||v.researchReceiptId!==o||v.intakeRevision!==i)throw new Error("planning-generation-predecessor-mismatch");const u=p.epics[e],g=u.createEpicPlanningPhysical.artifactDigests,_=u.createEpicPlanningResearchPhysical.artifactDigests,j={idea:`${c}/idea.json`,diagnosis:`${c}/diagnosis.md`,enrichment:`${c}/enriched-prompt.md`,research:`${c}/research.md`};for(const[w,D]of Object.entries(j)){const H=w==="research"?_.research:g[w];if(F("sha256").update(m(a(t.sourceRoot,D))).digest("hex")!==H)throw new Error("planning-generation-artifact-drift")}if(F("sha256").update(m(a(t.sourceRoot,l))).digest("hex")!==_.index)throw new Error("planning-generation-index-drift");const b=M(B(t.workspacePath,!0)),N=new RegExp(`^docs/stories/${e}\\.([0-9]{2})\\.story\\.md$`),y=b.paths.filter(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!==f&&w!==l&&!N.test(w)))throw new Error("planning-generation-write-scope-invalid");const A=[f,l,...y];for(const w of[f,...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===f?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(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}
8
+ `).filter(I=>I.startsWith(`${D}:`))??[];return k.length===1?k[0].slice(D.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0},U=m(a(t.workspacePath,f),"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=m(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(m(a(t.sourceRoot,l),"utf8")),$=JSON.parse(m(a(t.workspacePath,l),"utf8")),q=L.epics,C=$.epics,z=q?.[e],V=C?.[e];if(!q||!C||!z||!V||z.id!==e||z.status!=="researched"||!Array.isArray(z.steps_completed)||z.steps_completed.length!==2||!tt(z.steps_completed[0],ut)||!tt(z.steps_completed[1],Rt)||!S(z.output_files,{diagnosis:`${c}/diagnosis.md`,research:`${c}/research.md`})||typeof $.last_scan!="string"||!Number.isFinite(Date.parse($.last_scan))||typeof V.completed_at!="string"||!Number.isFinite(Date.parse(V.completed_at)))throw new Error("planning-generation-index-predecessor-invalid");const X=V.steps_completed?.[2];if(!tt(X,Qt))throw new Error("planning-generation-index-transition-invalid");const Q={...L,last_scan:$.last_scan,epics:{...q,[e]:{...z,status:"generated",steps_completed:[...z.steps_completed,X],completed_at:V.completed_at,output_files:{...z.output_files,epic:f,stories:y}}}};if(!S($,Q))throw new Error("planning-generation-index-transition-invalid");const O=A.map(w=>F("sha256").update(m(a(t.workspacePath,w))).digest("hex")),W=()=>A.every((w,D)=>{try{return P(t.workspacePath,w),F("sha256").update(m(a(t.workspacePath,w))).digest("hex")===O[D]}catch{return!1}});return Y(t,A,t.baseSha,bt(t.sourceRoot),W)}catch{throw new Error("private-execution-planning-generation-admission-unverified")}}function Oe(t,r,e){try{if(!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e))throw new Error("story-id-invalid");const n=".neocortex/state.json";P(r.sourceRoot,n),P(r.workspacePath,n);const o=m(a(r.sourceRoot,n));if(!o.equals(m(a(r.workspacePath,n))))throw new Error("state-drift");const i=JSON.parse(o.toString("utf8")),s=i?.stories?.[e],d=s?.files_to_modify;if(i?.schema_version!==1||s?.id!==e||!Array.isArray(d)||d.length<1||d.length>st||d.some(f=>typeof f!="string"||!rt(f)||f.length>1024||/[\r\n]/.test(f))||new Set(d).size!==d.length)throw new Error("write-set-invalid");const l=d,c=l.filter(f=>{if(!f.startsWith("docs/stories/")||!f.endsWith(".story.md"))return!1;P(r.sourceRoot,f),P(r.workspacePath,f);const h=m(a(r.sourceRoot,f));if(!h.equals(m(a(r.workspacePath,f))))throw new Error("story-drift");const v=/^---\r?\n([\s\S]{1,8192}?)\r?\n---(?:\r?\n|$)/.exec(h.toString("utf8"))?.[1]?.split(/\r?\n/).filter(u=>u.startsWith("id:"))??[];return v.length===1&&v[0].slice(3).trim().replace(/^(["'])(.*)\1$/,"$2")===e});if(c.length!==1)throw new Error("story-target-ambiguous");return`${t}
10
+
11
+ Private story handoff (local only):
12
+ ${JSON.stringify({storyId:e,storyPath:c[0],allowedPaths:[...l].sort()})}
13
+ Work from this isolated checkout's current directory. Use the exact storyPath above for the delivered current step; do not use an unresolved story-file placeholder or infer a filename. Persist the current step's actual result in the declared files; a final chat response alone is not a saved candidate. Modify only allowedPaths and preserve story identity and the write set. Do not operate Git, change unrelated stories, grant root QA/checkpoint authority, or declare the story, epic or pipeline complete. If required inputs are unavailable, report failure without inventing evidence or completion.
14
+ `}catch{throw new Error("private-execution-state-step-handoff-unverified")}}function Te(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 n=JSON.parse(m(a(t.sourceRoot,e),"utf8")),o=JSON.parse(m(a(t.workspacePath,e),"utf8"));if(!n||typeof n!="object"||Array.isArray(n)||!o||typeof o!="object"||Array.isArray(o))throw new Error("state-invalid");const i=n,s=o,d=i.stories,l=s.stories,c=d?.[r],f=l?.[r],h=c?.files_to_modify;if(i.schema_version!==1||s.schema_version!==1||!d||!l||!c||!f||c.id!==r||f.id!==r||f.epic_id!==c.epic_id||!Array.isArray(h)||h.length===0||h.length>st||h.some(R=>typeof R!="string"||!rt(R)||R.length>1024)||new Set(h).size!==h.length||!S(f.files_to_modify,h))throw new Error("write-set-invalid");const{[r]:p,...v}=d,{[r]:u,...g}=l,{stories:_,last_updated:j,...b}=i,{stories:N,last_updated:y,...A}=s;if(!S(g,v)||!S(A,b))throw new Error("state-unrelated-drift");return Y(t,[...h].sort(),t.baseSha)}catch{throw new Error("private-execution-state-step-admission-unverified")}}function je(t,r,e){if(r==="chaos-plan"&&e==="chaos-quarterly-v1")try{const o=new Date,i=`Q${Math.floor(o.getUTCMonth()/3)+1}-${o.getUTCFullYear()}`,s=M(B(t.workspacePath,!0)).paths,d=`tools/chaos/${i}-plan.md`,l=`.neocortex/chaos-history/${i}.md`,c=s.filter(u=>u.startsWith("tools/chaos/experiments/")),f=c.map(u=>/^tools\/chaos\/experiments\/(chaos-mesh|litmus|aws-fis)-(?:PodKill|NetworkChaos|IOChaos|StressChaos|TimeChaos|pod-kill|network-chaos|io-chaos|stress-chaos|time-chaos)-([a-z0-9]+(?:-[a-z0-9]+)*)\.yaml$/.exec(u));if(!s.includes(d)||!s.includes(l)||c.length<5||c.length>10||s.length!==c.length+2||f.some(u=>!u)||new Set(f.map(u=>u[1])).size!==1)throw new Error("chaos-write-set-invalid");for(const u of s)if(P(t.workspacePath,u),x(a(t.workspacePath,u)).size===0)throw new Error("chaos-empty-artifact");const h=m(a(t.workspacePath,l),"utf8");if(!h.includes(i)||!/\bPLANNED\b/.test(h))throw new Error("chaos-history-invalid");const v=G(t.workspacePath,["ls-tree","-z","HEAD","--",l]).length>0?G(t.workspacePath,["show",`HEAD:${l}`]).toString("utf8"):"";if(v&&!h.startsWith(v))throw new Error("chaos-history-not-append-only");return Y(t,s,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 o=".neocortex/tech-debt-registry.json";P(t.workspacePath,o);const i=JSON.parse(m(a(t.workspacePath,o),"utf8"));if(!i||typeof i!="object"||Array.isArray(i))throw new Error("registry-invalid");const s=i;if(s.schema_version!==2||s.version!==void 0&&s.version!==2||!Array.isArray(s.items))throw new Error("registry-invalid")}return Y(t,n,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 Ne(t,r,e,n="all"){const o=Tt(r,e);if(!o)throw new Error("private-execution-architecture-admission-unverified");return`${t}
10
15
 
11
16
  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.
17
+ ${JSON.stringify({allowedPaths:o})}
18
+ ${n==="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
19
  `:""}Write exactly the listed nonempty artifacts inside this isolated clone. Existing compliant listed artifacts may remain unchanged; all listed artifacts must exist after execution. Place any necessary scope notes inside those artifacts. Do not edit README, package files, other documents, state, Git, QA records or configuration outside the listed paths. Do not install dependencies, use network, deploy or continue to another stage. Preserve existing arch:keep blocks byte-for-byte. Do not add new arch:keep markers. For managed memory, preserve all bytes outside its existing managed block. Root independently reviews artifacts and owns continuation, Git and acceptance.
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(`
20
+ `}function De(t,r,e,n,o){const i=Tt(r,e);if(!i||!/^P[1-9][0-9]{0,11}$/.test(n)||!/^[a-f0-9]{64}$/.test(o))throw new Error("private-execution-architecture-admission-unverified");try{P(t.workspacePath,".neocortex/state.json");const s=JSON.parse(m(a(t.workspacePath,".neocortex/state.json"),"utf8"));if(!s||typeof s!="object"||Array.isArray(s))throw new Error("state-invalid");const d=s,c=d.archPlan?.execution,f=d.epics;if(!c||c.currentStageCommand!==r||c.targetEpicId!==n||c.graphRevision!==o||!f||!Object.hasOwn(f,n))throw new Error("state-binding-mismatch");if(r==="update-memory"){if(c.continuationState!=="delegate"||c.reviewDecision?.decision!=="approved")throw new Error("memory-root-review-missing");const h="NEOCORTEX.md";if(!M(B(t.workspacePath,!0)).paths.includes(h))throw new Error("memory-effect-missing");P(t.sourceRoot,h),P(t.workspacePath,h);const p=m(a(t.sourceRoot,h),"utf8"),v=m(a(t.workspacePath,h),"utf8"),u="<!-- NEOCORTEX-MEMORY-START -->",g="<!-- NEOCORTEX-MEMORY-END -->",_=y=>{if(y.split(u).length!==2||y.split(g).length!==2||y.indexOf(u)>=y.indexOf(g))throw new Error("memory-markers-invalid");const A=y.indexOf(u)+u.length,R=y.indexOf(g);return{before:y.slice(0,A),body:y.slice(A,R),after:y.slice(R)}},j=_(p),b=_(v);if(j.before!==b.before||j.after!==b.after||j.body===b.body||Buffer.byteLength(v,"utf8")>32768||v.split(`
16
21
  `).length>240)throw new Error("memory-managed-block-invalid");const N=new Set(j.body.split(`
17
22
  `));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};
23
+ `))N.has(y)||Mt(y)}if(r==="arch-prd"){const h="docs/architecture/prd.md";if(!M(B(t.workspacePath,!0)).paths.includes(h))throw new Error("prd-effect-missing");if(P(t.workspacePath,h),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(B(t.workspacePath,!0)).paths;for(const p of i){if(!h.includes(p)&&G(t.workspacePath,["cat-file","-t",`${t.baseSha}:${p}`]).toString("utf8").trim()!=="blob")throw new Error("architecture-required-effect-missing");if(P(t.workspacePath,p),x(a(t.workspacePath,p)).size===0)throw new Error("architecture-required-effect-empty");if(r==="arch-fitness-functions"){P(t.sourceRoot,p);const v=nt(a(t.sourceRoot,p))?m(a(t.sourceRoot,p),"utf8"):"",u=m(a(t.workspacePath,p),"utf8"),g=At(v),_=At(u);if(!S(_,g))throw new Error("architecture-keep-marker-changed")}}}return Y(t,i,t.baseSha)}catch{throw new Error("private-execution-architecture-admission-unverified")}}function Fe(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 o=Lt(t.sourceRoot,r),i=zt(t.workspacePath,r);if(!S(o,n)||!S(i,n))throw new Error("write-set-invalid");P(t.workspacePath,".neocortex/state.json");const s=JSON.parse(m(a(t.workspacePath,".neocortex/state.json"),"utf8"));if(!s||typeof s!="object"||Array.isArray(s))throw new Error("state-invalid");const d=s,c=d.archPlan?.execution,f=d.epics;if(!c||c.currentStageCommand!=="arch-ux-design"||c.continuationState!=="delegate"||c.targetEpicId!==r||c.graphRevision!==e||!f||!Object.hasOwn(f,r))throw new Error("stage-invalid");const h=M(B(t.workspacePath,!0)).paths;if(h.length!==n.pathCount||h.some(p=>!n.paths.includes(p)))throw new Error("agent-path-unclaimed");for(const p of n.paths){P(t.sourceRoot,p),P(t.workspacePath,p);const v=x(a(t.workspacePath,p));if(!v.isFile()||v.isSymbolicLink()||v.size<1)throw new Error("effect-empty");const u=new TextDecoder("utf-8",{fatal:!0}).decode(m(a(t.workspacePath,p)));if(!u.trim()||u.includes("\0"))throw new Error("effect-invalid")}return Ht(t.workspacePath,n),Y(t,n.paths,t.baseSha)}catch{throw new Error("private-execution-ux-admission-unverified")}}function Be(t,r,e,n,o,i){try{if(!/^P[1-9][0-9]{0,11}$/.test(r)||!/^[a-f0-9]{64}$/.test(e)||n.targetEpicId!==r||n.graphRevision!==e||o.schemaVersion!==1)throw new Error("binding-invalid");const s=Ct(t.sourceRoot);if(!s||!S(s.receipt,n))throw new Error("answers-invalid");const d=_t(t.sourceRoot,s.answers.generateProvider),l=_t(t.workspacePath,s.answers.generateProvider);if(d.outcome!=="ready"||l.outcome!=="ready"||!S(d.writeSet,o)||!S(l.writeSet,o))throw new Error("write-set-invalid");const c=M(B(t.workspacePath,!0)).paths;if(c.some(u=>!o.paths.includes(u)))throw new Error("agent-path-unclaimed");let f=0,h=0;for(const u of o.paths){if(P(t.sourceRoot,u),nt(a(t.sourceRoot,u))||!c.includes(u))throw new Error("effect-missing-or-overwrite");P(t.workspacePath,u);const g=x(a(t.workspacePath,u));if(!g.isFile()||g.size<1)throw new Error("effect-empty");const _=new TextDecoder("utf-8",{fatal:!0}).decode(m(a(t.workspacePath,u))),j=o.interactions.find(N=>N.filePath===u);if(u!==o.providerPath&&!j)throw new Error("private-execution-pact-interaction-missing");const b=Jt(u,_,s.answers.brokerUrl,j,t.workspacePath,s.answers.matchersAggressive);b.consumerBinding==="app-import-candidate"&&f++,b.consumerBinding==="mock-only-scaffold"&&h++}let p=o.paths;if(i){const u=Ut(t.sourceRoot,s.answers.generateProvider),g=_=>F("sha256").update(_).digest("hex");if(i.schemaVersion!==1||i.outcome!=="candidate-unverified"||i.executionVerified!==!1||i.sourceManifestSha256!==g(u.sourceText)||i.sourceLockSha256!==(u.sourceLockText===null?null:g(u.sourceLockText))||i.manifestText!==u.candidateText||!lt(t.sourceRoot,t.workspacePath,t.baseSha,"package.json")||!lt(t.sourceRoot,t.workspacePath,t.baseSha,"package-lock.json"))throw new Error("toolchain-binding-invalid");for(const _ of["package.json","package-lock.json"]){P(t.sourceRoot,_),P(t.workspacePath,_);const j=_==="package.json"?u.sourceText:u.sourceLockText,b=nt(a(t.workspacePath,_))?m(a(t.workspacePath,_),"utf8"):null;if(j!==b)throw new Error("toolchain-clone-raced")}if(mt(a(t.workspacePath,"package.json"),i.manifestText),mt(a(t.workspacePath,"package-lock.json"),i.lockText),Yt(t.workspacePath,s.answers.generateProvider).outcome!=="manifest-aligned")throw new Error("toolchain-candidate-invalid");p=[...o.paths,"package.json","package-lock.json"]}const v=Y(t,p,t.baseSha);return Object.freeze({...v,consumerBindingCandidateCount:f,consumerScaffoldCount:h})}catch{throw new Error("private-execution-pact-admission-unverified")}}function Ce(t,r,e,n=new Date().toISOString()){try{const o=xt(t.sourceRoot,r);if(!S(o,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(B(t.workspacePath,!0)).paths;if(!S(i,e.writeSet))throw new Error("agent-path-unclaimed");const s=new Map;for(const h of e.aggregates){P(t.sourceRoot,h.testFile),P(t.workspacePath,h.testFile);const p=x(a(t.workspacePath,h.testFile));if(!p.isFile()||p.isSymbolicLink()||p.size<1||p.size>Z)throw new Error("test-invalid");const v=m(a(t.workspacePath,h.testFile)),u=new TextDecoder("utf-8",{fatal:!0}).decode(v),g=e.language==="typescript"?(u.match(/\b(?:it|test)\s*\(/g)??[]).length:(u.match(/^def\s+test_[A-Za-z0-9_]+\s*\(/gm)??[]).length;if(!u.trim()||u.includes("\0")||g<h.invariantCount||/\b(?:it|test|describe)\s*\.\s*(?:skip|todo|only)\s*\(/.test(u)||!u.includes(String(e.numRuns)))throw new Error("test-invalid");e.language==="typescript"&&Kt({source:u,testFile:h.testFile,implementationFile:h.implementationFile,invariantCount:h.invariantCount,numRuns:e.numRuns}),s.set(h.testFile,F("sha256").update(v).digest("hex"))}P(t.sourceRoot,e.prdPath),P(t.workspacePath,e.prdPath);const d=m(a(t.workspacePath,e.prdPath)),l=new TextDecoder("utf-8",{fatal:!0}).decode(d),c=Xt(l,e,n);mt(a(t.workspacePath,e.prdPath),c);const f=F("sha256").update(c).digest("hex");return Y(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(m(a(t.workspacePath,e.prdPath))).digest("hex")!==f?!1:[...s].every(([h,p])=>F("sha256").update(m(a(t.workspacePath,h))).digest("hex")===p)}catch{return!1}})}catch{throw new Error("private-execution-property-admission-unverified")}}export{De as admitPrivateArchitectureStageWorkspace,Re as admitPrivateEpicClaimWorkspace,$e as admitPrivateGenerateEpicWorkspace,Ae as admitPrivateIdeaDiagnosisWorkspace,Se as admitPrivateIdeaResearchWorkspace,Be as admitPrivatePactWorkspace,je as admitPrivateProjectStepWorkspace,Ce as admitPrivatePropertyTestWorkspace,Te as admitPrivateStateBoundStepWorkspace,Fe as admitPrivateUxWorkspace,xe as admitPrivateYoloFrozenWorkspace,Ne as appendPrivateArchitectureHandoff,Oe as appendPrivateStateBoundStepHandoff,Tt as privateArchitectureStagePaths,ve as privateYoloSourceFileMatchesSnapshot,be as verifyPrivateYoloRejectedCandidateOrigin,_e as verifyPrivateYoloSnapshotBoundary};
@@ -1,4 +1,4 @@
1
- import { type RootProjectMemoryEffect } from '../../../shared/dist/yoloop/root-memory-effect.js';
1
+ import { type RootProjectMemoryEffect } from './shared-root-memory-types.js';
2
2
  import { type PrivateYoloIsolatedAdmissionV1 } from './isolated-admission.js';
3
3
  import { type PrivateYoloIsolatedWorkspaceV1 } from './isolated-workspace.js';
4
4
  export interface PrivateYoloIsolatedSessionV1 {
@@ -1,5 +1,5 @@
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};
1
+ import{execFileSync as ge,spawnSync as _e}from"node:child_process";import{createCipheriv as Ae,createHash as T,randomBytes as Ee,randomUUID as Oe}from"node:crypto";import{existsSync as Y,lstatSync as U,mkdirSync as qe,readFileSync as R,unlinkSync as Te}from"node:fs";import{homedir as De}from"node:os";import{basename as Ge,dirname as Be,join as v,resolve as _}from"node:path";import{isRootProjectMemoryEffect as Ce,rootProjectMemoryPaths as Me}from"./shared-root-memory-types.js";import{readPrivateRootMemoryScope as Ne,privateRootMemoryEffect as xe}from"./root-memory-scope.js";import{executeRootMemoryWriter as ze,rootMemoryFileState as Re,verifyRootMemoryWriterExecution as He}from"./root-memory-writer.js";import{rootMemoryGitFileState as $e,verifyRootMemoryEffectGitEvidence as Le}from"./root-memory-git-evidence.js";import{parsePrivateRootMemoryRequest as Ye}from"./root-memory-request.js";import{rootMemoryOperationJournalName as Je,readVerifiedPreparedRootMemory as Ve}from"./root-memory-recovery.js";import{assertProjectMemoryPaths as Fe}from"../memory/project-memory-path-scope.js";import{isDeepStrictEqual as J}from"node:util";import{acquireGitLifecyclePhysicalIntegrationLock as We,applyGitLifecycleRuntimeOverlay as Qe,assertGitLifecyclePrivateFile as X,ensureGitLifecyclePrivateChildDirectory as Z,gitLifecycleRuntimeDirectory as ke,mutateGitLifecycleRuntime as Ke,readGitLifecycleRuntimeSync as ue,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{privateYoloRootOnlySetupReady as et,readPrivateYoloFrozenWriteSet as M,readPrivateYoloFrozenWriteSetForTransition as tt}from"./clean-baseline.js";import{admitPrivateYoloFrozenWorkspace as at,verifyPrivateYoloSnapshotBoundary as V,verifyPrivateYoloRejectedCandidateOrigin as ot}from"./isolated-admission.js";import{preparePrivateYoloIsolatedWorkspace as st}from"./isolated-workspace.js";async function bt(t,a,e={}){const o=Ye(a),{directive:r,review:s}=o,i=_(t),n=r.storyId,f=n.split(".")[0],p=d=>T("sha256").update(d).digest("hex");let h="session";const u=()=>{throw new Error(`private-root-memory-acceptance-${h}-unverified`)};try{return await G(i,n,I(i,n),async()=>{const d=ue(i,{required:!0}),m=d.epics[f],l=m?.branch_lease,c=await D(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 u();te(c,i,n,r.graphRevision);const S=await Z(await ke(i),"private-execution"),H=Je(c,o),B=c.rootMemoryEffect===void 0&&Y(v(S,H));B||await A(c,i,n,r.graphRevision);const W=await Xe(i);h="source-evidence",Fe(i,[".neocortex/state.json",`.neocortex/stories/${n}/validation-evidence.md`]);const E=R(v(i,".neocortex/state.json"));if(p(E)!==s.sourceStateSha256)return u();const y=Qe(JSON.parse(E.toString("utf8")),d).stories?.[n];if(!y||y.checkpoint!==void 0||!Array.isArray(y.steps_completed))return u();const ae=[...y.steps_completed],oe=`.neocortex/stories/${n}/validation-evidence.md`,$=U(v(i,oe));if(!$.isFile()||$.isSymbolicLink()||$.nlink!==1||$.size<128||$.size>256*1024||p(R(v(i,oe)))!==s.proposalSha256)return u();const we=v(S,`qa-review-${s.rootQaReceiptId}.json`);h="qa-predecessor",await X(we,S);const se=R(we);if(se.length>16384||p(se)!==s.rootQaReceiptId)return u();const q=JSON.parse(se.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 u();const re=p(JSON.stringify(s.notes)),ie=w=>`memory-review-${p(JSON.stringify(w))}.json`,me=y.status==="qa-gate-passed"&&typeof y.last_step=="string"&&p(y.last_step)==="8721319de90ade506bc9b72a908d8296856b34a11bc640629178bed3fe32e373"&&ae.at(-1)===y.last_step,Se=async w=>{await Ke(i,j=>{if(!J(j.epics[f],m)||!J(j.stories[n],d.stories[n]))return u();j.stories[n]={...j.stories[n],status:"memory-updated",last_step:s.rawStepId,steps_completed:[...ae,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!==re||c.rootMemoryEffect.rootQaReceiptId!==s.rootQaReceiptId)return u();const w=v(S,ie(c.rootMemoryEffect));await X(w,S);const j=R(w),k=JSON.parse(j.toString("utf8"));if(k.proposalSha256!==s.proposalSha256||k.notesSha256!==re||!J(k.rootMemoryEffect,c.rootMemoryEffect))return u();const C=y.status==="memory-updated"&&y.last_step===s.rawStepId&&ae.at(-1)===s.rawStepId;return!C&&!me?u():(C||(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:!C,independentStoryQaAccepted:!1,terminalAccepted:!1,publicSafe:!0})}if(c.snapshotSha!==s.snapshotSha||!me)return u();const P=c.workspace.workspacePath;g(P,["merge-base","--is-ancestor",q.snapshotSha,c.snapshotSha]);const Pe=[`.neocortex/stories/${n}/qa-gate-result.json`,oe,`.neocortex/stories/${n}/tdd-evidence.md`,`docs/stories/${n}.rtm.md`];if(b(P,["diff","--name-only","-z",q.snapshotSha,c.snapshotSha]).toString("utf8").split("\0").filter(Boolean).some(w=>!Pe.includes(w)))return u();const ne=await M(i,n,r.executionBranch,r.graphRevision);if(!fe(i,["diff","--cached","--quiet"]))return u();const je=b(i,["status","--porcelain=v1","-z","--untracked-files=all"]);let x,Q,N,K=!1;if(B){h="prepared-recovery";const w=await Ve({projectRoot:i,parent:S,current:c,request:o,childPaths:ne});x=w.effect,Q=w.receipt,N=w.patch,K=w.sourceAlreadyApplied}else{for(const L of Me())if(ne.includes(L)||!J(Re(i,L),$e(P,c.snapshotSha,L)))return u();h="writer";const w=await Z(S,"memory-backups"),j=ze({snapshotRoot:P,expectedSnapshotSha:c.snapshotSha,notes:s.notes,backupDirectory:w}),k=He(j);h="writer-snapshot",k.files.length&&(g(P,["add","-A","--",...k.files.map(L=>L.path)]),g(P,["-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 C=g(P,["rev-parse","HEAD"]);x={schemaVersion:"RootProjectMemoryEffect/1",producer:"root-project-memory",storyId:n,epicId:f,executionBranch:r.executionBranch,sourceHeadSha:c.workspace.baseSha,sourceSnapshotSha:c.snapshotSha,memorySnapshotSha:C,graphRevision:r.graphRevision,childClaimRevision:p([...ne].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",Le(P,x,{storyId:n,graphRevision:r.graphRevision,childClaimRevision:x.childClaimRevision,setupSessionId:c.setupSessionId,sourceHeadSha:c.workspace.baseSha,executionBranch:r.executionBranch}),N=b(P,["diff","--binary","--full-index",c.snapshotSha,C]),Q={schemaVersion:1,kind:"private-project-memory-root-review",storyId:n,graphRevision:r.graphRevision,sourceHeadSha:c.workspace.baseSha,snapshotSha:C,proposalSha256:s.proposalSha256,notesSha256:re,sourceStateSha256:s.sourceStateSha256,checks:s.checks,reviewedAt:s.reviewedAt,rootMemoryEffect:x,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 ce=JSON.stringify(Q)+`
3
+ `,ye=x.memorySnapshotSha;if(h="source-admission",!b(i,["status","--porcelain=v1","-z","--untracked-files=all"]).equals(je)||g(i,["rev-parse","HEAD"])!==c.workspace.baseSha||g(i,["symbolic-ref","--short","HEAD"])!==r.executionBranch)return u();if(!K){for(const w of x.files)if(!J(Re(i,w.path),w.before))return u()}const ve=w=>Ze(Be(i),Ge(i),W,["apply",...w?["--check"]:[],"--binary","-"],N);if(N.length&&!K&&(await ve(!0),await ve(!1)),await e.fault?.("after-source-admission"),!R(v(i,".neocortex/state.json")).equals(E))return u();const pe=v(S,ie(x));if(Y(pe)){if(await X(pe,S),R(pe,"utf8")!==ce)return u()}else await z(S,ie(x),ce);const he=Object.freeze({...c,snapshotSha:ye,sequence:c.sequence+(x.files.length?1:0),lastPatchSha256:x.files.length?p(N):c.lastPatchSha256,rootMemoryEffect:x});return h="session-pin",await e.fault?.("before-session-pin"),await F(i,he),await A(he,i,n,r.graphRevision),h="phase-transition",await Se(he),{schemaVersion:1,outcome:"project-memory-root-accepted",storyId:n,graphRevision:r.graphRevision,receiptId:p(ce),snapshotSha:ye,reused:B,sourceStateUnchanged:!0,preparedRecovered:B,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 u()}}function g(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 b(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 fe(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=_e("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){const e=await ke(t),o=await Z(e,"private-execution"),r=`session-${T("sha256").update(a).digest("hex")}.json`;return{parent:o,name:r,path:v(o,r)}}function I(t,a){const e=a.split(".")[0],r=ue(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 be(t,a){const e=ue(t,{required:!0}).stories[a];return et(e)}function rt(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&&!Ce(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 D(t,a){const e=await de(t,a);if(Y(e.path))return await X(e.path,e.parent),rt(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 G(t,a,e,o){const r=await We(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){te(t,a,e,o);const r=await M(a,e,t.workspace.executionBranch,o),s=await ee(t,r);return V(t.workspace,r,t.snapshotSha,s),s}async function ee(t,a){if(t.rootMemoryEffect===void 0)return;const e=await Ne({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(xe(e))!==JSON.stringify(t.rootMemoryEffect))throw new Error("private-root-memory-scope-unverified");return e}function te(t,a,e,o){if(t.storyId!==e||t.graphRevision!==o||t.workspace.sourceRoot!==a||t.setupSessionId!==I(a,e)||t.sequence===0&&t.snapshotSha!==t.workspace.baseSha||t.sequence===0&&t.graphHistory.length>1&&!be(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=I(o,a);return await G(o,a,r,async()=>{const s=await D(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 Ie(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!==I(a,e)||t.sequence===0&&(t.graphHistory.length!==1||t.lastPatchSha256!==null||!be(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 tt(a,e,t.workspace.executionBranch,t.initialGraphRevision,o);V(t.workspace,r,t.snapshotSha,await ee(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 Pt(t,a,e){const o=_(t);try{const r=I(o,a);return await G(o,a,r,async()=>{const s=await D(o,a);if(!s)throw new Error("session-missing");return Ie(s,o,a,e)})}catch{throw new Error("private-execution-isolated-session-unverified")}}async function jt(t,a,e,o){const r=_(t);try{const s=I(r,a);return await G(r,a,s,async()=>{const i=await D(r,a);if(i)return Ie(i,r,a,e);const n=o??v(De(),".local","share","neocortex","private-yolo-workspaces");o===void 0&&qe(n,{recursive:!0,mode:448});const f=st(r,n),p=await M(r,a,f.executionBranch,e);V(f,p,f.baseSha);const h=Object.freeze({schemaVersion:1,kind:"private-yolo-isolated-session",storyId:a,initialGraphRevision:e,graphRevision:e,graphHistory:[e],setupSessionId:s,workspace:f,snapshotSha:f.baseSha,sequence:0,lastPatchSha256:null});return await F(r,h),h})}catch{throw new Error("private-execution-isolated-session-unverified")}}async function _t(t,a,e){const o=_(t);try{const r=await D(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 At(t,a,e){const o=_(t);try{const r=I(o,a);return await G(o,a,r,async()=>{const s=await D(o,a);if(!s)throw new Error("session-missing");te(s,o,a,e);const i=await M(o,a,s.workspace.executionBranch,e),n=await ee(s,i),f=await at(s.workspace,a,e,s.snapshotSha,!1,n);g(s.workspace.workspacePath,["add","-A","--",...f.changedPaths]),g(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=g(s.workspace.workspacePath,["rev-parse","HEAD"]);V(s.workspace,i,p,n);const h=Object.freeze({...s,snapshotSha:p,sequence:s.sequence+1,lastPatchSha256:f.patchSha256});return await F(o,h),{session:h,admission:f}})}catch{throw new Error("private-execution-isolated-session-unverified")}}async function Ot(t,a,e){const o=_(t);try{const r=I(o,a);return await G(o,a,r,async()=>{const s=await D(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),f=s.workspace.workspacePath,p=b(f,["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&&xe(i).files.some(c=>c.path===l)))||h.some(l=>!p.includes(l)))throw new Error("bundle-incomplete");if(!fe(o,["diff","--cached","--quiet"])||b(o,["ls-files","-u","-z"]).byteLength!==0)throw new Error("index-not-clean");const u=b(f,["diff","--binary","--full-index",s.workspace.baseSha,s.snapshotSha]);if(u.byteLength===0)throw new Error("bundle-empty");g(o,["add","-A","--",...p]);const d=b(o,["diff","--cached","--binary","--full-index"]),m=b(o,["diff","--cached","--name-only","-z"]).toString("utf8").split("\0").filter(Boolean).sort();if(!d.equals(u)||m.length!==p.length||m.some((l,c)=>l!==p[c])||!fe(o,["diff","--quiet"])||g(o,["rev-parse","HEAD"])!==s.workspace.baseSha||g(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:T("sha256").update(d).digest("hex"),changedPaths:Object.freeze(p)})})}catch{throw new Error("private-execution-root-stage-unverified")}}function it(t){const a=t.workspace.workspacePath,e=b(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 f=n.slice(0,2),p=n.slice(3);if(![" M"," D","??"].includes(f)||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=v(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 u=v(a,p);if(f===" D"){if(Y(u))throw new Error("rejected-candidate-raced");return{path:p,code:f,mode:null,sha256:null,content:null}}const d=U(u);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(u);if(r+=m.byteLength,r>16*1024*1024)throw new Error("rejected-candidate-too-large");return{path:p,code:f,mode:d.mode&511,sha256:T("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:T("sha256").update(e).digest("hex"),files:s.map(({content:n,...f})=>f)};return{files:s,inspection:{schemaVersion:i.schemaVersion,storyId:i.storyId,graphRevision:i.graphRevision,snapshotSha:i.snapshotSha,sourceHead:i.sourceHead,sequence:i.sequence,candidateDigest:T("sha256").update(JSON.stringify(i)).digest("hex"),changedPaths:s.map(n=>n.path),publicSafe:!0}}}async function le(t,a,e){const o=await D(t,a);if(!o)throw new Error("session-missing");te(o,t,a,e);const r=await M(t,a,o.workspace.executionBranch,e);return ot(o.workspace,r,o.snapshotSha,await ee(o,r)),{record:o,...it(o)}}async function qt(t,a,e,o){if(o!==!0)throw new Error("private-execution-rejected-candidate-executor-not-stopped");const r=_(t);try{return await G(r,a,I(r,a),async()=>(await le(r,a,e)).inspection)}catch{throw new Error("private-execution-rejected-candidate-unverified")}}async function Tt(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 G(r,a,I(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),f=`rejected-${Oe()}`,p=await Z(i.parent,f),h=Ee(32),u=Ee(12),d=Buffer.from(JSON.stringify({schemaVersion:"PrivateYoloRejectedCandidateArchive/1",inspection:s.inspection,files:s.files.map(({content:E,...O})=>({...O,contentBase64:E?.toString("base64")??null}))})),m=Ae("aes-256-gcm",h,u);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([u,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,B=s.files.filter(E=>E.code!=="??").map(E=>E.path);B.length&&g(H,["restore","--source",s.record.snapshotSha,"--worktree","--",...B]);for(const E of s.files.filter(O=>O.code==="??")){const O=v(H,E.path),y=U(O);if(!y.isFile()||y.isSymbolicLink()||y.nlink!==1||T("sha256").update(R(O)).digest("hex")!==E.sha256)throw new Error("candidate-raced");Te(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:f,archiveSha256:T("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{bt as acceptPrivateYoloProjectMemoryRootReview,At as admitPrivateYoloIsolatedSessionStep,It as beginPrivateYoloIsolatedSession,Tt as discardPrivateYoloRejectedCandidate,jt as ensurePrivateYoloIsolatedSession,qt as inspectPrivateYoloRejectedCandidate,Pt as reconcilePrivateYoloIsolatedSession,_t as resumePrivateYoloIsolatedSession,Ot as stagePrivateYoloIsolatedSessionBundle};
@@ -1,4 +1,4 @@
1
- import { type RootMemoryFileState, type RootProjectMemoryEffect } from '../../../shared/dist/yoloop/root-memory-effect.js';
1
+ import { type RootMemoryFileState, type RootProjectMemoryEffect } from './shared-root-memory-types.js';
2
2
  /** Hash Git blobs without following links, using the same link-byte hash as the writer. */
3
3
  export declare function rootMemoryGitFileState(root: string, sha: string, path: string): RootMemoryFileState;
4
4
  export interface RootMemoryGitBinding {
@@ -1,3 +1,3 @@
1
- import{execFileSync as S}from"node:child_process";import{createHash as R}from"node:crypto";import{isDeepStrictEqual as f}from"node:util";import{canonicalRootMemoryEffectJson as x,isRootProjectMemoryEffect as p,rootProjectMemoryPaths as d}from"../../../shared/dist/yoloop/root-memory-effect.js";import{getProjectMemoryTarget as E,listProjectMemoryTargets as P}from"../../../shared/dist/project-memory-targets.js";import{shouldUseManagedWrapper as g}from"../memory/project-memory-writer.js";const u=o=>R("sha256").update(o).digest("hex"),i=()=>{throw new Error("private-root-memory-git-evidence-unverified")};function l(o,t){return S("git",[...t],{cwd:o,stdio:["ignore","pipe","ignore"],env:{...Object.fromEntries(Object.entries(process.env).filter(([e])=>!e.startsWith("GIT_"))),GIT_NO_REPLACE_OBJECTS:"1"},timeout:3e4,maxBuffer:2*1024*1024})}function m(o,t,e){if(t!==":"&&!/^[a-f0-9]{40,64}$/.test(t)||!d().includes(e))return i();const h=l(o,t===":"?["ls-files","--stage","-z","--",e]:["ls-tree","-z",t,"--",e]).toString("utf8");if(!h)return{kind:"absent",sha256:null};const s=(t===":"?/^(100644|120000) ([a-f0-9]{40,64}) 0\t([^\0]+)\0$/:/^(100644|120000) blob ([a-f0-9]{40,64})\t([^\0]+)\0$/).exec(h);if(!s||s[3]!==e)return i();const c=l(o,["cat-file","blob",s[2]]);return c.byteLength>512*1024?i():s[1]==="120000"?{kind:"symlink",sha256:u(c),linkTarget:c.toString("utf8")}:{kind:"regular",sha256:u(c)}}function C(o,t,e){try{if(!p(t)||!e||["storyId","graphRevision","childClaimRevision","setupSessionId","sourceHeadSha","executionBranch"].some(s=>t[s]!==e[s]))return i();l(o,["merge-base","--is-ancestor",t.sourceHeadSha,t.sourceSnapshotSha]),l(o,["merge-base","--is-ancestor",t.sourceSnapshotSha,t.memorySnapshotSha]);const h=l(o,["diff","--name-only","--no-renames","--no-ext-diff","--no-textconv","-z",t.sourceSnapshotSha,t.memorySnapshotSha]).toString("utf8").split("\0").filter(Boolean).sort();if(!f(h,t.files.map(s=>s.path).sort()))return i();for(const s of t.files){const c=m(o,t.sourceSnapshotSha,s.path),r=m(o,t.memorySnapshotSha,s.path);if(!f(c,s.before)||!f(r,s.after)||f(c,r))return i()}return y(o,t.memorySnapshotSha,t),t}catch{return i()}}function y(o,t,e){const h=m(o,t,"NEOCORTEX.md");if(h.kind!=="regular"||h.sha256!==e.canonicalSha256)return i();const s=new Map;for(const r of[E("canonical"),...P()])for(const a of[r.primaryFile,...r.targetId==="canonical"?[]:r.secondaryFiles.filter(n=>n.scope==="project").map(n=>n.path)])s.has(a)||s.set(a,r.targetId==="canonical"?"canonical":g(r,a)?"managed-wrapper":"semantic-symlink");const c=[...s].sort(([r],[a])=>r<a?-1:r>a?1:0).map(([r,a])=>{const n=m(o,t,r);return n.kind==="absent"||a!=="semantic-symlink"&&n.kind!=="regular"||a==="semantic-symlink"&&(n.kind!=="symlink"||n.linkTarget!=="../".repeat(r.split("/").length-1)+"NEOCORTEX.md")?i():`${r}:${a}:${n.kind==="symlink"?h.sha256:n.sha256}`});if(e.projectionFileCount!==c.length||e.projectionSha256!==u(Buffer.from(c.join(`
2
- `))))return i()}function k(o){return u(Buffer.from(x(o)))}function I(o,t,e){try{if(!p(t)||!e||t.storyId!==e.storyId||t.executionBranch!==e.executionBranch||t.sourceHeadSha!==e.baseSha||!/^[a-f0-9]{40,64}$/.test(e.baseSha)||e.headRef!==":"&&!/^[a-f0-9]{40,64}$/.test(e.headRef)||!Array.isArray(e.childPaths)||e.childPaths.length<1||e.childPaths.length>1024||e.childPaths.some(r=>typeof r!="string"||!r||r.startsWith("/")||/[\\\x00-\x1f\x7f]/.test(r)||r.split("/").includes("..")||r.split("/").includes(".git"))||new Set(e.childPaths).size!==e.childPaths.length||t.childClaimRevision!==u(Buffer.from([...e.childPaths].sort().join("\0"))))return i();const h=r=>e.childPaths.some(a=>a===r||a.endsWith("/")&&r.startsWith(a)),s=l(o,["diff",...e.headRef===":"?["--cached"]:[],"--name-only","--no-renames","--no-ext-diff","--no-textconv","-z",e.baseSha,...e.headRef===":"?[]:[e.headRef]]).toString("utf8").split("\0").filter(Boolean),c=t.files.map(r=>r.path).sort();if(!f(s.filter(r=>!h(r)).sort(),c)||t.files.some(r=>h(r.path)))return i();for(const r of t.files){const a=m(o,e.baseSha,r.path),n=m(o,e.headRef,r.path);if(!f(a,r.before)||!f(n,r.after)||f(a,n))return i()}if(y(o,e.headRef,t),e.headRef!==":"){const a=l(o,["show","--no-patch","--format=%B",e.headRef]).toString("utf8").split(`
3
- `).filter(n=>n.startsWith("Neocortex-Root-Memory-Effect:"));if(a.length!==1||a[0]!==`Neocortex-Root-Memory-Effect: ${k(t)}`)return i()}return t}catch{return i()}}export{k as rootMemoryEffectDigest,m as rootMemoryGitFileState,C as verifyRootMemoryEffectGitEvidence,I as verifyRootMemoryPhysicalWriteSet};
1
+ import{execFileSync as S}from"node:child_process";import{createHash as R}from"node:crypto";import{isDeepStrictEqual as f}from"node:util";import{canonicalRootMemoryEffectJson as x,getProjectMemoryTarget as d,listProjectMemoryTargets as E,isRootProjectMemoryEffect as p,rootProjectMemoryPaths as P}from"./shared-root-memory-types.js";import{shouldUseManagedWrapper as g}from"../memory/project-memory-writer.js";const u=o=>R("sha256").update(o).digest("hex"),i=()=>{throw new Error("private-root-memory-git-evidence-unverified")};function l(o,t){return S("git",[...t],{cwd:o,stdio:["ignore","pipe","ignore"],env:{...Object.fromEntries(Object.entries(process.env).filter(([e])=>!e.startsWith("GIT_"))),GIT_NO_REPLACE_OBJECTS:"1"},timeout:3e4,maxBuffer:2*1024*1024})}function m(o,t,e){if(t!==":"&&!/^[a-f0-9]{40,64}$/.test(t)||!P().includes(e))return i();const h=l(o,t===":"?["ls-files","--stage","-z","--",e]:["ls-tree","-z",t,"--",e]).toString("utf8");if(!h)return{kind:"absent",sha256:null};const s=(t===":"?/^(100644|120000) ([a-f0-9]{40,64}) 0\t([^\0]+)\0$/:/^(100644|120000) blob ([a-f0-9]{40,64})\t([^\0]+)\0$/).exec(h);if(!s||s[3]!==e)return i();const c=l(o,["cat-file","blob",s[2]]);return c.byteLength>512*1024?i():s[1]==="120000"?{kind:"symlink",sha256:u(c),linkTarget:c.toString("utf8")}:{kind:"regular",sha256:u(c)}}function $(o,t,e){try{if(!p(t)||!e||["storyId","graphRevision","childClaimRevision","setupSessionId","sourceHeadSha","executionBranch"].some(s=>t[s]!==e[s]))return i();l(o,["merge-base","--is-ancestor",t.sourceHeadSha,t.sourceSnapshotSha]),l(o,["merge-base","--is-ancestor",t.sourceSnapshotSha,t.memorySnapshotSha]);const h=l(o,["diff","--name-only","--no-renames","--no-ext-diff","--no-textconv","-z",t.sourceSnapshotSha,t.memorySnapshotSha]).toString("utf8").split("\0").filter(Boolean).sort();if(!f(h,t.files.map(s=>s.path).sort()))return i();for(const s of t.files){const c=m(o,t.sourceSnapshotSha,s.path),r=m(o,t.memorySnapshotSha,s.path);if(!f(c,s.before)||!f(r,s.after)||f(c,r))return i()}return y(o,t.memorySnapshotSha,t),t}catch{return i()}}function y(o,t,e){const h=m(o,t,"NEOCORTEX.md");if(h.kind!=="regular"||h.sha256!==e.canonicalSha256)return i();const s=new Map;for(const r of[d("canonical"),...E()])for(const a of[r.primaryFile,...r.targetId==="canonical"?[]:r.secondaryFiles.filter(n=>n.scope==="project").map(n=>n.path)])s.has(a)||s.set(a,r.targetId==="canonical"?"canonical":g(r,a)?"managed-wrapper":"semantic-symlink");const c=[...s].sort(([r],[a])=>r<a?-1:r>a?1:0).map(([r,a])=>{const n=m(o,t,r);return n.kind==="absent"||a!=="semantic-symlink"&&n.kind!=="regular"||a==="semantic-symlink"&&(n.kind!=="symlink"||n.linkTarget!=="../".repeat(r.split("/").length-1)+"NEOCORTEX.md")?i():`${r}:${a}:${n.kind==="symlink"?h.sha256:n.sha256}`});if(e.projectionFileCount!==c.length||e.projectionSha256!==u(Buffer.from(c.join(`
2
+ `))))return i()}function k(o){return u(Buffer.from(x(o)))}function C(o,t,e){try{if(!p(t)||!e||t.storyId!==e.storyId||t.executionBranch!==e.executionBranch||t.sourceHeadSha!==e.baseSha||!/^[a-f0-9]{40,64}$/.test(e.baseSha)||e.headRef!==":"&&!/^[a-f0-9]{40,64}$/.test(e.headRef)||!Array.isArray(e.childPaths)||e.childPaths.length<1||e.childPaths.length>1024||e.childPaths.some(r=>typeof r!="string"||!r||r.startsWith("/")||/[\\\x00-\x1f\x7f]/.test(r)||r.split("/").includes("..")||r.split("/").includes(".git"))||new Set(e.childPaths).size!==e.childPaths.length||t.childClaimRevision!==u(Buffer.from([...e.childPaths].sort().join("\0"))))return i();const h=r=>e.childPaths.some(a=>a===r||a.endsWith("/")&&r.startsWith(a)),s=l(o,["diff",...e.headRef===":"?["--cached"]:[],"--name-only","--no-renames","--no-ext-diff","--no-textconv","-z",e.baseSha,...e.headRef===":"?[]:[e.headRef]]).toString("utf8").split("\0").filter(Boolean),c=t.files.map(r=>r.path).sort();if(!f(s.filter(r=>!h(r)).sort(),c)||t.files.some(r=>h(r.path)))return i();for(const r of t.files){const a=m(o,e.baseSha,r.path),n=m(o,e.headRef,r.path);if(!f(a,r.before)||!f(n,r.after)||f(a,n))return i()}if(y(o,e.headRef,t),e.headRef!==":"){const a=l(o,["show","--no-patch","--format=%B",e.headRef]).toString("utf8").split(`
3
+ `).filter(n=>n.startsWith("Neocortex-Root-Memory-Effect:"));if(a.length!==1||a[0]!==`Neocortex-Root-Memory-Effect: ${k(t)}`)return i()}return t}catch{return i()}}export{k as rootMemoryEffectDigest,m as rootMemoryGitFileState,$ as verifyRootMemoryEffectGitEvidence,C as verifyRootMemoryPhysicalWriteSet};
@@ -9,7 +9,7 @@ export declare function readVerifiedPreparedRootMemory(input: {
9
9
  readonly childPaths: readonly string[];
10
10
  }): Promise<{
11
11
  receipt: any;
12
- effect: import("../../../shared/dist/yoloop/root-memory-effect.js").RootProjectMemoryEffect;
12
+ effect: import("./shared-root-memory-types.js").RootProjectMemoryEffect;
13
13
  patch: Buffer<ArrayBufferLike>;
14
14
  sourceAlreadyApplied: boolean;
15
15
  journalPath: string;
@@ -1 +1 @@
1
- import{createHash as x}from"node:crypto";import{execFileSync as M}from"node:child_process";import{existsSync as O,lstatSync as m,readFileSync as P,realpathSync as A}from"node:fs";import{join as l}from"node:path";import{isDeepStrictEqual as d}from"node:util";import{isRootProjectMemoryEffect as D,rootProjectMemoryPaths as H}from"../../../shared/dist/yoloop/root-memory-effect.js";import{assertGitLifecyclePrivateFile as B}from"../git/git-lifecycle-store.js";import{privateYoloSourceFileMatchesSnapshot as F}from"./isolated-admission.js";import{rootMemoryGitFileState as I,verifyRootMemoryEffectGitEvidence as J}from"./root-memory-git-evidence.js";import{rootMemoryFileState as N}from"./root-memory-writer.js";const S=s=>x("sha256").update(s).digest("hex"),n=()=>{throw new Error("private-root-memory-prepared-recovery-unverified")},b=(s,e)=>Object.keys(s).sort().join("|")===[...e].sort().join("|");function c(s,e){return M("git",[...e],{cwd:s,stdio:["ignore","pipe","ignore"],env:{...Object.fromEntries(Object.entries(process.env).filter(([t])=>!t.startsWith("GIT_"))),GIT_NO_REPLACE_OBJECTS:"1"},timeout:3e4,maxBuffer:16*1024*1024})}function G(s,e){return`memory-operation-${S(JSON.stringify([s.storyId,s.setupSessionId,s.graphRevision,e.review.snapshotSha,e.review.proposalSha256,e.review.sourceStateSha256,e.review.rootQaReceiptId,S(JSON.stringify(e.review.notes))]))}.json`}async function U(s){try{const{projectRoot:e,current:t,request:g,childPaths:f}=s,{review:h,directive:u}=g,y=l(s.parent,G(t,g));await B(y,s.parent);const w=P(y);if(w.length>256*1024)return n();const p=JSON.parse(w.toString("utf8"));if(!p||!b(p,["schemaVersion","kind","previousSession","receipt","patchSha256"])||p.schemaVersion!==1||p.kind!=="prepared-root-memory-effect"||!d(p.previousSession,t)||t.rootMemoryEffect!==void 0)return n();const r=p.receipt,a=r?.rootMemoryEffect;if(!r||!b(r,["schemaVersion","kind","storyId","graphRevision","sourceHeadSha","snapshotSha","proposalSha256","notesSha256","sourceStateSha256","checks","reviewedAt","rootMemoryEffect","independentStoryQaAccepted","terminalAccepted"])||!D(a)||r.schemaVersion!==1||r.kind!=="private-project-memory-root-review"||r.storyId!==t.storyId||r.graphRevision!==t.graphRevision||r.sourceHeadSha!==t.workspace.baseSha||r.snapshotSha!==a.memorySnapshotSha||r.proposalSha256!==h.proposalSha256||r.sourceStateSha256!==h.sourceStateSha256||r.notesSha256!==S(JSON.stringify(h.notes))||r.notesSha256!==a.proposalSha256||!d(r.checks,h.checks)||r.reviewedAt!==a.recordedAt||a.sourceSnapshotSha!==t.snapshotSha||a.rootQaReceiptId!==h.rootQaReceiptId||r.independentStoryQaAccepted!==!1||r.terminalAccepted!==!1)return n();const o=t.workspace.workspacePath;if(A(e)!==e||A(o)!==o||!m(o).isDirectory()||m(o).uid!==process.getuid?.()||(m(o).mode&63)!==0||!m(l(o,".git")).isDirectory()||m(l(o,".git")).isSymbolicLink()||O(l(o,".git/objects/info/alternates"))||c(o,["rev-parse","--show-toplevel"]).toString().trim()!==o||c(e,["rev-parse","--show-toplevel"]).toString().trim()!==e||c(e,["rev-parse","HEAD"]).toString().trim()!==t.workspace.baseSha||c(e,["symbolic-ref","--short","HEAD"]).toString().trim()!==u.executionBranch||c(o,["rev-parse","HEAD"]).toString().trim()!==a.memorySnapshotSha||c(o,["symbolic-ref","--short","HEAD"]).toString().trim()!==u.executionBranch||c(o,["status","--porcelain=v1","-z","--untracked-files=all","--ignored=matching"]).length!==0||c(e,["diff","--cached","--name-only","-z"]).length!==0||(J(o,a,{storyId:t.storyId,graphRevision:t.graphRevision,childClaimRevision:S([...f].sort().join("\0")),setupSessionId:t.setupSessionId,sourceHeadSha:t.workspace.baseSha,executionBranch:u.executionBranch}),f.some(i=>!F(e,o,t.snapshotSha,i))))return n();const k=a.files.map(i=>i.path);if(c(e,["status","--porcelain=v1","-z","--untracked-files=all"]).toString("utf8").split("\0").filter(Boolean).some(i=>![" M"," D","??"," T"].includes(i.slice(0,2))||!f.includes(i.slice(3))&&!k.includes(i.slice(3))||i.slice(0,2)===" T"&&!k.includes(i.slice(3))))return n();let E=!0,v=!0;for(const i of H()){if(f.includes(i))return n();const R=N(e,i);E&&=d(R,I(o,t.snapshotSha,i)),v&&=d(R,I(o,a.memorySnapshotSha,i))}if(!E&&!v)return n();const j=c(o,["diff","--binary","--full-index",t.snapshotSha,a.memorySnapshotSha]);return S(j)!==p.patchSha256?n():{receipt:r,effect:a,patch:j,sourceAlreadyApplied:v,journalPath:y}}catch{return n()}}export{U as readVerifiedPreparedRootMemory,G as rootMemoryOperationJournalName};
1
+ import{createHash as x}from"node:crypto";import{execFileSync as M}from"node:child_process";import{existsSync as O,lstatSync as m,readFileSync as P,realpathSync as A}from"node:fs";import{join as l}from"node:path";import{isDeepStrictEqual as d}from"node:util";import{isRootProjectMemoryEffect as D,rootProjectMemoryPaths as H}from"./shared-root-memory-types.js";import{assertGitLifecyclePrivateFile as B}from"../git/git-lifecycle-store.js";import{privateYoloSourceFileMatchesSnapshot as F}from"./isolated-admission.js";import{rootMemoryGitFileState as I,verifyRootMemoryEffectGitEvidence as J}from"./root-memory-git-evidence.js";import{rootMemoryFileState as N}from"./root-memory-writer.js";const S=s=>x("sha256").update(s).digest("hex"),n=()=>{throw new Error("private-root-memory-prepared-recovery-unverified")},b=(s,e)=>Object.keys(s).sort().join("|")===[...e].sort().join("|");function c(s,e){return M("git",[...e],{cwd:s,stdio:["ignore","pipe","ignore"],env:{...Object.fromEntries(Object.entries(process.env).filter(([t])=>!t.startsWith("GIT_"))),GIT_NO_REPLACE_OBJECTS:"1"},timeout:3e4,maxBuffer:16*1024*1024})}function G(s,e){return`memory-operation-${S(JSON.stringify([s.storyId,s.setupSessionId,s.graphRevision,e.review.snapshotSha,e.review.proposalSha256,e.review.sourceStateSha256,e.review.rootQaReceiptId,S(JSON.stringify(e.review.notes))]))}.json`}async function U(s){try{const{projectRoot:e,current:t,request:g,childPaths:f}=s,{review:h,directive:u}=g,y=l(s.parent,G(t,g));await B(y,s.parent);const w=P(y);if(w.length>256*1024)return n();const p=JSON.parse(w.toString("utf8"));if(!p||!b(p,["schemaVersion","kind","previousSession","receipt","patchSha256"])||p.schemaVersion!==1||p.kind!=="prepared-root-memory-effect"||!d(p.previousSession,t)||t.rootMemoryEffect!==void 0)return n();const r=p.receipt,a=r?.rootMemoryEffect;if(!r||!b(r,["schemaVersion","kind","storyId","graphRevision","sourceHeadSha","snapshotSha","proposalSha256","notesSha256","sourceStateSha256","checks","reviewedAt","rootMemoryEffect","independentStoryQaAccepted","terminalAccepted"])||!D(a)||r.schemaVersion!==1||r.kind!=="private-project-memory-root-review"||r.storyId!==t.storyId||r.graphRevision!==t.graphRevision||r.sourceHeadSha!==t.workspace.baseSha||r.snapshotSha!==a.memorySnapshotSha||r.proposalSha256!==h.proposalSha256||r.sourceStateSha256!==h.sourceStateSha256||r.notesSha256!==S(JSON.stringify(h.notes))||r.notesSha256!==a.proposalSha256||!d(r.checks,h.checks)||r.reviewedAt!==a.recordedAt||a.sourceSnapshotSha!==t.snapshotSha||a.rootQaReceiptId!==h.rootQaReceiptId||r.independentStoryQaAccepted!==!1||r.terminalAccepted!==!1)return n();const o=t.workspace.workspacePath;if(A(e)!==e||A(o)!==o||!m(o).isDirectory()||m(o).uid!==process.getuid?.()||(m(o).mode&63)!==0||!m(l(o,".git")).isDirectory()||m(l(o,".git")).isSymbolicLink()||O(l(o,".git/objects/info/alternates"))||c(o,["rev-parse","--show-toplevel"]).toString().trim()!==o||c(e,["rev-parse","--show-toplevel"]).toString().trim()!==e||c(e,["rev-parse","HEAD"]).toString().trim()!==t.workspace.baseSha||c(e,["symbolic-ref","--short","HEAD"]).toString().trim()!==u.executionBranch||c(o,["rev-parse","HEAD"]).toString().trim()!==a.memorySnapshotSha||c(o,["symbolic-ref","--short","HEAD"]).toString().trim()!==u.executionBranch||c(o,["status","--porcelain=v1","-z","--untracked-files=all","--ignored=matching"]).length!==0||c(e,["diff","--cached","--name-only","-z"]).length!==0||(J(o,a,{storyId:t.storyId,graphRevision:t.graphRevision,childClaimRevision:S([...f].sort().join("\0")),setupSessionId:t.setupSessionId,sourceHeadSha:t.workspace.baseSha,executionBranch:u.executionBranch}),f.some(i=>!F(e,o,t.snapshotSha,i))))return n();const k=a.files.map(i=>i.path);if(c(e,["status","--porcelain=v1","-z","--untracked-files=all"]).toString("utf8").split("\0").filter(Boolean).some(i=>![" M"," D","??"," T"].includes(i.slice(0,2))||!f.includes(i.slice(3))&&!k.includes(i.slice(3))||i.slice(0,2)===" T"&&!k.includes(i.slice(3))))return n();let E=!0,v=!0;for(const i of H()){if(f.includes(i))return n();const R=N(e,i);E&&=d(R,I(o,t.snapshotSha,i)),v&&=d(R,I(o,a.memorySnapshotSha,i))}if(!E&&!v)return n();const j=c(o,["diff","--binary","--full-index",t.snapshotSha,a.memorySnapshotSha]);return S(j)!==p.patchSha256?n():{receipt:r,effect:a,patch:j,sourceAlreadyApplied:v,journalPath:y}}catch{return n()}}export{U as readVerifiedPreparedRootMemory,G as rootMemoryOperationJournalName};
@@ -1,4 +1,4 @@
1
- import { type RootProjectMemoryEffect } from '../../../shared/dist/yoloop/root-memory-effect.js';
1
+ import { type RootProjectMemoryEffect } from './shared-root-memory-types.js';
2
2
  export interface PrivateRootMemoryScope {
3
3
  readonly __rootMemoryScope: never;
4
4
  }
@@ -1 +1 @@
1
- import{createHash as S}from"node:crypto";import{execFileSync as A}from"node:child_process";import{existsSync as B,readFileSync as l}from"node:fs";import{join as g,resolve as w}from"node:path";import{isDeepStrictEqual as u}from"node:util";import{isRootProjectMemoryEffect as _}from"../../../shared/dist/yoloop/root-memory-effect.js";import{assertGitLifecyclePrivateFile as R,ensureGitLifecyclePrivateChildDirectory as k,gitLifecycleRuntimeDirectory as P,readGitLifecycleRuntime as H}from"../git/git-lifecycle-store.js";import{rootMemoryGitFileState as I,verifyRootMemoryEffectGitEvidence as C,verifyRootMemoryPhysicalWriteSet as $}from"./root-memory-git-evidence.js";import{rootMemoryFileState as G}from"./root-memory-writer.js";import{ROOT_MEMORY_REVIEW_CHECKS as b,ROOT_MEMORY_STEP_DIGEST as T}from"./root-memory-request.js";import{parseRefreshMemoryArgs as q,verifyProjectMemoryTargets as F}from"../commands/refresh-memory.js";const j=new WeakMap,n=()=>{throw new Error("private-root-memory-scope-unverified")};function m(e,o){return A("git",[...o],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],env:{...Object.fromEntries(Object.entries(process.env).filter(([h])=>!h.startsWith("GIT_"))),GIT_NO_REPLACE_OBJECTS:"1"},timeout:3e4,maxBuffer:2*1024*1024})}async function J(e){let o="pin";try{const h=w(e.projectRoot);if(!/^P[1-9][0-9]*\.[0-9]+$/.test(e.storyId))return n();const r=await k(await P(h),"private-execution"),a=g(r,`session-${S("sha256").update(e.storyId).digest("hex")}.json`);await R(a,r);const i=l(a);if(i.length>128*1024)return n();const s=JSON.parse(i.toString("utf8"));if(o="binding",s.storyId!==e.storyId||s.graphRevision!==e.graphRevision||s.setupSessionId!==e.setupSessionId||s.snapshotSha!==e.snapshotSha||s.workspace?.sourceRoot!==h||s.workspace?.workspacePath!==e.snapshotRoot||s.workspace?.baseSha!==e.sourceHeadSha||s.workspace?.executionBranch!==e.executionBranch)return n();if(s.rootMemoryEffect===void 0)return;const t=s.rootMemoryEffect;if(!_(t)||!Array.isArray(s.graphHistory)||!s.graphHistory.includes(t.graphRevision))return n();o="producer-receipt";const d=f=>S("sha256").update(f).digest("hex"),y=g(r,`memory-review-${d(JSON.stringify(t))}.json`);await R(y,r);const x=l(y);if(x.length>128*1024)return n();const c=JSON.parse(x.toString("utf8"));if(Object.keys(c).sort().join("|")!==["schemaVersion","kind","storyId","graphRevision","sourceHeadSha","snapshotSha","proposalSha256","notesSha256","sourceStateSha256","checks","reviewedAt","rootMemoryEffect","independentStoryQaAccepted","terminalAccepted"].sort().join("|")||c.schemaVersion!==1||c.kind!=="private-project-memory-root-review"||c.storyId!==e.storyId||c.graphRevision!==t.graphRevision||c.sourceHeadSha!==e.sourceHeadSha||c.snapshotSha!==t.memorySnapshotSha||c.notesSha256!==t.proposalSha256||c.reviewedAt!==t.recordedAt||c.independentStoryQaAccepted!==!1||c.terminalAccepted!==!1||!u(c.rootMemoryEffect,t)||!c.checks||Object.keys(c.checks).sort().join("|")!==[...b].sort().join("|")||b.some(f=>c.checks[f]!==!0)||c.proposalSha256!==d(Buffer.from(m(e.snapshotRoot,["show",`${t.sourceSnapshotSha}:.neocortex/stories/${e.storyId}/validation-evidence.md`])))||c.sourceStateSha256!==d(Buffer.from(m(e.snapshotRoot,["show",`${t.sourceSnapshotSha}:.neocortex/state.json`]))))return n();const E=g(r,`qa-review-${t.rootQaReceiptId}.json`);await R(E,r);const v=l(E);if(v.length>16384||d(v)!==t.rootQaReceiptId)return n();const p=JSON.parse(v.toString("utf8"));if(p.kind!=="private-qa-root-review"||p.storyId!==e.storyId||p.sourceHeadSha!==e.sourceHeadSha||p.precommitQaAccepted!==!0||p.independentStoryQaAccepted!==!1||p.terminalAccepted!==!1||(m(e.snapshotRoot,["merge-base","--is-ancestor",p.snapshotSha,t.sourceSnapshotSha]),o="git-evidence",C(e.snapshotRoot,t,{storyId:e.storyId,executionBranch:e.executionBranch,sourceHeadSha:e.sourceHeadSha,graphRevision:t.graphRevision,setupSessionId:e.setupSessionId,childClaimRevision:S("sha256").update([...e.childPaths].sort().join("\0")).digest("hex")}),o="range",m(e.snapshotRoot,["merge-base","--is-ancestor",t.memorySnapshotSha,e.snapshotSha]),m(e.snapshotRoot,["diff","--name-only","--no-renames","--no-ext-diff","--no-textconv","-z",e.sourceHeadSha,e.snapshotSha]).split("\0").filter(Boolean).some(f=>!e.childPaths.includes(f)&&!t.files.some(O=>O.path===f))))return n();o="files";for(const f of t.files)if(e.childPaths.includes(f.path)||!u(I(e.snapshotRoot,e.sourceHeadSha,f.path),f.before)||!u(I(e.snapshotRoot,e.snapshotSha,f.path),f.after))return n();const M=Object.freeze(Object.create(null));return j.set(M,Object.freeze({effect:structuredClone(t),root:h,snapshotRoot:e.snapshotRoot})),M}catch{throw new Error(`private-root-memory-scope-${o}-unverified`)}}function N(e){const o=j.get(e);return o?structuredClone(o.effect):n()}function Q(e,o,h,r){return L(e,o,h,r)==="matched"}function L(e,o,h,r){const a=j.get(e);if(!a||a.root!==w(o)||h!==void 0&&h!==a.snapshotRoot)return"scope-binding";let i="snapshot-ancestry";try{if(r&&(m(a.snapshotRoot,["merge-base","--is-ancestor",a.effect.memorySnapshotSha,r]),i="snapshot-content",a.effect.files.some(t=>!u(I(a.snapshotRoot,r,t.path),t.after)))||(i="source-content",!a.effect.files.every(t=>u(G(o,t.path),t.after))))return i;i="source-projection";const s=F(q(["--project-root",o,"--verify"]));return s.canonicalSha256===a.effect.canonicalSha256&&s.projectionSha256===a.effect.projectionSha256&&s.fileCount===a.effect.projectionFileCount?"matched":i}catch{return i+"-unsafe"}}async function re(e){try{const o=w(e.projectRoot),h=await H(o,{required:!0}),r=h.stories[e.storyId]?.checkpoint;if(r?.rootMemoryEffect!==void 0)return r.storyId!==e.storyId||r.branch!==e.executionBranch||typeof r.baseSha!="string"||typeof r.headSha!="string"?n():structuredClone($(o,r.rootMemoryEffect,{storyId:e.storyId,executionBranch:e.executionBranch,baseSha:r.baseSha,headRef:r.headSha,childPaths:e.childPaths}));if(!/^P[1-9][0-9]*\.[0-9]+$/.test(e.storyId))return;const a=await k(await P(o),"private-execution"),i=g(a,`session-${S("sha256").update(e.storyId).digest("hex")}.json`);if(!B(i))return;await R(i,a);const s=l(i);if(s.length>128*1024)return n();const t=JSON.parse(s.toString("utf8"));if(t.rootMemoryEffect===void 0)return;const d=h.stories[e.storyId];if(d?.status!=="memory-updated"||typeof d.last_step!="string"||S("sha256").update(d.last_step).digest("hex")!==T||!Array.isArray(d.steps_completed)||d.steps_completed.at(-1)!==d.last_step)return n();const y=await J({projectRoot:o,storyId:e.storyId,snapshotRoot:t.workspace?.workspacePath,snapshotSha:t.snapshotSha,sourceHeadSha:t.workspace?.baseSha,executionBranch:e.executionBranch,graphRevision:e.graphRevision,setupSessionId:t.setupSessionId,childPaths:e.childPaths});return!y||!Q(y,o,t.workspace?.workspacePath,t.snapshotSha)?n():N(y)}catch{return n()}}export{N as privateRootMemoryEffect,L as privateRootMemorySourceMatchReason,Q as privateRootMemorySourceMatches,J as readPrivateRootMemoryScope,re as readRootMemoryEffectForCheckpoint};
1
+ import{createHash as S}from"node:crypto";import{execFileSync as A}from"node:child_process";import{existsSync as B,readFileSync as l}from"node:fs";import{join as g,resolve as w}from"node:path";import{isDeepStrictEqual as u}from"node:util";import{isRootProjectMemoryEffect as _}from"./shared-root-memory-types.js";import{assertGitLifecyclePrivateFile as R,ensureGitLifecyclePrivateChildDirectory as k,gitLifecycleRuntimeDirectory as P,readGitLifecycleRuntime as H}from"../git/git-lifecycle-store.js";import{rootMemoryGitFileState as I,verifyRootMemoryEffectGitEvidence as C,verifyRootMemoryPhysicalWriteSet as $}from"./root-memory-git-evidence.js";import{rootMemoryFileState as G}from"./root-memory-writer.js";import{ROOT_MEMORY_REVIEW_CHECKS as b,ROOT_MEMORY_STEP_DIGEST as T}from"./root-memory-request.js";import{parseRefreshMemoryArgs as q,verifyProjectMemoryTargets as F}from"../commands/refresh-memory.js";const j=new WeakMap,n=()=>{throw new Error("private-root-memory-scope-unverified")};function m(e,o){return A("git",[...o],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],env:{...Object.fromEntries(Object.entries(process.env).filter(([h])=>!h.startsWith("GIT_"))),GIT_NO_REPLACE_OBJECTS:"1"},timeout:3e4,maxBuffer:2*1024*1024})}async function J(e){let o="pin";try{const h=w(e.projectRoot);if(!/^P[1-9][0-9]*\.[0-9]+$/.test(e.storyId))return n();const r=await k(await P(h),"private-execution"),a=g(r,`session-${S("sha256").update(e.storyId).digest("hex")}.json`);await R(a,r);const i=l(a);if(i.length>128*1024)return n();const s=JSON.parse(i.toString("utf8"));if(o="binding",s.storyId!==e.storyId||s.graphRevision!==e.graphRevision||s.setupSessionId!==e.setupSessionId||s.snapshotSha!==e.snapshotSha||s.workspace?.sourceRoot!==h||s.workspace?.workspacePath!==e.snapshotRoot||s.workspace?.baseSha!==e.sourceHeadSha||s.workspace?.executionBranch!==e.executionBranch)return n();if(s.rootMemoryEffect===void 0)return;const t=s.rootMemoryEffect;if(!_(t)||!Array.isArray(s.graphHistory)||!s.graphHistory.includes(t.graphRevision))return n();o="producer-receipt";const d=f=>S("sha256").update(f).digest("hex"),y=g(r,`memory-review-${d(JSON.stringify(t))}.json`);await R(y,r);const x=l(y);if(x.length>128*1024)return n();const c=JSON.parse(x.toString("utf8"));if(Object.keys(c).sort().join("|")!==["schemaVersion","kind","storyId","graphRevision","sourceHeadSha","snapshotSha","proposalSha256","notesSha256","sourceStateSha256","checks","reviewedAt","rootMemoryEffect","independentStoryQaAccepted","terminalAccepted"].sort().join("|")||c.schemaVersion!==1||c.kind!=="private-project-memory-root-review"||c.storyId!==e.storyId||c.graphRevision!==t.graphRevision||c.sourceHeadSha!==e.sourceHeadSha||c.snapshotSha!==t.memorySnapshotSha||c.notesSha256!==t.proposalSha256||c.reviewedAt!==t.recordedAt||c.independentStoryQaAccepted!==!1||c.terminalAccepted!==!1||!u(c.rootMemoryEffect,t)||!c.checks||Object.keys(c.checks).sort().join("|")!==[...b].sort().join("|")||b.some(f=>c.checks[f]!==!0)||c.proposalSha256!==d(Buffer.from(m(e.snapshotRoot,["show",`${t.sourceSnapshotSha}:.neocortex/stories/${e.storyId}/validation-evidence.md`])))||c.sourceStateSha256!==d(Buffer.from(m(e.snapshotRoot,["show",`${t.sourceSnapshotSha}:.neocortex/state.json`]))))return n();const E=g(r,`qa-review-${t.rootQaReceiptId}.json`);await R(E,r);const v=l(E);if(v.length>16384||d(v)!==t.rootQaReceiptId)return n();const p=JSON.parse(v.toString("utf8"));if(p.kind!=="private-qa-root-review"||p.storyId!==e.storyId||p.sourceHeadSha!==e.sourceHeadSha||p.precommitQaAccepted!==!0||p.independentStoryQaAccepted!==!1||p.terminalAccepted!==!1||(m(e.snapshotRoot,["merge-base","--is-ancestor",p.snapshotSha,t.sourceSnapshotSha]),o="git-evidence",C(e.snapshotRoot,t,{storyId:e.storyId,executionBranch:e.executionBranch,sourceHeadSha:e.sourceHeadSha,graphRevision:t.graphRevision,setupSessionId:e.setupSessionId,childClaimRevision:S("sha256").update([...e.childPaths].sort().join("\0")).digest("hex")}),o="range",m(e.snapshotRoot,["merge-base","--is-ancestor",t.memorySnapshotSha,e.snapshotSha]),m(e.snapshotRoot,["diff","--name-only","--no-renames","--no-ext-diff","--no-textconv","-z",e.sourceHeadSha,e.snapshotSha]).split("\0").filter(Boolean).some(f=>!e.childPaths.includes(f)&&!t.files.some(O=>O.path===f))))return n();o="files";for(const f of t.files)if(e.childPaths.includes(f.path)||!u(I(e.snapshotRoot,e.sourceHeadSha,f.path),f.before)||!u(I(e.snapshotRoot,e.snapshotSha,f.path),f.after))return n();const M=Object.freeze(Object.create(null));return j.set(M,Object.freeze({effect:structuredClone(t),root:h,snapshotRoot:e.snapshotRoot})),M}catch{throw new Error(`private-root-memory-scope-${o}-unverified`)}}function N(e){const o=j.get(e);return o?structuredClone(o.effect):n()}function Q(e,o,h,r){return L(e,o,h,r)==="matched"}function L(e,o,h,r){const a=j.get(e);if(!a||a.root!==w(o)||h!==void 0&&h!==a.snapshotRoot)return"scope-binding";let i="snapshot-ancestry";try{if(r&&(m(a.snapshotRoot,["merge-base","--is-ancestor",a.effect.memorySnapshotSha,r]),i="snapshot-content",a.effect.files.some(t=>!u(I(a.snapshotRoot,r,t.path),t.after)))||(i="source-content",!a.effect.files.every(t=>u(G(o,t.path),t.after))))return i;i="source-projection";const s=F(q(["--project-root",o,"--verify"]));return s.canonicalSha256===a.effect.canonicalSha256&&s.projectionSha256===a.effect.projectionSha256&&s.fileCount===a.effect.projectionFileCount?"matched":i}catch{return i+"-unsafe"}}async function re(e){try{const o=w(e.projectRoot),h=await H(o,{required:!0}),r=h.stories[e.storyId]?.checkpoint;if(r?.rootMemoryEffect!==void 0)return r.storyId!==e.storyId||r.branch!==e.executionBranch||typeof r.baseSha!="string"||typeof r.headSha!="string"?n():structuredClone($(o,r.rootMemoryEffect,{storyId:e.storyId,executionBranch:e.executionBranch,baseSha:r.baseSha,headRef:r.headSha,childPaths:e.childPaths}));if(!/^P[1-9][0-9]*\.[0-9]+$/.test(e.storyId))return;const a=await k(await P(o),"private-execution"),i=g(a,`session-${S("sha256").update(e.storyId).digest("hex")}.json`);if(!B(i))return;await R(i,a);const s=l(i);if(s.length>128*1024)return n();const t=JSON.parse(s.toString("utf8"));if(t.rootMemoryEffect===void 0)return;const d=h.stories[e.storyId];if(d?.status!=="memory-updated"||typeof d.last_step!="string"||S("sha256").update(d.last_step).digest("hex")!==T||!Array.isArray(d.steps_completed)||d.steps_completed.at(-1)!==d.last_step)return n();const y=await J({projectRoot:o,storyId:e.storyId,snapshotRoot:t.workspace?.workspacePath,snapshotSha:t.snapshotSha,sourceHeadSha:t.workspace?.baseSha,executionBranch:e.executionBranch,graphRevision:e.graphRevision,setupSessionId:t.setupSessionId,childPaths:e.childPaths});return!y||!Q(y,o,t.workspace?.workspacePath,t.snapshotSha)?n():N(y)}catch{return n()}}export{N as privateRootMemoryEffect,L as privateRootMemorySourceMatchReason,Q as privateRootMemorySourceMatches,J as readPrivateRootMemoryScope,re as readRootMemoryEffectForCheckpoint};
@@ -1,4 +1,4 @@
1
- import { type RootMemoryFileEffect, type RootMemoryFileState } from '../../../shared/dist/yoloop/root-memory-effect.js';
1
+ import { type RootMemoryFileEffect, type RootMemoryFileState } from './shared-root-memory-types.js';
2
2
  import { type ProjectMemoryVerification } from '../commands/refresh-memory.js';
3
3
  export interface RootMemoryWriterAuthority {
4
4
  readonly __rootMemoryWriter?: never;