@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,193 +1,4 @@
1
- /**
2
- * @license FSL-1.1
3
- * Copyright (c) 2026 OrNexus AI
4
- *
5
- * P190.06 -- runner root-owned execution plane for run_yoloop directives.
6
- */
7
- import { createHash, randomBytes } from 'node:crypto';
8
- import { spawn } from 'node:child_process';
9
- import { existsSync } from 'node:fs';
10
- import * as os from 'node:os';
11
- import { dirname, join } from 'node:path';
12
- import { fileURLToPath } from 'node:url';
13
- import { AUTONOMOUS_GOVERNANCE_EVIDENCE_TAG, AUTONOMOUS_GOVERNANCE_REASON_CODES, autonomousGovernanceMetadata, buildAutonomousGovernanceEnvelope, readAutonomousGovernanceEnvelopeFromMetadata, recordAutonomousGovernance, } from '../../continuity/autonomous-governance.js';
14
- import { createDefaultHeadlessAdapterRegistry } from './adapters.js';
15
- import { loadHeadlessRuntimeDefaults, resolveHeadlessRuntime } from './resolver.js';
16
- import { DEFAULT_HEADLESS_EXECUTION_BACKOFF_MS, DEFAULT_HEADLESS_EXECUTION_LIMIT, DEFAULT_HEADLESS_EXECUTION_MAX_ATTEMPTS, DEFAULT_HEADLESS_EXECUTION_STALE_LEASE_AFTER_MS, DEFAULT_HEADLESS_EXECUTION_TIMEOUT_MS, headlessExecutionEntityId, runYoloExecutionPhase, } from './run-yolo.js';
17
- import { HEADLESS_REASON_CODES, boundPublicSummary, hashPublicValue, redaction, } from './types.js';
18
- import { validatePhasedYoloopPlan } from './prepared-story-bundle.js';
19
- import { createAnchoredContinuousStoryCommandRunner, createBranchlessContinuousStoryWorkspaceManager, } from './continuous-story-workspace.js';
20
- import { P205_RELEASE_GATE_BUDGETS, } from '../../../../shared/dist/yoloop/epic-terminal-git.js';
21
- import { executeEpicGitReconciliation, executeEpicTerminalGit } from './epic-terminal-git-runner.js';
22
- import { createCliEpicTerminalGitAdapter } from './epic-terminal-git-cli-adapter.js';
23
- import { installStoryWorktreeSignalSweep, sweepStoryWorktreeOrphans } from '../../git/story-worktree-cleanup.js';
24
- import { integrateStoryWorktreesInOrder, syncReleasedDependents, } from '../../git/story-worktree-integration.js';
25
- import { acquireGitLifecyclePhysicalIntegrationLock, releaseGitLifecyclePhysicalIntegrationLock, } from '../../git/git-lifecycle-store.js';
26
- import { normalizeContinuousWriteRef } from '../../../../shared/dist/yoloop/wave-decision-receipt.js';
27
- import { parseReleaseBlockedResult, } from '../../../../shared/dist/yoloop/release-blocked.js';
28
- export const DEFAULT_HEADLESS_YOLOOP_MAX_ITERATIONS = 20;
29
- export const DEFAULT_HEADLESS_YOLOOP_MAX_DURATION_MS = P205_RELEASE_GATE_BUDGETS.terminalWorkflowMaxDurationMs;
30
- export const DEFAULT_HEADLESS_YOLOOP_LEASE_MS = P205_RELEASE_GATE_BUDGETS.terminalWorkflowMaxDurationMs;
31
- export const DEFAULT_HEADLESS_YOLOOP_LOCAL_CONCURRENCY_CAP = 1;
32
- export const MAX_HEADLESS_YOLOOP_LOCAL_CONCURRENCY_CAP = 10;
33
- /**
34
- * Resolve the absent-override default from physical capacity. The explicit CLI
35
- * option remains authoritative; this resolver is injectable for deterministic
36
- * Node 18 fallback tests.
37
- */
38
- export function resolveDefaultHeadlessYoloopLocalConcurrencyCap(input = {}) {
39
- let reported = input.availableParallelism;
40
- if (reported === undefined) {
41
- const available = os.availableParallelism;
42
- if (typeof available === 'function') {
43
- try {
44
- reported = available();
45
- }
46
- catch {
47
- reported = undefined;
48
- }
49
- }
50
- }
51
- if (!Number.isFinite(reported) || (reported ?? 0) < 1) {
52
- const cpuCount = input.cpuCount ?? (() => {
53
- try {
54
- return os.cpus().length;
55
- }
56
- catch {
57
- return DEFAULT_HEADLESS_YOLOOP_LOCAL_CONCURRENCY_CAP;
58
- }
59
- })();
60
- reported = Number.isFinite(cpuCount) && cpuCount > 0
61
- ? cpuCount
62
- : DEFAULT_HEADLESS_YOLOOP_LOCAL_CONCURRENCY_CAP;
63
- }
64
- return boundedInteger(reported ?? DEFAULT_HEADLESS_YOLOOP_LOCAL_CONCURRENCY_CAP, 1, MAX_HEADLESS_YOLOOP_LOCAL_CONCURRENCY_CAP);
65
- }
66
- export const RUN_YOLOOP_DRIVER_STATES = Object.freeze([
67
- 'start',
68
- 'lifecycle_evidence',
69
- 'metadata_parse',
70
- 'child_story_delegation',
71
- 'reinvoke',
72
- 'git_reconciliation',
73
- 'terminal_git',
74
- 'complete',
75
- 'aborted',
76
- 'release_blocked',
77
- 'backoff',
78
- ]);
79
- const EPIC_TARGET_PATTERN = /^docs\/epics\/epic-[A-Za-z0-9._-]+\.md$/;
80
- const CHILD_STORY_TARGET_PATTERN = /^docs\/stories\/[A-Za-z0-9._-]+\.story\.md$/;
81
- const CHILD_PROMPT_PATTERN = /^\*yolo @docs\/stories\/[A-Za-z0-9._-]+\.story\.md(?: branchless-preparation)?$/;
82
- const BRANCHLESS_PREPARATION_PROMPT_PATTERN = /^\*yolo @docs\/stories\/[A-Za-z0-9._-]+\.story\.md branchless-preparation$/;
83
- const FRONTMATTER_ENVELOPE_PATTERN = /^(?:\uFEFF)?---(?:\r?\n)/;
84
- const SAFE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/;
85
- const SHELL_FRAGMENT_PATTERN = /(?:[;&|`$<>]|\$\(|\n|\r|\0)/;
86
- const UNSAFE_KEY_PATTERN = /(raw[_-]?(?:logs?|payloads?)|std(?:out|err)|stack(?:[_-]?trace)?|transcript|objective(?:[_-]?(?:text|body|prompt))|prompt(?:[_-]?(?:body|text))?|private[_-]?(?:urls?|prompts?)|secret|token|password|protected(?:[_-]?(?:field|body|bodies|internals))?|workflow(?:[_-]?body)?|step(?:[_-]?body)?|customer(?:[_-]?(?:pii|data))?|\bpii\b|authorization|api[_-]?key|license[_-]?key|argv|args|executable(?:[_-]?path)?|binary(?:[_-]?path)?|shell|cwd|command[_-]?path|vendor(?:[_-]?(?:payload|corpus|response|output)))/i;
87
- const UNSAFE_VALUE_PATTERN = /(https?:\/\/\S+|(?:^|\s)(?:\/(?:home|Users|media|mnt|tmp|var|etc|private)\/\S+|[A-Za-z]:\\\S+)|ghp_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|-----BEGIN [A-Z ]*PRIVATE KEY-----|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=|raw[_-]?(?:logs?)\s*[:=]|transcript|stack\s*trace|stderr:|stdout:|system prompt|workflow body|step body|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|\bPII\b|VENDOR_CORPUS|P190[_-]?SYNTHETIC[_-]?(?:HEADLESS|CONTINUITY))/i;
88
- const PUBLIC_CHILD_DEBT_CONSTRAINTS = new Set([
89
- 'no_private_prompt_or_history',
90
- 'no_raw_vendor_corpus',
91
- 'no_unrelated_story_context',
92
- ]);
93
- function hasDelegatedPromptIsolationViolation(prompt) {
94
- return FRONTMATTER_ENVELOPE_PATTERN.test(prompt) ||
95
- prompt.includes('@neocortex') ||
96
- prompt.includes('*yoloop') ||
97
- SHELL_FRAGMENT_PATTERN.test(prompt) ||
98
- UNSAFE_VALUE_PATTERN.test(prompt);
99
- }
100
- const YOLOOP_V4_STORY_ID = /^P[1-9][0-9]*(?:\.[0-9]+)+$/;
101
- /**
102
- * P225.07-ADR-8: validate the v4 integration fields (root-owned, one
103
- * integrator) and integrate in `integrationOrder`, then sync released
104
- * dependents. Phase dispatch of v4 children is wired by P225.09.
105
- */
106
- export async function executeYoloopV4IntegrationOrder(plan, options) {
107
- const record = isRecord(plan) ? plan : undefined;
108
- const policy = record && isRecord(record.isolationPolicy) ? record.isolationPolicy : undefined;
109
- const storyIds = record && Array.isArray(record.storyIds) ? record.storyIds : [];
110
- const order = record && Array.isArray(record.integrationOrder) ? record.integrationOrder : [];
111
- const validStories = storyIds.length > 0 && new Set(storyIds).size === storyIds.length
112
- && storyIds.every((storyId) => typeof storyId === 'string' && YOLOOP_V4_STORY_ID.test(storyId));
113
- if (!record || record.version !== 4 || record.mode !== 'two_phase_worktree_dag'
114
- || record.authorization !== 'server_authorized'
115
- || !policy || policy.integrationOwner !== 'root_agent' || policy.maxIntegrationConcurrency !== 1
116
- || policy.rootOwnsLoop !== true || policy.allowOuterYoloopInChild !== false
117
- || !validStories || order.length === 0 || new Set(order).size !== order.length
118
- || order.some((storyId) => typeof storyId !== 'string' || !storyIds.includes(storyId))
119
- || options.readyStoryIds.some((storyId) => !storyIds.includes(storyId))) {
120
- return { ok: false, reasonCode: 'plan-v4-integration-order-invalid', synced: [], publicSafe: true };
121
- }
122
- const integrateInOrder = options.integrateInOrder ?? integrateStoryWorktreesInOrder;
123
- const integration = await integrateInOrder({
124
- projectRoot: options.projectRoot,
125
- integrationOrder: order,
126
- readyStoryIds: options.readyStoryIds,
127
- ...(options.push !== undefined ? { push: options.push } : {}),
128
- ...(options.remote ? { remote: options.remote } : {}),
129
- });
130
- const directives = (options.releaseDirectives ?? []).filter((directive) => isRecord(directive) && typeof directive.storyId === 'string' && storyIds.includes(directive.storyId));
131
- const sync = options.syncDependents ?? syncReleasedDependents;
132
- const synced = directives.length > 0 ? await sync({ projectRoot: options.projectRoot, directives }) : [];
133
- const syncFailure = synced.find((item) => !item.ok);
134
- // Waiting and conflict-reopened are scheduler signals (the server reopens C14), not failures.
135
- const blocking = integration.reasonCode && integration.reasonCode !== 'story-worktree-integration-waiting'
136
- && integration.reasonCode !== 'integration-conflict-reopened' ? integration.reasonCode : undefined;
137
- return {
138
- ok: !blocking && !syncFailure,
139
- ...(blocking ? { reasonCode: blocking } : syncFailure?.reasonCode ? { reasonCode: syncFailure.reasonCode } : {}),
140
- integration, synced, publicSafe: true,
141
- };
142
- }
143
- export function isCanonicalDelegatedStoryPrompt(prompt) {
144
- return !hasDelegatedPromptIsolationViolation(prompt) && CHILD_PROMPT_PATTERN.test(prompt);
145
- }
146
- const EXECUTION_DIRECTIVE_ALLOWED_KEYS = new Set([
147
- 'schemaVersion',
148
- 'contractVersion',
149
- 'kind',
150
- 'commandClass',
151
- 'jobId',
152
- 'operationId',
153
- 'idempotencyKey',
154
- 'targetKind',
155
- 'targetRef',
156
- 'commandRef',
157
- 'epicId',
158
- 'runtime',
159
- 'publicSummary',
160
- 'reasonCode',
161
- 'attempts',
162
- 'metadata',
163
- 'redactionSummary',
164
- 'publicSafe',
165
- ]);
166
- const RUNTIME_ALLOWED_KEYS = new Set(['runtimeId', 'modelId', 'source', 'reasonCode', 'publicSafe']);
167
- const JOB_ABORTED_REASON_CODE = 'job-aborted';
168
- const MAX_ITERATIONS_REASON_CODE = 'max-iterations-reached';
169
- const MAX_DURATION_REASON_CODE = 'max-duration-reached';
170
- const PUBLIC_TERMINAL_LOCK_RETRY_REASONS = new Set([
171
- 'git-lifecycle-integration-backpressure',
172
- 'git-lifecycle-integration-lock-failed',
173
- 'git-lifecycle-integration-lock-release-failed',
174
- ]);
175
- const RESUMABLE_YOLOOP_BOUNDARY_REASONS = new Set([
176
- 'yoloop-per-run-cap-resumable',
177
- 'yoloop-session-timeout-resumable',
178
- ]);
179
- async function defaultIsolatedYoloopRootInvokeTransport(options, boundary) {
180
- // The thin client's lock belongs to its invocation PID. Keeping invoke in
181
- // the long-lived runner made the next iteration see its own PID as another
182
- // live owner forever. Use the normal short-lived client lifetime; only the
183
- // existing local liveness reconciler may recover its lock after process exit.
184
- // Loop scheduling and all Git effects remain in this root, not in the child.
185
- const moduleDirectory = dirname(fileURLToPath(import.meta.url));
186
- const installedModule = join(moduleDirectory, '../../commands/invoke.js');
187
- const modulePath = existsSync(installedModule) ? installedModule
188
- : join(moduleDirectory, '../../../dist/commands/invoke.js');
189
- return new Promise((resolveResult) => {
190
- const child = spawn(process.execPath, ['--input-type=module', '-e', `
1
+ import{createHash as ze,randomBytes as Ke}from"node:crypto";import{spawn as Ue}from"node:child_process";import{existsSync as $e}from"node:fs";import*as ke from"node:os";import{dirname as Ye,join as Oe}from"node:path";import{fileURLToPath as Fe}from"node:url";import{AUTONOMOUS_GOVERNANCE_EVIDENCE_TAG as Ve,AUTONOMOUS_GOVERNANCE_REASON_CODES as Ee,autonomousGovernanceMetadata as Re,buildAutonomousGovernanceEnvelope as We,readAutonomousGovernanceEnvelopeFromMetadata as ve,recordAutonomousGovernance as qe}from"../../continuity/autonomous-governance.js";import{createDefaultHeadlessAdapterRegistry as Ge}from"./adapters.js";import{loadHeadlessRuntimeDefaults as Xe,resolveHeadlessRuntime as Ze}from"./resolver.js";import{DEFAULT_HEADLESS_EXECUTION_BACKOFF_MS as Je,DEFAULT_HEADLESS_EXECUTION_LIMIT as Qe,DEFAULT_HEADLESS_EXECUTION_MAX_ATTEMPTS as et,DEFAULT_HEADLESS_EXECUTION_STALE_LEASE_AFTER_MS as tt,DEFAULT_HEADLESS_EXECUTION_TIMEOUT_MS as rt,headlessExecutionEntityId as W,runYoloExecutionPhase as ot}from"./run-yolo.js";import{HEADLESS_REASON_CODES as f,boundPublicSummary as me,hashPublicValue as x,redaction as h}from"./types.js";import{validatePhasedYoloopPlan as at}from"./prepared-story-bundle.js";import{buildHeadlessChildEnv as nt,loadHeadlessChildEnvContract as st}from"./child-env.js";import{createAnchoredContinuousStoryCommandRunner as it,createBranchlessContinuousStoryWorkspaceManager as ct}from"./continuous-story-workspace.js";import{P205_RELEASE_GATE_BUDGETS as oe}from"../../../../shared/dist/yoloop/epic-terminal-git.js";import{executeEpicGitReconciliation as dt,executeEpicTerminalGit as lt}from"./epic-terminal-git-runner.js";import{createCliEpicTerminalGitAdapter as ut}from"./epic-terminal-git-cli-adapter.js";import{installStoryWorktreeSignalSweep as pt,sweepStoryWorktreeOrphans as mt}from"../../git/story-worktree-cleanup.js";import{integrateStoryWorktreesInOrder as ft,syncReleasedDependents as yt}from"../../git/story-worktree-integration.js";import{acquireGitLifecyclePhysicalIntegrationLock as ht,releaseGitLifecyclePhysicalIntegrationLock as _t}from"../../git/git-lifecycle-store.js";import{normalizeContinuousWriteRef as Ct}from"../../../../shared/dist/yoloop/wave-decision-receipt.js";import{parseReleaseBlockedResult as gt}from"../../../../shared/dist/yoloop/release-blocked.js";const It=20,St=oe.terminalWorkflowMaxDurationMs,bt=oe.terminalWorkflowMaxDurationMs,fe=1,Pe=10;function we(e={}){let r=e.availableParallelism;if(r===void 0){const t=ke.availableParallelism;if(typeof t=="function")try{r=t()}catch{r=void 0}}if(!Number.isFinite(r)||(r??0)<1){const t=e.cpuCount??(()=>{try{return ke.cpus().length}catch{return fe}})();r=Number.isFinite(t)&&t>0?t:fe}return V(r??fe,1,Pe)}const Nr=Object.freeze(["start","lifecycle_evidence","metadata_parse","child_story_delegation","reinvoke","git_reconciliation","terminal_git","complete","aborted","release_blocked","backoff"]),ye=/^docs\/epics\/epic-[A-Za-z0-9._-]+\.md$/,At=/^docs\/stories\/[A-Za-z0-9._-]+\.story\.md$/,he=/^\*yolo @docs\/stories\/[A-Za-z0-9._-]+\.story\.md(?: branchless-preparation)?$/,kt=/^\*yolo @docs\/stories\/[A-Za-z0-9._-]+\.story\.md branchless-preparation$/,Ot=/^(?:\uFEFF)?---(?:\r?\n)/,Et=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/,q=/(?:[;&|`$<>]|\$\(|\n|\r|\0)/,ae=/(raw[_-]?(?:logs?|payloads?)|std(?:out|err)|stack(?:[_-]?trace)?|transcript|objective(?:[_-]?(?:text|body|prompt))|prompt(?:[_-]?(?:body|text))?|private[_-]?(?:urls?|prompts?)|secret|token|password|protected(?:[_-]?(?:field|body|bodies|internals))?|workflow(?:[_-]?body)?|step(?:[_-]?body)?|customer(?:[_-]?(?:pii|data))?|\bpii\b|authorization|api[_-]?key|license[_-]?key|argv|args|executable(?:[_-]?path)?|binary(?:[_-]?path)?|shell|cwd|command[_-]?path|vendor(?:[_-]?(?:payload|corpus|response|output)))/i,D=/(https?:\/\/\S+|(?:^|\s)(?:\/(?:home|Users|media|mnt|tmp|var|etc|private)\/\S+|[A-Za-z]:\\\S+)|ghp_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|-----BEGIN [A-Z ]*PRIVATE KEY-----|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=|raw[_-]?(?:logs?)\s*[:=]|transcript|stack\s*trace|stderr:|stdout:|system prompt|workflow body|step body|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|\bPII\b|VENDOR_CORPUS|P190[_-]?SYNTHETIC[_-]?(?:HEADLESS|CONTINUITY))/i,Rt=new Set(["no_private_prompt_or_history","no_raw_vendor_corpus","no_unrelated_story_context"]);function Te(e){return Ot.test(e)||e.includes("@neocortex")||e.includes("*yoloop")||q.test(e)||D.test(e)}const vt=/^P[1-9][0-9]*(?:\.[0-9]+)+$/;async function Br(e,r){const t=C(e)?e:void 0,a=t&&C(t.isolationPolicy)?t.isolationPolicy:void 0,o=t&&Array.isArray(t.storyIds)?t.storyIds:[],s=t&&Array.isArray(t.integrationOrder)?t.integrationOrder:[],n=o.length>0&&new Set(o).size===o.length&&o.every(_=>typeof _=="string"&&vt.test(_));if(!t||t.version!==4||t.mode!=="two_phase_worktree_dag"||t.authorization!=="server_authorized"||!a||a.integrationOwner!=="root_agent"||a.maxIntegrationConcurrency!==1||a.rootOwnsLoop!==!0||a.allowOuterYoloopInChild!==!1||!n||s.length===0||new Set(s).size!==s.length||s.some(_=>typeof _!="string"||!o.includes(_))||r.readyStoryIds.some(_=>!o.includes(_)))return{ok:!1,reasonCode:"plan-v4-integration-order-invalid",synced:[],publicSafe:!0};const c=await(r.integrateInOrder??ft)({projectRoot:r.projectRoot,integrationOrder:s,readyStoryIds:r.readyStoryIds,...r.push!==void 0?{push:r.push}:{},...r.remote?{remote:r.remote}:{}}),l=(r.releaseDirectives??[]).filter(_=>C(_)&&typeof _.storyId=="string"&&o.includes(_.storyId)),p=r.syncDependents??yt,m=l.length>0?await p({projectRoot:r.projectRoot,directives:l}):[],u=m.find(_=>!_.ok),y=c.reasonCode&&c.reasonCode!=="story-worktree-integration-waiting"&&c.reasonCode!=="integration-conflict-reopened"?c.reasonCode:void 0;return{ok:!y&&!u,...y?{reasonCode:y}:u?.reasonCode?{reasonCode:u.reasonCode}:{},integration:c,synced:m,publicSafe:!0}}function jr(e){return!Te(e)&&he.test(e)}const Pt=new Set(["schemaVersion","contractVersion","kind","commandClass","jobId","operationId","idempotencyKey","targetKind","targetRef","commandRef","epicId","runtime","publicSummary","reasonCode","attempts","metadata","redactionSummary","publicSafe"]),wt=new Set(["runtimeId","modelId","source","reasonCode","publicSafe"]),Tt="job-aborted",xt="max-iterations-reached",Lt="max-duration-reached",Dt=new Set(["git-lifecycle-integration-backpressure","git-lifecycle-integration-lock-failed","git-lifecycle-integration-lock-release-failed"]),xe=new Set(["yoloop-per-run-cap-resumable","yoloop-session-timeout-resumable"]);async function Mt(e,r){const t=Ye(Fe(import.meta.url)),a=Oe(t,"../../commands/invoke.js"),o=$e(a)?a:Oe(t,"../../../dist/commands/invoke.js");return new Promise(s=>{const n=Ue(process.execPath,["--input-type=module","-e",`
191
2
  import { pathToFileURL } from 'node:url';
192
3
  process.once('message', async ({ modulePath, options }) => {
193
4
  try {
@@ -196,2470 +7,4 @@ async function defaultIsolatedYoloopRootInvokeTransport(options, boundary) {
196
7
  process.send(result, () => process.exit(0));
197
8
  } catch { process.exit(1); }
198
9
  });
199
- `], { cwd: boundary.projectRoot, stdio: ['ignore', 'pipe', 'pipe', 'ipc'], windowsHide: true });
200
- let received;
201
- let bytes = 0;
202
- let invalid = false;
203
- const timer = setTimeout(() => { invalid = true; child.kill(); }, boundary.timeoutMs);
204
- const countOutput = (chunk) => {
205
- bytes += chunk.length;
206
- if (bytes > 32 * 1024 * 1024) {
207
- invalid = true;
208
- child.kill();
209
- }
210
- };
211
- child.stdout?.on('data', countOutput);
212
- child.stderr?.on('data', countOutput);
213
- child.on('message', (value) => {
214
- if (received || !isRecord(value) || typeof value.success !== 'boolean'
215
- || Buffer.byteLength(JSON.stringify(value)) > 32 * 1024 * 1024) {
216
- invalid = true;
217
- child.kill();
218
- return;
219
- }
220
- received = value;
221
- });
222
- const failed = { success: false, errorCode: 'headless-root-invoke-failed',
223
- error: 'The isolated root metadata invocation did not complete.', exitCode: 1 };
224
- child.on('error', () => { invalid = true; });
225
- child.on('close', (code) => {
226
- clearTimeout(timer);
227
- resolveResult(code === 0 && !invalid && received ? received : failed);
228
- });
229
- child.send({ modulePath, options }, (error) => { if (error) {
230
- invalid = true;
231
- child.kill();
232
- } });
233
- });
234
- }
235
- export async function defaultYoloopRootInvoker(input, invokeTransport = defaultIsolatedYoloopRootInvokeTransport) {
236
- const startedAt = Date.now();
237
- const options = {
238
- args: input.args,
239
- projectRoot: input.projectRoot,
240
- format: 'json',
241
- platformTarget: 'runner',
242
- serverUrl: input.serverUrl,
243
- strictReadOnly: input.strictReadOnly,
244
- };
245
- const result = await invokeTransport(options, {
246
- projectRoot: input.projectRoot,
247
- timeoutMs: input.timeoutMs,
248
- });
249
- return {
250
- success: result.success,
251
- instructions: result.instructions,
252
- metadata: result.metadata,
253
- error: result.error,
254
- errorCode: result.errorCode,
255
- exitCode: result.exitCode,
256
- durationMs: Date.now() - startedAt,
257
- publicSafe: true,
258
- };
259
- }
260
- export async function runYoloopExecutionPhase(options) {
261
- const registry = options.adapterRegistry ?? createDefaultHeadlessAdapterRegistry();
262
- const limit = boundedInteger(options.limit ?? DEFAULT_HEADLESS_EXECUTION_LIMIT, 1, 10);
263
- const leaseMs = boundedInteger(options.leaseMs ?? DEFAULT_HEADLESS_YOLOOP_LEASE_MS, 1_000, P205_RELEASE_GATE_BUDGETS.terminalWorkflowMaxDurationMs);
264
- const staleLeaseAfterMs = boundedInteger(options.staleLeaseAfterMs ?? DEFAULT_HEADLESS_EXECUTION_STALE_LEASE_AFTER_MS, 0, 24 * 60 * 60 * 1000);
265
- const maxAttempts = boundedInteger(options.maxAttempts ?? DEFAULT_HEADLESS_EXECUTION_MAX_ATTEMPTS, 1, 10);
266
- const localConcurrencyCap = boundedInteger(options.localConcurrencyCap ?? resolveDefaultHeadlessYoloopLocalConcurrencyCap(), 1, MAX_HEADLESS_YOLOOP_LOCAL_CONCURRENCY_CAP);
267
- const reasonCodes = [];
268
- const receipts = [];
269
- const disposeSignalSweep = options.storyWorktreeSignalSweep === true
270
- ? installStoryWorktreeSignalSweep(options.projectRoot)
271
- : undefined;
272
- try {
273
- // P225.06: sweep codes are appended to (never replace) the phase summary codes.
274
- const sweepReasonCodes = [];
275
- if (options.storyWorktreeSweeper !== false) {
276
- const sweeper = options.storyWorktreeSweeper ?? sweepStoryWorktreeOrphans;
277
- try {
278
- sweepReasonCodes.push(...(await sweeper(options.projectRoot)).reasonCodes);
279
- }
280
- catch {
281
- sweepReasonCodes.push('story-worktree-sweep-failed');
282
- }
283
- }
284
- const summary = await runYoloopExecutionPhaseInner(options, {
285
- registry, limit, leaseMs, staleLeaseAfterMs, maxAttempts, localConcurrencyCap, reasonCodes, receipts,
286
- });
287
- return sweepReasonCodes.length === 0 ? summary : { ...summary, reasonCodes: unique([...summary.reasonCodes, ...sweepReasonCodes]) };
288
- }
289
- finally {
290
- disposeSignalSweep?.();
291
- }
292
- }
293
- async function runYoloopExecutionPhaseInner(options, context) {
294
- const { registry, limit, leaseMs, staleLeaseAfterMs, maxAttempts, localConcurrencyCap, reasonCodes, receipts } = context;
295
- const nowIso = options.now();
296
- const enqueueResult = enqueueRunYoloopExecutionDirectives({
297
- store: options.store,
298
- metadata: options.metadata,
299
- nowIso,
300
- maxAttempts,
301
- queueCap: options.queueCap,
302
- });
303
- reasonCodes.push(...enqueueResult.reasonCodes);
304
- const recovered = options.store.recoverStaleHeadlessExecutionAttempts({
305
- nowIso,
306
- staleAfterMs: staleLeaseAfterMs,
307
- limit: limit * 2,
308
- });
309
- if (recovered.recoveredAttemptIds.length > 0) {
310
- reasonCodes.push(HEADLESS_REASON_CODES.EXECUTION_BACKOFF);
311
- if (recovered.failedAttemptIds.length > 0)
312
- reasonCodes.push(HEADLESS_REASON_CODES.EXECUTION_TIMEOUT);
313
- }
314
- const dueAttempts = options.store
315
- .listDueHeadlessExecutionAttempts({ nowIso: options.now(), limit: Math.max(limit * 5, 10) })
316
- .filter((attempt) => attempt.directive_kind === 'run_yoloop')
317
- .slice(0, limit);
318
- for (const attempt of dueAttempts) {
319
- const receipt = await processRunYoloopAttempt({
320
- store: options.store,
321
- projectRoot: options.projectRoot,
322
- runnerId: options.runnerId,
323
- attempt,
324
- registry,
325
- now: options.now,
326
- leaseMs,
327
- timeoutMs: boundedInteger(options.timeoutMs ?? DEFAULT_HEADLESS_EXECUTION_TIMEOUT_MS, 1_000, P205_RELEASE_GATE_BUDGETS.terminalWorkflowMaxDurationMs),
328
- backoffMs: boundedInteger(options.backoffMs ?? DEFAULT_HEADLESS_EXECUTION_BACKOFF_MS, 1_000, 60 * 60 * 1000),
329
- maxAttempts,
330
- maxIterations: boundedInteger(options.maxIterations ?? DEFAULT_HEADLESS_YOLOOP_MAX_ITERATIONS, 1, 100),
331
- maxDurationMs: boundedInteger(options.maxDurationMs ?? DEFAULT_HEADLESS_YOLOOP_MAX_DURATION_MS, 1_000, P205_RELEASE_GATE_BUDGETS.terminalWorkflowMaxDurationMs),
332
- localConcurrencyCap,
333
- queueCap: options.queueCap,
334
- adapterOptions: options.adapterOptions,
335
- runtimeDefaults: options.runtimeDefaults,
336
- runtimeFallback: options.runtimeFallback,
337
- yoloopInvoker: options.yoloopInvoker ?? defaultYoloopRootInvoker,
338
- serverUrl: options.serverUrl,
339
- idFactory: options.idFactory ?? defaultHeadlessIdFactory,
340
- continuousWorkspaceManager: options.continuousWorkspaceManager ?? createBranchlessContinuousStoryWorkspaceManager(),
341
- terminalGitAdapter: options.terminalGitAdapter ?? createCliEpicTerminalGitAdapter(options.projectRoot),
342
- });
343
- receipts.push(receipt);
344
- reasonCodes.push(receipt.reasonCode, ...receipt.workerPoolSummary.reasonCodes);
345
- }
346
- return {
347
- ok: receipts.every((receipt) => receipt.outcome !== 'failed') && enqueueResult.rejectedCount === 0,
348
- enqueuedAttemptCount: enqueueResult.enqueuedCount,
349
- dueAttemptCount: dueAttempts.length,
350
- processedAttemptCount: receipts.filter((receipt) => receipt.outcome !== 'ignored').length,
351
- recoveredAttemptIds: recovered.recoveredAttemptIds,
352
- receipts,
353
- reasonCodes: unique(reasonCodes.length > 0 ? reasonCodes : [HEADLESS_REASON_CODES.OK]),
354
- publicSafe: true,
355
- };
356
- }
357
- function enqueueRunYoloopExecutionDirectives(input) {
358
- let enqueuedCount = 0;
359
- let rejectedCount = 0;
360
- const reasonCodes = [];
361
- for (const candidate of extractExecutionDirectiveCandidates(input.metadata)) {
362
- if (!isRecord(candidate) || candidate.kind !== 'run_yoloop')
363
- continue;
364
- const validation = validateRunYoloopExecutionDirective(candidate);
365
- if (!validation.ok) {
366
- rejectedCount += 1;
367
- reasonCodes.push(validation.reasonCode);
368
- continue;
369
- }
370
- const directive = validation.directive;
371
- if (!input.store.jobExists(directive.jobId)) {
372
- rejectedCount += 1;
373
- reasonCodes.push(AUTONOMOUS_GOVERNANCE_REASON_CODES.BYPASS_BLOCKED);
374
- continue;
375
- }
376
- const directiveHash = hashDirective(directive);
377
- if (input.store.hasCompletedHeadlessExecutionDirectiveHash(directiveHash)) {
378
- reasonCodes.push(HEADLESS_REASON_CODES.EXECUTION_COMPLETED);
379
- continue;
380
- }
381
- const governanceEnvelope = buildAutonomousGovernanceEnvelope({
382
- autonomousKind: 'run_yoloop',
383
- source: 'headless-run-yoloop',
384
- targetKind: 'epic',
385
- targetRef: directive.targetRef,
386
- epicId: directive.epicId ?? epicIdFromTargetRef(directive.targetRef),
387
- jobId: directive.jobId,
388
- operationSeed: directive.operationId,
389
- commandHash: hashPublicValue(directive.commandRef),
390
- });
391
- const governance = recordAutonomousGovernance(input.store, governanceEnvelope, input.nowIso, { requireExistingJob: true });
392
- if (!governance.ok) {
393
- rejectedCount += 1;
394
- reasonCodes.push(governance.reasonCode);
395
- continue;
396
- }
397
- const attemptId = headlessExecutionEntityId('attempt', directive.idempotencyKey);
398
- const executionId = headlessExecutionEntityId('exec', directive.operationId);
399
- const result = input.store.enqueueHeadlessExecutionAttempt({
400
- attemptId,
401
- executionId,
402
- jobId: directive.jobId,
403
- directiveHash,
404
- directiveKind: 'run_yoloop',
405
- commandClass: directive.commandClass,
406
- targetKind: 'epic',
407
- targetRef: directive.targetRef,
408
- epicId: directive.epicId ?? epicIdFromTargetRef(directive.targetRef),
409
- runtimeId: directive.runtime?.runtimeId,
410
- modelId: directive.runtime?.modelId,
411
- runtimeSource: normalizeStoredRuntimeSource(directive.runtime?.source),
412
- reasonCode: directive.reasonCode,
413
- publicSummary: directive.publicSummary,
414
- enqueuedAt: input.nowIso,
415
- notBeforeAt: input.nowIso,
416
- maxAttempts: input.maxAttempts,
417
- queueCap: input.queueCap,
418
- operationId: `${directive.operationId}:enqueue`,
419
- idempotencyKey: directive.idempotencyKey,
420
- counts: { directives: 1 },
421
- hashes: { directive: directiveHash },
422
- redactionSummary: directive.redactionSummary,
423
- relativePaths: [directive.targetRef],
424
- metadata: autonomousGovernanceMetadata(governanceEnvelope, {
425
- schemaVersion: 1,
426
- contractVersion: 'continuity-v1',
427
- jobId: directive.jobId,
428
- operationId: directive.operationId,
429
- reasonCode: directive.reasonCode ?? HEADLESS_REASON_CODES.OK,
430
- targetRef: directive.targetRef,
431
- directiveHash,
432
- }),
433
- });
434
- if (!result.accepted) {
435
- rejectedCount += 1;
436
- reasonCodes.push(result.reasonCode ?? 'queue-cap-reached');
437
- continue;
438
- }
439
- if (result.inserted)
440
- enqueuedCount += 1;
441
- reasonCodes.push(HEADLESS_REASON_CODES.OK);
442
- }
443
- return { enqueuedCount, rejectedCount, reasonCodes: unique(reasonCodes) };
444
- }
445
- async function processRunYoloopAttempt(input) {
446
- const claimedAt = input.now();
447
- const leaseId = input.idFactory('lease', input.attempt.attempt_id);
448
- const leaseExpiresAt = addMilliseconds(claimedAt, input.leaseMs);
449
- const claim = input.store.claimHeadlessExecutionAttempt({
450
- attemptId: input.attempt.attempt_id,
451
- leaseId,
452
- runnerId: input.runnerId,
453
- claimedAt,
454
- leaseExpiresAt,
455
- reasonCode: HEADLESS_REASON_CODES.OK,
456
- });
457
- if (!claim.inserted) {
458
- return emptyYoloopReceipt(input.attempt, {
459
- status: input.attempt.status,
460
- receiptStatus: 'ignored',
461
- reasonCode: 'lease-conflict',
462
- timestamp: claimedAt,
463
- });
464
- }
465
- const duplicateCompletion = input.store.hasCompletedHeadlessExecutionDirectiveHash(input.attempt.directive_hash, input.attempt.attempt_id);
466
- if (duplicateCompletion) {
467
- return persistYoloopAttemptOutcome(input.store, input.attempt, {
468
- leaseId,
469
- runnerId: input.runnerId,
470
- status: 'skipped',
471
- receiptStatus: 'ignored',
472
- reasonCode: HEADLESS_REASON_CODES.EXECUTION_COMPLETED,
473
- publicSummary: 'Skipped duplicate run_yoloop directive because the directive hash is already completed.',
474
- completedAt: input.now(),
475
- counts: emptyAggregateCounts(),
476
- hashes: { directive: input.attempt.directive_hash },
477
- redactionSummary: [],
478
- relativePaths: [input.attempt.target_ref],
479
- childStoryIds: [],
480
- stateTransitions: ['start', 'complete'],
481
- });
482
- }
483
- const preparation = prepareYoloopAttemptInput(input);
484
- if (!preparation.ok) {
485
- return persistYoloopAttemptOutcome(input.store, input.attempt, {
486
- leaseId,
487
- runnerId: input.runnerId,
488
- status: preparation.status,
489
- receiptStatus: preparation.receiptStatus,
490
- reasonCode: preparation.reasonCode,
491
- publicSummary: preparation.publicSummary,
492
- completedAt: input.now(),
493
- counts: emptyAggregateCounts(),
494
- hashes: { directive: input.attempt.directive_hash },
495
- redactionSummary: preparation.redactionSummary,
496
- relativePaths: safeAttemptRelativePaths(input.attempt),
497
- childStoryIds: [],
498
- stateTransitions: ['start'],
499
- });
500
- }
501
- const driverResult = await executeRootOwnedYoloop({
502
- ...input,
503
- prepared: preparation.input,
504
- });
505
- const retry = retryDecision(input.attempt, driverResult, input.maxAttempts, input.backoffMs, input.now());
506
- const status = retry.retry ? 'backoff' : driverResult.status;
507
- const receiptStatus = retry.retry ? 'deferred' : driverResult.receiptStatus;
508
- const reasonCode = retry.retry
509
- ? (PUBLIC_TERMINAL_LOCK_RETRY_REASONS.has(driverResult.reasonCode)
510
- || RESUMABLE_YOLOOP_BOUNDARY_REASONS.has(driverResult.reasonCode)
511
- ? driverResult.reasonCode : HEADLESS_REASON_CODES.EXECUTION_BACKOFF)
512
- : driverResult.reasonCode;
513
- const publicSummary = retry.retry
514
- ? 'Headless run_yoloop execution scheduled bounded retry after transient metadata/runtime outcome.'
515
- : driverResult.publicSummary;
516
- return persistYoloopAttemptOutcome(input.store, input.attempt, {
517
- leaseId,
518
- runnerId: input.runnerId,
519
- status,
520
- receiptStatus,
521
- reasonCode,
522
- publicSummary,
523
- completedAt: input.now(),
524
- durationMs: driverResult.durationMs,
525
- notBeforeAt: retry.notBeforeAt,
526
- retryCount: retry.retryCount,
527
- counts: driverResult.counts,
528
- workerPoolSummary: driverResult.workerPoolSummary,
529
- hashes: { ...driverResult.hashes, directive: input.attempt.directive_hash },
530
- redactionSummary: driverResult.redactionSummary,
531
- relativePaths: driverResult.relativePaths,
532
- childStoryIds: driverResult.childStoryIds,
533
- runtimeId: preparation.input.runtimeId,
534
- modelId: preparation.input.modelId,
535
- runtimeSource: preparation.input.runtimeSource,
536
- stateTransitions: driverResult.stateTransitions,
537
- terminalClass: driverResult.terminalClass,
538
- releaseBlocked: driverResult.releaseBlocked,
539
- });
540
- }
541
- async function executeRootOwnedYoloop(input) {
542
- const startedAt = Date.now();
543
- const stateTransitions = ['start'];
544
- const processedStoryIds = new Set();
545
- const childStoryIds = [];
546
- const childTargetRefs = [];
547
- const hashes = { root: hashPublicValue(input.prepared.rootPrompt) };
548
- const redactions = [redaction('rootPrompt', 'prompt_body', hashes.root)];
549
- let iterations = 0;
550
- let succeededChildCount = 0;
551
- let failedChildCount = 0;
552
- let skippedChildCount = 0;
553
- let metadataCompleteCount = 0;
554
- let metadataAbortedCount = 0;
555
- let terminalP205Authority;
556
- let lifecycleEvidencePrepared = false;
557
- const workerPool = createMutableWorkerPoolSummary(input.localConcurrencyCap);
558
- const continuousInFlight = new Map();
559
- let continuousModeObserved = false;
560
- const continuousDeferredReasons = new Map();
561
- const continuousFailureReasons = new Map();
562
- const recordContinuousChild = (result) => {
563
- const child = result.child;
564
- hashes[`child-${child.storyId.replace(/[^A-Za-z0-9_.:-]/g, '-')}`] = result.commandHash;
565
- redactions.push(result.promptRedaction);
566
- const receipt = result.receipt;
567
- if (result.terminalFailure) {
568
- if (result.deferredFailure) {
569
- continuousDeferredReasons.set(child.storyId, result.terminalFailure);
570
- workerPool.backpressurePauseCount += 1;
571
- return;
572
- }
573
- continuousDeferredReasons.delete(child.storyId);
574
- continuousFailureReasons.set(child.storyId, result.terminalFailure);
575
- if (!processedStoryIds.has(child.storyId)) {
576
- processedStoryIds.add(child.storyId);
577
- childStoryIds.push(child.storyId);
578
- childTargetRefs.push(child.targetRef);
579
- failedChildCount += 1;
580
- }
581
- return;
582
- }
583
- if (!receipt || receipt.outcome === 'deferred') {
584
- continuousDeferredReasons.set(child.storyId, result.reasonCodes.includes('queue-cap-reached')
585
- ? HEADLESS_REASON_CODES.WORKER_POOL_BACKPRESSURE_PAUSED
586
- : receipt?.reasonCode || HEADLESS_REASON_CODES.EXECUTION_BACKOFF);
587
- if (result.reasonCodes.includes('queue-cap-reached'))
588
- workerPool.backpressurePauseCount += 1;
589
- return;
590
- }
591
- continuousDeferredReasons.delete(child.storyId);
592
- if (processedStoryIds.has(child.storyId))
593
- return;
594
- processedStoryIds.add(child.storyId);
595
- childStoryIds.push(child.storyId);
596
- childTargetRefs.push(child.targetRef);
597
- if (receipt.outcome === 'failed') {
598
- failedChildCount += 1;
599
- continuousFailureReasons.set(child.storyId, receipt.reasonCode || HEADLESS_REASON_CODES.EXECUTION_FAILED);
600
- }
601
- else if (receipt.outcome === 'ignored')
602
- skippedChildCount += 1;
603
- else
604
- succeededChildCount += 1;
605
- };
606
- const settleOneContinuousChild = async () => {
607
- const settled = await Promise.race([...continuousInFlight.entries()].map(([storyId, entry]) => entry.promise.then((result) => ({ storyId, result }))));
608
- continuousInFlight.delete(settled.storyId);
609
- workerPool.completedChildCount += 1;
610
- workerPool.pendingChildCount = continuousInFlight.size;
611
- recordContinuousChild(settled.result);
612
- };
613
- while (true) {
614
- if (iterations >= input.maxIterations) {
615
- stateTransitions.push('backoff');
616
- return driverResult({
617
- status: 'failed',
618
- receiptStatus: 'failed',
619
- reasonCode: MAX_ITERATIONS_REASON_CODE,
620
- publicSummary: 'Headless yoloop reached the bounded iteration limit before completion metadata.',
621
- retryable: false,
622
- startedAt,
623
- counts: aggregateCounts(iterations, childStoryIds.length, succeededChildCount, failedChildCount, skippedChildCount, metadataCompleteCount, metadataAbortedCount),
624
- workerPoolSummary: publicWorkerPoolSummary(workerPool),
625
- hashes,
626
- redactions,
627
- relativePaths: [input.prepared.targetRef, ...childTargetRefs],
628
- childStoryIds,
629
- stateTransitions,
630
- });
631
- }
632
- if (Date.now() - startedAt > input.maxDurationMs) {
633
- stateTransitions.push('backoff');
634
- return driverResult({
635
- status: 'failed',
636
- receiptStatus: 'failed',
637
- reasonCode: MAX_DURATION_REASON_CODE,
638
- publicSummary: 'Headless yoloop reached the bounded duration limit before completion metadata.',
639
- retryable: false,
640
- startedAt,
641
- counts: aggregateCounts(iterations, childStoryIds.length, succeededChildCount, failedChildCount, skippedChildCount, metadataCompleteCount, metadataAbortedCount),
642
- workerPoolSummary: publicWorkerPoolSummary(workerPool),
643
- hashes,
644
- redactions,
645
- relativePaths: [input.prepared.targetRef, ...childTargetRefs],
646
- childStoryIds,
647
- stateTransitions,
648
- });
649
- }
650
- stateTransitions.push('metadata_parse');
651
- const rootResult = await input.yoloopInvoker({
652
- projectRoot: input.projectRoot,
653
- args: input.prepared.rootPrompt,
654
- attemptId: input.attempt.attempt_id,
655
- executionId: input.attempt.execution_id,
656
- jobId: input.attempt.job_id,
657
- runnerId: input.runnerId,
658
- iteration: iterations,
659
- runtimeId: input.prepared.runtimeId,
660
- ...(input.prepared.modelId ? { modelId: input.prepared.modelId } : {}),
661
- timeoutMs: input.timeoutMs,
662
- serverUrl: input.serverUrl,
663
- });
664
- if (rootResult.durationMs !== undefined)
665
- hashes[`iter-${iterations}`] = hashPublicValue(String(rootResult.durationMs));
666
- const metadata = rootResult.metadata;
667
- const releaseBlockedTransport = rootResult.errorCode === 'YOLOOP_RELEASE_BLOCKED'
668
- || metadata?.yoloopReleaseBlocked === true
669
- || metadata?.terminalClass === 'release-blocked'
670
- || metadata?.releaseBlocked !== undefined;
671
- if (!rootResult.success && !releaseBlockedTransport) {
672
- stateTransitions.push('backoff');
673
- return driverResult({
674
- status: 'backoff',
675
- receiptStatus: 'deferred',
676
- reasonCode: HEADLESS_REASON_CODES.EXECUTION_FAILED,
677
- publicSummary: 'Headless yoloop root metadata invocation failed with bounded public evidence.',
678
- retryable: true,
679
- startedAt,
680
- counts: aggregateCounts(iterations, childStoryIds.length, succeededChildCount, failedChildCount, skippedChildCount, metadataCompleteCount, metadataAbortedCount),
681
- workerPoolSummary: publicWorkerPoolSummary(workerPool),
682
- hashes,
683
- redactions,
684
- relativePaths: [input.prepared.targetRef, ...childTargetRefs],
685
- childStoryIds,
686
- stateTransitions,
687
- });
688
- }
689
- const terminal = classifyYoloopTerminalMetadata(metadata);
690
- if (!terminal.ok) {
691
- stateTransitions.push('backoff');
692
- return driverResult({
693
- status: 'failed',
694
- receiptStatus: 'failed',
695
- reasonCode: terminal.reasonCode,
696
- publicSummary: terminal.publicSummary,
697
- retryable: false,
698
- startedAt,
699
- counts: aggregateCounts(iterations, childStoryIds.length, succeededChildCount, failedChildCount, skippedChildCount, metadataCompleteCount, metadataAbortedCount),
700
- workerPoolSummary: publicWorkerPoolSummary(workerPool),
701
- hashes,
702
- redactions: [...redactions, ...terminal.redactionSummary],
703
- relativePaths: [input.prepared.targetRef, ...childTargetRefs],
704
- childStoryIds,
705
- stateTransitions,
706
- });
707
- }
708
- const resumableBoundary = extractResumableExhaustionBoundary(metadata);
709
- if (terminal.aborted && resumableBoundary) {
710
- while (continuousInFlight.size > 0)
711
- await settleOneContinuousChild();
712
- metadataAbortedCount += 1;
713
- stateTransitions.push('backoff');
714
- return driverResult({
715
- status: 'backoff',
716
- receiptStatus: 'deferred',
717
- reasonCode: resumableBoundary.reason === 'YOLOOP_SESSION_TIMEOUT'
718
- ? 'yoloop-session-timeout-resumable'
719
- : 'yoloop-per-run-cap-resumable',
720
- publicSummary: 'Headless yoloop reached a finite run boundary and scheduled the same queue after cool-down.',
721
- retryable: true,
722
- retryNotBeforeAt: resumableBoundary.coolDownUntil,
723
- startedAt,
724
- counts: aggregateCounts(iterations + 1, childStoryIds.length, succeededChildCount, failedChildCount, skippedChildCount, metadataCompleteCount, metadataAbortedCount),
725
- workerPoolSummary: publicWorkerPoolSummary(workerPool),
726
- hashes,
727
- redactions,
728
- relativePaths: [input.prepared.targetRef, ...childTargetRefs],
729
- childStoryIds,
730
- stateTransitions,
731
- });
732
- }
733
- if ((terminal.releaseBlocked || terminal.aborted || terminal.complete || terminal.replay || (terminal.outcome && terminal.outcome !== 'selected' && terminal.outcome !== 'queue_exhausted'))
734
- && continuousModeObserved && continuousInFlight.size > 0) {
735
- await settleOneContinuousChild();
736
- iterations += 1;
737
- stateTransitions.push('reinvoke');
738
- continue;
739
- }
740
- if (terminal.releaseBlocked) {
741
- stateTransitions.push('release_blocked');
742
- return driverResult({
743
- status: 'failed',
744
- receiptStatus: 'failed',
745
- reasonCode: 'yoloop-release-blocked',
746
- publicSummary: 'Headless yoloop stopped at a terminal release-blocked boundary without declaring success.',
747
- retryable: false,
748
- startedAt,
749
- counts: aggregateCounts(iterations + 1, childStoryIds.length, succeededChildCount, failedChildCount, skippedChildCount, metadataCompleteCount, metadataAbortedCount),
750
- workerPoolSummary: publicWorkerPoolSummary(workerPool),
751
- hashes: { ...hashes, releaseBlocked: hashPublicValue(terminal.releaseBlocked.resultId) },
752
- redactions,
753
- relativePaths: [input.prepared.targetRef, ...childTargetRefs],
754
- childStoryIds,
755
- stateTransitions,
756
- terminalClass: 'release-blocked',
757
- releaseBlocked: terminal.releaseBlocked,
758
- });
759
- }
760
- const epicIntegration = isRecord(metadata?.epicIntegration) ? metadata.epicIntegration : undefined;
761
- const integrationReasonCodes = Array.isArray(epicIntegration?.reasonCodes)
762
- ? epicIntegration.reasonCodes.filter((value) => typeof value === 'string')
763
- : [];
764
- const lifecycleEvidenceCanRepair = terminal.aborted
765
- && metadata?.abortReason === 'epic-integration-checkpoints-incomplete'
766
- && epicIntegration?.required === true
767
- && epicIntegration.ready === false
768
- && integrationReasonCodes.length > 0
769
- && integrationReasonCodes.every((reasonCode) => reasonCode === 'epic-aggregate-qa-receipt-required'
770
- || reasonCode === 'epic-aggregate-qa-graph-stale'
771
- || reasonCode === 'epic-aggregate-qa-expired'
772
- || reasonCode === 'epic-head-reconciliation-bindings-incomplete'
773
- || reasonCode === 'epic-origin-binding-required'
774
- || /^missing-story-checkpoint:[A-Za-z0-9._-]+$/.test(reasonCode)
775
- || /^scheduling-checkpoint-evidence-missing:[A-Za-z0-9._-]+$/.test(reasonCode));
776
- // P223 release admission has already completed for this root invocation.
777
- // Only now may the client produce the physical aggregate/origin evidence
778
- // needed for the server to emit the terminal Git directive. This avoids a
779
- // release-blocked request causing Git effects while preserving the
780
- // pre-P223 terminal-integration convergence path.
781
- if (lifecycleEvidenceCanRepair && input.terminalGitAdapter.prepareLifecycleEvidence) {
782
- stateTransitions.push('lifecycle_evidence');
783
- const evidence = await input.terminalGitAdapter.prepareLifecycleEvidence({
784
- epicId: input.prepared.epicId,
785
- nowIso: input.now(),
786
- });
787
- if (!evidence.ok) {
788
- stateTransitions.push('backoff');
789
- return driverResult({
790
- status: evidence.retryEligible ? 'backoff' : 'failed',
791
- receiptStatus: evidence.retryEligible ? 'deferred' : 'failed',
792
- reasonCode: evidence.reasonCode,
793
- publicSummary: 'Headless yoloop stopped because physical Git lifecycle evidence could not be produced safely.',
794
- retryable: evidence.retryEligible,
795
- startedAt,
796
- counts: aggregateCounts(iterations + 1, childStoryIds.length, succeededChildCount, failedChildCount, skippedChildCount, metadataCompleteCount, metadataAbortedCount),
797
- workerPoolSummary: publicWorkerPoolSummary(workerPool),
798
- hashes,
799
- redactions,
800
- relativePaths: [input.prepared.targetRef, ...childTargetRefs],
801
- childStoryIds,
802
- stateTransitions,
803
- });
804
- }
805
- terminalP205Authority = evidence.terminalAuthority ?? evidence.p205Authority;
806
- lifecycleEvidencePrepared = true;
807
- iterations += 1;
808
- stateTransitions.push('reinvoke');
809
- continue;
810
- }
811
- if (terminal.aborted) {
812
- metadataAbortedCount += 1;
813
- stateTransitions.push('aborted');
814
- return driverResult({
815
- status: 'failed',
816
- receiptStatus: 'failed',
817
- reasonCode: JOB_ABORTED_REASON_CODE,
818
- publicSummary: 'Headless yoloop stopped because public metadata reported an aborted loop.',
819
- retryable: false,
820
- startedAt,
821
- counts: aggregateCounts(iterations + 1, childStoryIds.length, succeededChildCount, failedChildCount, skippedChildCount, metadataCompleteCount, metadataAbortedCount),
822
- workerPoolSummary: publicWorkerPoolSummary(workerPool),
823
- hashes,
824
- redactions,
825
- relativePaths: [input.prepared.targetRef, ...childTargetRefs],
826
- childStoryIds,
827
- stateTransitions,
828
- });
829
- }
830
- if (terminal.outcome && terminal.outcome !== 'selected' && terminal.outcome !== 'queue_exhausted') {
831
- stateTransitions.push('backoff');
832
- return driverResult({
833
- status: 'failed', receiptStatus: 'failed', reasonCode: `yoloop-${terminal.outcome}`,
834
- publicSummary: 'Headless yoloop stopped on a non-executable graph-first continuation outcome.',
835
- retryable: false, startedAt,
836
- counts: aggregateCounts(iterations + 1, childStoryIds.length, succeededChildCount, failedChildCount, skippedChildCount, metadataCompleteCount, metadataAbortedCount),
837
- workerPoolSummary: publicWorkerPoolSummary(workerPool), hashes, redactions,
838
- relativePaths: [input.prepared.targetRef, ...childTargetRefs], childStoryIds, stateTransitions,
839
- });
840
- }
841
- if (terminal.replay) {
842
- stateTransitions.push('backoff');
843
- return driverResult({
844
- status: 'backoff', receiptStatus: 'deferred', reasonCode: 'yoloop-replay-pending',
845
- publicSummary: 'Headless yoloop observed pending replay authority and did not delegate a second child.',
846
- retryable: true, startedAt,
847
- counts: aggregateCounts(iterations + 1, childStoryIds.length, succeededChildCount, failedChildCount, skippedChildCount, metadataCompleteCount, metadataAbortedCount),
848
- workerPoolSummary: publicWorkerPoolSummary(workerPool), hashes, redactions,
849
- relativePaths: [input.prepared.targetRef, ...childTargetRefs], childStoryIds, stateTransitions,
850
- });
851
- }
852
- if (terminal.complete && continuousModeObserved
853
- && continuousDeferredReasons.size > 0 && continuousFailureReasons.size === 0) {
854
- stateTransitions.push('backoff');
855
- return driverResult({
856
- status: 'backoff', receiptStatus: 'deferred',
857
- reasonCode: [...continuousDeferredReasons.values()].sort()[0],
858
- publicSummary: 'Headless yoloop rejected terminal completion while previously runnable work remained undispatched.',
859
- retryable: true, startedAt,
860
- counts: aggregateCounts(iterations + 1, childStoryIds.length, succeededChildCount, failedChildCount, skippedChildCount, metadataCompleteCount, metadataAbortedCount),
861
- workerPoolSummary: publicWorkerPoolSummary(workerPool), hashes, redactions,
862
- relativePaths: [input.prepared.targetRef, ...childTargetRefs], childStoryIds, stateTransitions,
863
- });
864
- }
865
- if (terminal.complete && continuousModeObserved && continuousFailureReasons.size > 0) {
866
- stateTransitions.push('backoff');
867
- return driverResult({
868
- status: 'failed', receiptStatus: 'failed',
869
- reasonCode: [...continuousFailureReasons.values()].sort()[0],
870
- publicSummary: 'Headless yoloop rejected terminal completion because runnable work failed before an accepted dispatch receipt.',
871
- retryable: false, startedAt,
872
- counts: aggregateCounts(iterations + 1, childStoryIds.length, succeededChildCount, failedChildCount, skippedChildCount, metadataCompleteCount, metadataAbortedCount),
873
- workerPoolSummary: publicWorkerPoolSummary(workerPool), hashes, redactions,
874
- relativePaths: [input.prepared.targetRef, ...childTargetRefs], childStoryIds, stateTransitions,
875
- });
876
- }
877
- // A terminal response can truthfully report queue exhaustion while also
878
- // carrying the still-required physical Git integration directive. The
879
- // effect must run before accepting yoloopComplete; the persisted receipt
880
- // makes the next invocation converge to terminal success.
881
- const terminalGitDirective = extractEpicTerminalGitDirective(metadata);
882
- if (terminalGitDirective) {
883
- if (!lifecycleEvidencePrepared && input.terminalGitAdapter.prepareLifecycleEvidence) {
884
- stateTransitions.push('lifecycle_evidence');
885
- const evidence = await input.terminalGitAdapter.prepareLifecycleEvidence({
886
- epicId: input.prepared.epicId,
887
- nowIso: input.now(),
888
- });
889
- if (!evidence.ok) {
890
- stateTransitions.push('backoff');
891
- return driverResult({
892
- status: evidence.retryEligible ? 'backoff' : 'failed',
893
- receiptStatus: evidence.retryEligible ? 'deferred' : 'failed',
894
- reasonCode: evidence.reasonCode,
895
- publicSummary: 'Headless yoloop stopped because physical Git lifecycle evidence could not be produced safely.',
896
- retryable: evidence.retryEligible,
897
- startedAt,
898
- counts: aggregateCounts(iterations, childStoryIds.length, succeededChildCount, failedChildCount, skippedChildCount, metadataCompleteCount, metadataAbortedCount),
899
- workerPoolSummary: publicWorkerPoolSummary(workerPool),
900
- hashes,
901
- redactions,
902
- relativePaths: [input.prepared.targetRef, ...childTargetRefs],
903
- childStoryIds,
904
- stateTransitions,
905
- });
906
- }
907
- terminalP205Authority = evidence.terminalAuthority ?? evidence.p205Authority;
908
- lifecycleEvidencePrepared = true;
909
- }
910
- stateTransitions.push('terminal_git');
911
- const lockStartedAt = new Date();
912
- const physicalLock = await acquireGitLifecyclePhysicalIntegrationLock(input.projectRoot, {
913
- kind: 'continuous', storyId: terminalGitDirective.epicId,
914
- sessionId: `${input.runnerId}:${input.attempt.attempt_id}`,
915
- idempotencyKey: terminalGitDirective.idempotencyKey,
916
- persistent: false,
917
- expiresAt: new Date(lockStartedAt.getTime() + Math.max(input.timeoutMs, input.maxDurationMs) + 60_000).toISOString(),
918
- });
919
- if (!physicalLock.ok) {
920
- stateTransitions.push('backoff');
921
- return driverResult({
922
- status: 'backoff', receiptStatus: 'deferred', reasonCode: physicalLock.reasonCode,
923
- publicSummary: 'Headless yoloop deferred terminal Git while another physical writer retained authority.',
924
- retryable: true, startedAt,
925
- counts: aggregateCounts(iterations + 1, childStoryIds.length, succeededChildCount, failedChildCount, skippedChildCount, metadataCompleteCount, metadataAbortedCount),
926
- workerPoolSummary: publicWorkerPoolSummary(workerPool), hashes, redactions,
927
- relativePaths: [input.prepared.targetRef, ...childTargetRefs], childStoryIds, stateTransitions,
928
- });
929
- }
930
- let integration;
931
- let released = false;
932
- try {
933
- integration = await executeEpicTerminalGit(terminalGitDirective, input.terminalGitAdapter, input.now, terminalP205Authority);
934
- }
935
- finally {
936
- released = await releaseGitLifecyclePhysicalIntegrationLock(physicalLock.path, physicalLock.owner)
937
- .catch(() => false);
938
- }
939
- if (!released) {
940
- stateTransitions.push('backoff');
941
- return driverResult({
942
- status: 'backoff', receiptStatus: 'deferred', reasonCode: 'git-lifecycle-integration-lock-release-failed',
943
- publicSummary: 'Headless yoloop stopped because terminal Git writer ownership could not be released safely.',
944
- retryable: true, startedAt,
945
- counts: aggregateCounts(iterations + 1, childStoryIds.length, succeededChildCount, failedChildCount, skippedChildCount, metadataCompleteCount, metadataAbortedCount),
946
- workerPoolSummary: publicWorkerPoolSummary(workerPool), hashes, redactions,
947
- relativePaths: [input.prepared.targetRef, ...childTargetRefs], childStoryIds, stateTransitions,
948
- });
949
- }
950
- hashes[`terminal-git-${iterations}`] = hashPublicValue(`${integration.receipt.idempotencyKey}:${integration.receipt.physicalStatus}`);
951
- if (!integration.ok) {
952
- const retryable = integration.receipt.retryEligible;
953
- stateTransitions.push('backoff');
954
- return driverResult({
955
- status: retryable ? 'backoff' : 'failed',
956
- receiptStatus: retryable ? 'deferred' : 'failed',
957
- reasonCode: integration.reasonCodes[0] ?? 'epic-terminal-git-failed',
958
- publicSummary: 'Headless yoloop stopped at the epic terminal Git boundary with public-safe retry evidence.',
959
- retryable,
960
- startedAt,
961
- counts: aggregateCounts(iterations + 1, childStoryIds.length, succeededChildCount, failedChildCount, skippedChildCount, metadataCompleteCount, metadataAbortedCount),
962
- workerPoolSummary: publicWorkerPoolSummary(workerPool), hashes, redactions,
963
- relativePaths: [input.prepared.targetRef, ...childTargetRefs], childStoryIds, stateTransitions,
964
- });
965
- }
966
- // The terminal capability is intentionally one-shot. A post-push replay
967
- // must obtain a newly revalidated in-process capability from the persisted
968
- // immutable receipt; this is a cheap physical renewal, never another P205.
969
- terminalP205Authority = undefined;
970
- lifecycleEvidencePrepared = false;
971
- // A persisted pushed receipt may let the server render queue exhaustion,
972
- // but it never lets the root accept completion without this invocation's
973
- // fresh physical ancestry/provider verification. The same directive is
974
- // therefore emitted on replay and this successful verification is the
975
- // terminal authority for the current root run.
976
- if (terminal.complete) {
977
- metadataCompleteCount += 1;
978
- stateTransitions.push('complete');
979
- return driverResult({
980
- status: 'completed', receiptStatus: 'applied',
981
- reasonCode: HEADLESS_REASON_CODES.EXECUTION_COMPLETED,
982
- publicSummary: 'Headless yoloop completed only after fresh root-owned physical Git verification.',
983
- retryable: false, startedAt,
984
- counts: aggregateCounts(iterations + 1, childStoryIds.length, succeededChildCount, failedChildCount, skippedChildCount, metadataCompleteCount, metadataAbortedCount),
985
- workerPoolSummary: publicWorkerPoolSummary(workerPool), hashes, redactions,
986
- relativePaths: [input.prepared.targetRef, ...childTargetRefs], childStoryIds, stateTransitions,
987
- });
988
- }
989
- iterations += 1;
990
- stateTransitions.push('reinvoke');
991
- continue;
992
- }
993
- if (terminal.complete) {
994
- metadataCompleteCount += 1;
995
- stateTransitions.push('complete');
996
- return driverResult({
997
- status: 'completed',
998
- receiptStatus: 'applied',
999
- reasonCode: HEADLESS_REASON_CODES.EXECUTION_COMPLETED,
1000
- publicSummary: 'Headless yoloop completed after public metadata reported yoloopComplete.',
1001
- retryable: false,
1002
- startedAt,
1003
- counts: aggregateCounts(iterations + 1, childStoryIds.length, succeededChildCount, failedChildCount, skippedChildCount, metadataCompleteCount, metadataAbortedCount),
1004
- workerPoolSummary: publicWorkerPoolSummary(workerPool),
1005
- hashes,
1006
- redactions,
1007
- relativePaths: [input.prepared.targetRef, ...childTargetRefs],
1008
- childStoryIds,
1009
- stateTransitions,
1010
- });
1011
- }
1012
- const reconciliationDirective = extractEpicGitReconciliationDirective(metadata);
1013
- if (reconciliationDirective) {
1014
- stateTransitions.push('git_reconciliation');
1015
- const reconciliation = await executeEpicGitReconciliation(reconciliationDirective, input.terminalGitAdapter, input.now);
1016
- hashes[`git-reconciliation-${iterations}`] = hashPublicValue(`${reconciliationDirective.idempotencyKey}:${reconciliation.reasonCodes.join(',')}`);
1017
- if (!reconciliation.ok) {
1018
- stateTransitions.push('backoff');
1019
- return driverResult({
1020
- status: 'backoff', receiptStatus: 'deferred',
1021
- reasonCode: reconciliation.reasonCodes[0] ?? 'git-reconciliation-failed',
1022
- publicSummary: 'Headless yoloop paused at a fail-closed Git reconciliation boundary.',
1023
- retryable: true, startedAt,
1024
- counts: aggregateCounts(iterations + 1, childStoryIds.length, succeededChildCount, failedChildCount, skippedChildCount, metadataCompleteCount, metadataAbortedCount),
1025
- workerPoolSummary: publicWorkerPoolSummary(workerPool), hashes, redactions,
1026
- relativePaths: [input.prepared.targetRef, ...childTargetRefs], childStoryIds, stateTransitions,
1027
- });
1028
- }
1029
- }
1030
- const extraction = extractAuthorizedChildPrompts(metadata, input.prepared.epicId);
1031
- if (!extraction.ok) {
1032
- stateTransitions.push('backoff');
1033
- return driverResult({
1034
- status: 'failed',
1035
- receiptStatus: 'failed',
1036
- reasonCode: extraction.reasonCode,
1037
- publicSummary: extraction.publicSummary,
1038
- retryable: false,
1039
- startedAt,
1040
- counts: aggregateCounts(iterations + 1, childStoryIds.length, succeededChildCount, failedChildCount, skippedChildCount, metadataCompleteCount, metadataAbortedCount),
1041
- workerPoolSummary: publicWorkerPoolSummary(workerPool),
1042
- hashes,
1043
- redactions: [...redactions, ...extraction.redactionSummary],
1044
- relativePaths: [input.prepared.targetRef, ...childTargetRefs],
1045
- childStoryIds,
1046
- stateTransitions,
1047
- });
1048
- }
1049
- const repeatedChild = extraction.continuous
1050
- ? undefined
1051
- : extraction.prompts.find((child) => processedStoryIds.has(child.storyId));
1052
- if (repeatedChild) {
1053
- stateTransitions.push('backoff');
1054
- return driverResult({
1055
- status: 'failed',
1056
- receiptStatus: 'failed',
1057
- reasonCode: HEADLESS_REASON_CODES.YOLOOP_ISOLATION_VIOLATION,
1058
- publicSummary: 'Headless yoloop rejected cyclic child story delegation evidence.',
1059
- retryable: false,
1060
- startedAt,
1061
- counts: aggregateCounts(iterations + 1, childStoryIds.length, succeededChildCount, failedChildCount, skippedChildCount, metadataCompleteCount, metadataAbortedCount),
1062
- workerPoolSummary: publicWorkerPoolSummary(workerPool),
1063
- hashes,
1064
- redactions: [...redactions, redaction('storyId', 'prompt_body', hashPublicValue(repeatedChild.storyId))],
1065
- relativePaths: [input.prepared.targetRef, ...childTargetRefs],
1066
- childStoryIds,
1067
- stateTransitions,
1068
- });
1069
- }
1070
- workerPool.mode = extraction.mode === 'continuous_dag'
1071
- ? 'continuous_dag'
1072
- : extraction.parallelAuthorized ? 'parallel_wave' : 'serial';
1073
- workerPool.serverMaxConcurrency = extraction.serverMaxConcurrency;
1074
- if (extraction.continuous) {
1075
- continuousModeObserved = true;
1076
- const eligible = extraction.prompts.filter((child) => !processedStoryIds.has(child.storyId) && !continuousInFlight.has(child.storyId));
1077
- workerPool.pendingChildCount = eligible.length + continuousInFlight.size;
1078
- if (eligible.length > 0) {
1079
- const capacity = resolveWorkerPoolCapacity({
1080
- store: input.store,
1081
- nowIso: input.now(),
1082
- localCap: input.localConcurrencyCap,
1083
- serverMaxConcurrency: extraction.serverMaxConcurrency,
1084
- parallelAuthorized: true,
1085
- continuous: true,
1086
- eligibleCount: eligible.length,
1087
- });
1088
- workerPool.queueCap = capacity.queueCap;
1089
- workerPool.availableLeases = capacity.availableLeases;
1090
- workerPool.effectiveConcurrency = capacity.effectiveConcurrency;
1091
- workerPool.reasonCodes.push(capacity.reasonCode);
1092
- if (capacity.effectiveConcurrency === 0 && continuousInFlight.size === 0) {
1093
- workerPool.backpressurePauseCount += 1;
1094
- stateTransitions.push('backoff');
1095
- return driverResult({
1096
- status: 'backoff', receiptStatus: 'deferred', reasonCode: HEADLESS_REASON_CODES.WORKER_POOL_BACKPRESSURE_PAUSED,
1097
- publicSummary: 'Headless yoloop retained its eligible frontier while physical worker capacity was unavailable.',
1098
- retryable: true, startedAt,
1099
- counts: aggregateCounts(iterations + 1, childStoryIds.length, succeededChildCount, failedChildCount, skippedChildCount, metadataCompleteCount, metadataAbortedCount),
1100
- workerPoolSummary: publicWorkerPoolSummary(workerPool), hashes, redactions,
1101
- relativePaths: [input.prepared.targetRef, ...childTargetRefs], childStoryIds, stateTransitions,
1102
- });
1103
- }
1104
- const launchable = eligible.slice(0, capacity.effectiveConcurrency);
1105
- stateTransitions.push('child_story_delegation');
1106
- for (const child of launchable) {
1107
- continuousInFlight.set(child.storyId, {
1108
- child,
1109
- promise: executeYoloopChild({ ...input, child, iteration: iterations }),
1110
- });
1111
- }
1112
- workerPool.startedChildCount += launchable.length;
1113
- workerPool.peakConcurrency = Math.max(workerPool.peakConcurrency, continuousInFlight.size);
1114
- workerPool.pendingChildCount = eligible.length - launchable.length + continuousInFlight.size;
1115
- }
1116
- if (continuousInFlight.size > 0) {
1117
- await settleOneContinuousChild();
1118
- }
1119
- else if (continuousDeferredReasons.size > 0) {
1120
- stateTransitions.push('backoff');
1121
- return driverResult({
1122
- status: 'backoff', receiptStatus: 'deferred', reasonCode: [...continuousDeferredReasons.values()].sort()[0],
1123
- publicSummary: 'Headless yoloop retained deferred continuous work for a bounded retry.',
1124
- retryable: true, startedAt,
1125
- counts: aggregateCounts(iterations + 1, childStoryIds.length, succeededChildCount, failedChildCount, skippedChildCount, metadataCompleteCount, metadataAbortedCount),
1126
- workerPoolSummary: publicWorkerPoolSummary(workerPool), hashes, redactions,
1127
- relativePaths: [input.prepared.targetRef, ...childTargetRefs], childStoryIds, stateTransitions,
1128
- });
1129
- }
1130
- else if (continuousFailureReasons.size > 0) {
1131
- stateTransitions.push('backoff');
1132
- return driverResult({
1133
- status: 'failed', receiptStatus: 'failed', reasonCode: [...continuousFailureReasons.values()].sort()[0],
1134
- publicSummary: 'Headless yoloop completed independent work and stopped on the remaining failed dependency closure.',
1135
- retryable: false, startedAt,
1136
- counts: aggregateCounts(iterations + 1, childStoryIds.length, succeededChildCount, failedChildCount, skippedChildCount, metadataCompleteCount, metadataAbortedCount),
1137
- workerPoolSummary: publicWorkerPoolSummary(workerPool), hashes, redactions,
1138
- relativePaths: [input.prepared.targetRef, ...childTargetRefs], childStoryIds, stateTransitions,
1139
- });
1140
- }
1141
- iterations += 1;
1142
- stateTransitions.push('reinvoke');
1143
- continue;
1144
- }
1145
- workerPool.pendingChildCount = extraction.prompts.length;
1146
- const pending = [...extraction.prompts];
1147
- while (pending.length > 0) {
1148
- const capacity = resolveWorkerPoolCapacity({
1149
- store: input.store,
1150
- nowIso: input.now(),
1151
- localCap: input.localConcurrencyCap,
1152
- serverMaxConcurrency: extraction.serverMaxConcurrency,
1153
- parallelAuthorized: extraction.parallelAuthorized,
1154
- continuous: false,
1155
- eligibleCount: pending.length,
1156
- });
1157
- workerPool.queueCap = capacity.queueCap;
1158
- workerPool.availableLeases = capacity.availableLeases;
1159
- workerPool.effectiveConcurrency = capacity.effectiveConcurrency;
1160
- workerPool.reasonCodes.push(capacity.reasonCode);
1161
- if (capacity.effectiveConcurrency === 0) {
1162
- workerPool.backpressurePauseCount += 1;
1163
- workerPool.pendingChildCount = pending.length;
1164
- stateTransitions.push('backoff');
1165
- return driverResult({
1166
- status: 'backoff',
1167
- receiptStatus: 'deferred',
1168
- reasonCode: HEADLESS_REASON_CODES.WORKER_POOL_BACKPRESSURE_PAUSED,
1169
- publicSummary: 'Headless yoloop paused child workers because bounded queue or lease capacity was unavailable.',
1170
- retryable: true,
1171
- startedAt,
1172
- counts: aggregateCounts(iterations + 1, childStoryIds.length, succeededChildCount, failedChildCount, skippedChildCount, metadataCompleteCount, metadataAbortedCount),
1173
- workerPoolSummary: publicWorkerPoolSummary(workerPool),
1174
- hashes,
1175
- redactions,
1176
- relativePaths: [input.prepared.targetRef, ...childTargetRefs],
1177
- childStoryIds,
1178
- stateTransitions,
1179
- });
1180
- }
1181
- const batch = pending.splice(0, capacity.effectiveConcurrency);
1182
- workerPool.startedChildCount += batch.length;
1183
- workerPool.peakConcurrency = Math.max(workerPool.peakConcurrency, batch.length);
1184
- workerPool.pendingChildCount = pending.length;
1185
- stateTransitions.push('child_story_delegation');
1186
- const settled = await Promise.all(batch.map((child) => executeYoloopChild({
1187
- ...input,
1188
- child,
1189
- iteration: iterations,
1190
- })));
1191
- workerPool.completedChildCount += settled.length;
1192
- let terminalChild;
1193
- for (const result of settled) {
1194
- const child = result.child;
1195
- hashes[`child-${child.storyId.replace(/[^A-Za-z0-9_.:-]/g, '-')}`] = result.commandHash;
1196
- redactions.push(result.promptRedaction);
1197
- childStoryIds.push(child.storyId);
1198
- childTargetRefs.push(child.targetRef);
1199
- processedStoryIds.add(child.storyId);
1200
- const receipt = result.receipt;
1201
- if (!receipt) {
1202
- if (result.reasonCodes.includes('queue-cap-reached')) {
1203
- workerPool.backpressurePauseCount += 1;
1204
- workerPool.pendingChildCount += 1;
1205
- workerPool.reasonCodes.push(HEADLESS_REASON_CODES.WORKER_POOL_BACKPRESSURE_PAUSED);
1206
- terminalChild ??= { kind: 'deferred', reasonCode: HEADLESS_REASON_CODES.WORKER_POOL_BACKPRESSURE_PAUSED };
1207
- }
1208
- else {
1209
- failedChildCount += 1;
1210
- terminalChild ??= { kind: 'missing', reasonCode: HEADLESS_REASON_CODES.EXECUTION_FAILED };
1211
- }
1212
- continue;
1213
- }
1214
- if (receipt.outcome === 'deferred') {
1215
- terminalChild ??= { kind: 'deferred', reasonCode: HEADLESS_REASON_CODES.EXECUTION_BACKOFF };
1216
- continue;
1217
- }
1218
- if (receipt.outcome === 'failed') {
1219
- failedChildCount += 1;
1220
- terminalChild ??= { kind: 'failed', reasonCode: receipt.reasonCode || HEADLESS_REASON_CODES.EXECUTION_FAILED };
1221
- continue;
1222
- }
1223
- if (receipt.outcome === 'ignored')
1224
- skippedChildCount += 1;
1225
- else
1226
- succeededChildCount += 1;
1227
- }
1228
- if (terminalChild) {
1229
- const deferred = terminalChild.kind === 'deferred';
1230
- return driverResult({
1231
- status: deferred ? 'backoff' : 'failed',
1232
- receiptStatus: deferred ? 'deferred' : 'failed',
1233
- reasonCode: terminalChild.reasonCode,
1234
- publicSummary: terminalChild.kind === 'missing'
1235
- ? 'Headless yoloop child story delegation did not produce a public receipt.'
1236
- : deferred
1237
- ? 'Headless yoloop child story delegated bounded backoff to the root attempt.'
1238
- : 'Headless yoloop child story execution failed with public receipt evidence.',
1239
- retryable: deferred,
1240
- startedAt,
1241
- counts: aggregateCounts(iterations + 1, childStoryIds.length, succeededChildCount, failedChildCount, skippedChildCount, metadataCompleteCount, metadataAbortedCount),
1242
- workerPoolSummary: publicWorkerPoolSummary(workerPool),
1243
- hashes,
1244
- redactions,
1245
- relativePaths: [input.prepared.targetRef, ...childTargetRefs],
1246
- childStoryIds,
1247
- stateTransitions,
1248
- });
1249
- }
1250
- }
1251
- iterations += 1;
1252
- stateTransitions.push('reinvoke');
1253
- }
1254
- }
1255
- async function executeYoloopChild(input) {
1256
- const workspace = input.child.dispatchId
1257
- ? await input.continuousWorkspaceManager.prepare({
1258
- projectRoot: input.projectRoot,
1259
- epicId: input.prepared.epicId,
1260
- storyId: input.child.storyId,
1261
- targetRef: input.child.targetRef,
1262
- dispatchId: input.child.dispatchId,
1263
- executionBranch: input.child.executionBranch ?? '',
1264
- graphRevision: input.child.graphRevision ?? '',
1265
- authorizedWriteSet: input.child.writeSet ?? [],
1266
- })
1267
- : undefined;
1268
- if (workspace && !workspace.ok) {
1269
- return {
1270
- child: input.child,
1271
- reasonCodes: [workspace.reasonCode],
1272
- commandHash: hashPublicValue(input.child.commandRef),
1273
- promptRedaction: redaction(`child.${input.child.storyId}`, 'prompt_body', hashPublicValue(input.child.commandRef)),
1274
- terminalFailure: workspace.reasonCode,
1275
- deferredFailure: /backpressure|lease-active/.test(workspace.reasonCode),
1276
- };
1277
- }
1278
- const childProjectRoot = input.projectRoot;
1279
- const childCommandRunner = workspace?.ok
1280
- ? createAnchoredContinuousStoryCommandRunner(workspace.value)
1281
- : input.adapterOptions?.commandRunner;
1282
- const childDirective = buildChildRunYoloDirective({
1283
- rootAttempt: input.attempt,
1284
- child: input.child,
1285
- iteration: input.iteration,
1286
- runtimeId: input.prepared.runtimeId,
1287
- modelId: input.prepared.modelId,
1288
- runtimeSource: input.prepared.runtimeSource,
1289
- });
1290
- const childAttemptId = headlessExecutionEntityId('attempt', childDirective.idempotencyKey);
1291
- let preserveWorkspace = Boolean(workspace);
1292
- try {
1293
- const childResult = await runYoloExecutionPhase({
1294
- store: input.store,
1295
- projectRoot: childProjectRoot,
1296
- runnerId: input.runnerId,
1297
- now: input.now,
1298
- metadata: { continuityExecutionDirectives: [childDirective] },
1299
- adapterRegistry: input.registry,
1300
- adapterOptions: {
1301
- ...input.adapterOptions,
1302
- cwd: childProjectRoot,
1303
- env: {
1304
- ...input.adapterOptions?.env,
1305
- ...(workspace?.ok ? {
1306
- NEOCORTEX_BRANCHLESS_PROJECT_ROOT: workspace.value.workspacePath,
1307
- NEOCORTEX_BRANCHLESS_ROOT_AUTHORITY: JSON.stringify(input.child.rootAuthority),
1308
- } : {}),
1309
- },
1310
- ...(childCommandRunner ? { commandRunner: childCommandRunner, versionRunner: childCommandRunner } : {}),
1311
- },
1312
- runtimeDefaults: input.runtimeDefaults,
1313
- runtimeFallback: input.runtimeFallback,
1314
- timeoutMs: input.timeoutMs,
1315
- maxAttempts: 1,
1316
- limit: 1,
1317
- queueCap: input.queueCap,
1318
- attemptIds: [childAttemptId],
1319
- idFactory: input.idFactory,
1320
- });
1321
- const receipt = childResult.receipts.find((item) => item.attemptId === childAttemptId) ?? childResult.receipts[0];
1322
- if (workspace?.ok && receipt && receipt.outcome !== 'failed' && receipt.outcome !== 'deferred') {
1323
- const integration = await input.continuousWorkspaceManager.integrate(workspace.value, {
1324
- receiptRefs: [`continuity:${receipt.attemptId}`],
1325
- nowIso: receipt.timestamp,
1326
- });
1327
- if (!integration.ok) {
1328
- return {
1329
- child: input.child,
1330
- receipt,
1331
- reasonCodes: [...childResult.reasonCodes, integration.reasonCode],
1332
- commandHash: hashPublicValue(input.child.commandRef),
1333
- promptRedaction: redaction(`child.${input.child.storyId}`, 'prompt_body', hashPublicValue(input.child.commandRef)),
1334
- terminalFailure: integration.reasonCode,
1335
- deferredFailure: /backpressure|graph-revision-stale/.test(integration.reasonCode),
1336
- };
1337
- }
1338
- preserveWorkspace = false;
1339
- }
1340
- return {
1341
- child: input.child,
1342
- receipt,
1343
- reasonCodes: childResult.reasonCodes,
1344
- commandHash: hashPublicValue(input.child.commandRef),
1345
- promptRedaction: redaction(`child.${input.child.storyId}`, 'prompt_body', hashPublicValue(input.child.commandRef)),
1346
- };
1347
- }
1348
- finally {
1349
- if (workspace?.ok)
1350
- await input.continuousWorkspaceManager.release(workspace.value, preserveWorkspace);
1351
- }
1352
- }
1353
- function resolveWorkerPoolCapacity(input) {
1354
- const snapshot = input.store.collectSnapshotRows({
1355
- nowIso: input.nowIso,
1356
- jobLimit: 1,
1357
- staleLeaseLimit: 1,
1358
- receiptLimit: 1,
1359
- eventLimit: 1,
1360
- snapshotLimit: 1,
1361
- });
1362
- const queueCap = Math.max(1, Math.floor(snapshot.queue.capacity));
1363
- // The current run_yoloop parent owns one active queue lease. Only other active
1364
- // headless workers reduce the local child-lease budget.
1365
- const activeOtherLeases = Math.max(0, Math.floor(snapshot.queue.running) - 1);
1366
- const availableLeases = input.continuous
1367
- ? Math.max(0, Math.floor(snapshot.queue.available))
1368
- : Math.max(0, Math.min(Math.max(0, input.localCap - activeOtherLeases), Math.floor(snapshot.queue.available)));
1369
- const serverMaxConcurrency = input.parallelAuthorized
1370
- ? Math.max(1, Math.floor(input.serverMaxConcurrency))
1371
- : 1;
1372
- const effectiveConcurrency = Math.max(0, Math.min(input.eligibleCount, serverMaxConcurrency, input.localCap, queueCap, availableLeases));
1373
- return {
1374
- queueCap,
1375
- availableLeases,
1376
- effectiveConcurrency,
1377
- reasonCode: effectiveConcurrency === 0
1378
- ? HEADLESS_REASON_CODES.WORKER_POOL_BACKPRESSURE_PAUSED
1379
- : (input.parallelAuthorized || input.continuous) && effectiveConcurrency > 1
1380
- ? HEADLESS_REASON_CODES.WORKER_POOL_PARALLEL_ACTIVE
1381
- : HEADLESS_REASON_CODES.WORKER_POOL_SERIAL_FALLBACK,
1382
- };
1383
- }
1384
- function createMutableWorkerPoolSummary(localCap) {
1385
- return {
1386
- mode: 'serial',
1387
- serverMaxConcurrency: 1,
1388
- localCap,
1389
- queueCap: 1,
1390
- availableLeases: 1,
1391
- effectiveConcurrency: 1,
1392
- peakConcurrency: 0,
1393
- pendingChildCount: 0,
1394
- startedChildCount: 0,
1395
- completedChildCount: 0,
1396
- backpressurePauseCount: 0,
1397
- reasonCodes: [],
1398
- };
1399
- }
1400
- function publicWorkerPoolSummary(summary) {
1401
- return {
1402
- mode: summary.mode,
1403
- serverMaxConcurrency: boundedCount(summary.serverMaxConcurrency),
1404
- localCap: boundedCount(summary.localCap),
1405
- queueCap: boundedCount(summary.queueCap),
1406
- availableLeases: boundedCount(summary.availableLeases),
1407
- effectiveConcurrency: boundedCount(summary.effectiveConcurrency),
1408
- peakConcurrency: boundedCount(summary.peakConcurrency),
1409
- pendingChildCount: boundedCount(summary.pendingChildCount),
1410
- startedChildCount: boundedCount(summary.startedChildCount),
1411
- completedChildCount: boundedCount(summary.completedChildCount),
1412
- backpressurePauseCount: boundedCount(summary.backpressurePauseCount),
1413
- reasonCodes: unique(summary.reasonCodes.length > 0
1414
- ? summary.reasonCodes
1415
- : [HEADLESS_REASON_CODES.WORKER_POOL_SERIAL_FALLBACK]).slice(0, 10),
1416
- publicSafe: true,
1417
- };
1418
- }
1419
- function defaultWorkerPoolSummary(localCap = resolveDefaultHeadlessYoloopLocalConcurrencyCap()) {
1420
- return publicWorkerPoolSummary(createMutableWorkerPoolSummary(localCap));
1421
- }
1422
- function boundedCount(value) {
1423
- if (!Number.isFinite(value))
1424
- return 0;
1425
- return Math.max(0, Math.min(10_000, Math.floor(value)));
1426
- }
1427
- function prepareYoloopAttemptInput(input) {
1428
- const governance = readAutonomousGovernanceEnvelopeFromMetadata(input.attempt.metadata_json, {
1429
- autonomousKind: 'run_yoloop',
1430
- jobId: input.attempt.job_id,
1431
- targetKind: 'epic',
1432
- targetRef: input.attempt.target_ref,
1433
- });
1434
- if (!governance.ok) {
1435
- return {
1436
- ok: false,
1437
- status: 'failed',
1438
- receiptStatus: 'failed',
1439
- reasonCode: governance.reasonCode,
1440
- publicSummary: governance.publicSummary,
1441
- redactionSummary: governance.redactionSummary,
1442
- };
1443
- }
1444
- const promptValidation = validateRunYoloopAttemptShape(input.attempt);
1445
- if (!promptValidation.ok)
1446
- return promptValidation;
1447
- const runtime = resolveAttemptRuntime(input);
1448
- if (!runtime.ok) {
1449
- return {
1450
- ok: false,
1451
- status: 'failed',
1452
- receiptStatus: 'failed',
1453
- reasonCode: runtime.reasonCode,
1454
- publicSummary: runtime.publicSummary,
1455
- redactionSummary: runtime.redactionSummary,
1456
- };
1457
- }
1458
- const epicId = input.attempt.epic_id ?? epicIdFromTargetRef(input.attempt.target_ref);
1459
- return {
1460
- ok: true,
1461
- input: {
1462
- rootPrompt: `*yoloop @${input.attempt.target_ref}`,
1463
- targetRef: input.attempt.target_ref,
1464
- epicId,
1465
- runtimeId: runtime.runtimeId,
1466
- ...(runtime.modelId ? { modelId: runtime.modelId } : {}),
1467
- runtimeSource: runtime.runtimeSource,
1468
- publicSafe: true,
1469
- },
1470
- };
1471
- }
1472
- function validateRunYoloopAttemptShape(attempt) {
1473
- const redactions = [];
1474
- if (attempt.directive_kind !== 'run_yoloop')
1475
- redactions.push(redaction('directiveKind', 'unsafe_key', 'value-denied'));
1476
- if (attempt.target_kind !== 'epic')
1477
- redactions.push(redaction('targetKind', 'prompt_body', 'value-denied'));
1478
- if (!EPIC_TARGET_PATTERN.test(attempt.target_ref) || SHELL_FRAGMENT_PATTERN.test(attempt.target_ref) || UNSAFE_VALUE_PATTERN.test(attempt.target_ref)) {
1479
- redactions.push(redaction('targetRef', 'prompt_body', 'value-denied'));
1480
- }
1481
- const epicId = epicIdFromTargetRef(attempt.target_ref);
1482
- if (attempt.epic_id && attempt.epic_id !== epicId)
1483
- redactions.push(redaction('epicId', 'prompt_body', 'value-denied'));
1484
- if (redactions.length > 0) {
1485
- return {
1486
- ok: false,
1487
- status: 'failed',
1488
- receiptStatus: 'failed',
1489
- reasonCode: HEADLESS_REASON_CODES.PROMPT_REJECTED,
1490
- publicSummary: 'Headless run_yoloop attempt did not match the canonical public epic prompt shape.',
1491
- redactionSummary: redactions,
1492
- };
1493
- }
1494
- return {
1495
- ok: true,
1496
- input: {
1497
- rootPrompt: `*yoloop @${attempt.target_ref}`,
1498
- targetRef: attempt.target_ref,
1499
- epicId,
1500
- runtimeId: 'fake',
1501
- publicSafe: true,
1502
- },
1503
- };
1504
- }
1505
- function resolveAttemptRuntime(input) {
1506
- const defaults = input.runtimeDefaults !== undefined
1507
- ? input.runtimeDefaults
1508
- : loadHeadlessRuntimeDefaults({ projectRoot: input.projectRoot });
1509
- if (isRecord(defaults) && defaults.ok === false) {
1510
- return {
1511
- ok: false,
1512
- reasonCode: HEADLESS_REASON_CODES.RUNTIME_UNTRUSTED,
1513
- publicSummary: typeof defaults.publicSummary === 'string' ? defaults.publicSummary : 'Headless runtime defaults failed public-safety validation.',
1514
- redactionSummary: Array.isArray(defaults.redactionSummary) ? defaults.redactionSummary : [],
1515
- };
1516
- }
1517
- const source = normalizeRuntimeSource(input.attempt.runtime_source) ?? 'explicit';
1518
- const hint = (input.attempt.runtime_id || input.attempt.model_id)
1519
- ? {
1520
- ...(input.attempt.runtime_id ? { runtimeId: input.attempt.runtime_id } : {}),
1521
- ...(input.attempt.model_id ? { modelId: input.attempt.model_id } : {}),
1522
- source,
1523
- publicSafe: true,
1524
- }
1525
- : undefined;
1526
- const resolutionInput = {
1527
- registry: input.registry,
1528
- defaults,
1529
- fallback: input.runtimeFallback,
1530
- };
1531
- if (hint) {
1532
- if (source === 'origin')
1533
- resolutionInput.origin = hint;
1534
- else if (source === 'default')
1535
- resolutionInput.projectDefault = hint;
1536
- else if (source === 'fallback')
1537
- resolutionInput.fallback = hint;
1538
- else
1539
- resolutionInput.explicit = hint;
1540
- }
1541
- const resolution = resolveHeadlessRuntime(resolutionInput);
1542
- if (!resolution.ok) {
1543
- return {
1544
- ok: false,
1545
- reasonCode: resolution.reasonCode,
1546
- publicSummary: resolution.publicSummary,
1547
- redactionSummary: resolution.redactionSummary,
1548
- };
1549
- }
1550
- return {
1551
- ok: true,
1552
- runtimeId: resolution.runtimeId,
1553
- ...(resolution.modelId ? { modelId: resolution.modelId } : {}),
1554
- runtimeSource: resolution.runtimeSource,
1555
- };
1556
- }
1557
- function validateRunYoloopExecutionDirective(input) {
1558
- const redactions = [];
1559
- for (const key of Object.keys(input)) {
1560
- if (!EXECUTION_DIRECTIVE_ALLOWED_KEYS.has(key) || UNSAFE_KEY_PATTERN.test(key)) {
1561
- redactions.push(redaction(key, unsafeKeyReason(key), 'key-denied'));
1562
- }
1563
- }
1564
- if (input.publicSafe !== true)
1565
- redactions.push(redaction('publicSafe', 'unsafe_key', 'value-denied'));
1566
- const kind = stringField(input, 'kind');
1567
- const commandClass = stringField(input, 'commandClass');
1568
- const jobId = stringField(input, 'jobId');
1569
- const operationId = stringField(input, 'operationId');
1570
- const idempotencyKey = stringField(input, 'idempotencyKey');
1571
- const targetKind = stringField(input, 'targetKind');
1572
- const targetRef = stringField(input, 'targetRef');
1573
- const commandRef = stringField(input, 'commandRef');
1574
- const publicSummary = stringField(input, 'publicSummary');
1575
- const epicId = stringField(input, 'epicId');
1576
- if (kind !== 'run_yoloop')
1577
- redactions.push(redaction('kind', 'unsafe_key', 'value-denied'));
1578
- if (commandClass !== 'goal-tick' && commandClass !== 'loop-tick')
1579
- redactions.push(redaction('commandClass', 'unsafe_key', 'value-denied'));
1580
- if (!isSafeIdentifier(jobId))
1581
- redactions.push(redaction('jobId', 'unsafe_key', 'value-denied'));
1582
- if (!isSafeIdentifier(operationId))
1583
- redactions.push(redaction('operationId', 'unsafe_key', 'value-denied'));
1584
- if (!isSafeIdentifier(idempotencyKey))
1585
- redactions.push(redaction('idempotencyKey', 'unsafe_key', 'value-denied'));
1586
- if (targetKind !== 'epic' || !targetRef || !EPIC_TARGET_PATTERN.test(targetRef) || UNSAFE_VALUE_PATTERN.test(targetRef)) {
1587
- redactions.push(redaction('targetRef', 'prompt_body', 'value-denied'));
1588
- }
1589
- const expectedCommandRef = targetRef ? `*yoloop @${targetRef}` : undefined;
1590
- if (!commandRef || commandRef !== expectedCommandRef || commandRef.includes('@neocortex') || SHELL_FRAGMENT_PATTERN.test(commandRef) || UNSAFE_VALUE_PATTERN.test(commandRef)) {
1591
- redactions.push(redaction('commandRef', 'prompt_body', 'value-denied'));
1592
- }
1593
- if (epicId && targetRef && epicId !== epicIdFromTargetRef(targetRef))
1594
- redactions.push(redaction('epicId', 'prompt_body', 'value-denied'));
1595
- if (!publicSummary || publicSummary.length > 240 || UNSAFE_VALUE_PATTERN.test(publicSummary)) {
1596
- redactions.push(redaction('publicSummary', 'unbounded_text', 'value-denied'));
1597
- }
1598
- if (input.reasonCode !== undefined && (typeof input.reasonCode !== 'string' || UNSAFE_VALUE_PATTERN.test(input.reasonCode))) {
1599
- redactions.push(redaction('reasonCode', 'unsafe_key', 'value-denied'));
1600
- }
1601
- const runtime = validateDirectiveRuntime(input.runtime, redactions);
1602
- if (input.attempts !== undefined)
1603
- assertPublicSafeCandidate(input.attempts, 'attempts', redactions);
1604
- if (input.metadata !== undefined)
1605
- assertPublicSafeCandidate(input.metadata, 'metadata', redactions);
1606
- const metadata = isRecord(input.metadata) ? input.metadata : undefined;
1607
- const redactionSummary = validateDirectiveRedactions(input.redactionSummary, redactions);
1608
- if (redactions.length > 0 || kind !== 'run_yoloop' || !commandClass || !jobId || !operationId || !idempotencyKey || !targetRef || !commandRef || !publicSummary) {
1609
- const promptRejected = redactions.some((item) => item.reason === 'prompt_body');
1610
- return {
1611
- ok: false,
1612
- reasonCode: promptRejected ? HEADLESS_REASON_CODES.PROMPT_REJECTED : HEADLESS_REASON_CODES.DIRECTIVE_REJECTED,
1613
- redactionSummary: redactions,
1614
- };
1615
- }
1616
- return {
1617
- ok: true,
1618
- directive: {
1619
- kind: 'run_yoloop',
1620
- commandClass: commandClass,
1621
- jobId: jobId,
1622
- operationId: operationId,
1623
- idempotencyKey: idempotencyKey,
1624
- targetKind: 'epic',
1625
- targetRef: targetRef,
1626
- commandRef: commandRef,
1627
- ...(epicId ? { epicId } : {}),
1628
- ...(runtime ? { runtime } : {}),
1629
- publicSummary: publicSummary,
1630
- ...(typeof input.reasonCode === 'string' ? { reasonCode: input.reasonCode } : {}),
1631
- ...(metadata ? { metadata } : {}),
1632
- ...(redactionSummary.length > 0 ? { redactionSummary } : {}),
1633
- publicSafe: true,
1634
- },
1635
- };
1636
- }
1637
- function extractAuthorizedChildPrompts(metadata, epicId) {
1638
- if (!metadata) {
1639
- return rejectPromptExtraction(HEADLESS_REASON_CODES.YOLOOP_METADATA_INVALID, 'Headless yoloop metadata was missing.', []);
1640
- }
1641
- const publicSafety = validateYoloopMetadataPublicSubset(metadata);
1642
- if (!publicSafety.ok)
1643
- return publicSafety;
1644
- const prompts = [];
1645
- const plan = isRecord(metadata.yoloopExecutionPlan) ? metadata.yoloopExecutionPlan : undefined;
1646
- const planStoryIds = plan ? safeStringArray(plan.storyIds).filter(isStoryId) : [];
1647
- const continuousNodes = plan?.version === 3 && isRecord(plan.scheduler) && Array.isArray(plan.scheduler.nodes)
1648
- ? new Map(plan.scheduler.nodes.filter(isRecord).map((node) => [String(node.storyId ?? ''), node]))
1649
- : new Map();
1650
- const continuousGraphRevision = plan?.version === 3 && isRecord(plan.scheduler) && typeof plan.scheduler.graphRevision === 'string'
1651
- ? plan.scheduler.graphRevision
1652
- : undefined;
1653
- const continuousExecutionBranch = plan?.version === 3 && typeof plan.executionBranch === 'string'
1654
- ? plan.executionBranch
1655
- : undefined;
1656
- let planValidation;
1657
- if (plan) {
1658
- const validation = validateExecutionPlan(plan);
1659
- if (!validation.ok)
1660
- return validation;
1661
- planValidation = validation;
1662
- for (const prompt of extractPlanPrompts(plan)) {
1663
- const normalized = normalizeChildPrompt(prompt, epicId, 'execution-plan');
1664
- if (!normalized.ok)
1665
- return normalized;
1666
- prompts.push(enrichContinuousPrompt(normalized.prompt, continuousNodes.get(normalized.prompt.storyId), continuousGraphRevision, continuousExecutionBranch));
1667
- }
1668
- if (prompts.length === 0) {
1669
- for (const storyId of planStoryIds) {
1670
- const normalized = normalizeChildPrompt(`*yolo @docs/stories/${storyId}.story.md`, epicId, 'execution-plan');
1671
- if (!normalized.ok)
1672
- return normalized;
1673
- prompts.push(enrichContinuousPrompt(normalized.prompt, continuousNodes.get(normalized.prompt.storyId), continuousGraphRevision, continuousExecutionBranch));
1674
- }
1675
- }
1676
- const directiveCompatibility = validatePlanTaskDirectives(metadata.skillDirectives, prompts);
1677
- if (!directiveCompatibility.ok)
1678
- return directiveCompatibility;
1679
- }
1680
- const nextStoryId = typeof metadata.nextStoryId === 'string' && isStoryId(metadata.nextStoryId)
1681
- ? metadata.nextStoryId
1682
- : undefined;
1683
- // A validated execution plan is the sole child-dispatch authority. Compatible
1684
- // duplicate task directives were checked above but never become a second
1685
- // dispatch source.
1686
- for (const directive of plan ? [] : Array.isArray(metadata.skillDirectives) ? metadata.skillDirectives : []) {
1687
- if (!isRecord(directive) || directive.kind !== 'task')
1688
- continue;
1689
- const explicitPrompts = safeStringArray(directive.promptTemplates);
1690
- if (explicitPrompts.length > 0) {
1691
- for (const prompt of explicitPrompts) {
1692
- const normalized = normalizeChildPrompt(prompt, epicId, 'task-directive');
1693
- if (!normalized.ok)
1694
- return normalized;
1695
- prompts.push(normalized.prompt);
1696
- }
1697
- continue;
1698
- }
1699
- const template = typeof directive.promptTemplate === 'string' ? directive.promptTemplate : undefined;
1700
- if (!template)
1701
- continue;
1702
- const storyIds = safeStringArray(directive.storyIds).filter(isStoryId);
1703
- const ids = storyIds.length > 0 ? storyIds : nextStoryId ? [nextStoryId] : [];
1704
- if (ids.length === 0 && CHILD_PROMPT_PATTERN.test(template)) {
1705
- const normalized = normalizeChildPrompt(template, epicId, 'task-directive');
1706
- if (!normalized.ok)
1707
- return normalized;
1708
- prompts.push(normalized.prompt);
1709
- continue;
1710
- }
1711
- for (const storyId of ids) {
1712
- const prompt = template.includes('{storyId}') ? template.replaceAll('{storyId}', storyId) : template;
1713
- const normalized = normalizeChildPrompt(prompt, epicId, 'task-directive');
1714
- if (!normalized.ok)
1715
- return normalized;
1716
- prompts.push(normalized.prompt);
1717
- }
1718
- }
1719
- if (prompts.length === 0 && nextStoryId) {
1720
- const normalized = normalizeChildPrompt(`*yolo @docs/stories/${nextStoryId}.story.md`, epicId, 'next-story');
1721
- if (!normalized.ok)
1722
- return normalized;
1723
- prompts.push(normalized.prompt);
1724
- }
1725
- const uniquePrompts = uniqueBy(prompts, (item) => item.commandRef);
1726
- if (planValidation?.continuous) {
1727
- if (uniquePrompts.length !== planStoryIds.length
1728
- || uniquePrompts.some((prompt) => prompt.preparationOnly !== true || prompt.source !== 'execution-plan')) {
1729
- return rejectPromptExtraction(HEADLESS_REASON_CODES.YOLOOP_ISOLATION_VIOLATION, 'Headless continuous yoloop rejected an ambiguous or non-preparation child prompt.', [redaction('promptTemplates', 'prompt_body', 'operation-denied')]);
1730
- }
1731
- }
1732
- else if (uniquePrompts.some((prompt) => prompt.preparationOnly === true)) {
1733
- return rejectPromptExtraction(HEADLESS_REASON_CODES.YOLOOP_ISOLATION_VIOLATION, 'Headless yoloop rejected branchless preparation outside a validated continuous plan.', [redaction('promptTemplates', 'prompt_body', 'operation-denied')]);
1734
- }
1735
- if (planStoryIds.length > 0) {
1736
- const authorized = new Set(planStoryIds);
1737
- for (const prompt of uniquePrompts) {
1738
- if (!authorized.has(prompt.storyId)) {
1739
- return rejectPromptExtraction(HEADLESS_REASON_CODES.YOLOOP_ISOLATION_VIOLATION, 'Headless yoloop rejected a child prompt outside the server-authorized execution plan.', [redaction('storyId', 'prompt_body', hashPublicValue(prompt.storyId))]);
1740
- }
1741
- }
1742
- }
1743
- if (planValidation?.parallelAuthorized && !sameStringSet(uniquePrompts.map((item) => item.storyId), planStoryIds)) {
1744
- return rejectPromptExtraction(HEADLESS_REASON_CODES.YOLOOP_METADATA_INVALID, 'Headless yoloop rejected a parallel plan whose executable prompts did not match the selected wave.', []);
1745
- }
1746
- if (uniquePrompts.length === 0 && !planValidation?.continuous) {
1747
- return rejectPromptExtraction(HEADLESS_REASON_CODES.YOLOOP_METADATA_INVALID, 'Headless yoloop metadata did not include an authorized per-story child prompt.', []);
1748
- }
1749
- return {
1750
- ok: true,
1751
- prompts: uniquePrompts,
1752
- mode: planValidation?.mode ?? 'legacy',
1753
- serverMaxConcurrency: planValidation?.serverMaxConcurrency ?? 1,
1754
- parallelAuthorized: planValidation?.parallelAuthorized ?? false,
1755
- continuous: planValidation?.continuous ?? false,
1756
- reasonCodes: [
1757
- HEADLESS_REASON_CODES.OK,
1758
- planValidation?.parallelAuthorized
1759
- ? HEADLESS_REASON_CODES.WORKER_POOL_PARALLEL_ACTIVE
1760
- : HEADLESS_REASON_CODES.WORKER_POOL_SERIAL_FALLBACK,
1761
- ],
1762
- };
1763
- }
1764
- function enrichContinuousPrompt(prompt, node, graphRevision, executionBranch) {
1765
- if (!node || !graphRevision || !executionBranch)
1766
- return prompt;
1767
- const writeSet = Array.isArray(node.writeSet) ? safeStringArray(node.writeSet) : [];
1768
- const rootAuthority = parseBranchlessRootAuthority(node.childExecutionAuthority, {
1769
- storyId: prompt.storyId,
1770
- invocationPrompt: prompt.commandRef,
1771
- authorizedWriteSet: writeSet,
1772
- });
1773
- return {
1774
- ...prompt,
1775
- ...(typeof node.dispatchId === 'string' ? { dispatchId: node.dispatchId } : {}),
1776
- ...(typeof node.idempotencyKey === 'string' ? { idempotencyKey: node.idempotencyKey } : {}),
1777
- graphRevision,
1778
- executionBranch,
1779
- ...(writeSet.length > 0 ? { writeSet } : {}),
1780
- ...(rootAuthority ? { rootAuthority } : {}),
1781
- };
1782
- }
1783
- function validateYoloopMetadataPublicSubset(metadata) {
1784
- const redactions = [];
1785
- if (metadata.nextStoryId !== undefined)
1786
- validatePublicMetadataValue(metadata.nextStoryId, 'nextStoryId', redactions);
1787
- if (metadata.yoloopExecutionPlan !== undefined)
1788
- validatePublicMetadataValue(metadata.yoloopExecutionPlan, 'yoloopExecutionPlan', redactions);
1789
- if (Array.isArray(metadata.skillDirectives)) {
1790
- metadata.skillDirectives.forEach((directive, index) => {
1791
- if (isRecord(directive) && directive.kind === 'task')
1792
- validatePublicMetadataValue(directive, `skillDirectives.${index}`, redactions);
1793
- });
1794
- }
1795
- if (redactions.length > 0) {
1796
- return rejectPromptExtraction(HEADLESS_REASON_CODES.YOLOOP_METADATA_INVALID, 'Headless yoloop rejected unsafe public metadata before child delegation.', redactions);
1797
- }
1798
- return { ok: true };
1799
- }
1800
- function validatePlanTaskDirectives(value, planPrompts) {
1801
- if (!Array.isArray(value))
1802
- return { ok: true };
1803
- const authorized = new Set(planPrompts.map((prompt) => prompt.commandRef));
1804
- for (const [index, directive] of value.entries()) {
1805
- if (!isRecord(directive) || directive.kind !== 'task')
1806
- continue;
1807
- const promptTemplate = typeof directive.promptTemplate === 'string' ? directive.promptTemplate : undefined;
1808
- const promptTemplates = safeStringArray(directive.promptTemplates);
1809
- const redactedDuplicate = promptTemplate === '[REDACTED]'
1810
- && directive.subagentType === 'neocortex'
1811
- && typeof directive.reasonCode === 'string'
1812
- && directive.reasonCode.startsWith('directive-prompt-')
1813
- && promptTemplates.length === 0;
1814
- if (redactedDuplicate)
1815
- continue;
1816
- const candidates = [...(promptTemplate ? [promptTemplate] : []), ...promptTemplates];
1817
- if (directive.subagentType !== 'neocortex'
1818
- || candidates.length === 0
1819
- || candidates.some((candidate) => !authorized.has(candidate))) {
1820
- return rejectPromptExtraction(HEADLESS_REASON_CODES.YOLOOP_ISOLATION_VIOLATION, 'Headless yoloop rejected a task directive that conflicted with the server-authorized execution plan.', [redaction(`skillDirectives.${index}`, 'prompt_body', 'operation-denied')]);
1821
- }
1822
- }
1823
- return { ok: true };
1824
- }
1825
- function validatePublicMetadataValue(value, path, redactions) {
1826
- if (typeof value === 'string') {
1827
- if (/\.allowedDebt\.constraints\.\d+$/.test(path) && PUBLIC_CHILD_DEBT_CONSTRAINTS.has(value))
1828
- return;
1829
- if (UNSAFE_VALUE_PATTERN.test(value) || /\0/.test(value))
1830
- redactions.push(redaction(path, unsafeKeyReason(path), 'value-denied'));
1831
- return;
1832
- }
1833
- if (value === undefined || value === null || typeof value === 'number' || typeof value === 'boolean')
1834
- return;
1835
- if (Array.isArray(value)) {
1836
- value.forEach((item, index) => validatePublicMetadataValue(item, `${path}.${index}`, redactions));
1837
- return;
1838
- }
1839
- if (isRecord(value)) {
1840
- for (const [key, child] of Object.entries(value)) {
1841
- const childPath = `${path}.${key}`;
1842
- const promptTemplateKey = key === 'promptTemplate'
1843
- || key === 'promptTemplates'
1844
- || key === 'invocationPrompt'
1845
- || key === 'childPromptKind'
1846
- || key === 'allowMetaTaskPromptInChild'
1847
- || key === 'authorization';
1848
- if (!promptTemplateKey && UNSAFE_KEY_PATTERN.test(key))
1849
- redactions.push(redaction(childPath, unsafeKeyReason(key), 'key-denied'));
1850
- validatePublicMetadataValue(child, childPath, redactions);
1851
- }
1852
- return;
1853
- }
1854
- redactions.push(redaction(path, 'unsafe_key', 'value-denied'));
1855
- }
1856
- function validateExecutionPlan(plan) {
1857
- const mode = typeof plan.mode === 'string' ? plan.mode : '';
1858
- const isolationPolicy = isRecord(plan.isolationPolicy) ? plan.isolationPolicy : undefined;
1859
- const storyIds = safeStringArray(plan.storyIds);
1860
- if (plan.authorization !== 'server_authorized') {
1861
- return rejectPromptExtraction(HEADLESS_REASON_CODES.YOLOOP_METADATA_INVALID, 'Headless yoloop execution plan was not server-authorized.', []);
1862
- }
1863
- if (plan.executor !== 'root_agent' && plan.executor !== 'root_agent_with_child_tasks') {
1864
- return rejectPromptExtraction(HEADLESS_REASON_CODES.YOLOOP_METADATA_INVALID, 'Headless yoloop execution plan executor was not root-owned.', []);
1865
- }
1866
- if (mode !== 'serial' && mode !== 'parallel_wave' && mode !== 'continuous_dag' && mode !== 'manual') {
1867
- return rejectPromptExtraction(HEADLESS_REASON_CODES.YOLOOP_METADATA_INVALID, 'Headless yoloop execution plan mode was invalid.', []);
1868
- }
1869
- const continuousMode = plan.version === 3 && mode === 'continuous_dag';
1870
- if (!Array.isArray(plan.storyIds) ||
1871
- (!continuousMode && storyIds.length === 0) ||
1872
- storyIds.length !== plan.storyIds.length ||
1873
- storyIds.some((storyId) => !isStoryId(storyId)) ||
1874
- new Set(storyIds).size !== storyIds.length) {
1875
- return rejectPromptExtraction(HEADLESS_REASON_CODES.YOLOOP_METADATA_INVALID, 'Headless yoloop execution plan story selection was invalid or ambiguous.', []);
1876
- }
1877
- if (!isolationPolicy ||
1878
- isolationPolicy.rootOwnsLoop !== true ||
1879
- (isolationPolicy.childPromptKind === 'per_story_branchless_preparation_only' && !continuousMode) ||
1880
- (Object.prototype.hasOwnProperty.call(isolationPolicy, 'childExecutionBoundary') && !continuousMode) ||
1881
- (isolationPolicy.childPromptKind !== 'per_story_yolo_only' &&
1882
- isolationPolicy.childPromptKind !== 'per_story_branchless_preparation_only' &&
1883
- !(isolationPolicy.childPromptKind === 'none' &&
1884
- ((mode === 'serial' && isolationPolicy.childTaskDelegation === 'not_required') ||
1885
- (mode === 'parallel_wave' && plan.executor === 'root_agent' && isolationPolicy.childTaskDelegation === 'forbidden')))) ||
1886
- isolationPolicy.allowOuterYoloopInChild !== false ||
1887
- isolationPolicy.allowMetaTaskPromptInChild !== false) {
1888
- return rejectPromptExtraction(HEADLESS_REASON_CODES.YOLOOP_ISOLATION_VIOLATION, 'Headless yoloop rejected an execution plan that did not preserve root-owned child isolation.', [redaction('isolationPolicy', 'prompt_body', 'value-denied')]);
1889
- }
1890
- const skippedStories = Array.isArray(plan.skippedStories) ? plan.skippedStories : [];
1891
- for (const skipped of skippedStories) {
1892
- if (!isRecord(skipped) || typeof skipped.storyId !== 'string' || !isStoryId(skipped.storyId) || typeof skipped.reason !== 'string') {
1893
- return rejectPromptExtraction(HEADLESS_REASON_CODES.YOLOOP_METADATA_INVALID, 'Headless yoloop skipped-story evidence was malformed.', []);
1894
- }
1895
- if (storyIds.includes(skipped.storyId)) {
1896
- return rejectPromptExtraction(HEADLESS_REASON_CODES.YOLOOP_METADATA_INVALID, 'Headless yoloop selected a story that server evidence marked skipped.', []);
1897
- }
1898
- }
1899
- if (continuousMode) {
1900
- const scheduler = isRecord(plan.scheduler) ? plan.scheduler : undefined;
1901
- const nodes = Array.isArray(scheduler?.nodes) ? scheduler.nodes.filter(isRecord) : [];
1902
- const schedulerReady = safeStringArray(scheduler?.readyStoryIds);
1903
- const schedulerRunning = safeStringArray(scheduler?.runningStoryIds);
1904
- const promptTemplates = safeStringArray(plan.promptTemplates);
1905
- const dependencyBasis = isRecord(plan.dependencyBasis) ? plan.dependencyBasis : undefined;
1906
- const readinessBasis = isRecord(plan.readinessBasis) ? plan.readinessBasis : undefined;
1907
- const graphRevision = typeof scheduler?.graphRevision === 'string' ? scheduler.graphRevision : '';
1908
- const executionBranch = typeof plan.executionBranch === 'string' ? plan.executionBranch : '';
1909
- const nodeIds = nodes.map((node) => typeof node.storyId === 'string' ? node.storyId : '');
1910
- const unsafeNode = nodes.find((node) => {
1911
- const storyId = typeof node.storyId === 'string' ? node.storyId : '';
1912
- const prompt = typeof node.promptTemplate === 'string' ? node.promptTemplate : '';
1913
- const writeSet = Array.isArray(node.writeSet) ? safeStringArray(node.writeSet) : [];
1914
- return !isStoryId(storyId) || prompt !== `*yolo @docs/stories/${storyId}.story.md branchless-preparation`
1915
- || typeof node.dispatchId !== 'string' || !/^[a-f0-9]{64}$/.test(node.dispatchId)
1916
- || typeof node.idempotencyKey !== 'string' || !/^[a-f0-9]{64}$/.test(node.idempotencyKey)
1917
- || node.dependencyBasis !== 'verified'
1918
- || !Array.isArray(node.dependencies) || safeStringArray(node.dependencies).length !== node.dependencies.length
1919
- || !Array.isArray(node.writeSet) || writeSet.length === 0 || writeSet.length !== node.writeSet.length
1920
- || !parseBranchlessRootAuthority(node.childExecutionAuthority, {
1921
- storyId, invocationPrompt: prompt, authorizedWriteSet: writeSet,
1922
- });
1923
- });
1924
- if (plan.executor !== 'root_agent_with_child_tasks'
1925
- || plan.legacyConcurrencyIgnored !== true
1926
- || Object.prototype.hasOwnProperty.call(plan, 'maxConcurrency')
1927
- || Object.prototype.hasOwnProperty.call(plan, 'maxParallel')
1928
- || isolationPolicy?.rootOwnedScheduling !== 'continuous_dag_allowed'
1929
- || isolationPolicy?.childPromptKind !== 'per_story_branchless_preparation_only'
1930
- || isolationPolicy?.childExecutionBoundary !== 'filesystem_only'
1931
- || isolationPolicy?.childTaskDelegation !== 'allowed'
1932
- || isolationPolicy?.maxDepth !== 1
1933
- || isolationPolicy?.childWorkspace !== 'branchless_sandbox'
1934
- || isolationPolicy?.epicCheckout !== 'current_checkout'
1935
- || isolationPolicy?.workspaceLifecycle !== 'user_managed'
1936
- || isolationPolicy?.integrationOwner !== 'root_agent'
1937
- || !scheduler
1938
- || scheduler.schemaVersion !== 1
1939
- || scheduler.strategy !== 'continuous-event-driven-dag'
1940
- || scheduler.logicalConcurrency !== 'ready-set'
1941
- || scheduler.capacityPolicy !== 'backpressure-only'
1942
- || scheduler.rootOwnsLoop !== true
1943
- || scheduler.maxDepth !== 1
1944
- || !/^[a-f0-9]{64}$/.test(graphRevision)
1945
- || !isSafeExecutionBranch(executionBranch)
1946
- || new Set(nodeIds).size !== nodeIds.length
1947
- || nodeIds.some((storyId) => !isStoryId(storyId))
1948
- || schedulerReady.some((storyId) => !nodeIds.includes(storyId))
1949
- || schedulerRunning.some((storyId) => !nodeIds.includes(storyId) || schedulerReady.includes(storyId))
1950
- || !sameStringSet(storyIds, schedulerReady)
1951
- || promptTemplates.length !== storyIds.length
1952
- || promptTemplates.some((prompt, index) => prompt !== `*yolo @docs/stories/${storyIds[index]}.story.md branchless-preparation`)
1953
- || !dependencyBasis || dependencyBasis.source !== 'state_snapshot'
1954
- || !readinessBasis || readinessBasis.source !== 'ready_wave'
1955
- || !sameStringSet(safeStringArray(readinessBasis.selectedStoryIds), storyIds)
1956
- || unsafeNode) {
1957
- return rejectPromptExtraction(HEADLESS_REASON_CODES.YOLOOP_METADATA_INVALID, 'Headless yoloop rejected an invalid continuous DAG execution plan.', []);
1958
- }
1959
- return {
1960
- ok: true,
1961
- mode: 'continuous_dag',
1962
- serverMaxConcurrency: storyIds.length,
1963
- parallelAuthorized: true,
1964
- continuous: true,
1965
- };
1966
- }
1967
- if (plan.version === 2) {
1968
- const phased = validatePhasedYoloopPlan(plan);
1969
- if (!phased.ok) {
1970
- return rejectPromptExtraction(HEADLESS_REASON_CODES.YOLOOP_METADATA_INVALID, 'Headless yoloop rejected an unsafe phased execution plan.', []);
1971
- }
1972
- // A child *yolo performs the complete story lifecycle and may write. Until
1973
- // preparation-only child directives exist, full child execution is pinned
1974
- // to the P207 single writer even when preparation phases allow parallelism.
1975
- return { ok: true, mode: 'parallel_wave', serverMaxConcurrency: phased.childExecutionConcurrency, parallelAuthorized: false, continuous: false };
1976
- }
1977
- if (mode !== 'parallel_wave') {
1978
- return {
1979
- ok: true,
1980
- mode: mode,
1981
- serverMaxConcurrency: 1,
1982
- parallelAuthorized: false,
1983
- continuous: false,
1984
- };
1985
- }
1986
- const maxConcurrency = plan.maxConcurrency;
1987
- const maxParallel = plan.maxParallel;
1988
- const dependencyBasis = isRecord(plan.dependencyBasis) ? plan.dependencyBasis : undefined;
1989
- const readinessBasis = isRecord(plan.readinessBasis) ? plan.readinessBasis : undefined;
1990
- const parallelWaves = Array.isArray(plan.parallelWaves) ? plan.parallelWaves : [];
1991
- const wave = parallelWaves.length === 1 && isRecord(parallelWaves[0]) ? parallelWaves[0] : undefined;
1992
- if (isolationPolicy.rootOwnedScheduling !== 'parallel_wave_allowed' ||
1993
- !Number.isInteger(maxConcurrency) || typeof maxConcurrency !== 'number' || maxConcurrency < 2 || maxConcurrency > storyIds.length ||
1994
- !Number.isInteger(maxParallel) || maxParallel !== maxConcurrency ||
1995
- !dependencyBasis || dependencyBasis.source !== 'state_snapshot' || !sameStringSet(safeStringArray(dependencyBasis.storyIds), storyIds) ||
1996
- !readinessBasis || readinessBasis.source !== 'ready_wave' || !sameStringSet(safeStringArray(readinessBasis.selectedStoryIds), storyIds) ||
1997
- !wave || !sameStringSet(safeStringArray(wave.storyIds), storyIds) || wave.maxConcurrency !== maxConcurrency) {
1998
- return rejectPromptExtraction(HEADLESS_REASON_CODES.YOLOOP_METADATA_INVALID, 'Headless yoloop parallel plan lacked consistent bounded authorization and readiness evidence.', []);
1999
- }
2000
- const wavePrompts = safeStringArray(wave.promptTemplates);
2001
- if (wavePrompts.length !== storyIds.length || new Set(wavePrompts).size !== wavePrompts.length) {
2002
- return rejectPromptExtraction(HEADLESS_REASON_CODES.YOLOOP_METADATA_INVALID, 'Headless yoloop parallel wave prompts were incomplete or ambiguous.', []);
2003
- }
2004
- const proofs = Array.isArray(wave.proofSummaries)
2005
- ? wave.proofSummaries
2006
- : Array.isArray(plan.proofSummaries) ? plan.proofSummaries : [];
2007
- const waveProof = proofs.find((proof) => isRecord(proof) && sameStringSet(safeStringArray(proof.storyIds), storyIds));
2008
- if (!isRecord(waveProof) ||
2009
- waveProof.dependencyClosure !== 'resolved' ||
2010
- waveProof.contractOwnership !== 'non_overlapping' ||
2011
- waveProof.validationSurfaces !== 'compatible') {
2012
- return rejectPromptExtraction(HEADLESS_REASON_CODES.YOLOOP_METADATA_INVALID, 'Headless yoloop parallel plan lacked resolved independence proof.', []);
2013
- }
2014
- const unsafeSkipped = skippedStories.find((skipped) => isRecord(skipped) && typeof skipped.reason === 'string' && /(cycle|unresolved|ambiguous)/i.test(skipped.reason));
2015
- if (unsafeSkipped) {
2016
- return rejectPromptExtraction(HEADLESS_REASON_CODES.YOLOOP_METADATA_INVALID, 'Headless yoloop parallel plan contained unresolved dependency evidence.', []);
2017
- }
2018
- return {
2019
- ok: true,
2020
- mode: 'parallel_wave',
2021
- serverMaxConcurrency: maxConcurrency,
2022
- parallelAuthorized: true,
2023
- continuous: false,
2024
- };
2025
- }
2026
- function parseBranchlessRootAuthority(value, expected) {
2027
- if (!isRecord(value) || !isRecord(value.artifact))
2028
- return undefined;
2029
- const artifact = value.artifact;
2030
- const writeSet = Array.isArray(value.authorizedWriteSet) ? safeStringArray(value.authorizedWriteSet) : [];
2031
- if (Object.keys(value).sort().join('\0') !== [
2032
- 'artifact', 'authorizedWriteSet', 'effectScope', 'invocationPrompt', 'kind',
2033
- 'lifecycleAuthority', 'publicSafe', 'schemaVersion', 'storyId',
2034
- ].sort().join('\0')
2035
- || Object.keys(artifact).sort().join('\0') !== [
2036
- 'content', 'contentBinding', 'kind', 'path', 'schemaVersion',
2037
- ].sort().join('\0')
2038
- || value.schemaVersion !== 1 || value.kind !== 'branchless_story_preparation'
2039
- || value.storyId !== expected.storyId || value.invocationPrompt !== expected.invocationPrompt
2040
- || !Array.isArray(value.authorizedWriteSet)
2041
- || writeSet.length !== value.authorizedWriteSet.length
2042
- || writeSet.some((ref) => normalizeContinuousWriteRef(ref) !== ref)
2043
- || !sameOrderedStrings(writeSet, expected.authorizedWriteSet)
2044
- || value.effectScope !== 'filesystem_only' || value.lifecycleAuthority !== 'root_only'
2045
- || value.publicSafe !== true || artifact.schemaVersion !== 1
2046
- || artifact.kind !== 'branchless_root_bound_artifact'
2047
- || typeof artifact.path !== 'string' || !writeSet.includes(artifact.path)
2048
- || typeof artifact.content !== 'string' || artifact.content.length === 0 || artifact.content.length > 4096
2049
- || typeof artifact.contentBinding !== 'string' || !/^[a-f0-9]{64}$/.test(artifact.contentBinding)) {
2050
- return undefined;
2051
- }
2052
- const expectedBinding = createHash('sha256').update([
2053
- 'branchless-root-bound-artifact-v1', expected.storyId, expected.invocationPrompt,
2054
- ...writeSet, 'filesystem_only', 'root_only', artifact.path, artifact.content,
2055
- ].join('\0')).digest('hex');
2056
- if (artifact.contentBinding !== expectedBinding)
2057
- return undefined;
2058
- return value;
2059
- }
2060
- function sameOrderedStrings(left, right) {
2061
- return left.length === right.length && left.every((value, index) => value === right[index]);
2062
- }
2063
- function extractPlanPrompts(plan) {
2064
- const prompts = [];
2065
- prompts.push(...safeStringArray(plan.promptTemplates));
2066
- for (const step of Array.isArray(plan.serialSteps) ? plan.serialSteps : []) {
2067
- if (isRecord(step) && typeof step.promptTemplate === 'string')
2068
- prompts.push(step.promptTemplate);
2069
- }
2070
- for (const wave of Array.isArray(plan.parallelWaves) ? plan.parallelWaves : []) {
2071
- if (isRecord(wave))
2072
- prompts.push(...safeStringArray(wave.promptTemplates));
2073
- }
2074
- return prompts;
2075
- }
2076
- function normalizeChildPrompt(prompt, epicId, source) {
2077
- if (hasDelegatedPromptIsolationViolation(prompt)) {
2078
- return rejectPromptExtraction(HEADLESS_REASON_CODES.YOLOOP_ISOLATION_VIOLATION, 'Headless yoloop rejected an unsafe child prompt shape.', [redaction('promptTemplate', 'prompt_body', hashPublicValue(prompt))]);
2079
- }
2080
- if (!CHILD_PROMPT_PATTERN.test(prompt)) {
2081
- return rejectPromptExtraction(HEADLESS_REASON_CODES.YOLOOP_METADATA_INVALID, 'Headless yoloop child prompt did not match the canonical per-story yolo shape.', [redaction('promptTemplate', 'prompt_body', hashPublicValue(prompt))]);
2082
- }
2083
- const preparationOnly = BRANCHLESS_PREPARATION_PROMPT_PATTERN.test(prompt);
2084
- const targetRef = prompt.replace(/^\*yolo @/, '').replace(/ branchless-preparation$/, '');
2085
- const storyId = storyIdFromTargetRef(targetRef);
2086
- if (!CHILD_STORY_TARGET_PATTERN.test(targetRef) || !isStoryId(storyId) || !storyId.startsWith(`${epicId}.`)) {
2087
- return rejectPromptExtraction(HEADLESS_REASON_CODES.YOLOOP_ISOLATION_VIOLATION, 'Headless yoloop rejected a child prompt outside the targeted public epic.', [redaction('storyId', 'prompt_body', hashPublicValue(storyId))]);
2088
- }
2089
- return {
2090
- ok: true,
2091
- prompt: { storyId, targetRef, commandRef: prompt, source, ...(preparationOnly ? { preparationOnly: true } : {}) },
2092
- };
2093
- }
2094
- function extractEpicTerminalGitDirective(metadata) {
2095
- const value = metadata?.epicTerminalGitDirective;
2096
- if (!isRecord(value)
2097
- || value.schemaVersion !== 1
2098
- || value.kind !== 'epic_terminal_git'
2099
- || typeof value.epicId !== 'string'
2100
- || typeof value.executionBranch !== 'string'
2101
- || typeof value.originBranch !== 'string'
2102
- || typeof value.expectedExecutionHeadSha !== 'string'
2103
- || !Array.isArray(value.storyCheckpointIds)
2104
- || !isRecord(value.localGates)
2105
- || value.localGates.passed !== true
2106
- || !Array.isArray(value.localGates.receiptRefs)
2107
- || !isRecord(value.reconcile)
2108
- || typeof value.idempotencyKey !== 'string'
2109
- || value.publicSafe !== true)
2110
- return undefined;
2111
- return value;
2112
- }
2113
- function extractEpicGitReconciliationDirective(metadata) {
2114
- const value = metadata?.epicGitReconciliationDirective;
2115
- if (!isRecord(value)
2116
- || value.schemaVersion !== 1
2117
- || value.kind !== 'epic_git_reconciliation'
2118
- || typeof value.epicId !== 'string'
2119
- || typeof value.executionBranch !== 'string'
2120
- || typeof value.originBranch !== 'string'
2121
- || !['start', 'resume', 'audit'].includes(String(value.lifecycleBoundary))
2122
- || typeof value.dryRun !== 'boolean'
2123
- || typeof value.idempotencyKey !== 'string'
2124
- || value.publicSafe !== true)
2125
- return undefined;
2126
- return value;
2127
- }
2128
- function classifyYoloopTerminalMetadata(metadata) {
2129
- if (!metadata || !isRecord(metadata)) {
2130
- return {
2131
- ok: false,
2132
- reasonCode: HEADLESS_REASON_CODES.YOLOOP_METADATA_INVALID,
2133
- publicSummary: 'Headless yoloop root invocation did not return public metadata.',
2134
- redactionSummary: [],
2135
- };
2136
- }
2137
- const decision = isRecord(metadata.yoloopContinuationDecision) ? metadata.yoloopContinuationDecision : undefined;
2138
- const outcome = typeof decision?.outcome === 'string' ? decision.outcome : undefined;
2139
- const complete = outcome === 'queue_exhausted' || metadata.yoloopComplete === true;
2140
- const aborted = metadata.yoloopAborted === true;
2141
- const releaseBlocked = parseReleaseBlockedResult(metadata.releaseBlocked);
2142
- const replay = outcome === 'selected' && decision?.replay === true;
2143
- if (outcome && !['selected', 'queue_exhausted', 'blocked', 'cycle', 'invalid', 'no_progress'].includes(outcome)) {
2144
- return { ok: false, reasonCode: HEADLESS_REASON_CODES.YOLOOP_METADATA_INVALID, publicSummary: 'Headless yoloop rejected an unknown continuation outcome.', redactionSummary: [] };
2145
- }
2146
- if (outcome === 'queue_exhausted' && decision?.terminalSuccess !== true) {
2147
- return { ok: false, reasonCode: HEADLESS_REASON_CODES.YOLOOP_METADATA_INVALID, publicSummary: 'Headless yoloop rejected inconsistent queue exhaustion metadata.', redactionSummary: [] };
2148
- }
2149
- if (complete && aborted) {
2150
- return {
2151
- ok: false,
2152
- reasonCode: HEADLESS_REASON_CODES.YOLOOP_METADATA_INVALID,
2153
- publicSummary: 'Headless yoloop metadata reported mutually exclusive terminal states.',
2154
- redactionSummary: [redaction('yoloopTerminal', 'unsafe_key', 'value-denied')],
2155
- };
2156
- }
2157
- const releaseBlockedSignalled = metadata.yoloopReleaseBlocked === true
2158
- || metadata.terminalClass === 'release-blocked'
2159
- || metadata.releaseBlocked !== undefined;
2160
- if (releaseBlockedSignalled && (!releaseBlocked || metadata.yoloopReleaseBlocked !== true
2161
- || metadata.terminalClass !== 'release-blocked' || complete || aborted || outcome !== undefined)) {
2162
- return {
2163
- ok: false,
2164
- reasonCode: HEADLESS_REASON_CODES.YOLOOP_METADATA_INVALID,
2165
- publicSummary: 'Headless yoloop rejected inconsistent release-blocked terminal metadata.',
2166
- redactionSummary: [],
2167
- };
2168
- }
2169
- return { ok: true, complete, aborted, ...(releaseBlocked ? { releaseBlocked } : {}), outcome, replay };
2170
- }
2171
- function extractResumableExhaustionBoundary(metadata) {
2172
- if (!metadata)
2173
- return undefined;
2174
- const reason = metadata.abortReason;
2175
- if (reason !== 'YOLOOP_PER_RUN_CAP_REACHED' && reason !== 'YOLOOP_SESSION_TIMEOUT')
2176
- return undefined;
2177
- const boundary = metadata.yoloopResumableBoundary;
2178
- const boundedId = /^[A-Za-z0-9._:-]{1,128}$/;
2179
- if (!isRecord(boundary)
2180
- || boundary.schemaVersion !== 'YoloopResumableBoundary/1.0'
2181
- || boundary.resumable !== true
2182
- || boundary.reason !== reason
2183
- || boundary.publicSafe !== true
2184
- || typeof boundary.coolDownUntil !== 'string'
2185
- || !Number.isFinite(Date.parse(boundary.coolDownUntil))
2186
- || !Number.isSafeInteger(boundary.retryAfterMs)
2187
- || boundary.retryAfterMs < 0
2188
- || typeof boundary.operationId !== 'string'
2189
- || !boundedId.test(boundary.operationId)
2190
- || !isRecord(boundary.receipt)
2191
- || boundary.receipt.schemaVersion !== 'YoloopSessionRolloverReceipt/1.0'
2192
- || typeof boundary.receipt.runId !== 'string'
2193
- || !boundedId.test(boundary.receipt.runId)
2194
- || boundary.receipt.operationId !== boundary.operationId
2195
- || typeof boundary.receipt.idempotencyKey !== 'string'
2196
- || !boundedId.test(boundary.receipt.idempotencyKey)
2197
- || typeof boundary.receipt.payloadHash !== 'string'
2198
- || !/^[a-f0-9]{64}$/.test(boundary.receipt.payloadHash)
2199
- || boundary.receipt.coolDownUntil !== boundary.coolDownUntil
2200
- || !Number.isSafeInteger(boundary.receipt.revision)
2201
- || boundary.receipt.revision < 0
2202
- || (boundary.receipt.snapshotHash !== null
2203
- && (typeof boundary.receipt.snapshotHash !== 'string'
2204
- || !/^[a-f0-9]{64}$/.test(boundary.receipt.snapshotHash)))
2205
- || boundary.receipt.status !== 'exhausted'
2206
- || boundary.receipt.publicSafe !== true)
2207
- return undefined;
2208
- return { coolDownUntil: boundary.coolDownUntil, reason };
2209
- }
2210
- function buildChildRunYoloDirective(input) {
2211
- const stableBasis = `${input.rootAttempt.execution_id}:${input.child.graphRevision ?? 'legacy'}:${input.child.storyId}`;
2212
- const operationId = input.child.dispatchId ?? headlessExecutionEntityId('child-op', `${stableBasis}:${input.iteration}`);
2213
- const idempotencyKey = input.child.idempotencyKey ?? headlessExecutionEntityId('child-idem', `${stableBasis}:${input.iteration}`);
2214
- return {
2215
- schemaVersion: 1,
2216
- contractVersion: 'continuity-v1',
2217
- kind: 'run_yolo',
2218
- commandClass: input.rootAttempt.command_class === 'goal-tick' ? 'goal-tick' : 'loop-tick',
2219
- jobId: input.rootAttempt.job_id,
2220
- operationId,
2221
- idempotencyKey,
2222
- targetKind: 'story',
2223
- targetRef: input.child.targetRef,
2224
- commandRef: input.child.commandRef,
2225
- ...(input.child.preparationOnly ? { executionMode: 'branchless_child_preparation' } : {}),
2226
- storyId: input.child.storyId,
2227
- runtime: {
2228
- runtimeId: input.runtimeId,
2229
- ...(input.modelId ? { modelId: input.modelId } : {}),
2230
- source: input.runtimeSource ?? 'explicit',
2231
- reasonCode: input.runtimeSource === 'fallback' ? HEADLESS_REASON_CODES.RUNTIME_FALLBACK : HEADLESS_REASON_CODES.RUNTIME_EXPLICIT,
2232
- publicSafe: true,
2233
- },
2234
- publicSummary: `Root-owned yoloop delegated public story ${input.child.storyId}.`,
2235
- reasonCode: HEADLESS_REASON_CODES.OK,
2236
- metadata: {
2237
- governanceSource: 'delegated-subagent',
2238
- parentAttemptId: input.rootAttempt.attempt_id,
2239
- parentExecutionId: input.rootAttempt.execution_id,
2240
- iteration: input.iteration,
2241
- ...(input.child.dispatchId ? { dispatchId: input.child.dispatchId } : {}),
2242
- ...(input.child.graphRevision ? { graphRevision: input.child.graphRevision } : {}),
2243
- ...(input.child.writeSet ? { writeSet: input.child.writeSet } : {}),
2244
- ...(input.child.executionBranch ? { executionBranch: input.child.executionBranch } : {}),
2245
- ...(input.child.graphRevision ? {
2246
- childWorkspace: 'branchless_sandbox',
2247
- epicCheckout: 'current_checkout',
2248
- workspaceLifecycle: 'user_managed',
2249
- integrationOwner: 'root_agent',
2250
- maxDepth: 1,
2251
- } : {}),
2252
- publicSafe: true,
2253
- },
2254
- attempts: [],
2255
- redactionSummary: [redaction('prompt', 'prompt_body', hashPublicValue(input.child.commandRef))],
2256
- publicSafe: true,
2257
- };
2258
- }
2259
- function persistYoloopAttemptOutcome(store, attempt, outcome) {
2260
- const hashes = sanitizePublicRecord(outcome.hashes);
2261
- const workerPoolSummary = outcome.workerPoolSummary ?? defaultWorkerPoolSummary();
2262
- const counts = sanitizePublicRecord({
2263
- iterations: outcome.counts.iterations,
2264
- childCount: outcome.counts.childCount,
2265
- succeededChildCount: outcome.counts.succeededChildCount,
2266
- failedChildCount: outcome.counts.failedChildCount,
2267
- skippedChildCount: outcome.counts.skippedChildCount,
2268
- metadataCompleteCount: outcome.counts.metadataCompleteCount,
2269
- metadataAbortedCount: outcome.counts.metadataAbortedCount,
2270
- serverMaxConcurrency: workerPoolSummary.serverMaxConcurrency,
2271
- localCap: workerPoolSummary.localCap,
2272
- queueCap: workerPoolSummary.queueCap,
2273
- availableLeases: workerPoolSummary.availableLeases,
2274
- effectiveConcurrency: workerPoolSummary.effectiveConcurrency,
2275
- peakConcurrency: workerPoolSummary.peakConcurrency,
2276
- pendingChildCount: workerPoolSummary.pendingChildCount,
2277
- startedChildCount: workerPoolSummary.startedChildCount,
2278
- completedChildCount: workerPoolSummary.completedChildCount,
2279
- backpressurePauseCount: workerPoolSummary.backpressurePauseCount,
2280
- });
2281
- const outcomeMetadata = {
2282
- schemaVersion: 1,
2283
- contractVersion: 'continuity-v1',
2284
- attemptId: attempt.attempt_id,
2285
- executionId: attempt.execution_id,
2286
- jobId: attempt.job_id,
2287
- directiveHash: attempt.directive_hash,
2288
- status: outcome.status,
2289
- reasonCode: outcome.reasonCode,
2290
- storyIds: outcome.childStoryIds.slice(0, 50),
2291
- counts,
2292
- hashes,
2293
- ...(outcome.reasonCode === AUTONOMOUS_GOVERNANCE_REASON_CODES.BYPASS_BLOCKED ? { governanceEvidence: AUTONOMOUS_GOVERNANCE_EVIDENCE_TAG } : {}),
2294
- reasonCodes: unique([outcome.reasonCode, ...workerPoolSummary.reasonCodes, ...outcome.stateTransitions]),
2295
- publicSummary: boundPublicSummary(outcome.publicSummary),
2296
- ...(outcome.terminalClass ? { terminalClass: outcome.terminalClass } : {}),
2297
- ...(outcome.releaseBlocked ? { releaseBlocked: outcome.releaseBlocked } : {}),
2298
- };
2299
- const governance = readAutonomousGovernanceEnvelopeFromMetadata(attempt.metadata_json, {
2300
- autonomousKind: 'run_yoloop',
2301
- jobId: attempt.job_id,
2302
- targetKind: 'epic',
2303
- targetRef: attempt.target_ref,
2304
- });
2305
- // Backoff reuses the same attempt row. Preserve only its already-validated,
2306
- // public-safe authority envelope so the next tick cannot lose authorization
2307
- // when completion metadata replaces the queued metadata.
2308
- const metadata = governance.ok
2309
- ? autonomousGovernanceMetadata(governance.envelope, outcomeMetadata)
2310
- : outcomeMetadata;
2311
- store.completeHeadlessExecutionAttempt({
2312
- attemptId: attempt.attempt_id,
2313
- executionId: attempt.execution_id,
2314
- jobId: attempt.job_id,
2315
- leaseId: outcome.leaseId,
2316
- runnerId: outcome.runnerId,
2317
- status: outcome.status,
2318
- completedAt: outcome.completedAt,
2319
- durationMs: outcome.durationMs,
2320
- reasonCode: outcome.reasonCode,
2321
- publicSummary: boundPublicSummary(outcome.publicSummary),
2322
- notBeforeAt: outcome.notBeforeAt,
2323
- retryCount: outcome.retryCount,
2324
- counts,
2325
- hashes,
2326
- redactionSummary: outcome.redactionSummary,
2327
- relativePaths: unique([attempt.target_ref, ...outcome.relativePaths]),
2328
- metadata,
2329
- });
2330
- store.recordHeadlessExecutionReceipt({
2331
- receiptId: `receipt-${headlessExecutionEntityId('headless-yoloop', `${attempt.attempt_id}-${outcome.status}`)}`,
2332
- attemptId: attempt.attempt_id,
2333
- executionId: attempt.execution_id,
2334
- jobId: attempt.job_id,
2335
- status: outcome.receiptStatus,
2336
- reasonCode: outcome.reasonCode,
2337
- createdAt: outcome.completedAt,
2338
- operationId: `${attempt.execution_id}:${outcome.status}:receipt`,
2339
- idempotencyKey: `${attempt.directive_hash}:${outcome.status}:receipt`,
2340
- counts,
2341
- hashes,
2342
- redactionSummary: outcome.redactionSummary,
2343
- relativePaths: unique([attempt.target_ref, ...outcome.relativePaths]),
2344
- metadata,
2345
- });
2346
- store.recordHeadlessExecutionSummary({
2347
- eventId: `event-${headlessExecutionEntityId('headless-yoloop-summary', `${attempt.attempt_id}-${outcome.status}`)}`,
2348
- attemptId: attempt.attempt_id,
2349
- executionId: attempt.execution_id,
2350
- jobId: attempt.job_id,
2351
- status: outcome.status,
2352
- runtimeId: outcome.runtimeId,
2353
- modelId: outcome.modelId,
2354
- publicSummary: boundPublicSummary(outcome.publicSummary),
2355
- reasonCode: outcome.reasonCode,
2356
- createdAt: outcome.completedAt,
2357
- durationMs: outcome.durationMs,
2358
- counts,
2359
- hashes,
2360
- redactionSummary: outcome.redactionSummary,
2361
- relativePaths: unique([attempt.target_ref, ...outcome.relativePaths]),
2362
- metadata,
2363
- });
2364
- return {
2365
- attemptId: attempt.attempt_id,
2366
- executionId: attempt.execution_id,
2367
- jobId: attempt.job_id,
2368
- status: outcome.status,
2369
- outcome: outcome.receiptStatus,
2370
- reasonCode: outcome.reasonCode,
2371
- timestamp: outcome.completedAt,
2372
- childStoryIds: outcome.childStoryIds,
2373
- aggregateCounts: outcome.counts,
2374
- workerPoolSummary,
2375
- redactionSummary: outcome.redactionSummary,
2376
- ...(outcome.terminalClass ? { terminalClass: outcome.terminalClass } : {}),
2377
- ...(outcome.releaseBlocked ? { releaseBlocked: outcome.releaseBlocked } : {}),
2378
- publicSafe: true,
2379
- };
2380
- }
2381
- function emptyYoloopReceipt(attempt, input) {
2382
- return {
2383
- attemptId: attempt.attempt_id,
2384
- executionId: attempt.execution_id,
2385
- jobId: attempt.job_id,
2386
- status: input.status,
2387
- outcome: input.receiptStatus,
2388
- reasonCode: input.reasonCode,
2389
- timestamp: input.timestamp,
2390
- childStoryIds: [],
2391
- aggregateCounts: emptyAggregateCounts(),
2392
- workerPoolSummary: defaultWorkerPoolSummary(),
2393
- redactionSummary: [],
2394
- publicSafe: true,
2395
- };
2396
- }
2397
- function retryDecision(attempt, result, maxAttempts, backoffMs, nowIso) {
2398
- if (!result.retryable)
2399
- return { retry: false };
2400
- if (RESUMABLE_YOLOOP_BOUNDARY_REASONS.has(result.reasonCode)) {
2401
- return {
2402
- retry: true,
2403
- // A valid operational boundary is a resumable checkpoint, not a failed
2404
- // attempt. Preserve the generic failure budget across any number of
2405
- // server-authorized timeout/per-run successor boundaries.
2406
- retryCount: attempt.retry_count,
2407
- notBeforeAt: laterIsoTimestamp(addMilliseconds(nowIso, backoffMs), result.retryNotBeforeAt),
2408
- };
2409
- }
2410
- const retryCount = attempt.retry_count + 1;
2411
- if (retryCount >= Math.max(1, attempt.max_attempts || maxAttempts))
2412
- return { retry: false, retryCount };
2413
- const multiplier = Math.min(8, 2 ** Math.max(0, attempt.retry_count));
2414
- return {
2415
- retry: true,
2416
- retryCount,
2417
- notBeforeAt: laterIsoTimestamp(addMilliseconds(nowIso, backoffMs * multiplier), result.retryNotBeforeAt),
2418
- };
2419
- }
2420
- function driverResult(input) {
2421
- return {
2422
- status: input.status,
2423
- receiptStatus: input.receiptStatus,
2424
- reasonCode: input.reasonCode,
2425
- publicSummary: input.publicSummary,
2426
- retryable: input.retryable,
2427
- ...(input.retryNotBeforeAt ? { retryNotBeforeAt: input.retryNotBeforeAt } : {}),
2428
- durationMs: Math.max(0, Date.now() - input.startedAt),
2429
- counts: input.counts,
2430
- workerPoolSummary: input.workerPoolSummary ?? defaultWorkerPoolSummary(),
2431
- hashes: input.hashes,
2432
- redactionSummary: input.redactions.slice(0, 50),
2433
- relativePaths: unique(input.relativePaths).slice(0, 50),
2434
- childStoryIds: unique(input.childStoryIds).slice(0, 50),
2435
- stateTransitions: unique(input.stateTransitions),
2436
- ...(input.terminalClass ? { terminalClass: input.terminalClass } : {}),
2437
- ...(input.releaseBlocked ? { releaseBlocked: input.releaseBlocked } : {}),
2438
- };
2439
- }
2440
- function validateDirectiveRuntime(value, redactions) {
2441
- if (value === undefined)
2442
- return undefined;
2443
- if (!isRecord(value)) {
2444
- redactions.push(redaction('runtime', 'unsafe_key', 'value-denied'));
2445
- return undefined;
2446
- }
2447
- for (const key of Object.keys(value)) {
2448
- if (!RUNTIME_ALLOWED_KEYS.has(key) || UNSAFE_KEY_PATTERN.test(key))
2449
- redactions.push(redaction(`runtime.${key}`, unsafeKeyReason(key), 'key-denied'));
2450
- }
2451
- if (value.publicSafe !== true)
2452
- redactions.push(redaction('runtime.publicSafe', 'unsafe_key', 'value-denied'));
2453
- const runtimeId = stringField(value, 'runtimeId');
2454
- const modelId = stringField(value, 'modelId');
2455
- const source = stringField(value, 'source');
2456
- if (runtimeId && (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,79}$/.test(runtimeId) || UNSAFE_VALUE_PATTERN.test(runtimeId) || SHELL_FRAGMENT_PATTERN.test(runtimeId))) {
2457
- redactions.push(redaction('runtime.runtimeId', 'unsafe_key', 'value-denied'));
2458
- }
2459
- if (modelId && (!/^[A-Za-z0-9][A-Za-z0-9._:+/-]{0,119}$/.test(modelId) || UNSAFE_VALUE_PATTERN.test(modelId) || SHELL_FRAGMENT_PATTERN.test(modelId))) {
2460
- redactions.push(redaction('runtime.modelId', 'unsafe_key', 'value-denied'));
2461
- }
2462
- if (source !== undefined && source !== 'explicit' && source !== 'origin' && source !== 'default' && source !== 'fallback' && source !== 'unspecified') {
2463
- redactions.push(redaction('runtime.source', 'unsafe_key', 'value-denied'));
2464
- }
2465
- if (value.reasonCode !== undefined && (typeof value.reasonCode !== 'string' || UNSAFE_VALUE_PATTERN.test(value.reasonCode))) {
2466
- redactions.push(redaction('runtime.reasonCode', 'unsafe_key', 'value-denied'));
2467
- }
2468
- if (value.publicSafe !== true)
2469
- return undefined;
2470
- return {
2471
- ...(runtimeId ? { runtimeId } : {}),
2472
- ...(modelId ? { modelId } : {}),
2473
- ...(source === 'explicit' || source === 'origin' || source === 'default' || source === 'fallback' || source === 'unspecified' ? { source } : {}),
2474
- ...(typeof value.reasonCode === 'string' ? { reasonCode: value.reasonCode } : {}),
2475
- publicSafe: true,
2476
- };
2477
- }
2478
- function extractExecutionDirectiveCandidates(metadata) {
2479
- const records = Array.isArray(metadata) ? metadata : metadata ? [metadata] : [];
2480
- const directives = [];
2481
- for (const record of records) {
2482
- const value = record.continuityExecutionDirectives;
2483
- if (Array.isArray(value))
2484
- directives.push(...value);
2485
- }
2486
- return directives;
2487
- }
2488
- function hashDirective(directive) {
2489
- return hashPublicValue(stableJson({
2490
- kind: directive.kind,
2491
- commandClass: directive.commandClass,
2492
- jobId: directive.jobId,
2493
- targetRef: directive.targetRef,
2494
- commandRef: directive.commandRef,
2495
- epicId: directive.epicId,
2496
- runtime: directive.runtime,
2497
- }));
2498
- }
2499
- function stableJson(value) {
2500
- if (Array.isArray(value))
2501
- return `[${value.map(stableJson).join(',')}]`;
2502
- if (isRecord(value)) {
2503
- return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableJson(value[key])}`).join(',')}}`;
2504
- }
2505
- return JSON.stringify(value);
2506
- }
2507
- function assertPublicSafeCandidate(value, path, redactions) {
2508
- if (typeof value === 'string') {
2509
- if (UNSAFE_VALUE_PATTERN.test(value) || SHELL_FRAGMENT_PATTERN.test(value))
2510
- redactions.push(redaction(path, unsafeKeyReason(path), 'value-denied'));
2511
- return;
2512
- }
2513
- if (value === undefined || value === null || typeof value === 'number' || typeof value === 'boolean')
2514
- return;
2515
- if (Array.isArray(value)) {
2516
- value.forEach((item, index) => assertPublicSafeCandidate(item, `${path}.${index}`, redactions));
2517
- return;
2518
- }
2519
- if (isRecord(value)) {
2520
- for (const [key, child] of Object.entries(value)) {
2521
- const field = `${path}.${key}`;
2522
- if (UNSAFE_KEY_PATTERN.test(key))
2523
- redactions.push(redaction(field, unsafeKeyReason(key), 'key-denied'));
2524
- assertPublicSafeCandidate(child, field, redactions);
2525
- }
2526
- return;
2527
- }
2528
- redactions.push(redaction(path, 'unsafe_key', 'value-denied'));
2529
- }
2530
- function validateDirectiveRedactions(value, redactions) {
2531
- if (value === undefined)
2532
- return [];
2533
- if (!Array.isArray(value)) {
2534
- redactions.push(redaction('redactionSummary', 'unsafe_key', 'value-denied'));
2535
- return [];
2536
- }
2537
- const safe = [];
2538
- for (const [index, item] of value.entries()) {
2539
- if (!isRecord(item) || item.publicSafe !== true) {
2540
- redactions.push(redaction(`redactionSummary.${index}`, 'unsafe_key', 'value-denied'));
2541
- continue;
2542
- }
2543
- const field = stringField(item, 'field');
2544
- const reason = stringField(item, 'reason');
2545
- const evidence = stringField(item, 'evidence');
2546
- if (!field || !reason || !evidence || UNSAFE_VALUE_PATTERN.test(field) || UNSAFE_VALUE_PATTERN.test(reason) || UNSAFE_VALUE_PATTERN.test(evidence)) {
2547
- redactions.push(redaction(`redactionSummary.${index}`, 'unsafe_key', 'value-denied'));
2548
- continue;
2549
- }
2550
- safe.push({ field, reason, evidence, publicSafe: true });
2551
- }
2552
- return safe;
2553
- }
2554
- function rejectPromptExtraction(reasonCode, publicSummary, redactionSummary) {
2555
- return { ok: false, reasonCode, publicSummary, redactionSummary };
2556
- }
2557
- function safeStringArray(value) {
2558
- return Array.isArray(value) ? value.filter((item) => typeof item === 'string') : [];
2559
- }
2560
- function isSafeExecutionBranch(value) {
2561
- return value.length > 0 && value.length <= 240 && !value.startsWith('-') && !value.includes('..')
2562
- && !value.includes('\\') && /^[A-Za-z0-9._/-]+$/.test(value);
2563
- }
2564
- function sameStringSet(left, right) {
2565
- return left.length === right.length && new Set(left).size === left.length && left.every((item) => right.includes(item));
2566
- }
2567
- function safeAttemptRelativePaths(attempt) {
2568
- return EPIC_TARGET_PATTERN.test(attempt.target_ref) ? [attempt.target_ref] : [];
2569
- }
2570
- function sanitizePublicRecord(record) {
2571
- if (!record)
2572
- return undefined;
2573
- const output = {};
2574
- for (const [key, value] of Object.entries(record)) {
2575
- if (!/^[A-Za-z0-9_.:-]{1,80}$/.test(key) || UNSAFE_KEY_PATTERN.test(key) || UNSAFE_VALUE_PATTERN.test(key))
2576
- continue;
2577
- if (typeof value === 'string' && UNSAFE_VALUE_PATTERN.test(value))
2578
- continue;
2579
- output[key] = value;
2580
- }
2581
- return Object.keys(output).length > 0 ? output : undefined;
2582
- }
2583
- function emptyAggregateCounts() {
2584
- return aggregateCounts(0, 0, 0, 0, 0, 0, 0);
2585
- }
2586
- function aggregateCounts(iterations, childCount, succeededChildCount, failedChildCount, skippedChildCount, metadataCompleteCount, metadataAbortedCount) {
2587
- return { iterations, childCount, succeededChildCount, failedChildCount, skippedChildCount, metadataCompleteCount, metadataAbortedCount };
2588
- }
2589
- function storyIdFromTargetRef(targetRef) {
2590
- return targetRef.replace(/^docs\/stories\//, '').replace(/\.story\.md$/, '');
2591
- }
2592
- function epicIdFromTargetRef(targetRef) {
2593
- return targetRef.replace(/^docs\/epics\/epic-/, '').replace(/\.md$/, '');
2594
- }
2595
- function isStoryId(value) {
2596
- return /^[A-Za-z0-9][A-Za-z0-9_-]*\.\d+[A-Za-z0-9_-]*$/.test(value) && !UNSAFE_VALUE_PATTERN.test(value) && !SHELL_FRAGMENT_PATTERN.test(value);
2597
- }
2598
- function normalizeRuntimeSource(value) {
2599
- if (value === 'explicit' || value === 'origin' || value === 'default' || value === 'fallback')
2600
- return value;
2601
- return undefined;
2602
- }
2603
- function normalizeStoredRuntimeSource(value) {
2604
- if (value === 'explicit' || value === 'origin' || value === 'default' || value === 'fallback' || value === 'unspecified')
2605
- return value;
2606
- return undefined;
2607
- }
2608
- function unsafeKeyReason(key) {
2609
- if (/prompt|commandRef/i.test(key))
2610
- return 'prompt_body';
2611
- if (/std(?:out|err)|raw|log|transcript|stack/i.test(key))
2612
- return 'raw_log';
2613
- if (/url/i.test(key))
2614
- return 'private_url';
2615
- if (/path|cwd|argv|args|shell|command|binary|executable/i.test(key))
2616
- return 'executable_path';
2617
- if (/secret|token|password|authorization|api[_-]?key|license/i.test(key))
2618
- return 'secret_or_pii';
2619
- return 'unsafe_key';
2620
- }
2621
- function stringField(record, key) {
2622
- return typeof record[key] === 'string' ? record[key] : undefined;
2623
- }
2624
- function isSafeIdentifier(value) {
2625
- return Boolean(value && SAFE_ID_PATTERN.test(value) && !UNSAFE_VALUE_PATTERN.test(value) && !SHELL_FRAGMENT_PATTERN.test(value));
2626
- }
2627
- function isRecord(value) {
2628
- return typeof value === 'object' && value !== null && !Array.isArray(value);
2629
- }
2630
- function defaultHeadlessIdFactory(prefix, attemptId) {
2631
- return headlessExecutionEntityId(prefix, `${attemptId}-${Date.now()}-${randomBytes(4).toString('hex')}`);
2632
- }
2633
- function addMilliseconds(iso, ms) {
2634
- const base = Date.parse(iso);
2635
- return new Date((Number.isFinite(base) ? base : Date.now()) + ms).toISOString();
2636
- }
2637
- function laterIsoTimestamp(left, right) {
2638
- const leftMs = Date.parse(left);
2639
- const rightMs = right ? Date.parse(right) : Number.NaN;
2640
- if (!Number.isFinite(rightMs))
2641
- return left;
2642
- if (!Number.isFinite(leftMs))
2643
- return right;
2644
- return rightMs > leftMs ? right : left;
2645
- }
2646
- function boundedInteger(value, min, max) {
2647
- if (!Number.isFinite(value))
2648
- return min;
2649
- return Math.max(min, Math.min(max, Math.floor(value)));
2650
- }
2651
- function unique(values) {
2652
- return Array.from(new Set(values));
2653
- }
2654
- function uniqueBy(values, key) {
2655
- const seen = new Set();
2656
- const output = [];
2657
- for (const value of values) {
2658
- const itemKey = key(value);
2659
- if (seen.has(itemKey))
2660
- continue;
2661
- seen.add(itemKey);
2662
- output.push(value);
2663
- }
2664
- return output;
2665
- }
10
+ `],{cwd:r.projectRoot,stdio:["ignore","pipe","pipe","ipc"],windowsHide:!0});let d,c=0,l=!1;const p=setTimeout(()=>{l=!0,n.kill()},r.timeoutMs),m=y=>{c+=y.length,c>32*1024*1024&&(l=!0,n.kill())};n.stdout?.on("data",m),n.stderr?.on("data",m),n.on("message",y=>{if(d||!C(y)||typeof y.success!="boolean"||Buffer.byteLength(JSON.stringify(y))>32*1024*1024){l=!0,n.kill();return}d=y});const u={success:!1,errorCode:"headless-root-invoke-failed",error:"The isolated root metadata invocation did not complete.",exitCode:1};n.on("error",()=>{l=!0}),n.on("close",y=>{clearTimeout(p),s(y===0&&!l&&d?d:u)}),n.send({modulePath:o,options:e},y=>{y&&(l=!0,n.kill())})})}async function Nt(e,r=Mt){const t=Date.now(),a={args:e.args,projectRoot:e.projectRoot,format:"json",platformTarget:"runner",serverUrl:e.serverUrl,strictReadOnly:e.strictReadOnly},o=await r(a,{projectRoot:e.projectRoot,timeoutMs:e.timeoutMs});return{success:o.success,instructions:o.instructions,metadata:o.metadata,error:o.error,errorCode:o.errorCode,exitCode:o.exitCode,durationMs:Date.now()-t,publicSafe:!0}}async function Hr(e){const r=e.adapterRegistry??Ge(),t=V(e.limit??Qe,1,10),a=V(e.leaseMs??bt,1e3,oe.terminalWorkflowMaxDurationMs),o=V(e.staleLeaseAfterMs??tt,0,1440*60*1e3),s=V(e.maxAttempts??et,1,10),n=V(e.localConcurrencyCap??we(),1,Pe),d=[],c=[],l=e.storyWorktreeSignalSweep===!0?pt(e.projectRoot):void 0;try{const p=[];if(e.storyWorktreeSweeper!==!1){const u=e.storyWorktreeSweeper??mt;try{p.push(...(await u(e.projectRoot)).reasonCodes)}catch{p.push("story-worktree-sweep-failed")}}const m=await Bt(e,{registry:r,limit:t,leaseMs:a,staleLeaseAfterMs:o,maxAttempts:s,localConcurrencyCap:n,reasonCodes:d,receipts:c});return p.length===0?m:{...m,reasonCodes:U([...m.reasonCodes,...p])}}finally{l?.()}}async function Bt(e,r){const{registry:t,limit:a,leaseMs:o,staleLeaseAfterMs:s,maxAttempts:n,localConcurrencyCap:d,reasonCodes:c,receipts:l}=r,p=e.now(),m=jt({store:e.store,metadata:e.metadata,nowIso:p,maxAttempts:n,queueCap:e.queueCap});c.push(...m.reasonCodes);const u=e.store.recoverStaleHeadlessExecutionAttempts({nowIso:p,staleAfterMs:s,limit:a*2});u.recoveredAttemptIds.length>0&&(c.push(f.EXECUTION_BACKOFF),u.failedAttemptIds.length>0&&c.push(f.EXECUTION_TIMEOUT));const y=e.store.listDueHeadlessExecutionAttempts({nowIso:e.now(),limit:Math.max(a*5,10)}).filter(_=>_.directive_kind==="run_yoloop").slice(0,a);for(const _ of y){const E=await Ht({store:e.store,projectRoot:e.projectRoot,runnerId:e.runnerId,attempt:_,registry:t,now:e.now,leaseMs:o,timeoutMs:V(e.timeoutMs??rt,1e3,oe.terminalWorkflowMaxDurationMs),backoffMs:V(e.backoffMs??Je,1e3,36e5),maxAttempts:n,maxIterations:V(e.maxIterations??It,1,100),maxDurationMs:V(e.maxDurationMs??St,1e3,oe.terminalWorkflowMaxDurationMs),localConcurrencyCap:d,queueCap:e.queueCap,adapterOptions:e.adapterOptions,runtimeDefaults:e.runtimeDefaults,runtimeFallback:e.runtimeFallback,yoloopInvoker:e.yoloopInvoker??Nt,serverUrl:e.serverUrl,idFactory:e.idFactory??mr,continuousWorkspaceManager:e.continuousWorkspaceManager??ct(),terminalGitAdapter:e.terminalGitAdapter??ut(e.projectRoot)});l.push(E),c.push(E.reasonCode,...E.workerPoolSummary.reasonCodes)}return{ok:l.every(_=>_.outcome!=="failed")&&m.rejectedCount===0,enqueuedAttemptCount:m.enqueuedCount,dueAttemptCount:y.length,processedAttemptCount:l.filter(_=>_.outcome!=="ignored").length,recoveredAttemptIds:u.recoveredAttemptIds,receipts:l,reasonCodes:U(c.length>0?c:[f.OK]),publicSafe:!0}}function jt(e){let r=0,t=0;const a=[];for(const o of nr(e.metadata)){if(!C(o)||o.kind!=="run_yoloop")continue;const s=Yt(o);if(!s.ok){t+=1,a.push(s.reasonCode);continue}const n=s.directive;if(!e.store.jobExists(n.jobId)){t+=1,a.push(Ee.BYPASS_BLOCKED);continue}const d=sr(n);if(e.store.hasCompletedHeadlessExecutionDirectiveHash(d)){a.push(f.EXECUTION_COMPLETED);continue}const c=We({autonomousKind:"run_yoloop",source:"headless-run-yoloop",targetKind:"epic",targetRef:n.targetRef,epicId:n.epicId??se(n.targetRef),jobId:n.jobId,operationSeed:n.operationId,commandHash:x(n.commandRef)}),l=qe(e.store,c,e.nowIso,{requireExistingJob:!0});if(!l.ok){t+=1,a.push(l.reasonCode);continue}const p=W("attempt",n.idempotencyKey),m=W("exec",n.operationId),u=e.store.enqueueHeadlessExecutionAttempt({attemptId:p,executionId:m,jobId:n.jobId,directiveHash:d,directiveKind:"run_yoloop",commandClass:n.commandClass,targetKind:"epic",targetRef:n.targetRef,epicId:n.epicId??se(n.targetRef),runtimeId:n.runtime?.runtimeId,modelId:n.runtime?.modelId,runtimeSource:pr(n.runtime?.source),reasonCode:n.reasonCode,publicSummary:n.publicSummary,enqueuedAt:e.nowIso,notBeforeAt:e.nowIso,maxAttempts:e.maxAttempts,queueCap:e.queueCap,operationId:`${n.operationId}:enqueue`,idempotencyKey:n.idempotencyKey,counts:{directives:1},hashes:{directive:d},redactionSummary:n.redactionSummary,relativePaths:[n.targetRef],metadata:Re(c,{schemaVersion:1,contractVersion:"continuity-v1",jobId:n.jobId,operationId:n.operationId,reasonCode:n.reasonCode??f.OK,targetRef:n.targetRef,directiveHash:d})});if(!u.accepted){t+=1,a.push(u.reasonCode??"queue-cap-reached");continue}u.inserted&&(r+=1),a.push(f.OK)}return{enqueuedCount:r,rejectedCount:t,reasonCodes:U(a)}}async function Ht(e){const r=e.now(),t=e.idFactory("lease",e.attempt.attempt_id),a=be(r,e.leaseMs);if(!e.store.claimHeadlessExecutionAttempt({attemptId:e.attempt.attempt_id,leaseId:t,runnerId:e.runnerId,claimedAt:r,leaseExpiresAt:a,reasonCode:f.OK}).inserted)return rr(e.attempt,{status:e.attempt.status,receiptStatus:"ignored",reasonCode:"lease-conflict",timestamp:r});if(e.store.hasCompletedHeadlessExecutionDirectiveHash(e.attempt.directive_hash,e.attempt.attempt_id))return Ce(e.store,e.attempt,{leaseId:t,runnerId:e.runnerId,status:"skipped",receiptStatus:"ignored",reasonCode:f.EXECUTION_COMPLETED,publicSummary:"Skipped duplicate run_yoloop directive because the directive hash is already completed.",completedAt:e.now(),counts:Ie(),hashes:{directive:e.attempt.directive_hash},redactionSummary:[],relativePaths:[e.attempt.target_ref],childStoryIds:[],stateTransitions:["start","complete"]});const n=Kt(e);if(!n.ok)return Ce(e.store,e.attempt,{leaseId:t,runnerId:e.runnerId,status:n.status,receiptStatus:n.receiptStatus,reasonCode:n.reasonCode,publicSummary:n.publicSummary,completedAt:e.now(),counts:Ie(),hashes:{directive:e.attempt.directive_hash},redactionSummary:n.redactionSummary,relativePaths:dr(e.attempt),childStoryIds:[],stateTransitions:["start"]});const d=await zt({...e,prepared:n.input}),c=or(e.attempt,d,e.maxAttempts,e.backoffMs,e.now()),l=c.retry?"backoff":d.status,p=c.retry?"deferred":d.receiptStatus,m=c.retry?Dt.has(d.reasonCode)||xe.has(d.reasonCode)?d.reasonCode:f.EXECUTION_BACKOFF:d.reasonCode,u=c.retry?"Headless run_yoloop execution scheduled bounded retry after transient metadata/runtime outcome.":d.publicSummary;return Ce(e.store,e.attempt,{leaseId:t,runnerId:e.runnerId,status:l,receiptStatus:p,reasonCode:m,publicSummary:u,completedAt:e.now(),durationMs:d.durationMs,notBeforeAt:c.notBeforeAt,retryCount:c.retryCount,counts:d.counts,workerPoolSummary:d.workerPoolSummary,hashes:{...d.hashes,directive:e.attempt.directive_hash},redactionSummary:d.redactionSummary,relativePaths:d.relativePaths,childStoryIds:d.childStoryIds,runtimeId:n.input.runtimeId,modelId:n.input.modelId,runtimeSource:n.input.runtimeSource,stateTransitions:d.stateTransitions,terminalClass:d.terminalClass,releaseBlocked:d.releaseBlocked})}async function zt(e){const r=Date.now(),t=["start"],a=new Set,o=[],s=[],n={root:x(e.prepared.rootPrompt)},d=[h("rootPrompt","prompt_body",n.root)];let c=0,l=0,p=0,m=0,u=0,y=0,_,E=!1;const i=Me(e.localConcurrencyCap),R=new Map;let H=!1;const z=new Map,$=new Map,ie=w=>{const S=w.child;n[`child-${S.storyId.replace(/[^A-Za-z0-9_.:-]/g,"-")}`]=w.commandHash,d.push(w.promptRedaction);const M=w.receipt;if(w.terminalFailure){if(w.deferredFailure){z.set(S.storyId,w.terminalFailure),i.backpressurePauseCount+=1;return}z.delete(S.storyId),$.set(S.storyId,w.terminalFailure),a.has(S.storyId)||(a.add(S.storyId),o.push(S.storyId),s.push(S.targetRef),p+=1);return}if(!M||M.outcome==="deferred"){z.set(S.storyId,w.reasonCodes.includes("queue-cap-reached")?f.WORKER_POOL_BACKPRESSURE_PAUSED:M?.reasonCode||f.EXECUTION_BACKOFF),w.reasonCodes.includes("queue-cap-reached")&&(i.backpressurePauseCount+=1);return}z.delete(S.storyId),!a.has(S.storyId)&&(a.add(S.storyId),o.push(S.storyId),s.push(S.targetRef),M.outcome==="failed"?(p+=1,$.set(S.storyId,M.reasonCode||f.EXECUTION_FAILED)):M.outcome==="ignored"?m+=1:l+=1)},X=async()=>{const w=await Promise.race([...R.entries()].map(([S,M])=>M.promise.then(b=>({storyId:S,result:b}))));R.delete(w.storyId),i.completedChildCount+=1,i.pendingChildCount=R.size,ie(w.result)};for(;;){if(c>=e.maxIterations)return t.push("backoff"),O({status:"failed",receiptStatus:"failed",reasonCode:xt,publicSummary:"Headless yoloop reached the bounded iteration limit before completion metadata.",retryable:!1,startedAt:r,counts:k(c,o.length,l,p,m,u,y),workerPoolSummary:A(i),hashes:n,redactions:d,relativePaths:[e.prepared.targetRef,...s],childStoryIds:o,stateTransitions:t});if(Date.now()-r>e.maxDurationMs)return t.push("backoff"),O({status:"failed",receiptStatus:"failed",reasonCode:Lt,publicSummary:"Headless yoloop reached the bounded duration limit before completion metadata.",retryable:!1,startedAt:r,counts:k(c,o.length,l,p,m,u,y),workerPoolSummary:A(i),hashes:n,redactions:d,relativePaths:[e.prepared.targetRef,...s],childStoryIds:o,stateTransitions:t});t.push("metadata_parse");const w=await e.yoloopInvoker({projectRoot:e.projectRoot,args:e.prepared.rootPrompt,attemptId:e.attempt.attempt_id,executionId:e.attempt.execution_id,jobId:e.attempt.job_id,runnerId:e.runnerId,iteration:c,runtimeId:e.prepared.runtimeId,...e.prepared.modelId?{modelId:e.prepared.modelId}:{},timeoutMs:e.timeoutMs,serverUrl:e.serverUrl});w.durationMs!==void 0&&(n[`iter-${c}`]=x(String(w.durationMs)));const S=w.metadata,M=w.errorCode==="YOLOOP_RELEASE_BLOCKED"||S?.yoloopReleaseBlocked===!0||S?.terminalClass==="release-blocked"||S?.releaseBlocked!==void 0;if(!w.success&&!M)return t.push("backoff"),O({status:"backoff",receiptStatus:"deferred",reasonCode:f.EXECUTION_FAILED,publicSummary:"Headless yoloop root metadata invocation failed with bounded public evidence.",retryable:!0,startedAt:r,counts:k(c,o.length,l,p,m,u,y),workerPoolSummary:A(i),hashes:n,redactions:d,relativePaths:[e.prepared.targetRef,...s],childStoryIds:o,stateTransitions:t});const b=Qt(S);if(!b.ok)return t.push("backoff"),O({status:"failed",receiptStatus:"failed",reasonCode:b.reasonCode,publicSummary:b.publicSummary,retryable:!1,startedAt:r,counts:k(c,o.length,l,p,m,u,y),workerPoolSummary:A(i),hashes:n,redactions:[...d,...b.redactionSummary],relativePaths:[e.prepared.targetRef,...s],childStoryIds:o,stateTransitions:t});const I=er(S);if(b.aborted&&I){for(;R.size>0;)await X();return y+=1,t.push("backoff"),O({status:"backoff",receiptStatus:"deferred",reasonCode:I.reason==="YOLOOP_SESSION_TIMEOUT"?"yoloop-session-timeout-resumable":"yoloop-per-run-cap-resumable",publicSummary:"Headless yoloop reached a finite run boundary and scheduled the same queue after cool-down.",retryable:!0,retryNotBeforeAt:I.coolDownUntil,startedAt:r,counts:k(c+1,o.length,l,p,m,u,y),workerPoolSummary:A(i),hashes:n,redactions:d,relativePaths:[e.prepared.targetRef,...s],childStoryIds:o,stateTransitions:t})}if((b.releaseBlocked||b.aborted||b.complete||b.replay||b.outcome&&b.outcome!=="selected"&&b.outcome!=="queue_exhausted")&&H&&R.size>0){await X(),c+=1,t.push("reinvoke");continue}if(b.releaseBlocked)return t.push("release_blocked"),O({status:"failed",receiptStatus:"failed",reasonCode:"yoloop-release-blocked",publicSummary:"Headless yoloop stopped at a terminal release-blocked boundary without declaring success.",retryable:!1,startedAt:r,counts:k(c+1,o.length,l,p,m,u,y),workerPoolSummary:A(i),hashes:{...n,releaseBlocked:x(b.releaseBlocked.resultId)},redactions:d,relativePaths:[e.prepared.targetRef,...s],childStoryIds:o,stateTransitions:t,terminalClass:"release-blocked",releaseBlocked:b.releaseBlocked});const Y=C(S?.epicIntegration)?S.epicIntegration:void 0,ee=Array.isArray(Y?.reasonCodes)?Y.reasonCodes.filter(g=>typeof g=="string"):[];if(b.aborted&&S?.abortReason==="epic-integration-checkpoints-incomplete"&&Y?.required===!0&&Y.ready===!1&&ee.length>0&&ee.every(g=>g==="epic-aggregate-qa-receipt-required"||g==="epic-aggregate-qa-graph-stale"||g==="epic-aggregate-qa-expired"||g==="epic-head-reconciliation-bindings-incomplete"||g==="epic-origin-binding-required"||/^missing-story-checkpoint:[A-Za-z0-9._-]+$/.test(g)||/^scheduling-checkpoint-evidence-missing:[A-Za-z0-9._-]+$/.test(g))&&e.terminalGitAdapter.prepareLifecycleEvidence){t.push("lifecycle_evidence");const g=await e.terminalGitAdapter.prepareLifecycleEvidence({epicId:e.prepared.epicId,nowIso:e.now()});if(!g.ok)return t.push("backoff"),O({status:g.retryEligible?"backoff":"failed",receiptStatus:g.retryEligible?"deferred":"failed",reasonCode:g.reasonCode,publicSummary:"Headless yoloop stopped because physical Git lifecycle evidence could not be produced safely.",retryable:g.retryEligible,startedAt:r,counts:k(c+1,o.length,l,p,m,u,y),workerPoolSummary:A(i),hashes:n,redactions:d,relativePaths:[e.prepared.targetRef,...s],childStoryIds:o,stateTransitions:t});_=g.terminalAuthority??g.p205Authority,E=!0,c+=1,t.push("reinvoke");continue}if(b.aborted)return y+=1,t.push("aborted"),O({status:"failed",receiptStatus:"failed",reasonCode:Tt,publicSummary:"Headless yoloop stopped because public metadata reported an aborted loop.",retryable:!1,startedAt:r,counts:k(c+1,o.length,l,p,m,u,y),workerPoolSummary:A(i),hashes:n,redactions:d,relativePaths:[e.prepared.targetRef,...s],childStoryIds:o,stateTransitions:t});if(b.outcome&&b.outcome!=="selected"&&b.outcome!=="queue_exhausted")return t.push("backoff"),O({status:"failed",receiptStatus:"failed",reasonCode:`yoloop-${b.outcome}`,publicSummary:"Headless yoloop stopped on a non-executable graph-first continuation outcome.",retryable:!1,startedAt:r,counts:k(c+1,o.length,l,p,m,u,y),workerPoolSummary:A(i),hashes:n,redactions:d,relativePaths:[e.prepared.targetRef,...s],childStoryIds:o,stateTransitions:t});if(b.replay)return t.push("backoff"),O({status:"backoff",receiptStatus:"deferred",reasonCode:"yoloop-replay-pending",publicSummary:"Headless yoloop observed pending replay authority and did not delegate a second child.",retryable:!0,startedAt:r,counts:k(c+1,o.length,l,p,m,u,y),workerPoolSummary:A(i),hashes:n,redactions:d,relativePaths:[e.prepared.targetRef,...s],childStoryIds:o,stateTransitions:t});if(b.complete&&H&&z.size>0&&$.size===0)return t.push("backoff"),O({status:"backoff",receiptStatus:"deferred",reasonCode:[...z.values()].sort()[0],publicSummary:"Headless yoloop rejected terminal completion while previously runnable work remained undispatched.",retryable:!0,startedAt:r,counts:k(c+1,o.length,l,p,m,u,y),workerPoolSummary:A(i),hashes:n,redactions:d,relativePaths:[e.prepared.targetRef,...s],childStoryIds:o,stateTransitions:t});if(b.complete&&H&&$.size>0)return t.push("backoff"),O({status:"failed",receiptStatus:"failed",reasonCode:[...$.values()].sort()[0],publicSummary:"Headless yoloop rejected terminal completion because runnable work failed before an accepted dispatch receipt.",retryable:!1,startedAt:r,counts:k(c+1,o.length,l,p,m,u,y),workerPoolSummary:A(i),hashes:n,redactions:d,relativePaths:[e.prepared.targetRef,...s],childStoryIds:o,stateTransitions:t});const de=Zt(S);if(de){if(!E&&e.terminalGitAdapter.prepareLifecycleEvidence){t.push("lifecycle_evidence");const v=await e.terminalGitAdapter.prepareLifecycleEvidence({epicId:e.prepared.epicId,nowIso:e.now()});if(!v.ok)return t.push("backoff"),O({status:v.retryEligible?"backoff":"failed",receiptStatus:v.retryEligible?"deferred":"failed",reasonCode:v.reasonCode,publicSummary:"Headless yoloop stopped because physical Git lifecycle evidence could not be produced safely.",retryable:v.retryEligible,startedAt:r,counts:k(c,o.length,l,p,m,u,y),workerPoolSummary:A(i),hashes:n,redactions:d,relativePaths:[e.prepared.targetRef,...s],childStoryIds:o,stateTransitions:t});_=v.terminalAuthority??v.p205Authority,E=!0}t.push("terminal_git");const g=new Date,L=await ht(e.projectRoot,{kind:"continuous",storyId:de.epicId,sessionId:`${e.runnerId}:${e.attempt.attempt_id}`,idempotencyKey:de.idempotencyKey,persistent:!1,expiresAt:new Date(g.getTime()+Math.max(e.timeoutMs,e.maxDurationMs)+6e4).toISOString()});if(!L.ok)return t.push("backoff"),O({status:"backoff",receiptStatus:"deferred",reasonCode:L.reasonCode,publicSummary:"Headless yoloop deferred terminal Git while another physical writer retained authority.",retryable:!0,startedAt:r,counts:k(c+1,o.length,l,p,m,u,y),workerPoolSummary:A(i),hashes:n,redactions:d,relativePaths:[e.prepared.targetRef,...s],childStoryIds:o,stateTransitions:t});let K,j=!1;try{K=await lt(de,e.terminalGitAdapter,e.now,_)}finally{j=await _t(L.path,L.owner).catch(()=>!1)}if(!j)return t.push("backoff"),O({status:"backoff",receiptStatus:"deferred",reasonCode:"git-lifecycle-integration-lock-release-failed",publicSummary:"Headless yoloop stopped because terminal Git writer ownership could not be released safely.",retryable:!0,startedAt:r,counts:k(c+1,o.length,l,p,m,u,y),workerPoolSummary:A(i),hashes:n,redactions:d,relativePaths:[e.prepared.targetRef,...s],childStoryIds:o,stateTransitions:t});if(n[`terminal-git-${c}`]=x(`${K.receipt.idempotencyKey}:${K.receipt.physicalStatus}`),!K.ok){const v=K.receipt.retryEligible;return t.push("backoff"),O({status:v?"backoff":"failed",receiptStatus:v?"deferred":"failed",reasonCode:K.reasonCodes[0]??"epic-terminal-git-failed",publicSummary:"Headless yoloop stopped at the epic terminal Git boundary with public-safe retry evidence.",retryable:v,startedAt:r,counts:k(c+1,o.length,l,p,m,u,y),workerPoolSummary:A(i),hashes:n,redactions:d,relativePaths:[e.prepared.targetRef,...s],childStoryIds:o,stateTransitions:t})}if(_=void 0,E=!1,b.complete)return u+=1,t.push("complete"),O({status:"completed",receiptStatus:"applied",reasonCode:f.EXECUTION_COMPLETED,publicSummary:"Headless yoloop completed only after fresh root-owned physical Git verification.",retryable:!1,startedAt:r,counts:k(c+1,o.length,l,p,m,u,y),workerPoolSummary:A(i),hashes:n,redactions:d,relativePaths:[e.prepared.targetRef,...s],childStoryIds:o,stateTransitions:t});c+=1,t.push("reinvoke");continue}if(b.complete)return u+=1,t.push("complete"),O({status:"completed",receiptStatus:"applied",reasonCode:f.EXECUTION_COMPLETED,publicSummary:"Headless yoloop completed after public metadata reported yoloopComplete.",retryable:!1,startedAt:r,counts:k(c+1,o.length,l,p,m,u,y),workerPoolSummary:A(i),hashes:n,redactions:d,relativePaths:[e.prepared.targetRef,...s],childStoryIds:o,stateTransitions:t});const pe=Jt(S);if(pe){t.push("git_reconciliation");const g=await dt(pe,e.terminalGitAdapter,e.now);if(n[`git-reconciliation-${c}`]=x(`${pe.idempotencyKey}:${g.reasonCodes.join(",")}`),!g.ok)return t.push("backoff"),O({status:"backoff",receiptStatus:"deferred",reasonCode:g.reasonCodes[0]??"git-reconciliation-failed",publicSummary:"Headless yoloop paused at a fail-closed Git reconciliation boundary.",retryable:!0,startedAt:r,counts:k(c+1,o.length,l,p,m,u,y),workerPoolSummary:A(i),hashes:n,redactions:d,relativePaths:[e.prepared.targetRef,...s],childStoryIds:o,stateTransitions:t})}const N=Ft(S,e.prepared.epicId);if(!N.ok)return t.push("backoff"),O({status:"failed",receiptStatus:"failed",reasonCode:N.reasonCode,publicSummary:N.publicSummary,retryable:!1,startedAt:r,counts:k(c+1,o.length,l,p,m,u,y),workerPoolSummary:A(i),hashes:n,redactions:[...d,...N.redactionSummary],relativePaths:[e.prepared.targetRef,...s],childStoryIds:o,stateTransitions:t});const Ae=N.continuous?void 0:N.prompts.find(g=>a.has(g.storyId));if(Ae)return t.push("backoff"),O({status:"failed",receiptStatus:"failed",reasonCode:f.YOLOOP_ISOLATION_VIOLATION,publicSummary:"Headless yoloop rejected cyclic child story delegation evidence.",retryable:!1,startedAt:r,counts:k(c+1,o.length,l,p,m,u,y),workerPoolSummary:A(i),hashes:n,redactions:[...d,h("storyId","prompt_body",x(Ae.storyId))],relativePaths:[e.prepared.targetRef,...s],childStoryIds:o,stateTransitions:t});if(i.mode=N.mode==="continuous_dag"?"continuous_dag":N.parallelAuthorized?"parallel_wave":"serial",i.serverMaxConcurrency=N.serverMaxConcurrency,N.continuous){H=!0;const g=N.prompts.filter(L=>!a.has(L.storyId)&&!R.has(L.storyId));if(i.pendingChildCount=g.length+R.size,g.length>0){const L=De({store:e.store,nowIso:e.now(),localCap:e.localConcurrencyCap,serverMaxConcurrency:N.serverMaxConcurrency,parallelAuthorized:!0,continuous:!0,eligibleCount:g.length});if(i.queueCap=L.queueCap,i.availableLeases=L.availableLeases,i.effectiveConcurrency=L.effectiveConcurrency,i.reasonCodes.push(L.reasonCode),L.effectiveConcurrency===0&&R.size===0)return i.backpressurePauseCount+=1,t.push("backoff"),O({status:"backoff",receiptStatus:"deferred",reasonCode:f.WORKER_POOL_BACKPRESSURE_PAUSED,publicSummary:"Headless yoloop retained its eligible frontier while physical worker capacity was unavailable.",retryable:!0,startedAt:r,counts:k(c+1,o.length,l,p,m,u,y),workerPoolSummary:A(i),hashes:n,redactions:d,relativePaths:[e.prepared.targetRef,...s],childStoryIds:o,stateTransitions:t});const K=g.slice(0,L.effectiveConcurrency);t.push("child_story_delegation");for(const j of K)R.set(j.storyId,{child:j,promise:Le({...e,child:j,iteration:c})});i.startedChildCount+=K.length,i.peakConcurrency=Math.max(i.peakConcurrency,R.size),i.pendingChildCount=g.length-K.length+R.size}if(R.size>0)await X();else{if(z.size>0)return t.push("backoff"),O({status:"backoff",receiptStatus:"deferred",reasonCode:[...z.values()].sort()[0],publicSummary:"Headless yoloop retained deferred continuous work for a bounded retry.",retryable:!0,startedAt:r,counts:k(c+1,o.length,l,p,m,u,y),workerPoolSummary:A(i),hashes:n,redactions:d,relativePaths:[e.prepared.targetRef,...s],childStoryIds:o,stateTransitions:t});if($.size>0)return t.push("backoff"),O({status:"failed",receiptStatus:"failed",reasonCode:[...$.values()].sort()[0],publicSummary:"Headless yoloop completed independent work and stopped on the remaining failed dependency closure.",retryable:!1,startedAt:r,counts:k(c+1,o.length,l,p,m,u,y),workerPoolSummary:A(i),hashes:n,redactions:d,relativePaths:[e.prepared.targetRef,...s],childStoryIds:o,stateTransitions:t})}c+=1,t.push("reinvoke");continue}i.pendingChildCount=N.prompts.length;const te=[...N.prompts];for(;te.length>0;){const g=De({store:e.store,nowIso:e.now(),localCap:e.localConcurrencyCap,serverMaxConcurrency:N.serverMaxConcurrency,parallelAuthorized:N.parallelAuthorized,continuous:!1,eligibleCount:te.length});if(i.queueCap=g.queueCap,i.availableLeases=g.availableLeases,i.effectiveConcurrency=g.effectiveConcurrency,i.reasonCodes.push(g.reasonCode),g.effectiveConcurrency===0)return i.backpressurePauseCount+=1,i.pendingChildCount=te.length,t.push("backoff"),O({status:"backoff",receiptStatus:"deferred",reasonCode:f.WORKER_POOL_BACKPRESSURE_PAUSED,publicSummary:"Headless yoloop paused child workers because bounded queue or lease capacity was unavailable.",retryable:!0,startedAt:r,counts:k(c+1,o.length,l,p,m,u,y),workerPoolSummary:A(i),hashes:n,redactions:d,relativePaths:[e.prepared.targetRef,...s],childStoryIds:o,stateTransitions:t});const L=te.splice(0,g.effectiveConcurrency);i.startedChildCount+=L.length,i.peakConcurrency=Math.max(i.peakConcurrency,L.length),i.pendingChildCount=te.length,t.push("child_story_delegation");const K=await Promise.all(L.map(v=>Le({...e,child:v,iteration:c})));i.completedChildCount+=K.length;let j;for(const v of K){const le=v.child;n[`child-${le.storyId.replace(/[^A-Za-z0-9_.:-]/g,"-")}`]=v.commandHash,d.push(v.promptRedaction),o.push(le.storyId),s.push(le.targetRef),a.add(le.storyId);const re=v.receipt;if(!re){v.reasonCodes.includes("queue-cap-reached")?(i.backpressurePauseCount+=1,i.pendingChildCount+=1,i.reasonCodes.push(f.WORKER_POOL_BACKPRESSURE_PAUSED),j??={kind:"deferred",reasonCode:f.WORKER_POOL_BACKPRESSURE_PAUSED}):(p+=1,j??={kind:"missing",reasonCode:f.EXECUTION_FAILED});continue}if(re.outcome==="deferred"){j??={kind:"deferred",reasonCode:f.EXECUTION_BACKOFF};continue}if(re.outcome==="failed"){p+=1,j??={kind:"failed",reasonCode:re.reasonCode||f.EXECUTION_FAILED};continue}re.outcome==="ignored"?m+=1:l+=1}if(j){const v=j.kind==="deferred";return O({status:v?"backoff":"failed",receiptStatus:v?"deferred":"failed",reasonCode:j.reasonCode,publicSummary:j.kind==="missing"?"Headless yoloop child story delegation did not produce a public receipt.":v?"Headless yoloop child story delegated bounded backoff to the root attempt.":"Headless yoloop child story execution failed with public receipt evidence.",retryable:v,startedAt:r,counts:k(c+1,o.length,l,p,m,u,y),workerPoolSummary:A(i),hashes:n,redactions:d,relativePaths:[e.prepared.targetRef,...s],childStoryIds:o,stateTransitions:t})}}c+=1,t.push("reinvoke")}}async function Le(e){const r=e.child.dispatchId?await e.continuousWorkspaceManager.prepare({projectRoot:e.projectRoot,epicId:e.prepared.epicId,storyId:e.child.storyId,targetRef:e.child.targetRef,dispatchId:e.child.dispatchId,executionBranch:e.child.executionBranch??"",graphRevision:e.child.graphRevision??"",authorizedWriteSet:e.child.writeSet??[]}):void 0;if(r&&!r.ok)return{child:e.child,reasonCodes:[r.reasonCode],commandHash:x(e.child.commandRef),promptRedaction:h(`child.${e.child.storyId}`,"prompt_body",x(e.child.commandRef)),terminalFailure:r.reasonCode,deferredFailure:/backpressure|lease-active/.test(r.reasonCode)};const t=e.projectRoot,a=await st(e.projectRoot),o=r?.ok?it(r.value):e.adapterOptions?.commandRunner,s=tr({rootAttempt:e.attempt,child:e.child,iteration:e.iteration,runtimeId:e.prepared.runtimeId,modelId:e.prepared.modelId,runtimeSource:e.prepared.runtimeSource}),n=W("attempt",s.idempotencyKey);let d=!!r;try{const c=await ot({store:e.store,projectRoot:t,runnerId:e.runnerId,now:e.now,metadata:{continuityExecutionDirectives:[s]},adapterRegistry:e.registry,adapterOptions:{...e.adapterOptions,cwd:t,env:nt({processEnv:process.env,platform:e.adapterOptions?.platform??process.platform,contract:a.status==="declared"?a.contract:null,explicitEnv:e.adapterOptions?.env,branchless:r?.ok?{NEOCORTEX_BRANCHLESS_PROJECT_ROOT:r.value.workspacePath,NEOCORTEX_BRANCHLESS_ROOT_AUTHORITY:JSON.stringify(e.child.rootAuthority)}:void 0}),...o?{commandRunner:o,versionRunner:o}:{}},runtimeDefaults:e.runtimeDefaults,runtimeFallback:e.runtimeFallback,timeoutMs:e.timeoutMs,maxAttempts:1,limit:1,queueCap:e.queueCap,attemptIds:[n],idFactory:e.idFactory}),l=c.receipts.find(p=>p.attemptId===n)??c.receipts[0];if(r?.ok&&l&&l.outcome!=="failed"&&l.outcome!=="deferred"){const p=await e.continuousWorkspaceManager.integrate(r.value,{receiptRefs:[`continuity:${l.attemptId}`],nowIso:l.timestamp});if(!p.ok)return{child:e.child,receipt:l,reasonCodes:[...c.reasonCodes,p.reasonCode],commandHash:x(e.child.commandRef),promptRedaction:h(`child.${e.child.storyId}`,"prompt_body",x(e.child.commandRef)),terminalFailure:p.reasonCode,deferredFailure:/backpressure|graph-revision-stale/.test(p.reasonCode)};d=!1}return{child:e.child,receipt:l,reasonCodes:c.reasonCodes,commandHash:x(e.child.commandRef),promptRedaction:h(`child.${e.child.storyId}`,"prompt_body",x(e.child.commandRef))}}finally{r?.ok&&await e.continuousWorkspaceManager.release(r.value,d)}}function De(e){const r=e.store.collectSnapshotRows({nowIso:e.nowIso,jobLimit:1,staleLeaseLimit:1,receiptLimit:1,eventLimit:1,snapshotLimit:1}),t=Math.max(1,Math.floor(r.queue.capacity)),a=Math.max(0,Math.floor(r.queue.running)-1),o=e.continuous?Math.max(0,Math.floor(r.queue.available)):Math.max(0,Math.min(Math.max(0,e.localCap-a),Math.floor(r.queue.available))),s=e.parallelAuthorized?Math.max(1,Math.floor(e.serverMaxConcurrency)):1,n=Math.max(0,Math.min(e.eligibleCount,s,e.localCap,t,o));return{queueCap:t,availableLeases:o,effectiveConcurrency:n,reasonCode:n===0?f.WORKER_POOL_BACKPRESSURE_PAUSED:(e.parallelAuthorized||e.continuous)&&n>1?f.WORKER_POOL_PARALLEL_ACTIVE:f.WORKER_POOL_SERIAL_FALLBACK}}function Me(e){return{mode:"serial",serverMaxConcurrency:1,localCap:e,queueCap:1,availableLeases:1,effectiveConcurrency:1,peakConcurrency:0,pendingChildCount:0,startedChildCount:0,completedChildCount:0,backpressurePauseCount:0,reasonCodes:[]}}function A(e){return{mode:e.mode,serverMaxConcurrency:F(e.serverMaxConcurrency),localCap:F(e.localCap),queueCap:F(e.queueCap),availableLeases:F(e.availableLeases),effectiveConcurrency:F(e.effectiveConcurrency),peakConcurrency:F(e.peakConcurrency),pendingChildCount:F(e.pendingChildCount),startedChildCount:F(e.startedChildCount),completedChildCount:F(e.completedChildCount),backpressurePauseCount:F(e.backpressurePauseCount),reasonCodes:U(e.reasonCodes.length>0?e.reasonCodes:[f.WORKER_POOL_SERIAL_FALLBACK]).slice(0,10),publicSafe:!0}}function _e(e=we()){return A(Me(e))}function F(e){return Number.isFinite(e)?Math.max(0,Math.min(1e4,Math.floor(e))):0}function Kt(e){const r=ve(e.attempt.metadata_json,{autonomousKind:"run_yoloop",jobId:e.attempt.job_id,targetKind:"epic",targetRef:e.attempt.target_ref});if(!r.ok)return{ok:!1,status:"failed",receiptStatus:"failed",reasonCode:r.reasonCode,publicSummary:r.publicSummary,redactionSummary:r.redactionSummary};const t=Ut(e.attempt);if(!t.ok)return t;const a=$t(e);if(!a.ok)return{ok:!1,status:"failed",receiptStatus:"failed",reasonCode:a.reasonCode,publicSummary:a.publicSummary,redactionSummary:a.redactionSummary};const o=e.attempt.epic_id??se(e.attempt.target_ref);return{ok:!0,input:{rootPrompt:`*yoloop @${e.attempt.target_ref}`,targetRef:e.attempt.target_ref,epicId:o,runtimeId:a.runtimeId,...a.modelId?{modelId:a.modelId}:{},runtimeSource:a.runtimeSource,publicSafe:!0}}}function Ut(e){const r=[];e.directive_kind!=="run_yoloop"&&r.push(h("directiveKind","unsafe_key","value-denied")),e.target_kind!=="epic"&&r.push(h("targetKind","prompt_body","value-denied")),(!ye.test(e.target_ref)||q.test(e.target_ref)||D.test(e.target_ref))&&r.push(h("targetRef","prompt_body","value-denied"));const t=se(e.target_ref);return e.epic_id&&e.epic_id!==t&&r.push(h("epicId","prompt_body","value-denied")),r.length>0?{ok:!1,status:"failed",receiptStatus:"failed",reasonCode:f.PROMPT_REJECTED,publicSummary:"Headless run_yoloop attempt did not match the canonical public epic prompt shape.",redactionSummary:r}:{ok:!0,input:{rootPrompt:`*yoloop @${e.target_ref}`,targetRef:e.target_ref,epicId:t,runtimeId:"fake",publicSafe:!0}}}function $t(e){const r=e.runtimeDefaults!==void 0?e.runtimeDefaults:Xe({projectRoot:e.projectRoot});if(C(r)&&r.ok===!1)return{ok:!1,reasonCode:f.RUNTIME_UNTRUSTED,publicSummary:typeof r.publicSummary=="string"?r.publicSummary:"Headless runtime defaults failed public-safety validation.",redactionSummary:Array.isArray(r.redactionSummary)?r.redactionSummary:[]};const t=ur(e.attempt.runtime_source)??"explicit",a=e.attempt.runtime_id||e.attempt.model_id?{...e.attempt.runtime_id?{runtimeId:e.attempt.runtime_id}:{},...e.attempt.model_id?{modelId:e.attempt.model_id}:{},source:t,publicSafe:!0}:void 0,o={registry:e.registry,defaults:r,fallback:e.runtimeFallback};a&&(t==="origin"?o.origin=a:t==="default"?o.projectDefault=a:t==="fallback"?o.fallback=a:o.explicit=a);const s=Ze(o);return s.ok?{ok:!0,runtimeId:s.runtimeId,...s.modelId?{modelId:s.modelId}:{},runtimeSource:s.runtimeSource}:{ok:!1,reasonCode:s.reasonCode,publicSummary:s.publicSummary,redactionSummary:s.redactionSummary}}function Yt(e){const r=[];for(const i of Object.keys(e))(!Pt.has(i)||ae.test(i))&&r.push(h(i,Q(i),"key-denied"));e.publicSafe!==!0&&r.push(h("publicSafe","unsafe_key","value-denied"));const t=B(e,"kind"),a=B(e,"commandClass"),o=B(e,"jobId"),s=B(e,"operationId"),n=B(e,"idempotencyKey"),d=B(e,"targetKind"),c=B(e,"targetRef"),l=B(e,"commandRef"),p=B(e,"publicSummary"),m=B(e,"epicId");t!=="run_yoloop"&&r.push(h("kind","unsafe_key","value-denied")),a!=="goal-tick"&&a!=="loop-tick"&&r.push(h("commandClass","unsafe_key","value-denied")),Se(o)||r.push(h("jobId","unsafe_key","value-denied")),Se(s)||r.push(h("operationId","unsafe_key","value-denied")),Se(n)||r.push(h("idempotencyKey","unsafe_key","value-denied")),(d!=="epic"||!c||!ye.test(c)||D.test(c))&&r.push(h("targetRef","prompt_body","value-denied"));const u=c?`*yoloop @${c}`:void 0;(!l||l!==u||l.includes("@neocortex")||q.test(l)||D.test(l))&&r.push(h("commandRef","prompt_body","value-denied")),m&&c&&m!==se(c)&&r.push(h("epicId","prompt_body","value-denied")),(!p||p.length>240||D.test(p))&&r.push(h("publicSummary","unbounded_text","value-denied")),e.reasonCode!==void 0&&(typeof e.reasonCode!="string"||D.test(e.reasonCode))&&r.push(h("reasonCode","unsafe_key","value-denied"));const y=ar(e.runtime,r);e.attempts!==void 0&&ue(e.attempts,"attempts",r),e.metadata!==void 0&&ue(e.metadata,"metadata",r);const _=C(e.metadata)?e.metadata:void 0,E=ir(e.redactionSummary,r);return r.length>0||t!=="run_yoloop"||!a||!o||!s||!n||!c||!l||!p?{ok:!1,reasonCode:r.some(R=>R.reason==="prompt_body")?f.PROMPT_REJECTED:f.DIRECTIVE_REJECTED,redactionSummary:r}:{ok:!0,directive:{kind:"run_yoloop",commandClass:a,jobId:o,operationId:s,idempotencyKey:n,targetKind:"epic",targetRef:c,commandRef:l,...m?{epicId:m}:{},...y?{runtime:y}:{},publicSummary:p,...typeof e.reasonCode=="string"?{reasonCode:e.reasonCode}:{},..._?{metadata:_}:{},...E.length>0?{redactionSummary:E}:{},publicSafe:!0}}}function Ft(e,r){if(!e)return P(f.YOLOOP_METADATA_INVALID,"Headless yoloop metadata was missing.",[]);const t=Vt(e);if(!t.ok)return t;const a=[],o=C(e.yoloopExecutionPlan)?e.yoloopExecutionPlan:void 0,s=o?T(o.storyIds).filter(G):[],n=o?.version===3&&C(o.scheduler)&&Array.isArray(o.scheduler.nodes)?new Map(o.scheduler.nodes.filter(C).map(u=>[String(u.storyId??""),u])):new Map,d=o?.version===3&&C(o.scheduler)&&typeof o.scheduler.graphRevision=="string"?o.scheduler.graphRevision:void 0,c=o?.version===3&&typeof o.executionBranch=="string"?o.executionBranch:void 0;let l;if(o){const u=qt(o);if(!u.ok)return u;l=u;for(const _ of Xt(o)){const E=J(_,r,"execution-plan");if(!E.ok)return E;a.push(Ne(E.prompt,n.get(E.prompt.storyId),d,c))}if(a.length===0)for(const _ of s){const E=J(`*yolo @docs/stories/${_}.story.md`,r,"execution-plan");if(!E.ok)return E;a.push(Ne(E.prompt,n.get(E.prompt.storyId),d,c))}const y=Wt(e.skillDirectives,a);if(!y.ok)return y}const p=typeof e.nextStoryId=="string"&&G(e.nextStoryId)?e.nextStoryId:void 0;for(const u of o?[]:Array.isArray(e.skillDirectives)?e.skillDirectives:[]){if(!C(u)||u.kind!=="task")continue;const y=T(u.promptTemplates);if(y.length>0){for(const R of y){const H=J(R,r,"task-directive");if(!H.ok)return H;a.push(H.prompt)}continue}const _=typeof u.promptTemplate=="string"?u.promptTemplate:void 0;if(!_)continue;const E=T(u.storyIds).filter(G),i=E.length>0?E:p?[p]:[];if(i.length===0&&he.test(_)){const R=J(_,r,"task-directive");if(!R.ok)return R;a.push(R.prompt);continue}for(const R of i){const H=_.includes("{storyId}")?_.replaceAll("{storyId}",R):_,z=J(H,r,"task-directive");if(!z.ok)return z;a.push(z.prompt)}}if(a.length===0&&p){const u=J(`*yolo @docs/stories/${p}.story.md`,r,"next-story");if(!u.ok)return u;a.push(u.prompt)}const m=fr(a,u=>u.commandRef);if(l?.continuous){if(m.length!==s.length||m.some(u=>u.preparationOnly!==!0||u.source!=="execution-plan"))return P(f.YOLOOP_ISOLATION_VIOLATION,"Headless continuous yoloop rejected an ambiguous or non-preparation child prompt.",[h("promptTemplates","prompt_body","operation-denied")])}else if(m.some(u=>u.preparationOnly===!0))return P(f.YOLOOP_ISOLATION_VIOLATION,"Headless yoloop rejected branchless preparation outside a validated continuous plan.",[h("promptTemplates","prompt_body","operation-denied")]);if(s.length>0){const u=new Set(s);for(const y of m)if(!u.has(y.storyId))return P(f.YOLOOP_ISOLATION_VIOLATION,"Headless yoloop rejected a child prompt outside the server-authorized execution plan.",[h("storyId","prompt_body",x(y.storyId))])}return l?.parallelAuthorized&&!Z(m.map(u=>u.storyId),s)?P(f.YOLOOP_METADATA_INVALID,"Headless yoloop rejected a parallel plan whose executable prompts did not match the selected wave.",[]):m.length===0&&!l?.continuous?P(f.YOLOOP_METADATA_INVALID,"Headless yoloop metadata did not include an authorized per-story child prompt.",[]):{ok:!0,prompts:m,mode:l?.mode??"legacy",serverMaxConcurrency:l?.serverMaxConcurrency??1,parallelAuthorized:l?.parallelAuthorized??!1,continuous:l?.continuous??!1,reasonCodes:[f.OK,l?.parallelAuthorized?f.WORKER_POOL_PARALLEL_ACTIVE:f.WORKER_POOL_SERIAL_FALLBACK]}}function Ne(e,r,t,a){if(!r||!t||!a)return e;const o=Array.isArray(r.writeSet)?T(r.writeSet):[],s=Be(r.childExecutionAuthority,{storyId:e.storyId,invocationPrompt:e.commandRef,authorizedWriteSet:o});return{...e,...typeof r.dispatchId=="string"?{dispatchId:r.dispatchId}:{},...typeof r.idempotencyKey=="string"?{idempotencyKey:r.idempotencyKey}:{},graphRevision:t,executionBranch:a,...o.length>0?{writeSet:o}:{},...s?{rootAuthority:s}:{}}}function Vt(e){const r=[];return e.nextStoryId!==void 0&&ne(e.nextStoryId,"nextStoryId",r),e.yoloopExecutionPlan!==void 0&&ne(e.yoloopExecutionPlan,"yoloopExecutionPlan",r),Array.isArray(e.skillDirectives)&&e.skillDirectives.forEach((t,a)=>{C(t)&&t.kind==="task"&&ne(t,`skillDirectives.${a}`,r)}),r.length>0?P(f.YOLOOP_METADATA_INVALID,"Headless yoloop rejected unsafe public metadata before child delegation.",r):{ok:!0}}function Wt(e,r){if(!Array.isArray(e))return{ok:!0};const t=new Set(r.map(a=>a.commandRef));for(const[a,o]of e.entries()){if(!C(o)||o.kind!=="task")continue;const s=typeof o.promptTemplate=="string"?o.promptTemplate:void 0,n=T(o.promptTemplates);if(s==="[REDACTED]"&&o.subagentType==="neocortex"&&typeof o.reasonCode=="string"&&o.reasonCode.startsWith("directive-prompt-")&&n.length===0)continue;const c=[...s?[s]:[],...n];if(o.subagentType!=="neocortex"||c.length===0||c.some(l=>!t.has(l)))return P(f.YOLOOP_ISOLATION_VIOLATION,"Headless yoloop rejected a task directive that conflicted with the server-authorized execution plan.",[h(`skillDirectives.${a}`,"prompt_body","operation-denied")])}return{ok:!0}}function ne(e,r,t){if(typeof e=="string"){if(/\.allowedDebt\.constraints\.\d+$/.test(r)&&Rt.has(e))return;(D.test(e)||/\0/.test(e))&&t.push(h(r,Q(r),"value-denied"));return}if(!(e==null||typeof e=="number"||typeof e=="boolean")){if(Array.isArray(e)){e.forEach((a,o)=>ne(a,`${r}.${o}`,t));return}if(C(e)){for(const[a,o]of Object.entries(e)){const s=`${r}.${a}`;!(a==="promptTemplate"||a==="promptTemplates"||a==="invocationPrompt"||a==="childPromptKind"||a==="allowMetaTaskPromptInChild"||a==="authorization")&&ae.test(a)&&t.push(h(s,Q(a),"key-denied")),ne(o,s,t)}return}t.push(h(r,"unsafe_key","value-denied"))}}function qt(e){const r=typeof e.mode=="string"?e.mode:"",t=C(e.isolationPolicy)?e.isolationPolicy:void 0,a=T(e.storyIds);if(e.authorization!=="server_authorized")return P(f.YOLOOP_METADATA_INVALID,"Headless yoloop execution plan was not server-authorized.",[]);if(e.executor!=="root_agent"&&e.executor!=="root_agent_with_child_tasks")return P(f.YOLOOP_METADATA_INVALID,"Headless yoloop execution plan executor was not root-owned.",[]);if(r!=="serial"&&r!=="parallel_wave"&&r!=="continuous_dag"&&r!=="manual")return P(f.YOLOOP_METADATA_INVALID,"Headless yoloop execution plan mode was invalid.",[]);const o=e.version===3&&r==="continuous_dag";if(!Array.isArray(e.storyIds)||!o&&a.length===0||a.length!==e.storyIds.length||a.some(i=>!G(i))||new Set(a).size!==a.length)return P(f.YOLOOP_METADATA_INVALID,"Headless yoloop execution plan story selection was invalid or ambiguous.",[]);if(!t||t.rootOwnsLoop!==!0||t.childPromptKind==="per_story_branchless_preparation_only"&&!o||Object.prototype.hasOwnProperty.call(t,"childExecutionBoundary")&&!o||t.childPromptKind!=="per_story_yolo_only"&&t.childPromptKind!=="per_story_branchless_preparation_only"&&!(t.childPromptKind==="none"&&(r==="serial"&&t.childTaskDelegation==="not_required"||r==="parallel_wave"&&e.executor==="root_agent"&&t.childTaskDelegation==="forbidden"))||t.allowOuterYoloopInChild!==!1||t.allowMetaTaskPromptInChild!==!1)return P(f.YOLOOP_ISOLATION_VIOLATION,"Headless yoloop rejected an execution plan that did not preserve root-owned child isolation.",[h("isolationPolicy","prompt_body","value-denied")]);const s=Array.isArray(e.skippedStories)?e.skippedStories:[];for(const i of s){if(!C(i)||typeof i.storyId!="string"||!G(i.storyId)||typeof i.reason!="string")return P(f.YOLOOP_METADATA_INVALID,"Headless yoloop skipped-story evidence was malformed.",[]);if(a.includes(i.storyId))return P(f.YOLOOP_METADATA_INVALID,"Headless yoloop selected a story that server evidence marked skipped.",[])}if(o){const i=C(e.scheduler)?e.scheduler:void 0,R=Array.isArray(i?.nodes)?i.nodes.filter(C):[],H=T(i?.readyStoryIds),z=T(i?.runningStoryIds),$=T(e.promptTemplates),ie=C(e.dependencyBasis)?e.dependencyBasis:void 0,X=C(e.readinessBasis)?e.readinessBasis:void 0,w=typeof i?.graphRevision=="string"?i.graphRevision:"",S=typeof e.executionBranch=="string"?e.executionBranch:"",M=R.map(I=>typeof I.storyId=="string"?I.storyId:""),b=R.find(I=>{const Y=typeof I.storyId=="string"?I.storyId:"",ee=typeof I.promptTemplate=="string"?I.promptTemplate:"",ce=Array.isArray(I.writeSet)?T(I.writeSet):[];return!G(Y)||ee!==`*yolo @docs/stories/${Y}.story.md branchless-preparation`||typeof I.dispatchId!="string"||!/^[a-f0-9]{64}$/.test(I.dispatchId)||typeof I.idempotencyKey!="string"||!/^[a-f0-9]{64}$/.test(I.idempotencyKey)||I.dependencyBasis!=="verified"||!Array.isArray(I.dependencies)||T(I.dependencies).length!==I.dependencies.length||!Array.isArray(I.writeSet)||ce.length===0||ce.length!==I.writeSet.length||!Be(I.childExecutionAuthority,{storyId:Y,invocationPrompt:ee,authorizedWriteSet:ce})});return e.executor!=="root_agent_with_child_tasks"||e.legacyConcurrencyIgnored!==!0||Object.prototype.hasOwnProperty.call(e,"maxConcurrency")||Object.prototype.hasOwnProperty.call(e,"maxParallel")||t?.rootOwnedScheduling!=="continuous_dag_allowed"||t?.childPromptKind!=="per_story_branchless_preparation_only"||t?.childExecutionBoundary!=="filesystem_only"||t?.childTaskDelegation!=="allowed"||t?.maxDepth!==1||t?.childWorkspace!=="branchless_sandbox"||t?.epicCheckout!=="current_checkout"||t?.workspaceLifecycle!=="user_managed"||t?.integrationOwner!=="root_agent"||!i||i.schemaVersion!==1||i.strategy!=="continuous-event-driven-dag"||i.logicalConcurrency!=="ready-set"||i.capacityPolicy!=="backpressure-only"||i.rootOwnsLoop!==!0||i.maxDepth!==1||!/^[a-f0-9]{64}$/.test(w)||!cr(S)||new Set(M).size!==M.length||M.some(I=>!G(I))||H.some(I=>!M.includes(I))||z.some(I=>!M.includes(I)||H.includes(I))||!Z(a,H)||$.length!==a.length||$.some((I,Y)=>I!==`*yolo @docs/stories/${a[Y]}.story.md branchless-preparation`)||!ie||ie.source!=="state_snapshot"||!X||X.source!=="ready_wave"||!Z(T(X.selectedStoryIds),a)||b?P(f.YOLOOP_METADATA_INVALID,"Headless yoloop rejected an invalid continuous DAG execution plan.",[]):{ok:!0,mode:"continuous_dag",serverMaxConcurrency:a.length,parallelAuthorized:!0,continuous:!0}}if(e.version===2){const i=at(e);return i.ok?{ok:!0,mode:"parallel_wave",serverMaxConcurrency:i.childExecutionConcurrency,parallelAuthorized:!1,continuous:!1}:P(f.YOLOOP_METADATA_INVALID,"Headless yoloop rejected an unsafe phased execution plan.",[])}if(r!=="parallel_wave")return{ok:!0,mode:r,serverMaxConcurrency:1,parallelAuthorized:!1,continuous:!1};const n=e.maxConcurrency,d=e.maxParallel,c=C(e.dependencyBasis)?e.dependencyBasis:void 0,l=C(e.readinessBasis)?e.readinessBasis:void 0,p=Array.isArray(e.parallelWaves)?e.parallelWaves:[],m=p.length===1&&C(p[0])?p[0]:void 0;if(t.rootOwnedScheduling!=="parallel_wave_allowed"||!Number.isInteger(n)||typeof n!="number"||n<2||n>a.length||!Number.isInteger(d)||d!==n||!c||c.source!=="state_snapshot"||!Z(T(c.storyIds),a)||!l||l.source!=="ready_wave"||!Z(T(l.selectedStoryIds),a)||!m||!Z(T(m.storyIds),a)||m.maxConcurrency!==n)return P(f.YOLOOP_METADATA_INVALID,"Headless yoloop parallel plan lacked consistent bounded authorization and readiness evidence.",[]);const u=T(m.promptTemplates);if(u.length!==a.length||new Set(u).size!==u.length)return P(f.YOLOOP_METADATA_INVALID,"Headless yoloop parallel wave prompts were incomplete or ambiguous.",[]);const _=(Array.isArray(m.proofSummaries)?m.proofSummaries:Array.isArray(e.proofSummaries)?e.proofSummaries:[]).find(i=>C(i)&&Z(T(i.storyIds),a));return!C(_)||_.dependencyClosure!=="resolved"||_.contractOwnership!=="non_overlapping"||_.validationSurfaces!=="compatible"?P(f.YOLOOP_METADATA_INVALID,"Headless yoloop parallel plan lacked resolved independence proof.",[]):s.find(i=>C(i)&&typeof i.reason=="string"&&/(cycle|unresolved|ambiguous)/i.test(i.reason))?P(f.YOLOOP_METADATA_INVALID,"Headless yoloop parallel plan contained unresolved dependency evidence.",[]):{ok:!0,mode:"parallel_wave",serverMaxConcurrency:n,parallelAuthorized:!0,continuous:!1}}function Be(e,r){if(!C(e)||!C(e.artifact))return;const t=e.artifact,a=Array.isArray(e.authorizedWriteSet)?T(e.authorizedWriteSet):[];if(Object.keys(e).sort().join("\0")!==["artifact","authorizedWriteSet","effectScope","invocationPrompt","kind","lifecycleAuthority","publicSafe","schemaVersion","storyId"].sort().join("\0")||Object.keys(t).sort().join("\0")!==["content","contentBinding","kind","path","schemaVersion"].sort().join("\0")||e.schemaVersion!==1||e.kind!=="branchless_story_preparation"||e.storyId!==r.storyId||e.invocationPrompt!==r.invocationPrompt||!Array.isArray(e.authorizedWriteSet)||a.length!==e.authorizedWriteSet.length||a.some(s=>Ct(s)!==s)||!Gt(a,r.authorizedWriteSet)||e.effectScope!=="filesystem_only"||e.lifecycleAuthority!=="root_only"||e.publicSafe!==!0||t.schemaVersion!==1||t.kind!=="branchless_root_bound_artifact"||typeof t.path!="string"||!a.includes(t.path)||typeof t.content!="string"||t.content.length===0||t.content.length>4096||typeof t.contentBinding!="string"||!/^[a-f0-9]{64}$/.test(t.contentBinding))return;const o=ze("sha256").update(["branchless-root-bound-artifact-v1",r.storyId,r.invocationPrompt,...a,"filesystem_only","root_only",t.path,t.content].join("\0")).digest("hex");if(t.contentBinding===o)return e}function Gt(e,r){return e.length===r.length&&e.every((t,a)=>t===r[a])}function Xt(e){const r=[];r.push(...T(e.promptTemplates));for(const t of Array.isArray(e.serialSteps)?e.serialSteps:[])C(t)&&typeof t.promptTemplate=="string"&&r.push(t.promptTemplate);for(const t of Array.isArray(e.parallelWaves)?e.parallelWaves:[])C(t)&&r.push(...T(t.promptTemplates));return r}function J(e,r,t){if(Te(e))return P(f.YOLOOP_ISOLATION_VIOLATION,"Headless yoloop rejected an unsafe child prompt shape.",[h("promptTemplate","prompt_body",x(e))]);if(!he.test(e))return P(f.YOLOOP_METADATA_INVALID,"Headless yoloop child prompt did not match the canonical per-story yolo shape.",[h("promptTemplate","prompt_body",x(e))]);const a=kt.test(e),o=e.replace(/^\*yolo @/,"").replace(/ branchless-preparation$/,""),s=lr(o);return!At.test(o)||!G(s)||!s.startsWith(`${r}.`)?P(f.YOLOOP_ISOLATION_VIOLATION,"Headless yoloop rejected a child prompt outside the targeted public epic.",[h("storyId","prompt_body",x(s))]):{ok:!0,prompt:{storyId:s,targetRef:o,commandRef:e,source:t,...a?{preparationOnly:!0}:{}}}}function Zt(e){const r=e?.epicTerminalGitDirective;if(!(!C(r)||r.schemaVersion!==1||r.kind!=="epic_terminal_git"||typeof r.epicId!="string"||typeof r.executionBranch!="string"||typeof r.originBranch!="string"||typeof r.expectedExecutionHeadSha!="string"||!Array.isArray(r.storyCheckpointIds)||!C(r.localGates)||r.localGates.passed!==!0||!Array.isArray(r.localGates.receiptRefs)||!C(r.reconcile)||typeof r.idempotencyKey!="string"||r.publicSafe!==!0))return r}function Jt(e){const r=e?.epicGitReconciliationDirective;if(!(!C(r)||r.schemaVersion!==1||r.kind!=="epic_git_reconciliation"||typeof r.epicId!="string"||typeof r.executionBranch!="string"||typeof r.originBranch!="string"||!["start","resume","audit"].includes(String(r.lifecycleBoundary))||typeof r.dryRun!="boolean"||typeof r.idempotencyKey!="string"||r.publicSafe!==!0))return r}function Qt(e){if(!e||!C(e))return{ok:!1,reasonCode:f.YOLOOP_METADATA_INVALID,publicSummary:"Headless yoloop root invocation did not return public metadata.",redactionSummary:[]};const r=C(e.yoloopContinuationDecision)?e.yoloopContinuationDecision:void 0,t=typeof r?.outcome=="string"?r.outcome:void 0,a=t==="queue_exhausted"||e.yoloopComplete===!0,o=e.yoloopAborted===!0,s=gt(e.releaseBlocked),n=t==="selected"&&r?.replay===!0;return t&&!["selected","queue_exhausted","blocked","cycle","invalid","no_progress"].includes(t)?{ok:!1,reasonCode:f.YOLOOP_METADATA_INVALID,publicSummary:"Headless yoloop rejected an unknown continuation outcome.",redactionSummary:[]}:t==="queue_exhausted"&&r?.terminalSuccess!==!0?{ok:!1,reasonCode:f.YOLOOP_METADATA_INVALID,publicSummary:"Headless yoloop rejected inconsistent queue exhaustion metadata.",redactionSummary:[]}:a&&o?{ok:!1,reasonCode:f.YOLOOP_METADATA_INVALID,publicSummary:"Headless yoloop metadata reported mutually exclusive terminal states.",redactionSummary:[h("yoloopTerminal","unsafe_key","value-denied")]}:(e.yoloopReleaseBlocked===!0||e.terminalClass==="release-blocked"||e.releaseBlocked!==void 0)&&(!s||e.yoloopReleaseBlocked!==!0||e.terminalClass!=="release-blocked"||a||o||t!==void 0)?{ok:!1,reasonCode:f.YOLOOP_METADATA_INVALID,publicSummary:"Headless yoloop rejected inconsistent release-blocked terminal metadata.",redactionSummary:[]}:{ok:!0,complete:a,aborted:o,...s?{releaseBlocked:s}:{},outcome:t,replay:n}}function er(e){if(!e)return;const r=e.abortReason;if(r!=="YOLOOP_PER_RUN_CAP_REACHED"&&r!=="YOLOOP_SESSION_TIMEOUT")return;const t=e.yoloopResumableBoundary,a=/^[A-Za-z0-9._:-]{1,128}$/;if(!(!C(t)||t.schemaVersion!=="YoloopResumableBoundary/1.0"||t.resumable!==!0||t.reason!==r||t.publicSafe!==!0||typeof t.coolDownUntil!="string"||!Number.isFinite(Date.parse(t.coolDownUntil))||!Number.isSafeInteger(t.retryAfterMs)||t.retryAfterMs<0||typeof t.operationId!="string"||!a.test(t.operationId)||!C(t.receipt)||t.receipt.schemaVersion!=="YoloopSessionRolloverReceipt/1.0"||typeof t.receipt.runId!="string"||!a.test(t.receipt.runId)||t.receipt.operationId!==t.operationId||typeof t.receipt.idempotencyKey!="string"||!a.test(t.receipt.idempotencyKey)||typeof t.receipt.payloadHash!="string"||!/^[a-f0-9]{64}$/.test(t.receipt.payloadHash)||t.receipt.coolDownUntil!==t.coolDownUntil||!Number.isSafeInteger(t.receipt.revision)||t.receipt.revision<0||t.receipt.snapshotHash!==null&&(typeof t.receipt.snapshotHash!="string"||!/^[a-f0-9]{64}$/.test(t.receipt.snapshotHash))||t.receipt.status!=="exhausted"||t.receipt.publicSafe!==!0))return{coolDownUntil:t.coolDownUntil,reason:r}}function tr(e){const r=`${e.rootAttempt.execution_id}:${e.child.graphRevision??"legacy"}:${e.child.storyId}`,t=e.child.dispatchId??W("child-op",`${r}:${e.iteration}`),a=e.child.idempotencyKey??W("child-idem",`${r}:${e.iteration}`);return{schemaVersion:1,contractVersion:"continuity-v1",kind:"run_yolo",commandClass:e.rootAttempt.command_class==="goal-tick"?"goal-tick":"loop-tick",jobId:e.rootAttempt.job_id,operationId:t,idempotencyKey:a,targetKind:"story",targetRef:e.child.targetRef,commandRef:e.child.commandRef,...e.child.preparationOnly?{executionMode:"branchless_child_preparation"}:{},storyId:e.child.storyId,runtime:{runtimeId:e.runtimeId,...e.modelId?{modelId:e.modelId}:{},source:e.runtimeSource??"explicit",reasonCode:e.runtimeSource==="fallback"?f.RUNTIME_FALLBACK:f.RUNTIME_EXPLICIT,publicSafe:!0},publicSummary:`Root-owned yoloop delegated public story ${e.child.storyId}.`,reasonCode:f.OK,metadata:{governanceSource:"delegated-subagent",parentAttemptId:e.rootAttempt.attempt_id,parentExecutionId:e.rootAttempt.execution_id,iteration:e.iteration,...e.child.dispatchId?{dispatchId:e.child.dispatchId}:{},...e.child.graphRevision?{graphRevision:e.child.graphRevision}:{},...e.child.writeSet?{writeSet:e.child.writeSet}:{},...e.child.executionBranch?{executionBranch:e.child.executionBranch}:{},...e.child.graphRevision?{childWorkspace:"branchless_sandbox",epicCheckout:"current_checkout",workspaceLifecycle:"user_managed",integrationOwner:"root_agent",maxDepth:1}:{},publicSafe:!0},attempts:[],redactionSummary:[h("prompt","prompt_body",x(e.child.commandRef))],publicSafe:!0}}function Ce(e,r,t){const a=je(t.hashes),o=t.workerPoolSummary??_e(),s=je({iterations:t.counts.iterations,childCount:t.counts.childCount,succeededChildCount:t.counts.succeededChildCount,failedChildCount:t.counts.failedChildCount,skippedChildCount:t.counts.skippedChildCount,metadataCompleteCount:t.counts.metadataCompleteCount,metadataAbortedCount:t.counts.metadataAbortedCount,serverMaxConcurrency:o.serverMaxConcurrency,localCap:o.localCap,queueCap:o.queueCap,availableLeases:o.availableLeases,effectiveConcurrency:o.effectiveConcurrency,peakConcurrency:o.peakConcurrency,pendingChildCount:o.pendingChildCount,startedChildCount:o.startedChildCount,completedChildCount:o.completedChildCount,backpressurePauseCount:o.backpressurePauseCount}),n={schemaVersion:1,contractVersion:"continuity-v1",attemptId:r.attempt_id,executionId:r.execution_id,jobId:r.job_id,directiveHash:r.directive_hash,status:t.status,reasonCode:t.reasonCode,storyIds:t.childStoryIds.slice(0,50),counts:s,hashes:a,...t.reasonCode===Ee.BYPASS_BLOCKED?{governanceEvidence:Ve}:{},reasonCodes:U([t.reasonCode,...o.reasonCodes,...t.stateTransitions]),publicSummary:me(t.publicSummary),...t.terminalClass?{terminalClass:t.terminalClass}:{},...t.releaseBlocked?{releaseBlocked:t.releaseBlocked}:{}},d=ve(r.metadata_json,{autonomousKind:"run_yoloop",jobId:r.job_id,targetKind:"epic",targetRef:r.target_ref}),c=d.ok?Re(d.envelope,n):n;return e.completeHeadlessExecutionAttempt({attemptId:r.attempt_id,executionId:r.execution_id,jobId:r.job_id,leaseId:t.leaseId,runnerId:t.runnerId,status:t.status,completedAt:t.completedAt,durationMs:t.durationMs,reasonCode:t.reasonCode,publicSummary:me(t.publicSummary),notBeforeAt:t.notBeforeAt,retryCount:t.retryCount,counts:s,hashes:a,redactionSummary:t.redactionSummary,relativePaths:U([r.target_ref,...t.relativePaths]),metadata:c}),e.recordHeadlessExecutionReceipt({receiptId:`receipt-${W("headless-yoloop",`${r.attempt_id}-${t.status}`)}`,attemptId:r.attempt_id,executionId:r.execution_id,jobId:r.job_id,status:t.receiptStatus,reasonCode:t.reasonCode,createdAt:t.completedAt,operationId:`${r.execution_id}:${t.status}:receipt`,idempotencyKey:`${r.directive_hash}:${t.status}:receipt`,counts:s,hashes:a,redactionSummary:t.redactionSummary,relativePaths:U([r.target_ref,...t.relativePaths]),metadata:c}),e.recordHeadlessExecutionSummary({eventId:`event-${W("headless-yoloop-summary",`${r.attempt_id}-${t.status}`)}`,attemptId:r.attempt_id,executionId:r.execution_id,jobId:r.job_id,status:t.status,runtimeId:t.runtimeId,modelId:t.modelId,publicSummary:me(t.publicSummary),reasonCode:t.reasonCode,createdAt:t.completedAt,durationMs:t.durationMs,counts:s,hashes:a,redactionSummary:t.redactionSummary,relativePaths:U([r.target_ref,...t.relativePaths]),metadata:c}),{attemptId:r.attempt_id,executionId:r.execution_id,jobId:r.job_id,status:t.status,outcome:t.receiptStatus,reasonCode:t.reasonCode,timestamp:t.completedAt,childStoryIds:t.childStoryIds,aggregateCounts:t.counts,workerPoolSummary:o,redactionSummary:t.redactionSummary,...t.terminalClass?{terminalClass:t.terminalClass}:{},...t.releaseBlocked?{releaseBlocked:t.releaseBlocked}:{},publicSafe:!0}}function rr(e,r){return{attemptId:e.attempt_id,executionId:e.execution_id,jobId:e.job_id,status:r.status,outcome:r.receiptStatus,reasonCode:r.reasonCode,timestamp:r.timestamp,childStoryIds:[],aggregateCounts:Ie(),workerPoolSummary:_e(),redactionSummary:[],publicSafe:!0}}function or(e,r,t,a,o){if(!r.retryable)return{retry:!1};if(xe.has(r.reasonCode))return{retry:!0,retryCount:e.retry_count,notBeforeAt:He(be(o,a),r.retryNotBeforeAt)};const s=e.retry_count+1;if(s>=Math.max(1,e.max_attempts||t))return{retry:!1,retryCount:s};const n=Math.min(8,2**Math.max(0,e.retry_count));return{retry:!0,retryCount:s,notBeforeAt:He(be(o,a*n),r.retryNotBeforeAt)}}function O(e){return{status:e.status,receiptStatus:e.receiptStatus,reasonCode:e.reasonCode,publicSummary:e.publicSummary,retryable:e.retryable,...e.retryNotBeforeAt?{retryNotBeforeAt:e.retryNotBeforeAt}:{},durationMs:Math.max(0,Date.now()-e.startedAt),counts:e.counts,workerPoolSummary:e.workerPoolSummary??_e(),hashes:e.hashes,redactionSummary:e.redactions.slice(0,50),relativePaths:U(e.relativePaths).slice(0,50),childStoryIds:U(e.childStoryIds).slice(0,50),stateTransitions:U(e.stateTransitions),...e.terminalClass?{terminalClass:e.terminalClass}:{},...e.releaseBlocked?{releaseBlocked:e.releaseBlocked}:{}}}function ar(e,r){if(e===void 0)return;if(!C(e)){r.push(h("runtime","unsafe_key","value-denied"));return}for(const s of Object.keys(e))(!wt.has(s)||ae.test(s))&&r.push(h(`runtime.${s}`,Q(s),"key-denied"));e.publicSafe!==!0&&r.push(h("runtime.publicSafe","unsafe_key","value-denied"));const t=B(e,"runtimeId"),a=B(e,"modelId"),o=B(e,"source");if(t&&(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,79}$/.test(t)||D.test(t)||q.test(t))&&r.push(h("runtime.runtimeId","unsafe_key","value-denied")),a&&(!/^[A-Za-z0-9][A-Za-z0-9._:+/-]{0,119}$/.test(a)||D.test(a)||q.test(a))&&r.push(h("runtime.modelId","unsafe_key","value-denied")),o!==void 0&&o!=="explicit"&&o!=="origin"&&o!=="default"&&o!=="fallback"&&o!=="unspecified"&&r.push(h("runtime.source","unsafe_key","value-denied")),e.reasonCode!==void 0&&(typeof e.reasonCode!="string"||D.test(e.reasonCode))&&r.push(h("runtime.reasonCode","unsafe_key","value-denied")),e.publicSafe===!0)return{...t?{runtimeId:t}:{},...a?{modelId:a}:{},...o==="explicit"||o==="origin"||o==="default"||o==="fallback"||o==="unspecified"?{source:o}:{},...typeof e.reasonCode=="string"?{reasonCode:e.reasonCode}:{},publicSafe:!0}}function nr(e){const r=Array.isArray(e)?e:e?[e]:[],t=[];for(const a of r){const o=a.continuityExecutionDirectives;Array.isArray(o)&&t.push(...o)}return t}function sr(e){return x(ge({kind:e.kind,commandClass:e.commandClass,jobId:e.jobId,targetRef:e.targetRef,commandRef:e.commandRef,epicId:e.epicId,runtime:e.runtime}))}function ge(e){return Array.isArray(e)?`[${e.map(ge).join(",")}]`:C(e)?`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${ge(e[r])}`).join(",")}}`:JSON.stringify(e)}function ue(e,r,t){if(typeof e=="string"){(D.test(e)||q.test(e))&&t.push(h(r,Q(r),"value-denied"));return}if(!(e==null||typeof e=="number"||typeof e=="boolean")){if(Array.isArray(e)){e.forEach((a,o)=>ue(a,`${r}.${o}`,t));return}if(C(e)){for(const[a,o]of Object.entries(e)){const s=`${r}.${a}`;ae.test(a)&&t.push(h(s,Q(a),"key-denied")),ue(o,s,t)}return}t.push(h(r,"unsafe_key","value-denied"))}}function ir(e,r){if(e===void 0)return[];if(!Array.isArray(e))return r.push(h("redactionSummary","unsafe_key","value-denied")),[];const t=[];for(const[a,o]of e.entries()){if(!C(o)||o.publicSafe!==!0){r.push(h(`redactionSummary.${a}`,"unsafe_key","value-denied"));continue}const s=B(o,"field"),n=B(o,"reason"),d=B(o,"evidence");if(!s||!n||!d||D.test(s)||D.test(n)||D.test(d)){r.push(h(`redactionSummary.${a}`,"unsafe_key","value-denied"));continue}t.push({field:s,reason:n,evidence:d,publicSafe:!0})}return t}function P(e,r,t){return{ok:!1,reasonCode:e,publicSummary:r,redactionSummary:t}}function T(e){return Array.isArray(e)?e.filter(r=>typeof r=="string"):[]}function cr(e){return e.length>0&&e.length<=240&&!e.startsWith("-")&&!e.includes("..")&&!e.includes("\\")&&/^[A-Za-z0-9._/-]+$/.test(e)}function Z(e,r){return e.length===r.length&&new Set(e).size===e.length&&e.every(t=>r.includes(t))}function dr(e){return ye.test(e.target_ref)?[e.target_ref]:[]}function je(e){if(!e)return;const r={};for(const[t,a]of Object.entries(e))!/^[A-Za-z0-9_.:-]{1,80}$/.test(t)||ae.test(t)||D.test(t)||typeof a=="string"&&D.test(a)||(r[t]=a);return Object.keys(r).length>0?r:void 0}function Ie(){return k(0,0,0,0,0,0,0)}function k(e,r,t,a,o,s,n){return{iterations:e,childCount:r,succeededChildCount:t,failedChildCount:a,skippedChildCount:o,metadataCompleteCount:s,metadataAbortedCount:n}}function lr(e){return e.replace(/^docs\/stories\//,"").replace(/\.story\.md$/,"")}function se(e){return e.replace(/^docs\/epics\/epic-/,"").replace(/\.md$/,"")}function G(e){return/^[A-Za-z0-9][A-Za-z0-9_-]*\.\d+[A-Za-z0-9_-]*$/.test(e)&&!D.test(e)&&!q.test(e)}function ur(e){if(e==="explicit"||e==="origin"||e==="default"||e==="fallback")return e}function pr(e){if(e==="explicit"||e==="origin"||e==="default"||e==="fallback"||e==="unspecified")return e}function Q(e){return/prompt|commandRef/i.test(e)?"prompt_body":/std(?:out|err)|raw|log|transcript|stack/i.test(e)?"raw_log":/url/i.test(e)?"private_url":/path|cwd|argv|args|shell|command|binary|executable/i.test(e)?"executable_path":/secret|token|password|authorization|api[_-]?key|license/i.test(e)?"secret_or_pii":"unsafe_key"}function B(e,r){return typeof e[r]=="string"?e[r]:void 0}function Se(e){return!!(e&&Et.test(e)&&!D.test(e)&&!q.test(e))}function C(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function mr(e,r){return W(e,`${r}-${Date.now()}-${Ke(4).toString("hex")}`)}function be(e,r){const t=Date.parse(e);return new Date((Number.isFinite(t)?t:Date.now())+r).toISOString()}function He(e,r){const t=Date.parse(e),a=r?Date.parse(r):Number.NaN;return Number.isFinite(a)?Number.isFinite(t)?a>t?r:e:r:e}function V(e,r,t){return Number.isFinite(e)?Math.max(r,Math.min(t,Math.floor(e))):r}function U(e){return Array.from(new Set(e))}function fr(e,r){const t=new Set,a=[];for(const o of e){const s=r(o);t.has(s)||(t.add(s),a.push(o))}return a}export{bt as DEFAULT_HEADLESS_YOLOOP_LEASE_MS,fe as DEFAULT_HEADLESS_YOLOOP_LOCAL_CONCURRENCY_CAP,St as DEFAULT_HEADLESS_YOLOOP_MAX_DURATION_MS,It as DEFAULT_HEADLESS_YOLOOP_MAX_ITERATIONS,Pe as MAX_HEADLESS_YOLOOP_LOCAL_CONCURRENCY_CAP,Nr as RUN_YOLOOP_DRIVER_STATES,Nt as defaultYoloopRootInvoker,Br as executeYoloopV4IntegrationOrder,jr as isCanonicalDelegatedStoryPrompt,we as resolveDefaultHeadlessYoloopLocalConcurrencyCap,Hr as runYoloopExecutionPhase};