A local-first multi-agent app development platform, built on PenguinHarness
refactor: extract drafted mechanisms (#546)
Myriad-Dreaminb2b5ca49e059
diff --git a/changelog/unreleased/2026-08-29-module-tree.md b/changelog/unreleased/2026-08-29-module-tree.mdindex 9ab7a033..6f30ec0c 100644--- a/changelog/unreleased/2026-08-29-module-tree.md+++ b/changelog/unreleased/2026-08-29-module-tree.md@@ -14,7 +14,7 @@ The business surface of the server — every service, every repo, every route grA component's interface is its class, projected; anything else is an abstract class `extends Interface<…>()`, wherever it is declared. `pnpm gen:ifaces` projects every such interface into `packages/server/src/ifaces.json` — parameters and return types included, not just method names; named data types are emitted once and referenced, so a recursive type is a reference to itself. The table is generated, not committed: `typecheck`, `build`, `test` and the deploy script regenerate it. A requirement is satisfied by Go's rule: every method the consumer names exists on the provider with an assignable signature (parameters contravariant, returns covariant). A module may declare the narrow interface it needs where it consumes it; the scheduler's `ScheduleTaskRunner` is one, satisfied by the session runtime's wider `SessionManager`.-Host objects (`AbortSignal`, `Request`, a class of this package written as `Opaque<"Name">`) compare by name only, and the generator says so rather than guessing.+Host objects (`AbortSignal`, `Request`, a class of this package written as `Opaque<"Name">`) compare by name only — and the name is always qualified by the package that declares the type (`@types/node#Request`, `@prismshadow/penguin-core#Resources`), so the same word in two packages is two identities. Mapped types (`Pick<…>`, `Record<…>`) are projected as the shapes they are, an alias with methods as an interface under the alias's name.## Contributions are manifest data@@ -24,6 +24,24 @@ A route group is a line in a manifest — `"HttpModule.routes": [{ id: "agents.mA plugin package is a set of modules, written the way the platform's own are: `@Component` / `@Module` classes with `@Use` / `@Provide` / `@Bind` fields. Its manifests are generated — the package's build runs `gen-ifaces` and ships `ifaces.json` beside its `package.json` — the table is the package's module payload, a plugin is a plugin by being listed; the default export is `{ modules: [<class>, …] }`, each class checked against that table at load, and the modules boot as children of the platform's tree at every App creation. The `activate(ctx)` contract — `initialize` / `create` events, `PenguinInterface`, `PenguinContext` — is gone; what it registered (a sandbox backend, a workflow factory) is now a contribution or a provided interface, and what it reached (`terminals`, `sandbox`) is a requirement checked at signature level. The four sandbox backends are converted. A hand-written manifest (a workflow package's) may leave out an empty `requires`, `provides`, `contributes` or `children`.+## Mechanisms, not implementations: the runtime split and the end of `Overrides`++The single `RuntimeModule` that exported ten unrelated things is gone: each claimed capability is a node of its own (`RuntimeConfig`, `RuntimeDb`, `RuntimeChannels`, `RuntimeProxy`, `RuntimeHmr`, `RuntimeDesktop`, `RuntimeAuthState`, `RuntimeResourceGroups`), and what most nodes actually wanted from the config is its own mechanism, `Paths` (`root`). Time is a mechanism (`Clock`, `SystemClock`), so is the log (`Log`, `ConsoleLog`), password hashing (`PasswordHasher`, `ScryptHasher`), the messaging pacing knobs (`MessagingTuning`), each connector's network transport (`FeishuSdkHandle`, `TelegramTransportHandle`, `QQTransportHandle`, `QQScanTransportHandle`), the session loader and title generator (`SessionLoaders`, `TitleGenerators`) and the update check's network (`HttpFetch`). A component says what it implements — `class SystemClock implements Clock` — and the generator records it; a provider that declares the interface wins the wiring over one that merely has the shape.++`BuildDepsOverrides` — the bag of test doubles that thirteen production nodes read at boot — is deleted. A test stands in for a node instead: `bootAppDeps(config, [[SystemClock, { now }]])`, a list of **replacements** the platform boots in place of the classes they name, checked against the same table as the classes themselves. `createTestApp` keeps its option names and turns them into replacements.++### Every dependency is a mechanism++`packages/server/src/mechanisms/*.ts` declares the mechanisms the tree is made of — `identity` (`Users`, `AuthSessions`, `Auth`, `Admin`), `projects` (`Projects`, `Members`, `AgentIndex`, `Access`, `ProjectLifecycle`, `ProjectConfigStore`, `ModelOAuth`), `sessions` (`SessionIndex`, `Goals`, `SessionOrigins`, `Schedules`, `Scheduling`), `observability` (`ErrorLog`, `Errors`, `UsageStore`, `UsageRecording`, `UsageQueries`), `traces`, `workspace`, `agents`, `settings`, `messaging` — as interface classes with full signatures, apart from what implements them. Each implementation says so (`class UsersRepo implements Users`); every `@Use` field, every route's dependency type and every service's dependency type names the mechanism. `AuthService` requires `Users`, `AuthSessions`, `AuthState`, `Clock`, `PasswordHasher` and its own `InitialProjectProvisioner` — nothing about SQLite, nothing about the runtime. `gen-ifaces` refuses a `@Use` field typed by a component class, so the rule holds without review; the count went from 102 of 189 to 0 of 192.++### Groups that export++The root has fourteen children, not seventy-four: `RuntimeModule`, `SettingsModule`, `IdentityModule`, `ProjectsModule`, `SessionRuntimeModule`, `ObservabilityModule`, `TracesModule`, `AgentsModule`, `WorkspaceModule`, `MessagingHubModule`, `ApiModule`, plus the sandbox, terminal and machines modules and `Startup`. A group is `@Module({ children, exports })`: its `exports` are the interfaces its children offer the rest of the tree, forwarded from the child that declares each; everything else in the group — the repos, the seams a test replaces, the route components — is visible only inside it (the kernel's visibility is lexical: siblings and the ancestors' siblings, never an ancestor). A whole group is replaceable, and so is any node in one. Ordering follows the exported child, not the group, so two groups may need each other's children without a cycle. The generator resolves every requirement to the module that will provide it and records it as `from` — the table now says which *module* a node depends on, and the page shows who depends on whom.++## An extension replaces any node++`package.json#penguin.replaces` lists manifests under the names of the nodes they stand in for — a component, a module, a whole group with `children` and `exports` of its own — and the default export's `replaces` carries their code. Nothing about a stand-in is checked when it is put in place: the platform builds the tree with the stand-in where the class would have been, and the tree is checked as one before any node runs — every requirement resolved at signature level, every exported alias resolved to a child, every provision present on the instance. A stand-in that offers less than its consumers need is refused by name (`ServerSettingsRepo: api 'Settings' does not satisfy 'Settings': missing [getAttachmentLimitsMb]`, `SettingsModule: exports 'Settings' but no child provides it`), and the App does not boot; two extensions replacing the same node is a load-time conflict. Production code and the test helpers read the tree through the groups' exports, never an implementation node by name, so a replaced node is what everyone gets.+## The table as a page`pnpm ifaces:page` renders `ifaces.json` into one self-contained HTML page (`dist-ifaces/index.html`): the module tree, every node's requires / provides / contributes, every interface at signature level, with the table's sha256 in the title and the JSON beside it.diff --git a/changelog/unreleased/2026-08-29-module-tree.zh.md b/changelog/unreleased/2026-08-29-module-tree.zh.mdindex c3d6d5f1..6bf8eea6 100644--- a/changelog/unreleased/2026-08-29-module-tree.zh.md+++ b/changelog/unreleased/2026-08-29-module-tree.zh.md@@ -14,7 +14,7 @@组件的接口就是它的 class 的投影;其余接口是 `extends Interface<…>()` 的抽象类,声明在哪里都可以。`pnpm gen:ifaces` 把每个这样的 interface 投影进 `packages/server/src/ifaces.json`——包含参数和返回类型,而不只是方法名;具名数据类型只输出一次、按引用使用,因此递归类型就是对自身的引用。这张表是生成物,不进版本库:`typecheck`、`build`、`test` 和部署脚本都会重新生成它。一个 requires 按 Go 的规则判定满足:消费者列出的每个方法都存在于提供者上且签名可赋值(参数逆变,返回协变)。模块可以在消费处声明自己需要的窄接口;scheduler 的 `ScheduleTaskRunner` 就是一例,由 session 运行时更宽的 `SessionManager` 满足。-宿主对象(`AbortSignal`、`Request`,以及本包里写成 `Opaque<"Name">` 的 class)只按名字比较,生成器会明说而不是猜。+宿主对象(`AbortSignal`、`Request`,以及本包里写成 `Opaque<"Name">` 的 class)只按名字比较,生成器会明说而不是猜——而且名字总是带着声明它的包(`@types/node#Request`、`@prismshadow/penguin-core#Resources`),同一个词在两个包里是两个身份。映射类型(`Pick<…>`、`Record<…>`)按它们本来的形状投影,带方法的别名以别名为名成为接口。## contribution 是 manifest 数据@@ -24,6 +24,24 @@一个插件包就是一组模块,写法与 platform 自己的模块相同:`@Component` / `@Module` 类,字段上是 `@Use` / `@Provide` / `@Bind`。它的 manifest 是生成的——包的 build 跑 `gen-ifaces`,把 `ifaces.json` 随 `package.json` 一起发布——这张表就是包的模块载荷,包是不是插件由它被列出决定;默认导出是 `{ modules: [<class>, …] }`,加载时每个类对照该表核对,这些模块在每次 App 创建时作为 platform 树的子节点启动。`activate(ctx)` 契约——`initialize` / `create` 事件、`PenguinInterface`、`PenguinContext`——不再存在;它过去注册的东西(沙箱后端、workflow factory)现在是 contribution 或 provides,它过去触达的东西(`terminals`、`sandbox`)现在是按签名校验的 requires。四个沙箱后端已转换。手写的 manifest(workflow 包的)里为空的 `requires`、`provides`、`contributes`、`children` 可以省略。+## 机制而非实现:运行时拆分,`Overrides` 消失++那个一口气导出十样东西的 `RuntimeModule` 没有了:每个认领的能力是一个自己的节点(`RuntimeConfig`、`RuntimeDb`、`RuntimeChannels`、`RuntimeProxy`、`RuntimeHmr`、`RuntimeDesktop`、`RuntimeAuthState`、`RuntimeResourceGroups`),大多数节点真正想从 config 拿的东西成了独立机制 `Paths`(`root`)。时间是机制(`Clock` / `SystemClock`),日志是(`Log` / `ConsoleLog`),密码哈希是(`PasswordHasher` / `ScryptHasher`),消息节奏参数是(`MessagingTuning`),每个 connector 的网络传输是(`FeishuSdkHandle`、`TelegramTransportHandle`、`QQTransportHandle`、`QQScanTransportHandle`),session loader 与标题生成器是(`SessionLoaders`、`TitleGenerators`),更新检查的网络也是(`HttpFetch`)。组件声明自己实现什么——`class SystemClock implements Clock`——生成器记录下来;声明了该接口的提供者在接线时胜过只是形状相符的。++`BuildDepsOverrides`——十三个生产节点在启动时读的那袋测试替身——被删除。测试改为顶替一个节点:`bootAppDeps(config, [[SystemClock, { now }]])`,一份**替换**列表,平台用它们代替所命名的 class 启动,并按同一张表校验。`createTestApp` 保留原有选项名,把它们变成替换。++### 每个依赖都是机制++`packages/server/src/mechanisms/*.ts` 声明这棵树由哪些机制组成——`identity`(`Users`、`AuthSessions`、`Auth`、`Admin`)、`projects`(`Projects`、`Members`、`AgentIndex`、`Access`、`ProjectLifecycle`、`ProjectConfigStore`、`ModelOAuth`)、`sessions`(`SessionIndex`、`Goals`、`SessionOrigins`、`Schedules`、`Scheduling`)、`observability`(`ErrorLog`、`Errors`、`UsageStore`、`UsageRecording`、`UsageQueries`)、`traces`、`workspace`、`agents`、`settings`、`messaging`——都是带完整签名的接口类,与实现分开声明。每个实现自己表明(`class UsersRepo implements Users`);每个 `@Use` 字段、每组路由的依赖类型、每个服务的依赖类型都写机制名。`AuthService` 需要 `Users`、`AuthSessions`、`AuthState`、`Clock`、`PasswordHasher` 和它自己声明的 `InitialProjectProvisioner`——没有 sqlite,没有运行时。`gen-ifaces` 拒绝类型为组件 class 的 `@Use` 字段,规则不靠 review 维持;计数从 102/189 归零(0/192)。++### 会导出的组++根下面是十四个 child 而不是七十四个:`RuntimeModule`、`SettingsModule`、`IdentityModule`、`ProjectsModule`、`SessionRuntimeModule`、`ObservabilityModule`、`TracesModule`、`AgentsModule`、`WorkspaceModule`、`MessagingHubModule`、`ApiModule`,加上沙箱、终端、machines 三个模块和 `Startup`。组是 `@Module({ children, exports })`:`exports` 是它的 children 向树的其余部分提供的接口,由声明该接口的那个 child 转出;组里其余的一切——repo、测试要顶替的接缝、路由组件——只在组内可见(kernel 的可见性是词法的:兄弟与祖先的兄弟,从不包括祖先)。整个组可以替换,组里的任何节点也可以。启动顺序跟随被导出的 child 而不是组,所以两个组可以互相需要对方的 child 而不成环。生成器把每个 requires 解析到将要提供它的模块并记为 `from`——表现在写明一个节点依赖哪个*模块*,页面也就显示出谁依赖谁。++## 扩展可以替换任意节点++`package.json#penguin.replaces` 以被顶替节点的名字列出 manifest——组件、模块、乃至带自己 `children` 与 `exports` 的整个组——默认导出的 `replaces` 提供代码。放入时对替身不做任何检查:平台把替身放在原 class 的位置上组装整棵树,然后在任何节点运行之前把树当作一个整体校验——每个 requires 按签名解析、每个导出别名解析到某个 child、每个 provides 在实例上确实存在。替身提供的少于消费者所需,就按名字拒绝(`ServerSettingsRepo: api 'Settings' does not satisfy 'Settings': missing [getAttachmentLimitsMb]`、`SettingsModule: exports 'Settings' but no child provides it`),App 不启动;两个扩展替换同一节点在加载期就冲突。生产代码与测试 helper 都经由组的导出读树,从不按实现节点的名字,所以被替换的节点就是所有人拿到的那个。+## 表就是一个页面`pnpm ifaces:page` 把 `ifaces.json` 渲染成一个自包含的 HTML 页面(`dist-ifaces/index.html`):模块树、每个节点的 requires / provides / contributes、每个接口的签名,标题里是表的 sha256,旁边就是那份 JSON。diff --git a/packages/core/src/kernel/check.ts b/packages/core/src/kernel/check.tsindex 89f40002..65d1acd3 100644--- a/packages/core/src/kernel/check.ts+++ b/packages/core/src/kernel/check.ts@@ -49,7 +49,7 @@ interface Located {manifest: Manifest;/** Module names this module may wire to or contribute to. */visible: Set<string>;- /** The subset of `visible` that is an ancestor — contributable, not requirable. */+ /** Module names above this one — never a provider for it (their exports face outward). */ancestors: Set<string>;}@@ -70,19 +70,14 @@ function provided(function locate(root: ManifestNode): Located[] {const out: Located[] = [];- const walk = (node: ManifestNode, path: string, inherited: string[], ancestors: string[]) => {- const names = node.children.map((c) => c.manifest.name);- const above = [...ancestors, node.manifest.name];+ const walk = (node: ManifestNode, path: string, inherited: string[], above: string[]) => {+ const siblings = node.children.map((c) => c.manifest.name);+ const ancestors = new Set([...above, node.manifest.name]);for (const child of node.children) {const childPath = `${path}/${child.manifest.name}`;- const siblings = names.filter((n) => n !== child.manifest.name);- out.push({- path: childPath,- manifest: child.manifest,- visible: new Set([...inherited, node.manifest.name, ...siblings]),- ancestors: new Set(above),- });- walk(child, childPath, [...inherited, node.manifest.name, ...names], above);+ const visible = new Set([...inherited, node.manifest.name, ...siblings]);+ out.push({ path: childPath, manifest: child.manifest, visible, ancestors });+ walk(child, childPath, [...inherited, node.manifest.name, ...siblings], [...ancestors]);}};out.push({@@ -143,24 +138,30 @@ export function checkTree(need.from !== undefined? [need.from]: [...m.visible, ...Object.keys(published)].filter(- (name) => name !== mf.name && requirable(name),+ (name) => name !== mf.name && !m.ancestors.has(name),);const matches: string[] = [];+ // Providers that DECLARE this very interface (the same table entry): when exactly+ // one does, it wins over the others that merely have the shape.+ const declared: string[] = [];let lastMismatch: { from: string; method: string; why: string } | null = null;for (const from of candidates) {if (!requirable(from)) continue;const offered = provides[from];if (offered === undefined) continue;+ let satisfied = false;for (const decl of Object.values(offered)) {const gaps = satisfies(decl, required, table);if (gaps.length === 0) {- matches.push(from);- break;+ satisfied = true;+ if (decl === required) declared.push(from);+ continue;}lastMismatch = { from, method: gaps[0]!.method, why: gaps[0]!.why };}+ if (satisfied) matches.push(from);}- if (matches.length === 1) continue;+ if (matches.length === 1 || declared.length === 1) continue;if (need.from !== undefined) {const from = need.from;if (!requirable(from) || provides[from] === undefined) {@@ -197,10 +198,7 @@ export function checkTree(}for (const [slotKey, entries] of Object.entries(mf.contributes)) {const split = splitSlotKey(slotKey);- const reachable =- split !== null &&- (split.module === mf.name || m.visible.has(split.module) || split.module in published);- const target = reachable ? provides[split.module] : undefined;+ const target = split === null ? undefined : provides[split.module];const slot =split === null || target === undefined? undefineddiff --git a/packages/core/src/kernel/decorators.ts b/packages/core/src/kernel/decorators.tsindex 81d817dc..89c12cb2 100644--- a/packages/core/src/kernel/decorators.ts+++ b/packages/core/src/kernel/decorators.ts@@ -31,6 +31,8 @@ export interface ModuleMeta {>;readonly context?: ContextDecl;readonly children?: ReadonlyArray<ModuleClass>;+ /** Interfaces this module forwards from its children — what the subtree offers outside. */+ readonly exports?: ReadonlyArray<IfaceClass>;}/** What a @Component declares: a module's meta minus children — a component exports itself. */diff --git a/packages/core/src/kernel/manifest.ts b/packages/core/src/kernel/manifest.tsindex 660ac2b3..52d87a87 100644--- a/packages/core/src/kernel/manifest.ts+++ b/packages/core/src/kernel/manifest.ts@@ -47,6 +47,15 @@ export interface Manifest {>;readonly context?: ContextDecl;readonly children: ReadonlyArray<ChildRef>;+ /**+ * Aliases in `provides` that are FORWARDED from a child: the module exports what one of+ * its children provides under that interface, so the subtree's other provisions stay+ * private to it. Resolved at boot to the child declaring the interface (else the one+ * child whose provision satisfies it).+ */+ readonly exports?: ReadonlyArray<string>;+ /** What the class was declared as: a component exports itself, a module exports others. Informational. */+ readonly kind?: "module" | "component";}const ManifestType = type({@@ -56,6 +65,8 @@ const ManifestType = type({"contributes?": { "[string]": type({ id: "string > 0", "[string]": "unknown" }).array() },"context?": { version: "number.integer >= 1", "schema?": "unknown" },"children?": type("string").or({ keyed: "string" }).array(),+ "exports?": "string[]",+ "kind?": "'module' | 'component'",});/**diff --git a/packages/core/src/kernel/markers.ts b/packages/core/src/kernel/markers.tsindex b249c290..10d42e19 100644--- a/packages/core/src/kernel/markers.ts+++ b/packages/core/src/kernel/markers.ts@@ -6,7 +6,9 @@/*** A host object compared by NAME across the push boundary: `Opaque<"AbortSignal">`- * projects to `{ opaque: "AbortSignal" }`. The generator refuses an unmarked class type+ * projects to `{ opaque: "<declaring package>#AbortSignal" }` — the generator qualifies+ * the name by the package that declares the type, so two packages' `Resources` never+ * match each other. The generator refuses an unmarked class type* — writing this out is how a declaration says "structure not checked here".*/export type Opaque<Name extends string, T = unknown> = T & { readonly __opaque?: Name };diff --git a/packages/core/src/kernel/module.ts b/packages/core/src/kernel/module.tsindex bc59e629..049e919a 100644--- a/packages/core/src/kernel/module.ts+++ b/packages/core/src/kernel/module.ts@@ -155,15 +155,47 @@ export function moduleDefOf(manifests: ManifestTable;instances?: ReadonlyMap<ModuleClass, object>;extra?: ModuleDef[];+ /**+ * Definitions standing in for nodes, by name — an extension's replacements. A+ * replaced class is not looked at (its table entry, its fields): the definition is+ * taken as it is, and the assembled tree is what gets checked.+ */+ replace?: ReadonlyMap<string, ModuleDef>;},): ModuleDef {const meta = moduleMetaOf(cls);+ const replacement = opts.replace?.get(meta.name);+ if (replacement !== undefined) {+ if (replacement.manifest.name !== meta.name) {+ throw new ModuleBootError(+ `replacement for '${meta.name}' is named '${replacement.manifest.name}' — a replacement keeps the name of the node it stands in for`,+ );+ }+ return replacement;+ }const manifest = opts.manifests[meta.name];if (manifest === undefined) {throw new ModuleBootError(`${meta.name}: not in the generated manifest table — run gen:ifaces`);}- const instance = (opts.instances?.get(cls) ??- new (cls as unknown as new () => object)()) as Record<string, unknown> & {+ // The field decorators record a class's @Use / @Provide / @Bind fields when an instance+ // is constructed. A replacement (a test double standing in for the class) is not one,+ // so the class is probed once to learn its fields before the double is checked against+ // them; the node classes' constructors only store what they are given.+ const supplied = opts.instances?.get(cls);+ if (+ supplied !== undefined &&+ fieldsOf(cls).use.size + fieldsOf(cls).provide.size + fieldsOf(cls).bind.size === 0+ ) {+ try {+ new (cls as unknown as new () => object)();+ } catch {+ // A class that cannot be built without arguments keeps whatever was recorded.+ }+ }+ const instance = (supplied ?? new (cls as unknown as new () => object)()) as Record<+ string,+ unknown+ > & {setup?: (ctx: ClassCtx, context: Json) => void | Promise<void>;park?: () => Json;migrations?: Record<number, (old: Json) => Json>;@@ -187,15 +219,18 @@ export function moduleDefOf(for (const field of Object.keys(manifest.requires)) {if (!f.use.has(field)) throw stale(`requirement '${field}' in the table has no @Use field`);}- const selfAlias = meta.kind === "component" ? meta.name : null;- if (selfAlias !== null && manifest.provides[selfAlias] === undefined)- throw stale(`component '${meta.name}' does not provide itself in the table`);+ // A component's provisions are all the instance: itself, and every interface it+ // `implements` (the generator records both).+ const selfAliases = meta.kind === "component" ? Object.keys(manifest.provides) : [];+ if (meta.kind === "component" && manifest.provides[cls.name] === undefined)+ throw stale(`component '${cls.name}' does not provide itself in the table`);for (const field of f.provide) {if (manifest.provides[field] === undefined)throw stale(`@Provide field '${field}' is not a provision in the table`);}+ const forwarded = new Set(manifest.exports ?? []);for (const field of Object.keys(manifest.provides)) {- if (field === selfAlias) continue;+ if (selfAliases.includes(field) || forwarded.has(field)) continue;if (!f.provide.has(field))throw stale(`provision '${field}' in the table has no @Provide field`);}@@ -215,11 +250,14 @@ export function moduleDefOf(children: [...manifest.children.filter((c) => c !== "*"), ...(extra.length > 0 ? ["*"] : [])],},async create(ctx, context) {+ // A supplied instance (a double) keeps the fields it came with; the tree fills the+ // rest, so a double may be partial.for (const field of f.use.keys())- instance[field] = (ctx.use as Record<string, unknown>)[field];+ if (supplied === undefined || instance[field] === undefined)+ instance[field] = (ctx.use as Record<string, unknown>)[field];if (typeof instance.setup === "function") await instance.setup(ctx, context);const api: Record<string, unknown> = {};- if (selfAlias !== null) api[selfAlias] = instance;+ for (const alias of selfAliases) api[alias] = instance;for (const field of f.provide) {if (instance[field] === undefined) {throw new ModuleBootError(@@ -284,12 +322,19 @@ interface Flat {def: ModuleDef;parent: Flat | null;childrenDefs: ModuleDef[];+ /** Module names above this one; a node never wires to an ancestor (its exports are for outsiders). */+ ancestors: Set<string>;}function flatten(root: ModuleDef): { nodes: Flat[]; tree: ManifestNode } {const nodes: Flat[] = [];const walk = (def: ModuleDef, parent: Flat | null): ManifestNode => {- const flat: Flat = { def, parent, childrenDefs: def.children ?? [] };+ const flat: Flat = {+ def,+ parent,+ childrenDefs: def.children ?? [],+ ancestors: new Set(parent ? [...parent.ancestors, parent.def.manifest.name] : []),+ };nodes.push(flat);return { manifest: def.manifest, children: flat.childrenDefs.map((c) => walk(c, flat)) };};@@ -302,6 +347,7 @@ function wiring(manifest: Manifest,provides: Record<string, Record<string, IfaceDecl>>,ifaces: TableLike,+ ancestors: ReadonlySet<string> = new Set(),): Record<string, { from: string; alias: string }> {const out: Record<string, { from: string; alias: string }> = {};for (const [alias, need] of Object.entries(manifest.requires)) {@@ -310,14 +356,18 @@ function wiring(need.iface.includes("#") ? need.iface : `${manifest.name}#${need.iface}`]!;const candidates = need.from !== undefined ? [need.from] : Object.keys(provides);- for (const from of candidates) {- if (from === manifest.name) continue;- for (const [pAlias, decl] of Object.entries(provides[from] ?? {})) {- // checkTree already established satisfaction; pick the first satisfying alias.- if (satisfiesQuick(decl, required, ifaces)) {- out[alias] = { from, alias: pAlias };- break;+ // checkTree already established a unique satisfier — a provision DECLARING the very+ // interface (the same table entry) wins over one that merely has the shape.+ for (const exact of [true, false]) {+ for (const from of candidates) {+ if (from === manifest.name || ancestors.has(from)) continue;+ for (const [pAlias, decl] of Object.entries(provides[from] ?? {})) {+ if (exact ? decl === required : satisfiesQuick(decl, required, ifaces)) {+ out[alias] = { from, alias: pAlias };+ break;+ }}+ if (out[alias] !== undefined) break;}if (out[alias] !== undefined) break;}@@ -395,16 +445,49 @@ export async function bootModules(root: ModuleDef, opts: BootModulesOptions): Prconst byName = new Map(nodes.map((n) => [n.def.manifest.name, n]));const wires = new Map<string, Record<string, { from: string; alias: string }>>();for (const n of nodes)- wires.set(n.def.manifest.name, wiring(n.def.manifest, provides, opts.ifaces));+ wires.set(n.def.manifest.name, wiring(n.def.manifest, provides, opts.ifaces, n.ancestors));- // Edges: a module comes after what it requires, after what contributes to it, and- // after its children (a parent reaches its children's apis).+ /**+ * Where an exported alias actually comes from: the child declaring the interface (else+ * the one child whose provision satisfies it), followed through nested exports. A+ * module's exports are a scope's outward face, not a gate — a consumer waits for the+ * child, never for the whole group, which is what keeps two groups that need one+ * another's children from being a cycle.+ */+ const exportTarget = (module: string, alias: string): { module: string; alias: string } => {+ const n = byName.get(module);+ if (n === undefined || !(n.def.manifest.exports ?? []).includes(alias))+ return { module, alias };+ const wanted = provides[module]![alias]!;+ const found: Array<{ module: string; alias: string }> = [];+ for (const exact of [true, false]) {+ for (const child of n.childrenDefs) {+ const name = child.manifest.name;+ for (const [cAlias, decl] of Object.entries(provides[name] ?? {})) {+ if (exact ? decl === wanted : satisfiesQuick(decl, wanted, opts.ifaces)) {+ found.push({ module: name, alias: cAlias });+ break;+ }+ }+ }+ if (found.length > 0) break;+ }+ if (found.length !== 1) {+ throw new ModuleBootError(+ `${module}: exports '${alias}' but ${found.length === 0 ? "no child provides it" : `${found.map((f) => f.module).join(", ")} all do`}`,+ );+ }+ return exportTarget(found[0]!.module, found[0]!.alias);+ };++ // Edges: a module comes after what it requires (resolved through exports to the node+ // that provides it), after what contributes to it, and after its children.const after = new Map<string, Set<string>>();for (const n of nodes) after.set(n.def.manifest.name, new Set());for (const n of nodes) {const name = n.def.manifest.name;for (const w of Object.values(wires.get(name)!)) {- if (byName.has(w.from)) after.get(name)!.add(w.from);+ if (byName.has(w.from)) after.get(name)!.add(exportTarget(w.from, w.alias).module);}for (const slotKey of Object.keys(n.def.manifest.contributes)) {const target = splitSlotKey(slotKey)!.module;@@ -466,8 +549,10 @@ export async function bootModules(root: ModuleDef, opts: BootModulesOptions): Prfor (const n of order) {const mf = n.def.manifest;const use: Record<string, unknown> = {};- for (const [alias, w] of Object.entries(wires.get(mf.name)!))- use[alias] = apiOf(w.from, w.alias);+ for (const [alias, w] of Object.entries(wires.get(mf.name)!)) {+ const t = exportTarget(w.from, w.alias);+ use[alias] = apiOf(t.module, t.alias);+ }const contributions: Record<string, Contributed[]> = {};for (const other of nodes) {for (const [slotKey, entries] of Object.entries(other.def.manifest.contributes)) {@@ -511,6 +596,12 @@ export async function bootModules(root: ModuleDef, opts: BootModulesOptions): Prdrain(disposers);throw err;}+ // Exports: the alias is forwarded from the child that declares the interface — else+ // from the one child whose provision satisfies it — so the subtree offers it as one.+ for (const alias of mf.exports ?? []) {+ const t = exportTarget(mf.name, alias);+ inst.api[alias] = apiOf(t.module, t.alias);+ }const validate = () => {for (const alias of Object.keys(mf.provides)) {const value = inst.api[alias];diff --git a/packages/core/src/plugin/index.ts b/packages/core/src/plugin/index.tsindex df114978..101ac119 100644--- a/packages/core/src/plugin/index.ts+++ b/packages/core/src/plugin/index.ts@@ -47,7 +47,19 @@ export { Interface } from "../kernel/markers.js";export type * from "./sandbox.js";-/** What a plugin package's default export is: the module classes to boot, each in the package's `ifaces.json`. */+/**+ * What a plugin package's default export is.+ *+ * `modules` ADD nodes under the host's root. `replaces` STAND IN for nodes the host+ * already has, by name — any node: a component, a module, a whole group with its+ * children — a class of the replaced node's NAME, whose manifest in the package's+ * `ifaces.json` declares its own requires / provides / contributes / children / exports.+ * Nothing about a replacement is checked when it is put in place; the tree it results+ * in is checked as one, before any node runs — every requirement resolved at signature+ * level, every provision present on the instance — so a replacement that offers less+ * than its consumers need is refused by name, and the App does not boot.+ */export interface Plugin {- modules: readonly ModuleClass[];+ modules?: readonly ModuleClass[];+ replaces?: readonly ModuleClass[];}diff --git a/packages/core/test/kernel-modules.test.ts b/packages/core/test/kernel-modules.test.tsindex c3ea039d..4d97b6c4 100644--- a/packages/core/test/kernel-modules.test.ts+++ b/packages/core/test/kernel-modules.test.ts@@ -259,72 +259,6 @@ describe("checkTree", () => {expect.objectContaining({ kind: "unresolved", why: "not visible from here" }),]);});- it("a module cannot require itself, nor an ancestor — created after its children, its api is not there yet", () => {- const selfish = manifest({- name: "scheduler",- requires: { runner: { iface: "ScheduleTaskRunner", from: "scheduler" } },- });- expect(checkTree(tree(http, sessions, selfish), table).problems).toEqual([- expect.objectContaining({ kind: "unresolved", from: "scheduler", why: "itself" }),- ]);-- const byName = manifest({- name: "inner",- requires: { sessions: { iface: "Sessions", from: "outer" } },- });- const unnamed = manifest({ name: "inner", requires: { sessions: { iface: "Sessions" } } });- const outerOf = (inner: Manifest) => ({- manifest: platform,- children: [- {- manifest: manifest({- name: "outer",- provides: { sessions: "Sessions" },- children: ["inner"],- }),- children: [{ manifest: inner, children: [] }],- },- ],- });- const t = { ...table, "outer#Sessions": Sessions, "inner#Sessions": Sessions };- expect(checkTree(outerOf(byName), t).problems).toEqual([- expect.objectContaining({- kind: "unresolved",- from: "outer",- why: expect.stringContaining("an ancestor"),- }),- ]);- expect(checkTree(outerOf(unnamed), t).problems).toEqual([- expect.objectContaining({ kind: "unresolved", from: "" }),- ]);- });-- it("a contribution reaches a parent or a sibling, not another subtree's child", () => {- const parentSlot = {- manifest: platform,- children: [- {- manifest: manifest({ name: "http", provides: { http: "Http" }, children: ["sessions"] }),- children: [{ manifest: sessions, children: [] }],- },- ],- };- expect(checkTree(parentSlot, table).problems).toEqual([]);-- const hidden = {- manifest: platform,- children: [- {- manifest: manifest({ name: "wrapper", children: ["http"] }),- children: [{ manifest: http, children: [] }],- },- { manifest: sessions, children: [] },- ],- };- expect(checkTree(hidden, table).problems).toEqual([- expect.objectContaining({ kind: "no-such-slot", slotKey: "http.routes" }),- ]);- });});describe("parseManifest", () => {@@ -802,6 +736,63 @@ describe("class form: @Module / @Use / @Provide / @Bind", () => {expect(c).toBeInstanceOf(Counter);});+ it("a replacement stands in for a node by name and is checked as the tree, not as the class", async () => {+ // The in-memory stand-in never sees SessionsModule's class or table entry: it is a+ // definition of its own, under the replaced node's name, checked with everything else.+ const calls: string[] = [];+ const memory = {+ manifest: manifests.SessionsModule!,+ create: () => ({+ api: {+ sessions: {+ startTask: async (id: string) => ({ sessionId: `mem-${id}` }),+ statusOf: () => "idle",+ },+ },+ }),+ };+ const seenHere: string[] = [];+ @Module()+ class SchedulerModule {+ @Use(SessionsModule) readonly runner!: Runner;+ setup() {+ seenHere.push(this.runner.statusOf("s"));+ }+ }+ @Module({ children: [SessionsModule, SchedulerModule] })+ class PlatformModule {}+ const def = moduleDefOf(PlatformModule, {+ manifests,+ replace: new Map([["SessionsModule", memory]]),+ });+ const tree = await bootModules(def, { ifaces: t, resources });+ expect(seenHere).toEqual(["idle"]);+ expect((await tree.api<Sessions>("SessionsModule", "sessions").startTask("x")).sessionId).toBe(+ "mem-x",+ );+ calls.push("ok");+ tree.dispose();+ // A stand-in that offers less than a consumer needs is refused by name, before anything runs.+ const hollow = {+ manifest: manifests.SessionsModule!,+ create: () => ({ api: { sessions: {} } }),+ };+ const bad = moduleDefOf(PlatformModule, {+ manifests,+ replace: new Map([["SessionsModule", hollow]]),+ });+ await expect(bootModules(bad, { ifaces: t, resources })).rejects.toThrow(+ /SessionsModule: api 'sessions' does not satisfy 'Sessions': missing \[startTask, statusOf\]/,+ );+ // A stand-in under another name is not a replacement at all.+ expect(() =>+ moduleDefOf(PlatformModule, {+ manifests,+ replace: new Map([["SessionsModule", { ...memory, manifest: manifests.SchedulerModule! }]]),+ }),+ ).toThrow(/keeps the name of the node it stands in for/);+ });+it("an undecorated class is refused by name", () => {class Plain {setup() {}diff --git a/packages/docs/content/server-boot.en.md b/packages/docs/content/server-boot.en.mdindex 569dca32..c59b90ad 100644--- a/packages/docs/content/server-boot.en.md+++ b/packages/docs/content/server-boot.en.md@@ -80,7 +80,7 @@ platformImpl.create│ # order. Plugin modules (a package's ifaces.json) are children of the same tree.└─ ctx.effect: tree.dispose() (every module's effects, reverse order) + manager.shutdown drain```-A plugin is a set of modules — the unit the harness itself is built from, written the same way: `@Component` / `@Module` classes with `@Use` / `@Provide` / `@Bind` fields. Its manifests are generated, not written — the package's build runs `gen-ifaces` over its own tsconfig and ships the `ifaces.json` beside its `package.json` — the table is the package's module payload, and a plugin is a plugin by being listed; the default export is `{ modules: [<class>, …] }`, each class checked against its manifest in that table at load. Split by frequency:+A plugin is a set of modules — the unit the harness itself is built from, written the same way: `@Component` / `@Module` classes with `@Use` / `@Provide` / `@Bind` fields. Its manifests are generated, not written — the package's build runs `gen-ifaces` over its own tsconfig and ships the `ifaces.json` beside its `package.json` — the table is the package's module payload, and a plugin is a plugin by being listed; the default export is `{ modules?: [<class>, …], replaces?: [<class>, …] }` — `modules` the nodes it adds, `replaces` the nodes it stands in for (a class of the replaced node's name: a component, a module, or a whole group) — each class checked against its manifest in that table at load. A stand-in is not checked when it is put in place; the tree it results in is checked as one before any node runs, and refused by name if the stand-in offers less than its consumers need. Split by frequency:| Moment | Frequency | What happens || --------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |@@ -108,7 +108,7 @@ Each subsystem's construction site and external surface (step numbers refer to t| Terminals | `terminal/` — **App-level** | `/api/terminals*` route group (registered into the platform's one Hono app), WS `GET /api/terminals/:id/stream`; ptys are parked and survive swaps || Plugin host | built by ④ `loadPlugins`, published to the registry in ⑤ | an npm package: its generated `ifaces.json` (the module payload), a default export `{ modules: [<class>, …] }`; the configuration surface is `<root>/plugins.json` || Sandbox | `sandbox/service.ts` — **App-level** (a module; backends contribute to its `providers` slot) | a `SandboxModule.providers` contribution from a plugin module; enforcement reaches commands through core's spawn seam |-| Module tree | `src/platform.ts` — **App-level** (booted by create over the claimed capabilities) | `@Component()` on each service / repo class (a node is named by its class) with `@Use()` fields for its dependencies; `@Module({ … })` classes with `@Provide()` fields where one class builds several things; narrow consumer interfaces as abstract classes beside their consumer (`extends Interface<…>()`); no `modules/` directory — each node lives in the file of the thing it is; `src/ifaces.json` generated; `GET /api/contributions` lists what reached the web slots |+| Module tree | `src/platform.ts` — **App-level** (booted by create over the claimed capabilities) | `@Component()` on each service / repo class (a node is named by its class) with `@Use()` fields for its dependencies; `@Module({ children, exports })` groups (`IdentityModule`, `ProjectsModule`, …) whose exports are what their children offer the rest of the tree; `@Module({ … })` classes with `@Provide()` fields where one class builds several things; narrow consumer interfaces as abstract classes beside their consumer (`extends Interface<…>()`); no `modules/` directory — each node lives in the file of the thing it is; `src/ifaces.json` generated; `GET /api/contributions` lists what reached the web slots || Model catalog | No boot-time construction — static core data | `/api/projects/:projectId/models`; the catalog itself lives in `core/src/state/model-catalog.ts` |One request-time path is worth knowing: the platform's HTTP seam offers every request to the current App's `http(request)` first, and only a `null` return falls through to the runtime's own routes; while a hot swap is in flight, requests queue at the seam for the new App instead of hitting a half-disposed one.diff --git a/packages/docs/content/server-boot.zh.md b/packages/docs/content/server-boot.zh.mdindex 2ee1563f..17068dd4 100644--- a/packages/docs/content/server-boot.zh.md+++ b/packages/docs/content/server-boot.zh.md@@ -78,7 +78,7 @@ platformImpl.create│ # 插件模块(包里生成的 ifaces.json)是同一棵树的子节点。└─ ctx.effect:tree.dispose()(每个模块的 effect,逆序)+ manager.shutdown 排空```-插件是一组模块——与 harness 自身的构成单位相同,写法也相同:`@Component` / `@Module` 类,字段上是 `@Use` / `@Provide` / `@Bind`。它的 manifest 是生成的,不是手写的——包的 build 对自己的 tsconfig 跑 `gen-ifaces`,把 `ifaces.json` 随 `package.json` 一起发布——这张表就是包的模块载荷,包是不是插件由它被列出决定;默认导出是 `{ modules: [<class>, …] }`,加载时每个类对照表中自己的 manifest 核对。按频率拆开:+插件是一组模块——与 harness 自身的构成单位相同,写法也相同:`@Component` / `@Module` 类,字段上是 `@Use` / `@Provide` / `@Bind`。它的 manifest 是生成的,不是手写的——包的 build 对自己的 tsconfig 跑 `gen-ifaces`,把 `ifaces.json` 随 `package.json` 一起发布——这张表就是包的模块载荷,包是不是插件由它被列出决定;默认导出是 `{ modules?: [<class>, …], replaces?: [<class>, …] }`——`modules` 是它新增的节点,`replaces` 是它顶替的节点(以被顶替节点为名的类:组件、模块或整个组)——加载时每个类对照表中自己的 manifest 核对。替身放入时不做检查;组装出的树在任何节点运行前作为整体校验,替身提供的少于消费者所需就按名字拒绝。按频率拆开:| 时机 | 频率 | 发生什么 || ------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |@@ -105,7 +105,7 @@ platformImpl.create| HMR 宿主 / 平台 | `hmr/host.ts`(⑤ 末尾) | `PlatformApi`(`park` / `info` / `http` / `terminals` / `attachStream`);`POST /api/hmr/upgrade` 为运行时自留路由,不经平台 || 终端 | `terminal/`——**App 级** | `/api/terminals*` 路由组(注册进平台唯一的 Hono app)、WS `GET /api/terminals/:id/stream`;pty 寄存跨热更新存活 || 插件宿主 | ④ `loadPlugins` 构建,⑤ 发布进资源注册表 | 一个 npm 包:生成的 `ifaces.json`(模块载荷)、默认导出 `{ modules: [<class>, …] }`;配置面是 `<root>/plugins.json` |-| 模块树 | `src/platform.ts`——**App 级**(create 在认领的能力之上启动) | 每个服务 / repo class 上 `@Component()`(节点以 class 命名),依赖是 `@Use()` 字段;一个 class 造出多个东西时用带 `@Provide()` 字段的 `@Module({ … })`;消费者的窄接口是紧挨消费者声明的抽象类(`extends Interface<…>()`);没有 `modules/` 目录——每个节点就住在它所是的那个东西的文件里;生成的 `src/ifaces.json`;`GET /api/contributions` 列出到达 web 槽位的内容 |+| 模块树 | `src/platform.ts`——**App 级**(create 在认领的能力之上启动) | 每个服务 / repo class 上 `@Component()`(节点以 class 命名),依赖是 `@Use()` 字段;`@Module({ children, exports })` 分组(`IdentityModule`、`ProjectsModule`……),exports 是组内 children 向树的其余部分提供的接口;一个 class 造出多个东西时用带 `@Provide()` 字段的 `@Module({ … })`;消费者的窄接口是紧挨消费者声明的抽象类(`extends Interface<…>()`);没有 `modules/` 目录——每个节点就住在它所是的那个东西的文件里;生成的 `src/ifaces.json`;`GET /api/contributions` 列出到达 web 槽位的内容 || 沙盒 | `sandbox/service.ts`——**App 级**(一个模块;后端向它的 `providers` 槽位投递) | 插件模块向 `SandboxModule.providers` 投递的一条 contribution;约束经 core 的 spawn seam 落到命令上 || 模型目录 | 无启动期构建——core 静态数据 | `/api/projects/:projectId/models`;目录本体在 `core/src/state/model-catalog.ts` |diff --git a/packages/server/src/app.ts b/packages/server/src/app.tsindex 353116b1..d4c07db9 100644--- a/packages/server/src/app.ts+++ b/packages/server/src/app.ts@@ -27,7 +27,6 @@ import { bodyLimit } from "hono/body-limit";import { bodyLimitBytes, toAttachmentLimits } from "./services/attachment-limits.js";import type { DatabaseSync } from "node:sqlite";import type { ModuleTree } from "@prismshadow/penguin-core/kernel";-import type { ProjectAccess } from "./services/project-access.js";import type { ServerConfig } from "./config.js";import { applyProxySettings, mergedNoProxy } from "./net/proxy.js";import {@@ -41,10 +40,13 @@ import {RUNTIME_LIFECYCLE_RESOURCE_ID,RUNTIME_HMR_RESOURCE_ID,RUNTIME_OVERRIDES_RESOURCE_ID,+ type Replacements,RUNTIME_PROXY_RESOURCE_ID,RuntimeCapabilities,+ ConsoleLog,+ type Log,+ type ProxyControl,} from "./hmr/capabilities.js";-import type { ProxyControl } from "./hmr/capabilities.js";import { ensureCliShim } from "./services/cli-shim.js";import { openDatabase } from "./db/database.js";import { MachinesRepo } from "./db/repos/machines.js";@@ -169,6 +171,10 @@ import { UsageRecorder } from "./runtime/usage-recorder.js";import { previewRoutes } from "./http/routes/preview.js";import { MachinesService } from "./machines/service.js";import { wire } from "@prismshadow/penguin-core/kernel";+import type { Settings } from "./mechanisms/settings.js";+import type { Errors } from "./mechanisms/observability.js";+import type { Access } from "./mechanisms/projects.js";+import type { Auth } from "./mechanisms/identity.js";/*** What the runtime process holds after boot: the capabilities it owns for the process@@ -186,48 +192,6 @@ export interface ServerBoot {tree: ModuleTree;}-export interface BuildDepsOverrides {- /** Test double: session-manager's underlying loader (avoids the real LLM/SDK path). */- loader?: SessionLoader;- /** Test double: Session title generator (avoids real LLM requests). */- titles?: TitleNotifier;- /** Test double: update-check service with a stubbed fetch/clock (avoids real network calls). */- updateCheck?: UpdateCheckService;- /** Tests: a job service over a scripted runner, so no real `penguin update` is ever spawned. */- updateJob?: UpdateJobService;- /** Test double: the Feishu connector's SDK factory (avoids real Lark network / long connections). */- feishuSdk?: FeishuSdk;- /** Test double: the Telegram connector's Bot API transport (avoids real Telegram network / long polls). */- telegramTransport?: TelegramTransport;- /** Test hook: the Telegram connector's poll backoff (tests collapse it to zero). */- telegramRetryDelayMs?: (failures: number) => number;- /** Test double: the QQ connector's OpenAPI + gateway transport (avoids real QQ network / a WebSocket). */- qqTransport?: QQTransport;- /** Test hook: how long the QQ connector withholds its coalesced tail (tests collapse it to zero). */- qqTailFlushMs?: number;- /** Test hook: the bridge's pace between a per-line reply's messages (tests collapse it to zero). */- messagingLineDelayMs?: number;- /** Test hook: one binding's inbound image budget, so a budget test needs no 20MB buffers. */- messagingInboundImageBudgetBytes?: number;- /** Test double: the QQ scan-to-connect transport (avoids real q.qq.com requests). */- qqScanTransport?: QQScanTransport;- /** Test double: the WeChat connector's long-poll + CDN transport (avoids real WeChat network). */- wechatTransport?: WeChatTransport;- /** Test hook: the WeChat poll loop's backoff (tests collapse it to zero). */- wechatRetryDelayMs?: (failures: number) => number;- /** Test double: the WeChat scan-to-connect transport (avoids real ilinkai.weixin.qq.com requests). */- wechatScanTransport?: WeChatScanTransport;- /** Test double: machines service whose ssh effects are faked (the real one reads ~/.ssh/config and spawns ssh). */- machines?: MachinesService;- /**- * Test double: scrypt work factor for password hashes written through this app.- * Omitted in production, where the KDF runs at full strength.- */- passwordHashCost?: number;- log?: (line: string) => void;- now?: () => Date;-}-/*** Assemble the runtime core, publish its capabilities, boot the platform (which builds* the business surface — see app.ts), and return the merged view. Shared@@ -240,7 +204,7 @@ export interface BuildDepsOverrides {*/export async function bootAppDeps(config: ServerConfig,- overrides: BuildDepsOverrides = {},+ replacements: Replacements = [],plugins?: PluginHost,): Promise<ServerBoot> {const db = openDatabase(config.dbPath);@@ -283,7 +247,10 @@ export async function bootAppDeps(// Here rather than per App, for the same reason the two above are: it is a fact about// this PROCESS's installation, and a hot-pushed platform — compiled somewhere else// entirely — has no way to work out where the CLI it should point at lives.- const shimLog = overrides.log ?? ((line: string) => console.log(line));+ // Pre-boot, so the Log mechanism is not up yet: a ConsoleLog replacement (the double a+ // test hands the tree) is honoured here too, and the process's own console otherwise.+ const logDouble = replacements.find(([cls]) => cls === ConsoleLog)?.[1] as Log | undefined;+ const shimLog = (line: string): void => (logDouble ?? new ConsoleLog()).line(line);const shim = ensureCliShim(config.root, config.cliEntry);if (shim.kind === "written") {shimLog(`Agent CLI: ${path.join(shim.dir, "penguin")} -> ${shim.entry}`);@@ -305,7 +272,7 @@ export async function bootAppDeps(hmr.resources.register(RUNTIME_CHANNELS_RESOURCE_ID, channels);hmr.resources.register(RUNTIME_PROXY_RESOURCE_ID, applyProxySettings);hmr.resources.register(RUNTIME_HMR_RESOURCE_ID, hmr);- hmr.resources.register(RUNTIME_OVERRIDES_RESOURCE_ID, overrides);+ hmr.resources.register(RUNTIME_OVERRIDES_RESOURCE_ID, replacements);const desktop = config.desktopToken !== null ? new DesktopService(config.desktopToken) : null;hmr.resources.register(RUNTIME_DESKTOP_RESOURCE_ID, desktop);const lifecycle = new LifecycleService(config.supervised);@@ -334,11 +301,11 @@ export async function bootAppDeps(/** Assembles the Hono app (does not listen on a port). */export function createRuntimeApp(boot: ServerBoot): Hono<AppEnv> {const { tree } = boot;- const errors = tree.api<ErrorRecorder>("ErrorRecorder", "ErrorRecorder");- const log = tree.api<{ line(text: string): void }>("RuntimeModule", "log");- const settings = tree.api<ServerSettingsRepo>("ServerSettingsRepo", "ServerSettingsRepo");- const access = tree.api<ProjectAccess>("ProjectAccess", "ProjectAccess");- const authService = tree.api<AuthService>("AuthService", "AuthService");+ const errors = tree.api<Errors>("ObservabilityModule", "Errors");+ const log = tree.api<{ line(text: string): void }>("RuntimeModule", "Log");+ const settings = tree.api<Settings>("SettingsModule", "Settings");+ const access = tree.api<Access>("ProjectsModule", "Access");+ const authService = tree.api<Auth>("IdentityModule", "Auth");const deps = {config: boot.config,desktop: boot.desktop,diff --git a/packages/server/src/auth/middleware.ts b/packages/server/src/auth/middleware.tsindex 2e5c9759..f662ea83 100644--- a/packages/server/src/auth/middleware.ts+++ b/packages/server/src/auth/middleware.ts@@ -17,7 +17,8 @@ import type { MiddlewareHandler } from "hono";import { getCookie, setCookie } from "hono/cookie";import { HttpError } from "../http/errors.js";import type { UserRow } from "../db/repos/users.js";-import type { AuthService, SessionVia } from "./service.js";+import type { SessionVia } from "./service.js";+import type { Auth } from "../mechanisms/identity.js";/** Session cookie name. */export const SESSION_COOKIE = "penguin_session";@@ -62,7 +63,7 @@ export function currentUser(c: { var: { user: UserRow } }): UserRow {return c.var.user;}-export function authMiddleware(auth: AuthService, trustProxy: boolean): MiddlewareHandler<AppEnv> {+export function authMiddleware(auth: Auth, trustProxy: boolean): MiddlewareHandler<AppEnv> {return async (c, next) => {// Bearer first: an explicit credential on the request outranks ambient cookies, and// a wrong one is an error, never a silent fallback (see the module doc).diff --git a/packages/server/src/auth/password.ts b/packages/server/src/auth/password.tsindex 9e8208e4..baf5bd19 100644--- a/packages/server/src/auth/password.ts+++ b/packages/server/src/auth/password.ts@@ -1,3 +1,4 @@+import { Component, Interface } from "@prismshadow/penguin-core/kernel";/*** Password hashing (slow-hash storage).*@@ -81,3 +82,16 @@ export async function verifyPassword(password: string, stored: string): Promise<}return actual.length === expected.length && timingSafeEqual(actual, expected);}++/** Hashes the passwords this server writes; a test stands in a cheap one. */+export abstract class PasswordHasher extends Interface<{+ hash(password: string): Promise<string>;+}>() {}++/** scrypt at full strength. */+@Component()+export class ScryptHasher implements PasswordHasher {+ hash(password: string): Promise<string> {+ return hashPassword(password, SCRYPT_COST);+ }+}diff --git a/packages/server/src/auth/service.ts b/packages/server/src/auth/service.tsindex f20e8286..fc8e64d8 100644--- a/packages/server/src/auth/service.ts+++ b/packages/server/src/auth/service.ts@@ -10,13 +10,15 @@ import { randomBytes } from "node:crypto";import { tokensEqual } from "./api-token.js";import type { UserInfo } from "../api/types.js";import { HttpError } from "../http/errors.js";-import type { UserRow, UsersRepo } from "../db/repos/users.js";+import type { UserRow } from "../db/repos/users.js";import { sessionTokenHash } from "../db/repos/auth-sessions.js";import type { SessionViaValue, AuthSessionsRepo } from "../db/repos/auth-sessions.js";import type { AuthRuntimeState } from "./runtime-state.js";-import { SCRYPT_COST, hashPassword, verifyPassword } from "./password.js";+import { verifyPassword } from "./password.js";+import type { PasswordHasher } from "./password.js";import { Component, Use, Interface } from "@prismshadow/penguin-core/kernel";-import type { AuthState, Config, Overrides } from "../hmr/capabilities.js";+import type { AuthState, Clock, Config } from "../hmr/capabilities.js";+import type { Auth, AuthSessions, Users } from "../mechanisms/identity.js";export const MIN_PASSWORD_LENGTH = 8;@@ -67,9 +69,9 @@ export function toUserInfo(row: UserRow): UserInfo {}@Component()-export class AuthService {- @Use() private readonly users!: UsersRepo;- @Use() private readonly authSessions!: AuthSessionsRepo;+export class AuthService implements Auth {+ @Use() private readonly users!: Users;+ @Use() private readonly authSessions!: AuthSessions;/*** Process-scoped auth values (runtime-state.ts). Held by the RUNTIME so the link a boot* printed survives a platform push; everything else about auth is rebuilt with the App.@@ -78,10 +80,8 @@ export class AuthService {/** Provisions the initial Project at signup — declared at the consumer, below. */@Use() private readonly provisioner!: InitialProjectProvisioner;@Use() private readonly config!: Config;- @Use() private readonly overrides!: Overrides;- private now: () => Date = () => new Date();- /** scrypt work factor for hashes this service writes; a test double lowers it. */- private hashCost: number = SCRYPT_COST;+ @Use() private readonly clock!: Clock;+ @Use() private readonly hasher!: PasswordHasher;/** Session lifetime, for the cookie that must expire WITH the session, not before it. */get sessionTtlMs(): number {return this.config.authSessionTtlMs;@@ -95,10 +95,7 @@ export class AuthService {}setup(): void {- const overrides = this.overrides.value();- this.now = overrides.now ?? this.now;- this.hashCost = overrides.passwordHashCost ?? SCRYPT_COST;- this.authSessions.deleteExpired(this.now().toISOString());+ this.authSessions.deleteExpired(this.clock.now().toISOString());}/**@@ -145,12 +142,12 @@ export class AuthService {}const user: UserRow = {userId: ADMIN_USER_ID,- passwordHash: await hashPassword(password, this.hashCost),+ passwordHash: await this.hasher.hash(password),isAdmin: true,passwordIsInitial: true,displayName: null,avatar: null,- createdAt: this.now().toISOString(),+ createdAt: this.clock.now().toISOString(),};this.users.insert(user);try {@@ -188,7 +185,7 @@ export class AuthService {}async login(userId: string, password: string): Promise<{ user: UserInfo; token: string }> {- const nowMs = this.now().getTime();+ const nowMs = this.clock.now().getTime();for (const [key, entry] of this.loginFailures) {if (nowMs - entry.lastFailureAt > LOGIN_FAILURE_IDLE_MS) this.loginFailures.delete(key);}@@ -208,12 +205,12 @@ export class AuthService {if (!row || !ok) {this.loginFailures.set(userId, {failures: (failed?.failures ?? 0) + 1,- lastFailureAt: this.now().getTime(),+ lastFailureAt: this.clock.now().getTime(),});throw new HttpError(401, "invalid_credentials", "Incorrect username or password.");}this.loginFailures.delete(userId);- this.authSessions.deleteExpired(this.now().toISOString());+ this.authSessions.deleteExpired(this.clock.now().toISOString());return { user: toUserInfo(row), token: this.issueSession(row.userId, "password") };}@@ -252,7 +249,7 @@ export class AuthService {if (newPassword.length < MIN_PASSWORD_LENGTH) {throw new HttpError(400, "invalid_password", "Password must be at least 8 characters.");}- this.users.updatePassword(userId, await hashPassword(newPassword, this.hashCost), false);+ this.users.updatePassword(userId, await this.hasher.hash(newPassword), false);// A successful set proves at least what the successful login that resets the counter// proves (the old password, or a desktop/setup session), so it resets it too. Without// this, anyone spamming the login endpoint holds the backoff window open, and the sign-in@@ -308,7 +305,7 @@ export class AuthService {const tokenHash = sessionTokenHash(token);const session = this.authSessions.findByTokenHash(tokenHash);if (!session) return null;- const now = this.now();+ const now = this.clock.now();const expiresAt = Date.parse(session.expiresAt);if (expiresAt <= now.getTime()) {this.authSessions.delete(tokenHash);@@ -331,7 +328,7 @@ export class AuthService {return this.authSessions.issue({userId,via,- now: this.now(),+ now: this.clock.now(),ttlMs: this.sessionTtlMs,}).token;}diff --git a/packages/server/src/db/repos/agents.ts b/packages/server/src/db/repos/agents.tsindex 5b978506..31702eca 100644--- a/packages/server/src/db/repos/agents.ts+++ b/packages/server/src/db/repos/agents.ts@@ -3,6 +3,7 @@*/import { Component, Use } from "@prismshadow/penguin-core/kernel";import type { Db } from "../../hmr/capabilities.js";+import type { AgentIndex } from "../../mechanisms/projects.js";export interface AgentRow {projectId: string;@@ -11,7 +12,7 @@ export interface AgentRow {}@Component()-export class AgentsRepo {+export class AgentsRepo implements AgentIndex {@Use() private readonly db!: Db;/** Idempotent insert: backfills an untracked Agent discovered via directory scan; shared with explicit creation. */diff --git a/packages/server/src/db/repos/auth-sessions.ts b/packages/server/src/db/repos/auth-sessions.tsindex 9409f9f3..a57d1cd8 100644--- a/packages/server/src/db/repos/auth-sessions.ts+++ b/packages/server/src/db/repos/auth-sessions.ts@@ -6,6 +6,7 @@import { createHash, randomBytes } from "node:crypto";import { Component, Use } from "@prismshadow/penguin-core/kernel";import type { Db } from "../../hmr/capabilities.js";+import type { AuthSessions } from "../../mechanisms/identity.js";/** How a session was established, as stored. NULL on rows formed before the column existed. */export type SessionViaValue = "password" | "desktop" | "setup" | "cli";@@ -24,7 +25,7 @@ export function sessionTokenHash(token: string): string {}@Component()-export class AuthSessionsRepo {+export class AuthSessionsRepo implements AuthSessions {@Use() private readonly db!: Db;/**diff --git a/packages/server/src/db/repos/errors.ts b/packages/server/src/db/repos/errors.tsindex 00d7e9a8..331fe33a 100644--- a/packages/server/src/db/repos/errors.ts+++ b/packages/server/src/db/repos/errors.ts@@ -22,6 +22,7 @@*/import { Component, Use } from "@prismshadow/penguin-core/kernel";import type { Db } from "../../hmr/capabilities.js";+import type { ErrorLog } from "../../mechanisms/observability.js";/** Row cap: once exceeded, oldest rows are evicted in ascending id order (see file header). */export const MAX_ROWS = 20000;@@ -90,7 +91,7 @@ export interface ErrorItem {}@Component()-export class ErrorsRepo {+export class ErrorsRepo implements ErrorLog {private readonly maxRows: number = MAX_ROWS;private readonly pruneEvery: number = PRUNE_EVERY;/** Insert count since the last capacity check (see file header: avoids COUNT on every call). */diff --git a/packages/server/src/db/repos/members.ts b/packages/server/src/db/repos/members.tsindex 7c207736..82142f73 100644--- a/packages/server/src/db/repos/members.ts+++ b/packages/server/src/db/repos/members.ts@@ -4,6 +4,7 @@*/import { Component, Use } from "@prismshadow/penguin-core/kernel";import type { Db } from "../../hmr/capabilities.js";+import type { Members } from "../../mechanisms/projects.js";export interface MemberRow {projectId: string;@@ -12,7 +13,7 @@ export interface MemberRow {}@Component()-export class MembersRepo {+export class MembersRepo implements Members {@Use() private readonly db!: Db;insert(row: MemberRow): void {diff --git a/packages/server/src/db/repos/messaging-bindings.ts b/packages/server/src/db/repos/messaging-bindings.tsindex d4c97b5e..b95d94de 100644--- a/packages/server/src/db/repos/messaging-bindings.ts+++ b/packages/server/src/db/repos/messaging-bindings.ts@@ -29,6 +29,7 @@*/import { Component, Use } from "@prismshadow/penguin-core/kernel";import type { Db } from "../../hmr/capabilities.js";+import type { MessagingBindings } from "../../mechanisms/messaging.js";export interface MessagingBindingRow {sessionId: string;@@ -118,7 +119,7 @@ function mapRow(r: Record<string, unknown>): MessagingBindingRow {}@Component()-export class MessagingBindingsRepo {+export class MessagingBindingsRepo implements MessagingBindings {@Use() private readonly db!: Db;/** The Session's saved config of ONE channel (null when that channel is not configured). */diff --git a/packages/server/src/db/repos/projects.ts b/packages/server/src/db/repos/projects.tsindex f715c345..c4c3c036 100644--- a/packages/server/src/db/repos/projects.ts+++ b/packages/server/src/db/repos/projects.ts@@ -5,6 +5,7 @@import type { ProjectRole } from "../../api/types.js";import { Component, Use } from "@prismshadow/penguin-core/kernel";import type { Db } from "../../hmr/capabilities.js";+import type { Projects } from "../../mechanisms/projects.js";export interface ProjectRow {projectId: string;@@ -25,7 +26,7 @@ function mapRow(r: Record<string, unknown>): ProjectRow {}@Component()-export class ProjectsRepo {+export class ProjectsRepo implements Projects {@Use() private readonly db!: Db;insert(row: ProjectRow): void {diff --git a/packages/server/src/db/repos/schedules.ts b/packages/server/src/db/repos/schedules.tsindex 04b56185..3997aa23 100644--- a/packages/server/src/db/repos/schedules.ts+++ b/packages/server/src/db/repos/schedules.ts@@ -9,6 +9,7 @@*/import { Component, Use } from "@prismshadow/penguin-core/kernel";import type { Db } from "../../hmr/capabilities.js";+import type { Schedules } from "../../mechanisms/sessions.js";export interface ScheduleStateRow {projectId: string;@@ -41,7 +42,7 @@ function mapRow(r: Record<string, unknown>): ScheduleStateRow {}@Component()-export class SchedulesRepo {+export class SchedulesRepo implements Schedules {@Use() private readonly db!: Db;find(projectId: string, agentId: string, name: string): ScheduleStateRow | null {diff --git a/packages/server/src/db/repos/server-settings.ts b/packages/server/src/db/repos/server-settings.tsindex f0178f97..2cf213d4 100644--- a/packages/server/src/db/repos/server-settings.ts+++ b/packages/server/src/db/repos/server-settings.ts@@ -10,6 +10,7 @@ import {} from "../../services/attachment-limits.js";import { Component, Use } from "@prismshadow/penguin-core/kernel";import type { Db } from "../../hmr/capabilities.js";+import type { Settings } from "../../mechanisms/settings.js";/** Key of the "application uses the proxy" switch (the server's own outbound dispatcher); default on. */const PROXY_FOR_APP_KEY = "proxy_for_app";@@ -35,7 +36,7 @@ const ATTACHMENT_MAX_MB_KEY = "attachment_max_mb";const ATTACHMENT_TOTAL_MB_KEY = "attachment_total_mb";@Component()-export class ServerSettingsRepo {+export class ServerSettingsRepo implements Settings {@Use() private readonly db!: Db;/** Returns the raw JSON-encoded value; null if never set. */diff --git a/packages/server/src/db/repos/sessions.ts b/packages/server/src/db/repos/sessions.tsindex 303df60e..9ef1e287 100644--- a/packages/server/src/db/repos/sessions.ts+++ b/packages/server/src/db/repos/sessions.ts@@ -6,6 +6,7 @@ import type { ThinkingLevelName } from "@prismshadow/penguin-core/interfaces";import type { ApprovalMode } from "../../api/types.js";import { Component, Use } from "@prismshadow/penguin-core/kernel";import type { Db } from "../../hmr/capabilities.js";+import type { SessionIndex } from "../../mechanisms/sessions.js";export interface SessionRow {sessionId: string;@@ -73,7 +74,7 @@ function mapRow(r: Record<string, unknown>): SessionRow {}@Component()-export class SessionsRepo {+export class SessionsRepo implements SessionIndex {@Use() private readonly db!: Db;insert(row: SessionRow): void {diff --git a/packages/server/src/db/repos/trace-index.ts b/packages/server/src/db/repos/trace-index.tsindex c59ae3ab..2565ab8d 100644--- a/packages/server/src/db/repos/trace-index.ts+++ b/packages/server/src/db/repos/trace-index.ts@@ -7,6 +7,7 @@ import type { SessionSource } from "../../api/types.js";import { asSessionSource } from "../../runtime/session-sources.js";import { Component, Use } from "@prismshadow/penguin-core/kernel";import type { Db } from "../../hmr/capabilities.js";+import type { TraceIndexStore } from "../../mechanisms/traces.js";/** One indexed Trace shard. */export interface TraceFileRow {@@ -61,7 +62,7 @@ function mapSession(r: Record<string, unknown>): TraceSessionRow {}@Component()-export class TraceIndexRepo {+export class TraceIndexRepo implements TraceIndexStore {@Use() private readonly db!: Db;upsertFile(row: TraceFileRow): void {diff --git a/packages/server/src/db/repos/ui-prefs.ts b/packages/server/src/db/repos/ui-prefs.tsindex bf9fb34f..7945272f 100644--- a/packages/server/src/db/repos/ui-prefs.ts+++ b/packages/server/src/db/repos/ui-prefs.ts@@ -3,9 +3,10 @@*/import { Component, Use } from "@prismshadow/penguin-core/kernel";import type { Db } from "../../hmr/capabilities.js";+import type { UiPrefsStore } from "../../mechanisms/settings.js";@Component()-export class UiPrefsRepo {+export class UiPrefsRepo implements UiPrefsStore {@Use() private readonly db!: Db;/** Returns the raw JSON string; null if never set. */diff --git a/packages/server/src/db/repos/usage.ts b/packages/server/src/db/repos/usage.tsindex cfc49a3d..03fa0a5d 100644--- a/packages/server/src/db/repos/usage.ts+++ b/packages/server/src/db/repos/usage.ts@@ -8,6 +8,7 @@import type { UsageGroupBy } from "../../api/types.js";import { Component, Use } from "@prismshadow/penguin-core/kernel";import type { Db } from "../../hmr/capabilities.js";+import type { UsageStore } from "../../mechanisms/observability.js";export interface UsageRecordInsert {ts: string;@@ -183,7 +184,7 @@ function toSums(r: Record<string, unknown>): UsageModelSums {}@Component()-export class UsageRepo {+export class UsageRepo implements UsageStore {@Use() private readonly db!: Db;insert(r: UsageRecordInsert): void {diff --git a/packages/server/src/db/repos/users.ts b/packages/server/src/db/repos/users.tsindex 6b8f344e..6e52e74f 100644--- a/packages/server/src/db/repos/users.ts+++ b/packages/server/src/db/repos/users.ts@@ -4,6 +4,7 @@*/import { Component, Use } from "@prismshadow/penguin-core/kernel";import type { Db } from "../../hmr/capabilities.js";+import type { Users } from "../../mechanisms/identity.js";export interface UserRow {userId: string;@@ -31,7 +32,7 @@ function mapRow(r: Record<string, unknown>): UserRow {}@Component()-export class UsersRepo {+export class UsersRepo implements Users {@Use() private readonly db!: Db;insert(row: UserRow): void {diff --git a/packages/server/src/hmr/capabilities.ts b/packages/server/src/hmr/capabilities.tsindex 4a983244..a96e9e9f 100644--- a/packages/server/src/hmr/capabilities.ts+++ b/packages/server/src/hmr/capabilities.ts@@ -21,17 +21,16 @@* registry.*/import type { DatabaseSync } from "node:sqlite";-import type { Resources, Opaque, ClassCtx } from "@prismshadow/penguin-core/kernel";+import type { Resources, Opaque, ModuleClass } from "@prismshadow/penguin-core/kernel";import type { ServerConfig } from "../config.js";import type { AuthRuntimeState } from "../auth/runtime-state.js";import { newAuthRuntimeState } from "../auth/runtime-state.js";import type { ChannelHub, Channel } from "../runtime/channel.js";import type { ProxySettings } from "../net/proxy.js";-import type { BuildDepsOverrides } from "../app.js";import type { HmrHost } from "./host.js";import type { DesktopService } from "../services/desktop-service.js";import type { LifecycleService } from "../services/lifecycle-service.js";-import { Interface, Module, Provide } from "@prismshadow/penguin-core/kernel";+import { Interface, Component, Module, Provide, Use } from "@prismshadow/penguin-core/kernel";/*** What one side of the seam speaks: a family, and a Go-style structural interface per@@ -116,9 +115,8 @@ export const RUNTIME_INTERFACES: RuntimeInterfaces = {channels: ["get", "peek", "broadcast", "dispose", "setActivityProbe"],proxy: [],hmr: ["resources", "ensure", "resolveWebSource", "assetsDir", "dispose"],- // The construction-override seam (BuildDepsOverrides): production publishes {}, tests- // publish live collaborators (loader fakes, clocks). Presence-only — its fields are all- // optional, so there are no members to verify.+ // The replacement seam (Replacements): production publishes [], tests publish the nodes+ // they stand in for. Presence-only — a list has no members to verify.overrides: [],desktop: ["onShutdownRequest", "requestShutdown", "verifyToken", "redeemLoginToken"],lifecycle: ["supervised", "onRestartRequest", "requestRestart"],@@ -195,7 +193,7 @@ export const RUNTIME_DESKTOP_RESOURCE_ID = "runtime:desktop";* a definite "nobody would relaunch me" to refuse with, not a missing capability.*/export const RUNTIME_LIFECYCLE_RESOURCE_ID = "runtime:lifecycle";-/** Test-only: BuildDepsOverrides published by bootAppDeps for the platform boot to claim. */+/** Test-only: the node Replacements published by bootAppDeps for the platform boot to claim. */export const RUNTIME_OVERRIDES_RESOURCE_ID = "runtime:overrides";/**@@ -238,8 +236,8 @@ export interface RuntimeCapabilities {/** Null on a non-desktop server (a real value, not an absent capability). */desktop: DesktopService | null;lifecycle: LifecycleService;- /** The construction-override seam; {} outside tests. */- overrides: BuildDepsOverrides;+ /** Nodes a test stands in for (see Replacements); [] outside tests. */+ replacements: Replacements;}/**@@ -292,7 +290,7 @@ export function claimRuntimeCapabilities(resources: Resources): RuntimeClaim {}// Desktop is nullable by meaning, so it sits outside the all-present check.const desktop = resources.claim<DesktopService | null>(RUNTIME_DESKTOP_RESOURCE_ID) ?? null;- const overrides = resources.claim<BuildDepsOverrides>(RUNTIME_OVERRIDES_RESOURCE_ID) ?? {};+ const replacements = resources.claim<Replacements>(RUNTIME_OVERRIDES_RESOURCE_ID) ?? [];// Optional by design (see the resource's own note): an older runtime published no such// holder, and a fresh one is a correct, slightly forgetful substitute. A runtime older// than this platform may also publish a holder missing the fields added since; they are@@ -324,15 +322,15 @@ export function claimRuntimeCapabilities(resources: Resources): RuntimeClaim {}return {kind: "claimed",- caps: { config, db, authState, channels, proxyControl, hmr, desktop, lifecycle, overrides },+ caps: { config, db, authState, channels, proxyControl, hmr, desktop, lifecycle, replacements },};}/**- * What the runtime publishes, as the platform's modules see it. The runtime registers live- * objects in the resource registry (hmr/capabilities.ts); this module claims them once and- * exposes each under an interface here. Every other module reaches the runtime only through- * these — `requires: { db: { iface: "runtime#Db", from: "RuntimeModule" } }` — so what a bundle+ * What the runtime publishes, as the tree sees it. The runtime registers live objects in+ * the resource registry; the platform claims them once and hands each to a node of its own+ * (RuntimeDb, RuntimeChannels, …) that provides it under an interface declared here. Every+ * other node reaches the runtime only through these — `@Use() db!: Db` — so what a bundle* needs from its host is written down and checked, not assumed.*/@@ -401,11 +399,6 @@ export abstract class Lifecycle extends Interface<Pick<LifecycleService, "supervised" | "onRestartRequest" | "requestRestart">>() {}-/** Construction overrides — production publishes {}, tests publish live collaborators. */-export abstract class Overrides extends Interface<{- value(): Opaque<"BuildDepsOverrides", BuildDepsOverrides>;-}>() {}-export abstract class Log extends Interface<{line(text: string): void;}>() {}@@ -419,42 +412,121 @@ export abstract class ResourceGroups extends Interface<{adoptable(group: string): boolean;}>() {}+/** A clock every node reads time through; a test replaces it. */+export abstract class Clock extends Interface<{ now(): Date }>() {}++/** Where the data lives — what most nodes actually want from the config. */+export abstract class Paths extends Interface<{ root: string }>() {}+/**- * The claimed capabilities are handed in by the platform node, which is the one place the- * registry is read (see hmr/platform.ts): this module only presents them. It is the one- * module class with constructor arguments, so the platform pre-builds its instance.+ * A replacement for one node of the tree: the class the platform would build, and the+ * instance to boot in its place. Tests publish these (bootAppDeps) for the platform to+ * claim; production publishes none. A replacement is checked exactly like the node it+ * stands in for — the table says what the class provides, the instance has to have it.+ */+export type Replacements = ReadonlyArray<readonly [ModuleClass, object]>;++/**+ * The claimed capabilities enter the tree one node each, so a consumer names the one it+ * needs and nothing else. They are the only classes with constructor arguments; the+ * platform pre-builds their instances (platform.ts) from the claim, which is the one+ * place the registry is read.*/@Module()-export class RuntimeModule {+export class RuntimeConfig {@Provide() config!: Config;+ constructor(private readonly caps: RuntimeCapabilities) {}+ setup() {+ this.config = this.caps.config;+ }+}+@Module()+export class RuntimeDb {@Provide() db!: Db;+ constructor(private readonly caps: RuntimeCapabilities) {}+ setup() {+ this.db = this.caps.db;+ }+}+@Module()+export class RuntimeChannels {@Provide() channels!: Channels;+ constructor(private readonly caps: RuntimeCapabilities) {}+ setup() {+ this.channels = this.caps.channels;+ }+}+@Module()+export class RuntimeProxy {@Provide() proxy!: Proxy;+ constructor(private readonly caps: RuntimeCapabilities) {}+ setup() {+ this.proxy = { apply: this.caps.proxyControl };+ }+}+@Module()+export class RuntimeHmr {@Provide() hmr!: Hmr;+ constructor(private readonly caps: RuntimeCapabilities) {}+ setup() {+ this.hmr = this.caps.hmr;+ }+}+@Module()+export class RuntimeDesktop {@Provide() desktop!: Desktop;- @Provide() authState!: AuthState;+ constructor(private readonly caps: RuntimeCapabilities) {}+ setup() {+ const { desktop } = this.caps;+ this.desktop = { current: () => desktop };+ }+}+@Module()+export class RuntimeLifecycle {@Provide() lifecycle!: Lifecycle;- @Provide() overrides!: Overrides;- @Provide() log!: Log;+ constructor(private readonly caps: RuntimeCapabilities) {}+ setup() {+ this.lifecycle = this.caps.lifecycle;+ }+}+@Module()+export class RuntimeAuthState {+ @Provide() authState!: AuthState;+ constructor(private readonly caps: RuntimeCapabilities) {}+ setup() {+ this.authState = this.caps.authState;+ }+}+@Module()+export class RuntimeResourceGroups {@Provide() resourceGroups!: ResourceGroups;- constructor(- private readonly caps: RuntimeCapabilities,- private readonly adoptable: (group: string) => boolean,- ) {}-- setup(_ctx: ClassCtx) {- const { caps } = this;- const log = caps.overrides.log ?? ((line: string) => console.log(line));- this.config = caps.config;- this.db = caps.db;- this.channels = caps.channels;- this.proxy = { apply: caps.proxyControl };- this.hmr = caps.hmr;- this.desktop = { current: () => caps.desktop };- this.authState = caps.authState;- this.lifecycle = caps.lifecycle;- this.overrides = { value: () => caps.overrides };- this.log = { line: log };+ constructor(private readonly adoptable: (group: string) => boolean) {}+ setup() {this.resourceGroups = { adoptable: this.adoptable };}}++/** The process log; a test replaces it with a sink. */+@Component()+export class ConsoleLog implements Log {+ line(text: string): void {+ console.log(text);+ }+}++/** Wall-clock time; a test replaces it with a frozen one. */+@Component()+export class SystemClock implements Clock {+ now(): Date {+ return new Date();+ }+}++/** The data root, read off the config. */+@Component()+export class ConfigPaths implements Paths {+ @Use() private readonly config!: Config;+ get root(): string {+ return this.config.root;+ }+}diff --git a/packages/server/src/hmr/platform.ts b/packages/server/src/hmr/platform.tsindex da12907b..ae2e298d 100644--- a/packages/server/src/hmr/platform.ts+++ b/packages/server/src/hmr/platform.ts@@ -46,7 +46,6 @@ import { identityFrom } from "../terminal/identity.js";import { bindTerminalStream } from "../terminal/stream.js";import { Hono } from "hono";import type { AppEnv } from "../auth/middleware.js";-import type { AuthService } from "../auth/service.js";import type { SessionManager } from "../runtime/session-manager.js";import { terminalRoutes } from "../terminal/routes.js";import type { Identity } from "../terminal/identity.js";@@ -61,6 +60,8 @@ import {} from "./capabilities.js";import type { Interfaces, MembersOf } from "./capabilities.js";import { pluginHostFrom } from "../plugin/host.js";+import { migrate } from "../db/migrations.js";+import type { Auth } from "../mechanisms/identity.js";export interface PlatformApi extends Park {info(): Json;@@ -230,6 +231,12 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {);}const caps = claim.kind === "claimed" ? claim.caps : null;+ // A pushed platform carries its own migrations, which is the only way the tables its+ // business needs can reach a runtime older than they are — that runtime will never grow+ // them by restarting, because it does not have them. swapPath: this boot can be rolled+ // back, so a restart-only migration is refused here instead of being left behind. Before+ // any node is created: every repo below prepares its statements against this schema.+ if (caps !== null) migrate(caps.db, { swapPath: true });// Resource-interface reconciliation, BEFORE anything is adopted: integrate the groups// the predecessor declared at the version this build also declares, hard-stop the// rest — a version bump or a dropped group means this create() does not speak the@@ -271,7 +278,7 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {console.warn("[platform] bare kernel: terminals only, no business surface");terminals = new TerminalManager(ctx.resources, { assets: () => null });terminals.adopt(adoptable("TerminalModule") ? (context.terminals ?? []) : []);- tree = await bootModules(bareTree([...plugins.modules()]), {+ tree = await bootModules(bareTree([...plugins.modules()], plugins.replacements()), {ifaces: plugins.ifaces(ifaceTable as unknown as IfaceTable),resources: ctx.resources,parked: parkedModules(context),@@ -281,19 +288,22 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {// group and the terminal manager are modules wired by their manifests — checked as// data before any create() runs, created in dependency order. Sandbox backends the// plugin host registered enter the same tree as one contributing module.- tree = await bootModules(platformDef(caps, adoptable, [...plugins.modules()]), {- ifaces: plugins.ifaces(ifaceTable as unknown as IfaceTable),- resources: ctx.resources,- parked: parkedModules(context),- });+ tree = await bootModules(+ platformDef(caps, adoptable, [...plugins.modules()], plugins.replacements()),+ {+ ifaces: plugins.ifaces(ifaceTable as unknown as IfaceTable),+ resources: ctx.resources,+ parked: parkedModules(context),+ },+ );business = tree;terminals = tree.api<TerminalManager>("TerminalModule", "terminals");}// Ordinary code over this App's own auth: the same object the business routes// authenticate with. A bare kernel has none — terminals stay fail-closed.- const auth = business?.api<AuthService>("AuthService", "AuthService") ?? null;+ const auth = business?.api<Auth>("IdentityModule", "Auth") ?? null;const identity = identityFrom(auth);- const manager = business?.api<SessionManager>("SessionsModule", "manager") ?? null;+ const manager = business?.api<SessionManager>("SessionRuntimeModule", "Sessions") ?? null;// The runtime's one mid-request need of the CURRENT App is a hook installed over a// claimed capability — overwrite-only across swaps, so a dead generation's hook is// replaced and never removed: "is this session busy" for the channel sweep.@@ -396,7 +406,10 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {};/** A bare kernel's tree: the sandbox floor and whatever contributes to it, nothing that needs a capability. */-function bareTree(plugins: ModuleDef[]): ModuleDef {+function bareTree(+ plugins: ModuleDef[],+ replace: ReadonlyMap<string, ModuleDef> = new Map(),+): ModuleDef {return {manifest: {name: "platform",@@ -406,7 +419,7 @@ function bareTree(plugins: ModuleDef[]): ModuleDef {children: ["SandboxModule", "*"],},children: [- moduleDefOf(SandboxModule, { manifests: ifaceTable.modules as ManifestTable }),+ moduleDefOf(SandboxModule, { manifests: ifaceTable.modules as ManifestTable, replace }),...plugins,],create: () => ({ api: {} }),diff --git a/packages/server/src/hmr/routes.ts b/packages/server/src/hmr/routes.tsindex 515f4de4..11532960 100644--- a/packages/server/src/hmr/routes.ts+++ b/packages/server/src/hmr/routes.ts@@ -20,20 +20,20 @@import zlib from "node:zlib";import { Hono } from "hono";import type { ServerConfig } from "../config.js";-import type { AuthService } from "../auth/service.js";import type { HmrHost } from "./host.js";import type { ChannelHub } from "../runtime/channel.js";/** What the hot-update routes reach: runtime capabilities and the current App's auth. */export interface HmrRouteDeps {hmr: HmrHost;- authService: AuthService;+ authService: Auth;config: ServerConfig;channels: ChannelHub;}import { authMiddleware } from "../auth/middleware.js";import type { AppEnv } from "../auth/middleware.js";import { HttpError } from "../http/errors.js";+import type { Auth } from "../mechanisms/identity.js";/** Bind addresses considered safe by default; anything else needs HTTPS. */const LOOPBACK_HOSTS = new Set(["127.0.0.1", "::1", "localhost"]);diff --git a/packages/server/src/http/app.ts b/packages/server/src/http/app.tsindex bbb42166..25ab3bde 100644--- a/packages/server/src/http/app.ts+++ b/packages/server/src/http/app.ts@@ -2,18 +2,18 @@ import { Interface, Module, Provide, Use } from "@prismshadow/penguin-core/kerneimport type { Opaque, Slot, ClassCtx } from "@prismshadow/penguin-core/kernel";import { Hono } from "hono";import type { AppEnv } from "../auth/middleware.js";-import { Config, Log, RuntimeModule } from "../hmr/capabilities.js";+import { Config, Log } from "../hmr/capabilities.js";import type { MiddlewareHandler } from "hono";import { bodyLimit } from "hono/body-limit";import { authMiddleware, jsonOnlyWrites } from "../auth/middleware.js";-import type { AuthService } from "../auth/service.js";import { HttpError, handleError } from "./errors.js";import { attributedProjectId } from "./attribution.js";import { bodyLimitBytes } from "../services/attachment-limits.js";import { declined } from "../hmr/hono-seam.js";-import type { ErrorRecorder } from "../runtime/error-recorder.js";-import type { ProjectAccess } from "../services/project-access.js";-import type { ServerSettingsRepo } from "../db/repos/server-settings.js";+import type { Auth } from "../mechanisms/identity.js";+import type { Access } from "../mechanisms/projects.js";+import type { Errors } from "../mechanisms/observability.js";+import type { Settings } from "../mechanisms/settings.js";/** The assembled business surface: one request in, one response (or a decline) out. */export abstract class Http extends Interface<{@@ -42,12 +42,12 @@ const RUNTIME_PREFIXES = ["/api/auth", "/api/desktop", "/api/hmr"];*/@Module()export class HttpModule {- @Use(RuntimeModule) private readonly config!: Config;- @Use(RuntimeModule) private readonly log!: Log;- @Use() private readonly auth!: AuthService;- @Use() private readonly errors!: ErrorRecorder;- @Use() private readonly settings!: ServerSettingsRepo;- @Use() private readonly access!: ProjectAccess;+ @Use() private readonly config!: Config;+ @Use() private readonly log!: Log;+ @Use() private readonly auth!: Auth;+ @Use() private readonly errors!: Errors;+ @Use() private readonly settings!: Settings;+ @Use() private readonly access!: Access;@Provide() http!: Http;setup({ contributions }: ClassCtx) {const errors = this.errors;@@ -115,10 +115,21 @@ export class HttpModule {});declinedRuntime = true;}- if (!gated && r.auth === "user") {- // Protected routes: cookie -> auth_session -> user.- app.use("/api/*", authMiddleware(this.auth, this.config.trustProxy));- gated = true;+ if (r.auth === "user") {+ // Protected routes: cookie -> auth_session -> user. /api/* is gated once, ahead of+ // the first protected group. A protected group under another prefix — the machine+ // proxy at /server/ — is gated on its own prefix: the gate is what puts the user on+ // the context, and a handler reading it behind an ungated prefix would throw.+ if (!gated) {+ app.use("/api/*", authMiddleware(this.auth, this.config.trustProxy));+ gated = true;+ }+ if (!r.prefix.startsWith("/api")) {+ app.use(+ `${r.prefix.replace(/\/$/, "")}/*`,+ authMiddleware(this.auth, this.config.trustProxy),+ );+ }}app.route(r.prefix, r.app);}diff --git a/packages/server/src/http/attribution.ts b/packages/server/src/http/attribution.tsindex d0d7e755..079fc6a8 100644--- a/packages/server/src/http/attribution.ts+++ b/packages/server/src/http/attribution.ts@@ -4,9 +4,9 @@* it without dragging the runtime shell into its graph.*/import type { Context } from "hono";-import type { ProjectAccess } from "../services/project-access.js";import type { AppEnv } from "../auth/middleware.js";import type { UserRow } from "../db/repos/users.js";+import type { Access } from "../mechanisms/projects.js";/*** The Project an error is attributed to: only@@ -32,7 +32,7 @@ import type { UserRow } from "../db/repos/users.js";*/export function attributedProjectId(c: Context<AppEnv>,- deps: { access: ProjectAccess },+ deps: { access: Access },): string | undefined {try {const projectId = c.req.param("projectId");diff --git a/packages/server/src/http/routes/admin-settings.ts b/packages/server/src/http/routes/admin-settings.tsindex 60797936..0782f7a1 100644--- a/packages/server/src/http/routes/admin-settings.ts+++ b/packages/server/src/http/routes/admin-settings.ts@@ -24,13 +24,12 @@ import type {import { HttpError } from "../errors.js";import type { AppEnv } from "../../auth/middleware.js";import { optionalBoolean, readJson } from "../validate.js";-import type { ServerSettingsRepo } from "../../db/repos/server-settings.js";import type { ProxyControl } from "../../hmr/capabilities.js";/** What this route group reaches — bound by its module (src/modules). */export interface AdminSettingsRouteDeps {proxyControl: ProxyControl;- serverSettingsRepo: ServerSettingsRepo;+ serverSettingsRepo: Settings;}import { applyProxySettings, normalizeProxyUrl } from "../../net/proxy.js";import { MAX_ATTACHMENT_MB, MIN_ATTACHMENT_MB } from "../../services/attachment-limits.js";@@ -39,6 +38,7 @@ import {probeProxyReachabilityOf,proxyProbeTarget,} from "../../services/proxy-probe.js";+import type { Settings } from "../../mechanisms/settings.js";/*** proxyUrl update value -> stored value: null and empty/whitespace-only clear thediff --git a/packages/server/src/http/routes/admin.ts b/packages/server/src/http/routes/admin.tsindex 6eb096ac..76bcfa01 100644--- a/packages/server/src/http/routes/admin.ts+++ b/packages/server/src/http/routes/admin.ts@@ -10,16 +10,16 @@ import { rejectInDesktopMode } from "./desktop.js";import type { DesktopService } from "../../services/desktop-service.js";import type { AppEnv } from "../../auth/middleware.js";import { pathParam, readJson, requireString } from "../validate.js";-import type { AdminService } from "../../services/admin-service.js";import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";import type { Desktop, Proxy } from "../../hmr/capabilities.js";-import type { ServerSettingsRepo } from "../../db/repos/server-settings.js";import { adminSettingsRoutes } from "./admin-settings.js";+import type { Admin } from "../../mechanisms/identity.js";+import type { Settings } from "../../mechanisms/settings.js";/** What this route group reaches — bound by its module (src/modules). */export interface AdminRouteDeps {desktop: DesktopService | null;- adminService: AdminService;+ adminService: Admin;}export function adminUsersRoutes(deps: AdminRouteDeps): Hono<AppEnv> {@@ -79,10 +79,10 @@ export function adminUsersRoutes(deps: AdminRouteDeps): Hono<AppEnv> {},})export class AdminRoutes {- @Use() private readonly admin!: AdminService;+ @Use() private readonly admin!: Admin;@Use() private readonly desktop!: Desktop;@Use() private readonly proxy!: Proxy;- @Use() private readonly settings!: ServerSettingsRepo;+ @Use() private readonly settings!: Settings;@Bind("admin-api.users") usersRoutes!: Hono<AppEnv>;@Bind("admin-api.settings") settingsRoutes!: Hono<AppEnv>;setup() {diff --git a/packages/server/src/http/routes/agent-config.ts b/packages/server/src/http/routes/agent-config.tsindex 2e838a33..ef764c88 100644--- a/packages/server/src/http/routes/agent-config.ts+++ b/packages/server/src/http/routes/agent-config.ts@@ -21,14 +21,14 @@ import type {import type { AppEnv } from "../../auth/middleware.js";import { badRequest, optionalString, readJson, requireValidId } from "../validate.js";import type { SessionManager } from "../../runtime/session-manager.js";-import type { AgentConfigService } from "../../services/agent-config-service.js";-import type { ProjectAccess } from "../../services/project-access.js";+import type { AgentConfig } from "../../mechanisms/agents.js";+import type { Access } from "../../mechanisms/projects.js";/** What this route group reaches — bound by its module (src/modules). */export interface AgentConfigRouteDeps {- agentConfigService: AgentConfigService;+ agentConfigService: AgentConfig;manager: SessionManager;- access: ProjectAccess;+ access: Access;}/** Ceiling on a single mcp-test probe's connect budget (an entry may configure minutes). */diff --git a/packages/server/src/http/routes/agent-traces.ts b/packages/server/src/http/routes/agent-traces.tsindex d8bfe115..9da4a318 100644--- a/packages/server/src/http/routes/agent-traces.ts+++ b/packages/server/src/http/routes/agent-traces.ts@@ -33,15 +33,15 @@ import {requireString,requireValidId,} from "../validate.js";-import type { AgentConfigService } from "../../services/agent-config-service.js";-import type { ProjectAccess } from "../../services/project-access.js";-import type { TraceService } from "../../services/trace-service.js";+import type { AgentConfig } from "../../mechanisms/agents.js";+import type { Traces } from "../../mechanisms/traces.js";+import type { Access } from "../../mechanisms/projects.js";/** What this route group reaches — bound by its module (src/modules). */export interface AgentTracesRouteDeps {- agentConfigService: AgentConfigService;- access: ProjectAccess;- traceService: TraceService;+ agentConfigService: AgentConfig;+ access: Access;+ traceService: Traces;}/** Import file size cap: aligned with the snapshot import (stays within the 20MB body limit after base64). */diff --git a/packages/server/src/http/routes/agent-transfer.ts b/packages/server/src/http/routes/agent-transfer.tsindex e51d728f..ba942b21 100644--- a/packages/server/src/http/routes/agent-transfer.ts+++ b/packages/server/src/http/routes/agent-transfer.ts@@ -7,17 +7,16 @@ import fs from "node:fs/promises";import { Hono } from "hono";import type { AgentImportResponse } from "../../api/types.js";import type { AppEnv } from "../../auth/middleware.js";-import type { AgentConfigService } from "../../services/agent-config-service.js";-import type { ProjectAccess } from "../../services/project-access.js";-import type { SnapshotService } from "../../services/snapshot-service.js";/** What this route group reaches — bound by its module (src/modules). */export interface AgentTransferRouteDeps {- agentConfigService: AgentConfigService;- access: ProjectAccess;- snapshots: SnapshotService;+ agentConfigService: AgentConfig;+ access: Access;+ snapshots: Snapshots;}import { badRequest, readJson, requireString, requireValidId } from "../validate.js";+import type { AgentConfig, Snapshots } from "../../mechanisms/agents.js";+import type { Access } from "../../mechanisms/projects.js";/** Import archive size cap: aligned with the global request body limit (stays within 20MB after base64). */const MAX_ARCHIVE_BYTES = 14 * 1024 * 1024;diff --git a/packages/server/src/http/routes/agents.ts b/packages/server/src/http/routes/agents.tsindex 652afca8..1bf21ddc 100644--- a/packages/server/src/http/routes/agents.ts+++ b/packages/server/src/http/routes/agents.ts@@ -18,27 +18,25 @@ import {requireValidId,} from "../validate.js";import { readArchiveBase64 } from "./agent-transfer.js";-import type { ErrorsRepo } from "../../db/repos/errors.js";-import type { SchedulesRepo } from "../../db/repos/schedules.js";-import type { SessionsRepo } from "../../db/repos/sessions.js";import type { SessionManager } from "../../runtime/session-manager.js";-import type { AgentConfigService } from "../../services/agent-config-service.js";-import type { AgentService } from "../../services/agent-service.js";-import type { ProjectAccess } from "../../services/project-access.js";import type { SessionService } from "../../services/session-service.js";-import type { TraceIndexService } from "../../services/trace-index.js";+import type { AgentConfig, AgentLifecycle } from "../../mechanisms/agents.js";+import type { TraceIndex } from "../../mechanisms/traces.js";+import type { ErrorLog } from "../../mechanisms/observability.js";+import type { Schedules, SessionIndex } from "../../mechanisms/sessions.js";+import type { Access } from "../../mechanisms/projects.js";/** What this route group reaches — bound by its module (src/modules). */export interface AgentsRouteDeps {- agentConfigService: AgentConfigService;- agentService: AgentService;- errorsRepo: ErrorsRepo;+ agentConfigService: AgentConfig;+ agentService: AgentLifecycle;+ errorsRepo: ErrorLog;manager: SessionManager;- access: ProjectAccess;- schedulesRepo: SchedulesRepo;+ access: Access;+ schedulesRepo: Schedules;sessionService: SessionService;- sessionsRepo: SessionsRepo;- traceIndex: TraceIndexService;+ sessionsRepo: SessionIndex;+ traceIndex: TraceIndex;}/** Window size in days for the card's activity sparkline (last 30 days, including today). */diff --git a/packages/server/src/http/routes/auth.ts b/packages/server/src/http/routes/auth.tsindex 078f176c..e14215bc 100644--- a/packages/server/src/http/routes/auth.ts+++ b/packages/server/src/http/routes/auth.ts@@ -12,13 +12,13 @@ import type { AuthResponse } from "../../api/types.js";import { SESSION_COOKIE, cookieOptions } from "../../auth/middleware.js";import type { AppEnv } from "../../auth/middleware.js";import { readJson, requireString } from "../validate.js";-import type { AuthService } from "../../auth/service.js";import type { ServerConfig } from "../../config.js";import type { DesktopService } from "../../services/desktop-service.js";+import type { Auth } from "../../mechanisms/identity.js";/** What this route group reaches — bound by its module (src/modules). */export interface AuthRouteDeps {- authService: AuthService;+ authService: Auth;config: ServerConfig;desktop: DesktopService | null;}diff --git a/packages/server/src/http/routes/benchmarks.ts b/packages/server/src/http/routes/benchmarks.tsindex d6198baf..2dbd8db3 100644--- a/packages/server/src/http/routes/benchmarks.ts+++ b/packages/server/src/http/routes/benchmarks.ts@@ -16,8 +16,9 @@ import { Hono, type Context } from "hono";import { isValidId } from "@prismshadow/penguin-core";import type { AppEnv } from "../../auth/middleware.js";import type { BenchmarkCreateResponse, CaseMaterial } from "../../api/types.js";-import type { BenchmarkCaseInput, BenchmarkService } from "../../services/benchmark-service.js";-import type { ProjectAccess } from "../../services/project-access.js";+import type { BenchmarkCaseInput } from "../../services/benchmark-service.js";+import type { Benchmarks } from "../../mechanisms/agents.js";+import type { Access } from "../../mechanisms/projects.js";import {badRequest,optionalNumber,@@ -29,8 +30,8 @@ import {/** What this route group reaches — bound by its module (src/modules). */export interface BenchmarksRouteDeps {- benchmarks: BenchmarkService;- access: ProjectAccess;+ benchmarks: Benchmarks;+ access: Access;}const TEXT_PREVIEW_BYTES = 256 * 1024;diff --git a/packages/server/src/http/routes/chat-defaults.ts b/packages/server/src/http/routes/chat-defaults.tsindex 63ef0977..6a037b48 100644--- a/packages/server/src/http/routes/chat-defaults.ts+++ b/packages/server/src/http/routes/chat-defaults.ts@@ -12,15 +12,14 @@ import type { AppEnv } from "../../auth/middleware.js";import { HttpError } from "../errors.js";import { optionalEnum, optionalString, readJson, requireValidId } from "../validate.js";import { APPROVAL_MODES } from "./sessions.js";-import type { AgentConfigService } from "../../services/agent-config-service.js";-import type { ProjectAccess } from "../../services/project-access.js";-import type { ProjectConfigService } from "../../services/project-config-service.js";+import type { AgentConfig } from "../../mechanisms/agents.js";+import type { Access, ProjectConfigStore } from "../../mechanisms/projects.js";/** What this route group reaches — bound by its module (src/modules). */export interface ChatDefaultsRouteDeps {- agentConfigService: AgentConfigService;- projectConfigService: ProjectConfigService;- access: ProjectAccess;+ agentConfigService: AgentConfig;+ projectConfigService: ProjectConfigStore;+ access: Access;}export function chatDefaultsRoutes(deps: ChatDefaultsRouteDeps): Hono<AppEnv> {diff --git a/packages/server/src/http/routes/command-policy.ts b/packages/server/src/http/routes/command-policy.tsindex fd862d5b..6ae4ee5b 100644--- a/packages/server/src/http/routes/command-policy.ts+++ b/packages/server/src/http/routes/command-policy.ts@@ -11,13 +11,12 @@ import { Hono } from "hono";import type { AppEnv } from "../../auth/middleware.js";import { HttpError } from "../errors.js";import { readJson, requireValidId } from "../validate.js";-import type { ProjectAccess } from "../../services/project-access.js";-import type { ProjectConfigService } from "../../services/project-config-service.js";+import type { Access, ProjectConfigStore } from "../../mechanisms/projects.js";/** What this route group reaches — bound by its module (src/modules). */export interface CommandPolicyRouteDeps {- projectConfigService: ProjectConfigService;- access: ProjectAccess;+ projectConfigService: ProjectConfigStore;+ access: Access;}/** Bounds for the rule list: enough for a serious deny list, small enough to stay a config file. */diff --git a/packages/server/src/http/routes/directory-skills.ts b/packages/server/src/http/routes/directory-skills.tsindex 9d44679a..06006c23 100644--- a/packages/server/src/http/routes/directory-skills.ts+++ b/packages/server/src/http/routes/directory-skills.ts@@ -17,14 +17,14 @@ import { Hono } from "hono";import type { DirectorySkillsResponse } from "../../api/types.js";import type { AppEnv } from "../../auth/middleware.js";import { requireProjectDir, requireValidId } from "../validate.js";-import type { ProjectAccess } from "../../services/project-access.js";/** What this route group reaches — bound by its module (src/modules). */export interface DirectorySkillsRouteDeps {- access: ProjectAccess;+ access: Access;}import { discoverDirectorySkills } from "../../services/directory-skills.js";import { toSkillItem } from "../../services/plugin-library.js";+import type { Access } from "../../mechanisms/projects.js";export function directorySkillsRoutes(deps: DirectorySkillsRouteDeps): Hono<AppEnv> {const app = new Hono<AppEnv>();diff --git a/packages/server/src/http/routes/dirs.ts b/packages/server/src/http/routes/dirs.tsindex 5948f49e..14722fd5 100644--- a/packages/server/src/http/routes/dirs.ts+++ b/packages/server/src/http/routes/dirs.ts@@ -17,13 +17,13 @@ import { Hono } from "hono";import type { DirListResponse } from "../../api/types.js";import type { AppEnv } from "../../auth/middleware.js";import { requireProjectDir, requireValidId } from "../validate.js";-import type { ProjectAccess } from "../../services/project-access.js";import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";import { directorySkillsRoutes } from "./directory-skills.js";+import type { Access } from "../../mechanisms/projects.js";/** What this route group reaches — bound by its module (src/modules). */export interface DirsRouteDeps {- access: ProjectAccess;+ access: Access;}export function dirsRoutes(deps: DirsRouteDeps): Hono<AppEnv> {@@ -80,7 +80,7 @@ export function dirsRoutes(deps: DirsRouteDeps): Hono<AppEnv> {},})export class ProjectsRoutes {- @Use() private readonly access!: ProjectAccess;+ @Use() private readonly access!: Access;@Bind("projects.dirs") dirsRoutes!: Hono<AppEnv>;@Bind("projects.dir-skills") dirSkillsRoutes!: Hono<AppEnv>;setup() {diff --git a/packages/server/src/http/routes/events.ts b/packages/server/src/http/routes/events.tsindex 44d9820d..f07297bb 100644--- a/packages/server/src/http/routes/events.ts+++ b/packages/server/src/http/routes/events.ts@@ -8,7 +8,7 @@ import { sseEndpoint } from "../sse.js";import type { ChannelHub } from "../../runtime/channel.js";import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";import type { ClassCtx } from "@prismshadow/penguin-core/kernel";-import { Channels, RuntimeModule } from "../../hmr/capabilities.js";+import { Channels } from "../../hmr/capabilities.js";/** What this route group reaches — bound by its module (src/modules). */export interface EventsRouteDeps {@@ -44,7 +44,7 @@ export function eventsRoutes(deps: EventsRouteDeps): Hono<AppEnv> {},})export class EventsRoutes {- @Use(RuntimeModule) private readonly channels!: Channels;+ @Use() private readonly channels!: Channels;@Bind("EventsRoutes.routes") routes!: Hono<AppEnv>;setup() {this.routes = eventsRoutes({ channels: this.channels as ChannelHub });diff --git a/packages/server/src/http/routes/install.ts b/packages/server/src/http/routes/install.tsindex 69daa331..ccefca5b 100644--- a/packages/server/src/http/routes/install.ts+++ b/packages/server/src/http/routes/install.ts@@ -31,7 +31,7 @@ export interface InstallRouteDeps {import { ensureInstallId } from "../../install-id.js";import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";import type { ClassCtx } from "@prismshadow/penguin-core/kernel";-import { Config, RuntimeModule } from "../../hmr/capabilities.js";+import { Config } from "../../hmr/capabilities.js";export function installRoutes(deps: InstallRouteDeps): Hono<AppEnv> {const app = new Hono<AppEnv>();@@ -61,7 +61,7 @@ export function installRoutes(deps: InstallRouteDeps): Hono<AppEnv> {},})export class InstallRoutes {- @Use(RuntimeModule) private readonly config!: Config;+ @Use() private readonly config!: Config;@Bind("InstallRoutes.routes") routes!: Hono<AppEnv>;setup() {this.routes = installRoutes({ config: this.config });diff --git a/packages/server/src/http/routes/machines.ts b/packages/server/src/http/routes/machines.tsindex 8c9b627f..261f09e7 100644--- a/packages/server/src/http/routes/machines.ts+++ b/packages/server/src/http/routes/machines.ts@@ -30,12 +30,12 @@ import { HttpError } from "../errors.js";import { requireValidId } from "../validate.js";import type { AppEnv } from "../../auth/middleware.js";import type { MachinesService } from "../../machines/service.js";-import type { ProjectAccess } from "../../services/project-access.js";+import type { Access } from "../../mechanisms/projects.js";/** What this route group reaches — bound by its module (src/modules). */export interface MachinesRouteDeps {machines: MachinesService;- access: ProjectAccess;+ access: Access;}export function machinesRoutes(deps: MachinesRouteDeps): Hono<AppEnv> {diff --git a/packages/server/src/http/routes/me.ts b/packages/server/src/http/routes/me.tsindex 6b6323df..02694040 100644--- a/packages/server/src/http/routes/me.ts+++ b/packages/server/src/http/routes/me.ts@@ -25,22 +25,18 @@ import { SESSION_COOKIE, cookieOptions } from "../../auth/middleware.js";import type { AppEnv } from "../../auth/middleware.js";import { badRequest, readJson, requireString } from "../validate.js";import { HttpError } from "../errors.js";-import type { AuthService } from "../../auth/service.js";import type { ServerConfig } from "../../config.js";-import type { ServerSettingsRepo } from "../../db/repos/server-settings.js";-import type { UiPrefsRepo } from "../../db/repos/ui-prefs.js";-import type { UsersRepo } from "../../db/repos/users.js";import type { DesktopService } from "../../services/desktop-service.js";/** What this route group reaches — bound by its module (src/modules). */export interface MeRouteDeps {- authService: AuthService;+ authService: Auth;config: ServerConfig;desktop: DesktopService | null;- prefsRepo: UiPrefsRepo;- serverSettingsRepo: ServerSettingsRepo;+ prefsRepo: UiPrefsStore;+ serverSettingsRepo: Settings;/** The `users` table itself, for the one route that writes a column no service owns (PUT /api/me/profile). */- usersRepo: UsersRepo;+ usersRepo: Users;}import { resolvePreviewTarget } from "../../services/preview-token.js";import { validateDraftShortcuts } from "../../services/draft-shortcuts.js";@@ -52,7 +48,9 @@ import {} from "../../services/attachment-limits.js";import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";import type { ClassCtx } from "@prismshadow/penguin-core/kernel";-import { Config, Desktop, RuntimeModule } from "../../hmr/capabilities.js";+import { Config, Desktop } from "../../hmr/capabilities.js";+import type { Auth, Users } from "../../mechanisms/identity.js";+import type { Settings, UiPrefsStore } from "../../mechanisms/settings.js";/** Nickname bounds, counted in user-perceived code points so a CJK name is 32 characters, not 96. */const DISPLAY_NAME_MIN = 1;@@ -265,12 +263,12 @@ export function meRoutes(deps: MeRouteDeps): Hono<AppEnv> {},})export class MeRoutes {- @Use(RuntimeModule) private readonly config!: Config;- @Use(RuntimeModule) private readonly desktop!: Desktop;- @Use() private readonly auth!: AuthService;- @Use() private readonly prefs!: UiPrefsRepo;- @Use() private readonly settings!: ServerSettingsRepo;- @Use() private readonly users!: UsersRepo;+ @Use() private readonly config!: Config;+ @Use() private readonly desktop!: Desktop;+ @Use() private readonly auth!: Auth;+ @Use() private readonly prefs!: UiPrefsStore;+ @Use() private readonly settings!: Settings;+ @Use() private readonly users!: Users;@Bind("MeRoutes.routes") routes!: Hono<AppEnv>;setup() {this.routes = meRoutes({diff --git a/packages/server/src/http/routes/members.ts b/packages/server/src/http/routes/members.tsindex c92ff0eb..a2bc7e61 100644--- a/packages/server/src/http/routes/members.ts+++ b/packages/server/src/http/routes/members.ts@@ -10,12 +10,12 @@ import type { AppEnv } from "../../auth/middleware.js";import { rejectInDesktopMode } from "./desktop.js";import type { DesktopService } from "../../services/desktop-service.js";import { pathParam, readJson, requireString, requireValidId } from "../validate.js";-import type { ProjectService } from "../../services/project-service.js";+import type { ProjectLifecycle } from "../../mechanisms/projects.js";/** What this route group reaches — bound by its module (src/modules). */export interface MembersRouteDeps {desktop: DesktopService | null;- projectService: ProjectService;+ projectService: ProjectLifecycle;}export function membersRoutes(deps: MembersRouteDeps): Hono<AppEnv> {diff --git a/packages/server/src/http/routes/memory.ts b/packages/server/src/http/routes/memory.tsindex f02d5615..9284f088 100644--- a/packages/server/src/http/routes/memory.ts+++ b/packages/server/src/http/routes/memory.ts@@ -24,17 +24,16 @@import { Hono } from "hono";import type { Context } from "hono";import type { AppEnv } from "../../auth/middleware.js";-import type { ProjectAccess } from "../../services/project-access.js";--import type { MemoryService } from "../../services/memory-service.js";/** What this route group reaches — bound by its module (src/modules). */export interface MemoryRouteDeps {- memoryService: MemoryService;- access: ProjectAccess;+ memoryService: Memory;+ access: Access;}import type { MemoryImportMode } from "../../api/types.js";import { optionalBoolean, optionalEnum, pathParam, readJson, requireValidId } from "../validate.js";+import type { Memory } from "../../mechanisms/agents.js";+import type { Access } from "../../mechanisms/projects.js";const IMPORT_MODES: readonly MemoryImportMode[] = ["skip", "overwrite", "replace"];diff --git a/packages/server/src/http/routes/messaging.ts b/packages/server/src/http/routes/messaging.tsindex 9e258d0a..b4dd0658 100644--- a/packages/server/src/http/routes/messaging.ts+++ b/packages/server/src/http/routes/messaging.ts@@ -72,11 +72,8 @@ import type {WeChatTestResponse,} from "../../api/types.js";import type { AppEnv } from "../../auth/middleware.js";-import type {- MessagingBindingRow,- MessagingBindingsRepo,-} from "../../db/repos/messaging-bindings.js";-import type { SessionRow, SessionsRepo } from "../../db/repos/sessions.js";+import type { MessagingBindingRow } from "../../db/repos/messaging-bindings.js";+import type { SessionRow } from "../../db/repos/sessions.js";import { FEISHU_DEFAULT_DOMAIN, feishuConfigOf } from "../../runtime/messaging/feishu-connector.js";import { telegramBotIdOf } from "../../runtime/messaging/telegram-connector.js";import { maskApiKey } from "../../services/project-config-service.js";@@ -96,19 +93,21 @@ import {} from "./messaging-channels.js";import type { MessagingChannelSpec } from "./messaging-channels.js";import type { MessagingChannel } from "../../runtime/messaging/connector.js";+import type { WeChatScanService } from "../../runtime/messaging/wechat-scan.js";import type { MessagingBridge } from "../../runtime/messaging/bridge.js";import type { QQScanService } from "../../runtime/messaging/qq-scan.js";-import type { WeChatScanService } from "../../runtime/messaging/wechat-scan.js";-import type { ProjectAccess } from "../../services/project-access.js";+import type { MessagingBindings } from "../../mechanisms/messaging.js";+import type { SessionIndex } from "../../mechanisms/sessions.js";+import type { Access } from "../../mechanisms/projects.js";/** What this route group reaches — bound by its module (src/modules). */export interface MessagingRouteDeps {messaging: MessagingBridge;- messagingRepo: MessagingBindingsRepo;- access: ProjectAccess;+ messagingRepo: MessagingBindings;+ access: Access;qqScan: QQScanService;wechatScan: WeChatScanService;- sessionsRepo: SessionsRepo;+ sessionsRepo: SessionIndex;}/** The stored feishu config, tolerated loosely (a malformed document reads as blanks). */diff --git a/packages/server/src/http/routes/model-oauth.ts b/packages/server/src/http/routes/model-oauth.tsindex 5771a692..48598e6e 100644--- a/packages/server/src/http/routes/model-oauth.ts+++ b/packages/server/src/http/routes/model-oauth.ts@@ -24,20 +24,19 @@ import type {import type { AppEnv } from "../../auth/middleware.js";import type { ServerConfig } from "../../config.js";import type { SessionManager } from "../../runtime/session-manager.js";-import type { ModelOAuthService } from "../../services/model-oauth-service.js";-import type { ProjectAccess } from "../../services/project-access.js";/** What this route group reaches — bound by its module (src/modules). */export interface ModelOauthRouteDeps extends ModelsRouteDeps {config: ServerConfig;manager: SessionManager;- modelOAuth: ModelOAuthService;- access: ProjectAccess;+ modelOAuth: ModelOAuth;+ access: Access;}import { HttpError } from "../errors.js";import { badRequest, readJson, requireString, requireValidId } from "../validate.js";import { modelConfigChanged } from "./models.js";import type { ModelsRouteDeps } from "./models.js";+import type { Access, ModelOAuth } from "../../mechanisms/projects.js";/** Flow ids are base64url (`randomBytes(32)`); reject anything else before it reaches the store. */const FLOW_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;diff --git a/packages/server/src/http/routes/models.ts b/packages/server/src/http/routes/models.tsindex ff202cac..fe39d327 100644--- a/packages/server/src/http/routes/models.ts+++ b/packages/server/src/http/routes/models.ts@@ -22,12 +22,11 @@ import type {import type { AppEnv } from "../../auth/middleware.js";import { badRequest, readJson, requireString, requireValidId } from "../validate.js";import { isHttpUrl } from "../../services/protocol-detect.js";-import type { SessionsRepo } from "../../db/repos/sessions.js";import type { ChannelHub } from "../../runtime/channel.js";import type { SessionManager } from "../../runtime/session-manager.js";-import type { ProjectAccess } from "../../services/project-access.js";+import type { SessionIndex } from "../../mechanisms/sessions.js";+import type { Access, ProjectConfigStore } from "../../mechanisms/projects.js";import type { Machines } from "../../machines/service.js";-import type { ProjectConfigService } from "../../services/project-config-service.js";/** What this route group reaches — bound by its module (src/modules). */export interface ModelsRouteDeps {@@ -35,9 +34,9 @@ export interface ModelsRouteDeps {machines: Machines;channels: ChannelHub;manager: SessionManager;- projectConfigService: ProjectConfigService;- access: ProjectAccess;- sessionsRepo: SessionsRepo;+ projectConfigService: ProjectConfigStore;+ access: Access;+ sessionsRepo: SessionIndex;}/**diff --git a/packages/server/src/http/routes/plugins.ts b/packages/server/src/http/routes/plugins.tsindex 1e626cb7..9524c7bf 100644--- a/packages/server/src/http/routes/plugins.ts+++ b/packages/server/src/http/routes/plugins.ts@@ -24,17 +24,17 @@ import type {import type { AppEnv } from "../../auth/middleware.js";import type { ServerConfig } from "../../config.js";import type { Config } from "../../hmr/capabilities.js";-import type { AgentConfigService } from "../../services/agent-config-service.js";-import type { ProjectAccess } from "../../services/project-access.js";-import { Sessions as ManagerIface, SessionsModule } from "../../runtime/session-manager.js";+import type { AgentConfig } from "../../mechanisms/agents.js";+import type { Access } from "../../mechanisms/projects.js";+import type { Sessions as ManagerIface } from "../../runtime/session-manager.js";import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";import { agentHooksRoutes } from "./hooks.js";/** What these route groups reach — bound by their component below. */export interface PluginsRouteDeps {config: ServerConfig;- access: ProjectAccess;- agentConfigService: AgentConfigService;+ access: Access;+ agentConfigService: AgentConfig;manager: ManagerIface;}import { HttpError } from "../errors.js";@@ -135,9 +135,9 @@ export function agentPluginsRoutes(deps: PluginsRouteDeps): Hono<AppEnv> {})export class PluginRoutes {@Use() private readonly config!: Config;- @Use() private readonly access!: ProjectAccess;- @Use() private readonly agentConfig!: AgentConfigService;- @Use(SessionsModule) private readonly manager!: ManagerIface;+ @Use() private readonly access!: Access;+ @Use() private readonly agentConfig!: AgentConfig;+ @Use() private readonly manager!: ManagerIface;@Bind("PluginRoutes.library") libraryRoutes!: Hono<AppEnv>;@Bind("PluginRoutes.agent-plugins") pluginRoutes!: Hono<AppEnv>;@Bind("PluginRoutes.agent-hooks") hookRoutes!: Hono<AppEnv>;diff --git a/packages/server/src/http/routes/preview.ts b/packages/server/src/http/routes/preview.tsindex 92b4ec85..98cafcfa 100644--- a/packages/server/src/http/routes/preview.ts+++ b/packages/server/src/http/routes/preview.ts@@ -14,8 +14,6 @@* would be a same-origin XSS with full API access.*/import { Hono } from "hono";-import type { SessionsRepo } from "../../db/repos/sessions.js";-import { WorkspaceFilesService } from "../../services/workspace-files-service.js";import type { PreviewTokenSigner } from "../../services/preview-token.js";import {hostOnly,@@ -25,10 +23,12 @@ import {import { Interface, Bind, Module, Provide, Use } from "@prismshadow/penguin-core/kernel";import type { AppEnv } from "../../auth/middleware.js";import type { ClassCtx } from "@prismshadow/penguin-core/kernel";+import type { SessionIndex } from "../../mechanisms/sessions.js";+import type { WorkspaceFiles } from "../../mechanisms/workspace.js";export interface PreviewDeps {- sessionsRepo: SessionsRepo;- workspaceFiles: WorkspaceFilesService;+ sessionsRepo: SessionIndex;+ workspaceFiles: WorkspaceFiles;previewTokens: PreviewTokenSigner;}@@ -91,9 +91,6 @@ export function previewRoutes(deps: PreviewDeps) {return app;}-export abstract class WorkspaceFiles extends Interface<- Pick<WorkspaceFilesService, "list" | "read" | "write" | "statExisting">->() {}export abstract class PreviewTokens extends Interface<Pick<PreviewTokenSigner, "sign" | "verify">>() {}@@ -110,20 +107,18 @@ export abstract class PreviewTokens extends Interface<],},})-export class WorkspaceModule {- @Use() private readonly sessionsRepo!: SessionsRepo;- @Provide() workspaceFiles!: WorkspaceFiles;+export class PreviewModule {+ @Use() private readonly workspaceFiles!: WorkspaceFiles;+ @Use() private readonly sessionsRepo!: SessionIndex;@Provide() previewTokens!: PreviewTokens;@Bind("workspace.preview") previewRoutes!: ReturnType<typeof previewRoutes>;setup() {- const workspaceFiles = new WorkspaceFilesService();const previewTokens = createPreviewTokenSigner();- this.workspaceFiles = workspaceFiles;this.previewTokens = previewTokens;this.previewRoutes = previewRoutes({previewTokens,sessionsRepo: this.sessionsRepo,- workspaceFiles,+ workspaceFiles: this.workspaceFiles,});}}diff --git a/packages/server/src/http/routes/projects.ts b/packages/server/src/http/routes/projects.tsindex 9082dbe0..03bd0a90 100644--- a/packages/server/src/http/routes/projects.ts+++ b/packages/server/src/http/routes/projects.ts@@ -15,15 +15,15 @@ import {requireString,requireValidId,} from "../validate.js";-import type { ProjectService } from "../../services/project-service.js";import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";import type { Desktop } from "../../hmr/capabilities.js";import type { DesktopService } from "../../services/desktop-service.js";import { membersRoutes } from "./members.js";+import type { ProjectLifecycle } from "../../mechanisms/projects.js";/** What this route group reaches — bound by its module (src/modules). */export interface ProjectsRouteDeps {- projectService: ProjectService;+ projectService: ProjectLifecycle;}export function projectsRoutes(deps: ProjectsRouteDeps): Hono<AppEnv> {@@ -83,7 +83,7 @@ export function projectsRoutes(deps: ProjectsRouteDeps): Hono<AppEnv> {},})export class ProjectAdminRoutes {- @Use() private readonly projectService!: ProjectService;+ @Use() private readonly projectService!: ProjectLifecycle;@Use() private readonly desktop!: Desktop;@Bind("project-admin.projects") projectsRoutes!: Hono<AppEnv>;@Bind("project-admin.members") membersRoutes!: Hono<AppEnv>;diff --git a/packages/server/src/http/routes/schedules.ts b/packages/server/src/http/routes/schedules.tsindex 9c5240a2..e1cae9c7 100644--- a/packages/server/src/http/routes/schedules.ts+++ b/packages/server/src/http/routes/schedules.ts@@ -13,20 +13,15 @@ import { isValidId } from "@prismshadow/penguin-core";import type { ScheduleItem, ScheduleStatus, SchedulesResponse } from "../../api/types.js";import type { AppEnv } from "../../auth/middleware.js";import type { ServerConfig } from "../../config.js";-import type { SchedulesRepo, ScheduleStateRow } from "../../db/repos/schedules.js";-import type { Scheduler } from "../../runtime/scheduler.js";-import type { AgentConfigService } from "../../services/agent-config-service.js";-import type { ProjectAccess } from "../../services/project-access.js";-import type { ProjectConfigService } from "../../services/project-config-service.js";/** What this route group reaches — bound by its module (src/modules). */export interface SchedulesRouteDeps {- agentConfigService: AgentConfigService;+ agentConfigService: AgentConfig;config: ServerConfig;- projectConfigService: ProjectConfigService;- access: ProjectAccess;- scheduler: Scheduler;- schedulesRepo: SchedulesRepo;+ projectConfigService: ProjectConfigStore;+ access: Access;+ scheduler: Scheduling;+ schedulesRepo: Schedules;}import { HttpError } from "../errors.js";import {@@ -43,6 +38,7 @@ import {parseScheduleFile,slotInWindow,} from "../../runtime/schedule-file.js";+import type { ScheduleStateRow } from "../../db/repos/schedules.js";import {deleteScheduleFile,readScheduleFile,@@ -52,6 +48,9 @@ import {} from "../../runtime/schedule-store.js";import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";import type { Config } from "../../hmr/capabilities.js";+import type { Access, ProjectConfigStore } from "../../mechanisms/projects.js";+import type { Schedules, Scheduling } from "../../mechanisms/sessions.js";+import type { AgentConfig } from "../../mechanisms/agents.js";/** Validate and shape the POST/PUT request body into file fields (semantic validation is left to parseScheduleFile). */function parseUpsertBody(body: Record<string, unknown>): {@@ -290,11 +289,11 @@ async function readItem(})export class SchedulerRoutes {@Use() private readonly config!: Config;- @Use() private readonly agentConfig!: AgentConfigService;- @Use() private readonly projectConfig!: ProjectConfigService;- @Use() private readonly access!: ProjectAccess;- @Use() private readonly scheduler!: Scheduler;- @Use() private readonly schedulesRepo!: SchedulesRepo;+ @Use() private readonly agentConfig!: AgentConfig;+ @Use() private readonly projectConfig!: ProjectConfigStore;+ @Use() private readonly access!: Access;+ @Use() private readonly scheduler!: Scheduling;+ @Use() private readonly schedulesRepo!: Schedules;@Bind("SchedulerRoutes.routes") routes!: Hono<AppEnv>;setup() {this.routes = scheduleRoutes({diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.tsindex bb78ef70..38f81b8b 100644--- a/packages/server/src/http/routes/sessions.ts+++ b/packages/server/src/http/routes/sessions.ts@@ -42,10 +42,10 @@ import type {} from "../../api/types.js";import { compactionThresholdFor } from "../../services/context-breakdown.js";import { decodeCursor } from "../../services/message-window.js";-import type { MessagesPageRequest, TraceService } from "../../services/trace-service.js";+import type { MessagesPageRequest } from "../../services/trace-service.js";import { PREVIEW_TOKEN_TTL_MS, resolvePreviewTarget } from "../../services/preview-token.js";import type { AppEnv } from "../../auth/middleware.js";-import type { SessionRow, SessionsRepo } from "../../db/repos/sessions.js";+import type { SessionRow } from "../../db/repos/sessions.js";import { assertWorkspaceAllowed } from "../../services/workspace-guard.js";import { isGoalOutcome } from "../../runtime/goal-events.js";import { HttpError } from "../errors.js";@@ -64,35 +64,28 @@ import {requireValidId,} from "../validate.js";import type { ServerConfig } from "../../config.js";-import type { ServerSettingsRepo } from "../../db/repos/server-settings.js";import type { ChannelHub } from "../../runtime/channel.js";import type { MessagingBridge } from "../../runtime/messaging/bridge.js";import type { SessionManager, RecallStore } from "../../runtime/session-manager.js";-import type { SessionSources } from "../../runtime/session-sources.js";-import type { AgentConfigService } from "../../services/agent-config-service.js";import type { PreviewTokenSigner } from "../../services/preview-token.js";-import type { ProjectAccess } from "../../services/project-access.js";-import type { Machines } from "../../machines/service.js";-import type { ProjectConfigService } from "../../services/project-config-service.js";import type { SessionService } from "../../services/session-service.js";-import type { WorkspaceFilesService } from "../../services/workspace-files-service.js";/** What this route group reaches — bound by its module (src/modules). */export interface SessionsRouteDeps {- agentConfigService: AgentConfigService;+ agentConfigService: AgentConfig;channels: ChannelHub;config: ServerConfig;manager: SessionManager;messaging: MessagingBridge;previewTokens: PreviewTokenSigner;- projectConfigService: ProjectConfigService;- access: ProjectAccess;- serverSettingsRepo: ServerSettingsRepo;+ projectConfigService: ProjectConfigStore;+ access: Access;+ serverSettingsRepo: Settings;sessionService: SessionService;- sessionSources: SessionSources;- sessionsRepo: SessionsRepo;- traceService: TraceService;- workspaceFiles: WorkspaceFilesService;+ sessionSources: SessionOrigins;+ sessionsRepo: SessionIndex;+ traceService: Traces;+ workspaceFiles: WorkspaceFiles;}import { MAX_UPLOAD_BYTES } from "../../services/workspace-files-service.js";import {@@ -111,14 +104,10 @@ import {import type { AttachmentLimits } from "../../services/attachment-limits.js";import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";import type { ClassCtx } from "@prismshadow/penguin-core/kernel";-import { Channels, Config, RuntimeModule } from "../../hmr/capabilities.js";-import {- Sessions as ManagerIface,- SessionServiceIface,- SessionsModule,-} from "../../runtime/session-manager.js";-import { Messaging, MessagingModule } from "../../runtime/messaging/bridge.js";-import { WorkspaceModule, PreviewTokens } from "./preview.js";+import { Channels, Config } from "../../hmr/capabilities.js";+import { Sessions as ManagerIface, SessionServiceIface } from "../../runtime/session-manager.js";+import { Messaging } from "../../runtime/messaging/bridge.js";+import { agentsRoutes } from "./agents.js";import { agentConfigRoutes } from "./agent-config.js";import { vaultRoutes } from "./vault.js";@@ -127,12 +116,15 @@ import { modelOAuthCallbackRoutes, modelOAuthRoutes } from "./model-oauth.js";import { chatDefaultsRoutes } from "./chat-defaults.js";import { commandPolicyRoutes } from "./command-policy.js";import { usageRoutes } from "./usage.js";-import type { AgentService } from "../../services/agent-service.js";-import type { SchedulesRepo } from "../../db/repos/schedules.js";-import type { ModelOAuthService } from "../../services/model-oauth-service.js";-import type { TraceIndexService } from "../../services/trace-index.js";-import type { ErrorsRepo } from "../../db/repos/errors.js";-import type { UsageService } from "../../services/usage-service.js";+import { PreviewTokens } from "./preview.js";+import type { Access, ModelOAuth, ProjectConfigStore } from "../../mechanisms/projects.js";+import type { Schedules, SessionIndex, SessionOrigins } from "../../mechanisms/sessions.js";+import type { ErrorLog, UsageQueries } from "../../mechanisms/observability.js";+import type { TraceIndex, Traces } from "../../mechanisms/traces.js";+import type { WorkspaceFiles } from "../../mechanisms/workspace.js";+import type { Machines } from "../../machines/service.js";+import type { AgentConfig, AgentLifecycle } from "../../mechanisms/agents.js";+import type { Settings } from "../../mechanisms/settings.js";/** Max title length for manual renames: looser than the auto-generated 30-char limit, to accommodate users' own organizing conventions. */const SESSION_TITLE_MAX = 120;@@ -1609,27 +1601,27 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {},})export class SessionApiRoutes {- @Use(RuntimeModule) private readonly config!: Config;- @Use(RuntimeModule) private readonly channels!: Channels;- @Use(SessionsModule) private readonly manager!: ManagerIface;- @Use(SessionsModule) private readonly sessionService!: SessionServiceIface;- @Use() private readonly agentConfig!: AgentConfigService;- @Use() private readonly agents!: AgentService;- @Use(MessagingModule) private readonly messaging!: Messaging;- @Use() private readonly schedulesRepo!: SchedulesRepo;- @Use() private readonly access!: ProjectAccess;+ @Use() private readonly config!: Config;+ @Use() private readonly channels!: Channels;+ @Use() private readonly manager!: ManagerIface;@Use() private readonly machines!: Machines;- @Use() private readonly projectConfig!: ProjectConfigService;- @Use() private readonly modelOAuth!: ModelOAuthService;- @Use() private readonly traceIndex!: TraceIndexService;- @Use() private readonly traces!: TraceService;- @Use() private readonly workspaceFiles!: WorkspaceFilesService;- @Use(WorkspaceModule) private readonly previewTokens!: PreviewTokens;- @Use() private readonly settings!: ServerSettingsRepo;- @Use() private readonly sessionsRepo!: SessionsRepo;- @Use() private readonly sources!: SessionSources;- @Use() private readonly errorsRepo!: ErrorsRepo;- @Use() private readonly usage!: UsageService;+ @Use() private readonly sessionService!: SessionServiceIface;+ @Use() private readonly agentConfig!: AgentConfig;+ @Use() private readonly agents!: AgentLifecycle;+ @Use() private readonly messaging!: Messaging;+ @Use() private readonly schedulesRepo!: Schedules;+ @Use() private readonly access!: Access;+ @Use() private readonly projectConfig!: ProjectConfigStore;+ @Use() private readonly modelOAuth!: ModelOAuth;+ @Use() private readonly traceIndex!: TraceIndex;+ @Use() private readonly traces!: Traces;+ @Use() private readonly workspaceFiles!: WorkspaceFiles;+ @Use() private readonly previewTokens!: PreviewTokens;+ @Use() private readonly settings!: Settings;+ @Use() private readonly sessionsRepo!: SessionIndex;+ @Use() private readonly sources!: SessionOrigins;+ @Use() private readonly errorsRepo!: ErrorLog;+ @Use() private readonly usage!: UsageQueries;@Bind("session-api.model-oauth-callback") modelOauthCallbackRoutes!: Hono<AppEnv>;@Bind("session-api.models") modelsRoutes!: Hono<AppEnv>;@Bind("session-api.model-oauth") modelOauthRoutes!: Hono<AppEnv>;@@ -1670,16 +1662,16 @@ export class SessionApiRoutes {manager,modelOAuth: this.modelOAuth,access,- machines: this.machines,channels,+ machines: this.machines,projectConfigService,sessionsRepo,};this.modelOauthCallbackRoutes = modelOAuthCallbackRoutes(modelOAuthDeps);this.modelsRoutes = modelsRoutes({- machines: this.machines,channels,manager,+ machines: this.machines,projectConfigService,access,sessionsRepo,diff --git a/packages/server/src/http/routes/skills.ts b/packages/server/src/http/routes/skills.tsindex c5408e53..0a5f9c46 100644--- a/packages/server/src/http/routes/skills.ts+++ b/packages/server/src/http/routes/skills.ts@@ -27,14 +27,12 @@ import {import type { AgentSkillsResponse } from "../../api/types.js";import type { AppEnv } from "../../auth/middleware.js";import type { ServerConfig } from "../../config.js";-import type { AgentConfigService } from "../../services/agent-config-service.js";-import type { ProjectAccess } from "../../services/project-access.js";/** What this route group reaches — bound by its module (src/modules). */export interface SkillsRouteDeps {- agentConfigService: AgentConfigService;+ agentConfigService: AgentConfig;config: ServerConfig;- access: ProjectAccess;+ access: Access;}import { HttpError } from "../errors.js";import { badRequest, readJson, requireString, requireValidId } from "../validate.js";@@ -48,6 +46,8 @@ import {} from "../../services/skill-import-limits.js";import { Bind, Component } from "@prismshadow/penguin-core/kernel";import type { ClassCtx } from "@prismshadow/penguin-core/kernel";+import type { AgentConfig } from "../../mechanisms/agents.js";+import type { Access } from "../../mechanisms/projects.js";/** Decoded zip cap: aligned with the Agent snapshot import (stays within the 20MB body limit after base64). Shared with the hooks archive routes. */export const MAX_ARCHIVE_BYTES = 14 * 1024 * 1024;diff --git a/packages/server/src/http/routes/usage.ts b/packages/server/src/http/routes/usage.tsindex 26de7c37..3fd9c8ee 100644--- a/packages/server/src/http/routes/usage.ts+++ b/packages/server/src/http/routes/usage.ts@@ -23,13 +23,13 @@ import type {} from "../../api/types.js";import type { AppEnv } from "../../auth/middleware.js";import { badRequest, optionalDateParam, paginationQuery, requireValidId } from "../validate.js";-import type { ProjectAccess } from "../../services/project-access.js";-import type { UsageService } from "../../services/usage-service.js";+import type { UsageQueries } from "../../mechanisms/observability.js";+import type { Access } from "../../mechanisms/projects.js";/** What this route group reaches — bound by its module (src/modules). */export interface UsageRouteDeps {- access: ProjectAccess;- usageService: UsageService;+ access: Access;+ usageService: UsageQueries;}const GROUP_BYS: readonly UsageGroupBy[] = ["date", "agent", "model", "session"];diff --git a/packages/server/src/http/routes/vault.ts b/packages/server/src/http/routes/vault.tsindex b7a4033b..0aba6242 100644--- a/packages/server/src/http/routes/vault.ts+++ b/packages/server/src/http/routes/vault.ts@@ -10,14 +10,14 @@ import type { VaultEntryUpdate, VaultUpdateRequest } from "../../api/types.js";import type { AppEnv } from "../../auth/middleware.js";import { badRequest, readJson, requireString, requireValidId } from "../validate.js";import type { SessionManager } from "../../runtime/session-manager.js";-import type { AgentConfigService } from "../../services/agent-config-service.js";-import type { ProjectAccess } from "../../services/project-access.js";+import type { AgentConfig } from "../../mechanisms/agents.js";+import type { Access } from "../../mechanisms/projects.js";/** What this route group reaches — bound by its module (src/modules). */export interface VaultRouteDeps {- agentConfigService: AgentConfigService;+ agentConfigService: AgentConfig;manager: SessionManager;- access: ProjectAccess;+ access: Access;}/** Validate the PUT request body and shape it into a VaultUpdateRequest (semantic checks like key-name rules live in the service layer). */diff --git a/packages/server/src/http/routes/version.ts b/packages/server/src/http/routes/version.tsindex f192eea6..72679af1 100644--- a/packages/server/src/http/routes/version.ts+++ b/packages/server/src/http/routes/version.ts@@ -26,16 +26,16 @@ import type { RestartResponse, UpdateJobStatus, VersionResponse } from "../../apimport { HttpError } from "../errors.js";import type { AppEnv } from "../../auth/middleware.js";import type { ServerConfig } from "../../config.js";-import type { UpdateCheckService } from "../../services/update-check-service.js";-import type { UpdateJobService } from "../../services/update-job.js";+import type { UpdateCheck } from "../../services/update-check-service.js";+import type { UpdateJob } from "../../services/update-job.js";import type { Lifecycle } from "../../hmr/capabilities.js";/** What this route group reaches — bound by its module (src/modules). */export interface VersionRouteDeps {config: ServerConfig;- updateCheck: UpdateCheckService;+ updateCheck: UpdateCheck;/** The admin self-update run in the background (`penguin update --yes`), with its progress for the update modal. */- updateJob: UpdateJobService;+ updateJob: UpdateJob;/** Whether a supervisor relaunches this process, and the restart trigger the update flow pulls. */lifecycle: Lifecycle;}diff --git a/packages/server/src/index.ts b/packages/server/src/index.tsindex aa462a4b..035d048b 100644--- a/packages/server/src/index.ts+++ b/packages/server/src/index.ts@@ -22,9 +22,6 @@ import { serve } from "@hono/node-server";import { SERVER_RESTART_EXIT_CODE } from "@prismshadow/penguin-core";import { bootAppDeps, createRuntimeApp } from "./app.js";import type { ServerBoot } from "./app.js";-import type { AuthService } from "./auth/service.js";-import type { ServerSettingsRepo } from "./db/repos/server-settings.js";-import type { ErrorRecorder } from "./runtime/error-recorder.js";import { ADMIN_USER_ID } from "./auth/service.js";import { resolveServerConfig, type ServerConfig } from "./config.js";import { clearInitialAdminPassword, renderFirstLoginNotice } from "./initial-password.js";@@ -35,6 +32,9 @@ import { attachTerminalWebSocket } from "./terminal/ws.js";import { loopbackHostRoles } from "./services/preview-token.js";import { acquireServerLock, liveServerLock, releaseServerLock } from "./lock.js";import { shellPortOf, wireShellUpdatePort } from "./services/desktop-update-port.js";+import type { Settings } from "./mechanisms/settings.js";+import type { Errors } from "./mechanisms/observability.js";+import type { Auth } from "./mechanisms/identity.js";/*** The startup lifecycle: one line per step, in the order they have to happen.@@ -85,8 +85,8 @@ class PenguinServer {private shuttingDown = false;/** The current App's auth service — resolved per call, since a hot swap replaces the tree. */- private auth(): AuthService {- return this.deps.tree.api<AuthService>("AuthService", "AuthService");+ private auth(): Auth {+ return this.deps.tree.api<Auth>("IdentityModule", "Auth");}/** `.env` may itself define HTTP_PROXY, so it is loaded before the dispatcher reads one. */@@ -163,7 +163,7 @@ class PenguinServer {* plugin objects at all (see plugin/index.ts's pluginHostFrom).*/async buildDeps(): Promise<void> {- this.deps = await bootAppDeps(this.config, {}, this.plugins);+ this.deps = await bootAppDeps(this.config, [], this.plugins);}/**@@ -173,10 +173,7 @@ class PenguinServer {* handlers).*/applyPersistedProxy(): void {- const settings = this.deps.tree.api<ServerSettingsRepo>(- "ServerSettingsRepo",- "ServerSettingsRepo",- );+ const settings = this.deps.tree.api<Settings>("SettingsModule", "Settings");applyProxySettings({proxyForApp: settings.getProxyForApp(),proxyUrl: settings.getProxyUrl(),@@ -264,7 +261,7 @@ class PenguinServer {process.on("uncaughtException", (err) => {console.error(`[server] Uncaught exception: ${err.stack ?? err.message}`);this.deps.tree- .api<ErrorRecorder>("ErrorRecorder", "ErrorRecorder")+ .api<Errors>("ObservabilityModule", "Errors").record({ source: "process", err, code: "uncaught_exception" });// From this point the process state can't be trusted (the error was never converged// by any catch): don't swallow it — wrap up per existing shutdown semantics and exit@@ -278,7 +275,7 @@ class PenguinServer {const err = reason instanceof Error ? reason : new Error(String(reason));console.error(`[server] Unhandled promise rejection: ${err.stack ?? err.message}`);this.deps.tree- .api<ErrorRecorder>("ErrorRecorder", "ErrorRecorder")+ .api<Errors>("ObservabilityModule", "Errors").record({ source: "process", err, code: "unhandled_rejection" });// Unlike uncaughtException, this **doesn't** exit: a rejected promise is a localized// failure of some background task, and the process state isn't compromised; draggingdiff --git a/packages/server/src/machines/service.ts b/packages/server/src/machines/service.tsindex 1988cf99..9de627f3 100644--- a/packages/server/src/machines/service.ts+++ b/packages/server/src/machines/service.ts@@ -60,14 +60,14 @@ import type { MachineRow } from "../db/repos/machines.js";import { Interface, Bind, Module, Provide, Use } from "@prismshadow/penguin-core/kernel";import type { AppEnv } from "../auth/middleware.js";import type { ClassCtx } from "@prismshadow/penguin-core/kernel";-import { Config, Hmr, Overrides, RuntimeModule, Db } from "../hmr/capabilities.js";import { machinesRoutes } from "../http/routes/machines.js";import { machinesProxy } from "./proxy.js";import { HttpError } from "../http/errors.js";-import type { ProjectAccess } from "../services/project-access.js";+import type { Access } from "../mechanisms/projects.js";import { Hono } from "hono";import { MachinesRepo } from "../db/repos/machines.js";import type { DatabaseSync } from "node:sqlite";+import type { Db, Hmr, Paths } from "../hmr/capabilities.js";/** Why an install was refused before any ssh ran. */type InstallRefusal = "busy" | "unknown-machine" | "no-image" | "self";@@ -1159,11 +1159,10 @@ export abstract class Machines extends Interface<},})export class MachinesModule {- @Use(RuntimeModule) private readonly config!: Config;- @Use(RuntimeModule) private readonly db!: Db;- @Use(RuntimeModule) private readonly hmr!: Hmr;- @Use(RuntimeModule) private readonly overrides!: Overrides;- @Use() private readonly access!: ProjectAccess;+ @Use() private readonly paths!: Paths;+ @Use() private readonly db!: Db;+ @Use() private readonly hmr!: Hmr;+ @Use() private readonly access!: Access;@Provide() machines!: Machines;@Bind("MachinesModule.routes") routes!: Hono<AppEnv>;@Bind("MachinesModule.server-proxy") serverProxyRoutes!: Hono<AppEnv>;@@ -1171,17 +1170,13 @@ export class MachinesModule {// This machine's own id is minted on the first boot of this data root and stable ever// after — every stored reference to this machine, here and on the machines it reaches,// points at it. A test that supplies its own service mints none.- const machines =- this.overrides.value().machines ??- (() => {- const repo = new MachinesRepo(this.db as unknown as DatabaseSync);- return new MachinesService(this.config.root, repo.ownId(), repo, {}, () =>- this.hmr.assetsDir(),- );- })();+ const repo = new MachinesRepo(this.db as unknown as DatabaseSync);+ const machines = new MachinesService(this.paths.root, repo.ownId(), repo, {}, () =>+ this.hmr.assetsDir(),+ );this.machines = machines;this.routes = machinesRoutes({ machines, access: this.access });- this.serverProxyRoutes = serverProxyApp(machines);+ this.serverProxyRoutes = machinesServerProxyRoutes(machines);// Every ssh session THIS generation opened closes with it; the successor's setup// re-holds each one the install record says was held.effect(() => machines.stop());@@ -1194,7 +1189,7 @@ export class MachinesModule {* that machine's admin, with a session this server minted over the ssh access that installed* it, so this server's admin session is the one credential involved.*/-function serverProxyApp(machines: MachinesService): Hono<AppEnv> {+export function machinesServerProxyRoutes(machines: MachinesService): Hono<AppEnv> {const app = new Hono<AppEnv>();const proxy = machinesProxy((machineId) => machines.proxyTarget(machineId),diff --git a/packages/server/src/mechanisms/agents.ts b/packages/server/src/mechanisms/agents.tsnew file mode 100644index 00000000..068d14f3--- /dev/null+++ b/packages/server/src/mechanisms/agents.ts@@ -0,0 +1,132 @@+/**+ * The agents mechanisms: what a node may require, declared apart from what implements it.+ */+import { Interface } from "@prismshadow/penguin-core/kernel";+import type { AgentConfigView } from "../services/agent-config-service.js";+import type {+ AgentConfigUpdateRequest,+ AgentKernelUpdateResponse,+ BenchmarkCasesResponse,+ BenchmarksResponse,+ BenchmarkSummary,+ CaseMaterial,+ MemoryFileResponse,+ MemoryFilesResponse,+ MemoryImportMode,+ MemoryImportResponse,+ MemoryOverviewResponse,+ MemoryScopeExport,+ MemoryScopeInfo,+ VaultResponse,+ VaultUpdateRequest,+ WorkspaceFilesResponse,+} from "../api/types.js";+import type {+ WorkspaceFileContent,+ WorkspaceFileReadOptions,+} from "../services/workspace-files-service.js";+import type { AgentListItem } from "../services/agent-service.js";+import type { BenchmarkCreateInput } from "../services/benchmark-service.js";++/** AgentConfig: the mechanism AgentConfigService implements. */+export abstract class AgentConfig extends Interface<{+ exists(projectId: string, agentId: string): Promise<boolean>;+ requireExists(projectId: string, agentId: string): Promise<void>;+ readCardMeta(+ projectId: string,+ agentId: string,+ ): Promise<{+ name?: string;+ description?: string;+ toolCount: number;+ version: number;+ kernelOutdated: boolean;+ }>;+ getConfig(projectId: string, agentId: string): Promise<AgentConfigView>;+ updateConfig(projectId: string, agentId: string, req: AgentConfigUpdateRequest): Promise<void>;+ resetConfig(projectId: string, agentId: string): Promise<void>;+ kernelUpdate(projectId: string, agentId: string): Promise<AgentKernelUpdateResponse>;+ insertTemplatePlaceholder(+ projectId: string,+ agentId: string,+ feature: "vault" | "skills" | "schedules",+ ): Promise<AgentConfigView>;+ getVault(projectId: string, agentId: string): Promise<VaultResponse>;+ updateVault(projectId: string, agentId: string, req: VaultUpdateRequest): Promise<VaultResponse>;+}>() {}++/** Snapshots: the mechanism SnapshotService implements. */+export abstract class Snapshots extends Interface<{+ currentVersion(projectId: string, agentId: string): Promise<number>;+ ensureSnapshot(projectId: string, agentId: string): Promise<{ version: number; file: string }>;+ exportArchive(+ projectId: string,+ agentId: string,+ ): Promise<{ version: number; file: string; fileName: string }>;+ importArchive(+ projectId: string,+ agentId: string,+ archive: Buffer<ArrayBufferLike>,+ opts: { confirm: boolean; preSnapshot?: boolean },+ ): Promise<{ version: number }>;+}>() {}++/** Memory: the mechanism MemoryService implements. */+export abstract class Memory extends Interface<{+ overview(projectId: string, agentId: string): Promise<MemoryOverviewResponse>;+ insertTemplatePlaceholder(projectId: string, agentId: string): Promise<MemoryOverviewResponse>;+ listScopes(projectId: string, agentId: string): Promise<MemoryScopeInfo[]>;+ listFiles(projectId: string, agentId: string, scopeKey: string): Promise<MemoryFilesResponse>;+ readFile(+ projectId: string,+ agentId: string,+ scopeKey: string,+ fileName: string,+ ): Promise<MemoryFileResponse>;+ exportScope(projectId: string, agentId: string, scopeKey: string): Promise<MemoryScopeExport>;+ importScope(+ projectId: string,+ agentId: string,+ scopeKey: string,+ request: { mode: MemoryImportMode; confirm: boolean; payload: unknown },+ ): Promise<MemoryImportResponse>;+ deleteFile(projectId: string, agentId: string, scopeKey: string, fileName: string): Promise<void>;+}>() {}++/** Benchmarks: the mechanism BenchmarkService implements. */+export abstract class Benchmarks extends Interface<{+ list(projectId: string): Promise<BenchmarksResponse>;+ create(projectId: string, input: BenchmarkCreateInput): Promise<BenchmarkSummary>;+ remove(projectId: string, benchmarkId: string): Promise<void>;+ listCases(projectId: string, benchmarkId: string): Promise<BenchmarkCasesResponse>;+ listCaseFiles(+ projectId: string,+ benchmarkId: string,+ caseId: string,+ rel: string,+ material: CaseMaterial,+ ): Promise<WorkspaceFilesResponse>;+ readCaseFile(+ projectId: string,+ benchmarkId: string,+ caseId: string,+ rel: string,+ material: CaseMaterial,+ options?: WorkspaceFileReadOptions,+ ): Promise<WorkspaceFileContent>;+}>() {}++/** AgentLifecycle: the mechanism AgentService implements. */+export abstract class AgentLifecycle extends Interface<{+ listAgents(projectId: string): Promise<AgentListItem[]>;+ deleteAgent(projectId: string, agentId: string): Promise<void>;+ createAgent(+ projectId: string,+ agentId: string,+ name?: string,+ description?: string,+ skillNames?: readonly string[],+ directory?: { path: string; names: readonly string[] },+ archive?: Buffer<ArrayBufferLike>,+ ): Promise<AgentListItem>;+}>() {}diff --git a/packages/server/src/mechanisms/identity.ts b/packages/server/src/mechanisms/identity.tsnew file mode 100644index 00000000..70112593--- /dev/null+++ b/packages/server/src/mechanisms/identity.ts@@ -0,0 +1,66 @@+/**+ * The identity mechanisms: what a node may require, declared apart from what implements it.+ */+import { Interface } from "@prismshadow/penguin-core/kernel";+import type { UserRow } from "../db/repos/users.js";+import type { AuthSessionRow, SessionViaValue } from "../db/repos/auth-sessions.js";+import type { UserInfo } from "../api/types.js";+import type { SessionVia } from "../auth/service.js";++/** Users: the mechanism UsersRepo implements. */+export abstract class Users extends Interface<{+ insert(row: UserRow): void;+ findById(userId: string): UserRow | null;+ list(): UserRow[];+ count(): number;+ updatePassword(userId: string, passwordHash: string, isInitial: boolean): void;+ updateProfile(+ userId: string,+ patch: { displayName?: string | null; avatar?: string | null },+ ): void;+ delete(userId: string): void;+}>() {}++/** AuthSessions: the mechanism AuthSessionsRepo implements. */+export abstract class AuthSessions extends Interface<{+ issue(opts: {+ userId: string;+ via: SessionViaValue;+ now: Date;+ ttlMs: number;+ maxTtlMs?: number;+ }): { token: string; expiresAt: string };+ insert(row: AuthSessionRow): void;+ findByTokenHash(tokenHash: string): AuthSessionRow | null;+ touch(tokenHash: string, expiresAt: string): void;+ delete(tokenHash: string): void;+ deleteExpired(nowIso: string): void;+ deleteByUser(userId: string): void;+ deleteByUserAndVia(userId: string, via: SessionViaValue): void;+}>() {}++/** Auth: the mechanism AuthService implements. */+export abstract class Auth extends Interface<{+ readonly sessionTtlMs: number;+ mintFirstLogin(): string | null;+ adminPasswordIs(password: string): Promise<boolean>;+ seedAdmin(): Promise<void>;+ redeemFirstLogin(given: string): string | null;+ adminPasswordIsInitial(): boolean;+ login(userId: string, password: string): Promise<{ user: UserInfo; token: string }>;+ loginDesktop(): { user: UserInfo; token: string };+ changePassword(userId: string, oldPassword: string, newPassword: string): Promise<void>;+ setInitialPassword(userId: string, newPassword: string): Promise<void>;+ logout(token: string): void;+ localApiToken(): string | null;+ authenticateApiToken(token: string): { user: UserRow; via: SessionVia } | null;+ authenticateWithMeta(token: string): { user: UserRow; via: SessionVia; renewed: boolean } | null;+}>() {}++/** Admin: the mechanism AdminService implements. */+export abstract class Admin extends Interface<{+ listUsers(): UserInfo[];+ createUser(userId: string, password: string): Promise<UserInfo>;+ resetPassword(userId: string, password: string): Promise<void>;+ deleteUser(userId: string): Promise<void>;+}>() {}diff --git a/packages/server/src/mechanisms/messaging.ts b/packages/server/src/mechanisms/messaging.tsnew file mode 100644index 00000000..ba414577--- /dev/null+++ b/packages/server/src/mechanisms/messaging.ts@@ -0,0 +1,28 @@+/**+ * The messaging mechanisms: what a node may require, declared apart from what implements it.+ */+import { Interface } from "@prismshadow/penguin-core/kernel";+import type { MessagingBindingRow } from "../db/repos/messaging-bindings.js";++/** MessagingBindings: the mechanism MessagingBindingsRepo implements. */+export abstract class MessagingBindings extends Interface<{+ find(sessionId: string, channel: string): MessagingBindingRow | null;+ findEnabled(sessionId: string): MessagingBindingRow | null;+ listForSession(sessionId: string): MessagingBindingRow[];+ findEnabledByAccount(channel: string, accountId: string): MessagingBindingRow | null;+ listAll(): MessagingBindingRow[];+ upsert(args: {+ sessionId: string;+ channel: string;+ accountId: string;+ config: Record<string, unknown>;+ linePerMessage?: boolean;+ finalReplyOnly?: boolean;+ renderMarkdown?: boolean;+ }): MessagingBindingRow;+ setEnabled(sessionId: string, channel: string, enabled: boolean): void;+ recordChat(sessionId: string, channel: string, chatId: string, isDirect: boolean): void;+ recordInboundWatermark(sessionId: string, channel: string, messageId: string | null): void;+ delete(sessionId: string, channel: string): void;+ deleteSession(sessionId: string): void;+}>() {}diff --git a/packages/server/src/mechanisms/observability.ts b/packages/server/src/mechanisms/observability.tsnew file mode 100644index 00000000..fa1d9383--- /dev/null+++ b/packages/server/src/mechanisms/observability.ts@@ -0,0 +1,116 @@+/**+ * The observability mechanisms: what a node may require, declared apart from what implements it.+ */+import { Interface } from "@prismshadow/penguin-core/kernel";+import type {+ ErrorCodeCount,+ ErrorFilter,+ ErrorItem,+ ErrorRecordInsert,+ ErrorSummary,+} from "../db/repos/errors.js";+import type { ErrorRecordArgs } from "../runtime/error-recorder.js";+import type {+ UsageAgentBucketCount,+ UsageFilter,+ UsageGroupModelSums,+ UsageModelSums,+ UsageRecordInsert,+ UsageSeriesGranularity,+ UsageSeriesModelSums,+ PeakTier,+} from "../db/repos/usage.js";+import type {+ UsageErrorsPage,+ UsageGroupBy,+ UsageResponse,+ UsageModelTotals,+} from "../api/types.js";+import type { UsageContext } from "../runtime/usage-recorder.js";+import type {+ AbortPayload,+ ApprovalDecisionPayload,+ CompactionBeginPayload,+ CompactionEndPayload,+ ImageUrlPayload,+ InlineDataPayload,+ InlineThinkingPayload,+ McpConnectBeginPayload,+ McpConnectEndPayload,+ OmniMessage,+ OmniPayload,+ PartialTextPayload,+ PartialThinkingPayload,+ PartialToolCallOutputPayload,+ PartialToolCallPayload,+ RequestBeginPayload,+ RequestEndPayload,+ SessionMetaPayload,+ SubagentPayload,+ TextPayload,+ ThinkingPayload,+ TokenUsagePayload,+ ToolCallOutputPayload,+ ToolCallPayload,+ ToolListReadyPayload,+} from "@prismshadow/penguin-core";+import type {+ UsageQuery,+ UsageErrorsClearQuery,+ UsageErrorsQuery,+} from "../services/usage-service.js";++/** ErrorLog: the mechanism ErrorsRepo implements. */+export abstract class ErrorLog extends Interface<{+ insert(r: ErrorRecordInsert): void;+ summary(projectId: string, f?: ErrorFilter): ErrorSummary;+ topCode(projectId: string, f?: ErrorFilter): ErrorCodeCount | null;+ recent(projectId: string, f?: ErrorFilter, limit?: number, offset?: number): ErrorItem[];+ deleteFiltered(projectId: string, f?: Omit<ErrorFilter, "includeGlobal">): number;+ deleteByAgent(projectId: string, agentId: string): void;+ deleteByProject(projectId: string): void;+}>() {}++/** Errors: the mechanism ErrorRecorder implements. */+export abstract class Errors extends Interface<{+ record(args: ErrorRecordArgs): void;+}>() {}++/** UsageStore: the mechanism UsageRepo implements. */+export abstract class UsageStore extends Interface<{+ insert(r: UsageRecordInsert): void;+ bucketByModel(projectId: string, f?: UsageFilter, tiers?: readonly PeakTier[]): UsageModelSums[];+ groupsByModel(+ projectId: string,+ groupBy: UsageGroupBy,+ f?: UsageFilter,+ tiers?: readonly PeakTier[],+ ): UsageGroupModelSums[];+ seriesByModel(+ projectId: string,+ granularity: UsageSeriesGranularity,+ f?: UsageFilter,+ tiers?: readonly PeakTier[],+ ): UsageSeriesModelSums[];+ agentSeries(+ projectId: string,+ granularity: UsageSeriesGranularity,+ f?: UsageFilter,+ ): UsageAgentBucketCount[];+ distinctAgentIds(projectId: string): string[];+ distinctModels(projectId: string): { provider: string; modelId: string }[];+ deleteByProject(projectId: string): void;+}>() {}++/** UsageRecording: the mechanism UsageRecorder implements. */+export abstract class UsageRecording extends Interface<{+ record(ctx: UsageContext, msg: OmniMessage<OmniPayload>): Promise<void>;+}>() {}++/** UsageQueries: the mechanism UsageService implements. */+export abstract class UsageQueries extends Interface<{+ query(projectId: string, q: UsageQuery): Promise<UsageResponse>;+ queryErrors(projectId: string, q: UsageErrorsQuery): UsageErrorsPage;+ clearErrors(projectId: string, q: UsageErrorsClearQuery): number;+ modelTotals(projectId: string): UsageModelTotals;+}>() {}diff --git a/packages/server/src/mechanisms/projects.ts b/packages/server/src/mechanisms/projects.tsnew file mode 100644index 00000000..efebd2e6--- /dev/null+++ b/packages/server/src/mechanisms/projects.ts@@ -0,0 +1,158 @@+/**+ * The projects mechanisms: what a node may require, declared apart from what implements it.+ */+import { Interface } from "@prismshadow/penguin-core/kernel";+import type { AccessibleProjectRow, ProjectRow } from "../db/repos/projects.js";+import type { MemberRow } from "../db/repos/members.js";+import type { AgentRow } from "../db/repos/agents.js";+import type {+ ChatDefaultsDto,+ CommandPolicyDto,+ EndpointModelListRequest,+ EndpointModelListResponse,+ MemberInfo,+ ModelProtocolDetectRequest,+ ModelProtocolDetectResponse,+ ModelRefDto,+ ModelTestRequest,+ ModelTestResponse,+ ModelVisionDetectRequest,+ ModelVisionDetectResponse,+ ModelsResponse,+ ModelsUpdateRequest,+ ProjectRole,+ ProjectSummary,+} from "../api/types.js";+import type { UserRow } from "../db/repos/users.js";+import type { RawTable } from "../services/project-config-service.js";+import type { ListEndpointModelsOptions, ModelRef, ProjectConfig } from "@prismshadow/penguin-core";+import type { TieredRates } from "../services/usage-service.js";+import type {+ ModelOAuthErrorCode,+ ModelOAuthMode,+ ModelOAuthStartResult,+ ModelOAuthStatus,+} from "../services/model-oauth-service.js";++/** Projects: the mechanism ProjectsRepo implements. */+export abstract class Projects extends Interface<{+ insert(row: ProjectRow): void;+ findById(projectId: string): ProjectRow | null;+ listAll(): ProjectRow[];+ listAccessible(userId: string): AccessibleProjectRow[];+ listByOwner(userId: string): ProjectRow[];+ delete(projectId: string): void;+}>() {}++/** Members: the mechanism MembersRepo implements. */+export abstract class Members extends Interface<{+ insert(row: MemberRow): void;+ isMember(projectId: string, userId: string): boolean;+ list(projectId: string): MemberRow[];+ delete(projectId: string, userId: string): void;+}>() {}++/** AgentIndex: the mechanism AgentsRepo implements. */+export abstract class AgentIndex extends Interface<{+ insertOrIgnore(row: AgentRow): void;+ exists(projectId: string, agentId: string): boolean;+ list(projectId: string): AgentRow[];+ delete(projectId: string, agentId: string): void;+ deleteByProject(projectId: string): void;+}>() {}++/** Access: the mechanism ProjectAccess implements. */+export abstract class Access extends Interface<{+ find(userId: string, projectId: string): (ProjectRow & { role: ProjectRole }) | null;+ requireProjectAccess(userId: string, projectId: string): ProjectRow & { role: ProjectRole };+ canAccess(userId: string, projectId: string): boolean;+ requireProjectOwner(userId: string, projectId: string): ProjectRow;+ accessibleProjectIds(userId: string): string[];+ listProjects(userId: string): Promise<ProjectSummary[]>;+}>() {}++/** ProjectLifecycle: the mechanism ProjectService implements. */+export abstract class ProjectLifecycle extends Interface<{+ requireProjectAccess(userId: string, projectId: string): ProjectRow & { role: ProjectRole };+ canAccess(userId: string, projectId: string): boolean;+ requireProjectOwner(userId: string, projectId: string): ProjectRow;+ accessibleProjectIds(userId: string): string[];+ listProjects(userId: string): Promise<ProjectSummary[]>;+ createProject(owner: UserRow, projectId: string, name?: string): Promise<ProjectSummary>;+ provisionInitialProject(user: UserRow, isAdmin: boolean): Promise<void>;+ renameProject(userId: string, projectId: string, name: string): Promise<ProjectSummary>;+ deleteProject(userId: string, projectId: string): Promise<void>;+ destroyProject(projectId: string): Promise<void>;+ listMembers(userId: string, projectId: string): MemberInfo[];+ addMember(userId: string, projectId: string, targetUserId: string): MemberInfo;+ removeMember(userId: string, projectId: string, targetUserId: string): void;+}>() {}++/** ProjectConfigStore: the mechanism ProjectConfigService implements. */+export abstract class ProjectConfigStore extends Interface<{+ readRaw(projectId: string): Promise<RawTable>;+ loadConfig(projectId: string): Promise<ProjectConfig>;+ writeRaw(projectId: string, data: RawTable): Promise<void>;+ writeInitialConfig(projectId: string, name: string): Promise<void>;+ ensurePresetModels(projectId: string): Promise<void>;+ getName(projectId: string): Promise<string | undefined>;+ setName(projectId: string, name: string): Promise<void>;+ getDefaultModelRef(projectId: string): Promise<ModelRef | undefined>;+ setDefaultModelRef(projectId: string, ref: ModelRefDto): Promise<ModelRefDto>;+ getChatDefaults(projectId: string): Promise<ChatDefaultsDto>;+ setChatDefaults(projectId: string, req: ChatDefaultsDto): Promise<ChatDefaultsDto>;+ getCommandPolicy(projectId: string): Promise<CommandPolicyDto>;+ setCommandPolicy(+ projectId: string,+ req: {+ enabled?: boolean;+ rules: { name: string; pattern: string; description?: string; enabled?: boolean }[];+ },+ ): Promise<CommandPolicyDto>;+ getPricing(+ projectId: string,+ provider: string,+ modelId: string,+ ): Promise<TieredRates | undefined>;+ detectVision(+ projectId: string,+ req: ModelVisionDetectRequest,+ ): Promise<ModelVisionDetectResponse>;+ testModel(projectId: string, req: ModelTestRequest): Promise<ModelTestResponse>;+ detectProtocol(+ projectId: string,+ req: ModelProtocolDetectRequest,+ ): Promise<ModelProtocolDetectResponse>;+ listEndpointModels(+ req: EndpointModelListRequest,+ listImpl?: (options: ListEndpointModelsOptions) => Promise<string[]>,+ timeoutMs?: number,+ ): Promise<EndpointModelListResponse>;+ getModels(projectId: string): Promise<ModelsResponse>;+ updateModels(projectId: string, req: ModelsUpdateRequest): Promise<ModelsResponse>;+ setGroupApiKey(projectId: string, provider: string, apiKey: string): Promise<number>;+}>() {}++/** ModelOAuth: the mechanism ModelOAuthService implements. */+export abstract class ModelOAuth extends Interface<{+ start(input: {+ projectId: string;+ userId: string;+ provider: string;+ mode: ModelOAuthMode;+ callbackOrigin: string;+ }): ModelOAuthStartResult;+ deposit(input: { flowId: string; projectId: string; code: string }): void;+ poll(input: { flowId: string; userId: string; projectId: string }): Promise<{+ status: ModelOAuthStatus;+ provider: string;+ error?: ModelOAuthErrorCode;+ applied?: number;+ }>;+ complete(input: {+ flowId: string;+ userId: string;+ projectId: string;+ code: string;+ }): Promise<{ ok: true; applied: number } | { ok: false; error: ModelOAuthErrorCode }>;+}>() {}diff --git a/packages/server/src/mechanisms/sessions.ts b/packages/server/src/mechanisms/sessions.tsnew file mode 100644index 00000000..dbf6f0bd--- /dev/null+++ b/packages/server/src/mechanisms/sessions.ts@@ -0,0 +1,82 @@+/**+ * The sessions mechanisms: what a node may require, declared apart from what implements it.+ */+import { Interface } from "@prismshadow/penguin-core/kernel";+import type { Opaque } from "@prismshadow/penguin-core/kernel";+import type { SessionSource, ApprovalMode } from "../api/types.js";+import type { SessionRow } from "../db/repos/sessions.js";+import type { ThinkingLevelName } from "@prismshadow/penguin-core";+import type { ScheduleStateRow } from "../db/repos/schedules.js";+import type { ScheduleFileCache } from "../runtime/schedule-store.js";+import type { ScheduleEntryView } from "../runtime/scheduler.js";++/** SessionIndex: the mechanism SessionsRepo implements. */+export abstract class SessionIndex extends Interface<{+ insert(row: SessionRow): void;+ insertOrIgnore(row: SessionRow): void;+ insertFork(sourceSessionId: string, row: SessionRow): SessionRow;+ markHasTrace(sessionId: string): void;+ markDriven(sessionId: string, at: string): void;+ touchLastActive(sessionId: string, at: string): void;+ findById(sessionId: string): SessionRow | null;+ listByAgent(projectId: string, agentId: string): SessionRow[];+ listByProject(projectId: string): SessionRow[];+ updateApprovalMode(sessionId: string, mode: ApprovalMode): void;+ updateThinkingLevel(sessionId: string, level: ThinkingLevelName): void;+ updateTitle(sessionId: string, title: string): void;+ updateTitleIfNull(sessionId: string, title: string): void;+ setArchived(sessionId: string, archivedAt: string | null): void;+ replaceId(oldSessionId: string, newSessionId: string): void;+ deleteByAgent(projectId: string, agentId: string): void;+ deleteByProject(projectId: string): void;+ deleteById(sessionId: string): void;+}>() {}++/** SessionOrigins: the mechanism SessionSources implements. */+export abstract class SessionOrigins extends Interface<{+ set(sessionId: string, source: SessionSource | null): void;+ get(sessionId: string): SessionSource | null | undefined;+ delete(sessionId: string): void;+}>() {}++/** Schedules: the mechanism SchedulesRepo implements. */+export abstract class Schedules extends Interface<{+ find(projectId: string, agentId: string, name: string): ScheduleStateRow | null;+ listByAgent(projectId: string, agentId: string): ScheduleStateRow[];+ registerOrSync(args: {+ projectId: string;+ agentId: string;+ name: string;+ startAtMs: number;+ defHash: string;+ creatorUserId: string | null;+ }): { row: ScheduleStateRow; fresh: boolean };+ markSlot(projectId: string, agentId: string, name: string, slotMs: number): void;+ markFired(+ projectId: string,+ agentId: string,+ name: string,+ firedAt: string,+ oneShot: boolean,+ ): void;+ markMissed(projectId: string, agentId: string, name: string): void;+ markInvalid(projectId: string, agentId: string, name: string, reason: string): void;+ delete(projectId: string, agentId: string, name: string): void;+ deleteMissing(projectId: string, agentId: string, presentNames: string[]): string[];+ deleteByAgent(projectId: string, agentId: string): void;+ deleteByProject(projectId: string): void;+}>() {}++/** Scheduling: the mechanism Scheduler implements. */+export abstract class Scheduling extends Interface<{+ readonly files: Opaque<"ScheduleFileCache", ScheduleFileCache>;+ start(): Promise<void>;+ stop(): void;+ tickOnce(): Promise<void>;+ reconcileAgent(projectId: string, agentId: string): Promise<void>;+ listAgent(+ projectId: string,+ agentId: string,+ ): Promise<{ entries: ScheduleEntryView[]; invalid: Array<{ name: string; error: string }> }>;+ dropEntry(projectId: string, agentId: string, name: string): void;+}>() {}diff --git a/packages/server/src/mechanisms/settings.ts b/packages/server/src/mechanisms/settings.tsnew file mode 100644index 00000000..c69b6dbc--- /dev/null+++ b/packages/server/src/mechanisms/settings.ts@@ -0,0 +1,27 @@+/**+ * The settings mechanisms: what a node may require, declared apart from what implements it.+ */+import { Interface } from "@prismshadow/penguin-core/kernel";++/** Settings: the mechanism ServerSettingsRepo implements. */+export abstract class Settings extends Interface<{+ get(key: string): string | null;+ set(key: string, value: string): void;+ getProxyForApp(): boolean;+ setProxyForApp(value: boolean): void;+ getProxyForAgent(): boolean;+ setProxyForAgent(value: boolean): void;+ getProxyUrl(): string | null;+ setProxyUrl(value: string | null): void;+ getAttachmentMaxMb(): number;+ setAttachmentMaxMb(value: number): void;+ getAttachmentTotalMb(): number;+ setAttachmentTotalMb(value: number): void;+ getAttachmentLimitsMb(): { attachmentMaxMb: number; attachmentTotalMb: number };+}>() {}++/** UiPrefsStore: the mechanism UiPrefsRepo implements. */+export abstract class UiPrefsStore extends Interface<{+ get(userId: string): string | null;+ set(userId: string, prefsJson: string): void;+}>() {}diff --git a/packages/server/src/mechanisms/traces.ts b/packages/server/src/mechanisms/traces.tsnew file mode 100644index 00000000..45e9bb55--- /dev/null+++ b/packages/server/src/mechanisms/traces.ts@@ -0,0 +1,160 @@+/**+ * The traces mechanisms: what a node may require, declared apart from what implements it.+ */+import { Interface } from "@prismshadow/penguin-core/kernel";+import type {+ SessionCategory,+ AgentTracesResponse,+ HistoryMessage,+ SessionContextParts,+ TraceAnalysisResponse,+ TraceEventsResponse,+ TraceFileInfo,+ TraceImportResponse,+ TracePosition,+} from "../api/types.js";+import type { TraceFileRow, TraceSessionRow } from "../db/repos/trace-index.js";+import type {+ AbortPayload,+ ApprovalDecisionPayload,+ CompactionBeginPayload,+ CompactionEndPayload,+ ImageUrlPayload,+ InlineDataPayload,+ InlineThinkingPayload,+ McpConnectBeginPayload,+ McpConnectEndPayload,+ OmniMessage,+ OmniPayload,+ PartialTextPayload,+ PartialThinkingPayload,+ PartialToolCallOutputPayload,+ PartialToolCallPayload,+ RequestBeginPayload,+ RequestEndPayload,+ SessionMetaPayload,+ SubagentPayload,+ TextPayload,+ ThinkingPayload,+ TokenUsagePayload,+ ToolCallOutputPayload,+ ToolCallPayload,+ ToolListReadyPayload,+} from "@prismshadow/penguin-core";+import type {+ ForkTraceResult,+ MessagesPageRequest,+ MessagesPageResult,+} from "../services/trace-service.js";+import type { MessageCursor } from "../services/message-window.js";++/** TraceIndexStore: the mechanism TraceIndexRepo implements. */+export abstract class TraceIndexStore extends Interface<{+ upsertFile(row: TraceFileRow): void;+ updateFileSize(+ projectId: string,+ agentId: string,+ sessionId: string,+ fileIndex: number,+ sizeBytes: number,+ ): void;+ getPageStats(+ projectId: string,+ agentId: string,+ sessionId: string,+ fileIndex: number,+ ): string | null;+ setPageStats(+ projectId: string,+ agentId: string,+ sessionId: string,+ fileIndex: number,+ sizeBytes: number,+ pageStats: string,+ ): void;+ deleteFile(projectId: string, agentId: string, sessionId: string, fileIndex: number): void;+ listFilesByAgent(projectId: string, agentId: string): TraceFileRow[];+ listFilesBySession(projectId: string, agentId: string, sessionId: string): TraceFileRow[];+ findAgentBySession(projectId: string, sessionId: string): string | null;+ upsertSession(row: TraceSessionRow): void;+ getSession(sessionId: string): TraceSessionRow | null;+ listSessionsByAgent(projectId: string, agentId: string): TraceSessionRow[];+ deleteBySession(sessionId: string): void;+ deleteByAgent(projectId: string, agentId: string): void;+ deleteByProject(projectId: string): void;+}>() {}++/** TraceIndex: the mechanism TraceIndexService implements. */+export abstract class TraceIndex extends Interface<{+ readonly counters: { gateStats: number; dirScans: number; headReads: number };+ reconcileAgent(projectId: string, agentId: string, opts?: { force?: boolean }): Promise<void>;+ reconcileProject(projectId: string, opts?: { force?: boolean }): Promise<void>;+ registerImportedFile(args: {+ projectId: string;+ agentId: string;+ sessionId: string;+ fileIndex: number;+ date: string;+ sizeBytes: number;+ records: OmniMessage[];+ }): void;+ removeSession(projectId: string, agentId: string, sessionId: string): void;+ removeAgent(projectId: string, agentId: string): void;+ removeProject(projectId: string): void;+}>() {}++/** Traces: the mechanism TraceService implements. */+export abstract class Traces extends Interface<{+ observeShardRead?: ((path: string) => void) | undefined;+ deleteSessionTraces(projectId: string, agentId: string, sessionId: string): Promise<void>;+ readMessages(projectId: string, agentId: string, sessionId: string): Promise<HistoryMessage[]>;+ readMessagesPage(+ projectId: string,+ agentId: string,+ sessionId: string,+ req: MessagesPageRequest,+ ): Promise<MessagesPageResult>;+ forkSessionTrace(+ projectId: string,+ agentId: string,+ sourceSessionId: string,+ position: TracePosition,+ ): Promise<ForkTraceResult>;+ contextBreakdown(+ projectId: string,+ agentId: string,+ sessionId: string,+ ): Promise<SessionContextParts>;+ listTraceFiles(projectId: string, agentId: string, sessionId: string): Promise<TraceFileInfo[]>;+ readEvents(+ projectId: string,+ agentId: string,+ sessionId: string,+ index: number,+ offset: number,+ limit: number,+ ): Promise<TraceEventsResponse>;+ analyze(+ projectId: string,+ agentId: string,+ sessionId: string,+ index: number,+ ): Promise<TraceAnalysisResponse>;+ agentTraces(+ projectId: string,+ agentId: string,+ paging: { offset: number; limit: number } | null,+ opts?: { category?: SessionCategory },+ ): Promise<AgentTracesResponse>;+ readFileRaw(+ projectId: string,+ agentId: string,+ sessionId: string,+ index: number,+ ): Promise<Buffer<ArrayBufferLike>>;+ importTraceFile(+ projectId: string,+ agentId: string,+ content: string,+ ): Promise<TraceImportResponse>;+}>() {}diff --git a/packages/server/src/mechanisms/workspace.ts b/packages/server/src/mechanisms/workspace.tsnew file mode 100644index 00000000..ab4a8a3d--- /dev/null+++ b/packages/server/src/mechanisms/workspace.ts@@ -0,0 +1,31 @@+/**+ * The workspace mechanisms: what a node may require, declared apart from what implements it.+ */+import { Interface } from "@prismshadow/penguin-core/kernel";+import type {+ WorkspaceFileContent,+ WorkspaceFileReadOptions,+ WorkspaceFileStat,+} from "../services/workspace-files-service.js";+import type { WorkspaceFilesResponse, WorkspaceSearchResponse } from "../api/types.js";++/** WorkspaceFiles: the mechanism WorkspaceFilesService implements. */+export abstract class WorkspaceFiles extends Interface<{+ statExisting(workspace: string, rels: string[]): Promise<string[]>;+ statExistingWithMtime(workspace: string, rels: string[]): Promise<WorkspaceFileStat[]>;+ list(workspace: string, rel: string): Promise<WorkspaceFilesResponse>;+ read(+ workspace: string,+ rel: string,+ options?: WorkspaceFileReadOptions,+ ): Promise<WorkspaceFileContent>;+ write(+ workspace: string,+ rel: string,+ data: Buffer<ArrayBufferLike>,+ ifVersion?: string,+ ): Promise<void>;+ move(workspace: string, from: string, to: string, ifVersion?: string): Promise<void>;+ remove(workspace: string, rel: string, ifVersion?: string): Promise<void>;+ search(workspace: string, q: string): Promise<WorkspaceSearchResponse>;+}>() {}diff --git a/packages/server/src/platform.ts b/packages/server/src/platform.tsindex e3a0d3b1..a257e9e9 100644--- a/packages/server/src/platform.ts+++ b/packages/server/src/platform.ts@@ -1,8 +1,62 @@import { Component, Module, moduleDefOf, Use } from "@prismshadow/penguin-core/kernel";-import type { ManifestTable, ModuleDef } from "@prismshadow/penguin-core/kernel";+import type { ManifestTable, ModuleClass, ModuleDef } from "@prismshadow/penguin-core/kernel";import table from "./ifaces.json" with { type: "json" };import type { RuntimeCapabilities } from "./hmr/capabilities.js";-import { RuntimeModule } from "./hmr/capabilities.js";+import {+ ConfigPaths,+ ConsoleLog,+ RuntimeAuthState,+ RuntimeChannels,+ RuntimeLifecycle,+ RuntimeConfig,+ RuntimeDb,+ RuntimeDesktop,+ RuntimeHmr,+ RuntimeProxy,+ RuntimeResourceGroups,+ SystemClock,+ AuthState,+ Channels,+ Clock,+ Config,+ Db,+ Desktop,+ Lifecycle,+ Hmr,+ Log,+ Paths,+ Proxy,+ ResourceGroups,+} from "./hmr/capabilities.js";+import { ScryptHasher, PasswordHasher } from "./auth/password.js";+import {+ DefaultMessagingTuning,+ Messaging,+ MessagingTaskRunner,+ MessagingModule,+ QQScan,+} from "./runtime/messaging/bridge.js";+import { FeishuSdkProvider } from "./runtime/messaging/feishu-connector.js";+import { TelegramTransportProvider } from "./runtime/messaging/telegram-connector.js";+import { QQTransportProvider } from "./runtime/messaging/qq-connector.js";+import { QQScanTransportProvider } from "./runtime/messaging/qq-scan.js";+import { WeChatTransportProvider } from "./runtime/messaging/wechat-connector.js";+import { WeChatScanTransportProvider } from "./runtime/messaging/wechat-scan.js";+import {+ CoreSessionLoaders,+ DefaultTitleGenerators,+ SessionsModule,+ SessionEnv,+ Sessions,+ SessionServiceIface,+} from "./runtime/session-manager.js";+import {+ GlobalFetch,+ UpdateCheckService,+ VersionRoutes,+ UpdateCheck,+} from "./services/update-check-service.js";+import { UpdateJobService } from "./services/update-job.js";import { UsersRepo } from "./db/repos/users.js";import { AuthSessionsRepo } from "./db/repos/auth-sessions.js";import { ServerSettingsRepo } from "./db/repos/server-settings.js";@@ -26,10 +80,10 @@ import { TraceIndexService } from "./services/trace-index.js";import { TraceService } from "./services/trace-service.js";import { WorkspaceFilesService } from "./services/workspace-files-service.js";import { ProjectAccess } from "./services/project-access.js";-import { ProjectService } from "./services/project-service.js";-import { AuthService } from "./auth/service.js";+import { ProjectService, ProjectRuns } from "./services/project-service.js";+import { AuthService, InitialProjectProvisioner } from "./auth/service.js";import { AdminService } from "./services/admin-service.js";-import { Scheduler } from "./runtime/scheduler.js";+import { Scheduler, ScheduleSessionCreator, ScheduleTaskRunner } from "./runtime/scheduler.js";import { AgentConfigService } from "./services/agent-config-service.js";import { SnapshotService } from "./services/snapshot-service.js";import { AgentRoutes } from "./services/agent-routes.js";@@ -37,23 +91,43 @@ import { AgentService } from "./services/agent-service.js";import { MemoryService } from "./services/memory-service.js";import { BenchmarkService } from "./services/benchmark-service.js";import { ProjectsRoutes } from "./http/routes/dirs.js";-import { WorkspaceModule } from "./http/routes/preview.js";import { SandboxModule } from "./sandbox/service.js";-import { SessionServiceIface, SessionsModule } from "./runtime/session-manager.js";import { SchedulerRoutes } from "./http/routes/schedules.js";-import { MessagingModule } from "./runtime/messaging/bridge.js";-import { MachinesModule } from "./machines/service.js";+import { Machines, MachinesModule } from "./machines/service.js";import { ProjectAdminRoutes } from "./http/routes/projects.js";import { AdminRoutes } from "./http/routes/admin.js";import { MeRoutes } from "./http/routes/me.js";-import { VersionModule } from "./services/update-check-service.js";import { InstallRoutes } from "./http/routes/install.js";import { EventsRoutes } from "./http/routes/events.js";import { PluginRoutes } from "./http/routes/plugins.js";import { TerminalModule } from "./terminal/manager.js";import { SessionApiRoutes } from "./http/routes/sessions.js";-import { HttpModule } from "./http/app.js";-import { WebModule } from "./http/routes/contributions.js";+import { Admin, Auth, AuthSessions, Users } from "./mechanisms/identity.js";+import {+ Access,+ AgentIndex,+ Members,+ ModelOAuth,+ ProjectConfigStore,+ ProjectLifecycle,+ Projects,+} from "./mechanisms/projects.js";+import { Schedules, Scheduling, SessionIndex, SessionOrigins } from "./mechanisms/sessions.js";+import {+ ErrorLog,+ Errors,+ UsageQueries,+ UsageRecording,+ UsageStore,+} from "./mechanisms/observability.js";+import { TraceIndex, TraceIndexStore, Traces } from "./mechanisms/traces.js";+import { AgentConfig, AgentLifecycle, Benchmarks, Memory, Snapshots } from "./mechanisms/agents.js";+import { WorkspaceFiles } from "./mechanisms/workspace.js";+import { Settings, UiPrefsStore } from "./mechanisms/settings.js";+import { MessagingBindings } from "./mechanisms/messaging.js";+import { PreviewModule, PreviewTokens } from "./http/routes/preview.js";+import { Http, HttpModule } from "./http/app.js";+import { WebModule, WebShell } from "./http/routes/contributions.js";/*** The platform's module tree: the root module and its children, in one place.@@ -72,9 +146,10 @@ import { WebModule } from "./http/routes/contributions.js";*/@Component()export class Startup {- @Use() private readonly scheduler!: Scheduler;- @Use(SessionsModule) private readonly sessionService!: SessionServiceIface;- @Use() private readonly errors!: ErrorRecorder;+ @Use() private readonly scheduler!: Scheduling;+ @Use() private readonly sessionService!: SessionServiceIface;+ @Use() private readonly machines!: Machines;+ @Use() private readonly errors!: Errors;async setup() {// Schedule scheduler: startup reconciliation (missed, don't backfill) + periodic scan.@@ -84,81 +159,242 @@ export class Startup {void this.sessionService.adoptUnmanagedTraceSessions().catch((err: unknown) => {this.errors.record({ source: "process", err, code: "trace_adoption_failed" });});+ // Machines, in one sweep (machines/service.ts start()): a push here is a push everywhere,+ // so this App booting hands the same build on to any machine still carrying a different+ // one, and then re-holds every connection the record says was held — the generation+ // before closed what it opened on its way out. Without this, every push and every+ // restart leaves each machine disconnected until someone connects it by hand.+ // Fire-and-forget for the same reason as the adoption sweep: a host that is slow to+ // answer must not hold up the App that serves everything else.+ void this.machines.start().catch((err: unknown) => {+ this.errors.record({ source: "process", err, code: "machines_reconnect_failed" });+ });}}-/** The root: provides nothing and requires nothing; it exists so the children have a scope to see each other in. */+/**+ * The tree, grouped by mechanism. Each group is a @Module whose `exports` are the+ * interfaces its children offer the rest of the tree; everything else in a group — the+ * repos, the seams a test replaces, the route components — is visible only inside it.+ * A whole group is replaceable, and so is any node inside one.+ */+@Module({+ children: [+ RuntimeConfig,+ RuntimeDb,+ RuntimeChannels,+ RuntimeProxy,+ RuntimeHmr,+ RuntimeDesktop,+ RuntimeAuthState,+ RuntimeLifecycle,+ RuntimeResourceGroups,+ ConsoleLog,+ SystemClock,+ ConfigPaths,+ ],+ exports: [+ Config,+ Db,+ Channels,+ Proxy,+ Hmr,+ Desktop,+ AuthState,+ Lifecycle,+ ResourceGroups,+ Log,+ Clock,+ Paths,+ ],+})+export class RuntimeModule {}+@Module({children: [- RuntimeModule,- // StoresUsersRepo,AuthSessionsRepo,- ServerSettingsRepo,- UiPrefsRepo,- SessionsRepo,+ ScryptHasher,+ AuthService,+ AdminService,+ AdminRoutes,+ MeRoutes,+ ],+ exports: [Users, AuthSessions, Auth, Admin, PasswordHasher],+})+export class IdentityModule {}++@Module({+ children: [ProjectsRepo,MembersRepo,AgentsRepo,- UsageRepo,- SchedulesRepo,- TraceIndexRepo,- MessagingBindingsRepo,- ErrorsRepo,- SessionSources,- // Services- ErrorRecorder,- UsageRecorder,- UsageService,- ProjectConfigService,- ModelOAuthService,- TraceIndexService,- TraceService,- WorkspaceFilesService,ProjectAccess,ProjectService,- AuthService,- AdminService,+ ProjectConfigService,+ ModelOAuthService,+ ProjectsRoutes,+ ProjectAdminRoutes,+ ],+ exports: [+ Projects,+ Members,+ AgentIndex,+ Access,+ ProjectLifecycle,+ ProjectConfigStore,+ ModelOAuth,+ InitialProjectProvisioner,+ ],+})+export class ProjectsModule {}++@Module({+ children: [+ SessionsRepo,+ SessionSources,+ SchedulesRepo,Scheduler,+ CoreSessionLoaders,+ DefaultTitleGenerators,+ SessionsModule,+ SessionApiRoutes,+ SchedulerRoutes,+ EventsRoutes,+ ],+ exports: [+ SessionIndex,+ SessionOrigins,+ Schedules,+ Scheduling,+ Sessions,+ SessionServiceIface,+ SessionEnv,+ ScheduleTaskRunner,+ ScheduleSessionCreator,+ MessagingTaskRunner,+ ProjectRuns,+ ],+})+export class SessionRuntimeModule {}++@Module({+ children: [ServerSettingsRepo, UiPrefsRepo],+ exports: [Settings, UiPrefsStore],+})+export class SettingsModule {}++@Module({+ children: [ErrorsRepo, ErrorRecorder, UsageRepo, UsageRecorder, UsageService],+ exports: [ErrorLog, Errors, UsageStore, UsageRecording, UsageQueries],+})+export class ObservabilityModule {}++@Module({+ children: [TraceIndexRepo, TraceIndexService, TraceService],+ exports: [TraceIndexStore, TraceIndex, Traces],+})+export class TracesModule {}++@Module({+ children: [AgentConfigService,SnapshotService,AgentService,MemoryService,BenchmarkService,AgentRoutes,- // Runtimes and route groups- WorkspaceModule,- SandboxModule,- SessionsModule,+ ],+ exports: [AgentConfig, Snapshots, AgentLifecycle, Memory, Benchmarks],+})+export class AgentsModule {}++@Module({+ children: [WorkspaceFilesService, PreviewModule],+ exports: [WorkspaceFiles, PreviewTokens],+})+export class WorkspaceModule {}++@Module({+ children: [+ FeishuSdkProvider,+ TelegramTransportProvider,+ QQTransportProvider,+ QQScanTransportProvider,+ WeChatTransportProvider,+ WeChatScanTransportProvider,+ DefaultMessagingTuning,+ MessagingBindingsRepo,MessagingModule,- MachinesModule,- ProjectsRoutes,- SchedulerRoutes,- ProjectAdminRoutes,- AdminRoutes,- MeRoutes,- VersionModule,+ ],+ exports: [Messaging, QQScan, MessagingBindings],+})+export class MessagingHubModule {}++@Module({+ children: [+ GlobalFetch,+ UpdateCheckService,+ UpdateJobService,+ HttpModule,+ WebModule,InstallRoutes,- EventsRoutes,+ VersionRoutes,PluginRoutes,+ ],+ exports: [Http, WebShell, UpdateCheck],+})+export class ApiModule {}++/** The root: provides nothing and requires nothing; it exists so the groups have a scope to see each other in. */+@Module({+ children: [+ RuntimeModule,+ SettingsModule,+ IdentityModule,+ ProjectsModule,+ SessionRuntimeModule,+ ObservabilityModule,+ TracesModule,+ AgentsModule,+ WorkspaceModule,+ MessagingHubModule,+ ApiModule,+ SandboxModule,TerminalModule,- SessionApiRoutes,- WebModule,- HttpModule,+ MachinesModule,Startup,],})export class PlatformModule {}-/** The platform tree as the booter takes it: the runtime adapter pre-built over the claimed capabilities, plugin modules appended under the root. */+/**+ * The platform tree as the booter takes it: the runtime nodes pre-built over the claimed+ * capabilities, the claim's replacements standing in for the nodes a test names, and+ * plugin modules appended under the root.+ */export function platformDef(caps: RuntimeCapabilities,adoptable: (group: string) => boolean,plugins: ModuleDef[] = [],+ replace: ReadonlyMap<string, ModuleDef> = new Map(),): ModuleDef {+ const instances = new Map<ModuleClass, object>([+ [RuntimeConfig, new RuntimeConfig(caps)],+ [RuntimeDb, new RuntimeDb(caps)],+ [RuntimeChannels, new RuntimeChannels(caps)],+ [RuntimeProxy, new RuntimeProxy(caps)],+ [RuntimeHmr, new RuntimeHmr(caps)],+ [RuntimeDesktop, new RuntimeDesktop(caps)],+ [RuntimeAuthState, new RuntimeAuthState(caps)],+ [RuntimeLifecycle, new RuntimeLifecycle(caps)],+ [RuntimeResourceGroups, new RuntimeResourceGroups(adoptable)],+ ]);+ for (const [cls, instance] of caps.replacements) instances.set(cls, instance);return moduleDefOf(PlatformModule, {manifests: table.modules as ManifestTable,- instances: new Map([[RuntimeModule, new RuntimeModule(caps, adoptable)]]),+ instances,extra: plugins,+ replace,});}diff --git a/packages/server/src/plugin/host.ts b/packages/server/src/plugin/host.tsindex 1ff43f76..eab248c7 100644--- a/packages/server/src/plugin/host.ts+++ b/packages/server/src/plugin/host.ts@@ -5,10 +5,13 @@*/import type { IfaceTable, ModuleDef, Resources } from "@prismshadow/penguin-core/kernel";-/** One loaded plugin: the package, its modules with manifests paired to code, and its generated table. */+/** One loaded plugin: the package, its modules and stand-ins with manifests paired to code, and its generated table. */export interface LoadedPlugin {specifier: string;+ /** Nodes the plugin adds under the root. */modules: ModuleDef[];+ /** Nodes the plugin stands in for, by the replaced node's name. */+ replaces: ModuleDef[];/** The interfaces and types the package's `ifaces.json` carries; absent for a module built in code. */ifaces?: IfaceTable;}@@ -27,6 +30,14 @@ export class PluginHost {);}}+ const replaced = this.replacements();+ for (const m of plugin.replaces) {+ if (replaced.has(m.manifest.name)) {+ throw new Error(+ `plugin '${plugin.specifier}': '${m.manifest.name}' is already replaced by another plugin`,+ );+ }+ }this.plugins.push(plugin);}@@ -35,6 +46,11 @@ export class PluginHost {return this.plugins.flatMap((e) => e.modules);}+ /** The nodes plugins stand in for, by name — what the platform builds instead of its own. */+ replacements(): ReadonlyMap<string, ModuleDef> {+ return new Map(this.plugins.flatMap((e) => e.replaces.map((m) => [m.manifest.name, m])));+ }+/*** The host's table with every plugin's folded in — what the tree is checked against. On* a key both carry (a plugin's table copies the host interfaces it compiled against) thediff --git a/packages/server/src/plugin/loader.ts b/packages/server/src/plugin/loader.tsindex d07fdf08..3791abf2 100644--- a/packages/server/src/plugin/loader.ts+++ b/packages/server/src/plugin/loader.ts@@ -17,7 +17,12 @@ import fs from "node:fs/promises";import { createRequire } from "node:module";import path from "node:path";import { pathToFileURL } from "node:url";-import type { IfaceTable, ManifestTable, ModuleDef } from "@prismshadow/penguin-core/kernel";+import type {+ IfaceTable,+ ManifestTable,+ ModuleClass,+ ModuleDef,+} from "@prismshadow/penguin-core/kernel";import { moduleDefOf, parseManifest } from "@prismshadow/penguin-core/kernel";import type { Plugin } from "@prismshadow/penguin-core/plugin";import type { LoadedPlugin } from "./host.js";@@ -135,10 +140,16 @@ async function readPackageTable(/** The package's default export as a Plugin, or null when it is not one. */function asPlugin(module: unknown): Plugin | null {const def = (module as { default?: unknown }).default;- const modules = (def as { modules?: unknown } | null)?.modules;- return Array.isArray(modules) && modules.every((m) => typeof m === "function")- ? (def as Plugin)- : null;+ const d = def as { modules?: unknown; replaces?: unknown } | null;+ const classes = (v: unknown) => Array.isArray(v) && v.every((m) => typeof m === "function");+ if (d === null || typeof d !== "object") return null;+ if (d.modules === undefined && d.replaces === undefined) return null;+ if (+ (d.modules !== undefined && !classes(d.modules)) ||+ (d.replaces !== undefined && !classes(d.replaces))+ )+ return null;+ return def as Plugin;}/**@@ -168,29 +179,32 @@ export async function loadPlugins(root: string): Promise<PluginLoadResult> {if (plugin === null) {failed.set(specifier,- "the default export is not a Plugin ({ modules: [<@Component or @Module class>, …] })",+ "the default export is not a Plugin ({ modules?: [<@Component or @Module class>, …], replaces?: [<class>, …] })",);continue;}- if (plugin.modules.length > 0 && Object.keys(read.manifests).length === 0) {+ const named = (plugin.modules?.length ?? 0) + (plugin.replaces?.length ?? 0);+ if (named > 0 && Object.keys(read.manifests).length === 0) {// Classes named, no table: the package was not built (gen-ifaces runs in its build).throw new Error(`the default export names module classes, but ${path.join(path.dirname(read.where), IFACES_FILE)} is missing — build the package`,);}- const modules: ModuleDef[] = [];+ // Each class is checked against its generated manifest here (a stale table is a+ // named error); the manifest is checked against the tree at boot.const seen = new Set<string>();- for (const cls of plugin.modules) {- // The class is checked against its generated manifest here (a stale table is a- // named error); the manifest is checked against the tree at boot.- const def = moduleDefOf(cls, { manifests: read.manifests });- if (seen.has(def.manifest.name)) {- throw new Error(`the default export lists module '${def.manifest.name}' twice`);- }- seen.add(def.manifest.name);- modules.push(def);- }- loaded.push({ specifier, modules, ifaces: read.ifaces });+ const pair = (classes: readonly ModuleClass[] | undefined): ModuleDef[] =>+ (classes ?? []).map((cls) => {+ const def = moduleDefOf(cls, { manifests: read.manifests });+ if (seen.has(def.manifest.name)) {+ throw new Error(`the default export lists '${def.manifest.name}' twice`);+ }+ seen.add(def.manifest.name);+ return def;+ });+ const modules = pair(plugin.modules);+ const replaces = pair(plugin.replaces);+ loaded.push({ specifier, modules, replaces, ifaces: read.ifaces });} catch (err) {failed.set(specifier, err instanceof Error ? err.message : String(err));}diff --git a/packages/server/src/runtime/error-recorder.ts b/packages/server/src/runtime/error-recorder.tsindex e682fc88..7e834180 100644--- a/packages/server/src/runtime/error-recorder.ts+++ b/packages/server/src/runtime/error-recorder.ts@@ -53,9 +53,9 @@*/import { formatLocalDate } from "../internal/dates.js";import { HttpError } from "../http/errors.js";-import type { ErrorsRepo } from "../db/repos/errors.js";import { Component, Use } from "@prismshadow/penguin-core/kernel";-import type { Overrides } from "../hmr/capabilities.js";+import type { Clock } from "../hmr/capabilities.js";+import type { ErrorLog, Errors } from "../mechanisms/observability.js";/** Capture-site source (maps one-to-one to error_records.source). */export type ErrorSource =@@ -109,23 +109,18 @@ function messageOf(err: unknown): string {}@Component()-export class ErrorRecorder {+export class ErrorRecorder implements Errors {/** Dedup table: `source \0 code \0 projectId` → timestamp of the last **persist** (see file header). */private readonly lastSeen = new Map<string, number>();- @Use() private readonly errors!: ErrorsRepo;- @Use() private readonly overrides!: Overrides;- private now: () => Date = () => new Date();-- setup(): void {- this.now = this.overrides.value().now ?? this.now;- }+ @Use() private readonly errors!: ErrorLog;+ @Use() private readonly clock!: Clock;/** Record an error (synchronous, fails silently; same-window duplicates are dropped outright, see file header). */record(args: ErrorRecordArgs): void {try {const http = args.err instanceof HttpError ? args.err : null;- const now = this.now();+ const now = this.clock.now();const projectId = args.ctx?.projectId ?? null;const code = args.code ?? http?.code ?? "internal";// Short-window dedup: coarse-grained to "same kind of error for the same Project"; repeats within the window aren't persisted.diff --git a/packages/server/src/runtime/messaging/bridge.ts b/packages/server/src/runtime/messaging/bridge.tsindex adacd987..1ee3d45e 100644--- a/packages/server/src/runtime/messaging/bridge.ts+++ b/packages/server/src/runtime/messaging/bridge.ts@@ -73,17 +73,14 @@import { imageUrlMessage, scratchpadDir, userText } from "@prismshadow/penguin-core";import type { OmniMessage } from "@prismshadow/penguin-core";import type { MessagingDeliveryError, MessagingRuntimeStatus } from "../../api/types.js";-import type {- MessagingBindingRow,- MessagingBindingsRepo,-} from "../../db/repos/messaging-bindings.js";+import type { MessagingBindingRow } from "../../db/repos/messaging-bindings.js";import { INLINE_IMAGE_MAX_BYTES, toAttachmentLimits } from "../../services/attachment-limits.js";import type { AttachmentLimits } from "../../services/attachment-limits.js";import { attachFilesToInput, removeAttachments } from "../../services/task-attachments.js";import type { AttachedFiles, TaskAttachment } from "../../services/task-attachments.js";import type { ChannelEvent, ChannelHub } from "../channel.js";-import type { ErrorSink, ErrorRecorder } from "../error-recorder.js";-import { recallStoreOf, SessionsModule } from "../session-manager.js";+import type { ErrorSink } from "../error-recorder.js";+import { recallStoreOf } from "../session-manager.js";import type { RecallStore } from "../session-manager.js";import type {MessagingChannelConnector,@@ -97,23 +94,27 @@ import { messagingErrorKind } from "./error-kind.js";import { chunkMarkdown } from "./markdown.js";import { MessagingMediaTooLargeError, MessagingPermissionError, isImageFileName } from "./media.js";import { replyFileMentions } from "./reply-files.js";-import { Interface, Bind, Module, Provide, Use } from "@prismshadow/penguin-core/kernel";+import { Component, Interface, Bind, Module, Provide, Use } from "@prismshadow/penguin-core/kernel";import type { Slot, ClassCtx } from "@prismshadow/penguin-core/kernel";+import type { QQScanTransportHandle } from "./qq-scan.js";import { QQScanService, createQQScanTransport } from "./qq-scan.js";import type { AppEnv } from "../../auth/middleware.js";import { Hono } from "hono";-import { Channels, Config, Log, Overrides, RuntimeModule } from "../../hmr/capabilities.js";-import { WorkspaceModule } from "../../http/routes/preview.js";+import { FeishuMessaging } from "./feishu-connector.js";import { TelegramMessaging } from "./telegram-connector.js";import { QqMessaging } from "./qq-connector.js";import { WechatMessaging } from "./wechat-connector.js";-import { WeChatScanService, createWeChatScanTransport } from "./wechat-scan.js";-import type { SessionsRepo } from "../../db/repos/sessions.js";-import type { WorkspaceFilesService } from "../../services/workspace-files-service.js";-import type { ProjectAccess } from "../../services/project-access.js";+import { WeChatScanService } from "./wechat-scan.js";+import type { WeChatScanTransportHandle } from "./wechat-scan.js";import { sessionMessagingRoutes } from "../../http/routes/messaging.js";-import type { ServerSettingsRepo } from "../../db/repos/server-settings.js";+import type { Channels, Clock, Log, Paths } from "../../hmr/capabilities.js";+import type { Access } from "../../mechanisms/projects.js";+import type { SessionIndex } from "../../mechanisms/sessions.js";+import type { Errors } from "../../mechanisms/observability.js";+import type { WorkspaceFiles } from "../../mechanisms/workspace.js";+import type { Settings } from "../../mechanisms/settings.js";+import type { MessagingBindings } from "../../mechanisms/messaging.js";/*** Max characters per outbound text message, shared by every channel: it must sit under@@ -621,7 +622,7 @@ export interface MessagingWorkspaceFiles {}export interface MessagingBridgeDeps {- repo: MessagingBindingsRepo;+ repo: MessagingBindings;sessions: MessagingSessionIndex;files: MessagingWorkspaceFiles;/**@@ -1904,29 +1905,33 @@ export interface MessagingSlots {children: [FeishuMessaging, TelegramMessaging, QqMessaging, WechatMessaging],})export class MessagingModule {- @Use(RuntimeModule) private readonly config!: Config;- @Use(RuntimeModule) private readonly channels!: Channels;- @Use(RuntimeModule) private readonly overrides!: Overrides;- @Use(RuntimeModule) private readonly log!: Log;- @Use() private readonly messagingRepo!: MessagingBindingsRepo;- @Use() private readonly sessionsRepo!: SessionsRepo;- @Use() private readonly workspaceFiles!: WorkspaceFilesService;- @Use() private readonly settings!: ServerSettingsRepo;- @Use(SessionsModule) private readonly runner!: MessagingTaskRunner;- @Use() private readonly errors!: ErrorRecorder;- @Use() private readonly access!: ProjectAccess;+ @Use() private readonly paths!: Paths;+ @Use() private readonly channels!: Channels;+ @Use() private readonly clock!: Clock;+ @Use() private readonly tuning!: MessagingTuning;+ @Use() private readonly qqScanTransport!: QQScanTransportHandle;+ @Use() private readonly wechatScanTransport!: WeChatScanTransportHandle;+ @Use() private readonly log!: Log;+ @Use() private readonly messagingRepo!: MessagingBindings;+ @Use() private readonly sessionsRepo!: SessionIndex;+ @Use() private readonly workspaceFiles!: WorkspaceFiles;+ @Use() private readonly settings!: Settings;+ @Use() private readonly runner!: MessagingTaskRunner;+ @Use() private readonly errors!: Errors;+ @Use() private readonly access!: Access;@Provide() messaging!: Messaging;@Provide() qqScan!: QQScan;@Bind("messaging.session-routes") sessionRoutesRoutes!: Hono<AppEnv>;async setup({ contributions, effect }: ClassCtx) {- const overrides = this.overrides.value();+ const { lineDelayMs, inboundImageBudgetBytes } = this.tuning;+ const now = () => this.clock.now().getTime();const messagingRepo = this.messagingRepo;const sessionsRepo = this.sessionsRepo;const messaging = new MessagingBridge({repo: messagingRepo,sessions: sessionsRepo,files: this.workspaceFiles,- root: this.config.root,+ root: this.paths.root,attachmentLimits: () => toAttachmentLimits(this.settings.getAttachmentLimitsMb()),channels: this.channels as ChannelHub,runner: this.runner,@@ -1935,23 +1940,14 @@ export class MessagingModule {connectors: (contributions.connectors ?? []).map((c) => c.code as MessagingChannelConnector),errors: this.errors,log: (line) => this.log.line(line),- ...(overrides.now ? { now: () => overrides.now!().getTime() } : {}),- ...(overrides.messagingLineDelayMs !== undefined- ? { lineDelayMs: overrides.messagingLineDelayMs }- : {}),- ...(overrides.messagingInboundImageBudgetBytes !== undefined- ? { inboundImageBudgetBytes: overrides.messagingInboundImageBudgetBytes }- : {}),- });- const qqScan = new QQScanService(overrides.qqScanTransport ?? createQQScanTransport(), {- ...(overrides.now ? { now: () => overrides.now!().getTime() } : {}),+ now,+ ...(lineDelayMs !== undefined ? { lineDelayMs } : {}),+ ...(inboundImageBudgetBytes !== undefined ? { inboundImageBudgetBytes } : {}),});+ const qqScan = new QQScanService(this.qqScanTransport.transport, { now });// Same shape as the QQ one: what it holds is the handle that collects a bot token// rather than a key that decrypts a secret, and is equally not worth persisting.- const wechatScan = new WeChatScanService(- overrides.wechatScanTransport ?? createWeChatScanTransport(),- { ...(overrides.now ? { now: () => overrides.now!().getTime() } : {}) },- );+ const wechatScan = new WeChatScanService(this.wechatScanTransport.transport, { now });// Connect every enabled binding; only active while this App is.await messaging.start();effect(() => messaging.stop());@@ -1967,3 +1963,16 @@ export class MessagingModule {});}}++/**+ * The pacing and budgets the messaging bridge and its connectors run with. Every field is+ * optional: absent, a connector applies its own default; a test stands in zeros.+ */+export abstract class MessagingTuning extends Interface<{+ lineDelayMs?: number;+ inboundImageBudgetBytes?: number;+ qqTailFlushMs?: number;+ retryDelayMs?: (failures: number) => number;+}>() {}+@Component()+export class DefaultMessagingTuning implements MessagingTuning {}diff --git a/packages/server/src/runtime/messaging/feishu-connector.ts b/packages/server/src/runtime/messaging/feishu-connector.tsindex e0ba4204..024df475 100644--- a/packages/server/src/runtime/messaging/feishu-connector.ts+++ b/packages/server/src/runtime/messaging/feishu-connector.ts@@ -20,9 +20,8 @@ import type {import { feishuCardOf } from "./feishu-card.js";import type { FeishuApiClient, FeishuCredentials, FeishuMention, FeishuSdk } from "./feishu-sdk.js";import { FeishuApiError, createLarkSdk } from "./feishu-sdk.js";-import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";-import type { ClassCtx } from "@prismshadow/penguin-core/kernel";-import { Overrides, RuntimeModule } from "../../hmr/capabilities.js";+import { Bind, Component, Interface, Module, Provide, Use } from "@prismshadow/penguin-core/kernel";+import type { ClassCtx, Opaque } from "@prismshadow/penguin-core/kernel";/** Default Feishu open-platform domain (Lark tenants override it in the form). */export const FEISHU_DEFAULT_DOMAIN = "https://open.feishu.cn";@@ -327,10 +326,21 @@ export class FeishuConnector implements MessagingChannelConnector {},})export class FeishuMessaging {- @Use(RuntimeModule) private readonly overrides!: Overrides;+ @Use() private readonly feishu!: FeishuSdkHandle;@Bind("messaging-feishu.connector") connector!: MessagingChannelConnector;setup() {- const overrides = this.overrides.value();- this.connector = new FeishuConnector(overrides.feishuSdk ?? createLarkSdk());+ this.connector = new FeishuConnector(this.feishu.sdk);+ }+}++/** The Lark SDK as a node, so a test stands in a fake for the network. */+export abstract class FeishuSdkHandle extends Interface<{+ sdk: Opaque<"FeishuSdk", FeishuSdk>;+}>() {}+@Module()+export class FeishuSdkProvider {+ @Provide() feishuSdk!: FeishuSdkHandle;+ setup() {+ this.feishuSdk = { sdk: createLarkSdk() };}}diff --git a/packages/server/src/runtime/messaging/qq-connector.ts b/packages/server/src/runtime/messaging/qq-connector.tsindex 010b35cb..85f161d0 100644--- a/packages/server/src/runtime/messaging/qq-connector.ts+++ b/packages/server/src/runtime/messaging/qq-connector.ts@@ -73,6 +73,7 @@* refused with a reason — see refuseMedia, which explains what QQ would require.*/import { MESSAGING_TEXT_CHUNK_CHARS, chunkMessagingText } from "./bridge.js";+import type { MessagingTuning } from "./bridge.js";import { MessagingUnsupportedError } from "./media.js";import type {MessagingChannelConnector,@@ -91,9 +92,9 @@ import type {} from "./qq-api.js";import { QQ_BODY_INDEPENDENT_SEND_CODES, QQApiError, createQQTransport } from "./qq-api.js";import { qqMarkdownOf } from "./qq-markdown.js";-import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";-import type { ClassCtx } from "@prismshadow/penguin-core/kernel";-import { Overrides, RuntimeModule } from "../../hmr/capabilities.js";+import { Bind, Component, Interface, Module, Provide, Use } from "@prismshadow/penguin-core/kernel";+import type { ClassCtx, Opaque } from "@prismshadow/penguin-core/kernel";+import type { Clock } from "../../hmr/capabilities.js";/** The QQ binding's stored config document (`messaging_bindings.config_json`). */export interface QQBindingConfig extends Record<string, unknown> {@@ -645,13 +646,27 @@ export class QQConnector implements MessagingChannelConnector {},})export class QqMessaging {- @Use(RuntimeModule) private readonly overrides!: Overrides;+ @Use() private readonly qq!: QQTransportHandle;+ @Use() private readonly tuning!: MessagingTuning;+ @Use() private readonly clock!: Clock;@Bind("messaging-qq.connector") connector!: MessagingChannelConnector;setup() {- const overrides = this.overrides.value();- this.connector = new QQConnector(overrides.qqTransport ?? createQQTransport(), {- ...(overrides.qqTailFlushMs !== undefined ? { tailFlushMs: overrides.qqTailFlushMs } : {}),- ...(overrides.now ? { now: () => overrides.now!().getTime() } : {}),+ const { qqTailFlushMs } = this.tuning;+ this.connector = new QQConnector(this.qq.transport, {+ ...(qqTailFlushMs !== undefined ? { tailFlushMs: qqTailFlushMs } : {}),+ now: () => this.clock.now().getTime(),});}}++/** The QQ OpenAPI + gateway transport as a node, so a test stands in a fake for the network. */+export abstract class QQTransportHandle extends Interface<{+ transport: Opaque<"QQTransport", QQTransport>;+}>() {}+@Module()+export class QQTransportProvider {+ @Provide() qqTransport!: QQTransportHandle;+ setup() {+ this.qqTransport = { transport: createQQTransport() };+ }+}diff --git a/packages/server/src/runtime/messaging/qq-scan.ts b/packages/server/src/runtime/messaging/qq-scan.tsindex 00e455cf..eb315d38 100644--- a/packages/server/src/runtime/messaging/qq-scan.ts+++ b/packages/server/src/runtime/messaging/qq-scan.ts@@ -31,6 +31,8 @@* style of telegram-api.ts.*/import { createDecipheriv, randomBytes } from "node:crypto";+import { Interface, Module, Provide } from "@prismshadow/penguin-core/kernel";+import type { Opaque } from "@prismshadow/penguin-core/kernel";/** Host serving the three bind-task calls (not the bot OpenAPI host). */export const QQ_SCAN_BASE = "https://q.qq.com";@@ -432,3 +434,15 @@ export class QQScanService {this.sweepTimer = timer;}}++/** The scan-to-connect transport as a node, so a test stands in a fake for the network. */+export abstract class QQScanTransportHandle extends Interface<{+ transport: Opaque<"QQScanTransport", QQScanTransport>;+}>() {}+@Module()+export class QQScanTransportProvider {+ @Provide() qqScanTransport!: QQScanTransportHandle;+ setup() {+ this.qqScanTransport = { transport: createQQScanTransport() };+ }+}diff --git a/packages/server/src/runtime/messaging/telegram-connector.ts b/packages/server/src/runtime/messaging/telegram-connector.tsindex 4ee96c13..a9fcfc31 100644--- a/packages/server/src/runtime/messaging/telegram-connector.ts+++ b/packages/server/src/runtime/messaging/telegram-connector.ts@@ -63,9 +63,9 @@ import {TelegramApiError,createTelegramTransport,} from "./telegram-api.js";-import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";-import type { ClassCtx } from "@prismshadow/penguin-core/kernel";-import { Overrides, RuntimeModule } from "../../hmr/capabilities.js";+import { Bind, Component, Interface, Module, Provide, Use } from "@prismshadow/penguin-core/kernel";+import type { ClassCtx, Opaque } from "@prismshadow/penguin-core/kernel";+import type { MessagingTuning } from "./bridge.js";/** The Telegram binding's stored config document (`messaging_bindings.config_json`). */export interface TelegramBindingConfig extends Record<string, unknown> {@@ -599,13 +599,26 @@ export class TelegramConnector implements MessagingChannelConnector {},})export class TelegramMessaging {- @Use(RuntimeModule) private readonly overrides!: Overrides;+ @Use() private readonly telegram!: TelegramTransportHandle;+ @Use() private readonly tuning!: MessagingTuning;@Bind("messaging-telegram.connector") connector!: MessagingChannelConnector;setup() {- const overrides = this.overrides.value();+ const { retryDelayMs } = this.tuning;this.connector = new TelegramConnector(- overrides.telegramTransport ?? createTelegramTransport(),- overrides.telegramRetryDelayMs ? { retryDelayMs: overrides.telegramRetryDelayMs } : {},+ this.telegram.transport,+ retryDelayMs !== undefined ? { retryDelayMs } : {},);}}++/** The Bot API transport as a node, so a test stands in a fake for the network. */+export abstract class TelegramTransportHandle extends Interface<{+ transport: Opaque<"TelegramTransport", TelegramTransport>;+}>() {}+@Module()+export class TelegramTransportProvider {+ @Provide() telegramTransport!: TelegramTransportHandle;+ setup() {+ this.telegramTransport = { transport: createTelegramTransport() };+ }+}diff --git a/packages/server/src/runtime/messaging/wechat-connector.ts b/packages/server/src/runtime/messaging/wechat-connector.tsindex d37480dd..a8785f83 100644--- a/packages/server/src/runtime/messaging/wechat-connector.ts+++ b/packages/server/src/runtime/messaging/wechat-connector.ts@@ -96,8 +96,9 @@ import type {WeChatTransport,} from "./wechat-api.js";import { WECHAT_API_BASE, createWeChatTransport } from "./wechat-api.js";-import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";-import { Overrides, RuntimeModule } from "../../hmr/capabilities.js";+import { Bind, Component, Interface, Module, Provide, Use } from "@prismshadow/penguin-core/kernel";+import type { Opaque } from "@prismshadow/penguin-core/kernel";+import type { MessagingTuning } from "./bridge.js";/** The WeChat binding's stored config document (`messaging_bindings.config_json`). */export interface WeChatBindingConfig extends Record<string, unknown> {@@ -425,13 +426,26 @@ export class WeChatConnector implements MessagingChannelConnector {},})export class WechatMessaging {- @Use(RuntimeModule) private readonly overrides!: Overrides;+ @Use() private readonly wechat!: WeChatTransportHandle;+ @Use() private readonly tuning!: MessagingTuning;@Bind("messaging-wechat.connector") connector!: MessagingChannelConnector;setup() {- const overrides = this.overrides.value();+ const { retryDelayMs } = this.tuning;this.connector = new WeChatConnector(- overrides.wechatTransport ?? createWeChatTransport(),- overrides.wechatRetryDelayMs ? { retryDelayMs: overrides.wechatRetryDelayMs } : {},+ this.wechat.transport,+ retryDelayMs !== undefined ? { retryDelayMs } : {},);}}++/** The long-poll + CDN transport as a node, so a test stands in a fake for the network. */+export abstract class WeChatTransportHandle extends Interface<{+ transport: Opaque<"WeChatTransport", WeChatTransport>;+}>() {}+@Module()+export class WeChatTransportProvider {+ @Provide() wechatTransport!: WeChatTransportHandle;+ setup() {+ this.wechatTransport = { transport: createWeChatTransport() };+ }+}diff --git a/packages/server/src/runtime/messaging/wechat-scan.ts b/packages/server/src/runtime/messaging/wechat-scan.tsindex b8939bb3..260f90cf 100644--- a/packages/server/src/runtime/messaging/wechat-scan.ts+++ b/packages/server/src/runtime/messaging/wechat-scan.ts@@ -1,3 +1,5 @@+import { Interface, Module, Provide } from "@prismshadow/penguin-core/kernel";+import type { Opaque } from "@prismshadow/penguin-core/kernel";/*** WeChat scan-to-connect: binding the official claw bot by scanning a QR code in WeChat.*@@ -465,3 +467,15 @@ export class WeChatScanService {this.sweepTimer = timer;}}++/** The scan-to-connect transport as a node, so a test stands in a fake for the network. */+export abstract class WeChatScanTransportHandle extends Interface<{+ transport: Opaque<"WeChatScanTransport", WeChatScanTransport>;+}>() {}+@Module()+export class WeChatScanTransportProvider {+ @Provide() wechatScanTransport!: WeChatScanTransportHandle;+ setup() {+ this.wechatScanTransport = { transport: createWeChatScanTransport() };+ }+}diff --git a/packages/server/src/runtime/scheduler.ts b/packages/server/src/runtime/scheduler.tsindex e6be0722..46108c74 100644--- a/packages/server/src/runtime/scheduler.ts+++ b/packages/server/src/runtime/scheduler.ts@@ -22,11 +22,9 @@import { createHash } from "node:crypto";import fs from "node:fs/promises";import { agentsDir, buildScheduledMessage, userText } from "@prismshadow/penguin-core";-import type { ProjectsRepo } from "../db/repos/projects.js";-import type { SchedulesRepo, ScheduleStateRow } from "../db/repos/schedules.js";-import type { SessionsRepo } from "../db/repos/sessions.js";+import type { ScheduleStateRow } from "../db/repos/schedules.js";import { cacheable, statMtime } from "../internal/mtime-gate.js";-import type { ErrorSink, ErrorRecorder } from "./error-recorder.js";+import type { ErrorSink } from "./error-recorder.js";import type { ScheduleDefinition } from "./schedule-file.js";import { latestSlotAt, slotInWindow } from "./schedule-file.js";import { ScheduleFileCache, readScheduleFile, validateScheduleModelRef } from "./schedule-store.js";@@ -34,9 +32,11 @@ import type { ScheduleConfigSource } from "./schedule-store.js";import type { ScheduleServerEvent } from "../api/types.js";import { Component, Interface, Use } from "@prismshadow/penguin-core/kernel";import type { ClassCtx } from "@prismshadow/penguin-core/kernel";-import type { Channels, Config, Overrides } from "../hmr/capabilities.js";-import type { ProjectConfigService } from "../services/project-config-service.js";import { userChannelKey } from "../http/routes/events.js";+import type { Channels, Clock, Paths } from "../hmr/capabilities.js";+import type { Schedules, Scheduling, SessionIndex } from "../mechanisms/sessions.js";+import type { ProjectConfigStore, Projects } from "../mechanisms/projects.js";+import type { Errors } from "../mechanisms/observability.js";/** Reconcile and fire-check interval (min period is 5m, so 30s granularity is plenty). */const TICK_INTERVAL_MS = 30_000;@@ -90,8 +90,7 @@ export interface ScheduleEntryView {}@Component()-export class Scheduler {- private now: () => number = () => Date.now();+export class Scheduler implements Scheduling {private intervalMs: number = TICK_INTERVAL_MS;private timer: ReturnType<typeof setInterval> | null = null;/** key = `${projectId}\0${agentId}\0${name}` */@@ -105,24 +104,25 @@ export class Scheduler {/** Per-Project agents-dir listing gate: dir mtime → Agent ids (creating/removing an Agent dir moves it). */private readonly agentDirs = new Map<string, { mtimeMs: number; ids: string[] }>();- @Use() private readonly config!: Config;+ @Use() private readonly paths!: Paths;private get root(): string {- return this.config.root;+ return this.paths.root;}- @Use() private readonly repo!: SchedulesRepo;- @Use() private readonly projects!: ProjectsRepo;- @Use() private readonly sessions!: SessionsRepo;+ @Use() private readonly repo!: Schedules;+ @Use() private readonly projects!: Projects;+ @Use() private readonly sessions!: SessionIndex;@Use() private readonly runner!: ScheduleTaskRunner;@Use() private readonly sessionCreator!: ScheduleSessionCreator;/** Project-config source for model-ref validation (mtime-cached reads). */- @Use() private readonly projectConfig!: ProjectConfigService;- @Use() private readonly errors!: ErrorRecorder;+ @Use() private readonly projectConfig!: ProjectConfigStore;+ @Use() private readonly errors!: Errors;@Use() private readonly channels!: Channels;- @Use() private readonly overrides!: Overrides;+ @Use() private readonly clock!: Clock;+ private now(): number {+ return this.clock.now().getTime();+ }setup({ effect }: ClassCtx): void {- const overrides = this.overrides.value();- if (overrides.now) this.now = () => overrides.now!().getTime();// Only active while this App is; the successor's start() reconciles missed fires.effect(() => this.stop());}diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.tsindex 897d4c42..de9acef7 100644--- a/packages/server/src/runtime/session-manager.ts+++ b/packages/server/src/runtime/session-manager.ts@@ -67,35 +67,34 @@ import type {import type { RecallableFile } from "../services/task-attachments.js";import { cliShimDir } from "../services/cli-shim.js";import { HttpError, isMissingCredential, modelCredentialMissing } from "../http/errors.js";-import type { SessionRow, SessionsRepo } from "../db/repos/sessions.js";+import type { SessionRow } from "../db/repos/sessions.js";import { ApprovalRegistry, makeApprove } from "./approvals.js";import { goalOutcomeOf, goalProgressOf } from "./goal-events.js";import type { PendingApproval } from "./approvals.js";import type { ChannelHub } from "./channel.js";-import type { ErrorSink, ErrorRecorder } from "./error-recorder.js";+import type { ErrorSink } from "./error-recorder.js";import { LiveTailTracker } from "./live-tail.js";import { asSessionSource } from "./session-sources.js";-import type { SessionSources } from "./session-sources.js";import { StreamErrorWatcher } from "./stream-error-watcher.js";import type { TitleNotifier } from "./title-generator.js";-import type { UsageContext, UsageRecorder } from "./usage-recorder.js";-import { Interface, Module, Provide, Use } from "@prismshadow/penguin-core/kernel";+import type { UsageContext } from "./usage-recorder.js";+import { Component, Interface, Module, Provide, Use } from "@prismshadow/penguin-core/kernel";import type { SessionService as SessionServiceImpl } from "../services/session-service.js";-import type { ClassCtx } from "@prismshadow/penguin-core/kernel";-import { AuthState, Channels, Config, Log, Overrides, RuntimeModule } from "../hmr/capabilities.js";+import type { ClassCtx, Opaque } from "@prismshadow/penguin-core/kernel";import { Sandbox, SandboxModule } from "../sandbox/service.js";import { SessionService } from "../services/session-service.js";import { TitleGenerator } from "./title-generator.js";import { loopbackHostRoles } from "../services/preview-token.js";import { mergedNoProxy } from "../net/proxy.js";import { userChannelKey } from "../http/routes/events.js";-import type { ProjectConfigService } from "../services/project-config-service.js";-import type { TraceIndexService } from "../services/trace-index.js";import type { SandboxService } from "../sandbox/service.js";-import type { ServerSettingsRepo } from "../db/repos/server-settings.js";-import type { MessagingBindingsRepo } from "../db/repos/messaging-bindings.js";-import type { MembersRepo } from "../db/repos/members.js";-import type { ProjectsRepo } from "../db/repos/projects.js";+import type { AuthState, Channels, Clock, Config, Log } from "../hmr/capabilities.js";+import type { Members, ProjectConfigStore, Projects } from "../mechanisms/projects.js";+import type { SessionIndex, SessionOrigins } from "../mechanisms/sessions.js";+import type { Errors, UsageRecording } from "../mechanisms/observability.js";+import type { TraceIndex, TraceIndexStore } from "../mechanisms/traces.js";+import type { Settings } from "../mechanisms/settings.js";+import type { MessagingBindings } from "../mechanisms/messaging.js";/*** 409 for when there's nothing to compact: give the specific reason rather than a@@ -250,7 +249,7 @@ export interface SessionLoader {*/export function createCoreSessionLoader(root: string,- sources?: SessionSources,+ sources?: SessionOrigins,opts: {proxyEnv?: () => ProxyEnvPolicy | null;controlEnv?: (ctx: ControlEnvContext) => Record<string, string>;@@ -338,17 +337,18 @@ export interface UsageRecorderLike {}export interface SessionManagerDeps {- sessions: SessionsRepo;+ sessions: SessionIndex;channels: ChannelHub;loader: SessionLoader;/** Session-origin registry (session_meta is the single source of truth; subagent registration records the forwarded meta's source here). */- sources: SessionSources;+ sources: SessionOrigins;recorder: UsageRecorderLike;/** Automatic Session title generation (optional: not injected in tests or when disabled). */titles?: TitleNotifier;/** Error persistence (optional: without it, only logs — same as before this was wired up). */errors?: ErrorSink;log?: (line: string) => void;+ /** Goal run-state persistence (optional like `titles`: without it, goals run but leave no restorable record). *//*** Publishes a Session-scoped event on the user-level channel of everyone who can see the* Project. The audience lookup (owner + members) and the `user:<id>` channel binding stay in@@ -2064,7 +2064,7 @@ export class SessionManager {* run-end one lives in its finally — and the realistic failure (the DatabaseSync handle* closed by shutdown while a run outlived its drain window) throws ERR_INVALID_STATE.*/- private touchRow(ctx: UsageContext, write: (repo: SessionsRepo, at: string) => void): void {+ private touchRow(ctx: UsageContext, write: (repo: SessionIndex, at: string) => void): void {try {write(this.deps.sessions, this.now().toISOString());} catch (err) {@@ -2248,28 +2248,30 @@ export abstract class SessionEnv extends Interface<{@Module()export class SessionsModule {- @Use(RuntimeModule) private readonly config!: Config;- @Use(RuntimeModule) private readonly channels!: Channels;- @Use(RuntimeModule) private readonly authState!: AuthState;- @Use(RuntimeModule) private readonly overrides!: Overrides;- @Use(RuntimeModule) private readonly log!: Log;- @Use() private readonly settings!: ServerSettingsRepo;- @Use() private readonly sessionsRepo!: SessionsRepo;- @Use() private readonly sources!: SessionSources;- @Use() private readonly recorder!: UsageRecorder;- @Use() private readonly errors!: ErrorRecorder;- @Use() private readonly projectConfig!: ProjectConfigService;- @Use() private readonly traceIndex!: TraceIndexService;+ @Use() private readonly config!: Config;+ @Use() private readonly channels!: Channels;+ @Use() private readonly authState!: AuthState;+ @Use() private readonly clock!: Clock;+ @Use() private readonly sessionLoaders!: SessionLoaders;+ @Use() private readonly titleGenerators!: TitleGenerators;+ @Use() private readonly log!: Log;+ @Use() private readonly settings!: Settings;+ @Use() private readonly sessionsRepo!: SessionIndex;+ @Use() private readonly sources!: SessionOrigins;+ @Use() private readonly recorder!: UsageRecording;+ @Use() private readonly errors!: Errors;+ @Use() private readonly projectConfig!: ProjectConfigStore;+ @Use() private readonly traceIndex!: TraceIndex;+ @Use() private readonly traceStore!: TraceIndexStore;@Use(SandboxModule) private readonly sandbox!: Sandbox;- @Use() private readonly projectsRepo!: ProjectsRepo;- @Use() private readonly membersRepo!: MembersRepo;- @Use() private readonly messagingRepo!: MessagingBindingsRepo;+ @Use() private readonly projectsRepo!: Projects;+ @Use() private readonly membersRepo!: Members;+ @Use() private readonly messagingRepo!: MessagingBindings;@Provide() manager!: Sessions;@Provide() sessionService!: SessionServiceIface;@Provide() env!: SessionEnv;setup() {const { config, settings, authState } = this;- const overrides = this.overrides.value();const log = (line: string) => this.log.line(line);const channels = this.channels as ChannelHub;const sessionsRepo = this.sessionsRepo;@@ -2322,34 +2324,30 @@ export class SessionsModule {channels.peek(userChannelKey(userId))?.publish(event, "server_event");}};- const titles =- overrides.titles ??- new TitleGenerator({- sessions: sessionsRepo,- channels,- recorder,- errors,- log,- notifyProjectUsers,- });+ const titles = this.titleGenerators.create({+ sessions: sessionsRepo,+ channels,+ recorder,+ errors,+ log,+ notifyProjectUsers,+ });const manager = new SessionManager({sessions: sessionsRepo,channels,- loader:- overrides.loader ??- createCoreSessionLoader(config.root, sources, {- proxyEnv: env.proxyEnv,- controlEnv: env.controlEnv,- pathPrepend: env.pathPrepend,- confineSpawn: env.confineSpawn,- }),+ loader: this.sessionLoaders.create(config.root, sources, {+ proxyEnv: env.proxyEnv,+ controlEnv: env.controlEnv,+ pathPrepend: env.pathPrepend,+ confineSpawn: env.confineSpawn,+ }),sources,recorder,errors,titles,log,notifyProjectUsers,- ...(overrides.now ? { now: overrides.now } : {}),+ now: () => this.clock.now(),});const sessionService = new SessionService({root: config.root,@@ -2358,6 +2356,7 @@ export class SessionsModule {projectConfig,sources,traceIndex: this.traceIndex,+ traceStore: this.traceStore,proxyEnv: env.proxyEnv,controlEnv: env.controlEnv,messagingChannel: (sessionId) => {@@ -2377,3 +2376,35 @@ export class SessionsModule {this.env = env;}}++/** Builds the loader a manager runs sessions through; a test stands in a fake session. */+export abstract class SessionLoaders extends Interface<{+ create(+ root: string,+ sources: Opaque<"SessionOrigins", SessionOrigins>,+ env: Opaque<"SessionLoaderEnv", Parameters<typeof createCoreSessionLoader>[2]>,+ ): Opaque<"SessionLoader", SessionLoader>;+}>() {}+@Component()+export class CoreSessionLoaders implements SessionLoaders {+ create(+ root: string,+ sources: SessionOrigins,+ env: Parameters<typeof createCoreSessionLoader>[2],+ ): SessionLoader {+ return createCoreSessionLoader(root, sources, env);+ }+}++/** Builds the title generator; a test stands in a notifier that never calls a model. */+export abstract class TitleGenerators extends Interface<{+ create(+ deps: Opaque<"TitleGeneratorDeps", ConstructorParameters<typeof TitleGenerator>[0]>,+ ): Opaque<"TitleNotifier", TitleNotifier>;+}>() {}+@Component()+export class DefaultTitleGenerators implements TitleGenerators {+ create(deps: ConstructorParameters<typeof TitleGenerator>[0]): TitleNotifier {+ return new TitleGenerator(deps);+ }+}diff --git a/packages/server/src/runtime/session-sources.ts b/packages/server/src/runtime/session-sources.tsindex da22c737..8c58891b 100644--- a/packages/server/src/runtime/session-sources.ts+++ b/packages/server/src/runtime/session-sources.ts@@ -12,6 +12,7 @@*/import type { SessionSource } from "../api/types.js";import { Component } from "@prismshadow/penguin-core/kernel";+import type { SessionOrigins } from "../mechanisms/sessions.js";/*** Narrows an untrusted value (on-disk Trace JSON / forwarded meta) to a SessionSource:@@ -23,7 +24,7 @@ export function asSessionSource(v: unknown): SessionSource | undefined {}@Component()-export class SessionSources {+export class SessionSources implements SessionOrigins {private readonly map = new Map<string, SessionSource | null>();/** Records a Session's origin as read from session_meta (`null` = meta seen, user-created). */diff --git a/packages/server/src/runtime/title-generator.ts b/packages/server/src/runtime/title-generator.tsindex 3a0bfc69..b77cd7bf 100644--- a/packages/server/src/runtime/title-generator.ts+++ b/packages/server/src/runtime/title-generator.ts@@ -29,16 +29,17 @@ import {truncateTitle,} from "@prismshadow/penguin-core";import type { ServerEvent } from "../api/types.js";-import type { SessionsRepo } from "../db/repos/sessions.js";import type { ChannelHub } from "./channel.js";import type { ErrorSink } from "./error-recorder.js";import type { RuntimeSession } from "./session-manager.js";-import type { UsageContext, UsageRecorder } from "./usage-recorder.js";+import type { UsageContext } from "./usage-recorder.js";+import type { UsageRecording } from "../mechanisms/observability.js";+import type { SessionIndex } from "../mechanisms/sessions.js";export interface TitleGeneratorDeps {- sessions: SessionsRepo;+ sessions: SessionIndex;channels: ChannelHub;- recorder: Pick<UsageRecorder, "record">;+ recorder: Pick<UsageRecording, "record">;/** Error persistence (optional: without it, only logs — same as before this was wired up). */errors?: ErrorSink;log?: (line: string) => void;diff --git a/packages/server/src/runtime/usage-recorder.ts b/packages/server/src/runtime/usage-recorder.tsindex 9218d5bb..c27f3e16 100644--- a/packages/server/src/runtime/usage-recorder.ts+++ b/packages/server/src/runtime/usage-recorder.ts@@ -16,9 +16,9 @@import { isEventMessage, isSessionMeta } from "@prismshadow/penguin-core";import type { OmniMessage } from "@prismshadow/penguin-core";import { formatLocalDate } from "../internal/dates.js";-import type { UsageRepo } from "../db/repos/usage.js";import { Component, Use } from "@prismshadow/penguin-core/kernel";-import type { Overrides } from "../hmr/capabilities.js";+import type { Clock } from "../hmr/capabilities.js";+import type { UsageRecording, UsageStore } from "../mechanisms/observability.js";/** Attribution context for one record (top-level Session scope). */export interface UsageContext {@@ -36,17 +36,12 @@ export interface UsageContext {export const ORIGIN_MODELS_MAX = 1000;@Component()-export class UsageRecorder {+export class UsageRecorder implements UsageRecording {/** Subagent model attribution mapping: origin's last session_id → paired reference (session_id is globally unique). */private readonly originModels = new Map<string, { provider: string; modelId: string }>();- @Use() private readonly usage!: UsageRepo;- @Use() private readonly overrides!: Overrides;- private now: () => Date = () => new Date();-- setup(): void {- this.now = this.overrides.value().now ?? this.now;- }+ @Use() private readonly usage!: UsageStore;+ @Use() private readonly clock!: Clock;/** Consume one outgoing message; messages other than session_meta / token_usage are a no-op. */async record(ctx: UsageContext, msg: OmniMessage): Promise<void> {@@ -81,7 +76,7 @@ export class UsageRecorder {provider: ctx.provider,modelId: ctx.modelId,});- const now = this.now();+ const now = this.clock.now();const base = {ts: now.toISOString(),date: formatLocalDate(now),diff --git a/packages/server/src/services/admin-service.ts b/packages/server/src/services/admin-service.tsindex 0f1219ff..3c76251e 100644--- a/packages/server/src/services/admin-service.ts+++ b/packages/server/src/services/admin-service.ts@@ -13,31 +13,22 @@import type { UserInfo } from "../api/types.js";import { HttpError } from "../http/errors.js";import { ADMIN_USER_ID, MIN_PASSWORD_LENGTH, toUserInfo } from "../auth/service.js";-import { SCRYPT_COST, hashPassword } from "../auth/password.js";-import type { ProjectsRepo } from "../db/repos/projects.js";-import type { AuthSessionsRepo } from "../db/repos/auth-sessions.js";-import type { UserRow, UsersRepo } from "../db/repos/users.js";+import type { PasswordHasher } from "../auth/password.js";+import type { UserRow } from "../db/repos/users.js";import { SEMANTIC_ID_RULE, USERNAME_PATTERN } from "./ids.js";-import type { ProjectService } from "./project-service.js";import { Component, Use } from "@prismshadow/penguin-core/kernel";-import type { Overrides } from "../hmr/capabilities.js";+import type { Clock } from "../hmr/capabilities.js";+import type { Admin, AuthSessions, Users } from "../mechanisms/identity.js";+import type { ProjectLifecycle, Projects } from "../mechanisms/projects.js";@Component()-export class AdminService {- @Use() private readonly users!: UsersRepo;- @Use() private readonly authSessions!: AuthSessionsRepo;- @Use() private readonly projects!: ProjectsRepo;- @Use() private readonly projectService!: ProjectService;- @Use() private readonly overrides!: Overrides;- private now: () => Date = () => new Date();- /** scrypt work factor for hashes this service writes; a test double lowers it. */- private hashCost: number = SCRYPT_COST;-- setup(): void {- const overrides = this.overrides.value();- this.now = overrides.now ?? this.now;- this.hashCost = overrides.passwordHashCost ?? SCRYPT_COST;- }+export class AdminService implements Admin {+ @Use() private readonly users!: Users;+ @Use() private readonly authSessions!: AuthSessions;+ @Use() private readonly projects!: Projects;+ @Use() private readonly projectService!: ProjectLifecycle;+ @Use() private readonly clock!: Clock;+ @Use() private readonly hasher!: PasswordHasher;/*** Every account, for the admin user backend. The avatar is dropped on the way out: a stored@@ -67,12 +58,12 @@ export class AdminService {}const user: UserRow = {userId,- passwordHash: await hashPassword(password, this.hashCost),+ passwordHash: await this.hasher.hash(password),isAdmin: false,passwordIsInitial: true,displayName: null,avatar: null,- createdAt: this.now().toISOString(),+ createdAt: this.clock.now().toISOString(),};this.users.insert(user);try {@@ -100,11 +91,7 @@ export class AdminService {throw new HttpError(400, "invalid_password", "Password must be at least 8 characters.");}const isSelfAdminReset = userId === ADMIN_USER_ID;- this.users.updatePassword(- userId,- await hashPassword(password, this.hashCost),- !isSelfAdminReset,- );+ this.users.updatePassword(userId, await this.hasher.hash(password), !isSelfAdminReset);// Force re-login: delete every session row for this user.this.authSessions.deleteByUser(userId);}diff --git a/packages/server/src/services/agent-config-service.ts b/packages/server/src/services/agent-config-service.tsindex f4ee87f1..1d0b3ecb 100644--- a/packages/server/src/services/agent-config-service.ts+++ b/packages/server/src/services/agent-config-service.ts@@ -69,7 +69,8 @@ import {} from "../http/validate.js";import { maskApiKey } from "./project-config-service.js";import { Component, Use } from "@prismshadow/penguin-core/kernel";-import type { Config } from "../hmr/capabilities.js";+import type { Config, Paths } from "../hmr/capabilities.js";+import type { AgentConfig } from "../mechanisms/agents.js";const COMPACTION_MODES = ["summarize", "discard"] as const;@@ -87,10 +88,10 @@ export interface AgentConfigView {}@Component()-export class AgentConfigService {- @Use() private readonly config!: Config;+export class AgentConfigService implements AgentConfig {+ @Use() private readonly paths!: Paths;private get root(): string {- return this.config.root;+ return this.paths.root;}/** Whether the Agent exists (determined by the presence of system_config.yaml, matching the CLI's convention). */diff --git a/packages/server/src/services/agent-routes.ts b/packages/server/src/services/agent-routes.tsindex da87bef8..4dbad9df 100644--- a/packages/server/src/services/agent-routes.ts+++ b/packages/server/src/services/agent-routes.ts@@ -2,17 +2,14 @@ import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";import type { AppEnv } from "../auth/middleware.js";import type { Hono } from "hono";import type { Config } from "../hmr/capabilities.js";-import type { ProjectAccess } from "./project-access.js";-import type { AgentConfigService } from "./agent-config-service.js";-import type { MemoryService } from "./memory-service.js";-import type { SnapshotService } from "./snapshot-service.js";-import type { BenchmarkService } from "./benchmark-service.js";-import type { TraceService } from "./trace-service.js";import { memoryRoutes } from "../http/routes/memory.js";import { benchmarksRoutes } from "../http/routes/benchmarks.js";import { agentSkillsRoutes } from "../http/routes/skills.js";import { agentTransferRoutes } from "../http/routes/agent-transfer.js";import { agentTracesRoutes } from "../http/routes/agent-traces.js";+import type { AgentConfig, Benchmarks, Memory, Snapshots } from "../mechanisms/agents.js";+import type { Access } from "../mechanisms/projects.js";+import type { Traces } from "../mechanisms/traces.js";/*** The Agent-scoped route groups: memory, skills, transfer, traces — and benchmarks, which@@ -56,12 +53,12 @@ import { agentTracesRoutes } from "../http/routes/agent-traces.js";})export class AgentRoutes {@Use() private readonly config!: Config;- @Use() private readonly access!: ProjectAccess;- @Use() private readonly agentConfig!: AgentConfigService;- @Use() private readonly memory!: MemoryService;- @Use() private readonly snapshots!: SnapshotService;- @Use() private readonly benchmarks!: BenchmarkService;- @Use() private readonly traces!: TraceService;+ @Use() private readonly access!: Access;+ @Use() private readonly agentConfig!: AgentConfig;+ @Use() private readonly memory!: Memory;+ @Use() private readonly snapshots!: Snapshots;+ @Use() private readonly benchmarks!: Benchmarks;+ @Use() private readonly traces!: Traces;@Bind("agents.memory") memoryRoutes!: Hono<AppEnv>;@Bind("agents.benchmarks") benchmarksRoutes!: Hono<AppEnv>;@Bind("agents.skills") skillsRoutes!: Hono<AppEnv>;diff --git a/packages/server/src/services/agent-service.ts b/packages/server/src/services/agent-service.tsindex 8a0372ba..647a2066 100644--- a/packages/server/src/services/agent-service.ts+++ b/packages/server/src/services/agent-service.ts@@ -33,16 +33,15 @@ import {parseSkillFrontmatter,} from "@prismshadow/penguin-core";import type { LibraryPlugin } from "@prismshadow/penguin-core";-import type { AgentsRepo } from "../db/repos/agents.js";import { SEMANTIC_ID_PATTERN, SEMANTIC_ID_RULE } from "./ids.js";-import type { AgentConfigService } from "./agent-config-service.js";-import type { SnapshotService } from "./snapshot-service.js";import { isTopicFileName } from "./memory-service.js";import type { PluginUpdateRef } from "../api/types.js";import { resolveLibraryPlugins } from "./plugin-library.js";import { resolveDirectorySkills } from "./directory-skills.js";import { Component, Use } from "@prismshadow/penguin-core/kernel";-import type { Config } from "../hmr/capabilities.js";+import type { Config, Paths } from "../hmr/capabilities.js";+import type { AgentConfig, AgentLifecycle, Snapshots } from "../mechanisms/agents.js";+import type { AgentIndex } from "../mechanisms/projects.js";/*** How much of a SKILL.md is read to answer "which version is installed" (see `installedSkills`).@@ -94,14 +93,14 @@ export interface AgentListItem {}@Component()-export class AgentService {- @Use() private readonly config!: Config;+export class AgentService implements AgentLifecycle {+ @Use() private readonly paths!: Paths;private get root(): string {- return this.config.root;+ return this.paths.root;}- @Use() private readonly agents!: AgentsRepo;- @Use() private readonly agentConfig!: AgentConfigService;- @Use() private readonly snapshots!: SnapshotService;+ @Use() private readonly agents!: AgentIndex;+ @Use() private readonly agentConfig!: AgentConfig;+ @Use() private readonly snapshots!: Snapshots;/** Union of DB index ∪ directory scan; unmanaged directory Agents are backfilled into the DB. */async listAgents(projectId: string): Promise<AgentListItem[]> {diff --git a/packages/server/src/services/benchmark-service.ts b/packages/server/src/services/benchmark-service.tsindex fcd45209..c5df890a 100644--- a/packages/server/src/services/benchmark-service.ts+++ b/packages/server/src/services/benchmark-service.ts@@ -34,14 +34,12 @@ import type {CaseMaterial,WorkspaceFilesResponse,} from "../api/types.js";-import type {- WorkspaceFileContent,- WorkspaceFileReadOptions,- WorkspaceFilesService,-} from "./workspace-files-service.js";+import type { WorkspaceFileContent, WorkspaceFileReadOptions } from "./workspace-files-service.js";import { HttpError } from "../http/errors.js";import { Component, Use } from "@prismshadow/penguin-core/kernel";-import type { Config } from "../hmr/capabilities.js";+import type { Paths } from "../hmr/capabilities.js";+import type { Benchmarks } from "../mechanisms/agents.js";+import type { WorkspaceFiles } from "../mechanisms/workspace.js";const STATEMENT_TITLE_READ_BYTES = 64 * 1024;@@ -223,12 +221,12 @@ function toEvaluation(v: unknown): BenchmarkEvaluation | null {}@Component()-export class BenchmarkService {- @Use() private readonly config!: Config;+export class BenchmarkService implements Benchmarks {+ @Use() private readonly paths!: Paths;private get root(): string {- return this.config.root;+ return this.paths.root;}- @Use() private readonly workspaceFiles!: WorkspaceFilesService;+ @Use() private readonly workspaceFiles!: WorkspaceFiles;async list(projectId: string): Promise<BenchmarksResponse> {const dir = benchmarksDir(this.root, projectId);diff --git a/packages/server/src/services/memory-service.ts b/packages/server/src/services/memory-service.tsindex 7ad25133..40804714 100644--- a/packages/server/src/services/memory-service.ts+++ b/packages/server/src/services/memory-service.ts@@ -51,9 +51,9 @@ import type {} from "../api/types.js";import { HttpError } from "../http/errors.js";import { badRequest } from "../http/validate.js";-import type { AgentConfigService } from "./agent-config-service.js";import { Component, Use } from "@prismshadow/penguin-core/kernel";-import type { Config } from "../hmr/capabilities.js";+import type { Config, Paths } from "../hmr/capabilities.js";+import type { AgentConfig, Memory } from "../mechanisms/agents.js";/** Scope directory names: what core's key generator produces (a safe base may start with `_`), plus the leeway of a hand-made directory. Excludes `.`/`..` and any separator, so the name can never climb out of `memory/`. */const SCOPE_KEY_PATTERN = /^[A-Za-z0-9_][A-Za-z0-9._-]*$/;@@ -210,12 +210,12 @@ function parseTransferDocument(payload: unknown): {}@Component()-export class MemoryService {- @Use() private readonly config!: Config;+export class MemoryService implements Memory {+ @Use() private readonly paths!: Paths;private get root(): string {- return this.config.root;+ return this.paths.root;}- @Use() private readonly agentConfigService!: AgentConfigService;+ @Use() private readonly agentConfigService!: AgentConfig;/** The tab's landing payload: the Agent-level switch and one entry per scope directory. */async overview(projectId: string, agentId: string): Promise<MemoryOverviewResponse> {diff --git a/packages/server/src/services/model-oauth-service.ts b/packages/server/src/services/model-oauth-service.tsindex 092728c1..594bd3b7 100644--- a/packages/server/src/services/model-oauth-service.ts+++ b/packages/server/src/services/model-oauth-service.ts@@ -29,7 +29,7 @@ import type { ModelProviderOAuth } from "@prismshadow/penguin-core/model-catalogimport { HttpError } from "../http/errors.js";import { badRequest } from "../http/validate.js";import { Component, Use } from "@prismshadow/penguin-core/kernel";-import type { ProjectConfigService } from "./project-config-service.js";+import type { ModelOAuth, ProjectConfigStore } from "../mechanisms/projects.js";/** How the user gets the authorization code back to the harness. */export type ModelOAuthMode = "callback" | "manual";@@ -204,9 +204,9 @@ export type ApplyGroupKey = () => Promise<number>;@Component()-export class ModelOAuthService {+export class ModelOAuthService implements ModelOAuth {private readonly flows = new Map<string, Flow>();- @Use() private readonly projectConfig!: ProjectConfigService;+ @Use() private readonly projectConfig!: ProjectConfigStore;private applyGroupKey: ApplyGroupKey = (projectId, provider, apiKey) =>this.projectConfig.setGroupApiKey(projectId, provider, apiKey);/** Replaced in tests so they never reach the network. */diff --git a/packages/server/src/services/project-access.ts b/packages/server/src/services/project-access.tsindex 500d748c..b1e2f812 100644--- a/packages/server/src/services/project-access.ts+++ b/packages/server/src/services/project-access.ts@@ -8,17 +8,16 @@*/import type { ProjectRole, ProjectSummary } from "../api/types.js";import { HttpError } from "../http/errors.js";-import type { MembersRepo } from "../db/repos/members.js";-import type { ProjectRow, ProjectsRepo } from "../db/repos/projects.js";+import type { ProjectRow } from "../db/repos/projects.js";import { Component, Use } from "@prismshadow/penguin-core/kernel";-import type { ProjectConfigService } from "./project-config-service.js";+import type { Access, Members, ProjectConfigStore, Projects } from "../mechanisms/projects.js";@Component()-export class ProjectAccess {- @Use() private readonly projects!: ProjectsRepo;- @Use() private readonly members!: MembersRepo;+export class ProjectAccess implements Access {+ @Use() private readonly projects!: Projects;+ @Use() private readonly members!: Members;/** Display names come from each project's own config file. */- @Use() private readonly projectConfig!: ProjectConfigService;+ @Use() private readonly projectConfig!: ProjectConfigStore;/*** The sole implementation of the owner / member check: the row with a role whendiff --git a/packages/server/src/services/project-config-service.ts b/packages/server/src/services/project-config-service.tsindex 5d9a4b7a..34a05885 100644--- a/packages/server/src/services/project-config-service.ts+++ b/packages/server/src/services/project-config-service.ts@@ -84,9 +84,10 @@ import {} from "./vision-detect.js";import type { PricingRates, TieredRates } from "./usage-service.js";import { Component, Use } from "@prismshadow/penguin-core/kernel";-import type { Config } from "../hmr/capabilities.js";+import type { Config, Paths } from "../hmr/capabilities.js";+import type { ProjectConfigStore } from "../mechanisms/projects.js";-type RawTable = Record<string, unknown>;+export type RawTable = Record<string, unknown>;/*** API key masking: length <=12 -> `***`, otherwise `first4…last4`; plaintext is@@ -257,7 +258,7 @@ const SPEED_PROBE_PROMPT ="Count from 1 to 50 as a comma-separated list, and nothing else. Do not think or explain.\n<think></think>";@Component()-export class ProjectConfigService {+export class ProjectConfigService implements ProjectConfigStore {/*** Parsed-table cache, one entry per Project, keyed by the config file's mtime as* recorded at read time (a fresh mtime is stored as a never-matching sentinel, see@@ -267,9 +268,9 @@ export class ProjectConfigService {*/private readonly cache = new Map<string, { mtimeMs: number; table: RawTable }>();- @Use() private readonly config!: Config;+ @Use() private readonly paths!: Paths;private get root(): string {- return this.config.root;+ return this.paths.root;}private filePath(projectId: string): string {diff --git a/packages/server/src/services/project-service.ts b/packages/server/src/services/project-service.tsindex 3eabf637..7c6d5bfc 100644--- a/packages/server/src/services/project-service.ts+++ b/packages/server/src/services/project-service.ts@@ -14,14 +14,8 @@ import fs from "node:fs/promises";import { DEFAULT_PROJECT_ID, projectDir, provisionProjectAgents } from "@prismshadow/penguin-core";import type { MemberInfo, ProjectRole, ProjectSummary } from "../api/types.js";import { HttpError } from "../http/errors.js";-import type { AgentsRepo } from "../db/repos/agents.js";-import type { ErrorsRepo } from "../db/repos/errors.js";-import type { MembersRepo } from "../db/repos/members.js";-import type { ProjectRow, ProjectsRepo } from "../db/repos/projects.js";-import type { SessionsRepo } from "../db/repos/sessions.js";-import type { SchedulesRepo } from "../db/repos/schedules.js";-import type { UsageRepo } from "../db/repos/usage.js";-import type { UserRow, UsersRepo } from "../db/repos/users.js";+import type { ProjectRow } from "../db/repos/projects.js";+import type { UserRow } from "../db/repos/users.js";import type { SessionManager } from "../runtime/session-manager.js";import {PROJECT_ID_MAX_LENGTH,@@ -29,11 +23,20 @@ import {SEMANTIC_ID_PATTERN,SEMANTIC_ID_RULE,} from "./ids.js";-import type { ProjectAccess } from "./project-access.js";-import type { ProjectConfigService } from "./project-config-service.js";-import type { TraceIndexService } from "./trace-index.js";import { Component, Use, Interface } from "@prismshadow/penguin-core/kernel";-import type { Config } from "../hmr/capabilities.js";+import type { Config, Paths } from "../hmr/capabilities.js";+import type {+ Access,+ AgentIndex,+ Members,+ ProjectConfigStore,+ ProjectLifecycle,+ Projects,+} from "../mechanisms/projects.js";+import type { Users } from "../mechanisms/identity.js";+import type { Schedules, SessionIndex } from "../mechanisms/sessions.js";+import type { ErrorLog, UsageStore } from "../mechanisms/observability.js";+import type { TraceIndex } from "../mechanisms/traces.js";/** Fallback timeout for waiting on runs to settle before deleting a Project. */const ABORT_SETTLE_TIMEOUT_MS = 5000;@@ -48,25 +51,25 @@ async function dirExists(path: string): Promise<boolean> {}@Component()-export class ProjectService {- @Use() private readonly config!: Config;+export class ProjectService implements ProjectLifecycle {+ @Use() private readonly paths!: Paths;private get root(): string {- return this.config.root;+ return this.paths.root;}- @Use() private readonly access!: ProjectAccess;- @Use() private readonly users!: UsersRepo;- @Use() private readonly projects!: ProjectsRepo;- @Use() private readonly members!: MembersRepo;- @Use() private readonly agents!: AgentsRepo;- @Use() private readonly sessions!: SessionsRepo;- @Use() private readonly usage!: UsageRepo;- @Use() private readonly errors!: ErrorsRepo;- @Use() private readonly schedules!: SchedulesRepo;- @Use() private readonly projectConfig!: ProjectConfigService;+ @Use() private readonly access!: Access;+ @Use() private readonly users!: Users;+ @Use() private readonly projects!: Projects;+ @Use() private readonly members!: Members;+ @Use() private readonly agents!: AgentIndex;+ @Use() private readonly sessions!: SessionIndex;+ @Use() private readonly usage!: UsageStore;+ @Use() private readonly errors!: ErrorLog;+ @Use() private readonly schedules!: Schedules;+ @Use() private readonly projectConfig!: ProjectConfigStore;/** What destroying a Project needs of the session runtime — declared at the consumer. */@Use() private readonly manager!: ProjectRuns;/** Trace-index cleanup on Project destruction (rows describe files removed with the Project dir). */- @Use() private readonly traceIndex!: TraceIndexService;+ @Use() private readonly traceIndex!: TraceIndex;// Access control lives in ProjectAccess (services/project-access.ts); these delegate so// in-package callers keep one entry point.diff --git a/packages/server/src/services/session-service.ts b/packages/server/src/services/session-service.tsindex 5a1d0a06..e5af87b9 100644--- a/packages/server/src/services/session-service.ts+++ b/packages/server/src/services/session-service.ts@@ -26,13 +26,14 @@ import type {} from "../api/types.js";import { HttpError, isMissingCredential, modelCredentialMissing } from "../http/errors.js";import { badRequest } from "../http/validate.js";-import type { SessionRow, SessionsRepo } from "../db/repos/sessions.js";+import type { SessionRow } from "../db/repos/sessions.js";import type { SessionManager } from "../runtime/session-manager.js";import { asSessionSource } from "../runtime/session-sources.js";-import type { SessionSources } from "../runtime/session-sources.js";import { TraceIndexService, traceFilePath } from "./trace-index.js";import { matchesWorkspaceGroup } from "./workspace-group.js";-import type { ProjectConfigService } from "./project-config-service.js";+import type { TraceIndex, TraceIndexStore } from "../mechanisms/traces.js";+import type { SessionIndex, SessionOrigins } from "../mechanisms/sessions.js";+import type { ProjectConfigStore } from "../mechanisms/projects.js";const SESSION_ID_TS_RE = /^session-(\d{4})-(\d{2})-(\d{2})-(\d{2})-(\d{2})-(\d{2})-[0-9a-f]{8}$/;@@ -47,13 +48,15 @@ export function sessionIdCreatedAt(sessionId: string): string | null {export interface SessionServiceDeps {root: string;- sessions: SessionsRepo;+ sessions: SessionIndex;manager: SessionManager;- projectConfig: ProjectConfigService;+ projectConfig: ProjectConfigStore;/** In-process origin registry derived from session_meta (the DB stores no source column). */- sources: SessionSources;+ sources: SessionOrigins;/** Trace-file index: discovery / adoption / stats serve from it (mtime-gated reconciler; no per-request walks). */- traceIndex: TraceIndexService;+ traceIndex: TraceIndex;+ /** The index rows themselves (files and sessions), for the reads the service does directly. */+ traceStore: TraceIndexStore;/*** Admin proxy-settings threading (same getter the session loader passes, see* createCoreSessionLoader): the runtime created here is adopted by the manager and@@ -132,7 +135,7 @@ export class SessionService {const known = this.deps.sources.get(row.sessionId);if (known !== undefined) return known ?? undefined;if (!hasTrace) return undefined;- const facts = this.deps.traceIndex.repo.getSession(row.sessionId);+ const facts = this.deps.traceStore.getSession(row.sessionId);if (!facts?.metaRead) return undefined; // Unreadable/unregistered: stay unknown, retry on the next list.this.deps.sources.set(row.sessionId, facts.source);return facts.source ?? undefined;@@ -298,7 +301,7 @@ export class SessionService {// this used to walk the Agent's ENTIRE trace history on every agents-list request):// the date is the shard's date directory (local yyyy-mm-dd, core's writing convention).await this.deps.traceIndex.reconcileAgent(projectId, agentId);- for (const f of this.deps.traceIndex.repo.listFilesByAgent(projectId, agentId)) {+ for (const f of this.deps.traceStore.listFilesByAgent(projectId, agentId)) {mark(f.date, f.sessionId);}// DB index: the creation day also counts as active (a Session that hasn't run a Task yet produces no Trace).@@ -440,20 +443,12 @@ export class SessionService {*/async latestTracePath(row: SessionRow): Promise<string | undefined> {await this.deps.traceIndex.reconcileAgent(row.projectId, row.agentId);- let files = this.deps.traceIndex.repo.listFilesBySession(- row.projectId,- row.agentId,- row.sessionId,- );+ let files = this.deps.traceStore.listFilesBySession(row.projectId, row.agentId, row.sessionId);if (files.length === 0) {// Index miss with disk possibly ahead: one forced diff, then retry (the consumers'// rule — a stale index costs one extra scan, never a missing resume shard).await this.deps.traceIndex.reconcileAgent(row.projectId, row.agentId, { force: true });- files = this.deps.traceIndex.repo.listFilesBySession(- row.projectId,- row.agentId,- row.sessionId,- );+ files = this.deps.traceStore.listFilesBySession(row.projectId, row.agentId, row.sessionId);}const latest = files.at(-1);return latest === undefined ? undefined : traceFilePath(this.deps.root, latest);@@ -468,7 +463,7 @@ export class SessionService {private async discoverTraces(projectId: string, agentId: string): Promise<Set<string>> {await this.deps.traceIndex.reconcileAgent(projectId, agentId);const out = new Set<string>();- for (const f of this.deps.traceIndex.repo.listFilesByAgent(projectId, agentId)) {+ for (const f of this.deps.traceStore.listFilesByAgent(projectId, agentId)) {out.add(f.sessionId);}return out;@@ -512,7 +507,7 @@ export class SessionService {agentId: string,sessionId: string,): SessionRow | null {- const facts = this.deps.traceIndex.repo.getSession(sessionId);+ const facts = this.deps.traceStore.getSession(sessionId);if (!facts?.metaRead) return null; // Corrupt/unreadable head: skip (does not block the list; retried by a later reconcile)// An older Trace version's session_meta lacks provider (the model reference// wasn't split into separate fields yet): no backward compat, skip adoptiondiff --git a/packages/server/src/services/snapshot-service.ts b/packages/server/src/services/snapshot-service.tsindex f16217cf..dddca2ae 100644--- a/packages/server/src/services/snapshot-service.ts+++ b/packages/server/src/services/snapshot-service.ts@@ -26,7 +26,8 @@ import {import { HttpError } from "../http/errors.js";import { badRequest } from "../http/validate.js";import { Component, Use } from "@prismshadow/penguin-core/kernel";-import type { Config } from "../hmr/capabilities.js";+import type { Config, Paths } from "../hmr/capabilities.js";+import type { Snapshots } from "../mechanisms/agents.js";/** Vault file name inside a snapshot/import package (used for archive filtering). */const VAULT_BASENAME = ".vault.toml";@@ -36,10 +37,10 @@ function isVaultEntry(entryPath: string): boolean {}@Component()-export class SnapshotService {- @Use() private readonly config!: Config;+export class SnapshotService implements Snapshots {+ @Use() private readonly paths!: Paths;private get root(): string {- return this.config.root;+ return this.paths.root;}/** Current Agent State version number (missing field treated as 1); throws 404 if the Agent doesn't exist. */diff --git a/packages/server/src/services/trace-index.ts b/packages/server/src/services/trace-index.tsindex b92515ec..3551307e 100644--- a/packages/server/src/services/trace-index.ts+++ b/packages/server/src/services/trace-index.ts@@ -46,10 +46,11 @@ import { TraceIndexRepo } from "../db/repos/trace-index.js";import { cacheable, statMtime } from "../internal/mtime-gate.js";import { readTraceHead } from "../internal/trace-head.js";import { asSessionSource } from "../runtime/session-sources.js";-import type { SessionSources } from "../runtime/session-sources.js";import { fallbackTitle } from "../runtime/title-generator.js";import { Component, Use } from "@prismshadow/penguin-core/kernel";-import type { Config } from "../hmr/capabilities.js";+import type { Paths } from "../hmr/capabilities.js";+import type { TraceIndex, TraceIndexStore } from "../mechanisms/traces.js";+import type { SessionOrigins } from "../mechanisms/sessions.js";const TRACE_FILE_RE = /^(.+)_(\d{3})\.jsonl$/;@@ -115,7 +116,7 @@ interface SeenDirs {}@Component()-export class TraceIndexService {+export class TraceIndexService implements TraceIndex {private readonly seen = new Map<string, SeenDirs>();private readonly inflight = new Map<string, Promise<void>>();/**@@ -125,13 +126,13 @@ export class TraceIndexService {*/readonly counters = { gateStats: 0, dirScans: 0, headReads: 0 };- @Use() private readonly config!: Config;+ @Use() private readonly paths!: Paths;private get root(): string {- return this.config.root;+ return this.paths.root;}- @Use() readonly repo!: TraceIndexRepo;+ @Use() readonly repo!: TraceIndexStore;/** Shared origin registry: registration-time classification publishes into it (single source of truth for `source`). */- @Use() private readonly sources?: SessionSources;+ @Use() private readonly sources?: SessionOrigins;/*** Brings one Agent's index in step with disk. Hot path: one root stat, then thediff --git a/packages/server/src/services/trace-service.ts b/packages/server/src/services/trace-service.tsindex df06f727..0bbf81c0 100644--- a/packages/server/src/services/trace-service.ts+++ b/packages/server/src/services/trace-service.ts@@ -50,14 +50,13 @@ import type {TraceToolSpan,UsageTrendPointInTrace,} from "../api/types.js";-import type { SessionRow, SessionsRepo } from "../db/repos/sessions.js";+import type { SessionRow } from "../db/repos/sessions.js";import type { TraceFileRow, TraceSessionRow } from "../db/repos/trace-index.js";import { HttpError } from "../http/errors.js";import { formatLocalDate } from "../internal/dates.js";-import type { SessionSources } from "../runtime/session-sources.js";import { ratesAt, requestCostUsd } from "./usage-service.js";import type { PricingLookup, TieredRates } from "./usage-service.js";-import type { ProjectConfigService } from "./project-config-service.js";+import type { ProjectConfigStore } from "../mechanisms/projects.js";import {cloneScanState,deserializePrefix,@@ -78,7 +77,9 @@ import { buildContextBreakdown, emptyContextBreakdown } from "./context-breakdowimport { sessionIdCreatedAt } from "./session-service.js";import { TraceIndexService, traceFilePath } from "./trace-index.js";import { Component, Use } from "@prismshadow/penguin-core/kernel";-import type { Config } from "../hmr/capabilities.js";+import type { Paths } from "../hmr/capabilities.js";+import type { TraceIndex, TraceIndexStore, Traces } from "../mechanisms/traces.js";+import type { SessionIndex, SessionOrigins } from "../mechanisms/sessions.js";const TRACE_FILE_RE = /^(.+)_(\d{3})\.jsonl$/;@@ -252,17 +253,18 @@ interface TraceSessionFacts {}@Component()-export class TraceService {- @Use() private readonly config!: Config;+export class TraceService implements Traces {+ @Use() private readonly paths!: Paths;private get root(): string {- return this.config.root;+ return this.paths.root;}- @Use() private readonly index!: TraceIndexService;+ @Use() private readonly index!: TraceIndex;+ @Use() private readonly store!: TraceIndexStore;/** DB rows supplying titles / archived / workspace / client (narrow tests may omit). */- @Use() private readonly sessions?: SessionsRepo;+ @Use() private readonly sessions?: SessionIndex;/** The shared in-process Session-origin registry, single source of truth for `source` (narrow tests may omit). */- @Use() private readonly sources?: SessionSources;- @Use() private readonly projectConfig?: ProjectConfigService;+ @Use() private readonly sources?: SessionOrigins;+ @Use() private readonly projectConfig?: ProjectConfigStore;/*** The Project's current price for a paired reference — the same lookup the cost center* prices `usage_records` with, so the analysis' per-turn cost and the toolbar's figure come@@ -292,10 +294,10 @@ export class TraceService {sessionId: string,): Promise<LocatedFile[]> {await this.index.reconcileAgent(projectId, agentId);- let rows = this.index.repo.listFilesBySession(projectId, agentId, sessionId);+ let rows = this.store.listFilesBySession(projectId, agentId, sessionId);if (rows.length === 0) {await this.index.reconcileAgent(projectId, agentId, { force: true });- rows = this.index.repo.listFilesBySession(projectId, agentId, sessionId);+ rows = this.store.listFilesBySession(projectId, agentId, sessionId);}return rows.map((r) => ({path: traceFilePath(this.root, r),@@ -368,11 +370,11 @@ export class TraceService {childSid: string,ctx: { projectScanned: boolean },): Promise<string | null> {- const hit = this.index.repo.findAgentBySession(projectId, childSid);+ const hit = this.store.findAgentBySession(projectId, childSid);if (hit !== null || ctx.projectScanned) return hit;ctx.projectScanned = true;await this.index.reconcileProject(projectId, { force: true });- return this.index.repo.findAgentBySession(projectId, childSid);+ return this.store.findAgentBySession(projectId, childSid);}/** A child session's concatenated raw shard messages, memoized per request; null = no Trace located. */@@ -496,7 +498,7 @@ export class TraceService {for (let j = 0; j <= upto; j++) {const file = files[j]!;const cached = deserializePrefix(- this.index.repo.getPageStats(projectId, agentId, sessionId, file.index),+ this.store.getPageStats(projectId, agentId, sessionId, file.index),);if (cached !== null) {states.push(cached);@@ -510,7 +512,7 @@ export class TraceService {() => {},(sid) => this.aggregateChild(projectId, sid, ctx),);- this.index.repo.setPageStats(+ this.store.setPageStats(projectId,agentId,sessionId,@@ -1457,7 +1459,7 @@ export class TraceService {opts: { category?: SessionCategory } = {},): Promise<AgentTracesResponse> {await this.index.reconcileAgent(projectId, agentId);- const files = this.index.repo.listFilesByAgent(projectId, agentId);+ const files = this.store.listFilesByAgent(projectId, agentId);if (paging) return this.agentTracesPage(projectId, agentId, files, paging, opts);const byDate = new Map<string, Map<string, { index: number; sizeBytes: number }[]>>();for (const f of files) {@@ -1529,7 +1531,7 @@ export class TraceService {(this.sessions?.listByAgent(projectId, agentId) ?? []).map((r) => [r.sessionId, r]),);const factsBySession = new Map(- this.index.repo.listSessionsByAgent(projectId, agentId).map((r) => [r.sessionId, r]),+ this.store.listSessionsByAgent(projectId, agentId).map((r) => [r.sessionId, r]),);const ids = [...bySession.keys()].sort((a, b) => b.localeCompare(a));// Classify every group once; the same result drives the category filter, the@@ -1575,7 +1577,7 @@ export class TraceService {try {sizeBytes = (await fs.stat(traceFilePath(this.root, f))).size;if (sizeBytes !== f.sizeBytes) {- this.index.repo.updateFileSize(projectId, agentId, sessionId, f.fileIndex, sizeBytes);+ this.store.updateFileSize(projectId, agentId, sessionId, f.fileIndex, sizeBytes);}} catch {/* Vanished mid-request: serve the last observed size; the next reconcile settles the rows. */@@ -1737,7 +1739,7 @@ export class TraceService {private indexImportedSession(projectId: string, agentId: string, sessionId: string): void {const sessions = this.sessions;if (!sessions) return;- const facts = this.index.repo.getSession(sessionId);+ const facts = this.store.getSession(sessionId);if (!facts?.metaRead || facts.provider === null || facts.modelId === null) return;if (facts.source !== null) this.sources?.set(sessionId, facts.source);const createdAt = sessionIdCreatedAt(sessionId) ?? facts.firstTs ?? new Date().toISOString();diff --git a/packages/server/src/services/update-check-service.ts b/packages/server/src/services/update-check-service.tsindex 642a8ffc..41e42394 100644--- a/packages/server/src/services/update-check-service.ts+++ b/packages/server/src/services/update-check-service.ts@@ -18,13 +18,13 @@*/import { BUILD_DATE, VERSION, compareVersions, normalizeVersion } from "@prismshadow/penguin-core";import type { UpdateCheckResponse } from "../api/types.js";-import { Interface, Bind, Module, Provide, Use } from "@prismshadow/penguin-core/kernel";+import { Bind, Component, Interface, Use } from "@prismshadow/penguin-core/kernel";import type { AppEnv } from "../auth/middleware.js";import type { Hono } from "hono";-import type { ClassCtx } from "@prismshadow/penguin-core/kernel";-import { Config, Lifecycle, Overrides, RuntimeModule } from "../hmr/capabilities.js";-import { UpdateJobService } from "./update-job.js";+import type { ClassCtx, Opaque } from "@prismshadow/penguin-core/kernel";import { versionRoutes } from "../http/routes/version.js";+import type { Clock, Config, Lifecycle } from "../hmr/capabilities.js";+import type { UpdateJob } from "./update-job.js";/** Repository the released artifacts come from (same slug as cli/update.ts's REPO_SLUG). */const REPO_SLUG = "Prism-Shadow/penguin-harness";@@ -36,28 +36,29 @@ export const SUCCESS_TTL_MS = 60 * 60 * 1000;/** How long a failed lookup is served from cache (short: transient failures should heal). */export const FAILURE_TTL_MS = 10 * 60 * 1000;-export interface UpdateCheckServiceOptions {- /** Test double for the network call (defaults to global fetch). */- fetchImpl?: typeof fetch;- /** Injectable clock for TTL determinism in tests. */- now?: () => Date;- /** Environment to read PENGUIN_UPDATE_CHECK from (defaults to process.env). */- env?: Record<string, string | undefined>;+/** The network, as the update check reaches it; a test stands in a canned one. */+export abstract class HttpFetch extends Interface<{+ fetch(+ input: string,+ init?: Opaque<"RequestInit", RequestInit>,+ ): Promise<Opaque<"Response", Response>>;+}>() {}+@Component()+export class GlobalFetch implements HttpFetch {+ fetch(input: string, init?: RequestInit): Promise<Response> {+ return fetch(input, init);+ }}-export class UpdateCheckService {- private readonly fetchImpl: typeof fetch;- private readonly now: () => Date;- private readonly env: Record<string, string | undefined>;+@Component()+export class UpdateCheckService implements UpdateCheck {+ @Use() private readonly http!: HttpFetch;+ @Use() private readonly clock!: Clock;+ /** Environment to read PENGUIN_UPDATE_CHECK from; a test wires its own. */+ private env: Record<string, string | undefined> = process.env;private cached: { response: UpdateCheckResponse; expiresAt: number } | null = null;private inflight: Promise<UpdateCheckResponse> | null = null;- constructor(options: UpdateCheckServiceOptions = {}) {- this.fetchImpl = options.fetchImpl ?? fetch;- this.now = options.now ?? (() => new Date());- this.env = options.env ?? process.env;- }-/*** Never throws; never makes a network call when disabled or (without `force`) while* the cache is fresh. `force` — the web's manual "check for updates" action — skips@@ -78,11 +79,11 @@ export class UpdateCheckService {updateAvailable: false,releaseUrl: null,publishedAt: null,- checkedAt: this.now().toISOString(),+ checkedAt: this.clock.now().toISOString(),disabled: true,};}- if (!force && this.cached && this.now().getTime() < this.cached.expiresAt) {+ if (!force && this.cached && this.clock.now().getTime() < this.cached.expiresAt) {return this.cached.response;}this.inflight ??= this.lookup().finally(() => {@@ -95,7 +96,7 @@ export class UpdateCheckService {private async lookup(): Promise<UpdateCheckResponse> {const response = await this.resolveLatest();const ttl = response.error === undefined ? SUCCESS_TTL_MS : FAILURE_TTL_MS;- this.cached = { response, expiresAt: this.now().getTime() + ttl };+ this.cached = { response, expiresAt: this.clock.now().getTime() + ttl };return response;}@@ -106,7 +107,7 @@ export class UpdateCheckService {* without a usable tag_name is "bad_response".*/private async resolveLatest(): Promise<UpdateCheckResponse> {- const checkedAt = this.now().toISOString();+ const checkedAt = this.clock.now().toISOString();const base = { currentVersion: VERSION, buildDate: BUILD_DATE, checkedAt };const failure = (error: "network" | "rate_limited" | "bad_response"): UpdateCheckResponse => ({...base,@@ -119,7 +120,7 @@ export class UpdateCheckService {let res: Response;try {- res = await this.fetchImpl(LATEST_RELEASE_API, {+ res = await this.http.fetch(LATEST_RELEASE_API, {headers: { accept: "application/vnd.github+json", "user-agent": "penguin-server" },signal: AbortSignal.timeout(15_000),});@@ -149,7 +150,7 @@ export class UpdateCheckService {export abstract class UpdateCheck extends Interface<Pick<UpdateCheckService, "check">>() {}-@Module({+@Component({contributes: {"HttpModule.routes": [{@@ -161,22 +162,17 @@ export abstract class UpdateCheck extends Interface<Pick<UpdateCheckService, "ch],},})-export class VersionModule {- @Use(RuntimeModule) private readonly config!: Config;- @Use(RuntimeModule) private readonly overrides!: Overrides;- @Use(RuntimeModule) private readonly lifecycle!: Lifecycle;- @Provide() updateCheck!: UpdateCheck;+export class VersionRoutes {+ @Use() private readonly config!: Config;+ @Use() private readonly updateCheck!: UpdateCheck;+ @Use() private readonly updateJob!: UpdateJob;+ @Use() private readonly lifecycle!: Lifecycle;@Bind("VersionModule.routes") routes!: Hono<AppEnv>;setup() {- const overrides = this.overrides.value();- const updateCheck =- overrides.updateCheck ?? new UpdateCheckService(overrides.now ? { now: overrides.now } : {});- this.updateCheck = updateCheck;- const updateJob = overrides.updateJob ?? new UpdateJobService();this.routes = versionRoutes({config: this.config,- updateCheck,- updateJob,+ updateCheck: this.updateCheck,+ updateJob: this.updateJob,lifecycle: this.lifecycle,});}diff --git a/packages/server/src/services/update-job.ts b/packages/server/src/services/update-job.tsindex d4ed478f..10af8482 100644--- a/packages/server/src/services/update-job.ts+++ b/packages/server/src/services/update-job.ts@@ -32,6 +32,7 @@* A platform hot-swap while a run is in flight builds a fresh service that knows nothing of* it; the child finishes on its own and only its status is lost. Rare enough to accept.*/+import { Component, Interface } from "@prismshadow/penguin-core/kernel";import { spawn } from "node:child_process";import type { UpdateJobPhase, UpdateJobStatus, UpdateRunResponse } from "../api/types.js";@@ -153,11 +154,16 @@ export const spawnUpdateRunner: UpdateRunner = (cliEntry, onOutput) =>});});-export class UpdateJobService {+/** The self-update run as a node, so a test stands in a scripted runner for the real spawn. */+export abstract class UpdateJob extends Interface<Pick<UpdateJobService, "status" | "start">>() {}++@Component()+export class UpdateJobService implements UpdateJob {private current: UpdateJobStatus = { state: "idle", targetVersion: null, output: "" };private progress: UpdateProgress = INITIAL_PROGRESS;- constructor(private readonly runner: UpdateRunner = spawnUpdateRunner) {}+ /** The spawn a run goes through; a replacement supplies its own. */+ private readonly runner: UpdateRunner = spawnUpdateRunner;/** The job as it stands (idle / running with progress / done with its result). */status(): UpdateJobStatus {diff --git a/packages/server/src/services/usage-service.ts b/packages/server/src/services/usage-service.tsindex 51969dd1..cd46f39e 100644--- a/packages/server/src/services/usage-service.ts+++ b/packages/server/src/services/usage-service.ts@@ -29,14 +29,13 @@ import type {UsageResponse,UsageSeriesPoint,} from "../api/types.js";-import type { ErrorFilter, ErrorsRepo } from "../db/repos/errors.js";+import type { ErrorFilter } from "../db/repos/errors.js";import {catalogEntryFor,offPeakAt,offPeakScheduledRefs,} from "@prismshadow/penguin-core/model-catalog";import type {- UsageRepo,UsageModelSums,UsageGroupModelSums,UsageSeriesModelSums,@@ -52,8 +51,9 @@ import {} from "../internal/dates.js";import { badRequest } from "../http/validate.js";import { Component, Use } from "@prismshadow/penguin-core/kernel";-import type { Overrides } from "../hmr/capabilities.js";-import type { ProjectConfigService } from "./project-config-service.js";+import type { Clock } from "../hmr/capabilities.js";+import type { ErrorLog, UsageQueries, UsageStore } from "../mechanisms/observability.js";+import type { ProjectConfigStore } from "../mechanisms/projects.js";/*** Number of most-recent entries kept in the error detail table. Also the page size the whole@@ -189,18 +189,13 @@ function refKey(provider: string, modelId: string): string {}@Component()-export class UsageService {- @Use() private readonly usage!: UsageRepo;- @Use() private readonly errors!: ErrorsRepo;- @Use() private readonly projectConfig!: ProjectConfigService;- @Use() private readonly overrides!: Overrides;+export class UsageService implements UsageQueries {+ @Use() private readonly usage!: UsageStore;+ @Use() private readonly errors!: ErrorLog;+ @Use() private readonly projectConfig!: ProjectConfigStore;+ @Use() private readonly clock!: Clock;private lookupPricing: PricingLookup = (projectId, provider, modelId) =>this.projectConfig.getPricing(projectId, provider, modelId);- private now: () => Date = () => new Date();-- setup(): void {- this.now = this.overrides.value().now ?? this.now;- }/*** The catalog's time-based schedules, as the aggregations want them.@@ -220,7 +215,7 @@ export class UsageService {}async query(projectId: string, q: UsageQuery): Promise<UsageResponse> {- const today = formatLocalDate(this.now());+ const today = formatLocalDate(this.clock.now());// Top-level filter: agent + model (the cost center switches views by agent/model; the model filter is always sent as a pair).const base: UsageFilter = {};if (q.agentId !== undefined) base.agentId = q.agentId;@@ -244,7 +239,7 @@ export class UsageService {const todayRows = this.usage.bucketByModel(projectId, win(today, today), tiers);const last7dRows = this.usage.bucketByModel(projectId,- win(localDateMinusDays(this.now(), 6)),+ win(localDateMinusDays(this.clock.now(), 6)),tiers,);const totalRows = this.usage.bucketByModel(projectId, { ...win(q.from, q.to), ...ts }, tiers);@@ -257,7 +252,7 @@ export class UsageService {// Time series at the requested precision, zero-filled over the requested// range, defaulting to the last 30 days when no range is given.const granularity = q.granularity ?? "day";- const seriesFrom = q.from ?? localDateMinusDays(this.now(), 29);+ const seriesFrom = q.from ?? localDateMinusDays(this.clock.now(), 29);const seriesTo = q.to ?? today;// The series is zero-filled over the whole effective range: cap the bucket// count so an arbitrary range × precision combination cannot materialize andiff --git a/packages/server/src/services/workspace-files-service.ts b/packages/server/src/services/workspace-files-service.tsindex 764c8945..9c6457d2 100644--- a/packages/server/src/services/workspace-files-service.ts+++ b/packages/server/src/services/workspace-files-service.ts@@ -18,6 +18,7 @@ import type {import { HttpError } from "../http/errors.js";import { badRequest } from "../http/validate.js";import { Component } from "@prismshadow/penguin-core/kernel";+import type { WorkspaceFiles } from "../mechanisms/workspace.js";/** Per-file read cap (a safety limit since preview/download reads the whole file into memory). */const MAX_READ_BYTES = 50 * 1024 * 1024;@@ -126,7 +127,7 @@ export interface WorkspaceFileStat {}@Component()-export class WorkspaceFilesService {+export class WorkspaceFilesService implements WorkspaceFiles {/** Canonical path (realpath) of the Workspace root; 404 if it doesn't exist. */private async realBase(workspace: string): Promise<string> {try {diff --git a/packages/server/src/terminal/manager.ts b/packages/server/src/terminal/manager.tsindex 6762296e..cd2bb548 100644--- a/packages/server/src/terminal/manager.ts+++ b/packages/server/src/terminal/manager.ts@@ -25,10 +25,10 @@ import {import { Interface, Bind, Module, Provide, Use } from "@prismshadow/penguin-core/kernel";import type { AppEnv } from "../auth/middleware.js";import type { Hono } from "hono";-import { Hmr, ResourceGroups, RuntimeModule } from "../hmr/capabilities.js";+import { Hmr, ResourceGroups } from "../hmr/capabilities.js";import { terminalRoutes } from "./routes.js";import { identityFrom } from "./identity.js";-import type { AuthService } from "../auth/service.js";+import type { Auth } from "../mechanisms/identity.js";/** How long an exited session stays listable/attachable before it is disposed. */export const EXITED_SESSION_GRACE_MS = 5 * 60 * 1000;@@ -315,9 +315,9 @@ export type _Check = TerminalManager extends Terminals ? true : never;},})export class TerminalModule {- @Use(RuntimeModule) private readonly hmr!: Hmr;- @Use(RuntimeModule) private readonly resourceGroups!: ResourceGroups;- @Use() private readonly auth!: AuthService;+ @Use() private readonly hmr!: Hmr;+ @Use() private readonly resourceGroups!: ResourceGroups;+ @Use() private readonly auth!: Auth;@Provide() terminals!: Terminals;@Bind("TerminalModule.routes") routes!: ReturnType<typeof terminalRoutes>;setup({ resources, effect }: ClassCtx, context: Json) {diff --git a/packages/server/src/terminal/ws.ts b/packages/server/src/terminal/ws.tsindex ebd2f9ec..606aca21 100644--- a/packages/server/src/terminal/ws.ts+++ b/packages/server/src/terminal/ws.ts@@ -15,9 +15,9 @@import type { IncomingMessage, Server as HttpServer } from "node:http";import type { Duplex } from "node:stream";import { WebSocketServer } from "ws";-import type { AuthService } from "../auth/service.js";import { SESSION_COOKIE } from "../auth/middleware.js";import type { HmrHost } from "../hmr/host.js";+import type { Auth } from "../mechanisms/identity.js";const STREAM_PATH = /^\/api\/terminals\/([^/]+)\/stream$/;@@ -39,7 +39,7 @@ const BACKPRESSURE_POLL_MS = 250;export interface TerminalWebSocketDeps {/** The booted platform owns the terminals; the runtime asks it per upgrade. */hmr: HmrHost;- authService: AuthService;+ authService: Auth;log: (line: string) => void;}diff --git a/packages/server/test/auth.test.ts b/packages/server/test/auth.test.tsindex bfeb11a9..aa0c2eeb 100644--- a/packages/server/test/auth.test.ts+++ b/packages/server/test/auth.test.ts@@ -18,6 +18,7 @@ import {TEST_ADMIN_PASSWORD,testConfig,flattenForTests,+ replacementsFor,} from "./helpers.js";import type { TestApp } from "./helpers.js";@@ -204,7 +205,10 @@ describe("auth", () => {it("seedAdmin rejects an override below the password policy before creating the account", async () => {const root = await makeTempRoot();const deps = flattenForTests(- await bootAppDeps({ ...testConfig(root), seedAdminPassword: "x" }, { log: () => {} }),+ await bootAppDeps(+ { ...testConfig(root), seedAdminPassword: "x" },+ replacementsFor({ log: () => {} }),+ ),);try {await expect(deps.authService.seedAdmin()).rejects.toThrow(/at least 8 characters/);diff --git a/packages/server/test/errors.test.ts b/packages/server/test/errors.test.tsindex c13389a1..de468d5b 100644--- a/packages/server/test/errors.test.ts+++ b/packages/server/test/errors.test.ts@@ -259,7 +259,7 @@ describe("error-recorder", () => {afterEach(() => db.close());it("HttpError → expected (keeps code and status)", () => {- wire(ErrorRecorder, { errors: repo, now: now }).record({+ wire(ErrorRecorder, { errors: repo, clock: { now: now } }).record({source: "http",err: new HttpError(404,@@ -277,7 +277,7 @@ describe("error-recorder", () => {});it("non-HttpError → unexpected; HTTP source converges to 500, non-HTTP status is NULL", () => {- const rec = wire(ErrorRecorder, { errors: repo, now: now });+ const rec = wire(ErrorRecorder, { errors: repo, clock: { now: now } });rec.record({ source: "http", err: new Error("boom") });rec.record({source: "session",@@ -297,7 +297,7 @@ describe("error-recorder", () => {});it("non-Error throwables and overlong messages: stringified and truncated to the cap", () => {- const rec = wire(ErrorRecorder, { errors: repo, now: now });+ const rec = wire(ErrorRecorder, { errors: repo, clock: { now: now } });rec.record({ source: "process", err: "a string error", code: "unhandled_rejection" });rec.record({ source: "usage", err: new Error("x".repeat(MESSAGE_MAX + 100)) });const rows = db.prepare("SELECT message FROM error_records ORDER BY id").all();@@ -312,12 +312,15 @@ describe("error-recorder", () => {},} as unknown as ErrorsRepo;expect(() =>- wire(ErrorRecorder, { errors: broken }).record({ source: "http", err: new Error("x") }),+ wire(ErrorRecorder, { errors: broken, clock: { now: () => new Date() } }).record({+ source: "http",+ err: new Error("x"),+ }),).not.toThrow();});it("explicit kind wins over HttpError inference (sources self-report human need)", () => {- const rec = wire(ErrorRecorder, { errors: repo, now: now });+ const rec = wire(ErrorRecorder, { errors: repo, clock: { now: now } });rec.record({ source: "llm", err: "timed out", code: "llm_timeout", kind: "expected" });rec.record({ source: "llm", err: "auth failed", code: "llm_failed", kind: "unexpected" });const rows = db.prepare("SELECT kind, source, status FROM error_records ORDER BY id").all();@@ -330,7 +333,7 @@ describe("error-recorder", () => {// close, classified by messagingErrorKind, persisted under `messaging_connect_failed`.// Both rows land — the log keeps everything — but only the one a person has to act on// reaches the unexpected count the cost center highlights.- const rec = wire(ErrorRecorder, { errors: repo, now: now });+ const rec = wire(ErrorRecorder, { errors: repo, clock: { now: now } });const closed = (message: string, code: number, recovers: boolean) =>new MessagingConnectionClosedError(message, code, recovers);for (const err of [@@ -363,7 +366,7 @@ describe("error-recorder", () => {it("short-window dedup: same-kind errors persist once per window, then resume", () => {let t = Date.parse("2026-07-06T10:00:00Z");- const rec = wire(ErrorRecorder, { errors: repo, now: () => new Date(t) });+ const rec = wire(ErrorRecorder, { errors: repo, clock: { now: () => new Date(t) } });const boom = () =>rec.record({source: "http",@@ -385,7 +388,7 @@ describe("error-recorder", () => {});it("dedup never crosses source / code / Project (kinds don't suppress each other)", () => {- const rec = wire(ErrorRecorder, { errors: repo, now: now }); // time frozen: everything lands in the same window+ const rec = wire(ErrorRecorder, { errors: repo, clock: { now: now } }); // time frozen: everything lands in the same windowconst err = new Error("boom");rec.record({ source: "http", err, ctx: { projectId: "p1" }, code: "c1" });rec.record({ source: "http", err, ctx: { projectId: "p1" }, code: "c1" }); // same kind: discarded@@ -398,7 +401,7 @@ describe("error-recorder", () => {it("bounded dedup table: expired entries cleaned first, else wiped; works afterward", () => {let t = Date.parse("2026-07-06T10:00:00Z");- const rec = wire(ErrorRecorder, { errors: repo, now: () => new Date(t) });+ const rec = wire(ErrorRecorder, { errors: repo, clock: { now: () => new Date(t) } });const boom = (code: string) =>rec.record({ source: "http", err: "boom", ctx: { projectId: "p1" }, code });@@ -433,7 +436,7 @@ describe("stream-error-watcher (LLM / Environment errors)", () => {afterEach(() => db.close());const watcher = () =>- new StreamErrorWatcher(wire(ErrorRecorder, { errors: repo, now: now }), CTX);+ new StreamErrorWatcher(wire(ErrorRecorder, { errors: repo, clock: { now: now } }), CTX);const rows = () =>db.prepare("SELECT * FROM error_records ORDER BY id").all() as Array<Record<string, unknown>>;diff --git a/packages/server/test/helpers.ts b/packages/server/test/helpers.tsindex 9a39fcba..c8c36f17 100644--- a/packages/server/test/helpers.ts+++ b/packages/server/test/helpers.ts@@ -9,8 +9,8 @@ import path from "node:path";import type { Hono } from "hono";import type { OmniMessage } from "@prismshadow/penguin-core";import { bootAppDeps, createRuntimeApp } from "../src/app.js";-import type { BuildDepsOverrides, ServerBoot } from "../src/app.js";-import type { ModuleTree } from "@prismshadow/penguin-core/kernel";+import type { ServerBoot } from "../src/app.js";+import type { ModuleTree, ModuleClass } from "@prismshadow/penguin-core/kernel";import type { DatabaseSync } from "node:sqlite";import type { HmrHost } from "../src/hmr/host.js";import type { ChannelHub } from "../src/runtime/channel.js";@@ -26,7 +26,6 @@ import type { AgentConfigService } from "../src/services/agent-config-service.jsimport type { MemoryService } from "../src/services/memory-service.js";import type { SessionService } from "../src/services/session-service.js";import type { PricingLookup, UsageService } from "../src/services/usage-service.js";-import type { UpdateCheckService } from "../src/services/update-check-service.js";import type { WorkspaceFilesService } from "../src/services/workspace-files-service.js";import type { PreviewTokenSigner } from "../src/services/preview-token.js";import type { BenchmarkService } from "../src/services/benchmark-service.js";@@ -38,9 +37,9 @@ import type { SchedulesRepo } from "../src/db/repos/schedules.js";import type { ErrorsRepo } from "../src/db/repos/errors.js";import type { MessagingBindingsRepo } from "../src/db/repos/messaging-bindings.js";import type { MessagingBridge } from "../src/runtime/messaging/bridge.js";-import type { QQScanService } from "../src/runtime/messaging/qq-scan.js";+import type { QQScanService, QQScanTransport } from "../src/runtime/messaging/qq-scan.js";import type { Scheduler } from "../src/runtime/scheduler.js";-import type { SessionManager } from "../src/runtime/session-manager.js";+import type { SessionManager, SessionLoader } from "../src/runtime/session-manager.js";import type { ErrorRecorder } from "../src/runtime/error-recorder.js";import type { MachinesService } from "../src/machines/service.js";import { openDatabase } from "../src/db/database.js";@@ -54,6 +53,28 @@ import { ADMIN_USER_ID } from "../src/auth/service.js";import type { ServerConfig } from "../src/config.js";import type { UserInfo } from "../src/api/types.js";import { wire } from "@prismshadow/penguin-core/kernel";+import type { PluginHost } from "../src/plugin/host.js";+import type { Replacements } from "../src/hmr/capabilities.js";+import { ConsoleLog, SystemClock } from "../src/hmr/capabilities.js";+import { hashPassword, ScryptHasher } from "../src/auth/password.js";+import { CoreSessionLoaders, DefaultTitleGenerators } from "../src/runtime/session-manager.js";+import type { TitleNotifier } from "../src/runtime/title-generator.js";+import { UpdateCheckService } from "../src/services/update-check-service.js";+import { DefaultMessagingTuning } from "../src/runtime/messaging/bridge.js";+import { FeishuSdkProvider } from "../src/runtime/messaging/feishu-connector.js";+import type { FeishuSdk } from "../src/runtime/messaging/feishu-sdk.js";+import { TelegramTransportProvider } from "../src/runtime/messaging/telegram-connector.js";+import type { TelegramTransport } from "../src/runtime/messaging/telegram-api.js";+import { QQTransportProvider } from "../src/runtime/messaging/qq-connector.js";+import type { QQTransport } from "../src/runtime/messaging/qq-api.js";+import { QQScanTransportProvider } from "../src/runtime/messaging/qq-scan.js";+import { WeChatTransportProvider } from "../src/runtime/messaging/wechat-connector.js";+import type { WeChatTransport } from "../src/runtime/messaging/wechat-api.js";+import { WeChatScanTransportProvider } from "../src/runtime/messaging/wechat-scan.js";+import type { WeChatScanTransport } from "../src/runtime/messaging/wechat-scan.js";+import { MachinesModule, machinesServerProxyRoutes } from "../src/machines/service.js";+import { machinesRoutes } from "../src/http/routes/machines.js";+import type { Access } from "../src/mechanisms/projects.js";export async function makeTempRoot(): Promise<string> {return fs.mkdtemp(path.join(os.tmpdir(), "penguin-server-test-"));@@ -145,6 +166,8 @@ export interface TestDeps {export function flattenForTests(boot: ServerBoot): TestDeps {const { tree } = boot;+ // Read through the groups' exports, never an implementation node by name: a test that+ // replaces a node (or a whole group) still gets what the tree actually serves.const api = <T>(module: string, alias: string): T => tree.api<T>(module, alias);return {config: boot.config,@@ -153,36 +176,36 @@ export function flattenForTests(boot: ServerBoot): TestDeps {channels: boot.channels,desktop: boot.desktop,tree,- sessionsRepo: api("SessionsRepo", "SessionsRepo"),- prefsRepo: api("UiPrefsRepo", "UiPrefsRepo"),- serverSettingsRepo: api("ServerSettingsRepo", "ServerSettingsRepo"),- authService: api("AuthService", "AuthService"),- adminService: api("AdminService", "AdminService"),- projectService: api("ProjectService", "ProjectService"),- access: api("ProjectAccess", "ProjectAccess"),- projectConfigService: api("ProjectConfigService", "ProjectConfigService"),- modelOAuth: api("ModelOAuthService", "ModelOAuthService"),- agentService: api("AgentService", "AgentService"),- agentConfigService: api("AgentConfigService", "AgentConfigService"),- memoryService: api("MemoryService", "MemoryService"),- sessionService: api("SessionsModule", "sessionService"),- traceService: api("TraceService", "TraceService"),- traceIndex: api("TraceIndexService", "TraceIndexService"),- usageService: api("UsageService", "UsageService"),- updateCheck: api("VersionModule", "updateCheck"),- workspaceFiles: api("WorkspaceFilesService", "WorkspaceFilesService"),- previewTokens: api("WorkspaceModule", "previewTokens"),- benchmarks: api("BenchmarkService", "BenchmarkService"),- snapshots: api("SnapshotService", "SnapshotService"),- schedulesRepo: api("SchedulesRepo", "SchedulesRepo"),- errorsRepo: api("ErrorsRepo", "ErrorsRepo"),- messagingRepo: api("MessagingBindingsRepo", "MessagingBindingsRepo"),- messaging: api("MessagingModule", "messaging"),- qqScan: api("MessagingModule", "qqScan"),- scheduler: api("Scheduler", "Scheduler"),- manager: api("SessionsModule", "manager"),- sessionSources: api("SessionSources", "SessionSources"),- errors: api("ErrorRecorder", "ErrorRecorder"),+ sessionsRepo: api("SessionRuntimeModule", "SessionIndex"),+ prefsRepo: api("SettingsModule", "UiPrefsStore"),+ serverSettingsRepo: api("SettingsModule", "Settings"),+ authService: api("IdentityModule", "Auth"),+ adminService: api("IdentityModule", "Admin"),+ projectService: api("ProjectsModule", "ProjectLifecycle"),+ access: api("ProjectsModule", "Access"),+ projectConfigService: api("ProjectsModule", "ProjectConfigStore"),+ modelOAuth: api("ProjectsModule", "ModelOAuth"),+ agentService: api("AgentsModule", "AgentLifecycle"),+ agentConfigService: api("AgentsModule", "AgentConfig"),+ memoryService: api("AgentsModule", "Memory"),+ sessionService: api("SessionRuntimeModule", "SessionServiceIface"),+ traceService: api("TracesModule", "Traces"),+ traceIndex: api("TracesModule", "TraceIndex"),+ usageService: api("ObservabilityModule", "UsageQueries"),+ updateCheck: api("ApiModule", "UpdateCheck"),+ workspaceFiles: api("WorkspaceModule", "WorkspaceFiles"),+ previewTokens: api("WorkspaceModule", "PreviewTokens"),+ benchmarks: api("AgentsModule", "Benchmarks"),+ snapshots: api("AgentsModule", "Snapshots"),+ schedulesRepo: api("SessionRuntimeModule", "Schedules"),+ errorsRepo: api("ObservabilityModule", "ErrorLog"),+ messagingRepo: api("MessagingHubModule", "MessagingBindings"),+ messaging: api("MessagingHubModule", "Messaging"),+ qqScan: api("MessagingHubModule", "QQScan"),+ scheduler: api("SessionRuntimeModule", "Scheduling"),+ manager: api("SessionRuntimeModule", "Sessions"),+ sessionSources: api("SessionRuntimeModule", "SessionOrigins"),+ errors: api("ObservabilityModule", "Errors"),machines: api("MachinesModule", "machines"),};}@@ -196,26 +219,134 @@ export interface TestApp {cleanup(): Promise<void>;}-export interface TestAppOptions extends BuildDepsOverrides {+/**+ * What a test stands in for, by the name it has always used; each becomes a node+ * Replacement (the platform boots the given instance instead of the class it names).+ */+export interface TestAppOptions {+ /** Test double: session-manager's underlying loader (avoids the real LLM/SDK path). */+ loader?: SessionLoader;+ /** Test double: Session title generator (avoids real LLM requests). */+ titles?: TitleNotifier;+ /** Test double: update-check service with a stubbed fetch/clock (avoids real network calls). */+ updateCheck?: UpdateCheckService;+ /** Test double: the Feishu connector's SDK (avoids real Lark network / long connections). */+ feishuSdk?: FeishuSdk;+ /** Test double: the Telegram connector's Bot API transport. */+ telegramTransport?: TelegramTransport;+ /** Test hook: the Telegram connector's poll backoff (tests collapse it to zero). */+ telegramRetryDelayMs?: (failures: number) => number;+ /** Test double: the QQ connector's OpenAPI + gateway transport. */+ qqTransport?: QQTransport;+ /** Test hook: how long the QQ connector withholds its coalesced tail. */+ qqTailFlushMs?: number;+ /** Test hook: the bridge's pace between a per-line reply's messages. */+ messagingLineDelayMs?: number;+ /** Test hook: one binding's inbound image budget. */+ messagingInboundImageBudgetBytes?: number;+ /** Test double: the QQ scan-to-connect transport. */+ qqScanTransport?: QQScanTransport;+ /** Test double: the WeChat connector's long-poll + CDN transport. */+ wechatTransport?: WeChatTransport;+ /** Test double: the WeChat scan-to-connect transport. */+ wechatScanTransport?: WeChatScanTransport;+ /** Test hook: the WeChat poll loop's backoff (tests collapse it to zero). */+ wechatRetryDelayMs?: (failures: number) => number;+ /** Test double: machines service whose ssh effects are faked. */+ machines?: MachinesService;+ /** Test double: the password work factor (scrypt at full strength is seconds per hash). */+ passwordHashCost?: number;+ log?: (line: string) => void;+ now?: () => Date;+ /** The plugins this app boots with (their modules and replacements), as the runtime would have loaded them. */+ plugins?: PluginHost;/** Runs before seeding the admin (for scenarios pre-populating a default_project config as the CLI would). */beforeSeed?: (root: string) => Promise<void>;/** Overrides merged onto the default test ServerConfig (e.g. `previewOrigin`). */config?: Partial<ServerConfig>;}+/** The node each option stands in for. */+/** A stand-in Project gate for a replaced machines node: every test that supplies one is an admin's. */+function accessDouble(): Access {+ return {+ requireProjectAccess: () => ({}) as never,+ requireProjectOwner: () => ({}) as never,+ } as unknown as Access;+}++export function replacementsFor(o: TestAppOptions): Replacements {+ const out: Array<readonly [ModuleClass, object]> = [];+ if (o.log) out.push([ConsoleLog, { line: o.log }]);+ if (o.now) out.push([SystemClock, { now: o.now }]);+ if (o.passwordHashCost !== undefined) {+ const cost = o.passwordHashCost;+ out.push([ScryptHasher, { hash: (password: string) => hashPassword(password, cost) }]);+ }+ if (o.loader) {+ const loader = o.loader;+ out.push([CoreSessionLoaders, { create: () => loader }]);+ }+ if (o.titles) {+ const titles = o.titles;+ out.push([DefaultTitleGenerators, { create: () => titles }]);+ }+ if (o.updateCheck) out.push([UpdateCheckService, o.updateCheck]);+ if (o.feishuSdk) out.push([FeishuSdkProvider, { feishuSdk: { sdk: o.feishuSdk } }]);+ if (o.telegramTransport)+ out.push([+ TelegramTransportProvider,+ { telegramTransport: { transport: o.telegramTransport } },+ ]);+ if (o.qqTransport) out.push([QQTransportProvider, { qqTransport: { transport: o.qqTransport } }]);+ if (o.qqScanTransport)+ out.push([QQScanTransportProvider, { qqScanTransport: { transport: o.qqScanTransport } }]);+ if (o.wechatTransport)+ out.push([WeChatTransportProvider, { wechatTransport: { transport: o.wechatTransport } }]);+ if (o.wechatScanTransport)+ out.push([+ WeChatScanTransportProvider,+ { wechatScanTransport: { transport: o.wechatScanTransport } },+ ]);+ const tuning: Record<string, unknown> = {};+ if (o.messagingLineDelayMs !== undefined) tuning.lineDelayMs = o.messagingLineDelayMs;+ if (o.messagingInboundImageBudgetBytes !== undefined)+ tuning.inboundImageBudgetBytes = o.messagingInboundImageBudgetBytes;+ if (o.qqTailFlushMs !== undefined) tuning.qqTailFlushMs = o.qqTailFlushMs;+ if (o.telegramRetryDelayMs) tuning.retryDelayMs = o.telegramRetryDelayMs;+ if (o.wechatRetryDelayMs) tuning.retryDelayMs = o.wechatRetryDelayMs;+ if (Object.keys(tuning).length > 0) out.push([DefaultMessagingTuning, tuning]);+ if (o.machines) {+ const machines = o.machines;+ out.push([+ MachinesModule,+ {+ machines,+ routes: machinesRoutes({ machines, access: accessDouble() }),+ serverProxyRoutes: machinesServerProxyRoutes(machines),+ },+ ]);+ }+ return out;+}+export async function createTestApp(options: TestAppOptions = {}): Promise<TestApp> {- const { beforeSeed, config, ...overrides } = options;+ const { beforeSeed, config, plugins, ...overrides } = options;const root = await makeTempRoot();if (beforeSeed) await beforeSeed(root);const finalConfig = { ...testConfig(root), ...config };- const boot = await bootAppDeps(finalConfig, {- log: () => {},- passwordHashCost: TEST_PASSWORD_HASH_COST,- // The bridge's per-line pace is a real wait in production; every test but the one- // about the pacing itself collapses it to nothing.- messagingLineDelayMs: 0,- ...overrides,- });+ const boot = await bootAppDeps(+ finalConfig,+ replacementsFor({+ log: () => {},+ passwordHashCost: TEST_PASSWORD_HASH_COST,+ // The bridge's per-line pace is a real wait in production; every test but the one+ // about the pacing itself collapses it to nothing.+ messagingLineDelayMs: 0,+ ...overrides,+ }),+ plugins,+ );// Consistent with the startup entrypoint: seed the built-in admin (owning default_project).const deps = flattenForTests(boot);await deps.authService.seedAdmin();@@ -349,15 +480,13 @@ export function makeTraceHarness(} {const db = openDatabase(":memory:");const sources = opts.sources ?? new SessionSources();- const traceIndex = wire(TraceIndexService, {- config: { root },- repo: wire(TraceIndexRepo, { db }),- sources,- });+ const repo = wire(TraceIndexRepo, { db });+ const traceIndex = wire(TraceIndexService, { paths: { root }, repo, sources });const shardReads: string[] = [];const service = wire(TraceService, {- config: { root },+ paths: { root },index: traceIndex,+ store: repo,...(opts.sessions !== undefined ? { sessions: opts.sessions } : {}),...(opts.lookupPricing !== undefined ? { lookupPricing: opts.lookupPricing } : {}),sources,diff --git a/packages/server/test/hot-replace.test.ts b/packages/server/test/hot-replace.test.tsnew file mode 100644index 00000000..c354e4f4--- /dev/null+++ b/packages/server/test/hot-replace.test.ts@@ -0,0 +1,180 @@+/**+ * A plugin replaces any node of the tree — a component, a whole group — by name.+ * Nothing about the stand-in is checked when it is put in place; the tree it results in+ * is checked as one before any node runs: a stand-in that offers less than its consumers+ * need is refused by name, and the App does not boot.+ */+import { describe, expect, it, afterEach } from "vitest";+import { parseManifest } from "@prismshadow/penguin-core/kernel";+import type { ModuleDef } from "@prismshadow/penguin-core/kernel";+import { PluginHost } from "../src/plugin/host.js";+import type { Settings, UiPrefsStore } from "../src/mechanisms/settings.js";+import { createTestApp, loginAdmin, type TestApp } from "./helpers.js";++const PKG = "@prismshadow/penguin-server";++function replacing(+ name: string,+ provides: Record<string, string>,+ api: Record<string, unknown>,+ extra: Partial<ModuleDef["manifest"]> = {},+): ModuleDef {+ return {+ manifest: parseManifest({+ name,+ requires: {},+ provides,+ contributes: {},+ children: [],+ ...extra,+ }),+ create: () => ({ api }),+ };+}++function hostWith(...replaces: ModuleDef[]): PluginHost {+ const host = new PluginHost();+ host.use({ specifier: "memory-ext", modules: [], replaces });+ return host;+}++function memorySettings(maxMb = 7): Settings {+ const kv = new Map<string, string>();+ return {+ get: (k) => kv.get(k) ?? null,+ set: (k, v) => void kv.set(k, v),+ getProxyForApp: () => false,+ setProxyForApp: () => {},+ getProxyForAgent: () => false,+ setProxyForAgent: () => {},+ getProxyUrl: () => null,+ setProxyUrl: () => {},+ getAttachmentMaxMb: () => maxMb,+ setAttachmentMaxMb: () => {},+ getAttachmentTotalMb: () => maxMb * 10,+ setAttachmentTotalMb: () => {},+ getAttachmentLimitsMb: () => ({ attachmentMaxMb: maxMb, attachmentTotalMb: maxMb * 10 }),+ };+}++describe("hot replacement by a plugin", () => {+ let t: TestApp | null = null;+ afterEach(async () => {+ await t?.cleanup();+ t = null;+ });++ it("a component is replaced by name; its consumers run against the stand-in", async () => {+ const settings = memorySettings(7);+ t = await createTestApp({+ plugins: hostWith(+ replacing("ServerSettingsRepo", { Settings: `${PKG}#Settings` }, { Settings: settings }),+ ),+ });+ // The node and the group's export are the stand-in itself …+ expect(t.deps.tree.api("ServerSettingsRepo", "Settings")).toBe(settings);+ expect(t.deps.tree.api("SettingsModule", "Settings")).toBe(settings);+ // … and a consumer in another group (the admin routes) serves what it says.+ const admin = await loginAdmin(t.app);+ const res = await t.app.request("/api/admin/settings", { headers: { cookie: admin.cookie } });+ expect(res.status).toBe(200);+ expect(+ ((await res.json()) as { settings: { attachmentMaxMb: number } }).settings.attachmentMaxMb,+ ).toBe(7);+ });++ it("a stand-in whose instance lacks a method the interface names is refused, by name", async () => {+ const hollow = { ...memorySettings() } as Record<string, unknown>;+ delete hollow.getAttachmentLimitsMb;+ await expect(+ createTestApp({+ plugins: hostWith(+ replacing("ServerSettingsRepo", { Settings: `${PKG}#Settings` }, { Settings: hollow }),+ ),+ }),+ ).rejects.toThrow(+ /ServerSettingsRepo: api 'Settings' does not satisfy 'Settings': missing \[getAttachmentLimitsMb\]/,+ );+ });++ it("a stand-in that provides nothing its consumers need is refused before anything runs", async () => {+ await expect(+ createTestApp({ plugins: hostWith(replacing("ServerSettingsRepo", {}, {})) }),+ ).rejects.toThrow(/SettingsModule: exports 'Settings' but no child provides it/);+ });++ it("a stand-in naming an interface the table does not carry is refused", async () => {+ await expect(+ createTestApp({+ plugins: hostWith(+ replacing(+ "ServerSettingsRepo",+ { Settings: `${PKG}#Nope` },+ { Settings: memorySettings() },+ ),+ ),+ }),+ ).rejects.toThrow(/Nope/);+ });++ it("a whole group is replaced with a subtree of its own, exporting the same interfaces", async () => {+ const settings = memorySettings(7);+ const prefs = new Map<string, string>();+ const uiPrefs: UiPrefsStore = {+ get: (u) => prefs.get(u) ?? null,+ set: (u, j) => void prefs.set(u, j),+ };+ const group: ModuleDef = {+ manifest: parseManifest({+ name: "SettingsModule",+ requires: {},+ provides: { Settings: `${PKG}#Settings`, UiPrefsStore: `${PKG}#UiPrefsStore` },+ exports: ["Settings", "UiPrefsStore"],+ contributes: {},+ children: ["MemorySettings", "MemoryPrefs"],+ }),+ create: () => ({ api: {} }),+ children: [+ replacing("MemorySettings", { Settings: `${PKG}#Settings` }, { Settings: settings }),+ replacing(+ "MemoryPrefs",+ { UiPrefsStore: `${PKG}#UiPrefsStore` },+ { UiPrefsStore: uiPrefs },+ ),+ ],+ };+ t = await createTestApp({ plugins: hostWith(group) });+ expect(t.deps.tree.api("SettingsModule", "Settings")).toBe(settings);+ // A consumer in another group reached it through the export: the attachment limit+ // the HTTP layer enforces is the stand-in's.+ const admin = await loginAdmin(t.app);+ const res = await t.app.request("/api/admin/settings", { headers: { cookie: admin.cookie } });+ expect(res.status).toBe(200);+ expect(+ ((await res.json()) as { settings: { attachmentMaxMb: number } }).settings.attachmentMaxMb,+ ).toBe(7);+ });++ it("two plugins replacing the same node is a load-time conflict", () => {+ const host = hostWith(+ replacing(+ "ServerSettingsRepo",+ { Settings: `${PKG}#Settings` },+ { Settings: memorySettings() },+ ),+ );+ expect(() =>+ host.use({+ specifier: "other",+ modules: [],+ replaces: [+ replacing(+ "ServerSettingsRepo",+ { Settings: `${PKG}#Settings` },+ { Settings: memorySettings() },+ ),+ ],+ }),+ ).toThrow(/'ServerSettingsRepo' is already replaced by another plugin/);+ });+});diff --git a/packages/server/test/machines-api.test.ts b/packages/server/test/machines-api.test.tsindex 19d227cc..018bf780 100644--- a/packages/server/test/machines-api.test.ts+++ b/packages/server/test/machines-api.test.ts@@ -149,6 +149,20 @@ describe("machines API", () => {it("needs a session at all", async () => {expect((await t.app.request("/api/projects/default_project/machines")).status).toBe(401);});++ it("gates a machine's proxied API the same way, under its own prefix", async () => {+ // /server/<machineId>/api/… is a protected group outside /api: the gate is what puts+ // the user on the context, and an ungated prefix left the handler reading isAdmin off+ // nothing — a 500, for the admin who was allowed and the stranger who was not.+ expect((await t.app.request("/server/tXIvjrl0pgKa5_dD/api/version")).status).toBe(401);+ const user = await provisionUser(t.app, "member");+ const member = apiClient(t.app, user.cookie);+ expect((await member.get("/server/tXIvjrl0pgKa5_dD/api/version")).status).toBe(403);+ // An admin reaches the proxy itself, which answers for a machine it does not hold.+ const res = await admin.get("/server/tXIvjrl0pgKa5_dD/api/version");+ expect(res.status).toBe(503);+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe("not_connected");+ });});describe("the list", () => {@@ -933,6 +947,48 @@ describe("machines API", () => {});});+ it("the App's boot re-holds what the record says was held, without being asked", async () => {+ // What a hot push or a restart finds: a record written by the generation before. Nobody+ // calls start() here — the Startup component does, as the App comes up.+ const heldNow: string[] = [];+ connected.clear();+ machinesRoot = await makeTempRoot();+ store = openDatabase(":memory:");+ store+ .prepare(+ "INSERT INTO users (user_id, password_hash, is_admin, created_at) VALUES (?, ?, 1, ?)",+ )+ .run("admin", "x", "2026-08-24T00:00:00.000Z");+ store+ .prepare("INSERT INTO projects (project_id, owner_user_id, created_at) VALUES (?, ?, ?)")+ .run("default_project", "admin", "2026-08-24T00:00:00.000Z");+ machinesRepo = new MachinesRepo(store);+ machinesRepo.patch("ssh:nas", {+ version: "9.9.9",+ installedAt: "2026-08-01T00:00:00.000Z",+ sessionPid: 424242,+ remotePort: 7364,+ });+ t = await createTestApp({+ machines: new MachinesService(+ machinesRoot,+ LOCAL_ID,+ machinesRepo,+ effects({+ hold: async (target) => {+ heldNow.push(target.alias);+ connected.add(`ssh:${target.alias}`);+ return { ok: true, session: { pid: process.pid, socksPort: 1 } };+ },+ }),+ ),+ });+ admin = apiClient(t.app, (await loginAdmin(t.app)).cookie);+ await waitFor(() => heldNow.length > 0);+ expect(heldNow).toEqual(["nas"]);+ expect(machinesRepo.get("ssh:nas")?.sessionPid).toBe(process.pid);+ });+it("disconnect clears the record, so a later boot leaves the machine alone", async () => {const heldNow: string[] = [];await boot({diff --git a/packages/server/test/models-list.test.ts b/packages/server/test/models-list.test.tsindex 2799e4b8..3ac01def 100644--- a/packages/server/test/models-list.test.ts+++ b/packages/server/test/models-list.test.ts@@ -19,7 +19,7 @@ describe("ProjectConfigService.listEndpointModels", () => {beforeEach(async () => {root = await mkdtemp(path.join(tmpdir(), "penguin-models-list-"));- service = wire(ProjectConfigService, { config: { root } });+ service = wire(ProjectConfigService, { paths: { root } });});afterEach(async () => {await rm(root, { recursive: true, force: true });diff --git a/packages/server/test/models.test.ts b/packages/server/test/models.test.tsindex 03c89286..285419c1 100644--- a/packages/server/test/models.test.ts+++ b/packages/server/test/models.test.ts@@ -466,7 +466,7 @@ describe("default_project presets", () => {// First have the "CLI" write a config with a single custom model, then admin seeding adopts it.t = await createTestApp({beforeSeed: async (root) => {- await wire(ProjectConfigService, { config: { root } }).writeRaw("default_project", {+ await wire(ProjectConfigService, { paths: { root } }).writeRaw("default_project", {default_model: { provider: "custom", model_id: "cli-model" },models: [{ provider: "custom", model_id: "cli-model", context_window: 1234 }],});@@ -602,7 +602,7 @@ describe("model-reference rekeying and the connectivity test", () => {// No clock is passed and none is wanted: which tier a given request ran in is decided from// that record's own timestamp when the usage is aggregated, so the price lookup's whole job// is to say what the two tiers are. The number on disk is the peak one either way.- const svc = wire(ProjectConfigService, { config: { root: t.root } });+ const svc = wire(ProjectConfigService, { paths: { root: t.root } });const rates = await svc.getPricing(projectId, "deepseek", "deepseek-v4-flash");const catalogPeak = catalogEntryFor("deepseek", "deepseek-v4-flash")!.pricing!;expect(rates!.peak.output).toBe(catalogPeak.output);@@ -630,7 +630,7 @@ describe("model-reference rekeying and the connectivity test", () => {: {}),}));await api.put(url(), { models: entries });- const svc = wire(ProjectConfigService, { config: { root: t.root } });+ const svc = wire(ProjectConfigService, { paths: { root: t.root } });// Nothing here knows whether 3 is a peak rate, so halving it would invent a discount: the// two tiers collapse to the typed number and the split costs a row and changes nothing.const typed = { cacheRead: 1, cacheWrite: 2, output: 3 };diff --git a/packages/server/test/plugin-loader.test.ts b/packages/server/test/plugin-loader.test.tsindex 4b5f6eac..e576bd98 100644--- a/packages/server/test/plugin-loader.test.ts+++ b/packages/server/test/plugin-loader.test.ts@@ -193,6 +193,34 @@ describe("plugin loading", () => {expect(result.failed.get(file)).toMatch(/Ghost: not in the generated manifest table/);});+ it("classes under `replaces` are paired the same way, and land in the plugin's replaces", async () => {+ const file = await writePackage(+ "@acme/penguin-plugin-thing",+ {+ ...oneModule,+ modules: {+ ...oneModule.modules,+ MemoryService: {+ ...oneModule.modules.Thing,+ name: "MemoryService",+ provides: {},+ contributes: {},+ },+ },+ },+ `${thingClass}+ import { Module } from ${JSON.stringify(decorators)};+ @Module() export class MemoryService {}+ export default { modules: [Thing], replaces: [MemoryService] };`,+ );+ await writeConfig({ plugins: [file] });+ const result = await loadPlugins(root);+ expect(result.failed.size).toBe(0);+ const entry = result.loaded[0]!;+ expect(entry.modules.map((m) => m.manifest.name)).toEqual(["Thing"]);+ expect(entry.replaces.map((m) => m.manifest.name)).toEqual(["MemoryService"]);+ });+it("a package without a table ships no modules — a plugin is a plugin by being listed", async () => {const file = await writePackage("@acme/skills-only", null, "export default { modules: [] };");await writeConfig({ plugins: [file] });diff --git a/packages/server/test/plugin.test.ts b/packages/server/test/plugin.test.tsindex 9a876bef..5627d07b 100644--- a/packages/server/test/plugin.test.ts+++ b/packages/server/test/plugin.test.ts@@ -44,15 +44,15 @@ function backend(name: string, onCreate?: () => void): ModuleDef {describe("plugin host", () => {it("holds every plugin's modules in load order", () => {const host = new PluginHost();- host.use({ specifier: "a", modules: [backend("a1"), backend("a2")] });- host.use({ specifier: "b", modules: [backend("b1")] });+ host.use({ specifier: "a", modules: [backend("a1"), backend("a2")], replaces: [] });+ host.use({ specifier: "b", modules: [backend("b1")], replaces: [] });expect(host.modules().map((m) => m.manifest.name)).toEqual(["ext-a1", "ext-a2", "ext-b1"]);});it("refuses a module name another plugin already loaded, naming both", () => {const host = new PluginHost();- host.use({ specifier: "a", modules: [backend("x")] });- expect(() => host.use({ specifier: "b", modules: [backend("x")] })).toThrow(+ host.use({ specifier: "a", modules: [backend("x")], replaces: [] });+ expect(() => host.use({ specifier: "b", modules: [backend("x")], replaces: [] })).toThrow(/plugin 'b': module 'ext-x' is already loaded/,);});@@ -77,7 +77,7 @@ describe("plugin modules on the real platform", () => {const resources = new HotResources();resources.register(RUNTIME_INTERFACES_RESOURCE_ID, { family: PENGUIN_FAMILY });const host = new PluginHost();- host.use({ specifier: "test", modules });+ host.use({ specifier: "test", modules, replaces: [] });resources.register(PLUGINS_RESOURCE_ID, host);return boot(packagedPlatform.impl,diff --git a/packages/server/test/project-config-cache.test.ts b/packages/server/test/project-config-cache.test.tsindex 588ed9c0..61f6d6d7 100644--- a/packages/server/test/project-config-cache.test.ts+++ b/packages/server/test/project-config-cache.test.ts@@ -36,7 +36,7 @@ describe("project-config read cache", () => {beforeEach(async () => {root = await makeTempRoot();- svc = wire(ProjectConfigService, { config: { root } });+ svc = wire(ProjectConfigService, { paths: { root } });file = projectConfigPath(root, P);await svc.writeRaw(P, { name: "cached", models: [PRICED] });await backdate(file, "2026-01-01T00:00:00Z");diff --git a/packages/server/test/sandbox.test.ts b/packages/server/test/sandbox.test.tsindex 80076a3c..c8301e38 100644--- a/packages/server/test/sandbox.test.ts+++ b/packages/server/test/sandbox.test.ts@@ -176,6 +176,7 @@ describe("sandbox settings ride the parked context across a swap", () => {const host = new PluginHost();host.use({specifier: "observer",+ replaces: [],modules: [{manifest: parseManifest({diff --git a/packages/server/test/scheduler.test.ts b/packages/server/test/scheduler.test.tsindex 7fa76008..47143662 100644--- a/packages/server/test/scheduler.test.ts+++ b/packages/server/test/scheduler.test.ts@@ -87,7 +87,7 @@ describe("scheduler", () => {errors = [];let seq = 0;scheduler = wire(Scheduler, {- config: { root },+ paths: { root },repo,projects,sessions,@@ -106,7 +106,7 @@ describe("scheduler", () => {return { sessionId };},},- projectConfig: wire(ProjectConfigService, { config: { root } }),+ projectConfig: wire(ProjectConfigService, { paths: { root } }),errors: { record: (args: ErrorRecordArgs) => void errors.push(args) },notify: (userId: string, event: ScheduleServerEvent) => void events.push({ userId, event }),now: () => nowMs,diff --git a/packages/server/test/trace-service.test.ts b/packages/server/test/trace-service.test.tsindex d96f7632..88f8c2d6 100644--- a/packages/server/test/trace-service.test.ts+++ b/packages/server/test/trace-service.test.ts@@ -278,7 +278,7 @@ describe("trace-service", () => {usage: rows,errors: wire(ErrorsRepo, { db }),lookupPricing: lookup,- now: () => new Date(),+ clock: { now: () => new Date() },});const res = await center.query(P, { groupBy: "session" });expect(res.groups.find((g) => g.key === S)?.cost).toBeCloseTo(a.cost!, 12);diff --git a/packages/server/test/update-job.test.ts b/packages/server/test/update-job.test.tsindex d9b5b186..b6989274 100644--- a/packages/server/test/update-job.test.ts+++ b/packages/server/test/update-job.test.ts@@ -3,6 +3,7 @@* over a scripted runner (nothing is ever spawned here).*/import { describe, expect, it } from "vitest";+import { wire } from "@prismshadow/penguin-core/kernel";import {INITIAL_PROGRESS,UpdateJobService,@@ -97,7 +98,7 @@ function scriptedRunner(): {describe("UpdateJobService", () => {it("starts idle, runs the CLI entry with progress, and ends updated with needsRestart", async () => {const script = scriptedRunner();- const job = new UpdateJobService(script.runner);+ const job = wire(UpdateJobService, { runner: script.runner });expect(job.status()).toEqual({ state: "idle", targetVersion: null, output: "" });const started = job.start("/opt/penguin/cli.js", "0.3.0");@@ -128,14 +129,14 @@ describe("UpdateJobService", () => {it("classifies a refusal, a failure, a timeout and a spawn error", async () => {const refused = scriptedRunner();- const a = new UpdateJobService(refused.runner);+ const a = wire(UpdateJobService, { runner: refused.runner });a.start("/e", null);refused.emit("This penguin runs from a source checkout, so there is nothing to download.");await refused.finish({ exitCode: 0, timedOut: false });expect(a.status().result).toMatchObject({ status: "unsupported", needsRestart: false });const failed = scriptedRunner();- const b = new UpdateJobService(failed.runner);+ const b = wire(UpdateJobService, { runner: failed.runner });b.start("/e", "0.3.0");await failed.finish({ exitCode: 1, timedOut: false });expect(b.status().result).toMatchObject({ status: "failed" });@@ -143,14 +144,14 @@ describe("UpdateJobService", () => {expect(b.start("/e", "0.3.0").state).toBe("running");const timedOut = scriptedRunner();- const c = new UpdateJobService(timedOut.runner);+ const c = wire(UpdateJobService, { runner: timedOut.runner });c.start("/e", null);await timedOut.finish({ exitCode: -1, timedOut: true });expect(c.status().result?.status).toBe("failed");expect(c.status().output).toContain("killed after 10 minutes");const broken = scriptedRunner();- const d = new UpdateJobService(broken.runner);+ const d = wire(UpdateJobService, { runner: broken.runner });d.start("/e", null);await broken.finish({ exitCode: -1, timedOut: false, spawnError: "ENOENT" });expect(d.status().result?.status).toBe("failed");@@ -159,7 +160,7 @@ describe("UpdateJobService", () => {it("ends at once as unsupported when there is no CLI to run", () => {const script = scriptedRunner();- const job = new UpdateJobService(script.runner);+ const job = wire(UpdateJobService, { runner: script.runner });expect(job.start(null, "0.3.0")).toMatchObject({state: "done",result: { status: "unsupported", reason: "not_launched_via_cli", needsRestart: false },diff --git a/packages/server/test/usage.test.ts b/packages/server/test/usage.test.tsindex dbe2fedb..9adad1c9 100644--- a/packages/server/test/usage.test.ts+++ b/packages/server/test/usage.test.ts@@ -54,7 +54,7 @@ describe("usage-recorder", () => {afterEach(() => db.close());it("token_usage → one row (the request bucket; only Tokens persisted, never cost)", async () => {- const rec = wire(UsageRecorder, { usage: repo });+ const rec = wire(UsageRecorder, { usage: repo, clock: { now: () => new Date() } });await rec.record(CTX, tokenUsage(counts(1000), counts(115)));const rows = db.prepare("SELECT * FROM usage_records").all();expect(rows).toHaveLength(1);@@ -67,7 +67,7 @@ describe("usage-recorder", () => {});it("a sub-session's session_meta registers the origin→model mapping; token_usage is attributed via it", async () => {- const rec = wire(UsageRecorder, { usage: repo });+ const rec = wire(UsageRecorder, { usage: repo, clock: { now: () => new Date() } });const childMeta = withOrigin(sessionMeta(meta("session-child", "child-model")),"session-child",@@ -81,20 +81,20 @@ describe("usage-recorder", () => {});it("falls back to the main Session's Model when the origin mapping is missing", async () => {- const rec = wire(UsageRecorder, { usage: repo });+ const rec = wire(UsageRecorder, { usage: repo, clock: { now: () => new Date() } });await rec.record(CTX, withOrigin(tokenUsage(counts(5), counts(5)), "session-unknown"));const row = db.prepare("SELECT model_id FROM usage_records").get()!;expect(row.model_id).toBe("main-model");});it("non-token_usage messages are a no-op", async () => {- const rec = wire(UsageRecorder, { usage: repo });+ const rec = wire(UsageRecorder, { usage: repo, clock: { now: () => new Date() } });await rec.record(CTX, sessionMeta(meta("session-main", "main-model")));expect(db.prepare("SELECT COUNT(*) AS n FROM usage_records").get()!.n).toBe(0);});it("the origin mapping is capped: past the limit the earliest entry is evicted and falls back to the main Session's Model", async () => {- const rec = wire(UsageRecorder, { usage: repo });+ const rec = wire(UsageRecorder, { usage: repo, clock: { now: () => new Date() } });for (let i = 0; i <= ORIGIN_MODELS_MAX; i++) {// ORIGIN_MODELS_MAX + 1 entries total: the earliest, sub-0, gets evicted.await rec.record(CTX, withOrigin(sessionMeta(meta(`sub-${i}`, "sub-model")), `sub-${i}`));@@ -127,7 +127,7 @@ describe("usage-service (cost computed on the fly)", () => {repo = wire(UsageRepo, { db: db });const errors = wire(ErrorsRepo, { db: db });service = (now: Date) =>- wire(UsageService, { usage: repo, errors, lookupPricing: lookup, now: () => now });+ wire(UsageService, { usage: repo, errors, lookupPricing: lookup, clock: { now: () => now } });pricing = { m1: { cacheRead: 0.3, cacheWrite: 3.75, output: 15 } };});afterEach(() => db.close());@@ -176,7 +176,7 @@ describe("usage-service (cost computed on the fly)", () => {usage: repo,errors: wire(ErrorsRepo, { db: db }),lookupPricing: tiered,- now: () => new Date(at),+ clock: { now: () => new Date(at) },});const res = await svc.query("p1", { groupBy: "date", from: "2026-08-31", to: "2026-08-31" });expect(res.summary.total.cost, at).toBeCloseTo(expected, 10);@@ -256,7 +256,7 @@ describe("usage-service (cost computed on the fly)", () => {asked.push(modelId);return lookup(p, provider, modelId);},- now: () => now,+ clock: { now: () => now },});const res = await svc.query("p1", { groupBy: "date", from: "2026-07-06", to: "2026-07-06" });expect(asked).toEqual(["m1"]);@@ -421,7 +421,7 @@ describe("usage-service series (zero-filled time-series buckets)", () => {repo = wire(UsageRepo, { db: db });const errors = wire(ErrorsRepo, { db: db });service = (now: Date) =>- wire(UsageService, { usage: repo, errors, lookupPricing: lookup, now: () => now });+ wire(UsageService, { usage: repo, errors, lookupPricing: lookup, clock: { now: () => now } });pricing = { m1: { cacheRead: 0.3, cacheWrite: 3.75, output: 15 } };});afterEach(() => db.close());@@ -694,6 +694,7 @@ describe("usage-service.queryErrors (error table paging)", () => {usage: wire(UsageRepo, { db: db }),errors,lookupPricing: async () => undefined,+ clock: { now: () => new Date() },});// 25 rows, oldest first — so "newest first" ordering is observable across a page boundary.for (let i = 0; i < 25; i += 1) {diff --git a/packages/server/test/version.test.ts b/packages/server/test/version.test.tsindex a8677ec5..d7b258c3 100644--- a/packages/server/test/version.test.ts+++ b/packages/server/test/version.test.ts@@ -26,6 +26,7 @@ import {import { classifyUpdateRun } from "../src/http/routes/version.js";import { apiClient, createTestApp, loginAdmin, provisionUser } from "./helpers.js";import type { TestApp } from "./helpers.js";+import { wire } from "@prismshadow/penguin-core/kernel";/** Counting fetch stub; the handler decides the outcome per call. */function makeFetch(handler: () => Response | Promise<Response>): {@@ -118,7 +119,13 @@ describe("GET /api/version/update-check", () => {it("reports a newer release with its URL and publish date", async () => {const { impl } = makeFetch(() => releaseResponse("v99.0.0"));- t = await createTestApp({ updateCheck: new UpdateCheckService({ fetchImpl: impl, env: {} }) });+ t = await createTestApp({+ updateCheck: wire(UpdateCheckService, {+ http: { fetch: impl },+ env: {},+ clock: { now: () => new Date() },+ }),+ });const admin = await loginAdmin(t.app);const res = await apiClient(t.app, admin.cookie).get("/api/version/update-check");expect(res.status).toBe(200);@@ -138,7 +145,13 @@ describe("GET /api/version/update-check", () => {const { impl } = makeFetch(() => {throw new Error("getaddrinfo ENOTFOUND api.github.com");});- t = await createTestApp({ updateCheck: new UpdateCheckService({ fetchImpl: impl, env: {} }) });+ t = await createTestApp({+ updateCheck: wire(UpdateCheckService, {+ http: { fetch: impl },+ env: {},+ clock: { now: () => new Date() },+ }),+ });const admin = await loginAdmin(t.app);const res = await apiClient(t.app, admin.cookie).get("/api/version/update-check");expect(res.status).toBe(200);@@ -151,7 +164,13 @@ describe("GET /api/version/update-check", () => {it("?force=1 (the manual check) reaches the service as a cache bypass", async () => {const { impl, state } = makeFetch(() => releaseResponse("v99.0.0"));- t = await createTestApp({ updateCheck: new UpdateCheckService({ fetchImpl: impl, env: {} }) });+ t = await createTestApp({+ updateCheck: wire(UpdateCheckService, {+ http: { fetch: impl },+ env: {},+ clock: { now: () => new Date() },+ }),+ });const admin = await loginAdmin(t.app);const client = apiClient(t.app, admin.cookie);@@ -176,7 +195,11 @@ describe("UpdateCheckService", () => {[() => new Response("not json", { status: 200 }), "bad_response"],[() => new Response(JSON.stringify({ name: "no tag" }), { status: 200 }), "bad_response"],] as const) {- const service = new UpdateCheckService({ fetchImpl: makeFetch(make).impl, env: {} });+ const service = wire(UpdateCheckService, {+ http: { fetch: makeFetch(make).impl },+ env: {},+ clock: { now: () => new Date() },+ });const result = await service.check();expect(result.error).toBe(expected);expect(result.updateAvailable).toBe(false);@@ -186,7 +209,11 @@ describe("UpdateCheckService", () => {it("updateAvailable is false when the latest release is not newer", async () => {const { impl } = makeFetch(() => releaseResponse(`v${VERSION}`));- const service = new UpdateCheckService({ fetchImpl: impl, env: {} });+ const service = wire(UpdateCheckService, {+ http: { fetch: impl },+ env: {},+ clock: { now: () => new Date() },+ });const result = await service.check();expect(result.error).toBeUndefined();expect(result.latestVersion).toBe(VERSION);@@ -195,9 +222,10 @@ describe("UpdateCheckService", () => {it("PENGUIN_UPDATE_CHECK=off disables the lookup without any network call", async () => {const { impl, state } = makeFetch(() => releaseResponse("v99.0.0"));- const service = new UpdateCheckService({- fetchImpl: impl,+ const service = wire(UpdateCheckService, {+ http: { fetch: impl },env: { PENGUIN_UPDATE_CHECK: "off" },+ clock: { now: () => new Date() },});const result = await service.check();expect(result.disabled).toBe(true);@@ -213,10 +241,10 @@ describe("UpdateCheckService", () => {if (fail) throw new Error("down");return releaseResponse("v99.0.0");});- const service = new UpdateCheckService({- fetchImpl: impl,+ const service = wire(UpdateCheckService, {+ http: { fetch: impl },env: {},- now: () => new Date(nowMs),+ clock: { now: () => new Date(nowMs) },});const first = await service.check();@@ -251,7 +279,11 @@ describe("UpdateCheckService", () => {it("force bypasses a warm cache and recaches the fresh outcome", async () => {let tag = "v99.0.0";const { impl, state } = makeFetch(() => releaseResponse(tag));- const service = new UpdateCheckService({ fetchImpl: impl, env: {} });+ const service = wire(UpdateCheckService, {+ http: { fetch: impl },+ env: {},+ clock: { now: () => new Date() },+ });// Warm the cache; a passive check is then served from it.expect((await service.check()).latestVersion).toBe("99.0.0");@@ -270,9 +302,10 @@ describe("UpdateCheckService", () => {it("force never dials out when PENGUIN_UPDATE_CHECK=off (the opt-out stays authoritative)", async () => {const { impl, state } = makeFetch(() => releaseResponse("v99.0.0"));- const service = new UpdateCheckService({- fetchImpl: impl,+ const service = wire(UpdateCheckService, {+ http: { fetch: impl },env: { PENGUIN_UPDATE_CHECK: "off" },+ clock: { now: () => new Date() },});const result = await service.check(true);expect(result.disabled).toBe(true);diff --git a/scripts/gen-ifaces.mjs b/scripts/gen-ifaces.mjsindex 61cce5d9..43d6099a 100644--- a/scripts/gen-ifaces.mjs+++ b/scripts/gen-ifaces.mjs@@ -33,7 +33,8 @@* Promise<T> / PromiseLike<T> → { promise }* AsyncIterable<T> / AsyncGenerator<T> → { stream }* void / undefined return → { void }- * Opaque<"Name"> (core kernel/markers) → { opaque: "Name" } — the only by-name comparison+ * Opaque<"Name"> (core kernel/markers) → { opaque: "<package>#Name" } — the only by-name+ * comparison, and the name is always qualified by the declaring package* <Name>Slots companion interface → the slots of <Name>; a property typed Slot<D, C>* declares a code half* classes, Map/Set, generics, rest parameters, unions mixing data with non-data → error@@ -98,6 +99,8 @@ function moduleNameOf(fileName) {}const table = {};+/** `@Use` fields typed by a component class — a dependency on an implementation, not a mechanism. */+const implementationDeps = [];/** Named data types, keyed like interfaces; signatures reference them as { "$ref": key }. */const types = {};/** Module manifests, extracted STATICALLY from each module.ts's defineModule({...}) literal. */@@ -584,11 +587,51 @@ for (const project of projects) {return null;}- function opaqueName(type) {+ /**+ * The package a declaration belongs to — the second half of an opaque identity. A+ * by-name comparison is only safe when the name is qualified by who declared it: two+ * packages may both declare a `Resources`, and they must not match.+ */+ const packageCache = new Map();+ function packageOf(fileName) {+ if (/\/lib\.[\w.]+\.d\.ts$/.test(fileName)) return "lib";+ // pnpm nests `node_modules/.pnpm/<pkg>@<ver>/node_modules/<pkg>/…`: the LAST segment names the package.+ const segments = [...fileName.matchAll(/node_modules\/(@[^/]+\/[^/]+|[^/@.][^/]*)/g)];+ if (segments.length > 0) return segments[segments.length - 1][1];+ let dir = path.dirname(fileName);+ for (;;) {+ if (packageCache.has(dir)) return packageCache.get(dir);+ const pkg = path.join(dir, "package.json");+ if (fs.existsSync(pkg)) {+ const name = JSON.parse(fs.readFileSync(pkg, "utf8")).name;+ packageCache.set(dir, name);+ return name;+ }+ const parent = path.dirname(dir);+ if (parent === dir) return "?";+ dir = parent;+ }+ }+ /** `<package>#<name>`: an opaque identity, never a bare name. */+ const opaqueId = (name, fileName) => `${packageOf(fileName)}#${name}`;++ /**+ * The identity of an `Opaque<"Name", T>`: the name, qualified by the package declaring+ * T (else the package writing the marker) — so the same word in two packages is two+ * identities.+ */+ function opaqueName(type, atNode) {const prop = type.getProperty("__opaque");if (!prop) return null;const t = checker.getNonNullableType(checker.getTypeOfSymbol(prop));- return t.isStringLiteral() ? t.value : null;+ if (!t.isStringLiteral()) return null;+ const parts = type.isIntersection()+ ? type.types.filter((x) => !x.getProperty("__opaque") || x.getProperties().length > 1)+ : [type];+ const declaring = parts+ .map((x) => (x.aliasSymbol ?? x.getSymbol())?.declarations?.[0]?.getSourceFile()?.fileName)+ .find((f) => f !== undefined);+ return opaqueId(t.value, declaring ?? atNode.getSourceFile().fileName);}/** TypeExpr for any type in a signature position. */@@ -596,7 +639,7 @@ for (const project of projects) {notData = "";const f = type.getFlags();if (f & ts.TypeFlags.Void) return { void: true };- const opaque = opaqueName(type);+ const opaque = opaqueName(type, atNode);if (opaque !== null) return { opaque };const symbol = type.getSymbol();const name = symbol?.getName();@@ -649,7 +692,17 @@ for (const project of projects) {`tuple '${checker.typeToString(type)}' holds a non-data element (${notData})`,);}- if (isHostDeclared(symbol)) return { opaque: name };+ // A mapped or anonymous type (`Pick<…>`, `Record<…>`, an inline `{…}`) has the lib's+ // `__type` symbol; it is a shape, not a host object. With methods and a name (a+ // `type X = Pick<…>` alias) it is an interface keyed by the alias; otherwise its+ // members are projected in place.+ const anonymous = name === "__type" || name === "__object";+ if (anonymous && type.aliasSymbol && hasMethods(type, atNode)) {+ const aliasDecl = type.aliasSymbol.declarations?.[0];+ if (aliasDecl) return { iface: keyOf(type.aliasSymbol, aliasDecl) };+ }+ if (!anonymous && isHostDeclared(symbol))+ return { opaque: opaqueId(name, symbol.declarations[0].getSourceFile().fileName) };// A plain object shape some member of which is not data (a Buffer field, a callback// property): structured, compared member by member.if (@@ -672,6 +725,16 @@ for (const project of projects) {if (symbol && symbol.flags & ts.SymbolFlags.Class && !isIfaceClass(symbol)) {return fail(atNode, `class '${name}' in a signature: wrap it as Opaque<"${name}">`);}+ // Inside a component's own surface, an interface with methods that is not an+ // interface class is a host object of that class's world, compared by name — the+ // component does not publish its dependencies' types as contracts.+ if (lenient && hasMethods(type, atNode) && !isIfaceClass(symbol))+ return {+ opaque: opaqueId(+ name,+ symbol?.declarations?.[0]?.getSourceFile()?.fileName ?? atNode.getSourceFile().fileName,+ ),+ };if (hasMethods(type, atNode) || isIfaceClass(symbol)) {const decl = symbol?.declarations?.find((d) =>@@ -718,6 +781,8 @@ for (const project of projects) {return { params, returns: exprOf(signature.getReturnType(), atNode, stack) };}+ /** True while a component member is being projected (see `tolerant` in ifaceOf). */+ let lenient = false;const LIFECYCLE = new Set(["setup", "park", "migrations"]);/** A member of a component class that is not part of its interface. */const isHiddenMember = (prop) => {@@ -742,13 +807,21 @@ for (const project of projects) {const tolerant = (prop, project) => {if (!component) return project();const mark = errors.length;- const out = project();+ lenient = true;+ let out;+ try {+ out = project();+ } finally {+ lenient = false;+ }if (errors.length === mark) return out;const why = errors.splice(mark).map((e) => e.slice(e.indexOf(": ") + 2));warnings.push(`${where(prop.valueDeclaration ?? decl)}: component member '${prop.getName()}' is opaque in the contract (${why.join("; ")})`,);- return { opaque: `${symbol.getName()}.${prop.getName()}` };+ return {+ opaque: opaqueId(`${symbol.getName()}.${prop.getName()}`, decl.getSourceFile().fileName),+ };};for (const prop of type.getProperties()) {if (component && isHiddenMember(prop)) continue;@@ -871,6 +944,7 @@ for (const project of projects) {for (const [sym, { node, meta, file, kind, className }] of moduleClasses) {const m = {name: meta.name,+ kind,requires: {},provides: {},contributes: meta.contributes ?? {},@@ -879,6 +953,23 @@ for (const project of projects) {if (meta.context !== undefined) m.context = meta.context;if (kind === "component") {m.provides[className] = componentKeyBySymbol.get(sym);+ // `implements Users`: the component declares the mechanism it implements; the+ // provision is the same instance under the interface's name.+ for (const clause of node.heritageClauses ?? []) {+ if (clause.token !== ts.SyntaxKind.ImplementsKeyword) continue;+ for (const t of clause.types) {+ const s0 = checker.getSymbolAtLocation(t.expression);+ const isym = s0 && s0.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(s0) : s0;+ const idecl = isym?.declarations?.find((d) => isInterfaceClassDecl(d));+ if (!idecl) {+ errors.push(+ `${file}: ${className} implements '${t.getText()}', which is not an interface class (extends Interface<…>())`,+ );+ continue;+ }+ m.provides[isym.getName()] = keyOf(isym, idecl);+ }+ }if (meta.children !== undefined)errors.push(`${file}: a @Component has no children — it exports itself`);}@@ -893,6 +984,8 @@ for (const project of projects) {const use = decoratorCall(member, "Use");if (use) {const req = { iface: ifaceKeyOfType(member.type, file) };+ if (componentOfType(member.type) !== undefined)+ implementationDeps.push(`${m.name}.${field} → ${member.type.getText()}`);if (use.arguments.length > 0) {const ref = refLiteral(use.arguments[0], file);const fromName = moduleNameBySymbol.get(ref?.$id);@@ -913,6 +1006,19 @@ for (const project of projects) {m.provides[field] = ifaceKeyOfType(member.type, file);}}+ // `exports: [Users, …]`: the module forwards a child's provision under that interface.+ for (const exp of meta.exports ?? []) {+ const isym = exp?.$id;+ const idecl = isym?.declarations?.find((d) => isInterfaceClassDecl(d));+ if (!idecl) {+ errors.push(+ `${file}: exports: an entry is not an interface class (extends Interface<…>())`,+ );+ continue;+ }+ m.provides[isym.getName()] = keyOf(isym, idecl);+ (m.exports ??= []).push(isym.getName());+ }for (const child of meta.children ?? []) {const childName = moduleNameBySymbol.get(child?.$id);if (childName === undefined)@@ -922,6 +1028,40 @@ for (const project of projects) {if (manifests[m.name]) errors.push(`${file}: module '${m.name}' is defined twice`);manifests[m.name] = m;}+ // Wire every requirement that names no module to the module that will provide it —+ // the one visible provider declaring that very interface (siblings, or an ancestor's+ // siblings; never an ancestor). Recorded as `from`, so the table says which MODULE a+ // node depends on, not only which interface, and the booter follows the same choice.+ {+ const childOf = new Map();+ for (const m of Object.values(manifests))+ for (const c of m.children) if (c !== "*") childOf.set(c, m.name);+ const visibleOf = (name) => {+ const out = new Set();+ const ancestors = new Set();+ let cur = name;+ for (;;) {+ const parent = childOf.get(cur);+ if (parent === undefined) break;+ ancestors.add(parent);+ for (const s of manifests[parent].children) if (s !== "*" && s !== name) out.add(s);+ cur = parent;+ }+ for (const a of ancestors) out.delete(a); // an ancestor's exports face outward, not down+ return out;+ };+ for (const m of Object.values(manifests)) {+ if (!childOf.has(m.name)) continue; // roots and extension modules: the booter decides+ const visible = visibleOf(m.name);+ for (const [alias, req] of Object.entries(m.requires)) {+ if (req.from !== undefined) continue;+ const declaring = [...visible].filter((v) =>+ Object.values(manifests[v]?.provides ?? {}).includes(req.iface),+ );+ if (declaring.length === 1) req.from = declaring[0];+ }+ }+ }for (const { symbol, decl, owner, sf } of slotCompanions) {const ownerExp = checker.getExportsOfModule(checker.getSymbolAtLocation(sf))@@ -941,6 +1081,10 @@ for (const project of projects) {}for (const w of warnings) console.warn(`gen-ifaces: warning: ${w}`);+// A node depends on mechanisms, never on implementations: a `@Use` field typed by a+// @Component class is refused. The component implements an interface class; require that.+for (const dep of implementationDeps)+ errors.push(`${dep}: a @Use field names an implementation; require the interface it implements`);if (errors.length > 0) {for (const e of errors) console.error(`gen-ifaces: error: ${e}`);process.exit(1);diff --git a/scripts/iface-page.mjs b/scripts/iface-page.mjsindex 870f1949..2c59ebd3 100644--- a/scripts/iface-page.mjs+++ b/scripts/iface-page.mjs@@ -69,6 +69,7 @@ nav button.current { outline: 1px solid var(--line); }.kind.module { color: var(--mod); border-color: var(--mod); }.kind.component { color: var(--comp); border-color: var(--comp); }.kind.iface { color: var(--accent); border-color: var(--accent); }+.kind.group { color: var(--ink); border-color: var(--ink); }.kind.slot { color: var(--muted); border-color: var(--muted); }section { padding: 16px 24px; max-width: 1100px; }section h2 { margin: 0 0 4px; font-size: 20px; }@@ -104,7 +105,7 @@ const T = JSON.parse(document.getElementById("data").textContent);const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);const short = (key) => key.slice(key.indexOf("#") + 1);const ref = (key, kind) => '<a class="ref" href="#' + kind + ':' + encodeURIComponent(key) + '" title="' + esc(key) + '">' + esc(short(key)) + "</a>";-const isComponent = (m) => Object.entries(m.provides).length === 1 && Object.entries(m.provides).every(([alias, key]) => key === m.name + "#" + alias);+const kindOf = (m) => (m.kind === "component" ? "component" : m.exports?.length ? "group" : "module");// --- TypeExpr → TypeScript-ish text (mirrors core kernel/sig.ts) ---function data(d) {@@ -122,7 +123,7 @@ function expr(e) {if ("data" in e) return data(e.data);if ("$ref" in e) return ref(e.$ref, "type");if ("iface" in e) return ref(e.iface, "iface");- if ("opaque" in e) return '<span class="opaque">' + esc(e.opaque) + "</span>";+ if ("opaque" in e) return '<span class="opaque" title="' + esc(e.opaque) + '">' + esc(short(e.opaque)) + "</span>";if ("void" in e) return "void";if ("promise" in e) return "Promise<" + expr(e.promise) + ">";if ("stream" in e) return "AsyncIterable<" + expr(e.stream) + ">";@@ -146,7 +147,7 @@ const roots = Object.keys(modules).filter((n) => !childOf.has(n));function node(name) {const m = modules[name];if (!m) return "<li><button disabled>" + esc(name) + " (not in this table)</button></li>";- const kind = isComponent(m) ? "component" : "module";+ const kind = kindOf(m);const kids = m.children.map((c) => (c === "*" ? '<li><span class="kind slot">slot</span><span class="muted">plugin modules</span></li>' : node(c))).join("");return "<li data-name=\\"" + esc(name) + "\\"><button data-go=\\"node:" + encodeURIComponent(name) + "\\"><span class=\\"kind " + kind + "\\">" + kind[0] + "</span>" + esc(name) + "</button>" + (kids ? "<ul>" + kids + "</ul>" : "") + "</li>";}@@ -159,7 +160,7 @@ document.getElementById("tree").innerHTML =// --- detail ---function showNode(name) {const m = modules[name];- const kind = isComponent(m) ? "component" : "module";+ const kind = kindOf(m);const req = Object.entries(m.requires);const prov = Object.entries(m.provides);const contrib = Object.entries(m.contributes);@@ -168,8 +169,8 @@ function showNode(name) {(m.context ? "<p class=\\"muted\\">parks context v" + esc(m.context.version) + "</p>" : "") +"<h3>requires (" + req.length + ")</h3>" + (req.length ? "<table><tr><th>field</th><th>interface</th><th>from</th></tr>" +req.map(([f, r]) => "<tr><td><code>" + esc(f) + "</code></td><td>" + ref(r.iface, "iface") + "</td><td>" + (r.from ? '<a class="ref" href="#node:' + encodeURIComponent(r.from) + '">' + esc(r.from) + "</a>" : "<span class=\\"muted\\">by structure</span>") + "</td></tr>").join("") + "</table>" : "<p class=\\"muted\\">nothing</p>") +- "<h3>provides (" + prov.length + ")</h3>" + (prov.length ? "<table><tr><th>alias</th><th>interface</th></tr>" +- prov.map(([a, k]) => "<tr><td><code>" + esc(a) + "</code></td><td>" + ref(k, "iface") + "</td></tr>").join("") + "</table>" : "<p class=\\"muted\\">nothing</p>") ++ "<h3>" + (m.exports?.length ? "exports" : "provides") + " (" + prov.length + ")</h3>" + (prov.length ? "<table><tr><th>alias</th><th>interface</th>" + (m.exports?.length ? "<th></th>" : "") + "</tr>" ++ prov.map(([a, k]) => "<tr><td><code>" + esc(a) + "</code></td><td>" + ref(k, "iface") + "</td>" + (m.exports?.length ? "<td class=\\"muted\\">" + (m.exports.includes(a) ? "from a child" : "") + "</td>" : "") + "</tr>").join("") + "</table>" : "<p class=\\"muted\\">nothing</p>") +"<h3>contributes (" + contrib.length + ")</h3>" + (contrib.length ? contrib.map(([slot, items]) =>"<details open><summary><code>" + esc(slot) + "</code> × " + items.length + "</summary><pre>" + esc(JSON.stringify(items, null, 2)) + "</pre></details>").join("") : "<p class=\\"muted\\">nothing</p>") +(m.children.length ? "<h3>children (" + m.children.length + ")</h3><p>" + m.children.map((c) => c === "*" ? "<span class=\\"muted\\">+ plugin modules</span>" : '<a class="ref" href="#node:' + encodeURIComponent(c) + '">' + esc(c) + "</a>").join(", ") + "</p>" : "") +