@ornexus/neocortex 4.60.73 → 4.60.75

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (269) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1216 -1210
  3. package/install.ps1 +1 -1
  4. package/install.sh +1 -1
  5. package/package.json +2 -2
  6. package/packages/client/dist/adapters/adapter-registry.js +1 -108
  7. package/packages/client/dist/adapters/antigravity-adapter.js +2 -77
  8. package/packages/client/dist/adapters/claude-code-adapter.js +3 -79
  9. package/packages/client/dist/adapters/codex-adapter.js +2 -80
  10. package/packages/client/dist/adapters/cursor-adapter.js +4 -115
  11. package/packages/client/dist/adapters/gemini-adapter.js +2 -71
  12. package/packages/client/dist/adapters/grok-adapter.js +2 -42
  13. package/packages/client/dist/adapters/index.js +1 -22
  14. package/packages/client/dist/adapters/platform-detector.js +1 -212
  15. package/packages/client/dist/adapters/target-adapter.js +0 -12
  16. package/packages/client/dist/adapters/vscode-adapter.js +2 -72
  17. package/packages/client/dist/agent/refresh-stubs.js +2 -417
  18. package/packages/client/dist/agent/update-agent-yaml.js +1 -102
  19. package/packages/client/dist/agent/update-description.js +1 -251
  20. package/packages/client/dist/cache/crypto-utils.js +1 -78
  21. package/packages/client/dist/cache/encrypted-cache.d.ts +27 -0
  22. package/packages/client/dist/cache/encrypted-cache.js +1 -108
  23. package/packages/client/dist/cache/in-memory-asset-cache.js +1 -73
  24. package/packages/client/dist/cache/index.js +1 -13
  25. package/packages/client/dist/cache/protected-pi-boundary.js +1 -44
  26. package/packages/client/dist/checkpoint/checkpoint-client-reader.js +2 -127
  27. package/packages/client/dist/checkpoint/index.js +1 -11
  28. package/packages/client/dist/checkpoint/shared-checkpoint-types.js +1 -32
  29. package/packages/client/dist/cli.js +5 -358
  30. package/packages/client/dist/commands/activate.js +8 -394
  31. package/packages/client/dist/commands/architecture-answers.js +7 -274
  32. package/packages/client/dist/commands/architecture-memory-terminal.js +4 -253
  33. package/packages/client/dist/commands/architecture-non-ui-continuation.js +1 -100
  34. package/packages/client/dist/commands/architecture-root-binding.js +1 -51
  35. package/packages/client/dist/commands/cache-status.js +2 -112
  36. package/packages/client/dist/commands/config.js +1 -88
  37. package/packages/client/dist/commands/doctor.js +2 -635
  38. package/packages/client/dist/commands/invoke.d.ts +38 -1
  39. package/packages/client/dist/commands/invoke.js +143 -7200
  40. package/packages/client/dist/commands/legacy-epic-terminal.js +1 -71
  41. package/packages/client/dist/commands/legacy-story-branch.js +1 -96
  42. package/packages/client/dist/commands/legacy-story-pr.js +1 -276
  43. package/packages/client/dist/commands/mutation-qa-checkpoint.js +5 -285
  44. package/packages/client/dist/commands/mutation-qa-gate.js +1 -54
  45. package/packages/client/dist/commands/mutation-qa-git.js +1 -41
  46. package/packages/client/dist/commands/mutation-qa-policy.js +1 -102
  47. package/packages/client/dist/commands/mutation-qa-run.js +3 -219
  48. package/packages/client/dist/commands/mutation-qa-verdict.js +1 -149
  49. package/packages/client/dist/commands/mutation-qa.js +1 -220
  50. package/packages/client/dist/commands/native-agent.js +2 -136
  51. package/packages/client/dist/commands/planning-diagnosis.js +1 -43
  52. package/packages/client/dist/commands/planning-generation.js +1 -53
  53. package/packages/client/dist/commands/planning-memory.js +1 -40
  54. package/packages/client/dist/commands/planning-research.js +1 -42
  55. package/packages/client/dist/commands/private-session.js +1 -75
  56. package/packages/client/dist/commands/property-qa.js +1 -139
  57. package/packages/client/dist/commands/qa-control.js +1 -16
  58. package/packages/client/dist/commands/qa-scan-browser-launch.js +1 -55
  59. package/packages/client/dist/commands/qa-scan-browser-route.js +1 -28
  60. package/packages/client/dist/commands/qa-scan-capture.js +5 -663
  61. package/packages/client/dist/commands/qa-scan-discovery.js +3 -376
  62. package/packages/client/dist/commands/qa-scan-review.js +5 -826
  63. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +1 -266
  64. package/packages/client/dist/commands/qa-synthetic-backend-review.js +1 -297
  65. package/packages/client/dist/commands/qa-synthetic-backend.js +2 -340
  66. package/packages/client/dist/commands/qa-synthetic-broker-port.js +1 -85
  67. package/packages/client/dist/commands/qa-synthetic-browser.js +1 -39
  68. package/packages/client/dist/commands/refactor-characterization.js +21 -671
  69. package/packages/client/dist/commands/refactor-commit.js +13 -399
  70. package/packages/client/dist/commands/refactor-control.js +3 -142
  71. package/packages/client/dist/commands/refactor-cpp-assertions.js +3 -93
  72. package/packages/client/dist/commands/refactor-review.js +5 -283
  73. package/packages/client/dist/commands/refactor-root.js +7 -588
  74. package/packages/client/dist/commands/refresh-memory.js +3 -156
  75. package/packages/client/dist/commands/shared-architecture-non-ui.js +1 -24
  76. package/packages/client/dist/commands/story-checkpoint.js +1 -171
  77. package/packages/client/dist/config/host-auth-broker.d.ts +31 -0
  78. package/packages/client/dist/config/host-auth-broker.js +1 -0
  79. package/packages/client/dist/config/host-auth-reference.d.ts +32 -0
  80. package/packages/client/dist/config/host-auth-reference.js +1 -0
  81. package/packages/client/dist/config/profile-directory.js +1 -13
  82. package/packages/client/dist/config/resolver-selection.js +1 -278
  83. package/packages/client/dist/config/secure-config.js +12 -281
  84. package/packages/client/dist/config.js +2 -223
  85. package/packages/client/dist/constants.js +1 -25
  86. package/packages/client/dist/context/context-collector.js +2 -222
  87. package/packages/client/dist/context/context-sanitizer.js +1 -145
  88. package/packages/client/dist/continuity/autonomous-governance.js +1 -285
  89. package/packages/client/dist/continuity/continuity-client-state-store.js +1 -1587
  90. package/packages/client/dist/continuity/invoke-hooks.js +1 -129
  91. package/packages/client/dist/continuity/migrations/001-initial-schema.js +2 -12
  92. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +2 -12
  93. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +2 -12
  94. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +2 -12
  95. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +2 -12
  96. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +2 -10
  97. package/packages/client/dist/continuity/native-agent-store.js +1 -69
  98. package/packages/client/dist/continuity/native-agent-types.d.ts +11 -0
  99. package/packages/client/dist/continuity/native-agent-types.js +1 -90
  100. package/packages/client/dist/continuity/outbox.js +1 -117
  101. package/packages/client/dist/continuity/runner-bootstrap-policy.js +1 -172
  102. package/packages/client/dist/continuity/sqlite-store.js +81 -2612
  103. package/packages/client/dist/effects/invoke-effect-gateways.js +1 -62
  104. package/packages/client/dist/errors/error-messages.d.ts +3 -0
  105. package/packages/client/dist/errors/error-messages.js +2 -228
  106. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -125
  107. package/packages/client/dist/evidence/collector.js +1 -347
  108. package/packages/client/dist/evidence/index.js +1 -1
  109. package/packages/client/dist/evidence/types.js +0 -2
  110. package/packages/client/dist/fs/atomic-state-replace.js +1 -152
  111. package/packages/client/dist/generated/command-registry.generated.js +1 -4076
  112. package/packages/client/dist/generated/public-projections.generated.js +1 -149
  113. package/packages/client/dist/git/direct-yolo-c01-retry.js +4 -138
  114. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +11 -1
  115. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -1234
  116. package/packages/client/dist/git/epic-operational-state.js +2 -672
  117. package/packages/client/dist/git/git-lifecycle-step-ids.js +1 -14
  118. package/packages/client/dist/git/git-lifecycle-store.d.ts +23 -0
  119. package/packages/client/dist/git/git-lifecycle-store.js +10 -1981
  120. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +9 -259
  121. package/packages/client/dist/git/legacy-story-branch-setup.js +4 -348
  122. package/packages/client/dist/git/legacy-story-pr.js +70 -3538
  123. package/packages/client/dist/git/secure-filesystem-boundary.js +5 -182
  124. package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -284
  125. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +1 -237
  126. package/packages/client/dist/i18n/first-run.js +2 -60
  127. package/packages/client/dist/index.d.ts +2 -0
  128. package/packages/client/dist/index.js +1 -47
  129. package/packages/client/dist/invocation/invoke-input.js +1 -24
  130. package/packages/client/dist/license/host-auth-recovery.d.ts +158 -0
  131. package/packages/client/dist/license/host-auth-recovery.js +1 -0
  132. package/packages/client/dist/license/index.js +1 -5
  133. package/packages/client/dist/license/license-client.d.ts +10 -1
  134. package/packages/client/dist/license/license-client.js +1 -304
  135. package/packages/client/dist/machine/fingerprint.js +2 -163
  136. package/packages/client/dist/machine/index.js +1 -5
  137. package/packages/client/dist/memory/project-memory-path-scope.js +1 -62
  138. package/packages/client/dist/memory/project-memory-writer.js +40 -1007
  139. package/packages/client/dist/memory/shared-project-memory-types.js +2 -253
  140. package/packages/client/dist/migrations/epic-lifecycle-backfill.js +3 -1060
  141. package/packages/client/dist/migrations/project-identity-capability.js +1 -50
  142. package/packages/client/dist/migrations/project-identity.js +7 -493
  143. package/packages/client/dist/migrations/state-json.js +4 -393
  144. package/packages/client/dist/policy/architecture-policy.js +2 -184
  145. package/packages/client/dist/policy/index.js +1 -7
  146. package/packages/client/dist/policy/shared-policy-types.js +0 -38
  147. package/packages/client/dist/policy/subagent-approval-policy.js +1 -55
  148. package/packages/client/dist/private-execution/clean-baseline.js +2 -279
  149. package/packages/client/dist/private-execution/codex-executor.js +4 -574
  150. package/packages/client/dist/private-execution/codex-host-runtime.js +1 -137
  151. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +1 -97
  152. package/packages/client/dist/private-execution/codex-scoped-permissions.js +1 -128
  153. package/packages/client/dist/private-execution/delivery.js +13 -410
  154. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -294
  155. package/packages/client/dist/private-execution/frozen-handoff.js +6 -19
  156. package/packages/client/dist/private-execution/implementation-validation.js +2 -106
  157. package/packages/client/dist/private-execution/isolated-admission.js +23 -1432
  158. package/packages/client/dist/private-execution/isolated-session.js +5 -725
  159. package/packages/client/dist/private-execution/isolated-workspace.js +1 -122
  160. package/packages/client/dist/private-execution/pact-consumer-runtime.js +3 -409
  161. package/packages/client/dist/private-execution/pact-test-source.js +1 -258
  162. package/packages/client/dist/private-execution/pact-toolchain.js +3 -290
  163. package/packages/client/dist/private-execution/pact-write-set.js +1 -172
  164. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -406
  165. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +5 -462
  166. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +3 -139
  167. package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -325
  168. package/packages/client/dist/private-execution/private-report-store.js +1 -42
  169. package/packages/client/dist/private-execution/property-test-candidate.js +1 -103
  170. package/packages/client/dist/private-execution/property-test-choices.js +3 -147
  171. package/packages/client/dist/private-execution/property-test-plan.js +7 -271
  172. package/packages/client/dist/private-execution/property-test-review.js +4 -258
  173. package/packages/client/dist/private-execution/property-test-runtime.js +9 -372
  174. package/packages/client/dist/private-execution/property-test-source.js +1 -139
  175. package/packages/client/dist/private-execution/root-checkpoint.js +1 -80
  176. package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -135
  177. package/packages/client/dist/private-execution/root-memory-recovery.js +1 -93
  178. package/packages/client/dist/private-execution/root-memory-request.js +1 -29
  179. package/packages/client/dist/private-execution/root-memory-scope.js +1 -178
  180. package/packages/client/dist/private-execution/root-memory-writer.js +1 -102
  181. package/packages/client/dist/private-execution/session-lease.js +1 -63
  182. package/packages/client/dist/private-execution/shared-private-admission-types.js +1 -50
  183. package/packages/client/dist/private-execution/shared-project-validation.js +1 -66
  184. package/packages/client/dist/private-execution/shared-root-memory-types.js +1 -61
  185. package/packages/client/dist/private-execution/ux-source-validation.js +1 -372
  186. package/packages/client/dist/private-execution/ux-write-set.js +2 -191
  187. package/packages/client/dist/registry/registry-reconciliation.js +1 -234
  188. package/packages/client/dist/resilience/circuit-breaker.js +1 -170
  189. package/packages/client/dist/resilience/degradation-manager.js +1 -164
  190. package/packages/client/dist/resilience/freshness-indicator.js +1 -100
  191. package/packages/client/dist/resilience/index.js +1 -8
  192. package/packages/client/dist/resilience/recovery-detector.js +1 -74
  193. package/packages/client/dist/resolvers/asset-resolver.js +0 -13
  194. package/packages/client/dist/resolvers/local-resolver.js +8 -255
  195. package/packages/client/dist/resolvers/remote-resolver.js +1 -233
  196. package/packages/client/dist/runner/binary.js +1 -404
  197. package/packages/client/dist/runner/cli.js +17 -1571
  198. package/packages/client/dist/runner/epic-background-dispatcher.d.ts +61 -0
  199. package/packages/client/dist/runner/epic-background-dispatcher.js +1 -0
  200. package/packages/client/dist/runner/headless/adapters.js +1 -49
  201. package/packages/client/dist/runner/headless/background-root.d.ts +65 -0
  202. package/packages/client/dist/runner/headless/background-root.js +1 -0
  203. package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -79
  204. package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -1628
  205. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +1 -69
  206. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.d.ts +1 -1
  207. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +2 -110
  208. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +2 -0
  209. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -1236
  210. package/packages/client/dist/runner/headless/epic-terminal-git-runner.d.ts +27 -2
  211. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +2 -318
  212. package/packages/client/dist/runner/headless/fake-adapter.js +1 -62
  213. package/packages/client/dist/runner/headless/managed-environment-cleanup.d.ts +95 -0
  214. package/packages/client/dist/runner/headless/managed-environment-cleanup.js +1 -0
  215. package/packages/client/dist/runner/headless/managed-profile.js +1 -132
  216. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -145
  217. package/packages/client/dist/runner/headless/prepared-story-bundle.js +1 -43
  218. package/packages/client/dist/runner/headless/resolver.js +1 -231
  219. package/packages/client/dist/runner/headless/run-yolo.js +1 -885
  220. package/packages/client/dist/runner/headless/run-yoloop.d.ts +1 -0
  221. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2574
  222. package/packages/client/dist/runner/headless/types.js +2 -574
  223. package/packages/client/dist/runner/local-console.js +13 -396
  224. package/packages/client/dist/runner/portal-sync-worker.js +1 -1487
  225. package/packages/client/dist/runner/project-identity.js +1 -106
  226. package/packages/client/dist/runner/scheduler.js +7 -995
  227. package/packages/client/dist/runner-cli.js +2 -18
  228. package/packages/client/dist/state/invocation-shape.js +1 -13
  229. package/packages/client/dist/state/project-state-snapshot.d.ts +7 -0
  230. package/packages/client/dist/state/project-state-snapshot.js +1 -1731
  231. package/packages/client/dist/state/state-json-repair.js +3 -785
  232. package/packages/client/dist/state/structural-dag-projection.js +1 -118
  233. package/packages/client/dist/telemetry/index.js +1 -5
  234. package/packages/client/dist/telemetry/offline-queue.js +1 -131
  235. package/packages/client/dist/tier/index.js +1 -5
  236. package/packages/client/dist/tier/tier-aware-client.js +1 -405
  237. package/packages/client/dist/types/index.js +1 -38
  238. package/packages/client/dist/version.js +1 -27
  239. package/packages/client/dist/yolo/change-evidence-collector.d.ts +21 -1
  240. package/packages/client/dist/yolo/change-evidence-collector.js +1 -126
  241. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -62
  242. package/packages/client/dist/yolo/spec-envelope-collector.js +5 -184
  243. package/packages/client/dist/yoloop/discovery-hook.js +2 -300
  244. package/packages/client/dist/yoloop/index.js +1 -8
  245. package/packages/client/dist/yoloop/invoke-hooks.js +12 -669
  246. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1007
  247. package/packages/client/dist/yoloop/shared-yoloop-types.js +1 -33
  248. package/packages/client/dist/yoloop/target-normalization.js +1 -180
  249. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1920
  250. package/packages/shared/dist/invocation/explicit-intent-recovery.d.ts +83 -0
  251. package/packages/shared/dist/invocation/explicit-intent-recovery.js +187 -0
  252. package/packages/shared/dist/invocation/index.d.ts +7 -0
  253. package/packages/shared/dist/invocation/index.js +22 -0
  254. package/packages/shared/dist/yolo/change-evidence.js +1 -1
  255. package/packages/shared/dist/yoloop/epic-terminal-git.js +144 -2
  256. package/targets-stubs/antigravity/gemini.md +1 -1
  257. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  258. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  259. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  260. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  261. package/targets-stubs/claude-code/neocortex.md +2 -2
  262. package/targets-stubs/codex/AGENTS.md +24 -21
  263. package/targets-stubs/codex/README.md +6 -1
  264. package/targets-stubs/codex/neocortex.toml +7 -2
  265. package/targets-stubs/cursor/agent.md +2 -2
  266. package/targets-stubs/gemini-cli/agent.md +2 -2
  267. package/targets-stubs/opencode/neocortex-root.md +16 -1
  268. package/targets-stubs/opencode/neocortex.md +6 -0
  269. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,885 +1 @@
1
- /**
2
- * @license FSL-1.1
3
- * Copyright (c) 2026 OrNexus AI
4
- *
5
- * P190.05 -- runner execution plane for one-story run_yolo directives.
6
- */
7
- import { createHash, randomBytes } from 'node:crypto';
8
- import { AUTONOMOUS_GOVERNANCE_EVIDENCE_TAG, AUTONOMOUS_GOVERNANCE_REASON_CODES, autonomousGovernanceMetadata, buildAutonomousGovernanceEnvelope, readAutonomousGovernanceEnvelopeFromMetadata, recordAutonomousGovernance, } from '../../continuity/autonomous-governance.js';
9
- import { createDefaultHeadlessAdapterRegistry } from './adapters.js';
10
- import { loadHeadlessRuntimeDefaults, resolveHeadlessRuntime } from './resolver.js';
11
- import { HEADLESS_REASON_CODES, boundPublicSummary, hashPublicValue, redaction, } from './types.js';
12
- export const DEFAULT_HEADLESS_EXECUTION_LEASE_MS = 5 * 60 * 1000;
13
- export const DEFAULT_HEADLESS_EXECUTION_STALE_LEASE_AFTER_MS = 30 * 1000;
14
- export const DEFAULT_HEADLESS_EXECUTION_BACKOFF_MS = 30 * 1000;
15
- export const DEFAULT_HEADLESS_EXECUTION_TIMEOUT_MS = 10 * 60 * 1000;
16
- export const DEFAULT_HEADLESS_EXECUTION_LIMIT = 1;
17
- export const DEFAULT_HEADLESS_EXECUTION_MAX_ATTEMPTS = 3;
18
- const STORY_TARGET_PATTERN = /^docs\/stories\/[A-Za-z0-9._-]+\.story\.md$/;
19
- const SAFE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/;
20
- const EXECUTION_DIRECTIVE_ALLOWED_KEYS = new Set([
21
- 'schemaVersion',
22
- 'contractVersion',
23
- 'kind',
24
- 'commandClass',
25
- 'jobId',
26
- 'operationId',
27
- 'idempotencyKey',
28
- 'targetKind',
29
- 'targetRef',
30
- 'commandRef',
31
- 'storyId',
32
- 'executionMode',
33
- 'runtime',
34
- 'publicSummary',
35
- 'reasonCode',
36
- 'attempts',
37
- 'metadata',
38
- 'redactionSummary',
39
- 'publicSafe',
40
- ]);
41
- const RUNTIME_ALLOWED_KEYS = new Set(['runtimeId', 'modelId', 'source', 'reasonCode', 'publicSafe']);
42
- 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;
43
- 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;
44
- const SHELL_FRAGMENT_PATTERN = /(?:[;&|`$<>]|\$\(|\n|\r|\0)/;
45
- export async function runYoloExecutionPhase(options) {
46
- const registry = options.adapterRegistry ?? createDefaultHeadlessAdapterRegistry();
47
- const limit = boundedInteger(options.limit ?? DEFAULT_HEADLESS_EXECUTION_LIMIT, 1, 10);
48
- const leaseMs = boundedInteger(options.leaseMs ?? DEFAULT_HEADLESS_EXECUTION_LEASE_MS, 1_000, 60 * 60 * 1000);
49
- const staleLeaseAfterMs = boundedInteger(options.staleLeaseAfterMs ?? DEFAULT_HEADLESS_EXECUTION_STALE_LEASE_AFTER_MS, 0, 24 * 60 * 60 * 1000);
50
- const maxAttempts = boundedInteger(options.maxAttempts ?? DEFAULT_HEADLESS_EXECUTION_MAX_ATTEMPTS, 1, 10);
51
- const reasonCodes = [];
52
- const receipts = [];
53
- const nowIso = options.now();
54
- const enqueueResult = enqueueRunYoloExecutionDirectives({
55
- store: options.store,
56
- metadata: options.metadata,
57
- nowIso,
58
- maxAttempts,
59
- queueCap: options.queueCap,
60
- });
61
- reasonCodes.push(...enqueueResult.reasonCodes);
62
- const recovered = options.store.recoverStaleHeadlessExecutionAttempts({
63
- nowIso,
64
- staleAfterMs: staleLeaseAfterMs,
65
- limit: limit * 2,
66
- });
67
- if (recovered.recoveredAttemptIds.length > 0) {
68
- reasonCodes.push(HEADLESS_REASON_CODES.EXECUTION_BACKOFF);
69
- if (recovered.failedAttemptIds.length > 0)
70
- reasonCodes.push(HEADLESS_REASON_CODES.EXECUTION_TIMEOUT);
71
- }
72
- const allowedAttemptIds = new Set(options.attemptIds ?? []);
73
- const dueAttempts = options.store
74
- .listDueHeadlessExecutionAttempts({ nowIso: options.now(), limit: Math.max(limit * 5, 10) })
75
- .filter((attempt) => attempt.directive_kind === 'run_yolo')
76
- .filter((attempt) => allowedAttemptIds.size === 0 || allowedAttemptIds.has(attempt.attempt_id))
77
- .slice(0, limit);
78
- for (const attempt of dueAttempts) {
79
- const receipt = await processRunYoloAttempt({
80
- store: options.store,
81
- projectRoot: options.projectRoot,
82
- runnerId: options.runnerId,
83
- attempt,
84
- registry,
85
- now: options.now,
86
- leaseMs,
87
- timeoutMs: boundedInteger(options.timeoutMs ?? DEFAULT_HEADLESS_EXECUTION_TIMEOUT_MS, 1_000, 30 * 60 * 1000),
88
- backoffMs: boundedInteger(options.backoffMs ?? DEFAULT_HEADLESS_EXECUTION_BACKOFF_MS, 1_000, 60 * 60 * 1000),
89
- maxAttempts,
90
- adapterOptions: options.adapterOptions,
91
- runtimeDefaults: options.runtimeDefaults,
92
- runtimeFallback: options.runtimeFallback,
93
- idFactory: options.idFactory ?? defaultHeadlessIdFactory,
94
- });
95
- receipts.push(receipt);
96
- reasonCodes.push(receipt.reasonCode);
97
- }
98
- return {
99
- ok: receipts.every((receipt) => receipt.outcome !== 'failed') && enqueueResult.rejectedCount === 0,
100
- enqueuedAttemptCount: enqueueResult.enqueuedCount,
101
- dueAttemptCount: dueAttempts.length,
102
- processedAttemptCount: receipts.filter((receipt) => receipt.outcome !== 'ignored').length,
103
- recoveredAttemptIds: recovered.recoveredAttemptIds,
104
- receipts,
105
- reasonCodes: unique(reasonCodes.length > 0 ? reasonCodes : [HEADLESS_REASON_CODES.OK]),
106
- publicSafe: true,
107
- };
108
- }
109
- function enqueueRunYoloExecutionDirectives(input) {
110
- let enqueuedCount = 0;
111
- let rejectedCount = 0;
112
- const reasonCodes = [];
113
- for (const candidate of extractExecutionDirectiveCandidates(input.metadata)) {
114
- if (!isRecord(candidate) || candidate.kind !== 'run_yolo')
115
- continue;
116
- const validation = validateRunYoloExecutionDirective(candidate);
117
- if (!validation.ok) {
118
- rejectedCount += 1;
119
- reasonCodes.push(validation.reasonCode);
120
- continue;
121
- }
122
- const directive = validation.directive;
123
- if (!input.store.jobExists(directive.jobId)) {
124
- rejectedCount += 1;
125
- reasonCodes.push(AUTONOMOUS_GOVERNANCE_REASON_CODES.BYPASS_BLOCKED);
126
- continue;
127
- }
128
- const directiveHash = hashDirective(directive);
129
- if (input.store.hasCompletedHeadlessExecutionDirectiveHash(directiveHash)) {
130
- reasonCodes.push(HEADLESS_REASON_CODES.EXECUTION_COMPLETED);
131
- continue;
132
- }
133
- const governanceEnvelope = buildAutonomousGovernanceEnvelope({
134
- autonomousKind: 'run_yolo',
135
- source: governanceSourceFromDirective(directive.metadata, 'headless-run-yolo'),
136
- targetKind: 'story',
137
- targetRef: directive.targetRef,
138
- storyId: directive.storyId ?? storyIdFromTargetRef(directive.targetRef),
139
- jobId: directive.jobId,
140
- operationSeed: directive.operationId,
141
- commandHash: hashPublicValue(directive.commandRef),
142
- });
143
- const governance = recordAutonomousGovernance(input.store, governanceEnvelope, input.nowIso, { requireExistingJob: true });
144
- if (!governance.ok) {
145
- rejectedCount += 1;
146
- reasonCodes.push(governance.reasonCode);
147
- continue;
148
- }
149
- const attemptId = headlessExecutionEntityId('attempt', directive.idempotencyKey);
150
- const executionId = headlessExecutionEntityId('exec', directive.operationId);
151
- const result = input.store.enqueueHeadlessExecutionAttempt({
152
- attemptId,
153
- executionId,
154
- jobId: directive.jobId,
155
- directiveHash,
156
- directiveKind: 'run_yolo',
157
- commandClass: directive.commandClass,
158
- targetKind: 'story',
159
- targetRef: directive.targetRef,
160
- storyId: directive.storyId ?? storyIdFromTargetRef(directive.targetRef),
161
- runtimeId: directive.runtime?.runtimeId,
162
- modelId: directive.runtime?.modelId,
163
- runtimeSource: normalizeStoredRuntimeSource(directive.runtime?.source),
164
- reasonCode: directive.reasonCode,
165
- publicSummary: directive.publicSummary,
166
- enqueuedAt: input.nowIso,
167
- notBeforeAt: input.nowIso,
168
- maxAttempts: input.maxAttempts,
169
- queueCap: input.queueCap,
170
- operationId: `${directive.operationId}:enqueue`,
171
- idempotencyKey: directive.idempotencyKey,
172
- counts: { directives: 1 },
173
- hashes: { directive: directiveHash },
174
- redactionSummary: directive.redactionSummary,
175
- relativePaths: [directive.targetRef],
176
- metadata: autonomousGovernanceMetadata(governanceEnvelope, {
177
- schemaVersion: 1,
178
- contractVersion: 'continuity-v1',
179
- jobId: directive.jobId,
180
- operationId: directive.operationId,
181
- reasonCode: directive.reasonCode ?? HEADLESS_REASON_CODES.OK,
182
- targetRef: directive.targetRef,
183
- directiveHash,
184
- ...(directive.executionMode ? { executionMode: directive.executionMode } : {}),
185
- }),
186
- });
187
- if (!result.accepted) {
188
- rejectedCount += 1;
189
- reasonCodes.push(result.reasonCode ?? 'queue-cap-reached');
190
- continue;
191
- }
192
- if (result.inserted)
193
- enqueuedCount += 1;
194
- reasonCodes.push(HEADLESS_REASON_CODES.OK);
195
- }
196
- return { enqueuedCount, rejectedCount, reasonCodes: unique(reasonCodes) };
197
- }
198
- async function processRunYoloAttempt(input) {
199
- const claimedAt = input.now();
200
- const leaseId = input.idFactory('lease', input.attempt.attempt_id);
201
- const leaseExpiresAt = addMilliseconds(claimedAt, input.leaseMs);
202
- const claim = input.store.claimHeadlessExecutionAttempt({
203
- attemptId: input.attempt.attempt_id,
204
- leaseId,
205
- runnerId: input.runnerId,
206
- claimedAt,
207
- leaseExpiresAt,
208
- reasonCode: HEADLESS_REASON_CODES.OK,
209
- });
210
- if (!claim.inserted) {
211
- return {
212
- attemptId: input.attempt.attempt_id,
213
- executionId: input.attempt.execution_id,
214
- jobId: input.attempt.job_id,
215
- status: input.attempt.status,
216
- outcome: 'ignored',
217
- reasonCode: 'lease-conflict',
218
- timestamp: claimedAt,
219
- redactionSummary: [],
220
- publicSafe: true,
221
- };
222
- }
223
- const duplicateCompletion = input.store.hasCompletedHeadlessExecutionDirectiveHash(input.attempt.directive_hash, input.attempt.attempt_id);
224
- if (duplicateCompletion) {
225
- return persistAttemptOutcome(input.store, input.attempt, {
226
- leaseId,
227
- runnerId: input.runnerId,
228
- status: 'skipped',
229
- receiptStatus: 'ignored',
230
- reasonCode: HEADLESS_REASON_CODES.EXECUTION_COMPLETED,
231
- publicSummary: 'Skipped duplicate run_yolo directive because the directive hash is already completed.',
232
- completedAt: input.now(),
233
- counts: { duplicateDirectiveHashes: 1 },
234
- hashes: { directive: input.attempt.directive_hash },
235
- redactionSummary: [],
236
- relativePaths: [input.attempt.target_ref],
237
- });
238
- }
239
- const preparation = prepareAttemptInput(input);
240
- if (!preparation.ok) {
241
- return persistAttemptOutcome(input.store, input.attempt, {
242
- leaseId,
243
- runnerId: input.runnerId,
244
- status: preparation.status,
245
- receiptStatus: preparation.receiptStatus,
246
- reasonCode: preparation.reasonCode,
247
- publicSummary: preparation.publicSummary,
248
- completedAt: input.now(),
249
- counts: { rejectedDirectives: 1 },
250
- hashes: { directive: input.attempt.directive_hash },
251
- redactionSummary: preparation.redactionSummary,
252
- relativePaths: safeAttemptRelativePaths(input.attempt),
253
- });
254
- }
255
- const adapterLookup = input.registry.getAdapter(preparation.input.runtimeId);
256
- if (!adapterLookup.ok) {
257
- return persistAttemptOutcome(input.store, input.attempt, {
258
- leaseId,
259
- runnerId: input.runnerId,
260
- status: 'failed',
261
- receiptStatus: 'failed',
262
- reasonCode: adapterLookup.reasonCode,
263
- publicSummary: adapterLookup.publicSummary,
264
- completedAt: input.now(),
265
- counts: { rejectedAdapters: 1 },
266
- hashes: { directive: input.attempt.directive_hash },
267
- redactionSummary: adapterLookup.redactionSummary,
268
- relativePaths: [input.attempt.target_ref],
269
- runtimeId: preparation.input.runtimeId,
270
- modelId: preparation.input.modelId,
271
- runtimeSource: preparation.input.runtimeSource,
272
- });
273
- }
274
- let adapterResult;
275
- try {
276
- adapterResult = await adapterLookup.adapter.execute(preparation.input, {
277
- ...input.adapterOptions,
278
- cwd: input.adapterOptions?.cwd ?? input.projectRoot,
279
- });
280
- }
281
- catch {
282
- adapterResult = {
283
- status: 'failed',
284
- adapterId: preparation.input.runtimeId,
285
- runtimeId: preparation.input.runtimeId,
286
- ...(preparation.input.modelId ? { modelId: preparation.input.modelId } : {}),
287
- ...(preparation.input.runtimeSource ? { runtimeSource: preparation.input.runtimeSource } : {}),
288
- reasonCode: HEADLESS_REASON_CODES.EXECUTION_FAILED,
289
- reasonCodes: [HEADLESS_REASON_CODES.EXECUTION_FAILED, HEADLESS_REASON_CODES.RECEIPT_REDACTED],
290
- exitCode: 1,
291
- signal: null,
292
- durationMs: 0,
293
- counts: { adapterExceptions: 1 },
294
- hashes: { directive: input.attempt.directive_hash },
295
- publicSummary: 'Headless adapter failed with public-safe exception summary.',
296
- redactionSummary: [redaction('adapter', 'raw_log', 'value-denied')],
297
- relativePaths: [input.attempt.target_ref],
298
- receipt: preparation.input.receipt,
299
- publicSafe: true,
300
- };
301
- }
302
- const retry = retryDecision(input.attempt, adapterResult, input.maxAttempts, input.backoffMs, input.now());
303
- const status = retry.retry ? 'backoff' : adapterResult.status;
304
- const reasonCode = retry.retry ? HEADLESS_REASON_CODES.EXECUTION_BACKOFF : adapterResult.reasonCode;
305
- const receiptStatus = status === 'completed' ? 'applied' : status === 'backoff' ? 'deferred' : status === 'skipped' ? 'ignored' : 'failed';
306
- return persistAttemptOutcome(input.store, input.attempt, {
307
- leaseId,
308
- runnerId: input.runnerId,
309
- status,
310
- receiptStatus,
311
- reasonCode,
312
- publicSummary: retry.retry
313
- ? 'Headless run_yolo execution scheduled bounded retry after transient adapter outcome.'
314
- : adapterResult.publicSummary,
315
- completedAt: input.now(),
316
- durationMs: adapterResult.durationMs,
317
- notBeforeAt: retry.notBeforeAt,
318
- retryCount: retry.retryCount,
319
- counts: adapterResult.counts,
320
- hashes: { ...adapterResult.hashes, directive: input.attempt.directive_hash },
321
- redactionSummary: adapterResult.redactionSummary,
322
- relativePaths: adapterResult.relativePaths.length > 0 ? adapterResult.relativePaths : [input.attempt.target_ref],
323
- runtimeId: adapterResult.runtimeId,
324
- modelId: adapterResult.modelId,
325
- runtimeSource: adapterResult.runtimeSource,
326
- });
327
- }
328
- function prepareAttemptInput(input) {
329
- const governance = readAutonomousGovernanceEnvelopeFromMetadata(input.attempt.metadata_json, {
330
- autonomousKind: 'run_yolo',
331
- jobId: input.attempt.job_id,
332
- targetKind: 'story',
333
- targetRef: input.attempt.target_ref,
334
- });
335
- if (!governance.ok) {
336
- return {
337
- ok: false,
338
- status: 'failed',
339
- receiptStatus: 'failed',
340
- reasonCode: HEADLESS_REASON_CODES.DIRECTIVE_REJECTED,
341
- publicSummary: governance.publicSummary,
342
- redactionSummary: governance.redactionSummary,
343
- };
344
- }
345
- const directCommandHash = hashPublicValue(`*yolo @${input.attempt.target_ref}`);
346
- const branchlessCommandHash = hashPublicValue(`*yolo @${input.attempt.target_ref} branchless-preparation`);
347
- const branchlessPreparation = governance.envelope.hashes.command === branchlessCommandHash;
348
- if (!branchlessPreparation && governance.envelope.hashes.command !== directCommandHash) {
349
- return {
350
- ok: false,
351
- status: 'failed',
352
- receiptStatus: 'failed',
353
- reasonCode: HEADLESS_REASON_CODES.DIRECTIVE_REJECTED,
354
- publicSummary: 'Headless run_yolo governance command does not match an authorized execution mode.',
355
- redactionSummary: [redaction('autonomousGovernance.commandHash', 'prompt_body', 'operation-denied')],
356
- };
357
- }
358
- const promptValidation = validateRunYoloAttemptShape(input.attempt);
359
- if (!promptValidation.ok)
360
- return promptValidation;
361
- const runtime = resolveAttemptRuntime(input);
362
- if (!runtime.ok) {
363
- return {
364
- ok: false,
365
- status: 'failed',
366
- receiptStatus: 'failed',
367
- reasonCode: runtime.reasonCode,
368
- publicSummary: runtime.publicSummary,
369
- redactionSummary: runtime.redactionSummary,
370
- };
371
- }
372
- return {
373
- ok: true,
374
- input: {
375
- promptKind: branchlessPreparation ? 'yolo-branchless-preparation' : 'yolo',
376
- targetKind: 'story',
377
- targetRef: input.attempt.target_ref,
378
- ...(input.attempt.story_id ? { storyId: input.attempt.story_id } : {}),
379
- runtimeId: runtime.runtimeId,
380
- ...(runtime.modelId ? { modelId: runtime.modelId } : {}),
381
- runtimeSource: runtime.runtimeSource,
382
- timeoutMs: input.timeoutMs,
383
- receipt: {
384
- attemptId: input.attempt.attempt_id,
385
- subagentId: input.attempt.attempt_id,
386
- executionId: input.attempt.execution_id,
387
- jobId: input.attempt.job_id,
388
- operationId: input.attempt.execution_id,
389
- idempotencyKey: input.attempt.directive_hash,
390
- runnerId: input.runnerId,
391
- },
392
- publicSummary: boundPublicSummary(input.attempt.public_summary ?? 'Headless run_yolo execution attempt.'),
393
- publicSafe: true,
394
- },
395
- };
396
- }
397
- function resolveAttemptRuntime(input) {
398
- const defaults = input.runtimeDefaults !== undefined
399
- ? input.runtimeDefaults
400
- : loadHeadlessRuntimeDefaults({ projectRoot: input.projectRoot });
401
- if (isRecord(defaults) && defaults.ok === false) {
402
- return {
403
- ok: false,
404
- reasonCode: HEADLESS_REASON_CODES.RUNTIME_UNTRUSTED,
405
- publicSummary: typeof defaults.publicSummary === 'string' ? defaults.publicSummary : 'Headless runtime defaults failed public-safety validation.',
406
- redactionSummary: Array.isArray(defaults.redactionSummary) ? defaults.redactionSummary : [],
407
- };
408
- }
409
- const source = normalizeRuntimeSource(input.attempt.runtime_source) ?? 'explicit';
410
- const hint = (input.attempt.runtime_id || input.attempt.model_id)
411
- ? {
412
- ...(input.attempt.runtime_id ? { runtimeId: input.attempt.runtime_id } : {}),
413
- ...(input.attempt.model_id ? { modelId: input.attempt.model_id } : {}),
414
- source,
415
- publicSafe: true,
416
- }
417
- : undefined;
418
- const resolutionInput = {
419
- registry: input.registry,
420
- defaults,
421
- fallback: input.runtimeFallback,
422
- };
423
- if (hint) {
424
- if (source === 'origin')
425
- resolutionInput.origin = hint;
426
- else if (source === 'default')
427
- resolutionInput.projectDefault = hint;
428
- else if (source === 'fallback')
429
- resolutionInput.fallback = hint;
430
- else
431
- resolutionInput.explicit = hint;
432
- }
433
- const resolution = resolveHeadlessRuntime(resolutionInput);
434
- if (!resolution.ok) {
435
- return {
436
- ok: false,
437
- reasonCode: resolution.reasonCode,
438
- publicSummary: resolution.publicSummary,
439
- redactionSummary: resolution.redactionSummary,
440
- };
441
- }
442
- return {
443
- ok: true,
444
- runtimeId: resolution.runtimeId,
445
- ...(resolution.modelId ? { modelId: resolution.modelId } : {}),
446
- runtimeSource: resolution.runtimeSource,
447
- };
448
- }
449
- function validateRunYoloAttemptShape(attempt) {
450
- const redactions = [];
451
- if (attempt.directive_kind !== 'run_yolo')
452
- redactions.push(redaction('directiveKind', 'unsafe_key', 'value-denied'));
453
- if (attempt.target_kind !== 'story')
454
- redactions.push(redaction('targetKind', 'prompt_body', 'value-denied'));
455
- if (!STORY_TARGET_PATTERN.test(attempt.target_ref) || SHELL_FRAGMENT_PATTERN.test(attempt.target_ref) || UNSAFE_VALUE_PATTERN.test(attempt.target_ref)) {
456
- redactions.push(redaction('targetRef', 'prompt_body', 'value-denied'));
457
- }
458
- const storyId = storyIdFromTargetRef(attempt.target_ref);
459
- if (attempt.story_id && attempt.story_id !== storyId)
460
- redactions.push(redaction('storyId', 'prompt_body', 'value-denied'));
461
- if (redactions.length > 0) {
462
- return {
463
- ok: false,
464
- status: 'failed',
465
- receiptStatus: 'failed',
466
- reasonCode: HEADLESS_REASON_CODES.PROMPT_REJECTED,
467
- publicSummary: 'Headless run_yolo attempt did not match the canonical public story prompt shape.',
468
- redactionSummary: redactions,
469
- };
470
- }
471
- return {
472
- ok: true,
473
- input: {
474
- promptKind: 'yolo',
475
- targetKind: 'story',
476
- targetRef: attempt.target_ref,
477
- ...(attempt.story_id ? { storyId: attempt.story_id } : {}),
478
- runtimeId: 'fake',
479
- publicSafe: true,
480
- },
481
- };
482
- }
483
- function validateRunYoloExecutionDirective(input) {
484
- const redactions = [];
485
- for (const key of Object.keys(input)) {
486
- if (!EXECUTION_DIRECTIVE_ALLOWED_KEYS.has(key) || UNSAFE_KEY_PATTERN.test(key)) {
487
- redactions.push(redaction(key, unsafeKeyReason(key), 'key-denied'));
488
- }
489
- }
490
- if (input.publicSafe !== true)
491
- redactions.push(redaction('publicSafe', 'unsafe_key', 'value-denied'));
492
- const kind = stringField(input, 'kind');
493
- const commandClass = stringField(input, 'commandClass');
494
- const jobId = stringField(input, 'jobId');
495
- const operationId = stringField(input, 'operationId');
496
- const idempotencyKey = stringField(input, 'idempotencyKey');
497
- const targetKind = stringField(input, 'targetKind');
498
- const targetRef = stringField(input, 'targetRef');
499
- const commandRef = stringField(input, 'commandRef');
500
- const publicSummary = stringField(input, 'publicSummary');
501
- const storyId = stringField(input, 'storyId');
502
- const executionMode = stringField(input, 'executionMode');
503
- if (kind !== 'run_yolo')
504
- redactions.push(redaction('kind', 'unsafe_key', 'value-denied'));
505
- if (commandClass !== 'goal-tick' && commandClass !== 'loop-tick')
506
- redactions.push(redaction('commandClass', 'unsafe_key', 'value-denied'));
507
- if (!isSafeIdentifier(jobId))
508
- redactions.push(redaction('jobId', 'unsafe_key', 'value-denied'));
509
- if (!isSafeIdentifier(operationId))
510
- redactions.push(redaction('operationId', 'unsafe_key', 'value-denied'));
511
- if (!isSafeIdentifier(idempotencyKey))
512
- redactions.push(redaction('idempotencyKey', 'unsafe_key', 'value-denied'));
513
- if (targetKind !== 'story' || !targetRef || !STORY_TARGET_PATTERN.test(targetRef) || UNSAFE_VALUE_PATTERN.test(targetRef)) {
514
- redactions.push(redaction('targetRef', 'prompt_body', 'value-denied'));
515
- }
516
- if (executionMode !== undefined && executionMode !== 'branchless_child_preparation') {
517
- redactions.push(redaction('executionMode', 'unsafe_key', 'value-denied'));
518
- }
519
- const metadata = isRecord(input.metadata) ? input.metadata : undefined;
520
- const branchlessPreparation = executionMode === 'branchless_child_preparation';
521
- if (branchlessPreparation && (metadata?.governanceSource !== 'delegated-subagent'
522
- || metadata.childWorkspace !== 'branchless_sandbox'
523
- || metadata.integrationOwner !== 'root_agent'
524
- || metadata.maxDepth !== 1
525
- || typeof metadata.graphRevision !== 'string'
526
- || !/^[a-f0-9]{64}$/.test(metadata.graphRevision))) {
527
- redactions.push(redaction('executionMode', 'unsafe_key', 'value-denied'));
528
- }
529
- const expectedCommandRef = targetRef
530
- ? `*yolo @${targetRef}${branchlessPreparation ? ' branchless-preparation' : ''}`
531
- : undefined;
532
- if (!commandRef || commandRef !== expectedCommandRef || commandRef.includes('@neocortex') || SHELL_FRAGMENT_PATTERN.test(commandRef) || UNSAFE_VALUE_PATTERN.test(commandRef)) {
533
- redactions.push(redaction('commandRef', 'prompt_body', 'value-denied'));
534
- }
535
- if (storyId && targetRef && storyId !== storyIdFromTargetRef(targetRef))
536
- redactions.push(redaction('storyId', 'prompt_body', 'value-denied'));
537
- if (!publicSummary || publicSummary.length > 240 || UNSAFE_VALUE_PATTERN.test(publicSummary)) {
538
- redactions.push(redaction('publicSummary', 'unbounded_text', 'value-denied'));
539
- }
540
- if (input.reasonCode !== undefined && (typeof input.reasonCode !== 'string' || UNSAFE_VALUE_PATTERN.test(input.reasonCode))) {
541
- redactions.push(redaction('reasonCode', 'unsafe_key', 'value-denied'));
542
- }
543
- const runtime = validateDirectiveRuntime(input.runtime, redactions);
544
- if (input.attempts !== undefined)
545
- assertPublicSafeCandidate(input.attempts, 'attempts', redactions);
546
- if (input.metadata !== undefined)
547
- assertPublicSafeCandidate(input.metadata, 'metadata', redactions);
548
- const redactionSummary = validateDirectiveRedactions(input.redactionSummary, redactions);
549
- if (redactions.length > 0 || kind !== 'run_yolo' || !commandClass || !jobId || !operationId || !idempotencyKey || !targetRef || !commandRef || !publicSummary) {
550
- const promptRejected = redactions.some((item) => item.reason === 'prompt_body');
551
- return {
552
- ok: false,
553
- reasonCode: promptRejected ? HEADLESS_REASON_CODES.PROMPT_REJECTED : HEADLESS_REASON_CODES.DIRECTIVE_REJECTED,
554
- redactionSummary: redactions,
555
- };
556
- }
557
- return {
558
- ok: true,
559
- directive: {
560
- kind: 'run_yolo',
561
- commandClass: commandClass,
562
- jobId: jobId,
563
- operationId: operationId,
564
- idempotencyKey: idempotencyKey,
565
- targetKind: 'story',
566
- targetRef: targetRef,
567
- commandRef: commandRef,
568
- ...(storyId ? { storyId } : {}),
569
- ...(branchlessPreparation ? { executionMode: 'branchless_child_preparation' } : {}),
570
- ...(runtime ? { runtime } : {}),
571
- publicSummary: publicSummary,
572
- ...(typeof input.reasonCode === 'string' ? { reasonCode: input.reasonCode } : {}),
573
- ...(metadata ? { metadata } : {}),
574
- ...(redactionSummary.length > 0 ? { redactionSummary } : {}),
575
- publicSafe: true,
576
- },
577
- };
578
- }
579
- function governanceSourceFromDirective(metadata, fallback) {
580
- return metadata?.governanceSource === 'delegated-subagent' ? 'delegated-subagent' : fallback;
581
- }
582
- function validateDirectiveRuntime(value, redactions) {
583
- if (value === undefined)
584
- return undefined;
585
- if (!isRecord(value)) {
586
- redactions.push(redaction('runtime', 'unsafe_key', 'value-denied'));
587
- return undefined;
588
- }
589
- for (const key of Object.keys(value)) {
590
- if (!RUNTIME_ALLOWED_KEYS.has(key) || UNSAFE_KEY_PATTERN.test(key))
591
- redactions.push(redaction(`runtime.${key}`, unsafeKeyReason(key), 'key-denied'));
592
- }
593
- if (value.publicSafe !== true)
594
- redactions.push(redaction('runtime.publicSafe', 'unsafe_key', 'value-denied'));
595
- const runtimeId = stringField(value, 'runtimeId');
596
- const modelId = stringField(value, 'modelId');
597
- const source = stringField(value, 'source');
598
- if (runtimeId && (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,79}$/.test(runtimeId) || UNSAFE_VALUE_PATTERN.test(runtimeId) || SHELL_FRAGMENT_PATTERN.test(runtimeId))) {
599
- redactions.push(redaction('runtime.runtimeId', 'unsafe_key', 'value-denied'));
600
- }
601
- if (modelId && (!/^[A-Za-z0-9][A-Za-z0-9._:+/-]{0,119}$/.test(modelId) || UNSAFE_VALUE_PATTERN.test(modelId) || SHELL_FRAGMENT_PATTERN.test(modelId))) {
602
- redactions.push(redaction('runtime.modelId', 'unsafe_key', 'value-denied'));
603
- }
604
- if (source !== undefined && source !== 'explicit' && source !== 'origin' && source !== 'default' && source !== 'fallback' && source !== 'unspecified') {
605
- redactions.push(redaction('runtime.source', 'unsafe_key', 'value-denied'));
606
- }
607
- if (value.reasonCode !== undefined && (typeof value.reasonCode !== 'string' || UNSAFE_VALUE_PATTERN.test(value.reasonCode))) {
608
- redactions.push(redaction('runtime.reasonCode', 'unsafe_key', 'value-denied'));
609
- }
610
- if (value.publicSafe !== true)
611
- return undefined;
612
- return {
613
- ...(runtimeId ? { runtimeId } : {}),
614
- ...(modelId ? { modelId } : {}),
615
- ...(source === 'explicit' || source === 'origin' || source === 'default' || source === 'fallback' || source === 'unspecified' ? { source } : {}),
616
- ...(typeof value.reasonCode === 'string' ? { reasonCode: value.reasonCode } : {}),
617
- publicSafe: true,
618
- };
619
- }
620
- function persistAttemptOutcome(store, attempt, outcome) {
621
- const redactionSummary = outcome.redactionSummary ?? [];
622
- const relativePaths = outcome.relativePaths ?? safeAttemptRelativePaths(attempt);
623
- const counts = sanitizePublicRecord(outcome.counts);
624
- const hashes = sanitizePublicRecord(outcome.hashes);
625
- const outcomeMetadata = {
626
- schemaVersion: 1,
627
- contractVersion: 'continuity-v1',
628
- attemptId: attempt.attempt_id,
629
- executionId: attempt.execution_id,
630
- jobId: attempt.job_id,
631
- directiveHash: attempt.directive_hash,
632
- status: outcome.status,
633
- reasonCode: outcome.reasonCode,
634
- ...(outcome.runtimeId ? { runtimeId: outcome.runtimeId } : {}),
635
- ...(outcome.modelId ? { modelId: outcome.modelId } : {}),
636
- ...(outcome.runtimeSource ? { runtimeSource: outcome.runtimeSource } : {}),
637
- ...(outcome.retryCount !== undefined ? { retryCount: outcome.retryCount } : {}),
638
- ...(outcome.reasonCode === AUTONOMOUS_GOVERNANCE_REASON_CODES.BYPASS_BLOCKED ? { governanceEvidence: AUTONOMOUS_GOVERNANCE_EVIDENCE_TAG } : {}),
639
- publicSummary: boundPublicSummary(outcome.publicSummary),
640
- };
641
- const governance = readAutonomousGovernanceEnvelopeFromMetadata(attempt.metadata_json, {
642
- autonomousKind: 'run_yolo',
643
- jobId: attempt.job_id,
644
- targetKind: 'story',
645
- targetRef: attempt.target_ref,
646
- });
647
- // Backoff reuses the same attempt row. Preserve only its already-validated,
648
- // public-safe authority envelope so retry preparation remains fail-closed
649
- // without converting a recoverable execution boundary into a rejection.
650
- const metadata = governance.ok
651
- ? autonomousGovernanceMetadata(governance.envelope, outcomeMetadata)
652
- : outcomeMetadata;
653
- store.completeHeadlessExecutionAttempt({
654
- attemptId: attempt.attempt_id,
655
- executionId: attempt.execution_id,
656
- jobId: attempt.job_id,
657
- leaseId: outcome.leaseId,
658
- runnerId: outcome.runnerId,
659
- status: outcome.status,
660
- completedAt: outcome.completedAt,
661
- durationMs: outcome.durationMs,
662
- reasonCode: outcome.reasonCode,
663
- publicSummary: boundPublicSummary(outcome.publicSummary),
664
- notBeforeAt: outcome.notBeforeAt,
665
- retryCount: outcome.retryCount,
666
- counts,
667
- hashes,
668
- redactionSummary,
669
- relativePaths,
670
- metadata,
671
- });
672
- store.recordHeadlessExecutionReceipt({
673
- receiptId: `receipt-${safeEntityId('headless', `${attempt.attempt_id}-${outcome.status}`)}`,
674
- attemptId: attempt.attempt_id,
675
- executionId: attempt.execution_id,
676
- jobId: attempt.job_id,
677
- status: outcome.receiptStatus,
678
- reasonCode: outcome.reasonCode,
679
- createdAt: outcome.completedAt,
680
- operationId: `${attempt.execution_id}:${outcome.status}:receipt`,
681
- idempotencyKey: `${attempt.directive_hash}:${outcome.status}:receipt`,
682
- counts,
683
- hashes,
684
- redactionSummary,
685
- relativePaths,
686
- metadata,
687
- });
688
- store.recordHeadlessExecutionSummary({
689
- eventId: `event-${safeEntityId('headless-summary', `${attempt.attempt_id}-${outcome.status}`)}`,
690
- attemptId: attempt.attempt_id,
691
- executionId: attempt.execution_id,
692
- jobId: attempt.job_id,
693
- status: outcome.status,
694
- runtimeId: outcome.runtimeId,
695
- modelId: outcome.modelId,
696
- publicSummary: boundPublicSummary(outcome.publicSummary),
697
- reasonCode: outcome.reasonCode,
698
- createdAt: outcome.completedAt,
699
- durationMs: outcome.durationMs,
700
- counts,
701
- hashes,
702
- redactionSummary,
703
- relativePaths,
704
- metadata,
705
- });
706
- return {
707
- attemptId: attempt.attempt_id,
708
- executionId: attempt.execution_id,
709
- jobId: attempt.job_id,
710
- status: outcome.status,
711
- outcome: outcome.receiptStatus,
712
- reasonCode: outcome.reasonCode,
713
- timestamp: outcome.completedAt,
714
- redactionSummary,
715
- publicSafe: true,
716
- };
717
- }
718
- function retryDecision(attempt, result, maxAttempts, backoffMs, nowIso) {
719
- const transient = result.status === 'timed_out'
720
- || result.reasonCode === HEADLESS_REASON_CODES.EXECUTION_FAILED
721
- || result.reasonCode === HEADLESS_REASON_CODES.ADAPTER_UNAVAILABLE;
722
- if (!transient)
723
- return { retry: false };
724
- const retryCount = attempt.retry_count + 1;
725
- if (retryCount >= Math.max(1, attempt.max_attempts || maxAttempts))
726
- return { retry: false, retryCount };
727
- const multiplier = Math.min(8, 2 ** Math.max(0, attempt.retry_count));
728
- return {
729
- retry: true,
730
- retryCount,
731
- notBeforeAt: addMilliseconds(nowIso, backoffMs * multiplier),
732
- };
733
- }
734
- function extractExecutionDirectiveCandidates(metadata) {
735
- const records = Array.isArray(metadata) ? metadata : metadata ? [metadata] : [];
736
- const directives = [];
737
- for (const record of records) {
738
- const value = record.continuityExecutionDirectives;
739
- if (Array.isArray(value))
740
- directives.push(...value);
741
- }
742
- return directives;
743
- }
744
- function hashDirective(directive) {
745
- return hashPublicValue(stableJson({
746
- kind: directive.kind,
747
- commandClass: directive.commandClass,
748
- jobId: directive.jobId,
749
- targetRef: directive.targetRef,
750
- commandRef: directive.commandRef,
751
- storyId: directive.storyId,
752
- executionMode: directive.executionMode,
753
- runtime: directive.runtime,
754
- }));
755
- }
756
- function stableJson(value) {
757
- if (Array.isArray(value))
758
- return `[${value.map(stableJson).join(',')}]`;
759
- if (isRecord(value)) {
760
- return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableJson(value[key])}`).join(',')}}`;
761
- }
762
- return JSON.stringify(value);
763
- }
764
- function assertPublicSafeCandidate(value, path, redactions) {
765
- if (typeof value === 'string') {
766
- if (UNSAFE_VALUE_PATTERN.test(value) || SHELL_FRAGMENT_PATTERN.test(value))
767
- redactions.push(redaction(path, unsafeKeyReason(path), 'value-denied'));
768
- return;
769
- }
770
- if (value === undefined || value === null || typeof value === 'number' || typeof value === 'boolean')
771
- return;
772
- if (Array.isArray(value)) {
773
- value.forEach((item, index) => assertPublicSafeCandidate(item, `${path}.${index}`, redactions));
774
- return;
775
- }
776
- if (isRecord(value)) {
777
- for (const [key, child] of Object.entries(value)) {
778
- const field = `${path}.${key}`;
779
- if (UNSAFE_KEY_PATTERN.test(key))
780
- redactions.push(redaction(field, unsafeKeyReason(key), 'key-denied'));
781
- assertPublicSafeCandidate(child, field, redactions);
782
- }
783
- return;
784
- }
785
- redactions.push(redaction(path, 'unsafe_key', 'value-denied'));
786
- }
787
- function validateDirectiveRedactions(value, redactions) {
788
- if (value === undefined)
789
- return [];
790
- if (!Array.isArray(value)) {
791
- redactions.push(redaction('redactionSummary', 'unsafe_key', 'value-denied'));
792
- return [];
793
- }
794
- const safe = [];
795
- for (const [index, item] of value.entries()) {
796
- if (!isRecord(item) || item.publicSafe !== true) {
797
- redactions.push(redaction(`redactionSummary.${index}`, 'unsafe_key', 'value-denied'));
798
- continue;
799
- }
800
- const field = stringField(item, 'field');
801
- const reason = stringField(item, 'reason');
802
- const evidence = stringField(item, 'evidence');
803
- if (!field || !reason || !evidence || UNSAFE_VALUE_PATTERN.test(field) || UNSAFE_VALUE_PATTERN.test(reason) || UNSAFE_VALUE_PATTERN.test(evidence)) {
804
- redactions.push(redaction(`redactionSummary.${index}`, 'unsafe_key', 'value-denied'));
805
- continue;
806
- }
807
- safe.push({ field, reason, evidence, publicSafe: true });
808
- }
809
- return safe;
810
- }
811
- function safeAttemptRelativePaths(attempt) {
812
- return STORY_TARGET_PATTERN.test(attempt.target_ref) ? [attempt.target_ref] : [];
813
- }
814
- function sanitizePublicRecord(record) {
815
- if (!record)
816
- return undefined;
817
- const output = {};
818
- for (const [key, value] of Object.entries(record)) {
819
- if (!/^[A-Za-z0-9_.:-]{1,80}$/.test(key) || UNSAFE_KEY_PATTERN.test(key) || UNSAFE_VALUE_PATTERN.test(key))
820
- continue;
821
- if (typeof value === 'string' && UNSAFE_VALUE_PATTERN.test(value))
822
- continue;
823
- output[key] = value;
824
- }
825
- return Object.keys(output).length > 0 ? output : undefined;
826
- }
827
- function storyIdFromTargetRef(targetRef) {
828
- return targetRef.replace(/^docs\/stories\//, '').replace(/\.story\.md$/, '');
829
- }
830
- function normalizeRuntimeSource(value) {
831
- if (value === 'explicit' || value === 'origin' || value === 'default' || value === 'fallback')
832
- return value;
833
- return undefined;
834
- }
835
- function normalizeStoredRuntimeSource(value) {
836
- if (value === 'explicit' || value === 'origin' || value === 'default' || value === 'fallback' || value === 'unspecified')
837
- return value;
838
- return undefined;
839
- }
840
- function unsafeKeyReason(key) {
841
- if (/prompt|commandRef/i.test(key))
842
- return 'prompt_body';
843
- if (/std(?:out|err)|raw|log|transcript|stack/i.test(key))
844
- return 'raw_log';
845
- if (/url/i.test(key))
846
- return 'private_url';
847
- if (/path|cwd|argv|args|shell|command|binary|executable/i.test(key))
848
- return 'executable_path';
849
- if (/secret|token|password|authorization|api[_-]?key|license/i.test(key))
850
- return 'secret_or_pii';
851
- return 'unsafe_key';
852
- }
853
- function stringField(record, key) {
854
- return typeof record[key] === 'string' ? record[key] : undefined;
855
- }
856
- function isSafeIdentifier(value) {
857
- return Boolean(value && SAFE_ID_PATTERN.test(value) && !UNSAFE_VALUE_PATTERN.test(value) && !SHELL_FRAGMENT_PATTERN.test(value));
858
- }
859
- function isRecord(value) {
860
- return typeof value === 'object' && value !== null && !Array.isArray(value);
861
- }
862
- function safeEntityId(prefix, value) {
863
- const normalized = `${prefix}-${value}`.replace(/[^A-Za-z0-9_.:-]+/g, '-').replace(/^-+|-+$/g, '');
864
- if (normalized.length > 0 && normalized.length <= 120)
865
- return normalized;
866
- return `${prefix}-${createHash('sha256').update(value).digest('hex').slice(0, 32)}`;
867
- }
868
- export function headlessExecutionEntityId(prefix, value) {
869
- return safeEntityId(prefix, value);
870
- }
871
- function defaultHeadlessIdFactory(prefix, attemptId) {
872
- return safeEntityId(prefix, `${attemptId}-${Date.now()}-${randomBytes(4).toString('hex')}`);
873
- }
874
- function addMilliseconds(iso, ms) {
875
- const base = Date.parse(iso);
876
- return new Date((Number.isFinite(base) ? base : Date.now()) + ms).toISOString();
877
- }
878
- function boundedInteger(value, min, max) {
879
- if (!Number.isFinite(value))
880
- return min;
881
- return Math.max(min, Math.min(max, Math.floor(value)));
882
- }
883
- function unique(values) {
884
- return Array.from(new Set(values));
885
- }
1
+ import{createHash as q,randomBytes as Y}from"node:crypto";import{P205_RELEASE_GATE_BUDGETS as G,P205_ROOT_INVOKE_TIMEOUT_MS as K}from"../../../../shared/dist/yoloop/epic-terminal-git.js";import{AUTONOMOUS_GOVERNANCE_EVIDENCE_TAG as Z,AUTONOMOUS_GOVERNANCE_REASON_CODES as P,autonomousGovernanceMetadata as $,buildAutonomousGovernanceEnvelope as J,readAutonomousGovernanceEnvelopeFromMetadata as U,recordAutonomousGovernance as W}from"../../continuity/autonomous-governance.js";import{createDefaultHeadlessAdapterRegistry as Q}from"./adapters.js";import{loadHeadlessRuntimeDefaults as ee,resolveHeadlessRuntime as te}from"./resolver.js";import{HEADLESS_REASON_CODES as m,boundPublicSummary as A,hashPublicValue as g,redaction as i}from"./types.js";const re=K+60*1e3,oe=30*1e3,ae=30*1e3,ne=K,se=1,de=3,O=/^docs\/stories\/[A-Za-z0-9._-]+\.story\.md$/,ie=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/,ue=new Set(["schemaVersion","contractVersion","kind","commandClass","jobId","operationId","idempotencyKey","targetKind","targetRef","commandRef","storyId","executionMode","runtime","publicSummary","reasonCode","attempts","metadata","redactionSummary","publicSafe"]),ce=new Set(["runtimeId","modelId","source","reasonCode","publicSafe"]),R=/(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,y=/(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,E=/(?:[;&|`$<>]|\$\(|\n|\r|\0)/;async function Me(e){const t=e.adapterRegistry??Q(),r=b(e.limit??se,1,10),a=b(e.leaseMs??re,1e3,G.terminalWorkflowMaxDurationMs),n=b(e.staleLeaseAfterMs??oe,0,1440*60*1e3),s=b(e.maxAttempts??de,1,10),o=[],u=[],d=e.now(),c=me({store:e.store,metadata:e.metadata,nowIso:d,maxAttempts:s,queueCap:e.queueCap});o.push(...c.reasonCodes);const p=e.store.recoverStaleHeadlessExecutionAttempts({nowIso:d,staleAfterMs:n,limit:r*2});p.recoveredAttemptIds.length>0&&(o.push(m.EXECUTION_BACKOFF),p.failedAttemptIds.length>0&&o.push(m.EXECUTION_TIMEOUT));const I=new Set(e.attemptIds??[]),_=e.store.listDueHeadlessExecutionAttempts({nowIso:e.now(),limit:Math.max(r*5,10)}).filter(l=>l.directive_kind==="run_yolo").filter(l=>I.size===0||I.has(l.attempt_id)).slice(0,r);for(const l of _){const S=await le({store:e.store,projectRoot:e.projectRoot,runnerId:e.runnerId,attempt:l,registry:t,now:e.now,leaseMs:a,timeoutMs:b(e.timeoutMs??ne,1e3,72e5),backoffMs:b(e.backoffMs??ae,1e3,36e5),maxAttempts:s,adapterOptions:e.adapterOptions,runtimeDefaults:e.runtimeDefaults,runtimeFallback:e.runtimeFallback,idFactory:e.idFactory??Re});u.push(S),o.push(S.reasonCode)}return{ok:u.every(l=>l.outcome!=="failed")&&c.rejectedCount===0,enqueuedAttemptCount:c.enqueuedCount,dueAttemptCount:_.length,processedAttemptCount:u.filter(l=>l.outcome!=="ignored").length,recoveredAttemptIds:p.recoveredAttemptIds,receipts:u,reasonCodes:V(o.length>0?o:[m.OK]),publicSafe:!0}}function me(e){let t=0,r=0;const a=[];for(const n of Ee(e.metadata)){if(!h(n)||n.kind!=="run_yolo")continue;const s=_e(n);if(!s.ok){r+=1,a.push(s.reasonCode);continue}const o=s.directive;if(!e.store.jobExists(o.jobId)){r+=1,a.push(P.BYPASS_BLOCKED);continue}const u=be(o);if(e.store.hasCompletedHeadlessExecutionDirectiveHash(u)){a.push(m.EXECUTION_COMPLETED);continue}const d=J({autonomousKind:"run_yolo",source:Ie(o.metadata,"headless-run-yolo"),targetKind:"story",targetRef:o.targetRef,storyId:o.storyId??T(o.targetRef),jobId:o.jobId,operationSeed:o.operationId,commandHash:g(o.commandRef)}),c=W(e.store,d,e.nowIso,{requireExistingJob:!0});if(!c.ok){r+=1,a.push(c.reasonCode);continue}const p=F("attempt",o.idempotencyKey),I=F("exec",o.operationId),_=e.store.enqueueHeadlessExecutionAttempt({attemptId:p,executionId:I,jobId:o.jobId,directiveHash:u,directiveKind:"run_yolo",commandClass:o.commandClass,targetKind:"story",targetRef:o.targetRef,storyId:o.storyId??T(o.targetRef),runtimeId:o.runtime?.runtimeId,modelId:o.runtime?.modelId,runtimeSource:ge(o.runtime?.source),reasonCode:o.reasonCode,publicSummary:o.publicSummary,enqueuedAt:e.nowIso,notBeforeAt:e.nowIso,maxAttempts:e.maxAttempts,queueCap:e.queueCap,operationId:`${o.operationId}:enqueue`,idempotencyKey:o.idempotencyKey,counts:{directives:1},hashes:{directive:u},redactionSummary:o.redactionSummary,relativePaths:[o.targetRef],metadata:$(d,{schemaVersion:1,contractVersion:"continuity-v1",jobId:o.jobId,operationId:o.operationId,reasonCode:o.reasonCode??m.OK,targetRef:o.targetRef,directiveHash:u,...o.executionMode?{executionMode:o.executionMode}:{}})});if(!_.accepted){r+=1,a.push(_.reasonCode??"queue-cap-reached");continue}_.inserted&&(t+=1),a.push(m.OK)}return{enqueuedCount:t,rejectedCount:r,reasonCodes:V(a)}}async function le(e){const t=e.now(),r=e.idFactory("lease",e.attempt.attempt_id),a=z(t,e.leaseMs);if(!e.store.claimHeadlessExecutionAttempt({attemptId:e.attempt.attempt_id,leaseId:r,runnerId:e.runnerId,claimedAt:t,leaseExpiresAt:a,reasonCode:m.OK}).inserted)return{attemptId:e.attempt.attempt_id,executionId:e.attempt.execution_id,jobId:e.attempt.job_id,status:e.attempt.status,outcome:"ignored",reasonCode:"lease-conflict",timestamp:t,redactionSummary:[],publicSafe:!0};if(e.store.hasCompletedHeadlessExecutionDirectiveHash(e.attempt.directive_hash,e.attempt.attempt_id))return k(e.store,e.attempt,{leaseId:r,runnerId:e.runnerId,status:"skipped",receiptStatus:"ignored",reasonCode:m.EXECUTION_COMPLETED,publicSummary:"Skipped duplicate run_yolo directive because the directive hash is already completed.",completedAt:e.now(),counts:{duplicateDirectiveHashes:1},hashes:{directive:e.attempt.directive_hash},redactionSummary:[],relativePaths:[e.attempt.target_ref]});const o=fe(e);if(!o.ok)return k(e.store,e.attempt,{leaseId:r,runnerId:e.runnerId,status:o.status,receiptStatus:o.receiptStatus,reasonCode:o.reasonCode,publicSummary:o.publicSummary,completedAt:e.now(),counts:{rejectedDirectives:1},hashes:{directive:e.attempt.directive_hash},redactionSummary:o.redactionSummary,relativePaths:H(e.attempt)});const u=e.registry.getAdapter(o.input.runtimeId);if(!u.ok)return k(e.store,e.attempt,{leaseId:r,runnerId:e.runnerId,status:"failed",receiptStatus:"failed",reasonCode:u.reasonCode,publicSummary:u.publicSummary,completedAt:e.now(),counts:{rejectedAdapters:1},hashes:{directive:e.attempt.directive_hash},redactionSummary:u.redactionSummary,relativePaths:[e.attempt.target_ref],runtimeId:o.input.runtimeId,modelId:o.input.modelId,runtimeSource:o.input.runtimeSource});let d;try{d=await u.adapter.execute(o.input,{...e.adapterOptions,cwd:e.adapterOptions?.cwd??e.projectRoot})}catch{d={status:"failed",adapterId:o.input.runtimeId,runtimeId:o.input.runtimeId,...o.input.modelId?{modelId:o.input.modelId}:{},...o.input.runtimeSource?{runtimeSource:o.input.runtimeSource}:{},reasonCode:m.EXECUTION_FAILED,reasonCodes:[m.EXECUTION_FAILED,m.RECEIPT_REDACTED],exitCode:1,signal:null,durationMs:0,counts:{adapterExceptions:1},hashes:{directive:e.attempt.directive_hash},publicSummary:"Headless adapter failed with public-safe exception summary.",redactionSummary:[i("adapter","raw_log","value-denied")],relativePaths:[e.attempt.target_ref],receipt:o.input.receipt,publicSafe:!0}}const c=Se(e.attempt,d,e.maxAttempts,e.backoffMs,e.now()),p=c.retry?"backoff":d.status,I=c.retry?m.EXECUTION_BACKOFF:d.reasonCode,_=p==="completed"?"applied":p==="backoff"?"deferred":p==="skipped"?"ignored":"failed";return k(e.store,e.attempt,{leaseId:r,runnerId:e.runnerId,status:p,receiptStatus:_,reasonCode:I,publicSummary:c.retry?"Headless run_yolo execution scheduled bounded retry after transient adapter outcome.":d.publicSummary,completedAt:e.now(),durationMs:d.durationMs,notBeforeAt:c.notBeforeAt,retryCount:c.retryCount,counts:d.counts,hashes:{...d.hashes,directive:e.attempt.directive_hash},redactionSummary:d.redactionSummary,relativePaths:d.relativePaths.length>0?d.relativePaths:[e.attempt.target_ref],runtimeId:d.runtimeId,modelId:d.modelId,runtimeSource:d.runtimeSource})}function fe(e){const t=U(e.attempt.metadata_json,{autonomousKind:"run_yolo",jobId:e.attempt.job_id,targetKind:"story",targetRef:e.attempt.target_ref});if(!t.ok)return{ok:!1,status:"failed",receiptStatus:"failed",reasonCode:m.DIRECTIVE_REJECTED,publicSummary:t.publicSummary,redactionSummary:t.redactionSummary};const r=g(`*yolo @${e.attempt.target_ref}`),a=g(`*yolo @${e.attempt.target_ref} branchless-preparation`),n=t.envelope.hashes.command===a;if(!n&&t.envelope.hashes.command!==r)return{ok:!1,status:"failed",receiptStatus:"failed",reasonCode:m.DIRECTIVE_REJECTED,publicSummary:"Headless run_yolo governance command does not match an authorized execution mode.",redactionSummary:[i("autonomousGovernance.commandHash","prompt_body","operation-denied")]};const s=ye(e.attempt);if(!s.ok)return s;const o=pe(e);return o.ok?{ok:!0,input:{promptKind:n?"yolo-branchless-preparation":"yolo",targetKind:"story",targetRef:e.attempt.target_ref,...e.attempt.story_id?{storyId:e.attempt.story_id}:{},runtimeId:o.runtimeId,...o.modelId?{modelId:o.modelId}:{},runtimeSource:o.runtimeSource,timeoutMs:e.timeoutMs,receipt:{attemptId:e.attempt.attempt_id,subagentId:e.attempt.attempt_id,executionId:e.attempt.execution_id,jobId:e.attempt.job_id,operationId:e.attempt.execution_id,idempotencyKey:e.attempt.directive_hash,runnerId:e.runnerId},publicSummary:A(e.attempt.public_summary??"Headless run_yolo execution attempt."),publicSafe:!0}}:{ok:!1,status:"failed",receiptStatus:"failed",reasonCode:o.reasonCode,publicSummary:o.publicSummary,redactionSummary:o.redactionSummary}}function pe(e){const t=e.runtimeDefaults!==void 0?e.runtimeDefaults:ee({projectRoot:e.projectRoot});if(h(t)&&t.ok===!1)return{ok:!1,reasonCode:m.RUNTIME_UNTRUSTED,publicSummary:typeof t.publicSummary=="string"?t.publicSummary:"Headless runtime defaults failed public-safety validation.",redactionSummary:Array.isArray(t.redactionSummary)?t.redactionSummary:[]};const r=Ae(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:r,publicSafe:!0}:void 0,n={registry:e.registry,defaults:t,fallback:e.runtimeFallback};a&&(r==="origin"?n.origin=a:r==="default"?n.projectDefault=a:r==="fallback"?n.fallback=a:n.explicit=a);const s=te(n);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 ye(e){const t=[];e.directive_kind!=="run_yolo"&&t.push(i("directiveKind","unsafe_key","value-denied")),e.target_kind!=="story"&&t.push(i("targetKind","prompt_body","value-denied")),(!O.test(e.target_ref)||E.test(e.target_ref)||y.test(e.target_ref))&&t.push(i("targetRef","prompt_body","value-denied"));const r=T(e.target_ref);return e.story_id&&e.story_id!==r&&t.push(i("storyId","prompt_body","value-denied")),t.length>0?{ok:!1,status:"failed",receiptStatus:"failed",reasonCode:m.PROMPT_REJECTED,publicSummary:"Headless run_yolo attempt did not match the canonical public story prompt shape.",redactionSummary:t}:{ok:!0,input:{promptKind:"yolo",targetKind:"story",targetRef:e.target_ref,...e.story_id?{storyId:e.story_id}:{},runtimeId:"fake",publicSafe:!0}}}function _e(e){const t=[];for(const C of Object.keys(e))(!ue.has(C)||R.test(C))&&t.push(i(C,v(C),"key-denied"));e.publicSafe!==!0&&t.push(i("publicSafe","unsafe_key","value-denied"));const r=f(e,"kind"),a=f(e,"commandClass"),n=f(e,"jobId"),s=f(e,"operationId"),o=f(e,"idempotencyKey"),u=f(e,"targetKind"),d=f(e,"targetRef"),c=f(e,"commandRef"),p=f(e,"publicSummary"),I=f(e,"storyId"),_=f(e,"executionMode");r!=="run_yolo"&&t.push(i("kind","unsafe_key","value-denied")),a!=="goal-tick"&&a!=="loop-tick"&&t.push(i("commandClass","unsafe_key","value-denied")),j(n)||t.push(i("jobId","unsafe_key","value-denied")),j(s)||t.push(i("operationId","unsafe_key","value-denied")),j(o)||t.push(i("idempotencyKey","unsafe_key","value-denied")),(u!=="story"||!d||!O.test(d)||y.test(d))&&t.push(i("targetRef","prompt_body","value-denied")),_!==void 0&&_!=="branchless_child_preparation"&&t.push(i("executionMode","unsafe_key","value-denied"));const l=h(e.metadata)?e.metadata:void 0,S=_==="branchless_child_preparation";S&&(l?.governanceSource!=="delegated-subagent"||l.childWorkspace!=="branchless_sandbox"||l.integrationOwner!=="root_agent"||l.maxDepth!==1||typeof l.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(l.graphRevision))&&t.push(i("executionMode","unsafe_key","value-denied"));const B=d?`*yolo @${d}${S?" branchless-preparation":""}`:void 0;(!c||c!==B||c.includes("@neocortex")||E.test(c)||y.test(c))&&t.push(i("commandRef","prompt_body","value-denied")),I&&d&&I!==T(d)&&t.push(i("storyId","prompt_body","value-denied")),(!p||p.length>240||y.test(p))&&t.push(i("publicSummary","unbounded_text","value-denied")),e.reasonCode!==void 0&&(typeof e.reasonCode!="string"||y.test(e.reasonCode))&&t.push(i("reasonCode","unsafe_key","value-denied"));const N=he(e.runtime,t);e.attempts!==void 0&&x(e.attempts,"attempts",t),e.metadata!==void 0&&x(e.metadata,"metadata",t);const w=Ce(e.redactionSummary,t);return t.length>0||r!=="run_yolo"||!a||!n||!s||!o||!d||!c||!p?{ok:!1,reasonCode:t.some(X=>X.reason==="prompt_body")?m.PROMPT_REJECTED:m.DIRECTIVE_REJECTED,redactionSummary:t}:{ok:!0,directive:{kind:"run_yolo",commandClass:a,jobId:n,operationId:s,idempotencyKey:o,targetKind:"story",targetRef:d,commandRef:c,...I?{storyId:I}:{},...S?{executionMode:"branchless_child_preparation"}:{},...N?{runtime:N}:{},publicSummary:p,...typeof e.reasonCode=="string"?{reasonCode:e.reasonCode}:{},...l?{metadata:l}:{},...w.length>0?{redactionSummary:w}:{},publicSafe:!0}}}function Ie(e,t){return e?.governanceSource==="delegated-subagent"?"delegated-subagent":t}function he(e,t){if(e===void 0)return;if(!h(e)){t.push(i("runtime","unsafe_key","value-denied"));return}for(const s of Object.keys(e))(!ce.has(s)||R.test(s))&&t.push(i(`runtime.${s}`,v(s),"key-denied"));e.publicSafe!==!0&&t.push(i("runtime.publicSafe","unsafe_key","value-denied"));const r=f(e,"runtimeId"),a=f(e,"modelId"),n=f(e,"source");if(r&&(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,79}$/.test(r)||y.test(r)||E.test(r))&&t.push(i("runtime.runtimeId","unsafe_key","value-denied")),a&&(!/^[A-Za-z0-9][A-Za-z0-9._:+/-]{0,119}$/.test(a)||y.test(a)||E.test(a))&&t.push(i("runtime.modelId","unsafe_key","value-denied")),n!==void 0&&n!=="explicit"&&n!=="origin"&&n!=="default"&&n!=="fallback"&&n!=="unspecified"&&t.push(i("runtime.source","unsafe_key","value-denied")),e.reasonCode!==void 0&&(typeof e.reasonCode!="string"||y.test(e.reasonCode))&&t.push(i("runtime.reasonCode","unsafe_key","value-denied")),e.publicSafe===!0)return{...r?{runtimeId:r}:{},...a?{modelId:a}:{},...n==="explicit"||n==="origin"||n==="default"||n==="fallback"||n==="unspecified"?{source:n}:{},...typeof e.reasonCode=="string"?{reasonCode:e.reasonCode}:{},publicSafe:!0}}function k(e,t,r){const a=r.redactionSummary??[],n=r.relativePaths??H(t),s=L(r.counts),o=L(r.hashes),u={schemaVersion:1,contractVersion:"continuity-v1",attemptId:t.attempt_id,executionId:t.execution_id,jobId:t.job_id,directiveHash:t.directive_hash,status:r.status,reasonCode:r.reasonCode,...r.runtimeId?{runtimeId:r.runtimeId}:{},...r.modelId?{modelId:r.modelId}:{},...r.runtimeSource?{runtimeSource:r.runtimeSource}:{},...r.retryCount!==void 0?{retryCount:r.retryCount}:{},...r.reasonCode===P.BYPASS_BLOCKED?{governanceEvidence:Z}:{},publicSummary:A(r.publicSummary)},d=U(t.metadata_json,{autonomousKind:"run_yolo",jobId:t.job_id,targetKind:"story",targetRef:t.target_ref}),c=d.ok?$(d.envelope,u):u;return e.completeHeadlessExecutionAttempt({attemptId:t.attempt_id,executionId:t.execution_id,jobId:t.job_id,leaseId:r.leaseId,runnerId:r.runnerId,status:r.status,completedAt:r.completedAt,durationMs:r.durationMs,reasonCode:r.reasonCode,publicSummary:A(r.publicSummary),notBeforeAt:r.notBeforeAt,retryCount:r.retryCount,counts:s,hashes:o,redactionSummary:a,relativePaths:n,metadata:c}),e.recordHeadlessExecutionReceipt({receiptId:`receipt-${D("headless",`${t.attempt_id}-${r.status}`)}`,attemptId:t.attempt_id,executionId:t.execution_id,jobId:t.job_id,status:r.receiptStatus,reasonCode:r.reasonCode,createdAt:r.completedAt,operationId:`${t.execution_id}:${r.status}:receipt`,idempotencyKey:`${t.directive_hash}:${r.status}:receipt`,counts:s,hashes:o,redactionSummary:a,relativePaths:n,metadata:c}),e.recordHeadlessExecutionSummary({eventId:`event-${D("headless-summary",`${t.attempt_id}-${r.status}`)}`,attemptId:t.attempt_id,executionId:t.execution_id,jobId:t.job_id,status:r.status,runtimeId:r.runtimeId,modelId:r.modelId,publicSummary:A(r.publicSummary),reasonCode:r.reasonCode,createdAt:r.completedAt,durationMs:r.durationMs,counts:s,hashes:o,redactionSummary:a,relativePaths:n,metadata:c}),{attemptId:t.attempt_id,executionId:t.execution_id,jobId:t.job_id,status:r.status,outcome:r.receiptStatus,reasonCode:r.reasonCode,timestamp:r.completedAt,redactionSummary:a,publicSafe:!0}}function Se(e,t,r,a,n){if(!(t.status==="timed_out"||t.reasonCode===m.EXECUTION_FAILED||t.reasonCode===m.ADAPTER_UNAVAILABLE))return{retry:!1};const o=e.retry_count+1;if(o>=Math.max(1,e.max_attempts||r))return{retry:!1,retryCount:o};const u=Math.min(8,2**Math.max(0,e.retry_count));return{retry:!0,retryCount:o,notBeforeAt:z(n,a*u)}}function Ee(e){const t=Array.isArray(e)?e:e?[e]:[],r=[];for(const a of t){const n=a.continuityExecutionDirectives;Array.isArray(n)&&r.push(...n)}return r}function be(e){return g(M({kind:e.kind,commandClass:e.commandClass,jobId:e.jobId,targetRef:e.targetRef,commandRef:e.commandRef,storyId:e.storyId,executionMode:e.executionMode,runtime:e.runtime}))}function M(e){return Array.isArray(e)?`[${e.map(M).join(",")}]`:h(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${M(e[t])}`).join(",")}}`:JSON.stringify(e)}function x(e,t,r){if(typeof e=="string"){(y.test(e)||E.test(e))&&r.push(i(t,v(t),"value-denied"));return}if(!(e==null||typeof e=="number"||typeof e=="boolean")){if(Array.isArray(e)){e.forEach((a,n)=>x(a,`${t}.${n}`,r));return}if(h(e)){for(const[a,n]of Object.entries(e)){const s=`${t}.${a}`;R.test(a)&&r.push(i(s,v(a),"key-denied")),x(n,s,r)}return}r.push(i(t,"unsafe_key","value-denied"))}}function Ce(e,t){if(e===void 0)return[];if(!Array.isArray(e))return t.push(i("redactionSummary","unsafe_key","value-denied")),[];const r=[];for(const[a,n]of e.entries()){if(!h(n)||n.publicSafe!==!0){t.push(i(`redactionSummary.${a}`,"unsafe_key","value-denied"));continue}const s=f(n,"field"),o=f(n,"reason"),u=f(n,"evidence");if(!s||!o||!u||y.test(s)||y.test(o)||y.test(u)){t.push(i(`redactionSummary.${a}`,"unsafe_key","value-denied"));continue}r.push({field:s,reason:o,evidence:u,publicSafe:!0})}return r}function H(e){return O.test(e.target_ref)?[e.target_ref]:[]}function L(e){if(!e)return;const t={};for(const[r,a]of Object.entries(e))!/^[A-Za-z0-9_.:-]{1,80}$/.test(r)||R.test(r)||y.test(r)||typeof a=="string"&&y.test(a)||(t[r]=a);return Object.keys(t).length>0?t:void 0}function T(e){return e.replace(/^docs\/stories\//,"").replace(/\.story\.md$/,"")}function Ae(e){if(e==="explicit"||e==="origin"||e==="default"||e==="fallback")return e}function ge(e){if(e==="explicit"||e==="origin"||e==="default"||e==="fallback"||e==="unspecified")return e}function v(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 f(e,t){return typeof e[t]=="string"?e[t]:void 0}function j(e){return!!(e&&ie.test(e)&&!y.test(e)&&!E.test(e))}function h(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function D(e,t){const r=`${e}-${t}`.replace(/[^A-Za-z0-9_.:-]+/g,"-").replace(/^-+|-+$/g,"");return r.length>0&&r.length<=120?r:`${e}-${q("sha256").update(t).digest("hex").slice(0,32)}`}function F(e,t){return D(e,t)}function Re(e,t){return D(e,`${t}-${Date.now()}-${Y(4).toString("hex")}`)}function z(e,t){const r=Date.parse(e);return new Date((Number.isFinite(r)?r:Date.now())+t).toISOString()}function b(e,t,r){return Number.isFinite(e)?Math.max(t,Math.min(r,Math.floor(e))):t}function V(e){return Array.from(new Set(e))}export{ae as DEFAULT_HEADLESS_EXECUTION_BACKOFF_MS,re as DEFAULT_HEADLESS_EXECUTION_LEASE_MS,se as DEFAULT_HEADLESS_EXECUTION_LIMIT,de as DEFAULT_HEADLESS_EXECUTION_MAX_ATTEMPTS,oe as DEFAULT_HEADLESS_EXECUTION_STALE_LEASE_AFTER_MS,ne as DEFAULT_HEADLESS_EXECUTION_TIMEOUT_MS,F as headlessExecutionEntityId,Me as runYoloExecutionPhase};