@ornexus/neocortex 4.60.73 → 4.60.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (241) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +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.js +1 -108
  22. package/packages/client/dist/cache/in-memory-asset-cache.js +1 -73
  23. package/packages/client/dist/cache/index.js +1 -13
  24. package/packages/client/dist/cache/protected-pi-boundary.js +1 -44
  25. package/packages/client/dist/checkpoint/checkpoint-client-reader.js +2 -127
  26. package/packages/client/dist/checkpoint/index.js +1 -11
  27. package/packages/client/dist/checkpoint/shared-checkpoint-types.js +1 -32
  28. package/packages/client/dist/cli.js +5 -358
  29. package/packages/client/dist/commands/activate.js +8 -394
  30. package/packages/client/dist/commands/architecture-answers.js +7 -274
  31. package/packages/client/dist/commands/architecture-memory-terminal.js +4 -253
  32. package/packages/client/dist/commands/architecture-non-ui-continuation.js +1 -100
  33. package/packages/client/dist/commands/architecture-root-binding.js +1 -51
  34. package/packages/client/dist/commands/cache-status.js +2 -112
  35. package/packages/client/dist/commands/config.js +1 -88
  36. package/packages/client/dist/commands/doctor.js +2 -635
  37. package/packages/client/dist/commands/invoke.js +143 -7200
  38. package/packages/client/dist/commands/legacy-epic-terminal.js +1 -71
  39. package/packages/client/dist/commands/legacy-story-branch.js +1 -96
  40. package/packages/client/dist/commands/legacy-story-pr.js +1 -276
  41. package/packages/client/dist/commands/mutation-qa-checkpoint.js +5 -285
  42. package/packages/client/dist/commands/mutation-qa-gate.js +1 -54
  43. package/packages/client/dist/commands/mutation-qa-git.js +1 -41
  44. package/packages/client/dist/commands/mutation-qa-policy.js +1 -102
  45. package/packages/client/dist/commands/mutation-qa-run.js +3 -219
  46. package/packages/client/dist/commands/mutation-qa-verdict.js +1 -149
  47. package/packages/client/dist/commands/mutation-qa.js +1 -220
  48. package/packages/client/dist/commands/native-agent.js +2 -136
  49. package/packages/client/dist/commands/planning-diagnosis.js +1 -43
  50. package/packages/client/dist/commands/planning-generation.js +1 -53
  51. package/packages/client/dist/commands/planning-memory.js +1 -40
  52. package/packages/client/dist/commands/planning-research.js +1 -42
  53. package/packages/client/dist/commands/private-session.js +1 -75
  54. package/packages/client/dist/commands/property-qa.js +1 -139
  55. package/packages/client/dist/commands/qa-control.js +1 -16
  56. package/packages/client/dist/commands/qa-scan-browser-launch.js +1 -55
  57. package/packages/client/dist/commands/qa-scan-browser-route.js +1 -28
  58. package/packages/client/dist/commands/qa-scan-capture.js +5 -663
  59. package/packages/client/dist/commands/qa-scan-discovery.js +3 -376
  60. package/packages/client/dist/commands/qa-scan-review.js +5 -826
  61. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +1 -266
  62. package/packages/client/dist/commands/qa-synthetic-backend-review.js +1 -297
  63. package/packages/client/dist/commands/qa-synthetic-backend.js +2 -340
  64. package/packages/client/dist/commands/qa-synthetic-broker-port.js +1 -85
  65. package/packages/client/dist/commands/qa-synthetic-browser.js +1 -39
  66. package/packages/client/dist/commands/refactor-characterization.js +21 -671
  67. package/packages/client/dist/commands/refactor-commit.js +13 -399
  68. package/packages/client/dist/commands/refactor-control.js +3 -142
  69. package/packages/client/dist/commands/refactor-cpp-assertions.js +3 -93
  70. package/packages/client/dist/commands/refactor-review.js +5 -283
  71. package/packages/client/dist/commands/refactor-root.js +7 -588
  72. package/packages/client/dist/commands/refresh-memory.js +3 -156
  73. package/packages/client/dist/commands/shared-architecture-non-ui.js +1 -24
  74. package/packages/client/dist/commands/story-checkpoint.js +1 -171
  75. package/packages/client/dist/config/profile-directory.js +1 -13
  76. package/packages/client/dist/config/resolver-selection.js +1 -278
  77. package/packages/client/dist/config/secure-config.js +12 -281
  78. package/packages/client/dist/config.js +2 -223
  79. package/packages/client/dist/constants.js +1 -25
  80. package/packages/client/dist/context/context-collector.js +2 -222
  81. package/packages/client/dist/context/context-sanitizer.js +1 -145
  82. package/packages/client/dist/continuity/autonomous-governance.js +1 -285
  83. package/packages/client/dist/continuity/continuity-client-state-store.js +1 -1587
  84. package/packages/client/dist/continuity/invoke-hooks.js +1 -129
  85. package/packages/client/dist/continuity/migrations/001-initial-schema.js +2 -12
  86. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +2 -12
  87. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +2 -12
  88. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +2 -12
  89. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +2 -12
  90. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +2 -10
  91. package/packages/client/dist/continuity/native-agent-store.js +1 -69
  92. package/packages/client/dist/continuity/native-agent-types.js +1 -90
  93. package/packages/client/dist/continuity/outbox.js +1 -117
  94. package/packages/client/dist/continuity/runner-bootstrap-policy.js +1 -172
  95. package/packages/client/dist/continuity/sqlite-store.js +81 -2612
  96. package/packages/client/dist/effects/invoke-effect-gateways.js +1 -62
  97. package/packages/client/dist/errors/error-messages.js +2 -228
  98. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -125
  99. package/packages/client/dist/evidence/collector.js +1 -347
  100. package/packages/client/dist/evidence/index.js +1 -1
  101. package/packages/client/dist/evidence/types.js +0 -2
  102. package/packages/client/dist/fs/atomic-state-replace.js +1 -152
  103. package/packages/client/dist/generated/command-registry.generated.js +1 -4076
  104. package/packages/client/dist/generated/public-projections.generated.js +1 -149
  105. package/packages/client/dist/git/direct-yolo-c01-retry.js +4 -138
  106. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -1234
  107. package/packages/client/dist/git/epic-operational-state.js +2 -672
  108. package/packages/client/dist/git/git-lifecycle-step-ids.js +1 -14
  109. package/packages/client/dist/git/git-lifecycle-store.d.ts +23 -0
  110. package/packages/client/dist/git/git-lifecycle-store.js +10 -1981
  111. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +9 -259
  112. package/packages/client/dist/git/legacy-story-branch-setup.js +4 -348
  113. package/packages/client/dist/git/legacy-story-pr.js +70 -3538
  114. package/packages/client/dist/git/secure-filesystem-boundary.js +5 -182
  115. package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -284
  116. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +1 -237
  117. package/packages/client/dist/i18n/first-run.js +2 -60
  118. package/packages/client/dist/index.js +1 -47
  119. package/packages/client/dist/invocation/invoke-input.js +1 -24
  120. package/packages/client/dist/license/index.js +1 -5
  121. package/packages/client/dist/license/license-client.js +1 -304
  122. package/packages/client/dist/machine/fingerprint.js +2 -163
  123. package/packages/client/dist/machine/index.js +1 -5
  124. package/packages/client/dist/memory/project-memory-path-scope.js +1 -62
  125. package/packages/client/dist/memory/project-memory-writer.js +40 -1007
  126. package/packages/client/dist/memory/shared-project-memory-types.js +2 -253
  127. package/packages/client/dist/migrations/epic-lifecycle-backfill.js +3 -1060
  128. package/packages/client/dist/migrations/project-identity-capability.js +1 -50
  129. package/packages/client/dist/migrations/project-identity.js +7 -493
  130. package/packages/client/dist/migrations/state-json.js +4 -393
  131. package/packages/client/dist/policy/architecture-policy.js +2 -184
  132. package/packages/client/dist/policy/index.js +1 -7
  133. package/packages/client/dist/policy/shared-policy-types.js +0 -38
  134. package/packages/client/dist/policy/subagent-approval-policy.js +1 -55
  135. package/packages/client/dist/private-execution/clean-baseline.js +2 -279
  136. package/packages/client/dist/private-execution/codex-executor.js +4 -574
  137. package/packages/client/dist/private-execution/codex-host-runtime.js +1 -137
  138. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +1 -97
  139. package/packages/client/dist/private-execution/codex-scoped-permissions.js +1 -128
  140. package/packages/client/dist/private-execution/delivery.js +13 -410
  141. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -294
  142. package/packages/client/dist/private-execution/frozen-handoff.js +6 -19
  143. package/packages/client/dist/private-execution/implementation-validation.js +2 -106
  144. package/packages/client/dist/private-execution/isolated-admission.js +23 -1432
  145. package/packages/client/dist/private-execution/isolated-session.js +5 -725
  146. package/packages/client/dist/private-execution/isolated-workspace.js +1 -122
  147. package/packages/client/dist/private-execution/pact-consumer-runtime.js +3 -409
  148. package/packages/client/dist/private-execution/pact-test-source.js +1 -258
  149. package/packages/client/dist/private-execution/pact-toolchain.js +3 -290
  150. package/packages/client/dist/private-execution/pact-write-set.js +1 -172
  151. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -406
  152. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +5 -462
  153. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +3 -139
  154. package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -325
  155. package/packages/client/dist/private-execution/private-report-store.js +1 -42
  156. package/packages/client/dist/private-execution/property-test-candidate.js +1 -103
  157. package/packages/client/dist/private-execution/property-test-choices.js +3 -147
  158. package/packages/client/dist/private-execution/property-test-plan.js +7 -271
  159. package/packages/client/dist/private-execution/property-test-review.js +4 -258
  160. package/packages/client/dist/private-execution/property-test-runtime.js +9 -372
  161. package/packages/client/dist/private-execution/property-test-source.js +1 -139
  162. package/packages/client/dist/private-execution/root-checkpoint.js +1 -80
  163. package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -135
  164. package/packages/client/dist/private-execution/root-memory-recovery.js +1 -93
  165. package/packages/client/dist/private-execution/root-memory-request.js +1 -29
  166. package/packages/client/dist/private-execution/root-memory-scope.js +1 -178
  167. package/packages/client/dist/private-execution/root-memory-writer.js +1 -102
  168. package/packages/client/dist/private-execution/session-lease.js +1 -63
  169. package/packages/client/dist/private-execution/shared-private-admission-types.js +1 -50
  170. package/packages/client/dist/private-execution/shared-project-validation.js +1 -66
  171. package/packages/client/dist/private-execution/shared-root-memory-types.js +1 -61
  172. package/packages/client/dist/private-execution/ux-source-validation.js +1 -372
  173. package/packages/client/dist/private-execution/ux-write-set.js +2 -191
  174. package/packages/client/dist/registry/registry-reconciliation.js +1 -234
  175. package/packages/client/dist/resilience/circuit-breaker.js +1 -170
  176. package/packages/client/dist/resilience/degradation-manager.js +1 -164
  177. package/packages/client/dist/resilience/freshness-indicator.js +1 -100
  178. package/packages/client/dist/resilience/index.js +1 -8
  179. package/packages/client/dist/resilience/recovery-detector.js +1 -74
  180. package/packages/client/dist/resolvers/asset-resolver.js +0 -13
  181. package/packages/client/dist/resolvers/local-resolver.js +8 -255
  182. package/packages/client/dist/resolvers/remote-resolver.js +1 -233
  183. package/packages/client/dist/runner/binary.js +1 -404
  184. package/packages/client/dist/runner/cli.js +17 -1571
  185. package/packages/client/dist/runner/headless/adapters.js +1 -49
  186. package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -79
  187. package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -1628
  188. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +1 -69
  189. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.d.ts +1 -1
  190. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +2 -110
  191. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +2 -0
  192. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -1236
  193. package/packages/client/dist/runner/headless/epic-terminal-git-runner.d.ts +18 -2
  194. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +2 -318
  195. package/packages/client/dist/runner/headless/fake-adapter.js +1 -62
  196. package/packages/client/dist/runner/headless/managed-profile.js +1 -132
  197. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -145
  198. package/packages/client/dist/runner/headless/prepared-story-bundle.js +1 -43
  199. package/packages/client/dist/runner/headless/resolver.js +1 -231
  200. package/packages/client/dist/runner/headless/run-yolo.js +1 -885
  201. package/packages/client/dist/runner/headless/run-yoloop.d.ts +1 -0
  202. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2574
  203. package/packages/client/dist/runner/headless/types.js +2 -574
  204. package/packages/client/dist/runner/local-console.js +13 -396
  205. package/packages/client/dist/runner/portal-sync-worker.js +1 -1487
  206. package/packages/client/dist/runner/project-identity.js +1 -106
  207. package/packages/client/dist/runner/scheduler.js +7 -995
  208. package/packages/client/dist/runner-cli.js +2 -18
  209. package/packages/client/dist/state/invocation-shape.js +1 -13
  210. package/packages/client/dist/state/project-state-snapshot.js +1 -1731
  211. package/packages/client/dist/state/state-json-repair.js +3 -785
  212. package/packages/client/dist/state/structural-dag-projection.js +1 -118
  213. package/packages/client/dist/telemetry/index.js +1 -5
  214. package/packages/client/dist/telemetry/offline-queue.js +1 -131
  215. package/packages/client/dist/tier/index.js +1 -5
  216. package/packages/client/dist/tier/tier-aware-client.js +1 -405
  217. package/packages/client/dist/types/index.js +1 -38
  218. package/packages/client/dist/version.js +1 -27
  219. package/packages/client/dist/yolo/change-evidence-collector.js +1 -126
  220. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -62
  221. package/packages/client/dist/yolo/spec-envelope-collector.js +5 -184
  222. package/packages/client/dist/yoloop/discovery-hook.js +2 -300
  223. package/packages/client/dist/yoloop/index.js +1 -8
  224. package/packages/client/dist/yoloop/invoke-hooks.js +12 -669
  225. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1007
  226. package/packages/client/dist/yoloop/shared-yoloop-types.js +1 -33
  227. package/packages/client/dist/yoloop/target-normalization.js +1 -180
  228. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1920
  229. package/packages/shared/dist/yolo/change-evidence.js +1 -1
  230. package/packages/shared/dist/yoloop/epic-terminal-git.js +144 -2
  231. package/targets-stubs/antigravity/gemini.md +1 -1
  232. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  233. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  234. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  235. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  236. package/targets-stubs/claude-code/neocortex.md +2 -2
  237. package/targets-stubs/codex/AGENTS.md +1 -1
  238. package/targets-stubs/cursor/agent.md +2 -2
  239. package/targets-stubs/gemini-cli/agent.md +2 -2
  240. package/targets-stubs/opencode/neocortex-root.md +1 -1
  241. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,995 +1,7 @@
1
- /**
2
- * @license FSL-1.1
3
- * Copyright (c) 2026 OrNexus AI
4
- *
5
- * P180.07 -- user-scope scheduler install/start/stop/status/doctor for
6
- * `neocortex-runner`.
7
- */
8
- import { Buffer } from 'node:buffer';
9
- import { spawnSync } from 'node:child_process';
10
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
11
- import { delimiter, dirname, isAbsolute, join, resolve } from 'node:path';
12
- import { checkRunnerBinaryTrust, resolveTrustedRunnerBinary, } from './binary.js';
13
- import { deriveProjectIdentity } from './project-identity.js';
14
- import { executeClosedGitInspection, executeSchedulerManifestWrite, executeSchedulerProcess, } from '../effects/invoke-effect-gateways.js';
15
- export const SCHEDULER_REASON_CODES = Object.freeze({
16
- OK: 'continuity-ok',
17
- SCHEDULER_INSTALL_UNSAFE: 'scheduler-install-unsafe',
18
- PRIMARY_USER_SCHEDULER_UNAVAILABLE: 'primary-user-scheduler-unavailable',
19
- SYSTEMD_USER_BUS_UNAVAILABLE: 'systemd-user-bus-unavailable',
20
- CRON_FALLBACK_SELECTED: 'cron-fallback-selected',
21
- CRON_FALLBACK_NOT_ALLOWED: 'cron-fallback-primary-scheduler-available',
22
- CRON_FALLBACK_NOT_PERMITTED: 'cron-fallback-not-permitted',
23
- SCHEDULER_UNAVAILABLE: 'scheduler-unavailable',
24
- SCHEDULER_COMMAND_FAILED: 'scheduler-command-failed',
25
- RUNNER_BINARY_UNTRUSTED: 'runner-binary-untrusted',
26
- LEGACY_GLOBAL_SCHEDULER_DETECTED: 'legacy-global-scheduler-detected',
27
- LEGACY_GLOBAL_SCHEDULER_AMBIGUOUS: 'legacy-global-scheduler-ambiguous',
28
- LEGACY_GLOBAL_SCHEDULER_OTHER_PROJECT: 'legacy-global-scheduler-other-project',
29
- });
30
- export const RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES = Object.freeze({
31
- OK: 'runner-bootstrap-ok',
32
- ALREADY_ACTIVE: 'runner-bootstrap-already-active',
33
- BINARY_UNAVAILABLE: 'runner-bootstrap-binary-unavailable',
34
- INSTALL_FAILED: 'runner-bootstrap-install-failed',
35
- START_FAILED: 'runner-bootstrap-start-failed',
36
- UNEXPECTED_ERROR: 'runner-bootstrap-unexpected-error',
37
- });
38
- /** Request-only observation: never exports subprocess output or scheduler paths. */
39
- export async function observeRunnerOperationalStatus(command, options = {}) {
40
- const report = await runRunnerSchedulerCommand({ ...options, command, trustCheck: false });
41
- const operational = Boolean(report.strategy);
42
- const knownCodes = new Set(Object.values(SCHEDULER_REASON_CODES));
43
- const reasonCodes = unique(report.reasonCodes.filter((code) => knownCodes.has(code) && (report.ok || code !== SCHEDULER_REASON_CODES.OK))).slice(0, 12);
44
- return {
45
- schemaVersion: 1,
46
- command,
47
- projectKey: report.identity.projectKey,
48
- platform: report.platform,
49
- ...(report.capability.primaryStrategy ? { primaryStrategy: report.capability.primaryStrategy } : {}),
50
- ...(report.strategy ? { selectedStrategy: report.strategy } : {}),
51
- operational,
52
- status: !operational ? 'unavailable' : command === 'doctor' ? 'available' : report.ok ? 'active' : 'inactive',
53
- reasonCodes,
54
- observedAt: new Date().toISOString(),
55
- publicSafe: true,
56
- };
57
- }
58
- const SCHEDULER_NAME_PREFIX = 'neocortex-runner';
59
- const LEGACY_SYSTEMD_SERVICE_FILE = `${SCHEDULER_NAME_PREFIX}.service`;
60
- const LEGACY_SYSTEMD_TIMER_FILE = `${SCHEDULER_NAME_PREFIX}.timer`;
61
- const LEGACY_LAUNCHD_LABEL = 'com.ornexus.neocortex.runner';
62
- const LEGACY_LAUNCHD_FILE = `${LEGACY_LAUNCHD_LABEL}.plist`;
63
- const LEGACY_WINDOWS_TASK_NAME = 'NeocortexRunner';
64
- const LEGACY_WINDOWS_XML_FILE = 'neocortex-runner-task.xml';
65
- const LEGACY_CRON_FILE = 'runner.cron';
66
- const DEFAULT_INTERVAL_SECONDS = 60;
67
- const runnerSchedulerBootstrapCache = new Map();
68
- export function createRunnerSchedulerIdentity(canonicalProjectRoot) {
69
- const safeRoot = safeAbsolutePath(canonicalProjectRoot) ?? resolve(canonicalProjectRoot || '.');
70
- const projectIdentity = deriveProjectIdentity(safeRoot);
71
- const projectBasename = projectIdentity.projectLabel;
72
- const projectKey = projectIdentity.projectId;
73
- const serviceBase = `${SCHEDULER_NAME_PREFIX}-${projectKey}`;
74
- const launchdLabel = `com.ornexus.neocortex.runner.${projectKey}`;
75
- return {
76
- projectKey,
77
- projectBasename,
78
- systemdServiceName: `${serviceBase}.service`,
79
- systemdTimerName: `${serviceBase}.timer`,
80
- systemdServiceFile: `${serviceBase}.service`,
81
- systemdTimerFile: `${serviceBase}.timer`,
82
- launchdLabel,
83
- launchdFile: `${launchdLabel}.plist`,
84
- windowsTaskName: `NeocortexRunner-${projectKey}`,
85
- windowsXmlFile: `${serviceBase}-task.xml`,
86
- cronFile: `runner-${projectKey}.cron`,
87
- cronMarkerStart: `# BEGIN neocortex-runner:${projectKey}`,
88
- cronMarkerEnd: `# END neocortex-runner:${projectKey}`,
89
- publicSafe: true,
90
- };
91
- }
92
- export function __resetRunnerSchedulerBootstrapCacheForTests() {
93
- runnerSchedulerBootstrapCache.clear();
94
- }
95
- export async function ensureRunnerSchedulerBootstrap(options = {}) {
96
- const platform = options.platform ?? process.platform;
97
- const projectRoot = safeAbsolutePath(options.projectRoot ?? process.cwd()) ?? process.cwd();
98
- const identity = createRunnerSchedulerIdentity(projectRoot);
99
- const cacheKey = `${platform}:${identity.projectKey}`;
100
- const cached = runnerSchedulerBootstrapCache.get(cacheKey);
101
- if (cached?.ok) {
102
- return {
103
- ...cached,
104
- attempted: false,
105
- installed: false,
106
- started: false,
107
- cached: true,
108
- reasonCodes: unique([...cached.reasonCodes, RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES.ALREADY_ACTIVE]),
109
- publicSummary: 'runner scheduler bootstrap already active for project key.',
110
- publicSafe: true,
111
- };
112
- }
113
- try {
114
- if (options.effectAuthority) {
115
- executeClosedGitInspection(options.effectAuthority, 'git-rev-parse', projectRoot, (profile) => {
116
- const inspected = spawnSync(profile.executable, [...profile.argv], {
117
- cwd: profile.cwd,
118
- env: { ...profile.env },
119
- shell: profile.shell,
120
- timeout: profile.timeoutMs,
121
- encoding: 'utf8',
122
- maxBuffer: 64 * 1024,
123
- });
124
- return {
125
- status: inspected.status,
126
- stdout: inspected.stdout ?? '',
127
- stderr: inspected.stderr ?? '',
128
- projected: false,
129
- };
130
- }, 'client-preflight');
131
- }
132
- const resolver = options.binaryResolver ?? resolveTrustedRunnerBinary;
133
- const sourceExecutable = safeAbsolutePath(options.executablePath ?? process.argv[1]) ?? process.argv[1];
134
- const resolution = resolver({ from: sourceExecutable, platform });
135
- if (!resolution.ok) {
136
- return bootstrapFailure({
137
- projectKey: identity.projectKey,
138
- reasonCodes: [RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES.BINARY_UNAVAILABLE, ...resolution.reasonCodes],
139
- publicSummary: 'runner scheduler bootstrap could not resolve a trusted runner binary.',
140
- });
141
- }
142
- const guardedEnv = bootstrapGuardEnv(options.env ?? process.env);
143
- const sharedOptions = {
144
- ...options,
145
- projectRoot,
146
- executablePath: resolution.executablePath,
147
- platform,
148
- env: guardedEnv,
149
- binaryResolver: () => resolution,
150
- };
151
- const install = await runRunnerSchedulerCommand({
152
- ...sharedOptions,
153
- command: 'install',
154
- });
155
- if (!install.ok) {
156
- return bootstrapFailure({
157
- projectKey: identity.projectKey,
158
- strategy: install.strategy,
159
- reasonCodes: [RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES.INSTALL_FAILED, ...install.reasonCodes],
160
- publicSummary: 'runner scheduler bootstrap install failed.',
161
- attempted: true,
162
- });
163
- }
164
- const start = await runRunnerSchedulerCommand({
165
- ...sharedOptions,
166
- command: 'start',
167
- });
168
- if (!start.ok) {
169
- return bootstrapFailure({
170
- projectKey: identity.projectKey,
171
- strategy: start.strategy ?? install.strategy,
172
- reasonCodes: [RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES.START_FAILED, ...start.reasonCodes],
173
- publicSummary: 'runner scheduler bootstrap start failed.',
174
- attempted: true,
175
- installed: install.applied || install.ok,
176
- });
177
- }
178
- const result = {
179
- ok: true,
180
- attempted: true,
181
- installed: install.applied || install.ok,
182
- started: start.applied || start.ok,
183
- cached: false,
184
- projectKey: identity.projectKey,
185
- strategy: start.strategy ?? install.strategy,
186
- reasonCodes: unique([
187
- RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES.OK,
188
- ...install.reasonCodes,
189
- ...start.reasonCodes,
190
- ]),
191
- publicSummary: 'runner scheduler bootstrap completed for project key.',
192
- publicSafe: true,
193
- };
194
- runnerSchedulerBootstrapCache.set(cacheKey, result);
195
- return result;
196
- }
197
- catch {
198
- return bootstrapFailure({
199
- projectKey: identity.projectKey,
200
- reasonCodes: [RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES.UNEXPECTED_ERROR],
201
- publicSummary: 'runner scheduler bootstrap stopped unexpectedly.',
202
- });
203
- }
204
- }
205
- function bootstrapFailure(input) {
206
- return {
207
- ok: false,
208
- attempted: input.attempted ?? false,
209
- installed: input.installed ?? false,
210
- started: false,
211
- cached: false,
212
- projectKey: input.projectKey,
213
- strategy: input.strategy,
214
- reasonCodes: unique(input.reasonCodes),
215
- publicSummary: input.publicSummary,
216
- publicSafe: true,
217
- };
218
- }
219
- function bootstrapGuardEnv(env) {
220
- return {
221
- ...env,
222
- NEOCORTEX_RUNNER_BOOTSTRAP_IN_PROGRESS: '1',
223
- NEOCORTEX_BOOTSTRAP_IN_PROGRESS: '1',
224
- };
225
- }
226
- export async function runRunnerSchedulerCommand(options) {
227
- const env = options.env ?? process.env;
228
- const platform = options.platform ?? process.platform;
229
- const dryRun = options.dryRun === true;
230
- const projectRoot = safeAbsolutePath(options.projectRoot ?? process.cwd());
231
- const requestedExecutablePath = safeAbsolutePath(options.executablePath ?? process.argv[1]);
232
- const resolvedRunner = resolveSchedulerRunnerCommand(options, requestedExecutablePath, platform);
233
- const runnerCommand = resolvedRunner.runnerCommand;
234
- const executablePath = runnerCommand?.executablePath ?? requestedExecutablePath;
235
- const identity = createRunnerSchedulerIdentity(projectRoot ?? process.cwd());
236
- const commandAvailable = options.commandAvailable ?? ((command) => defaultCommandAvailable(command, env));
237
- const intervalSeconds = boundedInteger(options.intervalSeconds ?? DEFAULT_INTERVAL_SECONDS, 10, 24 * 60 * 60);
238
- const capability = detectSchedulerCapability({
239
- platform,
240
- env,
241
- strategy: options.strategy,
242
- allowCronFallback: options.allowCronFallback,
243
- commandAvailable,
244
- userBusProbe: options.userBusProbe ?? (options.commandAvailable ? () => true : undefined),
245
- uid: options.uid,
246
- });
247
- const trust = evaluateTrust(options, executablePath, resolvedRunner.resolution);
248
- const safetyBlockers = [...capability.blockers];
249
- if (!projectRoot || !runnerCommand)
250
- safetyBlockers.push(SCHEDULER_REASON_CODES.SCHEDULER_INSTALL_UNSAFE);
251
- if (!trust.trusted) {
252
- const trustReasonCodes = trust.reasonCodes && trust.reasonCodes.length > 0
253
- ? trust.reasonCodes
254
- : [trust.reasonCode ?? SCHEDULER_REASON_CODES.RUNNER_BINARY_UNTRUSTED];
255
- safetyBlockers.push(SCHEDULER_REASON_CODES.SCHEDULER_INSTALL_UNSAFE, SCHEDULER_REASON_CODES.RUNNER_BINARY_UNTRUSTED, ...trustReasonCodes);
256
- }
257
- const selectedStrategy = capability.selectedStrategy;
258
- if (!selectedStrategy)
259
- safetyBlockers.push(SCHEDULER_REASON_CODES.SCHEDULER_UNAVAILABLE);
260
- const paths = selectedStrategy ? pathsForStrategy(selectedStrategy, env, identity) : undefined;
261
- const legacyEntries = selectedStrategy && projectRoot && shouldDiscoverLegacy(options.command)
262
- ? detectLegacyManagedEntries({ strategy: selectedStrategy, env, projectRoot })
263
- : [];
264
- const legacyReasonCodes = legacyEntries.flatMap((entry) => entry.reasonCodes);
265
- const blocksMutation = options.command === 'install' || options.command === 'start' || options.command === 'stop';
266
- const blocked = blocksMutation && safetyBlockers.length > 0;
267
- const reasonCodes = unique([
268
- ...capability.reasonCodes,
269
- ...safetyBlockers,
270
- ...legacyReasonCodes,
271
- blocked ? SCHEDULER_REASON_CODES.SCHEDULER_INSTALL_UNSAFE : SCHEDULER_REASON_CODES.OK,
272
- ]);
273
- if (blocked || !selectedStrategy || !paths || !projectRoot || !runnerCommand) {
274
- return {
275
- ok: !blocked && Boolean(selectedStrategy),
276
- command: options.command,
277
- platform,
278
- strategy: selectedStrategy,
279
- dryRun,
280
- manifestPaths: [],
281
- manifests: [],
282
- identity,
283
- legacyEntries,
284
- controlCommands: [],
285
- uninstallGuidance: selectedStrategy && paths ? uninstallGuidance(selectedStrategy, paths, identity) : [],
286
- capability: withSafetyBlockers(capability, safetyBlockers),
287
- reasonCodes,
288
- applied: false,
289
- publicSafe: true,
290
- };
291
- }
292
- const manifests = options.command === 'install'
293
- ? renderSchedulerManifests({ strategy: selectedStrategy, paths, projectRoot, executablePath: runnerCommand.command, runnerCommand, intervalSeconds, identity })
294
- : [];
295
- const controlCommands = controlCommandsForAction(options.command, selectedStrategy, paths, identity, legacyEntries, env);
296
- let applied = false;
297
- let ok = true;
298
- const commandReasonCodes = [];
299
- if (options.command === 'install' && !dryRun) {
300
- let manifestApplied = false;
301
- for (const manifest of manifests) {
302
- const writeManifest = () => {
303
- mkdirSync(dirname(manifest.path), { recursive: true });
304
- writeFileSync(manifest.path, manifest.content, 'utf8');
305
- };
306
- if (options.effectAuthority) {
307
- manifestApplied = executeSchedulerManifestWrite(options.effectAuthority, writeManifest) || manifestApplied;
308
- }
309
- else {
310
- writeManifest();
311
- manifestApplied = true;
312
- }
313
- }
314
- applied = manifestApplied;
315
- }
316
- if (!dryRun && controlCommands.length > 0) {
317
- const runner = options.commandRunner ?? defaultCommandRunner;
318
- for (const controlCommand of controlCommands) {
319
- if (controlCommand.manualOnly)
320
- continue;
321
- const execution = options.effectAuthority
322
- ? executeSchedulerProcess(options.effectAuthority, controlCommand, () => ({ executed: true, result: runner(controlCommand) }), () => ({ executed: false, result: { ok: true, reasonCode: SCHEDULER_REASON_CODES.OK } }))
323
- : { executed: true, result: runner(controlCommand) };
324
- const result = execution.result;
325
- if (!result.ok) {
326
- ok = false;
327
- commandReasonCodes.push(result.reasonCode ?? SCHEDULER_REASON_CODES.SCHEDULER_COMMAND_FAILED);
328
- }
329
- else if (execution.executed) {
330
- applied = true;
331
- }
332
- }
333
- }
334
- return {
335
- ok,
336
- command: options.command,
337
- platform,
338
- strategy: selectedStrategy,
339
- dryRun,
340
- manifestPaths: manifests.map((manifest) => manifest.path),
341
- manifests,
342
- identity,
343
- legacyEntries,
344
- controlCommands,
345
- uninstallGuidance: [...uninstallGuidance(selectedStrategy, paths, identity), ...legacyRemediationGuidance(selectedStrategy, legacyEntries)],
346
- capability: withSafetyBlockers(capability, safetyBlockers),
347
- reasonCodes: unique([...reasonCodes, ...commandReasonCodes, ok ? SCHEDULER_REASON_CODES.OK : SCHEDULER_REASON_CODES.SCHEDULER_COMMAND_FAILED]),
348
- applied,
349
- publicSafe: true,
350
- };
351
- }
352
- export function detectSchedulerCapability(input = {}) {
353
- const env = input.env ?? process.env;
354
- const platform = input.platform ?? process.platform;
355
- const commandAvailable = input.commandAvailable ?? ((command) => defaultCommandAvailable(command, env));
356
- const blockers = unsafeContextBlockers(platform, env, input.uid);
357
- const primaryStrategy = primaryStrategyForPlatform(platform);
358
- const primaryBinaryAvailable = primaryStrategy ? strategyAvailable(primaryStrategy, commandAvailable) : false;
359
- let userBusAvailable = true;
360
- if (primaryStrategy === 'systemd-user' && primaryBinaryAvailable) {
361
- try {
362
- userBusAvailable = (input.userBusProbe ?? defaultUserBusProbe)(env) === true;
363
- }
364
- catch {
365
- userBusAvailable = false;
366
- }
367
- }
368
- const primaryAvailable = primaryBinaryAvailable && userBusAvailable;
369
- const cronFallbackAvailable = platform !== 'win32' && commandAvailable('crontab');
370
- const allowCronFallback = input.allowCronFallback === true;
371
- let selectedStrategy = input.strategy;
372
- const reasonCodes = [];
373
- if (primaryStrategy === 'systemd-user' && primaryBinaryAvailable && !userBusAvailable) {
374
- reasonCodes.push(SCHEDULER_REASON_CODES.SYSTEMD_USER_BUS_UNAVAILABLE);
375
- }
376
- if (!selectedStrategy) {
377
- if (primaryStrategy && primaryAvailable)
378
- selectedStrategy = primaryStrategy;
379
- else if (allowCronFallback && cronFallbackAvailable) {
380
- selectedStrategy = 'cron-fallback';
381
- reasonCodes.push(SCHEDULER_REASON_CODES.PRIMARY_USER_SCHEDULER_UNAVAILABLE, SCHEDULER_REASON_CODES.CRON_FALLBACK_SELECTED);
382
- }
383
- }
384
- if (selectedStrategy === 'cron-fallback' && primaryAvailable) {
385
- selectedStrategy = undefined;
386
- reasonCodes.push(SCHEDULER_REASON_CODES.CRON_FALLBACK_NOT_ALLOWED);
387
- }
388
- else if (selectedStrategy === 'cron-fallback' && !allowCronFallback) {
389
- selectedStrategy = undefined;
390
- reasonCodes.push(SCHEDULER_REASON_CODES.CRON_FALLBACK_NOT_PERMITTED);
391
- }
392
- if (selectedStrategy && (selectedStrategy === primaryStrategy ? !primaryAvailable : !strategyAvailable(selectedStrategy, commandAvailable))) {
393
- if (selectedStrategy !== 'cron-fallback' || !cronFallbackAvailable)
394
- selectedStrategy = undefined;
395
- }
396
- if (!selectedStrategy)
397
- reasonCodes.push(SCHEDULER_REASON_CODES.SCHEDULER_UNAVAILABLE);
398
- if (blockers.length > 0)
399
- reasonCodes.push(...blockers);
400
- if (reasonCodes.length === 0)
401
- reasonCodes.push(SCHEDULER_REASON_CODES.OK);
402
- return {
403
- platform,
404
- primaryStrategy,
405
- selectedStrategy,
406
- fallbackStrategy: cronFallbackAvailable ? 'cron-fallback' : undefined,
407
- primaryAvailable,
408
- cronFallbackAvailable,
409
- safeToInstall: blockers.length === 0,
410
- blockers,
411
- reasonCodes: unique(reasonCodes),
412
- publicSafe: true,
413
- };
414
- }
415
- function defaultUserBusProbe(env) {
416
- const result = spawnSync('systemctl', ['--user', 'show-environment'], {
417
- env, shell: false, stdio: 'ignore', timeout: 2_000, windowsHide: true,
418
- });
419
- return result.error === undefined && result.status === 0;
420
- }
421
- export function renderSchedulerManifests(input) {
422
- const identity = input.identity ?? createRunnerSchedulerIdentity(input.projectRoot);
423
- const runnerCommand = input.runnerCommand ?? { command: input.executablePath, args: [], executablePath: input.executablePath, publicSafe: true };
424
- switch (input.strategy) {
425
- case 'systemd-user':
426
- return [
427
- {
428
- kind: 'systemd-service',
429
- path: input.paths.systemdServicePath,
430
- content: renderSystemdService(runnerCommand, input.projectRoot, identity),
431
- publicSafe: true,
432
- },
433
- {
434
- kind: 'systemd-timer',
435
- path: input.paths.systemdTimerPath,
436
- content: renderSystemdTimer(input.intervalSeconds, identity),
437
- publicSafe: true,
438
- },
439
- ];
440
- case 'launchd-user':
441
- return [{ kind: 'launchd-plist', path: input.paths.launchdPlistPath, content: renderLaunchdPlist(runnerCommand, input.projectRoot, input.intervalSeconds, identity), publicSafe: true }];
442
- case 'windows-task-scheduler':
443
- return [{ kind: 'windows-task-xml', path: input.paths.windowsTaskXmlPath, content: renderWindowsTaskXml(runnerCommand, input.projectRoot, input.intervalSeconds, identity), publicSafe: true }];
444
- case 'cron-fallback':
445
- return [{ kind: 'cron-snippet', path: input.paths.cronSnippetPath, content: renderCronSnippet(runnerCommand, input.projectRoot, identity), publicSafe: true }];
446
- }
447
- }
448
- function pathsForStrategy(strategy, env, identity) {
449
- const home = resolveHome(env);
450
- const xdgConfig = safeAbsolutePath(env.XDG_CONFIG_HOME) ?? join(home, '.config');
451
- const systemdUserDir = join(xdgConfig, 'systemd', 'user');
452
- const launchAgentsDir = join(home, 'Library', 'LaunchAgents');
453
- const appData = safeAbsolutePath(env.APPDATA) ?? join(safeAbsolutePath(env.USERPROFILE) ?? home, 'AppData', 'Roaming');
454
- const windowsDir = join(appData, 'Neocortex', 'Runner');
455
- const cronDir = join(xdgConfig, 'neocortex');
456
- void strategy;
457
- return {
458
- systemdServicePath: join(systemdUserDir, identity.systemdServiceFile),
459
- systemdTimerPath: join(systemdUserDir, identity.systemdTimerFile),
460
- launchdPlistPath: join(launchAgentsDir, identity.launchdFile),
461
- windowsTaskXmlPath: join(windowsDir, identity.windowsXmlFile),
462
- cronSnippetPath: join(cronDir, identity.cronFile),
463
- };
464
- }
465
- function legacyPathsForStrategy(strategy, env) {
466
- const home = resolveHome(env);
467
- const xdgConfig = safeAbsolutePath(env.XDG_CONFIG_HOME) ?? join(home, '.config');
468
- const systemdUserDir = join(xdgConfig, 'systemd', 'user');
469
- const launchAgentsDir = join(home, 'Library', 'LaunchAgents');
470
- const appData = safeAbsolutePath(env.APPDATA) ?? join(safeAbsolutePath(env.USERPROFILE) ?? home, 'AppData', 'Roaming');
471
- const windowsDir = join(appData, 'Neocortex', 'Runner');
472
- const cronDir = join(xdgConfig, 'neocortex');
473
- void strategy;
474
- return {
475
- systemdServicePath: join(systemdUserDir, LEGACY_SYSTEMD_SERVICE_FILE),
476
- systemdTimerPath: join(systemdUserDir, LEGACY_SYSTEMD_TIMER_FILE),
477
- launchdPlistPath: join(launchAgentsDir, LEGACY_LAUNCHD_FILE),
478
- windowsTaskXmlPath: join(windowsDir, LEGACY_WINDOWS_XML_FILE),
479
- cronSnippetPath: join(cronDir, LEGACY_CRON_FILE),
480
- };
481
- }
482
- function controlCommandsForAction(command, strategy, paths, identity, legacyEntries, env) {
483
- if (command === 'doctor')
484
- return [];
485
- const scopedCommands = command === 'install'
486
- ? installCommands(strategy, paths, identity)
487
- : command === 'start'
488
- ? startCommands(strategy, paths, identity)
489
- : command === 'stop'
490
- ? stopCommands(strategy, paths, identity)
491
- : statusCommands(strategy, paths, identity);
492
- return [...scopedCommands, ...legacyControlCommandsForAction(command, strategy, legacyEntries, env)];
493
- }
494
- function installCommands(strategy, paths, identity) {
495
- switch (strategy) {
496
- case 'systemd-user':
497
- return [control('systemctl', ['--user', 'daemon-reload']), control('systemctl', ['--user', 'enable', '--now', identity.systemdTimerName])];
498
- case 'launchd-user':
499
- return [control('launchctl', ['load', '-w', paths.launchdPlistPath])];
500
- case 'windows-task-scheduler':
501
- return [control('schtasks', ['/Create', '/TN', identity.windowsTaskName, '/XML', paths.windowsTaskXmlPath, '/F'])];
502
- case 'cron-fallback':
503
- return [control('crontab', ['-l', '# append snippet from', paths.cronSnippetPath], true)];
504
- }
505
- }
506
- function startCommands(strategy, paths, identity) {
507
- switch (strategy) {
508
- case 'systemd-user':
509
- return [control('systemctl', ['--user', 'start', identity.systemdTimerName])];
510
- case 'launchd-user':
511
- return [control('launchctl', ['load', '-w', paths.launchdPlistPath])];
512
- case 'windows-task-scheduler':
513
- return [control('schtasks', ['/Run', '/TN', identity.windowsTaskName])];
514
- case 'cron-fallback':
515
- return [control('crontab', ['-l', '# ensure snippet from', paths.cronSnippetPath, 'is installed'], true)];
516
- }
517
- }
518
- function stopCommands(strategy, paths, identity) {
519
- switch (strategy) {
520
- case 'systemd-user':
521
- return [control('systemctl', ['--user', 'stop', identity.systemdTimerName])];
522
- case 'launchd-user':
523
- return [control('launchctl', ['unload', '-w', paths.launchdPlistPath])];
524
- case 'windows-task-scheduler':
525
- return [control('schtasks', ['/End', '/TN', identity.windowsTaskName])];
526
- case 'cron-fallback':
527
- return [control('crontab', ['-l', '# remove scoped neocortex-runner snippet'], true)];
528
- }
529
- }
530
- function statusCommands(strategy, paths, identity) {
531
- switch (strategy) {
532
- case 'systemd-user':
533
- return [control('systemctl', ['--user', 'status', identity.systemdTimerName, '--no-pager'])];
534
- case 'launchd-user':
535
- return [control('launchctl', ['list', identity.launchdLabel])];
536
- case 'windows-task-scheduler':
537
- return [control('schtasks', ['/Query', '/TN', identity.windowsTaskName, '/FO', 'LIST'])];
538
- case 'cron-fallback':
539
- return [control('crontab', ['-l', '# look for neocortex-runner snippet from', paths.cronSnippetPath], true)];
540
- }
541
- }
542
- function uninstallGuidance(strategy, paths, identity) {
543
- switch (strategy) {
544
- case 'systemd-user':
545
- return [
546
- `systemctl --user disable --now ${identity.systemdTimerName}`,
547
- `rm ${paths.systemdServicePath}`,
548
- `rm ${paths.systemdTimerPath}`,
549
- ];
550
- case 'launchd-user':
551
- return [`launchctl unload -w ${paths.launchdPlistPath}`, `rm ${paths.launchdPlistPath}`];
552
- case 'windows-task-scheduler':
553
- return [`schtasks /Delete /TN ${identity.windowsTaskName} /F`, `Remove-Item ${paths.windowsTaskXmlPath}`];
554
- case 'cron-fallback':
555
- return [`Remove the ${identity.cronMarkerStart} block from the user crontab.`, `rm ${paths.cronSnippetPath}`];
556
- }
557
- }
558
- function legacyControlCommandsForAction(command, strategy, entries, env) {
559
- const hasCurrentProjectLegacy = entries.some((entry) => entry.relation === 'current-project');
560
- if (!hasCurrentProjectLegacy || (command !== 'status' && command !== 'stop'))
561
- return [];
562
- const paths = legacyPathsForStrategy(strategy, env);
563
- return command === 'status' ? legacyStatusCommands(strategy, paths) : legacyStopCommands(strategy, paths);
564
- }
565
- function legacyStatusCommands(strategy, paths) {
566
- switch (strategy) {
567
- case 'systemd-user':
568
- return [control('systemctl', ['--user', 'status', LEGACY_SYSTEMD_TIMER_FILE, '--no-pager'])];
569
- case 'launchd-user':
570
- return [control('launchctl', ['list', LEGACY_LAUNCHD_LABEL])];
571
- case 'windows-task-scheduler':
572
- return [control('schtasks', ['/Query', '/TN', LEGACY_WINDOWS_TASK_NAME, '/FO', 'LIST'])];
573
- case 'cron-fallback':
574
- return [control('crontab', ['-l', '# look for legacy neocortex-runner snippet from', paths.cronSnippetPath], true)];
575
- }
576
- }
577
- function legacyStopCommands(strategy, paths) {
578
- switch (strategy) {
579
- case 'systemd-user':
580
- return [control('systemctl', ['--user', 'stop', LEGACY_SYSTEMD_TIMER_FILE])];
581
- case 'launchd-user':
582
- return [control('launchctl', ['unload', '-w', paths.launchdPlistPath])];
583
- case 'windows-task-scheduler':
584
- return [control('schtasks', ['/End', '/TN', LEGACY_WINDOWS_TASK_NAME])];
585
- case 'cron-fallback':
586
- return [control('crontab', ['-l', '# remove legacy neocortex-runner snippet'], true)];
587
- }
588
- }
589
- function legacyRemediationGuidance(strategy, entries) {
590
- if (entries.length === 0)
591
- return [];
592
- const current = entries.filter((entry) => entry.relation === 'current-project');
593
- const ambiguous = entries.filter((entry) => entry.relation === 'ambiguous');
594
- const otherProject = entries.filter((entry) => entry.relation === 'other-project');
595
- const guidance = [];
596
- if (current.length > 0)
597
- guidance.push(`Legacy global ${strategy} scheduler matches this project; stop it before relying on project-scoped runner scheduling.`);
598
- if (ambiguous.length > 0)
599
- guidance.push(`Legacy global ${strategy} scheduler ownership is ambiguous; inspect it manually before removal.`);
600
- if (otherProject.length > 0)
601
- guidance.push(`Legacy global ${strategy} scheduler appears to belong to another project; leave it unchanged.`);
602
- return guidance;
603
- }
604
- function renderSystemdService(runnerCommand, projectRoot, identity) {
605
- const commandLine = [...systemdRunnerCommand(runnerCommand), 'tick', '--project-root', projectRoot, '--scheduled']
606
- .map(systemdQuote)
607
- .join(' ');
608
- return [
609
- '[Unit]',
610
- `Description=Neocortex Enterprise Continuity Runner (${identity.projectKey}, user scope)`,
611
- `# Managed by Neocortex runner for project ${identity.projectKey}`,
612
- 'After=network-online.target',
613
- '',
614
- '[Service]',
615
- 'Type=oneshot',
616
- `WorkingDirectory=${systemdPathSettingValue(projectRoot)}`,
617
- `ExecStart=${commandLine}`,
618
- '',
619
- '[Install]',
620
- 'WantedBy=default.target',
621
- '',
622
- ].join('\n');
623
- }
624
- function systemdRunnerCommand(runnerCommand) {
625
- const nodeExecutable = safeAbsolutePath(process.execPath);
626
- if (!nodeExecutable || runnerCommand.command === nodeExecutable)
627
- return [runnerCommand.command, ...runnerCommand.args];
628
- return [nodeExecutable, runnerCommand.command, ...runnerCommand.args];
629
- }
630
- function renderSystemdTimer(intervalSeconds, identity) {
631
- return [
632
- '[Unit]',
633
- `Description=Run Neocortex Enterprise Continuity Runner periodically (${identity.projectKey}, user scope)`,
634
- `# Managed by Neocortex runner for project ${identity.projectKey}`,
635
- '',
636
- '[Timer]',
637
- 'OnBootSec=60s',
638
- `OnUnitActiveSec=${intervalSeconds}s`,
639
- `Unit=${identity.systemdServiceName}`,
640
- '',
641
- '[Install]',
642
- 'WantedBy=timers.target',
643
- '',
644
- ].join('\n');
645
- }
646
- function renderLaunchdPlist(runnerCommand, projectRoot, intervalSeconds, identity) {
647
- const args = [runnerCommand.command, ...runnerCommand.args, 'tick', '--project-root', projectRoot, '--scheduled'];
648
- return [
649
- '<?xml version="1.0" encoding="UTF-8"?>',
650
- '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
651
- '<plist version="1.0">',
652
- '<dict>',
653
- ` <!-- Managed by Neocortex runner for project ${xmlEscape(identity.projectKey)} -->`,
654
- ' <key>Label</key>',
655
- ` <string>${xmlEscape(identity.launchdLabel)}</string>`,
656
- ' <key>ProgramArguments</key>',
657
- ' <array>',
658
- ...args.map((arg) => ` <string>${xmlEscape(arg)}</string>`),
659
- ' </array>',
660
- ' <key>WorkingDirectory</key>',
661
- ` <string>${xmlEscape(projectRoot)}</string>`,
662
- ' <key>StartInterval</key>',
663
- ` <integer>${intervalSeconds}</integer>`,
664
- ' <key>RunAtLoad</key>',
665
- ' <true/>',
666
- '</dict>',
667
- '</plist>',
668
- '',
669
- ].join('\n');
670
- }
671
- function renderWindowsTaskXml(runnerCommand, projectRoot, intervalSeconds, identity) {
672
- const args = [...runnerCommand.args, 'tick', '--project-root', projectRoot, '--scheduled'].map(windowsQuote).join(' ');
673
- return [
674
- '<?xml version="1.0" encoding="UTF-16"?>',
675
- '<Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">',
676
- ' <RegistrationInfo>',
677
- ` <Description>Neocortex Enterprise Continuity Runner (${xmlEscape(identity.projectKey)}, user scope)</Description>`,
678
- ' </RegistrationInfo>',
679
- ' <Triggers>',
680
- ' <TimeTrigger>',
681
- ' <Repetition>',
682
- ` <Interval>PT${intervalSeconds}S</Interval>`,
683
- ' <StopAtDurationEnd>false</StopAtDurationEnd>',
684
- ' </Repetition>',
685
- ' <Enabled>true</Enabled>',
686
- ' </TimeTrigger>',
687
- ' </Triggers>',
688
- ' <Principals>',
689
- ' <Principal id="Author">',
690
- ' <LogonType>InteractiveToken</LogonType>',
691
- ' <RunLevel>LeastPrivilege</RunLevel>',
692
- ' </Principal>',
693
- ' </Principals>',
694
- ' <Settings>',
695
- ' <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>',
696
- ' <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>',
697
- ' <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>',
698
- ' <Enabled>true</Enabled>',
699
- ' </Settings>',
700
- ' <Actions Context="Author">',
701
- ' <Exec>',
702
- ` <Command>${xmlEscape(runnerCommand.command)}</Command>`,
703
- ` <Arguments>${xmlEscape(args)}</Arguments>`,
704
- ` <WorkingDirectory>${xmlEscape(projectRoot)}</WorkingDirectory>`,
705
- ' </Exec>',
706
- ' </Actions>',
707
- '</Task>',
708
- '',
709
- ].join('\n');
710
- }
711
- function renderCronSnippet(runnerCommand, projectRoot, identity) {
712
- const commandLine = [runnerCommand.command, ...runnerCommand.args, 'tick', '--project-root', projectRoot, '--scheduled']
713
- .map(shellQuote)
714
- .join(' ');
715
- return [
716
- identity.cronMarkerStart,
717
- `# neocortex-runner user-scope cron fallback for project ${identity.projectKey}`,
718
- '# Reason: primary-user-scheduler-unavailable',
719
- `* * * * * ${commandLine} # neocortex-runner:${identity.projectKey}`,
720
- identity.cronMarkerEnd,
721
- '',
722
- ].join('\n');
723
- }
724
- function shouldDiscoverLegacy(command) {
725
- return command === 'status' || command === 'stop' || command === 'doctor';
726
- }
727
- function detectLegacyManagedEntries(input) {
728
- const paths = legacyPathsForStrategy(input.strategy, input.env);
729
- switch (input.strategy) {
730
- case 'systemd-user': {
731
- const serviceContent = readOptional(paths.systemdServicePath);
732
- const timerContent = readOptional(paths.systemdTimerPath);
733
- const serviceManaged = serviceContent ? looksLikeManagedLegacy(serviceContent) : false;
734
- const timerManaged = timerContent ? looksLikeLegacySystemdTimer(timerContent) : false;
735
- if (!serviceManaged && !timerManaged)
736
- return [];
737
- const relation = classifyLegacyRelation([serviceContent, timerContent].filter(Boolean).join('\n'), input.projectRoot, serviceManaged);
738
- return [legacyEntry(input.strategy, 'systemd-timer', LEGACY_SYSTEMD_TIMER_FILE, relation)];
739
- }
740
- case 'launchd-user': {
741
- const content = readOptional(paths.launchdPlistPath);
742
- if (!content || !looksLikeManagedLegacy(content))
743
- return [];
744
- return [legacyEntry(input.strategy, 'launchd-plist', LEGACY_LAUNCHD_LABEL, classifyLegacyRelation(content, input.projectRoot, true))];
745
- }
746
- case 'windows-task-scheduler': {
747
- const content = readOptional(paths.windowsTaskXmlPath);
748
- if (!content || !looksLikeManagedLegacy(content))
749
- return [];
750
- return [legacyEntry(input.strategy, 'windows-task-xml', LEGACY_WINDOWS_TASK_NAME, classifyLegacyRelation(content, input.projectRoot, true))];
751
- }
752
- case 'cron-fallback': {
753
- const content = readOptional(paths.cronSnippetPath);
754
- if (!content || !looksLikeManagedLegacy(content))
755
- return [];
756
- return [legacyEntry(input.strategy, 'cron-snippet', '# neocortex-runner', classifyLegacyRelation(content, input.projectRoot, true))];
757
- }
758
- }
759
- }
760
- function legacyEntry(strategy, kind, name, relation) {
761
- const reasonCode = relation === 'current-project'
762
- ? SCHEDULER_REASON_CODES.LEGACY_GLOBAL_SCHEDULER_DETECTED
763
- : relation === 'ambiguous'
764
- ? SCHEDULER_REASON_CODES.LEGACY_GLOBAL_SCHEDULER_AMBIGUOUS
765
- : SCHEDULER_REASON_CODES.LEGACY_GLOBAL_SCHEDULER_OTHER_PROJECT;
766
- return {
767
- strategy,
768
- kind,
769
- name,
770
- relation,
771
- reasonCodes: [reasonCode],
772
- remediation: relation === 'current-project' ? 'stop-safe' : relation === 'ambiguous' ? 'manual-review-only' : 'report-only',
773
- publicSafe: true,
774
- };
775
- }
776
- function classifyLegacyRelation(content, projectRoot, managedWithRootHint) {
777
- if (containsCurrentProjectRoot(content, projectRoot))
778
- return 'current-project';
779
- if (managedWithRootHint && /--project-root|WorkingDirectory=|<key>WorkingDirectory<\/key>|<Arguments>[^<]*--project-root/i.test(content))
780
- return 'other-project';
781
- return 'ambiguous';
782
- }
783
- function containsCurrentProjectRoot(content, projectRoot) {
784
- const candidates = unique([
785
- projectRoot,
786
- systemdQuote(projectRoot),
787
- legacySystemdQuote(projectRoot),
788
- systemdPathSettingValue(projectRoot),
789
- legacySystemdPathValue(projectRoot),
790
- shellQuote(projectRoot),
791
- windowsQuote(projectRoot),
792
- xmlEscape(projectRoot),
793
- ].filter(Boolean));
794
- return candidates.some((candidate) => content.includes(candidate));
795
- }
796
- function looksLikeManagedLegacy(content) {
797
- return /neocortex-runner|com\.ornexus\.neocortex\.runner|NeocortexRunner|Neocortex Enterprise Continuity Runner/i.test(content)
798
- && /tick|--project-root|StartInterval|OnUnitActiveSec|InteractiveToken|primary-user-scheduler-unavailable/i.test(content);
799
- }
800
- function looksLikeLegacySystemdTimer(content) {
801
- return /neocortex-runner\.service|Neocortex Enterprise Continuity Runner|OnUnitActiveSec/i.test(content);
802
- }
803
- function readOptional(path) {
804
- try {
805
- return readFileSync(path, 'utf8');
806
- }
807
- catch {
808
- return null;
809
- }
810
- }
811
- function primaryStrategyForPlatform(platform) {
812
- if (platform === 'linux')
813
- return 'systemd-user';
814
- if (platform === 'darwin')
815
- return 'launchd-user';
816
- if (platform === 'win32')
817
- return 'windows-task-scheduler';
818
- return undefined;
819
- }
820
- function strategyAvailable(strategy, commandAvailable) {
821
- switch (strategy) {
822
- case 'systemd-user': return commandAvailable('systemctl');
823
- case 'launchd-user': return commandAvailable('launchctl');
824
- case 'windows-task-scheduler': return commandAvailable('schtasks') || commandAvailable('schtasks.exe');
825
- case 'cron-fallback': return commandAvailable('crontab');
826
- }
827
- }
828
- function unsafeContextBlockers(platform, env, uid) {
829
- const blockers = [];
830
- const effectiveUid = uid ?? (typeof process.getuid === 'function' ? process.getuid() : null);
831
- if (platform !== 'win32' && effectiveUid === 0)
832
- blockers.push(SCHEDULER_REASON_CODES.SCHEDULER_INSTALL_UNSAFE);
833
- if (platform !== 'win32' && (env.SUDO_USER || env.SUDO_UID || env.SUDO_COMMAND))
834
- blockers.push(SCHEDULER_REASON_CODES.SCHEDULER_INSTALL_UNSAFE);
835
- const declaredHome = env.HOME ?? env.USERPROFILE;
836
- if (!declaredHome || !isAbsolute(declaredHome) || !safeAbsolutePath(declaredHome))
837
- blockers.push(SCHEDULER_REASON_CODES.SCHEDULER_INSTALL_UNSAFE);
838
- return unique(blockers);
839
- }
840
- function resolveSchedulerRunnerCommand(options, executablePath, platform) {
841
- if (options.trustCheck === false || options.trustChecker) {
842
- return {
843
- runnerCommand: executablePath ? { command: executablePath, args: [], executablePath, publicSafe: true } : undefined,
844
- };
845
- }
846
- const resolver = options.binaryResolver ?? resolveTrustedRunnerBinary;
847
- const resolution = resolver({ from: executablePath ?? process.argv[1], platform });
848
- if (resolution.ok) {
849
- return {
850
- runnerCommand: {
851
- command: resolution.command,
852
- args: resolution.args,
853
- executablePath: resolution.executablePath,
854
- provenance: resolution.provenance,
855
- publicSafe: true,
856
- },
857
- resolution,
858
- };
859
- }
860
- return {
861
- runnerCommand: executablePath ? { command: executablePath, args: [], executablePath, provenance: resolution.provenance, publicSafe: true } : undefined,
862
- resolution,
863
- };
864
- }
865
- function evaluateTrust(options, executablePath, resolution) {
866
- if (options.trustCheck === false)
867
- return { trusted: true, executablePath: executablePath ?? undefined, publicSafe: true };
868
- if (options.trustChecker)
869
- return options.trustChecker(executablePath ?? undefined);
870
- if (resolution)
871
- return resolution.ok ? {
872
- trusted: true,
873
- packageName: resolution.packageName,
874
- packageVersion: resolution.packageVersion,
875
- packageRoot: resolution.packageRoot,
876
- executablePath: resolution.executablePath,
877
- expectedRelativePath: resolution.expectedRelativePath,
878
- provenance: resolution.provenance,
879
- reasonCodes: resolution.reasonCodes,
880
- publicSafe: true,
881
- } : {
882
- trusted: false,
883
- reasonCode: resolution.reasonCode,
884
- reasonCodes: resolution.reasonCodes,
885
- packageName: resolution.packageName,
886
- packageVersion: resolution.packageVersion,
887
- packageRoot: resolution.packageRoot,
888
- executablePath: resolution.executablePath ?? executablePath ?? undefined,
889
- expectedRelativePath: resolution.expectedRelativePath,
890
- provenance: resolution.provenance,
891
- publicSafe: true,
892
- };
893
- return checkRunnerBinaryTrust(executablePath ?? undefined);
894
- }
895
- function resolveHome(env) {
896
- return env.HOME ?? env.USERPROFILE ?? process.env.HOME ?? process.cwd();
897
- }
898
- function safeAbsolutePath(value) {
899
- if (!value || /[\r\n\0]/.test(value))
900
- return null;
901
- const resolved = isAbsolute(value) ? value : resolve(value);
902
- return isAbsolute(resolved) ? resolved : null;
903
- }
904
- function control(command, args, manualOnly = false) {
905
- return { command, args, preview: [command, ...args.map(shellQuote)].join(' '), safeUserScope: true, ...(manualOnly ? { manualOnly: true } : {}) };
906
- }
907
- function defaultCommandRunner(command) {
908
- const result = spawnSync(command.command, [...command.args], { stdio: 'ignore', shell: false, timeout: 3_000, windowsHide: true });
909
- return {
910
- ok: result.status === 0,
911
- code: result.status,
912
- signal: result.signal,
913
- reasonCode: result.status === 0 ? SCHEDULER_REASON_CODES.OK : SCHEDULER_REASON_CODES.SCHEDULER_COMMAND_FAILED,
914
- };
915
- }
916
- function defaultCommandAvailable(command, env) {
917
- const pathValue = env.PATH ?? process.env.PATH ?? '';
918
- const pathExt = (env.PATHEXT ?? '.EXE;.CMD;.BAT;.COM').split(';').filter(Boolean);
919
- const candidates = pathValue.split(delimiter).filter(Boolean);
920
- for (const directory of candidates) {
921
- const direct = join(directory, command);
922
- if (existsSync(direct))
923
- return true;
924
- for (const extension of pathExt) {
925
- if (existsSync(join(directory, `${command}${extension.toLowerCase()}`)) || existsSync(join(directory, `${command}${extension.toUpperCase()}`)))
926
- return true;
927
- }
928
- }
929
- return false;
930
- }
931
- function withSafetyBlockers(capability, blockers) {
932
- const mergedBlockers = unique([...capability.blockers, ...blockers]);
933
- return {
934
- ...capability,
935
- safeToInstall: mergedBlockers.length === 0,
936
- blockers: mergedBlockers,
937
- reasonCodes: unique([...capability.reasonCodes, ...mergedBlockers]),
938
- };
939
- }
940
- function systemdQuote(value) {
941
- return systemdArgValue(value, true);
942
- }
943
- function legacySystemdQuote(value) {
944
- return systemdArgValue(value, false);
945
- }
946
- function systemdArgValue(value, escapePercent) {
947
- const escaped = value
948
- .replace(/\\/g, '\\\\')
949
- .replace(/"/g, '\\"')
950
- .replace(/%/g, escapePercent ? '%%' : '%');
951
- if (!/[\s"'\\]/.test(value))
952
- return escaped;
953
- return `"${escaped}"`;
954
- }
955
- function systemdPathSettingValue(value) {
956
- // systemd path settings are not argv tokens and must not use unit-name
957
- // \xNN escaping. Preserve literal path characters and only escape percent
958
- // specifiers by doubling them.
959
- return value.replace(/%/g, '%%');
960
- }
961
- function legacySystemdPathValue(value) {
962
- return Array.from(value, (char) => {
963
- if (/^[A-Za-z0-9_./:@+=,-]$/.test(char))
964
- return char;
965
- if (char === '%')
966
- return '%%';
967
- return Array.from(Buffer.from(char, 'utf8'), (byte) => `\\x${byte.toString(16).padStart(2, '0')}`).join('');
968
- }).join('');
969
- }
970
- function shellQuote(value) {
971
- if (/^[A-Za-z0-9_./:=@%+-]+$/.test(value))
972
- return value;
973
- return `'${value.replace(/'/g, `'\\''`)}'`;
974
- }
975
- function windowsQuote(value) {
976
- if (!/[\s"]/.test(value))
977
- return value;
978
- return `"${value.replace(/"/g, '\\"')}"`;
979
- }
980
- function xmlEscape(value) {
981
- return value
982
- .replace(/&/g, '&amp;')
983
- .replace(/</g, '&lt;')
984
- .replace(/>/g, '&gt;')
985
- .replace(/"/g, '&quot;')
986
- .replace(/'/g, '&apos;');
987
- }
988
- function boundedInteger(value, min, max) {
989
- if (!Number.isFinite(value))
990
- return min;
991
- return Math.max(min, Math.min(max, Math.floor(value)));
992
- }
993
- function unique(values) {
994
- return Array.from(new Set(values));
995
- }
1
+ import{Buffer as de}from"node:buffer";import{spawnSync as F}from"node:child_process";import{existsSync as $,mkdirSync as me,readFileSync as fe,writeFileSync as pe}from"node:fs";import{delimiter as he,dirname as ye,isAbsolute as M,join as l,resolve as J}from"node:path";import{checkRunnerBinaryTrust as Ee,resolveTrustedRunnerBinary as Z}from"./binary.js";import{deriveProjectIdentity as Se}from"./project-identity.js";import{executeClosedGitInspection as ge,executeSchedulerManifestWrite as Ae,executeSchedulerProcess as Ce}from"../effects/invoke-effect-gateways.js";const c=Object.freeze({OK:"continuity-ok",SCHEDULER_INSTALL_UNSAFE:"scheduler-install-unsafe",PRIMARY_USER_SCHEDULER_UNAVAILABLE:"primary-user-scheduler-unavailable",SYSTEMD_USER_BUS_UNAVAILABLE:"systemd-user-bus-unavailable",CRON_FALLBACK_SELECTED:"cron-fallback-selected",CRON_FALLBACK_NOT_ALLOWED:"cron-fallback-primary-scheduler-available",CRON_FALLBACK_NOT_PERMITTED:"cron-fallback-not-permitted",SCHEDULER_UNAVAILABLE:"scheduler-unavailable",SCHEDULER_COMMAND_FAILED:"scheduler-command-failed",RUNNER_BINARY_UNTRUSTED:"runner-binary-untrusted",LEGACY_GLOBAL_SCHEDULER_DETECTED:"legacy-global-scheduler-detected",LEGACY_GLOBAL_SCHEDULER_AMBIGUOUS:"legacy-global-scheduler-ambiguous",LEGACY_GLOBAL_SCHEDULER_OTHER_PROJECT:"legacy-global-scheduler-other-project"}),R=Object.freeze({OK:"runner-bootstrap-ok",ALREADY_ACTIVE:"runner-bootstrap-already-active",BINARY_UNAVAILABLE:"runner-bootstrap-binary-unavailable",INSTALL_FAILED:"runner-bootstrap-install-failed",START_FAILED:"runner-bootstrap-start-failed",UNEXPECTED_ERROR:"runner-bootstrap-unexpected-error"});async function ft(e,t={}){const r=await X({...t,command:e,trustCheck:!1}),n=!!r.strategy,s=new Set(Object.values(c)),a=g(r.reasonCodes.filter(o=>s.has(o)&&(r.ok||o!==c.OK))).slice(0,12);return{schemaVersion:1,command:e,projectKey:r.identity.projectKey,platform:r.platform,...r.capability.primaryStrategy?{primaryStrategy:r.capability.primaryStrategy}:{},...r.strategy?{selectedStrategy:r.strategy}:{},operational:n,status:n?e==="doctor"?"available":r.ok?"active":"inactive":"unavailable",reasonCodes:a,observedAt:new Date().toISOString(),publicSafe:!0}}const H="neocortex-runner",be=`${H}.service`,N=`${H}.timer`,K="com.ornexus.neocortex.runner",Le=`${K}.plist`,G="NeocortexRunner",ke="neocortex-runner-task.xml",Re="runner.cron",_e=60,Y=new Map;function V(e){const t=S(e)??J(e||"."),r=Se(t),n=r.projectLabel,s=r.projectId,a=`${H}-${s}`,o=`com.ornexus.neocortex.runner.${s}`;return{projectKey:s,projectBasename:n,systemdServiceName:`${a}.service`,systemdTimerName:`${a}.timer`,systemdServiceFile:`${a}.service`,systemdTimerFile:`${a}.timer`,launchdLabel:o,launchdFile:`${o}.plist`,windowsTaskName:`NeocortexRunner-${s}`,windowsXmlFile:`${a}-task.xml`,cronFile:`runner-${s}.cron`,cronMarkerStart:`# BEGIN neocortex-runner:${s}`,cronMarkerEnd:`# END neocortex-runner:${s}`,publicSafe:!0}}function pt(){Y.clear()}async function ht(e={}){const t=e.platform??process.platform,r=S(e.projectRoot??process.cwd())??process.cwd(),n=V(r),s=`${t}:${n.projectKey}`,a=Y.get(s);if(a?.ok)return{...a,attempted:!1,installed:!1,started:!1,cached:!0,reasonCodes:g([...a.reasonCodes,R.ALREADY_ACTIVE]),publicSummary:"runner scheduler bootstrap already active for project key.",publicSafe:!0};try{e.effectAuthority&&ge(e.effectAuthority,"git-rev-parse",r,E=>{const f=F(E.executable,[...E.argv],{cwd:E.cwd,env:{...E.env},shell:E.shell,timeout:E.timeoutMs,encoding:"utf8",maxBuffer:65536});return{status:f.status,stdout:f.stdout??"",stderr:f.stderr??"",projected:!1}},"client-preflight");const o=e.binaryResolver??Z,m=S(e.executablePath??process.argv[1])??process.argv[1],h=o({from:m,platform:t});if(!h.ok)return P({projectKey:n.projectKey,reasonCodes:[R.BINARY_UNAVAILABLE,...h.reasonCodes],publicSummary:"runner scheduler bootstrap could not resolve a trusted runner binary."});const p=Te(e.env??process.env),L={...e,projectRoot:r,executablePath:h.executablePath,platform:t,env:p,binaryResolver:()=>h},u=await X({...L,command:"install"});if(!u.ok)return P({projectKey:n.projectKey,strategy:u.strategy,reasonCodes:[R.INSTALL_FAILED,...u.reasonCodes],publicSummary:"runner scheduler bootstrap install failed.",attempted:!0});const d=await X({...L,command:"start"});if(!d.ok)return P({projectKey:n.projectKey,strategy:d.strategy??u.strategy,reasonCodes:[R.START_FAILED,...d.reasonCodes],publicSummary:"runner scheduler bootstrap start failed.",attempted:!0,installed:u.applied||u.ok});const A={ok:!0,attempted:!0,installed:u.applied||u.ok,started:d.applied||d.ok,cached:!1,projectKey:n.projectKey,strategy:d.strategy??u.strategy,reasonCodes:g([R.OK,...u.reasonCodes,...d.reasonCodes]),publicSummary:"runner scheduler bootstrap completed for project key.",publicSafe:!0};return Y.set(s,A),A}catch{return P({projectKey:n.projectKey,reasonCodes:[R.UNEXPECTED_ERROR],publicSummary:"runner scheduler bootstrap stopped unexpectedly."})}}function P(e){return{ok:!1,attempted:e.attempted??!1,installed:e.installed??!1,started:!1,cached:!1,projectKey:e.projectKey,strategy:e.strategy,reasonCodes:g(e.reasonCodes),publicSummary:e.publicSummary,publicSafe:!0}}function Te(e){return{...e,NEOCORTEX_RUNNER_BOOTSTRAP_IN_PROGRESS:"1",NEOCORTEX_BOOTSTRAP_IN_PROGRESS:"1"}}async function X(e){const t=e.env??process.env,r=e.platform??process.platform,n=e.dryRun===!0,s=S(e.projectRoot??process.cwd()),a=S(e.executablePath??process.argv[1]),o=Ze(e,a,r),m=o.runnerCommand,h=m?.executablePath??a,p=V(s??process.cwd()),L=e.commandAvailable??(y=>se(y,t)),u=st(e.intervalSeconds??_e,10,1440*60),d=we({platform:r,env:t,strategy:e.strategy,allowCronFallback:e.allowCronFallback,commandAvailable:L,userBusProbe:e.userBusProbe??(e.commandAvailable?()=>!0:void 0),uid:e.uid}),A=et(e,h,o.resolution),E=[...d.blockers];if((!s||!m)&&E.push(c.SCHEDULER_INSTALL_UNSAFE),!A.trusted){const y=A.reasonCodes&&A.reasonCodes.length>0?A.reasonCodes:[A.reasonCode??c.RUNNER_BINARY_UNTRUSTED];E.push(c.SCHEDULER_INSTALL_UNSAFE,c.RUNNER_BINARY_UNTRUSTED,...y)}const f=d.selectedStrategy;f||E.push(c.SCHEDULER_UNAVAILABLE);const k=f?De(f,t,p):void 0,_=f&&s&&Xe(e.command)?We({strategy:f,env:t,projectRoot:s}):[],ie=_.flatMap(y=>y.reasonCodes),x=(e.command==="install"||e.command==="start"||e.command==="stop")&&E.length>0,Q=g([...d.reasonCodes,...E,...ie,x?c.SCHEDULER_INSTALL_UNSAFE:c.OK]);if(x||!f||!k||!s||!m)return{ok:!x&&!!f,command:e.command,platform:r,strategy:f,dryRun:n,manifestPaths:[],manifests:[],identity:p,legacyEntries:_,controlCommands:[],uninstallGuidance:f&&k?te(f,k,p):[],capability:ae(d,E),reasonCodes:Q,applied:!1,publicSafe:!0};const I=e.command==="install"?Pe({strategy:f,paths:k,projectRoot:s,executablePath:m.command,runnerCommand:m,intervalSeconds:u,identity:p}):[],U=ve(e.command,f,k,p,_,t);let j=!1,B=!0;const z=[];if(e.command==="install"&&!n){let y=!1;for(const b of I){const T=()=>{me(ye(b.path),{recursive:!0}),pe(b.path,b.content,"utf8")};e.effectAuthority?y=Ae(e.effectAuthority,T)||y:(T(),y=!0)}j=y}if(!n&&U.length>0){const y=e.commandRunner??tt;for(const b of U){if(b.manualOnly)continue;const T=e.effectAuthority?Ce(e.effectAuthority,b,()=>({executed:!0,result:y(b)}),()=>({executed:!1,result:{ok:!0,reasonCode:c.OK}})):{executed:!0,result:y(b)},q=T.result;q.ok?T.executed&&(j=!0):(B=!1,z.push(q.reasonCode??c.SCHEDULER_COMMAND_FAILED))}}return{ok:B,command:e.command,platform:r,strategy:f,dryRun:n,manifestPaths:I.map(y=>y.path),manifests:I,identity:p,legacyEntries:_,controlCommands:U,uninstallGuidance:[...te(f,k,p),...$e(f,_)],capability:ae(d,E),reasonCodes:g([...Q,...z,B?c.OK:c.SCHEDULER_COMMAND_FAILED]),applied:j,publicSafe:!0}}function we(e={}){const t=e.env??process.env,r=e.platform??process.platform,n=e.commandAvailable??(A=>se(A,t)),s=Je(r,t,e.uid),a=qe(r),o=a?re(a,n):!1;let m=!0;if(a==="systemd-user"&&o)try{m=(e.userBusProbe??Ne)(t)===!0}catch{m=!1}const h=o&&m,p=r!=="win32"&&n("crontab"),L=e.allowCronFallback===!0;let u=e.strategy;const d=[];return a==="systemd-user"&&o&&!m&&d.push(c.SYSTEMD_USER_BUS_UNAVAILABLE),u||(a&&h?u=a:L&&p&&(u="cron-fallback",d.push(c.PRIMARY_USER_SCHEDULER_UNAVAILABLE,c.CRON_FALLBACK_SELECTED))),u==="cron-fallback"&&h?(u=void 0,d.push(c.CRON_FALLBACK_NOT_ALLOWED)):u==="cron-fallback"&&!L&&(u=void 0,d.push(c.CRON_FALLBACK_NOT_PERMITTED)),u&&(u===a?!h:!re(u,n))&&(u!=="cron-fallback"||!p)&&(u=void 0),u||d.push(c.SCHEDULER_UNAVAILABLE),s.length>0&&d.push(...s),d.length===0&&d.push(c.OK),{platform:r,primaryStrategy:a,selectedStrategy:u,fallbackStrategy:p?"cron-fallback":void 0,primaryAvailable:h,cronFallbackAvailable:p,safeToInstall:s.length===0,blockers:s,reasonCodes:g(d),publicSafe:!0}}function Ne(e){const t=F("systemctl",["--user","show-environment"],{env:e,shell:!1,stdio:"ignore",timeout:2e3,windowsHide:!0});return t.error===void 0&&t.status===0}function Pe(e){const t=e.identity??V(e.projectRoot),r=e.runnerCommand??{command:e.executablePath,args:[],executablePath:e.executablePath,publicSafe:!0};switch(e.strategy){case"systemd-user":return[{kind:"systemd-service",path:e.paths.systemdServicePath,content:Me(r,e.projectRoot,t),publicSafe:!0},{kind:"systemd-timer",path:e.paths.systemdTimerPath,content:Ke(e.intervalSeconds,t),publicSafe:!0}];case"launchd-user":return[{kind:"launchd-plist",path:e.paths.launchdPlistPath,content:Ge(r,e.projectRoot,e.intervalSeconds,t),publicSafe:!0}];case"windows-task-scheduler":return[{kind:"windows-task-xml",path:e.paths.windowsTaskXmlPath,content:Ye(r,e.projectRoot,e.intervalSeconds,t),publicSafe:!0}];case"cron-fallback":return[{kind:"cron-snippet",path:e.paths.cronSnippetPath,content:Ve(r,e.projectRoot,t),publicSafe:!0}]}}function De(e,t,r){const n=ne(t),s=S(t.XDG_CONFIG_HOME)??l(n,".config"),a=l(s,"systemd","user"),o=l(n,"Library","LaunchAgents"),m=S(t.APPDATA)??l(S(t.USERPROFILE)??n,"AppData","Roaming"),h=l(m,"Neocortex","Runner"),p=l(s,"neocortex");return{systemdServicePath:l(a,r.systemdServiceFile),systemdTimerPath:l(a,r.systemdTimerFile),launchdPlistPath:l(o,r.launchdFile),windowsTaskXmlPath:l(h,r.windowsXmlFile),cronSnippetPath:l(p,r.cronFile)}}function ee(e,t){const r=ne(t),n=S(t.XDG_CONFIG_HOME)??l(r,".config"),s=l(n,"systemd","user"),a=l(r,"Library","LaunchAgents"),o=S(t.APPDATA)??l(S(t.USERPROFILE)??r,"AppData","Roaming"),m=l(o,"Neocortex","Runner"),h=l(n,"neocortex");return{systemdServicePath:l(s,be),systemdTimerPath:l(s,N),launchdPlistPath:l(a,Le),windowsTaskXmlPath:l(m,ke),cronSnippetPath:l(h,Re)}}function ve(e,t,r,n,s,a){return e==="doctor"?[]:[...e==="install"?Oe(t,r,n):e==="start"?xe(t,r,n):e==="stop"?Ie(t,r,n):Ue(t,r,n),...je(e,t,s,a)]}function Oe(e,t,r){switch(e){case"systemd-user":return[i("systemctl",["--user","daemon-reload"]),i("systemctl",["--user","enable","--now",r.systemdTimerName])];case"launchd-user":return[i("launchctl",["load","-w",t.launchdPlistPath])];case"windows-task-scheduler":return[i("schtasks",["/Create","/TN",r.windowsTaskName,"/XML",t.windowsTaskXmlPath,"/F"])];case"cron-fallback":return[i("crontab",["-l","# append snippet from",t.cronSnippetPath],!0)]}}function xe(e,t,r){switch(e){case"systemd-user":return[i("systemctl",["--user","start",r.systemdTimerName])];case"launchd-user":return[i("launchctl",["load","-w",t.launchdPlistPath])];case"windows-task-scheduler":return[i("schtasks",["/Run","/TN",r.windowsTaskName])];case"cron-fallback":return[i("crontab",["-l","# ensure snippet from",t.cronSnippetPath,"is installed"],!0)]}}function Ie(e,t,r){switch(e){case"systemd-user":return[i("systemctl",["--user","stop",r.systemdTimerName])];case"launchd-user":return[i("launchctl",["unload","-w",t.launchdPlistPath])];case"windows-task-scheduler":return[i("schtasks",["/End","/TN",r.windowsTaskName])];case"cron-fallback":return[i("crontab",["-l","# remove scoped neocortex-runner snippet"],!0)]}}function Ue(e,t,r){switch(e){case"systemd-user":return[i("systemctl",["--user","status",r.systemdTimerName,"--no-pager"])];case"launchd-user":return[i("launchctl",["list",r.launchdLabel])];case"windows-task-scheduler":return[i("schtasks",["/Query","/TN",r.windowsTaskName,"/FO","LIST"])];case"cron-fallback":return[i("crontab",["-l","# look for neocortex-runner snippet from",t.cronSnippetPath],!0)]}}function te(e,t,r){switch(e){case"systemd-user":return[`systemctl --user disable --now ${r.systemdTimerName}`,`rm ${t.systemdServicePath}`,`rm ${t.systemdTimerPath}`];case"launchd-user":return[`launchctl unload -w ${t.launchdPlistPath}`,`rm ${t.launchdPlistPath}`];case"windows-task-scheduler":return[`schtasks /Delete /TN ${r.windowsTaskName} /F`,`Remove-Item ${t.windowsTaskXmlPath}`];case"cron-fallback":return[`Remove the ${r.cronMarkerStart} block from the user crontab.`,`rm ${t.cronSnippetPath}`]}}function je(e,t,r,n){if(!r.some(o=>o.relation==="current-project")||e!=="status"&&e!=="stop")return[];const a=ee(t,n);return e==="status"?Be(t,a):Fe(t,a)}function Be(e,t){switch(e){case"systemd-user":return[i("systemctl",["--user","status",N,"--no-pager"])];case"launchd-user":return[i("launchctl",["list",K])];case"windows-task-scheduler":return[i("schtasks",["/Query","/TN",G,"/FO","LIST"])];case"cron-fallback":return[i("crontab",["-l","# look for legacy neocortex-runner snippet from",t.cronSnippetPath],!0)]}}function Fe(e,t){switch(e){case"systemd-user":return[i("systemctl",["--user","stop",N])];case"launchd-user":return[i("launchctl",["unload","-w",t.launchdPlistPath])];case"windows-task-scheduler":return[i("schtasks",["/End","/TN",G])];case"cron-fallback":return[i("crontab",["-l","# remove legacy neocortex-runner snippet"],!0)]}}function $e(e,t){if(t.length===0)return[];const r=t.filter(o=>o.relation==="current-project"),n=t.filter(o=>o.relation==="ambiguous"),s=t.filter(o=>o.relation==="other-project"),a=[];return r.length>0&&a.push(`Legacy global ${e} scheduler matches this project; stop it before relying on project-scoped runner scheduling.`),n.length>0&&a.push(`Legacy global ${e} scheduler ownership is ambiguous; inspect it manually before removal.`),s.length>0&&a.push(`Legacy global ${e} scheduler appears to belong to another project; leave it unchanged.`),a}function Me(e,t,r){const n=[...He(e),"tick","--project-root",t,"--scheduled"].map(oe).join(" ");return["[Unit]",`Description=Neocortex Enterprise Continuity Runner (${r.projectKey}, user scope)`,`# Managed by Neocortex runner for project ${r.projectKey}`,"After=network-online.target","","[Service]","Type=oneshot",`WorkingDirectory=${ue(t)}`,`ExecStart=${n}`,"","[Install]","WantedBy=default.target",""].join(`
2
+ `)}function He(e){const t=S(process.execPath);return!t||e.command===t?[e.command,...e.args]:[t,e.command,...e.args]}function Ke(e,t){return["[Unit]",`Description=Run Neocortex Enterprise Continuity Runner periodically (${t.projectKey}, user scope)`,`# Managed by Neocortex runner for project ${t.projectKey}`,"","[Timer]","OnBootSec=60s",`OnUnitActiveSec=${e}s`,`Unit=${t.systemdServiceName}`,"","[Install]","WantedBy=timers.target",""].join(`
3
+ `)}function Ge(e,t,r,n){const s=[e.command,...e.args,"tick","--project-root",t,"--scheduled"];return['<?xml version="1.0" encoding="UTF-8"?>','<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">','<plist version="1.0">',"<dict>",` <!-- Managed by Neocortex runner for project ${C(n.projectKey)} -->`," <key>Label</key>",` <string>${C(n.launchdLabel)}</string>`," <key>ProgramArguments</key>"," <array>",...s.map(a=>` <string>${C(a)}</string>`)," </array>"," <key>WorkingDirectory</key>",` <string>${C(t)}</string>`," <key>StartInterval</key>",` <integer>${r}</integer>`," <key>RunAtLoad</key>"," <true/>","</dict>","</plist>",""].join(`
4
+ `)}function Ye(e,t,r,n){const s=[...e.args,"tick","--project-root",t,"--scheduled"].map(le).join(" ");return['<?xml version="1.0" encoding="UTF-16"?>','<Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">'," <RegistrationInfo>",` <Description>Neocortex Enterprise Continuity Runner (${C(n.projectKey)}, user scope)</Description>`," </RegistrationInfo>"," <Triggers>"," <TimeTrigger>"," <Repetition>",` <Interval>PT${r}S</Interval>`," <StopAtDurationEnd>false</StopAtDurationEnd>"," </Repetition>"," <Enabled>true</Enabled>"," </TimeTrigger>"," </Triggers>"," <Principals>",' <Principal id="Author">'," <LogonType>InteractiveToken</LogonType>"," <RunLevel>LeastPrivilege</RunLevel>"," </Principal>"," </Principals>"," <Settings>"," <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>"," <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>"," <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>"," <Enabled>true</Enabled>"," </Settings>",' <Actions Context="Author">'," <Exec>",` <Command>${C(e.command)}</Command>`,` <Arguments>${C(s)}</Arguments>`,` <WorkingDirectory>${C(t)}</WorkingDirectory>`," </Exec>"," </Actions>","</Task>",""].join(`
5
+ `)}function Ve(e,t,r){const n=[e.command,...e.args,"tick","--project-root",t,"--scheduled"].map(W).join(" ");return[r.cronMarkerStart,`# neocortex-runner user-scope cron fallback for project ${r.projectKey}`,"# Reason: primary-user-scheduler-unavailable",`* * * * * ${n} # neocortex-runner:${r.projectKey}`,r.cronMarkerEnd,""].join(`
6
+ `)}function Xe(e){return e==="status"||e==="stop"||e==="doctor"}function We(e){const t=ee(e.strategy,e.env);switch(e.strategy){case"systemd-user":{const r=w(t.systemdServicePath),n=w(t.systemdTimerPath),s=r?O(r):!1,a=n?ze(n):!1;if(!s&&!a)return[];const o=v([r,n].filter(Boolean).join(`
7
+ `),e.projectRoot,s);return[D(e.strategy,"systemd-timer",N,o)]}case"launchd-user":{const r=w(t.launchdPlistPath);return!r||!O(r)?[]:[D(e.strategy,"launchd-plist",K,v(r,e.projectRoot,!0))]}case"windows-task-scheduler":{const r=w(t.windowsTaskXmlPath);return!r||!O(r)?[]:[D(e.strategy,"windows-task-xml",G,v(r,e.projectRoot,!0))]}case"cron-fallback":{const r=w(t.cronSnippetPath);return!r||!O(r)?[]:[D(e.strategy,"cron-snippet","# neocortex-runner",v(r,e.projectRoot,!0))]}}}function D(e,t,r,n){const s=n==="current-project"?c.LEGACY_GLOBAL_SCHEDULER_DETECTED:n==="ambiguous"?c.LEGACY_GLOBAL_SCHEDULER_AMBIGUOUS:c.LEGACY_GLOBAL_SCHEDULER_OTHER_PROJECT;return{strategy:e,kind:t,name:r,relation:n,reasonCodes:[s],remediation:n==="current-project"?"stop-safe":n==="ambiguous"?"manual-review-only":"report-only",publicSafe:!0}}function v(e,t,r){return Qe(e,t)?"current-project":r&&/--project-root|WorkingDirectory=|<key>WorkingDirectory<\/key>|<Arguments>[^<]*--project-root/i.test(e)?"other-project":"ambiguous"}function Qe(e,t){return g([t,oe(t),rt(t),ue(t),nt(t),W(t),le(t),C(t)].filter(Boolean)).some(n=>e.includes(n))}function O(e){return/neocortex-runner|com\.ornexus\.neocortex\.runner|NeocortexRunner|Neocortex Enterprise Continuity Runner/i.test(e)&&/tick|--project-root|StartInterval|OnUnitActiveSec|InteractiveToken|primary-user-scheduler-unavailable/i.test(e)}function ze(e){return/neocortex-runner\.service|Neocortex Enterprise Continuity Runner|OnUnitActiveSec/i.test(e)}function w(e){try{return fe(e,"utf8")}catch{return null}}function qe(e){if(e==="linux")return"systemd-user";if(e==="darwin")return"launchd-user";if(e==="win32")return"windows-task-scheduler"}function re(e,t){switch(e){case"systemd-user":return t("systemctl");case"launchd-user":return t("launchctl");case"windows-task-scheduler":return t("schtasks")||t("schtasks.exe");case"cron-fallback":return t("crontab")}}function Je(e,t,r){const n=[],s=r??(typeof process.getuid=="function"?process.getuid():null);e!=="win32"&&s===0&&n.push(c.SCHEDULER_INSTALL_UNSAFE),e!=="win32"&&(t.SUDO_USER||t.SUDO_UID||t.SUDO_COMMAND)&&n.push(c.SCHEDULER_INSTALL_UNSAFE);const a=t.HOME??t.USERPROFILE;return(!a||!M(a)||!S(a))&&n.push(c.SCHEDULER_INSTALL_UNSAFE),g(n)}function Ze(e,t,r){if(e.trustCheck===!1||e.trustChecker)return{runnerCommand:t?{command:t,args:[],executablePath:t,publicSafe:!0}:void 0};const s=(e.binaryResolver??Z)({from:t??process.argv[1],platform:r});return s.ok?{runnerCommand:{command:s.command,args:s.args,executablePath:s.executablePath,provenance:s.provenance,publicSafe:!0},resolution:s}:{runnerCommand:t?{command:t,args:[],executablePath:t,provenance:s.provenance,publicSafe:!0}:void 0,resolution:s}}function et(e,t,r){return e.trustCheck===!1?{trusted:!0,executablePath:t??void 0,publicSafe:!0}:e.trustChecker?e.trustChecker(t??void 0):r?r.ok?{trusted:!0,packageName:r.packageName,packageVersion:r.packageVersion,packageRoot:r.packageRoot,executablePath:r.executablePath,expectedRelativePath:r.expectedRelativePath,provenance:r.provenance,reasonCodes:r.reasonCodes,publicSafe:!0}:{trusted:!1,reasonCode:r.reasonCode,reasonCodes:r.reasonCodes,packageName:r.packageName,packageVersion:r.packageVersion,packageRoot:r.packageRoot,executablePath:r.executablePath??t??void 0,expectedRelativePath:r.expectedRelativePath,provenance:r.provenance,publicSafe:!0}:Ee(t??void 0)}function ne(e){return e.HOME??e.USERPROFILE??process.env.HOME??process.cwd()}function S(e){if(!e||/[\r\n\0]/.test(e))return null;const t=M(e)?e:J(e);return M(t)?t:null}function i(e,t,r=!1){return{command:e,args:t,preview:[e,...t.map(W)].join(" "),safeUserScope:!0,...r?{manualOnly:!0}:{}}}function tt(e){const t=F(e.command,[...e.args],{stdio:"ignore",shell:!1,timeout:3e3,windowsHide:!0});return{ok:t.status===0,code:t.status,signal:t.signal,reasonCode:t.status===0?c.OK:c.SCHEDULER_COMMAND_FAILED}}function se(e,t){const r=t.PATH??process.env.PATH??"",n=(t.PATHEXT??".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean),s=r.split(he).filter(Boolean);for(const a of s){const o=l(a,e);if($(o))return!0;for(const m of n)if($(l(a,`${e}${m.toLowerCase()}`))||$(l(a,`${e}${m.toUpperCase()}`)))return!0}return!1}function ae(e,t){const r=g([...e.blockers,...t]);return{...e,safeToInstall:r.length===0,blockers:r,reasonCodes:g([...e.reasonCodes,...r])}}function oe(e){return ce(e,!0)}function rt(e){return ce(e,!1)}function ce(e,t){const r=e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,t?"%%":"%");return/[\s"'\\]/.test(e)?`"${r}"`:r}function ue(e){return e.replace(/%/g,"%%")}function nt(e){return Array.from(e,t=>/^[A-Za-z0-9_./:@+=,-]$/.test(t)?t:t==="%"?"%%":Array.from(de.from(t,"utf8"),r=>`\\x${r.toString(16).padStart(2,"0")}`).join("")).join("")}function W(e){return/^[A-Za-z0-9_./:=@%+-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function le(e){return/[\s"]/.test(e)?`"${e.replace(/"/g,'\\"')}"`:e}function C(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function st(e,t,r){return Number.isFinite(e)?Math.max(t,Math.min(r,Math.floor(e))):t}function g(e){return Array.from(new Set(e))}export{R as RUNNER_SCHEDULER_BOOTSTRAP_REASON_CODES,c as SCHEDULER_REASON_CODES,pt as __resetRunnerSchedulerBootstrapCacheForTests,V as createRunnerSchedulerIdentity,we as detectSchedulerCapability,ht as ensureRunnerSchedulerBootstrap,ft as observeRunnerOperationalStatus,Pe as renderSchedulerManifests,X as runRunnerSchedulerCommand};