@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,574 +1,2 @@
1
- /**
2
- * @license FSL-1.1
3
- * Copyright (c) 2026 OrNexus AI
4
- *
5
- * P190.04 -- public-safe headless runtime/adapter contracts.
6
- */
7
- import { createHash } from 'node:crypto';
8
- import { spawn } from 'node:child_process';
9
- import { createLocalJobConsoleServer } from '../local-console.js';
10
- export const HEADLESS_ADAPTER_IDS = Object.freeze([
11
- 'fake',
12
- 'test',
13
- 'opencode',
14
- 'claude-code',
15
- ]);
16
- export const HEADLESS_REASON_CODES = Object.freeze({
17
- OK: 'continuity-ok',
18
- RUNTIME_EXPLICIT: 'headless-runtime-explicit',
19
- RUNTIME_ORIGIN: 'headless-runtime-origin',
20
- RUNTIME_DEFAULT: 'headless-runtime-default',
21
- RUNTIME_FALLBACK: 'headless-runtime-fallback',
22
- RUNTIME_UNRESOLVED: 'headless-runtime-unresolved',
23
- RUNTIME_UNTRUSTED: 'headless-runtime-untrusted',
24
- MODEL_REJECTED: 'headless-model-rejected',
25
- DIRECTIVE_REJECTED: 'headless-directive-rejected',
26
- PROMPT_REJECTED: 'headless-prompt-rejected',
27
- ADAPTER_UNAVAILABLE: 'headless-adapter-unavailable',
28
- RUNTIME_AUTH_REQUIRED: 'headless-runtime-auth-required',
29
- MANAGED_PROFILE_MISSING: 'headless-managed-profile-missing',
30
- MANAGED_PROFILE_INVALID: 'headless-managed-profile-invalid',
31
- APPROVAL_POLICY_INVALID: 'headless-approval-policy-invalid',
32
- APPROVAL_POLICY_MISMATCH: 'headless-approval-policy-mismatch',
33
- EXECUTION_CANCELLED: 'headless-execution-cancelled',
34
- EXECUTION_TIMEOUT: 'headless-execution-timeout',
35
- EXECUTION_BACKOFF: 'headless-execution-backoff',
36
- EXECUTION_COMPLETED: 'headless-execution-completed',
37
- EXECUTION_FAILED: 'headless-execution-failed',
38
- RECEIPT_REDACTED: 'headless-receipt-redacted',
39
- YOLOOP_METADATA_INVALID: 'headless-yoloop-metadata-invalid',
40
- YOLOOP_ISOLATION_VIOLATION: 'headless-yoloop-isolation-violation',
41
- WORKER_POOL_SERIAL_FALLBACK: 'worker-pool-serial-fallback',
42
- WORKER_POOL_PARALLEL_ACTIVE: 'worker-pool-parallel-active',
43
- WORKER_POOL_BACKPRESSURE_PAUSED: 'worker-pool-backpressure-paused',
44
- });
45
- const HEADLESS_MODEL_ID_MAX_CHARS = 120;
46
- const HEADLESS_PUBLIC_SUMMARY_MAX_CHARS = 240;
47
- const DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;
48
- const MAX_TIMEOUT_MS = 30 * 60 * 1000;
49
- const MODEL_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:+/-]{0,119}$/;
50
- const STORY_REF_PATTERN = /^docs\/stories\/[A-Za-z0-9._-]+\.story\.md$/;
51
- const EPIC_REF_PATTERN = /^docs\/epics\/epic-[A-Za-z0-9._-]+\.md$/;
52
- 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;
53
- 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)/i;
54
- const SHELL_FRAGMENT_PATTERN = /(?:[;&|`$<>]|\$\(|\n|\r|\0)/;
55
- const ADAPTER_INPUT_ALLOWED_KEYS = new Set([
56
- 'promptKind',
57
- 'targetKind',
58
- 'targetRef',
59
- 'storyId',
60
- 'epicId',
61
- 'runtimeId',
62
- 'modelId',
63
- 'runtimeSource',
64
- 'timeoutMs',
65
- 'receipt',
66
- 'publicSummary',
67
- 'publicSafe',
68
- ]);
69
- const RECEIPT_ALLOWED_KEYS = new Set([
70
- 'executionId',
71
- 'attemptId',
72
- 'jobId',
73
- 'operationId',
74
- 'idempotencyKey',
75
- 'runnerId',
76
- 'subagentId',
77
- ]);
78
- export function isHeadlessAdapterId(value) {
79
- return HEADLESS_ADAPTER_IDS.includes(value);
80
- }
81
- export function validateHeadlessAdapterExecutionInput(input, expectedRuntimeId) {
82
- const redactions = [];
83
- const rejectedKeys = [];
84
- if (!isRecord(input)) {
85
- redactions.push(redaction('input', 'unsafe_key', 'value-denied'));
86
- return rejectAdapterInput(HEADLESS_REASON_CODES.DIRECTIVE_REJECTED, 'Headless adapter input must be a public object.', redactions);
87
- }
88
- for (const key of Object.keys(input)) {
89
- if (!ADAPTER_INPUT_ALLOWED_KEYS.has(key)) {
90
- rejectedKeys.push(key);
91
- redactions.push(redaction(key, unsafeKeyReason(key), 'key-denied'));
92
- }
93
- }
94
- const publicSafe = input.publicSafe === true;
95
- if (!publicSafe)
96
- redactions.push(redaction('publicSafe', 'unsafe_key', 'value-denied'));
97
- const promptKind = stringValue(input.promptKind);
98
- if (promptKind !== 'yolo' && promptKind !== 'yolo-branchless-preparation' && promptKind !== 'yoloop') {
99
- redactions.push(redaction('promptKind', 'unsafe_key', 'value-denied'));
100
- }
101
- const targetKind = stringValue(input.targetKind);
102
- if (targetKind !== 'story' && targetKind !== 'epic') {
103
- redactions.push(redaction('targetKind', 'unsafe_key', 'value-denied'));
104
- }
105
- const targetRef = stringValue(input.targetRef);
106
- if (!targetRef || !isSafePublicText(targetRef) || SHELL_FRAGMENT_PATTERN.test(targetRef) || targetRef.includes('..')) {
107
- redactions.push(redaction('targetRef', 'prompt_body', 'value-denied'));
108
- }
109
- if ((promptKind === 'yolo' || promptKind === 'yolo-branchless-preparation')
110
- && (targetKind !== 'story' || !targetRef || !STORY_REF_PATTERN.test(targetRef))) {
111
- redactions.push(redaction('targetRef', 'prompt_body', 'value-denied'));
112
- }
113
- if (promptKind === 'yoloop' && (targetKind !== 'epic' || !targetRef || !EPIC_REF_PATTERN.test(targetRef))) {
114
- redactions.push(redaction('targetRef', 'prompt_body', 'value-denied'));
115
- }
116
- const storyId = optionalSafeString(input.storyId, 'storyId', redactions);
117
- const epicId = optionalSafeString(input.epicId, 'epicId', redactions);
118
- if (storyId && targetRef && (promptKind === 'yolo' || promptKind === 'yolo-branchless-preparation')
119
- && storyId !== targetRef.replace(/^docs\/stories\//, '').replace(/\.story\.md$/, '')) {
120
- redactions.push(redaction('storyId', 'prompt_body', 'value-denied'));
121
- }
122
- if (epicId && targetRef && promptKind === 'yoloop' && epicId !== targetRef.replace(/^docs\/epics\/epic-/, '').replace(/\.md$/, '')) {
123
- redactions.push(redaction('epicId', 'prompt_body', 'value-denied'));
124
- }
125
- const runtimeId = stringValue(input.runtimeId);
126
- if (!runtimeId || !isHeadlessAdapterId(runtimeId) || (expectedRuntimeId && runtimeId !== expectedRuntimeId)) {
127
- redactions.push(redaction('runtimeId', 'unsafe_key', 'value-denied'));
128
- }
129
- const modelId = optionalSafeModelId(input.modelId, redactions);
130
- const runtimeSource = optionalRuntimeSource(input.runtimeSource, redactions);
131
- const timeoutMs = normalizeTimeout(input.timeoutMs, redactions);
132
- const publicSummary = optionalPublicSummary(input.publicSummary, redactions);
133
- const receipt = validateReceipt(input.receipt, redactions);
134
- if (redactions.length > 0 || rejectedKeys.length > 0 || !publicSafe || !promptKind || !targetKind || !targetRef || !runtimeId) {
135
- const modelRejected = redactions.some((item) => item.field === 'modelId');
136
- const promptRejected = redactions.some((item) => item.reason === 'prompt_body');
137
- return rejectAdapterInput(modelRejected
138
- ? HEADLESS_REASON_CODES.MODEL_REJECTED
139
- : promptRejected
140
- ? HEADLESS_REASON_CODES.PROMPT_REJECTED
141
- : HEADLESS_REASON_CODES.DIRECTIVE_REJECTED, promptRejected
142
- ? 'Headless adapter target did not match a public prompt shape.'
143
- : 'Headless adapter input failed public-safety validation.', redactions);
144
- }
145
- const normalized = {
146
- promptKind: promptKind,
147
- targetKind: targetKind,
148
- targetRef,
149
- ...(storyId ? { storyId } : {}),
150
- ...(epicId ? { epicId } : {}),
151
- runtimeId: runtimeId,
152
- ...(modelId ? { modelId } : {}),
153
- ...(runtimeSource ? { runtimeSource } : {}),
154
- ...(timeoutMs ? { timeoutMs } : {}),
155
- ...(receipt ? { receipt } : {}),
156
- ...(publicSummary ? { publicSummary } : {}),
157
- publicSafe: true,
158
- };
159
- const prompt = renderHeadlessPrompt(normalized);
160
- return {
161
- ok: true,
162
- input: normalized,
163
- prompt,
164
- promptHash: hashPublicValue(prompt),
165
- reasonCodes: [HEADLESS_REASON_CODES.OK],
166
- publicSafe: true,
167
- };
168
- }
169
- export function renderHeadlessPrompt(input) {
170
- if (input.promptKind === 'yolo')
171
- return `*yolo @${input.targetRef}`;
172
- if (input.promptKind === 'yolo-branchless-preparation')
173
- return `*yolo @${input.targetRef} branchless-preparation`;
174
- return `*yoloop @${input.targetRef}`;
175
- }
176
- export function hashPublicValue(value) {
177
- return `sha256:${createHash('sha256').update(value).digest('hex')}`;
178
- }
179
- export function createRejectedExecutionResult(adapterId, runtimeId, rejected, durationMs = 0) {
180
- return {
181
- status: 'failed',
182
- adapterId,
183
- runtimeId,
184
- reasonCode: rejected.reasonCode,
185
- reasonCodes: rejected.reasonCodes,
186
- durationMs,
187
- counts: {},
188
- hashes: {},
189
- publicSummary: boundPublicSummary(rejected.publicSummary),
190
- redactionSummary: rejected.redactionSummary,
191
- relativePaths: [],
192
- publicSafe: true,
193
- };
194
- }
195
- export function createUnavailableExecutionResult(adapterId, input, availability, durationMs = 0) {
196
- return {
197
- status: 'failed',
198
- adapterId,
199
- runtimeId: input.runtimeId,
200
- ...(input.modelId ? { modelId: input.modelId } : {}),
201
- ...(input.runtimeSource ? { runtimeSource: input.runtimeSource } : {}),
202
- reasonCode: availability.reasonCode,
203
- reasonCodes: availability.reasonCodes,
204
- durationMs,
205
- counts: {},
206
- hashes: { prompt: hashPublicValue(renderHeadlessPrompt(input)) },
207
- publicSummary: boundPublicSummary(availability.publicSummary),
208
- redactionSummary: availability.redactionSummary,
209
- relativePaths: [input.targetRef],
210
- ...(input.receipt ? { receipt: input.receipt } : {}),
211
- publicSafe: true,
212
- };
213
- }
214
- export function normalizeHeadlessCommandResult(adapterId, input, commandResult) {
215
- const prompt = renderHeadlessPrompt(input);
216
- const stdoutHash = hashPublicValue(commandResult.stdout);
217
- const stderrHash = hashPublicValue(commandResult.stderr);
218
- const authEvidenceMatches = commandResult.timedOut || commandResult.exitCode === 0
219
- ? 0
220
- : countHeadlessAuthEvidenceMatches(commandResult.stdout, commandResult.stderr);
221
- const status = commandResult.cancelled
222
- ? 'failed'
223
- : commandResult.timedOut
224
- ? 'timed_out'
225
- : commandResult.exitCode === 0
226
- ? 'completed'
227
- : 'failed';
228
- const reasonCode = commandResult.cancelled
229
- ? HEADLESS_REASON_CODES.EXECUTION_CANCELLED
230
- : commandResult.timedOut
231
- ? HEADLESS_REASON_CODES.EXECUTION_TIMEOUT
232
- : commandResult.exitCode === 0
233
- ? HEADLESS_REASON_CODES.EXECUTION_COMPLETED
234
- : authEvidenceMatches > 0
235
- ? HEADLESS_REASON_CODES.RUNTIME_AUTH_REQUIRED
236
- : HEADLESS_REASON_CODES.EXECUTION_FAILED;
237
- const redactionSummary = [
238
- redaction('prompt', 'prompt_body', hashPublicValue(prompt)),
239
- ];
240
- if (commandResult.stdoutBytes > 0)
241
- redactionSummary.push(redaction('stdout', 'raw_log', stdoutHash));
242
- if (commandResult.stderrBytes > 0)
243
- redactionSummary.push(redaction('stderr', 'raw_log', stderrHash));
244
- return {
245
- status,
246
- adapterId,
247
- runtimeId: input.runtimeId,
248
- ...(input.modelId ? { modelId: input.modelId } : {}),
249
- ...(input.runtimeSource ? { runtimeSource: input.runtimeSource } : {}),
250
- reasonCode,
251
- reasonCodes: [reasonCode, HEADLESS_REASON_CODES.RECEIPT_REDACTED],
252
- exitCode: commandResult.exitCode,
253
- signal: commandResult.signal ?? null,
254
- durationMs: commandResult.durationMs,
255
- counts: {
256
- stdoutBytes: commandResult.stdoutBytes,
257
- stderrBytes: commandResult.stderrBytes,
258
- stdoutLines: countLines(commandResult.stdout),
259
- stderrLines: countLines(commandResult.stderr),
260
- ...(authEvidenceMatches > 0 ? { authEvidenceMatches } : {}),
261
- },
262
- hashes: {
263
- prompt: hashPublicValue(prompt),
264
- stdout: stdoutHash,
265
- stderr: stderrHash,
266
- },
267
- publicSummary: status === 'completed'
268
- ? 'Headless adapter completed with public-safe redacted output summary.'
269
- : reasonCode === HEADLESS_REASON_CODES.EXECUTION_CANCELLED
270
- ? 'Headless adapter was cancelled; raw output was redacted.'
271
- : status === 'timed_out'
272
- ? 'Headless adapter timed out; raw output was redacted.'
273
- : reasonCode === HEADLESS_REASON_CODES.RUNTIME_AUTH_REQUIRED
274
- ? 'Headless adapter requires local runtime authentication; raw output was redacted.'
275
- : 'Headless adapter failed; raw output was redacted.',
276
- redactionSummary,
277
- relativePaths: [input.targetRef],
278
- ...(input.receipt ? { receipt: input.receipt } : {}),
279
- publicSafe: true,
280
- };
281
- }
282
- export async function runHeadlessCommand(command, args, options = {}) {
283
- const startedAt = Date.now();
284
- const timeoutMs = normalizeRunnerTimeout(options.timeoutMs);
285
- const maxOutputBytes = options.maxOutputBytes ?? 64_000;
286
- if (options.signal?.aborted) {
287
- return {
288
- exitCode: null,
289
- signal: 'SIGTERM',
290
- timedOut: false,
291
- cancelled: true,
292
- durationMs: Date.now() - startedAt,
293
- stdout: '',
294
- stderr: '',
295
- stdoutBytes: 0,
296
- stderrBytes: 0,
297
- };
298
- }
299
- return await new Promise((resolve) => {
300
- const child = spawn(command, [...args], {
301
- cwd: options.cwd,
302
- env: options.env,
303
- shell: false,
304
- stdio: [options.localConsole ? 'pipe' : 'ignore', 'pipe', 'pipe'],
305
- });
306
- const localConsole = options.localConsole?.jobId
307
- ? createLocalJobConsoleServer({
308
- ...options.localConsole,
309
- projectRoot: options.localConsole.projectRoot ?? options.cwd,
310
- writeStdin: (chunk) => {
311
- child.stdin?.write(chunk);
312
- },
313
- signalProcess: (signal) => child.kill(signal),
314
- })
315
- : undefined;
316
- void localConsole?.start();
317
- let stdout = '';
318
- let stderr = '';
319
- let stdoutBytes = 0;
320
- let stderrBytes = 0;
321
- let settled = false;
322
- let timedOut = false;
323
- let cancelled = false;
324
- const abort = () => {
325
- if (settled)
326
- return;
327
- cancelled = true;
328
- child.kill('SIGTERM');
329
- };
330
- options.signal?.addEventListener('abort', abort, { once: true });
331
- const cleanup = () => {
332
- options.signal?.removeEventListener('abort', abort);
333
- };
334
- const append = (current, chunk, previousBytes) => {
335
- const bytes = previousBytes + chunk.length;
336
- if (current.length < maxOutputBytes) {
337
- const remaining = maxOutputBytes - current.length;
338
- return { text: current + chunk.toString('utf8').slice(0, remaining), bytes };
339
- }
340
- return { text: current, bytes };
341
- };
342
- child.stdout?.on('data', (chunk) => {
343
- const next = append(stdout, chunk, stdoutBytes);
344
- stdout = next.text;
345
- stdoutBytes = next.bytes;
346
- localConsole?.broadcastStdout(chunk);
347
- });
348
- child.stderr?.on('data', (chunk) => {
349
- const next = append(stderr, chunk, stderrBytes);
350
- stderr = next.text;
351
- stderrBytes = next.bytes;
352
- localConsole?.broadcastStderr(chunk);
353
- });
354
- const timer = setTimeout(() => {
355
- timedOut = true;
356
- child.kill('SIGTERM');
357
- }, timeoutMs);
358
- child.on('error', (error) => {
359
- if (settled)
360
- return;
361
- settled = true;
362
- clearTimeout(timer);
363
- cleanup();
364
- localConsole?.close({ exitCode: 127, signal: null });
365
- const safeMessage = error instanceof Error ? error.message : String(error);
366
- resolve({
367
- exitCode: 127,
368
- signal: null,
369
- timedOut: false,
370
- cancelled,
371
- durationMs: Date.now() - startedAt,
372
- stdout,
373
- stderr: safeMessage,
374
- stdoutBytes,
375
- stderrBytes: Buffer.byteLength(safeMessage),
376
- });
377
- });
378
- child.on('close', (exitCode, signal) => {
379
- if (settled)
380
- return;
381
- settled = true;
382
- clearTimeout(timer);
383
- cleanup();
384
- localConsole?.close({ exitCode, signal });
385
- resolve({
386
- exitCode,
387
- signal,
388
- timedOut,
389
- cancelled,
390
- durationMs: Date.now() - startedAt,
391
- stdout,
392
- stderr,
393
- stdoutBytes,
394
- stderrBytes,
395
- });
396
- });
397
- });
398
- }
399
- export function adapterAvailabilityFailure(adapterId, commandName, reasonCode, publicSummary, redactionSummary = []) {
400
- return {
401
- ok: false,
402
- adapterId,
403
- ...(commandName ? { commandName } : {}),
404
- reasonCode,
405
- reasonCodes: [reasonCode],
406
- publicSummary: boundPublicSummary(publicSummary),
407
- redactionSummary,
408
- publicSafe: true,
409
- };
410
- }
411
- export function adapterAvailabilitySuccess(adapterId, commandName, publicSummary, details = {}) {
412
- const result = {
413
- ok: true,
414
- adapterId,
415
- commandName,
416
- ...(details.versionText ? { versionHash: hashPublicValue(details.versionText) } : {}),
417
- reasonCodes: [HEADLESS_REASON_CODES.OK],
418
- publicSummary: boundPublicSummary(publicSummary),
419
- publicSafe: true,
420
- };
421
- if (details.executablePath) {
422
- Object.defineProperty(result, 'executablePath', {
423
- value: details.executablePath,
424
- enumerable: false,
425
- configurable: false,
426
- });
427
- }
428
- return result;
429
- }
430
- export function redaction(field, reason, evidence) {
431
- return { field, reason, evidence, publicSafe: true };
432
- }
433
- export function boundPublicSummary(value) {
434
- return value.length <= HEADLESS_PUBLIC_SUMMARY_MAX_CHARS
435
- ? value
436
- : `${value.slice(0, HEADLESS_PUBLIC_SUMMARY_MAX_CHARS)}…[TRUNCATED:${value.length - HEADLESS_PUBLIC_SUMMARY_MAX_CHARS}]`;
437
- }
438
- export function isSafeHeadlessModelId(value) {
439
- return value.length <= HEADLESS_MODEL_ID_MAX_CHARS
440
- && MODEL_ID_PATTERN.test(value)
441
- && !UNSAFE_VALUE_PATTERN.test(value)
442
- && !SHELL_FRAGMENT_PATTERN.test(value)
443
- && !value.includes('..')
444
- && !value.startsWith('/');
445
- }
446
- function rejectAdapterInput(reasonCode, publicSummary, redactions) {
447
- return {
448
- ok: false,
449
- reasonCode,
450
- reasonCodes: [reasonCode],
451
- publicSummary: boundPublicSummary(publicSummary),
452
- redactionSummary: redactions,
453
- publicSafe: true,
454
- };
455
- }
456
- function optionalSafeString(value, field, redactions) {
457
- if (value === undefined)
458
- return undefined;
459
- const text = stringValue(value);
460
- if (!text || !isSafePublicText(text) || SHELL_FRAGMENT_PATTERN.test(text)) {
461
- redactions.push(redaction(field, unsafeKeyReason(field), 'value-denied'));
462
- return undefined;
463
- }
464
- return text;
465
- }
466
- function optionalSafeModelId(value, redactions) {
467
- if (value === undefined)
468
- return undefined;
469
- const modelId = stringValue(value);
470
- if (!modelId || !isSafeHeadlessModelId(modelId)) {
471
- redactions.push(redaction('modelId', 'unsafe_key', 'value-denied'));
472
- return undefined;
473
- }
474
- return modelId;
475
- }
476
- function optionalRuntimeSource(value, redactions) {
477
- if (value === undefined)
478
- return undefined;
479
- if (value === 'explicit' || value === 'origin' || value === 'default' || value === 'fallback')
480
- return value;
481
- redactions.push(redaction('runtimeSource', 'unsafe_key', 'value-denied'));
482
- return undefined;
483
- }
484
- function normalizeTimeout(value, redactions) {
485
- if (value === undefined)
486
- return undefined;
487
- if (typeof value !== 'number' || !Number.isInteger(value) || value <= 0 || value > MAX_TIMEOUT_MS) {
488
- redactions.push(redaction('timeoutMs', 'unbounded_number', 'value-denied'));
489
- return undefined;
490
- }
491
- return value;
492
- }
493
- function normalizeRunnerTimeout(value) {
494
- if (!value || !Number.isInteger(value) || value <= 0 || value > MAX_TIMEOUT_MS)
495
- return DEFAULT_TIMEOUT_MS;
496
- return value;
497
- }
498
- function optionalPublicSummary(value, redactions) {
499
- if (value === undefined)
500
- return undefined;
501
- const text = stringValue(value);
502
- if (!text || text.length > HEADLESS_PUBLIC_SUMMARY_MAX_CHARS || !isSafePublicText(text)) {
503
- redactions.push(redaction('publicSummary', 'unbounded_text', 'value-denied'));
504
- return undefined;
505
- }
506
- return text;
507
- }
508
- function validateReceipt(value, redactions) {
509
- if (value === undefined)
510
- return undefined;
511
- if (!isRecord(value)) {
512
- redactions.push(redaction('receipt', 'unsafe_key', 'value-denied'));
513
- return undefined;
514
- }
515
- const receipt = {};
516
- for (const [key, child] of Object.entries(value)) {
517
- if (!RECEIPT_ALLOWED_KEYS.has(key) || UNSAFE_KEY_PATTERN.test(key)) {
518
- redactions.push(redaction(`receipt.${key}`, unsafeKeyReason(key), 'key-denied'));
519
- continue;
520
- }
521
- const text = optionalSafeString(child, `receipt.${key}`, redactions);
522
- if (text)
523
- receipt[key] = text;
524
- }
525
- return Object.keys(receipt).length > 0 ? receipt : undefined;
526
- }
527
- function unsafeKeyReason(key) {
528
- if (/prompt/i.test(key))
529
- return 'prompt_body';
530
- if (/std(?:out|err)|raw|log|transcript|stack/i.test(key))
531
- return 'raw_log';
532
- if (/url/i.test(key))
533
- return 'private_url';
534
- if (/path|cwd|argv|args|shell|command|binary|executable/i.test(key))
535
- return 'executable_path';
536
- if (/secret|token|password|authorization|api[_-]?key|license/i.test(key))
537
- return 'secret_or_pii';
538
- return 'unsafe_key';
539
- }
540
- function stringValue(value) {
541
- return typeof value === 'string' ? value : undefined;
542
- }
543
- function isSafePublicText(value) {
544
- return value.length > 0 && !UNSAFE_VALUE_PATTERN.test(value) && !/\0/.test(value);
545
- }
546
- function countLines(value) {
547
- if (!value)
548
- return 0;
549
- return value.split(/\r?\n/).filter((line) => line.length > 0).length;
550
- }
551
- const HEADLESS_AUTH_EVIDENCE_PATTERNS = Object.freeze([
552
- /\bauth(?:entication|orization)?\s+(?:is\s+)?required\b/i,
553
- /\brequires?\s+authentication\b/i,
554
- /\bmust\s+(?:log\s?in|authenticate|be\s+authenticated)\b/i,
555
- /\bunauthenticated\b/i,
556
- /\b(?:not|unauthenticated)\s+(?:logged\s+in|authenticated)\b/i,
557
- /\blog\s?in\s+(?:required|to\s+continue|before\s+continuing)\b/i,
558
- /\bplease\s+(?:log\s?in|authenticate|sign\s?in)\b/i,
559
- /\bsign\s?in\s+(?:required|to\s+continue|before\s+continuing)\b/i,
560
- /\bsession\s+(?:expired|not\s+found|invalid)\b/i,
561
- /\bcredentials?\s+(?:missing|required|not\s+found)\b/i,
562
- ]);
563
- function countHeadlessAuthEvidenceMatches(...values) {
564
- const bounded = values
565
- .filter((value) => value.length > 0)
566
- .map((value) => value.slice(0, 8_000))
567
- .join('\n');
568
- if (!bounded)
569
- return 0;
570
- return HEADLESS_AUTH_EVIDENCE_PATTERNS.reduce((count, pattern) => count + (pattern.test(bounded) ? 1 : 0), 0);
571
- }
572
- function isRecord(value) {
573
- return typeof value === 'object' && value !== null && !Array.isArray(value);
574
- }
1
+ import{createHash as v}from"node:crypto";import{spawn as V}from"node:child_process";import{P205_RELEASE_GATE_BUDGETS as z,P205_ROOT_INVOKE_TIMEOUT_MS as F}from"../../../../shared/dist/yoloop/epic-terminal-git.js";import{createLocalJobConsoleServer as $}from"../local-console.js";const X=Object.freeze(["fake","test","opencode","claude-code"]),l=Object.freeze({OK:"continuity-ok",RUNTIME_EXPLICIT:"headless-runtime-explicit",RUNTIME_ORIGIN:"headless-runtime-origin",RUNTIME_DEFAULT:"headless-runtime-default",RUNTIME_FALLBACK:"headless-runtime-fallback",RUNTIME_UNRESOLVED:"headless-runtime-unresolved",RUNTIME_UNTRUSTED:"headless-runtime-untrusted",MODEL_REJECTED:"headless-model-rejected",DIRECTIVE_REJECTED:"headless-directive-rejected",PROMPT_REJECTED:"headless-prompt-rejected",ADAPTER_UNAVAILABLE:"headless-adapter-unavailable",RUNTIME_AUTH_REQUIRED:"headless-runtime-auth-required",MANAGED_PROFILE_MISSING:"headless-managed-profile-missing",MANAGED_PROFILE_INVALID:"headless-managed-profile-invalid",APPROVAL_POLICY_INVALID:"headless-approval-policy-invalid",APPROVAL_POLICY_MISMATCH:"headless-approval-policy-mismatch",EXECUTION_CANCELLED:"headless-execution-cancelled",EXECUTION_TIMEOUT:"headless-execution-timeout",EXECUTION_BACKOFF:"headless-execution-backoff",EXECUTION_COMPLETED:"headless-execution-completed",EXECUTION_FAILED:"headless-execution-failed",RECEIPT_REDACTED:"headless-receipt-redacted",YOLOOP_METADATA_INVALID:"headless-yoloop-metadata-invalid",YOLOOP_ISOLATION_VIOLATION:"headless-yoloop-isolation-violation",WORKER_POOL_SERIAL_FALLBACK:"worker-pool-serial-fallback",WORKER_POOL_PARALLEL_ACTIVE:"worker-pool-parallel-active",WORKER_POOL_BACKPRESSURE_PAUSED:"worker-pool-backpressure-paused"}),G=120,C=240,Y=F,U=z.terminalWorkflowMaxDurationMs,J=/^[A-Za-z0-9][A-Za-z0-9._:+/-]{0,119}$/,Z=/^docs\/stories\/[A-Za-z0-9._-]+\.story\.md$/,q=/^docs\/epics\/epic-[A-Za-z0-9._-]+\.md$/,W=/(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,w=/(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)/i,L=/(?:[;&|`$<>]|\$\(|\n|\r|\0)/,Q=new Set(["promptKind","targetKind","targetRef","storyId","epicId","runtimeId","modelId","runtimeSource","timeoutMs","receipt","publicSummary","publicSafe"]),ee=new Set(["executionId","attemptId","jobId","operationId","idempotencyKey","runnerId","subagentId"]);function te(e){return X.includes(e)}function _e(e,r){const t=[],o=[];if(!K(e))return t.push(i("input","unsafe_key","value-denied")),k(l.DIRECTIVE_REJECTED,"Headless adapter input must be a public object.",t);for(const _ of Object.keys(e))Q.has(_)||(o.push(_),t.push(i(_,M(_),"key-denied")));const u=e.publicSafe===!0;u||t.push(i("publicSafe","unsafe_key","value-denied"));const a=h(e.promptKind);a!=="yolo"&&a!=="yolo-branchless-preparation"&&a!=="yoloop"&&t.push(i("promptKind","unsafe_key","value-denied"));const p=h(e.targetKind);p!=="story"&&p!=="epic"&&t.push(i("targetKind","unsafe_key","value-denied"));const s=h(e.targetRef);(!s||!x(s)||L.test(s)||s.includes(".."))&&t.push(i("targetRef","prompt_body","value-denied")),(a==="yolo"||a==="yolo-branchless-preparation")&&(p!=="story"||!s||!Z.test(s))&&t.push(i("targetRef","prompt_body","value-denied")),a==="yoloop"&&(p!=="epic"||!s||!q.test(s))&&t.push(i("targetRef","prompt_body","value-denied"));const d=P(e.storyId,"storyId",t),f=P(e.epicId,"epicId",t);d&&s&&(a==="yolo"||a==="yolo-branchless-preparation")&&d!==s.replace(/^docs\/stories\//,"").replace(/\.story\.md$/,"")&&t.push(i("storyId","prompt_body","value-denied")),f&&s&&a==="yoloop"&&f!==s.replace(/^docs\/epics\/epic-/,"").replace(/\.md$/,"")&&t.push(i("epicId","prompt_body","value-denied"));const E=h(e.runtimeId);(!E||!te(E)||r&&E!==r)&&t.push(i("runtimeId","unsafe_key","value-denied"));const b=oe(e.modelId,t),y=se(e.runtimeSource,t),m=ne(e.timeoutMs,t),T=ae(e.publicSummary,t),S=de(e.receipt,t);if(t.length>0||o.length>0||!u||!a||!p||!s||!E){const _=t.some(n=>n.field==="modelId"),O=t.some(n=>n.reason==="prompt_body");return k(_?l.MODEL_REJECTED:O?l.PROMPT_REJECTED:l.DIRECTIVE_REJECTED,O?"Headless adapter target did not match a public prompt shape.":"Headless adapter input failed public-safety validation.",t)}const A={promptKind:a,targetKind:p,targetRef:s,...d?{storyId:d}:{},...f?{epicId:f}:{},runtimeId:E,...b?{modelId:b}:{},...y?{runtimeSource:y}:{},...m?{timeoutMs:m}:{},...S?{receipt:S}:{},...T?{publicSummary:T}:{},publicSafe:!0},R=D(A);return{ok:!0,input:A,prompt:R,promptHash:I(R),reasonCodes:[l.OK],publicSafe:!0}}function D(e){return e.promptKind==="yolo"?`*yolo @${e.targetRef}`:e.promptKind==="yolo-branchless-preparation"?`*yolo @${e.targetRef} branchless-preparation`:`*yoloop @${e.targetRef}`}function I(e){return`sha256:${v("sha256").update(e).digest("hex")}`}function me(e,r,t,o=0){return{status:"failed",adapterId:e,runtimeId:r,reasonCode:t.reasonCode,reasonCodes:t.reasonCodes,durationMs:o,counts:{},hashes:{},publicSummary:g(t.publicSummary),redactionSummary:t.redactionSummary,relativePaths:[],publicSafe:!0}}function be(e,r,t,o=0){return{status:"failed",adapterId:e,runtimeId:r.runtimeId,...r.modelId?{modelId:r.modelId}:{},...r.runtimeSource?{runtimeSource:r.runtimeSource}:{},reasonCode:t.reasonCode,reasonCodes:t.reasonCodes,durationMs:o,counts:{},hashes:{prompt:I(D(r))},publicSummary:g(t.publicSummary),redactionSummary:t.redactionSummary,relativePaths:[r.targetRef],...r.receipt?{receipt:r.receipt}:{},publicSafe:!0}}function Ie(e,r,t){const o=D(r),u=I(t.stdout),a=I(t.stderr),p=t.timedOut||t.exitCode===0?0:ce(t.stdout,t.stderr),s=t.cancelled?"failed":t.timedOut?"timed_out":t.exitCode===0?"completed":"failed",d=t.cancelled?l.EXECUTION_CANCELLED:t.timedOut?l.EXECUTION_TIMEOUT:t.exitCode===0?l.EXECUTION_COMPLETED:p>0?l.RUNTIME_AUTH_REQUIRED:l.EXECUTION_FAILED,f=[i("prompt","prompt_body",I(o))];return t.stdoutBytes>0&&f.push(i("stdout","raw_log",u)),t.stderrBytes>0&&f.push(i("stderr","raw_log",a)),{status:s,adapterId:e,runtimeId:r.runtimeId,...r.modelId?{modelId:r.modelId}:{},...r.runtimeSource?{runtimeSource:r.runtimeSource}:{},reasonCode:d,reasonCodes:[d,l.RECEIPT_REDACTED],exitCode:t.exitCode,signal:t.signal??null,durationMs:t.durationMs,counts:{stdoutBytes:t.stdoutBytes,stderrBytes:t.stderrBytes,stdoutLines:H(t.stdout),stderrLines:H(t.stderr),...p>0?{authEvidenceMatches:p}:{}},hashes:{prompt:I(o),stdout:u,stderr:a},publicSummary:s==="completed"?"Headless adapter completed with public-safe redacted output summary.":d===l.EXECUTION_CANCELLED?"Headless adapter was cancelled; raw output was redacted.":s==="timed_out"?"Headless adapter timed out; raw output was redacted.":d===l.RUNTIME_AUTH_REQUIRED?"Headless adapter requires local runtime authentication; raw output was redacted.":"Headless adapter failed; raw output was redacted.",redactionSummary:f,relativePaths:[r.targetRef],...r.receipt?{receipt:r.receipt}:{},publicSafe:!0}}async function he(e,r,t={}){const o=Date.now(),u=ie(t.timeoutMs),a=t.maxOutputBytes??64e3;return t.signal?.aborted?{exitCode:null,signal:"SIGTERM",timedOut:!1,cancelled:!0,durationMs:Date.now()-o,stdout:"",stderr:"",stdoutBytes:0,stderrBytes:0}:await new Promise(p=>{const s=V(e,[...r],{cwd:t.cwd,env:t.env,shell:!1,stdio:[t.localConsole?"pipe":"ignore","pipe","pipe"]}),d=t.localConsole?.jobId?$({...t.localConsole,projectRoot:t.localConsole.projectRoot??t.cwd,writeStdin:n=>{s.stdin?.write(n)},signalProcess:n=>s.kill(n)}):void 0;d?.start();let f="",E="",b=0,y=0,m=!1,T=!1,S=!1;const A=()=>{m||(S=!0,s.kill("SIGTERM"))};t.signal?.addEventListener("abort",A,{once:!0});const R=()=>{t.signal?.removeEventListener("abort",A)},_=(n,c,B)=>{const N=B+c.length;if(n.length<a){const j=a-n.length;return{text:n+c.toString("utf8").slice(0,j),bytes:N}}return{text:n,bytes:N}};s.stdout?.on("data",n=>{const c=_(f,n,b);f=c.text,b=c.bytes,d?.broadcastStdout(n)}),s.stderr?.on("data",n=>{const c=_(E,n,y);E=c.text,y=c.bytes,d?.broadcastStderr(n)});const O=setTimeout(()=>{T=!0,s.kill("SIGTERM")},u);s.on("error",n=>{if(m)return;m=!0,clearTimeout(O),R(),d?.close({exitCode:127,signal:null});const c=n instanceof Error?n.message:String(n);p({exitCode:127,signal:null,timedOut:!1,cancelled:S,durationMs:Date.now()-o,stdout:f,stderr:c,stdoutBytes:b,stderrBytes:Buffer.byteLength(c)})}),s.on("close",(n,c)=>{m||(m=!0,clearTimeout(O),R(),d?.close({exitCode:n,signal:c}),p({exitCode:n,signal:c,timedOut:T,cancelled:S,durationMs:Date.now()-o,stdout:f,stderr:E,stdoutBytes:b,stderrBytes:y}))})})}function ye(e,r,t,o,u=[]){return{ok:!1,adapterId:e,...r?{commandName:r}:{},reasonCode:t,reasonCodes:[t],publicSummary:g(o),redactionSummary:u,publicSafe:!0}}function Se(e,r,t,o={}){const u={ok:!0,adapterId:e,commandName:r,...o.versionText?{versionHash:I(o.versionText)}:{},reasonCodes:[l.OK],publicSummary:g(t),publicSafe:!0};return o.executablePath&&Object.defineProperty(u,"executablePath",{value:o.executablePath,enumerable:!1,configurable:!1}),u}function i(e,r,t){return{field:e,reason:r,evidence:t,publicSafe:!0}}function g(e){return e.length<=C?e:`${e.slice(0,C)}\u2026[TRUNCATED:${e.length-C}]`}function re(e){return e.length<=G&&J.test(e)&&!w.test(e)&&!L.test(e)&&!e.includes("..")&&!e.startsWith("/")}function k(e,r,t){return{ok:!1,reasonCode:e,reasonCodes:[e],publicSummary:g(r),redactionSummary:t,publicSafe:!0}}function P(e,r,t){if(e===void 0)return;const o=h(e);if(!o||!x(o)||L.test(o)){t.push(i(r,M(r),"value-denied"));return}return o}function oe(e,r){if(e===void 0)return;const t=h(e);if(!t||!re(t)){r.push(i("modelId","unsafe_key","value-denied"));return}return t}function se(e,r){if(e!==void 0){if(e==="explicit"||e==="origin"||e==="default"||e==="fallback")return e;r.push(i("runtimeSource","unsafe_key","value-denied"))}}function ne(e,r){if(e!==void 0){if(typeof e!="number"||!Number.isInteger(e)||e<=0||e>U){r.push(i("timeoutMs","unbounded_number","value-denied"));return}return e}}function ie(e){return!e||!Number.isInteger(e)||e<=0||e>U?Y:e}function ae(e,r){if(e===void 0)return;const t=h(e);if(!t||t.length>C||!x(t)){r.push(i("publicSummary","unbounded_text","value-denied"));return}return t}function de(e,r){if(e===void 0)return;if(!K(e)){r.push(i("receipt","unsafe_key","value-denied"));return}const t={};for(const[o,u]of Object.entries(e)){if(!ee.has(o)||W.test(o)){r.push(i(`receipt.${o}`,M(o),"key-denied"));continue}const a=P(u,`receipt.${o}`,r);a&&(t[o]=a)}return Object.keys(t).length>0?t:void 0}function M(e){return/prompt/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 h(e){return typeof e=="string"?e:void 0}function x(e){return e.length>0&&!w.test(e)&&!/\0/.test(e)}function H(e){return e?e.split(/\r?\n/).filter(r=>r.length>0).length:0}const ue=Object.freeze([/\bauth(?:entication|orization)?\s+(?:is\s+)?required\b/i,/\brequires?\s+authentication\b/i,/\bmust\s+(?:log\s?in|authenticate|be\s+authenticated)\b/i,/\bunauthenticated\b/i,/\b(?:not|unauthenticated)\s+(?:logged\s+in|authenticated)\b/i,/\blog\s?in\s+(?:required|to\s+continue|before\s+continuing)\b/i,/\bplease\s+(?:log\s?in|authenticate|sign\s?in)\b/i,/\bsign\s?in\s+(?:required|to\s+continue|before\s+continuing)\b/i,/\bsession\s+(?:expired|not\s+found|invalid)\b/i,/\bcredentials?\s+(?:missing|required|not\s+found)\b/i]);function ce(...e){const r=e.filter(t=>t.length>0).map(t=>t.slice(0,8e3)).join(`
2
+ `);return r?ue.reduce((t,o)=>t+(o.test(r)?1:0),0):0}function K(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}export{X as HEADLESS_ADAPTER_IDS,l as HEADLESS_REASON_CODES,ye as adapterAvailabilityFailure,Se as adapterAvailabilitySuccess,g as boundPublicSummary,me as createRejectedExecutionResult,be as createUnavailableExecutionResult,I as hashPublicValue,te as isHeadlessAdapterId,re as isSafeHeadlessModelId,Ie as normalizeHeadlessCommandResult,i as redaction,D as renderHeadlessPrompt,he as runHeadlessCommand,_e as validateHeadlessAdapterExecutionInput};