@ornexus/neocortex 4.61.5 → 4.62.0

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