@ornexus/neocortex 4.60.66 → 4.60.68

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1598 -1640
  3. package/install.ps1 +1 -1
  4. package/install.sh +2 -1
  5. package/package.json +10 -7
  6. package/packages/client/dist/adapters/adapter-registry.js +108 -1
  7. package/packages/client/dist/adapters/antigravity-adapter.js +77 -2
  8. package/packages/client/dist/adapters/claude-code-adapter.js +79 -3
  9. package/packages/client/dist/adapters/codex-adapter.js +80 -2
  10. package/packages/client/dist/adapters/cursor-adapter.js +115 -4
  11. package/packages/client/dist/adapters/gemini-adapter.js +71 -2
  12. package/packages/client/dist/adapters/grok-adapter.js +42 -2
  13. package/packages/client/dist/adapters/index.js +22 -1
  14. package/packages/client/dist/adapters/platform-detector.js +212 -1
  15. package/packages/client/dist/adapters/target-adapter.js +12 -0
  16. package/packages/client/dist/adapters/vscode-adapter.js +72 -2
  17. package/packages/client/dist/agent/refresh-stubs.js +417 -2
  18. package/packages/client/dist/agent/update-agent-yaml.js +102 -1
  19. package/packages/client/dist/agent/update-description.js +251 -1
  20. package/packages/client/dist/cache/crypto-utils.js +78 -1
  21. package/packages/client/dist/cache/encrypted-cache.js +108 -1
  22. package/packages/client/dist/cache/in-memory-asset-cache.js +73 -1
  23. package/packages/client/dist/cache/index.js +13 -1
  24. package/packages/client/dist/cache/protected-pi-boundary.js +44 -1
  25. package/packages/client/dist/checkpoint/checkpoint-client-reader.js +127 -2
  26. package/packages/client/dist/checkpoint/index.js +11 -1
  27. package/packages/client/dist/checkpoint/shared-checkpoint-types.js +32 -1
  28. package/packages/client/dist/cli.js +303 -3
  29. package/packages/client/dist/commands/activate.js +394 -8
  30. package/packages/client/dist/commands/architecture-answers.js +274 -7
  31. package/packages/client/dist/commands/architecture-memory-terminal.js +253 -4
  32. package/packages/client/dist/commands/architecture-non-ui-continuation.js +100 -1
  33. package/packages/client/dist/commands/architecture-root-binding.js +51 -1
  34. package/packages/client/dist/commands/cache-status.js +112 -2
  35. package/packages/client/dist/commands/config.js +88 -1
  36. package/packages/client/dist/commands/doctor.d.ts +135 -0
  37. package/packages/client/dist/commands/doctor.js +635 -0
  38. package/packages/client/dist/commands/invoke.d.ts +18 -0
  39. package/packages/client/dist/commands/invoke.js +7140 -142
  40. package/packages/client/dist/commands/legacy-epic-terminal.js +71 -1
  41. package/packages/client/dist/commands/legacy-story-branch.js +96 -1
  42. package/packages/client/dist/commands/legacy-story-pr.js +276 -1
  43. package/packages/client/dist/commands/mutation-qa-checkpoint.js +285 -5
  44. package/packages/client/dist/commands/mutation-qa-gate.js +54 -1
  45. package/packages/client/dist/commands/mutation-qa-git.js +41 -1
  46. package/packages/client/dist/commands/mutation-qa-policy.js +102 -1
  47. package/packages/client/dist/commands/mutation-qa-run.js +219 -3
  48. package/packages/client/dist/commands/mutation-qa-verdict.js +149 -1
  49. package/packages/client/dist/commands/mutation-qa.js +220 -1
  50. package/packages/client/dist/commands/native-agent.js +136 -2
  51. package/packages/client/dist/commands/planning-diagnosis.js +43 -1
  52. package/packages/client/dist/commands/planning-generation.js +53 -1
  53. package/packages/client/dist/commands/planning-memory.js +40 -1
  54. package/packages/client/dist/commands/planning-research.js +42 -1
  55. package/packages/client/dist/commands/private-session.js +75 -1
  56. package/packages/client/dist/commands/property-qa.js +139 -1
  57. package/packages/client/dist/commands/qa-control.js +16 -1
  58. package/packages/client/dist/commands/qa-scan-browser-launch.js +55 -1
  59. package/packages/client/dist/commands/qa-scan-browser-route.js +28 -1
  60. package/packages/client/dist/commands/qa-scan-capture.js +663 -5
  61. package/packages/client/dist/commands/qa-scan-discovery.js +376 -3
  62. package/packages/client/dist/commands/qa-scan-review.js +826 -5
  63. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +266 -1
  64. package/packages/client/dist/commands/qa-synthetic-backend-review.js +297 -1
  65. package/packages/client/dist/commands/qa-synthetic-backend.js +340 -2
  66. package/packages/client/dist/commands/qa-synthetic-broker-port.js +85 -1
  67. package/packages/client/dist/commands/qa-synthetic-browser.js +39 -1
  68. package/packages/client/dist/commands/refactor-characterization.js +671 -21
  69. package/packages/client/dist/commands/refactor-commit.js +399 -13
  70. package/packages/client/dist/commands/refactor-control.js +142 -3
  71. package/packages/client/dist/commands/refactor-cpp-assertions.js +93 -3
  72. package/packages/client/dist/commands/refactor-review.js +283 -5
  73. package/packages/client/dist/commands/refactor-root.js +588 -7
  74. package/packages/client/dist/commands/refresh-memory.js +156 -3
  75. package/packages/client/dist/commands/shared-architecture-non-ui.js +24 -1
  76. package/packages/client/dist/commands/story-checkpoint.js +171 -1
  77. package/packages/client/dist/config/profile-directory.js +13 -1
  78. package/packages/client/dist/config/resolver-selection.js +278 -1
  79. package/packages/client/dist/config/secure-config.js +281 -12
  80. package/packages/client/dist/config.js +223 -2
  81. package/packages/client/dist/constants.js +25 -1
  82. package/packages/client/dist/context/context-collector.js +222 -2
  83. package/packages/client/dist/context/context-sanitizer.js +145 -1
  84. package/packages/client/dist/continuity/autonomous-governance.js +285 -1
  85. package/packages/client/dist/continuity/continuity-client-state-store.js +1587 -1
  86. package/packages/client/dist/continuity/invoke-hooks.js +129 -1
  87. package/packages/client/dist/continuity/migrations/001-initial-schema.js +12 -2
  88. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +12 -2
  89. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +12 -2
  90. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +12 -2
  91. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +12 -2
  92. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +10 -2
  93. package/packages/client/dist/continuity/native-agent-store.js +69 -1
  94. package/packages/client/dist/continuity/native-agent-types.js +90 -1
  95. package/packages/client/dist/continuity/outbox.js +117 -1
  96. package/packages/client/dist/continuity/runner-bootstrap-policy.js +172 -1
  97. package/packages/client/dist/continuity/sqlite-store.js +2536 -81
  98. package/packages/client/dist/effects/invoke-effect-gateways.js +62 -1
  99. package/packages/client/dist/errors/error-messages.js +228 -2
  100. package/packages/client/dist/errors/frontmatter-diagnostics.js +125 -1
  101. package/packages/client/dist/evidence/collector.js +347 -1
  102. package/packages/client/dist/evidence/index.js +1 -1
  103. package/packages/client/dist/evidence/types.js +2 -0
  104. package/packages/client/dist/fs/atomic-state-replace.js +152 -1
  105. package/packages/client/dist/generated/command-registry.generated.js +4076 -1
  106. package/packages/client/dist/generated/public-projections.generated.js +149 -1
  107. package/packages/client/dist/git/direct-yolo-c01-retry.js +138 -4
  108. package/packages/client/dist/git/direct-yolo-checkpoint.js +1234 -4
  109. package/packages/client/dist/git/git-lifecycle-step-ids.js +14 -1
  110. package/packages/client/dist/git/git-lifecycle-store.js +1938 -9
  111. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +259 -9
  112. package/packages/client/dist/git/legacy-story-branch-setup.js +348 -4
  113. package/packages/client/dist/git/legacy-story-pr.js +3538 -70
  114. package/packages/client/dist/git/secure-filesystem-boundary.js +182 -5
  115. package/packages/client/dist/graph-retrieval/pre-command-hook.js +284 -1
  116. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +237 -1
  117. package/packages/client/dist/i18n/first-run.js +60 -2
  118. package/packages/client/dist/index.js +47 -1
  119. package/packages/client/dist/invocation/invoke-input.js +24 -1
  120. package/packages/client/dist/license/index.js +5 -1
  121. package/packages/client/dist/license/license-client.js +304 -1
  122. package/packages/client/dist/machine/fingerprint.js +163 -2
  123. package/packages/client/dist/machine/index.js +5 -1
  124. package/packages/client/dist/memory/project-memory-path-scope.js +62 -1
  125. package/packages/client/dist/memory/project-memory-writer.js +1007 -40
  126. package/packages/client/dist/memory/shared-project-memory-types.js +253 -2
  127. package/packages/client/dist/migrations/project-identity-capability.js +50 -1
  128. package/packages/client/dist/migrations/project-identity.js +493 -7
  129. package/packages/client/dist/migrations/state-json.js +344 -4
  130. package/packages/client/dist/policy/architecture-policy.js +184 -2
  131. package/packages/client/dist/policy/index.js +7 -1
  132. package/packages/client/dist/policy/shared-policy-types.js +38 -0
  133. package/packages/client/dist/policy/subagent-approval-policy.js +55 -1
  134. package/packages/client/dist/private-execution/clean-baseline.js +279 -2
  135. package/packages/client/dist/private-execution/codex-executor.js +574 -4
  136. package/packages/client/dist/private-execution/codex-host-runtime.js +137 -1
  137. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +97 -1
  138. package/packages/client/dist/private-execution/codex-scoped-permissions.js +128 -1
  139. package/packages/client/dist/private-execution/delivery.js +410 -13
  140. package/packages/client/dist/private-execution/diagnosis-root-review.js +294 -2
  141. package/packages/client/dist/private-execution/frozen-handoff.js +19 -6
  142. package/packages/client/dist/private-execution/implementation-validation.js +106 -2
  143. package/packages/client/dist/private-execution/isolated-admission.js +1432 -23
  144. package/packages/client/dist/private-execution/isolated-session.js +725 -5
  145. package/packages/client/dist/private-execution/isolated-workspace.js +122 -1
  146. package/packages/client/dist/private-execution/pact-consumer-runtime.js +409 -3
  147. package/packages/client/dist/private-execution/pact-test-source.js +258 -1
  148. package/packages/client/dist/private-execution/pact-toolchain.js +290 -3
  149. package/packages/client/dist/private-execution/pact-write-set.js +172 -1
  150. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +406 -5
  151. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +462 -5
  152. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +139 -3
  153. package/packages/client/dist/private-execution/planning-research-checkpoint.js +325 -4
  154. package/packages/client/dist/private-execution/private-report-store.js +42 -1
  155. package/packages/client/dist/private-execution/property-test-candidate.js +103 -1
  156. package/packages/client/dist/private-execution/property-test-choices.js +147 -3
  157. package/packages/client/dist/private-execution/property-test-plan.js +271 -7
  158. package/packages/client/dist/private-execution/property-test-review.js +258 -4
  159. package/packages/client/dist/private-execution/property-test-runtime.js +372 -9
  160. package/packages/client/dist/private-execution/property-test-source.js +139 -1
  161. package/packages/client/dist/private-execution/root-checkpoint.js +80 -1
  162. package/packages/client/dist/private-execution/root-memory-git-evidence.js +135 -3
  163. package/packages/client/dist/private-execution/root-memory-recovery.js +93 -1
  164. package/packages/client/dist/private-execution/root-memory-request.js +29 -1
  165. package/packages/client/dist/private-execution/root-memory-scope.js +178 -1
  166. package/packages/client/dist/private-execution/root-memory-writer.js +102 -1
  167. package/packages/client/dist/private-execution/session-lease.js +63 -1
  168. package/packages/client/dist/private-execution/shared-private-admission-types.js +50 -1
  169. package/packages/client/dist/private-execution/shared-project-validation.js +66 -1
  170. package/packages/client/dist/private-execution/shared-root-memory-types.js +61 -1
  171. package/packages/client/dist/private-execution/ux-source-validation.js +372 -1
  172. package/packages/client/dist/private-execution/ux-write-set.js +191 -2
  173. package/packages/client/dist/resilience/circuit-breaker.js +170 -1
  174. package/packages/client/dist/resilience/degradation-manager.js +164 -1
  175. package/packages/client/dist/resilience/freshness-indicator.js +100 -1
  176. package/packages/client/dist/resilience/index.js +8 -1
  177. package/packages/client/dist/resilience/recovery-detector.js +74 -1
  178. package/packages/client/dist/resolvers/asset-resolver.js +13 -0
  179. package/packages/client/dist/resolvers/local-resolver.js +255 -8
  180. package/packages/client/dist/resolvers/remote-resolver.js +233 -1
  181. package/packages/client/dist/runner/binary.js +404 -1
  182. package/packages/client/dist/runner/cli.js +1571 -17
  183. package/packages/client/dist/runner/headless/adapters.js +49 -1
  184. package/packages/client/dist/runner/headless/claude-code-adapter.js +79 -1
  185. package/packages/client/dist/runner/headless/continuous-story-workspace.js +1628 -11
  186. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +69 -1
  187. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +110 -2
  188. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +1236 -8
  189. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +318 -2
  190. package/packages/client/dist/runner/headless/fake-adapter.js +62 -1
  191. package/packages/client/dist/runner/headless/managed-profile.js +132 -1
  192. package/packages/client/dist/runner/headless/opencode-adapter.js +145 -2
  193. package/packages/client/dist/runner/headless/prepared-story-bundle.js +43 -1
  194. package/packages/client/dist/runner/headless/resolver.js +231 -1
  195. package/packages/client/dist/runner/headless/run-yolo.js +885 -1
  196. package/packages/client/dist/runner/headless/run-yoloop.d.ts +4 -1
  197. package/packages/client/dist/runner/headless/run-yoloop.js +2574 -2
  198. package/packages/client/dist/runner/headless/types.js +574 -2
  199. package/packages/client/dist/runner/local-console.js +396 -13
  200. package/packages/client/dist/runner/portal-sync-worker.js +1487 -1
  201. package/packages/client/dist/runner/project-identity.js +106 -1
  202. package/packages/client/dist/runner/scheduler.js +995 -7
  203. package/packages/client/dist/runner-cli.js +18 -2
  204. package/packages/client/dist/state/invocation-shape.js +13 -1
  205. package/packages/client/dist/state/project-state-snapshot.js +1677 -1
  206. package/packages/client/dist/state/state-json-repair.js +785 -3
  207. package/packages/client/dist/state/structural-dag-projection.js +118 -1
  208. package/packages/client/dist/telemetry/index.js +5 -1
  209. package/packages/client/dist/telemetry/offline-queue.js +131 -1
  210. package/packages/client/dist/tier/index.js +5 -1
  211. package/packages/client/dist/tier/tier-aware-client.js +405 -1
  212. package/packages/client/dist/types/index.js +38 -1
  213. package/packages/client/dist/version.js +27 -1
  214. package/packages/client/dist/yolo/change-evidence-collector.js +126 -1
  215. package/packages/client/dist/yolo/invoke-envelope-capability.js +62 -1
  216. package/packages/client/dist/yolo/spec-envelope-collector.js +185 -5
  217. package/packages/client/dist/yoloop/discovery-hook.js +300 -2
  218. package/packages/client/dist/yoloop/index.js +8 -1
  219. package/packages/client/dist/yoloop/invoke-hooks.js +669 -12
  220. package/packages/client/dist/yoloop/shared-discover-epics.js +1007 -1
  221. package/packages/client/dist/yoloop/shared-yoloop-types.js +33 -1
  222. package/packages/client/dist/yoloop/target-normalization.js +180 -1
  223. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1723 -1
  224. package/packages/shared/dist/compatibility/index.js +476 -0
  225. package/packages/shared/dist/yoloop/release-blocked.js +653 -0
  226. package/targets-stubs/antigravity/gemini.md +1 -1
  227. package/targets-stubs/antigravity/skill/SKILL.md +3 -2
  228. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  229. package/targets-stubs/claude-code/neocortex-root.md +5 -5
  230. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  231. package/targets-stubs/claude-code/neocortex.md +8 -9
  232. package/targets-stubs/codex/AGENTS.md +3 -3
  233. package/targets-stubs/cursor/agent.md +4 -3
  234. package/targets-stubs/gemini-cli/agent.md +5 -4
  235. package/targets-stubs/opencode/neocortex-root.md +3 -3
  236. package/targets-stubs/vscode/neocortex.agent.md +5 -4
@@ -1,8 +1,1236 @@
1
- import{execFile as ye}from"node:child_process";import{createHash as O}from"node:crypto";import{readFile as ae}from"node:fs/promises";import{join as we}from"node:path";import{promisify as be}from"node:util";import{classifyGitReconciliationCandidate as ie,reconcileTerminalReceipt as Se}from"../../../../shared/dist/yoloop/epic-terminal-git.js";import{collectGitResourceOwnership as _e,GIT_INVENTORY_PR_LIMIT as ne,GIT_INVENTORY_REF_LIMIT as Z}from"./epic-git-reconciliation-inventory.js";import{executeEpicMergeCandidateQa as oe,verifiedEpicMergeCandidateReceipt as W}from"./epic-merge-candidate-qa.js";import{applyGitLifecycleRuntimeOverlay as xe,ensureRuntimeEpic as z,executeP205TransientAuthority as ve,P205_COMPLETE_COMMAND as Q,projectP205TransientExecutionEvidence as Re,verifyAcceptedGitLifecycleStoryCheckpoint as ce,mutateGitLifecycleRuntime as J,readGitLifecycleRuntime as He}from"../../git/git-lifecycle-store.js";const ke=be(ye);function ze(e,a={}){const c=we(e,".neocortex","state.json"),t=a.gitRunner??((...r)=>ue("git",r,e)),u=a.providerRunner??((...r)=>ue("gh",r,e)),m=new Map;return{async prepareLifecycleEvidence(r){try{try{await ae(c,"utf8")}catch(k){if(Oe(k,"ENOENT"))return{ok:!0,originBindingCaptured:!1,aggregateQaRecorded:!1};throw k}const n=(await D(e,c)).epics?.[r.epicId];if(!n)return o("epic-state-missing",!1,!1);if(S(n.branch_mode)!=="epic")return{ok:!0,originBindingCaptured:!1,aggregateQaRecorded:!1};const s=S(n.execution_branch),d=S(n.origin_branch);if(!s||!E(s))return o("epic-execution-branch-missing",!1,!1);let l=await t("symbolic-ref","--quiet","--short","HEAD").catch(()=>""),f=await t("rev-parse","HEAD"),h=_(n.origin_binding)?n.origin_binding:null,b=!1;if(h){if(h.executionBranch!==s||h.originBranch!==d||l!==s&&l!==h.originBranch||!await j(t,h.originHeadSha)||!await v(t,h.originHeadSha,f))return o("epic-origin-binding-physical-drift",!1,!1)}else{if(!l||l===s||!E(l))return o("epic-origin-binding-capture-window-missed",!1,!1);if(d&&d!==l)return o("epic-origin-binding-recorded-origin-drift",!1,!1);h={schemaVersion:1,originBranch:l,originHeadSha:f,executionBranch:s,capturedFromCurrentCheckout:!0,capturedAt:r.nowIso},await J(e,k=>{const y=z(k,r.epicId);if(y.origin_binding&&JSON.stringify(y.origin_binding)!==JSON.stringify(h))throw new Error("origin-binding-cas-conflict");y.origin_branch=l,y.origin_binding=h}),b=!0}if(l!==s){const k=await le(t,`refs/heads/${s}`);try{if(k){if(!await v(t,h.originHeadSha,k))return o("epic-execution-branch-origin-drift",!1,!1);await t("switch",s)}else await t("switch","-c",s,h.originHeadSha)}catch{const y=await t("status","--porcelain","--untracked-files=normal").catch(()=>"");return o(y?"epic-execution-branch-switch-blocked-by-user-changes":"epic-execution-branch-switch-failed",!0,!1)}if(l=await t("symbolic-ref","--quiet","--short","HEAD"),f=await t("rev-parse","HEAD"),l!==s)return o("epic-execution-branch-switch-unverified",!0,!1)}const g=await D(e,c,!0),p=g.epics?.[r.epicId];if(!p)return o("epic-state-missing",!1,!1);const x=Y(p),w=await Promise.all(x.map(k=>ce(e,g.stories?.[k]?.checkpoint,k,r.epicId,s).then(y=>y&&ge(g.stories?.[k]?.checkpoint))));if(!(x.length>0&&w.every(Boolean)))return{ok:!0,originBindingCaptured:b,aggregateQaRecorded:!1};if(l!==s)return o("epic-aggregate-qa-execution-checkout-required",!0,!1);const H=S(p.graph_revision);if(!/^[a-f0-9]{64}$/i.test(H))return o("epic-aggregate-qa-graph-required",!1,!1);if(await pe(t))return o("epic-aggregate-qa-checkout-dirty",!0,!1);const G=await ve(e,{headSha:f,graphRevision:H,nowIso:r.nowIso}),B=Re(G);if(!B)return o("epic-aggregate-qa-authority-invalid",!1,!1);if(await a.aggregateQaRunner?.({projectRoot:e,gateIds:B.gateIds}),await t("rev-parse","HEAD")!==f||await pe(t))return o("epic-aggregate-qa-head-raced",!0,!1);const M=`local-yolo-tdd:${O("sha256").update(["epic-aggregate-p205-execution-v2",Q,f,H,B.manifestDigest,B.gateIds.join(","),B.resultDigest].join("\0")).digest("hex")}`,T={schemaVersion:1,evidenceVersion:"p205-execution-v2",producer:"local-yolo-tdd",contract:"P205-CI-02",command:Q,verdict:"passed",executionHeadSha:f,graphRevision:H,manifestDigest:B.manifestDigest,resultDigest:B.resultDigest,checkedAt:B.executedAt,receiptRef:M,gateIds:B.gateIds};return await J(e,k=>{const y=z(k,r.epicId);y.aggregate_qa_receipt=T}),{ok:!0,originBindingCaptured:b,aggregateQaRecorded:!0,p205Authority:G}}catch{return o("epic-lifecycle-evidence-production-failed",!0,!1)}},async inspect(r){try{const i=await D(e,c,!0),n=i.epics?.[r.epicId];if(!n)return o("epic-state-missing",!1,!1);if(S(n.execution_branch)!==r.executionBranch||S(n.origin_branch)!==r.originBranch)return o("epic-branch-boundary-drift",!1,!1);const s=await t("rev-parse",`refs/heads/${r.executionBranch}`),d=await A(t,r.originBranch);await P(t,r.originBranch,d);const l=await X(e,i,n,r.epicId,r.executionBranch);let f=_(n.terminal_git_receipt)?n.terminal_git_receipt:null;f?.physicalStatus==="pushed"&&(f.pushedSha&&await v(t,f.executionHeadSha,f.pushedSha)&&await v(t,f.pushedSha,d)||(f=null)),f||(f=await Ae({directive:r,executionHeadSha:s,originHeadSha:d,git:t}));const h=new Set((Array.isArray(n.git_reconciliation_receipts)?n.git_reconciliation_receipts:[]).filter(_).filter(K).map(R=>S(R.resourceId)).filter(Boolean)),b=await t("symbolic-ref","--quiet","--short","HEAD").catch(()=>""),g=r.reconcile.enabled?await se({state:i,epic:n,directive:r,currentBranch:b,originHeadSha:d,receiptIds:h,git:t,gh:u}):[],p=_(n.origin_binding)?n.origin_binding:null,x=p&&p.originBranch===r.originBranch&&p.executionBranch===r.executionBranch&&await j(t,p.originHeadSha)&&await v(t,p.originHeadSha,s)?p:null;return{ok:!0,snapshot:{executionHeadSha:s,originHeadSha:d,...S(n.graph_revision)?{graphRevision:S(n.graph_revision)}:{},writerLeaseActive:re(n.branch_lease),acceptedCheckpointIds:l,existingReceipt:f,aggregateQaReceipt:_(n.aggregate_qa_receipt)?n.aggregate_qa_receipt:null,originBinding:x,reconciliationCandidates:g}}}catch(i){return o(de(i)??"epic-terminal-inspection-failed",!0,!1)}},async prepareMergeObject(r){let i;try{const n=await t("merge-tree","--write-tree",r.originHeadSha,r.executionHeadSha);i=await t("commit-tree",n,"-p",r.originHeadSha,"-p",r.executionHeadSha,"-m",r.message)}catch{return o("epic-terminal-merge-conflict",!1,!1)}try{const n=await oe(e,{mergeSha:i,originHeadSha:r.originHeadSha,executionHeadSha:r.executionHeadSha,graphRevision:r.graphRevision},r.nowIso);return m.set(i,n.candidateAuthority),{ok:!0,mergeSha:i,...n}}catch{return o("epic-merge-candidate-qa-failed",!0,!1)}},async inspectReconciliation(r){try{const i=await D(e,c,!0),n=i.epics?.[r.epicId];if(!n)return o("epic-state-missing",!1,!1);if(S(n.execution_branch)!==r.executionBranch||S(n.origin_branch)!==r.originBranch)return o("epic-branch-boundary-drift",!1,!1);const s=await A(t,r.originBranch);await P(t,r.originBranch,s);const d=new Set((Array.isArray(n.git_reconciliation_receipts)?n.git_reconciliation_receipts:[]).filter(_).filter(K).map(h=>S(h.resourceId)).filter(Boolean)),l=await t("symbolic-ref","--quiet","--short","HEAD").catch(()=>"");return{ok:!0,candidates:await se({state:i,epic:n,directive:r,currentBranch:l,originHeadSha:s,receiptIds:d,git:t,gh:u})}}catch(i){return o(de(i)??"git-reconciliation-inspection-failed",!0,!1)}},async pushMergeObject(r){try{if(!W(r.candidateAuthority,{mergeSha:r.mergeSha,originHeadSha:r.expectedOriginSha,executionHeadSha:r.executionHeadSha,graphRevision:r.graphRevision}))return o("epic-merge-candidate-authority-required",!1,!1);const n=await D(e,c,!0),s=n.epics?.[r.epicId];if(!s||s.execution_branch!==r.executionBranch||s.origin_branch!==r.originBranch||s.graph_revision!==r.graphRevision||re(s.branch_lease)||await t("rev-parse",`refs/heads/${r.executionBranch}`)!==r.executionHeadSha)return o("epic-merge-candidate-authority-raced",!0,!1);const d=await X(e,n,s,r.epicId,r.executionBranch);if(!ee(d,r.storyCheckpointIds)||!ee(Y(s),r.storyCheckpointIds))return o("epic-checkpoint-set-revalidation-drift",!0,!1);const l=_(s.aggregate_qa_receipt)?s.aggregate_qa_receipt:null;if(!he(l,r.executionHeadSha,r.graphRevision,r.nowIso)||l.receiptRef!==r.aggregateQaReceipt.receiptRef)return o("epic-terminal-aggregate-qa-revalidation-drift",!0,!1);if(await A(t,r.originBranch)!==r.expectedOriginSha)return o("epic-origin-head-raced",!0,!1);await t("push","--porcelain","origin",`${r.mergeSha}:refs/heads/${r.originBranch}`);const h=await A(t,r.originBranch);return h!==r.mergeSha?o("epic-terminal-push-unverified",!0,!1):{ok:!0,pushedSha:h}}catch(i){return te(i)?o("epic-terminal-remote-policy-denied",!0,!0):o("epic-terminal-push-failed",!0,!1)}},async ensureSingleEpicPullRequest(r){try{const i=W(r.candidateAuthority,{mergeSha:r.expectedPullRequestHeadSha,originHeadSha:r.candidateQa.originHeadSha,executionHeadSha:r.expectedStoryHeadSha,graphRevision:r.candidateQa.graphRevision});if(!i||i!==r.candidateQa||!await v(t,r.candidateQa.originHeadSha,r.expectedPullRequestHeadSha)||!await v(t,r.expectedStoryHeadSha,r.expectedPullRequestHeadSha))return o("epic-merge-candidate-authority-required",!1,!1);const n=await I(t,u);if(!n)return o("git-resource-provider-repository-unverified",!0,!0);const s=`https://github.com/${n.nameWithOwner}`,d=await C(t,r.executionBranch);if(d&&d!==r.expectedPullRequestHeadSha){if(await P(t,r.executionBranch,d),!await v(t,d,r.expectedPullRequestHeadSha))return o("epic-terminal-execution-remote-head-drift",!0,!0);await t("push","--porcelain","origin",`${r.expectedPullRequestHeadSha}:refs/heads/${r.executionBranch}`)}if(d||await t("push","--porcelain","origin",`${r.expectedPullRequestHeadSha}:refs/heads/${r.executionBranch}`),await A(t,r.executionBranch)!==r.expectedPullRequestHeadSha)return o("epic-terminal-execution-publish-unverified",!0,!0);const l=await u("pr","list","--repo",s,"--state","all","--head",r.executionBranch,"--base",r.originBranch,"--json","number,state,headRefName,headRefOid,baseRefName,mergeCommit","--limit","100"),f=JSON.parse(l),h=f.filter(w=>w.headRefName===r.executionBranch&&w.baseRefName===r.originBranch&&w.headRefOid===r.expectedPullRequestHeadSha&&(w.state==="OPEN"||w.state==="MERGED"));if(h.length>1)return o("epic-terminal-duplicate-prs",!1,!0);if(typeof h[0]?.number=="number")return{ok:!0,prNumber:h[0].number};if(f.some(w=>w.state==="OPEN"))return o("epic-terminal-stale-pr",!1,!0);const g=(await u("pr","create","--repo",s,"--head",r.executionBranch,"--base",r.originBranch,"--title",`[${r.epicId}] Terminal epic integration`,"--body",`Autonomous terminal integration receipt: ${r.idempotencyKey}`)).match(/\/(\d+)(?:\s*)$/);if(!g)return o("epic-terminal-pr-number-unverified",!0,!0);const p=Number(g[1]),x=await L(u,n.nameWithOwner,p);return!x||x.state!=="OPEN"||x.headRefName!==r.executionBranch||x.baseRefName!==r.originBranch||x.headRefOid!==r.expectedPullRequestHeadSha?o("epic-terminal-pr-create-unverified",!0,!0):{ok:!0,prNumber:p}}catch(i){return o("epic-terminal-pr-create-denied",!0,te(i))}},async mergeEpicPullRequest(r){try{const i=await I(t,u);if(!i)return o("git-resource-provider-repository-unverified",!0,!0);const n=r.candidateQa&&W(r.candidateAuthority,{mergeSha:r.expectedPullRequestHeadSha,graphRevision:r.candidateQa.graphRevision,originHeadSha:r.expectedOriginHeadSha,executionHeadSha:r.expectedStoryHeadSha});if(!n||n!==r.candidateQa)return o("epic-merge-candidate-authority-required",!1,!1);const s=await L(u,i.nameWithOwner,r.prNumber),d=await C(t,r.executionBranch),l=await A(t,r.originBranch);if(!s||s.headRefName!==r.executionBranch||s.baseRefName!==r.originBranch||s.headRefOid!==r.expectedPullRequestHeadSha||d&&d!==r.expectedPullRequestHeadSha||!await v(t,r.expectedOriginHeadSha,r.expectedPullRequestHeadSha)||!await v(t,r.expectedStoryHeadSha,r.expectedPullRequestHeadSha))return o("epic-terminal-pr-revalidation-drift",!0,!0);if(s.state==="OPEN"&&l!==r.expectedOriginHeadSha)return o("epic-terminal-pr-origin-raced",!0,!0);let f;if(s.state==="OPEN"){const w=await Ee(u,i.nameWithOwner,r.originBranch,r.expectedPullRequestHeadSha,r.expectedOriginHeadSha,r.nowIso);if(!w.ok)return o(w.reasonCode,!0,!0);if(f=w.receipt,await A(t,r.originBranch)!==r.expectedOriginHeadSha)return o("epic-terminal-pr-origin-raced",!0,!0);await u("pr","merge",String(r.prNumber),"--repo",`https://github.com/${i.nameWithOwner}`,"--merge","--match-head-commit",r.expectedPullRequestHeadSha)}else{if(s.state!=="MERGED")return o("epic-terminal-pr-not-open-or-merged",!1,!0);f={schemaVersion:1,provider:"github",mode:"recovered_exact_tree",source:"physical_recovery",prHeadSha:r.expectedPullRequestHeadSha,originHeadSha:r.expectedOriginHeadSha,checkedAt:r.nowIso,publicSafe:!0}}const h=await L(u,i.nameWithOwner,r.prNumber),b=h?.mergeCommit?.oid;if(h?.state!=="MERGED"||!b)return o("epic-terminal-pr-merge-unverified",!0,!0);const g=await A(t,r.originBranch);if(await P(t,r.originBranch,g),!await v(t,r.expectedStoryHeadSha,g)||!await v(t,r.expectedPullRequestHeadSha,g)||!await v(t,b,g))return o("epic-terminal-pr-merge-ancestry-unproven",!0,!0);const[p,x]=await Promise.all([t("rev-parse",`${r.expectedPullRequestHeadSha}^{tree}`),t("rev-parse",`${b}^{tree}`)]);return p!==r.candidateQa.treeSha||x!==p?o("epic-terminal-pr-merged-tree-mismatch",!1,!0):{ok:!0,mergeSha:r.expectedPullRequestHeadSha,pushedSha:b,providerGuard:f}}catch(i){return o("epic-terminal-pr-merge-denied",!0,te(i))}},async verifyTerminalReceipt(r,i,n){try{if(i.physicalStatus!=="pushed"||!i.pushedSha||!i.mergeSha)return o("epic-terminal-physical-revalidation-required",!0,!1);const s=await D(e,c,!0),d=s.epics?.[r.epicId];if(!d||S(d.execution_branch)!==r.executionBranch||S(d.origin_branch)!==r.originBranch||S(d.graph_revision)!==r.graphRevision)return o("epic-terminal-state-revalidation-drift",!0,!1);const l=await t("rev-parse",`refs/heads/${r.executionBranch}`);if(l!==r.expectedExecutionHeadSha||i.executionHeadSha!==l)return o("epic-terminal-execution-revalidation-drift",!0,!1);const f=_(d.origin_binding)?d.origin_binding:null;if(!f||f.originBranch!==r.originBranch||f.executionBranch!==r.executionBranch||!await j(t,f.originHeadSha)||!await v(t,f.originHeadSha,l))return o("epic-origin-binding-revalidation-drift",!0,!1);const h=await X(e,s,d,r.epicId,r.executionBranch);if(re(d.branch_lease)||!ee(h,r.storyCheckpointIds))return o("epic-checkpoint-set-revalidation-drift",!0,!1);const b=_(d.aggregate_qa_receipt)?d.aggregate_qa_receipt:null;if(!he(b,l,r.graphRevision,n)||b?.receiptRef!==r.localGates.aggregateQaReceipt.receiptRef)return o("epic-terminal-aggregate-qa-revalidation-drift",!0,!1);const g=await A(t,r.originBranch);if(await P(t,r.originBranch,g),!await v(t,l,g)||!await v(t,i.mergeSha,g)||!await v(t,i.pushedSha,g))return o("epic-terminal-physical-ancestry-unproven",!0,!1);const p={originHeadSha:i.baseSha,executionHeadSha:l,mergeSha:i.mergeSha,graphRevision:r.graphRevision};let x=m.get(i.mergeSha),w=W(x,p);if(!w){const H=await oe(e,p,n);x=H.candidateAuthority,w=H.candidateQa,m.set(i.mergeSha,x)}if(i.candidateQa&&(i.candidateQa.originHeadSha!==w.originHeadSha||i.candidateQa.executionHeadSha!==w.executionHeadSha||i.candidateQa.graphRevision!==w.graphRevision||i.candidateQa.treeSha!==w.treeSha))return o("epic-merge-candidate-receipt-drift",!0,!1);let R=i.providerGuard;if(i.strategy==="single_pr"){if(!i.prNumber)return o("epic-terminal-pr-merge-unverified",!0,!1);if(await t("rev-parse",`${i.pushedSha}^{tree}`)!==w.treeSha)return o("epic-terminal-pr-merged-tree-mismatch",!1,!1);if(R&&!Ie(R,i))return o("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 o("epic-terminal-pr-base-guard-unverifiable",!1,!1);return{ok:!0,candidateQa:w,candidateAuthority:x,...R?{providerGuard:R}:{}}}catch{return o("epic-terminal-physical-revalidation-failed",!0,!1)}},async applyReconciliation(r,i,n){if(i.action==="preserve")return o("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 Be(r,i,t,u);try{const s=await F({candidate:r,decision:i,git:t,gh:u});if(!s.ok)return o(s.reasonCode,!0,!1);if(s.alreadyAbsent)return{ok:!0,outcome:"already_absent"};if(i.action==="delete_local_branch")await t("update-ref","-d",`refs/heads/${r.branchName}`,r.headSha);else if(i.action==="close_pull_request"){if(!r.prNumber)return o("git-reconciliation-pr-number-missing",!1,!1);const d=await I(t,u);if(!d)return o("git-resource-provider-repository-unverified",!0,!0);const l=`https://github.com/${d.nameWithOwner}`,f=`neocortex-reconciliation:${O("sha256").update(r.resourceId).digest("hex")}`,h=JSON.parse(await u("pr","view",String(r.prNumber),"--repo",l,"--json","comments"));if(!_(h)||!Array.isArray(h.comments)||h.comments.length>1e3||h.comments.some(p=>!_(p)||typeof p.body!="string"))return o("git-reconciliation-pr-comments-unverified",!0,!0);h.comments.some(p=>String(p.body).includes(f))||await u("pr","comment",String(r.prNumber),"--repo",l,"--body",`Neocortex reconciliation verified managed ownership and integrated content; requesting closure. [${f}]`);const b=await F({candidate:r,decision:i,git:t,gh:u});if(!b.ok)return o(b.reasonCode,!0,!1);if(b.alreadyAbsent)return{ok:!0,outcome:"already_absent"};await u("pr","close",String(r.prNumber),"--repo",l);const g=await F({candidate:r,decision:i,git:t,gh:u});if(!g.ok)return o(g.reasonCode,!0,!1);if(!g.alreadyAbsent)return o("git-reconciliation-pr-close-unverified",!0,!0)}return{ok:!0,outcome:"applied"}}catch{return o("git-reconciliation-effect-failed",!0,!1)}},async persist(r){try{let i;return await J(e,n=>{const s=z(n,r.terminalReceipt.epicId),d=Array.isArray(s.git_reconciliation_receipts)?s.git_reconciliation_receipts.filter(_):[],l=new Map(d.map(b=>[b.idempotencyKey,b]));for(const b of r.reconciliationReceipts)K(l.get(b.idempotencyKey))||l.set(b.idempotencyKey,b);const f=_(s.terminal_git_receipt)?s.terminal_git_receipt:null,h=Se(f,r.terminalReceipt);if(h.kind==="blocked"){i=h.reasonCode;return}s.terminal_git_receipt=h.receipt,s.git_reconciliation_receipts=[...l.values()],s.physicalMergeStatus=r.terminalReceipt.physicalStatus==="pushed"?"merged":r.terminalReceipt.physicalStatus,s.pr_number=r.terminalReceipt.prNumber??s.pr_number??null,s.git_reconciliation_debt=me(s.git_reconciliation_debt,r.preservedDecisions)}),i?o(i,!1,!1):{ok:!0}}catch{return o("epic-terminal-state-persist-failed",!0,!1)}},async persistReconciliation(r){try{return await J(e,i=>{const n=z(i,r.epicId),s=Array.isArray(n.git_reconciliation_receipts)?n.git_reconciliation_receipts.filter(_):[],d=new Map(s.map(l=>[l.idempotencyKey,l]));for(const l of r.reconciliationReceipts)K(d.get(l.idempotencyKey))||d.set(l.idempotencyKey,l);n.git_reconciliation_receipts=[...d.values()],n.git_reconciliation_debt=me(n.git_reconciliation_debt,r.preservedDecisions)}),{ok:!0}}catch{return o("git-reconciliation-state-persist-failed",!0,!1)}}}}async function I(e,a){try{const c=await e("remote","get-url","origin"),t=c.match(/^https:\/\/github\.com\/([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+?)(?:\.git)?\/?$/)?.[1]??c.match(/^git@github\.com:([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+?)(?:\.git)?$/)?.[1];if(!t)return null;const u=JSON.parse(await a("repo","view",`https://github.com/${t}`,"--json","id,nameWithOwner,url"));return u.nameWithOwner!==t||u.url!==`https://github.com/${t}`||typeof u.id!="string"||!/^[A-Za-z0-9_=-]{1,256}$/.test(u.id)?null:{id:u.id,nameWithOwner:t}}catch{return null}}async function Be(e,a,c,t){try{if(e.kind!=="remote_branch"||a.resourceId!==e.resourceId||!e.baseBranch||e.baseBranch===e.branchName||!E(e.branchName)||!E(e.baseBranch)||!/^[a-f0-9]{40}$/.test(e.headSha)||!/^[a-f0-9]{40}$/.test(e.integrationHeadSha))return o("git-reconciliation-candidate-no-longer-safe",!1,!1);const u=await I(c,t);if(!u)return o("git-resource-remote-delete-cas-unavailable",!1,!1);if(!await C(c,e.branchName))return{ok:!0,outcome:"already_absent"};const r=await F({candidate:e,decision:a,git:c,gh:t});if(!r.ok)return o(r.reasonCode,!0,!1);if((await I(c,t))?.id!==u.id)return o("git-resource-provider-repository-raced",!0,!1);const n=O("sha256").update(["managed-remote-delete-v1",u.id,e.branchName,e.headSha,e.baseBranch,e.integrationHeadSha].join("\0")).digest("hex"),s=(f,h,b)=>`{name:${JSON.stringify(`refs/heads/${f}`)},beforeOid:${JSON.stringify(h)},afterOid:${JSON.stringify(b)},force:false}`,d=`mutation{updateRefs(input:{repositoryId:${JSON.stringify(u.id)},clientMutationId:${JSON.stringify(n)},refUpdates:[`+s(e.branchName,e.headSha,"0".repeat(40))+","+s(e.baseBranch,e.integrationHeadSha,e.integrationHeadSha)+"]}){clientMutationId}}",l=JSON.parse(await t("api","graphql","--hostname","github.com","-f",`query=${d}`));return l.errors||l.data?.updateRefs?.clientMutationId!==n?o("git-resource-remote-delete-cas-unverified",!0,!0):await C(c,e.branchName)?o("git-resource-remote-delete-recreated-or-unverified",!0,!1):{ok:!0,outcome:"applied"}}catch{return o("git-resource-remote-delete-cas-rejected",!0,!0)}}async function F(e){const{candidate:a,decision:c,git:t,gh:u}=e;if(!c.managed||!a.providerVerified||a.current||a.origin||a.protected||a.lifecycle==="active"||a.hasExclusiveCommits||a.worktreeActive)return{ok:!1,reasonCode:"git-reconciliation-candidate-no-longer-safe"};const m=await t("symbolic-ref","--quiet","--short","HEAD").catch(()=>""),r=await fe(t);if(m===a.branchName||r.has(a.branchName))return{ok:!1,reasonCode:"git-resource-worktree-active"};if(a.kind==="local_branch"){const d=await le(t,`refs/heads/${a.branchName}`);return d?d!==a.headSha?{ok:!1,reasonCode:"git-resource-expected-oid-raced"}:!a.baseBranch||await A(t,a.baseBranch)!==a.integrationHeadSha||!await v(t,d,a.integrationHeadSha)?{ok:!1,reasonCode:"git-resource-integration-unproven"}:{ok:!0}:{ok:!0,alreadyAbsent:!0}}if(a.kind==="remote_branch"){const d=await C(t,a.branchName);if(!d)return{ok:!0};if(d!==a.headSha)return{ok:!1,reasonCode:"git-resource-expected-oid-raced"};const l=await I(t,u);return l?await U(u,l.nameWithOwner,a.branchName)!=="unprotected"?{ok:!1,reasonCode:"git-resource-protected"}:!a.baseBranch||await A(t,a.baseBranch)!==a.integrationHeadSha?{ok:!1,reasonCode:"git-resource-integration-unproven"}:(await t("fetch","--quiet","--no-tags","origin",`refs/heads/${a.branchName}`),await t("rev-parse","FETCH_HEAD")!==a.headSha||!await v(t,a.headSha,a.integrationHeadSha)?{ok:!1,reasonCode:"git-resource-integration-unproven"}:{ok:!0}):{ok:!1,reasonCode:"git-resource-provider-repository-unverified"}}if(!a.prNumber||!a.baseBranch)return{ok:!1,reasonCode:"git-reconciliation-pr-proof-missing"};const i=await I(t,u);if(!i)return{ok:!1,reasonCode:"git-resource-provider-repository-unverified"};const n=await L(u,i.nameWithOwner,a.prNumber);if(!n||n.headRefName!==a.branchName||n.baseRefName!==a.baseBranch||n.headRefOid!==a.headSha)return{ok:!1,reasonCode:"git-resource-expected-oid-raced"};if(n.state==="CLOSED"||n.state==="MERGED")return{ok:!0,alreadyAbsent:!0};if(await U(u,i.nameWithOwner,a.branchName)!=="unprotected")return{ok:!1,reasonCode:"git-resource-protected"};const s=await C(t,a.branchName);return!n||n.state!=="OPEN"||n.headRefName!==a.branchName||n.baseRefName!==a.baseBranch||n.headRefOid!==a.headSha||s!==a.headSha?{ok:!1,reasonCode:"git-resource-expected-oid-raced"}:(await t("fetch","--quiet","--no-tags","origin",`refs/heads/${a.branchName}`),await t("rev-parse","FETCH_HEAD")!==a.headSha||await A(t,a.baseBranch)!==a.integrationHeadSha||!await v(t,a.headSha,a.integrationHeadSha)?{ok:!1,reasonCode:"git-resource-integration-unproven"}:{ok:!0})}async function se(e){const a=[],c=await fe(e.git),t=_e(e.state),u=await I(e.git,e.gh),m=g=>{const p=g.split(`
2
- `).filter(Boolean).map(w=>w.split(/\s+/));if(p.length>Z)throw new Error("git-reconciliation-ref-inventory-limit");const x=new Map;for(const[w,R]of p){const H=R?.replace(/^refs\/heads\//,"");if(!H||!E(H)||!/^[a-f0-9]{40,64}$/.test(w??"")||x.has(H))throw new Error("git-reconciliation-ref-inventory-invalid");x.set(H,w)}return x},r=m(await e.git("for-each-ref",`--count=${Z+1}`,"--format=%(objectname) %(refname)","refs/heads")),i=m(await e.git("ls-remote","--heads","origin")),n=new Set([...t.claims.keys()].filter(E)),s=u?await $e(e.gh,u.nameWithOwner,n):[],d=new Map([[e.directive.originBranch,e.originHeadSha]]),l=async g=>{if(d.has(g))return d.get(g);const p=i.get(g);return p?(await P(e.git,g,p),d.set(g,p),p):""},f=new Map,h=async(g,p)=>{const x=`${g}:${p}`;return f.has(x)||f.set(x,!!(g&&p)&&await v(e.git,g,p)),f.get(x)},b=new Set([...r.keys(),...i.keys(),...t.claims.keys()]);if(b.size>Z)throw new Error("git-reconciliation-ref-inventory-limit");for(const g of[...b].sort()){if(!E(g))continue;const p=t.claims.get(g)??[],x=new Set(p.map(y=>`${y.epicId}:${y.origin}`)),w=x.size===1?p[0].origin:e.directive.originBranch,R=await l(w),H=p.length===0||p.some(y=>y.active),G=r.get(g),B=i.get(g);B&&await P(e.git,g,B);const M=u&&B?await U(e.gh,u.nameWithOwner,g):"unknown",T=async y=>{if(x.size!==1)return[];const $=new Set;for(const q of p)for(const N of q.proofs)N.head===y&&(N.mergeSha&&(!N.pushedSha||!await h(y,N.mergeSha)||!await h(N.mergeSha,N.pushedSha)||!await h(N.pushedSha,R))||N.evidence.forEach(V=>$.add(V)));return[...$]},k={schemaVersion:1,branchName:g,baseBranch:w,integrationHeadSha:R,lifecycle:H?"active":"integrated",current:g===e.currentBranch,origin:t.origins.has(g)||g===e.directive.originBranch,worktreeActive:c.has(g),contentEquivalent:!1,publicSafe:!0};for(const[y,$]of[["local_branch",G],["remote_branch",B]]){if(!$)continue;const q=`${y}:${O("sha256").update(g).digest("hex")}:${$}`,N=await h($,R);a.push({...k,resourceId:q,kind:y,headSha:$,ownershipEvidence:await T($),protected:!!B&&M!=="unprotected",providerVerified:y==="local_branch"?!0:!!u&&M!=="unknown",...y==="remote_branch"&&u?{remoteDeletionCas:"github-update-refs-v1"}:{},commitsReachable:N,hasExclusiveCommits:!N,previouslyReconciled:e.receiptIds.has(q)})}for(const y of s.filter($=>$.headRefName===g)){const $=y.baseRefName===w&&y.sameRepository,q=await T(y.headRefOid);$&&q.includes("managed_metadata")&&q.push("pr_head_base_match");const N=`pr:${y.number}:${y.headRefOid}:${O("sha256").update(y.baseRefName).digest("hex")}`,V=await h(y.headRefOid,R);a.push({...k,resourceId:N,kind:"pull_request",prNumber:y.number,headSha:y.headRefOid,lifecycle:y.state!=="OPEN"?"already_absent":H?"active":"superseded",ownershipEvidence:q,providerVerified:$,protected:M!=="unprotected",commitsReachable:V,hasExclusiveCommits:!V,previouslyReconciled:e.receiptIds.has(N)})}}return Ne(e.epic,a),a}function Ne(e,a){const c=new Set((Array.isArray(e.git_reconciliation_receipts)?e.git_reconciliation_receipts:[]).filter(_).map(m=>S(m.idempotencyKey))),t=new Set((Array.isArray(e.git_reconciliation_debt)?e.git_reconciliation_debt:[]).filter(_).map(m=>S(m.resourceId))),u=new Set(a.filter(m=>m.kind==="pull_request"&&ie(m).action==="close_pull_request").map(m=>m.branchName));for(const m of a){const r=ie(m);r.action==="preserve"?t.add(m.resourceId):(c.add(`reconciliation:v2:${O("sha256").update([m.resourceId,r.action].join("\0")).digest("hex")}`),m.kind!=="pull_request"&&u.has(m.branchName)&&t.add(m.resourceId))}if(c.size>1024)throw new Error("git-reconciliation-receipt-capacity");if(t.size>1024)throw new Error("git-reconciliation-debt-capacity")}function de(e){const a=new Set(["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 e instanceof Error&&a.has(e.message)?e.message:void 0}async function $e(e,a,c){const t=a.split("/")[0];if(!t||!/^[A-Za-z0-9_.-]+$/.test(t))throw new Error("git-reconciliation-pr-inventory-invalid");const u=[],m=new Set,r=100,i=Math.floor(ne/r)+1;for(const n of[...c].sort()){if(!E(n))throw new Error("git-reconciliation-pr-inventory-invalid");const s=encodeURIComponent(`${t}:${n}`);for(let d=1;d<=i;d+=1){const l=`repos/${a}/pulls?state=all&head=${s}&per_page=${r}&page=${d}`,f=JSON.parse(await e("api",l,"--hostname","github.com"));if(!Array.isArray(f)||f.length>r)throw new Error("git-reconciliation-pr-inventory-limit");for(const h of f){if(!_(h)||!Number.isSafeInteger(h.number)||Number(h.number)<=0||m.has(Number(h.number))||!_(h.head)||!_(h.base)||S(h.head.ref)!==n||!E(S(h.head.ref))||!E(S(h.base.ref))||!/^[a-f0-9]{40,64}$/.test(S(h.head.sha))||!["open","closed"].includes(S(h.state)))throw new Error("git-reconciliation-pr-inventory-invalid");if(m.add(Number(h.number)),u.push({number:Number(h.number),state:S(h.state).toUpperCase(),headRefName:S(h.head.ref),headRefOid:S(h.head.sha),baseRefName:S(h.base.ref),sameRepository:_(h.head.repo)&&_(h.base.repo)&&h.head.repo.full_name===a&&h.base.repo.full_name===a}),u.length>ne)throw new Error("git-reconciliation-pr-inventory-limit")}if(f.length<r)break}}return u}function K(e){return _(e)&&(e.outcome==="applied"||e.outcome==="already_absent")}async function Ae(e){try{const a=(await e.git("log",e.originHeadSha,"--format=%H","--fixed-strings",`--grep=Neocortex-Idempotency: ${e.directive.idempotencyKey}`)).split(`
3
- `).filter(s=>/^[a-f0-9]{40,64}$/i.test(s));if(a.length!==1)return null;const c=a[0],t=(await e.git("rev-list","--parents","-n","1",c)).split(/\s+/),u=await e.git("show","-s","--format=%B",c),[m]=u.split(`
4
- `),r=`merge(${e.directive.epicId}): integrate ${e.directive.executionBranch} into ${e.directive.originBranch}`;if(t.length!==3||t[2]!==e.executionHeadSha||m!==r)return null;const i=new Set(u.split(`
5
- `).map(s=>s.trim()));for(const s of[`Neocortex-Epic: ${e.directive.epicId}`,`Neocortex-Origin-Branch: ${e.directive.originBranch}`,`Neocortex-Execution-Branch: ${e.directive.executionBranch}`,`Neocortex-Execution-Head: ${e.executionHeadSha}`,`Neocortex-Origin-Base: ${t[1]}`,`Neocortex-Graph-Revision: ${e.directive.graphRevision}`,`Neocortex-Aggregate-QA: ${e.directive.localGates.aggregateQaReceipt.receiptRef}`,`Neocortex-Idempotency: ${e.directive.idempotencyKey}`])if(!i.has(s))return null;const n=await e.git("show","-s","--format=%cI",c);return{schemaVersion:1,epicId:e.directive.epicId,executionBranch:e.directive.executionBranch,originBranch:e.directive.originBranch,baseSha:t[1],executionHeadSha:e.executionHeadSha,mergeSha:c,pushedSha:c,strategy:"direct",physicalStatus:"pushed",localGateReceiptRefs:e.directive.localGates.receiptRefs,idempotencyKey:e.directive.idempotencyKey,attemptStartedAt:n,completedAt:n,retryEligible:!1,reasonCodes:["epic-terminal-recovered-physical-push"],publicSafe:!0}}catch{return null}}async function U(e,a,c){try{if(!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(a))return"unknown";const t=await e("api",`repos/${a}/branches/${encodeURIComponent(c)}`,"--hostname","github.com","--jq",".protected");return t==="false"?"unprotected":t==="true"?"protected":"unknown"}catch{return"unknown"}}async function L(e,a,c){try{const t=JSON.parse(await e("pr","view",String(c),"--repo",`https://github.com/${a}`,"--json","state,headRefName,headRefOid,baseRefName,mergeCommit"));return[t.state,t.headRefName,t.headRefOid,t.baseRefName].every(u=>typeof u=="string")?t:null}catch{return null}}async function Ee(e,a,c,t,u,m){if(!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(a)||!E(c)||!/^[a-f0-9]{40,64}$/i.test(t)||!/^[a-f0-9]{40,64}$/i.test(u)||Number.isNaN(Date.parse(m)))return{ok:!1,reasonCode:"epic-terminal-pr-base-guard-unverifiable"};let r;try{const d=JSON.parse(await e("api",`repos/${a}/rules/branches/${encodeURIComponent(c)}`,"--hostname","github.com","--paginate","--slurp")),l=Array.isArray(d)&&d.every(Array.isArray)?d.flat():d;if(!Array.isArray(l)||l.length>256||l.some(f=>!_(f)))return{ok:!1,reasonCode:"epic-terminal-pr-base-guard-unverifiable"};r=l}catch{return{ok:!1,reasonCode:"epic-terminal-pr-base-guard-unverifiable"}}if(r.some(d=>d.type==="merge_queue"))return{ok:!1,reasonCode:"epic-terminal-pr-merge-queue-local-gate-required"};const i=r.some(d=>d.type==="required_status_checks"&&_(d.parameters)&&d.parameters.strict_required_status_checks_policy===!0);let n=!1;try{const d=JSON.parse(await e("api",`repos/${a}/branches/${encodeURIComponent(c)}/protection/required_status_checks`,"--hostname","github.com"));if(!_(d)||typeof d.strict!="boolean")return{ok:!1,reasonCode:"epic-terminal-pr-base-guard-unverifiable"};n=d.strict}catch(d){if(!qe(d))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:t,originHeadSha:u,checkedAt:m,publicSafe:!0}}}function qe(e){return e instanceof Error&&/(?:HTTP\s*)?404\b|not found/i.test(e.message)}function Ie(e,a){const c=e.mode==="recovered_exact_tree"?e.source==="physical_recovery":e.mode==="strict_up_to_date_expected_head"&&["branch_protection","ruleset","branch_protection_and_ruleset"].includes(e.source);return e.schemaVersion===1&&e.provider==="github"&&c&&e.publicSafe===!0&&!Number.isNaN(Date.parse(e.checkedAt))&&e.prHeadSha===a.mergeSha&&e.originHeadSha===a.baseSha}async function ue(e,a,c){return(await ke(e,[...a],{cwd:c,encoding:"utf8",maxBuffer:16777216})).stdout.trim()}async function D(e,a,c=!1){const t=JSON.parse(await ae(a,"utf8"));return xe(t,await He(e,{required:c}))}function he(e,a,c,t){if(!e||e.schemaVersion!==1||e.evidenceVersion!=="p205-execution-v2"||e.producer!=="local-yolo-tdd"||e.contract!=="P205-CI-02"||e.command!==Q||e.verdict!=="passed"||e.executionHeadSha!==a||e.graphRevision!==c||!/^[a-f0-9]{64}$/i.test(e.manifestDigest??"")||!/^[a-f0-9]{64}$/i.test(e.resultDigest??"")||e.gateIds.length===0)return!1;const u=`local-yolo-tdd:${O("sha256").update(["epic-aggregate-p205-execution-v2",Q,a,c,e.manifestDigest,e.gateIds.join(","),e.resultDigest].join("\0")).digest("hex")}`;if(e.receiptRef!==u)return!1;const m=Date.parse(e.checkedAt),r=Date.parse(t);return Number.isFinite(m)&&Number.isFinite(r)&&r-m<=1800*1e3&&m-r<=300*1e3}async function A(e,a){const c=await C(e,a);if(!c)throw new Error("origin-ref-missing");return c}async function C(e,a){if(!E(a))throw new Error("branch-ref-invalid");const t=(await e("ls-remote","--heads","origin",`refs/heads/${a}`)).split(`
6
- `).filter(Boolean).map(u=>u.split(/\s+/));if(t.length!==0){if(t.length!==1||t[0].length!==2||t[0][1]!==`refs/heads/${a}`||!/^[a-f0-9]{40,64}$/i.test(t[0][0]??""))throw new Error("remote-ref-query-invalid");return t[0][0]}}async function P(e,a,c){if(await e("fetch","--quiet","--no-tags","origin",`refs/heads/${a}`),await e("rev-parse","FETCH_HEAD")!==c)throw new Error("remote-head-raced")}async function le(e,a){try{return await e("rev-parse","--verify",a)}catch{return}}async function v(e,a,c){try{return await e("merge-base","--is-ancestor",a,c),!0}catch{return!1}}async function j(e,a){if(!/^[a-f0-9]{40,64}$/i.test(a))return!1;try{return await e("cat-file","-t",a)==="commit"}catch{return!1}}async function fe(e){const a=new Set,c=await e("worktree","list","--porcelain");for(const t of c.split(`
7
- `))t.startsWith("branch refs/heads/")&&a.add(t.slice(18));return a}function o(e,a,c){return{ok:!1,reasonCode:e,retryEligible:a,externalPolicy:c}}function S(e){return typeof e=="string"?e.trim():""}function E(e){return e.length>0&&e.length<=240&&!e.startsWith("-")&&!e.startsWith("/")&&!e.endsWith("/")&&!e.endsWith(".lock")&&!e.includes("..")&&!e.includes("\\")&&!e.includes("@{")&&!e.includes("//")&&/^[A-Za-z0-9._/-]+$/.test(e)}function _(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Oe(e,a){return e instanceof Error&&"code"in e&&e.code===a}function Y(e){return(Array.isArray(e.stories)?e.stories:Array.isArray(e.story_ids)?e.story_ids:[]).filter(c=>typeof c=="string")}async function X(e,a,c,t,u){const m=Y(c),r=await Promise.all(m.map(i=>ce(e,a.stories?.[i]?.checkpoint,i,t,u).then(n=>n&&ge(a.stories?.[i]?.checkpoint))));return m.filter((i,n)=>r[n])}function ge(e){const a=_(e)?e:void 0,c=a&&_(a.qaReceipt)?a.qaReceipt:void 0;return!!(c&&c.evidenceVersion==="p205-execution-v2"&&c.producer==="local-yolo-tdd"&&c.contract==="P205-CI-02"&&c.command===Q&&/^[a-f0-9]{64}$/i.test(S(c.manifestDigest))&&/^[a-f0-9]{64}$/i.test(S(c.resultDigest))&&Array.isArray(c.gateIds)&&c.gateIds.length>0)}function ee(e,a){return e.length===a.length&&[...e].sort().every((c,t)=>c===[...a].sort()[t])}function re(e){return _(e)&&typeof e.expiresAt=="string"&&e.expiresAt>new Date().toISOString()}async function pe(e){const a=new Set([".neocortex/yoloop.lock",".neocortex/yoloop-state.json",".neocortex/continuity/continuity.sqlite",".neocortex/continuity/continuity.sqlite-shm",".neocortex/continuity/continuity.sqlite-wal"]);return(await e("status","--porcelain","--untracked-files=all")).split(`
8
- `).filter(Boolean).some(c=>!c.startsWith("?? ")||!a.has(c.slice(3)))}function te(e){const a=e instanceof Error?e.message:"";return/protected branch|branch protection|required pull request|GH006|GH013|ruleset|review required/i.test(a)}function me(e,a){const c=Array.isArray(e)?e.filter(_):[],t=new Map(c.map(u=>[S(u.resourceId),u]));for(const u of a)t.set(u.resourceId,u);return[...t.values()]}export{ze as createCliEpicTerminalGitAdapter};
1
+ /** Production Git/GitHub adapter for the terminal epic lifecycle. */
2
+ import { execFile } from 'node:child_process';
3
+ import { createHash } from 'node:crypto';
4
+ import { readFile } from 'node:fs/promises';
5
+ import { join } from 'node:path';
6
+ import { promisify } from 'node:util';
7
+ import { classifyGitReconciliationCandidate, reconcileTerminalReceipt } from '../../../../shared/dist/yoloop/epic-terminal-git.js';
8
+ import { collectGitResourceOwnership, GIT_INVENTORY_PR_LIMIT, GIT_INVENTORY_REF_LIMIT, } from './epic-git-reconciliation-inventory.js';
9
+ import { executeEpicMergeCandidateQa, verifiedEpicMergeCandidateReceipt } from './epic-merge-candidate-qa.js';
10
+ import { applyGitLifecycleRuntimeOverlay, ensureRuntimeEpic, executeP205TransientAuthority, P205_COMPLETE_COMMAND, projectP205TransientExecutionEvidence, verifyAcceptedGitLifecycleStoryCheckpoint, mutateGitLifecycleRuntime, readGitLifecycleRuntime, } from '../../git/git-lifecycle-store.js';
11
+ const execFileAsync = promisify(execFile);
12
+ export function createCliEpicTerminalGitAdapter(projectRoot, options = {}) {
13
+ const statePath = join(projectRoot, '.neocortex', 'state.json');
14
+ const git = options.gitRunner ?? ((...args) => command('git', args, projectRoot));
15
+ const gh = options.providerRunner ?? ((...args) => command('gh', args, projectRoot));
16
+ const candidateAuthorities = new Map();
17
+ return {
18
+ async prepareLifecycleEvidence(input) {
19
+ try {
20
+ try {
21
+ await readFile(statePath, 'utf8');
22
+ }
23
+ catch (error) {
24
+ // Continuity can execute in projectless fixtures/hosts. Git lifecycle
25
+ // evidence is inapplicable until a canonical project state exists.
26
+ if (isNodeError(error, 'ENOENT')) {
27
+ return { ok: true, originBindingCaptured: false, aggregateQaRecorded: false };
28
+ }
29
+ throw error;
30
+ }
31
+ const state = await readEffectiveState(projectRoot, statePath);
32
+ const epic = state.epics?.[input.epicId];
33
+ if (!epic)
34
+ return failure('epic-state-missing', false, false);
35
+ if (stringValue(epic.branch_mode) !== 'epic') {
36
+ return { ok: true, originBindingCaptured: false, aggregateQaRecorded: false };
37
+ }
38
+ const executionBranch = stringValue(epic.execution_branch);
39
+ const recordedOrigin = stringValue(epic.origin_branch);
40
+ if (!executionBranch || !safeBranch(executionBranch))
41
+ return failure('epic-execution-branch-missing', false, false);
42
+ let currentBranch = await git('symbolic-ref', '--quiet', '--short', 'HEAD').catch(() => '');
43
+ let currentHead = await git('rev-parse', 'HEAD');
44
+ let originBinding = isRecord(epic.origin_binding)
45
+ ? epic.origin_binding
46
+ : null;
47
+ let originBindingCaptured = false;
48
+ if (!originBinding) {
49
+ if (!currentBranch || currentBranch === executionBranch || !safeBranch(currentBranch)) {
50
+ return failure('epic-origin-binding-capture-window-missed', false, false);
51
+ }
52
+ if (recordedOrigin && recordedOrigin !== currentBranch) {
53
+ return failure('epic-origin-binding-recorded-origin-drift', false, false);
54
+ }
55
+ originBinding = {
56
+ schemaVersion: 1,
57
+ originBranch: currentBranch,
58
+ originHeadSha: currentHead,
59
+ executionBranch,
60
+ capturedFromCurrentCheckout: true,
61
+ capturedAt: input.nowIso,
62
+ };
63
+ await mutateGitLifecycleRuntime(projectRoot, (runtime) => {
64
+ const runtimeEpic = ensureRuntimeEpic(runtime, input.epicId);
65
+ if (runtimeEpic.origin_binding && JSON.stringify(runtimeEpic.origin_binding) !== JSON.stringify(originBinding)) {
66
+ throw new Error('origin-binding-cas-conflict');
67
+ }
68
+ runtimeEpic.origin_branch = currentBranch;
69
+ runtimeEpic.origin_binding = originBinding;
70
+ });
71
+ originBindingCaptured = true;
72
+ }
73
+ else if (originBinding.executionBranch !== executionBranch
74
+ || originBinding.originBranch !== recordedOrigin
75
+ || currentBranch !== executionBranch && currentBranch !== originBinding.originBranch
76
+ || !(await isCommit(git, originBinding.originHeadSha))
77
+ || !(await isAncestor(git, originBinding.originHeadSha, currentHead))) {
78
+ return failure('epic-origin-binding-physical-drift', false, false);
79
+ }
80
+ if (currentBranch !== executionBranch) {
81
+ const executionHead = await resolveOptionalRef(git, `refs/heads/${executionBranch}`);
82
+ try {
83
+ if (executionHead) {
84
+ if (!(await isAncestor(git, originBinding.originHeadSha, executionHead))) {
85
+ return failure('epic-execution-branch-origin-drift', false, false);
86
+ }
87
+ await git('switch', executionBranch);
88
+ }
89
+ else {
90
+ await git('switch', '-c', executionBranch, originBinding.originHeadSha);
91
+ }
92
+ }
93
+ catch {
94
+ const dirty = await git('status', '--porcelain', '--untracked-files=normal').catch(() => '');
95
+ return failure(dirty ? 'epic-execution-branch-switch-blocked-by-user-changes' : 'epic-execution-branch-switch-failed', true, false);
96
+ }
97
+ currentBranch = await git('symbolic-ref', '--quiet', '--short', 'HEAD');
98
+ currentHead = await git('rev-parse', 'HEAD');
99
+ if (currentBranch !== executionBranch)
100
+ return failure('epic-execution-branch-switch-unverified', true, false);
101
+ }
102
+ const effective = await readEffectiveState(projectRoot, statePath, true);
103
+ const effectiveEpic = effective.epics?.[input.epicId];
104
+ if (!effectiveEpic)
105
+ return failure('epic-state-missing', false, false);
106
+ const checkpointStoryIds = storyIds(effectiveEpic);
107
+ const checkpointVerdicts = await Promise.all(checkpointStoryIds.map((storyId) => verifyAcceptedGitLifecycleStoryCheckpoint(projectRoot, effective.stories?.[storyId]?.checkpoint, storyId, input.epicId, executionBranch).then((verified) => verified && hasP205ExecutionAuthority(effective.stories?.[storyId]?.checkpoint))));
108
+ const checkpointsReady = checkpointStoryIds.length > 0 && checkpointVerdicts.every(Boolean);
109
+ if (!checkpointsReady)
110
+ return { ok: true, originBindingCaptured, aggregateQaRecorded: false };
111
+ if (currentBranch !== executionBranch)
112
+ return failure('epic-aggregate-qa-execution-checkout-required', true, false);
113
+ const graphRevision = stringValue(effectiveEpic.graph_revision);
114
+ if (!/^[a-f0-9]{64}$/i.test(graphRevision))
115
+ return failure('epic-aggregate-qa-graph-required', false, false);
116
+ if (await hasUncommittedSourceChanges(git)) {
117
+ return failure('epic-aggregate-qa-checkout-dirty', true, false);
118
+ }
119
+ const p205Authority = await executeP205TransientAuthority(projectRoot, {
120
+ headSha: currentHead,
121
+ graphRevision,
122
+ nowIso: input.nowIso,
123
+ });
124
+ const evidence = projectP205TransientExecutionEvidence(p205Authority);
125
+ if (!evidence)
126
+ return failure('epic-aggregate-qa-authority-invalid', false, false);
127
+ await options.aggregateQaRunner?.({ projectRoot, gateIds: evidence.gateIds });
128
+ if (await git('rev-parse', 'HEAD') !== currentHead || await hasUncommittedSourceChanges(git)) {
129
+ return failure('epic-aggregate-qa-head-raced', true, false);
130
+ }
131
+ const receiptRef = `local-yolo-tdd:${createHash('sha256').update([
132
+ 'epic-aggregate-p205-execution-v2', P205_COMPLETE_COMMAND,
133
+ currentHead, graphRevision, evidence.manifestDigest, evidence.gateIds.join(','), evidence.resultDigest,
134
+ ].join('\0')).digest('hex')}`;
135
+ const aggregateQaReceipt = {
136
+ schemaVersion: 1, evidenceVersion: 'p205-execution-v2', producer: 'local-yolo-tdd',
137
+ contract: 'P205-CI-02', command: P205_COMPLETE_COMMAND,
138
+ verdict: 'passed', executionHeadSha: currentHead, graphRevision,
139
+ manifestDigest: evidence.manifestDigest, resultDigest: evidence.resultDigest,
140
+ checkedAt: evidence.executedAt, receiptRef, gateIds: evidence.gateIds,
141
+ };
142
+ await mutateGitLifecycleRuntime(projectRoot, (runtime) => {
143
+ const runtimeEpic = ensureRuntimeEpic(runtime, input.epicId);
144
+ runtimeEpic.aggregate_qa_receipt = aggregateQaReceipt;
145
+ });
146
+ return { ok: true, originBindingCaptured, aggregateQaRecorded: true, p205Authority };
147
+ }
148
+ catch {
149
+ return failure('epic-lifecycle-evidence-production-failed', true, false);
150
+ }
151
+ },
152
+ async inspect(directive) {
153
+ try {
154
+ const state = await readEffectiveState(projectRoot, statePath, true);
155
+ const epic = state.epics?.[directive.epicId];
156
+ if (!epic)
157
+ return failure('epic-state-missing', false, false);
158
+ if (stringValue(epic.execution_branch) !== directive.executionBranch || stringValue(epic.origin_branch) !== directive.originBranch) {
159
+ return failure('epic-branch-boundary-drift', false, false);
160
+ }
161
+ const executionHeadSha = await git('rev-parse', `refs/heads/${directive.executionBranch}`);
162
+ const originHeadSha = await resolveRemoteHeadFresh(git, directive.originBranch);
163
+ await fetchRemoteHeadExact(git, directive.originBranch, originHeadSha);
164
+ const acceptedCheckpointIds = await acceptedPhysicalCheckpointIds(projectRoot, state, epic, directive.epicId, directive.executionBranch);
165
+ let existingReceipt = isRecord(epic.terminal_git_receipt)
166
+ ? epic.terminal_git_receipt
167
+ : null;
168
+ if (existingReceipt?.physicalStatus === 'pushed') {
169
+ const receiptStillPhysical = Boolean(existingReceipt.pushedSha)
170
+ && await isAncestor(git, existingReceipt.executionHeadSha, existingReceipt.pushedSha)
171
+ && await isAncestor(git, existingReceipt.pushedSha, originHeadSha);
172
+ if (!receiptStillPhysical)
173
+ existingReceipt = null;
174
+ }
175
+ if (!existingReceipt) {
176
+ existingReceipt = await recoverDirectPhysicalReceipt({ directive, executionHeadSha, originHeadSha, git });
177
+ }
178
+ const receiptIds = new Set((Array.isArray(epic.git_reconciliation_receipts) ? epic.git_reconciliation_receipts : [])
179
+ .filter(isRecord).filter(successfulReconciliation).map((item) => stringValue(item.resourceId)).filter(Boolean));
180
+ const currentBranch = await git('symbolic-ref', '--quiet', '--short', 'HEAD').catch(() => '');
181
+ const candidates = directive.reconcile.enabled
182
+ ? await buildCandidates({ state, epic, directive, currentBranch, originHeadSha, receiptIds, git, gh }) : [];
183
+ const persistedOriginBinding = isRecord(epic.origin_binding)
184
+ ? epic.origin_binding
185
+ : null;
186
+ const originBinding = persistedOriginBinding
187
+ && persistedOriginBinding.originBranch === directive.originBranch
188
+ && persistedOriginBinding.executionBranch === directive.executionBranch
189
+ && await isCommit(git, persistedOriginBinding.originHeadSha)
190
+ && await isAncestor(git, persistedOriginBinding.originHeadSha, executionHeadSha)
191
+ ? persistedOriginBinding
192
+ : null;
193
+ const snapshot = {
194
+ executionHeadSha, originHeadSha,
195
+ ...(stringValue(epic.graph_revision) ? { graphRevision: stringValue(epic.graph_revision) } : {}),
196
+ writerLeaseActive: isLiveLease(epic.branch_lease),
197
+ acceptedCheckpointIds,
198
+ existingReceipt,
199
+ aggregateQaReceipt: isRecord(epic.aggregate_qa_receipt)
200
+ ? epic.aggregate_qa_receipt
201
+ : null,
202
+ originBinding,
203
+ reconciliationCandidates: candidates,
204
+ };
205
+ return { ok: true, snapshot };
206
+ }
207
+ catch (error) {
208
+ return failure(publicInventoryReason(error) ?? 'epic-terminal-inspection-failed', true, false);
209
+ }
210
+ },
211
+ async prepareMergeObject(input) {
212
+ let mergeSha;
213
+ try {
214
+ const treeSha = await git('merge-tree', '--write-tree', input.originHeadSha, input.executionHeadSha);
215
+ mergeSha = await git('commit-tree', treeSha, '-p', input.originHeadSha, '-p', input.executionHeadSha, '-m', input.message);
216
+ }
217
+ catch {
218
+ return failure('epic-terminal-merge-conflict', false, false);
219
+ }
220
+ try {
221
+ const accepted = await executeEpicMergeCandidateQa(projectRoot, {
222
+ mergeSha, originHeadSha: input.originHeadSha, executionHeadSha: input.executionHeadSha,
223
+ graphRevision: input.graphRevision,
224
+ }, input.nowIso);
225
+ candidateAuthorities.set(mergeSha, accepted.candidateAuthority);
226
+ return { ok: true, mergeSha, ...accepted };
227
+ }
228
+ catch {
229
+ return failure('epic-merge-candidate-qa-failed', true, false);
230
+ }
231
+ },
232
+ async inspectReconciliation(directive) {
233
+ try {
234
+ const state = await readEffectiveState(projectRoot, statePath, true);
235
+ const epic = state.epics?.[directive.epicId];
236
+ if (!epic)
237
+ return failure('epic-state-missing', false, false);
238
+ if (stringValue(epic.execution_branch) !== directive.executionBranch || stringValue(epic.origin_branch) !== directive.originBranch) {
239
+ return failure('epic-branch-boundary-drift', false, false);
240
+ }
241
+ const originHeadSha = await resolveRemoteHeadFresh(git, directive.originBranch);
242
+ await fetchRemoteHeadExact(git, directive.originBranch, originHeadSha);
243
+ const receiptIds = new Set((Array.isArray(epic.git_reconciliation_receipts) ? epic.git_reconciliation_receipts : [])
244
+ .filter(isRecord).filter(successfulReconciliation).map((item) => stringValue(item.resourceId)).filter(Boolean));
245
+ const currentBranch = await git('symbolic-ref', '--quiet', '--short', 'HEAD').catch(() => '');
246
+ const candidates = await buildCandidates({ state, epic, directive, currentBranch, originHeadSha, receiptIds, git, gh });
247
+ return { ok: true, candidates };
248
+ }
249
+ catch (error) {
250
+ return failure(publicInventoryReason(error) ?? 'git-reconciliation-inspection-failed', true, false);
251
+ }
252
+ },
253
+ async pushMergeObject(input) {
254
+ try {
255
+ const candidate = verifiedEpicMergeCandidateReceipt(input.candidateAuthority, {
256
+ mergeSha: input.mergeSha, originHeadSha: input.expectedOriginSha,
257
+ executionHeadSha: input.executionHeadSha, graphRevision: input.graphRevision,
258
+ });
259
+ if (!candidate)
260
+ return failure('epic-merge-candidate-authority-required', false, false);
261
+ const state = await readEffectiveState(projectRoot, statePath, true);
262
+ const epic = state.epics?.[input.epicId];
263
+ if (!epic || epic.execution_branch !== input.executionBranch || epic.origin_branch !== input.originBranch
264
+ || epic.graph_revision !== input.graphRevision || isLiveLease(epic.branch_lease)
265
+ || await git('rev-parse', `refs/heads/${input.executionBranch}`) !== input.executionHeadSha) {
266
+ return failure('epic-merge-candidate-authority-raced', true, false);
267
+ }
268
+ const accepted = await acceptedPhysicalCheckpointIds(projectRoot, state, epic, input.epicId, input.executionBranch);
269
+ if (!sameSet(accepted, input.storyCheckpointIds) || !sameSet(storyIds(epic), input.storyCheckpointIds)) {
270
+ return failure('epic-checkpoint-set-revalidation-drift', true, false);
271
+ }
272
+ const aggregate = isRecord(epic.aggregate_qa_receipt) ? epic.aggregate_qa_receipt : null;
273
+ if (!validFreshAggregate(aggregate, input.executionHeadSha, input.graphRevision, input.nowIso)
274
+ || aggregate.receiptRef !== input.aggregateQaReceipt.receiptRef) {
275
+ return failure('epic-terminal-aggregate-qa-revalidation-drift', true, false);
276
+ }
277
+ const physicalOrigin = await resolveRemoteHeadFresh(git, input.originBranch);
278
+ if (physicalOrigin !== input.expectedOriginSha)
279
+ return failure('epic-origin-head-raced', true, false);
280
+ await git('push', '--porcelain', 'origin', `${input.mergeSha}:refs/heads/${input.originBranch}`);
281
+ const pushedSha = await resolveRemoteHeadFresh(git, input.originBranch);
282
+ if (pushedSha !== input.mergeSha)
283
+ return failure('epic-terminal-push-unverified', true, false);
284
+ return { ok: true, pushedSha };
285
+ }
286
+ catch (error) {
287
+ return looksLikeRemotePolicy(error)
288
+ ? failure('epic-terminal-remote-policy-denied', true, true)
289
+ : failure('epic-terminal-push-failed', true, false);
290
+ }
291
+ },
292
+ async ensureSingleEpicPullRequest(input) {
293
+ try {
294
+ const candidate = verifiedEpicMergeCandidateReceipt(input.candidateAuthority, {
295
+ mergeSha: input.expectedPullRequestHeadSha,
296
+ originHeadSha: input.candidateQa.originHeadSha,
297
+ executionHeadSha: input.expectedStoryHeadSha,
298
+ graphRevision: input.candidateQa.graphRevision,
299
+ });
300
+ if (!candidate || candidate !== input.candidateQa
301
+ || !(await isAncestor(git, input.candidateQa.originHeadSha, input.expectedPullRequestHeadSha))
302
+ || !(await isAncestor(git, input.expectedStoryHeadSha, input.expectedPullRequestHeadSha))) {
303
+ return failure('epic-merge-candidate-authority-required', false, false);
304
+ }
305
+ const repository = await githubOriginRepository(git, gh);
306
+ if (!repository)
307
+ return failure('git-resource-provider-repository-unverified', true, true);
308
+ const repositoryUrl = `https://github.com/${repository.nameWithOwner}`;
309
+ const remoteHead = await resolveRemoteHeadFreshOptional(git, input.executionBranch);
310
+ if (remoteHead && remoteHead !== input.expectedPullRequestHeadSha) {
311
+ await fetchRemoteHeadExact(git, input.executionBranch, remoteHead);
312
+ if (!(await isAncestor(git, remoteHead, input.expectedPullRequestHeadSha))) {
313
+ return failure('epic-terminal-execution-remote-head-drift', true, true);
314
+ }
315
+ await git('push', '--porcelain', 'origin', `${input.expectedPullRequestHeadSha}:refs/heads/${input.executionBranch}`);
316
+ }
317
+ if (!remoteHead) {
318
+ await git('push', '--porcelain', 'origin', `${input.expectedPullRequestHeadSha}:refs/heads/${input.executionBranch}`);
319
+ }
320
+ if (await resolveRemoteHeadFresh(git, input.executionBranch) !== input.expectedPullRequestHeadSha) {
321
+ return failure('epic-terminal-execution-publish-unverified', true, true);
322
+ }
323
+ const existingJson = await gh('pr', 'list', '--repo', repositoryUrl, '--state', 'all', '--head', input.executionBranch, '--base', input.originBranch, '--json', 'number,state,headRefName,headRefOid,baseRefName,mergeCommit', '--limit', '100');
324
+ const existing = JSON.parse(existingJson);
325
+ const matching = existing.filter((item) => item.headRefName === input.executionBranch
326
+ && item.baseRefName === input.originBranch && item.headRefOid === input.expectedPullRequestHeadSha
327
+ && (item.state === 'OPEN' || item.state === 'MERGED'));
328
+ if (matching.length > 1)
329
+ return failure('epic-terminal-duplicate-prs', false, true);
330
+ if (typeof matching[0]?.number === 'number')
331
+ return { ok: true, prNumber: matching[0].number };
332
+ if (existing.some((item) => item.state === 'OPEN')) {
333
+ return failure('epic-terminal-stale-pr', false, true);
334
+ }
335
+ const created = await gh('pr', 'create', '--repo', repositoryUrl, '--head', input.executionBranch, '--base', input.originBranch, '--title', `[${input.epicId}] Terminal epic integration`, '--body', `Autonomous terminal integration receipt: ${input.idempotencyKey}`);
336
+ const match = created.match(/\/(\d+)(?:\s*)$/);
337
+ if (!match)
338
+ return failure('epic-terminal-pr-number-unverified', true, true);
339
+ const prNumber = Number(match[1]);
340
+ const createdView = await inspectPullRequest(gh, repository.nameWithOwner, prNumber);
341
+ if (!createdView || createdView.state !== 'OPEN' || createdView.headRefName !== input.executionBranch
342
+ || createdView.baseRefName !== input.originBranch || createdView.headRefOid !== input.expectedPullRequestHeadSha) {
343
+ return failure('epic-terminal-pr-create-unverified', true, true);
344
+ }
345
+ return { ok: true, prNumber };
346
+ }
347
+ catch (error) {
348
+ return failure('epic-terminal-pr-create-denied', true, looksLikeRemotePolicy(error));
349
+ }
350
+ },
351
+ async mergeEpicPullRequest(input) {
352
+ try {
353
+ const repository = await githubOriginRepository(git, gh);
354
+ if (!repository)
355
+ return failure('git-resource-provider-repository-unverified', true, true);
356
+ const candidate = input.candidateQa && verifiedEpicMergeCandidateReceipt(input.candidateAuthority, {
357
+ mergeSha: input.expectedPullRequestHeadSha,
358
+ graphRevision: input.candidateQa.graphRevision,
359
+ originHeadSha: input.expectedOriginHeadSha,
360
+ executionHeadSha: input.expectedStoryHeadSha,
361
+ });
362
+ if (!candidate || candidate !== input.candidateQa) {
363
+ return failure('epic-merge-candidate-authority-required', false, false);
364
+ }
365
+ const before = await inspectPullRequest(gh, repository.nameWithOwner, input.prNumber);
366
+ const freshExecution = await resolveRemoteHeadFreshOptional(git, input.executionBranch);
367
+ const freshOrigin = await resolveRemoteHeadFresh(git, input.originBranch);
368
+ if (!before || before.headRefName !== input.executionBranch || before.baseRefName !== input.originBranch
369
+ || before.headRefOid !== input.expectedPullRequestHeadSha
370
+ || freshExecution && freshExecution !== input.expectedPullRequestHeadSha
371
+ || !(await isAncestor(git, input.expectedOriginHeadSha, input.expectedPullRequestHeadSha))
372
+ || !(await isAncestor(git, input.expectedStoryHeadSha, input.expectedPullRequestHeadSha))) {
373
+ return failure('epic-terminal-pr-revalidation-drift', true, true);
374
+ }
375
+ if (before.state === 'OPEN' && freshOrigin !== input.expectedOriginHeadSha) {
376
+ return failure('epic-terminal-pr-origin-raced', true, true);
377
+ }
378
+ let providerGuard;
379
+ if (before.state === 'OPEN') {
380
+ const guarded = await inspectGitHubBaseGuard(gh, repository.nameWithOwner, input.originBranch, input.expectedPullRequestHeadSha, input.expectedOriginHeadSha, input.nowIso);
381
+ if (!guarded.ok)
382
+ return failure(guarded.reasonCode, true, true);
383
+ providerGuard = guarded.receipt;
384
+ if (await resolveRemoteHeadFresh(git, input.originBranch) !== input.expectedOriginHeadSha) {
385
+ return failure('epic-terminal-pr-origin-raced', true, true);
386
+ }
387
+ await gh('pr', 'merge', String(input.prNumber), '--repo', `https://github.com/${repository.nameWithOwner}`, '--merge', '--match-head-commit', input.expectedPullRequestHeadSha);
388
+ }
389
+ else if (before.state !== 'MERGED') {
390
+ return failure('epic-terminal-pr-not-open-or-merged', false, true);
391
+ }
392
+ else {
393
+ providerGuard = {
394
+ schemaVersion: 1, provider: 'github', mode: 'recovered_exact_tree', source: 'physical_recovery',
395
+ prHeadSha: input.expectedPullRequestHeadSha, originHeadSha: input.expectedOriginHeadSha,
396
+ checkedAt: input.nowIso, publicSafe: true,
397
+ };
398
+ }
399
+ const view = await inspectPullRequest(gh, repository.nameWithOwner, input.prNumber);
400
+ const providerMergeSha = view?.mergeCommit?.oid;
401
+ if (view?.state !== 'MERGED' || !providerMergeSha)
402
+ return failure('epic-terminal-pr-merge-unverified', true, true);
403
+ const postMergeOrigin = await resolveRemoteHeadFresh(git, input.originBranch);
404
+ await fetchRemoteHeadExact(git, input.originBranch, postMergeOrigin);
405
+ if (!(await isAncestor(git, input.expectedStoryHeadSha, postMergeOrigin))
406
+ || !(await isAncestor(git, input.expectedPullRequestHeadSha, postMergeOrigin))
407
+ || !(await isAncestor(git, providerMergeSha, postMergeOrigin))) {
408
+ return failure('epic-terminal-pr-merge-ancestry-unproven', true, true);
409
+ }
410
+ const [candidateTree, pushedTree] = await Promise.all([
411
+ git('rev-parse', `${input.expectedPullRequestHeadSha}^{tree}`),
412
+ git('rev-parse', `${providerMergeSha}^{tree}`),
413
+ ]);
414
+ if (candidateTree !== input.candidateQa.treeSha || pushedTree !== candidateTree) {
415
+ return failure('epic-terminal-pr-merged-tree-mismatch', false, true);
416
+ }
417
+ return { ok: true, mergeSha: input.expectedPullRequestHeadSha, pushedSha: providerMergeSha, providerGuard };
418
+ }
419
+ catch (error) {
420
+ return failure('epic-terminal-pr-merge-denied', true, looksLikeRemotePolicy(error));
421
+ }
422
+ },
423
+ async verifyTerminalReceipt(directive, receipt, nowIso) {
424
+ try {
425
+ if (receipt.physicalStatus !== 'pushed' || !receipt.pushedSha || !receipt.mergeSha) {
426
+ return failure('epic-terminal-physical-revalidation-required', true, false);
427
+ }
428
+ const state = await readEffectiveState(projectRoot, statePath, true);
429
+ const epic = state.epics?.[directive.epicId];
430
+ if (!epic || stringValue(epic.execution_branch) !== directive.executionBranch
431
+ || stringValue(epic.origin_branch) !== directive.originBranch
432
+ || stringValue(epic.graph_revision) !== directive.graphRevision) {
433
+ return failure('epic-terminal-state-revalidation-drift', true, false);
434
+ }
435
+ const executionHead = await git('rev-parse', `refs/heads/${directive.executionBranch}`);
436
+ if (executionHead !== directive.expectedExecutionHeadSha || receipt.executionHeadSha !== executionHead) {
437
+ return failure('epic-terminal-execution-revalidation-drift', true, false);
438
+ }
439
+ const originBinding = isRecord(epic.origin_binding)
440
+ ? epic.origin_binding
441
+ : null;
442
+ if (!originBinding || originBinding.originBranch !== directive.originBranch
443
+ || originBinding.executionBranch !== directive.executionBranch
444
+ || !(await isCommit(git, originBinding.originHeadSha))
445
+ || !(await isAncestor(git, originBinding.originHeadSha, executionHead))) {
446
+ return failure('epic-origin-binding-revalidation-drift', true, false);
447
+ }
448
+ const acceptedCheckpointIds = await acceptedPhysicalCheckpointIds(projectRoot, state, epic, directive.epicId, directive.executionBranch);
449
+ if (isLiveLease(epic.branch_lease) || !sameSet(acceptedCheckpointIds, directive.storyCheckpointIds)) {
450
+ return failure('epic-checkpoint-set-revalidation-drift', true, false);
451
+ }
452
+ const aggregate = isRecord(epic.aggregate_qa_receipt)
453
+ ? epic.aggregate_qa_receipt
454
+ : null;
455
+ if (!validFreshAggregate(aggregate, executionHead, directive.graphRevision, nowIso)
456
+ || aggregate?.receiptRef !== directive.localGates.aggregateQaReceipt.receiptRef) {
457
+ return failure('epic-terminal-aggregate-qa-revalidation-drift', true, false);
458
+ }
459
+ const physicalOrigin = await resolveRemoteHeadFresh(git, directive.originBranch);
460
+ await fetchRemoteHeadExact(git, directive.originBranch, physicalOrigin);
461
+ if (!(await isAncestor(git, executionHead, physicalOrigin))
462
+ || !(await isAncestor(git, receipt.mergeSha, physicalOrigin))
463
+ || !(await isAncestor(git, receipt.pushedSha, physicalOrigin))) {
464
+ return failure('epic-terminal-physical-ancestry-unproven', true, false);
465
+ }
466
+ const binding = { originHeadSha: receipt.baseSha, executionHeadSha: executionHead,
467
+ mergeSha: receipt.mergeSha, graphRevision: directive.graphRevision };
468
+ let authority = candidateAuthorities.get(receipt.mergeSha);
469
+ let candidateQa = verifiedEpicMergeCandidateReceipt(authority, binding);
470
+ if (!candidateQa) {
471
+ const accepted = await executeEpicMergeCandidateQa(projectRoot, binding, nowIso);
472
+ authority = accepted.candidateAuthority;
473
+ candidateQa = accepted.candidateQa;
474
+ candidateAuthorities.set(receipt.mergeSha, authority);
475
+ }
476
+ if (receipt.candidateQa && (receipt.candidateQa.originHeadSha !== candidateQa.originHeadSha
477
+ || receipt.candidateQa.executionHeadSha !== candidateQa.executionHeadSha
478
+ || receipt.candidateQa.graphRevision !== candidateQa.graphRevision
479
+ || receipt.candidateQa.treeSha !== candidateQa.treeSha)) {
480
+ return failure('epic-merge-candidate-receipt-drift', true, false);
481
+ }
482
+ let providerGuard = receipt.providerGuard;
483
+ if (receipt.strategy === 'single_pr') {
484
+ if (!receipt.prNumber)
485
+ return failure('epic-terminal-pr-merge-unverified', true, false);
486
+ const pushedTree = await git('rev-parse', `${receipt.pushedSha}^{tree}`);
487
+ if (pushedTree !== candidateQa.treeSha) {
488
+ return failure('epic-terminal-pr-merged-tree-mismatch', false, false);
489
+ }
490
+ if (providerGuard && !validProviderGuardReceipt(providerGuard, receipt)) {
491
+ return failure('epic-terminal-pr-base-guard-unverifiable', false, false);
492
+ }
493
+ providerGuard ??= {
494
+ schemaVersion: 1, provider: 'github', mode: 'recovered_exact_tree', source: 'physical_recovery',
495
+ prHeadSha: receipt.mergeSha, originHeadSha: receipt.baseSha, checkedAt: nowIso, publicSafe: true,
496
+ };
497
+ }
498
+ else if (providerGuard) {
499
+ return failure('epic-terminal-pr-base-guard-unverifiable', false, false);
500
+ }
501
+ return { ok: true, candidateQa, candidateAuthority: authority, ...(providerGuard ? { providerGuard } : {}) };
502
+ }
503
+ catch {
504
+ return failure('epic-terminal-physical-revalidation-failed', true, false);
505
+ }
506
+ },
507
+ async applyReconciliation(candidate, decision, dryRun) {
508
+ if (decision.action === 'preserve')
509
+ return failure('git-reconciliation-preserve-not-actionable', false, false);
510
+ if (dryRun)
511
+ return { ok: true, outcome: 'dry_run' };
512
+ if (decision.action === 'no_op')
513
+ return { ok: true, outcome: 'already_absent' };
514
+ if (decision.action === 'delete_remote_branch') {
515
+ return deleteRemoteBranchWithCas(candidate, decision, git, gh);
516
+ }
517
+ try {
518
+ const revalidated = await revalidateCandidate({ candidate, decision, git, gh });
519
+ if (!revalidated.ok)
520
+ return failure(revalidated.reasonCode, true, false);
521
+ if (revalidated.alreadyAbsent)
522
+ return { ok: true, outcome: 'already_absent' };
523
+ if (decision.action === 'delete_local_branch') {
524
+ await git('update-ref', '-d', `refs/heads/${candidate.branchName}`, candidate.headSha);
525
+ }
526
+ else if (decision.action === 'close_pull_request') {
527
+ if (!candidate.prNumber)
528
+ return failure('git-reconciliation-pr-number-missing', false, false);
529
+ const repository = await githubOriginRepository(git, gh);
530
+ if (!repository)
531
+ return failure('git-resource-provider-repository-unverified', true, true);
532
+ const repositoryUrl = `https://github.com/${repository.nameWithOwner}`;
533
+ const marker = `neocortex-reconciliation:${createHash('sha256').update(candidate.resourceId).digest('hex')}`;
534
+ const commentView = JSON.parse(await gh('pr', 'view', String(candidate.prNumber), '--repo', repositoryUrl, '--json', 'comments'));
535
+ if (!isRecord(commentView) || !Array.isArray(commentView.comments) || commentView.comments.length > 1000
536
+ || commentView.comments.some((item) => !isRecord(item) || typeof item.body !== 'string')) {
537
+ return failure('git-reconciliation-pr-comments-unverified', true, true);
538
+ }
539
+ if (!commentView.comments.some((item) => String(item.body).includes(marker))) {
540
+ await gh('pr', 'comment', String(candidate.prNumber), '--repo', repositoryUrl, '--body', `Neocortex reconciliation verified managed ownership and integrated content; requesting closure. [${marker}]`);
541
+ }
542
+ // Commenting is an external round trip: repeat head/base/protection
543
+ // proof before closure, then verify closure before releasing branches.
544
+ const beforeClose = await revalidateCandidate({ candidate, decision, git, gh });
545
+ if (!beforeClose.ok)
546
+ return failure(beforeClose.reasonCode, true, false);
547
+ if (beforeClose.alreadyAbsent)
548
+ return { ok: true, outcome: 'already_absent' };
549
+ await gh('pr', 'close', String(candidate.prNumber), '--repo', repositoryUrl);
550
+ const closed = await revalidateCandidate({ candidate, decision, git, gh });
551
+ if (!closed.ok)
552
+ return failure(closed.reasonCode, true, false);
553
+ if (!closed.alreadyAbsent)
554
+ return failure('git-reconciliation-pr-close-unverified', true, true);
555
+ }
556
+ return { ok: true, outcome: 'applied' };
557
+ }
558
+ catch {
559
+ // Provider 404/auth/transport text does not prove the resource absent.
560
+ return failure('git-reconciliation-effect-failed', true, false);
561
+ }
562
+ },
563
+ async persist(input) {
564
+ try {
565
+ let blocked;
566
+ await mutateGitLifecycleRuntime(projectRoot, (runtime) => {
567
+ const epic = ensureRuntimeEpic(runtime, input.terminalReceipt.epicId);
568
+ const existing = Array.isArray(epic.git_reconciliation_receipts)
569
+ ? epic.git_reconciliation_receipts.filter(isRecord)
570
+ : [];
571
+ const byKey = new Map(existing.map((item) => [item.idempotencyKey, item]));
572
+ for (const receipt of input.reconciliationReceipts) {
573
+ if (!successfulReconciliation(byKey.get(receipt.idempotencyKey)))
574
+ byKey.set(receipt.idempotencyKey, receipt);
575
+ }
576
+ const currentReceipt = isRecord(epic.terminal_git_receipt)
577
+ ? epic.terminal_git_receipt
578
+ : null;
579
+ const terminalReceipt = reconcileTerminalReceipt(currentReceipt, input.terminalReceipt);
580
+ if (terminalReceipt.kind === 'blocked') {
581
+ blocked = terminalReceipt.reasonCode;
582
+ return;
583
+ }
584
+ epic.terminal_git_receipt = terminalReceipt.receipt;
585
+ epic.git_reconciliation_receipts = [...byKey.values()];
586
+ epic.physicalMergeStatus = input.terminalReceipt.physicalStatus === 'pushed' ? 'merged' : input.terminalReceipt.physicalStatus;
587
+ epic.pr_number = input.terminalReceipt.prNumber ?? epic.pr_number ?? null;
588
+ epic.git_reconciliation_debt = dedupePreserved(epic.git_reconciliation_debt, input.preservedDecisions);
589
+ });
590
+ if (blocked)
591
+ return failure(blocked, false, false);
592
+ return { ok: true };
593
+ }
594
+ catch {
595
+ return failure('epic-terminal-state-persist-failed', true, false);
596
+ }
597
+ },
598
+ async persistReconciliation(input) {
599
+ try {
600
+ await mutateGitLifecycleRuntime(projectRoot, (runtime) => {
601
+ const epic = ensureRuntimeEpic(runtime, input.epicId);
602
+ const existing = Array.isArray(epic.git_reconciliation_receipts)
603
+ ? epic.git_reconciliation_receipts.filter(isRecord)
604
+ : [];
605
+ const byKey = new Map(existing.map((item) => [item.idempotencyKey, item]));
606
+ for (const receipt of input.reconciliationReceipts) {
607
+ if (!successfulReconciliation(byKey.get(receipt.idempotencyKey)))
608
+ byKey.set(receipt.idempotencyKey, receipt);
609
+ }
610
+ epic.git_reconciliation_receipts = [...byKey.values()];
611
+ epic.git_reconciliation_debt = dedupePreserved(epic.git_reconciliation_debt, input.preservedDecisions);
612
+ });
613
+ return { ok: true };
614
+ }
615
+ catch {
616
+ return failure('git-reconciliation-state-persist-failed', true, false);
617
+ }
618
+ },
619
+ };
620
+ }
621
+ /** Bind provider identity to origin; ambient GH_REPO must never redirect deletion. */
622
+ async function githubOriginRepository(git, gh) {
623
+ try {
624
+ const origin = await git('remote', 'get-url', 'origin');
625
+ const nameWithOwner = origin.match(/^https:\/\/github\.com\/([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+?)(?:\.git)?\/?$/)?.[1]
626
+ ?? origin.match(/^git@github\.com:([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+?)(?:\.git)?$/)?.[1];
627
+ if (!nameWithOwner)
628
+ return null;
629
+ const repository = JSON.parse(await gh('repo', 'view', `https://github.com/${nameWithOwner}`, '--json', 'id,nameWithOwner,url'));
630
+ if (repository.nameWithOwner !== nameWithOwner || repository.url !== `https://github.com/${nameWithOwner}`
631
+ || typeof repository.id !== 'string' || !/^[A-Za-z0-9_=-]{1,256}$/.test(repository.id))
632
+ return null;
633
+ return { id: repository.id, nameWithOwner };
634
+ }
635
+ catch {
636
+ return null;
637
+ }
638
+ }
639
+ async function deleteRemoteBranchWithCas(candidate, decision, git, gh) {
640
+ try {
641
+ if (candidate.kind !== 'remote_branch' || decision.resourceId !== candidate.resourceId
642
+ || !candidate.baseBranch || candidate.baseBranch === candidate.branchName
643
+ || !safeBranch(candidate.branchName) || !safeBranch(candidate.baseBranch)
644
+ || !/^[a-f0-9]{40}$/.test(candidate.headSha) || !/^[a-f0-9]{40}$/.test(candidate.integrationHeadSha)) {
645
+ return failure('git-reconciliation-candidate-no-longer-safe', false, false);
646
+ }
647
+ const repository = await githubOriginRepository(git, gh);
648
+ if (!repository)
649
+ return failure('git-resource-remote-delete-cas-unavailable', false, false);
650
+ const currentHead = await resolveRemoteHeadFreshOptional(git, candidate.branchName);
651
+ if (!currentHead)
652
+ return { ok: true, outcome: 'already_absent' };
653
+ const revalidated = await revalidateCandidate({ candidate, decision, git, gh });
654
+ if (!revalidated.ok)
655
+ return failure(revalidated.reasonCode, true, false);
656
+ // Recheck provider identity after revalidation, which itself issues queries.
657
+ const freshRepository = await githubOriginRepository(git, gh);
658
+ if (freshRepository?.id !== repository.id)
659
+ return failure('git-resource-provider-repository-raced', true, false);
660
+ const mutationId = createHash('sha256').update([
661
+ 'managed-remote-delete-v1', repository.id, candidate.branchName, candidate.headSha,
662
+ candidate.baseBranch, candidate.integrationHeadSha,
663
+ ].join('\0')).digest('hex');
664
+ const update = (name, before, after) => `{name:${JSON.stringify(`refs/heads/${name}`)},beforeOid:${JSON.stringify(before)},afterOid:${JSON.stringify(after)},force:false}`;
665
+ const query = `mutation{updateRefs(input:{repositoryId:${JSON.stringify(repository.id)},clientMutationId:${JSON.stringify(mutationId)},refUpdates:[`
666
+ + update(candidate.branchName, candidate.headSha, '0'.repeat(40)) + ','
667
+ + update(candidate.baseBranch, candidate.integrationHeadSha, candidate.integrationHeadSha)
668
+ + ']}){clientMutationId}}';
669
+ const result = JSON.parse(await gh('api', 'graphql', '--hostname', 'github.com', '-f', `query=${query}`));
670
+ if (result.errors || result.data?.updateRefs?.clientMutationId !== mutationId) {
671
+ return failure('git-resource-remote-delete-cas-unverified', true, true);
672
+ }
673
+ if (await resolveRemoteHeadFreshOptional(git, candidate.branchName)) {
674
+ return failure('git-resource-remote-delete-recreated-or-unverified', true, false);
675
+ }
676
+ return { ok: true, outcome: 'applied' };
677
+ }
678
+ catch {
679
+ return failure('git-resource-remote-delete-cas-rejected', true, true);
680
+ }
681
+ }
682
+ async function revalidateCandidate(input) {
683
+ const { candidate, decision, git, gh } = input;
684
+ if (!decision.managed || !candidate.providerVerified || candidate.current || candidate.origin || candidate.protected
685
+ || candidate.lifecycle === 'active' || candidate.hasExclusiveCommits || candidate.worktreeActive) {
686
+ return { ok: false, reasonCode: 'git-reconciliation-candidate-no-longer-safe' };
687
+ }
688
+ const current = await git('symbolic-ref', '--quiet', '--short', 'HEAD').catch(() => '');
689
+ const worktrees = await inspectWorktreeBranches(git);
690
+ if (current === candidate.branchName || worktrees.has(candidate.branchName)) {
691
+ return { ok: false, reasonCode: 'git-resource-worktree-active' };
692
+ }
693
+ if (candidate.kind === 'local_branch') {
694
+ const head = await resolveOptionalRef(git, `refs/heads/${candidate.branchName}`);
695
+ if (!head)
696
+ return { ok: true, alreadyAbsent: true };
697
+ if (head !== candidate.headSha)
698
+ return { ok: false, reasonCode: 'git-resource-expected-oid-raced' };
699
+ if (!candidate.baseBranch || await resolveRemoteHeadFresh(git, candidate.baseBranch) !== candidate.integrationHeadSha
700
+ || !(await isAncestor(git, head, candidate.integrationHeadSha))) {
701
+ return { ok: false, reasonCode: 'git-resource-integration-unproven' };
702
+ }
703
+ return { ok: true };
704
+ }
705
+ if (candidate.kind === 'remote_branch') {
706
+ const head = await resolveRemoteHeadFreshOptional(git, candidate.branchName);
707
+ if (!head)
708
+ return { ok: true };
709
+ if (head !== candidate.headSha)
710
+ return { ok: false, reasonCode: 'git-resource-expected-oid-raced' };
711
+ const repository = await githubOriginRepository(git, gh);
712
+ if (!repository)
713
+ return { ok: false, reasonCode: 'git-resource-provider-repository-unverified' };
714
+ if (await inspectRemoteBranchProtection(gh, repository.nameWithOwner, candidate.branchName) !== 'unprotected') {
715
+ return { ok: false, reasonCode: 'git-resource-protected' };
716
+ }
717
+ if (!candidate.baseBranch || await resolveRemoteHeadFresh(git, candidate.baseBranch) !== candidate.integrationHeadSha) {
718
+ return { ok: false, reasonCode: 'git-resource-integration-unproven' };
719
+ }
720
+ await git('fetch', '--quiet', '--no-tags', 'origin', `refs/heads/${candidate.branchName}`);
721
+ if (await git('rev-parse', 'FETCH_HEAD') !== candidate.headSha
722
+ || !(await isAncestor(git, candidate.headSha, candidate.integrationHeadSha))) {
723
+ return { ok: false, reasonCode: 'git-resource-integration-unproven' };
724
+ }
725
+ return { ok: true };
726
+ }
727
+ if (!candidate.prNumber || !candidate.baseBranch)
728
+ return { ok: false, reasonCode: 'git-reconciliation-pr-proof-missing' };
729
+ const repository = await githubOriginRepository(git, gh);
730
+ if (!repository)
731
+ return { ok: false, reasonCode: 'git-resource-provider-repository-unverified' };
732
+ const pr = await inspectPullRequest(gh, repository.nameWithOwner, candidate.prNumber);
733
+ if (!pr || pr.headRefName !== candidate.branchName || pr.baseRefName !== candidate.baseBranch || pr.headRefOid !== candidate.headSha) {
734
+ return { ok: false, reasonCode: 'git-resource-expected-oid-raced' };
735
+ }
736
+ // A positively observed closed resource requires no effect, even if its
737
+ // integrated branch has since been removed. Unknown/error is not absence.
738
+ if (pr.state === 'CLOSED' || pr.state === 'MERGED')
739
+ return { ok: true, alreadyAbsent: true };
740
+ if (await inspectRemoteBranchProtection(gh, repository.nameWithOwner, candidate.branchName) !== 'unprotected') {
741
+ return { ok: false, reasonCode: 'git-resource-protected' };
742
+ }
743
+ const remoteHead = await resolveRemoteHeadFreshOptional(git, candidate.branchName);
744
+ if (!pr || pr.state !== 'OPEN' || pr.headRefName !== candidate.branchName || pr.baseRefName !== candidate.baseBranch
745
+ || pr.headRefOid !== candidate.headSha || remoteHead !== candidate.headSha) {
746
+ return { ok: false, reasonCode: 'git-resource-expected-oid-raced' };
747
+ }
748
+ await git('fetch', '--quiet', '--no-tags', 'origin', `refs/heads/${candidate.branchName}`);
749
+ if (await git('rev-parse', 'FETCH_HEAD') !== candidate.headSha
750
+ || await resolveRemoteHeadFresh(git, candidate.baseBranch) !== candidate.integrationHeadSha
751
+ || !(await isAncestor(git, candidate.headSha, candidate.integrationHeadSha))) {
752
+ return { ok: false, reasonCode: 'git-resource-integration-unproven' };
753
+ }
754
+ return { ok: true };
755
+ }
756
+ async function buildCandidates(input) {
757
+ const candidates = [];
758
+ const activeWorktreeBranches = await inspectWorktreeBranches(input.git);
759
+ const ownership = collectGitResourceOwnership(input.state);
760
+ const repository = await githubOriginRepository(input.git, input.gh);
761
+ const parseRefs = (output) => {
762
+ const entries = output.split('\n').filter(Boolean).map((line) => line.split(/\s+/));
763
+ if (entries.length > GIT_INVENTORY_REF_LIMIT)
764
+ throw new Error('git-reconciliation-ref-inventory-limit');
765
+ const map = new Map();
766
+ for (const [sha, ref] of entries) {
767
+ const branch = ref?.replace(/^refs\/heads\//, '');
768
+ if (!branch || !safeBranch(branch) || !/^[a-f0-9]{40,64}$/.test(sha ?? '') || map.has(branch)) {
769
+ throw new Error('git-reconciliation-ref-inventory-invalid');
770
+ }
771
+ map.set(branch, sha);
772
+ }
773
+ return map;
774
+ };
775
+ const local = parseRefs(await input.git('for-each-ref', `--count=${GIT_INVENTORY_REF_LIMIT + 1}`, '--format=%(objectname) %(refname)', 'refs/heads'));
776
+ const remote = parseRefs(await input.git('ls-remote', '--heads', 'origin'));
777
+ const managedBranches = new Set([...ownership.claims.keys()].filter(safeBranch));
778
+ const prs = repository
779
+ ? await listRepositoryPullRequests(input.gh, repository.nameWithOwner, managedBranches)
780
+ : [];
781
+ const origins = new Map([[input.directive.originBranch, input.originHeadSha]]);
782
+ const originHead = async (branch) => {
783
+ if (origins.has(branch))
784
+ return origins.get(branch);
785
+ const head = remote.get(branch);
786
+ if (!head)
787
+ return '';
788
+ await fetchRemoteHeadExact(input.git, branch, head);
789
+ origins.set(branch, head);
790
+ return head;
791
+ };
792
+ const ancestry = new Map();
793
+ const ancestor = async (head, base) => {
794
+ const key = `${head}:${base}`;
795
+ if (!ancestry.has(key))
796
+ ancestry.set(key, Boolean(head && base) && await isAncestor(input.git, head, base));
797
+ return ancestry.get(key);
798
+ };
799
+ // PRs can corroborate a branch already claimed by durable Neocortex state,
800
+ // but an arbitrary repository PR must never create an ownership candidate.
801
+ // Keeping the branch set independent from PR inventory also prevents large
802
+ // repository histories from exhausting the managed-ref bound.
803
+ const branches = new Set([...local.keys(), ...remote.keys(), ...ownership.claims.keys()]);
804
+ if (branches.size > GIT_INVENTORY_REF_LIMIT)
805
+ throw new Error('git-reconciliation-ref-inventory-limit');
806
+ for (const branchName of [...branches].sort()) {
807
+ if (!safeBranch(branchName))
808
+ continue;
809
+ const claims = ownership.claims.get(branchName) ?? [];
810
+ const uniqueOwners = new Set(claims.map((claim) => `${claim.epicId}:${claim.origin}`));
811
+ const baseBranch = uniqueOwners.size === 1 ? claims[0].origin : input.directive.originBranch;
812
+ const integrationHeadSha = await originHead(baseBranch);
813
+ const active = claims.length === 0 || claims.some((claim) => claim.active);
814
+ const localHead = local.get(branchName), remoteHead = remote.get(branchName);
815
+ if (remoteHead)
816
+ await fetchRemoteHeadExact(input.git, branchName, remoteHead);
817
+ const protection = repository && remoteHead
818
+ ? await inspectRemoteBranchProtection(input.gh, repository.nameWithOwner, branchName) : 'unknown';
819
+ const evidenceFor = async (head) => {
820
+ if (uniqueOwners.size !== 1)
821
+ return [];
822
+ const evidence = new Set();
823
+ for (const claim of claims)
824
+ for (const proof of claim.proofs) {
825
+ if (proof.head !== head)
826
+ continue;
827
+ if (proof.mergeSha && (!proof.pushedSha || !(await ancestor(head, proof.mergeSha))
828
+ || !(await ancestor(proof.mergeSha, proof.pushedSha)) || !(await ancestor(proof.pushedSha, integrationHeadSha))))
829
+ continue;
830
+ proof.evidence.forEach((item) => evidence.add(item));
831
+ }
832
+ return [...evidence];
833
+ };
834
+ const common = {
835
+ schemaVersion: 1, branchName, baseBranch, integrationHeadSha,
836
+ lifecycle: active ? 'active' : 'integrated',
837
+ current: branchName === input.currentBranch,
838
+ origin: ownership.origins.has(branchName) || branchName === input.directive.originBranch,
839
+ worktreeActive: activeWorktreeBranches.has(branchName), contentEquivalent: false, publicSafe: true,
840
+ };
841
+ for (const [kind, head] of [['local_branch', localHead], ['remote_branch', remoteHead]]) {
842
+ if (!head)
843
+ continue;
844
+ const resourceId = `${kind}:${createHash('sha256').update(branchName).digest('hex')}:${head}`;
845
+ const reachable = await ancestor(head, integrationHeadSha);
846
+ candidates.push({ ...common, resourceId, kind, headSha: head, ownershipEvidence: await evidenceFor(head),
847
+ // Local-only refs have no provider policy; matching remote protected refs
848
+ // are protected on both sides. Unknown remote policy fails closed.
849
+ protected: Boolean(remoteHead) && protection !== 'unprotected',
850
+ providerVerified: kind === 'local_branch' ? true : Boolean(repository) && protection !== 'unknown',
851
+ ...(kind === 'remote_branch' && repository ? { remoteDeletionCas: 'github-update-refs-v1' } : {}),
852
+ commitsReachable: reachable, hasExclusiveCommits: !reachable,
853
+ previouslyReconciled: input.receiptIds.has(resourceId), });
854
+ }
855
+ for (const pr of prs.filter((item) => item.headRefName === branchName)) {
856
+ const headBaseMatch = pr.baseRefName === baseBranch && pr.sameRepository;
857
+ const evidence = await evidenceFor(pr.headRefOid);
858
+ if (headBaseMatch && evidence.includes('managed_metadata'))
859
+ evidence.push('pr_head_base_match');
860
+ const resourceId = `pr:${pr.number}:${pr.headRefOid}:${createHash('sha256').update(pr.baseRefName).digest('hex')}`;
861
+ const reachable = await ancestor(pr.headRefOid, integrationHeadSha);
862
+ candidates.push({ ...common, resourceId, kind: 'pull_request', prNumber: pr.number, headSha: pr.headRefOid,
863
+ lifecycle: pr.state !== 'OPEN' ? 'already_absent' : active ? 'active' : 'superseded',
864
+ ownershipEvidence: evidence, providerVerified: headBaseMatch,
865
+ protected: protection !== 'unprotected', commitsReachable: reachable, hasExclusiveCommits: !reachable,
866
+ previouslyReconciled: input.receiptIds.has(resourceId),
867
+ });
868
+ }
869
+ }
870
+ assertReconciliationCapacity(input.epic, candidates);
871
+ return candidates;
872
+ }
873
+ /** Preflight the whole batch before any ref/PR effect. Never trim old receipts. */
874
+ function assertReconciliationCapacity(epic, candidates) {
875
+ const receipts = new Set((Array.isArray(epic.git_reconciliation_receipts) ? epic.git_reconciliation_receipts : [])
876
+ .filter(isRecord).map((item) => stringValue(item.idempotencyKey)));
877
+ const debt = new Set((Array.isArray(epic.git_reconciliation_debt) ? epic.git_reconciliation_debt : [])
878
+ .filter(isRecord).map((item) => stringValue(item.resourceId)));
879
+ const prBranches = new Set(candidates.filter((item) => item.kind === 'pull_request'
880
+ && classifyGitReconciliationCandidate(item).action === 'close_pull_request').map((item) => item.branchName));
881
+ for (const candidate of candidates) {
882
+ const decision = classifyGitReconciliationCandidate(candidate);
883
+ if (decision.action === 'preserve')
884
+ debt.add(candidate.resourceId);
885
+ else {
886
+ receipts.add(`reconciliation:v2:${createHash('sha256').update([candidate.resourceId, decision.action].join('\0')).digest('hex')}`);
887
+ // A failed PR close defers related branch effects into preserved debt.
888
+ if (candidate.kind !== 'pull_request' && prBranches.has(candidate.branchName))
889
+ debt.add(candidate.resourceId);
890
+ }
891
+ }
892
+ if (receipts.size > 1024)
893
+ throw new Error('git-reconciliation-receipt-capacity');
894
+ if (debt.size > 1024)
895
+ throw new Error('git-reconciliation-debt-capacity');
896
+ }
897
+ function publicInventoryReason(error) {
898
+ const reasons = new Set([
899
+ 'git-reconciliation-state-inventory-limit', 'git-reconciliation-ref-inventory-limit',
900
+ 'git-reconciliation-ref-inventory-invalid', 'git-reconciliation-pr-inventory-limit',
901
+ 'git-reconciliation-pr-inventory-invalid', 'git-reconciliation-receipt-capacity',
902
+ 'git-reconciliation-debt-capacity',
903
+ ]);
904
+ return error instanceof Error && reasons.has(error.message) ? error.message : undefined;
905
+ }
906
+ async function listRepositoryPullRequests(gh, repository, managedBranches) {
907
+ const repositoryOwner = repository.split('/')[0];
908
+ if (!repositoryOwner || !/^[A-Za-z0-9_.-]+$/.test(repositoryOwner)) {
909
+ throw new Error('git-reconciliation-pr-inventory-invalid');
910
+ }
911
+ const result = [];
912
+ const seen = new Set();
913
+ const pageSize = 100;
914
+ const maxPagesPerBranch = Math.floor(GIT_INVENTORY_PR_LIMIT / pageSize) + 1;
915
+ for (const branch of [...managedBranches].sort()) {
916
+ if (!safeBranch(branch))
917
+ throw new Error('git-reconciliation-pr-inventory-invalid');
918
+ const head = encodeURIComponent(`${repositoryOwner}:${branch}`);
919
+ for (let page = 1; page <= maxPagesPerBranch; page += 1) {
920
+ const endpoint = `repos/${repository}/pulls?state=all&head=${head}&per_page=${pageSize}&page=${page}`;
921
+ const items = JSON.parse(await gh('api', endpoint, '--hostname', 'github.com'));
922
+ if (!Array.isArray(items) || items.length > pageSize) {
923
+ throw new Error('git-reconciliation-pr-inventory-limit');
924
+ }
925
+ for (const item of items) {
926
+ if (!isRecord(item) || !Number.isSafeInteger(item.number) || Number(item.number) <= 0 || seen.has(Number(item.number))
927
+ || !isRecord(item.head) || !isRecord(item.base) || stringValue(item.head.ref) !== branch
928
+ || !safeBranch(stringValue(item.head.ref)) || !safeBranch(stringValue(item.base.ref))
929
+ || !/^[a-f0-9]{40,64}$/.test(stringValue(item.head.sha))
930
+ || !['open', 'closed'].includes(stringValue(item.state)))
931
+ throw new Error('git-reconciliation-pr-inventory-invalid');
932
+ seen.add(Number(item.number));
933
+ result.push({ number: Number(item.number), state: stringValue(item.state).toUpperCase(),
934
+ headRefName: stringValue(item.head.ref), headRefOid: stringValue(item.head.sha), baseRefName: stringValue(item.base.ref),
935
+ sameRepository: isRecord(item.head.repo) && isRecord(item.base.repo)
936
+ && item.head.repo.full_name === repository && item.base.repo.full_name === repository,
937
+ });
938
+ if (result.length > GIT_INVENTORY_PR_LIMIT) {
939
+ throw new Error('git-reconciliation-pr-inventory-limit');
940
+ }
941
+ }
942
+ if (items.length < pageSize)
943
+ break;
944
+ }
945
+ }
946
+ return result;
947
+ }
948
+ function successfulReconciliation(value) {
949
+ return isRecord(value) && (value.outcome === 'applied' || value.outcome === 'already_absent');
950
+ }
951
+ async function recoverDirectPhysicalReceipt(input) {
952
+ try {
953
+ const matches = (await input.git('log', input.originHeadSha, '--format=%H', '--fixed-strings', `--grep=Neocortex-Idempotency: ${input.directive.idempotencyKey}`)).split('\n').filter((sha) => /^[a-f0-9]{40,64}$/i.test(sha));
954
+ if (matches.length !== 1)
955
+ return null;
956
+ const mergeSha = matches[0];
957
+ const parents = (await input.git('rev-list', '--parents', '-n', '1', mergeSha)).split(/\s+/);
958
+ const message = await input.git('show', '-s', '--format=%B', mergeSha);
959
+ const [subject] = message.split('\n');
960
+ const expectedSubject = `merge(${input.directive.epicId}): integrate ${input.directive.executionBranch} into ${input.directive.originBranch}`;
961
+ if (parents.length !== 3 || parents[2] !== input.executionHeadSha || subject !== expectedSubject)
962
+ return null;
963
+ const trailers = new Set(message.split('\n').map((line) => line.trim()));
964
+ for (const trailer of [
965
+ `Neocortex-Epic: ${input.directive.epicId}`,
966
+ `Neocortex-Origin-Branch: ${input.directive.originBranch}`,
967
+ `Neocortex-Execution-Branch: ${input.directive.executionBranch}`,
968
+ `Neocortex-Execution-Head: ${input.executionHeadSha}`,
969
+ `Neocortex-Origin-Base: ${parents[1]}`,
970
+ `Neocortex-Graph-Revision: ${input.directive.graphRevision}`,
971
+ `Neocortex-Aggregate-QA: ${input.directive.localGates.aggregateQaReceipt.receiptRef}`,
972
+ `Neocortex-Idempotency: ${input.directive.idempotencyKey}`,
973
+ ])
974
+ if (!trailers.has(trailer))
975
+ return null;
976
+ const completedAt = await input.git('show', '-s', '--format=%cI', mergeSha);
977
+ return {
978
+ schemaVersion: 1, epicId: input.directive.epicId, executionBranch: input.directive.executionBranch,
979
+ originBranch: input.directive.originBranch, baseSha: parents[1], executionHeadSha: input.executionHeadSha,
980
+ mergeSha, pushedSha: mergeSha, strategy: 'direct', physicalStatus: 'pushed',
981
+ localGateReceiptRefs: input.directive.localGates.receiptRefs, idempotencyKey: input.directive.idempotencyKey,
982
+ attemptStartedAt: completedAt, completedAt, retryEligible: false,
983
+ reasonCodes: ['epic-terminal-recovered-physical-push'], publicSafe: true,
984
+ };
985
+ }
986
+ catch {
987
+ return null;
988
+ }
989
+ }
990
+ async function inspectRemoteBranchProtection(gh, nameWithOwner, branchName) {
991
+ try {
992
+ if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(nameWithOwner))
993
+ return 'unknown';
994
+ const value = await gh('api', `repos/${nameWithOwner}/branches/${encodeURIComponent(branchName)}`, '--hostname', 'github.com', '--jq', '.protected');
995
+ return value === 'false' ? 'unprotected' : value === 'true' ? 'protected' : 'unknown';
996
+ }
997
+ catch {
998
+ return 'unknown';
999
+ }
1000
+ }
1001
+ async function inspectPullRequest(gh, nameWithOwner, prNumber) {
1002
+ try {
1003
+ const value = JSON.parse(await gh('pr', 'view', String(prNumber), '--repo', `https://github.com/${nameWithOwner}`, '--json', 'state,headRefName,headRefOid,baseRefName,mergeCommit'));
1004
+ if (![value.state, value.headRefName, value.headRefOid, value.baseRefName].every((item) => typeof item === 'string'))
1005
+ return null;
1006
+ return value;
1007
+ }
1008
+ catch {
1009
+ return null;
1010
+ }
1011
+ }
1012
+ /**
1013
+ * GitHub protects expectedHeadOid but has no expected base OID on PR merge.
1014
+ * A strict up-to-date rule closes that base race: the tested candidate already
1015
+ * contains the exact base, and GitHub refuses it if the base advances. Merge
1016
+ * queues are a separate candidate/CI lifecycle and remain fail-closed here.
1017
+ */
1018
+ async function inspectGitHubBaseGuard(gh, nameWithOwner, originBranch, prHeadSha, originHeadSha, checkedAt) {
1019
+ if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(nameWithOwner) || !safeBranch(originBranch)
1020
+ || !/^[a-f0-9]{40,64}$/i.test(prHeadSha) || !/^[a-f0-9]{40,64}$/i.test(originHeadSha)
1021
+ || Number.isNaN(Date.parse(checkedAt))) {
1022
+ return { ok: false, reasonCode: 'epic-terminal-pr-base-guard-unverifiable' };
1023
+ }
1024
+ let rules;
1025
+ try {
1026
+ const raw = JSON.parse(await gh('api', `repos/${nameWithOwner}/rules/branches/${encodeURIComponent(originBranch)}`, '--hostname', 'github.com', '--paginate', '--slurp'));
1027
+ const flattened = Array.isArray(raw) && raw.every(Array.isArray) ? raw.flat() : raw;
1028
+ if (!Array.isArray(flattened) || flattened.length > 256 || flattened.some((item) => !isRecord(item))) {
1029
+ return { ok: false, reasonCode: 'epic-terminal-pr-base-guard-unverifiable' };
1030
+ }
1031
+ rules = flattened;
1032
+ }
1033
+ catch {
1034
+ return { ok: false, reasonCode: 'epic-terminal-pr-base-guard-unverifiable' };
1035
+ }
1036
+ if (rules.some((rule) => rule.type === 'merge_queue')) {
1037
+ return { ok: false, reasonCode: 'epic-terminal-pr-merge-queue-local-gate-required' };
1038
+ }
1039
+ const rulesetStrict = rules.some((rule) => rule.type === 'required_status_checks'
1040
+ && isRecord(rule.parameters) && rule.parameters.strict_required_status_checks_policy === true);
1041
+ let branchProtectionStrict = false;
1042
+ try {
1043
+ const classic = JSON.parse(await gh('api', `repos/${nameWithOwner}/branches/${encodeURIComponent(originBranch)}/protection/required_status_checks`, '--hostname', 'github.com'));
1044
+ if (!isRecord(classic) || typeof classic.strict !== 'boolean') {
1045
+ return { ok: false, reasonCode: 'epic-terminal-pr-base-guard-unverifiable' };
1046
+ }
1047
+ branchProtectionStrict = classic.strict;
1048
+ }
1049
+ catch (error) {
1050
+ if (!isProviderNotFound(error)) {
1051
+ return { ok: false, reasonCode: 'epic-terminal-pr-base-guard-unverifiable' };
1052
+ }
1053
+ }
1054
+ if (!rulesetStrict && !branchProtectionStrict) {
1055
+ return { ok: false, reasonCode: 'epic-terminal-pr-strict-base-guard-required' };
1056
+ }
1057
+ const source = rulesetStrict && branchProtectionStrict
1058
+ ? 'branch_protection_and_ruleset'
1059
+ : rulesetStrict ? 'ruleset' : 'branch_protection';
1060
+ return {
1061
+ ok: true,
1062
+ receipt: {
1063
+ schemaVersion: 1, provider: 'github', mode: 'strict_up_to_date_expected_head', source,
1064
+ prHeadSha, originHeadSha, checkedAt, publicSafe: true,
1065
+ },
1066
+ };
1067
+ }
1068
+ function isProviderNotFound(error) {
1069
+ return error instanceof Error && /(?:HTTP\s*)?404\b|not found/i.test(error.message);
1070
+ }
1071
+ function validProviderGuardReceipt(value, terminal) {
1072
+ const modeSourceValid = value.mode === 'recovered_exact_tree'
1073
+ ? value.source === 'physical_recovery'
1074
+ : value.mode === 'strict_up_to_date_expected_head'
1075
+ && ['branch_protection', 'ruleset', 'branch_protection_and_ruleset'].includes(value.source);
1076
+ return value.schemaVersion === 1 && value.provider === 'github' && modeSourceValid
1077
+ && value.publicSafe === true && !Number.isNaN(Date.parse(value.checkedAt))
1078
+ && value.prHeadSha === terminal.mergeSha && value.originHeadSha === terminal.baseSha;
1079
+ }
1080
+ async function command(binary, args, cwd) {
1081
+ const result = await execFileAsync(binary, [...args], { cwd, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 });
1082
+ return result.stdout.trim();
1083
+ }
1084
+ async function readEffectiveState(projectRoot, statePath, requiredRuntime = false) {
1085
+ const tracked = JSON.parse(await readFile(statePath, 'utf8'));
1086
+ return applyGitLifecycleRuntimeOverlay(tracked, await readGitLifecycleRuntime(projectRoot, { required: requiredRuntime }));
1087
+ }
1088
+ function validFreshAggregate(value, executionHeadSha, graphRevision, nowIso) {
1089
+ if (!value || value.schemaVersion !== 1 || value.evidenceVersion !== 'p205-execution-v2'
1090
+ || value.producer !== 'local-yolo-tdd' || value.contract !== 'P205-CI-02'
1091
+ || value.command !== P205_COMPLETE_COMMAND || value.verdict !== 'passed'
1092
+ || value.executionHeadSha !== executionHeadSha || value.graphRevision !== graphRevision
1093
+ || !/^[a-f0-9]{64}$/i.test(value.manifestDigest ?? '')
1094
+ || !/^[a-f0-9]{64}$/i.test(value.resultDigest ?? '') || value.gateIds.length === 0)
1095
+ return false;
1096
+ const expectedRef = `local-yolo-tdd:${createHash('sha256').update([
1097
+ 'epic-aggregate-p205-execution-v2', P205_COMPLETE_COMMAND,
1098
+ executionHeadSha, graphRevision, value.manifestDigest, value.gateIds.join(','), value.resultDigest,
1099
+ ].join('\0')).digest('hex')}`;
1100
+ if (value.receiptRef !== expectedRef)
1101
+ return false;
1102
+ const checkedAt = Date.parse(value.checkedAt);
1103
+ const now = Date.parse(nowIso);
1104
+ return Number.isFinite(checkedAt) && Number.isFinite(now)
1105
+ && now - checkedAt <= 30 * 60 * 1000 && checkedAt - now <= 5 * 60 * 1000;
1106
+ }
1107
+ async function resolveRemoteHeadFresh(git, branch) {
1108
+ const sha = await resolveRemoteHeadFreshOptional(git, branch);
1109
+ if (!sha)
1110
+ throw new Error('origin-ref-missing');
1111
+ return sha;
1112
+ }
1113
+ async function resolveRemoteHeadFreshOptional(git, branch) {
1114
+ if (!safeBranch(branch))
1115
+ throw new Error('branch-ref-invalid');
1116
+ // Only a successful empty query proves absence. Transport/auth failure or
1117
+ // malformed/ambiguous output must never authorize creation/deletion/replay.
1118
+ const output = await git('ls-remote', '--heads', 'origin', `refs/heads/${branch}`);
1119
+ const matches = output.split('\n').filter(Boolean).map((line) => line.split(/\s+/));
1120
+ if (matches.length === 0)
1121
+ return undefined;
1122
+ if (matches.length !== 1 || matches[0].length !== 2 || matches[0][1] !== `refs/heads/${branch}`
1123
+ || !/^[a-f0-9]{40,64}$/i.test(matches[0][0] ?? ''))
1124
+ throw new Error('remote-ref-query-invalid');
1125
+ return matches[0][0];
1126
+ }
1127
+ async function fetchRemoteHeadExact(git, branch, expectedSha) {
1128
+ await git('fetch', '--quiet', '--no-tags', 'origin', `refs/heads/${branch}`);
1129
+ if (await git('rev-parse', 'FETCH_HEAD') !== expectedSha)
1130
+ throw new Error('remote-head-raced');
1131
+ }
1132
+ async function resolveOptionalRef(git, ref) {
1133
+ try {
1134
+ return await git('rev-parse', '--verify', ref);
1135
+ }
1136
+ catch {
1137
+ return undefined;
1138
+ }
1139
+ }
1140
+ async function isAncestor(git, ancestor, branch) {
1141
+ try {
1142
+ await git('merge-base', '--is-ancestor', ancestor, branch);
1143
+ return true;
1144
+ }
1145
+ catch {
1146
+ return false;
1147
+ }
1148
+ }
1149
+ async function isCommit(git, sha) {
1150
+ if (!/^[a-f0-9]{40,64}$/i.test(sha))
1151
+ return false;
1152
+ try {
1153
+ return await git('cat-file', '-t', sha) === 'commit';
1154
+ }
1155
+ catch {
1156
+ return false;
1157
+ }
1158
+ }
1159
+ async function inspectWorktreeBranches(git) {
1160
+ const branches = new Set();
1161
+ const output = await git('worktree', 'list', '--porcelain');
1162
+ for (const line of output.split('\n')) {
1163
+ if (line.startsWith('branch refs/heads/'))
1164
+ branches.add(line.slice('branch refs/heads/'.length));
1165
+ }
1166
+ return branches;
1167
+ }
1168
+ function failure(reasonCode, retryEligible, externalPolicy) {
1169
+ return { ok: false, reasonCode, retryEligible, externalPolicy };
1170
+ }
1171
+ function stringValue(value) {
1172
+ return typeof value === 'string' ? value.trim() : '';
1173
+ }
1174
+ function safeBranch(value) {
1175
+ return value.length > 0 && value.length <= 240 && !value.startsWith('-') && !value.startsWith('/')
1176
+ && !value.endsWith('/') && !value.endsWith('.lock') && !value.includes('..') && !value.includes('\\')
1177
+ && !value.includes('@{') && !value.includes('//') && /^[A-Za-z0-9._/-]+$/.test(value);
1178
+ }
1179
+ function isRecord(value) {
1180
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
1181
+ }
1182
+ function isNodeError(error, code) {
1183
+ return error instanceof Error && 'code' in error && error.code === code;
1184
+ }
1185
+ function storyIds(epic) {
1186
+ const value = Array.isArray(epic.stories) ? epic.stories : Array.isArray(epic.story_ids) ? epic.story_ids : [];
1187
+ return value.filter((item) => typeof item === 'string');
1188
+ }
1189
+ async function acceptedPhysicalCheckpointIds(projectRoot, state, epic, epicId, executionBranch) {
1190
+ const ids = storyIds(epic);
1191
+ const verdicts = await Promise.all(ids.map((storyId) => verifyAcceptedGitLifecycleStoryCheckpoint(projectRoot, state.stories?.[storyId]?.checkpoint, storyId, epicId, executionBranch).then((verified) => verified && hasP205ExecutionAuthority(state.stories?.[storyId]?.checkpoint))));
1192
+ return ids.filter((_storyId, index) => verdicts[index]);
1193
+ }
1194
+ function hasP205ExecutionAuthority(value) {
1195
+ const checkpoint = isRecord(value) ? value : undefined;
1196
+ const qa = checkpoint && isRecord(checkpoint.qaReceipt) ? checkpoint.qaReceipt : undefined;
1197
+ return Boolean(qa
1198
+ && qa.evidenceVersion === 'p205-execution-v2'
1199
+ && qa.producer === 'local-yolo-tdd'
1200
+ && qa.contract === 'P205-CI-02'
1201
+ && qa.command === P205_COMPLETE_COMMAND
1202
+ && /^[a-f0-9]{64}$/i.test(stringValue(qa.manifestDigest))
1203
+ && /^[a-f0-9]{64}$/i.test(stringValue(qa.resultDigest))
1204
+ && Array.isArray(qa.gateIds)
1205
+ && qa.gateIds.length > 0);
1206
+ }
1207
+ function sameSet(left, right) {
1208
+ return left.length === right.length
1209
+ && [...left].sort().every((item, index) => item === [...right].sort()[index]);
1210
+ }
1211
+ function isLiveLease(value) {
1212
+ return isRecord(value) && typeof value.expiresAt === 'string' && value.expiresAt > new Date().toISOString();
1213
+ }
1214
+ async function hasUncommittedSourceChanges(git) {
1215
+ // These exact untracked files are the running client's own operational data.
1216
+ // Never exempt a tracked modification (including a user-tracked SQLite), and
1217
+ // never ignore an entire directory that could contain unrelated user work.
1218
+ const runtimeFiles = new Set([
1219
+ '.neocortex/yoloop.lock', '.neocortex/yoloop-state.json',
1220
+ '.neocortex/continuity/continuity.sqlite', '.neocortex/continuity/continuity.sqlite-shm',
1221
+ '.neocortex/continuity/continuity.sqlite-wal',
1222
+ ]);
1223
+ return (await git('status', '--porcelain', '--untracked-files=all')).split('\n').filter(Boolean)
1224
+ .some((line) => !line.startsWith('?? ') || !runtimeFiles.has(line.slice(3)));
1225
+ }
1226
+ function looksLikeRemotePolicy(error) {
1227
+ const text = error instanceof Error ? error.message : '';
1228
+ return /protected branch|branch protection|required pull request|GH006|GH013|ruleset|review required/i.test(text);
1229
+ }
1230
+ function dedupePreserved(existing, decisions) {
1231
+ const values = Array.isArray(existing) ? existing.filter(isRecord) : [];
1232
+ const byId = new Map(values.map((item) => [stringValue(item.resourceId), item]));
1233
+ for (const decision of decisions)
1234
+ byId.set(decision.resourceId, decision);
1235
+ return [...byId.values()];
1236
+ }