@ornexus/neocortex 4.60.77 → 4.60.79

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