@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,1487 +1 @@
1
- /**
2
- * @license FSL-1.1
3
- * Copyright (c) 2026 OrNexus AI
4
- *
5
- * P192.02 -- outbound Portal sync worker for runner heartbeat, jobs sync and
6
- * pending command acknowledgements.
7
- */
8
- import { createHash } from 'node:crypto';
9
- import { resolve } from 'node:path';
10
- import { DEFAULT_SERVER_URL } from '../constants.js';
11
- import { loadSecureConfig } from '../config/secure-config.js';
12
- import { LicenseClient } from '../license/license-client.js';
13
- import { CLIENT_VERSION } from '../version.js';
14
- import { deriveProjectIdentity } from './project-identity.js';
15
- import { CONTINUITY_CLIENT_CONTRACT_VERSION, CONTINUITY_CLIENT_PORTAL_SYNC_ENVELOPE_VERSION, CONTINUITY_CLIENT_SCHEMA_VERSION, ContinuityClientStateStore, } from '../continuity/continuity-client-state-store.js';
16
- import { isContinuityPublicStage, normalizeContinuityStageIteration, openContinuitySqliteStore, sanitizeContinuityStageHistory, } from '../continuity/sqlite-store.js';
17
- export const RUNNER_PORTAL_SYNC_REASON_CODES = Object.freeze({
18
- OK: 'continuity-ok',
19
- AUTH_TOKEN_PERMISSION_FAILURE: 'auth-token-permission-failure',
20
- BACKOFF_SCHEDULED: 'backoff-scheduled',
21
- COMMAND_EXPIRED: 'command-expired',
22
- IDEMPOTENCY_REPLAY: 'idempotency-replay',
23
- INVALID_STATE_TRANSITION: 'invalid-state-transition',
24
- JOB_CANCELLED: 'job-cancelled',
25
- PORTAL_COMMAND_LOCAL_AUDIT_RECORDED: 'portal-command-local-audit-recorded',
26
- PORTAL_COMMAND_PAYLOAD_REJECTED: 'portal-command-payload-rejected',
27
- PORTAL_SYNC_PAYLOAD_REJECTED: 'portal-sync-payload-rejected',
28
- RUNNER_DIRECTIVE_UNTRUSTED: 'runner-directive-untrusted',
29
- SQLITE_ADAPTER_UNAVAILABLE: 'sqlite-adapter-unavailable',
30
- SQLITE_INTEGRITY_FAILED: 'sqlite-integrity-failed',
31
- UNSAFE_FIELD_REJECTED: 'unsafe-field-rejected',
32
- WAITING_HUMAN: 'waiting-human',
33
- });
34
- const REVIEW_GATE_DECISION_OPTIONS = new Set(['approve', 'deny', 'hold']);
35
- const REVIEW_GATE_DECISION_ALLOWED_KEYS = new Set(['option', 'decisionId', 'gateId', 'publicSafe']);
36
- export const DEFAULT_RUNNER_HEARTBEAT_INTERVAL_MS = 60_000;
37
- export const DEFAULT_RUNNER_HEARTBEAT_BACKOFF_MS = 30_000;
38
- export const DEFAULT_RUNNER_HEARTBEAT_TIMEOUT_MS = 10_000;
39
- export const DEFAULT_RUNNER_HEARTBEAT_JITTER_RATIO = 0.2;
40
- const PORTAL_PROCESS_SESSION_SEED = `${Date.now()}:${Math.random().toString(16).slice(2)}`;
41
- const COMMAND_ACTIONS = new Set(['pause', 'resume', 'cancel', 'run_once', 'retry', 'snapshot', 'approve_review_gate', 'deny_review_gate', 'answer_decision']);
42
- const COMMAND_ALLOWED_KEYS = new Set([
43
- 'commandId',
44
- 'jobId',
45
- 'action',
46
- 'decision',
47
- 'status',
48
- 'queuedAt',
49
- 'expiresAt',
50
- 'acknowledgedAt',
51
- 'idempotencyKey',
52
- 'delivery',
53
- 'workspaceId',
54
- 'workspaceLabel',
55
- 'runnerId',
56
- 'projectId',
57
- 'projectLabel',
58
- 'reasonCode',
59
- 'publicSafe',
60
- ]);
61
- const SAFE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/;
62
- const SAFE_RUNNER_ID_PATTERN = /^runner-[A-Za-z0-9._-]{1,80}$/;
63
- const SAFE_JOB_ID_PATTERN = /^(?:job|goal|loop|runner)-[A-Za-z0-9._-]{1,80}$/;
64
- const SAFE_COMMAND_ID_PATTERN = /^pcmd-[a-f0-9]{8,64}$/i;
65
- const SAFE_REASON_CODE_PATTERN = /^[a-z0-9][a-z0-9-]{1,80}$/;
66
- const UNSAFE_KEY_PATTERN = /(raw[_-]?(?:logs?|payloads?)|std(?:out|err)|stack(?:[_-]?trace)?|transcript|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;
67
- 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|P180[_-]?SYNTHETIC[_-]?CONTINUITY|P185[_-]?SYNTHETIC[_-]?CONTINUITY|P187[_-]?SYNTHETIC[_-]?(?:CONTINUITY|RUNNER|WATCH)|P190[_-]?SYNTHETIC[_-]?(?:HEADLESS|CONTINUITY)|P192[_-]?SYNTHETIC[_-]?(?:PORTAL|RUNNER|SYNC))/i;
68
- const UNSAFE_LABEL_PATTERN = /(?:[;&|`$<>]|\$\(|\n|\r|\0|(?:^|\s)(?:bash|sh|zsh|fish|cmd\.exe|powershell|pwsh|npm|pnpm|yarn|node|python|ruby|go|cargo|sudo|chmod|curl|wget)\s+(?:-c|run|exec|install|test|build|[A-Za-z0-9_./:-]+))/i;
69
- export async function runRunnerPortalHeartbeat(options = {}) {
70
- const projectRoot = resolve(options.projectRoot ?? process.cwd());
71
- const now = options.now ?? (() => new Date().toISOString());
72
- const generatedAt = now();
73
- const runnerId = sanitizeRunnerId(options.runnerId ?? defaultPortalRunnerId(projectRoot));
74
- const sessionId = sanitizeSessionId(options.sessionId) ?? defaultPortalSessionId(projectRoot);
75
- const identity = resolveRunnerPortalIdentity(projectRoot, options);
76
- const { workspaceId, workspaceLabel, projectId, projectLabel } = identity;
77
- const mode = options.mode ?? 'background';
78
- const reasonCodes = [];
79
- const redactionEvidence = [];
80
- const posted = { heartbeat: false };
81
- let store;
82
- try {
83
- store = await openContinuitySqliteStore({
84
- projectRoot,
85
- adapter: options.adapter,
86
- adapterLoader: options.adapterLoader,
87
- now,
88
- });
89
- const clientStateStore = new ContinuityClientStateStore(store, now, deriveProjectIdentity(projectRoot));
90
- const snapshot = clientStateStore.collectSnapshot({
91
- nowIso: generatedAt,
92
- jobLimit: boundedInteger(options.jobLimit ?? 20, 1, 50),
93
- dueJobLimit: 20,
94
- eventLimit: 1,
95
- receiptLimit: 1,
96
- staleLeaseLimit: 20,
97
- processingSummaryLimit: 1,
98
- snapshotLimit: 1,
99
- });
100
- const authToken = options.httpClient ? options.authToken : await resolveAuthToken(options);
101
- const http = options.httpClient ?? defaultPortalHttpClient(resolveServerUrl(options), authToken);
102
- const headers = buildPortalHeaders(options.clientVersion ?? CLIENT_VERSION, authToken);
103
- const heartbeatBody = buildHeartbeatPayload(snapshot, {
104
- runnerId,
105
- sessionId,
106
- identity,
107
- generatedAt,
108
- schedulerState: options.schedulerState ?? 'unknown',
109
- clientVersion: options.clientVersion ?? CLIENT_VERSION,
110
- });
111
- const heartbeatResult = await safeHttp(http, {
112
- method: 'POST',
113
- path: '/api/v1/continuity/runner/heartbeat',
114
- body: heartbeatBody,
115
- headers,
116
- }, { timeoutMs: options.timeoutMs ?? options.heartbeatTimeoutMs ?? DEFAULT_RUNNER_HEARTBEAT_TIMEOUT_MS });
117
- if (heartbeatResult.ok)
118
- posted.heartbeat = true;
119
- else
120
- reasonCodes.push(heartbeatResult.reasonCode);
121
- const counts = heartbeatCounts(snapshot, redactionEvidence.length);
122
- return {
123
- ok: posted.heartbeat,
124
- runnerId,
125
- sessionId,
126
- workspaceId,
127
- workspaceLabel,
128
- projectId,
129
- projectLabel,
130
- mode,
131
- generatedAt,
132
- serverAccessToLocalhost: false,
133
- serverHeldStream: false,
134
- localhostCallback: false,
135
- posted,
136
- counts,
137
- reasonCodes: unique(reasonCodes.length > 0 ? reasonCodes : [RUNNER_PORTAL_SYNC_REASON_CODES.OK]),
138
- redactionEvidence,
139
- publicSafe: true,
140
- };
141
- }
142
- catch (error) {
143
- const reasonCode = classifyPortalSyncError(error);
144
- return {
145
- ok: false,
146
- runnerId,
147
- sessionId,
148
- workspaceId,
149
- workspaceLabel,
150
- projectId,
151
- projectLabel,
152
- mode,
153
- generatedAt,
154
- serverAccessToLocalhost: false,
155
- serverHeldStream: false,
156
- localhostCallback: false,
157
- posted,
158
- counts: { redactions: redactionEvidence.length },
159
- reasonCodes: [reasonCode],
160
- redactionEvidence,
161
- publicSafe: true,
162
- };
163
- }
164
- finally {
165
- store?.close();
166
- }
167
- }
168
- export async function runRunnerPortalSync(options = {}) {
169
- const projectRoot = resolve(options.projectRoot ?? process.cwd());
170
- const now = options.now ?? (() => new Date().toISOString());
171
- const generatedAt = now();
172
- const runnerId = sanitizeRunnerId(options.runnerId ?? defaultPortalRunnerId(projectRoot));
173
- const sessionId = sanitizeSessionId(options.sessionId) ?? defaultPortalSessionId(projectRoot);
174
- const identity = resolveRunnerPortalIdentity(projectRoot, options);
175
- const { workspaceId, workspaceLabel, projectId, projectLabel } = identity;
176
- const mode = options.mode ?? 'manual';
177
- const reasonCodes = [];
178
- const redactionEvidence = [];
179
- const commandAcks = [];
180
- const posted = { heartbeat: false, runnerSync: false, commandAcks: 0 };
181
- const commandPoll = { polled: 0, applied: 0, alreadyApplied: 0, rejected: 0, expired: 0, failedLocal: 0 };
182
- let store;
183
- try {
184
- store = await openContinuitySqliteStore({
185
- projectRoot,
186
- adapter: options.adapter,
187
- adapterLoader: options.adapterLoader,
188
- now,
189
- });
190
- const retention = store.compactPublicReceiptsAndOutputs({
191
- nowIso: generatedAt,
192
- policy: options.retentionPolicy,
193
- });
194
- const clientStateStore = new ContinuityClientStateStore(store, now, deriveProjectIdentity(projectRoot));
195
- const snapshot = clientStateStore.collectSnapshot({
196
- nowIso: generatedAt,
197
- jobLimit: boundedInteger(options.jobLimit ?? 50, 1, 50),
198
- dueJobLimit: 50,
199
- eventLimit: boundedInteger(options.eventLimit ?? 50, 1, 100),
200
- receiptLimit: boundedInteger(options.receiptLimit ?? 50, 1, 100),
201
- staleLeaseLimit: 20,
202
- processingSummaryLimit: 20,
203
- snapshotLimit: 10,
204
- });
205
- const syncCursor = buildSyncCursor(snapshot, generatedAt);
206
- const http = options.httpClient ?? defaultPortalHttpClient(resolveServerUrl(options), await resolveAuthToken(options));
207
- const headers = buildPortalHeaders(options.clientVersion ?? CLIENT_VERSION, options.httpClient ? options.authToken : await resolveAuthToken(options));
208
- const heartbeatBody = buildHeartbeatPayload(snapshot, { runnerId, sessionId, identity, generatedAt, schedulerState: options.schedulerState ?? 'unknown', clientVersion: options.clientVersion ?? CLIENT_VERSION });
209
- const heartbeatResult = await safeHttp(http, {
210
- method: 'POST',
211
- path: '/api/v1/continuity/runner/heartbeat',
212
- body: heartbeatBody,
213
- headers,
214
- });
215
- if (heartbeatResult.ok)
216
- posted.heartbeat = true;
217
- else
218
- reasonCodes.push(heartbeatResult.reasonCode);
219
- const runnerSyncBody = buildRunnerSyncPayload(snapshot, {
220
- runnerId,
221
- identity,
222
- generatedAt,
223
- previousSyncCursor: options.syncCursor,
224
- nextSyncCursor: syncCursor,
225
- heartbeat: heartbeatBody,
226
- });
227
- const outboxDelivery = enqueueRunnerSyncOutboxDelivery(store, snapshot, {
228
- runnerId,
229
- identity,
230
- generatedAt,
231
- previousSyncCursor: options.syncCursor,
232
- nextSyncCursor: syncCursor,
233
- });
234
- const runnerSyncResult = outboxDelivery.status === 'acked' && outboxDelivery.replay
235
- ? { ok: true, body: { reasonCode: RUNNER_PORTAL_SYNC_REASON_CODES.IDEMPOTENCY_REPLAY, publicSafe: true } }
236
- : outboxDelivery.status === 'conflict' || outboxDelivery.status === 'dead_letter'
237
- ? { ok: false, reasonCode: outboxDelivery.reasonCode ?? RUNNER_PORTAL_SYNC_REASON_CODES.BACKOFF_SCHEDULED }
238
- : await safeHttp(http, {
239
- method: 'POST',
240
- path: '/api/v1/continuity/jobs/sync',
241
- body: runnerSyncBody,
242
- headers,
243
- });
244
- if (runnerSyncResult.ok) {
245
- posted.runnerSync = true;
246
- store.ackOutbox({
247
- outboxId: outboxDelivery.outboxId,
248
- deliveryCursor: outboxDelivery.deliveryCursor,
249
- ackedAt: now(),
250
- reasonCode: RUNNER_PORTAL_SYNC_REASON_CODES.OK,
251
- });
252
- }
253
- else {
254
- reasonCodes.push(runnerSyncResult.reasonCode);
255
- store.failOutboxDelivery({
256
- outboxId: outboxDelivery.outboxId,
257
- deliveryCursor: outboxDelivery.deliveryCursor,
258
- failedAt: now(),
259
- reasonCode: runnerSyncResult.reasonCode,
260
- summary: 'Runner sync delivery failed with a public reason code and will retry or dead-letter by policy.',
261
- policy: { maxAttempts: 3 },
262
- });
263
- }
264
- const commandResponse = await safeHttp(http, {
265
- method: 'GET',
266
- path: '/api/v1/continuity/runner/commands',
267
- query: { runnerId, workspaceId, workspaceLabel, projectId, projectLabel },
268
- headers,
269
- });
270
- if (commandResponse.ok) {
271
- const commands = extractPendingCommands(commandResponse.body).slice(0, boundedInteger(options.commandLimit ?? 20, 1, 20));
272
- commandPoll.polled = commands.length;
273
- for (const rawCommand of commands) {
274
- const ack = await applyAndAcknowledgeCommand({
275
- store,
276
- http,
277
- headers,
278
- rawCommand,
279
- runnerId,
280
- identity,
281
- nowIso: now(),
282
- });
283
- commandAcks.push(ack);
284
- posted.commandAcks += 1;
285
- if (ack.localStatus === 'applied')
286
- commandPoll.applied += 1;
287
- else if (ack.localStatus === 'already_applied')
288
- commandPoll.alreadyApplied += 1;
289
- else if (ack.localStatus === 'rejected')
290
- commandPoll.rejected += 1;
291
- else if (ack.localStatus === 'expired')
292
- commandPoll.expired += 1;
293
- else
294
- commandPoll.failedLocal += 1;
295
- redactionEvidence.push(...ack.redactionEvidence);
296
- reasonCodes.push(ack.reasonCode);
297
- }
298
- }
299
- else {
300
- reasonCodes.push(commandResponse.reasonCode);
301
- }
302
- const counts = {
303
- jobs: snapshot.counts.jobs ?? snapshot.jobs.length,
304
- dueJobs: snapshot.dueJobCount,
305
- receipts: snapshot.counts.receipts ?? snapshot.lastReceipts.length,
306
- events: snapshot.counts.events ?? snapshot.lastEvents.length,
307
- commandsPolled: commandPoll.polled,
308
- commandAcks: posted.commandAcks,
309
- commandApplied: commandPoll.applied,
310
- commandAlreadyApplied: commandPoll.alreadyApplied,
311
- commandRejected: commandPoll.rejected,
312
- commandExpired: commandPoll.expired,
313
- commandFailedLocal: commandPoll.failedLocal,
314
- receiptCompactionSummaries: retention.counts.summariesCreated,
315
- receiptsCompacted: retention.counts.receiptsRemoved,
316
- processingSummariesCompacted: retention.counts.outputsRemoved,
317
- redactions: redactionEvidence.length,
318
- ...queueCounts(snapshot),
319
- };
320
- const finalReasonCodes = unique(reasonCodes.length > 0 ? reasonCodes : [RUNNER_PORTAL_SYNC_REASON_CODES.OK]);
321
- return {
322
- ok: posted.heartbeat && posted.runnerSync && commandPoll.failedLocal === 0,
323
- runnerId,
324
- sessionId,
325
- workspaceId,
326
- workspaceLabel,
327
- projectId,
328
- projectLabel,
329
- mode,
330
- generatedAt,
331
- serverAccessToLocalhost: false,
332
- serverHeldStream: false,
333
- localhostCallback: false,
334
- posted,
335
- commandPoll,
336
- sync: {
337
- ...(options.syncCursor ? { previousSyncCursor: options.syncCursor } : {}),
338
- nextSyncCursor: syncCursor,
339
- counts,
340
- },
341
- commandAcks,
342
- reasonCodes: finalReasonCodes,
343
- redactionEvidence: redactionEvidence.slice(0, 50),
344
- publicSafe: true,
345
- };
346
- }
347
- catch (error) {
348
- const reasonCode = classifyPortalSyncError(error);
349
- return {
350
- ok: false,
351
- runnerId,
352
- sessionId,
353
- workspaceId,
354
- workspaceLabel,
355
- projectId,
356
- projectLabel,
357
- mode,
358
- generatedAt,
359
- serverAccessToLocalhost: false,
360
- serverHeldStream: false,
361
- localhostCallback: false,
362
- posted,
363
- commandPoll,
364
- sync: { nextSyncCursor: `sync-${sha256Hex(generatedAt).slice(0, 24)}`, counts: { commandAcks: 0 } },
365
- commandAcks,
366
- reasonCodes: [reasonCode],
367
- redactionEvidence,
368
- publicSafe: true,
369
- };
370
- }
371
- finally {
372
- store?.close();
373
- }
374
- }
375
- export async function runRunnerPortalSyncLoop(options = {}) {
376
- const maxRuns = boundedInteger(options.maxRuns ?? 1, 1, 10_000);
377
- const intervalMs = boundedInteger(options.intervalMs ?? 60_000, 0, 24 * 60 * 60 * 1000);
378
- const runs = [];
379
- let syncCursor = options.syncCursor;
380
- for (let index = 0; index < maxRuns; index++) {
381
- const run = await runRunnerPortalSync({ ...options, mode: options.mode ?? 'background', syncCursor });
382
- runs.push(run);
383
- syncCursor = run.sync.nextSyncCursor;
384
- if (index < maxRuns - 1 && intervalMs > 0)
385
- await sleep(intervalMs);
386
- }
387
- return {
388
- ok: runs.every((run) => run.ok),
389
- runs,
390
- reasonCodes: unique(runs.flatMap((run) => run.reasonCodes)),
391
- publicSafe: true,
392
- };
393
- }
394
- export async function runRunnerPortalHeartbeatLoop(options = {}) {
395
- const maxRuns = boundedInteger(options.maxRuns ?? 1, 1, 10_000);
396
- const intervalMs = boundedInteger(options.intervalMs ?? DEFAULT_RUNNER_HEARTBEAT_INTERVAL_MS, 0, 24 * 60 * 60 * 1000);
397
- const backoffMs = boundedInteger(options.backoffMs ?? DEFAULT_RUNNER_HEARTBEAT_BACKOFF_MS, 1_000, 30 * 60 * 1000);
398
- const jitterRatio = boundedNumber(options.jitterRatio ?? DEFAULT_RUNNER_HEARTBEAT_JITTER_RATIO, 0, 0.5);
399
- const random = options.random ?? Math.random;
400
- const runs = [];
401
- for (let index = 0; index < maxRuns; index++) {
402
- const run = await runRunnerPortalHeartbeat({ ...options, mode: options.mode ?? 'background' });
403
- runs.push(run);
404
- if (index < maxRuns - 1) {
405
- const baseDelayMs = run.ok ? intervalMs : backoffMs;
406
- const delayMs = jitteredDelayMs(baseDelayMs, jitterRatio, random);
407
- if (delayMs > 0)
408
- await sleep(delayMs);
409
- }
410
- }
411
- return {
412
- ok: runs.every((run) => run.ok),
413
- runs,
414
- reasonCodes: unique(runs.flatMap((run) => run.reasonCodes)),
415
- schedule: { intervalMs, backoffMs, jitterRatio, maxRuns },
416
- publicSafe: true,
417
- };
418
- }
419
- async function applyAndAcknowledgeCommand(input) {
420
- const validation = validatePendingCommand(input.rawCommand);
421
- if (!validation.ok || !validation.command) {
422
- recordRejectedCommandAuditIfPossible(input.store, validation, input.runnerId, input.nowIso);
423
- return postCommandAck(input.http, input.headers, {
424
- commandId: validation.commandId ?? `pcmd-${sha256Hex('invalid-command').slice(0, 16)}`,
425
- jobId: validation.jobId,
426
- action: validation.action,
427
- runnerId: input.runnerId,
428
- identity: input.identity,
429
- idempotencyKey: `invalid:${validation.commandId ?? 'unknown'}`,
430
- localStatus: 'rejected',
431
- remoteStatus: 'rejected',
432
- reasonCode: RUNNER_PORTAL_SYNC_REASON_CODES.PORTAL_COMMAND_PAYLOAD_REJECTED,
433
- publicSummary: 'Runner rejected unsafe Portal command before local application.',
434
- acknowledgedAt: input.nowIso,
435
- redactionEvidence: validation.redactions,
436
- counts: { rejected: 1, redactions: validation.redactions.length },
437
- });
438
- }
439
- const command = validation.command;
440
- const operationId = operationIdForCommand(command.commandId);
441
- const baseAck = {
442
- commandId: command.commandId,
443
- jobId: command.jobId,
444
- action: command.action,
445
- runnerId: input.runnerId,
446
- identity: input.identity,
447
- idempotencyKey: command.idempotencyKey,
448
- acknowledgedAt: input.nowIso,
449
- redactionEvidence: validation.redactions,
450
- };
451
- if (command.expiresAt && Date.parse(command.expiresAt) <= Date.parse(input.nowIso)) {
452
- recordCommandReceiptIfPossible(input.store, command, {
453
- operationId,
454
- status: 'ignored',
455
- reasonCode: RUNNER_PORTAL_SYNC_REASON_CODES.COMMAND_EXPIRED,
456
- createdAt: input.nowIso,
457
- summary: 'Portal command expired before local application.',
458
- redactionEvidence: validation.redactions,
459
- });
460
- return postCommandAck(input.http, input.headers, {
461
- ...baseAck,
462
- localStatus: 'expired',
463
- remoteStatus: 'expired',
464
- reasonCode: RUNNER_PORTAL_SYNC_REASON_CODES.COMMAND_EXPIRED,
465
- publicSummary: 'Runner skipped expired Portal command.',
466
- counts: { expired: 1 },
467
- });
468
- }
469
- if (input.store.hasOperationRef(operationId, command.idempotencyKey)) {
470
- recordCommandReplayAuditIfPossible(input.store, command, operationId, input.runnerId, input.nowIso, validation.redactions);
471
- return postCommandAck(input.http, input.headers, {
472
- ...baseAck,
473
- localStatus: 'already_applied',
474
- remoteStatus: 'applied',
475
- reasonCode: RUNNER_PORTAL_SYNC_REASON_CODES.IDEMPOTENCY_REPLAY,
476
- publicSummary: 'Runner already applied Portal command; duplicate poll was acknowledged without local mutation.',
477
- counts: { alreadyApplied: 1 },
478
- });
479
- }
480
- if (!input.store.jobExists(command.jobId)) {
481
- return postCommandAck(input.http, input.headers, {
482
- ...baseAck,
483
- localStatus: 'failed-local',
484
- remoteStatus: 'rejected',
485
- reasonCode: RUNNER_PORTAL_SYNC_REASON_CODES.INVALID_STATE_TRANSITION,
486
- publicSummary: 'Runner could not find the public job for Portal command application.',
487
- counts: { failedLocal: 1 },
488
- });
489
- }
490
- try {
491
- const appliedReasonCode = reasonCodeForCommand(command);
492
- input.store.runInTransaction(() => {
493
- applyLocalCommand(input.store, command, input.nowIso);
494
- input.store.appendEvent({
495
- eventId: `${operationId}:event`,
496
- jobId: command.jobId,
497
- operationId,
498
- idempotencyKey: command.idempotencyKey,
499
- type: 'portal_command_applied',
500
- summary: `Portal command ${command.action} applied locally by runner.`,
501
- reasonCode: appliedReasonCode,
502
- createdAt: input.nowIso,
503
- metadata: commandPublicMetadata(command, operationId, input.runnerId, 'applied', input.nowIso, validation.redactions, appliedReasonCode),
504
- });
505
- input.store.appendReceipt({
506
- receiptId: `receipt-${operationId}`,
507
- jobId: command.jobId,
508
- operationId,
509
- idempotencyKey: command.idempotencyKey,
510
- status: 'applied',
511
- reasonCode: appliedReasonCode,
512
- appliedOperationIds: [operationId],
513
- createdAt: input.nowIso,
514
- metadata: commandPublicMetadata(command, operationId, input.runnerId, 'applied', input.nowIso, validation.redactions, appliedReasonCode),
515
- });
516
- });
517
- return postCommandAck(input.http, input.headers, {
518
- ...baseAck,
519
- localStatus: 'applied',
520
- remoteStatus: 'applied',
521
- reasonCode: appliedReasonCode,
522
- publicSummary: `Runner applied Portal command ${command.action} locally.`,
523
- counts: { applied: 1 },
524
- });
525
- }
526
- catch {
527
- recordCommandReceiptIfPossible(input.store, command, {
528
- operationId,
529
- status: 'failed',
530
- reasonCode: RUNNER_PORTAL_SYNC_REASON_CODES.INVALID_STATE_TRANSITION,
531
- createdAt: input.nowIso,
532
- summary: 'Portal command failed local application with public reason code.',
533
- redactionEvidence: validation.redactions,
534
- });
535
- return postCommandAck(input.http, input.headers, {
536
- ...baseAck,
537
- localStatus: 'failed-local',
538
- remoteStatus: 'rejected',
539
- reasonCode: RUNNER_PORTAL_SYNC_REASON_CODES.INVALID_STATE_TRANSITION,
540
- publicSummary: 'Runner failed local Portal command application with public reason code.',
541
- counts: { failedLocal: 1 },
542
- });
543
- }
544
- }
545
- function applyLocalCommand(store, command, nowIso) {
546
- switch (command.action) {
547
- case 'pause':
548
- store.updateJobAndExistingGoalCampaignStatus({ jobId: command.jobId, status: 'paused', updatedAt: nowIso, reasonCode: RUNNER_PORTAL_SYNC_REASON_CODES.WAITING_HUMAN });
549
- return;
550
- case 'resume':
551
- case 'approve_review_gate':
552
- store.updateJobAndExistingGoalCampaignStatus({ jobId: command.jobId, status: 'active', updatedAt: nowIso, reasonCode: RUNNER_PORTAL_SYNC_REASON_CODES.OK });
553
- return;
554
- case 'cancel':
555
- case 'deny_review_gate':
556
- store.updateJobAndExistingGoalCampaignStatus({ jobId: command.jobId, status: 'cancelled', updatedAt: nowIso, reasonCode: RUNNER_PORTAL_SYNC_REASON_CODES.JOB_CANCELLED });
557
- return;
558
- case 'answer_decision':
559
- if (command.decision?.option === 'approve') {
560
- store.updateJobAndExistingGoalCampaignStatus({ jobId: command.jobId, status: 'active', updatedAt: nowIso, reasonCode: RUNNER_PORTAL_SYNC_REASON_CODES.OK });
561
- return;
562
- }
563
- if (command.decision?.option === 'deny') {
564
- store.updateJobAndExistingGoalCampaignStatus({ jobId: command.jobId, status: 'cancelled', updatedAt: nowIso, reasonCode: RUNNER_PORTAL_SYNC_REASON_CODES.JOB_CANCELLED });
565
- return;
566
- }
567
- if (command.decision?.option === 'hold') {
568
- store.updateJobAndExistingGoalCampaignStatus({ jobId: command.jobId, status: 'blocked', updatedAt: nowIso, reasonCode: RUNNER_PORTAL_SYNC_REASON_CODES.WAITING_HUMAN });
569
- return;
570
- }
571
- throw new Error('unsupported-review-gate-decision');
572
- case 'run_once':
573
- case 'retry':
574
- store.scheduleNextTick({ jobId: command.jobId, scheduledAt: nowIso, updatedAt: nowIso, reasonCode: RUNNER_PORTAL_SYNC_REASON_CODES.OK });
575
- return;
576
- case 'snapshot':
577
- store.recordStateSnapshot({
578
- snapshotId: `snapshot-${operationIdForCommand(command.commandId)}`,
579
- jobId: command.jobId,
580
- kind: 'portal_command_snapshot',
581
- summary: 'Portal snapshot command recorded public local state checkpoint request.',
582
- capturedAt: nowIso,
583
- operationId: operationIdForCommand(command.commandId),
584
- idempotencyKey: command.idempotencyKey,
585
- metadata: commandPublicMetadata(command, operationIdForCommand(command.commandId), command.runnerId, 'applied', nowIso, [], RUNNER_PORTAL_SYNC_REASON_CODES.OK),
586
- });
587
- return;
588
- default:
589
- throw new Error('unsupported-command-action');
590
- }
591
- }
592
- async function postCommandAck(http, headers, input) {
593
- await safeHttp(http, {
594
- method: 'POST',
595
- path: `/api/v1/continuity/runner/commands/${encodeURIComponent(input.commandId)}/ack`,
596
- body: {
597
- status: input.remoteStatus,
598
- runnerId: input.runnerId,
599
- workspaceId: input.identity.workspaceId,
600
- workspaceLabel: input.identity.workspaceLabel,
601
- projectId: input.identity.projectId,
602
- projectLabel: input.identity.projectLabel,
603
- idempotencyKey: input.idempotencyKey,
604
- reasonCode: input.reasonCode,
605
- publicSummary: boundPublicText(input.publicSummary, 280),
606
- counts: filterFiniteCounts(input.counts),
607
- redactionEvidence: input.redactionEvidence.slice(0, 20),
608
- publicSafe: true,
609
- },
610
- headers,
611
- });
612
- return {
613
- commandId: input.commandId,
614
- ...(input.jobId ? { jobId: input.jobId } : {}),
615
- workspaceId: input.identity.workspaceId,
616
- workspaceLabel: input.identity.workspaceLabel,
617
- projectId: input.identity.projectId,
618
- projectLabel: input.identity.projectLabel,
619
- ...(input.action ? { action: input.action } : {}),
620
- localStatus: input.localStatus,
621
- remoteStatus: input.remoteStatus,
622
- reasonCode: input.reasonCode,
623
- publicSummary: boundPublicText(input.publicSummary, 280),
624
- acknowledgedAt: input.acknowledgedAt,
625
- counts: input.counts,
626
- redactionEvidence: input.redactionEvidence.slice(0, 20),
627
- publicSafe: true,
628
- };
629
- }
630
- function recordCommandReceiptIfPossible(store, command, input) {
631
- try {
632
- if (!store.jobExists(command.jobId) || store.hasOperationRef(input.operationId, command.idempotencyKey))
633
- return;
634
- store.appendReceipt({
635
- receiptId: `receipt-${input.operationId}`,
636
- jobId: command.jobId,
637
- operationId: input.operationId,
638
- idempotencyKey: command.idempotencyKey,
639
- status: input.status,
640
- reasonCode: input.reasonCode,
641
- ignoredOperationIds: [input.operationId],
642
- createdAt: input.createdAt,
643
- metadata: commandPublicMetadata(command, input.operationId, command.runnerId, input.status, input.createdAt, input.redactionEvidence, input.reasonCode),
644
- });
645
- store.appendEvent({
646
- eventId: `${input.operationId}:event`,
647
- jobId: command.jobId,
648
- operationId: `${input.operationId}:event`,
649
- idempotencyKey: `${command.idempotencyKey}:event`,
650
- type: input.status === 'failed' ? 'portal_command_failed' : 'portal_command_rejected',
651
- summary: input.summary,
652
- reasonCode: input.reasonCode,
653
- createdAt: input.createdAt,
654
- metadata: commandPublicMetadata(command, input.operationId, command.runnerId, input.status, input.createdAt, input.redactionEvidence, input.reasonCode),
655
- });
656
- }
657
- catch {
658
- // Acknowledgement still proceeds with a public failed-local/rejected reason.
659
- }
660
- }
661
- function recordRejectedCommandAuditIfPossible(store, validation, runnerId, nowIso) {
662
- if (!validation.commandId || !SAFE_COMMAND_ID_PATTERN.test(validation.commandId))
663
- return;
664
- if (!validation.jobId || !isSafePublicJobId(validation.jobId))
665
- return;
666
- if (!validation.action || !COMMAND_ACTIONS.has(validation.action))
667
- return;
668
- const command = {
669
- commandId: validation.commandId,
670
- jobId: validation.jobId,
671
- action: validation.action,
672
- status: 'queued',
673
- queuedAt: nowIso,
674
- idempotencyKey: `rejected:${validation.commandId}`,
675
- delivery: 'runner_poll',
676
- runnerId,
677
- reasonCode: RUNNER_PORTAL_SYNC_REASON_CODES.PORTAL_COMMAND_PAYLOAD_REJECTED,
678
- publicSafe: true,
679
- };
680
- recordCommandReceiptIfPossible(store, command, {
681
- operationId: `${operationIdForCommand(validation.commandId)}:rejected`,
682
- status: 'ignored',
683
- reasonCode: RUNNER_PORTAL_SYNC_REASON_CODES.PORTAL_COMMAND_PAYLOAD_REJECTED,
684
- createdAt: nowIso,
685
- summary: 'Runner rejected unsafe Portal command before local application.',
686
- redactionEvidence: validation.redactions,
687
- });
688
- }
689
- function recordCommandReplayAuditIfPossible(store, command, operationId, runnerId, nowIso, redactions) {
690
- const replayOperationId = `${operationId}:replay`;
691
- try {
692
- if (!store.jobExists(command.jobId) || store.hasOperationRef(replayOperationId, `${command.idempotencyKey}:replay`))
693
- return;
694
- store.appendEvent({
695
- eventId: `${replayOperationId}:event`,
696
- jobId: command.jobId,
697
- operationId: replayOperationId,
698
- idempotencyKey: `${command.idempotencyKey}:replay`,
699
- type: 'portal_command_replay',
700
- summary: 'Runner recorded idempotent Portal command replay without local mutation.',
701
- reasonCode: RUNNER_PORTAL_SYNC_REASON_CODES.IDEMPOTENCY_REPLAY,
702
- createdAt: nowIso,
703
- metadata: commandPublicMetadata(command, replayOperationId, runnerId, 'already_applied', nowIso, redactions, RUNNER_PORTAL_SYNC_REASON_CODES.IDEMPOTENCY_REPLAY),
704
- });
705
- }
706
- catch {
707
- // Replay acknowledgement still proceeds; local replay audit is best-effort public evidence.
708
- }
709
- }
710
- function buildHeartbeatPayload(snapshot, input) {
711
- const status = runnerStatus(snapshot);
712
- const activeJobIds = snapshot.jobs
713
- .filter((job) => ['planned', 'active', 'running', 'backoff', 'waiting_external', 'waiting_human'].includes(job.status))
714
- .map((job) => job.jobId)
715
- .filter(isSafePublicJobId)
716
- .slice(0, 20);
717
- const leaseIds = snapshot.staleLeases.map((lease) => lease.leaseId).filter(isSafePublicId).slice(0, 20);
718
- const nextTickAt = minIso(snapshot.dueJobs.map((job) => job.nextRunAt).filter((value) => Boolean(value)));
719
- return {
720
- schemaVersion: CONTINUITY_CLIENT_SCHEMA_VERSION,
721
- contractVersion: CONTINUITY_CLIENT_CONTRACT_VERSION,
722
- runnerId: input.runnerId,
723
- ...(input.sessionId ? { sessionId: input.sessionId } : {}),
724
- workspaceId: input.identity.workspaceId,
725
- workspaceLabel: input.identity.workspaceLabel,
726
- projectId: input.identity.projectId,
727
- projectLabel: input.identity.projectLabel,
728
- status,
729
- observedAt: input.generatedAt,
730
- version: boundPublicText(input.clientVersion, 80),
731
- activeJobIds,
732
- leaseIds,
733
- ...(nextTickAt ? { nextTickAt } : {}),
734
- schedulerState: input.schedulerState,
735
- doctorSummary: status === 'degraded'
736
- ? 'Runner sync is degraded by public stale lease or retryable outbox counts.'
737
- : 'Runner sync heartbeat contains public local continuity summaries.',
738
- reasonCode: status === 'degraded' ? RUNNER_PORTAL_SYNC_REASON_CODES.BACKOFF_SCHEDULED : RUNNER_PORTAL_SYNC_REASON_CODES.OK,
739
- queue: {
740
- depth: snapshot.queue.depth,
741
- queued: snapshot.queue.queued,
742
- running: snapshot.queue.running,
743
- retrying: snapshot.queue.retrying,
744
- deadLetter: snapshot.queue.deadLetter,
745
- capacity: snapshot.queue.capacity,
746
- available: snapshot.queue.available,
747
- backpressure: snapshot.queue.backpressure,
748
- generatedAt: snapshot.queue.generatedAt,
749
- ...(snapshot.queue.nextRetryAt ? { nextRetryAt: snapshot.queue.nextRetryAt } : {}),
750
- ...(snapshot.queue.reasonCode ? { reasonCode: safeReasonCode(snapshot.queue.reasonCode) } : {}),
751
- publicSafe: true,
752
- },
753
- metadata: {
754
- schemaVersion: CONTINUITY_CLIENT_SCHEMA_VERSION,
755
- contractVersion: CONTINUITY_CLIENT_CONTRACT_VERSION,
756
- transportKind: 'runner_heartbeat',
757
- ...(input.sessionId ? { sessionId: input.sessionId } : {}),
758
- workspaceId: input.identity.workspaceId,
759
- workspaceLabel: input.identity.workspaceLabel,
760
- projectId: input.identity.projectId,
761
- projectLabel: input.identity.projectLabel,
762
- observedAt: input.generatedAt,
763
- serverAccessToLocalhost: false,
764
- serverHeldStream: false,
765
- counts: {
766
- jobs: snapshot.counts.jobs ?? snapshot.jobs.length,
767
- dueJobs: snapshot.dueJobCount,
768
- activeLeases: snapshot.counts.activeLeases ?? 0,
769
- staleLeases: snapshot.counts.staleLeases ?? snapshot.staleLeases.length,
770
- outboxPending: snapshot.outbox.pending ?? 0,
771
- outboxFailed: (snapshot.outbox.failed ?? 0) + (snapshot.outbox.deadLetter ?? 0),
772
- ...queueCounts(snapshot),
773
- },
774
- reasonCodes: [status === 'degraded' ? RUNNER_PORTAL_SYNC_REASON_CODES.BACKOFF_SCHEDULED : RUNNER_PORTAL_SYNC_REASON_CODES.OK],
775
- publicSummary: 'Runner heartbeat generated from local continuity SQLite public summaries.',
776
- },
777
- publicSafe: true,
778
- };
779
- }
780
- function buildRunnerSyncPayload(snapshot, input) {
781
- const jobs = snapshot.jobs.map((job) => toPortalJobSync(job, input.identity, snapshot)).slice(0, 50);
782
- const events = [
783
- ...snapshot.lastEvents.map(toPortalEventSync),
784
- ...(snapshot.headlessExecutionAttempts ?? []).map(toPortalHeadlessExecutionEventSync),
785
- ].slice(0, 100);
786
- const receipts = snapshot.lastReceipts.map(toPortalReceiptSync).slice(0, 100);
787
- const outbox = outboxSummaries(snapshot, input.generatedAt);
788
- return {
789
- runnerId: input.runnerId,
790
- workspaceId: input.identity.workspaceId,
791
- workspaceLabel: input.identity.workspaceLabel,
792
- projectId: input.identity.projectId,
793
- projectLabel: input.identity.projectLabel,
794
- runner: {
795
- ...input.heartbeat,
796
- metadata: {
797
- schemaVersion: CONTINUITY_CLIENT_SCHEMA_VERSION,
798
- contractVersion: CONTINUITY_CLIENT_CONTRACT_VERSION,
799
- syncVersion: CONTINUITY_CLIENT_PORTAL_SYNC_ENVELOPE_VERSION,
800
- transportKind: 'runner_sync',
801
- workspaceId: input.identity.workspaceId,
802
- workspaceLabel: input.identity.workspaceLabel,
803
- projectId: input.identity.projectId,
804
- projectLabel: input.identity.projectLabel,
805
- syncCursor: input.previousSyncCursor ?? 'sync-initial',
806
- nextSyncCursor: input.nextSyncCursor,
807
- generatedAt: input.generatedAt,
808
- serverAccessToLocalhost: false,
809
- serverHeldStream: false,
810
- counts: {
811
- jobs: jobs.length,
812
- events: events.length,
813
- receipts: receipts.length,
814
- outbox: outbox.length,
815
- headlessExecutionAttempts: snapshot.headlessExecutionAttempts?.length ?? 0,
816
- ...queueCounts(snapshot),
817
- },
818
- publicSummary: 'Runner sync uploaded public job, event and receipt summaries.',
819
- },
820
- },
821
- jobs,
822
- events,
823
- receipts,
824
- outbox,
825
- runnerSync: {
826
- runnerId: input.runnerId,
827
- workspaceId: input.identity.workspaceId,
828
- workspaceLabel: input.identity.workspaceLabel,
829
- projectId: input.identity.projectId,
830
- projectLabel: input.identity.projectLabel,
831
- syncCursor: input.previousSyncCursor ?? 'sync-initial',
832
- nextSyncCursor: input.nextSyncCursor,
833
- generatedAt: input.generatedAt,
834
- publicSummary: 'Runner sync uploaded public job, event and receipt summaries.',
835
- counts: {
836
- jobs: jobs.length,
837
- events: events.length,
838
- receipts: receipts.length,
839
- outbox: outbox.length,
840
- ...queueCounts(snapshot),
841
- },
842
- publicSafe: true,
843
- },
844
- };
845
- }
846
- function enqueueRunnerSyncOutboxDelivery(store, snapshot, input) {
847
- const outboxId = runnerSyncOutboxId({ runnerId: input.runnerId, workspaceId: input.identity.workspaceId, projectId: input.identity.projectId, nextSyncCursor: input.nextSyncCursor });
848
- const deliveryCursor = runnerSyncDeliveryCursor({ runnerId: input.runnerId, workspaceId: input.identity.workspaceId, projectId: input.identity.projectId, nextSyncCursor: input.nextSyncCursor });
849
- store.enqueueOutbox({
850
- outboxId,
851
- jobId: firstSafeJobId(snapshot),
852
- operationId: `op-${outboxId}`,
853
- idempotencyKey: `idem-${outboxId}`,
854
- type: 'runner_sync',
855
- status: 'pending',
856
- payload: runnerSyncOutboxPayload(snapshot, input),
857
- createdAt: input.generatedAt,
858
- updatedAt: input.generatedAt,
859
- });
860
- return store.markOutboxSent({
861
- outboxId,
862
- deliveryCursor,
863
- sentAt: input.generatedAt,
864
- reasonCode: RUNNER_PORTAL_SYNC_REASON_CODES.OK,
865
- });
866
- }
867
- function runnerSyncOutboxId(input) {
868
- return `outbox-runner-sync-${sha256Hex(`${input.runnerId}:${input.workspaceId}:${input.projectId ?? 'project'}:${input.nextSyncCursor}`).slice(0, 32)}`;
869
- }
870
- function runnerSyncDeliveryCursor(input) {
871
- return `cursor-runner-sync-${sha256Hex(`${input.workspaceId}:${input.projectId ?? 'project'}:${input.runnerId}:${input.nextSyncCursor}`).slice(0, 32)}`;
872
- }
873
- function runnerSyncOutboxPayload(snapshot, input) {
874
- return {
875
- schemaVersion: CONTINUITY_CLIENT_SCHEMA_VERSION,
876
- contractVersion: CONTINUITY_CLIENT_CONTRACT_VERSION,
877
- syncVersion: CONTINUITY_CLIENT_PORTAL_SYNC_ENVELOPE_VERSION,
878
- transportKind: 'runner_sync',
879
- envelopeId: `runner-sync-${sha256Hex(`${input.runnerId}:${input.nextSyncCursor}`).slice(0, 24)}`,
880
- runnerId: input.runnerId,
881
- workspaceId: input.identity.workspaceId,
882
- workspaceLabel: input.identity.workspaceLabel,
883
- projectId: input.identity.projectId,
884
- projectLabel: input.identity.projectLabel,
885
- syncCursor: input.previousSyncCursor ?? 'sync-initial',
886
- nextSyncCursor: input.nextSyncCursor,
887
- generatedAt: input.generatedAt,
888
- serverAccessToLocalhost: false,
889
- serverHeldStream: false,
890
- counts: {
891
- jobs: snapshot.counts.jobs ?? snapshot.jobs.length,
892
- events: snapshot.counts.events ?? snapshot.lastEvents.length,
893
- receipts: snapshot.counts.receipts ?? snapshot.lastReceipts.length,
894
- outboxPending: snapshot.outbox.pending ?? 0,
895
- outboxFailed: snapshot.outbox.failed ?? 0,
896
- outboxDeadLetter: snapshot.outbox.deadLetter ?? 0,
897
- headlessExecutionAttempts: snapshot.headlessExecutionAttempts?.length ?? 0,
898
- ...queueCounts(snapshot),
899
- },
900
- redactionEvidence: [{ field: 'runnerSyncBody', reason: 'unbounded_text', evidence: 'operation-denied', publicSafe: true }],
901
- publicSummary: 'Runner sync outbox stores public IDs, counts, redaction evidence and cursor state only.',
902
- };
903
- }
904
- function firstSafeJobId(snapshot) {
905
- return snapshot.jobs.map((job) => job.jobId).find(isSafePublicJobId);
906
- }
907
- function toPortalJobSync(job, identity, snapshot) {
908
- // P195.04: carry the additive stage projection into the legacy `jobs[]` sync
909
- // row. Values are re-validated against the public stage allow-list and the
910
- // bounded history cap; server-side field gating remains P195.05.
911
- const currentStage = isContinuityPublicStage(job.currentStage) ? job.currentStage : undefined;
912
- const stageHistory = sanitizeContinuityStageHistory(job.stageHistory);
913
- const iteration = normalizeContinuityStageIteration(job.iteration);
914
- const operations = jobOperationsSummary(job.jobId, snapshot);
915
- return {
916
- jobId: job.jobId,
917
- workspaceId: identity.workspaceId,
918
- workspaceLabel: identity.workspaceLabel,
919
- projectId: identity.projectId,
920
- projectLabel: identity.projectLabel,
921
- kind: safeJobKind(job.kind),
922
- status: safeJobStatus(job.status),
923
- publicSummary: boundPublicText(job.publicSummary, 240),
924
- updatedAt: job.updatedAt,
925
- ...(job.nextRunAt ? { nextRunAt: job.nextRunAt } : {}),
926
- ...(job.reasonCode ? { reasonCode: safeReasonCode(job.reasonCode) } : {}),
927
- ...(job.counts ? { counts: filterFiniteCounts(job.counts) } : {}),
928
- ...(operations ? { operations } : {}),
929
- ...(currentStage ? { currentStage } : {}),
930
- ...(stageHistory.length > 0 ? { stageHistory } : {}),
931
- ...(iteration !== undefined ? { iteration } : {}),
932
- publicSafe: true,
933
- };
934
- }
935
- function jobOperationsSummary(jobId, snapshot) {
936
- const attempts = (snapshot.headlessExecutionAttempts ?? []).filter((attempt) => attempt.jobId === jobId).slice(0, 50);
937
- const staleLeases = snapshot.staleLeases.filter((lease) => lease.jobId === jobId).slice(0, 50);
938
- if (attempts.length === 0 && staleLeases.length === 0)
939
- return undefined;
940
- const retrying = attempts.filter((attempt) => attempt.status === 'backoff' || (attempt.retryCount > 0 && Boolean(attempt.nextRetryAt))).length;
941
- const deadLetter = attempts.filter((attempt) => Boolean(attempt.deadLetteredAt) || attempt.status === 'dead_letter').length;
942
- const queueDepth = attempts.filter((attempt) => ['queued', 'pending', 'backoff'].includes(attempt.status)).length;
943
- const nextRetryAt = minIso(attempts.map((attempt) => attempt.nextRetryAt).filter((value) => Boolean(value)));
944
- const latestLeaseExpiresAt = [...attempts]
945
- .map((attempt) => attempt.leaseExpiresAt)
946
- .filter((value) => Boolean(value))
947
- .sort()
948
- .at(-1);
949
- return {
950
- attempts: attempts.length,
951
- retries: attempts.reduce((total, attempt) => total + Math.max(0, Math.trunc(attempt.retryCount)), 0),
952
- retrying,
953
- deadLetter,
954
- activeLeases: attempts.filter((attempt) => Boolean(attempt.leaseId) && attempt.status === 'running').length,
955
- staleLeases: staleLeases.length,
956
- queueDepth,
957
- backpressure: snapshot.queue.backpressure && queueDepth > 0,
958
- generatedAt: snapshot.generatedAt,
959
- ...(nextRetryAt ? { nextRetryAt } : {}),
960
- ...(latestLeaseExpiresAt ? { latestLeaseExpiresAt } : {}),
961
- publicSafe: true,
962
- };
963
- }
964
- function toPortalEventSync(event) {
965
- return {
966
- eventId: event.eventId,
967
- jobId: event.jobId,
968
- operationId: event.operationId,
969
- type: boundPublicText(event.type, 80),
970
- summary: boundPublicText(event.publicSummary, 240),
971
- publicSummary: boundPublicText(event.publicSummary, 240),
972
- createdAt: event.createdAt,
973
- ...(event.metadata ? { metadata: event.metadata } : {}),
974
- ...(event.reasonCode ? { reasonCode: safeReasonCode(event.reasonCode) } : {}),
975
- publicSafe: true,
976
- };
977
- }
978
- function toPortalHeadlessExecutionEventSync(attempt) {
979
- return {
980
- eventId: `headless-${sanitizeId(attempt.attemptId)}`,
981
- jobId: attempt.jobId,
982
- operationId: attempt.executionId,
983
- type: 'headless_execution_attempt',
984
- summary: boundPublicText(attempt.publicSummary, 240),
985
- publicSummary: boundPublicText(attempt.publicSummary, 240),
986
- createdAt: attempt.heartbeatAt ?? attempt.enqueuedAt,
987
- ...(attempt.reasonCode ? { reasonCode: safeReasonCode(attempt.reasonCode) } : {}),
988
- publicSafe: true,
989
- };
990
- }
991
- function toPortalReceiptSync(receipt) {
992
- return {
993
- receiptId: receipt.receiptId,
994
- jobId: receipt.jobId,
995
- ...(receipt.operationId ? { operationId: receipt.operationId } : {}),
996
- status: safeReceiptStatus(receipt.status),
997
- summary: `Runner receipt ${receipt.status} for ${receipt.jobId}.`,
998
- createdAt: receipt.createdAt,
999
- ...(receipt.reasonCode ? { reasonCode: safeReasonCode(receipt.reasonCode) } : {}),
1000
- publicSafe: true,
1001
- };
1002
- }
1003
- function outboxSummaries(snapshot, generatedAt) {
1004
- const entries = [];
1005
- for (const [status, count] of Object.entries(snapshot.outbox)) {
1006
- if (status === 'total' || !Number.isFinite(count) || count <= 0)
1007
- continue;
1008
- entries.push({
1009
- outboxId: `outbox-${status}`,
1010
- operationId: `outbox-${status}-${sha256Hex(generatedAt).slice(0, 12)}`,
1011
- status: status === 'failed' || status === 'deadLetter' ? 'failed' : status === 'acked' || status === 'sent' ? 'applied' : 'accepted',
1012
- summary: `Outbox ${status} count ${Math.trunc(count)} synced as public status evidence.`,
1013
- updatedAt: generatedAt,
1014
- reasonCode: status === 'failed' || status === 'deadLetter' ? RUNNER_PORTAL_SYNC_REASON_CODES.BACKOFF_SCHEDULED : RUNNER_PORTAL_SYNC_REASON_CODES.OK,
1015
- counts: { [status]: Math.trunc(count) },
1016
- publicSafe: true,
1017
- });
1018
- }
1019
- return entries.slice(0, 20);
1020
- }
1021
- function validatePendingCommand(input) {
1022
- const redactions = [];
1023
- if (!isRecord(input)) {
1024
- redactions.push(redaction('command', 'unsafe_key', 'operation-denied'));
1025
- return { ok: false, reasonCode: RUNNER_PORTAL_SYNC_REASON_CODES.UNSAFE_FIELD_REJECTED, redactions };
1026
- }
1027
- for (const key of Object.keys(input)) {
1028
- if (!COMMAND_ALLOWED_KEYS.has(key) || UNSAFE_KEY_PATTERN.test(key)) {
1029
- redactions.push(redaction(`command.${boundPublicText(key, 80)}`, 'unsafe_key', 'key-denied'));
1030
- }
1031
- }
1032
- for (const [key, value] of Object.entries(input)) {
1033
- if (!COMMAND_ALLOWED_KEYS.has(key))
1034
- continue;
1035
- collectUnsafeValueRedactions(value, `command.${key}`, redactions);
1036
- }
1037
- const commandId = typeof input.commandId === 'string' ? input.commandId : undefined;
1038
- const jobId = typeof input.jobId === 'string' ? input.jobId : undefined;
1039
- const action = typeof input.action === 'string' ? input.action : undefined;
1040
- const status = typeof input.status === 'string' ? input.status : undefined;
1041
- const queuedAt = typeof input.queuedAt === 'string' ? input.queuedAt : undefined;
1042
- const idempotencyKey = typeof input.idempotencyKey === 'string' ? input.idempotencyKey : undefined;
1043
- const delivery = typeof input.delivery === 'string' ? input.delivery : undefined;
1044
- if (!commandId || !SAFE_COMMAND_ID_PATTERN.test(commandId))
1045
- redactions.push(redaction('command.commandId', 'unsafe_key'));
1046
- if (!jobId || !isSafePublicJobId(jobId))
1047
- redactions.push(redaction('command.jobId', 'unsafe_key'));
1048
- if (!action || !COMMAND_ACTIONS.has(action))
1049
- redactions.push(redaction('command.action', 'unsafe_key'));
1050
- if (status !== 'queued')
1051
- redactions.push(redaction('command.status', 'unsafe_key'));
1052
- const decision = validateReviewGateDecision(input.decision, action, redactions);
1053
- if (!queuedAt || !Number.isFinite(Date.parse(queuedAt)))
1054
- redactions.push(redaction('command.queuedAt', 'unsafe_key'));
1055
- if (!idempotencyKey || !isSafePublicId(idempotencyKey))
1056
- redactions.push(redaction('command.idempotencyKey', 'unsafe_key'));
1057
- if (delivery !== 'runner_poll')
1058
- redactions.push(redaction('command.delivery', 'unsafe_key'));
1059
- if (input.publicSafe !== true)
1060
- redactions.push(redaction('command.publicSafe', 'unsafe_key'));
1061
- if (typeof input.expiresAt === 'string' && !Number.isFinite(Date.parse(input.expiresAt)))
1062
- redactions.push(redaction('command.expiresAt', 'unsafe_key'));
1063
- if (typeof input.workspaceId === 'string' && !isSafePublicId(input.workspaceId))
1064
- redactions.push(redaction('command.workspaceId', 'unsafe_key'));
1065
- if (typeof input.workspaceLabel === 'string' && !isSafePublicLabel(input.workspaceLabel))
1066
- redactions.push(redaction('command.workspaceLabel', 'unsafe_key'));
1067
- if (typeof input.runnerId === 'string' && !SAFE_RUNNER_ID_PATTERN.test(input.runnerId))
1068
- redactions.push(redaction('command.runnerId', 'unsafe_key'));
1069
- if (typeof input.projectId === 'string' && !isSafePublicId(input.projectId))
1070
- redactions.push(redaction('command.projectId', 'unsafe_key'));
1071
- if (typeof input.projectLabel === 'string' && !isSafePublicLabel(input.projectLabel))
1072
- redactions.push(redaction('command.projectLabel', 'unsafe_key'));
1073
- if (typeof input.reasonCode === 'string' && !SAFE_REASON_CODE_PATTERN.test(input.reasonCode))
1074
- redactions.push(redaction('command.reasonCode', 'unsafe_key'));
1075
- if (redactions.length > 0 || !commandId || !jobId || !action || !queuedAt || !idempotencyKey || !delivery) {
1076
- return { ok: false, commandId, jobId, action, reasonCode: RUNNER_PORTAL_SYNC_REASON_CODES.UNSAFE_FIELD_REJECTED, redactions: uniqueRedactions(redactions) };
1077
- }
1078
- return {
1079
- ok: true,
1080
- command: {
1081
- commandId,
1082
- jobId,
1083
- action,
1084
- ...(decision ? { decision } : {}),
1085
- status: status ?? 'queued',
1086
- queuedAt,
1087
- ...(typeof input.expiresAt === 'string' ? { expiresAt: input.expiresAt } : {}),
1088
- idempotencyKey,
1089
- delivery: delivery ?? 'runner_poll',
1090
- ...(typeof input.workspaceId === 'string' ? { workspaceId: input.workspaceId } : {}),
1091
- ...(typeof input.workspaceLabel === 'string' ? { workspaceLabel: input.workspaceLabel } : {}),
1092
- ...(typeof input.runnerId === 'string' ? { runnerId: input.runnerId } : {}),
1093
- ...(typeof input.projectId === 'string' ? { projectId: input.projectId } : {}),
1094
- ...(typeof input.projectLabel === 'string' ? { projectLabel: input.projectLabel } : {}),
1095
- ...(typeof input.reasonCode === 'string' ? { reasonCode: input.reasonCode } : {}),
1096
- publicSafe: true,
1097
- },
1098
- reasonCode: RUNNER_PORTAL_SYNC_REASON_CODES.OK,
1099
- redactions: [],
1100
- };
1101
- }
1102
- function validateReviewGateDecision(value, action, redactions) {
1103
- if (action !== 'answer_decision' && action !== 'approve_review_gate' && action !== 'deny_review_gate') {
1104
- if (value !== undefined)
1105
- redactions.push(redaction('command.decision', 'unsafe_key'));
1106
- return undefined;
1107
- }
1108
- if (value === undefined) {
1109
- if (action === 'answer_decision')
1110
- redactions.push(redaction('command.decision', 'unsafe_key'));
1111
- return undefined;
1112
- }
1113
- if (!isRecord(value)) {
1114
- redactions.push(redaction('command.decision', 'unsafe_key'));
1115
- return undefined;
1116
- }
1117
- for (const key of Object.keys(value)) {
1118
- if (!REVIEW_GATE_DECISION_ALLOWED_KEYS.has(key) || UNSAFE_KEY_PATTERN.test(key)) {
1119
- redactions.push(redaction(`command.decision.${boundPublicText(key, 80)}`, 'unsafe_key', 'key-denied'));
1120
- }
1121
- }
1122
- const option = typeof value.option === 'string' ? value.option : undefined;
1123
- if (!option || !REVIEW_GATE_DECISION_OPTIONS.has(option))
1124
- redactions.push(redaction('command.decision.option', 'unsafe_key'));
1125
- if (typeof value.decisionId === 'string' && !isSafePublicId(value.decisionId))
1126
- redactions.push(redaction('command.decision.decisionId', 'unsafe_key'));
1127
- if (typeof value.gateId === 'string' && !isSafePublicId(value.gateId))
1128
- redactions.push(redaction('command.decision.gateId', 'unsafe_key'));
1129
- if (action === 'approve_review_gate' && option !== 'approve')
1130
- redactions.push(redaction('command.decision.option', 'unsafe_key'));
1131
- if (action === 'deny_review_gate' && option !== 'deny')
1132
- redactions.push(redaction('command.decision.option', 'unsafe_key'));
1133
- if (!option || !REVIEW_GATE_DECISION_OPTIONS.has(option))
1134
- return undefined;
1135
- return {
1136
- option: option,
1137
- ...(typeof value.decisionId === 'string' ? { decisionId: value.decisionId } : {}),
1138
- ...(typeof value.gateId === 'string' ? { gateId: value.gateId } : {}),
1139
- publicSafe: true,
1140
- };
1141
- }
1142
- function extractPendingCommands(body) {
1143
- if (!isRecord(body))
1144
- return [];
1145
- return Array.isArray(body.commands) ? body.commands : [];
1146
- }
1147
- function commandPublicMetadata(command, operationId, runnerId, status, timestamp, redactions, reasonCode) {
1148
- const effectiveReasonCode = reasonCode ?? reasonCodeForCommand(command);
1149
- const effectiveRunnerId = runnerId ?? command.runnerId;
1150
- return {
1151
- schemaVersion: CONTINUITY_CLIENT_SCHEMA_VERSION,
1152
- contractVersion: CONTINUITY_CLIENT_CONTRACT_VERSION,
1153
- syncVersion: CONTINUITY_CLIENT_PORTAL_SYNC_ENVELOPE_VERSION,
1154
- transportKind: 'command_ack',
1155
- actorType: 'runner',
1156
- ...(effectiveRunnerId ? { actorId: effectiveRunnerId, runnerId: effectiveRunnerId } : {}),
1157
- jobId: command.jobId,
1158
- ...(command.workspaceId ? { workspaceId: command.workspaceId } : {}),
1159
- ...(command.workspaceLabel ? { workspaceLabel: command.workspaceLabel } : {}),
1160
- ...(command.projectId ? { projectId: command.projectId } : {}),
1161
- ...(command.projectLabel ? { projectLabel: command.projectLabel } : {}),
1162
- operationId,
1163
- idempotencyKey: command.idempotencyKey,
1164
- commandId: command.commandId,
1165
- commandKind: command.action,
1166
- ...(command.decision ? { decisionOption: command.decision.option } : {}),
1167
- ...(command.decision?.decisionId ? { decisionId: command.decision.decisionId } : {}),
1168
- ...(command.decision?.gateId ? { gateId: command.decision.gateId } : {}),
1169
- commandStatus: status,
1170
- auditStatus: status,
1171
- acknowledgedAt: timestamp,
1172
- reasonCode: effectiveReasonCode,
1173
- redactionCount: redactions.length,
1174
- redactionEvidence: redactions.slice(0, 20),
1175
- counts: { redactions: redactions.length },
1176
- publicSummary: `Portal command ${command.action} ${status}.`,
1177
- };
1178
- }
1179
- function operationIdForCommand(commandId) {
1180
- return `portal-command-${sanitizeId(commandId)}`;
1181
- }
1182
- function reasonCodeForCommand(command) {
1183
- if (command.action === 'cancel' || command.action === 'deny_review_gate')
1184
- return RUNNER_PORTAL_SYNC_REASON_CODES.JOB_CANCELLED;
1185
- if (command.action === 'answer_decision' && command.decision?.option === 'deny')
1186
- return RUNNER_PORTAL_SYNC_REASON_CODES.JOB_CANCELLED;
1187
- if (command.action === 'pause')
1188
- return RUNNER_PORTAL_SYNC_REASON_CODES.WAITING_HUMAN;
1189
- if (command.action === 'answer_decision' && command.decision?.option === 'hold')
1190
- return RUNNER_PORTAL_SYNC_REASON_CODES.WAITING_HUMAN;
1191
- return RUNNER_PORTAL_SYNC_REASON_CODES.OK;
1192
- }
1193
- function runnerStatus(snapshot) {
1194
- if ((snapshot.counts.staleLeases ?? 0) > 0 || (snapshot.outbox.failed ?? 0) > 0 || (snapshot.outbox.deadLetter ?? 0) > 0 || snapshot.queue.backpressure)
1195
- return 'degraded';
1196
- if ((snapshot.counts.activeLeases ?? 0) > 0 || snapshot.dueJobCount > 0 || (snapshot.counts.headlessRunningAttempts ?? 0) > 0)
1197
- return 'busy';
1198
- return 'idle';
1199
- }
1200
- function heartbeatCounts(snapshot, redactions) {
1201
- return {
1202
- jobs: snapshot.counts.jobs ?? snapshot.jobs.length,
1203
- dueJobs: snapshot.dueJobCount,
1204
- activeLeases: snapshot.counts.activeLeases ?? 0,
1205
- staleLeases: snapshot.counts.staleLeases ?? snapshot.staleLeases.length,
1206
- headlessRunningAttempts: snapshot.counts.headlessRunningAttempts ?? 0,
1207
- outboxPending: snapshot.outbox.pending ?? 0,
1208
- outboxFailed: (snapshot.outbox.failed ?? 0) + (snapshot.outbox.deadLetter ?? 0),
1209
- redactions,
1210
- ...queueCounts(snapshot),
1211
- };
1212
- }
1213
- function queueCounts(snapshot) {
1214
- return {
1215
- queueDepth: snapshot.queue.depth,
1216
- queueQueued: snapshot.queue.queued,
1217
- queueRunning: snapshot.queue.running,
1218
- queueRetrying: snapshot.queue.retrying,
1219
- queueDeadLetter: snapshot.queue.deadLetter,
1220
- queueCapacity: snapshot.queue.capacity,
1221
- queueAvailable: snapshot.queue.available,
1222
- queueBackpressure: snapshot.queue.backpressure ? 1 : 0,
1223
- };
1224
- }
1225
- function buildSyncCursor(snapshot, generatedAt) {
1226
- const hash = sha256Hex(JSON.stringify({ generatedAt, counts: snapshot.counts, outbox: snapshot.outbox }));
1227
- return `sync-${hash.slice(0, 24)}`;
1228
- }
1229
- function resolveRunnerPortalIdentity(projectRoot, options) {
1230
- const derived = deriveProjectIdentity(projectRoot);
1231
- const workspaceId = sanitizeId(options.workspaceId ?? derived.workspaceId);
1232
- const projectId = sanitizeId(options.projectId ?? derived.projectId);
1233
- const projectLabel = sanitizePublicLabel(options.projectLabel ?? (options.projectId ? undefined : derived.projectLabel), options.projectId ? `Project ${projectId}` : derived.projectLabel);
1234
- const workspaceLabel = sanitizePublicLabel(options.workspaceLabel ?? (options.workspaceId ? undefined : derived.workspaceLabel), options.workspaceId ? `Workspace ${workspaceId}` : derived.workspaceLabel);
1235
- return { workspaceId, workspaceLabel, projectId, projectLabel };
1236
- }
1237
- function defaultPortalRunnerId(projectRoot) {
1238
- return `runner-${sha256Hex(projectRoot).slice(0, 16)}`;
1239
- }
1240
- function defaultPortalSessionId(projectRoot) {
1241
- return `session-${sha256Hex(`${projectRoot}:${process.pid}:${PORTAL_PROCESS_SESSION_SEED}`).slice(0, 16)}`;
1242
- }
1243
- function sanitizeSessionId(value) {
1244
- if (!value)
1245
- return undefined;
1246
- const safe = sanitizeId(value);
1247
- return SAFE_ID_PATTERN.test(safe) ? safe.slice(0, 96) : undefined;
1248
- }
1249
- function resolveServerUrl(options) {
1250
- return (options.serverUrl ?? process.env.NEOCORTEX_SERVER_URL ?? loadSecureConfig()?.serverUrl ?? DEFAULT_SERVER_URL).replace(/\/+$/, '');
1251
- }
1252
- async function resolveAuthToken(options) {
1253
- if (options.authToken)
1254
- return options.authToken;
1255
- if (options.httpClient)
1256
- return undefined;
1257
- const serverUrl = resolveServerUrl(options);
1258
- const licenseKey = options.licenseKey ?? loadSecureConfig()?.licenseKey;
1259
- if (!licenseKey)
1260
- return undefined;
1261
- return await new LicenseClient({ serverUrl, licenseKey, clientVersion: options.clientVersion ?? CLIENT_VERSION }).getToken() ?? undefined;
1262
- }
1263
- function defaultPortalHttpClient(serverUrl, authToken) {
1264
- return async (request) => {
1265
- if (!authToken) {
1266
- return { ok: false, status: 401, body: { reasonCode: RUNNER_PORTAL_SYNC_REASON_CODES.AUTH_TOKEN_PERMISSION_FAILURE } };
1267
- }
1268
- const url = new URL(`${serverUrl}${request.path}`);
1269
- for (const [key, value] of Object.entries(request.query ?? {})) {
1270
- if (value !== undefined)
1271
- url.searchParams.set(key, value);
1272
- }
1273
- const response = await fetch(url, {
1274
- method: request.method,
1275
- headers: request.headers,
1276
- body: request.method === 'POST' ? JSON.stringify(request.body ?? {}) : undefined,
1277
- });
1278
- const text = await response.text().catch(() => '');
1279
- let body;
1280
- try {
1281
- body = text ? JSON.parse(text) : undefined;
1282
- }
1283
- catch {
1284
- body = undefined;
1285
- }
1286
- return { ok: response.ok, status: response.status, body };
1287
- };
1288
- }
1289
- function buildPortalHeaders(clientVersion, authToken) {
1290
- return {
1291
- 'Content-Type': 'application/json',
1292
- 'X-Client-Version': boundPublicText(clientVersion, 80),
1293
- ...(authToken ? { Authorization: `Bearer ${authToken}` } : {}),
1294
- };
1295
- }
1296
- async function safeHttp(http, request, options = {}) {
1297
- try {
1298
- const timeoutMs = boundedInteger(options.timeoutMs ?? 0, 0, 60_000);
1299
- const response = timeoutMs > 0 ? await withTimeout(http(request), timeoutMs) : await http(request);
1300
- if (response.ok)
1301
- return { ok: true, body: response.body };
1302
- return { ok: false, reasonCode: reasonCodeFromResponse(response.body, response.status), body: response.body };
1303
- }
1304
- catch {
1305
- return { ok: false, reasonCode: RUNNER_PORTAL_SYNC_REASON_CODES.BACKOFF_SCHEDULED };
1306
- }
1307
- }
1308
- function reasonCodeFromResponse(body, status) {
1309
- if (isRecord(body)) {
1310
- const candidate = typeof body.reasonCode === 'string' ? body.reasonCode : typeof body.error_code === 'string' ? body.error_code.toLowerCase().replaceAll('_', '-') : undefined;
1311
- if (candidate && SAFE_REASON_CODE_PATTERN.test(candidate))
1312
- return candidate;
1313
- }
1314
- if (status === 401 || status === 403)
1315
- return RUNNER_PORTAL_SYNC_REASON_CODES.AUTH_TOKEN_PERMISSION_FAILURE;
1316
- if (status === 400)
1317
- return RUNNER_PORTAL_SYNC_REASON_CODES.PORTAL_SYNC_PAYLOAD_REJECTED;
1318
- return RUNNER_PORTAL_SYNC_REASON_CODES.BACKOFF_SCHEDULED;
1319
- }
1320
- function classifyPortalSyncError(error) {
1321
- if (isRecord(error)) {
1322
- const code = typeof error.reasonCode === 'string' ? error.reasonCode : typeof error.code === 'string' ? error.code : undefined;
1323
- if (code && SAFE_REASON_CODE_PATTERN.test(code))
1324
- return code;
1325
- }
1326
- const message = error instanceof Error ? error.message : String(error);
1327
- if (/sqlite-adapter-unavailable/i.test(message))
1328
- return RUNNER_PORTAL_SYNC_REASON_CODES.SQLITE_ADAPTER_UNAVAILABLE;
1329
- if (/integrity|corrupt|malformed|not a database/i.test(message))
1330
- return RUNNER_PORTAL_SYNC_REASON_CODES.SQLITE_INTEGRITY_FAILED;
1331
- return RUNNER_PORTAL_SYNC_REASON_CODES.BACKOFF_SCHEDULED;
1332
- }
1333
- function withTimeout(promise, timeoutMs) {
1334
- return new Promise((resolvePromise, rejectPromise) => {
1335
- const timer = setTimeout(() => rejectPromise(new Error('portal-http-timeout')), timeoutMs);
1336
- if (typeof timer.unref === 'function')
1337
- timer.unref();
1338
- promise.then((value) => {
1339
- clearTimeout(timer);
1340
- resolvePromise(value);
1341
- }, (error) => {
1342
- clearTimeout(timer);
1343
- rejectPromise(error);
1344
- });
1345
- });
1346
- }
1347
- function collectUnsafeValueRedactions(value, path, redactions) {
1348
- if (typeof value === 'string') {
1349
- if (UNSAFE_VALUE_PATTERN.test(value))
1350
- redactions.push(redaction(path, unsafeValueReason(value), 'value-denied'));
1351
- return;
1352
- }
1353
- if (value === null || typeof value === 'number' || typeof value === 'boolean' || value === undefined)
1354
- return;
1355
- if (Array.isArray(value)) {
1356
- for (const [index, child] of value.entries())
1357
- collectUnsafeValueRedactions(child, `${path}.${index}`, redactions);
1358
- return;
1359
- }
1360
- if (isRecord(value)) {
1361
- for (const [key, child] of Object.entries(value)) {
1362
- const childPath = `${path}.${boundPublicText(key, 80)}`;
1363
- if (UNSAFE_KEY_PATTERN.test(key))
1364
- redactions.push(redaction(childPath, 'unsafe_key', 'key-denied'));
1365
- collectUnsafeValueRedactions(child, childPath, redactions);
1366
- }
1367
- }
1368
- }
1369
- function unsafeValueReason(value) {
1370
- if (/https?:\/\//i.test(value))
1371
- return 'private_url';
1372
- if (/(?:^|\s)(?:\/(?:home|Users|media|mnt|tmp|var|etc|private)\/\S+|[A-Za-z]:\\\S+)/i.test(value))
1373
- return 'local_absolute_path';
1374
- if (/secret|token|password|api[_-]?key|license[_-]?key|authorization/i.test(value))
1375
- return 'secret';
1376
- if (/stdout|stderr|raw[_-]?log|transcript|stack/i.test(value))
1377
- return 'raw_log';
1378
- if (/prompt|workflow body|step body/i.test(value))
1379
- return 'prompt_body';
1380
- return 'protected_field';
1381
- }
1382
- function redaction(field, reason, evidence = 'value-denied') {
1383
- return { field: boundPublicText(field, 120), reason, evidence, publicSafe: true };
1384
- }
1385
- function uniqueRedactions(values) {
1386
- const seen = new Set();
1387
- const output = [];
1388
- for (const value of values) {
1389
- const key = `${value.field}:${value.reason}:${value.evidence}`;
1390
- if (seen.has(key))
1391
- continue;
1392
- seen.add(key);
1393
- output.push(value);
1394
- }
1395
- return output.slice(0, 20);
1396
- }
1397
- function sanitizeRunnerId(value) {
1398
- const sanitized = sanitizeId(value);
1399
- return SAFE_RUNNER_ID_PATTERN.test(sanitized) ? sanitized : `runner-${sha256Hex(value).slice(0, 16)}`;
1400
- }
1401
- function sanitizeId(value) {
1402
- if (UNSAFE_VALUE_PATTERN.test(value))
1403
- return `id-${sha256Hex(value).slice(0, 16)}`;
1404
- const safe = value.replace(/[^A-Za-z0-9._:-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 120);
1405
- return safe.length > 0 ? safe : `id-${sha256Hex(value).slice(0, 16)}`;
1406
- }
1407
- function sanitizePublicLabel(value, fallback) {
1408
- const normalized = (value ?? '').replace(/\s+/g, ' ').trim();
1409
- if (!normalized)
1410
- return fallback;
1411
- if (UNSAFE_VALUE_PATTERN.test(normalized) || UNSAFE_LABEL_PATTERN.test(normalized))
1412
- return fallback;
1413
- const safe = normalized.replace(/[^A-Za-z0-9 ._-]+/g, ' ').replace(/\s+/g, ' ').trim();
1414
- if (!safe)
1415
- return fallback;
1416
- return safe.length <= 80 ? safe : `${safe.slice(0, 77)}...`;
1417
- }
1418
- function isSafePublicId(value) {
1419
- return SAFE_ID_PATTERN.test(value) && !UNSAFE_VALUE_PATTERN.test(value);
1420
- }
1421
- function isSafePublicLabel(value) {
1422
- return value.trim().length > 0
1423
- && value.length <= 80
1424
- && !UNSAFE_VALUE_PATTERN.test(value)
1425
- && !UNSAFE_LABEL_PATTERN.test(value);
1426
- }
1427
- function isSafePublicJobId(value) {
1428
- return SAFE_JOB_ID_PATTERN.test(value) && !UNSAFE_VALUE_PATTERN.test(value);
1429
- }
1430
- function safeReasonCode(value) {
1431
- return SAFE_REASON_CODE_PATTERN.test(value) && !UNSAFE_VALUE_PATTERN.test(value) ? value : RUNNER_PORTAL_SYNC_REASON_CODES.OK;
1432
- }
1433
- function safeJobKind(value) {
1434
- return ['goal', 'loop', 'runner', 'jobs'].includes(value) ? value : 'jobs';
1435
- }
1436
- function safeJobStatus(value) {
1437
- return ['draft', 'planned', 'active', 'running', 'waiting_external', 'waiting_human', 'backoff', 'paused', 'blocked', 'completed', 'aborted', 'cancelled'].includes(value) ? value : 'active';
1438
- }
1439
- function safeReceiptStatus(value) {
1440
- return ['accepted', 'applied', 'ignored', 'failed', 'deferred'].includes(value) ? value : 'accepted';
1441
- }
1442
- function filterFiniteCounts(input) {
1443
- const output = {};
1444
- for (const [key, value] of Object.entries(input)) {
1445
- if (/^[A-Za-z][A-Za-z0-9_:-]{0,63}$/.test(key) && Number.isFinite(value) && value >= 0)
1446
- output[key] = Math.trunc(value);
1447
- }
1448
- return output;
1449
- }
1450
- function minIso(values) {
1451
- return values.filter((value) => Number.isFinite(Date.parse(value))).sort()[0];
1452
- }
1453
- function boundedInteger(value, min, max) {
1454
- if (!Number.isFinite(value))
1455
- return min;
1456
- return Math.max(min, Math.min(max, Math.floor(value)));
1457
- }
1458
- function boundedNumber(value, min, max) {
1459
- if (!Number.isFinite(value))
1460
- return min;
1461
- return Math.max(min, Math.min(max, value));
1462
- }
1463
- function jitteredDelayMs(baseDelayMs, jitterRatio, random) {
1464
- if (baseDelayMs <= 0)
1465
- return 0;
1466
- if (jitterRatio <= 0)
1467
- return baseDelayMs;
1468
- const boundedRandom = boundedNumber(random(), 0, 1);
1469
- const jitter = Math.floor(baseDelayMs * jitterRatio * boundedRandom);
1470
- return Math.max(0, baseDelayMs + jitter);
1471
- }
1472
- function sha256Hex(value) {
1473
- return createHash('sha256').update(value).digest('hex');
1474
- }
1475
- function boundPublicText(value, maxChars) {
1476
- const redacted = UNSAFE_VALUE_PATTERN.test(value) ? '[REDACTED]' : value;
1477
- return redacted.length <= maxChars ? redacted : `${redacted.slice(0, maxChars)}...[TRUNCATED:${redacted.length - maxChars}]`;
1478
- }
1479
- function isRecord(value) {
1480
- return typeof value === 'object' && value !== null && !Array.isArray(value);
1481
- }
1482
- function unique(values) {
1483
- return Array.from(new Set(values));
1484
- }
1485
- function sleep(ms) {
1486
- return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
1487
- }
1
+ import{createHash as ve}from"node:crypto";import{resolve as ae}from"node:path";import{DEFAULT_SERVER_URL as $e}from"../constants.js";import{loadSecureConfig as se}from"../config/secure-config.js";import{LicenseClient as Ke}from"../license/license-client.js";import{CLIENT_VERSION as $}from"../version.js";import{deriveProjectIdentity as G}from"./project-identity.js";import{CONTINUITY_CLIENT_CONTRACT_VERSION as K,CONTINUITY_CLIENT_PORTAL_SYNC_ENVELOPE_VERSION as Z,CONTINUITY_CLIENT_SCHEMA_VERSION as M,ContinuityClientStateStore as de}from"../continuity/continuity-client-state-store.js";import{isContinuityPublicStage as Me,normalizeContinuityStageIteration as Ue,openContinuitySqliteStore as ce,sanitizeContinuityStageHistory as Fe}from"../continuity/sqlite-store.js";const d=Object.freeze({OK:"continuity-ok",AUTH_TOKEN_PERMISSION_FAILURE:"auth-token-permission-failure",BACKOFF_SCHEDULED:"backoff-scheduled",COMMAND_EXPIRED:"command-expired",IDEMPOTENCY_REPLAY:"idempotency-replay",INVALID_STATE_TRANSITION:"invalid-state-transition",JOB_CANCELLED:"job-cancelled",PORTAL_COMMAND_LOCAL_AUDIT_RECORDED:"portal-command-local-audit-recorded",PORTAL_COMMAND_PAYLOAD_REJECTED:"portal-command-payload-rejected",PORTAL_SYNC_PAYLOAD_REJECTED:"portal-sync-payload-rejected",RUNNER_DIRECTIVE_UNTRUSTED:"runner-directive-untrusted",SQLITE_ADAPTER_UNAVAILABLE:"sqlite-adapter-unavailable",SQLITE_INTEGRITY_FAILED:"sqlite-integrity-failed",UNSAFE_FIELD_REJECTED:"unsafe-field-rejected",WAITING_HUMAN:"waiting-human"}),ie=new Set(["approve","deny","hold"]),qe=new Set(["option","decisionId","gateId","publicSafe"]),He=6e4,Ve=3e4,Je=1e4,Ye=.2,Be=`${Date.now()}:${Math.random().toString(16).slice(2)}`,ue=new Set(["pause","resume","cancel","run_once","retry","snapshot","approve_review_gate","deny_review_gate","answer_decision"]),le=new Set(["commandId","jobId","action","decision","status","queuedAt","expiresAt","acknowledgedAt","idempotencyKey","delivery","workspaceId","workspaceLabel","runnerId","projectId","projectLabel","reasonCode","publicSafe"]),ye=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/,fe=/^runner-[A-Za-z0-9._-]{1,80}$/,ze=/^(?:job|goal|loop|runner)-[A-Za-z0-9._-]{1,80}$/,pe=/^pcmd-[a-f0-9]{8,64}$/i,V=/^[a-z0-9][a-z0-9-]{1,80}$/,W=/(raw[_-]?(?:logs?|payloads?)|std(?:out|err)|stack(?:[_-]?trace)?|transcript|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,g=/(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|P180[_-]?SYNTHETIC[_-]?CONTINUITY|P185[_-]?SYNTHETIC[_-]?CONTINUITY|P187[_-]?SYNTHETIC[_-]?(?:CONTINUITY|RUNNER|WATCH)|P190[_-]?SYNTHETIC[_-]?(?:HEADLESS|CONTINUITY)|P192[_-]?SYNTHETIC[_-]?(?:PORTAL|RUNNER|SYNC))/i,me=/(?:[;&|`$<>]|\$\(|\n|\r|\0|(?:^|\s)(?:bash|sh|zsh|fish|cmd\.exe|powershell|pwsh|npm|pnpm|yarn|node|python|ruby|go|cargo|sudo|chmod|curl|wget)\s+(?:-c|run|exec|install|test|build|[A-Za-z0-9_./:-]+))/i;async function Ge(e={}){const t=ae(e.projectRoot??process.cwd()),r=e.now??(()=>new Date().toISOString()),o=r(),n=ge(e.runnerId??_e(t)),a=Se(e.sessionId)??Ce(t),s=Ae(t,e),{workspaceId:u,workspaceLabel:l,projectId:c,projectLabel:y}=s,h=e.mode??"background",C=[],S=[],L={heartbeat:!1};let b;try{b=await ce({projectRoot:t,adapter:e.adapter,adapterLoader:e.adapterLoader,now:r});const I=new de(b,r,G(t)).collectSnapshot({nowIso:o,jobLimit:_(e.jobLimit??20,1,50),dueJobLimit:20,eventLimit:1,receiptLimit:1,staleLeaseLimit:20,processingSummaryLimit:1,snapshotLimit:1}),k=e.httpClient?e.authToken:await ee(e),H=e.httpClient??Ee(X(e),k),p=Le(e.clientVersion??$,k),v=Ie(I,{runnerId:n,sessionId:a,identity:s,generatedAt:o,schedulerState:e.schedulerState??"unknown",clientVersion:e.clientVersion??$}),j=await F(H,{method:"POST",path:"/api/v1/continuity/runner/heartbeat",body:v,headers:p},{timeoutMs:e.timeoutMs??e.heartbeatTimeoutMs??Je});j.ok?L.heartbeat=!0:C.push(j.reasonCode);const w=bt(I,S.length);return{ok:L.heartbeat,runnerId:n,sessionId:a,workspaceId:u,workspaceLabel:l,projectId:c,projectLabel:y,mode:h,generatedAt:o,serverAccessToLocalhost:!1,serverHeldStream:!1,localhostCallback:!1,posted:L,counts:w,reasonCodes:Y(C.length>0?C:[d.OK]),redactionEvidence:S,publicSafe:!0}}catch(f){const I=ke(f);return{ok:!1,runnerId:n,sessionId:a,workspaceId:u,workspaceLabel:l,projectId:c,projectLabel:y,mode:h,generatedAt:o,serverAccessToLocalhost:!1,serverHeldStream:!1,localhostCallback:!1,posted:L,counts:{redactions:S.length},reasonCodes:[I],redactionEvidence:S,publicSafe:!0}}finally{b?.close()}}async function Ze(e={}){const t=ae(e.projectRoot??process.cwd()),r=e.now??(()=>new Date().toISOString()),o=r(),n=ge(e.runnerId??_e(t)),a=Se(e.sessionId)??Ce(t),s=Ae(t,e),{workspaceId:u,workspaceLabel:l,projectId:c,projectLabel:y}=s,h=e.mode??"manual",C=[],S=[],L=[],b={heartbeat:!1,runnerSync:!1,commandAcks:0},f={polled:0,applied:0,alreadyApplied:0,rejected:0,expired:0,failedLocal:0};let I;try{I=await ce({projectRoot:t,adapter:e.adapter,adapterLoader:e.adapterLoader,now:r});const k=I.compactPublicReceiptsAndOutputs({nowIso:o,policy:e.retentionPolicy}),p=new de(I,r,G(t)).collectSnapshot({nowIso:o,jobLimit:_(e.jobLimit??50,1,50),dueJobLimit:50,eventLimit:_(e.eventLimit??50,1,100),receiptLimit:_(e.receiptLimit??50,1,100),staleLeaseLimit:20,processingSummaryLimit:20,snapshotLimit:10}),v=At(p,o),j=e.httpClient??Ee(X(e),await ee(e)),w=Le(e.clientVersion??$,e.httpClient?e.authToken:await ee(e)),re=Ie(p,{runnerId:n,sessionId:a,identity:s,generatedAt:o,schedulerState:e.schedulerState??"unknown",clientVersion:e.clientVersion??$}),oe=await F(j,{method:"POST",path:"/api/v1/continuity/runner/heartbeat",body:re,headers:w});oe.ok?b.heartbeat=!0:C.push(oe.reasonCode);const Ne=tt(p,{runnerId:n,identity:s,generatedAt:o,previousSyncCursor:e.syncCursor,nextSyncCursor:v,heartbeat:re}),E=rt(I,p,{runnerId:n,identity:s,generatedAt:o,previousSyncCursor:e.syncCursor,nextSyncCursor:v}),B=E.status==="acked"&&E.replay?{ok:!0,body:{reasonCode:d.IDEMPOTENCY_REPLAY,publicSafe:!0}}:E.status==="conflict"||E.status==="dead_letter"?{ok:!1,reasonCode:E.reasonCode??d.BACKOFF_SCHEDULED}:await F(j,{method:"POST",path:"/api/v1/continuity/jobs/sync",body:Ne,headers:w});B.ok?(b.runnerSync=!0,I.ackOutbox({outboxId:E.outboxId,deliveryCursor:E.deliveryCursor,ackedAt:r(),reasonCode:d.OK})):(C.push(B.reasonCode),I.failOutboxDelivery({outboxId:E.outboxId,deliveryCursor:E.deliveryCursor,failedAt:r(),reasonCode:B.reasonCode,summary:"Runner sync delivery failed with a public reason code and will retry or dead-letter by policy.",policy:{maxAttempts:3}}));const z=await F(j,{method:"GET",path:"/api/v1/continuity/runner/commands",query:{runnerId:n,workspaceId:u,workspaceLabel:l,projectId:c,projectLabel:y},headers:w});if(z.ok){const ne=mt(z.body).slice(0,_(e.commandLimit??20,1,20));f.polled=ne.length;for(const De of ne){const R=await We({store:I,http:j,headers:w,rawCommand:De,runnerId:n,identity:s,nowIso:r()});L.push(R),b.commandAcks+=1,R.localStatus==="applied"?f.applied+=1:R.localStatus==="already_applied"?f.alreadyApplied+=1:R.localStatus==="rejected"?f.rejected+=1:R.localStatus==="expired"?f.expired+=1:f.failedLocal+=1,S.push(...R.redactionEvidence),C.push(R.reasonCode)}}else C.push(z.reasonCode);const Oe={jobs:p.counts.jobs??p.jobs.length,dueJobs:p.dueJobCount,receipts:p.counts.receipts??p.lastReceipts.length,events:p.counts.events??p.lastEvents.length,commandsPolled:f.polled,commandAcks:b.commandAcks,commandApplied:f.applied,commandAlreadyApplied:f.alreadyApplied,commandRejected:f.rejected,commandExpired:f.expired,commandFailedLocal:f.failedLocal,receiptCompactionSummaries:k.counts.summariesCreated,receiptsCompacted:k.counts.receiptsRemoved,processingSummariesCompacted:k.counts.outputsRemoved,redactions:S.length,...N(p)},Pe=Y(C.length>0?C:[d.OK]);return{ok:b.heartbeat&&b.runnerSync&&f.failedLocal===0,runnerId:n,sessionId:a,workspaceId:u,workspaceLabel:l,projectId:c,projectLabel:y,mode:h,generatedAt:o,serverAccessToLocalhost:!1,serverHeldStream:!1,localhostCallback:!1,posted:b,commandPoll:f,sync:{...e.syncCursor?{previousSyncCursor:e.syncCursor}:{},nextSyncCursor:v,counts:Oe},commandAcks:L,reasonCodes:Pe,redactionEvidence:S.slice(0,50),publicSafe:!0}}catch(k){const H=ke(k);return{ok:!1,runnerId:n,sessionId:a,workspaceId:u,workspaceLabel:l,projectId:c,projectLabel:y,mode:h,generatedAt:o,serverAccessToLocalhost:!1,serverHeldStream:!1,localhostCallback:!1,posted:b,commandPoll:f,sync:{nextSyncCursor:`sync-${A(o).slice(0,24)}`,counts:{commandAcks:0}},commandAcks:L,reasonCodes:[H],redactionEvidence:S,publicSafe:!0}}finally{I?.close()}}async function vt(e={}){const t=_(e.maxRuns??1,1,1e4),r=_(e.intervalMs??6e4,0,1440*60*1e3),o=[];let n=e.syncCursor;for(let a=0;a<t;a++){const s=await Ze({...e,mode:e.mode??"background",syncCursor:n});o.push(s),n=s.sync.nextSyncCursor,a<t-1&&r>0&&await xe(r)}return{ok:o.every(a=>a.ok),runs:o,reasonCodes:Y(o.flatMap(a=>a.reasonCodes)),publicSafe:!0}}async function $t(e={}){const t=_(e.maxRuns??1,1,1e4),r=_(e.intervalMs??He,0,1440*60*1e3),o=_(e.backoffMs??Ve,1e3,1800*1e3),n=Te(e.jitterRatio??Ye,0,.5),a=e.random??Math.random,s=[];for(let u=0;u<t;u++){const l=await Ge({...e,mode:e.mode??"background"});if(s.push(l),u<t-1){const c=l.ok?r:o,y=ht(c,n,a);y>0&&await xe(y)}}return{ok:s.every(u=>u.ok),runs:s,reasonCodes:Y(s.flatMap(u=>u.reasonCodes)),schedule:{intervalMs:r,backoffMs:o,jitterRatio:n,maxRuns:t},publicSafe:!0}}async function We(e){const t=ft(e.rawCommand);if(!t.ok||!t.command)return Xe(e.store,t,e.runnerId,e.nowIso),T(e.http,e.headers,{commandId:t.commandId??`pcmd-${A("invalid-command").slice(0,16)}`,jobId:t.jobId,action:t.action,runnerId:e.runnerId,identity:e.identity,idempotencyKey:`invalid:${t.commandId??"unknown"}`,localStatus:"rejected",remoteStatus:"rejected",reasonCode:d.PORTAL_COMMAND_PAYLOAD_REJECTED,publicSummary:"Runner rejected unsafe Portal command before local application.",acknowledgedAt:e.nowIso,redactionEvidence:t.redactions,counts:{rejected:1,redactions:t.redactions.length}});const r=t.command,o=U(r.commandId),n={commandId:r.commandId,jobId:r.jobId,action:r.action,runnerId:e.runnerId,identity:e.identity,idempotencyKey:r.idempotencyKey,acknowledgedAt:e.nowIso,redactionEvidence:t.redactions};if(r.expiresAt&&Date.parse(r.expiresAt)<=Date.parse(e.nowIso))return Q(e.store,r,{operationId:o,status:"ignored",reasonCode:d.COMMAND_EXPIRED,createdAt:e.nowIso,summary:"Portal command expired before local application.",redactionEvidence:t.redactions}),T(e.http,e.headers,{...n,localStatus:"expired",remoteStatus:"expired",reasonCode:d.COMMAND_EXPIRED,publicSummary:"Runner skipped expired Portal command.",counts:{expired:1}});if(e.store.hasOperationRef(o,r.idempotencyKey))return et(e.store,r,o,e.runnerId,e.nowIso,t.redactions),T(e.http,e.headers,{...n,localStatus:"already_applied",remoteStatus:"applied",reasonCode:d.IDEMPOTENCY_REPLAY,publicSummary:"Runner already applied Portal command; duplicate poll was acknowledged without local mutation.",counts:{alreadyApplied:1}});if(!e.store.jobExists(r.jobId))return T(e.http,e.headers,{...n,localStatus:"failed-local",remoteStatus:"rejected",reasonCode:d.INVALID_STATE_TRANSITION,publicSummary:"Runner could not find the public job for Portal command application.",counts:{failedLocal:1}});try{const a=be(r);return e.store.runInTransaction(()=>{Qe(e.store,r,e.nowIso),e.store.appendEvent({eventId:`${o}:event`,jobId:r.jobId,operationId:o,idempotencyKey:r.idempotencyKey,type:"portal_command_applied",summary:`Portal command ${r.action} applied locally by runner.`,reasonCode:a,createdAt:e.nowIso,metadata:x(r,o,e.runnerId,"applied",e.nowIso,t.redactions,a)}),e.store.appendReceipt({receiptId:`receipt-${o}`,jobId:r.jobId,operationId:o,idempotencyKey:r.idempotencyKey,status:"applied",reasonCode:a,appliedOperationIds:[o],createdAt:e.nowIso,metadata:x(r,o,e.runnerId,"applied",e.nowIso,t.redactions,a)})}),T(e.http,e.headers,{...n,localStatus:"applied",remoteStatus:"applied",reasonCode:a,publicSummary:`Runner applied Portal command ${r.action} locally.`,counts:{applied:1}})}catch{return Q(e.store,r,{operationId:o,status:"failed",reasonCode:d.INVALID_STATE_TRANSITION,createdAt:e.nowIso,summary:"Portal command failed local application with public reason code.",redactionEvidence:t.redactions}),T(e.http,e.headers,{...n,localStatus:"failed-local",remoteStatus:"rejected",reasonCode:d.INVALID_STATE_TRANSITION,publicSummary:"Runner failed local Portal command application with public reason code.",counts:{failedLocal:1}})}}function Qe(e,t,r){switch(t.action){case"pause":e.updateJobAndExistingGoalCampaignStatus({jobId:t.jobId,status:"paused",updatedAt:r,reasonCode:d.WAITING_HUMAN});return;case"resume":case"approve_review_gate":e.updateJobAndExistingGoalCampaignStatus({jobId:t.jobId,status:"active",updatedAt:r,reasonCode:d.OK});return;case"cancel":case"deny_review_gate":e.updateJobAndExistingGoalCampaignStatus({jobId:t.jobId,status:"cancelled",updatedAt:r,reasonCode:d.JOB_CANCELLED});return;case"answer_decision":if(t.decision?.option==="approve"){e.updateJobAndExistingGoalCampaignStatus({jobId:t.jobId,status:"active",updatedAt:r,reasonCode:d.OK});return}if(t.decision?.option==="deny"){e.updateJobAndExistingGoalCampaignStatus({jobId:t.jobId,status:"cancelled",updatedAt:r,reasonCode:d.JOB_CANCELLED});return}if(t.decision?.option==="hold"){e.updateJobAndExistingGoalCampaignStatus({jobId:t.jobId,status:"blocked",updatedAt:r,reasonCode:d.WAITING_HUMAN});return}throw new Error("unsupported-review-gate-decision");case"run_once":case"retry":e.scheduleNextTick({jobId:t.jobId,scheduledAt:r,updatedAt:r,reasonCode:d.OK});return;case"snapshot":e.recordStateSnapshot({snapshotId:`snapshot-${U(t.commandId)}`,jobId:t.jobId,kind:"portal_command_snapshot",summary:"Portal snapshot command recorded public local state checkpoint request.",capturedAt:r,operationId:U(t.commandId),idempotencyKey:t.idempotencyKey,metadata:x(t,U(t.commandId),t.runnerId,"applied",r,[],d.OK)});return;default:throw new Error("unsupported-command-action")}}async function T(e,t,r){return await F(e,{method:"POST",path:`/api/v1/continuity/runner/commands/${encodeURIComponent(r.commandId)}/ack`,body:{status:r.remoteStatus,runnerId:r.runnerId,workspaceId:r.identity.workspaceId,workspaceLabel:r.identity.workspaceLabel,projectId:r.identity.projectId,projectLabel:r.identity.projectLabel,idempotencyKey:r.idempotencyKey,reasonCode:r.reasonCode,publicSummary:m(r.publicSummary,280),counts:Re(r.counts),redactionEvidence:r.redactionEvidence.slice(0,20),publicSafe:!0},headers:t}),{commandId:r.commandId,...r.jobId?{jobId:r.jobId}:{},workspaceId:r.identity.workspaceId,workspaceLabel:r.identity.workspaceLabel,projectId:r.identity.projectId,projectLabel:r.identity.projectLabel,...r.action?{action:r.action}:{},localStatus:r.localStatus,remoteStatus:r.remoteStatus,reasonCode:r.reasonCode,publicSummary:m(r.publicSummary,280),acknowledgedAt:r.acknowledgedAt,counts:r.counts,redactionEvidence:r.redactionEvidence.slice(0,20),publicSafe:!0}}function Q(e,t,r){try{if(!e.jobExists(t.jobId)||e.hasOperationRef(r.operationId,t.idempotencyKey))return;e.appendReceipt({receiptId:`receipt-${r.operationId}`,jobId:t.jobId,operationId:r.operationId,idempotencyKey:t.idempotencyKey,status:r.status,reasonCode:r.reasonCode,ignoredOperationIds:[r.operationId],createdAt:r.createdAt,metadata:x(t,r.operationId,t.runnerId,r.status,r.createdAt,r.redactionEvidence,r.reasonCode)}),e.appendEvent({eventId:`${r.operationId}:event`,jobId:t.jobId,operationId:`${r.operationId}:event`,idempotencyKey:`${t.idempotencyKey}:event`,type:r.status==="failed"?"portal_command_failed":"portal_command_rejected",summary:r.summary,reasonCode:r.reasonCode,createdAt:r.createdAt,metadata:x(t,r.operationId,t.runnerId,r.status,r.createdAt,r.redactionEvidence,r.reasonCode)})}catch{}}function Xe(e,t,r,o){if(!t.commandId||!pe.test(t.commandId)||!t.jobId||!J(t.jobId)||!t.action||!ue.has(t.action))return;const n={commandId:t.commandId,jobId:t.jobId,action:t.action,status:"queued",queuedAt:o,idempotencyKey:`rejected:${t.commandId}`,delivery:"runner_poll",runnerId:r,reasonCode:d.PORTAL_COMMAND_PAYLOAD_REJECTED,publicSafe:!0};Q(e,n,{operationId:`${U(t.commandId)}:rejected`,status:"ignored",reasonCode:d.PORTAL_COMMAND_PAYLOAD_REJECTED,createdAt:o,summary:"Runner rejected unsafe Portal command before local application.",redactionEvidence:t.redactions})}function et(e,t,r,o,n,a){const s=`${r}:replay`;try{if(!e.jobExists(t.jobId)||e.hasOperationRef(s,`${t.idempotencyKey}:replay`))return;e.appendEvent({eventId:`${s}:event`,jobId:t.jobId,operationId:s,idempotencyKey:`${t.idempotencyKey}:replay`,type:"portal_command_replay",summary:"Runner recorded idempotent Portal command replay without local mutation.",reasonCode:d.IDEMPOTENCY_REPLAY,createdAt:n,metadata:x(t,s,o,"already_applied",n,a,d.IDEMPOTENCY_REPLAY)})}catch{}}function Ie(e,t){const r=It(e),o=e.jobs.filter(s=>["planned","active","running","backoff","waiting_external","waiting_human"].includes(s.status)).map(s=>s.jobId).filter(J).slice(0,20),n=e.staleLeases.map(s=>s.leaseId).filter(P).slice(0,20),a=we(e.dueJobs.map(s=>s.nextRunAt).filter(s=>!!s));return{schemaVersion:M,contractVersion:K,runnerId:t.runnerId,...t.sessionId?{sessionId:t.sessionId}:{},workspaceId:t.identity.workspaceId,workspaceLabel:t.identity.workspaceLabel,projectId:t.identity.projectId,projectLabel:t.identity.projectLabel,status:r,observedAt:t.generatedAt,version:m(t.clientVersion,80),activeJobIds:o,leaseIds:n,...a?{nextTickAt:a}:{},schedulerState:t.schedulerState,doctorSummary:r==="degraded"?"Runner sync is degraded by public stale lease or retryable outbox counts.":"Runner sync heartbeat contains public local continuity summaries.",reasonCode:r==="degraded"?d.BACKOFF_SCHEDULED:d.OK,queue:{depth:e.queue.depth,queued:e.queue.queued,running:e.queue.running,retrying:e.queue.retrying,deadLetter:e.queue.deadLetter,capacity:e.queue.capacity,available:e.queue.available,backpressure:e.queue.backpressure,generatedAt:e.queue.generatedAt,...e.queue.nextRetryAt?{nextRetryAt:e.queue.nextRetryAt}:{},...e.queue.reasonCode?{reasonCode:q(e.queue.reasonCode)}:{},publicSafe:!0},metadata:{schemaVersion:M,contractVersion:K,transportKind:"runner_heartbeat",...t.sessionId?{sessionId:t.sessionId}:{},workspaceId:t.identity.workspaceId,workspaceLabel:t.identity.workspaceLabel,projectId:t.identity.projectId,projectLabel:t.identity.projectLabel,observedAt:t.generatedAt,serverAccessToLocalhost:!1,serverHeldStream:!1,counts:{jobs:e.counts.jobs??e.jobs.length,dueJobs:e.dueJobCount,activeLeases:e.counts.activeLeases??0,staleLeases:e.counts.staleLeases??e.staleLeases.length,outboxPending:e.outbox.pending??0,outboxFailed:(e.outbox.failed??0)+(e.outbox.deadLetter??0),...N(e)},reasonCodes:[r==="degraded"?d.BACKOFF_SCHEDULED:d.OK],publicSummary:"Runner heartbeat generated from local continuity SQLite public summaries."},publicSafe:!0}}function tt(e,t){const r=e.jobs.map(s=>dt(s,t.identity,e)).slice(0,50),o=[...e.lastEvents.map(it),...(e.headlessExecutionAttempts??[]).map(ut)].slice(0,100),n=e.lastReceipts.map(lt).slice(0,100),a=yt(e,t.generatedAt);return{runnerId:t.runnerId,workspaceId:t.identity.workspaceId,workspaceLabel:t.identity.workspaceLabel,projectId:t.identity.projectId,projectLabel:t.identity.projectLabel,runner:{...t.heartbeat,metadata:{schemaVersion:M,contractVersion:K,syncVersion:Z,transportKind:"runner_sync",workspaceId:t.identity.workspaceId,workspaceLabel:t.identity.workspaceLabel,projectId:t.identity.projectId,projectLabel:t.identity.projectLabel,syncCursor:t.previousSyncCursor??"sync-initial",nextSyncCursor:t.nextSyncCursor,generatedAt:t.generatedAt,serverAccessToLocalhost:!1,serverHeldStream:!1,counts:{jobs:r.length,events:o.length,receipts:n.length,outbox:a.length,headlessExecutionAttempts:e.headlessExecutionAttempts?.length??0,...N(e)},publicSummary:"Runner sync uploaded public job, event and receipt summaries."}},jobs:r,events:o,receipts:n,outbox:a,runnerSync:{runnerId:t.runnerId,workspaceId:t.identity.workspaceId,workspaceLabel:t.identity.workspaceLabel,projectId:t.identity.projectId,projectLabel:t.identity.projectLabel,syncCursor:t.previousSyncCursor??"sync-initial",nextSyncCursor:t.nextSyncCursor,generatedAt:t.generatedAt,publicSummary:"Runner sync uploaded public job, event and receipt summaries.",counts:{jobs:r.length,events:o.length,receipts:n.length,outbox:a.length,...N(e)},publicSafe:!0}}}function rt(e,t,r){const o=ot({runnerId:r.runnerId,workspaceId:r.identity.workspaceId,projectId:r.identity.projectId,nextSyncCursor:r.nextSyncCursor}),n=nt({runnerId:r.runnerId,workspaceId:r.identity.workspaceId,projectId:r.identity.projectId,nextSyncCursor:r.nextSyncCursor});return e.enqueueOutbox({outboxId:o,jobId:st(t),operationId:`op-${o}`,idempotencyKey:`idem-${o}`,type:"runner_sync",status:"pending",payload:at(t,r),createdAt:r.generatedAt,updatedAt:r.generatedAt}),e.markOutboxSent({outboxId:o,deliveryCursor:n,sentAt:r.generatedAt,reasonCode:d.OK})}function ot(e){return`outbox-runner-sync-${A(`${e.runnerId}:${e.workspaceId}:${e.projectId??"project"}:${e.nextSyncCursor}`).slice(0,32)}`}function nt(e){return`cursor-runner-sync-${A(`${e.workspaceId}:${e.projectId??"project"}:${e.runnerId}:${e.nextSyncCursor}`).slice(0,32)}`}function at(e,t){return{schemaVersion:M,contractVersion:K,syncVersion:Z,transportKind:"runner_sync",envelopeId:`runner-sync-${A(`${t.runnerId}:${t.nextSyncCursor}`).slice(0,24)}`,runnerId:t.runnerId,workspaceId:t.identity.workspaceId,workspaceLabel:t.identity.workspaceLabel,projectId:t.identity.projectId,projectLabel:t.identity.projectLabel,syncCursor:t.previousSyncCursor??"sync-initial",nextSyncCursor:t.nextSyncCursor,generatedAt:t.generatedAt,serverAccessToLocalhost:!1,serverHeldStream:!1,counts:{jobs:e.counts.jobs??e.jobs.length,events:e.counts.events??e.lastEvents.length,receipts:e.counts.receipts??e.lastReceipts.length,outboxPending:e.outbox.pending??0,outboxFailed:e.outbox.failed??0,outboxDeadLetter:e.outbox.deadLetter??0,headlessExecutionAttempts:e.headlessExecutionAttempts?.length??0,...N(e)},redactionEvidence:[{field:"runnerSyncBody",reason:"unbounded_text",evidence:"operation-denied",publicSafe:!0}],publicSummary:"Runner sync outbox stores public IDs, counts, redaction evidence and cursor state only."}}function st(e){return e.jobs.map(t=>t.jobId).find(J)}function dt(e,t,r){const o=Me(e.currentStage)?e.currentStage:void 0,n=Fe(e.stageHistory),a=Ue(e.iteration),s=ct(e.jobId,r);return{jobId:e.jobId,workspaceId:t.workspaceId,workspaceLabel:t.workspaceLabel,projectId:t.projectId,projectLabel:t.projectLabel,kind:Lt(e.kind),status:kt(e.status),publicSummary:m(e.publicSummary,240),updatedAt:e.updatedAt,...e.nextRunAt?{nextRunAt:e.nextRunAt}:{},...e.reasonCode?{reasonCode:q(e.reasonCode)}:{},...e.counts?{counts:Re(e.counts)}:{},...s?{operations:s}:{},...o?{currentStage:o}:{},...n.length>0?{stageHistory:n}:{},...a!==void 0?{iteration:a}:{},publicSafe:!0}}function ct(e,t){const r=(t.headlessExecutionAttempts??[]).filter(c=>c.jobId===e).slice(0,50),o=t.staleLeases.filter(c=>c.jobId===e).slice(0,50);if(r.length===0&&o.length===0)return;const n=r.filter(c=>c.status==="backoff"||c.retryCount>0&&!!c.nextRetryAt).length,a=r.filter(c=>!!c.deadLetteredAt||c.status==="dead_letter").length,s=r.filter(c=>["queued","pending","backoff"].includes(c.status)).length,u=we(r.map(c=>c.nextRetryAt).filter(c=>!!c)),l=[...r].map(c=>c.leaseExpiresAt).filter(c=>!!c).sort().at(-1);return{attempts:r.length,retries:r.reduce((c,y)=>c+Math.max(0,Math.trunc(y.retryCount)),0),retrying:n,deadLetter:a,activeLeases:r.filter(c=>!!c.leaseId&&c.status==="running").length,staleLeases:o.length,queueDepth:s,backpressure:t.queue.backpressure&&s>0,generatedAt:t.generatedAt,...u?{nextRetryAt:u}:{},...l?{latestLeaseExpiresAt:l}:{},publicSafe:!0}}function it(e){return{eventId:e.eventId,jobId:e.jobId,operationId:e.operationId,type:m(e.type,80),summary:m(e.publicSummary,240),publicSummary:m(e.publicSummary,240),createdAt:e.createdAt,...e.metadata?{metadata:e.metadata}:{},...e.reasonCode?{reasonCode:q(e.reasonCode)}:{},publicSafe:!0}}function ut(e){return{eventId:`headless-${O(e.attemptId)}`,jobId:e.jobId,operationId:e.executionId,type:"headless_execution_attempt",summary:m(e.publicSummary,240),publicSummary:m(e.publicSummary,240),createdAt:e.heartbeatAt??e.enqueuedAt,...e.reasonCode?{reasonCode:q(e.reasonCode)}:{},publicSafe:!0}}function lt(e){return{receiptId:e.receiptId,jobId:e.jobId,...e.operationId?{operationId:e.operationId}:{},status:gt(e.status),summary:`Runner receipt ${e.status} for ${e.jobId}.`,createdAt:e.createdAt,...e.reasonCode?{reasonCode:q(e.reasonCode)}:{},publicSafe:!0}}function yt(e,t){const r=[];for(const[o,n]of Object.entries(e.outbox))o==="total"||!Number.isFinite(n)||n<=0||r.push({outboxId:`outbox-${o}`,operationId:`outbox-${o}-${A(t).slice(0,12)}`,status:o==="failed"||o==="deadLetter"?"failed":o==="acked"||o==="sent"?"applied":"accepted",summary:`Outbox ${o} count ${Math.trunc(n)} synced as public status evidence.`,updatedAt:t,reasonCode:o==="failed"||o==="deadLetter"?d.BACKOFF_SCHEDULED:d.OK,counts:{[o]:Math.trunc(n)},publicSafe:!0});return r.slice(0,20)}function ft(e){const t=[];if(!D(e))return t.push(i("command","unsafe_key","operation-denied")),{ok:!1,reasonCode:d.UNSAFE_FIELD_REJECTED,redactions:t};for(const y of Object.keys(e))(!le.has(y)||W.test(y))&&t.push(i(`command.${m(y,80)}`,"unsafe_key","key-denied"));for(const[y,h]of Object.entries(e))le.has(y)&&te(h,`command.${y}`,t);const r=typeof e.commandId=="string"?e.commandId:void 0,o=typeof e.jobId=="string"?e.jobId:void 0,n=typeof e.action=="string"?e.action:void 0,a=typeof e.status=="string"?e.status:void 0,s=typeof e.queuedAt=="string"?e.queuedAt:void 0,u=typeof e.idempotencyKey=="string"?e.idempotencyKey:void 0,l=typeof e.delivery=="string"?e.delivery:void 0;(!r||!pe.test(r))&&t.push(i("command.commandId","unsafe_key")),(!o||!J(o))&&t.push(i("command.jobId","unsafe_key")),(!n||!ue.has(n))&&t.push(i("command.action","unsafe_key")),a!=="queued"&&t.push(i("command.status","unsafe_key"));const c=pt(e.decision,n,t);return(!s||!Number.isFinite(Date.parse(s)))&&t.push(i("command.queuedAt","unsafe_key")),(!u||!P(u))&&t.push(i("command.idempotencyKey","unsafe_key")),l!=="runner_poll"&&t.push(i("command.delivery","unsafe_key")),e.publicSafe!==!0&&t.push(i("command.publicSafe","unsafe_key")),typeof e.expiresAt=="string"&&!Number.isFinite(Date.parse(e.expiresAt))&&t.push(i("command.expiresAt","unsafe_key")),typeof e.workspaceId=="string"&&!P(e.workspaceId)&&t.push(i("command.workspaceId","unsafe_key")),typeof e.workspaceLabel=="string"&&!je(e.workspaceLabel)&&t.push(i("command.workspaceLabel","unsafe_key")),typeof e.runnerId=="string"&&!fe.test(e.runnerId)&&t.push(i("command.runnerId","unsafe_key")),typeof e.projectId=="string"&&!P(e.projectId)&&t.push(i("command.projectId","unsafe_key")),typeof e.projectLabel=="string"&&!je(e.projectLabel)&&t.push(i("command.projectLabel","unsafe_key")),typeof e.reasonCode=="string"&&!V.test(e.reasonCode)&&t.push(i("command.reasonCode","unsafe_key")),t.length>0||!r||!o||!n||!s||!u||!l?{ok:!1,commandId:r,jobId:o,action:n,reasonCode:d.UNSAFE_FIELD_REJECTED,redactions:Et(t)}:{ok:!0,command:{commandId:r,jobId:o,action:n,...c?{decision:c}:{},status:a??"queued",queuedAt:s,...typeof e.expiresAt=="string"?{expiresAt:e.expiresAt}:{},idempotencyKey:u,delivery:l??"runner_poll",...typeof e.workspaceId=="string"?{workspaceId:e.workspaceId}:{},...typeof e.workspaceLabel=="string"?{workspaceLabel:e.workspaceLabel}:{},...typeof e.runnerId=="string"?{runnerId:e.runnerId}:{},...typeof e.projectId=="string"?{projectId:e.projectId}:{},...typeof e.projectLabel=="string"?{projectLabel:e.projectLabel}:{},...typeof e.reasonCode=="string"?{reasonCode:e.reasonCode}:{},publicSafe:!0},reasonCode:d.OK,redactions:[]}}function pt(e,t,r){if(t!=="answer_decision"&&t!=="approve_review_gate"&&t!=="deny_review_gate"){e!==void 0&&r.push(i("command.decision","unsafe_key"));return}if(e===void 0){t==="answer_decision"&&r.push(i("command.decision","unsafe_key"));return}if(!D(e)){r.push(i("command.decision","unsafe_key"));return}for(const n of Object.keys(e))(!qe.has(n)||W.test(n))&&r.push(i(`command.decision.${m(n,80)}`,"unsafe_key","key-denied"));const o=typeof e.option=="string"?e.option:void 0;if((!o||!ie.has(o))&&r.push(i("command.decision.option","unsafe_key")),typeof e.decisionId=="string"&&!P(e.decisionId)&&r.push(i("command.decision.decisionId","unsafe_key")),typeof e.gateId=="string"&&!P(e.gateId)&&r.push(i("command.decision.gateId","unsafe_key")),t==="approve_review_gate"&&o!=="approve"&&r.push(i("command.decision.option","unsafe_key")),t==="deny_review_gate"&&o!=="deny"&&r.push(i("command.decision.option","unsafe_key")),!(!o||!ie.has(o)))return{option:o,...typeof e.decisionId=="string"?{decisionId:e.decisionId}:{},...typeof e.gateId=="string"?{gateId:e.gateId}:{},publicSafe:!0}}function mt(e){return D(e)?Array.isArray(e.commands)?e.commands:[]:[]}function x(e,t,r,o,n,a,s){const u=s??be(e),l=r??e.runnerId;return{schemaVersion:M,contractVersion:K,syncVersion:Z,transportKind:"command_ack",actorType:"runner",...l?{actorId:l,runnerId:l}:{},jobId:e.jobId,...e.workspaceId?{workspaceId:e.workspaceId}:{},...e.workspaceLabel?{workspaceLabel:e.workspaceLabel}:{},...e.projectId?{projectId:e.projectId}:{},...e.projectLabel?{projectLabel:e.projectLabel}:{},operationId:t,idempotencyKey:e.idempotencyKey,commandId:e.commandId,commandKind:e.action,...e.decision?{decisionOption:e.decision.option}:{},...e.decision?.decisionId?{decisionId:e.decision.decisionId}:{},...e.decision?.gateId?{gateId:e.decision.gateId}:{},commandStatus:o,auditStatus:o,acknowledgedAt:n,reasonCode:u,redactionCount:a.length,redactionEvidence:a.slice(0,20),counts:{redactions:a.length},publicSummary:`Portal command ${e.action} ${o}.`}}function U(e){return`portal-command-${O(e)}`}function be(e){return e.action==="cancel"||e.action==="deny_review_gate"||e.action==="answer_decision"&&e.decision?.option==="deny"?d.JOB_CANCELLED:e.action==="pause"||e.action==="answer_decision"&&e.decision?.option==="hold"?d.WAITING_HUMAN:d.OK}function It(e){return(e.counts.staleLeases??0)>0||(e.outbox.failed??0)>0||(e.outbox.deadLetter??0)>0||e.queue.backpressure?"degraded":(e.counts.activeLeases??0)>0||e.dueJobCount>0||(e.counts.headlessRunningAttempts??0)>0?"busy":"idle"}function bt(e,t){return{jobs:e.counts.jobs??e.jobs.length,dueJobs:e.dueJobCount,activeLeases:e.counts.activeLeases??0,staleLeases:e.counts.staleLeases??e.staleLeases.length,headlessRunningAttempts:e.counts.headlessRunningAttempts??0,outboxPending:e.outbox.pending??0,outboxFailed:(e.outbox.failed??0)+(e.outbox.deadLetter??0),redactions:t,...N(e)}}function N(e){return{queueDepth:e.queue.depth,queueQueued:e.queue.queued,queueRunning:e.queue.running,queueRetrying:e.queue.retrying,queueDeadLetter:e.queue.deadLetter,queueCapacity:e.queue.capacity,queueAvailable:e.queue.available,queueBackpressure:e.queue.backpressure?1:0}}function At(e,t){return`sync-${A(JSON.stringify({generatedAt:t,counts:e.counts,outbox:e.outbox})).slice(0,24)}`}function Ae(e,t){const r=G(e),o=O(t.workspaceId??r.workspaceId),n=O(t.projectId??r.projectId),a=he(t.projectLabel??(t.projectId?void 0:r.projectLabel),t.projectId?`Project ${n}`:r.projectLabel),s=he(t.workspaceLabel??(t.workspaceId?void 0:r.workspaceLabel),t.workspaceId?`Workspace ${o}`:r.workspaceLabel);return{workspaceId:o,workspaceLabel:s,projectId:n,projectLabel:a}}function _e(e){return`runner-${A(e).slice(0,16)}`}function Ce(e){return`session-${A(`${e}:${process.pid}:${Be}`).slice(0,16)}`}function Se(e){if(!e)return;const t=O(e);return ye.test(t)?t.slice(0,96):void 0}function X(e){return(e.serverUrl??process.env.NEOCORTEX_SERVER_URL??se()?.serverUrl??$e).replace(/\/+$/,"")}async function ee(e){if(e.authToken)return e.authToken;if(e.httpClient)return;const t=X(e),r=e.licenseKey??se()?.licenseKey;if(r)return await new Ke({serverUrl:t,licenseKey:r,clientVersion:e.clientVersion??$}).getToken()??void 0}function Ee(e,t){return async r=>{if(!t)return{ok:!1,status:401,body:{reasonCode:d.AUTH_TOKEN_PERMISSION_FAILURE}};const o=new URL(`${e}${r.path}`);for(const[u,l]of Object.entries(r.query??{}))l!==void 0&&o.searchParams.set(u,l);const n=await fetch(o,{method:r.method,headers:r.headers,body:r.method==="POST"?JSON.stringify(r.body??{}):void 0}),a=await n.text().catch(()=>"");let s;try{s=a?JSON.parse(a):void 0}catch{s=void 0}return{ok:n.ok,status:n.status,body:s}}}function Le(e,t){return{"Content-Type":"application/json","X-Client-Version":m(e,80),...t?{Authorization:`Bearer ${t}`}:{}}}async function F(e,t,r={}){try{const o=_(r.timeoutMs??0,0,6e4),n=o>0?await Ct(e(t),o):await e(t);return n.ok?{ok:!0,body:n.body}:{ok:!1,reasonCode:_t(n.body,n.status),body:n.body}}catch{return{ok:!1,reasonCode:d.BACKOFF_SCHEDULED}}}function _t(e,t){if(D(e)){const r=typeof e.reasonCode=="string"?e.reasonCode:typeof e.error_code=="string"?e.error_code.toLowerCase().replaceAll("_","-"):void 0;if(r&&V.test(r))return r}return t===401||t===403?d.AUTH_TOKEN_PERMISSION_FAILURE:t===400?d.PORTAL_SYNC_PAYLOAD_REJECTED:d.BACKOFF_SCHEDULED}function ke(e){if(D(e)){const r=typeof e.reasonCode=="string"?e.reasonCode:typeof e.code=="string"?e.code:void 0;if(r&&V.test(r))return r}const t=e instanceof Error?e.message:String(e);return/sqlite-adapter-unavailable/i.test(t)?d.SQLITE_ADAPTER_UNAVAILABLE:/integrity|corrupt|malformed|not a database/i.test(t)?d.SQLITE_INTEGRITY_FAILED:d.BACKOFF_SCHEDULED}function Ct(e,t){return new Promise((r,o)=>{const n=setTimeout(()=>o(new Error("portal-http-timeout")),t);typeof n.unref=="function"&&n.unref(),e.then(a=>{clearTimeout(n),r(a)},a=>{clearTimeout(n),o(a)})})}function te(e,t,r){if(typeof e=="string"){g.test(e)&&r.push(i(t,St(e),"value-denied"));return}if(!(e===null||typeof e=="number"||typeof e=="boolean"||e===void 0)){if(Array.isArray(e)){for(const[o,n]of e.entries())te(n,`${t}.${o}`,r);return}if(D(e))for(const[o,n]of Object.entries(e)){const a=`${t}.${m(o,80)}`;W.test(o)&&r.push(i(a,"unsafe_key","key-denied")),te(n,a,r)}}}function St(e){return/https?:\/\//i.test(e)?"private_url":/(?:^|\s)(?:\/(?:home|Users|media|mnt|tmp|var|etc|private)\/\S+|[A-Za-z]:\\\S+)/i.test(e)?"local_absolute_path":/secret|token|password|api[_-]?key|license[_-]?key|authorization/i.test(e)?"secret":/stdout|stderr|raw[_-]?log|transcript|stack/i.test(e)?"raw_log":/prompt|workflow body|step body/i.test(e)?"prompt_body":"protected_field"}function i(e,t,r="value-denied"){return{field:m(e,120),reason:t,evidence:r,publicSafe:!0}}function Et(e){const t=new Set,r=[];for(const o of e){const n=`${o.field}:${o.reason}:${o.evidence}`;t.has(n)||(t.add(n),r.push(o))}return r.slice(0,20)}function ge(e){const t=O(e);return fe.test(t)?t:`runner-${A(e).slice(0,16)}`}function O(e){if(g.test(e))return`id-${A(e).slice(0,16)}`;const t=e.replace(/[^A-Za-z0-9._:-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,120);return t.length>0?t:`id-${A(e).slice(0,16)}`}function he(e,t){const r=(e??"").replace(/\s+/g," ").trim();if(!r||g.test(r)||me.test(r))return t;const o=r.replace(/[^A-Za-z0-9 ._-]+/g," ").replace(/\s+/g," ").trim();return o?o.length<=80?o:`${o.slice(0,77)}...`:t}function P(e){return ye.test(e)&&!g.test(e)}function je(e){return e.trim().length>0&&e.length<=80&&!g.test(e)&&!me.test(e)}function J(e){return ze.test(e)&&!g.test(e)}function q(e){return V.test(e)&&!g.test(e)?e:d.OK}function Lt(e){return["goal","loop","runner","jobs"].includes(e)?e:"jobs"}function kt(e){return["draft","planned","active","running","waiting_external","waiting_human","backoff","paused","blocked","completed","aborted","cancelled"].includes(e)?e:"active"}function gt(e){return["accepted","applied","ignored","failed","deferred"].includes(e)?e:"accepted"}function Re(e){const t={};for(const[r,o]of Object.entries(e))/^[A-Za-z][A-Za-z0-9_:-]{0,63}$/.test(r)&&Number.isFinite(o)&&o>=0&&(t[r]=Math.trunc(o));return t}function we(e){return e.filter(t=>Number.isFinite(Date.parse(t))).sort()[0]}function _(e,t,r){return Number.isFinite(e)?Math.max(t,Math.min(r,Math.floor(e))):t}function Te(e,t,r){return Number.isFinite(e)?Math.max(t,Math.min(r,e)):t}function ht(e,t,r){if(e<=0)return 0;if(t<=0)return e;const o=Te(r(),0,1),n=Math.floor(e*t*o);return Math.max(0,e+n)}function A(e){return ve("sha256").update(e).digest("hex")}function m(e,t){const r=g.test(e)?"[REDACTED]":e;return r.length<=t?r:`${r.slice(0,t)}...[TRUNCATED:${r.length-t}]`}function D(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Y(e){return Array.from(new Set(e))}function xe(e){return new Promise(t=>setTimeout(t,e))}export{Ve as DEFAULT_RUNNER_HEARTBEAT_BACKOFF_MS,He as DEFAULT_RUNNER_HEARTBEAT_INTERVAL_MS,Ye as DEFAULT_RUNNER_HEARTBEAT_JITTER_RATIO,Je as DEFAULT_RUNNER_HEARTBEAT_TIMEOUT_MS,d as RUNNER_PORTAL_SYNC_REASON_CODES,Ge as runRunnerPortalHeartbeat,$t as runRunnerPortalHeartbeatLoop,Ze as runRunnerPortalSync,vt as runRunnerPortalSyncLoop};