@ornexus/neocortex 4.60.72 → 4.60.73

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 (243) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +24 -24
  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 +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 +358 -5
  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.js +635 -2
  37. package/packages/client/dist/commands/invoke.js +7200 -143
  38. package/packages/client/dist/commands/legacy-epic-terminal.js +71 -1
  39. package/packages/client/dist/commands/legacy-story-branch.js +96 -1
  40. package/packages/client/dist/commands/legacy-story-pr.js +276 -1
  41. package/packages/client/dist/commands/mutation-qa-checkpoint.js +285 -5
  42. package/packages/client/dist/commands/mutation-qa-gate.js +54 -1
  43. package/packages/client/dist/commands/mutation-qa-git.js +41 -1
  44. package/packages/client/dist/commands/mutation-qa-policy.js +102 -1
  45. package/packages/client/dist/commands/mutation-qa-run.js +219 -3
  46. package/packages/client/dist/commands/mutation-qa-verdict.js +149 -1
  47. package/packages/client/dist/commands/mutation-qa.js +220 -1
  48. package/packages/client/dist/commands/native-agent.js +136 -2
  49. package/packages/client/dist/commands/planning-diagnosis.js +43 -1
  50. package/packages/client/dist/commands/planning-generation.js +53 -1
  51. package/packages/client/dist/commands/planning-memory.js +40 -1
  52. package/packages/client/dist/commands/planning-research.js +42 -1
  53. package/packages/client/dist/commands/private-session.js +75 -1
  54. package/packages/client/dist/commands/property-qa.js +139 -1
  55. package/packages/client/dist/commands/qa-control.js +16 -1
  56. package/packages/client/dist/commands/qa-scan-browser-launch.js +55 -1
  57. package/packages/client/dist/commands/qa-scan-browser-route.js +28 -1
  58. package/packages/client/dist/commands/qa-scan-capture.js +663 -5
  59. package/packages/client/dist/commands/qa-scan-discovery.js +376 -3
  60. package/packages/client/dist/commands/qa-scan-review.js +826 -5
  61. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +266 -1
  62. package/packages/client/dist/commands/qa-synthetic-backend-review.js +297 -1
  63. package/packages/client/dist/commands/qa-synthetic-backend.js +340 -2
  64. package/packages/client/dist/commands/qa-synthetic-broker-port.js +85 -1
  65. package/packages/client/dist/commands/qa-synthetic-browser.js +39 -1
  66. package/packages/client/dist/commands/refactor-characterization.js +671 -21
  67. package/packages/client/dist/commands/refactor-commit.js +399 -13
  68. package/packages/client/dist/commands/refactor-control.js +142 -3
  69. package/packages/client/dist/commands/refactor-cpp-assertions.js +93 -3
  70. package/packages/client/dist/commands/refactor-review.js +283 -5
  71. package/packages/client/dist/commands/refactor-root.js +588 -7
  72. package/packages/client/dist/commands/refresh-memory.js +156 -3
  73. package/packages/client/dist/commands/shared-architecture-non-ui.js +24 -1
  74. package/packages/client/dist/commands/story-checkpoint.js +171 -1
  75. package/packages/client/dist/config/profile-directory.js +13 -1
  76. package/packages/client/dist/config/resolver-selection.js +278 -1
  77. package/packages/client/dist/config/secure-config.js +281 -12
  78. package/packages/client/dist/config.js +223 -2
  79. package/packages/client/dist/constants.js +25 -1
  80. package/packages/client/dist/context/context-collector.js +222 -2
  81. package/packages/client/dist/context/context-sanitizer.js +145 -1
  82. package/packages/client/dist/continuity/autonomous-governance.js +285 -1
  83. package/packages/client/dist/continuity/continuity-client-state-store.js +1587 -1
  84. package/packages/client/dist/continuity/invoke-hooks.js +129 -1
  85. package/packages/client/dist/continuity/migrations/001-initial-schema.js +12 -2
  86. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +12 -2
  87. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +12 -2
  88. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +12 -2
  89. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +12 -2
  90. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +10 -2
  91. package/packages/client/dist/continuity/native-agent-store.js +69 -1
  92. package/packages/client/dist/continuity/native-agent-types.js +90 -1
  93. package/packages/client/dist/continuity/outbox.js +117 -1
  94. package/packages/client/dist/continuity/runner-bootstrap-policy.js +172 -1
  95. package/packages/client/dist/continuity/sqlite-store.d.ts +22 -1
  96. package/packages/client/dist/continuity/sqlite-store.js +2612 -81
  97. package/packages/client/dist/effects/invoke-effect-gateways.js +62 -1
  98. package/packages/client/dist/errors/error-messages.js +228 -2
  99. package/packages/client/dist/errors/frontmatter-diagnostics.js +125 -1
  100. package/packages/client/dist/evidence/collector.js +347 -1
  101. package/packages/client/dist/evidence/index.js +1 -1
  102. package/packages/client/dist/evidence/types.js +2 -0
  103. package/packages/client/dist/fs/atomic-state-replace.js +152 -1
  104. package/packages/client/dist/generated/command-registry.generated.js +4076 -1
  105. package/packages/client/dist/generated/public-projections.generated.js +149 -1
  106. package/packages/client/dist/git/direct-yolo-c01-retry.js +138 -4
  107. package/packages/client/dist/git/direct-yolo-checkpoint.js +1234 -4
  108. package/packages/client/dist/git/epic-operational-state.d.ts +198 -0
  109. package/packages/client/dist/git/epic-operational-state.js +672 -0
  110. package/packages/client/dist/git/git-lifecycle-step-ids.js +14 -1
  111. package/packages/client/dist/git/git-lifecycle-store.d.ts +9 -1
  112. package/packages/client/dist/git/git-lifecycle-store.js +1981 -9
  113. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +259 -9
  114. package/packages/client/dist/git/legacy-story-branch-setup.js +348 -4
  115. package/packages/client/dist/git/legacy-story-pr.js +3538 -70
  116. package/packages/client/dist/git/secure-filesystem-boundary.js +182 -5
  117. package/packages/client/dist/graph-retrieval/pre-command-hook.js +284 -1
  118. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +237 -1
  119. package/packages/client/dist/i18n/first-run.js +60 -2
  120. package/packages/client/dist/index.js +47 -1
  121. package/packages/client/dist/invocation/invoke-input.js +24 -1
  122. package/packages/client/dist/license/index.js +5 -1
  123. package/packages/client/dist/license/license-client.js +304 -1
  124. package/packages/client/dist/machine/fingerprint.js +163 -2
  125. package/packages/client/dist/machine/index.js +5 -1
  126. package/packages/client/dist/memory/project-memory-path-scope.js +62 -1
  127. package/packages/client/dist/memory/project-memory-writer.js +1007 -40
  128. package/packages/client/dist/memory/shared-project-memory-types.js +253 -2
  129. package/packages/client/dist/migrations/epic-lifecycle-backfill.d.ts +97 -0
  130. package/packages/client/dist/migrations/epic-lifecycle-backfill.js +1060 -0
  131. package/packages/client/dist/migrations/project-identity-capability.js +50 -1
  132. package/packages/client/dist/migrations/project-identity.js +493 -7
  133. package/packages/client/dist/migrations/state-json.d.ts +22 -0
  134. package/packages/client/dist/migrations/state-json.js +393 -4
  135. package/packages/client/dist/policy/architecture-policy.js +184 -2
  136. package/packages/client/dist/policy/index.js +7 -1
  137. package/packages/client/dist/policy/shared-policy-types.js +38 -0
  138. package/packages/client/dist/policy/subagent-approval-policy.js +55 -1
  139. package/packages/client/dist/private-execution/clean-baseline.js +279 -2
  140. package/packages/client/dist/private-execution/codex-executor.js +574 -4
  141. package/packages/client/dist/private-execution/codex-host-runtime.js +137 -1
  142. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +97 -1
  143. package/packages/client/dist/private-execution/codex-scoped-permissions.js +128 -1
  144. package/packages/client/dist/private-execution/delivery.js +410 -13
  145. package/packages/client/dist/private-execution/diagnosis-root-review.js +294 -2
  146. package/packages/client/dist/private-execution/frozen-handoff.js +19 -6
  147. package/packages/client/dist/private-execution/implementation-validation.js +106 -2
  148. package/packages/client/dist/private-execution/isolated-admission.js +1432 -23
  149. package/packages/client/dist/private-execution/isolated-session.js +725 -5
  150. package/packages/client/dist/private-execution/isolated-workspace.js +122 -1
  151. package/packages/client/dist/private-execution/pact-consumer-runtime.js +409 -3
  152. package/packages/client/dist/private-execution/pact-test-source.js +258 -1
  153. package/packages/client/dist/private-execution/pact-toolchain.js +290 -3
  154. package/packages/client/dist/private-execution/pact-write-set.js +172 -1
  155. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +406 -5
  156. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +462 -5
  157. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +139 -3
  158. package/packages/client/dist/private-execution/planning-research-checkpoint.js +325 -4
  159. package/packages/client/dist/private-execution/private-report-store.js +42 -1
  160. package/packages/client/dist/private-execution/property-test-candidate.js +103 -1
  161. package/packages/client/dist/private-execution/property-test-choices.js +147 -3
  162. package/packages/client/dist/private-execution/property-test-plan.js +271 -7
  163. package/packages/client/dist/private-execution/property-test-review.js +258 -4
  164. package/packages/client/dist/private-execution/property-test-runtime.js +372 -9
  165. package/packages/client/dist/private-execution/property-test-source.js +139 -1
  166. package/packages/client/dist/private-execution/root-checkpoint.js +80 -1
  167. package/packages/client/dist/private-execution/root-memory-git-evidence.js +135 -3
  168. package/packages/client/dist/private-execution/root-memory-recovery.js +93 -1
  169. package/packages/client/dist/private-execution/root-memory-request.js +29 -1
  170. package/packages/client/dist/private-execution/root-memory-scope.js +178 -1
  171. package/packages/client/dist/private-execution/root-memory-writer.js +102 -1
  172. package/packages/client/dist/private-execution/session-lease.js +63 -1
  173. package/packages/client/dist/private-execution/shared-private-admission-types.js +50 -1
  174. package/packages/client/dist/private-execution/shared-project-validation.js +66 -1
  175. package/packages/client/dist/private-execution/shared-root-memory-types.js +61 -1
  176. package/packages/client/dist/private-execution/ux-source-validation.js +372 -1
  177. package/packages/client/dist/private-execution/ux-write-set.js +191 -2
  178. package/packages/client/dist/registry/registry-reconciliation.js +234 -1
  179. package/packages/client/dist/resilience/circuit-breaker.js +170 -1
  180. package/packages/client/dist/resilience/degradation-manager.js +164 -1
  181. package/packages/client/dist/resilience/freshness-indicator.js +100 -1
  182. package/packages/client/dist/resilience/index.js +8 -1
  183. package/packages/client/dist/resilience/recovery-detector.js +74 -1
  184. package/packages/client/dist/resolvers/asset-resolver.js +13 -0
  185. package/packages/client/dist/resolvers/local-resolver.js +255 -8
  186. package/packages/client/dist/resolvers/remote-resolver.js +233 -1
  187. package/packages/client/dist/runner/binary.js +404 -1
  188. package/packages/client/dist/runner/cli.js +1571 -17
  189. package/packages/client/dist/runner/headless/adapters.js +49 -1
  190. package/packages/client/dist/runner/headless/claude-code-adapter.js +79 -1
  191. package/packages/client/dist/runner/headless/continuous-story-workspace.js +1628 -11
  192. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +69 -1
  193. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +110 -2
  194. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +1236 -8
  195. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +318 -2
  196. package/packages/client/dist/runner/headless/fake-adapter.js +62 -1
  197. package/packages/client/dist/runner/headless/managed-profile.js +132 -1
  198. package/packages/client/dist/runner/headless/opencode-adapter.js +145 -2
  199. package/packages/client/dist/runner/headless/prepared-story-bundle.js +43 -1
  200. package/packages/client/dist/runner/headless/resolver.js +231 -1
  201. package/packages/client/dist/runner/headless/run-yolo.js +885 -1
  202. package/packages/client/dist/runner/headless/run-yoloop.js +2574 -2
  203. package/packages/client/dist/runner/headless/types.js +574 -2
  204. package/packages/client/dist/runner/local-console.js +396 -13
  205. package/packages/client/dist/runner/portal-sync-worker.js +1487 -1
  206. package/packages/client/dist/runner/project-identity.js +106 -1
  207. package/packages/client/dist/runner/scheduler.js +995 -7
  208. package/packages/client/dist/runner-cli.js +18 -2
  209. package/packages/client/dist/state/invocation-shape.js +13 -1
  210. package/packages/client/dist/state/project-state-snapshot.d.ts +8 -0
  211. package/packages/client/dist/state/project-state-snapshot.js +1731 -1
  212. package/packages/client/dist/state/state-json-repair.js +785 -3
  213. package/packages/client/dist/state/structural-dag-projection.js +118 -1
  214. package/packages/client/dist/telemetry/index.js +5 -1
  215. package/packages/client/dist/telemetry/offline-queue.js +131 -1
  216. package/packages/client/dist/tier/index.js +5 -1
  217. package/packages/client/dist/tier/tier-aware-client.js +405 -1
  218. package/packages/client/dist/types/index.js +38 -1
  219. package/packages/client/dist/version.js +27 -1
  220. package/packages/client/dist/yolo/change-evidence-collector.js +126 -1
  221. package/packages/client/dist/yolo/invoke-envelope-capability.js +62 -1
  222. package/packages/client/dist/yolo/spec-envelope-collector.js +184 -5
  223. package/packages/client/dist/yoloop/discovery-hook.js +300 -2
  224. package/packages/client/dist/yoloop/index.js +8 -1
  225. package/packages/client/dist/yoloop/invoke-hooks.js +669 -12
  226. package/packages/client/dist/yoloop/shared-discover-epics.js +1007 -1
  227. package/packages/client/dist/yoloop/shared-yoloop-types.d.ts +65 -1
  228. package/packages/client/dist/yoloop/shared-yoloop-types.js +33 -1
  229. package/packages/client/dist/yoloop/target-normalization.js +180 -1
  230. package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +8 -0
  231. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1920 -1
  232. package/packages/shared/dist/yolo/spec-envelope.js +3 -6
  233. package/targets-stubs/antigravity/gemini.md +1 -1
  234. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  235. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  236. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  237. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  238. package/targets-stubs/claude-code/neocortex.md +2 -2
  239. package/targets-stubs/codex/AGENTS.md +1 -1
  240. package/targets-stubs/cursor/agent.md +2 -2
  241. package/targets-stubs/gemini-cli/agent.md +2 -2
  242. package/targets-stubs/opencode/neocortex-root.md +1 -1
  243. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,7 +1,345 @@
1
- import{spawn as F}from"node:child_process";import{createHash as H,randomUUID as P}from"node:crypto";import{closeSync as b,constants as u,fstatSync as j,fsyncSync as q,openSync as w,readFileSync as D,writeFileSync as T}from"node:fs";import{join as A}from"node:path";import{planRootQaScan as z,rootQaScanEvidenceDirectory as C}from"./qa-scan-review.js";const B=/^[a-f0-9]{64}$/,I=e=>H("sha256").update(e).digest("hex");function s(e){throw new Error(`qa-synthetic-backend-${e}`)}const k=(e,r)=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).sort().join(",")===[...r].sort().join(","),R=(e,r)=>Number.isSafeInteger(e)&&Number(e)>0&&Number(e)<=r;function _(e){(!k(e,["generation","scenarioSha256","containerId","imageId","programSha256","port","routes","maxRequests","maxBodyBytes","maxResponseBytes","durationMs"])||typeof e.generation!="string"||!B.test(e.generation)||typeof e.scenarioSha256!="string"||!B.test(e.scenarioSha256)||typeof e.containerId!="string"||!B.test(e.containerId)||typeof e.imageId!="string"||!/^sha256:[a-f0-9]{64}$/.test(e.imageId)||typeof e.programSha256!="string"||!B.test(e.programSha256)||!R(e.port,65535)||!R(e.maxRequests,64)||!R(e.maxBodyBytes,16384)||!R(e.maxResponseBytes,1048576)||!R(e.durationMs,3e4)||!Array.isArray(e.routes)||!e.routes.length||e.routes.length>32)&&s("contract-invalid");const r=new Set;for(const t of e.routes){(!k(t,["path","method","fields"])||typeof t.path!="string"||!/^\/[a-zA-Z0-9/_-]*$/.test(t.path)||t.path.length>256||!["GET","POST","PUT","DELETE"].includes(String(t.method))||!t.fields||typeof t.fields!="object"||Array.isArray(t.fields)||Object.keys(t.fields).length>16||t.method==="GET"&&Object.keys(t.fields).length)&&s("contract-invalid");for(const[a,i]of Object.entries(t.fields))(!/^[a-z][a-z0-9_]{0,31}$/.test(a)||["constructor","prototype","__proto__"].includes(a)||!Array.isArray(i)||!i.length||i.length>32||i.some(d=>typeof d!="string"||d.length>256||/[\x00-\x1f\x7f]/.test(d)))&&s("contract-invalid");const n=`${t.method} ${t.path}`;r.has(n)&&s("contract-invalid"),r.add(n)}return Buffer.byteLength(JSON.stringify(e))>24576&&s("contract-invalid"),JSON.parse(JSON.stringify(e))}async function J(e,r="",t=131072,n=5e3){return new Promise((a,i)=>{if(process.platform!=="linux"){i(new Error("qa-synthetic-backend-host-unsupported"));return}const d=F("docker",["--host","unix:///var/run/docker.sock",...e],{stdio:["pipe","pipe","pipe"]}),p=[];let g=0,S=!1;const f=c=>{S||(S=!0,clearTimeout(o),c?(d.kill("SIGKILL"),i(c)):a(Buffer.concat(p).toString("utf8")))},o=setTimeout(()=>f(new Error("qa-synthetic-backend-transport-timeout")),n);d.stdout.on("data",c=>{g+=c.length,g>t?f(new Error("qa-synthetic-backend-response-limit")):p.push(c)}),d.stderr.resume(),d.on("error",()=>f(new Error("qa-synthetic-backend-transport-unavailable"))),d.stdin.on("error",()=>f(new Error("qa-synthetic-backend-transport-unavailable"))),d.on("close",c=>f(c===0?void 0:new Error("qa-synthetic-backend-transport-failed"))),d.stdin.end(r)})}async function N(e){let r;try{const a=JSON.parse(await J(["inspect",e.containerId]));(!Array.isArray(a)||a.length!==1)&&s("sandbox-unverified"),r=a[0]}catch{return s("sandbox-unverified")}const t=r.HostConfig,n=r.Config;(r.Id!==e.containerId||r.Image!==e.imageId||!r.State?.Running||!t||!n||t.NetworkMode!=="none"||t.Privileged!==!1||t.ReadonlyRootfs!==!0||!Array.isArray(t.CapDrop)||!t.CapDrop.includes("ALL")||(t.CapAdd?.length??0)!==0||!t.SecurityOpt?.includes("no-new-privileges")||!/^[1-9][0-9]*(?::[1-9][0-9]*)?$/.test(n.User)||(r.Mounts?.length??0)!==0||Object.keys(t.PortBindings??{}).length!==0||t.PublishAllPorts||t.PidMode||t.IpcMode!=="private"||t.Devices?.length||t.Binds?.length||t.VolumesFrom?.length||t.ExtraHosts?.length||t.Memory<=0||t.Memory>512*1024*1024||t.PidsLimit<=0||t.PidsLimit>128||t.NanoCpus<=0||t.NanoCpus>1e9||t.DeviceRequests?.length||t.SecurityOpt.length!==1||t.UsernsMode==="host"||t.CgroupnsMode==="host"||Object.keys(t.Tmpfs??{}).some(a=>a!=="/tmp")||n.Labels?.["neocortex.qa.synthetic-generation"]!==e.generation||!Array.isArray(n.Cmd)||!n.Cmd.every(a=>typeof a=="string")||n.Entrypoint!==null&&(!Array.isArray(n.Entrypoint)||!n.Entrypoint.every(a=>typeof a=="string"))||I(JSON.stringify({entrypoint:n.Entrypoint,command:n.Cmd}))!==e.programSha256||(n.Env??[]).some(a=>!/^(PATH|NODE_VERSION|YARN_VERSION|HOME)=/.test(a)))&&s("sandbox-unverified")}async function Z(e){try{const r=e[0];let t=process.cwd(),n="",a="",i=!1,d=!1;const p=new Set;["register","capture","accept","status","observation"].includes(String(r))||s("action-invalid");for(let c=1;c<e.length;c++){const l=e[c];if(p.has(l)&&s("argument-invalid"),p.add(l),l==="--authorize-synthetic-backend")i=!0;else if(l==="--authorize-root-review")d=!0;else{const O=e[++c];(!O||O.startsWith("--"))&&s("argument-invalid"),l==="--project-root"?t=O:l==="--surface"?n=O:l==="--target-url"?a=O:s("argument-invalid")}}(!n||!a||i!==(r==="register")||d!==(r==="accept"))&&s("operator-approval-required");let g="";for await(const c of process.stdin)g+=String(c),Buffer.byteLength(g)>32768&&s("input-limit");const{parseDocument:S}=await import("yaml"),f=S(g,{strict:!0,uniqueKeys:!0,schema:"core",customTags:[]});(f.errors.length||f.warnings.length)&&s("input-invalid");const o=JSON.parse(g);if(r==="register"){const c=await W({projectRoot:t,surface:n,targetUrl:a,contract:_(o),authorizeSyntheticBackend:i});console.log(JSON.stringify({schemaVersion:1,grantId:c,qaAccepted:!1,checkpointAccepted:!1}))}else if(r==="capture"){(!k(o,["scenario","generation","grantId"])||typeof o.generation!="string"||typeof o.grantId!="string")&&s("input-invalid");const{captureSyntheticBackendScenario:c}=await import("./qa-synthetic-backend-capture.js");console.log(JSON.stringify(await c({projectRoot:t,surface:n,targetUrl:a,scenario:o.scenario,generation:o.generation,grantId:o.grantId})))}else{const c=await import("./qa-synthetic-backend-review.js");if(r==="accept"){const l=c.acceptSyntheticBackendRootReview({projectRoot:t,surface:n,targetUrl:a,report:o,authorizeRootReview:d});return console.log(JSON.stringify(l)),l.qaAccepted?0:2}if((!k(o,["sha256"])||typeof o.sha256!="string")&&s("input-invalid"),r==="observation")console.log(JSON.stringify(c.readSyntheticBackendObservation(t,n,a,o.sha256)));else{const l=c.readSyntheticBackendRootReview(t,n,a,o.sha256);return console.log(JSON.stringify(l.receipt)),l.receipt.qaAccepted?0:2}}return 0}catch(r){const t=r instanceof Error&&/^qa-(synthetic-backend|scan-review)-[a-z-]+$/.test(r.message)?r.message:"qa-synthetic-backend-unavailable";return console.error(t),1}}async function W(e){e.authorizeSyntheticBackend!==!0&&s("operator-approval-required");const r=_(e.contract),t=z(e.projectRoot,e.surface,e.targetUrl);await N(r);const n={schemaVersion:1,contract:r,planSha256:t.planSha256,sourceHead:t.sourceHead,surface:e.surface,targetUrl:e.targetUrl,expiresAt:new Date(Date.now()+r.durationMs).toISOString()},a=P(),i=C(e.projectRoot),d=w(A(i,`backend-grant-${a}.json`),u.O_WRONLY|u.O_CREAT|u.O_EXCL|u.O_NOFOLLOW,384);try{T(d,JSON.stringify(n)),q(d)}finally{b(d)}const p=w(i,u.O_RDONLY|u.O_DIRECTORY|u.O_NOFOLLOW);try{q(p)}finally{b(p)}return a}const Y=`let input='';for await(const b of process.stdin)input+=b;
1
+ /** Confined synthetic backend transport. It produces observations, never QA approval.
2
+ * The backend has no network or host mounts; the root transfers bounded HTTP data
3
+ * through Docker stdin/stdout, without exposing a host port to the browser. */
4
+ import { spawn } from 'node:child_process';
5
+ import { createHash, randomUUID } from 'node:crypto';
6
+ import { closeSync, constants, fstatSync, fsyncSync, openSync, readFileSync, writeFileSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+ import { planRootQaScan, rootQaScanEvidenceDirectory } from './qa-scan-review.js';
9
+ const HASH = /^[a-f0-9]{64}$/;
10
+ const sha = (value) => createHash('sha256').update(value).digest('hex');
11
+ function fail(reason) { throw new Error(`qa-synthetic-backend-${reason}`); }
12
+ const exact = (v, keys) => !!v && typeof v === 'object' && !Array.isArray(v)
13
+ && Object.keys(v).sort().join(',') === [...keys].sort().join(',');
14
+ const bounded = (v, max) => Number.isSafeInteger(v) && Number(v) > 0 && Number(v) <= max;
15
+ export function validateSyntheticBackendContract(v) {
16
+ if (!exact(v, ['generation', 'scenarioSha256', 'containerId', 'imageId', 'programSha256', 'port', 'routes',
17
+ 'maxRequests', 'maxBodyBytes', 'maxResponseBytes', 'durationMs'])
18
+ || typeof v.generation !== 'string' || !HASH.test(v.generation)
19
+ || typeof v.scenarioSha256 !== 'string' || !HASH.test(v.scenarioSha256)
20
+ || typeof v.containerId !== 'string' || !HASH.test(v.containerId)
21
+ || typeof v.imageId !== 'string' || !/^sha256:[a-f0-9]{64}$/.test(v.imageId)
22
+ || typeof v.programSha256 !== 'string' || !HASH.test(v.programSha256)
23
+ || !bounded(v.port, 65535) || !bounded(v.maxRequests, 64) || !bounded(v.maxBodyBytes, 16384)
24
+ || !bounded(v.maxResponseBytes, 1048576) || !bounded(v.durationMs, 30000)
25
+ || !Array.isArray(v.routes) || !v.routes.length || v.routes.length > 32)
26
+ fail('contract-invalid');
27
+ const seen = new Set();
28
+ for (const r of v.routes) {
29
+ if (!exact(r, ['path', 'method', 'fields']) || typeof r.path !== 'string'
30
+ || !/^\/[a-zA-Z0-9/_-]*$/.test(r.path) || r.path.length > 256
31
+ || !['GET', 'POST', 'PUT', 'DELETE'].includes(String(r.method))
32
+ || !r.fields || typeof r.fields !== 'object' || Array.isArray(r.fields)
33
+ || Object.keys(r.fields).length > 16 || r.method === 'GET' && Object.keys(r.fields).length)
34
+ fail('contract-invalid');
35
+ for (const [name, values] of Object.entries(r.fields)) {
36
+ if (!/^[a-z][a-z0-9_]{0,31}$/.test(name) || ['constructor', 'prototype', '__proto__'].includes(name)
37
+ || !Array.isArray(values) || !values.length || values.length > 32
38
+ || values.some(s => typeof s !== 'string' || s.length > 256 || /[\x00-\x1f\x7f]/.test(s)))
39
+ fail('contract-invalid');
40
+ }
41
+ const key = `${r.method} ${r.path}`;
42
+ if (seen.has(key))
43
+ fail('contract-invalid');
44
+ seen.add(key);
45
+ }
46
+ if (Buffer.byteLength(JSON.stringify(v)) > 24576)
47
+ fail('contract-invalid');
48
+ return JSON.parse(JSON.stringify(v));
49
+ }
50
+ /** Fixed executable/argv; caller data is carried only on stdin. */
51
+ async function docker(args, input = '', maxBytes = 131072, timeout = 5000) {
52
+ return new Promise((resolve, reject) => {
53
+ // This qualification path is Linux/local only. Ambient Docker contexts or
54
+ // DOCKER_HOST cannot redirect operator execution to another tenancy/host.
55
+ if (process.platform !== 'linux') {
56
+ reject(new Error('qa-synthetic-backend-host-unsupported'));
57
+ return;
58
+ }
59
+ const child = spawn('docker', ['--host', 'unix:///var/run/docker.sock', ...args], { stdio: ['pipe', 'pipe', 'pipe'] });
60
+ const chunks = [];
61
+ let size = 0;
62
+ let settled = false;
63
+ const finish = (error) => {
64
+ if (settled)
65
+ return;
66
+ settled = true;
67
+ clearTimeout(timer);
68
+ if (error) {
69
+ child.kill('SIGKILL');
70
+ reject(error);
71
+ }
72
+ else
73
+ resolve(Buffer.concat(chunks).toString('utf8'));
74
+ };
75
+ const timer = setTimeout(() => finish(new Error('qa-synthetic-backend-transport-timeout')), timeout);
76
+ child.stdout.on('data', (b) => { size += b.length; if (size > maxBytes)
77
+ finish(new Error('qa-synthetic-backend-response-limit'));
78
+ else
79
+ chunks.push(b); });
80
+ // Do not propagate Docker stderr, which may contain host configuration.
81
+ child.stderr.resume();
82
+ child.on('error', () => finish(new Error('qa-synthetic-backend-transport-unavailable')));
83
+ child.stdin.on('error', () => finish(new Error('qa-synthetic-backend-transport-unavailable')));
84
+ child.on('close', code => finish(code === 0 ? undefined : new Error('qa-synthetic-backend-transport-failed')));
85
+ child.stdin.end(input);
86
+ });
87
+ }
88
+ export async function verifySyntheticBackendSandbox(contract) {
89
+ let v;
90
+ try {
91
+ const rows = JSON.parse(await docker(['inspect', contract.containerId]));
92
+ if (!Array.isArray(rows) || rows.length !== 1)
93
+ fail('sandbox-unverified');
94
+ v = rows[0];
95
+ }
96
+ catch {
97
+ return fail('sandbox-unverified');
98
+ }
99
+ const h = v.HostConfig;
100
+ const c = v.Config;
101
+ if (v.Id !== contract.containerId || v.Image !== contract.imageId || !v.State?.Running
102
+ || !h || !c || h.NetworkMode !== 'none' || h.Privileged !== false || h.ReadonlyRootfs !== true
103
+ || !Array.isArray(h.CapDrop) || !h.CapDrop.includes('ALL') || (h.CapAdd?.length ?? 0) !== 0
104
+ || !h.SecurityOpt?.includes('no-new-privileges') || !/^[1-9][0-9]*(?::[1-9][0-9]*)?$/.test(c.User)
105
+ || (v.Mounts?.length ?? 0) !== 0 || Object.keys(h.PortBindings ?? {}).length !== 0
106
+ || h.PublishAllPorts || h.PidMode || h.IpcMode !== 'private' || h.Devices?.length
107
+ || h.Binds?.length || h.VolumesFrom?.length || h.ExtraHosts?.length
108
+ || h.Memory <= 0 || h.Memory > 512 * 1024 * 1024 || h.PidsLimit <= 0 || h.PidsLimit > 128
109
+ || h.NanoCpus <= 0 || h.NanoCpus > 1_000_000_000 || h.DeviceRequests?.length
110
+ || h.SecurityOpt.length !== 1 || h.UsernsMode === 'host' || h.CgroupnsMode === 'host'
111
+ || Object.keys(h.Tmpfs ?? {}).some(path => path !== '/tmp')
112
+ || c.Labels?.['neocortex.qa.synthetic-generation'] !== contract.generation
113
+ || !Array.isArray(c.Cmd) || !c.Cmd.every((s) => typeof s === 'string')
114
+ || c.Entrypoint !== null && (!Array.isArray(c.Entrypoint) || !c.Entrypoint.every((s) => typeof s === 'string'))
115
+ || sha(JSON.stringify({ entrypoint: c.Entrypoint, command: c.Cmd })) !== contract.programSha256
116
+ || (c.Env ?? []).some((e) => !/^(PATH|NODE_VERSION|YARN_VERSION|HOME)=/.test(e)))
117
+ fail('sandbox-unverified');
118
+ }
119
+ /** Separate SDK command. Registration requires explicit root consent; capture
120
+ * consumes that source-bound grant and cannot emit a QA/checkpoint approval. */
121
+ export async function syntheticBackendCliHandler(args) {
122
+ try {
123
+ const action = args[0];
124
+ let projectRoot = process.cwd();
125
+ let surface = '';
126
+ let targetUrl = '';
127
+ let authorize = false;
128
+ let authorizeReview = false;
129
+ const seen = new Set();
130
+ if (!['register', 'capture', 'accept', 'status', 'observation'].includes(String(action)))
131
+ fail('action-invalid');
132
+ for (let i = 1; i < args.length; i++) {
133
+ const flag = args[i];
134
+ if (seen.has(flag))
135
+ fail('argument-invalid');
136
+ seen.add(flag);
137
+ if (flag === '--authorize-synthetic-backend')
138
+ authorize = true;
139
+ else if (flag === '--authorize-root-review')
140
+ authorizeReview = true;
141
+ else {
142
+ const value = args[++i];
143
+ if (!value || value.startsWith('--'))
144
+ fail('argument-invalid');
145
+ if (flag === '--project-root')
146
+ projectRoot = value;
147
+ else if (flag === '--surface')
148
+ surface = value;
149
+ else if (flag === '--target-url')
150
+ targetUrl = value;
151
+ else
152
+ fail('argument-invalid');
153
+ }
154
+ }
155
+ if (!surface || !targetUrl || authorize !== (action === 'register') || authorizeReview !== (action === 'accept'))
156
+ fail('operator-approval-required');
157
+ let raw = '';
158
+ for await (const chunk of process.stdin) {
159
+ raw += String(chunk);
160
+ if (Buffer.byteLength(raw) > 32768)
161
+ fail('input-limit');
162
+ }
163
+ const { parseDocument } = await import('yaml');
164
+ const doc = parseDocument(raw, { strict: true, uniqueKeys: true, schema: 'core', customTags: [] });
165
+ if (doc.errors.length || doc.warnings.length)
166
+ fail('input-invalid');
167
+ const v = JSON.parse(raw);
168
+ if (action === 'register') {
169
+ const grantId = await registerSyntheticBackendGrant({ projectRoot, surface, targetUrl,
170
+ contract: validateSyntheticBackendContract(v), authorizeSyntheticBackend: authorize });
171
+ console.log(JSON.stringify({ schemaVersion: 1, grantId, qaAccepted: false, checkpointAccepted: false }));
172
+ }
173
+ else if (action === 'capture') {
174
+ if (!exact(v, ['scenario', 'generation', 'grantId']) || typeof v.generation !== 'string'
175
+ || typeof v.grantId !== 'string')
176
+ fail('input-invalid');
177
+ const { captureSyntheticBackendScenario } = await import('./qa-synthetic-backend-capture.js');
178
+ console.log(JSON.stringify(await captureSyntheticBackendScenario({ projectRoot, surface, targetUrl,
179
+ scenario: v.scenario, generation: v.generation, grantId: v.grantId })));
180
+ }
181
+ else {
182
+ const review = await import('./qa-synthetic-backend-review.js');
183
+ if (action === 'accept') {
184
+ const receipt = review.acceptSyntheticBackendRootReview({ projectRoot, surface, targetUrl, report: v, authorizeRootReview: authorizeReview });
185
+ console.log(JSON.stringify(receipt));
186
+ return receipt.qaAccepted ? 0 : 2;
187
+ }
188
+ if (!exact(v, ['sha256']) || typeof v.sha256 !== 'string')
189
+ fail('input-invalid');
190
+ if (action === 'observation') {
191
+ console.log(JSON.stringify(review.readSyntheticBackendObservation(projectRoot, surface, targetUrl, v.sha256)));
192
+ }
193
+ else {
194
+ const checked = review.readSyntheticBackendRootReview(projectRoot, surface, targetUrl, v.sha256);
195
+ console.log(JSON.stringify(checked.receipt));
196
+ return checked.receipt.qaAccepted ? 0 : 2;
197
+ }
198
+ }
199
+ return 0;
200
+ }
201
+ catch (error) {
202
+ const reason = error instanceof Error && /^qa-(synthetic-backend|scan-review)-[a-z-]+$/.test(error.message)
203
+ ? error.message : 'qa-synthetic-backend-unavailable';
204
+ console.error(reason);
205
+ return 1;
206
+ }
207
+ }
208
+ /** Host operator consent is required; no DOM marker or scenario JSON grants network. */
209
+ export async function registerSyntheticBackendGrant(options) {
210
+ if (options.authorizeSyntheticBackend !== true)
211
+ fail('operator-approval-required');
212
+ const contract = validateSyntheticBackendContract(options.contract);
213
+ const plan = planRootQaScan(options.projectRoot, options.surface, options.targetUrl);
214
+ await verifySyntheticBackendSandbox(contract);
215
+ const grant = { schemaVersion: 1, contract, planSha256: plan.planSha256, sourceHead: plan.sourceHead,
216
+ surface: options.surface, targetUrl: options.targetUrl, expiresAt: new Date(Date.now() + contract.durationMs).toISOString() };
217
+ const id = randomUUID();
218
+ const dir = rootQaScanEvidenceDirectory(options.projectRoot);
219
+ const fd = openSync(join(dir, `backend-grant-${id}.json`), constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
220
+ try {
221
+ writeFileSync(fd, JSON.stringify(grant));
222
+ fsyncSync(fd);
223
+ }
224
+ finally {
225
+ closeSync(fd);
226
+ }
227
+ const parent = openSync(dir, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
228
+ try {
229
+ fsyncSync(parent);
230
+ }
231
+ finally {
232
+ closeSync(parent);
233
+ }
234
+ return id;
235
+ }
236
+ // Runs inside a no-network container; only its own loopback backend is reachable.
237
+ const REQUEST_SCRIPT = `let input='';for await(const b of process.stdin)input+=b;
2
238
  const q=JSON.parse(input); const r=await fetch('http://127.0.0.1:'+q.port+q.path,{method:q.method,
3
239
  headers:q.body===null?{}:{'content-type':'application/json'},body:q.body===null?undefined:q.body,
4
240
  redirect:'manual',signal:AbortSignal.timeout(q.timeout)});
5
241
  if(r.status>=300&&r.status<400||r.headers.has('set-cookie'))process.exit(3);
6
242
  let size=0;const parts=[];for await(const b of r.body){size+=b.length;if(size>q.maxResponseBytes)process.exit(4);parts.push(Buffer.from(b));}
7
- process.stdout.write(JSON.stringify({status:r.status,body:Buffer.concat(parts).toString('base64'),contentType:r.headers.get('content-type')||'application/octet-stream'}));`;async function ee(e){/^[a-f0-9-]{36}$/.test(e.grantId)||s("grant-invalid");const r=C(e.projectRoot),t=w(A(r,`backend-grant-${e.grantId}.json`),u.O_RDONLY|u.O_NOFOLLOW);let n,a;try{const o=j(t);(!o.isFile()||o.nlink!==1||o.uid!==process.getuid?.()||o.mode&63||o.size<1||o.size>32768)&&s("grant-invalid"),a=D(t,"utf8"),n=JSON.parse(a),k(n,["schemaVersion","contract","planSha256","sourceHead","surface","targetUrl","expiresAt"])||s("grant-invalid")}finally{b(t)}const i=_(n.contract),d=()=>{const o=w(A(r,`backend-grant-${e.grantId}.json`),u.O_RDONLY|u.O_NOFOLLOW);try{const l=j(o);(!l.isFile()||l.nlink!==1||l.uid!==process.getuid?.()||l.mode&63||l.size!==Buffer.byteLength(a)||D(o,"utf8")!==a)&&s("grant-stale")}finally{b(o)}const c=z(e.projectRoot,e.surface,e.targetUrl);(n.schemaVersion!==1||n.surface!==e.surface||n.targetUrl!==e.targetUrl||n.planSha256!==c.planSha256||n.sourceHead!==c.sourceHead||i.scenarioSha256!==e.scenarioSha256||i.generation!==e.generation||!Number.isFinite(Date.parse(n.expiresAt))||Date.parse(n.expiresAt)<=Date.now())&&s("grant-stale")};d(),await N(i);const p=w(A(r,`backend-consumed-${e.grantId}`),u.O_WRONLY|u.O_CREAT|u.O_EXCL|u.O_NOFOLLOW,384);try{T(p,"consumed"),q(p)}finally{b(p)}const g=w(r,u.O_RDONLY|u.O_DIRECTORY|u.O_NOFOLLOW);try{q(g)}finally{b(g)}let S=0;const f=[];return{contractSha256:I(JSON.stringify(i)),verify:async()=>{d(),await N(i),d()},observations:()=>f.map(o=>({...o})),request:async(o,c,l,O)=>{d();const U=new URL(e.targetUrl),h=new URL(o);(h.origin!==U.origin||h.username||h.password||h.hash||h.search||Object.keys(O).some(m=>/^(authorization|proxy-authorization|cookie)$/i.test(m)))&&s("request-denied");const x=i.routes.find(m=>m.path===h.pathname&&m.method===c);if((!x||++S>i.maxRequests)&&s("request-denied"),Object.keys(x.fields).length){(l===null||Buffer.byteLength(l)>i.maxBodyBytes)&&s("request-denied");let m;try{m=JSON.parse(l)}catch{return s("request-denied")}(!k(m,Object.keys(x.fields))||Object.entries(m).some(([M,v])=>typeof v!="string"||!x.fields[M].includes(v)))&&s("request-denied")}else l!==null&&l!==""&&s("request-denied");await N(i),d();const L=Math.min(5e3,Date.parse(n.expiresAt)-Date.now());L<1&&s("grant-stale");const $=await J(["exec","-i",i.containerId,"node","--input-type=module","-e",Y],JSON.stringify({port:i.port,path:h.pathname,method:c,body:l,maxResponseBytes:i.maxResponseBytes,timeout:L}),Math.ceil(i.maxResponseBytes*4/3)+1024,L+250);d(),await N(i);const y=JSON.parse($),E=Buffer.from(y.body,"base64");return(!R(y.status,599)||y.status<200||y.status>=300&&y.status<400||E.length>i.maxResponseBytes||typeof y.contentType!="string"||y.contentType.length>128||/[\r\n]/.test(y.contentType))&&s("response-denied"),f.push({path:h.pathname,method:c,status:y.status,responseSha256:I(E.toString("base64"))}),{status:y.status,body:E,contentType:y.contentType}}}}export{ee as openSyntheticBackendSession,W as registerSyntheticBackendGrant,Z as syntheticBackendCliHandler,_ as validateSyntheticBackendContract,N as verifySyntheticBackendSandbox};
243
+ process.stdout.write(JSON.stringify({status:r.status,body:Buffer.concat(parts).toString('base64'),contentType:r.headers.get('content-type')||'application/octet-stream'}));`;
244
+ export async function openSyntheticBackendSession(options) {
245
+ if (!/^[a-f0-9-]{36}$/.test(options.grantId))
246
+ fail('grant-invalid');
247
+ const dir = rootQaScanEvidenceDirectory(options.projectRoot);
248
+ const fd = openSync(join(dir, `backend-grant-${options.grantId}.json`), constants.O_RDONLY | constants.O_NOFOLLOW);
249
+ let grant;
250
+ let grantBytes;
251
+ try {
252
+ const st = fstatSync(fd);
253
+ if (!st.isFile() || st.nlink !== 1 || st.uid !== process.getuid?.() || st.mode & 0o077 || st.size < 1 || st.size > 32768)
254
+ fail('grant-invalid');
255
+ grantBytes = readFileSync(fd, 'utf8');
256
+ grant = JSON.parse(grantBytes);
257
+ if (!exact(grant, ['schemaVersion', 'contract', 'planSha256', 'sourceHead', 'surface', 'targetUrl', 'expiresAt']))
258
+ fail('grant-invalid');
259
+ }
260
+ finally {
261
+ closeSync(fd);
262
+ }
263
+ const contract = validateSyntheticBackendContract(grant.contract);
264
+ const check = () => {
265
+ const currentFd = openSync(join(dir, `backend-grant-${options.grantId}.json`), constants.O_RDONLY | constants.O_NOFOLLOW);
266
+ try {
267
+ const st = fstatSync(currentFd);
268
+ if (!st.isFile() || st.nlink !== 1 || st.uid !== process.getuid?.() || st.mode & 0o077
269
+ || st.size !== Buffer.byteLength(grantBytes) || readFileSync(currentFd, 'utf8') !== grantBytes)
270
+ fail('grant-stale');
271
+ }
272
+ finally {
273
+ closeSync(currentFd);
274
+ }
275
+ const plan = planRootQaScan(options.projectRoot, options.surface, options.targetUrl);
276
+ if (grant.schemaVersion !== 1 || grant.surface !== options.surface || grant.targetUrl !== options.targetUrl
277
+ || grant.planSha256 !== plan.planSha256 || grant.sourceHead !== plan.sourceHead
278
+ || contract.scenarioSha256 !== options.scenarioSha256 || contract.generation !== options.generation
279
+ || !Number.isFinite(Date.parse(grant.expiresAt)) || Date.parse(grant.expiresAt) <= Date.now())
280
+ fail('grant-stale');
281
+ };
282
+ check();
283
+ await verifySyntheticBackendSandbox(contract);
284
+ // One consumption per grant, including a crash or failed scenario. No replacement/replay.
285
+ const marker = openSync(join(dir, `backend-consumed-${options.grantId}`), constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
286
+ try {
287
+ writeFileSync(marker, 'consumed');
288
+ fsyncSync(marker);
289
+ }
290
+ finally {
291
+ closeSync(marker);
292
+ }
293
+ const parent = openSync(dir, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
294
+ try {
295
+ fsyncSync(parent);
296
+ }
297
+ finally {
298
+ closeSync(parent);
299
+ }
300
+ let requests = 0;
301
+ const rows = [];
302
+ return { contractSha256: sha(JSON.stringify(contract)), verify: async () => { check(); await verifySyntheticBackendSandbox(contract); check(); },
303
+ observations: () => rows.map(r => ({ ...r })), request: async (url, method, body, headers) => {
304
+ check();
305
+ const target = new URL(options.targetUrl);
306
+ const u = new URL(url);
307
+ if (u.origin !== target.origin || u.username || u.password || u.hash || u.search
308
+ || Object.keys(headers).some(key => /^(authorization|proxy-authorization|cookie)$/i.test(key)))
309
+ fail('request-denied');
310
+ const route = contract.routes.find(r => r.path === u.pathname && r.method === method);
311
+ if (!route || ++requests > contract.maxRequests)
312
+ fail('request-denied');
313
+ if (Object.keys(route.fields).length) {
314
+ if (body === null || Buffer.byteLength(body) > contract.maxBodyBytes)
315
+ fail('request-denied');
316
+ let v;
317
+ try {
318
+ v = JSON.parse(body);
319
+ }
320
+ catch {
321
+ return fail('request-denied');
322
+ }
323
+ if (!exact(v, Object.keys(route.fields)) || Object.entries(v).some(([key, value]) => typeof value !== 'string' || !route.fields[key].includes(value)))
324
+ fail('request-denied');
325
+ }
326
+ else if (body !== null && body !== '')
327
+ fail('request-denied');
328
+ await verifySyntheticBackendSandbox(contract);
329
+ check();
330
+ const remaining = Math.min(5000, Date.parse(grant.expiresAt) - Date.now());
331
+ if (remaining < 1)
332
+ fail('grant-stale');
333
+ const output = await docker(['exec', '-i', contract.containerId, 'node', '--input-type=module', '-e', REQUEST_SCRIPT], JSON.stringify({ port: contract.port, path: u.pathname, method, body, maxResponseBytes: contract.maxResponseBytes, timeout: remaining }), Math.ceil(contract.maxResponseBytes * 4 / 3) + 1024, remaining + 250);
334
+ check();
335
+ await verifySyntheticBackendSandbox(contract);
336
+ const result = JSON.parse(output);
337
+ const bytes = Buffer.from(result.body, 'base64');
338
+ if (!bounded(result.status, 599) || result.status < 200 || result.status >= 300 && result.status < 400
339
+ || bytes.length > contract.maxResponseBytes || typeof result.contentType !== 'string'
340
+ || result.contentType.length > 128 || /[\r\n]/.test(result.contentType))
341
+ fail('response-denied');
342
+ rows.push({ path: u.pathname, method, status: result.status, responseSha256: sha(bytes.toString('base64')) });
343
+ return { status: result.status, body: bytes, contentType: result.contentType };
344
+ } };
345
+ }
@@ -1 +1,85 @@
1
- import{createHash as D}from"node:crypto";import{request as M}from"node:http";import{lstatSync as m,realpathSync as U}from"node:fs";import{dirname as z,isAbsolute as O}from"node:path";import{planRootQaScan as T}from"./qa-scan-review.js";function s(e="unverified"){throw new Error(`qa-synthetic-backend-broker-port-${e}`)}function N(e){(!e||Object.keys(e).sort().join(",")!=="contractSha256,expiresAt,generation,grantId,projectRoot,scenarioSha256,socketPath,sourceHead,surface,targetUrl"||!/^[a-f0-9]{64}$/.test(e.contractSha256)||!/^[a-f0-9]{64}$/.test(e.generation)||!/^[a-f0-9]{64}$/.test(e.scenarioSha256)||!/^[a-f0-9-]{36}$/.test(e.grantId)||!O(e.socketPath)||Buffer.byteLength(e.socketPath)>100||!Number.isFinite(Date.parse(e.expiresAt))||Date.parse(e.expiresAt)>Date.now()+3e4)&&s();const t=Object.freeze({...e}),i=z(t.socketPath),b=m(i),c=m(t.socketPath),A=new URL(t.targetUrl),$=performance.now()+Math.max(0,Date.parse(t.expiresAt)-Date.now()),h=()=>{const a=m(i),r=m(t.socketPath);(Date.now()>=Date.parse(t.expiresAt)||performance.now()>=$)&&s("expired"),(U(i)!==i||!a.isDirectory()||a.isSymbolicLink()||a.uid!==process.getuid?.()||(a.mode&511)!==448||a.dev!==b.dev||a.ino!==b.ino||!r.isSocket()||r.isSymbolicLink()||r.uid!==process.getuid?.()||(r.mode&511)!==384||r.dev!==c.dev||r.ino!==c.ino||r.ctimeMs!==c.ctimeMs||r.mtimeMs!==c.mtimeMs)&&s("custody"),T(t.projectRoot,t.surface,t.targetUrl).sourceHead!==t.sourceHead&&s("source")};h();let q=0;const S=[],E=D("sha256").update(JSON.stringify([t.sourceHead,t.surface,t.targetUrl,t.generation,t.scenarioSha256,t.grantId])).digest("hex");return Object.freeze({contractSha256:t.contractSha256,scopeSha256:E,verify:async()=>h(),observations:()=>S.map(a=>({...a})),request:async(a,r,d,L)=>{h();const n=new URL(a);(n.origin!==A.origin||n.username||n.password||n.search||n.hash||!/^\/[a-zA-Z0-9/_-]*$/.test(n.pathname)||!["GET","POST","PUT","DELETE"].includes(r)||Object.keys(L).some(y=>/^(authorization|proxy-authorization|cookie)$/i.test(y))||d!==null&&Buffer.byteLength(d)>16384||++q>64)&&s("request");const g=await new Promise((y,p)=>{const k=d===null?void 0:Buffer.from(d),f=M({socketPath:t.socketPath,path:n.pathname,method:r,agent:!1,headers:{...k?{"content-type":"application/json","content-length":String(k.length)}:{}}},o=>{const u=o.statusCode??502,l=o.headers["content-length"];if(u>=300&&u<400||u>=400||o.headers["set-cookie"]||l!==void 0&&(!/^[0-9]+$/.test(l)||Number(l)>1048576)){o.destroy(),p(new Error("qa-synthetic-backend-broker-port-unverified"));return}let w=0;const x=[];o.on("data",P=>{w+=P.length,w>1048576?(o.destroy(),p(new Error("qa-synthetic-backend-broker-port-unverified"))):x.push(P)}),o.on("error",()=>p(new Error("qa-synthetic-backend-broker-port-unverified"))),o.on("end",()=>y({status:u,body:Buffer.concat(x),contentType:o.headers["content-type"]??"application/octet-stream"}))});f.setTimeout(Math.max(1,Math.min(5e3,Date.parse(t.expiresAt)-Date.now())),()=>f.destroy()),f.on("error",o=>p(new Error(`qa-synthetic-backend-broker-port-${/^[A-Z_]+$/.test(o.code??"")?o.code.toLowerCase().replaceAll("_","-"):"transport"}`))),f.end(k)});return h(),S.push({path:n.pathname,method:r,status:g.status,responseSha256:D("sha256").update(g.body.toString("base64")).digest("hex")}),g}})}export{N as createSyntheticBrokerPort};
1
+ /** Producer data port: a single owner-private socket, no Docker or grant minting.
2
+ * Its observations require independent comparison with the root broker ledger. */
3
+ import { createHash } from 'node:crypto';
4
+ import { request } from 'node:http';
5
+ import { lstatSync, realpathSync } from 'node:fs';
6
+ import { dirname, isAbsolute } from 'node:path';
7
+ import { planRootQaScan } from './qa-scan-review.js';
8
+ function fail(reason = 'unverified') { throw new Error(`qa-synthetic-backend-broker-port-${reason}`); }
9
+ /** Trusted worker composition only. Public capture CLI never accepts a port. */
10
+ export function createSyntheticBrokerPort(value) {
11
+ if (!value || Object.keys(value).sort().join(',') !== 'contractSha256,expiresAt,generation,grantId,projectRoot,scenarioSha256,socketPath,sourceHead,surface,targetUrl'
12
+ || !/^[a-f0-9]{64}$/.test(value.contractSha256) || !/^[a-f0-9]{64}$/.test(value.generation)
13
+ || !/^[a-f0-9]{64}$/.test(value.scenarioSha256) || !/^[a-f0-9-]{36}$/.test(value.grantId)
14
+ || !isAbsolute(value.socketPath) || Buffer.byteLength(value.socketPath) > 100
15
+ || !Number.isFinite(Date.parse(value.expiresAt)) || Date.parse(value.expiresAt) > Date.now() + 30000)
16
+ fail();
17
+ const config = Object.freeze({ ...value });
18
+ const parentPath = dirname(config.socketPath);
19
+ const parent = lstatSync(parentPath);
20
+ const socket = lstatSync(config.socketPath);
21
+ const target = new URL(config.targetUrl);
22
+ const deadline = performance.now() + Math.max(0, Date.parse(config.expiresAt) - Date.now());
23
+ const check = () => {
24
+ const directory = lstatSync(parentPath), current = lstatSync(config.socketPath);
25
+ if (Date.now() >= Date.parse(config.expiresAt) || performance.now() >= deadline)
26
+ fail('expired');
27
+ if (realpathSync(parentPath) !== parentPath || !directory.isDirectory() || directory.isSymbolicLink()
28
+ || directory.uid !== process.getuid?.() || (directory.mode & 0o777) !== 0o700 || directory.dev !== parent.dev || directory.ino !== parent.ino
29
+ || !current.isSocket() || current.isSymbolicLink() || current.uid !== process.getuid?.() || (current.mode & 0o777) !== 0o600
30
+ || current.dev !== socket.dev || current.ino !== socket.ino || current.ctimeMs !== socket.ctimeMs || current.mtimeMs !== socket.mtimeMs)
31
+ fail('custody');
32
+ if (planRootQaScan(config.projectRoot, config.surface, config.targetUrl).sourceHead !== config.sourceHead)
33
+ fail('source');
34
+ };
35
+ check();
36
+ let count = 0;
37
+ const rows = [];
38
+ const scopeSha256 = createHash('sha256').update(JSON.stringify([config.sourceHead, config.surface, config.targetUrl,
39
+ config.generation, config.scenarioSha256, config.grantId])).digest('hex');
40
+ return Object.freeze({ contractSha256: config.contractSha256, scopeSha256, verify: async () => check(),
41
+ observations: () => rows.map(row => ({ ...row })), request: async (url, method, body, headers) => {
42
+ check();
43
+ const parsed = new URL(url);
44
+ if (parsed.origin !== target.origin || parsed.username || parsed.password || parsed.search || parsed.hash
45
+ || !/^\/[a-zA-Z0-9/_-]*$/.test(parsed.pathname) || !['GET', 'POST', 'PUT', 'DELETE'].includes(method)
46
+ || Object.keys(headers).some(key => /^(authorization|proxy-authorization|cookie)$/i.test(key))
47
+ || body !== null && Buffer.byteLength(body) > 16384 || ++count > 64)
48
+ fail('request');
49
+ const result = await new Promise((resolve, reject) => {
50
+ const payload = body === null ? undefined : Buffer.from(body);
51
+ const req = request({ socketPath: config.socketPath, path: parsed.pathname, method, agent: false,
52
+ headers: { ...(payload ? { 'content-type': 'application/json', 'content-length': String(payload.length) } : {}) } }, response => {
53
+ const status = response.statusCode ?? 502;
54
+ const length = response.headers['content-length'];
55
+ if (status >= 300 && status < 400 || status >= 400 || response.headers['set-cookie']
56
+ || length !== undefined && (!/^[0-9]+$/.test(length) || Number(length) > 1048576)) {
57
+ response.destroy();
58
+ reject(new Error('qa-synthetic-backend-broker-port-unverified'));
59
+ return;
60
+ }
61
+ let size = 0;
62
+ const parts = [];
63
+ response.on('data', (chunk) => {
64
+ size += chunk.length;
65
+ if (size > 1048576) {
66
+ response.destroy();
67
+ reject(new Error('qa-synthetic-backend-broker-port-unverified'));
68
+ }
69
+ else
70
+ parts.push(chunk);
71
+ });
72
+ response.on('error', () => reject(new Error('qa-synthetic-backend-broker-port-unverified')));
73
+ response.on('end', () => resolve({ status, body: Buffer.concat(parts), contentType: response.headers['content-type'] ?? 'application/octet-stream' }));
74
+ });
75
+ req.setTimeout(Math.max(1, Math.min(5000, Date.parse(config.expiresAt) - Date.now())), () => req.destroy());
76
+ req.on('error', error => reject(new Error(`qa-synthetic-backend-broker-port-${/^[A-Z_]+$/.test(error.code ?? '')
77
+ ? error.code.toLowerCase().replaceAll('_', '-') : 'transport'}`)));
78
+ req.end(payload);
79
+ });
80
+ check();
81
+ rows.push({ path: parsed.pathname, method, status: result.status,
82
+ responseSha256: createHash('sha256').update(result.body.toString('base64')).digest('hex') });
83
+ return result;
84
+ } });
85
+ }
@@ -1 +1,39 @@
1
- import{lstatSync as s,realpathSync as c}from"node:fs";import{chromium as i}from"playwright-core";async function h(){if(process.platform!=="linux")throw new Error("qa-synthetic-backend-host-unsupported");const e=process.arch==="arm64",r=e?"/usr/bin/chromium":"/opt/google/chrome/chrome",n=["/usr/bin/bwrap","/usr","/usr/lib","/usr/lib64","/etc/fonts","/etc/ld.so.cache",...e?[r]:["/opt","/opt/google","/opt/google/chrome",r]];try{for(const o of n){const t=s(o);if(t.uid!==0||t.mode&18||t.isSymbolicLink()||c(o)!==o)throw new Error}}catch{throw new Error("qa-synthetic-backend-browser-unverified")}try{return await i.launch({executablePath:"/usr/bin/bwrap",ignoreDefaultArgs:!0,timeout:1e4,env:{PATH:"/usr/bin:/bin",LANG:"C.UTF-8"},args:["--unshare-all","--die-with-parent","--ro-bind","/usr","/usr","--ro-bind","/lib","/lib","--ro-bind","/lib64","/lib64",...e?[]:["--ro-bind","/opt/google/chrome","/opt/google/chrome"],"--ro-bind","/etc/fonts","/etc/fonts","--ro-bind","/etc/ld.so.cache","/etc/ld.so.cache","--proc","/proc","--dev","/dev","--tmpfs","/tmp","--dir","/tmp/home","--chdir","/tmp","--clearenv","--setenv","HOME","/tmp/home","--setenv","PATH","/usr/bin:/bin",r,"--headless=new","--no-sandbox","--remote-debugging-pipe","--user-data-dir=/tmp/qa-profile","--disable-dev-shm-usage","--no-first-run","--disable-background-networking","--disable-component-update","--disable-sync"]})}catch{throw new Error("qa-synthetic-backend-browser-unavailable")}}export{h as launchSyntheticBackendBrowser};
1
+ /** Linux-only browser confinement for synthetic backend qualification.
2
+ * No caller executable, host HOME/workspace/run mounts or shared network. */
3
+ import { lstatSync, realpathSync } from 'node:fs';
4
+ import { chromium } from 'playwright-core';
5
+ export async function launchSyntheticBackendBrowser() {
6
+ if (process.platform !== 'linux')
7
+ throw new Error('qa-synthetic-backend-host-unsupported');
8
+ const arm = process.arch === 'arm64';
9
+ const executable = arm ? '/usr/bin/chromium' : '/opt/google/chrome/chrome';
10
+ const paths = ['/usr/bin/bwrap', '/usr', '/usr/lib', '/usr/lib64', '/etc/fonts', '/etc/ld.so.cache',
11
+ ...(arm ? [executable] : ['/opt', '/opt/google', '/opt/google/chrome', executable])];
12
+ try {
13
+ for (const path of paths) {
14
+ const stat = lstatSync(path);
15
+ if (stat.uid !== 0 || stat.mode & 0o022 || stat.isSymbolicLink() || realpathSync(path) !== path)
16
+ throw new Error();
17
+ }
18
+ }
19
+ catch {
20
+ throw new Error('qa-synthetic-backend-browser-unverified');
21
+ }
22
+ try {
23
+ return await chromium.launch({ executablePath: '/usr/bin/bwrap', ignoreDefaultArgs: true, timeout: 10000,
24
+ env: { PATH: '/usr/bin:/bin', LANG: 'C.UTF-8' }, args: [
25
+ '--unshare-all', '--die-with-parent', '--ro-bind', '/usr', '/usr',
26
+ '--ro-bind', '/lib', '/lib', '--ro-bind', '/lib64', '/lib64',
27
+ ...(!arm ? ['--ro-bind', '/opt/google/chrome', '/opt/google/chrome'] : []),
28
+ '--ro-bind', '/etc/fonts', '/etc/fonts', '--ro-bind', '/etc/ld.so.cache', '/etc/ld.so.cache',
29
+ '--proc', '/proc', '--dev', '/dev', '--tmpfs', '/tmp', '--dir', '/tmp/home', '--chdir', '/tmp',
30
+ '--clearenv', '--setenv', 'HOME', '/tmp/home', '--setenv', 'PATH', '/usr/bin:/bin',
31
+ executable, '--headless=new', '--no-sandbox', '--remote-debugging-pipe',
32
+ '--user-data-dir=/tmp/qa-profile', '--disable-dev-shm-usage', '--no-first-run',
33
+ '--disable-background-networking', '--disable-component-update', '--disable-sync',
34
+ ] });
35
+ }
36
+ catch {
37
+ throw new Error('qa-synthetic-backend-browser-unavailable');
38
+ }
39
+ }