Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.
TypeScript agentic-aiaiai-agentsai-videocompilerdslffmpeggenerative-aillmmarkup-languagemonorepoplugin-systemprogramming-languagetext-to-videotypescriptvideovideo-automationvideo-clonevideo-editingvideo-generation
refactor: separate workspace from runtime hosts
kashorinfdc17b41948b
diff --git a/.agents/skills/narratage/SKILL.md b/.agents/skills/narratage/SKILL.mdindex a9e112a5..c866b79e 100644--- a/.agents/skills/narratage/SKILL.md+++ b/.agents/skills/narratage/SKILL.md@@ -42,7 +42,7 @@ Run `packages sync` after import or Runtime package selections change. Use `chec`doctor` for deployment setup or diagnosis; do not impose either as ceremony before every Build.Treat `--follow` as an observer: stopping it does not stop the durable Build. Use `runtime down`-to stop only the Worker; use `services down` separately when external programs should also stop.+to stop only the Worker; use `programs down` separately when external programs should also stop.Neither command cancels Builds or remote Provider work.Every `build` invocation receives a fresh automatic Build id. Never try to reclaim a prior Build bydiff --git a/.agents/skills/narratage/references/environment.md b/.agents/skills/narratage/references/environment.mdindex ad2a05a7..6b51405f 100644--- a/.agents/skills/narratage/references/environment.md+++ b/.agents/skills/narratage/references/environment.md@@ -26,7 +26,7 @@ pnpm checkpnpm test```-For managed local services:+For managed local programs:```textuv python install 3.13@@ -39,8 +39,8 @@ node --run narratage -- runtime upnode --run narratage -- runtime status```-Use `runtime up` for normal Build preparation: it owns the detached durable Worker and the external-programs declared by the Runtime Profile. `services up/status/down` is only the narrow external-+Use `runtime up` for normal Build preparation: it owns the detached durable Worker and prepares the external+programs declared by the Runtime Profile. `programs up/status/down` is only the narrow external-program view and does not manage the Worker. See `references/runtime.md` for the Build lifecycle.After intentionally installing, removing or changing selected packages, refresh both explicitdiff --git a/.agents/skills/narratage/references/runtime.md b/.agents/skills/narratage/references/runtime.mdindex 626c02ed..590e7f8b 100644--- a/.agents/skills/narratage/references/runtime.md+++ b/.agents/skills/narratage/references/runtime.md@@ -20,17 +20,17 @@ node --run narratage -- get <build-id> \Use `packages sync` only after package selection changes. Use `check` during authoring and `doctor`or `runtime status` when diagnosing the deployment. `build` already ensures the detached Worker-and demanded managed services are available.+and demanded Managed Programs are available.Use `runtime logs` to diagnose the Worker. Use `runtime down` to stop it from claiming more leases.-External programs are intentionally independent; stop them only with `services down`. Durable+External programs are intentionally independent; stop them only with `programs down`. DurableBuilds remain archived and neither command cancels remote Provider work.## Preserve durable semantics- `runtime up` starts or reuses the detached Worker plus declared external programs. A direct`build` also ensures the execution domain is running before submission.-- `services up/status/down` manages external programs only. Do not use it as the normal Build+- `programs up/status/down` manages external programs only. Do not use it as the normal Buildbootstrap because it does not own the Worker lifecycle.- A Build continues after durable submission. `--follow` only observes progress; interrupting theterminal does not stop the Build.@@ -45,9 +45,9 @@ Builds remain archived and neither command cancels remote Provider work.## Keep project and package boundaries distinctPrefer production projects outside the Narratage checkout. Relative Author Sources and assets stay-inside the Source Workspace, which defaults to the directory containing the entry `.svrun`.+inside the independently resolved Source Workspace.-- `--root` deliberately widens the Source Workspace boundary.+- `--workspace` explicitly selects the Source Workspace boundary.- `--package-root` only changes where the Host locates installed packages whose bytes are verifiedby the package lock. It does not widen Source access.- Do not symlink an external project into the repository to bypass containment; canonical-pathdiff --git a/.gitignore b/.gitignoreindex 7c72ba6d..9c24db91 100644--- a/.gitignore+++ b/.gitignore@@ -41,6 +41,7 @@ docs/.vitepress/cache/docs/.vitepress/dist/*.tsbuildinfo.svml-cache/+.narratage/examples/**/assets/examples/**/build/examples/**/output/diff --git a/README.md b/README.mdindex d4ddddb9..f6791d39 100644--- a/README.md+++ b/README.md@@ -162,7 +162,7 @@ The Core is small and domain-neutral: it knows nothing about video. Installing a| **Compiler** | Source parsing, imports and graph elaboration | `host`, `markup`, `svs`, `elaborator` || **Infrastructure** | Media processing, spatial layout, fonts and text | `media-pipeline`, `spatial`, `fonts-open` || **Video authoring** | Script, generation, speech, tracks, film and rendering | `script`, `seedance`, `caption`, `film` |-| **Providers** | Adapters for external models, programs and services | `provider-kie`, `provider-whisperx-local` |+| **Providers** | Adapters for external models, APIs and Managed Programs | `provider-kie`, `provider-whisperx-local` || **Runtime** | Scheduling, storage, credentials and execution | `runtime`, `store-sqlite`, `local` || **Applications** | User-facing ways to author and operate Narratage | `cli`, `svml-playground` |diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.tsindex 0d89fa21..7a2bcd6a 100644--- a/docs/.vitepress/config.ts+++ b/docs/.vitepress/config.ts@@ -156,9 +156,8 @@ const enTheme = {{ text: "Package Architecture", link: "/guide/packages" },{ text: "Adding an Author Package", link: "/guide/author-packages" },{ text: "Adding a Provider", link: "/guide/providers" },- { text: "Runtime Profile", link: "/guide/runtime-profile" },+ { text: "Runtime", link: "/guide/runtime" },{ text: "Caption Playground", link: "/guide/caption-playground" },- { text: "Runtime & External Services", link: "/guide/services" },{ text: "Testing", link: "/guide/testing" },{ text: "Conventions", link: "/guide/conventions" },],@@ -201,9 +200,8 @@ const zhTheme = {{ text: "包架构", link: "/zh/guide/packages" },{ text: "添加 Author 包", link: "/zh/guide/author-packages" },{ text: "添加 Provider", link: "/zh/guide/providers" },- { text: "Runtime Profile", link: "/zh/guide/runtime-profile" },+ { text: "Runtime", link: "/zh/guide/runtime" },{ text: "字幕 Playground", link: "/zh/guide/caption-playground" },- { text: "Runtime 与外部服务", link: "/zh/guide/services" },{ text: "测试", link: "/zh/guide/testing" },{ text: "代码规范", link: "/zh/guide/conventions" },],diff --git a/docs/guide/develop.md b/docs/guide/develop.mdindex 1bebf755..0c547418 100644--- a/docs/guide/develop.md+++ b/docs/guide/develop.md@@ -11,7 +11,7 @@ description: Getting started with Narratage development.|---|---|---|| Node.js | 22+ | everything || pnpm | 10.33.x | workspace management; selected by the root `packageManager` field |-| Python | 3.10–3.13 | WhisperX and OpenCV [local services](./services.md) |+| Python | 3.10–3.13 | local WhisperX and OpenCV Managed Programs || uv | latest | Python environment management || ffmpeg / ffprobe | recent stable | media processing || Chrome / Chromium | managed by HyperFrames | local HyperFrames rendering |@@ -55,8 +55,7 @@ narratage/| [Package architecture](./packages.md) | The five layers, dependency rules, package anatomy, facets || [Adding an author package](./author-packages.md) | Step-by-step: new component, Surface, activation || [Adding a Provider](./providers.md) | Step-by-step: new Endpoint adapter |-| [Runtime Profile](./runtime-profile.md) | Declarative CLI configuration, embedding boundary, diagnostics, Build archive |+| [Runtime](./runtime.md) | Profile, Workspace, execution and lifecycle boundaries || [Caption Playground](./caption-playground.md) | Edit real Caption SVML/SVS with live feedback |-| [Local services](./services.md) | WhisperX and OpenCV setup || [Testing](./testing.md) | Test runner, patterns, examples, boundary tests || [Conventions](./conventions.md) | Naming, module boundaries, wire data, TypeScript config |diff --git a/docs/guide/packages.md b/docs/guide/packages.mdindex 5556a5b8..0ba4ee67 100644--- a/docs/guide/packages.md+++ b/docs/guide/packages.md@@ -269,10 +269,10 @@ Frontend implementations are not privileged fields in the physical package formathe ordinary `svml.source-frontend@1` Host facet, exactly as Run Fragments, Markup Surfaces andRuntime Adapters advertise their own Host ABIs. Only the Source Host interprets that facet.-Runtime Profiles follow the same rule. Each `use` selects either an Endpoint Adapter ABI or a-Runtime Service Adapter ABI plus a logical name. A physical npm package advertises that logical+Runtime Profiles follow the same rule. Each `use` selects a Runtime Host, Endpoint Adapter or+Runtime Component Adapter ABI plus a logical name. A physical npm package advertises that logicaloffer; its package name is only an enrollment hint and lockfile fact. The generic CLI therefore-does not contain a Provider registry, and an Endpoint adapter and Runtime-service adapter may share+does not contain a Provider registry, and different Adapter kinds may sharea logical spelling without colliding.When a logical name and physical npm package have the conventional same root, `packages sync` candiff --git a/docs/guide/providers.md b/docs/guide/providers.mdindex 5286480f..56d88712 100644--- a/docs/guide/providers.md+++ b/docs/guide/providers.md@@ -31,7 +31,7 @@ packages or the CLI:"exports": {".": "./src/index.ts"},- "svml": { "activation": "./src/activation.ts", "service": true },+ "svml": { "activation": "./src/activation.ts" },"dependencies": {"@narratage/endpoint-kit": "workspace:*","@narratage/protocol": "workspace:*",@@ -122,17 +122,16 @@ start work. It keeps environment names as references until a matching Need is hapresence is diagnosed through the generic CredentialStore path; a Provider must not special-caseenvironment variables as a secret Store.-## 5. Declare an external service (if needed)+## 5. Declare a Managed Program when needed-If the Provider depends on an external program (a Python service, a local server), add-`"service": true` to the `svml` block in `package.json` (shown in step 2) and export a factory-from `src/service.ts`:+If the Provider depends on a warm external program, export its declaration beside the Endpoint.+There is no second manifest flag or central program registry:```typescript-// src/service.ts-import type { RuntimeExternalService } from "@narratage/local";+// src/program.ts+import type { ManagedProgram } from "@narratage/runtime-adapter";-export function createMyExternalService(): RuntimeExternalService {+export function createMyProgram(): ManagedProgram {return {id: "my-service",prepare: { command: "uv", args: ["sync", "--project", "services/my-service", "--frozen"] },@@ -152,16 +151,15 @@ const adapter = createRuntimeEndpointAdapterFacet({activate(context) {return {endpoint: createMyServiceProvider(/* parsed config */),- externalService: createMyExternalService(),+ program: createMyProgram(),};},});```-`narratage runtime up` prepares, starts and probes declared external programs before starting the-durable Worker. `build` starts only services backing capabilities declared by its selected Producer-steps. Providers that call only remote APIs omit this step entirely—leave `"service"` out of-`package.json`.+`narratage runtime up` prepares, starts and probes declared Managed Programs before starting the+durable Worker. `build` starts only Programs backing capabilities demanded by its plan. Providers+that call only remote APIs omit `program` entirely.## 6. Register and lockdiff --git a/docs/guide/runtime-profile.md b/docs/guide/runtime-profile.mddeleted file mode 100644index 928f29f6..00000000--- a/docs/guide/runtime-profile.md+++ /dev/null@@ -1,242 +0,0 @@-----title: Runtime Profile-description: Configuring where Builds execute, diagnostics and Build archive.------# Runtime Profile--The Runtime Profile declares *where* a frozen Build executes: the Scheduler and Worker, all durable-Stores, Endpoints, credentials and concurrency. It is deployment configuration, not-creative content—it never enters Author or Run graph identity.--Select it once for the project:--```bash-narratage runtime use svml.runtime.json-```--The CLI stores only a relative pointer in `.svml/runtime`. The Profile remains authoritative for-its root, both package-lock paths, Stores, Endpoints and scheduling. `runtime unset` removes the-pointer without stopping work or deleting state. `--runtime <profile>` is a one-command override.--## Declarative JSON--```json-{- "format": "svml.runtime-config@1",- "packageLock": "./svml.packages.lock",- "runtimePackageLock": "./svml.runtime-packages.lock",- "runtimeServices": [- { "use": "@narratage/local", "instance": "execution" },- { "use": "@narratage/store-sqlite", "instance": "state", "config": { "path": ".svml/runtime.sqlite" } },- { "use": "@narratage/artifact-store-fs", "instance": "artifacts", "config": { "path": ".svml/artifacts" } },- { "use": "@narratage/credential-store-keychain", "instance": "credentials.keychain", "config": { "service": "narratage" } }- ],- "services": {- "scheduler": "execution.scheduler",- "worker": "execution.worker",- "stores": {- "build": "state.builds",- "operations": "state.operations",- "dispatch": "state.dispatch",- "artifacts": "artifacts",- "credentials": ["credentials.keychain"]- }- },- "endpoints": [- {- "use": "@narratage/provider-kie",- "instance": "kie.production",- "config": {- "apiKey": { "store": "keychain", "key": "kie.api-key" },- "defaultConcurrency": 2- }- },- {- "use": "@narratage/provider-media-local",- "instance": "media.local",- "config": { "defaultConcurrency": 2 }- },- {- "use": "@narratage/provider-whisperx-local",- "instance": "whisperx.local",- "config": { "defaultConcurrency": 1 }- },- {- "use": "@narratage/provider-google-vertex",- "instance": "vertex.local",- "config": {- "projectEnv": "GOOGLE_CLOUD_PROJECT",- "credentials": { "store": "keychain", "key": "google.vertex-json" },- "defaultConcurrency": 1- }- },- {- "use": "@narratage/provider-hyperframes-local",- "instance": "hyperframes.local",- "config": { "workers": 2, "quality": "standard", "defaultConcurrency": 1 }- }- ],- "scheduling": { "maxConcurrency": 4 }-}-```--### Endpoint fields--| Field | Meaning |-|---|---|-| `use` | Adapter name, resolved from `runtimePackageLock` |-| `instance` | Unique identifier for this Endpoint instance |-| `authority` | Optional shared account/compute-pool identity; omitted instances use their own `instance` id |-| `config` | Adapter-specific non-secret configuration, CredentialRefs, concurrency and timeouts |--Credentials are addressed as `{ "store": "…", "key": "…" }`; secret bytes never enter the-Profile. More than one selected CredentialStore may coexist, and each answers only for its own-store name.--### Runtime service fields--`runtimeServices` activates installed service adapters. `services` selects every required role by-its exact instance id: Scheduler, Worker, BuildStore, OperationStore, DispatchStore,-ArtifactStore and one or more CredentialStores. No role is inferred from package-presence or filled by `@narratage/local`.--### Filesystem fields--| Field | Meaning |-|---|---|-| `root` | Project root. It bounds Source files and bases Runtime state, Artifact storage and relative lock paths. Defaults to the Profile directory. |-| `packageRoot` | Optional Host override for the `node_modules` supplying both locks. The official CLI defaults to its own installation; the direct local API defaults to `root`. |-| `packageLock` | Trusted Author/Run implementation inventory. One compilation activates its exact Source-selected subset. |-| `runtimePackageLock` | Trusted Runtime-adapter inventory. One Profile activates only its explicitly selected adapters. |--`root` and `packageRoot` are deliberately separate. An external video project can retain all data-in its own directory while loading verified executable packages from one Narratage installation.-Neither value enters Author or Run graph identity.--### Scheduling--`maxConcurrency` caps admitted Operations across all Workers sharing the DispatchStore. Each-configured Provider contributes one total Authority limit plus its own route limits for actual model-or API lanes. The Store acquires both for one task atomically; work is not copied through two queues.-Routes are Provider-local, so KIE Seedance and another Provider's Seedance never share a hidden-family counter. Capacity tickets are durable and fenced by the Build lease rather than process-local-counters.--### Trust boundary--Runtime packages currently execute as trusted local code. Narratage does not pretend that a string-allowlist can restrict Node code that shares the Host process. Arbitrary community runtime packages-must wait for a real process/Wasm isolation boundary with enforceable filesystem, network, process-and resource controls.--## Embedding API--The official video Distribution currently parses declarative Runtime Profiles as JSON. The generic-CLI assigns no meaning to `.json`; it delegates the selected document to the Distribution. A server-or application embedding Narratage may assemble the same Scheduler, Worker, Store and Endpoint-roles directly through `@narratage/local`.--## Diagnostics--### doctor--Checks the Runtime Profile without running a Build or making paid requests:--```bash-node --run narratage -- doctor-```--Validates:-- Package locks exist and are readable-- Adapter byte digests match-- Configuration keys are valid for each adapter-- Referenced credentials resolve from their selected stores-- Required executables (ffmpeg, ffprobe, chrome) are found-- Declared external services are reachable and match the selected profile--Runtime Adapter Host ABI `@1` gives each Endpoint one pure activation declaration. `doctor` evaluates-that declaration and reads credentials and prerequisites from the resulting Endpoint-package; there is no diagnostic-only credential mirror. Activation may construct handlers but may-not resolve credentials, access the network, start a process or mutate durable state. `doctor` never-constructs a Scheduler, Worker, Build Store or author package, starts a service, writes Runtime state-or submits work. It opens only the CredentialStore adapters selected by the Profile, then closes-them, and may run explicitly declared bounded read-only probes.--### Credential control is not Runtime execution--`auth status|login|logout <endpoint-instance>` constructs only that exact Endpoint declaration and-the CredentialStores selected by the Profile. It does not open SQLite, start a Worker, load author-packages or construct unrelated Providers. Logging into KIE therefore cannot be blocked by an old-Build database or an unrelated Vertex configuration.--## Runtime lifecycle--```bash-node --run narratage -- runtime up-node --run narratage -- runtime status-node --run narratage -- runtime logs-node --run narratage -- runtime down-```--`runtime up` owns the detached Worker plus declared external programs. `services` remains a narrow-expert command for those external programs only. A Build submission ensures the Runtime is up, but-the Build terminal never owns execution.--During the pre-release period SQLite execution schemas are intentionally not migrated in place.-If a development database predates the selected Store implementation, the CLI names the exact path-and asks the operator to archive that database (including its WAL companions) or select a new path.-Artifact bytes live in the independently selected ArtifactStore and are never deleted by this-refusal.--### gc (garbage collection)--```bash-node --run narratage -- gc # dry-run-node --run narratage -- gc --apply # delete unreachable Artifacts-```--Walks every retained BuildState and Operation, computes reachable Artifact digests, and reports-(or deletes) unreachable orphans.--## Build archive and inspection--Every Build archives all accepted Records and referenced Artifacts durably, independent of any-`--to` destination path.--### List Builds--```bash-node --run narratage -- builds-```--### Inspect--```bash-node --run narratage -- inspect <build-id>-```--Shows target bindings, demanded Logical Outputs, every accepted Record and Operation status.--### Retrieve Records--```bash-# By source output name-node --run narratage -- get <build-id> \- --name final.video --to output.mp4--# By Record id-node --run narratage -- get <build-id> \- --record <record-id> --to output.json--# By Logical Output id-node --run narratage -- get <build-id> \- --output <output-id>--# By Artifact digest-node --run narratage -- get <build-id> \- --artifact <sha256:...> --to file.bin-```--`--name` uses the source output alias from the Host-only Build Catalog. The Catalog is a-presentation convenience; it does not enter Core Build identity.diff --git a/docs/guide/runtime.md b/docs/guide/runtime.mdnew file mode 100644index 00000000..877179c7--- /dev/null+++ b/docs/guide/runtime.md@@ -0,0 +1,199 @@+---+title: Runtime+description: The execution boundary outside Narratage source and Core.+---++# Runtime++Narratage keeps three decisions separate:++| Owner | Decides |+|---|---|+| Workspace | Which source files and local assets one compilation may read |+| Runtime Profile | Which execution environment receives a frozen Build |+| Runtime | How that Build is queued, executed, stored and observed |++The Runtime Profile does not define the Workspace. A Profile may be reused by many projects, and a+project may submit Builds to different Profiles without changing its author source.++## Runtime boundary++Core is a domain neutral state machine. It accepts facts, derives Commands and verifies returned+Records. It does not start processes, read credentials, choose Providers or know that a Build makes+video.++A Runtime receives one already compiled Build and owns everything environmental:++* durable Build and Operation state;+* dispatch, leases and concurrency;+* Artifact and Credential storage;+* Endpoint activation and Provider calls;+* optional long lived programs;+* lifecycle, status, logs and cancellation.++The generic CLI talks to the selected Runtime through one Runtime Controller. It never assumes that+the Runtime is a local Node process. A local controller may own a detached Worker; a remote+controller may submit the same Build over HTTP.++## Runtime Profile++A Profile selects one Runtime adapter and gives that adapter closed configuration:++```json+{+ "format": "narratage.runtime-profile@1",+ "runtimePackageLock": "./svml.runtime-packages.lock",+ "runtime": {+ "use": "@narratage/local",+ "config": {+ "dataRoot": ".narratage/runtimes/local",+ "components": {+ "execution": { "use": "@narratage/local" },+ "state": {+ "use": "@narratage/store-sqlite",+ "config": { "path": "state.sqlite" }+ },+ "artifacts": {+ "use": "@narratage/artifact-store-fs",+ "config": { "path": "artifacts" }+ }+ },+ "bindings": {+ "scheduler": "execution.scheduler",+ "worker": "execution.worker",+ "stores": {+ "build": "state.builds",+ "operations": "state.operations",+ "dispatch": "state.dispatch",+ "artifacts": "artifacts",+ "credentials": []+ }+ },+ "endpoints": {+ "media": { "use": "@narratage/provider-media-local" }+ },+ "limits": { "maxOperations": 4 }+ }+ }+}+```++`components` configures replaceable Runtime pieces. One Component may expose several related role+facets. `bindings` selects the exact instance for each singleton role. `endpoints` configures+capability implementers. `limits` bounds this Runtime as a whole. Presence never implies selection.++The Profile contains no source package lock, source root or author package selection. Those belong+to the project and the compilation command. Relative Profile paths resolve from the Profile file;+relative local Runtime data paths resolve beneath `dataRoot`.++## Project state++Selecting a Profile writes one relative pointer:++```text+.narratage/+ runtime+```++A project local Runtime normally keeps its private state alongside that pointer:++```text+.narratage/+ runtime+ runtimes/+ local/+ worker/+ state.sqlite+ artifacts/+```++These paths are deployment state, not source. `check` and `plan` never create them. `runtime use`+creates only the pointer. A local Runtime creates its data directory only when it is explicitly+started or receives a Build.++## Host state++Host global state is reserved for a Managed Program that is deliberately shared across projects.+It never contains source, Build state, Artifacts or credentials.++The default location follows the operating system:++| Platform | Location |+|---|---|+| macOS | `~/Library/Application Support/Narratage` |+| Linux | `$XDG_STATE_HOME/narratage`, otherwise `~/.local/state/narratage` |+| Windows | `%LOCALAPPDATA%\\Narratage` |++`NARRATAGE_STATE_HOME` overrides it. `narratage paths` reports every effective location. A command+prints the location before its first write. A program that is externally owned and only probed does+not create Narratage host state.++## Components, bindings and endpoints++A Runtime Component is a configured package instance that supplies one or more infrastructure+facets such as Scheduler, Worker or Store. A Runtime Binding chooses an exact facet instance. This+keeps a package free to bundle cohesive implementation parts without giving package presence any+routing authority.++An Endpoint supplies one or more declared capabilities. An author package may explicitly request a+particular model capability; the Profile binds that request to configured Endpoint instances.+Provider selection is deployment configuration, never a hidden creative decision by Core.++Both Components and Endpoints are loaded only from the separately verified runtime package lock.+Installing a package adds an available implementation; it does not alter Core or activate itself.++## Managed Programs++A Managed Program is a long lived external process declared by an Endpoint, such as a warm local+WhisperX server. It is not a Runtime Component and not a queue. The Endpoint declares how to probe+it and may declare how to prepare or start it. If lifecycle ownership remains external, it declares+only a probe.++```bash+narratage programs status+narratage programs up+narratage programs down+```++Build preparation starts only Programs required by demanded capabilities. Explicit `programs up`+acts on the complete selected Profile. Runtime shutdown does not automatically stop shared Programs.++## Lifecycle++```bash+narratage runtime use svml.runtime.json+narratage runtime up+narratage runtime status+narratage runtime logs+narratage runtime down+```++These commands are controller operations. Their behavior belongs to the selected Runtime adapter.+For a local adapter, `up` owns one durable Worker domain. For a remote adapter, the same command may+only verify reachability. The generic CLI renders the result but does not manage PIDs or signals.++`build` submits a fresh Build identity and returns after durable admission unless `--follow` is+present. A running Build may be observed or cancelled. A terminal Build is never reopened; reuse of+prior material is expressed by Run Candidates, not Build identity.++## Workspace resolution++The compiler resolves its Workspace independently of Runtime content, in this order:++1. explicit `--workspace`;+2. the project containing the selected `.narratage/runtime` pointer;+3. the nearest source package lock;+4. the entry source directory.++The Runtime Profile may not widen that boundary. Runtime package installation paths are Host+implementation details and may not become source roots.++## Trust++Source packages and Runtime packages have separate locks because they run with different authority.+Compilation activates the exact source selected subset. Runtime activation is limited to the exact+adapter closure selected by the Profile. The frozen source implementation closure accompanies the+Build so the Runtime can verify what it is asked to execute.++Node Runtime packages are trusted deployment code until Narratage has a real process or Wasm+isolation boundary. A manifest or claimed digest is not a sandbox.diff --git a/docs/guide/services.md b/docs/guide/services.mddeleted file mode 100644index 36a00f6c..00000000--- a/docs/guide/services.md+++ /dev/null@@ -1,147 +0,0 @@-----title: Runtime & External Services-description: Managing the durable Worker and local programs selected by a Runtime Profile.------# Runtime & External Services--Two lifecycle scopes are deliberately separate.--## Runtime execution domain--```bash-node --run narratage -- runtime use svml.runtime.json-node --run narratage -- runtime up-node --run narratage -- runtime status-node --run narratage -- runtime logs-node --run narratage -- runtime down-```--`runtime up` starts or reuses the detached fenced Worker and also prepares/starts the external-programs declared by selected adapters. The process identity, profile digest and log path are-project-scoped. Repeating `runtime up` does not create a second Worker for the same domain.-Independent external programs are prepared concurrently. The human CLI prints each bounded phase-(`Checking`, `Preparing`, `Starting`, `Waiting`, `Ready`) so a first WhisperX model preparation or-browser installation is visible instead of looking like a frozen command. JSON output remains one-clean final document.--`runtime status` combines:--- Worker process and profile identity;-- durable queue phase counts and shared capacity reservations;-- declared external-program health.--A stopped idle Runtime is a valid observation, not a failed command. `runtime status` exits-successfully after a successful query and reports `ready: false`; it becomes an attention warning-when unfinished dispatch exists but the Worker or a required declared program is unavailable.--The Worker record binds an opaque Profile revision supplied by the selected Distribution. The-official JSON Profile implementation covers the Profile bytes plus both package locks it names;-the generic CLI neither parses that document nor assumes what belongs to a revision. Editing the-same Profile path or regenerating either lock therefore makes the official Worker process-`stale`. The next `runtime up` or `build` first checks the DispatchStore: unfinished work from the-old revision rejects the new revision without stopping the old Worker or starting external-programs. Once old work is terminal, replacement is allowed.--`runtime down` stops only the Worker. It deliberately leaves external programs alone because another-Runtime Profile may share them. Use `services down` when the programs themselves should stop.-Neither command cancels Builds or remote Provider jobs; queued Builds remain durable.--## External programs only--```bash-node --run narratage -- services up svml.runtime.json-node --run narratage -- services status svml.runtime.json-node --run narratage -- services down svml.runtime.json-```--`services` is an expert/debugging command. It never starts the Worker and never reads or mutates a-Build queue. It operates only on adapter-declared programs such as:--- the warm local WhisperX HTTP service;-- the managed OpenCV Python environment probe;-- HyperFrames browser preparation;-- local media executable compatibility probes.--Remote-only Endpoints such as KIE have no local service.--`services status` names every unavailable declared program and also treats a successful query as a-successful command. Readiness remains explicit in its structured `ready` field. `services up` and-`services down` are lifecycle requests and still fail when the requested state is not reached.--## Build relationship--```bash-node --run narratage -- build build.svrun-node --run narratage -- build build.svrun --follow-```--Before submission, `build` derives the capabilities declared by the selected Producer steps and-prepares only external programs backing those capabilities. A text-only or Estimate-only Target-therefore does not load WhisperX merely because the Profile also offers it. This selection changes-no graph edge and does not route Providers; it only avoids starting unrelated deployment programs.-Concurrent launches are serialized per Profile, so they share one Worker and one managed instance-of each demanded external service. The Build command-then stores one verified Build plus dispatch ticket. Without `--follow` it exits immediately after-submission. `--follow` observes durable state only and prints a line when the Build phase or-Operation revision/progress changes; if that Worker stops, it fails with a restart command instead-of waiting forever. Ctrl-C detaches the observer and leaves the Worker running.--`--no-services` skips automatic external-program startup for an operator who already owns those-programs, but it does not create implicit Runtime services or move execution back into the CLI.--Explicit `runtime up` and `services up` still operate the complete Profile because their subject is-the deployment, not one Build.--## Visibility--```bash-node --run narratage -- queue-node --run narratage -- queue --watch-node --run narratage -- status <build-id>-node --run narratage -- inspect <build-id>-node --run narratage -- cancel <build-id>-```--These views expose the active durable dispatch set, Worker state, lease/capacity facts, Operation-attempts, generic Endpoint progress, checkpoints and cancellation state. They do not reconstruct a-secret second graph or ask a Provider for creative-routing.--The public control unit is the Build. `cancel` atomically withdraws a queued Build that no Worker-has claimed, or closes admission and reconciles already-submitted Provider work for a running-Build. Individual Operations remain visible inside Build status but are not independently-controlled by the CLI. A terminal Build is never reopened; running the same `.svrun` submits a new-Build. Endpoint checkpoint recovery only continues the same already-paid external task after a-Worker restart.--Use `--json` for one versioned result and `--jsonl` for a watch stream. `queue --watch` emits the-first snapshot and later changes; it does not print an identical block every second while a remote-job remains in the same state.--## WhisperX--`@narratage/provider-whisperx-local` declares the warm service. Its health probe locks protocol,-package, model, device, compute type and batch size. It accepts only canonical evidence WAVs beneath-the configured input roots. WhisperX remains one-at-a-time internally; the Runtime Route resource prevents-avoidable `BUSY` responses.--For service development it may be run directly:--```bash-uv sync --project services/whisperx --frozen-uv run --project services/whisperx --frozen svml-whisperx-prepare-uv run --project services/whisperx --frozen svml-whisperx-check-uv run --project services/whisperx --frozen svml-whisperx-service-```--## OpenCV and HyperFrames--The OpenCV adapter owns preparation of its frozen Python environment unless an explicit executable-transfers lifecycle ownership to the deployment. HyperFrames owns its profile-scoped browser-preparation. Neither is a central Runtime default; only a selected locked adapter contributes the-corresponding program.--The local media Endpoint accepts an explicitly configured or system `ffmpeg`/`ffprobe` only after-its capability probe succeeds. Runtime lifecycle does not mutate Homebrew, apt or another system-package manager.diff --git a/docs/quickstart.md b/docs/quickstart.mdindex bb4ac071..b3b0ed0b 100644--- a/docs/quickstart.md+++ b/docs/quickstart.md@@ -124,12 +124,11 @@ cd /path/to/my-video/path/to/narratage/narratage plan build.svrun```-The launcher uses dependencies installed in the Narratage checkout, but Source, SQLite state,-Artifacts and outputs remain inside your project. `runtime use` stores only a local pointer at-`.svml/runtime`; the selected Profile remains the single source for both lock paths and the-execution environment. `packages sync` adds or refreshes the current-Run and Runtime selections in the two project package inventories; it does not remove another-Run's packages.+The launcher uses dependencies installed in the Narratage checkout while Source and exported files+remain in your project. Runtime state and Artifacts live under the selected Profile's `dataRoot`.+`runtime use` stores only a local pointer at `.narratage/runtime`. The Source lock belongs to the+project; the Profile independently selects its Runtime lock. `packages sync` updates both+inventories without removing packages needed by another Run.Start from [`examples/talking-film-live`](https://github.com/hypit-ai/narratage/tree/main/examples/talking-film-live) when you need acomplete Runtime Profile. Copy the source structure, then replace its assets, Script, model choices@@ -174,7 +173,7 @@ Install only what your selected Runtime Profile needs:| Chromium | managed automatically by local HyperFrames rendering || API credentials | selecting remote KIE, Vertex, Xiaomi or AWS endpoints |-For local Python services:+For local Python programs:```bashuv python install 3.13diff --git a/docs/quickstart/composition.md b/docs/quickstart/composition.mdindex bcfe6b2e..57e1ace7 100644--- a/docs/quickstart/composition.md+++ b/docs/quickstart/composition.md@@ -249,10 +249,10 @@ width and is rejected.```bashnode --run narratage -- check examples/talking-film-graph-check/main.svml \- --package-lock examples/talking-film-graph-check/svml.packages.lock --root .+ --package-lock examples/talking-film-graph-check/svml.packages.lock --workspace .node --run narratage -- plan examples/talking-film-graph-check/build.svrun \- --package-lock examples/talking-film-graph-check/svml.packages.lock --root .+ --package-lock examples/talking-film-graph-check/svml.packages.lock --workspace .````check` compiles the Author Graph — validates all imports, types, and graph edges without callingdiff --git a/docs/quickstart/images.md b/docs/quickstart/images.mdindex 971a8180..9cf52ee5 100644--- a/docs/quickstart/images.md+++ b/docs/quickstart/images.md@@ -13,7 +13,7 @@ They all need an endpoint. `image-compose` and `image-transform` ask for the ras`@narratage/provider-image-opencv-local` answers by running OpenCV in a bounded Python process onyour own machine; `background-removal` asks for its own capability, which `@narratage/provider-kie`answers remotely. No example in this repository binds either, so add the endpoint to your-[Runtime Profile](/guide/runtime-profile) before planning a Build that uses one.+[Runtime Profile](/guide/runtime) before planning a Build that uses one.## Composing layersdiff --git a/docs/quickstart/run.md b/docs/quickstart/run.mdindex 2acfe5a7..e4666277 100644--- a/docs/quickstart/run.md+++ b/docs/quickstart/run.md@@ -120,8 +120,7 @@ Core has no Pin state or fidelity label.Query an output name as it appeared in each historical Build's frozen Host Catalog:```bash-node --run narratage -- history hook-take.video \- --runtime ./svml.runtime.json+narratage history hook-take.video````history` reports only public Logical Outputs that the Build actually produced. It@@ -130,8 +129,7 @@ does not list merely declared-but-unbuilt aliases or authored Record aliases thaCatalog recorded an exact source path:```bash-node --run narratage -- history --source ./main.svml \- --runtime ./svml.runtime.json+narratage history --source ./main.svml```An output name is a human locator inside one immutable historical Catalog, not its identity. The@@ -192,104 +190,17 @@ human-supplied result uses the same mechanism.## Runtime Profile-The declarative Runtime Profile (`svml.runtime.json`) tells the CLI **where** to run each type of-work. The official video Distribution parses this document as JSON; the command delegates to that-Distribution instead of assigning semantics from the filename suffix. Applications embedding-Narratage may assemble the same Runtime roles through `@narratage/local`. See the complete-[Runtime Profile guide](../guide/runtime-profile.md).--`narratage runtime use <profile>` stores only a project-local pointer in `.svml/runtime`. It does-not copy the Profile, start anything or generate locks. Commands resolve the Profile through that-pointer; the Profile then names both lock files. An explicit `--runtime <profile>` remains a-one-command override and never changes the saved selection. Source commands search upward from the-entry Source; Runtime and archive commands search upward from the current directory.--```json-{- "format": "svml.runtime-config@1",- "packageLock": "./svml.packages.lock",- "runtimePackageLock": "./svml.runtime-packages.lock",- "runtimeServices": [- { "use": "@narratage/local", "instance": "execution" },- { "use": "@narratage/store-sqlite", "instance": "state", "config": { "path": ".svml/runtime.sqlite" } },- { "use": "@narratage/artifact-store-fs", "instance": "artifacts", "config": { "path": ".svml/artifacts" } },- { "use": "@narratage/credential-store-env", "instance": "credentials.env", "config": {} }- ],- "services": {- "scheduler": "execution.scheduler",- "worker": "execution.worker",- "stores": {- "build": "state.builds",- "operations": "state.operations",- "dispatch": "state.dispatch",- "artifacts": "artifacts",- "credentials": ["credentials.env"]- }- },- "endpoints": [- {- "use": "@narratage/provider-kie",- "instance": "kie.main",- "config": {- "apiKey": { "store": "env", "key": "KIE_API_KEY" },- "defaultConcurrency": 2- }- },- {- "use": "@narratage/provider-media-local",- "instance": "media.main",- "config": { "defaultConcurrency": 2 }- },- {- "use": "@narratage/provider-whisperx-local",- "instance": "whisperx.main",- "config": { "defaultConcurrency": 1 }- },- {- "use": "@narratage/provider-google-vertex",- "instance": "vertex.main",- "config": {- "projectEnv": "GOOGLE_CLOUD_PROJECT",- "credentials": { "store": "env", "key": "GOOGLE_APPLICATION_CREDENTIALS_JSON" },- "location": "global",- "defaultConcurrency": 1- }- },- {- "use": "@narratage/provider-hyperframes-local",- "instance": "hyperframes.main",- "config": {- "workers": 2,- "quality": "standard",- "defaultConcurrency": 1- }- }- ],- "scheduling": { "maxConcurrency": 4 }-}-```--### Endpoints--Each endpoint binds a Provider package to a named instance and an explicit Provider Authority:--| Field | Description |-|---|---|-| `use` | Provider package name (e.g. `@narratage/provider-kie`) |-| `instance` | Unique instance identifier |-| `authority` | Optional shared account/compute-pool identity; omit it when this instance owns its own limits |-| `config` | Provider-specific non-secret configuration and ordinary CredentialRefs |+The Runtime Profile chooses where Builds execute. It selects one locked Runtime package; that package+owns its Components, Bindings, Endpoints, limits, lifecycle and private `dataRoot`. The Profile never+defines the Source Workspace or Source package lock.-### Trust--Runtime packages currently execute as trusted local code. A real process/Wasm sandbox is required-before arbitrary third-party runtime packages can be treated as untrusted.--### Scheduling+```bash+narratage runtime use svml.runtime.json+narratage paths+```-`maxConcurrency` limits total parallel Operations. Every Provider contributes an Authority resource-and one exact capability Route resource. Optional `resources` overrides use those opaque resource-ids; they never select a model or Provider.+`runtime use` writes only `.narratage/runtime`. It does not start a Worker, create Runtime data or+change either package lock. See [Runtime](../guide/runtime.md) for the Profile schema and boundaries.## Configure selected credentials@@ -329,111 +240,30 @@ Keep credentials out of Author Source, Run Source, Runtime Profile source, and c## Build workflow-Keep credentials, generated media, Runtime state/databases, and logs out of commits.--### 0. Install--```bash-pnpm install-```--This installs only the JavaScript workspace. It does not download Python models or prepare every-Provider found in the repository. `runtime up` / `services up` reads the selected Runtime Profile-and prepares only the external programs its chosen Endpoints declare. Install-[uv](https://docs.astral.sh/uv/) first only when that Profile selects a local Python service such as-WhisperX or OpenCV.--`narratage runtime up` starts the durable Worker and the external programs declared by the selected-adapters. `build` also ensures that execution domain is running before it submits, but never owns-the Worker.--#### Keep production projects outside the Narratage checkout--Author files do not have to live under this repository. For example, keep a project at-`/work/my-film` while using packages installed in `/opt/narratage`:+Keep credentials, generated media, Runtime data and logs out of commits. A project may live anywhere:```bashcd /work/my-film-/opt/narratage/narratage runtime use svml.runtime.json-/opt/narratage/narratage packages sync build.svrun-/opt/narratage/narratage plan build.svrun```-When a Runtime Profile is selected, its `root` (or its own directory when `root` is omitted) is the-stable Source Workspace for every `.svml`, `.svs`, and `.svrun` in that project. Without a Profile,-the package-lock directory is the boundary when a lock is selected; otherwise the entry Source-directory is used. `--package-root` has one unrelated Host purpose: it-overrides where the CLI locates the installed `node_modules` whose bytes are verified against the-lock. The official CLI normally supplies its own installation location, so no package path is-needed above. Use `--root` only when deliberately widening the Source Workspace above the Run-Source directory. Do not symlink a project into this repository: canonical-path containment-intentionally rejects that escape.+The Workspace is the selected project, nearest Source lock or entry Source directory. Override it+only with `--workspace`. `--package-root` locates installed packages and never widens Source access.+`--asset-root` grants read access to additional asset bytes without permitting Source imports there.-Keep deployment state out of source control. A normal external project should include:--```gitignore-.svml/+```text+.narratage/output/```-Package locks are project source and should remain committed. Read-only archive commands such as-`status` and `builds` do not initialize an absent Runtime database.--For a shared read-only media library, keep Source imports inside the project and authorize only its-asset bytes explicitly:--```bash-node --run narratage -- plan /work/my-film/build.svrun \- --runtime /work/my-film/svml.runtime.json \- --asset-root /work/shared-media-```--`--asset-root` is repeatable. It never permits `.svml`/`.svs` source imports outside `--root`, and-it does not enter Author or Build identity; the exact bytes still enter as content-addressed assets.--The official CLI supplies the same installation location while reading the external project's-Runtime Profile, so the Profile remains portable:--```json-{- "format": "svml.runtime-config@1",- "packageLock": "./svml.packages.lock",- "runtimePackageLock": "./svml.runtime-packages.lock",- "runtimeServices": [- { "use": "@narratage/local", "instance": "execution" },- { "use": "@narratage/store-sqlite", "instance": "state", "config": { "path": ".svml/runtime.sqlite" } },- { "use": "@narratage/artifact-store-fs", "instance": "artifacts", "config": { "path": ".svml/artifacts" } },- { "use": "@narratage/credential-store-env", "instance": "credentials.env", "config": {} }- ],- "services": {- "scheduler": "execution.scheduler",- "worker": "execution.worker",- "stores": {- "build": "state.builds",- "operations": "state.operations",- "dispatch": "state.dispatch",- "artifacts": "artifacts",- "credentials": ["credentials.env"]- }- },- "endpoints": [],- "scheduling": { "maxConcurrency": 4 }-}-```--Runtime state, archived Artifacts and the lock files remain under `/work/my-film`. Set-`--package-root` or the Profile's `packageRoot` only when the packages intentionally live somewhere-other than the CLI installation.-### 1. Synchronize installed packagesAfter installing or updating packages, synchronize the project inventories:```bashcd examples/talking-head-aroll-node --run narratage -- runtime use svml.runtime.json-node --run narratage -- packages sync build.svrun+narratage runtime use svml.runtime.json+narratage packages sync build.svrun```The current Author and Run sources choose author packages. The Runtime Profile chooses environment@@ -445,10 +275,10 @@ scans the project, starts a Provider or generates media.### 2. Diagnose the environment```bash-node --run narratage -- doctor+narratage doctor```-Doctor validates both locks, every selected Runtime role, Endpoint configuration, credential+Doctor validates the Runtime lock, every selected Runtime role, Endpoint configuration, credentialpresence and bounded environment probes. It never starts the Worker or performs a paid request.Doctor is intentionally a **full profile audit**. For the environment required by one Run, use@@ -459,25 +289,25 @@ readiness.### 3. Check source and inspect the plan```bash-node --run narratage -- check main.svml+narratage check main.svml``````bash-node --run narratage -- plan build.svrun+narratage plan build.svrun```Review the frozen BuildPlan before spending money. The plan shows every Operation and Needs theScheduler would issue. With a selected Runtime, it also reports only the relevant Endpoint, credential andexternal-program diagnostics. It never starts external work.-`build` starts or reuses the detached Runtime automatically. Use `runtime up` only when you want to-prepare it before submission; `runtime status` observes it. The narrower `services up|status|down`-commands manage external programs only and do not own the Worker lifecycle.+`build` starts or reuses the selected Runtime automatically. Use `runtime up` to prepare it before+submission and `runtime status` to observe it. `programs up|status|down` is the narrower lifecycle+view for long lived processes declared by Endpoints.### 4. Submit the Build```bash-node --run narratage -- build build.svrun --follow+narratage build build.svrun --follow```Without `--follow`, `build` returns after durable submission. The detached Worker continues. With@@ -487,9 +317,9 @@ interrupting it leaves the Build running.| Flag | Description ||---|---|| `--runtime` | One-command Runtime Profile override; normally select it once with `runtime use` |-| `--package-lock` | Standalone compilation lock when no Runtime Profile is supplied; a JSON Profile single-sources it for `check`, `plan` and `build` |+| `--package-lock` | Explicit Source package lock override || `--package-root` | Host directory containing the installed packages named by the lock |-| `--root` | Optional Source Workspace override; otherwise the Runtime Profile root, package-lock directory, or entry Source directory is used in that order |+| `--workspace` | Explicit Source Workspace override || `--follow` | Wait for terminal state as an observer; durable execution remains with the Worker |Each invocation creates a fresh Build id, even when the Author and Run Sources are unchanged. That@@ -500,14 +330,14 @@ Records and the same external task checkpoints; it never turns another invocatio### 5. Inspect and retrieve results```bash-node --run narratage -- inspect <build-id>+narratage inspect <build-id>````inspect` reports durable Build state, demanded outputs, and accepted Records. Retrieve the selectedarchived Artifact only after those facts are correct:```bash-node --run narratage -- get <build-id> \+narratage get <build-id> \--name final.video \--to examples/talking-head-aroll/output/final.mp4```@@ -526,16 +356,16 @@ Create a new `.svrun` file that references the completed Build's Records (see [Rabove), then submit it:```bash-node --run narratage -- build reuse-generated.svrun --follow+narratage build reuse-generated.svrun --follow```### 7. Diagnose or stop the local Runtime```bash-node --run narratage -- runtime logs-node --run narratage -- runtime down+narratage runtime logs+narratage runtime down````runtime down` stops the Worker from claiming more leases but leaves external programs running.-Use `services down` only when those programs should also stop. Neither command cancels durable+Use `programs down` only when those programs should also stop. Neither command cancels durableBuilds or remote Provider work. Starting the same Profile again continues unfinished dispatches.diff --git a/docs/zh/guide/develop.md b/docs/zh/guide/develop.mdindex 2a47a7cc..bdea3be9 100644--- a/docs/zh/guide/develop.md+++ b/docs/zh/guide/develop.md@@ -11,7 +11,7 @@ description: 开始 Narratage 开发工作。|---|---|---|| Node.js | 22+ | 所有工作 || pnpm | 10.33.x | workspace 管理;由根目录 `packageManager` 字段选择 |-| Python | 3.10–3.13 | WhisperX 与 OpenCV [本地服务](./services.md) |+| Python | 3.10–3.13 | 本地 WhisperX 与 OpenCV Managed Program || uv | latest | Python 环境管理 || ffmpeg / ffprobe | 较新的稳定版 | 媒体处理 || Chrome / Chromium | 由 HyperFrames 管理 | 本地 HyperFrames 渲染 |@@ -55,8 +55,7 @@ narratage/| [包架构](./packages.md) | 五个层次、依赖规则、包的构成、facets || [添加 Author 包](./author-packages.md) | 分步说明:新增组件、Surface、activation || [添加 Provider](./providers.md) | 分步说明:新增 Endpoint 适配器 |-| [Runtime Profile](./runtime-profile.md) | 声明式 CLI 配置、嵌入边界、诊断、Build 归档 |+| [Runtime](./runtime.md) | Profile、Workspace、执行与生命周期边界 || [字幕 Playground](./caption-playground.md) | 直接编辑真实字幕 SVML/SVS 并实时预览 |-| [本地服务](./services.md) | WhisperX 与 OpenCV 的搭建 || [测试](./testing.md) | 测试运行器、写法、示例、boundary tests || [代码规范](./conventions.md) | 命名、模块边界、wire 数据、TypeScript 配置 |diff --git a/docs/zh/guide/packages.md b/docs/zh/guide/packages.mdindex c00f081e..d475be6b 100644--- a/docs/zh/guide/packages.md+++ b/docs/zh/guide/packages.md@@ -245,10 +245,10 @@ Frontend 实现不是物理包格式里的特权字段。它们与 Run FragmentAdapter 一样,通过自己的 Host ABI 发布普通 facet;Frontend 使用`svml.source-frontend@1`,只有 Source Host 会解释它。-Runtime Profile 也遵循同一规则。每个 `use` 选择的是 Endpoint Adapter ABI 或 Runtime Service-Adapter ABI 加逻辑名;物理 npm 包只负责声明它提供这个逻辑能力。包名只是首次纳入库存的提示+Runtime Profile 也遵循同一规则。每个 `use` 选择的是 Runtime Host、Endpoint Adapter 或 Runtime+Component Adapter ABI 加逻辑名;物理 npm 包只负责声明它提供这个逻辑能力。包名只是首次纳入库存的提示和 lockfile 事实,通用 CLI 不维护 Provider 注册表;同名的 Endpoint Adapter 与 Runtime-Service Adapter 也不会互相冲突。+Component Adapter 也不会互相冲突。逻辑名与物理 npm 包根同名时,`packages sync` 可以直接完成首次纳入。若一个物理合集包使用不同名字,开发者需先把它显式加入项目库存;此后 Source 仍只依赖逻辑名。系统绝不会diff --git a/docs/zh/guide/providers.md b/docs/zh/guide/providers.mdindex 271a6c08..b5c01845 100644--- a/docs/zh/guide/providers.md+++ b/docs/zh/guide/providers.md@@ -28,7 +28,7 @@ Provider 包依赖 Runtime 端口与共享能力词汇,不依赖精确模型"exports": {".": "./src/index.ts"},- "svml": { "activation": "./src/activation.ts", "service": true },+ "svml": { "activation": "./src/activation.ts" },"dependencies": {"@narratage/endpoint-kit": "workspace:*","@narratage/protocol": "workspace:*",@@ -115,16 +115,16 @@ export default svmlPackage;capability 和调度事实。Activation 不得解析密钥或环境来源的部署值、访问网络或启动任务;环境变量名会作为引用保留到真正处理匹配 Need 时。凭据是否存在由通用 CredentialStore 路径诊断,Provider 不得把环境变量硬编码成特殊的密钥 Store。-## 5. 声明外部服务(如需要)+## 5. 按需声明 Managed Program-如果 Provider 依赖外部程序(Python 服务、本地服务器),在 `package.json` 的 `svml` 块中添加-`"service": true`(见第 2 步),并在 `src/service.ts` 中导出工厂函数:+如果 Provider 依赖需要保持温热的外部程序,就在 Endpoint 旁边导出它的声明。这里没有第二个+manifest 开关,也没有中央 Program 注册表:```typescript-// src/service.ts-import type { RuntimeExternalService } from "@narratage/local";+// src/program.ts+import type { ManagedProgram } from "@narratage/runtime-adapter";-export function createMyExternalService(): RuntimeExternalService {+export function createMyProgram(): ManagedProgram {return {id: "my-service",prepare: { command: "uv", args: ["sync", "--project", "services/my-service", "--frozen"] },@@ -144,13 +144,14 @@ const adapter = createRuntimeEndpointAdapterFacet({activate(context) {return {endpoint: createMyServiceProvider(/* 已解析配置 */),- externalService: createMyExternalService(),+ program: createMyProgram(),};},});```-`narratage runtime up` 会准备、启动并探测外部程序,然后启动耐久 Worker。`build` 只启动所选 Producer steps 声明的 capability 所需服务。只调用远程 API 的 Provider 不声明 service。+`narratage runtime up` 会准备、启动并探测 Managed Program,然后启动耐久 Worker。`build` 只启动+本次 Plan 所需 Capability 对应的 Program。只调用远程 API 的 Provider 不返回 `program`。## 6. 注册并锁定diff --git a/docs/zh/guide/runtime-profile.md b/docs/zh/guide/runtime-profile.mddeleted file mode 100644index 14ce76d5..00000000--- a/docs/zh/guide/runtime-profile.md+++ /dev/null@@ -1,135 +0,0 @@-----title: Runtime Profile-description: 显式配置 Build 的执行环境、状态存储、凭据与并发。------# Runtime Profile--Runtime Profile 声明冻结后的 Build *在哪里*执行:Scheduler、Worker、全部 Store、Endpoint、凭据和并发。它属于部署配置,绝不进入 Author Graph 或 Run Graph 身份。--每个项目只需选择一次:--```bash-narratage runtime use svml.runtime.json-```--CLI 只在 `.svml/runtime` 保存一个相对路径指针。Profile 仍然唯一决定项目根、两份 package-lock、Store、Endpoint 与调度。`runtime unset` 只删除该指针,不停止任务、不删除状态;-`--runtime <profile>` 则是单次命令覆盖。--## 声明式 Profile--```json-{- "format": "svml.runtime-config@1",- "packageLock": "./svml.packages.lock",- "runtimePackageLock": "./svml.runtime-packages.lock",- "runtimeServices": [- { "use": "@narratage/local", "instance": "execution" },- { "use": "@narratage/store-sqlite", "instance": "state", "config": { "path": ".svml/runtime.sqlite" } },- { "use": "@narratage/artifact-store-fs", "instance": "artifacts", "config": { "path": ".svml/artifacts" } },- { "use": "@narratage/credential-store-keychain", "instance": "credentials.keychain", "config": { "service": "narratage" } }- ],- "services": {- "scheduler": "execution.scheduler",- "worker": "execution.worker",- "stores": {- "build": "state.builds",- "operations": "state.operations",- "dispatch": "state.dispatch",- "artifacts": "artifacts",- "credentials": ["credentials.keychain"]- }- },- "endpoints": [- {- "use": "@narratage/provider-kie",- "instance": "kie.production",- "config": {- "apiKey": { "store": "keychain", "key": "kie.api-key" },- "defaultConcurrency": 2- }- }- ],- "scheduling": { "maxConcurrency": 4 }-}-```--`runtimeServices` 激活已安装的实现;`services` 按实例 id 逐项选择 Scheduler、Worker、-BuildStore、OperationStore、DispatchStore、ArtifactStore 和一个或多个-CredentialStore。不存在“因为只装了一个所以自动选中”,`@narratage/local` 也不补 SQLite、文件系统或凭据默认值。--凭据只写地址:`{ "store": "…", "key": "…" }`,秘密字节不进 Profile。多个 Store 可以并存,每个 Store 只响应属于自己命名空间的引用。--## 文件边界--| 字段 | 含义 |-|---|---|-| `root` | 项目根;既约束 Source,也承载 Runtime 数据、Artifact 与相对 lock;默认是 Profile 所在目录 |-| `packageRoot` | 提供已安装 `node_modules` 的 Host 位置;与项目数据目录无关 |-| `packageLock` | 可信 Author/Run 实现包库存;每次编译只激活当前 Source 的精确子集 |-| `runtimePackageLock` | 可信 Runtime Adapter 包库存;每份 Profile 只激活自己显式选择的 Adapter |--外部项目可以把源文件、锁、SQLite 和 Artifact 全部留在自己的目录,同时从另一个-Narratage 安装目录加载校验后的包。--## 并发与信任边界--`maxConcurrency`、每个 Provider 的总 Authority 上限与其内部实际模型/API route 上限,由 DispatchStore 在所有共享 Worker 之间执行。一次任务原子领取 Provider 与 route 两份容量,不会在父子队列间复制。Route 是 Provider 本地概念;KIE Seedance 与另一个 Provider 的 Seedance 不共享隐藏的家族计数器。容量租约跟随 Build 的 fenced lease;过期 Worker 不能继续准入结果。--Runtime Adapter 当前是可信本地代码。开放任意第三方 Adapter 之前,需要真正的进程或 Wasm-隔离;字符串 allowlist 不能限制同一 Node 进程里的代码。--## 凭据控制不是 Runtime 执行--`auth status|login|logout <endpoint-instance>` 只构造该 Endpoint 的声明和 Profile 明确选择的-CredentialStore,不会打开 SQLite、启动 Worker、加载作者包或构造其他 Provider。因此登录-KIE 不会被旧 Build 数据库或无关的 Vertex 配置拦住。--## 生命周期--```bash-node --run narratage -- doctor-node --run narratage -- runtime up-node --run narratage -- runtime status-node --run narratage -- runtime logs-node --run narratage -- runtime down-```--`runtime up` 管理耐久 Worker 与声明的外部程序。`services up/status/down` 只管理外部程序,不会启动 Worker。`build` 会确保 Runtime 已启动,但 Build 所在终端从不拥有执行权。Distribution 提供一个不透明 Runtime 修订;官方 JSON Profile 让它覆盖 Profile 与两份 package lock,通用 CLI 不解释其语法。任一文件变化后状态变为-`stale`,下一次启动或提交会按新执行闭包替换进程,而不是继续复用旧装配。--`doctor` 会求值 Endpoint Adapter 唯一的纯 `activate()` 声明,并直接从产生的 Endpoint package-读取凭据和前置条件;不存在另一份仅供诊断使用的凭据镜像。Activation 可以构造 handler,但不得解析密钥、访问网络、启动进程或修改持久状态。`doctor` 不构造 Scheduler、Worker、Build-Store 或作者包,不会启动服务、写入 Runtime 状态或提交任务;它只打开 Profile 明确选择的-CredentialStore 来解析引用,完成后立即关闭,并可执行显式声明的有界只读探测。--预发布阶段不会原地迁移 SQLite 执行 schema。遇到更早的开发数据库时,CLI 会指出精确路径,要求把数据库连同 WAL 文件归档,或在 Profile 选择新路径。ArtifactStore 是独立选择的;该拒绝不会删除任何产物字节。--## Build、队列与归档--```bash-node --run narratage -- build build.svrun-node --run narratage -- build build.svrun --follow-node --run narratage -- queue --watch-node --run narratage -- status <build-id>-node --run narratage -- inspect <build-id>-node --run narratage -- get <build-id> --name final.video --to output.mp4-```--不带 `--follow` 时,`build` 在耐久提交后退出;Worker 继续执行。`--follow` 只是观察,Ctrl-C-不会取消任务。所有已接受 Record 与引用的 Artifact 都会归档,`get` 只是可选导出。--## 取消--```bash-node --run narratage -- cancel <build-id>-```--CLI 唯一控制单位是 Build。尚未被 Worker 领取的排队 Build 会在 Store 中原子撤回;已经运行的 Build 会先关闭后续准入,再尽力取消已提交的 Provider 工作。`accepted` 只是远端接受停止请求,不等于已经停止;系统继续协调到 `confirmed`、`unsupported`、`too-late` 或自然结束。Operation 仍会作为 Build 详情显示,但不能被 CLI 单独控制。终态 Build 不会重新打开;再次运行同一 `.svrun` 会创建新 Build。Endpoint 的 checkpoint 恢复只用于 Worker 重启后续接同一个已提交外部任务,避免重复付费。--## 嵌入 API--官方 video Distribution 目前按 JSON 解析声明式 Runtime Profile;通用 CLI 不给 `.json`-后缀任何语义,只把文档交给 Distribution。嵌入 Narratage 的应用可以通过-`@narratage/local` 直接组装相同的 Runtime 角色。diff --git a/docs/zh/guide/runtime.md b/docs/zh/guide/runtime.mdnew file mode 100644index 00000000..c8cbc111--- /dev/null+++ b/docs/zh/guide/runtime.md@@ -0,0 +1,120 @@+---+title: Runtime+description: Narratage Source 与 Core 之外的执行边界。+---++# Runtime++Narratage 把三个决定分开:++| 所有者 | 决定什么 |+|---|---|+| Workspace | 一次编译能读取哪些 Source 和本地素材 |+| Runtime Profile | 编译完成的 Build 交给哪个执行环境 |+| Runtime | Build 如何排队、执行、存储和被观察 |++Runtime Profile 不定义 Workspace。同一 Profile 可以服务多个项目,同一项目也可以在不改+Author Source 的情况下选择不同 Runtime。++## 边界++Core 是领域无关的状态机。它接收事实、派生 Command、验证 Record,不启动进程、不读取凭证、+不选择 Provider,也不知道 Build 最终是不是视频。++Runtime 接收已经编译完成的 Build,负责耐久状态、队列、租约、并发、Artifact、凭证、Endpoint、+Provider 调用和可选的长期运行程序。通用 CLI 只通过 Runtime Controller 与它通信,不假设它是+本地 Node 进程。本地 Controller 可以管理独立 Worker;远程 Controller 可以通过 HTTP 接收同一份 Build。++## Runtime Profile++Profile 选择一个 Runtime 包,并把封闭配置交给它:++```json+{+ "format": "narratage.runtime-profile@1",+ "runtimePackageLock": "./svml.runtime-packages.lock",+ "runtime": {+ "use": "@narratage/local",+ "config": {+ "dataRoot": ".narratage/runtimes/local",+ "components": {+ "execution": { "use": "@narratage/local" },+ "state": { "use": "@narratage/store-sqlite", "config": { "path": "state.sqlite" } },+ "artifacts": { "use": "@narratage/artifact-store-fs", "config": { "path": "artifacts" } }+ },+ "bindings": {+ "scheduler": "execution.scheduler",+ "worker": "execution.worker",+ "stores": {+ "build": "state.builds",+ "operations": "state.operations",+ "dispatch": "state.dispatch",+ "artifacts": "artifacts",+ "credentials": []+ }+ },+ "endpoints": {+ "media": { "use": "@narratage/provider-media-local" }+ },+ "limits": { "maxOperations": 4 }+ }+ }+}+```++`components` 配置可替换的 Runtime 基础设施,`bindings` 选择每个角色的确切实例,`endpoints`+配置能力实现,`limits` 限制整个 Runtime。安装包只增加可用实现,不会自动激活或改变 Core。++Profile 不包含 Source Workspace、Source package lock 或 Author 包选择。相对 Profile 路径从+Profile 文件解析;本地 Runtime 的私有路径从 `dataRoot` 解析。++## 项目状态与路径++```text+.narratage/+ runtime+ runtimes/+ local/+ worker/+ state.sqlite+ artifacts/+```++`runtime use` 只写 `.narratage/runtime` 指针,不启动进程。`check` 和 `plan` 不创建 Runtime 数据。+`narratage paths` 会报告 Workspace、项目状态、Runtime 数据与操作系统级 Host 状态的位置。++Workspace 独立按以下顺序确定:显式 `--workspace`、所选 `.narratage/runtime` 所在项目、最近的+Source package lock、入口 Source 目录。Runtime Profile 无权扩大它。++## Component、Endpoint 与 Managed Program++Runtime Component 是 Scheduler、Worker、Store 等基础设施实现。Binding 明确选择一个实例,包的+存在本身不具备路由权。Endpoint 实现声明过的 Capability,并负责 Provider 调用。++Managed Program 是 Endpoint 声明的长期外部进程,例如常驻 WhisperX 服务。它不是 Component,+也不是队列。Endpoint 可以声明探测、准备和启动方法;外部托管时只声明探测。++```bash+narratage programs status+narratage programs up+narratage programs down+```++Build 只准备本次所需能力对应的 Program。显式 `programs up` 检查完整 Profile;停止 Runtime+Worker 不会自动停止可能被共享的 Program。++## 生命周期++```bash+narratage runtime use svml.runtime.json+narratage runtime up+narratage runtime status+narratage runtime logs+narratage runtime down+```++这些都是 Controller 操作。`build` 每次提交一个新的 Build id;`--follow` 只负责观察。终态 Build+不会重新打开,复用已有结果必须由新的 Run Source Candidate 显式表达。++Source 包和 Runtime 包使用不同锁,因为它们拥有不同权限。目前 Node Runtime 包仍是可信部署代码;+在真正的进程或 Wasm 隔离完成前,Manifest 和 digest 都不能充当沙箱。diff --git a/docs/zh/guide/services.md b/docs/zh/guide/services.mddeleted file mode 100644index 080d285a..00000000--- a/docs/zh/guide/services.md+++ /dev/null@@ -1,93 +0,0 @@-----title: Runtime 与外部服务-description: 管理耐久 Worker 与 Profile 明确选择的本地程序。------# Runtime 与外部服务--这里有两个故意分开的生命周期。--## 整个执行域--```bash-node --run narratage -- runtime use svml.runtime.json-node --run narratage -- runtime up-node --run narratage -- runtime status-node --run narratage -- runtime logs-node --run narratage -- runtime down-```--`runtime up` 启动或复用当前 Profile 的后台 Worker,并准备、启动该 Profile 声明的外部程序。重复执行不会创建第二个同域 Worker。`runtime status` 同时展示 Worker、耐久队列、共享容量和外部程序健康状态。--彼此独立的外部程序会并行准备。人类可读输出会显示 `Checking`、`Preparing`、`Starting`、-`Waiting`、`Ready`,首次准备 WhisperX 模型或浏览器时不会像命令卡死;JSON 模式仍只输出一份干净的最终文档。--后台进程同时绑定 Profile 路径与 Distribution 提供的不透明修订值。官方 JSON Profile 的实现让该修订覆盖 Profile 与两份 package lock;通用 CLI 不解析配置文档,也不假定哪些文件属于修订。任一文件变化后,官方 Worker 会显示为 `stale`;下一次 `runtime up` 或 `build` 会先替换旧进程,不会让新 Dispatch 偷偷进入旧执行闭包。--`runtime down` 只停止 Worker,并故意保留外部程序,因为其他 Runtime Profile 可能正在共用-它们。只有确实要停止这些程序时才执行 `services down`。两条命令都不会取消 Build 或远端-Provider 任务,队列仍在 Store 中,下次启动后继续。--## 只管理外部程序--```bash-node --run narratage -- services up svml.runtime.json-node --run narratage -- services status svml.runtime.json-node --run narratage -- services down svml.runtime.json-```--`services` 是调试/运维命令,只处理 Adapter 声明的程序,不启动 Worker、不读取或修改 Build-队列。例如:--- 常驻的本地 WhisperX HTTP 服务;-- OpenCV Python 环境探测;-- HyperFrames 浏览器准备;-- ffmpeg/ffprobe 兼容性探测。--KIE 这种纯远端 API Endpoint 没有本地 service。--## 与 Build 的关系--`build` 会先从选中 Producer steps 推导其声明的 capability,只准备承载这些 capability 的外部程序。纯文本或纯 Estimate Target 不会仅仅因为 Profile 里也提供 WhisperX 就加载几 GB-模型;这不改变图、不替作者路由 Provider,只避免启动无关部署程序。之后 Build 与 Dispatch-ticket 会被耐久写入。无 `--follow` 时立刻退出;`--follow` 只观察,并在 Build phase 或-Operation 数量变化时输出一行。中断观察终端不会中断 Worker。--`--no-services` 只表示外部程序由部署者另行维护,不会把执行塞回 CLI,也不会恢复任何隐式 Runtime 默认。--显式 `runtime up` 与 `services up` 仍管理整个 Profile,因为它们的对象是部署而非某次 Build。--## 可见性--```bash-node --run narratage -- queue --watch-node --run narratage -- status <build-id>-node --run narratage -- inspect <build-id>-node --run narratage -- cancel <build-id>-```--这些命令展示活跃 dispatch、Worker 状态、租约/容量、Operation 的通用进度、checkpoint 和取消状态。并发启动按 Profile 串行化,只会复用一个 Worker 和每个受管外部服务的一个实例;-`--follow` 若发现 Worker 已停止会明确报出重启命令,不会无限等待。`--json` 输出一次结构化结果,watch 命令可用 `--jsonl`。`queue --watch` 只输出第一份快照和后续变化,不会在远端任务状态没变时每秒重复刷同一个块。--CLI 的公开控制单位只有 Build。未被 Worker 领取的排队 Build 会被原子撤回;已运行的 Build-会关闭后续准入并协调已经提交的 Provider 工作。Operation 仍显示在 Build 详情中,但不能单独控制。终态 Build 不会重新打开;再次运行同一 `.svrun` 会创建新 Build。Endpoint checkpoint 只用于 Worker 重启后续接同一个已提交的外部任务,避免重复付费。--## WhisperX--`@narratage/provider-whisperx-local` 声明热服务及健康探测,锁定协议、包版本、模型、设备、计算类型和 batch size。服务只读取允许目录下的规范证据 WAV。Runtime Route 资源避免无意义的并发 `BUSY`。--开发服务本身时仍可前台运行:--```bash-uv sync --project services/whisperx --frozen-uv run --project services/whisperx --frozen svml-whisperx-prepare-uv run --project services/whisperx --frozen svml-whisperx-check-uv run --project services/whisperx --frozen svml-whisperx-service-```--## OpenCV、HyperFrames 与媒体工具--OpenCV Adapter 在没有显式外部 Python 时维护冻结环境;HyperFrames Adapter 维护自身浏览器。二者都不是中央默认,只有被 Profile 选中的锁定 Adapter 才能贡献程序。--本地媒体 Endpoint 只接受通过能力探测的显式或系统 `ffmpeg`/`ffprobe`。Runtime 不会修改-Homebrew、apt 或其他系统包管理器。diff --git a/docs/zh/quickstart.md b/docs/zh/quickstart.mdindex a75c984a..6db88e77 100644--- a/docs/zh/quickstart.md+++ b/docs/zh/quickstart.md@@ -120,9 +120,10 @@ cd /path/to/my-video/path/to/narratage/narratage plan build.svrun```-启动器使用 Narratage 仓库已经安装好的依赖,但源码、SQLite 状态、Artifact 和输出都会留在你的项目里。-`runtime use` 只在 `.svml/runtime` 保存一个本地指针;所选 Profile 仍然是两份 lock 路径和执行环境的-唯一来源。`packages sync` 把当前 Run 与 Runtime 选择加入或刷新到两份项目包库存中,不会删除其他 Run 的包。+启动器使用 Narratage 仓库已经安装好的依赖,Source 与导出的文件留在项目里;Runtime 状态与+Artifact 位于所选 Profile 的 `dataRoot`。`runtime use` 只在 `.narratage/runtime` 保存一个本地指针。+Source lock 属于项目,Profile 独立选择 Runtime lock。`packages sync` 根据两项选择更新库存,+不会删除其他 Run 需要的包。需要完整 Runtime Profile 时,从[`examples/talking-film-live`](https://github.com/hypit-ai/narratage/tree/main/examples/talking-film-live) 的结构开始:复制文件结构,@@ -166,7 +167,7 @@ Runtime 会归档所有已经接受的中间 Record 和媒体。`get` 只负责| Chromium | 本地 HyperFrames 渲染时由 Adapter 管理 || API 凭据 | 选择 KIE、Vertex、Xiaomi 或 AWS Endpoint 时 |-准备本地 Python 服务:+准备本地 Python 程序:```bashuv python install 3.13diff --git a/docs/zh/quickstart/composition.md b/docs/zh/quickstart/composition.mdindex e287b87d..05d09125 100644--- a/docs/zh/quickstart/composition.md+++ b/docs/zh/quickstart/composition.md@@ -243,10 +243,10 @@ Build Target,也可以直接接到媒体裁切、音频/帧提取或模型参```bashnode --run narratage -- check examples/talking-film-graph-check/main.svml \- --package-lock examples/talking-film-graph-check/svml.packages.lock --root .+ --package-lock examples/talking-film-graph-check/svml.packages.lock --workspace .node --run narratage -- plan examples/talking-film-graph-check/build.svrun \- --package-lock examples/talking-film-graph-check/svml.packages.lock --root .+ --package-lock examples/talking-film-graph-check/svml.packages.lock --workspace .````check` 编译 Author Graph——验证所有导入、类型和图的边,而不调用任何外部服务。`plan`diff --git a/docs/zh/quickstart/images.md b/docs/zh/quickstart/images.mdindex a926dc8a..33e8af51 100644--- a/docs/zh/quickstart/images.md+++ b/docs/zh/quickstart/images.md@@ -7,7 +7,7 @@ description: 在图片流向生成器或 Track 之前,对它做合成、校正有三个包接收一张图片、交还一张图片。它们都不产出 Track:每个输出都是一张可供下游引用的图片——作为 Seedance 的参考帧、作为 Media Item,或作为下一次操作的来源。-它们都需要 endpoint。`image-compose` 与 `image-transform` 索取 raster 能力,由 `@narratage/provider-image-opencv-local` 在你自己机器上以受限的 Python 进程运行 OpenCV 来满足;`background-removal` 索取的是它自己声明的能力,由 `@narratage/provider-kie` 远程满足。本仓库没有任何示例绑定过这两者,所以在 plan 一次用到它们的 Build 之前,先把 endpoint 加进你的 [Runtime Profile](/zh/guide/runtime-profile)。+它们都需要 Endpoint。`image-compose` 与 `image-transform` 索取 raster 能力,由 `@narratage/provider-image-opencv-local` 在本机运行 OpenCV 来满足;`background-removal` 索取的是它自己声明的能力,由 `@narratage/provider-kie` 远程满足。本仓库没有示例默认绑定这两者,所以在 plan 一次用到它们的 Build 之前,先把 Endpoint 加进你的 [Runtime Profile](/zh/guide/runtime)。## 合成图层diff --git a/docs/zh/quickstart/run.md b/docs/zh/quickstart/run.mdindex 4e3e19b5..1caadb4c 100644--- a/docs/zh/quickstart/run.md+++ b/docs/zh/quickstart/run.md@@ -108,15 +108,13 @@ Narratage 没有隐式缓存。复用结果是显式的运行图编写——你按照输出在各个历史 Build 冻结 Catalog 中的旧名字查询:```bash-node --run narratage -- history hook-take.video \- --runtime ./svml.runtime.json+narratage history hook-take.video````history` 只列出该 Build 确实产出过的公开 Logical Output。仅仅在源码中声明但没有运行出来的别名,以及不能作为 `build-record` Candidate 的 authored Record 别名,都不会混入结果。如果忘了旧名字,可以按 Catalog 当时记录的精确源码路径列出真正验收过的输出名:```bash-node --run narratage -- history --source ./main.svml \- --runtime ./svml.runtime.json+narratage history --source ./main.svml```输出名只是某个不可变历史 Catalog 内供人查找的名字,不是产物身份。真正身份由历史 Core@@ -169,104 +167,17 @@ Core 不再给 Candidate 标注 `exact` 或 `substitute`。选择 Candidate 本## Runtime Profile-Runtime Profile(`svml.runtime.json`)告诉系统**在哪里**执行每种类型的工作:--官方 video Distribution 目前按 JSON 解析这份文档;CLI 根据命令把它交给 Distribution,-不会根据文件后缀赋予语义。嵌入 Narratage 的应用可以通过 `@narratage/local` 直接组装-相同的 Runtime 角色。完整说明见-[Runtime Profile 指南](../guide/runtime-profile.md)。--`narratage runtime use <profile>` 只在 `.svml/runtime` 保存一个项目本地指针,不复制 Profile、-不启动环境,也不生成 lock。后续命令先通过该指针找到 Profile,再由 Profile 指定两份 lock。-显式 `--runtime <profile>` 仍可作为单次覆盖,并且不会改变已经保存的选择。源码命令从入口-Source 所在目录向上查找;Runtime 与归档命令则从当前目录向上查找。--```json-{- "format": "svml.runtime-config@1",- "packageLock": "./svml.packages.lock",- "runtimePackageLock": "./svml.runtime-packages.lock",- "runtimeServices": [- { "use": "@narratage/local", "instance": "execution" },- { "use": "@narratage/store-sqlite", "instance": "state", "config": { "path": ".svml/runtime.sqlite" } },- { "use": "@narratage/artifact-store-fs", "instance": "artifacts", "config": { "path": ".svml/artifacts" } },- { "use": "@narratage/credential-store-env", "instance": "credentials.env", "config": {} }- ],- "services": {- "scheduler": "execution.scheduler",- "worker": "execution.worker",- "stores": {- "build": "state.builds",- "operations": "state.operations",- "dispatch": "state.dispatch",- "artifacts": "artifacts",- "credentials": ["credentials.env"]- }- },- "endpoints": [- {- "use": "@narratage/provider-kie",- "instance": "kie.main",- "config": {- "apiKey": { "store": "env", "key": "KIE_API_KEY" },- "defaultConcurrency": 2- }- },- {- "use": "@narratage/provider-media-local",- "instance": "media.main",- "config": { "defaultConcurrency": 2 }- },- {- "use": "@narratage/provider-whisperx-local",- "instance": "whisperx.main",- "config": { "defaultConcurrency": 1 }- },- {- "use": "@narratage/provider-google-vertex",- "instance": "vertex.main",- "config": {- "projectEnv": "GOOGLE_CLOUD_PROJECT",- "credentials": { "store": "env", "key": "GOOGLE_APPLICATION_CREDENTIALS_JSON" },- "location": "global",- "defaultConcurrency": 1- }- },- {- "use": "@narratage/provider-hyperframes-local",- "instance": "hyperframes.main",- "config": {- "workers": 2,- "quality": "standard",- "defaultConcurrency": 1- }- }- ],- "scheduling": { "maxConcurrency": 4 }-}-```--### Endpoint--每个 endpoint 将一个 Provider 包绑定到命名实例与显式的 Provider Authority:--| 字段 | 说明 |-|---|---|-| `use` | Provider 包名(例如 `@narratage/provider-kie`) |-| `instance` | 唯一的实例标识符 |-| `authority` | 可选的共享账号或计算池标识;实例独享容量时省略即可 |-| `config` | Provider 专属非秘密配置、CredentialRef 与并发数 |+Runtime Profile 选择 Build 在哪里执行。它选择一个锁定的 Runtime 包;该包拥有自己的+Component、Binding、Endpoint、并发限制、生命周期和私有 `dataRoot`。Profile 不定义+Source Workspace,也不包含 Source package lock。-### 信任边界--Runtime 包目前作为可信本地代码执行。开放任意第三方 Runtime 包之前,需要真正的进程或-Wasm 隔离;字符串 allowlist 不能限制同一 Node 进程里的代码。--### 调度--`maxConcurrency` 限制总的并行 Operation 数。Provider 会贡献一个 Authority 资源和一个精确-Capability Route 资源,二者由 Store 原子获取;可选的 `resources` 只按不透明资源 id 覆盖容量。+```bash+narratage runtime use svml.runtime.json+narratage paths+```+`runtime use` 只写入 `.narratage/runtime`,不会启动 Worker、创建 Runtime 数据或修改任何+package lock。Profile 结构和完整边界见 [Runtime](../guide/runtime.md)。## 配置所选凭据`check` 与 `plan` 不会请求在线 Provider,因此不需要 API key。在运行 `doctor` 或付费/外部@@ -312,7 +223,7 @@ pnpm install```这条命令只安装 JavaScript 工作区,不会下载 Python 模型,也不会准备仓库内的所有 Provider。-`runtime up` / `services up` 会读取所选 Runtime Profile,只准备其中 Endpoint 声明的外部程序。只有 Profile 选择 WhisperX、OpenCV 等本地 Python 服务时,才需要先安装+`runtime up` 会读取所选 Runtime Profile,并准备其中 Endpoint 声明的外部程序。只有 Profile 选择 WhisperX、OpenCV 等本地 Python 程序时,才需要先安装[`uv`](https://docs.astral.sh/uv/);具体锁定环境命令见 Quickstart 首页的 [安装](../quickstart.md#安装)。`narratage runtime up` 管理后台 Worker 和外部程序;`build` 会确保 Runtime 已运行,但不拥有@@ -331,15 +242,14 @@ cd /work/my-film/opt/narratage/narratage plan build.svrun```-选择 Runtime Profile 时,Profile 的 `root`(未写则为 Profile 所在目录)是该项目所有-`.svml`、`.svs`、`.svrun` 的稳定 Source Workspace。没有 Profile 时,若选择了 package lock-就以 lock 所在目录为边界,否则才以入口 Source 所在目录为边界。`--package-root` 是另一项无关的 Host 覆盖项:它只负责指定已安装的-`node_modules`,然后按照 lock 校验包字节。官方 CLI 通常会自动提供自身的安装位置,所以上面的命令无需填写包路径。只有需要主动扩大源码边界时才传 `--root`。不要把外部项目软链接进仓库;canonical path 的边界检查会有意拒绝这种逃逸。+Workspace 依次取显式 `--workspace`、所选 `.narratage/runtime` 所在项目、最近的 Source lock、+入口 Source 目录。Runtime Profile 无权改变这条源码边界。`--package-root` 只定位已经安装的+`node_modules`;`--asset-root` 只额外授权读取素材字节。外部项目通常应提交如下 `.gitignore`:-```gitignore-.svml/+```text+.narratage/output/```@@ -349,45 +259,14 @@ output/共享只读素材库不必复制进项目,也不必放宽 Source 边界:```bash-node --run narratage -- plan /work/my-film/build.svrun \- --runtime /work/my-film/svml.runtime.json \- --asset-root /work/shared-media+narratage plan /work/my-film/build.svrun --asset-root /work/shared-media````--asset-root` 可重复使用,只授权读取素材字节,不允许从那里导入 `.svml/.svs` 源码。该 Host选项不进入作者或 Build 身份;真正进入图的仍是素材内容摘要。-官方 CLI 读取外部项目的 Runtime Profile 时也会提供同一个安装位置,因此 Profile 仍可移植:--```json-{- "format": "svml.runtime-config@1",- "packageLock": "./svml.packages.lock",- "runtimePackageLock": "./svml.runtime-packages.lock",- "runtimeServices": [- { "use": "@narratage/local", "instance": "execution" },- { "use": "@narratage/store-sqlite", "instance": "state", "config": { "path": ".svml/runtime.sqlite" } },- { "use": "@narratage/artifact-store-fs", "instance": "artifacts", "config": { "path": ".svml/artifacts" } },- { "use": "@narratage/credential-store-env", "instance": "credentials.env", "config": {} }- ],- "services": {- "scheduler": "execution.scheduler",- "worker": "execution.worker",- "stores": {- "build": "state.builds",- "operations": "state.operations",- "dispatch": "state.dispatch",- "artifacts": "artifacts",- "credentials": ["credentials.env"]- }- },- "endpoints": [],- "scheduling": { "maxConcurrency": 4 }-}-```--Runtime 状态、归档 Artifact 和 lock 仍全部留在 `/work/my-film`。只有包被有意安装在 CLI-之外时,才使用 `--package-root` 或 Profile 的 `packageRoot` 覆盖位置。+Runtime Profile 只选择 Runtime 包、Runtime lock 与该 Runtime 的封闭配置。完整结构只在+[Runtime](../guide/runtime.md) 维护,不在 Quickstart 复制第二份。### 1. 同步已安装包@@ -395,8 +274,8 @@ Runtime 状态、归档 Artifact 和 lock 仍全部留在 `/work/my-film`。只```bashcd examples/talking-head-aroll-node --run narratage -- runtime use svml.runtime.json-node --run narratage -- packages sync build.svrun+narratage runtime use svml.runtime.json+narratage packages sync build.svrun```当前 Author/Run Source 选择作者包,Runtime Profile 选择环境包。`packages sync` 只把本次@@ -407,7 +286,7 @@ Provider,也不生成媒体。### 2. 诊断环境```bash-node --run narratage -- doctor+narratage doctor```Doctor 校验两份 lock、全部显式 Runtime 角色、Endpoint 配置、凭据是否存在和有界环境探测;它不启动 Worker,也不发付费请求。@@ -419,23 +298,23 @@ Doctor 校验两份 lock、全部显式 Runtime 角色、Endpoint 配置、凭### 3. 检查 Source 与计划```bash-node --run narratage -- check main.svml+narratage check main.svml``````bash-node --run narratage -- plan build.svrun+narratage plan build.svrun```在花费资金之前审查冻结的 BuildPlan。该计划展示调度器将发出的每个 Operation 和 Needs;选择Runtime 后只预检这次计划真正需要的 Endpoint、凭据和外部程序,不启动任何外部工作。`build` 会自动启动或复用后台 Runtime。只有希望提交前预热时才需要显式执行 `runtime up`;-`runtime status` 用于观察。范围更窄的 `services up|status|down` 只管理外部程序,不负责 Worker。+`runtime status` 用于观察。范围更窄的 `programs up|status|down` 只管理外部程序,不负责 Worker。### 4. 提交 Build```bash-node --run narratage -- build build.svrun --follow+narratage build build.svrun --follow```不带 `--follow` 时,Build 在耐久提交后退出,后台 Worker 继续。带 `--follow` 时终端也只是观察者,并会报告 phase / Operation 数量变化;Ctrl-C 不会取消任务。@@ -445,7 +324,7 @@ node --run narratage -- build build.svrun --follow| `--runtime` | 单次命令的 Runtime Profile 覆盖;通常用 `runtime use` 选择一次即可 || `--package-lock` | 包锁定文件的路径 || `--package-root` | 存放 lock 所列已安装包的 Host 目录 |-| `--root` | 可选的 Source Workspace 覆盖项;未传时依次使用 Runtime Profile 根、package lock 目录或入口 Source 目录 |+| `--workspace` | 显式 Source Workspace 覆盖项 || `--follow` | 将 Build 进度流式输出到终端 |每次执行都会创建新的 Build id,即使 Author Source 和 Run Source 完全没变。这是非确定性生成@@ -456,13 +335,13 @@ node --run narratage -- build build.svrun --follow### 5. 检查并获取结果```bash-node --run narratage -- inspect <build-id>+narratage inspect <build-id>````inspect` 会显示耐久 Build 状态、所需输出与已接受的 Record。确认这些事实正确后,再获取所选归档 Artifact:```bash-node --run narratage -- get <build-id> \+narratage get <build-id> \--name final.video \--to examples/talking-head-aroll/output/final.mp4```@@ -477,16 +356,16 @@ Build 的最终输出会为每个目标别名打印精确的 `get --name …`创建一个引用已完成 Build 的 Record 的新 `.svrun` 文件(参见上文 [复用结果](#复用结果)),然后提交:```bash-node --run narratage -- build reuse-generated.svrun --follow+narratage build reuse-generated.svrun --follow```### 7. 诊断或停止本地 Runtime```bash-node --run narratage -- runtime logs-node --run narratage -- runtime down+narratage runtime logs+narratage runtime down````runtime down` 只会让 Worker 停止领取新 lease,并保留外部程序;只有确实要停掉这些程序时-才执行 `services down`。两条命令都不会取消耐久 Build 或远程 Provider 工作。再次启动同一+才执行 `programs down`。两条命令都不会取消耐久 Build 或远程 Provider 工作。再次启动同一Profile 后,会继续其中尚未完成的 dispatch。diff --git a/examples/all-components-preview/svml.packages.lock b/examples/all-components-preview/svml.packages.lockindex b2b49e07..66a16863 100644--- a/examples/all-components-preview/svml.packages.lock+++ b/examples/all-components-preview/svml.packages.lock@@ -608,7 +608,7 @@{"name": "@narratage/component-kit","version": "0.0.0-dev",- "digest": "sha256:f67949d59b628490e2a371bc4fb42f546ee33648d2a82d439875757b0909f6ab"+ "digest": "sha256:a503483ab1e923d1c81473e2f3d433aacfa08703c2d81715e66aa310f170a0ae"},{"name": "@narratage/composition",@@ -843,7 +843,7 @@}],"facetsDigest": "sha256:1fbbf9bcdc39382ec612df3f29765b5d6ceb8598c0df2c7b5d6b8515f73367a3",- "closureDigest": "sha256:7ee87cd64e4788e5c6fc3deb81c2f568192b9f0030a9241ceb635d283eb4bfaa"+ "closureDigest": "sha256:790bad794d072c3bab93c3d76307b9cc836669681273ab04b1f06709dff1eb5a"},{"package": {@@ -857,7 +857,7 @@}],"facetsDigest": "sha256:73e3f528a76fdc553ba2ee87fe5beb5fb2c91b7d4fcdff4ba9e6963d4740fdf6",- "closureDigest": "sha256:c21b0177c8cb2268ba1150706973da9c6411e67c1d16b4f4a491928e6130b83a"+ "closureDigest": "sha256:894767197868c4df9cfec52541621b53298e5dcef78dc692b90dc7f73c1a2aa7"},{"package": {@@ -871,7 +871,7 @@}],"facetsDigest": "sha256:894d546ffa3c9e221fc6b686d11bc117d15a250399332e3ae1c1d28a547e0f30",- "closureDigest": "sha256:679c01ef81efbe378f077b4afda3c19ac58ed554d5ca2768ec52a5d87af6fde1"+ "closureDigest": "sha256:7ae1df06b13ad365e05f8d1b45eb045bddc832976dc612898aff0e05d0c9366f"},{"package": {@@ -885,7 +885,7 @@}],"facetsDigest": "sha256:05c22bda8c301365c1cfff2c0afa80067f3d2a0fba167a57ebf923af720a5c34",- "closureDigest": "sha256:8d42e7b295199f7775430131f7df5f3753474a44ff579ede2b8b36ae5a653e19"+ "closureDigest": "sha256:7d309e990bdfaf84168b43bd8b41a3b6f25dd394eb53c7bb34340fd59c0a67a9"},{"package": {@@ -899,7 +899,7 @@}],"facetsDigest": "sha256:a969929d929b22148363dc0dd12bc60d2e61f6e186d146554f1bcf51f55f7845",- "closureDigest": "sha256:0f7019ec7bf0e4d20f8c22c8c7d75423285069c54c19c44b968bbb38c8735c46"+ "closureDigest": "sha256:7593d4b7c035e49ce59e4e9c0f1cadf8f07fd7c086b2d4105784a83fe9e1fb7b"},{"package": {@@ -913,7 +913,7 @@}],"facetsDigest": "sha256:b96fd578be298ab154d1ad30a27d7e54ae0cf2f8f52f52d7bf13c0785d2a8da7",- "closureDigest": "sha256:fb78c8e6c91d8d8486959067ec3dc9791549e0c675689376f26462044d5c3359"+ "closureDigest": "sha256:f98b81818ae8bc4d0b5e47edb5ef9a080b092f65766178d0dad4dc7b86d74b55"},{"package": {@@ -927,7 +927,7 @@}],"facetsDigest": "sha256:de93037cec9a364da45fedc69a2d82cca93c5866e475942241c008f46c3a8da9",- "closureDigest": "sha256:55541f35bfcce5f705cd14e706c887222b79e802c2207ddf6878114ef309b23e"+ "closureDigest": "sha256:716b251dd7100f055b10dbb6c92d799f19ac1c9e3d17aeaaa38eef421ebe4512"},{"package": {@@ -941,7 +941,7 @@}],"facetsDigest": "sha256:d9ee4c44949ca2d24967e7d81898999db84ab592fdaaafe1bd6d22a28ea5e094",- "closureDigest": "sha256:7a42bf1315d3f85ac539498cacd7acfd87fe66d1f56650eacaf29046b2bd2406"+ "closureDigest": "sha256:8f86d9c4e36b2a01d484f44ea59278ec4deedd86cc1797ca6d84ba5bd2ca38ff"},{"package": {@@ -959,7 +959,7 @@}],"facetsDigest": "sha256:45c292c4b6dd39acec22e896379fca2c42f8a39c6f5211195a83a3fcc1044db5",- "closureDigest": "sha256:8ffd587fdbe759781ccb7f01984ab90fe822d9cad9b2aa01d1a9b55c246eb929"+ "closureDigest": "sha256:f870451de07aa9969902141fa74602439c53a2cac74b023cededccf7e0ae5540"},{"package": {@@ -973,7 +973,7 @@}],"facetsDigest": "sha256:7596800f1ce4506145f9ff50c768bfc07131c5ea8d421711a6b5268ce13960f7",- "closureDigest": "sha256:f784868d13286f882a1319c781181e843cb92df03b59a34fb046400fc2bf659c"+ "closureDigest": "sha256:1a45cbbbfdf5b2da33be35fdb33aac91fa7536fa29b75d3959e1fc9ae52e0bf2"},{"package": {@@ -987,7 +987,7 @@}],"facetsDigest": "sha256:9b25cec76fbf30e59177addb1c065fca7baa0a03a1eb2af141f52354ba3ce28a",- "closureDigest": "sha256:2550bc37232508707f0b83d1e70f399983da0c4b3f1ae03d1426bb8c250f39af"+ "closureDigest": "sha256:0493e3228c77d865874f431f343b3a777658690dbed099ea9789c2e53c038a2c"},{"package": {@@ -1001,7 +1001,7 @@}],"facetsDigest": "sha256:5bbef7d089f36dd1ea36b743b1b4f03289ccb8a2fc50383e3b355982916ccfc6",- "closureDigest": "sha256:9013ba2bddbda6b5b472bf2c44b9e880f1459baba2e47164f1b3a4f499095a12"+ "closureDigest": "sha256:70cbebe094cab5f1990f5effcdfd72f48a78e5cf2316b3629049d1eca34cfa35"},{"package": {@@ -1015,7 +1015,7 @@}],"facetsDigest": "sha256:a96ae88d7813e660bb496b77e53f66ed7e218b20d4e157632c9a4fd832580a92",- "closureDigest": "sha256:6a717a97a67b450827bc405f5c8100d5e3fb9d24469d89b0a1dd29077c65a03a"+ "closureDigest": "sha256:a37b9c1903ce96a1b7554147e8a48dd2104bc54dc732909edeb6a77c37f2ce36"},{"package": {@@ -1029,7 +1029,7 @@}],"facetsDigest": "sha256:c9d43bfabee11db7c1ad5f65286ef568ff51c09def5f5f05b4510fca36b0336f",- "closureDigest": "sha256:d0c9bd0bfe8394ca671eeeca3298f9f438086e45a8180d955bb28ac4aa3b97aa"+ "closureDigest": "sha256:d147833a92ccb5c520bcf8ee1545c5b62e5a8af8f46d99a7c6a86abe24976fbd"},{"package": {@@ -1071,7 +1071,7 @@}],"facetsDigest": "sha256:2f3de1f3f02d7c57ed8489c23234ae6265ded95497bf0cd60589726972e7fda7",- "closureDigest": "sha256:2957a0e696a86e7044ba1ca91a49575fa3bbf001ebfe234ff6927b7dfe5a7e76"+ "closureDigest": "sha256:c1278c09a7d7c4d4579035ed4385ca7b13e90d0ecbad6b57a29f85783930a794"},{"package": {@@ -1085,7 +1085,7 @@}],"facetsDigest": "sha256:4801d4128840216adc451dfc55593127aad41f8fec6d221e288ff7b1c7cad9c4",- "closureDigest": "sha256:2eace47bc158a08a43dac8747c45ed1eef357c0adaccb5c4f25e94f4058b0920"+ "closureDigest": "sha256:ef6888cd399b7bb949930ffb33f3f502b3a8bca60dd19730b255e92bef8a13c3"},{"package": {@@ -1099,7 +1099,7 @@}],"facetsDigest": "sha256:31b63a4bf10385d31feb50114811c5185b78a0caab6b7c1646c86a61c4958128",- "closureDigest": "sha256:0e147ec078e35a7ad8bb12ca0a0df3b6b41dcb3cca8fae30b62013c9b90b577b"+ "closureDigest": "sha256:1ba24f24c93b7aa090d41a62b6708f93364c906e483efea007bac9d399db7bf5"},{"package": {@@ -1127,7 +1127,7 @@}],"facetsDigest": "sha256:5e1d4c2c60bda7a5d25ff5393e7d2606fd0c253562d886382d1d248982cc87ca",- "closureDigest": "sha256:37dc4eaa2cedace4ee9bd8f04b563d5b3eadba42b3b292eea47a5a487b34fe1f"+ "closureDigest": "sha256:a54950e5050ab0c245438477b0cec0414c5eeefa3c0acfa1abb0f5790c59e4ed"},{"package": {@@ -1141,7 +1141,7 @@}],"facetsDigest": "sha256:acc754c61e24f93d5e2692ceb6998a3638cc384de8e512e155738435663a8342",- "closureDigest": "sha256:9627e181544189562aaed76f26da3e8dc57cef9901d0ff3cc513a61104613031"+ "closureDigest": "sha256:cbf4fe4ec28ae6958956ee67d02c8a4a30d2e4e5cbd64d8952e317c6df435fbb"},{"package": {@@ -1155,7 +1155,7 @@}],"facetsDigest": "sha256:41615659f664d3480af5a50c81df188b6fc848628c60bc82d37eb7735071f111",- "closureDigest": "sha256:084b229a2e566267e62ee6b07a219a4928e614aca0b87e2a2782beee504c62ce"+ "closureDigest": "sha256:3ea90ac12b4ac7bddce6064ac99d946aa89745c0fbf06861100415c12bd63882"},{"package": {@@ -1183,7 +1183,7 @@}],"facetsDigest": "sha256:4e6da482a365cd36423f3baf568ea741f2e0eddf26b559bce43d3c4270830c91",- "closureDigest": "sha256:b61d84f259dad599b783e3ebd236a3800e7356c6233a4e0eb6e39e61e416061c"+ "closureDigest": "sha256:dde427e997833b5ed6639deeed75070eb98bc9e50c8f0a7da8f31fefe4435724"},{"package": {@@ -1197,7 +1197,7 @@}],"facetsDigest": "sha256:e86e5c90307ab183d2ea5d75e4ca0daab4f2b65905feb79c387871370d625e3a",- "closureDigest": "sha256:fe97f366b85930ec11fcbfab56e62c11b92ce85b95480328e2229e02303bf959"+ "closureDigest": "sha256:8be1559095728f977914d56c4e7dfd070362d7bbddfb0565062129fe27a67d8d"},{"package": {@@ -1211,7 +1211,7 @@}],"facetsDigest": "sha256:b55e20b4fdf24cbfaf956447ff62885e81638fdbcbb61f25483392a1c8fac8c9",- "closureDigest": "sha256:6d5142eb1ae177537eeb19e1fdedd93a904d492002cd3dcf9d253d85932303b6"+ "closureDigest": "sha256:34ff2b938c8cdb94823a2843e882ac9d1e8f51f46dee02a6b0342b69f48c5be3"},{"package": {@@ -1225,7 +1225,7 @@}],"facetsDigest": "sha256:3e7413acb9b39071fad0ea2e99777ae9ab7a4b636041a8345ec1d08428859b3f",- "closureDigest": "sha256:d2c3ebea16f7f58a4871df4c75dc011166c69031450371c6ff8fda33ffe528d0"+ "closureDigest": "sha256:e0a9f8e7c454beb36d67e9bd358383fc91567e70e9f43f75290a831028e39576"},{"package": {@@ -1253,7 +1253,7 @@}],"facetsDigest": "sha256:340cf867483022b3896008781f24a04e22aa0abc76873cc44787aefdc0219522",- "closureDigest": "sha256:0e2332df3f9b9d295224a2bef2fdfaf06fa5454e1fac131b2137a0e814d38f91"+ "closureDigest": "sha256:f215f8ec4e02bf26ff0960b129760eeb80ab59658cd0ec0476481b73c11f09ee"},{"package": {@@ -1303,7 +1303,7 @@}],"facetsDigest": "sha256:2d4d0e9eea9ec795fb675ddf7d204bc29fe7eb8e3a743eced944a0cdb50ecf50",- "closureDigest": "sha256:48cca7d31b965ac882090e805e55044c9b44a319d4a67eefcef940614c9ee4da"+ "closureDigest": "sha256:51afff4d06131cc77a3e6953a9151564dfb79bde943f1250d91d24db1f2c00d4"},{"package": {@@ -1317,7 +1317,7 @@}],"facetsDigest": "sha256:063c2641007f401709acfed6eab95ae9c566de1e0987a06c7cdce305abe33aa7",- "closureDigest": "sha256:5ed601a7063b973faf1b80b5e6186c45c35f1342273054e46ad3ede1cdcfd003"+ "closureDigest": "sha256:489ec9e9f0bdfa329ddf39537529b95f14e79b2608c48d6031a47ce2944fdbb3"},{"package": {@@ -1345,8 +1345,8 @@}],"facetsDigest": "sha256:64c0e76dea02b19be28bc7425e11938fd9c1dbb9994dde3a6d98c41da819b85e",- "closureDigest": "sha256:57cd991e800c5c55bcbb38931b6b81a67fe32cb532f9832784d219126f11fea8"+ "closureDigest": "sha256:233b055191b86b8527083fe601c89216d7dabbce7a227123dc5d6b2117322753"}],- "digest": "sha256:be4bfc34df7f94b0bcd73ff8ae5aa6ffee4c80a789cd151595819d3bb9738345"+ "digest": "sha256:5089b8f7904a7d9782e28b7a4cd869fd398aad7ddf5fcd835b02a918933fb2ec"}diff --git a/examples/all-components-preview/svml.runtime-packages.lock b/examples/all-components-preview/svml.runtime-packages.lockindex 4f15e02e..2f109c4c 100644--- a/examples/all-components-preview/svml.runtime-packages.lock+++ b/examples/all-components-preview/svml.runtime-packages.lock@@ -40,7 +40,7 @@{"name": "@narratage/artifact-store-fs","version": "0.0.0-dev",- "digest": "sha256:0321ea7083887bb13329c6815dfb5e8bfc0a5dc711fba95c10dac625976cbda7"+ "digest": "sha256:609d09f53cba3f7367ef59502dc02f6c71d52b4f36914a0ebff8ac34703c8775"},{"name": "@narratage/artifact",@@ -65,7 +65,7 @@{"name": "@narratage/component-kit","version": "0.0.0-dev",- "digest": "sha256:f67949d59b628490e2a371bc4fb42f546ee33648d2a82d439875757b0909f6ab"+ "digest": "sha256:a503483ab1e923d1c81473e2f3d433aacfa08703c2d81715e66aa310f170a0ae"},{"name": "@narratage/composition",@@ -80,7 +80,7 @@{"name": "@narratage/credential-store-env","version": "0.0.0-dev",- "digest": "sha256:97724c0aedcacaee14699dd2fb22f73b1cfd901b85434a0376a6eb157793b3ae"+ "digest": "sha256:86ca20d6418e2c591359971f6afc59232c391fac37e3150eb5ed95adda495fe9"},{"name": "@narratage/driver-node",@@ -115,7 +115,7 @@{"name": "@narratage/local","version": "0.0.0-dev",- "digest": "sha256:53bfb88dfb3cb16a1747f7dfa9d92864fd5385c45584491577cf2f714d2d4c27"+ "digest": "sha256:ac56790c50bedb1e3380ca251463c3e41adfc1edc27cb8e6960791f95ec621de"},{"name": "@narratage/markup",@@ -165,7 +165,7 @@{"name": "@narratage/provider-hyperframes-local","version": "0.0.0-dev",- "digest": "sha256:93d1a6cce2f0e56e4f8324db405ef0ae1a863086ee0aa8363999dba7d8384427"+ "digest": "sha256:4827eaae0955d045f92ead0ee42d12521268fa8fded6372a3f53521d65ccfcba"},{"name": "@narratage/provider-kie",@@ -175,12 +175,12 @@{"name": "@narratage/provider-media-local","version": "0.0.0-dev",- "digest": "sha256:203c7dbe366f8cb1568bd9413ccd6ff3a7b10b9a7380b5568e8a4c4d58c96736"+ "digest": "sha256:eefbd7478a1c37eb3ddc28af0a70cf8fac2e1d8c37ed61a3026b36f03c8f21d4"},{"name": "@narratage/provider-whisperx-local","version": "0.0.0-dev",- "digest": "sha256:8a83f5326337865e8ff6c59eaa98ea1b1f94f9529c96f733a140705a0cff99da"+ "digest": "sha256:65e080a86701e76c9fafbe60235c38db1262557392ed7be3a0e893a73752bd30"},{"name": "@narratage/render-hyperframes",@@ -190,17 +190,17 @@{"name": "@narratage/runtime-adapter-node","version": "0.0.0-dev",- "digest": "sha256:767e12f845be87f96b13fd8e147007a5adae1ebfe2e1192d94a15590b5542601"+ "digest": "sha256:0ce0b9d4ab66c1ba248b7925a859b4654429d5cd68f4309d2932a6070456cbb6"},{"name": "@narratage/runtime-adapter","version": "0.0.0-dev",- "digest": "sha256:0c62cd7704e2e99bfece8b708174144474aeb075b2e3bea415d9c2fc50dc4c80"+ "digest": "sha256:37bfc677595841a6b4491b0066894271f252150e96b47dcd10123eecfe29cc3a"},{"name": "@narratage/runtime","version": "0.0.0-dev",- "digest": "sha256:7fed643f688774621b28eb846d68bc4e70ca98a0b04a5d0cc3a521152e50a5c6"+ "digest": "sha256:9dc9cbeb2c3124c219da91237a02693cc6cd0c3f2511f20329c0f7cddffb2d06"},{"name": "@narratage/semantic-map",@@ -235,7 +235,7 @@{"name": "@narratage/store-sqlite","version": "0.0.0-dev",- "digest": "sha256:a277e24e32632a113b4b4713d3d3bce9eaef289ccc30a5f889c6fef935cb228a"+ "digest": "sha256:35e7243a129b0db8d7b1c9876411015e8c48cdb241506bfae5cbec7dfc2d512b"},{"name": "@narratage/svs",@@ -916,12 +916,12 @@},"offers": [{- "abi": "svml.runtime-service-adapter-host@1",+ "abi": "svml.runtime-component-adapter-host@1","name": "@narratage/artifact-store-fs"}],- "facetsDigest": "sha256:89812ac838e22ffcec73619ddb033f6f9150c916e0a52693ec920cb9f41f13ff",- "closureDigest": "sha256:7a9bdee0c11fb6412e9a7ce176a3af25ff0fb0b2c40cfbd46f223e6b00cb8003"+ "facetsDigest": "sha256:d06bf1c242e6b819ab605471f7332e1150e1ebf5f81e08cf77f9bfff082ea197",+ "closureDigest": "sha256:941a2c17d30e3cc733a8415557aecd80c45b7de0493ee69b670270fc7e492ae2"},{"package": {@@ -930,12 +930,12 @@},"offers": [{- "abi": "svml.runtime-service-adapter-host@1",+ "abi": "svml.runtime-component-adapter-host@1","name": "@narratage/credential-store-env"}],- "facetsDigest": "sha256:b2a771b23ea9dcdada76501804c717cc4509579244acbb09babc0807cb26401a",- "closureDigest": "sha256:24df31243ffc21fe8429a5c3f2584de75cf3189727a7c27e773bd81ca9e0af30"+ "facetsDigest": "sha256:cac24cfb3965fe73d76c8b90e1fb676ff5f7606928fb38ff3b1aeb8eb9e3ea0e",+ "closureDigest": "sha256:e3dfea4ee0734eb0ae53593b5aaae2ee05d652aa6322055e0dc0d3a58e4009b1"},{"package": {@@ -944,12 +944,16 @@},"offers": [{- "abi": "svml.runtime-service-adapter-host@1",+ "abi": "svml.node-runtime-host-adapter@1",+ "name": "@narratage/local"+ },+ {+ "abi": "svml.runtime-component-adapter-host@1","name": "@narratage/local"}],- "facetsDigest": "sha256:bacc2fe27612f029aeef34236fd5fa687259e08c980c310adc8118be2cceeaba",- "closureDigest": "sha256:5019f5018c2a8b746382a8ba838c57855af0bbf155e82c2a3b6ac87aa37f4390"+ "facetsDigest": "sha256:552616c833a22031c623b0ad24f08a843f72f332eff2113032d63e2539d42e88",+ "closureDigest": "sha256:8baca82be34ae891ca52c8835e23116e51ccf59086ae3f90243f5c41bc6c12f0"},{"package": {@@ -963,7 +967,7 @@}],"facetsDigest": "sha256:485fc29d1efcdaeb4e395980975b35090ea6aef0f78d02108d3bd9b3f11aeb91",- "closureDigest": "sha256:ccd1e3307e9ebffceb5e0cf98e03868b9e2484b364d16f8f19eefbe234d36105"+ "closureDigest": "sha256:a9c49b1ee0b7e446739c552f006efdb2e02a6fbd95026be9ac2e2a4f579bcbff"},{"package": {@@ -977,7 +981,7 @@}],"facetsDigest": "sha256:e08dde3e4d38b167dca29cdc54eb2bb5e9ebc294e0e42b371099d53d6c44b402",- "closureDigest": "sha256:cfadfcd967b2a7b5d51c6852d1f1045167734609dbcdd05a83de8eeff34f2f6d"+ "closureDigest": "sha256:8716f0eda32fec48f21cccfdb15b953f6708100923be2f9d1ed577c10db40f19"},{"package": {@@ -991,7 +995,7 @@}],"facetsDigest": "sha256:110648301d69b5b49ea553d285a27626f6fb74ebc74ee67175f688f914d7d74b",- "closureDigest": "sha256:c6105b8f3a5583f35e48ba3e9882f6a4a76adfc9f19a31877c3c6c7f8957bbc8"+ "closureDigest": "sha256:f7f87ad8a1ad76f950edf27bbd8a69bc9080da2b408fec8945d619cea8bf3208"},{"package": {@@ -1005,7 +1009,7 @@}],"facetsDigest": "sha256:998de772acb283828fee16310e77922bf43597bca1efa768e8398166a90af27d",- "closureDigest": "sha256:c59d8d31a59a5f26b9a064789e16e6db9505d26e170eb21350ee3104922a737d"+ "closureDigest": "sha256:d8386c799c6f77909767076e81a3932be033bf24e0eb65b07f79a14e7bf759a8"},{"package": {@@ -1019,7 +1023,7 @@}],"facetsDigest": "sha256:e7d4f1e2fd56f2bcb5dbc36e1faae48d2680bb839aed4a43eb0cb23207ffbe1d",- "closureDigest": "sha256:75c92b5ae14e4672ceba48b91376363f6648574f7d3655329deae60ba9c20807"+ "closureDigest": "sha256:8e38557baf5fb4c5abcdc4f6a702a8e792fd19b36a088e0f9fee6a68577e367b"},{"package": {@@ -1028,13 +1032,13 @@},"offers": [{- "abi": "svml.runtime-service-adapter-host@1",+ "abi": "svml.runtime-component-adapter-host@1","name": "@narratage/store-sqlite"}],- "facetsDigest": "sha256:eb9df1ee7597620bc2e80c168971e020f77cd0880608957ca3048cac7c559c28",- "closureDigest": "sha256:e7ab56c71e2fc2b11fccdfadc2c95fb0929e6a3bd4af1bf28577bff4758ea73c"+ "facetsDigest": "sha256:dcd11bfeb19b68e69aeecd31d34de36045dd92e36039d651385081ce4180080b",+ "closureDigest": "sha256:dbc85921b27942e27a5fde033803962733f20970536cbdfd2059ff249e22d946"}],- "digest": "sha256:6984ff6c3e2d79950e3fae3f486718ebad0f4fab8376e4322e1bc2c90b5039e6"+ "digest": "sha256:a038c726f4d7a38e761a8d07b317187e7bd1178130560e0aeeeaa6c75c2fcd30"}diff --git a/examples/all-components-preview/svml.runtime.json b/examples/all-components-preview/svml.runtime.jsonindex 67e1db15..940b4c44 100644--- a/examples/all-components-preview/svml.runtime.json+++ b/examples/all-components-preview/svml.runtime.json@@ -1,98 +1,63 @@{- "format": "svml.runtime-config@1",- "packageLock": "./svml.packages.lock",+ "format": "narratage.runtime-profile@1","runtimePackageLock": "./svml.runtime-packages.lock",- "runtimeServices": [- {- "use": "@narratage/local",- "instance": "execution"- },- {- "use": "@narratage/store-sqlite",- "instance": "state",- "config": {- "path": ".svml/runtime.sqlite"- }- },- {- "use": "@narratage/artifact-store-fs",- "instance": "artifacts",- "config": {- "path": ".svml/artifacts"- }- },- {- "use": "@narratage/credential-store-env",- "instance": "credentials.env",- "config": {}- }- ],- "services": {- "scheduler": "execution.scheduler",- "worker": "execution.worker",- "stores": {- "build": "state.builds",- "operations": "state.operations",- "dispatch": "state.dispatch",- "artifacts": "artifacts",- "credentials": [- "credentials.env"- ]- }- },- "endpoints": [- {- "use": "@narratage/provider-kie",- "instance": "kie.all-components",- "authority": "generation",- "config": {- "apiKey": {- "store": "env",- "key": "KIE_API_KEY"+ "runtime": {+ "use": "@narratage/local",+ "config": {+ "dataRoot": ".narratage/runtimes/local",+ "components": {+ "execution": { "use": "@narratage/local" },+ "state": { "use": "@narratage/store-sqlite", "config": { "path": "state.sqlite" } },+ "artifacts": { "use": "@narratage/artifact-store-fs", "config": { "path": "artifacts" } },+ "credentials.env": { "use": "@narratage/credential-store-env", "config": {} }+ },+ "bindings": {+ "scheduler": "execution.scheduler",+ "worker": "execution.worker",+ "stores": {+ "build": "state.builds",+ "operations": "state.operations",+ "dispatch": "state.dispatch",+ "artifacts": "artifacts",+ "credentials": ["credentials.env"]+ }+ },+ "endpoints": {+ "kie.all-components": {+ "use": "@narratage/provider-kie",+ "authority": "generation",+ "config": {+ "apiKey": { "store": "env", "key": "KIE_API_KEY" },+ "defaultConcurrency": 2+ }+ },+ "media.all-components": {+ "use": "@narratage/provider-media-local",+ "authority": "media",+ "config": { "defaultConcurrency": 2 }+ },+ "whisperx.all-components": {+ "use": "@narratage/provider-whisperx-local",+ "authority": "alignment",+ "config": { "defaultConcurrency": 1 }},- "defaultConcurrency": 2- }- },- {- "use": "@narratage/provider-media-local",- "instance": "media.all-components",- "authority": "media",- "config": {- "defaultConcurrency": 2- }- },- {- "use": "@narratage/provider-whisperx-local",- "instance": "whisperx.all-components",- "authority": "alignment",- "config": {- "defaultConcurrency": 1- }- },- {- "use": "@narratage/provider-hyperframes-local",- "instance": "hyperframes.all-components",- "authority": "render",- "config": {- "defaultConcurrency": 1- }- },- {- "use": "@narratage/provider-google-vertex",- "instance": "vertex.all-components",- "authority": "planning",- "config": {- "projectEnv": "GOOGLE_CLOUD_PROJECT",- "location": "global",- "credentials": {- "store": "env",- "key": "GOOGLE_VERTEX_CREDENTIALS_JSON"+ "hyperframes.all-components": {+ "use": "@narratage/provider-hyperframes-local",+ "authority": "render",+ "config": { "defaultConcurrency": 1 }},- "defaultConcurrency": 1- }+ "vertex.all-components": {+ "use": "@narratage/provider-google-vertex",+ "authority": "planning",+ "config": {+ "projectEnv": "GOOGLE_CLOUD_PROJECT",+ "location": "global",+ "credentials": { "store": "env", "key": "GOOGLE_VERTEX_CREDENTIALS_JSON" },+ "defaultConcurrency": 1+ }+ }+ },+ "limits": { "maxOperations": 4 }}- ],- "scheduling": {- "maxConcurrency": 4}}diff --git a/examples/talking-film-graph-check/svml.packages.lock b/examples/talking-film-graph-check/svml.packages.lockindex ffde59b6..8ff88f38 100644--- a/examples/talking-film-graph-check/svml.packages.lock+++ b/examples/talking-film-graph-check/svml.packages.lock@@ -602,7 +602,7 @@{"name": "@narratage/component-kit","version": "0.0.0-dev",- "digest": "sha256:f67949d59b628490e2a371bc4fb42f546ee33648d2a82d439875757b0909f6ab"+ "digest": "sha256:a503483ab1e923d1c81473e2f3d433aacfa08703c2d81715e66aa310f170a0ae"},{"name": "@narratage/composition",@@ -807,7 +807,7 @@}],"facetsDigest": "sha256:1fbbf9bcdc39382ec612df3f29765b5d6ceb8598c0df2c7b5d6b8515f73367a3",- "closureDigest": "sha256:7ee87cd64e4788e5c6fc3deb81c2f568192b9f0030a9241ceb635d283eb4bfaa"+ "closureDigest": "sha256:790bad794d072c3bab93c3d76307b9cc836669681273ab04b1f06709dff1eb5a"},{"package": {@@ -821,7 +821,7 @@}],"facetsDigest": "sha256:73e3f528a76fdc553ba2ee87fe5beb5fb2c91b7d4fcdff4ba9e6963d4740fdf6",- "closureDigest": "sha256:c21b0177c8cb2268ba1150706973da9c6411e67c1d16b4f4a491928e6130b83a"+ "closureDigest": "sha256:894767197868c4df9cfec52541621b53298e5dcef78dc692b90dc7f73c1a2aa7"},{"package": {@@ -835,7 +835,7 @@}],"facetsDigest": "sha256:894d546ffa3c9e221fc6b686d11bc117d15a250399332e3ae1c1d28a547e0f30",- "closureDigest": "sha256:679c01ef81efbe378f077b4afda3c19ac58ed554d5ca2768ec52a5d87af6fde1"+ "closureDigest": "sha256:7ae1df06b13ad365e05f8d1b45eb045bddc832976dc612898aff0e05d0c9366f"},{"package": {@@ -849,7 +849,7 @@}],"facetsDigest": "sha256:05c22bda8c301365c1cfff2c0afa80067f3d2a0fba167a57ebf923af720a5c34",- "closureDigest": "sha256:8d42e7b295199f7775430131f7df5f3753474a44ff579ede2b8b36ae5a653e19"+ "closureDigest": "sha256:7d309e990bdfaf84168b43bd8b41a3b6f25dd394eb53c7bb34340fd59c0a67a9"},{"package": {@@ -863,7 +863,7 @@}],"facetsDigest": "sha256:b96fd578be298ab154d1ad30a27d7e54ae0cf2f8f52f52d7bf13c0785d2a8da7",- "closureDigest": "sha256:fb78c8e6c91d8d8486959067ec3dc9791549e0c675689376f26462044d5c3359"+ "closureDigest": "sha256:f98b81818ae8bc4d0b5e47edb5ef9a080b092f65766178d0dad4dc7b86d74b55"},{"package": {@@ -877,7 +877,7 @@}],"facetsDigest": "sha256:de93037cec9a364da45fedc69a2d82cca93c5866e475942241c008f46c3a8da9",- "closureDigest": "sha256:55541f35bfcce5f705cd14e706c887222b79e802c2207ddf6878114ef309b23e"+ "closureDigest": "sha256:716b251dd7100f055b10dbb6c92d799f19ac1c9e3d17aeaaa38eef421ebe4512"},{"package": {@@ -891,7 +891,7 @@}],"facetsDigest": "sha256:d9ee4c44949ca2d24967e7d81898999db84ab592fdaaafe1bd6d22a28ea5e094",- "closureDigest": "sha256:7a42bf1315d3f85ac539498cacd7acfd87fe66d1f56650eacaf29046b2bd2406"+ "closureDigest": "sha256:8f86d9c4e36b2a01d484f44ea59278ec4deedd86cc1797ca6d84ba5bd2ca38ff"},{"package": {@@ -905,7 +905,7 @@}],"facetsDigest": "sha256:7596800f1ce4506145f9ff50c768bfc07131c5ea8d421711a6b5268ce13960f7",- "closureDigest": "sha256:f784868d13286f882a1319c781181e843cb92df03b59a34fb046400fc2bf659c"+ "closureDigest": "sha256:1a45cbbbfdf5b2da33be35fdb33aac91fa7536fa29b75d3959e1fc9ae52e0bf2"},{"package": {@@ -919,7 +919,7 @@}],"facetsDigest": "sha256:5bbef7d089f36dd1ea36b743b1b4f03289ccb8a2fc50383e3b355982916ccfc6",- "closureDigest": "sha256:9013ba2bddbda6b5b472bf2c44b9e880f1459baba2e47164f1b3a4f499095a12"+ "closureDigest": "sha256:70cbebe094cab5f1990f5effcdfd72f48a78e5cf2316b3629049d1eca34cfa35"},{"package": {@@ -933,7 +933,7 @@}],"facetsDigest": "sha256:a96ae88d7813e660bb496b77e53f66ed7e218b20d4e157632c9a4fd832580a92",- "closureDigest": "sha256:6a717a97a67b450827bc405f5c8100d5e3fb9d24469d89b0a1dd29077c65a03a"+ "closureDigest": "sha256:a37b9c1903ce96a1b7554147e8a48dd2104bc54dc732909edeb6a77c37f2ce36"},{"package": {@@ -947,7 +947,7 @@}],"facetsDigest": "sha256:c9d43bfabee11db7c1ad5f65286ef568ff51c09def5f5f05b4510fca36b0336f",- "closureDigest": "sha256:d0c9bd0bfe8394ca671eeeca3298f9f438086e45a8180d955bb28ac4aa3b97aa"+ "closureDigest": "sha256:d147833a92ccb5c520bcf8ee1545c5b62e5a8af8f46d99a7c6a86abe24976fbd"},{"package": {@@ -989,7 +989,7 @@}],"facetsDigest": "sha256:31b63a4bf10385d31feb50114811c5185b78a0caab6b7c1646c86a61c4958128",- "closureDigest": "sha256:0e147ec078e35a7ad8bb12ca0a0df3b6b41dcb3cca8fae30b62013c9b90b577b"+ "closureDigest": "sha256:1ba24f24c93b7aa090d41a62b6708f93364c906e483efea007bac9d399db7bf5"},{"package": {@@ -1017,7 +1017,7 @@}],"facetsDigest": "sha256:acc754c61e24f93d5e2692ceb6998a3638cc384de8e512e155738435663a8342",- "closureDigest": "sha256:9627e181544189562aaed76f26da3e8dc57cef9901d0ff3cc513a61104613031"+ "closureDigest": "sha256:cbf4fe4ec28ae6958956ee67d02c8a4a30d2e4e5cbd64d8952e317c6df435fbb"},{"package": {@@ -1031,7 +1031,7 @@}],"facetsDigest": "sha256:41615659f664d3480af5a50c81df188b6fc848628c60bc82d37eb7735071f111",- "closureDigest": "sha256:084b229a2e566267e62ee6b07a219a4928e614aca0b87e2a2782beee504c62ce"+ "closureDigest": "sha256:3ea90ac12b4ac7bddce6064ac99d946aa89745c0fbf06861100415c12bd63882"},{"package": {@@ -1059,7 +1059,7 @@}],"facetsDigest": "sha256:4e6da482a365cd36423f3baf568ea741f2e0eddf26b559bce43d3c4270830c91",- "closureDigest": "sha256:b61d84f259dad599b783e3ebd236a3800e7356c6233a4e0eb6e39e61e416061c"+ "closureDigest": "sha256:dde427e997833b5ed6639deeed75070eb98bc9e50c8f0a7da8f31fefe4435724"},{"package": {@@ -1073,7 +1073,7 @@}],"facetsDigest": "sha256:e86e5c90307ab183d2ea5d75e4ca0daab4f2b65905feb79c387871370d625e3a",- "closureDigest": "sha256:fe97f366b85930ec11fcbfab56e62c11b92ce85b95480328e2229e02303bf959"+ "closureDigest": "sha256:8be1559095728f977914d56c4e7dfd070362d7bbddfb0565062129fe27a67d8d"},{"package": {@@ -1087,7 +1087,7 @@}],"facetsDigest": "sha256:b55e20b4fdf24cbfaf956447ff62885e81638fdbcbb61f25483392a1c8fac8c9",- "closureDigest": "sha256:6d5142eb1ae177537eeb19e1fdedd93a904d492002cd3dcf9d253d85932303b6"+ "closureDigest": "sha256:34ff2b938c8cdb94823a2843e882ac9d1e8f51f46dee02a6b0342b69f48c5be3"},{"package": {@@ -1101,7 +1101,7 @@}],"facetsDigest": "sha256:3e7413acb9b39071fad0ea2e99777ae9ab7a4b636041a8345ec1d08428859b3f",- "closureDigest": "sha256:d2c3ebea16f7f58a4871df4c75dc011166c69031450371c6ff8fda33ffe528d0"+ "closureDigest": "sha256:e0a9f8e7c454beb36d67e9bd358383fc91567e70e9f43f75290a831028e39576"},{"package": {@@ -1129,7 +1129,7 @@}],"facetsDigest": "sha256:340cf867483022b3896008781f24a04e22aa0abc76873cc44787aefdc0219522",- "closureDigest": "sha256:0e2332df3f9b9d295224a2bef2fdfaf06fa5454e1fac131b2137a0e814d38f91"+ "closureDigest": "sha256:f215f8ec4e02bf26ff0960b129760eeb80ab59658cd0ec0476481b73c11f09ee"},{"package": {@@ -1179,7 +1179,7 @@}],"facetsDigest": "sha256:2d4d0e9eea9ec795fb675ddf7d204bc29fe7eb8e3a743eced944a0cdb50ecf50",- "closureDigest": "sha256:48cca7d31b965ac882090e805e55044c9b44a319d4a67eefcef940614c9ee4da"+ "closureDigest": "sha256:51afff4d06131cc77a3e6953a9151564dfb79bde943f1250d91d24db1f2c00d4"},{"package": {@@ -1193,7 +1193,7 @@}],"facetsDigest": "sha256:063c2641007f401709acfed6eab95ae9c566de1e0987a06c7cdce305abe33aa7",- "closureDigest": "sha256:5ed601a7063b973faf1b80b5e6186c45c35f1342273054e46ad3ede1cdcfd003"+ "closureDigest": "sha256:489ec9e9f0bdfa329ddf39537529b95f14e79b2608c48d6031a47ce2944fdbb3"},{"package": {@@ -1221,8 +1221,8 @@}],"facetsDigest": "sha256:64c0e76dea02b19be28bc7425e11938fd9c1dbb9994dde3a6d98c41da819b85e",- "closureDigest": "sha256:57cd991e800c5c55bcbb38931b6b81a67fe32cb532f9832784d219126f11fea8"+ "closureDigest": "sha256:233b055191b86b8527083fe601c89216d7dabbce7a227123dc5d6b2117322753"}],- "digest": "sha256:9452b4bc7121b5809bf02863dd066b9c05dfd0b9482f6b8965f1c3b2f8e9f926"+ "digest": "sha256:f48396a2f7f8cafe5383bea15ca6c4669a9f0e9214000ba8615cf26a8bcbc6ab"}diff --git a/examples/talking-film-live/svml.packages.lock b/examples/talking-film-live/svml.packages.lockindex d123f3ce..d1efd8a0 100644--- a/examples/talking-film-live/svml.packages.lock+++ b/examples/talking-film-live/svml.packages.lock@@ -588,7 +588,7 @@{"name": "@narratage/component-kit","version": "0.0.0-dev",- "digest": "sha256:f67949d59b628490e2a371bc4fb42f546ee33648d2a82d439875757b0909f6ab"+ "digest": "sha256:a503483ab1e923d1c81473e2f3d433aacfa08703c2d81715e66aa310f170a0ae"},{"name": "@narratage/composition",@@ -803,7 +803,7 @@}],"facetsDigest": "sha256:1fbbf9bcdc39382ec612df3f29765b5d6ceb8598c0df2c7b5d6b8515f73367a3",- "closureDigest": "sha256:7ee87cd64e4788e5c6fc3deb81c2f568192b9f0030a9241ceb635d283eb4bfaa"+ "closureDigest": "sha256:790bad794d072c3bab93c3d76307b9cc836669681273ab04b1f06709dff1eb5a"},{"package": {@@ -817,7 +817,7 @@}],"facetsDigest": "sha256:73e3f528a76fdc553ba2ee87fe5beb5fb2c91b7d4fcdff4ba9e6963d4740fdf6",- "closureDigest": "sha256:c21b0177c8cb2268ba1150706973da9c6411e67c1d16b4f4a491928e6130b83a"+ "closureDigest": "sha256:894767197868c4df9cfec52541621b53298e5dcef78dc692b90dc7f73c1a2aa7"},{"package": {@@ -831,7 +831,7 @@}],"facetsDigest": "sha256:894d546ffa3c9e221fc6b686d11bc117d15a250399332e3ae1c1d28a547e0f30",- "closureDigest": "sha256:679c01ef81efbe378f077b4afda3c19ac58ed554d5ca2768ec52a5d87af6fde1"+ "closureDigest": "sha256:7ae1df06b13ad365e05f8d1b45eb045bddc832976dc612898aff0e05d0c9366f"},{"package": {@@ -845,7 +845,7 @@}],"facetsDigest": "sha256:05c22bda8c301365c1cfff2c0afa80067f3d2a0fba167a57ebf923af720a5c34",- "closureDigest": "sha256:8d42e7b295199f7775430131f7df5f3753474a44ff579ede2b8b36ae5a653e19"+ "closureDigest": "sha256:7d309e990bdfaf84168b43bd8b41a3b6f25dd394eb53c7bb34340fd59c0a67a9"},{"package": {@@ -859,7 +859,7 @@}],"facetsDigest": "sha256:c22a49bd60d2e8061f9cd57c57869a6bcdcfb1a39886ad68f5f4f62a8ddc663a",- "closureDigest": "sha256:eb417038512a811a82dfbcd0a5b17c18e20e28b4e2df950a351c82e3a42263ea"+ "closureDigest": "sha256:85f440f06d6e65eeb3ca38768a6a64796994ead70a78e4d9fc518697b0da71c3"},{"package": {@@ -873,7 +873,7 @@}],"facetsDigest": "sha256:b96fd578be298ab154d1ad30a27d7e54ae0cf2f8f52f52d7bf13c0785d2a8da7",- "closureDigest": "sha256:fb78c8e6c91d8d8486959067ec3dc9791549e0c675689376f26462044d5c3359"+ "closureDigest": "sha256:f98b81818ae8bc4d0b5e47edb5ef9a080b092f65766178d0dad4dc7b86d74b55"},{"package": {@@ -887,7 +887,7 @@}],"facetsDigest": "sha256:de93037cec9a364da45fedc69a2d82cca93c5866e475942241c008f46c3a8da9",- "closureDigest": "sha256:55541f35bfcce5f705cd14e706c887222b79e802c2207ddf6878114ef309b23e"+ "closureDigest": "sha256:716b251dd7100f055b10dbb6c92d799f19ac1c9e3d17aeaaa38eef421ebe4512"},{"package": {@@ -901,7 +901,7 @@}],"facetsDigest": "sha256:d9ee4c44949ca2d24967e7d81898999db84ab592fdaaafe1bd6d22a28ea5e094",- "closureDigest": "sha256:7a42bf1315d3f85ac539498cacd7acfd87fe66d1f56650eacaf29046b2bd2406"+ "closureDigest": "sha256:8f86d9c4e36b2a01d484f44ea59278ec4deedd86cc1797ca6d84ba5bd2ca38ff"},{"package": {@@ -915,7 +915,7 @@}],"facetsDigest": "sha256:7596800f1ce4506145f9ff50c768bfc07131c5ea8d421711a6b5268ce13960f7",- "closureDigest": "sha256:f784868d13286f882a1319c781181e843cb92df03b59a34fb046400fc2bf659c"+ "closureDigest": "sha256:1a45cbbbfdf5b2da33be35fdb33aac91fa7536fa29b75d3959e1fc9ae52e0bf2"},{"package": {@@ -929,7 +929,7 @@}],"facetsDigest": "sha256:5bbef7d089f36dd1ea36b743b1b4f03289ccb8a2fc50383e3b355982916ccfc6",- "closureDigest": "sha256:9013ba2bddbda6b5b472bf2c44b9e880f1459baba2e47164f1b3a4f499095a12"+ "closureDigest": "sha256:70cbebe094cab5f1990f5effcdfd72f48a78e5cf2316b3629049d1eca34cfa35"},{"package": {@@ -943,7 +943,7 @@}],"facetsDigest": "sha256:a96ae88d7813e660bb496b77e53f66ed7e218b20d4e157632c9a4fd832580a92",- "closureDigest": "sha256:6a717a97a67b450827bc405f5c8100d5e3fb9d24469d89b0a1dd29077c65a03a"+ "closureDigest": "sha256:a37b9c1903ce96a1b7554147e8a48dd2104bc54dc732909edeb6a77c37f2ce36"},{"package": {@@ -985,7 +985,7 @@}],"facetsDigest": "sha256:31b63a4bf10385d31feb50114811c5185b78a0caab6b7c1646c86a61c4958128",- "closureDigest": "sha256:0e147ec078e35a7ad8bb12ca0a0df3b6b41dcb3cca8fae30b62013c9b90b577b"+ "closureDigest": "sha256:1ba24f24c93b7aa090d41a62b6708f93364c906e483efea007bac9d399db7bf5"},{"package": {@@ -1013,7 +1013,7 @@}],"facetsDigest": "sha256:acc754c61e24f93d5e2692ceb6998a3638cc384de8e512e155738435663a8342",- "closureDigest": "sha256:9627e181544189562aaed76f26da3e8dc57cef9901d0ff3cc513a61104613031"+ "closureDigest": "sha256:cbf4fe4ec28ae6958956ee67d02c8a4a30d2e4e5cbd64d8952e317c6df435fbb"},{"package": {@@ -1027,7 +1027,7 @@}],"facetsDigest": "sha256:41615659f664d3480af5a50c81df188b6fc848628c60bc82d37eb7735071f111",- "closureDigest": "sha256:084b229a2e566267e62ee6b07a219a4928e614aca0b87e2a2782beee504c62ce"+ "closureDigest": "sha256:3ea90ac12b4ac7bddce6064ac99d946aa89745c0fbf06861100415c12bd63882"},{"package": {@@ -1055,7 +1055,7 @@}],"facetsDigest": "sha256:4e6da482a365cd36423f3baf568ea741f2e0eddf26b559bce43d3c4270830c91",- "closureDigest": "sha256:b61d84f259dad599b783e3ebd236a3800e7356c6233a4e0eb6e39e61e416061c"+ "closureDigest": "sha256:dde427e997833b5ed6639deeed75070eb98bc9e50c8f0a7da8f31fefe4435724"},{"package": {@@ -1069,7 +1069,7 @@}],"facetsDigest": "sha256:e86e5c90307ab183d2ea5d75e4ca0daab4f2b65905feb79c387871370d625e3a",- "closureDigest": "sha256:fe97f366b85930ec11fcbfab56e62c11b92ce85b95480328e2229e02303bf959"+ "closureDigest": "sha256:8be1559095728f977914d56c4e7dfd070362d7bbddfb0565062129fe27a67d8d"},{"package": {@@ -1083,7 +1083,7 @@}],"facetsDigest": "sha256:b55e20b4fdf24cbfaf956447ff62885e81638fdbcbb61f25483392a1c8fac8c9",- "closureDigest": "sha256:6d5142eb1ae177537eeb19e1fdedd93a904d492002cd3dcf9d253d85932303b6"+ "closureDigest": "sha256:34ff2b938c8cdb94823a2843e882ac9d1e8f51f46dee02a6b0342b69f48c5be3"},{"package": {@@ -1097,7 +1097,7 @@}],"facetsDigest": "sha256:3e7413acb9b39071fad0ea2e99777ae9ab7a4b636041a8345ec1d08428859b3f",- "closureDigest": "sha256:d2c3ebea16f7f58a4871df4c75dc011166c69031450371c6ff8fda33ffe528d0"+ "closureDigest": "sha256:e0a9f8e7c454beb36d67e9bd358383fc91567e70e9f43f75290a831028e39576"},{"package": {@@ -1125,7 +1125,7 @@}],"facetsDigest": "sha256:340cf867483022b3896008781f24a04e22aa0abc76873cc44787aefdc0219522",- "closureDigest": "sha256:0e2332df3f9b9d295224a2bef2fdfaf06fa5454e1fac131b2137a0e814d38f91"+ "closureDigest": "sha256:f215f8ec4e02bf26ff0960b129760eeb80ab59658cd0ec0476481b73c11f09ee"},{"package": {@@ -1161,7 +1161,7 @@}],"facetsDigest": "sha256:2d4d0e9eea9ec795fb675ddf7d204bc29fe7eb8e3a743eced944a0cdb50ecf50",- "closureDigest": "sha256:48cca7d31b965ac882090e805e55044c9b44a319d4a67eefcef940614c9ee4da"+ "closureDigest": "sha256:51afff4d06131cc77a3e6953a9151564dfb79bde943f1250d91d24db1f2c00d4"},{"package": {@@ -1175,7 +1175,7 @@}],"facetsDigest": "sha256:063c2641007f401709acfed6eab95ae9c566de1e0987a06c7cdce305abe33aa7",- "closureDigest": "sha256:5ed601a7063b973faf1b80b5e6186c45c35f1342273054e46ad3ede1cdcfd003"+ "closureDigest": "sha256:489ec9e9f0bdfa329ddf39537529b95f14e79b2608c48d6031a47ce2944fdbb3"},{"package": {@@ -1203,8 +1203,8 @@}],"facetsDigest": "sha256:64c0e76dea02b19be28bc7425e11938fd9c1dbb9994dde3a6d98c41da819b85e",- "closureDigest": "sha256:57cd991e800c5c55bcbb38931b6b81a67fe32cb532f9832784d219126f11fea8"+ "closureDigest": "sha256:233b055191b86b8527083fe601c89216d7dabbce7a227123dc5d6b2117322753"}],- "digest": "sha256:238a25aa5e86efa7791ee849831868e938991fe6fbeb18eca8d2ace649ebefa6"+ "digest": "sha256:08cea3a161efc3a7c06c73a3ac5ccbaf3bcefa4894798a03cf088f8b2d18347f"}diff --git a/examples/talking-film-live/svml.runtime-packages.lock b/examples/talking-film-live/svml.runtime-packages.lockindex 4f15e02e..2f109c4c 100644--- a/examples/talking-film-live/svml.runtime-packages.lock+++ b/examples/talking-film-live/svml.runtime-packages.lock@@ -40,7 +40,7 @@{"name": "@narratage/artifact-store-fs","version": "0.0.0-dev",- "digest": "sha256:0321ea7083887bb13329c6815dfb5e8bfc0a5dc711fba95c10dac625976cbda7"+ "digest": "sha256:609d09f53cba3f7367ef59502dc02f6c71d52b4f36914a0ebff8ac34703c8775"},{"name": "@narratage/artifact",@@ -65,7 +65,7 @@{"name": "@narratage/component-kit","version": "0.0.0-dev",- "digest": "sha256:f67949d59b628490e2a371bc4fb42f546ee33648d2a82d439875757b0909f6ab"+ "digest": "sha256:a503483ab1e923d1c81473e2f3d433aacfa08703c2d81715e66aa310f170a0ae"},{"name": "@narratage/composition",@@ -80,7 +80,7 @@{"name": "@narratage/credential-store-env","version": "0.0.0-dev",- "digest": "sha256:97724c0aedcacaee14699dd2fb22f73b1cfd901b85434a0376a6eb157793b3ae"+ "digest": "sha256:86ca20d6418e2c591359971f6afc59232c391fac37e3150eb5ed95adda495fe9"},{"name": "@narratage/driver-node",@@ -115,7 +115,7 @@{"name": "@narratage/local","version": "0.0.0-dev",- "digest": "sha256:53bfb88dfb3cb16a1747f7dfa9d92864fd5385c45584491577cf2f714d2d4c27"+ "digest": "sha256:ac56790c50bedb1e3380ca251463c3e41adfc1edc27cb8e6960791f95ec621de"},{"name": "@narratage/markup",@@ -165,7 +165,7 @@{"name": "@narratage/provider-hyperframes-local","version": "0.0.0-dev",- "digest": "sha256:93d1a6cce2f0e56e4f8324db405ef0ae1a863086ee0aa8363999dba7d8384427"+ "digest": "sha256:4827eaae0955d045f92ead0ee42d12521268fa8fded6372a3f53521d65ccfcba"},{"name": "@narratage/provider-kie",@@ -175,12 +175,12 @@{"name": "@narratage/provider-media-local","version": "0.0.0-dev",- "digest": "sha256:203c7dbe366f8cb1568bd9413ccd6ff3a7b10b9a7380b5568e8a4c4d58c96736"+ "digest": "sha256:eefbd7478a1c37eb3ddc28af0a70cf8fac2e1d8c37ed61a3026b36f03c8f21d4"},{"name": "@narratage/provider-whisperx-local","version": "0.0.0-dev",- "digest": "sha256:8a83f5326337865e8ff6c59eaa98ea1b1f94f9529c96f733a140705a0cff99da"+ "digest": "sha256:65e080a86701e76c9fafbe60235c38db1262557392ed7be3a0e893a73752bd30"},{"name": "@narratage/render-hyperframes",@@ -190,17 +190,17 @@{"name": "@narratage/runtime-adapter-node","version": "0.0.0-dev",- "digest": "sha256:767e12f845be87f96b13fd8e147007a5adae1ebfe2e1192d94a15590b5542601"+ "digest": "sha256:0ce0b9d4ab66c1ba248b7925a859b4654429d5cd68f4309d2932a6070456cbb6"},{"name": "@narratage/runtime-adapter","version": "0.0.0-dev",- "digest": "sha256:0c62cd7704e2e99bfece8b708174144474aeb075b2e3bea415d9c2fc50dc4c80"+ "digest": "sha256:37bfc677595841a6b4491b0066894271f252150e96b47dcd10123eecfe29cc3a"},{"name": "@narratage/runtime","version": "0.0.0-dev",- "digest": "sha256:7fed643f688774621b28eb846d68bc4e70ca98a0b04a5d0cc3a521152e50a5c6"+ "digest": "sha256:9dc9cbeb2c3124c219da91237a02693cc6cd0c3f2511f20329c0f7cddffb2d06"},{"name": "@narratage/semantic-map",@@ -235,7 +235,7 @@{"name": "@narratage/store-sqlite","version": "0.0.0-dev",- "digest": "sha256:a277e24e32632a113b4b4713d3d3bce9eaef289ccc30a5f889c6fef935cb228a"+ "digest": "sha256:35e7243a129b0db8d7b1c9876411015e8c48cdb241506bfae5cbec7dfc2d512b"},{"name": "@narratage/svs",@@ -916,12 +916,12 @@},"offers": [{- "abi": "svml.runtime-service-adapter-host@1",+ "abi": "svml.runtime-component-adapter-host@1","name": "@narratage/artifact-store-fs"}],- "facetsDigest": "sha256:89812ac838e22ffcec73619ddb033f6f9150c916e0a52693ec920cb9f41f13ff",- "closureDigest": "sha256:7a9bdee0c11fb6412e9a7ce176a3af25ff0fb0b2c40cfbd46f223e6b00cb8003"+ "facetsDigest": "sha256:d06bf1c242e6b819ab605471f7332e1150e1ebf5f81e08cf77f9bfff082ea197",+ "closureDigest": "sha256:941a2c17d30e3cc733a8415557aecd80c45b7de0493ee69b670270fc7e492ae2"},{"package": {@@ -930,12 +930,12 @@},"offers": [{- "abi": "svml.runtime-service-adapter-host@1",+ "abi": "svml.runtime-component-adapter-host@1","name": "@narratage/credential-store-env"}],- "facetsDigest": "sha256:b2a771b23ea9dcdada76501804c717cc4509579244acbb09babc0807cb26401a",- "closureDigest": "sha256:24df31243ffc21fe8429a5c3f2584de75cf3189727a7c27e773bd81ca9e0af30"+ "facetsDigest": "sha256:cac24cfb3965fe73d76c8b90e1fb676ff5f7606928fb38ff3b1aeb8eb9e3ea0e",+ "closureDigest": "sha256:e3dfea4ee0734eb0ae53593b5aaae2ee05d652aa6322055e0dc0d3a58e4009b1"},{"package": {@@ -944,12 +944,16 @@},"offers": [{- "abi": "svml.runtime-service-adapter-host@1",+ "abi": "svml.node-runtime-host-adapter@1",+ "name": "@narratage/local"+ },+ {+ "abi": "svml.runtime-component-adapter-host@1","name": "@narratage/local"}],- "facetsDigest": "sha256:bacc2fe27612f029aeef34236fd5fa687259e08c980c310adc8118be2cceeaba",- "closureDigest": "sha256:5019f5018c2a8b746382a8ba838c57855af0bbf155e82c2a3b6ac87aa37f4390"+ "facetsDigest": "sha256:552616c833a22031c623b0ad24f08a843f72f332eff2113032d63e2539d42e88",+ "closureDigest": "sha256:8baca82be34ae891ca52c8835e23116e51ccf59086ae3f90243f5c41bc6c12f0"},{"package": {@@ -963,7 +967,7 @@}],"facetsDigest": "sha256:485fc29d1efcdaeb4e395980975b35090ea6aef0f78d02108d3bd9b3f11aeb91",- "closureDigest": "sha256:ccd1e3307e9ebffceb5e0cf98e03868b9e2484b364d16f8f19eefbe234d36105"+ "closureDigest": "sha256:a9c49b1ee0b7e446739c552f006efdb2e02a6fbd95026be9ac2e2a4f579bcbff"},{"package": {@@ -977,7 +981,7 @@}],"facetsDigest": "sha256:e08dde3e4d38b167dca29cdc54eb2bb5e9ebc294e0e42b371099d53d6c44b402",- "closureDigest": "sha256:cfadfcd967b2a7b5d51c6852d1f1045167734609dbcdd05a83de8eeff34f2f6d"+ "closureDigest": "sha256:8716f0eda32fec48f21cccfdb15b953f6708100923be2f9d1ed577c10db40f19"},{"package": {@@ -991,7 +995,7 @@}],"facetsDigest": "sha256:110648301d69b5b49ea553d285a27626f6fb74ebc74ee67175f688f914d7d74b",- "closureDigest": "sha256:c6105b8f3a5583f35e48ba3e9882f6a4a76adfc9f19a31877c3c6c7f8957bbc8"+ "closureDigest": "sha256:f7f87ad8a1ad76f950edf27bbd8a69bc9080da2b408fec8945d619cea8bf3208"},{"package": {@@ -1005,7 +1009,7 @@}],"facetsDigest": "sha256:998de772acb283828fee16310e77922bf43597bca1efa768e8398166a90af27d",- "closureDigest": "sha256:c59d8d31a59a5f26b9a064789e16e6db9505d26e170eb21350ee3104922a737d"+ "closureDigest": "sha256:d8386c799c6f77909767076e81a3932be033bf24e0eb65b07f79a14e7bf759a8"},{"package": {@@ -1019,7 +1023,7 @@}],"facetsDigest": "sha256:e7d4f1e2fd56f2bcb5dbc36e1faae48d2680bb839aed4a43eb0cb23207ffbe1d",- "closureDigest": "sha256:75c92b5ae14e4672ceba48b91376363f6648574f7d3655329deae60ba9c20807"+ "closureDigest": "sha256:8e38557baf5fb4c5abcdc4f6a702a8e792fd19b36a088e0f9fee6a68577e367b"},{"package": {@@ -1028,13 +1032,13 @@},"offers": [{- "abi": "svml.runtime-service-adapter-host@1",+ "abi": "svml.runtime-component-adapter-host@1","name": "@narratage/store-sqlite"}],- "facetsDigest": "sha256:eb9df1ee7597620bc2e80c168971e020f77cd0880608957ca3048cac7c559c28",- "closureDigest": "sha256:e7ab56c71e2fc2b11fccdfadc2c95fb0929e6a3bd4af1bf28577bff4758ea73c"+ "facetsDigest": "sha256:dcd11bfeb19b68e69aeecd31d34de36045dd92e36039d651385081ce4180080b",+ "closureDigest": "sha256:dbc85921b27942e27a5fde033803962733f20970536cbdfd2059ff249e22d946"}],- "digest": "sha256:6984ff6c3e2d79950e3fae3f486718ebad0f4fab8376e4322e1bc2c90b5039e6"+ "digest": "sha256:a038c726f4d7a38e761a8d07b317187e7bd1178130560e0aeeeaa6c75c2fcd30"}diff --git a/examples/talking-film-live/svml.runtime.json b/examples/talking-film-live/svml.runtime.jsonindex 8afae13c..d5c31fc3 100644--- a/examples/talking-film-live/svml.runtime.json+++ b/examples/talking-film-live/svml.runtime.json@@ -1,67 +1,57 @@{- "format": "svml.runtime-config@1",- "packageLock": "./svml.packages.lock",+ "format": "narratage.runtime-profile@1","runtimePackageLock": "./svml.runtime-packages.lock",- "runtimeServices": [- { "use": "@narratage/local", "instance": "execution" },- { "use": "@narratage/store-sqlite", "instance": "state", "config": { "path": ".svml/state.sqlite" } },- { "use": "@narratage/artifact-store-fs", "instance": "artifacts", "config": { "path": ".svml/artifacts" } },- { "use": "@narratage/credential-store-env", "instance": "credentials.env", "config": {} }- ],- "services": {- "scheduler": "execution.scheduler",- "worker": "execution.worker",- "stores": {- "build": "state.builds",- "operations": "state.operations",- "dispatch": "state.dispatch",- "artifacts": "artifacts",- "credentials": ["credentials.env"]+ "runtime": {+ "use": "@narratage/local",+ "config": {+ "dataRoot": ".narratage/runtimes/local",+ "components": {+ "execution": { "use": "@narratage/local" },+ "state": { "use": "@narratage/store-sqlite", "config": { "path": "state.sqlite" } },+ "artifacts": { "use": "@narratage/artifact-store-fs", "config": { "path": "artifacts" } },+ "credentials.env": { "use": "@narratage/credential-store-env", "config": {} }+ },+ "bindings": {+ "scheduler": "execution.scheduler",+ "worker": "execution.worker",+ "stores": {+ "build": "state.builds",+ "operations": "state.operations",+ "dispatch": "state.dispatch",+ "artifacts": "artifacts",+ "credentials": ["credentials.env"]+ }+ },+ "endpoints": {+ "kie.talking-film": {+ "use": "@narratage/provider-kie",+ "config": {+ "apiKey": { "store": "env", "key": "KIE_API_KEY" },+ "defaultConcurrency": 2+ }+ },+ "media.talking-film": {+ "use": "@narratage/provider-media-local",+ "config": { "defaultConcurrency": 2 }+ },+ "whisperx.talking-film": {+ "use": "@narratage/provider-whisperx-local",+ "config": { "defaultConcurrency": 1 }+ },+ "vertex.talking-film": {+ "use": "@narratage/provider-google-vertex",+ "config": {+ "projectEnv": "GOOGLE_CLOUD_PROJECT",+ "credentials": { "store": "env", "key": "GOOGLE_APPLICATION_CREDENTIALS_JSON" },+ "defaultConcurrency": 1+ }+ },+ "hyperframes.talking-film": {+ "use": "@narratage/provider-hyperframes-local",+ "config": { "workers": 2, "quality": "standard", "defaultConcurrency": 1 }+ }+ },+ "limits": { "maxOperations": 4 }}- },- "endpoints": [- {- "use": "@narratage/provider-kie",- "instance": "kie.talking-film",- "config": {- "apiKey": { "store": "env", "key": "KIE_API_KEY" },- "defaultConcurrency": 2- }- },- {- "use": "@narratage/provider-media-local",- "instance": "media.talking-film",- "config": {- "defaultConcurrency": 2- }- },- {- "use": "@narratage/provider-whisperx-local",- "instance": "whisperx.talking-film",- "config": {- "defaultConcurrency": 1- }- },- {- "use": "@narratage/provider-google-vertex",- "instance": "vertex.talking-film",- "config": {- "projectEnv": "GOOGLE_CLOUD_PROJECT",- "credentials": { "store": "env", "key": "GOOGLE_APPLICATION_CREDENTIALS_JSON" },- "defaultConcurrency": 1- }- },- {- "use": "@narratage/provider-hyperframes-local",- "instance": "hyperframes.talking-film",- "config": {- "workers": 2,- "quality": "standard",- "defaultConcurrency": 1- }- }- ],- "scheduling": {- "maxConcurrency": 4}}diff --git a/examples/talking-head-aroll/svml.packages.lock b/examples/talking-head-aroll/svml.packages.lockindex 0e6e5d1f..3d37d148 100644--- a/examples/talking-head-aroll/svml.packages.lock+++ b/examples/talking-head-aroll/svml.packages.lock@@ -587,7 +587,7 @@{"name": "@narratage/component-kit","version": "0.0.0-dev",- "digest": "sha256:f67949d59b628490e2a371bc4fb42f546ee33648d2a82d439875757b0909f6ab"+ "digest": "sha256:a503483ab1e923d1c81473e2f3d433aacfa08703c2d81715e66aa310f170a0ae"},{"name": "@narratage/composition",@@ -797,7 +797,7 @@}],"facetsDigest": "sha256:1fbbf9bcdc39382ec612df3f29765b5d6ceb8598c0df2c7b5d6b8515f73367a3",- "closureDigest": "sha256:7ee87cd64e4788e5c6fc3deb81c2f568192b9f0030a9241ceb635d283eb4bfaa"+ "closureDigest": "sha256:790bad794d072c3bab93c3d76307b9cc836669681273ab04b1f06709dff1eb5a"},{"package": {@@ -811,7 +811,7 @@}],"facetsDigest": "sha256:73e3f528a76fdc553ba2ee87fe5beb5fb2c91b7d4fcdff4ba9e6963d4740fdf6",- "closureDigest": "sha256:c21b0177c8cb2268ba1150706973da9c6411e67c1d16b4f4a491928e6130b83a"+ "closureDigest": "sha256:894767197868c4df9cfec52541621b53298e5dcef78dc692b90dc7f73c1a2aa7"},{"package": {@@ -825,7 +825,7 @@}],"facetsDigest": "sha256:894d546ffa3c9e221fc6b686d11bc117d15a250399332e3ae1c1d28a547e0f30",- "closureDigest": "sha256:679c01ef81efbe378f077b4afda3c19ac58ed554d5ca2768ec52a5d87af6fde1"+ "closureDigest": "sha256:7ae1df06b13ad365e05f8d1b45eb045bddc832976dc612898aff0e05d0c9366f"},{"package": {@@ -839,7 +839,7 @@}],"facetsDigest": "sha256:05c22bda8c301365c1cfff2c0afa80067f3d2a0fba167a57ebf923af720a5c34",- "closureDigest": "sha256:8d42e7b295199f7775430131f7df5f3753474a44ff579ede2b8b36ae5a653e19"+ "closureDigest": "sha256:7d309e990bdfaf84168b43bd8b41a3b6f25dd394eb53c7bb34340fd59c0a67a9"},{"package": {@@ -853,7 +853,7 @@}],"facetsDigest": "sha256:c22a49bd60d2e8061f9cd57c57869a6bcdcfb1a39886ad68f5f4f62a8ddc663a",- "closureDigest": "sha256:eb417038512a811a82dfbcd0a5b17c18e20e28b4e2df950a351c82e3a42263ea"+ "closureDigest": "sha256:85f440f06d6e65eeb3ca38768a6a64796994ead70a78e4d9fc518697b0da71c3"},{"package": {@@ -867,7 +867,7 @@}],"facetsDigest": "sha256:b96fd578be298ab154d1ad30a27d7e54ae0cf2f8f52f52d7bf13c0785d2a8da7",- "closureDigest": "sha256:fb78c8e6c91d8d8486959067ec3dc9791549e0c675689376f26462044d5c3359"+ "closureDigest": "sha256:f98b81818ae8bc4d0b5e47edb5ef9a080b092f65766178d0dad4dc7b86d74b55"},{"package": {@@ -881,7 +881,7 @@}],"facetsDigest": "sha256:de93037cec9a364da45fedc69a2d82cca93c5866e475942241c008f46c3a8da9",- "closureDigest": "sha256:55541f35bfcce5f705cd14e706c887222b79e802c2207ddf6878114ef309b23e"+ "closureDigest": "sha256:716b251dd7100f055b10dbb6c92d799f19ac1c9e3d17aeaaa38eef421ebe4512"},{"package": {@@ -895,7 +895,7 @@}],"facetsDigest": "sha256:d9ee4c44949ca2d24967e7d81898999db84ab592fdaaafe1bd6d22a28ea5e094",- "closureDigest": "sha256:7a42bf1315d3f85ac539498cacd7acfd87fe66d1f56650eacaf29046b2bd2406"+ "closureDigest": "sha256:8f86d9c4e36b2a01d484f44ea59278ec4deedd86cc1797ca6d84ba5bd2ca38ff"},{"package": {@@ -909,7 +909,7 @@}],"facetsDigest": "sha256:7596800f1ce4506145f9ff50c768bfc07131c5ea8d421711a6b5268ce13960f7",- "closureDigest": "sha256:f784868d13286f882a1319c781181e843cb92df03b59a34fb046400fc2bf659c"+ "closureDigest": "sha256:1a45cbbbfdf5b2da33be35fdb33aac91fa7536fa29b75d3959e1fc9ae52e0bf2"},{"package": {@@ -923,7 +923,7 @@}],"facetsDigest": "sha256:5bbef7d089f36dd1ea36b743b1b4f03289ccb8a2fc50383e3b355982916ccfc6",- "closureDigest": "sha256:9013ba2bddbda6b5b472bf2c44b9e880f1459baba2e47164f1b3a4f499095a12"+ "closureDigest": "sha256:70cbebe094cab5f1990f5effcdfd72f48a78e5cf2316b3629049d1eca34cfa35"},{"package": {@@ -937,7 +937,7 @@}],"facetsDigest": "sha256:a96ae88d7813e660bb496b77e53f66ed7e218b20d4e157632c9a4fd832580a92",- "closureDigest": "sha256:6a717a97a67b450827bc405f5c8100d5e3fb9d24469d89b0a1dd29077c65a03a"+ "closureDigest": "sha256:a37b9c1903ce96a1b7554147e8a48dd2104bc54dc732909edeb6a77c37f2ce36"},{"package": {@@ -979,7 +979,7 @@}],"facetsDigest": "sha256:31b63a4bf10385d31feb50114811c5185b78a0caab6b7c1646c86a61c4958128",- "closureDigest": "sha256:0e147ec078e35a7ad8bb12ca0a0df3b6b41dcb3cca8fae30b62013c9b90b577b"+ "closureDigest": "sha256:1ba24f24c93b7aa090d41a62b6708f93364c906e483efea007bac9d399db7bf5"},{"package": {@@ -1007,7 +1007,7 @@}],"facetsDigest": "sha256:acc754c61e24f93d5e2692ceb6998a3638cc384de8e512e155738435663a8342",- "closureDigest": "sha256:9627e181544189562aaed76f26da3e8dc57cef9901d0ff3cc513a61104613031"+ "closureDigest": "sha256:cbf4fe4ec28ae6958956ee67d02c8a4a30d2e4e5cbd64d8952e317c6df435fbb"},{"package": {@@ -1021,7 +1021,7 @@}],"facetsDigest": "sha256:41615659f664d3480af5a50c81df188b6fc848628c60bc82d37eb7735071f111",- "closureDigest": "sha256:084b229a2e566267e62ee6b07a219a4928e614aca0b87e2a2782beee504c62ce"+ "closureDigest": "sha256:3ea90ac12b4ac7bddce6064ac99d946aa89745c0fbf06861100415c12bd63882"},{"package": {@@ -1049,7 +1049,7 @@}],"facetsDigest": "sha256:4e6da482a365cd36423f3baf568ea741f2e0eddf26b559bce43d3c4270830c91",- "closureDigest": "sha256:b61d84f259dad599b783e3ebd236a3800e7356c6233a4e0eb6e39e61e416061c"+ "closureDigest": "sha256:dde427e997833b5ed6639deeed75070eb98bc9e50c8f0a7da8f31fefe4435724"},{"package": {@@ -1063,7 +1063,7 @@}],"facetsDigest": "sha256:e86e5c90307ab183d2ea5d75e4ca0daab4f2b65905feb79c387871370d625e3a",- "closureDigest": "sha256:fe97f366b85930ec11fcbfab56e62c11b92ce85b95480328e2229e02303bf959"+ "closureDigest": "sha256:8be1559095728f977914d56c4e7dfd070362d7bbddfb0565062129fe27a67d8d"},{"package": {@@ -1077,7 +1077,7 @@}],"facetsDigest": "sha256:b55e20b4fdf24cbfaf956447ff62885e81638fdbcbb61f25483392a1c8fac8c9",- "closureDigest": "sha256:6d5142eb1ae177537eeb19e1fdedd93a904d492002cd3dcf9d253d85932303b6"+ "closureDigest": "sha256:34ff2b938c8cdb94823a2843e882ac9d1e8f51f46dee02a6b0342b69f48c5be3"},{"package": {@@ -1091,7 +1091,7 @@}],"facetsDigest": "sha256:3e7413acb9b39071fad0ea2e99777ae9ab7a4b636041a8345ec1d08428859b3f",- "closureDigest": "sha256:d2c3ebea16f7f58a4871df4c75dc011166c69031450371c6ff8fda33ffe528d0"+ "closureDigest": "sha256:e0a9f8e7c454beb36d67e9bd358383fc91567e70e9f43f75290a831028e39576"},{"package": {@@ -1119,7 +1119,7 @@}],"facetsDigest": "sha256:340cf867483022b3896008781f24a04e22aa0abc76873cc44787aefdc0219522",- "closureDigest": "sha256:0e2332df3f9b9d295224a2bef2fdfaf06fa5454e1fac131b2137a0e814d38f91"+ "closureDigest": "sha256:f215f8ec4e02bf26ff0960b129760eeb80ab59658cd0ec0476481b73c11f09ee"},{"package": {@@ -1155,7 +1155,7 @@}],"facetsDigest": "sha256:2d4d0e9eea9ec795fb675ddf7d204bc29fe7eb8e3a743eced944a0cdb50ecf50",- "closureDigest": "sha256:48cca7d31b965ac882090e805e55044c9b44a319d4a67eefcef940614c9ee4da"+ "closureDigest": "sha256:51afff4d06131cc77a3e6953a9151564dfb79bde943f1250d91d24db1f2c00d4"},{"package": {@@ -1183,8 +1183,8 @@}],"facetsDigest": "sha256:64c0e76dea02b19be28bc7425e11938fd9c1dbb9994dde3a6d98c41da819b85e",- "closureDigest": "sha256:57cd991e800c5c55bcbb38931b6b81a67fe32cb532f9832784d219126f11fea8"+ "closureDigest": "sha256:233b055191b86b8527083fe601c89216d7dabbce7a227123dc5d6b2117322753"}],- "digest": "sha256:25c125d3b7019e4f799215851db46825df3888d7977e46eb65574c0a87b854cb"+ "digest": "sha256:d9336d5b418b1221706f3dedf6c0c7ee082a8db6725a996817f626cace3b668c"}diff --git a/examples/talking-head-aroll/svml.runtime-packages.lock b/examples/talking-head-aroll/svml.runtime-packages.lockindex 4f15e02e..2f109c4c 100644--- a/examples/talking-head-aroll/svml.runtime-packages.lock+++ b/examples/talking-head-aroll/svml.runtime-packages.lock@@ -40,7 +40,7 @@{"name": "@narratage/artifact-store-fs","version": "0.0.0-dev",- "digest": "sha256:0321ea7083887bb13329c6815dfb5e8bfc0a5dc711fba95c10dac625976cbda7"+ "digest": "sha256:609d09f53cba3f7367ef59502dc02f6c71d52b4f36914a0ebff8ac34703c8775"},{"name": "@narratage/artifact",@@ -65,7 +65,7 @@{"name": "@narratage/component-kit","version": "0.0.0-dev",- "digest": "sha256:f67949d59b628490e2a371bc4fb42f546ee33648d2a82d439875757b0909f6ab"+ "digest": "sha256:a503483ab1e923d1c81473e2f3d433aacfa08703c2d81715e66aa310f170a0ae"},{"name": "@narratage/composition",@@ -80,7 +80,7 @@{"name": "@narratage/credential-store-env","version": "0.0.0-dev",- "digest": "sha256:97724c0aedcacaee14699dd2fb22f73b1cfd901b85434a0376a6eb157793b3ae"+ "digest": "sha256:86ca20d6418e2c591359971f6afc59232c391fac37e3150eb5ed95adda495fe9"},{"name": "@narratage/driver-node",@@ -115,7 +115,7 @@{"name": "@narratage/local","version": "0.0.0-dev",- "digest": "sha256:53bfb88dfb3cb16a1747f7dfa9d92864fd5385c45584491577cf2f714d2d4c27"+ "digest": "sha256:ac56790c50bedb1e3380ca251463c3e41adfc1edc27cb8e6960791f95ec621de"},{"name": "@narratage/markup",@@ -165,7 +165,7 @@{"name": "@narratage/provider-hyperframes-local","version": "0.0.0-dev",- "digest": "sha256:93d1a6cce2f0e56e4f8324db405ef0ae1a863086ee0aa8363999dba7d8384427"+ "digest": "sha256:4827eaae0955d045f92ead0ee42d12521268fa8fded6372a3f53521d65ccfcba"},{"name": "@narratage/provider-kie",@@ -175,12 +175,12 @@{"name": "@narratage/provider-media-local","version": "0.0.0-dev",- "digest": "sha256:203c7dbe366f8cb1568bd9413ccd6ff3a7b10b9a7380b5568e8a4c4d58c96736"+ "digest": "sha256:eefbd7478a1c37eb3ddc28af0a70cf8fac2e1d8c37ed61a3026b36f03c8f21d4"},{"name": "@narratage/provider-whisperx-local","version": "0.0.0-dev",- "digest": "sha256:8a83f5326337865e8ff6c59eaa98ea1b1f94f9529c96f733a140705a0cff99da"+ "digest": "sha256:65e080a86701e76c9fafbe60235c38db1262557392ed7be3a0e893a73752bd30"},{"name": "@narratage/render-hyperframes",@@ -190,17 +190,17 @@{"name": "@narratage/runtime-adapter-node","version": "0.0.0-dev",- "digest": "sha256:767e12f845be87f96b13fd8e147007a5adae1ebfe2e1192d94a15590b5542601"+ "digest": "sha256:0ce0b9d4ab66c1ba248b7925a859b4654429d5cd68f4309d2932a6070456cbb6"},{"name": "@narratage/runtime-adapter","version": "0.0.0-dev",- "digest": "sha256:0c62cd7704e2e99bfece8b708174144474aeb075b2e3bea415d9c2fc50dc4c80"+ "digest": "sha256:37bfc677595841a6b4491b0066894271f252150e96b47dcd10123eecfe29cc3a"},{"name": "@narratage/runtime","version": "0.0.0-dev",- "digest": "sha256:7fed643f688774621b28eb846d68bc4e70ca98a0b04a5d0cc3a521152e50a5c6"+ "digest": "sha256:9dc9cbeb2c3124c219da91237a02693cc6cd0c3f2511f20329c0f7cddffb2d06"},{"name": "@narratage/semantic-map",@@ -235,7 +235,7 @@{"name": "@narratage/store-sqlite","version": "0.0.0-dev",- "digest": "sha256:a277e24e32632a113b4b4713d3d3bce9eaef289ccc30a5f889c6fef935cb228a"+ "digest": "sha256:35e7243a129b0db8d7b1c9876411015e8c48cdb241506bfae5cbec7dfc2d512b"},{"name": "@narratage/svs",@@ -916,12 +916,12 @@},"offers": [{- "abi": "svml.runtime-service-adapter-host@1",+ "abi": "svml.runtime-component-adapter-host@1","name": "@narratage/artifact-store-fs"}],- "facetsDigest": "sha256:89812ac838e22ffcec73619ddb033f6f9150c916e0a52693ec920cb9f41f13ff",- "closureDigest": "sha256:7a9bdee0c11fb6412e9a7ce176a3af25ff0fb0b2c40cfbd46f223e6b00cb8003"+ "facetsDigest": "sha256:d06bf1c242e6b819ab605471f7332e1150e1ebf5f81e08cf77f9bfff082ea197",+ "closureDigest": "sha256:941a2c17d30e3cc733a8415557aecd80c45b7de0493ee69b670270fc7e492ae2"},{"package": {@@ -930,12 +930,12 @@},"offers": [{- "abi": "svml.runtime-service-adapter-host@1",+ "abi": "svml.runtime-component-adapter-host@1","name": "@narratage/credential-store-env"}],- "facetsDigest": "sha256:b2a771b23ea9dcdada76501804c717cc4509579244acbb09babc0807cb26401a",- "closureDigest": "sha256:24df31243ffc21fe8429a5c3f2584de75cf3189727a7c27e773bd81ca9e0af30"+ "facetsDigest": "sha256:cac24cfb3965fe73d76c8b90e1fb676ff5f7606928fb38ff3b1aeb8eb9e3ea0e",+ "closureDigest": "sha256:e3dfea4ee0734eb0ae53593b5aaae2ee05d652aa6322055e0dc0d3a58e4009b1"},{"package": {@@ -944,12 +944,16 @@},"offers": [{- "abi": "svml.runtime-service-adapter-host@1",+ "abi": "svml.node-runtime-host-adapter@1",+ "name": "@narratage/local"+ },+ {+ "abi": "svml.runtime-component-adapter-host@1","name": "@narratage/local"}],- "facetsDigest": "sha256:bacc2fe27612f029aeef34236fd5fa687259e08c980c310adc8118be2cceeaba",- "closureDigest": "sha256:5019f5018c2a8b746382a8ba838c57855af0bbf155e82c2a3b6ac87aa37f4390"+ "facetsDigest": "sha256:552616c833a22031c623b0ad24f08a843f72f332eff2113032d63e2539d42e88",+ "closureDigest": "sha256:8baca82be34ae891ca52c8835e23116e51ccf59086ae3f90243f5c41bc6c12f0"},{"package": {@@ -963,7 +967,7 @@}],"facetsDigest": "sha256:485fc29d1efcdaeb4e395980975b35090ea6aef0f78d02108d3bd9b3f11aeb91",- "closureDigest": "sha256:ccd1e3307e9ebffceb5e0cf98e03868b9e2484b364d16f8f19eefbe234d36105"+ "closureDigest": "sha256:a9c49b1ee0b7e446739c552f006efdb2e02a6fbd95026be9ac2e2a4f579bcbff"},{"package": {@@ -977,7 +981,7 @@}],"facetsDigest": "sha256:e08dde3e4d38b167dca29cdc54eb2bb5e9ebc294e0e42b371099d53d6c44b402",- "closureDigest": "sha256:cfadfcd967b2a7b5d51c6852d1f1045167734609dbcdd05a83de8eeff34f2f6d"+ "closureDigest": "sha256:8716f0eda32fec48f21cccfdb15b953f6708100923be2f9d1ed577c10db40f19"},{"package": {@@ -991,7 +995,7 @@}],"facetsDigest": "sha256:110648301d69b5b49ea553d285a27626f6fb74ebc74ee67175f688f914d7d74b",- "closureDigest": "sha256:c6105b8f3a5583f35e48ba3e9882f6a4a76adfc9f19a31877c3c6c7f8957bbc8"+ "closureDigest": "sha256:f7f87ad8a1ad76f950edf27bbd8a69bc9080da2b408fec8945d619cea8bf3208"},{"package": {@@ -1005,7 +1009,7 @@}],"facetsDigest": "sha256:998de772acb283828fee16310e77922bf43597bca1efa768e8398166a90af27d",- "closureDigest": "sha256:c59d8d31a59a5f26b9a064789e16e6db9505d26e170eb21350ee3104922a737d"+ "closureDigest": "sha256:d8386c799c6f77909767076e81a3932be033bf24e0eb65b07f79a14e7bf759a8"},{"package": {@@ -1019,7 +1023,7 @@}],"facetsDigest": "sha256:e7d4f1e2fd56f2bcb5dbc36e1faae48d2680bb839aed4a43eb0cb23207ffbe1d",- "closureDigest": "sha256:75c92b5ae14e4672ceba48b91376363f6648574f7d3655329deae60ba9c20807"+ "closureDigest": "sha256:8e38557baf5fb4c5abcdc4f6a702a8e792fd19b36a088e0f9fee6a68577e367b"},{"package": {@@ -1028,13 +1032,13 @@},"offers": [{- "abi": "svml.runtime-service-adapter-host@1",+ "abi": "svml.runtime-component-adapter-host@1","name": "@narratage/store-sqlite"}],- "facetsDigest": "sha256:eb9df1ee7597620bc2e80c168971e020f77cd0880608957ca3048cac7c559c28",- "closureDigest": "sha256:e7ab56c71e2fc2b11fccdfadc2c95fb0929e6a3bd4af1bf28577bff4758ea73c"+ "facetsDigest": "sha256:dcd11bfeb19b68e69aeecd31d34de36045dd92e36039d651385081ce4180080b",+ "closureDigest": "sha256:dbc85921b27942e27a5fde033803962733f20970536cbdfd2059ff249e22d946"}],- "digest": "sha256:6984ff6c3e2d79950e3fae3f486718ebad0f4fab8376e4322e1bc2c90b5039e6"+ "digest": "sha256:a038c726f4d7a38e761a8d07b317187e7bd1178130560e0aeeeaa6c75c2fcd30"}diff --git a/examples/talking-head-aroll/svml.runtime.json b/examples/talking-head-aroll/svml.runtime.jsonindex 3b6446d9..8ee79970 100644--- a/examples/talking-head-aroll/svml.runtime.json+++ b/examples/talking-head-aroll/svml.runtime.json@@ -1,68 +1,58 @@{- "format": "svml.runtime-config@1",- "packageLock": "./svml.packages.lock",+ "format": "narratage.runtime-profile@1","runtimePackageLock": "./svml.runtime-packages.lock",- "runtimeServices": [- { "use": "@narratage/local", "instance": "execution" },- { "use": "@narratage/store-sqlite", "instance": "state", "config": { "path": ".svml/state.sqlite" } },- { "use": "@narratage/artifact-store-fs", "instance": "artifacts", "config": { "path": ".svml/artifacts" } },- { "use": "@narratage/credential-store-env", "instance": "credentials.env", "config": {} }- ],- "services": {- "scheduler": "execution.scheduler",- "worker": "execution.worker",- "stores": {- "build": "state.builds",- "operations": "state.operations",- "dispatch": "state.dispatch",- "artifacts": "artifacts",- "credentials": ["credentials.env"]+ "runtime": {+ "use": "@narratage/local",+ "config": {+ "dataRoot": ".narratage/runtimes/local",+ "components": {+ "execution": { "use": "@narratage/local" },+ "state": { "use": "@narratage/store-sqlite", "config": { "path": "state.sqlite" } },+ "artifacts": { "use": "@narratage/artifact-store-fs", "config": { "path": "artifacts" } },+ "credentials.env": { "use": "@narratage/credential-store-env", "config": {} }+ },+ "bindings": {+ "scheduler": "execution.scheduler",+ "worker": "execution.worker",+ "stores": {+ "build": "state.builds",+ "operations": "state.operations",+ "dispatch": "state.dispatch",+ "artifacts": "artifacts",+ "credentials": ["credentials.env"]+ }+ },+ "endpoints": {+ "kie.talking-head-aroll": {+ "use": "@narratage/provider-kie",+ "config": {+ "apiKey": { "store": "env", "key": "KIE_API_KEY" },+ "defaultConcurrency": 2+ }+ },+ "media.talking-head-aroll": {+ "use": "@narratage/provider-media-local",+ "config": { "defaultConcurrency": 2 }+ },+ "whisperx.talking-head-aroll": {+ "use": "@narratage/provider-whisperx-local",+ "config": { "defaultConcurrency": 1 }+ },+ "vertex.talking-head-aroll": {+ "use": "@narratage/provider-google-vertex",+ "config": {+ "projectEnv": "GOOGLE_CLOUD_PROJECT",+ "credentials": { "store": "env", "key": "GOOGLE_APPLICATION_CREDENTIALS_JSON" },+ "location": "global",+ "defaultConcurrency": 1+ }+ },+ "hyperframes.talking-head-aroll": {+ "use": "@narratage/provider-hyperframes-local",+ "config": { "workers": 2, "quality": "standard", "defaultConcurrency": 1 }+ }+ },+ "limits": { "maxOperations": 4 }}- },- "endpoints": [- {- "use": "@narratage/provider-kie",- "instance": "kie.talking-head-aroll",- "config": {- "apiKey": { "store": "env", "key": "KIE_API_KEY" },- "defaultConcurrency": 2- }- },- {- "use": "@narratage/provider-media-local",- "instance": "media.talking-head-aroll",- "config": {- "defaultConcurrency": 2- }- },- {- "use": "@narratage/provider-whisperx-local",- "instance": "whisperx.talking-head-aroll",- "config": {- "defaultConcurrency": 1- }- },- {- "use": "@narratage/provider-google-vertex",- "instance": "vertex.talking-head-aroll",- "config": {- "projectEnv": "GOOGLE_CLOUD_PROJECT",- "credentials": { "store": "env", "key": "GOOGLE_APPLICATION_CREDENTIALS_JSON" },- "location": "global",- "defaultConcurrency": 1- }- },- {- "use": "@narratage/provider-hyperframes-local",- "instance": "hyperframes.talking-head-aroll",- "config": {- "workers": 2,- "quality": "standard",- "defaultConcurrency": 1- }- }- ],- "scheduling": {- "maxConcurrency": 4}}diff --git a/packages/artifact-store-fs/README.md b/packages/artifact-store-fs/README.mdindex 8594ff6e..4899e912 100644--- a/packages/artifact-store-fs/README.md+++ b/packages/artifact-store-fs/README.md@@ -7,5 +7,5 @@ same adapter can later be replaced by S3 without changing Core, component or EndThis package does not store BuildState, Endpoint checkpoints, credentials or author library records.`createFileArtifactStorePackage()` contributes the configured store through the generic Runtime-service-package protocol. Its absolute root is bound into Runtime instance identity; the Local Host+Component Adapter protocol. Its absolute root is bound into Runtime instance identity; the Local Hostdoes not need filesystem-specific registration code.diff --git a/packages/artifact-store-fs/src/activation.ts b/packages/artifact-store-fs/src/activation.tsindex bd42addc..947961fc 100644--- a/packages/artifact-store-fs/src/activation.ts+++ b/packages/artifact-store-fs/src/activation.ts@@ -1,7 +1,7 @@import { resolve } from "node:path";import {- createRuntimeServiceAdapterFacet,+ createRuntimeComponentAdapterFacet,runtimeConfigExact,runtimeConfigObject,runtimeConfigString,@@ -9,7 +9,7 @@ import {import { createFileArtifactStorePackage } from "./store.js";-const fileArtifactStoreAdapter = createRuntimeServiceAdapterFacet({+const fileArtifactStoreAdapter = createRuntimeComponentAdapterFacet({use: "@narratage/artifact-store-fs",validate(context) {const config = runtimeConfigObject(context.config, "filesystem ArtifactStore");@@ -21,7 +21,7 @@ const fileArtifactStoreAdapter = createRuntimeServiceAdapterFacet({const path = runtimeConfigString(config.path, "Artifact path");if (path === undefined) throw new Error("Artifact path is required");return createFileArtifactStorePackage({- root: resolve(context.root, path),+ root: resolve(context.dataRoot, path),instance: context.instance,});},diff --git a/packages/artifact-store-fs/src/store.ts b/packages/artifact-store-fs/src/store.tsindex 9a759b3a..40b20bc1 100644--- a/packages/artifact-store-fs/src/store.ts+++ b/packages/artifact-store-fs/src/store.ts@@ -11,8 +11,8 @@ import { dirname, join, resolve } from "node:path";import { digestOf, isDigest } from "@narratage/protocol";import type { BlobRef, Digest } from "@narratage/protocol";-import { defineRuntimeServicePackage } from "@narratage/runtime";-import type { ArtifactStore, RuntimeServicePackage } from "@narratage/runtime";+import { defineRuntimeComponentPackage } from "@narratage/runtime";+import type { ArtifactStore, RuntimeComponentPackage } from "@narratage/runtime";export const fileArtifactStoreModuleRef = {name: "@narratage/artifact-store-fs",@@ -188,11 +188,11 @@ export class FileArtifactStore implements ArtifactStore {export function createFileArtifactStorePackage(options: CreateFileArtifactStorePackageOptions,-): RuntimeServicePackage {+): RuntimeComponentPackage {const instance = options.instance ?? "artifacts.fs";- return defineRuntimeServicePackage({+ return defineRuntimeComponentPackage({module: fileArtifactStoreModuleRef,- services: [{+ components: [{role: "artifact-store",facet: "artifact-store",instance,@@ -200,7 +200,7 @@ export function createFileArtifactStorePackage(digest: fileArtifactStoreImplementationDigest,},configuration: { root: resolve(options.root) },- service: new FileArtifactStore(options.root),+ port: new FileArtifactStore(options.root),}],});}diff --git a/packages/artifact-store-s3/README.md b/packages/artifact-store-s3/README.mdindex 4edef404..cc9403c1 100644--- a/packages/artifact-store-s3/README.md+++ b/packages/artifact-store-s3/README.md@@ -31,7 +31,7 @@ const artifacts = createS3ArtifactStorePackage({// then select `artifacts.team` as runtimeSelection.stores.artifacts.```-`createProjectLocalRuntime()` never infers the other required services from this package.+`createProjectLocalRuntime()` never infers the other required Components from this package.The AWS SDK default credential chain or an explicitly injected trusted client owns AWSauthentication. Secret bytes never enter the package contribution or Runtime Closure; bucket,diff --git a/packages/artifact-store-s3/src/activation.ts b/packages/artifact-store-s3/src/activation.tsindex 05f9eb3c..2d6954be 100644--- a/packages/artifact-store-s3/src/activation.ts+++ b/packages/artifact-store-s3/src/activation.ts@@ -1,5 +1,5 @@import {- createRuntimeServiceAdapterFacet,+ createRuntimeComponentAdapterFacet,runtimeConfigBoolean,runtimeConfigExact,runtimeConfigObject,@@ -31,7 +31,7 @@ function validateConfig(context: RuntimeAdapterFactoryContext): void {}}-const s3ArtifactStoreRuntimeAdapter = createRuntimeServiceAdapterFacet({+const s3ArtifactStoreRuntimeAdapter = createRuntimeComponentAdapterFacet({use: "@narratage/artifact-store-s3",validate: validateConfig,create(context) {diff --git a/packages/artifact-store-s3/src/store.ts b/packages/artifact-store-s3/src/store.tsindex 49be59fe..895f7d46 100644--- a/packages/artifact-store-s3/src/store.ts+++ b/packages/artifact-store-s3/src/store.ts@@ -2,8 +2,8 @@ import { createHash, randomUUID } from "node:crypto";import { digestOf, isDigest } from "@narratage/protocol";import type { BlobRef, Digest } from "@narratage/protocol";-import { defineRuntimeServicePackage } from "@narratage/runtime";-import type { ArtifactStore, RuntimeServicePackage } from "@narratage/runtime";+import { defineRuntimeComponentPackage } from "@narratage/runtime";+import type { ArtifactStore, RuntimeComponentPackage } from "@narratage/runtime";import { AwsS3ObjectClient } from "./client.js";import type { S3ListPage, S3ObjectClient } from "./client.js";@@ -381,7 +381,7 @@ export class S3ArtifactStore implements ArtifactStore {export function createS3ArtifactStorePackage(options: CreateS3ArtifactStorePackageOptions,-): RuntimeServicePackage {+): RuntimeComponentPackage {const instance = options.instance ?? "artifacts.s3";assert(instance.trim().length > 0, "S3 ArtifactStore instance id must not be empty");const prefix = normalizePrefix(options.prefix);@@ -399,9 +399,9 @@ export function createS3ArtifactStorePackage(...(options.endpoint === undefined ? {} : { endpoint: options.endpoint }),...(options.forcePathStyle === undefined ? {} : { forcePathStyle: options.forcePathStyle }),});- return defineRuntimeServicePackage({+ return defineRuntimeComponentPackage({module: s3ArtifactStoreModuleRef,- services: [{+ components: [{role: "artifact-store",facet: "artifact-store",instance,@@ -409,7 +409,7 @@ export function createS3ArtifactStorePackage(digest: s3ArtifactStoreImplementationDigest,},configuration,- service: new S3ArtifactStore({+ port: new S3ArtifactStore({client,bucket: options.bucket,...(options.partSizeBytes === undefined ? {} : { partSizeBytes: options.partSizeBytes }),diff --git a/packages/artifact-store-s3/test/store.test.ts b/packages/artifact-store-s3/test/store.test.tsindex 8c7c50ba..10513a83 100644--- a/packages/artifact-store-s3/test/store.test.ts+++ b/packages/artifact-store-s3/test/store.test.ts@@ -57,8 +57,8 @@ test("configured S3 service locks its location", () => {region: "us-east-1",expectedBucketOwner: "123456789012",});- assert.equal(configured.services[0]?.instance.id, "artifacts.team");- assert.ok(configured.services[0]?.instance.configurationDigest);+ assert.equal(configured.components[0]?.instance.id, "artifacts.team");+ assert.ok(configured.components[0]?.instance.configurationDigest);});/** A client that can do everything, backed by an in-memory bucket. */diff --git a/packages/cli/package.json b/packages/cli/package.jsonindex a3c891b0..4d33e802 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -15,6 +15,7 @@"@narratage/protocol": "workspace:*","@narratage/run": "workspace:*","@narratage/runtime": "workspace:*",+ "@narratage/runtime-adapter-node": "workspace:*","@narratage/source": "workspace:*"},"devDependencies": {diff --git a/packages/cli/src/distribution.ts b/packages/cli/src/distribution.tsindex 86cb9910..79ea9d34 100644--- a/packages/cli/src/distribution.ts+++ b/packages/cli/src/distribution.ts@@ -1,17 +1,6 @@import type { NodeCompiler } from "@narratage/compiler-node";import type { NodePackageBinding, NodePackageContribution } from "@narratage/package-loader-node";-import type { LoadedNodePackageSet } from "@narratage/package-loader-node";-import type { CapabilityRef } from "@narratage/protocol";-import type {- CliCredentialControl,- CliExternalServiceProgress,- CliExternalServiceReport,- CliRuntime,- CliRuntimeArchiveControl,- CliRuntimeArtifactAccess,- CliRuntimeMaintenance,- CliRuntimeDoctorResult,-} from "./runtime-port.js";+import type { NodeRuntimeHost } from "@narratage/runtime-adapter-node";export type CliCompilerOptions = {/** Canonical containment boundary for Author and Run Sources plus source assets. */@@ -48,53 +37,6 @@ export type CliDistribution = {readonly selected: readonly string[];readonly logical?: readonly import("@narratage/package-loader-node").LogicalPackageAddress[];}>;- /**- * Resolve the deterministic implementation lock named by a declarative- * Runtime Profile without constructing that Runtime. Trusted executable- * Runtime modules may decline and require an explicit CLI package lock.- */- resolveCompilationPackages?(path: string): Promise<{- /** Stable project Source boundary selected by this Runtime Profile. */- readonly root?: string;- readonly packageLock?: string;- readonly runtimePackageLock?: string;- readonly packageRoot?: string;- /** ABI-qualified Runtime adapters selected by the Profile. */- readonly runtimeSelection?: import("@narratage/package-loader-node").NodePackageSelectionRequest;- }>;- /** Opaque revision of the Profile and every deployment input that requires a fresh Worker. */- runtimeProfileRevision(path: string): Promise<string>;- createRuntimeFromConfig(path: string, options?: {- /** Same-process package set already verified for compilation. */- readonly implementationPackages?: LoadedNodePackageSet;- }): Promise<CliRuntime>;- /** Open only durable execution-state Stores for observation and cancellation. */- createRuntimeArchiveFromConfig(path: string, options?: { readonly readOnly?: boolean }): Promise<CliRuntimeArchiveControl>;- /** Open only the selected ArtifactStore for explicit byte ingress or egress. */- createRuntimeArtifactAccessFromConfig(path: string, options?: { readonly readOnly?: boolean }): Promise<CliRuntimeArtifactAccess>;- /** Open execution-state Stores plus the ArtifactStore for explicit retention maintenance. */- createRuntimeMaintenanceFromConfig(path: string, options?: { readonly readOnly?: boolean }): Promise<CliRuntimeMaintenance>;- /** Open only the selected Endpoint declaration and configured CredentialStores. */- createRuntimeCredentialsFromConfig(path: string, endpoint: string): Promise<CliCredentialControl>;- /** Re-enter this exact Distribution as the hidden durable Worker process. */- runtimeWorkerLaunch(): { readonly command: string; readonly args: readonly string[] };- doctorRuntimeConfig(path: string, options?: {- readonly capabilities?: readonly CapabilityRef[];- readonly implementationPackages?: LoadedNodePackageSet;- }): Promise<CliRuntimeDoctorResult>;- /** The external programs a Runtime Profile implies: probe, prepare and start them. */- readonly externalServices: {- up(path: string, options: {- readonly maxWaitMs?: number;- readonly onProgress?: (event: CliExternalServiceProgress) => void;- readonly capabilities?: readonly CapabilityRef[];- }): Promise<ExternalServiceResult>;- down(path: string): Promise<ExternalServiceResult>;- report(path: string): Promise<ExternalServiceResult>;- };-};--export type ExternalServiceResult = {- readonly root: string;- readonly services: readonly CliExternalServiceReport[];+ /** Load the Runtime Host selected by the Profile's locked `runtime.use` package. */+ openRuntimeHost(path: string): Promise<NodeRuntimeHost>;};diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.tsindex e0efd11e..9cc04efa 100644--- a/packages/cli/src/index.ts+++ b/packages/cli/src/index.ts@@ -1,6 +1,7 @@export { materializeArtifact, materializeRecord } from "./archive.js";export { runCli } from "./main.js";export { discoverSourcePackages } from "./source-discovery.js";+export { narratageHostStateRoot, narratageProjectStateRoot } from "./paths.js";export { renderCliError, writeCliHelp, writeCliOutput } from "./output.js";export type {CliColorMode,diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.tsindex ad3745bb..a2c2bf98 100644--- a/packages/cli/src/main.ts+++ b/packages/cli/src/main.ts@@ -1,8 +1,9 @@import { randomUUID } from "node:crypto";import { dirname, isAbsolute, relative, resolve, sep } from "node:path";-import { readFile } from "node:fs/promises";+import { readFile, stat } from "node:fs/promises";import type { NodeCompiledSourceClosure } from "@narratage/compiler-node";+import type { NodeRuntimeHost } from "@narratage/runtime-adapter-node";import { plannedNeeds } from "@narratage/runtime";import type { BuildCatalogDescriptor, CapacityReservation, OperationProgress } from "@narratage/runtime";import type { BuildState, CapabilityRef, TypeRef } from "@narratage/protocol";@@ -31,27 +32,22 @@ import { checkRunFile, collectRunFrontends, loadRunFile } from "./run-file.js";import type { CliDistribution } from "./distribution.js";import type {CliBuildSubmission,- CliExternalServiceProgress,- CliExternalServiceReport,+ CliManagedProgramProgress,+ CliManagedProgramReport,CliRuntime,CliRuntimeArchiveControl,CliRuntimeArtifactAccess,+ CliRuntimeController,CliRuntimeMaintenance,} from "./runtime-port.js";import { writeCliHelp, writeCliOutput } from "./output.js";import type { CliColorMode, CliIo } from "./output.js";import { withPackageLockEdit } from "./package-lock-edit.js";+import { narratageHostStateRoot, narratageProjectStateRoot } from "./paths.js";import {createDiscoveredSourceInventory,loadDiscoveredSourcePackages,} from "./source-packages.js";-import {- ensureRuntimeProcess,- markRuntimeProcessReady,- runtimeProcessLogs,- runtimeProcessStatus,- stopRuntimeProcess,-} from "./runtime-process.js";import {clearRuntimeProfile,findRuntimeProfile,@@ -84,7 +80,7 @@ type ParsedArgs = {readonly to: string | undefined;readonly apply: boolean;/** Leave the declared external programs alone; build against what is running. */- readonly noServices: boolean;+ readonly noPrograms: boolean;readonly json: boolean;readonly color: CliColorMode;readonly verbose: boolean;@@ -100,13 +96,28 @@ type ParsedArgs = {readonly seenOptions: readonly string[];};+async function nearestSourcePackageLock(start: string): Promise<string | undefined> {+ let directory = resolve(start);+ while (true) {+ const candidate = resolve(directory, "svml.packages.lock");+ try {+ if ((await stat(candidate)).isFile()) return candidate;+ } catch (error) {+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;+ }+ const parent = dirname(directory);+ if (parent === directory) return undefined;+ directory = parent;+ }+}+function parseArgs(argv: readonly string[]): ParsedArgs {const [command, ...tail] = argv;- const scoped = command === "services" || command === "runtime" || command === "auth"+ const scoped = command === "programs" || command === "runtime" || command === "auth"|| command === "packages";const action = scoped ? tail[0] : undefined;const positional = scoped ? tail.slice(1) : tail;- const noFile = command === "builds" || command === "queue";+ const noFile = command === "builds" || command === "queue" || command === "paths";const hasFile = !noFile && positional[0] !== undefined && !positional[0]!.startsWith("--");const file = hasFile ? positional[0] : undefined;const rest = noFile || !hasFile ? positional : positional.slice(1);@@ -128,7 +139,7 @@ function parseArgs(argv: readonly string[]): ParsedArgs {let artifact: string | undefined;let to: string | undefined;let apply = false;- let noServices = false;+ let noPrograms = false;let json = false;let color: CliColorMode = "auto";let verbose = false;@@ -145,7 +156,7 @@ function parseArgs(argv: readonly string[]): ParsedArgs {if (item.startsWith("--")) {const repeatable = ["--package", "--add", "--remove", "--json", "--jsonl", "--watch", "--verbose", "--debug",- "--no-color", "--refresh", "--follow", "--apply", "--no-services", "--asset-root",+ "--no-color", "--refresh", "--follow", "--apply", "--no-programs", "--asset-root",].includes(item);if (!repeatable && seenOptions.has(item)) throw new Error(`${item} cannot be repeated`);seenOptions.add(item);@@ -182,9 +193,9 @@ function parseArgs(argv: readonly string[]): ParsedArgs {index += 1;continue;}- if (item === "--root") {+ if (item === "--workspace") {const value = rest[index + 1];- if (value === undefined || value.startsWith("--")) throw new Error("--root requires a directory");+ if (value === undefined || value.startsWith("--")) throw new Error("--workspace requires a directory");workspaceRoot = resolve(value);index += 1;continue;@@ -292,8 +303,8 @@ function parseArgs(argv: readonly string[]): ParsedArgs {apply = true;continue;}- if (item === "--no-services") {- noServices = true;+ if (item === "--no-programs") {+ noPrograms = true;continue;}if (item === "--max-wait-ms") {@@ -365,7 +376,7 @@ function parseArgs(argv: readonly string[]): ParsedArgs {artifact,to,apply,- noServices,+ noPrograms,json,color,verbose,@@ -389,9 +400,9 @@ function assertCommandOptions(args: ParsedArgs): void {add("--package", "--add", "--remove", "--refresh", "--verify", "--package-root");break;case "packages":- add("--runtime", "--root", "--package-root");+ add("--runtime", "--workspace", "--package-root");break;- case "services":+ case "programs":// This command has older, more specific diagnostics for deployment-selection// flags and waiting on status/down; let its handler render those repairs.add("--max-wait-ms", "--runtime", "--package-lock", "--package-root", "--package", "--apply");@@ -410,6 +421,9 @@ function assertCommandOptions(args: ParsedArgs): void {case "queue":add("--runtime", "--watch", "--jsonl");break;+ case "paths":+ add("--runtime");+ break;case "get":add("--runtime", "--name", "--record", "--output", "--artifact", "--to");break;@@ -425,18 +439,18 @@ function assertCommandOptions(args: ParsedArgs): void {break;case "check":case "plan":- add("--runtime", "--package-lock", "--package-root", "--root", "--asset-root");+ add("--runtime", "--package-lock", "--package-root", "--workspace", "--asset-root");break;case "build":- add("--runtime", "--package-lock", "--package-root", "--root", "--asset-root", "--follow",- "--max-wait-ms", "--no-services");+ add("--runtime", "--package-lock", "--package-root", "--workspace", "--asset-root", "--follow",+ "--max-wait-ms", "--no-programs");break;}const invalid = args.seenOptions.find((item) => !allowed.has(item));if (invalid !== undefined) {const command = args.action === undefined ? args.command : `${args.command} ${args.action}`;- if (args.command === "doctor" && invalid === "--root") {- throw new Error("doctor already uses the Runtime Profile directory and its declared root; remove --root");+ if (args.command === "doctor" && invalid === "--workspace") {+ throw new Error("doctor does not compile a Source Workspace; remove --workspace");}throw new Error(`${invalid} does not apply to ${command}`);}@@ -451,17 +465,17 @@ function usage(): string {" narratage lock-packages <lock> --package name [...] [--package-root directory] # exact create/replace"," narratage lock-packages <lock> (--add name [...] | --remove name [...]) [--package-root directory]"," narratage lock-packages <lock> (--refresh | --verify) [--package-root directory]",- " narratage packages sync <run-source> [--runtime <runtime-profile>] [--root workspace]",+ " narratage packages sync <run-source> [--runtime <runtime-profile>] [--workspace workspace]"," narratage doctor [<runtime-profile>]",- " narratage services up|down|status [<runtime-profile>] [--max-wait-ms milliseconds]",+ " narratage programs up|down|status [<runtime-profile>] [--max-wait-ms milliseconds]"," narratage runtime use <runtime-profile>"," narratage runtime unset"," narratage runtime up|status|logs|down [<runtime-profile>]"," narratage queue [--runtime profile.json] [--watch]"," narratage gc [<runtime-profile>] [--apply]",- " narratage check <self-described-source> [--runtime profile.json] [--package-lock file] [--root workspace] [--asset-root directory]",- " narratage plan <run-source> [--runtime profile.json] [--package-lock file] [--root workspace] [--asset-root directory]",- " narratage build <run-source> [--runtime profile.json] [--root workspace] [--asset-root directory] [--follow] [--no-services]",+ " narratage check <self-described-source> [--runtime profile.json] [--package-lock file] [--workspace workspace] [--asset-root directory]",+ " narratage plan <run-source> [--runtime profile.json] [--package-lock file] [--workspace workspace] [--asset-root directory]",+ " narratage build <run-source> [--runtime profile.json] [--workspace workspace] [--asset-root directory] [--follow] [--no-programs]"," narratage status <build-id> [--runtime profile.json]"," narratage builds [--runtime profile.json]"," narratage history [source-output-name] [--runtime profile.json] [--source author.svml]",@@ -507,34 +521,33 @@ function createCatalogDescriptor(options: {* running otherwise surfaces as a refused connection partway through, after the* paid generation ahead of it has already been spent.*- * Services are started and left running: a developer submits several Builds+ * Programs are started and left running: a developer submits several Builds* against one warm program, and stopping it between them would pay the model- * load every time. `narratage services down` ends them.+ * load every time. `narratage programs down` ends them.*/-async function startDeclaredServices(- path: string,- distribution: CliDistribution,+async function startDeclaredPrograms(+ controller: CliRuntimeController,capabilities: readonly CapabilityRef[],- onProgress?: (event: CliExternalServiceProgress) => void,-): Promise<readonly CliExternalServiceReport[] | undefined> {- const result = await distribution.externalServices.up(resolve(path), {+ onProgress?: (event: CliManagedProgramProgress) => void,+): Promise<readonly CliManagedProgramReport[] | undefined> {+ const result = await controller.programs.up({capabilities,...(onProgress === undefined ? {} : { onProgress }),});- const unavailable = result.services.filter((item) => item.state.state !== "ready");+ const unavailable = result.programs.filter((item) => item.state.state !== "ready");if (unavailable.length > 0) {throw new Error([- `${unavailable.length} external service${unavailable.length === 1 ? " is" : "s are"} not ready:`,+ `${unavailable.length} external program${unavailable.length === 1 ? " is" : "s are"} not ready:`,// The report carries two reasons that do not overlap: what the probe saw,// and why the attempt to fix it fell short. Both name a different repair....unavailable.map((item) => ` ${item.id}: ${item.state.state}`+ `${"detail" in item.state ? ` — ${item.state.detail}` : ""}`+ `${item.detail === undefined ? "" : `; ${item.detail}`}`+ `${item.logPath === undefined ? "" : ` (log: ${item.logPath})`}`),- "Fix the service, or pass --no-services to build against what is already running.",+ "Fix the program, or pass --no-programs to build against what is already running.",].join("\n"));}- return result.services;+ return result.programs;}function demandedCapabilities(state: BuildState): readonly CapabilityRef[] {@@ -547,19 +560,18 @@ function capabilityName(capability: CapabilityRef): string {}async function preflightPlan(- runtimeProfile: string,- distribution: CliDistribution,+ host: NodeRuntimeHost,state: BuildState,implementationPackages?: LoadedNodePackageSet,) {const capabilities = demandedCapabilities(state);- const result = await distribution.doctorRuntimeConfig(runtimeProfile, {+ const result = await host.doctor({capabilities,...(implementationPackages === undefined ? {} : { implementationPackages }),});return {ok: !result.diagnostics.some((item) => item.severity === "error"),- root: result.root,+ dataRoot: result.dataRoot,capabilities: capabilities.map(capabilityName),diagnostics: result.diagnostics,} as const;@@ -581,37 +593,33 @@ function assertPreflight(}async function loadRuntime(- path: string,- distribution: CliDistribution,+ host: NodeRuntimeHost,implementationPackages?: LoadedNodePackageSet,): Promise<CliRuntime> {- return await distribution.createRuntimeFromConfig(path, {+ return await host.createRuntime({...(implementationPackages === undefined ? {} : { implementationPackages }),});}async function loadRuntimeArchive(- path: string,- distribution: CliDistribution,+ host: NodeRuntimeHost,readOnly = true,): Promise<CliRuntimeArchiveControl> {- return await distribution.createRuntimeArchiveFromConfig(path, { readOnly });+ return await host.openArchive({ readOnly });}async function loadRuntimeArtifactAccess(- path: string,- distribution: CliDistribution,+ host: NodeRuntimeHost,readOnly = true,): Promise<CliRuntimeArtifactAccess> {- return await distribution.createRuntimeArtifactAccessFromConfig(path, { readOnly });+ return await host.openArtifacts({ readOnly });}async function loadRuntimeMaintenance(- path: string,- distribution: CliDistribution,+ host: NodeRuntimeHost,readOnly = true,): Promise<CliRuntimeMaintenance> {- return await distribution.createRuntimeMaintenanceFromConfig(path, { readOnly });+ return await host.openMaintenance({ readOnly });}function displayType(type: TypeRef): string {@@ -677,14 +685,14 @@ function queueRouteLines(groups: readonly QueueRouteSummary[]): readonly string[return lines;}-function externalServiceLine(service: CliExternalServiceReport): string {- const stateDetail = "detail" in service.state ? ` — ${service.state.detail}` : "";- const action = service.action === undefined ? "" : ` · ${service.action}`;- const detail = service.detail === undefined ? "" : ` · ${service.detail}`;- const instances = service.instances.length === 0 ? "" : ` · ${service.instances.join(", ")}`;- const pid = service.pid === undefined ? "" : ` · pid ${service.pid}`;- const log = service.logPath === undefined ? "" : ` · log ${service.logPath}`;- return `${service.id}: ${service.state.state}${stateDetail}${action}${detail}${instances}${pid}${log}`;+function programLine(program: CliManagedProgramReport): string {+ const stateDetail = "detail" in program.state ? ` — ${program.state.detail}` : "";+ const action = program.action === undefined ? "" : ` · ${program.action}`;+ const detail = program.detail === undefined ? "" : ` · ${program.detail}`;+ const instances = program.instances.length === 0 ? "" : ` · ${program.instances.join(", ")}`;+ const pid = program.pid === undefined ? "" : ` · pid ${program.pid}`;+ const log = program.logPath === undefined ? "" : ` · log ${program.logPath}`;+ return `${program.id}: ${program.state.state}${stateDetail}${action}${detail}${instances}${pid}${log}`;}function inlineValuePreview(value: unknown, limit = 240): string {@@ -698,8 +706,7 @@ async function observeBuild(initial: CliBuildSubmission,options: {readonly maxWaitMs?: number;- readonly workerProfile?: string;- readonly workerProfileDigest?: string;+ readonly controller?: CliRuntimeController;readonly onProgress?: (value: {readonly build: string;readonly phase: string;@@ -735,13 +742,12 @@ async function observeBuild(dispatch: status.dispatch,};if (!["complete", "failed", "cancelled"].includes(current.status)- && options.workerProfile !== undefined- && options.workerProfileDigest !== undefined) {- const worker = await runtimeProcessStatus(options.workerProfile, options.workerProfileDigest);+ && options.controller !== undefined) {+ const worker = await options.controller.worker.status();if (worker.state !== "running") {throw new Error(`Runtime Worker is ${worker.state}; Build ${current.id} remains durable. `- + `Run narratage runtime up ${options.workerProfile}, then observe the same Build again`,+ + "Run narratage runtime up, then inspect the same Build again",);}}@@ -800,12 +806,11 @@ type RuntimeArchiveView = Pick<CliRuntimeArchiveControl, "status" | "close">;* the Runtime Profile single-source the author package lock for every plan.*/function lazyRuntimeArchive(- path: string,- distribution: CliDistribution,+ host: NodeRuntimeHost,): RuntimeArchiveView {let loading: Promise<CliRuntimeArchiveControl> | undefined;const open = (): Promise<CliRuntimeArchiveControl> => {- loading ??= loadRuntimeArchive(path, distribution);+ loading ??= loadRuntimeArchive(host);return loading;};return {@@ -841,9 +846,9 @@ export async function runCli(color: args.color,verbose: args.verbose,}, { kind: "operational", machine, title, status, facts, lines });- const reportServiceProgress = args.json || args.jsonl+ const reportProgramProgress = args.json || args.jsonl? undefined- : (event: CliExternalServiceProgress): void => {+ : (event: CliManagedProgramProgress): void => {const verb = {checking: "Checking",preparing: "Preparing",@@ -853,26 +858,27 @@ export async function runCli(}[event.phase];io.write(` · ${verb} ${event.id}\n`);};+ const runtimeHosts = new Map<string, Promise<NodeRuntimeHost>>();+ const runtimeHost = async (path: string): Promise<NodeRuntimeHost> => {+ const profile = resolve(path);+ let opened = runtimeHosts.get(profile);+ if (opened === undefined) {+ opened = distribution.openRuntimeHost(profile);+ runtimeHosts.set(profile, opened);+ }+ return await opened;+ };if (args.command === "_worker") {if (args.file === undefined || args.readyFile === undefined) throw new Error("internal Worker launch is incomplete");- const runtime = await loadRuntime(resolve(args.file), distribution);- const abort = new AbortController();- const stop = (): void => abort.abort();- process.once("SIGTERM", stop);- process.once("SIGINT", stop);- try {- await markRuntimeProcessReady(args.readyFile);- await runtime.work({- owner: `worker-${process.pid}`,- leaseMs: 30_000,- idlePollMs: 250,- signal: abort.signal,- });- } finally {- process.removeListener("SIGTERM", stop);- process.removeListener("SIGINT", stop);- await runtime.close();- }+ const implementationPackages = args.packageLock === undefined+ ? undefined+ : await loadNodePackageSet(+ args.packageLock,+ args.packageRoot ?? distribution.packageRoot ?? dirname(args.packageLock),+ );+ await (await runtimeHost(args.file)).runWorker(args.readyFile, {+ ...(implementationPackages === undefined ? {} : { implementationPackages }),+ });return;}if (args.command === "runtime" && args.action === "use") {@@ -882,21 +888,17 @@ export async function runCli(if (args.file === undefined) throw new Error("runtime use requires a Runtime Profile");assertCommandOptions(args);const profile = resolve(args.file);- const packageSelection = await distribution.resolveCompilationPackages?.(profile);- const selected = await selectRuntimeProfile(packageSelection?.root ?? dirname(profile), profile);+ const packageSelection = await (await runtimeHost(profile)).resolvePackages();+ const selected = await selectRuntimeProfile(args.workspaceRoot ?? process.cwd(), profile);writeOperational({format: "narratage.cli-runtime-selection@1",profile: selected.profile,- root: selected.projectRoot,+ project: selected.projectRoot,selectionFile: selected.selectionFile,- authorPackageLock: packageSelection?.packageLock,runtimePackageLock: packageSelection?.runtimePackageLock,}, "Runtime selected", "success", [["Profile", selected.profile],["Project", selected.projectRoot],- ...(packageSelection?.packageLock === undefined- ? []- : [["Author lock", packageSelection.packageLock] as const]),...(packageSelection?.runtimePackageLock === undefined? []: [["Runtime lock", packageSelection.runtimePackageLock] as const]),@@ -914,7 +916,7 @@ export async function runCli(selected: false,removed: cleared !== undefined,profile: cleared?.profile,- root: cleared?.projectRoot,+ project: cleared?.projectRoot,}, cleared === undefined ? "No Runtime was selected" : "Runtime selection removed",cleared === undefined ? "info" : "success", cleared === undefined ? [] : [["Profile", cleared.profile], ["Project", cleared.projectRoot],@@ -922,10 +924,11 @@ export async function runCli(return;}- const positionalRuntime = (args.command === "runtime" || args.command === "services"+ const positionalRuntime = (args.command === "runtime" || args.command === "programs"|| args.command === "doctor" || args.command === "gc") && args.file !== undefined;const runtimeWasExplicit = args.runtime !== undefined || positionalRuntime;let runtimeNeedsHint = runtimeWasExplicit;+ let selectedRuntimeProjectRoot: string | undefined;if (args.runtime === undefined && !positionalRuntime) {const sourceScoped = args.command === "check" || args.command === "plan" || args.command === "build"|| args.command === "packages";@@ -933,6 +936,7 @@ export async function runCli(const selected = await findRuntimeProfile(start);if (selected !== undefined) {args = { ...args, runtime: selected.profile };+ selectedRuntimeProjectRoot = selected.projectRoot;const cwdFromProject = relative(selected.projectRoot, resolve(process.cwd()));runtimeNeedsHint = cwdFromProject === ".." || cwdFromProject.startsWith(`..${sep}`)|| isAbsolute(cwdFromProject);@@ -942,11 +946,12 @@ export async function runCli(|| args.command === "build" || args.command === "status" || args.command === "builds"|| args.command === "history"|| args.command === "inspect" || args.command === "get" || args.command === "cancel"- || args.command === "doctor" || args.command === "gc" || args.command === "services"- || args.command === "runtime" || args.command === "queue";+ || args.command === "doctor" || args.command === "gc" || args.command === "programs"+ || args.command === "runtime" || args.command === "queue" || args.command === "paths";const operational = known || args.command === "auth";const fileOptional = args.command === "builds" || args.command === "history" || args.command === "queue"- || args.command === "services" || args.command === "runtime" || args.command === "doctor"+ || args.command === "paths"+ || args.command === "programs" || args.command === "runtime" || args.command === "doctor"|| args.command === "gc";if (!operational || (!fileOptional && args.file === undefined)) {throw new Error(usage());@@ -956,13 +961,46 @@ export async function runCli(throw new Error("--jsonl applies only to queue --watch");}if (args.watch && args.json) throw new Error("queue --watch is a stream; use --jsonl instead of --json");- if (args.noServices && args.command !== "build") {- throw new Error("--no-services is only valid for build; no other command starts an external program");+ if (args.noPrograms && args.command !== "build") {+ throw new Error("--no-programs is only valid for build; no other command starts an external program");}if (args.command === "history" && args.file === undefined && args.source === undefined) {throw new Error("history requires an output name or --source path");}assertCommandOptions(args);+ const runtimeController = async (profile: string, source?: string): Promise<CliRuntimeController> => {+ const workspaceRoot = args.workspaceRoot+ ?? selectedRuntimeProjectRoot+ ?? (source === undefined ? process.cwd() : dirname(resolve(source)));+ const packageLock = await nearestSourcePackageLock(workspaceRoot);+ return await (await runtimeHost(profile)).controller({+ workspaceRoot,+ ...(packageLock === undefined ? {} : { packageLock }),+ packageRoot: args.packageRoot ?? distribution.packageRoot ?? workspaceRoot,+ });+ };+ if (args.command === "paths") {+ const projectRoot = selectedRuntimeProjectRoot ?? process.cwd();+ const runtimeSelection = args.runtime === undefined+ ? undefined+ : await (await runtimeHost(args.runtime)).resolvePackages();+ const machine = {+ format: "narratage.cli-paths@1" as const,+ project: projectRoot,+ projectState: narratageProjectStateRoot(projectRoot),+ profile: args.runtime,+ runtimeData: runtimeSelection?.runtimeDataRoot,+ hostState: narratageHostStateRoot(),+ };+ writeOperational(machine, "Narratage paths", "info", [+ ["Project", machine.project],+ ["Project state", machine.projectState],+ ["Runtime Profile", machine.profile ?? "not selected"],+ ["Runtime data", machine.runtimeData ?? "not selected"],+ ["Host state", machine.hostState],+ ]);+ return;+ }if (args.command === "lock-packages") {const exact = args.packages.length > 0;const mutation = args.addPackages.length > 0 || args.removePackages.length > 0;@@ -1106,17 +1144,19 @@ export async function runCli(}const source = resolve(args.file!);const profile = resolve(args.runtime);- const selection = await distribution.resolveCompilationPackages?.(profile);- if (selection?.packageLock === undefined || selection.runtimePackageLock === undefined) {- throw new Error("packages sync requires the Runtime Profile to declare both packageLock and runtimePackageLock");+ const selection = await (await runtimeHost(profile)).resolvePackages();+ if (selection.runtimePackageLock === undefined) {+ throw new Error("packages sync requires the Runtime Profile to declare runtimePackageLock");}if (selection.runtimeSelection === undefined) {throw new Error("this Distribution cannot discover Runtime packages from the selected Profile");}const runtimeSelection = selection.runtimeSelection;- const syncWorkspaceRoot = args.workspaceRoot ?? selection.root;+ const sourceLock = await nearestSourcePackageLock(dirname(source))+ ?? resolve(dirname(source), "svml.packages.lock");+ const syncWorkspaceRoot = args.workspaceRoot ?? selectedRuntimeProjectRoot ?? dirname(sourceLock);const packageRoot = args.packageRoot ?? selection.packageRoot ?? distribution.packageRoot ?? dirname(profile);- const locks = [resolve(selection.packageLock), resolve(selection.runtimePackageLock)].sort();+ const locks = [resolve(sourceLock), resolve(selection.runtimePackageLock)].sort();if (locks[0] === locks[1]) throw new Error("packageLock and runtimePackageLock must be different files");const summarizeDifference = (before: NodePackageLock | undefined, after: NodePackageLock) => {const oldArtifacts = new Map(before?.artifacts.map((item) => [`${item.name}@${item.version}`, item.digest]) ?? []);@@ -1139,7 +1179,7 @@ export async function runCli(}};await withPackageLockEdit(locks[0]!, async () => await withPackageLockEdit(locks[1]!, async () => {- const authorBefore = await readExistingLock(selection.packageLock!);+ const authorBefore = await readExistingLock(sourceLock);const runtimeBefore = await readExistingLock(selection.runtimePackageLock!);const discovered = await createDiscoveredSourceInventory(distribution, {source,@@ -1169,7 +1209,7 @@ export async function runCli(const runtimeSelected = runtimeInventory.lock.selected;const authorAfter = discovered.packages.lock;const runtimeAfter = runtimeInventory.lock;- if (authorBefore?.digest !== authorAfter.digest) await writeNodePackageLock(selection.packageLock!, authorAfter);+ if (authorBefore?.digest !== authorAfter.digest) await writeNodePackageLock(sourceLock, authorAfter);if (runtimeBefore?.digest !== runtimeAfter.digest) await writeNodePackageLock(selection.runtimePackageLock!, runtimeAfter);const author = summarizeDifference(authorBefore, authorAfter);const runtime = summarizeDifference(runtimeBefore, runtimeAfter);@@ -1186,7 +1226,7 @@ export async function runCli(author: authorSelected,runtime: runtimeSelected,},- author: { path: selection.packageLock, digest: authorAfter.digest, difference: author },+ author: { path: sourceLock, digest: authorAfter.digest, difference: author },runtime: { path: selection.runtimePackageLock, digest: runtimeAfter.digest, difference: runtime },}, changed ? "Project package locks synchronized" : "Project package locks already current",changed ? "success" : "info", [@@ -1218,61 +1258,62 @@ export async function runCli(throw new Error("doctor requires a Runtime Profile; run narratage runtime use <profile> or provide it positionally");}const profile = resolve(profileInput);- const result = await distribution.doctorRuntimeConfig(profile);+ const result = await (await runtimeHost(profile)).doctor();const machine = {format: "narratage.cli-doctor@1" as const,ok: !result.diagnostics.some((item) => item.severity === "error"),- root: result.root,+ dataRoot: result.dataRoot,diagnostics: result.diagnostics,};writeCliOutput(io, args, { kind: "doctor", machine, profile });if (!machine.ok) io.setExitCode?.(1);return;}- if (args.command === "services") {+ if (args.command === "programs") {if (args.file !== undefined && args.runtime !== undefined) {- throw new Error("services reads all deployment selection from the Runtime Profile itself; provide that Profile only once");+ throw new Error("programs reads all deployment selection from the Runtime Profile itself; provide that Profile only once");}if (args.packageLock !== undefined || args.packageRoot !== undefined|| args.packages.length > 0 || args.apply) {- throw new Error("services reads all deployment selection from the Runtime Profile itself");+ throw new Error("programs reads all deployment selection from the Runtime Profile itself");}if (args.action !== "up" && args.action !== "down" && args.action !== "status") {- throw new Error("services takes up, down or status");+ throw new Error("programs takes up, down or status");}if (args.action !== "up" && args.maxWaitMs !== undefined) {- throw new Error("--max-wait-ms applies to services up");+ throw new Error("--max-wait-ms applies to programs up");}const profileInput = args.runtime ?? args.file;- if (profileInput === undefined) throw new Error("services requires a Runtime Profile");+ if (profileInput === undefined) throw new Error("programs requires a Runtime Profile");const profile = resolve(profileInput);- const result = args.action === "up"- ? await distribution.externalServices.up(profile, {+ const controller = await runtimeController(profile);+ const result = args.action === "up"+ ? await controller.programs.up({...(args.maxWaitMs === undefined ? {} : { maxWaitMs: args.maxWaitMs }),- ...(reportServiceProgress === undefined ? {} : { onProgress: reportServiceProgress }),+ ...(reportProgramProgress === undefined ? {} : { onProgress: reportProgramProgress }),}): args.action === "down"- ? await distribution.externalServices.down(profile)- : await distribution.externalServices.report(profile);- const ready = result.services.every((item) => item.state.state === "ready");- const desiredState = args.action === "down" ? !result.services.some((item) => item.state.state === "ready") : ready;+ ? await controller.programs.down()+ : await controller.programs.report();+ const ready = result.programs.every((item) => item.state.state === "ready");+ const desiredState = args.action === "down" ? !result.programs.some((item) => item.state.state === "ready") : ready;const machine = {- format: "narratage.cli-services-status@1" as const,+ format: "narratage.cli-programs-status@1" as const,// A successful status query is not a failed lifecycle action. `ready` carries readiness.ok: args.action === "status" ? true : desiredState,ready,- root: result.root,- services: result.services,+ dataRoot: result.dataRoot,+ programs: result.programs,};- const shownServices = args.verbose || args.action !== "status"- ? result.services- : result.services.filter((item) => item.state.state !== "ready");- writeOperational(machine, `External services ${args.action}`,+ const shownPrograms = args.verbose || args.action !== "status"+ ? result.programs+ : result.programs.filter((item) => item.state.state !== "ready");+ writeOperational(machine, `External programs ${args.action}`,args.action === "status" ? ready ? "success" : "info" : machine.ok ? "success" : "warning", [- ["Root", result.root],- ["Services", String(result.services.length)],- ["Ready", String(result.services.filter((item) => item.state.state === "ready").length)],- ], shownServices.map(externalServiceLine));+ ["Data root", result.dataRoot],+ ["Programs", String(result.programs.length)],+ ["Ready", String(result.programs.filter((item) => item.state.state === "ready").length)],+ ], shownPrograms.map(programLine));if (args.action !== "status" && !machine.ok) io.setExitCode?.(1);return;}@@ -1286,33 +1327,39 @@ export async function runCli(const profileInput = args.runtime ?? args.file;if (profileInput === undefined) throw new Error("runtime requires a Runtime Profile");const profile = resolve(profileInput);+ const controller = await runtimeController(profile);if (args.action === "up") {// Validate the exact Runtime Closure against unfinished work before replacing a stale Worker// or starting external programs. A refusal must leave the old execution environment intact.- const validated = await loadRuntime(profile, distribution);+ const workspaceRoot = args.workspaceRoot ?? selectedRuntimeProjectRoot ?? process.cwd();+ const sourceLock = await nearestSourcePackageLock(workspaceRoot);+ const implementationPackages = sourceLock === undefined+ ? undefined+ : await loadNodePackageSet(+ sourceLock,+ args.packageRoot ?? distribution.packageRoot ?? workspaceRoot,+ );+ const validated = await loadRuntime(await runtimeHost(profile), implementationPackages);await validated.close();- const external = await distribution.externalServices.up(profile, {+ const external = await controller.programs.up({+ ...(args.maxWaitMs === undefined ? {} : { maxWaitMs: args.maxWaitMs }),+ ...(reportProgramProgress === undefined ? {} : { onProgress: reportProgramProgress }),+ });+ const processState = await controller.worker.up({...(args.maxWaitMs === undefined ? {} : { maxWaitMs: args.maxWaitMs }),- ...(reportServiceProgress === undefined ? {} : { onProgress: reportServiceProgress }),});- const processState = await ensureRuntimeProcess(- profile,- distribution.runtimeWorkerLaunch(),- await distribution.runtimeProfileRevision(profile),- args.maxWaitMs ?? 10_000,- );const ok = processState.state === "running"- && external.services.every((item) => item.state.state === "ready");- writeOperational({ ok, worker: processState, services: external.services }, "Runtime is up",+ && external.programs.every((item) => item.state.state === "ready");+ writeOperational({ ok, worker: processState, programs: external.programs }, "Runtime is up",ok ? "success" : "warning", [["Worker", String(processState.pid)],- ["External services", String(external.services.length)],+ ["External programs", String(external.programs.length)],]);if (!ok) io.setExitCode?.(1);return;}if (args.action === "logs") {- const logs = await runtimeProcessLogs(profile);+ const logs = await controller.worker.logs();const lines = logs.text.length === 0 ? [] : logs.text.replace(/\n$/u, "").split("\n");const shown = args.verbose ? lines : lines.slice(-100);writeOperational({@@ -1326,21 +1373,22 @@ export async function runCli(return;}if (args.action === "down") {- const worker = await stopRuntimeProcess(profile, args.maxWaitMs ?? 10_000);+ const worker = await controller.worker.down({+ ...(args.maxWaitMs === undefined ? {} : { maxWaitMs: args.maxWaitMs }),+ });writeOperational({ ok: true, worker }, "Runtime Worker is down", "success", [["Worker", worker.state],- ], ["External programs were left running. Stop them explicitly with narratage services down."]);+ ], ["External programs were left running. Stop them explicitly with narratage programs down."]);return;}// These are independent views over one Profile. Load them concurrently without inventing a// second registry; each selected package remains the authority for its own report.- const runtimeLoading = loadRuntimeArchive(profile, distribution);+ const runtimeLoading = loadRuntimeArchive(await runtimeHost(profile));let runtime: CliRuntimeArchiveControl | undefined;try {const loaded = await Promise.all([- distribution.runtimeProfileRevision(profile)- .then(async (digest) => await runtimeProcessStatus(profile, digest)),- distribution.externalServices.report(profile),+ controller.worker.status(),+ controller.programs.report(),runtimeLoading,]);const [worker, external, selectedRuntime] = loaded;@@ -1350,11 +1398,11 @@ export async function runCli(.map((phase) => [phase, queue.dispatches.filter((item) => item.phase === phase).length]));const routes = summarizeQueueRoutes(queue.capacity);const ready = worker.state === "running"- && external.services.every((item) => item.state.state === "ready");+ && external.programs.every((item) => item.state.state === "ready");const active = ["queued", "leased", "waiting", "blocked", "settling"].reduce((total, phase) => total + (counts[phase] ?? 0), 0);const attention = active > 0 && !ready;- const unavailable = external.services.filter((item) => item.state.state !== "ready");+ const unavailable = external.programs.filter((item) => item.state.state !== "ready");const machine = {format: "narratage.cli-runtime-status@1" as const,ok: true,@@ -1362,17 +1410,17 @@ export async function runCli(attention,worker,queue: { counts, routes, capacity: queue.capacity },- services: external.services,+ programs: external.programs,};writeOperational(machine, "Runtime status", attention ? "warning" : ready ? "success" : "info", [["Worker", worker.state],["Queued", String(counts.queued ?? 0)],["Running", String(counts.leased ?? 0)],["Waiting", String(counts.waiting ?? 0)],- ["Services", `${external.services.length - unavailable.length}/${external.services.length} ready`],+ ["Programs", `${external.programs.length - unavailable.length}/${external.programs.length} ready`],["Capacity reservations", String(queue.capacity.length)],], [- ...unavailable.map(externalServiceLine),+ ...unavailable.map(programLine),...queueRouteLines(routes),]);} finally {@@ -1389,7 +1437,7 @@ export async function runCli(if (profileInput === undefined) {throw new Error("gc requires a Runtime Profile; run narratage runtime use <profile> or provide it positionally");}- const runtime = await loadRuntimeMaintenance(resolve(profileInput), distribution, !args.apply);+ const runtime = await loadRuntimeMaintenance(await runtimeHost(profileInput), !args.apply);try {const report = await runtime.garbageCollectArtifacts({ apply: args.apply });const machine = {@@ -1417,7 +1465,7 @@ export async function runCli(throw new Error("auth requires a Runtime; run narratage runtime use <profile> or pass --runtime <profile>");}if (args.from !== undefined && args.action !== "login") throw new Error("--from applies only to auth login");- const runtime = await distribution.createRuntimeCredentialsFromConfig(args.runtime, args.file!);+ const runtime = await (await runtimeHost(args.runtime)).openCredentials(args.file!);try {let credentials = await runtime.credentials(args.file!);if (args.slot !== undefined) credentials = credentials.filter((item) => item.slot === args.slot);@@ -1471,8 +1519,8 @@ export async function runCli(}if (args.apply) throw new Error("--apply is only valid for gc");if (args.refresh) throw new Error("--refresh is only valid for lock-packages");- if (args.noServices && args.command !== "build") {- throw new Error("--no-services is only valid for build; no other command starts an external program");+ if (args.noPrograms && args.command !== "build") {+ throw new Error("--no-programs is only valid for build; no other command starts an external program");}if ((args.record !== undefined || args.output !== undefined || args.name !== undefined|| args.artifact !== undefined || args.to !== undefined)@@ -1490,15 +1538,15 @@ export async function runCli(`${args.command} requires a Runtime; run narratage runtime use <profile> or pass --runtime <profile>`,);}- const runtime = await loadRuntimeArchive(args.runtime, distribution, args.command !== "cancel");+ const runtime = await loadRuntimeArchive(await runtimeHost(args.runtime), args.command !== "cancel");try {if (args.command === "queue") {+ const controller = await runtimeController(args.runtime);let previous: string | undefined;const writeQueue = async (): Promise<void> => {const [queue, worker] = await Promise.all([runtime.queue(),- distribution.runtimeProfileRevision(args.runtime!)- .then(async (digest) => await runtimeProcessStatus(args.runtime!, digest)),+ controller.worker.status(),]);const fingerprint = JSON.stringify({dispatches: queue.dispatches,@@ -1752,7 +1800,7 @@ export async function runCli(} else {const [first] = references;if (first === undefined) throw new Error(`Build ${args.file} does not reference Artifact ${args.artifact}`);- const artifacts = await loadRuntimeArtifactAccess(args.runtime!, distribution);+ const artifacts = await loadRuntimeArtifactAccess(await runtimeHost(args.runtime!));let materialized;try {materialized = await materializeArtifact(artifacts, first, args.to, `Build ${args.file}`);@@ -1792,7 +1840,7 @@ export async function runCli(["Artifacts", String(machine.artifacts.length)],]);} else {- const artifacts = await loadRuntimeArtifactAccess(args.runtime!, distribution);+ const artifacts = await loadRuntimeArtifactAccess(await runtimeHost(args.runtime!));let materialized;try {materialized = await materializeRecord(artifacts, record, args.to);@@ -1841,18 +1889,15 @@ export async function runCli(if (args.packages.length > 0) throw new Error("--package is only valid for lock-packages");const runtimePackageSelection = args.runtime === undefined? undefined- : await distribution.resolveCompilationPackages?.(args.runtime);- if (args.packageLock !== undefined && runtimePackageSelection?.packageLock !== undefined- && resolve(args.packageLock) !== resolve(runtimePackageSelection.packageLock)) {- throw new Error(- `--package-lock ${args.packageLock} differs from the deterministic package lock selected by ${args.runtime}`,- );- }- const effectivePackageLock = args.packageLock ?? runtimePackageSelection?.packageLock;+ : await (await runtimeHost(args.runtime)).resolvePackages();+ const discoveredPackageLock = args.file === undefined+ ? undefined+ : await nearestSourcePackageLock(dirname(resolve(args.file)));+ const effectivePackageLock = args.packageLock ?? discoveredPackageLock;const effectivePackageRoot = args.packageRoot ?? runtimePackageSelection?.packageRoot;const effectiveWorkspaceRoot = args.workspaceRoot- ?? runtimePackageSelection?.root- ?? (effectivePackageLock === undefined ? undefined : dirname(resolve(effectivePackageLock)));+ ?? selectedRuntimeProjectRoot+ ?? (effectivePackageLock === undefined ? dirname(resolve(args.file!)) : dirname(resolve(effectivePackageLock)));if (effectivePackageRoot !== undefined && effectivePackageLock === undefined) {throw new Error("--package-root locates the installed packages named by --package-lock; provide both options");}@@ -1950,7 +1995,7 @@ export async function runCli(if (args.runtime === undefined) {throw new Error("build requires a Runtime; run narratage runtime use <profile> or pass --runtime <profile>");}- const archive = lazyRuntimeArchive(args.runtime, distribution);+ const archive = lazyRuntimeArchive(await runtimeHost(args.runtime));let loadedRun;try {loadedRun = await loadRunFile({@@ -1982,37 +2027,36 @@ export async function runCli(catalog,attachments: result.compilation.attachments,} as const;- const workerProfileDigest = await distribution.runtimeProfileRevision(args.runtime);- let services: Awaited<ReturnType<typeof startDeclaredServices>> | undefined;- let worker = await runtimeProcessStatus(args.runtime, workerProfileDigest);- const preflight = await preflightPlan(args.runtime, distribution, result.state, loadedPackageSet);+ const controller = await (await runtimeHost(args.runtime)).controller({+ workspaceRoot: effectiveWorkspaceRoot,+ ...(effectivePackageLock === undefined ? {} : { packageLock: effectivePackageLock }),+ packageRoot: effectivePackageRoot ?? distribution.packageRoot ?? effectiveWorkspaceRoot,+ });+ let programs: Awaited<ReturnType<typeof startDeclaredPrograms>> | undefined;+ let worker = await controller.worker.status();+ const preflight = await preflightPlan(await runtimeHost(args.runtime), result.state, loadedPackageSet);// A managed program being down is repairable after Runtime validation;// every other deployment error fails before we construct execution or- // start anything. With --no-services, readiness errors remain fatal.- assertPreflight(preflight, args.noServices+ // start anything. With --no-programs, readiness errors remain fatal.+ assertPreflight(preflight, args.noPrograms? new Set()- : new Set(["EXTERNAL_SERVICE_DOWN", "EXTERNAL_SERVICE_MISMATCH"]));- services = args.noServices+ : new Set(["MANAGED_PROGRAM_DOWN", "MANAGED_PROGRAM_MISMATCH"]));+ programs = args.noPrograms? undefined- : await startDeclaredServices(- args.runtime,- distribution,+ : await startDeclaredPrograms(+ controller,demandedCapabilities(result.state),- reportServiceProgress,+ reportProgramProgress,);- runtime = await loadRuntime(args.runtime, distribution, loadedPackageSet);- worker = await ensureRuntimeProcess(- args.runtime,- distribution.runtimeWorkerLaunch(),- workerProfileDigest,- args.maxWaitMs ?? 10_000,- );+ runtime = await loadRuntime(await runtimeHost(args.runtime), loadedPackageSet);+ worker = await controller.worker.up({+ ...(args.maxWaitMs === undefined ? {} : { maxWaitMs: args.maxWaitMs }),+ });let built = await runtime.build(request);if (args.follow && runtime !== undefined) {built = await observeBuild(runtime, built, {...(args.maxWaitMs === undefined ? {} : { maxWaitMs: args.maxWaitMs }),- workerProfile: args.runtime,- workerProfileDigest,+ controller,...(args.json || args.jsonl ? {} : {onProgress: (progress) => {const operations = Object.entries(progress.operations)@@ -2048,8 +2092,8 @@ export async function runCli(core: built.state.id,status: built.status,worker,- ...(services === undefined ? {} : {- services: services.map((item) => ({ id: item.id, action: item.action })),+ ...(programs === undefined ? {} : {+ programs: programs.map((item) => ({ id: item.id, action: item.action })),}),goals: built.state.plan.goals.map((goal) => {const record = built.state.records.find((item) => item.id === goal.record);@@ -2109,7 +2153,7 @@ export async function runCli(try {runtime = args.runtime === undefined? undefined- : lazyRuntimeArchive(args.runtime, distribution);+ : lazyRuntimeArchive(await runtimeHost(args.runtime));const loaded = await loadRunFile({workspace,authorCompiler: compiler,@@ -2120,7 +2164,7 @@ export async function runCli(const result = loaded.compiler.planCompilation(loaded, loadedPackageSet?.lock.digest);const preflight = args.runtime === undefined? undefined- : await preflightPlan(args.runtime, distribution, result.state, loadedPackageSet);+ : await preflightPlan(await runtimeHost(args.runtime), result.state, loadedPackageSet);writeCliOutput(io, args, {kind: "plan",machine: {diff --git a/packages/cli/src/output.ts b/packages/cli/src/output.tsindex ed6d51cd..8524ccef 100644--- a/packages/cli/src/output.ts+++ b/packages/cli/src/output.ts@@ -37,7 +37,7 @@ export type CliDiagnostic = {export type DoctorOutput = {readonly format: "narratage.cli-doctor@1";readonly ok: boolean;- readonly root: string;+ readonly dataRoot: string;readonly diagnostics: readonly CliDiagnostic[];};@@ -84,7 +84,7 @@ export type RunCheckOutput = {export type PlanPreflight = {readonly ok: boolean;- readonly root: string;+ readonly dataRoot: string;readonly capabilities: readonly string[];readonly diagnostics: readonly CliDiagnostic[];};@@ -212,7 +212,7 @@ function renderDoctor(view: Extract<CliPresentation, { kind: "doctor" }>, io: Clconst lines = [colors.accent(colors.strong("Narratage Doctor")), ""];lines.push(...facts([["Profile", shortPath(view.profile)],- ["Root", shortPath(view.machine.root)],+ ["Data root", shortPath(view.machine.dataRoot)],], colors));lines.push("");if (view.machine.diagnostics.length === 0) {@@ -448,7 +448,7 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undeficolors.accent(colors.strong("narratage check")),colors.dim("Validate one self-described Author Source or Run Source without executing it."),"",- " narratage check <source> [--runtime <profile>] [--package-lock <lock>] [--root <workspace>] [--asset-root <directory>]",+ " narratage check <source> [--runtime <profile>] [--package-lock <lock>] [--workspace <workspace>] [--asset-root <directory>]",],doctor: [colors.accent(colors.strong("narratage doctor")),@@ -460,7 +460,7 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undeficolors.accent(colors.strong("narratage plan")),colors.dim("Freeze the demanded subgraph and expose explicit Run choices and every external Need."),"",- " narratage plan <run-source> [--runtime <profile>] [--package-lock <lock>] [--root <workspace>] [--asset-root <directory>]",+ " narratage plan <run-source> [--runtime <profile>] [--package-lock <lock>] [--workspace <workspace>] [--asset-root <directory>]","","With --runtime, plan also preflights only the demanded deployment slice.","Planning never starts external work.",@@ -469,10 +469,10 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undeficolors.accent(colors.strong("narratage build")),colors.dim("Submit one durable Build and ensure its selected Runtime Worker is available."),"",- " narratage build <run-source> [--runtime <profile>] [--asset-root <directory>] [--follow] [--no-services]",+ " narratage build <run-source> [--runtime <profile>] [--asset-root <directory>] [--follow] [--no-programs]",""," --follow observe the Build; the Worker still owns execution",- " --no-services do not start declared external programs",+ " --no-programs do not start declared external programs"," --max-wait-ms <ms> bound startup or follow waiting",],runtime: [@@ -481,18 +481,18 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi""," narratage runtime use <profile> select the Profile for this project"," narratage runtime unset remove only the local selection",- " narratage runtime up [<profile>] validate the Runtime Closure, start services and Worker",- " narratage runtime status [<profile>] inspect Worker, queue capacity and declared services",+ " narratage runtime up [<profile>] validate the Runtime Closure, start programs and Worker",+ " narratage runtime status [<profile>] inspect Worker, queue capacity and declared programs"," narratage runtime logs [<profile>] read Worker logs"," narratage runtime down [<profile>] stop the Worker; external programs keep running",],- services: [- colors.accent(colors.strong("narratage services")),+ programs: [+ colors.accent(colors.strong("narratage programs")),colors.dim("Operate only the external programs declared by Endpoints in one Runtime Profile."),"",- " narratage services up [<profile>] [--max-wait-ms <ms>]",- " narratage services status [<profile>]",- " narratage services down [<profile>]",+ " narratage programs up [<profile>] [--max-wait-ms <ms>]",+ " narratage programs status [<profile>]",+ " narratage programs down [<profile>]",],queue: [colors.accent(colors.strong("narratage queue")),@@ -501,6 +501,12 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi" narratage queue [--runtime <profile>] [--watch]"," narratage queue [--runtime <profile>] --watch --jsonl",],+ paths: [+ colors.accent(colors.strong("narratage paths")),+ colors.dim("Show project, Runtime and host state locations without creating them."),+ "",+ " narratage paths [--runtime <profile>]",+ ],builds: [colors.accent(colors.strong("narratage builds")),colors.dim("List Builds archived by one Runtime Profile."),@@ -556,7 +562,7 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undeficolors.accent(colors.strong("narratage packages")),colors.dim("Derive both package locks from one Run Source and Runtime Profile."),"",- " narratage packages sync <run-source> [--runtime <profile>] [--root <workspace>]",+ " narratage packages sync <run-source> [--runtime <profile>] [--workspace <workspace>]","","The sources select author packages; the Profile selects Runtime packages.","This never installs packages or runs Providers.",@@ -604,8 +610,9 @@ export function writeCliHelp(io: CliIo, topic?: string): void {" doctor <profile> validate deployment without executing"," runtime use|unset select this project's Runtime Profile"," runtime up|status|logs|down manage the durable Worker",- " services up|status|down manage declared external programs only",+ " programs up|status|down manage declared external programs only"," queue [--watch] inspect durable dispatch and shared capacity",+ " paths show every effective state location"," auth status|login|logout manage Endpoint-declared credential references"," gc <profile> report unreachable Artifacts; --apply deletes","",diff --git a/packages/cli/src/paths.ts b/packages/cli/src/paths.tsnew file mode 100644index 00000000..d01008dd--- /dev/null+++ b/packages/cli/src/paths.ts@@ -0,0 +1,29 @@+import { homedir } from "node:os";+import { join, resolve } from "node:path";++export function narratageHostStateRoot(options: {+ readonly env?: NodeJS.ProcessEnv;+ readonly platform?: NodeJS.Platform;+ readonly home?: string;+} = {}): string {+ const env = options.env ?? process.env;+ const override = env.NARRATAGE_STATE_HOME;+ if (override !== undefined && override.trim().length > 0) return resolve(override);+ const platform = options.platform ?? process.platform;+ const home = options.home ?? homedir();+ if (platform === "darwin") return join(home, "Library", "Application Support", "Narratage");+ if (platform === "win32") {+ const local = env.LOCALAPPDATA;+ return join(local === undefined || local.trim().length === 0+ ? join(home, "AppData", "Local")+ : local, "Narratage");+ }+ const state = env.XDG_STATE_HOME;+ return join(state === undefined || state.trim().length === 0+ ? join(home, ".local", "state")+ : state, "narratage");+}++export function narratageProjectStateRoot(projectRoot: string): string {+ return resolve(projectRoot, ".narratage");+}diff --git a/packages/cli/src/runtime-port.ts b/packages/cli/src/runtime-port.tsindex 69aed02c..661f7003 100644--- a/packages/cli/src/runtime-port.ts+++ b/packages/cli/src/runtime-port.ts@@ -1,123 +1,16 @@-import type { ArtifactAttachment } from "@narratage/workspace";-import type { BuildState, Digest } from "@narratage/protocol";-import type {- BuildCatalogDescriptor,- BuildCatalogEntry,- BuildDispatchSnapshot,- BuildSnapshot,- CapacityReservation,- CredentialRef,- OperationSnapshot,- RuntimeWorkerRunOptions,-} from "@narratage/runtime";--export type CliBuildSubmission = {- readonly id: string;- readonly state: BuildState;- readonly status: "queued" | "running" | "waiting" | "blocked" | "settling" | "complete" | "failed" | "cancelled";- readonly dispatch: BuildDispatchSnapshot;-};--export type CliRuntimeStatus = {- readonly build: BuildSnapshot | undefined;- readonly catalog: BuildCatalogEntry | undefined;- readonly operations: readonly OperationSnapshot[];- readonly dispatch: BuildDispatchSnapshot | undefined;-};--export type CliCredentialStatus = {- readonly endpoint: string;- readonly slot: string;- readonly label: string;- readonly kind: "secret" | "json";- readonly ref: CredentialRef;- readonly configured: boolean;- readonly writable: boolean;-};--export type CliArtifactGarbageCollection = {- readonly reachable: readonly Digest[];- readonly unreachable: readonly Digest[];- readonly deleted: readonly Digest[];-};--export type CliRuntimeArchiveControl = {- status(build: string): Promise<CliRuntimeStatus>;- activity(build: string): Promise<{- readonly operations: readonly OperationSnapshot[];- readonly dispatch: BuildDispatchSnapshot | undefined;- }>;- queue(): Promise<{- readonly dispatches: readonly BuildDispatchSnapshot[];- readonly capacity: readonly CapacityReservation[];- readonly operations: readonly OperationSnapshot[];- }>;- builds(): Promise<readonly BuildCatalogEntry[]>;- cancel(build: string, reason?: string): Promise<BuildDispatchSnapshot | undefined>;- close(): void | Promise<void>;-};--export type CliRuntimeArtifactAccess = {- readArtifact(digest: Digest): Promise<Uint8Array | undefined>;- openArtifact(digest: Digest): Promise<AsyncIterable<Uint8Array> | undefined>;- close(): void | Promise<void>;-};--export type CliRuntimeMaintenance = CliRuntimeArchiveControl & CliRuntimeArtifactAccess & {- garbageCollectArtifacts(options?: { readonly apply?: boolean }): Promise<CliArtifactGarbageCollection>;-};--export type CliCredentialControl = {- credentials(endpoint?: string): Promise<readonly CliCredentialStatus[]>;- putCredential(endpoint: string, slot: string, secret: string): Promise<CliCredentialStatus>;- deleteCredential(endpoint: string, slot: string): Promise<{- readonly deleted: boolean;- readonly credential: CliCredentialStatus;- }>;- close(): void | Promise<void>;-};--export type CliRuntime = CliRuntimeMaintenance & CliCredentialControl & {- build(request: {- readonly id: string;- readonly state: BuildState;- readonly catalog?: BuildCatalogDescriptor;- readonly attachments?: readonly ArtifactAttachment[];- }, options?: {- readonly follow?: boolean;- readonly pollIntervalMs?: number;- readonly maxWaitMs?: number;- readonly signal?: AbortSignal;- }): Promise<CliBuildSubmission>;- work(options: RuntimeWorkerRunOptions): Promise<void>;-};--export type CliRuntimeDoctorDiagnostic = {- readonly severity: "error" | "warning" | "info";- readonly code: string;- readonly message: string;- readonly subject?: string;-};--export type CliRuntimeDoctorResult = {- readonly root: string;- readonly diagnostics: readonly CliRuntimeDoctorDiagnostic[];-};--export type CliExternalServiceProgress = {- readonly id: string;- readonly phase: "checking" | "preparing" | "starting" | "waiting" | "ready";-};--export type CliExternalServiceReport = {- readonly id: string;- readonly instances: readonly string[];- readonly action?: "already-running" | "prepared" | "started" | "stopped" | "not-ours" | "nothing-to-stop" | "unchanged";- readonly state:- | { readonly state: "ready" }- | { readonly state: "down"; readonly detail: string }- | { readonly state: "mismatch"; readonly detail: string };- readonly detail?: string;- readonly logPath?: string;- readonly pid?: number;-};+export type {+ ManagedProgramProgress as CliManagedProgramProgress,+ ManagedProgramReport as CliManagedProgramReport,+ RuntimeController as CliRuntimeController,+ RuntimeHostArchive as CliRuntimeArchiveControl,+ RuntimeHostArtifactAccess as CliRuntimeArtifactAccess,+ RuntimeHostArtifactGarbageCollection as CliArtifactGarbageCollection,+ RuntimeHostBuildSubmission as CliBuildSubmission,+ RuntimeHostCredentialControl as CliCredentialControl,+ RuntimeHostCredentialStatus as CliCredentialStatus,+ RuntimeHostDoctorResult as CliRuntimeDoctorResult,+ RuntimeHostExecution as CliRuntime,+ RuntimeHostMaintenance as CliRuntimeMaintenance,+ RuntimeHostStatus as CliRuntimeStatus,+ RuntimeWorkerState as CliRuntimeWorkerState,+} from "@narratage/runtime-adapter-node";diff --git a/packages/cli/src/runtime-selection.ts b/packages/cli/src/runtime-selection.tsindex f8210b76..0471af66 100644--- a/packages/cli/src/runtime-selection.ts+++ b/packages/cli/src/runtime-selection.ts@@ -1,7 +1,7 @@import { mkdir, readFile, realpath, unlink, writeFile } from "node:fs/promises";import { dirname, relative, resolve } from "node:path";-const stateDirectoryName = ".svml";+const stateDirectoryName = ".narratage";const selectionFileName = "runtime";export type RuntimeProfileSelection = {@@ -84,7 +84,7 @@ export async function findRuntimeProfile(start: string): Promise<RuntimeProfileS}}-/** Remove only the local pointer. Runtime state, locks, services and Builds are untouched. */+/** Remove only the local pointer. Runtime state, locks, Programs and Builds are untouched. */export async function clearRuntimeProfile(start: string): Promise<RuntimeProfileSelection | undefined> {const selected = await readSelectionFile(start);if (selected === undefined) return undefined;diff --git a/packages/cli/test/build-services.test.ts b/packages/cli/test/build-programs.test.tssimilarity index 63%rename from packages/cli/test/build-services.test.tsrename to packages/cli/test/build-programs.test.tsindex 3033e6bb..f7bacf79 100644--- a/packages/cli/test/build-services.test.ts+++ b/packages/cli/test/build-programs.test.ts@@ -8,7 +8,8 @@ import { digestOf } from "@narratage/protocol";import { createRunFrontendHostFacet } from "@narratage/run";import { runCli } from "../src/main.js";-import type { CliDistribution, ExternalServiceResult } from "../src/distribution.js";+import type { CliDistribution } from "../src/distribution.js";+import type { CliManagedProgramReport } from "../src/runtime-port.js";const io = { write: () => {} };@@ -19,7 +20,7 @@ const io = { write: () => {} };*/function distribution(calls: string[],- services: ExternalServiceResult["services"],+ programs: readonly CliManagedProgramReport[],): CliDistribution {return {name: "test",@@ -41,25 +42,43 @@ function distribution(}),supportsFrontend: () => false,}),- externalServices: {- up: async (path: string) => {- calls.push(`up ${path}`);- return { root: "/tmp", services };- },- down: async () => ({ root: "/tmp", services: [] }),- report: async () => ({ root: "/tmp", services: [] }),- },+ openRuntimeHost: async (path: string) => ({+ profile: path,+ resolvePackages: async () => ({}),+ controller: async () => ({+ profile: path,+ dataRoot: "/tmp",+ revision: async () => "test-revision",+ worker: {+ up: async () => ({ state: "stopped", profile: path, logPath: "/tmp/worker.log" }),+ status: async () => ({ state: "stopped", profile: path, logPath: "/tmp/worker.log" }),+ logs: async () => ({ path: "/tmp/worker.log", text: "" }),+ down: async () => ({ state: "stopped", profile: path, logPath: "/tmp/worker.log" }),+ },+ programs: {+ up: async () => {+ calls.push(`up ${path}`);+ return { dataRoot: "/tmp", programs };+ },+ down: async () => ({ dataRoot: "/tmp", programs: [] }),+ report: async () => ({ dataRoot: "/tmp", programs: [] }),+ },+ }),+ doctor: async () => ({ dataRoot: "/tmp", diagnostics: [] }),+ createRuntime: async () => { throw new Error("createRuntimeFromConfig is unavailable"); },+ openArchive: async () => ({ status: async () => ({}) }),+ }),} as unknown as CliDistribution;}async function runSource(): Promise<string> {- const root = await mkdtemp(join(tmpdir(), "svml-build-services-"));+ const root = await mkdtemp(join(tmpdir(), "svml-build-programs-"));const path = join(root, "build.svrun");await writeFile(path, '<?svml using="@narratage/run-markup@1"?>\n<svrun/>\n', "utf8");return path;}-test("a Build that cannot construct its Runtime starts no declared external service", async () => {+test("a Build that cannot construct its Runtime starts no declared external program", async () => {const calls: string[] = [];const source = await runSource();await assert.rejects(@@ -79,15 +98,15 @@ test("a Build that cannot construct its Runtime starts no declared external servassert.deepEqual(calls, []);});-test("--no-services leaves the declared programs alone", async () => {+test("--no-programs leaves the declared programs alone", async () => {const calls: string[] = [];const source = await runSource();// Reaching the Runtime is the boundary just past the gate: the stub has no- // createRuntimeFromConfig, so arriving there proves the down service was+ // createRuntimeFromConfig, so arriving there proves the down program was// never consulted rather than merely tolerated.await assert.rejects(async () => await runCli(- ["build", source, "--runtime", "/p/svml.runtime.json", "--no-services"],+ ["build", source, "--runtime", "/p/svml.runtime.json", "--no-programs"],io,distribution(calls, [{id: "whisperx",@@ -100,13 +119,13 @@ test("--no-services leaves the declared programs alone", async () => {assert.deepEqual(calls, []);});-test("--no-services belongs to build, the only command that starts a program", async () => {+test("--no-programs belongs to build, the only command that starts a program", async () => {await assert.rejects(async () => await runCli(- ["plan", "/p/build.svrun", "--no-services"],+ ["plan", "/p/build.svrun", "--no-programs"],io,distribution([], []),),- /--no-services is only valid for build/u,+ /--no-programs is only valid for build/u,);});diff --git a/packages/cli/test/control-commands.test.ts b/packages/cli/test/control-commands.test.tsindex 9ee05824..fb8d6dcf 100644--- a/packages/cli/test/control-commands.test.ts+++ b/packages/cli/test/control-commands.test.ts@@ -17,15 +17,20 @@ test("queue opens durable control without constructing execution Providers", asy},} as unknown as CliRuntimeArchiveControl;const distribution = {- runtimeProfileRevision: async () => "test-revision",- createRuntimeArchiveFromConfig: async () => {- calls.push("control.create");- return control;- },- createRuntimeFromConfig: async () => {- calls.push("execution.create");- throw new Error("execution Providers must not be constructed");- },+ openRuntimeHost: async (path: string) => ({+ profile: path,+ openArchive: async () => {+ calls.push("control.create");+ return control;+ },+ controller: async () => ({+ worker: { status: async () => ({ state: "stopped", profile: path, logPath: "/tmp/worker.log" }) },+ }),+ createRuntime: async () => {+ calls.push("execution.create");+ throw new Error("execution Providers must not be constructed");+ },+ }),} as unknown as CliDistribution;let output = "";@@ -52,16 +57,16 @@ test("queue opens durable control without constructing execution Providers", asytest("command options fail closed instead of being silently ignored", async () => {const distribution = {- createRuntimeArchiveFromConfig: async (path: string) => {+ openRuntimeHost: async (path: string) => {throw new Error(`profile delegated: ${path}`);},} as unknown as CliDistribution;const io = { write() {} };await assert.rejects(async () => await runCli([- "status", "build-1", "--runtime", "/tmp/runtime.json", "--root", "/tmp",+ "status", "build-1", "--runtime", "/tmp/runtime.json", "--workspace", "/tmp",], io, distribution),- /--root does not apply to status/u,+ /--workspace does not apply to status/u,);await assert.rejects(async () => await runCli([@@ -77,9 +82,9 @@ test("command options fail closed instead of being silently ignored", async () =);await assert.rejects(async () => await runCli([- "doctor", "/tmp/runtime.json", "--root", "/tmp",+ "doctor", "/tmp/runtime.json", "--workspace", "/tmp",], io, distribution),- /doctor already uses the Runtime Profile directory and its declared root; remove --root/u,+ /doctor does not compile a Source Workspace; remove --workspace/u,);await assert.rejects(async () => await runCli([@@ -107,14 +112,17 @@ test("auth opens only one Endpoint credential control, never the execution Runtiasync close() { calls.push("credentials.close"); },} as unknown as CliCredentialControl;const distribution = {- createRuntimeCredentialsFromConfig: async (_path: string, endpoint: string) => {- calls.push(`credentials.create:${endpoint}`);- return credentials;- },- createRuntimeFromConfig: async () => {- calls.push("execution.create");- throw new Error("auth must not construct execution");- },+ openRuntimeHost: async (path: string) => ({+ profile: path,+ openCredentials: async (endpoint: string) => {+ calls.push(`credentials.create:${endpoint}`);+ return credentials;+ },+ createRuntime: async () => {+ calls.push("execution.create");+ throw new Error("auth must not construct execution");+ },+ }),} as unknown as CliDistribution;let output = "";@@ -148,7 +156,10 @@ test("auth login rejects a read-only CredentialStore before asking for a secret"async close() { closed = true; },} as unknown as CliCredentialControl;const distribution = {- createRuntimeCredentialsFromConfig: async () => credentials,+ openRuntimeHost: async (path: string) => ({+ profile: path,+ openCredentials: async () => credentials,+ }),} as unknown as CliDistribution;await assert.rejects(@@ -180,7 +191,10 @@ test("cancelling a completed Build reports that no cancellation was requested",async close() {},} as unknown as CliRuntimeArchiveControl;const distribution = {- createRuntimeArchiveFromConfig: async () => control,+ openRuntimeHost: async (path: string) => ({+ profile: path,+ openArchive: async () => control,+ }),} as unknown as CliDistribution;let output = "";diff --git a/packages/cli/test/output.test.ts b/packages/cli/test/output.test.tsindex 0c64a9d4..44ba7d62 100644--- a/packages/cli/test/output.test.ts+++ b/packages/cli/test/output.test.ts@@ -145,7 +145,7 @@ test("JSON mode is exact machine data with no terminal decoration", () => {const machine = {format: "narratage.cli-doctor@1" as const,ok: false,- root: "/project",+ dataRoot: "/project",diagnostics: [{ severity: "error" as const, code: "MISSING", message: "not found" }],};const output = capture({ json: true, color: "always", verbose: true }, {@@ -237,7 +237,7 @@ test("plan runtime preflight presents only demanded capabilities", () => {};const preflight: PlanPreflight = {ok: false,- root: "/project",+ dataRoot: "/project",capabilities: ["@example/image@1#generate"],diagnostics: [{severity: "error",diff --git a/packages/cli/test/programs-command.test.ts b/packages/cli/test/programs-command.test.tsnew file mode 100644index 00000000..8b5a6b93--- /dev/null+++ b/packages/cli/test/programs-command.test.ts@@ -0,0 +1,104 @@+import assert from "node:assert/strict";+import test from "node:test";++import { runCli } from "../src/main.js";+import type { CliDistribution } from "../src/distribution.js";+import type { CliManagedProgramReport, CliRuntimeController } from "../src/runtime-port.js";++const io = { write: () => {} };++function controller(+ path: string,+ calls: string[],+ reports: readonly CliManagedProgramReport[] = [],+): CliRuntimeController {+ const worker = { state: "stopped" as const, profile: path, logPath: "/tmp/worker.log" };+ return {+ profile: path,+ dataRoot: "/tmp",+ revision: async () => "test-revision",+ worker: {+ up: async () => worker,+ status: async () => worker,+ logs: async () => ({ path: worker.logPath, text: "" }),+ down: async () => worker,+ },+ programs: {+ up: async (options) => {+ calls.push(`up ${path} ${JSON.stringify(options)}`);+ return { dataRoot: "/tmp", programs: reports };+ },+ down: async () => { calls.push(`down ${path}`); return { dataRoot: "/tmp", programs: reports }; },+ report: async () => { calls.push(`report ${path}`); return { dataRoot: "/tmp", programs: reports }; },+ },+ };+}++function distribution(calls: string[], reports: readonly CliManagedProgramReport[] = []): CliDistribution {+ return {+ bootstrapPackages: [],+ openRuntimeHost: async (path: string) => ({+ profile: path,+ controller: async () => controller(path, calls, reports),+ }),+ } as unknown as CliDistribution;+}++test("programs dispatches lifecycle through the selected Runtime Controller", async () => {+ const calls: string[] = [];+ await runCli(["programs", "up", "/p/svml.runtime.json", "--max-wait-ms", "1000"], io, distribution(calls));+ await runCli(["programs", "down", "/p/svml.runtime.json"], io, distribution(calls));+ await runCli(["programs", "status", "/p/svml.runtime.json"], io, distribution(calls));+ assert.deepEqual(calls, [+ 'up /p/svml.runtime.json {"maxWaitMs":1000}',+ "down /p/svml.runtime.json",+ "report /p/svml.runtime.json",+ ]);+});++test("programs accepts only up, down and status", async () => {+ await assert.rejects(+ runCli(["programs", "restart", "/p/svml.runtime.json"], io, distribution([])),+ /programs takes up, down or status/u,+ );+});++test("waiting belongs only to programs up", async () => {+ await assert.rejects(+ runCli(["programs", "status", "/p/svml.runtime.json", "--max-wait-ms", "1000"], io, distribution([])),+ /--max-wait-ms applies to programs up/u,+ );+});++test("program status may report down without failing the observation", async () => {+ let output = "";+ let exitCode: number | undefined;+ await runCli(["programs", "status", "/project/svml.runtime.json"], {+ write(text) { output += text; },+ setExitCode(code) { exitCode = code; },+ }, distribution([], [{+ id: "speech-evidence.local",+ instances: ["speech.primary"],+ state: { state: "down", detail: "not running" },+ }]));+ assert.equal(exitCode, undefined);+ assert.match(output, /speech-evidence\.local: down/u);+});++test("runtime up validates the Runtime before it starts Programs", async () => {+ const calls: string[] = [];+ const base = distribution(calls);+ const selected = {+ ...base,+ openRuntimeHost: async (path: string) => ({+ profile: path,+ controller: async () => controller(path, calls),+ createRuntime: async () => { throw new Error("Runtime Closure conflict"); },+ }),+ } as unknown as CliDistribution;+ await assert.rejects(+ runCli(["runtime", "up", "/p/svml.runtime.json"], io, selected),+ /Runtime Closure conflict/u,+ );+ assert.deepEqual(calls, []);+});diff --git a/packages/cli/test/runtime-build-process.test.ts b/packages/cli/test/runtime-build-process.test.tsindex 834462d7..eb9208dd 100644--- a/packages/cli/test/runtime-build-process.test.ts+++ b/packages/cli/test/runtime-build-process.test.ts@@ -8,15 +8,17 @@ import test from "node:test";import {createNodePackageLock,+ readNodePackageLock,writeNodePackageLock,} from "@narratage/package-loader-node";+import { digestOf } from "@narratage/protocol";import { runtimeConfigRevision } from "@narratage/local/config";import {ensureRuntimeProcess,runtimeProcessStatus,stopRuntimeProcess,-} from "../src/runtime-process.js";+} from "@narratage/local/worker-process";const execute = promisify(execFile);const cliEntry = join(process.cwd(), "packages", "video-cli", "src", "cli.ts");@@ -112,33 +114,42 @@ test("CLI exits after durable submission and a restarted detached Worker complet</svrun>`, "utf8");await writeFile(profile, JSON.stringify({- format: "svml.runtime-config@1",- root: ".",- packageRoot: process.cwd(),- packageLock: "./svml.packages.lock",+ format: "narratage.runtime-profile@1",runtimePackageLock: "./svml.runtime-packages.lock",- runtimeServices: [- { use: "@narratage/local", instance: "execution" },- { use: "@narratage/store-sqlite", instance: "state", config: { path: ".svml/runtime.sqlite" } },- { use: "@narratage/artifact-store-fs", instance: "artifacts", config: { path: ".svml/artifacts" } },- { use: "@narratage/credential-store-env", instance: "credentials.env", config: {} },- ],- services: {- scheduler: "execution.scheduler",- worker: "execution.worker",- stores: {- build: "state.builds",- operations: "state.operations",- dispatch: "state.dispatch",- artifacts: "artifacts",- credentials: ["credentials.env"],+ runtime: {+ use: "@narratage/local",+ config: {+ dataRoot: ".narratage/runtime",+ components: {+ execution: { use: "@narratage/local" },+ state: { use: "@narratage/store-sqlite", config: { path: "runtime.sqlite" } },+ artifacts: { use: "@narratage/artifact-store-fs", config: { path: "artifacts" } },+ "credentials.env": { use: "@narratage/credential-store-env", config: {} },+ },+ bindings: {+ scheduler: "execution.scheduler",+ worker: "execution.worker",+ stores: {+ build: "state.builds",+ operations: "state.operations",+ dispatch: "state.dispatch",+ artifacts: "artifacts",+ credentials: ["credentials.env"],+ },+ },+ endpoints: {},+ limits: { maxOperations: 2 },},},- endpoints: [],- scheduling: { maxConcurrency: 2 },}, null, 2), "utf8");- const parked = await ensureRuntimeProcess(profile, {+ const dataRoot = join(project, ".narratage", "runtime");+ const workerRevision = digestOf({+ format: "narratage.runtime-worker-revision@1",+ profile: await runtimeConfigRevision(profile),+ source: (await readNodePackageLock(authorLockPath)).digest,+ });+ const parked = await ensureRuntimeProcess(profile, dataRoot, {command: process.execPath,args: ["-e", `const fs = require("node:fs");@@ -150,22 +161,22 @@ test("CLI exits after durable submission and a restarted detached Worker completprocess.on("SIGTERM", () => process.exit(0));setInterval(() => {}, 1000);`],- }, await runtimeConfigRevision(profile), 5_000);+ }, workerRevision, 5_000);const submitted = await cli(project, ["build", run,"--runtime", profile,- "--root", project,- "--no-services",+ "--workspace", project,+ "--no-programs",]);const build = String(submitted.build);assert.match(build, /^bld_[0-9a-f-]{36}$/u);assert.equal(submitted.status, "queued", "the foreground CLI reports durable admission, not execution ownership");assert.equal((submitted.dispatch as { readonly phase?: string }).phase, "queued");- const originalProcess = await runtimeProcessStatus(profile, await runtimeConfigRevision(profile));+ const originalProcess = await runtimeProcessStatus(profile, dataRoot, workerRevision);assert.equal(originalProcess.state, "running", "the detached Runtime process outlives the submitting CLI process");assert.equal(originalProcess.pid, parked.pid, "build reuses one profile-scoped Runtime process");- await stopRuntimeProcess(profile, 10_000);+ await stopRuntimeProcess(profile, dataRoot, 10_000);const interrupted = await cli(project, ["status", build, "--runtime", profile]);assert.notEqual((interrupted.dispatch as { readonly phase?: string }).phase, "terminal","the long Build is durably incomplete when its first Worker is killed");@@ -196,19 +207,19 @@ test("CLI exits after durable submission and a restarted detached Worker completassert.equal((materialized.materialized as { readonly kind?: string }).kind, "json");assert.notEqual(JSON.parse(await readFile(exported, "utf8")), undefined);- await stopRuntimeProcess(profile, 10_000);+ await stopRuntimeProcess(profile, dataRoot, 10_000);const repeated = await cli(project, ["build", run,"--runtime", profile,- "--root", project,- "--no-services",+ "--workspace", project,+ "--no-programs","--follow",]);assert.equal(repeated.status, "complete");assert.notEqual(repeated.build, build,"repeating the same Run Source creates a fresh Build instead of reclaiming source-derived state");} finally {- await stopRuntimeProcess(profile, 10_000).catch(() => undefined);+ await stopRuntimeProcess(profile, join(project, ".narratage", "runtime"), 10_000).catch(() => undefined);await rm(project, { recursive: true, force: true });}});diff --git a/packages/cli/test/runtime-selection.test.ts b/packages/cli/test/runtime-selection.test.tsindex d105c269..151c5008 100644--- a/packages/cli/test/runtime-selection.test.ts+++ b/packages/cli/test/runtime-selection.test.ts@@ -20,7 +20,7 @@ test("project Runtime selection is a relative local pointer discovered from nestconst selected = await selectRuntimeProfile(root, profile);assert.equal(selected.profile, await realpath(profile));- assert.equal((await readFile(join(root, ".svml", "runtime"), "utf8")).trim(), join("runtime", "local.json"));+ assert.equal((await readFile(join(root, ".narratage", "runtime"), "utf8")).trim(), join("runtime", "local.json"));const found = await findRuntimeProfile(nested);assert.equal(found?.profile, selected.profile);@@ -44,19 +44,20 @@ test("runtime use lets later CLI commands reuse the selected Profile", async ()async close() {},} as unknown as CliRuntimeArchiveControl;const distribution = {- resolveCompilationPackages: async (path: string) => {- calls.push(`select:${resolve(path)}`);- return {- root,- packageLock: join(root, "svml.packages.lock"),- runtimePackageLock: join(root, "svml.runtime-packages.lock"),- };- },- createRuntimeArchiveFromConfig: async (path: string) => {- calls.push(`queue:${resolve(path)}`);- return control;- },- runtimeProfileRevision: async () => "runtime-selection-test",+ openRuntimeHost: async (path: string) => ({+ profile: path,+ resolvePackages: async () => {+ calls.push(`select:${resolve(path)}`);+ return { runtimePackageLock: join(root, "svml.runtime-packages.lock") };+ },+ openArchive: async () => {+ calls.push(`queue:${resolve(path)}`);+ return control;+ },+ controller: async () => ({+ worker: { status: async () => ({ state: "stopped", profile: path, logPath: "/tmp/worker.log" }) },+ }),+ }),} as unknown as CliDistribution;process.chdir(root);diff --git a/packages/cli/test/services-command.test.ts b/packages/cli/test/services-command.test.tsdeleted file mode 100644index 47af2549..00000000--- a/packages/cli/test/services-command.test.ts+++ /dev/null@@ -1,137 +0,0 @@-import assert from "node:assert/strict";-import { mkdtemp, rm } from "node:fs/promises";-import { tmpdir } from "node:os";-import { join } from "node:path";-import test from "node:test";--import { runCli } from "../src/main.js";-import type { CliDistribution, ExternalServiceResult } from "../src/distribution.js";--const empty: ExternalServiceResult = { root: "/tmp", services: [] };--function distribution(calls: string[]): CliDistribution {- return {- name: "test",- bootstrapPackages: [],- runtimeProfileRevision: async () => "test-revision",- externalServices: {- up: async (path: string, options: { maxWaitMs?: number }) => {- calls.push(`up ${path} ${JSON.stringify(options)}`);- return empty;- },- down: async (path: string) => { calls.push(`down ${path}`); return empty; },- report: async (path: string) => { calls.push(`report ${path}`); return empty; },- },- } as unknown as CliDistribution;-}--const io = { write: () => {} };--test("services dispatches its second word, and passes the wait only to up", async () => {- const calls: string[] = [];- await runCli(["services", "up", "/p/svml.runtime.json", "--max-wait-ms", "1000"], io, distribution(calls));- await runCli(["services", "down", "/p/svml.runtime.json"], io, distribution(calls));- await runCli(["services", "status", "/p/svml.runtime.json"], io, distribution(calls));- assert.deepEqual(calls, [- 'up /p/svml.runtime.json {"maxWaitMs":1000}',- "down /p/svml.runtime.json",- "report /p/svml.runtime.json",- ]);-});--test("services names its three words rather than guessing one", async () => {- await assert.rejects(- async () => await runCli(["services", "restart", "/p/svml.runtime.json"], io, distribution([])),- /services takes up, down or status/u,- );-});--test("waiting is a property of bringing up, not of looking or stopping", async () => {- await assert.rejects(- async () => await runCli(["services", "status", "/p/svml.runtime.json", "--max-wait-ms", "1000"], io, distribution([])),- /--max-wait-ms applies to services up/u,- );-});--test("services reads deployment selection from the Profile, never from flags", async () => {- await assert.rejects(- async () => await runCli(- ["services", "up", "/p/svml.runtime.json", "--runtime", "other.json"],- io,- distribution([]),- ),- /services reads all deployment selection from the Runtime Profile itself/u,- );-});--test("runtime up validates its Revision before starting any external program", async () => {- const calls: string[] = [];- const selected = distribution(calls);- const failing = {- ...selected,- createRuntimeFromConfig: async () => {- calls.push("runtime.validate");- throw new Error("Runtime Closure conflict");- },- } as CliDistribution;- await assert.rejects(- async () => await runCli(["runtime", "up", "/p/svml.runtime.json"], io, failing),- /Runtime Closure conflict/u,- );- assert.deepEqual(calls, ["runtime.validate"]);-});--test("services status reports readiness without turning an observation into a failed command", async () => {- let output = "";- let exitCode: number | undefined;- const selected = distribution([]);- selected.externalServices.report = async () => ({- root: "/project",- services: [{- id: "speech-evidence.local",- instances: ["speech.primary"],- state: { state: "down", detail: "not running" },- }],- });- await runCli(["services", "status", "/project/svml.runtime.json"], {- write(text) { output += text; },- setExitCode(code) { exitCode = code; },- }, selected);- assert.equal(exitCode, undefined);- assert.match(output, /speech-evidence\.local: down — not running/u);- assert.doesNotMatch(output, /Command failed/u);-});--test("an idle stopped Runtime is status data, not a command failure", async () => {- let output = "";- let exitCode: number | undefined;- const selected = {- ...distribution([]),- createRuntimeArchiveFromConfig: async () => ({- async queue() { return { dispatches: [], capacity: [], operations: [] }; },- async close() {},- }),- externalServices: {- ...distribution([]).externalServices,- report: async () => ({ root: "/project", services: [] }),- },- } as unknown as CliDistribution;- await runCli(["runtime", "status", "/project/svml.runtime.json"], {- write(text) { output += text; },- setExitCode(code) { exitCode = code; },- }, selected);- assert.equal(exitCode, undefined);- assert.match(output, /Runtime status/u);- assert.match(output, /Worker\s+stopped/u);-});--test("runtime down stops only its Worker and never an external program shared by another Profile", async () => {- const root = await mkdtemp(join(tmpdir(), "narratage-runtime-down-"));- const calls: string[] = [];- try {- await runCli(["runtime", "down", join(root, "svml.runtime.json")], io, distribution(calls));- assert.deepEqual(calls, []);- } finally {- await rm(root, { recursive: true, force: true });- }-});diff --git a/packages/component-kit/README.md b/packages/component-kit/README.mdindex 1aa46e55..e6b677a7 100644--- a/packages/component-kit/README.md+++ b/packages/component-kit/README.md@@ -6,7 +6,7 @@ reference plus implementation digest and handler. Package locks and Hosts can inthe identities without running an opaque `install()` callback. Producer handlers receive only theCore command, Producer identity and immutable typed inputs.-They receive no ArtifactStore, credentials, network client, queue or Runtime service. Work that+They receive no ArtifactStore, credentials, network client, queue or Runtime Component. Work thatneeds those authorities must emit an explicit Need and be implemented by a separately selectedEndpoint package. `@narratage/driver-node` implements the structural registrar but is not part of thisSDK.diff --git a/packages/component-kit/src/index.ts b/packages/component-kit/src/index.tsindex ce81a8d0..e7fba2f0 100644--- a/packages/component-kit/src/index.ts+++ b/packages/component-kit/src/index.ts@@ -88,7 +88,7 @@ export function registerTypeValidatorFacets(}}-/** Trusted deterministic implementation package; it selects no Provider or Runtime service. */+/** Trusted deterministic implementation package; it selects no Provider or Runtime Component. */export type ComponentPackage = {readonly producers?: readonly ProducerFacet[];readonly validators?: readonly TypeValidatorFacet[];diff --git a/packages/credential-store-env/README.md b/packages/credential-store-env/README.mdindex 4ad99b12..c7915f06 100644--- a/packages/credential-store-env/README.md+++ b/packages/credential-store-env/README.md@@ -10,7 +10,7 @@ The store resolves only the requested key at Endpoint invocation time. It neverserializes the environment. Secret values are handed only to that Endpoint call and do not enterBuildState, Runtime Closure, Operation checkpoints, logs or SQLite through framework code.-`createEnvironmentCredentialStorePackage()` exposes it through the same generic Runtime service+`createEnvironmentCredentialStorePackage()` exposes it through the same generic Runtime Componentpackage ABI as every other CredentialStore. A Runtime Profile must activate and select itexplicitly; `@narratage/local` supplies no credential default. Several selected Stores may coexist,and this one declines every reference whose `store` is not `env`.diff --git a/packages/credential-store-env/src/activation.ts b/packages/credential-store-env/src/activation.tsindex 49570df1..6085e099 100644--- a/packages/credential-store-env/src/activation.ts+++ b/packages/credential-store-env/src/activation.ts@@ -1,12 +1,12 @@import {- createRuntimeServiceAdapterFacet,+ createRuntimeComponentAdapterFacet,runtimeConfigExact,runtimeConfigObject,} from "@narratage/runtime-adapter";import { createEnvironmentCredentialStorePackage } from "./index.js";-const environmentCredentialStoreAdapter = createRuntimeServiceAdapterFacet({+const environmentCredentialStoreAdapter = createRuntimeComponentAdapterFacet({use: "@narratage/credential-store-env",validate(context) {const config = runtimeConfigObject(context.config, "environment CredentialStore");diff --git a/packages/credential-store-env/src/index.ts b/packages/credential-store-env/src/index.tsindex 28ae7a2b..a7a8b34c 100644--- a/packages/credential-store-env/src/index.ts+++ b/packages/credential-store-env/src/index.ts@@ -1,10 +1,10 @@import { digestOf } from "@narratage/protocol";-import { defineRuntimeServicePackage } from "@narratage/runtime";+import { defineRuntimeComponentPackage } from "@narratage/runtime";import type {CredentialRef,CredentialStore,CredentialValue,- RuntimeServicePackage,+ RuntimeComponentPackage,} from "@narratage/runtime";import { verifyCredentialRef } from "@narratage/runtime";@@ -41,11 +41,11 @@ export class EnvironmentCredentialStore implements CredentialStore {export function createEnvironmentCredentialStorePackage(options: CreateEnvironmentCredentialStorePackageOptions = {},-): RuntimeServicePackage {+): RuntimeComponentPackage {const instance = options.instance ?? "credentials.env";- return defineRuntimeServicePackage({+ return defineRuntimeComponentPackage({module: environmentCredentialStoreModuleRef,- services: [{+ components: [{role: "credential-store",facet: "credential-store",instance,@@ -53,7 +53,7 @@ export function createEnvironmentCredentialStorePackage(digest: environmentCredentialStoreImplementationDigest,},configuration: { source: "process-environment", explicitKeysOnly: true },- service: new EnvironmentCredentialStore(options.environment),+ port: new EnvironmentCredentialStore(options.environment),}],});}diff --git a/packages/credential-store-keychain/src/activation.ts b/packages/credential-store-keychain/src/activation.tsindex 0185f7cf..cf04bb98 100644--- a/packages/credential-store-keychain/src/activation.ts+++ b/packages/credential-store-keychain/src/activation.ts@@ -1,5 +1,5 @@import {- createRuntimeServiceAdapterFacet,+ createRuntimeComponentAdapterFacet,runtimeConfigExact,runtimeConfigObject,runtimeConfigString,@@ -7,7 +7,7 @@ import {import { createKeychainCredentialStorePackage } from "./store.js";-const keychainCredentialStoreRuntimeAdapter = createRuntimeServiceAdapterFacet({+const keychainCredentialStoreRuntimeAdapter = createRuntimeComponentAdapterFacet({use: "@narratage/credential-store-keychain",validate(context) {const config = runtimeConfigObject(context.config, "keychain CredentialStore");diff --git a/packages/credential-store-keychain/src/store.ts b/packages/credential-store-keychain/src/store.tsindex 35ba8927..d67d1148 100644--- a/packages/credential-store-keychain/src/store.ts+++ b/packages/credential-store-keychain/src/store.ts@@ -1,11 +1,11 @@import { execFile } from "node:child_process";import { digestOf } from "@narratage/protocol";-import { defineRuntimeServicePackage, verifyCredentialRef } from "@narratage/runtime";+import { defineRuntimeComponentPackage, verifyCredentialRef } from "@narratage/runtime";import type {CredentialRef,CredentialValue,- RuntimeServicePackage,+ RuntimeComponentPackage,WritableCredentialStore,} from "@narratage/runtime";@@ -133,12 +133,12 @@ export class KeychainCredentialStore implements WritableCredentialStore {export function createKeychainCredentialStorePackage(options: CreateKeychainCredentialStorePackageOptions = {},-): RuntimeServicePackage {+): RuntimeComponentPackage {const instance = options.instance ?? "credentials.keychain";const service = options.service ?? DEFAULT_SERVICE;- return defineRuntimeServicePackage({+ return defineRuntimeComponentPackage({module: keychainCredentialStoreModuleRef,- services: [{+ components: [{role: "credential-store",facet: "credential-store",instance,@@ -146,7 +146,7 @@ export function createKeychainCredentialStorePackage(digest: keychainCredentialStoreImplementationDigest,},configuration: { source: "os-keychain", service, explicitKeysOnly: true },- service: new KeychainCredentialStore({+ port: new KeychainCredentialStore({service,...(options.read === undefined ? {} : { read: options.read }),...(options.write === undefined ? {} : { write: options.write }),diff --git a/packages/credential-store-keychain/test/store.test.ts b/packages/credential-store-keychain/test/store.test.tsindex ea00c270..65f8d5c6 100644--- a/packages/credential-store-keychain/test/store.test.ts+++ b/packages/credential-store-keychain/test/store.test.ts@@ -34,15 +34,15 @@ test("a malformed reference is refused before anything is looked up", async () =test("the configured service is part of the instance's identity", () => {const configured = createKeychainCredentialStorePackage({ instance: "credentials.team", service: "acme" });- assert.equal(configured.services[0]?.instance.id, "credentials.team");+ assert.equal(configured.components[0]?.instance.id, "credentials.team");// Configuration reaches identity as a digest and is not carried in the// Closure, so the proof that the service name counts is that a different// name is a different instance.const other = createKeychainCredentialStorePackage({ instance: "credentials.team", service: "other" });- assert.ok(configured.services[0]?.instance.configurationDigest);+ assert.ok(configured.components[0]?.instance.configurationDigest);assert.notEqual(- configured.services[0]?.instance.configurationDigest,- other.services[0]?.instance.configurationDigest,+ configured.components[0]?.instance.configurationDigest,+ other.components[0]?.instance.configurationDigest,);});diff --git a/packages/local/README.md b/packages/local/README.mdindex 8557b18f..44dfcb9a 100644--- a/packages/local/README.md+++ b/packages/local/README.md@@ -1,89 +1,63 @@# `@narratage/local`-Node-hosted assembly and process lifecycle for an explicitly selected Runtime. It is not a bundle of-default Stores and it contains no authoring, video, Provider or package-routing policy.+Local Runtime Host for Narratage. The package owns local process lifecycle, durable dispatch and+assembly of explicitly selected Runtime Components. It contains no authoring, video or Provider+routing policy.-`@narratage/local` contributes two replaceable Runtime services:--- `scheduler`: regenerates ready Core commands from verified BuildState;-- `worker`: claims durable Build dispatches, maintains fenced leases and advances them.--A Runtime Profile must separately select every service:+The Runtime Profile selects this Host at the top level, then configures its private deployment:```json{- "format": "svml.runtime-config@1",- "packageLock": "./svml.packages.lock",+ "format": "narratage.runtime-profile@1","runtimePackageLock": "./svml.runtime-packages.lock",- "runtimeServices": [- { "use": "@narratage/local", "instance": "execution" },- { "use": "@narratage/store-sqlite", "instance": "state", "config": { "path": ".svml/runtime.sqlite" } },- { "use": "@narratage/artifact-store-fs", "instance": "artifacts", "config": { "path": ".svml/artifacts" } },- { "use": "@narratage/credential-store-keychain", "instance": "credentials", "config": {} }- ],- "services": {- "scheduler": "execution.scheduler",- "worker": "execution.worker",- "stores": {- "build": "state.builds",- "operations": "state.operations",- "dispatch": "state.dispatch",- "artifacts": "artifacts",- "credentials": ["credentials"]+ "runtime": {+ "use": "@narratage/local",+ "config": {+ "dataRoot": ".narratage/runtimes/local",+ "components": {+ "execution": { "use": "@narratage/local" },+ "state": { "use": "@narratage/store-sqlite", "config": { "path": "state.sqlite" } },+ "artifacts": { "use": "@narratage/artifact-store-fs", "config": { "path": "artifacts" } }+ },+ "bindings": {+ "scheduler": "execution.scheduler",+ "worker": "execution.worker",+ "stores": {+ "build": "state.builds",+ "operations": "state.operations",+ "dispatch": "state.dispatch",+ "artifacts": "artifacts",+ "credentials": []+ }+ },+ "endpoints": {},+ "limits": { "maxOperations": 4 }}- },- "endpoints": [],- "scheduling": { "maxConcurrency": 4 }+ }}```-No role is inferred by uniqueness. An empty or incomplete selection fails before work starts.-`@narratage/local` has no production dependency on SQLite, the filesystem ArtifactStore, an-environment credential source, or any Provider.--## Execution law+`components` declares available infrastructure instances; `bindings` selects exact role facets.+Nothing is selected by presence or uniqueness. `endpoints` declares capability implementations and+their Managed Programs. `limits` belongs to this Runtime deployment, not to Core or Author Source.-`LocalRuntime.build()` stages source attachments, creates verified BuildState and one durable-dispatch, then returns. A Worker process owns execution. `--follow` polls that dispatch and never-becomes its executor; interrupting the observer does not cancel the Build.+## Execution-The Worker stores no serialized Core command. After every restart it reopens verified BuildState and-asks the selected Scheduler to regenerate the current commands. Recoverable Provider checkpoints-remain in `OperationStore`; dispatch lease, heartbeat, admission and shared resource capacity remain in-`BuildDispatchStore`. Queue and cancellation inspection read those authoritative stores directly.+Build submission creates durable state and returns. A detached Worker claims dispatches and asks+Core to regenerate Commands from verified Build facts after every restart. Provider recovery data+stays with each Operation; cancellation closes Build admission and reconciles work already submitted.-Cancellation is Build-scoped. A queued Build that no Worker has claimed becomes terminal atomically;-an active Build first closes admission. Existing Operations keep their own execution fact and a-separate cancellation-control fact. Provider acceptance is not reported as cancellation; unsupported-or too-late requests continue reconciling the same Operation and never select another Candidate.-Endpoint checkpoint recovery continues the same in-flight task after Worker failure; it is not a way-to reopen a terminal Build.+The Runtime Controller owns the local Worker and Managed Program lifecycle. The generic CLI calls+that Controller and has no PID, signal, log path or Python/Node process policy of its own.## Boundaries-- `svml.packages.lock` closes deterministic Producer and Validator code used by the graph.-- `svml.runtime-packages.lock` closes privileged Runtime adapters that may access files, credentials,- processes or networks.-- `.svml` and `.svrun` source can affect neither lock.-- loaded implementation identities are rebound to actual package and dependency bytes.-- Runtime credentials are resolved only from explicitly selected `CredentialStore` instances.--`LocalBuildRequest.attachments` is explicit Host ingress into the selected ArtifactStore. The Store's-returned digest, media type and size must equal the claimed `BlobRef` before Core execution. Artifact-attachments are reopenable streams; a streaming Store receives them without a whole-file compiler or-Runtime buffer. A non-streaming replacement Store remains valid but explicitly pays the buffering cost.-Operation progress is a small generic `{ phase, completed?, total?, unit? }` fact owned by the-Endpoint, independent from its opaque recovery checkpoint.-Artifact retention is explicit maintenance: `narratage gc` previews by default and `--apply` removes only bytes-unreachable from retained Build and Operation facts.--Worker and managed-service lifecycle changes are serialized by profile-scoped filesystem locks. Two-simultaneous `build` commands therefore reuse one detached Worker rather than launching orphan-processes. CLI log reads are tail-bounded and oversized logs rotate on the next managed start.--`BuildCatalog` is optional Host presentation metadata. SQLite may expose one beside its execution-facets, but Local never creates a second hidden database or treats aliases and source paths as Build-truth.+* The Runtime Profile contains no Source Workspace or Source package lock.+* `dataRoot` contains deployment state, never author source or credentials.+* `svml.runtime-packages.lock` closes privileged Runtime packages.+* `svml.packages.lock` independently closes source and compute implementations for one project.+* Components and Endpoints communicate through their declared facets and capabilities; this Host+ keeps no central list of video packages.-Advanced embeddings may call `createProjectLocalRuntime()` with explicitly constructed service and-Endpoint packages. That TypeScript API has the same selection laws as the JSON Profile.+The local Host is one possible implementation. Another package may expose the same Node Runtime Host+facet and submit Builds to a remote deployment without changing the CLI or Core.diff --git a/packages/local/package.json b/packages/local/package.jsonindex d90c8f50..0240702f 100644--- a/packages/local/package.json+++ b/packages/local/package.json@@ -7,7 +7,8 @@"exports": {".": "./src/index.ts","./config": "./src/config.ts",- "./external-services": "./src/external-services.ts"+ "./programs": "./src/programs.ts",+ "./worker-process": "./src/worker-process.ts"},"svml": {"activation": "./src/activation.ts"@@ -21,6 +22,7 @@"@narratage/protocol": "workspace:*","@narratage/runtime": "workspace:*","@narratage/runtime-adapter": "workspace:*",+ "@narratage/runtime-adapter-node": "workspace:*","@narratage/validation": "workspace:*"},"devDependencies": {diff --git a/packages/local/src/activation.ts b/packages/local/src/activation.tsindex 92efac9d..6ede09cc 100644--- a/packages/local/src/activation.ts+++ b/packages/local/src/activation.ts@@ -1,12 +1,13 @@import {- createRuntimeServiceAdapterFacet,+ createRuntimeComponentAdapterFacet,runtimeConfigExact,runtimeConfigObject,} from "@narratage/runtime-adapter";import { createLocalExecutionPackage } from "./scheduler-package.js";+import { localRuntimeHostAdapter } from "./host.js";-const localExecutionAdapter = createRuntimeServiceAdapterFacet({+const localExecutionAdapter = createRuntimeComponentAdapterFacet({use: "@narratage/local",validate(context) {const config = runtimeConfigObject(context.config, "local execution");@@ -19,7 +20,7 @@ const localExecutionAdapter = createRuntimeServiceAdapterFacet({export const svmlPackage = {format: "svml.node-package@1" as const,- hostFacets: [localExecutionAdapter],+ hostFacets: [localRuntimeHostAdapter, localExecutionAdapter],};export default svmlPackage;diff --git a/packages/local/src/config.ts b/packages/local/src/config.tsindex 1e1b9e2d..50fbd9d2 100644--- a/packages/local/src/config.ts+++ b/packages/local/src/config.ts@@ -14,20 +14,20 @@ import type { CanonicalValue, CapabilityRef } from "@narratage/protocol";import {isRuntimeAdapterHostFacet,runtimeEndpointAdapterHostAbi,- runtimeServiceAdapterHostAbi,+ runtimeComponentAdapterHostAbi,RuntimeAdapterRegistry,} from "@narratage/runtime-adapter";import type {RuntimeDoctorDiagnostic,RuntimeEndpointActivation,- RuntimeExternalService,- RuntimeServiceState,+ ManagedProgram,+ ManagedProgramState,} from "@narratage/runtime-adapter";import {CompositeCredentialStore,- verifyRuntimeServicePackage,+ verifyRuntimeComponentPackage,} from "@narratage/runtime";-import type { RuntimeServicePackage, RuntimeServiceSelection } from "@narratage/runtime";+import type { RuntimeComponentPackage, RuntimeBindings } from "@narratage/runtime";import type { LocalRuntime } from "./types.js";import type { LocalCredentialControl } from "./types.js";@@ -45,19 +45,17 @@ export type RuntimeConfigEntry = {};export type RuntimeConfigDocument = {- readonly format: "svml.runtime-config@1";- /** Resolved relative to the configuration file. Defaults to its directory. */- readonly root?: string;- /** Resolved relative to the configuration file. Locates installed Node packages, not Runtime data. */- readonly packageRoot?: string;- readonly packageLock?: string;+ readonly format: "narratage.runtime-profile@1";+ readonly runtimeUse: string;+ /** Private deployment state, resolved relative to the Profile. */+ readonly dataRoot: string;/** Locked physical packages allowed to configure privileged Runtime adapters. */readonly runtimePackageLock?: string;/** Replaceable parts of the Runtime itself. One package may fill several roles. */- readonly runtimeServices: readonly RuntimeConfigEntry[];- readonly services: RuntimeServiceSelection;+ readonly components: readonly RuntimeConfigEntry[];+ readonly bindings: RuntimeBindings;readonly endpoints: readonly RuntimeConfigEntry[];- readonly scheduling: {+ readonly limits: {readonly maxConcurrency: number;readonly resources?: Readonly<Record<string, number>>;};@@ -99,87 +97,93 @@ function stringList(value: unknown, subject: string): readonly string[] {return items;}-function entry(value: unknown, subject: string, authorityRequired: boolean): RuntimeConfigEntry {+function entry(value: unknown, instance: string, subject: string, authorityRequired: boolean): RuntimeConfigEntry {const item = object(value, subject);- exactKeys(item, authorityRequired ? ["use", "instance", "authority", "config"] : ["use", "instance", "config"], subject);+ exactKeys(item, authorityRequired ? ["use", "authority", "config"] : ["use", "config"], subject);const authority = authorityRequired ? optionalString(item.authority, `${subject}.authority`) : undefined;return {use: requiredString(item.use, `${subject}.use`),- instance: requiredString(item.instance, `${subject}.instance`),+ instance,...(authority === undefined ? {} : { authority }),...(item.config === undefined ? {} : { config: canonicalize(item.config) }),};}-function scheduling(value: unknown): RuntimeConfigDocument["scheduling"] {- if (value === undefined) throw new Error("$runtime.scheduling is required");- const item = object(value, "$runtime.scheduling");- exactKeys(item, ["maxConcurrency", "resources"], "$runtime.scheduling");- const resources = item.resources === undefined ? undefined : object(item.resources, "$runtime.scheduling.resources");+function limits(value: unknown): RuntimeConfigDocument["limits"] {+ if (value === undefined) throw new Error("$runtime.runtime.config.limits is required");+ const item = object(value, "$runtime.runtime.config.limits");+ exactKeys(item, ["maxOperations", "resources"], "$runtime.runtime.config.limits");+ const resources = item.resources === undefined ? undefined : object(item.resources, "$runtime.runtime.config.limits.resources");const normalizedResources = resources === undefined ? undefined : Object.fromEntries(Object.entries(resources).map(([name, limit]) => {if (name.trim().length === 0) throw new Error("Runtime resource id must not be empty");- return [name, positiveInteger(limit, `$runtime.scheduling.resources.${name}`)!];+ return [name, positiveInteger(limit, `$runtime.runtime.config.limits.resources.${name}`)!];}));- const maxConcurrency = positiveInteger(item.maxConcurrency, "$runtime.scheduling.maxConcurrency");- if (maxConcurrency === undefined) throw new Error("$runtime.scheduling.maxConcurrency is required");+ const maxConcurrency = positiveInteger(item.maxOperations, "$runtime.runtime.config.limits.maxOperations");+ if (maxConcurrency === undefined) throw new Error("$runtime.runtime.config.limits.maxOperations is required");return {maxConcurrency,...(normalizedResources === undefined ? {} : { resources: normalizedResources }),};}-function serviceSelection(value: unknown): RuntimeServiceSelection {- const item = object(value, "$runtime.services");- exactKeys(item, ["scheduler", "worker", "stores"], "$runtime.services");- const stores = object(item.stores, "$runtime.services.stores");+function serviceSelection(value: unknown): RuntimeBindings {+ const item = object(value, "$runtime.runtime.config.bindings");+ exactKeys(item, ["scheduler", "worker", "stores"], "$runtime.runtime.config.bindings");+ const stores = object(item.stores, "$runtime.runtime.config.bindings.stores");exactKeys(stores, ["build", "operations", "dispatch", "artifacts", "credentials"],- "$runtime.services.stores");- const credentials = stringList(stores.credentials, "$runtime.services.stores.credentials");+ "$runtime.runtime.config.bindings.stores");+ const credentials = stringList(stores.credentials, "$runtime.runtime.config.bindings.stores.credentials");return {- scheduler: requiredString(item.scheduler, "$runtime.services.scheduler"),- worker: requiredString(item.worker, "$runtime.services.worker"),+ scheduler: requiredString(item.scheduler, "$runtime.runtime.config.bindings.scheduler"),+ worker: requiredString(item.worker, "$runtime.runtime.config.bindings.worker"),stores: {- build: requiredString(stores.build, "$runtime.services.stores.build"),- operations: requiredString(stores.operations, "$runtime.services.stores.operations"),- dispatch: requiredString(stores.dispatch, "$runtime.services.stores.dispatch"),- artifacts: requiredString(stores.artifacts, "$runtime.services.stores.artifacts"),+ build: requiredString(stores.build, "$runtime.runtime.config.bindings.stores.build"),+ operations: requiredString(stores.operations, "$runtime.runtime.config.bindings.stores.operations"),+ dispatch: requiredString(stores.dispatch, "$runtime.runtime.config.bindings.stores.dispatch"),+ artifacts: requiredString(stores.artifacts, "$runtime.runtime.config.bindings.stores.artifacts"),credentials,},};}+function entries(value: unknown, subject: string, authorityRequired: boolean): readonly RuntimeConfigEntry[] {+ const configured = object(value, subject);+ return Object.entries(configured).map(([instance, item]) => {+ if (instance.trim().length === 0) throw new Error(`${subject} contains an empty instance name`);+ return entry(item, instance, `${subject}.${instance}`, authorityRequired);+ });+}+export function parseRuntimeConfig(value: unknown): RuntimeConfigDocument {const item = object(value, "$runtime");- exactKeys(item, [- "format", "root", "packageRoot", "packageLock", "runtimePackageLock",- "runtimeServices", "services", "endpoints", "scheduling",- ], "$runtime");- if (item.format !== "svml.runtime-config@1") throw new Error("$runtime.format must be svml.runtime-config@1");- if (!Array.isArray(item.runtimeServices)) throw new Error("$runtime.runtimeServices must be an array");- const runtimeServices = item.runtimeServices.map((value, index) =>- entry(value, `$runtime.runtimeServices[${index}]`, false));- const endpoints = item.endpoints === undefined ? [] : (() => {- if (!Array.isArray(item.endpoints)) throw new Error("$runtime.endpoints must be an array");- return item.endpoints.map((value, index) => entry(value, `$runtime.endpoints[${index}]`, true));- })();- const instances = [...runtimeServices, ...endpoints].map((value) => value.instance);+ exactKeys(item, ["format", "runtimePackageLock", "runtime"], "$runtime");+ if (item.format !== "narratage.runtime-profile@1") {+ throw new Error("$runtime.format must be narratage.runtime-profile@1");+ }+ const runtime = object(item.runtime, "$runtime.runtime");+ exactKeys(runtime, ["use", "config"], "$runtime.runtime");+ const runtimeUse = requiredString(runtime.use, "$runtime.runtime.use");+ if (runtimeUse !== "@narratage/local") throw new Error(`Local Runtime loader cannot activate ${runtimeUse}`);+ const config = object(runtime.config, "$runtime.runtime.config");+ exactKeys(config, ["dataRoot", "components", "bindings", "endpoints", "limits"], "$runtime.runtime.config");+ const components = entries(config.components, "$runtime.runtime.config.components", false);+ const endpoints = config.endpoints === undefined+ ? []+ : entries(config.endpoints, "$runtime.runtime.config.endpoints", true);+ const instances = [...components, ...endpoints].map((value) => value.instance);if (new Set(instances).size !== instances.length) throw new Error("$runtime repeats a Runtime instance id");- const scheduled = scheduling(item.scheduling);return {- format: "svml.runtime-config@1",- ...(optionalString(item.root, "$runtime.root") === undefined ? {} : { root: item.root as string }),- ...(optionalString(item.packageRoot, "$runtime.packageRoot") === undefined- ? {}- : { packageRoot: item.packageRoot as string }),- ...(optionalString(item.packageLock, "$runtime.packageLock") === undefined ? {} : { packageLock: item.packageLock as string }),+ format: "narratage.runtime-profile@1",+ runtimeUse,+ dataRoot: requiredString(config.dataRoot, "$runtime.runtime.config.dataRoot"),...(optionalString(item.runtimePackageLock, "$runtime.runtimePackageLock") === undefined? {}: { runtimePackageLock: item.runtimePackageLock as string }),- runtimeServices,- services: serviceSelection(item.services),+ components,+ bindings: serviceSelection(config.bindings),endpoints,- scheduling: scheduled,+ limits: limits(config.limits),};}@@ -196,14 +200,13 @@ export type LoadRuntimeConfigOptions = {};export type RuntimeConfigDoctorResult = {- readonly root: string;+ readonly dataRoot: string;readonly diagnostics: readonly RuntimeDoctorDiagnostic[];};export type RuntimeConfigPackageSelection = {- readonly root: string;readonly packageRoot: string;- readonly packageLock?: string;+ readonly dataRoot: string;readonly runtimePackageLock?: string;/** Logical Runtime adapters selected by kind and use name. */readonly runtimeSelection: NodePackageSelectionRequest;@@ -212,6 +215,7 @@ export type RuntimeConfigPackageSelection = {type OpenedRuntimeConfig = {readonly absolute: string;readonly document: RuntimeConfigDocument;+ readonly profileRoot: string;readonly root: string;readonly packageRoot: string;};@@ -222,11 +226,13 @@ async function openRuntimeConfig(): Promise<OpenedRuntimeConfig> {const absolute = resolve(path);const document = parseRuntimeConfig(JSON.parse(await readFile(absolute, "utf8")));+ const profileRoot = dirname(absolute);return {absolute,document,- root: resolve(dirname(absolute), document.root ?? "."),- packageRoot: resolve(dirname(absolute), document.packageRoot ?? packageRootHint ?? document.root ?? "."),+ profileRoot,+ root: resolve(profileRoot, document.dataRoot),+ packageRoot: resolve(packageRootHint ?? profileRoot),};}@@ -234,7 +240,7 @@ function runtimePackageSelection(document: RuntimeConfigDocument): NodePackageSereturn {selected: [],logical: [- ...document.runtimeServices.map((item) => ({ abi: runtimeServiceAdapterHostAbi, name: item.use })),+ ...document.components.map((item) => ({ abi: runtimeComponentAdapterHostAbi, name: item.use })),...document.endpoints.map((item) => ({ abi: runtimeEndpointAdapterHostAbi, name: item.use })),],};@@ -251,33 +257,27 @@ export async function runtimeConfigPackageSelection(path: string,options: LoadRuntimeConfigOptions = {},): Promise<RuntimeConfigPackageSelection> {- const { document, root, packageRoot } = await openRuntimeConfig(path, options.packageRoot);+ const { document, profileRoot, root, packageRoot } = await openRuntimeConfig(path, options.packageRoot);return {- root,packageRoot,+ dataRoot: root,runtimeSelection: runtimePackageSelection(document),- ...(document.packageLock === undefined- ? {}- : { packageLock: resolve(root, document.packageLock) }),...(document.runtimePackageLock === undefined? {}- : { runtimePackageLock: resolve(root, document.runtimePackageLock) }),+ : { runtimePackageLock: resolve(profileRoot, document.runtimePackageLock) }),};}/** Deployment revision understood only by this Runtime Profile implementation. */export async function runtimeConfigRevision(path: string): Promise<string> {- const { document, root } = await openRuntimeConfig(path);+ const { document, profileRoot } = await openRuntimeConfig(path);const locks: Record<string, string> = {};- for (const [name, value] of [- ["packageLock", document.packageLock],- ["runtimePackageLock", document.runtimePackageLock],- ] as const) {+ for (const [name, value] of [["runtimePackageLock", document.runtimePackageLock]] as const) {if (value === undefined) continue;- locks[name] = (await readNodePackageLock(resolve(root, value))).digest;+ locks[name] = (await readNodePackageLock(resolve(profileRoot, value))).digest;}return digestOf(canonicalize({- format: "svml.runtime-config-revision@1",+ format: "narratage.runtime-profile-revision@1",document,locks,}));@@ -309,9 +309,9 @@ async function installLockedRuntimeAdapters(}/** One Endpoint's declaration of an external program its Provider drives. */-type DeclaredExternalService = {+type DeclaredManagedProgram = {readonly instance: string;- readonly service: RuntimeExternalService;+ readonly program: ManagedProgram;};function sameCapability(left: CapabilityRef, right: CapabilityRef): boolean {@@ -324,28 +324,34 @@ function sameCapability(left: CapabilityRef, right: CapabilityRef): boolean {* The external programs a Runtime Profile implies, in the order it declares* them. Two Endpoints may name the same program — one WhisperX serves every* Provider instance pointed at it — so callers that act on these deduplicate- * by `service.id` and act once.+ * by `program.id` and act once.*/-export async function declaredExternalServices(+export async function declaredManagedPrograms(path: string,options: LoadRuntimeConfigOptions & { readonly capabilities?: readonly CapabilityRef[] } = {},-): Promise<{ readonly root: string; readonly services: readonly DeclaredExternalService[] }> {- const { document, root, packageRoot } = await openRuntimeConfig(path, options.packageRoot);+): Promise<{ readonly dataRoot: string; readonly programs: readonly DeclaredManagedProgram[] }> {+ const { document, profileRoot, root, packageRoot } = await openRuntimeConfig(path, options.packageRoot);// A Build with no demanded external capability has no program to discover.// Keep validating the Profile document and its root, but do not load the// privileged Runtime package closure merely to prove that the empty set is- // empty. `services up/status/down` omit this filter and still inspect every- // declared service.- if (options.capabilities?.length === 0) return { root, services: [] };+ // empty. `programs up/status/down` omit this filter and still inspect every+ // declared program.+ if (options.capabilities?.length === 0) return { dataRoot: root, programs: [] };const registry = options.registry ?? new RuntimeAdapterRegistry();- await installLockedRuntimeAdapters(registry, document.runtimePackageLock, root, packageRoot, runtimePackageSelection(document));- const services: DeclaredExternalService[] = [];+ await installLockedRuntimeAdapters(+ registry,+ document.runtimePackageLock,+ profileRoot,+ packageRoot,+ runtimePackageSelection(document),+ );+ const programs: DeclaredManagedProgram[] = [];for (const item of document.endpoints) {if (!registry.has(item.use, "endpoint")) {throw new Error(`Runtime Adapter ${item.use} is not registered`);}const activation = await registry.activateEndpoint(item.use, {- root,+ dataRoot: root,instance: item.instance,authority: item.authority ?? item.instance,config: item.config ?? {},@@ -354,10 +360,10 @@ export async function declaredExternalServices(options.capabilities!.some((capability) => sameCapability(binding.capability, capability)))) {continue;}- const service = activation.externalService;- if (service !== undefined) services.push({ instance: item.instance, service });+ const program = activation.program;+ if (program !== undefined) programs.push({ instance: item.instance, program });}- return { root, services };+ return { dataRoot: root, programs };}function diagnostic(error: unknown, code: string, subject?: string): RuntimeDoctorDiagnostic {@@ -374,7 +380,7 @@ export async function doctorRuntimeConfig(path: string,options: LoadRuntimeConfigOptions & { readonly capabilities?: readonly CapabilityRef[] } = {},): Promise<RuntimeConfigDoctorResult> {- const { absolute, document, root, packageRoot } = await openRuntimeConfig(path, options.packageRoot);+ const { absolute, document, profileRoot, root, packageRoot } = await openRuntimeConfig(path, options.packageRoot);const diagnostics: RuntimeDoctorDiagnostic[] = [];const credentialEndpoints: Array<{readonly entry: RuntimeConfigEntry;@@ -386,56 +392,45 @@ export async function doctorRuntimeConfig(try {if (!(await stat(root)).isDirectory()) throw new Error(`Runtime root ${root} is not a directory`);} catch (error) {- diagnostics.push(diagnostic(error, "RUNTIME_ROOT_INVALID", root));- return { root, diagnostics };+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {+ // Observation is allowed before the selected Runtime has created private state.+ } else {+ diagnostics.push(diagnostic(error, "RUNTIME_DATA_ROOT_INVALID", root));+ return { dataRoot: root, diagnostics };+ }}const registry = options.registry ?? new RuntimeAdapterRegistry();const runtimeLock = installLockedRuntimeAdapters(registry,document.runtimePackageLock,- root,+ profileRoot,packageRoot,runtimePackageSelection(document),);- const implementationLock = options.implementationPackages !== undefined- ? (async () => {- if (document.packageLock === undefined) throw new Error("Runtime Profile has no packageLock for verified implementation packages");- const declared = await readNodePackageLock(resolve(root, document.packageLock));- if (declared.digest !== options.implementationPackages!.inventoryDigest) {- throw new Error("Runtime Profile packageLock differs from the implementation packages already verified by this Host");- }- return options.implementationPackages;- })()- : document.packageLock === undefined- ? Promise.resolve(undefined)- : loadNodePackageSet(resolve(root, document.packageLock), packageRoot);- const [runtimeResult, implementationResult] = await Promise.allSettled([runtimeLock, implementationLock]);+ const [runtimeResult] = await Promise.allSettled([runtimeLock]);if (runtimeResult.status === "rejected") {diagnostics.push(diagnostic(runtimeResult.reason, "RUNTIME_PACKAGE_LOCK_INVALID", document.runtimePackageLock));- return { root, diagnostics };- }- if (implementationResult.status === "rejected") {- diagnostics.push(diagnostic(implementationResult.reason, "IMPLEMENTATION_PACKAGE_LOCK_INVALID", document.packageLock));+ return { dataRoot: root, diagnostics };}- for (const item of document.runtimeServices) {- const context = { root, instance: item.instance, config: item.config ?? {} };+ for (const item of document.components) {+ const context = { dataRoot: root, instance: item.instance, config: item.config ?? {} };try {- const selection = registry.validate(item.use, "runtime-service", context);+ const selection = registry.validate(item.use, "runtime-component", context);diagnostics.push(...selection);if (selection.some((entry) => entry.severity === "error")) continue;} catch (error) {- diagnostics.push(diagnostic(error, "RUNTIME_SERVICE_CONFIG_INVALID", item.instance));+ diagnostics.push(diagnostic(error, "RUNTIME_COMPONENT_CONFIG_INVALID", item.instance));continue;}try {- diagnostics.push(...await registry.doctor(item.use, "runtime-service", context));+ diagnostics.push(...await registry.doctor(item.use, "runtime-component", context));} catch (error) {diagnostics.push(diagnostic(error, "RUNTIME_ADAPTER_DOCTOR_FAILED", item.instance));}}for (const item of document.endpoints) {const context = {- root,+ dataRoot: root,instance: item.instance,authority: item.authority ?? item.instance,config: item.config ?? {},@@ -467,40 +462,39 @@ export async function doctorRuntimeConfig(}if (adapterHasError) continue;credentialEndpoints.push({ entry: item, activation });- // An external program is a prerequisite a Build cannot supply for itself, so+ // A Managed Program is a prerequisite a Build cannot supply for itself, so// name the command that supplies it here rather than failing mid-Build on a- // socket. `RUNTIME_SERVICE_` above is the Runtime's own part; this is the- // separate program a deployment must have installed or running.- let service: RuntimeExternalService | undefined;+ // socket. This is the separate process a deployment must have installed or running.+ let program: ManagedProgram | undefined;try {- service = activation.externalService;+ program = activation.program;} catch (error) {- diagnostics.push(diagnostic(error, "EXTERNAL_SERVICE_INVALID", item.instance));+ diagnostics.push(diagnostic(error, "MANAGED_PROGRAM_INVALID", item.instance));}- if (service === undefined) continue;- let state: RuntimeServiceState;+ if (program === undefined) continue;+ let state: ManagedProgramState;try {- state = await service.probe();+ state = await program.probe();} catch (error) {- diagnostics.push(diagnostic(error, "EXTERNAL_SERVICE_PROBE_FAILED", service.id));+ diagnostics.push(diagnostic(error, "MANAGED_PROGRAM_PROBE_FAILED", program.id));continue;}if (state.state === "down") {diagnostics.push({severity: "error",- code: "EXTERNAL_SERVICE_DOWN",- message: `${service.id} is not usable: ${state.detail}.${- service.start === undefined && service.prepare === undefined+ code: "MANAGED_PROGRAM_DOWN",+ message: `${program.id} is not usable: ${state.detail}.${+ program.start === undefined && program.prepare === undefined? ""- : " Bring it up with: narratage services up"}`,- subject: service.id,+ : " Bring it up with: narratage programs up"}`,+ subject: program.id,});} else if (state.state === "mismatch") {diagnostics.push({severity: "error",- code: "EXTERNAL_SERVICE_MISMATCH",- message: `${service.id} is running but differs from this Runtime Profile: ${state.detail}`,- subject: service.id,+ code: "MANAGED_PROGRAM_MISMATCH",+ message: `${program.id} is running but differs from this Runtime Profile: ${state.detail}`,+ subject: program.id,});}}@@ -514,32 +508,32 @@ export async function doctorRuntimeConfig(});}if (credentialEndpoints.length > 0) {- let packages: readonly RuntimeServicePackage[] = [];+ let packages: readonly RuntimeComponentPackage[] = [];try {const endpoints = credentialEndpoints.map(({ entry, activation }) => ({entry,credentials: activation.endpoint.credentials,}));- if (endpoints.every((item) => item.credentials.length === 0)) return { root, diagnostics };- const serviceEntries = runtimeEntriesForServices(- document.runtimeServices,- document.services.stores.credentials,+ if (endpoints.every((item) => item.credentials.length === 0)) return { dataRoot: root, diagnostics };+ const serviceEntries = runtimeEntriesForComponents(+ document.components,+ document.bindings.stores.credentials,);- packages = await Promise.all(serviceEntries.map(async (item) => await registry.createService(item.use, {- root,+ packages = await Promise.all(serviceEntries.map(async (item) => await registry.createComponent(item.use, {+ dataRoot: root,instance: item.instance,config: item.config ?? {},})));- for (const item of packages) verifyRuntimeServicePackage(item);+ for (const item of packages) verifyRuntimeComponentPackage(item);const byId = new Map(packages.flatMap((item) =>- item.services.map((service) => [service.instance.id, service] as const)));- const stores = document.services.stores.credentials.map((id) => {- const service = byId.get(id);- if (service === undefined) throw new Error(`CredentialStore selection refers to unknown instance ${id}`);- if (service.role !== "credential-store") {- throw new Error(`Runtime service ${id} is ${service.role}, not credential-store`);+ item.components.map((component) => [component.instance.id, component] as const)));+ const stores = document.bindings.stores.credentials.map((id) => {+ const component = byId.get(id);+ if (component === undefined) throw new Error(`CredentialStore selection refers to unknown instance ${id}`);+ if (component.role !== "credential-store") {+ throw new Error(`Runtime Component ${id} is ${component.role}, not credential-store`);}- return service.service;+ return component.port;});const credentials = new CompositeCredentialStore(stores);for (const { entry, credentials: slots } of endpoints) {@@ -559,10 +553,10 @@ export async function doctorRuntimeConfig(} catch (error) {diagnostics.push(diagnostic(error, "RUNTIME_CREDENTIAL_CHECK_FAILED"));} finally {- await closeRuntimeServicePackages(packages);+ await closeRuntimeComponentPackages(packages);}}- return { root, diagnostics };+ return { dataRoot: root, diagnostics };}export async function createRuntimeFromConfig(@@ -572,79 +566,65 @@ export async function createRuntimeFromConfig(// Diagnostics and lifecycle discovery must not initialize SQLite, Drivers or Endpoints.// Load the executable Runtime assembly only on the command that actually constructs it.const { createProjectLocalRuntime } = await import("./runtime.js");- const { document, root, packageRoot } = await openRuntimeConfig(path, options.packageRoot);- if (options.implementationPackages !== undefined) {- if (document.packageLock === undefined) {- throw new Error("Runtime Profile has no packageLock for the supplied implementation packages");- }- const declared = await readNodePackageLock(resolve(root, document.packageLock));- if (declared.digest !== options.implementationPackages.inventoryDigest) {- throw new Error("Runtime Profile packageLock differs from the implementation packages already verified by this Host");- }- }+ const { document, profileRoot, root, packageRoot } = await openRuntimeConfig(path, options.packageRoot);const registry = options.registry ?? new RuntimeAdapterRegistry();- const implementationPackagesPromise = options.implementationPackages !== undefined- ? Promise.resolve(options.implementationPackages)- : document.packageLock === undefined- ? Promise.resolve(undefined)- : loadNodePackageSet(resolve(root, document.packageLock), packageRoot);- const [, implementationPackages] = await Promise.all([+ await Promise.all([installLockedRuntimeAdapters(registry,document.runtimePackageLock,- root,+ profileRoot,packageRoot,runtimePackageSelection(document),),- implementationPackagesPromise,]);- const runtimeServices = await Promise.all(document.runtimeServices.map(async (item) => {- return await registry.createService(item.use, {- root,+ const runtimeComponents = await Promise.all(document.components.map(async (item) => {+ return await registry.createComponent(item.use, {+ dataRoot: root,instance: item.instance,config: item.config ?? {},});}));const endpoints = await Promise.all(document.endpoints.map(async (item) => {return await registry.createEndpoint(item.use, {- root,+ dataRoot: root,instance: item.instance,authority: item.authority ?? item.instance,config: item.config ?? {},});}));return await createProjectLocalRuntime({- root,+ dataRoot: root,packageRoot,- runtimeServices,- runtimeSelection: document.services,+ runtimeComponents,+ bindings: document.bindings,components: [- ...collectNodePackageComponents((implementationPackages?.packages ?? []).map((item) => item.contribution)),+ ...collectNodePackageComponents((options.implementationPackages?.packages ?? []).map((item) => item.contribution)),...(options.components ?? []),],endpoints,- scheduling: document.scheduling,+ scheduling: document.limits,});}-async function createSelectedRuntimeServices(+async function createSelectedRuntimeComponents(document: RuntimeConfigDocument,+ profileRoot: string,root: string,packageRoot: string,registry: RuntimeAdapterRegistry,serviceIds: readonly string[],readOnly: boolean,-): Promise<readonly RuntimeServicePackage[]> {- const serviceEntries = runtimeEntriesForServices(document.runtimeServices, serviceIds);- await installLockedRuntimeAdapters(registry, document.runtimePackageLock, root, packageRoot, {+): Promise<readonly RuntimeComponentPackage[]> {+ const serviceEntries = runtimeEntriesForComponents(document.components, serviceIds);+ await installLockedRuntimeAdapters(registry, document.runtimePackageLock, profileRoot, packageRoot, {selected: [],- logical: serviceEntries.map((item) => ({ abi: runtimeServiceAdapterHostAbi, name: item.use })),+ logical: serviceEntries.map((item) => ({ abi: runtimeComponentAdapterHostAbi, name: item.use })),});- const packages: RuntimeServicePackage[] = [];+ const packages: RuntimeComponentPackage[] = [];try {for (const item of serviceEntries) {- packages.push(await registry.createService(item.use, {- root,+ packages.push(await registry.createComponent(item.use, {+ dataRoot: root,instance: item.instance,config: item.config ?? {},access: readOnly ? "read-only" : "read-write",@@ -652,7 +632,7 @@ async function createSelectedRuntimeServices(}return packages;} catch (error) {- await closeRuntimeServicePackages(packages);+ await closeRuntimeComponentPackages(packages);throw error;}}@@ -663,17 +643,17 @@ export async function createRuntimeArchiveFromConfig(options: LoadRuntimeConfigOptions = {},): Promise<LocalRuntimeArchiveControl> {const { createProjectLocalRuntimeArchiveControl } = await import("./control.js");- const { document, root, packageRoot } = await openRuntimeConfig(path, options.packageRoot);+ const { document, profileRoot, root, packageRoot } = await openRuntimeConfig(path, options.packageRoot);const registry = options.registry ?? new RuntimeAdapterRegistry();- const runtimeServices = await createSelectedRuntimeServices(document, root, packageRoot, registry, [- document.services.stores.build,- document.services.stores.operations,- document.services.stores.dispatch,+ const runtimeComponents = await createSelectedRuntimeComponents(document, profileRoot, root, packageRoot, registry, [+ document.bindings.stores.build,+ document.bindings.stores.operations,+ document.bindings.stores.dispatch,], options.readOnly === true);return await createProjectLocalRuntimeArchiveControl({- root,- runtimeServices,- runtimeSelection: document.services,+ dataRoot: root,+ runtimeComponents,+ bindings: document.bindings,});}@@ -683,15 +663,15 @@ export async function createRuntimeArtifactAccessFromConfig(options: LoadRuntimeConfigOptions = {},): Promise<LocalRuntimeArtifactAccess> {const { createProjectLocalRuntimeArtifactAccess } = await import("./control.js");- const { document, root, packageRoot } = await openRuntimeConfig(path, options.packageRoot);+ const { document, profileRoot, root, packageRoot } = await openRuntimeConfig(path, options.packageRoot);const registry = options.registry ?? new RuntimeAdapterRegistry();- const runtimeServices = await createSelectedRuntimeServices(document, root, packageRoot, registry, [- document.services.stores.artifacts,+ const runtimeComponents = await createSelectedRuntimeComponents(document, profileRoot, root, packageRoot, registry, [+ document.bindings.stores.artifacts,], options.readOnly === true);return await createProjectLocalRuntimeArtifactAccess({- root,- runtimeServices,- runtimeSelection: document.services,+ dataRoot: root,+ runtimeComponents,+ bindings: document.bindings,});}@@ -701,43 +681,43 @@ export async function createRuntimeMaintenanceFromConfig(options: LoadRuntimeConfigOptions = {},): Promise<LocalRuntimeControl> {const { createProjectLocalRuntimeControl } = await import("./control.js");- const { document, root, packageRoot } = await openRuntimeConfig(path, options.packageRoot);+ const { document, profileRoot, root, packageRoot } = await openRuntimeConfig(path, options.packageRoot);const registry = options.registry ?? new RuntimeAdapterRegistry();- const runtimeServices = await createSelectedRuntimeServices(document, root, packageRoot, registry, [- document.services.stores.build,- document.services.stores.operations,- document.services.stores.dispatch,- document.services.stores.artifacts,+ const runtimeComponents = await createSelectedRuntimeComponents(document, profileRoot, root, packageRoot, registry, [+ document.bindings.stores.build,+ document.bindings.stores.operations,+ document.bindings.stores.dispatch,+ document.bindings.stores.artifacts,], options.readOnly === true);return await createProjectLocalRuntimeControl({- root,- runtimeServices,- runtimeSelection: document.services,+ dataRoot: root,+ runtimeComponents,+ bindings: document.bindings,});}-function ownsSelectedService(entry: RuntimeConfigEntry, service: string): boolean {- return service === entry.instance || service.startsWith(`${entry.instance}.`);+function ownsSelectedComponent(entry: RuntimeConfigEntry, component: string): boolean {+ return component === entry.instance || component.startsWith(`${entry.instance}.`);}-function runtimeEntriesForServices(+function runtimeEntriesForComponents(entries: readonly RuntimeConfigEntry[],- services: readonly string[],+ components: readonly string[],): readonly RuntimeConfigEntry[] {const selected = new Set<RuntimeConfigEntry>();- for (const service of services) {- const owners = entries.filter((entry) => ownsSelectedService(entry, service));+ for (const component of components) {+ const owners = entries.filter((entry) => ownsSelectedComponent(entry, component));if (owners.length !== 1) {throw new Error(owners.length === 0- ? `Runtime service ${service} is outside every configured adapter namespace`- : `Runtime service ${service} has overlapping configured adapter namespaces`);+ ? `Runtime Component ${component} is outside every configured adapter namespace`+ : `Runtime Component ${component} has overlapping configured adapter namespaces`);}selected.add(owners[0]!);}return [...selected];}-async function closeRuntimeServicePackages(packages: readonly RuntimeServicePackage[]): Promise<void> {+async function closeRuntimeComponentPackages(packages: readonly RuntimeComponentPackage[]): Promise<void> {for (const item of [...packages].reverse()) await item.close?.();}@@ -752,39 +732,39 @@ export async function createRuntimeCredentialsFromConfig(options: LoadRuntimeConfigOptions = {},): Promise<LocalCredentialControl> {const { createLocalCredentialControl } = await import("./credentials.js");- const { document, root, packageRoot } = await openRuntimeConfig(path, options.packageRoot);+ const { document, profileRoot, root, packageRoot } = await openRuntimeConfig(path, options.packageRoot);const endpointEntry = document.endpoints.find((item) => item.instance === endpointInstance);if (endpointEntry === undefined) throw new Error(`Runtime Profile has no Endpoint instance ${endpointInstance}`);const registry = options.registry ?? new RuntimeAdapterRegistry();- const serviceEntries = runtimeEntriesForServices(- document.runtimeServices,- document.services.stores.credentials,+ const serviceEntries = runtimeEntriesForComponents(+ document.components,+ document.bindings.stores.credentials,);- await installLockedRuntimeAdapters(registry, document.runtimePackageLock, root, packageRoot, {+ await installLockedRuntimeAdapters(registry, document.runtimePackageLock, profileRoot, packageRoot, {selected: [],logical: [{ abi: runtimeEndpointAdapterHostAbi, name: endpointEntry.use },- ...serviceEntries.map((item) => ({ abi: runtimeServiceAdapterHostAbi, name: item.use })),+ ...serviceEntries.map((item) => ({ abi: runtimeComponentAdapterHostAbi, name: item.use })),],});- const packages = await Promise.all(serviceEntries.map(async (item) => await registry.createService(item.use, {- root,+ const packages = await Promise.all(serviceEntries.map(async (item) => await registry.createComponent(item.use, {+ dataRoot: root,instance: item.instance,config: item.config ?? {},})));try {- for (const item of packages) verifyRuntimeServicePackage(item);- const byId = new Map(packages.flatMap((item) => item.services.map((service) => [service.instance.id, service] as const)));- const credentialStores = document.services.stores.credentials.map((id) => {- const service = byId.get(id);- if (service === undefined) throw new Error(`CredentialStore selection refers to unknown instance ${id}`);- if (service.role !== "credential-store") {- throw new Error(`Runtime service ${id} is ${service.role}, not credential-store`);+ for (const item of packages) verifyRuntimeComponentPackage(item);+ const byId = new Map(packages.flatMap((item) => item.components.map((component) => [component.instance.id, component] as const)));+ const credentialStores = document.bindings.stores.credentials.map((id) => {+ const component = byId.get(id);+ if (component === undefined) throw new Error(`CredentialStore selection refers to unknown instance ${id}`);+ if (component.role !== "credential-store") {+ throw new Error(`Runtime Component ${id} is ${component.role}, not credential-store`);}- return service.service;+ return component.port;});const endpoint = await registry.createEndpoint(endpointEntry.use, {- root,+ dataRoot: root,instance: endpointEntry.instance,authority: endpointEntry.authority ?? endpointEntry.instance,config: endpointEntry.config ?? {},@@ -792,10 +772,10 @@ export async function createRuntimeCredentialsFromConfig(return createLocalCredentialControl({credentialStore: new CompositeCredentialStore(credentialStores),endpoints: [endpoint],- close: async () => await closeRuntimeServicePackages(packages),+ close: async () => await closeRuntimeComponentPackages(packages),});} catch (error) {- await closeRuntimeServicePackages(packages);+ await closeRuntimeComponentPackages(packages);throw error;}}diff --git a/packages/local/src/control.ts b/packages/local/src/control.tsindex 35dcc574..c9f87664 100644--- a/packages/local/src/control.ts+++ b/packages/local/src/control.ts@@ -4,9 +4,9 @@ import {isManagedArtifactStore,isStreamingArtifactStore,operationCancellationRequestId,- verifyRuntimeServicePackage,+ verifyRuntimeComponentPackage,} from "@narratage/runtime";-import type { RuntimeService, RuntimeServicePackage } from "@narratage/runtime";+import type { RuntimeComponent, RuntimeComponentPackage } from "@narratage/runtime";import type {CreateLocalRuntimeArchiveControlOptions,@@ -19,7 +19,7 @@ import type {ProjectLocalRuntimeArtifactAccessOptions,ProjectLocalRuntimeControlOptions,} from "./types.js";-import { selectedBuildCatalog } from "./project-services.js";+import { selectedBuildCatalog } from "./project-components.js";function assert(condition: unknown, message: string): asserts condition {if (!condition) throw new Error(message);@@ -182,29 +182,29 @@ export function createLocalRuntimeControl(};}-type OpenedProjectServices = {- readonly packages: readonly RuntimeServicePackage[];- readonly services: ReadonlyMap<string, { readonly package: RuntimeServicePackage; readonly service: RuntimeService }>;+type OpenedProjectComponents = {+ readonly packages: readonly RuntimeComponentPackage[];+ readonly components: ReadonlyMap<string, { readonly package: RuntimeComponentPackage; readonly component: RuntimeComponent }>;close(): Promise<void>;};-async function openProjectServices(+async function openProjectComponents(options: ProjectLocalRuntimeControlOptions,-): Promise<OpenedProjectServices> {- const packages = [...options.runtimeServices];- const services = new Map<string, { readonly package: RuntimeServicePackage; readonly service: RuntimeService }>();+): Promise<OpenedProjectComponents> {+ const packages = [...options.runtimeComponents];+ const components = new Map<string, { readonly package: RuntimeComponentPackage; readonly component: RuntimeComponent }>();try {for (const item of packages) {- verifyRuntimeServicePackage(item);- for (const service of item.services) {- assert(!services.has(service.instance.id), `Runtime service instance ${service.instance.id} is configured twice`);- services.set(service.instance.id, { package: item, service });+ verifyRuntimeComponentPackage(item);+ for (const component of item.components) {+ assert(!components.has(component.instance.id), `Runtime Component instance ${component.instance.id} is configured twice`);+ components.set(component.instance.id, { package: item, component });}}let closed = false;return {packages,- services,+ components,close: async () => {if (closed) return;closed = true;@@ -217,32 +217,32 @@ async function openProjectServices(}}-function selectedService<Role extends RuntimeService["role"]>(- opened: OpenedProjectServices,+function selectedComponent<Role extends RuntimeComponent["role"]>(+ opened: OpenedProjectComponents,id: string,role: Role,-): Extract<RuntimeService, { readonly role: Role }> {- const item = opened.services.get(id);- assert(item !== undefined, `Runtime service selection refers to unknown instance ${id}`);- assert(item.service.role === role, `Runtime service ${id} is ${item.service.role}, not ${role}`);- return item.service as Extract<RuntimeService, { readonly role: Role }>;+): Extract<RuntimeComponent, { readonly role: Role }> {+ const item = opened.components.get(id);+ assert(item !== undefined, `Runtime Component selection refers to unknown instance ${id}`);+ assert(item.component.role === role, `Runtime Component ${id} is ${item.component.role}, not ${role}`);+ return item.component as Extract<RuntimeComponent, { readonly role: Role }>;}/** Assemble only Build, Operation and Dispatch state selected by the Profile. */export async function createProjectLocalRuntimeArchiveControl(options: ProjectLocalRuntimeArchiveControlOptions,): Promise<LocalRuntimeArchiveControl> {- const opened = await openProjectServices(options);+ const opened = await openProjectComponents(options);try {- const build = selectedService(opened, options.runtimeSelection.stores.build, "build-store");- const operations = selectedService(opened, options.runtimeSelection.stores.operations, "operation-store");- const dispatch = selectedService(opened, options.runtimeSelection.stores.dispatch, "dispatch-store");- const catalog = selectedBuildCatalog(opened.packages, options.runtimeSelection.stores.build);+ const build = selectedComponent(opened, options.bindings.stores.build, "build-store");+ const operations = selectedComponent(opened, options.bindings.stores.operations, "operation-store");+ const dispatch = selectedComponent(opened, options.bindings.stores.dispatch, "dispatch-store");+ const catalog = selectedBuildCatalog(opened.packages, options.bindings.stores.build);return createLocalRuntimeArchiveControl({- buildStore: build.service,+ buildStore: build.port,...(catalog === undefined ? {} : { buildCatalog: catalog }),- operationStore: operations.service,- dispatchStore: dispatch.service,+ operationStore: operations.port,+ dispatchStore: dispatch.port,close: opened.close,});} catch (error) {@@ -255,10 +255,10 @@ export async function createProjectLocalRuntimeArchiveControl(export async function createProjectLocalRuntimeArtifactAccess(options: ProjectLocalRuntimeArtifactAccessOptions,): Promise<LocalRuntimeArtifactAccess> {- const opened = await openProjectServices(options);+ const opened = await openProjectComponents(options);try {- const artifacts = selectedService(opened, options.runtimeSelection.stores.artifacts, "artifact-store");- return createLocalRuntimeArtifactAccess({ artifactStore: artifacts.service, close: opened.close });+ const artifacts = selectedComponent(opened, options.bindings.stores.artifacts, "artifact-store");+ return createLocalRuntimeArtifactAccess({ artifactStore: artifacts.port, close: opened.close });} catch (error) {await opened.close();throw error;@@ -269,19 +269,19 @@ export async function createProjectLocalRuntimeArtifactAccess(export async function createProjectLocalRuntimeControl(options: ProjectLocalRuntimeControlOptions,): Promise<LocalRuntimeControl> {- const opened = await openProjectServices(options);+ const opened = await openProjectComponents(options);try {- const build = selectedService(opened, options.runtimeSelection.stores.build, "build-store");- const operations = selectedService(opened, options.runtimeSelection.stores.operations, "operation-store");- const dispatch = selectedService(opened, options.runtimeSelection.stores.dispatch, "dispatch-store");- const artifacts = selectedService(opened, options.runtimeSelection.stores.artifacts, "artifact-store");- const catalog = selectedBuildCatalog(opened.packages, options.runtimeSelection.stores.build);+ const build = selectedComponent(opened, options.bindings.stores.build, "build-store");+ const operations = selectedComponent(opened, options.bindings.stores.operations, "operation-store");+ const dispatch = selectedComponent(opened, options.bindings.stores.dispatch, "dispatch-store");+ const artifacts = selectedComponent(opened, options.bindings.stores.artifacts, "artifact-store");+ const catalog = selectedBuildCatalog(opened.packages, options.bindings.stores.build);return createLocalRuntimeControl({- buildStore: build.service,+ buildStore: build.port,...(catalog === undefined ? {} : { buildCatalog: catalog }),- operationStore: operations.service,- dispatchStore: dispatch.service,- artifactStore: artifacts.service,+ operationStore: operations.port,+ dispatchStore: dispatch.port,+ artifactStore: artifacts.port,close: opened.close,});} catch (error) {diff --git a/packages/local/src/host.ts b/packages/local/src/host.tsnew file mode 100644index 00000000..effdaf49--- /dev/null+++ b/packages/local/src/host.ts@@ -0,0 +1,163 @@+import { digestOf } from "@narratage/protocol";+import { readNodePackageLock } from "@narratage/package-loader-node";+import {+ createNodeRuntimeHostAdapterFacet,+} from "@narratage/runtime-adapter-node";+import type {+ NodeRuntimeHost,+ NodeRuntimeHostAdapterContext,+ RuntimeController,+} from "@narratage/runtime-adapter-node";++import {+ createRuntimeArchiveFromConfig,+ createRuntimeArtifactAccessFromConfig,+ createRuntimeCredentialsFromConfig,+ createRuntimeFromConfig,+ createRuntimeMaintenanceFromConfig,+ doctorRuntimeConfig,+ runtimeConfigPackageSelection,+ runtimeConfigRevision,+} from "./config.js";+import {+ bringManagedProgramsUp,+ reportManagedPrograms,+ takeManagedProgramsDown,+} from "./programs.js";+import {+ ensureRuntimeProcess,+ markRuntimeProcessReady,+ runtimeProcessLogs,+ runtimeProcessStatus,+ stopRuntimeProcess,+} from "./worker-process.js";++async function createLocalRuntimeHost(context: NodeRuntimeHostAdapterContext): Promise<NodeRuntimeHost> {+ const profile = context.profile;+ const basePackageRoot = context.packageRoot;+ const controller = async (options: {+ readonly workspaceRoot?: string;+ readonly packageLock?: string;+ readonly packageRoot?: string;+ } = {}): Promise<RuntimeController> => {+ const packageRoot = options.packageRoot ?? basePackageRoot;+ const selection = await runtimeConfigPackageSelection(profile, { packageRoot });+ const revision = async (): Promise<string> => {+ const source = options.packageLock === undefined+ ? undefined+ : (await readNodePackageLock(options.packageLock)).digest;+ return digestOf({+ format: "narratage.runtime-worker-revision@1",+ profile: await runtimeConfigRevision(profile),+ source,+ });+ };+ const launch = {+ ...context.workerLaunch,+ workerArgs: [+ ...(options.workspaceRoot === undefined ? [] : ["--workspace", options.workspaceRoot]),+ ...(options.packageLock === undefined ? [] : ["--package-lock", options.packageLock]),+ "--package-root", packageRoot,+ ],+ };+ return {+ profile,+ dataRoot: selection.dataRoot,+ revision,+ worker: {+ up: async (workerOptions) => await ensureRuntimeProcess(+ profile,+ selection.dataRoot,+ launch,+ await revision(),+ workerOptions?.maxWaitMs ?? 10_000,+ ),+ status: async () => await runtimeProcessStatus(profile, selection.dataRoot, await revision()),+ logs: async () => await runtimeProcessLogs(selection.dataRoot),+ down: async (workerOptions) => await stopRuntimeProcess(+ profile,+ selection.dataRoot,+ workerOptions?.maxWaitMs ?? 10_000,+ ),+ },+ programs: {+ up: async (programOptions) => await bringManagedProgramsUp(profile, { ...programOptions, packageRoot }),+ down: async () => await takeManagedProgramsDown(profile, { packageRoot }),+ report: async () => await reportManagedPrograms(profile, { packageRoot }),+ },+ };+ };+ return {+ profile,+ resolvePackages: async () => {+ const selection = await runtimeConfigPackageSelection(profile, { packageRoot: basePackageRoot });+ return {+ ...(selection.runtimePackageLock === undefined ? {} : { runtimePackageLock: selection.runtimePackageLock }),+ packageRoot: selection.packageRoot,+ runtimeDataRoot: selection.dataRoot,+ runtimeSelection: selection.runtimeSelection,+ };+ },+ controller,+ createRuntime: async (options) => await createRuntimeFromConfig(profile, {+ packageRoot: basePackageRoot,+ ...(options?.implementationPackages === undefined+ ? {}+ : { implementationPackages: options.implementationPackages }),+ }),+ openArchive: async (options) => await createRuntimeArchiveFromConfig(profile, {+ packageRoot: basePackageRoot,+ ...(options?.readOnly === undefined ? {} : { readOnly: options.readOnly }),+ }),+ openArtifacts: async (options) => await createRuntimeArtifactAccessFromConfig(profile, {+ packageRoot: basePackageRoot,+ ...(options?.readOnly === undefined ? {} : { readOnly: options.readOnly }),+ }),+ openMaintenance: async (options) => await createRuntimeMaintenanceFromConfig(profile, {+ packageRoot: basePackageRoot,+ ...(options?.readOnly === undefined ? {} : { readOnly: options.readOnly }),+ }),+ openCredentials: async (endpoint) => await createRuntimeCredentialsFromConfig(+ profile,+ endpoint,+ { packageRoot: basePackageRoot },+ ),+ doctor: async (options) => await doctorRuntimeConfig(profile, {+ packageRoot: basePackageRoot,+ ...(options?.capabilities === undefined ? {} : { capabilities: options.capabilities }),+ ...(options?.implementationPackages === undefined+ ? {}+ : { implementationPackages: options.implementationPackages }),+ }),+ runWorker: async (readyFile, options) => {+ const runtime = await createRuntimeFromConfig(profile, {+ packageRoot: basePackageRoot,+ ...(options?.implementationPackages === undefined+ ? {}+ : { implementationPackages: options.implementationPackages }),+ });+ const abort = new AbortController();+ const stop = (): void => abort.abort();+ process.once("SIGTERM", stop);+ process.once("SIGINT", stop);+ try {+ await markRuntimeProcessReady(readyFile);+ await runtime.work({+ owner: `worker-${process.pid}`,+ leaseMs: 30_000,+ idlePollMs: 250,+ signal: abort.signal,+ });+ } finally {+ process.removeListener("SIGTERM", stop);+ process.removeListener("SIGINT", stop);+ await runtime.close();+ }+ },+ };+}++export const localRuntimeHostAdapter = createNodeRuntimeHostAdapterFacet({+ use: "@narratage/local",+ open: createLocalRuntimeHost,+});diff --git a/packages/local/src/index.ts b/packages/local/src/index.tsindex 76220028..84a73f16 100644--- a/packages/local/src/index.ts+++ b/packages/local/src/index.ts@@ -20,20 +20,20 @@ export {createRuntimeArtifactAccessFromConfig,createRuntimeMaintenanceFromConfig,createRuntimeCredentialsFromConfig,- declaredExternalServices,+ declaredManagedPrograms,doctorRuntimeConfig,parseRuntimeConfig,runtimeConfigPackageSelection,runtimeConfigRevision,} from "./config.js";export {- bringExternalServicesUp,- reportExternalServices,- takeExternalServicesDown,-} from "./external-services.js";+ bringManagedProgramsUp,+ reportManagedPrograms,+ takeManagedProgramsDown,+} from "./programs.js";export {RuntimeAdapterRegistry,} from "@narratage/runtime-adapter";export type * from "./types.js";export type * from "./config.js";-export type * from "./external-services.js";+export type * from "./programs.js";diff --git a/packages/local/src/external-services.ts b/packages/local/src/programs.tssimilarity index 60%rename from packages/local/src/external-services.tsrename to packages/local/src/programs.tsindex 6ac364ac..ff09132c 100644--- a/packages/local/src/external-services.ts+++ b/packages/local/src/programs.ts@@ -4,12 +4,12 @@ import { join } from "node:path";import { setTimeout as sleep } from "node:timers/promises";import type { CapabilityRef } from "@narratage/protocol";-import type { RuntimeExternalService, RuntimeServiceCommand, RuntimeServiceState } from "@narratage/runtime-adapter";+import type { ManagedProgram, ManagedProgramCommand, ManagedProgramState } from "@narratage/runtime-adapter";-import { declaredExternalServices } from "./config.js";+import { declaredManagedPrograms } from "./config.js";import type { LoadRuntimeConfigOptions } from "./config.js";-export type ExternalServiceAction =+export type ManagedProgramAction =| "already-running"| "prepared"| "started"@@ -18,51 +18,51 @@ export type ExternalServiceAction =| "nothing-to-stop"| "unchanged";-export type ExternalServiceReport = {+export type ManagedProgramReport = {readonly id: string;/** Every Endpoint this program serves, so an operator sees what a restart affects. */readonly instances: readonly string[];/** What this call did. Absent when it was only asked to look. */- readonly action?: ExternalServiceAction;- readonly state: RuntimeServiceState;+ readonly action?: ManagedProgramAction;+ readonly state: ManagedProgramState;/** Why the action fell short. Never a copy of what `state` already says. */readonly detail?: string;readonly logPath?: string;readonly pid?: number;};-export type ExternalServiceProgress = {+export type ManagedProgramProgress = {readonly id: string;readonly phase: "checking" | "preparing" | "starting" | "waiting" | "ready";};-export type ExternalServiceOptions = LoadRuntimeConfigOptions & {+export type ManagedProgramOptions = LoadRuntimeConfigOptions & {/** How long to wait for a started program to answer its probe. Default 300000. */readonly maxWaitMs?: number;- /** Human-facing progress only; never changes service selection or lifecycle. */- readonly onProgress?: (event: ExternalServiceProgress) => void;+ /** Human-facing progress only; never changes program selection or lifecycle. */+ readonly onProgress?: (event: ManagedProgramProgress) => void;/** When present, operate only programs backing at least one demanded capability. */readonly capabilities?: readonly CapabilityRef[];};/** Two Endpoints may drive the same program; it is brought up once. */-function distinct(services: readonly { instance: string; service: RuntimeExternalService }[]) {- const unique = new Map<string, { service: RuntimeExternalService; instances: string[] }>();- for (const item of services) {- const found = unique.get(item.service.id);- if (found === undefined) unique.set(item.service.id, { service: item.service, instances: [item.instance] });+function distinct(programs: readonly { instance: string; program: ManagedProgram }[]) {+ const unique = new Map<string, { program: ManagedProgram; instances: string[] }>();+ for (const item of programs) {+ const found = unique.get(item.program.id);+ if (found === undefined) unique.set(item.program.id, { program: item.program, instances: [item.instance] });else found.instances.push(item.instance);}return [...unique.values()];}function directory(root: string): string {- return join(root, ".svml", "services");+ return join(root, "programs");}const LOG_ROTATE_BYTES = 10 * 1024 * 1024;-async function withServiceLifecycleLock<T>(+async function withProgramLifecycleLock<T>(root: string,id: string,timeoutMs: number,@@ -85,7 +85,7 @@ async function withServiceLifecycleLock<T>(continue;}if (Date.now() >= deadline) {- throw new Error(`External service ${id} lifecycle is busy in process ${String(owner.pid)}; lock: ${path}`);+ throw new Error(`External program ${id} lifecycle is busy in process ${String(owner.pid)}; lock: ${path}`);}await sleep(25);continue;@@ -138,7 +138,7 @@ function signal(pid: number, name: NodeJS.Signals): "sent" | "gone" | "denied" {}}-function run(root: string, command: RuntimeServiceCommand): Promise<{ ok: boolean; detail: string }> {+function run(root: string, command: ManagedProgramCommand): Promise<{ ok: boolean; detail: string }> {return new Promise((resolve) => {const child = spawn(command.command, [...command.args], { cwd: root, shell: false, stdio: ["ignore", "pipe", "pipe"] });let output = "";@@ -157,28 +157,28 @@ function run(root: string, command: RuntimeServiceCommand): Promise<{ ok: boolea* weights; `mismatch` is not, and stops the wait — a program that is answering* with another identity will not become the right one by waiting.*/-async function waitForReady(service: RuntimeExternalService, maxWaitMs: number): Promise<RuntimeServiceState> {+async function waitForReady(program: ManagedProgram, maxWaitMs: number): Promise<ManagedProgramState> {const deadline = Date.now() + maxWaitMs;- let state = await service.probe();+ let state = await program.probe();while (state.state === "down" && Date.now() < deadline) {await sleep(1000);- state = await service.probe();+ state = await program.probe();}return state;}async function bringUp(root: string,- service: RuntimeExternalService,+ program: ManagedProgram,instances: readonly string[],maxWaitMs: number,- onProgress?: (event: ExternalServiceProgress) => void,-): Promise<ExternalServiceReport> {- const base = { id: service.id, instances };- onProgress?.({ id: service.id, phase: "checking" });- const initial = await service.probe();+ onProgress?: (event: ManagedProgramProgress) => void,+): Promise<ManagedProgramReport> {+ const base = { id: program.id, instances };+ onProgress?.({ id: program.id, phase: "checking" });+ const initial = await program.probe();if (initial.state === "ready") {- onProgress?.({ id: service.id, phase: "ready" });+ onProgress?.({ id: program.id, phase: "ready" });return { ...base, action: "already-running", state: initial };}if (initial.state === "mismatch") {@@ -186,28 +186,28 @@ async function bringUp(return { ...base, action: "unchanged", state: initial };}- if (service.prepare !== undefined) {- onProgress?.({ id: service.id, phase: "preparing" });- const prepared = await run(root, service.prepare);+ if (program.prepare !== undefined) {+ onProgress?.({ id: program.id, phase: "preparing" });+ const prepared = await run(root, program.prepare);if (!prepared.ok) {- return { ...base, action: "unchanged", state: initial, detail: `${service.prepare.command} failed: ${prepared.detail}` };+ return { ...base, action: "unchanged", state: initial, detail: `${program.prepare.command} failed: ${prepared.detail}` };}}- if (service.start === undefined) {+ if (program.start === undefined) {// Nothing to keep running: preparing was the whole job, and the probe says// whether it worked.- const state = await service.probe();- if (state.state === "ready") onProgress?.({ id: service.id, phase: "ready" });+ const state = await program.probe();+ if (state.state === "ready") onProgress?.({ id: program.id, phase: "ready" });return { ...base, action: state.state === "ready" ? "prepared" : "unchanged", state };}- onProgress?.({ id: service.id, phase: "starting" });+ onProgress?.({ id: program.id, phase: "starting" });await mkdir(directory(root), { recursive: true });- const logPath = join(directory(root), `${service.id}.log`);+ const logPath = join(directory(root), `${program.id}.log`);await rotateLog(logPath);const log = await open(logPath, "a");try {- const child = spawn(service.start.command, [...service.start.args], {+ const child = spawn(program.start.command, [...program.start.args], {cwd: root,shell: false,detached: true,@@ -215,12 +215,12 @@ async function bringUp(});child.unref();if (child.pid === undefined) {- return { ...base, action: "unchanged", state: initial, detail: `${service.start.command} did not start`, logPath };+ return { ...base, action: "unchanged", state: initial, detail: `${program.start.command} did not start`, logPath };}- await writeFile(join(directory(root), `${service.id}.pid`), `${child.pid}\n`);- onProgress?.({ id: service.id, phase: "waiting" });- const state = await waitForReady(service, maxWaitMs);- if (state.state === "ready") onProgress?.({ id: service.id, phase: "ready" });+ await writeFile(join(directory(root), `${program.id}.pid`), `${child.pid}\n`);+ onProgress?.({ id: program.id, phase: "waiting" });+ const state = await waitForReady(program, maxWaitMs);+ if (state.state === "ready") onProgress?.({ id: program.id, phase: "ready" });return {...base,action: state.state === "ready" ? "started" : "unchanged",@@ -235,52 +235,52 @@ async function bringUp(}/** Prepare and start every external program the Runtime Profile implies. */-export async function bringExternalServicesUp(+export async function bringManagedProgramsUp(path: string,- options: ExternalServiceOptions = {},-): Promise<{ readonly root: string; readonly services: readonly ExternalServiceReport[] }> {- const { root, services } = await declaredExternalServices(path, options);- const reports = await Promise.all(distinct(services).map(async ({ service, instances }) =>- await withServiceLifecycleLock(root, service.id, options.maxWaitMs ?? 300_000, async () =>- await bringUp(root, service, instances, options.maxWaitMs ?? 300_000, options.onProgress))));- return { root, services: reports };+ options: ManagedProgramOptions = {},+): Promise<{ readonly dataRoot: string; readonly programs: readonly ManagedProgramReport[] }> {+ const { dataRoot, programs } = await declaredManagedPrograms(path, options);+ const reports = await Promise.all(distinct(programs).map(async ({ program, instances }) =>+ await withProgramLifecycleLock(dataRoot, program.id, options.maxWaitMs ?? 300_000, async () =>+ await bringUp(dataRoot, program, instances, options.maxWaitMs ?? 300_000, options.onProgress))));+ return { dataRoot, programs: reports };}/** Stop the programs this project started. A program it did not start is left alone. */-export async function takeExternalServicesDown(+export async function takeManagedProgramsDown(path: string,- options: ExternalServiceOptions = {},-): Promise<{ readonly root: string; readonly services: readonly ExternalServiceReport[] }> {- const { root, services } = await declaredExternalServices(path, options);- const reports = await Promise.all(distinct(services).map(async ({ service, instances }): Promise<ExternalServiceReport> =>- await withServiceLifecycleLock(root, service.id, 30_000, async () => {- const base = { id: service.id, instances };- const pid = await readPid(root, service.id);+ options: ManagedProgramOptions = {},+): Promise<{ readonly dataRoot: string; readonly programs: readonly ManagedProgramReport[] }> {+ const { dataRoot, programs } = await declaredManagedPrograms(path, options);+ const reports = await Promise.all(distinct(programs).map(async ({ program, instances }): Promise<ManagedProgramReport> =>+ await withProgramLifecycleLock(dataRoot, program.id, 30_000, async () => {+ const base = { id: program.id, instances };+ const pid = await readPid(dataRoot, program.id);if (pid === undefined || !alive(pid)) {- if (pid !== undefined) await rm(join(directory(root), `${service.id}.pid`), { force: true });- const state = await service.probe();+ if (pid !== undefined) await rm(join(directory(dataRoot), `${program.id}.pid`), { force: true });+ const state = await program.probe();return state.state === "down"? { ...base, action: "nothing-to-stop", state }// Someone else's process, or one started by hand. Killing it is not this// command's business; saying so is.- : { ...base, action: "not-ours", state, detail: `${service.id} is running but this project did not start it` };+ : { ...base, action: "not-ours", state, detail: `${program.id} is running but this project did not start it` };}const term = signal(pid, "SIGTERM");if (term === "denied") {return {...base,action: "unchanged",- state: await service.probe(),+ state: await program.probe(),pid,detail: `process ${pid} is running but this environment cannot stop it`,};}if (term === "gone") {- await rm(join(directory(root), `${service.id}.pid`), { force: true });- const state = await service.probe();+ await rm(join(directory(dataRoot), `${program.id}.pid`), { force: true });+ const state = await program.probe();return state.state === "down"? { ...base, action: "nothing-to-stop", state }- : { ...base, action: "not-ours", state, detail: `${service.id} is now served by another process` };+ : { ...base, action: "not-ours", state, detail: `${program.id} is now served by another process` };}const deadline = Date.now() + 15_000;while (alive(pid) && Date.now() < deadline) await sleep(200);@@ -288,35 +288,35 @@ export async function takeExternalServicesDown(return {...base,action: "unchanged",- state: await service.probe(),+ state: await program.probe(),pid,detail: `process ${pid} ignored SIGTERM and this environment cannot force-stop it`,};}- await rm(join(directory(root), `${service.id}.pid`), { force: true });- return { ...base, action: "stopped", state: await service.probe(), pid };+ await rm(join(directory(dataRoot), `${program.id}.pid`), { force: true });+ return { ...base, action: "stopped", state: await program.probe(), pid };})));- return { root, services: reports };+ return { dataRoot, programs: reports };}/** Probe every external program without changing anything. */-export async function reportExternalServices(+export async function reportManagedPrograms(path: string,- options: ExternalServiceOptions = {},-): Promise<{ readonly root: string; readonly services: readonly ExternalServiceReport[] }> {- const { root, services } = await declaredExternalServices(path, options);- const reports = await Promise.all(distinct(services).map(async ({ service, instances }): Promise<ExternalServiceReport> => {- const state = await service.probe();- const pid = await readPid(root, service.id);- const logPath = join(directory(root), `${service.id}.log`);+ options: ManagedProgramOptions = {},+): Promise<{ readonly dataRoot: string; readonly programs: readonly ManagedProgramReport[] }> {+ const { dataRoot, programs } = await declaredManagedPrograms(path, options);+ const reports = await Promise.all(distinct(programs).map(async ({ program, instances }): Promise<ManagedProgramReport> => {+ const state = await program.probe();+ const pid = await readPid(dataRoot, program.id);+ const logPath = join(directory(dataRoot), `${program.id}.log`);const hasLog = await stat(logPath).then(() => true).catch(() => false);return {- id: service.id,+ id: program.id,instances,state,...(pid !== undefined && alive(pid) ? { pid } : {}),...(hasLog ? { logPath } : {}),};}));- return { root, services: reports };+ return { dataRoot, programs: reports };}diff --git a/packages/local/src/project-services.ts b/packages/local/src/project-components.tssimilarity index 50%rename from packages/local/src/project-services.tsrename to packages/local/src/project-components.tsindex 173b2f1c..0bf08d97 100644--- a/packages/local/src/project-services.ts+++ b/packages/local/src/project-components.ts@@ -1,23 +1,23 @@import {- assembleRuntimeServices,- verifyRuntimeServicePackage,+ assembleRuntimeComponents,+ verifyRuntimeComponentPackage,} from "@narratage/runtime";import type {BuildCatalog,- RuntimeServiceAssembly,- RuntimeServicePackage,- RuntimeServiceSelection,+ RuntimeComponentAssembly,+ RuntimeComponentPackage,+ RuntimeBindings,} from "@narratage/runtime";import type { ProjectLocalRuntimeControlOptions } from "./types.js";-export type ProjectRuntimeServiceSelection = RuntimeServiceSelection;-export type ProjectRuntimeServiceAssembly = RuntimeServiceAssembly;+export type ProjectRuntimeBindings = RuntimeBindings;+export type ProjectRuntimeComponentAssembly = RuntimeComponentAssembly;-export type AssembledProjectRuntimeServices = {- readonly assembly: ProjectRuntimeServiceAssembly;+export type AssembledProjectRuntimeComponents = {+ readonly assembly: ProjectRuntimeComponentAssembly;readonly catalog: BuildCatalog | undefined;- readonly selection: ProjectRuntimeServiceSelection;+ readonly selection: ProjectRuntimeBindings;close(): Promise<void>;};@@ -26,11 +26,11 @@ function assert(condition: unknown, message: string): asserts condition {}export function selectedBuildCatalog(- packages: readonly RuntimeServicePackage[],+ packages: readonly RuntimeComponentPackage[],buildStore: string,): BuildCatalog | undefined {- const owner = packages.find((item) => item.services.some((service) =>- service.role === "build-store" && service.instance.id === buildStore));+ const owner = packages.find((item) => item.components.some((component) =>+ component.role === "build-store" && component.instance.id === buildStore));if (owner === undefined) return undefined;const catalog = owner.buildCatalog;if (catalog === undefined) return undefined;@@ -38,27 +38,27 @@ export function selectedBuildCatalog(&& "record" in catalog && typeof catalog.record === "function"&& "read" in catalog && typeof catalog.read === "function"&& "list" in catalog && typeof catalog.list === "function",- `Runtime service ${buildStore} exposes an invalid Build Catalog`);+ `Runtime Component ${buildStore} exposes an invalid Build Catalog`);return catalog as BuildCatalog;}/**- * Assemble only the services named by the Runtime Profile. This layer never manufactures a+ * Assemble only the Components named by the Runtime Profile. This layer never manufactures a* Scheduler, Worker, Store, path or credential source on the project's behalf.*/-export async function createProjectRuntimeServices(+export async function createProjectRuntimeComponents(_root: string,options: ProjectLocalRuntimeControlOptions,-): Promise<AssembledProjectRuntimeServices> {- const packages = [...options.runtimeServices];+): Promise<AssembledProjectRuntimeComponents> {+ const packages = [...options.runtimeComponents];try {- for (const item of packages) verifyRuntimeServicePackage(item);- const assembly = assembleRuntimeServices(packages, options.runtimeSelection);- const catalog = selectedBuildCatalog(packages, options.runtimeSelection.stores.build);+ for (const item of packages) verifyRuntimeComponentPackage(item);+ const assembly = assembleRuntimeComponents(packages, options.bindings);+ const catalog = selectedBuildCatalog(packages, options.bindings.stores.build);return {assembly,catalog,- selection: options.runtimeSelection,+ selection: options.bindings,close: () => assembly.close(),};} catch (error) {diff --git a/packages/local/src/runtime.ts b/packages/local/src/runtime.tsindex 16ab05b6..bc44b832 100644--- a/packages/local/src/runtime.ts+++ b/packages/local/src/runtime.ts@@ -29,7 +29,7 @@ import type {RuntimeProfileInstance,} from "@narratage/runtime";-import { createProjectRuntimeServices } from "./project-services.js";+import { createProjectRuntimeComponents } from "./project-components.js";import { createLocalRuntimeControl } from "./control.js";import { createLocalCredentialControl } from "./credentials.js";import type {@@ -283,14 +283,14 @@ export async function createLocalRuntime(}/**- * Node project assembly over only the Runtime service packages selected by the caller. Capability+ * Node project assembly over only the Runtime Component packages selected by the caller. Capability* Endpoints may execute locally, in a vendor API, in Lambda, or on a hosted service; none is* inferred from this local process boundary.*/export async function createProjectLocalRuntime(options: ProjectLocalRuntimeOptions,): Promise<LocalRuntime> {- const root = resolve(options.root ?? process.cwd());+ const root = resolve(options.dataRoot ?? process.cwd());const packageRoot = resolve(options.packageRoot ?? root);const lockedPackageSet = options.packageLock === undefined? undefined@@ -299,21 +299,21 @@ export async function createProjectLocalRuntime(? []: collectNodePackageComponents(lockedPackageSet.packages.map((item) => item.contribution));const configuredComponents = [...lockedComponents, ...(options.components ?? [])];- const projectServices = await createProjectRuntimeServices(root, options);- const services = projectServices.assembly;- const selection = projectServices.selection;+ const projectComponents = await createProjectRuntimeComponents(root, options);+ const components = projectComponents.assembly;+ const selection = projectComponents.selection;const endpointPackages = options.endpoints ?? [];try {verifyEndpointPackages(endpointPackages);const modules = new RuntimeModuleRegistry();registerManifests(modules, [- ...services.manifests,+ ...components.manifests,...endpointPackages.map((item) => item.manifest),]);const profile = sealRuntimeProfile({instances: [- ...services.instances,+ ...components.instances,...endpointPackages.map((item) => item.instance),],scheduler: selection.scheduler,@@ -336,14 +336,14 @@ export async function createProjectLocalRuntime(});const closure = resolveRuntimeProfile(modules, profile);const runtime = await createLocalRuntime({- buildStore: services.buildStore,- ...(projectServices.catalog === undefined ? {} : { buildCatalog: projectServices.catalog }),- operationStore: services.operationStore,- dispatchStore: services.dispatchStore,- artifactStore: services.artifactStore,- credentialStore: services.credentialStore,- scheduler: services.scheduler,- worker: services.worker,+ buildStore: components.buildStore,+ ...(projectComponents.catalog === undefined ? {} : { buildCatalog: projectComponents.catalog }),+ operationStore: components.operationStore,+ dispatchStore: components.dispatchStore,+ artifactStore: components.artifactStore,+ credentialStore: components.credentialStore,+ scheduler: components.scheduler,+ worker: components.worker,...(configuredComponents.length === 0? {}: { components: configuredComponents }),@@ -370,11 +370,11 @@ export async function createProjectLocalRuntime(openArtifact: runtime.openArtifact,garbageCollectArtifacts: runtime.garbageCollectArtifacts,close() {- return projectServices.close();+ return projectComponents.close();},};} catch (error) {- await projectServices.close();+ await projectComponents.close();throw error;}}diff --git a/packages/local/src/scheduler-package.ts b/packages/local/src/scheduler-package.tsindex 5a96a3bb..e49fb66c 100644--- a/packages/local/src/scheduler-package.ts+++ b/packages/local/src/scheduler-package.ts@@ -1,9 +1,9 @@import { digestOf } from "@narratage/protocol";import {LocalBuildScheduler,- defineRuntimeServicePackage,+ defineRuntimeComponentPackage,} from "@narratage/runtime";-import type { RuntimeServicePackage } from "@narratage/runtime";+import type { RuntimeComponentPackage } from "@narratage/runtime";import { durableLocalWorkerFactory } from "./worker.js";@@ -17,10 +17,10 @@ const localWorkerImplementationDigest = digestOf("@narratage/local/worker@1/blocexport function createLocalExecutionPackage(instance: string,-): RuntimeServicePackage {- return defineRuntimeServicePackage({+): RuntimeComponentPackage {+ return defineRuntimeComponentPackage({module: localRuntimeModuleRef,- services: [+ components: [{role: "scheduler",facet: "scheduler",@@ -29,7 +29,7 @@ export function createLocalExecutionPackage(digest: localSchedulerImplementationDigest,},configuration: { algorithm: "atomic-resources", version: 1 },- service: {+ port: {create(executor, options) {return new LocalBuildScheduler(executor, options);},@@ -43,7 +43,7 @@ export function createLocalExecutionPackage(digest: localWorkerImplementationDigest,},configuration: { dispatch: "leased", capacity: "shared", version: 1 },- service: durableLocalWorkerFactory,+ port: durableLocalWorkerFactory,},],});diff --git a/packages/local/src/types.ts b/packages/local/src/types.tsindex e5a71113..37119464 100644--- a/packages/local/src/types.ts+++ b/packages/local/src/types.ts@@ -18,8 +18,8 @@ import type {OperationStore,OperationSnapshot,RuntimeModuleRegistry,- RuntimeServicePackage,- RuntimeServiceSelection,+ RuntimeComponentPackage,+ RuntimeBindings,RuntimeWorkerFactory,} from "@narratage/runtime";import type { TypeValidatorRegistrar, TypeValidatorRegistryLike } from "@narratage/validation";@@ -29,7 +29,7 @@ export type { ComponentPackage } from "@narratage/component-kit";export type LocalTypeValidatorRegistry = TypeValidatorRegistryLike & TypeValidatorRegistrar;export type { EndpointPackage } from "@narratage/endpoint-kit";-export type { RuntimeServicePackage } from "@narratage/runtime";+export type { RuntimeComponentPackage } from "@narratage/runtime";export type LocalRuntimeClosureOptions = {readonly modules: RuntimeModuleRegistry;@@ -58,13 +58,13 @@ export type CreateLocalRuntimeArchiveControlOptions = {readonly buildCatalog?: BuildCatalog;readonly operationStore: OperationStore;readonly dispatchStore: BuildDispatchStore;- /** Optional owner supplied by the project service assembly. */+ /** Optional owner supplied by the project Component assembly. */readonly close?: () => Awaitable<void>;};export type CreateLocalRuntimeArtifactAccessOptions = {readonly artifactStore: ArtifactStore;- /** Optional owner supplied by the project service assembly. */+ /** Optional owner supplied by the project Component assembly. */readonly close?: () => Awaitable<void>;};@@ -78,9 +78,9 @@ export type CreateLocalCredentialControlOptions = {};export type ProjectLocalRuntimeOptions = {- /** Project directory containing the private .svml Runtime directory. Defaults to cwd. */- readonly root?: string;- /** Host directory whose node_modules contains the packages named by packageLock. Defaults to root. */+ /** Runtime data boundary. It does not grant access to author source. */+ readonly dataRoot?: string;+ /** Host directory whose node_modules contains the packages named by packageLock. Defaults to dataRoot. */readonly packageRoot?: string;/** Trusted implementation package inventory. Each compilation activates its exact Source subset. */readonly packageLock?: string;@@ -89,9 +89,9 @@ export type ProjectLocalRuntimeOptions = {* every selected role is explicit, and two packages exposing the same instance* id are a configuration error rather than a choice made here.*/- readonly runtimeServices: readonly RuntimeServicePackage[];- /** Exact service instances selected from runtimeServices; no role is inferred by uniqueness. */- readonly runtimeSelection: RuntimeServiceSelection;+ readonly runtimeComponents: readonly RuntimeComponentPackage[];+ /** Exact Component instances selected by role; no role is inferred by uniqueness. */+ readonly bindings: RuntimeBindings;readonly components?: readonly ComponentPackage[];readonly endpoints?: readonly EndpointPackage[];readonly scheduling: {@@ -102,9 +102,9 @@ export type ProjectLocalRuntimeOptions = {};export type ProjectLocalRuntimeArchiveControlOptions = Pick<ProjectLocalRuntimeOptions,- | "root"- | "runtimeServices"- | "runtimeSelection"+ | "dataRoot"+ | "runtimeComponents"+ | "bindings">;export type ProjectLocalRuntimeArtifactAccessOptions = ProjectLocalRuntimeArchiveControlOptions;diff --git a/packages/cli/src/runtime-process.ts b/packages/local/src/worker-process.tssimilarity index 82%rename from packages/cli/src/runtime-process.tsrename to packages/local/src/worker-process.tsindex 21e0c051..00fc3c71 100644--- a/packages/cli/src/runtime-process.ts+++ b/packages/local/src/worker-process.ts@@ -1,4 +1,3 @@-import { createHash } from "node:crypto";import { spawn } from "node:child_process";import { mkdir, open, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";import { dirname, join, resolve } from "node:path";@@ -6,6 +5,7 @@ import { dirname, join, resolve } from "node:path";export type RuntimeWorkerLaunch = {readonly command: string;readonly args: readonly string[];+ readonly workerArgs?: readonly string[];};export type RuntimeProcessState = {@@ -29,12 +29,8 @@ type ProcessRecord = {const LOG_TAIL_BYTES = 1024 * 1024;const LOG_ROTATE_BYTES = 10 * 1024 * 1024;-function paths(profile: string) {- const absolute = resolve(profile);- const id = createHash("sha256").update(absolute).digest("hex").slice(0, 16);- // `.svml/runtime` is the project-local active Profile pointer. Worker process- // state is independent and must never compete with that file for the same path.- const root = join(dirname(absolute), ".svml", "workers", id);+function paths(dataRoot: string) {+ const root = join(resolve(dataRoot), "worker");return {root,pid: join(root, "worker.json"),@@ -66,8 +62,8 @@ function alive(pid: number): boolean {}}-async function withLifecycleLock<T>(profile: string, timeoutMs: number, run: () => Promise<T>): Promise<T> {- const location = paths(profile);+async function withLifecycleLock<T>(dataRoot: string, timeoutMs: number, run: () => Promise<T>): Promise<T> {+ const location = paths(dataRoot);await mkdir(location.root, { recursive: true });const deadline = Date.now() + timeoutMs;while (true) {@@ -107,8 +103,8 @@ async function rotateLog(path: string): Promise<void> {await rename(path, previous);}-async function record(profile: string): Promise<ProcessRecord | undefined> {- const path = paths(profile).pid;+async function record(profile: string, dataRoot: string): Promise<ProcessRecord | undefined> {+ const path = paths(dataRoot).pid;try {const value = JSON.parse(await readFile(path, "utf8")) as ProcessRecord;if (value.format !== "narratage.runtime-process@1" || value.profile !== resolve(profile)@@ -123,10 +119,11 @@ async function record(profile: string): Promise<ProcessRecord | undefined> {export async function runtimeProcessStatus(profile: string,+ dataRoot: string,currentProfileDigest: string,): Promise<RuntimeProcessState> {- const location = paths(profile);- const current = await record(profile);+ const location = paths(dataRoot);+ const current = await record(profile, dataRoot);if (current === undefined || !alive(current.pid)) {return { state: "stopped", profile: resolve(profile), logPath: location.log };}@@ -154,13 +151,14 @@ export async function runtimeProcessStatus(async function waitForReady(profile: string,+ dataRoot: string,profileDigest: string,timeoutMs: number,): Promise<RuntimeProcessState> {- const location = paths(profile);+ const location = paths(dataRoot);const deadline = Date.now() + timeoutMs;while (Date.now() <= deadline) {- const state = await runtimeProcessStatus(profile, profileDigest);+ const state = await runtimeProcessStatus(profile, dataRoot, profileDigest);if (state.state === "stopped") {const log = await readFile(location.log, "utf8").catch(() => "");throw new Error(`Runtime Worker exited before becoming ready${log.length === 0 ? "" : `: ${log.trim().split("\n").at(-1)}`}`);@@ -173,16 +171,17 @@ async function waitForReady(export async function ensureRuntimeProcess(profile: string,+ dataRoot: string,launch: RuntimeWorkerLaunch,profileDigest: string,timeoutMs = 10_000,): Promise<RuntimeProcessState> {- return await withLifecycleLock(profile, timeoutMs, async () => {- const current = await runtimeProcessStatus(profile, profileDigest);+ return await withLifecycleLock(dataRoot, timeoutMs, async () => {+ const current = await runtimeProcessStatus(profile, dataRoot, profileDigest);if (current.state === "running") return current;- if (current.state === "stale") await stopRuntimeProcessUnlocked(profile, timeoutMs);+ if (current.state === "stale") await stopRuntimeProcessUnlocked(profile, dataRoot, timeoutMs);const absolute = resolve(profile);- const location = paths(absolute);+ const location = paths(dataRoot);await mkdir(location.root, { recursive: true });await unlink(location.ready).catch(() => undefined);await rotateLog(location.log);@@ -193,6 +192,7 @@ export async function ensureRuntimeProcess(absolute,"--ready-file",location.ready,+ ...(launch.workerArgs ?? []),], {cwd: process.cwd(),detached: true,@@ -210,13 +210,13 @@ export async function ensureRuntimeProcess(} satisfies ProcessRecord), "utf8");child.unref();await log.close();- return await waitForReady(absolute, profileDigest, timeoutMs);+ return await waitForReady(absolute, dataRoot, profileDigest, timeoutMs);});}-async function stopRuntimeProcessUnlocked(profile: string, timeoutMs: number): Promise<RuntimeProcessState> {- const current = await record(profile);- const location = paths(profile);+async function stopRuntimeProcessUnlocked(profile: string, dataRoot: string, timeoutMs: number): Promise<RuntimeProcessState> {+ const current = await record(profile, dataRoot);+ const location = paths(dataRoot);if (current === undefined || !alive(current.pid)) {await unlink(location.pid).catch(() => undefined);await unlink(location.ready).catch(() => undefined);@@ -242,12 +242,13 @@ async function stopRuntimeProcessUnlocked(profile: string, timeoutMs: number): Preturn { state: "stopped", profile: resolve(profile), logPath: location.log };}-export async function stopRuntimeProcess(profile: string, timeoutMs = 10_000): Promise<RuntimeProcessState> {- return await withLifecycleLock(profile, timeoutMs, async () => await stopRuntimeProcessUnlocked(profile, timeoutMs));+export async function stopRuntimeProcess(profile: string, dataRoot: string, timeoutMs = 10_000): Promise<RuntimeProcessState> {+ return await withLifecycleLock(dataRoot, timeoutMs, async () =>+ await stopRuntimeProcessUnlocked(profile, dataRoot, timeoutMs));}-export async function runtimeProcessLogs(profile: string): Promise<{ readonly path: string; readonly text: string }> {- const path = paths(profile).log;+export async function runtimeProcessLogs(dataRoot: string): Promise<{ readonly path: string; readonly text: string }> {+ const path = paths(dataRoot).log;let file;try {file = await open(path, "r");diff --git a/packages/local/test/config.test.ts b/packages/local/test/config.test.tsindex 615f8a35..ffb25312 100644--- a/packages/local/test/config.test.ts+++ b/packages/local/test/config.test.ts@@ -1,22 +1,16 @@import assert from "node:assert/strict";-import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import { mkdtemp, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import test from "node:test";+import { digestOf } from "@narratage/protocol";import {- defineEndpointPackage,-} from "@narratage/endpoint-kit";-import {+ createRuntimeComponentAdapterFacet,createRuntimeEndpointAdapterFacet,- createRuntimeServiceAdapterFacet,} from "@narratage/runtime-adapter";-import { digestOf } from "@narratage/protocol";-import { credentialRef, defineRuntimeServicePackage } from "@narratage/runtime";-import { createSqliteRuntimeServicePackage } from "@narratage/store-sqlite";-+import { createSqliteRuntimeComponentPackage } from "@narratage/store-sqlite";import {- createRuntimeFromConfig,createRuntimeArchiveFromConfig,createRuntimeArtifactAccessFromConfig,doctorRuntimeConfig,@@ -25,51 +19,113 @@ import {RuntimeAdapterRegistry,} from "@narratage/local";-const services = {+const bindings = {scheduler: "execution.scheduler",worker: "execution.worker",stores: {build: "state.builds",operations: "state.operations",dispatch: "state.dispatch",- artifacts: "artifacts",- credentials: ["credentials"],+ artifacts: "artifacts.store",+ credentials: [] as string[],},};-const required = { runtimeServices: [], services, scheduling: { maxConcurrency: 3 } } as const;--test("archive observation does not construct the selected ArtifactStore adapter", async () => {- const root = await mkdtemp(join(tmpdir(), "svml-runtime-archive-slice-"));- const path = join(root, "svml.runtime.json");- await writeFile(path, JSON.stringify({- format: "svml.runtime-config@1",- runtimeServices: [- { use: "example.state", instance: "state", config: {} },- { use: "example.artifacts", instance: "artifacts", config: {} },- ],- services: {- scheduler: "execution.scheduler",- worker: "execution.worker",- stores: {- build: "state.builds",- operations: "state.operations",- dispatch: "state.dispatch",- artifacts: "artifacts.store",- credentials: [],+function profile(config: {+ readonly dataRoot?: string;+ readonly components?: Readonly<Record<string, unknown>>;+ readonly endpoints?: Readonly<Record<string, unknown>>;+ readonly selectedBindings?: typeof bindings;+ readonly runtimePackageLock?: string;+} = {}) {+ return {+ format: "narratage.runtime-profile@1",+ ...(config.runtimePackageLock === undefined ? {} : { runtimePackageLock: config.runtimePackageLock }),+ runtime: {+ use: "@narratage/local",+ config: {+ dataRoot: config.dataRoot ?? ".narratage/runtimes/local",+ components: config.components ?? {},+ bindings: config.selectedBindings ?? bindings,+ endpoints: config.endpoints ?? {},+ limits: { maxOperations: 3 },},},- scheduling: { maxConcurrency: 1 },- endpoints: [],+ };+}++test("Runtime Profile keeps deployment data separate from source and derives instance names from maps", () => {+ const parsed = parseRuntimeConfig(profile({+ components: { state: { use: "example.state", config: { path: "state.sqlite" } } },+ endpoints: { generation: { use: "example.provider", authority: "shared" } },}));+ assert.equal(parsed.dataRoot, ".narratage/runtimes/local");+ assert.deepEqual(parsed.components, [{+ use: "example.state",+ instance: "state",+ config: { path: "state.sqlite" },+ }]);+ assert.deepEqual(parsed.endpoints, [{+ use: "example.provider",+ instance: "generation",+ authority: "shared",+ }]);+ assert.deepEqual(parsed.bindings, bindings);+ assert.equal("root" in parsed, false);+ assert.equal("packageLock" in parsed, false);+});++test("Runtime Profile rejects source ownership fields", () => {+ assert.throws(() => parseRuntimeConfig({ ...profile(), packageLock: "./svml.packages.lock" }),+ /does not accept packageLock/u);+ assert.throws(() => parseRuntimeConfig({ ...profile(), root: "." }),+ /does not accept root/u);+});++test("Runtime revision follows Profile content and its Runtime lock only", async () => {+ const root = await mkdtemp(join(tmpdir(), "narratage-runtime-revision-"));+ const profilePath = join(root, "deployment.profile");+ const lockPath = join(root, "runtime.lock");+ const lock = (label: string) => {+ const content = {+ format: "svml.node-package-lock@1" as const,+ selected: [],+ artifacts: [{ name: `example-${label}`, version: "1", digest: digestOf(label) }],+ packages: [],+ };+ return JSON.stringify({ ...content, digest: digestOf(content) });+ };+ try {+ await writeFile(lockPath, lock("one"), "utf8");+ await writeFile(profilePath, JSON.stringify(profile({ runtimePackageLock: "./runtime.lock" })), "utf8");+ const first = await runtimeConfigRevision(profilePath);+ await writeFile(profilePath, JSON.stringify(profile({ runtimePackageLock: "./runtime.lock" }), null, 2), "utf8");+ assert.equal(await runtimeConfigRevision(profilePath), first);+ await writeFile(lockPath, lock("two"), "utf8");+ assert.notEqual(await runtimeConfigRevision(profilePath), first);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++test("archive observation constructs only the Components bound to archive roles", async () => {+ const root = await mkdtemp(join(tmpdir(), "narratage-runtime-slice-"));+ const path = join(root, "svml.runtime.json");+ await writeFile(path, JSON.stringify(profile({+ dataRoot: ".",+ components: {+ state: { use: "example.state" },+ artifacts: { use: "example.artifacts" },+ },+ })));let artifactConstructions = 0;const registry = new RuntimeAdapterRegistry();- registry.registerFacet(createRuntimeServiceAdapterFacet({+ registry.registerFacet(createRuntimeComponentAdapterFacet({use: "example.state",validate() {},create(context) {- return createSqliteRuntimeServicePackage({- path: join(context.root, "runtime.sqlite"),+ return createSqliteRuntimeComponentPackage({+ path: join(context.dataRoot, "state.sqlite"),buildInstance: `${context.instance}.builds`,operationInstance: `${context.instance}.operations`,dispatchInstance: `${context.instance}.dispatch`,@@ -77,7 +133,7 @@ test("archive observation does not construct the selected ArtifactStore adapter"});},}));- registry.registerFacet(createRuntimeServiceAdapterFacet({+ registry.registerFacet(createRuntimeComponentAdapterFacet({use: "example.artifacts",validate() {},create() {@@ -92,376 +148,40 @@ test("archive observation does not construct the selected ArtifactStore adapter"assert.equal(artifactConstructions, 0);await assert.rejects(createRuntimeArtifactAccessFromConfig(path, { registry, readOnly: true }),/artifact adapter constructed/u);- assert.equal(artifactConstructions, 1);- } finally {- await rm(root, { recursive: true, force: true });- }-});--test("Runtime revision follows content and referenced locks, not a filename suffix", async () => {- const root = await mkdtemp(join(tmpdir(), "svml-runtime-revision-"));- const path = join(root, "deployment.profile");- const lock = (label: string) => {- const content = {- format: "svml.node-package-lock@1" as const,- selected: [],- artifacts: [{ name: `example-${label}`, version: "1", digest: digestOf(label) }],- packages: [],- };- return JSON.stringify({ ...content, digest: digestOf(content) });- };- try {- await writeFile(join(root, "author.lock"), lock("author-v1"), "utf8");- await writeFile(join(root, "runtime.lock"), lock("runtime-v1"), "utf8");- const profile = {- format: "svml.runtime-config@1",- root: ".",- packageLock: "./author.lock",- runtimePackageLock: "./runtime.lock",- endpoints: [],- ...required,- } as const;- await writeFile(path, JSON.stringify(profile), "utf8");- const first = await runtimeConfigRevision(path);- await writeFile(path, JSON.stringify(profile, null, 2), "utf8");- assert.equal(await runtimeConfigRevision(path), first);- await writeFile(join(root, "runtime.lock"), lock("runtime-v2"), "utf8");- const second = await runtimeConfigRevision(path);- assert.notEqual(second, first);} finally {await rm(root, { recursive: true, force: true });}});-function endpointPackage(instance: string, credentials: readonly unknown[] = []) {- return {- name: instance,- manifest: { facets: [] },- instance: { id: instance },- bindings: [],- credentials,- install() {},- } as never;-}--test("declarative Runtime config has no implicit local services", () => {- assert.throws(() => parseRuntimeConfig({- format: "svml.runtime-config@1",- endpoints: [],- }), /runtimeServices/u);-});--test("an explicit empty Runtime service set fails instead of manufacturing local defaults", async () => {- const root = await mkdtemp(join(tmpdir(), "svml-runtime-empty-services-"));- const path = join(root, "svml.runtime.json");- try {- await writeFile(path, JSON.stringify({- format: "svml.runtime-config@1",- ...required,- endpoints: [],- }));- await assert.rejects(- async () => await createRuntimeFromConfig(path, { registry: new RuntimeAdapterRegistry() }),- /unknown instance execution\.scheduler/u,- );- } finally {- await rm(root, { recursive: true, force: true });- }-});--test("Runtime config is closed data and rejects unknown environment authority", () => {- const parsed = parseRuntimeConfig({- format: "svml.runtime-config@1",- ...required,- packageRoot: "/opt/narratage",- endpoints: [],- });- assert.equal(parsed.packageRoot, "/opt/narratage");- assert.throws(() => parseRuntimeConfig({- format: "svml.runtime-config@1",- ...required,- endpoints: [],- apiKey: "must-not-live-here",- }), /does not accept apiKey/u);-});--test("Endpoint authority is optional and remains explicit only when shared", () => {- const local = parseRuntimeConfig({- format: "svml.runtime-config@1",- ...required,- endpoints: [{ use: "example.local", instance: "local", config: {} }],- });- assert.equal(local.endpoints[0]?.authority, undefined);- const shared = parseRuntimeConfig({- format: "svml.runtime-config@1",- ...required,- endpoints: [{ use: "example.remote", instance: "one", authority: "shared-account", config: {} }],- });- assert.equal(shared.endpoints[0]?.authority, "shared-account");-});--test("declarative adapters are explicit and never guessed", async () => {- const root = await mkdtemp(join(tmpdir(), "svml-runtime-adapter-"));+test("doctor reports a down Managed Program without inventing a Runtime default", async () => {+ const root = await mkdtemp(join(tmpdir(), "narratage-runtime-program-"));const path = join(root, "svml.runtime.json");- await writeFile(path, JSON.stringify({- format: "svml.runtime-config@1",- ...required,- endpoints: [{ use: "example.missing", instance: "missing", authority: "example.missing", config: {} }],- }));- await assert.rejects(- async () => await createRuntimeFromConfig(path, { registry: new RuntimeAdapterRegistry() }),- /adapter example\.missing is not registered/u,- );-});--test("runtimeServices names the Runtime's own replaceable parts, apart from external services", async () => {- const root = await mkdtemp(join(tmpdir(), "svml-runtime-config-"));- const path = join(root, "svml.runtime.json");- await writeFile(path, JSON.stringify({- format: "svml.runtime-config@1",- ...required,- runtimeServices: [{ use: "@example/store", instance: "artifacts.example" }],- endpoints: [],- }));- const document = parseRuntimeConfig(JSON.parse(await readFile(path, "utf8")));- assert.deepEqual(document.runtimeServices, [{ use: "@example/store", instance: "artifacts.example" }]);-- assert.deepEqual(document.services, services);- await rm(root, { recursive: true, force: true });-});--test("doctor names the external program a Provider needs, and the command that supplies it", async () => {- const root = await mkdtemp(join(tmpdir(), "svml-external-service-"));- const path = join(root, "svml.runtime.json");- await writeFile(path, JSON.stringify({- format: "svml.runtime-config@1",- ...required,- endpoints: [- { use: "example.absent", instance: "absent", authority: "example.account", config: {} },- { use: "example.wrong", instance: "wrong", authority: "example.account", config: {} },- { use: "example.exploding", instance: "exploding", authority: "example.account", config: {} },- ],- }));-- const registry = new RuntimeAdapterRegistry();- const declare = (use: string, service: unknown) =>- registry.registerFacet(createRuntimeEndpointAdapterFacet({- use,- activate: (context) => ({ endpoint: endpointPackage(context.instance), externalService: service as never }),- }));- declare("example.absent", {- id: "absent-one",- start: { command: "uv", args: ["run", "serve"] },- probe: async () => ({ state: "down", detail: "nothing is answering at http://127.0.0.1:1" }),- });- declare("example.wrong", {- id: "wrong-one",- probe: async () => ({ state: "mismatch", detail: "model is large-v3, expected small" }),- });- declare("example.exploding", {- id: "exploding-one",- probe: async () => { throw new Error("the probe itself is broken"); },- });-- const { diagnostics } = await doctorRuntimeConfig(path, { registry });- const seen = diagnostics.map((item) => `${item.code}: ${item.message}`);-- assert.deepEqual(seen, [- "EXTERNAL_SERVICE_DOWN: absent-one is not usable: nothing is answering at http://127.0.0.1:1."- + " Bring it up with: narratage services up",- // Nothing to prepare and nothing to start: report the difference, name no command.- "EXTERNAL_SERVICE_MISMATCH: wrong-one is running but differs from this Runtime Profile:"- + " model is large-v3, expected small",- // A broken probe is a broken Provider, never a silently healthy service.- "EXTERNAL_SERVICE_PROBE_FAILED: the probe itself is broken",- ]);- await rm(root, { recursive: true, force: true });-});--test("doctor activates one pure Endpoint declaration without constructing Runtime services", async () => {- const root = await mkdtemp(join(tmpdir(), "svml-read-only-doctor-"));- const path = join(root, "svml.runtime.json");- await writeFile(path, JSON.stringify({- format: "svml.runtime-config@1",- ...required,- runtimeServices: [{ use: "example.store", instance: "store", config: { mode: "valid" } }],- endpoints: [- { use: "example.invalid", instance: "invalid", authority: "example.account", config: { mode: "bad" } },- { use: "example.missing-credential", instance: "missing-credential", authority: "example.account", config: {} },- ],- }));-- let constructed = 0;- let invalidDoctorCalls = 0;- let serviceDeclarations = 0;- const registry = new RuntimeAdapterRegistry();- registry.registerFacet(createRuntimeServiceAdapterFacet({- use: "example.store",- validate(context) {- assert.deepEqual(context.config, { mode: "valid" });- },- create() {- constructed += 1;- throw new Error("doctor constructed the Runtime service");- },- doctor: () => [{ severity: "info", code: "STORE_OK", message: "store config is valid" }],- }));- registry.registerFacet(createRuntimeEndpointAdapterFacet({- use: "example.invalid",- activate() {- throw new Error("mode is invalid");- },- }));- registry.registerFacet(createRuntimeEndpointAdapterFacet({- use: "example.missing-credential",- activate(context) {- serviceDeclarations += 1;- return {- endpoint: endpointPackage(context.instance),- diagnose: () => {- invalidDoctorCalls += 1;- return [{- severity: "error" as const,- code: "RUNTIME_CREDENTIAL_MISSING",- message: "one declared credential is absent",- }];- },- externalService: { id: "should-not-be-probed", probe: async () => ({ state: "ready" as const }) },- };- },- }));-- const { diagnostics } = await doctorRuntimeConfig(path, { registry });- assert.deepEqual(diagnostics.map(({ severity, code, message, subject }) => ({- severity, code, message, ...(subject === undefined ? {} : { subject }),- })), [- { severity: "info", code: "STORE_OK", message: "store config is valid" },- { severity: "error", code: "RUNTIME_ENDPOINT_CONFIG_INVALID", message: "mode is invalid", subject: "invalid" },- { severity: "error", code: "RUNTIME_CREDENTIAL_MISSING", message: "one declared credential is absent" },- ]);- assert.equal(constructed, 0);- assert.equal(invalidDoctorCalls, 1);- assert.equal(serviceDeclarations, 1);- await rm(root, { recursive: true, force: true });-});--test("doctor resolves credentials from the same Endpoint declaration used by execution", async () => {- const root = await mkdtemp(join(tmpdir(), "svml-credential-doctor-"));- const path = join(root, "svml.runtime.json");- await writeFile(path, JSON.stringify({- format: "svml.runtime-config@1",- ...required,- runtimeServices: [{ use: "example.credentials", instance: "credentials", config: {} }],- endpoints: [{ use: "example.provider", instance: "provider", authority: "example.account", config: {} }],- }));-- let endpointActivations = 0;- let credentialStoreConstructions = 0;- let credentialStoreCloses = 0;+ await writeFile(path, JSON.stringify(profile({+ dataRoot: ".",+ endpoints: { speech: { use: "example.speech" } },+ })));const registry = new RuntimeAdapterRegistry();- registry.registerFacet(createRuntimeEndpointAdapterFacet({- use: "example.provider",- activate(context) {- endpointActivations += 1;- return { endpoint: endpointPackage(context.instance, [{- endpoint: context.instance,- slot: "token",- label: "Example token",- kind: "secret",- ref: credentialRef("env", "EXAMPLE_TOKEN_THAT_IS_NOT_SET"),- }]) };- },- }));- registry.registerFacet(createRuntimeServiceAdapterFacet({- use: "example.credentials",- validate() {},- create(context) {- credentialStoreConstructions += 1;- return defineRuntimeServicePackage({- module: { name: "example.credentials", version: "1" },- services: [{- role: "credential-store",- facet: "credentials",- instance: context.instance,- implementation: { digest: digestOf("example.credentials@1") },- service: { async resolve() { return undefined; } },- }],- close() { credentialStoreCloses += 1; },- });- },- }));-- const { diagnostics } = await doctorRuntimeConfig(path, { registry });- assert.deepEqual(diagnostics.map(({ code, message, subject }) => ({ code, message, subject })), [{- code: "RUNTIME_CREDENTIAL_MISSING",- message: "Example token for Endpoint provider is not configured in CredentialStore env. "- + "Set EXAMPLE_TOKEN_THAT_IS_NOT_SET in this process environment, or select a writable CredentialStore in the Runtime Profile.",- subject: "provider.token",- }]);- assert.equal(endpointActivations, 1);- assert.equal(credentialStoreConstructions, 1);- assert.equal(credentialStoreCloses, 1);- await rm(root, { recursive: true, force: true });-});--test("plan-scoped doctor ignores unrelated Endpoints and diagnoses only demanded capabilities", async () => {- const root = await mkdtemp(join(tmpdir(), "svml-scoped-doctor-"));- const path = join(root, "svml.runtime.json");- await writeFile(path, JSON.stringify({- format: "svml.runtime-config@1",- ...required,- runtimeServices: [{ use: "example.credentials", instance: "credentials", config: {} }],- endpoints: [- { use: "example.image", instance: "image", authority: "image.account", config: {} },- { use: "example.speech", instance: "speech", authority: "speech.account", config: {} },- ],- }));- const imageCapability = { module: { name: "example.image", version: "1" }, name: "generate" } as const;- const speechCapability = { module: { name: "example.speech", version: "1" }, name: "align" } as const;- const resultType = { module: { name: "example.result", version: "1" }, name: "Value" } as const;- const registry = new RuntimeAdapterRegistry();- const endpoint = (instance: string, capability: typeof imageCapability | typeof speechCapability, credential?: string) =>- defineEndpointPackage({- module: { name: `example.${instance}-endpoint`, version: "1" },- facet: "endpoint",- instance,- authority: `${instance}.account`,- implementation: { digest: digestOf(`example.${instance}@1`) },- capabilities: [{ lifecycle: "immediate" as const, capability, returns: resultType, handler: async () => ({}) as never }],- ...(credential === undefined ? {} : {- credentials: { token: credentialRef("env", credential) },- credentialInputs: { token: { label: `${instance} token` } },- }),- });- registry.registerFacet(createRuntimeEndpointAdapterFacet({- use: "example.image",- activate: () => ({ endpoint: endpoint("image", imageCapability) }),- }));registry.registerFacet(createRuntimeEndpointAdapterFacet({use: "example.speech",- activate: () => ({- endpoint: endpoint("speech", speechCapability, "EXAMPLE_UNUSED_SPEECH_TOKEN"),- externalService: { id: "speech-service", probe: async () => ({ state: "down" as const, detail: "not running" }) },+ activate: (context) => ({+ endpoint: {+ name: context.instance,+ manifest: { facets: [] },+ instance: { id: context.instance },+ bindings: [],+ credentials: [],+ install() {},+ } as never,+ program: {+ id: "speech.local",+ probe: async () => ({ state: "down", detail: "not running" }),+ },}),}));- registry.registerFacet(createRuntimeServiceAdapterFacet({- use: "example.credentials",- validate() {},- create(context) {- return defineRuntimeServicePackage({- module: { name: "example.credentials", version: "1" },- services: [{- role: "credential-store",- facet: "credentials",- instance: context.instance,- implementation: { digest: digestOf("example.credentials@1") },- service: { async resolve() { return undefined; } },- }],- });- },- }));-- const { diagnostics } = await doctorRuntimeConfig(path, { registry, capabilities: [imageCapability] });- assert.deepEqual(diagnostics, []);- await rm(root, { recursive: true, force: true });+ try {+ const result = await doctorRuntimeConfig(path, { registry });+ assert.equal(result.diagnostics.some((item) => item.code === "MANAGED_PROGRAM_DOWN"), true);+ } finally {+ await rm(root, { recursive: true, force: true });+ }});diff --git a/packages/local/test/local.test.ts b/packages/local/test/local.test.tsindex 497ea7e2..13b41b50 100644--- a/packages/local/test/local.test.ts+++ b/packages/local/test/local.test.ts@@ -25,10 +25,10 @@ import {createNodePackageLock,writeNodePackageLock,} from "@narratage/package-loader-node";-import { LocalBuildScheduler, credentialRef, defineRuntimeServicePackage } from "@narratage/runtime";+import { LocalBuildScheduler, credentialRef, defineRuntimeComponentPackage } from "@narratage/runtime";import type { CredentialValue, WritableCredentialStore } from "@narratage/runtime";import type { RuntimeModuleManifest } from "@narratage/runtime";-import { createSqliteRuntimeServicePackage } from "@narratage/store-sqlite";+import { createSqliteRuntimeComponentPackage } from "@narratage/store-sqlite";import {capabilities,@@ -58,20 +58,20 @@ const providerManifest: RuntimeModuleManifest = {function projectRuntimeFixture(directory: string) {const execution = createLocalExecutionPackage("execution.local");- const state = createSqliteRuntimeServicePackage({- path: join(directory, ".svml", "runtime.sqlite"),+ const state = createSqliteRuntimeComponentPackage({+ path: join(directory, ".narratage", "runtime.sqlite"),buildInstance: "state.builds",operationInstance: "state.operations",dispatchInstance: "state.dispatch",});const artifacts = createFileArtifactStorePackage({- root: join(directory, ".svml", "artifacts"),+ root: join(directory, ".narratage", "artifacts"),instance: "artifacts.fs",});const credentials = createEnvironmentCredentialStorePackage({ instance: "credentials.env" });return {- runtimeServices: [execution, state, artifacts, credentials],- runtimeSelection: {+ runtimeComponents: [execution, state, artifacts, credentials],+ bindings: {scheduler: "execution.local.scheduler",worker: "execution.local.worker",stores: {@@ -90,7 +90,7 @@ test("one local execution domain fences Runtime Closure revisions, not author paconst directory = await mkdtemp(join(tmpdir(), "svml-local-revision-gate-"));try {const first = await createProjectLocalRuntime({- root: directory,+ dataRoot: directory,...projectRuntimeFixture(directory),});await first.build({@@ -100,7 +100,7 @@ test("one local execution domain fences Runtime Closure revisions, not author paawait first.close();const changedRuntimePackages = projectRuntimeFixture(directory);- const execution = changedRuntimePackages.runtimeServices[0];+ const execution = changedRuntimePackages.runtimeComponents[0];const revisedExecution = {...execution,manifest: {@@ -113,9 +113,9 @@ test("one local execution domain fences Runtime Closure revisions, not author pa};await assert.rejects(createProjectLocalRuntime({- root: directory,+ dataRoot: directory,...changedRuntimePackages,- runtimeServices: [revisedExecution, ...changedRuntimePackages.runtimeServices.slice(1)],+ runtimeComponents: [revisedExecution, ...changedRuntimePackages.runtimeComponents.slice(1)],}),/cannot enter this execution domain[\s\S]*unfinished-build[\s\S]*original Runtime Profile/u,);@@ -127,9 +127,9 @@ test("one local execution domain fences Runtime Closure revisions, not author patest("Artifact GC is explicit, dry-run by default, and only removes unreachable managed bytes", async () => {const directory = await mkdtemp(join(tmpdir(), "svml-local-artifact-gc-"));try {- const artifacts = new FileArtifactStore(join(directory, ".svml", "artifacts"));+ const artifacts = new FileArtifactStore(join(directory, ".narratage", "artifacts"));const orphan = await artifacts.put(new TextEncoder().encode("orphan"), "application/octet-stream");- const runtime = await createProjectLocalRuntime({ root: directory, ...projectRuntimeFixture(directory) });+ const runtime = await createProjectLocalRuntime({ dataRoot: directory, ...projectRuntimeFixture(directory) });const preview = await runtime.garbageCollectArtifacts();assert.deepEqual(preview.unreachable, [orphan.digest]);assert.deepEqual(preview.deleted, []);@@ -151,14 +151,14 @@ test("Endpoint-declared credentials use the selected writable Store without a Prasync put(ref, value) { values.set(ref.key, value); },async delete(ref) { return values.delete(ref.key); },};- const memoryCredentials = defineRuntimeServicePackage({+ const memoryCredentials = defineRuntimeComponentPackage({module: { name: "example.credentials-memory", version: "1" },- services: [{+ components: [{role: "credential-store",facet: "credential-store",instance: "credentials.memory",implementation: { digest: digestOf("credentials-memory@1") },- service: credentialStore,+ port: credentialStore,}],});const endpoint = defineEndpointPackage({@@ -182,12 +182,12 @@ test("Endpoint-declared credentials use the selected writable Store without a Prtry {const base = projectRuntimeFixture(directory);const runtime = await createProjectLocalRuntime({- root: directory,+ dataRoot: directory,...base,- runtimeServices: [...base.runtimeServices.slice(0, -1), memoryCredentials],- runtimeSelection: {- ...base.runtimeSelection,- stores: { ...base.runtimeSelection.stores, credentials: ["credentials.memory"] },+ runtimeComponents: [...base.runtimeComponents.slice(0, -1), memoryCredentials],+ bindings: {+ ...base.bindings,+ stores: { ...base.bindings.stores, credentials: ["credentials.memory"] },},endpoints: [endpoint],});@@ -331,7 +331,7 @@ test("project local runtime resumes durable work while component and endpoint patry {const firstRuntime = await createProjectLocalRuntime({- root: directory,+ dataRoot: directory,...projectRuntimeFixture(directory),components: [components],endpoints: [endpointPackage],@@ -344,7 +344,7 @@ test("project local runtime resumes durable work while component and endpoint paawait firstRuntime.close();const secondRuntime = await createProjectLocalRuntime({- root: directory,+ dataRoot: directory,...projectRuntimeFixture(directory),components: [components],endpoints: [endpointPackage],@@ -510,8 +510,8 @@ test("two durable Workers share one SQLite capacity limit across Runtime instanclet firstTurn: Promise<unknown> | undefined;let secondTurn: Promise<unknown> | undefined;try {- first = await createProjectLocalRuntime({ root: directory, ...options() });- second = await createProjectLocalRuntime({ root: directory, ...options() });+ first = await createProjectLocalRuntime({ dataRoot: directory, ...options() });+ second = await createProjectLocalRuntime({ dataRoot: directory, ...options() });await first.build({id: "capacity-a",state: createGreetingBuild({ generationRealization: "placeholder" }),@@ -598,7 +598,7 @@ test("project local runtime activates locked compute facets without deployment sconst lock = await createNodePackageLock(["example-greeting-components"], installedRoot);await writeNodePackageLock(lockPath, lock);const runtime = await createProjectLocalRuntime({- root: runtimeRoot,+ dataRoot: runtimeRoot,...projectRuntimeFixture(runtimeRoot),packageRoot: installedRoot,packageLock: "../svml.packages.lock",@@ -624,16 +624,16 @@ test("project local runtime activates locked compute facets without deployment stest("project local runtime uses only the explicitly selected Scheduler", async () => {const directory = await mkdtemp(join(tmpdir(), "svml-local-scheduler-service-"));let creates = 0;- const scheduler = defineRuntimeServicePackage({+ const scheduler = defineRuntimeComponentPackage({module: { name: "example.scheduler", version: "1" },- services: [{+ components: [{role: "scheduler",facet: "scheduler",instance: "scheduler.example",implementation: {digest: digestOf("example.scheduler/fair@1"),},- service: {+ port: {create(executor, options) {creates += 1;return new LocalBuildScheduler(executor, options);@@ -644,10 +644,10 @@ test("project local runtime uses only the explicitly selected Scheduler", asynctry {const base = projectRuntimeFixture(directory);const runtime = await createProjectLocalRuntime({- root: directory,+ dataRoot: directory,...base,- runtimeServices: [...base.runtimeServices, scheduler],- runtimeSelection: { ...base.runtimeSelection, scheduler: "scheduler.example" },+ runtimeComponents: [...base.runtimeComponents, scheduler],+ bindings: { ...base.bindings, scheduler: "scheduler.example" },});await runtime.build({ id: "scheduler-selection", state: createGreetingBuild() });await runtime.workOnce({ owner: "scheduler-test", leaseMs: 5_000 });@@ -662,16 +662,16 @@ test("two installed Schedulers are unambiguous because the Profile selects one",const directory = await mkdtemp(join(tmpdir(), "svml-local-scheduler-selection-"));const creates = { one: 0, two: 0 };const closes = { one: 0, two: 0 };- const scheduler = (name: "one" | "two") => defineRuntimeServicePackage({+ const scheduler = (name: "one" | "two") => defineRuntimeComponentPackage({module: { name: `example.scheduler.${name}`, version: "1" },- services: [{+ components: [{role: "scheduler",facet: "scheduler",instance: `scheduler.${name}`,implementation: {digest: digestOf(`example.scheduler.${name}/fair@1`),},- service: {+ port: {create(executor, options) {creates[name] += 1;return new LocalBuildScheduler(executor, options);@@ -683,10 +683,10 @@ test("two installed Schedulers are unambiguous because the Profile selects one",try {const base = projectRuntimeFixture(directory);const runtime = await createProjectLocalRuntime({- root: directory,+ dataRoot: directory,...base,- runtimeServices: [...base.runtimeServices, scheduler("one"), scheduler("two")],- runtimeSelection: { ...base.runtimeSelection, scheduler: "scheduler.two" },+ runtimeComponents: [...base.runtimeComponents, scheduler("one"), scheduler("two")],+ bindings: { ...base.bindings, scheduler: "scheduler.two" },});await runtime.build({ id: "scheduler-two", state: createGreetingBuild() });await runtime.workOnce({ owner: "scheduler-test", leaseMs: 5_000 });@@ -702,9 +702,9 @@ test("project local runtime accepts an explicitly selected replacement ArtifactSconst directory = await mkdtemp(join(tmpdir(), "svml-local-artifacts-"));const module = { name: "example.remote-artifacts", version: "1" } as const;const artifactStore = new MemoryArtifactStore();- const artifacts = defineRuntimeServicePackage({+ const artifacts = defineRuntimeComponentPackage({module,- services: [{+ components: [{facet: "artifact-store",instance: "artifacts.remote",role: "artifact-store",@@ -712,18 +712,18 @@ test("project local runtime accepts an explicitly selected replacement ArtifactSdigest: digestOf("example.remote-artifacts@1"),},configuration: { bucket: "fixture" },- service: artifactStore,+ port: artifactStore,}],});try {const selected = projectRuntimeFixture(directory);const runtime = await createProjectLocalRuntime({- root: directory,+ dataRoot: directory,...selected,- runtimeServices: [...selected.runtimeServices, artifacts],- runtimeSelection: {- ...selected.runtimeSelection,- stores: { ...selected.runtimeSelection.stores, artifacts: "artifacts.remote" },+ runtimeComponents: [...selected.runtimeComponents, artifacts],+ bindings: {+ ...selected.bindings,+ stores: { ...selected.bindings.stores, artifacts: "artifacts.remote" },},});const bytes = new Uint8Array([7, 8, 9]);diff --git a/packages/local/test/external-services.test.ts b/packages/local/test/programs.test.tssimilarity index 59%rename from packages/local/test/external-services.test.tsrename to packages/local/test/programs.test.tsindex 9c70456b..f6e59026 100644--- a/packages/local/test/external-services.test.ts+++ b/packages/local/test/programs.test.ts@@ -6,15 +6,15 @@ import test from "node:test";import { setTimeout as sleep } from "node:timers/promises";import { createRuntimeEndpointAdapterFacet } from "@narratage/runtime-adapter";-import type { RuntimeExternalService } from "@narratage/runtime-adapter";+import type { ManagedProgram } from "@narratage/runtime-adapter";import type { CapabilityRef } from "@narratage/protocol";import {- bringExternalServicesUp,- declaredExternalServices,- reportExternalServices,+ bringManagedProgramsUp,+ declaredManagedPrograms,+ reportManagedPrograms,RuntimeAdapterRegistry,- takeExternalServicesDown,+ takeManagedProgramsDown,} from "@narratage/local";const requiredCapability = {@@ -27,29 +27,34 @@ const requiredCapability = {* file back. That is enough to exercise detaching, the pid file, waiting for* ready, and stopping — without a Python environment.*/-async function project(service: (root: string) => RuntimeExternalService) {- const root = await mkdtemp(join(tmpdir(), "svml-services-"));+async function project(program: (root: string) => ManagedProgram) {+ const root = await mkdtemp(join(tmpdir(), "narratage-programs-"));const path = join(root, "svml.runtime.json");await writeFile(path, JSON.stringify({- format: "svml.runtime-config@1",- runtimeServices: [],- services: {- scheduler: "execution.scheduler",- worker: "execution.worker",- stores: {- build: "state.builds",- operations: "state.operations",- dispatch: "state.dispatch",- artifacts: "artifacts",- credentials: ["credentials"],+ format: "narratage.runtime-profile@1",+ runtime: {+ use: "@narratage/local",+ config: {+ dataRoot: ".",+ components: {},+ bindings: {+ scheduler: "execution.scheduler",+ worker: "execution.worker",+ stores: {+ build: "state.builds",+ operations: "state.operations",+ dispatch: "state.dispatch",+ artifacts: "artifacts",+ credentials: ["credentials"],+ },+ },+ endpoints: {+ one: { use: "example.program", authority: "example.local", config: {} },+ two: { use: "example.program", authority: "example.local", config: {} },+ },+ limits: { maxOperations: 1 },},},- endpoints: [- { use: "example.program", instance: "one", authority: "example.local", config: {} },- // A second Endpoint driving the same program: it is brought up once.- { use: "example.program", instance: "two", authority: "example.local", config: {} },- ],- scheduling: { maxConcurrency: 1 },}));const registry = new RuntimeAdapterRegistry();registry.registerFacet(createRuntimeEndpointAdapterFacet({@@ -67,13 +72,13 @@ async function project(service: (root: string) => RuntimeExternalService) {credentials: [],install() {},} as never,- externalService: service(root),+ program: program(root),}),}));return { root, path, options: { registry } };}-test("a Build service selection ignores programs outside its demanded capabilities", async () => {+test("a Build capability selection ignores unrelated Programs", async () => {let probes = 0;const configured = await project(() => ({id: "unused",@@ -82,14 +87,14 @@ test("a Build service selection ignores programs outside its demanded capabilitireturn { state: "ready" as const };},}));- const result = await bringExternalServicesUp(configured.path, {+ const result = await bringManagedProgramsUp(configured.path, {...configured.options,capabilities: [{module: { name: "another.capabilities", version: "1" },name: "Other",}],});- assert.deepEqual(result.services, []);+ assert.deepEqual(result.programs, []);assert.equal(probes, 0);});@@ -100,15 +105,15 @@ test("an empty Build capability set loads no Runtime Adapter closure", async ()throw new Error("an empty capability set must not activate or probe an Endpoint");},}));- const result = await declaredExternalServices(configured.path, {+ const result = await declaredManagedPrograms(configured.path, {// Deliberately omit the registry. Reaching adapter activation would fail// because `example.program` is not installed in a package lock.capabilities: [],});- assert.deepEqual(result, { root: configured.root, services: [] });+ assert.deepEqual(result, { dataRoot: configured.root, programs: [] });});-function fileBackedService(root: string, marker: string): RuntimeExternalService {+function fileBackedProgram(root: string, marker: string): ManagedProgram {return {id: "example",start: { command: "sh", args: ["-c", `printf ready > ${marker}; while true; do sleep 1; done`] },@@ -125,58 +130,58 @@ function fileBackedService(root: string, marker: string): RuntimeExternalServicetest("up starts the program once for every Endpoint that drives it, and down stops it", async () => {const marker = join(await mkdtemp(join(tmpdir(), "svml-marker-")), "ready");- const { root, path, options } = await project((projectRoot) => fileBackedService(projectRoot, marker));+ const { root, path, options } = await project((projectRoot) => fileBackedProgram(projectRoot, marker));const progress: string[] = [];- const started = await bringExternalServicesUp(path, {+ const started = await bringManagedProgramsUp(path, {...options,maxWaitMs: 20_000,onProgress: (event) => progress.push(`${event.id}:${event.phase}`),});- assert.equal(started.services.length, 1, "one program, not one per Endpoint");- assert.deepEqual(started.services[0]!.instances, ["one", "two"]);- assert.equal(started.services[0]!.action, "started");- assert.deepEqual(started.services[0]!.state, { state: "ready" });+ assert.equal(started.programs.length, 1, "one program, not one per Endpoint");+ assert.deepEqual(started.programs[0]!.instances, ["one", "two"]);+ assert.equal(started.programs[0]!.action, "started");+ assert.deepEqual(started.programs[0]!.state, { state: "ready" });assert.deepEqual(progress, ["example:checking", "example:starting", "example:waiting", "example:ready"]);- const pid = started.services[0]!.pid!;- assert.equal(await readFile(join(root, ".svml", "services", "example.pid"), "utf8"), `${pid}\n`);+ const pid = started.programs[0]!.pid!;+ assert.equal(await readFile(join(root, "programs", "example.pid"), "utf8"), `${pid}\n`);// Asking again changes nothing: a healthy program is left alone.- const again = await bringExternalServicesUp(path, { ...options, maxWaitMs: 20_000 });- assert.equal(again.services[0]!.action, "already-running");- assert.equal(again.services[0]!.pid, undefined, "nothing was started, so no pid is claimed");+ const again = await bringManagedProgramsUp(path, { ...options, maxWaitMs: 20_000 });+ assert.equal(again.programs[0]!.action, "already-running");+ assert.equal(again.programs[0]!.pid, undefined, "nothing was started, so no pid is claimed");- const status = await reportExternalServices(path, options);- assert.equal(status.services[0]!.pid, pid);- assert.equal(status.services[0]!.logPath, join(root, ".svml", "services", "example.log"));+ const status = await reportManagedPrograms(path, options);+ assert.equal(status.programs[0]!.pid, pid);+ assert.equal(status.programs[0]!.logPath, join(root, "programs", "example.log"));await rm(marker, { force: true });- const stopped = await takeExternalServicesDown(path, options);- assert.equal(stopped.services[0]!.action, "stopped");- assert.equal(stopped.services[0]!.pid, pid);+ const stopped = await takeManagedProgramsDown(path, options);+ assert.equal(stopped.programs[0]!.action, "stopped");+ assert.equal(stopped.programs[0]!.pid, pid);await sleep(100);assert.throws(() => process.kill(pid, 0), "the detached program is gone");- await assert.rejects(async () => await readFile(join(root, ".svml", "services", "example.pid"), "utf8"));+ await assert.rejects(async () => await readFile(join(root, "programs", "example.pid"), "utf8"));await rm(root, { recursive: true, force: true });});-test("concurrent up calls atomically share one external service process", async () => {+test("concurrent up calls atomically share one Managed Program process", async () => {const markerRoot = await mkdtemp(join(tmpdir(), "svml-marker-concurrent-"));const marker = join(markerRoot, "ready");- const { root, path, options } = await project((projectRoot) => fileBackedService(projectRoot, marker));+ const { root, path, options } = await project((projectRoot) => fileBackedProgram(projectRoot, marker));try {const results = await Promise.all(Array.from({ length: 6 }, async () =>- await bringExternalServicesUp(path, { ...options, maxWaitMs: 20_000 })));- assert.equal(results.filter((item) => item.services[0]!.action === "started").length, 1);- assert.equal(results.filter((item) => item.services[0]!.action === "already-running").length, 5);- const pid = Number.parseInt(await readFile(join(root, ".svml", "services", "example.pid"), "utf8"), 10);+ await bringManagedProgramsUp(path, { ...options, maxWaitMs: 20_000 })));+ assert.equal(results.filter((item) => item.programs[0]!.action === "started").length, 1);+ assert.equal(results.filter((item) => item.programs[0]!.action === "already-running").length, 5);+ const pid = Number.parseInt(await readFile(join(root, "programs", "example.pid"), "utf8"), 10);assert.ok(Number.isSafeInteger(pid) && pid > 0);- await takeExternalServicesDown(path, options);+ await takeManagedProgramsDown(path, options);await sleep(100);assert.throws(() => process.kill(pid, 0));} finally {- await takeExternalServicesDown(path, options).catch(() => undefined);+ await takeManagedProgramsDown(path, options).catch(() => undefined);await rm(root, { recursive: true, force: true });await rm(markerRoot, { recursive: true, force: true });}@@ -188,10 +193,10 @@ test("a program answering with another identity is never joined by a second copystart: { command: "sh", args: ["-c", "exit 1"] },probe: async () => ({ state: "mismatch", detail: "model is large-v3, expected small" }),}));- const result = await bringExternalServicesUp(path, options);- assert.equal(result.services[0]!.action, "unchanged");- assert.equal(result.services[0]!.state.state, "mismatch");- assert.equal(result.services[0]!.pid, undefined, "nothing was started beside it");+ const result = await bringManagedProgramsUp(path, options);+ assert.equal(result.programs[0]!.action, "unchanged");+ assert.equal(result.programs[0]!.state.state, "mismatch");+ assert.equal(result.programs[0]!.pid, undefined, "nothing was started beside it");});test("down leaves a running program this project did not start", async () => {@@ -200,9 +205,9 @@ test("down leaves a running program this project did not start", async () => {start: { command: "sh", args: ["-c", "sleep 60"] },probe: async () => ({ state: "ready" }),}));- const result = await takeExternalServicesDown(path, options);- assert.equal(result.services[0]!.action, "not-ours");- assert.match(result.services[0]!.detail ?? "", /this project did not start it/u);+ const result = await takeManagedProgramsDown(path, options);+ assert.equal(result.programs[0]!.action, "not-ours");+ assert.match(result.programs[0]!.detail ?? "", /this project did not start it/u);});test("a program with nothing to start is prepared, and preparing is the whole job", async () => {@@ -220,10 +225,10 @@ test("a program with nothing to start is prepared, and preparing is the whole jo}},}));- const result = await bringExternalServicesUp(path, options);- assert.equal(result.services[0]!.action, "prepared");- assert.deepEqual(result.services[0]!.state, { state: "ready" });- assert.equal(result.services[0]!.pid, undefined, "there is no daemon to hold a pid");+ const result = await bringManagedProgramsUp(path, options);+ assert.equal(result.programs[0]!.action, "prepared");+ assert.deepEqual(result.programs[0]!.state, { state: "ready" });+ assert.equal(result.programs[0]!.pid, undefined, "there is no daemon to hold a pid");await rm(directory, { recursive: true, force: true });});@@ -234,10 +239,10 @@ test("a failing prepare stops before starting anything, and says which command fstart: { command: "sh", args: ["-c", "while true; do sleep 1; done"] },probe: async () => ({ state: "down", detail: "nothing is answering" }),}));- const result = await bringExternalServicesUp(path, options);- assert.equal(result.services[0]!.action, "unchanged");- assert.match(result.services[0]!.detail ?? "", /sh failed: no such project/u);- assert.equal(result.services[0]!.logPath, undefined, "nothing was started, so nothing logged");+ const result = await bringManagedProgramsUp(path, options);+ assert.equal(result.programs[0]!.action, "unchanged");+ assert.match(result.programs[0]!.detail ?? "", /sh failed: no such project/u);+ assert.equal(result.programs[0]!.logPath, undefined, "nothing was started, so nothing logged");});test("status probes and changes nothing, so it claims no action", async () => {@@ -246,7 +251,7 @@ test("status probes and changes nothing, so it claims no action", async () => {start: { command: "sh", args: ["-c", "exit 1"] },probe: async () => ({ state: "down", detail: "nothing is answering" }),}));- const result = await reportExternalServices(path, options);- assert.equal(result.services[0]!.action, undefined);- assert.deepEqual(result.services[0]!.state, { state: "down", detail: "nothing is answering" });+ const result = await reportManagedPrograms(path, options);+ assert.equal(result.programs[0]!.action, undefined);+ assert.deepEqual(result.programs[0]!.state, { state: "down", detail: "nothing is answering" });});diff --git a/packages/cli/test/runtime-process.test.ts b/packages/local/test/worker-process.test.tssimilarity index 61%rename from packages/cli/test/runtime-process.test.tsrename to packages/local/test/worker-process.test.tsindex 855fe410..7ad389a9 100644--- a/packages/cli/test/runtime-process.test.ts+++ b/packages/local/test/worker-process.test.ts@@ -9,11 +9,12 @@ import {runtimeProcessLogs,runtimeProcessStatus,stopRuntimeProcess,-} from "../src/runtime-process.js";+} from "../src/worker-process.js";test("one detached Runtime Worker is observable, reusable and explicitly stoppable", async () => {const root = await mkdtemp(join(tmpdir(), "narratage-runtime-process-"));const profile = join(root, "runtime.json");+ const dataRoot = join(root, ".narratage", "runtimes", "local");const authorLock = join(root, "author.lock");const runtimeLock = join(root, "runtime.lock");await writeFile(authorLock, "author-v1\n", "utf8");@@ -22,8 +23,8 @@ test("one detached Runtime Worker is observable, reusable and explicitly stoppabpackageLock: "./author.lock",runtimePackageLock: "./runtime.lock",}), "utf8");- await mkdir(join(root, ".svml"), { recursive: true });- await writeFile(join(root, ".svml", "runtime"), "runtime.json\n", "utf8");+ await mkdir(join(root, ".narratage"), { recursive: true });+ await writeFile(join(root, ".narratage", "runtime"), "runtime.json\n", "utf8");const program = `const fs = require("node:fs");const path = require("node:path");@@ -37,28 +38,28 @@ test("one detached Runtime Worker is observable, reusable and explicitly stoppab`;try {const first = await ensureRuntimeProcess(- profile, { command: process.execPath, args: ["-e", program] }, "revision-1", 5_000);+ profile, dataRoot, { command: process.execPath, args: ["-e", program] }, "revision-1", 5_000);assert.equal(first.state, "running");assert.ok(first.pid);- assert.equal(await readFile(join(root, ".svml", "runtime"), "utf8"), "runtime.json\n",+ assert.equal(await readFile(join(root, ".narratage", "runtime"), "utf8"), "runtime.json\n","Worker state must not overwrite or descend through the active Runtime Profile pointer");- const second = await ensureRuntimeProcess(profile, { command: "must-not-run", args: [] }, "revision-1", 5_000);+ const second = await ensureRuntimeProcess(profile, dataRoot, { command: "must-not-run", args: [] }, "revision-1", 5_000);assert.equal(second.pid, first.pid);const concurrent = await Promise.all(Array.from({ length: 8 }, async () =>- await ensureRuntimeProcess(profile, { command: "must-not-run", args: [] }, "revision-1", 5_000)));+ await ensureRuntimeProcess(profile, dataRoot, { command: "must-not-run", args: [] }, "revision-1", 5_000)));assert.deepEqual([...new Set(concurrent.map((item) => item.pid))], [first.pid],"concurrent clients share one atomically launched Worker");- assert.equal((await runtimeProcessStatus(profile, "revision-1")).state, "running");- assert.match((await runtimeProcessLogs(profile)).text, /worker-ready/u);- const logPath = (await runtimeProcessLogs(profile)).path;+ assert.equal((await runtimeProcessStatus(profile, dataRoot, "revision-1")).state, "running");+ assert.match((await runtimeProcessLogs(dataRoot)).text, /worker-ready/u);+ const logPath = (await runtimeProcessLogs(dataRoot)).path;await appendFile(logPath, `${"x".repeat(1024 * 1024 + 64)}\ntail-marker\n`, "utf8");- const bounded = await runtimeProcessLogs(profile);+ const bounded = await runtimeProcessLogs(dataRoot);assert.ok(Buffer.byteLength(bounded.text) <= 1024 * 1024);assert.match(bounded.text, /tail-marker/u);await writeFile(runtimeLock, "runtime-v2\n", "utf8");- assert.equal((await runtimeProcessStatus(profile, "revision-2")).state, "stale");+ assert.equal((await runtimeProcessStatus(profile, dataRoot, "revision-2")).state, "stale");const replaced = await ensureRuntimeProcess(- profile, { command: process.execPath, args: ["-e", program] }, "revision-2", 5_000);+ profile, dataRoot, { command: process.execPath, args: ["-e", program] }, "revision-2", 5_000);assert.notEqual(replaced.pid, first.pid);assert.equal(replaced.state, "running");await writeFile(profile, JSON.stringify({@@ -66,15 +67,15 @@ test("one detached Runtime Worker is observable, reusable and explicitly stoppabpackageLock: "./author.lock",runtimePackageLock: "./runtime.lock",}), "utf8");- assert.equal((await runtimeProcessStatus(profile, "revision-3")).state, "stale");+ assert.equal((await runtimeProcessStatus(profile, dataRoot, "revision-3")).state, "stale");const replacedAgain = await ensureRuntimeProcess(- profile, { command: process.execPath, args: ["-e", program] }, "revision-3", 5_000);+ profile, dataRoot, { command: process.execPath, args: ["-e", program] }, "revision-3", 5_000);assert.notEqual(replacedAgain.pid, replaced.pid);assert.equal(replacedAgain.state, "running");- assert.equal((await stopRuntimeProcess(profile, 5_000)).state, "stopped");- assert.equal((await runtimeProcessStatus(profile, "revision-3")).state, "stopped");+ assert.equal((await stopRuntimeProcess(profile, dataRoot, 5_000)).state, "stopped");+ assert.equal((await runtimeProcessStatus(profile, dataRoot, "revision-3")).state, "stopped");} finally {- await stopRuntimeProcess(profile, 1_000).catch(() => undefined);+ await stopRuntimeProcess(profile, dataRoot, 1_000).catch(() => undefined);await rm(root, { recursive: true, force: true });}});diff --git a/packages/mimo-tts/README.md b/packages/mimo-tts/README.mdindex 3336a5c9..7d0383b4 100644--- a/packages/mimo-tts/README.md+++ b/packages/mimo-tts/README.md@@ -39,8 +39,7 @@ Add the author package to the project's explicit package lock before compiling:```shnode --run narratage -- lock-packages svml.packages.lock \--package @narratage/script \- --package @narratage/mimo-tts \- --root .+ --package @narratage/mimo-tts```This selects author syntax and exact model semantics only. It does not select an API service.diff --git a/packages/package-loader-node/README.md b/packages/package-loader-node/README.mdindex 1361e379..52cd29e9 100644--- a/packages/package-loader-node/README.md+++ b/packages/package-loader-node/README.md@@ -23,13 +23,13 @@ Run-specific fragment field or interpretation branch. Author and Run Frontends lordinary `svml.source-frontend@1` Host facet; the Loader has no Frontend fields or parser registry.This package is deliberately not an npm client and does not activate Provider or privileged Runtime-services. Source `<import>` can select only an already installed author contribution; trusted+packages. Source `<import>` can select only an already installed author contribution; trusteddeployment configuration independently chooses whether to grant author or deterministic compute registries.Executable plans bind the package-lock digest as `BuildRequest.implementationClosure`.```bashnarratage lock-packages ./svml.packages.lock --package @example/cards --package-root .-narratage check ./main.svml --package-lock ./svml.packages.lock --root .+narratage check ./main.svml --package-lock ./svml.packages.lock --workspace .```If `@example/cards` requires a Module exported by an installed dependency, that dependency does notdiff --git a/packages/package-loader-node/test/loader.test.ts b/packages/package-loader-node/test/loader.test.tsindex 8963de5f..5d1fbb07 100644--- a/packages/package-loader-node/test/loader.test.ts+++ b/packages/package-loader-node/test/loader.test.ts@@ -24,7 +24,7 @@ const implementationDigest = `sha256:${"1".repeat(64)}`;const producerDigest = `sha256:${"3".repeat(64)}`;async function fixture(): Promise<{- readonly root: string;+ readonly dataRoot: string;readonly activation: string;readonly dependency: string;readonly helperDigest: string;@@ -187,7 +187,7 @@ async function fixture(): Promise<{<example:Card/></svml>`, "utf8");return {- root,+ dataRoot: root,activation,dependency,helperDigest: digestOf(helperManifest),@@ -198,12 +198,12 @@ async function fixture(): Promise<{test("an installed locked package carries inert Host facets and activatable compute", async () => {const item = await fixture();- const lock = await createNodePackageLock(["example-card"], item.root);+ const lock = await createNodePackageLock(["example-card"], item.dataRoot);assert.deepEqual(lock.artifacts.map((artifact) => artifact.name), ["example-card", "example-helper", "example-types"]);assert.deepEqual(lock.selected, ["example-card"]);assert.deepEqual(lock.packages.map((value) => value.package.name), ["example-card", "example-helper"]);await writeNodePackageLock(item.lock, lock);- const packages = (await loadNodePackageSet(item.lock, item.root)).packages.map((value) => value.contribution);+ const packages = (await loadNodePackageSet(item.lock, item.dataRoot)).packages.map((value) => value.contribution);assert.equal(packages[0]?.modules?.[0]?.manifest.name, "example.card");assert.equal(packages[1]?.modules?.[0]?.manifest.name, "example.helper");@@ -229,12 +229,12 @@ test("an empty local trust selection is a valid authenticated package lock", asytest("dependency bytes are rejected before a locked contribution entry is reused", async () => {const item = await fixture();- const lock = await createNodePackageLock(["example-card"], item.root);+ const lock = await createNodePackageLock(["example-card"], item.dataRoot);await writeNodePackageLock(item.lock, lock);await writeFile(item.dependency, `${await readFile(item.dependency, "utf8")}\n// changed bytes\n`, "utf8");await assert.rejects(- async () => await loadNodePackageSet(item.lock, item.root),+ async () => await loadNodePackageSet(item.lock, item.dataRoot),/installed Node package bytes do not match the lock/,);});@@ -248,14 +248,14 @@ test("a missing exact Module provider is rejected while the lock is created", as);await assert.rejects(- async () => await createNodePackageLock(["example-card"], item.root),+ async () => await createNodePackageLock(["example-card"], item.dataRoot),/no installed package .* provides required Module example\.helper@1/u,);});test("two physical packages cannot ambiguously provide one required Module", async () => {const item = await fixture();- const copyRoot = join(item.root, "node_modules", "example-helper-copy");+ const copyRoot = join(item.dataRoot, "node_modules", "example-helper-copy");await mkdir(copyRoot, { recursive: true });await writeFile(join(copyRoot, "package.json"), JSON.stringify({name: "example-helper-copy",@@ -269,7 +269,7 @@ test("two physical packages cannot ambiguously provide one required Module", asyawait readFile(item.dependency, "utf8"),"utf8",);- const cardPackagePath = join(item.root, "node_modules", "example-card", "package.json");+ const cardPackagePath = join(item.dataRoot, "node_modules", "example-card", "package.json");const cardPackage = JSON.parse(await readFile(cardPackagePath, "utf8")) as {dependencies: Record<string, string>;};@@ -277,15 +277,15 @@ test("two physical packages cannot ambiguously provide one required Module", asyawait writeFile(cardPackagePath, JSON.stringify(cardPackage, null, 2), "utf8");await assert.rejects(- async () => await createNodePackageLock(["example-card"], item.root),+ async () => await createNodePackageLock(["example-card"], item.dataRoot),/multiple installed packages .* provide required Module example\.helper@1/u,);});test("an unrelated selected package does not contaminate another package's implementation closure", async () => {const item = await fixture();- const alone = await createNodePackageLock(["example-card"], item.root);- const together = await createNodePackageLock(["example-card", "example-extra"], item.root);+ const alone = await createNodePackageLock(["example-card"], item.dataRoot);+ const together = await createNodePackageLock(["example-card", "example-extra"], item.dataRoot);const left = alone.packages.find((value) => value.package.name === "example-card")!;const right = together.packages.find((value) => value.package.name === "example-card")!;assert.equal(left.closureDigest, right.closureDigest);@@ -294,8 +294,8 @@ test("an unrelated selected package does not contaminate another package's impletest("selection mutation keeps a shared dependency only through its retained root", async () => {const item = await fixture();- const old = await createNodePackageLock(["example-card", "example-extra"], item.root);- const next = await createNodePackageLock(["example-extra"], item.root, {+ const old = await createNodePackageLock(["example-card", "example-extra"], item.dataRoot);+ const next = await createNodePackageLock(["example-extra"], item.dataRoot, {retain: { from: old, selected: ["example-extra"] },});assert.deepEqual(next.selected, ["example-extra"]);@@ -316,13 +316,13 @@ test("a compute facet cannot claim another implementation than its static Manife);await assert.rejects(- async () => await createNodePackageLock(["example-card"], item.root),+ async () => await createNodePackageLock(["example-card"], item.dataRoot),/Producer .* differs from its Manifest/u,);});async function runtimeAdapterFixture(marker: string): Promise<{- readonly root: string;+ readonly dataRoot: string;readonly lock: string;}> {const root = await mkdtemp(join(tmpdir(), "svml-external-runtime-adapter-"));@@ -388,19 +388,19 @@ async function runtimeAdapterFixture(marker: string): Promise<{hostFacets: [runtimeFacet],};`, "utf8");- return { root, lock: join(root, "runtime.packages.lock") };+ return { dataRoot: root, lock: join(root, "runtime.packages.lock") };}async function loadedExternalEndpointDigest(marker: string): Promise<string> {const item = await runtimeAdapterFixture(marker);await writeNodePackageLock(item.lock,- await createNodePackageLock(["example-runtime-adapter"], item.root),+ await createNodePackageLock(["example-runtime-adapter"], item.dataRoot),);const loaded = await loadNodePackageSelection(item.lock, {selected: [],logical: [{ abi: runtimeEndpointAdapterHostAbi, name: "example.logical-endpoint" }],- }, item.root);+ }, item.dataRoot);const loadedPackage = loaded.packages[0]!;const contribution = loadedPackage.contribution;const locked = loaded.lock.packages[0]!;@@ -409,7 +409,7 @@ async function loadedExternalEndpointDigest(marker: string): Promise<string> {closureDigest: locked.closureDigest,});const endpoint = await registry.createEndpoint("example.logical-endpoint", {- root: item.root,+ dataRoot: item.dataRoot,instance: "external.fixture",config: {},});diff --git a/packages/provider-hyperframes-aws-lambda/test/provider.test.ts b/packages/provider-hyperframes-aws-lambda/test/provider.test.tsindex 37f8218d..74c9c9df 100644--- a/packages/provider-hyperframes-aws-lambda/test/provider.test.ts+++ b/packages/provider-hyperframes-aws-lambda/test/provider.test.ts@@ -270,7 +270,7 @@ test("the Runtime adapter refuses a hardware-GPU deployment wish instead of ignoconst facet = awsLambdaActivation.hostFacets[0]!;const implementation = facet.implementation as RuntimeEndpointAdapterImplementation;assert.throws(() => implementation.activate({- root: "/tmp",+ dataRoot: "/tmp",instance: "hyperframes.lambda.test",authority: "hyperframes.lambda.test",config: canonicalize({diff --git a/packages/provider-hyperframes-local/README.md b/packages/provider-hyperframes-local/README.mdindex bc2facae..75062542 100644--- a/packages/provider-hyperframes-local/README.md+++ b/packages/provider-hyperframes-local/README.md@@ -17,8 +17,8 @@ The Provider owns both controls because they are deployment policy, not author irenders program audio; `@narratage/provider-media-local` separately prepares `TimelineAudio` and muxesthe final media.-The Runtime Adapter also owns one non-daemon browser service. `services up` invokes the pinned-HyperFrames CLI's `browser ensure`; the service probe resolves and starts that browser and checks+The Runtime Adapter also declares one managed browser program. `programs up` invokes the pinned+HyperFrames CLI's `browser ensure`; its probe resolves and starts that browser and checksffprobe before a Build.```tsdiff --git a/packages/provider-hyperframes-local/src/activation.ts b/packages/provider-hyperframes-local/src/activation.tsindex 35d8d1a6..28f5a242 100644--- a/packages/provider-hyperframes-local/src/activation.ts+++ b/packages/provider-hyperframes-local/src/activation.ts@@ -12,7 +12,7 @@ import {import { createLocalHyperframesProvider } from "./provider.js";import type { HyperframesBrowserGpu, HyperframesQuality, HyperframesWorkers } from "./provider.js";-import { localHyperframesBrowserService } from "./service.js";+import { localHyperframesBrowserProgram } from "./program.js";const localHyperframesRuntimeAdapter = createRuntimeEndpointAdapterFacet({use: "@narratage/provider-hyperframes-local",@@ -42,9 +42,9 @@ const localHyperframesRuntimeAdapter = createRuntimeEndpointAdapterFacet({const configuredNode = runtimeConfigString(config.nodePath, "HyperFrames nodePath");const configuredCli = runtimeConfigString(config.hyperframesCliPath, "HyperFrames hyperframesCliPath");const configuredFfprobe = runtimeConfigString(config.ffprobePath, "HyperFrames ffprobePath");- const nodePath = configuredNode === undefined ? undefined : resolveRuntimeExecutable(context.root, configuredNode);- const hyperframesCliPath = configuredCli === undefined ? undefined : resolveRuntimeExecutable(context.root, configuredCli);- const ffprobePath = configuredFfprobe === undefined ? undefined : resolveRuntimeExecutable(context.root, configuredFfprobe);+ const nodePath = configuredNode === undefined ? undefined : resolveRuntimeExecutable(context.dataRoot, configuredNode);+ const hyperframesCliPath = configuredCli === undefined ? undefined : resolveRuntimeExecutable(context.dataRoot, configuredCli);+ const ffprobePath = configuredFfprobe === undefined ? undefined : resolveRuntimeExecutable(context.dataRoot, configuredFfprobe);const defaultConcurrency = runtimeConfigPositiveInteger(config.defaultConcurrency, "HyperFrames defaultConcurrency");const processTimeoutMs = runtimeConfigPositiveInteger(config.processTimeoutMs, "HyperFrames processTimeoutMs");const maxProcessOutputBytes = runtimeConfigPositiveInteger(config.maxProcessOutputBytes, "HyperFrames maxProcessOutputBytes");@@ -64,16 +64,16 @@ const localHyperframesRuntimeAdapter = createRuntimeEndpointAdapterFacet({...(maxProcessOutputBytes === undefined ? {} : { maxProcessOutputBytes }),...(maxRenderedBytes === undefined ? {} : { maxRenderedBytes }),}),- externalService: localHyperframesBrowserService(context),+ program: localHyperframesBrowserProgram(context),diagnose: async () => [...await diagnoseRuntimeExecutable({- root: context.root,+ root: context.dataRoot,configured: configuredNode,fallback: process.execPath,subject: "Node.js",}),...await diagnoseRuntimeExecutable({- root: context.root,+ root: context.dataRoot,configured: configuredFfprobe,fallback: "ffprobe",subject: "FFprobe",diff --git a/packages/provider-hyperframes-local/src/service.ts b/packages/provider-hyperframes-local/src/program.tssimilarity index 78%rename from packages/provider-hyperframes-local/src/service.tsrename to packages/provider-hyperframes-local/src/program.tsindex 080856f9..8d19e3d7 100644--- a/packages/provider-hyperframes-local/src/service.ts+++ b/packages/provider-hyperframes-local/src/program.ts@@ -2,7 +2,7 @@ import { execFile } from "node:child_process";import { probeMediaToolchain } from "@narratage/media-execution";import { runtimeConfigObject, runtimeConfigString } from "@narratage/runtime-adapter";-import type { RuntimeAdapterFactoryContext, RuntimeExternalService, RuntimeServiceState } from "@narratage/runtime-adapter";+import type { RuntimeAdapterFactoryContext, ManagedProgram, ManagedProgramState } from "@narratage/runtime-adapter";import { resolveRuntimeExecutable } from "@narratage/runtime-adapter-node";import { defaultHyperframesCliPath } from "./provider.js";@@ -19,23 +19,23 @@ function run(executable: string, args: readonly string[]): Promise<{ ok: boolean/*** HyperFrames owns the browser cache behind its CLI. It is deployment state,- * not an author dependency, so the Runtime service lifecycle prepares it only+ * not an author dependency, so the Runtime Component lifecycle prepares it only* when this Provider is selected.*/-export function localHyperframesBrowserService(+export function localHyperframesBrowserProgram(context: RuntimeAdapterFactoryContext,-): RuntimeExternalService {+): ManagedProgram {const config = runtimeConfigObject(context.config, "local HyperFrames");const configuredNode = runtimeConfigString(config.nodePath, "HyperFrames nodePath");const configuredCli = runtimeConfigString(config.hyperframesCliPath, "HyperFrames hyperframesCliPath");const configuredFfprobe = runtimeConfigString(config.ffprobePath, "HyperFrames ffprobePath");- const node = resolveRuntimeExecutable(context.root, configuredNode ?? process.execPath);- const cli = resolveRuntimeExecutable(context.root, configuredCli ?? defaultHyperframesCliPath());- const ffprobe = resolveRuntimeExecutable(context.root, configuredFfprobe ?? "ffprobe");+ const node = resolveRuntimeExecutable(context.dataRoot, configuredNode ?? process.execPath);+ const cli = resolveRuntimeExecutable(context.dataRoot, configuredCli ?? defaultHyperframesCliPath());+ const ffprobe = resolveRuntimeExecutable(context.dataRoot, configuredFfprobe ?? "ffprobe");return {id: "hyperframes-browser",prepare: { command: node, args: [cli, "browser", "ensure"] },- async probe(): Promise<RuntimeServiceState> {+ async probe(): Promise<ManagedProgramState> {const located = await run(node, [cli, "browser", "path"]);if (!located.ok) return { state: "down", detail: `HyperFrames browser is unavailable: ${located.output}` };const path = located.output.trim();diff --git a/packages/provider-hyperframes-local/test/provider.test.ts b/packages/provider-hyperframes-local/test/provider.test.tsindex b48b89f7..41446980 100644--- a/packages/provider-hyperframes-local/test/provider.test.ts+++ b/packages/provider-hyperframes-local/test/provider.test.ts@@ -14,7 +14,7 @@ import { canonicalize, digestOf } from "@narratage/protocol";import type { CanonicalValue, Need } from "@narratage/protocol";import { createLocalHyperframesProvider } from "../src/index.js";-import { localHyperframesBrowserService } from "../src/service.js";+import { localHyperframesBrowserProgram } from "../src/program.js";const liveEnabled = process.env.SVML_BROWSER_TESTS === "1";const hasFfprobe = spawnSync("ffprobe", ["-version"], { stdio: "ignore" }).status === 0;@@ -118,10 +118,10 @@ test("local HyperFrames Provider exposes one exact visual capability and two sep});test("the selected HyperFrames Provider owns one idempotent browser preparation", () => {- const service = localHyperframesBrowserService({ root: "/project", instance: "hyperframes", config: {} });- assert.equal(service.id, "hyperframes-browser");- assert.equal(service.start, undefined);- assert.deepEqual(service.prepare?.args.slice(-2), ["browser", "ensure"]);+ const program = localHyperframesBrowserProgram({ dataRoot: "/project", instance: "hyperframes", config: {} });+ assert.equal(program.id, "hyperframes-browser");+ assert.equal(program.start, undefined);+ assert.deepEqual(program.prepare?.args.slice(-2), ["browser", "ensure"]);});test("local HyperFrames Provider really renders a silent frame-exact MP4 with parallel workers", {diff --git a/packages/provider-image-opencv-local/README.md b/packages/provider-image-opencv-local/README.mdindex 468aa225..a291f959 100644--- a/packages/provider-image-opencv-local/README.md+++ b/packages/provider-image-opencv-local/README.md@@ -9,7 +9,7 @@ and stores one new image Artifact. Temporary paths, OpenCV details and diagnostistay inside the Endpoint/Receipt and never enter the image Product.The repository ships the frozen deployment environment in `services/image-opencv`. With the Runtime-Adapter's default configuration, `services up` runs `uv sync --frozen` and the Endpoint, service probe+Adapter's declared configuration, `programs up` runs `uv sync --frozen`; the Endpoint and program probeand doctor all resolve the resulting `.venv` interpreter. An explicit `pythonExecutable` selects anoperator-managed compatible environment and suppresses that managed prepare. Runtime admission andinner image work share the configured Endpoint Authority/Route resources; no separate queue is hidden in this package.diff --git a/packages/provider-image-opencv-local/package.json b/packages/provider-image-opencv-local/package.jsonindex 29d0cb04..4bf4e909 100644--- a/packages/provider-image-opencv-local/package.json+++ b/packages/provider-image-opencv-local/package.json@@ -8,8 +8,7 @@".": "./src/index.ts"},"svml": {- "activation": "./src/activation.ts",- "service": true+ "activation": "./src/activation.ts"},"dependencies": {"@narratage/artifact": "workspace:*",diff --git a/packages/provider-image-opencv-local/src/activation.ts b/packages/provider-image-opencv-local/src/activation.tsindex c567aa59..8fa3b8d6 100644--- a/packages/provider-image-opencv-local/src/activation.ts+++ b/packages/provider-image-opencv-local/src/activation.ts@@ -11,7 +11,7 @@ import {import { resolveLocalOpenCvDeployment } from "./deployment.js";import { createLocalOpenCvImageProvider } from "./provider.js";-import { localOpenCvService } from "./service.js";+import { localOpenCvProgram } from "./program.js";const localOpenCvRuntimeAdapter = createRuntimeEndpointAdapterFacet({use: "@narratage/provider-image-opencv-local",@@ -37,9 +37,9 @@ const localOpenCvRuntimeAdapter = createRuntimeEndpointAdapterFacet({...(maxInputBytes === undefined ? {} : { maxInputBytes }),...(maxOutputBytes === undefined ? {} : { maxOutputBytes }),}),- externalService: localOpenCvService(context),+ program: localOpenCvProgram(context),diagnose: () => diagnoseRuntimeExecutable({- root: context.root,+ root: context.dataRoot,configured: deployment.pythonExecutable,fallback: deployment.pythonExecutable,subject: "OpenCV Python",diff --git a/packages/provider-image-opencv-local/src/deployment.ts b/packages/provider-image-opencv-local/src/deployment.tsindex 359527d0..871f31d8 100644--- a/packages/provider-image-opencv-local/src/deployment.ts+++ b/packages/provider-image-opencv-local/src/deployment.ts@@ -3,7 +3,7 @@ import { join } from "node:path";import { fileURLToPath } from "node:url";import { runtimeConfigObject, runtimeConfigString } from "@narratage/runtime-adapter";-import type { RuntimeAdapterFactoryContext, RuntimeServiceCommand } from "@narratage/runtime-adapter";+import type { RuntimeAdapterFactoryContext, ManagedProgramCommand } from "@narratage/runtime-adapter";import { resolveRuntimeExecutable } from "@narratage/runtime-adapter-node";/**@@ -17,7 +17,7 @@ export const localOpenCvManagedProject = fileURLToPath(export type LocalOpenCvDeployment = {readonly pythonExecutable: string;- readonly prepare?: RuntimeServiceCommand;+ readonly prepare?: ManagedProgramCommand;readonly ownership: "managed" | "external";};@@ -40,7 +40,7 @@ export function resolveLocalOpenCvDeployment(const configured = runtimeConfigString(config.pythonExecutable, "OpenCV pythonExecutable");if (configured !== undefined) {return {- pythonExecutable: resolveRuntimeExecutable(context.root, configured),+ pythonExecutable: resolveRuntimeExecutable(context.dataRoot, configured),ownership: "external",};}diff --git a/packages/provider-image-opencv-local/src/service.ts b/packages/provider-image-opencv-local/src/program.tssimilarity index 86%rename from packages/provider-image-opencv-local/src/service.tsrename to packages/provider-image-opencv-local/src/program.tsindex 42c89690..770e4d57 100644--- a/packages/provider-image-opencv-local/src/service.ts+++ b/packages/provider-image-opencv-local/src/program.ts@@ -1,6 +1,6 @@import { execFile } from "node:child_process";-import type { RuntimeAdapterFactoryContext, RuntimeExternalService, RuntimeServiceState } from "@narratage/runtime-adapter";+import type { RuntimeAdapterFactoryContext, ManagedProgram, ManagedProgramState } from "@narratage/runtime-adapter";import { resolveLocalOpenCvDeployment } from "./deployment.js";@@ -22,18 +22,18 @@ function run(executable: string, args: readonly string[]): Promise<{ ok: boolean/*** OpenCV runs as one bounded process per Need, so there is nothing to keep warm- * and this service declares no `start`. What it does declare is the+ * and this Program declares no `start`. What it does declare is the* interpreter's identity: a Python without `cv2`, or with a `cv2` from before* the APIs this Provider calls, fails in the middle of a Build with a* subprocess error. Probing says so at `doctor` time instead.*/-export function localOpenCvService(context: RuntimeAdapterFactoryContext): RuntimeExternalService {+export function localOpenCvProgram(context: RuntimeAdapterFactoryContext): ManagedProgram {const deployment = resolveLocalOpenCvDeployment(context);const python = deployment.pythonExecutable;return {id: "image-opencv",...(deployment.prepare === undefined ? {} : { prepare: deployment.prepare }),- async probe(): Promise<RuntimeServiceState> {+ async probe(): Promise<ManagedProgramState> {const result = await run(python, ["-c", PROBE_PROGRAM]);if (!result.ok) return { state: "down", detail: `${python} cannot import cv2 and numpy: ${result.output}` };let found: Record<string, string>;diff --git a/packages/provider-image-opencv-local/test/service.test.ts b/packages/provider-image-opencv-local/test/program.test.tssimilarity index 78%rename from packages/provider-image-opencv-local/test/service.test.tsrename to packages/provider-image-opencv-local/test/program.test.tsindex a792bb6b..7297795f 100644--- a/packages/provider-image-opencv-local/test/service.test.ts+++ b/packages/provider-image-opencv-local/test/program.test.ts@@ -5,28 +5,28 @@ import { tmpdir } from "node:os";import { isAbsolute, join } from "node:path";import test from "node:test";-import { localOpenCvService } from "../src/service.js";+import { localOpenCvProgram } from "../src/program.js";const context = (config: Record<string, unknown> = {}) => ({- root: process.cwd(), instance: "opencv.test", config: config as never,+ dataRoot: process.cwd(), instance: "opencv.test", config: config as never,});test("OpenCV declares how to install its interpreter and nothing to keep running", () => {- const service = localOpenCvService(context());- assert.equal(service.id, "image-opencv");- assert.equal(service.start, undefined, "OpenCV runs per Need; there is no daemon to start");+ const program = localOpenCvProgram(context());+ assert.equal(program.id, "image-opencv");+ assert.equal(program.start, undefined, "OpenCV runs per Need; there is no daemon to start");// Absolute: a Runtime root is wherever the Profile lives, not where the// pinned uv project lives.- assert.equal(service.prepare?.command, "uv");- assert.equal(service.prepare?.args.at(-1), "--frozen");- const project = service.prepare?.args.at(-2) ?? "";+ assert.equal(program.prepare?.command, "uv");+ assert.equal(program.prepare?.args.at(-1), "--frozen");+ const project = program.prepare?.args.at(-2) ?? "";assert.ok(isAbsolute(project), `${project} must be absolute`);assert.ok(existsSync(join(project, "pyproject.toml")), `${project} must be the pinned uv project`);});test("an interpreter without cv2 is reported here, not mid-Build", async () => {// `false` exits non-zero without printing a version report.- const state = await localOpenCvService(context({ pythonExecutable: "/usr/bin/false" })).probe();+ const state = await localOpenCvProgram(context({ pythonExecutable: "/usr/bin/false" })).probe();assert.equal(state.state, "down");assert.match(state.state === "down" ? state.detail : "", /cannot import cv2 and numpy/u);});@@ -38,7 +38,7 @@ test("an interpreter carrying another OpenCV major is a mismatch, not a failure"const fake = join(directory, "python");await writeFile(fake, "#!/bin/sh\necho '{\"cv2\": \"3.4.18\", \"numpy\": \"2.1.0\"}'\n", { mode: 0o755 });try {- const state = await localOpenCvService(context({ pythonExecutable: fake })).probe();+ const state = await localOpenCvProgram(context({ pythonExecutable: fake })).probe();assert.equal(state.state, "mismatch");assert.match(state.state === "mismatch" ? state.detail : "", /cv2 is 3\.4\.18, expected 4\.x/u);} finally {diff --git a/packages/provider-image-opencv-local/test/provider.test.ts b/packages/provider-image-opencv-local/test/provider.test.tsindex 574fbbdb..d09a7387 100644--- a/packages/provider-image-opencv-local/test/provider.test.ts+++ b/packages/provider-image-opencv-local/test/provider.test.ts@@ -18,7 +18,7 @@ import type { BlobRef, Need } from "@narratage/protocol";import { rasterCapabilities } from "@narratage/raster";import { resolveLocalOpenCvDeployment } from "../src/deployment.js";-import { localOpenCvService } from "../src/service.js";+import { localOpenCvProgram } from "../src/program.js";function need(source: BlobRef, program: ImageTransformProgram = gptImageDenoiseV1): Need {const constraints = canonicalize({@@ -77,16 +77,16 @@ test("the OpenCV package is one replaceable Endpoint with no second queue", asyn});test("managed and external OpenCV deployments never mix their interpreters", () => {- const managedContext = { root: "/project", instance: "opencv", config: {} } as const;+ const managedContext = { dataRoot: "/project", instance: "opencv", config: {} } as const;const managed = resolveLocalOpenCvDeployment(managedContext);assert.equal(managed.ownership, "managed");assert.match(managed.pythonExecutable, /services\/image-opencv\/\.venv\/(?:bin\/python|Scripts\/python\.exe)$/u);assert.deepEqual(managed.prepare?.args.slice(-1), ["--frozen"]);- const managedService = localOpenCvService(managedContext);- assert.deepEqual(managedService.prepare, managed.prepare);+ const managedProgram = localOpenCvProgram(managedContext);+ assert.deepEqual(managedProgram.prepare, managed.prepare);const externalContext = {- root: "/project",+ dataRoot: "/project",instance: "opencv",config: { pythonExecutable: "./tools/python" },} as const;@@ -94,7 +94,7 @@ test("managed and external OpenCV deployments never mix their interpreters", ()assert.equal(external.ownership, "external");assert.equal(external.pythonExecutable, "/project/tools/python");assert.equal(external.prepare, undefined);- assert.equal(localOpenCvService(externalContext).prepare, undefined);+ assert.equal(localOpenCvProgram(externalContext).prepare, undefined);});const liveEnabled = process.env.SVML_OPENCV_TESTS === "1";diff --git a/packages/provider-kie/test/live-smoke.ts b/packages/provider-kie/test/live-smoke.tsindex c5a2b5b6..e98c2bb8 100644--- a/packages/provider-kie/test/live-smoke.ts+++ b/packages/provider-kie/test/live-smoke.ts@@ -63,7 +63,7 @@ import type {TypedRecord,} from "@narratage/protocol";import { credentialRef } from "@narratage/runtime";-import { createSqliteRuntimeServicePackage } from "@narratage/store-sqlite";+import { createSqliteRuntimeComponentPackage } from "@narratage/store-sqlite";import {sealSeedanceRequest,seedanceComponent,@@ -409,18 +409,18 @@ async function main(): Promise<void> {pollIntervalMs: 3_000,});const execution = createLocalExecutionPackage("execution.local");- const state = createSqliteRuntimeServicePackage({- path: join(root, ".svml", "runtime.sqlite"),+ const state = createSqliteRuntimeComponentPackage({+ path: join(root, ".narratage", "runtime.sqlite"),buildInstance: "state.builds",operationInstance: "state.operations",dispatchInstance: "state.dispatch",});- const artifacts = createFileArtifactStorePackage({ root: join(root, ".svml", "artifacts"), instance: "artifacts.fs" });+ const artifacts = createFileArtifactStorePackage({ root: join(root, ".narratage", "artifacts"), instance: "artifacts.fs" });const credentials = createEnvironmentCredentialStorePackage({ instance: "credentials.env" });const runtime = await createProjectLocalRuntime({- root,- runtimeServices: [execution, state, artifacts, credentials],- runtimeSelection: {+ dataRoot: root,+ runtimeComponents: [execution, state, artifacts, credentials],+ bindings: {scheduler: "execution.local.scheduler",worker: "execution.local.worker",stores: {diff --git a/packages/provider-media-local/README.md b/packages/provider-media-local/README.mdindex 68c9f0a6..fe2915fe 100644--- a/packages/provider-media-local/README.md+++ b/packages/provider-media-local/README.md@@ -26,7 +26,7 @@ The Endpoint:- muxes exactly one verified silent visual stream and one verified program-audio stream into MP4;- distinguishes AAC coding-frame padding from the authoritative packet presentation span.-The Runtime Adapter declares the selected `ffmpeg`/`ffprobe` pair as an external, non-daemon service.+The Runtime Adapter declares the selected `ffmpeg`/`ffprobe` pair as an external, non-daemon Program.Its shared probe checks the encoders and filters used by the execution body. Compatible custom pathsremain valid; the package neither pins a semantic Capability to one FFmpeg version nor mutates asystem package manager.diff --git a/packages/provider-media-local/src/activation.ts b/packages/provider-media-local/src/activation.tsindex 8d684a69..c9c2c67d 100644--- a/packages/provider-media-local/src/activation.ts+++ b/packages/provider-media-local/src/activation.ts@@ -11,7 +11,7 @@ import {} from "@narratage/runtime-adapter-node";import { createLocalMediaProvider } from "./provider.js";-import { localMediaToolchainService } from "./service.js";+import { localMediaToolchainProgram } from "./program.js";const localMediaRuntimeAdapter = createRuntimeEndpointAdapterFacet({use: "@narratage/provider-media-local",@@ -23,8 +23,8 @@ const localMediaRuntimeAdapter = createRuntimeEndpointAdapterFacet({], "local media");const configuredFfmpeg = runtimeConfigString(config.ffmpegPath, "media ffmpegPath");const configuredFfprobe = runtimeConfigString(config.ffprobePath, "media ffprobePath");- const ffmpegPath = configuredFfmpeg === undefined ? undefined : resolveRuntimeExecutable(context.root, configuredFfmpeg);- const ffprobePath = configuredFfprobe === undefined ? undefined : resolveRuntimeExecutable(context.root, configuredFfprobe);+ const ffmpegPath = configuredFfmpeg === undefined ? undefined : resolveRuntimeExecutable(context.dataRoot, configuredFfmpeg);+ const ffprobePath = configuredFfprobe === undefined ? undefined : resolveRuntimeExecutable(context.dataRoot, configuredFfprobe);const defaultConcurrency = runtimeConfigPositiveInteger(config.defaultConcurrency, "media defaultConcurrency");const processTimeoutMs = runtimeConfigPositiveInteger(config.processTimeoutMs, "media processTimeoutMs");const maxProbeOutputBytes = runtimeConfigPositiveInteger(config.maxProbeOutputBytes, "media maxProbeOutputBytes");@@ -38,16 +38,16 @@ const localMediaRuntimeAdapter = createRuntimeEndpointAdapterFacet({...(processTimeoutMs === undefined ? {} : { processTimeoutMs }),...(maxProbeOutputBytes === undefined ? {} : { maxProbeOutputBytes }),}),- externalService: localMediaToolchainService(context),+ program: localMediaToolchainProgram(context),diagnose: async () => [...await diagnoseRuntimeExecutable({- root: context.root,+ root: context.dataRoot,configured: configuredFfmpeg,fallback: "ffmpeg",subject: "FFmpeg",}),...await diagnoseRuntimeExecutable({- root: context.root,+ root: context.dataRoot,configured: configuredFfprobe,fallback: "ffprobe",subject: "FFprobe",diff --git a/packages/provider-media-local/src/service.ts b/packages/provider-media-local/src/program.tssimilarity index 74%rename from packages/provider-media-local/src/service.tsrename to packages/provider-media-local/src/program.tsindex d3ab1b42..c285c6b9 100644--- a/packages/provider-media-local/src/service.ts+++ b/packages/provider-media-local/src/program.ts@@ -1,17 +1,17 @@import { probeMediaToolchain } from "@narratage/media-execution";import { runtimeConfigObject, runtimeConfigString } from "@narratage/runtime-adapter";-import type { RuntimeAdapterFactoryContext, RuntimeExternalService } from "@narratage/runtime-adapter";+import type { RuntimeAdapterFactoryContext, ManagedProgram } from "@narratage/runtime-adapter";import { resolveRuntimeExecutable } from "@narratage/runtime-adapter-node";-/** A system/custom FFmpeg deployment is external: services up probes it but never mutates a package manager. */-export function localMediaToolchainService(context: RuntimeAdapterFactoryContext): RuntimeExternalService {+/** A system/custom FFmpeg deployment is external: programs up probes it but never mutates a package manager. */+export function localMediaToolchainProgram(context: RuntimeAdapterFactoryContext): ManagedProgram {const config = runtimeConfigObject(context.config, "local media");const ffmpegPath = resolveRuntimeExecutable(- context.root,+ context.dataRoot,runtimeConfigString(config.ffmpegPath, "media ffmpegPath") ?? "ffmpeg",);const ffprobePath = resolveRuntimeExecutable(- context.root,+ context.dataRoot,runtimeConfigString(config.ffprobePath, "media ffprobePath") ?? "ffprobe",);return {diff --git a/packages/provider-media-local/test/provider.test.ts b/packages/provider-media-local/test/provider.test.tsindex e212d1b1..971344f4 100644--- a/packages/provider-media-local/test/provider.test.ts+++ b/packages/provider-media-local/test/provider.test.ts@@ -25,17 +25,17 @@ import { canonicalize, digestOf } from "@narratage/protocol";import type { CapabilityRef, CanonicalValue, Need, TypeRef } from "@narratage/protocol";import { createLocalMediaProvider } from "../src/index.js";-import { localMediaToolchainService } from "../src/service.js";+import { localMediaToolchainProgram } from "../src/program.js";const hasMediaBinaries = spawnSync("ffmpeg", ["-version"], { stdio: "ignore" }).status === 0&& spawnSync("ffprobe", ["-version"], { stdio: "ignore" }).status === 0;test("the local media Provider declares its external toolchain without owning a second daemon", async () => {- const service = localMediaToolchainService({ root: "/project", instance: "media", config: {} });- assert.equal(service.id, "media-ffmpeg-toolchain");- assert.equal(service.prepare, undefined);- assert.equal(service.start, undefined);- const state = await service.probe();+ const program = localMediaToolchainProgram({ dataRoot: "/project", instance: "media", config: {} });+ assert.equal(program.id, "media-ffmpeg-toolchain");+ assert.equal(program.prepare, undefined);+ assert.equal(program.start, undefined);+ const state = await program.probe();assert.equal(state.state, hasMediaBinaries ? "ready" : "down");});@@ -122,10 +122,10 @@ function presentationSampleFrames(stream: MediaAudioStream): number {return Number((numerator * 2n + denominator) / (denominator * 2n));}-async function fixture(root: string): Promise<string> {- const primary = join(root, "primary.mp4");- const cover = join(root, "cover.jpg");- const source = join(root, "source.mp4");+async function fixture(dataRoot: string): Promise<string> {+ const primary = join(dataRoot, "primary.mp4");+ const cover = join(dataRoot, "cover.jpg");+ const source = join(dataRoot, "source.mp4");await run("ffmpeg", ["-v", "error", "-y","-f", "lavfi", "-i", "testsrc2=s=160x96:r=24:d=1",diff --git a/packages/provider-whisperx-local/package.json b/packages/provider-whisperx-local/package.jsonindex 16c47ea1..7c3a7576 100644--- a/packages/provider-whisperx-local/package.json+++ b/packages/provider-whisperx-local/package.json@@ -8,8 +8,7 @@".": "./src/index.ts"},"svml": {- "activation": "./src/activation.ts",- "service": true+ "activation": "./src/activation.ts"},"dependencies": {"@narratage/endpoint-kit": "workspace:*",diff --git a/packages/provider-whisperx-local/src/activation.ts b/packages/provider-whisperx-local/src/activation.tsindex fbe5cf8e..cbb5f73c 100644--- a/packages/provider-whisperx-local/src/activation.ts+++ b/packages/provider-whisperx-local/src/activation.ts@@ -7,7 +7,7 @@ import {} from "@narratage/runtime-adapter";import { createLocalWhisperXProvider } from "./provider.js";-import { localWhisperXService } from "./service.js";+import { localWhisperXProgram } from "./program.js";const localWhisperXRuntimeAdapter = createRuntimeEndpointAdapterFacet({use: "@narratage/provider-whisperx-local",@@ -65,7 +65,7 @@ const localWhisperXRuntimeAdapter = createRuntimeEndpointAdapterFacet({...(requestTimeoutMs === undefined ? {} : { requestTimeoutMs }),...(maxResponseBytes === undefined ? {} : { maxResponseBytes }),}),- externalService: localWhisperXService(context),+ program: localWhisperXProgram(context),};},});diff --git a/packages/provider-whisperx-local/src/service.ts b/packages/provider-whisperx-local/src/program.tssimilarity index 93%rename from packages/provider-whisperx-local/src/service.tsrename to packages/provider-whisperx-local/src/program.tsindex 673eff2c..4c66411c 100644--- a/packages/provider-whisperx-local/src/service.ts+++ b/packages/provider-whisperx-local/src/program.ts@@ -2,7 +2,7 @@ import { existsSync } from "node:fs";import { fileURLToPath } from "node:url";import { runtimeConfigObject, runtimeConfigString } from "@narratage/runtime-adapter";-import type { RuntimeAdapterFactoryContext, RuntimeExternalService, RuntimeServiceState } from "@narratage/runtime-adapter";+import type { RuntimeAdapterFactoryContext, ManagedProgram, ManagedProgramState } from "@narratage/runtime-adapter";import { localWhisperXPunktTabDigest } from "./provider.js";@@ -33,7 +33,7 @@ function configuredCommand(value: unknown, key: string) {return { command: value[0] as string, args: (value as string[]).slice(1) };}-export function localWhisperXService(context: RuntimeAdapterFactoryContext): RuntimeExternalService {+export function localWhisperXProgram(context: RuntimeAdapterFactoryContext): ManagedProgram {const config = runtimeConfigObject(context.config, "local WhisperX");const baseUrl = (runtimeConfigString(config.baseUrl, "WhisperX baseUrl") ?? "http://127.0.0.1:8765").replace(/\/+$/u, "");@@ -59,7 +59,7 @@ export function localWhisperXService(context: RuntimeAdapterFactoryContext): Runid: "whisperx",...(prepare === undefined ? {} : { prepare }),...(start === undefined ? {} : { start }),- async probe(): Promise<RuntimeServiceState> {+ async probe(): Promise<ManagedProgramState> {let health: Record<string, unknown>;try {const response = await fetch(`${baseUrl}/health`, { signal: AbortSignal.timeout(2000) });diff --git a/packages/provider-whisperx-local/test/service.test.ts b/packages/provider-whisperx-local/test/program.test.tssimilarity index 70%rename from packages/provider-whisperx-local/test/service.test.tsrename to packages/provider-whisperx-local/test/program.test.tsindex 57b876bf..f2e46ecc 100644--- a/packages/provider-whisperx-local/test/service.test.ts+++ b/packages/provider-whisperx-local/test/program.test.ts@@ -3,33 +3,33 @@ import { existsSync } from "node:fs";import { isAbsolute, join } from "node:path";import test from "node:test";-import { localWhisperXService } from "../src/service.js";+import { localWhisperXProgram } from "../src/program.js";const context = (config: Record<string, unknown> = {}) => ({- root: "/tmp", instance: "whisperx.test", config: config as never,+ dataRoot: "/tmp", instance: "whisperx.test", config: config as never,});test("the Provider declares how to bring WhisperX up and how to recognise it", () => {- const service = localWhisperXService(context());- assert.equal(service.id, "whisperx");- assert.equal(service.start?.command, "uv");- assert.equal(service.start?.args.at(-1), "svml-whisperx-service");- assert.equal(service.prepare?.args.at(-1), "svml-whisperx-prepare");+ const program = localWhisperXProgram(context());+ assert.equal(program.id, "whisperx");+ assert.equal(program.start?.command, "uv");+ assert.equal(program.start?.args.at(-1), "svml-whisperx-service");+ assert.equal(program.prepare?.args.at(-1), "svml-whisperx-prepare");// Absolute: a Runtime root is wherever the Profile lives, not where the// pinned uv project lives.- const project = service.start?.args.at(-3) ?? "";+ const project = program.start?.args.at(-3) ?? "";assert.ok(isAbsolute(project), `${project} must be absolute`);assert.ok(existsSync(join(project, "pyproject.toml")), `${project} must be the pinned uv project`);});test("a deployment that installs WhisperX elsewhere overrides the command", () => {- const service = localWhisperXService(context({ serviceCommand: ["conda", "run", "whisperx-serve"] }));- assert.deepEqual(service.start, { command: "conda", args: ["run", "whisperx-serve"] });- assert.equal(service.prepare, undefined);+ const program = localWhisperXProgram(context({ serviceCommand: ["conda", "run", "whisperx-serve"] }));+ assert.deepEqual(program.start, { command: "conda", args: ["run", "whisperx-serve"] });+ assert.equal(program.prepare, undefined);});test("custom prepare and probe-only deployments do not inherit managed lifecycle commands", () => {- const prepared = localWhisperXService(context({ servicePrepareCommand: ["make", "models"] }));+ const prepared = localWhisperXProgram(context({ servicePrepareCommand: ["make", "models"] }));assert.deepEqual(prepared.prepare, { command: "make", args: ["models"] });assert.equal(prepared.start, undefined);});@@ -46,7 +46,7 @@ test("a program answering with another identity is reported, never used", asyncpunktTabDigest: "sha256:" + "0".repeat(64),}), { status: 200 })) as typeof fetch;try {- const state = await localWhisperXService(context()).probe();+ const state = await localWhisperXProgram(context()).probe();assert.equal(state.state, "mismatch");assert.match(state.state === "mismatch" ? state.detail : "", /model is large-v3, expected small/u);} finally {@@ -58,7 +58,7 @@ test("nothing answering is down, not a mismatch", async () => {const original = globalThis.fetch;globalThis.fetch = (async () => { throw new Error("ECONNREFUSED"); }) as typeof fetch;try {- const state = await localWhisperXService(context({ baseUrl: "http://127.0.0.1:9" })).probe();+ const state = await localWhisperXProgram(context({ baseUrl: "http://127.0.0.1:9" })).probe();assert.equal(state.state, "down");} finally {globalThis.fetch = original;diff --git a/packages/provider-whisperx-local/test/provider.test.ts b/packages/provider-whisperx-local/test/provider.test.tsindex bb817261..c5ef9054 100644--- a/packages/provider-whisperx-local/test/provider.test.ts+++ b/packages/provider-whisperx-local/test/provider.test.ts@@ -1,4 +1,3 @@-import { createServer } from "node:http";import { readFile } from "node:fs/promises";import test from "node:test";import { sealSpeechEvidenceAudio, speechTypes } from "@narratage/speech";@@ -80,11 +79,11 @@ test("wire seconds are lowered once to exact evidence samples without authored Stest("local Provider stages canonical evidence bytes unchanged and returns sealed alignment evidence", async () => {const expected = wav(32_000);let stagedMatches = false;- const server = createServer((request, response) => {- void (async () => {- if (request.url === "/health") {- response.setHeader("content-type", "application/json");- response.end(JSON.stringify({+ const originalFetch = globalThis.fetch;+ globalThis.fetch = (async (input, init) => {+ const url = String(input);+ if (url.endsWith("/health")) {+ return new Response(JSON.stringify({ok: true,protocol: "svml.whisperx-service@1",serviceVersion: "0.1.0",@@ -94,34 +93,22 @@ test("local Provider stages canonical evidence bytes unchanged and returns sealecompute: "int8",batchSize: 8,punktTabDigest: "e57f64187974277726a3417ca6f181ec5403676c717672eef6a748a7b20e0106",- }));- return;- }- assert.equal(request.url, "/transcribe");- const chunks: Buffer[] = [];- for await (const chunk of request) chunks.push(Buffer.from(chunk));- const body = JSON.parse(Buffer.concat(chunks).toString("utf8")) as { readonly audio_path: string };- stagedMatches = Buffer.compare(Buffer.from(await readFile(body.audio_path)), Buffer.from(expected)) === 0;- response.setHeader("content-type", "application/json");- response.end(JSON.stringify({- language: "en",- segments: [{ start: 0, end: 2, words: [- { text: "hello", start: 0.1, end: 0.4 },- { text: "world", start: 1.2, end: 1.6 },- ] }],- }));- })().catch((error: unknown) => {- response.statusCode = 500;- response.end(String(error));- });- });- await new Promise<void>((resolve, reject) => {- server.once("error", reject);- server.listen(0, "127.0.0.1", resolve);- });+ }), { headers: { "content-type": "application/json" } });+ }+ assert.ok(url.endsWith("/transcribe"));+ const requestBody = init?.body;+ if (typeof requestBody !== "string") throw new Error("WhisperX request body is not JSON text");+ const body = JSON.parse(requestBody) as { readonly audio_path: string };+ stagedMatches = Buffer.compare(Buffer.from(await readFile(body.audio_path)), Buffer.from(expected)) === 0;+ return new Response(JSON.stringify({+ language: "en",+ segments: [{ start: 0, end: 2, words: [+ { text: "hello", start: 0.1, end: 0.4 },+ { text: "world", start: 1.2, end: 1.6 },+ ] }],+ }), { headers: { "content-type": "application/json" } });+ }) as typeof fetch;try {- const address = server.address();- assert(address !== null && typeof address === "object");const artifacts = new MemoryArtifactStore();const artifact = await artifacts.put(expected, "audio/wav");const evidenceAudio = sealSpeechEvidenceAudio({@@ -144,7 +131,7 @@ test("local Provider stages canonical evidence bytes unchanged and returns seale};const registry = new EndpointRegistry();await createLocalWhisperXProvider({- baseUrl: `http://127.0.0.1:${address.port}`,+ baseUrl: "http://127.0.0.1:8765",expectedModel: "small",expectedDevice: "cpu",}).install(registry);@@ -163,6 +150,6 @@ test("local Provider stages canonical evidence bytes unchanged and returns sealeassert.equal((value as { readonly passages?: readonly unknown[] }).passages?.length, 1);assert.equal(speechTypes.evidenceAudio.name, "SpeechEvidenceAudio");} finally {- await new Promise<void>((resolve) => server.close(() => resolve()));+ globalThis.fetch = originalFetch;}});diff --git a/packages/runtime-adapter-node/README.md b/packages/runtime-adapter-node/README.mdindex 89dab5b8..18a8e6df 100644--- a/packages/runtime-adapter-node/README.md+++ b/packages/runtime-adapter-node/README.md@@ -2,8 +2,8 @@Node.js environment helpers for Runtime Adapter implementations.-The package keeps Node-specific filesystem, `PATH` and environment checks out of the host-neutral-`@narratage/runtime-adapter` ABI. It currently provides:+The package keeps Node-specific hosting out of the host-neutral `@narratage/runtime-adapter` ABI. It+defines the Node Runtime Host port loaded by the CLI and also provides:- project-root resolution for configured relative executable paths;- executable availability diagnostics for absolute, relative and `PATH` commands;@@ -11,3 +11,7 @@ The package keeps Node-specific filesystem, `PATH` and environment checks out ofThese functions produce `RuntimeDoctorDiagnostic` values only. They do not construct Endpoints,read secret values, execute commands or choose fallback Providers.++`loadNodeRuntimeHost()` reads only the Runtime Profile header, verifies the separately locked package+selected by `runtime.use`, and opens its Host facet. The selected package then owns Runtime assembly,+lifecycle and storage. The generic CLI never imports `@narratage/local` or assumes a local Worker.diff --git a/packages/runtime-adapter-node/package.json b/packages/runtime-adapter-node/package.jsonindex 83e7e877..c94fbaf7 100644--- a/packages/runtime-adapter-node/package.json+++ b/packages/runtime-adapter-node/package.json@@ -8,6 +8,11 @@".": "./src/index.ts"},"dependencies": {- "@narratage/runtime-adapter": "workspace:*"+ "@narratage/host": "workspace:*",+ "@narratage/package-loader-node": "workspace:*",+ "@narratage/protocol": "workspace:*",+ "@narratage/runtime": "workspace:*",+ "@narratage/runtime-adapter": "workspace:*",+ "@narratage/workspace": "workspace:*"}}diff --git a/packages/runtime-adapter-node/src/index.ts b/packages/runtime-adapter-node/src/index.tsindex 90b3a71e..6b4c1a43 100644--- a/packages/runtime-adapter-node/src/index.ts+++ b/packages/runtime-adapter-node/src/index.ts@@ -1,9 +1,273 @@-import { access } from "node:fs/promises";+import { access, readFile } from "node:fs/promises";import { constants } from "node:fs";-import { delimiter, isAbsolute, resolve } from "node:path";+import { delimiter, dirname, isAbsolute, resolve } from "node:path";+import type { HostFacet } from "@narratage/host";+import {+ loadNodePackageSelection,+} from "@narratage/package-loader-node";+import type {+ LoadedNodePackageSet,+ NodePackageSelectionRequest,+} from "@narratage/package-loader-node";+import type { ArtifactAttachment } from "@narratage/workspace";+import type { BuildState, CanonicalValue, CapabilityRef, Digest } from "@narratage/protocol";+import type {+ BuildCatalogDescriptor,+ BuildCatalogEntry,+ BuildDispatchSnapshot,+ BuildSnapshot,+ CapacityReservation,+ CredentialRef,+ OperationSnapshot,+ RuntimeWorkerRunOptions,+} from "@narratage/runtime";import type { RuntimeDoctorDiagnostic } from "@narratage/runtime-adapter";+export const nodeRuntimeHostAdapterAbi = "svml.node-runtime-host-adapter@1";++export type RuntimeHostBuildSubmission = {+ readonly id: string;+ readonly state: BuildState;+ readonly status: "queued" | "running" | "waiting" | "blocked" | "settling" | "complete" | "failed" | "cancelled";+ readonly dispatch: BuildDispatchSnapshot;+};++export type RuntimeHostStatus = {+ readonly build: BuildSnapshot | undefined;+ readonly catalog: BuildCatalogEntry | undefined;+ readonly operations: readonly OperationSnapshot[];+ readonly dispatch: BuildDispatchSnapshot | undefined;+};++export type RuntimeHostCredentialStatus = {+ readonly endpoint: string;+ readonly slot: string;+ readonly label: string;+ readonly kind: "secret" | "json";+ readonly ref: CredentialRef;+ readonly configured: boolean;+ readonly writable: boolean;+};++export type RuntimeHostArtifactGarbageCollection = {+ readonly reachable: readonly Digest[];+ readonly unreachable: readonly Digest[];+ readonly deleted: readonly Digest[];+};++export type RuntimeHostArchive = {+ status(build: string): Promise<RuntimeHostStatus>;+ activity(build: string): Promise<{+ readonly operations: readonly OperationSnapshot[];+ readonly dispatch: BuildDispatchSnapshot | undefined;+ }>;+ queue(): Promise<{+ readonly dispatches: readonly BuildDispatchSnapshot[];+ readonly capacity: readonly CapacityReservation[];+ readonly operations: readonly OperationSnapshot[];+ }>;+ builds(): Promise<readonly BuildCatalogEntry[]>;+ cancel(build: string, reason?: string): Promise<BuildDispatchSnapshot | undefined>;+ close(): void | Promise<void>;+};++export type RuntimeHostArtifactAccess = {+ readArtifact(digest: Digest): Promise<Uint8Array | undefined>;+ openArtifact(digest: Digest): Promise<AsyncIterable<Uint8Array> | undefined>;+ close(): void | Promise<void>;+};++export type RuntimeHostMaintenance = RuntimeHostArchive & RuntimeHostArtifactAccess & {+ garbageCollectArtifacts(options?: { readonly apply?: boolean }): Promise<RuntimeHostArtifactGarbageCollection>;+};++export type RuntimeHostCredentialControl = {+ credentials(endpoint?: string): Promise<readonly RuntimeHostCredentialStatus[]>;+ putCredential(endpoint: string, slot: string, secret: string): Promise<RuntimeHostCredentialStatus>;+ deleteCredential(endpoint: string, slot: string): Promise<{+ readonly deleted: boolean;+ readonly credential: RuntimeHostCredentialStatus;+ }>;+ close(): void | Promise<void>;+};++export type RuntimeHostExecution = RuntimeHostMaintenance & RuntimeHostCredentialControl & {+ build(request: {+ readonly id: string;+ readonly state: BuildState;+ readonly catalog?: BuildCatalogDescriptor;+ readonly attachments?: readonly ArtifactAttachment[];+ }, options?: {+ readonly follow?: boolean;+ readonly pollIntervalMs?: number;+ readonly maxWaitMs?: number;+ readonly signal?: AbortSignal;+ }): Promise<RuntimeHostBuildSubmission>;+ work(options: RuntimeWorkerRunOptions): Promise<void>;+};++export type RuntimeHostDoctorResult = {+ readonly dataRoot: string;+ readonly diagnostics: readonly RuntimeDoctorDiagnostic[];+};++export type ManagedProgramProgress = {+ readonly id: string;+ readonly phase: "checking" | "preparing" | "starting" | "waiting" | "ready";+};++export type ManagedProgramReport = {+ readonly id: string;+ readonly instances: readonly string[];+ readonly action?: "already-running" | "prepared" | "started" | "stopped" | "not-ours" | "nothing-to-stop" | "unchanged";+ readonly state:+ | { readonly state: "ready" }+ | { readonly state: "down"; readonly detail: string }+ | { readonly state: "mismatch"; readonly detail: string };+ readonly detail?: string;+ readonly logPath?: string;+ readonly pid?: number;+};++export type RuntimeWorkerState = {+ readonly state: "running" | "stale" | "stopped";+ readonly profile: string;+ readonly pid?: number;+ readonly startedAt?: number;+ readonly profileDigest?: string;+ readonly currentProfileDigest?: string;+ readonly logPath: string;+};++export type RuntimeController = {+ readonly profile: string;+ readonly dataRoot: string;+ revision(): Promise<string>;+ readonly worker: {+ up(options?: { readonly maxWaitMs?: number }): Promise<RuntimeWorkerState>;+ status(): Promise<RuntimeWorkerState>;+ logs(): Promise<{ readonly path: string; readonly text: string }>;+ down(options?: { readonly maxWaitMs?: number }): Promise<RuntimeWorkerState>;+ };+ readonly programs: {+ up(options: {+ readonly maxWaitMs?: number;+ readonly onProgress?: (event: ManagedProgramProgress) => void;+ readonly capabilities?: readonly CapabilityRef[];+ }): Promise<{ readonly dataRoot: string; readonly programs: readonly ManagedProgramReport[] }>;+ down(): Promise<{ readonly dataRoot: string; readonly programs: readonly ManagedProgramReport[] }>;+ report(): Promise<{ readonly dataRoot: string; readonly programs: readonly ManagedProgramReport[] }>;+ };+};++export type RuntimeWorkerLaunch = {+ readonly command: string;+ readonly args: readonly string[];+};++export type NodeRuntimeHost = {+ readonly profile: string;+ resolvePackages(): Promise<{+ readonly runtimePackageLock?: string;+ readonly packageRoot?: string;+ readonly runtimeDataRoot?: string;+ readonly runtimeSelection?: NodePackageSelectionRequest;+ }>;+ controller(options?: {+ readonly workspaceRoot?: string;+ readonly packageLock?: string;+ readonly packageRoot?: string;+ }): Promise<RuntimeController>;+ createRuntime(options?: { readonly implementationPackages?: LoadedNodePackageSet }): Promise<RuntimeHostExecution>;+ openArchive(options?: { readonly readOnly?: boolean }): Promise<RuntimeHostArchive>;+ openArtifacts(options?: { readonly readOnly?: boolean }): Promise<RuntimeHostArtifactAccess>;+ openMaintenance(options?: { readonly readOnly?: boolean }): Promise<RuntimeHostMaintenance>;+ openCredentials(endpoint: string): Promise<RuntimeHostCredentialControl>;+ doctor(options?: {+ readonly capabilities?: readonly CapabilityRef[];+ readonly implementationPackages?: LoadedNodePackageSet;+ }): Promise<RuntimeHostDoctorResult>;+ runWorker(readyFile: string, options?: {+ readonly implementationPackages?: LoadedNodePackageSet;+ }): Promise<void>;+};++export type NodeRuntimeHostAdapterContext = {+ readonly profile: string;+ readonly profileRoot: string;+ readonly packageRoot: string;+ readonly runtimePackageLock: string;+ readonly config: CanonicalValue;+ readonly workerLaunch: RuntimeWorkerLaunch;+};++export type NodeRuntimeHostAdapterFacet = HostFacet & {+ readonly abi: typeof nodeRuntimeHostAdapterAbi;+ readonly offers: readonly [string];+ readonly identity?: never;+ readonly implementation: {+ open(context: NodeRuntimeHostAdapterContext): NodeRuntimeHost | Promise<NodeRuntimeHost>;+ };+};++function nonEmpty(value: unknown, subject: string): string {+ if (typeof value !== "string" || value.trim().length === 0) throw new Error(`${subject} must be a non-empty string`);+ return value;+}++export function createNodeRuntimeHostAdapterFacet(options: {+ readonly use: string;+ readonly open: NodeRuntimeHostAdapterFacet["implementation"]["open"];+}): NodeRuntimeHostAdapterFacet {+ return {+ abi: nodeRuntimeHostAdapterAbi,+ offers: [nonEmpty(options.use, "Runtime Host Adapter use")],+ implementation: { open: options.open },+ };+}++export async function loadNodeRuntimeHost(+ path: string,+ options: { readonly packageRoot: string; readonly workerLaunch: RuntimeWorkerLaunch },+): Promise<NodeRuntimeHost> {+ const profile = resolve(path);+ const profileRoot = dirname(profile);+ const value = JSON.parse(await readFile(profile, "utf8")) as Record<string, unknown>;+ if (value.format !== "narratage.runtime-profile@1") {+ throw new Error("Runtime Profile format must be narratage.runtime-profile@1");+ }+ const runtimePackageLock = resolve(profileRoot, nonEmpty(value.runtimePackageLock, "Runtime Profile runtimePackageLock"));+ const runtime = value.runtime;+ if (runtime === null || typeof runtime !== "object" || Array.isArray(runtime)) {+ throw new Error("Runtime Profile runtime must be an object");+ }+ const record = runtime as Record<string, unknown>;+ const use = nonEmpty(record.use, "Runtime Profile runtime.use");+ const config = (record.config ?? {}) as CanonicalValue;+ const loaded = await loadNodePackageSelection(runtimePackageLock, {+ selected: [],+ logical: [{ abi: nodeRuntimeHostAdapterAbi, name: use }],+ }, options.packageRoot);+ const matches = loaded.packages.flatMap((item) => item.contribution.hostFacets ?? [])+ .filter((facet): facet is NodeRuntimeHostAdapterFacet => facet.abi === nodeRuntimeHostAdapterAbi+ && facet.offers?.includes(use) === true);+ if (matches.length !== 1) throw new Error(`Runtime Host Adapter ${use} must have exactly one implementation`);+ const implementation = matches[0]!.implementation;+ if (implementation === null || typeof implementation !== "object"+ || typeof (implementation as { readonly open?: unknown }).open !== "function") {+ throw new Error(`Runtime Host Adapter ${use} does not implement open()`);+ }+ return await implementation.open({+ profile,+ profileRoot,+ packageRoot: resolve(options.packageRoot),+ runtimePackageLock,+ config,+ workerLaunch: options.workerLaunch,+ });+}+function pathLike(value: string): boolean {return isAbsolute(value) || value.includes("/") || value.includes("\\");}diff --git a/packages/runtime-adapter/README.md b/packages/runtime-adapter/README.mdindex 4560c59d..37b9ad37 100644--- a/packages/runtime-adapter/README.md+++ b/packages/runtime-adapter/README.md@@ -1,25 +1,25 @@# `@narratage/runtime-adapter`Host ABI for turning locked Runtime Profile data into explicitly selected Endpoint and Runtime-service packages.+Component packages.One adapter is addressed by `(kind, use)`:- `endpoint` constructs an external capability Endpoint;-- `runtime-service` constructs a Scheduler, Store or credential service package.+- `runtime-component` constructs a Scheduler, Store or Credential Component package.-The two kinds have separate Host ABIs, so an Endpoint and Runtime service may intentionally share+The two kinds have separate Host ABIs, so an Endpoint and Runtime Component may intentionally shareone `use` spelling. A physical package advertises the logical name through its Host-facet `offers`;the Runtime Profile never has to name that package once the inventory binds the offer.An Endpoint adapter has one pure `activate()` declaration. It parses the selected configuration once-and returns the Endpoint package, optional diagnostics and an optional warm external service. The+and returns the Endpoint package, optional diagnostics and an optional Managed Program. TheEndpoint package is the only source of credentials, capabilities and scheduling facts.Activation must not resolve credentials or environment-sourced deployment values, access the network,start a process or mutate durable state. Environment references are resolved only when the Endpointactually handles a Need; `doctor` may diagnose them explicitly.-Runtime-service adapters retain a separate pure `validate()` gate because constructing SQLite or a+Runtime Component adapters retain a separate pure `validate()` gate because constructing SQLite or aStore can itself mutate deployment state; `doctor()` may diagnose them without calling `create()`.The registry binds adapter implementations to the actual locked package and dependency-closurediff --git a/packages/runtime-adapter/src/index.ts b/packages/runtime-adapter/src/index.tsindex 4c0522cb..1db77f3b 100644--- a/packages/runtime-adapter/src/index.ts+++ b/packages/runtime-adapter/src/index.ts@@ -6,19 +6,19 @@ import type {import type { HostFacet } from "@narratage/host";import { canonicalize, digestOf, isDigest } from "@narratage/protocol";import type { CanonicalValue, Digest } from "@narratage/protocol";-import type { RuntimeServicePackage } from "@narratage/runtime";+import type { RuntimeComponentPackage } from "@narratage/runtime";import { credentialRef } from "@narratage/runtime";import type { CredentialRef } from "@narratage/runtime";export const runtimeEndpointAdapterHostAbi = "svml.runtime-endpoint-adapter-host@1";-export const runtimeServiceAdapterHostAbi = "svml.runtime-service-adapter-host@1";+export const runtimeComponentAdapterHostAbi = "svml.runtime-component-adapter-host@1";-export type RuntimeAdapterKind = "endpoint" | "runtime-service";+export type RuntimeAdapterKind = "endpoint" | "runtime-component";function runtimeAdapterHostAbi(kind: RuntimeAdapterKind):| typeof runtimeEndpointAdapterHostAbi- | typeof runtimeServiceAdapterHostAbi {- return kind === "endpoint" ? runtimeEndpointAdapterHostAbi : runtimeServiceAdapterHostAbi;+ | typeof runtimeComponentAdapterHostAbi {+ return kind === "endpoint" ? runtimeEndpointAdapterHostAbi : runtimeComponentAdapterHostAbi;}type RuntimeAdapterAddress = {@@ -27,10 +27,10 @@ type RuntimeAdapterAddress = {};export type RuntimeAdapterFactoryContext = {- /** Absolute project root resolved from the Runtime Profile document. */- readonly root: string;+ /** Absolute private data root selected by the Runtime adapter. Never a source boundary. */+ readonly dataRoot: string;readonly instance: string;- /** Required for Endpoint adapters; absent for Runtime service adapters. */+ /** Required for Endpoint adapters; absent for Runtime Component adapters. */readonly authority?: string;readonly config: CanonicalValue;/** Observation commands may request adapters to avoid creating durable state. */@@ -45,12 +45,12 @@ export type RuntimeDoctorDiagnostic = {};/** One command this deployment may run on the developer's machine. */-export type RuntimeServiceCommand = {+export type ManagedProgramCommand = {readonly command: string;readonly args: readonly string[];};-export type RuntimeServiceState =+export type ManagedProgramState =| { readonly state: "ready" }| { readonly state: "down"; readonly detail: string }/** Something answers, but not as the configured deployment expects. */@@ -64,11 +64,11 @@ export type RuntimeServiceState =* Need and one Build. `start` is absent when the deployment does not own the* program's lifetime, as with a remote host, leaving `probe` to report on it.*/-export type RuntimeExternalService = {+export type ManagedProgram = {readonly id: string;- probe(): Promise<RuntimeServiceState>;- readonly prepare?: RuntimeServiceCommand;- readonly start?: RuntimeServiceCommand;+ probe(): Promise<ManagedProgramState>;+ readonly prepare?: ManagedProgramCommand;+ readonly start?: ManagedProgramCommand;};/**@@ -77,12 +77,12 @@ export type RuntimeExternalService = {* `activate` may parse configuration and construct handlers, but it must not* resolve credentials or environment-sourced deployment values, access the* network, start a process or mutate durable state. That gives normal execution, `doctor`, credential management and- * service lifecycle one source of truth without making a second manifest just+ * program lifecycle one source of truth without making a second manifest just* for diagnostics.*/export type RuntimeEndpointActivation = {readonly endpoint: EndpointPackage;- readonly externalService?: RuntimeExternalService;+ readonly program?: ManagedProgram;readonly diagnose?: () => readonly RuntimeDoctorDiagnostic[] | Promise<readonly RuntimeDoctorDiagnostic[]>;};@@ -90,17 +90,17 @@ export type RuntimeEndpointAdapterImplementation = {activate(context: RuntimeAdapterFactoryContext): RuntimeEndpointActivation | Promise<RuntimeEndpointActivation>;};-export type RuntimeServiceAdapterImplementation = {+export type RuntimeComponentAdapterImplementation = {/** Pure, closed-data validation. Must not construct a service or touch the environment. */validate(context: RuntimeAdapterFactoryContext): void;- create(context: RuntimeAdapterFactoryContext): RuntimeServicePackage | Promise<RuntimeServicePackage>;+ create(context: RuntimeAdapterFactoryContext): RuntimeComponentPackage | Promise<RuntimeComponentPackage>;doctor?(context: RuntimeAdapterFactoryContext): readonly RuntimeDoctorDiagnostic[] | Promise<readonly RuntimeDoctorDiagnostic[]>;};export type RuntimeAdapterHostFacet = HostFacet & {readonly abi: ReturnType<typeof runtimeAdapterHostAbi>;readonly identity?: never;- readonly implementation: RuntimeEndpointAdapterImplementation | RuntimeServiceAdapterImplementation;+ readonly implementation: RuntimeEndpointAdapterImplementation | RuntimeComponentAdapterImplementation;};export type RuntimeAdapterPackageBinding = {@@ -120,7 +120,7 @@ function assert(condition: unknown, message: string): asserts condition {function address(facet: RuntimeAdapterHostFacet): RuntimeAdapterAddress {const kind = facet.abi === runtimeEndpointAdapterHostAbi? "endpoint"- : facet.abi === runtimeServiceAdapterHostAbi ? "runtime-service" : undefined;+ : facet.abi === runtimeComponentAdapterHostAbi ? "runtime-component" : undefined;assert(kind !== undefined, `Runtime Adapter ${facet.abi} ABI is unsupported`);assert(facet.offers?.length === 1 && facet.offers[0]!.trim().length > 0,"Runtime Adapter must offer exactly one non-empty use name");@@ -142,7 +142,7 @@ function implementation(assert(typeof (value as { validate?: unknown }).validate === "function", `${subject} does not implement validate()`);const doctor = (value as { doctor?: unknown }).doctor;assert(doctor === undefined || typeof doctor === "function", `${subject}.doctor must be a function`);- return value as RuntimeServiceAdapterImplementation;+ return value as RuntimeComponentAdapterImplementation;}export function createRuntimeEndpointAdapterFacet(options: {@@ -158,21 +158,21 @@ export function createRuntimeEndpointAdapterFacet(options: {return facet;}-export function createRuntimeServiceAdapterFacet(options: {+export function createRuntimeComponentAdapterFacet(options: {readonly use: string;- readonly validate: RuntimeServiceAdapterImplementation["validate"];- readonly create: RuntimeServiceAdapterImplementation["create"];- readonly doctor?: RuntimeServiceAdapterImplementation["doctor"];+ readonly validate: RuntimeComponentAdapterImplementation["validate"];+ readonly create: RuntimeComponentAdapterImplementation["create"];+ readonly doctor?: RuntimeComponentAdapterImplementation["doctor"];}): RuntimeAdapterHostFacet {assert(options.use.trim().length > 0, "Runtime Adapter use name is empty");return {- abi: runtimeServiceAdapterHostAbi,+ abi: runtimeComponentAdapterHostAbi,offers: [options.use],implementation: implementation({validate: options.validate,create: options.create,...(options.doctor === undefined ? {} : { doctor: options.doctor }),- }, `Runtime Adapter ${options.use}`, "runtime-service"),+ }, `Runtime Adapter ${options.use}`, "runtime-component"),};}@@ -249,11 +249,11 @@ function bindEndpointPackage(};}-function bindServicePackage(- value: RuntimeServicePackage,+function bindComponentPackage(+ value: RuntimeComponentPackage,adapter: RuntimeAdapterAddress,binding: RuntimeAdapterPackageBinding | undefined,-): RuntimeServicePackage {+): RuntimeComponentPackage {if (binding === undefined) return value;return {...value,@@ -298,14 +298,14 @@ export class RuntimeAdapterRegistry {has(use: string, kind?: RuntimeAdapterKind): boolean {return kind === undefined- ? this.#registrations.has(this.#key(use, "endpoint")) || this.#registrations.has(this.#key(use, "runtime-service"))+ ? this.#registrations.has(this.#key(use, "endpoint")) || this.#registrations.has(this.#key(use, "runtime-component")): this.#registrations.has(this.#key(use, kind));}/*** Validate one selected adapter without constructing it. Missing/kind errors* are diagnostics; adapter-owned configuration errors remain throws so the- * Host can attach the selected instance and service/Endpoint-specific code.+ * Host can attach the selected instance and component/Endpoint-specific code.*/validate(use: string,@@ -319,8 +319,8 @@ export class RuntimeAdapterRegistry {message: `Runtime Adapter ${use} is not registered`,subject: use,}];- assert(kind === "runtime-service", "Endpoint configuration is validated by its activation");- (value.implementation as RuntimeServiceAdapterImplementation).validate(context);+ assert(kind === "runtime-component", "Endpoint configuration is validated by its activation");+ (value.implementation as RuntimeComponentAdapterImplementation).validate(context);return [];}@@ -337,8 +337,8 @@ export class RuntimeAdapterRegistry {`Runtime Endpoint adapter ${use} activation has no Endpoint package`);assert(activation.endpoint.instance.id === context.instance,`Runtime Endpoint adapter ${use} created Endpoint ${activation.endpoint.instance.id} outside configured instance ${context.instance}`);- assert(activation.externalService === undefined || activation.externalService.id.trim().length > 0,- `Runtime Endpoint adapter ${use} external service id is empty`);+ assert(activation.program === undefined || activation.program.id.trim().length > 0,+ `Runtime Endpoint adapter ${use} Managed Program id is empty`);assert(activation.diagnose === undefined || typeof activation.diagnose === "function",`Runtime Endpoint adapter ${use} activation diagnose must be a function`);return {@@ -351,24 +351,24 @@ export class RuntimeAdapterRegistry {return (await this.activateEndpoint(use, context)).endpoint;}- async createService(use: string, context: RuntimeAdapterFactoryContext): Promise<RuntimeServicePackage> {- const value = this.#registrations.get(this.#key(use, "runtime-service"));- assert(value !== undefined, `Runtime service adapter ${use} is not registered`);- const implementation = value.implementation as RuntimeServiceAdapterImplementation;+ async createComponent(use: string, context: RuntimeAdapterFactoryContext): Promise<RuntimeComponentPackage> {+ const value = this.#registrations.get(this.#key(use, "runtime-component"));+ assert(value !== undefined, `Runtime Component adapter ${use} is not registered`);+ const implementation = value.implementation as RuntimeComponentAdapterImplementation;implementation.validate(context);const created = await implementation.create(context);- for (const service of created.services) {+ for (const service of created.components) {assert(service.instance.id === context.instance || service.instance.id.startsWith(`${context.instance}.`),- `Runtime Adapter ${use} created service ${service.instance.id} outside configured namespace ${context.instance}`);+ `Runtime Adapter ${use} created Component ${service.instance.id} outside configured namespace ${context.instance}`);}- return bindServicePackage(created, { use, kind: "runtime-service" }, value.binding);+ return bindComponentPackage(created, { use, kind: "runtime-component" }, value.binding);}async doctor(use: string, kind: RuntimeAdapterKind, context: RuntimeAdapterFactoryContext): Promise<readonly RuntimeDoctorDiagnostic[]> {const value = this.#registrations.get(this.#key(use, kind));if (value === undefined) return [{ severity: "error", code: "RUNTIME_ADAPTER_MISSING", message: `Runtime Adapter ${use} is not registered`, subject: use }];- assert(kind === "runtime-service", "Endpoint diagnostics belong to its activation");- const diagnose = (value.implementation as RuntimeServiceAdapterImplementation).doctor;+ assert(kind === "runtime-component", "Endpoint diagnostics belong to its activation");+ const diagnose = (value.implementation as RuntimeComponentAdapterImplementation).doctor;return diagnose === undefined ? [] : await diagnose(context);}}diff --git a/packages/runtime-adapter/test/registry.test.ts b/packages/runtime-adapter/test/registry.test.tsindex 3043144a..1e124540 100644--- a/packages/runtime-adapter/test/registry.test.ts+++ b/packages/runtime-adapter/test/registry.test.ts@@ -3,7 +3,7 @@ import test from "node:test";import {createRuntimeEndpointAdapterFacet,- createRuntimeServiceAdapterFacet,+ createRuntimeComponentAdapterFacet,isRuntimeAdapterHostFacet,runtimeConfigBoolean,runtimeConfigExact,@@ -14,7 +14,7 @@ import {} from "@narratage/runtime-adapter";import type { RuntimeAdapterFactoryContext } from "@narratage/runtime-adapter";-const context = { root: "/tmp", instance: "one", config: {} };+const context = { dataRoot: "/tmp", instance: "one", config: {} };const endpointPackage = (instance: string) => ({name: instance,manifest: { facets: [] },@@ -32,47 +32,47 @@ const endpoint = (use: string, extra: Record<string, unknown> = {}) =>test("a facet declares which kind it is, and the registry keeps the two apart", () => {const registry = new RuntimeAdapterRegistry();registry.registerFacet(endpoint("example.endpoint"));- registry.registerFacet(createRuntimeServiceAdapterFacet({+ registry.registerFacet(createRuntimeComponentAdapterFacet({use: "example.service",validate() {},create: () => ({}) as never,}));assert.ok(registry.has("example.endpoint", "endpoint"));- assert.equal(registry.has("example.endpoint", "runtime-service"), false);- assert.ok(registry.has("example.service", "runtime-service"));+ assert.equal(registry.has("example.endpoint", "runtime-component"), false);+ assert.ok(registry.has("example.service", "runtime-component"));assert.equal(registry.has("example.service", "endpoint"), false);assert.equal(registry.has("example.absent"), false);});-test("Endpoint and Runtime Service may intentionally share one logical spelling", () => {+test("Endpoint and Runtime Component may intentionally share one logical spelling", () => {const registry = new RuntimeAdapterRegistry();registry.registerFacet(endpoint("example.shared"));- registry.registerFacet(createRuntimeServiceAdapterFacet({+ registry.registerFacet(createRuntimeComponentAdapterFacet({use: "example.shared",validate() {},- create: () => ({ services: [] }) as never,+ create: () => ({ components: [] }) as never,}));assert.ok(registry.has("example.shared", "endpoint"));- assert.ok(registry.has("example.shared", "runtime-service"));+ assert.ok(registry.has("example.shared", "runtime-component"));});-test("asking an Endpoint adapter for a Runtime Service is refused, not coerced", async () => {+test("asking an Endpoint adapter for a Runtime Component is refused, not coerced", async () => {const registry = new RuntimeAdapterRegistry();registry.registerFacet(endpoint("example.endpoint"));- await assert.rejects(async () => await registry.createService("example.endpoint", context));+ await assert.rejects(async () => await registry.createComponent("example.endpoint", context));await assert.rejects(async () => await registry.createEndpoint("example.absent", context));});-test("a Runtime Service adapter cannot escape its configured instance namespace", async () => {+test("a Runtime Component adapter cannot escape its configured instance namespace", async () => {const registry = new RuntimeAdapterRegistry();- registry.registerFacet(createRuntimeServiceAdapterFacet({+ registry.registerFacet(createRuntimeComponentAdapterFacet({use: "example.escaping-service",validate() {},- create: () => ({ services: [{ instance: { id: "someone-else" } }] }) as never,+ create: () => ({ components: [{ instance: { id: "someone-else" } }] }) as never,}));await assert.rejects(- async () => await registry.createService("example.escaping-service", context),+ async () => await registry.createComponent("example.escaping-service", context),/outside configured namespace one/u,);});diff --git a/packages/runtime/README.md b/packages/runtime/README.mdindex 80ed5c73..cdd1e686 100644--- a/packages/runtime/README.md+++ b/packages/runtime/README.md@@ -13,12 +13,12 @@ The first implementation contains:- a recoverable Endpoint lifecycle that creates an Operation before `start`, checkpoints `pending`,calls `resume` after a restart, and records wake, retry, failure and cancellation state;- a narrow `CredentialStore`/`CredentialRef` port that keeps secrets out of framework facts.-- one host-neutral `RuntimeServicePackage` ABI that binds configured Scheduler, BuildStore,+- one host-neutral `RuntimeComponentPackage` ABI that binds configured Scheduler, BuildStore,OperationStore, ArtifactStore and CredentialStore implementations to their exact Manifest facet;- one physical package may expose several separately selected services.+ one physical package may expose several separately selected Components.A Runtime assembly owns the lifecycle of the configured packages passed to it and closes each once.-Selection grants service authority; merely being installed never grants scheduling, storage or+Binding grants Component authority; merely being installed never grants scheduling, storage orcredential authority. These remain trusted deployment packages, not author-importable modules.The Scheduler does not traverse Graphs, choose Candidates, rewrite Needs or accept arbitrary@@ -39,7 +39,7 @@ call the Endpoint again.This package is an environment-neutral reference, not a durable queue. SQLite/filesystem adapters,environment credentials, the local follow loop, Endpoint implementations and`@narratage/endpoint-kit` live in separate packages. The repository already contains KIE, Vertex and-several local media/service Endpoint packages; distributed attempt leases and additional hosted+several local media and external-program Endpoint packages; distributed attempt leases and additional hostedadapters remain deployment work. An Endpoint whose upstream API cannot look up or deduplicate thesupplied Operation id cannot promise exactly-once remote work across the crash window; its`resume(undefined)` must explicitly reconcile that uncertainty.diff --git a/packages/runtime/src/components.ts b/packages/runtime/src/components.tsnew file mode 100644index 00000000..da088391--- /dev/null+++ b/packages/runtime/src/components.ts@@ -0,0 +1,291 @@+import { canonicalize, digestOf, isDigest } from "@narratage/protocol";+import type { CanonicalValue, Digest, ModuleRef } from "@narratage/protocol";++import { CompositeCredentialStore } from "./credentials.js";+import type { CredentialStore } from "./credentials.js";+import type { BuildCatalog } from "./catalog.js";+import type { BuildDispatchStore } from "./dispatch.js";+import type { OperationStore } from "./operations.js";+import {+ RuntimeModuleRegistry,+} from "./profile.js";+import type {+ RuntimeModuleManifest,+ RuntimeProfileInstance,+ RuntimeComponentFacetRole,+} from "./profile.js";+import type {+ ArtifactStore,+ BuildSchedulerFactory,+ BuildStore,+ RuntimeWorkerFactory,+} from "./types.js";++type RuntimeComponentBase<Role extends RuntimeComponentFacetRole, Implementation> = {+ readonly role: Role;+ readonly instance: RuntimeProfileInstance;+ readonly port: Implementation;+};++export type RuntimeSchedulerComponent = RuntimeComponentBase<"scheduler", BuildSchedulerFactory>;+export type RuntimeWorkerComponent = RuntimeComponentBase<"worker", RuntimeWorkerFactory>;+export type RuntimeBuildStoreComponent = RuntimeComponentBase<"build-store", BuildStore>;+export type RuntimeOperationStoreComponent = RuntimeComponentBase<"operation-store", OperationStore>;+export type RuntimeDispatchStoreComponent = RuntimeComponentBase<"dispatch-store", BuildDispatchStore>;+export type RuntimeArtifactStoreComponent = RuntimeComponentBase<"artifact-store", ArtifactStore>;+export type RuntimeCredentialStoreComponent = RuntimeComponentBase<"credential-store", CredentialStore>;++export type RuntimeComponent =+ | RuntimeSchedulerComponent+ | RuntimeWorkerComponent+ | RuntimeBuildStoreComponent+ | RuntimeOperationStoreComponent+ | RuntimeDispatchStoreComponent+ | RuntimeArtifactStoreComponent+ | RuntimeCredentialStoreComponent;++/** One configured deployment package may expose several exact Runtime Components. */+export type RuntimeComponentPackage = {+ readonly manifest: RuntimeModuleManifest;+ readonly components: readonly RuntimeComponent[];+ /** Optional Host-facing index owned by the same durable Build store; never part of Runtime selection. */+ readonly buildCatalog?: BuildCatalog;+ close?(): void | Promise<void>;+};++type RuntimeComponentDefinitionBase<Role extends RuntimeComponentFacetRole, Implementation> = {+ readonly role: Role;+ readonly facet: string;+ readonly instance: string;+ readonly implementation: {+ readonly digest: Digest;+ };+ readonly configuration?: CanonicalValue;+ readonly port: Implementation;+};++export type RuntimeComponentDefinition =+ | RuntimeComponentDefinitionBase<"scheduler", BuildSchedulerFactory>+ | RuntimeComponentDefinitionBase<"worker", RuntimeWorkerFactory>+ | RuntimeComponentDefinitionBase<"build-store", BuildStore>+ | RuntimeComponentDefinitionBase<"operation-store", OperationStore>+ | RuntimeComponentDefinitionBase<"dispatch-store", BuildDispatchStore>+ | RuntimeComponentDefinitionBase<"artifact-store", ArtifactStore>+ | RuntimeComponentDefinitionBase<"credential-store", CredentialStore>;++export type DefineRuntimeComponentPackageOptions = {+ readonly module: ModuleRef;+ readonly components: readonly RuntimeComponentDefinition[];+ /** Host presentation index co-owned with this package's BuildStore, if any. */+ readonly buildCatalog?: BuildCatalog;+ readonly close?: () => void | Promise<void>;+};++export type RuntimeBindings = {+ readonly scheduler: string;+ readonly worker: string;+ readonly stores: {+ readonly build: string;+ readonly operations: string;+ readonly dispatch: string;+ readonly artifacts: string;+ readonly credentials: readonly string[];+ };+};++export type RuntimeComponentAssembly = {+ readonly manifests: readonly RuntimeModuleManifest[];+ readonly instances: readonly RuntimeProfileInstance[];+ readonly scheduler: BuildSchedulerFactory;+ readonly worker: RuntimeWorkerFactory;+ readonly buildStore: BuildStore;+ readonly operationStore: OperationStore;+ readonly dispatchStore: BuildDispatchStore;+ readonly artifactStore: ArtifactStore;+ readonly credentialStore: CredentialStore;+ close(): Promise<void>;+};++function assert(condition: unknown, message: string): asserts condition {+ if (!condition) throw new Error(message);+}++function componentFacetKey(component: RuntimeComponent): string {+ const ref = component.instance.facet;+ return `${ref.module.name}@${ref.module.version}#${ref.name}`;+}++function callable(value: object, name: string, subject: string): void {+ assert(name in value && typeof (value as Record<string, unknown>)[name] === "function",+ `${subject} does not implement ${name}()`);+}++function verifyComponentPort(component: RuntimeComponent): void {+ assert(typeof component.port === "object" && component.port !== null,+ `${component.instance.id} Runtime Component implementation is invalid`);+ switch (component.role) {+ case "scheduler":+ callable(component.port, "create", component.instance.id);+ break;+ case "worker":+ callable(component.port, "create", component.instance.id);+ break;+ case "build-store":+ callable(component.port, "create", component.instance.id);+ callable(component.port, "read", component.instance.id);+ callable(component.port, "compareAndSwap", component.instance.id);+ break;+ case "operation-store":+ callable(component.port, "create", component.instance.id);+ callable(component.port, "read", component.instance.id);+ callable(component.port, "list", component.instance.id);+ callable(component.port, "compareAndSwap", component.instance.id);+ break;+ case "dispatch-store":+ for (const method of [+ "create", "read", "list", "claim", "heartbeat", "release", "finish", "requestCancellation", "wake",+ "acquireCapacity", "heartbeatCapacity", "parkCapacity", "releaseCapacity", "clearCapacity", "listCapacity",+ ]) callable(component.port, method, component.instance.id);+ break;+ case "artifact-store":+ callable(component.port, "put", component.instance.id);+ callable(component.port, "get", component.instance.id);+ callable(component.port, "has", component.instance.id);+ break;+ case "credential-store":+ callable(component.port, "resolve", component.instance.id);+ break;+ }+}++export function defineRuntimeComponentPackage(+ options: DefineRuntimeComponentPackageOptions,+): RuntimeComponentPackage {+ assert(options.module.name.trim().length > 0 && options.module.version.trim().length > 0,+ "Runtime Component module identity is invalid");+ assert(options.components.length > 0, "Runtime Component package is empty");+ const instances = new Set<string>();+ const facets = new Set<string>();+ const components = options.components.map((definition): RuntimeComponent => {+ assert(definition.facet.trim().length > 0, "Runtime Component facet is empty");+ assert(definition.instance.trim().length > 0, "Runtime Component instance is empty");+ assert(!instances.has(definition.instance), `Runtime Component instance ${definition.instance} is duplicated`);+ assert(!facets.has(definition.facet), `Runtime Component facet ${definition.facet} is duplicated`);+ assert(isDigest(definition.implementation.digest), `${definition.instance} implementation digest is invalid`);+ instances.add(definition.instance);+ facets.add(definition.facet);+ return {+ role: definition.role,+ instance: {+ id: definition.instance,+ facet: { module: { ...options.module }, name: definition.facet },+ configurationDigest: digestOf(canonicalize(definition.configuration ?? null)),+ },+ port: definition.port,+ } as RuntimeComponent;+ });+ const manifest: RuntimeModuleManifest = {+ format: "svml.runtime-module@1",+ name: options.module.name,+ version: options.module.version,+ facets: options.components.map((definition) => ({+ name: definition.facet,+ role: definition.role,+ implementation: { ...definition.implementation },+ })),+ };+ const result: RuntimeComponentPackage = {+ manifest,+ components,+ ...(options.buildCatalog === undefined ? {} : { buildCatalog: options.buildCatalog }),+ ...(options.close === undefined ? {} : { close: options.close }),+ };+ verifyRuntimeComponentPackage(result);+ return result;+}++export function verifyRuntimeComponentPackage(value: RuntimeComponentPackage): void {+ const packageName = `${value.manifest.name}@${value.manifest.version}`;+ assert(value.components.length > 0, `${packageName} contains no Runtime Component`);+ const modules = new RuntimeModuleRegistry();+ modules.register(value.manifest);+ const ids = new Set<string>();+ const claimedFacets = new Set<string>();+ for (const component of value.components) {+ assert(component.instance.id.trim().length > 0, `${packageName} Runtime Component instance is empty`);+ assert(!ids.has(component.instance.id), `${packageName} repeats Runtime Component ${component.instance.id}`);+ ids.add(component.instance.id);+ assert(isDigest(component.instance.configurationDigest),+ `${packageName} component ${component.instance.id} configuration digest is invalid`);+ verifyComponentPort(component);+ const resolved = modules.resolve(component.instance.facet);+ assert(resolved !== undefined, `${packageName} component ${component.instance.id} has no Manifest facet`);+ assert(resolved.facet.role === component.role,+ `${packageName} component ${component.instance.id} role differs from its Manifest facet`);+ claimedFacets.add(componentFacetKey(component));+ }+ for (const facet of value.manifest.facets) {+ assert(facet.role !== "capability-endpoint", `${packageName} Runtime Component Manifest contains an Endpoint facet`);+ const key = `${value.manifest.name}@${value.manifest.version}#${facet.name}`;+ assert(claimedFacets.has(key), `${packageName} Manifest facet ${facet.name} has no configured component`);+ }+}++type SelectedRuntimeComponent<Role extends RuntimeComponentFacetRole> = {+ readonly package: RuntimeComponentPackage;+ readonly component: Extract<RuntimeComponent, { readonly role: Role }>;+};++function selectedComponent<Role extends RuntimeComponentFacetRole>(+ components: ReadonlyMap<string, { readonly package: RuntimeComponentPackage; readonly component: RuntimeComponent }>,+ id: string | undefined,+ role: Role,+): SelectedRuntimeComponent<Role> | undefined {+ if (id === undefined) return undefined;+ const selected = components.get(id);+ assert(selected !== undefined, `Runtime Component selection refers to unknown instance ${id}`);+ assert(selected.component.role === role, `Runtime Component ${id} is ${selected.component.role}, not ${role}`);+ return selected as SelectedRuntimeComponent<Role>;+}++/** Resolve exact configured Component instances without giving any package routing authority. */+export function assembleRuntimeComponents(+ packages: readonly RuntimeComponentPackage[],+ selection: RuntimeBindings,+): RuntimeComponentAssembly {+ const components = new Map<string, { readonly package: RuntimeComponentPackage; readonly component: RuntimeComponent }>();+ for (const item of packages) {+ verifyRuntimeComponentPackage(item);+ for (const component of item.components) {+ assert(!components.has(component.instance.id), `Runtime Component instance ${component.instance.id} is configured twice`);+ components.set(component.instance.id, { package: item, component });+ }+ }+ const scheduler = selectedComponent(components, selection.scheduler, "scheduler")!;+ const worker = selectedComponent(components, selection.worker, "worker")!;+ const build = selectedComponent(components, selection.stores.build, "build-store");+ const operations = selectedComponent(components, selection.stores.operations, "operation-store");+ const dispatch = selectedComponent(components, selection.stores.dispatch, "dispatch-store");+ const artifacts = selectedComponent(components, selection.stores.artifacts, "artifact-store");+ const credentialComponents = selection.stores.credentials.map((id) => selectedComponent(components, id, "credential-store")!);+ const selected = [scheduler, worker, build, operations, dispatch, artifacts, ...credentialComponents]+ .filter((item): item is NonNullable<typeof item> => item !== undefined);+ const selectedPackages = [...new Set(selected.map((item) => item.package))];+ let closed = false;+ return {+ manifests: selectedPackages.map((item) => item.manifest),+ instances: selected.map((item) => item.component.instance),+ scheduler: scheduler.component.port,+ worker: worker.component.port,+ buildStore: build!.component.port,+ operationStore: operations!.component.port,+ dispatchStore: dispatch!.component.port,+ artifactStore: artifacts!.component.port,+ credentialStore: new CompositeCredentialStore(credentialComponents.map((item) => item.component.port)),+ async close() {+ if (closed) return;+ closed = true;+ for (const item of [...packages].reverse()) await item.close?.();+ },+ };+}diff --git a/packages/runtime/src/index.ts b/packages/runtime/src/index.tsindex dc345c3d..4065a119 100644--- a/packages/runtime/src/index.ts+++ b/packages/runtime/src/index.ts@@ -47,11 +47,11 @@ export {} from "./profile.js";export type * from "./profile.js";export {- assembleRuntimeServices,- defineRuntimeServicePackage,- verifyRuntimeServicePackage,-} from "./services.js";-export type * from "./services.js";+ assembleRuntimeComponents,+ defineRuntimeComponentPackage,+ verifyRuntimeComponentPackage,+} from "./components.js";+export type * from "./components.js";export { LocalBuildScheduler } from "./scheduler.js";export {isEnumerableBuildStore,diff --git a/packages/runtime/src/profile.ts b/packages/runtime/src/profile.tsindex a4c01c68..eb1fdba6 100644--- a/packages/runtime/src/profile.ts+++ b/packages/runtime/src/profile.ts@@ -18,7 +18,7 @@ export type RuntimeFacetRole =| "credential-store"| "capability-endpoint";-export type RuntimeServiceFacetRole = Exclude<RuntimeFacetRole, "capability-endpoint">;+export type RuntimeComponentFacetRole = Exclude<RuntimeFacetRole, "capability-endpoint">;export type RuntimeFacetRef = {readonly module: ModuleRef;@@ -34,9 +34,9 @@ export type RuntimeCapability = {readonly returns: TypeRef;};-export type RuntimeServiceFacet = {+export type RuntimeComponentFacet = {readonly name: string;- readonly role: RuntimeServiceFacetRole;+ readonly role: RuntimeComponentFacetRole;readonly implementation: RuntimeImplementation;};@@ -56,7 +56,7 @@ export type RuntimeEndpointFacet = {readonly credentialSlots?: readonly string[];};-export type RuntimeFacet = RuntimeServiceFacet | RuntimeEndpointFacet;+export type RuntimeFacet = RuntimeComponentFacet | RuntimeEndpointFacet;/** Static package metadata. Reading it must never execute the implementation it describes. */export type RuntimeModuleManifest = {@@ -98,9 +98,9 @@ export type RuntimeProfile = {};};-export type ResolvedRuntimeService = {+export type ResolvedRuntimeComponent = {readonly id: string;- readonly role: RuntimeServiceFacetRole;+ readonly role: RuntimeComponentFacetRole;readonly facet: RuntimeFacetRef;readonly implementation: RuntimeImplementation;readonly configurationDigest: Digest;@@ -123,7 +123,7 @@ export type ResolvedRuntimeEndpoint = {})[];};-export type ResolvedRuntimeInstance = ResolvedRuntimeService | ResolvedRuntimeEndpoint;+export type ResolvedRuntimeInstance = ResolvedRuntimeComponent | ResolvedRuntimeEndpoint;export type RuntimeClosure = {readonly format: "svml.runtime-closure@1";diff --git a/packages/runtime/src/services.ts b/packages/runtime/src/services.tsdeleted file mode 100644index 0c4178b3..00000000--- a/packages/runtime/src/services.ts+++ /dev/null@@ -1,291 +0,0 @@-import { canonicalize, digestOf, isDigest } from "@narratage/protocol";-import type { CanonicalValue, Digest, ModuleRef } from "@narratage/protocol";--import { CompositeCredentialStore } from "./credentials.js";-import type { CredentialStore } from "./credentials.js";-import type { BuildCatalog } from "./catalog.js";-import type { BuildDispatchStore } from "./dispatch.js";-import type { OperationStore } from "./operations.js";-import {- RuntimeModuleRegistry,-} from "./profile.js";-import type {- RuntimeModuleManifest,- RuntimeProfileInstance,- RuntimeServiceFacetRole,-} from "./profile.js";-import type {- ArtifactStore,- BuildSchedulerFactory,- BuildStore,- RuntimeWorkerFactory,-} from "./types.js";--type RuntimeServiceBase<Role extends RuntimeServiceFacetRole, Service> = {- readonly role: Role;- readonly instance: RuntimeProfileInstance;- readonly service: Service;-};--export type RuntimeSchedulerService = RuntimeServiceBase<"scheduler", BuildSchedulerFactory>;-export type RuntimeWorkerService = RuntimeServiceBase<"worker", RuntimeWorkerFactory>;-export type RuntimeBuildStoreService = RuntimeServiceBase<"build-store", BuildStore>;-export type RuntimeOperationStoreService = RuntimeServiceBase<"operation-store", OperationStore>;-export type RuntimeDispatchStoreService = RuntimeServiceBase<"dispatch-store", BuildDispatchStore>;-export type RuntimeArtifactStoreService = RuntimeServiceBase<"artifact-store", ArtifactStore>;-export type RuntimeCredentialStoreService = RuntimeServiceBase<"credential-store", CredentialStore>;--export type RuntimeService =- | RuntimeSchedulerService- | RuntimeWorkerService- | RuntimeBuildStoreService- | RuntimeOperationStoreService- | RuntimeDispatchStoreService- | RuntimeArtifactStoreService- | RuntimeCredentialStoreService;--/** One configured deployment package may expose several exact Runtime services. */-export type RuntimeServicePackage = {- readonly manifest: RuntimeModuleManifest;- readonly services: readonly RuntimeService[];- /** Optional Host-facing index owned by the same durable Build store; never part of Runtime selection. */- readonly buildCatalog?: BuildCatalog;- close?(): void | Promise<void>;-};--type RuntimeServiceDefinitionBase<Role extends RuntimeServiceFacetRole, Service> = {- readonly role: Role;- readonly facet: string;- readonly instance: string;- readonly implementation: {- readonly digest: Digest;- };- readonly configuration?: CanonicalValue;- readonly service: Service;-};--export type RuntimeServiceDefinition =- | RuntimeServiceDefinitionBase<"scheduler", BuildSchedulerFactory>- | RuntimeServiceDefinitionBase<"worker", RuntimeWorkerFactory>- | RuntimeServiceDefinitionBase<"build-store", BuildStore>- | RuntimeServiceDefinitionBase<"operation-store", OperationStore>- | RuntimeServiceDefinitionBase<"dispatch-store", BuildDispatchStore>- | RuntimeServiceDefinitionBase<"artifact-store", ArtifactStore>- | RuntimeServiceDefinitionBase<"credential-store", CredentialStore>;--export type DefineRuntimeServicePackageOptions = {- readonly module: ModuleRef;- readonly services: readonly RuntimeServiceDefinition[];- /** Host presentation index co-owned with this package's BuildStore, if any. */- readonly buildCatalog?: BuildCatalog;- readonly close?: () => void | Promise<void>;-};--export type RuntimeServiceSelection = {- readonly scheduler: string;- readonly worker: string;- readonly stores: {- readonly build: string;- readonly operations: string;- readonly dispatch: string;- readonly artifacts: string;- readonly credentials: readonly string[];- };-};--export type RuntimeServiceAssembly = {- readonly manifests: readonly RuntimeModuleManifest[];- readonly instances: readonly RuntimeProfileInstance[];- readonly scheduler: BuildSchedulerFactory;- readonly worker: RuntimeWorkerFactory;- readonly buildStore: BuildStore;- readonly operationStore: OperationStore;- readonly dispatchStore: BuildDispatchStore;- readonly artifactStore: ArtifactStore;- readonly credentialStore: CredentialStore;- close(): Promise<void>;-};--function assert(condition: unknown, message: string): asserts condition {- if (!condition) throw new Error(message);-}--function serviceFacetKey(service: RuntimeService): string {- const ref = service.instance.facet;- return `${ref.module.name}@${ref.module.version}#${ref.name}`;-}--function callable(value: object, name: string, subject: string): void {- assert(name in value && typeof (value as Record<string, unknown>)[name] === "function",- `${subject} does not implement ${name}()`);-}--function verifyServicePort(service: RuntimeService): void {- assert(typeof service.service === "object" && service.service !== null,- `${service.instance.id} Runtime service implementation is invalid`);- switch (service.role) {- case "scheduler":- callable(service.service, "create", service.instance.id);- break;- case "worker":- callable(service.service, "create", service.instance.id);- break;- case "build-store":- callable(service.service, "create", service.instance.id);- callable(service.service, "read", service.instance.id);- callable(service.service, "compareAndSwap", service.instance.id);- break;- case "operation-store":- callable(service.service, "create", service.instance.id);- callable(service.service, "read", service.instance.id);- callable(service.service, "list", service.instance.id);- callable(service.service, "compareAndSwap", service.instance.id);- break;- case "dispatch-store":- for (const method of [- "create", "read", "list", "claim", "heartbeat", "release", "finish", "requestCancellation", "wake",- "acquireCapacity", "heartbeatCapacity", "parkCapacity", "releaseCapacity", "clearCapacity", "listCapacity",- ]) callable(service.service, method, service.instance.id);- break;- case "artifact-store":- callable(service.service, "put", service.instance.id);- callable(service.service, "get", service.instance.id);- callable(service.service, "has", service.instance.id);- break;- case "credential-store":- callable(service.service, "resolve", service.instance.id);- break;- }-}--export function defineRuntimeServicePackage(- options: DefineRuntimeServicePackageOptions,-): RuntimeServicePackage {- assert(options.module.name.trim().length > 0 && options.module.version.trim().length > 0,- "Runtime service module identity is invalid");- assert(options.services.length > 0, "Runtime service package is empty");- const instances = new Set<string>();- const facets = new Set<string>();- const services = options.services.map((definition): RuntimeService => {- assert(definition.facet.trim().length > 0, "Runtime service facet is empty");- assert(definition.instance.trim().length > 0, "Runtime service instance is empty");- assert(!instances.has(definition.instance), `Runtime service instance ${definition.instance} is duplicated`);- assert(!facets.has(definition.facet), `Runtime service facet ${definition.facet} is duplicated`);- assert(isDigest(definition.implementation.digest), `${definition.instance} implementation digest is invalid`);- instances.add(definition.instance);- facets.add(definition.facet);- return {- role: definition.role,- instance: {- id: definition.instance,- facet: { module: { ...options.module }, name: definition.facet },- configurationDigest: digestOf(canonicalize(definition.configuration ?? null)),- },- service: definition.service,- } as RuntimeService;- });- const manifest: RuntimeModuleManifest = {- format: "svml.runtime-module@1",- name: options.module.name,- version: options.module.version,- facets: options.services.map((definition) => ({- name: definition.facet,- role: definition.role,- implementation: { ...definition.implementation },- })),- };- const result: RuntimeServicePackage = {- manifest,- services,- ...(options.buildCatalog === undefined ? {} : { buildCatalog: options.buildCatalog }),- ...(options.close === undefined ? {} : { close: options.close }),- };- verifyRuntimeServicePackage(result);- return result;-}--export function verifyRuntimeServicePackage(value: RuntimeServicePackage): void {- const packageName = `${value.manifest.name}@${value.manifest.version}`;- assert(value.services.length > 0, `${packageName} contains no Runtime service`);- const modules = new RuntimeModuleRegistry();- modules.register(value.manifest);- const ids = new Set<string>();- const claimedFacets = new Set<string>();- for (const service of value.services) {- assert(service.instance.id.trim().length > 0, `${packageName} Runtime service instance is empty`);- assert(!ids.has(service.instance.id), `${packageName} repeats Runtime service ${service.instance.id}`);- ids.add(service.instance.id);- assert(isDigest(service.instance.configurationDigest),- `${packageName} service ${service.instance.id} configuration digest is invalid`);- verifyServicePort(service);- const resolved = modules.resolve(service.instance.facet);- assert(resolved !== undefined, `${packageName} service ${service.instance.id} has no Manifest facet`);- assert(resolved.facet.role === service.role,- `${packageName} service ${service.instance.id} role differs from its Manifest facet`);- claimedFacets.add(serviceFacetKey(service));- }- for (const facet of value.manifest.facets) {- assert(facet.role !== "capability-endpoint", `${packageName} Runtime service Manifest contains an Endpoint facet`);- const key = `${value.manifest.name}@${value.manifest.version}#${facet.name}`;- assert(claimedFacets.has(key), `${packageName} Manifest facet ${facet.name} has no configured service`);- }-}--type SelectedRuntimeService<Role extends RuntimeServiceFacetRole> = {- readonly package: RuntimeServicePackage;- readonly service: Extract<RuntimeService, { readonly role: Role }>;-};--function selectedService<Role extends RuntimeServiceFacetRole>(- services: ReadonlyMap<string, { readonly package: RuntimeServicePackage; readonly service: RuntimeService }>,- id: string | undefined,- role: Role,-): SelectedRuntimeService<Role> | undefined {- if (id === undefined) return undefined;- const selected = services.get(id);- assert(selected !== undefined, `Runtime service selection refers to unknown instance ${id}`);- assert(selected.service.role === role, `Runtime service ${id} is ${selected.service.role}, not ${role}`);- return selected as SelectedRuntimeService<Role>;-}--/** Resolve exact configured service instances without giving any package routing authority. */-export function assembleRuntimeServices(- packages: readonly RuntimeServicePackage[],- selection: RuntimeServiceSelection,-): RuntimeServiceAssembly {- const services = new Map<string, { readonly package: RuntimeServicePackage; readonly service: RuntimeService }>();- for (const item of packages) {- verifyRuntimeServicePackage(item);- for (const service of item.services) {- assert(!services.has(service.instance.id), `Runtime service instance ${service.instance.id} is configured twice`);- services.set(service.instance.id, { package: item, service });- }- }- const scheduler = selectedService(services, selection.scheduler, "scheduler")!;- const worker = selectedService(services, selection.worker, "worker")!;- const build = selectedService(services, selection.stores.build, "build-store");- const operations = selectedService(services, selection.stores.operations, "operation-store");- const dispatch = selectedService(services, selection.stores.dispatch, "dispatch-store");- const artifacts = selectedService(services, selection.stores.artifacts, "artifact-store");- const credentialServices = selection.stores.credentials.map((id) => selectedService(services, id, "credential-store")!);- const selected = [scheduler, worker, build, operations, dispatch, artifacts, ...credentialServices]- .filter((item): item is NonNullable<typeof item> => item !== undefined);- const selectedPackages = [...new Set(selected.map((item) => item.package))];- let closed = false;- return {- manifests: selectedPackages.map((item) => item.manifest),- instances: selected.map((item) => item.service.instance),- scheduler: scheduler.service.service,- worker: worker.service.service,- buildStore: build!.service.service,- operationStore: operations!.service.service,- dispatchStore: dispatch!.service.service,- artifactStore: artifacts!.service.service,- credentialStore: new CompositeCredentialStore(credentialServices.map((item) => item.service.service)),- async close() {- if (closed) return;- closed = true;- for (const item of [...packages].reverse()) await item.close?.();- },- };-}diff --git a/packages/runtime/test/services.test.ts b/packages/runtime/test/components.test.tssimilarity index 72%rename from packages/runtime/test/services.test.tsrename to packages/runtime/test/components.test.tsindex 620d2686..58ede1f7 100644--- a/packages/runtime/test/services.test.ts+++ b/packages/runtime/test/components.test.ts@@ -5,26 +5,26 @@ import { digestOf } from "@narratage/protocol";import {MemoryBuildStore,MemoryOperationStore,- assembleRuntimeServices,- defineRuntimeServicePackage,- verifyRuntimeServicePackage,+ assembleRuntimeComponents,+ defineRuntimeComponentPackage,+ verifyRuntimeComponentPackage,} from "@narratage/runtime";-const moduleRef = { name: "example.runtime-services", version: "1" } as const;+const moduleRef = { name: "example.runtime-components", version: "1" } as const;function servicePackage(close?: () => void) {- return defineRuntimeServicePackage({+ return defineRuntimeComponentPackage({module: moduleRef,- services: [+ components: [{role: "scheduler",facet: "scheduler",instance: "scheduler.example",implementation: {- digest: digestOf("example.runtime-services/scheduler@1"),+ digest: digestOf("example.runtime-components/scheduler@1"),},configuration: { algorithm: "fixture" },- service: {+ port: {create() {return { async run() { return []; } };},@@ -35,34 +35,34 @@ function servicePackage(close?: () => void) {facet: "worker",instance: "worker.example",implementation: { digest: digestOf("worker") },- service: { create() { return { async runOnce() { return undefined; }, async run() {} }; } },+ port: { create() { return { async runOnce() { return undefined; }, async run() {} }; } },},{role: "build-store",facet: "build-store",instance: "builds.example",implementation: {- digest: digestOf("example.runtime-services/build-store@1"),+ digest: digestOf("example.runtime-components/build-store@1"),},configuration: { database: "fixture" },- service: new MemoryBuildStore(),+ port: new MemoryBuildStore(),},{role: "operation-store",facet: "operation-store",instance: "operations.example",implementation: {- digest: digestOf("example.runtime-services/operation-store@1"),+ digest: digestOf("example.runtime-components/operation-store@1"),},configuration: { database: "fixture" },- service: new MemoryOperationStore(),+ port: new MemoryOperationStore(),},{role: "dispatch-store",facet: "dispatch-store",instance: "dispatch.example",implementation: { digest: digestOf("dispatch") },- service: Object.fromEntries([+ port: Object.fromEntries(["create", "read", "list", "wake", "claim", "heartbeat", "release", "finish", "requestCancellation","acquireCapacity", "heartbeatCapacity", "parkCapacity", "releaseCapacity", "clearCapacity", "listCapacity",].map((name) => [name, async () => undefined])) as never,@@ -72,7 +72,7 @@ function servicePackage(close?: () => void) {facet: "artifact-store",instance: "artifacts.example",implementation: { digest: digestOf("artifacts") },- service: {+ port: {async put() { throw new Error("unused"); },async get() { return undefined; },async has() { return false; },@@ -83,17 +83,17 @@ function servicePackage(close?: () => void) {facet: "credential-store",instance: "credentials.example",implementation: { digest: digestOf("credentials") },- service: { async resolve() { return undefined; } },+ port: { async resolve() { return undefined; } },},],...(close === undefined ? {} : { close }),});}-test("one physical Runtime package exposes separately selected Scheduler and Store services", async () => {+test("one physical Runtime package exposes separately selected Scheduler and Store Components", async () => {let closes = 0;const configured = servicePackage(() => { closes += 1; });- const assembly = assembleRuntimeServices([configured], {+ const assembly = assembleRuntimeComponents([configured], {scheduler: "scheduler.example",worker: "worker.example",stores: {@@ -126,11 +126,11 @@ test("one physical Runtime package exposes separately selected Scheduler and Stoassert.equal(closes, 1);});-test("Runtime service configuration is identity-bound and role selection is exact", () => {+test("Runtime Component configuration is identity-bound and role selection is exact", () => {const configured = servicePackage();- assert.ok(configured.services.every((item) => item.instance.configurationDigest !== undefined));+ assert.ok(configured.components.every((item) => item.instance.configurationDigest !== undefined));assert.throws(- () => assembleRuntimeServices([configured], {+ () => assembleRuntimeComponents([configured], {scheduler: "builds.example",worker: "worker.example",stores: {@@ -147,16 +147,16 @@ test("Runtime service configuration is identity-bound and role selection is exacconst tampered = {...configured,manifest: structuredClone(configured.manifest),- services: [...configured.services],+ components: [...configured.components],};(tampered.manifest.facets[1] as { role: "artifact-store" }).role = "artifact-store";- assert.throws(() => verifyRuntimeServicePackage(tampered), /role differs/u);+ assert.throws(() => verifyRuntimeComponentPackage(tampered), /role differs/u);const missingPort = {...configured,- services: configured.services.map((service) => service.role === "build-store"- ? { ...service, service: {} as never }- : service),+ components: configured.components.map((component) => component.role === "build-store"+ ? { ...component, port: {} as never }+ : component),};- assert.throws(() => verifyRuntimeServicePackage(missingPort), /does not implement create/u);+ assert.throws(() => verifyRuntimeComponentPackage(missingPort), /does not implement create/u);});diff --git a/packages/store-sqlite/README.md b/packages/store-sqlite/README.mdindex 20f97d26..9b62bd9a 100644--- a/packages/store-sqlite/README.md+++ b/packages/store-sqlite/README.md@@ -15,8 +15,8 @@ Artifacts and credentials never enter this database. The adapter owns its privatschema `6`; Core and Endpoint packages do not import SQLite. Incompatible development databases arerejected and recreated explicitly instead of carrying migration code before the first release.-`createSqliteRuntimeServicePackage()` returns one physical package with three separately selectable-execution services plus a Host-only `catalog` handle. They share one connection and one close-lifecycle. The catalog is deliberately absent from the Runtime service Manifest and Runtime+`createSqliteRuntimeComponentPackage()` returns one physical package with three separately selectable+execution Components plus a Host-only `catalog` handle. They share one connection and one close+lifecycle. The catalog is deliberately absent from the Runtime Component Manifest and RuntimeClosure; changing the Host-only catalog table therefore cannot change the identity under which anactive Build continues.diff --git a/packages/store-sqlite/src/activation.ts b/packages/store-sqlite/src/activation.tsindex 1b56c5d4..d9dfd01e 100644--- a/packages/store-sqlite/src/activation.ts+++ b/packages/store-sqlite/src/activation.ts@@ -1,5 +1,5 @@import {- createRuntimeServiceAdapterFacet,+ createRuntimeComponentAdapterFacet,runtimeConfigExact,runtimeConfigObject,runtimeConfigPositiveInteger,@@ -7,7 +7,7 @@ import {} from "@narratage/runtime-adapter";import { resolve } from "node:path";-const sqliteStateAdapter = createRuntimeServiceAdapterFacet({+const sqliteStateAdapter = createRuntimeComponentAdapterFacet({use: "@narratage/store-sqlite",validate(context) {const config = runtimeConfigObject(context.config, "SQLite Runtime state");@@ -19,9 +19,9 @@ const sqliteStateAdapter = createRuntimeServiceAdapterFacet({const config = runtimeConfigObject(context.config, "SQLite Runtime state");const path = runtimeConfigString(config.path, "SQLite path");if (path === undefined) throw new Error("SQLite path is required");- const { createSqliteRuntimeServicePackage } = await import("./store.js");- return createSqliteRuntimeServicePackage({- path: resolve(context.root, path),+ const { createSqliteRuntimeComponentPackage } = await import("./store.js");+ return createSqliteRuntimeComponentPackage({+ path: resolve(context.dataRoot, path),buildInstance: `${context.instance}.builds`,operationInstance: `${context.instance}.operations`,dispatchInstance: `${context.instance}.dispatch`,diff --git a/packages/store-sqlite/src/index.ts b/packages/store-sqlite/src/index.tsindex a09490c8..7bee0822 100644--- a/packages/store-sqlite/src/index.ts+++ b/packages/store-sqlite/src/index.ts@@ -1,6 +1,6 @@export {SqliteRuntimeState,- createSqliteRuntimeServicePackage,+ createSqliteRuntimeComponentPackage,sqliteBuildStoreImplementationDigest,sqliteDispatchStoreImplementationDigest,sqliteOperationStoreImplementationDigest,diff --git a/packages/store-sqlite/src/store.ts b/packages/store-sqlite/src/store.tsindex 4af50240..3bb4cc2e 100644--- a/packages/store-sqlite/src/store.ts+++ b/packages/store-sqlite/src/store.ts@@ -16,7 +16,7 @@ import {sameBuildCatalogDescriptor,verifyBuildCatalogDescriptor,verifyBuildCatalogEntry,- defineRuntimeServicePackage,+ defineRuntimeComponentPackage,capacityReservationId,verifyBuildDispatchIdentity,verifyBuildDispatchSnapshot,@@ -51,7 +51,7 @@ import type {OperationStore,OperationStoreWrite,OperationUpdate,- RuntimeServicePackage,+ RuntimeComponentPackage,} from "@narratage/runtime";const databaseSchemaVersion = 6;@@ -79,7 +79,7 @@ export type SqliteRuntimeStateOptions = {readonly readOnly?: boolean;};-export type CreateSqliteRuntimeServicePackageOptions = SqliteRuntimeStateOptions & {+export type CreateSqliteRuntimeComponentPackageOptions = SqliteRuntimeStateOptions & {readonly path: string;readonly buildInstance?: string;readonly operationInstance?: string;@@ -1018,9 +1018,9 @@ export class SqliteRuntimeState {}}-export function createSqliteRuntimeServicePackage(- options: CreateSqliteRuntimeServicePackageOptions,-): RuntimeServicePackage {+export function createSqliteRuntimeComponentPackage(+ options: CreateSqliteRuntimeComponentPackageOptions,+): RuntimeComponentPackage {const state = new SqliteRuntimeState(options.path, {...(options.busyTimeoutMs === undefined ? {} : { busyTimeoutMs: options.busyTimeoutMs }),...(options.readOnly === undefined ? {} : { readOnly: options.readOnly }),@@ -1029,9 +1029,9 @@ export function createSqliteRuntimeServicePackage(const operationInstance = options.operationInstance ?? "operations.sqlite";const dispatchInstance = options.dispatchInstance ?? "dispatch.sqlite";try {- return defineRuntimeServicePackage({+ return defineRuntimeComponentPackage({module: sqliteStoreModuleRef,- services: [+ components: [{role: "build-store",facet: "build-store",@@ -1044,7 +1044,7 @@ export function createSqliteRuntimeServicePackage(schemaVersion: databaseSchemaVersion,busyTimeoutMs: options.busyTimeoutMs ?? 5_000,},- service: state.builds,+ port: state.builds,},{role: "operation-store",@@ -1058,7 +1058,7 @@ export function createSqliteRuntimeServicePackage(schemaVersion: databaseSchemaVersion,busyTimeoutMs: options.busyTimeoutMs ?? 5_000,},- service: state.operations,+ port: state.operations,},{role: "dispatch-store",@@ -1072,7 +1072,7 @@ export function createSqliteRuntimeServicePackage(schemaVersion: databaseSchemaVersion,busyTimeoutMs: options.busyTimeoutMs ?? 5_000,},- service: state.dispatch,+ port: state.dispatch,},],buildCatalog: state.catalog,diff --git a/packages/store-sqlite/test/store.test.ts b/packages/store-sqlite/test/store.test.tsindex 2c354bd3..fde70174 100644--- a/packages/store-sqlite/test/store.test.ts+++ b/packages/store-sqlite/test/store.test.ts@@ -12,7 +12,7 @@ import {sealOperationIdentity,} from "@narratage/runtime";import {- createSqliteRuntimeServicePackage,+ createSqliteRuntimeComponentPackage,SqliteRuntimeState,} from "@narratage/store-sqlite";@@ -172,9 +172,9 @@ test("SQLite keeps cancellation control independent from execution state", asynctest("Host Catalog schema changes do not change the execution Runtime Closure", async () => {const directory = await mkdtemp(join(tmpdir(), "svml-sqlite-closure-"));try {- const services = createSqliteRuntimeServicePackage({ path: join(directory, "runtime.sqlite") });+ const services = createSqliteRuntimeComponentPackage({ path: join(directory, "runtime.sqlite") });assert.deepEqual(- services.services.map((item) => item.instance.configurationDigest),+ services.components.map((item) => item.instance.configurationDigest),[...Array(3).fill(digestOf({ path: join(directory, "runtime.sqlite"), schemaVersion: 6, busyTimeoutMs: 5_000 })),],diff --git a/packages/video-cli/README.md b/packages/video-cli/README.mdindex e5c8f5ba..41e760c7 100644--- a/packages/video-cli/README.md+++ b/packages/video-cli/README.md@@ -28,18 +28,16 @@ cd path/to/project```From a separate project directory during source development, run-`/path/to/narratage/narratage ...`. The Runtime Profile may point `packageRoot` at the checkout while the-root launcher resolves its own-installed TypeScript loader and CLI, so it neither invokes pnpm nor requires the current directory-to contain Narratage's `package.json`.+`/path/to/narratage/narratage ...`. The root launcher resolves its own TypeScript loader, CLI and+package installation, so it neither invokes pnpm per command nor requires the project directory to+contain Narratage's `package.json`.-`--root` is only the Source Workspace containment boundary. `--asset-root` may additionally admit+`--workspace` is only the Source Workspace containment boundary. `--asset-root` may additionally admitexplicit asset bytes without widening Source imports. `--package-root` is only the Hostoverride used to resolve the installed packages named by a lock; by default this Distribution usesits own installation location. Keeping the two concepts separate lets a video project live outside-this checkout without weakening canonical-path source and asset containment. The official JSON Runtime Profile-has the same optional `packageRoot` override while retaining state and Artifacts under its own-`root`; the generic CLI does not infer that syntax from its suffix.+this checkout without weakening canonical-path source and asset containment. Runtime Profiles do+not contain either Workspace or package-installation overrides.`check` is usable for an Author Source or a complete Run Source. `plan` and `build` require a RunSource because an Author Graph without execution intent is not a Build. The live example executesdiff --git a/packages/video-cli/package.json b/packages/video-cli/package.jsonindex 65f1a904..e727ec46 100644--- a/packages/video-cli/package.json+++ b/packages/video-cli/package.json@@ -10,9 +10,9 @@"dependencies": {"@narratage/cli": "workspace:*","@narratage/compiler-markup-node": "workspace:*",- "@narratage/local": "workspace:*","@narratage/markup": "workspace:*","@narratage/package-loader-node": "workspace:*",+ "@narratage/runtime-adapter-node": "workspace:*","@narratage/workspace-fs-node": "workspace:*"}}diff --git a/packages/video-cli/src/distribution.ts b/packages/video-cli/src/distribution.tsindex cba27ea5..5e9dd353 100644--- a/packages/video-cli/src/distribution.ts+++ b/packages/video-cli/src/distribution.ts@@ -1,4 +1,5 @@import type { CliDistribution } from "@narratage/cli";+import { loadNodeRuntimeHost } from "@narratage/runtime-adapter-node";import { fileURLToPath } from "node:url";import {createVideoCompiler,@@ -6,7 +7,7 @@ import {const packageRoot = import.meta.dirname;-/** Official video authoring and local Runtime-adapter assembly for the generic CLI engine. */+/** Official video authoring assembly for the generic CLI engine. */export const videoCliDistribution: CliDistribution = {packageRoot,bootstrapPackages: [],@@ -15,70 +16,15 @@ export const videoCliDistribution: CliDistribution = {const { discoverVideoSourcePackages } = await import("./package-selection.js");return await discoverVideoSourcePackages(path, options);},- resolveCompilationPackages: async (path) => {- const { runtimeConfigPackageSelection } = await import("@narratage/local/config");- const selection = await runtimeConfigPackageSelection(path, { packageRoot });- return {- root: selection.root,- ...(selection.packageLock === undefined ? {} : { packageLock: selection.packageLock }),- ...(selection.runtimePackageLock === undefined ? {} : { runtimePackageLock: selection.runtimePackageLock }),- packageRoot: selection.packageRoot,- runtimeSelection: selection.runtimeSelection,- };- },- runtimeProfileRevision: async (path) => {- const { runtimeConfigRevision } = await import("@narratage/local/config");- return await runtimeConfigRevision(path);- },- runtimeWorkerLaunch: () => ({- command: process.execPath,- args: [...process.execArgv, fileURLToPath(new URL("./cli.ts", import.meta.url))],- }),- createRuntimeFromConfig: async (path, options) => {- const { createVideoRuntimeFromConfig } = await import("./runtime-config.js");- return await createVideoRuntimeFromConfig(path, packageRoot, options?.implementationPackages);- },- createRuntimeArchiveFromConfig: async (path, options) => {- const { createRuntimeArchiveFromConfig } = await import("@narratage/local/config");- return await createRuntimeArchiveFromConfig(path, {- packageRoot,- ...(options?.readOnly === undefined ? {} : { readOnly: options.readOnly }),- });- },- createRuntimeArtifactAccessFromConfig: async (path, options) => {- const { createRuntimeArtifactAccessFromConfig } = await import("@narratage/local/config");- return await createRuntimeArtifactAccessFromConfig(path, {- packageRoot,- ...(options?.readOnly === undefined ? {} : { readOnly: options.readOnly }),- });- },- createRuntimeMaintenanceFromConfig: async (path, options) => {- const { createRuntimeMaintenanceFromConfig } = await import("@narratage/local/config");- return await createRuntimeMaintenanceFromConfig(path, {- packageRoot,- ...(options?.readOnly === undefined ? {} : { readOnly: options.readOnly }),- });- },- createRuntimeCredentialsFromConfig: async (path, endpoint) => {- const { createRuntimeCredentialsFromConfig } = await import("@narratage/local/config");- return await createRuntimeCredentialsFromConfig(path, endpoint, { packageRoot });- },- doctorRuntimeConfig: async (path, options) => {- const { doctorRuntimeConfig } = await import("@narratage/local/config");- return await doctorRuntimeConfig(path, { packageRoot, ...options });- },- externalServices: {- up: async (path, options) => {- const { bringExternalServicesUp } = await import("@narratage/local/external-services");- return await bringExternalServicesUp(path, { ...options, packageRoot });- },- down: async (path) => {- const { takeExternalServicesDown } = await import("@narratage/local/external-services");- return await takeExternalServicesDown(path, { packageRoot });+ openRuntimeHost: async (path) => await loadNodeRuntimeHost(path, {+ packageRoot,+ workerLaunch: {+ command: process.execPath,+ // A test runner's --test flags must never leak into the detached CLI.+ args: [+ ...process.execArgv.filter((item) => !item.startsWith("--test")),+ fileURLToPath(new URL("./cli.ts", import.meta.url)),+ ],},- report: async (path) => {- const { reportExternalServices } = await import("@narratage/local/external-services");- return await reportExternalServices(path, { packageRoot });- },- },+ }),};diff --git a/packages/video-cli/src/index.ts b/packages/video-cli/src/index.tsindex 297df42f..30a4180e 100644--- a/packages/video-cli/src/index.ts+++ b/packages/video-cli/src/index.ts@@ -14,11 +14,6 @@ export {} from "./compiler.js";export { videoCliDistribution } from "./distribution.js";-export async function createVideoRuntimeFromConfig(path: string) {- const implementation = await import("./runtime-config.js");- return await implementation.createVideoRuntimeFromConfig(path);-}-export function runVideoCli(argv: readonly string[],io: CliIo,diff --git a/packages/video-cli/src/runtime-config.ts b/packages/video-cli/src/runtime-config.tsdeleted file mode 100644index 9a4283a8..00000000--- a/packages/video-cli/src/runtime-config.ts+++ /dev/null@@ -1,17 +0,0 @@-import { createRuntimeFromConfig } from "@narratage/local";-import type { LoadedNodePackageSet } from "@narratage/package-loader-node";--/**- * Video CLI assembly adds no privileged Provider registry. The Runtime Profile selects- * locked Runtime Adapter packages, so installing a new adapter never changes this CLI.- */-export async function createVideoRuntimeFromConfig(- path: string,- packageRoot = import.meta.dirname,- implementationPackages?: LoadedNodePackageSet,-) {- return await createRuntimeFromConfig(path, {- packageRoot,- ...(implementationPackages === undefined ? {} : { implementationPackages }),- });-}diff --git a/packages/video-cli/test/cli.test.ts b/packages/video-cli/test/cli.test.tsindex fb5d74be..a1234ae7 100644--- a/packages/video-cli/test/cli.test.ts+++ b/packages/video-cli/test/cli.test.ts@@ -298,33 +298,39 @@ test("CLI delegates a declarative Runtime Profile by content, not filename suffi], process.cwd()),);await writeFile(profile, JSON.stringify({- format: "svml.runtime-config@1",- root,+ format: "narratage.runtime-profile@1",runtimePackageLock,- runtimeServices: [- { use: "@narratage/local", instance: "execution" },- { use: "@narratage/store-sqlite", instance: "state", config: { path: "state.sqlite" } },- { use: "@narratage/artifact-store-fs", instance: "artifacts", config: { path: "artifacts" } },- { use: "@narratage/credential-store-env", instance: "credentials", config: {} },- ],- services: {- scheduler: "execution.scheduler",- worker: "execution.worker",- stores: {- build: "state.builds",- operations: "state.operations",- dispatch: "state.dispatch",- artifacts: "artifacts",- credentials: ["credentials"],+ runtime: {+ use: "@narratage/local",+ config: {+ dataRoot: ".",+ components: {+ execution: { use: "@narratage/local" },+ state: { use: "@narratage/store-sqlite", config: { path: "state.sqlite" } },+ artifacts: { use: "@narratage/artifact-store-fs", config: { path: "artifacts" } },+ credentials: { use: "@narratage/credential-store-env", config: {} },+ },+ bindings: {+ scheduler: "execution.scheduler",+ worker: "execution.worker",+ stores: {+ build: "state.builds",+ operations: "state.operations",+ dispatch: "state.dispatch",+ artifacts: "artifacts",+ credentials: ["credentials"],+ },+ },+ endpoints: {+ "kie.cli-test": {+ use: "@narratage/provider-kie",+ authority: "kie.cli-test",+ config: { apiKey: { store: "env", key: "SVML_TEST_MISSING_KIE_KEY" }, defaultConcurrency: 2 },+ },+ },+ limits: { maxOperations: 4, resources: { "authority:kie.cli-test": 2 } },},},- endpoints: [{- use: "@narratage/provider-kie",- instance: "kie.cli-test",- authority: "kie.cli-test",- config: { apiKey: { store: "env", key: "SVML_TEST_MISSING_KIE_KEY" }, defaultConcurrency: 2 },- }],- scheduling: { maxConcurrency: 4, resources: { "authority:kie.cli-test": 2 } },}), "utf8");let output = "";await runCli(["status", "missing-build", "--runtime", profile], {@@ -363,7 +369,7 @@ test("one checked-in fixture closes the complete provider-free video plan", asynjoin(fixture, "build.svrun"),"--package-lock",join(fixture, "svml.packages.lock"),- "--root",+ "--workspace",process.cwd(),], { write: (text) => { output += text; } });const plan = (JSON.parse(output) as { readonly plan: {@@ -405,28 +411,32 @@ test("one locked provider-free Build executes the checked-in Frame graph", async"@narratage/artifact-store-fs",], process.cwd()));await writeFile(profile, JSON.stringify({- format: "svml.runtime-config@1",- root: process.cwd(),- packageLock: join(fixture, "svml.packages.lock"),+ format: "narratage.runtime-profile@1",runtimePackageLock,- runtimeServices: [- { use: "@narratage/local", instance: "execution" },- { use: "@narratage/store-sqlite", instance: "state", config: { path: join(runtimeRoot, "state.sqlite") } },- { use: "@narratage/artifact-store-fs", instance: "artifacts", config: { path: join(runtimeRoot, "artifacts") } },- ],- services: {- scheduler: "execution.scheduler",- worker: "execution.worker",- stores: {- build: "state.builds",- operations: "state.operations",- dispatch: "state.dispatch",- artifacts: "artifacts",- credentials: [],+ runtime: {+ use: "@narratage/local",+ config: {+ dataRoot: ".",+ components: {+ execution: { use: "@narratage/local" },+ state: { use: "@narratage/store-sqlite", config: { path: "state.sqlite" } },+ artifacts: { use: "@narratage/artifact-store-fs", config: { path: "artifacts" } },+ },+ bindings: {+ scheduler: "execution.scheduler",+ worker: "execution.worker",+ stores: {+ build: "state.builds",+ operations: "state.operations",+ dispatch: "state.dispatch",+ artifacts: "artifacts",+ credentials: [],+ },+ },+ endpoints: {},+ limits: { maxOperations: 2, resources: {} },},},- endpoints: [],- scheduling: { maxConcurrency: 2, resources: {} },}), "utf8");let output = "";@@ -434,8 +444,9 @@ test("one locked provider-free Build executes the checked-in Frame graph", asyncawait runVideoCli(["build", join(fixture, "frame-smoke.svrun"),"--runtime", profile,+ "--workspace", fixture,"--follow",- "--max-wait-ms", "15000",+ "--max-wait-ms", "60000","--json",], { write: (text) => { output += text; } });const result = JSON.parse(output) as {@@ -828,9 +839,14 @@ test("CLI inspect and get read the durable Build archive independently of buildasync close() {},};const selected = {- runtimeProfileRevision: async () => "test-revision",- createRuntimeArchiveFromConfig: async () => control,- createRuntimeArtifactAccessFromConfig: async () => control,+ openRuntimeHost: async (path: string) => ({+ profile: path,+ openArchive: async () => control,+ openArtifacts: async () => control,+ controller: async () => ({+ worker: { status: async () => ({ state: "stopped", profile: path, logPath: "/tmp/worker.log" }) },+ }),+ }),} as unknown as CliDistribution;const runArchiveCli = (argv: readonly string[],diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 46a16c99..3a3610db 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -456,6 +456,9 @@ importers:'@narratage/runtime':specifier: workspace:*version: link:../runtime+ '@narratage/runtime-adapter-node':+ specifier: workspace:*+ version: link:../runtime-adapter-node'@narratage/source':specifier: workspace:*version: link:../source@@ -1426,6 +1429,9 @@ importers:'@narratage/runtime-adapter':specifier: workspace:*version: link:../runtime-adapter+ '@narratage/runtime-adapter-node':+ specifier: workspace:*+ version: link:../runtime-adapter-node'@narratage/validation':specifier: workspace:*version: link:../validation@@ -2213,9 +2219,24 @@ importers:packages/runtime-adapter-node:dependencies:+ '@narratage/host':+ specifier: workspace:*+ version: link:../host+ '@narratage/package-loader-node':+ specifier: workspace:*+ version: link:../package-loader-node+ '@narratage/protocol':+ specifier: workspace:*+ version: link:../protocol+ '@narratage/runtime':+ specifier: workspace:*+ version: link:../runtime'@narratage/runtime-adapter':specifier: workspace:*version: link:../runtime-adapter+ '@narratage/workspace':+ specifier: workspace:*+ version: link:../workspacepackages/screen-overlay:dependencies:@@ -2695,15 +2716,15 @@ importers:'@narratage/compiler-markup-node':specifier: workspace:*version: link:../compiler-markup-node- '@narratage/local':- specifier: workspace:*- version: link:../local'@narratage/markup':specifier: workspace:*version: link:../markup'@narratage/package-loader-node':specifier: workspace:*version: link:../package-loader-node+ '@narratage/runtime-adapter-node':+ specifier: workspace:*+ version: link:../runtime-adapter-node'@narratage/workspace-fs-node':specifier: workspace:*version: link:../workspace-fs-nodediff --git a/tools/repository-hygiene.test.mjs b/tools/repository-hygiene.test.mjsindex a2e6ed52..d68fea28 100644--- a/tools/repository-hygiene.test.mjs+++ b/tools/repository-hygiene.test.mjs@@ -7,7 +7,7 @@ import ts from "typescript";const repositoryRoot = new URL("../", import.meta.url);const scanRoots = ["docs", "examples", "packages", "services", "test", "tools"];const rootTextFiles = ["README.md", "package.json", "pnpm-workspace.yaml", "tsconfig.json"];-const ignoredDirectories = new Set(["node_modules", "dist", "output", ".svml", ".vitepress"]);+const ignoredDirectories = new Set(["node_modules", "dist", "output", ".narratage", ".svml", ".vitepress"]);const textExtensions = new Set([".css", ".html", ".js", ".json", ".jsx", ".md", ".mjs", ".sh", ".svml", ".svrun",".svs", ".ts", ".tsx", ".txt", ".yaml", ".yml",diff --git a/tools/svml-playground/test/markers.test.ts b/tools/svml-playground/test/markers.test.tsindex f7cf89b3..c60caa63 100644--- a/tools/svml-playground/test/markers.test.ts+++ b/tools/svml-playground/test/markers.test.ts@@ -1,5 +1,5 @@import assert from "node:assert/strict";-import { mkdtempSync, writeFileSync } from "node:fs";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import test from "node:test";@@ -54,15 +54,24 @@ const STYLES = `<?svml using="@narratage/svs@1"?></sheet>`;-async function fixture(): Promise<PlaygroundSnapshot> {- const directory = mkdtempSync(join(tmpdir(), "svml-playground-markers-"));- writeFileSync(join(directory, "main.svml"), SOURCE, "utf8");- writeFileSync(join(directory, "studio.svs"), STYLES, "utf8");- return (await readSource({- source: join(directory, "main.svml"), packageRoot: directory, revision: 1,- })).snapshot;+let fixtureDirectory: string | undefined;+let fixtureSnapshot: Promise<PlaygroundSnapshot> | undefined;++function fixture(): Promise<PlaygroundSnapshot> {+ if (fixtureSnapshot !== undefined) return fixtureSnapshot;+ fixtureDirectory = mkdtempSync(join(tmpdir(), "svml-playground-markers-"));+ writeFileSync(join(fixtureDirectory, "main.svml"), SOURCE, "utf8");+ writeFileSync(join(fixtureDirectory, "studio.svs"), STYLES, "utf8");+ fixtureSnapshot = readSource({+ source: join(fixtureDirectory, "main.svml"), packageRoot: fixtureDirectory, revision: 1,+ }).then((result) => result.snapshot);+ return fixtureSnapshot;}+test.after(() => {+ if (fixtureDirectory !== undefined) rmSync(fixtureDirectory, { recursive: true, force: true });+});+test("a Segment is the outermost level and Selections nest inside it", async () => {const snapshot = await fixture();const segment = snapshot.script!.segments.find((item) => item.id === "opening")!;