@ornexus/neocortex 4.61.4 → 4.61.6

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