@ornexus/neocortex 4.66.54 → 4.66.55
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/release-source.json +1 -1
- package/dist/sbom.cdx.json +1190 -1190
- package/install.ps1 +1 -1
- package/install.sh +1 -1
- package/package.json +2 -2
- package/packages/client/dist/commands/invoke.js +82 -82
- package/packages/client/dist/errors/continuation-diagnostics.d.ts +53 -0
- package/packages/client/dist/errors/continuation-diagnostics.js +1 -0
- package/packages/client/dist/private-execution/isolated-admission.js +12 -12
- package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +6 -6
- package/packages/client/dist/runner/headless/run-yoloop.js +3 -3
- package/packages/shared/dist/invocation/index.d.ts +1 -0
- package/packages/shared/dist/invocation/index.js +1 -0
- package/packages/shared/dist/invocation/planning-generation-failure.d.ts +56 -0
- package/packages/shared/dist/invocation/planning-generation-failure.js +65 -0
- package/targets-stubs/antigravity/gemini.md +1 -1
- package/targets-stubs/antigravity/neocortex.md +1 -1
- package/targets-stubs/antigravity/skill/SKILL.md +1 -1
- package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex-root.md +2 -2
- package/targets-stubs/claude-code/neocortex-sentinel.md +1 -1
- package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex.md +2 -2
- package/targets-stubs/codex/AGENTS.md +1 -1
- package/targets-stubs/codex/neocortex.toml +1 -1
- package/targets-stubs/cursor/agent.md +2 -2
- package/targets-stubs/deepseek-harness/SKILL.md +1 -1
- package/targets-stubs/gemini-cli/agent.md +2 -2
- package/targets-stubs/gemini-cli/agents/neocortex.md +2 -2
- package/targets-stubs/grok/SKILL.md +1 -1
- package/targets-stubs/kimi/neocortex.md +1 -1
- package/targets-stubs/openclaw/SKILL.md +1 -1
- package/targets-stubs/opencode/neocortex-root.md +2 -2
- package/targets-stubs/opencode/neocortex.md +2 -2
- package/targets-stubs/vscode/neocortex.agent.md +2 -2
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
export declare const PLANNING_RESEARCH_ADMISSION_GATE = "private-execution-planning-research-admission-unverified";
|
|
2
|
+
export declare function gitReconciliationSummary(reasonCode: string): string;
|
|
3
|
+
declare const RESEARCH_GUIDANCE: {
|
|
4
|
+
readonly 'planning-research-incomplete': "Complete the missing research in the isolated P02 attempt. Record the relevant public documentation and a dated search for reference implementations. Preserve the accepted diagnosis and resume the same claim after correcting the research.";
|
|
5
|
+
readonly 'planning-research-document-identity-invalid': "Check the research document identity, current stage, status and body against the admitted work. Preserve the accepted diagnosis.";
|
|
6
|
+
readonly 'planning-research-index-drift': "Recheck the planning index transition for this epic. The isolated research attempt may update only its research document and the corresponding index entry.";
|
|
7
|
+
readonly 'planning-research-index-invalid': "Check that the planning index is valid JSON for this claim before resuming the accepted diagnosis.";
|
|
8
|
+
readonly 'planning-research-index-predecessor-invalid': "Verify the committed diagnosis entry and its accepted artifact references before reattempting research.";
|
|
9
|
+
readonly 'planning-research-write-scope-invalid': "Review the isolated checkout and restrict the research candidate to its two admitted files.";
|
|
10
|
+
readonly 'planning-research-predecessor-mismatch': "Re-read the accepted diagnosis receipt and intake revision for the same claim before starting research.";
|
|
11
|
+
readonly 'planning-research-predecessor-invalid': "Verify the accepted diagnosis receipt for this claim before starting research.";
|
|
12
|
+
readonly 'planning-research-state-drift': "Compare the project state with the snapshot admitted for this claim.";
|
|
13
|
+
readonly 'planning-research-source-artifact-drift': "Compare the accepted diagnosis artifacts with their committed hashes. Reconcile the predecessor before resuming research.";
|
|
14
|
+
readonly 'planning-research-already-exists': "Reconcile the existing research document with the same claim before another isolated attempt.";
|
|
15
|
+
readonly 'planning-research-admission-unknown': "Inspect the isolated research document, planning index and accepted diagnosis receipts for this claim.";
|
|
16
|
+
};
|
|
17
|
+
type ResearchReason = keyof typeof RESEARCH_GUIDANCE;
|
|
18
|
+
export declare class PlanningResearchAdmissionError extends Error {
|
|
19
|
+
readonly reasonCode: ResearchReason;
|
|
20
|
+
constructor(cause: unknown);
|
|
21
|
+
}
|
|
22
|
+
export declare function projectPlanningResearchAdmissionFailure(value: unknown): {
|
|
23
|
+
stage: string;
|
|
24
|
+
reasonCode: "planning-research-incomplete" | "planning-research-document-identity-invalid" | "planning-research-index-drift" | "planning-research-index-invalid" | "planning-research-index-predecessor-invalid" | "planning-research-write-scope-invalid" | "planning-research-predecessor-mismatch" | "planning-research-predecessor-invalid" | "planning-research-state-drift" | "planning-research-source-artifact-drift" | "planning-research-already-exists" | "planning-research-admission-unknown";
|
|
25
|
+
guidance: "Complete the missing research in the isolated P02 attempt. Record the relevant public documentation and a dated search for reference implementations. Preserve the accepted diagnosis and resume the same claim after correcting the research." | "Check the research document identity, current stage, status and body against the admitted work. Preserve the accepted diagnosis." | "Recheck the planning index transition for this epic. The isolated research attempt may update only its research document and the corresponding index entry." | "Check that the planning index is valid JSON for this claim before resuming the accepted diagnosis." | "Verify the committed diagnosis entry and its accepted artifact references before reattempting research." | "Review the isolated checkout and restrict the research candidate to its two admitted files." | "Re-read the accepted diagnosis receipt and intake revision for the same claim before starting research." | "Verify the accepted diagnosis receipt for this claim before starting research." | "Compare the project state with the snapshot admitted for this claim." | "Compare the accepted diagnosis artifacts with their committed hashes. Reconcile the predecessor before resuming research." | "Reconcile the existing research document with the same claim before another isolated attempt." | "Inspect the isolated research document, planning index and accepted diagnosis receipts for this claim.";
|
|
26
|
+
publicSafe: true;
|
|
27
|
+
} | undefined;
|
|
28
|
+
declare const RUNNER_STAGES: readonly ["admission", "runtime-selection", "continuity-store", "execution"];
|
|
29
|
+
export type RunnerFailureStage = typeof RUNNER_STAGES[number];
|
|
30
|
+
declare const RUNNER_GUIDANCE: {
|
|
31
|
+
readonly 'sqlite-adapter-unavailable': "Check that the continuity SQLite adapter is installed and compatible with the same Node.js runtime that starts Neocortex.";
|
|
32
|
+
readonly 'sqlite-integrity-failed': "Inspect the continuity database integrity and preserve the database and its sidecars for recovery.";
|
|
33
|
+
readonly 'sqlite-migration-failed': "Inspect the continuity store migration and preserve its original database and sidecars.";
|
|
34
|
+
readonly 'sqlite-migration-conflict': "Inspect the continuity store schema and any other writer before resuming.";
|
|
35
|
+
readonly 'sqlite-mutation-failed': "Inspect the continuity store write permissions and available space on its filesystem.";
|
|
36
|
+
readonly 'runner-storage-capacity': "Verify data and metadata capacity on the worktree and continuity-store filesystems.";
|
|
37
|
+
readonly 'runner-filesystem-permission': "Check the runner account permissions on the worktree and continuity-store paths.";
|
|
38
|
+
readonly 'runner-operation-timeout': "Inspect the unfinished local operation and reconcile any existing dispatch before resuming.";
|
|
39
|
+
readonly 'runner-failure-unclassified': "Inspect the reported runner stage and reconcile any recorded dispatch or checkpoint before resuming.";
|
|
40
|
+
};
|
|
41
|
+
type RunnerReason = keyof typeof RUNNER_GUIDANCE;
|
|
42
|
+
export declare function identifyRunnerFailure(stage: RunnerFailureStage, error: unknown): {
|
|
43
|
+
stage: "execution" | "admission" | "runtime-selection" | "continuity-store";
|
|
44
|
+
reasonCode: "sqlite-adapter-unavailable" | "sqlite-integrity-failed" | "sqlite-migration-failed" | "sqlite-migration-conflict" | "sqlite-mutation-failed" | "runner-storage-capacity" | "runner-filesystem-permission" | "runner-operation-timeout" | "runner-failure-unclassified";
|
|
45
|
+
publicSafe: true;
|
|
46
|
+
};
|
|
47
|
+
export declare function projectRunnerFailure(value: unknown): {
|
|
48
|
+
stage: RunnerFailureStage;
|
|
49
|
+
reasonCode: RunnerReason;
|
|
50
|
+
guidance: "Check that the continuity SQLite adapter is installed and compatible with the same Node.js runtime that starts Neocortex." | "Inspect the continuity database integrity and preserve the database and its sidecars for recovery." | "Inspect the continuity store migration and preserve its original database and sidecars." | "Inspect the continuity store schema and any other writer before resuming." | "Inspect the continuity store write permissions and available space on its filesystem." | "Verify data and metadata capacity on the worktree and continuity-store filesystems." | "Check the runner account permissions on the worktree and continuity-store paths." | "Inspect the unfinished local operation and reconcile any existing dispatch before resuming." | "Inspect the reported runner stage and reconcile any recorded dispatch or checkpoint before resuming.";
|
|
51
|
+
publicSafe: true;
|
|
52
|
+
} | undefined;
|
|
53
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const l="private-execution-planning-research-admission-unverified",o={"git-reconciliation-state-unavailable":"Inspect the project state and the Git lifecycle store for this checkout before resuming.","git-reconciliation-origin-query-failed":"Verify access to the exact recorded origin branch with the same account that runs Neocortex.","git-reconciliation-origin-ref-missing":"Verify that the recorded origin branch exists on the configured remote.","git-reconciliation-origin-fetch-failed":"Verify that Git can read the advertised origin commit and that the local object store is writable.","git-reconciliation-origin-head-raced":"The origin changed during inspection. Verify the current upstream head before resuming.","git-reconciliation-worktree-inventory-unavailable":"Verify that Git can list the repository worktrees and read the Git common directory.","git-reconciliation-local-ref-inventory-unavailable":"Verify that Git can read the repository head refs and the common directory.","git-reconciliation-remote-ref-inventory-unavailable":"Check access to the full remote heads inventory, beyond a single branch lookup.","git-reconciliation-pr-inventory-unavailable":"Check GitHub CLI access to pull requests in the repository configured as origin.","git-reconciliation-base-fetch-failed":"Verify that the remote can serve the advertised integration base commit.","git-reconciliation-managed-ref-fetch-failed":"Verify that the remote can serve the advertised commit of the managed ref before reconciling it."};function u(e){return Object.hasOwn(o,e)?o[e]:"Headless yoloop paused at a fail-closed Git reconciliation boundary."}const s={"planning-research-incomplete":"Complete the missing research in the isolated P02 attempt. Record the relevant public documentation and a dated search for reference implementations. Preserve the accepted diagnosis and resume the same claim after correcting the research.","planning-research-document-identity-invalid":"Check the research document identity, current stage, status and body against the admitted work. Preserve the accepted diagnosis.","planning-research-index-drift":"Recheck the planning index transition for this epic. The isolated research attempt may update only its research document and the corresponding index entry.","planning-research-index-invalid":"Check that the planning index is valid JSON for this claim before resuming the accepted diagnosis.","planning-research-index-predecessor-invalid":"Verify the committed diagnosis entry and its accepted artifact references before reattempting research.","planning-research-write-scope-invalid":"Review the isolated checkout and restrict the research candidate to its two admitted files.","planning-research-predecessor-mismatch":"Re-read the accepted diagnosis receipt and intake revision for the same claim before starting research.","planning-research-predecessor-invalid":"Verify the accepted diagnosis receipt for this claim before starting research.","planning-research-state-drift":"Compare the project state with the snapshot admitted for this claim.","planning-research-source-artifact-drift":"Compare the accepted diagnosis artifacts with their committed hashes. Reconcile the predecessor before resuming research.","planning-research-already-exists":"Reconcile the existing research document with the same claim before another isolated attempt.","planning-research-admission-unknown":"Inspect the isolated research document, planning index and accepted diagnosis receipts for this claim."};function r(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function c(e){return typeof e=="string"&&Object.hasOwn(s,e)?e:void 0}class f extends Error{reasonCode;constructor(i){super(l),this.reasonCode=c(i instanceof Error?i.message:void 0)??"planning-research-admission-unknown"}}function g(e){const i=r(e),t=c(i?.reasonCode);return i?.publicSafe===!0&&t?{stage:"planning-research",reasonCode:t,guidance:s[t],publicSafe:!0}:void 0}const p=["admission","runtime-selection","continuity-store","execution"],a={"sqlite-adapter-unavailable":"Check that the continuity SQLite adapter is installed and compatible with the same Node.js runtime that starts Neocortex.","sqlite-integrity-failed":"Inspect the continuity database integrity and preserve the database and its sidecars for recovery.","sqlite-migration-failed":"Inspect the continuity store migration and preserve its original database and sidecars.","sqlite-migration-conflict":"Inspect the continuity store schema and any other writer before resuming.","sqlite-mutation-failed":"Inspect the continuity store write permissions and available space on its filesystem.","runner-storage-capacity":"Verify data and metadata capacity on the worktree and continuity-store filesystems.","runner-filesystem-permission":"Check the runner account permissions on the worktree and continuity-store paths.","runner-operation-timeout":"Inspect the unfinished local operation and reconcile any existing dispatch before resuming.","runner-failure-unclassified":"Inspect the reported runner stage and reconcile any recorded dispatch or checkpoint before resuming."},d=Object.freeze({ENOSPC:"runner-storage-capacity",EACCES:"runner-filesystem-permission",EPERM:"runner-filesystem-permission",ETIMEDOUT:"runner-operation-timeout"});function m(e,i){const t=r(i)?.code,h=typeof t=="string"&&t.startsWith("sqlite-")&&Object.hasOwn(a,t)?t:typeof t=="string"&&Object.hasOwn(d,t)?d[t]:"runner-failure-unclassified";return{stage:e,reasonCode:h,publicSafe:!0}}function y(e){const i=r(e),t=i?.stage,n=i?.reasonCode;if(!(i?.publicSafe!==!0||!p.includes(t)||typeof n!="string"||!Object.hasOwn(a,n)))return{stage:t,reasonCode:n,guidance:a[n],publicSafe:!0}}export{l as PLANNING_RESEARCH_ADMISSION_GATE,f as PlanningResearchAdmissionError,u as gitReconciliationSummary,m as identifyRunnerFailure,g as projectPlanningResearchAdmissionFailure,y as projectRunnerFailure};
|
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
import{execFileSync as Ft,spawnSync as vt}from"node:child_process";import{createHash as F}from"node:crypto";import{existsSync as nt,lstatSync as R,readFileSync as m,realpathSync as ht,writeFileSync as mt}from"node:fs";import{isAbsolute as ot,join as a,relative as dt,sep as
|
|
2
|
-
`)])));if(
|
|
3
|
-
`))?.[1];if(!K)return!1;const
|
|
4
|
-
`),at=gt=>{const ct=
|
|
5
|
-
`))?.[1],y=O=>{const U=
|
|
6
|
-
`).filter(
|
|
1
|
+
import{execFileSync as Ft,spawnSync as vt}from"node:child_process";import{createHash as F}from"node:crypto";import{existsSync as nt,lstatSync as R,readFileSync as m,realpathSync as ht,writeFileSync as mt}from"node:fs";import{isAbsolute as ot,join as a,relative as dt,sep as _t}from"node:path";import{isDeepStrictEqual as S}from"node:util";import{PlanningResearchAdmissionError as Bt}from"../errors/continuation-diagnostics.js";import{readPrivateYoloFrozenWriteSet as Ct,verifyPrivateYoloCandidateWriteSet as zt,verifyPrivateYoloCleanBaseline as Lt}from"./clean-baseline.js";import{isPrivateIsolatedWorkspacePlatform as bt,PRIVATE_EPIC_PENDING_SIDECAR as et,privateIsolatedWorkspaceModeVerified as xt,privatePendingEpicSidecarVerified as Ht}from"./isolated-workspace.js";import{loadPactPrivateAnswers as Jt}from"../commands/architecture-answers.js";import{derivePactWriteSet as Rt}from"./pact-write-set.js";import{deriveUxCandidateWriteSet as Mt,deriveUxWriteSet as qt}from"./ux-write-set.js";import{validateUxCandidateSource as Gt}from"./ux-source-validation.js";import{validatePactTestSource as Wt}from"./pact-test-source.js";import{classifyProjectMemoryUpdate as Yt}from"../memory/project-memory-writer.js";import{withoutVerifiedProjectIdentityStatus as Ut}from"../migrations/project-identity.js";import{privateRootMemoryEffect as yt,privateRootMemorySourceMatches as Vt,privateRootMemorySourceMatchReason as Xt}from"./root-memory-scope.js";import{inspectPactToolchain as Kt,planPactToolchainManifest as Zt}from"./pact-toolchain.js";import{acceptedPlanningDiagnosisPredecessor as Qt,planningPendingSidecarDigest as At}from"./planning-diagnosis-checkpoint.js";import{acceptedPlanningResearchPredecessor as kt}from"./planning-research-checkpoint.js";import{confirmPropertyTestPlan as St,renderPropertyTestConfiguration as It}from"./property-test-plan.js";import{validatePropertyTestTypeScriptSource as te}from"./property-test-source.js";const Z=16*1024*1024,st=1024,ut="acd455ed0e39d98b90fb57391db75e366e4c5604db043e03a89a20e33d643c3c",ee="81f50aaa801c1660eabe46e645501acbfb3e9873410c991e1496c014ca75c369",Et="fa2194f89c01f07e225fd6f39e98e679f628e072239b6cd0af3ee527f0722518",re="8636f22ec5950410902448ee1e9cb4947359ac98df518742bddbbb367468e3ae";function I(t,r){return typeof t=="string"&&t.length<=128&&F("sha256").update(t).digest("hex")===r}function Pt(){const t={...process.env};for(const r of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete t[r];return t}function G(t,r){return Ft("git",[...r],{cwd:t,env:Pt(),stdio:["ignore","pipe","pipe"],timeout:3e4,maxBuffer:Z})}function J(t,r){return G(t,r).toString("utf8").trim()}function B(t,r=!1){return G(t,["status","--porcelain=v1","-z","--untracked-files=all",...r?["--ignored=matching"]:[]])}function rt(t){return!!t&&!ot(t)&&!t.includes("\\")&&!t.includes("\0")&&!t.split("/").some(r=>!r||r==="."||r===".."||r===".git")}function P(t,r){const e=r.split("/");let o=t;for(const i of e.slice(0,-1)){o=a(o,i);try{const s=R(o);if(!s.isDirectory()||s.isSymbolicLink())throw new Error("path-boundary")}catch(s){if(s.code==="ENOENT")return;throw s}}try{const i=R(a(t,r));if(!i.isFile()||i.isSymbolicLink()||i.size>Z)throw new Error("path-boundary")}catch(i){if(i.code!=="ENOENT")throw i}}function $t(t){const r=[...t.matchAll(/\/\/\s*arch:keep-start[^\n]*\n[\s\S]*?\/\/\s*arch:keep-end[^\n]*/g)].map(i=>i[0]),e=(t.match(/arch:keep-start/g)??[]).length,o=(t.match(/arch:keep-end/g)??[]).length;if(e!==o||e!==r.length)throw new Error("architecture-keep-marker-invalid");return r}function M(t,r=!1,e=!1,o=[],i){const s=[],n=[],l=t.toString("utf8").split("\0").filter(Boolean),p=i?Ut(i,l):l;for(const c of p){if(c.length<4||c[2]!==" ")throw new Error("status-invalid");const d=c.slice(0,2),h=c.slice(3);if(!rt(h)||d!=="??"&&d!==" M"&&d!==" D"&&!(d===" T"&&o.includes(h))&&!(e&&d==="!!"&&h===et))throw new Error("status-invalid");s.push(h),d==="??"&&n.push(h)}if(!r&&s.length===0||s.length>st||new Set(s).size!==s.length)throw new Error("status-invalid");return{paths:s.sort(),untracked:n.sort()}}function lt(t,r,e,o){const i=G(r,["ls-tree","-z",e,"--",o]).toString("utf8");if(!i)try{return R(a(t,o)),!1}catch(n){return n.code==="ENOENT"}const s=/^([0-7]{6}) blob [a-f0-9]{40,64}\t([^\0]+)\0$/.exec(i);if(!s||s[2]!==o||!["100644","100755"].includes(s[1]))return!1;try{const n=R(a(t,o));return!n.isFile()||n.isSymbolicLink()||n.size>Z||!!(n.mode&73)!=(s[1]==="100755")?!1:m(a(t,o)).equals(G(r,["show",`${e}:${o}`]))}catch{return!1}}function $e(t,r,e,o){return rt(o)&&/^[a-f0-9]{40,64}$/.test(e)&<(t,r,e,o)}function it(t,r){try{const e=a(t,et);return Ht(t)&&F("sha256").update(m(e)).digest("hex")===r}catch{return!1}}function ft(t,r,e,o,i,s){const n=new Set(o),l=s?yt(s).files.map(d=>d.path):[],p=M(B(t),!0,!!i,l,i?t:void 0),c=s?Xt(s,t,r,e):"matched";if(c!=="matched")throw new Error(`root-memory-${c}`);if(!p.paths.every(d=>n.has(d)||l.includes(d)||d===et&&!!i&&it(t,i)))throw new Error("source-unclaimed-delta");if(!o.every(d=>lt(t,r,e,d)))throw new Error("source-frozen-mismatch");return!i||it(t,i)}function ne(t,r){const e=vt("git",["diff","--no-index","--binary","--no-ext-diff","--","/dev/null",r],{cwd:t,env:Pt(),encoding:"buffer",timeout:3e4,maxBuffer:Z});if(e.error||e.status!==1||!Buffer.isBuffer(e.stdout)||e.stdout.byteLength===0)throw new Error("patch-invalid");return e.stdout}function Ot(t,r,e){const o=vt("git",["apply",...e?["--check"]:[],"--binary","-"],{cwd:t,env:Pt(),input:r,encoding:"buffer",timeout:3e4,maxBuffer:Z});if(o.error||o.status!==0)throw new Error("apply-failed")}function pt(t,r,e){const o=a(t,e),i=a(r,e);try{const s=R(o),n=R(i);return s.isFile()&&n.isFile()&&(s.mode&73)===(n.mode&73)&&m(o).equals(m(i))}catch(s){if(s.code!=="ENOENT")return!1;try{return R(o),!1}catch(n){if(n.code!=="ENOENT")return!1}try{return R(i),!1}catch(n){return n.code==="ENOENT"}}}function Oe(t,r,e,o){Tt(t,r,e,!0,o)}function Te(t,r,e,o){if(Tt(t,r,e,!1,o),G(t.workspacePath,["diff","--cached","--name-only"]).byteLength!==0)throw new Error("private-execution-isolated-snapshot-unverified")}function Tt(t,r,e,o,i){try{if(!bt()||t.schemaVersion!==1||!ot(t.sourceRoot)||!ot(t.workspacePath)||ht(t.sourceRoot)!==t.sourceRoot||ht(t.workspacePath)!==t.workspacePath||!R(t.workspacePath).isDirectory()||!xt(R(t.workspacePath))||dt(t.sourceRoot,t.workspacePath)===""||dt(t.sourceRoot,t.workspacePath).split(_t)[0]!==".."||!/^[a-f0-9]{40,64}$/.test(t.baseSha)||!/^[a-f0-9]{40,64}$/.test(e)||J(t.sourceRoot,["rev-parse","--show-toplevel"])!==t.sourceRoot||J(t.workspacePath,["rev-parse","--show-toplevel"])!==t.workspacePath||J(t.sourceRoot,["rev-parse","HEAD"])!==t.baseSha||J(t.workspacePath,["rev-parse","HEAD"])!==e||J(t.sourceRoot,["symbolic-ref","--short","HEAD"])!==t.executionBranch||J(t.workspacePath,["symbolic-ref","--short","HEAD"])!==t.executionBranch||nt(a(t.workspacePath,".git","objects","info","alternates"))||o&&B(t.workspacePath,!0).byteLength!==0||r.length===0||r.length>st||r.some(s=>!rt(s))||new Set(r).size!==r.length)throw new Error("boundary-invalid");if(G(t.workspacePath,["merge-base","--is-ancestor",t.baseSha,e]),!ft(t.sourceRoot,t.workspacePath,e,r,void 0,i))throw new Error("boundary-raced")}catch(s){const n=s instanceof Error&&(["boundary-invalid","boundary-raced","status-invalid","source-unclaimed-delta","source-frozen-mismatch"].includes(s.message)||/^root-memory-(scope-binding|snapshot-ancestry|snapshot-content|source-content|source-projection)(-unsafe)?$/.test(s.message))?s.message:"physical-inspection-failed";throw new Error("private-execution-isolated-snapshot-unverified",{cause:new Error(n)})}}function W(t,r,e,o,i,s=[],n){try{if(!bt()||t.schemaVersion!==1||!ot(t.sourceRoot)||!ot(t.workspacePath)||ht(t.sourceRoot)!==t.sourceRoot||ht(t.workspacePath)!==t.workspacePath||!R(t.workspacePath).isDirectory()||!xt(R(t.workspacePath))||dt(t.sourceRoot,t.workspacePath)===""||dt(t.sourceRoot,t.workspacePath).split(_t)[0]!==".."||J(t.sourceRoot,["rev-parse","--show-toplevel"])!==t.sourceRoot||J(t.workspacePath,["rev-parse","--show-toplevel"])!==t.workspacePath||J(t.sourceRoot,["rev-parse","HEAD"])!==t.baseSha||!/^[a-f0-9]{40,64}$/.test(e)||J(t.workspacePath,["rev-parse","HEAD"])!==e||J(t.sourceRoot,["symbolic-ref","--short","HEAD"])!==t.executionBranch||J(t.workspacePath,["symbolic-ref","--short","HEAD"])!==t.executionBranch||r.length===0||r.length>st||r.some(g=>!rt(g))||new Set(r).size!==r.length)throw new Error("authority-invalid");if(G(t.workspacePath,["merge-base","--is-ancestor",t.baseSha,e]),!ft(t.sourceRoot,t.workspacePath,e,r,o,n))throw new Error("source-snapshot-mismatch");const l=B(t.workspacePath,!0),p=M(l),c=new Set(r);if(p.paths.some(g=>!c.has(g)||s.includes(g)))throw new Error("path-unclaimed");if(i&&!i())throw new Error("candidate-raced");for(const g of p.paths)P(t.workspacePath,g),P(t.sourceRoot,g);const h=[G(t.workspacePath,["diff","--binary","--no-ext-diff","--no-textconv","HEAD","--"]),...p.untracked.map(g=>ne(t.workspacePath,g))],f=Buffer.concat(h.map(g=>Buffer.concat([g,Buffer.from(`
|
|
2
|
+
`)])));if(f.byteLength===0||f.byteLength>Z||!B(t.workspacePath,!0).equals(l)||i&&!i()||!ft(t.sourceRoot,t.workspacePath,e,r,o,n))throw new Error("patch-raced");if(Ot(t.sourceRoot,f,!0),!B(t.workspacePath,!0).equals(l)||i&&!i()||!ft(t.sourceRoot,t.workspacePath,e,r,o,n))throw new Error("patch-raced");Ot(t.sourceRoot,f,!1);const v=n?yt(n).files.map(g=>g.path):[];if(M(B(t.sourceRoot),!0,!!o,v,o?t.sourceRoot:void 0).paths.some(g=>!c.has(g)&&!v.includes(g)&&g!==et)||n&&!Vt(n,t.sourceRoot)||o&&!it(t.sourceRoot,o)||r.some(g=>!pt(t.workspacePath,t.sourceRoot,g))||J(t.sourceRoot,["rev-parse","HEAD"])!==t.baseSha||J(t.sourceRoot,["symbolic-ref","--short","HEAD"])!==t.executionBranch)throw new Error("admission-raced");return Object.freeze({schemaVersion:1,outcome:"admitted-unverified",baseSha:t.baseSha,executionBranch:t.executionBranch,changedPaths:Object.freeze([...p.paths]),patchSha256:F("sha256").update(f).digest("hex")})}catch{throw new Error("private-execution-isolated-admission-unverified")}}async function je(t,r,e,o=t.baseSha,i=!1,s){try{const n=await Ct(t.sourceRoot,r,t.executionBranch,e);if(s){const d=yt(s);if(d.storyId!==r||d.childClaimRevision!==F("sha256").update([...n].sort().join("\0")).digest("hex"))throw new Error("root-memory-claim-mismatch")}const l=a(t.workspacePath,".neocortex","state.json"),p=R(l);if(!p.isFile()||p.isSymbolicLink()||p.size>Z)throw new Error("candidate-state-invalid");zt(m(l,"utf8"),r,n);const c=W(t,n,o,void 0,void 0,i?[".neocortex/state.json"]:[],s);return await Lt(t.sourceRoot,r,t.executionBranch,e),c}catch{throw new Error("private-execution-isolated-admission-unverified")}}const oe=new Set(["id","epic_id","title","description","status","steps_completed","last_step","branch_name","estimated_hours","complexity","priority","type","depends_on","created_at","updated_at","acceptance_criteria"]),se=new Set(["id","title","description","status","stories","total_stories","completed_stories","estimated_hours","complexity","priority","created_at","updated_at","last_updated","source","tags"]);function jt(t){return["title","description","complexity","priority","type","created_at","updated_at","last_updated","source"].some(e=>t[e]!==void 0&&typeof t[e]!="string")||t.estimated_hours!==void 0&&(typeof t.estimated_hours!="number"||!Number.isFinite(t.estimated_hours)||t.estimated_hours<0)?!1:["depends_on","acceptance_criteria","tags"].every(e=>t[e]===void 0||Array.isArray(t[e])&&t[e].length<=256&&t[e].every(o=>typeof o=="string"))}function ie(t){return Object.keys(t).every(r=>oe.has(r))&&t.status==="backlog"&&jt(t)&&(t.steps_completed===void 0||Array.isArray(t.steps_completed)&&t.steps_completed.length===0)&&(t.last_step===void 0||t.last_step===null)&&(t.branch_name===void 0||t.branch_name===null)}function Ne(t,r,e,o,i){try{if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(r)||!/^P[1-9][0-9]*$/.test(e)||!/^[a-f0-9]{64}$/.test(o)||!/^[a-f0-9]{64}$/.test(i)||!it(t.sourceRoot,i))throw new Error("claim-invalid");const s=JSON.parse(m(a(t.sourceRoot,et),"utf8")),n=s&&typeof s=="object"&&!Array.isArray(s)?s.operations?.[o]:void 0;if(!n||typeof n!="object"||Array.isArray(n)||n.claimId!==r||n.epicId!==e)throw new Error("claim-sidecar-mismatch");const l=M(B(t.workspacePath,!0)),p=`docs/epics/epic-${e}.md`,c=".neocortex/state.json",d=new RegExp(`^docs/stories/${e}\\.[0-9]{2}\\.story\\.md$`),h=l.paths.filter(E=>d.test(E));if(!l.paths.includes(p)||!l.paths.includes(c)||h.length===0||h.length>99||l.paths.some(E=>E!==p&&E!==c&&E!=="NEOCORTEX.md"&&!d.test(E)))throw new Error("artifact-scope-invalid");const f=h.map(E=>E.slice(13,-9)).sort();if(f.some((E,T)=>E!==`${e}.${String(T+1).padStart(2,"0")}`))throw new Error("story-sequence-invalid");for(const E of[p,...h])try{throw R(a(t.sourceRoot,E)),new Error("artifact-already-exists")}catch(T){if(T.code!=="ENOENT")throw T}const v=(E,T)=>{P(t.workspacePath,E);const K=m(a(t.workspacePath,E),"utf8");return Buffer.byteLength(K)>Z?null:/^---\r?\n([\s\S]{1,8192}?)\r?\n---(?:\r?\n|$)/.exec(K)?.[1]?.split(/\r?\n/).find(ct=>ct.startsWith(`${T}:`))?.slice(T.length+1).trim()?.replace(/^(["'])(.*)\1$/,"$2")??null};if(v(p,"id")!==e||h.some((E,T)=>v(E,"id")!==f[T]||v(E,"epic_id")!==e))throw new Error("artifact-id-invalid");P(t.workspacePath,c);const u=JSON.parse(m(a(t.workspacePath,c),"utf8"));if(!u||typeof u!="object"||Array.isArray(u))throw new Error("state-invalid");const g=u,_=g.epics,N=g.stories,b=_?.[e],j=g.epic_id_ledger;if(g.schema_version!==1||!b||b.id!==e||b.status!=="memory-updated"||Object.keys(b).some(E=>!se.has(E))||!jt(b)||b.completed_stories!==void 0&&b.completed_stories!==0||b.total_stories!==void 0&&b.total_stories!==f.length||!Array.isArray(b.stories)||b.stories.length!==f.length||b.stories.some((E,T)=>E!==f[T])||!N||f.some(E=>{const T=N[E];return!T||T.id!==E||T.epic_id!==e||!ie(T)})||!j||!Array.isArray(j.reserved_ids)||!j.reserved_ids.includes(e))throw new Error("state-claim-mismatch");P(t.sourceRoot,c);const y=JSON.parse(m(a(t.sourceRoot,c),"utf8")),A=y.epics,x=y.stories;if(!A||!x||A[e]!==void 0||f.some(E=>x[E]!==void 0))throw new Error("state-claim-conflict");const{[e]:Y,...L}=_,$={...N};for(const E of f)delete $[E];const{epic_id_ledger:q,last_updated:C,...z}=y,{epic_id_ledger:V,last_updated:X,...Q}=g;if(!S(L,A)||!S($,x)||!S({...Q,epics:void 0,stories:void 0},{...z,epics:void 0,stories:void 0}))throw new Error("state-unrelated-drift");const O=y.epic_id_ledger&&typeof y.epic_id_ledger=="object"?y.epic_id_ledger.reserved_ids:void 0,{reserved_ids:U,...w}=j,D=y.epic_id_ledger&&typeof y.epic_id_ledger=="object"?y.epic_id_ledger:{schema_version:1},{reserved_ids:H,...k}=D;if(O!==void 0&&(!Array.isArray(O)||O.some(E=>typeof E!="string"||!/^P[1-9][0-9]*$/.test(E))||new Set(O).size!==O.length))throw new Error("ledger-drift");const tt=[...Array.isArray(O)?O:[]];if(tt.includes(e)||tt.push(e),!S(j.reserved_ids,tt)||!S(w,k))throw new Error("ledger-drift");return W(t,l.paths,t.baseSha,i)}catch{throw new Error("private-execution-epic-claim-admission-unverified")}}function De(t,r,e,o,i,s){try{if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(r)||!/^P[1-9][0-9]{0,11}$/.test(e)||!/^[a-f0-9]{64}$/.test(o)||!/^[a-f0-9]{64}$/.test(i)||typeof s!="string"||!s.trim()||s.length>16384||!it(t.sourceRoot,i))throw new Error("planning-claim-invalid");const n=JSON.parse(m(a(t.sourceRoot,et),"utf8")),l=n&&typeof n=="object"&&!Array.isArray(n)?n.operations?.[o]:void 0;if(!l||typeof l!="object"||Array.isArray(l)||l.claimId!==r||l.epicId!==e)throw new Error("planning-claim-sidecar-mismatch");const p=`.neocortex/planning/epic-${e}`,c=`${p}/idea.json`,d=`${p}/diagnosis.md`,h=`${p}/enriched-prompt.md`,f=".neocortex/planning/planning.json",v=[c,d,h,f],u=M(B(t.workspacePath,!0));if(u.paths.length!==v.length||u.paths.some(E=>!v.includes(E)))throw new Error("planning-artifact-scope-invalid");for(const E of[c,d,h]){P(t.workspacePath,E);try{throw R(a(t.sourceRoot,E)),new Error("planning-artifact-already-exists")}catch(T){if(T.code!=="ENOENT")throw T}}const g=(E,T)=>{const K=R(a(t.workspacePath,E));if(!K.isFile()||K.isSymbolicLink()||K.size<1||K.size>T)throw new Error("planning-artifact-invalid");return m(a(t.workspacePath,E),"utf8")},_=JSON.parse(g(c,32*1024));if(!_||typeof _!="object"||Array.isArray(_)||_.epic_id!==e||_.status!=="diagnosed"||typeof _.raw_input!="string"||_.raw_input!==s)throw new Error("planning-idea-invalid");const N=g(d,256*1024),b=g(h,256*1024),j=(E,T)=>{const K=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(E.replace(/\r\n/g,`
|
|
3
|
+
`))?.[1];if(!K)return!1;const wt=K.split(`
|
|
4
|
+
`),at=gt=>{const ct=wt.filter(Dt=>Dt.startsWith(`${gt}:`));return ct.length===1?ct[0].slice(gt.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0};return at("epic_id")===e&&I(at("step"),T)&&at("status")==="completed"};if(!j(N,ut)||!j(b,ee))throw new Error("planning-document-identity-invalid");P(t.workspacePath,f),P(t.sourceRoot,f);const y=JSON.parse(g(f,128*1024)),A=nt(a(t.sourceRoot,f))?JSON.parse(m(a(t.sourceRoot,f),"utf8")):void 0;if(!y||typeof y!="object"||Array.isArray(y)||!("epics"in y)||!y.epics||typeof y.epics!="object"||Array.isArray(y.epics)||A!==void 0&&(!A||typeof A!="object"||Array.isArray(A)||!("epics"in A)||!A.epics||typeof A.epics!="object"||Array.isArray(A.epics)))throw new Error("planning-index-invalid");const x=y,Y=x.epics,L=Y[e],$=L,q=$?.output_files;if(!L||typeof L!="object"||Array.isArray(L)||$?.id!==e||$.status!=="diagnosed"||$.idea!==_.raw_input||!Array.isArray($.steps_completed)||$.steps_completed.length!==1||!I($.steps_completed[0],ut)||typeof $.created_at!="string"||!Number.isFinite(Date.parse($.created_at))||$.completed_at!==null||!q||typeof q!="object"||Array.isArray(q)||!S(q,{diagnosis:`${p}/diagnosis.md`})||!S(Object.keys($).sort(),["id","idea","status","steps_completed","created_at","completed_at","output_files"].sort()))throw new Error("planning-index-epic-invalid");const{last_scan:C,epics:z,...V}=x,X=A,Q=X?.epics,{last_scan:O,epics:U,...w}=X??{},{[e]:D,...H}=Y;if(Q?.[e]!==void 0||!S(H,Q??{})||X!==void 0&&!S(V,w)||X===void 0&&(Object.keys(Y).length!==1||!S(Object.keys(x).sort(),["version","next_epic_id","last_scan","existing_epics_discovered","epics"].sort())||x.version!=="1.0.0"||x.next_epic_id!==1||!S(x.existing_epics_discovered,[]))||typeof x.last_scan!="string"||!Number.isFinite(Date.parse(x.last_scan)))throw new Error("planning-index-drift");const k=v.map(E=>F("sha256").update(m(a(t.workspacePath,E))).digest("hex")),tt=()=>v.every((E,T)=>{try{return P(t.workspacePath,E),F("sha256").update(m(a(t.workspacePath,E))).digest("hex")===k[T]}catch{return!1}});return W(t,v,t.baseSha,i,tt)}catch{throw new Error("private-execution-planning-diagnosis-admission-unverified")}}function Fe(t,r,e,o,i,s){try{if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(r)||!/^P[1-9][0-9]{0,11}$/.test(e)||!/^[a-f0-9]{64}$/.test(o)||!/^[a-f0-9]{64}$/.test(i)||!/^[a-f0-9]{64}$/.test(s))throw new Error("planning-research-binding-invalid");const n=".neocortex/state.json",l=".neocortex/planning/planning.json",p=`.neocortex/planning/epic-${e}`,c=`${p}/research.md`;if(P(t.sourceRoot,n),P(t.workspacePath,n),P(t.sourceRoot,l),P(t.workspacePath,l),P(t.sourceRoot,c),P(t.workspacePath,c),R(a(t.sourceRoot,n)).size>8*1024*1024||R(a(t.workspacePath,n)).size>8*1024*1024||R(a(t.sourceRoot,l)).size>128*1024||R(a(t.workspacePath,l)).size>128*1024)throw new Error("planning-research-source-size-invalid");const d=m(a(t.sourceRoot,n));if(F("sha256").update(d).digest("hex")!==s||!d.equals(m(a(t.workspacePath,n))))throw new Error("planning-research-state-drift");const h=JSON.parse(d.toString("utf8")),f=Qt(h,r,e);if(f.diagnosisReceiptId!==o||f.intakeRevision!==i)throw new Error("planning-research-predecessor-mismatch");const u=h.epics[e].createEpicPlanningPhysical.artifactDigests;for(const[O,U]of Object.entries({idea:`${p}/idea.json`,diagnosis:`${p}/diagnosis.md`,enrichment:`${p}/enriched-prompt.md`,index:l}))if(P(t.sourceRoot,U),F("sha256").update(m(a(t.sourceRoot,U))).digest("hex")!==u[O])throw new Error("planning-research-source-artifact-drift");try{throw R(a(t.sourceRoot,c)),new Error("planning-research-already-exists")}catch(O){if(O.code!=="ENOENT")throw O}const g=[c,l],_=M(B(t.workspacePath,!0));if(_.paths.length!==g.length||_.paths.some(O=>!g.includes(O)))throw new Error("planning-research-write-scope-invalid");const N=R(a(t.workspacePath,c));if(!N.isFile()||N.isSymbolicLink()||N.size<64||N.size>256*1024)throw new Error("planning-research-document-invalid");const b=m(a(t.workspacePath,c),"utf8"),j=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(b.replace(/\r\n/g,`
|
|
5
|
+
`))?.[1],y=O=>{const U=j?.split(`
|
|
6
|
+
`).filter(w=>w.startsWith(`${O}:`))??[];return U.length===1?U[0].slice(O.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0};if(j&&y("epic_id")===e&&I(y("step"),Et)&&y("status")==="incomplete")throw new Error("planning-research-incomplete");if(!j||y("epic_id")!==e||y("status")!=="completed"||!I(y("step"),Et)||!b.slice(j.length+8).trim())throw new Error("planning-research-document-identity-invalid");const A=JSON.parse(m(a(t.sourceRoot,l),"utf8")),x=JSON.parse(m(a(t.workspacePath,l),"utf8"));if(!A||typeof A!="object"||Array.isArray(A)||!x||typeof x!="object"||Array.isArray(x))throw new Error("planning-research-index-invalid");const Y=A,L=x,$=Y.epics,q=L.epics,C=$?.[e];if(!$||Array.isArray($)||!q||Array.isArray(q)||!C||Array.isArray(C)||C.id!==e||C.idea!==f.rawIntent||C.status!=="diagnosed"||!Array.isArray(C.steps_completed)||C.steps_completed.length!==1||!I(C.steps_completed[0],ut)||!S(C.output_files,{diagnosis:`${p}/diagnosis.md`})||typeof L.last_scan!="string"||!Number.isFinite(Date.parse(L.last_scan)))throw new Error("planning-research-index-predecessor-invalid");const z={...C,status:"researched",steps_completed:[...C.steps_completed,y("step")],output_files:{diagnosis:`${p}/diagnosis.md`,research:c}},V={...Y,last_scan:L.last_scan,epics:{...$,[e]:z}};if(!S(L,V))throw new Error("planning-research-index-drift");const X=g.map(O=>F("sha256").update(m(a(t.workspacePath,O))).digest("hex")),Q=()=>g.every((O,U)=>{try{return P(t.workspacePath,O),F("sha256").update(m(a(t.workspacePath,O))).digest("hex")===X[U]}catch{return!1}});return W(t,g,t.baseSha,At(t.sourceRoot),Q)}catch(n){throw new Bt(n)}}function Be(t,r,e,o,i,s,n){try{if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(r)||!/^P[1-9][0-9]{0,11}$/.test(e)||[o,i,s,n].some(w=>!/^[a-f0-9]{64}$/.test(w)))throw new Error("planning-generation-binding-invalid");const l=".neocortex/state.json",p=".neocortex/planning/planning.json",c=`.neocortex/planning/epic-${e}`,d=`docs/epics/epic-${e}.md`;for(const w of[l,p,`${c}/idea.json`,`${c}/diagnosis.md`,`${c}/enriched-prompt.md`,`${c}/research.md`]){P(t.sourceRoot,w),P(t.workspacePath,w);const D=m(a(t.sourceRoot,w));if(w!==p&&!D.equals(m(a(t.workspacePath,w)))||!D.equals(G(t.sourceRoot,["show",`HEAD:${w}`])))throw new Error("planning-generation-predecessor-uncommitted")}const h=m(a(t.sourceRoot,l));if(h.byteLength>8*1024*1024||F("sha256").update(h).digest("hex")!==n)throw new Error("planning-generation-state-drift");const f=JSON.parse(h.toString("utf8")),v=kt(f,r,e);if(v.diagnosisReceiptId!==o||v.researchReceiptId!==i||v.intakeRevision!==s)throw new Error("planning-generation-predecessor-mismatch");const u=f.epics[e],g=u.createEpicPlanningPhysical.artifactDigests,_=u.createEpicPlanningResearchPhysical.artifactDigests,N={idea:`${c}/idea.json`,diagnosis:`${c}/diagnosis.md`,enrichment:`${c}/enriched-prompt.md`,research:`${c}/research.md`};for(const[w,D]of Object.entries(N)){const H=w==="research"?_.research:g[w];if(F("sha256").update(m(a(t.sourceRoot,D))).digest("hex")!==H)throw new Error("planning-generation-artifact-drift")}if(F("sha256").update(m(a(t.sourceRoot,p))).digest("hex")!==_.index)throw new Error("planning-generation-index-drift");const b=M(B(t.workspacePath,!0)),j=new RegExp(`^docs/stories/${e}\\.([0-9]{2})\\.story\\.md$`),y=b.paths.filter(w=>j.test(w)).sort((w,D)=>Number(j.exec(w)[1])-Number(j.exec(D)[1]));if(y.length<1||y.length>24||y.some((w,D)=>j.exec(w)[1]!==String(D+1).padStart(2,"0"))||b.paths.length!==y.length+2||b.paths.some(w=>w!==d&&w!==p&&!j.test(w)))throw new Error("planning-generation-write-scope-invalid");const A=[d,p,...y];for(const w of[d,...y]){P(t.sourceRoot,w),P(t.workspacePath,w);try{throw R(a(t.sourceRoot,w)),new Error("planning-generation-path-collision")}catch(H){if(H.code!=="ENOENT")throw H}const D=R(a(t.workspacePath,w));if(!D.isFile()||D.isSymbolicLink()||D.size<128||D.size>(w===d?512:128)*1024)throw new Error("planning-generation-document-invalid")}const x=(w,D)=>{const k=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(w.replace(/\r\n/g,`
|
|
7
7
|
`))?.[1]?.split(`
|
|
8
|
-
`).filter(
|
|
9
|
-
`))?.[1]??"";if(x(H,"id")!==`${e}.${String(
|
|
8
|
+
`).filter(tt=>tt.startsWith(`${D}:`))??[];return k.length===1?k[0].slice(D.length+1).trim().replace(/^(?:"(.*)"|'(.*)')$/,"$1$2"):void 0},Y=m(a(t.workspacePath,d),"utf8");if(x(Y,"id")!==e||x(Y,"stories_count")!==String(y.length)||!Y.includes("## Stories"))throw new Error("planning-generation-epic-invalid");for(const[w,D]of y.entries()){const H=m(a(t.workspacePath,D),"utf8"),k=/^---\n([\s\S]{1,8192}?)\n---\n/.exec(H.replace(/\r\n/g,`
|
|
9
|
+
`))?.[1]??"";if(x(H,"id")!==`${e}.${String(w+1).padStart(2,"0")}`||x(H,"epic_id")!==e||/^\s*epic\s*:/m.test(k)||x(H,"status")!=="backlog"||!H.includes("## Acceptance Criteria")||!/\bGiven\b[\s\S]*\bWhen\b[\s\S]*\bThen\b/.test(H))throw new Error("planning-generation-story-invalid")}const L=JSON.parse(m(a(t.sourceRoot,p),"utf8")),$=JSON.parse(m(a(t.workspacePath,p),"utf8")),q=L.epics,C=$.epics,z=q?.[e],V=C?.[e];if(!q||!C||!z||!V||z.id!==e||z.status!=="researched"||!Array.isArray(z.steps_completed)||z.steps_completed.length!==2||!I(z.steps_completed[0],ut)||!I(z.steps_completed[1],Et)||!S(z.output_files,{diagnosis:`${c}/diagnosis.md`,research:`${c}/research.md`})||typeof $.last_scan!="string"||!Number.isFinite(Date.parse($.last_scan))||typeof V.completed_at!="string"||!Number.isFinite(Date.parse(V.completed_at)))throw new Error("planning-generation-index-predecessor-invalid");const X=V.steps_completed?.[2];if(!I(X,re))throw new Error("planning-generation-index-transition-invalid");const Q={...L,last_scan:$.last_scan,epics:{...q,[e]:{...z,status:"generated",steps_completed:[...z.steps_completed,X],completed_at:V.completed_at,output_files:{...z.output_files,epic:d,stories:y}}}};if(!S($,Q))throw new Error("planning-generation-index-transition-invalid");const O=A.map(w=>F("sha256").update(m(a(t.workspacePath,w))).digest("hex")),U=()=>A.every((w,D)=>{try{return P(t.workspacePath,w),F("sha256").update(m(a(t.workspacePath,w))).digest("hex")===O[D]}catch{return!1}});return W(t,A,t.baseSha,At(t.sourceRoot),U)}catch{throw new Error("private-execution-planning-generation-admission-unverified")}}function Ce(t,r,e){try{if(!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e))throw new Error("story-id-invalid");const o=".neocortex/state.json";P(r.sourceRoot,o),P(r.workspacePath,o);const i=m(a(r.sourceRoot,o));if(!i.equals(m(a(r.workspacePath,o))))throw new Error("state-drift");const s=JSON.parse(i.toString("utf8")),n=s?.stories?.[e],l=n?.files_to_modify;if(s?.schema_version!==1||n?.id!==e||!Array.isArray(l)||l.length<1||l.length>st||l.some(d=>typeof d!="string"||!rt(d)||d.length>1024||/[\r\n]/.test(d))||new Set(l).size!==l.length)throw new Error("write-set-invalid");const p=l,c=p.filter(d=>{if(!d.startsWith("docs/stories/")||!d.endsWith(".story.md"))return!1;P(r.sourceRoot,d),P(r.workspacePath,d);const h=m(a(r.sourceRoot,d));if(!h.equals(m(a(r.workspacePath,d))))throw new Error("story-drift");const v=/^---\r?\n([\s\S]{1,8192}?)\r?\n---(?:\r?\n|$)/.exec(h.toString("utf8"))?.[1]?.split(/\r?\n/).filter(u=>u.startsWith("id:"))??[];return v.length===1&&v[0].slice(3).trim().replace(/^(["'])(.*)\1$/,"$2")===e});if(c.length!==1)throw new Error("story-target-ambiguous");return`${t}
|
|
10
10
|
|
|
11
11
|
Private story handoff (local only):
|
|
12
12
|
${JSON.stringify({storyId:e,storyPath:c[0],allowedPaths:[...p].sort()})}
|
|
13
13
|
Work from this isolated checkout's current directory. Use the exact storyPath above for the delivered current step; do not use an unresolved story-file placeholder or infer a filename. Persist the current step's actual result in the declared files; a final chat response alone is not a saved candidate. Modify only allowedPaths and preserve story identity and the write set. Do not operate Git, change unrelated stories, grant root QA/checkpoint authority, or declare the story, epic or pipeline complete. If required inputs are unavailable, report failure without inventing evidence or completion.
|
|
14
|
-
`}catch{throw new Error("private-execution-state-step-handoff-unverified")}}function
|
|
14
|
+
`}catch{throw new Error("private-execution-state-step-handoff-unverified")}}function ze(t,r){try{if(!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(r))throw new Error("story-id-invalid");const e=".neocortex/state.json";P(t.sourceRoot,e),P(t.workspacePath,e);const o=JSON.parse(m(a(t.sourceRoot,e),"utf8")),i=JSON.parse(m(a(t.workspacePath,e),"utf8"));if(!o||typeof o!="object"||Array.isArray(o)||!i||typeof i!="object"||Array.isArray(i))throw new Error("state-invalid");const s=o,n=i,l=s.stories,p=n.stories,c=l?.[r],d=p?.[r],h=c?.files_to_modify;if(s.schema_version!==1||n.schema_version!==1||!l||!p||!c||!d||c.id!==r||d.id!==r||d.epic_id!==c.epic_id||!Array.isArray(h)||h.length===0||h.length>st||h.some(x=>typeof x!="string"||!rt(x)||x.length>1024)||new Set(h).size!==h.length||!S(d.files_to_modify,h))throw new Error("write-set-invalid");const{[r]:f,...v}=l,{[r]:u,...g}=p,{stories:_,last_updated:N,...b}=s,{stories:j,last_updated:y,...A}=n;if(!S(g,v)||!S(A,b))throw new Error("state-unrelated-drift");return W(t,[...h].sort(),t.baseSha)}catch{throw new Error("private-execution-state-step-admission-unverified")}}function Le(t,r,e){if(r==="chaos-plan"&&e==="chaos-quarterly-v1")try{const i=new Date,s=`Q${Math.floor(i.getUTCMonth()/3)+1}-${i.getUTCFullYear()}`,n=M(B(t.workspacePath,!0)).paths,l=`tools/chaos/${s}-plan.md`,p=`.neocortex/chaos-history/${s}.md`,c=n.filter(u=>u.startsWith("tools/chaos/experiments/")),d=c.map(u=>/^tools\/chaos\/experiments\/(chaos-mesh|litmus|aws-fis)-(?:PodKill|NetworkChaos|IOChaos|StressChaos|TimeChaos|pod-kill|network-chaos|io-chaos|stress-chaos|time-chaos)-([a-z0-9]+(?:-[a-z0-9]+)*)\.yaml$/.exec(u));if(!n.includes(l)||!n.includes(p)||c.length<5||c.length>10||n.length!==c.length+2||d.some(u=>!u)||new Set(d.map(u=>u[1])).size!==1)throw new Error("chaos-write-set-invalid");for(const u of n)if(P(t.workspacePath,u),R(a(t.workspacePath,u)).size===0)throw new Error("chaos-empty-artifact");const h=m(a(t.workspacePath,p),"utf8");if(!h.includes(s)||!/\bPLANNED\b/.test(h))throw new Error("chaos-history-invalid");const v=G(t.workspacePath,["ls-tree","-z","HEAD","--",p]).length>0?G(t.workspacePath,["show",`HEAD:${p}`]).toString("utf8"):"";if(v&&!h.startsWith(v))throw new Error("chaos-history-not-append-only");return W(t,n,t.baseSha)}catch{throw new Error("private-execution-project-step-admission-unverified")}const o=r==="sync-openapi"&&e==="sync-openapi-contract-v1"?["docs/architecture/api-contracts.md","docs/api/openapi.yaml"]:r==="tech-debt"&&e==="tech-debt-registry-v1"?[".neocortex/tech-debt-registry.json"]:void 0;if(!o)throw new Error("private-execution-project-step-admission-unverified");try{if(r==="tech-debt"){const i=".neocortex/tech-debt-registry.json";P(t.workspacePath,i);const s=JSON.parse(m(a(t.workspacePath,i),"utf8"));if(!s||typeof s!="object"||Array.isArray(s))throw new Error("registry-invalid");const n=s;if(n.schema_version!==2||n.version!==void 0&&n.version!==2||!Array.isArray(n.items))throw new Error("registry-invalid")}return W(t,o,t.baseSha)}catch{throw new Error("private-execution-project-step-admission-unverified")}}function Nt(t,r){const e=t==="arch-prd"&&r==="arch-prd-docs-v1"?["docs/architecture/prd.md","docs/architecture/product-experience.md"]:t==="arch-architecture"&&r==="arch-architecture-doc-v1"?["docs/architecture/architecture.md"]:t==="arch-fitness-functions"&&r==="arch-fitness-tools-v1"?["tools/architecture/dependency-cruiser.config.js","tools/architecture/archunit-test.ts","tools/architecture/.eslintrc.boundaries.js"]:t==="arch-api-contracts"&&r==="arch-api-contracts-docs-v1"?["docs/architecture/api-contracts.md","docs/api/openapi.yaml"]:t==="arch-api-integrations"&&r==="arch-api-integrations-doc-v1"?["docs/architecture/api-integrations.md"]:t==="arch-database"&&r==="arch-database-doc-v1"?["docs/architecture/database-schema.md"]:t==="arch-security"&&r==="arch-security-doc-v1"?["docs/architecture/cyber-security.md"]:t==="arch-design-system"&&r==="arch-design-system-doc-v1"?["docs/architecture/atomic-design-system.md"]:t==="arch-performance"&&r==="arch-performance-doc-v1"?["docs/architecture/performance-strategy.md"]:t==="arch-testing"&&r==="arch-testing-doc-v1"?["docs/architecture/testing-strategy.md"]:t==="arch-infrastructure"&&r==="arch-infrastructure-doc-v1"?["docs/architecture/infrastructure-deploy.md"]:t==="arch-review"&&r==="arch-review-doc-v1"?["docs/architecture/review-consolidation.md"]:t==="update-memory"&&r==="arch-memory-canonical-v1"?["NEOCORTEX.md"]:null;return e===null?null:Object.freeze(e)}function He(t,r,e,o="all"){const i=Nt(r,e);if(!i)throw new Error("private-execution-architecture-admission-unverified");return`${t}
|
|
15
15
|
|
|
16
16
|
Private architecture handoff (local only):
|
|
17
17
|
${JSON.stringify({allowedPaths:i})}
|
|
18
18
|
${o==="non-ui"?`The server admitted a signed non-UI scope for this snapshot. Preserve the backend-only scope: design-system and UX phases are not applicable. Do not require or generate interface artifacts.
|
|
19
19
|
`:""}Write exactly the listed nonempty artifacts inside this isolated clone. Existing compliant listed artifacts may remain unchanged; all listed artifacts must exist after execution. Place any necessary scope notes inside those artifacts. Do not edit README, package files, other documents, state, Git, QA records or configuration outside the listed paths. Do not install dependencies, use network, deploy or continue to another stage. Preserve existing arch:keep blocks byte-for-byte. Do not add new arch:keep markers. For managed memory, preserve all bytes outside its existing managed block. Root independently reviews artifacts and owns continuation, Git and acceptance.
|
|
20
|
-
`}function
|
|
21
|
-
`).length>240)throw new Error("memory-managed-block-invalid");const
|
|
20
|
+
`}function Je(t,r,e,o,i){const s=Nt(r,e);if(!s||!/^P[1-9][0-9]{0,11}$/.test(o)||!/^[a-f0-9]{64}$/.test(i))throw new Error("private-execution-architecture-admission-unverified");try{P(t.workspacePath,".neocortex/state.json");const n=JSON.parse(m(a(t.workspacePath,".neocortex/state.json"),"utf8"));if(!n||typeof n!="object"||Array.isArray(n))throw new Error("state-invalid");const l=n,c=l.archPlan?.execution,d=l.epics;if(!c||c.currentStageCommand!==r||c.targetEpicId!==o||c.graphRevision!==i||!d||!Object.hasOwn(d,o))throw new Error("state-binding-mismatch");if(r==="update-memory"){if(c.continuationState!=="delegate"||c.reviewDecision?.decision!=="approved")throw new Error("memory-root-review-missing");const h="NEOCORTEX.md";if(!M(B(t.workspacePath,!0)).paths.includes(h))throw new Error("memory-effect-missing");P(t.sourceRoot,h),P(t.workspacePath,h);const f=m(a(t.sourceRoot,h),"utf8"),v=m(a(t.workspacePath,h),"utf8"),u="<!-- NEOCORTEX-MEMORY-START -->",g="<!-- NEOCORTEX-MEMORY-END -->",_=y=>{if(y.split(u).length!==2||y.split(g).length!==2||y.indexOf(u)>=y.indexOf(g))throw new Error("memory-markers-invalid");const A=y.indexOf(u)+u.length,x=y.indexOf(g);return{before:y.slice(0,A),body:y.slice(A,x),after:y.slice(x)}},N=_(f),b=_(v);if(N.before!==b.before||N.after!==b.after||N.body===b.body||Buffer.byteLength(v,"utf8")>32768||v.split(`
|
|
21
|
+
`).length>240)throw new Error("memory-managed-block-invalid");const j=new Set(N.body.split(`
|
|
22
22
|
`));for(const y of b.body.split(`
|
|
23
|
-
`))
|
|
23
|
+
`))j.has(y)||Yt(y)}if(r==="arch-prd"){const h="docs/architecture/prd.md";if(!M(B(t.workspacePath,!0)).paths.includes(h))throw new Error("prd-effect-missing");if(P(t.workspacePath,h),R(a(t.workspacePath,h)).size===0)throw new Error("prd-empty")}if(r==="arch-api-contracts"||r==="arch-fitness-functions"||r==="arch-api-integrations"||r==="arch-database"||r==="arch-security"||r==="arch-design-system"||r==="arch-performance"||r==="arch-testing"||r==="arch-infrastructure"||r==="arch-review"){const h=M(B(t.workspacePath,!0)).paths;for(const f of s){if(!h.includes(f)&&G(t.workspacePath,["cat-file","-t",`${t.baseSha}:${f}`]).toString("utf8").trim()!=="blob")throw new Error("architecture-required-effect-missing");if(P(t.workspacePath,f),R(a(t.workspacePath,f)).size===0)throw new Error("architecture-required-effect-empty");if(r==="arch-fitness-functions"){P(t.sourceRoot,f);const v=nt(a(t.sourceRoot,f))?m(a(t.sourceRoot,f),"utf8"):"",u=m(a(t.workspacePath,f),"utf8"),g=$t(v),_=$t(u);if(!S(_,g))throw new Error("architecture-keep-marker-changed")}}}return W(t,s,t.baseSha)}catch{throw new Error("private-execution-architecture-admission-unverified")}}function Me(t,r,e,o){try{if(!/^P[1-9][0-9]{0,11}$/.test(r)||!/^[a-f0-9]{64}$/.test(e)||o.schemaVersion!==1||o.targetEpicId!==r)throw new Error("binding-invalid");const i=qt(t.sourceRoot,r),s=Mt(t.workspacePath,r);if(!S(i,o)||!S(s,o))throw new Error("write-set-invalid");P(t.workspacePath,".neocortex/state.json");const n=JSON.parse(m(a(t.workspacePath,".neocortex/state.json"),"utf8"));if(!n||typeof n!="object"||Array.isArray(n))throw new Error("state-invalid");const l=n,c=l.archPlan?.execution,d=l.epics;if(!c||c.currentStageCommand!=="arch-ux-design"||c.continuationState!=="delegate"||c.targetEpicId!==r||c.graphRevision!==e||!d||!Object.hasOwn(d,r))throw new Error("stage-invalid");const h=M(B(t.workspacePath,!0)).paths;if(h.length!==o.pathCount||h.some(f=>!o.paths.includes(f)))throw new Error("agent-path-unclaimed");for(const f of o.paths){P(t.sourceRoot,f),P(t.workspacePath,f);const v=R(a(t.workspacePath,f));if(!v.isFile()||v.isSymbolicLink()||v.size<1)throw new Error("effect-empty");const u=new TextDecoder("utf-8",{fatal:!0}).decode(m(a(t.workspacePath,f)));if(!u.trim()||u.includes("\0"))throw new Error("effect-invalid")}return Gt(t.workspacePath,o),W(t,o.paths,t.baseSha)}catch{throw new Error("private-execution-ux-admission-unverified")}}function qe(t,r,e,o,i,s){try{if(!/^P[1-9][0-9]{0,11}$/.test(r)||!/^[a-f0-9]{64}$/.test(e)||o.targetEpicId!==r||o.graphRevision!==e||i.schemaVersion!==1)throw new Error("binding-invalid");const n=Jt(t.sourceRoot);if(!n||!S(n.receipt,o))throw new Error("answers-invalid");const l=Rt(t.sourceRoot,n.answers.generateProvider),p=Rt(t.workspacePath,n.answers.generateProvider);if(l.outcome!=="ready"||p.outcome!=="ready"||!S(l.writeSet,i)||!S(p.writeSet,i))throw new Error("write-set-invalid");const c=M(B(t.workspacePath,!0)).paths;if(c.some(u=>!i.paths.includes(u)))throw new Error("agent-path-unclaimed");let d=0,h=0;for(const u of i.paths){if(P(t.sourceRoot,u),nt(a(t.sourceRoot,u))||!c.includes(u))throw new Error("effect-missing-or-overwrite");P(t.workspacePath,u);const g=R(a(t.workspacePath,u));if(!g.isFile()||g.size<1)throw new Error("effect-empty");const _=new TextDecoder("utf-8",{fatal:!0}).decode(m(a(t.workspacePath,u))),N=i.interactions.find(j=>j.filePath===u);if(u!==i.providerPath&&!N)throw new Error("private-execution-pact-interaction-missing");const b=Wt(u,_,n.answers.brokerUrl,N,t.workspacePath,n.answers.matchersAggressive);b.consumerBinding==="app-import-candidate"&&d++,b.consumerBinding==="mock-only-scaffold"&&h++}let f=i.paths;if(s){const u=Zt(t.sourceRoot,n.answers.generateProvider),g=_=>F("sha256").update(_).digest("hex");if(s.schemaVersion!==1||s.outcome!=="candidate-unverified"||s.executionVerified!==!1||s.sourceManifestSha256!==g(u.sourceText)||s.sourceLockSha256!==(u.sourceLockText===null?null:g(u.sourceLockText))||s.manifestText!==u.candidateText||!lt(t.sourceRoot,t.workspacePath,t.baseSha,"package.json")||!lt(t.sourceRoot,t.workspacePath,t.baseSha,"package-lock.json"))throw new Error("toolchain-binding-invalid");for(const _ of["package.json","package-lock.json"]){P(t.sourceRoot,_),P(t.workspacePath,_);const N=_==="package.json"?u.sourceText:u.sourceLockText,b=nt(a(t.workspacePath,_))?m(a(t.workspacePath,_),"utf8"):null;if(N!==b)throw new Error("toolchain-clone-raced")}if(mt(a(t.workspacePath,"package.json"),s.manifestText),mt(a(t.workspacePath,"package-lock.json"),s.lockText),Kt(t.workspacePath,n.answers.generateProvider).outcome!=="manifest-aligned")throw new Error("toolchain-candidate-invalid");f=[...i.paths,"package.json","package-lock.json"]}const v=W(t,f,t.baseSha);return Object.freeze({...v,consumerBindingCandidateCount:d,consumerScaffoldCount:h})}catch{throw new Error("private-execution-pact-admission-unverified")}}function Ge(t,r,e,o=new Date().toISOString()){try{const i=St(t.sourceRoot,r);if(!S(i,e)||!pt(t.sourceRoot,t.workspacePath,e.prdPath)||e.aggregates.some(h=>!pt(t.sourceRoot,t.workspacePath,h.implementationFile))||e.writeSet.length===0)throw new Error("plan-drift");const s=M(B(t.workspacePath,!0)).paths;if(!S(s,e.writeSet))throw new Error("agent-path-unclaimed");const n=new Map;for(const h of e.aggregates){P(t.sourceRoot,h.testFile),P(t.workspacePath,h.testFile);const f=R(a(t.workspacePath,h.testFile));if(!f.isFile()||f.isSymbolicLink()||f.size<1||f.size>Z)throw new Error("test-invalid");const v=m(a(t.workspacePath,h.testFile)),u=new TextDecoder("utf-8",{fatal:!0}).decode(v),g=e.language==="typescript"?(u.match(/\b(?:it|test)\s*\(/g)??[]).length:(u.match(/^def\s+test_[A-Za-z0-9_]+\s*\(/gm)??[]).length;if(!u.trim()||u.includes("\0")||g<h.invariantCount||/\b(?:it|test|describe)\s*\.\s*(?:skip|todo|only)\s*\(/.test(u)||!u.includes(String(e.numRuns)))throw new Error("test-invalid");e.language==="typescript"&&te({source:u,testFile:h.testFile,implementationFile:h.implementationFile,invariantCount:h.invariantCount,numRuns:e.numRuns}),n.set(h.testFile,F("sha256").update(v).digest("hex"))}P(t.sourceRoot,e.prdPath),P(t.workspacePath,e.prdPath);const l=m(a(t.workspacePath,e.prdPath)),p=new TextDecoder("utf-8",{fatal:!0}).decode(l),c=It(p,e,o);mt(a(t.workspacePath,e.prdPath),c);const d=F("sha256").update(c).digest("hex");return W(t,[...e.writeSet,e.prdPath],t.baseSha,void 0,()=>{try{return!S(St(t.sourceRoot,r),e)||e.aggregates.some(h=>!pt(t.sourceRoot,t.workspacePath,h.implementationFile))||F("sha256").update(m(a(t.workspacePath,e.prdPath))).digest("hex")!==d?!1:[...n].every(([h,f])=>F("sha256").update(m(a(t.workspacePath,h))).digest("hex")===f)}catch{return!1}})}catch{throw new Error("private-execution-property-admission-unverified")}}export{Je as admitPrivateArchitectureStageWorkspace,Ne as admitPrivateEpicClaimWorkspace,Be as admitPrivateGenerateEpicWorkspace,De as admitPrivateIdeaDiagnosisWorkspace,Fe as admitPrivateIdeaResearchWorkspace,qe as admitPrivatePactWorkspace,Le as admitPrivateProjectStepWorkspace,Ge as admitPrivatePropertyTestWorkspace,ze as admitPrivateStateBoundStepWorkspace,Me as admitPrivateUxWorkspace,je as admitPrivateYoloFrozenWorkspace,He as appendPrivateArchitectureHandoff,Ce as appendPrivateStateBoundStepHandoff,Nt as privateArchitectureStagePaths,$e as privateYoloSourceFileMatchesSnapshot,Te as verifyPrivateYoloRejectedCandidateOrigin,Oe as verifyPrivateYoloSnapshotBoundary};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{execFile as pe}from"node:child_process";import{createHash as P}from"node:crypto";import{join as me}from"node:path";import{promisify as ye}from"node:util";import{classifyGitReconciliationCandidate as ee,isEpicOriginBindingEvidence as re,reconcileTerminalReceipt as we}from"../../../../shared/dist/yoloop/epic-terminal-git.js";import{collectGitResourceOwnership as Se,GIT_INVENTORY_PR_LIMIT as ae,GIT_INVENTORY_REF_LIMIT as z}from"./epic-git-reconciliation-inventory.js";import{executeEpicMergeCandidateQa as te,verifiedEpicMergeCandidateReceipt as G}from"./epic-merge-candidate-qa.js";import{ensureRuntimeEpic as ie,mutateGitLifecycleRuntime as ne}from"../../git/git-lifecycle-store.js";import{acceptedPhysicalCheckpointIds as Q,failure as c,fetchRemoteHeadExact as C,isAncestor as x,isCommit as oe,isRecord as b,physicalCheckpointOrder as be,physicallyValidHeadReconciliation as J,produceEpicLifecycleEvidence as _e,readEffectiveState as T,resolveOptionalRef as ve,resolveRemoteHeadFreshOptional as E,safeBranch as k,sameOrdered as ce,storyIds as se,stringValue as _,validFreshAggregate as F}from"../../git/epic-lifecycle-evidence.js";import{physicallyValidHeadReconciliation as Je,publicLifecycleEvidenceCause as Fe}from"../../git/epic-lifecycle-evidence.js";const xe=ye(pe);function Ke(r,t={}){const h=me(r,".neocortex","state.json"),a=t.gitRunner??((...e)=>le("git",e,r)),s=t.providerRunner??((...e)=>le("gh",e,r)),m=new Map;return{async prepareLifecycleEvidence(e){return _e({projectRoot:r,epicId:e.epicId,nowIso:e.nowIso,git:a,allowExecutionBranchSwitch:!0,...t.aggregateQaRunner?{aggregateQaRunner:t.aggregateQaRunner}:{}})},async inspect(e){try{const i=await T(r,h,!0),n=i.epics?.[e.epicId];if(!n)return c("epic-state-missing",!1,!1);if(_(n.execution_branch)!==e.executionBranch||_(n.origin_branch)!==e.originBranch)return c("epic-branch-boundary-drift",!1,!1);const d=await a("rev-parse",`refs/heads/${e.executionBranch}`),o=await N(a,e.originBranch);await C(a,e.originBranch,o);const u=await Q(r,i,n,e.epicId,e.executionBranch);let g=b(n.terminal_git_receipt)?n.terminal_git_receipt:null;g?.physicalStatus==="pushed"&&(g.pushedSha&&await x(a,g.executionHeadSha,g.pushedSha)&&await x(a,g.pushedSha,o)||(g=null)),g||(g=await Ie({directive:e,executionHeadSha:d,originHeadSha:o,git:a}));const l=new Set((Array.isArray(n.git_reconciliation_receipts)?n.git_reconciliation_receipts:[]).filter(b).filter(W).map(q=>_(q.resourceId)).filter(Boolean)),w=await a("symbolic-ref","--quiet","--short","HEAD").catch(()=>""),f=e.reconcile.enabled?await de({state:i,epic:n,directive:e,currentBranch:w,originHeadSha:o,receiptIds:l,git:a,gh:s}):[],p=re(n.origin_binding)?n.origin_binding:null,S=p&&p.originBranch===e.originBranch&&p.executionBranch===e.executionBranch&&await oe(a,p.originHeadSha)&&await x(a,p.originHeadSha,d)?p:null,y=b(n.aggregate_qa_receipt)?n.aggregate_qa_receipt:null,R=t.now?.()??new Date().toISOString(),B=y&&S&&await J({projectRoot:r,git:a,state:i,epic:n,epicId:e.epicId,executionBranch:e.executionBranch,originBranch:e.originBranch,executionHeadSha:d,graphRevision:e.graphRevision,aggregateQaReceipt:y,nowIso:R})?n.head_reconciliation_receipt:null,L=B?[...B.acceptedCheckpointIds]:u;return{ok:!0,snapshot:{executionHeadSha:d,originHeadSha:o,..._(n.graph_revision)?{graphRevision:_(n.graph_revision)}:{},writerLeaseActive:K(n.branch_lease),acceptedCheckpointIds:L,existingReceipt:g,aggregateQaReceipt:y,headReconciliationReceipt:B,originBinding:S,reconciliationCandidates:f}}}catch(i){return c(he(i)??"epic-terminal-inspection-failed",!0,!1)}},async prepareMergeObject(e){let i;try{const n=await a("merge-tree","--write-tree",e.originHeadSha,e.executionHeadSha);i=await a("commit-tree",n,"-p",e.originHeadSha,"-p",e.executionHeadSha,"-m",e.message)}catch{return c("epic-terminal-merge-conflict",!1,!1)}try{const n=await te(r,{mergeSha:i,originHeadSha:e.originHeadSha,executionHeadSha:e.executionHeadSha,graphRevision:e.graphRevision},e.nowIso);return m.set(i,n.candidateAuthority),{ok:!0,mergeSha:i,...n}}catch{return c("epic-merge-candidate-qa-failed",!0,!1)}},async inspectReconciliation(e){try{const i=await T(r,h,!0),n=i.epics?.[e.epicId];if(!n)return c("epic-state-missing",!1,!1);if(_(n.execution_branch)!==e.executionBranch||_(n.origin_branch)!==e.originBranch)return c("epic-branch-boundary-drift",!1,!1);const d=await N(a,e.originBranch);await C(a,e.originBranch,d);const o=new Set((Array.isArray(n.git_reconciliation_receipts)?n.git_reconciliation_receipts:[]).filter(b).filter(W).map(l=>_(l.resourceId)).filter(Boolean)),u=await a("symbolic-ref","--quiet","--short","HEAD").catch(()=>"");return{ok:!0,candidates:await de({state:i,epic:n,directive:e,currentBranch:u,originHeadSha:d,receiptIds:o,git:a,gh:s})}}catch(i){return c(he(i)??"git-reconciliation-inspection-failed",!0,!1)}},async pushMergeObject(e){try{if(!G(e.candidateAuthority,{mergeSha:e.mergeSha,originHeadSha:e.expectedOriginSha,executionHeadSha:e.executionHeadSha,graphRevision:e.graphRevision}))return c("epic-merge-candidate-authority-required",!1,!1);const n=await T(r,h,!0),d=n.epics?.[e.epicId];if(!d||d.execution_branch!==e.executionBranch||d.origin_branch!==e.originBranch||d.graph_revision!==e.graphRevision||K(d.branch_lease)||await a("rev-parse",`refs/heads/${e.executionBranch}`)!==e.executionHeadSha)return c("epic-merge-candidate-authority-raced",!0,!1);const o=await Q(r,n,d,e.epicId,e.executionBranch);if(!U(o,e.storyCheckpointIds)||!U(se(d),e.storyCheckpointIds))return c("epic-checkpoint-set-revalidation-drift",!0,!1);const u=b(d.aggregate_qa_receipt)?d.aggregate_qa_receipt:null;if(!F(u,e.executionHeadSha,e.graphRevision,e.nowIso)||u.receiptRef!==e.aggregateQaReceipt.receiptRef)return c("epic-terminal-aggregate-qa-revalidation-drift",!0,!1);if(!await J({projectRoot:r,git:a,state:n,epic:d,epicId:e.epicId,executionBranch:e.executionBranch,originBranch:e.originBranch,executionHeadSha:e.executionHeadSha,graphRevision:e.graphRevision,aggregateQaReceipt:u,nowIso:e.nowIso}))return c("epic-head-reconciliation-revalidation-drift",!0,!1);if(await N(a,e.originBranch)!==e.expectedOriginSha)return c("epic-origin-head-raced",!0,!1);await a("push","--porcelain","origin",`${e.mergeSha}:refs/heads/${e.originBranch}`);const l=await N(a,e.originBranch);return l!==e.mergeSha?c("epic-terminal-push-unverified",!0,!1):{ok:!0,pushedSha:l}}catch(i){return Y(i)?c("epic-terminal-remote-policy-denied",!0,!0):c("epic-terminal-push-failed",!0,!1)}},async ensureSingleEpicPullRequest(e){try{const i=G(e.candidateAuthority,{mergeSha:e.expectedPullRequestHeadSha,originHeadSha:e.candidateQa.originHeadSha,executionHeadSha:e.expectedStoryHeadSha,graphRevision:e.candidateQa.graphRevision});if(!i||i!==e.candidateQa||!await x(a,e.candidateQa.originHeadSha,e.expectedPullRequestHeadSha)||!await x(a,e.expectedStoryHeadSha,e.expectedPullRequestHeadSha))return c("epic-merge-candidate-authority-required",!1,!1);const n=await $(a,s);if(!n)return c("git-resource-provider-repository-unverified",!0,!0);if(e.terminalBinding&&!await ue({projectRoot:r,statePath:h,git:a,epicId:e.epicId,originBranch:e.originBranch,executionBranch:e.executionBranch,executionHeadSha:e.expectedStoryHeadSha,graphRevision:e.terminalBinding.graphRevision,storyCheckpointIds:e.terminalBinding.storyCheckpointIds,aggregateQaReceipt:e.terminalBinding.aggregateQaReceipt,nowIso:e.terminalBinding.nowIso}))return c("epic-head-reconciliation-revalidation-drift",!0,!1);const d=`https://github.com/${n.nameWithOwner}`,o=await E(a,e.executionBranch);if(o&&o!==e.expectedPullRequestHeadSha){if(await C(a,e.executionBranch,o),!await x(a,o,e.expectedPullRequestHeadSha))return c("epic-terminal-execution-remote-head-drift",!0,!0);await a("push","--porcelain","origin",`${e.expectedPullRequestHeadSha}:refs/heads/${e.executionBranch}`)}if(o||await a("push","--porcelain","origin",`${e.expectedPullRequestHeadSha}:refs/heads/${e.executionBranch}`),await N(a,e.executionBranch)!==e.expectedPullRequestHeadSha)return c("epic-terminal-execution-publish-unverified",!0,!0);const u=await s("pr","list","--repo",d,"--state","all","--head",e.executionBranch,"--base",e.originBranch,"--json","number,state,headRefName,headRefOid,baseRefName,mergeCommit","--limit","100"),g=JSON.parse(u),l=g.filter(y=>y.headRefName===e.executionBranch&&y.baseRefName===e.originBranch&&y.headRefOid===e.expectedPullRequestHeadSha&&(y.state==="OPEN"||y.state==="MERGED"));if(l.length>1)return c("epic-terminal-duplicate-prs",!1,!0);if(typeof l[0]?.number=="number")return{ok:!0,prNumber:l[0].number};if(g.some(y=>y.state==="OPEN"))return c("epic-terminal-stale-pr",!1,!0);const f=(await s("pr","create","--repo",d,"--head",e.executionBranch,"--base",e.originBranch,"--title",`[${e.epicId}] Terminal epic integration`,"--body",`Autonomous terminal integration receipt: ${e.idempotencyKey}`)).match(/\/(\d+)(?:\s*)$/);if(!f)return c("epic-terminal-pr-number-unverified",!0,!0);const p=Number(f[1]),S=await V(s,n.nameWithOwner,p);return!S||S.state!=="OPEN"||S.headRefName!==e.executionBranch||S.baseRefName!==e.originBranch||S.headRefOid!==e.expectedPullRequestHeadSha?c("epic-terminal-pr-create-unverified",!0,!0):{ok:!0,prNumber:p}}catch(i){return c("epic-terminal-pr-create-denied",!0,Y(i))}},async mergeEpicPullRequest(e){try{const i=await $(a,s);if(!i)return c("git-resource-provider-repository-unverified",!0,!0);const n=e.candidateQa&&G(e.candidateAuthority,{mergeSha:e.expectedPullRequestHeadSha,graphRevision:e.candidateQa.graphRevision,originHeadSha:e.expectedOriginHeadSha,executionHeadSha:e.expectedStoryHeadSha});if(!n||n!==e.candidateQa)return c("epic-merge-candidate-authority-required",!1,!1);const d=await V(s,i.nameWithOwner,e.prNumber),o=await E(a,e.executionBranch),u=await N(a,e.originBranch);if(!d||d.headRefName!==e.executionBranch||d.baseRefName!==e.originBranch||d.headRefOid!==e.expectedPullRequestHeadSha||o&&o!==e.expectedPullRequestHeadSha||!await x(a,e.expectedOriginHeadSha,e.expectedPullRequestHeadSha)||!await x(a,e.expectedStoryHeadSha,e.expectedPullRequestHeadSha))return c("epic-terminal-pr-revalidation-drift",!0,!0);if(d.state==="OPEN"&&u!==e.expectedOriginHeadSha)return c("epic-terminal-pr-origin-raced",!0,!0);let g;if(d.state==="OPEN"){const y=await Ne(s,i.nameWithOwner,e.originBranch,e.expectedPullRequestHeadSha,e.expectedOriginHeadSha,e.nowIso);if(!y.ok)return c(y.reasonCode,!0,!0);if(g=y.receipt,e.terminalBinding&&(!e.epicId||!await ue({projectRoot:r,statePath:h,git:a,epicId:e.epicId,originBranch:e.originBranch,executionBranch:e.executionBranch,executionHeadSha:e.expectedStoryHeadSha,graphRevision:e.terminalBinding.graphRevision,storyCheckpointIds:e.terminalBinding.storyCheckpointIds,aggregateQaReceipt:e.terminalBinding.aggregateQaReceipt,nowIso:e.nowIso})))return c("epic-head-reconciliation-revalidation-drift",!0,!1);if(await N(a,e.originBranch)!==e.expectedOriginHeadSha)return c("epic-terminal-pr-origin-raced",!0,!0);await s("pr","merge",String(e.prNumber),"--repo",`https://github.com/${i.nameWithOwner}`,"--merge","--match-head-commit",e.expectedPullRequestHeadSha)}else{if(d.state!=="MERGED")return c("epic-terminal-pr-not-open-or-merged",!1,!0);g={schemaVersion:1,provider:"github",mode:"recovered_exact_tree",source:"physical_recovery",prHeadSha:e.expectedPullRequestHeadSha,originHeadSha:e.expectedOriginHeadSha,checkedAt:e.nowIso,publicSafe:!0}}const l=await V(s,i.nameWithOwner,e.prNumber),w=l?.mergeCommit?.oid;if(l?.state!=="MERGED"||!w)return c("epic-terminal-pr-merge-unverified",!0,!0);const f=await N(a,e.originBranch);if(await C(a,e.originBranch,f),!await x(a,e.expectedStoryHeadSha,f)||!await x(a,e.expectedPullRequestHeadSha,f)||!await x(a,w,f))return c("epic-terminal-pr-merge-ancestry-unproven",!0,!0);const[p,S]=await Promise.all([a("rev-parse",`${e.expectedPullRequestHeadSha}^{tree}`),a("rev-parse",`${w}^{tree}`)]);return p!==e.candidateQa.treeSha||S!==p?c("epic-terminal-pr-merged-tree-mismatch",!1,!0):{ok:!0,mergeSha:e.expectedPullRequestHeadSha,pushedSha:w,providerGuard:g}}catch(i){return c("epic-terminal-pr-merge-denied",!0,Y(i))}},async verifyTerminalReceipt(e,i,n){try{if(i.physicalStatus!=="pushed"||!i.pushedSha||!i.mergeSha)return c("epic-terminal-physical-revalidation-required",!0,!1);const d=await T(r,h,!0),o=d.epics?.[e.epicId];if(!o||_(o.execution_branch)!==e.executionBranch||_(o.origin_branch)!==e.originBranch||_(o.graph_revision)!==e.graphRevision)return c("epic-terminal-state-revalidation-drift",!0,!1);const u=await a("rev-parse",`refs/heads/${e.executionBranch}`);if(u!==e.expectedExecutionHeadSha||i.executionHeadSha!==u)return c("epic-terminal-execution-revalidation-drift",!0,!1);const g=re(o.origin_binding)?o.origin_binding:null;if(!g||g.originBranch!==e.originBranch||g.executionBranch!==e.executionBranch||!await oe(a,g.originHeadSha)||!await x(a,g.originHeadSha,u))return c("epic-origin-binding-revalidation-drift",!0,!1);const l=await Q(r,d,o,e.epicId,e.executionBranch);if(K(o.branch_lease)||!U(l,e.storyCheckpointIds))return c("epic-checkpoint-set-revalidation-drift",!0,!1);const w=b(o.aggregate_qa_receipt)?o.aggregate_qa_receipt:null;if(!F(w,u,e.graphRevision,n)||w?.receiptRef!==e.localGates.aggregateQaReceipt.receiptRef)return c("epic-terminal-aggregate-qa-revalidation-drift",!0,!1);const f=await N(a,e.originBranch);if(await C(a,e.originBranch,f),!await x(a,u,f)||!await x(a,i.mergeSha,f)||!await x(a,i.pushedSha,f))return c("epic-terminal-physical-ancestry-unproven",!0,!1);const p={originHeadSha:i.baseSha,executionHeadSha:u,mergeSha:i.mergeSha,graphRevision:e.graphRevision};let S=m.get(i.mergeSha),y=G(S,p);if(!y){const B=await te(r,p,n);S=B.candidateAuthority,y=B.candidateQa,m.set(i.mergeSha,S)}if(i.candidateQa&&(i.candidateQa.originHeadSha!==y.originHeadSha||i.candidateQa.executionHeadSha!==y.executionHeadSha||i.candidateQa.graphRevision!==y.graphRevision||i.candidateQa.treeSha!==y.treeSha))return c("epic-merge-candidate-receipt-drift",!0,!1);let R=i.providerGuard;if(i.strategy==="single_pr"){if(!i.prNumber)return c("epic-terminal-pr-merge-unverified",!0,!1);if(await a("rev-parse",`${i.pushedSha}^{tree}`)!==y.treeSha)return c("epic-terminal-pr-merged-tree-mismatch",!1,!1);if(R&&!Oe(R,i))return c("epic-terminal-pr-base-guard-unverifiable",!1,!1);R??={schemaVersion:1,provider:"github",mode:"recovered_exact_tree",source:"physical_recovery",prHeadSha:i.mergeSha,originHeadSha:i.baseSha,checkedAt:n,publicSafe:!0}}else if(R)return c("epic-terminal-pr-base-guard-unverifiable",!1,!1);return{ok:!0,candidateQa:y,candidateAuthority:S,...R?{providerGuard:R}:{}}}catch{return c("epic-terminal-physical-revalidation-failed",!0,!1)}},async applyReconciliation(e,i,n){if(i.action==="preserve")return c("git-reconciliation-preserve-not-actionable",!1,!1);if(n)return{ok:!0,outcome:"dry_run"};if(i.action==="no_op")return{ok:!0,outcome:"already_absent"};if(i.action==="delete_remote_branch")return Re(e,i,a,s);try{const d=await D({candidate:e,decision:i,git:a,gh:s});if(!d.ok)return c(d.reasonCode,!0,!1);if(d.alreadyAbsent)return{ok:!0,outcome:"already_absent"};if(i.action==="delete_local_branch")await a("update-ref","-d",`refs/heads/${e.branchName}`,e.headSha);else if(i.action==="close_pull_request"){if(!e.prNumber)return c("git-reconciliation-pr-number-missing",!1,!1);const o=await $(a,s);if(!o)return c("git-resource-provider-repository-unverified",!0,!0);const u=`https://github.com/${o.nameWithOwner}`,g=`neocortex-reconciliation:${P("sha256").update(e.resourceId).digest("hex")}`,l=JSON.parse(await s("pr","view",String(e.prNumber),"--repo",u,"--json","comments"));if(!b(l)||!Array.isArray(l.comments)||l.comments.length>1e3||l.comments.some(p=>!b(p)||typeof p.body!="string"))return c("git-reconciliation-pr-comments-unverified",!0,!0);l.comments.some(p=>String(p.body).includes(g))||await s("pr","comment",String(e.prNumber),"--repo",u,"--body",`Neocortex reconciliation verified managed ownership and integrated content; requesting closure. [${g}]`);const w=await D({candidate:e,decision:i,git:a,gh:s});if(!w.ok)return c(w.reasonCode,!0,!1);if(w.alreadyAbsent)return{ok:!0,outcome:"already_absent"};await s("pr","close",String(e.prNumber),"--repo",u);const f=await D({candidate:e,decision:i,git:a,gh:s});if(!f.ok)return c(f.reasonCode,!0,!1);if(!f.alreadyAbsent)return c("git-reconciliation-pr-close-unverified",!0,!0)}return{ok:!0,outcome:"applied"}}catch{return c("git-reconciliation-effect-failed",!0,!1)}},async persist(e){try{let i;return await ne(r,n=>{const d=ie(n,e.terminalReceipt.epicId),o=Array.isArray(d.git_reconciliation_receipts)?d.git_reconciliation_receipts.filter(b):[],u=new Map(o.map(w=>[w.idempotencyKey,w]));for(const w of e.reconciliationReceipts)W(u.get(w.idempotencyKey))||u.set(w.idempotencyKey,w);const g=b(d.terminal_git_receipt)?d.terminal_git_receipt:null,l=we(g,e.terminalReceipt);if(l.kind==="blocked"){i=l.reasonCode;return}d.terminal_git_receipt=l.receipt,d.git_reconciliation_receipts=[...u.values()],d.physicalMergeStatus=e.terminalReceipt.physicalStatus==="pushed"?"merged":e.terminalReceipt.physicalStatus,d.pr_number=e.terminalReceipt.prNumber??d.pr_number??null,d.git_reconciliation_debt=ge(d.git_reconciliation_debt,e.preservedDecisions)}),i?c(i,!1,!1):{ok:!0}}catch{return c("epic-terminal-state-persist-failed",!0,!1)}},async persistReconciliation(e){try{return await ne(r,i=>{const n=ie(i,e.epicId),d=Array.isArray(n.git_reconciliation_receipts)?n.git_reconciliation_receipts.filter(b):[],o=new Map(d.map(u=>[u.idempotencyKey,u]));for(const u of e.reconciliationReceipts)W(o.get(u.idempotencyKey))||o.set(u.idempotencyKey,u);n.git_reconciliation_receipts=[...o.values()],n.git_reconciliation_debt=ge(n.git_reconciliation_debt,e.preservedDecisions)}),{ok:!0}}catch{return c("git-reconciliation-state-persist-failed",!0,!1)}}}}async function $(r,t){try{const h=await r("remote","get-url","origin"),a=h.match(/^https:\/\/github\.com\/([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+?)(?:\.git)?\/?$/)?.[1]??h.match(/^git@github\.com:([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+?)(?:\.git)?$/)?.[1];if(!a)return null;const s=JSON.parse(await t("repo","view",`https://github.com/${a}`,"--json","id,nameWithOwner,url"));return s.nameWithOwner!==a||s.url!==`https://github.com/${a}`||typeof s.id!="string"||!/^[A-Za-z0-9_=-]{1,256}$/.test(s.id)?null:{id:s.id,nameWithOwner:a}}catch{return null}}async function Re(r,t,h,a){try{if(r.kind!=="remote_branch"||t.resourceId!==r.resourceId||!r.baseBranch||r.baseBranch===r.branchName||!k(r.branchName)||!k(r.baseBranch)||!/^[a-f0-9]{40}$/.test(r.headSha)||!/^[a-f0-9]{40}$/.test(r.integrationHeadSha))return c("git-reconciliation-candidate-no-longer-safe",!1,!1);const s=await $(h,a);if(!s)return c("git-resource-remote-delete-cas-unavailable",!1,!1);if(!await E(h,r.branchName))return{ok:!0,outcome:"already_absent"};const e=await D({candidate:r,decision:t,git:h,gh:a});if(!e.ok)return c(e.reasonCode,!0,!1);if((await $(h,a))?.id!==s.id)return c("git-resource-provider-repository-raced",!0,!1);const n=P("sha256").update(["managed-remote-delete-v1",s.id,r.branchName,r.headSha,r.baseBranch,r.integrationHeadSha].join("\0")).digest("hex"),d=(g,l,w)=>`{name:${JSON.stringify(`refs/heads/${g}`)},beforeOid:${JSON.stringify(l)},afterOid:${JSON.stringify(w)},force:false}`,o=`mutation{updateRefs(input:{repositoryId:${JSON.stringify(s.id)},clientMutationId:${JSON.stringify(n)},refUpdates:[`+d(r.branchName,r.headSha,"0".repeat(40))+","+d(r.baseBranch,r.integrationHeadSha,r.integrationHeadSha)+"]}){clientMutationId}}",u=JSON.parse(await a("api","graphql","--hostname","github.com","-f",`query=${o}`));return u.errors||u.data?.updateRefs?.clientMutationId!==n?c("git-resource-remote-delete-cas-unverified",!0,!0):await E(h,r.branchName)?c("git-resource-remote-delete-recreated-or-unverified",!0,!1):{ok:!0,outcome:"applied"}}catch{return c("git-resource-remote-delete-cas-rejected",!0,!0)}}async function D(r){const{candidate:t,decision:h,git:a,gh:s}=r;if(!h.managed||!t.providerVerified||t.current||t.origin||t.protected||t.lifecycle==="active"||t.hasExclusiveCommits||t.worktreeActive)return{ok:!1,reasonCode:"git-reconciliation-candidate-no-longer-safe"};const m=await a("symbolic-ref","--quiet","--short","HEAD").catch(()=>""),e=await fe(a);if(m===t.branchName||e.has(t.branchName))return{ok:!1,reasonCode:"git-resource-worktree-active"};if(t.kind==="local_branch"){const o=await ve(a,`refs/heads/${t.branchName}`);return o?o!==t.headSha?{ok:!1,reasonCode:"git-resource-expected-oid-raced"}:!t.baseBranch||await N(a,t.baseBranch)!==t.integrationHeadSha||!await x(a,o,t.integrationHeadSha)?{ok:!1,reasonCode:"git-resource-integration-unproven"}:{ok:!0}:{ok:!0,alreadyAbsent:!0}}if(t.kind==="remote_branch"){const o=await E(a,t.branchName);if(!o)return{ok:!0};if(o!==t.headSha)return{ok:!1,reasonCode:"git-resource-expected-oid-raced"};const u=await $(a,s);return u?await Z(s,u.nameWithOwner,t.branchName)!=="unprotected"?{ok:!1,reasonCode:"git-resource-protected"}:!t.baseBranch||await N(a,t.baseBranch)!==t.integrationHeadSha?{ok:!1,reasonCode:"git-resource-integration-unproven"}:(await a("fetch","--quiet","--no-tags","origin",`refs/heads/${t.branchName}`),await a("rev-parse","FETCH_HEAD")!==t.headSha||!await x(a,t.headSha,t.integrationHeadSha)?{ok:!1,reasonCode:"git-resource-integration-unproven"}:{ok:!0}):{ok:!1,reasonCode:"git-resource-provider-repository-unverified"}}if(!t.prNumber||!t.baseBranch)return{ok:!1,reasonCode:"git-reconciliation-pr-proof-missing"};const i=await $(a,s);if(!i)return{ok:!1,reasonCode:"git-resource-provider-repository-unverified"};const n=await V(s,i.nameWithOwner,t.prNumber);if(!n||n.headRefName!==t.branchName||n.baseRefName!==t.baseBranch||n.headRefOid!==t.headSha)return{ok:!1,reasonCode:"git-resource-expected-oid-raced"};if(n.state==="CLOSED"||n.state==="MERGED")return{ok:!0,alreadyAbsent:!0};if(await Z(s,i.nameWithOwner,t.branchName)!=="unprotected")return{ok:!1,reasonCode:"git-resource-protected"};const d=await E(a,t.branchName);return!n||n.state!=="OPEN"||n.headRefName!==t.branchName||n.baseRefName!==t.baseBranch||n.headRefOid!==t.headSha||d!==t.headSha?{ok:!1,reasonCode:"git-resource-expected-oid-raced"}:(await a("fetch","--quiet","--no-tags","origin",`refs/heads/${t.branchName}`),await a("rev-parse","FETCH_HEAD")!==t.headSha||await N(a,t.baseBranch)!==t.integrationHeadSha||!await x(a,t.headSha,t.integrationHeadSha)?{ok:!1,reasonCode:"git-resource-integration-unproven"}:{ok:!0})}async function de(r){const t=[],h=await fe(r.git),a=Se(r.state),s=await $(r.git,r.gh),m=f=>{const p=f.split(`
|
|
2
|
-
`).filter(Boolean).map(
|
|
3
|
-
`).filter(d=>/^[a-f0-9]{40,64}$/i.test(d));if(t.length!==1)return null;const h=t[0],a=(await r.git("rev-list","--parents","-n","1",h)).split(/\s+/),s=await r.git("show","-s","--format=%B",h),[
|
|
4
|
-
`),e=`merge(${r.directive.epicId}): integrate ${r.directive.executionBranch} into ${r.directive.originBranch}`;if(a.length!==3||a[2]!==r.executionHeadSha||
|
|
5
|
-
`).map(d=>d.trim()));for(const d of[`Neocortex-Epic: ${r.directive.epicId}`,`Neocortex-Origin-Branch: ${r.directive.originBranch}`,`Neocortex-Execution-Branch: ${r.directive.executionBranch}`,`Neocortex-Execution-Head: ${r.executionHeadSha}`,`Neocortex-Origin-Base: ${a[1]}`,`Neocortex-Graph-Revision: ${r.directive.graphRevision}`,`Neocortex-Aggregate-QA: ${r.directive.localGates.aggregateQaReceipt.receiptRef}`,`Neocortex-Idempotency: ${r.directive.idempotencyKey}`])if(!i.has(d))return null;const n=await r.git("show","-s","--format=%cI",h);return{schemaVersion:1,epicId:r.directive.epicId,executionBranch:r.directive.executionBranch,originBranch:r.directive.originBranch,baseSha:a[1],executionHeadSha:r.executionHeadSha,mergeSha:h,pushedSha:h,strategy:"direct",physicalStatus:"pushed",localGateReceiptRefs:r.directive.localGates.receiptRefs,idempotencyKey:r.directive.idempotencyKey,attemptStartedAt:n,completedAt:n,retryEligible:!1,reasonCodes:["epic-terminal-recovered-physical-push"],publicSafe:!0}}catch{return null}}async function
|
|
6
|
-
`))a.startsWith("branch refs/heads/")&&t.add(a.slice(18));return t}function
|
|
1
|
+
import{execFile as we}from"node:child_process";import{createHash as q}from"node:crypto";import{join as be}from"node:path";import{promisify as Se}from"node:util";import{classifyGitReconciliationCandidate as ie,isEpicOriginBindingEvidence as ne,reconcileTerminalReceipt as _e}from"../../../../shared/dist/yoloop/epic-terminal-git.js";import{collectGitResourceOwnership as ve,GIT_INVENTORY_PR_LIMIT as oe,GIT_INVENTORY_REF_LIMIT as F}from"./epic-git-reconciliation-inventory.js";import{executeEpicMergeCandidateQa as ce,verifiedEpicMergeCandidateReceipt as G}from"./epic-merge-candidate-qa.js";import{ensureRuntimeEpic as se,mutateGitLifecycleRuntime as de}from"../../git/git-lifecycle-store.js";import{acceptedPhysicalCheckpointIds as Q,failure as c,fetchRemoteHeadExact as D,isAncestor as x,isCommit as W,isRecord as S,physicalCheckpointOrder as xe,physicallyValidHeadReconciliation as Z,produceEpicLifecycleEvidence as Re,readEffectiveState as P,resolveOptionalRef as Be,resolveRemoteHeadFreshOptional as $,safeBranch as N,sameOrdered as he,storyIds as le,stringValue as _,validFreshAggregate as U}from"../../git/epic-lifecycle-evidence.js";import{physicallyValidHeadReconciliation as Ue,publicLifecycleEvidenceCause as Ye}from"../../git/epic-lifecycle-evidence.js";const He=Se(we);function Je(r,t={}){const h=be(r,".neocortex","state.json"),a=t.gitRunner??((...e)=>fe("git",e,r)),s=t.providerRunner??((...e)=>fe("gh",e,r)),y=new Map;return{async prepareLifecycleEvidence(e){return Re({projectRoot:r,epicId:e.epicId,nowIso:e.nowIso,git:a,allowExecutionBranchSwitch:!0,...t.aggregateQaRunner?{aggregateQaRunner:t.aggregateQaRunner}:{}})},async inspect(e){try{const i=await P(r,h,!0),n=i.epics?.[e.epicId];if(!n)return c("epic-state-missing",!1,!1);if(_(n.execution_branch)!==e.executionBranch||_(n.origin_branch)!==e.originBranch)return c("epic-branch-boundary-drift",!1,!1);const d=await a("rev-parse",`refs/heads/${e.executionBranch}`),o=await k(a,e.originBranch);await D(a,e.originBranch,o);const l=await Q(r,i,n,e.epicId,e.executionBranch);let f=S(n.terminal_git_receipt)?n.terminal_git_receipt:null;f?.physicalStatus==="pushed"&&(f.pushedSha&&await x(a,f.executionHeadSha,f.pushedSha)&&await x(a,f.pushedSha,o)||(f=null)),f||(f=await Oe({directive:e,executionHeadSha:d,originHeadSha:o,git:a}));const p=new Set((Array.isArray(n.git_reconciliation_receipts)?n.git_reconciliation_receipts:[]).filter(S).filter(K).map(O=>_(O.resourceId)).filter(Boolean)),u=await a("symbolic-ref","--quiet","--short","HEAD").catch(()=>""),g=e.reconcile.enabled?await ue({state:i,epic:n,directive:e,currentBranch:u,originHeadSha:o,receiptIds:p,git:a,gh:s}):[],m=ne(n.origin_binding)?n.origin_binding:null,b=m&&m.originBranch===e.originBranch&&m.executionBranch===e.executionBranch&&await W(a,m.originHeadSha)&&await x(a,m.originHeadSha,d)?m:null,w=S(n.aggregate_qa_receipt)?n.aggregate_qa_receipt:null,B=t.now?.()??new Date().toISOString(),R=w&&b&&await Z({projectRoot:r,git:a,state:i,epic:n,epicId:e.epicId,executionBranch:e.executionBranch,originBranch:e.originBranch,executionHeadSha:d,graphRevision:e.graphRevision,aggregateQaReceipt:w,nowIso:B})?n.head_reconciliation_receipt:null,T=R?[...R.acceptedCheckpointIds]:l;return{ok:!0,snapshot:{executionHeadSha:d,originHeadSha:o,..._(n.graph_revision)?{graphRevision:_(n.graph_revision)}:{},writerLeaseActive:z(n.branch_lease),acceptedCheckpointIds:T,existingReceipt:f,aggregateQaReceipt:w,headReconciliationReceipt:R,originBinding:b,reconciliationCandidates:g}}}catch(i){return c(ge(i)??"epic-terminal-inspection-failed",!0,!1)}},async prepareMergeObject(e){let i;try{const n=await a("merge-tree","--write-tree",e.originHeadSha,e.executionHeadSha);i=await a("commit-tree",n,"-p",e.originHeadSha,"-p",e.executionHeadSha,"-m",e.message)}catch{return c("epic-terminal-merge-conflict",!1,!1)}try{const n=await ce(r,{mergeSha:i,originHeadSha:e.originHeadSha,executionHeadSha:e.executionHeadSha,graphRevision:e.graphRevision},e.nowIso);return y.set(i,n.candidateAuthority),{ok:!0,mergeSha:i,...n}}catch{return c("epic-merge-candidate-qa-failed",!0,!1)}},async inspectReconciliation(e){try{const i=await A("git-reconciliation-state-unavailable",()=>P(r,h,!0)),n=i.epics?.[e.epicId];if(!n)return c("epic-state-missing",!1,!1);if(_(n.execution_branch)!==e.executionBranch||_(n.origin_branch)!==e.originBranch)return c("epic-branch-boundary-drift",!1,!1);const d=await A("git-reconciliation-origin-query-failed",()=>$(a,e.originBranch));if(!d)return c("git-reconciliation-origin-ref-missing",!0,!1);await Y(a,d,"git-reconciliation-origin-fetch-failed");const o=new Set((Array.isArray(n.git_reconciliation_receipts)?n.git_reconciliation_receipts:[]).filter(S).filter(K).map(p=>_(p.resourceId)).filter(Boolean)),l=await a("symbolic-ref","--quiet","--short","HEAD").catch(()=>"");return{ok:!0,candidates:await ue({state:i,epic:n,directive:e,currentBranch:l,originHeadSha:d,receiptIds:o,git:a,gh:s})}}catch(i){return c(ge(i)??"git-reconciliation-inspection-failed",!0,!1)}},async pushMergeObject(e){try{if(!G(e.candidateAuthority,{mergeSha:e.mergeSha,originHeadSha:e.expectedOriginSha,executionHeadSha:e.executionHeadSha,graphRevision:e.graphRevision}))return c("epic-merge-candidate-authority-required",!1,!1);const n=await P(r,h,!0),d=n.epics?.[e.epicId];if(!d||d.execution_branch!==e.executionBranch||d.origin_branch!==e.originBranch||d.graph_revision!==e.graphRevision||z(d.branch_lease)||await a("rev-parse",`refs/heads/${e.executionBranch}`)!==e.executionHeadSha)return c("epic-merge-candidate-authority-raced",!0,!1);const o=await Q(r,n,d,e.epicId,e.executionBranch);if(!X(o,e.storyCheckpointIds)||!X(le(d),e.storyCheckpointIds))return c("epic-checkpoint-set-revalidation-drift",!0,!1);const l=S(d.aggregate_qa_receipt)?d.aggregate_qa_receipt:null;if(!U(l,e.executionHeadSha,e.graphRevision,e.nowIso)||l.receiptRef!==e.aggregateQaReceipt.receiptRef)return c("epic-terminal-aggregate-qa-revalidation-drift",!0,!1);if(!await Z({projectRoot:r,git:a,state:n,epic:d,epicId:e.epicId,executionBranch:e.executionBranch,originBranch:e.originBranch,executionHeadSha:e.executionHeadSha,graphRevision:e.graphRevision,aggregateQaReceipt:l,nowIso:e.nowIso}))return c("epic-head-reconciliation-revalidation-drift",!0,!1);if(await k(a,e.originBranch)!==e.expectedOriginSha)return c("epic-origin-head-raced",!0,!1);await a("push","--porcelain","origin",`${e.mergeSha}:refs/heads/${e.originBranch}`);const p=await k(a,e.originBranch);return p!==e.mergeSha?c("epic-terminal-push-unverified",!0,!1):{ok:!0,pushedSha:p}}catch(i){return ee(i)?c("epic-terminal-remote-policy-denied",!0,!0):c("epic-terminal-push-failed",!0,!1)}},async ensureSingleEpicPullRequest(e){try{const i=G(e.candidateAuthority,{mergeSha:e.expectedPullRequestHeadSha,originHeadSha:e.candidateQa.originHeadSha,executionHeadSha:e.expectedStoryHeadSha,graphRevision:e.candidateQa.graphRevision});if(!i||i!==e.candidateQa||!await x(a,e.candidateQa.originHeadSha,e.expectedPullRequestHeadSha)||!await x(a,e.expectedStoryHeadSha,e.expectedPullRequestHeadSha))return c("epic-merge-candidate-authority-required",!1,!1);const n=await C(a,s);if(!n)return c("git-resource-provider-repository-unverified",!0,!0);if(e.terminalBinding&&!await pe({projectRoot:r,statePath:h,git:a,epicId:e.epicId,originBranch:e.originBranch,executionBranch:e.executionBranch,executionHeadSha:e.expectedStoryHeadSha,graphRevision:e.terminalBinding.graphRevision,storyCheckpointIds:e.terminalBinding.storyCheckpointIds,aggregateQaReceipt:e.terminalBinding.aggregateQaReceipt,nowIso:e.terminalBinding.nowIso}))return c("epic-head-reconciliation-revalidation-drift",!0,!1);const d=`https://github.com/${n.nameWithOwner}`,o=await $(a,e.executionBranch);if(o&&o!==e.expectedPullRequestHeadSha){if(await D(a,e.executionBranch,o),!await x(a,o,e.expectedPullRequestHeadSha))return c("epic-terminal-execution-remote-head-drift",!0,!0);await a("push","--porcelain","origin",`${e.expectedPullRequestHeadSha}:refs/heads/${e.executionBranch}`)}if(o||await a("push","--porcelain","origin",`${e.expectedPullRequestHeadSha}:refs/heads/${e.executionBranch}`),await k(a,e.executionBranch)!==e.expectedPullRequestHeadSha)return c("epic-terminal-execution-publish-unverified",!0,!0);const l=await s("pr","list","--repo",d,"--state","all","--head",e.executionBranch,"--base",e.originBranch,"--json","number,state,headRefName,headRefOid,baseRefName,mergeCommit","--limit","100"),f=JSON.parse(l),p=f.filter(w=>w.headRefName===e.executionBranch&&w.baseRefName===e.originBranch&&w.headRefOid===e.expectedPullRequestHeadSha&&(w.state==="OPEN"||w.state==="MERGED"));if(p.length>1)return c("epic-terminal-duplicate-prs",!1,!0);if(typeof p[0]?.number=="number")return{ok:!0,prNumber:p[0].number};if(f.some(w=>w.state==="OPEN"))return c("epic-terminal-stale-pr",!1,!0);const g=(await s("pr","create","--repo",d,"--head",e.executionBranch,"--base",e.originBranch,"--title",`[${e.epicId}] Terminal epic integration`,"--body",`Autonomous terminal integration receipt: ${e.idempotencyKey}`)).match(/\/(\d+)(?:\s*)$/);if(!g)return c("epic-terminal-pr-number-unverified",!0,!0);const m=Number(g[1]),b=await L(s,n.nameWithOwner,m);return!b||b.state!=="OPEN"||b.headRefName!==e.executionBranch||b.baseRefName!==e.originBranch||b.headRefOid!==e.expectedPullRequestHeadSha?c("epic-terminal-pr-create-unverified",!0,!0):{ok:!0,prNumber:m}}catch(i){return c("epic-terminal-pr-create-denied",!0,ee(i))}},async mergeEpicPullRequest(e){try{const i=await C(a,s);if(!i)return c("git-resource-provider-repository-unverified",!0,!0);const n=e.candidateQa&&G(e.candidateAuthority,{mergeSha:e.expectedPullRequestHeadSha,graphRevision:e.candidateQa.graphRevision,originHeadSha:e.expectedOriginHeadSha,executionHeadSha:e.expectedStoryHeadSha});if(!n||n!==e.candidateQa)return c("epic-merge-candidate-authority-required",!1,!1);const d=await L(s,i.nameWithOwner,e.prNumber),o=await $(a,e.executionBranch),l=await k(a,e.originBranch);if(!d||d.headRefName!==e.executionBranch||d.baseRefName!==e.originBranch||d.headRefOid!==e.expectedPullRequestHeadSha||o&&o!==e.expectedPullRequestHeadSha||!await x(a,e.expectedOriginHeadSha,e.expectedPullRequestHeadSha)||!await x(a,e.expectedStoryHeadSha,e.expectedPullRequestHeadSha))return c("epic-terminal-pr-revalidation-drift",!0,!0);if(d.state==="OPEN"&&l!==e.expectedOriginHeadSha)return c("epic-terminal-pr-origin-raced",!0,!0);let f;if(d.state==="OPEN"){const w=await Ee(s,i.nameWithOwner,e.originBranch,e.expectedPullRequestHeadSha,e.expectedOriginHeadSha,e.nowIso);if(!w.ok)return c(w.reasonCode,!0,!0);if(f=w.receipt,e.terminalBinding&&(!e.epicId||!await pe({projectRoot:r,statePath:h,git:a,epicId:e.epicId,originBranch:e.originBranch,executionBranch:e.executionBranch,executionHeadSha:e.expectedStoryHeadSha,graphRevision:e.terminalBinding.graphRevision,storyCheckpointIds:e.terminalBinding.storyCheckpointIds,aggregateQaReceipt:e.terminalBinding.aggregateQaReceipt,nowIso:e.nowIso})))return c("epic-head-reconciliation-revalidation-drift",!0,!1);if(await k(a,e.originBranch)!==e.expectedOriginHeadSha)return c("epic-terminal-pr-origin-raced",!0,!0);await s("pr","merge",String(e.prNumber),"--repo",`https://github.com/${i.nameWithOwner}`,"--merge","--match-head-commit",e.expectedPullRequestHeadSha)}else{if(d.state!=="MERGED")return c("epic-terminal-pr-not-open-or-merged",!1,!0);f={schemaVersion:1,provider:"github",mode:"recovered_exact_tree",source:"physical_recovery",prHeadSha:e.expectedPullRequestHeadSha,originHeadSha:e.expectedOriginHeadSha,checkedAt:e.nowIso,publicSafe:!0}}const p=await L(s,i.nameWithOwner,e.prNumber),u=p?.mergeCommit?.oid;if(p?.state!=="MERGED"||!u)return c("epic-terminal-pr-merge-unverified",!0,!0);const g=await k(a,e.originBranch);if(await D(a,e.originBranch,g),!await x(a,e.expectedStoryHeadSha,g)||!await x(a,e.expectedPullRequestHeadSha,g)||!await x(a,u,g))return c("epic-terminal-pr-merge-ancestry-unproven",!0,!0);const[m,b]=await Promise.all([a("rev-parse",`${e.expectedPullRequestHeadSha}^{tree}`),a("rev-parse",`${u}^{tree}`)]);return m!==e.candidateQa.treeSha||b!==m?c("epic-terminal-pr-merged-tree-mismatch",!1,!0):{ok:!0,mergeSha:e.expectedPullRequestHeadSha,pushedSha:u,providerGuard:f}}catch(i){return c("epic-terminal-pr-merge-denied",!0,ee(i))}},async verifyTerminalReceipt(e,i,n){try{if(i.physicalStatus!=="pushed"||!i.pushedSha||!i.mergeSha)return c("epic-terminal-physical-revalidation-required",!0,!1);const d=await P(r,h,!0),o=d.epics?.[e.epicId];if(!o||_(o.execution_branch)!==e.executionBranch||_(o.origin_branch)!==e.originBranch||_(o.graph_revision)!==e.graphRevision)return c("epic-terminal-state-revalidation-drift",!0,!1);const l=await a("rev-parse",`refs/heads/${e.executionBranch}`);if(l!==e.expectedExecutionHeadSha||i.executionHeadSha!==l)return c("epic-terminal-execution-revalidation-drift",!0,!1);const f=ne(o.origin_binding)?o.origin_binding:null;if(!f||f.originBranch!==e.originBranch||f.executionBranch!==e.executionBranch||!await W(a,f.originHeadSha)||!await x(a,f.originHeadSha,l))return c("epic-origin-binding-revalidation-drift",!0,!1);const p=await Q(r,d,o,e.epicId,e.executionBranch);if(z(o.branch_lease)||!X(p,e.storyCheckpointIds))return c("epic-checkpoint-set-revalidation-drift",!0,!1);const u=S(o.aggregate_qa_receipt)?o.aggregate_qa_receipt:null;if(!U(u,l,e.graphRevision,n)||u?.receiptRef!==e.localGates.aggregateQaReceipt.receiptRef)return c("epic-terminal-aggregate-qa-revalidation-drift",!0,!1);const g=await k(a,e.originBranch);if(await D(a,e.originBranch,g),!await x(a,l,g)||!await x(a,i.mergeSha,g)||!await x(a,i.pushedSha,g))return c("epic-terminal-physical-ancestry-unproven",!0,!1);const m={originHeadSha:i.baseSha,executionHeadSha:l,mergeSha:i.mergeSha,graphRevision:e.graphRevision};let b=y.get(i.mergeSha),w=G(b,m);if(!w){const R=await ce(r,m,n);b=R.candidateAuthority,w=R.candidateQa,y.set(i.mergeSha,b)}if(i.candidateQa&&(i.candidateQa.originHeadSha!==w.originHeadSha||i.candidateQa.executionHeadSha!==w.executionHeadSha||i.candidateQa.graphRevision!==w.graphRevision||i.candidateQa.treeSha!==w.treeSha))return c("epic-merge-candidate-receipt-drift",!0,!1);let B=i.providerGuard;if(i.strategy==="single_pr"){if(!i.prNumber)return c("epic-terminal-pr-merge-unverified",!0,!1);if(await a("rev-parse",`${i.pushedSha}^{tree}`)!==w.treeSha)return c("epic-terminal-pr-merged-tree-mismatch",!1,!1);if(B&&!Ce(B,i))return c("epic-terminal-pr-base-guard-unverifiable",!1,!1);B??={schemaVersion:1,provider:"github",mode:"recovered_exact_tree",source:"physical_recovery",prHeadSha:i.mergeSha,originHeadSha:i.baseSha,checkedAt:n,publicSafe:!0}}else if(B)return c("epic-terminal-pr-base-guard-unverifiable",!1,!1);return{ok:!0,candidateQa:w,candidateAuthority:b,...B?{providerGuard:B}:{}}}catch{return c("epic-terminal-physical-revalidation-failed",!0,!1)}},async applyReconciliation(e,i,n){if(i.action==="preserve")return c("git-reconciliation-preserve-not-actionable",!1,!1);if(n)return{ok:!0,outcome:"dry_run"};if(i.action==="no_op")return{ok:!0,outcome:"already_absent"};if(i.action==="delete_remote_branch")return Ie(e,i,a,s);try{const d=await V({candidate:e,decision:i,git:a,gh:s});if(!d.ok)return c(d.reasonCode,!0,!1);if(d.alreadyAbsent)return{ok:!0,outcome:"already_absent"};if(i.action==="delete_local_branch")await a("update-ref","-d",`refs/heads/${e.branchName}`,e.headSha);else if(i.action==="close_pull_request"){if(!e.prNumber)return c("git-reconciliation-pr-number-missing",!1,!1);const o=await C(a,s);if(!o)return c("git-resource-provider-repository-unverified",!0,!0);const l=`https://github.com/${o.nameWithOwner}`,f=`neocortex-reconciliation:${q("sha256").update(e.resourceId).digest("hex")}`,p=JSON.parse(await s("pr","view",String(e.prNumber),"--repo",l,"--json","comments"));if(!S(p)||!Array.isArray(p.comments)||p.comments.length>1e3||p.comments.some(m=>!S(m)||typeof m.body!="string"))return c("git-reconciliation-pr-comments-unverified",!0,!0);p.comments.some(m=>String(m.body).includes(f))||await s("pr","comment",String(e.prNumber),"--repo",l,"--body",`Neocortex reconciliation verified managed ownership and integrated content; requesting closure. [${f}]`);const u=await V({candidate:e,decision:i,git:a,gh:s});if(!u.ok)return c(u.reasonCode,!0,!1);if(u.alreadyAbsent)return{ok:!0,outcome:"already_absent"};await s("pr","close",String(e.prNumber),"--repo",l);const g=await V({candidate:e,decision:i,git:a,gh:s});if(!g.ok)return c(g.reasonCode,!0,!1);if(!g.alreadyAbsent)return c("git-reconciliation-pr-close-unverified",!0,!0)}return{ok:!0,outcome:"applied"}}catch{return c("git-reconciliation-effect-failed",!0,!1)}},async persist(e){try{let i;return await de(r,n=>{const d=se(n,e.terminalReceipt.epicId),o=Array.isArray(d.git_reconciliation_receipts)?d.git_reconciliation_receipts.filter(S):[],l=new Map(o.map(u=>[u.idempotencyKey,u]));for(const u of e.reconciliationReceipts)K(l.get(u.idempotencyKey))||l.set(u.idempotencyKey,u);const f=S(d.terminal_git_receipt)?d.terminal_git_receipt:null,p=_e(f,e.terminalReceipt);if(p.kind==="blocked"){i=p.reasonCode;return}d.terminal_git_receipt=p.receipt,d.git_reconciliation_receipts=[...l.values()],d.physicalMergeStatus=e.terminalReceipt.physicalStatus==="pushed"?"merged":e.terminalReceipt.physicalStatus,d.pr_number=e.terminalReceipt.prNumber??d.pr_number??null,d.git_reconciliation_debt=ye(d.git_reconciliation_debt,e.preservedDecisions)}),i?c(i,!1,!1):{ok:!0}}catch{return c("epic-terminal-state-persist-failed",!0,!1)}},async persistReconciliation(e){try{return await de(r,i=>{const n=se(i,e.epicId),d=Array.isArray(n.git_reconciliation_receipts)?n.git_reconciliation_receipts.filter(S):[],o=new Map(d.map(l=>[l.idempotencyKey,l]));for(const l of e.reconciliationReceipts)K(o.get(l.idempotencyKey))||o.set(l.idempotencyKey,l);n.git_reconciliation_receipts=[...o.values()],n.git_reconciliation_debt=ye(n.git_reconciliation_debt,e.preservedDecisions)}),{ok:!0}}catch{return c("git-reconciliation-state-persist-failed",!0,!1)}}}}async function C(r,t){try{const h=await r("remote","get-url","origin"),a=h.match(/^https:\/\/github\.com\/([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+?)(?:\.git)?\/?$/)?.[1]??h.match(/^git@github\.com:([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+?)(?:\.git)?$/)?.[1];if(!a)return null;const s=JSON.parse(await t("repo","view",`https://github.com/${a}`,"--json","id,nameWithOwner,url"));return s.nameWithOwner!==a||s.url!==`https://github.com/${a}`||typeof s.id!="string"||!/^[A-Za-z0-9_=-]{1,256}$/.test(s.id)?null:{id:s.id,nameWithOwner:a}}catch{return null}}async function Ie(r,t,h,a){try{if(r.kind!=="remote_branch"||t.resourceId!==r.resourceId||!r.baseBranch||r.baseBranch===r.branchName||!N(r.branchName)||!N(r.baseBranch)||!/^[a-f0-9]{40}$/.test(r.headSha)||!/^[a-f0-9]{40}$/.test(r.integrationHeadSha))return c("git-reconciliation-candidate-no-longer-safe",!1,!1);const s=await C(h,a);if(!s)return c("git-resource-remote-delete-cas-unavailable",!1,!1);if(!await $(h,r.branchName))return{ok:!0,outcome:"already_absent"};const e=await V({candidate:r,decision:t,git:h,gh:a});if(!e.ok)return c(e.reasonCode,!0,!1);if((await C(h,a))?.id!==s.id)return c("git-resource-provider-repository-raced",!0,!1);const n=q("sha256").update(["managed-remote-delete-v1",s.id,r.branchName,r.headSha,r.baseBranch,r.integrationHeadSha].join("\0")).digest("hex"),d=(f,p,u)=>`{name:${JSON.stringify(`refs/heads/${f}`)},beforeOid:${JSON.stringify(p)},afterOid:${JSON.stringify(u)},force:false}`,o=`mutation{updateRefs(input:{repositoryId:${JSON.stringify(s.id)},clientMutationId:${JSON.stringify(n)},refUpdates:[`+d(r.branchName,r.headSha,"0".repeat(40))+","+d(r.baseBranch,r.integrationHeadSha,r.integrationHeadSha)+"]}){clientMutationId}}",l=JSON.parse(await a("api","graphql","--hostname","github.com","-f",`query=${o}`));return l.errors||l.data?.updateRefs?.clientMutationId!==n?c("git-resource-remote-delete-cas-unverified",!0,!0):await $(h,r.branchName)?c("git-resource-remote-delete-recreated-or-unverified",!0,!1):{ok:!0,outcome:"applied"}}catch{return c("git-resource-remote-delete-cas-rejected",!0,!0)}}async function V(r){const{candidate:t,decision:h,git:a,gh:s}=r;if(!h.managed||!t.providerVerified||t.current||t.origin||t.protected||t.lifecycle==="active"||t.hasExclusiveCommits||t.worktreeActive)return{ok:!1,reasonCode:"git-reconciliation-candidate-no-longer-safe"};const y=await a("symbolic-ref","--quiet","--short","HEAD").catch(()=>""),e=await me(a);if(y===t.branchName||e.has(t.branchName))return{ok:!1,reasonCode:"git-resource-worktree-active"};if(t.kind==="local_branch"){const o=await Be(a,`refs/heads/${t.branchName}`);return o?o!==t.headSha?{ok:!1,reasonCode:"git-resource-expected-oid-raced"}:!t.baseBranch||await k(a,t.baseBranch)!==t.integrationHeadSha||!await x(a,o,t.integrationHeadSha)?{ok:!1,reasonCode:"git-resource-integration-unproven"}:{ok:!0}:{ok:!0,alreadyAbsent:!0}}if(t.kind==="remote_branch"){const o=await $(a,t.branchName);if(!o)return{ok:!0};if(o!==t.headSha)return{ok:!1,reasonCode:"git-resource-expected-oid-raced"};const l=await C(a,s);return l?await j(s,l.nameWithOwner,t.branchName)!=="unprotected"?{ok:!1,reasonCode:"git-resource-protected"}:!t.baseBranch||await k(a,t.baseBranch)!==t.integrationHeadSha?{ok:!1,reasonCode:"git-resource-integration-unproven"}:(await a("fetch","--quiet","--no-tags","origin",`refs/heads/${t.branchName}`),await a("rev-parse","FETCH_HEAD")!==t.headSha||!await x(a,t.headSha,t.integrationHeadSha)?{ok:!1,reasonCode:"git-resource-integration-unproven"}:{ok:!0}):{ok:!1,reasonCode:"git-resource-provider-repository-unverified"}}if(!t.prNumber||!t.baseBranch)return{ok:!1,reasonCode:"git-reconciliation-pr-proof-missing"};const i=await C(a,s);if(!i)return{ok:!1,reasonCode:"git-resource-provider-repository-unverified"};const n=await L(s,i.nameWithOwner,t.prNumber);if(!n||n.headRefName!==t.branchName||n.baseRefName!==t.baseBranch||n.headRefOid!==t.headSha)return{ok:!1,reasonCode:"git-resource-expected-oid-raced"};if(n.state==="CLOSED"||n.state==="MERGED")return{ok:!0,alreadyAbsent:!0};if(await j(s,i.nameWithOwner,t.branchName)!=="unprotected")return{ok:!1,reasonCode:"git-resource-protected"};const d=await $(a,t.branchName);return!n||n.state!=="OPEN"||n.headRefName!==t.branchName||n.baseRefName!==t.baseBranch||n.headRefOid!==t.headSha||d!==t.headSha?{ok:!1,reasonCode:"git-resource-expected-oid-raced"}:(await a("fetch","--quiet","--no-tags","origin",`refs/heads/${t.branchName}`),await a("rev-parse","FETCH_HEAD")!==t.headSha||await k(a,t.baseBranch)!==t.integrationHeadSha||!await x(a,t.headSha,t.integrationHeadSha)?{ok:!1,reasonCode:"git-resource-integration-unproven"}:{ok:!0})}async function ue(r){const t=[],h=await A("git-reconciliation-worktree-inventory-unavailable",()=>me(r.git)),a=ve(r.state),s=await C(r.git,r.gh),y=g=>{const m=g.split(`
|
|
2
|
+
`).filter(Boolean).map(w=>w.split(/\s+/));if(m.length>F)throw new Error("git-reconciliation-ref-inventory-limit");const b=new Map;for(const[w,B]of m){const R=B?.replace(/^refs\/heads\//,"");if(!R||!N(R)||!/^[a-f0-9]{40,64}$/.test(w??"")||b.has(R))throw new Error("git-reconciliation-ref-inventory-invalid");b.set(R,w)}return b},e=y(await A("git-reconciliation-local-ref-inventory-unavailable",()=>r.git("for-each-ref",`--count=${F+1}`,"--format=%(objectname) %(refname)","refs/heads"))),i=y(await A("git-reconciliation-remote-ref-inventory-unavailable",()=>r.git("ls-remote","--heads","origin")));if(i.get(r.directive.originBranch)!==r.originHeadSha)throw new Error("git-reconciliation-origin-head-raced");const n=new Set([...a.claims.keys()].filter(N)),d=s?await Ne(r.gh,s.nameWithOwner,n):[],o=new Map([[r.directive.originBranch,r.originHeadSha]]),l=async g=>{if(o.has(g))return o.get(g);const m=i.get(g);return m?(await Y(r.git,m,"git-reconciliation-base-fetch-failed"),o.set(g,m),m):""},f=new Map,p=async(g,m)=>{const b=`${g}:${m}`;return f.has(b)||f.set(b,!!(g&&m)&&await x(r.git,g,m)),f.get(b)},u=new Set([...e.keys(),...i.keys(),...a.claims.keys()]);if(u.size>F)throw new Error("git-reconciliation-ref-inventory-limit");for(const g of[...u].sort()){if(!N(g))continue;const m=a.claims.get(g)??[],b=new Set(m.map(v=>`${v.epicId}:${v.origin}`)),w=b.size===1?m[0].origin:r.directive.originBranch,B=b.size===1,R=await l(w),T=m.length===0||m.some(v=>v.active),re=e.get(g),O=i.get(g);B&&O&&await Y(r.git,O,"git-reconciliation-managed-ref-fetch-failed");const J=B&&s&&O?await j(r.gh,s.nameWithOwner,g):"unknown",ae=async v=>{if(!B)return[];const I=new Set;for(const E of m)for(const H of E.proofs)H.head===v&&(H.mergeSha&&(!H.pushedSha||!await p(v,H.mergeSha)||!await p(H.mergeSha,H.pushedSha)||!await p(H.pushedSha,R))||H.evidence.forEach(M=>I.add(M)));return[...I]},te={schemaVersion:1,branchName:g,baseBranch:w,integrationHeadSha:R,lifecycle:T?"active":"integrated",current:g===r.currentBranch,origin:a.origins.has(g)||g===r.directive.originBranch,worktreeActive:h.has(g),contentEquivalent:!1,publicSafe:!0};for(const[v,I]of[["local_branch",re],["remote_branch",O]]){if(!I)continue;const E=`${v}:${q("sha256").update(g).digest("hex")}:${I}`,H=B&&await p(I,R);t.push({...te,resourceId:E,kind:v,headSha:I,ownershipEvidence:await ae(I),protected:!!O&&J!=="unprotected",providerVerified:v==="local_branch"?!0:!!s&&J!=="unknown",...v==="remote_branch"&&s?{remoteDeletionCas:"github-update-refs-v1"}:{},commitsReachable:H,hasExclusiveCommits:!H,previouslyReconciled:r.receiptIds.has(E)})}for(const v of d.filter(I=>I.headRefName===g)){const I=v.baseRefName===w&&v.sameRepository,E=await ae(v.headRefOid);I&&E.includes("managed_metadata")&&E.push("pr_head_base_match");const H=`pr:${v.number}:${v.headRefOid}:${q("sha256").update(v.baseRefName).digest("hex")}`,M=await p(v.headRefOid,R);t.push({...te,resourceId:H,kind:"pull_request",prNumber:v.number,headSha:v.headRefOid,lifecycle:v.state!=="OPEN"?"already_absent":T?"active":"superseded",ownershipEvidence:E,providerVerified:I,protected:J!=="unprotected",commitsReachable:M,hasExclusiveCommits:!M,previouslyReconciled:r.receiptIds.has(H)})}}return ke(r.epic,t),t}function ke(r,t){const h=new Set((Array.isArray(r.git_reconciliation_receipts)?r.git_reconciliation_receipts:[]).filter(S).map(y=>_(y.idempotencyKey))),a=new Set((Array.isArray(r.git_reconciliation_debt)?r.git_reconciliation_debt:[]).filter(S).map(y=>_(y.resourceId))),s=new Set(t.filter(y=>y.kind==="pull_request"&&ie(y).action==="close_pull_request").map(y=>y.branchName));for(const y of t){const e=ie(y);e.action==="preserve"?a.add(y.resourceId):(h.add(`reconciliation:v2:${q("sha256").update([y.resourceId,e.action].join("\0")).digest("hex")}`),y.kind!=="pull_request"&&s.has(y.branchName)&&a.add(y.resourceId))}if(h.size>1024)throw new Error("git-reconciliation-receipt-capacity");if(a.size>1024)throw new Error("git-reconciliation-debt-capacity")}function ge(r){const t=new Set(["git-reconciliation-state-unavailable","git-reconciliation-origin-query-failed","git-reconciliation-origin-fetch-failed","git-reconciliation-origin-head-raced","git-reconciliation-worktree-inventory-unavailable","git-reconciliation-local-ref-inventory-unavailable","git-reconciliation-remote-ref-inventory-unavailable","git-reconciliation-base-fetch-failed","git-reconciliation-managed-ref-fetch-failed","git-reconciliation-pr-inventory-unavailable","git-reconciliation-state-inventory-limit","git-reconciliation-ref-inventory-limit","git-reconciliation-ref-inventory-invalid","git-reconciliation-pr-inventory-limit","git-reconciliation-pr-inventory-invalid","git-reconciliation-receipt-capacity","git-reconciliation-debt-capacity"]);return r instanceof Error&&t.has(r.message)?r.message:void 0}async function A(r,t){try{return await t()}catch{throw new Error(r)}}async function Y(r,t,h){if(!await W(r,t)&&(await A(h,()=>r("fetch","--quiet","--no-tags","--no-write-fetch-head","--refmap=","origin",t)),!await W(r,t)))throw new Error(h)}async function Ne(r,t,h){const a=t.split("/")[0];if(!a||!/^[A-Za-z0-9_.-]+$/.test(a))throw new Error("git-reconciliation-pr-inventory-invalid");const s=[],y=new Set,e=100,i=Math.floor(oe/e)+1;for(const n of[...h].sort()){if(!N(n))throw new Error("git-reconciliation-pr-inventory-invalid");const d=encodeURIComponent(`${a}:${n}`);for(let o=1;o<=i;o+=1){const l=`repos/${t}/pulls?state=all&head=${d}&per_page=${e}&page=${o}`,f=await A("git-reconciliation-pr-inventory-unavailable",()=>r("api",l,"--hostname","github.com"));let p;try{p=JSON.parse(f)}catch{throw new Error("git-reconciliation-pr-inventory-invalid")}if(!Array.isArray(p)||p.length>e)throw new Error("git-reconciliation-pr-inventory-limit");for(const u of p){if(!S(u)||!Number.isSafeInteger(u.number)||Number(u.number)<=0||y.has(Number(u.number))||!S(u.head)||!S(u.base)||_(u.head.ref)!==n||!N(_(u.head.ref))||!N(_(u.base.ref))||!/^[a-f0-9]{40,64}$/.test(_(u.head.sha))||!["open","closed"].includes(_(u.state)))throw new Error("git-reconciliation-pr-inventory-invalid");if(y.add(Number(u.number)),s.push({number:Number(u.number),state:_(u.state).toUpperCase(),headRefName:_(u.head.ref),headRefOid:_(u.head.sha),baseRefName:_(u.base.ref),sameRepository:S(u.head.repo)&&S(u.base.repo)&&u.head.repo.full_name===t&&u.base.repo.full_name===t}),s.length>oe)throw new Error("git-reconciliation-pr-inventory-limit")}if(p.length<e)break}}return s}function K(r){return S(r)&&(r.outcome==="applied"||r.outcome==="already_absent")}async function Oe(r){try{const t=(await r.git("log",r.originHeadSha,"--format=%H","--fixed-strings",`--grep=Neocortex-Idempotency: ${r.directive.idempotencyKey}`)).split(`
|
|
3
|
+
`).filter(d=>/^[a-f0-9]{40,64}$/i.test(d));if(t.length!==1)return null;const h=t[0],a=(await r.git("rev-list","--parents","-n","1",h)).split(/\s+/),s=await r.git("show","-s","--format=%B",h),[y]=s.split(`
|
|
4
|
+
`),e=`merge(${r.directive.epicId}): integrate ${r.directive.executionBranch} into ${r.directive.originBranch}`;if(a.length!==3||a[2]!==r.executionHeadSha||y!==e)return null;const i=new Set(s.split(`
|
|
5
|
+
`).map(d=>d.trim()));for(const d of[`Neocortex-Epic: ${r.directive.epicId}`,`Neocortex-Origin-Branch: ${r.directive.originBranch}`,`Neocortex-Execution-Branch: ${r.directive.executionBranch}`,`Neocortex-Execution-Head: ${r.executionHeadSha}`,`Neocortex-Origin-Base: ${a[1]}`,`Neocortex-Graph-Revision: ${r.directive.graphRevision}`,`Neocortex-Aggregate-QA: ${r.directive.localGates.aggregateQaReceipt.receiptRef}`,`Neocortex-Idempotency: ${r.directive.idempotencyKey}`])if(!i.has(d))return null;const n=await r.git("show","-s","--format=%cI",h);return{schemaVersion:1,epicId:r.directive.epicId,executionBranch:r.directive.executionBranch,originBranch:r.directive.originBranch,baseSha:a[1],executionHeadSha:r.executionHeadSha,mergeSha:h,pushedSha:h,strategy:"direct",physicalStatus:"pushed",localGateReceiptRefs:r.directive.localGates.receiptRefs,idempotencyKey:r.directive.idempotencyKey,attemptStartedAt:n,completedAt:n,retryEligible:!1,reasonCodes:["epic-terminal-recovered-physical-push"],publicSafe:!0}}catch{return null}}async function j(r,t,h){try{if(!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(t))return"unknown";const a=await r("api",`repos/${t}/branches/${encodeURIComponent(h)}`,"--hostname","github.com","--jq",".protected");return a==="false"?"unprotected":a==="true"?"protected":"unknown"}catch{return"unknown"}}async function L(r,t,h){try{const a=JSON.parse(await r("pr","view",String(h),"--repo",`https://github.com/${t}`,"--json","state,headRefName,headRefOid,baseRefName,mergeCommit"));return[a.state,a.headRefName,a.headRefOid,a.baseRefName].every(s=>typeof s=="string")?a:null}catch{return null}}async function Ee(r,t,h,a,s,y){if(!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(t)||!N(h)||!/^[a-f0-9]{40,64}$/i.test(a)||!/^[a-f0-9]{40,64}$/i.test(s)||Number.isNaN(Date.parse(y)))return{ok:!1,reasonCode:"epic-terminal-pr-base-guard-unverifiable"};let e;try{const o=JSON.parse(await r("api",`repos/${t}/rules/branches/${encodeURIComponent(h)}`,"--hostname","github.com","--paginate","--slurp")),l=Array.isArray(o)&&o.every(Array.isArray)?o.flat():o;if(!Array.isArray(l)||l.length>256||l.some(f=>!S(f)))return{ok:!1,reasonCode:"epic-terminal-pr-base-guard-unverifiable"};e=l}catch{return{ok:!1,reasonCode:"epic-terminal-pr-base-guard-unverifiable"}}if(e.some(o=>o.type==="merge_queue"))return{ok:!1,reasonCode:"epic-terminal-pr-merge-queue-local-gate-required"};const i=e.some(o=>o.type==="required_status_checks"&&S(o.parameters)&&o.parameters.strict_required_status_checks_policy===!0);let n=!1;try{const o=JSON.parse(await r("api",`repos/${t}/branches/${encodeURIComponent(h)}/protection/required_status_checks`,"--hostname","github.com"));if(!S(o)||typeof o.strict!="boolean")return{ok:!1,reasonCode:"epic-terminal-pr-base-guard-unverifiable"};n=o.strict}catch(o){if(!$e(o))return{ok:!1,reasonCode:"epic-terminal-pr-base-guard-unverifiable"}}return!i&&!n?{ok:!1,reasonCode:"epic-terminal-pr-strict-base-guard-required"}:{ok:!0,receipt:{schemaVersion:1,provider:"github",mode:"strict_up_to_date_expected_head",source:i&&n?"branch_protection_and_ruleset":i?"ruleset":"branch_protection",prHeadSha:a,originHeadSha:s,checkedAt:y,publicSafe:!0}}}function $e(r){return r instanceof Error&&/(?:HTTP\s*)?404\b|not found/i.test(r.message)}function Ce(r,t){const h=r.mode==="recovered_exact_tree"?r.source==="physical_recovery":r.mode==="strict_up_to_date_expected_head"&&["branch_protection","ruleset","branch_protection_and_ruleset"].includes(r.source);return r.schemaVersion===1&&r.provider==="github"&&h&&r.publicSafe===!0&&!Number.isNaN(Date.parse(r.checkedAt))&&r.prHeadSha===t.mergeSha&&r.originHeadSha===t.baseSha}async function fe(r,t,h){const a=r==="git"&&Pe(t);return(await He(r,[...t],{cwd:h,encoding:"utf8",maxBuffer:16*1024*1024,...a?Te(process.env):{}})).stdout.trim()}const Ae=6e4,qe="ssh -o BatchMode=yes -o ConnectTimeout=15 -o ServerAliveInterval=15 -o ServerAliveCountMax=2";function Pe(r){return r[0]==="ls-remote"||r[0]==="fetch"}function Te(r){return{timeout:Ae,killSignal:"SIGKILL",env:{...r,GIT_TERMINAL_PROMPT:"0",GCM_INTERACTIVE:"never",GIT_HTTP_LOW_SPEED_LIMIT:"1000",GIT_HTTP_LOW_SPEED_TIME:"30",...r.GIT_SSH_COMMAND?{}:{GIT_SSH_COMMAND:qe}}}}async function pe(r){const t=await P(r.projectRoot,r.statePath,!0),h=t.epics?.[r.epicId];if(!h||h.execution_branch!==r.executionBranch||h.origin_branch!==r.originBranch||h.graph_revision!==r.graphRevision||z(h.branch_lease)||await r.git("rev-parse",`refs/heads/${r.executionBranch}`)!==r.executionHeadSha)return!1;const a=await Q(r.projectRoot,t,h,r.epicId,r.executionBranch);if(!he(a,r.storyCheckpointIds)||!he(a,le(h)))return!1;const s=S(h.aggregate_qa_receipt)?h.aggregate_qa_receipt:null;if(!U(s,r.executionHeadSha,r.graphRevision,r.nowIso)||s.receiptRef!==r.aggregateQaReceipt.receiptRef)return!1;const y=await xe(r.git,t,h,r.executionHeadSha),e=t.stories?.[y.at(-1)??""]?.checkpoint;return(S(e)?_(e.headSha):"")===r.executionHeadSha?!0:Z({projectRoot:r.projectRoot,git:r.git,state:t,epic:h,epicId:r.epicId,executionBranch:r.executionBranch,originBranch:r.originBranch,executionHeadSha:r.executionHeadSha,graphRevision:r.graphRevision,aggregateQaReceipt:s,nowIso:r.nowIso})}async function k(r,t){const h=await $(r,t);if(!h)throw new Error("origin-ref-missing");return h}async function me(r){const t=new Set,h=await r("worktree","list","--porcelain");for(const a of h.split(`
|
|
6
|
+
`))a.startsWith("branch refs/heads/")&&t.add(a.slice(18));return t}function X(r,t){return r.length===t.length&&[...r].sort().every((h,a)=>h===[...t].sort()[a])}function z(r){return S(r)&&typeof r.expiresAt=="string"&&r.expiresAt>new Date().toISOString()}function ee(r){const t=r instanceof Error?r.message:"";return/protected branch|branch protection|required pull request|GH006|GH013|ruleset|review required/i.test(t)}function ye(r,t){const h=Array.isArray(r)?r.filter(S):[],a=new Map(h.map(s=>[_(s.resourceId),s]));for(const s of t)a.set(s.resourceId,s);return[...a.values()]}export{Ae as GIT_NETWORK_TIMEOUT_MS,Je as createCliEpicTerminalGitAdapter,Te as gitNetworkExecOptions,Pe as isGitNetworkCommand,Ue as physicallyValidHeadReconciliation,Ye as publicLifecycleEvidenceCause};
|