diff --git a/docs/design/sandbox-testing/CONVENTIONS.md b/docs/design/sandbox-testing/CONVENTIONS.md index 41bda3172..e12b3aebf 100644 --- a/docs/design/sandbox-testing/CONVENTIONS.md +++ b/docs/design/sandbox-testing/CONVENTIONS.md @@ -93,6 +93,10 @@ uses these decisions to preserve its stated safety and fidelity goals: 13. Mutable GitHub runner labels and images are recorded as observed runtime facts. CI is a fresh hosted VM with many preinstalled developer tools, not a blank consumer machine. +14. A native Linux request may use Lima from a macOS or Linux host when its + probed architecture matches. This is a locally available real Linux guest, + even though the host family differs; it preserves the Tier 2 purpose more + faithfully than a remote CI redirect. The plan explicitly delegates uncovered decisions to the free, lightweight, harness-agnostic option. Items 1, 2, 5, 8, and 9 resolve internal contract diff --git a/docs/design/sandbox-testing/PROGRESS.md b/docs/design/sandbox-testing/PROGRESS.md index 0b18d4477..bf62298f4 100644 --- a/docs/design/sandbox-testing/PROGRESS.md +++ b/docs/design/sandbox-testing/PROGRESS.md @@ -56,9 +56,14 @@ combined tree. | 0 | dashboard | `npm run check` after adding ECC-017 | Pass | | 0 | official upstream sources | Verified SRT Apache-2.0 research preview, Podman Apache-2.0, microsandbox Apache-2.0 repo move, Lume MIT, Lima Apache-2.0, and dockur/windows MIT | Pass | | 0 | official upstream sources | Verified Tart's Fair Source status, Microsandbox disk-only snapshot semantics, Windows Sandbox CLI, Podman diff lifecycle, and CI dispatch constraints | Pass | +| 1 | local contract fixtures | `npm run test:sandbox` | Pass, 36/36 across strict schemas, 20 routing cases, report semantics, and CLI JSON | +| 1 | local package boundary | `node tests/scripts/npm-publish-surface.test.js` | Pass, 2/2; sandbox CLI is present in the packed runtime surface | +| 1 | local dependency/tooling | Focused ESLint, Markdown lint, `yarn install --immutable`, and `git diff --check` | Pass | +| 1 | independent review | Code and security review after adversarial capability/report fixes | Pass; no blocker/high finding remains | ## Current gate -S0 is complete. No adapter implementation has started. Phase 1 is released for -contract/schema/router implementation; adapter missions remain blocked until -S1 passes its focused and cross-contract tests. +S0 and S1 are complete. No adapter implementation has started. Phase 2 is +released for capability probing; adapter missions remain blocked until the +probe emits schema-valid cached/refresh output on the development host and its +cross-platform mock matrix passes. diff --git a/package-lock.json b/package-lock.json index a692663fa..917234409 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,7 +12,8 @@ "@iarna/toml": "2.2.5", "ajv": "8.20.0", "js-yaml": "4.3.1", - "sql.js": "1.14.2" + "sql.js": "1.14.2", + "yaml": "2.9.0" }, "bin": { "ecc": "scripts/ecc.js", @@ -2905,7 +2906,6 @@ "version": "2.9.0", "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz", "integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==", - "dev": true, "license": "ISC", "bin": { "yaml": "bin.mjs" diff --git a/package.json b/package.json index 70f136fc9..c633dabf3 100644 --- a/package.json +++ b/package.json @@ -131,6 +131,7 @@ "scripts/repair.js", "scripts/setup.js", "scripts/welcome.js", + "scripts/sandbox/", "scripts/session-inspect.js", "scripts/sessions-cli.js", "scripts/setup-package-manager.js", @@ -465,6 +466,7 @@ "security:ioc-scan": "node scripts/ci/scan-supply-chain-iocs.js", "security:advisory-sources": "node scripts/ci/supply-chain-advisory-sources.js", "test:plugin-setup-platform": "node docker/plugin-setup/run-platform-tests.js", + "test:sandbox": "node tests/sandbox/contracts-router.test.js", "claw": "node scripts/claw.js", "orchestrate:status": "node scripts/orchestration-status.js", "orchestrate:worker": "bash scripts/orchestrate-codex-worker.sh", @@ -480,7 +482,8 @@ "@iarna/toml": "2.2.5", "ajv": "8.20.0", "js-yaml": "4.3.1", - "sql.js": "1.14.2" + "sql.js": "1.14.2", + "yaml": "2.9.0" }, "pi": { "extensions": [ diff --git a/schemas/sandbox-capabilities.schema.json b/schemas/sandbox-capabilities.schema.json new file mode 100644 index 000000000..1e1e0c32f --- /dev/null +++ b/schemas/sandbox-capabilities.schema.json @@ -0,0 +1,81 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://ecc.tools/schemas/sandbox-capabilities.schema.json", + "title": "ECC sandbox capability map", + "type": "object", + "additionalProperties": false, + "required": ["schema_version", "host", "backends"], + "properties": { + "schema_version": { "const": 1 }, + "generated_at": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\\.[0-9]{3})?Z$" + }, + "host": { + "type": "object", + "additionalProperties": false, + "required": ["os", "arch"], + "properties": { + "os": { "enum": ["linux", "macos", "windows"] }, + "arch": { "enum": ["arm64", "x86_64"] }, + "cpus": { "type": "integer", "minimum": 1, "maximum": 1024 }, + "inside_container": { "type": "boolean" }, + "virtualization": { "enum": ["available", "unavailable", "unknown"] } + } + }, + "backends": { + "type": "object", + "additionalProperties": false, + "properties": { + "srt": { "$ref": "#/definitions/backend" }, + "podman": { "$ref": "#/definitions/backend" }, + "microsandbox": { "$ref": "#/definitions/backend" }, + "lume": { "$ref": "#/definitions/backend" }, + "lima": { "$ref": "#/definitions/backend" }, + "windows-sandbox": { "$ref": "#/definitions/backend" }, + "hyper-v": { "$ref": "#/definitions/backend" }, + "dockur-windows": { "$ref": "#/definitions/backend" }, + "tart": { "$ref": "#/definitions/backend" }, + "ci": { "$ref": "#/definitions/backend" } + } + } + }, + "definitions": { + "target": { + "type": "object", + "additionalProperties": false, + "required": ["os", "arch"], + "properties": { + "os": { "enum": ["linux", "macos", "windows"] }, + "arch": { "enum": ["arm64", "x86_64"] } + } + }, + "backend": { + "type": "object", + "additionalProperties": false, + "required": ["available"], + "properties": { + "available": { "type": "boolean" }, + "version": { "type": ["string", "null"], "maxLength": 200 }, + "path": { "type": ["string", "null"], "maxLength": 4096 }, + "state": { + "enum": ["ready", "stopped", "not-configured", "unavailable", "unknown"] + }, + "targets": { + "type": "array", + "maxItems": 32, + "items": { "$ref": "#/definitions/target" } + }, + "capabilities": { + "type": "array", + "uniqueItems": true, + "items": { + "enum": ["ios-simulator", "domain-network-policy"] + } + }, + "reason": { "type": "string", "maxLength": 1000 }, + "fix": { "type": "string", "maxLength": 1000 } + } + } + } +} diff --git a/schemas/sandbox-manifest.schema.json b/schemas/sandbox-manifest.schema.json new file mode 100644 index 000000000..7d324910f --- /dev/null +++ b/schemas/sandbox-manifest.schema.json @@ -0,0 +1,116 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://ecc.tools/schemas/sandbox-manifest.schema.json", + "title": "ECC sandbox manifest", + "type": "object", + "additionalProperties": false, + "required": ["name", "needs", "resources", "steps", "report"], + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 120, + "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]*$" + }, + "needs": { + "type": "object", + "additionalProperties": false, + "required": ["os", "capabilities", "trust", "native"], + "properties": { + "os": { + "type": "array", + "minItems": 1, + "uniqueItems": true, + "items": { + "enum": ["linux", "macos", "windows", "any", "all"] + } + }, + "arch": { + "type": "array", + "minItems": 1, + "uniqueItems": true, + "items": { + "enum": ["arm64", "x86_64"] + } + }, + "capabilities": { + "type": "array", + "uniqueItems": true, + "items": { + "oneOf": [ + { + "enum": [ + "fs-write", + "pkg-install", + "services", + "gui", + "clean-home", + "ios-simulator" + ] + }, + { + "type": "string", + "pattern": "^network:(?:\\*|(?:\\*\\.)?(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\\.)+[A-Za-z]{2,63})$" + } + ] + } + }, + "trust": { + "enum": ["untrusted", "first-party"] + }, + "native": { + "type": "boolean" + } + } + }, + "resources": { + "type": "object", + "additionalProperties": false, + "required": ["cpu", "memory", "timeout"], + "properties": { + "cpu": { + "type": "integer", + "minimum": 1, + "maximum": 64 + }, + "memory": { + "type": "string", + "pattern": "^[1-9][0-9]*(?:MB|GB)$" + }, + "timeout": { + "type": "integer", + "minimum": 1, + "maximum": 86400 + } + } + }, + "steps": { + "type": "object", + "additionalProperties": false, + "required": ["setup", "assert"], + "properties": { + "setup": { + "$ref": "#/definitions/commands" + }, + "assert": { + "$ref": "#/definitions/commands" + } + } + }, + "report": { + "enum": ["install-diff", "exit-only"] + } + }, + "definitions": { + "commands": { + "type": "array", + "minItems": 1, + "maxItems": 1000, + "items": { + "type": "string", + "minLength": 1, + "maxLength": 8192 + } + } + } +} diff --git a/schemas/sandbox-report.schema.json b/schemas/sandbox-report.schema.json new file mode 100644 index 000000000..7179c956b --- /dev/null +++ b/schemas/sandbox-report.schema.json @@ -0,0 +1,231 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://ecc.tools/schemas/sandbox-report.schema.json", + "title": "ECC sandbox report", + "oneOf": [ + { "$ref": "#/definitions/singleReport" }, + { "$ref": "#/definitions/aggregateReport" } + ], + "definitions": { + "result": { + "enum": ["pass", "fail", "error"] + }, + "timestamp": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\\.[0-9]{3})?Z$" + }, + "escalation": { + "type": "object", + "additionalProperties": false, + "required": ["from", "reason", "to"], + "properties": { + "from": { "type": "string", "minLength": 1 }, + "reason": { "type": "string", "minLength": 1 }, + "to": { "type": "string", "minLength": 1 } + } + }, + "step": { + "type": "object", + "additionalProperties": false, + "required": ["cmd", "exit", "stdout_tail", "stderr_tail"], + "properties": { + "cmd": { "type": "string", "minLength": 1, "maxLength": 8192 }, + "exit": { "type": "integer" }, + "stdout_tail": { "type": "string", "maxLength": 65536 }, + "stderr_tail": { "type": "string", "maxLength": 65536 } + } + }, + "assertion": { + "type": "object", + "additionalProperties": false, + "required": ["cmd", "pass"], + "properties": { + "cmd": { "type": "string", "minLength": 1, "maxLength": 8192 }, + "pass": { "type": "boolean" } + } + }, + "installDiff": { + "type": "object", + "additionalProperties": false, + "required": [ + "method", + "complete", + "files_added", + "files_changed", + "files_deleted", + "path_changes", + "services_registered", + "dotfiles_touched" + ], + "properties": { + "method": { "enum": ["podman-layer", "scan", "none"] }, + "complete": { "type": "boolean" }, + "files_added": { "$ref": "#/definitions/stringArray" }, + "files_changed": { "$ref": "#/definitions/stringArray" }, + "files_deleted": { "$ref": "#/definitions/stringArray" }, + "path_changes": { "$ref": "#/definitions/stringArray" }, + "services_registered": { "$ref": "#/definitions/stringArray" }, + "dotfiles_touched": { "$ref": "#/definitions/stringArray" } + }, + "allOf": [ + { + "if": { "properties": { "method": { "const": "none" } } }, + "then": { "properties": { "complete": { "const": false } } } + } + ] + }, + "stringArray": { + "type": "array", + "maxItems": 10000, + "items": { "type": "string", "maxLength": 4096 } + }, + "singleReport": { + "type": "object", + "additionalProperties": false, + "required": [ + "manifest", + "backend", + "tier", + "os", + "arch", + "started", + "duration_ms", + "escalations", + "steps", + "assertions", + "install_diff", + "result", + "notes" + ], + "properties": { + "manifest": { "type": "string", "minLength": 1 }, + "backend": { + "enum": [ + "srt", + "podman", + "microsandbox", + "lume", + "lima", + "windows-sandbox", + "hyper-v", + "dockur-windows", + "tart" + ] + }, + "tier": { "type": "integer", "minimum": 0, "maximum": 2 }, + "os": { "enum": ["linux", "macos", "windows"] }, + "arch": { "enum": ["arm64", "x86_64"] }, + "started": { "$ref": "#/definitions/timestamp" }, + "duration_ms": { "type": "integer", "minimum": 0 }, + "escalations": { + "type": "array", + "maxItems": 1, + "items": { "$ref": "#/definitions/escalation" } + }, + "steps": { + "type": "array", + "maxItems": 1000, + "items": { "$ref": "#/definitions/step" } + }, + "assertions": { + "type": "array", + "maxItems": 1000, + "items": { "$ref": "#/definitions/assertion" } + }, + "install_diff": { "$ref": "#/definitions/installDiff" }, + "result": { "$ref": "#/definitions/result" }, + "notes": { "$ref": "#/definitions/stringArray" } + }, + "allOf": [ + { + "if": { "properties": { "backend": { "const": "srt" } } }, + "then": { "properties": { "tier": { "const": 0 } } } + }, + { + "if": { "properties": { "backend": { "enum": ["podman", "microsandbox"] } } }, + "then": { + "properties": { + "tier": { "const": 1 }, + "os": { "const": "linux" } + } + } + }, + { + "if": { "properties": { "backend": { "enum": ["lume", "tart"] } } }, + "then": { + "properties": { + "tier": { "const": 2 }, + "os": { "const": "macos" }, + "arch": { "const": "arm64" } + } + } + }, + { + "if": { "properties": { "backend": { "const": "lima" } } }, + "then": { + "properties": { + "tier": { "const": 2 }, + "os": { "const": "linux" } + } + } + }, + { + "if": { + "properties": { + "backend": { + "enum": ["windows-sandbox", "hyper-v", "dockur-windows"] + } + } + }, + "then": { + "properties": { + "tier": { "const": 2 }, + "os": { "const": "windows" } + } + } + } + ] + }, + "aggregateReport": { + "type": "object", + "additionalProperties": false, + "required": [ + "manifest", + "backend", + "tier", + "os", + "arch", + "venue", + "started", + "duration_ms", + "escalations", + "children", + "result", + "notes" + ], + "properties": { + "manifest": { "type": "string", "minLength": 1 }, + "backend": { "const": "aggregate" }, + "tier": { "type": "null" }, + "os": { "const": "multiple" }, + "arch": { "const": "multiple" }, + "venue": { "enum": ["local", "ci", "mixed"] }, + "started": { "$ref": "#/definitions/timestamp" }, + "duration_ms": { "type": "integer", "minimum": 0 }, + "escalations": { + "type": "array", + "maxItems": 1, + "items": { "$ref": "#/definitions/escalation" } + }, + "children": { + "type": "array", + "minItems": 1, + "maxItems": 32, + "items": { "$ref": "#/definitions/singleReport" } + }, + "result": { "$ref": "#/definitions/result" }, + "notes": { "$ref": "#/definitions/stringArray" } + } + } + } +} diff --git a/scripts/sandbox/contracts.js b/scripts/sandbox/contracts.js new file mode 100644 index 000000000..82e06414b --- /dev/null +++ b/scripts/sandbox/contracts.js @@ -0,0 +1,242 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const Ajv = require('ajv'); +const YAML = require('yaml'); + +const repoRoot = path.join(__dirname, '..', '..'); +const schemaPaths = { + capabilities: path.join(repoRoot, 'schemas', 'sandbox-capabilities.schema.json'), + manifest: path.join(repoRoot, 'schemas', 'sandbox-manifest.schema.json'), + report: path.join(repoRoot, 'schemas', 'sandbox-report.schema.json'), +}; +const MAX_CONTRACT_BYTES = 1024 * 1024; + +class ContractValidationError extends Error { + constructor(contract, errors) { + super(`${contract} validation failed: ${errors.join('; ')}`); + this.name = 'ContractValidationError'; + this.contract = contract; + this.errors = errors; + } +} + +function readJson(filePath) { + return JSON.parse(fs.readFileSync(filePath, 'utf8')); +} + +function readBoundedRegularFile(filePath, label = 'contract') { + const resolved = path.resolve(filePath); + const descriptor = fs.openSync( + resolved, + fs.constants.O_RDONLY | fs.constants.O_NONBLOCK + ); + try { + const stats = fs.fstatSync(descriptor); + if (!stats.isFile()) { + throw new Error(`${label} must be a regular file: ${resolved}`); + } + if (stats.size > MAX_CONTRACT_BYTES) { + throw new Error(`${label} exceeds ${MAX_CONTRACT_BYTES} bytes: ${resolved}`); + } + + const buffer = Buffer.alloc(MAX_CONTRACT_BYTES + 1); + let offset = 0; + while (offset < buffer.length) { + const bytesRead = fs.readSync(descriptor, buffer, offset, buffer.length - offset, null); + if (bytesRead === 0) break; + offset += bytesRead; + } + if (offset > MAX_CONTRACT_BYTES) { + throw new Error(`${label} exceeds ${MAX_CONTRACT_BYTES} bytes: ${resolved}`); + } + return buffer.subarray(0, offset).toString('utf8'); + } finally { + fs.closeSync(descriptor); + } +} + +function createValidator(schemaPath) { + const ajv = new Ajv({ allErrors: true, strict: true }); + return ajv.compile(readJson(schemaPath)); +} + +const validateManifestSchema = createValidator(schemaPaths.manifest); +const validateReportSchema = createValidator(schemaPaths.report); +const validateCapabilitiesSchema = createValidator(schemaPaths.capabilities); + +function formatAjvErrors(errors = []) { + return errors.map(error => { + const location = error.instancePath || '/'; + const detail = error.keyword === 'additionalProperties' + ? `: ${error.params.additionalProperty}` + : ''; + return `${location} ${error.message}${detail}`; + }); +} + +function semanticManifestErrors(manifest) { + const errors = []; + const osTargets = manifest.needs.os; + const capabilities = manifest.needs.capabilities; + const specialTargets = osTargets.filter(target => target === 'any' || target === 'all'); + + if (specialTargets.length > 0 && osTargets.length !== 1) { + errors.push('/needs/os any and all must be used alone'); + } + + const networkCapabilities = capabilities.filter(capability => capability.startsWith('network:')); + if (networkCapabilities.includes('network:*') && networkCapabilities.length > 1) { + errors.push('/needs/capabilities network:* cannot be combined with domain allowlists'); + } + + if (capabilities.includes('ios-simulator')) { + const isMacOnly = osTargets.length === 1 && osTargets[0] === 'macos'; + if (!isMacOnly) { + errors.push('/needs/os ios-simulator requires a single explicit macos target'); + } + } + + const memoryMatch = manifest.resources.memory.match(/^([1-9][0-9]*)(MB|GB)$/); + if (memoryMatch) { + const memoryMb = Number(memoryMatch[1]) * (memoryMatch[2] === 'GB' ? 1024 : 1); + if (!Number.isSafeInteger(memoryMb) || memoryMb > 1024 * 1024) { + errors.push('/resources/memory cannot exceed 1024GB'); + } + } + + for (const [phase, commands] of Object.entries(manifest.steps)) { + commands.forEach((command, index) => { + if (command.includes('\0')) { + errors.push(`/steps/${phase}/${index} commands cannot contain NUL bytes`); + } + }); + } + + return errors; +} + +function validateManifest(manifest) { + if (!validateManifestSchema(manifest)) { + throw new ContractValidationError('sandbox manifest', formatAjvErrors(validateManifestSchema.errors)); + } + + const semanticErrors = semanticManifestErrors(manifest); + if (semanticErrors.length > 0) { + throw new ContractValidationError('sandbox manifest', semanticErrors); + } + + return manifest; +} + +function validateCapabilities(capabilities) { + if (!validateCapabilitiesSchema(capabilities)) { + throw new ContractValidationError( + 'sandbox capability map', + formatAjvErrors(validateCapabilitiesSchema.errors) + ); + } + return capabilities; +} + +function validateReport(report) { + if (!validateReportSchema(report)) { + throw new ContractValidationError('sandbox report', formatAjvErrors(validateReportSchema.errors)); + } + const semanticErrors = semanticReportErrors(report); + if (semanticErrors.length > 0) { + throw new ContractValidationError('sandbox report', semanticErrors); + } + return report; +} + +function semanticReportErrors(report) { + const errors = []; + if (report.backend === 'aggregate') { + report.children.forEach((child, index) => { + for (const error of semanticReportErrors(child)) { + errors.push(`/children/${index}${error}`); + } + }); + const expected = report.children.some(child => child.result === 'error') + ? 'error' + : (report.children.some(child => child.result === 'fail') ? 'fail' : 'pass'); + if (report.result !== expected) { + errors.push(`/result aggregate result must be ${expected}`); + } + return errors; + } + + if (report.install_diff.method === 'none' && report.install_diff.complete) { + errors.push('/install_diff/complete must be false when method is none'); + } + if ( + report.result === 'pass' + && (report.steps.some(step => step.exit !== 0) || report.assertions.some(assertion => !assertion.pass)) + ) { + errors.push('/result pass requires successful steps and assertions'); + } + return errors; +} + +function parseManifestText(text, source = '') { + if (Buffer.byteLength(text, 'utf8') > MAX_CONTRACT_BYTES) { + throw new ContractValidationError('sandbox manifest', [ + `${source}: manifest exceeds ${MAX_CONTRACT_BYTES} bytes`, + ]); + } + const document = YAML.parseDocument(text, { + merge: false, + prettyErrors: false, + uniqueKeys: true, + }); + + if (document.errors.length > 0) { + throw new ContractValidationError( + 'sandbox manifest', + document.errors.map(error => `${source}: ${error.message}`) + ); + } + if (document.warnings.length > 0) { + throw new ContractValidationError( + 'sandbox manifest', + document.warnings.map(warning => `${source}: ${warning.message}`) + ); + } + + let manifest; + try { + manifest = document.toJS({ maxAliasCount: 0 }); + } catch (error) { + throw new ContractValidationError('sandbox manifest', [`${source}: ${error.message}`]); + } + + return validateManifest(manifest); +} + +function loadManifest(filePath) { + const resolved = path.resolve(filePath); + let text; + try { + text = readBoundedRegularFile(resolved, 'Sandbox manifest'); + } catch (error) { + throw new ContractValidationError('sandbox manifest', [error.message]); + } + return parseManifestText(text, resolved); +} + +module.exports = { + ContractValidationError, + MAX_CONTRACT_BYTES, + formatAjvErrors, + loadManifest, + parseManifestText, + readBoundedRegularFile, + schemaPaths, + semanticManifestErrors, + semanticReportErrors, + validateManifest, + validateCapabilities, + validateReport, +}; diff --git a/scripts/sandbox/ecc-sandbox b/scripts/sandbox/ecc-sandbox new file mode 100755 index 000000000..d29b0a9af --- /dev/null +++ b/scripts/sandbox/ecc-sandbox @@ -0,0 +1,184 @@ +#!/usr/bin/env node +'use strict'; + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { + loadManifest, + readBoundedRegularFile, + validateCapabilities, + validateReport, +} = require('./contracts'); +const { defaultHost, routeManifest } = require('./router'); + +const COMMANDS = ['probe', 'run', 'report', 'escalate']; + +function writeJson(value) { + process.stdout.write(`${JSON.stringify(value, null, 2)}\n`); +} + +function help() { + return { + name: 'ecc-sandbox', + usage: [ + 'ecc-sandbox probe [--refresh]', + 'ecc-sandbox run [--dry-run] [--local-only] [--capabilities ]', + 'ecc-sandbox report ', + 'ecc-sandbox escalate ', + ], + commands: COMMANDS, + }; +} + +function parseRunArgs(args) { + const options = { + manifestPath: null, + dryRun: false, + localOnly: false, + capabilitiesPath: null, + }; + + for (let index = 0; index < args.length; index += 1) { + const arg = args[index]; + if (arg === '--dry-run') { + options.dryRun = true; + } else if (arg === '--local-only') { + options.localOnly = true; + } else if (arg === '--capabilities') { + const value = args[index + 1]; + if (!value || value.startsWith('-')) { + throw new Error('--capabilities requires a JSON file path'); + } + options.capabilitiesPath = value; + index += 1; + } else if (arg.startsWith('-')) { + throw new Error(`Unknown run argument: ${arg}`); + } else if (options.manifestPath === null) { + options.manifestPath = arg; + } else { + throw new Error(`Unexpected run argument: ${arg}`); + } + } + + if (!options.manifestPath) { + throw new Error('run requires a sandbox manifest path'); + } + return options; +} + +function emptyCapabilityMap() { + return { + schema_version: 1, + host: defaultHost(), + backends: Object.fromEntries([ + 'srt', + 'podman', + 'microsandbox', + 'lume', + 'lima', + 'windows-sandbox', + 'hyper-v', + 'dockur-windows', + 'tart', + 'ci', + ].map(backend => [backend, { available: false }])), + }; +} + +function defaultCapabilityCachePath() { + const cacheRoot = process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache'); + return path.join(cacheRoot, 'ecc', 'sandbox-capabilities.json'); +} + +function loadCapabilities(filePath) { + const candidate = filePath ? path.resolve(filePath) : defaultCapabilityCachePath(); + if (!fs.existsSync(candidate)) return emptyCapabilityMap(); + const capabilities = validateCapabilities(JSON.parse( + readBoundedRegularFile(candidate, 'Capability map') + )); + const host = defaultHost(); + if (capabilities.host.os !== host.os || capabilities.host.arch !== host.arch) { + throw new Error( + `Capability map host ${capabilities.host.os}/${capabilities.host.arch} does not match current host ${host.os}/${host.arch}; run ecc-sandbox probe --refresh` + ); + } + return capabilities; +} + +function runDryRun(options) { + const manifestPath = path.resolve(options.manifestPath); + const manifest = loadManifest(manifestPath); + const capabilities = loadCapabilities(options.capabilitiesPath); + return routeManifest(manifest, capabilities, { + localOnly: options.localOnly, + manifestPath, + }); +} + +function runReport(args) { + if (args.length !== 1) { + throw new Error('report requires exactly one report JSON path'); + } + const reportPath = path.resolve(args[0]); + const report = JSON.parse(readBoundedRegularFile(reportPath, 'Sandbox report')); + validateReport(report); + return { + result: 'valid', + report: reportPath, + report_result: report.result, + }; +} + +function main(argv = process.argv.slice(2)) { + const [command, ...args] = argv; + if (!command || command === '--help' || command === '-h' || command === 'help') { + writeJson(help()); + return 0; + } + if (!COMMANDS.includes(command)) { + throw new Error(`Unknown command: ${command}`); + } + if (command === 'run') { + const options = parseRunArgs(args); + if (!options.dryRun) { + throw new Error('Sandbox execution is unavailable until adapter phases; use run --dry-run'); + } + const decision = runDryRun(options); + writeJson(decision); + return decision.result === 'routable' ? 0 : 2; + } + if (command === 'report') { + writeJson(runReport(args)); + return 0; + } + throw new Error(`${command} is unavailable until its implementation phase`); +} + +if (require.main === module) { + try { + process.exitCode = main(); + } catch (error) { + writeJson({ + result: 'error', + error: { + code: error.name === 'ContractValidationError' ? 'contract-invalid' : 'sandbox-cli-error', + message: error.message, + details: error.errors || [], + }, + }); + process.exitCode = 2; + } +} + +module.exports = { + defaultCapabilityCachePath, + emptyCapabilityMap, + help, + loadCapabilities, + main, + parseRunArgs, + runDryRun, + runReport, + writeJson, +}; diff --git a/scripts/sandbox/router.js b/scripts/sandbox/router.js new file mode 100644 index 000000000..81c1d199c --- /dev/null +++ b/scripts/sandbox/router.js @@ -0,0 +1,298 @@ +'use strict'; + +const os = require('os'); +const { validateCapabilities } = require('./contracts'); + +const TARGET_OSES = ['linux', 'macos', 'windows']; +const TIER_TWO_BACKENDS = { + linux: ['lima'], + macos: ['lume', 'tart'], + windows: ['windows-sandbox', 'hyper-v', 'dockur-windows'], +}; + +function normalizeOs(platform = process.platform) { + const values = { + darwin: 'macos', + linux: 'linux', + win32: 'windows', + }; + return values[platform] || platform; +} + +function normalizeArch(architecture = process.arch) { + const values = { + arm64: 'arm64', + x64: 'x86_64', + }; + return values[architecture] || architecture; +} + +function defaultHost() { + return { + os: normalizeOs(), + arch: normalizeArch(), + cpus: os.cpus().length, + }; +} + +function expandTargets(manifest, host) { + // DECISION: CONVENTIONS item 1 makes routing a deterministic shard plan. + const requestedOs = manifest.needs.os; + let osTargets; + if (requestedOs[0] === 'any') { + osTargets = [host.os]; + } else if (requestedOs[0] === 'all') { + osTargets = TARGET_OSES; + } else { + osTargets = requestedOs; + } + + const archTargets = manifest.needs.arch || [host.arch]; + return osTargets.flatMap(targetOs => ( + archTargets.map(arch => ({ os: targetOs, arch })) + )); +} + +function backendEntry(capabilities, backend) { + return capabilities.backends?.[backend] || { available: false }; +} + +function targetMatches(target, shard) { + return target.os === shard.os && (target.arch === undefined || target.arch === shard.arch); +} + +function backendSupports(capabilities, backend, shard, manifest) { + const entry = backendEntry(capabilities, backend); + if (!entry.available) return false; + const host = capabilities.host; + const hardConstraints = { + srt: shard.os === host.os && shard.arch === host.arch, + podman: shard.os === 'linux' && shard.arch === host.arch, + microsandbox: shard.os === 'linux' && shard.arch === host.arch, + lume: host.os === 'macos' && host.arch === 'arm64' && shard.os === 'macos' && shard.arch === 'arm64', + // DECISION: CONVENTIONS item 14 permits a real Lima Linux guest on macOS. + lima: ['linux', 'macos'].includes(host.os) && shard.os === 'linux' && shard.arch === host.arch, + tart: host.os === 'macos' && host.arch === 'arm64' && shard.os === 'macos' && shard.arch === 'arm64', + 'windows-sandbox': host.os === 'windows' && shard.os === 'windows' && shard.arch === host.arch, + 'hyper-v': host.os === 'windows' && shard.os === 'windows' && shard.arch === host.arch, + 'dockur-windows': false, + ci: Array.isArray(entry.targets) && entry.targets.some(target => targetMatches(target, shard)), + }; + if (!hardConstraints[backend]) return false; + if (Array.isArray(entry.targets) && !entry.targets.some(target => targetMatches(target, shard))) { + return false; + } + if ( + manifest.needs.capabilities.includes('ios-simulator') + && !entry.capabilities?.includes('ios-simulator') + ) { + return false; + } + if ( + networkNeeds(manifest).domainAllowlist + && !entry.capabilities?.includes('domain-network-policy') + ) { + return false; + } + return true; +} + +function networkNeeds(manifest) { + const values = manifest.needs.capabilities.filter(value => value.startsWith('network:')); + return { + requested: values.length > 0, + open: values.includes('network:*'), + domainAllowlist: values.length > 0 && !values.includes('network:*'), + }; +} + +function hasAny(manifest, values) { + return values.some(value => manifest.needs.capabilities.includes(value)); +} + +function tierZeroEligible(manifest, shard, host) { + // DECISION: CONVENTIONS item 8 treats clean-home as environment isolation. + return ( + shard.os === host.os + && shard.arch === host.arch + && manifest.needs.native === false + && !hasAny(manifest, [ + 'pkg-install', + 'services', + 'gui', + 'clean-home', + 'ios-simulator', + ]) + ); +} + +function tierOneEligible(manifest, shard) { + // DECISION: CONVENTIONS item 2 keeps native service/GUI evidence out of containers. + return ( + shard.os === 'linux' + && manifest.needs.native === false + && !hasAny(manifest, ['services', 'gui', 'ios-simulator']) + ); +} + +function tierOneCandidates(manifest) { + const network = networkNeeds(manifest); + // DECISION: CONVENTIONS item 9 fails closed on unenforced domain allowlists. + if (network.domainAllowlist) return ['microsandbox']; + if (manifest.needs.trust === 'untrusted' || network.open) { + return ['microsandbox', 'podman']; + } + return ['podman']; +} + +function tierTwoCandidates(shard) { + return TIER_TWO_BACKENDS[shard.os] || []; +} + +function firstSupported(candidates, capabilities, shard, manifest) { + return candidates.find(backend => backendSupports(capabilities, backend, shard, manifest)) || null; +} + +function routeNotes(backend, manifest) { + const notes = []; + const network = networkNeeds(manifest); + if ( + backend === 'podman' + && (manifest.needs.trust === 'untrusted' || network.open) + ) { + notes.push('microsandbox unavailable; using documented degraded Podman isolation'); + } + if (backend === 'podman' && network.open) { + notes.push('Podman v1 network policy is unrestricted for network:*'); + } + if (backend === 'tart') { + notes.push('Tart uses Fair Source 100 licensing; personal use is free, while some large organizational server installations require a paid license'); + } + return notes; +} + +function missingRoute(shard, manifest, capabilities, localOnly) { + const network = networkNeeds(manifest); + if ( + network.domainAllowlist + && tierOneEligible(manifest, shard) + && !backendSupports(capabilities, 'microsandbox', shard, manifest) + ) { + return { + reason: 'strict domain allowlists require a probed microsandbox with domain-network-policy in Tier 1 v1', + fix: 'Install or update microsandbox: brew install superradcompany/tap/microsandbox', + }; + } + if (network.domainAllowlist) { + return { + reason: `no ${shard.os}/${shard.arch} native or CI backend enforces strict domain allowlists in v1`, + fix: 'Target Linux with microsandbox, or remove native OS needs after reviewing the network policy', + }; + } + if (!localOnly && !backendEntry(capabilities, 'ci').available) { + return { + reason: `no local backend satisfies ${shard.os}/${shard.arch}, and GitHub CLI authentication is unavailable`, + fix: 'Enable CI fallback: gh auth login', + }; + } + if (localOnly) { + return { + reason: `no local backend satisfies ${shard.os}/${shard.arch}`, + fix: 'Remove --local-only or install the native backend reported by ecc-sandbox probe', + }; + } + return { + reason: `no available backend satisfies ${shard.os}/${shard.arch}`, + fix: 'Run ecc-sandbox probe --refresh and enable one of the reported backend setup commands', + }; +} + +function resolveShard(manifest, capabilities, shard, options = {}) { + const host = capabilities.host; + const network = networkNeeds(manifest); + + const rules = [ + { + id: 'tier-0-process', + tier: 0, + eligible: () => tierZeroEligible(manifest, shard, host), + candidates: () => ['srt'], + reason: 'host-matching process isolation satisfies the declared needs', + }, + { + id: 'tier-1-ephemeral', + tier: 1, + eligible: () => tierOneEligible(manifest, shard), + candidates: () => tierOneCandidates(manifest), + reason: 'an ephemeral Linux environment is the cheapest clean venue for the declared needs', + }, + { + id: 'tier-2-native', + tier: 2, + eligible: () => !network.domainAllowlist, + candidates: () => tierTwoCandidates(shard), + reason: 'OS-native behavior requires a local full VM', + }, + { + id: 'ci-fallback', + tier: 3, + eligible: () => !options.localOnly && !network.domainAllowlist, + candidates: () => ['ci'], + reason: 'the requested OS or native capability is unavailable locally', + }, + ]; + + for (const rule of rules) { + if (!rule.eligible()) continue; + const candidates = rule.candidates(); + const backend = firstSupported(candidates, capabilities, shard, manifest); + if (!backend) continue; + return { + os: shard.os, + arch: shard.arch, + backend, + tier: rule.tier, + rule: rule.id, + reason: rule.reason, + notes: routeNotes(backend, manifest), + result: 'routable', + }; + } + + return { + os: shard.os, + arch: shard.arch, + backend: null, + tier: null, + rule: null, + ...missingRoute(shard, manifest, capabilities, options.localOnly), + notes: [], + result: 'error', + }; +} + +function routeManifest(manifest, capabilities, options = {}) { + validateCapabilities(capabilities); + const routes = expandTargets(manifest, capabilities.host) + .map(shard => resolveShard(manifest, capabilities, shard, options)); + return { + schema_version: 1, + manifest: options.manifestPath || null, + host: { ...capabilities.host }, + routes, + result: routes.every(route => route.result === 'routable') ? 'routable' : 'error', + }; +} + +module.exports = { + TARGET_OSES, + TIER_TWO_BACKENDS, + defaultHost, + expandTargets, + networkNeeds, + normalizeArch, + normalizeOs, + resolveShard, + routeManifest, + tierOneCandidates, +}; diff --git a/tests/fixtures/sandbox/invalid-capability.yaml b/tests/fixtures/sandbox/invalid-capability.yaml new file mode 100644 index 000000000..63e3158ef --- /dev/null +++ b/tests/fixtures/sandbox/invalid-capability.yaml @@ -0,0 +1,14 @@ +name: invalid-capability +needs: + os: [linux] + capabilities: [docker-socket] + trust: first-party + native: false +resources: + cpu: 2 + memory: 2GB + timeout: 300 +steps: + setup: [node --version] + assert: [node --version] +report: exit-only diff --git a/tests/fixtures/sandbox/routing-cases.json b/tests/fixtures/sandbox/routing-cases.json new file mode 100644 index 000000000..ba912fb3a --- /dev/null +++ b/tests/fixtures/sandbox/routing-cases.json @@ -0,0 +1,183 @@ +{ + "baseManifest": { + "name": "routing-fixture", + "needs": { + "os": ["macos"], + "arch": ["arm64"], + "capabilities": [], + "trust": "first-party", + "native": false + }, + "resources": { + "cpu": 2, + "memory": "2GB", + "timeout": 300 + }, + "steps": { + "setup": ["node --version"], + "assert": ["node --version"] + }, + "report": "exit-only" + }, + "cases": [ + { + "name": "benign host process uses srt", + "backends": { "srt": { "available": true } }, + "expected": ["srt"] + }, + { + "name": "filesystem write remains tier zero", + "needs": { "capabilities": ["fs-write"] }, + "backends": { "srt": { "available": true } }, + "expected": ["srt"] + }, + { + "name": "Linux package install uses Podman", + "needs": { "os": ["linux"], "capabilities": ["pkg-install"] }, + "backends": { "podman": { "available": true } }, + "expected": ["podman"] + }, + { + "name": "clean home skips host process", + "needs": { "os": ["linux"], "capabilities": ["clean-home"] }, + "backends": { "srt": { "available": true }, "podman": { "available": true } }, + "expected": ["podman"] + }, + { + "name": "untrusted Linux prefers Microsandbox", + "needs": { "os": ["linux"], "trust": "untrusted" }, + "backends": { + "podman": { "available": true }, + "microsandbox": { "available": true } + }, + "expected": ["microsandbox"] + }, + { + "name": "untrusted Linux records Podman degradation", + "needs": { "os": ["linux"], "trust": "untrusted" }, + "backends": { "podman": { "available": true } }, + "expected": ["podman"], + "notePattern": "degraded Podman" + }, + { + "name": "open network prefers Microsandbox", + "needs": { "os": ["linux"], "capabilities": ["network:*"] }, + "backends": { + "podman": { "available": true }, + "microsandbox": { + "available": true, + "capabilities": ["domain-network-policy"] + } + }, + "expected": ["microsandbox"] + }, + { + "name": "open network Podman fallback is explicit", + "needs": { "os": ["linux"], "capabilities": ["network:*"] }, + "backends": { "podman": { "available": true } }, + "expected": ["podman"], + "notePattern": "unrestricted" + }, + { + "name": "Tier one domain policy selects Microsandbox", + "needs": { "os": ["linux"], "capabilities": ["pkg-install", "network:npmjs.org"] }, + "backends": { + "podman": { "available": true }, + "microsandbox": { + "available": true, + "capabilities": ["domain-network-policy"] + } + }, + "expected": ["microsandbox"] + }, + { + "name": "Tier one domain policy fails closed", + "needs": { "os": ["linux"], "capabilities": ["pkg-install", "network:npmjs.org"] }, + "backends": { "podman": { "available": true }, "ci": { "available": true } }, + "expected": [null], + "result": "error", + "reasonPattern": "require.*microsandbox" + }, + { + "name": "Microsandbox without domain policy fails closed", + "needs": { "os": ["linux"], "capabilities": ["pkg-install", "network:npmjs.org"] }, + "backends": { "microsandbox": { "available": true } }, + "expected": [null], + "result": "error", + "reasonPattern": "require.*microsandbox" + }, + { + "name": "macOS services use Lume", + "needs": { "capabilities": ["services"] }, + "backends": { "podman": { "available": true }, "lume": { "available": true } }, + "expected": ["lume"] + }, + { + "name": "Tart selection emits license notice", + "needs": { "capabilities": ["gui"] }, + "backends": { "tart": { "available": true } }, + "expected": ["tart"], + "notePattern": "Fair Source 100" + }, + { + "name": "native Linux on macOS uses Lima", + "needs": { "os": ["linux"], "capabilities": ["services"], "native": true }, + "backends": { "lima": { "available": true } }, + "expected": ["lima"] + }, + { + "name": "native Windows uses Windows Sandbox", + "host": { "os": "windows", "arch": "x86_64" }, + "needs": { "os": ["windows"], "arch": ["x86_64"], "native": true }, + "backends": { "windows-sandbox": { "available": true } }, + "expected": ["windows-sandbox"] + }, + { + "name": "unavailable Windows routes to CI", + "needs": { "os": ["windows"] }, + "backends": { "ci": { "available": true, "targets": [{ "os": "windows", "arch": "arm64" }] } }, + "expected": ["ci"] + }, + { + "name": "all fans out independently", + "needs": { "os": ["all"] }, + "backends": { + "srt": { "available": true }, + "podman": { "available": true, "targets": [{ "os": "linux", "arch": "arm64" }] }, + "ci": { "available": true, "targets": [{ "os": "windows", "arch": "arm64" }] } + }, + "expected": ["podman", "srt", "ci"] + }, + { + "name": "iOS Simulator routes to capable macOS CI", + "needs": { "capabilities": ["ios-simulator"] }, + "backends": { + "lume": { "available": true }, + "ci": { + "available": true, + "capabilities": ["ios-simulator"], + "targets": [{ "os": "macos", "arch": "arm64" }] + } + }, + "expected": ["ci"] + }, + { + "name": "local-only rejects unavailable OS", + "needs": { "os": ["windows"] }, + "options": { "localOnly": true }, + "backends": { "ci": { "available": true } }, + "expected": [null], + "result": "error", + "reasonPattern": "no local backend" + }, + { + "name": "architecture mismatch routes to CI", + "needs": { "arch": ["x86_64"] }, + "backends": { + "srt": { "available": true }, + "ci": { "available": true, "targets": [{ "os": "macos", "arch": "x86_64" }] } + }, + "expected": ["ci"] + } + ] +} diff --git a/tests/fixtures/sandbox/unknown-key.yaml b/tests/fixtures/sandbox/unknown-key.yaml new file mode 100644 index 000000000..9f3bcddc5 --- /dev/null +++ b/tests/fixtures/sandbox/unknown-key.yaml @@ -0,0 +1,15 @@ +name: invalid-unknown-key +needs: + os: [linux] + capabilities: [] + trust: first-party + native: false + backend: podman +resources: + cpu: 2 + memory: 2GB + timeout: 300 +steps: + setup: [node --version] + assert: [node --version] +report: exit-only diff --git a/tests/fixtures/sandbox/valid.yaml b/tests/fixtures/sandbox/valid.yaml new file mode 100644 index 000000000..2913e0422 --- /dev/null +++ b/tests/fixtures/sandbox/valid.yaml @@ -0,0 +1,20 @@ +name: install-ecc-clean +needs: + os: [linux] + arch: [arm64] + capabilities: + - clean-home + - fs-write + - network:npmjs.org + trust: first-party + native: false +resources: + cpu: 2 + memory: 2GB + timeout: 300 +steps: + setup: + - node --version + assert: + - node --version +report: install-diff diff --git a/tests/sandbox/contracts-router.test.js b/tests/sandbox/contracts-router.test.js new file mode 100644 index 000000000..2814e0b56 --- /dev/null +++ b/tests/sandbox/contracts-router.test.js @@ -0,0 +1,403 @@ +'use strict'; + +const assert = require('assert'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { spawnSync } = require('child_process'); +const { + ContractValidationError, + loadManifest, + parseManifestText, + readBoundedRegularFile, + validateManifest, + validateCapabilities, + validateReport, +} = require('../../scripts/sandbox/contracts'); +const { routeManifest } = require('../../scripts/sandbox/router'); + +const repoRoot = path.join(__dirname, '..', '..'); +const fixtureRoot = path.join(repoRoot, 'tests', 'fixtures', 'sandbox'); +const cliPath = path.join(repoRoot, 'scripts', 'sandbox', 'ecc-sandbox'); +const routingFixtures = JSON.parse( + fs.readFileSync(path.join(fixtureRoot, 'routing-cases.json'), 'utf8') +); +const SUBPROCESS_TIMEOUT_MS = 30_000; + +let passed = 0; +let failed = 0; + +function test(name, fn) { + try { + fn(); + console.log(` ✓ ${name}`); + passed += 1; + } catch (error) { + console.log(` ✗ ${name}`); + console.log(` Error: ${error.stack || error.message}`); + failed += 1; + } +} + +function buildManifest(testCase) { + const base = routingFixtures.baseManifest; + return { + ...base, + needs: { + ...base.needs, + ...(testCase.needs || {}), + }, + }; +} + +function buildCapabilityMap(testCase) { + return { + schema_version: 1, + host: testCase.host || { os: 'macos', arch: 'arm64' }, + backends: testCase.backends || {}, + }; +} + +function sampleSingleReport(overrides = {}) { + return { + manifest: '/tmp/sandbox.yaml', + backend: 'podman', + tier: 1, + os: 'linux', + arch: 'arm64', + started: '2026-08-08T12:00:00.000Z', + duration_ms: 42, + escalations: [], + steps: [{ cmd: 'node --version', exit: 0, stdout_tail: 'v24', stderr_tail: '' }], + assertions: [{ cmd: 'node --version', pass: true }], + install_diff: { + method: 'podman-layer', + complete: true, + files_added: ['/usr/local/bin/tool'], + files_changed: [], + files_deleted: [], + path_changes: ['/usr/local/bin'], + services_registered: [], + dotfiles_touched: [], + }, + result: 'pass', + notes: [], + ...overrides, + }; +} + +function runCli(args) { + return spawnSync(process.execPath, [cliPath, ...args], { + cwd: repoRoot, + encoding: 'utf8', + shell: false, + timeout: SUBPROCESS_TIMEOUT_MS, + }); +} + +console.log('\n=== ECC sandbox contracts and router tests ===\n'); + +test('loads and validates the canonical YAML manifest fixture', () => { + const manifest = loadManifest(path.join(fixtureRoot, 'valid.yaml')); + assert.strictEqual(manifest.name, 'install-ecc-clean'); + assert.ok(manifest.needs.capabilities.includes('clean-home')); +}); + +test('rejects unknown manifest keys loudly', () => { + assert.throws( + () => loadManifest(path.join(fixtureRoot, 'unknown-key.yaml')), + error => ( + error instanceof ContractValidationError + && /additional properties/.test(error.message) + && /backend/.test(error.message) + ) + ); +}); + +test('rejects capabilities outside the closed vocabulary', () => { + assert.throws( + () => loadManifest(path.join(fixtureRoot, 'invalid-capability.yaml')), + error => error instanceof ContractValidationError && /must match/.test(error.message) + ); +}); + +test('rejects duplicate YAML keys before schema validation', () => { + assert.throws( + () => parseManifestText('name: one\nname: two\n', 'duplicate.yaml'), + error => error instanceof ContractValidationError && /Map keys must be unique/.test(error.message) + ); +}); + +test('rejects YAML aliases and oversized manifests', () => { + assert.throws( + () => parseManifestText('name: &name alias-name\ncopy: *name\n', 'alias.yaml'), + error => error instanceof ContractValidationError + ); + assert.throws( + () => parseManifestText(`name: ${'x'.repeat(1024 * 1024)}\n`, 'large.yaml'), + error => error instanceof ContractValidationError && /exceeds/.test(error.message) + ); +}); + +test('rejects YAML warnings and non-regular contract files', () => { + assert.throws( + () => parseManifestText('name: !unsupported tagged\n', 'tagged.yaml'), + error => error instanceof ContractValidationError && /tag/i.test(error.message) + ); + assert.throws( + () => readBoundedRegularFile(fixtureRoot, 'Fixture contract'), + /regular file/ + ); +}); + +test('rejects mixed any and explicit OS targets semantically', () => { + const manifest = buildManifest({ needs: { os: ['any', 'linux'] } }); + assert.throws( + () => validateManifest(manifest), + error => error instanceof ContractValidationError && /must be used alone/.test(error.message) + ); +}); + +test('rejects open network combined with domain allowlists', () => { + const manifest = buildManifest({ + needs: { capabilities: ['network:*', 'network:npmjs.org'] }, + }); + assert.throws( + () => validateManifest(manifest), + error => error instanceof ContractValidationError && /cannot be combined/.test(error.message) + ); +}); + +test('rejects forged capability maps before routing', () => { + const manifest = validateManifest(buildManifest({ needs: { capabilities: ['services'] } })); + const forged = { + schema_version: 1, + host: { os: 'linux', arch: 'x86_64' }, + backends: { lume: { available: 'yes' } }, + }; + assert.throws( + () => validateCapabilities(forged), + error => error instanceof ContractValidationError && /must be boolean/.test(error.message) + ); + assert.throws( + () => routeManifest(manifest, forged), + error => error instanceof ContractValidationError + ); +}); + +test('hard backend constraints reject impossible local target claims', () => { + const manifest = validateManifest(buildManifest({ + needs: { os: ['macos'], arch: ['arm64'], capabilities: ['services'] }, + })); + const capabilities = { + schema_version: 1, + host: { os: 'linux', arch: 'x86_64' }, + backends: { + lume: { available: true }, + ci: { available: true, targets: [{ os: 'macos', arch: 'arm64' }] }, + }, + }; + const decision = routeManifest(manifest, capabilities); + assert.strictEqual(decision.routes[0].backend, 'ci'); +}); + +test('requires an explicit macOS target for iOS Simulator', () => { + const manifest = buildManifest({ + needs: { os: ['any'], capabilities: ['ios-simulator'] }, + }); + assert.throws( + () => validateManifest(manifest), + error => error instanceof ContractValidationError && /explicit macos/.test(error.message) + ); +}); + +test('rejects unbounded memory and command collections', () => { + assert.throws( + () => validateManifest({ + ...buildManifest({}), + resources: { cpu: 1, memory: '999999999GB', timeout: 30 }, + }), + error => error instanceof ContractValidationError && /cannot exceed/.test(error.message) + ); + assert.throws( + () => validateManifest({ + ...buildManifest({}), + steps: { setup: Array(1001).fill('true'), assert: ['true'] }, + }), + error => error instanceof ContractValidationError && /more than 1000/.test(error.message) + ); +}); + +for (const testCase of routingFixtures.cases) { + test(`routes fixture: ${testCase.name}`, () => { + const manifest = validateManifest(buildManifest(testCase)); + const decision = routeManifest(manifest, buildCapabilityMap(testCase), testCase.options || {}); + assert.deepStrictEqual(decision.routes.map(route => route.backend), testCase.expected); + assert.strictEqual(decision.result, testCase.result || 'routable'); + const expectedTier = { + srt: 0, + podman: 1, + microsandbox: 1, + lume: 2, + lima: 2, + tart: 2, + 'windows-sandbox': 2, + 'hyper-v': 2, + 'dockur-windows': 2, + ci: 3, + }; + for (const route of decision.routes) { + assert.ok(route.reason.length > 0); + if (route.backend === null) { + assert.strictEqual(route.rule, null); + assert.strictEqual(route.tier, null); + } else { + assert.strictEqual(route.tier, expectedTier[route.backend]); + assert.ok(route.rule); + } + } + if (testCase.notePattern) { + assert.match(decision.routes.flatMap(route => route.notes).join('\n'), new RegExp(testCase.notePattern)); + } + if (testCase.reasonPattern) { + assert.match(decision.routes.map(route => route.reason).join('\n'), new RegExp(testCase.reasonPattern)); + } + }); +} + +test('validates single and aggregate reports through one schema', () => { + const single = sampleSingleReport(); + assert.strictEqual(validateReport(single), single); + const aggregate = { + manifest: '/tmp/sandbox.yaml', + backend: 'aggregate', + tier: null, + os: 'multiple', + arch: 'multiple', + venue: 'local', + started: '2026-08-08T12:00:00.000Z', + duration_ms: 84, + escalations: [], + children: [single, sampleSingleReport({ backend: 'lume', tier: 2, os: 'macos' })], + result: 'pass', + notes: [], + }; + assert.strictEqual(validateReport(aggregate), aggregate); +}); + +test('rejects malformed reports and more than one escalation', () => { + assert.throws( + () => validateReport(sampleSingleReport({ unexpected: true })), + error => error instanceof ContractValidationError && /additional properties/.test(error.message) + ); + assert.throws( + () => validateReport(sampleSingleReport({ + escalations: [ + { from: 'srt', reason: 'denied', to: 'podman' }, + { from: 'podman', reason: 'native', to: 'lume' }, + ], + })), + error => error instanceof ContractValidationError && /more than 1 items/.test(error.message) + ); + assert.throws( + () => validateReport(sampleSingleReport({ backend: 'lume', tier: 0, os: 'windows' })), + error => error instanceof ContractValidationError + ); + assert.throws( + () => validateReport(sampleSingleReport({ + install_diff: { + ...sampleSingleReport().install_diff, + method: 'none', + complete: true, + }, + })), + error => error instanceof ContractValidationError + ); + assert.throws( + () => validateReport({ + manifest: '/tmp/sandbox.yaml', + backend: 'aggregate', + tier: null, + os: 'multiple', + arch: 'multiple', + venue: 'ci', + started: '2026-08-08T12:00:00.000Z', + duration_ms: 84, + escalations: [], + children: [sampleSingleReport({ result: 'fail' })], + result: 'pass', + notes: [], + }), + error => error instanceof ContractValidationError && /aggregate result must be fail/.test(error.message) + ); + assert.throws( + () => validateReport({ + manifest: '/tmp/sandbox.yaml', + backend: 'aggregate', + tier: null, + os: 'multiple', + arch: 'multiple', + venue: 'local', + started: '2026-08-08T12:00:00.000Z', + duration_ms: 84, + escalations: [], + children: [sampleSingleReport({ + steps: [{ cmd: 'false', exit: 1, stdout_tail: '', stderr_tail: '' }], + })], + result: 'pass', + notes: [], + }), + error => error instanceof ContractValidationError && /children\/0/.test(error.message) + ); +}); + +test('CLI dry-run emits only a routable JSON decision on stdout', () => { + const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-sandbox-contract-')); + try { + const capabilitiesPath = path.join(tempRoot, 'capabilities.json'); + fs.writeFileSync(capabilitiesPath, JSON.stringify({ + schema_version: 1, + host: { os: 'macos', arch: 'arm64' }, + backends: { + microsandbox: { + available: true, + capabilities: ['domain-network-policy'], + }, + }, + })); + const result = runCli([ + 'run', + path.join(fixtureRoot, 'valid.yaml'), + '--dry-run', + '--capabilities', + capabilitiesPath, + ]); + assert.ifError(result.error); + assert.strictEqual(result.status, 0, result.stderr); + assert.strictEqual(result.stderr, ''); + const output = JSON.parse(result.stdout); + assert.strictEqual(output.result, 'routable'); + assert.strictEqual(output.routes[0].backend, 'microsandbox'); + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +}); + +test('CLI renders manifest failures as structured JSON', () => { + const result = runCli([ + 'run', + path.join(fixtureRoot, 'unknown-key.yaml'), + '--dry-run', + ]); + assert.ifError(result.error); + assert.strictEqual(result.status, 2); + assert.strictEqual(result.stderr, ''); + const output = JSON.parse(result.stdout); + assert.strictEqual(output.result, 'error'); + assert.strictEqual(output.error.code, 'contract-invalid'); + assert.match(output.error.message, /backend/); +}); + +console.log(`\nPassed: ${passed}`); +console.log(`Failed: ${failed}`); +process.exit(failed > 0 ? 1 : 0); diff --git a/tests/scripts/npm-publish-surface.test.js b/tests/scripts/npm-publish-surface.test.js index a28b42cd0..81cb79ceb 100644 --- a/tests/scripts/npm-publish-surface.test.js +++ b/tests/scripts/npm-publish-surface.test.js @@ -73,6 +73,7 @@ function buildExpectedPublishPaths(repoRoot) { "scripts/release-video-suite.js", "scripts/skill-create-output.js", "scripts/repair.js", + "scripts/sandbox", "scripts/harness-adapter-compliance.js", "scripts/session-inspect.js", "scripts/setup.js", @@ -172,6 +173,9 @@ function main() { "scripts/preview-pack-smoke.js", "scripts/release-approval-gate.js", "scripts/release-video-suite.js", + "scripts/sandbox/ecc-sandbox", + "scripts/sandbox/contracts.js", + "scripts/sandbox/router.js", "scripts/work-items.js", "scripts/platform-audit.js", "scripts/sync-ecc-to-codex.sh", diff --git a/yarn.lock b/yarn.lock index 8867e1184..bfdea17d7 100644 --- a/yarn.lock +++ b/yarn.lock @@ -610,6 +610,7 @@ __metadata: markdownlint-cli: "npm:0.49.1" sql.js: "npm:1.14.2" typescript: "npm:6.0.3" + yaml: "npm:2.9.0" bin: ecc: scripts/ecc.js ecc-control-pane: scripts/control-pane.js @@ -2144,7 +2145,7 @@ __metadata: languageName: node linkType: hard -"yaml@npm:^2.9.0": +"yaml@npm:2.9.0, yaml@npm:^2.9.0": version: 2.9.0 resolution: "yaml@npm:2.9.0" bin: