@ornexus/neocortex 4.60.66 → 4.60.68

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 (236) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1598 -1640
  3. package/install.ps1 +1 -1
  4. package/install.sh +2 -1
  5. package/package.json +10 -7
  6. package/packages/client/dist/adapters/adapter-registry.js +108 -1
  7. package/packages/client/dist/adapters/antigravity-adapter.js +77 -2
  8. package/packages/client/dist/adapters/claude-code-adapter.js +79 -3
  9. package/packages/client/dist/adapters/codex-adapter.js +80 -2
  10. package/packages/client/dist/adapters/cursor-adapter.js +115 -4
  11. package/packages/client/dist/adapters/gemini-adapter.js +71 -2
  12. package/packages/client/dist/adapters/grok-adapter.js +42 -2
  13. package/packages/client/dist/adapters/index.js +22 -1
  14. package/packages/client/dist/adapters/platform-detector.js +212 -1
  15. package/packages/client/dist/adapters/target-adapter.js +12 -0
  16. package/packages/client/dist/adapters/vscode-adapter.js +72 -2
  17. package/packages/client/dist/agent/refresh-stubs.js +417 -2
  18. package/packages/client/dist/agent/update-agent-yaml.js +102 -1
  19. package/packages/client/dist/agent/update-description.js +251 -1
  20. package/packages/client/dist/cache/crypto-utils.js +78 -1
  21. package/packages/client/dist/cache/encrypted-cache.js +108 -1
  22. package/packages/client/dist/cache/in-memory-asset-cache.js +73 -1
  23. package/packages/client/dist/cache/index.js +13 -1
  24. package/packages/client/dist/cache/protected-pi-boundary.js +44 -1
  25. package/packages/client/dist/checkpoint/checkpoint-client-reader.js +127 -2
  26. package/packages/client/dist/checkpoint/index.js +11 -1
  27. package/packages/client/dist/checkpoint/shared-checkpoint-types.js +32 -1
  28. package/packages/client/dist/cli.js +303 -3
  29. package/packages/client/dist/commands/activate.js +394 -8
  30. package/packages/client/dist/commands/architecture-answers.js +274 -7
  31. package/packages/client/dist/commands/architecture-memory-terminal.js +253 -4
  32. package/packages/client/dist/commands/architecture-non-ui-continuation.js +100 -1
  33. package/packages/client/dist/commands/architecture-root-binding.js +51 -1
  34. package/packages/client/dist/commands/cache-status.js +112 -2
  35. package/packages/client/dist/commands/config.js +88 -1
  36. package/packages/client/dist/commands/doctor.d.ts +135 -0
  37. package/packages/client/dist/commands/doctor.js +635 -0
  38. package/packages/client/dist/commands/invoke.d.ts +18 -0
  39. package/packages/client/dist/commands/invoke.js +7140 -142
  40. package/packages/client/dist/commands/legacy-epic-terminal.js +71 -1
  41. package/packages/client/dist/commands/legacy-story-branch.js +96 -1
  42. package/packages/client/dist/commands/legacy-story-pr.js +276 -1
  43. package/packages/client/dist/commands/mutation-qa-checkpoint.js +285 -5
  44. package/packages/client/dist/commands/mutation-qa-gate.js +54 -1
  45. package/packages/client/dist/commands/mutation-qa-git.js +41 -1
  46. package/packages/client/dist/commands/mutation-qa-policy.js +102 -1
  47. package/packages/client/dist/commands/mutation-qa-run.js +219 -3
  48. package/packages/client/dist/commands/mutation-qa-verdict.js +149 -1
  49. package/packages/client/dist/commands/mutation-qa.js +220 -1
  50. package/packages/client/dist/commands/native-agent.js +136 -2
  51. package/packages/client/dist/commands/planning-diagnosis.js +43 -1
  52. package/packages/client/dist/commands/planning-generation.js +53 -1
  53. package/packages/client/dist/commands/planning-memory.js +40 -1
  54. package/packages/client/dist/commands/planning-research.js +42 -1
  55. package/packages/client/dist/commands/private-session.js +75 -1
  56. package/packages/client/dist/commands/property-qa.js +139 -1
  57. package/packages/client/dist/commands/qa-control.js +16 -1
  58. package/packages/client/dist/commands/qa-scan-browser-launch.js +55 -1
  59. package/packages/client/dist/commands/qa-scan-browser-route.js +28 -1
  60. package/packages/client/dist/commands/qa-scan-capture.js +663 -5
  61. package/packages/client/dist/commands/qa-scan-discovery.js +376 -3
  62. package/packages/client/dist/commands/qa-scan-review.js +826 -5
  63. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +266 -1
  64. package/packages/client/dist/commands/qa-synthetic-backend-review.js +297 -1
  65. package/packages/client/dist/commands/qa-synthetic-backend.js +340 -2
  66. package/packages/client/dist/commands/qa-synthetic-broker-port.js +85 -1
  67. package/packages/client/dist/commands/qa-synthetic-browser.js +39 -1
  68. package/packages/client/dist/commands/refactor-characterization.js +671 -21
  69. package/packages/client/dist/commands/refactor-commit.js +399 -13
  70. package/packages/client/dist/commands/refactor-control.js +142 -3
  71. package/packages/client/dist/commands/refactor-cpp-assertions.js +93 -3
  72. package/packages/client/dist/commands/refactor-review.js +283 -5
  73. package/packages/client/dist/commands/refactor-root.js +588 -7
  74. package/packages/client/dist/commands/refresh-memory.js +156 -3
  75. package/packages/client/dist/commands/shared-architecture-non-ui.js +24 -1
  76. package/packages/client/dist/commands/story-checkpoint.js +171 -1
  77. package/packages/client/dist/config/profile-directory.js +13 -1
  78. package/packages/client/dist/config/resolver-selection.js +278 -1
  79. package/packages/client/dist/config/secure-config.js +281 -12
  80. package/packages/client/dist/config.js +223 -2
  81. package/packages/client/dist/constants.js +25 -1
  82. package/packages/client/dist/context/context-collector.js +222 -2
  83. package/packages/client/dist/context/context-sanitizer.js +145 -1
  84. package/packages/client/dist/continuity/autonomous-governance.js +285 -1
  85. package/packages/client/dist/continuity/continuity-client-state-store.js +1587 -1
  86. package/packages/client/dist/continuity/invoke-hooks.js +129 -1
  87. package/packages/client/dist/continuity/migrations/001-initial-schema.js +12 -2
  88. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +12 -2
  89. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +12 -2
  90. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +12 -2
  91. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +12 -2
  92. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +10 -2
  93. package/packages/client/dist/continuity/native-agent-store.js +69 -1
  94. package/packages/client/dist/continuity/native-agent-types.js +90 -1
  95. package/packages/client/dist/continuity/outbox.js +117 -1
  96. package/packages/client/dist/continuity/runner-bootstrap-policy.js +172 -1
  97. package/packages/client/dist/continuity/sqlite-store.js +2536 -81
  98. package/packages/client/dist/effects/invoke-effect-gateways.js +62 -1
  99. package/packages/client/dist/errors/error-messages.js +228 -2
  100. package/packages/client/dist/errors/frontmatter-diagnostics.js +125 -1
  101. package/packages/client/dist/evidence/collector.js +347 -1
  102. package/packages/client/dist/evidence/index.js +1 -1
  103. package/packages/client/dist/evidence/types.js +2 -0
  104. package/packages/client/dist/fs/atomic-state-replace.js +152 -1
  105. package/packages/client/dist/generated/command-registry.generated.js +4076 -1
  106. package/packages/client/dist/generated/public-projections.generated.js +149 -1
  107. package/packages/client/dist/git/direct-yolo-c01-retry.js +138 -4
  108. package/packages/client/dist/git/direct-yolo-checkpoint.js +1234 -4
  109. package/packages/client/dist/git/git-lifecycle-step-ids.js +14 -1
  110. package/packages/client/dist/git/git-lifecycle-store.js +1938 -9
  111. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +259 -9
  112. package/packages/client/dist/git/legacy-story-branch-setup.js +348 -4
  113. package/packages/client/dist/git/legacy-story-pr.js +3538 -70
  114. package/packages/client/dist/git/secure-filesystem-boundary.js +182 -5
  115. package/packages/client/dist/graph-retrieval/pre-command-hook.js +284 -1
  116. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +237 -1
  117. package/packages/client/dist/i18n/first-run.js +60 -2
  118. package/packages/client/dist/index.js +47 -1
  119. package/packages/client/dist/invocation/invoke-input.js +24 -1
  120. package/packages/client/dist/license/index.js +5 -1
  121. package/packages/client/dist/license/license-client.js +304 -1
  122. package/packages/client/dist/machine/fingerprint.js +163 -2
  123. package/packages/client/dist/machine/index.js +5 -1
  124. package/packages/client/dist/memory/project-memory-path-scope.js +62 -1
  125. package/packages/client/dist/memory/project-memory-writer.js +1007 -40
  126. package/packages/client/dist/memory/shared-project-memory-types.js +253 -2
  127. package/packages/client/dist/migrations/project-identity-capability.js +50 -1
  128. package/packages/client/dist/migrations/project-identity.js +493 -7
  129. package/packages/client/dist/migrations/state-json.js +344 -4
  130. package/packages/client/dist/policy/architecture-policy.js +184 -2
  131. package/packages/client/dist/policy/index.js +7 -1
  132. package/packages/client/dist/policy/shared-policy-types.js +38 -0
  133. package/packages/client/dist/policy/subagent-approval-policy.js +55 -1
  134. package/packages/client/dist/private-execution/clean-baseline.js +279 -2
  135. package/packages/client/dist/private-execution/codex-executor.js +574 -4
  136. package/packages/client/dist/private-execution/codex-host-runtime.js +137 -1
  137. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +97 -1
  138. package/packages/client/dist/private-execution/codex-scoped-permissions.js +128 -1
  139. package/packages/client/dist/private-execution/delivery.js +410 -13
  140. package/packages/client/dist/private-execution/diagnosis-root-review.js +294 -2
  141. package/packages/client/dist/private-execution/frozen-handoff.js +19 -6
  142. package/packages/client/dist/private-execution/implementation-validation.js +106 -2
  143. package/packages/client/dist/private-execution/isolated-admission.js +1432 -23
  144. package/packages/client/dist/private-execution/isolated-session.js +725 -5
  145. package/packages/client/dist/private-execution/isolated-workspace.js +122 -1
  146. package/packages/client/dist/private-execution/pact-consumer-runtime.js +409 -3
  147. package/packages/client/dist/private-execution/pact-test-source.js +258 -1
  148. package/packages/client/dist/private-execution/pact-toolchain.js +290 -3
  149. package/packages/client/dist/private-execution/pact-write-set.js +172 -1
  150. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +406 -5
  151. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +462 -5
  152. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +139 -3
  153. package/packages/client/dist/private-execution/planning-research-checkpoint.js +325 -4
  154. package/packages/client/dist/private-execution/private-report-store.js +42 -1
  155. package/packages/client/dist/private-execution/property-test-candidate.js +103 -1
  156. package/packages/client/dist/private-execution/property-test-choices.js +147 -3
  157. package/packages/client/dist/private-execution/property-test-plan.js +271 -7
  158. package/packages/client/dist/private-execution/property-test-review.js +258 -4
  159. package/packages/client/dist/private-execution/property-test-runtime.js +372 -9
  160. package/packages/client/dist/private-execution/property-test-source.js +139 -1
  161. package/packages/client/dist/private-execution/root-checkpoint.js +80 -1
  162. package/packages/client/dist/private-execution/root-memory-git-evidence.js +135 -3
  163. package/packages/client/dist/private-execution/root-memory-recovery.js +93 -1
  164. package/packages/client/dist/private-execution/root-memory-request.js +29 -1
  165. package/packages/client/dist/private-execution/root-memory-scope.js +178 -1
  166. package/packages/client/dist/private-execution/root-memory-writer.js +102 -1
  167. package/packages/client/dist/private-execution/session-lease.js +63 -1
  168. package/packages/client/dist/private-execution/shared-private-admission-types.js +50 -1
  169. package/packages/client/dist/private-execution/shared-project-validation.js +66 -1
  170. package/packages/client/dist/private-execution/shared-root-memory-types.js +61 -1
  171. package/packages/client/dist/private-execution/ux-source-validation.js +372 -1
  172. package/packages/client/dist/private-execution/ux-write-set.js +191 -2
  173. package/packages/client/dist/resilience/circuit-breaker.js +170 -1
  174. package/packages/client/dist/resilience/degradation-manager.js +164 -1
  175. package/packages/client/dist/resilience/freshness-indicator.js +100 -1
  176. package/packages/client/dist/resilience/index.js +8 -1
  177. package/packages/client/dist/resilience/recovery-detector.js +74 -1
  178. package/packages/client/dist/resolvers/asset-resolver.js +13 -0
  179. package/packages/client/dist/resolvers/local-resolver.js +255 -8
  180. package/packages/client/dist/resolvers/remote-resolver.js +233 -1
  181. package/packages/client/dist/runner/binary.js +404 -1
  182. package/packages/client/dist/runner/cli.js +1571 -17
  183. package/packages/client/dist/runner/headless/adapters.js +49 -1
  184. package/packages/client/dist/runner/headless/claude-code-adapter.js +79 -1
  185. package/packages/client/dist/runner/headless/continuous-story-workspace.js +1628 -11
  186. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +69 -1
  187. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +110 -2
  188. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +1236 -8
  189. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +318 -2
  190. package/packages/client/dist/runner/headless/fake-adapter.js +62 -1
  191. package/packages/client/dist/runner/headless/managed-profile.js +132 -1
  192. package/packages/client/dist/runner/headless/opencode-adapter.js +145 -2
  193. package/packages/client/dist/runner/headless/prepared-story-bundle.js +43 -1
  194. package/packages/client/dist/runner/headless/resolver.js +231 -1
  195. package/packages/client/dist/runner/headless/run-yolo.js +885 -1
  196. package/packages/client/dist/runner/headless/run-yoloop.d.ts +4 -1
  197. package/packages/client/dist/runner/headless/run-yoloop.js +2574 -2
  198. package/packages/client/dist/runner/headless/types.js +574 -2
  199. package/packages/client/dist/runner/local-console.js +396 -13
  200. package/packages/client/dist/runner/portal-sync-worker.js +1487 -1
  201. package/packages/client/dist/runner/project-identity.js +106 -1
  202. package/packages/client/dist/runner/scheduler.js +995 -7
  203. package/packages/client/dist/runner-cli.js +18 -2
  204. package/packages/client/dist/state/invocation-shape.js +13 -1
  205. package/packages/client/dist/state/project-state-snapshot.js +1677 -1
  206. package/packages/client/dist/state/state-json-repair.js +785 -3
  207. package/packages/client/dist/state/structural-dag-projection.js +118 -1
  208. package/packages/client/dist/telemetry/index.js +5 -1
  209. package/packages/client/dist/telemetry/offline-queue.js +131 -1
  210. package/packages/client/dist/tier/index.js +5 -1
  211. package/packages/client/dist/tier/tier-aware-client.js +405 -1
  212. package/packages/client/dist/types/index.js +38 -1
  213. package/packages/client/dist/version.js +27 -1
  214. package/packages/client/dist/yolo/change-evidence-collector.js +126 -1
  215. package/packages/client/dist/yolo/invoke-envelope-capability.js +62 -1
  216. package/packages/client/dist/yolo/spec-envelope-collector.js +185 -5
  217. package/packages/client/dist/yoloop/discovery-hook.js +300 -2
  218. package/packages/client/dist/yoloop/index.js +8 -1
  219. package/packages/client/dist/yoloop/invoke-hooks.js +669 -12
  220. package/packages/client/dist/yoloop/shared-discover-epics.js +1007 -1
  221. package/packages/client/dist/yoloop/shared-yoloop-types.js +33 -1
  222. package/packages/client/dist/yoloop/target-normalization.js +180 -1
  223. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1723 -1
  224. package/packages/shared/dist/compatibility/index.js +476 -0
  225. package/packages/shared/dist/yoloop/release-blocked.js +653 -0
  226. package/targets-stubs/antigravity/gemini.md +1 -1
  227. package/targets-stubs/antigravity/skill/SKILL.md +3 -2
  228. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  229. package/targets-stubs/claude-code/neocortex-root.md +5 -5
  230. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  231. package/targets-stubs/claude-code/neocortex.md +8 -9
  232. package/targets-stubs/codex/AGENTS.md +3 -3
  233. package/targets-stubs/cursor/agent.md +4 -3
  234. package/targets-stubs/gemini-cli/agent.md +5 -4
  235. package/targets-stubs/opencode/neocortex-root.md +3 -3
  236. package/targets-stubs/vscode/neocortex.agent.md +5 -4
@@ -1,4 +1,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};
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
+ }