Skip to content

armgit / hypit

Public Imported from GitHub
0

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.

refactor: make the local runtime one implementation

kashorin6db26a983a4f
diff --git a/docs/guide/runtime.md b/docs/guide/runtime.md
index ec439533..eec9b30b 100644
--- a/docs/guide/runtime.md
+++ b/docs/guide/runtime.md
@@ -9,35 +9,20 @@ 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
+| Workspace | Which source files and local assets compilation may read |
+| Runtime Profile | Which environmental packages may be used |
+| Local Runtime | How Builds are queued, executed, stored and observed |
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 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.
+`@narratage/runtime-local` is the default execution environment. It owns one Worker, scheduler, Build
+queue and SQLite database. Those are one implementation, not user-selectable pseudo-components.
## Runtime Profile
-A Profile selects one Runtime adapter and gives that adapter closed configuration:
+The Profile contains only environmental choices that genuinely vary:
```json
{
@@ -46,114 +31,65 @@ A Profile selects one Runtime adapter and gives that adapter closed configuratio
"use": "@narratage/runtime-local",
"config": {
"dataRoot": ".narratage/runtimes/local",
- "infrastructure": {
- "execution": { "use": "@narratage/runtime-local" },
- "state": {
- "use": "@narratage/store-sqlite",
- "config": { "path": "state.sqlite" }
- },
- "artifacts": {
- "use": "@narratage/artifact-store-fs",
- "config": { "path": "artifacts" }
- }
+ "artifacts": {
+ "use": "@narratage/artifact-store-fs",
+ "config": { "path": "artifacts" }
},
- "roles": {
- "scheduler": { "from": "execution", "part": "scheduler" },
- "worker": { "from": "execution", "part": "worker" },
- "buildStore": { "from": "state", "part": "builds" },
- "operationStore": { "from": "state", "part": "operations" },
- "dispatchStore": { "from": "state", "part": "dispatch" },
- "artifactStore": { "from": "artifacts", "part": "store" },
- "credentialStores": []
+ "credentials": {
+ "environment": { "use": "@narratage/credential-store-env" }
},
"endpoints": {
"media": { "use": "@narratage/provider-media-local" }
},
- "capacity": { "maxActiveOperations": 4 }
+ "concurrency": 4
}
}
}
```
-`infrastructure` creates named package instances. Each instance may expose several named parts.
-`roles` selects those parts explicitly; installed or configured packages never select themselves.
-`endpoints` configures external capability implementations. `capacity` bounds this Runtime as a whole.
+* `artifacts` selects where generated bytes are stored.
+* `credentials` selects stores for explicit credential references.
+* `endpoints` selects exact Provider implementations and their configuration.
+* `concurrency` bounds commands running in this local Worker process.
-The Profile contains no source root or author package selection. Those belong to the project and
-its Source imports. Relative Profile paths resolve from the Profile file;
-relative local Runtime data paths resolve beneath `dataRoot`.
+Installing a package only makes an implementation available. A Profile must select it. The Profile
+contains no Workspace, author imports or creative routing.
-## Project state
+## Local state
-Selecting a Profile writes one relative pointer:
-
-```text
-.narratage/
- runtime
-```
-
-A project local Runtime normally keeps its private state alongside that pointer:
+Selecting a Profile writes a project pointer. Execution data stays under `dataRoot`:
```text
.narratage/
runtime
runtimes/
local/
- worker/
- state.sqlite
+ runtime.sqlite
artifacts/
+ worker/
+ programs/
```
-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.
+`check` and `plan` do not create Runtime data. SQLite stores Build facts, Operations and queue state;
+Artifact bytes stay in the selected Artifact Store; secrets stay in the selected Credential Stores.
-## Host state
+The Workspace is resolved independently from the explicit `--workspace`, the project containing the
+Runtime pointer, or the entry source directory. Runtime configuration cannot widen source access.
-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` |
+## Queue and concurrency
-`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.
+`build` admits a fresh Build and returns. The Worker may advance multiple Builds concurrently. All of
+them share the Profile's process-wide command limit. Endpoint packages additionally declare Provider
+and model limits, so work from separate Builds still respects one shared external quota.
-## Packages, instances, parts and roles
-
-A Runtime package is installed code. An entry under `infrastructure` creates one configured
-**instance** of that package. The package may expose several cohesive **parts**. For example,
-`@narratage/store-sqlite` exposes `builds`, `operations` and `dispatch` from one `state` instance and
-one database. A **role** selects one exact `{ from, part }` pair:
-
-```json
-"buildStore": { "from": "state", "part": "builds" }
-```
-
-`from` always names a configured instance; `part` is declared by that instance's package. The Host
-validates that the selected part implements the requested role. No central registry knows SQLite,
-and no dotted string is parsed to guess ownership.
-
-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.
-
-Infrastructure and Endpoints are loaded only when the Runtime Profile selects their logical `use`
-names. Installing a package adds an available implementation; it does not alter Core or activate
-itself.
+Cancellation is best effort. Queued work is withdrawn before it starts; running work stops receiving
+new commands and an Endpoint may try to cancel an already submitted external operation. Completed
+output is retained and never rolled back.
## 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 infrastructure 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.
+An Endpoint may declare a long-lived helper such as a warm local WhisperX service. The Endpoint owns
+its probe and optional start command; the local Runtime only supervises it.
```bash
narratage programs status
@@ -161,8 +97,8 @@ 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.
+Program commands load Endpoint packages only. They do not open SQLite, Artifact Stores or Credential
+Stores.
## Lifecycle
@@ -174,31 +110,9 @@ 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 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 imports and Runtime Profile entries are separate selections because they grant different
-authority. Compilation activates the source-selected subset. Runtime activation is limited to the
-adapter closure selected by the Profile. Unfinished Builds retain only the installed package names
-their Worker must load; npm or pnpm owns installed versions and bytes.
+`runtime up` starts the local Worker. `build` submits work; `status`, `queue` and `cancel` observe or
+control it. A terminal Build is not resumed. Reusing an earlier result is an explicit Candidate in a
+new `.svrun`, not hidden Runtime behavior.
-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.
+Runtime packages are trusted local deployment code. npm or pnpm owns their installed versions; the
+Runtime does not implement another package manager or claim that metadata is a sandbox.
diff --git a/docs/zh/guide/runtime.md b/docs/zh/guide/runtime.md
index f70ee0b0..355424a0 100644
--- a/docs/zh/guide/runtime.md
+++ b/docs/zh/guide/runtime.md
@@ -9,25 +9,19 @@ Narratage 把三个决定分开:
| 所有者 | 决定什么 |
|---|---|
-| Workspace | 一次编译能读取哪些 Source 和本地素材 |
-| Runtime Profile | 编译完成的 Build 交给哪个执行环境 |
-| Runtime | Build 如何排队、执行、存储和被观察 |
-
-Runtime Profile 不定义 Workspace。同一 Profile 可以服务多个项目,同一项目也可以在不改
-Author Source 的情况下选择不同 Runtime。
-
-## 边界
+| Workspace | 编译能读取哪些 Source 和本地素材 |
+| Runtime Profile | 允许使用哪些环境包 |
+| Local Runtime | Build 如何排队、执行、保存和被观察 |
Core 是领域无关的状态机。它接收事实、派生 Command、验证 Record,不启动进程、不读取凭证、
不选择 Provider,也不知道 Build 最终是不是视频。
-Runtime 接收已经编译完成的 Build,负责耐久状态、队列、租约、并发、Artifact、凭证、Endpoint、
-Provider 调用和可选的长期运行程序。通用 CLI 只通过 Runtime Controller 与它通信,不假设它是
-本地 Node 进程。本地 Controller 可以管理独立 Worker;远程 Controller 可以通过 HTTP 接收同一份 Build。
+`@narratage/runtime-local` 是默认执行环境。它自己拥有 Worker、调度器、Build 队列和 SQLite。
+这些是同一个本地实现,不再伪装成需要用户逐项选择的组件。
## Runtime Profile
-Profile 选择一个 Runtime 包,并把封闭配置交给它:
+Profile 只保留真正会随环境变化的选择:
```json
{
@@ -36,69 +30,62 @@ Profile 选择一个 Runtime 包,并把封闭配置交给它:
"use": "@narratage/runtime-local",
"config": {
"dataRoot": ".narratage/runtimes/local",
- "infrastructure": {
- "execution": { "use": "@narratage/runtime-local" },
- "state": { "use": "@narratage/store-sqlite", "config": { "path": "state.sqlite" } },
- "artifacts": { "use": "@narratage/artifact-store-fs", "config": { "path": "artifacts" } }
+ "artifacts": {
+ "use": "@narratage/artifact-store-fs",
+ "config": { "path": "artifacts" }
},
- "roles": {
- "scheduler": { "from": "execution", "part": "scheduler" },
- "worker": { "from": "execution", "part": "worker" },
- "buildStore": { "from": "state", "part": "builds" },
- "operationStore": { "from": "state", "part": "operations" },
- "dispatchStore": { "from": "state", "part": "dispatch" },
- "artifactStore": { "from": "artifacts", "part": "store" },
- "credentialStores": []
+ "credentials": {
+ "environment": { "use": "@narratage/credential-store-env" }
},
"endpoints": {
"media": { "use": "@narratage/provider-media-local" }
},
- "capacity": { "maxActiveOperations": 4 }
+ "concurrency": 4
}
}
}
```
-`infrastructure` 创建具名的包实例,`roles` 显式选择实例提供的 part,`endpoints`
-配置外部能力实现,`capacity` 限制整个 Runtime。安装包只增加可用实现,不会自动激活或改变 Core。
+`artifacts` 决定产物字节放在哪里;`credentials` 选择凭证存储;`endpoints` 选择明确的
+Provider 实现;`concurrency` 限制这个本地 Worker 同时执行的 Command 数量。
-Profile 不包含 Source Workspace 或 Author 包选择。相对 Profile 路径从
-Profile 文件解析;本地 Runtime 的私有路径从 `dataRoot` 解析。
+安装包只增加一种可选实现,不会自动激活。Profile 不包含 Workspace、作者 import 或隐藏的
+创作路由。
-## 项目状态与路径
+## 本地状态
+
+选择 Profile 会写入项目指针,执行数据位于 `dataRoot`:
```text
.narratage/
runtime
runtimes/
local/
- worker/
- state.sqlite
+ runtime.sqlite
artifacts/
+ worker/
+ programs/
```
-`runtime use` 只写 `.narratage/runtime` 指针,不启动进程。`check` 和 `plan` 不创建 Runtime 数据。
-`narratage paths` 会报告 Workspace、项目状态、Runtime 数据与操作系统级 Host 状态的位置。
+`check` 和 `plan` 不创建 Runtime 数据。SQLite 保存 Build 事实、Operation 与队列;产物字节进入
+Artifact Store;密钥只留在 Credential Store。
-Workspace 独立按以下顺序确定:显式 `--workspace`、所选 `.narratage/runtime` 所在项目、入口
-Source 目录。Runtime Profile 无权扩大它。
+Workspace 独立由显式 `--workspace`、Runtime 指针所在项目或入口 Source 目录确定。Runtime 配置
+不能扩大源码读取范围。
-## Package、instance、part 与 role
+## 队列与并发
-Runtime 包是已安装代码;`infrastructure` 中的一项创建一个带配置的 instance。一个 instance
-可以公开多个内聚的 part。例如 `@narratage/store-sqlite` 的 `state` instance 从同一个数据库公开
-`builds`、`operations` 和 `dispatch`。role 通过 `{ from, part }` 精确选择其中一个:
+`build` 保存一个全新 Build 后立即返回。Worker 可以并行推进多个 Build,它们共同受 Profile 的
+进程级并发限制。Endpoint 包还会声明 Provider 与模型自身的限制,因此不同 Build 的外部调用仍
+共享同一额度。
-```json
-"buildStore": { "from": "state", "part": "builds" }
-```
+取消是尽力而为:未开始的工作直接撤回;运行中的 Build 不再接收新 Command,Endpoint 可以尝试
+取消已经提交的外部 Operation。已经完成的产物永远保留,不做回滚。
-`from` 只指向 Profile 中的 instance,`part` 只由该包声明。Host 验证这个 part 是否实现所选 role;
-没有中央注册表认识 SQLite,也不会拆解点号字符串来猜归属。Endpoint 则实现声明过的 Capability,
-并负责 Provider 调用。
+## Managed Programs
-Managed Program 是 Endpoint 声明的长期外部进程,例如常驻 WhisperX 服务。它不是 Runtime
-infrastructure,也不是队列。Endpoint 可以声明探测、准备和启动方法;外部托管时只声明探测。
+Endpoint 可以声明 WhisperX 这类需要常驻的辅助程序。Endpoint 提供探测和可选启动命令,本地
+Runtime 只负责管理它。
```bash
narratage programs status
@@ -106,8 +93,7 @@ narratage programs up
narratage programs down
```
-Build 只准备本次所需能力对应的 Program。显式 `programs up` 检查完整 Profile;停止 Runtime
-Worker 不会自动停止可能被共享的 Program。
+这些命令只加载 Endpoint 包,不打开 SQLite、Artifact Store 或 Credential Store。
## 生命周期
@@ -119,8 +105,8 @@ narratage runtime logs
narratage runtime down
```
-这些都是 Controller 操作。`build` 每次提交一个新的 Build id;`--follow` 只负责观察。终态 Build
-不会重新打开,复用已有结果必须由新的 Run Source Candidate 显式表达。
+`runtime up` 启动本地 Worker。`build` 提交任务,`status`、`queue`、`cancel` 用来观察和控制。
+终态 Build 不恢复;复用以前的结果必须在新的 `.svrun` 中显式写 Candidate。
-Source 包和 Runtime 包使用不同锁,因为它们拥有不同权限。目前 Node Runtime 包仍是可信部署代码;
-在真正的进程或 Wasm 隔离完成前,Manifest 和 digest 都不能充当沙箱。
+Runtime 包是本地可信部署代码,其安装版本由 npm 或 pnpm 管理。Runtime 不再实现另一套包管理器,
+也不会把元数据冒充成沙箱。
diff --git a/examples/all-components-preview/narratage.runtime.json b/examples/all-components-preview/narratage.runtime.json
index 37cc78c1..0f147a6e 100644
--- a/examples/all-components-preview/narratage.runtime.json
+++ b/examples/all-components-preview/narratage.runtime.json
@@ -4,20 +4,9 @@
"use": "@narratage/runtime-local",
"config": {
"dataRoot": ".narratage/runtimes/local",
- "infrastructure": {
- "execution": { "use": "@narratage/runtime-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": {} }
- },
- "roles": {
- "scheduler": { "from": "execution", "part": "scheduler" },
- "worker": { "from": "execution", "part": "worker" },
- "buildStore": { "from": "state", "part": "builds" },
- "operationStore": { "from": "state", "part": "operations" },
- "dispatchStore": { "from": "state", "part": "dispatch" },
- "artifactStore": { "from": "artifacts", "part": "store" },
- "credentialStores": [{ "from": "credentials", "part": "store" }]
+ "artifacts": { "use": "@narratage/artifact-store-fs", "config": { "path": "artifacts" } },
+ "credentials": {
+ "environment": { "use": "@narratage/credential-store-env" }
},
"endpoints": {
"kie.all-components": {
@@ -54,7 +43,7 @@
}
}
},
- "capacity": { "maxActiveOperations": 4 }
+ "concurrency": 4
}
}
}
diff --git a/examples/talking-film-live/narratage.runtime.json b/examples/talking-film-live/narratage.runtime.json
index be0a77b6..6aecf71d 100644
--- a/examples/talking-film-live/narratage.runtime.json
+++ b/examples/talking-film-live/narratage.runtime.json
@@ -4,20 +4,9 @@
"use": "@narratage/runtime-local",
"config": {
"dataRoot": ".narratage/runtimes/local",
- "infrastructure": {
- "execution": { "use": "@narratage/runtime-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": {} }
- },
- "roles": {
- "scheduler": { "from": "execution", "part": "scheduler" },
- "worker": { "from": "execution", "part": "worker" },
- "buildStore": { "from": "state", "part": "builds" },
- "operationStore": { "from": "state", "part": "operations" },
- "dispatchStore": { "from": "state", "part": "dispatch" },
- "artifactStore": { "from": "artifacts", "part": "store" },
- "credentialStores": [{ "from": "credentials", "part": "store" }]
+ "artifacts": { "use": "@narratage/artifact-store-fs", "config": { "path": "artifacts" } },
+ "credentials": {
+ "environment": { "use": "@narratage/credential-store-env" }
},
"endpoints": {
"kie.talking-film": {
@@ -48,7 +37,7 @@
"config": { "workers": 2, "quality": "standard", "defaultConcurrency": 1 }
}
},
- "capacity": { "maxActiveOperations": 4 }
+ "concurrency": 4
}
}
}
diff --git a/examples/talking-head-aroll/narratage.runtime.json b/examples/talking-head-aroll/narratage.runtime.json
index 72436d3b..471304af 100644
--- a/examples/talking-head-aroll/narratage.runtime.json
+++ b/examples/talking-head-aroll/narratage.runtime.json
@@ -4,20 +4,9 @@
"use": "@narratage/runtime-local",
"config": {
"dataRoot": ".narratage/runtimes/local",
- "infrastructure": {
- "execution": { "use": "@narratage/runtime-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": {} }
- },
- "roles": {
- "scheduler": { "from": "execution", "part": "scheduler" },
- "worker": { "from": "execution", "part": "worker" },
- "buildStore": { "from": "state", "part": "builds" },
- "operationStore": { "from": "state", "part": "operations" },
- "dispatchStore": { "from": "state", "part": "dispatch" },
- "artifactStore": { "from": "artifacts", "part": "store" },
- "credentialStores": [{ "from": "credentials", "part": "store" }]
+ "artifacts": { "use": "@narratage/artifact-store-fs", "config": { "path": "artifacts" } },
+ "credentials": {
+ "environment": { "use": "@narratage/credential-store-env" }
},
"endpoints": {
"kie.talking-head-aroll": {
@@ -49,7 +38,7 @@
"config": { "workers": 2, "quality": "standard", "defaultConcurrency": 1 }
}
},
- "capacity": { "maxActiveOperations": 4 }
+ "concurrency": 4
}
}
}
diff --git a/packages/artifact-store-fs/README.md b/packages/artifact-store-fs/README.md
index 0c09ead8..8dc232b9 100644
--- a/packages/artifact-store-fs/README.md
+++ b/packages/artifact-store-fs/README.md
@@ -1,11 +1,7 @@
# `@narratage/artifact-store-fs`
-A project-local, content-addressed implementation of the Runtime `ArtifactStore` port.
+Filesystem implementation of the Runtime `ArtifactStore` port. It keeps generated bytes under a
+content-addressed path and exposes streaming reads, writes and explicit garbage collection.
-The path is deployment configuration. Artifact identity is the SHA-256 digest of its bytes, so the
-same adapter can later be replaced by S3 without changing Core, component or Endpoint contracts.
-This package does not store BuildState, Endpoint checkpoints, credentials or author library records.
-
-`createFileArtifactStorePackage()` creates one Runtime infrastructure instance exposing the `store`
-part with the `artifact-store` role. Its absolute root is bound into that instance's identity; the
-Runtime Host does not need filesystem-specific registration code.
+The Runtime Profile selects this package and supplies its path. It stores no Build state, credentials or
+author source. Code embedding the Runtime directly may construct `FileArtifactStore` itself.
diff --git a/packages/artifact-store-fs/src/activation.ts b/packages/artifact-store-fs/src/activation.ts
index 7f8d8e88..b302e48f 100644
--- a/packages/artifact-store-fs/src/activation.ts
+++ b/packages/artifact-store-fs/src/activation.ts
@@ -1,29 +1,26 @@
import { resolve } from "node:path";
import {
- createRuntimeInfrastructureAdapterFacet,
+ createRuntimeArtifactStoreAdapterFacet,
runtimeConfigExact,
runtimeConfigObject,
runtimeConfigString,
} from "@narratage/runtime-kit";
-import { createFileArtifactStorePackage } from "./store.js";
+import { FileArtifactStore } from "./store.js";
-const fileArtifactStoreAdapter = createRuntimeInfrastructureAdapterFacet({
+const fileArtifactStoreAdapter = createRuntimeArtifactStoreAdapterFacet({
use: "@narratage/artifact-store-fs",
validate(context) {
const config = runtimeConfigObject(context.config, "filesystem ArtifactStore");
runtimeConfigExact(config, ["path"], "filesystem ArtifactStore");
if (runtimeConfigString(config.path, "Artifact path") === undefined) throw new Error("Artifact path is required");
},
- create(context) {
+ open(context) {
const config = runtimeConfigObject(context.config, "filesystem ArtifactStore");
const path = runtimeConfigString(config.path, "Artifact path");
if (path === undefined) throw new Error("Artifact path is required");
- return createFileArtifactStorePackage({
- root: resolve(context.dataRoot, path),
- instance: context.instance,
- });
+ return { value: new FileArtifactStore(resolve(context.dataRoot, path)) };
},
});
diff --git a/packages/artifact-store-fs/src/index.ts b/packages/artifact-store-fs/src/index.ts
index 96eab4f7..5d0c094b 100644
--- a/packages/artifact-store-fs/src/index.ts
+++ b/packages/artifact-store-fs/src/index.ts
@@ -1,2 +1,2 @@
-export { FileArtifactStore, createFileArtifactStorePackage, fileArtifactStoreModuleRef } from "./store.js";
+export { FileArtifactStore } from "./store.js";
export type * from "./store.js";
diff --git a/packages/artifact-store-fs/src/store.ts b/packages/artifact-store-fs/src/store.ts
index e0575e23..fe66aaf0 100644
--- a/packages/artifact-store-fs/src/store.ts
+++ b/packages/artifact-store-fs/src/store.ts
@@ -11,18 +11,7 @@ import { dirname, join, resolve } from "node:path";
import { isDigest } from "@narratage/protocol";
import type { BlobRef, Digest } from "@narratage/protocol";
-import { defineRuntimeInfrastructurePackage } from "@narratage/runtime";
-import type { ArtifactStore, RuntimeInfrastructurePackage } from "@narratage/runtime";
-
-export const fileArtifactStoreModuleRef = {
- name: "@narratage/artifact-store-fs",
- version: "1",
-} as const;
-
-export type CreateFileArtifactStorePackageOptions = {
- readonly root: string;
- readonly instance?: string;
-};
+import type { ArtifactStore } from "@narratage/runtime";
function digestPath(root: string, digest: Digest): string {
if (!isDigest(digest)) throw new Error("Artifact digest is invalid");
@@ -177,19 +166,3 @@ export class FileArtifactStore implements ArtifactStore {
}
}
}
-
-export function createFileArtifactStorePackage(
- options: CreateFileArtifactStorePackageOptions,
-): RuntimeInfrastructurePackage {
- const instance = options.instance ?? "artifacts";
- return defineRuntimeInfrastructurePackage({
- module: fileArtifactStoreModuleRef,
- instance,
- parts: [{
- role: "artifact-store",
- part: "store",
- facet: "artifact-store",
- port: new FileArtifactStore(options.root),
- }],
- });
-}
diff --git a/packages/artifact-store-s3/README.md b/packages/artifact-store-s3/README.md
index bc84c3ab..9acd5a05 100644
--- a/packages/artifact-store-s3/README.md
+++ b/packages/artifact-store-s3/README.md
@@ -1,38 +1,13 @@
# `@narratage/artifact-store-s3`
-S3 implementation of the environment-neutral Runtime `ArtifactStore` port.
-
-Objects use deterministic keys:
+S3 implementation of the Runtime `ArtifactStore` port. Objects use:
```text
<prefix>/sha256/<first-two-hex>/<full-hex>
```
-Writes compute the content digest once and store it at the corresponding key. The AWS client also
-exposes the optional streaming and retention facets: streamed writes use multipart upload to an isolated
-staging key followed by a server-side copy to the content-addressed key; `list`/`delete` support
-explicit maintenance.
-
-Those optional facets are attached only when an injected client supplies every operation needed to
-implement them. A reduced test or MinIO client therefore advertises only the capabilities it can
-actually perform instead of failing midway through a Build.
-
-```ts
-const artifacts = createS3ArtifactStorePackage({
- instance: "artifacts.team",
- bucket: "team-narratage-artifacts",
- prefix: "development",
- region: "us-east-1",
- expectedBucketOwner: "123456789012",
-});
-
-// A Runtime Profile creates this as a named infrastructure instance, then selects
-// its `store` part for the `artifactStore` role.
-```
-
-The package exposes only its own `store` part. It never infers or installs the Scheduler, Worker,
-state or Credential Store selected for the other Runtime roles.
+The injected AWS client owns authentication. Multipart upload, streaming reads and retention are exposed
+when that client supports the required S3 operations. The package stores no Build state or credentials.
-The AWS SDK default credential chain or an explicitly injected trusted client owns AWS
-authentication. Secret bytes never enter the package contribution or Runtime Closure; bucket,
-prefix, region, endpoint and account constraint do.
+The Runtime Profile selects its adapter; code embedding the Runtime directly may call
+`createS3ArtifactStore()`.
diff --git a/packages/artifact-store-s3/src/activation.ts b/packages/artifact-store-s3/src/activation.ts
index bac9b0b8..fb2f8ee4 100644
--- a/packages/artifact-store-s3/src/activation.ts
+++ b/packages/artifact-store-s3/src/activation.ts
@@ -1,5 +1,5 @@
import {
- createRuntimeInfrastructureAdapterFacet,
+ createRuntimeArtifactStoreAdapterFacet,
runtimeConfigBoolean,
runtimeConfigExact,
runtimeConfigObject,
@@ -9,7 +9,7 @@ import {
import type { RuntimeAdapterFactoryContext } from "@narratage/runtime-kit";
import { AwsS3ObjectClient } from "./client.js";
-import { createS3ArtifactStorePackage, s3ArtifactKey } from "./store.js";
+import { createS3ArtifactStore, s3ArtifactKey } from "./store.js";
const VALIDATION_DIGEST = "sha256:0000000000000000000000000000000000000000000000000000000000000000" as const;
@@ -31,18 +31,17 @@ function validateConfig(context: RuntimeAdapterFactoryContext): void {
}
}
-const s3ArtifactStoreRuntimeAdapter = createRuntimeInfrastructureAdapterFacet({
+const s3ArtifactStoreRuntimeAdapter = createRuntimeArtifactStoreAdapterFacet({
use: "@narratage/artifact-store-s3",
validate: validateConfig,
- create(context) {
+ open(context) {
const config = runtimeConfigObject(context.config, "S3 ArtifactStore");
runtimeConfigExact(config, [
"bucket", "prefix", "expectedBucketOwner", "region", "endpoint", "forcePathStyle", "partSizeBytes",
], "S3 ArtifactStore");
const bucket = runtimeConfigString(config.bucket, "S3 bucket");
if (bucket === undefined) throw new Error("S3 bucket is required");
- return createS3ArtifactStorePackage({
- instance: context.instance,
+ return { value: createS3ArtifactStore({
bucket,
...(runtimeConfigString(config.prefix, "S3 prefix") === undefined
? {} : { prefix: config.prefix as string }),
@@ -56,7 +55,7 @@ const s3ArtifactStoreRuntimeAdapter = createRuntimeInfrastructureAdapterFacet({
? {} : { forcePathStyle: config.forcePathStyle as boolean }),
...(runtimeConfigPositiveInteger(config.partSizeBytes, "S3 partSizeBytes") === undefined
? {} : { partSizeBytes: config.partSizeBytes as number }),
- });
+ }) };
},
/**
* A bucket that cannot be reached, or is owned by another account, is a
diff --git a/packages/artifact-store-s3/src/index.ts b/packages/artifact-store-s3/src/index.ts
index 8e980aa5..320f35ae 100644
--- a/packages/artifact-store-s3/src/index.ts
+++ b/packages/artifact-store-s3/src/index.ts
@@ -1,4 +1,4 @@
export { AwsS3ObjectClient } from "./client.js";
export type { S3ListPage, S3ObjectClient } from "./client.js";
-export { S3ArtifactStore, createS3ArtifactStorePackage, s3ArtifactKey, s3ArtifactStoreModuleRef } from "./store.js";
+export { S3ArtifactStore, createS3ArtifactStore, s3ArtifactKey, s3ArtifactStoreModuleRef } from "./store.js";
export type * from "./store.js";
diff --git a/packages/artifact-store-s3/src/store.ts b/packages/artifact-store-s3/src/store.ts
index 5ec93d5a..d6dd45c2 100644
--- a/packages/artifact-store-s3/src/store.ts
+++ b/packages/artifact-store-s3/src/store.ts
@@ -2,8 +2,7 @@ import { createHash, randomUUID } from "node:crypto";
import { isDigest } from "@narratage/protocol";
import type { BlobRef, Digest } from "@narratage/protocol";
-import { defineRuntimeInfrastructurePackage } from "@narratage/runtime";
-import type { ArtifactStore, RuntimeInfrastructurePackage } from "@narratage/runtime";
+import type { ArtifactStore } from "@narratage/runtime";
import { AwsS3ObjectClient } from "./client.js";
import type { S3ListPage, S3ObjectClient } from "./client.js";
@@ -311,11 +310,9 @@ export class S3ArtifactStore implements ArtifactStore {
}
}
-export function createS3ArtifactStorePackage(
+export function createS3ArtifactStore(
options: CreateS3ArtifactStorePackageOptions,
-): RuntimeInfrastructurePackage {
- const instance = options.instance ?? "artifacts";
- assert(instance.trim().length > 0, "S3 ArtifactStore instance id must not be empty");
+): S3ArtifactStore {
const prefix = normalizePrefix(options.prefix);
const configuration = {
bucket: options.bucket,
@@ -331,22 +328,13 @@ export function createS3ArtifactStorePackage(
...(options.endpoint === undefined ? {} : { endpoint: options.endpoint }),
...(options.forcePathStyle === undefined ? {} : { forcePathStyle: options.forcePathStyle }),
});
- return defineRuntimeInfrastructurePackage({
- module: s3ArtifactStoreModuleRef,
- instance,
- parts: [{
- role: "artifact-store",
- part: "store",
- facet: "artifact-store",
- port: new S3ArtifactStore({
- client,
- bucket: options.bucket,
- ...(options.partSizeBytes === undefined ? {} : { partSizeBytes: options.partSizeBytes }),
- ...(prefix.length === 0 ? {} : { prefix }),
- ...(options.expectedBucketOwner === undefined
- ? {}
- : { expectedBucketOwner: options.expectedBucketOwner }),
- }),
- }],
+ return new S3ArtifactStore({
+ client,
+ bucket: options.bucket,
+ ...(options.partSizeBytes === undefined ? {} : { partSizeBytes: options.partSizeBytes }),
+ ...(prefix.length === 0 ? {} : { prefix }),
+ ...(options.expectedBucketOwner === undefined
+ ? {}
+ : { expectedBucketOwner: options.expectedBucketOwner }),
});
}
diff --git a/packages/artifact-store-s3/test/store.test.ts b/packages/artifact-store-s3/test/store.test.ts
index 240c823f..5b7e0501 100644
--- a/packages/artifact-store-s3/test/store.test.ts
+++ b/packages/artifact-store-s3/test/store.test.ts
@@ -1,10 +1,7 @@
import assert from "node:assert/strict";
import test from "node:test";
-import {
- S3ArtifactStore,
- createS3ArtifactStorePackage,
-} from "@narratage/artifact-store-s3";
+import { S3ArtifactStore } from "@narratage/artifact-store-s3";
import type { S3ObjectClient } from "@narratage/artifact-store-s3";
import { isManagedArtifactStore, isStreamingArtifactStore } from "@narratage/runtime";
@@ -36,18 +33,6 @@ test("S3 artifacts use deterministic content-addressed keys", async () => {
assert.deepEqual(await store.get(first.digest), bytes);
});
-test("configured S3 service locks its location", () => {
- const configured = createS3ArtifactStorePackage({
- instance: "artifacts.team",
- client: new FakeS3(),
- bucket: "team-artifacts",
- prefix: "svml",
- region: "us-east-1",
- expectedBucketOwner: "123456789012",
- });
- assert.equal(configured.parts[0]?.instance.id, "artifacts.team.store");
-});
-
/** A client that can do everything, backed by an in-memory bucket. */
class FullFakeS3 extends FakeS3 {
readonly uploads = new Map<string, Uint8Array[]>();
diff --git a/packages/cli/src/output.ts b/packages/cli/src/output.ts
index 03173051..51738d9f 100644
--- a/packages/cli/src/output.ts
+++ b/packages/cli/src/output.ts
@@ -440,7 +440,7 @@ 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 programs and Worker",
+ " narratage runtime up [<profile>] validate the Profile, 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",
diff --git a/packages/cli/test/programs-command.test.ts b/packages/cli/test/programs-command.test.ts
index 12342a9b..6baf1f19 100644
--- a/packages/cli/test/programs-command.test.ts
+++ b/packages/cli/test/programs-command.test.ts
@@ -92,12 +92,12 @@ test("runtime up validates the Runtime before it starts Programs", async () => {
openRuntimeHost: async (path: string) => ({
profile: path,
controller: async () => controller(path, calls),
- createRuntime: async () => { throw new Error("Runtime Closure conflict"); },
+ createRuntime: async () => { throw new Error("Runtime Profile conflict"); },
}),
} as unknown as CliDistribution;
await assert.rejects(
runCli(["runtime", "up", "/p/narratage.runtime.json"], io, selected),
- /Runtime Closure conflict/u,
+ /Runtime Profile conflict/u,
);
assert.deepEqual(calls, []);
});
diff --git a/packages/credential-store-env/README.md b/packages/credential-store-env/README.md
index 138f055d..41a1ab3f 100644
--- a/packages/credential-store-env/README.md
+++ b/packages/credential-store-env/README.md
@@ -1,19 +1,11 @@
# `@narratage/credential-store-env`
-Minimal local `CredentialStore` backed by explicitly named environment variables.
+Read-only `CredentialStore` backed by explicitly named environment variables.
```ts
credentialRef("env", "KIE_API_KEY")
```
-The store resolves only the requested key at Endpoint invocation time. It never enumerates or
-serializes the environment. Secret values are handed only to that Endpoint call and do not enter
-BuildState, Runtime Closure, Operation checkpoints, logs or SQLite through framework code.
-
-`createEnvironmentCredentialStorePackage()` exposes it through the same generic Runtime infrastructure
-package ABI as every other CredentialStore. A Runtime Profile must activate and select it
-explicitly; `@narratage/runtime-local` supplies no credential default. Several selected Stores may coexist,
-and this one declines every reference whose `store` is not `env`.
-
-The environment facet is intentionally read-only. Interactive `auth login/logout` requires a
-selected Store with the optional bounded writable facet, such as the macOS Keychain adapter.
+It resolves only the requested key when an Endpoint needs it. It never enumerates or serializes the
+environment, and declines references owned by another store. The Runtime Profile must select this package;
+installing it grants nothing.
diff --git a/packages/credential-store-env/src/activation.ts b/packages/credential-store-env/src/activation.ts
index 7b578626..09847134 100644
--- a/packages/credential-store-env/src/activation.ts
+++ b/packages/credential-store-env/src/activation.ts
@@ -1,19 +1,19 @@
import {
- createRuntimeInfrastructureAdapterFacet,
+ createRuntimeCredentialStoreAdapterFacet,
runtimeConfigExact,
runtimeConfigObject,
} from "@narratage/runtime-kit";
-import { createEnvironmentCredentialStorePackage } from "./index.js";
+import { EnvironmentCredentialStore } from "./index.js";
-const environmentCredentialStoreAdapter = createRuntimeInfrastructureAdapterFacet({
+const environmentCredentialStoreAdapter = createRuntimeCredentialStoreAdapterFacet({
use: "@narratage/credential-store-env",
validate(context) {
const config = runtimeConfigObject(context.config, "environment CredentialStore");
runtimeConfigExact(config, [], "environment CredentialStore");
},
- create(context) {
- return createEnvironmentCredentialStorePackage({ instance: context.instance });
+ open() {
+ return { value: new EnvironmentCredentialStore() };
},
});
diff --git a/packages/credential-store-env/src/index.ts b/packages/credential-store-env/src/index.ts
index 0bbe9698..ea4a5466 100644
--- a/packages/credential-store-env/src/index.ts
+++ b/packages/credential-store-env/src/index.ts
@@ -1,22 +1,10 @@
-import { defineRuntimeInfrastructurePackage } from "@narratage/runtime";
import type {
CredentialRef,
CredentialStore,
CredentialValue,
- RuntimeInfrastructurePackage,
} from "@narratage/runtime";
import { verifyCredentialRef } from "@narratage/runtime";
-export const environmentCredentialStoreModuleRef = {
- name: "@narratage/credential-store-env",
- version: "1",
-} as const;
-
-export type CreateEnvironmentCredentialStorePackageOptions = {
- readonly instance?: string;
- readonly environment?: NodeJS.ProcessEnv;
-};
-
/** Resolves only explicitly requested environment variables and never snapshots or enumerates env. */
export class EnvironmentCredentialStore implements CredentialStore {
readonly #environment: NodeJS.ProcessEnv;
@@ -33,19 +21,3 @@ export class EnvironmentCredentialStore implements CredentialStore {
return { secret };
}
}
-
-export function createEnvironmentCredentialStorePackage(
- options: CreateEnvironmentCredentialStorePackageOptions = {},
-): RuntimeInfrastructurePackage {
- const instance = options.instance ?? "credentials";
- return defineRuntimeInfrastructurePackage({
- module: environmentCredentialStoreModuleRef,
- instance,
- parts: [{
- role: "credential-store",
- part: "store",
- facet: "credential-store",
- port: new EnvironmentCredentialStore(options.environment),
- }],
- });
-}
diff --git a/packages/credential-store-keychain/README.md b/packages/credential-store-keychain/README.md
index 2c021177..adc78543 100644
--- a/packages/credential-store-keychain/README.md
+++ b/packages/credential-store-keychain/README.md
@@ -4,7 +4,7 @@ macOS Keychain-backed implementation of the domain-neutral Runtime `CredentialSt
its optional writable facet.
It resolves only explicit `{ store: "keychain", key }` references and cannot enumerate credentials.
-Secrets never enter Runtime Profile, Runtime Closure or BuildState. The package invokes the bounded
+Secrets never enter Runtime Profile or BuildState. The package invokes the bounded
`/usr/bin/security find-generic-password` command without a shell and returns no command output on
failure.
diff --git a/packages/credential-store-keychain/src/activation.ts b/packages/credential-store-keychain/src/activation.ts
index f2eb768e..6da4ccf8 100644
--- a/packages/credential-store-keychain/src/activation.ts
+++ b/packages/credential-store-keychain/src/activation.ts
@@ -1,27 +1,26 @@
import {
- createRuntimeInfrastructureAdapterFacet,
+ createRuntimeCredentialStoreAdapterFacet,
runtimeConfigExact,
runtimeConfigObject,
runtimeConfigString,
} from "@narratage/runtime-kit";
-import { createKeychainCredentialStorePackage } from "./store.js";
+import { KeychainCredentialStore } from "./store.js";
-const keychainCredentialStoreRuntimeAdapter = createRuntimeInfrastructureAdapterFacet({
+const keychainCredentialStoreRuntimeAdapter = createRuntimeCredentialStoreAdapterFacet({
use: "@narratage/credential-store-keychain",
validate(context) {
const config = runtimeConfigObject(context.config, "keychain CredentialStore");
runtimeConfigExact(config, ["service"], "keychain CredentialStore");
runtimeConfigString(config.service, "keychain service");
},
- create(context) {
+ open(context) {
const config = runtimeConfigObject(context.config, "keychain CredentialStore");
runtimeConfigExact(config, ["service"], "keychain CredentialStore");
- return createKeychainCredentialStorePackage({
- instance: context.instance,
+ return { value: new KeychainCredentialStore({
...(runtimeConfigString(config.service, "keychain service") === undefined
? {} : { service: config.service as string }),
- });
+ }) };
},
});
diff --git a/packages/credential-store-keychain/src/index.ts b/packages/credential-store-keychain/src/index.ts
index a0bb0372..a3b65aa7 100644
--- a/packages/credential-store-keychain/src/index.ts
+++ b/packages/credential-store-keychain/src/index.ts
@@ -1,4 +1,4 @@
-export { KeychainCredentialStore, createKeychainCredentialStorePackage, keychainCredentialStoreModuleRef } from "./store.js";
+export { KeychainCredentialStore, keychainCredentialStoreModuleRef } from "./store.js";
export type {
CreateKeychainCredentialStorePackageOptions,
KeychainDeleter,
diff --git a/packages/credential-store-keychain/src/store.ts b/packages/credential-store-keychain/src/store.ts
index 009c00ea..9f2da3ed 100644
--- a/packages/credential-store-keychain/src/store.ts
+++ b/packages/credential-store-keychain/src/store.ts
@@ -1,10 +1,9 @@
import { execFile } from "node:child_process";
-import { defineRuntimeInfrastructurePackage, verifyCredentialRef } from "@narratage/runtime";
+import { verifyCredentialRef } from "@narratage/runtime";
import type {
CredentialRef,
CredentialValue,
- RuntimeInfrastructurePackage,
WritableCredentialStore,
} from "@narratage/runtime";
@@ -125,25 +124,3 @@ export class KeychainCredentialStore implements WritableCredentialStore {
return await this.#remove(this.#service, ref.key);
}
}
-
-export function createKeychainCredentialStorePackage(
- options: CreateKeychainCredentialStorePackageOptions = {},
-): RuntimeInfrastructurePackage {
- const instance = options.instance ?? "credentials";
- const service = options.service ?? DEFAULT_SERVICE;
- return defineRuntimeInfrastructurePackage({
- module: keychainCredentialStoreModuleRef,
- instance,
- parts: [{
- role: "credential-store",
- part: "store",
- facet: "credential-store",
- port: new KeychainCredentialStore({
- service,
- ...(options.read === undefined ? {} : { read: options.read }),
- ...(options.write === undefined ? {} : { write: options.write }),
- ...(options.remove === undefined ? {} : { remove: options.remove }),
- }),
- }],
- });
-}
diff --git a/packages/credential-store-keychain/test/store.test.ts b/packages/credential-store-keychain/test/store.test.ts
index 1c081c0e..1f6fd445 100644
--- a/packages/credential-store-keychain/test/store.test.ts
+++ b/packages/credential-store-keychain/test/store.test.ts
@@ -3,10 +3,7 @@ import test from "node:test";
import { credentialRef } from "@narratage/runtime";
-import {
- KeychainCredentialStore,
- createKeychainCredentialStorePackage,
-} from "@narratage/credential-store-keychain";
+import { KeychainCredentialStore } from "@narratage/credential-store-keychain";
const reader = (entries: Readonly<Record<string, string>>) =>
async (_service: string, account: string) => entries[account];
diff --git a/packages/driver-node/test/driver.test.ts b/packages/driver-node/test/driver.test.ts
index d40df702..c47ce993 100644
--- a/packages/driver-node/test/driver.test.ts
+++ b/packages/driver-node/test/driver.test.ts
@@ -100,7 +100,7 @@ test("Driver pauses at an unbound Need, then resumes without rerunning producers
assert.equal(completed.state.records.some((record) => record.id === "generated:root"), true);
});
-test("Endpoint Registry rejects ambiguity until a Runtime Closure selects one endpoint", async () => {
+test("Endpoint Registry rejects an ambiguous Runtime Profile", async () => {
const { producers, endpoints } = configuredRegistry();
endpoints.registerImmediateEndpoint("example:alpha", capabilities.generation, types.generated, () => ({
value: { kind: "inline", value: "Alpha" },
diff --git a/packages/provider-google-vertex/README.md b/packages/provider-google-vertex/README.md
index 3da7b07b..e2d36aa1 100644
--- a/packages/provider-google-vertex/README.md
+++ b/packages/provider-google-vertex/README.md
@@ -18,7 +18,7 @@ createGoogleVertexCaptionProvider({
The Runtime Profile must provide an ordinary `{ store, key }` credential reference. The referenced
value is the JSON contents rather than a path, keeping filesystem authority out of the Provider.
The low-level TypeScript factory retains an environment-reference convenience for embeddings;
-declarative Runtime activation has no implicit credential source. Credentials never enter author source, Runtime Closure, BuildState,
+declarative Runtime activation has no implicit credential source. Credentials never enter author source, BuildState,
Operation state, Prompt or Receipt metadata.
A host may expose an ADC file through a file-backed CredentialStore, but the Provider itself does
diff --git a/packages/provider-kie/test/live-smoke.ts b/packages/provider-kie/test/live-smoke.ts
index f683b7b6..a6f20f0d 100644
--- a/packages/provider-kie/test/live-smoke.ts
+++ b/packages/provider-kie/test/live-smoke.ts
@@ -2,8 +2,8 @@ import { randomUUID } from "node:crypto";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
-import { FileArtifactStore, createFileArtifactStorePackage } from "@narratage/artifact-store-fs";
-import { createEnvironmentCredentialStorePackage } from "@narratage/credential-store-env";
+import { FileArtifactStore } from "@narratage/artifact-store-fs";
+import { EnvironmentCredentialStore } from "@narratage/credential-store-env";
import { registerTypeValidatorFacets } from "@narratage/component-kit";
import {
buildDefinition,
@@ -40,7 +40,7 @@ import {
grokImagineManifest,
sealGrokImagineRequest,
} from "@narratage/grok-imagine";
-import { createLocalExecutionPackage, createProjectLocalRuntime } from "@narratage/runtime-local";
+import { createLocalRuntime } from "@narratage/runtime-local";
import type { LocalBuildSubmission } from "@narratage/runtime-local";
import {
minimaxH3Component,
@@ -63,7 +63,7 @@ import type {
TypedRecord,
} from "@narratage/protocol";
import { credentialRef } from "@narratage/runtime";
-import { createSqliteRuntimeInfrastructurePackage } from "@narratage/store-sqlite";
+import { SqliteRuntimeState } from "@narratage/store-sqlite";
import {
sealSeedanceRequest,
seedanceComponent,
@@ -390,31 +390,21 @@ async function main(): Promise<void> {
defaultConcurrency: 1,
pollIntervalMs: 3_000,
});
- const execution = createLocalExecutionPackage("execution");
- const state = createSqliteRuntimeInfrastructurePackage({
- path: join(root, ".narratage", "runtime.sqlite"),
- instance: "state",
- });
- const artifacts = createFileArtifactStorePackage({ root: join(root, ".narratage", "artifacts"), instance: "artifacts" });
- const credentials = createEnvironmentCredentialStorePackage({ instance: "credentials" });
- const runtime = await createProjectLocalRuntime({
- dataRoot: root,
- infrastructure: [execution, state, artifacts, credentials],
- roles: {
- scheduler: { from: "execution", part: "scheduler" },
- worker: { from: "execution", part: "worker" },
- buildStore: { from: "state", part: "builds" },
- operationStore: { from: "state", part: "operations" },
- dispatchStore: { from: "state", part: "dispatch" },
- artifactStore: { from: "artifacts", part: "store" },
- credentialStores: [{ from: "credentials", part: "store" }],
- },
+ const state = new SqliteRuntimeState(join(root, ".narratage", "runtime.sqlite"));
+ const runtime = await createLocalRuntime({
+ buildStore: state.builds,
+ buildCatalog: state.catalog,
+ operationStore: state.operations,
+ dispatchStore: state.dispatch,
+ artifactStore: new FileArtifactStore(join(root, ".narratage", "artifacts")),
+ credentialStore: new EnvironmentCredentialStore(),
components: [
generationComponent,
...[...new Map(selected.map((item) => [item.manifest.name, item.component])).values()],
],
endpoints: [provider],
scheduling: { maxConcurrency: 1 },
+ close: () => state.close(),
});
const failures: string[] = [];
const workerAbort = new AbortController();
diff --git a/packages/runtime-kit/README.md b/packages/runtime-kit/README.md
index 46ea3c16..29588cbc 100644
--- a/packages/runtime-kit/README.md
+++ b/packages/runtime-kit/README.md
@@ -1,25 +1,14 @@
# `@narratage/runtime-kit`
-Host ABI for turning a Runtime Profile into explicitly selected Endpoints and Runtime infrastructure.
+Host facets for the three environmental choices a Runtime Profile may select:
-One adapter is addressed by `(kind, use)`:
+* an Endpoint implements external capabilities;
+* an Artifact Store keeps generated bytes;
+* a Credential Store resolves explicit credential references.
-- `endpoint` constructs an external capability Endpoint;
-- `infrastructure` constructs a package instance exposing Scheduler, Worker, Store or Credential parts.
+Each adapter is addressed by its kind and `use` name. A package advertises that name through a Host
+facet; the Runtime Profile selects it explicitly. Installing a package does not activate it.
-The two kinds have separate Host ABIs, so an Endpoint and Runtime infrastructure may intentionally share
-one `use` spelling. A physical package advertises the logical name through its Host-facet `offers`,
-and the Runtime Profile selects that package by name.
-
-An Endpoint adapter has one pure `activate()` declaration. It parses the selected configuration once
-and returns the Endpoint package, optional diagnostics and an optional Managed Program. The
-Endpoint 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 Endpoint
-actually handles a Need; `doctor` may diagnose them explicitly.
-
-Runtime infrastructure adapters retain a separate pure `validate()` gate because constructing SQLite or a
-Store can itself mutate deployment state; `doctor()` may diagnose them without calling `create()`.
-
-The registry binds adapter implementations to the selected package contribution. Source imports cannot
-select these facets; only the Runtime Profile may do so.
+Endpoint activation returns one Endpoint and may also describe a Managed Program such as a warm local
+WhisperX process. Store adapters validate configuration before opening a store. Runtime Kit knows no
+Provider, filesystem, database or video package by name.
diff --git a/packages/runtime-kit/src/index.ts b/packages/runtime-kit/src/index.ts
index f98dc8eb..638d5a60 100644
--- a/packages/runtime-kit/src/index.ts
+++ b/packages/runtime-kit/src/index.ts
@@ -2,20 +2,14 @@ import type { EndpointPackage } from "@narratage/endpoint-kit";
import type { HostFacet } from "@narratage/host";
import { canonicalize } from "@narratage/protocol";
import type { CanonicalValue } from "@narratage/protocol";
-import type { RuntimeInfrastructurePackage } from "@narratage/runtime";
import { credentialRef } from "@narratage/runtime";
-import type { CredentialRef } from "@narratage/runtime";
+import type { ArtifactStore, CredentialRef, CredentialStore } from "@narratage/runtime";
export const runtimeEndpointAdapterHostAbi = "narratage.runtime-endpoint-adapter-host@1";
-export const runtimeInfrastructureHostAbi = "narratage.runtime-infrastructure-adapter-host@1";
+export const runtimeArtifactStoreAdapterHostAbi = "narratage.runtime-artifact-store-adapter-host@1";
+export const runtimeCredentialStoreAdapterHostAbi = "narratage.runtime-credential-store-adapter-host@1";
-export type RuntimeAdapterKind = "endpoint" | "infrastructure";
-
-function runtimeAdapterHostAbi(kind: RuntimeAdapterKind):
- | typeof runtimeEndpointAdapterHostAbi
- | typeof runtimeInfrastructureHostAbi {
- return kind === "endpoint" ? runtimeEndpointAdapterHostAbi : runtimeInfrastructureHostAbi;
-}
+export type RuntimeAdapterKind = "endpoint" | "artifact-store" | "credential-store";
type RuntimeAdapterAddress = {
readonly use: string;
@@ -23,13 +17,10 @@ type RuntimeAdapterAddress = {
};
export type RuntimeAdapterFactoryContext = {
- /** 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 infrastructure adapters. */
readonly pool?: string;
readonly config: CanonicalValue;
- /** Observation commands may request adapters to avoid creating durable state. */
readonly access?: "read-write" | "read-only";
};
@@ -40,7 +31,6 @@ export type RuntimeDoctorDiagnostic = {
readonly subject?: string;
};
-/** One command this deployment may run on the developer's machine. */
export type ManagedProgramCommand = {
readonly command: string;
readonly args: readonly string[];
@@ -49,17 +39,8 @@ export type ManagedProgramCommand = {
export type ManagedProgramState =
| { readonly state: "ready" }
| { readonly state: "down"; readonly detail: string }
- /** Something answers, but not as the configured deployment expects. */
| { readonly state: "mismatch"; readonly detail: string };
-/**
- * A separate program that must already be running for this Endpoint to work.
- *
- * An Endpoint that spawns a bounded process per Need declares nothing here; this
- * is for a program whose cost is its warm state, which therefore outlives one
- * 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 ManagedProgram = {
readonly id: string;
probe(): Promise<ManagedProgramState>;
@@ -67,108 +48,128 @@ export type ManagedProgram = {
readonly start?: ManagedProgramCommand;
};
-/**
- * The complete, side-effect-free declaration of one configured Endpoint.
- *
- * `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
- * program lifecycle one source of truth without making a second manifest just
- * for diagnostics.
- */
export type RuntimeEndpointActivation = {
readonly endpoint: EndpointPackage;
readonly program?: ManagedProgram;
readonly diagnose?: () => readonly RuntimeDoctorDiagnostic[] | Promise<readonly RuntimeDoctorDiagnostic[]>;
};
+export type RuntimeOpened<T> = {
+ readonly value: T;
+ readonly close?: () => void | Promise<void>;
+};
+
export type RuntimeEndpointAdapterImplementation = {
activate(context: RuntimeAdapterFactoryContext): RuntimeEndpointActivation | Promise<RuntimeEndpointActivation>;
};
-export type RuntimeInfrastructureImplementation = {
- /** Pure, closed-data validation. Must not construct a service or touch the environment. */
+type RuntimeStoreAdapterImplementation<T> = {
validate(context: RuntimeAdapterFactoryContext): void;
- create(context: RuntimeAdapterFactoryContext): RuntimeInfrastructurePackage | Promise<RuntimeInfrastructurePackage>;
+ open(context: RuntimeAdapterFactoryContext): RuntimeOpened<T> | Promise<RuntimeOpened<T>>;
doctor?(context: RuntimeAdapterFactoryContext): readonly RuntimeDoctorDiagnostic[] | Promise<readonly RuntimeDoctorDiagnostic[]>;
};
-export type RuntimeAdapterHostFacet = HostFacet & {
- readonly abi: ReturnType<typeof runtimeAdapterHostAbi>;
- readonly implementation: RuntimeEndpointAdapterImplementation | RuntimeInfrastructureImplementation;
-};
+type RuntimeAdapterImplementation =
+ | RuntimeEndpointAdapterImplementation
+ | RuntimeStoreAdapterImplementation<ArtifactStore>
+ | RuntimeStoreAdapterImplementation<CredentialStore>;
-type RuntimeAdapterRegistration = {
- readonly implementation: RuntimeAdapterHostFacet["implementation"];
+export type RuntimeAdapterHostFacet = HostFacet & {
+ readonly abi:
+ | typeof runtimeEndpointAdapterHostAbi
+ | typeof runtimeArtifactStoreAdapterHostAbi
+ | typeof runtimeCredentialStoreAdapterHostAbi;
+ readonly implementation: RuntimeAdapterImplementation;
};
function assert(condition: unknown, message: string): asserts condition {
if (!condition) throw new Error(message);
}
+function abiFor(kind: RuntimeAdapterKind): RuntimeAdapterHostFacet["abi"] {
+ if (kind === "endpoint") return runtimeEndpointAdapterHostAbi;
+ if (kind === "artifact-store") return runtimeArtifactStoreAdapterHostAbi;
+ return runtimeCredentialStoreAdapterHostAbi;
+}
+
function address(facet: RuntimeAdapterHostFacet): RuntimeAdapterAddress {
const kind = facet.abi === runtimeEndpointAdapterHostAbi
? "endpoint"
- : facet.abi === runtimeInfrastructureHostAbi ? "infrastructure" : undefined;
+ : facet.abi === runtimeArtifactStoreAdapterHostAbi
+ ? "artifact-store"
+ : facet.abi === runtimeCredentialStoreAdapterHostAbi ? "credential-store" : 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");
return { use: facet.offers[0]!, kind };
}
-function implementation(
- value: unknown,
- subject: string,
- kind: RuntimeAdapterKind,
-): RuntimeAdapterHostFacet["implementation"] {
+function verifyImplementation(value: unknown, subject: string, kind: RuntimeAdapterKind): RuntimeAdapterImplementation {
assert(value !== null && typeof value === "object", `${subject} implementation is not an object`);
if (kind === "endpoint") {
- assert(typeof (value as { activate?: unknown }).activate === "function",
- `${subject} does not implement activate()`);
+ assert(typeof (value as { activate?: unknown }).activate === "function", `${subject} does not implement activate()`);
return value as RuntimeEndpointAdapterImplementation;
}
- assert(typeof (value as { create?: unknown }).create === "function", `${subject} does not implement create()`);
assert(typeof (value as { validate?: unknown }).validate === "function", `${subject} does not implement validate()`);
+ assert(typeof (value as { open?: unknown }).open === "function", `${subject} does not implement open()`);
const doctor = (value as { doctor?: unknown }).doctor;
assert(doctor === undefined || typeof doctor === "function", `${subject}.doctor must be a function`);
- return value as RuntimeInfrastructureImplementation;
+ return value as RuntimeAdapterImplementation;
}
-export function createRuntimeEndpointAdapterFacet(options: {
+function storeFacet<T>(kind: "artifact-store" | "credential-store", options: {
readonly use: string;
- readonly activate: RuntimeEndpointAdapterImplementation["activate"];
+ readonly validate: RuntimeStoreAdapterImplementation<T>["validate"];
+ readonly open: RuntimeStoreAdapterImplementation<T>["open"];
+ readonly doctor?: RuntimeStoreAdapterImplementation<T>["doctor"];
}): RuntimeAdapterHostFacet {
assert(options.use.trim().length > 0, "Runtime Adapter use name is empty");
- const facet: RuntimeAdapterHostFacet = {
- abi: runtimeEndpointAdapterHostAbi,
+ const implementation = {
+ validate: options.validate,
+ open: options.open,
+ ...(options.doctor === undefined ? {} : { doctor: options.doctor }),
+ };
+ return {
+ abi: abiFor(kind),
offers: [options.use],
- implementation: implementation({ activate: options.activate }, `Runtime Adapter ${options.use}`, "endpoint"),
+ implementation: verifyImplementation(implementation, `Runtime Adapter ${options.use}`, kind),
};
- return facet;
}
-export function createRuntimeInfrastructureAdapterFacet(options: {
+export function createRuntimeEndpointAdapterFacet(options: {
readonly use: string;
- readonly validate: RuntimeInfrastructureImplementation["validate"];
- readonly create: RuntimeInfrastructureImplementation["create"];
- readonly doctor?: RuntimeInfrastructureImplementation["doctor"];
+ readonly activate: RuntimeEndpointAdapterImplementation["activate"];
}): RuntimeAdapterHostFacet {
assert(options.use.trim().length > 0, "Runtime Adapter use name is empty");
return {
- abi: runtimeInfrastructureHostAbi,
+ abi: runtimeEndpointAdapterHostAbi,
offers: [options.use],
- implementation: implementation({
- validate: options.validate,
- create: options.create,
- ...(options.doctor === undefined ? {} : { doctor: options.doctor }),
- }, `Runtime Adapter ${options.use}`, "infrastructure"),
+ implementation: verifyImplementation({ activate: options.activate }, `Runtime Adapter ${options.use}`, "endpoint"),
};
}
+export function createRuntimeArtifactStoreAdapterFacet(options: {
+ readonly use: string;
+ readonly validate: RuntimeStoreAdapterImplementation<ArtifactStore>["validate"];
+ readonly open: RuntimeStoreAdapterImplementation<ArtifactStore>["open"];
+ readonly doctor?: RuntimeStoreAdapterImplementation<ArtifactStore>["doctor"];
+}): RuntimeAdapterHostFacet {
+ return storeFacet("artifact-store", options);
+}
+
+export function createRuntimeCredentialStoreAdapterFacet(options: {
+ readonly use: string;
+ readonly validate: RuntimeStoreAdapterImplementation<CredentialStore>["validate"];
+ readonly open: RuntimeStoreAdapterImplementation<CredentialStore>["open"];
+ readonly doctor?: RuntimeStoreAdapterImplementation<CredentialStore>["doctor"];
+}): RuntimeAdapterHostFacet {
+ return storeFacet("credential-store", options);
+}
+
export function isRuntimeAdapterHostFacet(value: HostFacet): value is RuntimeAdapterHostFacet {
try {
const resolved = address(value as RuntimeAdapterHostFacet);
- implementation(value.implementation, "Runtime Adapter", resolved.kind);
+ verifyImplementation(value.implementation, "Runtime Adapter", resolved.kind);
return true;
} catch {
return false;
@@ -176,70 +177,33 @@ export function isRuntimeAdapterHostFacet(value: HostFacet): value is RuntimeAda
}
export class RuntimeAdapterRegistry {
- readonly #registrations = new Map<string, RuntimeAdapterRegistration>();
+ readonly #registrations = new Map<string, RuntimeAdapterImplementation>();
#key(use: string, kind: RuntimeAdapterKind): string {
return `${kind}\u0000${use}`;
}
- #register(facet: RuntimeAdapterHostFacet): void {
+ registerFacet(facet: HostFacet): void {
+ assert(isRuntimeAdapterHostFacet(facet), `Host facet ${facet.abi} is not a valid Runtime Adapter`);
const resolved = address(facet);
- implementation(facet.implementation, `Runtime Adapter ${resolved.use}`, resolved.kind);
const key = this.#key(resolved.use, resolved.kind);
assert(!this.#registrations.has(key), `Runtime ${resolved.kind} Adapter ${resolved.use} is already registered`);
- this.#registrations.set(key, { implementation: facet.implementation });
- }
-
- registerFacet(facet: HostFacet): void {
- assert(isRuntimeAdapterHostFacet(facet), `Host facet ${facet.abi} is not a valid Runtime Adapter`);
- this.#register(facet);
+ this.#registrations.set(key, facet.implementation);
}
has(use: string, kind?: RuntimeAdapterKind): boolean {
return kind === undefined
- ? this.#registrations.has(this.#key(use, "endpoint")) || this.#registrations.has(this.#key(use, "infrastructure"))
+ ? (["endpoint", "artifact-store", "credential-store"] as const).some((value) =>
+ this.#registrations.has(this.#key(use, value)))
: 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 component/Endpoint-specific code.
- */
- validate(
- use: string,
- kind: RuntimeAdapterKind,
- context: RuntimeAdapterFactoryContext,
- ): 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 === "infrastructure", "Endpoint configuration is validated by its activation");
- (value.implementation as RuntimeInfrastructureImplementation).validate(context);
- return [];
- }
-
- async activateEndpoint(
- use: string,
- context: RuntimeAdapterFactoryContext,
- ): Promise<RuntimeEndpointActivation> {
- const value = this.#registrations.get(this.#key(use, "endpoint"));
- assert(value !== undefined, `Runtime Endpoint adapter ${use} is not registered`);
- const implementation = value.implementation as RuntimeEndpointAdapterImplementation;
+ async activateEndpoint(use: string, context: RuntimeAdapterFactoryContext): Promise<RuntimeEndpointActivation> {
+ const implementation = this.#registrations.get(this.#key(use, "endpoint")) as RuntimeEndpointAdapterImplementation | undefined;
+ assert(implementation !== undefined, `Runtime Endpoint adapter ${use} is not registered`);
const activation = await implementation.activate(context);
- assert(activation !== null && typeof activation === "object", `Runtime Endpoint adapter ${use} returned no activation`);
- assert(activation.endpoint !== null && typeof activation.endpoint === "object",
- `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.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 activation;
}
@@ -247,25 +211,38 @@ export class RuntimeAdapterRegistry {
return (await this.activateEndpoint(use, context)).endpoint;
}
- async createInfrastructure(use: string, context: RuntimeAdapterFactoryContext): Promise<RuntimeInfrastructurePackage> {
- const value = this.#registrations.get(this.#key(use, "infrastructure"));
- assert(value !== undefined, `Runtime infrastructure adapter ${use} is not registered`);
- const implementation = value.implementation as RuntimeInfrastructureImplementation;
+ async #openStore<T>(use: string, kind: "artifact-store" | "credential-store", context: RuntimeAdapterFactoryContext): Promise<RuntimeOpened<T>> {
+ const implementation = this.#registrations.get(this.#key(use, kind)) as RuntimeStoreAdapterImplementation<T> | undefined;
+ assert(implementation !== undefined, `Runtime ${kind} adapter ${use} is not registered`);
implementation.validate(context);
- const created = await implementation.create(context);
- for (const part of created.parts) {
- assert(part.instance.id === `${context.instance}.${part.part}`,
- `Runtime Adapter ${use} created part ${part.instance.id} outside configured instance ${context.instance}`);
- }
- return created;
+ const opened = await implementation.open(context);
+ assert(opened.value !== null && typeof opened.value === "object", `Runtime ${kind} adapter ${use} returned no value`);
+ return opened;
}
- 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 === "infrastructure", "Endpoint diagnostics belong to its activation");
- const diagnose = (value.implementation as RuntimeInfrastructureImplementation).doctor;
- return diagnose === undefined ? [] : await diagnose(context);
+ async openArtifactStore(use: string, context: RuntimeAdapterFactoryContext): Promise<RuntimeOpened<ArtifactStore>> {
+ return await this.#openStore(use, "artifact-store", context);
+ }
+
+ async openCredentialStore(use: string, context: RuntimeAdapterFactoryContext): Promise<RuntimeOpened<CredentialStore>> {
+ return await this.#openStore(use, "credential-store", context);
+ }
+
+ validate(use: string, kind: Exclude<RuntimeAdapterKind, "endpoint">, context: RuntimeAdapterFactoryContext): readonly RuntimeDoctorDiagnostic[] {
+ const implementation = this.#registrations.get(this.#key(use, kind)) as RuntimeStoreAdapterImplementation<unknown> | undefined;
+ if (implementation === undefined) return [{
+ severity: "error", code: "RUNTIME_ADAPTER_MISSING", message: `Runtime Adapter ${use} is not registered`, subject: use,
+ }];
+ implementation.validate(context);
+ return [];
+ }
+
+ async doctor(use: string, kind: Exclude<RuntimeAdapterKind, "endpoint">, context: RuntimeAdapterFactoryContext): Promise<readonly RuntimeDoctorDiagnostic[]> {
+ const implementation = this.#registrations.get(this.#key(use, kind)) as RuntimeStoreAdapterImplementation<unknown> | undefined;
+ if (implementation === undefined) return [{
+ severity: "error", code: "RUNTIME_ADAPTER_MISSING", message: `Runtime Adapter ${use} is not registered`, subject: use,
+ }];
+ return implementation.doctor === undefined ? [] : await implementation.doctor(context);
}
}
@@ -297,7 +274,6 @@ export function runtimeConfigBoolean(value: CanonicalValue | undefined, subject:
return value;
}
-/** Closed deployment syntax for a CredentialRef; secret bytes never enter the Profile. */
export function runtimeConfigCredentialRef(
value: CanonicalValue | undefined,
subject: string,
@@ -310,3 +286,7 @@ export function runtimeConfigCredentialRef(
assert(store !== undefined && key !== undefined, `${subject} requires store and key`);
return credentialRef(store, key);
}
+
+export function canonicalRuntimeConfig(value: unknown): CanonicalValue {
+ return canonicalize(value);
+}
diff --git a/packages/runtime-kit/test/registry.test.ts b/packages/runtime-kit/test/registry.test.ts
index 57081514..742b57d1 100644
--- a/packages/runtime-kit/test/registry.test.ts
+++ b/packages/runtime-kit/test/registry.test.ts
@@ -2,8 +2,8 @@ import assert from "node:assert/strict";
import test from "node:test";
import {
+ createRuntimeArtifactStoreAdapterFacet,
createRuntimeEndpointAdapterFacet,
- createRuntimeInfrastructureAdapterFacet,
isRuntimeAdapterHostFacet,
runtimeConfigBoolean,
runtimeConfigExact,
@@ -32,49 +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(createRuntimeInfrastructureAdapterFacet({
+ registry.registerFacet(createRuntimeArtifactStoreAdapterFacet({
use: "example.service",
validate() {},
- create: () => ({}) as never,
+ open: () => ({ value: {} as never }),
}));
assert.ok(registry.has("example.endpoint", "endpoint"));
- assert.equal(registry.has("example.endpoint", "infrastructure"), false);
- assert.ok(registry.has("example.service", "infrastructure"));
+ assert.equal(registry.has("example.endpoint", "artifact-store"), false);
+ assert.ok(registry.has("example.service", "artifact-store"));
assert.equal(registry.has("example.service", "endpoint"), false);
assert.equal(registry.has("example.absent"), false);
});
-test("Endpoint and Runtime infrastructure may intentionally share one logical spelling", () => {
+test("Endpoint and Artifact Store adapters may share one package address", () => {
const registry = new RuntimeAdapterRegistry();
registry.registerFacet(endpoint("example.shared"));
- registry.registerFacet(createRuntimeInfrastructureAdapterFacet({
+ registry.registerFacet(createRuntimeArtifactStoreAdapterFacet({
use: "example.shared",
validate() {},
- create: () => ({ parts: [] }) as never,
+ open: () => ({ value: {} as never }),
}));
assert.ok(registry.has("example.shared", "endpoint"));
- assert.ok(registry.has("example.shared", "infrastructure"));
+ assert.ok(registry.has("example.shared", "artifact-store"));
});
-test("asking an Endpoint adapter for a Runtime infrastructure is refused, not coerced", async () => {
+test("asking an Endpoint adapter for an Artifact Store is refused, not coerced", async () => {
const registry = new RuntimeAdapterRegistry();
registry.registerFacet(endpoint("example.endpoint"));
- await assert.rejects(async () => await registry.createInfrastructure("example.endpoint", context));
+ await assert.rejects(async () => await registry.openArtifactStore("example.endpoint", context));
await assert.rejects(async () => await registry.createEndpoint("example.absent", context));
});
-test("a Runtime infrastructure adapter cannot escape its configured instance namespace", async () => {
+test("an Artifact Store adapter returns the selected Store directly", async () => {
const registry = new RuntimeAdapterRegistry();
- registry.registerFacet(createRuntimeInfrastructureAdapterFacet({
- use: "example.escaping-service",
+ const value = { put() {}, get() {}, has() {} } as never;
+ registry.registerFacet(createRuntimeArtifactStoreAdapterFacet({
+ use: "example.artifacts",
validate() {},
- create: () => ({ parts: [{ part: "escape", instance: { id: "someone-else" } }] }) as never,
+ open: () => ({ value }),
}));
- await assert.rejects(
- async () => await registry.createInfrastructure("example.escaping-service", context),
- /outside configured instance one/u,
- );
+ assert.equal((await registry.openArtifactStore("example.artifacts", context)).value, value);
});
test("one kind and logical name has one adapter, so a second registration is an error", () => {
diff --git a/packages/runtime-local/README.md b/packages/runtime-local/README.md
index 1f1bd301..761fa784 100644
--- a/packages/runtime-local/README.md
+++ b/packages/runtime-local/README.md
@@ -1,10 +1,9 @@
# `@narratage/runtime-local`
-Local Runtime Host for Narratage. The package owns local process lifecycle, durable dispatch and
-assembly of explicitly selected Runtime infrastructures. It contains no authoring, video or Provider
-routing policy.
+The default local Runtime for Narratage. It owns the Worker, scheduler, SQLite state and Build queue.
+It contains no video, authoring or Provider policy.
-The Runtime Profile selects this Host at the top level, then configures its private deployment:
+A Runtime Profile selects only the environmental parts that genuinely vary:
```json
{
@@ -13,47 +12,24 @@ The Runtime Profile selects this Host at the top level, then configures its priv
"use": "@narratage/runtime-local",
"config": {
"dataRoot": ".narratage/runtimes/local",
- "infrastructure": {
- "execution": { "use": "@narratage/runtime-local" },
- "state": { "use": "@narratage/store-sqlite", "config": { "path": "state.sqlite" } },
- "artifacts": { "use": "@narratage/artifact-store-fs", "config": { "path": "artifacts" } }
+ "artifacts": {
+ "use": "@narratage/artifact-store-fs",
+ "config": { "path": "artifacts" }
},
- "roles": {
- "scheduler": { "from": "execution", "part": "scheduler" },
- "worker": { "from": "execution", "part": "worker" },
- "buildStore": { "from": "state", "part": "builds" },
- "operationStore": { "from": "state", "part": "operations" },
- "dispatchStore": { "from": "state", "part": "dispatch" },
- "artifactStore": { "from": "artifacts", "part": "store" },
- "credentialStores": []
+ "credentials": {
+ "environment": { "use": "@narratage/credential-store-env" }
},
"endpoints": {},
- "capacity": { "maxActiveOperations": 4 }
+ "concurrency": 4
}
}
}
```
-`infrastructure` declares configured package instances; `roles` selects exact package parts.
-Nothing is selected by presence or uniqueness. `endpoints` declares capability implementations and
-their Managed Programs. `capacity` belongs to this Runtime deployment, not to Core or Author Source.
+Submitting a Build stores it and returns. The local Worker advances several Builds concurrently while
+sharing the configured command limit. Endpoint packages declare their own Provider and model limits.
+Cancellation prevents new work and makes a best effort to cancel an external operation already submitted;
+completed output is never rolled back.
-## Execution
-
-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 stops new work and makes one best-effort attempt for work already submitted.
-
-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
-
-* The Runtime Profile contains no Source Workspace or author package selection.
-* `dataRoot` contains deployment state, never author source or credentials.
-* Source imports select author packages; Profile `use` fields select Runtime packages.
-* Infrastructure parts and Endpoints communicate through declared ports and capabilities; this Host
- keeps no central list of video packages.
-
-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.
+Source imports select author packages. Runtime Profile entries select only code allowed to access files,
+credentials, processes or networks. Installing a package changes neither selection.
diff --git a/packages/runtime-local/package.json b/packages/runtime-local/package.json
index 32e75a20..8d27f94a 100644
--- a/packages/runtime-local/package.json
+++ b/packages/runtime-local/package.json
@@ -23,12 +23,12 @@
"@narratage/runtime": "workspace:*",
"@narratage/runtime-kit": "workspace:*",
"@narratage/runtime-host-node": "workspace:*",
+ "@narratage/store-sqlite": "workspace:*",
"@narratage/validation": "workspace:*"
},
"devDependencies": {
"@narratage/artifact-store-fs": "workspace:*",
"@narratage/credential-store-env": "workspace:*",
- "@narratage/core": "workspace:*",
- "@narratage/store-sqlite": "workspace:*"
+ "@narratage/core": "workspace:*"
}
}
diff --git a/packages/runtime-local/src/activation.ts b/packages/runtime-local/src/activation.ts
index 557125f1..f25409b2 100644
--- a/packages/runtime-local/src/activation.ts
+++ b/packages/runtime-local/src/activation.ts
@@ -1,26 +1,8 @@
-import {
- createRuntimeInfrastructureAdapterFacet,
- runtimeConfigExact,
- runtimeConfigObject,
-} from "@narratage/runtime-kit";
-
-import { createLocalExecutionPackage } from "./scheduler-package.js";
import { localRuntimeHostAdapter } from "./host.js";
-const localExecutionAdapter = createRuntimeInfrastructureAdapterFacet({
- use: "@narratage/runtime-local",
- validate(context) {
- const config = runtimeConfigObject(context.config, "local execution");
- runtimeConfigExact(config, [], "local execution");
- },
- create(context) {
- return createLocalExecutionPackage(context.instance);
- },
-});
-
export const narratagePackage = {
format: "narratage.node-package@1" as const,
- hostFacets: [localRuntimeHostAdapter, localExecutionAdapter],
+ hostFacets: [localRuntimeHostAdapter],
};
export default narratagePackage;
diff --git a/packages/runtime-local/src/config.ts b/packages/runtime-local/src/config.ts
index afbe331a..f2877f43 100644
--- a/packages/runtime-local/src/config.ts
+++ b/packages/runtime-local/src/config.ts
@@ -2,38 +2,40 @@ import { readFile, stat } from "node:fs/promises";
import { dirname, resolve } from "node:path";
import type { ComponentPackage } from "@narratage/component-kit";
-import {
- collectNodePackageComponents,
- loadNodePackageSelection,
-} from "@narratage/package-loader-node";
+import { collectNodePackageComponents, loadNodePackageSelection } from "@narratage/package-loader-node";
import type { LoadedPackage, NodePackageSelectionRequest } from "@narratage/package-loader-node";
import { canonicalize } from "@narratage/protocol";
import type { CanonicalValue, CapabilityRef } from "@narratage/protocol";
+import {
+ CompositeCredentialStore,
+} from "@narratage/runtime";
+import type { ArtifactStore, CredentialStore } from "@narratage/runtime";
import {
isRuntimeAdapterHostFacet,
+ runtimeArtifactStoreAdapterHostAbi,
+ runtimeCredentialStoreAdapterHostAbi,
runtimeEndpointAdapterHostAbi,
- runtimeInfrastructureHostAbi,
RuntimeAdapterRegistry,
} from "@narratage/runtime-kit";
import type {
- RuntimeDoctorDiagnostic,
- RuntimeEndpointActivation,
ManagedProgram,
ManagedProgramState,
+ RuntimeDoctorDiagnostic,
+ RuntimeEndpointActivation,
+ RuntimeOpened,
} from "@narratage/runtime-kit";
-import {
- CompositeCredentialStore,
- verifyRuntimeInfrastructurePackage,
-} from "@narratage/runtime";
-import type {
- RuntimeInfrastructurePackage,
- RuntimePartReference,
- RuntimeRoleSelection,
-} from "@narratage/runtime";
+import { SqliteRuntimeState } from "@narratage/store-sqlite";
-import type { LocalRuntime } from "./types.js";
-import type { LocalCredentialControl } from "./types.js";
+import { createLocalRuntime } from "./runtime.js";
+import {
+ createLocalRuntimeArchiveControl,
+ createLocalRuntimeArtifactAccess,
+ createLocalRuntimeControl,
+} from "./control.js";
+import { createLocalCredentialControl } from "./credentials.js";
import type {
+ LocalCredentialControl,
+ LocalRuntime,
LocalRuntimeArchiveControl,
LocalRuntimeArtifactAccess,
LocalRuntimeControl,
@@ -48,17 +50,42 @@ export type RuntimeConfigEntry = {
export type RuntimeConfigDocument = {
readonly format: "narratage.runtime-profile@1";
- readonly runtimeUse: string;
- /** Private deployment state, resolved relative to the Profile. */
+ readonly runtimeUse: "@narratage/runtime-local";
readonly dataRoot: string;
- /** Replaceable parts of the Runtime itself. One package may fill several roles. */
- readonly infrastructure: readonly RuntimeConfigEntry[];
- readonly roles: RuntimeRoleSelection;
+ readonly artifacts: RuntimeConfigEntry;
+ readonly credentials: readonly RuntimeConfigEntry[];
readonly endpoints: readonly RuntimeConfigEntry[];
- readonly capacity: {
- readonly maxConcurrency: number;
- readonly resources?: Readonly<Record<string, number>>;
- };
+ readonly concurrency: number;
+};
+
+export type LoadRuntimeConfigOptions = {
+ readonly registry?: RuntimeAdapterRegistry;
+ readonly components?: readonly ComponentPackage[];
+ readonly packageRoot?: string;
+ readonly implementationPackages?: readonly LoadedPackage[];
+ readonly readOnly?: boolean;
+};
+
+export type RuntimeConfigDoctorResult = {
+ readonly dataRoot: string;
+ readonly diagnostics: readonly RuntimeDoctorDiagnostic[];
+};
+
+export type ResolvedRuntimeConfigPaths = {
+ readonly packageRoot: string;
+ readonly dataRoot: string;
+};
+
+type OpenedRuntimeConfig = {
+ readonly absolute: string;
+ readonly document: RuntimeConfigDocument;
+ readonly root: string;
+ readonly packageRoot: string;
+};
+
+type DeclaredManagedProgram = {
+ readonly instance: string;
+ readonly program: ManagedProgram;
};
function object(value: unknown, subject: string): Record<string, unknown> {
@@ -71,36 +98,20 @@ function exactKeys(value: Record<string, unknown>, allowed: readonly string[], s
if (unknown.length > 0) throw new Error(`${subject} does not accept ${unknown[0]}`);
}
-function optionalString(value: unknown, subject: string): string | undefined {
- if (value === undefined) return undefined;
+function requiredString(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;
}
-function requiredString(value: unknown, subject: string): string {
- const result = optionalString(value, subject);
- if (result === undefined) throw new Error(`${subject} is required`);
- return result;
-}
-
-function positiveInteger(value: unknown, subject: string): number | undefined {
- if (value === undefined) return undefined;
- if (!Number.isSafeInteger(value) || (value as number) <= 0) throw new Error(`${subject} must be a positive integer`);
+function positiveInteger(value: unknown, subject: string): number {
+ if (!Number.isSafeInteger(value) || (value as number) < 1) throw new Error(`${subject} must be a positive integer`);
return value as number;
}
-function stringList(value: unknown, subject: string): readonly string[] {
- if (value === undefined) return [];
- if (!Array.isArray(value)) throw new Error(`${subject} must be an array`);
- const items = value.map((item, index) => optionalString(item, `${subject}[${index}]`)!);
- if (new Set(items).size !== items.length) throw new Error(`${subject} contains duplicates`);
- return items;
-}
-
-function entry(value: unknown, instance: string, subject: string, poolAllowed: boolean): RuntimeConfigEntry {
+function entry(value: unknown, instance: string, subject: string, poolAllowed = false): RuntimeConfigEntry {
const item = object(value, subject);
exactKeys(item, poolAllowed ? ["use", "pool", "config"] : ["use", "config"], subject);
- const pool = poolAllowed ? optionalString(item.pool, `${subject}.pool`) : undefined;
+ const pool = item.pool === undefined ? undefined : requiredString(item.pool, `${subject}.pool`);
return {
use: requiredString(item.use, `${subject}.use`),
instance,
@@ -109,66 +120,10 @@ function entry(value: unknown, instance: string, subject: string, poolAllowed: b
};
}
-
-function capacity(value: unknown): RuntimeConfigDocument["capacity"] {
- if (value === undefined) throw new Error("$runtime.runtime.config.capacity is required");
- const item = object(value, "$runtime.runtime.config.capacity");
- exactKeys(item, ["maxActiveOperations", "resources"], "$runtime.runtime.config.capacity");
- const resources = item.resources === undefined ? undefined : object(item.resources, "$runtime.runtime.config.capacity.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.runtime.config.capacity.resources.${name}`)!];
- }));
- const maxConcurrency = positiveInteger(item.maxActiveOperations,
- "$runtime.runtime.config.capacity.maxActiveOperations");
- if (maxConcurrency === undefined) {
- throw new Error("$runtime.runtime.config.capacity.maxActiveOperations is required");
- }
- return {
- maxConcurrency,
- ...(normalizedResources === undefined ? {} : { resources: normalizedResources }),
- };
-}
-
-function partReference(value: unknown, subject: string): RuntimePartReference {
- const item = object(value, subject);
- exactKeys(item, ["from", "part"], subject);
- return {
- from: requiredString(item.from, `${subject}.from`),
- part: requiredString(item.part, `${subject}.part`),
- };
-}
-
-function partReferences(value: unknown, subject: string): readonly RuntimePartReference[] {
- if (value === undefined) return [];
- if (!Array.isArray(value)) throw new Error(`${subject} must be an array`);
- const references = value.map((item, index) => partReference(item, `${subject}[${index}]`));
- const keys = references.map((item) => `${item.from}\u0000${item.part}`);
- if (new Set(keys).size !== keys.length) throw new Error(`${subject} contains duplicates`);
- return references;
-}
-
-function roleSelection(value: unknown): RuntimeRoleSelection {
- const subject = "$runtime.runtime.config.roles";
- const item = object(value, subject);
- exactKeys(item, [
- "scheduler", "worker", "buildStore", "operationStore", "dispatchStore", "artifactStore", "credentialStores",
- ], subject);
- return {
- scheduler: partReference(item.scheduler, `${subject}.scheduler`),
- worker: partReference(item.worker, `${subject}.worker`),
- buildStore: partReference(item.buildStore, `${subject}.buildStore`),
- operationStore: partReference(item.operationStore, `${subject}.operationStore`),
- dispatchStore: partReference(item.dispatchStore, `${subject}.dispatchStore`),
- artifactStore: partReference(item.artifactStore, `${subject}.artifactStore`),
- credentialStores: partReferences(item.credentialStores, `${subject}.credentialStores`),
- };
-}
-
-function entries(value: unknown, subject: string, poolAllowed: 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`);
+function entries(value: unknown, subject: string, poolAllowed = false): readonly RuntimeConfigEntry[] {
+ const values = object(value ?? {}, subject);
+ return Object.entries(values).map(([instance, item]) => {
+ requiredString(instance, `${subject} instance`);
return entry(item, instance, `${subject}.${instance}`, poolAllowed);
});
}
@@ -181,68 +136,34 @@ export function parseRuntimeConfig(value: unknown): RuntimeConfigDocument {
}
const runtime = object(item.runtime, "$runtime.runtime");
exactKeys(runtime, ["use", "config"], "$runtime.runtime");
- const runtimeUse = requiredString(runtime.use, "$runtime.runtime.use");
- if (runtimeUse !== "@narratage/runtime-local") throw new Error(`Local Runtime loader cannot activate ${runtimeUse}`);
+ if (runtime.use !== "@narratage/runtime-local") {
+ throw new Error(`Local Runtime loader cannot activate ${String(runtime.use)}`);
+ }
const config = object(runtime.config, "$runtime.runtime.config");
- exactKeys(config, ["dataRoot", "infrastructure", "roles", "endpoints", "capacity"], "$runtime.runtime.config");
- const infrastructure = entries(config.infrastructure, "$runtime.runtime.config.infrastructure", false);
- const endpoints = config.endpoints === undefined
- ? []
- : entries(config.endpoints, "$runtime.runtime.config.endpoints", true);
- const instances = [...infrastructure, ...endpoints].map((value) => value.instance);
- if (new Set(instances).size !== instances.length) throw new Error("$runtime repeats a Runtime instance id");
+ exactKeys(config, ["dataRoot", "artifacts", "credentials", "endpoints", "concurrency"], "$runtime.runtime.config");
+ const artifacts = entry(config.artifacts, "artifacts", "$runtime.runtime.config.artifacts");
+ const credentials = entries(config.credentials, "$runtime.runtime.config.credentials");
+ const endpoints = entries(config.endpoints, "$runtime.runtime.config.endpoints", true);
+ const ids = [...credentials, ...endpoints].map((value) => value.instance);
+ if (new Set(ids).size !== ids.length) throw new Error("$runtime repeats a Runtime instance id");
return {
format: "narratage.runtime-profile@1",
- runtimeUse,
+ runtimeUse: "@narratage/runtime-local",
dataRoot: requiredString(config.dataRoot, "$runtime.runtime.config.dataRoot"),
- infrastructure,
- roles: roleSelection(config.roles),
+ artifacts,
+ credentials,
endpoints,
- capacity: capacity(config.capacity),
+ concurrency: positiveInteger(config.concurrency, "$runtime.runtime.config.concurrency"),
};
}
-export type LoadRuntimeConfigOptions = {
- /** Trusted embedding adapters supplied directly by an embedding application. */
- readonly registry?: RuntimeAdapterRegistry;
- readonly components?: readonly ComponentPackage[];
- /** Host package installation used when the Profile does not explicitly select packageRoot. */
- readonly packageRoot?: string;
- /** Package set already verified by this same Host command. */
- readonly implementationPackages?: readonly LoadedPackage[];
- /** Observation-only assembly must not initialize absent durable state. */
- readonly readOnly?: boolean;
-};
-
-export type RuntimeConfigDoctorResult = {
- readonly dataRoot: string;
- readonly diagnostics: readonly RuntimeDoctorDiagnostic[];
-};
-
-export type ResolvedRuntimeConfigPaths = {
- readonly packageRoot: string;
- readonly dataRoot: string;
-};
-
-type OpenedRuntimeConfig = {
- readonly absolute: string;
- readonly document: RuntimeConfigDocument;
- readonly profileRoot: string;
- readonly root: string;
- readonly packageRoot: string;
-};
-
-async function openRuntimeConfig(
- path: string,
- packageRootHint?: string,
-): Promise<OpenedRuntimeConfig> {
+async function openRuntimeConfig(path: string, packageRootHint?: string): Promise<OpenedRuntimeConfig> {
const absolute = resolve(path);
const document = parseRuntimeConfig(JSON.parse(await readFile(absolute, "utf8")));
const profileRoot = dirname(absolute);
return {
absolute,
document,
- profileRoot,
root: resolve(profileRoot, document.dataRoot),
packageRoot: resolve(packageRootHint ?? profileRoot),
};
@@ -252,103 +173,83 @@ function runtimePackageSelection(document: RuntimeConfigDocument): NodePackageSe
return {
selected: [],
logical: [
- ...document.infrastructure.map((item) => ({ abi: runtimeInfrastructureHostAbi, name: item.use })),
+ { abi: runtimeArtifactStoreAdapterHostAbi, name: document.artifacts.use },
+ ...document.credentials.map((item) => ({ abi: runtimeCredentialStoreAdapterHostAbi, name: item.use })),
...document.endpoints.map((item) => ({ abi: runtimeEndpointAdapterHostAbi, name: item.use })),
],
};
}
-/**
- * Resolve Runtime-owned paths without constructing infrastructure or Endpoints.
- */
-export async function resolveRuntimeConfigPaths(
- path: string,
- options: LoadRuntimeConfigOptions = {},
-): Promise<ResolvedRuntimeConfigPaths> {
- const { root, packageRoot } = await openRuntimeConfig(path, options.packageRoot);
+function endpointPackageSelection(document: RuntimeConfigDocument): NodePackageSelectionRequest {
return {
- packageRoot,
- dataRoot: root,
+ selected: [],
+ logical: document.endpoints.map((item) => ({ abi: runtimeEndpointAdapterHostAbi, name: item.use })),
};
}
async function installRuntimeAdapters(
registry: RuntimeAdapterRegistry,
packageRoot: string,
- selected: readonly string[] | NodePackageSelectionRequest,
+ selection: NodePackageSelectionRequest,
): Promise<void> {
- const request: NodePackageSelectionRequest = Array.isArray(selected)
- ? { selected }
- : selected as NodePackageSelectionRequest;
- const logical = (request.logical ?? []).filter((address) => {
+ const logical = selection.logical?.filter((address) => {
if (address.abi === runtimeEndpointAdapterHostAbi) return !registry.has(address.name, "endpoint");
- if (address.abi === runtimeInfrastructureHostAbi) return !registry.has(address.name, "infrastructure");
+ if (address.abi === runtimeArtifactStoreAdapterHostAbi) return !registry.has(address.name, "artifact-store");
+ if (address.abi === runtimeCredentialStoreAdapterHostAbi) return !registry.has(address.name, "credential-store");
return true;
- });
- if (request.selected.length === 0 && logical.length === 0) return;
- const loaded = await loadNodePackageSelection({ selected: request.selected, logical }, packageRoot);
- for (const loadedPackage of loaded) {
- const contribution = loadedPackage.contribution;
- for (const facet of contribution.hostFacets ?? []) {
- if (!isRuntimeAdapterHostFacet(facet)) continue;
- registry.registerFacet(facet);
+ }) ?? [];
+ if (selection.selected.length === 0 && logical.length === 0) return;
+ const loaded = await loadNodePackageSelection({ selected: selection.selected, logical }, packageRoot);
+ for (const item of loaded) {
+ for (const facet of item.contribution.hostFacets ?? []) {
+ if (isRuntimeAdapterHostFacet(facet)) registry.registerFacet(facet);
}
}
}
-/** One Endpoint's declaration of an external program its Provider drives. */
-type DeclaredManagedProgram = {
- readonly instance: string;
- readonly program: ManagedProgram;
-};
+export async function resolveRuntimeConfigPaths(
+ path: string,
+ options: LoadRuntimeConfigOptions = {},
+): Promise<ResolvedRuntimeConfigPaths> {
+ const opened = await openRuntimeConfig(path, options.packageRoot);
+ return { packageRoot: opened.packageRoot, dataRoot: opened.root };
+}
function capabilityKey(capability: CapabilityRef): string {
return `${capability.module.name}@${capability.module.version}#${capability.name}`;
}
-/**
- * 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 `program.id` and act once.
- */
+async function activatedEndpoints(
+ document: RuntimeConfigDocument,
+ root: string,
+ registry: RuntimeAdapterRegistry,
+): Promise<readonly { readonly entry: RuntimeConfigEntry; readonly activation: RuntimeEndpointActivation }[]> {
+ return await Promise.all(document.endpoints.map(async (item) => ({
+ entry: item,
+ activation: await registry.activateEndpoint(item.use, {
+ dataRoot: root,
+ instance: item.instance,
+ pool: item.pool ?? item.instance,
+ config: item.config ?? {},
+ }),
+ })));
+}
+
export async function declaredManagedPrograms(
path: string,
options: LoadRuntimeConfigOptions & { readonly capabilities?: readonly CapabilityRef[] } = {},
): Promise<{ readonly dataRoot: string; readonly programs: readonly DeclaredManagedProgram[] }> {
const { document, 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. `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();
- const requestedCapabilities = options.capabilities === undefined
+ await installRuntimeAdapters(registry, packageRoot, endpointPackageSelection(document));
+ const requested = options.capabilities === undefined
? undefined
: new Set(options.capabilities.map(capabilityKey));
- await installRuntimeAdapters(
- registry,
- 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, {
- dataRoot: root,
- instance: item.instance,
- pool: item.pool ?? item.instance,
- config: item.config ?? {},
- });
- if (requestedCapabilities !== undefined && !activation.endpoint.offers.some((offer) =>
- requestedCapabilities.has(capabilityKey(offer.capability)))) {
- continue;
- }
- const program = activation.program;
- if (program !== undefined) programs.push({ instance: item.instance, program });
+ for (const { entry, activation } of await activatedEndpoints(document, root, registry)) {
+ if (requested !== undefined && !activation.endpoint.offers.some((offer) => requested.has(capabilityKey(offer.capability)))) continue;
+ if (activation.program !== undefined) programs.push({ instance: entry.instance, program: activation.program });
}
return { dataRoot: root, programs };
}
@@ -362,101 +263,112 @@ function diagnostic(error: unknown, code: string, subject?: string): RuntimeDoct
};
}
-/** Read-only validation of package bytes, adapter config, credentials and local executable prerequisites. */
+async function openCredentialStores(
+ document: RuntimeConfigDocument,
+ root: string,
+ registry: RuntimeAdapterRegistry,
+ readOnly: boolean,
+): Promise<{ readonly store: CredentialStore; close(): Promise<void> }> {
+ const opened: RuntimeOpened<CredentialStore>[] = [];
+ try {
+ for (const item of document.credentials) {
+ opened.push(await registry.openCredentialStore(item.use, {
+ dataRoot: root,
+ instance: item.instance,
+ config: item.config ?? {},
+ access: readOnly ? "read-only" : "read-write",
+ }));
+ }
+ return {
+ store: new CompositeCredentialStore(opened.map((item) => item.value)),
+ close: async () => {
+ for (const item of [...opened].reverse()) await item.close?.();
+ },
+ };
+ } catch (error) {
+ for (const item of [...opened].reverse()) await item.close?.();
+ throw error;
+ }
+}
+
+async function openArtifactStore(
+ document: RuntimeConfigDocument,
+ root: string,
+ registry: RuntimeAdapterRegistry,
+ readOnly: boolean,
+): Promise<RuntimeOpened<ArtifactStore>> {
+ const item = document.artifacts;
+ return await registry.openArtifactStore(item.use, {
+ dataRoot: root,
+ instance: item.instance,
+ config: item.config ?? {},
+ access: readOnly ? "read-only" : "read-write",
+ });
+}
+
+function statePath(root: string): string {
+ return resolve(root, "runtime.sqlite");
+}
+
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 diagnostics: RuntimeDoctorDiagnostic[] = [];
- const credentialEndpoints: Array<{
- readonly entry: RuntimeConfigEntry;
- readonly activation: RuntimeEndpointActivation;
- }> = [];
- const coveredCapabilities = new Set<string>();
- const requestedCapabilities = options.capabilities === undefined
- ? undefined
- : new Set(options.capabilities.map(capabilityKey));
try {
if (!(await stat(root)).isDirectory()) throw new Error(`Runtime root ${root} is not a directory`);
} catch (error) {
- 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 };
+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) {
+ return { dataRoot: root, diagnostics: [diagnostic(error, "RUNTIME_DATA_ROOT_INVALID", root)] };
}
}
const registry = options.registry ?? new RuntimeAdapterRegistry();
- const runtimePackages = installRuntimeAdapters(
- registry,
- packageRoot,
- runtimePackageSelection(document),
- );
- const [runtimeResult] = await Promise.allSettled([runtimePackages]);
- if (runtimeResult.status === "rejected") {
- diagnostics.push(diagnostic(runtimeResult.reason, "RUNTIME_PACKAGE_SELECTION_INVALID"));
- return { dataRoot: root, diagnostics };
+ try {
+ await installRuntimeAdapters(registry, packageRoot, runtimePackageSelection(document));
+ } catch (error) {
+ return { dataRoot: root, diagnostics: [diagnostic(error, "RUNTIME_PACKAGE_SELECTION_INVALID")] };
}
- for (const item of document.infrastructure) {
- const context = { dataRoot: root, instance: item.instance, config: item.config ?? {} };
- try {
- const selection = registry.validate(item.use, "infrastructure", context);
- diagnostics.push(...selection);
- if (selection.some((entry) => entry.severity === "error")) continue;
- } catch (error) {
- diagnostics.push(diagnostic(error, "RUNTIME_COMPONENT_CONFIG_INVALID", item.instance));
- continue;
- }
+ const storeSelections = [
+ { item: document.artifacts, kind: "artifact-store" as const },
+ ...document.credentials.map((item) => ({ item, kind: "credential-store" as const })),
+ ];
+ for (const selection of storeSelections) {
+ const context = { dataRoot: root, instance: selection.item.instance, config: selection.item.config ?? {} };
try {
- diagnostics.push(...await registry.doctor(item.use, "infrastructure", context));
+ diagnostics.push(...registry.validate(selection.item.use, selection.kind, context));
+ diagnostics.push(...await registry.doctor(selection.item.use, selection.kind, context));
} catch (error) {
- diagnostics.push(diagnostic(error, "RUNTIME_ADAPTER_DOCTOR_FAILED", item.instance));
+ diagnostics.push(diagnostic(error, "RUNTIME_COMPONENT_CONFIG_INVALID", selection.item.instance));
}
}
+ const requested = options.capabilities === undefined
+ ? undefined
+ : new Set(options.capabilities.map(capabilityKey));
+ const covered = new Set<string>();
+ const credentialEndpoints: RuntimeEndpointActivation[] = [];
for (const item of document.endpoints) {
- const context = {
- dataRoot: root,
- instance: item.instance,
- pool: item.pool ?? item.instance,
- config: item.config ?? {},
- };
let activation: RuntimeEndpointActivation;
try {
- activation = await registry.activateEndpoint(item.use, context);
+ activation = await registry.activateEndpoint(item.use, {
+ dataRoot: root,
+ instance: item.instance,
+ pool: item.pool ?? item.instance,
+ config: item.config ?? {},
+ });
} catch (error) {
diagnostics.push(diagnostic(error, "RUNTIME_ENDPOINT_CONFIG_INVALID", item.instance));
continue;
}
- if (requestedCapabilities !== undefined && !activation.endpoint.offers.some((offer) =>
- requestedCapabilities.has(capabilityKey(offer.capability)))) {
- continue;
- }
- for (const offer of activation.endpoint.offers) {
- if (requestedCapabilities?.has(capabilityKey(offer.capability))) {
- coveredCapabilities.add(capabilityKey(offer.capability));
- }
- }
- let adapterHasError = false;
+ if (requested !== undefined && !activation.endpoint.offers.some((offer) => requested.has(capabilityKey(offer.capability)))) continue;
+ for (const offer of activation.endpoint.offers) covered.add(capabilityKey(offer.capability));
try {
- const adapterDiagnostics = activation.diagnose === undefined ? [] : await activation.diagnose();
- diagnostics.push(...adapterDiagnostics);
- adapterHasError = adapterDiagnostics.some((entry) => entry.severity === "error");
+ diagnostics.push(...(activation.diagnose === undefined ? [] : await activation.diagnose()));
} catch (error) {
diagnostics.push(diagnostic(error, "RUNTIME_ADAPTER_DOCTOR_FAILED", item.instance));
- continue;
- }
- if (adapterHasError) continue;
- credentialEndpoints.push({ entry: item, activation });
- // 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. This is the separate process a deployment must have installed or running.
- let program: ManagedProgram | undefined;
- try {
- program = activation.program;
- } catch (error) {
- diagnostics.push(diagnostic(error, "MANAGED_PROGRAM_INVALID", item.instance));
}
+ credentialEndpoints.push(activation);
+ const program = activation.program;
if (program === undefined) continue;
let state: ManagedProgramState;
try {
@@ -465,83 +377,45 @@ export async function doctorRuntimeConfig(
diagnostics.push(diagnostic(error, "MANAGED_PROGRAM_PROBE_FAILED", program.id));
continue;
}
- if (state.state === "down") {
- diagnostics.push({
- severity: "error",
- code: "MANAGED_PROGRAM_DOWN",
- message: `${program.id} is not usable: ${state.detail}.${
- program.start === undefined && program.prepare === undefined
- ? ""
- : " Bring it up with: narratage programs up"}`,
- subject: program.id,
- });
- } else if (state.state === "mismatch") {
+ if (state.state !== "ready") {
diagnostics.push({
severity: "error",
- code: "MANAGED_PROGRAM_MISMATCH",
- message: `${program.id} is running but differs from this Runtime Profile: ${state.detail}`,
+ code: state.state === "down" ? "MANAGED_PROGRAM_DOWN" : "MANAGED_PROGRAM_MISMATCH",
+ message: `${program.id} is not usable: ${state.detail}`,
subject: program.id,
});
}
}
for (const capability of options.capabilities ?? []) {
- if (coveredCapabilities.has(capabilityKey(capability))) continue;
- diagnostics.push({
+ if (!covered.has(capabilityKey(capability))) diagnostics.push({
severity: "error",
code: "RUNTIME_CAPABILITY_UNBOUND",
message: `No usable Endpoint in this Runtime Profile fulfills ${capabilityKey(capability)}`,
subject: capabilityKey(capability),
});
}
- if (credentialEndpoints.length > 0) {
- let packages: readonly RuntimeInfrastructurePackage[] = [];
+ if (credentialEndpoints.some((item) => item.endpoint.credentials.length > 0)) {
+ let stores: Awaited<ReturnType<typeof openCredentialStores>> | undefined;
try {
- const endpoints = credentialEndpoints.map(({ entry, activation }) => ({
- entry,
- credentials: activation.endpoint.credentials,
- }));
- if (endpoints.every((item) => item.credentials.length === 0)) return { dataRoot: root, diagnostics };
- const serviceEntries = runtimeEntriesForParts(
- document.infrastructure,
- document.roles.credentialStores,
- );
- packages = await Promise.all(serviceEntries.map(async (item) => await registry.createInfrastructure(item.use, {
- dataRoot: root,
- instance: item.instance,
- config: item.config ?? {},
- })));
- for (const item of packages) verifyRuntimeInfrastructurePackage(item);
- const byPart = new Map(packages.flatMap((item) =>
- item.parts.map((component) => [`${component.owner}\u0000${component.part}`, component] as const)));
- const stores = document.roles.credentialStores.map((reference) => {
- const component = byPart.get(`${reference.from}\u0000${reference.part}`);
- if (component === undefined) {
- throw new Error(`CredentialStore role refers to unknown part ${reference.from}.${reference.part}`);
- }
- if (component.role !== "credential-store") {
- throw new Error(`Runtime part ${reference.from}.${reference.part} is ${component.role}, not credential-store`);
- }
- return component.port;
- });
- const credentials = new CompositeCredentialStore(stores);
- for (const { entry, credentials: slots } of endpoints) {
- for (const slot of slots) {
- if (await credentials.resolve(slot.ref) !== undefined) continue;
+ stores = await openCredentialStores(document, root, registry, true);
+ for (const activation of credentialEndpoints) {
+ for (const slot of activation.endpoint.credentials) {
+ if (await stores.store.resolve(slot.ref) !== undefined) continue;
diagnostics.push({
severity: "error",
code: "RUNTIME_CREDENTIAL_MISSING",
- message: `${slot.label} for Endpoint ${entry.instance} is not configured in CredentialStore ${slot.ref.store}. `
- + (slot.ref.store === "env"
- ? `Set ${slot.ref.key} in this process environment, or select a writable CredentialStore in the Runtime Profile.`
- : `Configure it with: narratage auth login ${entry.instance} --runtime ${absolute}`),
- subject: `${entry.instance}.${slot.slot}`,
+ message: `${slot.label} for Endpoint ${slot.endpoint} is not configured. ${
+ slot.ref.store === "env"
+ ? `Set ${slot.ref.key} in this process environment.`
+ : `Configure it with: narratage auth login ${slot.endpoint} --runtime ${absolute}`}`,
+ subject: `${slot.endpoint}.${slot.slot}`,
});
}
}
} catch (error) {
diagnostics.push(diagnostic(error, "RUNTIME_CREDENTIAL_CHECK_FAILED"));
} finally {
- await closeRuntimeInfrastructurePackages(packages);
+ await stores?.close();
}
}
return { dataRoot: root, diagnostics };
@@ -551,213 +425,133 @@ export async function createRuntimeFromConfig(
path: string,
options: LoadRuntimeConfigOptions = {},
): Promise<LocalRuntime> {
- // 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);
const registry = options.registry ?? new RuntimeAdapterRegistry();
- await Promise.all([
- installRuntimeAdapters(
- registry,
- packageRoot,
- runtimePackageSelection(document),
- ),
- ]);
- const infrastructure = await Promise.all(document.infrastructure.map(async (item) => {
- return await registry.createInfrastructure(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, {
+ await installRuntimeAdapters(registry, packageRoot, runtimePackageSelection(document));
+ const state = new SqliteRuntimeState(statePath(root));
+ let artifacts: RuntimeOpened<ArtifactStore> | undefined;
+ let credentials: Awaited<ReturnType<typeof openCredentialStores>> | undefined;
+ try {
+ artifacts = await openArtifactStore(document, root, registry, false);
+ credentials = await openCredentialStores(document, root, registry, false);
+ const endpoints = await Promise.all(document.endpoints.map(async (item) => await registry.createEndpoint(item.use, {
dataRoot: root,
instance: item.instance,
pool: item.pool ?? item.instance,
config: item.config ?? {},
+ })));
+ return await createLocalRuntime({
+ buildStore: state.builds,
+ buildCatalog: state.catalog,
+ operationStore: state.operations,
+ dispatchStore: state.dispatch,
+ artifactStore: artifacts.value,
+ credentialStore: credentials.store,
+ components: [
+ ...collectNodePackageComponents((options.implementationPackages ?? []).map((item) => item.contribution)),
+ ...(options.components ?? []),
+ ],
+ endpoints,
+ scheduling: { maxConcurrency: document.concurrency },
+ close: async () => {
+ await credentials?.close();
+ await artifacts?.close?.();
+ state.close();
+ },
});
- }));
- return await createProjectLocalRuntime({
- dataRoot: root,
- packageRoot,
- infrastructure,
- roles: document.roles,
- components: [
- ...collectNodePackageComponents((options.implementationPackages ?? []).map((item) => item.contribution)),
- ...(options.components ?? []),
- ],
- endpoints,
- scheduling: document.capacity,
- });
-}
-
-async function createSelectedRuntimeInfrastructure(
- document: RuntimeConfigDocument,
- root: string,
- packageRoot: string,
- registry: RuntimeAdapterRegistry,
- references: readonly RuntimePartReference[],
- readOnly: boolean,
-): Promise<readonly RuntimeInfrastructurePackage[]> {
- const serviceEntries = runtimeEntriesForParts(document.infrastructure, references);
- await installRuntimeAdapters(registry, packageRoot, {
- selected: [],
- logical: serviceEntries.map((item) => ({ abi: runtimeInfrastructureHostAbi, name: item.use })),
- });
- const packages: RuntimeInfrastructurePackage[] = [];
- try {
- for (const item of serviceEntries) {
- packages.push(await registry.createInfrastructure(item.use, {
- dataRoot: root,
- instance: item.instance,
- config: item.config ?? {},
- access: readOnly ? "read-only" : "read-write",
- }));
- }
- return packages;
} catch (error) {
- await closeRuntimeInfrastructurePackages(packages);
+ await credentials?.close();
+ await artifacts?.close?.();
+ state.close();
throw error;
}
}
-/** Open Build, Operation and Dispatch state without constructing an ArtifactStore. */
export async function createRuntimeArchiveFromConfig(
path: string,
options: LoadRuntimeConfigOptions = {},
): Promise<LocalRuntimeArchiveControl> {
- const { createProjectLocalRuntimeArchiveControl } = await import("./control.js");
- const { document, root, packageRoot } = await openRuntimeConfig(path, options.packageRoot);
- const registry = options.registry ?? new RuntimeAdapterRegistry();
- const infrastructure = await createSelectedRuntimeInfrastructure(document, root, packageRoot, registry, [
- document.roles.buildStore,
- document.roles.operationStore,
- document.roles.dispatchStore,
- ], options.readOnly === true);
- return await createProjectLocalRuntimeArchiveControl({
- dataRoot: root,
- infrastructure,
- roles: document.roles,
+ const { root } = await openRuntimeConfig(path, options.packageRoot);
+ const state = new SqliteRuntimeState(statePath(root), { readOnly: options.readOnly === true });
+ return createLocalRuntimeArchiveControl({
+ buildStore: state.builds,
+ buildCatalog: state.catalog,
+ operationStore: state.operations,
+ dispatchStore: state.dispatch,
+ close: () => state.close(),
});
}
-/** Open only the ArtifactStore selected by a Runtime Profile. */
export async function createRuntimeArtifactAccessFromConfig(
path: string,
options: LoadRuntimeConfigOptions = {},
): Promise<LocalRuntimeArtifactAccess> {
- const { createProjectLocalRuntimeArtifactAccess } = await import("./control.js");
const { document, root, packageRoot } = await openRuntimeConfig(path, options.packageRoot);
const registry = options.registry ?? new RuntimeAdapterRegistry();
- const infrastructure = await createSelectedRuntimeInfrastructure(document, root, packageRoot, registry, [
- document.roles.artifactStore,
- ], options.readOnly === true);
- return await createProjectLocalRuntimeArtifactAccess({
- dataRoot: root,
- infrastructure,
- roles: document.roles,
+ await installRuntimeAdapters(registry, packageRoot, {
+ selected: [], logical: [{ abi: runtimeArtifactStoreAdapterHostAbi, name: document.artifacts.use }],
+ });
+ const opened = await openArtifactStore(document, root, registry, options.readOnly === true);
+ return createLocalRuntimeArtifactAccess({
+ artifactStore: opened.value,
+ ...(opened.close === undefined ? {} : { close: opened.close }),
});
}
-/** Open state plus Artifacts only for explicit cross-store maintenance such as GC. */
export async function createRuntimeMaintenanceFromConfig(
path: string,
options: LoadRuntimeConfigOptions = {},
): Promise<LocalRuntimeControl> {
- const { createProjectLocalRuntimeControl } = await import("./control.js");
const { document, root, packageRoot } = await openRuntimeConfig(path, options.packageRoot);
const registry = options.registry ?? new RuntimeAdapterRegistry();
- const infrastructure = await createSelectedRuntimeInfrastructure(document, root, packageRoot, registry, [
- document.roles.buildStore,
- document.roles.operationStore,
- document.roles.dispatchStore,
- document.roles.artifactStore,
- ], options.readOnly === true);
- return await createProjectLocalRuntimeControl({
- dataRoot: root,
- infrastructure,
- roles: document.roles,
+ await installRuntimeAdapters(registry, packageRoot, {
+ selected: [], logical: [{ abi: runtimeArtifactStoreAdapterHostAbi, name: document.artifacts.use }],
});
-}
-
-function runtimeEntriesForParts(
- entries: readonly RuntimeConfigEntry[],
- references: readonly RuntimePartReference[],
-): readonly RuntimeConfigEntry[] {
- const selected = new Set<RuntimeConfigEntry>();
- for (const reference of references) {
- const owner = entries.find((entry) => entry.instance === reference.from);
- if (owner === undefined) {
- throw new Error(`Runtime role refers to unknown infrastructure instance ${reference.from}`);
- }
- selected.add(owner);
+ const state = new SqliteRuntimeState(statePath(root), { readOnly: options.readOnly === true });
+ try {
+ const artifacts = await openArtifactStore(document, root, registry, options.readOnly === true);
+ return createLocalRuntimeControl({
+ buildStore: state.builds,
+ buildCatalog: state.catalog,
+ operationStore: state.operations,
+ dispatchStore: state.dispatch,
+ artifactStore: artifacts.value,
+ close: async () => {
+ await artifacts.close?.();
+ state.close();
+ },
+ });
+ } catch (error) {
+ state.close();
+ throw error;
}
- return [...selected];
-}
-
-async function closeRuntimeInfrastructurePackages(packages: readonly RuntimeInfrastructurePackage[]): Promise<void> {
- for (const item of [...packages].reverse()) await item.close?.();
}
-/**
- * Open the smallest deployment slice required to manage one exact Endpoint's
- * credentials. Build Stores, scheduler, Worker, author packages and unrelated
- * Endpoints are deliberately not constructed.
- */
export async function createRuntimeCredentialsFromConfig(
path: string,
endpointInstance: string,
options: LoadRuntimeConfigOptions = {},
): Promise<LocalCredentialControl> {
- const { createLocalCredentialControl } = await import("./credentials.js");
const { document, 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 endpoint = document.endpoints.find((item) => item.instance === endpointInstance);
+ if (endpoint === undefined) throw new Error(`Runtime Profile has no Endpoint instance ${endpointInstance}`);
const registry = options.registry ?? new RuntimeAdapterRegistry();
- const serviceEntries = runtimeEntriesForParts(
- document.infrastructure,
- document.roles.credentialStores,
- );
- await installRuntimeAdapters(registry, packageRoot, {
- selected: [],
- logical: [
- { abi: runtimeEndpointAdapterHostAbi, name: endpointEntry.use },
- ...serviceEntries.map((item) => ({ abi: runtimeInfrastructureHostAbi, name: item.use })),
- ],
- });
- const packages = await Promise.all(serviceEntries.map(async (item) => await registry.createInfrastructure(item.use, {
- dataRoot: root,
- instance: item.instance,
- config: item.config ?? {},
- })));
+ await installRuntimeAdapters(registry, packageRoot, runtimePackageSelection(document));
+ const credentials = await openCredentialStores(document, root, registry, false);
try {
- for (const item of packages) verifyRuntimeInfrastructurePackage(item);
- const byPart = new Map(packages.flatMap((item) => item.parts
- .map((component) => [`${component.owner}\u0000${component.part}`, component] as const)));
- const credentialStores = document.roles.credentialStores.map((reference) => {
- const component = byPart.get(`${reference.from}\u0000${reference.part}`);
- if (component === undefined) {
- throw new Error(`CredentialStore role refers to unknown part ${reference.from}.${reference.part}`);
- }
- if (component.role !== "credential-store") {
- throw new Error(`Runtime part ${reference.from}.${reference.part} is ${component.role}, not credential-store`);
- }
- return component.port;
- });
- const endpoint = await registry.createEndpoint(endpointEntry.use, {
+ const endpointPackage = await registry.createEndpoint(endpoint.use, {
dataRoot: root,
- instance: endpointEntry.instance,
- pool: endpointEntry.pool ?? endpointEntry.instance,
- config: endpointEntry.config ?? {},
+ instance: endpoint.instance,
+ pool: endpoint.pool ?? endpoint.instance,
+ config: endpoint.config ?? {},
});
return createLocalCredentialControl({
- credentialStore: new CompositeCredentialStore(credentialStores),
- endpoints: [endpoint],
- close: async () => await closeRuntimeInfrastructurePackages(packages),
+ credentialStore: credentials.store,
+ endpoints: [endpointPackage],
+ close: credentials.close,
});
} catch (error) {
- await closeRuntimeInfrastructurePackages(packages);
+ await credentials.close();
throw error;
}
}
diff --git a/packages/runtime-local/src/control.ts b/packages/runtime-local/src/control.ts
index 76221afd..edc1d1df 100644
--- a/packages/runtime-local/src/control.ts
+++ b/packages/runtime-local/src/control.ts
@@ -3,12 +3,6 @@ import {
isEnumerableBuildStore,
isManagedArtifactStore,
isStreamingArtifactStore,
- verifyRuntimeInfrastructurePackage,
-} from "@narratage/runtime";
-import type {
- RuntimePart,
- RuntimeInfrastructurePackage,
- RuntimePartReference,
} from "@narratage/runtime";
import type {
@@ -18,11 +12,7 @@ import type {
LocalRuntimeArchiveControl,
LocalRuntimeArtifactAccess,
LocalRuntimeControl,
- ProjectLocalRuntimeArchiveControlOptions,
- ProjectLocalRuntimeArtifactAccessOptions,
- ProjectLocalRuntimeControlOptions,
} from "./types.js";
-import { selectedBuildCatalog } from "./project-infrastructure.js";
function assert(condition: unknown, message: string): asserts condition {
if (!condition) throw new Error(message);
@@ -160,114 +150,3 @@ export function createLocalRuntimeControl(
},
};
}
-
-type OpenedProjectInfrastructure = {
- readonly packages: readonly RuntimeInfrastructurePackage[];
- readonly parts: ReadonlyMap<string, { readonly package: RuntimeInfrastructurePackage; readonly part: RuntimePart }>;
- close(): Promise<void>;
-};
-
-async function openProjectInfrastructure(
- options: ProjectLocalRuntimeControlOptions,
-): Promise<OpenedProjectInfrastructure> {
- const packages = [...options.infrastructure];
- const parts = new Map<string, { readonly package: RuntimeInfrastructurePackage; readonly part: RuntimePart }>();
- try {
- for (const item of packages) {
- verifyRuntimeInfrastructurePackage(item);
- for (const part of item.parts) {
- const key = `${part.owner}\u0000${part.part}`;
- assert(!parts.has(key), `Runtime part ${part.owner}.${part.part} is configured twice`);
- parts.set(key, { package: item, part });
- }
- }
- let closed = false;
- return {
- packages,
- parts,
- close: async () => {
- if (closed) return;
- closed = true;
- for (const item of [...packages].reverse()) await item.close?.();
- },
- };
- } catch (error) {
- for (const item of [...packages].reverse()) await item.close?.();
- throw error;
- }
-}
-
-function selectedPart<Role extends RuntimePart["role"]>(
- opened: OpenedProjectInfrastructure,
- reference: RuntimePartReference,
- role: Role,
-): Extract<RuntimePart, { readonly role: Role }> {
- const key = `${reference.from}\u0000${reference.part}`;
- const item = opened.parts.get(key);
- assert(item !== undefined, `Runtime role refers to unknown part ${reference.from}.${reference.part}`);
- assert(item.part.role === role,
- `Runtime part ${reference.from}.${reference.part} is ${item.part.role}, not ${role}`);
- return item.part as Extract<RuntimePart, { 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 openProjectInfrastructure(options);
- try {
- const build = selectedPart(opened, options.roles.buildStore, "build-store");
- const operations = selectedPart(opened, options.roles.operationStore, "operation-store");
- const dispatch = selectedPart(opened, options.roles.dispatchStore, "dispatch-store");
- const catalog = selectedBuildCatalog(opened.packages, options.roles.buildStore);
- return createLocalRuntimeArchiveControl({
- buildStore: build.port,
- ...(catalog === undefined ? {} : { buildCatalog: catalog }),
- operationStore: operations.port,
- dispatchStore: dispatch.port,
- close: opened.close,
- });
- } catch (error) {
- await opened.close();
- throw error;
- }
-}
-
-/** Assemble only the ArtifactStore selected by the Profile. */
-export async function createProjectLocalRuntimeArtifactAccess(
- options: ProjectLocalRuntimeArtifactAccessOptions,
-): Promise<LocalRuntimeArtifactAccess> {
- const opened = await openProjectInfrastructure(options);
- try {
- const artifacts = selectedPart(opened, options.roles.artifactStore, "artifact-store");
- return createLocalRuntimeArtifactAccess({ artifactStore: artifacts.port, close: opened.close });
- } catch (error) {
- await opened.close();
- throw error;
- }
-}
-
-/** Assemble all durable Stores only for execution or explicit cross-store maintenance. */
-export async function createProjectLocalRuntimeControl(
- options: ProjectLocalRuntimeControlOptions,
-): Promise<LocalRuntimeControl> {
- const opened = await openProjectInfrastructure(options);
- try {
- const build = selectedPart(opened, options.roles.buildStore, "build-store");
- const operations = selectedPart(opened, options.roles.operationStore, "operation-store");
- const dispatch = selectedPart(opened, options.roles.dispatchStore, "dispatch-store");
- const artifacts = selectedPart(opened, options.roles.artifactStore, "artifact-store");
- const catalog = selectedBuildCatalog(opened.packages, options.roles.buildStore);
- return createLocalRuntimeControl({
- buildStore: build.port,
- ...(catalog === undefined ? {} : { buildCatalog: catalog }),
- operationStore: operations.port,
- dispatchStore: dispatch.port,
- artifactStore: artifacts.port,
- close: opened.close,
- });
- } catch (error) {
- await opened.close();
- throw error;
- }
-}
diff --git a/packages/runtime-local/src/index.ts b/packages/runtime-local/src/index.ts
index fae26921..a725a260 100644
--- a/packages/runtime-local/src/index.ts
+++ b/packages/runtime-local/src/index.ts
@@ -1,18 +1,11 @@
-export {
- createLocalExecutionPackage,
-} from "./scheduler-package.js";
export {
createLocalRuntimeArchiveControl,
createLocalRuntimeArtifactAccess,
createLocalRuntimeControl,
- createProjectLocalRuntimeArchiveControl,
- createProjectLocalRuntimeArtifactAccess,
- createProjectLocalRuntimeControl,
} from "./control.js";
export { createLocalCredentialControl } from "./credentials.js";
export {
createLocalRuntime,
- createProjectLocalRuntime,
} from "./runtime.js";
export {
createRuntimeFromConfig,
diff --git a/packages/runtime-local/src/project-infrastructure.ts b/packages/runtime-local/src/project-infrastructure.ts
deleted file mode 100644
index a0569e7f..00000000
--- a/packages/runtime-local/src/project-infrastructure.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-import {
- assembleRuntimeInfrastructure,
- verifyRuntimeInfrastructurePackage,
-} from "@narratage/runtime";
-import type {
- BuildCatalog,
- RuntimeInfrastructureAssembly,
- RuntimeInfrastructurePackage,
- RuntimePartReference,
- RuntimeRoleSelection,
-} from "@narratage/runtime";
-
-import type { ProjectLocalRuntimeControlOptions } from "./types.js";
-
-export type ProjectRuntimeRoles = RuntimeRoleSelection;
-export type ProjectRuntimeInfrastructureAssembly = RuntimeInfrastructureAssembly;
-
-export type AssembledProjectRuntimeInfrastructure = {
- readonly assembly: ProjectRuntimeInfrastructureAssembly;
- readonly catalog: BuildCatalog | undefined;
- readonly selection: ProjectRuntimeRoles;
- close(): Promise<void>;
-};
-
-function assert(condition: unknown, message: string): asserts condition {
- if (!condition) throw new Error(message);
-}
-
-export function selectedBuildCatalog(
- packages: readonly RuntimeInfrastructurePackage[],
- buildStore: RuntimePartReference,
-): BuildCatalog | undefined {
- const owner = packages.find((item) => item.parts.some((part) =>
- part.role === "build-store"
- && part.owner === buildStore.from
- && part.part === buildStore.part));
- if (owner === undefined) return undefined;
- const catalog = owner.buildCatalog;
- if (catalog === undefined) return undefined;
- assert(catalog !== null && typeof catalog === "object"
- && "record" in catalog && typeof catalog.record === "function"
- && "read" in catalog && typeof catalog.read === "function"
- && "list" in catalog && typeof catalog.list === "function",
- `Runtime part ${buildStore.from}.${buildStore.part} exposes an invalid Build Catalog`);
- return catalog as BuildCatalog;
-}
-
-/**
- * Assemble only the infrastructure parts 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 createProjectRuntimeInfrastructure(
- _root: string,
- options: ProjectLocalRuntimeControlOptions,
-): Promise<AssembledProjectRuntimeInfrastructure> {
- const packages = [...options.infrastructure];
- try {
- for (const item of packages) verifyRuntimeInfrastructurePackage(item);
- const assembly = assembleRuntimeInfrastructure(packages, options.roles);
- const catalog = selectedBuildCatalog(packages, options.roles.buildStore);
- return {
- assembly,
- catalog,
- selection: options.roles,
- close: () => assembly.close(),
- };
- } catch (error) {
- for (const item of [...packages].reverse()) await item.close?.();
- throw error;
- }
-}
diff --git a/packages/runtime-local/src/runtime.ts b/packages/runtime-local/src/runtime.ts
index b7c5b6d3..b3e71a82 100644
--- a/packages/runtime-local/src/runtime.ts
+++ b/packages/runtime-local/src/runtime.ts
@@ -1,5 +1,3 @@
-import { resolve } from "node:path";
-
import {
registerProducerFacets,
registerTypeValidatorFacets,
@@ -10,13 +8,11 @@ import {
EndpointRegistry,
} from "@narratage/driver-node";
import {
- LocalBuildScheduler,
createBuildDispatchIdentity,
isStreamingArtifactStore,
} from "@narratage/runtime";
import { TypeValidatorRegistry } from "@narratage/validation";
-import { createProjectRuntimeInfrastructure } from "./project-infrastructure.js";
import { createLocalRuntimeControl } from "./control.js";
import { createLocalCredentialControl } from "./credentials.js";
import { createDurableLocalWorker } from "./worker.js";
@@ -27,7 +23,6 @@ import type {
LocalBuildSubmission,
LocalRuntime,
EndpointPackage,
- ProjectLocalRuntimeOptions,
} from "./types.js";
function assert(condition: unknown, message: string): asserts condition {
@@ -92,11 +87,6 @@ export async function createLocalRuntime(
});
const scheduling = options.scheduling;
const worker = createDurableLocalWorker(driver, {
- scheduler: {
- create(executor, schedulerOptions) {
- return new LocalBuildScheduler(executor, schedulerOptions);
- },
- },
stores: {
builds: options.buildStore,
operations: options.operationStore,
@@ -210,65 +200,3 @@ export async function createLocalRuntime(
close: control.close,
};
}
-
-/**
- * Node project assembly over only the Runtime infrastructure 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.dataRoot ?? process.cwd());
- const packageRoot = resolve(options.packageRoot ?? root);
- const configuredComponents = options.components ?? [];
- const projectInfrastructure = await createProjectRuntimeInfrastructure(root, options);
- const infrastructure = projectInfrastructure.assembly;
- const endpointPackages = options.endpoints ?? [];
-
- try {
- verifyEndpointPackages(endpointPackages);
- const runtime = await createLocalRuntime({
- buildStore: infrastructure.buildStore,
- ...(projectInfrastructure.catalog === undefined ? {} : { buildCatalog: projectInfrastructure.catalog }),
- operationStore: infrastructure.operationStore,
- dispatchStore: infrastructure.dispatchStore,
- artifactStore: infrastructure.artifactStore,
- credentialStore: infrastructure.credentialStore,
- ...(configuredComponents.length === 0
- ? {}
- : { components: configuredComponents }),
- endpoints: endpointPackages,
- scheduling: {
- maxConcurrency: options.scheduling.maxConcurrency,
- ...(options.scheduling.resources === undefined ? {} : {
- resourceLimits: options.scheduling.resources,
- }),
- },
- close: projectInfrastructure.close,
- ...(options.validators === undefined ? {} : { validators: options.validators }),
- });
- return {
- build: runtime.build,
- buildMany: runtime.buildMany,
- status: runtime.status,
- activity: runtime.activity,
- queue: runtime.queue,
- operation: runtime.operation,
- credentials: runtime.credentials,
- putCredential: runtime.putCredential,
- deleteCredential: runtime.deleteCredential,
- builds: runtime.builds,
- cancel: runtime.cancel,
- workOnce: runtime.workOnce,
- work: runtime.work,
- readArtifact: runtime.readArtifact,
- openArtifact: runtime.openArtifact,
- garbageCollectArtifacts: runtime.garbageCollectArtifacts,
- close: runtime.close,
- };
- } catch (error) {
- await projectInfrastructure.close();
- throw error;
- }
-}
diff --git a/packages/runtime-local/src/scheduler-package.ts b/packages/runtime-local/src/scheduler-package.ts
deleted file mode 100644
index 0069523b..00000000
--- a/packages/runtime-local/src/scheduler-package.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import {
- LocalBuildScheduler,
- defineRuntimeInfrastructurePackage,
-} from "@narratage/runtime";
-import type { RuntimeInfrastructurePackage } from "@narratage/runtime";
-
-import { createDurableLocalWorker } from "./worker.js";
-
-const localRuntimeModuleRef = {
- name: "@narratage/runtime-local",
- version: "1",
-} as const;
-
-export function createLocalExecutionPackage(
- instance: string,
-): RuntimeInfrastructurePackage {
- return defineRuntimeInfrastructurePackage({
- module: localRuntimeModuleRef,
- instance,
- parts: [
- {
- role: "scheduler",
- part: "scheduler",
- facet: "scheduler",
- port: {
- create(executor, options) {
- return new LocalBuildScheduler(executor, options);
- },
- },
- },
- {
- role: "worker",
- part: "worker",
- facet: "worker",
- port: { create: createDurableLocalWorker },
- },
- ],
- });
-}
diff --git a/packages/runtime-local/src/types.ts b/packages/runtime-local/src/types.ts
index d3158694..9ec83444 100644
--- a/packages/runtime-local/src/types.ts
+++ b/packages/runtime-local/src/types.ts
@@ -16,8 +16,6 @@ import type {
CredentialStore,
OperationStore,
OperationSnapshot,
- RuntimeInfrastructurePackage,
- RuntimeRoleSelection,
} from "@narratage/runtime";
import type { TypeValidatorRegistrar, TypeValidatorRegistryLike } from "@narratage/validation";
@@ -26,11 +24,10 @@ export type { ComponentPackage } from "@narratage/component-kit";
export type LocalTypeValidatorRegistry = TypeValidatorRegistryLike & TypeValidatorRegistrar;
export type { EndpointPackage } from "@narratage/endpoint-kit";
-export type { RuntimeInfrastructurePackage } from "@narratage/runtime";
export type CreateLocalRuntimeOptions = {
readonly buildStore: BuildStore;
- /** Host presentation metadata only; never part of Runtime Closure or Core state. */
+ /** Host presentation metadata only; never part of Core state. */
readonly buildCatalog?: BuildCatalog;
readonly operationStore: OperationStore;
readonly dispatchStore: import("@narratage/runtime").BuildDispatchStore;
@@ -48,13 +45,13 @@ export type CreateLocalRuntimeArchiveControlOptions = {
readonly buildCatalog?: BuildCatalog;
readonly operationStore: OperationStore;
readonly dispatchStore: BuildDispatchStore;
- /** Optional owner supplied by the project infrastructure assembly. */
+ /** Optional owner supplied by the Runtime assembly. */
readonly close?: () => Awaitable<void>;
};
export type CreateLocalRuntimeArtifactAccessOptions = {
readonly artifactStore: ArtifactStore;
- /** Optional owner supplied by the project infrastructure assembly. */
+ /** Optional owner supplied by the Runtime assembly. */
readonly close?: () => Awaitable<void>;
};
@@ -67,37 +64,6 @@ export type CreateLocalCredentialControlOptions = {
readonly close?: () => Awaitable<void>;
};
-export type ProjectLocalRuntimeOptions = {
- /** Runtime data boundary. It does not grant access to author source. */
- readonly dataRoot?: string;
- /** Host directory whose node_modules contains selected implementation packages. Defaults to dataRoot. */
- readonly packageRoot?: string;
- /**
- * Replaceable parts of the Runtime itself. One package may fill several roles;
- * every selected role is explicit, and two packages exposing the same instance
- * id are a configuration error rather than a choice made here.
- */
- readonly infrastructure: readonly RuntimeInfrastructurePackage[];
- /** Exact Component instances selected by role; no role is inferred by uniqueness. */
- readonly roles: RuntimeRoleSelection;
- readonly components?: readonly ComponentPackage[];
- readonly endpoints?: readonly EndpointPackage[];
- readonly scheduling: {
- readonly maxConcurrency: number;
- readonly resources?: Readonly<Record<string, number>>;
- };
- readonly validators?: LocalTypeValidatorRegistry;
-};
-
-export type ProjectLocalRuntimeArchiveControlOptions = Pick<ProjectLocalRuntimeOptions,
- | "dataRoot"
- | "infrastructure"
- | "roles"
->;
-
-export type ProjectLocalRuntimeArtifactAccessOptions = ProjectLocalRuntimeArchiveControlOptions;
-export type ProjectLocalRuntimeControlOptions = ProjectLocalRuntimeArchiveControlOptions;
-
export type LocalBuildRequest = {
/** Caller-generated identity for one submission; Source identity is separate. */
readonly id: string;
diff --git a/packages/runtime-local/src/worker.ts b/packages/runtime-local/src/worker.ts
index 19441c49..72a8298c 100644
--- a/packages/runtime-local/src/worker.ts
+++ b/packages/runtime-local/src/worker.ts
@@ -1,15 +1,22 @@
import type { BuildState } from "@narratage/protocol";
import type {
BuildDispatchSnapshot,
+ BuildSchedulerOptions,
CapacityResourceClaim,
RuntimeCommandExecutor,
RuntimeExecutionResult,
RuntimePreparation,
RuntimeRunnableCommand,
RuntimeWorker,
- RuntimeWorkerFactoryOptions,
+ RuntimeExecutionStores,
RuntimeWorkerRunOptions,
} from "@narratage/runtime";
+import { LocalBuildScheduler } from "@narratage/runtime";
+
+type LocalWorkerOptions = {
+ readonly stores: RuntimeExecutionStores;
+ readonly scheduling: BuildSchedulerOptions;
+};
function assert(condition: unknown, message: string): asserts condition {
if (!condition) throw new Error(message);
@@ -98,10 +105,10 @@ class CommandGate {
/** Adds persistent in-flight limits only to asynchronous external Operations. */
class CapacityExecutor implements RuntimeCommandExecutor {
readonly #delegate: RuntimeCommandExecutor;
- readonly #options: RuntimeWorkerFactoryOptions;
+ readonly #options: LocalWorkerOptions;
readonly #gate: CommandGate;
- constructor(delegate: RuntimeCommandExecutor, options: RuntimeWorkerFactoryOptions, gate: CommandGate) {
+ constructor(delegate: RuntimeCommandExecutor, options: LocalWorkerOptions, gate: CommandGate) {
this.#delegate = delegate;
this.#options = options;
this.#gate = gate;
@@ -175,10 +182,10 @@ class CapacityExecutor implements RuntimeCommandExecutor {
class DurableLocalWorker implements RuntimeWorker {
readonly #executor: RuntimeCommandExecutor;
- readonly #options: RuntimeWorkerFactoryOptions;
+ readonly #options: LocalWorkerOptions;
readonly #executorWithCapacity: CapacityExecutor;
- constructor(executor: RuntimeCommandExecutor, options: RuntimeWorkerFactoryOptions) {
+ constructor(executor: RuntimeCommandExecutor, options: LocalWorkerOptions) {
this.#executor = executor;
this.#options = options;
this.#executorWithCapacity = new CapacityExecutor(executor, options, new CommandGate(
@@ -211,7 +218,7 @@ class DurableLocalWorker implements RuntimeWorker {
if (dispatch.cancellation !== undefined) return await this.#cancel(dispatch);
const stored = await this.#options.stores.builds.read(dispatch.build);
assert(stored !== undefined, `Dispatch ${dispatch.build} has no Build Definition`);
- const scheduler = this.#options.scheduler.create(this.#executorWithCapacity, {
+ const scheduler = new LocalBuildScheduler(this.#executorWithCapacity, {
...this.#options.scheduling,
buildStore: this.#options.stores.builds,
});
@@ -298,7 +305,7 @@ class DurableLocalWorker implements RuntimeWorker {
export function createDurableLocalWorker(
executor: RuntimeCommandExecutor,
- options: RuntimeWorkerFactoryOptions,
+ options: LocalWorkerOptions,
): RuntimeWorker {
return new DurableLocalWorker(executor, options);
}
diff --git a/packages/runtime-local/test/config.test.ts b/packages/runtime-local/test/config.test.ts
index 021e604b..258a6744 100644
--- a/packages/runtime-local/test/config.test.ts
+++ b/packages/runtime-local/test/config.test.ts
@@ -5,10 +5,11 @@ import { join } from "node:path";
import test from "node:test";
import {
- createRuntimeInfrastructureAdapterFacet,
+ createRuntimeArtifactStoreAdapterFacet,
createRuntimeEndpointAdapterFacet,
} from "@narratage/runtime-kit";
-import { createSqliteRuntimeInfrastructurePackage } from "@narratage/store-sqlite";
+import { MemoryArtifactStore } from "@narratage/driver-node";
+import { SqliteRuntimeState } from "@narratage/store-sqlite";
import {
createRuntimeArchiveFromConfig,
createRuntimeArtifactAccessFromConfig,
@@ -17,21 +18,11 @@ import {
RuntimeAdapterRegistry,
} from "@narratage/runtime-local";
-const roles = {
- scheduler: { from: "execution", part: "scheduler" },
- worker: { from: "execution", part: "worker" },
- buildStore: { from: "state", part: "builds" },
- operationStore: { from: "state", part: "operations" },
- dispatchStore: { from: "state", part: "dispatch" },
- artifactStore: { from: "artifacts", part: "store" },
- credentialStores: [] as { from: string; part: string }[],
-};
-
function profile(config: {
readonly dataRoot?: string;
- readonly infrastructure?: Readonly<Record<string, unknown>>;
+ readonly artifacts?: Readonly<Record<string, unknown>>;
+ readonly credentials?: Readonly<Record<string, unknown>>;
readonly endpoints?: Readonly<Record<string, unknown>>;
- readonly selectedRoles?: typeof roles;
} = {}) {
return {
format: "narratage.runtime-profile@1",
@@ -39,69 +30,45 @@ function profile(config: {
use: "@narratage/runtime-local",
config: {
dataRoot: config.dataRoot ?? ".narratage/runtimes/local",
- infrastructure: config.infrastructure ?? {},
- roles: config.selectedRoles ?? roles,
+ artifacts: config.artifacts ?? { use: "example.artifacts" },
+ credentials: config.credentials ?? {},
endpoints: config.endpoints ?? {},
- capacity: { maxActiveOperations: 3 },
+ concurrency: 3,
},
},
};
}
-test("Runtime Profile keeps deployment data separate from source and derives instance names from maps", () => {
+test("Runtime Profile names the stores and Endpoints used by one local Runtime", () => {
const parsed = parseRuntimeConfig(profile({
- infrastructure: { state: { use: "example.state", config: { path: "state.sqlite" } } },
+ credentials: { secrets: { use: "example.credentials" } },
endpoints: { generation: { use: "example.provider", pool: "shared" } },
}));
assert.equal(parsed.dataRoot, ".narratage/runtimes/local");
- assert.deepEqual(parsed.infrastructure, [{
- use: "example.state",
- instance: "state",
- config: { path: "state.sqlite" },
- }]);
- assert.deepEqual(parsed.endpoints, [{
- use: "example.provider",
- instance: "generation",
- pool: "shared",
- }]);
- assert.deepEqual(parsed.roles, roles);
- assert.equal("root" in parsed, false);
+ assert.deepEqual(parsed.artifacts, { use: "example.artifacts", instance: "artifacts" });
+ assert.deepEqual(parsed.credentials, [{ use: "example.credentials", instance: "secrets" }]);
+ assert.deepEqual(parsed.endpoints, [{ use: "example.provider", instance: "generation", pool: "shared" }]);
+ assert.equal(parsed.concurrency, 3);
});
test("Runtime Profile rejects source ownership fields", () => {
- assert.throws(() => parseRuntimeConfig({ ...profile(), root: "." }),
- /does not accept root/u);
+ assert.throws(() => parseRuntimeConfig({ ...profile(), root: "." }), /does not accept root/u);
});
-test("archive observation constructs only the infrastructure selected by archive roles", async () => {
+test("archive inspection opens SQLite only; Artifact access opens the selected Store", async () => {
const root = await mkdtemp(join(tmpdir(), "narratage-runtime-slice-"));
const path = join(root, "narratage.runtime.json");
- await writeFile(path, JSON.stringify(profile({
- dataRoot: ".",
- infrastructure: {
- state: { use: "example.state" },
- artifacts: { use: "example.artifacts" },
- },
- })));
+ await writeFile(path, JSON.stringify(profile({ dataRoot: "." })));
+ const state = new SqliteRuntimeState(join(root, "runtime.sqlite"));
+ state.close();
let artifactConstructions = 0;
const registry = new RuntimeAdapterRegistry();
- registry.registerFacet(createRuntimeInfrastructureAdapterFacet({
- use: "example.state",
- validate() {},
- create(context) {
- return createSqliteRuntimeInfrastructurePackage({
- path: join(context.dataRoot, "state.sqlite"),
- instance: context.instance,
- readOnly: context.access === "read-only",
- });
- },
- }));
- registry.registerFacet(createRuntimeInfrastructureAdapterFacet({
+ registry.registerFacet(createRuntimeArtifactStoreAdapterFacet({
use: "example.artifacts",
validate() {},
- create() {
+ open() {
artifactConstructions += 1;
- throw new Error("artifact adapter constructed");
+ return { value: new MemoryArtifactStore() };
},
}));
try {
@@ -109,14 +76,15 @@ test("archive observation constructs only the infrastructure selected by archive
assert.equal((await archive.status("missing")).build, undefined);
await archive.close();
assert.equal(artifactConstructions, 0);
- await assert.rejects(createRuntimeArtifactAccessFromConfig(path, { registry, readOnly: true }),
- /artifact adapter constructed/u);
+ const artifacts = await createRuntimeArtifactAccessFromConfig(path, { registry, readOnly: true });
+ await artifacts.close();
+ assert.equal(artifactConstructions, 1);
} finally {
await rm(root, { recursive: true, force: true });
}
});
-test("doctor reports a down Managed Program without inventing a Runtime default", async () => {
+test("doctor reports a down Managed Program", async () => {
const root = await mkdtemp(join(tmpdir(), "narratage-runtime-program-"));
const path = join(root, "narratage.runtime.json");
await writeFile(path, JSON.stringify(profile({
@@ -124,13 +92,17 @@ test("doctor reports a down Managed Program without inventing a Runtime default"
endpoints: { speech: { use: "example.speech" } },
})));
const registry = new RuntimeAdapterRegistry();
+ registry.registerFacet(createRuntimeArtifactStoreAdapterFacet({
+ use: "example.artifacts",
+ validate() {},
+ open: () => ({ value: new MemoryArtifactStore() }),
+ }));
registry.registerFacet(createRuntimeEndpointAdapterFacet({
use: "example.speech",
activate: (context) => ({
endpoint: {
name: context.instance,
- manifest: { facets: [] },
- instance: { id: context.instance },
+ instance: { id: context.instance, pool: context.pool ?? context.instance },
offers: [],
credentials: [],
install() {},
diff --git a/packages/runtime-local/test/local.test.ts b/packages/runtime-local/test/local.test.ts
index de5594c9..cd9ff78d 100644
--- a/packages/runtime-local/test/local.test.ts
+++ b/packages/runtime-local/test/local.test.ts
@@ -11,8 +11,8 @@ import { join } from "node:path";
import test from "node:test";
import { fixtureDigest } from "../../../test/fixture-digest.js";
-import { FileArtifactStore, createFileArtifactStorePackage } from "@narratage/artifact-store-fs";
-import { createEnvironmentCredentialStorePackage } from "@narratage/credential-store-env";
+import { FileArtifactStore } from "@narratage/artifact-store-fs";
+import { EnvironmentCredentialStore } from "@narratage/credential-store-env";
import { MemoryArtifactStore } from "@narratage/driver-node";
import { defineEndpointPackage } from "@narratage/endpoint-kit";
import type { AsyncEndpoint } from "@narratage/endpoint-kit";
@@ -20,15 +20,15 @@ import type {
ComponentPackage,
EndpointPackage,
} from "@narratage/runtime-local";
-import { createLocalExecutionPackage, createProjectLocalRuntime } from "@narratage/runtime-local";
+import { createLocalRuntime } from "@narratage/runtime-local";
import { buildDefinition } from "@narratage/core";
import {
collectNodePackageComponents,
loadNodePackageSelection,
} from "@narratage/package-loader-node";
-import { credentialRef, defineRuntimeInfrastructurePackage } from "@narratage/runtime";
+import { credentialRef } from "@narratage/runtime";
import type { CredentialValue, WritableCredentialStore } from "@narratage/runtime";
-import { createSqliteRuntimeInfrastructurePackage } from "@narratage/store-sqlite";
+import { SqliteRuntimeState } from "@narratage/store-sqlite";
import {
capabilities,
@@ -41,28 +41,16 @@ import {
const providerModule = { name: "example.local-endpoint", version: "1" } as const;
function projectRuntimeFixture(directory: string) {
- const execution = createLocalExecutionPackage("execution");
- const state = createSqliteRuntimeInfrastructurePackage({
- path: join(directory, ".narratage", "runtime.sqlite"),
- instance: "state",
- });
- const artifacts = createFileArtifactStorePackage({
- root: join(directory, ".narratage", "artifacts"),
- instance: "artifacts",
- });
- const credentials = createEnvironmentCredentialStorePackage({ instance: "credentials" });
+ const state = new SqliteRuntimeState(join(directory, ".narratage", "runtime.sqlite"));
return {
- infrastructure: [execution, state, artifacts, credentials],
- roles: {
- scheduler: { from: "execution", part: "scheduler" },
- worker: { from: "execution", part: "worker" },
- buildStore: { from: "state", part: "builds" },
- operationStore: { from: "state", part: "operations" },
- dispatchStore: { from: "state", part: "dispatch" },
- artifactStore: { from: "artifacts", part: "store" },
- credentialStores: [{ from: "credentials", part: "store" }],
- },
+ buildStore: state.builds,
+ buildCatalog: state.catalog,
+ operationStore: state.operations,
+ dispatchStore: state.dispatch,
+ artifactStore: new FileArtifactStore(join(directory, ".narratage", "artifacts")),
+ credentialStore: new EnvironmentCredentialStore(),
scheduling: { maxConcurrency: 4 },
+ close: () => state.close(),
} as const;
}
@@ -71,7 +59,7 @@ test("Artifact GC is explicit, dry-run by default, and only removes unreachable
try {
const artifacts = new FileArtifactStore(join(directory, ".narratage", "artifacts"));
const orphan = await artifacts.put(new TextEncoder().encode("orphan"), "application/octet-stream");
- const runtime = await createProjectLocalRuntime({ dataRoot: directory, ...projectRuntimeFixture(directory) });
+ const runtime = await createLocalRuntime(projectRuntimeFixture(directory));
const preview = await runtime.garbageCollectArtifacts();
assert.deepEqual(preview.unreachable, [orphan.digest]);
assert.deepEqual(preview.deleted, []);
@@ -93,16 +81,6 @@ test("Endpoint-declared credentials use the selected writable Store without a Pr
async put(ref, value) { values.set(ref.key, value); },
async delete(ref) { return values.delete(ref.key); },
};
- const memoryCredentials = defineRuntimeInfrastructurePackage({
- module: { name: "example.credentials-memory", version: "1" },
- instance: "memory-credentials",
- parts: [{
- role: "credential-store",
- facet: "credential-store",
- part: "store",
- port: credentialStore,
- }],
- });
const endpoint = defineEndpointPackage({
module: providerModule,
facet: "generation",
@@ -121,15 +99,9 @@ test("Endpoint-declared credentials use the selected writable Store without a Pr
}],
});
try {
- const base = projectRuntimeFixture(directory);
- const runtime = await createProjectLocalRuntime({
- dataRoot: directory,
- ...base,
- infrastructure: [...base.infrastructure.slice(0, -1), memoryCredentials],
- roles: {
- ...base.roles,
- credentialStores: [{ from: "memory-credentials", part: "store" }],
- },
+ const runtime = await createLocalRuntime({
+ ...projectRuntimeFixture(directory),
+ credentialStore,
endpoints: [endpoint],
});
assert.deepEqual((await runtime.credentials("generation.auth-test")).map((item) => ({
@@ -238,8 +210,7 @@ test("project local runtime queues, polls and cancels work with replaceable pack
});
try {
- const firstRuntime = await createProjectLocalRuntime({
- dataRoot: directory,
+ const firstRuntime = await createLocalRuntime({
...projectRuntimeFixture(directory),
components: [components],
endpoints: [endpointPackage],
@@ -330,8 +301,7 @@ test("one local Worker advances independent Builds concurrently under one comman
],
};
try {
- const runtime = await createProjectLocalRuntime({
- dataRoot: directory,
+ const runtime = await createLocalRuntime({
...projectRuntimeFixture(directory),
components: [components],
});
@@ -405,10 +375,8 @@ test("project local runtime accepts components loaded from an installed package"
try {
const loaded = await loadNodePackageSelection(["example-greeting-components"], installedRoot);
- const runtime = await createProjectLocalRuntime({
- dataRoot: runtimeRoot,
+ const runtime = await createLocalRuntime({
...projectRuntimeFixture(runtimeRoot),
- packageRoot: installedRoot,
components: collectNodePackageComponents(loaded.map((item) => item.contribution)),
});
const result = await runtime.build({
@@ -430,28 +398,11 @@ test("project local runtime accepts components loaded from an installed package"
test("project local runtime accepts an explicitly selected replacement ArtifactStore package", async () => {
const directory = await mkdtemp(join(tmpdir(), "narratage-local-artifacts-"));
- const module = { name: "example.remote-artifacts", version: "1" } as const;
const artifactStore = new MemoryArtifactStore();
- const artifacts = defineRuntimeInfrastructurePackage({
- module,
- instance: "remote-artifacts",
- parts: [{
- facet: "artifact-store",
- part: "store",
- role: "artifact-store",
- port: artifactStore,
- }],
- });
try {
- const selected = projectRuntimeFixture(directory);
- const runtime = await createProjectLocalRuntime({
- dataRoot: directory,
- ...selected,
- infrastructure: [...selected.infrastructure, artifacts],
- roles: {
- ...selected.roles,
- artifactStore: { from: "remote-artifacts", part: "store" },
- },
+ const runtime = await createLocalRuntime({
+ ...projectRuntimeFixture(directory),
+ artifactStore,
});
const bytes = new Uint8Array([7, 8, 9]);
const sourceArtifact = {
diff --git a/packages/runtime-local/test/programs.test.ts b/packages/runtime-local/test/programs.test.ts
index b3885bce..bd291ccf 100644
--- a/packages/runtime-local/test/programs.test.ts
+++ b/packages/runtime-local/test/programs.test.ts
@@ -36,21 +36,13 @@ async function project(program: (root: string) => ManagedProgram) {
use: "@narratage/runtime-local",
config: {
dataRoot: ".",
- infrastructure: {},
- roles: {
- scheduler: { from: "execution", part: "scheduler" },
- worker: { from: "execution", part: "worker" },
- buildStore: { from: "state", part: "builds" },
- operationStore: { from: "state", part: "operations" },
- dispatchStore: { from: "state", part: "dispatch" },
- artifactStore: { from: "artifacts", part: "store" },
- credentialStores: [{ from: "credentials", part: "store" }],
- },
+ artifacts: { use: "example.artifacts" },
+ credentials: {},
endpoints: {
one: { use: "example.program", pool: "example.local", config: {} },
two: { use: "example.program", pool: "example.local", config: {} },
},
- capacity: { maxActiveOperations: 1 },
+ concurrency: 1,
},
},
}));
diff --git a/packages/runtime/src/catalog.ts b/packages/runtime/src/catalog.ts
index 64cbdf6d..eeafbf2b 100644
--- a/packages/runtime/src/catalog.ts
+++ b/packages/runtime/src/catalog.ts
@@ -24,7 +24,7 @@ export type BuildCatalogEntry = BuildCatalogDescriptor & {
readonly createdAt: number;
};
-/** Host presentation index only. It is never Build truth or part of Runtime Closure. */
+/** Host presentation index only. It is never Build truth. */
export type BuildCatalog = {
record(build: string, descriptor: BuildCatalogDescriptor): Promise<BuildCatalogEntry>;
read(build: string): Promise<BuildCatalogEntry | undefined>;
diff --git a/packages/runtime/src/index.ts b/packages/runtime/src/index.ts
index 84660dab..fa31e79f 100644
--- a/packages/runtime/src/index.ts
+++ b/packages/runtime/src/index.ts
@@ -25,23 +25,6 @@ export {
sealOperationIdentity,
} from "./operations.js";
export type * from "./operations.js";
-export {
- RuntimeModuleRegistry,
- localSchedulerOptionsFromClosure,
- resolveRuntimeClosure,
- runtimeEndpoint,
- sealResolvedRuntimeProfile,
- verifyRuntimeClosure,
- verifyRuntimeCoverage,
- verifyResolvedRuntimeProfile,
-} from "./profile.js";
-export type * from "./profile.js";
-export {
- assembleRuntimeInfrastructure,
- defineRuntimeInfrastructurePackage,
- verifyRuntimeInfrastructurePackage,
-} from "./infrastructure.js";
-export type * from "./infrastructure.js";
export { LocalBuildScheduler } from "./scheduler.js";
export {
isEnumerableBuildStore,
diff --git a/packages/runtime/src/infrastructure.ts b/packages/runtime/src/infrastructure.ts
deleted file mode 100644
index f5f49549..00000000
--- a/packages/runtime/src/infrastructure.ts
+++ /dev/null
@@ -1,308 +0,0 @@
-import type { 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,
- RuntimeFacetInstance,
- RuntimePartRole,
-} from "./profile.js";
-import type {
- ArtifactStore,
- BuildSchedulerFactory,
- BuildStore,
- RuntimeWorkerFactory,
-} from "./types.js";
-
-type RuntimePartBase<Role extends RuntimePartRole, Implementation> = {
- readonly role: Role;
- /** Configured infrastructure instance that owns this part. */
- readonly owner: string;
- /** Stable part name exported by that configured instance. */
- readonly part: string;
- readonly instance: RuntimeFacetInstance;
- readonly port: Implementation;
-};
-
-export type RuntimeSchedulerPart = RuntimePartBase<"scheduler", BuildSchedulerFactory>;
-export type RuntimeWorkerPart = RuntimePartBase<"worker", RuntimeWorkerFactory>;
-export type RuntimeBuildStorePart = RuntimePartBase<"build-store", BuildStore>;
-export type RuntimeOperationStorePart = RuntimePartBase<"operation-store", OperationStore>;
-export type RuntimeDispatchStorePart = RuntimePartBase<"dispatch-store", BuildDispatchStore>;
-export type RuntimeArtifactStorePart = RuntimePartBase<"artifact-store", ArtifactStore>;
-export type RuntimeCredentialStorePart = RuntimePartBase<"credential-store", CredentialStore>;
-
-export type RuntimePart =
- | RuntimeSchedulerPart
- | RuntimeWorkerPart
- | RuntimeBuildStorePart
- | RuntimeOperationStorePart
- | RuntimeDispatchStorePart
- | RuntimeArtifactStorePart
- | RuntimeCredentialStorePart;
-
-/** One configured infrastructure instance may expose several exact Runtime parts. */
-export type RuntimeInfrastructurePackage = {
- /** Configured infrastructure instance created from the Runtime Profile. */
- readonly instance: string;
- readonly manifest: RuntimeModuleManifest;
- readonly parts: readonly RuntimePart[];
- /** Optional Host-facing index owned by the same durable Build store; never part of Runtime selection. */
- readonly buildCatalog?: BuildCatalog;
- close?(): void | Promise<void>;
-};
-
-type RuntimePartDefinitionBase<Role extends RuntimePartRole, Implementation> = {
- readonly role: Role;
- readonly part: string;
- readonly facet: string;
- readonly port: Implementation;
-};
-
-export type RuntimePartDefinition =
- | RuntimePartDefinitionBase<"scheduler", BuildSchedulerFactory>
- | RuntimePartDefinitionBase<"worker", RuntimeWorkerFactory>
- | RuntimePartDefinitionBase<"build-store", BuildStore>
- | RuntimePartDefinitionBase<"operation-store", OperationStore>
- | RuntimePartDefinitionBase<"dispatch-store", BuildDispatchStore>
- | RuntimePartDefinitionBase<"artifact-store", ArtifactStore>
- | RuntimePartDefinitionBase<"credential-store", CredentialStore>;
-
-export type DefineRuntimeInfrastructurePackageOptions = {
- readonly module: ModuleRef;
- readonly instance: string;
- readonly parts: readonly RuntimePartDefinition[];
- /** Host presentation index co-owned with this package's BuildStore, if any. */
- readonly buildCatalog?: BuildCatalog;
- readonly close?: () => void | Promise<void>;
-};
-
-export type RuntimePartReference = {
- readonly from: string;
- readonly part: string;
-};
-
-export type RuntimeRoleSelection = {
- readonly scheduler: RuntimePartReference;
- readonly worker: RuntimePartReference;
- readonly buildStore: RuntimePartReference;
- readonly operationStore: RuntimePartReference;
- readonly dispatchStore: RuntimePartReference;
- readonly artifactStore: RuntimePartReference;
- readonly credentialStores: readonly RuntimePartReference[];
-};
-
-export type RuntimeInfrastructureAssembly = {
- readonly manifests: readonly RuntimeModuleManifest[];
- readonly instances: readonly RuntimeFacetInstance[];
- 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 partFacetKey(part: RuntimePart): string {
- const ref = part.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 verifyPartPort(part: RuntimePart): void {
- assert(typeof part.port === "object" && part.port !== null,
- `${part.instance.id} Runtime infrastructure implementation is invalid`);
- switch (part.role) {
- case "scheduler":
- callable(part.port, "create", part.instance.id);
- break;
- case "worker":
- callable(part.port, "create", part.instance.id);
- break;
- case "build-store":
- callable(part.port, "create", part.instance.id);
- callable(part.port, "read", part.instance.id);
- callable(part.port, "append", part.instance.id);
- break;
- case "operation-store":
- callable(part.port, "create", part.instance.id);
- callable(part.port, "read", part.instance.id);
- callable(part.port, "list", part.instance.id);
- callable(part.port, "update", part.instance.id);
- break;
- case "dispatch-store":
- for (const method of [
- "create", "read", "list", "claim", "release", "finish", "requestCancellation", "wake",
- "acquireCapacity", "releaseCapacity", "releaseBuildCapacity", "listCapacity",
- ]) callable(part.port, method, part.instance.id);
- break;
- case "artifact-store":
- callable(part.port, "put", part.instance.id);
- callable(part.port, "get", part.instance.id);
- callable(part.port, "has", part.instance.id);
- break;
- case "credential-store":
- callable(part.port, "resolve", part.instance.id);
- break;
- }
-}
-
-export function defineRuntimeInfrastructurePackage(
- options: DefineRuntimeInfrastructurePackageOptions,
-): RuntimeInfrastructurePackage {
- assert(options.module.name.trim().length > 0 && options.module.version.trim().length > 0,
- "Runtime infrastructure module identity is invalid");
- assert(options.instance.trim().length > 0, "Runtime infrastructure instance is empty");
- assert(options.parts.length > 0, "Runtime infrastructure package is empty");
- const partNames = new Set<string>();
- const facets = new Set<string>();
- const parts = options.parts.map((definition): RuntimePart => {
- assert(definition.part.trim().length > 0, "Runtime infrastructure part is empty");
- assert(definition.facet.trim().length > 0, "Runtime infrastructure facet is empty");
- assert(!partNames.has(definition.part), `Runtime infrastructure part ${definition.part} is duplicated`);
- assert(!facets.has(definition.facet), `Runtime infrastructure facet ${definition.facet} is duplicated`);
- partNames.add(definition.part);
- facets.add(definition.facet);
- return {
- role: definition.role,
- owner: options.instance,
- part: definition.part,
- instance: {
- id: `${options.instance}.${definition.part}`,
- facet: { module: { ...options.module }, name: definition.facet },
- },
- port: definition.port,
- } as RuntimePart;
- });
- const manifest: RuntimeModuleManifest = {
- format: "narratage.runtime-module@1",
- name: options.module.name,
- version: options.module.version,
- facets: options.parts.map((definition) => ({
- name: definition.facet,
- role: definition.role,
- })),
- };
- const result: RuntimeInfrastructurePackage = {
- instance: options.instance,
- manifest,
- parts,
- ...(options.buildCatalog === undefined ? {} : { buildCatalog: options.buildCatalog }),
- ...(options.close === undefined ? {} : { close: options.close }),
- };
- verifyRuntimeInfrastructurePackage(result);
- return result;
-}
-
-export function verifyRuntimeInfrastructurePackage(value: RuntimeInfrastructurePackage): void {
- const packageName = `${value.manifest.name}@${value.manifest.version}`;
- assert(value.instance.trim().length > 0, `${packageName} infrastructure instance is empty`);
- assert(value.parts.length > 0, `${packageName} contains no Runtime infrastructure`);
- const modules = new RuntimeModuleRegistry();
- modules.register(value.manifest);
- const ids = new Set<string>();
- const parts = new Set<string>();
- const claimedFacets = new Set<string>();
- for (const part of value.parts) {
- assert(part.owner === value.instance,
- `${packageName} part ${part.instance.id} belongs to another infrastructure instance`);
- assert(part.part.trim().length > 0, `${packageName} Runtime infrastructure part is empty`);
- assert(!parts.has(part.part), `${packageName} repeats Runtime infrastructure part ${part.part}`);
- parts.add(part.part);
- assert(part.instance.id.trim().length > 0, `${packageName} Runtime infrastructure instance is empty`);
- assert(part.instance.id === `${part.owner}.${part.part}`,
- `${packageName} part ${part.part} has a non-canonical instance id`);
- assert(!ids.has(part.instance.id), `${packageName} repeats Runtime infrastructure ${part.instance.id}`);
- ids.add(part.instance.id);
- verifyPartPort(part);
- const resolved = modules.resolve(part.instance.facet);
- assert(resolved !== undefined, `${packageName} part ${part.instance.id} has no Manifest facet`);
- assert(resolved.facet.role === part.role,
- `${packageName} part ${part.instance.id} role differs from its Manifest facet`);
- claimedFacets.add(partFacetKey(part));
- }
- for (const facet of value.manifest.facets) {
- assert(facet.role !== "capability-endpoint", `${packageName} Runtime infrastructure 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 part`);
- }
-}
-
-type SelectedRuntimePart<Role extends RuntimePartRole> = {
- readonly package: RuntimeInfrastructurePackage;
- readonly part: Extract<RuntimePart, { readonly role: Role }>;
-};
-
-function selectedPart<Role extends RuntimePartRole>(
- parts: ReadonlyMap<string, { readonly package: RuntimeInfrastructurePackage; readonly part: RuntimePart }>,
- reference: RuntimePartReference | undefined,
- role: Role,
-): SelectedRuntimePart<Role> | undefined {
- if (reference === undefined) return undefined;
- const key = `${reference.from}\u0000${reference.part}`;
- const selected = parts.get(key);
- assert(selected !== undefined, `Runtime role refers to unknown part ${reference.from}.${reference.part}`);
- assert(selected.part.role === role,
- `Runtime part ${reference.from}.${reference.part} is ${selected.part.role}, not ${role}`);
- return selected as SelectedRuntimePart<Role>;
-}
-
-/** Resolve exact configured infrastructure parts without giving any package routing authority. */
-export function assembleRuntimeInfrastructure(
- packages: readonly RuntimeInfrastructurePackage[],
- selection: RuntimeRoleSelection,
-): RuntimeInfrastructureAssembly {
- const parts = new Map<string, { readonly package: RuntimeInfrastructurePackage; readonly part: RuntimePart }>();
- for (const item of packages) {
- verifyRuntimeInfrastructurePackage(item);
- for (const part of item.parts) {
- const key = `${part.owner}\u0000${part.part}`;
- assert(!parts.has(key), `Runtime part ${part.owner}.${part.part} is configured twice`);
- parts.set(key, { package: item, part });
- }
- }
- const scheduler = selectedPart(parts, selection.scheduler, "scheduler")!;
- const worker = selectedPart(parts, selection.worker, "worker")!;
- const build = selectedPart(parts, selection.buildStore, "build-store");
- const operations = selectedPart(parts, selection.operationStore, "operation-store");
- const dispatch = selectedPart(parts, selection.dispatchStore, "dispatch-store");
- const artifacts = selectedPart(parts, selection.artifactStore, "artifact-store");
- const credentialParts = selection.credentialStores
- .map((reference) => selectedPart(parts, reference, "credential-store")!);
- const selected = [scheduler, worker, build, operations, dispatch, artifacts, ...credentialParts]
- .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.part.instance),
- scheduler: scheduler.part.port,
- worker: worker.part.port,
- buildStore: build!.part.port,
- operationStore: operations!.part.port,
- dispatchStore: dispatch!.part.port,
- artifactStore: artifacts!.part.port,
- credentialStore: new CompositeCredentialStore(credentialParts.map((item) => item.part.port)),
- async close() {
- if (closed) return;
- closed = true;
- for (const item of [...packages].reverse()) await item.close?.();
- },
- };
-}
diff --git a/packages/runtime/src/profile.ts b/packages/runtime/src/profile.ts
deleted file mode 100644
index 4dfb3fd3..00000000
--- a/packages/runtime/src/profile.ts
+++ /dev/null
@@ -1,514 +0,0 @@
-import { plannedNeeds } from "@narratage/core";
-import type {
- BuildState,
- CapabilityRef,
- ModuleRef,
- TypeRef,
-} from "@narratage/protocol";
-
-export type RuntimeFacetRole =
- | "scheduler"
- | "worker"
- | "build-store"
- | "operation-store"
- | "dispatch-store"
- | "artifact-store"
- | "credential-store"
- | "capability-endpoint";
-
-export type RuntimePartRole = Exclude<RuntimeFacetRole, "capability-endpoint">;
-
-export type RuntimeFacetRef = {
- readonly module: ModuleRef;
- readonly name: string;
-};
-
-export type RuntimeCapability = {
- readonly capability: CapabilityRef;
- readonly returns: TypeRef;
-};
-
-export type RuntimePartFacet = {
- readonly name: string;
- readonly role: RuntimePartRole;
-};
-
-export type RuntimeEndpointFacet = {
- readonly name: string;
- readonly role: "capability-endpoint";
- readonly fulfills: readonly RuntimeCapability[];
- readonly lifecycle: "immediate" | "asynchronous";
- readonly defaultConcurrency: number;
- /** Provider-local lanes. When omitted, each capability inherits the Provider total. */
- readonly lanes?: readonly (RuntimeCapability & {
- readonly lane: string;
- readonly maxConcurrency: number;
- })[];
- /** Named secret inputs. Values are resolved by the selected CredentialStore only at invocation. */
- readonly credentialSlots?: readonly string[];
-};
-
-export type RuntimeFacet = RuntimePartFacet | RuntimeEndpointFacet;
-
-/** Static package metadata. Reading it must never execute the implementation it describes. */
-export type RuntimeModuleManifest = {
- readonly format: "narratage.runtime-module@1";
- readonly name: string;
- readonly version: string;
- readonly facets: readonly RuntimeFacet[];
-};
-
-export type RuntimeFacetInstance = {
- readonly id: string;
- readonly facet: RuntimeFacetRef;
- /** Required for capability Endpoints; absent for Scheduler and Store instances. */
- readonly pool?: string;
-};
-
-export type EndpointOffer = RuntimeCapability & {
- readonly endpoint: string;
-};
-
-export type ResolvedRuntimeProfile = {
- readonly format: "narratage.resolved-runtime@1";
- readonly instances: readonly RuntimeFacetInstance[];
- readonly scheduler: string;
- readonly worker: string;
- readonly stores: {
- readonly build: string;
- readonly operations: string;
- readonly dispatch: string;
- readonly artifacts: string;
- readonly credentials: readonly string[];
- };
- readonly endpoints: readonly EndpointOffer[];
- readonly scheduling: {
- readonly maxConcurrency: number;
- readonly resources: readonly { readonly id: string; readonly maxConcurrency: number }[];
- };
-};
-
-export type ResolvedRuntimePart = {
- readonly id: string;
- readonly role: RuntimePartRole;
- readonly facet: RuntimeFacetRef;
-};
-
-export type ResolvedRuntimeEndpoint = {
- readonly id: string;
- readonly role: "capability-endpoint";
- readonly facet: RuntimeFacetRef;
- readonly fulfills: readonly RuntimeCapability[];
- readonly lifecycle: "immediate" | "asynchronous";
- readonly credentialSlots: readonly string[];
- readonly pool: string;
- readonly maxConcurrency: number;
- readonly lanes: readonly (RuntimeCapability & {
- readonly lane: string;
- readonly maxConcurrency: number;
- })[];
-};
-
-export type ResolvedRuntimeInstance = ResolvedRuntimePart | ResolvedRuntimeEndpoint;
-
-export type RuntimeClosure = {
- readonly format: "narratage.runtime-closure@1";
- readonly instances: readonly ResolvedRuntimeInstance[];
- readonly scheduler: string;
- readonly worker: string;
- readonly stores: ResolvedRuntimeProfile["stores"];
- readonly endpoints: readonly EndpointOffer[];
- readonly scheduling: ResolvedRuntimeProfile["scheduling"];
-};
-
-type RegisteredRuntimeModule = {
- readonly manifest: RuntimeModuleManifest;
- readonly facets: ReadonlyMap<string, RuntimeFacet>;
-};
-
-const runtimeInstanceIndexes = new WeakMap<RuntimeClosure, ReadonlyMap<string, ResolvedRuntimeInstance>>();
-
-function runtimeInstances(closure: RuntimeClosure): ReadonlyMap<string, ResolvedRuntimeInstance> {
- const existing = runtimeInstanceIndexes.get(closure);
- if (existing !== undefined) return existing;
- const created = new Map(closure.instances.map((instance) => [instance.id, instance]));
- runtimeInstanceIndexes.set(closure, created);
- return created;
-}
-
-function assert(condition: unknown, message: string): asserts condition {
- if (!condition) throw new Error(message);
-}
-
-function positiveInteger(value: number, subject: string): number {
- assert(Number.isSafeInteger(value) && value > 0, `${subject} must be a positive safe integer`);
- return value;
-}
-
-function moduleKey(module: ModuleRef): string {
- return `${module.name}@${module.version}`;
-}
-
-function facetKey(ref: RuntimeFacetRef): string {
- return `${moduleKey(ref.module)}#${ref.name}`;
-}
-
-function capabilityKey(capability: CapabilityRef): string {
- return `${moduleKey(capability.module)}#${capability.name}`;
-}
-
-function typeKey(type: TypeRef): string {
- return `${moduleKey(type.module)}#${type.name}`;
-}
-
-function offerKey(offer: RuntimeCapability): string {
- return `${capabilityKey(offer.capability)} -> ${typeKey(offer.returns)}`;
-}
-
-function sameModule(left: ModuleRef, right: ModuleRef): boolean {
- return left.name === right.name && left.version === right.version;
-}
-
-function sortedUniqueStrings(values: readonly string[], subject: string): readonly string[] {
- const sorted = [...values].map((value) => {
- assert(value.trim().length > 0, `${subject} contains an empty value`);
- return value;
- }).sort();
- assert(new Set(sorted).size === sorted.length, `${subject} contains a duplicate value`);
- return sorted;
-}
-
-function normalizeCapability(value: RuntimeCapability): RuntimeCapability {
- assert(value.capability.module.name.length > 0 && value.capability.module.version.length > 0, "runtime capability module is invalid");
- assert(value.capability.name.length > 0, "runtime capability name is empty");
- assert(value.returns.module.name.length > 0 && value.returns.module.version.length > 0, "runtime return type module is invalid");
- assert(value.returns.name.length > 0, "runtime return type name is empty");
- return {
- capability: {
- module: { ...value.capability.module },
- name: value.capability.name,
- },
- returns: {
- module: { ...value.returns.module },
- name: value.returns.name,
- },
- };
-}
-
-function normalizeFacet(facet: RuntimeFacet): RuntimeFacet {
- assert(facet.name.trim().length > 0, "runtime facet name is empty");
- const common = {
- name: facet.name,
- };
- if (facet.role !== "capability-endpoint") return { ...common, role: facet.role };
- const fulfills = facet.fulfills.map(normalizeCapability)
- .sort((left, right) => offerKey(left).localeCompare(offerKey(right)));
- assert(fulfills.length > 0, `${facet.name} must fulfill at least one exact capability`);
- assert(new Set(fulfills.map(offerKey)).size === fulfills.length, `${facet.name} repeats a capability offer`);
- assert(facet.lifecycle === "immediate" || facet.lifecycle === "asynchronous", `${facet.name} lifecycle is invalid`);
- const defaultConcurrency = positiveInteger(facet.defaultConcurrency, `${facet.name} defaultConcurrency`);
- const lanes = (facet.lanes ?? fulfills.map((item) => ({
- ...item,
- lane: capabilityKey(item.capability),
- maxConcurrency: defaultConcurrency,
- }))).map((item) => ({
- ...normalizeCapability(item),
- lane: item.lane,
- maxConcurrency: positiveInteger(item.maxConcurrency, `${facet.name} lane ${item.lane}`),
- })).sort((left, right) => offerKey(left).localeCompare(offerKey(right)));
- assert(lanes.every((item) => item.lane.trim().length > 0), `${facet.name} has an empty lane`);
- assert(JSON.stringify(lanes.map(offerKey)) === JSON.stringify(fulfills.map(offerKey)),
- `${facet.name} lanes must cover every fulfilled capability exactly once`);
- const laneConcurrency = new Map<string, number>();
- for (const item of lanes) {
- const previous = laneConcurrency.get(item.lane);
- assert(previous === undefined || previous === item.maxConcurrency,
- `${facet.name} lane ${item.lane} has conflicting concurrency limits`);
- laneConcurrency.set(item.lane, item.maxConcurrency);
- }
- return {
- ...common,
- role: "capability-endpoint",
- fulfills,
- lifecycle: facet.lifecycle,
- defaultConcurrency,
- lanes,
- credentialSlots: sortedUniqueStrings(facet.credentialSlots ?? [], `${facet.name} credential slots`),
- };
-}
-
-function normalizeManifest(manifest: RuntimeModuleManifest): RuntimeModuleManifest {
- assert(manifest.format === "narratage.runtime-module@1", "unsupported Runtime Module Manifest format");
- assert(manifest.name.trim().length > 0 && manifest.version.trim().length > 0, "runtime module identity is invalid");
- const facets = manifest.facets.map(normalizeFacet).sort((left, right) => left.name.localeCompare(right.name));
- assert(new Set(facets.map((facet) => facet.name)).size === facets.length, `${manifest.name} repeats a Runtime facet`);
- return {
- format: "narratage.runtime-module@1",
- name: manifest.name,
- version: manifest.version,
- facets,
- };
-}
-
-export class RuntimeModuleRegistry {
- readonly #modules = new Map<string, RegisteredRuntimeModule>();
-
- register(manifest: RuntimeModuleManifest): void {
- const normalized = normalizeManifest(manifest);
- const key = moduleKey(normalized);
- assert(!this.#modules.has(key), `runtime module ${key} is already registered`);
- this.#modules.set(key, {
- manifest: normalized,
- facets: new Map(normalized.facets.map((facet) => [facet.name, facet])),
- });
- }
-
- resolve(ref: RuntimeFacetRef): { readonly module: RegisteredRuntimeModule; readonly facet: RuntimeFacet } | undefined {
- const registered = this.#modules.get(moduleKey(ref.module));
- const facet = registered?.facets.get(ref.name);
- return registered === undefined || facet === undefined ? undefined : { module: registered, facet };
- }
-
- verifyClosure(closure: RuntimeClosure): void {
- verifyRuntimeClosure(closure);
- for (const instance of closure.instances) {
- const resolved = this.resolve(instance.facet);
- assert(resolved !== undefined, `Runtime facet ${facetKey(instance.facet)} is not registered`);
- assert(instance.role === resolved.facet.role, `${instance.id} Runtime facet role differs`);
- if (instance.role === "capability-endpoint" && resolved.facet.role === "capability-endpoint") {
- assert(instance.lifecycle === resolved.facet.lifecycle, `${instance.id} Endpoint lifecycle differs`);
- assert(JSON.stringify(instance.credentialSlots)
- === JSON.stringify(resolved.facet.credentialSlots ?? []), `${instance.id} Endpoint credential slots differ`);
- assert(JSON.stringify(instance.fulfills.map(offerKey))
- === JSON.stringify(resolved.facet.fulfills.map(offerKey)), `${instance.id} Endpoint capabilities differ`);
- assert(instance.maxConcurrency === resolved.facet.defaultConcurrency,
- `${instance.id} Endpoint concurrency differs`);
- assert(JSON.stringify(instance.lanes) === JSON.stringify(resolved.facet.lanes),
- `${instance.id} Endpoint lanes differ`);
- }
- }
- }
-}
-
-function resolvedRuntimeContent(profile: ResolvedRuntimeProfile): ResolvedRuntimeProfile {
- return {
- format: "narratage.resolved-runtime@1",
- instances: [...profile.instances]
- .map((instance) => ({
- id: instance.id,
- facet: { module: { ...instance.facet.module }, name: instance.facet.name },
- ...(instance.pool === undefined ? {} : { pool: instance.pool }),
- }))
- .sort((left, right) => left.id.localeCompare(right.id)),
- scheduler: profile.scheduler,
- worker: profile.worker,
- stores: {
- build: profile.stores.build,
- operations: profile.stores.operations,
- dispatch: profile.stores.dispatch,
- artifacts: profile.stores.artifacts,
- credentials: [...profile.stores.credentials].sort(),
- },
- endpoints: [...profile.endpoints]
- .map((offer) => ({ ...normalizeCapability(offer), endpoint: offer.endpoint }))
- .sort((left, right) => offerKey(left).localeCompare(offerKey(right))),
- scheduling: {
- maxConcurrency: profile.scheduling.maxConcurrency,
- resources: [...profile.scheduling.resources]
- .map((resource) => ({ id: resource.id, maxConcurrency: resource.maxConcurrency }))
- .sort((left, right) => left.id.localeCompare(right.id)),
- },
- };
-}
-
-function verifyResolvedRuntimeShape(profile: ResolvedRuntimeProfile): void {
- assert(profile.format === "narratage.resolved-runtime@1", "unsupported Resolved Runtime format");
- assert(profile.scheduler.trim().length > 0, "Resolved Runtime scheduler is empty");
- assert(profile.worker.trim().length > 0, "Resolved Runtime worker is empty");
- for (const [name, id] of Object.entries({
- build: profile.stores.build,
- operations: profile.stores.operations,
- dispatch: profile.stores.dispatch,
- artifacts: profile.stores.artifacts,
- })) assert(id.trim().length > 0, `Resolved Runtime ${name} store is empty`);
- for (const id of profile.stores.credentials) assert(id.trim().length > 0, "Resolved Runtime CredentialStore id is empty");
- assert(new Set(profile.stores.credentials).size === profile.stores.credentials.length,
- "Resolved Runtime repeats a CredentialStore");
- positiveInteger(profile.scheduling.maxConcurrency, "Resolved Runtime maxConcurrency");
- const ids = profile.instances.map((instance) => {
- assert(instance.id.trim().length > 0, "Resolved Runtime instance id is empty");
- assert(instance.facet.name.trim().length > 0, `${instance.id} facet name is empty`);
- assert(instance.facet.module.name.length > 0 && instance.facet.module.version.length > 0, `${instance.id} facet module is invalid`);
- if (instance.pool !== undefined) assert(instance.pool.trim().length > 0, `${instance.id} pool is empty`);
- return instance.id;
- });
- assert(new Set(ids).size === ids.length, "Resolved Runtime repeats an instance id");
- const offers = profile.endpoints.map((offer) => {
- assert(offer.endpoint.trim().length > 0, "Runtime Endpoint offer endpoint is empty");
- return offerKey(normalizeCapability(offer));
- });
- assert(new Set(offers).size === offers.length, "Resolved Runtime repeats an Endpoint offer");
- const resourceNames = profile.scheduling.resources.map((resource) => {
- assert(resource.id.trim().length > 0, "Resolved Runtime resource id is empty");
- positiveInteger(resource.maxConcurrency, `Runtime resource ${resource.id}`);
- return resource.id;
- });
- assert(new Set(resourceNames).size === resourceNames.length, "Resolved Runtime repeats a resource override");
-}
-
-export function sealResolvedRuntimeProfile(
- value: Omit<ResolvedRuntimeProfile, "format">,
-): ResolvedRuntimeProfile {
- const draft: ResolvedRuntimeProfile = {
- format: "narratage.resolved-runtime@1",
- ...value,
- };
- verifyResolvedRuntimeShape(draft);
- return resolvedRuntimeContent(draft);
-}
-
-export function verifyResolvedRuntimeProfile(profile: ResolvedRuntimeProfile): void {
- verifyResolvedRuntimeShape(profile);
-}
-
-export function verifyRuntimeClosure(closure: RuntimeClosure): void {
- assert(closure.format === "narratage.runtime-closure@1", "unsupported Runtime Closure format");
- positiveInteger(closure.scheduling.maxConcurrency, "Runtime Closure maxConcurrency");
- const resourceNames = closure.scheduling.resources.map((resource) => {
- assert(resource.id.trim().length > 0, "Runtime Closure resource id is empty");
- positiveInteger(resource.maxConcurrency, `Runtime Closure resource ${resource.id}`);
- return resource.id;
- });
- assert(new Set(resourceNames).size === resourceNames.length, "Runtime Closure repeats a resource override");
- const instances = new Map<string, ResolvedRuntimeInstance>();
- const endpointOffers = new Map<string, ReadonlySet<string>>();
- for (const instance of closure.instances) {
- assert(!instances.has(instance.id), `Runtime Closure repeats instance ${instance.id}`);
- assert(instance.facet.module.name.trim().length > 0 && instance.facet.module.version.trim().length > 0,
- `${instance.id} Runtime module identity is invalid`);
- assert(instance.facet.name.trim().length > 0, `${instance.id} Runtime facet name is empty`);
- if (instance.role === "capability-endpoint") {
- assert(instance.pool.trim().length > 0, `${instance.id} Endpoint pool is empty`);
- positiveInteger(instance.maxConcurrency, `${instance.id} Endpoint maxConcurrency`);
- assert(instance.fulfills.length > 0, `${instance.id} Endpoint fulfills nothing`);
- const fulfills = new Set(instance.fulfills.map(offerKey));
- assert(fulfills.size === instance.fulfills.length,
- `${instance.id} Endpoint repeats a capability`);
- endpointOffers.set(instance.id, fulfills);
- assert(instance.lanes.length === instance.fulfills.length,
- `${instance.id} Endpoint lanes differ from capabilities`);
- const laneConcurrency = new Map<string, number>();
- for (const lane of instance.lanes) {
- assert(lane.lane.trim().length > 0, `${instance.id} Endpoint lane is empty`);
- positiveInteger(lane.maxConcurrency, `${instance.id} Endpoint lane ${lane.lane}`);
- assert(fulfills.has(offerKey(lane)),
- `${instance.id} Endpoint lane is outside its capabilities`);
- const previous = laneConcurrency.get(lane.lane);
- assert(previous === undefined || previous === lane.maxConcurrency,
- `${instance.id} Endpoint lane ${lane.lane} has conflicting concurrency limits`);
- laneConcurrency.set(lane.lane, lane.maxConcurrency);
- }
- sortedUniqueStrings(instance.credentialSlots, `${instance.id} Endpoint credential slots`);
- }
- instances.set(instance.id, instance);
- }
- const schedulers = closure.instances.filter((instance) => instance.role === "scheduler");
- assert(schedulers.length === 1 && schedulers[0]?.id === closure.scheduler, "Runtime Closure must select exactly one scheduler");
- const workers = closure.instances.filter((instance) => instance.role === "worker");
- assert(workers.length === 1 && workers[0]?.id === closure.worker, "Runtime Closure must select exactly one worker");
- const roles = {
- build: "build-store",
- operations: "operation-store",
- dispatch: "dispatch-store",
- artifacts: "artifact-store",
- } as const;
- for (const [name, role] of Object.entries(roles) as [keyof typeof roles, typeof roles[keyof typeof roles]][]) {
- const id = closure.stores[name];
- assert(instances.get(id)?.role === role, `Runtime Closure ${name} store has the wrong role`);
- }
- for (const id of closure.stores.credentials) {
- assert(instances.get(id)?.role === "credential-store", `Runtime Closure credential store ${id} has the wrong role`);
- }
- for (const offer of closure.endpoints) {
- const endpoint = instances.get(offer.endpoint);
- assert(endpoint?.role === "capability-endpoint", `${offer.endpoint} is not a capability Endpoint`);
- assert(endpointOffers.get(offer.endpoint)?.has(offerKey(offer)), `${offer.endpoint} does not fulfill ${offerKey(offer)}`);
- }
- assert(new Set(closure.endpoints.map(offerKey)).size === closure.endpoints.length,
- "Runtime Closure repeats an Endpoint offer");
- if (closure.instances.some((instance) => instance.role === "capability-endpoint" && instance.lifecycle === "asynchronous")) {
- assert(instances.get(closure.stores.operations)?.role === "operation-store", "asynchronous Endpoints require an OperationStore");
- }
- if (closure.instances.some((instance) => instance.role === "capability-endpoint" && instance.credentialSlots.length > 0)) {
- assert(closure.stores.credentials.length > 0, "credentialed Endpoints require a CredentialStore");
- }
-}
-
-export function resolveRuntimeClosure(
- registry: RuntimeModuleRegistry,
- profile: ResolvedRuntimeProfile,
-): RuntimeClosure {
- verifyResolvedRuntimeProfile(profile);
- const instances = profile.instances.map((instance): ResolvedRuntimeInstance => {
- const resolved = registry.resolve(instance.facet);
- assert(resolved !== undefined, `Runtime facet ${facetKey(instance.facet)} is not registered`);
- const common = {
- id: instance.id,
- facet: { module: { ...instance.facet.module }, name: instance.facet.name },
- };
- if (resolved.facet.role !== "capability-endpoint") return { ...common, role: resolved.facet.role };
- assert(instance.pool !== undefined, `${instance.id} Endpoint Provider Pool is required`);
- return {
- ...common,
- role: "capability-endpoint",
- fulfills: resolved.facet.fulfills.map((item) => structuredClone(item)),
- lifecycle: resolved.facet.lifecycle,
- credentialSlots: [...(resolved.facet.credentialSlots ?? [])],
- pool: instance.pool,
- maxConcurrency: resolved.facet.defaultConcurrency,
- lanes: structuredClone(resolved.facet.lanes ?? []),
- };
- });
- const closure: RuntimeClosure = {
- format: "narratage.runtime-closure@1",
- instances,
- scheduler: profile.scheduler,
- worker: profile.worker,
- stores: { ...profile.stores },
- endpoints: profile.endpoints.map((offer) => structuredClone(offer)),
- scheduling: structuredClone(profile.scheduling),
- };
- verifyRuntimeClosure(closure);
- return closure;
-}
-
-export function runtimeEndpoint(
- closure: RuntimeClosure,
- id: string,
-): ResolvedRuntimeEndpoint | undefined {
- const instance = runtimeInstances(closure).get(id);
- return instance?.role === "capability-endpoint" ? instance : undefined;
-}
-
-/** Fail before execution if the selected finite BuildPlan has an unbound external requirement. */
-export function verifyRuntimeCoverage(closure: RuntimeClosure, state: BuildState): void {
- const offers = new Set(closure.endpoints.map(offerKey));
- for (const requirement of plannedNeeds(state)) {
- assert(
- offers.has(offerKey(requirement)),
- `Runtime Closure does not bind demanded capability ${offerKey(requirement)}`,
- );
- }
-}
-
-export function localSchedulerOptionsFromClosure(closure: RuntimeClosure): {
- readonly maxConcurrency: number;
- readonly resourceLimits: Readonly<Record<string, number>>;
- readonly runtimeClosure: RuntimeClosure;
-} {
- return {
- maxConcurrency: closure.scheduling.maxConcurrency,
- resourceLimits: Object.fromEntries(closure.scheduling.resources.map((resource) => [resource.id, resource.maxConcurrency])),
- runtimeClosure: structuredClone(closure),
- };
-}
diff --git a/packages/runtime/src/types.ts b/packages/runtime/src/types.ts
index e7b843f2..8808b23f 100644
--- a/packages/runtime/src/types.ts
+++ b/packages/runtime/src/types.ts
@@ -55,17 +55,6 @@ export type RuntimeWorker = {
run(options: RuntimeWorkerRunOptions): Promise<void>;
};
-export type RuntimeWorkerFactoryOptions = {
- readonly scheduler: BuildSchedulerFactory;
- readonly stores: RuntimeExecutionStores;
- readonly scheduling: BuildSchedulerOptions;
-};
-
-/** Selected execution strategy. Process supervision remains a generic Host concern. */
-export type RuntimeWorkerFactory = {
- create(executor: RuntimeCommandExecutor, options: RuntimeWorkerFactoryOptions): RuntimeWorker;
-};
-
export type RuntimePreparation = {
readonly state: BuildState;
readonly runnable: readonly RuntimeRunnableCommand[];
@@ -185,12 +174,7 @@ export type BuildSchedulerOptions = {
readonly buildStore?: BuildStore;
};
-/** Environment-neutral scheduling authority selected by the Runtime Profile. */
+/** Internal scheduler used by an execution Runtime. */
export type BuildScheduler = {
run(requests: readonly ScheduledBuild[]): Promise<readonly ScheduledBuildResult[]>;
};
-
-/** Installed Scheduler implementation. It receives policy only after Runtime Closure resolution. */
-export type BuildSchedulerFactory = {
- create(executor: RuntimeCommandExecutor, options?: BuildSchedulerOptions): BuildScheduler;
-};
diff --git a/packages/runtime/test/infrastructure.test.ts b/packages/runtime/test/infrastructure.test.ts
deleted file mode 100644
index b2dc2964..00000000
--- a/packages/runtime/test/infrastructure.test.ts
+++ /dev/null
@@ -1,141 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-
-import {
- MemoryBuildStore,
- MemoryOperationStore,
- assembleRuntimeInfrastructure,
- defineRuntimeInfrastructurePackage,
- verifyRuntimeInfrastructurePackage,
-} from "@narratage/runtime";
-
-const moduleRef = { name: "example.infrastructures", version: "1" } as const;
-
-function servicePackage(close?: () => void) {
- return defineRuntimeInfrastructurePackage({
- module: moduleRef,
- instance: "example",
- parts: [
- {
- role: "scheduler",
- facet: "scheduler",
- part: "scheduler",
- port: {
- create() {
- return { async run() { return []; } };
- },
- },
- },
- {
- role: "worker",
- facet: "worker",
- part: "worker",
- port: { create() { return { async runOnce() { return undefined; }, async run() {} }; } },
- },
- {
- role: "build-store",
- facet: "build-store",
- part: "builds",
- port: new MemoryBuildStore(),
- },
- {
- role: "operation-store",
- facet: "operation-store",
- part: "operations",
- port: new MemoryOperationStore(),
- },
- {
- role: "dispatch-store",
- facet: "dispatch-store",
- part: "dispatch",
- port: Object.fromEntries([
- "create", "read", "list", "wake", "claim", "release", "finish", "requestCancellation",
- "acquireCapacity", "releaseCapacity", "releaseBuildCapacity", "listCapacity",
- ].map((name) => [name, async () => undefined])) as never,
- },
- {
- role: "artifact-store",
- facet: "artifact-store",
- part: "artifacts",
- port: {
- async put() { throw new Error("unused"); },
- async get() { return undefined; },
- async has() { return false; },
- },
- },
- {
- role: "credential-store",
- facet: "credential-store",
- part: "credentials",
- port: { async resolve() { return undefined; } },
- },
- ],
- ...(close === undefined ? {} : { close }),
- });
-}
-
-test("one physical Runtime package exposes separately selected Scheduler and Store parts", async () => {
- let closes = 0;
- const configured = servicePackage(() => { closes += 1; });
- const assembly = assembleRuntimeInfrastructure([configured], {
- scheduler: { from: "example", part: "scheduler" },
- worker: { from: "example", part: "worker" },
- buildStore: { from: "example", part: "builds" },
- operationStore: { from: "example", part: "operations" },
- dispatchStore: { from: "example", part: "dispatch" },
- artifactStore: { from: "example", part: "artifacts" },
- credentialStores: [{ from: "example", part: "credentials" }],
- });
- assert.equal(assembly.manifests.length, 1);
- assert.deepEqual(assembly.instances.map((item) => item.id), [
- "example.scheduler",
- "example.worker",
- "example.builds",
- "example.operations",
- "example.dispatch",
- "example.artifacts",
- "example.credentials",
- ]);
- assert.ok(assembly.buildStore);
- assert.ok(assembly.operationStore);
- assert.ok(assembly.artifactStore);
- assert.equal((await assembly.scheduler.create({
- prepare() { throw new Error("unused"); },
- async executeCommand() { throw new Error("unused"); },
- }).run([])).length, 0);
- await assembly.close();
- await assembly.close();
- assert.equal(closes, 1);
-});
-
-test("Runtime infrastructure role selection is exact", () => {
- const configured = servicePackage();
- assert.throws(
- () => assembleRuntimeInfrastructure([configured], {
- scheduler: { from: "example", part: "builds" },
- worker: { from: "example", part: "worker" },
- buildStore: { from: "example", part: "builds" },
- operationStore: { from: "example", part: "operations" },
- dispatchStore: { from: "example", part: "dispatch" },
- artifactStore: { from: "example", part: "artifacts" },
- credentialStores: [{ from: "example", part: "credentials" }],
- }),
- /not scheduler/u,
- );
-
- const inconsistent = {
- ...configured,
- manifest: structuredClone(configured.manifest),
- parts: [...configured.parts],
- };
- (inconsistent.manifest.facets[1] as { role: "artifact-store" }).role = "artifact-store";
- assert.throws(() => verifyRuntimeInfrastructurePackage(inconsistent), /role differs/u);
-
- const missingPort = {
- ...configured,
- parts: configured.parts.map((part) => part.role === "build-store"
- ? { ...part, port: {} as never }
- : part),
- };
- assert.throws(() => verifyRuntimeInfrastructurePackage(missingPort), /does not implement create/u);
-});
diff --git a/packages/runtime/test/profile.test.ts b/packages/runtime/test/profile.test.ts
deleted file mode 100644
index edcab17a..00000000
--- a/packages/runtime/test/profile.test.ts
+++ /dev/null
@@ -1,199 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-
-import {
- RuntimeModuleRegistry,
- localSchedulerOptionsFromClosure,
- resolveRuntimeClosure,
- sealResolvedRuntimeProfile,
- verifyRuntimeClosure,
- verifyRuntimeCoverage,
- verifyResolvedRuntimeProfile,
-} from "@narratage/runtime";
-import type { RuntimeModuleManifest } from "@narratage/runtime";
-
-import {
- capabilities,
- createGreetingBuild,
- types,
-} from "../../core/test/greeting-fixture.js";
-
-const runtimeModule = { name: "example.runtime-fixture", version: "1" } as const;
-const endpointFacet = { module: runtimeModule, name: "greeting-endpoint" } as const;
-
-function manifest(): RuntimeModuleManifest {
- return {
- format: "narratage.runtime-module@1",
- name: runtimeModule.name,
- version: runtimeModule.version,
- facets: [
- {
- name: "local-scheduler",
- role: "scheduler",
- },
- ...([
- ["local-worker", "worker"],
- ["memory-build-store", "build-store"],
- ["memory-operation-store", "operation-store"],
- ["memory-dispatch-store", "dispatch-store"],
- ["memory-artifact-store", "artifact-store"],
- ["memory-credential-store", "credential-store"],
- ] as const).map(([name, role]) => ({
- name,
- role,
- })),
- {
- name: endpointFacet.name,
- role: "capability-endpoint",
- fulfills: [{ capability: capabilities.generation, returns: types.generated }],
- lifecycle: "asynchronous",
- defaultConcurrency: 1,
- },
- ],
- };
-}
-
-function profile(options: { readonly operations?: boolean; readonly resource?: number } = {}) {
- return sealResolvedRuntimeProfile({
- instances: [
- { id: "scheduler.local", facet: { module: runtimeModule, name: "local-scheduler" } },
- { id: "worker.local", facet: { module: runtimeModule, name: "local-worker" } },
- { id: "build.memory", facet: { module: runtimeModule, name: "memory-build-store" } },
- ...(options.operations === false ? [] : [{
- id: "operations.memory",
- facet: { module: runtimeModule, name: "memory-operation-store" },
- }]),
- { id: "dispatch.memory", facet: { module: runtimeModule, name: "memory-dispatch-store" } },
- { id: "artifacts.memory", facet: { module: runtimeModule, name: "memory-artifact-store" } },
- { id: "credentials.memory", facet: { module: runtimeModule, name: "memory-credential-store" } },
- {
- id: "greeting.local",
- facet: endpointFacet,
- pool: "greeting.local",
- },
- ],
- scheduler: "scheduler.local",
- worker: "worker.local",
- stores: {
- build: "build.memory",
- operations: "operations.memory",
- dispatch: "dispatch.memory",
- artifacts: "artifacts.memory",
- credentials: ["credentials.memory"],
- },
- endpoints: [{
- capability: capabilities.generation,
- returns: types.generated,
- endpoint: "greeting.local",
- }],
- scheduling: {
- maxConcurrency: 8,
- resources: [{ id: "pool:greeting.local", maxConcurrency: options.resource ?? 2 }],
- },
- });
-}
-
-test("Resolved Runtime resolves selected facets into one execution environment", () => {
- const registry = new RuntimeModuleRegistry();
- registry.register(manifest());
- const first = resolveRuntimeClosure(registry, profile());
- const second = resolveRuntimeClosure(registry, profile());
- assert.deepEqual(first, second);
- assert.equal(first.instances.filter((instance) => instance.role === "scheduler").length, 1);
- const endpoint = first.instances.find((instance) => instance.id === "greeting.local");
- assert.equal(endpoint?.role, "capability-endpoint");
- if (endpoint?.role === "capability-endpoint") {
- assert.equal(endpoint.pool, "greeting.local");
- assert.equal(endpoint.maxConcurrency, 1);
- }
- assert.deepEqual(localSchedulerOptionsFromClosure(first).resourceLimits, {
- "pool:greeting.local": 2,
- });
- assert.doesNotThrow(() => verifyRuntimeCoverage(first, createGreetingBuild()));
-});
-
-test("Profile order does not change the resolved selection", () => {
- const registry = new RuntimeModuleRegistry();
- registry.register(manifest());
- const normal = profile();
- const reordered = sealResolvedRuntimeProfile({
- ...normal,
- instances: [...normal.instances].reverse(),
- endpoints: [...normal.endpoints].reverse(),
- scheduling: { ...normal.scheduling, resources: [...normal.scheduling.resources].reverse() },
- });
- assert.deepEqual(
- resolveRuntimeClosure(registry, normal),
- resolveRuntimeClosure(registry, reordered),
- );
-});
-
-test("asynchronous Endpoints require an OperationStore before any paid execution", () => {
- const registry = new RuntimeModuleRegistry();
- registry.register(manifest());
- assert.throws(
- () => resolveRuntimeClosure(registry, profile({ operations: false })),
- /operations store/u,
- );
-});
-
-test("credentialed Endpoints require a selected CredentialStore", () => {
- const registry = new RuntimeModuleRegistry();
- const configured = manifest();
- registry.register({
- ...configured,
- facets: configured.facets.map((facet) => facet.role === "capability-endpoint"
- ? { ...facet, credentialSlots: ["apiKey"] }
- : facet),
- });
- const withoutCredentials = profile();
- assert.throws(
- () => resolveRuntimeClosure(registry, sealResolvedRuntimeProfile({
- ...withoutCredentials,
- stores: { ...withoutCredentials.stores, credentials: [] },
- })),
- /credentialed Endpoints require a CredentialStore/u,
- );
-});
-
-test("Coverage rejects an unbound demanded Need before the Scheduler starts", () => {
- const registry = new RuntimeModuleRegistry();
- registry.register(manifest());
- const configured = profile();
- const unbound = sealResolvedRuntimeProfile({ ...configured, endpoints: [] });
- const closure = resolveRuntimeClosure(registry, unbound);
- assert.throws(
- () => verifyRuntimeCoverage(closure, createGreetingBuild()),
- /does not bind demanded capability/u,
- );
-});
-
-test("Runtime Closure content is structurally validated", () => {
- const registry = new RuntimeModuleRegistry();
- registry.register(manifest());
- const closure = resolveRuntimeClosure(registry, profile());
- const invalid = structuredClone(closure);
- (invalid.scheduling as { maxConcurrency: number }).maxConcurrency = 0;
- assert.throws(() => verifyRuntimeClosure(invalid), /positive safe integer/u);
-});
-
-test("unsupported Runtime formats are rejected instead of being reinterpreted", () => {
- const registry = new RuntimeModuleRegistry();
- assert.throws(
- () => registry.register({ ...manifest(), format: "narratage.runtime-module@invalid" } as never),
- /unsupported Runtime Module Manifest format/u,
- );
-
- const configured = profile();
- assert.throws(
- () => verifyResolvedRuntimeProfile({ ...configured, format: "narratage.resolved-runtime@invalid" } as never),
- /unsupported Resolved Runtime format/u,
- );
-
- registry.register(manifest());
- const closure = resolveRuntimeClosure(registry, configured);
- assert.throws(
- () => verifyRuntimeClosure({ ...closure, format: "narratage.runtime-closure@invalid" } as never),
- /unsupported Runtime Closure format/u,
- );
-});
diff --git a/packages/store-sqlite/README.md b/packages/store-sqlite/README.md
index 7d702be3..a9ebd762 100644
--- a/packages/store-sqlite/README.md
+++ b/packages/store-sqlite/README.md
@@ -1,22 +1,11 @@
# `@narratage/store-sqlite`
-Durable local adapters for the environment-neutral Build, Operation and Dispatch ports.
+Private durable state used by `@narratage/runtime-local`.
-One SQLite file may physically contain the execution tables and an optional Host index, but their
-interfaces remain separate:
+One SQLite file stores Build facts, external Operations, the Build queue, active capacity reservations
+and a small output catalog. No ready-command queue is stored: Core derives ready work from the saved
+Build facts whenever the Worker advances it.
-- BuildStore persists one Definition and appends admitted Core Facts in order;
-- OperationStore persists external attempt identities, checkpoints and completions;
-- BuildDispatchStore persists the local Build queue and remote in-flight capacity reservations;
-- BuildCatalog indexes source/run paths and output aliases for Host presentation only;
-- no ready-command queue is stored. Core regenerates readiness from Definition plus Facts after every restart.
-
-Artifacts and credentials never enter this database. The adapter owns its private pre-release
-schema `9`; Core and Endpoint packages do not import SQLite. Incompatible development databases are
-rejected and recreated explicitly instead of carrying migration code before the first release.
-
-`createSqliteRuntimeInfrastructurePackage()` returns one configured instance with three separately selectable
-parts plus a Host-only `catalog` handle. They share one connection and one close
-lifecycle. The catalog is deliberately absent from the Runtime infrastructure Manifest and Runtime
-Closure; changing the Host-only catalog table therefore cannot change the identity under which an
-active Build continues.
+Artifacts and credentials never enter this database. Components and Endpoint packages do not import
+SQLite. `SqliteRuntimeState` exposes the narrow stores needed by the local Runtime and owns their shared
+connection.
diff --git a/packages/store-sqlite/package.json b/packages/store-sqlite/package.json
index 241cc4ab..7b6cc77d 100644
--- a/packages/store-sqlite/package.json
+++ b/packages/store-sqlite/package.json
@@ -10,13 +10,9 @@
"exports": {
".": "./src/index.ts"
},
- "narratage": {
- "activation": "./src/activation.ts"
- },
"dependencies": {
"@narratage/core": "workspace:*",
"@narratage/protocol": "workspace:*",
- "@narratage/runtime": "workspace:*",
- "@narratage/runtime-kit": "workspace:*"
+ "@narratage/runtime": "workspace:*"
}
}
diff --git a/packages/store-sqlite/src/activation.ts b/packages/store-sqlite/src/activation.ts
deleted file mode 100644
index 1267ce35..00000000
--- a/packages/store-sqlite/src/activation.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import {
- createRuntimeInfrastructureAdapterFacet,
- runtimeConfigExact,
- runtimeConfigObject,
- runtimeConfigPositiveInteger,
- runtimeConfigString,
-} from "@narratage/runtime-kit";
-import { resolve } from "node:path";
-
-const sqliteStateAdapter = createRuntimeInfrastructureAdapterFacet({
- use: "@narratage/store-sqlite",
- validate(context) {
- const config = runtimeConfigObject(context.config, "SQLite Runtime state");
- runtimeConfigExact(config, ["path", "busyTimeoutMs"], "SQLite Runtime state");
- if (runtimeConfigString(config.path, "SQLite path") === undefined) throw new Error("SQLite path is required");
- runtimeConfigPositiveInteger(config.busyTimeoutMs, "SQLite busyTimeoutMs");
- },
- async create(context) {
- 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 { createSqliteRuntimeInfrastructurePackage } = await import("./store.js");
- return createSqliteRuntimeInfrastructurePackage({
- path: resolve(context.dataRoot, path),
- instance: context.instance,
- ...(runtimeConfigPositiveInteger(config.busyTimeoutMs, "SQLite busyTimeoutMs") === undefined
- ? {} : { busyTimeoutMs: config.busyTimeoutMs as number }),
- ...(context.access === "read-only" ? { readOnly: true } : {}),
- });
- },
-});
-
-export const narratagePackage = {
- format: "narratage.node-package@1" as const,
- hostFacets: [sqliteStateAdapter],
-};
-
-export default narratagePackage;
diff --git a/packages/store-sqlite/src/index.ts b/packages/store-sqlite/src/index.ts
index aca6dc42..b8bf49a2 100644
--- a/packages/store-sqlite/src/index.ts
+++ b/packages/store-sqlite/src/index.ts
@@ -1,2 +1,2 @@
-export { SqliteRuntimeState, createSqliteRuntimeInfrastructurePackage, sqliteStoreModuleRef } from "./store.js";
+export { SqliteRuntimeState } from "./store.js";
export type * from "./store.js";
diff --git a/packages/store-sqlite/src/store.ts b/packages/store-sqlite/src/store.ts
index db1b98ee..ef557b47 100644
--- a/packages/store-sqlite/src/store.ts
+++ b/packages/store-sqlite/src/store.ts
@@ -14,7 +14,6 @@ import type {
import {
verifyBuildCatalogDescriptor,
verifyBuildCatalogEntry,
- defineRuntimeInfrastructurePackage,
capacityReservationId,
} from "@narratage/runtime";
import type {
@@ -36,27 +35,16 @@ import type {
OperationSnapshot,
OperationStore,
OperationUpdate,
- RuntimeInfrastructurePackage,
} from "@narratage/runtime";
const databaseSchemaVersion = 11;
-export const sqliteStoreModuleRef = {
- name: "@narratage/store-sqlite",
- version: "1",
-} as const;
-
export type SqliteRuntimeStateOptions = {
readonly busyTimeoutMs?: number;
/** Open an existing archive without creating files or schema. */
readonly readOnly?: boolean;
};
-export type CreateSqliteRuntimeInfrastructurePackageOptions = SqliteRuntimeStateOptions & {
- readonly path: string;
- readonly instance?: string;
-};
-
type Row = Record<string, unknown>;
function assert(condition: unknown, message: string): asserts condition {
@@ -725,44 +713,3 @@ export class SqliteRuntimeState {
this.#database.close();
}
}
-
-export function createSqliteRuntimeInfrastructurePackage(
- options: CreateSqliteRuntimeInfrastructurePackageOptions,
-): RuntimeInfrastructurePackage {
- const state = new SqliteRuntimeState(options.path, {
- ...(options.busyTimeoutMs === undefined ? {} : { busyTimeoutMs: options.busyTimeoutMs }),
- ...(options.readOnly === undefined ? {} : { readOnly: options.readOnly }),
- });
- const instance = options.instance ?? "state";
- try {
- return defineRuntimeInfrastructurePackage({
- module: sqliteStoreModuleRef,
- instance,
- parts: [
- {
- role: "build-store",
- part: "builds",
- facet: "build-store",
- port: state.builds,
- },
- {
- role: "operation-store",
- part: "operations",
- facet: "operation-store",
- port: state.operations,
- },
- {
- role: "dispatch-store",
- part: "dispatch",
- facet: "dispatch-store",
- port: state.dispatch,
- },
- ],
- buildCatalog: state.catalog,
- close: () => state.close(),
- });
- } catch (error) {
- state.close();
- throw error;
- }
-}
diff --git a/packages/store-sqlite/test/store.test.ts b/packages/store-sqlite/test/store.test.ts
index 0374c3a1..d0f2ea52 100644
--- a/packages/store-sqlite/test/store.test.ts
+++ b/packages/store-sqlite/test/store.test.ts
@@ -9,16 +9,13 @@ import {
nonTerminalDispatchPhases,
sealOperationIdentity,
} from "@narratage/runtime";
-import {
- createSqliteRuntimeInfrastructurePackage,
- SqliteRuntimeState,
-} from "@narratage/store-sqlite";
+import { SqliteRuntimeState } from "@narratage/store-sqlite";
import { createGreetingBuild } from "../../core/test/greeting-fixture.js";
test("read-only SQLite observation of an absent archive creates no file", async () => {
const directory = await mkdtemp(join(tmpdir(), "narratage-sqlite-read-only-"));
- const path = join(directory, ".svml", "runtime.sqlite");
+ const path = join(directory, ".narratage", "runtime.sqlite");
try {
const state = new SqliteRuntimeState(path, { readOnly: true });
assert.equal(await state.builds.read("missing"), undefined);
diff --git a/packages/video-cli/README.md b/packages/video-cli/README.md
index f07a86d3..76c702b5 100644
--- a/packages/video-cli/README.md
+++ b/packages/video-cli/README.md
@@ -69,7 +69,7 @@ writing a temporary file, then atomically replaces the requested destination. A
loaded into CLI memory and a corrupt stream cannot overwrite an existing export.
`builds` and source aliases come from an optional Host `BuildCatalog`. The Catalog contains paths
-and presentation names only. It is not Core truth or a Runtime Closure facet; `inspect` and `get`
+and presentation names only. It is not Core truth; `inspect` and `get`
always resolve the alias back through the verified BuildState before accepting it.
`history` searches those frozen Catalog names across Builds, but reports only Logical Outputs whose
selected Record is present in the reconstructed Build view. It neither infers renames nor lists unbuilt
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 9ec3bdc5..ac44c0e5 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2215,6 +2215,9 @@ importers:
'@narratage/runtime-kit':
specifier: workspace:*
version: link:../runtime-kit
+ '@narratage/store-sqlite':
+ specifier: workspace:*
+ version: link:../store-sqlite
'@narratage/validation':
specifier: workspace:*
version: link:../validation
@@ -2231,9 +2234,6 @@ importers:
'@narratage/credential-store-env':
specifier: workspace:*
version: link:../credential-store-env
- '@narratage/store-sqlite':
- specifier: workspace:*
- version: link:../store-sqlite
packages/screen-overlay:
dependencies:
@@ -2567,9 +2567,6 @@ importers:
'@narratage/runtime':
specifier: workspace:*
version: link:../runtime
- '@narratage/runtime-kit':
- specifier: workspace:*
- version: link:../runtime-kit
packages/svs:
dependencies: