@ornexus/neocortex 4.66.0 → 4.66.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/release-source.json +1 -1
- package/dist/sbom.cdx.json +1206 -1193
- package/docs/install/linux-global-install.md +21 -1
- package/install.js +22 -28
- package/install.ps1 +19 -24
- package/install.sh +26 -30
- package/package.json +2 -2
- package/packages/client/dist/commands/doctor.d.ts +26 -1
- package/packages/client/dist/commands/doctor.js +2 -2
- package/packages/client/dist/commands/invoke.d.ts +149 -1
- package/packages/client/dist/commands/invoke.js +88 -83
- package/packages/client/dist/commands/planning-qa.d.ts +57 -0
- package/packages/client/dist/commands/planning-qa.js +1 -1
- package/packages/client/dist/commands/story-checkpoint.d.ts +2 -0
- package/packages/client/dist/commands/story-checkpoint.js +1 -1
- package/packages/client/dist/commands/story-worktree.d.ts +1 -1
- package/packages/client/dist/commands/story-worktree.js +1 -1
- package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +51 -0
- package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -3
- package/packages/client/dist/git/epic-lifecycle-evidence.d.ts +184 -0
- package/packages/client/dist/git/epic-lifecycle-evidence.js +6 -0
- package/packages/client/dist/git/git-lifecycle-store.d.ts +9 -0
- package/packages/client/dist/git/git-lifecycle-store.js +9 -8
- package/packages/client/dist/git/story-worktree-cleanup.js +1 -1
- package/packages/client/dist/git/story-worktree-integration.js +3 -3
- package/packages/client/dist/git/story-worktree-manager.d.ts +39 -0
- package/packages/client/dist/git/story-worktree-manager.js +3 -3
- package/packages/client/dist/git/story-write-set-extension.d.ts +62 -0
- package/packages/client/dist/git/story-write-set-extension.js +1 -1
- package/packages/client/dist/private-execution/codex-executor.d.ts +13 -0
- package/packages/client/dist/private-execution/codex-executor.js +4 -4
- package/packages/client/dist/private-execution/harness-adapters/antigravity.d.ts +9 -0
- package/packages/client/dist/private-execution/harness-adapters/antigravity.js +1 -0
- package/packages/client/dist/private-execution/harness-adapters/claude-code.d.ts +8 -0
- package/packages/client/dist/private-execution/harness-adapters/claude-code.js +1 -0
- package/packages/client/dist/private-execution/harness-adapters/codex.d.ts +7 -0
- package/packages/client/dist/private-execution/harness-adapters/codex.js +1 -0
- package/packages/client/dist/private-execution/harness-adapters/copilot-cli.d.ts +8 -0
- package/packages/client/dist/private-execution/harness-adapters/copilot-cli.js +1 -0
- package/packages/client/dist/private-execution/harness-adapters/cursor.d.ts +9 -0
- package/packages/client/dist/private-execution/harness-adapters/cursor.js +1 -0
- package/packages/client/dist/private-execution/harness-adapters/deepseek.d.ts +9 -0
- package/packages/client/dist/private-execution/harness-adapters/deepseek.js +1 -0
- package/packages/client/dist/private-execution/harness-adapters/gemini.d.ts +8 -0
- package/packages/client/dist/private-execution/harness-adapters/gemini.js +1 -0
- package/packages/client/dist/private-execution/harness-adapters/grok.d.ts +9 -0
- package/packages/client/dist/private-execution/harness-adapters/grok.js +1 -0
- package/packages/client/dist/private-execution/harness-adapters/index.d.ts +73 -0
- package/packages/client/dist/private-execution/harness-adapters/index.js +1 -0
- package/packages/client/dist/private-execution/harness-adapters/kimi.d.ts +9 -0
- package/packages/client/dist/private-execution/harness-adapters/kimi.js +1 -0
- package/packages/client/dist/private-execution/harness-adapters/openclaw.d.ts +9 -0
- package/packages/client/dist/private-execution/harness-adapters/openclaw.js +1 -0
- package/packages/client/dist/private-execution/harness-adapters/opencode.d.ts +7 -0
- package/packages/client/dist/private-execution/harness-adapters/opencode.js +1 -0
- package/packages/client/dist/private-execution/harness-ephemeral-home.d.ts +19 -0
- package/packages/client/dist/private-execution/harness-ephemeral-home.js +1 -0
- package/packages/client/dist/private-execution/harness-executor.d.ts +79 -0
- package/packages/client/dist/private-execution/harness-executor.js +1 -0
- package/packages/client/dist/private-execution/harness-process.d.ts +43 -0
- package/packages/client/dist/private-execution/harness-process.js +1 -0
- package/packages/client/dist/private-execution/isolated-admission.js +12 -12
- package/packages/client/dist/private-execution/isolated-workspace.d.ts +16 -1
- package/packages/client/dist/private-execution/isolated-workspace.js +1 -1
- package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.d.ts +2 -3
- package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +7 -4
- package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +1 -22
- package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +6 -10
- package/packages/client/dist/state/project-state-snapshot.d.ts +10 -0
- package/packages/client/dist/state/project-state-snapshot.js +1 -1
- package/packages/client/dist/state/structural-dag-projection.d.ts +26 -0
- package/packages/client/dist/state/structural-dag-projection.js +1 -1
- package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +67 -0
- package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1
- package/packages/shared/dist/compatibility/index.js +28 -0
- package/targets-stubs/antigravity/gemini.md +1 -1
- package/targets-stubs/antigravity/skill/SKILL.md +1 -1
- package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex-root.md +2 -2
- package/targets-stubs/claude-code/neocortex-sentinel.md +1 -1
- package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex.md +2 -2
- package/targets-stubs/codex/AGENTS.md +1 -1
- package/targets-stubs/cursor/agent.md +2 -2
- package/targets-stubs/gemini-cli/agent.md +2 -2
- package/targets-stubs/gemini-cli/agents/neocortex.md +2 -2
- package/targets-stubs/grok/SKILL.md +3 -3
- package/targets-stubs/grok/agents/{neocortex.md → neocortex-sentinel.md} +2 -2
- package/targets-stubs/grok/install-grok.sh +45 -8
- package/targets-stubs/lib/managed-config-merge.js +21 -1
- package/targets-stubs/lib/mcp-merge.js +18 -7
- package/targets-stubs/opencode/neocortex-root.md +1 -1
- package/targets-stubs/opencode/neocortex.md +1 -1
- 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
|
|
2
|
-
`)])));if(p.byteLength===0||p.byteLength>Z||!B(t.workspacePath,!0).equals(d)||
|
|
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)&<(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(
|
|
5
|
-
`))?.[1],y=O=>{const
|
|
6
|
-
`).filter(
|
|
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},
|
|
9
|
-
`))?.[1]??"";if(
|
|
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
|
|
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:
|
|
18
|
-
${
|
|
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
|
|
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)||
|
|
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
|
|
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};
|
|
@@ -11,9 +11,8 @@ export interface PlanningSealOptions {
|
|
|
11
11
|
readonly trustedKeys?: readonly PlanningStepBindingTrustedKey[];
|
|
12
12
|
}
|
|
13
13
|
/**
|
|
14
|
-
* Pinned production keyring.
|
|
15
|
-
* server
|
|
16
|
-
* `p228-06-step-binding-production-key`); until then every seal fails closed.
|
|
14
|
+
* Pinned production keyring. The private half is operator-owned and remains on
|
|
15
|
+
* the OCI server; clients receive only this public trust anchor.
|
|
17
16
|
*/
|
|
18
17
|
export declare const PLANNING_STEP_BINDING_PRODUCTION_KEYS: readonly PlanningStepBindingTrustedKey[];
|
|
19
18
|
/**
|
|
@@ -1,5 +1,8 @@
|
|
|
1
|
-
import{execFileSync as
|
|
1
|
+
import{execFileSync as $,spawnSync as on}from"node:child_process";import{createHash as dn,createPublicKey as pn,randomUUID as gn,verify as fn}from"node:crypto";import{closeSync as j,fsyncSync as R,lstatSync as w,mkdirSync as ln,openSync as A,readFileSync as L,realpathSync as H,renameSync as hn,unlinkSync as G,writeFileSync as J}from"node:fs";import{isAbsolute as mn,join as u,resolve as N}from"node:path";import{isDeepStrictEqual as b}from"node:util";import{canonicalPlanningIntake as un,createPlanningReceiptV1 as T,planningIntakeRevision as M,preparePlanningIntake as Y,projectDiagnosedEpicState as Q}from"../../../shared/dist/planning/diagnosis-state.js";const S=/^[a-f0-9]{64}$/,yn=/^P[1-9][0-9]{0,11}$/,In=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,B=["idea","diagnosis","enrichment","index"],F="acd455ed0e39d98b90fb57391db75e366e4c5604db043e03a89a20e33d643c3c",Sn="81f50aaa801c1660eabe46e645501acbfb3e9873410c991e1496c014ca75c369",En=Object.freeze([Object.freeze({keyId:"oci-planning-step-2026-11",publicKeyPem:`-----BEGIN PUBLIC KEY-----
|
|
2
|
+
MCowBQYDK2VwAyEAgsdYlx3VXghDcKkYCf0YfhR07KEqtcgGrTtpf1vLy2g=
|
|
3
|
+
-----END PUBLIC KEY-----
|
|
4
|
+
`,state:"active"})]);let U;function Tn(n){U=n?Object.freeze([...n]):void 0}function V(){return U??En}const X=["schemaVersion","stage","epicId","stepId","claimId","revision","issuedAt","keyId","signature"],kn="neocortex-planning-step-binding-v1\0";function Pn(n){return y(`planning-step-binding-p01\0${n}`)}function wn(n){return d(n)&&Object.keys(n).sort().join("|")===[...X].sort().join("|")&&X.every(i=>typeof n[i]=="string"&&n[i].length>0&&Buffer.byteLength(n[i])<=256)&&n.schemaVersion==="PlanningStepBinding/1"&&["P01","P02","P03","memory"].includes(n.stage)&&/^[a-z0-9-]{1,64}$/.test(n.keyId)&&S.test(n.revision)&&Number.isFinite(Date.parse(n.issuedAt))}function xn(n,i,e=V()){if(!wn(n))throw new Error("planning-step-binding-missing");const t=e.filter(f=>f.keyId===n.keyId);if(t.length!==1||t[0].state!=="active"&&t[0].state!=="grace")throw new Error("planning-step-binding-key-unknown");let s;try{s=pn(t[0].publicKeyPem)}catch{throw new Error("planning-step-binding-key-unknown")}if(s.asymmetricKeyType!=="ed25519")throw new Error("planning-step-binding-key-unknown");const c=/^[a-f0-9]{128}$/.test(n.signature)?Buffer.from(n.signature,"hex"):void 0,o=Buffer.from(kn+JSON.stringify({schemaVersion:n.schemaVersion,stage:n.stage,epicId:n.epicId,stepId:n.stepId,claimId:n.claimId,revision:n.revision,issuedAt:n.issuedAt,keyId:n.keyId}),"utf8");if(!c||c.length!==64||c.toString("hex")!==n.signature||!fn(null,o,s,c))throw new Error("planning-step-binding-tampered");if(n.stage!==i.stage||n.epicId!==i.epicId||n.claimId!==i.claimId||n.revision!==i.revision||n.stepId!==`step-${i.stepDigest.slice(0,8)}`)throw new Error("planning-step-binding-step-mismatch")}function bn(n,i,e){n===void 0&&e.length===0||xn(n,i,e)}function Dn(n){return n===void 0?{}:{stepBinding:n}}function jn(n){return n.stepBinding===void 0?{}:{stepBinding:n.stepBinding}}function d(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function y(n){return dn("sha256").update(n).digest("hex")}const An=Object.freeze({diagnosis:"p01",research:"p02",generation:"p03"});function Z(n,i=0){return i>2||!d(n)?n:Object.fromEntries(Object.keys(n).sort().map(e=>[e,Z(n[e],i+1)]))}function W(n,i){const e=An[n];if(!e)throw new Error("planning-qa-phase-invalid");const t={schemaVersion:"PlanningQaEvidence/1",phase:n,claimId:i.claimId,epicId:i.epicId,sourceHead:i.sourceHead,admissionPatchSha256:i.admissionPatchSha256,artifactDigests:Z(i.artifactDigests)};return`qa-${e}-${y(JSON.stringify(t))}`}function v(n,i,e){try{return typeof i=="string"&&i===W(n,e)}catch{return!1}}function _(n,i){return $("git",[...i],{cwd:n,encoding:"utf8",stdio:["ignore","pipe","ignore"],maxBuffer:65536}).trim()}function E(n,i,e){const t=u(n,i),s=w(t);if(!s.isFile()||s.isSymbolicLink()||s.size<1||s.size>e)throw new Error("planning-diagnosis-physical-artifact-invalid");return L(t)}function nn(n,i){return typeof n=="string"&&n.length<=128&&y(n)===i}function en(n,i,e){const t=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(n.replace(/\r\n/g,`
|
|
2
5
|
`))?.[1];if(!t)return!1;const s=t.split(`
|
|
3
|
-
`),c=o=>{const f=s.filter(r=>r.startsWith(`${o}:`));return f.length===1?f[0].slice(o.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0};return c("epic_id")===i&&c("status")==="completed"&&nn(c("step"),e)}function
|
|
4
|
-
`)]))))}function tn(n){return{claimId:n.claimId,epicId:n.epicId,sourceHead:n.sourceHead,admissionPatchSha256:n.admission.patchSha256,artifactDigests:n.artifactDigests}}function sn(n,i){if(!d(n)||Object.keys(n).filter(e=>e!=="stepBinding").sort().join("|")!==["schemaVersion","verdict","claimId","epicId","logicalFingerprint","sourceHead","sourceBranch","sourceStateSha256","admission","artifactDigests","qaEvidenceId","intake","artifactSummary"].sort().join("|")||n.schemaVersion!=="PlanningDiagnosisRootReview/1"||n.verdict!=="accepted"||typeof n.claimId!="string"||!In.test(n.claimId)||typeof n.epicId!="string"||!yn.test(n.epicId)||typeof n.logicalFingerprint!="string"||!S.test(n.logicalFingerprint)||typeof n.sourceHead!="string"||!/^[a-f0-9]{40}$/.test(n.sourceHead)||typeof n.sourceBranch!="string"||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]{0,127}$/.test(n.sourceBranch)||typeof n.sourceStateSha256!="string"||!S.test(n.sourceStateSha256)||!d(n.admission)||n.admission.schemaVersion!==1||n.admission.outcome!=="admitted-unverified"||n.admission.baseSha!==n.sourceHead||n.admission.executionBranch!==n.sourceBranch||typeof n.admission.patchSha256!="string"||!S.test(n.admission.patchSha256)||typeof n.qaEvidenceId!="string"||!/^qa-[a-z0-9-]{8,80}$/.test(n.qaEvidenceId)||!d(n.artifactDigests)||Object.keys(n.artifactDigests).sort().join("|")!==[...B].sort().join("|")||B.some(e=>typeof n.artifactDigests[e]!="string"||!S.test(n.artifactDigests[e])))throw new Error("planning-diagnosis-review-invalid");if(F({kind:"diagnosis",epicId:n.epicId,intakeRevision:Q(n.intake).intakeRevision,artifactSummary:n.artifactSummary,accepted:!0}),bn(n.stepBinding,{stage:"P01",epicId:n.epicId,claimId:n.claimId,revision:Pn(n.claimId),stepDigest:T},i),!v("diagnosis",n.qaEvidenceId,tn(n)))throw new Error("planning-diagnosis-qa-evidence-unbound")}function cn(n,i,e,t){if(_(n,["rev-parse","HEAD"])!==i.sourceHead||_(n,["symbolic-ref","--quiet","--short","HEAD"])!==i.sourceBranch)throw new Error("planning-diagnosis-head-conflict");const s=w(u(n,".neocortex")),c=w(u(n,".neocortex/pending-epic-claims.json"));if(!s.isDirectory()||s.isSymbolicLink()||(s.mode&18)!==0||!c.isFile()||c.isSymbolicLink()||c.uid!==process.getuid?.()||(c.mode&63)!==0)throw new Error("planning-diagnosis-claim-boundary-invalid");const o=JSON.parse(E(n,".neocortex/pending-epic-claims.json",128*1024).toString("utf8")),f=d(o)&&d(o.operations)?o.operations[i.logicalFingerprint]:void 0;if(!d(f)||f.claimId!==i.claimId||f.epicId!==i.epicId)throw new Error("planning-diagnosis-claim-conflict");const r=`.neocortex/planning/epic-${i.epicId}`,h={idea:`${r}/idea.json`,diagnosis:`${r}/diagnosis.md`,enrichment:`${r}/enriched-prompt.md`,index:".neocortex/planning/planning.json"};if(!Array.isArray(i.admission.changedPaths)||[...i.admission.changedPaths].sort().join("|")!==Object.values(h).sort().join("|")||e&&Bn(n,h,t)!==i.admission.patchSha256)throw new Error("planning-diagnosis-admission-patch-conflict");const p={idea:E(n,h.idea,32*1024),diagnosis:E(n,h.diagnosis,256*1024),enrichment:E(n,h.enrichment,256*1024),index:E(n,h.index,128*1024)};for(const x of B)if(y(p[x])!==i.artifactDigests[x])throw new Error("planning-diagnosis-artifact-conflict");const g=JSON.parse(p.idea.toString("utf8")),l=JSON.parse(p.index.toString("utf8")),a=Q(i.intake).intake,m=d(l)&&d(l.epics)?l.epics[i.epicId]:void 0,I=d(m)?m.output_files:void 0;if(!d(g)||g.epic_id!==i.epicId||g.status!=="diagnosed"||g.raw_input!==a.rawIntent||!d(m)||m.id!==i.epicId||m.idea!==a.rawIntent||m.status!=="diagnosed"||!en(p.diagnosis.toString("utf8"),i.epicId,T)||!en(p.enrichment.toString("utf8"),i.epicId,Sn)||!Array.isArray(m.steps_completed)||m.steps_completed.length!==1||!nn(m.steps_completed[0],T)||!d(I)||!b(I,{diagnosis:h.diagnosis})||typeof m.created_at!="string"||!Number.isFinite(Date.parse(m.created_at))||m.completed_at!==null)throw new Error("planning-diagnosis-artifact-identity-conflict");if(typeof a.goal!="string"||!a.goal.trim()||typeof a.desiredOutcome!="string"||!a.desiredOutcome.trim()||!Array.isArray(a.users)||a.users.length===0||!Array.isArray(a.surfaces)||a.surfaces.length===0)throw new Error("planning-diagnosis-critical-intake-missing");const k=M(a),P=F({kind:"diagnosis",epicId:i.epicId,intakeRevision:k,artifactSummary:i.artifactSummary,accepted:!0});return{checkpoint:{schemaVersion:1,epicId:i.epicId,intake:a,intakeRevision:k,diagnosisReceipt:P},receiptId:P.receiptId}}function z(n,i,e){const t=cn(n,i,!0,e),s=E(n,".neocortex/state.json",8*1024*1024);if(y(s)!==i.sourceStateSha256)throw new Error("planning-diagnosis-state-conflict");const c=JSON.parse(s.toString("utf8"));if(!d(c)||d(c.scope)&&c.scope.kind==="projected")throw new Error("planning-diagnosis-state-invalid");return U(c,{claimId:i.claimId,epicId:i.epicId,checkpoint:t.checkpoint}),{stateRaw:s,state:c,...t}}function rn(n,i){const e={schemaVersion:"PlanningDiagnosisPhysicalAcceptance/1",claimId:n.claimId,epicId:n.epicId,diagnosisReceiptId:i,qaEvidenceId:n.qaEvidenceId,sourceHead:n.sourceHead,sourceStateSha256:n.sourceStateSha256,admissionPatchSha256:n.admission.patchSha256,artifactDigests:n.artifactDigests,...Dn(n.stepBinding)};return{...e,receiptId:y(JSON.stringify(e)),publicSafe:!0}}function Vn(n,i,e,t=!1){const s=d(n)?n:void 0,o=(s&&d(s.epics)?s.epics:void 0)?.[e];if(!d(o)||o.id!==e||o.source!=="create-epic"||o.status!=="diagnosed"&&!(t&&o.status==="researched")||!d(o.createEpicPlanningClaim)||o.createEpicPlanningClaim.claimId!==i||o.createEpicPlanningClaim.epicId!==e||!d(o.createEpicPlanning)||!d(o.createEpicPlanningPhysical))throw new Error("planning-research-predecessor-invalid");const f=o.createEpicPlanning,r=o.createEpicPlanningPhysical,h=d(r.artifactDigests)?r.artifactDigests:void 0,p=un(f.intake),g=M(p),l=s&&d(s.epic_id_ledger)?s.epic_id_ledger:void 0,a=d(f.diagnosisReceipt)?f.diagnosisReceipt:void 0;if(f.schemaVersion!==1||f.epicId!==e||f.intakeRevision!==g||!t&&f.researchReceipt!==void 0||typeof p.goal!="string"||!p.goal.trim()||typeof p.desiredOutcome!="string"||!p.desiredOutcome.trim()||typeof p.rawIntent!="string"||!p.rawIntent.trim()||!Array.isArray(p.users)||p.users.length===0||!Array.isArray(p.surfaces)||p.surfaces.length===0||!Array.isArray(l?.reserved_ids)||!l.reserved_ids.includes(e)||!a||a.kind!=="diagnosis"||a.epicId!==e||a.intakeRevision!==g||a.accepted!==!0||typeof a.artifactSummary!="string"||!b(a,F({kind:"diagnosis",epicId:e,intakeRevision:g,artifactSummary:a.artifactSummary,accepted:!0}))||r.schemaVersion!=="PlanningDiagnosisPhysicalAcceptance/1"||r.claimId!==i||r.epicId!==e||r.diagnosisReceiptId!==a.receiptId||typeof r.qaEvidenceId!="string"||!/^qa-[a-z0-9-]{8,80}$/.test(r.qaEvidenceId)||typeof r.sourceHead!="string"||!/^[a-f0-9]{40}$/.test(r.sourceHead)||typeof r.sourceStateSha256!="string"||!S.test(r.sourceStateSha256)||typeof r.admissionPatchSha256!="string"||!S.test(r.admissionPatchSha256)||!h||Object.keys(h).sort().join("|")!==[...B].sort().join("|")||B.some(I=>typeof h[I]!="string"||!S.test(h[I]))||!v("diagnosis",r.qaEvidenceId,{claimId:i,epicId:e,sourceHead:r.sourceHead,admissionPatchSha256:r.admissionPatchSha256,artifactDigests:h}))throw new Error("planning-research-predecessor-invalid");const m={schemaVersion:r.schemaVersion,claimId:i,epicId:e,diagnosisReceiptId:a.receiptId,qaEvidenceId:r.qaEvidenceId,sourceHead:r.sourceHead,sourceStateSha256:r.sourceStateSha256,admissionPatchSha256:r.admissionPatchSha256,artifactDigests:h,...jn(r)};if(!b(r,{...m,receiptId:y(JSON.stringify(m)),publicSafe:!0}))throw new Error("planning-research-predecessor-invalid");return{intakeRevision:g,diagnosisReceiptId:a.receiptId,rawIntent:p.rawIntent}}function _n(n,i){const e=cn(n,i,!1),t=JSON.parse(E(n,".neocortex/state.json",8*1024*1024).toString("utf8")),c=(d(t)&&d(t.epics)?t.epics:void 0)?.[i.epicId],o=d(t)&&d(t.epic_id_ledger)?t.epic_id_ledger:void 0;if(!d(c)||!d(c.createEpicPlanning)||!d(c.createEpicPlanningClaim)||c.createEpicPlanningClaim.claimId!==i.claimId||c.createEpicPlanningClaim.epicId!==i.epicId||c.createEpicPlanning.epicId!==i.epicId||c.createEpicPlanning.intakeRevision!==e.checkpoint.intakeRevision||!b(c.createEpicPlanning.intake,e.checkpoint.intake)||!b(c.createEpicPlanning.diagnosisReceipt,e.checkpoint.diagnosisReceipt)||!b(c.createEpicPlanningPhysical,rn(i,e.receiptId))||!Array.isArray(o?.reserved_ids)||!o.reserved_ids.includes(i.epicId))throw new Error("planning-diagnosis-replay-conflict");return e.receiptId}function zn(n,i,e={}){if(!d(i)||!d(i.admission))throw new Error("planning-diagnosis-review-invalid");const t={...i,qaEvidenceId:"qa-pending-record"};let s;try{s=X("diagnosis",tn(t))}catch{throw new Error("planning-diagnosis-review-invalid")}const c={...t,qaEvidenceId:s};sn(c,e.trustedKeys??V());const o=N(n);if(H(o)!==o||_(o,["rev-parse","--show-toplevel"])!==o)throw new Error("planning-diagnosis-root-invalid");return z(o,c),{epicId:c.epicId,qaEvidenceId:s}}function Cn(n,i,e={}){sn(i,e.trustedKeys??V());const t=i,s=N(n);if(H(s)!==s||_(s,["rev-parse","--show-toplevel"])!==s)throw new Error("planning-diagnosis-root-invalid");const c=u(s,".neocortex"),o=u(c,"state.json.planning.lock"),f=A(o,"wx",384);let r;try{const h=E(s,".neocortex/state.json",8388608);if(y(h)!==t.sourceStateSha256){const an=_n(s,t);return{epicId:t.epicId,diagnosisReceiptId:an,qaEvidenceId:t.qaEvidenceId}}const p=z(s,t),g=U(p.state,{claimId:t.claimId,epicId:t.epicId,checkpoint:p.checkpoint});if(g===p.state)throw new Error("planning-diagnosis-already-sealed");const l=rn(t,p.receiptId),a=g.epics,m={...g,epics:{...a,[t.epicId]:{...a[t.epicId],createEpicPlanningPhysical:l}}},I=_(s,["rev-parse","--git-common-dir"]),k=mn(I)?N(I):N(s,I);if(H(k)!==k||w(k).isSymbolicLink())throw new Error("planning-diagnosis-backup-dir-invalid");const P=u(k,"neocortex-planning");ln(P,{recursive:!0,mode:448});const D=w(P);if(!D.isDirectory()||D.isSymbolicLink()||D.uid!==process.getuid?.()||(D.mode&63)!==0)throw new Error("planning-diagnosis-backup-dir-invalid");const x=gn(),O=A(u(P,`state-backup-${x}.json`),"wx",384);try{G(O,p.stateRaw),R(O)}finally{j(O)}const C=A(P,"r");try{R(C)}finally{j(C)}r=u(c,`state.json.planning-tmp-${x}`);const $=A(r,"wx",384);try{G($,`${JSON.stringify(m,null,2)}
|
|
5
|
-
`),R(
|
|
6
|
+
`),c=o=>{const f=s.filter(r=>r.startsWith(`${o}:`));return f.length===1?f[0].slice(o.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0};return c("epic_id")===i&&c("status")==="completed"&&nn(c("step"),e)}function Fn(n){const i=u(n,".neocortex/pending-epic-claims.json");let e;try{e=w(i)}catch(c){if(c.code==="ENOENT")return;throw c}const t=w(u(n,".neocortex"));if(!t.isDirectory()||t.isSymbolicLink()||t.uid!==process.getuid?.()||(t.mode&18)!==0||!e.isFile()||e.isSymbolicLink()||e.uid!==process.getuid?.()||(e.mode&63)!==0||e.size<1||e.size>128*1024)throw new Error("planning-pending-sidecar-invalid");const s=L(i);if(s.length!==e.size)throw new Error("planning-pending-sidecar-invalid");return y(s)}function Bn(n,i,e,t=!0){const s=new Set(Object.values(i)),c=new Set([".neocortex/state.json.planning.lock",...e?[e]:[]]),o=$("git",["status","--porcelain=v1","-z","--untracked-files=all"],{cwd:n,stdio:["ignore","pipe","ignore"],maxBuffer:128*1024}).toString("utf8").split("\0").filter(Boolean),f=[],r=new Set;for(const g of o){const l=g.slice(0,2),a=g.slice(3);if(!(c.has(a)&&l==="??")){if(g[2]!==" "||!s.has(a)&&(!t||a!==".neocortex/pending-epic-claims.json")||a===".neocortex/pending-epic-claims.json"&&l!=="??"||a!==".neocortex/pending-epic-claims.json"&&l!=="??"&&l!==" M"||r.has(a))throw new Error("planning-diagnosis-write-scope-conflict");r.add(a),l==="??"&&s.has(a)&&f.push(a)}}if([...s].some(g=>!r.has(g)))throw new Error("planning-diagnosis-write-scope-conflict");const p=[$("git",["diff","--binary","--no-ext-diff","--no-textconv","HEAD","--"],{cwd:n,stdio:["ignore","pipe","ignore"],maxBuffer:2*1024*1024})];for(const g of f.sort()){const l=on("git",["diff","--no-index","--binary","--no-ext-diff","--","/dev/null",g],{cwd:n,encoding:"buffer",maxBuffer:2097152});if(l.status!==1||!Buffer.isBuffer(l.stdout))throw new Error("planning-diagnosis-patch-invalid");p.push(l.stdout)}return y(Buffer.concat(p.map(g=>Buffer.concat([g,Buffer.from(`
|
|
7
|
+
`)]))))}function tn(n){return{claimId:n.claimId,epicId:n.epicId,sourceHead:n.sourceHead,admissionPatchSha256:n.admission.patchSha256,artifactDigests:n.artifactDigests}}function sn(n,i){if(!d(n)||Object.keys(n).filter(e=>e!=="stepBinding").sort().join("|")!==["schemaVersion","verdict","claimId","epicId","logicalFingerprint","sourceHead","sourceBranch","sourceStateSha256","admission","artifactDigests","qaEvidenceId","intake","artifactSummary"].sort().join("|")||n.schemaVersion!=="PlanningDiagnosisRootReview/1"||n.verdict!=="accepted"||typeof n.claimId!="string"||!In.test(n.claimId)||typeof n.epicId!="string"||!yn.test(n.epicId)||typeof n.logicalFingerprint!="string"||!S.test(n.logicalFingerprint)||typeof n.sourceHead!="string"||!/^[a-f0-9]{40}$/.test(n.sourceHead)||typeof n.sourceBranch!="string"||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]{0,127}$/.test(n.sourceBranch)||typeof n.sourceStateSha256!="string"||!S.test(n.sourceStateSha256)||!d(n.admission)||n.admission.schemaVersion!==1||n.admission.outcome!=="admitted-unverified"||n.admission.baseSha!==n.sourceHead||n.admission.executionBranch!==n.sourceBranch||typeof n.admission.patchSha256!="string"||!S.test(n.admission.patchSha256)||typeof n.qaEvidenceId!="string"||!/^qa-[a-z0-9-]{8,80}$/.test(n.qaEvidenceId)||!d(n.artifactDigests)||Object.keys(n.artifactDigests).sort().join("|")!==[...B].sort().join("|")||B.some(e=>typeof n.artifactDigests[e]!="string"||!S.test(n.artifactDigests[e])))throw new Error("planning-diagnosis-review-invalid");if(T({kind:"diagnosis",epicId:n.epicId,intakeRevision:Y(n.intake).intakeRevision,artifactSummary:n.artifactSummary,accepted:!0}),bn(n.stepBinding,{stage:"P01",epicId:n.epicId,claimId:n.claimId,revision:Pn(n.claimId),stepDigest:F},i),!v("diagnosis",n.qaEvidenceId,tn(n)))throw new Error("planning-diagnosis-qa-evidence-unbound")}function cn(n,i,e,t){if(_(n,["rev-parse","HEAD"])!==i.sourceHead||_(n,["symbolic-ref","--quiet","--short","HEAD"])!==i.sourceBranch)throw new Error("planning-diagnosis-head-conflict");const s=w(u(n,".neocortex")),c=w(u(n,".neocortex/pending-epic-claims.json"));if(!s.isDirectory()||s.isSymbolicLink()||(s.mode&18)!==0||!c.isFile()||c.isSymbolicLink()||c.uid!==process.getuid?.()||(c.mode&63)!==0)throw new Error("planning-diagnosis-claim-boundary-invalid");const o=JSON.parse(E(n,".neocortex/pending-epic-claims.json",128*1024).toString("utf8")),f=d(o)&&d(o.operations)?o.operations[i.logicalFingerprint]:void 0;if(!d(f)||f.claimId!==i.claimId||f.epicId!==i.epicId)throw new Error("planning-diagnosis-claim-conflict");const r=`.neocortex/planning/epic-${i.epicId}`,h={idea:`${r}/idea.json`,diagnosis:`${r}/diagnosis.md`,enrichment:`${r}/enriched-prompt.md`,index:".neocortex/planning/planning.json"};if(!Array.isArray(i.admission.changedPaths)||[...i.admission.changedPaths].sort().join("|")!==Object.values(h).sort().join("|")||e&&Bn(n,h,t)!==i.admission.patchSha256)throw new Error("planning-diagnosis-admission-patch-conflict");const p={idea:E(n,h.idea,32*1024),diagnosis:E(n,h.diagnosis,256*1024),enrichment:E(n,h.enrichment,256*1024),index:E(n,h.index,128*1024)};for(const x of B)if(y(p[x])!==i.artifactDigests[x])throw new Error("planning-diagnosis-artifact-conflict");const g=JSON.parse(p.idea.toString("utf8")),l=JSON.parse(p.index.toString("utf8")),a=Y(i.intake).intake,m=d(l)&&d(l.epics)?l.epics[i.epicId]:void 0,I=d(m)?m.output_files:void 0;if(!d(g)||g.epic_id!==i.epicId||g.status!=="diagnosed"||g.raw_input!==a.rawIntent||!d(m)||m.id!==i.epicId||m.idea!==a.rawIntent||m.status!=="diagnosed"||!en(p.diagnosis.toString("utf8"),i.epicId,F)||!en(p.enrichment.toString("utf8"),i.epicId,Sn)||!Array.isArray(m.steps_completed)||m.steps_completed.length!==1||!nn(m.steps_completed[0],F)||!d(I)||!b(I,{diagnosis:h.diagnosis})||typeof m.created_at!="string"||!Number.isFinite(Date.parse(m.created_at))||m.completed_at!==null)throw new Error("planning-diagnosis-artifact-identity-conflict");if(typeof a.goal!="string"||!a.goal.trim()||typeof a.desiredOutcome!="string"||!a.desiredOutcome.trim()||!Array.isArray(a.users)||a.users.length===0||!Array.isArray(a.surfaces)||a.surfaces.length===0)throw new Error("planning-diagnosis-critical-intake-missing");const k=M(a),P=T({kind:"diagnosis",epicId:i.epicId,intakeRevision:k,artifactSummary:i.artifactSummary,accepted:!0});return{checkpoint:{schemaVersion:1,epicId:i.epicId,intake:a,intakeRevision:k,diagnosisReceipt:P},receiptId:P.receiptId}}function C(n,i,e){const t=cn(n,i,!0,e),s=E(n,".neocortex/state.json",8*1024*1024);if(y(s)!==i.sourceStateSha256)throw new Error("planning-diagnosis-state-conflict");const c=JSON.parse(s.toString("utf8"));if(!d(c)||d(c.scope)&&c.scope.kind==="projected")throw new Error("planning-diagnosis-state-invalid");return Q(c,{claimId:i.claimId,epicId:i.epicId,checkpoint:t.checkpoint}),{stateRaw:s,state:c,...t}}function rn(n,i){const e={schemaVersion:"PlanningDiagnosisPhysicalAcceptance/1",claimId:n.claimId,epicId:n.epicId,diagnosisReceiptId:i,qaEvidenceId:n.qaEvidenceId,sourceHead:n.sourceHead,sourceStateSha256:n.sourceStateSha256,admissionPatchSha256:n.admission.patchSha256,artifactDigests:n.artifactDigests,...Dn(n.stepBinding)};return{...e,receiptId:y(JSON.stringify(e)),publicSafe:!0}}function Vn(n,i,e,t=!1){const s=d(n)?n:void 0,o=(s&&d(s.epics)?s.epics:void 0)?.[e];if(!d(o)||o.id!==e||o.source!=="create-epic"||o.status!=="diagnosed"&&!(t&&o.status==="researched")||!d(o.createEpicPlanningClaim)||o.createEpicPlanningClaim.claimId!==i||o.createEpicPlanningClaim.epicId!==e||!d(o.createEpicPlanning)||!d(o.createEpicPlanningPhysical))throw new Error("planning-research-predecessor-invalid");const f=o.createEpicPlanning,r=o.createEpicPlanningPhysical,h=d(r.artifactDigests)?r.artifactDigests:void 0,p=un(f.intake),g=M(p),l=s&&d(s.epic_id_ledger)?s.epic_id_ledger:void 0,a=d(f.diagnosisReceipt)?f.diagnosisReceipt:void 0;if(f.schemaVersion!==1||f.epicId!==e||f.intakeRevision!==g||!t&&f.researchReceipt!==void 0||typeof p.goal!="string"||!p.goal.trim()||typeof p.desiredOutcome!="string"||!p.desiredOutcome.trim()||typeof p.rawIntent!="string"||!p.rawIntent.trim()||!Array.isArray(p.users)||p.users.length===0||!Array.isArray(p.surfaces)||p.surfaces.length===0||!Array.isArray(l?.reserved_ids)||!l.reserved_ids.includes(e)||!a||a.kind!=="diagnosis"||a.epicId!==e||a.intakeRevision!==g||a.accepted!==!0||typeof a.artifactSummary!="string"||!b(a,T({kind:"diagnosis",epicId:e,intakeRevision:g,artifactSummary:a.artifactSummary,accepted:!0}))||r.schemaVersion!=="PlanningDiagnosisPhysicalAcceptance/1"||r.claimId!==i||r.epicId!==e||r.diagnosisReceiptId!==a.receiptId||typeof r.qaEvidenceId!="string"||!/^qa-[a-z0-9-]{8,80}$/.test(r.qaEvidenceId)||typeof r.sourceHead!="string"||!/^[a-f0-9]{40}$/.test(r.sourceHead)||typeof r.sourceStateSha256!="string"||!S.test(r.sourceStateSha256)||typeof r.admissionPatchSha256!="string"||!S.test(r.admissionPatchSha256)||!h||Object.keys(h).sort().join("|")!==[...B].sort().join("|")||B.some(I=>typeof h[I]!="string"||!S.test(h[I]))||!v("diagnosis",r.qaEvidenceId,{claimId:i,epicId:e,sourceHead:r.sourceHead,admissionPatchSha256:r.admissionPatchSha256,artifactDigests:h}))throw new Error("planning-research-predecessor-invalid");const m={schemaVersion:r.schemaVersion,claimId:i,epicId:e,diagnosisReceiptId:a.receiptId,qaEvidenceId:r.qaEvidenceId,sourceHead:r.sourceHead,sourceStateSha256:r.sourceStateSha256,admissionPatchSha256:r.admissionPatchSha256,artifactDigests:h,...jn(r)};if(!b(r,{...m,receiptId:y(JSON.stringify(m)),publicSafe:!0}))throw new Error("planning-research-predecessor-invalid");return{intakeRevision:g,diagnosisReceiptId:a.receiptId,rawIntent:p.rawIntent}}function _n(n,i){const e=cn(n,i,!1),t=JSON.parse(E(n,".neocortex/state.json",8*1024*1024).toString("utf8")),c=(d(t)&&d(t.epics)?t.epics:void 0)?.[i.epicId],o=d(t)&&d(t.epic_id_ledger)?t.epic_id_ledger:void 0;if(!d(c)||!d(c.createEpicPlanning)||!d(c.createEpicPlanningClaim)||c.createEpicPlanningClaim.claimId!==i.claimId||c.createEpicPlanningClaim.epicId!==i.epicId||c.createEpicPlanning.epicId!==i.epicId||c.createEpicPlanning.intakeRevision!==e.checkpoint.intakeRevision||!b(c.createEpicPlanning.intake,e.checkpoint.intake)||!b(c.createEpicPlanning.diagnosisReceipt,e.checkpoint.diagnosisReceipt)||!b(c.createEpicPlanningPhysical,rn(i,e.receiptId))||!Array.isArray(o?.reserved_ids)||!o.reserved_ids.includes(i.epicId))throw new Error("planning-diagnosis-replay-conflict");return e.receiptId}function Cn(n,i,e={}){if(!d(i)||!d(i.admission))throw new Error("planning-diagnosis-review-invalid");const t={...i,qaEvidenceId:"qa-pending-record"};let s;try{s=W("diagnosis",tn(t))}catch{throw new Error("planning-diagnosis-review-invalid")}const c={...t,qaEvidenceId:s};sn(c,e.trustedKeys??V());const o=N(n);if(H(o)!==o||_(o,["rev-parse","--show-toplevel"])!==o)throw new Error("planning-diagnosis-root-invalid");return C(o,c),{epicId:c.epicId,qaEvidenceId:s}}function Kn(n,i,e={}){sn(i,e.trustedKeys??V());const t=i,s=N(n);if(H(s)!==s||_(s,["rev-parse","--show-toplevel"])!==s)throw new Error("planning-diagnosis-root-invalid");const c=u(s,".neocortex"),o=u(c,"state.json.planning.lock"),f=A(o,"wx",384);let r;try{const h=E(s,".neocortex/state.json",8388608);if(y(h)!==t.sourceStateSha256){const an=_n(s,t);return{epicId:t.epicId,diagnosisReceiptId:an,qaEvidenceId:t.qaEvidenceId}}const p=C(s,t),g=Q(p.state,{claimId:t.claimId,epicId:t.epicId,checkpoint:p.checkpoint});if(g===p.state)throw new Error("planning-diagnosis-already-sealed");const l=rn(t,p.receiptId),a=g.epics,m={...g,epics:{...a,[t.epicId]:{...a[t.epicId],createEpicPlanningPhysical:l}}},I=_(s,["rev-parse","--git-common-dir"]),k=mn(I)?N(I):N(s,I);if(H(k)!==k||w(k).isSymbolicLink())throw new Error("planning-diagnosis-backup-dir-invalid");const P=u(k,"neocortex-planning");ln(P,{recursive:!0,mode:448});const D=w(P);if(!D.isDirectory()||D.isSymbolicLink()||D.uid!==process.getuid?.()||(D.mode&63)!==0)throw new Error("planning-diagnosis-backup-dir-invalid");const x=gn(),O=A(u(P,`state-backup-${x}.json`),"wx",384);try{J(O,p.stateRaw),R(O)}finally{j(O)}const K=A(P,"r");try{R(K)}finally{j(K)}r=u(c,`state.json.planning-tmp-${x}`);const q=A(r,"wx",384);try{J(q,`${JSON.stringify(m,null,2)}
|
|
8
|
+
`),R(q)}finally{j(q)}if(!C(s,t,`.neocortex/state.json.planning-tmp-${x}`).stateRaw.equals(p.stateRaw))throw new Error("planning-diagnosis-state-conflict");hn(r,u(c,"state.json")),r=void 0;const z=A(c,"r");try{R(z)}finally{j(z)}return{epicId:t.epicId,diagnosisReceiptId:p.receiptId,qaEvidenceId:t.qaEvidenceId}}finally{if(r)try{G(r)}catch{}j(f),G(o)}}export{En as PLANNING_STEP_BINDING_PRODUCTION_KEYS,Vn as acceptedPlanningDiagnosisPredecessor,bn as enforcePlanningStepBinding,Fn as planningPendingSidecarDigest,Bn as planningPhysicalPatchDigest,v as planningQaEvidenceBound,W as planningQaEvidenceId,Dn as planningStepBindingAcceptanceField,Pn as planningStepBindingP01Revision,jn as planningStepBindingReceiptField,V as planningStepBindingTrustedKeys,Cn as recordPlanningDiagnosisQaEvidence,Kn as sealPlanningDiagnosis,Tn as setPlanningStepBindingTrustedKeysForTesting,xn as verifyPlanningStepBinding};
|
|
@@ -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
|
-
|
|
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 {};
|