diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index 29c8ed2..af1dbf1 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -7,9 +7,29 @@ on: permissions: contents: read jobs: - verify: - runs-on: ubuntu-24.04 + programs: + strategy: + fail-fast: false + matrix: + include: + - group: foundation + pattern: "^(unit:|integration:|smoke: (?!built CLI (installs|selects registered)))" + - group: npm + pattern: "^smoke: built CLI installs two typed" + - group: git + pattern: "^smoke: built CLI installs packaged" + - group: git-build + pattern: "^smoke: built CLI installs approved" + - group: git-registered + pattern: "^smoke: built CLI selects registered packaged" + - group: build-registered + pattern: "^smoke: built CLI selects registered built" + - group: live + pattern: "^smoke: built CLI installs and selects" + runs-on: ubuntu-26.04 timeout-minutes: 10 + env: + CORDIS_REQUIRE_PLAN: '1' steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 @@ -18,5 +38,15 @@ jobs: - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 with: node-version: 24.19.0 - - run: bun install --frozen-lockfile - - run: bun run verify + - run: bun install --frozen-lockfile --ignore-scripts + - run: bun run check && bun run build + - run: bun test ./tests --timeout 60000 --test-name-pattern "${{ matrix.pattern }}" + + verify: + if: always() + needs: programs + runs-on: ubuntu-26.04 + steps: + - env: + RESULT: ${{ needs.programs.result }} + run: test "$RESULT" = success diff --git a/CHANGELOG.md b/CHANGELOG.md index c8a112a..4cc988c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,8 +2,27 @@ ## [Unreleased] +### Changed +- Qualify built plugin commands against exact packaged Git, approved Git build and native live probe installation artifacts (#317). + +### Added +- Expose native installed plugin management and explicit plan restart scopes using reusable UI presentation (#317). + +### Added + +- Qualify compiled format-3 installed operations through the public durable host (#317). + +- Qualify extensible built CLI planning on Ubuntu 26.04 without runtime effects (#317). + +### Changed +- Qualify CLI with exact current SDK UI and Deployment archives (#317). + +- Render human command results through reusable UI providers and accept extensible plans (#317). + ### Added +- Cli: deliver Task 3C typed providers and mobile-first UI integration (#317). + - Submit and observe durable installed applications (#315). - Compose standalone CLI with native Cordis provider selection (#313). - Expose non-activating platform plans (#311). diff --git a/README.md b/README.md index 616343d..61b75c5 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ -# Cordis diagnostic and planning executable +# Cordis executable -`trsd-linux-x64` is a standalone diagnostic and non-activating planning front door. Run it without Node/Bun or a +`trsd-linux-x64` is the standalone diagnostic, planning and installed-operation front door. Run it without Node/Bun or a project checkout. Supported commands: ```text @@ -8,6 +8,9 @@ trsd --help trsd --version trsd doctor [--json] [--context NAME] [--installation ABSOLUTE_PATH] [--port INTEGER] trsd platform plan --file CONFIG [--json] +trsd platform apply --installation DIR --plan ID --digest SHA --idempotency-key KEY [--json] +trsd platform status --installation DIR [--json] +trsd platform application --installation DIR --id ID [--json] ``` `CliApplication` parses arguments and calls the public packaged `DeploymentHost` contract; @@ -20,8 +23,18 @@ JSON stdout is exactly one envelope: command, success, result, problem, blockers Doctor result follows the SDK DiagnosticReport schema. Human output uses concise checks; human errors go to stderr. Errors never echo unknown argument values or raw Docker stderr. Exit0 means success;1 runtime failure;2 invalid command/flag/value (with actionable help); -3 unmet prerequisites or explicitly unsupported lifecycle commands. `platform plan` is the only implemented platform binding; `apply`, `status`, `install`, `open`, `recover` and other lifecycle verbs remain unsupported. Remote SDK bindings remain contract-only. -Duplicate/missing flags and positional arguments fail validation. JSON is supported on doctor and platform plan, including validation failures. Version is `trsd 0.0.0-cordis.2`. +3 unmet prerequisites or explicitly unsupported lifecycle commands. Implemented platform bindings +are `plan`, `apply`, `status` and `application` read-back. Apply acknowledges durable acceptance; +application/status determine readiness. `plugin install`, `open` and `recover` remain unsupported +in this candidate. Remote SDK bindings remain contract-only. +Duplicate/missing flags and positional arguments fail validation. JSON is supported on doctor and +implemented platform commands, including validation failures. Version is `trsd 0.0.0-cordis.6`. + +This candidate consumes exact SDK `.16`, UI `.16` and Deployment `.73` archives. Source/byte +receipts are recorded in `package.json.cordisCandidate`, the lockfile and vendor archives. +Human presentation stays UI-owned and machine envelopes/exit codes stay CLI-owned. Default +Deployment selects the saved installation format; format-3 application and readonly observations +use its native standalone host without an ambient Node/Bun/package manager during apply. `CliProgramFixture.run(args)` spawns the compiled artifact with closed stdin, captures output and exit status, and supports fixture cwd/environment. Acceptance covers another directory, @@ -57,7 +70,7 @@ release. Migration PRs target `cordis`; issues remain open until authorized rele ## Task 2: non-activating plans -`trsd platform plan --file CONFIG [--json]` validates an explicitly prepared local release bundle. It never downloads, installs packages, imports plugin code, runs scripts, binds ports, loads images, creates credentials or starts containers. Apply remains unsupported. Successful plans describe future effects, not an active or healthy installation. +`trsd platform plan --file CONFIG [--json]` validates an explicitly prepared local release bundle. It never downloads, installs packages, imports plugin code, runs scripts, binds ports, loads images, creates credentials or starts containers. Planning reports future effects; explicit saved-plan apply is a separate installed operation. Configuration retains installationId, engineContext, installationDirectory (absolute), origin (loopback), runtimeState, plugins (exact id/package/version/archive SHA-256) and credentialReferences (unique `secret://` values). Add `release: {directory: ABSOLUTE_PATH, manifestDigest: SHA256}`. The installation and bundle must be disjoint. JSON object keys and semantic sets normalize deterministically; artifact byte identities remain exact. @@ -71,7 +84,7 @@ Plans bind normalized configuration, configuration/release/lock/recipe digests, CLI exits: 0 verified saved plan; 1 sanitized runtime/I/O failure; 2 invalid arguments/JSON/schema; 3 prerequisites/artifact/authority/state blockers. Blocked responses have result null, structured blockers and no saved reference. Never echo invalid input, archive content, credentials or engine stderr. SDK PlanningBlockedError carries only validated safe blockers. Seven remote operation IDs remain unchanged; platform.plan stays a write operation because saving a plan needs local ownership. -Verification: documentation first; outside-in built-program failure before implementation; exact read-back/modes/determinism; immutable/architecture/graph/recipe/secret/path/journal negative cases; no-runtime snapshots; actual default construction; all owner check/build/unit/integration/smoke gates plus assembled acceptance. Test fixtures are not a production application composition. CI must run a positive plan on ubuntu-26.04 and fail visibly if prerequisites are absent. No container starts, even in tests. +Verification: documentation first; outside-in built-program failure before implementation; exact read-back/modes/determinism; immutable/architecture/graph/recipe/secret/path/journal negative cases; no-runtime snapshots; actual default construction; all owner check/build/unit/integration/smoke gates plus assembled acceptance. Test fixtures are not a production application composition. CI must run a positive plan on ubuntu-26.04 and fail visibly if prerequisites are absent. These Task 2 planning scenes start no containers. Task 3C installed-operation acceptance below uses isolated, disposable fixture services. Tracked in #311; parent integration treeseed-ai/platform#697. Issues remain open until authorized release. @@ -126,3 +139,102 @@ Task 3B is authorized after the maintainer reviewed the isolated setup. Tracking Development: Bun 1.4.4, Node 24.19.0, TypeScript 5.9.3, native Cordis 4.0.0-rc.12. Run bun run verify (semantic class/source check, strict compiler, build and nonempty unit/integration/program smoke). Installed acceptance uses genuine exact package/OCI bytes, real identity/database/API/HTTPS and explicit isolated certificate trust. No global trust mutation or legacy service changes. All handwritten source, tools and tests are strict TypeScript classes. All capabilities that can be plugins, including container services, are native Cordis class plugins with typed swappable contracts. No parallel DI graph. Keep independent repository/public package boundaries, exact archive pins and original licenses. Migration PRs target cordis with Part of issue references. All issues remain open until authorized release; installer/Agent/generalized recovery are later tasks. + +## Task 3C contract + +Owner issue: https://github.com/treeseed-ai/cli/issues/317. Follow the approved Platform Task 3C service/provider/UI plan through exact public archives. Preserve independent repository ownership, strict TypeScript classes, native Cordis lifecycle, historical formats and all seven SDK operations. Expected-generation/idempotency, resource/credential/TLS retention and explicit unsafe restart/migration gates are mandatory. All issues remain open until release. + +Every visual component must be mobile-first from 320 CSS pixels to widescreen monitors; test 320/375/768/1024/1440/1920/2560 widths, long content, keyboard/touch and 200% text resizing. Keep authored controls at least 44×44 CSS pixels, required actions visible, logical/fluid dimensions and no page overflow (labeled local semantic-table overflow is permitted). UI owns components/styles/renderers; consumers retain domain behavior and Identity retains Keycloak authority. + +### Reusable terminal presentation + +Human output maps diagnostics, plans, installation state, applications and safe errors into +UI-owned text/status/table/feedback/stack view models. The native CLI output plugin consumes +UI's public terminal renderer; formatting and reusable presentation live in UI. Human plan +output contains explicit service, volume, port and future-effect tables. JSON envelope bytes, +exit meanings and stdout/stderr ownership stay with CLI; machine JSON does not create a UI +scope. Built-program tests use an empty or Docker-only PATH and retain Task 1 checks. + +Configuration and output accept the new format-3 service contracts through exact public +SDK/Deployment archives, preserving historical format-1/2 input/readers. This presentation +slice adds no installer commands or activation policy; those follow under this same Task 3C. + +### Built format-3 acceptance gate + +Owner CI runs on Ubuntu 26.04 with `CORDIS_REQUIRE_PLAN=1`: missing prerequisites fail visibly. +The built standalone CLI plans a genuine prepared five-instance bundle through Deployment's +public fixture/export, saves and repeats identical format-3 bytes, renders reusable human +service tables and runs with Docker-only PATH. It leaves Docker resources, listeners, +credentials and the import/script canary unchanged. Tampered input returns a blocked envelope +without a saved reference. These are planning checks, not installed activation evidence. + + +## Built format-3 installed-operation qualification + +The real `trsd` executable must plan a genuine prepared format-3 fixture bundle, submit its exact +saved plan, recover the same application after the submitting CLI process exits, and read status +and application through the durable standalone Deployment worker. The bundle contains a worker +produced before planning through Deployment's public `ServiceWorkerBuild`; CLI neither builds a +worker during apply nor implements a second coordinator. Apply/status/application run from a +foreign directory with only Docker on PATH, closed stdin and the executable reached by symlink. + +Exit zero from apply remains durable acceptance. Only subsequent verified application/status +read-back establishes readiness. Repeated submission with the same idempotency key returns the +same application, including after the source bundle is removed. JSON continues through SDK +schemas; human output continues through UI terminal providers. Qualification creates and cleans +only uniquely labelled fixture containers/volumes/networks and its exact selected worker process. +Graceful worker disposal preserves installed resources; a later apply must report repair rather +than silently restart that worker. Original services remain outside this fixture. + +## Installed plugin management + +`trsd plugin install --installation DIR` requests installation +and activation when the selected target is qualified. Use `--target deployment --service ID` for a +private container instance, `--provider ID` for an explicit provider and `--binding PORT=ID` for +explicit typed bindings. `--configuration FILE` loads a strict JSON object. `--idempotency-key KEY` +replays the exact accepted request; omission creates and reports a new key. `--scope installation` +is the default; client scope remains action-required until qualified. Ambiguous targets never +activate implicitly. Approved exact helpers and source/build policy belong to the installation. + +`trsd plugin select CAPABILITY PROVIDER --installation DIR --target TARGET [--service ID]` +selects an already registered provider through the same Deployment authority. +`trsd plugin list --installation DIR [--target TARGET]` and +`trsd plugin inspect REQUEST --installation DIR` read the current owner or verified cold records. +Cold records cannot establish active health. None of these commands invents a remote API endpoint. +Human output is rendered entirely by the reusable UI terminal providers; JSON emits the SDK +plugin envelope. Exit 0 for install/select requires active or already-active; pending/prepared or +blocked/action-required returns 3, invalid arguments/configuration returns 2 and unexpected I/O +returns 1. Read-only list/inspect success uses exit 0 without upgrading record health claims. + +`platform apply ... --restart SERVICE` explicitly authorizes each required restart scope from +the reviewed plan. Repeat the flag for multiple service IDs; duplicate or unrelated scopes fail. +No restart is inferred from install, readiness or an arbitrary configuration change. Keycloak +issuer, identities, sessions and grants remain under their existing owner/provider authority. + +## Final source and live-provider command gate + +The built command gate consumes Deployment's exact public NPM, packaged HTTPS Git, approved +source-only Git and live-probe fixtures. It runs installation, read-back and source-free retry +with only Docker on caller PATH. Registered selection uses retained archive bytes. An explicit +probe installation names an existing service and provider; only the accepted previous/next +qualification may activate it. The independent worker keeps its PID and physical resources; +unqualified reverse selection remains prepared for explicit restart review. CLI supplies no +source transport, lifecycle scheduler or container implementation. + +CI partitions built-program scenes into independent required jobs to preserve the existing +time budget; every test file/scene remains included. JSON exits and Keycloak authority remain +unchanged. This candidate is an unpublished Cordis review artifact. + +The final built source gate also selects two new registered instances after the packaged and +approved-build Git source is shut down. Selection rebases the complete retained closure without +reacquisition and preserves earlier endpoints/private resources. NPM's deliberately registered +stateful second version makes that provider ID ambiguous; source-free selection must refuse it +without changing the active composition. Explicit source/version installation remains distinct +from selecting an unambiguous registered provider ID. + +The built Git acquisition and registered-selection qualifications run as separate required +program cases. Each retains the 420-second case limit and the existing CI job budget. +Registered selection starts from a genuine accepted installed archive, stops the source, +then activates two further instances and verifies exact replay, direct protocols and retained +resources/private bytes. Acquisition still independently installs two named instances and +checks cold/source-free read-back. Splitting bounds verification; it does not weaken admission. diff --git a/bun.lock b/bun.lock index b75a81d..502c642 100644 --- a/bun.lock +++ b/bun.lock @@ -7,7 +7,10 @@ "dependencies": { "@treeseed-cordis/deployment": "file:vendor/deployment.tgz", "@treeseed-cordis/sdk": "file:vendor/sdk.tgz", + "@treeseed-cordis/ui": "file:vendor/ui.tgz", "jsonc-parser": "3.3.1", + "react": "19.3.1", + "react-dom": "19.3.1", }, "devDependencies": { "@types/bun": "1.4.4", @@ -22,14 +25,20 @@ "@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], - "@treeseed-cordis/deployment": ["@treeseed-cordis/deployment@vendor/deployment.tgz", { "dependencies": { "cordis": "4.0.0-rc.12", "jsonc-parser": "3.3.1", "semver": "7.8.5", "tar": "7.5.22" }, "peerDependencies": { "@treeseed-cordis/sdk": "0.0.0-cordis.4" } }, "sha512-RmtkuIPbRW8sTdeoGB+n11xxmgetyLeai7geTTz5dNVzgvH0OZyxwXk3DA3VZN/GIhkqz5+lRZX4jM/2vCJ0Cg=="], + "@treeseed-cordis/deployment": ["@treeseed-cordis/deployment@vendor/deployment.tgz", { "dependencies": { "ajv": "8.17.1", "ajv-formats": "3.0.1", "cordis": "4.0.0-rc.12", "jsonc-parser": "3.3.1", "postgres": "3.4.9", "semver": "7.8.5", "tar": "7.5.22", "zod": "4.6.7" }, "peerDependencies": { "@treeseed-cordis/sdk": "0.0.0-cordis.16" } }, "sha512-/+B2drru7gOnOGu0G+y24kTSV26iFilDKCIUQhjpOxN3e8vNlg0fN/7pCt9ZAejk+Pd0zOSmAzCfy6kkstGL+Q=="], - "@treeseed-cordis/sdk": ["@treeseed-cordis/sdk@vendor/sdk.tgz", { "dependencies": { "cordis": "4.0.0-rc.12", "jsonc-parser": "3.3.1", "semver": "7.8.5", "zod": "4.6.7" } }, "sha512-WSi3FYhgnA7TK9RGVn7vp+IgngCGlaCrv5lb1AJ8gGCGHW42/u40HIviMFINQDLxGyUILzMD7q19KnP+1VIDmQ=="], + "@treeseed-cordis/sdk": ["@treeseed-cordis/sdk@vendor/sdk.tgz", { "dependencies": { "cordis": "4.0.0-rc.12", "jsonc-parser": "3.3.1", "semver": "7.8.5", "zod": "4.6.7" } }, "sha512-rAg7xVOU05Z1+TcMxn2DWpAqZBrZuUvIhmYa4aEP6PetQrJdTBAtAxnM/Jo17Qa26wBq7j1hmwt6alu00sM4BQ=="], + + "@treeseed-cordis/ui": ["@treeseed-cordis/ui@vendor/ui.tgz", { "dependencies": { "cordis": "4.0.0-rc.12", "zod": "4.6.7" }, "peerDependencies": { "@treeseed-cordis/sdk": "0.0.0-cordis.16", "react": "19.3.1", "react-dom": "19.3.1", "typescript": "5.9.3" }, "optionalPeers": ["typescript"] }, "sha512-0ZM+ysL8u97gcyKJrSwDZW9hawyeAAAJ9Ax5SUk/OMlJHG3MNqwijC/ewbcdhsSE77soqwW+VUP+ysAAOoLIxw=="], "@types/bun": ["@types/bun@1.4.4", "", { "dependencies": { "bun-types": "1.4.4" } }, "sha512-9wkRDXUXK124pEnAutE6n/l18j+i9GC5IAHK8TmX/2nlySETmky0OU6yL5U8pW1AoKh++AN9auDCr647BfurjQ=="], "@types/node": ["@types/node@24.10.1", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-GNWcUTRBgIRJD5zj+Tq0fKOJ5XZajIiBroOF0yvj2bSU1WvNdYS/dn9UxwsujGW4JX06dnHyjV2y9rRaybH0iQ=="], + "ajv": ["ajv@8.17.1", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g=="], + + "ajv-formats": ["ajv-formats@3.0.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="], + "bun-types": ["bun-types@1.4.4", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-yjrJh5oGX7mMPKGd19YXyIjmEuj4G4zNC30bs7PM9Az7NQ3ndF3j6hbeRdvJTRQEhJ/FYQwW0a2moweEi2hMxQ=="], "chownr": ["chownr@3.0.0", "", {}, "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g=="], @@ -38,12 +47,28 @@ "cosmokit": ["cosmokit@1.8.1", "", {}, "sha512-PDBv4l90xZKrUsZ0vtoycgZpO/j4iFsqJXrAxsyBDsnQRI7ZMJXIjgDJsKNjd5L8jnVnnlrDCdhkFbTncgCVjQ=="], + "fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="], + + "fast-uri": ["fast-uri@3.1.9", "", {}, "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ=="], + + "json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="], + "jsonc-parser": ["jsonc-parser@3.3.1", "", {}, "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ=="], "minipass": ["minipass@7.1.3", "", {}, "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A=="], "minizlib": ["minizlib@3.1.0", "", { "dependencies": { "minipass": "^7.1.2" } }, "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw=="], + "postgres": ["postgres@3.4.9", "", {}, "sha512-GD3qdB0x1z9xgFI6cdRD6xu2Sp2WCOEoe3mtnyB5Ee0XrrL5Pe+e4CCnJrRMnL1zYtRDZmQQVbvOttLnKDLnaw=="], + + "react": ["react@19.3.1", "", {}, "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw=="], + + "react-dom": ["react-dom@19.3.1", "", { "dependencies": { "scheduler": "^0.28.0" }, "peerDependencies": { "react": "^19.3.1" } }, "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ=="], + + "require-from-string": ["require-from-string@2.0.2", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="], + + "scheduler": ["scheduler@0.28.0", "", {}, "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw=="], + "semver": ["semver@7.8.5", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="], "tar": ["tar@7.5.22", "", { "dependencies": { "@isaacs/fs-minipass": "^4.0.0", "chownr": "^3.0.0", "minipass": "^7.1.2", "minizlib": "^3.1.0", "yallist": "^5.0.0" } }, "sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA=="], diff --git a/package.json b/package.json index 72ca155..97804c6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@treeseed-cordis/cli", - "version": "0.0.0-cordis.4", + "version": "0.0.0-cordis.9", "private": true, "type": "module", "license": "Apache-2.0", @@ -16,7 +16,10 @@ "dependencies": { "@treeseed-cordis/sdk": "file:vendor/sdk.tgz", "@treeseed-cordis/deployment": "file:vendor/deployment.tgz", - "jsonc-parser": "3.3.1" + "jsonc-parser": "3.3.1", + "@treeseed-cordis/ui": "file:vendor/ui.tgz", + "react": "19.3.1", + "react-dom": "19.3.1" }, "devDependencies": { "@types/bun": "1.4.4", @@ -27,13 +30,18 @@ "cordisCandidate": { "sdk": { "repository": "https://github.com/treeseed-ai/sdk.git", - "commit": "f44ede394a58814b5d6e73146ba9ed7246b4f2ca", - "sha256": "16d3d7f699c55795b97972ca538bfeedeafdc6bfc4c32ed01708871ea02fe75c" + "commit": "4c0ecd2a0fc28545dbf677cc988ce69f0cf2f15d", + "sha256": "4084aa8dbe9767984fac9fef7f5cea30a0bec93ed416138d32c804e6389fdba5" }, "deployment": { "repository": "https://github.com/treeseed-ai/deployment.git", - "commit": "6a861aa81f3786b74752191b461d1bcddf99fce5", - "sha256": "7015e2447eb4d98f9979e8f10a3b33480c8ca80818384e2cbf939eba550ab65d" + "commit": "5ea1b2e76abd2b5531a765049f3afbef47abe8d4", + "sha256": "021a67e0fb488114a12654667f72ebfefa5cbe95fc187a108c9694f1935ffbdf" + }, + "ui": { + "repository": "https://github.com/treeseed-ai/ui.git", + "commit": "4d20cc65af0a83dd47b3ac436dc44c438d24b250", + "sha256": "0251c6ff1f5c4b6a628d85113d1e10b9ab019f26d1dda38c7aad3c12f84ef571" } } } diff --git a/scripts/build-cli.ts b/scripts/build-cli.ts index 1f55655..1b6c459 100644 --- a/scripts/build-cli.ts +++ b/scripts/build-cli.ts @@ -1,7 +1,8 @@ +import {UiSourcePolicy} from '@treeseed-cordis/ui/source-policy'; import { ProjectTooling } from '@treeseed-cordis/sdk/source-policy'; class CliBuild { static async run():Promise { - ProjectTooling.run(); + ProjectTooling.run();new UiSourcePolicy().check(); if(process.argv[2]==='build') { const result=await Bun.build({entrypoints:['./src/main.ts'],compile:{target:'bun-linux-x64',outfile:'./dist/trsd-linux-x64',autoloadDotenv:false,autoloadBunfig:false,autoloadTsconfig:false,autoloadPackageJson:true},minify:true}); if(!result.success)throw new Error('Standalone compilation failed'); diff --git a/src/main.ts b/src/main.ts index 261e5f9..c401d10 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,27 +1,32 @@ +import { InstalledPluginCommands, PluginArgumentProblem, type CliPluginManagement, type PluginEnvelope } from './plugins.js'; +import {UiTerminalRenderer,type UiTerminalRendering} from '@treeseed-cordis/ui/terminal'; +import type {UiViewModel} from '@treeseed-cordis/ui/contracts'; import { DeploymentWorker, DeploymentComposition, DeploymentCapability, type DeploymentHost } from '@treeseed-cordis/deployment'; -import { InstalledSchemas, PlatformSchemas, CapabilityToken, ProviderSchemas, type InstalledEnvelope as CliEnvelope, type DiagnosticConfiguration, type DeploymentConfiguration, type ProviderArtifact, type ProviderDeclaration, PlanningBlockedError } from '@treeseed-cordis/sdk'; +import { InstalledSchemas, ServiceSchemas, PlatformSchemas, CapabilityToken, ProviderSchemas, type InstalledEnvelope, type ServiceEnvelope, PluginManagementSchemas, type DiagnosticConfiguration, type DeploymentConfiguration, type ProviderArtifact, type ProviderDeclaration, PlanningBlockedError } from '@treeseed-cordis/sdk'; import { Context, CordisComposition, CordisServiceLocator, CompositionError, InstalledProviderLoader, type CompositionHandle, type ProviderLease, type ProviderRegistration } from '@treeseed-cordis/sdk/runtime'; import { openSync, fstatSync, readFileSync, closeSync, constants } from 'node:fs'; import { resolve, join, isAbsolute } from 'node:path'; import { createHash } from 'node:crypto'; import { parse, visit, type ParseError } from 'jsonc-parser'; -interface ConfigurationReader {read(path:string):DeploymentConfiguration;} +type CliEnvelope=InstalledEnvelope|ServiceEnvelope|PluginEnvelope; +class CliProtocol {static readonly envelope=ServiceSchemas.envelope.or(InstalledSchemas.envelope).or(PluginManagementSchemas.envelope);} +interface ConfigurationReader {read(path:string):DeploymentConfiguration;object(path:string):Record;} interface CommandService {execute(args:string[]):Promise;} -interface OutputService {render(result:CliExecution):RenderedOutput;} +interface OutputService {render(result:CliExecution):Promise;} interface RenderedOutput {stdout:string;stderr:string;} export interface CliExecution {code:0|1|2|3;json:boolean;envelope:CliEnvelope;} class ArgumentProblem extends Error {} export class CliArguments { - static readonly help='Usage: trsd --help | --version | doctor [--json] [--context NAME] [--installation ABSOLUTE_PATH] [--port INTEGER] | platform plan --file CONFIG [--json] | platform apply --installation DIR --plan ID --digest SHA --idempotency-key KEY [--json] | platform status --installation DIR [--json] | platform application --installation DIR --id ID [--json]'; + static readonly help='Usage: trsd --help | --version | doctor [--json] [--context NAME] [--installation ABSOLUTE_PATH] [--port INTEGER] | platform plan --file CONFIG [--json] | platform apply --installation DIR --plan ID --digest SHA --idempotency-key KEY [--json] | platform status --installation DIR [--json] | platform application --installation DIR --id ID [--json] | plugin install SOURCE --installation DIR [--target TARGET] [--service ID] [--json] | plugin select CAPABILITY PROVIDER --installation DIR --target TARGET [--json] | plugin list --installation DIR [--json] | plugin inspect REQUEST --installation DIR [--json] | platform apply ... --restart SERVICE'; static readonly unsupported=['platform','plan','apply','status','install','uninstall','update','open','recover','events','cancel','application','development']; static plan(args:string[],files:ConfigurationReader):DeploymentConfiguration { const seen=new Set();let file:string|null=null; for(let index=2;index();let json=false; - for(let index=2;index(),restartServices:string[]=[];let json=false; + for(let index=2;index(); @@ -44,60 +49,72 @@ class ConfigurationFile implements ConfigurationReader { begin():void {this.keys.push(new Set());} property(value:string):void {const current=this.keys[this.keys.length-1]!;if(current.has(value)||value==='__proto__')this.duplicate=true;current.add(value);} end():void {this.keys.pop();} - read(path:string):DeploymentConfiguration { - let fd:number|undefined; - try {fd=openSync(path,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);const stat=fstatSync(fd);if(!stat.isFile()||stat.size>1024*1024)throw new ArgumentProblem();const text=new TextDecoder('utf-8',{fatal:true}).decode(readFileSync(fd)),errors:ParseError[]=[];visit(text,{onObjectBegin:this.begin.bind(this),onObjectProperty:this.property.bind(this),onObjectEnd:this.end.bind(this)},{disallowComments:true,allowTrailingComma:false});const value:unknown=parse(text,errors,{disallowComments:true,allowTrailingComma:false});if(errors.length||this.duplicate)throw new ArgumentProblem();const parsed=PlatformSchemas.desired.safeParse(value);if(!parsed.success)throw new ArgumentProblem();return parsed.data;}catch{throw new ArgumentProblem();}finally{if(fd!==undefined)closeSync(fd);} + private value(path:string):unknown { + this.keys.length=0;this.duplicate=false;let fd:number|undefined; + try {fd=openSync(path,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);const stat=fstatSync(fd);if(!stat.isFile()||stat.size>1024*1024)throw new ArgumentProblem();const text=new TextDecoder('utf-8',{fatal:true}).decode(readFileSync(fd)),errors:ParseError[]=[];visit(text,{onObjectBegin:this.begin.bind(this),onObjectProperty:this.property.bind(this),onObjectEnd:this.end.bind(this)},{disallowComments:true,allowTrailingComma:false});const value:unknown=parse(text,errors,{disallowComments:true,allowTrailingComma:false});if(errors.length||this.duplicate)throw new ArgumentProblem();return value;}catch{throw new ArgumentProblem();}finally{if(fd!==undefined)closeSync(fd);} } + read(path:string):DeploymentConfiguration {const parsed=PlatformSchemas.desired.or(ServiceSchemas.configuration).safeParse(this.value(path));if(!parsed.success)throw new ArgumentProblem();return parsed.data;} + object(path:string):Record {const value=this.value(path);if(!value||typeof value!=='object'||Array.isArray(value))throw new ArgumentProblem();return value as Record;} } class CliCommands implements CommandService { constructor(private readonly context:Context) {} async execute(args:string[]):Promise { - const command=args[0]??'--help',planning=command==='platform'&&args[1]==='plan',json=(command==='doctor'||command==='platform')&&args.includes('--json'); - let hostLease:ProviderLease|undefined,configurationLease:ProviderLease|undefined; + const command=args[0]??'--help',planning=command==='platform'&&args[1]==='plan',json=(command==='doctor'||command==='platform'||command==='plugin')&&args.includes('--json'); + let hostLease:ProviderLease|undefined,configurationLease:ProviderLease|undefined,pluginLease:ProviderLease|undefined; try { const locator=CordisServiceLocator.from(this.context);hostLease=await locator.acquire(DeploymentCapability);configurationLease=await locator.acquire(ConfigurationCapability);const host=hostLease.value,files=configurationLease.value; if((command==='--help'||command==='help')&&args.length<=1)return this.success('help',{help:CliArguments.help}); - if(command==='--version'&&args.length===1)return this.success('version',{version:'0.0.0-cordis.4'}); - if(planning){const plan=await host.plan(CliArguments.plan(args,files));return {code:0,json,envelope:InstalledSchemas.envelope.parse({command:'platform.plan',success:true,result:plan,problem:null,blockers:[],references:[join(plan.configuration.installationDirectory,'.cordis/plans',plan.id+'.json')]})};} - if(command==='platform'&&['apply','status','application'].includes(args[1]??'')){const options=CliArguments.installed(args);let result:CliEnvelope['result'];const operation=args[1]!;if(operation==='apply'){if(!host.apply)return this.failure('platform.apply',3,json,'UNSUPPORTED_OPERATION','The selected Deployment provider does not support apply.');result=await host.apply(options.planId!,options.digest!,{installationDirectory:options.installationDirectory,idempotencyKey:options.idempotencyKey!});}else if(operation==='status'){if(!host.status)return this.failure('platform.status',3,json,'UNSUPPORTED_OPERATION','The selected Deployment provider does not support status.');result=await host.status(options.installationDirectory);}else{if(!host.application)return this.failure('platform.application',3,json,'UNSUPPORTED_OPERATION','The selected Deployment provider does not support application read-back.');result=await host.application(options.installationDirectory,options.id!);}return {code:0,json,envelope:InstalledSchemas.envelope.parse({command:'platform.'+operation,success:true,result,problem:null,blockers:[],references:operation==='apply'?['application:'+(result as {id:string}).id]:[]})};} + if(command==='--version'&&args.length===1)return this.success('version',{version:'0.0.0-cordis.8'}); + if(command==='plugin'){pluginLease=await locator.acquire(PluginCapability);return {json,...await pluginLease.value.execute(args)};} + if(planning){const plan=await host.plan(CliArguments.plan(args,files));return {code:0,json,envelope:CliProtocol.envelope.parse({command:'platform.plan',success:true,result:plan,problem:null,blockers:[],references:[join(plan.configuration.installationDirectory,'.cordis/plans',plan.id+'.json')]})};} + if(command==='platform'&&['apply','status','application'].includes(args[1]??'')){const options=CliArguments.installed(args);let result:CliEnvelope['result'];const operation=args[1]!;if(operation==='apply'){if(!host.apply)return this.failure('platform.apply',3,json,'UNSUPPORTED_OPERATION','The selected Deployment provider does not support apply.');result=await host.apply(options.planId!,options.digest!,{installationDirectory:options.installationDirectory,idempotencyKey:options.idempotencyKey!,...(options.restartServices?{restartServices:options.restartServices}:{})});}else if(operation==='status'){if(!host.status)return this.failure('platform.status',3,json,'UNSUPPORTED_OPERATION','The selected Deployment provider does not support status.');result=await host.status(options.installationDirectory);}else{if(!host.application)return this.failure('platform.application',3,json,'UNSUPPORTED_OPERATION','The selected Deployment provider does not support application read-back.');result=await host.application(options.installationDirectory,options.id!);}return {code:0,json,envelope:CliProtocol.envelope.parse({command:'platform.'+operation,success:true,result,problem:null,blockers:[],references:operation==='apply'?['application:'+(result as {id:string}).id]:[]})};} if(CliArguments.unsupported.includes(command))return this.failure('unsupported',3,json,'UNSUPPORTED_COMMAND','This executable supports help, version, doctor, plan, apply, status and application read-back. Run trsd --help.'); if(command!=='doctor')throw new ArgumentProblem(); const configuration=CliArguments.doctor(args),report=await host.diagnose(configuration); const blockers=[];for(const check of report.checks)if(check.status==='blocked')blockers.push({code:check.code,message:check.message}); - const envelope=InstalledSchemas.envelope.parse({command:'doctor',success:report.ready,result:report,problem:report.ready?null:{code:'PREREQUISITES_UNMET',title:'Host prerequisites are unmet',detail:'Resolve the blocked doctor checks before continuing.'},blockers,references:[]}); + const envelope=CliProtocol.envelope.parse({command:'doctor',success:report.ready,result:report,problem:report.ready?null:{code:'PREREQUISITES_UNMET',title:'Host prerequisites are unmet',detail:'Resolve the blocked doctor checks before continuing.'},blockers,references:[]}); return {code:report.ready?0:3,json,envelope}; }catch(error) { - const label=command==='platform'?'platform.'+(args[1]??'unknown'):command==='doctor'?'doctor':'unknown'; - if(error instanceof PlanningBlockedError)return {code:3,json,envelope:InstalledSchemas.envelope.parse({command:label,success:false,result:null,problem:{code:planning?'PLANNING_BLOCKED':'OPERATION_BLOCKED',title:'Operation is blocked',detail:'Resolve the reported blockers before continuing.'},blockers:error.blockers,references:[]})}; - if(error instanceof ArgumentProblem)return this.failure(label,2,json,'INVALID_ARGUMENTS','Invalid arguments. Run trsd --help for supported arguments.'); + const label=command==='plugin'?'plugin.'+(args[1]??'unknown'):command==='platform'?'platform.'+(args[1]??'unknown'):command==='doctor'?'doctor':'unknown'; + if(error instanceof PlanningBlockedError)return {code:3,json,envelope:CliProtocol.envelope.parse({command:label,success:false,result:null,problem:{code:planning?'PLANNING_BLOCKED':'OPERATION_BLOCKED',title:'Operation is blocked',detail:'Resolve the reported blockers before continuing.'},blockers:error.blockers,references:[]})}; + if(error instanceof ArgumentProblem||error instanceof PluginArgumentProblem)return this.failure(label,2,json,'INVALID_ARGUMENTS','Invalid arguments. Run trsd --help for supported arguments.'); return this.failure(label,1,json,'RUNTIME_FAILURE','The requested operation failed unexpectedly. Check local prerequisites and run trsd --help.'); - }finally{await configurationLease?.release();await hostLease?.release();} + }finally{await pluginLease?.release();await configurationLease?.release();await hostLease?.release();} } - private success(command:string,result:CliEnvelope['result']):CliExecution {return {code:0,json:false,envelope:InstalledSchemas.envelope.parse({command,success:true,result,problem:null,blockers:[],references:[]})};} - private failure(command:string,code:1|2|3,json:boolean,problemCode:string,detail:string):CliExecution {return {code,json,envelope:InstalledSchemas.envelope.parse({command,success:false,result:null,problem:{code:problemCode,title:problemCode,detail},blockers:[],references:[]})};} + private success(command:string,result:CliEnvelope['result']):CliExecution {return {code:0,json:false,envelope:CliProtocol.envelope.parse({command,success:true,result,problem:null,blockers:[],references:[]})};} + private failure(command:string,code:1|2|3,json:boolean,problemCode:string,detail:string):CliExecution {return {code,json,envelope:CliProtocol.envelope.parse({command,success:false,result:null,problem:{code:problemCode,title:problemCode,detail},blockers:[],references:[]})};} +} +class TerminalPresentation implements UiTerminalRendering { + async render(view:UiViewModel){const renderer=await UiTerminalRenderer.create();try{return await renderer.render(view);}finally{await renderer.dispose();}} +} +class CliViews { + static table(id:string,title:string,columns:string[],rows:string[][]):UiViewModel{return {id,componentId:'table',model:{title,columns,rows}};} + static primary(envelope:CliEnvelope):UiViewModel|null { + const result=envelope.result;if(!result)return null; + if(Array.isArray(result)){const rows:string[][]=[];for(const item of result)rows.push([item.requestId,item.pluginId??'unresolved',item.state,item.activeGeneration??'none']);return this.table('plugins','Plugin requests',['Request','Plugin','State','Active generation'],rows);} + if('requestId'in result){const rows:string[][]=[];for(const action of result.nextActions)rows.push([action]);return {id:'plugin',componentId:'stack',model:{children:[{id:'plugin-state',componentId:'status',model:{title:result.pluginId??'Plugin request',state:result.state,detail:'Request '+result.requestId}},this.table('plugin-references','Accepted references',['Plan','Application','Active generation'],[[result.planId??'none',result.applicationId??'none',result.activeGeneration??'none']]),this.table('plugin-actions','Required actions',['Action'],rows)]}};} + if('help'in result)return {id:'help',componentId:'text',model:{text:result.help}}; + if('version'in result)return {id:'version',componentId:'text',model:{text:'trsd '+result.version}}; + if('checks'in result){const rows:string[][]=[];for(const check of result.checks)rows.push([check.id,check.status,check.code,check.message]);return {id:'doctor',componentId:'stack',model:{title:'TreeSeed Cordis diagnostics',children:[{id:'host',componentId:'status',model:{title:'Host prerequisites',state:result.ready?'Qualified':'Blocked'}},this.table('checks','Diagnostic checks',['Check','Result','Code','Detail'],rows)]}};} + if('recipe'in result){const services:string[][]=[],volumes:string[][]=[],ports:string[][]=[],effects:string[][]=[],references:string[][]=[];for(const [id,service]of Object.entries(result.recipe.services)){services.push([id,service.image]);for(const volume of service.volumes??[])volumes.push([id,volume.source,volume.target,volume.read_only?'Read only':'Read/write']);for(const port of service.ports??[])ports.push([id,port.host_ip,String(port.published),String(port.target)]);}for(const effect of result.effects)effects.push([effect.kind,effect.target]);for(const reference of envelope.references)references.push([reference]);return {id:'plan',componentId:'stack',model:{title:'Deployment plan',children:[{id:'identity',componentId:'status',model:{title:result.id,state:'Saved',detail:'Future effects only. Digest '+result.digest}},{id:'origin',componentId:'status',model:{title:'Origin',state:result.configuration.origin}},{id:'engine',componentId:'status',model:{title:'Engine',state:result.expectedEngine.context,detail:result.expectedEngine.daemonId}},this.table('services','Services',['Service','Image'],services),this.table('volumes','Volume mounts',['Service','Source','Target','Access'],volumes),this.table('ports','Port publications',['Service','Host','Published','Target'],ports),this.table('effects','Future effects',['Effect','Target'],effects),this.table('references','Saved references',['Reference'],references)]}};} + if('accepted'in result)return {id:'application',componentId:'status',model:{title:'Application '+result.id,state:'Accepted',detail:'Check platform application for readiness.'}}; + if('phase'in result)return {id:'application',componentId:'stack',model:{children:[{id:'state',componentId:'status',model:{title:'Application '+result.id,state:result.phase}},this.table('result','Application result',['Result','Recovery'],[[result.result??'pending',result.recovery??'none']])]}}; + if('activeComposition'in result&&'installationId'in result){const children:UiViewModel[]=[{id:'installation',componentId:'status',model:{title:'Installation '+result.installationId,state:result.ready?'Ready':'Not ready'}},{id:'composition',componentId:'status',model:{title:'Active composition',state:result.activeComposition??'none'}}];if('services'in result){const rows:string[][]=[];for(const service of result.services)rows.push([service.serviceId,service.providerId,service.ready?'Ready':'Not ready',service.serviceGeneration]);children.push(this.table('services','Installed services',['Service','Provider','Readiness','Generation'],rows));}return {id:'status',componentId:'stack',model:{children}};} + return null; + } + static errors(envelope:CliEnvelope):UiViewModel|null{const children:UiViewModel[]=[];if(envelope.command.startsWith('platform.')||envelope.command.startsWith('plugin.'))for(const [index,blocker]of envelope.blockers.entries())children.push({id:'blocker-'+index,componentId:'feedback',model:{title:blocker.code,message:blocker.message,tone:'error'}});if(envelope.problem)children.push({id:'problem',componentId:'feedback',model:{title:envelope.problem.code,message:envelope.problem.detail,tone:'error'}});return children.length?{id:'errors',componentId:'stack',model:{children}}:null;} } export class CliOutput implements OutputService { - render(result:CliExecution):RenderedOutput { - const envelope=result.envelope,stdout:string[]=[],stderr:string[]=[]; - if(result.json)return {stdout:JSON.stringify(envelope)+'\n',stderr:''}; - if(envelope.result&&'help' in envelope.result)return {stdout:envelope.result.help+'\n',stderr:''}; - if(envelope.result&&'version' in envelope.result)return {stdout:'trsd '+envelope.result.version+'\n',stderr:''}; - if(envelope.result&&'checks' in envelope.result)for(const check of envelope.result.checks)stdout.push(`${check.status}: ${check.id} [${check.code}] ${check.message}`); - if(envelope.result&&'recipe' in envelope.result){stdout.push(`Plan ${envelope.result.id} (${envelope.result.digest}) saved. Future effects only.`,`Origin: ${envelope.result.configuration.origin}`,`Engine: ${envelope.result.expectedEngine.context} (${envelope.result.expectedEngine.daemonId})`);for(const [name,service] of Object.entries(envelope.result.recipe.services)){stdout.push(`Service ${name}: ${service.image}`);for(const mount of service.volumes??[])stdout.push(` Volume ${mount.source} -> ${mount.target}`);for(const port of service.ports??[])stdout.push(` Port ${port.host_ip}:${port.published} -> ${port.target}/tcp`);}for(const effect of envelope.result.effects)stdout.push(`${effect.kind}: ${effect.target}`);stdout.push(...envelope.references);} - if(envelope.result&&'accepted' in envelope.result)stdout.push(`Application ${envelope.result.id} accepted. Check platform application for readiness.`); - if(envelope.result&&'phase' in envelope.result)stdout.push(`Application ${envelope.result.id}: ${envelope.result.phase}`,`Result: ${envelope.result.result??'pending'}`,`Recovery: ${envelope.result.recovery??'none'}`); - if(envelope.result&&'activeComposition' in envelope.result&&'installationId' in envelope.result)stdout.push(`Installation ${envelope.result.installationId}: ${envelope.result.ready?'ready':'not ready'}`,`Active composition: ${envelope.result.activeComposition??'none'}`); - for(const blocker of envelope.blockers)if(envelope.command.startsWith('platform.'))stderr.push(`${blocker.code}: ${blocker.message}`); - if(envelope.problem)stderr.push(`${envelope.problem.code}: ${envelope.problem.detail}`); - return {stdout:stdout.length?stdout.join('\n')+'\n':'',stderr:stderr.length?stderr.join('\n')+'\n':''}; - } - write(result:CliExecution):void {NativeStreams.write(this.render(result));} + constructor(private readonly presentation:UiTerminalRendering=new TerminalPresentation()){} + async render(result:CliExecution):Promise{const envelope=result.envelope;if(result.json)return {stdout:JSON.stringify(envelope)+'\n',stderr:''};const primary=CliViews.primary(envelope),errors=CliViews.errors(envelope);return {stdout:primary?(await this.presentation.render(primary)).text:'',stderr:errors?(await this.presentation.render(errors)).text:''};} + async write(result:CliExecution):Promise{NativeStreams.write(await this.render(result));} } class NativeStreams {static write(output:RenderedOutput):void {if(output.stdout)process.stdout.write(output.stdout);if(output.stderr)process.stderr.write(output.stderr);}} class CapabilityValidation { constructor(private readonly method:string){} parse(value:unknown):T {if(!value||typeof Reflect.get(value as object,this.method)!=='function')throw new Error('Invalid CLI adapter');return value as T;} } +const PluginCapability=new CapabilityToken('cli.plugins','0.3.0-cordis.1',new CapabilityValidation('execute')); const ConfigurationCapability=new CapabilityToken('cli.configuration','0.3.0-cordis.1',new CapabilityValidation('read')); const CommandCapability=new CapabilityToken('cli.commands','0.3.0-cordis.1',new CapabilityValidation('execute')); const OutputCapability=new CapabilityToken('cli.output','0.3.0-cordis.1',new CapabilityValidation('render')); @@ -107,9 +124,13 @@ class ConfigurationPlugin { constructor(context:Context){context.provide(ConfigurationCapability.id,new ConfigurationFile());} } class CommandsPlugin { - static readonly declaration=CoreDeclarations.define('core-commands','cli.commands',['cordis.composition','deployment','cli.configuration']);static readonly provide=this.declaration.provide;static readonly inject=this.declaration.inject;static readonly Config=PlatformSchemas.empty; + static readonly declaration=CoreDeclarations.define('core-commands','cli.commands',['cordis.composition','deployment','cli.configuration','cli.plugins']);static readonly provide=this.declaration.provide;static readonly inject=this.declaration.inject;static readonly Config=PlatformSchemas.empty; constructor(context:Context){context.provide(CommandCapability.id,new CliCommands(context));} } +class PluginCommandsPlugin { + static readonly declaration=CoreDeclarations.define('installed-plugins','cli.plugins',['cli.configuration']);static readonly provide=this.declaration.provide;static readonly inject=this.declaration.inject;static readonly Config=PlatformSchemas.empty; + constructor(context:Context){context.provide(PluginCapability.id,new InstalledPluginCommands(ConfigurationCapability.parse(Reflect.get(context,ConfigurationCapability.id))));} +} class OutputPlugin { static readonly declaration=CoreDeclarations.define('terminal','cli.output');static readonly provide=this.declaration.provide;static readonly inject=this.declaration.inject;static readonly Config=PlatformSchemas.empty; constructor(context:Context){context.provide(OutputCapability.id,new CliOutput());} @@ -117,18 +138,18 @@ class OutputPlugin { class Invocation {context:Context|null=null;} class InvocationPlugin {static readonly inject=['cordis.composition','cli.commands','cli.output'];constructor(context:Context,invocation:Invocation){invocation.context=context;}} class CliComposition { - static core(artifact:ProviderArtifact):ProviderRegistration[] {return [{token:ConfigurationCapability,plugin:ConfigurationPlugin,declaration:ConfigurationPlugin.declaration,configuration:{},artifact},{token:CommandCapability,plugin:CommandsPlugin,declaration:CommandsPlugin.declaration,configuration:{},artifact},{token:OutputCapability,plugin:OutputPlugin,declaration:OutputPlugin.declaration,configuration:{},artifact}];} - static selections(scopeId:string):Array<{scopeId:string;capability:string;providerId:string}> {return [{scopeId,capability:'cli.configuration',providerId:'json-file'},{scopeId,capability:'cli.commands',providerId:'core-commands'},{scopeId,capability:'cli.output',providerId:'terminal'}];} + static core(artifact:ProviderArtifact):ProviderRegistration[] {return [{token:PluginCapability,plugin:PluginCommandsPlugin,declaration:PluginCommandsPlugin.declaration,configuration:{},artifact},{token:ConfigurationCapability,plugin:ConfigurationPlugin,declaration:ConfigurationPlugin.declaration,configuration:{},artifact},{token:CommandCapability,plugin:CommandsPlugin,declaration:CommandsPlugin.declaration,configuration:{},artifact},{token:OutputCapability,plugin:OutputPlugin,declaration:OutputPlugin.declaration,configuration:{},artifact}];} + static selections(scopeId:string):Array<{scopeId:string;capability:string;providerId:string}> {return [{scopeId,capability:'cli.plugins',providerId:'installed-plugins'},{scopeId,capability:'cli.configuration',providerId:'json-file'},{scopeId,capability:'cli.commands',providerId:'core-commands'},{scopeId,capability:'cli.output',providerId:'terminal'}];} static prepared(args:string[]):{args:string[];file:string|null;digest:string|null} { const result:string[]=[],seen=new Set();let file:string|null=null,digest:string|null=null; for(let index=0;index {return this.invoke(args,false);} private async invoke(args:string[],emit:boolean):Promise { - const planning=args[0]==='platform'&&args[1]==='plan',json=(args[0]==='doctor'||args[0]==='platform')&&args.includes('--json'); + const planning=args[0]==='platform'&&args[1]==='plan',json=(args[0]==='doctor'||args[0]==='platform'||args[0]==='plugin')&&args.includes('--json'); let handle:CompositionHandle|null=null,result:CliExecution,output:RenderedOutput; try { const prepared=CliComposition.prepared(args),scopeId='local-cli',artifact:ProviderArtifact={kind:'bundled',identity:'sha256:'+createHash('sha256').update(readFileSync(process.execPath)).digest('hex')}; @@ -137,9 +158,9 @@ export class CliApplication { registrations.push(...CliComposition.core(artifact));selections.push(...CliComposition.selections(scopeId)); handle=await CordisComposition.start({registrations,selections},{scopeId,target:'cli',principalId:'uid:'+String(process.getuid?.()??process.pid),resourceScope:'local-owner'}); const invocation=new Invocation();await handle.mount(InvocationPlugin,invocation);const locator=CordisServiceLocator.from(invocation.context!),commands=await locator.acquire(CommandCapability),renderer=await locator.acquire(OutputCapability); - try {result=await commands.value.execute(prepared.args);output=renderer.value.render(result);}finally{await renderer.release();await commands.release();} + try {result=await commands.value.execute(prepared.args);output=await renderer.value.render(result);}finally{await renderer.release();await commands.release();} await handle.dispose();handle=null; - }catch(error){if(handle)try{await handle.dispose();}catch{}const code=error instanceof ArgumentProblem?2:error instanceof CompositionError&&error.code!=='PROVIDER_LIFECYCLE'?3:1;const problemCode=code===2?'INVALID_ARGUMENTS':code===3?'COMPOSITION_BLOCKED':'RUNTIME_FAILURE';result={code,json,envelope:InstalledSchemas.envelope.parse({command:args[0]==='platform'?'platform.'+(args[1]??'unknown'):args[0]==='doctor'?'doctor':'unknown',success:false,result:null,problem:{code:problemCode,title:problemCode,detail:'The requested command could not complete. Check the selected provider and run trsd --help.'},blockers:code===3?[{code:'COMPOSITION_BLOCKED',message:'The prepared provider or composition was rejected.'}]:[],references:[]})};output=json?{stdout:JSON.stringify(result.envelope)+'\n',stderr:''}:{stdout:'',stderr:problemCode+': '+result.envelope.problem!.detail+'\n'};} + }catch(error){if(handle)try{await handle.dispose();}catch{}const code=error instanceof ArgumentProblem?2:error instanceof CompositionError&&error.code!=='PROVIDER_LIFECYCLE'?3:1;const problemCode=code===2?'INVALID_ARGUMENTS':code===3?'COMPOSITION_BLOCKED':'RUNTIME_FAILURE';result={code,json,envelope:CliProtocol.envelope.parse({command:args[0]==='plugin'?'plugin.'+(args[1]??'unknown'):args[0]==='platform'?'platform.'+(args[1]??'unknown'):args[0]==='doctor'?'doctor':'unknown',success:false,result:null,problem:{code:problemCode,title:problemCode,detail:'The requested command could not complete. Check the selected provider and run trsd --help.'},blockers:code===3?[{code:'COMPOSITION_BLOCKED',message:'The prepared provider or composition was rejected.'}]:[],references:[]})};try{output=await new CliOutput().render(result);}catch{output=json?{stdout:JSON.stringify(result.envelope)+'\n',stderr:''}:{stdout:'',stderr:problemCode+'\n'};}} if(emit)NativeStreams.write(output);return result; } private static notDeployment(registration:ProviderRegistration):boolean {return registration.token.id!=='deployment';} diff --git a/src/plugins.ts b/src/plugins.ts new file mode 100644 index 0000000..8167e48 --- /dev/null +++ b/src/plugins.ts @@ -0,0 +1,61 @@ +import { randomUUID } from 'node:crypto'; +import { isAbsolute, resolve } from 'node:path'; +import { PluginManagementSchemas, type PluginInstallResult, type PluginInstallRequest, type PluginSelectRequest } from '@treeseed-cordis/sdk'; +import { InstalledPluginManager } from '@treeseed-cordis/deployment'; +export type PluginEnvelope = ReturnType; +export class PluginArgumentProblem extends Error {} +export interface PluginConfigurationReader { object(path: string): Record; } +export interface CliPluginManagement { execute(args: string[]): Promise<{ code: 0 | 3; envelope: PluginEnvelope }>; } +interface PluginArguments { + operation: 'install' | 'select' | 'list' | 'inspect'; + installationDirectory: string; + target?: PluginInstallRequest['target']; + scope: PluginInstallRequest['scope']; + requestId?: string; + install?: PluginInstallRequest; + select?: PluginSelectRequest; +} +class PluginArgumentsReader { + static parse(args: string[], files: PluginConfigurationReader): PluginArguments { + try { return this.read(args, files); } catch { throw new PluginArgumentProblem(); } + } + private static read(args: string[], files: PluginConfigurationReader): PluginArguments { + const operation = args[1]; + if (!['install', 'select', 'list', 'inspect'].includes(operation ?? '')) throw new PluginArgumentProblem(); + const offset = operation === 'select' ? 4 : operation === 'list' ? 2 : 3, positionals = args.slice(2, offset); + if (args.length < offset || positionals.some(this.flag)) throw new PluginArgumentProblem(); + const allowed = operation === 'install' ? ['--installation', '--target', '--provider', '--service', '--scope', '--idempotency-key', '--binding', '--configuration'] : operation === 'select' ? ['--installation', '--target', '--service', '--scope', '--idempotency-key', '--configuration'] : operation === 'list' ? ['--installation', '--target', '--scope'] : ['--installation']; + const values = new Map(), bindings: Record = {}; let json = false; + for (let index = offset; index < args.length; index++) { + const flag = args[index]!; + if (flag === '--json') { if (json) throw new PluginArgumentProblem(); json = true; continue; } + if (!allowed.includes(flag) || (flag !== '--binding' && values.has(flag))) throw new PluginArgumentProblem(); + const value = args[++index]; if (!value || this.flag(value)) throw new PluginArgumentProblem(); + if (flag === '--binding') { const parts = value.split('='); if (parts.length !== 2 || !parts[0] || !parts[1] || Object.hasOwn(bindings, parts[0]) || parts[0] === '__proto__') throw new PluginArgumentProblem(); bindings[parts[0]] = parts[1]; } + else values.set(flag, value); + } + const directory = values.get('--installation'); if (!directory || !isAbsolute(directory)) throw new PluginArgumentProblem(); + const installationDirectory = resolve(directory), scope = PluginManagementSchemas.scope.parse(values.get('--scope') ?? 'installation'), target = values.has('--target') ? PluginManagementSchemas.target.parse(values.get('--target')) : undefined; + if (operation === 'list') return { operation, installationDirectory, scope, ...(target ? { target } : {}) }; + if (operation === 'inspect') return { operation, installationDirectory, scope, requestId: PluginManagementSchemas.key.parse(positionals[0]) }; + const configuration = values.has('--configuration') ? files.object(resolve(values.get('--configuration')!)) : {}, common = { installationDirectory, scope, target, configuration, idempotencyKey: values.get('--idempotency-key') ?? operation + '-' + randomUUID(), ...(values.has('--service') ? { serviceId: values.get('--service') } : {}) }; + if (operation === 'install') return { operation, installationDirectory, scope, install: PluginManagementSchemas.install.parse({ ...common, source: positionals[0], ...(values.has('--provider') ? { providerId: values.get('--provider') } : {}), ...(Object.keys(bindings).length ? { bindings } : {}) }) }; + return { operation: 'select', installationDirectory, scope, select: PluginManagementSchemas.select.parse({ ...common, capability: positionals[0], providerId: positionals[1] }) }; + } + private static flag(value: string): boolean { return value.startsWith('-'); } +} +/** Human/machine command adapter. Deployment owns source policy and durable transition authority. */ +export class InstalledPluginCommands implements CliPluginManagement { + constructor(private readonly files: PluginConfigurationReader) {} + async execute(args: string[]): Promise<{ code: 0 | 3; envelope: PluginEnvelope }> { + const parsed = PluginArgumentsReader.parse(args, this.files), manager = new InstalledPluginManager(parsed.installationDirectory); + let result: PluginInstallResult | PluginInstallResult[]; + if (parsed.operation === 'install') result = await manager.install(parsed.install!); + else if (parsed.operation === 'select') result = await manager.select(parsed.select!); + else if (parsed.operation === 'list') result = await manager.list(parsed.scope, parsed.target); + else result = await manager.inspect(parsed.requestId!); + const success = parsed.operation === 'list' || parsed.operation === 'inspect' || (!Array.isArray(result) && ['active', 'already-active'].includes(result.state)); + const envelope = PluginManagementSchemas.envelope.parse({ command: 'plugin.' + parsed.operation, success, result, problem: success ? null : { code: 'PLUGIN_ACTION_REQUIRED', title: 'Plugin action required', detail: 'Inspect the request and complete the reported actions.' }, blockers: success || Array.isArray(result) ? [] : result.blockers, references: Array.isArray(result) ? [] : ['request:' + result.requestId] }); + return { code: success ? 0 : 3, envelope }; + } +} diff --git a/tests/cli-program.test.ts b/tests/cli-program.test.ts index c267221..0d58ccf 100644 --- a/tests/cli-program.test.ts +++ b/tests/cli-program.test.ts @@ -7,7 +7,10 @@ import { createServer, type Server } from 'node:net'; import { createHash } from 'node:crypto'; import { PreparedReleaseFixture } from '@treeseed-cordis/deployment/testing'; import { CliApplication } from '../src/main.js'; -import { PlatformSchemas, type CliEnvelope } from '@treeseed-cordis/sdk'; +import { ServiceRuntimeFixture } from '@treeseed-cordis/deployment/testing/runtime'; +import { ServiceWorkerBuild, ServicePlanStore } from '@treeseed-cordis/deployment'; +import { PluginInstallationFixture } from '@treeseed-cordis/deployment/testing/plugins'; +import { CanonicalJson, ServiceSchemas, PlatformSchemas, PluginManagementSchemas, type PluginInstallResult, type ServiceResourceReceipt, type CliEnvelope } from '@treeseed-cordis/sdk'; class CliProgramFixture { readonly root=mkdtempSync(join(tmpdir(),'cordis cli ')); @@ -24,6 +27,24 @@ class CliTests { listen(resolvePort:(port:number)=>void):void {this.resolvePort=resolvePort;this.server=createServer();this.server.listen(0,'127.0.0.1',this.listening.bind(this));} listening():void {const address=this.server!.address();if(address&&typeof address==='object')this.resolvePort!(address.port);} async port(occupied=false):Promise {const port=await new Promise(this.listen.bind(this));if(!occupied)this.server!.close();return port;} + pluginArguments():void { + const fixture=new CliProgramFixture(); + try { + for(const args of [ + ['plugin','install','--json'], + ['plugin','install','@fixture/example','--installation','relative','--json'], + ['plugin','select','probe.service','example.probe','--installation',fixture.root,'--json'], + ['plugin','inspect','--installation',fixture.root,'--json'], + ['plugin','list','--installation',fixture.root,'--target','secret-canary','--json'], + ['plugin','install','@fixture/example','--installation',fixture.root,'--binding','invalid','--json'] + ]) {const result=fixture.run(args,{PATH:''});expect(result.status).toBe(2);expect(result.stderr).toBe('');const envelope=JSON.parse(result.stdout);expect(envelope.command).toBe('plugin.'+args[1]);expect(envelope.result).toBeNull();expect(envelope.problem.code).toBe('INVALID_ARGUMENTS');expect(result.stdout).not.toContain('secret-canary');} + const configuration=join(fixture.root,'provider.json'),installation=join(fixture.root,'uncreated'); + for(const bytes of ['{"enabled":true,"enabled":false}','{"__proto__":{"secret":"secret-canary"}}','[1,2]','malformed secret-canary']){writeFileSync(configuration,bytes);const result=fixture.run(['plugin','install','@fixture/example','--installation',installation,'--configuration',configuration,'--json'],{PATH:''});expect(result.status).toBe(2);expect(JSON.parse(result.stdout).problem.code).toBe('INVALID_ARGUMENTS');expect(result.stdout+result.stderr).not.toContain('secret-canary');expect(existsSync(installation)).toBe(false);} + const digest='0'.repeat(64),restart=fixture.run(['platform','apply','--installation',installation,'--plan','plan-'+digest,'--digest',digest,'--idempotency-key','explicit-restart','--restart','example','--json'],{PATH:''});expect(restart.status).toBe(1);expect(JSON.parse(restart.stdout).problem.code).toBe('RUNTIME_FAILURE');expect(existsSync(installation)).toBe(false); + const help=fixture.run(['--help'],{PATH:''});expect(help.stdout).toContain('plugin install');expect(help.stdout).toContain('--restart'); + const empty=fixture.run(['plugin','list','--installation',join(fixture.root,'missing'),'--json'],{PATH:''});expect(empty.status).toBe(3);expect(JSON.parse(empty.stdout).result).toBeNull();expect(existsSync(join(fixture.root,'missing'))).toBe(false); + } finally {fixture.close();} + } installedArguments():void { const fixture=new CliProgramFixture(); try{for(const command of ["apply","status","application"]){const result=fixture.run(["platform",command,"--json"],{PATH:""});expect(result.status).toBe(2);expect(result.stderr).toBe("");expect(JSON.parse(result.stdout).problem.code).toBe("INVALID_ARGUMENTS");}}finally{fixture.close();} @@ -32,7 +53,7 @@ class CliTests { const fixture=new CliProgramFixture(); try { for(const binary of [fixture.binary,fixture.symlink]) { - const version=fixture.run(['--version'],{PATH:''},binary);expect(version.status).toBe(0);expect(version.stdout).toBe('trsd 0.0.0-cordis.4\n');expect(version.stderr).toBe(''); + const version=fixture.run(['--version'],{PATH:''},binary);expect(version.status).toBe(0);expect(version.stdout).toBe('trsd 0.0.0-cordis.8\n');expect(version.stderr).toBe(''); const help=fixture.run(['--help'],{PATH:''},binary);expect(help.status).toBe(0);expect(help.stdout).toContain('doctor');expect(help.stderr).toBe(''); } expect(readdirSync(fixture.cwd)).toEqual([]); @@ -98,7 +119,7 @@ class CliTests { const repeat=program.run(['platform','plan','--file',configuration,'--json']);expect(repeat.status).toBe(0);expect(repeat.stdout).toBe(result.stdout); const dockerOnly=join(program.root,'docker-only');mkdirSync(dockerOnly);let docker:string|null=null;for(const directory of (process.env.PATH??'').split(':')){const path=join(directory,'docker');if(existsSync(path)){docker=path;break;}}expect(docker).not.toBeNull();symlinkSync(docker!,join(dockerOnly,'docker'));const standalone=program.run(['platform','plan','--file',configuration,'--json'],{PATH:dockerOnly});expect(standalone.status).toBe(0);expect(standalone.stdout).toBe(result.stdout); expect(readdirSync(fixture.installation)).toEqual(['.cordis']);expect(existsSync(join(fixture.installation,'.cordis/credentials'))).toBe(false);expect(existsSync(join(fixture.root,'SCRIPT_CANARY'))).toBe(false);expect(this.snapshot()).toBe(before); - const human=program.run(['platform','plan','--file',configuration]);expect(human.status).toBe(0);expect(human.stdout).toContain('Future effects only');expect(human.stdout).toContain('Volume data -> /data'); + const human=program.run(['platform','plan','--file',configuration]);expect(human.status).toBe(0);expect(human.stdout).toContain('Future effects only');expect(human.stdout).toContain('Volume mounts');expect(human.stdout).toContain('application | data | /data | Read/write'); const doctor=program.run(['doctor','--json','--installation',fixture.installation,'--port',String(plan.configuration.origin.split(':').pop())]);expect(doctor.status).toBe(0); writeFileSync(join(fixture.bundle,'archives/plugin.tgz'),'tampered');const blocked=program.run(['platform','plan','--file',configuration,'--json']);expect(blocked.status).toBe(3);const rejected=JSON.parse(blocked.stdout) as CliEnvelope;expect(rejected.result).toBeNull();expect(rejected.references).toEqual([]);expect(readdirSync(join(fixture.installation,'.cordis/plans'))).toEqual([plan.id+'.json']); }finally{fixture.close();program.close();} @@ -251,3 +272,152 @@ test('smoke: provider constructors and failed disposal cannot report successful test('smoke: prepared-provider metadata scope ownership and closure are checked before activation',compositionSuite.metadataFailures.bind(compositionSuite)); test('smoke: installed commands validate arguments before contacting worker',suite.installedArguments.bind(suite)); + +class UiOutputProgramTests { + human():void{const fixture=new CliProgramFixture();try{const result=fixture.run(['doctor','--installation',join(fixture.root,'new')],{PATH:''});expect(result.status).toBe(3);expect(result.stdout).toContain('Diagnostic checks');expect(result.stdout).toContain('Check | Result | Code | Detail');expect(result.stderr).toContain('PREREQUISITES_UNMET');expect(result.stdout+result.stderr).not.toContain('\u001b');}finally{fixture.close();}} +} +const uiOutput=new UiOutputProgramTests();test('smoke: built CLI renders structured diagnostic models through reusable terminal providers',uiOutput.human.bind(uiOutput)); + +class ExtensiblePlanProgramTests extends CliTests { + private listeners():string{const rows:string[]=[];for(const path of ['/proc/net/tcp','/proc/net/tcp6'])for(const line of readFileSync(path,'utf8').trim().split('\n').slice(1)){const fields=line.trim().split(/\s+/);if(fields[3]==='0A')rows.push(fields[1]!);}return rows.sort().join('\n');} + async plan():Promise{const {ServiceReleaseFixture}=await import('@treeseed-cordis/deployment/testing'),{ServiceSchemas}=await import('@treeseed-cordis/sdk'),fixture=await new ServiceReleaseFixture().services(),program=new CliProgramFixture();try{const port=await this.port();fixture.configuration.origin='https://localhost:'+port;fixture.release.composition.services[0]!.definition.ports[0]!.publication!.port=port;fixture.recipe.services['instance-0']!.ports![0]!.published=port;fixture.refreshService();const path=join(program.cwd,'service-config.json');writeFileSync(path,JSON.stringify(fixture.configuration));const before=this.snapshot(),listeners=this.listeners(),result=program.run(['platform','plan','--file',path,'--json']);expect(result.status).toBe(0);expect(result.stderr).toBe('');const plan=ServiceSchemas.plan.parse(JSON.parse(result.stdout).result);expect(plan.formatVersion).toBe(3);expect(plan.composition.services).toHaveLength(5);expect(plan.changes).toHaveLength(5);expect(plan.blockers).toEqual([]);const restart=program.run(['platform','apply','--installation',fixture.installation,'--plan',plan.id,'--digest',plan.digest,'--idempotency-key','not-an-additive-restart','--restart','instance-0','--json']);expect(restart.status).toBe(3);expect(JSON.parse(restart.stdout).blockers[0].code).toBe('RESTART_SCOPE_NOT_QUALIFIED');expect(existsSync(join(fixture.installation,'.cordis/launch'))).toBe(false);const saved=join(fixture.installation,'.cordis/plans',plan.id+'.json');expect(ServiceSchemas.plan.parse(JSON.parse(readFileSync(saved,'utf8')))).toEqual(plan);expect(statSync(saved).mode&0o777).toBe(0o600);const again=program.run(['platform','plan','--file',path,'--json']);expect(again.status).toBe(0);expect(again.stdout).toBe(result.stdout);const human=program.run(['platform','plan','--file',path]);expect(human.status).toBe(0);expect(human.stdout).toContain('Services\nService | Image');expect(human.stdout).toContain('instance-4');expect(human.stdout).toContain('Future effects only');const tools=join(program.root,'docker-only');mkdirSync(tools);let docker:string|null=null;for(const directory of(process.env.PATH??'').split(':'))if(existsSync(join(directory,'docker'))){docker=join(directory,'docker');break;}expect(docker).not.toBeNull();symlinkSync(docker!,join(tools,'docker'));const standalone=program.run(['platform','plan','--file',path,'--json'],{PATH:tools});expect(standalone.status).toBe(0);expect(standalone.stdout).toBe(result.stdout);expect(this.snapshot()).toBe(before);expect(this.listeners()).toBe(listeners);expect(existsSync(join(fixture.installation,'.cordis/credentials'))).toBe(false);expect(existsSync(join(fixture.root,'SCRIPT_CANARY'))).toBe(false);writeFileSync(join(fixture.bundle,'archives/plugin.tgz'),'tampered');const blocked=program.run(['platform','plan','--file',path,'--json']);expect(blocked.status).toBe(3);const envelope=JSON.parse(blocked.stdout);expect(envelope.result).toBeNull();expect(envelope.references).toEqual([]);expect(readdirSync(join(fixture.installation,'.cordis/plans'))).toEqual([plan.id+'.json']);}finally{fixture.close();program.close();}} +} +const extensiblePlan=new ExtensiblePlanProgramTests();test('smoke: standalone CLI plans genuine five-instance format3 bundle deterministically without runtime effects',extensiblePlan.plan.bind(extensiblePlan),60000); + + +class InstalledProgramTests { + private worker: { pid: number; dev: number; ino: number } | null = null; + async installed(): Promise { + const fixture = new ServiceRuntimeFixture(), program = new CliProgramFixture(); + try { + await fixture.running(); const output = join(fixture.root, 'worker-build'); mkdirSync(output, { mode: 0o700 }); + const descriptor = ServiceWorkerBuild.produce(output); copyFileSync(join(output, descriptor.path), join(fixture.bundle, 'worker')); + fixture.release.composition.worker = { ...descriptor, path: 'worker' }; fixture.refreshService(); + const input = join(fixture.root, 'configuration.json'); writeFileSync(input, JSON.stringify(fixture.configuration)); + const planResult = this.json(program, ['platform', 'plan', '--file', input, '--json']), plan = ServiceSchemas.plan.parse(planResult.result); + const docker = spawnSync('which', ['docker'], { encoding: 'utf8' }); if (docker.status !== 0 || !docker.stdout.trim().startsWith('/')) throw new Error('Docker prerequisite missing'); + const path = join(fixture.root, 'docker-only'); mkdirSync(path, { mode: 0o700 }); symlinkSync(docker.stdout.trim(), join(path, 'docker')); + const environment = { PATH: path }, apply = ['platform', 'apply', '--installation', fixture.installation, '--plan', plan.id, '--digest', plan.digest, '--idempotency-key', 'compiled-format3-program', '--json']; + const first = PlatformSchemas.apply.parse(this.json(program, apply, environment).result), owner = JSON.parse(readFileSync(join(fixture.installation, '.cordis/writer.lock/owner.json'), 'utf8')) as { pid: number }, executable = statSync(join(fixture.installation, '.cordis/worker')), running = statSync('/proc/' + owner.pid + '/exe'); + if (running.dev !== executable.dev || running.ino !== executable.ino) throw new Error('Wrong worker process'); this.worker = { pid: owner.pid, dev: running.dev, ino: running.ino }; + expect(PlatformSchemas.apply.parse(this.json(program, apply, environment).result).id).toBe(first.id); + const applicationArgs = ['platform', 'application', '--installation', fixture.installation, '--id', first.id, '--json'], deadline = Date.now() + 120000; + let application = ServiceSchemas.applicationRecord.parse(this.json(program, applicationArgs, environment).result); + while (!['completed', 'failed', 'cancelled'].includes(application.phase) && Date.now() < deadline) { await new Promise(InstalledProgramTests.delay); application = ServiceSchemas.applicationRecord.parse(this.json(program, applicationArgs, environment).result); } + expect(application.phase).toBe('completed'); expect(application.result).toBe('ready'); + const statusArgs = ['platform', 'status', '--installation', fixture.installation, '--json'], status = ServiceSchemas.status.parse(this.json(program, statusArgs, environment).result); + expect(status.ready).toBe(true); expect(status.services.length).toBe(5); expect(status.activeComposition).toBe(plan.compositionGeneration); + const human = program.run(['platform', 'status', '--installation', fixture.installation], environment, program.symlink); expect(human.status).toBe(0); expect(human.stderr).toBe(''); expect(human.stdout).toContain('Installed services'); for (const service of status.services) expect(human.stdout).toContain(service.serviceId); + rmSync(fixture.bundle, { recursive: true }); expect(PlatformSchemas.apply.parse(this.json(program, apply, environment).result).id).toBe(first.id); expect(ServiceSchemas.status.parse(this.json(program, statusArgs, environment).result).ready).toBe(true); + this.signal('SIGTERM'); const closeDeadline = Date.now() + 15000; while (existsSync(join(fixture.installation, '.cordis/writer.lock')) && Date.now() < closeDeadline) await new Promise(InstalledProgramTests.delay); + expect(existsSync(join(fixture.installation, '.cordis/writer.lock'))).toBe(false); const refused = program.run(apply, environment, program.symlink); expect(refused.status).toBe(3); expect(ServiceSchemas.envelope.parse(JSON.parse(refused.stdout)).success).toBe(false); expect(existsSync(join(fixture.installation, '.cordis/writer.lock'))).toBe(false); + } finally { + if (!this.worker) { try { const owner = JSON.parse(readFileSync(join(fixture.installation, '.cordis/launch/child.json'), 'utf8')) as { pid: number }, file = statSync(join(fixture.installation, '.cordis/worker')), observed = statSync('/proc/' + owner.pid + '/exe'); if (observed.dev === file.dev && observed.ino === file.ino) this.worker = { pid: owner.pid, dev: observed.dev, ino: observed.ino }; } catch { } } + this.signal('SIGKILL'); fixture.close(); program.close(); + } + } + private json(program: CliProgramFixture, args: string[], environment: NodeJS.ProcessEnv = {}): ReturnType { const result = program.run(args, environment, program.symlink); if (result.status !== 0) throw new Error('Compiled installed command failed: ' + result.stdout + result.stderr); expect(result.stderr).toBe(''); return ServiceSchemas.envelope.parse(JSON.parse(result.stdout)); } + private signal(signal: NodeJS.Signals): void { if (!this.worker) return; try { const current = statSync('/proc/' + this.worker.pid + '/exe'); if (current.dev === this.worker.dev && current.ino === this.worker.ino) process.kill(this.worker.pid, signal); } catch { } } + private static delay(done: (value: void) => void): void { setTimeout(done, 100); } +} +const installedPrograms = new InstalledProgramTests(); +test('smoke: standalone CLI applies and observes five format3 services through its default durable host', installedPrograms.installed.bind(installedPrograms), 240000); + +test('smoke: built plugin commands validate arguments with safe SDK JSON envelopes and do not create missing installations', suite.pluginArguments.bind(suite),30000); + +class InstalledPluginCliTests { + private worker: { pid: number; dev: number; ino: number } | null = null; + private static delay(done: (value: void) => void): void { setTimeout(done, 50); } + private static hash(bytes: Uint8Array): string { return createHash('sha256').update(bytes).digest('hex'); } + private request(program: CliProgramFixture, args: string[], expected?: number): ReturnType { + const result=program.run(['plugin',...args,'--json']); + if(result.status===null)throw new Error('Built CLI terminated without an exit status'); + if(expected!==undefined&&result.status!==expected){const envelope=PluginManagementSchemas.envelope.parse(JSON.parse(result.stdout));const codes:string[]=[];for(const blocker of envelope.blockers)codes.push(blocker.code);throw new Error('CLI_PLUGIN_READBACK:'+args[0]+':'+result.status+':'+envelope.problem?.code+':'+codes.join(','));} + if(expected===undefined)expect([0,3]).toContain(result.status);else expect(result.status).toBe(expected); + expect(result.stderr).toBe('');expect(result.stdout).not.toContain('NEVER_INHERIT');return PluginManagementSchemas.envelope.parse(JSON.parse(result.stdout)); + } + private async settled(program: CliProgramFixture, installation: string, input: PluginInstallResult): Promise { + let result=input;const deadline=Date.now()+150000; + while(result.state==='pending'&&Date.now() { + const result=new Map();const all=store.resources(); + for(const receipt of all)for(const binding of store.current()!.resources)if(receipt.resourceId===binding.resourceId){const prior=result.get(receipt.resourceId);if(!prior||prior.references.length, files: Map): void { + const current=this.receipts(store); + for(const [id,receipt]of before){const next=current.get(id);expect(next).toBeDefined();expect(next!.actualId).toBe(receipt.actualId);expect(next!.creatingGeneration).toBe(receipt.creatingGeneration);expect(next!.definitionDigest).toBe(receipt.definitionDigest);expect(next!.contentDigest).toBe(receipt.contentDigest);expect(next!.path).toBe(receipt.path);} + for(const [path,digest]of files)expect(InstalledPluginCliTests.hash(readFileSync(join(store.path,path)))).toBe(digest); + } + private async direct(store: ServicePlanStore, id: string): Promise { + for(const receipt of this.receipts(store).values())if(receipt.kind==='container'&&receipt.serviceId===id&&receipt.actualId){ + const inspected=spawnSync('docker',['container','inspect','--format','{{json .NetworkSettings.Networks}}',receipt.actualId],{encoding:'utf8'});expect(inspected.status).toBe(0);const networks=JSON.parse(inspected.stdout) as Record;let address:string|undefined;for(const network of Object.values(networks))address=network.IPAddress;expect(address).toBeDefined(); + const response=await fetch('http://'+address+':8080/'),body=await response.json() as {serviceId:string;passwordPresent:boolean;volumeMarker:string};expect(response.ok).toBe(true);expect(body.serviceId).toBe(id);expect(body.passwordPresent).toBe(true);expect(body.volumeMarker).toBe(id);return; + } + throw new Error('Installed CLI fixture endpoint missing'); + } + private identify(installation: string): void { + const child=JSON.parse(readFileSync(join(installation,'.cordis/launch/child.json'),'utf8')),file=statSync(join(installation,'.cordis/worker')),running=statSync('/proc/'+child.pid+'/exe'); + expect(file.dev).toBe(running.dev);expect(file.ino).toBe(running.ino);expect(file.uid).toBe(process.getuid!());this.worker={pid:child.pid,dev:running.dev,ino:running.ino}; + } + private signal(signal: NodeJS.Signals): void {if(!this.worker)return;try{const current=statSync('/proc/'+this.worker.pid+'/exe');if(current.dev===this.worker.dev&¤t.ino===this.worker.ino)process.kill(this.worker.pid,signal);}catch{}} + async git():Promise{await this.program('git');} + async gitBuild():Promise{await this.program('build');} + async program(source:'npm'|'git'|'build'='npm',registeredOnly=false): Promise { + const fixture=new PluginInstallationFixture(),program=new CliProgramFixture(); + try { + await fixture.prepare();if(source==='npm')await fixture.startRegistry();else await fixture.startGit(source==='build'); + const file=join(program.cwd,'plugins.json');writeFileSync(file,JSON.stringify(fixture.configuration));const planned=program.run(['platform','plan','--file',file,'--json']);expect(planned.status).toBe(0);expect(planned.stderr).toBe('');expect(ServiceSchemas.plan.parse(JSON.parse(planned.stdout).result).composition.services).toHaveLength(4); + const tools=join(program.root,'managed-only');mkdirSync(tools);let docker:string|undefined;for(const directory of(process.env.PATH??'').split(':'))if(existsSync(join(directory,'docker'))){docker=join(directory,'docker');break;}expect(docker).toBeDefined();symlinkSync(docker!,join(tools,'docker')); + const originalPath=process.env.PATH;process.env.PATH=tools; + try { + const args=['install',fixture.source(),'--installation',fixture.installation,'--target','deployment','--service','cli-addon-one','--idempotency-key','cli-first'],firstEnvelope=this.request(program,args),first=await this.settled(program,fixture.installation,PluginManagementSchemas.result.parse(firstEnvelope.result)); + this.identify(fixture.installation);expect(first.state).toBe('active');expect(first.acknowledgements.length).toBeGreaterThan(0);expect(first.planId).not.toBeNull();expect(first.applicationId).not.toBeNull(); + const store=new ServicePlanStore(fixture.installation),before=this.receipts(store),files=new Map();for(const receipt of before.values())if(receipt.path&&existsSync(join(store.path,receipt.path)))files.set(receipt.path,InstalledPluginCliTests.hash(readFileSync(join(store.path,receipt.path)))); + await this.direct(store,'cli-addon-one'); + const human=program.run(['plugin','inspect','cli-first','--installation',fixture.installation]);expect(human.status).toBe(0);expect(human.stderr).toBe('');expect(human.stdout).toContain('active');expect(human.stdout).toContain('Accepted references');expect(human.stdout).toContain('cli-first'); + const already=await this.settled(program,fixture.installation,PluginManagementSchemas.result.parse(this.request(program,[...args.slice(0,-1),'cli-already']).result));expect(already.state).toBe('already-active');expect(already.applicationId).toBe(first.applicationId); + let latest='cli-second'; + if(registeredOnly){await fixture.stopRegistry(); + const selectedPlan=store.read(first.planId!,first.planId!.slice(5));let provider:string|undefined;for(const service of selectedPlan.composition.services)if(service.serviceId==='cli-addon-one')provider=service.provider.providerId;expect(provider).toBeDefined(); + for(const id of ['cli-addon-two','cli-addon-three']){const key='cli-registered-'+id,args=['select','container.service',provider!,'--installation',fixture.installation,'--target','deployment','--service',id,'--idempotency-key',key],selection=await this.settled(program,fixture.installation,PluginManagementSchemas.result.parse(this.request(program,args).result));expect(selection.state).toBe('active');expect(selection.activeGeneration).not.toBeNull();this.same(store,before,files);await this.direct(store,id);expect(PluginManagementSchemas.result.parse(this.request(program,args,0).result)).toEqual(selection);latest=key;} + }else{ + if(source==='npm'){const applications=store.records().length,unsafeArgs=['install',fixture.source('2.0.0'),'--installation',fixture.installation,'--target','deployment','--service','cli-addon-one','--idempotency-key','cli-unsafe'],unsafe=await this.settled(program,fixture.installation,PluginManagementSchemas.result.parse(this.request(program,unsafeArgs).result)); + expect(unsafe.state).toBe('prepared');expect(unsafe.nextActions).toContain('review-migration');expect(unsafe.applicationId).toBeNull();expect(store.records().length).toBe(applications);expect(PluginManagementSchemas.result.parse(this.request(program,unsafeArgs,3).result)).toEqual(unsafe);this.same(store,before,files);} + const secondArgs=['install',fixture.source(),'--installation',fixture.installation,'--target','deployment','--service','cli-addon-two','--idempotency-key','cli-second'],second=await this.settled(program,fixture.installation,PluginManagementSchemas.result.parse(this.request(program,secondArgs).result));expect(second.state).toBe('active');this.same(store,before,files);await this.direct(store,'cli-addon-two'); + expect(this.receipts(store).size).toBeGreaterThan(before.size);const historical=PluginManagementSchemas.result.parse(this.request(program,['inspect','cli-first','--installation',fixture.installation],0).result);expect(historical.activeGeneration).toBeNull();expect(historical.acknowledgements).toEqual([]); + await fixture.stopRegistry();expect(PluginManagementSchemas.result.parse(this.request(program,secondArgs,0).result)).toEqual(second); + if(source==='npm'){ + const selectedPlan=store.read(second.planId!,second.planId!.slice(5));let provider:string|undefined;for(const service of selectedPlan.composition.services)if(service.serviceId==='cli-addon-two')provider=service.provider.providerId;expect(provider).toBeDefined(); + for(const id of ['cli-addon-three']){const key='cli-registered-'+id,args=['select','container.service',provider!,'--installation',fixture.installation,'--target','deployment','--service',id,'--idempotency-key',key],selection=await this.settled(program,fixture.installation,PluginManagementSchemas.result.parse(this.request(program,args).result));if(source==='npm'){expect(selection.state).toBe('blocked');expect(selection.blockers[0]!.code).toBe('AMBIGUOUS_REGISTERED_PROVIDER');expect(selection.applicationId).toBeNull();this.same(store,before,files);break;}expect(selection.state).toBe('active');expect(selection.activeGeneration).not.toBeNull();this.same(store,before,files);await this.direct(store,id);expect(PluginManagementSchemas.result.parse(this.request(program,args,0).result)).toEqual(selection);latest=key;} + } + } + const listed=this.request(program,['list','--installation',fixture.installation],0);expect(Array.isArray(listed.result)).toBe(true);expect((listed.result as PluginInstallResult[]).length).toBe(registeredOnly?4:source==='npm'?5:3); + + expect(existsSync(join(fixture.root,'MUST_NOT_RUN'))).toBe(false);this.signal('SIGTERM');const deadline=Date.now()+15000;while(existsSync(join(fixture.installation,'.cordis/writer.lock'))&&Date.now()void):void{setTimeout(done,50);} + private run(program:CliProgramFixture,args:string[],code?:number):ReturnType{const output=program.run(['plugin',...args,'--json']);expect(output.stderr).toBe('');if(code!==undefined)expect(output.status).toBe(code);else expect([0,3]).toContain(output.status!);expect(output.stdout).not.toContain('NEVER_INHERIT');return PluginManagementSchemas.envelope.parse(JSON.parse(output.stdout));} + private async settled(program:CliProgramFixture,installation:string,input:PluginInstallResult):Promise{let result=input;const until=Date.now()+180000;while(result.state==='pending'&&Date.now(){const{LiveProbeFixture}=await import('@treeseed-cordis/deployment/testing/live'),fixture=await new LiveProbeFixture().prepareLive(),program=new CliProgramFixture(),path=process.env.PATH,token=process.env.NPM_TOKEN;try{await fixture.startRegistry();const configuration=join(program.cwd,'live.json');writeFileSync(configuration,JSON.stringify(fixture.configuration));const planned=program.run(['platform','plan','--file',configuration,'--json']);expect(planned.status).toBe(0);const plan=ServiceSchemas.plan.parse(JSON.parse(planned.stdout).result),tools=join(program.root,'docker-only');mkdirSync(tools);let docker:string|undefined;for(const dir of(path??'').split(':'))if(existsSync(join(dir,'docker'))){docker=join(dir,'docker');break;}expect(docker).toBeDefined();symlinkSync(docker!,join(tools,'docker'));process.env.PATH=tools;process.env.NPM_TOKEN='NEVER_INHERIT';const{ComposeDeploymentHost,ServiceWorkerOwnerClient}=await import('@treeseed-cordis/deployment'),host=new ComposeDeploymentHost(),owner=new ServiceWorkerOwnerClient({installationDirectory:fixture.installation}),accepted=await host.apply(plan.id,plan.digest,{installationDirectory:fixture.installation,idempotencyKey:'cli-live-base'});let application=await owner.application(accepted.id);const until=Date.now()+180000;while(!['completed','failed'].includes(application.phase)&&Date.now()(),files=new Map();for(const binding of before.resources){const receipt=store.resources().find(LivePluginCliTests.digest.bind(null,binding.receiptDigest))!;physical.set(receipt.resourceId,LivePluginCliTests.physical(receipt));if(receipt.path&&existsSync(join(fixture.installation,receipt.path)))files.set(receipt.path,createHash('sha256').update(readFileSync(join(fixture.installation,receipt.path))).digest('hex'));}const child=JSON.parse(readFileSync(join(fixture.installation,'.cordis/launch/child.json'),'utf8')),provider=plan.composition.services[2]!.readiness,config=join(program.cwd,'probe.json');writeFileSync(config,JSON.stringify(provider.configuration));const args=['install',fixture.source(),'--installation',fixture.installation,'--target','deployment','--service','instance-2','--provider','fixture-live.next','--configuration',config,'--idempotency-key','cli-live-install'],live=await this.settled(program,fixture.installation,PluginManagementSchemas.result.parse(this.run(program,args).result));expect(live.state).toBe('active');expect(live.applicationId).not.toBeNull();expect(live.acknowledgements.length).toBeGreaterThan(0);for(const binding of store.current()!.resources){const receipt=store.resources().find(LivePluginCliTests.digest.bind(null,binding.receiptDigest))!;expect(LivePluginCliTests.physical(receipt)).toBe(physical.get(receipt.resourceId)!);}for(const[file,hash]of files)expect(createHash('sha256').update(readFileSync(join(fixture.installation,file))).digest('hex')).toBe(hash);expect((await owner.status()).services.find(LivePluginCliTests.next)).toBeDefined();renameSync(fixture.bundle,join(fixture.root,'source-bundle-offline'));await fixture.stopRegistry();expect(PluginManagementSchemas.result.parse(this.run(program,args,0).result)).toEqual(live);const select=['select','probe.service','fixture-live.next','--installation',fixture.installation,'--target','deployment','--service','instance-2','--configuration',config,'--idempotency-key','cli-live-current'],current=await this.settled(program,fixture.installation,PluginManagementSchemas.result.parse(this.run(program,select).result));expect(current.state).toBe('already-active');const count=store.records().length;select[2]='fixture-live.old';select[select.length-1]='cli-unsafe-reverse';const unsafe=await this.settled(program,fixture.installation,PluginManagementSchemas.result.parse(this.run(program,select).result));expect(unsafe.state).toBe('prepared');expect(unsafe.nextActions).toContain('review-restart');expect(unsafe.applicationId).toBeNull();expect(store.records().length).toBe(count);expect((await owner.status()).services.find(LivePluginCliTests.next)).toBeDefined();expect(JSON.parse(readFileSync(join(fixture.installation,'.cordis/launch/child.json'),'utf8')).pid).toBe(child.pid);expect(fixture.authorization).toBe(false);}finally{process.env.PATH=path;if(token===undefined)delete process.env.NPM_TOKEN;else process.env.NPM_TOKEN=token;await fixture.dispose();program.close();}} +} +const livePlugins=new LivePluginCliTests(); +test('smoke: built CLI installs and selects a qualified live probe with offline exact replay and unsafe reverse refusal',livePlugins.program.bind(livePlugins),420000); diff --git a/vendor/deployment.tgz b/vendor/deployment.tgz index 678cb15..e2e080a 100644 Binary files a/vendor/deployment.tgz and b/vendor/deployment.tgz differ diff --git a/vendor/sdk.tgz b/vendor/sdk.tgz index a5cf0af..d3a34a6 100644 Binary files a/vendor/sdk.tgz and b/vendor/sdk.tgz differ diff --git a/vendor/ui.tgz b/vendor/ui.tgz new file mode 100644 index 0000000..da5e139 Binary files /dev/null and b/vendor/ui.tgz differ