@ornexus/neocortex 4.61.6 → 4.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1193 -1193
  3. package/install.ps1 +31 -34
  4. package/install.sh +1 -1
  5. package/package.json +5 -2
  6. package/packages/client/dist/agent/update-description.d.ts +8 -1
  7. package/packages/client/dist/agent/update-description.js +2 -1
  8. package/packages/client/dist/commands/invoke.d.ts +17 -0
  9. package/packages/client/dist/commands/invoke.js +72 -72
  10. package/packages/client/dist/errors/frontmatter-diagnostics.d.ts +10 -1
  11. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -1
  12. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +24 -9
  13. package/packages/client/dist/git/direct-yolo-checkpoint.js +3 -4
  14. package/packages/client/dist/git/git-lifecycle-store.d.ts +66 -0
  15. package/packages/client/dist/git/git-lifecycle-store.js +8 -7
  16. package/packages/client/dist/git/release-gate-env.d.ts +62 -0
  17. package/packages/client/dist/git/release-gate-env.js +1 -0
  18. package/packages/client/dist/git/secure-filesystem-boundary.d.ts +24 -0
  19. package/packages/client/dist/git/secure-filesystem-boundary.js +20 -9
  20. package/packages/client/dist/runner/headless/child-env.d.ts +92 -0
  21. package/packages/client/dist/runner/headless/child-env.js +1 -0
  22. package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -11
  23. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +1 -0
  24. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -10
  25. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2
  26. package/packages/client/dist/yolo/invoke-envelope-capability.d.ts +2 -0
  27. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -1
  28. package/packages/client/dist/yolo/project-manifest-projection-collector.d.ts +28 -0
  29. package/packages/client/dist/yolo/project-manifest-projection-collector.js +1 -0
  30. package/packages/client/dist/yolo/spec-envelope-collector.d.ts +9 -0
  31. package/packages/client/dist/yolo/spec-envelope-collector.js +3 -3
  32. package/packages/client/dist/yoloop/shared-discover-epics.d.ts +16 -0
  33. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1
  34. package/packages/shared/dist/frontmatter-context-contract.js +164 -52
  35. package/packages/shared/dist/project-manifest-projection.js +199 -0
  36. package/packages/shared/dist/project-validation-commands.js +14 -6
  37. package/packages/shared/dist/yolo/spec-envelope-rules.js +85 -0
  38. package/packages/shared/dist/yolo/spec-envelope.js +33 -7
  39. package/packages/shared/dist/yoloop/epic-terminal-git.js +94 -6
  40. package/packages/shared/dist/yoloop/story-write-scope.js +212 -0
  41. package/targets-stubs/antigravity/gemini.md +1 -1
  42. package/targets-stubs/antigravity/install-antigravity.sh +13 -4
  43. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  44. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  45. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  46. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  47. package/targets-stubs/claude-code/neocortex.md +5 -5
  48. package/targets-stubs/codex/AGENTS.md +1 -1
  49. package/targets-stubs/cursor/agent.md +2 -2
  50. package/targets-stubs/gemini-cli/agent.md +2 -2
  51. package/targets-stubs/lib/managed-config-merge.js +77 -1
  52. package/targets-stubs/lib/managed-profile.sh +7 -0
  53. package/targets-stubs/opencode/neocortex-root.md +1 -1
  54. package/targets-stubs/vscode/install-vscode.sh +21 -0
  55. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,4 +1,4 @@
1
- import{spawn as b}from"node:child_process";import{randomBytes as B}from"node:crypto";import{lstat as w,stat as x}from"node:fs/promises";const T=String.raw`
1
+ import{spawn as G}from"node:child_process";import{randomBytes as F}from"node:crypto";import{lstat as _,stat as I}from"node:fs/promises";const X=String.raw`
2
2
  const fs = require('node:fs');
3
3
  const crypto = require('node:crypto');
4
4
  const [op, expectedDev, expectedIno, name, temporary, expectedSha] = process.argv.slice(1);
@@ -93,10 +93,10 @@ if (op === 'mkdir' || op === 'mkdir-exclusive') {
93
93
  if (safeExisting(name, 'directory')) fail('secure-filesystem-directory-remained');
94
94
  } else fail('secure-filesystem-operation-invalid');
95
95
  try { const parent = fs.openSync('.', fs.constants.O_RDONLY); fs.fsyncSync(parent); fs.closeSync(parent); } catch {}
96
- `,k=String.raw`
96
+ `,$=64*1024,M=Symbol.for("neocortex.p226.gateStderrTail"),T="secure-git-command-stderr:";function U(t){if(!(t instanceof Error))return;const e=t[M];return typeof e=="string"?e:void 0}const Y=String.raw`
97
97
  const fs = require('node:fs');
98
98
  const cp = require('node:child_process');
99
- const [expectedParentDev, expectedParentIno, name, expectedChildDev, expectedChildIno, encodedArgs, handshake, binary] = process.argv.slice(1);
99
+ const [expectedParentDev, expectedParentIno, name, expectedChildDev, expectedChildIno, encodedArgs, handshake, binary, captureStderr] = process.argv.slice(1);
100
100
  const fail = (code) => { process.stderr.write(code); process.exit(73); };
101
101
  process.on('uncaughtException', (error) => fail('secure-git-os:' + String(error && error.code || 'UNKNOWN')));
102
102
  const safeName = typeof name === 'string' && name.length > 0 && name.length <= 255
@@ -127,12 +127,17 @@ if (!Array.isArray(args) || args.length === 0 || args.length > 512
127
127
  process.umask(0o077);
128
128
  if (!['git', 'node', 'npm'].includes(binary)) fail('secure-git-command-invalid');
129
129
  const maxOutputBytes = binary === 'git' ? 16 * 1024 * 1024 : 64 * 1024 * 1024;
130
- const gitEnv = { ...process.env, GIT_OPTIONAL_LOCKS: '1' };
130
+ // P226.02 gate mode: the caller already projected and denylisted the exact
131
+ // environment; apply the same removals defensively but add nothing, so the
132
+ // anchored and plain gate paths see byte-identical environments.
133
+ const gateMode = captureStderr === '1';
134
+ const gitEnv = gateMode ? { ...process.env } : { ...process.env, GIT_OPTIONAL_LOCKS: '1' };
135
+ for (const key of Object.keys(gitEnv)) if (gateMode && key.toUpperCase().startsWith('GIT_')) delete gitEnv[key];
131
136
  for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_OBJECT_DIRECTORY',
132
137
  'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_COMMON_DIR', 'GIT_NAMESPACE', 'GIT_CEILING_DIRECTORIES']) delete gitEnv[key];
133
138
  if (binary !== 'git') {
134
139
  for (const key of ['NODE_OPTIONS', 'NODE_PATH', 'NEOCORTEX_RELEASE_GATE_MANIFEST', 'NEOCORTEX_PROFILE_DIR']) delete gitEnv[key];
135
- gitEnv.npm_config_global = 'false';
140
+ if (!gateMode) gitEnv.npm_config_global = 'false';
136
141
  }
137
142
  const result = cp.spawnSync(binary === 'node' ? process.execPath : binary, args, {
138
143
  input,
@@ -142,9 +147,15 @@ const result = cp.spawnSync(binary === 'node' ? process.execPath : binary, args,
142
147
  env: gitEnv,
143
148
  });
144
149
  if (result.error) fail('secure-git-command-error:' + String(result.error.code || 'UNKNOWN'));
145
- if (result.status !== 0) fail('secure-git-command-failed:' + String(Number.isInteger(result.status) ? result.status : 1));
150
+ if (result.status !== 0) {
151
+ if (captureStderr === '1' && result.stderr && result.stderr.length > 0) {
152
+ const tail = result.stderr.subarray(Math.max(0, result.stderr.length - 65536));
153
+ process.stderr.write('secure-git-command-stderr:' + tail.toString('base64url') + '\n');
154
+ }
155
+ fail('secure-git-command-failed:' + String(Number.isInteger(result.status) ? result.status : 1));
156
+ }
146
157
  if (result.stdout && result.stdout.length > maxOutputBytes) fail('secure-git-output-too-large');
147
158
  if (result.stdout) process.stdout.write(result.stdout);
148
- `;function v(r=process.platform){return r!=="win32"}async function G(r,t,e,i={}){const s=`.${t}.${process.pid}.${B(8).toString("hex")}.tmp`;await y(r,["write",t,s],Buffer.isBuffer(e)?e:Buffer.from(e),i)}async function P(r,t,e,i,s={}){const n=`.${t}.${process.pid}.${B(8).toString("hex")}.tmp`;await y(r,["write-cas",t,n,i],Buffer.isBuffer(e)?e:Buffer.from(e),s)}async function H(r,t,e={}){await y(r,["remove",t],void 0,e)}async function W(r,t,e={}){await y(r,["mkdir",t],void 0,e)}async function $(r,t){const i=(await y(r,["mkdir-exclusive",t])).toString("utf8").match(/^secure-filesystem-identity:([0-9]+):([0-9]+)$/);if(!i)throw new Error("secure-filesystem-created-identity-missing");return Object.freeze({dev:i[1],ino:i[2]})}async function X(r){if(!v())throw new Error("secure-filesystem-platform-unsupported");const t=await w(r,{bigint:!0}),e=await x(r,{bigint:!0});if(t.isSymbolicLink()||!t.isDirectory()||!e.isDirectory()||t.dev!==e.dev||t.ino!==e.ino)throw new Error("secure-filesystem-directory-unsafe");return Object.freeze({dev:String(e.dev),ino:String(e.ino)})}async function Y(r,t,e,i,s,n={}){return O("git",r,t,e,i,s,n)}async function M(r,t,e,i,s,n={}){return O("node",r,t,e,i,s,n)}async function K(r,t,e,i){return O("npm",r,t,e,i)}async function O(r,t,e,i,s,n,f={}){if(!v(f.platform??process.platform))throw new Error("secure-filesystem-platform-unsupported");if(s.length===0||s.length>512||s.some(a=>typeof a!="string"||a.length>4096||a.includes("\0")))throw new Error("secure-git-args-invalid");const d=await x(t,{bigint:!0}),o=await w(t,{bigint:!0});if(!d.isDirectory()||o.isSymbolicLink()||!o.isDirectory()||d.dev!==o.dev||d.ino!==o.ino)throw new Error("secure-filesystem-parent-invalid");await f.beforeHandoff?.();const m=r==="git"?16*1024*1024:64*1024*1024;return await new Promise((a,p)=>{const l=f.afterHandoff?"1":"0",g=Buffer.from(JSON.stringify([...s])).toString("base64url"),c=b(process.execPath,["-e",k,String(d.dev),String(d.ino),e,i.dev,i.ino,g,l,r],{cwd:t,stdio:["pipe","pipe","pipe"]}),h=[],E=[];let S=0,_=!f.afterHandoff,I=!1;const N=async()=>{if(!I){I=!0;try{await f.afterHandoff?.(),_=!0,c.stdin.end(n===void 0?void 0:Buffer.isBuffer(n)?n:Buffer.from(n))}catch(u){c.kill(),p(u)}}};c.stdout.on("data",u=>{S+=u.length,S>m?c.kill():h.push(u)}),c.stderr.on("data",u=>{E.push(u),!_&&Buffer.concat(E).includes(Buffer.from(`secure-git-handoff-ready
149
- `))&&N()}),c.once("error",p),c.once("close",u=>{if(u===0&&S<=m)return a(Buffer.concat(h));const R=Buffer.concat(E).toString("utf8").split(`
150
- `).find(D=>D.startsWith("secure-git-")&&D!=="secure-git-handoff-ready")??(S>m?"secure-git-output-too-large":"secure-git-helper-failed");p(new Error(R))}),f.afterHandoff||N()})}async function q(r,t,e){await y(r,["create-owned-directory",t],Buffer.isBuffer(e)?e:Buffer.from(e))}async function J(r,t,e,i={}){await y(r,["rename-directory",t,e],void 0,i)}async function U(r,t,e={}){await y(r,["remove-directory",t],void 0,e)}async function y(r,t,e,i={}){if(!v(i.platform??process.platform))throw new Error("secure-filesystem-platform-unsupported");const s=await x(r,{bigint:!0});if(!s.isDirectory())throw new Error("secure-filesystem-parent-invalid");if((await w(r,{bigint:!0})).isSymbolicLink())throw new Error("secure-filesystem-parent-symlink");return await i.beforeHandoff?.(),await new Promise((f,d)=>{const o=b(process.execPath,["-e",T,...t.slice(0,1),String(s.dev),String(s.ino),...t.slice(1)],{cwd:r,stdio:["pipe","pipe","pipe"]}),m=[];let a=0;const p=[];o.stdout.on("data",l=>{a+=l.length,a>1024?o.kill():m.push(l)}),o.stderr.on("data",l=>p.push(l)),o.once("error",d),o.once("close",l=>{if(l===0&&a<=1024)return f(Buffer.concat(m));const g=Buffer.concat(p).toString("utf8")||"secure-filesystem-helper-failed",c=new Error(g),h=g.match(/^secure-filesystem-os:(E[A-Z0-9]+)$/)?.[1];h&&(c.code=h),g==="secure-filesystem-entry-exists"&&(c.code="EEXIST"),d(c)}),o.stdin.end(e)})}export{G as anchoredAtomicWriteFile,P as anchoredCompareAndSwapFile,$ as anchoredCreateDirectory,q as anchoredCreateOwnedDirectory,X as anchoredDirectoryIdentity,W as anchoredEnsureDirectory,Y as anchoredExecuteGit,M as anchoredExecuteNode,K as anchoredExecuteNpm,U as anchoredRemoveDirectory,H as anchoredRemoveFile,J as anchoredRenameDirectory,v as secureFilesystemBoundaryAvailable};
159
+ `;function b(t=process.platform){return t!=="win32"}async function j(t,e,r,i={}){const s=`.${e}.${process.pid}.${F(8).toString("hex")}.tmp`;await m(t,["write",e,s],Buffer.isBuffer(r)?r:Buffer.from(r),i)}async function z(t,e,r,i,s={}){const a=`.${e}.${process.pid}.${F(8).toString("hex")}.tmp`;await m(t,["write-cas",e,a,i],Buffer.isBuffer(r)?r:Buffer.from(r),s)}async function Z(t,e,r={}){await m(t,["remove",e],void 0,r)}async function Q(t,e,r={}){await m(t,["mkdir",e],void 0,r)}async function V(t,e){const i=(await m(t,["mkdir-exclusive",e])).toString("utf8").match(/^secure-filesystem-identity:([0-9]+):([0-9]+)$/);if(!i)throw new Error("secure-filesystem-created-identity-missing");return Object.freeze({dev:i[1],ino:i[2]})}async function ee(t){if(!b())throw new Error("secure-filesystem-platform-unsupported");const e=await _(t,{bigint:!0}),r=await I(t,{bigint:!0});if(e.isSymbolicLink()||!e.isDirectory()||!r.isDirectory()||e.dev!==r.dev||e.ino!==r.ino)throw new Error("secure-filesystem-directory-unsafe");return Object.freeze({dev:String(r.dev),ino:String(r.ino)})}async function te(t,e,r,i,s,a={}){return w("git",t,e,r,i,s,a)}async function re(t,e,r,i,s,a={}){return w("node",t,e,r,i,s,a)}async function ie(t,e,r,i,s){if(!Number.isSafeInteger(s.timeoutMs)||s.timeoutMs<=0||!Number.isSafeInteger(s.graceMs)||s.graceMs<=0)throw new Error("secure-git-gate-budget-invalid");return w("node",t,e,r,i,void 0,{},s)}async function se(t,e,r,i){return w("npm",t,e,r,i)}async function w(t,e,r,i,s,a,l={},d){if(!b(l.platform??process.platform))throw new Error("secure-filesystem-platform-unsupported");if(s.length===0||s.length>512||s.some(u=>typeof u!="string"||u.length>4096||u.includes("\0")))throw new Error("secure-git-args-invalid");const c=await I(e,{bigint:!0}),y=await _(e,{bigint:!0});if(!c.isDirectory()||y.isSymbolicLink()||!y.isDirectory()||c.dev!==y.dev||c.ino!==y.ino)throw new Error("secure-filesystem-parent-invalid");await l.beforeHandoff?.();const p=t==="git"?16*1024*1024:64*1024*1024;return await new Promise((u,f)=>{const h=l.afterHandoff?"1":"0",S=Buffer.from(JSON.stringify([...s])).toString("base64url"),o=G(process.execPath,["-e",Y,String(c.dev),String(c.ino),r,i.dev,i.ino,S,h,t,d?"1":"0"],{cwd:e,stdio:["pipe","pipe","pipe"],...d?{env:{...d.env},detached:!0}:{}}),N=[],x=[];let E=0,R=!1;const v=[],O=n=>{try{o.pid!==void 0&&process.kill(-o.pid,n)}catch{o.kill(n)}};d&&v.push(setTimeout(()=>{R=!0,O("SIGTERM"),v.push(setTimeout(()=>O("SIGKILL"),d.graceMs))},d.timeoutMs));const D=()=>{for(const n of v)clearTimeout(n)};let k=!l.afterHandoff,B=!1;const L=async()=>{if(!B){B=!0;try{await l.afterHandoff?.(),k=!0,o.stdin.end(a===void 0?void 0:Buffer.isBuffer(a)?a:Buffer.from(a))}catch(n){o.kill(),f(n)}}};o.stdout.on("data",n=>{E+=n.length,E>p?o.kill():N.push(n)}),o.stderr.on("data",n=>{x.push(n),!k&&Buffer.concat(x).includes(Buffer.from(`secure-git-handoff-ready
160
+ `))&&L()}),o.once("error",n=>{D(),f(n)}),o.once("close",n=>{if(D(),R)return O("SIGKILL"),f(new Error("secure-git-command-timeout"));if(n===0&&E<=p)return u(Buffer.concat(N));const A=Buffer.concat(x).toString("utf8").split(`
161
+ `),P=A.find(g=>g.startsWith("secure-git-")&&g!=="secure-git-handoff-ready"&&!g.startsWith(T))??(E>p?"secure-git-output-too-large":"secure-git-helper-failed"),C=new Error(P);if(d){const g=A.find(H=>H.startsWith(T)),W=g===void 0?"":Buffer.from(g.slice(T.length),"base64url").subarray(-$).toString("utf8");Object.defineProperty(C,M,{value:W,enumerable:!1})}f(C)}),l.afterHandoff||L()})}async function ne(t,e,r){await m(t,["create-owned-directory",e],Buffer.isBuffer(r)?r:Buffer.from(r))}async function oe(t,e,r,i={}){await m(t,["rename-directory",e,r],void 0,i)}async function ce(t,e,r={}){await m(t,["remove-directory",e],void 0,r)}async function m(t,e,r,i={}){if(!b(i.platform??process.platform))throw new Error("secure-filesystem-platform-unsupported");const s=await I(t,{bigint:!0});if(!s.isDirectory())throw new Error("secure-filesystem-parent-invalid");if((await _(t,{bigint:!0})).isSymbolicLink())throw new Error("secure-filesystem-parent-symlink");return await i.beforeHandoff?.(),await new Promise((l,d)=>{const c=G(process.execPath,["-e",X,...e.slice(0,1),String(s.dev),String(s.ino),...e.slice(1)],{cwd:t,stdio:["pipe","pipe","pipe"]}),y=[];let p=0;const u=[];c.stdout.on("data",f=>{p+=f.length,p>1024?c.kill():y.push(f)}),c.stderr.on("data",f=>u.push(f)),c.once("error",d),c.once("close",f=>{if(f===0&&p<=1024)return l(Buffer.concat(y));const h=Buffer.concat(u).toString("utf8")||"secure-filesystem-helper-failed",S=new Error(h),o=h.match(/^secure-filesystem-os:(E[A-Z0-9]+)$/)?.[1];o&&(S.code=o),h==="secure-filesystem-entry-exists"&&(S.code="EEXIST"),d(S)}),c.stdin.end(r)})}export{$ as ANCHORED_GATE_STDERR_TAIL_BYTES,j as anchoredAtomicWriteFile,z as anchoredCompareAndSwapFile,V as anchoredCreateDirectory,ne as anchoredCreateOwnedDirectory,ee as anchoredDirectoryIdentity,Q as anchoredEnsureDirectory,ie as anchoredExecuteGate,te as anchoredExecuteGit,re as anchoredExecuteNode,se as anchoredExecuteNpm,U as anchoredGateStderrTail,ce as anchoredRemoveDirectory,Z as anchoredRemoveFile,oe as anchoredRenameDirectory,b as secureFilesystemBoundaryAvailable};
@@ -0,0 +1,92 @@
1
+ /**
2
+ * @license FSL-1.1
3
+ * Copyright (c) 2026 OrNexus AI
4
+ *
5
+ * P226.03 -- single constructor for the environment of every headless runner
6
+ * child (harness adapter child, anchored continuous-workspace helper and the
7
+ * continuous-workspace complete gate).
8
+ *
9
+ * The child environment is: present minimal names ∪ present declared names
10
+ * (`P205-CI-02-ENV` v1, `config/release-gates.env.v1.json`) ∪ explicit caller
11
+ * overrides ∪ branchless workspace keys. Undeclared parent variables never
12
+ * reach a child. Values are never logged, hashed into receipts or echoed in
13
+ * reason codes; only fixed reason codes and declared names leave this module.
14
+ *
15
+ * The minimal list, contract validation/reading and the minimum ∪ declared
16
+ * projection are owned by P226.01 (`../../git/release-gate-env.ts`, client
17
+ * shadow of `packages/shared/src/release-gate-env-contract.ts`); this module
18
+ * only layers explicit overrides, branchless keys and the gate outcome mapping.
19
+ */
20
+ import { P205_DATASOURCE_MISSING_PREFIX, P205_GATE_ENV_CONTRACT_INVALID, P205_GATE_ENV_CONTRACT_UNDECLARED, type ReleaseGateEnvContract } from '../../git/release-gate-env.js';
21
+ export { P205_DATASOURCE_MISSING_PREFIX, P205_GATE_ENV_CONTRACT_INVALID, P205_GATE_ENV_CONTRACT_UNDECLARED, };
22
+ export declare const HEADLESS_CHILD_ENV_CONTRACT_ID: "P205-CI-02-ENV";
23
+ export declare const HEADLESS_CHILD_ENV_CONTRACT_PATH: "config/release-gates.env.v1.json";
24
+ /** Closed, cross-OS minimal environment forwarded when present (P226.01). */
25
+ export declare const HEADLESS_CHILD_MINIMAL_ENV: readonly string[];
26
+ export type HeadlessChildEnvContract = ReleaseGateEnvContract;
27
+ export type HeadlessChildEnvContractLoad = {
28
+ readonly status: 'declared';
29
+ readonly contract: HeadlessChildEnvContract;
30
+ } | {
31
+ readonly status: 'undeclared';
32
+ } | {
33
+ readonly status: 'invalid';
34
+ readonly reason: typeof P205_GATE_ENV_CONTRACT_INVALID;
35
+ };
36
+ export interface HeadlessChildEnvInput {
37
+ /** Parent environment; injected and never mutated. */
38
+ readonly processEnv: Readonly<Record<string, string | undefined>>;
39
+ readonly platform: NodeJS.Platform | string;
40
+ /** Validated contract or `null` when undeclared/invalid (minimum only). */
41
+ readonly contract?: HeadlessChildEnvContract | null;
42
+ /** Explicit caller overrides (`adapterOptions.env`); defined values win over the projection. */
43
+ readonly explicitEnv?: Readonly<Record<string, string | undefined>>;
44
+ /** Branchless workspace keys; always present and highest precedence. */
45
+ readonly branchless?: Readonly<Record<string, string>>;
46
+ }
47
+ export type HeadlessGateEnvProjection = {
48
+ readonly ok: true;
49
+ readonly env: Readonly<Record<string, string>>;
50
+ readonly debt: readonly string[];
51
+ } | {
52
+ readonly ok: false;
53
+ readonly reason: string;
54
+ };
55
+ /** Closed validator (P226.01); any defect is `invalid` without echoing rejected input. */
56
+ export declare function parseHeadlessChildEnvContract(text: string): HeadlessChildEnvContractLoad;
57
+ /** Reads the versioned contract next to the P205 manifest (P226.01 reader); absence is `undeclared`. */
58
+ export declare function loadHeadlessChildEnvContract(projectRoot: string): Promise<HeadlessChildEnvContractLoad>;
59
+ /**
60
+ * Builds the frozen environment of a headless child. Precedence (later wins):
61
+ * minimum present -> declared present -> explicit overrides -> branchless keys.
62
+ * Missing `required` names are not an error for harness children (they are
63
+ * forwarded when present); the gate path uses `projectHeadlessGateEnv`, which
64
+ * fails closed before spawn.
65
+ */
66
+ export declare function buildHeadlessChildEnv(input: HeadlessChildEnvInput): Readonly<Record<string, string>>;
67
+ /**
68
+ * Gate projection for the continuous-workspace complete gate: same environment
69
+ * as the P205 finalize gate (P226.01 `projectReleaseGateEnv`). Invalid contract
70
+ * and missing required names fail closed with typed reason codes before spawn.
71
+ */
72
+ export declare function projectHeadlessGateEnv(input: {
73
+ readonly processEnv: Readonly<Record<string, string | undefined>>;
74
+ readonly platform: NodeJS.Platform | string;
75
+ readonly contract: HeadlessChildEnvContractLoad;
76
+ }): HeadlessGateEnvProjection;
77
+ export declare const P205_GATE_TIMEOUT: "p205-gate-timeout";
78
+ export declare const P205_GATE_FAILED_PREFIX: "p205-gate-failed:";
79
+ export declare const P205_GATE_FAILED_UNPARSED: "p205-gate-failed";
80
+ /** Manifest budget for the complete gate: worst case + cancellation grace. */
81
+ export declare function completeGateTimeoutMs(manifest: unknown): number;
82
+ /**
83
+ * Maps a failed complete-gate run to a typed reason code from the bounded
84
+ * runner stderr (`[release-gate] <profile>/<class>/<index> ...`). Only the
85
+ * class and index leave this function; stderr content is never echoed.
86
+ * P226.02 owns the finalize-path parser; align once it is integrated
87
+ * (debt `p226-03-gate-parser-align-p226-02`).
88
+ */
89
+ export declare function classifyCompleteGateFailure(input: {
90
+ readonly timedOut: boolean;
91
+ readonly stderr: string;
92
+ }): string;
@@ -0,0 +1 @@
1
+ import{P205_DATASOURCE_MISSING_PREFIX as l,P205_GATE_ENV_CONTRACT_INVALID as a,P205_GATE_ENV_CONTRACT_UNDECLARED as d,RELEASE_GATE_ENV_CONTRACT_ID as i,RELEASE_GATE_ENV_CONTRACT_PATH as A,RELEASE_GATE_MINIMAL_ENV as p,parseReleaseGateEnvContract as C,projectReleaseGateEnv as E,readReleaseGateEnvContract as T}from"../../git/release-gate-env.js";const v=i,D=A,G=p,_=Object.freeze({status:"invalid",reason:a});function u(e){return e.kind==="present"?Object.freeze({status:"declared",contract:e.contract}):e.kind==="absent"?Object.freeze({status:"undeclared"}):_}function S(e){const t=C(e);return t.ok?Object.freeze({status:"declared",contract:t.contract}):_}async function j(e){return u(T(e))}function f(e,t,o,c){if(c){const n=t.toUpperCase();for(const r of Object.keys(e))r!==t&&r.toUpperCase()===n&&delete e[r]}e[t]=o}function m(e){const t=e.platform==="win32",o=e.contract?{...e.contract,required:[],optional:[...e.contract.required,...e.contract.optional]}:null,c=E({contract:o,parentEnv:e.processEnv,platform:e.platform}),n=c.ok?{...c.env}:{};for(const[r,s]of Object.entries(e.explicitEnv??{}))typeof s=="string"&&f(n,r,s,t);for(const[r,s]of Object.entries(e.branchless??{}))typeof s=="string"&&f(n,r,s,t);return Object.freeze(n)}function x(e){if(e.contract.status==="invalid")return Object.freeze({ok:!1,reason:e.contract.reason});const t=E({contract:e.contract.status==="declared"?e.contract.contract:null,parentEnv:e.processEnv,platform:e.platform});return t.ok?Object.freeze({ok:!0,env:t.env,debt:t.debt}):Object.freeze({ok:!1,reason:t.reason})}const N="p205-gate-timeout",O="p205-gate-failed:",b="p205-gate-failed",I=27e5,L=3e5;function H(e){const t=e&&typeof e=="object"?e.budgets:void 0,o=r=>typeof r=="number"&&Number.isSafeInteger(r)&&r>0?r:void 0,c=o(t?.completeGateWorstCaseMs)??I,n=o(t?.cancellationGraceMs)??L;return c+n}function M(e){if(e.timedOut)return N;const t=e.stderr.length>64*1024?e.stderr.slice(-64*1024):e.stderr,o=/\[release-gate\] [a-z0-9-]+\/([a-z0-9-]{1,64})\/(\d{1,4}) /.exec(t);return o?`${O}${o[1]}/${Number(o[2])}`:b}export{v as HEADLESS_CHILD_ENV_CONTRACT_ID,D as HEADLESS_CHILD_ENV_CONTRACT_PATH,G as HEADLESS_CHILD_MINIMAL_ENV,l as P205_DATASOURCE_MISSING_PREFIX,a as P205_GATE_ENV_CONTRACT_INVALID,d as P205_GATE_ENV_CONTRACT_UNDECLARED,O as P205_GATE_FAILED_PREFIX,b as P205_GATE_FAILED_UNPARSED,N as P205_GATE_TIMEOUT,m as buildHeadlessChildEnv,M as classifyCompleteGateFailure,H as completeGateTimeoutMs,j as loadHeadlessChildEnvContract,S as parseHeadlessChildEnvContract,x as projectHeadlessGateEnv};
@@ -1,4 +1,4 @@
1
- import{execFile as wt,spawn as Fe}from"node:child_process";import{createHash as W,randomBytes as Ve}from"node:crypto";import{lstat as ye,readFile as B,realpath as U,stat as gt}from"node:fs/promises";import{basename as $,dirname as j,isAbsolute as ke,join as _,relative as mt,resolve as Qe}from"node:path";import{promisify as St}from"node:util";import{admitPreparedStoryBundle as vt}from"./prepared-story-bundle.js";import{StoryWorktreeManager as It}from"../../git/story-worktree-manager.js";import{acquireGitLifecyclePhysicalIntegrationLock as Rt,assertGitLifecyclePrivateDirectory as G,assertGitLifecyclePrivateFile as F,applyGitLifecycleRuntimeOverlay as ie,computeImmutableStoryQaEvidenceDigest as bt,computeP205StoryQaEvidenceDigest as kt,ensureGitLifecyclePrivateChildDirectory as xe,ensureRuntimeEpic as we,ensureRuntimeStory as xt,gitLifecycleRuntimeDirectory as Ye,mutateGitLifecycleRuntime as X,P205_COMPLETE_COMMAND as Et,readGitLifecycleRuntime as V,releaseGitLifecyclePhysicalIntegrationLock as At,removeGitLifecyclePrivateDirectory as ee,verifyAcceptedGitLifecycleStoryCheckpoint as Ee,verifyGitLifecyclePhysicalIntegrationLock as Ae}from"../../git/git-lifecycle-store.js";import{anchoredAtomicWriteFile as jt,anchoredCreateDirectory as je,anchoredDirectoryIdentity as Ze,anchoredExecuteGit as _e,anchoredEnsureDirectory as _t,anchoredRemoveFile as Dt}from"../../git/secure-filesystem-boundary.js";import{GIT_LIFECYCLE_COMMIT_PUSH_STEP_ID as Ue,GIT_LIFECYCLE_REVIEW_PR_STEP_ID as ge}from"../../git/git-lifecycle-step-ids.js";const De=St(wt),Ot=String.raw`
1
+ import{execFile as wt,spawn as Fe}from"node:child_process";import{createHash as W,randomBytes as Ve}from"node:crypto";import{lstat as ye,readFile as B,realpath as U,stat as gt}from"node:fs/promises";import{basename as $,dirname as j,isAbsolute as ke,join as C,relative as mt,resolve as Qe}from"node:path";import{promisify as St}from"node:util";import{admitPreparedStoryBundle as vt}from"./prepared-story-bundle.js";import{buildHeadlessChildEnv as It,classifyCompleteGateFailure as Rt,completeGateTimeoutMs as bt,loadHeadlessChildEnvContract as kt,projectHeadlessGateEnv as xt}from"./child-env.js";import{StoryWorktreeManager as Et}from"../../git/story-worktree-manager.js";import{acquireGitLifecyclePhysicalIntegrationLock as At,assertGitLifecyclePrivateDirectory as L,assertGitLifecyclePrivateFile as F,applyGitLifecycleRuntimeOverlay as ie,computeImmutableStoryQaEvidenceDigest as jt,computeP205StoryQaEvidenceDigest as Ct,ensureGitLifecyclePrivateChildDirectory as xe,ensureRuntimeEpic as we,ensureRuntimeStory as _t,gitLifecycleRuntimeDirectory as Ye,mutateGitLifecycleRuntime as X,P205_COMPLETE_COMMAND as Dt,readGitLifecycleRuntime as V,releaseGitLifecyclePhysicalIntegrationLock as Ot,removeGitLifecyclePrivateDirectory as ee,verifyAcceptedGitLifecycleStoryCheckpoint as Ee,verifyGitLifecyclePhysicalIntegrationLock as Ae}from"../../git/git-lifecycle-store.js";import{anchoredAtomicWriteFile as Nt,anchoredCreateDirectory as je,anchoredDirectoryIdentity as Ze,anchoredExecuteGit as Ce,anchoredEnsureDirectory as Pt,anchoredRemoveFile as Bt}from"../../git/secure-filesystem-boundary.js";import{GIT_LIFECYCLE_COMMIT_PUSH_STEP_ID as Ue,GIT_LIFECYCLE_REVIEW_PR_STEP_ID as ge}from"../../git/git-lifecycle-step-ids.js";const _e=St(wt),$t=String.raw`
2
2
  const fs = require('node:fs');
3
3
  const cp = require('node:child_process');
4
4
  const [expectedParentDev, expectedParentIno, name, expectedChildDev, expectedChildIno, encoded, handshake] = process.argv.slice(1);
@@ -46,13 +46,13 @@ runtime.on('close', (code, signal) => {
46
46
  if (signal) process.kill(process.pid, signal);
47
47
  else process.exit(Number.isInteger(code) ? code : 1);
48
48
  });
49
- `;function mr(e,r={}){return async(t,o,n={})=>Gt(e,t,o,n,r)}function Ct(e={}){let r=Promise.resolve();return{async prepare(t){if((e.platform??process.platform)==="win32")return d("continuous-sandbox-platform-unsupported");if(!/^[a-f0-9]{64}$/.test(t.dispatchId))return d("continuous-sandbox-dispatch-invalid");if(!oe(t.targetRef))return d("continuous-sandbox-target-invalid");if(!dt(t.executionBranch))return d("continuous-execution-branch-invalid");if(!/^[a-f0-9]{64}$/.test(t.graphRevision))return d("continuous-graph-revision-invalid");const o=st(t.authorizedWriteSet);if(o.length===0||o.length!==t.authorizedWriteSet.length)return d("continuous-authorized-write-set-invalid");const n=Ie(o),i=r;let c=()=>{};r=new Promise(s=>{c=s}),await i;let a,u;try{const s=await et(t.projectRoot),m=await C(s,["rev-parse","HEAD"]),g=await ue(s,t.epicId,t.storyId),I=g.revision,R=await Ye(s),l=await Xe(R,t.dispatchId,(v,y)=>{a=v,u=y},e.beforeSandboxWriteCommit);if(!l.ok)return l;const{leasePath:N}=l.value,b=await xe(R,"sandboxes"),h=_(b,t.dispatchId.slice(0,20)),S=await Ge(h,b);let k,f;const x=S?.preparedAt??new Date().toISOString(),E=S?.workspaceOwnerNonce??Ve(16).toString("hex");if(S){if(S.projectRoot!==s||S.storyId!==t.storyId||S.targetRef!==t.targetRef||S.dispatchId!==t.dispatchId||S.epicId!==t.epicId||S.executionBranch!==t.executionBranch||S.graphRevision!==t.graphRevision||S.claimRevision!==n||S.graphAuthorityRevision!==I||S.graphAuthorityEpoch!==g.epoch||S.graphAuthorityStoryStatus!==g.storyStatus||!ut(S.authorizedWriteSet,o)||(k=S.contextSnapshots.map(v=>({path:v.path,...v.contentBase64!==void 0?{content:Buffer.from(v.contentBase64,"base64")}:{}})),f=await Ze(h),f.dev!==S.workspaceIdentity.dev||f.ino!==S.workspaceIdentity.ino))return d("continuous-sandbox-recovery-mismatch")}else await ee(h,b),f=await je(b,$(h)),await G(h,b),await ae(b,$(h),f,["init","--quiet"]),await Tt(s,h),await zt(s,b,$(h),f),await ae(b,$(h),f,["remote","add","neocortex-root",s]),await ae(b,$(h),f,["fetch","--quiet","--no-tags","neocortex-root",m]),await ae(b,$(h),f,["checkout","--quiet","--detach","FETCH_HEAD"]),k=await $t(s,h,t.epicId,t.targetRef,e.beforeSandboxWriteCommit),await or(h,b,{schemaVersion:1,projectRoot:s,storyId:t.storyId,targetRef:t.targetRef,epicId:t.epicId,executionBranch:t.executionBranch,graphRevision:t.graphRevision,graphAuthorityRevision:I,graphAuthorityEpoch:g.epoch,graphAuthorityStoryStatus:g.storyStatus,authorizedWriteSet:o,claimRevision:n,dispatchId:t.dispatchId,baseSha:m,preparedAt:x,workspaceOwnerNonce:E,workspaceIdentity:f,contextSnapshots:k.map(v=>({path:v.path,...v.content!==void 0?{contentBase64:v.content.toString("base64")}:{}}))},e.beforeSandboxWriteCommit);return a=void 0,{ok:!0,value:{projectRoot:s,workspacePath:h,workspaceStrategy:"branchless_sandbox",storyId:t.storyId,targetRef:t.targetRef,epicId:t.epicId,executionBranch:t.executionBranch,graphRevision:t.graphRevision,graphAuthorityRevision:I,graphAuthorityEpoch:g.epoch,graphAuthorityStoryStatus:g.storyStatus,authorizedWriteSet:o,claimRevision:n,baseSha:S?.baseSha??m,dispatchId:t.dispatchId,preparedAt:x,leasePath:N,leaseOwnerNonce:l.value.owner.nonce,workspaceOwnerNonce:E,workspaceIdentity:f,contextSnapshots:k}}}catch{if(a&&u){const s=a,m=u;await ee(s,j(s),async g=>ht(await ne(g,j(s)),m)).catch(()=>{})}return d("continuous-sandbox-prepare-failed")}finally{c()}},async integrate(t,o){const n=await ne(t.leasePath,j(t.leasePath)).catch(()=>{}),i=await Ge(t.workspacePath,j(t.workspacePath)).catch(()=>{});if(!n||n.nonce!==t.leaseOwnerNonce||i?.workspaceOwnerNonce!==t.workspaceOwnerNonce||i.dispatchId!==t.dispatchId||i.storyId!==t.storyId)return d("continuous-sandbox-owner-mismatch");const c=it(o?.nowIso??new Date().toISOString()),a=await Rt(t.projectRoot,{kind:"continuous",storyId:t.storyId,sessionId:t.dispatchId,idempotencyKey:t.dispatchId,expiresAt:new Date(Date.parse(c)+1800*1e3).toISOString(),persistent:!1,createdAt:c});if(!a.ok)return d(a.reasonCode==="git-lifecycle-integration-backpressure"?"continuous-integration-backpressure":"continuous-integration-lease-failed");let u=[],s=!1,m=!1;try{const g=(await ce(t,["status","--porcelain"])).trimEnd(),I=await Ce(t,["rev-parse","HEAD"]);if(await te(t.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==t.executionBranch)return d("continuous-execution-branch-mismatch");const l=j(j(t.leasePath)),N=await xe(l,"integrated"),b=_(N,t.dispatchId),h=await nr(b,N);if(h?.childHeadSha===I&&h.bundle.storyId===t.storyId&&h.bundle.epicId===t.epicId&&h.bundle.executionBranch===t.executionBranch&&h.bundle.graphRevision===t.graphRevision&&h.bundle.claimRevision===t.claimRevision&&ut(h.bundle.authorizedWriteSet,t.authorizedWriteSet)&&h.checkpoint.idempotencyKey===t.dispatchId&&h.checkpoint.bundleId===h.bundle.bundleId&&h.checkpoint.bundleDigest===h.bundle.bundleDigest&&h.checkpoint.graphRevision===t.graphRevision&&h.checkpoint.claimRevision===t.claimRevision&&await se(t.projectRoot,["merge-base","--is-ancestor",h.rootHeadSha,"HEAD"])&&await ir(t,h.checkpoint))return{ok:!0,value:{headSha:h.rootHeadSha,alreadyIntegrated:!0,bundle:h.bundle,checkpoint:h.checkpoint}};if(I!==t.baseSha)return d("continuous-sandbox-child-git-authority-denied");if(g.length===0)return d("continuous-bundle-empty");const S=g.split(`
50
- `).some(w=>w.length>0&&w[0]!==" "&&w[0]!=="?");S||await Ce(t,["add","-A"]);const k=L(await ce(t,["diff","--cached","--name-only","-z",t.baseSha]));if(k.length===0||k.some(w=>!oe(w)))return d("continuous-integration-write-set-invalid");if(!await Wt(t,["merge-base","--is-ancestor",t.baseSha,I]))return d("continuous-bundle-base-not-ancestor");if(!await se(t.projectRoot,["merge-base","--is-ancestor",t.baseSha,"HEAD"]))return d("continuous-root-base-not-ancestor");const f=o?.nowIso??new Date().toISOString(),x=er(o?.receiptRefs,t.dispatchId),E=await ce(t,["diff","--cached","--binary",t.baseSha]),v={schemaVersion:1,storyId:t.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:t.baseSha,bundleDigest:W("sha256").update(E).digest("hex"),graphRevision:t.graphRevision,claimRevision:t.claimRevision,authorizedWriteSet:t.authorizedWriteSet,contextDigests:Object.fromEntries(t.contextSnapshots.map(w=>[w.path,W("sha256").update(w.content??Buffer.alloc(0)).digest("hex")])),validationRefs:x,createdAt:t.preparedAt,expiresAt:new Date(Date.parse(t.preparedAt)+1440*60*1e3).toISOString(),branchless:!0},y=Object.freeze({...v,bundleId:Ie(v)}),A=await cr(t,y);if(A){const w=await ar(t,y,A);if(w)return await He(b,I,A.headSha,y,w,e.beforeSandboxWriteCommit),{ok:!0,value:{headSha:A.headSha,alreadyIntegrated:!0,bundle:y,checkpoint:w}}}if(!A&&await Xt(t.projectRoot,t.epicId)!==t.graphAuthorityRevision)return d("continuous-graph-revision-stale");if(A){const w=await nt({lease:t,bundle:y,baseSha:A.baseSha,headSha:A.headSha,receiptRefs:x,nowIso:f,qaRunner:e.storyQaRunner});if(!w.ok)return w;await e.beforeCheckpointPersist?.({projectRoot:t.projectRoot,storyId:t.storyId,headSha:A.headSha});const D=await ot({lease:t,physicalLock:a,checkpointAuthority:A.checkpointAuthority,bundle:y,baseSha:A.baseSha,headSha:A.headSha,receiptRefs:[...x,`bundle:${y.bundleId}`,w.value.qaReceipt.receiptRef,w.value.reviewReceipt.receiptRef],qaReceipt:w.value.qaReceipt,reviewReceipt:w.value.reviewReceipt,recordedAt:f,checkpointNow:e.checkpointNow,insideCheckpointPreCommit:e.insideCheckpointPreCommit,afterCheckpointPersist:e.afterCheckpointPersist});return D.ok?(await He(b,I,A.headSha,y,D.value,e.beforeSandboxWriteCommit),{ok:!0,value:{headSha:A.headSha,alreadyIntegrated:!0,bundle:y,checkpoint:D.value}}):D}if(S)return d("continuous-sandbox-child-git-authority-denied");if(L(await z(t.projectRoot,["diff","--cached","--name-only","-z"])).length>0)return d("continuous-integration-root-index-dirty");const J=new Set(t.contextSnapshots.map(w=>w.path));if(k.filter(w=>!t.authorizedWriteSet.some(D=>ve(D,w))).length>0)return d("continuous-bundle-write-set-unauthorized");const M=k.filter(w=>!J.has(w)),be=new Set(L(await z(t.projectRoot,["diff","--name-only","-z",`${t.baseSha}..HEAD`])));if(M.some(w=>be.has(w)))return d("continuous-bundle-intervening-conflict");const fe=new Set([...L(await z(t.projectRoot,["diff","--name-only","-z"])),...L(await z(t.projectRoot,["ls-files","--others","--exclude-standard","-z"]))]);if(M.some(w=>fe.has(w)))return d("continuous-integration-root-conflict");u=await Mt(t.projectRoot,[...new Set([...k,".neocortex/state.json"])]);const H=await Kt(t,f);if(!H.ok)return H;const K=vt({bundle:y,payload:Buffer.from(E),expected:{epicId:t.epicId,storyId:t.storyId,executionBranch:t.executionBranch,baseSha:t.baseSha,graphRevision:t.graphRevision,claimRevision:t.claimRevision,authorizedWriteSet:t.authorizedWriteSet,nowIso:f},writerLease:H.value});if(K.length>0)return await Be(t.projectRoot,u),d(`continuous-bundle-admission-${K[0]}`);const pe=await C(t.projectRoot,["rev-parse","HEAD"]);let Q;await e.beforeRootCommit?.({projectRoot:t.projectRoot,storyId:t.storyId,headSha:pe});try{await X(t.projectRoot,w=>{const D=p(we(w,t.epicId).branch_lease);if(D?.ownerStoryId!==t.storyId||D.sessionId!==t.dispatchId||D.idempotencyKey!==t.dispatchId||Date.parse(String(D.expiresAt))<=Date.now())throw new Error("continuous-checkpoint-writer-lease-lost")},{preCommit:async w=>{const D=await ue(t.projectRoot,t.epicId,t.storyId,w);if(D.revision!==t.graphAuthorityRevision||D.epoch!==t.graphAuthorityEpoch||D.storyStatus!==t.graphAuthorityStoryStatus)throw new Error("continuous-graph-revision-stale");if(!await Ae(a.path,a.owner))throw new Error("continuous-integration-lock-raced");const ft=await te(t.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]),pt=await C(t.projectRoot,["rev-parse","HEAD"]);if(ft!==t.executionBranch||pt!==pe)throw new Error("continuous-integration-head-raced");const lt=L(await z(t.projectRoot,["diff","--cached","--name-only","-z"])),yt=new Set([...L(await z(t.projectRoot,["diff","--name-only","-z"])),...L(await z(t.projectRoot,["ls-files","--others","--exclude-standard","-z"]))]);if(lt.length>0)throw new Error("continuous-integration-root-index-dirty");if(M.some(P=>yt.has(P)))throw new Error("continuous-integration-root-conflict");if(m=!0,M.length>0){const P=await ce(t,["diff","--cached","--binary",t.baseSha,"--",...M]);if(P.length>0&&!await qt(t.projectRoot,["apply","--index","--3way","--whitespace=nowarn"],P))throw new Error("continuous-integration-conflict")}for(const P of t.contextSnapshots){if(!k.includes(P.path))continue;const Je=await Ne(_(t.projectRoot,P.path)),Me=await Lt(t,P.path),Ke=P.path===".neocortex/state.json"?Zt(P.content,Je,Vt(P.content,Me,t.storyId)):Yt(P.content,Je,Me);if(!Ke.ok)throw new Error(P.path===".neocortex/state.json"?"continuous-state-merge-conflict":"continuous-context-merge-conflict");await re(t.projectRoot,P.path,Ke.value),await C(t.projectRoot,["add","-A","--",P.path])}if(k.includes(".neocortex/state.json")&&await C(t.projectRoot,["add","-A","--",".neocortex/state.json"]),await se(t.projectRoot,["diff","--cached","--quiet"]))throw new Error("continuous-integration-empty-after-admission");Q=await ue(t.projectRoot,t.epicId,t.storyId,w),await C(t.projectRoot,["commit","-m",`feat(yoloop): integrate ${t.storyId}`,"-m",`Neocortex-Story: ${t.storyId}`,"-m",`Neocortex-Epic: ${t.epicId}`,"-m",`Neocortex-Execution-Branch: ${t.executionBranch}`,"-m",`Neocortex-Prepared-Base: ${t.baseSha}`,"-m",`Neocortex-Dispatch: ${t.dispatchId}`,"-m",`Neocortex-Bundle: ${y.bundleId}`,"-m",`Neocortex-Bundle-Digest: ${y.bundleDigest}`,"-m",`Neocortex-Graph-Revision: ${t.graphRevision}`,"-m",`Neocortex-Claim-Revision: ${t.claimRevision}`,"-m",`Neocortex-Checkpoint-Authority: ${Q.revision}`,"-m",`Neocortex-Checkpoint-Epoch: ${Q.epoch??"null"}`,"-m",`Neocortex-Checkpoint-Story-Status: ${Q.storyStatus??"null"}`]),s=!0}})}catch(w){m&&!s&&await Be(t.projectRoot,u);const D=w instanceof Error&&/^continuous-/.test(w.message)?w.message:"continuous-integration-failed";return d(D)}const Y=await C(t.projectRoot,["rev-parse","HEAD"]);if(!Q)return d("continuous-checkpoint-authority-missing");await e.afterRootCommit?.({projectRoot:t.projectRoot,storyId:t.storyId,headSha:Y});const Z=await nt({lease:t,bundle:y,baseSha:pe,headSha:Y,receiptRefs:x,nowIso:f,qaRunner:e.storyQaRunner});if(!Z.ok)return Z;await e.beforeCheckpointPersist?.({projectRoot:t.projectRoot,storyId:t.storyId,headSha:Y});const le=await ot({lease:t,physicalLock:a,checkpointAuthority:Q,bundle:y,baseSha:pe,headSha:Y,receiptRefs:[...x,`bundle:${y.bundleId}`,Z.value.qaReceipt.receiptRef,Z.value.reviewReceipt.receiptRef],qaReceipt:Z.value.qaReceipt,reviewReceipt:Z.value.reviewReceipt,recordedAt:f,checkpointNow:e.checkpointNow,insideCheckpointPreCommit:e.insideCheckpointPreCommit,afterCheckpointPersist:e.afterCheckpointPersist});return le.ok?(await He(b,I,Y,y,le.value,e.beforeSandboxWriteCommit),{ok:!0,value:{headSha:Y,alreadyIntegrated:!1,bundle:y,checkpoint:le.value}}):le}catch{return m&&!s&&u.length>0&&await Be(t.projectRoot,u),d("continuous-integration-failed")}finally{await Ft(t).catch(()=>{}),await At(a.path,a.owner).catch(()=>{})}},async release(t,o){o||await ee(t.workspacePath,j(t.workspacePath),async n=>{const i=await Ge(n,j(t.workspacePath)).catch(()=>{});return i?.workspaceOwnerNonce===t.workspaceOwnerNonce&&i.dispatchId===t.dispatchId&&i.storyId===t.storyId}),await ee(t.leasePath,j(t.leasePath),async n=>(await ne(n,j(t.leasePath)).catch(()=>{}))?.nonce===t.leaseOwnerNonce)}}}const Nt="story-worktree-integration-root-owned";function Pt(e={}){const r=e.storyWorktrees??(o=>new It({projectRoot:o}));let t=Promise.resolve();return{async prepare(o){if(!/^[a-f0-9]{64}$/.test(o.dispatchId))return d("continuous-sandbox-dispatch-invalid");if(!oe(o.targetRef))return d("continuous-sandbox-target-invalid");if(!dt(o.executionBranch))return d("continuous-execution-branch-invalid");if(!/^[a-f0-9]{64}$/.test(o.graphRevision))return d("continuous-graph-revision-invalid");const n=st(o.authorizedWriteSet);if(n.length===0||n.length!==o.authorizedWriteSet.length)return d("continuous-authorized-write-set-invalid");const i=Ie(n),c=t;let a=()=>{};t=new Promise(s=>{a=s}),await c;let u;try{const s=await et(o.projectRoot),m=await C(s,["rev-parse","--verify",`refs/heads/${o.executionBranch}^{commit}`]),g=await ue(s,o.epicId,o.storyId),I=await Ye(s),R=await Xe(I,o.dispatchId,(h,S)=>{u={leasePath:h,owner:S}},e.beforeSandboxWriteCommit);if(!R.ok)return R;const l=await r(s).create({epicId:o.epicId,storyId:o.storyId,dispatchId:o.dispatchId,baseSha:m,graphRevision:o.graphRevision});if(!l.ok||!l.privatePath||!ke(l.privatePath))return u=void 0,await Oe(R.value.leasePath,R.value.owner.nonce).catch(()=>{}),d(l.ok?"story-worktree-path-unavailable":l.reasonCode);const N=Qe(l.privatePath),b=await Ze(N);return u=void 0,{ok:!0,value:{projectRoot:s,workspacePath:N,workspaceStrategy:"story_worktree",storyWorktreeLeaseId:l.value.lease.leaseId,storyId:o.storyId,targetRef:o.targetRef,epicId:o.epicId,executionBranch:o.executionBranch,graphRevision:o.graphRevision,graphAuthorityRevision:g.revision,graphAuthorityEpoch:g.epoch,graphAuthorityStoryStatus:g.storyStatus,authorizedWriteSet:n,claimRevision:i,baseSha:l.value.baseSha,preparedAt:new Date().toISOString(),dispatchId:o.dispatchId,leasePath:R.value.leasePath,leaseOwnerNonce:R.value.owner.nonce,workspaceOwnerNonce:R.value.owner.nonce,workspaceIdentity:b,contextSnapshots:[]}}}catch{const s=u;return s&&await Oe(s.leasePath,s.owner.nonce).catch(()=>{}),d("story-worktree-prepare-failed")}finally{a()}},async integrate(o){return o.workspaceStrategy!=="story_worktree"?d("continuous-workspace-strategy-mismatch"):d(Nt)},async release(o){await Oe(o.leasePath,o.leaseOwnerNonce)}}}function Bt(e){const r=e&&typeof e=="object"&&!Array.isArray(e)?e:void 0;return r?.version===4&&r.mode==="two_phase_worktree_dag"&&r.authorization==="server_authorized"&&r.workspaceMechanism==="client_managed_worktree"?"story_worktree":"branchless_sandbox"}function Sr(e,r={}){const t=Bt(e);return t==="story_worktree"?{strategy:t,manager:r.storyWorktree??Pt()}:{strategy:t,manager:r.branchless??Ct()}}async function Xe(e,r,t,o){const n=await xe(e,"leases"),i=_(n,r);try{await je(n,r),await G(i,n)}catch(a){if(!q(a,"EEXIST"))throw a;await G(i,n);const u=await ne(i,n);if(u!==void 0&&rr(u.pid))return d("continuous-sandbox-lease-active");if(!u||!await ee(i,n,async s=>ht(await ne(s,n),u)))return d("continuous-sandbox-lease-owner-replaced");await je(n,r),await G(i,n)}const c=Object.freeze({pid:process.pid,createdAt:new Date().toISOString(),nonce:Ve(16).toString("hex")});return t(i,c),await re(i,"owner.json",Buffer.from(JSON.stringify(c)),o),await F(_(i,"owner.json"),i),{ok:!0,value:{leasePath:i,owner:c}}}async function Oe(e,r){await ee(e,j(e),async t=>(await ne(t,j(e)).catch(()=>{}))?.nonce===r)}async function $t(e,r,t,o,n){const i=[...new Set([".neocortex/state.json",o,`docs/epics/epic-${tr(t)}.md`])],c=[];for(const a of i){if(!oe(a))continue;const u=await Ne(_(e,a));c.push({path:a,...u!==void 0?{content:u}:{}}),u!==void 0&&await re(r,a,u,n)}return c}async function et(e){const r=await C(e,["rev-parse","--show-toplevel"]),[t,o]=await Promise.all([U(r),U(e)]);if(t!==o)throw new Error("project root mismatch");return t}async function zt(e,r,t,o){for(const n of["user.name","user.email"]){const i=await te(e,["config","--get",n]);i&&await ae(r,t,o,["config",n,i])}}async function Tt(e,r){const t=await V(e);await X(r,o=>{for(const[n,i]of Object.entries(t.epics))o.epics[n]={...structuredClone(i),branch_lease:null};for(const[n,i]of Object.entries(t.stories))o.stories[n]=structuredClone(i)})}async function ae(e,r,t,o){return(await _e(e,r,t,o)).toString("utf8").trim()}async function ce(e,r){return(await _e(j(e.workspacePath),$(e.workspacePath),e.workspaceIdentity,r)).toString("utf8")}async function Ce(e,r){return(await ce(e,r)).trim()}async function Wt(e,r){try{return await Ce(e,r),!0}catch{return!1}}async function Lt(e,r){try{return await _e(j(e.workspacePath),$(e.workspacePath),e.workspaceIdentity,["show",`:${r}`])}catch{return}}async function Gt(e,r,t,o,n){const i=Date.now(),c=R=>({exitCode:null,timedOut:!1,durationMs:Date.now()-i,stdout:"",stderr:"",stdoutBytes:0,stderrBytes:0,...R});if(o.signal?.aborted)return c({signal:"SIGTERM",cancelled:!0});if(!r||r.length>4096||r.includes("\0")||t.length>512||t.some(R=>R.length>32768||R.includes("\0")))return c({exitCode:73,stderr:"continuous-child-invocation-invalid",stderrBytes:35});const a=j(e.workspacePath),u=await ye(a,{bigint:!0}),s=await gt(a,{bigint:!0});if(!u.isDirectory()||u.isSymbolicLink()||!s.isDirectory()||u.dev!==s.dev||u.ino!==s.ino)return c({exitCode:73,stderr:"continuous-child-parent-invalid",stderrBytes:31});await n.beforeHandoff?.();const m=Buffer.from(JSON.stringify({command:r,args:[...t]})).toString("base64url"),g=o.maxOutputBytes??64e3,I=Math.max(1,Math.min(o.timeoutMs??600*1e3,1800*1e3));return await new Promise(R=>{const l=Fe(process.execPath,["-e",Ot,String(s.dev),String(s.ino),$(e.workspacePath),e.workspaceIdentity.dev,e.workspaceIdentity.ino,m,n.afterHandoff?"1":"0"],{cwd:a,env:o.env,stdio:["pipe","pipe","pipe"]});let N="",b="",h=0,S=0,k=!1,f=!1,x=!1,E=!n.afterHandoff;const v=(O,J)=>{k||(k=!0,clearTimeout(A),o.signal?.removeEventListener("abort",y),R({exitCode:O,...J?{signal:J}:{},timedOut:f,...x?{cancelled:!0}:{},durationMs:Date.now()-i,stdout:N,stderr:b,stdoutBytes:h,stderrBytes:S}))},y=()=>{x=!0,l.kill("SIGTERM")};o.signal?.addEventListener("abort",y,{once:!0});const A=setTimeout(()=>{f=!0,l.kill("SIGTERM")},I);l.stdout.on("data",O=>{h+=O.length,h+S>g?l.kill("SIGTERM"):N+=O.toString("utf8")}),l.stderr.on("data",O=>{S+=O.length,h+S>g?l.kill("SIGTERM"):b+=O.toString("utf8"),!E&&b.includes(`continuous-child-handoff-ready
51
- `)&&(E=!0,Promise.resolve(n.afterHandoff?.()).then(()=>l.stdin.end()).catch(()=>l.kill("SIGTERM")))}),l.once("error",()=>v(null)),l.once("close",(O,J)=>v(O,J)),n.afterHandoff||l.stdin.end()})}async function C(e,r){return(await z(e,r)).trim()}async function z(e,r){const t=await De("git",r,{cwd:e,encoding:"utf8",maxBuffer:16777216});return String(t.stdout)}async function te(e,r){try{return await C(e,r)}catch(t){if(q(t,"ENOENT"))return;throw t}}async function se(e,r){try{return await C(e,r),!0}catch{return!1}}async function qt(e,r,t){return await new Promise(o=>{const n=Fe("git",[...r],{cwd:e,stdio:["pipe","ignore","ignore"]});n.once("error",()=>o(!1)),n.once("close",i=>o(i===0)),n.stdin.end(t)})}async function vr(e,r,t){try{const o=await De("git",["show",`${r}:${t}`],{cwd:e,encoding:"buffer",maxBuffer:16777216});return Buffer.from(o.stdout)}catch(o){if(q(o,"ENOENT"))return;throw o}}async function Ne(e){try{return await B(e)}catch(r){if(q(r,"ENOENT"))return;throw r}}async function re(e,r,t,o){const n=de(r);if(!oe(n))throw new Error("continuous-sandbox-write-path-invalid");const i=await U(e);if(i!==Qe(e))throw new Error("continuous-sandbox-write-root-symlink");const c=j(n)==="."?"":j(n),a=await Ht(i,c),u=await tt(a),s=_(a,$(n));if(await me(s,i,!0),t===void 0){await o?.({boundaryRoot:i,relativePath:n,destinationPath:s}),await rt(a,i,u),await me(s,i,!0),await Dt(a,$(n));return}await o?.({boundaryRoot:i,relativePath:n,destinationPath:s}),await rt(a,i,u),await me(s,i,!0),await jt(a,$(n),t),await me(s,i,!1)}async function Ht(e,r){let t=e;for(const o of r.split("/").filter(Boolean)){t=_(t,o),await _t(j(t),$(t));const n=await ye(t);if(!n.isDirectory()||n.isSymbolicLink()||await U(t)!==t)throw new Error("continuous-sandbox-write-component-unsafe");Pe(e,t)}return t}async function me(e,r,t){Pe(r,e);try{const o=await ye(e);if(o.isSymbolicLink()||!o.isFile())throw new Error("continuous-sandbox-write-destination-unsafe");if(await U(e)!==e)throw new Error("continuous-sandbox-write-destination-symlink")}catch(o){if(t&&q(o,"ENOENT"))return;throw o}}function Pe(e,r){const t=mt(e,r);if(t===""||t.startsWith("..")||ke(t))throw new Error("continuous-sandbox-write-containment-invalid")}async function tt(e){const r=await ye(e,{bigint:!0});if(!r.isDirectory()||r.isSymbolicLink())throw new Error("continuous-sandbox-write-parent-unsafe");return{dev:r.dev,ino:r.ino}}async function Jt(e,r,t){try{if(e!==r&&Pe(r,e),await U(e)!==e)return!1;const o=await tt(e);return o.dev===t.dev&&o.ino===t.ino}catch{return!1}}async function rt(e,r,t){if(!await Jt(e,r,t))throw new Error("continuous-sandbox-write-parent-raced")}async function Mt(e,r){return await Promise.all(r.map(async t=>{const o=await Ne(_(e,t));return{path:t,...o!==void 0?{content:o}:{}}}))}async function Be(e,r){const t=r.map(o=>o.path);t.length>0&&await se(e,["reset","--quiet","HEAD","--",...t]);for(const o of r)await re(e,o.path,o.content)}async function Kt(e,r){try{const t=_(e.projectRoot,".neocortex/state.json"),o=T(JSON.parse((await B(t)).toString("utf8"))),n=p(p(o.epics)?.[e.epicId]),i=p(n?.branch_lease),c=Object.freeze({schemaVersion:1,ownerStoryId:e.storyId,sessionId:e.dispatchId,idempotencyKey:e.dispatchId,acquiredAt:r,expiresAt:new Date(Date.parse(r)+600*1e3).toISOString()});let a=!1;return await X(e.projectRoot,u=>{const s=we(u,e.epicId),m=p(s.branch_lease)??i;if(m&&typeof m.expiresAt=="string"&&m.expiresAt>r&&(m.ownerStoryId!==e.storyId||m.idempotencyKey!==e.dispatchId)){a=!0;return}s.branch_mode="epic",s.execution_branch=e.executionBranch,s.branch_lease=c}),a?d("continuous-epic-checkout-writer-active"):{ok:!0,value:c}}catch{return d("continuous-writer-lease-persist-failed")}}async function Ft(e){await X(e.projectRoot,r=>{const t=we(r,e.epicId),o=p(t.branch_lease);o?.ownerStoryId===e.storyId&&o.idempotencyKey===e.dispatchId&&(t.branch_lease=null)})}async function ot(e){try{const r=_(e.lease.projectRoot,".neocortex/state.json"),t=Object.freeze({schemaVersion:1,storyId:e.lease.storyId,epicId:e.lease.epicId,branch:e.lease.executionBranch,baseSha:e.baseSha,headSha:e.headSha,commits:Object.freeze([e.headSha]),idempotencyKey:e.lease.dispatchId,dispatchId:e.lease.dispatchId,bundleId:e.bundle.bundleId,bundleDigest:e.bundle.bundleDigest,graphRevision:e.lease.graphRevision,claimRevision:e.lease.claimRevision,receiptRefs:Object.freeze([...new Set(e.receiptRefs)]),qaVerdict:"passed",reviewVerdict:"approved",qaReceipt:e.qaReceipt,reviewReceipt:e.reviewReceipt,recordedAt:e.recordedAt}),o=T(JSON.parse((await B(r)).toString("utf8"))),n=p(p(o.stories)?.[e.lease.storyId]);let i="persisted",c,a,u,s,m=!1,g;const I=async(f,x,E)=>{const v=await te(e.lease.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]),y=await C(e.lease.projectRoot,["rev-parse","HEAD"]);if(v!==e.lease.executionBranch||y!==e.headSha)throw new Error("continuous-checkpoint-head-raced");if(f.graphRevision!==e.lease.graphRevision||f.claimRevision!==e.lease.claimRevision||f.bundleId!==e.bundle.bundleId||f.bundleDigest!==e.bundle.bundleDigest)throw new Error("continuous-checkpoint-graph-raced");const A=E??T(JSON.parse((await B(r)).toString("utf8"))),O=ie(A,x??await V(e.lease.projectRoot)),J=p(p(O.epics)?.[e.lease.epicId]),Re=p(p(O.stories)?.[e.lease.storyId]),M=Array.isArray(Re?.depends_on)?Re.depends_on.filter(H=>typeof H=="string"):[],be=p(O.stories);if(J?.execution_branch!==e.lease.executionBranch||M.some(H=>{const K=p(be?.[H]);return!K||!["done","completed","merged"].includes(String(K.status))}))throw new Error("continuous-checkpoint-dependency-raced");const fe=L(await z(e.lease.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",e.headSha]));if(fe.length===0||fe.some(H=>!e.lease.authorizedWriteSet.some(K=>ve(K,H))))throw new Error("continuous-checkpoint-write-set-raced");if(!await Ee(e.lease.projectRoot,f,e.lease.storyId,e.lease.epicId,e.lease.executionBranch,void 0,e.lease.authorizedWriteSet))throw new Error("continuous-checkpoint-receipt-revalidation-failed")},R=await V(e.lease.projectRoot,{required:!0}),l=p(p(R.epics[e.lease.epicId])?.branch_lease);if(l?.ownerStoryId!==e.lease.storyId||l.idempotencyKey!==e.lease.dispatchId||l.sessionId!==e.lease.dispatchId||typeof l.expiresAt!="string"||Date.parse(l.expiresAt)<=(e.checkpointNow?.("before-mutation")??Date.now()))return d("continuous-checkpoint-writer-lease-lost");if(!await Ae(e.physicalLock.path,e.physicalLock.owner))return d("continuous-checkpoint-integration-lock-raced");const N=await B(r),b=W("sha256").update(N).digest("hex");await I(t,R);const h=We(T(JSON.parse(N.toString("utf8"))),R,e.lease.epicId,e.lease.storyId);if(h.revision!==e.checkpointAuthority.revision||h.epoch!==e.checkpointAuthority.epoch||h.storyStatus!==e.checkpointAuthority.storyStatus)return d("continuous-graph-revision-stale");const S=await X(e.lease.projectRoot,f=>{const x=we(f,e.lease.epicId),E=p(x.branch_lease);a=E===void 0?void 0:structuredClone(E),u=structuredClone(f),m=f.stories[e.lease.storyId]!==void 0,s=structuredClone(f.stories[e.lease.storyId]??{}),g=structuredClone(x.branch_lease);const v=xt(f,e.lease.storyId),y=p(v.checkpoint)??p(n?.checkpoint);if(y?.idempotencyKey===e.lease.dispatchId){y.baseSha!==e.baseSha||y.headSha!==e.headSha||y.bundleId!==e.bundle.bundleId||y.bundleDigest!==e.bundle.bundleDigest||y.graphRevision!==e.lease.graphRevision||y.claimRevision!==e.lease.claimRevision?i="conflict":(i="reused",c=y,x.branch_lease=null);return}if(E?.ownerStoryId!==e.lease.storyId||E.idempotencyKey!==e.lease.dispatchId||E.sessionId!==e.lease.dispatchId){i="lease-lost";return}v.checkpoint=t,v.status="done",v.last_step=ge;const A=Array.isArray(v.steps_completed)?v.steps_completed.filter(O=>typeof O=="string"):[];v.steps_completed=[...new Set([...A,Ue,ge])],x.branch_lease=null},{expectedRevision:R.revision,preCommit:async f=>{if(a?.ownerStoryId!==e.lease.storyId||a.idempotencyKey!==e.lease.dispatchId||a.sessionId!==e.lease.dispatchId||typeof a.expiresAt!="string"||Date.parse(a.expiresAt)<=(e.checkpointNow?.("pre-commit")??Date.now()))throw new Error("continuous-checkpoint-writer-lease-lost");if(await e.insideCheckpointPreCommit?.({projectRoot:e.lease.projectRoot,storyId:e.lease.storyId,headSha:e.headSha}),!await Ae(e.physicalLock.path,e.physicalLock.owner))throw new Error("continuous-checkpoint-integration-lock-raced");await I(c??t,f);const x=await B(r);if(W("sha256").update(x).digest("hex")!==b)throw new Error("continuous-graph-revision-stale");if(!u)throw new Error("continuous-checkpoint-authority-missing");const E=T(JSON.parse(x.toString("utf8"))),v=We(E,u,e.lease.epicId,e.lease.storyId);if(v.revision!==e.checkpointAuthority.revision||v.epoch!==e.checkpointAuthority.epoch||v.storyStatus!==e.checkpointAuthority.storyStatus)throw new Error("continuous-graph-revision-stale");if(i==="persisted"&&!Le(E,f,e.lease,t))throw new Error("continuous-checkpoint-projection-raced")}}),k=i;if(k==="conflict")return d("continuous-checkpoint-idempotency-conflict");if(k==="lease-lost")return d("continuous-checkpoint-writer-lease-lost");if(k==="reused"&&c)try{return await I(c),{ok:!0,value:c}}catch{return d("continuous-checkpoint-reused-evidence-invalid")}try{await e.afterCheckpointPersist?.({projectRoot:e.lease.projectRoot,storyId:e.lease.storyId,headSha:e.headSha});const f=await V(e.lease.projectRoot,{required:!0});if(f.revision!==S.document.revision)throw new Error("continuous-checkpoint-post-persist-runtime-raced");await I(t,f);const x=await B(r);if(W("sha256").update(x).digest("hex")!==b)throw new Error("continuous-checkpoint-post-persist-authority-raced");const E=T(JSON.parse(x.toString("utf8")));if(!Le(E,f,e.lease,t))throw new Error("continuous-checkpoint-post-persist-projection-raced")}catch{const f=await B(r).catch(()=>{}),x=f===void 0||W("sha256").update(f).digest("hex")!==b;return await X(e.lease.projectRoot,E=>{const v=p(E.epics[e.lease.epicId]),y=p(E.stories[e.lease.storyId]),A=f===void 0?void 0:T(JSON.parse(f.toString("utf8")));if(!v||!y||!A||!Le(A,E,e.lease,t))throw new Error("continuous-checkpoint-cleanup-cas-conflict");if(x){m?Ut(y,s??{}):delete E.stories[e.lease.storyId],g===void 0?delete v.branch_lease:v.branch_lease=structuredClone(g);return}y.checkpoint=null,y.status="blocked",v.branch_lease=null},{expectedRevision:S.document.revision}).catch(()=>{}),d("continuous-checkpoint-post-persist-raced")}return{ok:!0,value:t}}catch(r){const t=r instanceof Error&&/^continuous-/.test(r.message)?r.message:"continuous-checkpoint-persist-failed";return d(t)}}async function nt(e){try{if(await C(e.lease.projectRoot,["rev-parse","HEAD"])!==e.headSha)return d("continuous-story-evidence-head-raced");const r=await B(_(e.lease.projectRoot,"config","release-gates.v2.json"),"utf8"),t=JSON.parse(r),o=Array.isArray(t.requiredCompleteClasses)?t.requiredCompleteClasses.filter(k=>typeof k=="string"&&/^[a-z0-9-]+$/.test(k)):[];if(t.contract!=="P205-CI-02"||o.length===0)return d("continuous-story-qa-manifest-invalid");const n=String((await De(process.execPath,["scripts/test-root.mjs","--gate","complete"],{cwd:e.lease.projectRoot,encoding:"utf8",maxBuffer:32*1024*1024})).stdout);if(await e.qaRunner?.({projectRoot:e.lease.projectRoot,storyId:e.lease.storyId,headSha:e.headSha}),await C(e.lease.projectRoot,["rev-parse","HEAD"])!==e.headSha)return d("continuous-story-qa-head-raced");const i=it(e.nowIso),c=await C(e.lease.projectRoot,["rev-list","--count",`${e.baseSha}..${e.headSha}`]),a=await z(e.lease.projectRoot,["show","--no-patch","--format=%H%n%P%n%B",e.headSha]),u=L(await z(e.lease.projectRoot,["diff","--name-only","-z",`${e.baseSha}..${e.headSha}`])),s=bt({storyId:e.lease.storyId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundle.bundleDigest,graphRevision:e.lease.graphRevision,commitBody:a,changedPaths:u}),m=W("sha256").update(r).digest("hex"),g=W("sha256").update(n).digest("hex"),I=kt({gitEvidenceDigest:s,headSha:e.headSha,graphRevision:e.lease.graphRevision,manifestDigest:m,gateIds:o,resultDigest:g}),R=`story-qa:${I}`,l=Object.freeze({schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",evidenceVersion:"p205-execution-v2",storyId:e.lease.storyId,epicId:e.lease.epicId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundle.bundleDigest,graphRevision:e.lease.graphRevision,contract:"P205-CI-02",command:Et,manifestDigest:m,gateIds:Object.freeze(o),resultDigest:g,sourceEvidenceDigest:I,verdict:"passed",checkedAt:i,receiptRef:R}),N=[`Neocortex-Story: ${e.lease.storyId}`,`Neocortex-Epic: ${e.lease.epicId}`,`Neocortex-Bundle-Digest: ${e.bundle.bundleDigest}`,`Neocortex-Graph-Revision: ${e.lease.graphRevision}`];if(c!=="1"||!N.every(k=>a.includes(k))||u.length===0||u.some(k=>!e.lease.authorizedWriteSet.some(f=>ve(f,k))))return d("continuous-story-review-evidence-rejected");const b=W("sha256").update(["root-commit-range-review-v1",e.lease.storyId,e.baseSha,e.headSha,e.bundle.bundleDigest,e.lease.graphRevision,R,W("sha256").update(a).digest("hex"),[...u].sort().join(",")].join("\0")).digest("hex"),h=`story-review:${b}`,S=Object.freeze({schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:e.lease.storyId,epicId:e.lease.epicId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundle.bundleDigest,graphRevision:e.lease.graphRevision,sourceEvidenceDigest:b,qaReceiptRef:R,verdict:"approved",reviewedAt:i,receiptRef:h});return{ok:!0,value:{qaReceipt:l,reviewReceipt:S}}}catch{return d("continuous-story-evidence-production-failed")}}function it(e){return Number.isFinite(Date.parse(e))?new Date(Date.parse(e)).toISOString():new Date().toISOString()}function Vt(e,r,t){if(r!==void 0)try{const o=e===void 0?{}:T(JSON.parse(e.toString("utf8"))),n=T(JSON.parse(r.toString("utf8"))),i=structuredClone(o),c=p(p(o.stories)?.[t]),a=p(p(n.stories)?.[t]),u=Qt(i,"stories"),s=structuredClone(c??{});for(const m of["status","last_step","steps_completed","last_updated","blocked_reason","blocked_at","implementation_evidence","validation_evidence","qa_gate"])a&&Object.prototype.hasOwnProperty.call(a,m)&&(s[m]=structuredClone(a[m]));return u[t]=s,Buffer.from(`${JSON.stringify(i,null,2)}
52
- `)}catch{return Buffer.from("{invalid-child-state")}}function Qt(e,r){const t=p(e[r]);if(t)return t;const o={};return e[r]=o,o}function T(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("record expected");return e}function p(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Yt(e,r,t){return Te(t,e)||Te(r,t)?{ok:!0,value:r}:Te(r,e)?{ok:!0,value:t}:d("continuous-context-merge-conflict")}function Zt(e,r,t){try{const o=at($e(e),$e(r),$e(t));return o.ok?{ok:!0,value:o.value===void 0?void 0:Buffer.from(`${JSON.stringify(o.value,null,2)}
53
- `)}:o}catch{return d("continuous-state-merge-invalid")}}function $e(e){return e===void 0?void 0:JSON.parse(e.toString("utf8"))}function at(e,r,t){if(Se(t,e)||Se(r,t))return{ok:!0,value:r};if(Se(r,e))return{ok:!0,value:t};if(ze(e)&&ze(r)&&ze(t)){const o={};for(const n of[...new Set([...Object.keys(e),...Object.keys(r),...Object.keys(t)])].sort()){const i=at(e[n],r[n],t[n]);if(!i.ok)return i;i.value!==void 0&&(o[n]=i.value)}return{ok:!0,value:o}}if(Array.isArray(e)&&Array.isArray(r)&&Array.isArray(t)&&ct(e,r)&&ct(e,t)){const o=[...e,...r.slice(e.length),...t.slice(e.length)],n=new Set;return{ok:!0,value:o.filter(i=>{const c=JSON.stringify(i);return n.has(c)?!1:(n.add(c),!0)})}}return d("continuous-state-merge-conflict")}function ze(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ct(e,r){return e.length<=r.length&&e.every((t,o)=>Se(t,r[o]))}function Se(e,r){return JSON.stringify(e)===JSON.stringify(r)}function Te(e,r){return e===void 0||r===void 0?e===r:e.equals(r)}function L(e){return e.split("\0").filter(Boolean)}function oe(e){const r=de(e);return r.length>0&&r.length<=1024&&!ke(r)&&!/^[A-Za-z]:\//.test(r)&&!r.split("/").includes("..")&&!r.includes("\0")&&!r.startsWith("/")}function de(e){return e.replaceAll("\\","/").replace(/^\.\//,"").replace(/\/{2,}/g,"/")}function st(e){const r=e.map(de).filter(oe);return[...new Set(r)].sort()}function ve(e,r){const t=de(e),o=de(r);return t===o||t.endsWith("/")&&o.startsWith(t)}function dt(e){return e.length>0&&e.length<=240&&!e.startsWith("-")&&!e.startsWith("/")&&!e.endsWith("/")&&!e.endsWith(".lock")&&!e.includes("..")&&!e.includes("\\")&&!e.includes("@{")&&!e.includes("//")&&/^[A-Za-z0-9._/-]+$/.test(e)}function ut(e,r){return e.length===r.length&&e.every((t,o)=>t===r[o])}async function ue(e,r,t,o){const n=T(JSON.parse(await B(_(e,".neocortex/state.json"),"utf8")));return We(n,o??await V(e),r,t)}function We(e,r,t,o){const n=ie(e,r),i=p(n.epics),c=p(n.stories),a=p(i?.[t])??{},u=(Array.isArray(a.stories)?a.stories:Array.isArray(a.story_ids)?a.story_ids:[]).filter(I=>typeof I=="string"),s=u.length>0?u:Object.entries(c??{}).filter(([I,R])=>p(R)?.epic_id===t||I.startsWith(`${t}.`)).map(([I])=>I).sort(),m=["status","depends_on","files_to_modify","contracts","contract_refs","shared_surfaces","steps_completed","last_step","branch_name","physicalMergeStatus","merged","checkpoint","planning","attempts","retry_count","rollback_receipt","cancelled_at"],g=Object.fromEntries(s.map(I=>{const R=p(c?.[I])??{};return[I,Object.fromEntries(m.filter(l=>Object.prototype.hasOwnProperty.call(R,l)).map(l=>[l,R[l]]))]}));return{revision:Ie({epicId:t,epic:{stories:s,status:a.status??null,branch_mode:a.branch_mode??null,execution_branch:a.execution_branch??null,graph_revision:a.graph_revision??null,depends_on:a.depends_on??null,planning:a.planning??null,execution_plan:a.execution_plan??null,waves:a.waves??null,current_wave:a.current_wave??null,replan:a.replan??null,replan_revision:a.replan_revision??null,dependency_graph:a.dependency_graph??null,scheduler:a.scheduler??null,attempts:a.attempts??null,retry_count:a.retry_count??null},stories:g}),epoch:typeof a.graph_revision=="string"?a.graph_revision:null,storyStatus:typeof p(c?.[o])?.status=="string"?String(p(c?.[o])?.status):null}}function Le(e,r,t,o){const n=ie(e,r),i=p(p(n.epics)?.[t.epicId]),c=p(p(n.stories)?.[t.storyId]),a=Array.isArray(c?.steps_completed)?c.steps_completed.filter(u=>typeof u=="string"):[];return!!(i&&c&&i.branch_lease===null&&c.status==="done"&&c.last_step===ge&&a.includes(Ue)&&a.includes(ge)&&he(c.checkpoint)===he(o))}function Ut(e,r){for(const t of Object.keys(e))delete e[t];Object.assign(e,structuredClone(r))}async function Xt(e,r){return(await ue(e,r,"")).revision}function Ie(e){return W("sha256").update(he(e)).digest("hex")}function he(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(he).join(",")}]`:`{${Object.entries(e).sort(([r],[t])=>r.localeCompare(t)).map(([r,t])=>`${JSON.stringify(r)}:${he(t)}`).join(",")}}`}function er(e,r){const t=(e??[]).filter(o=>/^[A-Za-z0-9._/:@#-]{1,200}$/.test(o)&&!o.includes(".."));return Object.freeze([...new Set(t.length>0?t:[`dispatch:${r}`])].sort())}function tr(e){return e.replace(/[^A-Za-z0-9._-]/g,"-").slice(0,80)}function d(e){return{ok:!1,reasonCode:e}}function q(e,r){return e instanceof Error&&"code"in e&&e.code===r}async function ne(e,r){try{await G(e,r);const t=_(e,"owner.json");await F(t,e);const o=JSON.parse(await B(t,"utf8"));if(!Number.isSafeInteger(o.pid)||Number(o.pid)<=0||typeof o.createdAt!="string"||!Number.isFinite(Date.parse(o.createdAt))||typeof o.nonce!="string"||!/^[a-f0-9]{32}$/.test(o.nonce))throw new Error("continuous-sandbox-lease-owner-invalid");return{pid:Number(o.pid),createdAt:o.createdAt,nonce:o.nonce}}catch(t){if(q(t,"ENOENT"))return;throw t}}function ht(e,r){return e?.pid===r.pid&&e.createdAt===r.createdAt&&e.nonce===r.nonce}function rr(e){try{return process.kill(e,0),!0}catch(r){return q(r,"EPERM")}}async function Ge(e,r){try{await G(e,r);const t=_(e,".git");await G(t,e);const o=_(t,"neocortex-sandbox.json");await F(o,t);const n=JSON.parse(await B(o,"utf8"));if(n.schemaVersion!==1||typeof n.workspaceOwnerNonce!="string"||!/^[a-f0-9]{32}$/.test(n.workspaceOwnerNonce)||!/^[a-f0-9]{64}$/.test(n.graphAuthorityRevision)||!(n.graphAuthorityEpoch===null||/^[a-f0-9]{64}$/.test(n.graphAuthorityEpoch))||!(n.graphAuthorityStoryStatus===null||typeof n.graphAuthorityStoryStatus=="string"&&n.graphAuthorityStoryStatus.length<=80)||typeof n.workspaceIdentity?.dev!="string"||!/^[0-9]+$/.test(n.workspaceIdentity.dev)||typeof n.workspaceIdentity?.ino!="string"||!/^[0-9]+$/.test(n.workspaceIdentity.ino))throw new Error("continuous-sandbox-metadata-invalid");return n}catch(t){if(q(t,"ENOENT"))return;throw t}}async function or(e,r,t,o){await G(e,r);const n=_(e,".git");await G(n,e);const i=_(n,"neocortex-sandbox.json");await re(e,".git/neocortex-sandbox.json",Buffer.from(`${JSON.stringify(t,null,2)}
54
- `),o),await F(i,n)}async function nr(e,r){try{await F(e,r);const t=JSON.parse(await B(e,"utf8"));return typeof t.childHeadSha=="string"&&typeof t.rootHeadSha=="string"&&/^[a-f0-9]{40,64}$/.test(t.childHeadSha)&&/^[a-f0-9]{40,64}$/.test(t.rootHeadSha)&&t.bundle?.schemaVersion===1&&t.checkpoint?.schemaVersion===1?t:void 0}catch(t){if(q(t,"ENOENT"))return;throw t}}async function ir(e,r){try{const t=T(JSON.parse(await B(_(e.projectRoot,".neocortex/state.json"),"utf8"))),o=ie(t,await V(e.projectRoot)),n=p(p(o.stories)?.[e.storyId]),i=p(n?.checkpoint);return i?.idempotencyKey===r.idempotencyKey&&i.headSha===r.headSha&&i.bundleDigest===r.bundleDigest&&p(p(o.epics)?.[e.epicId])?.branch_lease===null&&await Ee(e.projectRoot,i,e.storyId,e.epicId,e.executionBranch,void 0,e.authorizedWriteSet)}catch{return!1}}async function ar(e,r,t){try{const o=T(JSON.parse(await B(_(e.projectRoot,".neocortex/state.json"),"utf8"))),n=ie(o,await V(e.projectRoot)),i=p(p(n.stories)?.[e.storyId]),c=p(i?.checkpoint);return c?.schemaVersion!==1||c.storyId!==e.storyId||c.epicId!==e.epicId||c.branch!==e.executionBranch||c.baseSha!==t.baseSha||c.headSha!==t.headSha||c.idempotencyKey!==e.dispatchId||c.dispatchId!==e.dispatchId||c.bundleId!==r.bundleId||c.bundleDigest!==r.bundleDigest||c.graphRevision!==e.graphRevision||c.claimRevision!==e.claimRevision||p(p(n.epics)?.[e.epicId])?.branch_lease!==null||!await Ee(e.projectRoot,c,e.storyId,e.epicId,e.executionBranch,void 0,e.authorizedWriteSet)?void 0:c}catch{return}}async function cr(e,r){const t=(await te(e.projectRoot,["log","--format=%H","--fixed-strings",`--grep=Neocortex-Dispatch: ${e.dispatchId}`]))?.split(`
55
- `).filter(g=>/^[a-f0-9]{40,64}$/.test(g))??[];if(t.length!==1)return;const o=t[0];if(!await se(e.projectRoot,["merge-base","--is-ancestor",o,"HEAD"]))return;const n=await C(e.projectRoot,["show","-s","--format=%B",o]),i=new Set(n.split(`
56
- `).map(g=>g.trim()));for(const g of[`Neocortex-Story: ${e.storyId}`,`Neocortex-Epic: ${e.epicId}`,`Neocortex-Execution-Branch: ${e.executionBranch}`,`Neocortex-Prepared-Base: ${e.baseSha}`,`Neocortex-Dispatch: ${e.dispatchId}`,`Neocortex-Bundle: ${r.bundleId}`,`Neocortex-Bundle-Digest: ${r.bundleDigest}`,`Neocortex-Graph-Revision: ${e.graphRevision}`,`Neocortex-Claim-Revision: ${e.claimRevision}`])if(!i.has(g))return;const c=qe(n,"Neocortex-Checkpoint-Authority"),a=qe(n,"Neocortex-Checkpoint-Epoch"),u=qe(n,"Neocortex-Checkpoint-Story-Status");if(!c||!/^[a-f0-9]{64}$/.test(c)||!a||!(a==="null"||/^[a-f0-9]{64}$/.test(a))||!u||u.length>80)return;const s=await te(e.projectRoot,["rev-parse",`${o}^`]);if(!s||!/^[a-f0-9]{40,64}$/.test(s))return;const m=L(await z(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",o]));if(!(m.length===0||m.some(g=>!r.authorizedWriteSet.some(I=>ve(I,g)))))return{baseSha:s,headSha:o,checkpointAuthority:{revision:c,epoch:a==="null"?null:a,storyStatus:u==="null"?null:u}}}function qe(e,r){const t=`${r}: `,o=e.split(`
57
- `).map(n=>n.trim()).filter(n=>n.startsWith(t));return o.length===1?o[0].slice(t.length):void 0}async function He(e,r,t,o,n,i){const c=j(e);await G(c,j(c));try{await F(e,c)}catch(a){if(!q(a,"ENOENT"))throw a}await re(c,$(e),Buffer.from(`${JSON.stringify({childHeadSha:r,rootHeadSha:t,bundle:o,checkpoint:n})}
58
- `),i),await F(e,c)}export{Nt as STORY_WORKTREE_INTEGRATION_ROOT_OWNED,mr as createAnchoredContinuousStoryCommandRunner,Ct as createBranchlessContinuousStoryWorkspaceManager,Pt as createStoryWorktreeContinuousStoryWorkspaceManager,Sr as selectContinuousStoryWorkspaceManager,Bt as selectContinuousStoryWorkspaceStrategy};
49
+ `;function kr(e,r={}){return async(t,o,n={})=>Kt(e,t,o,n,r)}function Tt(e={}){let r=Promise.resolve();return{async prepare(t){if((e.platform??process.platform)==="win32")return d("continuous-sandbox-platform-unsupported");if(!/^[a-f0-9]{64}$/.test(t.dispatchId))return d("continuous-sandbox-dispatch-invalid");if(!oe(t.targetRef))return d("continuous-sandbox-target-invalid");if(!dt(t.executionBranch))return d("continuous-execution-branch-invalid");if(!/^[a-f0-9]{64}$/.test(t.graphRevision))return d("continuous-graph-revision-invalid");const o=st(t.authorizedWriteSet);if(o.length===0||o.length!==t.authorizedWriteSet.length)return d("continuous-authorized-write-set-invalid");const n=Ie(o),i=r;let c=()=>{};r=new Promise(s=>{c=s}),await i;let a,u;try{const s=await et(t.projectRoot),v=await O(s,["rev-parse","HEAD"]),g=await ue(s,t.epicId,t.storyId),I=g.revision,b=await Ye(s),l=await Xe(b,t.dispatchId,(S,y)=>{a=S,u=y},e.beforeSandboxWriteCommit);if(!l.ok)return l;const{leasePath:N}=l.value,k=await xe(b,"sandboxes"),f=C(k,t.dispatchId.slice(0,20)),m=await Le(f,k);let A,h;const R=m?.preparedAt??new Date().toISOString(),x=m?.workspaceOwnerNonce??Ve(16).toString("hex");if(m){if(m.projectRoot!==s||m.storyId!==t.storyId||m.targetRef!==t.targetRef||m.dispatchId!==t.dispatchId||m.epicId!==t.epicId||m.executionBranch!==t.executionBranch||m.graphRevision!==t.graphRevision||m.claimRevision!==n||m.graphAuthorityRevision!==I||m.graphAuthorityEpoch!==g.epoch||m.graphAuthorityStoryStatus!==g.storyStatus||!ut(m.authorizedWriteSet,o)||(A=m.contextSnapshots.map(S=>({path:S.path,...S.contentBase64!==void 0?{content:Buffer.from(S.contentBase64,"base64")}:{}})),h=await Ze(f),h.dev!==m.workspaceIdentity.dev||h.ino!==m.workspaceIdentity.ino))return d("continuous-sandbox-recovery-mismatch")}else await ee(f,k),h=await je(k,$(f)),await L(f,k),await ae(k,$(f),h,["init","--quiet"]),await Ht(s,f),await qt(s,k,$(f),h),await ae(k,$(f),h,["remote","add","neocortex-root",s]),await ae(k,$(f),h,["fetch","--quiet","--no-tags","neocortex-root",v]),await ae(k,$(f),h,["checkout","--quiet","--detach","FETCH_HEAD"]),A=await Lt(s,f,t.epicId,t.targetRef,e.beforeSandboxWriteCommit),await sr(f,k,{schemaVersion:1,projectRoot:s,storyId:t.storyId,targetRef:t.targetRef,epicId:t.epicId,executionBranch:t.executionBranch,graphRevision:t.graphRevision,graphAuthorityRevision:I,graphAuthorityEpoch:g.epoch,graphAuthorityStoryStatus:g.storyStatus,authorizedWriteSet:o,claimRevision:n,dispatchId:t.dispatchId,baseSha:v,preparedAt:R,workspaceOwnerNonce:x,workspaceIdentity:h,contextSnapshots:A.map(S=>({path:S.path,...S.content!==void 0?{contentBase64:S.content.toString("base64")}:{}}))},e.beforeSandboxWriteCommit);return a=void 0,{ok:!0,value:{projectRoot:s,workspacePath:f,workspaceStrategy:"branchless_sandbox",storyId:t.storyId,targetRef:t.targetRef,epicId:t.epicId,executionBranch:t.executionBranch,graphRevision:t.graphRevision,graphAuthorityRevision:I,graphAuthorityEpoch:g.epoch,graphAuthorityStoryStatus:g.storyStatus,authorizedWriteSet:o,claimRevision:n,baseSha:m?.baseSha??v,dispatchId:t.dispatchId,preparedAt:R,leasePath:N,leaseOwnerNonce:l.value.owner.nonce,workspaceOwnerNonce:x,workspaceIdentity:h,contextSnapshots:A}}}catch{if(a&&u){const s=a,v=u;await ee(s,j(s),async g=>ht(await ne(g,j(s)),v)).catch(()=>{})}return d("continuous-sandbox-prepare-failed")}finally{c()}},async integrate(t,o){const n=await ne(t.leasePath,j(t.leasePath)).catch(()=>{}),i=await Le(t.workspacePath,j(t.workspacePath)).catch(()=>{});if(!n||n.nonce!==t.leaseOwnerNonce||i?.workspaceOwnerNonce!==t.workspaceOwnerNonce||i.dispatchId!==t.dispatchId||i.storyId!==t.storyId)return d("continuous-sandbox-owner-mismatch");const c=it(o?.nowIso??new Date().toISOString()),a=await At(t.projectRoot,{kind:"continuous",storyId:t.storyId,sessionId:t.dispatchId,idempotencyKey:t.dispatchId,expiresAt:new Date(Date.parse(c)+1800*1e3).toISOString(),persistent:!1,createdAt:c});if(!a.ok)return d(a.reasonCode==="git-lifecycle-integration-backpressure"?"continuous-integration-backpressure":"continuous-integration-lease-failed");let u=[],s=!1,v=!1;try{const g=(await ce(t,["status","--porcelain"])).trimEnd(),I=await Oe(t,["rev-parse","HEAD"]);if(await te(t.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==t.executionBranch)return d("continuous-execution-branch-mismatch");const l=j(j(t.leasePath)),N=await xe(l,"integrated"),k=C(N,t.dispatchId),f=await dr(k,N);if(f?.childHeadSha===I&&f.bundle.storyId===t.storyId&&f.bundle.epicId===t.epicId&&f.bundle.executionBranch===t.executionBranch&&f.bundle.graphRevision===t.graphRevision&&f.bundle.claimRevision===t.claimRevision&&ut(f.bundle.authorizedWriteSet,t.authorizedWriteSet)&&f.checkpoint.idempotencyKey===t.dispatchId&&f.checkpoint.bundleId===f.bundle.bundleId&&f.checkpoint.bundleDigest===f.bundle.bundleDigest&&f.checkpoint.graphRevision===t.graphRevision&&f.checkpoint.claimRevision===t.claimRevision&&await se(t.projectRoot,["merge-base","--is-ancestor",f.rootHeadSha,"HEAD"])&&await ur(t,f.checkpoint))return{ok:!0,value:{headSha:f.rootHeadSha,alreadyIntegrated:!0,bundle:f.bundle,checkpoint:f.checkpoint}};if(I!==t.baseSha)return d("continuous-sandbox-child-git-authority-denied");if(g.length===0)return d("continuous-bundle-empty");const m=g.split(`
50
+ `).some(w=>w.length>0&&w[0]!==" "&&w[0]!=="?");m||await Oe(t,["add","-A"]);const A=G(await ce(t,["diff","--cached","--name-only","-z",t.baseSha]));if(A.length===0||A.some(w=>!oe(w)))return d("continuous-integration-write-set-invalid");if(!await Jt(t,["merge-base","--is-ancestor",t.baseSha,I]))return d("continuous-bundle-base-not-ancestor");if(!await se(t.projectRoot,["merge-base","--is-ancestor",t.baseSha,"HEAD"]))return d("continuous-root-base-not-ancestor");const h=o?.nowIso??new Date().toISOString(),R=ir(o?.receiptRefs,t.dispatchId),x=await ce(t,["diff","--cached","--binary",t.baseSha]),S={schemaVersion:1,storyId:t.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:t.baseSha,bundleDigest:W("sha256").update(x).digest("hex"),graphRevision:t.graphRevision,claimRevision:t.claimRevision,authorizedWriteSet:t.authorizedWriteSet,contextDigests:Object.fromEntries(t.contextSnapshots.map(w=>[w.path,W("sha256").update(w.content??Buffer.alloc(0)).digest("hex")])),validationRefs:R,createdAt:t.preparedAt,expiresAt:new Date(Date.parse(t.preparedAt)+1440*60*1e3).toISOString(),branchless:!0},y=Object.freeze({...S,bundleId:Ie(S)}),E=await fr(t,y);if(E){const w=await hr(t,y,E);if(w)return await He(k,I,E.headSha,y,w,e.beforeSandboxWriteCommit),{ok:!0,value:{headSha:E.headSha,alreadyIntegrated:!0,bundle:y,checkpoint:w}}}if(!E&&await nr(t.projectRoot,t.epicId)!==t.graphAuthorityRevision)return d("continuous-graph-revision-stale");if(E){const w=await nt({lease:t,bundle:y,baseSha:E.baseSha,headSha:E.headSha,receiptRefs:R,nowIso:h,qaRunner:e.storyQaRunner});if(!w.ok)return w;await e.beforeCheckpointPersist?.({projectRoot:t.projectRoot,storyId:t.storyId,headSha:E.headSha});const _=await ot({lease:t,physicalLock:a,checkpointAuthority:E.checkpointAuthority,bundle:y,baseSha:E.baseSha,headSha:E.headSha,receiptRefs:[...R,`bundle:${y.bundleId}`,w.value.qaReceipt.receiptRef,w.value.reviewReceipt.receiptRef],qaReceipt:w.value.qaReceipt,reviewReceipt:w.value.reviewReceipt,recordedAt:h,checkpointNow:e.checkpointNow,insideCheckpointPreCommit:e.insideCheckpointPreCommit,afterCheckpointPersist:e.afterCheckpointPersist});return _.ok?(await He(k,I,E.headSha,y,_.value,e.beforeSandboxWriteCommit),{ok:!0,value:{headSha:E.headSha,alreadyIntegrated:!0,bundle:y,checkpoint:_.value}}):_}if(m)return d("continuous-sandbox-child-git-authority-denied");if(G(await T(t.projectRoot,["diff","--cached","--name-only","-z"])).length>0)return d("continuous-integration-root-index-dirty");const J=new Set(t.contextSnapshots.map(w=>w.path));if(A.filter(w=>!t.authorizedWriteSet.some(_=>ve(_,w))).length>0)return d("continuous-bundle-write-set-unauthorized");const M=A.filter(w=>!J.has(w)),be=new Set(G(await T(t.projectRoot,["diff","--name-only","-z",`${t.baseSha}..HEAD`])));if(M.some(w=>be.has(w)))return d("continuous-bundle-intervening-conflict");const fe=new Set([...G(await T(t.projectRoot,["diff","--name-only","-z"])),...G(await T(t.projectRoot,["ls-files","--others","--exclude-standard","-z"]))]);if(M.some(w=>fe.has(w)))return d("continuous-integration-root-conflict");u=await Yt(t.projectRoot,[...new Set([...A,".neocortex/state.json"])]);const H=await Zt(t,h);if(!H.ok)return H;const K=vt({bundle:y,payload:Buffer.from(x),expected:{epicId:t.epicId,storyId:t.storyId,executionBranch:t.executionBranch,baseSha:t.baseSha,graphRevision:t.graphRevision,claimRevision:t.claimRevision,authorizedWriteSet:t.authorizedWriteSet,nowIso:h},writerLease:H.value});if(K.length>0)return await Be(t.projectRoot,u),d(`continuous-bundle-admission-${K[0]}`);const pe=await O(t.projectRoot,["rev-parse","HEAD"]);let Q;await e.beforeRootCommit?.({projectRoot:t.projectRoot,storyId:t.storyId,headSha:pe});try{await X(t.projectRoot,w=>{const _=p(we(w,t.epicId).branch_lease);if(_?.ownerStoryId!==t.storyId||_.sessionId!==t.dispatchId||_.idempotencyKey!==t.dispatchId||Date.parse(String(_.expiresAt))<=Date.now())throw new Error("continuous-checkpoint-writer-lease-lost")},{preCommit:async w=>{const _=await ue(t.projectRoot,t.epicId,t.storyId,w);if(_.revision!==t.graphAuthorityRevision||_.epoch!==t.graphAuthorityEpoch||_.storyStatus!==t.graphAuthorityStoryStatus)throw new Error("continuous-graph-revision-stale");if(!await Ae(a.path,a.owner))throw new Error("continuous-integration-lock-raced");const ft=await te(t.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]),pt=await O(t.projectRoot,["rev-parse","HEAD"]);if(ft!==t.executionBranch||pt!==pe)throw new Error("continuous-integration-head-raced");const lt=G(await T(t.projectRoot,["diff","--cached","--name-only","-z"])),yt=new Set([...G(await T(t.projectRoot,["diff","--name-only","-z"])),...G(await T(t.projectRoot,["ls-files","--others","--exclude-standard","-z"]))]);if(lt.length>0)throw new Error("continuous-integration-root-index-dirty");if(M.some(P=>yt.has(P)))throw new Error("continuous-integration-root-conflict");if(v=!0,M.length>0){const P=await ce(t,["diff","--cached","--binary",t.baseSha,"--",...M]);if(P.length>0&&!await Ft(t.projectRoot,["apply","--index","--3way","--whitespace=nowarn"],P))throw new Error("continuous-integration-conflict")}for(const P of t.contextSnapshots){if(!A.includes(P.path))continue;const Je=await Ne(C(t.projectRoot,P.path)),Me=await Mt(t,P.path),Ke=P.path===".neocortex/state.json"?rr(P.content,Je,Xt(P.content,Me,t.storyId)):tr(P.content,Je,Me);if(!Ke.ok)throw new Error(P.path===".neocortex/state.json"?"continuous-state-merge-conflict":"continuous-context-merge-conflict");await re(t.projectRoot,P.path,Ke.value),await O(t.projectRoot,["add","-A","--",P.path])}if(A.includes(".neocortex/state.json")&&await O(t.projectRoot,["add","-A","--",".neocortex/state.json"]),await se(t.projectRoot,["diff","--cached","--quiet"]))throw new Error("continuous-integration-empty-after-admission");Q=await ue(t.projectRoot,t.epicId,t.storyId,w),await O(t.projectRoot,["commit","-m",`feat(yoloop): integrate ${t.storyId}`,"-m",`Neocortex-Story: ${t.storyId}`,"-m",`Neocortex-Epic: ${t.epicId}`,"-m",`Neocortex-Execution-Branch: ${t.executionBranch}`,"-m",`Neocortex-Prepared-Base: ${t.baseSha}`,"-m",`Neocortex-Dispatch: ${t.dispatchId}`,"-m",`Neocortex-Bundle: ${y.bundleId}`,"-m",`Neocortex-Bundle-Digest: ${y.bundleDigest}`,"-m",`Neocortex-Graph-Revision: ${t.graphRevision}`,"-m",`Neocortex-Claim-Revision: ${t.claimRevision}`,"-m",`Neocortex-Checkpoint-Authority: ${Q.revision}`,"-m",`Neocortex-Checkpoint-Epoch: ${Q.epoch??"null"}`,"-m",`Neocortex-Checkpoint-Story-Status: ${Q.storyStatus??"null"}`]),s=!0}})}catch(w){v&&!s&&await Be(t.projectRoot,u);const _=w instanceof Error&&/^continuous-/.test(w.message)?w.message:"continuous-integration-failed";return d(_)}const Y=await O(t.projectRoot,["rev-parse","HEAD"]);if(!Q)return d("continuous-checkpoint-authority-missing");await e.afterRootCommit?.({projectRoot:t.projectRoot,storyId:t.storyId,headSha:Y});const Z=await nt({lease:t,bundle:y,baseSha:pe,headSha:Y,receiptRefs:R,nowIso:h,qaRunner:e.storyQaRunner});if(!Z.ok)return Z;await e.beforeCheckpointPersist?.({projectRoot:t.projectRoot,storyId:t.storyId,headSha:Y});const le=await ot({lease:t,physicalLock:a,checkpointAuthority:Q,bundle:y,baseSha:pe,headSha:Y,receiptRefs:[...R,`bundle:${y.bundleId}`,Z.value.qaReceipt.receiptRef,Z.value.reviewReceipt.receiptRef],qaReceipt:Z.value.qaReceipt,reviewReceipt:Z.value.reviewReceipt,recordedAt:h,checkpointNow:e.checkpointNow,insideCheckpointPreCommit:e.insideCheckpointPreCommit,afterCheckpointPersist:e.afterCheckpointPersist});return le.ok?(await He(k,I,Y,y,le.value,e.beforeSandboxWriteCommit),{ok:!0,value:{headSha:Y,alreadyIntegrated:!1,bundle:y,checkpoint:le.value}}):le}catch{return v&&!s&&u.length>0&&await Be(t.projectRoot,u),d("continuous-integration-failed")}finally{await Ut(t).catch(()=>{}),await Ot(a.path,a.owner).catch(()=>{})}},async release(t,o){o||await ee(t.workspacePath,j(t.workspacePath),async n=>{const i=await Le(n,j(t.workspacePath)).catch(()=>{});return i?.workspaceOwnerNonce===t.workspaceOwnerNonce&&i.dispatchId===t.dispatchId&&i.storyId===t.storyId}),await ee(t.leasePath,j(t.leasePath),async n=>(await ne(n,j(t.leasePath)).catch(()=>{}))?.nonce===t.leaseOwnerNonce)}}}const zt="story-worktree-integration-root-owned";function Wt(e={}){const r=e.storyWorktrees??(o=>new Et({projectRoot:o}));let t=Promise.resolve();return{async prepare(o){if(!/^[a-f0-9]{64}$/.test(o.dispatchId))return d("continuous-sandbox-dispatch-invalid");if(!oe(o.targetRef))return d("continuous-sandbox-target-invalid");if(!dt(o.executionBranch))return d("continuous-execution-branch-invalid");if(!/^[a-f0-9]{64}$/.test(o.graphRevision))return d("continuous-graph-revision-invalid");const n=st(o.authorizedWriteSet);if(n.length===0||n.length!==o.authorizedWriteSet.length)return d("continuous-authorized-write-set-invalid");const i=Ie(n),c=t;let a=()=>{};t=new Promise(s=>{a=s}),await c;let u;try{const s=await et(o.projectRoot),v=await O(s,["rev-parse","--verify",`refs/heads/${o.executionBranch}^{commit}`]),g=await ue(s,o.epicId,o.storyId),I=await Ye(s),b=await Xe(I,o.dispatchId,(f,m)=>{u={leasePath:f,owner:m}},e.beforeSandboxWriteCommit);if(!b.ok)return b;const l=await r(s).create({epicId:o.epicId,storyId:o.storyId,dispatchId:o.dispatchId,baseSha:v,graphRevision:o.graphRevision});if(!l.ok||!l.privatePath||!ke(l.privatePath))return u=void 0,await De(b.value.leasePath,b.value.owner.nonce).catch(()=>{}),d(l.ok?"story-worktree-path-unavailable":l.reasonCode);const N=Qe(l.privatePath),k=await Ze(N);return u=void 0,{ok:!0,value:{projectRoot:s,workspacePath:N,workspaceStrategy:"story_worktree",storyWorktreeLeaseId:l.value.lease.leaseId,storyId:o.storyId,targetRef:o.targetRef,epicId:o.epicId,executionBranch:o.executionBranch,graphRevision:o.graphRevision,graphAuthorityRevision:g.revision,graphAuthorityEpoch:g.epoch,graphAuthorityStoryStatus:g.storyStatus,authorizedWriteSet:n,claimRevision:i,baseSha:l.value.baseSha,preparedAt:new Date().toISOString(),dispatchId:o.dispatchId,leasePath:b.value.leasePath,leaseOwnerNonce:b.value.owner.nonce,workspaceOwnerNonce:b.value.owner.nonce,workspaceIdentity:k,contextSnapshots:[]}}}catch{const s=u;return s&&await De(s.leasePath,s.owner.nonce).catch(()=>{}),d("story-worktree-prepare-failed")}finally{a()}},async integrate(o){return o.workspaceStrategy!=="story_worktree"?d("continuous-workspace-strategy-mismatch"):d(zt)},async release(o){await De(o.leasePath,o.leaseOwnerNonce)}}}function Gt(e){const r=e&&typeof e=="object"&&!Array.isArray(e)?e:void 0;return r?.version===4&&r.mode==="two_phase_worktree_dag"&&r.authorization==="server_authorized"&&r.workspaceMechanism==="client_managed_worktree"?"story_worktree":"branchless_sandbox"}function xr(e,r={}){const t=Gt(e);return t==="story_worktree"?{strategy:t,manager:r.storyWorktree??Wt()}:{strategy:t,manager:r.branchless??Tt()}}async function Xe(e,r,t,o){const n=await xe(e,"leases"),i=C(n,r);try{await je(n,r),await L(i,n)}catch(a){if(!q(a,"EEXIST"))throw a;await L(i,n);const u=await ne(i,n);if(u!==void 0&&cr(u.pid))return d("continuous-sandbox-lease-active");if(!u||!await ee(i,n,async s=>ht(await ne(s,n),u)))return d("continuous-sandbox-lease-owner-replaced");await je(n,r),await L(i,n)}const c=Object.freeze({pid:process.pid,createdAt:new Date().toISOString(),nonce:Ve(16).toString("hex")});return t(i,c),await re(i,"owner.json",Buffer.from(JSON.stringify(c)),o),await F(C(i,"owner.json"),i),{ok:!0,value:{leasePath:i,owner:c}}}async function De(e,r){await ee(e,j(e),async t=>(await ne(t,j(e)).catch(()=>{}))?.nonce===r)}async function Lt(e,r,t,o,n){const i=[...new Set([".neocortex/state.json",o,`docs/epics/epic-${ar(t)}.md`])],c=[];for(const a of i){if(!oe(a))continue;const u=await Ne(C(e,a));c.push({path:a,...u!==void 0?{content:u}:{}}),u!==void 0&&await re(r,a,u,n)}return c}async function et(e){const r=await O(e,["rev-parse","--show-toplevel"]),[t,o]=await Promise.all([U(r),U(e)]);if(t!==o)throw new Error("project root mismatch");return t}async function qt(e,r,t,o){for(const n of["user.name","user.email"]){const i=await te(e,["config","--get",n]);i&&await ae(r,t,o,["config",n,i])}}async function Ht(e,r){const t=await V(e);await X(r,o=>{for(const[n,i]of Object.entries(t.epics))o.epics[n]={...structuredClone(i),branch_lease:null};for(const[n,i]of Object.entries(t.stories))o.stories[n]=structuredClone(i)})}async function ae(e,r,t,o){return(await Ce(e,r,t,o)).toString("utf8").trim()}async function ce(e,r){return(await Ce(j(e.workspacePath),$(e.workspacePath),e.workspaceIdentity,r)).toString("utf8")}async function Oe(e,r){return(await ce(e,r)).trim()}async function Jt(e,r){try{return await Oe(e,r),!0}catch{return!1}}async function Mt(e,r){try{return await Ce(j(e.workspacePath),$(e.workspacePath),e.workspaceIdentity,["show",`:${r}`])}catch{return}}async function Kt(e,r,t,o,n){const i=Date.now(),c=b=>({exitCode:null,timedOut:!1,durationMs:Date.now()-i,stdout:"",stderr:"",stdoutBytes:0,stderrBytes:0,...b});if(o.signal?.aborted)return c({signal:"SIGTERM",cancelled:!0});if(!r||r.length>4096||r.includes("\0")||t.length>512||t.some(b=>b.length>32768||b.includes("\0")))return c({exitCode:73,stderr:"continuous-child-invocation-invalid",stderrBytes:35});const a=j(e.workspacePath),u=await ye(a,{bigint:!0}),s=await gt(a,{bigint:!0});if(!u.isDirectory()||u.isSymbolicLink()||!s.isDirectory()||u.dev!==s.dev||u.ino!==s.ino)return c({exitCode:73,stderr:"continuous-child-parent-invalid",stderrBytes:31});await n.beforeHandoff?.();const v=Buffer.from(JSON.stringify({command:r,args:[...t]})).toString("base64url"),g=o.maxOutputBytes??64e3,I=Math.max(1,Math.min(o.timeoutMs??600*1e3,1800*1e3));return await new Promise(b=>{const l=Fe(process.execPath,["-e",$t,String(s.dev),String(s.ino),$(e.workspacePath),e.workspaceIdentity.dev,e.workspaceIdentity.ino,v,n.afterHandoff?"1":"0"],{cwd:a,env:o.env??It({processEnv:process.env,platform:process.platform}),stdio:["pipe","pipe","pipe"]});let N="",k="",f=0,m=0,A=!1,h=!1,R=!1,x=!n.afterHandoff;const S=(D,J)=>{A||(A=!0,clearTimeout(E),o.signal?.removeEventListener("abort",y),b({exitCode:D,...J?{signal:J}:{},timedOut:h,...R?{cancelled:!0}:{},durationMs:Date.now()-i,stdout:N,stderr:k,stdoutBytes:f,stderrBytes:m}))},y=()=>{R=!0,l.kill("SIGTERM")};o.signal?.addEventListener("abort",y,{once:!0});const E=setTimeout(()=>{h=!0,l.kill("SIGTERM")},I);l.stdout.on("data",D=>{f+=D.length,f+m>g?l.kill("SIGTERM"):N+=D.toString("utf8")}),l.stderr.on("data",D=>{m+=D.length,f+m>g?l.kill("SIGTERM"):k+=D.toString("utf8"),!x&&k.includes(`continuous-child-handoff-ready
51
+ `)&&(x=!0,Promise.resolve(n.afterHandoff?.()).then(()=>l.stdin.end()).catch(()=>l.kill("SIGTERM")))}),l.once("error",()=>S(null)),l.once("close",(D,J)=>S(D,J)),n.afterHandoff||l.stdin.end()})}async function O(e,r){return(await T(e,r)).trim()}async function T(e,r){const t=await _e("git",r,{cwd:e,encoding:"utf8",maxBuffer:16777216});return String(t.stdout)}async function te(e,r){try{return await O(e,r)}catch(t){if(q(t,"ENOENT"))return;throw t}}async function se(e,r){try{return await O(e,r),!0}catch{return!1}}async function Ft(e,r,t){return await new Promise(o=>{const n=Fe("git",[...r],{cwd:e,stdio:["pipe","ignore","ignore"]});n.once("error",()=>o(!1)),n.once("close",i=>o(i===0)),n.stdin.end(t)})}async function Er(e,r,t){try{const o=await _e("git",["show",`${r}:${t}`],{cwd:e,encoding:"buffer",maxBuffer:16777216});return Buffer.from(o.stdout)}catch(o){if(q(o,"ENOENT"))return;throw o}}async function Ne(e){try{return await B(e)}catch(r){if(q(r,"ENOENT"))return;throw r}}async function re(e,r,t,o){const n=de(r);if(!oe(n))throw new Error("continuous-sandbox-write-path-invalid");const i=await U(e);if(i!==Qe(e))throw new Error("continuous-sandbox-write-root-symlink");const c=j(n)==="."?"":j(n),a=await Vt(i,c),u=await tt(a),s=C(a,$(n));if(await me(s,i,!0),t===void 0){await o?.({boundaryRoot:i,relativePath:n,destinationPath:s}),await rt(a,i,u),await me(s,i,!0),await Bt(a,$(n));return}await o?.({boundaryRoot:i,relativePath:n,destinationPath:s}),await rt(a,i,u),await me(s,i,!0),await Nt(a,$(n),t),await me(s,i,!1)}async function Vt(e,r){let t=e;for(const o of r.split("/").filter(Boolean)){t=C(t,o),await Pt(j(t),$(t));const n=await ye(t);if(!n.isDirectory()||n.isSymbolicLink()||await U(t)!==t)throw new Error("continuous-sandbox-write-component-unsafe");Pe(e,t)}return t}async function me(e,r,t){Pe(r,e);try{const o=await ye(e);if(o.isSymbolicLink()||!o.isFile())throw new Error("continuous-sandbox-write-destination-unsafe");if(await U(e)!==e)throw new Error("continuous-sandbox-write-destination-symlink")}catch(o){if(t&&q(o,"ENOENT"))return;throw o}}function Pe(e,r){const t=mt(e,r);if(t===""||t.startsWith("..")||ke(t))throw new Error("continuous-sandbox-write-containment-invalid")}async function tt(e){const r=await ye(e,{bigint:!0});if(!r.isDirectory()||r.isSymbolicLink())throw new Error("continuous-sandbox-write-parent-unsafe");return{dev:r.dev,ino:r.ino}}async function Qt(e,r,t){try{if(e!==r&&Pe(r,e),await U(e)!==e)return!1;const o=await tt(e);return o.dev===t.dev&&o.ino===t.ino}catch{return!1}}async function rt(e,r,t){if(!await Qt(e,r,t))throw new Error("continuous-sandbox-write-parent-raced")}async function Yt(e,r){return await Promise.all(r.map(async t=>{const o=await Ne(C(e,t));return{path:t,...o!==void 0?{content:o}:{}}}))}async function Be(e,r){const t=r.map(o=>o.path);t.length>0&&await se(e,["reset","--quiet","HEAD","--",...t]);for(const o of r)await re(e,o.path,o.content)}async function Zt(e,r){try{const t=C(e.projectRoot,".neocortex/state.json"),o=z(JSON.parse((await B(t)).toString("utf8"))),n=p(p(o.epics)?.[e.epicId]),i=p(n?.branch_lease),c=Object.freeze({schemaVersion:1,ownerStoryId:e.storyId,sessionId:e.dispatchId,idempotencyKey:e.dispatchId,acquiredAt:r,expiresAt:new Date(Date.parse(r)+600*1e3).toISOString()});let a=!1;return await X(e.projectRoot,u=>{const s=we(u,e.epicId),v=p(s.branch_lease)??i;if(v&&typeof v.expiresAt=="string"&&v.expiresAt>r&&(v.ownerStoryId!==e.storyId||v.idempotencyKey!==e.dispatchId)){a=!0;return}s.branch_mode="epic",s.execution_branch=e.executionBranch,s.branch_lease=c}),a?d("continuous-epic-checkout-writer-active"):{ok:!0,value:c}}catch{return d("continuous-writer-lease-persist-failed")}}async function Ut(e){await X(e.projectRoot,r=>{const t=we(r,e.epicId),o=p(t.branch_lease);o?.ownerStoryId===e.storyId&&o.idempotencyKey===e.dispatchId&&(t.branch_lease=null)})}async function ot(e){try{const r=C(e.lease.projectRoot,".neocortex/state.json"),t=Object.freeze({schemaVersion:1,storyId:e.lease.storyId,epicId:e.lease.epicId,branch:e.lease.executionBranch,baseSha:e.baseSha,headSha:e.headSha,commits:Object.freeze([e.headSha]),idempotencyKey:e.lease.dispatchId,dispatchId:e.lease.dispatchId,bundleId:e.bundle.bundleId,bundleDigest:e.bundle.bundleDigest,graphRevision:e.lease.graphRevision,claimRevision:e.lease.claimRevision,receiptRefs:Object.freeze([...new Set(e.receiptRefs)]),qaVerdict:"passed",reviewVerdict:"approved",qaReceipt:e.qaReceipt,reviewReceipt:e.reviewReceipt,recordedAt:e.recordedAt}),o=z(JSON.parse((await B(r)).toString("utf8"))),n=p(p(o.stories)?.[e.lease.storyId]);let i="persisted",c,a,u,s,v=!1,g;const I=async(h,R,x)=>{const S=await te(e.lease.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]),y=await O(e.lease.projectRoot,["rev-parse","HEAD"]);if(S!==e.lease.executionBranch||y!==e.headSha)throw new Error("continuous-checkpoint-head-raced");if(h.graphRevision!==e.lease.graphRevision||h.claimRevision!==e.lease.claimRevision||h.bundleId!==e.bundle.bundleId||h.bundleDigest!==e.bundle.bundleDigest)throw new Error("continuous-checkpoint-graph-raced");const E=x??z(JSON.parse((await B(r)).toString("utf8"))),D=ie(E,R??await V(e.lease.projectRoot)),J=p(p(D.epics)?.[e.lease.epicId]),Re=p(p(D.stories)?.[e.lease.storyId]),M=Array.isArray(Re?.depends_on)?Re.depends_on.filter(H=>typeof H=="string"):[],be=p(D.stories);if(J?.execution_branch!==e.lease.executionBranch||M.some(H=>{const K=p(be?.[H]);return!K||!["done","completed","merged"].includes(String(K.status))}))throw new Error("continuous-checkpoint-dependency-raced");const fe=G(await T(e.lease.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",e.headSha]));if(fe.length===0||fe.some(H=>!e.lease.authorizedWriteSet.some(K=>ve(K,H))))throw new Error("continuous-checkpoint-write-set-raced");if(!await Ee(e.lease.projectRoot,h,e.lease.storyId,e.lease.epicId,e.lease.executionBranch,void 0,e.lease.authorizedWriteSet))throw new Error("continuous-checkpoint-receipt-revalidation-failed")},b=await V(e.lease.projectRoot,{required:!0}),l=p(p(b.epics[e.lease.epicId])?.branch_lease);if(l?.ownerStoryId!==e.lease.storyId||l.idempotencyKey!==e.lease.dispatchId||l.sessionId!==e.lease.dispatchId||typeof l.expiresAt!="string"||Date.parse(l.expiresAt)<=(e.checkpointNow?.("before-mutation")??Date.now()))return d("continuous-checkpoint-writer-lease-lost");if(!await Ae(e.physicalLock.path,e.physicalLock.owner))return d("continuous-checkpoint-integration-lock-raced");const N=await B(r),k=W("sha256").update(N).digest("hex");await I(t,b);const f=We(z(JSON.parse(N.toString("utf8"))),b,e.lease.epicId,e.lease.storyId);if(f.revision!==e.checkpointAuthority.revision||f.epoch!==e.checkpointAuthority.epoch||f.storyStatus!==e.checkpointAuthority.storyStatus)return d("continuous-graph-revision-stale");const m=await X(e.lease.projectRoot,h=>{const R=we(h,e.lease.epicId),x=p(R.branch_lease);a=x===void 0?void 0:structuredClone(x),u=structuredClone(h),v=h.stories[e.lease.storyId]!==void 0,s=structuredClone(h.stories[e.lease.storyId]??{}),g=structuredClone(R.branch_lease);const S=_t(h,e.lease.storyId),y=p(S.checkpoint)??p(n?.checkpoint);if(y?.idempotencyKey===e.lease.dispatchId){y.baseSha!==e.baseSha||y.headSha!==e.headSha||y.bundleId!==e.bundle.bundleId||y.bundleDigest!==e.bundle.bundleDigest||y.graphRevision!==e.lease.graphRevision||y.claimRevision!==e.lease.claimRevision?i="conflict":(i="reused",c=y,R.branch_lease=null);return}if(x?.ownerStoryId!==e.lease.storyId||x.idempotencyKey!==e.lease.dispatchId||x.sessionId!==e.lease.dispatchId){i="lease-lost";return}S.checkpoint=t,S.status="done",S.last_step=ge;const E=Array.isArray(S.steps_completed)?S.steps_completed.filter(D=>typeof D=="string"):[];S.steps_completed=[...new Set([...E,Ue,ge])],R.branch_lease=null},{expectedRevision:b.revision,preCommit:async h=>{if(a?.ownerStoryId!==e.lease.storyId||a.idempotencyKey!==e.lease.dispatchId||a.sessionId!==e.lease.dispatchId||typeof a.expiresAt!="string"||Date.parse(a.expiresAt)<=(e.checkpointNow?.("pre-commit")??Date.now()))throw new Error("continuous-checkpoint-writer-lease-lost");if(await e.insideCheckpointPreCommit?.({projectRoot:e.lease.projectRoot,storyId:e.lease.storyId,headSha:e.headSha}),!await Ae(e.physicalLock.path,e.physicalLock.owner))throw new Error("continuous-checkpoint-integration-lock-raced");await I(c??t,h);const R=await B(r);if(W("sha256").update(R).digest("hex")!==k)throw new Error("continuous-graph-revision-stale");if(!u)throw new Error("continuous-checkpoint-authority-missing");const x=z(JSON.parse(R.toString("utf8"))),S=We(x,u,e.lease.epicId,e.lease.storyId);if(S.revision!==e.checkpointAuthority.revision||S.epoch!==e.checkpointAuthority.epoch||S.storyStatus!==e.checkpointAuthority.storyStatus)throw new Error("continuous-graph-revision-stale");if(i==="persisted"&&!Ge(x,h,e.lease,t))throw new Error("continuous-checkpoint-projection-raced")}}),A=i;if(A==="conflict")return d("continuous-checkpoint-idempotency-conflict");if(A==="lease-lost")return d("continuous-checkpoint-writer-lease-lost");if(A==="reused"&&c)try{return await I(c),{ok:!0,value:c}}catch{return d("continuous-checkpoint-reused-evidence-invalid")}try{await e.afterCheckpointPersist?.({projectRoot:e.lease.projectRoot,storyId:e.lease.storyId,headSha:e.headSha});const h=await V(e.lease.projectRoot,{required:!0});if(h.revision!==m.document.revision)throw new Error("continuous-checkpoint-post-persist-runtime-raced");await I(t,h);const R=await B(r);if(W("sha256").update(R).digest("hex")!==k)throw new Error("continuous-checkpoint-post-persist-authority-raced");const x=z(JSON.parse(R.toString("utf8")));if(!Ge(x,h,e.lease,t))throw new Error("continuous-checkpoint-post-persist-projection-raced")}catch{const h=await B(r).catch(()=>{}),R=h===void 0||W("sha256").update(h).digest("hex")!==k;return await X(e.lease.projectRoot,x=>{const S=p(x.epics[e.lease.epicId]),y=p(x.stories[e.lease.storyId]),E=h===void 0?void 0:z(JSON.parse(h.toString("utf8")));if(!S||!y||!E||!Ge(E,x,e.lease,t))throw new Error("continuous-checkpoint-cleanup-cas-conflict");if(R){v?or(y,s??{}):delete x.stories[e.lease.storyId],g===void 0?delete S.branch_lease:S.branch_lease=structuredClone(g);return}y.checkpoint=null,y.status="blocked",S.branch_lease=null},{expectedRevision:m.document.revision}).catch(()=>{}),d("continuous-checkpoint-post-persist-raced")}return{ok:!0,value:t}}catch(r){const t=r instanceof Error&&/^continuous-/.test(r.message)?r.message:"continuous-checkpoint-persist-failed";return d(t)}}async function nt(e){try{if(await O(e.lease.projectRoot,["rev-parse","HEAD"])!==e.headSha)return d("continuous-story-evidence-head-raced");const r=await B(C(e.lease.projectRoot,"config","release-gates.v2.json"),"utf8"),t=JSON.parse(r),o=Array.isArray(t.requiredCompleteClasses)?t.requiredCompleteClasses.filter(h=>typeof h=="string"&&/^[a-z0-9-]+$/.test(h)):[];if(t.contract!=="P205-CI-02"||o.length===0)return d("continuous-story-qa-manifest-invalid");const n=xt({processEnv:process.env,platform:process.platform,contract:await kt(e.lease.projectRoot)});if(!n.ok)return d(n.reason);let i;try{i=String((await _e(process.execPath,["scripts/test-root.mjs","--gate","complete"],{cwd:e.lease.projectRoot,env:n.env,encoding:"utf8",maxBuffer:32*1024*1024,timeout:bt(t),killSignal:"SIGTERM"})).stdout)}catch(h){const R=h;return d(Rt({timedOut:R?.killed===!0&&!!R.signal,stderr:typeof R?.stderr=="string"?R.stderr:""}))}if(await e.qaRunner?.({projectRoot:e.lease.projectRoot,storyId:e.lease.storyId,headSha:e.headSha}),await O(e.lease.projectRoot,["rev-parse","HEAD"])!==e.headSha)return d("continuous-story-qa-head-raced");const c=it(e.nowIso),a=await O(e.lease.projectRoot,["rev-list","--count",`${e.baseSha}..${e.headSha}`]),u=await T(e.lease.projectRoot,["show","--no-patch","--format=%H%n%P%n%B",e.headSha]),s=G(await T(e.lease.projectRoot,["diff","--name-only","-z",`${e.baseSha}..${e.headSha}`])),v=jt({storyId:e.lease.storyId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundle.bundleDigest,graphRevision:e.lease.graphRevision,commitBody:u,changedPaths:s}),g=W("sha256").update(r).digest("hex"),I=W("sha256").update(i).digest("hex"),b=Ct({gitEvidenceDigest:v,headSha:e.headSha,graphRevision:e.lease.graphRevision,manifestDigest:g,gateIds:o,resultDigest:I}),l=`story-qa:${b}`,N=Object.freeze({schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",evidenceVersion:"p205-execution-v2",storyId:e.lease.storyId,epicId:e.lease.epicId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundle.bundleDigest,graphRevision:e.lease.graphRevision,contract:"P205-CI-02",command:Dt,manifestDigest:g,gateIds:Object.freeze(o),resultDigest:I,sourceEvidenceDigest:b,verdict:"passed",checkedAt:c,receiptRef:l}),k=[`Neocortex-Story: ${e.lease.storyId}`,`Neocortex-Epic: ${e.lease.epicId}`,`Neocortex-Bundle-Digest: ${e.bundle.bundleDigest}`,`Neocortex-Graph-Revision: ${e.lease.graphRevision}`];if(a!=="1"||!k.every(h=>u.includes(h))||s.length===0||s.some(h=>!e.lease.authorizedWriteSet.some(R=>ve(R,h))))return d("continuous-story-review-evidence-rejected");const f=W("sha256").update(["root-commit-range-review-v1",e.lease.storyId,e.baseSha,e.headSha,e.bundle.bundleDigest,e.lease.graphRevision,l,W("sha256").update(u).digest("hex"),[...s].sort().join(",")].join("\0")).digest("hex"),m=`story-review:${f}`,A=Object.freeze({schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:e.lease.storyId,epicId:e.lease.epicId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundle.bundleDigest,graphRevision:e.lease.graphRevision,sourceEvidenceDigest:f,qaReceiptRef:l,verdict:"approved",reviewedAt:c,receiptRef:m});return{ok:!0,value:{qaReceipt:N,reviewReceipt:A}}}catch{return d("continuous-story-evidence-production-failed")}}function it(e){return Number.isFinite(Date.parse(e))?new Date(Date.parse(e)).toISOString():new Date().toISOString()}function Xt(e,r,t){if(r!==void 0)try{const o=e===void 0?{}:z(JSON.parse(e.toString("utf8"))),n=z(JSON.parse(r.toString("utf8"))),i=structuredClone(o),c=p(p(o.stories)?.[t]),a=p(p(n.stories)?.[t]),u=er(i,"stories"),s=structuredClone(c??{});for(const v of["status","last_step","steps_completed","last_updated","blocked_reason","blocked_at","implementation_evidence","validation_evidence","qa_gate"])a&&Object.prototype.hasOwnProperty.call(a,v)&&(s[v]=structuredClone(a[v]));return u[t]=s,Buffer.from(`${JSON.stringify(i,null,2)}
52
+ `)}catch{return Buffer.from("{invalid-child-state")}}function er(e,r){const t=p(e[r]);if(t)return t;const o={};return e[r]=o,o}function z(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("record expected");return e}function p(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function tr(e,r,t){return ze(t,e)||ze(r,t)?{ok:!0,value:r}:ze(r,e)?{ok:!0,value:t}:d("continuous-context-merge-conflict")}function rr(e,r,t){try{const o=at($e(e),$e(r),$e(t));return o.ok?{ok:!0,value:o.value===void 0?void 0:Buffer.from(`${JSON.stringify(o.value,null,2)}
53
+ `)}:o}catch{return d("continuous-state-merge-invalid")}}function $e(e){return e===void 0?void 0:JSON.parse(e.toString("utf8"))}function at(e,r,t){if(Se(t,e)||Se(r,t))return{ok:!0,value:r};if(Se(r,e))return{ok:!0,value:t};if(Te(e)&&Te(r)&&Te(t)){const o={};for(const n of[...new Set([...Object.keys(e),...Object.keys(r),...Object.keys(t)])].sort()){const i=at(e[n],r[n],t[n]);if(!i.ok)return i;i.value!==void 0&&(o[n]=i.value)}return{ok:!0,value:o}}if(Array.isArray(e)&&Array.isArray(r)&&Array.isArray(t)&&ct(e,r)&&ct(e,t)){const o=[...e,...r.slice(e.length),...t.slice(e.length)],n=new Set;return{ok:!0,value:o.filter(i=>{const c=JSON.stringify(i);return n.has(c)?!1:(n.add(c),!0)})}}return d("continuous-state-merge-conflict")}function Te(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ct(e,r){return e.length<=r.length&&e.every((t,o)=>Se(t,r[o]))}function Se(e,r){return JSON.stringify(e)===JSON.stringify(r)}function ze(e,r){return e===void 0||r===void 0?e===r:e.equals(r)}function G(e){return e.split("\0").filter(Boolean)}function oe(e){const r=de(e);return r.length>0&&r.length<=1024&&!ke(r)&&!/^[A-Za-z]:\//.test(r)&&!r.split("/").includes("..")&&!r.includes("\0")&&!r.startsWith("/")}function de(e){return e.replaceAll("\\","/").replace(/^\.\//,"").replace(/\/{2,}/g,"/")}function st(e){const r=e.map(de).filter(oe);return[...new Set(r)].sort()}function ve(e,r){const t=de(e),o=de(r);return t===o||t.endsWith("/")&&o.startsWith(t)}function dt(e){return e.length>0&&e.length<=240&&!e.startsWith("-")&&!e.startsWith("/")&&!e.endsWith("/")&&!e.endsWith(".lock")&&!e.includes("..")&&!e.includes("\\")&&!e.includes("@{")&&!e.includes("//")&&/^[A-Za-z0-9._/-]+$/.test(e)}function ut(e,r){return e.length===r.length&&e.every((t,o)=>t===r[o])}async function ue(e,r,t,o){const n=z(JSON.parse(await B(C(e,".neocortex/state.json"),"utf8")));return We(n,o??await V(e),r,t)}function We(e,r,t,o){const n=ie(e,r),i=p(n.epics),c=p(n.stories),a=p(i?.[t])??{},u=(Array.isArray(a.stories)?a.stories:Array.isArray(a.story_ids)?a.story_ids:[]).filter(I=>typeof I=="string"),s=u.length>0?u:Object.entries(c??{}).filter(([I,b])=>p(b)?.epic_id===t||I.startsWith(`${t}.`)).map(([I])=>I).sort(),v=["status","depends_on","files_to_modify","contracts","contract_refs","shared_surfaces","steps_completed","last_step","branch_name","physicalMergeStatus","merged","checkpoint","planning","attempts","retry_count","rollback_receipt","cancelled_at"],g=Object.fromEntries(s.map(I=>{const b=p(c?.[I])??{};return[I,Object.fromEntries(v.filter(l=>Object.prototype.hasOwnProperty.call(b,l)).map(l=>[l,b[l]]))]}));return{revision:Ie({epicId:t,epic:{stories:s,status:a.status??null,branch_mode:a.branch_mode??null,execution_branch:a.execution_branch??null,graph_revision:a.graph_revision??null,depends_on:a.depends_on??null,planning:a.planning??null,execution_plan:a.execution_plan??null,waves:a.waves??null,current_wave:a.current_wave??null,replan:a.replan??null,replan_revision:a.replan_revision??null,dependency_graph:a.dependency_graph??null,scheduler:a.scheduler??null,attempts:a.attempts??null,retry_count:a.retry_count??null},stories:g}),epoch:typeof a.graph_revision=="string"?a.graph_revision:null,storyStatus:typeof p(c?.[o])?.status=="string"?String(p(c?.[o])?.status):null}}function Ge(e,r,t,o){const n=ie(e,r),i=p(p(n.epics)?.[t.epicId]),c=p(p(n.stories)?.[t.storyId]),a=Array.isArray(c?.steps_completed)?c.steps_completed.filter(u=>typeof u=="string"):[];return!!(i&&c&&i.branch_lease===null&&c.status==="done"&&c.last_step===ge&&a.includes(Ue)&&a.includes(ge)&&he(c.checkpoint)===he(o))}function or(e,r){for(const t of Object.keys(e))delete e[t];Object.assign(e,structuredClone(r))}async function nr(e,r){return(await ue(e,r,"")).revision}function Ie(e){return W("sha256").update(he(e)).digest("hex")}function he(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(he).join(",")}]`:`{${Object.entries(e).sort(([r],[t])=>r.localeCompare(t)).map(([r,t])=>`${JSON.stringify(r)}:${he(t)}`).join(",")}}`}function ir(e,r){const t=(e??[]).filter(o=>/^[A-Za-z0-9._/:@#-]{1,200}$/.test(o)&&!o.includes(".."));return Object.freeze([...new Set(t.length>0?t:[`dispatch:${r}`])].sort())}function ar(e){return e.replace(/[^A-Za-z0-9._-]/g,"-").slice(0,80)}function d(e){return{ok:!1,reasonCode:e}}function q(e,r){return e instanceof Error&&"code"in e&&e.code===r}async function ne(e,r){try{await L(e,r);const t=C(e,"owner.json");await F(t,e);const o=JSON.parse(await B(t,"utf8"));if(!Number.isSafeInteger(o.pid)||Number(o.pid)<=0||typeof o.createdAt!="string"||!Number.isFinite(Date.parse(o.createdAt))||typeof o.nonce!="string"||!/^[a-f0-9]{32}$/.test(o.nonce))throw new Error("continuous-sandbox-lease-owner-invalid");return{pid:Number(o.pid),createdAt:o.createdAt,nonce:o.nonce}}catch(t){if(q(t,"ENOENT"))return;throw t}}function ht(e,r){return e?.pid===r.pid&&e.createdAt===r.createdAt&&e.nonce===r.nonce}function cr(e){try{return process.kill(e,0),!0}catch(r){return q(r,"EPERM")}}async function Le(e,r){try{await L(e,r);const t=C(e,".git");await L(t,e);const o=C(t,"neocortex-sandbox.json");await F(o,t);const n=JSON.parse(await B(o,"utf8"));if(n.schemaVersion!==1||typeof n.workspaceOwnerNonce!="string"||!/^[a-f0-9]{32}$/.test(n.workspaceOwnerNonce)||!/^[a-f0-9]{64}$/.test(n.graphAuthorityRevision)||!(n.graphAuthorityEpoch===null||/^[a-f0-9]{64}$/.test(n.graphAuthorityEpoch))||!(n.graphAuthorityStoryStatus===null||typeof n.graphAuthorityStoryStatus=="string"&&n.graphAuthorityStoryStatus.length<=80)||typeof n.workspaceIdentity?.dev!="string"||!/^[0-9]+$/.test(n.workspaceIdentity.dev)||typeof n.workspaceIdentity?.ino!="string"||!/^[0-9]+$/.test(n.workspaceIdentity.ino))throw new Error("continuous-sandbox-metadata-invalid");return n}catch(t){if(q(t,"ENOENT"))return;throw t}}async function sr(e,r,t,o){await L(e,r);const n=C(e,".git");await L(n,e);const i=C(n,"neocortex-sandbox.json");await re(e,".git/neocortex-sandbox.json",Buffer.from(`${JSON.stringify(t,null,2)}
54
+ `),o),await F(i,n)}async function dr(e,r){try{await F(e,r);const t=JSON.parse(await B(e,"utf8"));return typeof t.childHeadSha=="string"&&typeof t.rootHeadSha=="string"&&/^[a-f0-9]{40,64}$/.test(t.childHeadSha)&&/^[a-f0-9]{40,64}$/.test(t.rootHeadSha)&&t.bundle?.schemaVersion===1&&t.checkpoint?.schemaVersion===1?t:void 0}catch(t){if(q(t,"ENOENT"))return;throw t}}async function ur(e,r){try{const t=z(JSON.parse(await B(C(e.projectRoot,".neocortex/state.json"),"utf8"))),o=ie(t,await V(e.projectRoot)),n=p(p(o.stories)?.[e.storyId]),i=p(n?.checkpoint);return i?.idempotencyKey===r.idempotencyKey&&i.headSha===r.headSha&&i.bundleDigest===r.bundleDigest&&p(p(o.epics)?.[e.epicId])?.branch_lease===null&&await Ee(e.projectRoot,i,e.storyId,e.epicId,e.executionBranch,void 0,e.authorizedWriteSet)}catch{return!1}}async function hr(e,r,t){try{const o=z(JSON.parse(await B(C(e.projectRoot,".neocortex/state.json"),"utf8"))),n=ie(o,await V(e.projectRoot)),i=p(p(n.stories)?.[e.storyId]),c=p(i?.checkpoint);return c?.schemaVersion!==1||c.storyId!==e.storyId||c.epicId!==e.epicId||c.branch!==e.executionBranch||c.baseSha!==t.baseSha||c.headSha!==t.headSha||c.idempotencyKey!==e.dispatchId||c.dispatchId!==e.dispatchId||c.bundleId!==r.bundleId||c.bundleDigest!==r.bundleDigest||c.graphRevision!==e.graphRevision||c.claimRevision!==e.claimRevision||p(p(n.epics)?.[e.epicId])?.branch_lease!==null||!await Ee(e.projectRoot,c,e.storyId,e.epicId,e.executionBranch,void 0,e.authorizedWriteSet)?void 0:c}catch{return}}async function fr(e,r){const t=(await te(e.projectRoot,["log","--format=%H","--fixed-strings",`--grep=Neocortex-Dispatch: ${e.dispatchId}`]))?.split(`
55
+ `).filter(g=>/^[a-f0-9]{40,64}$/.test(g))??[];if(t.length!==1)return;const o=t[0];if(!await se(e.projectRoot,["merge-base","--is-ancestor",o,"HEAD"]))return;const n=await O(e.projectRoot,["show","-s","--format=%B",o]),i=new Set(n.split(`
56
+ `).map(g=>g.trim()));for(const g of[`Neocortex-Story: ${e.storyId}`,`Neocortex-Epic: ${e.epicId}`,`Neocortex-Execution-Branch: ${e.executionBranch}`,`Neocortex-Prepared-Base: ${e.baseSha}`,`Neocortex-Dispatch: ${e.dispatchId}`,`Neocortex-Bundle: ${r.bundleId}`,`Neocortex-Bundle-Digest: ${r.bundleDigest}`,`Neocortex-Graph-Revision: ${e.graphRevision}`,`Neocortex-Claim-Revision: ${e.claimRevision}`])if(!i.has(g))return;const c=qe(n,"Neocortex-Checkpoint-Authority"),a=qe(n,"Neocortex-Checkpoint-Epoch"),u=qe(n,"Neocortex-Checkpoint-Story-Status");if(!c||!/^[a-f0-9]{64}$/.test(c)||!a||!(a==="null"||/^[a-f0-9]{64}$/.test(a))||!u||u.length>80)return;const s=await te(e.projectRoot,["rev-parse",`${o}^`]);if(!s||!/^[a-f0-9]{40,64}$/.test(s))return;const v=G(await T(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",o]));if(!(v.length===0||v.some(g=>!r.authorizedWriteSet.some(I=>ve(I,g)))))return{baseSha:s,headSha:o,checkpointAuthority:{revision:c,epoch:a==="null"?null:a,storyStatus:u==="null"?null:u}}}function qe(e,r){const t=`${r}: `,o=e.split(`
57
+ `).map(n=>n.trim()).filter(n=>n.startsWith(t));return o.length===1?o[0].slice(t.length):void 0}async function He(e,r,t,o,n,i){const c=j(e);await L(c,j(c));try{await F(e,c)}catch(a){if(!q(a,"ENOENT"))throw a}await re(c,$(e),Buffer.from(`${JSON.stringify({childHeadSha:r,rootHeadSha:t,bundle:o,checkpoint:n})}
58
+ `),i),await F(e,c)}export{zt as STORY_WORKTREE_INTEGRATION_ROOT_OWNED,kr as createAnchoredContinuousStoryCommandRunner,Tt as createBranchlessContinuousStoryWorkspaceManager,Wt as createStoryWorktreeContinuousStoryWorkspaceManager,xr as selectContinuousStoryWorkspaceManager,Gt as selectContinuousStoryWorkspaceStrategy};
@@ -12,3 +12,4 @@ export interface CliEpicTerminalGitAdapterOptions {
12
12
  readonly now?: () => string;
13
13
  }
14
14
  export declare function createCliEpicTerminalGitAdapter(projectRoot: string, options?: CliEpicTerminalGitAdapterOptions): EpicTerminalGitAdapter;
15
+ export declare function publicLifecycleEvidenceCause(error: unknown): string | undefined;