@ornexus/neocortex 4.66.0 → 4.66.1

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 (90) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1206 -1193
  3. package/install.ps1 +1 -1
  4. package/install.sh +2 -2
  5. package/package.json +2 -2
  6. package/packages/client/dist/commands/doctor.d.ts +26 -1
  7. package/packages/client/dist/commands/doctor.js +2 -2
  8. package/packages/client/dist/commands/invoke.d.ts +149 -1
  9. package/packages/client/dist/commands/invoke.js +88 -83
  10. package/packages/client/dist/commands/planning-qa.d.ts +57 -0
  11. package/packages/client/dist/commands/planning-qa.js +1 -1
  12. package/packages/client/dist/commands/story-checkpoint.d.ts +2 -0
  13. package/packages/client/dist/commands/story-checkpoint.js +1 -1
  14. package/packages/client/dist/commands/story-worktree.d.ts +1 -1
  15. package/packages/client/dist/commands/story-worktree.js +1 -1
  16. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +51 -0
  17. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -3
  18. package/packages/client/dist/git/epic-lifecycle-evidence.d.ts +184 -0
  19. package/packages/client/dist/git/epic-lifecycle-evidence.js +6 -0
  20. package/packages/client/dist/git/git-lifecycle-store.d.ts +9 -0
  21. package/packages/client/dist/git/git-lifecycle-store.js +9 -8
  22. package/packages/client/dist/git/story-worktree-cleanup.js +1 -1
  23. package/packages/client/dist/git/story-worktree-integration.js +3 -3
  24. package/packages/client/dist/git/story-worktree-manager.d.ts +39 -0
  25. package/packages/client/dist/git/story-worktree-manager.js +3 -3
  26. package/packages/client/dist/git/story-write-set-extension.d.ts +62 -0
  27. package/packages/client/dist/git/story-write-set-extension.js +1 -1
  28. package/packages/client/dist/private-execution/codex-executor.d.ts +13 -0
  29. package/packages/client/dist/private-execution/codex-executor.js +4 -4
  30. package/packages/client/dist/private-execution/harness-adapters/antigravity.d.ts +9 -0
  31. package/packages/client/dist/private-execution/harness-adapters/antigravity.js +1 -0
  32. package/packages/client/dist/private-execution/harness-adapters/claude-code.d.ts +8 -0
  33. package/packages/client/dist/private-execution/harness-adapters/claude-code.js +1 -0
  34. package/packages/client/dist/private-execution/harness-adapters/codex.d.ts +7 -0
  35. package/packages/client/dist/private-execution/harness-adapters/codex.js +1 -0
  36. package/packages/client/dist/private-execution/harness-adapters/copilot-cli.d.ts +8 -0
  37. package/packages/client/dist/private-execution/harness-adapters/copilot-cli.js +1 -0
  38. package/packages/client/dist/private-execution/harness-adapters/cursor.d.ts +9 -0
  39. package/packages/client/dist/private-execution/harness-adapters/cursor.js +1 -0
  40. package/packages/client/dist/private-execution/harness-adapters/deepseek.d.ts +9 -0
  41. package/packages/client/dist/private-execution/harness-adapters/deepseek.js +1 -0
  42. package/packages/client/dist/private-execution/harness-adapters/gemini.d.ts +8 -0
  43. package/packages/client/dist/private-execution/harness-adapters/gemini.js +1 -0
  44. package/packages/client/dist/private-execution/harness-adapters/grok.d.ts +9 -0
  45. package/packages/client/dist/private-execution/harness-adapters/grok.js +1 -0
  46. package/packages/client/dist/private-execution/harness-adapters/index.d.ts +73 -0
  47. package/packages/client/dist/private-execution/harness-adapters/index.js +1 -0
  48. package/packages/client/dist/private-execution/harness-adapters/kimi.d.ts +9 -0
  49. package/packages/client/dist/private-execution/harness-adapters/kimi.js +1 -0
  50. package/packages/client/dist/private-execution/harness-adapters/openclaw.d.ts +9 -0
  51. package/packages/client/dist/private-execution/harness-adapters/openclaw.js +1 -0
  52. package/packages/client/dist/private-execution/harness-adapters/opencode.d.ts +7 -0
  53. package/packages/client/dist/private-execution/harness-adapters/opencode.js +1 -0
  54. package/packages/client/dist/private-execution/harness-ephemeral-home.d.ts +19 -0
  55. package/packages/client/dist/private-execution/harness-ephemeral-home.js +1 -0
  56. package/packages/client/dist/private-execution/harness-executor.d.ts +79 -0
  57. package/packages/client/dist/private-execution/harness-executor.js +1 -0
  58. package/packages/client/dist/private-execution/harness-process.d.ts +43 -0
  59. package/packages/client/dist/private-execution/harness-process.js +1 -0
  60. package/packages/client/dist/private-execution/isolated-admission.js +12 -12
  61. package/packages/client/dist/private-execution/isolated-workspace.d.ts +16 -1
  62. package/packages/client/dist/private-execution/isolated-workspace.js +1 -1
  63. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +1 -22
  64. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +6 -10
  65. package/packages/client/dist/state/project-state-snapshot.d.ts +10 -0
  66. package/packages/client/dist/state/project-state-snapshot.js +1 -1
  67. package/packages/client/dist/state/structural-dag-projection.d.ts +26 -0
  68. package/packages/client/dist/state/structural-dag-projection.js +1 -1
  69. package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +67 -0
  70. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1
  71. package/packages/shared/dist/compatibility/index.js +28 -0
  72. package/targets-stubs/antigravity/gemini.md +1 -1
  73. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  74. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  75. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  76. package/targets-stubs/claude-code/neocortex-sentinel.md +1 -1
  77. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  78. package/targets-stubs/claude-code/neocortex.md +2 -2
  79. package/targets-stubs/codex/AGENTS.md +1 -1
  80. package/targets-stubs/cursor/agent.md +2 -2
  81. package/targets-stubs/gemini-cli/agent.md +2 -2
  82. package/targets-stubs/gemini-cli/agents/neocortex.md +2 -2
  83. package/targets-stubs/grok/SKILL.md +3 -3
  84. package/targets-stubs/grok/agents/{neocortex.md → neocortex-sentinel.md} +2 -2
  85. package/targets-stubs/grok/install-grok.sh +45 -8
  86. package/targets-stubs/lib/managed-config-merge.js +21 -1
  87. package/targets-stubs/lib/mcp-merge.js +12 -3
  88. package/targets-stubs/opencode/neocortex-root.md +1 -1
  89. package/targets-stubs/opencode/neocortex.md +1 -1
  90. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -0,0 +1,43 @@
1
+ export type PrivateHarnessPlatform = 'linux' | 'darwin' | 'win32';
2
+ export declare const MAX_PRIVATE_HARNESS_MATERIAL_BYTES: number;
3
+ export declare const PRIVATE_HARNESS_KILL_GRACE_MS = 500;
4
+ export type TreeKillStep = {
5
+ readonly kind: 'signal-group';
6
+ readonly signal: 'SIGTERM' | 'SIGKILL';
7
+ readonly pid: number;
8
+ } | {
9
+ readonly kind: 'command';
10
+ readonly command: 'taskkill';
11
+ readonly args: readonly ['/T', '/F', '/PID', string];
12
+ };
13
+ export interface BoundedHarnessProcessResult {
14
+ readonly exitCode: number | null;
15
+ readonly stdout: Buffer;
16
+ readonly stderr: Buffer;
17
+ readonly timedOut: boolean;
18
+ readonly outputExceeded: boolean;
19
+ }
20
+ export interface BoundedHarnessProcessOptions {
21
+ readonly cwd: string;
22
+ readonly stdin?: string;
23
+ readonly timeoutMs: number;
24
+ readonly maxOutputBytes: number;
25
+ readonly environmentKeys: readonly string[];
26
+ readonly environmentOverrides?: Readonly<Record<string, string>>;
27
+ readonly platform?: PrivateHarnessPlatform;
28
+ readonly killGraceMs?: number;
29
+ /** Test seam: receives the full plan once; timing becomes the caller's job. */
30
+ readonly killTree?: (steps: readonly TreeKillStep[], pid: number) => void;
31
+ }
32
+ export declare function resolvePrivateHarnessPlatform(platform?: string): PrivateHarnessPlatform;
33
+ export declare function planTreeKill(platform: PrivateHarnessPlatform, pid: number): readonly TreeKillStep[];
34
+ /**
35
+ * P229.02 (AC-ENV): variables a Windows child needs to start at all. They are
36
+ * added to an adapter allowlist only on win32; linux and darwin are unchanged.
37
+ */
38
+ export declare const PRIVATE_HARNESS_WIN32_BOOTSTRAP_KEYS: readonly string[];
39
+ export declare function harnessEnvironmentKeys(platform: PrivateHarnessPlatform, keys: readonly string[]): readonly string[];
40
+ /** Only declared keys reach the child; no host secret or proxy is inherited. */
41
+ export declare function harnessEnvironment(source: NodeJS.ProcessEnv, keys: readonly string[]): NodeJS.ProcessEnv;
42
+ export declare function assertPrivateHarnessMaterial(material: unknown): asserts material is string;
43
+ export declare function runBoundedHarnessProcess(command: string, args: readonly string[], options: BoundedHarnessProcessOptions): Promise<BoundedHarnessProcessResult>;
@@ -0,0 +1 @@
1
+ import{spawn as y}from"node:child_process";const L=256*1024,R=500,b=["linux","darwin","win32"];function E(r=process.platform){if(!b.includes(r))throw new Error("private-executor-platform-unsupported");return r}function M(r,t){const e=E(r);if(!Number.isSafeInteger(t)||t<=0)throw new Error("private-executor-spawn-failed");return Object.freeze(e==="win32"?[Object.freeze({kind:"command",command:"taskkill",args:Object.freeze(["/T","/F","/PID",String(t)])})]:[Object.freeze({kind:"signal-group",signal:"SIGTERM",pid:t}),Object.freeze({kind:"signal-group",signal:"SIGKILL",pid:t})])}const _=Object.freeze(["SYSTEMROOT","USERPROFILE","APPDATA","LOCALAPPDATA","PATHEXT","COMSPEC","TEMP","TMP"]);function H(r,t){return E(r)!=="win32"?t:Object.freeze([...t,..._.filter(e=>!t.includes(e))])}function j(r,t){const e={};for(const s of t)typeof r[s]=="string"&&(e[s]=r[s]);return e}function B(r){if(typeof r!="string")throw new Error("private-executor-material-invalid");const t=Buffer.byteLength(r,"utf8");if(t<1||t>L)throw new Error("private-executor-material-invalid")}function k(r,t){try{return process.kill(-r,t),!0}catch(e){if(e.code==="ESRCH")return!1;throw e}}function K(r){try{const t=y("taskkill",[...r],{stdio:"ignore",windowsHide:!0,shell:!1});t.on("error",()=>{}),t.unref()}catch{}}function C(r,t,e){let s;try{e.stdin!==void 0&&B(e.stdin),s=E(e.platform??process.platform)}catch(a){return Promise.reject(a)}const T=s!=="win32",I=e.killGraceMs??R,w=j(process.env,H(s,e.environmentKeys));for(const[a,c]of Object.entries(e.environmentOverrides??{}))w[a]=c;return new Promise((a,c)=>{let n;try{n=y(r,[...t],{cwd:e.cwd,env:w,stdio:["pipe","pipe","pipe"],detached:T,windowsHide:!0,shell:!1})}catch{c(new Error("private-executor-spawn-failed"));return}const v=[],S=[];let g=0,h=0,O=!1,f=!1,d=!1,l=!1,u;const p=()=>{if(u&&(clearTimeout(u),u=void 0),T&&n.pid!==void 0&&!e.killTree)try{k(n.pid,"SIGKILL")}catch{}},P=()=>{if(d||n.pid===void 0)return;d=!0;const i=M(s,n.pid);if(e.killTree){e.killTree(i,n.pid);return}const[o]=i;try{o?.kind==="command"?K(o.args):o?.kind==="signal-group"&&k(o.pid,o.signal)&&(u=setTimeout(p,I))}catch{try{n.kill("SIGKILL")}catch{}}},A=setTimeout(()=>{O=!0,P()},e.timeoutMs),x=(i,o)=>m=>{o==="stdout"?g+=m.byteLength:h+=m.byteLength,g+h>e.maxOutputBytes?(f=!0,P()):f||i.push(m)};n.stdout.on("data",x(v,"stdout")),n.stderr.on("data",x(S,"stderr")),n.stdin.on("error",()=>{}),n.on("error",i=>{clearTimeout(A),p(),!l&&(l=!0,c(new Error(i.code==="ENOENT"||i.code==="EACCES"?"private-executor-headless-unavailable":"private-executor-spawn-failed")))}),n.on("close",i=>{clearTimeout(A),d&&p(),!l&&(l=!0,a({exitCode:i,stdout:Buffer.concat(v),stderr:Buffer.concat(S),timedOut:O,outputExceeded:f}))}),n.stdin.end(e.stdin)})}export{L as MAX_PRIVATE_HARNESS_MATERIAL_BYTES,R as PRIVATE_HARNESS_KILL_GRACE_MS,_ as PRIVATE_HARNESS_WIN32_BOOTSTRAP_KEYS,B as assertPrivateHarnessMaterial,j as harnessEnvironment,H as harnessEnvironmentKeys,M as planTreeKill,E as resolvePrivateHarnessPlatform,C as runBoundedHarnessProcess};
@@ -1,23 +1,23 @@
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,`
1
+ import{execFileSync as Ft,spawnSync as vt}from"node:child_process";import{createHash as F}from"node:crypto";import{existsSync as nt,lstatSync as R,readFileSync as m,realpathSync as ht,writeFileSync as mt}from"node:fs";import{isAbsolute as ot,join as a,relative as dt,sep as wt}from"node:path";import{isDeepStrictEqual as S}from"node:util";import{readPrivateYoloFrozenWriteSet as Bt,verifyPrivateYoloCandidateWriteSet as Ct,verifyPrivateYoloCleanBaseline as zt}from"./clean-baseline.js";import{isPrivateIsolatedWorkspacePlatform as _t,PRIVATE_EPIC_PENDING_SIDECAR as et,privateIsolatedWorkspaceModeVerified as bt,privatePendingEpicSidecarVerified as Lt}from"./isolated-workspace.js";import{loadPactPrivateAnswers as Ht}from"../commands/architecture-answers.js";import{derivePactWriteSet as xt}from"./pact-write-set.js";import{deriveUxCandidateWriteSet as Jt,deriveUxWriteSet as Mt}from"./ux-write-set.js";import{validateUxCandidateSource as qt}from"./ux-source-validation.js";import{validatePactTestSource as Gt}from"./pact-test-source.js";import{classifyProjectMemoryUpdate as Wt}from"../memory/project-memory-writer.js";import{privateRootMemoryEffect as yt,privateRootMemorySourceMatches as Yt,privateRootMemorySourceMatchReason as Ut}from"./root-memory-scope.js";import{inspectPactToolchain as Vt,planPactToolchainManifest as Xt}from"./pact-toolchain.js";import{acceptedPlanningDiagnosisPredecessor as Kt,planningPendingSidecarDigest as Rt}from"./planning-diagnosis-checkpoint.js";import{acceptedPlanningResearchPredecessor as Zt}from"./planning-research-checkpoint.js";import{confirmPropertyTestPlan as At,renderPropertyTestConfiguration as Qt}from"./property-test-plan.js";import{validatePropertyTestTypeScriptSource as kt}from"./property-test-source.js";const Z=16*1024*1024,st=1024,ut="acd455ed0e39d98b90fb57391db75e366e4c5604db043e03a89a20e33d643c3c",It="81f50aaa801c1660eabe46e645501acbfb3e9873410c991e1496c014ca75c369",St="fa2194f89c01f07e225fd6f39e98e679f628e072239b6cd0af3ee527f0722518",te="8636f22ec5950410902448ee1e9cb4947359ac98df518742bddbbb367468e3ae";function tt(t,r){return typeof t=="string"&&t.length<=128&&F("sha256").update(t).digest("hex")===r}function Et(){const t={...process.env};for(const r of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete t[r];return t}function G(t,r){return Ft("git",[...r],{cwd:t,env:Et(),stdio:["ignore","pipe","pipe"],timeout:3e4,maxBuffer:Z})}function J(t,r){return G(t,r).toString("utf8").trim()}function B(t,r=!1){return G(t,["status","--porcelain=v1","-z","--untracked-files=all",...r?["--ignored=matching"]:[]])}function rt(t){return!!t&&!ot(t)&&!t.includes("\\")&&!t.includes("\0")&&!t.split("/").some(r=>!r||r==="."||r===".."||r===".git")}function P(t,r){const e=r.split("/");let o=t;for(const s of e.slice(0,-1)){o=a(o,s);try{const i=R(o);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("path-boundary")}catch(i){if(i.code==="ENOENT")return;throw i}}try{const s=R(a(t,r));if(!s.isFile()||s.isSymbolicLink()||s.size>Z)throw new Error("path-boundary")}catch(s){if(s.code!=="ENOENT")throw s}}function $t(t){const r=[...t.matchAll(/\/\/\s*arch:keep-start[^\n]*\n[\s\S]*?\/\/\s*arch:keep-end[^\n]*/g)].map(s=>s[0]),e=(t.match(/arch:keep-start/g)??[]).length,o=(t.match(/arch:keep-end/g)??[]).length;if(e!==o||e!==r.length)throw new Error("architecture-keep-marker-invalid");return r}function M(t,r=!1,e=!1,o=[]){const s=[],i=[];for(const n of t.toString("utf8").split("\0").filter(Boolean)){if(n.length<4||n[2]!==" ")throw new Error("status-invalid");const d=n.slice(0,2),l=n.slice(3);if(!rt(l)||d!=="??"&&d!==" M"&&d!==" D"&&!(d===" T"&&o.includes(l))&&!(e&&d==="!!"&&l===et))throw new Error("status-invalid");s.push(l),d==="??"&&i.push(l)}if(!r&&s.length===0||s.length>st||new Set(s).size!==s.length)throw new Error("status-invalid");return{paths:s.sort(),untracked:i.sort()}}function lt(t,r,e,o){const s=G(r,["ls-tree","-z",e,"--",o]).toString("utf8");if(!s)try{return R(a(t,o)),!1}catch(n){return n.code==="ENOENT"}const i=/^([0-7]{6}) blob [a-f0-9]{40,64}\t([^\0]+)\0$/.exec(s);if(!i||i[2]!==o||!["100644","100755"].includes(i[1]))return!1;try{const n=R(a(t,o));return!n.isFile()||n.isSymbolicLink()||n.size>Z||!!(n.mode&73)!=(i[1]==="100755")?!1:m(a(t,o)).equals(G(r,["show",`${e}:${o}`]))}catch{return!1}}function xe(t,r,e,o){return rt(o)&&/^[a-f0-9]{40,64}$/.test(e)&&lt(t,r,e,o)}function it(t,r){try{const e=a(t,et);return Lt(t)&&F("sha256").update(m(e)).digest("hex")===r}catch{return!1}}function ft(t,r,e,o,s,i){const n=new Set(o),d=i?yt(i).files.map(f=>f.path):[],l=M(B(t),!0,!!s,d),c=i?Ut(i,t,r,e):"matched";if(c!=="matched")throw new Error(`root-memory-${c}`);if(!l.paths.every(f=>n.has(f)||d.includes(f)||f===et&&!!s&&it(t,s)))throw new Error("source-unclaimed-delta");if(!o.every(f=>lt(t,r,e,f)))throw new Error("source-frozen-mismatch");return!s||it(t,s)}function ee(t,r){const e=vt("git",["diff","--no-index","--binary","--no-ext-diff","--","/dev/null",r],{cwd:t,env:Et(),encoding:"buffer",timeout:3e4,maxBuffer:Z});if(e.error||e.status!==1||!Buffer.isBuffer(e.stdout)||e.stdout.byteLength===0)throw new Error("patch-invalid");return e.stdout}function Ot(t,r,e){const o=vt("git",["apply",...e?["--check"]:[],"--binary","-"],{cwd:t,env:Et(),input:r,encoding:"buffer",timeout:3e4,maxBuffer:Z});if(o.error||o.status!==0)throw new Error("apply-failed")}function pt(t,r,e){const o=a(t,e),s=a(r,e);try{const i=R(o),n=R(s);return i.isFile()&&n.isFile()&&(i.mode&73)===(n.mode&73)&&m(o).equals(m(s))}catch(i){if(i.code!=="ENOENT")return!1;try{return R(o),!1}catch(n){if(n.code!=="ENOENT")return!1}try{return R(s),!1}catch(n){return n.code==="ENOENT"}}}function Re(t,r,e,o){Tt(t,r,e,!0,o)}function Ae(t,r,e,o){if(Tt(t,r,e,!1,o),G(t.workspacePath,["diff","--cached","--name-only"]).byteLength!==0)throw new Error("private-execution-isolated-snapshot-unverified")}function Tt(t,r,e,o,s){try{if(!_t()||t.schemaVersion!==1||!ot(t.sourceRoot)||!ot(t.workspacePath)||ht(t.sourceRoot)!==t.sourceRoot||ht(t.workspacePath)!==t.workspacePath||!R(t.workspacePath).isDirectory()||!bt(R(t.workspacePath))||dt(t.sourceRoot,t.workspacePath)===""||dt(t.sourceRoot,t.workspacePath).split(wt)[0]!==".."||!/^[a-f0-9]{40,64}$/.test(t.baseSha)||!/^[a-f0-9]{40,64}$/.test(e)||J(t.sourceRoot,["rev-parse","--show-toplevel"])!==t.sourceRoot||J(t.workspacePath,["rev-parse","--show-toplevel"])!==t.workspacePath||J(t.sourceRoot,["rev-parse","HEAD"])!==t.baseSha||J(t.workspacePath,["rev-parse","HEAD"])!==e||J(t.sourceRoot,["symbolic-ref","--short","HEAD"])!==t.executionBranch||J(t.workspacePath,["symbolic-ref","--short","HEAD"])!==t.executionBranch||nt(a(t.workspacePath,".git","objects","info","alternates"))||o&&B(t.workspacePath,!0).byteLength!==0||r.length===0||r.length>st||r.some(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,s))throw new Error("boundary-raced")}catch(i){const n=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(n)})}}function W(t,r,e,o,s,i=[],n){try{if(!_t()||t.schemaVersion!==1||!ot(t.sourceRoot)||!ot(t.workspacePath)||ht(t.sourceRoot)!==t.sourceRoot||ht(t.workspacePath)!==t.workspacePath||!R(t.workspacePath).isDirectory()||!bt(R(t.workspacePath))||dt(t.sourceRoot,t.workspacePath)===""||dt(t.sourceRoot,t.workspacePath).split(wt)[0]!==".."||J(t.sourceRoot,["rev-parse","--show-toplevel"])!==t.sourceRoot||J(t.workspacePath,["rev-parse","--show-toplevel"])!==t.workspacePath||J(t.sourceRoot,["rev-parse","HEAD"])!==t.baseSha||!/^[a-f0-9]{40,64}$/.test(e)||J(t.workspacePath,["rev-parse","HEAD"])!==e||J(t.sourceRoot,["symbolic-ref","--short","HEAD"])!==t.executionBranch||J(t.workspacePath,["symbolic-ref","--short","HEAD"])!==t.executionBranch||r.length===0||r.length>st||r.some(g=>!rt(g))||new Set(r).size!==r.length)throw new Error("authority-invalid");if(G(t.workspacePath,["merge-base","--is-ancestor",t.baseSha,e]),!ft(t.sourceRoot,t.workspacePath,e,r,o,n))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(s&&!s())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=>ee(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)||s&&!s()||!ft(t.sourceRoot,t.workspacePath,e,r,o,n))throw new Error("patch-raced");if(Ot(t.sourceRoot,p,!0),!B(t.workspacePath,!0).equals(d)||s&&!s()||!ft(t.sourceRoot,t.workspacePath,e,r,o,n))throw new Error("patch-raced");Ot(t.sourceRoot,p,!1);const w=n?yt(n).files.map(g=>g.path):[];if(M(B(t.sourceRoot),!0,!!o,w).paths.some(g=>!c.has(g)&&!w.includes(g)&&g!==et)||n&&!Yt(n,t.sourceRoot)||o&&!it(t.sourceRoot,o)||r.some(g=>!pt(t.workspacePath,t.sourceRoot,g))||J(t.sourceRoot,["rev-parse","HEAD"])!==t.baseSha||J(t.sourceRoot,["symbolic-ref","--short","HEAD"])!==t.executionBranch)throw new Error("admission-raced");return Object.freeze({schemaVersion:1,outcome:"admitted-unverified",baseSha:t.baseSha,executionBranch:t.executionBranch,changedPaths:Object.freeze([...l.paths]),patchSha256:F("sha256").update(p).digest("hex")})}catch{throw new Error("private-execution-isolated-admission-unverified")}}async function Se(t,r,e,o=t.baseSha,s=!1,i){try{const n=await Bt(t.sourceRoot,r,t.executionBranch,e);if(i){const f=yt(i);if(f.storyId!==r||f.childClaimRevision!==F("sha256").update([...n].sort().join("\0")).digest("hex"))throw new Error("root-memory-claim-mismatch")}const d=a(t.workspacePath,".neocortex","state.json"),l=R(d);if(!l.isFile()||l.isSymbolicLink()||l.size>Z)throw new Error("candidate-state-invalid");Ct(m(d,"utf8"),r,n);const c=W(t,n,o,void 0,void 0,s?[".neocortex/state.json"]:[],i);return await zt(t.sourceRoot,r,t.executionBranch,e),c}catch{throw new Error("private-execution-isolated-admission-unverified")}}const re=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"]),ne=new Set(["id","title","description","status","stories","total_stories","completed_stories","estimated_hours","complexity","priority","created_at","updated_at","last_updated","source","tags"]);function jt(t){return["title","description","complexity","priority","type","created_at","updated_at","last_updated","source"].some(e=>t[e]!==void 0&&typeof t[e]!="string")||t.estimated_hours!==void 0&&(typeof t.estimated_hours!="number"||!Number.isFinite(t.estimated_hours)||t.estimated_hours<0)?!1:["depends_on","acceptance_criteria","tags"].every(e=>t[e]===void 0||Array.isArray(t[e])&&t[e].length<=256&&t[e].every(o=>typeof o=="string"))}function oe(t){return Object.keys(t).every(r=>re.has(r))&&t.status==="backlog"&&jt(t)&&(t.steps_completed===void 0||Array.isArray(t.steps_completed)&&t.steps_completed.length===0)&&(t.last_step===void 0||t.last_step===null)&&(t.branch_name===void 0||t.branch_name===null)}function $e(t,r,e,o,s){try{if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(r)||!/^P[1-9][0-9]*$/.test(e)||!/^[a-f0-9]{64}$/.test(o)||!/^[a-f0-9]{64}$/.test(s)||!it(t.sourceRoot,s))throw new Error("claim-invalid");const i=JSON.parse(m(a(t.sourceRoot,et),"utf8")),n=i&&typeof i=="object"&&!Array.isArray(i)?i.operations?.[o]:void 0;if(!n||typeof n!="object"||Array.isArray(n)||n.claimId!==r||n.epicId!==e)throw new Error("claim-sidecar-mismatch");const 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 R(a(t.sourceRoot,E)),new Error("artifact-already-exists")}catch(T){if(T.code!=="ENOENT")throw T}const w=(E,T)=>{P(t.workspacePath,E);const K=m(a(t.workspacePath,E),"utf8");return Buffer.byteLength(K)>Z?null:/^---\r?\n([\s\S]{1,8192}?)\r?\n---(?:\r?\n|$)/.exec(K)?.[1]?.split(/\r?\n/).find(ct=>ct.startsWith(`${T}:`))?.slice(T.length+1).trim()?.replace(/^(["'])(.*)\1$/,"$2")??null};if(w(l,"id")!==e||h.some((E,T)=>w(E,"id")!==p[T]||w(E,"epic_id")!==e))throw new Error("artifact-id-invalid");P(t.workspacePath,c);const u=JSON.parse(m(a(t.workspacePath,c),"utf8"));if(!u||typeof u!="object"||Array.isArray(u))throw new Error("state-invalid");const g=u,_=g.epics,j=g.stories,b=_?.[e],N=g.epic_id_ledger;if(g.schema_version!==1||!b||b.id!==e||b.status!=="memory-updated"||Object.keys(b).some(E=>!ne.has(E))||!jt(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||!oe(T)})||!N||!Array.isArray(N.reserved_ids)||!N.reserved_ids.includes(e))throw new Error("state-claim-mismatch");P(t.sourceRoot,c);const y=JSON.parse(m(a(t.sourceRoot,c),"utf8")),A=y.epics,x=y.stories;if(!A||!x||A[e]!==void 0||p.some(E=>x[E]!==void 0))throw new Error("state-claim-conflict");const{[e]:Y,...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($,x)||!S({...Q,epics:void 0,stories:void 0},{...z,epics:void 0,stories:void 0}))throw new Error("state-unrelated-drift");const O=y.epic_id_ledger&&typeof y.epic_id_ledger=="object"?y.epic_id_ledger.reserved_ids:void 0,{reserved_ids:U,...v}=N,D=y.epic_id_ledger&&typeof y.epic_id_ledger=="object"?y.epic_id_ledger:{schema_version:1},{reserved_ids:H,...k}=D;if(O!==void 0&&(!Array.isArray(O)||O.some(E=>typeof E!="string"||!/^P[1-9][0-9]*$/.test(E))||new Set(O).size!==O.length))throw new Error("ledger-drift");const I=[...Array.isArray(O)?O:[]];if(I.includes(e)||I.push(e),!S(N.reserved_ids,I)||!S(v,k))throw new Error("ledger-drift");return W(t,d.paths,t.baseSha,s)}catch{throw new Error("private-execution-epic-claim-admission-unverified")}}function Oe(t,r,e,o,s,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(o)||!/^[a-f0-9]{64}$/.test(s)||typeof i!="string"||!i.trim()||i.length>16384||!it(t.sourceRoot,s))throw new Error("planning-claim-invalid");const n=JSON.parse(m(a(t.sourceRoot,et),"utf8")),d=n&&typeof n=="object"&&!Array.isArray(n)?n.operations?.[o]: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",w=[c,f,h,p],u=M(B(t.workspacePath,!0));if(u.paths.length!==w.length||u.paths.some(E=>!w.includes(E)))throw new Error("planning-artifact-scope-invalid");for(const E of[c,f,h]){P(t.workspacePath,E);try{throw R(a(t.sourceRoot,E)),new Error("planning-artifact-already-exists")}catch(T){if(T.code!=="ENOENT")throw T}}const g=(E,T)=>{const K=R(a(t.workspacePath,E));if(!K.isFile()||K.isSymbolicLink()||K.size<1||K.size>T)throw new Error("planning-artifact-invalid");return m(a(t.workspacePath,E),"utf8")},_=JSON.parse(g(c,32*1024));if(!_||typeof _!="object"||Array.isArray(_)||_.epic_id!==e||_.status!=="diagnosed"||typeof _.raw_input!="string"||_.raw_input!==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
- `),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,`
4
+ `),at=gt=>{const ct=Pt.filter(Dt=>Dt.startsWith(`${gt}:`));return ct.length===1?ct[0].slice(gt.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0};return at("epic_id")===e&&tt(at("step"),T)&&at("status")==="completed"};if(!N(j,ut)||!N(b,It))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 x=y,Y=x.epics,L=Y[e],$=L,q=$?.output_files;if(!L||typeof L!="object"||Array.isArray(L)||$?.id!==e||$.status!=="diagnosed"||$.idea!==_.raw_input||!Array.isArray($.steps_completed)||$.steps_completed.length!==1||!tt($.steps_completed[0],ut)||typeof $.created_at!="string"||!Number.isFinite(Date.parse($.created_at))||$.completed_at!==null||!q||typeof q!="object"||Array.isArray(q)||!S(q,{diagnosis:`${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}=x,X=A,Q=X?.epics,{last_scan:O,epics:U,...v}=X??{},{[e]:D,...H}=Y;if(Q?.[e]!==void 0||!S(H,Q??{})||X!==void 0&&!S(V,v)||X===void 0&&(Object.keys(Y).length!==1||!S(Object.keys(x).sort(),["version","next_epic_id","last_scan","existing_epics_discovered","epics"].sort())||x.version!=="1.0.0"||x.next_epic_id!==1||!S(x.existing_epics_discovered,[]))||typeof x.last_scan!="string"||!Number.isFinite(Date.parse(x.last_scan)))throw new Error("planning-index-drift");const k=w.map(E=>F("sha256").update(m(a(t.workspacePath,E))).digest("hex")),I=()=>w.every((E,T)=>{try{return P(t.workspacePath,E),F("sha256").update(m(a(t.workspacePath,E))).digest("hex")===k[T]}catch{return!1}});return W(t,w,t.baseSha,s,I)}catch{throw new Error("private-execution-planning-diagnosis-admission-unverified")}}function Te(t,r,e,o,s,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(o)||!/^[a-f0-9]{64}$/.test(s)||!/^[a-f0-9]{64}$/.test(i))throw new Error("planning-research-binding-invalid");const n=".neocortex/state.json",d=".neocortex/planning/planning.json",l=`.neocortex/planning/epic-${e}`,c=`${l}/research.md`;if(P(t.sourceRoot,n),P(t.workspacePath,n),P(t.sourceRoot,d),P(t.workspacePath,d),P(t.sourceRoot,c),P(t.workspacePath,c),R(a(t.sourceRoot,n)).size>8*1024*1024||R(a(t.workspacePath,n)).size>8*1024*1024||R(a(t.sourceRoot,d)).size>128*1024||R(a(t.workspacePath,d)).size>128*1024)throw new Error("planning-research-source-size-invalid");const f=m(a(t.sourceRoot,n));if(F("sha256").update(f).digest("hex")!==i||!f.equals(m(a(t.workspacePath,n))))throw new Error("planning-research-state-drift");const h=JSON.parse(f.toString("utf8")),p=Kt(h,r,e);if(p.diagnosisReceiptId!==o||p.intakeRevision!==s)throw new Error("planning-research-predecessor-mismatch");const u=h.epics[e].createEpicPlanningPhysical.artifactDigests;for(const[O,U]of Object.entries({idea:`${l}/idea.json`,diagnosis:`${l}/diagnosis.md`,enrichment:`${l}/enriched-prompt.md`,index:d}))if(P(t.sourceRoot,U),F("sha256").update(m(a(t.sourceRoot,U))).digest("hex")!==u[O])throw new Error("planning-research-source-artifact-drift");try{throw R(a(t.sourceRoot,c)),new Error("planning-research-already-exists")}catch(O){if(O.code!=="ENOENT")throw O}const g=[c,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=R(a(t.workspacePath,c));if(!j.isFile()||j.isSymbolicLink()||j.size<64||j.size>256*1024)throw new Error("planning-research-document-invalid");const b=m(a(t.workspacePath,c),"utf8"),N=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(b.replace(/\r\n/g,`
5
+ `))?.[1],y=O=>{const U=N?.split(`
6
+ `).filter(v=>v.startsWith(`${O}:`))??[];return U.length===1?U[0].slice(O.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0};if(!N||y("epic_id")!==e||y("status")!=="completed"||!tt(y("step"),St)||!b.slice(N.length+8).trim())throw new Error("planning-research-document-identity-invalid");const A=JSON.parse(m(a(t.sourceRoot,d),"utf8")),x=JSON.parse(m(a(t.workspacePath,d),"utf8"));if(!A||typeof A!="object"||Array.isArray(A)||!x||typeof x!="object"||Array.isArray(x))throw new Error("planning-research-index-invalid");const Y=A,L=x,$=Y.epics,q=L.epics,C=$?.[e];if(!$||Array.isArray($)||!q||Array.isArray(q)||!C||Array.isArray(C)||C.id!==e||C.idea!==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={...Y,last_scan:L.last_scan,epics:{...$,[e]:z}};if(!S(L,V))throw new Error("planning-research-index-drift");const X=g.map(O=>F("sha256").update(m(a(t.workspacePath,O))).digest("hex")),Q=()=>g.every((O,U)=>{try{return P(t.workspacePath,O),F("sha256").update(m(a(t.workspacePath,O))).digest("hex")===X[U]}catch{return!1}});return W(t,g,t.baseSha,Rt(t.sourceRoot),Q)}catch{throw new Error("private-execution-planning-research-admission-unverified")}}function je(t,r,e,o,s,i,n){try{if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(r)||!/^P[1-9][0-9]{0,11}$/.test(e)||[o,s,i,n].some(v=>!/^[a-f0-9]{64}$/.test(v)))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 v of[d,l,`${c}/idea.json`,`${c}/diagnosis.md`,`${c}/enriched-prompt.md`,`${c}/research.md`]){P(t.sourceRoot,v),P(t.workspacePath,v);const D=m(a(t.sourceRoot,v));if(v!==l&&!D.equals(m(a(t.workspacePath,v)))||!D.equals(G(t.sourceRoot,["show",`HEAD:${v}`])))throw new Error("planning-generation-predecessor-uncommitted")}const h=m(a(t.sourceRoot,d));if(h.byteLength>8*1024*1024||F("sha256").update(h).digest("hex")!==n)throw new Error("planning-generation-state-drift");const p=JSON.parse(h.toString("utf8")),w=Zt(p,r,e);if(w.diagnosisReceiptId!==o||w.researchReceiptId!==s||w.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[v,D]of Object.entries(j)){const H=v==="research"?_.research:g[v];if(F("sha256").update(m(a(t.sourceRoot,D))).digest("hex")!==H)throw new Error("planning-generation-artifact-drift")}if(F("sha256").update(m(a(t.sourceRoot,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(v=>N.test(v)).sort((v,D)=>Number(N.exec(v)[1])-Number(N.exec(D)[1]));if(y.length<1||y.length>24||y.some((v,D)=>N.exec(v)[1]!==String(D+1).padStart(2,"0"))||b.paths.length!==y.length+2||b.paths.some(v=>v!==f&&v!==l&&!N.test(v)))throw new Error("planning-generation-write-scope-invalid");const A=[f,l,...y];for(const v of[f,...y]){P(t.sourceRoot,v),P(t.workspacePath,v);try{throw R(a(t.sourceRoot,v)),new Error("planning-generation-path-collision")}catch(H){if(H.code!=="ENOENT")throw H}const D=R(a(t.workspacePath,v));if(!D.isFile()||D.isSymbolicLink()||D.size<128||D.size>(v===f?512:128)*1024)throw new Error("planning-generation-document-invalid")}const x=(v,D)=>{const k=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(v.replace(/\r\n/g,`
7
7
  `))?.[1]?.split(`
8
- `).filter(I=>I.startsWith(`${D}:`))??[];return k.length===1?k[0].slice(D.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0},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}
8
+ `).filter(I=>I.startsWith(`${D}:`))??[];return k.length===1?k[0].slice(D.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0},Y=m(a(t.workspacePath,f),"utf8");if(x(Y,"id")!==e||x(Y,"stories_count")!==String(y.length)||!Y.includes("## Stories"))throw new Error("planning-generation-epic-invalid");for(const[v,D]of y.entries()){const H=m(a(t.workspacePath,D),"utf8"),k=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(H.replace(/\r\n/g,`
9
+ `))?.[1]??"";if(x(H,"id")!==`${e}.${String(v+1).padStart(2,"0")}`||x(H,"epic_id")!==e||/^\s*epic\s*:/m.test(k)||x(H,"status")!=="backlog"||!H.includes("## Acceptance Criteria")||!/\bGiven\b[\s\S]*\bWhen\b[\s\S]*\bThen\b/.test(H))throw new Error("planning-generation-story-invalid")}const L=JSON.parse(m(a(t.sourceRoot,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],St)||!S(z.output_files,{diagnosis:`${c}/diagnosis.md`,research:`${c}/research.md`})||typeof $.last_scan!="string"||!Number.isFinite(Date.parse($.last_scan))||typeof V.completed_at!="string"||!Number.isFinite(Date.parse(V.completed_at)))throw new Error("planning-generation-index-predecessor-invalid");const X=V.steps_completed?.[2];if(!tt(X,te))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(v=>F("sha256").update(m(a(t.workspacePath,v))).digest("hex")),U=()=>A.every((v,D)=>{try{return P(t.workspacePath,v),F("sha256").update(m(a(t.workspacePath,v))).digest("hex")===O[D]}catch{return!1}});return W(t,A,t.baseSha,Rt(t.sourceRoot),U)}catch{throw new Error("private-execution-planning-generation-admission-unverified")}}function Ne(t,r,e){try{if(!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e))throw new Error("story-id-invalid");const o=".neocortex/state.json";P(r.sourceRoot,o),P(r.workspacePath,o);const s=m(a(r.sourceRoot,o));if(!s.equals(m(a(r.workspacePath,o))))throw new Error("state-drift");const i=JSON.parse(s.toString("utf8")),n=i?.stories?.[e],d=n?.files_to_modify;if(i?.schema_version!==1||n?.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 w=/^---\r?\n([\s\S]{1,8192}?)\r?\n---(?:\r?\n|$)/.exec(h.toString("utf8"))?.[1]?.split(/\r?\n/).filter(u=>u.startsWith("id:"))??[];return w.length===1&&w[0].slice(3).trim().replace(/^(["'])(.*)\1$/,"$2")===e});if(c.length!==1)throw new Error("story-target-ambiguous");return`${t}
10
10
 
11
11
  Private story handoff (local only):
12
12
  ${JSON.stringify({storyId:e,storyPath:c[0],allowedPaths:[...l].sort()})}
13
13
  Work from this isolated checkout's current directory. Use the exact storyPath above for the delivered current step; do not use an unresolved story-file placeholder or infer a filename. Persist the current step's actual result in the declared files; a final chat response alone is not a saved candidate. Modify only allowedPaths and preserve story identity and the write set. Do not operate Git, change unrelated stories, grant root QA/checkpoint authority, or declare the story, epic or pipeline complete. If required inputs are unavailable, report failure without inventing evidence or completion.
14
- `}catch{throw new Error("private-execution-state-step-handoff-unverified")}}function 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}
14
+ `}catch{throw new Error("private-execution-state-step-handoff-unverified")}}function De(t,r){try{if(!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(r))throw new Error("story-id-invalid");const e=".neocortex/state.json";P(t.sourceRoot,e),P(t.workspacePath,e);const o=JSON.parse(m(a(t.sourceRoot,e),"utf8")),s=JSON.parse(m(a(t.workspacePath,e),"utf8"));if(!o||typeof o!="object"||Array.isArray(o)||!s||typeof s!="object"||Array.isArray(s))throw new Error("state-invalid");const i=o,n=s,d=i.stories,l=n.stories,c=d?.[r],f=l?.[r],h=c?.files_to_modify;if(i.schema_version!==1||n.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(x=>typeof x!="string"||!rt(x)||x.length>1024)||new Set(h).size!==h.length||!S(f.files_to_modify,h))throw new Error("write-set-invalid");const{[r]:p,...w}=d,{[r]:u,...g}=l,{stories:_,last_updated:j,...b}=i,{stories:N,last_updated:y,...A}=n;if(!S(g,w)||!S(A,b))throw new Error("state-unrelated-drift");return W(t,[...h].sort(),t.baseSha)}catch{throw new Error("private-execution-state-step-admission-unverified")}}function Fe(t,r,e){if(r==="chaos-plan"&&e==="chaos-quarterly-v1")try{const s=new Date,i=`Q${Math.floor(s.getUTCMonth()/3)+1}-${s.getUTCFullYear()}`,n=M(B(t.workspacePath,!0)).paths,d=`tools/chaos/${i}-plan.md`,l=`.neocortex/chaos-history/${i}.md`,c=n.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(!n.includes(d)||!n.includes(l)||c.length<5||c.length>10||n.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 n)if(P(t.workspacePath,u),R(a(t.workspacePath,u)).size===0)throw new Error("chaos-empty-artifact");const h=m(a(t.workspacePath,l),"utf8");if(!h.includes(i)||!/\bPLANNED\b/.test(h))throw new Error("chaos-history-invalid");const w=G(t.workspacePath,["ls-tree","-z","HEAD","--",l]).length>0?G(t.workspacePath,["show",`HEAD:${l}`]).toString("utf8"):"";if(w&&!h.startsWith(w))throw new Error("chaos-history-not-append-only");return W(t,n,t.baseSha)}catch{throw new Error("private-execution-project-step-admission-unverified")}const o=r==="sync-openapi"&&e==="sync-openapi-contract-v1"?["docs/architecture/api-contracts.md","docs/api/openapi.yaml"]:r==="tech-debt"&&e==="tech-debt-registry-v1"?[".neocortex/tech-debt-registry.json"]:void 0;if(!o)throw new Error("private-execution-project-step-admission-unverified");try{if(r==="tech-debt"){const s=".neocortex/tech-debt-registry.json";P(t.workspacePath,s);const i=JSON.parse(m(a(t.workspacePath,s),"utf8"));if(!i||typeof i!="object"||Array.isArray(i))throw new Error("registry-invalid");const n=i;if(n.schema_version!==2||n.version!==void 0&&n.version!==2||!Array.isArray(n.items))throw new Error("registry-invalid")}return W(t,o,t.baseSha)}catch{throw new Error("private-execution-project-step-admission-unverified")}}function Nt(t,r){const e=t==="arch-prd"&&r==="arch-prd-docs-v1"?["docs/architecture/prd.md","docs/architecture/product-experience.md"]:t==="arch-architecture"&&r==="arch-architecture-doc-v1"?["docs/architecture/architecture.md"]:t==="arch-fitness-functions"&&r==="arch-fitness-tools-v1"?["tools/architecture/dependency-cruiser.config.js","tools/architecture/archunit-test.ts","tools/architecture/.eslintrc.boundaries.js"]:t==="arch-api-contracts"&&r==="arch-api-contracts-docs-v1"?["docs/architecture/api-contracts.md","docs/api/openapi.yaml"]:t==="arch-api-integrations"&&r==="arch-api-integrations-doc-v1"?["docs/architecture/api-integrations.md"]:t==="arch-database"&&r==="arch-database-doc-v1"?["docs/architecture/database-schema.md"]:t==="arch-security"&&r==="arch-security-doc-v1"?["docs/architecture/cyber-security.md"]:t==="arch-design-system"&&r==="arch-design-system-doc-v1"?["docs/architecture/atomic-design-system.md"]:t==="arch-performance"&&r==="arch-performance-doc-v1"?["docs/architecture/performance-strategy.md"]:t==="arch-testing"&&r==="arch-testing-doc-v1"?["docs/architecture/testing-strategy.md"]:t==="arch-infrastructure"&&r==="arch-infrastructure-doc-v1"?["docs/architecture/infrastructure-deploy.md"]:t==="arch-review"&&r==="arch-review-doc-v1"?["docs/architecture/review-consolidation.md"]:t==="update-memory"&&r==="arch-memory-canonical-v1"?["NEOCORTEX.md"]:null;return e===null?null:Object.freeze(e)}function Be(t,r,e,o="all"){const s=Nt(r,e);if(!s)throw new Error("private-execution-architecture-admission-unverified");return`${t}
15
15
 
16
16
  Private architecture handoff (local only):
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.
17
+ ${JSON.stringify({allowedPaths:s})}
18
+ ${o==="non-ui"?`The server admitted a signed non-UI scope for this snapshot. Preserve the backend-only scope: design-system and UX phases are not applicable. Do not require or generate interface artifacts.
19
19
  `:""}Write exactly the listed nonempty artifacts inside this isolated clone. Existing compliant listed artifacts may remain unchanged; all listed artifacts must exist after execution. Place any necessary scope notes inside those artifacts. Do not edit README, package files, other documents, state, Git, QA records or configuration outside the listed paths. Do not install dependencies, use network, deploy or continue to another stage. Preserve existing arch:keep blocks byte-for-byte. Do not add new arch:keep markers. For managed memory, preserve all bytes outside its existing managed block. Root independently reviews artifacts and owns continuation, Git and acceptance.
20
- `}function 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(`
20
+ `}function Ce(t,r,e,o,s){const i=Nt(r,e);if(!i||!/^P[1-9][0-9]{0,11}$/.test(o)||!/^[a-f0-9]{64}$/.test(s))throw new Error("private-execution-architecture-admission-unverified");try{P(t.workspacePath,".neocortex/state.json");const n=JSON.parse(m(a(t.workspacePath,".neocortex/state.json"),"utf8"));if(!n||typeof n!="object"||Array.isArray(n))throw new Error("state-invalid");const d=n,c=d.archPlan?.execution,f=d.epics;if(!c||c.currentStageCommand!==r||c.targetEpicId!==o||c.graphRevision!==s||!f||!Object.hasOwn(f,o))throw new Error("state-binding-mismatch");if(r==="update-memory"){if(c.continuationState!=="delegate"||c.reviewDecision?.decision!=="approved")throw new Error("memory-root-review-missing");const h="NEOCORTEX.md";if(!M(B(t.workspacePath,!0)).paths.includes(h))throw new Error("memory-effect-missing");P(t.sourceRoot,h),P(t.workspacePath,h);const p=m(a(t.sourceRoot,h),"utf8"),w=m(a(t.workspacePath,h),"utf8"),u="<!-- NEOCORTEX-MEMORY-START -->",g="<!-- NEOCORTEX-MEMORY-END -->",_=y=>{if(y.split(u).length!==2||y.split(g).length!==2||y.indexOf(u)>=y.indexOf(g))throw new Error("memory-markers-invalid");const A=y.indexOf(u)+u.length,x=y.indexOf(g);return{before:y.slice(0,A),body:y.slice(A,x),after:y.slice(x)}},j=_(p),b=_(w);if(j.before!==b.before||j.after!==b.after||j.body===b.body||Buffer.byteLength(w,"utf8")>32768||w.split(`
21
21
  `).length>240)throw new Error("memory-managed-block-invalid");const N=new Set(j.body.split(`
22
22
  `));for(const y of b.body.split(`
23
- `))N.has(y)||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};
23
+ `))N.has(y)||Wt(y)}if(r==="arch-prd"){const h="docs/architecture/prd.md";if(!M(B(t.workspacePath,!0)).paths.includes(h))throw new Error("prd-effect-missing");if(P(t.workspacePath,h),R(a(t.workspacePath,h)).size===0)throw new Error("prd-empty")}if(r==="arch-api-contracts"||r==="arch-fitness-functions"||r==="arch-api-integrations"||r==="arch-database"||r==="arch-security"||r==="arch-design-system"||r==="arch-performance"||r==="arch-testing"||r==="arch-infrastructure"||r==="arch-review"){const h=M(B(t.workspacePath,!0)).paths;for(const 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),R(a(t.workspacePath,p)).size===0)throw new Error("architecture-required-effect-empty");if(r==="arch-fitness-functions"){P(t.sourceRoot,p);const w=nt(a(t.sourceRoot,p))?m(a(t.sourceRoot,p),"utf8"):"",u=m(a(t.workspacePath,p),"utf8"),g=$t(w),_=$t(u);if(!S(_,g))throw new Error("architecture-keep-marker-changed")}}}return W(t,i,t.baseSha)}catch{throw new Error("private-execution-architecture-admission-unverified")}}function ze(t,r,e,o){try{if(!/^P[1-9][0-9]{0,11}$/.test(r)||!/^[a-f0-9]{64}$/.test(e)||o.schemaVersion!==1||o.targetEpicId!==r)throw new Error("binding-invalid");const s=Mt(t.sourceRoot,r),i=Jt(t.workspacePath,r);if(!S(s,o)||!S(i,o))throw new Error("write-set-invalid");P(t.workspacePath,".neocortex/state.json");const n=JSON.parse(m(a(t.workspacePath,".neocortex/state.json"),"utf8"));if(!n||typeof n!="object"||Array.isArray(n))throw new Error("state-invalid");const d=n,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!==o.pathCount||h.some(p=>!o.paths.includes(p)))throw new Error("agent-path-unclaimed");for(const p of o.paths){P(t.sourceRoot,p),P(t.workspacePath,p);const w=R(a(t.workspacePath,p));if(!w.isFile()||w.isSymbolicLink()||w.size<1)throw new Error("effect-empty");const u=new TextDecoder("utf-8",{fatal:!0}).decode(m(a(t.workspacePath,p)));if(!u.trim()||u.includes("\0"))throw new Error("effect-invalid")}return qt(t.workspacePath,o),W(t,o.paths,t.baseSha)}catch{throw new Error("private-execution-ux-admission-unverified")}}function Le(t,r,e,o,s,i){try{if(!/^P[1-9][0-9]{0,11}$/.test(r)||!/^[a-f0-9]{64}$/.test(e)||o.targetEpicId!==r||o.graphRevision!==e||s.schemaVersion!==1)throw new Error("binding-invalid");const n=Ht(t.sourceRoot);if(!n||!S(n.receipt,o))throw new Error("answers-invalid");const d=xt(t.sourceRoot,n.answers.generateProvider),l=xt(t.workspacePath,n.answers.generateProvider);if(d.outcome!=="ready"||l.outcome!=="ready"||!S(d.writeSet,s)||!S(l.writeSet,s))throw new Error("write-set-invalid");const c=M(B(t.workspacePath,!0)).paths;if(c.some(u=>!s.paths.includes(u)))throw new Error("agent-path-unclaimed");let f=0,h=0;for(const u of s.paths){if(P(t.sourceRoot,u),nt(a(t.sourceRoot,u))||!c.includes(u))throw new Error("effect-missing-or-overwrite");P(t.workspacePath,u);const g=R(a(t.workspacePath,u));if(!g.isFile()||g.size<1)throw new Error("effect-empty");const _=new TextDecoder("utf-8",{fatal:!0}).decode(m(a(t.workspacePath,u))),j=s.interactions.find(N=>N.filePath===u);if(u!==s.providerPath&&!j)throw new Error("private-execution-pact-interaction-missing");const b=Gt(u,_,n.answers.brokerUrl,j,t.workspacePath,n.answers.matchersAggressive);b.consumerBinding==="app-import-candidate"&&f++,b.consumerBinding==="mock-only-scaffold"&&h++}let p=s.paths;if(i){const u=Xt(t.sourceRoot,n.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),Vt(t.workspacePath,n.answers.generateProvider).outcome!=="manifest-aligned")throw new Error("toolchain-candidate-invalid");p=[...s.paths,"package.json","package-lock.json"]}const w=W(t,p,t.baseSha);return Object.freeze({...w,consumerBindingCandidateCount:f,consumerScaffoldCount:h})}catch{throw new Error("private-execution-pact-admission-unverified")}}function He(t,r,e,o=new Date().toISOString()){try{const s=At(t.sourceRoot,r);if(!S(s,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 n=new Map;for(const h of e.aggregates){P(t.sourceRoot,h.testFile),P(t.workspacePath,h.testFile);const p=R(a(t.workspacePath,h.testFile));if(!p.isFile()||p.isSymbolicLink()||p.size<1||p.size>Z)throw new Error("test-invalid");const w=m(a(t.workspacePath,h.testFile)),u=new TextDecoder("utf-8",{fatal:!0}).decode(w),g=e.language==="typescript"?(u.match(/\b(?:it|test)\s*\(/g)??[]).length:(u.match(/^def\s+test_[A-Za-z0-9_]+\s*\(/gm)??[]).length;if(!u.trim()||u.includes("\0")||g<h.invariantCount||/\b(?:it|test|describe)\s*\.\s*(?:skip|todo|only)\s*\(/.test(u)||!u.includes(String(e.numRuns)))throw new Error("test-invalid");e.language==="typescript"&&kt({source:u,testFile:h.testFile,implementationFile:h.implementationFile,invariantCount:h.invariantCount,numRuns:e.numRuns}),n.set(h.testFile,F("sha256").update(w).digest("hex"))}P(t.sourceRoot,e.prdPath),P(t.workspacePath,e.prdPath);const d=m(a(t.workspacePath,e.prdPath)),l=new TextDecoder("utf-8",{fatal:!0}).decode(d),c=Qt(l,e,o);mt(a(t.workspacePath,e.prdPath),c);const f=F("sha256").update(c).digest("hex");return W(t,[...e.writeSet,e.prdPath],t.baseSha,void 0,()=>{try{return!S(At(t.sourceRoot,r),e)||e.aggregates.some(h=>!pt(t.sourceRoot,t.workspacePath,h.implementationFile))||F("sha256").update(m(a(t.workspacePath,e.prdPath))).digest("hex")!==f?!1:[...n].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{Ce as admitPrivateArchitectureStageWorkspace,$e as admitPrivateEpicClaimWorkspace,je as admitPrivateGenerateEpicWorkspace,Oe as admitPrivateIdeaDiagnosisWorkspace,Te as admitPrivateIdeaResearchWorkspace,Le as admitPrivatePactWorkspace,Fe as admitPrivateProjectStepWorkspace,He as admitPrivatePropertyTestWorkspace,De as admitPrivateStateBoundStepWorkspace,ze as admitPrivateUxWorkspace,Se as admitPrivateYoloFrozenWorkspace,Be as appendPrivateArchitectureHandoff,Ne as appendPrivateStateBoundStepHandoff,Nt as privateArchitectureStagePaths,xe as privateYoloSourceFileMatchesSnapshot,Ae as verifyPrivateYoloRejectedCandidateOrigin,Re as verifyPrivateYoloSnapshotBoundary};
@@ -1,3 +1,4 @@
1
+ import { type Stats } from 'node:fs';
1
2
  export interface PrivateYoloIsolatedWorkspaceV1 {
2
3
  readonly schemaVersion: 1;
3
4
  readonly sourceRoot: string;
@@ -10,6 +11,20 @@ export interface PrivateProjectStepBaselineV1 {
10
11
  readonly stateSha256: string;
11
12
  }
12
13
  export declare const PRIVATE_EPIC_PENDING_SIDECAR = ".neocortex/pending-epic-claims.json";
14
+ /** P230.08: test/host seams; the defaults are the running process and its user profile. */
15
+ export interface PrivateIsolatedWorkspaceOptionsV1 {
16
+ readonly platform?: string;
17
+ readonly userProfileRoot?: string;
18
+ }
19
+ /**
20
+ * P230.08: admission-side view of the same platform rule. A prepared workspace
21
+ * is only re-inspected on linux/darwin (POSIX, getuid required) or win32.
22
+ */
23
+ export declare function isPrivateIsolatedWorkspacePlatform(platform?: string): boolean;
24
+ /** POSIX: no group/other bits on the workspace directory. win32 mode bits carry no owner meaning. */
25
+ export declare function privateIsolatedWorkspaceModeVerified(entry: Stats, platform?: string): boolean;
26
+ /** Owner-private pending create-epic sidecar under the same per-platform rule as preparation. */
27
+ export declare function privatePendingEpicSidecarVerified(root: string, platform?: string): boolean;
13
28
  /** Pin the request's physical source before projecting a private project-step snapshot. */
14
29
  export declare function capturePrivateProjectStepBaseline(projectRoot: string): PrivateProjectStepBaselineV1;
15
30
  /** A later commit or state rewrite cannot execute against an older server lease. */
@@ -19,4 +34,4 @@ export declare function assertPrivateProjectStepBaseline(workspace: PrivateYoloI
19
34
  * The caller must retain the workspace until its bytes are independently
20
35
  * admitted into the root; this function never stages, commits, or deletes it.
21
36
  */
22
- export declare function preparePrivateYoloIsolatedWorkspace(projectRoot: string, workspaceParent: string, allowPendingEpicSidecar?: boolean): PrivateYoloIsolatedWorkspaceV1;
37
+ export declare function preparePrivateYoloIsolatedWorkspace(projectRoot: string, workspaceParent: string, allowPendingEpicSidecar?: boolean, options?: PrivateIsolatedWorkspaceOptionsV1): PrivateYoloIsolatedWorkspaceV1;
@@ -1 +1 @@
1
- import{execFileSync as v}from"node:child_process";import{createHash as S}from"node:crypto";import{chmodSync as I,existsSync as D,lstatSync as h,mkdtempSync as _,readFileSync as w,realpathSync as l}from"node:fs";import{isAbsolute as E,join as u,resolve as d}from"node:path";const y=".neocortex/pending-epic-claims.json";function p(e,t){const s={...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 s[r];return v("git",[...t],{cwd:e,env:s,stdio:["ignore","pipe","pipe"],timeout:3e4,maxBuffer:16*1024*1024})}function c(e,t){return p(e,t).toString("utf8").trim()}function m(e,t,s,r=!1){const n=p(e,["status","--porcelain=v1","-z","--untracked-files=all"]).toString("utf8");let a=!r;if(r)try{const i=h(u(e,".neocortex")),o=h(u(e,y));a=i.isDirectory()&&!i.isSymbolicLink()&&i.uid===process.getuid?.()&&(i.mode&18)===0&&o.isFile()&&!o.isSymbolicLink()&&o.uid===process.getuid?.()&&(o.mode&63)===0&&o.size>0&&o.size<=128*1024}catch{a=!1}return c(e,["rev-parse","HEAD"])===t&&c(e,["symbolic-ref","--quiet","--short","HEAD"])===s&&a&&(n.length===0||r&&n===`?? ${y}\0`)}function f(e){const t=u(e,".neocortex","state.json"),s=h(t);if(!s.isFile()||s.isSymbolicLink())throw new Error("state-invalid");return S("sha256").update(w(t)).digest("hex")}function g(e){try{const t=c(e,["rev-parse","--verify","HEAD"]);if(!/^[a-f0-9]{40,64}$/.test(t))throw new Error("head-invalid");return Object.freeze({headSha:t,stateSha256:f(e)})}catch{throw new Error("private-execution-project-snapshot-unverified")}}function b(e,t){try{if(e.baseSha!==t.headSha||c(e.sourceRoot,["rev-parse","--verify","HEAD"])!==t.headSha||f(e.sourceRoot)!==t.stateSha256||f(e.workspacePath)!==t.stateSha256)throw new Error("snapshot-mismatch")}catch{throw new Error("private-execution-project-snapshot-unverified")}}function C(e,t,s=!1){let r,n;try{if(process.platform!=="linux"||typeof process.getuid!="function"||!E(e)||!E(t))throw new Error("path-invalid");if(r=d(e),n=d(t),l(r)!==r||!h(r).isDirectory()||l(n)!==n||!h(n).isDirectory()||h(n).uid!==process.getuid()||(h(n).mode&18)!==0||c(r,["rev-parse","--show-toplevel"])!==r)throw new Error("path-invalid");const a=c(r,["rev-parse","HEAD"]),i=c(r,["symbolic-ref","--quiet","--short","HEAD"]);if(!/^[a-f0-9]{40,64}$/.test(a)||!i||!m(r,a,i,s))throw new Error("source-dirty");const o=_(u(n,"p222-private-yolo-"));if(I(o,448),p(o,["init","-q"]),p(o,["fetch","-q","--no-tags","--depth=1",r,a]),p(o,["checkout","-q","-b",i,"FETCH_HEAD"]),!m(r,a,i,s)||c(o,["rev-parse","HEAD"])!==a||c(o,["symbolic-ref","--quiet","--short","HEAD"])!==i||p(o,["status","--porcelain=v1","-z","--untracked-files=all"]).byteLength!==0||D(u(o,".git","objects","info","alternates")))throw new Error("physical-mismatch");return Object.freeze({schemaVersion:1,sourceRoot:r,workspacePath:o,baseSha:a,executionBranch:i})}catch{throw new Error("private-execution-isolated-workspace-unverified")}}export{y as PRIVATE_EPIC_PENDING_SIDECAR,b as assertPrivateProjectStepBaseline,g as capturePrivateProjectStepBaseline,C as preparePrivateYoloIsolatedWorkspace};
1
+ import{execFileSync as R}from"node:child_process";import{createHash as T}from"node:crypto";import{chmodSync as A,existsSync as C,lstatSync as f,mkdtempSync as g,readFileSync as L,realpathSync as b}from"node:fs";import{homedir as G}from"node:os";import{isAbsolute as m,join as d,relative as H,resolve as E}from"node:path";const S=".neocortex/pending-epic-claims.json",N=["/var","/tmp","/etc"],k=128*1024;function s(){throw new Error("path-invalid")}function O(e){return N.some(t=>e===t||e.startsWith(`${t}/`))?`/private${e}`:e}function v(e,t){const r=b(e);return r===e||t==="darwin"&&r===O(e)||t==="win32"&&r.toLowerCase()===e.toLowerCase()?r:s()}function j(e){const t=e.platform??process.platform;if(t==="linux"||t==="darwin")return typeof process.getuid!="function"&&s(),{platform:t};if(t==="win32"){const r=e.userProfileRoot??G();(typeof r!="string"||!m(r))&&s();const o=v(E(r),t);return f(o).isDirectory()||s(),{platform:t,profileRoot:o}}return s()}function y(e,t,r){return t.platform==="win32"?!0:e.uid===process.getuid?.()&&(e.mode&r)===0}function q(e,t){if(t.platform!=="win32")return!0;const r=H(t.profileRoot.toLowerCase(),e.toLowerCase());return r!==""&&!r.startsWith("..")&&!m(r)}function B(e,t){const r=f(e);(!r.isDirectory()||r.isSymbolicLink())&&s();const o=v(e,t.platform);return(!y(f(o),t,18)||!q(o,t))&&s(),o}function I(e){return e==="linux"||e==="darwin"||e==="win32"}function D(e=process.platform){return I(e)?e==="win32"||typeof process.getuid=="function":!1}function $(e,t=process.platform){return D(t)?t==="win32"||(e.mode&63)===0:!1}function Y(e,t=process.platform){return!D(t)||!I(t)?!1:_(e,{platform:t})}function _(e,t){try{const r=f(d(e,".neocortex")),o=f(d(e,S));return r.isDirectory()&&!r.isSymbolicLink()&&y(r,t,18)&&o.isFile()&&!o.isSymbolicLink()&&y(o,t,63)&&o.size>0&&o.size<=k}catch{return!1}}function l(e,t){const r={...process.env};for(const o of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete r[o];return R("git",[...t],{cwd:e,env:r,stdio:["ignore","pipe","pipe"],timeout:3e4,maxBuffer:16*1024*1024})}function c(e,t){return l(e,t).toString("utf8").trim()}function P(e,t,r,o,a=!1){const h=l(e,["status","--porcelain=v1","-z","--untracked-files=all"]).toString("utf8"),i=!a||_(e,o);return c(e,["rev-parse","HEAD"])===t&&c(e,["symbolic-ref","--quiet","--short","HEAD"])===r&&i&&(h.length===0||a&&h===`?? ${S}\0`)}function w(e){const t=d(e,".neocortex","state.json"),r=f(t);if(!r.isFile()||r.isSymbolicLink())throw new Error("state-invalid");return T("sha256").update(L(t)).digest("hex")}function J(e){try{const t=c(e,["rev-parse","--verify","HEAD"]);if(!/^[a-f0-9]{40,64}$/.test(t))throw new Error("head-invalid");return Object.freeze({headSha:t,stateSha256:w(e)})}catch{throw new Error("private-execution-project-snapshot-unverified")}}function K(e,t){try{if(e.baseSha!==t.headSha||c(e.sourceRoot,["rev-parse","--verify","HEAD"])!==t.headSha||w(e.sourceRoot)!==t.stateSha256||w(e.workspacePath)!==t.stateSha256)throw new Error("snapshot-mismatch")}catch{throw new Error("private-execution-project-snapshot-unverified")}}function X(e,t,r=!1,o={}){try{const a=j(o);(!m(e)||!m(t))&&s();const h=E(e);f(h).isDirectory()||s();const i=v(h,a.platform),x=B(E(t),a);c(i,["rev-parse","--show-toplevel"])!==i&&s();const u=c(i,["rev-parse","HEAD"]),p=c(i,["symbolic-ref","--quiet","--short","HEAD"]);if(!/^[a-f0-9]{40,64}$/.test(u)||!p||!P(i,u,p,a,r))throw new Error("source-dirty");const n=g(d(x,"p222-private-yolo-"));if(a.platform!=="win32"&&(A(n,448),(f(n).mode&511)!==448))throw new Error("physical-mismatch");if(l(n,["init","-q"]),l(n,["fetch","-q","--no-tags","--depth=1",i,u]),l(n,["checkout","-q","-b",p,"FETCH_HEAD"]),!P(i,u,p,a,r)||c(n,["rev-parse","HEAD"])!==u||c(n,["symbolic-ref","--quiet","--short","HEAD"])!==p||l(n,["status","--porcelain=v1","-z","--untracked-files=all"]).byteLength!==0||C(d(n,".git","objects","info","alternates")))throw new Error("physical-mismatch");return Object.freeze({schemaVersion:1,sourceRoot:i,workspacePath:n,baseSha:u,executionBranch:p})}catch{throw new Error("private-execution-isolated-workspace-unverified")}}export{S as PRIVATE_EPIC_PENDING_SIDECAR,K as assertPrivateProjectStepBaseline,J as capturePrivateProjectStepBaseline,D as isPrivateIsolatedWorkspacePlatform,X as preparePrivateYoloIsolatedWorkspace,$ as privateIsolatedWorkspaceModeVerified,Y as privatePendingEpicSidecarVerified};
@@ -1,10 +1,5 @@
1
- import type { EpicAggregateQaReceipt } from '../../../../shared/dist/yoloop/epic-terminal-git.js';
2
1
  import type { EpicTerminalGitAdapter } from './epic-terminal-git-runner.js';
3
- interface JsonState {
4
- readonly epics?: Record<string, Record<string, unknown>>;
5
- readonly stories?: Record<string, Record<string, unknown>>;
6
- [key: string]: unknown;
7
- }
2
+ export { physicallyValidHeadReconciliation, publicLifecycleEvidenceCause } from '../../git/epic-lifecycle-evidence.js';
8
3
  export interface CliEpicTerminalGitAdapterOptions {
9
4
  /** Test observer after canonical P205; cannot replace the command or result. */
10
5
  readonly aggregateQaRunner?: (input: {
@@ -27,19 +22,3 @@ export declare function gitNetworkExecOptions(baseEnv: NodeJS.ProcessEnv): {
27
22
  readonly killSignal: 'SIGKILL';
28
23
  readonly env: NodeJS.ProcessEnv;
29
24
  };
30
- export declare function publicLifecycleEvidenceCause(error: unknown): string | undefined;
31
- /** Exported for P227.12 revalidation tests; production callers stay internal. */
32
- export declare function physicallyValidHeadReconciliation(input: {
33
- readonly projectRoot: string;
34
- readonly git: (...args: readonly string[]) => Promise<string>;
35
- readonly state: JsonState;
36
- readonly epic: Record<string, unknown>;
37
- readonly epicId: string;
38
- readonly executionBranch: string;
39
- readonly originBranch: string;
40
- readonly executionHeadSha: string;
41
- readonly graphRevision: string;
42
- readonly aggregateQaReceipt: EpicAggregateQaReceipt;
43
- readonly nowIso: string;
44
- }): Promise<boolean>;
45
- export {};