@ornexus/neocortex 4.60.73 → 4.60.75

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