@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,574 +1,4 @@
1
- import { codexLifecycleGuardPath } from './codex-lifecycle-guard.js';
2
- /**
3
- * P222.16 beta candidate. A local Codex CLI is an executor, not a P127 native
4
- * task delegation capability. No protected material is passed in argv, env,
5
- * files, logs, or this module's public receipt.
6
- */
7
- import { execFileSync, spawn } from 'node:child_process';
8
- import { createHash, randomBytes } from 'node:crypto';
9
- import { connect, createServer } from 'node:net';
10
- import { accessSync, lstatSync, mkdtempSync, readFileSync, realpathSync, rmdirSync, unlinkSync, constants as fsConstants, } from 'node:fs';
11
- import { homedir } from 'node:os';
12
- import { join, resolve } from 'node:path';
13
- import { gitLifecycleRuntimeDirectory } from '../git/git-lifecycle-store.js';
14
- import { captureDirectYoloCheckoutEvidence } from '../git/direct-yolo-checkpoint.js';
15
- import { createPrivateCodexScopedRunner } from './codex-scoped-permissions.js';
16
- import { createPrivateCodexHostRuntime } from './codex-host-runtime.js';
17
- const PREFLIGHT_TTL_MS = 30_000;
18
- const MAX_PROBE_OUTPUT_BYTES = 16 * 1024;
19
- const MAX_AGENT_OUTPUT_BYTES = 1024 * 1024;
20
- const MAX_AGENT_MATERIAL_BYTES = 256 * 1024;
21
- const VERSION_PATTERN = /^codex-cli\s+(\d+\.\d+\.\d+)\s*$/;
22
- const PRIVATE_PERMISSION_PROFILE = 'p222-isolated';
23
- const PRIVATE_ENVIRONMENT_KEYS = [
24
- 'PATH', 'HOME', 'LANG', 'LC_ALL', 'TERM', 'CODEX_HOME',
25
- ];
26
- // Keep these scoped to the protected exec, not the operator's global Codex
27
- // configuration. This limits local telemetry/history; it says nothing about
28
- // retention by the authenticated ChatGPT workspace or inference provider.
29
- const PRIVATE_CODEX_DATA_CONTROLS = [
30
- '-c', 'web_search="disabled"',
31
- '-c', 'features.hooks=false',
32
- '-c', 'analytics.enabled=false',
33
- '-c', 'history.persistence="none"',
34
- '-c', 'otel.exporter="none"',
35
- '-c', 'otel.metrics_exporter="none"',
36
- '-c', 'otel.trace_exporter="none"',
37
- '-c', 'otel.log_user_prompt=false',
38
- '-c', 'notify=[]',
39
- ];
40
- const scopedPreflightRunners = new WeakMap();
41
- const scopedHostRuntimes = new WeakMap();
42
- /** The CLI needs its login location and executable path, not host secrets. */
43
- export function privateCodexEnvironment(source) {
44
- const environment = {};
45
- for (const key of PRIVATE_ENVIRONMENT_KEYS) {
46
- if (typeof source[key] === 'string')
47
- environment[key] = source[key];
48
- }
49
- return environment;
50
- }
51
- export async function runBoundedCodexProcess(args, options) {
52
- if (options.configReadProbe && (options.stdin !== undefined || args.at(-1) !== 'app-server')) {
53
- throw new Error('private-codex-web-search-isolation-unproven');
54
- }
55
- return new Promise((resolveProcess, rejectProcess) => {
56
- const environment = privateCodexEnvironment(process.env);
57
- if (options.codexHome !== undefined)
58
- environment.CODEX_HOME = options.codexHome;
59
- const supervised = process.platform === 'linux';
60
- const child = spawn(supervised ? process.execPath : options.codexHome === undefined ? 'codex' : '/bin/sh', supervised
61
- ? [codexLifecycleGuardPath, 'process'] : options.codexHome === undefined
62
- ? [...args] : ['-c', 'umask 077; exec codex "$@"', 'neocortex-private-codex', ...args], {
63
- cwd: options.cwd,
64
- stdio: supervised ? ['pipe', 'pipe', 'pipe', 'ipc'] : ['pipe', 'pipe', 'pipe'],
65
- env: environment,
66
- detached: supervised,
67
- });
68
- const stop = () => {
69
- if (process.platform === 'linux' && child.pid !== undefined) {
70
- try {
71
- process.kill(-child.pid, 'SIGKILL');
72
- }
73
- catch (error) {
74
- if (error.code !== 'ESRCH')
75
- throw error;
76
- }
77
- }
78
- else
79
- child.kill('SIGKILL');
80
- };
81
- const stdout = [];
82
- const stderr = [];
83
- let stdoutBytes = 0;
84
- let stderrBytes = 0;
85
- let timedOut = false;
86
- let outputExceeded = false;
87
- let rpcBuffer = '';
88
- let rpcInitialized = false;
89
- const sendRpc = (value) => child.stdin.write(`${JSON.stringify(value)}\n`);
90
- const timeout = setTimeout(() => { timedOut = true; stop(); }, options.timeoutMs);
91
- child.stdout.on('data', (chunk) => {
92
- stdoutBytes += chunk.byteLength;
93
- if (stdoutBytes + stderrBytes > options.maxOutputBytes) {
94
- outputExceeded = true;
95
- stop();
96
- }
97
- else {
98
- stdout.push(chunk);
99
- if (options.configReadProbe) {
100
- rpcBuffer += chunk.toString('utf8');
101
- let boundary;
102
- while ((boundary = rpcBuffer.indexOf('\n')) >= 0) {
103
- const line = rpcBuffer.slice(0, boundary);
104
- rpcBuffer = rpcBuffer.slice(boundary + 1);
105
- try {
106
- const row = JSON.parse(line);
107
- if (row.id === 1 && row.result && !rpcInitialized) {
108
- rpcInitialized = true;
109
- sendRpc({ method: 'initialized', params: {} });
110
- sendRpc({ id: 2, method: 'config/read', params: { includeLayers: false, cwd: options.cwd } });
111
- }
112
- else if (row.id === 2)
113
- child.stdin.end();
114
- }
115
- catch { /* Invalid probe output is refused below; never print configuration. */ }
116
- }
117
- }
118
- }
119
- });
120
- child.stderr.on('data', (chunk) => {
121
- stderrBytes += chunk.byteLength;
122
- if (stdoutBytes + stderrBytes > options.maxOutputBytes) {
123
- outputExceeded = true;
124
- stop();
125
- }
126
- else
127
- stderr.push(chunk);
128
- });
129
- child.on('error', (error) => { clearTimeout(timeout); rejectProcess(error); });
130
- child.on('close', (exitCode) => {
131
- clearTimeout(timeout);
132
- resolveProcess({
133
- exitCode, stdout: Buffer.concat(stdout), stderr: Buffer.concat(stderr), timedOut, outputExceeded,
134
- });
135
- });
136
- child.stdin.on('error', () => {
137
- // A child that closed stdin still reaches the close handler and fails
138
- // through its physical exit code; never print the private stdin payload.
139
- });
140
- if (supervised)
141
- child.send({ kind: 'private-codex-launch', args: [...args], codexHome: options.codexHome }, error => {
142
- if (error) {
143
- clearTimeout(timeout);
144
- stop();
145
- rejectProcess(new Error('private-codex-process-guard-unavailable'));
146
- }
147
- });
148
- if (options.configReadProbe)
149
- sendRpc({ id: 1, method: 'initialize', params: {
150
- clientInfo: { name: 'p222-isolation-probe', version: '1' }, capabilities: {},
151
- } });
152
- else
153
- child.stdin.end(options.stdin);
154
- });
155
- }
156
- function processPassed(result) {
157
- return result.exitCode === 0 && !result.timedOut && !result.outputExceeded;
158
- }
159
- async function privateMcpOverrides(root, runner) {
160
- // Installed account plugins can bring MCP tools even when `codex mcp list`
161
- // reports no directly configured servers. Disable plugins on the actual
162
- // agent run and prove the CLI resolves that override to an empty catalog.
163
- const plugins = await runner(['-c', 'features.plugins=false', 'plugin', 'list', '--json'], {
164
- cwd: root, timeoutMs: 10_000, maxOutputBytes: MAX_PROBE_OUTPUT_BYTES,
165
- });
166
- const servers = await runner(['mcp', 'list', '--json'], {
167
- cwd: root, timeoutMs: 10_000, maxOutputBytes: MAX_PROBE_OUTPUT_BYTES,
168
- });
169
- if (!processPassed(plugins) || !processPassed(servers))
170
- return null;
171
- try {
172
- const pluginCatalog = JSON.parse(plugins.stdout.toString('utf8'));
173
- const directServers = JSON.parse(servers.stdout.toString('utf8'));
174
- const pluginsDisabled = Boolean(pluginCatalog && typeof pluginCatalog === 'object'
175
- && !Array.isArray(pluginCatalog)
176
- && Array.isArray(pluginCatalog.installed)
177
- && pluginCatalog.installed.length === 0);
178
- if (!pluginsDisabled || !Array.isArray(directServers) || directServers.length > 64)
179
- return null;
180
- const names = directServers.map((server) => {
181
- if (!server || typeof server !== 'object' || Array.isArray(server))
182
- throw new Error('invalid catalog');
183
- const value = server;
184
- // The CLI's dotted override parser cannot safely address dots/quoted keys.
185
- if (typeof value.name !== 'string' || !/^[A-Za-z0-9_-]{1,64}$/.test(value.name)
186
- || typeof value.enabled !== 'boolean')
187
- throw new Error('invalid catalog');
188
- return value.name;
189
- });
190
- if (new Set(names).size !== names.length)
191
- return null;
192
- if (names.length === 0)
193
- return [];
194
- const overrides = [...names].sort().flatMap(name => ['-c', `mcp_servers.${name}.enabled=false`]);
195
- const scoped = await runner([...overrides, 'mcp', 'list', '--json'], {
196
- cwd: root, timeoutMs: 10_000, maxOutputBytes: MAX_PROBE_OUTPUT_BYTES,
197
- });
198
- if (!processPassed(scoped))
199
- return null;
200
- const resolved = JSON.parse(scoped.stdout.toString('utf8'));
201
- if (!Array.isArray(resolved) || resolved.length !== names.length)
202
- return null;
203
- const observed = new Set();
204
- for (const server of resolved) {
205
- if (!server || typeof server !== 'object' || Array.isArray(server)
206
- || typeof server.name !== 'string' || !names.includes(server.name)
207
- || server.enabled !== false || observed.has(server.name))
208
- return null;
209
- observed.add(server.name);
210
- }
211
- return Object.freeze(overrides);
212
- }
213
- catch {
214
- return null;
215
- }
216
- }
217
- async function checkHookIsolation(root, runner) {
218
- // User and project hooks are additive. Prove the same per-run override used
219
- // below resolves to disabled before delivering any protected material.
220
- const features = await runner(['-c', 'features.hooks=false', 'features', 'list'], {
221
- cwd: root, timeoutMs: 10_000, maxOutputBytes: MAX_PROBE_OUTPUT_BYTES,
222
- });
223
- if (!processPassed(features))
224
- return false;
225
- const hooks = features.stdout.toString('utf8').split(/\r?\n/)
226
- .filter((line) => /^hooks\s+\S+\s+(?:true|false)\s*$/.test(line));
227
- return hooks.length === 1 && /^hooks\s+\S+\s+false\s*$/.test(hooks[0]);
228
- }
229
- async function checkWebSearchIsolation(root, runner, mcpOverrides) {
230
- const result = await runner(['-c', 'features.plugins=false', ...mcpOverrides,
231
- ...PRIVATE_CODEX_DATA_CONTROLS, '--strict-config', 'app-server'], {
232
- cwd: root, configReadProbe: true, timeoutMs: 10_000, maxOutputBytes: 256 * 1024,
233
- });
234
- try {
235
- if (!processPassed(result))
236
- return false;
237
- const rows = result.stdout.toString('utf8').split(/\r?\n/).filter(Boolean).map(line => JSON.parse(line));
238
- const replies = rows.filter(row => row && row.id === 2);
239
- return replies.length === 1 && !replies[0].error && replies[0].result?.config?.web_search === 'disabled';
240
- }
241
- catch {
242
- return false;
243
- }
244
- finally {
245
- result.stdout.fill(0);
246
- result.stderr.fill(0);
247
- }
248
- }
249
- function requireReadableRegularFile(path) {
250
- const stat = lstatSync(path);
251
- if (!stat.isFile() || stat.isSymbolicLink())
252
- throw new Error('private-codex-auth-unavailable');
253
- accessSync(path, fsConstants.R_OK);
254
- }
255
- function gitControlDirectories(root) {
256
- const environment = { ...process.env };
257
- for (const key of [
258
- 'GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_OBJECT_DIRECTORY',
259
- 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_COMMON_DIR', 'GIT_NAMESPACE', 'GIT_CEILING_DIRECTORIES',
260
- ])
261
- delete environment[key];
262
- try {
263
- const command = (args) => execFileSync('git', [...args], {
264
- cwd: root, env: environment, encoding: 'utf8', timeout: 5_000, maxBuffer: MAX_PROBE_OUTPUT_BYTES,
265
- stdio: ['ignore', 'pipe', 'ignore'],
266
- }).trim();
267
- const directories = [command(['rev-parse', '--git-dir']), command(['rev-parse', '--git-common-dir'])]
268
- .map((path) => realpathSync(resolve(root, path)));
269
- if (directories.some((path) => !lstatSync(path).isDirectory()))
270
- throw new Error('git-control-invalid');
271
- return [...new Set(directories)];
272
- }
273
- catch {
274
- throw new Error('private-codex-git-control-unavailable');
275
- }
276
- }
277
- async function checkGitControlWriteDenied(root, runner) {
278
- const readable = await runner(['sandbox', '-P', PRIVATE_PERMISSION_PROFILE, '--', 'git', 'rev-parse', '--git-dir'], {
279
- cwd: root, timeoutMs: 10_000, maxOutputBytes: MAX_PROBE_OUTPUT_BYTES,
280
- });
281
- if (!processPassed(readable))
282
- return false;
283
- for (const directory of gitControlDirectories(root)) {
284
- const marker = join(directory, `.neocortex-git-probe-${randomBytes(16).toString('hex')}`);
285
- const denied = await runner([
286
- 'sandbox', '-P', PRIVATE_PERMISSION_PROFILE, '--', 'sh', '-c', 'mkdir "$1"', 'sh', marker,
287
- ], { cwd: root, timeoutMs: 10_000, maxOutputBytes: MAX_PROBE_OUTPUT_BYTES });
288
- let markerExists = false;
289
- let createdDirectory = false;
290
- try {
291
- const entry = lstatSync(marker);
292
- markerExists = true;
293
- createdDirectory = entry.isDirectory();
294
- }
295
- catch (error) {
296
- if (error.code !== 'ENOENT')
297
- return false;
298
- }
299
- if (markerExists) {
300
- if (createdDirectory)
301
- rmdirSync(marker);
302
- else
303
- unlinkSync(marker);
304
- }
305
- if (denied.exitCode !== 1 || denied.timedOut || denied.outputExceeded || markerExists)
306
- return false;
307
- }
308
- return true;
309
- }
310
- async function checkGitLifecycleReadDenied(root, privateDirectory, runner) {
311
- if (!lstatSync(privateDirectory).isDirectory())
312
- return false;
313
- accessSync(privateDirectory, fsConstants.R_OK);
314
- const denied = await runner([
315
- 'sandbox', '-P', PRIVATE_PERMISSION_PROFILE, '--', 'sh', '-c',
316
- 'if test -r "$1"; then exit 42; else exit 43; fi', 'sh', privateDirectory,
317
- ], { cwd: root, timeoutMs: 10_000, maxOutputBytes: MAX_PROBE_OUTPUT_BYTES });
318
- return denied.exitCode === 43 && !denied.timedOut && !denied.outputExceeded;
319
- }
320
- async function checkSandboxNetworkDenied(root, runner) {
321
- const server = createServer((socket) => socket.end());
322
- await new Promise((resolveListen, rejectListen) => {
323
- server.once('error', rejectListen);
324
- server.listen(0, '127.0.0.1', () => resolveListen());
325
- });
326
- try {
327
- const address = server.address();
328
- if (!address || typeof address === 'string')
329
- return false;
330
- // First prove the loopback endpoint is reachable outside the sandbox.
331
- const script = 'const s=require("node:net").connect(Number(process.argv[1]),"127.0.0.1");s.setTimeout(1500);s.on("connect",()=>{s.end();process.exit(0)});s.on("error",()=>process.exit(1));s.on("timeout",()=>process.exit(1))';
332
- const outside = await new Promise((resolveConnection) => {
333
- const connection = connect(address.port, '127.0.0.1');
334
- connection.setTimeout(1500);
335
- connection.once('connect', () => { connection.end(); resolveConnection(true); });
336
- connection.once('error', () => resolveConnection(false));
337
- connection.once('timeout', () => { connection.destroy(); resolveConnection(false); });
338
- });
339
- if (!outside)
340
- return false;
341
- const nodeAvailable = await runner(['sandbox', '-P', PRIVATE_PERMISSION_PROFILE, '--', 'node', '--version'], {
342
- cwd: root, timeoutMs: 5_000, maxOutputBytes: MAX_PROBE_OUTPUT_BYTES,
343
- });
344
- if (!processPassed(nodeAvailable))
345
- return false;
346
- const inside = await runner(['sandbox', '-P', PRIVATE_PERMISSION_PROFILE, '--', 'node', '-e', script, String(address.port)], {
347
- cwd: root, timeoutMs: 5_000, maxOutputBytes: MAX_PROBE_OUTPUT_BYTES,
348
- });
349
- return inside.exitCode === 1 && !inside.timedOut && !inside.outputExceeded;
350
- }
351
- finally {
352
- server.close();
353
- }
354
- }
355
- /**
356
- * Probe the exact default sandbox configuration used by `codex exec`. This
357
- * intentionally does not elevate P127 task delegation or attest remote code.
358
- */
359
- export async function preflightPrivateCodexExecutor(projectRoot, options = {}) {
360
- if ((options.platform ?? process.platform) !== 'linux')
361
- throw new Error('private-codex-platform-unsupported');
362
- const root = resolve(projectRoot);
363
- const userHome = options.userHome ?? homedir();
364
- const sourceHome = options.codexHome ?? process.env.CODEX_HOME ?? join(userHome, '.codex');
365
- const hostRuntime = options.runner ? undefined : createPrivateCodexHostRuntime(root, sourceHome);
366
- try {
367
- const base = hostRuntime ? async (args, runOptions) => {
368
- hostRuntime.verify();
369
- return runBoundedCodexProcess(args, { ...runOptions, codexHome: hostRuntime.home });
370
- } : runBoundedCodexProcess;
371
- const codexHome = hostRuntime?.home ?? sourceHome;
372
- const runner = options.runner ?? await createPrivateCodexScopedRunner(root, base, {
373
- ...options, codexHome, credentialSourceHome: hostRuntime?.sourceHome ?? sourceHome, gitControlDirectories: gitControlDirectories(root),
374
- });
375
- const authPath = join(codexHome, 'auth.json');
376
- try {
377
- requireReadableRegularFile(authPath);
378
- }
379
- catch {
380
- throw new Error('private-codex-auth-unavailable');
381
- }
382
- const version = await runner(['--version'], { cwd: root, timeoutMs: 5_000, maxOutputBytes: MAX_PROBE_OUTPUT_BYTES });
383
- const match = processPassed(version) ? VERSION_PATTERN.exec(version.stdout.toString('utf8').trim()) : null;
384
- if (!match)
385
- throw new Error('private-codex-version-unavailable');
386
- const login = await runner(['login', 'status'], { cwd: root, timeoutMs: 5_000, maxOutputBytes: MAX_PROBE_OUTPUT_BYTES });
387
- if (!processPassed(login) || !/Logged in using ChatGPT/i.test(Buffer.concat([login.stdout, login.stderr]).toString('utf8'))) {
388
- throw new Error('private-codex-subscription-required');
389
- }
390
- const mcpOverrides = await privateMcpOverrides(root, runner).catch(() => null);
391
- if (mcpOverrides === null)
392
- throw new Error('private-codex-mcp-isolation-unproven');
393
- const hookIsolation = await checkHookIsolation(root, runner).catch(() => false);
394
- if (!hookIsolation)
395
- throw new Error('private-codex-hook-isolation-unproven');
396
- if (!await checkWebSearchIsolation(root, runner, mcpOverrides).catch(() => false)) {
397
- throw new Error('private-codex-web-search-isolation-unproven');
398
- }
399
- // Codex's path-deny mount requires this exact path to exist before the first
400
- // sandbox process starts. Create it outside the sandbox and verify it later.
401
- const lifecycleDirectory = await gitLifecycleRuntimeDirectory(root).catch(() => {
402
- throw new Error('private-codex-git-lifecycle-read-isolation-unproven');
403
- });
404
- const sshDirectory = join(userHome, '.ssh');
405
- const credentialDenial = await runner([
406
- 'sandbox', '-P', PRIVATE_PERMISSION_PROFILE, '--', 'sh', '-c',
407
- ...(hostRuntime ? ['test ! -r "$1" && test ! -r "$2" && test ! -r "$3"', 'sh', authPath, sshDirectory, join(sourceHome, 'auth.json')]
408
- : ['test ! -r "$1" && test ! -r "$2"', 'sh', authPath, sshDirectory]),
409
- ], { cwd: root, timeoutMs: 10_000, maxOutputBytes: MAX_PROBE_OUTPUT_BYTES });
410
- if (!processPassed(credentialDenial))
411
- throw new Error('private-codex-auth-isolation-unproven');
412
- const probeDir = mkdtempSync(join(root, '.private-codex-probe-'));
413
- const receiptPath = join(probeDir, 'receipt');
414
- try {
415
- const writer = await runner([
416
- 'sandbox', '-P', PRIVATE_PERMISSION_PROFILE, '--', 'sh', '-c', 'printf "P222_PROBE\\n" > "$1"', 'sh', receiptPath,
417
- ], { cwd: root, timeoutMs: 10_000, maxOutputBytes: MAX_PROBE_OUTPUT_BYTES });
418
- if (!processPassed(writer) || readFileSync(receiptPath, 'utf8') !== 'P222_PROBE\n') {
419
- throw new Error('private-codex-workspace-write-unproven');
420
- }
421
- }
422
- catch {
423
- throw new Error('private-codex-workspace-write-unproven');
424
- }
425
- finally {
426
- try {
427
- unlinkSync(receiptPath);
428
- }
429
- catch { /* no receipt */ }
430
- rmdirSync(probeDir);
431
- }
432
- const gitControlWriteDenied = await checkGitControlWriteDenied(root, runner).catch(() => false);
433
- if (!gitControlWriteDenied)
434
- throw new Error('private-codex-git-control-isolation-unproven');
435
- const gitLifecycleReadDenied = await checkGitLifecycleReadDenied(root, lifecycleDirectory, runner).catch(() => false);
436
- if (!gitLifecycleReadDenied)
437
- throw new Error('private-codex-git-lifecycle-read-isolation-unproven');
438
- const networkDenied = await (options.networkProbe ?? checkSandboxNetworkDenied)(root, runner);
439
- if (!networkDenied)
440
- throw new Error('private-codex-network-isolation-unproven');
441
- const preflight = Object.freeze({
442
- schemaVersion: 6, hostKind: 'codex-cli', hostVersion: match[1], projectRoot: root,
443
- observedAtMs: (options.now ?? Date.now)(), authIsolation: 'passed', workspaceWrite: 'passed',
444
- gitControlWriteDenied: 'passed', gitLifecycleReadDenied: 'passed', mcpIsolation: 'passed',
445
- environmentIsolation: 'passed',
446
- networkDenied: 'passed', webSearchDisabled: 'passed', credentialKind: 'chatgpt-subscription',
447
- });
448
- scopedPreflightRunners.set(preflight, runner);
449
- if (hostRuntime) {
450
- const timer = setTimeout(() => {
451
- scopedHostRuntimes.delete(preflight);
452
- scopedPreflightRunners.delete(preflight);
453
- try {
454
- hostRuntime.close();
455
- }
456
- catch { /* Custody failure must not delete another owner's directory. */ }
457
- }, PREFLIGHT_TTL_MS);
458
- timer.unref();
459
- scopedHostRuntimes.set(preflight, { runtime: hostRuntime, timer });
460
- }
461
- return preflight;
462
- }
463
- catch (error) {
464
- hostRuntime?.close();
465
- throw error;
466
- }
467
- }
468
- export async function runPrivateCodexStep(material, preflight, options = {}) {
469
- const hostRuntime = scopedHostRuntimes.get(preflight);
470
- if (hostRuntime) {
471
- clearTimeout(hostRuntime.timer);
472
- scopedHostRuntimes.delete(preflight);
473
- }
474
- try {
475
- const now = (options.now ?? Date.now)();
476
- if (options.model !== undefined && !/^gpt-[a-z0-9][a-z0-9.-]{0,63}$/.test(options.model)) {
477
- throw new Error('private-codex-model-invalid');
478
- }
479
- if (preflight.schemaVersion !== 6 || preflight.hostKind !== 'codex-cli'
480
- || preflight.authIsolation !== 'passed' || preflight.workspaceWrite !== 'passed'
481
- || preflight.gitControlWriteDenied !== 'passed' || preflight.gitLifecycleReadDenied !== 'passed'
482
- || preflight.mcpIsolation !== 'passed' || preflight.environmentIsolation !== 'passed'
483
- || preflight.webSearchDisabled !== 'passed' || preflight.networkDenied !== 'passed' || preflight.credentialKind !== 'chatgpt-subscription'
484
- || now < preflight.observedAtMs || now - preflight.observedAtMs > PREFLIGHT_TTL_MS
485
- || typeof material !== 'string' || Buffer.byteLength(material, 'utf8') < 1
486
- || Buffer.byteLength(material, 'utf8') > MAX_AGENT_MATERIAL_BYTES) {
487
- throw new Error('private-codex-preflight-stale');
488
- }
489
- const runner = options.runner ?? scopedPreflightRunners.get(preflight);
490
- if (!runner)
491
- throw new Error('private-codex-preflight-stale');
492
- const version = await runner(['--version'], {
493
- cwd: preflight.projectRoot, timeoutMs: 5_000, maxOutputBytes: MAX_PROBE_OUTPUT_BYTES,
494
- });
495
- if (!processPassed(version) || VERSION_PATTERN.exec(version.stdout.toString('utf8').trim())?.[1] !== preflight.hostVersion) {
496
- throw new Error('private-codex-version-drift');
497
- }
498
- const effectFailure = (phase, processResult) => {
499
- const observation = Object.freeze({
500
- schemaVersion: 1, kind: 'PrivateCodexWorkspaceEffectFailure/1', phase,
501
- agentReturnedSuccessfully: processResult !== undefined,
502
- ...(processResult === undefined ? {} : {
503
- stdoutSha256: createHash('sha256').update(processResult.stdout).digest('hex'),
504
- stderrSha256: createHash('sha256').update(processResult.stderr).digest('hex'),
505
- stdoutBytes: processResult.stdout.length, stderrBytes: processResult.stderr.length,
506
- }), publicSafe: true,
507
- });
508
- try {
509
- void Promise.resolve(options.onWorkspaceEffectFailure?.(observation)).catch(() => undefined);
510
- }
511
- catch { /* Observation cannot replace the original refusal. */ }
512
- return new Error('private-codex-workspace-effect-unverified');
513
- };
514
- const before = options.requireWorkspaceEffect
515
- ? await captureDirectYoloCheckoutEvidence(preflight.projectRoot).catch(() => {
516
- throw effectFailure('before-capture');
517
- }) : undefined;
518
- if (before && options.expectedExecutionBranch !== undefined
519
- && before.branch !== options.expectedExecutionBranch) {
520
- throw effectFailure('branch-before');
521
- }
522
- // A managed requirement may change after the short-lived preflight. Check
523
- // again at the material handoff boundary; never let a passing old receipt
524
- // authorize an exec whose effective hook policy is now enabled.
525
- if (!await checkHookIsolation(preflight.projectRoot, runner).catch(() => false)) {
526
- throw new Error('private-codex-hook-isolation-unproven');
527
- }
528
- const mcpOverrides = await privateMcpOverrides(preflight.projectRoot, runner).catch(() => null);
529
- if (mcpOverrides === null) {
530
- throw new Error('private-codex-mcp-isolation-unproven');
531
- }
532
- if (!await checkWebSearchIsolation(preflight.projectRoot, runner, mcpOverrides).catch(() => false)) {
533
- throw new Error('private-codex-web-search-isolation-unproven');
534
- }
535
- const result = await runner([
536
- 'exec', '--ephemeral', '--json', '--strict-config', '-c', 'features.plugins=false',
537
- ...(options.model === undefined ? [] : ['--model', options.model]),
538
- ...mcpOverrides,
539
- ...PRIVATE_CODEX_DATA_CONTROLS,
540
- '-c', 'shell_environment_policy.ignore_default_excludes=false',
541
- '-c', 'shell_environment_policy.include_only=["PATH","HOME","LANG","LC_ALL","TERM"]',
542
- '-c', `default_permissions="${PRIVATE_PERMISSION_PROFILE}"`,
543
- '-C', preflight.projectRoot, '-',
544
- ], {
545
- cwd: preflight.projectRoot, stdin: material, timeoutMs: 10 * 60_000, maxOutputBytes: MAX_AGENT_OUTPUT_BYTES,
546
- });
547
- if (!processPassed(result))
548
- throw new Error('private-codex-execution-unverified');
549
- hostRuntime?.runtime.verify();
550
- if (before) {
551
- const after = await captureDirectYoloCheckoutEvidence(preflight.projectRoot).catch(() => {
552
- throw effectFailure('after-capture', result);
553
- });
554
- if (after.headSha !== before.headSha || after.branch !== before.branch) {
555
- throw effectFailure('identity-after', result);
556
- }
557
- if (after.payloadDigest === before.payloadDigest)
558
- throw effectFailure('no-payload-change', result);
559
- }
560
- return Object.freeze({
561
- schemaVersion: 1, outcome: 'executor-returned-unverified', exitCode: 0,
562
- stdoutSha256: createHash('sha256').update(result.stdout).digest('hex'),
563
- stderrSha256: createHash('sha256').update(result.stderr).digest('hex'),
564
- stdoutBytes: result.stdout.byteLength, stderrBytes: result.stderr.byteLength,
565
- publicSafe: true,
566
- });
567
- }
568
- finally {
569
- if (hostRuntime) {
570
- scopedPreflightRunners.delete(preflight);
571
- hostRuntime.runtime.close();
572
- }
573
- }
574
- }
1
+ import{codexLifecycleGuardPath as J}from"./codex-lifecycle-guard.js";import{execFileSync as X,spawn as Y}from"node:child_process";import{createHash as T,randomBytes as q}from"node:crypto";import{connect as U,createServer as Z}from"node:net";import{accessSync as k,lstatSync as B,mkdtempSync as Q,readFileSync as ee,realpathSync as te,rmdirSync as M,unlinkSync as A,constants as C}from"node:fs";import{homedir as re}from"node:os";import{join as v,resolve as L}from"node:path";import{gitLifecycleRuntimeDirectory as oe}from"../git/git-lifecycle-store.js";import{captureDirectYoloCheckoutEvidence as H}from"../git/direct-yolo-checkpoint.js";import{createPrivateCodexScopedRunner as ne}from"./codex-scoped-permissions.js";import{createPrivateCodexHostRuntime as se}from"./codex-host-runtime.js";const N=3e4,m=16*1024,ie=1024*1024,ae=256*1024,j=/^codex-cli\s+(\d+\.\d+\.\d+)\s*$/,x="p222-isolated",ce=["PATH","HOME","LANG","LC_ALL","TERM","CODEX_HOME"],G=["-c",'web_search="disabled"',"-c","features.hooks=false","-c","analytics.enabled=false","-c",'history.persistence="none"',"-c",'otel.exporter="none"',"-c",'otel.metrics_exporter="none"',"-c",'otel.trace_exporter="none"',"-c","otel.log_user_prompt=false","-c","notify=[]"],I=new WeakMap,P=new WeakMap;function de(r){const e={};for(const t of ce)typeof r[t]=="string"&&(e[t]=r[t]);return e}async function $(r,e){if(e.configReadProbe&&(e.stdin!==void 0||r.at(-1)!=="app-server"))throw new Error("private-codex-web-search-isolation-unproven");return new Promise((t,o)=>{const s=de(process.env);e.codexHome!==void 0&&(s.CODEX_HOME=e.codexHome);const n=process.platform==="linux",a=Y(n?process.execPath:e.codexHome===void 0?"codex":"/bin/sh",n?[J,"process"]:e.codexHome===void 0?[...r]:["-c",'umask 077; exec codex "$@"',"neocortex-private-codex",...r],{cwd:e.cwd,stdio:n?["pipe","pipe","pipe","ipc"]:["pipe","pipe","pipe"],env:s,detached:n}),d=()=>{if(process.platform==="linux"&&a.pid!==void 0)try{process.kill(-a.pid,"SIGKILL")}catch(l){if(l.code!=="ESRCH")throw l}else a.kill("SIGKILL")},i=[],u=[];let f=0,p=0,c=!1,w=!1,E="",S=!1;const b=l=>a.stdin.write(`${JSON.stringify(l)}
2
+ `),_=setTimeout(()=>{c=!0,d()},e.timeoutMs);a.stdout.on("data",l=>{if(f+=l.byteLength,f+p>e.maxOutputBytes)w=!0,d();else if(i.push(l),e.configReadProbe){E+=l.toString("utf8");let y;for(;(y=E.indexOf(`
3
+ `))>=0;){const D=E.slice(0,y);E=E.slice(y+1);try{const R=JSON.parse(D);R.id===1&&R.result&&!S?(S=!0,b({method:"initialized",params:{}}),b({id:2,method:"config/read",params:{includeLayers:!1,cwd:e.cwd}})):R.id===2&&a.stdin.end()}catch{}}}}),a.stderr.on("data",l=>{p+=l.byteLength,f+p>e.maxOutputBytes?(w=!0,d()):u.push(l)}),a.on("error",l=>{clearTimeout(_),o(l)}),a.on("close",l=>{clearTimeout(_),t({exitCode:l,stdout:Buffer.concat(i),stderr:Buffer.concat(u),timedOut:c,outputExceeded:w})}),a.stdin.on("error",()=>{}),n&&a.send({kind:"private-codex-launch",args:[...r],codexHome:e.codexHome},l=>{l&&(clearTimeout(_),d(),o(new Error("private-codex-process-guard-unavailable")))}),e.configReadProbe?b({id:1,method:"initialize",params:{clientInfo:{name:"p222-isolation-probe",version:"1"},capabilities:{}}}):a.stdin.end(e.stdin)})}function h(r){return r.exitCode===0&&!r.timedOut&&!r.outputExceeded}async function W(r,e){const t=await e(["-c","features.plugins=false","plugin","list","--json"],{cwd:r,timeoutMs:1e4,maxOutputBytes:m}),o=await e(["mcp","list","--json"],{cwd:r,timeoutMs:1e4,maxOutputBytes:m});if(!h(t)||!h(o))return null;try{const s=JSON.parse(t.stdout.toString("utf8")),n=JSON.parse(o.stdout.toString("utf8"));if(!!!(s&&typeof s=="object"&&!Array.isArray(s)&&Array.isArray(s.installed)&&s.installed.length===0)||!Array.isArray(n)||n.length>64)return null;const d=n.map(c=>{if(!c||typeof c!="object"||Array.isArray(c))throw new Error("invalid catalog");const w=c;if(typeof w.name!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(w.name)||typeof w.enabled!="boolean")throw new Error("invalid catalog");return w.name});if(new Set(d).size!==d.length)return null;if(d.length===0)return[];const i=[...d].sort().flatMap(c=>["-c",`mcp_servers.${c}.enabled=false`]),u=await e([...i,"mcp","list","--json"],{cwd:r,timeoutMs:1e4,maxOutputBytes:m});if(!h(u))return null;const f=JSON.parse(u.stdout.toString("utf8"));if(!Array.isArray(f)||f.length!==d.length)return null;const p=new Set;for(const c of f){if(!c||typeof c!="object"||Array.isArray(c)||typeof c.name!="string"||!d.includes(c.name)||c.enabled!==!1||p.has(c.name))return null;p.add(c.name)}return Object.freeze(i)}catch{return null}}async function z(r,e){const t=await e(["-c","features.hooks=false","features","list"],{cwd:r,timeoutMs:1e4,maxOutputBytes:m});if(!h(t))return!1;const o=t.stdout.toString("utf8").split(/\r?\n/).filter(s=>/^hooks\s+\S+\s+(?:true|false)\s*$/.test(s));return o.length===1&&/^hooks\s+\S+\s+false\s*$/.test(o[0])}async function V(r,e,t){const o=await e(["-c","features.plugins=false",...t,...G,"--strict-config","app-server"],{cwd:r,configReadProbe:!0,timeoutMs:1e4,maxOutputBytes:262144});try{if(!h(o))return!1;const n=o.stdout.toString("utf8").split(/\r?\n/).filter(Boolean).map(a=>JSON.parse(a)).filter(a=>a&&a.id===2);return n.length===1&&!n[0].error&&n[0].result?.config?.web_search==="disabled"}catch{return!1}finally{o.stdout.fill(0),o.stderr.fill(0)}}function ue(r){const e=B(r);if(!e.isFile()||e.isSymbolicLink())throw new Error("private-codex-auth-unavailable");k(r,C.R_OK)}function F(r){const e={...process.env};for(const t of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES"])delete e[t];try{const t=s=>X("git",[...s],{cwd:r,env:e,encoding:"utf8",timeout:5e3,maxBuffer:m,stdio:["ignore","pipe","ignore"]}).trim(),o=[t(["rev-parse","--git-dir"]),t(["rev-parse","--git-common-dir"])].map(s=>te(L(r,s)));if(o.some(s=>!B(s).isDirectory()))throw new Error("git-control-invalid");return[...new Set(o)]}catch{throw new Error("private-codex-git-control-unavailable")}}async function le(r,e){const t=await e(["sandbox","-P",x,"--","git","rev-parse","--git-dir"],{cwd:r,timeoutMs:1e4,maxOutputBytes:m});if(!h(t))return!1;for(const o of F(r)){const s=v(o,`.neocortex-git-probe-${q(16).toString("hex")}`),n=await e(["sandbox","-P",x,"--","sh","-c",'mkdir "$1"',"sh",s],{cwd:r,timeoutMs:1e4,maxOutputBytes:m});let a=!1,d=!1;try{const i=B(s);a=!0,d=i.isDirectory()}catch(i){if(i.code!=="ENOENT")return!1}if(a&&(d?M(s):A(s)),n.exitCode!==1||n.timedOut||n.outputExceeded||a)return!1}return!0}async function fe(r,e,t){if(!B(e).isDirectory())return!1;k(e,C.R_OK);const o=await t(["sandbox","-P",x,"--","sh","-c",'if test -r "$1"; then exit 42; else exit 43; fi',"sh",e],{cwd:r,timeoutMs:1e4,maxOutputBytes:m});return o.exitCode===43&&!o.timedOut&&!o.outputExceeded}async function pe(r,e){const t=Z(o=>o.end());await new Promise((o,s)=>{t.once("error",s),t.listen(0,"127.0.0.1",()=>o())});try{const o=t.address();if(!o||typeof o=="string")return!1;const s='const s=require("node:net").connect(Number(process.argv[1]),"127.0.0.1");s.setTimeout(1500);s.on("connect",()=>{s.end();process.exit(0)});s.on("error",()=>process.exit(1));s.on("timeout",()=>process.exit(1))';if(!await new Promise(i=>{const u=U(o.port,"127.0.0.1");u.setTimeout(1500),u.once("connect",()=>{u.end(),i(!0)}),u.once("error",()=>i(!1)),u.once("timeout",()=>{u.destroy(),i(!1)})}))return!1;const a=await e(["sandbox","-P",x,"--","node","--version"],{cwd:r,timeoutMs:5e3,maxOutputBytes:m});if(!h(a))return!1;const d=await e(["sandbox","-P",x,"--","node","-e",s,String(o.port)],{cwd:r,timeoutMs:5e3,maxOutputBytes:m});return d.exitCode===1&&!d.timedOut&&!d.outputExceeded}finally{t.close()}}async function Re(r,e={}){if((e.platform??process.platform)!=="linux")throw new Error("private-codex-platform-unsupported");const t=L(r),o=e.userHome??re(),s=e.codexHome??process.env.CODEX_HOME??v(o,".codex"),n=e.runner?void 0:se(t,s);try{const a=n?async(g,K)=>(n.verify(),$(g,{...K,codexHome:n.home})):$,d=n?.home??s,i=e.runner??await ne(t,a,{...e,codexHome:d,credentialSourceHome:n?.sourceHome??s,gitControlDirectories:F(t)}),u=v(d,"auth.json");try{ue(u)}catch{throw new Error("private-codex-auth-unavailable")}const f=await i(["--version"],{cwd:t,timeoutMs:5e3,maxOutputBytes:m}),p=h(f)?j.exec(f.stdout.toString("utf8").trim()):null;if(!p)throw new Error("private-codex-version-unavailable");const c=await i(["login","status"],{cwd:t,timeoutMs:5e3,maxOutputBytes:m});if(!h(c)||!/Logged in using ChatGPT/i.test(Buffer.concat([c.stdout,c.stderr]).toString("utf8")))throw new Error("private-codex-subscription-required");const w=await W(t,i).catch(()=>null);if(w===null)throw new Error("private-codex-mcp-isolation-unproven");if(!await z(t,i).catch(()=>!1))throw new Error("private-codex-hook-isolation-unproven");if(!await V(t,i,w).catch(()=>!1))throw new Error("private-codex-web-search-isolation-unproven");const S=await oe(t).catch(()=>{throw new Error("private-codex-git-lifecycle-read-isolation-unproven")}),b=v(o,".ssh"),_=await i(["sandbox","-P",x,"--","sh","-c",...n?['test ! -r "$1" && test ! -r "$2" && test ! -r "$3"',"sh",u,b,v(s,"auth.json")]:['test ! -r "$1" && test ! -r "$2"',"sh",u,b]],{cwd:t,timeoutMs:1e4,maxOutputBytes:m});if(!h(_))throw new Error("private-codex-auth-isolation-unproven");const l=Q(v(t,".private-codex-probe-")),y=v(l,"receipt");try{const g=await i(["sandbox","-P",x,"--","sh","-c",'printf "P222_PROBE\\n" > "$1"',"sh",y],{cwd:t,timeoutMs:1e4,maxOutputBytes:m});if(!h(g)||ee(y,"utf8")!==`P222_PROBE
4
+ `)throw new Error("private-codex-workspace-write-unproven")}catch{throw new Error("private-codex-workspace-write-unproven")}finally{try{A(y)}catch{}M(l)}if(!await le(t,i).catch(()=>!1))throw new Error("private-codex-git-control-isolation-unproven");if(!await fe(t,S,i).catch(()=>!1))throw new Error("private-codex-git-lifecycle-read-isolation-unproven");if(!await(e.networkProbe??pe)(t,i))throw new Error("private-codex-network-isolation-unproven");const O=Object.freeze({schemaVersion:6,hostKind:"codex-cli",hostVersion:p[1],projectRoot:t,observedAtMs:(e.now??Date.now)(),authIsolation:"passed",workspaceWrite:"passed",gitControlWriteDenied:"passed",gitLifecycleReadDenied:"passed",mcpIsolation:"passed",environmentIsolation:"passed",networkDenied:"passed",webSearchDisabled:"passed",credentialKind:"chatgpt-subscription"});if(I.set(O,i),n){const g=setTimeout(()=>{P.delete(O),I.delete(O);try{n.close()}catch{}},N);g.unref(),P.set(O,{runtime:n,timer:g})}return O}catch(a){throw n?.close(),a}}async function Te(r,e,t={}){const o=P.get(e);o&&(clearTimeout(o.timer),P.delete(e));try{const s=(t.now??Date.now)();if(t.model!==void 0&&!/^gpt-[a-z0-9][a-z0-9.-]{0,63}$/.test(t.model))throw new Error("private-codex-model-invalid");if(e.schemaVersion!==6||e.hostKind!=="codex-cli"||e.authIsolation!=="passed"||e.workspaceWrite!=="passed"||e.gitControlWriteDenied!=="passed"||e.gitLifecycleReadDenied!=="passed"||e.mcpIsolation!=="passed"||e.environmentIsolation!=="passed"||e.webSearchDisabled!=="passed"||e.networkDenied!=="passed"||e.credentialKind!=="chatgpt-subscription"||s<e.observedAtMs||s-e.observedAtMs>N||typeof r!="string"||Buffer.byteLength(r,"utf8")<1||Buffer.byteLength(r,"utf8")>ae)throw new Error("private-codex-preflight-stale");const n=t.runner??I.get(e);if(!n)throw new Error("private-codex-preflight-stale");const a=await n(["--version"],{cwd:e.projectRoot,timeoutMs:5e3,maxOutputBytes:m});if(!h(a)||j.exec(a.stdout.toString("utf8").trim())?.[1]!==e.hostVersion)throw new Error("private-codex-version-drift");const d=(p,c)=>{const w=Object.freeze({schemaVersion:1,kind:"PrivateCodexWorkspaceEffectFailure/1",phase:p,agentReturnedSuccessfully:c!==void 0,...c===void 0?{}:{stdoutSha256:T("sha256").update(c.stdout).digest("hex"),stderrSha256:T("sha256").update(c.stderr).digest("hex"),stdoutBytes:c.stdout.length,stderrBytes:c.stderr.length},publicSafe:!0});try{Promise.resolve(t.onWorkspaceEffectFailure?.(w)).catch(()=>{})}catch{}return new Error("private-codex-workspace-effect-unverified")},i=t.requireWorkspaceEffect?await H(e.projectRoot).catch(()=>{throw d("before-capture")}):void 0;if(i&&t.expectedExecutionBranch!==void 0&&i.branch!==t.expectedExecutionBranch)throw d("branch-before");if(!await z(e.projectRoot,n).catch(()=>!1))throw new Error("private-codex-hook-isolation-unproven");const u=await W(e.projectRoot,n).catch(()=>null);if(u===null)throw new Error("private-codex-mcp-isolation-unproven");if(!await V(e.projectRoot,n,u).catch(()=>!1))throw new Error("private-codex-web-search-isolation-unproven");const f=await n(["exec","--ephemeral","--json","--strict-config","-c","features.plugins=false",...t.model===void 0?[]:["--model",t.model],...u,...G,"-c","shell_environment_policy.ignore_default_excludes=false","-c",'shell_environment_policy.include_only=["PATH","HOME","LANG","LC_ALL","TERM"]',"-c",`default_permissions="${x}"`,"-C",e.projectRoot,"-"],{cwd:e.projectRoot,stdin:r,timeoutMs:10*6e4,maxOutputBytes:ie});if(!h(f))throw new Error("private-codex-execution-unverified");if(o?.runtime.verify(),i){const p=await H(e.projectRoot).catch(()=>{throw d("after-capture",f)});if(p.headSha!==i.headSha||p.branch!==i.branch)throw d("identity-after",f);if(p.payloadDigest===i.payloadDigest)throw d("no-payload-change",f)}return Object.freeze({schemaVersion:1,outcome:"executor-returned-unverified",exitCode:0,stdoutSha256:T("sha256").update(f.stdout).digest("hex"),stderrSha256:T("sha256").update(f.stderr).digest("hex"),stdoutBytes:f.stdout.byteLength,stderrBytes:f.stderr.byteLength,publicSafe:!0})}finally{o&&(I.delete(e),o.runtime.close())}}export{Re as preflightPrivateCodexExecutor,de as privateCodexEnvironment,$ as runBoundedCodexProcess,Te as runPrivateCodexStep};