Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2879da1f6a |
@@ -8,7 +8,6 @@ coverage
|
||||
.env.local
|
||||
*.tsbuildinfo
|
||||
.pnpm-store
|
||||
__pycache__/
|
||||
docs/reports/
|
||||
|
||||
# Step-CA dev password — real file is gitignored; commit only the .example
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
pnpm preflight && pnpm typecheck && pnpm lint && pnpm format:check
|
||||
pnpm typecheck && pnpm lint && pnpm format:check
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
@mosaicstack:registry=https://git.mosaicstack.dev/api/packages/mosaicstack/npm/
|
||||
# HOME resolves to /root in the ci-base image, preserving its warmed-store path.
|
||||
# Non-root checkouts use their own HOME. Override without editing this file via
|
||||
# NPM_CONFIG_STORE_DIR (pnpm's environment form of the store-dir setting).
|
||||
store-dir=${HOME}/.local/share/pnpm/store
|
||||
# Pin the pnpm store to the same path the ci-base image warms (Dockerfile.ci),
|
||||
# so the pipeline `pnpm install --prefer-offline` consumes the baked store
|
||||
# instead of repopulating a fresh one.
|
||||
store-dir=/root/.local/share/pnpm/store
|
||||
|
||||
@@ -4,15 +4,6 @@ pnpm-lock.yaml
|
||||
**/node_modules
|
||||
**/drizzle
|
||||
**/.next
|
||||
# Python build/test artifacts — same category as node_modules/dist/.next above.
|
||||
# Prettier must never scan generated trees; without these a local venv poisons
|
||||
# `pnpm format:check` with thousands of third-party files.
|
||||
**/venv
|
||||
**/__pycache__
|
||||
**/.mypy_cache
|
||||
**/.pytest_cache
|
||||
**/htmlcov
|
||||
.claude/
|
||||
docs/tess/TASKS.md
|
||||
docs/scratchpads/
|
||||
packages/mosaic/src/fleet/testdata/documentation-publication-v1/inline-migration-v1.json
|
||||
|
||||
+1
-51
@@ -7,14 +7,7 @@ variables:
|
||||
- &enable_pnpm 'corepack enable'
|
||||
|
||||
when:
|
||||
# PR + manual CI run on any branch — the pull_request pipeline is the merge gate.
|
||||
# push CI is restricted to protected branches (main) so a feature-branch push no
|
||||
# longer fires a redundant SECOND pipeline alongside its PR pipeline. This ~halves
|
||||
# CI load on the storage-constrained runner with zero loss of gating (branch
|
||||
# protection requires no push/ci status context; main still gets full push CI).
|
||||
- event: [pull_request, manual]
|
||||
- event: push
|
||||
branch: main
|
||||
- event: [push, pull_request, manual]
|
||||
|
||||
# Turbo remote cache (turbo.mosaicstack.dev) is configured via Woodpecker
|
||||
# repository-level environment variables (TURBO_API, TURBO_TEAM, TURBO_TOKEN).
|
||||
@@ -41,32 +34,6 @@ steps:
|
||||
# (Constitution + dispatcher + each RUNTIME.md slice). See DESIGN §7 / R9.
|
||||
- bash packages/mosaic/framework/tools/quality/scripts/check-resident-budget.sh --self-test
|
||||
- bash packages/mosaic/framework/tools/quality/scripts/check-resident-budget.sh
|
||||
# Test-membership guard (#1017): also first link of test:framework-shell.
|
||||
# Invoked from BOTH surfaces it audits (F2, PR #1018) — the guard is link
|
||||
# [0] of the pnpm chain, so severing that chain would silence it together
|
||||
# with everything it guards; this direct line keeps one instrument running.
|
||||
- bash packages/mosaic/framework/tools/quality/scripts/check-test-enumeration.sh
|
||||
|
||||
# Blocking gate (#791): a framework upgrade must never write or delete an
|
||||
# operator-owned path. The HARD GATE proves an unanticipated operator sentinel
|
||||
# survives a keep-mode reseed byte-identical (with rsync present AND absent —
|
||||
# keep mode is a single cp-based path that must not depend on rsync), and that a
|
||||
# corrupt/empty/missing manifest aborts fail-closed leaving operator files
|
||||
# untouched (B2/B3). The rollback gate proves a mid-sync failure is rolled back
|
||||
# from the pre-update snapshot (B1). The durable-snapshot gate (#791 PR2) proves
|
||||
# the retained, operator-scoped pre-update backup is taken before any mutation
|
||||
# (0700/0600, secret never logged, retention-pruned) and that the post-sync
|
||||
# verify net restores any operator file a manifest bug lets the sync touch. The
|
||||
# migration matrix pins the v2→v3 contract-file semantics. Pure bash, no
|
||||
# node_modules — runs early alongside sanitization.
|
||||
upgrade-guard:
|
||||
image: *node_image
|
||||
commands:
|
||||
- apk add --no-cache bash rsync
|
||||
- bash packages/mosaic/framework/tools/quality/scripts/test-upgrade-manifest-guard.sh
|
||||
- bash packages/mosaic/framework/tools/quality/scripts/test-upgrade-rollback.sh
|
||||
- bash packages/mosaic/framework/tools/quality/scripts/test-upgrade-durable-snapshot.sh
|
||||
- bash packages/mosaic/framework/tools/quality/scripts/test-install-migration.sh
|
||||
|
||||
typecheck:
|
||||
image: *node_image
|
||||
@@ -76,7 +43,6 @@ steps:
|
||||
depends_on:
|
||||
- install
|
||||
- sanitization
|
||||
- upgrade-guard
|
||||
|
||||
# lint, format, and test are independent — run in parallel after typecheck
|
||||
lint:
|
||||
@@ -103,22 +69,6 @@ steps:
|
||||
DATABASE_URL: postgresql://mosaic:mosaic@ci-postgres:5432/mosaic
|
||||
commands:
|
||||
- *enable_pnpm
|
||||
# openssl (#912) is the wake HMAC signer: the digest H1/H2, beacon B12,
|
||||
# and install I8 legs hard-require it in CI. It is baked into ci-base via
|
||||
# Dockerfile.ci, but ci-base only rebuilds on push-to-main/tag — this
|
||||
# `apk add` guarantees openssl is present on PR pipelines too (and is a
|
||||
# fast no-op once the rebuilt image already ships it).
|
||||
- apk add --no-cache openssl
|
||||
# Pi runtime (Invariant R): invariant_r_unittest.py hard-requires an
|
||||
# installed `pi` binary at exactly this measured version — the test
|
||||
# boots Pi's real tool registry to prove the read-only carve-out
|
||||
# resolves to real, unshadowed builtins, and fails loud (by design)
|
||||
# when the runtime is absent or drifts. The canonical Pi is
|
||||
# @earendil-works/[email protected] exactly (@mariozechner/* is
|
||||
# embedded-legacy). Step-level install because ci-base image publishes
|
||||
# are currently blocked on registry auth; fold into Dockerfile.ci once
|
||||
# that is fixed, keeping this as a fast no-op guard.
|
||||
- npm install -g @earendil-works/[email protected]
|
||||
# postgresql-client (pg_isready) is baked into ci-base.
|
||||
# Wait up to 60s for CI postgres to be ready; fail fast if it never comes up.
|
||||
- |
|
||||
|
||||
+5
-104
@@ -1,5 +1,5 @@
|
||||
# Build, publish npm packages, and push Docker images
|
||||
# Runs on main for stable publishes and on next for integration-line prereleases/images
|
||||
# Runs only on main branch push/tag
|
||||
|
||||
variables:
|
||||
# Pre-baked CI base (see .woodpecker/ci-image.yml): node:24-alpine +
|
||||
@@ -23,21 +23,9 @@ variables:
|
||||
- 'docs/**'
|
||||
- '**/*.md'
|
||||
- '.woodpecker/**'
|
||||
- event: [push, manual]
|
||||
branch: next
|
||||
- &main_image_build_when
|
||||
- event: tag
|
||||
- event: [push, manual]
|
||||
branch: main
|
||||
path:
|
||||
exclude:
|
||||
- 'packages/mosaic/**'
|
||||
- 'docs/**'
|
||||
- '**/*.md'
|
||||
- '.woodpecker/**'
|
||||
|
||||
when:
|
||||
- branch: [main, next]
|
||||
- branch: [main]
|
||||
event: [push, manual, tag]
|
||||
|
||||
steps:
|
||||
@@ -115,84 +103,6 @@ steps:
|
||||
depends_on:
|
||||
- build
|
||||
|
||||
publish-next-npm:
|
||||
image: *node_image
|
||||
# Durable @next integration-line publish. Runs only on next; never writes
|
||||
# the latest dist-tag and never commits the computed prerelease versions.
|
||||
when:
|
||||
- event: [push, manual]
|
||||
branch: next
|
||||
environment:
|
||||
NPM_TOKEN:
|
||||
from_secret: gitea_token
|
||||
CI_COMMIT_BRANCH: ${CI_COMMIT_BRANCH}
|
||||
CI_PIPELINE_NUMBER: ${CI_PIPELINE_NUMBER}
|
||||
commands:
|
||||
- *enable_pnpm
|
||||
- |
|
||||
if [ "$CI_COMMIT_BRANCH" != "next" ]; then
|
||||
echo "[publish-next] FATAL: publish-next-npm may only run on next (got '$CI_COMMIT_BRANCH')" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ -z "$CI_PIPELINE_NUMBER" ]; then
|
||||
echo "[publish-next] FATAL: CI_PIPELINE_NUMBER is required for prerelease versioning" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "//git.mosaicstack.dev/api/packages/mosaicstack/npm/:_authToken=$NPM_TOKEN" > ~/.npmrc
|
||||
echo "@mosaicstack:registry=https://git.mosaicstack.dev/api/packages/mosaicstack/npm/" >> ~/.npmrc
|
||||
DIST_TAGS_JSON="$(npm view @mosaicstack/mosaic dist-tags --registry https://git.mosaicstack.dev/api/packages/mosaicstack/npm/ --json)"
|
||||
DIST_TAGS_JSON="$DIST_TAGS_JSON" node -e 'const tags = JSON.parse(process.env.DIST_TAGS_JSON || "{}"); if (!tags || typeof tags !== "object" || !Object.hasOwn(tags, "latest")) { throw new Error("Gitea npm registry did not return a usable dist-tags object"); } console.log("[publish-next] registry dist-tags OK: latest=" + tags.latest);'
|
||||
node <<'NODE'
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const pipelineNumber = process.env.CI_PIPELINE_NUMBER;
|
||||
const roots = ['apps', 'packages', 'plugins'];
|
||||
const updated = [];
|
||||
|
||||
function walk(dir) {
|
||||
if (!fs.existsSync(dir)) return;
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
if (entry.name === 'node_modules' || entry.name === 'dist' || entry.name === '.turbo') continue;
|
||||
const fullPath = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
const packagePath = path.join(fullPath, 'package.json');
|
||||
if (fs.existsSync(packagePath)) updatePackage(packagePath);
|
||||
walk(fullPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function updatePackage(packagePath) {
|
||||
const manifest = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
|
||||
if (!manifest.name?.startsWith('@mosaicstack/') || manifest.private) return;
|
||||
const stableMatch = /^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(manifest.version);
|
||||
if (!stableMatch) {
|
||||
throw new Error(manifest.name + " has unsupported semver version '" + manifest.version + "'");
|
||||
}
|
||||
const [, major, minor, patch] = stableMatch;
|
||||
const oldVersion = manifest.version;
|
||||
manifest.version = major + '.' + minor + '.' + (Number(patch) + 1) + '-next.' + pipelineNumber;
|
||||
fs.writeFileSync(packagePath, JSON.stringify(manifest, null, 2) + '\n');
|
||||
updated.push(manifest.name + ' ' + oldVersion + ' -> ' + manifest.version);
|
||||
}
|
||||
|
||||
for (const root of roots) walk(root);
|
||||
if (updated.length === 0) throw new Error('No publishable @mosaicstack/* packages found');
|
||||
console.log('[publish-next] computed prerelease versions for ' + updated.length + ' packages:');
|
||||
for (const line of updated) console.log('[publish-next] ' + line);
|
||||
NODE
|
||||
pnpm --filter "@mosaicstack/*" --filter "!@mosaicstack/web" --filter "!@mosaicstack/mosaic-as" publish --no-git-checks --access public --tag next
|
||||
EXPECTED_VERSION="$(node -p "require('./packages/mosaic/package.json').version")"
|
||||
RESOLVED_VERSION="$(npm view @mosaicstack/mosaic@next version --registry https://git.mosaicstack.dev/api/packages/mosaicstack/npm/)"
|
||||
if [ "$RESOLVED_VERSION" != "$EXPECTED_VERSION" ]; then
|
||||
echo "[publish-next] FATAL: @mosaicstack/mosaic@next resolved '$RESOLVED_VERSION', expected '$EXPECTED_VERSION'" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "[publish-next] @mosaicstack/mosaic@next resolves to $RESOLVED_VERSION"
|
||||
depends_on:
|
||||
- build
|
||||
|
||||
# TODO: Uncomment when ready to publish to npmjs.org
|
||||
# publish-npmjs:
|
||||
# image: *node_image
|
||||
@@ -224,17 +134,8 @@ steps:
|
||||
- echo "{\"auths\":{\"git.mosaicstack.dev\":{\"username\":\"$REGISTRY_USER\",\"password\":\"$REGISTRY_PASS\"}}}" > /kaniko/.docker/config.json
|
||||
- |
|
||||
DESTINATIONS="--destination git.mosaicstack.dev/mosaicstack/stack/gateway:sha-${CI_COMMIT_SHA:0:7}"
|
||||
if [ "$CI_COMMIT_BRANCH" = "next" ]; then
|
||||
if [ -n "$CI_COMMIT_TAG" ]; then
|
||||
echo "[publish] FATAL: next gateway publish must be sha-only; refusing tag '$CI_COMMIT_TAG'" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "[publish] next gateway publish is sha-only"
|
||||
elif [ "$CI_COMMIT_BRANCH" = "main" ]; then
|
||||
if [ "$CI_COMMIT_BRANCH" = "main" ]; then
|
||||
DESTINATIONS="$DESTINATIONS --destination git.mosaicstack.dev/mosaicstack/stack/gateway:latest"
|
||||
elif [ -z "$CI_COMMIT_TAG" ]; then
|
||||
echo "[publish] FATAL: gateway image publish may only run for main, next, or tag events" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ -n "$CI_COMMIT_TAG" ]; then
|
||||
DESTINATIONS="$DESTINATIONS --destination git.mosaicstack.dev/mosaicstack/stack/gateway:$CI_COMMIT_TAG"
|
||||
@@ -245,7 +146,7 @@ steps:
|
||||
|
||||
build-appservice:
|
||||
image: gcr.io/kaniko-project/executor:debug
|
||||
when: *main_image_build_when
|
||||
when: *image_build_when
|
||||
environment:
|
||||
REGISTRY_USER:
|
||||
from_secret: gitea_username
|
||||
@@ -271,7 +172,7 @@ steps:
|
||||
|
||||
build-web:
|
||||
image: gcr.io/kaniko-project/executor:debug
|
||||
when: *main_image_build_when
|
||||
when: *image_build_when
|
||||
environment:
|
||||
REGISTRY_USER:
|
||||
from_secret: gitea_username
|
||||
|
||||
@@ -11,87 +11,48 @@
|
||||
|
||||
## Project Context
|
||||
|
||||
Mosaic Stack is a self-hosted, multi-user AI agent platform. It is a TypeScript monorepo with a NestJS gateway, Next.js dashboard, Pi SDK agent runtime, and Discord/Telegram plugin architecture.
|
||||
Mosaic Stack is a self-hosted, multi-user AI agent platform. TypeScript monorepo with NestJS gateway, Next.js web dashboard, Pi SDK agent runtime, and plugin architecture for Discord/Telegram.
|
||||
|
||||
### Stack
|
||||
## Package Map
|
||||
|
||||
- **API:** NestJS with Fastify (`apps/gateway`)
|
||||
- **Web:** Next.js 16 with React 19 (`apps/web`)
|
||||
- **ORM and database:** Drizzle ORM, PostgreSQL 17, and pgvector (`packages/db`)
|
||||
- **Authentication:** BetterAuth (`packages/auth`)
|
||||
- **Agent runtime:** Pi SDK (`apps/gateway`, `packages/mosaic`)
|
||||
- **Queue:** Valkey 8 (`packages/queue`)
|
||||
- **Build:** pnpm workspaces and Turborepo
|
||||
- **CI:** Woodpecker CI
|
||||
- **Observability:** OpenTelemetry and Jaeger
|
||||
| Package | Purpose | Key Dependencies |
|
||||
| ------------------ | ------------------------------- | -------------------------------- |
|
||||
| `apps/gateway` | NestJS API + WebSocket hub | Fastify, Socket.IO, Pi SDK, OTEL |
|
||||
| `apps/web` | Next.js dashboard | React 19, Tailwind |
|
||||
| `packages/types` | Shared TypeScript contracts | class-validator |
|
||||
| `packages/db` | Drizzle ORM schema + migrations | drizzle-orm, postgres |
|
||||
| `packages/auth` | BetterAuth configuration | better-auth, @mosaicstack/db |
|
||||
| `packages/brain` | Data layer (PG-backed) | @mosaicstack/db |
|
||||
| `packages/queue` | Valkey task queue + MCP | ioredis |
|
||||
| `packages/coord` | Mission coordination | @mosaicstack/queue |
|
||||
| `packages/mosaic` | Unified `mosaic` CLI + TUI | Ink, Pi SDK, commander |
|
||||
| `plugins/discord` | Discord channel plugin | discord.js |
|
||||
| `plugins/telegram` | Telegram channel plugin | Telegraf |
|
||||
|
||||
### Package Map
|
||||
## Architecture Rules
|
||||
|
||||
| Package | Purpose | Key Dependencies |
|
||||
| ------------------ | ----------------------------- | -------------------------------- |
|
||||
| `apps/gateway` | NestJS API + WebSocket hub | Fastify, Socket.IO, Pi SDK, OTEL |
|
||||
| `apps/web` | Next.js dashboard | React 19, Tailwind |
|
||||
| `packages/types` | Shared TypeScript contracts | class-validator |
|
||||
| `packages/db` | Drizzle schema and migrations | drizzle-orm, postgres |
|
||||
| `packages/auth` | BetterAuth configuration | better-auth, @mosaicstack/db |
|
||||
| `packages/brain` | Structured data layer | @mosaicstack/db |
|
||||
| `packages/queue` | Valkey task queue and MCP | ioredis |
|
||||
| `packages/coord` | Mission coordination | @mosaicstack/queue |
|
||||
| `packages/mosaic` | Unified `mosaic` CLI and TUI | Ink, Pi SDK, commander |
|
||||
| `plugins/discord` | Discord channel plugin | discord.js |
|
||||
| `plugins/telegram` | Telegram channel plugin | Telegraf |
|
||||
|
||||
## Architecture and Code Conventions
|
||||
|
||||
1. Gateway is the single API surface; all clients connect through it.
|
||||
2. Pi SDK is ESM-only; gateway and CLI code must remain ESM.
|
||||
3. Use `"type": "module"`, NodeNext module resolution, and `.js` extensions in imports.
|
||||
4. Keep typed Socket.IO events in `@mosaicstack/types` to enforce client/server contracts.
|
||||
5. Import OTEL tracing before NestJS bootstrap (`import './tracing.js'`).
|
||||
6. Use explicit `@Inject()` decorators in NestJS because tsx/esbuild does not emit decorator metadata.
|
||||
7. Keep DTOs in `*.dto.ts` files at module boundaries.
|
||||
8. BetterAuth owns authentication tables; their schema is defined in `@mosaicstack/db`.
|
||||
9. Create a task-specific scratchpad for non-trivial work.
|
||||
1. Gateway is the single API surface — all clients connect through it
|
||||
2. Pi SDK is ESM-only — gateway and CLI must use ESM
|
||||
3. Socket.IO typed events defined in `@mosaicstack/types` enforce compile-time contracts
|
||||
4. OTEL auto-instrumentation loads before NestJS bootstrap
|
||||
5. BetterAuth manages auth tables; schema defined in `@mosaicstack/db`
|
||||
6. Docker Compose provides PG (5433), Valkey (6380), OTEL Collector (4317/4318), Jaeger (16686)
|
||||
7. Explicit `@Inject()` decorators required in NestJS (tsx/esbuild doesn't emit decorator metadata)
|
||||
|
||||
## Development Workflow
|
||||
|
||||
Requirements: Node.js 20+, pnpm 10.6.2, and Docker Compose when optional local services are needed.
|
||||
|
||||
```bash
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm preflight
|
||||
|
||||
# Optional local queue service only; do not start the full Compose stack.
|
||||
docker compose up -d valkey
|
||||
docker compose up -d # Infrastructure
|
||||
pnpm install # Dependencies
|
||||
pnpm typecheck && pnpm lint && pnpm format:check # Quality gates
|
||||
```
|
||||
|
||||
The pre-push hook requires:
|
||||
## Repo-Specific Notes
|
||||
|
||||
```bash
|
||||
pnpm preflight && pnpm typecheck && pnpm lint && pnpm format:check
|
||||
```
|
||||
|
||||
Software delivery also requires the applicable tests. Common repository commands are:
|
||||
|
||||
```bash
|
||||
pnpm typecheck # TypeScript checks across the workspace
|
||||
pnpm lint # ESLint across the workspace
|
||||
pnpm test # Checkout tests and package Vitest suites
|
||||
pnpm format:check # Prettier check
|
||||
pnpm build # Build all packages and applications
|
||||
```
|
||||
|
||||
## Database and Local Runtime Safety
|
||||
|
||||
- Current local data-layer work uses in-process PGlite; leave `DATABASE_URL` unset.
|
||||
- PostgreSQL execution is held until KBN-101-00, KBN-101-03, and KBN-101-05 land.
|
||||
- Do not invoke a migration runner, initialization SQL, or the Compose PostgreSQL service from this checkout.
|
||||
- Do not start Gateway/Web or run root `pnpm dev` as a local PGlite route. The current dotenv loader can inherit a daemon PostgreSQL DSN; KBN-101-02 must make that path fail closed first.
|
||||
- Migration artifact generation is offline and does not authorize PostgreSQL access:
|
||||
|
||||
```bash
|
||||
pnpm --filter @mosaicstack/db db:generate
|
||||
```
|
||||
- DTOs in `*.dto.ts` files at module boundaries
|
||||
- ESM everywhere (`"type": "module"`, `.js` extensions in imports)
|
||||
- NodeNext module resolution in all tsconfigs
|
||||
- Scratchpads are mandatory for non-trivial tasks
|
||||
|
||||
## docs/TASKS.md — Schema (CANONICAL)
|
||||
|
||||
|
||||
@@ -1,5 +1,45 @@
|
||||
# Claude Compatibility Pointer
|
||||
# CLAUDE.md — Mosaic Stack
|
||||
|
||||
@AGENTS.md
|
||||
## Project
|
||||
|
||||
Do not add project guidance here. Keep `AGENTS.md` authoritative so every agent runtime receives the same instructions.
|
||||
Self-hosted, multi-user AI agent platform. TypeScript monorepo.
|
||||
|
||||
## Stack
|
||||
|
||||
- **API**: NestJS + Fastify adapter (`apps/gateway`)
|
||||
- **Web**: Next.js 16 + React 19 (`apps/web`)
|
||||
- **ORM**: Drizzle ORM + PostgreSQL 17 + pgvector (`packages/db`)
|
||||
- **Auth**: BetterAuth (`packages/auth`)
|
||||
- **Agent**: Pi SDK (`packages/agent`, `packages/mosaic`)
|
||||
- **Queue**: Valkey 8 (`packages/queue`)
|
||||
- **Build**: pnpm workspaces + Turborepo
|
||||
- **CI**: Woodpecker CI
|
||||
- **Observability**: OpenTelemetry → Jaeger
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
pnpm typecheck # TypeScript check (all packages)
|
||||
pnpm lint # ESLint (all packages)
|
||||
pnpm format:check # Prettier check
|
||||
pnpm test # Vitest (all packages)
|
||||
pnpm build # Build all packages
|
||||
|
||||
# Database
|
||||
pnpm --filter @mosaicstack/db db:push # Push schema to PG (dev)
|
||||
pnpm --filter @mosaicstack/db db:generate # Generate migrations
|
||||
pnpm --filter @mosaicstack/db db:migrate # Run migrations
|
||||
|
||||
# Dev
|
||||
docker compose up -d # Start PG, Valkey, OTEL, Jaeger
|
||||
pnpm --filter @mosaicstack/gateway exec tsx src/main.ts # Start gateway
|
||||
```
|
||||
|
||||
## Conventions
|
||||
|
||||
- ESM everywhere (`"type": "module"`, `.js` extensions in imports)
|
||||
- NodeNext module resolution
|
||||
- Explicit `@Inject()` decorators in NestJS (tsx/esbuild doesn't support emitDecoratorMetadata)
|
||||
- DTOs in `*.dto.ts` files at module boundaries
|
||||
- OTEL tracing imported before NestJS bootstrap (`import './tracing.js'`)
|
||||
- All three gates must pass before push: typecheck, lint, format:check
|
||||
|
||||
+4
-7
@@ -22,13 +22,10 @@
|
||||
FROM node:24-alpine
|
||||
|
||||
# Native toolchain required to compile node-gyp deps on musl, plus the
|
||||
# postgresql-client used by the test step's pg_isready readiness probe. `bash`,
|
||||
# `git`, and `jq` are baked here too — framework shell tests and the shipped
|
||||
# Codex review wrappers require them without per-run installation in ci.yml.
|
||||
# `openssl` (#912) is the non-circular HMAC signer for the wake trust layer:
|
||||
# the digest H1/H2, beacon B12, and install I8 legs hard-require it in CI so the
|
||||
# §4 G6 evidence comes from an actually-run HMAC leg, not a skipped one.
|
||||
RUN apk add --no-cache python3 make g++ postgresql-client bash git jq openssl
|
||||
# postgresql-client used by the test step's pg_isready readiness probe. `bash`
|
||||
# is baked here too — the sanitization step in ci.yml otherwise does a per-run
|
||||
# `apk add bash`.
|
||||
RUN apk add --no-cache python3 make g++ postgresql-client bash
|
||||
|
||||
# Pin pnpm to the repo's packageManager version via corepack.
|
||||
RUN corepack enable && corepack prepare [email protected] --activate
|
||||
|
||||
@@ -30,16 +30,6 @@ This installs both components:
|
||||
| **Framework** | Bash launcher, guides, runtime configs, tools, skills | `~/.config/mosaic/` |
|
||||
| **@mosaicstack/mosaic** | Unified `mosaic` CLI — TUI, gateway client, wizard, auto-updater | `~/.npm-global/bin/` |
|
||||
|
||||
### Install lanes
|
||||
|
||||
| Lane | Command | Use when | Source |
|
||||
| ------------------------ | ------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------------------------- |
|
||||
| Stable | `bash tools/install.sh` | You want the released Mosaic CLI/framework | npm registry `@mosaicstack/mosaic@latest` + framework archive at `main` |
|
||||
| Prerelease integration | `bash tools/install.sh --next` | You want the current `next` integration branch | Build-from-source at `next` |
|
||||
| Contributor/source build | `bash tools/install.sh --dev --ref X` | You are testing a branch before release; `--ref` wins | Build-from-source at the requested ref |
|
||||
|
||||
`--next` is shorthand for the prerelease integration lane: it enables source-build mode and uses `next` unless an explicit `--ref` or `MOSAIC_REF` is provided.
|
||||
|
||||
After install, the wizard runs automatically or you can invoke it manually:
|
||||
|
||||
```bash
|
||||
@@ -48,13 +38,9 @@ mosaic wizard # Full guided setup (gateway install → verify)
|
||||
|
||||
### Requirements
|
||||
|
||||
- Node.js ≥ 22
|
||||
- Node.js ≥ 20
|
||||
- npm (for global @mosaicstack/mosaic install)
|
||||
- One or more runtimes:
|
||||
- [Claude Code](https://docs.anthropic.com/en/docs/claude-code)
|
||||
- [Codex](https://github.com/openai/codex)
|
||||
- [OpenCode](https://opencode.ai)
|
||||
- [Pi](https://pi.dev)
|
||||
- One or more runtimes: [Claude Code](https://docs.anthropic.com/en/docs/claude-code), [Codex](https://github.com/openai/codex), [OpenCode](https://opencode.ai), or [Pi](https://github.com/mariozechner/pi-coding-agent)
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -111,10 +97,7 @@ mosaic config path # Print config file path
|
||||
```bash
|
||||
mosaic doctor # Health audit — detect drift and missing files
|
||||
mosaic sync # Sync skills from canonical source
|
||||
mosaic skill list # Audit Claude skill registrations and conflicts
|
||||
mosaic skill register <name> # Register one canonical skill with Claude Code
|
||||
mosaic skill unregister <name> # Remove one Mosaic-owned Claude link
|
||||
mosaic update # Update CLI/framework and auto-register canonical skills
|
||||
mosaic update # Check for and install CLI updates
|
||||
mosaic wizard # Full guided setup wizard
|
||||
mosaic bootstrap <path> # Bootstrap a repo with Mosaic standards
|
||||
mosaic coord init # Initialize a new orchestration mission
|
||||
@@ -174,12 +157,7 @@ mosaic storage status
|
||||
mosaic storage tier
|
||||
mosaic storage export
|
||||
mosaic storage import
|
||||
# Schema migration is unavailable in this release. The current storage wrapper shells
|
||||
# directly to `pnpm --filter @mosaicstack/db db:migrate`; it is legacy N-1,
|
||||
# uncertified, and MUST NOT be invoked pending KBN-101-02/-03/-06/-08 activation.
|
||||
# Future schema migration is non-operative: external bootstrap → TLS/roles → runner
|
||||
# --run → runner --verify → readiness. Tier copy uses only the separately held secure
|
||||
# migrate-tier route.
|
||||
mosaic storage migrate
|
||||
```
|
||||
|
||||
### Telemetry
|
||||
@@ -204,7 +182,7 @@ Consent state is persisted in config. Remote upload is a no-op until you run `mo
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Node.js ≥ 22
|
||||
- Node.js ≥ 20
|
||||
- pnpm 10.6+
|
||||
- Docker & Docker Compose
|
||||
|
||||
@@ -214,50 +192,33 @@ Consent state is persisted in config. Remote upload is a no-op until you run `mo
|
||||
git clone [email protected]:mosaicstack/stack.git
|
||||
cd stack
|
||||
|
||||
# Install dependencies. The local tier uses in-process PGlite; leave DATABASE_URL unset.
|
||||
# The pnpm store defaults to $HOME/.local/share/pnpm/store. Override it without
|
||||
# editing the checkout with NPM_CONFIG_STORE_DIR=$HOME/another-store if needed.
|
||||
# Start infrastructure (Postgres, Valkey, Jaeger)
|
||||
docker compose up -d
|
||||
|
||||
# Install dependencies
|
||||
pnpm install
|
||||
|
||||
# Verify dependencies and generated state before running source-quality gates.
|
||||
# Missing dependencies exit 42; stale/foreign apps/web/.next state exits 43.
|
||||
# The web build certifies its exact standalone symlink manifest; added, removed,
|
||||
# retargeted, or manifest-only-tampered generated links also exit 43. This detects
|
||||
# accidental, independent, stale, and foreign-residue mutation—the class exposed by
|
||||
# a five-month-stale .next that produced 19 phantom TS2307 errors.
|
||||
# It does NOT defend against a same-UID actor that can rewrite both manifest and
|
||||
# marker consistently (CWE-345). RM-59 tracks the required executor/spine-side
|
||||
# trust anchor outside worktree authority.
|
||||
pnpm preflight
|
||||
# Run migrations
|
||||
pnpm --filter @mosaicstack/db run db:migrate
|
||||
|
||||
# Optional local queue service only. This does not start PostgreSQL.
|
||||
docker compose up -d valkey
|
||||
|
||||
# The current Gateway/Web local process is held; see docs/guides/dev-guide.md.
|
||||
# Do not start it until KBN-101-02 makes inherited dotenv/DSN state fail closed.
|
||||
# Start all services in dev mode
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
### Held future procedure
|
||||
### Infrastructure
|
||||
|
||||
The checked-in Compose PostgreSQL service mounts legacy initialization SQL and is **not** a
|
||||
current PostgreSQL, standalone, or federated developer route. Do not start it with Compose,
|
||||
invoke initialization SQL, or treat the planned migrator as currently executable.
|
||||
Docker Compose provides:
|
||||
|
||||
**Held future activation procedure — non-operative and no current command authority until KBN-101-00, KBN-101-03, and KBN-101-05
|
||||
land:** external bootstrap → TLS/roles → `mosaic-db-migrator --run` →
|
||||
`mosaic-db-migrator --verify` → Gateway/Compose readiness. The future deployment artifacts—not
|
||||
this README—will provide the reviewed commands and secret-consumer interface.
|
||||
|
||||
For local data-layer work, PGlite needs no PostgreSQL service. The optional Compose command above
|
||||
starts only Valkey; OTEL Collector and Jaeger may likewise be started individually if needed,
|
||||
without starting PostgreSQL. A Gateway/Web local process is not currently a safe PGlite route:
|
||||
its unguarded dotenv loader may inherit a daemon PostgreSQL DSN. Do not use root `pnpm dev` or a
|
||||
Gateway start command until KBN-101-02 makes that state fail closed.
|
||||
| Service | Port | Purpose |
|
||||
| --------------------- | --------- | ---------------------- |
|
||||
| PostgreSQL (pgvector) | 5433 | Primary database |
|
||||
| Valkey | 6380 | Task queue + caching |
|
||||
| Jaeger | 16686 | Distributed tracing UI |
|
||||
| OTEL Collector | 4317/4318 | Telemetry ingestion |
|
||||
|
||||
### Quality Gates
|
||||
|
||||
```bash
|
||||
pnpm preflight # Checkout/dependency/generated-state validation
|
||||
pnpm typecheck # TypeScript type checking (all packages)
|
||||
pnpm lint # ESLint (all packages)
|
||||
pnpm test # Vitest (all packages)
|
||||
@@ -270,7 +231,7 @@ pnpm format # Prettier auto-fix
|
||||
Woodpecker CI runs on every push:
|
||||
|
||||
- `pnpm install --frozen-lockfile`
|
||||
- **Legacy N-1 CI status only — active, uncertified, and non-authorizing as an operator route:** the checked-in job currently invokes `pnpm --filter @mosaicstack/db run db:migrate` with `DATABASE_URL` against an isolated disposable PostgreSQL CI database. It performs direct DDL in that CI database, is not approved ordinary behavior or an operator route, and remains a known exception pending KBN-101-06 removal/replacement by the certified runner-backed CI path.
|
||||
- Database migration against a fresh Postgres
|
||||
- `pnpm test` (Turbo-orchestrated across all packages)
|
||||
|
||||
npm packages are published to the Gitea package registry on main merges.
|
||||
@@ -375,15 +336,11 @@ The CLI also performs a background update check on every invocation (cached for
|
||||
bash tools/install.sh --check # Version check only
|
||||
bash tools/install.sh --framework # Framework only (skip npm CLI)
|
||||
bash tools/install.sh --cli # npm CLI only (skip framework)
|
||||
bash tools/install.sh --next # Prerelease lane: source build from next
|
||||
bash tools/install.sh --dev # Contributor lane: source build at --ref/main
|
||||
bash tools/install.sh --ref v1.0 # Install from a specific git ref (--ref wins over --next)
|
||||
bash tools/install.sh --ref v1.0 # Install from a specific git ref
|
||||
bash tools/install.sh --yes # Non-interactive, accept all defaults
|
||||
bash tools/install.sh --no-auto-launch # Skip auto-launch of wizard
|
||||
```
|
||||
|
||||
The installer rejects unrecognized flags or positional arguments before making changes and prints the supported-option usage.
|
||||
|
||||
## Contributing
|
||||
|
||||
```bash
|
||||
|
||||
@@ -31,7 +31,6 @@
|
||||
"@mariozechner/pi-ai": "^0.65.0",
|
||||
"@mariozechner/pi-coding-agent": "^0.65.0",
|
||||
"@modelcontextprotocol/sdk": "^1.27.1",
|
||||
"@mosaicstack/agent": "workspace:^",
|
||||
"@mosaicstack/auth": "workspace:^",
|
||||
"@mosaicstack/brain": "workspace:^",
|
||||
"@mosaicstack/config": "workspace:^",
|
||||
|
||||
@@ -417,7 +417,7 @@ describe('ConversationsController — search endpoint', () => {
|
||||
},
|
||||
];
|
||||
brain = createMockBrain({ searchResults });
|
||||
controller = new ConversationsController(brain as never, { runtimeMode: 'legacy' });
|
||||
controller = new ConversationsController(brain as never);
|
||||
});
|
||||
|
||||
it('returns matching messages for a valid search query', async () => {
|
||||
@@ -479,7 +479,7 @@ describe('ConversationsController — search endpoint', () => {
|
||||
describe('ConversationsController — message CRUD', () => {
|
||||
it('listMessages returns 404 when conversation is not owned by user', async () => {
|
||||
const brain = createMockBrain({ conversation: undefined });
|
||||
const controller = new ConversationsController(brain as never, { runtimeMode: 'legacy' });
|
||||
const controller = new ConversationsController(brain as never);
|
||||
|
||||
await expect(controller.listMessages(CONV_ID, { id: USER_ID })).rejects.toBeInstanceOf(
|
||||
NotFoundException,
|
||||
@@ -489,7 +489,7 @@ describe('ConversationsController — message CRUD', () => {
|
||||
it('listMessages returns the messages for an owned conversation', async () => {
|
||||
const msgs = [makeMessage('user', 'Test message'), makeMessage('assistant', 'Test reply')];
|
||||
const brain = createMockBrain({ conversation: makeConversation(), messages: msgs });
|
||||
const controller = new ConversationsController(brain as never, { runtimeMode: 'legacy' });
|
||||
const controller = new ConversationsController(brain as never);
|
||||
|
||||
const result = await controller.listMessages(CONV_ID, { id: USER_ID });
|
||||
|
||||
@@ -500,7 +500,7 @@ describe('ConversationsController — message CRUD', () => {
|
||||
|
||||
it('addMessage returns the persisted message', async () => {
|
||||
const brain = createMockBrain({ conversation: makeConversation() });
|
||||
const controller = new ConversationsController(brain as never, { runtimeMode: 'legacy' });
|
||||
const controller = new ConversationsController(brain as never);
|
||||
|
||||
const result = await controller.addMessage(
|
||||
CONV_ID,
|
||||
|
||||
@@ -1,519 +0,0 @@
|
||||
/**
|
||||
* Federation M3 single-gateway integration tests (FED-M3-10).
|
||||
*
|
||||
* Covers MILESTONES.md M3 acceptance:
|
||||
* - #6: malformed certificate OIDs fail with 401; valid cert + revoked grant fails with 403.
|
||||
* - #7: max_rows_per_query caps list results.
|
||||
*
|
||||
* Strategy:
|
||||
* - Real PostgreSQL via @mosaicstack/db.
|
||||
* - Mocked TLS context/Fastify request shim for FederationAuthGuard.
|
||||
* - Direct controller calls using the real POST /api/federation/v1/list/:resource contract.
|
||||
*
|
||||
* Run:
|
||||
* FEDERATED_INTEGRATION=1 pnpm --filter @mosaicstack/gateway test -- \
|
||||
* src/__tests__/integration/federation-m3-list.integration.test.ts
|
||||
*/
|
||||
|
||||
import 'reflect-metadata';
|
||||
import * as crypto from 'node:crypto';
|
||||
import type { ExecutionContext } from '@nestjs/common';
|
||||
import { Test, type TestingModule } from '@nestjs/testing';
|
||||
import type { FastifyReply, FastifyRequest } from 'fastify';
|
||||
import {
|
||||
and,
|
||||
createDb,
|
||||
eq,
|
||||
federationGrants,
|
||||
federationPeers,
|
||||
inArray,
|
||||
missionTasks,
|
||||
missions,
|
||||
projects,
|
||||
tasks,
|
||||
teamMembers,
|
||||
teams,
|
||||
type Db,
|
||||
type DbHandle,
|
||||
users,
|
||||
} from '@mosaicstack/db';
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { DB } from '../../database/database.module.js';
|
||||
import { GrantsService } from '../../federation/grants.service.js';
|
||||
import { FederationAuthGuard } from '../../federation/server/federation-auth.guard.js';
|
||||
import { FederationScopeService } from '../../federation/server/scope.service.js';
|
||||
import { FederationListQueryService } from '../../federation/server/verbs/list-query.service.js';
|
||||
import { ListController } from '../../federation/server/verbs/list.controller.js';
|
||||
import {
|
||||
makeMosaicIssuedCert,
|
||||
makeSelfSignedCert,
|
||||
} from '../../federation/__tests__/helpers/test-cert.js';
|
||||
|
||||
const run = process.env['FEDERATED_INTEGRATION'] === '1';
|
||||
const PG_URL = process.env['DATABASE_URL'] ?? 'postgresql://mosaic:mosaic@localhost:5433/mosaic';
|
||||
const RUN_ID = `fed-m3-10-${crypto.randomUUID()}`;
|
||||
const CERT_SERIAL_HEX = crypto.randomUUID().replace(/-/g, '').toUpperCase();
|
||||
|
||||
interface TestIds {
|
||||
readonly subjectUserId: string;
|
||||
readonly otherUserId: string;
|
||||
readonly peerId: string;
|
||||
readonly revokedPeerId: string;
|
||||
readonly activeGrantId: string;
|
||||
readonly revokedGrantId: string;
|
||||
readonly subjectProjectId: string;
|
||||
readonly subjectMissionId: string;
|
||||
readonly otherProjectId: string;
|
||||
readonly teamId: string;
|
||||
readonly unauthorizedTeamId: string;
|
||||
readonly teamProjectId: string;
|
||||
readonly taskIds: readonly string[];
|
||||
readonly excludedTaskIds: readonly string[];
|
||||
readonly subjectNoteId: string;
|
||||
readonly otherUserNoteId: string;
|
||||
}
|
||||
|
||||
function pemToDer(pem: string): Buffer {
|
||||
return Buffer.from(
|
||||
pem
|
||||
.replace(/-----BEGIN CERTIFICATE-----/, '')
|
||||
.replace(/-----END CERTIFICATE-----/, '')
|
||||
.replace(/\s+/g, ''),
|
||||
'base64',
|
||||
);
|
||||
}
|
||||
|
||||
function makeFederationRequest(certPem: string): FastifyRequest {
|
||||
return {
|
||||
raw: {
|
||||
socket: {
|
||||
getPeerCertificate: () => ({
|
||||
raw: pemToDer(certPem),
|
||||
serialNumber: CERT_SERIAL_HEX,
|
||||
}),
|
||||
},
|
||||
},
|
||||
} as unknown as FastifyRequest;
|
||||
}
|
||||
|
||||
function makeGuardContext(request: FastifyRequest): {
|
||||
readonly context: ExecutionContext;
|
||||
readonly sent: { statusCode?: number; payload?: unknown };
|
||||
} {
|
||||
const sent: { statusCode?: number; payload?: unknown } = {};
|
||||
const reply = {
|
||||
status: (statusCode: number) => {
|
||||
sent.statusCode = statusCode;
|
||||
return {
|
||||
header: () => ({
|
||||
send: (payload: unknown) => {
|
||||
sent.payload = payload;
|
||||
},
|
||||
}),
|
||||
};
|
||||
},
|
||||
} as unknown as FastifyReply;
|
||||
|
||||
const context = {
|
||||
switchToHttp: () => ({
|
||||
getRequest: () => request,
|
||||
getResponse: () => reply,
|
||||
}),
|
||||
} as unknown as ExecutionContext;
|
||||
|
||||
return { context, sent };
|
||||
}
|
||||
|
||||
async function insertUser(db: Db, id: string, label: string): Promise<void> {
|
||||
await db.insert(users).values({
|
||||
id,
|
||||
name: `${RUN_ID}-${label}`,
|
||||
email: `${RUN_ID}-${label}@federation-test.invalid`,
|
||||
emailVerified: false,
|
||||
});
|
||||
}
|
||||
|
||||
async function seedFixtures(db: Db): Promise<TestIds> {
|
||||
const subjectUserId = `${RUN_ID}-subject`;
|
||||
const otherUserId = `${RUN_ID}-other`;
|
||||
const peerId = crypto.randomUUID();
|
||||
const revokedPeerId = crypto.randomUUID();
|
||||
const activeGrantId = crypto.randomUUID();
|
||||
const revokedGrantId = crypto.randomUUID();
|
||||
const subjectProjectId = crypto.randomUUID();
|
||||
const subjectMissionId = crypto.randomUUID();
|
||||
const otherProjectId = crypto.randomUUID();
|
||||
const teamId = crypto.randomUUID();
|
||||
const unauthorizedTeamId = crypto.randomUUID();
|
||||
const teamProjectId = crypto.randomUUID();
|
||||
const taskIds = [crypto.randomUUID(), crypto.randomUUID(), crypto.randomUUID()] as const;
|
||||
const excludedTaskIds = [crypto.randomUUID(), crypto.randomUUID()] as const;
|
||||
const subjectNoteId = crypto.randomUUID();
|
||||
const otherUserNoteId = crypto.randomUUID();
|
||||
|
||||
await insertUser(db, subjectUserId, 'subject');
|
||||
await insertUser(db, otherUserId, 'other');
|
||||
|
||||
await db.insert(teams).values([
|
||||
{
|
||||
id: teamId,
|
||||
name: `${RUN_ID} allowed team`,
|
||||
slug: `${RUN_ID}-allowed-team`,
|
||||
ownerId: subjectUserId,
|
||||
managerId: subjectUserId,
|
||||
},
|
||||
{
|
||||
id: unauthorizedTeamId,
|
||||
name: `${RUN_ID} unauthorized team`,
|
||||
slug: `${RUN_ID}-unauthorized-team`,
|
||||
ownerId: otherUserId,
|
||||
managerId: otherUserId,
|
||||
},
|
||||
]);
|
||||
|
||||
await db.insert(teamMembers).values([
|
||||
{ teamId, userId: subjectUserId, role: 'member' },
|
||||
{ teamId: unauthorizedTeamId, userId: subjectUserId, role: 'member' },
|
||||
]);
|
||||
|
||||
await db.insert(projects).values([
|
||||
{
|
||||
id: subjectProjectId,
|
||||
name: `${RUN_ID} subject personal project`,
|
||||
ownerType: 'user',
|
||||
ownerId: subjectUserId,
|
||||
},
|
||||
{
|
||||
id: otherProjectId,
|
||||
name: `${RUN_ID} other personal project`,
|
||||
ownerType: 'user',
|
||||
ownerId: otherUserId,
|
||||
},
|
||||
{
|
||||
id: teamProjectId,
|
||||
name: `${RUN_ID} unauthorized team project`,
|
||||
ownerType: 'team',
|
||||
teamId: unauthorizedTeamId,
|
||||
},
|
||||
]);
|
||||
|
||||
await db.insert(missions).values({
|
||||
id: subjectMissionId,
|
||||
name: `${RUN_ID} subject mission`,
|
||||
projectId: subjectProjectId,
|
||||
userId: subjectUserId,
|
||||
});
|
||||
|
||||
await db.insert(tasks).values([
|
||||
{
|
||||
id: taskIds[0],
|
||||
title: `${RUN_ID} visible task 1`,
|
||||
missionId: subjectMissionId,
|
||||
createdAt: new Date('2026-06-25T03:00:00.000Z'),
|
||||
updatedAt: new Date('2026-06-25T03:00:00.000Z'),
|
||||
},
|
||||
{
|
||||
id: taskIds[1],
|
||||
title: `${RUN_ID} visible task 2`,
|
||||
projectId: subjectProjectId,
|
||||
createdAt: new Date('2026-06-25T02:00:00.000Z'),
|
||||
updatedAt: new Date('2026-06-25T02:00:00.000Z'),
|
||||
},
|
||||
{
|
||||
id: taskIds[2],
|
||||
title: `${RUN_ID} visible task 3`,
|
||||
projectId: subjectProjectId,
|
||||
createdAt: new Date('2026-06-25T01:00:00.000Z'),
|
||||
updatedAt: new Date('2026-06-25T01:00:00.000Z'),
|
||||
},
|
||||
{
|
||||
id: excludedTaskIds[0],
|
||||
title: `${RUN_ID} other user task`,
|
||||
projectId: otherProjectId,
|
||||
createdAt: new Date('2026-06-25T04:00:00.000Z'),
|
||||
updatedAt: new Date('2026-06-25T04:00:00.000Z'),
|
||||
},
|
||||
{
|
||||
id: excludedTaskIds[1],
|
||||
title: `${RUN_ID} unauthorized team task`,
|
||||
projectId: teamProjectId,
|
||||
createdAt: new Date('2026-06-25T05:00:00.000Z'),
|
||||
updatedAt: new Date('2026-06-25T05:00:00.000Z'),
|
||||
},
|
||||
]);
|
||||
|
||||
await db.insert(missionTasks).values([
|
||||
{
|
||||
id: subjectNoteId,
|
||||
missionId: subjectMissionId,
|
||||
userId: subjectUserId,
|
||||
notes: `${RUN_ID} subject visible note`,
|
||||
createdAt: new Date('2026-06-25T03:30:00.000Z'),
|
||||
updatedAt: new Date('2026-06-25T03:30:00.000Z'),
|
||||
},
|
||||
{
|
||||
id: otherUserNoteId,
|
||||
missionId: subjectMissionId,
|
||||
userId: otherUserId,
|
||||
notes: `${RUN_ID} other user note on subject mission`,
|
||||
createdAt: new Date('2026-06-25T04:30:00.000Z'),
|
||||
updatedAt: new Date('2026-06-25T04:30:00.000Z'),
|
||||
},
|
||||
]);
|
||||
|
||||
await db.insert(federationPeers).values([
|
||||
{
|
||||
id: peerId,
|
||||
commonName: `${RUN_ID}-active-peer`,
|
||||
displayName: `${RUN_ID} Active Peer`,
|
||||
certPem: '-----BEGIN CERTIFICATE-----\nMOCK\n-----END CERTIFICATE-----\n',
|
||||
certSerial: CERT_SERIAL_HEX,
|
||||
certNotAfter: new Date(Date.now() + 86_400_000),
|
||||
state: 'active',
|
||||
},
|
||||
{
|
||||
id: revokedPeerId,
|
||||
commonName: `${RUN_ID}-revoked-peer`,
|
||||
displayName: `${RUN_ID} Revoked Peer`,
|
||||
certPem: '-----BEGIN CERTIFICATE-----\nMOCK\n-----END CERTIFICATE-----\n',
|
||||
certSerial: `${CERT_SERIAL_HEX}${RUN_ID.replace(/-/g, '').slice(0, 8).toUpperCase()}`,
|
||||
certNotAfter: new Date(Date.now() + 86_400_000),
|
||||
state: 'active',
|
||||
},
|
||||
]);
|
||||
|
||||
await db.insert(federationGrants).values([
|
||||
{
|
||||
id: activeGrantId,
|
||||
peerId,
|
||||
subjectUserId,
|
||||
status: 'active',
|
||||
scope: {
|
||||
resources: ['tasks', 'notes'],
|
||||
excluded_resources: [],
|
||||
filters: {
|
||||
tasks: { include_personal: true, include_teams: [] },
|
||||
notes: { include_personal: true, include_teams: [] },
|
||||
},
|
||||
max_rows_per_query: 2,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: revokedGrantId,
|
||||
peerId,
|
||||
subjectUserId,
|
||||
status: 'revoked',
|
||||
revokedAt: new Date(),
|
||||
revokedReason: `${RUN_ID} revoked grant fixture`,
|
||||
scope: {
|
||||
resources: ['tasks'],
|
||||
excluded_resources: [],
|
||||
max_rows_per_query: 2,
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
return {
|
||||
subjectUserId,
|
||||
otherUserId,
|
||||
peerId,
|
||||
revokedPeerId,
|
||||
activeGrantId,
|
||||
revokedGrantId,
|
||||
subjectProjectId,
|
||||
subjectMissionId,
|
||||
otherProjectId,
|
||||
teamId,
|
||||
unauthorizedTeamId,
|
||||
teamProjectId,
|
||||
taskIds,
|
||||
excludedTaskIds,
|
||||
subjectNoteId,
|
||||
otherUserNoteId,
|
||||
};
|
||||
}
|
||||
|
||||
async function cleanupFixtures(db: Db, ids: TestIds | undefined): Promise<void> {
|
||||
if (!ids) {
|
||||
return;
|
||||
}
|
||||
|
||||
await db
|
||||
.delete(missionTasks)
|
||||
.where(inArray(missionTasks.id, [ids.subjectNoteId, ids.otherUserNoteId]))
|
||||
.catch(() => {});
|
||||
await db
|
||||
.delete(tasks)
|
||||
.where(inArray(tasks.id, [...ids.taskIds, ...ids.excludedTaskIds]))
|
||||
.catch(() => {});
|
||||
await db
|
||||
.delete(missions)
|
||||
.where(eq(missions.id, ids.subjectMissionId))
|
||||
.catch(() => {});
|
||||
await db
|
||||
.delete(projects)
|
||||
.where(inArray(projects.id, [ids.subjectProjectId, ids.otherProjectId, ids.teamProjectId]))
|
||||
.catch(() => {});
|
||||
await db
|
||||
.delete(teamMembers)
|
||||
.where(
|
||||
and(
|
||||
eq(teamMembers.userId, ids.subjectUserId),
|
||||
inArray(teamMembers.teamId, [ids.teamId, ids.unauthorizedTeamId]),
|
||||
),
|
||||
)
|
||||
.catch(() => {});
|
||||
await db
|
||||
.delete(teams)
|
||||
.where(inArray(teams.id, [ids.teamId, ids.unauthorizedTeamId]))
|
||||
.catch(() => {});
|
||||
await db
|
||||
.delete(federationGrants)
|
||||
.where(inArray(federationGrants.id, [ids.activeGrantId, ids.revokedGrantId]))
|
||||
.catch(() => {});
|
||||
await db
|
||||
.delete(federationPeers)
|
||||
.where(inArray(federationPeers.id, [ids.peerId, ids.revokedPeerId]))
|
||||
.catch(() => {});
|
||||
await db
|
||||
.delete(users)
|
||||
.where(inArray(users.id, [ids.subjectUserId, ids.otherUserId]))
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
describe.skipIf(!run)('federation M3 list verb — single-gateway integration', () => {
|
||||
let handle: DbHandle;
|
||||
let db: Db;
|
||||
let moduleRef: TestingModule;
|
||||
let guard: FederationAuthGuard;
|
||||
let listController: ListController;
|
||||
let ids: TestIds | undefined;
|
||||
|
||||
beforeAll(async () => {
|
||||
handle = createDb(PG_URL);
|
||||
db = handle.db;
|
||||
ids = await seedFixtures(db);
|
||||
|
||||
moduleRef = await Test.createTestingModule({
|
||||
controllers: [ListController],
|
||||
providers: [
|
||||
{ provide: DB, useValue: db },
|
||||
GrantsService,
|
||||
FederationAuthGuard,
|
||||
FederationScopeService,
|
||||
FederationListQueryService,
|
||||
],
|
||||
}).compile();
|
||||
|
||||
guard = moduleRef.get(FederationAuthGuard);
|
||||
listController = moduleRef.get(ListController);
|
||||
}, 30_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await moduleRef?.close().catch((e: unknown) => console.error('[fed-m3-10 cleanup]', e));
|
||||
await cleanupFixtures(db, ids).catch((e: unknown) => console.error('[fed-m3-10 cleanup]', e));
|
||||
await handle?.close().catch((e: unknown) => console.error('[fed-m3-10 cleanup]', e));
|
||||
});
|
||||
|
||||
it('#6 — rejects a client cert with malformed/missing Mosaic OIDs with 401', async () => {
|
||||
const malformedOidCert = await makeSelfSignedCert();
|
||||
const request = makeFederationRequest(malformedOidCert);
|
||||
const { context, sent } = makeGuardContext(request);
|
||||
|
||||
await expect(guard.canActivate(context)).resolves.toBe(false);
|
||||
expect(sent.statusCode).toBe(401);
|
||||
expect(sent.payload).toMatchObject({
|
||||
error: {
|
||||
code: 'unauthorized',
|
||||
message: expect.stringContaining('missing required OID'),
|
||||
},
|
||||
});
|
||||
expect(request.federationContext).toBeUndefined();
|
||||
});
|
||||
|
||||
it('#6 — rejects a valid client cert when its grant is revoked with 403', async () => {
|
||||
expect(ids).toBeDefined();
|
||||
const revokedCert = await makeMosaicIssuedCert({
|
||||
grantId: ids!.revokedGrantId,
|
||||
subjectUserId: ids!.subjectUserId,
|
||||
});
|
||||
const request = makeFederationRequest(revokedCert);
|
||||
const { context, sent } = makeGuardContext(request);
|
||||
|
||||
await expect(guard.canActivate(context)).resolves.toBe(false);
|
||||
expect(sent.statusCode).toBe(403);
|
||||
expect(sent.payload).toMatchObject({
|
||||
error: {
|
||||
code: 'forbidden',
|
||||
message: 'Federation access denied',
|
||||
},
|
||||
});
|
||||
expect(request.federationContext).toBeUndefined();
|
||||
});
|
||||
|
||||
it('#7 — enforces max_rows_per_query on POST /api/federation/v1/list/:resource', async () => {
|
||||
expect(ids).toBeDefined();
|
||||
const activeCert = await makeMosaicIssuedCert({
|
||||
grantId: ids!.activeGrantId,
|
||||
subjectUserId: ids!.subjectUserId,
|
||||
});
|
||||
const request = makeFederationRequest(activeCert);
|
||||
const { context } = makeGuardContext(request);
|
||||
|
||||
await expect(guard.canActivate(context)).resolves.toBe(true);
|
||||
|
||||
const response = await listController.list('tasks', request, { limit: 100 });
|
||||
const returnedIds = response.items.map((item) => item['id']);
|
||||
|
||||
expect(response.items).toHaveLength(2);
|
||||
expect(response._truncated).toBe(true);
|
||||
expect(response.nextCursor).toEqual(expect.any(String));
|
||||
expect(returnedIds).toEqual([ids!.taskIds[0], ids!.taskIds[1]]);
|
||||
expect(returnedIds).not.toContain(ids!.taskIds[2]);
|
||||
for (const excludedId of ids!.excludedTaskIds) {
|
||||
expect(returnedIds).not.toContain(excludedId);
|
||||
}
|
||||
expect(response.items.every((item) => item._source === 'local')).toBe(true);
|
||||
});
|
||||
|
||||
it('excludes another user mission task notes on the same authorized mission', async () => {
|
||||
expect(ids).toBeDefined();
|
||||
const activeCert = await makeMosaicIssuedCert({
|
||||
grantId: ids!.activeGrantId,
|
||||
subjectUserId: ids!.subjectUserId,
|
||||
});
|
||||
const request = makeFederationRequest(activeCert);
|
||||
const { context } = makeGuardContext(request);
|
||||
|
||||
await expect(guard.canActivate(context)).resolves.toBe(true);
|
||||
|
||||
const response = await listController.list('notes', request, { limit: 10 });
|
||||
const returnedIds = response.items.map((item) => item['id']);
|
||||
|
||||
expect(returnedIds).toEqual([ids!.subjectNoteId]);
|
||||
expect(returnedIds).not.toContain(ids!.otherUserNoteId);
|
||||
expect(response.items.every((item) => item._source === 'local')).toBe(true);
|
||||
});
|
||||
|
||||
it('fails closed for unsupported list resources', async () => {
|
||||
expect(ids).toBeDefined();
|
||||
const activeCert = await makeMosaicIssuedCert({
|
||||
grantId: ids!.activeGrantId,
|
||||
subjectUserId: ids!.subjectUserId,
|
||||
});
|
||||
const request = makeFederationRequest(activeCert);
|
||||
const { context } = makeGuardContext(request);
|
||||
|
||||
await expect(guard.canActivate(context)).resolves.toBe(true);
|
||||
|
||||
await expect(listController.list('widgets', request, {})).rejects.toMatchObject({
|
||||
response: {
|
||||
error: {
|
||||
code: 'scope_violation',
|
||||
message: 'Requested federation resource is not supported',
|
||||
},
|
||||
},
|
||||
status: 403,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,213 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { InMemoryDurableSessionStore } from '@mosaicstack/agent';
|
||||
import {
|
||||
createDiscordIngressEnvelope,
|
||||
DiscordPlugin,
|
||||
type DiscordIngressPayload,
|
||||
} from '@mosaicstack/discord-plugin';
|
||||
import { InteractionController } from '../../agent/interaction.controller.js';
|
||||
import { RuntimeProviderService } from '../../agent/runtime-provider-registry.service.js';
|
||||
import { DurableSessionService } from '../../agent/durable-session.service.js';
|
||||
import { ChatGateway } from '../../chat/chat.gateway.js';
|
||||
import { CommandAuthorizationService } from '../../commands/command-authorization.service.js';
|
||||
|
||||
const SERVICE_TOKEN = 'test-discord-service-token';
|
||||
const envKeys = [
|
||||
'DISCORD_SERVICE_TOKEN',
|
||||
'DISCORD_SERVICE_TENANT_ID',
|
||||
'DISCORD_INTERACTION_BINDINGS',
|
||||
'DISCORD_ALLOWED_GUILD_IDS',
|
||||
'DISCORD_ALLOWED_CHANNEL_IDS',
|
||||
'DISCORD_ALLOWED_USER_IDS',
|
||||
'MOSAIC_AGENT_NAME',
|
||||
] as const;
|
||||
const priorEnv = new Map<string, string | undefined>();
|
||||
|
||||
function payload(content: string, messageId: string, correlationId: string): DiscordIngressPayload {
|
||||
return {
|
||||
content,
|
||||
messageId,
|
||||
correlationId,
|
||||
guildId: 'guild-1',
|
||||
channelId: 'channel-1',
|
||||
userId: 'discord-admin-1',
|
||||
conversationId: 'Nova:discord:channel-1',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The chat runtime router must never be exercised on the Discord approval/stop control paths —
|
||||
* those paths run entirely through the command-authorization, runtime-provider and durable-session
|
||||
* dependencies. Placed in the gateway's chat-runtime-router slot (the former direct `AgentService`
|
||||
* slot) so any accidental chat-runtime dispatch throws loudly instead of silently passing. Because
|
||||
* approval/stop never resolve a chat runtime, this fixture is never triggered and the integration
|
||||
* stays a GREEN cross-surface control.
|
||||
*/
|
||||
function failIfUsedChatRuntimeRouter() {
|
||||
return {
|
||||
onModuleInit: () => {
|
||||
throw new Error('chat runtime router must not initialise on the Discord control path');
|
||||
},
|
||||
get active(): never {
|
||||
throw new Error('chat runtime must not be resolved on the Discord approval/stop path');
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function authorization(): CommandAuthorizationService {
|
||||
const entries = new Map<string, string>();
|
||||
return new CommandAuthorizationService(
|
||||
{
|
||||
select: () => ({
|
||||
from: () => ({ where: () => ({ limit: async () => [{ role: 'admin' }] }) }),
|
||||
}),
|
||||
} as never,
|
||||
{
|
||||
get: async (key: string) => entries.get(key) ?? null,
|
||||
set: async (key: string, value: string) => entries.set(key, value),
|
||||
del: async (key: string) => Number(entries.delete(key)),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
describe('interaction Discord/CLI durable-session integration', () => {
|
||||
afterEach(() => {
|
||||
for (const key of envKeys) {
|
||||
const value = priorEnv.get(key);
|
||||
if (value === undefined) delete process.env[key];
|
||||
else process.env[key] = value;
|
||||
}
|
||||
priorEnv.clear();
|
||||
});
|
||||
|
||||
it('enrolls through the CLI surface then resolves the same durable session from Discord', async () => {
|
||||
for (const key of envKeys) priorEnv.set(key, process.env[key]);
|
||||
process.env['MOSAIC_AGENT_NAME'] = 'Nova';
|
||||
process.env['DISCORD_SERVICE_TOKEN'] = SERVICE_TOKEN;
|
||||
process.env['DISCORD_SERVICE_TENANT_ID'] = 'tenant-1';
|
||||
process.env['DISCORD_ALLOWED_GUILD_IDS'] = 'guild-1';
|
||||
process.env['DISCORD_ALLOWED_CHANNEL_IDS'] = 'channel-1';
|
||||
process.env['DISCORD_ALLOWED_USER_IDS'] = 'discord-admin-1';
|
||||
process.env['DISCORD_INTERACTION_BINDINGS'] = JSON.stringify([
|
||||
{
|
||||
instanceId: 'Nova',
|
||||
agentConfigId: 'agent-config-nova',
|
||||
guildId: 'guild-1',
|
||||
channelId: 'channel-1',
|
||||
pairedUsers: {
|
||||
'discord-admin-1': { role: 'admin', mosaicUserId: 'mosaic-admin-1' },
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
const durable = new DurableSessionService(
|
||||
new InMemoryDurableSessionStore() as never,
|
||||
{} as never,
|
||||
);
|
||||
const enrollmentRuntime = {
|
||||
listSessions: vi.fn().mockResolvedValue([{ id: 'runtime-1' }]),
|
||||
};
|
||||
const controller = new InteractionController(enrollmentRuntime as never, durable);
|
||||
await controller.enroll(
|
||||
'Nova',
|
||||
'Nova:discord:channel-1',
|
||||
{ providerId: 'fleet', runtimeSessionId: 'runtime-1' },
|
||||
{ id: 'mosaic-admin-1', tenantId: 'tenant-1' },
|
||||
'cli-enrollment-correlation',
|
||||
);
|
||||
|
||||
const authz = authorization();
|
||||
const terminated = vi.fn().mockResolvedValue(undefined);
|
||||
const runtime = new RuntimeProviderService(
|
||||
{
|
||||
require: () => ({
|
||||
capabilities: async () => ({ supported: ['session.terminate'] }),
|
||||
terminate: terminated,
|
||||
}),
|
||||
} as never,
|
||||
{ record: async () => undefined } as never,
|
||||
{
|
||||
consume: (approvalId, action) =>
|
||||
authz.consumeRuntimeTerminationApproval(approvalId, action),
|
||||
},
|
||||
);
|
||||
const gateway = new ChatGateway(
|
||||
failIfUsedChatRuntimeRouter() as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
authz,
|
||||
runtime,
|
||||
durable,
|
||||
);
|
||||
const client = { data: { discordService: true }, emit: vi.fn() };
|
||||
const plugin = new DiscordPlugin({
|
||||
token: 'unused',
|
||||
gatewayUrl: 'http://unused',
|
||||
serviceToken: SERVICE_TOKEN,
|
||||
allowedGuildIds: ['guild-1'],
|
||||
allowedChannelIds: ['channel-1'],
|
||||
allowedUserIds: ['discord-admin-1'],
|
||||
interactionBindings: [
|
||||
{
|
||||
instanceId: 'Nova',
|
||||
agentConfigId: 'agent-config-nova',
|
||||
guildId: 'guild-1',
|
||||
channelId: 'channel-1',
|
||||
pairedUsers: {
|
||||
'discord-admin-1': { role: 'admin', mosaicUserId: 'mosaic-admin-1' },
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
const pluginInternals = plugin as unknown as {
|
||||
client: { user: { id: string } };
|
||||
socket: { connected: boolean; emit: ReturnType<typeof vi.fn> };
|
||||
handleDiscordMessage(message: unknown): void;
|
||||
};
|
||||
const pluginSocket = { connected: true, emit: vi.fn() };
|
||||
pluginInternals.client = { user: { id: 'bot-1' } };
|
||||
pluginInternals.socket = pluginSocket;
|
||||
pluginInternals.handleDiscordMessage({
|
||||
id: 'approve-1',
|
||||
guildId: 'guild-1',
|
||||
channelId: 'channel-1',
|
||||
author: { id: 'discord-admin-1', bot: false },
|
||||
mentions: { has: () => true },
|
||||
content: '<@bot-1> /approve',
|
||||
channel: { parentId: null },
|
||||
attachments: new Map(),
|
||||
});
|
||||
|
||||
expect(pluginSocket.emit).toHaveBeenCalledWith('discord:approve', expect.any(Object));
|
||||
const approvalEnvelope = pluginSocket.emit.mock.calls[0]?.[1];
|
||||
await gateway.handleDiscordApproval(client as never, approvalEnvelope);
|
||||
const approval = client.emit.mock.calls.find(
|
||||
([event]) => event === 'discord:approval',
|
||||
)?.[1] as {
|
||||
approvalId: string;
|
||||
success: boolean;
|
||||
};
|
||||
expect(approval.success).toBe(true);
|
||||
|
||||
await gateway.handleDiscordStop(
|
||||
client as never,
|
||||
createDiscordIngressEnvelope(
|
||||
payload(`/stop ${approval.approvalId}`, 'stop-1', 'discord-stop-correlation'),
|
||||
SERVICE_TOKEN,
|
||||
),
|
||||
);
|
||||
|
||||
expect(terminated).toHaveBeenCalledWith(
|
||||
'runtime-1',
|
||||
approval.approvalId,
|
||||
expect.objectContaining({ actorId: 'mosaic-admin-1' }),
|
||||
);
|
||||
expect(client.emit).toHaveBeenCalledWith('discord:stop', {
|
||||
correlationId: 'discord-stop-correlation',
|
||||
success: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -60,7 +60,7 @@ describe('Resource ownership checks', () => {
|
||||
// The repo enforces ownership via the WHERE clause; it returns undefined when the
|
||||
// conversation does not belong to the requesting user.
|
||||
brain.conversations.findById.mockResolvedValue(undefined);
|
||||
const controller = new ConversationsController(brain as never, { runtimeMode: 'legacy' });
|
||||
const controller = new ConversationsController(brain as never);
|
||||
|
||||
await expect(controller.findOne('conv-1', { id: 'user-1' })).rejects.toBeInstanceOf(
|
||||
NotFoundException,
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import { Controller, Get, Inject, Optional, UseGuards } from '@nestjs/common';
|
||||
import { Controller, Get, Inject, UseGuards } from '@nestjs/common';
|
||||
import { sql, type Db } from '@mosaicstack/db';
|
||||
import { createQueue } from '@mosaicstack/queue';
|
||||
import type { MosaicConfig } from '@mosaicstack/config';
|
||||
import { DB } from '../database/database.module.js';
|
||||
import { AgentService } from '../agent/agent.service.js';
|
||||
import { ProviderService } from '../agent/provider.service.js';
|
||||
import { MOSAIC_CONFIG } from '../config/config.module.js';
|
||||
import { AdminGuard } from './admin.guard.js';
|
||||
import type { HealthStatusDto, ServiceStatusDto } from './admin.dto.js';
|
||||
|
||||
@@ -16,16 +14,13 @@ export class AdminHealthController {
|
||||
@Inject(DB) private readonly db: Db,
|
||||
@Inject(AgentService) private readonly agentService: AgentService,
|
||||
@Inject(ProviderService) private readonly providerService: ProviderService,
|
||||
@Optional()
|
||||
@Inject(MOSAIC_CONFIG)
|
||||
private readonly mosaicConfig: MosaicConfig | null,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
async check(): Promise<HealthStatusDto> {
|
||||
const [database, cache] = await Promise.all([this.checkDatabase(), this.checkCache()]);
|
||||
|
||||
const sessions = this.agentService.listAllSessionsForSystem();
|
||||
const sessions = this.agentService.listSessions();
|
||||
const providers = this.providerService.listProviders();
|
||||
|
||||
const allOk = database.status === 'ok' && cache.status === 'ok';
|
||||
@@ -60,14 +55,6 @@ export class AdminHealthController {
|
||||
}
|
||||
|
||||
private async checkCache(): Promise<ServiceStatusDto> {
|
||||
// On Local tier there is no Redis. The cache is intentionally absent, which
|
||||
// is a healthy state for this tier — report 'ok' rather than opening a new
|
||||
// ioredis connection on every admin health check (which would spam
|
||||
// ECONNREFUSED and create/destroy a connection per request). latencyMs 0
|
||||
// signals "no cache backend to measure" for this tier.
|
||||
if (this.mosaicConfig?.queue?.type === 'local') {
|
||||
return { status: 'ok', latencyMs: 0 };
|
||||
}
|
||||
const start = Date.now();
|
||||
const handle = createQueue();
|
||||
try {
|
||||
|
||||
@@ -1,191 +0,0 @@
|
||||
import { ForbiddenException } from '@nestjs/common';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { AgentService, type AgentSession } from '../agent.service.js';
|
||||
import type { ActorTenantScope } from '../../auth/session-scope.js';
|
||||
|
||||
const CONVERSATION_ID = '22222222-2222-4222-8222-222222222222';
|
||||
const OWNER_SCOPE: ActorTenantScope = { userId: 'owner-user', tenantId: 'owner-tenant' };
|
||||
const FOREIGN_SCOPE: ActorTenantScope = { userId: 'foreign-user', tenantId: 'foreign-tenant' };
|
||||
|
||||
type AgentServiceInternals = {
|
||||
sessions: Map<string, AgentSession>;
|
||||
creating: Map<string, Promise<AgentSession>>;
|
||||
};
|
||||
|
||||
function makeService(operatorMemory: unknown = null): AgentService {
|
||||
return new AgentService(
|
||||
{
|
||||
getDefaultModel: vi.fn(() => null),
|
||||
getRegistry: vi.fn(() => ({})),
|
||||
findModel: vi.fn(),
|
||||
listAvailableModels: vi.fn(() => []),
|
||||
} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{ available: false } as never,
|
||||
{} as never,
|
||||
{ getToolDefinitions: vi.fn(() => []) } as never,
|
||||
{ loadForSession: vi.fn(async () => ({ metaTools: [], promptAdditions: [] })) } as never,
|
||||
null,
|
||||
null,
|
||||
{ collect: vi.fn().mockResolvedValue(undefined) } as never,
|
||||
operatorMemory as never,
|
||||
);
|
||||
}
|
||||
|
||||
function internals(service: AgentService): AgentServiceInternals {
|
||||
return service as unknown as AgentServiceInternals;
|
||||
}
|
||||
|
||||
function makeSession(scope: ActorTenantScope = OWNER_SCOPE): AgentSession {
|
||||
return {
|
||||
id: CONVERSATION_ID,
|
||||
provider: 'test-provider',
|
||||
modelId: 'test-model',
|
||||
piSession: {
|
||||
thinkingLevel: 'off',
|
||||
getAvailableThinkingLevels: vi.fn().mockReturnValue(['off', 'low', 'high']),
|
||||
setThinkingLevel: vi.fn(),
|
||||
abort: vi.fn().mockResolvedValue(undefined),
|
||||
prompt: vi.fn().mockResolvedValue(undefined),
|
||||
dispose: vi.fn(),
|
||||
getSessionStats: vi.fn(),
|
||||
getContextUsage: vi.fn(),
|
||||
} as unknown as AgentSession['piSession'],
|
||||
listeners: new Set(),
|
||||
unsubscribe: vi.fn(),
|
||||
createdAt: Date.now(),
|
||||
promptCount: 0,
|
||||
channels: new Set(),
|
||||
skillPromptAdditions: [],
|
||||
sandboxDir: '/tmp/tess-session-ownership-test',
|
||||
allowedTools: null,
|
||||
userId: scope.userId,
|
||||
tenantId: scope.tenantId,
|
||||
metrics: {
|
||||
tokens: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
||||
modelSwitches: 0,
|
||||
messageCount: 0,
|
||||
lastActivityAt: new Date('2026-07-12T00:00:00Z').toISOString(),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('AgentService owner/tenant scope enforcement', () => {
|
||||
it('allows owner-scoped operations and rejects foreign scopes for seeded sessions', async () => {
|
||||
const service = makeService();
|
||||
const session = makeSession();
|
||||
internals(service).sessions.set(CONVERSATION_ID, session);
|
||||
|
||||
expect(service.getSession(CONVERSATION_ID, OWNER_SCOPE)).toBe(session);
|
||||
expect(service.getSession(CONVERSATION_ID, FOREIGN_SCOPE)).toBeUndefined();
|
||||
expect(service.getSessionInfo(CONVERSATION_ID, FOREIGN_SCOPE)).toBeUndefined();
|
||||
expect(service.listSessions(OWNER_SCOPE)).toHaveLength(1);
|
||||
expect(service.listSessions(FOREIGN_SCOPE)).toEqual([]);
|
||||
|
||||
service.addChannel(CONVERSATION_ID, 'websocket:owner', OWNER_SCOPE);
|
||||
expect(session.channels.has('websocket:owner')).toBe(true);
|
||||
expect(() => service.addChannel(CONVERSATION_ID, 'websocket:foreign', FOREIGN_SCOPE)).toThrow(
|
||||
ForbiddenException,
|
||||
);
|
||||
expect(() => service.removeChannel(CONVERSATION_ID, 'websocket:owner', FOREIGN_SCOPE)).toThrow(
|
||||
ForbiddenException,
|
||||
);
|
||||
|
||||
expect(() =>
|
||||
service.updateSessionModel(CONVERSATION_ID, 'foreign-model', FOREIGN_SCOPE),
|
||||
).toThrow(ForbiddenException);
|
||||
service.updateSessionModel(CONVERSATION_ID, 'owner-model', OWNER_SCOPE);
|
||||
expect(session.modelId).toBe('owner-model');
|
||||
|
||||
expect(() =>
|
||||
service.applyAgentConfig(CONVERSATION_ID, 'agent-foreign', 'Foreign Agent', FOREIGN_SCOPE),
|
||||
).toThrow(ForbiddenException);
|
||||
service.applyAgentConfig(CONVERSATION_ID, 'agent-owner', 'Owner Agent', OWNER_SCOPE);
|
||||
expect(session.agentConfigId).toBe('agent-owner');
|
||||
|
||||
expect(() => service.onEvent(CONVERSATION_ID, vi.fn(), FOREIGN_SCOPE)).toThrow(
|
||||
ForbiddenException,
|
||||
);
|
||||
const cleanup = service.onEvent(CONVERSATION_ID, vi.fn(), OWNER_SCOPE);
|
||||
cleanup();
|
||||
|
||||
await expect(
|
||||
service.prompt(CONVERSATION_ID, 'foreign prompt', FOREIGN_SCOPE),
|
||||
).rejects.toBeInstanceOf(ForbiddenException);
|
||||
await service.prompt(CONVERSATION_ID, 'owner prompt', OWNER_SCOPE);
|
||||
expect(session.piSession.prompt).toHaveBeenCalledWith('owner prompt');
|
||||
await service.prompt(CONVERSATION_ID, '', OWNER_SCOPE, [
|
||||
{
|
||||
id: 'attachment-001',
|
||||
name: 'diagram.png',
|
||||
url: 'https://cdn.example.test/diagram.png',
|
||||
mimeType: 'image/png',
|
||||
},
|
||||
]);
|
||||
expect(session.piSession.prompt).toHaveBeenLastCalledWith(
|
||||
'\n\n[Untrusted channel attachments]\n' +
|
||||
'{"id":"attachment-001","name":"diagram.png","mimeType":"image/png","url":"https://cdn.example.test/diagram.png"}',
|
||||
);
|
||||
|
||||
await expect(service.destroySession(CONVERSATION_ID, FOREIGN_SCOPE)).rejects.toBeInstanceOf(
|
||||
ForbiddenException,
|
||||
);
|
||||
expect(internals(service).sessions.has(CONVERSATION_ID)).toBe(true);
|
||||
|
||||
await service.destroySession(CONVERSATION_ID, OWNER_SCOPE);
|
||||
expect(session.piSession.dispose).toHaveBeenCalled();
|
||||
expect(internals(service).sessions.has(CONVERSATION_ID)).toBe(false);
|
||||
});
|
||||
|
||||
it('derives the operator-memory scope on the createSession production path', async () => {
|
||||
const plugin = { capture: vi.fn(), search: vi.fn() };
|
||||
const service = makeService(plugin);
|
||||
const buildTools = vi.spyOn(service as never, 'buildToolsForSandbox').mockReturnValue([]);
|
||||
|
||||
// Session construction reaches the real scope derivation before the intentionally incomplete
|
||||
// Pi test double rejects later in createAgentSession.
|
||||
await service.createSession(CONVERSATION_ID, OWNER_SCOPE).catch(() => undefined);
|
||||
|
||||
expect(buildTools).toHaveBeenCalledWith(expect.any(String), OWNER_SCOPE.userId, {
|
||||
tenantId: OWNER_SCOPE.tenantId,
|
||||
ownerId: OWNER_SCOPE.userId,
|
||||
sessionId: CONVERSATION_ID,
|
||||
});
|
||||
});
|
||||
|
||||
it('denies a foreign actor before it can obtain another session operator-memory scope', async () => {
|
||||
const plugin = { capture: vi.fn(), search: vi.fn() };
|
||||
const service = makeService(plugin);
|
||||
internals(service).sessions.set(CONVERSATION_ID, makeSession());
|
||||
const buildTools = vi.spyOn(service as never, 'buildToolsForSandbox');
|
||||
|
||||
await expect(service.createSession(CONVERSATION_ID, FOREIGN_SCOPE)).rejects.toBeInstanceOf(
|
||||
ForbiddenException,
|
||||
);
|
||||
|
||||
expect(buildTools).not.toHaveBeenCalled();
|
||||
expect(plugin.capture).not.toHaveBeenCalled();
|
||||
expect(plugin.search).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('checks owner/tenant scope before returning an in-flight session creation', async () => {
|
||||
const service = makeService();
|
||||
const session = makeSession();
|
||||
internals(service).creating.set(CONVERSATION_ID, Promise.resolve(session));
|
||||
|
||||
await expect(
|
||||
service.createSession(CONVERSATION_ID, {
|
||||
userId: FOREIGN_SCOPE.userId,
|
||||
tenantId: FOREIGN_SCOPE.tenantId,
|
||||
}),
|
||||
).rejects.toBeInstanceOf(ForbiddenException);
|
||||
|
||||
await expect(
|
||||
service.createSession(CONVERSATION_ID, {
|
||||
userId: OWNER_SCOPE.userId,
|
||||
tenantId: OWNER_SCOPE.tenantId,
|
||||
}),
|
||||
).resolves.toBe(session);
|
||||
});
|
||||
});
|
||||
@@ -1,370 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type {
|
||||
AgentRuntimeProvider,
|
||||
RuntimeAttachHandle,
|
||||
RuntimeAttachMode,
|
||||
RuntimeCapability,
|
||||
RuntimeCapabilitySet,
|
||||
RuntimeHealth,
|
||||
RuntimeMessage,
|
||||
RuntimeScope,
|
||||
RuntimeSession,
|
||||
RuntimeSessionTree,
|
||||
RuntimeStreamEvent,
|
||||
} from '@mosaicstack/types';
|
||||
import { AgentRuntimeProviderRegistry } from '@mosaicstack/agent';
|
||||
import type { ActorTenantScope } from '../../auth/session-scope.js';
|
||||
import {
|
||||
RuntimeProviderAuditService,
|
||||
RuntimeProviderService,
|
||||
type RuntimeAuditEvent,
|
||||
type RuntimeAuditSink,
|
||||
type RuntimeApprovalVerifier,
|
||||
} from '../runtime-provider-registry.service.js';
|
||||
|
||||
process.env['MOSAIC_AGENT_NAME'] ??= 'test-runtime-agent';
|
||||
|
||||
const OWNER_SCOPE: ActorTenantScope = { userId: 'owner-1', tenantId: 'tenant-1' };
|
||||
const CONTEXT = {
|
||||
actorScope: OWNER_SCOPE,
|
||||
channelId: 'cli',
|
||||
correlationId: 'correlation-1',
|
||||
};
|
||||
|
||||
class RecordingRuntimeProvider implements AgentRuntimeProvider {
|
||||
readonly id = 'fleet';
|
||||
readonly receivedScopes: RuntimeScope[] = [];
|
||||
readonly sentMessages: RuntimeMessage[] = [];
|
||||
terminateCalls = 0;
|
||||
throwAfterSend = false;
|
||||
throwAuthorization = false;
|
||||
|
||||
constructor(private readonly supported: RuntimeCapability[]) {}
|
||||
|
||||
async capabilities(scope: RuntimeScope): Promise<RuntimeCapabilitySet> {
|
||||
this.receivedScopes.push(scope);
|
||||
return { supported: this.supported };
|
||||
}
|
||||
|
||||
async health(scope: RuntimeScope): Promise<RuntimeHealth> {
|
||||
this.receivedScopes.push(scope);
|
||||
return { status: 'healthy', checkedAt: '2026-07-12T00:00:00.000Z' };
|
||||
}
|
||||
|
||||
async listSessions(scope: RuntimeScope): Promise<RuntimeSession[]> {
|
||||
this.receivedScopes.push(scope);
|
||||
return [];
|
||||
}
|
||||
|
||||
async getSessionTree(scope: RuntimeScope): Promise<RuntimeSessionTree[]> {
|
||||
this.receivedScopes.push(scope);
|
||||
return [];
|
||||
}
|
||||
|
||||
async *streamSession(
|
||||
_sessionId: string,
|
||||
_cursor: string | undefined,
|
||||
scope: RuntimeScope,
|
||||
): AsyncIterable<RuntimeStreamEvent> {
|
||||
this.receivedScopes.push(scope);
|
||||
return;
|
||||
}
|
||||
|
||||
async sendMessage(
|
||||
_sessionId: string,
|
||||
message: RuntimeMessage,
|
||||
scope: RuntimeScope,
|
||||
): Promise<void> {
|
||||
this.receivedScopes.push(scope);
|
||||
this.sentMessages.push(message);
|
||||
if (this.throwAuthorization) {
|
||||
throw Object.assign(new Error('provider authorization denied'), { code: 'forbidden' });
|
||||
}
|
||||
if (this.throwAfterSend) {
|
||||
throw new Error('provider acknowledgement failed');
|
||||
}
|
||||
}
|
||||
|
||||
async attach(
|
||||
sessionId: string,
|
||||
mode: RuntimeAttachMode,
|
||||
scope: RuntimeScope,
|
||||
): Promise<RuntimeAttachHandle> {
|
||||
this.receivedScopes.push(scope);
|
||||
return {
|
||||
attachmentId: 'attachment-1',
|
||||
sessionId,
|
||||
mode,
|
||||
expiresAt: '2026-07-12T00:00:00.000Z',
|
||||
};
|
||||
}
|
||||
|
||||
async detach(_attachmentId: string, scope: RuntimeScope): Promise<void> {
|
||||
this.receivedScopes.push(scope);
|
||||
}
|
||||
|
||||
async terminate(_sessionId: string, _approvalRef: string, scope: RuntimeScope): Promise<void> {
|
||||
this.receivedScopes.push(scope);
|
||||
this.terminateCalls += 1;
|
||||
}
|
||||
}
|
||||
|
||||
class RecordingAuditSink implements RuntimeAuditSink {
|
||||
readonly events: RuntimeAuditEvent[] = [];
|
||||
|
||||
async record(event: RuntimeAuditEvent): Promise<void> {
|
||||
this.events.push(event);
|
||||
}
|
||||
}
|
||||
|
||||
class DenyingApprovalVerifier implements RuntimeApprovalVerifier {
|
||||
async consume(): Promise<boolean> {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
class AcceptingApprovalVerifier implements RuntimeApprovalVerifier {
|
||||
consumedAction: Parameters<RuntimeApprovalVerifier['consume']>[1] | undefined;
|
||||
|
||||
async consume(
|
||||
_approvalRef: string,
|
||||
action: Parameters<RuntimeApprovalVerifier['consume']>[1],
|
||||
): Promise<boolean> {
|
||||
this.consumedAction = action;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
function makeService(
|
||||
provider: RecordingRuntimeProvider,
|
||||
audit: RuntimeAuditSink = new RecordingAuditSink(),
|
||||
approval: RuntimeApprovalVerifier = new DenyingApprovalVerifier(),
|
||||
): RuntimeProviderService {
|
||||
const registry = new AgentRuntimeProviderRegistry();
|
||||
registry.register(provider);
|
||||
return new RuntimeProviderService(registry, audit, approval);
|
||||
}
|
||||
|
||||
describe('RuntimeProviderService security boundary', (): void => {
|
||||
it('derives and freezes only the authenticated actor scope while preserving correlation metadata', async (): Promise<void> => {
|
||||
const provider = new RecordingRuntimeProvider(['session.send']);
|
||||
const audit = new RecordingAuditSink();
|
||||
const service = makeService(provider, audit);
|
||||
|
||||
await service.sendMessage(
|
||||
'fleet',
|
||||
'session-1',
|
||||
{ content: 'hello', idempotencyKey: 'key-1' },
|
||||
CONTEXT,
|
||||
);
|
||||
|
||||
const providerScope = provider.receivedScopes[0];
|
||||
expect(providerScope).toEqual({
|
||||
actorId: OWNER_SCOPE.userId,
|
||||
tenantId: OWNER_SCOPE.tenantId,
|
||||
channelId: CONTEXT.channelId,
|
||||
correlationId: CONTEXT.correlationId,
|
||||
});
|
||||
expect(Object.isFrozen(providerScope)).toBe(true);
|
||||
expect(audit.events).toContainEqual(
|
||||
expect.objectContaining({
|
||||
providerId: 'fleet',
|
||||
operation: 'session.send',
|
||||
outcome: 'succeeded',
|
||||
actorId: OWNER_SCOPE.userId,
|
||||
tenantId: OWNER_SCOPE.tenantId,
|
||||
channelId: CONTEXT.channelId,
|
||||
correlationId: CONTEXT.correlationId,
|
||||
resourceId: 'session-1',
|
||||
durationMs: expect.any(Number),
|
||||
}),
|
||||
);
|
||||
expect(JSON.stringify(audit.events)).not.toContain('hello');
|
||||
expect(JSON.stringify(audit.events)).not.toContain('key-1');
|
||||
});
|
||||
|
||||
it('does not block a provider operation when an unsafe resource ID is redacted in durable audit', async (): Promise<void> => {
|
||||
const provider = new RecordingRuntimeProvider(['session.send']);
|
||||
let persisted: unknown;
|
||||
const durableAudit = new RuntimeProviderAuditService({
|
||||
logs: {
|
||||
ingest: async (entry: unknown): Promise<unknown> => {
|
||||
persisted = entry;
|
||||
return entry;
|
||||
},
|
||||
},
|
||||
} as never);
|
||||
const service = makeService(provider, durableAudit);
|
||||
|
||||
await service.sendMessage(
|
||||
'fleet',
|
||||
'session/credential-canary=secret-value',
|
||||
{ content: 'safe message', idempotencyKey: 'key-1' },
|
||||
CONTEXT,
|
||||
);
|
||||
|
||||
expect(provider.sentMessages).toHaveLength(1);
|
||||
expect(JSON.stringify(persisted)).not.toContain('secret-value');
|
||||
});
|
||||
|
||||
it('fails closed before a provider side effect when a capability is missing', async (): Promise<void> => {
|
||||
const provider = new RecordingRuntimeProvider([]);
|
||||
const service = makeService(provider);
|
||||
|
||||
await expect(
|
||||
service.sendMessage(
|
||||
'fleet',
|
||||
'session-1',
|
||||
{ content: 'hello', idempotencyKey: 'key-1' },
|
||||
CONTEXT,
|
||||
),
|
||||
).rejects.toThrow(/capability denied/);
|
||||
expect(provider.sentMessages).toEqual([]);
|
||||
});
|
||||
|
||||
it('requires a consumed exact-action approval before termination', async (): Promise<void> => {
|
||||
const provider = new RecordingRuntimeProvider(['session.terminate']);
|
||||
const approval = new DenyingApprovalVerifier();
|
||||
const audit = new RecordingAuditSink();
|
||||
const service = makeService(provider, audit, approval);
|
||||
|
||||
await expect(
|
||||
service.terminate('fleet', 'session-1', 'forged-approval', CONTEXT),
|
||||
).rejects.toThrow(/approval denied/);
|
||||
expect(provider.terminateCalls).toBe(0);
|
||||
expect(audit.events.at(-1)).toMatchObject({ outcome: 'denied', errorCode: 'policy_denied' });
|
||||
});
|
||||
|
||||
it('binds an accepted termination approval to provider, session, immutable scope, and correlation', async (): Promise<void> => {
|
||||
const provider = new RecordingRuntimeProvider(['session.terminate']);
|
||||
const approval = new AcceptingApprovalVerifier();
|
||||
const service = makeService(provider, new RecordingAuditSink(), approval);
|
||||
|
||||
await service.terminate('fleet', 'session-1', 'approval-1', CONTEXT);
|
||||
|
||||
expect(approval.consumedAction).toEqual({
|
||||
providerId: 'fleet',
|
||||
sessionId: 'session-1',
|
||||
actorId: OWNER_SCOPE.userId,
|
||||
tenantId: OWNER_SCOPE.tenantId,
|
||||
channelId: CONTEXT.channelId,
|
||||
correlationId: CONTEXT.correlationId,
|
||||
agentName: process.env['MOSAIC_AGENT_NAME'],
|
||||
});
|
||||
expect(provider.terminateCalls).toBe(1);
|
||||
});
|
||||
|
||||
it('fails closed before invoking a provider when audit persistence rejects the request', async (): Promise<void> => {
|
||||
const provider = new RecordingRuntimeProvider(['session.send']);
|
||||
const unavailableAudit: RuntimeAuditSink = {
|
||||
async record(): Promise<void> {
|
||||
throw new Error('audit unavailable');
|
||||
},
|
||||
};
|
||||
const service = makeService(provider, unavailableAudit);
|
||||
|
||||
await expect(
|
||||
service.sendMessage(
|
||||
'fleet',
|
||||
'session-1',
|
||||
{ content: 'hello', idempotencyKey: 'key-1' },
|
||||
CONTEXT,
|
||||
),
|
||||
).rejects.toThrow(/audit unavailable/);
|
||||
expect(provider.sentMessages).toEqual([]);
|
||||
});
|
||||
|
||||
it('records a provider error after invocation as failed rather than denied', async (): Promise<void> => {
|
||||
const provider = new RecordingRuntimeProvider(['session.send']);
|
||||
provider.throwAfterSend = true;
|
||||
const audit = new RecordingAuditSink();
|
||||
const service = makeService(provider, audit);
|
||||
|
||||
await expect(
|
||||
service.sendMessage(
|
||||
'fleet',
|
||||
'session-1',
|
||||
{ content: 'hello', idempotencyKey: 'key-1' },
|
||||
CONTEXT,
|
||||
),
|
||||
).rejects.toThrow(/provider acknowledgement failed/);
|
||||
expect(provider.sentMessages).toHaveLength(1);
|
||||
expect(audit.events.map((event: RuntimeAuditEvent): string => event.outcome)).toEqual([
|
||||
'requested',
|
||||
'failed',
|
||||
]);
|
||||
expect(audit.events.at(-1)).toMatchObject({
|
||||
errorCode: 'provider_error',
|
||||
durationMs: expect.any(Number),
|
||||
});
|
||||
});
|
||||
|
||||
it('records a provider authorization rejection as denied rather than provider failure', async (): Promise<void> => {
|
||||
const provider = new RecordingRuntimeProvider(['session.send']);
|
||||
provider.throwAuthorization = true;
|
||||
const audit = new RecordingAuditSink();
|
||||
const service = makeService(provider, audit);
|
||||
|
||||
await expect(
|
||||
service.sendMessage(
|
||||
'fleet',
|
||||
'session-1',
|
||||
{ content: 'hello', idempotencyKey: 'key-1' },
|
||||
CONTEXT,
|
||||
),
|
||||
).rejects.toThrow(/provider authorization denied/);
|
||||
expect(audit.events.at(-1)).toMatchObject({ outcome: 'denied', errorCode: 'policy_denied' });
|
||||
});
|
||||
|
||||
it('persists only metadata-only runtime audit fields', async (): Promise<void> => {
|
||||
let persisted: unknown;
|
||||
const ingest = async (entry: unknown): Promise<unknown> => {
|
||||
persisted = entry;
|
||||
return entry;
|
||||
};
|
||||
const service = new RuntimeProviderAuditService({ logs: { ingest } } as never);
|
||||
|
||||
await service.record({
|
||||
providerId: 'fleet',
|
||||
operation: 'session.send',
|
||||
outcome: 'succeeded',
|
||||
actorId: 'owner-1',
|
||||
tenantId: 'tenant-1',
|
||||
channelId: 'cli',
|
||||
correlationId: 'correlation-1',
|
||||
resourceId: 'session-1',
|
||||
durationMs: 12,
|
||||
});
|
||||
|
||||
expect(persisted).toMatchObject({
|
||||
content: 'runtime.provider.audit',
|
||||
metadata: expect.objectContaining({ correlationId: 'correlation-1', durationMs: 12 }),
|
||||
});
|
||||
expect(JSON.stringify(persisted)).not.toContain('approval');
|
||||
});
|
||||
|
||||
it('does not misreport a completed provider side effect when completion auditing fails', async (): Promise<void> => {
|
||||
const provider = new RecordingRuntimeProvider(['session.send']);
|
||||
let auditCalls = 0;
|
||||
const audit: RuntimeAuditSink = {
|
||||
async record(): Promise<void> {
|
||||
auditCalls += 1;
|
||||
if (auditCalls === 2) {
|
||||
throw new Error('completion audit unavailable');
|
||||
}
|
||||
},
|
||||
};
|
||||
const service = makeService(provider, audit);
|
||||
|
||||
await expect(
|
||||
service.sendMessage(
|
||||
'fleet',
|
||||
'session-1',
|
||||
{ content: 'hello', idempotencyKey: 'key-1' },
|
||||
CONTEXT,
|
||||
),
|
||||
).resolves.toBeUndefined();
|
||||
expect(provider.sentMessages).toHaveLength(1);
|
||||
expect(auditCalls).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -1,866 +0,0 @@
|
||||
import 'reflect-metadata';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { ForbiddenException, NotFoundException } from '@nestjs/common';
|
||||
import { Test, type TestingModule } from '@nestjs/testing';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('../agent.service.js', () => ({ AgentService: class AgentService {} }));
|
||||
vi.mock('../../commands/command-executor.service.js', () => ({
|
||||
CommandExecutorService: class CommandExecutorService {},
|
||||
}));
|
||||
vi.mock('../routing/routing-engine.service.js', () => ({
|
||||
RoutingEngineService: class RoutingEngineService {},
|
||||
}));
|
||||
|
||||
import { SessionsController } from '../sessions.controller.js';
|
||||
import { AgentService } from '../agent.service.js';
|
||||
import { ChatController } from '../../chat/chat.controller.js';
|
||||
import { ChatGateway } from '../../chat/chat.gateway.js';
|
||||
import type { AgentSession } from '../agent.service.js';
|
||||
import type { SessionInfoDto } from '../session.dto.js';
|
||||
import type { HarnessAdapter, HarnessConversationService } from '@mosaicstack/types';
|
||||
import { AuthGuard } from '../../auth/auth.guard.js';
|
||||
import { AUTH } from '../../auth/auth.tokens.js';
|
||||
import { BRAIN } from '../../brain/brain.tokens.js';
|
||||
import { CommandRegistryService } from '../../commands/command-registry.service.js';
|
||||
import { CommandExecutorService } from '../../commands/command-executor.service.js';
|
||||
import { RoutingEngineService } from '../routing/routing-engine.service.js';
|
||||
import { ChatRuntimeRouter } from '../../chat/chat-runtime-router.js';
|
||||
import { EmbeddedChatRuntime } from '../../chat/embedded-chat.runtime.js';
|
||||
import { ownConversation } from '../../chat/chat-runtime.js';
|
||||
import type { LegacyRuntimeStream } from '../../chat/chat-runtime.js';
|
||||
import { HarnessChatRuntime } from '../../chat/harness-chat.runtime.js';
|
||||
import { HarnessRegistry } from '../../harness/harness.registry.js';
|
||||
import { HARNESS_CONVERSATION_SERVICE_UNAVAILABLE } from '../../harness/harness.tokens.js';
|
||||
|
||||
const USER_A = { id: 'user-a', tenantId: 'tenant-a' };
|
||||
const USER_B = { id: 'user-b', tenantId: 'tenant-b' };
|
||||
const CONVERSATION_ID = '11111111-1111-4111-8111-111111111111';
|
||||
|
||||
function makeSessionInfo(overrides?: Partial<SessionInfoDto>): SessionInfoDto {
|
||||
return {
|
||||
id: CONVERSATION_ID,
|
||||
provider: 'test-provider',
|
||||
modelId: 'test-model',
|
||||
createdAt: new Date('2026-07-12T00:00:00Z').toISOString(),
|
||||
promptCount: 0,
|
||||
channels: [],
|
||||
durationMs: 0,
|
||||
metrics: {
|
||||
tokens: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
||||
modelSwitches: 0,
|
||||
messageCount: 0,
|
||||
lastActivityAt: new Date('2026-07-12T00:00:00Z').toISOString(),
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeAgentSession(owner = USER_A): AgentSession {
|
||||
return {
|
||||
id: CONVERSATION_ID,
|
||||
provider: 'test-provider',
|
||||
modelId: 'test-model',
|
||||
piSession: {
|
||||
thinkingLevel: 'off',
|
||||
getAvailableThinkingLevels: vi.fn().mockReturnValue(['off', 'low', 'high']),
|
||||
setThinkingLevel: vi.fn(),
|
||||
abort: vi.fn().mockResolvedValue(undefined),
|
||||
prompt: vi.fn().mockResolvedValue(undefined),
|
||||
dispose: vi.fn(),
|
||||
getSessionStats: vi.fn(),
|
||||
getContextUsage: vi.fn(),
|
||||
} as unknown as AgentSession['piSession'],
|
||||
listeners: new Set(),
|
||||
unsubscribe: vi.fn(),
|
||||
createdAt: Date.now(),
|
||||
promptCount: 0,
|
||||
channels: new Set(),
|
||||
skillPromptAdditions: [],
|
||||
sandboxDir: '/tmp',
|
||||
allowedTools: null,
|
||||
userId: owner.id,
|
||||
tenantId: owner.tenantId,
|
||||
metrics: {
|
||||
tokens: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
||||
modelSwitches: 0,
|
||||
messageCount: 0,
|
||||
lastActivityAt: new Date('2026-07-12T00:00:00Z').toISOString(),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A shape-complete, non-throwing AgentService fake scoped so that USER_B (a foreign owner guessing
|
||||
* USER_A's conversation id) is never granted the session. Because every method exists and no method
|
||||
* throws for a wrong shape, production runs to its real ownership decision — the RED never comes from
|
||||
* a `getSession is not a function` TypeError, only from a router-boundary/scope assertion mismatch.
|
||||
*/
|
||||
function makeScopedAgentService() {
|
||||
const foreign = makeAgentSession(USER_A);
|
||||
return {
|
||||
listSessions: vi.fn((scope?: { userId: string; tenantId?: string }) =>
|
||||
scope?.userId === USER_B.id ? [] : [makeSessionInfo({ id: foreign.id })],
|
||||
),
|
||||
getSessionInfo: vi.fn((_id: string, scope?: { userId: string; tenantId?: string }) =>
|
||||
scope?.userId === USER_B.id ? undefined : makeSessionInfo({ id: foreign.id }),
|
||||
),
|
||||
destroySession: vi.fn(),
|
||||
getSession: vi.fn((_id: string, scope?: { userId: string; tenantId?: string }) =>
|
||||
scope?.userId === USER_B.id ? undefined : foreign,
|
||||
),
|
||||
createSession: vi.fn().mockRejectedValue(new NotFoundException('Session scope mismatch')),
|
||||
onEvent: vi.fn(() => vi.fn()),
|
||||
addChannel: vi.fn(),
|
||||
removeChannel: vi.fn(),
|
||||
recordMessage: vi.fn(),
|
||||
prompt: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
}
|
||||
|
||||
type ScopedAgentService = ReturnType<typeof makeScopedAgentService>;
|
||||
|
||||
/**
|
||||
* A structurally-complete harness conversation service that throws if any method is invoked.
|
||||
* Fronted behind the legacy runtime's harness slot: the legacy path must never reach it.
|
||||
*/
|
||||
const failIfUsedConversationService = {
|
||||
attach: () => {
|
||||
throw new Error('harness conversation service must not be reached on the legacy path');
|
||||
},
|
||||
detach: () => {
|
||||
throw new Error('harness conversation service must not be reached on the legacy path');
|
||||
},
|
||||
send: () => {
|
||||
throw new Error('harness conversation service must not be reached on the legacy path');
|
||||
},
|
||||
|
||||
subscribeFrom: async function* () {
|
||||
throw new Error('harness conversation service must not be reached on the legacy path');
|
||||
},
|
||||
} as unknown as HarnessConversationService;
|
||||
|
||||
/** A structurally-complete, non-sentinel conversation service used to satisfy the pi-rpc readiness gate. */
|
||||
const boundConversationService = {
|
||||
attach: () => Promise.reject(new Error('unused')),
|
||||
detach: () => Promise.reject(new Error('unused')),
|
||||
send: () => Promise.reject(new Error('unused')),
|
||||
|
||||
subscribeFrom: async function* () {
|
||||
throw new Error('unused');
|
||||
},
|
||||
} as unknown as HarnessConversationService;
|
||||
|
||||
function registryWith(adapterIds: readonly string[]): HarnessRegistry {
|
||||
const registry = new HarnessRegistry();
|
||||
for (const id of adapterIds) {
|
||||
registry.register({
|
||||
id,
|
||||
describe: () => Promise.reject(new Error('unused')),
|
||||
catalog: () => Promise.reject(new Error('unused')),
|
||||
create: () => Promise.reject(new Error('unused')),
|
||||
resume: () => Promise.reject(new Error('unused')),
|
||||
} as HarnessAdapter);
|
||||
}
|
||||
return registry;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the real legacy-mode {@link ChatRuntimeRouter} fronting a real {@link EmbeddedChatRuntime}
|
||||
* that holds the scoped AgentService fake. This is the ONLY path server-derived scope may travel to
|
||||
* reach an AgentService: controller/gateway → ChatRuntimeRouter → EmbeddedChatRuntime → AgentService.
|
||||
* The `embeddedAgentService` handed here is a SEPARATE instance from the directly-injected fake, so a
|
||||
* call landing on it proves the router-delegation redesign is live rather than the old direct path.
|
||||
*/
|
||||
function legacyRouterFronting(agentService: unknown): ChatRuntimeRouter {
|
||||
const embedded = new EmbeddedChatRuntime(agentService as never);
|
||||
const harness = new HarnessChatRuntime(failIfUsedConversationService);
|
||||
const router = new ChatRuntimeRouter(
|
||||
new HarnessRegistry(),
|
||||
HARNESS_CONVERSATION_SERVICE_UNAVAILABLE,
|
||||
embedded,
|
||||
harness,
|
||||
'legacy',
|
||||
);
|
||||
router.onModuleInit();
|
||||
return router;
|
||||
}
|
||||
|
||||
/**
|
||||
* The AgentService method names the controller/gateway must NEVER drive on the runtime at the
|
||||
* delegation boundary. An AgentService-shaped router shim (a method-for-method mirror) would record
|
||||
* one of these instead of the frozen legacy op, so asserting their ABSENCE from the observed runtime
|
||||
* call set defeats the shim on INVOCATION evidence — never satisfiable by dead source text.
|
||||
*/
|
||||
const FORBIDDEN_AGENT_OPS = [
|
||||
'getSession',
|
||||
'createSession',
|
||||
'onEvent',
|
||||
'addChannel',
|
||||
'prompt',
|
||||
'setThinking',
|
||||
'abort',
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Wrap a real {@link ChatRuntimeRouter} in a call-recording Proxy. Every property access that yields
|
||||
* an OWN/inherited callable is returned as a thin wrapper that appends the method name to `calls` at
|
||||
* INVOCATION time and forwards to the real method (bound to the real target, so the router's internal
|
||||
* delegation to the embedded runtime runs untouched below this boundary). Non-function and MISSING
|
||||
* properties are returned verbatim via Reflect.get — the observer NEVER fabricates a value, returns a
|
||||
* canned outcome, or delegates a not-yet-implemented named op, so it cannot itself become a shim.
|
||||
*
|
||||
* The result is a RUNTIME call set of exactly the methods the controller/gateway invoke ON the router
|
||||
* at the delegation seam. Only an actual call can enter it; a dead method, comment, or string in the
|
||||
* production source cannot. This replaces the earlier `source.toContain('<frozen op>')` proof — which
|
||||
* a dead declaration could satisfy while production still executed a shim — with invocation evidence.
|
||||
*/
|
||||
function makeRecordingRouter(target: ChatRuntimeRouter, calls: string[]): ChatRuntimeRouter {
|
||||
return new Proxy(target, {
|
||||
get(t, prop) {
|
||||
const value = Reflect.get(t, prop);
|
||||
if (typeof value === 'function' && typeof prop === 'string') {
|
||||
return (...args: unknown[]) => {
|
||||
calls.push(prop);
|
||||
return (value as (...a: unknown[]) => unknown).apply(t, args);
|
||||
};
|
||||
}
|
||||
return value;
|
||||
},
|
||||
}) as ChatRuntimeRouter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Real Nest DI dual-provider fixture (mirrors the blessed group-3 pattern in chat-security.test.ts).
|
||||
*
|
||||
* BOTH an `AgentService` provider (the FORBIDDEN direct dependency) and a `ChatRuntimeRouter` provider
|
||||
* (fronting a real EmbeddedChatRuntime over a SEPARATE scoped AgentService) are registered. Production
|
||||
* resolves whichever its constructor declares:
|
||||
* - RED today: the controller/gateway `@Inject(AgentService)` → the direct fake is consulted, the
|
||||
* router (and its embedded fake) is never reached.
|
||||
* - GREEN later: the controller/gateway inject `ChatRuntimeRouter` → the direct fake is never
|
||||
* touched (stays at zero) and scope is observed inside the embedded fake behind the router.
|
||||
* The SAME test body reds today and greens later; a method-for-method AgentService shim on the router
|
||||
* records a FORBIDDEN op (and never the frozen legacy op) in the observed runtime call set, and
|
||||
* restoring the direct injection cannot satisfy the "direct fake at zero" / "embedded fake observed
|
||||
* scope" / "frozen op invoked on the router" anchors. The router is wrapped by {@link
|
||||
* makeRecordingRouter} so those anchors are runtime invocation evidence, not source substrings.
|
||||
*/
|
||||
function buildRestModule(
|
||||
directAgentService: ScopedAgentService,
|
||||
embeddedAgentService: ScopedAgentService,
|
||||
routerCalls: string[],
|
||||
): Promise<TestingModule> {
|
||||
return (
|
||||
Test.createTestingModule({
|
||||
controllers: [ChatController],
|
||||
providers: [
|
||||
{ provide: AgentService, useValue: directAgentService },
|
||||
{
|
||||
provide: ChatRuntimeRouter,
|
||||
useFactory: () =>
|
||||
makeRecordingRouter(legacyRouterFronting(embeddedAgentService), routerCalls),
|
||||
},
|
||||
],
|
||||
})
|
||||
// ChatController's @UseGuards(AuthGuard) is resolved during instance loading; AuthGuard injects
|
||||
// AUTH, an HTTP-only concern never exercised by a direct handler call. Stub it so the graph
|
||||
// resolves and the test reds on BEHAVIOUR, not on a DI collection error.
|
||||
.overrideGuard(AuthGuard)
|
||||
.useValue({ canActivate: () => true })
|
||||
.compile()
|
||||
);
|
||||
}
|
||||
|
||||
function buildGatewayModule(
|
||||
directAgentService: ScopedAgentService,
|
||||
embeddedAgentService: ScopedAgentService,
|
||||
routerCalls: string[],
|
||||
): Promise<TestingModule> {
|
||||
const brain = {
|
||||
conversations: {
|
||||
// The sender OWNS this durable conversation, so the browser-send admission gate lets the turn
|
||||
// reach the router seam. Foreignness is asserted downstream at the in-memory agent session
|
||||
// (getSession({USER_B}) -> undefined), not at durable admission — the admission-rejection
|
||||
// property has its own dedicated coverage.
|
||||
findById: vi.fn().mockResolvedValue({ id: CONVERSATION_ID, userId: USER_B.id }),
|
||||
create: vi.fn().mockResolvedValue(undefined),
|
||||
update: vi.fn().mockResolvedValue(undefined),
|
||||
findMessages: vi.fn().mockResolvedValue([]),
|
||||
addMessage: vi.fn().mockResolvedValue({ id: 'persisted-turn' }),
|
||||
},
|
||||
};
|
||||
return Test.createTestingModule({
|
||||
providers: [
|
||||
ChatGateway,
|
||||
{ provide: AgentService, useValue: directAgentService },
|
||||
{ provide: AUTH, useValue: { api: { getSession: vi.fn().mockResolvedValue(null) } } },
|
||||
{ provide: BRAIN, useValue: brain },
|
||||
{ provide: CommandRegistryService, useValue: { getManifest: vi.fn().mockReturnValue([]) } },
|
||||
{ provide: CommandExecutorService, useValue: { execute: vi.fn() } },
|
||||
{
|
||||
provide: RoutingEngineService,
|
||||
useValue: {
|
||||
resolve: vi.fn().mockResolvedValue({ provider: 'test', model: 'test-model' }),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: ChatRuntimeRouter,
|
||||
useFactory: () =>
|
||||
makeRecordingRouter(legacyRouterFronting(embeddedAgentService), routerCalls),
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
}
|
||||
|
||||
describe('TESS-M1-SEC-002 AgentService ownership boundary', () => {
|
||||
it('requires explicit owner+tenant scope on protected session operations', () => {
|
||||
const source = readFileSync(resolve('src/agent/agent.service.ts'), 'utf8');
|
||||
|
||||
expect(source).toContain('getSession(sessionId: string, scope: ActorTenantScope)');
|
||||
expect(source).toContain('listSessions(scope: ActorTenantScope)');
|
||||
expect(source).toContain('getSessionInfo(sessionId: string, scope: ActorTenantScope)');
|
||||
expect(source).toContain(
|
||||
'addChannel(sessionId: string, channel: string, scope: ActorTenantScope)',
|
||||
);
|
||||
expect(source).toContain(
|
||||
'removeChannel(sessionId: string, channel: string, scope: ActorTenantScope)',
|
||||
);
|
||||
expect(source).toContain(
|
||||
'async prompt(sessionId: string, message: string, scope: ActorTenantScope)',
|
||||
);
|
||||
expect(source).toContain('scope: ActorTenantScope,');
|
||||
expect(source).toContain('async destroySession(sessionId: string, scope: ActorTenantScope)');
|
||||
expect(source).not.toContain('scope?: ActorTenantScope');
|
||||
});
|
||||
});
|
||||
|
||||
describe('TESS-M1-SEC-002 REST session ownership and tenant binding', () => {
|
||||
it('lists only sessions owned by the authenticated owner+tenant scope', () => {
|
||||
const agentService = makeScopedAgentService();
|
||||
const controller = new SessionsController(agentService as never);
|
||||
|
||||
expect(controller.list(USER_B)).toEqual({ sessions: [], total: 0 });
|
||||
expect(agentService.listSessions).toHaveBeenCalledWith({
|
||||
userId: USER_B.id,
|
||||
tenantId: USER_B.tenantId,
|
||||
});
|
||||
});
|
||||
|
||||
it('does not reveal another owner/tenant session by guessed id', () => {
|
||||
const agentService = makeScopedAgentService();
|
||||
const controller = new SessionsController(agentService as never);
|
||||
|
||||
expect(() => controller.findOne(CONVERSATION_ID, USER_B)).toThrow(NotFoundException);
|
||||
expect(agentService.getSessionInfo).toHaveBeenCalledWith(CONVERSATION_ID, {
|
||||
userId: USER_B.id,
|
||||
tenantId: USER_B.tenantId,
|
||||
});
|
||||
});
|
||||
|
||||
it('does not terminate another owner/tenant session by guessed id', async () => {
|
||||
const agentService = makeScopedAgentService();
|
||||
const controller = new SessionsController(agentService as never);
|
||||
|
||||
await expect(controller.destroy(CONVERSATION_ID, USER_B)).rejects.toBeInstanceOf(
|
||||
NotFoundException,
|
||||
);
|
||||
expect(agentService.destroySession).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('TESS-M1-SEC-002 REST chat send ownership and tenant binding (router-delegated legacy runtime)', () => {
|
||||
// TESS test A — REST /api/chat send. The genuine RED is the router-delegation redesign, not a slot
|
||||
// swap: the forbidden directly-injected AgentService must go UNtouched while the server-derived
|
||||
// scope is observed inside the real ChatRuntimeRouter → EmbeddedChatRuntime → AgentService path.
|
||||
it('routes a REST send through completeLegacyRestTurn and never the directly-injected AgentService', async () => {
|
||||
const directAgentService = makeScopedAgentService(); // FORBIDDEN direct dependency
|
||||
const embeddedAgentService = makeScopedAgentService(); // reached ONLY via router → embedded delegation
|
||||
const routerCalls: string[] = []; // runtime call set observed AT the controller → router seam
|
||||
const moduleRef = await buildRestModule(directAgentService, embeddedAgentService, routerCalls);
|
||||
try {
|
||||
const controller = moduleRef.get(ChatController, { strict: false });
|
||||
|
||||
// Foreign ownership is denied (never resolves) — a control that holds today AND at GREEN.
|
||||
await expect(
|
||||
controller.chat({ conversationId: CONVERSATION_ID, content: 'take over' }, USER_B),
|
||||
).rejects.toBeDefined();
|
||||
|
||||
// Soft anchors so EVERY anchor is evaluated under each mutation, not just the first to fail.
|
||||
|
||||
// RUNTIME anchor A1 — delegation: the controller must INVOKE the frozen legacy op on the router.
|
||||
// Only an actual call enters routerCalls; a dead method/comment/string cannot. RED today (the
|
||||
// controller @Inject(AgentService) and never calls the router). GREEN once it drives the op.
|
||||
expect
|
||||
.soft(routerCalls, 'controller must invoke completeLegacyRestTurn on the router')
|
||||
.toContain('completeLegacyRestTurn');
|
||||
// RUNTIME anchor A2 — nondelegation: the controller must not drive any AgentService-shaped op on
|
||||
// the router. An AgentService-shaped router shim records one of these → RED, defeating the shim
|
||||
// on invocation evidence (not source text). A dead named method added alongside the shim does not
|
||||
// help: it is never invoked, so it never enters routerCalls while a forbidden op still does.
|
||||
for (const op of FORBIDDEN_AGENT_OPS) {
|
||||
expect
|
||||
.soft(routerCalls, `router seam must not invoke AgentService.${op}`)
|
||||
.not.toContain(op);
|
||||
}
|
||||
// RUNTIME anchor A3 — the forbidden directly-injected AgentService stays at zero (fails today;
|
||||
// restoring the direct injection keeps it failing).
|
||||
expect.soft(directAgentService.getSession).not.toHaveBeenCalled();
|
||||
// RUNTIME anchor A4 — server-derived scope observed INSIDE the separate embedded fake behind the
|
||||
// router (fails today; the router path is never taken).
|
||||
expect.soft(embeddedAgentService.getSession).toHaveBeenCalledWith(CONVERSATION_ID, {
|
||||
userId: USER_B.id,
|
||||
tenantId: USER_B.tenantId,
|
||||
});
|
||||
|
||||
// Zero foreign mutation on either path (holds today and at GREEN).
|
||||
expect.soft(directAgentService.prompt).not.toHaveBeenCalled();
|
||||
expect.soft(embeddedAgentService.prompt).not.toHaveBeenCalled();
|
||||
|
||||
// Defense-in-depth (NOT load-bearing; the runtime anchors above carry the anti-mask): the
|
||||
// controller no longer declares the direct embedded AgentService dependency. A negative source
|
||||
// check cannot be satisfied by dead text — it only fails when the injection is present.
|
||||
const controllerSource = readFileSync(resolve('src/chat/chat.controller.ts'), 'utf8');
|
||||
expect.soft(controllerSource).not.toContain('@Inject(AgentService)');
|
||||
} finally {
|
||||
await moduleRef.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('TESS-M1-SEC-002 WebSocket session ownership and tenant binding (router-delegated legacy runtime)', () => {
|
||||
function makeSocket() {
|
||||
return {
|
||||
id: 'socket-b',
|
||||
connected: true,
|
||||
data: { user: USER_B, session: { id: 'auth-session-b', userId: USER_B.id } },
|
||||
emit: vi.fn(),
|
||||
disconnect: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
// TESS test B — WebSocket send/attach.
|
||||
it('routes a WebSocket send through prepareLegacySocketTurn and never the directly-injected AgentService', async () => {
|
||||
const directAgentService = makeScopedAgentService();
|
||||
const embeddedAgentService = makeScopedAgentService();
|
||||
const routerCalls: string[] = [];
|
||||
const moduleRef = await buildGatewayModule(
|
||||
directAgentService,
|
||||
embeddedAgentService,
|
||||
routerCalls,
|
||||
);
|
||||
try {
|
||||
const gateway = moduleRef.get(ChatGateway, { strict: false });
|
||||
const socket = makeSocket();
|
||||
|
||||
await Promise.resolve(
|
||||
gateway.handleMessage(socket as never, {
|
||||
conversationId: CONVERSATION_ID,
|
||||
content: 'attach to foreign session',
|
||||
}),
|
||||
).catch(() => undefined);
|
||||
|
||||
// RUNTIME anchor B1 — delegation: the gateway must invoke the frozen socket op on the router.
|
||||
expect
|
||||
.soft(routerCalls, 'gateway must invoke prepareLegacySocketTurn on the router')
|
||||
.toContain('prepareLegacySocketTurn');
|
||||
// RUNTIME anchor B2 — nondelegation: no AgentService-shaped op on the router (defeats the shim).
|
||||
for (const op of FORBIDDEN_AGENT_OPS) {
|
||||
expect
|
||||
.soft(routerCalls, `router seam must not invoke AgentService.${op}`)
|
||||
.not.toContain(op);
|
||||
}
|
||||
// RED anchor B3 — forbidden direct AgentService untouched (fails today, gateway injects it).
|
||||
expect.soft(directAgentService.getSession).not.toHaveBeenCalled();
|
||||
// RED anchor B4 — scope observed inside router → embedded delegation (fails today, never reached).
|
||||
expect.soft(embeddedAgentService.getSession).toHaveBeenCalledWith(CONVERSATION_ID, {
|
||||
userId: USER_B.id,
|
||||
tenantId: USER_B.tenantId,
|
||||
});
|
||||
// Foreign session gets zero lease/listener/channel/prompt on EITHER path (holds today and GREEN).
|
||||
expect.soft(directAgentService.onEvent).not.toHaveBeenCalled();
|
||||
expect.soft(directAgentService.addChannel).not.toHaveBeenCalled();
|
||||
expect.soft(directAgentService.prompt).not.toHaveBeenCalled();
|
||||
expect.soft(embeddedAgentService.onEvent).not.toHaveBeenCalled();
|
||||
expect.soft(embeddedAgentService.addChannel).not.toHaveBeenCalled();
|
||||
expect.soft(embeddedAgentService.prompt).not.toHaveBeenCalled();
|
||||
expect
|
||||
.soft(socket.emit)
|
||||
.toHaveBeenCalledWith(
|
||||
'error',
|
||||
expect.objectContaining({ conversationId: CONVERSATION_ID }),
|
||||
);
|
||||
|
||||
// Defense-in-depth (NOT load-bearing): gateway no longer declares the direct dependency.
|
||||
const gatewaySource = readFileSync(resolve('src/chat/chat.gateway.ts'), 'utf8');
|
||||
expect.soft(gatewaySource).not.toContain('@Inject(AgentService)');
|
||||
} finally {
|
||||
await moduleRef.close();
|
||||
}
|
||||
});
|
||||
|
||||
// TESS test C — WebSocket set:thinking.
|
||||
it('routes set:thinking through setLegacyThinking and never the directly-injected AgentService', async () => {
|
||||
const directAgentService = makeScopedAgentService();
|
||||
const embeddedAgentService = makeScopedAgentService();
|
||||
const routerCalls: string[] = [];
|
||||
const moduleRef = await buildGatewayModule(
|
||||
directAgentService,
|
||||
embeddedAgentService,
|
||||
routerCalls,
|
||||
);
|
||||
try {
|
||||
const gateway = moduleRef.get(ChatGateway, { strict: false });
|
||||
const socket = makeSocket();
|
||||
|
||||
await Promise.resolve(
|
||||
gateway.handleSetThinking(socket as never, {
|
||||
conversationId: CONVERSATION_ID,
|
||||
level: 'high',
|
||||
}),
|
||||
).catch(() => undefined);
|
||||
|
||||
// RUNTIME anchor C1 — delegation: the gateway must invoke the frozen thinking op on the router.
|
||||
expect
|
||||
.soft(routerCalls, 'gateway must invoke setLegacyThinking on the router')
|
||||
.toContain('setLegacyThinking');
|
||||
// RUNTIME anchor C2 — nondelegation: no AgentService-shaped op on the router (defeats the shim).
|
||||
for (const op of FORBIDDEN_AGENT_OPS) {
|
||||
expect
|
||||
.soft(routerCalls, `router seam must not invoke AgentService.${op}`)
|
||||
.not.toContain(op);
|
||||
}
|
||||
expect.soft(directAgentService.getSession).not.toHaveBeenCalled();
|
||||
expect.soft(embeddedAgentService.getSession).toHaveBeenCalledWith(CONVERSATION_ID, {
|
||||
userId: USER_B.id,
|
||||
tenantId: USER_B.tenantId,
|
||||
});
|
||||
expect
|
||||
.soft(socket.emit)
|
||||
.toHaveBeenCalledWith(
|
||||
'error',
|
||||
expect.objectContaining({ conversationId: CONVERSATION_ID }),
|
||||
);
|
||||
} finally {
|
||||
await moduleRef.close();
|
||||
}
|
||||
});
|
||||
|
||||
// TESS test D — WebSocket abort.
|
||||
it('routes abort through abortLegacyTurn and never the directly-injected AgentService', async () => {
|
||||
const directAgentService = makeScopedAgentService();
|
||||
const embeddedAgentService = makeScopedAgentService();
|
||||
const routerCalls: string[] = [];
|
||||
const moduleRef = await buildGatewayModule(
|
||||
directAgentService,
|
||||
embeddedAgentService,
|
||||
routerCalls,
|
||||
);
|
||||
try {
|
||||
const gateway = moduleRef.get(ChatGateway, { strict: false });
|
||||
const socket = makeSocket();
|
||||
|
||||
await Promise.resolve(
|
||||
gateway.handleAbort(socket as never, { conversationId: CONVERSATION_ID }),
|
||||
).catch(() => undefined);
|
||||
|
||||
// RUNTIME anchor D1 — delegation: the gateway must invoke the frozen abort op on the router.
|
||||
expect
|
||||
.soft(routerCalls, 'gateway must invoke abortLegacyTurn on the router')
|
||||
.toContain('abortLegacyTurn');
|
||||
// RUNTIME anchor D2 — nondelegation: no AgentService-shaped op on the router (defeats the shim).
|
||||
for (const op of FORBIDDEN_AGENT_OPS) {
|
||||
expect
|
||||
.soft(routerCalls, `router seam must not invoke AgentService.${op}`)
|
||||
.not.toContain(op);
|
||||
}
|
||||
expect.soft(directAgentService.getSession).not.toHaveBeenCalled();
|
||||
expect.soft(embeddedAgentService.getSession).toHaveBeenCalledWith(CONVERSATION_ID, {
|
||||
userId: USER_B.id,
|
||||
tenantId: USER_B.tenantId,
|
||||
});
|
||||
expect
|
||||
.soft(socket.emit)
|
||||
.toHaveBeenCalledWith(
|
||||
'error',
|
||||
expect.objectContaining({ conversationId: CONVERSATION_ID }),
|
||||
);
|
||||
} finally {
|
||||
await moduleRef.close();
|
||||
}
|
||||
});
|
||||
|
||||
// TESS test E (genuine, unchanged) — pi-rpc browser-legacy refusal.
|
||||
it('rejects a browser legacy raw message in pi-rpc mode with a fixed typed unsupported and executes nothing', async () => {
|
||||
// pi-rpc: the harness runtime is live. The browser legacy `message` path is unsupported and
|
||||
// must be refused with a fixed typed code, touching neither the embedded AgentService nor the
|
||||
// harness conversation service.
|
||||
const agentService = makeScopedAgentService();
|
||||
const embedded = new EmbeddedChatRuntime(agentService as never);
|
||||
const harnessConversation = {
|
||||
attach: vi.fn(),
|
||||
detach: vi.fn(),
|
||||
send: vi.fn(),
|
||||
subscribeFrom: vi.fn(),
|
||||
};
|
||||
const harness = new HarnessChatRuntime(harnessConversation as never);
|
||||
const router = new ChatRuntimeRouter(
|
||||
registryWith(['pi']),
|
||||
boundConversationService,
|
||||
embedded,
|
||||
harness,
|
||||
'pi-rpc',
|
||||
);
|
||||
router.onModuleInit();
|
||||
|
||||
const brain = {
|
||||
conversations: {
|
||||
findById: vi.fn().mockResolvedValue(undefined),
|
||||
create: vi.fn().mockResolvedValue(undefined),
|
||||
update: vi.fn().mockResolvedValue(undefined),
|
||||
findMessages: vi.fn().mockResolvedValue([]),
|
||||
addMessage: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
};
|
||||
const gateway = new ChatGateway(
|
||||
router as never,
|
||||
{} as never,
|
||||
brain as never,
|
||||
{ getManifest: vi.fn().mockReturnValue([]) } as never,
|
||||
{ execute: vi.fn() } as never,
|
||||
{ resolve: vi.fn() } as never,
|
||||
);
|
||||
const socket = {
|
||||
id: 'socket-b',
|
||||
connected: true,
|
||||
data: { user: USER_B, session: { id: 'auth-session-b', userId: USER_B.id } },
|
||||
emit: vi.fn(),
|
||||
disconnect: vi.fn(),
|
||||
};
|
||||
|
||||
await Promise.resolve(
|
||||
gateway.handleMessage(socket as never, {
|
||||
conversationId: CONVERSATION_ID,
|
||||
content: 'route me',
|
||||
}),
|
||||
).catch(() => undefined);
|
||||
|
||||
expect(socket.emit).toHaveBeenCalledWith(
|
||||
'error',
|
||||
expect.objectContaining({ code: 'runtime_unsupported' }),
|
||||
);
|
||||
expect(agentService.getSession).not.toHaveBeenCalled();
|
||||
expect(agentService.prompt).not.toHaveBeenCalled();
|
||||
expect(harnessConversation.attach).not.toHaveBeenCalled();
|
||||
expect(harnessConversation.send).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Task-5 AMEND — embedded runtime lease lifecycle (G1) + ownership collapse (G5).
|
||||
// These drive the real EmbeddedChatRuntime directly over a shape-complete AgentService
|
||||
// fake (every touched method exists, so a RED can only come from behavior, never a
|
||||
// `getSession is not a function` TypeError). Ownership context is minted through the
|
||||
// real `ownConversation` factory — the only sanctioned way to reach a port op.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const EMBEDDED_SCOPE = { userId: USER_A.id, tenantId: USER_A.tenantId };
|
||||
const CONVERSATION_UNAVAILABLE_RESULT = {
|
||||
ok: false,
|
||||
code: 'conversation_unavailable',
|
||||
retryable: false,
|
||||
} as const;
|
||||
|
||||
/** A stream sink; `channelId` is server-derived, `onEvent` records nothing here. */
|
||||
function makeStream(): LegacyRuntimeStream {
|
||||
return { channelId: 'websocket:test-1', onEvent: vi.fn() };
|
||||
}
|
||||
|
||||
/**
|
||||
* getSession → undefined (session missing), createSession → rejects with `err`. Exercises the
|
||||
* `resolveOrCreate` collapse branch. `prompt` exists so its ABSENCE from the call record proves
|
||||
* the turn short-circuited before any dispatch.
|
||||
*/
|
||||
function makeCollapsingAgentService(err: Error) {
|
||||
return {
|
||||
getSession: vi.fn(() => undefined),
|
||||
createSession: vi.fn().mockRejectedValue(err),
|
||||
onEvent: vi.fn(() => vi.fn()),
|
||||
addChannel: vi.fn(),
|
||||
removeChannel: vi.fn(),
|
||||
prompt: vi.fn().mockResolvedValue(undefined),
|
||||
recordTokenUsage: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
/** getSession → a live owned session, so `resolveOrCreate` succeeds and a lease is built. */
|
||||
function makeLeaseAgentService() {
|
||||
const session = makeAgentSession(USER_A);
|
||||
const unsubscribe = vi.fn();
|
||||
const svc = {
|
||||
getSession: vi.fn(() => session),
|
||||
createSession: vi.fn(),
|
||||
onEvent: vi.fn(() => unsubscribe),
|
||||
addChannel: vi.fn(),
|
||||
removeChannel: vi.fn(),
|
||||
prompt: vi.fn().mockResolvedValue(undefined),
|
||||
recordTokenUsage: vi.fn(),
|
||||
};
|
||||
return { svc, unsubscribe, session };
|
||||
}
|
||||
|
||||
/**
|
||||
* getSession → a live owned session (REST resolveOrCreate succeeds), onEvent returns a `detach`
|
||||
* spy, and `prompt` REJECTS with a non-timeout error. Drives the REST-turn catch path so the single
|
||||
* idempotent teardown must clear the 120s timeout and detach the listener exactly once.
|
||||
*/
|
||||
function makeRejectingPromptAgentService() {
|
||||
const session = makeAgentSession(USER_A);
|
||||
const detach = vi.fn();
|
||||
const svc = {
|
||||
getSession: vi.fn(() => session),
|
||||
createSession: vi.fn(),
|
||||
onEvent: vi.fn(() => detach),
|
||||
addChannel: vi.fn(),
|
||||
removeChannel: vi.fn(),
|
||||
prompt: vi.fn().mockRejectedValue(new Error('agent backend exploded')),
|
||||
recordTokenUsage: vi.fn(),
|
||||
};
|
||||
return { svc, detach };
|
||||
}
|
||||
|
||||
describe('TESS Task-5 embedded ownership collapse (missing and foreign are indistinguishable, never throw)', () => {
|
||||
const ctx = ownConversation(CONVERSATION_ID, EMBEDDED_SCOPE);
|
||||
|
||||
it('collapses a foreign (Forbidden) create to conversation_unavailable and never throws', async () => {
|
||||
const svc = makeCollapsingAgentService(new ForbiddenException('foreign owner'));
|
||||
const runtime = new EmbeddedChatRuntime(svc as never);
|
||||
|
||||
const result = await runtime.completeLegacyRestTurn(ctx, { content: 'take over' });
|
||||
|
||||
expect(result).toEqual(CONVERSATION_UNAVAILABLE_RESULT);
|
||||
expect(svc.prompt).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('collapses a missing (NotFound) create to conversation_unavailable and never throws', async () => {
|
||||
const svc = makeCollapsingAgentService(new NotFoundException('no such conversation'));
|
||||
const runtime = new EmbeddedChatRuntime(svc as never);
|
||||
|
||||
const result = await runtime.completeLegacyRestTurn(ctx, { content: 'hello' });
|
||||
|
||||
expect(result).toEqual(CONVERSATION_UNAVAILABLE_RESULT);
|
||||
expect(svc.prompt).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns the IDENTICAL collapse for foreign and missing so neither can be distinguished', async () => {
|
||||
const foreign = new EmbeddedChatRuntime(
|
||||
makeCollapsingAgentService(new ForbiddenException('foreign owner')) as never,
|
||||
);
|
||||
const missing = new EmbeddedChatRuntime(
|
||||
makeCollapsingAgentService(new NotFoundException('no such conversation')) as never,
|
||||
);
|
||||
|
||||
const foreignResult = await foreign.completeLegacyRestTurn(ctx, { content: 'x' });
|
||||
const missingResult = await missing.completeLegacyRestTurn(ctx, { content: 'x' });
|
||||
|
||||
expect(foreignResult).toEqual(missingResult);
|
||||
expect(foreignResult).toEqual(CONVERSATION_UNAVAILABLE_RESULT);
|
||||
});
|
||||
});
|
||||
|
||||
describe('TESS Task-5 embedded socket lease lifecycle (one-shot dispatch, idempotent dispose, partial-setup rollback)', () => {
|
||||
const ctx = ownConversation(CONVERSATION_ID, EMBEDDED_SCOPE);
|
||||
|
||||
it('dispatches the turn exactly once; a second dispatch is a no-op turn_already_dispatched', async () => {
|
||||
const { svc } = makeLeaseAgentService();
|
||||
const runtime = new EmbeddedChatRuntime(svc as never);
|
||||
|
||||
const prepared = await runtime.prepareLegacySocketTurn(ctx, { content: 'first' }, makeStream());
|
||||
expect(prepared.ok).toBe(true);
|
||||
if (!prepared.ok) throw new Error('prepareLegacySocketTurn should succeed');
|
||||
const lease = prepared.value;
|
||||
|
||||
const first = await lease.dispatch();
|
||||
expect(first).toEqual({ ok: true, value: undefined });
|
||||
expect(svc.prompt).toHaveBeenCalledTimes(1);
|
||||
|
||||
const second = await lease.dispatch();
|
||||
expect(second).toEqual({ ok: false, code: 'turn_already_dispatched', retryable: false });
|
||||
// Zero additional effect — the second dispatch must not prompt again.
|
||||
expect(svc.prompt).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('disposes once; a second dispose is a silent no-op that never re-detaches or destroys the session', async () => {
|
||||
const { svc, unsubscribe, session } = makeLeaseAgentService();
|
||||
const runtime = new EmbeddedChatRuntime(svc as never);
|
||||
|
||||
const prepared = await runtime.prepareLegacySocketTurn(ctx, { content: 'x' }, makeStream());
|
||||
expect(prepared.ok).toBe(true);
|
||||
if (!prepared.ok) throw new Error('prepareLegacySocketTurn should succeed');
|
||||
const lease = prepared.value;
|
||||
|
||||
await lease.dispose();
|
||||
await lease.dispose();
|
||||
|
||||
// Listener + channel torn down exactly once across two dispose calls.
|
||||
expect(unsubscribe).toHaveBeenCalledTimes(1);
|
||||
expect(svc.removeChannel).toHaveBeenCalledTimes(1);
|
||||
// Disposal never terminates the underlying session or process.
|
||||
expect(session.piSession.abort).not.toHaveBeenCalled();
|
||||
expect(session.piSession.dispose).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rolls back the acquired listener and returns a total safe failure when channel attach fails mid-setup', async () => {
|
||||
const { svc, unsubscribe } = makeLeaseAgentService();
|
||||
svc.addChannel = vi.fn(() => {
|
||||
throw new Error('channel attach failed');
|
||||
});
|
||||
const runtime = new EmbeddedChatRuntime(svc as never);
|
||||
|
||||
// Must NOT throw out of the port — a partial setup collapses to a total safe failure.
|
||||
const prepared = await runtime.prepareLegacySocketTurn(ctx, { content: 'x' }, makeStream());
|
||||
expect(prepared.ok).toBe(false);
|
||||
// Exactly what was acquired (the event listener) is rolled back.
|
||||
expect(unsubscribe).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('TESS Task-5 embedded REST turn teardown (a prompt rejection frees the timer + listener exactly once)', () => {
|
||||
const ctx = ownConversation(CONVERSATION_ID, EMBEDDED_SCOPE);
|
||||
|
||||
it('clears the 120s timeout and detaches the listener exactly once when prompt() rejects, leaving no timer to reject the abandoned done-promise later (Task 5 finding 6)', async () => {
|
||||
const { svc, detach } = makeRejectingPromptAgentService();
|
||||
const runtime = new EmbeddedChatRuntime(svc as never);
|
||||
|
||||
// A rejected `done` promise firing after completeLegacyRestTurn has already returned would
|
||||
// surface as an unhandledRejection — the leak this test fences. Capture any that escape.
|
||||
const unhandled: unknown[] = [];
|
||||
const onUnhandled = (reason: unknown): void => {
|
||||
unhandled.push(reason);
|
||||
};
|
||||
process.on('unhandledRejection', onUnhandled);
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const result = await runtime.completeLegacyRestTurn(ctx, {
|
||||
content: 'trigger a backend failure',
|
||||
});
|
||||
|
||||
// The rejection collapses to a total safe failure (not a timeout) — never throws out of the port.
|
||||
expect(result).toEqual({ ok: false, code: 'operation_failed', retryable: false });
|
||||
// The single idempotent dispose ran in the catch: listener detached exactly once.
|
||||
expect(detach).toHaveBeenCalledTimes(1);
|
||||
|
||||
// dispose() cleared the REST timeout, so advancing far past it (120s) fires nothing: no second
|
||||
// detach, and — the actual leak — no live timer left to reject the now-abandoned `done` promise.
|
||||
vi.advanceTimersByTime(600_000);
|
||||
expect(detach).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
// Let any scheduled rejection surface on a real macrotask, then confirm none did.
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
process.off('unhandledRejection', onUnhandled);
|
||||
expect(unhandled).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,4 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { AgentRuntimeProviderRegistry, HermesRuntimeProvider } from '@mosaicstack/agent';
|
||||
import { AgentService } from './agent.service.js';
|
||||
import { ProviderService } from './provider.service.js';
|
||||
import { ProviderCredentialsService } from './provider-credentials.service.js';
|
||||
@@ -9,79 +8,24 @@ import { SkillLoaderService } from './skill-loader.service.js';
|
||||
import { ProvidersController } from './providers.controller.js';
|
||||
import { SessionsController } from './sessions.controller.js';
|
||||
import { AgentConfigsController } from './agent-configs.controller.js';
|
||||
import { InteractionController } from './interaction.controller.js';
|
||||
import { RoutingController } from './routing/routing.controller.js';
|
||||
import { DurableSessionRepository } from './durable-session.repository.js';
|
||||
import { DurableSessionService } from './durable-session.service.js';
|
||||
import { CoordModule } from '../coord/coord.module.js';
|
||||
import { McpClientModule } from '../mcp-client/mcp-client.module.js';
|
||||
import { SkillsModule } from '../skills/skills.module.js';
|
||||
import { GCModule } from '../gc/gc.module.js';
|
||||
import { LogModule } from '../log/log.module.js';
|
||||
import { CommandsModule } from '../commands/commands.module.js';
|
||||
import { CommandRuntimeApprovalVerifier } from '../commands/runtime-approval-verifier.js';
|
||||
import { GatewayHermesRuntimeTransport } from './hermes-runtime.transport.js';
|
||||
import { ConnectorLeaseRepository } from './connector-lease.repository.js';
|
||||
import {
|
||||
CONNECTOR_LEASE_POLICY,
|
||||
ConnectorLeaseService,
|
||||
DenyConnectorLeasePolicy,
|
||||
} from './connector-lease.service.js';
|
||||
import {
|
||||
AGENT_RUNTIME_PROVIDER_REGISTRY,
|
||||
RUNTIME_APPROVAL_VERIFIER,
|
||||
RUNTIME_PROVIDER_AUDIT_SINK,
|
||||
RuntimeProviderAuditService,
|
||||
RuntimeProviderService,
|
||||
} from './runtime-provider-registry.service.js';
|
||||
|
||||
export function createGatewayRuntimeProviderRegistry(): AgentRuntimeProviderRegistry {
|
||||
const registry = new AgentRuntimeProviderRegistry();
|
||||
registry.register(new HermesRuntimeProvider(new GatewayHermesRuntimeTransport()));
|
||||
return registry;
|
||||
}
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
imports: [CoordModule, McpClientModule, SkillsModule, GCModule, LogModule, CommandsModule],
|
||||
imports: [CoordModule, McpClientModule, SkillsModule, GCModule],
|
||||
providers: [
|
||||
ProviderService,
|
||||
ProviderCredentialsService,
|
||||
RoutingService,
|
||||
RoutingEngineService,
|
||||
SkillLoaderService,
|
||||
DurableSessionRepository,
|
||||
DurableSessionService,
|
||||
ConnectorLeaseRepository,
|
||||
DenyConnectorLeasePolicy,
|
||||
{
|
||||
provide: CONNECTOR_LEASE_POLICY,
|
||||
useExisting: DenyConnectorLeasePolicy,
|
||||
},
|
||||
ConnectorLeaseService,
|
||||
{
|
||||
provide: AGENT_RUNTIME_PROVIDER_REGISTRY,
|
||||
useFactory: createGatewayRuntimeProviderRegistry,
|
||||
},
|
||||
RuntimeProviderAuditService,
|
||||
{
|
||||
provide: RUNTIME_PROVIDER_AUDIT_SINK,
|
||||
useExisting: RuntimeProviderAuditService,
|
||||
},
|
||||
{
|
||||
provide: RUNTIME_APPROVAL_VERIFIER,
|
||||
useExisting: CommandRuntimeApprovalVerifier,
|
||||
},
|
||||
RuntimeProviderService,
|
||||
AgentService,
|
||||
],
|
||||
controllers: [
|
||||
ProvidersController,
|
||||
SessionsController,
|
||||
AgentConfigsController,
|
||||
InteractionController,
|
||||
RoutingController,
|
||||
],
|
||||
controllers: [ProvidersController, SessionsController, AgentConfigsController, RoutingController],
|
||||
exports: [
|
||||
AgentService,
|
||||
ProviderService,
|
||||
@@ -89,10 +33,6 @@ export function createGatewayRuntimeProviderRegistry(): AgentRuntimeProviderRegi
|
||||
RoutingService,
|
||||
RoutingEngineService,
|
||||
SkillLoaderService,
|
||||
DurableSessionService,
|
||||
RuntimeProviderService,
|
||||
ConnectorLeaseService,
|
||||
AGENT_RUNTIME_PROVIDER_REGISTRY,
|
||||
],
|
||||
})
|
||||
export class AgentModule {}
|
||||
|
||||
@@ -1,11 +1,4 @@
|
||||
import {
|
||||
ForbiddenException,
|
||||
Inject,
|
||||
Injectable,
|
||||
Logger,
|
||||
Optional,
|
||||
type OnModuleDestroy,
|
||||
} from '@nestjs/common';
|
||||
import { Inject, Injectable, Logger, Optional, type OnModuleDestroy } from '@nestjs/common';
|
||||
import {
|
||||
createAgentSession,
|
||||
DefaultResourceLoader,
|
||||
@@ -15,11 +8,9 @@ import {
|
||||
type ToolDefinition,
|
||||
} from '@mariozechner/pi-coding-agent';
|
||||
import type { Brain } from '@mosaicstack/brain';
|
||||
import type { ChannelAttachmentDto } from '@mosaicstack/types';
|
||||
import type { Memory, OperatorMemoryPlugin } from '@mosaicstack/memory';
|
||||
import type { Memory } from '@mosaicstack/memory';
|
||||
import { BRAIN } from '../brain/brain.tokens.js';
|
||||
import { MEMORY } from '../memory/memory.tokens.js';
|
||||
import { OPERATOR_MEMORY_PLUGIN } from '../memory/memory.module.js';
|
||||
import { EmbeddingService } from '../memory/embedding.service.js';
|
||||
import { CoordService } from '../coord/coord.service.js';
|
||||
import { ProviderService } from './provider.service.js';
|
||||
@@ -37,15 +28,12 @@ import type { SessionInfoDto, SessionMetrics } from './session.dto.js';
|
||||
import { SystemOverrideService } from '../preferences/system-override.service.js';
|
||||
import { PreferencesService } from '../preferences/preferences.service.js';
|
||||
import { SessionGCService } from '../gc/session-gc.service.js';
|
||||
import type { ActorTenantScope } from '../auth/session-scope.js';
|
||||
|
||||
/** A single message from DB conversation history, used for context injection. */
|
||||
export interface ConversationHistoryMessage {
|
||||
role: 'user' | 'assistant' | 'system';
|
||||
content: string;
|
||||
createdAt: Date;
|
||||
/** Validated, URI-referenced channel attachments preserved on session resume. */
|
||||
attachments?: readonly ChannelAttachmentDto[];
|
||||
}
|
||||
|
||||
export interface AgentSessionOptions {
|
||||
@@ -80,8 +68,6 @@ export interface AgentSessionOptions {
|
||||
agentConfigId?: string;
|
||||
/** ID of the user who owns this session. Used for preferences and system override lookups. */
|
||||
userId?: string;
|
||||
/** Server-derived tenant scope that owns this session. Falls back to userId for solo users. */
|
||||
tenantId?: string;
|
||||
/**
|
||||
* Prior conversation messages to inject as context when resuming a session.
|
||||
* These messages are formatted and prepended to the system prompt so the
|
||||
@@ -108,8 +94,6 @@ export interface AgentSession {
|
||||
allowedTools: string[] | null;
|
||||
/** User ID that owns this session, used for preference lookups. */
|
||||
userId?: string;
|
||||
/** Server-derived tenant scope that owns this session. Falls back to userId for solo users. */
|
||||
tenantId?: string;
|
||||
/** Agent config ID applied to this session, if any (M5-001). */
|
||||
agentConfigId?: string;
|
||||
/** Human-readable agent name applied to this session, if any (M5-001). */
|
||||
@@ -139,9 +123,6 @@ export class AgentService implements OnModuleDestroy {
|
||||
@Inject(PreferencesService)
|
||||
private readonly preferencesService: PreferencesService | null,
|
||||
@Inject(SessionGCService) private readonly gc: SessionGCService,
|
||||
@Optional()
|
||||
@Inject(OPERATOR_MEMORY_PLUGIN)
|
||||
private readonly operatorMemory: OperatorMemoryPlugin | null = null,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -153,7 +134,6 @@ export class AgentService implements OnModuleDestroy {
|
||||
private buildToolsForSandbox(
|
||||
sandboxDir: string,
|
||||
sessionUserId: string | undefined,
|
||||
sessionScope?: { tenantId: string; ownerId: string; sessionId: string },
|
||||
): ToolDefinition[] {
|
||||
return [
|
||||
...createBrainTools(this.brain),
|
||||
@@ -162,9 +142,6 @@ export class AgentService implements OnModuleDestroy {
|
||||
this.memory,
|
||||
this.embeddingService.available ? this.embeddingService : null,
|
||||
sessionUserId,
|
||||
this.operatorMemory && sessionScope
|
||||
? { plugin: this.operatorMemory, scope: sessionScope }
|
||||
: undefined,
|
||||
),
|
||||
...createFileTools(sandboxDir),
|
||||
...createGitTools(sandboxDir),
|
||||
@@ -197,20 +174,12 @@ export class AgentService implements OnModuleDestroy {
|
||||
.filter((t) => t.length > 0);
|
||||
}
|
||||
|
||||
async createSession(sessionId: string, options: AgentSessionOptions): Promise<AgentSession> {
|
||||
const scope = this.scopeFromOptions(options);
|
||||
async createSession(sessionId: string, options?: AgentSessionOptions): Promise<AgentSession> {
|
||||
const existing = this.sessions.get(sessionId);
|
||||
if (existing) {
|
||||
this.assertSessionScope(existing, scope);
|
||||
return existing;
|
||||
}
|
||||
if (existing) return existing;
|
||||
|
||||
const inflight = this.creating.get(sessionId);
|
||||
if (inflight) {
|
||||
const session = await inflight;
|
||||
this.assertSessionScope(session, scope);
|
||||
return session;
|
||||
}
|
||||
if (inflight) return inflight;
|
||||
|
||||
const promise = this.doCreateSession(sessionId, options).finally(() => {
|
||||
this.creating.delete(sessionId);
|
||||
@@ -239,7 +208,6 @@ export class AgentService implements OnModuleDestroy {
|
||||
isAdmin: options.isAdmin,
|
||||
agentConfigId: options.agentConfigId,
|
||||
userId: options.userId,
|
||||
tenantId: options.tenantId,
|
||||
conversationHistory: options.conversationHistory,
|
||||
};
|
||||
this.logger.log(
|
||||
@@ -279,15 +247,7 @@ export class AgentService implements OnModuleDestroy {
|
||||
}
|
||||
|
||||
// Build per-session tools scoped to the sandbox directory and authenticated user
|
||||
const sessionUserId = mergedOptions?.userId;
|
||||
const sessionTenantId = this.tenantIdFor(sessionUserId, mergedOptions?.tenantId);
|
||||
const sandboxTools = this.buildToolsForSandbox(
|
||||
sandboxDir,
|
||||
sessionUserId,
|
||||
sessionUserId && sessionTenantId
|
||||
? { tenantId: sessionTenantId, ownerId: sessionUserId, sessionId }
|
||||
: undefined,
|
||||
);
|
||||
const sandboxTools = this.buildToolsForSandbox(sandboxDir, mergedOptions?.userId);
|
||||
|
||||
// Combine static tools with dynamically discovered MCP client tools and skill tools
|
||||
const mcpTools = this.mcpClientService.getToolDefinitions();
|
||||
@@ -382,7 +342,6 @@ export class AgentService implements OnModuleDestroy {
|
||||
sandboxDir,
|
||||
allowedTools,
|
||||
userId: mergedOptions?.userId,
|
||||
tenantId: sessionTenantId,
|
||||
agentConfigId: mergedOptions?.agentConfigId,
|
||||
agentName: resolvedAgentName,
|
||||
metrics: {
|
||||
@@ -431,7 +390,7 @@ export class AgentService implements OnModuleDestroy {
|
||||
const formatMessage = (msg: ConversationHistoryMessage): string => {
|
||||
const roleLabel =
|
||||
msg.role === 'user' ? 'User' : msg.role === 'assistant' ? 'Assistant' : 'System';
|
||||
return `**${roleLabel}:** ${msg.content}${this.attachmentContext(msg.attachments ?? [])}`;
|
||||
return `**${roleLabel}:** ${msg.content}`;
|
||||
};
|
||||
|
||||
const formatted = history.map((msg) => formatMessage(msg));
|
||||
@@ -490,21 +449,6 @@ export class AgentService implements OnModuleDestroy {
|
||||
return result;
|
||||
}
|
||||
|
||||
private attachmentContext(attachments: readonly ChannelAttachmentDto[]): string {
|
||||
if (attachments.length === 0) return '';
|
||||
return `\n\n[Untrusted channel attachments]\n${attachments
|
||||
.map((attachment: ChannelAttachmentDto): string =>
|
||||
JSON.stringify({
|
||||
id: attachment.id,
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
url: attachment.url,
|
||||
...(attachment.sizeBytes !== undefined ? { sizeBytes: attachment.sizeBytes } : {}),
|
||||
}),
|
||||
)
|
||||
.join('\n')}`;
|
||||
}
|
||||
|
||||
private resolveModel(options?: AgentSessionOptions) {
|
||||
if (!options?.provider && !options?.modelId) {
|
||||
return this.providerService.getDefaultModel() ?? null;
|
||||
@@ -529,70 +473,38 @@ export class AgentService implements OnModuleDestroy {
|
||||
return this.providerService.getDefaultModel() ?? null;
|
||||
}
|
||||
|
||||
getSession(sessionId: string, scope: ActorTenantScope): AgentSession | undefined {
|
||||
const session = this.sessions.get(sessionId);
|
||||
if (!session || !this.sessionMatchesScope(session, scope)) return undefined;
|
||||
return session;
|
||||
getSession(sessionId: string): AgentSession | undefined {
|
||||
return this.sessions.get(sessionId);
|
||||
}
|
||||
|
||||
listSessions(scope: ActorTenantScope): SessionInfoDto[] {
|
||||
listSessions(): SessionInfoDto[] {
|
||||
const now = Date.now();
|
||||
return Array.from(this.sessions.values())
|
||||
.filter((s) => this.sessionMatchesScope(s, scope))
|
||||
.map((s) => this.toSessionInfo(s, now));
|
||||
return Array.from(this.sessions.values()).map((s) => ({
|
||||
id: s.id,
|
||||
provider: s.provider,
|
||||
modelId: s.modelId,
|
||||
...(s.agentName ? { agentName: s.agentName } : {}),
|
||||
createdAt: new Date(s.createdAt).toISOString(),
|
||||
promptCount: s.promptCount,
|
||||
channels: Array.from(s.channels),
|
||||
durationMs: now - s.createdAt,
|
||||
metrics: { ...s.metrics },
|
||||
}));
|
||||
}
|
||||
|
||||
listAllSessionsForSystem(): SessionInfoDto[] {
|
||||
const now = Date.now();
|
||||
return Array.from(this.sessions.values()).map((s) => this.toSessionInfo(s, now));
|
||||
}
|
||||
|
||||
getSessionInfo(sessionId: string, scope: ActorTenantScope): SessionInfoDto | undefined {
|
||||
getSessionInfo(sessionId: string): SessionInfoDto | undefined {
|
||||
const s = this.sessions.get(sessionId);
|
||||
if (!s || !this.sessionMatchesScope(s, scope)) return undefined;
|
||||
return this.toSessionInfo(s);
|
||||
}
|
||||
|
||||
private scopeFromOptions(options: AgentSessionOptions): ActorTenantScope {
|
||||
if (!options.userId) {
|
||||
throw new ForbiddenException('Session owner scope is required');
|
||||
}
|
||||
if (!s) return undefined;
|
||||
return {
|
||||
userId: options.userId,
|
||||
tenantId: this.tenantIdFor(options.userId, options.tenantId) ?? options.userId,
|
||||
};
|
||||
}
|
||||
|
||||
private tenantIdFor(
|
||||
userId: string | undefined,
|
||||
tenantId: string | undefined,
|
||||
): string | undefined {
|
||||
return tenantId ?? userId;
|
||||
}
|
||||
|
||||
private sessionMatchesScope(session: AgentSession, scope: ActorTenantScope): boolean {
|
||||
return (
|
||||
session.userId === scope.userId && (session.tenantId ?? session.userId) === scope.tenantId
|
||||
);
|
||||
}
|
||||
|
||||
private assertSessionScope(session: AgentSession, scope: ActorTenantScope): void {
|
||||
if (!this.sessionMatchesScope(session, scope)) {
|
||||
throw new ForbiddenException('Session does not belong to the current owner/tenant scope');
|
||||
}
|
||||
}
|
||||
|
||||
private toSessionInfo(session: AgentSession, now = Date.now()): SessionInfoDto {
|
||||
return {
|
||||
id: session.id,
|
||||
provider: session.provider,
|
||||
modelId: session.modelId,
|
||||
...(session.agentName ? { agentName: session.agentName } : {}),
|
||||
createdAt: new Date(session.createdAt).toISOString(),
|
||||
promptCount: session.promptCount,
|
||||
channels: Array.from(session.channels),
|
||||
durationMs: now - session.createdAt,
|
||||
metrics: { ...session.metrics },
|
||||
id: s.id,
|
||||
provider: s.provider,
|
||||
modelId: s.modelId,
|
||||
...(s.agentName ? { agentName: s.agentName } : {}),
|
||||
createdAt: new Date(s.createdAt).toISOString(),
|
||||
promptCount: s.promptCount,
|
||||
channels: Array.from(s.channels),
|
||||
durationMs: Date.now() - s.createdAt,
|
||||
metrics: { ...s.metrics },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -641,10 +553,9 @@ export class AgentService implements OnModuleDestroy {
|
||||
* not reconstructed — the model is used on the next createSession call for
|
||||
* the same conversationId when the session is torn down or a new one is created.
|
||||
*/
|
||||
updateSessionModel(sessionId: string, modelId: string, scope: ActorTenantScope): void {
|
||||
updateSessionModel(sessionId: string, modelId: string): void {
|
||||
const session = this.sessions.get(sessionId);
|
||||
if (!session) return;
|
||||
this.assertSessionScope(session, scope);
|
||||
const prev = session.modelId;
|
||||
session.modelId = modelId;
|
||||
this.recordModelSwitch(sessionId);
|
||||
@@ -661,67 +572,48 @@ export class AgentService implements OnModuleDestroy {
|
||||
sessionId: string,
|
||||
agentConfigId: string,
|
||||
agentName: string,
|
||||
scope: ActorTenantScope,
|
||||
modelId?: string,
|
||||
): void {
|
||||
const session = this.sessions.get(sessionId);
|
||||
if (!session) return;
|
||||
this.assertSessionScope(session, scope);
|
||||
session.agentConfigId = agentConfigId;
|
||||
session.agentName = agentName;
|
||||
if (modelId) {
|
||||
this.updateSessionModel(sessionId, modelId, scope);
|
||||
this.updateSessionModel(sessionId, modelId);
|
||||
}
|
||||
this.logger.log(
|
||||
`Session ${sessionId}: agent switched to "${agentName}" (${agentConfigId}) (M5-003)`,
|
||||
);
|
||||
}
|
||||
|
||||
addChannel(sessionId: string, channel: string, scope: ActorTenantScope): void {
|
||||
addChannel(sessionId: string, channel: string): void {
|
||||
const session = this.sessions.get(sessionId);
|
||||
if (!session) return;
|
||||
this.assertSessionScope(session, scope);
|
||||
session.channels.add(channel);
|
||||
if (session) {
|
||||
session.channels.add(channel);
|
||||
}
|
||||
}
|
||||
|
||||
removeChannel(sessionId: string, channel: string, scope: ActorTenantScope): void {
|
||||
removeChannel(sessionId: string, channel: string): void {
|
||||
const session = this.sessions.get(sessionId);
|
||||
if (!session) return;
|
||||
this.assertSessionScope(session, scope);
|
||||
session.channels.delete(channel);
|
||||
if (session) {
|
||||
session.channels.delete(channel);
|
||||
}
|
||||
}
|
||||
|
||||
async prompt(sessionId: string, message: string, scope: ActorTenantScope): Promise<void>;
|
||||
async prompt(
|
||||
sessionId: string,
|
||||
message: string,
|
||||
scope: ActorTenantScope,
|
||||
attachments: readonly ChannelAttachmentDto[] | undefined,
|
||||
): Promise<void>;
|
||||
async prompt(
|
||||
sessionId: string,
|
||||
message: string,
|
||||
scope: ActorTenantScope,
|
||||
attachments: readonly ChannelAttachmentDto[] = [],
|
||||
): Promise<void> {
|
||||
async prompt(sessionId: string, message: string): Promise<void> {
|
||||
const session = this.sessions.get(sessionId);
|
||||
if (!session) {
|
||||
throw new Error(`No agent session found: ${sessionId}`);
|
||||
}
|
||||
this.assertSessionScope(session, scope);
|
||||
session.promptCount += 1;
|
||||
|
||||
// Channel attachments are untrusted URI references. Preserve exact,
|
||||
// authenticated metadata for the agent without treating it as authority.
|
||||
const attachmentContext = this.attachmentContext(attachments);
|
||||
|
||||
// Prepend session-scoped system override if present (renew TTL on each turn)
|
||||
let effectiveMessage = `${message}${attachmentContext}`;
|
||||
let effectiveMessage = message;
|
||||
if (this.systemOverride) {
|
||||
const override = await this.systemOverride.get(sessionId, scope);
|
||||
const override = await this.systemOverride.get(sessionId);
|
||||
if (override) {
|
||||
effectiveMessage = `[System Override]\n${override}\n\n${effectiveMessage}`;
|
||||
await this.systemOverride.renew(sessionId, scope);
|
||||
effectiveMessage = `[System Override]\n${override}\n\n${message}`;
|
||||
await this.systemOverride.renew(sessionId);
|
||||
this.logger.debug(`Applied system override for session ${sessionId}`);
|
||||
}
|
||||
}
|
||||
@@ -737,28 +629,16 @@ export class AgentService implements OnModuleDestroy {
|
||||
}
|
||||
}
|
||||
|
||||
onEvent(
|
||||
sessionId: string,
|
||||
listener: (event: AgentSessionEvent) => void,
|
||||
scope: ActorTenantScope,
|
||||
): () => void {
|
||||
onEvent(sessionId: string, listener: (event: AgentSessionEvent) => void): () => void {
|
||||
const session = this.sessions.get(sessionId);
|
||||
if (!session) {
|
||||
throw new Error(`No agent session found: ${sessionId}`);
|
||||
}
|
||||
this.assertSessionScope(session, scope);
|
||||
session.listeners.add(listener);
|
||||
return () => session.listeners.delete(listener);
|
||||
}
|
||||
|
||||
async destroySession(sessionId: string, scope: ActorTenantScope): Promise<void> {
|
||||
const session = this.sessions.get(sessionId);
|
||||
if (!session) return;
|
||||
this.assertSessionScope(session, scope);
|
||||
await this.destroySessionForSystem(sessionId);
|
||||
}
|
||||
|
||||
private async destroySessionForSystem(sessionId: string): Promise<void> {
|
||||
async destroySession(sessionId: string): Promise<void> {
|
||||
const session = this.sessions.get(sessionId);
|
||||
if (!session) return;
|
||||
this.logger.log(`Destroying agent session ${sessionId}`);
|
||||
@@ -787,7 +667,7 @@ export class AgentService implements OnModuleDestroy {
|
||||
|
||||
async onModuleDestroy(): Promise<void> {
|
||||
this.logger.log('Shutting down all agent sessions');
|
||||
const stops = Array.from(this.sessions.keys()).map((id) => this.destroySessionForSystem(id));
|
||||
const stops = Array.from(this.sessions.keys()).map((id) => this.destroySession(id));
|
||||
const results = await Promise.allSettled(stops);
|
||||
for (const result of results) {
|
||||
if (result.status === 'rejected') {
|
||||
|
||||
@@ -1,341 +0,0 @@
|
||||
import { mkdtemp, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
import { Test, type TestingModule } from '@nestjs/testing';
|
||||
import {
|
||||
connectorLeaseAuditLog,
|
||||
createPgliteDb,
|
||||
eq,
|
||||
runPgliteMigrations,
|
||||
type DbHandle,
|
||||
} from '@mosaicstack/db';
|
||||
import type { ConnectorExecutionContext, FencedConnectorAdapter } from '@mosaicstack/types';
|
||||
import { DB } from '../database/database.module.js';
|
||||
import { ConnectorLeaseRepository } from './connector-lease.repository.js';
|
||||
import {
|
||||
CONNECTOR_LEASE_POLICY,
|
||||
ConnectorLeaseService,
|
||||
type ConnectorLeasePolicy,
|
||||
type ConnectorLeasePolicySubject,
|
||||
} from './connector-lease.service.js';
|
||||
|
||||
const authorize = vi.fn().mockResolvedValue(true);
|
||||
const policy: ConnectorLeasePolicy = { authorize };
|
||||
const context = {
|
||||
actorScope: { userId: 'operator-a', tenantId: 'tenant-a' },
|
||||
correlationId: 'correlation-acquire',
|
||||
};
|
||||
|
||||
describe('gateway connector lease fencing integration', (): void => {
|
||||
let dataDir: string;
|
||||
let handle: DbHandle;
|
||||
let moduleRef: TestingModule;
|
||||
let service: ConnectorLeaseService;
|
||||
let repository: ConnectorLeaseRepository;
|
||||
|
||||
beforeAll(async (): Promise<void> => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date('2026-07-14T17:00:00.000Z'));
|
||||
dataDir = await mkdtemp(join(tmpdir(), 'mosaic-gateway-connector-lease-'));
|
||||
handle = createPgliteDb(dataDir);
|
||||
await runPgliteMigrations(handle);
|
||||
moduleRef = await Test.createTestingModule({
|
||||
providers: [
|
||||
ConnectorLeaseRepository,
|
||||
ConnectorLeaseService,
|
||||
{ provide: DB, useValue: handle.db },
|
||||
{ provide: CONNECTOR_LEASE_POLICY, useValue: policy },
|
||||
],
|
||||
}).compile();
|
||||
service = moduleRef.get(ConnectorLeaseService);
|
||||
repository = moduleRef.get(ConnectorLeaseRepository);
|
||||
});
|
||||
|
||||
afterAll(async (): Promise<void> => {
|
||||
vi.useRealTimers();
|
||||
await moduleRef.close();
|
||||
await handle.close();
|
||||
await rm(dataDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('derives tenant authority at the gateway and validates a grant before side effects', async (): Promise<void> => {
|
||||
const lease = await service.acquire(
|
||||
{
|
||||
logicalAgentId: 'Mos',
|
||||
bindingId: 'operator-chat',
|
||||
connectorId: 'pi-worker-a',
|
||||
scopes: ['runtime.send'],
|
||||
ttlMs: 60_000,
|
||||
},
|
||||
context,
|
||||
);
|
||||
const grant = await service.issueGrant(
|
||||
{ lease, scopes: ['runtime.send'], ttlMs: 30_000 },
|
||||
{ ...context, correlationId: 'correlation-grant' },
|
||||
);
|
||||
const execute = vi.fn(async (_message: string, leaseContext: ConnectorExecutionContext) => {
|
||||
return leaseContext.leaseEpoch;
|
||||
});
|
||||
const adapter: FencedConnectorAdapter<string, string> = { execute };
|
||||
|
||||
await expect(service.executeGrant(grant, 'runtime.send', 'hello', adapter)).resolves.toBe('1');
|
||||
expect(execute).toHaveBeenCalledOnce();
|
||||
expect(authorize).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
action: 'grant.issue',
|
||||
requestedScopes: ['runtime.send'],
|
||||
requestedTtlMs: 30_000,
|
||||
}),
|
||||
);
|
||||
expect(execute.mock.calls[0]?.[1]).toMatchObject({
|
||||
identity: { tenantId: 'tenant-a', logicalAgentId: 'mos' },
|
||||
bindingId: 'operator-chat',
|
||||
connectorId: 'pi-worker-a',
|
||||
});
|
||||
});
|
||||
|
||||
it('normalizes lease-derived policy subjects before authorization', async (): Promise<void> => {
|
||||
const lease = await service.acquire(
|
||||
{
|
||||
logicalAgentId: 'mos',
|
||||
bindingId: 'operator-chat-policy',
|
||||
connectorId: 'pi-worker-a',
|
||||
scopes: ['runtime.send'],
|
||||
ttlMs: 60_000,
|
||||
},
|
||||
{ ...context, correlationId: 'correlation-policy-setup' },
|
||||
);
|
||||
const aliasedLease = {
|
||||
...lease,
|
||||
identity: { ...lease.identity, logicalAgentId: ' MOS ' },
|
||||
bindingId: ' Operator-Chat-Policy ',
|
||||
connectorId: ' PI-Worker-A ',
|
||||
scopes: [' Runtime.Send '],
|
||||
leaseEpoch: `00${lease.leaseEpoch}`,
|
||||
};
|
||||
|
||||
await service.heartbeat(aliasedLease, 30_000, {
|
||||
...context,
|
||||
correlationId: 'correlation-policy-heartbeat',
|
||||
});
|
||||
expect(authorize).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({
|
||||
action: 'lease.heartbeat',
|
||||
logicalAgentId: 'mos',
|
||||
bindingId: 'operator-chat-policy',
|
||||
connectorId: 'pi-worker-a',
|
||||
requestedScopes: ['runtime.send'],
|
||||
}),
|
||||
);
|
||||
|
||||
await service.issueGrant(
|
||||
{ lease: aliasedLease, scopes: [' Runtime.Send '], ttlMs: 1_000 },
|
||||
{ ...context, correlationId: 'correlation-policy-grant' },
|
||||
);
|
||||
expect(authorize).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({
|
||||
action: 'grant.issue',
|
||||
logicalAgentId: 'mos',
|
||||
bindingId: 'operator-chat-policy',
|
||||
connectorId: 'pi-worker-a',
|
||||
requestedScopes: ['runtime.send'],
|
||||
}),
|
||||
);
|
||||
|
||||
await service.release(aliasedLease, {
|
||||
...context,
|
||||
correlationId: 'correlation-policy-release',
|
||||
});
|
||||
expect(authorize).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({
|
||||
action: 'lease.release',
|
||||
logicalAgentId: 'mos',
|
||||
bindingId: 'operator-chat-policy',
|
||||
connectorId: 'pi-worker-a',
|
||||
requestedScopes: ['runtime.send'],
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('denies stale, forged, expired, cross-tenant, and cross-binding grants before effects', async (): Promise<void> => {
|
||||
const bindingId = 'operator-chat-denials';
|
||||
const current = await service.acquire(
|
||||
{
|
||||
logicalAgentId: 'mos',
|
||||
bindingId,
|
||||
connectorId: 'pi-worker-a',
|
||||
scopes: ['runtime.send'],
|
||||
ttlMs: 60_000,
|
||||
},
|
||||
{ ...context, correlationId: 'correlation-denial-setup' },
|
||||
);
|
||||
const stale = await service.issueGrant(
|
||||
{ lease: current, scopes: ['runtime.send'], ttlMs: 30_000 },
|
||||
{ ...context, correlationId: 'correlation-stale' },
|
||||
);
|
||||
await service.takeover(
|
||||
{
|
||||
logicalAgentId: 'mos',
|
||||
bindingId,
|
||||
connectorId: 'pi-worker-b',
|
||||
scopes: ['runtime.send'],
|
||||
ttlMs: 60_000,
|
||||
expectedEpoch: current.leaseEpoch,
|
||||
},
|
||||
{ ...context, correlationId: 'correlation-takeover' },
|
||||
);
|
||||
const adapter = { execute: vi.fn().mockResolvedValue(undefined) };
|
||||
|
||||
await expect(service.executeGrant(stale, 'runtime.send', undefined, adapter)).rejects.toThrow();
|
||||
|
||||
const active = await service.current('mos', bindingId, context);
|
||||
if (!active) throw new Error('active lease fixture is unavailable');
|
||||
const grant = await service.issueGrant(
|
||||
{ lease: active, scopes: ['runtime.send'], ttlMs: 1_000 },
|
||||
{ ...context, correlationId: 'correlation-active' },
|
||||
);
|
||||
await expect(
|
||||
service.executeGrant({ ...grant }, 'runtime.send', undefined, adapter),
|
||||
).rejects.toThrow();
|
||||
await expect(
|
||||
service.executeGrant(
|
||||
{ ...grant, bindingId: 'other-binding' },
|
||||
'runtime.send',
|
||||
undefined,
|
||||
adapter,
|
||||
),
|
||||
).rejects.toThrow();
|
||||
await expect(
|
||||
service.issueGrant(
|
||||
{ lease: active, scopes: ['runtime.send'], ttlMs: 30_000 },
|
||||
{
|
||||
actorScope: { userId: 'operator-b', tenantId: 'tenant-b' },
|
||||
correlationId: 'correlation-cross-tenant',
|
||||
},
|
||||
),
|
||||
).rejects.toThrow();
|
||||
const crossTenantAudit = await handle.db
|
||||
.select()
|
||||
.from(connectorLeaseAuditLog)
|
||||
.where(eq(connectorLeaseAuditLog.correlationId, 'correlation-cross-tenant'));
|
||||
expect(crossTenantAudit).toHaveLength(1);
|
||||
expect(crossTenantAudit[0]).toMatchObject({
|
||||
tenantId: 'tenant-b',
|
||||
logicalAgentId: 'untrusted',
|
||||
bindingId: 'untrusted',
|
||||
connectorId: 'untrusted',
|
||||
reason: 'policy_denied',
|
||||
});
|
||||
|
||||
vi.setSystemTime(new Date('2026-07-14T17:00:02.000Z'));
|
||||
await expect(service.executeGrant(grant, 'runtime.send', undefined, adapter)).rejects.toThrow();
|
||||
expect(adapter.execute).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects submitted lifecycle scopes that differ from durable authority before policy or mutation', async (): Promise<void> => {
|
||||
authorize.mockResolvedValue(true);
|
||||
const heartbeatLease = await service.acquire(
|
||||
{
|
||||
logicalAgentId: 'mos',
|
||||
bindingId: 'operator-chat-heartbeat-scope',
|
||||
connectorId: 'pi-worker-a',
|
||||
scopes: ['runtime.send'],
|
||||
ttlMs: 60_000,
|
||||
},
|
||||
{ ...context, correlationId: 'correlation-heartbeat-scope-setup' },
|
||||
);
|
||||
const releaseLease = await service.acquire(
|
||||
{
|
||||
logicalAgentId: 'mos',
|
||||
bindingId: 'operator-chat-release-scope',
|
||||
connectorId: 'pi-worker-a',
|
||||
scopes: ['runtime.send'],
|
||||
ttlMs: 60_000,
|
||||
},
|
||||
{ ...context, correlationId: 'correlation-release-scope-setup' },
|
||||
);
|
||||
const forgedHeartbeat = { ...heartbeatLease, scopes: ['tool.execute'] };
|
||||
const forgedRelease = { ...releaseLease, scopes: ['tool.execute'] };
|
||||
|
||||
authorize.mockImplementation(async (subject: ConnectorLeasePolicySubject) => {
|
||||
return subject.requestedScopes.length === 1 && subject.requestedScopes[0] === 'tool.execute';
|
||||
});
|
||||
authorize.mockClear();
|
||||
|
||||
await expect(
|
||||
service.heartbeat(forgedHeartbeat, 30_000, {
|
||||
...context,
|
||||
correlationId: 'correlation-heartbeat-scope-forgery',
|
||||
}),
|
||||
).rejects.toThrow('Connector authority policy denied');
|
||||
await expect(
|
||||
service.release(forgedRelease, {
|
||||
...context,
|
||||
correlationId: 'correlation-release-scope-forgery',
|
||||
}),
|
||||
).rejects.toThrow('Connector authority policy denied');
|
||||
expect(authorize).not.toHaveBeenCalled();
|
||||
|
||||
const currentHeartbeat = await repository.findCurrent({
|
||||
identity: heartbeatLease.identity,
|
||||
bindingId: heartbeatLease.bindingId,
|
||||
});
|
||||
const currentRelease = await repository.findCurrent({
|
||||
identity: releaseLease.identity,
|
||||
bindingId: releaseLease.bindingId,
|
||||
});
|
||||
expect(currentHeartbeat).toMatchObject({
|
||||
leaseId: heartbeatLease.leaseId,
|
||||
scopes: ['runtime.send'],
|
||||
heartbeatAt: heartbeatLease.heartbeatAt,
|
||||
expiresAt: heartbeatLease.expiresAt,
|
||||
});
|
||||
expect(currentRelease).toMatchObject({
|
||||
leaseId: releaseLease.leaseId,
|
||||
scopes: ['runtime.send'],
|
||||
});
|
||||
expect(currentRelease?.releasedAt).toBeUndefined();
|
||||
|
||||
const forgedAudits = await handle.db
|
||||
.select()
|
||||
.from(connectorLeaseAuditLog)
|
||||
.where(eq(connectorLeaseAuditLog.correlationId, 'correlation-heartbeat-scope-forgery'));
|
||||
expect(forgedAudits).toHaveLength(1);
|
||||
expect(forgedAudits[0]).toMatchObject({
|
||||
bindingId: heartbeatLease.bindingId,
|
||||
connectorId: heartbeatLease.connectorId,
|
||||
event: 'reject',
|
||||
outcome: 'denied',
|
||||
reason: 'policy_denied',
|
||||
});
|
||||
const forgedReleaseAudits = await handle.db
|
||||
.select()
|
||||
.from(connectorLeaseAuditLog)
|
||||
.where(eq(connectorLeaseAuditLog.correlationId, 'correlation-release-scope-forgery'));
|
||||
expect(forgedReleaseAudits).toHaveLength(1);
|
||||
expect(forgedReleaseAudits[0]).toMatchObject({
|
||||
bindingId: releaseLease.bindingId,
|
||||
connectorId: releaseLease.connectorId,
|
||||
event: 'reject',
|
||||
outcome: 'denied',
|
||||
reason: 'policy_denied',
|
||||
});
|
||||
|
||||
authorize.mockImplementation(async (subject: ConnectorLeasePolicySubject) => {
|
||||
return subject.requestedScopes.length === 1 && subject.requestedScopes[0] === 'runtime.send';
|
||||
});
|
||||
await expect(
|
||||
service.heartbeat(heartbeatLease, 30_000, {
|
||||
...context,
|
||||
correlationId: 'correlation-heartbeat-scope-canonical',
|
||||
}),
|
||||
).resolves.toMatchObject({ scopes: ['runtime.send'] });
|
||||
await expect(
|
||||
service.release(releaseLease, {
|
||||
...context,
|
||||
correlationId: 'correlation-release-scope-canonical',
|
||||
}),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,76 +0,0 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import {
|
||||
connectorLeaseAuditLog,
|
||||
createDb,
|
||||
eq,
|
||||
logicalAgentConnectorLeases,
|
||||
type DbHandle,
|
||||
} from '@mosaicstack/db';
|
||||
import { ConnectorLeaseCoordinator } from '@mosaicstack/agent';
|
||||
import { ConnectorLeaseRepository } from './connector-lease.repository.js';
|
||||
|
||||
const hasPostgres = Boolean(process.env['DATABASE_URL']);
|
||||
const tenantId = `lease-test-${randomUUID()}`;
|
||||
const identity = { tenantId, logicalAgentId: 'mos' } as const;
|
||||
|
||||
describe.skipIf(!hasPostgres)('ConnectorLeaseRepository real PostgreSQL integration', (): void => {
|
||||
let handle: DbHandle;
|
||||
|
||||
beforeAll((): void => {
|
||||
handle = createDb(process.env['DATABASE_URL']);
|
||||
});
|
||||
|
||||
afterAll(async (): Promise<void> => {
|
||||
if (!handle) return;
|
||||
await handle.db
|
||||
.delete(connectorLeaseAuditLog)
|
||||
.where(eq(connectorLeaseAuditLog.tenantId, tenantId));
|
||||
await handle.db
|
||||
.delete(logicalAgentConnectorLeases)
|
||||
.where(eq(logicalAgentConnectorLeases.tenantId, tenantId));
|
||||
await handle.close();
|
||||
});
|
||||
|
||||
it('preserves the exclusive CAS fence across a real pool close/reopen', async (): Promise<void> => {
|
||||
const command = {
|
||||
identity,
|
||||
bindingId: 'operator-chat',
|
||||
scopes: ['runtime.send'],
|
||||
ttlMs: 60_000,
|
||||
} as const;
|
||||
const firstCoordinator = new ConnectorLeaseCoordinator(new ConnectorLeaseRepository(handle.db));
|
||||
const contenders = await Promise.allSettled([
|
||||
firstCoordinator.acquire({
|
||||
...command,
|
||||
connectorId: 'connector-a',
|
||||
correlationId: 'postgres-acquire-a',
|
||||
}),
|
||||
firstCoordinator.acquire({
|
||||
...command,
|
||||
connectorId: 'connector-b',
|
||||
correlationId: 'postgres-acquire-b',
|
||||
}),
|
||||
]);
|
||||
const acquired = contenders.find((result) => result.status === 'fulfilled');
|
||||
if (!acquired || acquired.status !== 'fulfilled') throw new Error('no lease contender won');
|
||||
expect(contenders.filter((result) => result.status === 'fulfilled')).toHaveLength(1);
|
||||
|
||||
await handle.close();
|
||||
handle = createDb(process.env['DATABASE_URL']);
|
||||
const reopened = new ConnectorLeaseCoordinator(new ConnectorLeaseRepository(handle.db));
|
||||
const persisted = await reopened.current({ identity, bindingId: 'operator-chat' });
|
||||
expect(persisted).toMatchObject({
|
||||
leaseId: acquired.value.leaseId,
|
||||
leaseEpoch: '1',
|
||||
});
|
||||
|
||||
const takeover = await reopened.takeover({
|
||||
...command,
|
||||
connectorId: 'connector-c',
|
||||
correlationId: 'postgres-takeover',
|
||||
expectedEpoch: acquired.value.leaseEpoch,
|
||||
});
|
||||
expect(takeover).toMatchObject({ connectorId: 'connector-c', leaseEpoch: '2' });
|
||||
});
|
||||
});
|
||||
@@ -1,149 +0,0 @@
|
||||
import { mkdtemp, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import {
|
||||
connectorLeaseAuditLog,
|
||||
createPgliteDb,
|
||||
eq,
|
||||
runPgliteMigrations,
|
||||
type DbHandle,
|
||||
} from '@mosaicstack/db';
|
||||
import { ConnectorLeaseCoordinator, ConnectorLeaseError } from '@mosaicstack/agent';
|
||||
import { ConnectorLeaseRepository } from './connector-lease.repository.js';
|
||||
|
||||
const identity = { tenantId: 'tenant-a', logicalAgentId: 'mos' } as const;
|
||||
|
||||
function acquireCommand(connectorId: string, correlationId: string) {
|
||||
return {
|
||||
identity,
|
||||
bindingId: 'operator-chat',
|
||||
connectorId,
|
||||
scopes: ['runtime.send', 'tool.execute'],
|
||||
ttlMs: 60_000,
|
||||
correlationId,
|
||||
};
|
||||
}
|
||||
|
||||
describe('ConnectorLeaseRepository PostgreSQL semantics', (): void => {
|
||||
let dataDir: string;
|
||||
let handle: DbHandle;
|
||||
let now: Date;
|
||||
let coordinator: ConnectorLeaseCoordinator;
|
||||
|
||||
beforeEach(async (): Promise<void> => {
|
||||
dataDir = await mkdtemp(join(tmpdir(), 'mosaic-connector-lease-'));
|
||||
handle = createPgliteDb(dataDir);
|
||||
await runPgliteMigrations(handle);
|
||||
now = new Date('2026-07-14T17:00:00.000Z');
|
||||
coordinator = new ConnectorLeaseCoordinator(new ConnectorLeaseRepository(handle.db), {
|
||||
now: (): Date => now,
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async (): Promise<void> => {
|
||||
await handle.close();
|
||||
await rm(dataDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('allows only one concurrent contender to acquire a binding', async (): Promise<void> => {
|
||||
const outcomes = await Promise.allSettled([
|
||||
coordinator.acquire(acquireCommand('connector-a', 'correlation-a')),
|
||||
coordinator.acquire(acquireCommand('connector-b', 'correlation-b')),
|
||||
]);
|
||||
|
||||
expect(outcomes.filter((result) => result.status === 'fulfilled')).toHaveLength(1);
|
||||
const rejected = outcomes.find((result) => result.status === 'rejected');
|
||||
expect(rejected).toMatchObject({
|
||||
reason: { code: 'lease_held' } satisfies Partial<ConnectorLeaseError>,
|
||||
});
|
||||
});
|
||||
|
||||
it('uses compare-and-swap takeover and increments the fencing epoch monotonically', async (): Promise<void> => {
|
||||
const acquired = await coordinator.acquire(acquireCommand('connector-a', 'correlation-a'));
|
||||
const results = await Promise.allSettled([
|
||||
coordinator.takeover({
|
||||
...acquireCommand('connector-b', 'correlation-b'),
|
||||
expectedEpoch: acquired.leaseEpoch,
|
||||
}),
|
||||
coordinator.takeover({
|
||||
...acquireCommand('connector-c', 'correlation-c'),
|
||||
expectedEpoch: acquired.leaseEpoch,
|
||||
}),
|
||||
]);
|
||||
const winner = results.find((result) => result.status === 'fulfilled');
|
||||
|
||||
expect(results.filter((result) => result.status === 'fulfilled')).toHaveLength(1);
|
||||
expect(winner?.status === 'fulfilled' ? winner.value.leaseEpoch : null).toBe('2');
|
||||
expect(results.find((result) => result.status === 'rejected')).toMatchObject({
|
||||
reason: { code: 'cas_mismatch' } satisfies Partial<ConnectorLeaseError>,
|
||||
});
|
||||
});
|
||||
|
||||
it('heartbeats and releases only the current connector epoch', async (): Promise<void> => {
|
||||
const acquired = await coordinator.acquire(acquireCommand('connector-a', 'correlation-a'));
|
||||
now = new Date('2026-07-14T17:00:30.000Z');
|
||||
const renewed = await coordinator.heartbeat({
|
||||
lease: acquired,
|
||||
ttlMs: 120_000,
|
||||
correlationId: 'correlation-renew',
|
||||
});
|
||||
expect(renewed.expiresAt).toBe('2026-07-14T17:02:30.000Z');
|
||||
|
||||
await coordinator.release({ lease: renewed, correlationId: 'correlation-release' });
|
||||
await expect(
|
||||
coordinator.heartbeat({
|
||||
lease: renewed,
|
||||
ttlMs: 120_000,
|
||||
correlationId: 'correlation-stale',
|
||||
}),
|
||||
).rejects.toMatchObject({ code: 'lease_released' } satisfies Partial<ConnectorLeaseError>);
|
||||
});
|
||||
|
||||
it('survives close/reopen and requires CAS takeover to recover an expired lease', async (): Promise<void> => {
|
||||
const acquired = await coordinator.acquire(acquireCommand('connector-a', 'correlation-a'));
|
||||
await handle.close();
|
||||
|
||||
now = new Date('2026-07-14T17:02:00.000Z');
|
||||
handle = createPgliteDb(dataDir);
|
||||
await runPgliteMigrations(handle);
|
||||
coordinator = new ConnectorLeaseCoordinator(new ConnectorLeaseRepository(handle.db), {
|
||||
now: (): Date => now,
|
||||
});
|
||||
|
||||
await expect(
|
||||
coordinator.acquire(acquireCommand('connector-b', 'correlation-plain-acquire')),
|
||||
).rejects.toMatchObject({ code: 'takeover_required' } satisfies Partial<ConnectorLeaseError>);
|
||||
const recovered = await coordinator.takeover({
|
||||
...acquireCommand('connector-b', 'correlation-takeover'),
|
||||
expectedEpoch: acquired.leaseEpoch,
|
||||
});
|
||||
expect(recovered).toMatchObject({ connectorId: 'connector-b', leaseEpoch: '2' });
|
||||
});
|
||||
|
||||
it('writes credential-safe lifecycle and rejection audit records', async (): Promise<void> => {
|
||||
const acquired = await coordinator.acquire(acquireCommand('connector-a', 'correlation-a'));
|
||||
await coordinator.heartbeat({
|
||||
lease: acquired,
|
||||
ttlMs: 60_000,
|
||||
correlationId: 'correlation-renew',
|
||||
});
|
||||
await expect(
|
||||
coordinator.acquire(acquireCommand('connector-b', 'correlation-reject')),
|
||||
).rejects.toBeInstanceOf(ConnectorLeaseError);
|
||||
|
||||
const rows = await handle.db
|
||||
.select()
|
||||
.from(connectorLeaseAuditLog)
|
||||
.where(eq(connectorLeaseAuditLog.tenantId, identity.tenantId));
|
||||
expect(rows.map((row) => row.event)).toEqual(
|
||||
expect.arrayContaining(['acquire', 'renew', 'reject']),
|
||||
);
|
||||
const serialized = JSON.stringify(rows, (_key: string, value: unknown): unknown =>
|
||||
typeof value === 'bigint' ? value.toString(10) : value,
|
||||
);
|
||||
expect(serialized).not.toContain('tool.execute');
|
||||
expect(serialized).not.toContain('runtime.send');
|
||||
expect(serialized).not.toMatch(/token|secret|credential/i);
|
||||
});
|
||||
});
|
||||
@@ -1,354 +0,0 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import {
|
||||
and,
|
||||
connectorLeaseAuditLog,
|
||||
eq,
|
||||
gt,
|
||||
isNull,
|
||||
logicalAgentConnectorLeases,
|
||||
sql,
|
||||
type Db,
|
||||
} from '@mosaicstack/db';
|
||||
import { ConnectorLeaseError } from '@mosaicstack/agent';
|
||||
import type {
|
||||
ConnectorLease,
|
||||
ConnectorLeaseAcquireMutation,
|
||||
ConnectorLeaseAuditEvent,
|
||||
ConnectorLeaseHeartbeatMutation,
|
||||
ConnectorLeaseRejectReason,
|
||||
ConnectorLeaseReleaseMutation,
|
||||
ConnectorLeaseStore,
|
||||
ConnectorLeaseTakeoverMutation,
|
||||
LogicalAgentBinding,
|
||||
} from '@mosaicstack/types';
|
||||
import { DB } from '../database/database.module.js';
|
||||
|
||||
interface SuccessfulMutation {
|
||||
readonly ok: true;
|
||||
readonly lease: ConnectorLease;
|
||||
}
|
||||
|
||||
interface FailedMutation {
|
||||
readonly ok: false;
|
||||
readonly reason: ConnectorLeaseRejectReason;
|
||||
}
|
||||
|
||||
type MutationResult = SuccessfulMutation | FailedMutation;
|
||||
|
||||
@Injectable()
|
||||
export class ConnectorLeaseRepository implements ConnectorLeaseStore {
|
||||
constructor(@Inject(DB) private readonly db: Db) {}
|
||||
|
||||
async acquire(input: ConnectorLeaseAcquireMutation): Promise<ConnectorLease> {
|
||||
const result: MutationResult = await this.db.transaction(
|
||||
async (tx): Promise<MutationResult> => {
|
||||
const inserted = await tx
|
||||
.insert(logicalAgentConnectorLeases)
|
||||
.values({
|
||||
leaseId: input.leaseId,
|
||||
tenantId: input.identity.tenantId,
|
||||
logicalAgentId: input.identity.logicalAgentId,
|
||||
bindingId: input.bindingId,
|
||||
connectorId: input.connectorId,
|
||||
scopes: [...input.scopes],
|
||||
leaseEpoch: 1n,
|
||||
acquiredAt: new Date(input.now),
|
||||
heartbeatAt: new Date(input.now),
|
||||
expiresAt: new Date(input.expiresAt),
|
||||
updatedAt: new Date(input.now),
|
||||
})
|
||||
.onConflictDoNothing()
|
||||
.returning();
|
||||
const row = inserted[0];
|
||||
if (row) {
|
||||
const lease = toLease(row);
|
||||
await insertAudit(tx, lifecycleAudit(input, lease, 'acquire'));
|
||||
return { ok: true, lease };
|
||||
}
|
||||
|
||||
const current = await findRow(tx, input);
|
||||
if (current && current.expiresAt <= new Date(input.now) && !current.releasedAt) {
|
||||
await insertAudit(tx, lifecycleAudit(input, toLease(current), 'expiry'));
|
||||
}
|
||||
const reason: ConnectorLeaseRejectReason =
|
||||
current && (current.releasedAt || current.expiresAt <= new Date(input.now))
|
||||
? 'takeover_required'
|
||||
: 'lease_held';
|
||||
await insertAudit(tx, rejectionAudit(input, current ? toLease(current) : null, reason));
|
||||
return { ok: false, reason };
|
||||
},
|
||||
);
|
||||
return unwrap(result);
|
||||
}
|
||||
|
||||
async takeover(input: ConnectorLeaseTakeoverMutation): Promise<ConnectorLease> {
|
||||
const result: MutationResult = await this.db.transaction(
|
||||
async (tx): Promise<MutationResult> => {
|
||||
const current = await findRow(tx, input);
|
||||
if (!current || current.leaseEpoch.toString(10) !== input.expectedEpoch) {
|
||||
await insertAudit(
|
||||
tx,
|
||||
rejectionAudit(input, current ? toLease(current) : null, 'cas_mismatch'),
|
||||
);
|
||||
return { ok: false, reason: 'cas_mismatch' };
|
||||
}
|
||||
if (current.expiresAt <= new Date(input.now) && !current.releasedAt) {
|
||||
await insertAudit(tx, lifecycleAudit(input, toLease(current), 'expiry'));
|
||||
}
|
||||
const updated = await tx
|
||||
.update(logicalAgentConnectorLeases)
|
||||
.set({
|
||||
leaseId: input.leaseId,
|
||||
connectorId: input.connectorId,
|
||||
scopes: [...input.scopes],
|
||||
leaseEpoch: sql`${logicalAgentConnectorLeases.leaseEpoch} + 1`,
|
||||
acquiredAt: new Date(input.now),
|
||||
heartbeatAt: new Date(input.now),
|
||||
expiresAt: new Date(input.expiresAt),
|
||||
releasedAt: null,
|
||||
updatedAt: new Date(input.now),
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
bindingPredicate(input),
|
||||
eq(logicalAgentConnectorLeases.leaseId, current.leaseId),
|
||||
eq(logicalAgentConnectorLeases.leaseEpoch, BigInt(input.expectedEpoch)),
|
||||
),
|
||||
)
|
||||
.returning();
|
||||
const row = updated[0];
|
||||
if (!row) {
|
||||
await insertAudit(tx, rejectionAudit(input, toLease(current), 'cas_mismatch'));
|
||||
return { ok: false, reason: 'cas_mismatch' };
|
||||
}
|
||||
const lease = toLease(row);
|
||||
await insertAudit(tx, lifecycleAudit(input, lease, 'takeover'));
|
||||
return { ok: true, lease };
|
||||
},
|
||||
);
|
||||
return unwrap(result);
|
||||
}
|
||||
|
||||
async heartbeat(input: ConnectorLeaseHeartbeatMutation): Promise<ConnectorLease> {
|
||||
const result: MutationResult = await this.db.transaction(
|
||||
async (tx): Promise<MutationResult> => {
|
||||
const updated = await tx
|
||||
.update(logicalAgentConnectorLeases)
|
||||
.set({
|
||||
heartbeatAt: new Date(input.now),
|
||||
expiresAt: new Date(input.expiresAt),
|
||||
updatedAt: new Date(input.now),
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
bindingPredicate(input.lease),
|
||||
eq(logicalAgentConnectorLeases.leaseId, input.lease.leaseId),
|
||||
eq(logicalAgentConnectorLeases.connectorId, input.lease.connectorId),
|
||||
eq(logicalAgentConnectorLeases.leaseEpoch, BigInt(input.lease.leaseEpoch)),
|
||||
isNull(logicalAgentConnectorLeases.releasedAt),
|
||||
gt(logicalAgentConnectorLeases.expiresAt, new Date(input.now)),
|
||||
),
|
||||
)
|
||||
.returning();
|
||||
const row = updated[0];
|
||||
if (row) {
|
||||
const lease = toLease(row);
|
||||
await insertAudit(tx, lifecycleAudit(input, lease, 'renew'));
|
||||
return { ok: true, lease };
|
||||
}
|
||||
const current = await findRow(tx, input.lease);
|
||||
const reason = classifyAuthorityFailure(
|
||||
current ? toLease(current) : null,
|
||||
input.lease,
|
||||
input.now,
|
||||
);
|
||||
if (reason === 'lease_expired' && current) {
|
||||
await insertAudit(tx, lifecycleAudit(input, toLease(current), 'expiry'));
|
||||
}
|
||||
await insertAudit(
|
||||
tx,
|
||||
rejectionAudit(
|
||||
{ ...input.lease, correlationId: input.correlationId, now: input.now },
|
||||
current ? toLease(current) : null,
|
||||
reason,
|
||||
),
|
||||
);
|
||||
return { ok: false, reason };
|
||||
},
|
||||
);
|
||||
return unwrap(result);
|
||||
}
|
||||
|
||||
async release(input: ConnectorLeaseReleaseMutation): Promise<void> {
|
||||
const result: MutationResult = await this.db.transaction(
|
||||
async (tx): Promise<MutationResult> => {
|
||||
const updated = await tx
|
||||
.update(logicalAgentConnectorLeases)
|
||||
.set({
|
||||
releasedAt: new Date(input.now),
|
||||
expiresAt: new Date(input.now),
|
||||
updatedAt: new Date(input.now),
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
bindingPredicate(input.lease),
|
||||
eq(logicalAgentConnectorLeases.leaseId, input.lease.leaseId),
|
||||
eq(logicalAgentConnectorLeases.connectorId, input.lease.connectorId),
|
||||
eq(logicalAgentConnectorLeases.leaseEpoch, BigInt(input.lease.leaseEpoch)),
|
||||
isNull(logicalAgentConnectorLeases.releasedAt),
|
||||
gt(logicalAgentConnectorLeases.expiresAt, new Date(input.now)),
|
||||
),
|
||||
)
|
||||
.returning();
|
||||
const row = updated[0];
|
||||
if (row) {
|
||||
const lease = toLease(row);
|
||||
await insertAudit(tx, lifecycleAudit(input, lease, 'release'));
|
||||
return { ok: true, lease };
|
||||
}
|
||||
const current = await findRow(tx, input.lease);
|
||||
const reason = classifyAuthorityFailure(
|
||||
current ? toLease(current) : null,
|
||||
input.lease,
|
||||
input.now,
|
||||
);
|
||||
if (reason === 'lease_expired' && current) {
|
||||
await insertAudit(tx, lifecycleAudit(input, toLease(current), 'expiry'));
|
||||
}
|
||||
await insertAudit(
|
||||
tx,
|
||||
rejectionAudit(
|
||||
{ ...input.lease, correlationId: input.correlationId, now: input.now },
|
||||
current ? toLease(current) : null,
|
||||
reason,
|
||||
),
|
||||
);
|
||||
return { ok: false, reason };
|
||||
},
|
||||
);
|
||||
unwrap(result);
|
||||
}
|
||||
|
||||
async findCurrent(binding: LogicalAgentBinding): Promise<ConnectorLease | null> {
|
||||
const row = await findRow(this.db, binding);
|
||||
return row ? toLease(row) : null;
|
||||
}
|
||||
|
||||
async recordAudit(event: ConnectorLeaseAuditEvent): Promise<void> {
|
||||
await insertAudit(this.db, event);
|
||||
}
|
||||
}
|
||||
|
||||
function unwrap(result: MutationResult): ConnectorLease {
|
||||
if (!result.ok) throw new ConnectorLeaseError(result.reason, safeErrorMessage(result.reason));
|
||||
return result.lease;
|
||||
}
|
||||
|
||||
function safeErrorMessage(reason: ConnectorLeaseRejectReason): string {
|
||||
return `Connector lease mutation denied: ${reason}`;
|
||||
}
|
||||
|
||||
function bindingPredicate(binding: LogicalAgentBinding) {
|
||||
return and(
|
||||
eq(logicalAgentConnectorLeases.tenantId, binding.identity.tenantId),
|
||||
eq(logicalAgentConnectorLeases.logicalAgentId, binding.identity.logicalAgentId),
|
||||
eq(logicalAgentConnectorLeases.bindingId, binding.bindingId),
|
||||
);
|
||||
}
|
||||
|
||||
async function findRow(
|
||||
db: Pick<Db, 'select'>,
|
||||
binding: LogicalAgentBinding,
|
||||
): Promise<typeof logicalAgentConnectorLeases.$inferSelect | null> {
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(logicalAgentConnectorLeases)
|
||||
.where(bindingPredicate(binding))
|
||||
.limit(1);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
function toLease(row: typeof logicalAgentConnectorLeases.$inferSelect): ConnectorLease {
|
||||
return Object.freeze({
|
||||
identity: Object.freeze({ tenantId: row.tenantId, logicalAgentId: row.logicalAgentId }),
|
||||
bindingId: row.bindingId,
|
||||
leaseId: row.leaseId,
|
||||
connectorId: row.connectorId,
|
||||
scopes: Object.freeze([...row.scopes]),
|
||||
leaseEpoch: row.leaseEpoch.toString(10),
|
||||
acquiredAt: row.acquiredAt.toISOString(),
|
||||
heartbeatAt: row.heartbeatAt.toISOString(),
|
||||
expiresAt: row.expiresAt.toISOString(),
|
||||
...(row.releasedAt ? { releasedAt: row.releasedAt.toISOString() } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function classifyAuthorityFailure(
|
||||
current: ConnectorLease | null,
|
||||
claimed: ConnectorLease,
|
||||
now: string,
|
||||
): ConnectorLeaseRejectReason {
|
||||
if (!current) return 'lease_missing';
|
||||
if (current.releasedAt) return 'lease_released';
|
||||
if (new Date(current.expiresAt) <= new Date(now)) return 'lease_expired';
|
||||
if (current.leaseEpoch !== claimed.leaseEpoch) return 'stale_epoch';
|
||||
return 'connector_mismatch';
|
||||
}
|
||||
|
||||
function lifecycleAudit(
|
||||
input: { readonly correlationId: string; readonly now: string },
|
||||
lease: ConnectorLease,
|
||||
event: Exclude<ConnectorLeaseAuditEvent['event'], 'reject'>,
|
||||
): ConnectorLeaseAuditEvent {
|
||||
return {
|
||||
identity: lease.identity,
|
||||
bindingId: lease.bindingId,
|
||||
connectorId: lease.connectorId,
|
||||
leaseId: lease.leaseId,
|
||||
leaseEpoch: lease.leaseEpoch,
|
||||
event,
|
||||
outcome: 'succeeded',
|
||||
correlationId: input.correlationId,
|
||||
occurredAt: input.now,
|
||||
};
|
||||
}
|
||||
|
||||
function rejectionAudit(
|
||||
input: {
|
||||
readonly identity: ConnectorLease['identity'];
|
||||
readonly bindingId: string;
|
||||
readonly connectorId: string;
|
||||
readonly correlationId: string;
|
||||
readonly now: string;
|
||||
},
|
||||
current: ConnectorLease | null,
|
||||
reason: ConnectorLeaseRejectReason,
|
||||
): ConnectorLeaseAuditEvent {
|
||||
return {
|
||||
identity: input.identity,
|
||||
bindingId: input.bindingId,
|
||||
connectorId: input.connectorId,
|
||||
event: 'reject',
|
||||
outcome: 'denied',
|
||||
correlationId: input.correlationId,
|
||||
occurredAt: input.now,
|
||||
...(current ? { leaseId: current.leaseId, leaseEpoch: current.leaseEpoch } : {}),
|
||||
reason,
|
||||
};
|
||||
}
|
||||
|
||||
async function insertAudit(db: Pick<Db, 'insert'>, event: ConnectorLeaseAuditEvent): Promise<void> {
|
||||
await db.insert(connectorLeaseAuditLog).values({
|
||||
tenantId: event.identity.tenantId,
|
||||
logicalAgentId: event.identity.logicalAgentId,
|
||||
bindingId: event.bindingId,
|
||||
connectorId: event.connectorId,
|
||||
...(event.leaseId ? { leaseId: event.leaseId } : {}),
|
||||
...(event.leaseEpoch ? { leaseEpoch: BigInt(event.leaseEpoch) } : {}),
|
||||
event: event.event,
|
||||
outcome: event.outcome,
|
||||
...(event.reason ? { reason: event.reason } : {}),
|
||||
correlationId: event.correlationId,
|
||||
occurredAt: new Date(event.occurredAt),
|
||||
});
|
||||
}
|
||||
@@ -1,285 +0,0 @@
|
||||
import { ForbiddenException, Inject, Injectable } from '@nestjs/common';
|
||||
import { ConnectorLeaseCoordinator, normalizeConnectorLease } from '@mosaicstack/agent';
|
||||
import {
|
||||
normalizeConnectorId,
|
||||
normalizeConnectorScopes,
|
||||
normalizeCorrelationId,
|
||||
normalizeLogicalAgentIdentity,
|
||||
normalizeLogicalBindingId,
|
||||
type AcquireConnectorLeaseInput,
|
||||
type ConnectorExecutionGrant,
|
||||
type ConnectorLease,
|
||||
type ConnectorLeaseAuditEvent,
|
||||
type FencedConnectorAdapter,
|
||||
} from '@mosaicstack/types';
|
||||
import type { ActorTenantScope } from '../auth/session-scope.js';
|
||||
import { ConnectorLeaseRepository } from './connector-lease.repository.js';
|
||||
|
||||
export const CONNECTOR_LEASE_POLICY = Symbol('CONNECTOR_LEASE_POLICY');
|
||||
|
||||
export type ConnectorLeasePolicyAction =
|
||||
| 'lease.acquire'
|
||||
| 'lease.takeover'
|
||||
| 'lease.heartbeat'
|
||||
| 'lease.release'
|
||||
| 'lease.read'
|
||||
| 'grant.issue';
|
||||
|
||||
export interface ConnectorLeaseRequestContext {
|
||||
readonly actorScope: ActorTenantScope;
|
||||
readonly correlationId: string;
|
||||
}
|
||||
|
||||
export interface GatewayConnectorLeaseRequest {
|
||||
readonly logicalAgentId: string;
|
||||
readonly bindingId: string;
|
||||
readonly connectorId: string;
|
||||
readonly scopes: readonly string[];
|
||||
readonly ttlMs: number;
|
||||
}
|
||||
|
||||
export interface GatewayConnectorLeaseTakeoverRequest extends GatewayConnectorLeaseRequest {
|
||||
readonly expectedEpoch: string;
|
||||
}
|
||||
|
||||
export interface GatewayConnectorGrantRequest {
|
||||
readonly lease: ConnectorLease;
|
||||
readonly scopes: readonly string[];
|
||||
readonly ttlMs: number;
|
||||
}
|
||||
|
||||
export interface ConnectorLeasePolicySubject {
|
||||
readonly action: ConnectorLeasePolicyAction;
|
||||
readonly actorId: string;
|
||||
readonly tenantId: string;
|
||||
readonly logicalAgentId: string;
|
||||
readonly bindingId: string;
|
||||
readonly connectorId: string;
|
||||
readonly requestedScopes: readonly string[];
|
||||
readonly requestedTtlMs: number | null;
|
||||
}
|
||||
|
||||
export interface ConnectorLeasePolicy {
|
||||
authorize(subject: ConnectorLeasePolicySubject): Promise<boolean>;
|
||||
}
|
||||
|
||||
/** M1 has no concrete cutover policy: unconfigured production use fails closed. */
|
||||
@Injectable()
|
||||
export class DenyConnectorLeasePolicy implements ConnectorLeasePolicy {
|
||||
async authorize(_subject: ConnectorLeasePolicySubject): Promise<boolean> {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Gateway-owned policy surface for durable connector authority and fenced effects. */
|
||||
@Injectable()
|
||||
export class ConnectorLeaseService {
|
||||
private readonly coordinator: ConnectorLeaseCoordinator;
|
||||
|
||||
constructor(
|
||||
@Inject(ConnectorLeaseRepository) private readonly repository: ConnectorLeaseRepository,
|
||||
@Inject(CONNECTOR_LEASE_POLICY) private readonly policy: ConnectorLeasePolicy,
|
||||
) {
|
||||
this.coordinator = new ConnectorLeaseCoordinator(repository);
|
||||
}
|
||||
|
||||
async acquire(
|
||||
request: GatewayConnectorLeaseRequest,
|
||||
context: ConnectorLeaseRequestContext,
|
||||
): Promise<ConnectorLease> {
|
||||
const command = this.command(request, context);
|
||||
await this.assertPolicy('lease.acquire', command, context, command.scopes, command.ttlMs);
|
||||
return this.coordinator.acquire({ ...command, correlationId: this.correlation(context) });
|
||||
}
|
||||
|
||||
async takeover(
|
||||
request: GatewayConnectorLeaseTakeoverRequest,
|
||||
context: ConnectorLeaseRequestContext,
|
||||
): Promise<ConnectorLease> {
|
||||
const command = this.command(request, context);
|
||||
await this.assertPolicy('lease.takeover', command, context, command.scopes, command.ttlMs);
|
||||
return this.coordinator.takeover({
|
||||
...command,
|
||||
expectedEpoch: request.expectedEpoch,
|
||||
correlationId: this.correlation(context),
|
||||
});
|
||||
}
|
||||
|
||||
async heartbeat(
|
||||
lease: ConnectorLease,
|
||||
ttlMs: number,
|
||||
context: ConnectorLeaseRequestContext,
|
||||
): Promise<ConnectorLease> {
|
||||
const normalizedLease = normalizeConnectorLease(lease);
|
||||
const durableLease = await this.durableLifecycleLease(normalizedLease, context);
|
||||
await this.assertPolicy('lease.heartbeat', durableLease, context, durableLease.scopes, ttlMs);
|
||||
return this.coordinator.heartbeat({
|
||||
lease: durableLease,
|
||||
ttlMs,
|
||||
correlationId: this.correlation(context),
|
||||
});
|
||||
}
|
||||
|
||||
async release(lease: ConnectorLease, context: ConnectorLeaseRequestContext): Promise<void> {
|
||||
const normalizedLease = normalizeConnectorLease(lease);
|
||||
const durableLease = await this.durableLifecycleLease(normalizedLease, context);
|
||||
await this.assertPolicy('lease.release', durableLease, context, durableLease.scopes, null);
|
||||
await this.coordinator.release({
|
||||
lease: durableLease,
|
||||
correlationId: this.correlation(context),
|
||||
});
|
||||
}
|
||||
|
||||
async current(
|
||||
logicalAgentId: string,
|
||||
bindingId: string,
|
||||
context: ConnectorLeaseRequestContext,
|
||||
): Promise<ConnectorLease | null> {
|
||||
const binding = {
|
||||
identity: normalizeLogicalAgentIdentity({
|
||||
tenantId: context.actorScope.tenantId,
|
||||
logicalAgentId,
|
||||
}),
|
||||
bindingId: normalizeLogicalBindingId(bindingId),
|
||||
connectorId: 'gateway',
|
||||
};
|
||||
await this.assertPolicy('lease.read', binding, context, [], null);
|
||||
return this.coordinator.current(binding);
|
||||
}
|
||||
|
||||
async issueGrant(
|
||||
request: GatewayConnectorGrantRequest,
|
||||
context: ConnectorLeaseRequestContext,
|
||||
): Promise<ConnectorExecutionGrant> {
|
||||
const lease = normalizeConnectorLease(request.lease);
|
||||
await this.assertTenant(lease, context);
|
||||
const scopes = normalizeConnectorScopes(request.scopes);
|
||||
await this.assertPolicy('grant.issue', lease, context, scopes, request.ttlMs);
|
||||
return this.coordinator.issueGrant({
|
||||
lease,
|
||||
scopes,
|
||||
ttlMs: request.ttlMs,
|
||||
correlationId: this.correlation(context),
|
||||
});
|
||||
}
|
||||
|
||||
async executeGrant<TInput, TOutput>(
|
||||
grant: ConnectorExecutionGrant,
|
||||
requiredScope: string,
|
||||
input: TInput,
|
||||
adapter: FencedConnectorAdapter<TInput, TOutput>,
|
||||
): Promise<TOutput> {
|
||||
return this.coordinator.executeGrant(grant, requiredScope, input, adapter);
|
||||
}
|
||||
|
||||
private command(
|
||||
request: GatewayConnectorLeaseRequest,
|
||||
context: ConnectorLeaseRequestContext,
|
||||
): Omit<AcquireConnectorLeaseInput, 'correlationId'> {
|
||||
return {
|
||||
identity: normalizeLogicalAgentIdentity({
|
||||
tenantId: context.actorScope.tenantId,
|
||||
logicalAgentId: request.logicalAgentId,
|
||||
}),
|
||||
bindingId: normalizeLogicalBindingId(request.bindingId),
|
||||
connectorId: normalizeConnectorId(request.connectorId),
|
||||
scopes: normalizeConnectorScopes(request.scopes),
|
||||
ttlMs: request.ttlMs,
|
||||
};
|
||||
}
|
||||
|
||||
private async assertTenant(
|
||||
lease: Pick<ConnectorLease, 'identity' | 'bindingId' | 'connectorId'>,
|
||||
context: ConnectorLeaseRequestContext,
|
||||
): Promise<void> {
|
||||
if (lease.identity.tenantId !== context.actorScope.tenantId) {
|
||||
await this.recordPolicyDenial(
|
||||
{
|
||||
identity: {
|
||||
tenantId: context.actorScope.tenantId,
|
||||
logicalAgentId: 'untrusted',
|
||||
},
|
||||
bindingId: 'untrusted',
|
||||
connectorId: 'untrusted',
|
||||
},
|
||||
context,
|
||||
);
|
||||
throw new ForbiddenException('Connector authority tenant scope denied');
|
||||
}
|
||||
}
|
||||
|
||||
private async durableLifecycleLease(
|
||||
submittedLease: ConnectorLease,
|
||||
context: ConnectorLeaseRequestContext,
|
||||
): Promise<ConnectorLease> {
|
||||
await this.assertTenant(submittedLease, context);
|
||||
const durableLease = await this.coordinator.current(submittedLease);
|
||||
if (!durableLease || !hasSameLifecycleAuthority(submittedLease, durableLease)) {
|
||||
await this.recordPolicyDenial(durableLease ?? submittedLease, context);
|
||||
throw new ForbiddenException('Connector authority policy denied');
|
||||
}
|
||||
return durableLease;
|
||||
}
|
||||
|
||||
private async assertPolicy(
|
||||
action: ConnectorLeasePolicyAction,
|
||||
subject: Pick<ConnectorLease, 'identity' | 'bindingId' | 'connectorId'>,
|
||||
context: ConnectorLeaseRequestContext,
|
||||
requestedScopes: readonly string[],
|
||||
requestedTtlMs: number | null,
|
||||
): Promise<void> {
|
||||
const allowed = await this.policy.authorize({
|
||||
action,
|
||||
actorId: context.actorScope.userId,
|
||||
tenantId: subject.identity.tenantId,
|
||||
logicalAgentId: subject.identity.logicalAgentId,
|
||||
bindingId: subject.bindingId,
|
||||
connectorId: subject.connectorId,
|
||||
requestedScopes: Object.freeze([...requestedScopes]),
|
||||
requestedTtlMs,
|
||||
});
|
||||
if (!allowed) {
|
||||
await this.recordPolicyDenial(subject, context);
|
||||
throw new ForbiddenException('Connector authority policy denied');
|
||||
}
|
||||
}
|
||||
|
||||
private async recordPolicyDenial(
|
||||
subject: Pick<ConnectorLease, 'identity' | 'bindingId' | 'connectorId'>,
|
||||
context: ConnectorLeaseRequestContext,
|
||||
): Promise<void> {
|
||||
const event: ConnectorLeaseAuditEvent = {
|
||||
identity: subject.identity,
|
||||
bindingId: subject.bindingId,
|
||||
connectorId: subject.connectorId,
|
||||
event: 'reject',
|
||||
outcome: 'denied',
|
||||
reason: 'policy_denied',
|
||||
correlationId: this.correlation(context),
|
||||
occurredAt: new Date().toISOString(),
|
||||
};
|
||||
await this.repository.recordAudit(event);
|
||||
}
|
||||
|
||||
private correlation(context: ConnectorLeaseRequestContext): string {
|
||||
return normalizeCorrelationId(context.correlationId);
|
||||
}
|
||||
}
|
||||
|
||||
function hasSameLifecycleAuthority(
|
||||
submittedLease: ConnectorLease,
|
||||
durableLease: ConnectorLease,
|
||||
): boolean {
|
||||
return (
|
||||
submittedLease.identity.tenantId === durableLease.identity.tenantId &&
|
||||
submittedLease.identity.logicalAgentId === durableLease.identity.logicalAgentId &&
|
||||
submittedLease.bindingId === durableLease.bindingId &&
|
||||
submittedLease.leaseId === durableLease.leaseId &&
|
||||
submittedLease.connectorId === durableLease.connectorId &&
|
||||
submittedLease.leaseEpoch === durableLease.leaseEpoch &&
|
||||
submittedLease.scopes.length === durableLease.scopes.length &&
|
||||
submittedLease.scopes.every((scope: string, index: number): boolean => {
|
||||
return scope === durableLease.scopes[index];
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
import type { RuntimeProviderRequestContext } from './runtime-provider-registry.service.js';
|
||||
|
||||
/** Server-side request for a replay-safe provider message. */
|
||||
export interface ProviderOutboxDto {
|
||||
sessionId: string;
|
||||
idempotencyKey: string;
|
||||
correlationId: string;
|
||||
content: string;
|
||||
context: RuntimeProviderRequestContext;
|
||||
}
|
||||
@@ -1,416 +0,0 @@
|
||||
import { mkdtempSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { eq, sql, interactionCheckpoints, interactionInbox } from '@mosaicstack/db';
|
||||
import { DurableSessionCoordinator, type DurableSessionIdentity } from '@mosaicstack/agent';
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createPgliteDb, runPgliteMigrations, type DbHandle } from '@mosaicstack/db';
|
||||
import { DurableSessionRepository } from './durable-session.repository.js';
|
||||
import { DurableSessionService } from './durable-session.service.js';
|
||||
|
||||
const IDENTITY: DurableSessionIdentity = {
|
||||
agentName: 'Nova',
|
||||
sessionId: 'tess-pglite-session',
|
||||
tenantId: 'tenant-pglite',
|
||||
ownerId: 'tess-owner',
|
||||
providerId: 'fleet',
|
||||
runtimeSessionId: 'nova',
|
||||
};
|
||||
|
||||
describe('DurableSessionRepository', () => {
|
||||
let dataDir: string | undefined;
|
||||
let handle: DbHandle;
|
||||
let previousAuthSecret: string | undefined;
|
||||
|
||||
beforeAll(async (): Promise<void> => {
|
||||
previousAuthSecret = process.env['BETTER_AUTH_SECRET'];
|
||||
process.env['BETTER_AUTH_SECRET'] = 'tess-durable-state-test-sealing-key';
|
||||
dataDir = mkdtempSync(join(tmpdir(), 'tess-durable-state-'));
|
||||
handle = createPgliteDb(dataDir);
|
||||
await runPgliteMigrations(handle);
|
||||
await seedOwner(handle);
|
||||
}, 30_000);
|
||||
|
||||
beforeEach(async (): Promise<void> => {
|
||||
await handle.db.execute(sql`DELETE FROM interaction_handoffs`);
|
||||
await handle.db.execute(sql`DELETE FROM interaction_checkpoints`);
|
||||
await handle.db.execute(sql`DELETE FROM interaction_inbox`);
|
||||
await handle.db.execute(sql`DELETE FROM interaction_outbox`);
|
||||
await handle.db.execute(sql`DELETE FROM interaction_sessions`);
|
||||
});
|
||||
|
||||
afterAll(async (): Promise<void> => {
|
||||
await handle.close();
|
||||
if (dataDir) rmSync(dataDir, { recursive: true, force: true });
|
||||
if (previousAuthSecret === undefined) delete process.env['BETTER_AUTH_SECRET'];
|
||||
else process.env['BETTER_AUTH_SECRET'] = previousAuthSecret;
|
||||
});
|
||||
|
||||
it('survives a full PGlite close/reopen mid-session without duplicate inbox or outbox side effects', async () => {
|
||||
const beforeRestart = new DurableSessionCoordinator(new DurableSessionRepository(handle.db));
|
||||
await beforeRestart.create(IDENTITY);
|
||||
await beforeRestart.receive({
|
||||
sessionId: IDENTITY.sessionId,
|
||||
idempotencyKey: 'inbox-before-kill',
|
||||
correlationId: 'correlation-before-kill',
|
||||
content: 'resume after a kill',
|
||||
});
|
||||
await beforeRestart.enqueueOutbox({
|
||||
sessionId: IDENTITY.sessionId,
|
||||
idempotencyKey: 'outbox-before-kill',
|
||||
correlationId: 'correlation-before-kill',
|
||||
channelId: 'cli',
|
||||
kind: 'provider.send',
|
||||
content: 'one response only',
|
||||
});
|
||||
await beforeRestart.checkpoint({
|
||||
sessionId: IDENTITY.sessionId,
|
||||
checkpointId: 'checkpoint-before-kill',
|
||||
cursor: 'cursor-before-kill',
|
||||
summary: 'restart-safe state',
|
||||
compactionEpoch: 1,
|
||||
});
|
||||
await beforeRestart.handoff({
|
||||
sessionId: IDENTITY.sessionId,
|
||||
handoffId: 'handoff-before-kill',
|
||||
destination: 'mos',
|
||||
correlationId: 'correlation-before-kill',
|
||||
checkpointId: 'checkpoint-before-kill',
|
||||
status: 'pending',
|
||||
});
|
||||
await beforeRestart.checkpoint({
|
||||
sessionId: IDENTITY.sessionId,
|
||||
checkpointId: 'checkpoint-after-handoff',
|
||||
cursor: 'cursor-after-handoff',
|
||||
summary: 'newer state cannot strand the portable handoff',
|
||||
compactionEpoch: 2,
|
||||
});
|
||||
|
||||
await handle.close();
|
||||
handle = createPgliteDb(dataDir!);
|
||||
|
||||
const afterRestart = new DurableSessionCoordinator(new DurableSessionRepository(handle.db));
|
||||
const recovered = await afterRestart.recover(IDENTITY.sessionId);
|
||||
const resumedHandoff = await afterRestart.resumeHandoff('handoff-before-kill');
|
||||
const handled: string[] = [];
|
||||
const effects: string[] = [];
|
||||
|
||||
await afterRestart.drainInbox(IDENTITY.sessionId, async (entry): Promise<void> => {
|
||||
handled.push(entry.idempotencyKey);
|
||||
});
|
||||
await afterRestart.dispatchOutbox(IDENTITY.sessionId, async (entry): Promise<void> => {
|
||||
effects.push(entry.idempotencyKey);
|
||||
});
|
||||
await afterRestart.drainInbox(IDENTITY.sessionId, async (entry): Promise<void> => {
|
||||
handled.push(entry.idempotencyKey);
|
||||
});
|
||||
await afterRestart.dispatchOutbox(IDENTITY.sessionId, async (entry): Promise<void> => {
|
||||
effects.push(entry.idempotencyKey);
|
||||
});
|
||||
|
||||
expect(recovered.identity).toEqual(IDENTITY);
|
||||
expect(recovered.checkpoint).toMatchObject({ checkpointId: 'checkpoint-after-handoff' });
|
||||
expect(recovered.handoffs).toMatchObject([{ handoffId: 'handoff-before-kill' }]);
|
||||
expect(resumedHandoff.checkpoint).toMatchObject({ checkpointId: 'checkpoint-before-kill' });
|
||||
expect(handled).toEqual(['inbox-before-kill']);
|
||||
expect(effects).toEqual(['outbox-before-kill']);
|
||||
}, 30_000);
|
||||
|
||||
it('redacts sensitive durable payloads before persistence', async () => {
|
||||
const coordinator = new DurableSessionCoordinator(new DurableSessionRepository(handle.db));
|
||||
await coordinator.create(IDENTITY);
|
||||
await coordinator.receive({
|
||||
sessionId: IDENTITY.sessionId,
|
||||
idempotencyKey: 'redacted-inbox',
|
||||
correlationId: 'correlation-redaction',
|
||||
content: 'api_key=super-secret-canary',
|
||||
});
|
||||
await coordinator.enqueueOutbox({
|
||||
sessionId: IDENTITY.sessionId,
|
||||
idempotencyKey: 'redacted-outbox',
|
||||
correlationId: 'correlation-redaction',
|
||||
channelId: 'cli',
|
||||
kind: 'provider.send',
|
||||
content: 'email [email protected] api_key=super-secret-canary',
|
||||
});
|
||||
await coordinator.checkpoint({
|
||||
sessionId: IDENTITY.sessionId,
|
||||
checkpointId: 'redacted-checkpoint',
|
||||
cursor: 'bearer super-secret-canary',
|
||||
summary: 'email [email protected]',
|
||||
compactionEpoch: 0,
|
||||
});
|
||||
|
||||
const snapshot = await coordinator.snapshot(IDENTITY.sessionId);
|
||||
const [persisted] = await handle.db
|
||||
.select({ content: interactionInbox.content })
|
||||
.from(interactionInbox)
|
||||
.where(eq(interactionInbox.idempotencyKey, 'redacted-inbox'));
|
||||
|
||||
expect(JSON.stringify(snapshot)).not.toContain('super-secret-canary');
|
||||
expect(JSON.stringify(snapshot)).not.toContain('[email protected]');
|
||||
expect(persisted?.content).not.toContain('super-secret-canary');
|
||||
expect(persisted?.content).not.toContain('[REDACTED]');
|
||||
}, 30_000);
|
||||
|
||||
it('fails closed when the configured idempotency secret is unavailable', async () => {
|
||||
const coordinator = new DurableSessionCoordinator(new DurableSessionRepository(handle.db));
|
||||
await coordinator.create(IDENTITY);
|
||||
const secret = process.env['BETTER_AUTH_SECRET'];
|
||||
delete process.env['BETTER_AUTH_SECRET'];
|
||||
try {
|
||||
await expect(
|
||||
coordinator.receive({
|
||||
sessionId: IDENTITY.sessionId,
|
||||
idempotencyKey: 'requires-idempotency-secret',
|
||||
correlationId: 'correlation-secret',
|
||||
content: 'sensitive payload',
|
||||
}),
|
||||
).rejects.toThrow(/required for durable idempotency digests/);
|
||||
} finally {
|
||||
if (secret === undefined) delete process.env['BETTER_AUTH_SECRET'];
|
||||
else process.env['BETTER_AUTH_SECRET'] = secret;
|
||||
}
|
||||
}, 30_000);
|
||||
|
||||
it('uses keyed pre-redaction digests to reject distinct sensitive checkpoint payloads', async () => {
|
||||
const coordinator = new DurableSessionCoordinator(new DurableSessionRepository(handle.db));
|
||||
await coordinator.create(IDENTITY);
|
||||
const input = {
|
||||
sessionId: IDENTITY.sessionId,
|
||||
checkpointId: 'checkpoint-secret-conflict',
|
||||
cursor: 'api_key=secret-one',
|
||||
summary: 'bearer secret-one',
|
||||
compactionEpoch: 1,
|
||||
};
|
||||
await coordinator.checkpoint(input);
|
||||
|
||||
await expect(
|
||||
coordinator.checkpoint({
|
||||
...input,
|
||||
cursor: 'api_key=secret-two',
|
||||
summary: 'bearer secret-two',
|
||||
}),
|
||||
).rejects.toThrow(/checkpoint identity conflict/);
|
||||
|
||||
const [persisted] = await handle.db
|
||||
.select({
|
||||
digest: interactionCheckpoints.contentDigest,
|
||||
cursor: interactionCheckpoints.cursor,
|
||||
})
|
||||
.from(interactionCheckpoints)
|
||||
.where(eq(interactionCheckpoints.checkpointId, input.checkpointId));
|
||||
expect(persisted?.cursor).not.toContain('secret-one');
|
||||
expect(persisted?.digest).not.toBe(
|
||||
createHash('sha256')
|
||||
.update(JSON.stringify([input.cursor, input.summary]))
|
||||
.digest('hex'),
|
||||
);
|
||||
|
||||
await coordinator.checkpoint({
|
||||
...input,
|
||||
checkpointId: 'checkpoint-delimiter-conflict',
|
||||
cursor: 'a\u0000b',
|
||||
summary: 'c',
|
||||
});
|
||||
await expect(
|
||||
coordinator.checkpoint({
|
||||
...input,
|
||||
checkpointId: 'checkpoint-delimiter-conflict',
|
||||
cursor: 'a',
|
||||
summary: 'b\u0000c',
|
||||
}),
|
||||
).rejects.toThrow(/checkpoint identity conflict/);
|
||||
}, 30_000);
|
||||
|
||||
it('rejects distinct sensitive inbox and outbox payloads under reused idempotency keys', async () => {
|
||||
const coordinator = new DurableSessionCoordinator(new DurableSessionRepository(handle.db));
|
||||
await coordinator.create(IDENTITY);
|
||||
const inbox = {
|
||||
sessionId: IDENTITY.sessionId,
|
||||
idempotencyKey: 'inbox-secret-conflict',
|
||||
correlationId: 'correlation-inbox-secret',
|
||||
content: 'api_key=secret-one',
|
||||
};
|
||||
const outbox = {
|
||||
sessionId: IDENTITY.sessionId,
|
||||
idempotencyKey: 'outbox-secret-conflict',
|
||||
correlationId: 'correlation-outbox-secret',
|
||||
channelId: 'cli',
|
||||
kind: 'provider.send',
|
||||
content: 'api_key=secret-one',
|
||||
};
|
||||
await coordinator.receive(inbox);
|
||||
await coordinator.enqueueOutbox(outbox);
|
||||
|
||||
await expect(coordinator.receive({ ...inbox, content: 'api_key=secret-two' })).rejects.toThrow(
|
||||
/idempotency conflict/,
|
||||
);
|
||||
await expect(
|
||||
coordinator.enqueueOutbox({ ...outbox, content: 'api_key=secret-two' }),
|
||||
).rejects.toThrow(/idempotency conflict/);
|
||||
}, 30_000);
|
||||
|
||||
it('rejects database inbox and outbox idempotency-key conflicts', async () => {
|
||||
const coordinator = new DurableSessionCoordinator(new DurableSessionRepository(handle.db));
|
||||
await coordinator.create(IDENTITY);
|
||||
await coordinator.receive({
|
||||
sessionId: IDENTITY.sessionId,
|
||||
idempotencyKey: 'inbox-conflict',
|
||||
correlationId: 'correlation-inbox',
|
||||
content: 'original inbox',
|
||||
});
|
||||
await coordinator.enqueueOutbox({
|
||||
sessionId: IDENTITY.sessionId,
|
||||
idempotencyKey: 'outbox-conflict',
|
||||
correlationId: 'correlation-outbox',
|
||||
channelId: 'cli',
|
||||
kind: 'provider.send',
|
||||
content: 'original outbox',
|
||||
});
|
||||
|
||||
await expect(
|
||||
coordinator.receive({
|
||||
sessionId: IDENTITY.sessionId,
|
||||
idempotencyKey: 'inbox-conflict',
|
||||
correlationId: 'forged-correlation',
|
||||
content: 'original inbox',
|
||||
}),
|
||||
).rejects.toThrow(/idempotency conflict/);
|
||||
await expect(
|
||||
coordinator.enqueueOutbox({
|
||||
sessionId: IDENTITY.sessionId,
|
||||
idempotencyKey: 'outbox-conflict',
|
||||
correlationId: 'correlation-outbox',
|
||||
channelId: 'forged-channel',
|
||||
kind: 'provider.send',
|
||||
content: 'original outbox',
|
||||
}),
|
||||
).rejects.toThrow(/idempotency conflict/);
|
||||
}, 30_000);
|
||||
|
||||
it('does not requeue a live outbox claim during a normal scoped dispatch', async () => {
|
||||
const repository = new DurableSessionRepository(handle.db);
|
||||
const coordinator = new DurableSessionCoordinator(repository);
|
||||
const runtimeProviders = { sendMessage: vi.fn().mockResolvedValue(undefined) };
|
||||
const service = new DurableSessionService(repository, runtimeProviders as never);
|
||||
const input = {
|
||||
sessionId: IDENTITY.sessionId,
|
||||
idempotencyKey: 'live-effect',
|
||||
correlationId: 'correlation-live',
|
||||
content: 'must not duplicate',
|
||||
context: {
|
||||
actorScope: { userId: IDENTITY.ownerId, tenantId: IDENTITY.tenantId },
|
||||
channelId: 'cli',
|
||||
correlationId: 'correlation-live',
|
||||
},
|
||||
};
|
||||
|
||||
await coordinator.create(IDENTITY);
|
||||
await service.queueProviderSend(input);
|
||||
expect(await repository.claimOutbox(IDENTITY.sessionId)).toMatchObject({
|
||||
status: 'processing',
|
||||
});
|
||||
|
||||
await service.dispatchProviderOutbox(IDENTITY.sessionId, input);
|
||||
await expect(
|
||||
service.recoverProviderSession(IDENTITY.sessionId, {
|
||||
...input,
|
||||
context: {
|
||||
...input.context,
|
||||
actorScope: { userId: 'intruder', tenantId: 'tenant-pglite' },
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow(/scope or correlation mismatch/);
|
||||
|
||||
expect(runtimeProviders.sendMessage).not.toHaveBeenCalled();
|
||||
expect(await coordinator.snapshot(IDENTITY.sessionId)).toMatchObject({
|
||||
outbox: [{ idempotencyKey: 'live-effect', status: 'processing' }],
|
||||
});
|
||||
}, 30_000);
|
||||
|
||||
it('rejects an outbox correlation mismatch before claiming the pending effect', async () => {
|
||||
const repository = new DurableSessionRepository(handle.db);
|
||||
const coordinator = new DurableSessionCoordinator(repository);
|
||||
const runtimeProviders = { sendMessage: vi.fn().mockResolvedValue(undefined) };
|
||||
const service = new DurableSessionService(repository, runtimeProviders as never);
|
||||
const input = {
|
||||
sessionId: IDENTITY.sessionId,
|
||||
idempotencyKey: 'mismatch-effect',
|
||||
correlationId: 'correlation-expected',
|
||||
content: 'must remain pending',
|
||||
context: {
|
||||
actorScope: { userId: IDENTITY.ownerId, tenantId: IDENTITY.tenantId },
|
||||
channelId: 'cli',
|
||||
correlationId: 'correlation-expected',
|
||||
},
|
||||
};
|
||||
|
||||
await coordinator.create(IDENTITY);
|
||||
await service.queueProviderSend(input);
|
||||
await expect(
|
||||
service.dispatchProviderOutbox(IDENTITY.sessionId, {
|
||||
...input,
|
||||
correlationId: 'correlation-forged',
|
||||
context: { ...input.context, correlationId: 'correlation-forged' },
|
||||
}),
|
||||
).rejects.toThrow(/scope or correlation mismatch/);
|
||||
|
||||
expect(runtimeProviders.sendMessage).not.toHaveBeenCalled();
|
||||
expect(await coordinator.snapshot(IDENTITY.sessionId)).toMatchObject({
|
||||
outbox: [{ idempotencyKey: 'mismatch-effect', status: 'pending' }],
|
||||
});
|
||||
}, 30_000);
|
||||
|
||||
it('dispatches only the outbox record bound to the supplied correlation and channel', async () => {
|
||||
const repository = new DurableSessionRepository(handle.db);
|
||||
const coordinator = new DurableSessionCoordinator(repository);
|
||||
const runtimeProviders = { sendMessage: vi.fn().mockResolvedValue(undefined) };
|
||||
const service = new DurableSessionService(repository, runtimeProviders as never);
|
||||
const first = {
|
||||
sessionId: IDENTITY.sessionId,
|
||||
idempotencyKey: 'scoped-effect-one',
|
||||
correlationId: 'correlation-one',
|
||||
content: 'first result',
|
||||
context: {
|
||||
actorScope: { userId: IDENTITY.ownerId, tenantId: IDENTITY.tenantId },
|
||||
channelId: 'cli',
|
||||
correlationId: 'correlation-one',
|
||||
},
|
||||
};
|
||||
const second = {
|
||||
...first,
|
||||
idempotencyKey: 'scoped-effect-two',
|
||||
correlationId: 'correlation-two',
|
||||
content: 'second result',
|
||||
context: { ...first.context, correlationId: 'correlation-two' },
|
||||
};
|
||||
|
||||
await coordinator.create(IDENTITY);
|
||||
await service.queueProviderSend(first);
|
||||
await service.queueProviderSend(second);
|
||||
await service.dispatchProviderOutbox(IDENTITY.sessionId, first);
|
||||
|
||||
expect(runtimeProviders.sendMessage).toHaveBeenCalledTimes(1);
|
||||
expect(runtimeProviders.sendMessage).toHaveBeenCalledWith(
|
||||
IDENTITY.providerId,
|
||||
IDENTITY.runtimeSessionId,
|
||||
{ content: 'first result', idempotencyKey: 'scoped-effect-one' },
|
||||
first.context,
|
||||
);
|
||||
expect(await coordinator.snapshot(IDENTITY.sessionId)).toMatchObject({
|
||||
outbox: [
|
||||
{ idempotencyKey: 'scoped-effect-one', status: 'delivered' },
|
||||
{ idempotencyKey: 'scoped-effect-two', status: 'pending' },
|
||||
],
|
||||
});
|
||||
}, 30_000);
|
||||
});
|
||||
|
||||
async function seedOwner(handle: DbHandle): Promise<void> {
|
||||
await handle.db.execute(sql`
|
||||
INSERT INTO users (id, name, email, email_verified, created_at, updated_at)
|
||||
VALUES ('tess-owner', 'Tess Owner', '[email protected]', false, now(), now())
|
||||
`);
|
||||
}
|
||||
@@ -1,529 +0,0 @@
|
||||
import { createHash, createHmac } from 'node:crypto';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import {
|
||||
and,
|
||||
asc,
|
||||
desc,
|
||||
eq,
|
||||
interactionCheckpoints,
|
||||
interactionHandoffs,
|
||||
interactionInbox,
|
||||
interactionOutbox,
|
||||
interactionSessions,
|
||||
type Db,
|
||||
} from '@mosaicstack/db';
|
||||
import { seal, unseal } from '@mosaicstack/auth';
|
||||
import { redactSensitiveContent } from '@mosaicstack/log';
|
||||
import type {
|
||||
DurableCheckpoint,
|
||||
DurableCheckpointInput,
|
||||
DurableEnqueueResult,
|
||||
DurableHandoff,
|
||||
DurableHandoffInput,
|
||||
DurableInboxEntry,
|
||||
DurableInboxInput,
|
||||
DurableInboxStatus,
|
||||
DurableOutboxEntry,
|
||||
DurableOutboxInput,
|
||||
DurableOutboxStatus,
|
||||
DurableSessionIdentity,
|
||||
DurableSessionSnapshot,
|
||||
DurableSessionStore,
|
||||
} from '@mosaicstack/agent';
|
||||
import { DB } from '../database/database.module.js';
|
||||
|
||||
@Injectable()
|
||||
export class DurableSessionRepository implements DurableSessionStore {
|
||||
constructor(@Inject(DB) private readonly db: Db) {}
|
||||
|
||||
async create(identity: DurableSessionIdentity): Promise<void> {
|
||||
await this.db
|
||||
.insert(interactionSessions)
|
||||
.values({
|
||||
id: identity.sessionId,
|
||||
agentName: identity.agentName,
|
||||
tenantId: identity.tenantId,
|
||||
ownerId: identity.ownerId,
|
||||
providerId: identity.providerId,
|
||||
runtimeSessionId: identity.runtimeSessionId,
|
||||
})
|
||||
.onConflictDoNothing();
|
||||
|
||||
const existing = await this.session(identity.sessionId);
|
||||
if (!existing || !sameEnrollmentScope(existing, identity)) {
|
||||
throw new Error(`Durable session identity conflict: ${identity.sessionId}`);
|
||||
}
|
||||
// A recovered/re-enrolled runtime can receive a new provider session ID;
|
||||
// the conversation handle and owner scope remain immutable.
|
||||
if (
|
||||
existing.providerId !== identity.providerId ||
|
||||
existing.runtimeSessionId !== identity.runtimeSessionId
|
||||
) {
|
||||
await this.db
|
||||
.update(interactionSessions)
|
||||
.set({ providerId: identity.providerId, runtimeSessionId: identity.runtimeSessionId })
|
||||
.where(eq(interactionSessions.id, identity.sessionId));
|
||||
}
|
||||
}
|
||||
|
||||
async snapshot(sessionId: string): Promise<DurableSessionSnapshot | null> {
|
||||
const identity = await this.session(sessionId);
|
||||
if (!identity) return null;
|
||||
|
||||
const [inbox, outbox, checkpoints, handoffs] = await Promise.all([
|
||||
this.db
|
||||
.select()
|
||||
.from(interactionInbox)
|
||||
.where(eq(interactionInbox.sessionId, sessionId))
|
||||
.orderBy(asc(interactionInbox.createdAt)),
|
||||
this.db
|
||||
.select()
|
||||
.from(interactionOutbox)
|
||||
.where(eq(interactionOutbox.sessionId, sessionId))
|
||||
.orderBy(asc(interactionOutbox.createdAt)),
|
||||
this.db
|
||||
.select()
|
||||
.from(interactionCheckpoints)
|
||||
.where(eq(interactionCheckpoints.sessionId, sessionId))
|
||||
.orderBy(
|
||||
desc(interactionCheckpoints.compactionEpoch),
|
||||
desc(interactionCheckpoints.createdAt),
|
||||
)
|
||||
.limit(1),
|
||||
this.db
|
||||
.select()
|
||||
.from(interactionHandoffs)
|
||||
.where(eq(interactionHandoffs.sessionId, sessionId))
|
||||
.orderBy(asc(interactionHandoffs.createdAt)),
|
||||
]);
|
||||
|
||||
const checkpoint = checkpoints[0];
|
||||
return {
|
||||
identity,
|
||||
inbox: inbox.map(toInbox),
|
||||
outbox: outbox.map(toOutbox),
|
||||
...(checkpoint ? { checkpoint: toCheckpoint(checkpoint) } : {}),
|
||||
handoffs: handoffs.map(toHandoff),
|
||||
};
|
||||
}
|
||||
|
||||
async enqueueInbox(input: DurableInboxInput): Promise<DurableEnqueueResult<DurableInboxStatus>> {
|
||||
const digest = contentDigest(input.content);
|
||||
const record: DurableInboxInput = {
|
||||
...input,
|
||||
content: redactSensitiveContent(input.content).content,
|
||||
};
|
||||
const inserted = await this.db
|
||||
.insert(interactionInbox)
|
||||
.values({
|
||||
...record,
|
||||
content: seal(record.content),
|
||||
contentDigest: digest,
|
||||
status: 'pending',
|
||||
})
|
||||
.onConflictDoNothing()
|
||||
.returning({ status: interactionInbox.status });
|
||||
if (inserted[0]) return { accepted: true, status: inserted[0].status };
|
||||
|
||||
const existing = await this.db
|
||||
.select()
|
||||
.from(interactionInbox)
|
||||
.where(
|
||||
and(
|
||||
eq(interactionInbox.sessionId, input.sessionId),
|
||||
eq(interactionInbox.idempotencyKey, input.idempotencyKey),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
if (!existing[0]) throw new Error(`Durable inbox enqueue failed: ${input.idempotencyKey}`);
|
||||
const entry = toInbox(existing[0]);
|
||||
if (
|
||||
!sameInbox(entry, record) ||
|
||||
!matchesContentDigest(existing[0].contentDigest, input.content)
|
||||
) {
|
||||
throw new Error(`Durable inbox idempotency conflict: ${input.idempotencyKey}`);
|
||||
}
|
||||
return { accepted: false, status: entry.status };
|
||||
}
|
||||
|
||||
async claimInbox(sessionId: string): Promise<DurableInboxEntry | null> {
|
||||
for (let attempt = 0; attempt < 3; attempt += 1) {
|
||||
const candidate = await this.db
|
||||
.select()
|
||||
.from(interactionInbox)
|
||||
.where(
|
||||
and(eq(interactionInbox.sessionId, sessionId), eq(interactionInbox.status, 'pending')),
|
||||
)
|
||||
.orderBy(asc(interactionInbox.createdAt))
|
||||
.limit(1);
|
||||
const entry = candidate[0];
|
||||
if (!entry) return null;
|
||||
const claimed = await this.db
|
||||
.update(interactionInbox)
|
||||
.set({ status: 'processing', updatedAt: new Date() })
|
||||
.where(and(eq(interactionInbox.id, entry.id), eq(interactionInbox.status, 'pending')))
|
||||
.returning();
|
||||
if (claimed[0]) return toInbox(claimed[0]);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async completeInbox(sessionId: string, idempotencyKey: string): Promise<void> {
|
||||
await this.db
|
||||
.update(interactionInbox)
|
||||
.set({ status: 'processed', updatedAt: new Date() })
|
||||
.where(
|
||||
and(
|
||||
eq(interactionInbox.sessionId, sessionId),
|
||||
eq(interactionInbox.idempotencyKey, idempotencyKey),
|
||||
eq(interactionInbox.status, 'processing'),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async releaseInbox(sessionId: string, idempotencyKey: string): Promise<void> {
|
||||
await this.db
|
||||
.update(interactionInbox)
|
||||
.set({ status: 'pending', updatedAt: new Date() })
|
||||
.where(
|
||||
and(
|
||||
eq(interactionInbox.sessionId, sessionId),
|
||||
eq(interactionInbox.idempotencyKey, idempotencyKey),
|
||||
eq(interactionInbox.status, 'processing'),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async enqueueOutbox(
|
||||
input: DurableOutboxInput,
|
||||
): Promise<DurableEnqueueResult<DurableOutboxStatus>> {
|
||||
const digest = contentDigest(input.content);
|
||||
const record: DurableOutboxInput = {
|
||||
...input,
|
||||
content: redactSensitiveContent(input.content).content,
|
||||
};
|
||||
const inserted = await this.db
|
||||
.insert(interactionOutbox)
|
||||
.values({
|
||||
...record,
|
||||
content: seal(record.content),
|
||||
contentDigest: digest,
|
||||
status: 'pending',
|
||||
})
|
||||
.onConflictDoNothing()
|
||||
.returning({ status: interactionOutbox.status });
|
||||
if (inserted[0]) return { accepted: true, status: inserted[0].status };
|
||||
|
||||
const existing = await this.db
|
||||
.select()
|
||||
.from(interactionOutbox)
|
||||
.where(
|
||||
and(
|
||||
eq(interactionOutbox.sessionId, input.sessionId),
|
||||
eq(interactionOutbox.idempotencyKey, input.idempotencyKey),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
if (!existing[0]) throw new Error(`Durable outbox enqueue failed: ${input.idempotencyKey}`);
|
||||
const entry = toOutbox(existing[0]);
|
||||
if (
|
||||
!sameOutbox(entry, record) ||
|
||||
!matchesContentDigest(existing[0].contentDigest, input.content)
|
||||
) {
|
||||
throw new Error(`Durable outbox idempotency conflict: ${input.idempotencyKey}`);
|
||||
}
|
||||
return { accepted: false, status: entry.status };
|
||||
}
|
||||
|
||||
async claimOutbox(sessionId: string): Promise<DurableOutboxEntry | null> {
|
||||
for (let attempt = 0; attempt < 3; attempt += 1) {
|
||||
const candidate = await this.db
|
||||
.select()
|
||||
.from(interactionOutbox)
|
||||
.where(
|
||||
and(eq(interactionOutbox.sessionId, sessionId), eq(interactionOutbox.status, 'pending')),
|
||||
)
|
||||
.orderBy(asc(interactionOutbox.createdAt))
|
||||
.limit(1);
|
||||
const entry = candidate[0];
|
||||
if (!entry) return null;
|
||||
const claimed = await this.db
|
||||
.update(interactionOutbox)
|
||||
.set({ status: 'processing', updatedAt: new Date() })
|
||||
.where(and(eq(interactionOutbox.id, entry.id), eq(interactionOutbox.status, 'pending')))
|
||||
.returning();
|
||||
if (claimed[0]) return toOutbox(claimed[0]);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async claimOutboxByKey(
|
||||
sessionId: string,
|
||||
idempotencyKey: string,
|
||||
): Promise<DurableOutboxEntry | null> {
|
||||
const claimed = await this.db
|
||||
.update(interactionOutbox)
|
||||
.set({ status: 'processing', updatedAt: new Date() })
|
||||
.where(
|
||||
and(
|
||||
eq(interactionOutbox.sessionId, sessionId),
|
||||
eq(interactionOutbox.idempotencyKey, idempotencyKey),
|
||||
eq(interactionOutbox.status, 'pending'),
|
||||
),
|
||||
)
|
||||
.returning();
|
||||
return claimed[0] ? toOutbox(claimed[0]) : null;
|
||||
}
|
||||
|
||||
async completeOutbox(sessionId: string, idempotencyKey: string): Promise<void> {
|
||||
await this.db
|
||||
.update(interactionOutbox)
|
||||
.set({ status: 'delivered', updatedAt: new Date() })
|
||||
.where(
|
||||
and(
|
||||
eq(interactionOutbox.sessionId, sessionId),
|
||||
eq(interactionOutbox.idempotencyKey, idempotencyKey),
|
||||
eq(interactionOutbox.status, 'processing'),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async releaseOutbox(sessionId: string, idempotencyKey: string): Promise<void> {
|
||||
await this.db
|
||||
.update(interactionOutbox)
|
||||
.set({ status: 'pending', updatedAt: new Date() })
|
||||
.where(
|
||||
and(
|
||||
eq(interactionOutbox.sessionId, sessionId),
|
||||
eq(interactionOutbox.idempotencyKey, idempotencyKey),
|
||||
eq(interactionOutbox.status, 'processing'),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async checkpoint(input: DurableCheckpointInput): Promise<void> {
|
||||
// Compute identity before redaction. The persisted digest is keyed so a database
|
||||
// reader cannot use it as an offline oracle for sensitive cursor/summary values.
|
||||
const digest = contentDigest(JSON.stringify([input.cursor, input.summary]));
|
||||
const checkpoint: DurableCheckpointInput = {
|
||||
...input,
|
||||
cursor: redactSensitiveContent(input.cursor).content,
|
||||
summary: redactSensitiveContent(input.summary).content,
|
||||
};
|
||||
const inserted = await this.db
|
||||
.insert(interactionCheckpoints)
|
||||
.values({
|
||||
...checkpoint,
|
||||
contentDigest: digest,
|
||||
cursor: seal(checkpoint.cursor),
|
||||
summary: seal(checkpoint.summary),
|
||||
})
|
||||
.onConflictDoNothing()
|
||||
.returning({ checkpointId: interactionCheckpoints.checkpointId });
|
||||
if (inserted[0]) return;
|
||||
|
||||
const existing = await this.db
|
||||
.select()
|
||||
.from(interactionCheckpoints)
|
||||
.where(
|
||||
and(
|
||||
eq(interactionCheckpoints.sessionId, input.sessionId),
|
||||
eq(interactionCheckpoints.checkpointId, input.checkpointId),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
if (
|
||||
!existing[0] ||
|
||||
!sameCheckpoint(toCheckpoint(existing[0]), checkpoint) ||
|
||||
!matchesCheckpointDigest(existing[0].contentDigest, digest)
|
||||
) {
|
||||
throw new Error(`Durable checkpoint identity conflict: ${input.checkpointId}`);
|
||||
}
|
||||
}
|
||||
|
||||
async findCheckpoint(sessionId: string, checkpointId: string): Promise<DurableCheckpoint | null> {
|
||||
const checkpoints = await this.db
|
||||
.select()
|
||||
.from(interactionCheckpoints)
|
||||
.where(
|
||||
and(
|
||||
eq(interactionCheckpoints.sessionId, sessionId),
|
||||
eq(interactionCheckpoints.checkpointId, checkpointId),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
const checkpoint = checkpoints[0];
|
||||
return checkpoint ? toCheckpoint(checkpoint) : null;
|
||||
}
|
||||
|
||||
async handoff(input: DurableHandoffInput): Promise<void> {
|
||||
const checkpoint = await this.findCheckpoint(input.sessionId, input.checkpointId);
|
||||
if (!checkpoint) {
|
||||
throw new Error(`Durable handoff checkpoint is unavailable: ${input.checkpointId}`);
|
||||
}
|
||||
const inserted = await this.db
|
||||
.insert(interactionHandoffs)
|
||||
.values({ ...input })
|
||||
.onConflictDoNothing()
|
||||
.returning({ handoffId: interactionHandoffs.handoffId });
|
||||
if (inserted[0]) return;
|
||||
|
||||
const existing = await this.findHandoff(input.handoffId);
|
||||
if (!existing || !sameHandoff(existing, input)) {
|
||||
throw new Error(`Durable handoff identity conflict: ${input.handoffId}`);
|
||||
}
|
||||
}
|
||||
|
||||
async findHandoff(handoffId: string): Promise<DurableHandoff | null> {
|
||||
const handoffs = await this.db
|
||||
.select()
|
||||
.from(interactionHandoffs)
|
||||
.where(eq(interactionHandoffs.handoffId, handoffId))
|
||||
.limit(1);
|
||||
const handoff = handoffs[0];
|
||||
return handoff ? toHandoff(handoff) : null;
|
||||
}
|
||||
|
||||
async requeueInFlight(sessionId: string): Promise<void> {
|
||||
// Inbox handlers are process-local work. A provider outbox claim may have
|
||||
// reached an external target before a crash, so it is deliberately not
|
||||
// replayed by generic recovery.
|
||||
await this.db
|
||||
.update(interactionInbox)
|
||||
.set({ status: 'pending', updatedAt: new Date() })
|
||||
.where(
|
||||
and(eq(interactionInbox.sessionId, sessionId), eq(interactionInbox.status, 'processing')),
|
||||
);
|
||||
}
|
||||
|
||||
private async session(sessionId: string): Promise<DurableSessionIdentity | null> {
|
||||
const sessions = await this.db
|
||||
.select()
|
||||
.from(interactionSessions)
|
||||
.where(eq(interactionSessions.id, sessionId))
|
||||
.limit(1);
|
||||
const session = sessions[0];
|
||||
return session
|
||||
? {
|
||||
agentName: session.agentName,
|
||||
sessionId: session.id,
|
||||
tenantId: session.tenantId,
|
||||
ownerId: session.ownerId,
|
||||
providerId: session.providerId,
|
||||
runtimeSessionId: session.runtimeSessionId,
|
||||
}
|
||||
: null;
|
||||
}
|
||||
}
|
||||
|
||||
function contentDigest(content: string): string {
|
||||
const secret = process.env['BETTER_AUTH_SECRET'];
|
||||
if (!secret) {
|
||||
throw new Error('BETTER_AUTH_SECRET is required for durable idempotency digests');
|
||||
}
|
||||
return `hmac:v1:${createHmac('sha256', secret).update(content).digest('hex')}`;
|
||||
}
|
||||
|
||||
function matchesContentDigest(stored: string, content: string): boolean {
|
||||
return (
|
||||
stored === contentDigest(content) ||
|
||||
stored === createHash('sha256').update(content).digest('hex')
|
||||
);
|
||||
}
|
||||
|
||||
function matchesCheckpointDigest(stored: string, digest: string): boolean {
|
||||
// Legacy rows predate any pre-redaction identity and cannot safely prove equality.
|
||||
// Reject rather than let redaction collapse distinct sensitive checkpoint payloads.
|
||||
return stored === digest;
|
||||
}
|
||||
|
||||
function sameEnrollmentScope(left: DurableSessionIdentity, right: DurableSessionIdentity): boolean {
|
||||
return (
|
||||
left.agentName === right.agentName &&
|
||||
left.sessionId === right.sessionId &&
|
||||
left.tenantId === right.tenantId &&
|
||||
left.ownerId === right.ownerId
|
||||
);
|
||||
}
|
||||
|
||||
function sameInbox(left: DurableInboxEntry, right: DurableInboxInput): boolean {
|
||||
return (
|
||||
left.sessionId === right.sessionId &&
|
||||
left.idempotencyKey === right.idempotencyKey &&
|
||||
left.correlationId === right.correlationId &&
|
||||
left.content === right.content
|
||||
);
|
||||
}
|
||||
|
||||
function sameOutbox(left: DurableOutboxEntry, right: DurableOutboxInput): boolean {
|
||||
return (
|
||||
left.sessionId === right.sessionId &&
|
||||
left.idempotencyKey === right.idempotencyKey &&
|
||||
left.correlationId === right.correlationId &&
|
||||
left.channelId === right.channelId &&
|
||||
left.kind === right.kind &&
|
||||
left.content === right.content
|
||||
);
|
||||
}
|
||||
|
||||
function sameCheckpoint(left: DurableCheckpoint, right: DurableCheckpointInput): boolean {
|
||||
return (
|
||||
left.sessionId === right.sessionId &&
|
||||
left.checkpointId === right.checkpointId &&
|
||||
left.compactionEpoch === right.compactionEpoch
|
||||
);
|
||||
}
|
||||
|
||||
function sameHandoff(left: DurableHandoff, right: DurableHandoffInput): boolean {
|
||||
return (
|
||||
left.sessionId === right.sessionId &&
|
||||
left.handoffId === right.handoffId &&
|
||||
left.destination === right.destination &&
|
||||
left.correlationId === right.correlationId &&
|
||||
left.checkpointId === right.checkpointId &&
|
||||
left.status === right.status
|
||||
);
|
||||
}
|
||||
|
||||
function toInbox(row: typeof interactionInbox.$inferSelect): DurableInboxEntry {
|
||||
return {
|
||||
sessionId: row.sessionId,
|
||||
idempotencyKey: row.idempotencyKey,
|
||||
correlationId: row.correlationId,
|
||||
content: unseal(row.content),
|
||||
status: row.status,
|
||||
};
|
||||
}
|
||||
|
||||
function toOutbox(row: typeof interactionOutbox.$inferSelect): DurableOutboxEntry {
|
||||
return {
|
||||
sessionId: row.sessionId,
|
||||
idempotencyKey: row.idempotencyKey,
|
||||
correlationId: row.correlationId,
|
||||
channelId: row.channelId,
|
||||
kind: row.kind,
|
||||
content: unseal(row.content),
|
||||
status: row.status,
|
||||
};
|
||||
}
|
||||
|
||||
function toCheckpoint(row: typeof interactionCheckpoints.$inferSelect): DurableCheckpoint {
|
||||
return {
|
||||
sessionId: row.sessionId,
|
||||
checkpointId: row.checkpointId,
|
||||
cursor: unseal(row.cursor),
|
||||
summary: unseal(row.summary),
|
||||
compactionEpoch: row.compactionEpoch,
|
||||
};
|
||||
}
|
||||
|
||||
function toHandoff(row: typeof interactionHandoffs.$inferSelect): DurableHandoff {
|
||||
return {
|
||||
sessionId: row.sessionId,
|
||||
handoffId: row.handoffId,
|
||||
destination: row.destination,
|
||||
correlationId: row.correlationId,
|
||||
checkpointId: row.checkpointId,
|
||||
status: row.status,
|
||||
};
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
import { ForbiddenException, Inject, Injectable } from '@nestjs/common';
|
||||
import { DurableSessionCoordinator, type DurableSessionIdentity } from '@mosaicstack/agent';
|
||||
import type { ProviderOutboxDto } from './durable-session.dto.js';
|
||||
import { DurableSessionRepository } from './durable-session.repository.js';
|
||||
import {
|
||||
RuntimeProviderService,
|
||||
type RuntimeProviderRequestContext,
|
||||
} from './runtime-provider-registry.service.js';
|
||||
|
||||
/**
|
||||
* Scoped gateway boundary for the canonical durable session state machine. It deliberately
|
||||
* uses composition: raw state methods cannot be injected into channel, CLI, or
|
||||
* MCP adapters without a server-derived actor/tenant/correlation context.
|
||||
*/
|
||||
@Injectable()
|
||||
export class DurableSessionService {
|
||||
private readonly coordinator: DurableSessionCoordinator;
|
||||
|
||||
constructor(
|
||||
@Inject(DurableSessionRepository) repository: DurableSessionRepository,
|
||||
@Inject(RuntimeProviderService) private readonly runtimeProviders: RuntimeProviderService,
|
||||
) {
|
||||
this.coordinator = new DurableSessionCoordinator(repository);
|
||||
}
|
||||
|
||||
/** Enroll a verified runtime session under the stable cross-surface conversation handle. */
|
||||
async enroll(
|
||||
identity: DurableSessionIdentity,
|
||||
context: RuntimeProviderRequestContext,
|
||||
): Promise<void> {
|
||||
if (
|
||||
identity.ownerId !== context.actorScope.userId ||
|
||||
identity.tenantId !== context.actorScope.tenantId
|
||||
) {
|
||||
throw new ForbiddenException('Durable session enrollment scope mismatch');
|
||||
}
|
||||
await this.coordinator.create(identity);
|
||||
}
|
||||
|
||||
async queueProviderSend(input: ProviderOutboxDto): Promise<void> {
|
||||
const snapshot = await this.coordinator.snapshot(input.sessionId);
|
||||
this.assertScope(snapshot.identity.ownerId, snapshot.identity.tenantId, input);
|
||||
await this.coordinator.enqueueOutbox({
|
||||
sessionId: input.sessionId,
|
||||
idempotencyKey: input.idempotencyKey,
|
||||
correlationId: input.correlationId,
|
||||
channelId: input.context.channelId,
|
||||
kind: 'provider.send',
|
||||
content: input.content,
|
||||
});
|
||||
}
|
||||
|
||||
async dispatchProviderOutbox(sessionId: string, input: ProviderOutboxDto): Promise<void> {
|
||||
if (sessionId !== input.sessionId) {
|
||||
throw new ForbiddenException('Durable outbox session mismatch');
|
||||
}
|
||||
const snapshot = await this.coordinator.snapshot(sessionId);
|
||||
this.assertScope(snapshot.identity.ownerId, snapshot.identity.tenantId, input);
|
||||
const pendingEntry = snapshot.outbox.find(
|
||||
(entry): boolean => entry.idempotencyKey === input.idempotencyKey,
|
||||
);
|
||||
if (!pendingEntry) return;
|
||||
// Validate immutable routing before claiming. A caller with a mismatched
|
||||
// correlation/channel must not strand a pending external side effect.
|
||||
this.assertOutboxScope(pendingEntry, input);
|
||||
await this.coordinator.dispatchOutboxEntry(
|
||||
sessionId,
|
||||
input.idempotencyKey,
|
||||
async (entry): Promise<void> => {
|
||||
this.assertOutboxScope(entry, input);
|
||||
await this.runtimeProviders.sendMessage(
|
||||
snapshot.identity.providerId,
|
||||
snapshot.identity.runtimeSessionId,
|
||||
{ content: entry.content, idempotencyKey: entry.idempotencyKey },
|
||||
input.context,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/** Read durable identity/state only after deriving and checking the server-side actor scope. */
|
||||
async getSnapshot(sessionId: string, context: RuntimeProviderRequestContext) {
|
||||
const snapshot = await this.coordinator.snapshot(sessionId);
|
||||
this.assertScope(snapshot.identity.ownerId, snapshot.identity.tenantId, {
|
||||
sessionId,
|
||||
content: '',
|
||||
idempotencyKey: 'read-only',
|
||||
correlationId: context.correlationId,
|
||||
context,
|
||||
});
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
/** Startup/recovery-only path; normal queue/dispatch methods never requeue live work. */
|
||||
async recoverProviderSession(sessionId: string, input: ProviderOutboxDto): Promise<void> {
|
||||
const snapshot = await this.coordinator.snapshot(sessionId);
|
||||
this.assertScope(snapshot.identity.ownerId, snapshot.identity.tenantId, input);
|
||||
await this.coordinator.recover(sessionId);
|
||||
}
|
||||
|
||||
private assertOutboxScope(
|
||||
entry: { kind: string; correlationId: string; channelId: string },
|
||||
input: ProviderOutboxDto,
|
||||
): void {
|
||||
if (
|
||||
entry.kind !== 'provider.send' ||
|
||||
entry.correlationId !== input.correlationId ||
|
||||
entry.channelId !== input.context.channelId
|
||||
) {
|
||||
throw new ForbiddenException('Durable outbox scope or correlation mismatch');
|
||||
}
|
||||
}
|
||||
|
||||
private assertScope(ownerId: string, tenantId: string, input: ProviderOutboxDto): void {
|
||||
if (
|
||||
input.context.actorScope.userId !== ownerId ||
|
||||
input.context.actorScope.tenantId !== tenantId ||
|
||||
input.context.correlationId !== input.correlationId
|
||||
) {
|
||||
throw new ForbiddenException('Durable session scope or correlation mismatch');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,176 +0,0 @@
|
||||
import 'reflect-metadata';
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { FastifyAdapter, type NestFastifyApplication } from '@nestjs/platform-fastify';
|
||||
import { HermesRuntimeProvider } from '@mosaicstack/agent';
|
||||
import { AgentModule } from './agent.module.js';
|
||||
import { AUTH } from '../auth/auth.tokens.js';
|
||||
import { AuthGuard } from '../auth/auth.guard.js';
|
||||
import { BRAIN } from '../brain/brain.tokens.js';
|
||||
import { DB } from '../database/database.module.js';
|
||||
import { CoordModule } from '../coord/coord.module.js';
|
||||
import { McpClientModule } from '../mcp-client/mcp-client.module.js';
|
||||
import { SkillsModule } from '../skills/skills.module.js';
|
||||
import { GCModule } from '../gc/gc.module.js';
|
||||
import { LogModule } from '../log/log.module.js';
|
||||
import { CommandsModule } from '../commands/commands.module.js';
|
||||
import {
|
||||
AGENT_RUNTIME_PROVIDER_REGISTRY,
|
||||
RUNTIME_APPROVAL_VERIFIER,
|
||||
RUNTIME_PROVIDER_AUDIT_SINK,
|
||||
RuntimeProviderAuditService,
|
||||
} from './runtime-provider-registry.service.js';
|
||||
import { DurableSessionService } from './durable-session.service.js';
|
||||
import { DurableSessionRepository } from './durable-session.repository.js';
|
||||
import { AgentService } from './agent.service.js';
|
||||
import { ProviderService } from './provider.service.js';
|
||||
import { ProviderCredentialsService } from './provider-credentials.service.js';
|
||||
import { RoutingService } from './routing.service.js';
|
||||
import { RoutingEngineService } from './routing/routing-engine.service.js';
|
||||
import { SkillLoaderService } from './skill-loader.service.js';
|
||||
|
||||
const authenticatedUser = { id: 'operator-1', tenantId: 'tenant-1' };
|
||||
|
||||
@Module({})
|
||||
class EmptyAgentDependencyModule {}
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [
|
||||
{
|
||||
provide: AUTH,
|
||||
useValue: {
|
||||
api: {
|
||||
getSession: vi.fn(async ({ headers }: { headers: Headers }) =>
|
||||
headers.get('cookie') === 'session=trusted'
|
||||
? { user: authenticatedUser, session: { id: 'session-1' } }
|
||||
: null,
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
AuthGuard,
|
||||
{ provide: BRAIN, useValue: {} },
|
||||
{ provide: DB, useValue: {} },
|
||||
],
|
||||
exports: [AUTH, AuthGuard, BRAIN, DB],
|
||||
})
|
||||
class AuthenticatedRequestModule {}
|
||||
|
||||
/**
|
||||
* This is deliberately an HTTP test rather than a controller unit test: it
|
||||
* exercises AgentModule's actual provider factory, Nest DI, and AuthGuard.
|
||||
*/
|
||||
describe('Hermes runtime provider reachability', (): void => {
|
||||
let app: NestFastifyApplication | undefined;
|
||||
|
||||
beforeAll(async (): Promise<void> => {
|
||||
process.env['MOSAIC_AGENT_NAME'] = 'Nova';
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [AuthenticatedRequestModule, AgentModule],
|
||||
})
|
||||
.overrideModule(CoordModule)
|
||||
.useModule(EmptyAgentDependencyModule)
|
||||
.overrideModule(McpClientModule)
|
||||
.useModule(EmptyAgentDependencyModule)
|
||||
.overrideModule(SkillsModule)
|
||||
.useModule(EmptyAgentDependencyModule)
|
||||
.overrideModule(GCModule)
|
||||
.useModule(EmptyAgentDependencyModule)
|
||||
.overrideModule(LogModule)
|
||||
.useModule(EmptyAgentDependencyModule)
|
||||
.overrideModule(CommandsModule)
|
||||
.useModule(EmptyAgentDependencyModule)
|
||||
.overrideProvider(RuntimeProviderAuditService)
|
||||
.useValue({ record: vi.fn().mockResolvedValue(undefined) })
|
||||
.overrideProvider(RUNTIME_PROVIDER_AUDIT_SINK)
|
||||
.useValue({ record: vi.fn().mockResolvedValue(undefined) })
|
||||
.overrideProvider(RUNTIME_APPROVAL_VERIFIER)
|
||||
.useValue({ consume: vi.fn().mockResolvedValue(false) })
|
||||
.overrideProvider(DurableSessionService)
|
||||
.useValue({})
|
||||
.overrideProvider(DurableSessionRepository)
|
||||
.useValue({})
|
||||
.overrideProvider(AgentService)
|
||||
.useValue({})
|
||||
.overrideProvider(ProviderService)
|
||||
.useValue({})
|
||||
.overrideProvider(ProviderCredentialsService)
|
||||
.useValue({})
|
||||
.overrideProvider(RoutingService)
|
||||
.useValue({})
|
||||
.overrideProvider(RoutingEngineService)
|
||||
.useValue({})
|
||||
.overrideProvider(SkillLoaderService)
|
||||
.useValue({})
|
||||
.compile();
|
||||
|
||||
app = moduleRef.createNestApplication<NestFastifyApplication>(new FastifyAdapter());
|
||||
await app.init();
|
||||
await app.getHttpAdapter().getInstance().ready();
|
||||
});
|
||||
|
||||
afterAll(async (): Promise<void> => {
|
||||
await app?.close();
|
||||
});
|
||||
|
||||
it('returns gateway denial responses from the actual guarded interaction routes', async (): Promise<void> => {
|
||||
if (!app) throw new Error('Nest application did not initialize');
|
||||
|
||||
const attachDenied = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/interaction/Nova/sessions/session-1/attach',
|
||||
headers: { 'x-correlation-id': 'correlation-1' },
|
||||
payload: { mode: 'read' },
|
||||
});
|
||||
expect(attachDenied.statusCode).toBe(401);
|
||||
|
||||
const sendDenied = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/interaction/Nova/sessions/session-1/send',
|
||||
headers: { cookie: 'session=trusted', 'x-correlation-id': 'correlation-1' },
|
||||
payload: {},
|
||||
});
|
||||
expect(sendDenied.statusCode).toBe(403);
|
||||
expect(sendDenied.json()).toMatchObject({
|
||||
message: 'Content and idempotency key are required',
|
||||
});
|
||||
|
||||
const stopDenied = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/interaction/Nova/sessions/session-1/stop',
|
||||
headers: { cookie: 'session=trusted', 'x-correlation-id': 'correlation-1' },
|
||||
payload: {},
|
||||
});
|
||||
expect(stopDenied.statusCode).toBe(403);
|
||||
expect(stopDenied.json()).toMatchObject({ message: 'Exact-action approval is required' });
|
||||
});
|
||||
|
||||
it('requires authentication and reaches the Hermes provider registered by AgentModule', async (): Promise<void> => {
|
||||
if (!app) throw new Error('Nest application did not initialize');
|
||||
const registry = app.get(AGENT_RUNTIME_PROVIDER_REGISTRY);
|
||||
expect(registry.get('runtime.hermes')).toBeInstanceOf(HermesRuntimeProvider);
|
||||
|
||||
const denied = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/interaction/Nova/transitional-capabilities?provider=runtime.hermes',
|
||||
headers: { 'x-correlation-id': 'correlation-1' },
|
||||
});
|
||||
expect(denied.statusCode).toBe(401);
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/interaction/Nova/transitional-capabilities?provider=runtime.hermes',
|
||||
headers: { cookie: 'session=trusted', 'x-correlation-id': 'correlation-1' },
|
||||
});
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json()).toEqual([
|
||||
{ capability: 'kanban', status: 'unsupported' },
|
||||
{ capability: 'skills', status: 'unsupported' },
|
||||
{ capability: 'memory', status: 'unsupported' },
|
||||
{ capability: 'tools', status: 'unsupported' },
|
||||
{ capability: 'cron', status: 'unsupported' },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,46 +0,0 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { GatewayHermesRuntimeTransport } from './hermes-runtime.transport.js';
|
||||
|
||||
const scope = {
|
||||
actorId: 'owner-1',
|
||||
tenantId: 'tenant-1',
|
||||
channelId: 'cli',
|
||||
correlationId: 'correlation-1',
|
||||
};
|
||||
|
||||
describe('GatewayHermesRuntimeTransport', () => {
|
||||
it('preserves a configured path prefix and authenticates the concrete runtime request', async () => {
|
||||
const fetchFn = vi
|
||||
.fn()
|
||||
.mockResolvedValue(new Response(JSON.stringify(['session.list']), { status: 200 }));
|
||||
const transport = new GatewayHermesRuntimeTransport(
|
||||
'https://runtime.example.test/hermes',
|
||||
'test-service-token',
|
||||
fetchFn,
|
||||
);
|
||||
|
||||
await expect(transport.capabilities(scope)).resolves.toEqual(['session.list']);
|
||||
|
||||
expect(fetchFn).toHaveBeenCalledWith(
|
||||
new URL('https://runtime.example.test/hermes/capabilities'),
|
||||
expect.objectContaining({
|
||||
headers: expect.objectContaining({
|
||||
authorization: 'Bearer test-service-token',
|
||||
'x-mosaic-channel-id': 'cli',
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects non-loopback HTTP runtime endpoints before sending identity headers', async () => {
|
||||
const fetchFn = vi.fn();
|
||||
const transport = new GatewayHermesRuntimeTransport(
|
||||
'http://runtime.example.test/hermes',
|
||||
'test-service-token',
|
||||
fetchFn,
|
||||
);
|
||||
|
||||
await expect(transport.capabilities(scope)).rejects.toThrow('requires HTTPS');
|
||||
expect(fetchFn).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,121 +0,0 @@
|
||||
import type { HermesLegacySession, HermesRuntimeTransport } from '@mosaicstack/agent';
|
||||
import type {
|
||||
RuntimeAttachHandle,
|
||||
RuntimeAttachMode,
|
||||
RuntimeMessage,
|
||||
RuntimeScope,
|
||||
RuntimeStreamEvent,
|
||||
} from '@mosaicstack/types';
|
||||
|
||||
/** Concrete HTTP transport for a configured legacy Hermes runtime endpoint. */
|
||||
export class GatewayHermesRuntimeTransport implements HermesRuntimeTransport {
|
||||
constructor(
|
||||
private readonly baseUrl = process.env['MOSAIC_HERMES_RUNTIME_URL']?.trim(),
|
||||
private readonly serviceToken = process.env['MOSAIC_HERMES_RUNTIME_TOKEN']?.trim(),
|
||||
private readonly fetchFn: typeof fetch = fetch,
|
||||
) {}
|
||||
|
||||
async capabilities(scope: RuntimeScope): Promise<string[]> {
|
||||
return this.request<string[]>('/capabilities', scope);
|
||||
}
|
||||
|
||||
async health(scope: RuntimeScope): Promise<{ status: string; detail?: string }> {
|
||||
return this.request<{ status: string; detail?: string }>('/health', scope);
|
||||
}
|
||||
|
||||
async sessions(scope: RuntimeScope): Promise<HermesLegacySession[]> {
|
||||
return this.request<HermesLegacySession[]>('/sessions', scope);
|
||||
}
|
||||
|
||||
async *stream(
|
||||
sessionId: string,
|
||||
cursor: string | undefined,
|
||||
scope: RuntimeScope,
|
||||
): AsyncIterable<RuntimeStreamEvent> {
|
||||
const params = new URLSearchParams(cursor ? { cursor } : {});
|
||||
const events = await this.request<RuntimeStreamEvent[]>(
|
||||
`/sessions/${encodeURIComponent(sessionId)}/stream?${params.toString()}`,
|
||||
scope,
|
||||
);
|
||||
yield* events;
|
||||
}
|
||||
|
||||
async send(sessionId: string, message: RuntimeMessage, scope: RuntimeScope): Promise<void> {
|
||||
await this.request(`/sessions/${encodeURIComponent(sessionId)}/messages`, scope, {
|
||||
method: 'POST',
|
||||
body: message,
|
||||
});
|
||||
}
|
||||
|
||||
async attach(
|
||||
sessionId: string,
|
||||
mode: RuntimeAttachMode,
|
||||
scope: RuntimeScope,
|
||||
): Promise<RuntimeAttachHandle> {
|
||||
return this.request<RuntimeAttachHandle>(
|
||||
`/sessions/${encodeURIComponent(sessionId)}/attach`,
|
||||
scope,
|
||||
{
|
||||
method: 'POST',
|
||||
body: { mode },
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async detach(attachmentId: string, scope: RuntimeScope): Promise<void> {
|
||||
await this.request(`/attachments/${encodeURIComponent(attachmentId)}`, scope, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
}
|
||||
|
||||
async terminate(sessionId: string, approvalRef: string, scope: RuntimeScope): Promise<void> {
|
||||
await this.request(`/sessions/${encodeURIComponent(sessionId)}/terminate`, scope, {
|
||||
method: 'POST',
|
||||
body: { approvalRef },
|
||||
});
|
||||
}
|
||||
|
||||
private async request<T>(
|
||||
path: string,
|
||||
scope: RuntimeScope,
|
||||
init: { method?: string; body?: unknown } = {},
|
||||
): Promise<T> {
|
||||
if (!this.baseUrl || !this.serviceToken) {
|
||||
throw new Error(
|
||||
'MOSAIC_HERMES_RUNTIME_URL and MOSAIC_HERMES_RUNTIME_TOKEN must configure Hermes transport',
|
||||
);
|
||||
}
|
||||
const endpoint = new URL(this.baseUrl);
|
||||
if (endpoint.protocol !== 'https:' && !isLoopbackHttp(endpoint)) {
|
||||
throw new Error('Hermes runtime transport requires HTTPS outside loopback');
|
||||
}
|
||||
const response = await this.fetchFn(
|
||||
new URL(path.replace(/^\//, ''), `${endpoint.toString().replace(/\/$/, '')}/`),
|
||||
{
|
||||
method: init.method ?? 'GET',
|
||||
headers: {
|
||||
accept: 'application/json',
|
||||
authorization: `Bearer ${this.serviceToken}`,
|
||||
'x-mosaic-actor-id': scope.actorId,
|
||||
'x-mosaic-tenant-id': scope.tenantId,
|
||||
'x-mosaic-channel-id': scope.channelId,
|
||||
'x-correlation-id': scope.correlationId,
|
||||
...(init.body ? { 'content-type': 'application/json' } : {}),
|
||||
},
|
||||
...(init.body ? { body: JSON.stringify(init.body) } : {}),
|
||||
},
|
||||
);
|
||||
if (!response.ok) throw new Error(`Hermes runtime request failed: ${response.status}`);
|
||||
if (response.status === 204) return undefined as T;
|
||||
return (await response.json()) as T;
|
||||
}
|
||||
}
|
||||
|
||||
function isLoopbackHttp(endpoint: URL): boolean {
|
||||
return (
|
||||
endpoint.protocol === 'http:' &&
|
||||
(endpoint.hostname === 'localhost' ||
|
||||
endpoint.hostname === '127.0.0.1' ||
|
||||
endpoint.hostname === '::1')
|
||||
);
|
||||
}
|
||||
@@ -1,263 +0,0 @@
|
||||
import { createGatewayRuntimeProviderRegistry } from './agent.module.js';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
RuntimeApprovalDeniedError,
|
||||
RuntimeProviderService,
|
||||
} from './runtime-provider-registry.service.js';
|
||||
import { RuntimeApprovalDeniedFilter } from './runtime-approval-denied.filter.js';
|
||||
import { InteractionController } from './interaction.controller.js';
|
||||
|
||||
describe('InteractionController', (): void => {
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
it('maps a denied runtime approval to Fastify HTTP 403', () => {
|
||||
const send = vi.fn();
|
||||
const status = vi.fn().mockReturnValue({ send });
|
||||
const response = { status };
|
||||
const host = { switchToHttp: () => ({ getResponse: () => response }) };
|
||||
|
||||
new RuntimeApprovalDeniedFilter().catch(new RuntimeApprovalDeniedError(), host as never);
|
||||
|
||||
expect(status).toHaveBeenCalledWith(403);
|
||||
expect(send).toHaveBeenCalledWith({
|
||||
statusCode: 403,
|
||||
message: 'Runtime termination approval denied',
|
||||
});
|
||||
});
|
||||
|
||||
it('honors a differently named configured instance without a code change', async () => {
|
||||
const prior = process.env['MOSAIC_AGENT_NAME'];
|
||||
process.env['MOSAIC_AGENT_NAME'] = 'Nova';
|
||||
const runtime = { listSessions: vi.fn().mockResolvedValue([]) };
|
||||
const controller = new InteractionController(runtime as never, {} as never);
|
||||
|
||||
await expect(
|
||||
controller.sessions('Nova', 'fleet', { id: 'owner', tenantId: 'team' }, 'corr-1'),
|
||||
).resolves.toEqual([]);
|
||||
await expect(
|
||||
controller.sessions('Other', 'fleet', { id: 'owner', tenantId: 'team' }, 'corr-1'),
|
||||
).rejects.toThrow('Interaction agent is not configured');
|
||||
|
||||
if (prior === undefined) delete process.env['MOSAIC_AGENT_NAME'];
|
||||
else process.env['MOSAIC_AGENT_NAME'] = prior;
|
||||
});
|
||||
|
||||
it('reaches the registered Hermes provider through the authenticated transitional matrix route', async () => {
|
||||
process.env['MOSAIC_AGENT_NAME'] = 'Nova';
|
||||
const registry = createGatewayRuntimeProviderRegistry();
|
||||
const runtime = new RuntimeProviderService(
|
||||
registry,
|
||||
{ record: vi.fn().mockResolvedValue(undefined) },
|
||||
{ consume: vi.fn().mockResolvedValue(false) },
|
||||
);
|
||||
const controller = new InteractionController(runtime, {} as never);
|
||||
|
||||
await expect(
|
||||
controller.transitionalCapabilities(
|
||||
'Nova',
|
||||
'runtime.hermes',
|
||||
{ id: 'owner', tenantId: 'team' },
|
||||
'corr-1',
|
||||
),
|
||||
).resolves.toEqual([
|
||||
{ capability: 'kanban', status: 'unsupported' },
|
||||
{ capability: 'skills', status: 'unsupported' },
|
||||
{ capability: 'memory', status: 'unsupported' },
|
||||
{ capability: 'tools', status: 'unsupported' },
|
||||
{ capability: 'cron', status: 'unsupported' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('rejects a request without the non-simple correlation header', async () => {
|
||||
process.env['MOSAIC_AGENT_NAME'] = 'Nova';
|
||||
const controller = new InteractionController({ listSessions: vi.fn() } as never, {} as never);
|
||||
|
||||
await expect(controller.sessions('Nova', 'fleet', { id: 'owner' })).rejects.toThrow(
|
||||
'X-Correlation-Id is required',
|
||||
);
|
||||
});
|
||||
|
||||
it('enrolls a visible runtime session under the cross-surface conversation handle', async () => {
|
||||
process.env['MOSAIC_AGENT_NAME'] = 'Nova';
|
||||
const runtime = {
|
||||
listSessions: vi.fn().mockResolvedValue([{ id: 'runtime-1' }]),
|
||||
};
|
||||
const durable = { enroll: vi.fn().mockResolvedValue(undefined) };
|
||||
const controller = new InteractionController(runtime as never, durable as never);
|
||||
|
||||
await expect(
|
||||
controller.enroll(
|
||||
'Nova',
|
||||
'conversation-1',
|
||||
{ providerId: 'fleet', runtimeSessionId: 'runtime-1' },
|
||||
{ id: 'owner', tenantId: 'team' },
|
||||
'corr-1',
|
||||
),
|
||||
).resolves.toEqual({ status: 'enrolled', sessionId: 'conversation-1' });
|
||||
expect(durable.enroll).toHaveBeenCalledWith(
|
||||
{
|
||||
agentName: 'Nova',
|
||||
sessionId: 'conversation-1',
|
||||
tenantId: 'team',
|
||||
ownerId: 'owner',
|
||||
providerId: 'fleet',
|
||||
runtimeSessionId: 'runtime-1',
|
||||
},
|
||||
expect.objectContaining({ correlationId: 'corr-1' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects an invalid attach mode before invoking a provider', async () => {
|
||||
process.env['MOSAIC_AGENT_NAME'] = 'Nova';
|
||||
const controller = new InteractionController({ attach: vi.fn() } as never, {} as never);
|
||||
|
||||
await expect(
|
||||
controller.attach('Nova', 'durable-1', { mode: 'write' as never }, { id: 'owner' }, 'corr-1'),
|
||||
).rejects.toThrow('Interaction attach mode is invalid');
|
||||
});
|
||||
|
||||
it('resumes a durable session by attaching and streaming its runtime events', async () => {
|
||||
process.env['MOSAIC_AGENT_NAME'] = 'Nova';
|
||||
const runtimeEvent = {
|
||||
type: 'message.delta' as const,
|
||||
sessionId: 'runtime-1',
|
||||
cursor: 'cursor-1',
|
||||
occurredAt: '2026-07-13T00:00:00.000Z',
|
||||
content: 'resumed',
|
||||
};
|
||||
const runtime = {
|
||||
attach: vi.fn().mockResolvedValue({ attachmentId: 'attach-1', sessionId: 'runtime-1' }),
|
||||
streamSession: vi.fn(async function* () {
|
||||
yield runtimeEvent;
|
||||
}),
|
||||
};
|
||||
const durable = {
|
||||
getSnapshot: vi.fn().mockResolvedValue({
|
||||
identity: { agentName: 'Nova', providerId: 'fleet', runtimeSessionId: 'runtime-1' },
|
||||
}),
|
||||
};
|
||||
const controller = new InteractionController(runtime as never, durable as never);
|
||||
|
||||
await controller.attach('Nova', 'conversation-1', { mode: 'read' }, { id: 'owner' }, 'corr-1');
|
||||
await expect(
|
||||
firstValueFrom(
|
||||
controller.stream('Nova', 'conversation-1', undefined, { id: 'owner' }, 'corr-1'),
|
||||
),
|
||||
).resolves.toEqual({ data: runtimeEvent });
|
||||
|
||||
expect(runtime.attach).toHaveBeenCalledWith(
|
||||
'fleet',
|
||||
'runtime-1',
|
||||
'read',
|
||||
expect.objectContaining({ correlationId: 'corr-1' }),
|
||||
);
|
||||
expect(runtime.streamSession).toHaveBeenCalledWith(
|
||||
'fleet',
|
||||
'runtime-1',
|
||||
undefined,
|
||||
expect.objectContaining({ correlationId: 'corr-1' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('does not create a runtime stream after the SSE subscriber disconnects during snapshot lookup', async () => {
|
||||
process.env['MOSAIC_AGENT_NAME'] = 'Nova';
|
||||
let resolveSnapshot!: (value: { identity: Record<string, string> }) => void;
|
||||
const snapshot = new Promise<{ identity: Record<string, string> }>((resolve) => {
|
||||
resolveSnapshot = resolve;
|
||||
});
|
||||
const runtime = { streamSession: vi.fn() };
|
||||
const durable = { getSnapshot: vi.fn().mockReturnValue(snapshot) };
|
||||
const controller = new InteractionController(runtime as never, durable as never);
|
||||
|
||||
const subscription = controller
|
||||
.stream('Nova', 'conversation-1', undefined, { id: 'owner' }, 'corr-1')
|
||||
.subscribe();
|
||||
subscription.unsubscribe();
|
||||
resolveSnapshot({
|
||||
identity: { agentName: 'Nova', providerId: 'fleet', runtimeSessionId: 'runtime-1' },
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
expect(runtime.streamSession).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['wrong actor', { getSnapshot: vi.fn().mockRejectedValue(new Error('scope mismatch')) }],
|
||||
[
|
||||
'session-agent mismatch',
|
||||
{
|
||||
getSnapshot: vi.fn().mockResolvedValue({
|
||||
identity: { agentName: 'Other', providerId: 'fleet', runtimeSessionId: 'runtime-1' },
|
||||
}),
|
||||
},
|
||||
],
|
||||
])('denies a CLI stop for %s', async (_reason, durable) => {
|
||||
process.env['MOSAIC_AGENT_NAME'] = 'Nova';
|
||||
const runtime = { terminate: vi.fn().mockResolvedValue(undefined) };
|
||||
const controller = new InteractionController(runtime as never, durable as never);
|
||||
|
||||
await expect(
|
||||
controller.stop(
|
||||
'Nova',
|
||||
'durable-1',
|
||||
{ approvalRef: 'approval-1' },
|
||||
{ id: 'owner' },
|
||||
'corr-1',
|
||||
),
|
||||
).rejects.toBeDefined();
|
||||
expect(runtime.terminate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('surfaces a denied runtime approval to the CLI interaction surface', async () => {
|
||||
process.env['MOSAIC_AGENT_NAME'] = 'Nova';
|
||||
const runtime = {
|
||||
terminate: vi.fn().mockRejectedValue(new Error('Runtime termination approval denied')),
|
||||
};
|
||||
const durable = {
|
||||
getSnapshot: vi.fn().mockResolvedValue({
|
||||
identity: { agentName: 'Nova', providerId: 'fleet', runtimeSessionId: 'runtime-1' },
|
||||
}),
|
||||
};
|
||||
const controller = new InteractionController(runtime as never, durable as never);
|
||||
|
||||
await expect(
|
||||
controller.stop(
|
||||
'Nova',
|
||||
'durable-1',
|
||||
{ approvalRef: 'approval-1' },
|
||||
{ id: 'owner' },
|
||||
'corr-1',
|
||||
),
|
||||
).rejects.toThrow('Runtime termination approval denied');
|
||||
});
|
||||
|
||||
it('uses the durable session identity and runtime registry for an approved stop', async () => {
|
||||
process.env['MOSAIC_AGENT_NAME'] = 'Nova';
|
||||
const runtime = { terminate: vi.fn().mockResolvedValue(undefined) };
|
||||
const durable = {
|
||||
getSnapshot: vi.fn().mockResolvedValue({
|
||||
identity: { agentName: 'Nova', providerId: 'fleet', runtimeSessionId: 'runtime-1' },
|
||||
}),
|
||||
};
|
||||
const controller = new InteractionController(runtime as never, durable as never);
|
||||
|
||||
await controller.stop(
|
||||
'Nova',
|
||||
'durable-1',
|
||||
{ approvalRef: 'approval-1' },
|
||||
{ id: 'owner' },
|
||||
'corr-1',
|
||||
);
|
||||
|
||||
expect(runtime.terminate).toHaveBeenCalledWith(
|
||||
'fleet',
|
||||
'runtime-1',
|
||||
'approval-1',
|
||||
expect.objectContaining({
|
||||
correlationId: 'corr-1',
|
||||
actorScope: { userId: 'owner', tenantId: 'owner' },
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,293 +0,0 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
ForbiddenException,
|
||||
Get,
|
||||
Headers,
|
||||
Sse,
|
||||
Inject,
|
||||
Param,
|
||||
Post,
|
||||
Query,
|
||||
UseGuards,
|
||||
UseFilters,
|
||||
} from '@nestjs/common';
|
||||
import type { RuntimeAttachMode, RuntimeStreamEvent } from '@mosaicstack/types';
|
||||
import { Observable } from 'rxjs';
|
||||
import { AuthGuard } from '../auth/auth.guard.js';
|
||||
import { CurrentUser } from '../auth/current-user.decorator.js';
|
||||
import { scopeFromUser, type AuthenticatedUserLike } from '../auth/session-scope.js';
|
||||
import { DurableSessionService } from './durable-session.service.js';
|
||||
import { RuntimeApprovalDeniedFilter } from './runtime-approval-denied.filter.js';
|
||||
import {
|
||||
RuntimeProviderService,
|
||||
type RuntimeProviderRequestContext,
|
||||
} from './runtime-provider-registry.service.js';
|
||||
|
||||
/**
|
||||
* Authenticated HTTP boundary for operator interaction clients. Identity is
|
||||
* selected from deployment configuration, never a client-side command name.
|
||||
*/
|
||||
@Controller('api/interaction/:agentName')
|
||||
@UseGuards(AuthGuard)
|
||||
@UseFilters(RuntimeApprovalDeniedFilter)
|
||||
export class InteractionController {
|
||||
constructor(
|
||||
@Inject(RuntimeProviderService) private readonly runtime: RuntimeProviderService,
|
||||
@Inject(DurableSessionService) private readonly durable: DurableSessionService,
|
||||
) {}
|
||||
|
||||
@Get('sessions')
|
||||
async sessions(
|
||||
@Param('agentName') agentName: string,
|
||||
@Query('provider') providerId: string,
|
||||
@CurrentUser() user: AuthenticatedUserLike,
|
||||
@Headers('x-correlation-id') correlationId?: string,
|
||||
) {
|
||||
this.assertConfiguredAgent(agentName);
|
||||
return this.runtime.listSessions(
|
||||
this.requiredProvider(providerId),
|
||||
this.context(user, correlationId),
|
||||
);
|
||||
}
|
||||
|
||||
@Get('transitional-capabilities')
|
||||
async transitionalCapabilities(
|
||||
@Param('agentName') agentName: string,
|
||||
@Query('provider') providerId: string,
|
||||
@CurrentUser() user: AuthenticatedUserLike,
|
||||
@Headers('x-correlation-id') correlationId?: string,
|
||||
) {
|
||||
this.assertConfiguredAgent(agentName);
|
||||
return this.runtime.transitionalCapabilityMatrix(
|
||||
this.requiredProvider(providerId),
|
||||
this.context(user, correlationId),
|
||||
);
|
||||
}
|
||||
|
||||
@Get('tree')
|
||||
async tree(
|
||||
@Param('agentName') agentName: string,
|
||||
@Query('provider') providerId: string,
|
||||
@CurrentUser() user: AuthenticatedUserLike,
|
||||
@Headers('x-correlation-id') correlationId?: string,
|
||||
) {
|
||||
this.assertConfiguredAgent(agentName);
|
||||
return this.runtime.getSessionTree(
|
||||
this.requiredProvider(providerId),
|
||||
this.context(user, correlationId),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind an existing, authorized runtime session to the stable conversation ID.
|
||||
* This is the lifecycle boundary where both runtime identifiers are known.
|
||||
*/
|
||||
@Post('sessions/:sessionId/enroll')
|
||||
async enroll(
|
||||
@Param('agentName') agentName: string,
|
||||
@Param('sessionId') sessionId: string,
|
||||
@Body() body: { providerId?: string; runtimeSessionId?: string } = {},
|
||||
@CurrentUser() user: AuthenticatedUserLike,
|
||||
@Headers('x-correlation-id') correlationId?: string,
|
||||
) {
|
||||
this.assertConfiguredAgent(agentName);
|
||||
const providerId = this.requiredProvider(body.providerId ?? '');
|
||||
const runtimeSessionId = body.runtimeSessionId?.trim();
|
||||
if (!runtimeSessionId) throw new ForbiddenException('Runtime session identity is required');
|
||||
const context = this.context(user, correlationId);
|
||||
const sessions = await this.runtime.listSessions(providerId, context);
|
||||
if (!sessions.some((session): boolean => session.id === runtimeSessionId)) {
|
||||
throw new ForbiddenException('Runtime session is not visible to this actor');
|
||||
}
|
||||
await this.durable.enroll(
|
||||
{
|
||||
agentName,
|
||||
sessionId,
|
||||
tenantId: context.actorScope.tenantId,
|
||||
ownerId: context.actorScope.userId,
|
||||
providerId,
|
||||
runtimeSessionId,
|
||||
},
|
||||
context,
|
||||
);
|
||||
return { status: 'enrolled', sessionId };
|
||||
}
|
||||
|
||||
@Post('sessions/:sessionId/attach')
|
||||
async attach(
|
||||
@Param('agentName') agentName: string,
|
||||
@Param('sessionId') sessionId: string,
|
||||
@Body() body: { mode?: RuntimeAttachMode } = {},
|
||||
@CurrentUser() user: AuthenticatedUserLike,
|
||||
@Headers('x-correlation-id') correlationId?: string,
|
||||
) {
|
||||
this.assertConfiguredAgent(agentName);
|
||||
const context = this.context(user, correlationId);
|
||||
const mode = body.mode ?? 'read';
|
||||
if (mode !== 'read' && mode !== 'control') {
|
||||
throw new ForbiddenException('Interaction attach mode is invalid');
|
||||
}
|
||||
const snapshot = await this.durable.getSnapshot(sessionId, context);
|
||||
this.assertSessionAgent(snapshot.identity.agentName, agentName);
|
||||
return this.runtime.attach(
|
||||
snapshot.identity.providerId,
|
||||
snapshot.identity.runtimeSessionId,
|
||||
mode,
|
||||
context,
|
||||
);
|
||||
}
|
||||
|
||||
@Sse('sessions/:sessionId/stream')
|
||||
stream(
|
||||
@Param('agentName') agentName: string,
|
||||
@Param('sessionId') sessionId: string,
|
||||
@Query('cursor') cursor: string | undefined,
|
||||
@CurrentUser() user: AuthenticatedUserLike,
|
||||
@Headers('x-correlation-id') correlationId?: string,
|
||||
): Observable<{ data: RuntimeStreamEvent }> {
|
||||
this.assertConfiguredAgent(agentName);
|
||||
const context = this.context(user, correlationId);
|
||||
return new Observable((subscriber) => {
|
||||
let iterator: AsyncIterator<RuntimeStreamEvent> | undefined;
|
||||
let cancelled = false;
|
||||
void (async (): Promise<void> => {
|
||||
try {
|
||||
const snapshot = await this.durable.getSnapshot(sessionId, context);
|
||||
if (cancelled || subscriber.closed) return;
|
||||
this.assertSessionAgent(snapshot.identity.agentName, agentName);
|
||||
iterator = this.runtime
|
||||
.streamSession(
|
||||
snapshot.identity.providerId,
|
||||
snapshot.identity.runtimeSessionId,
|
||||
cursor?.trim() || undefined,
|
||||
context,
|
||||
)
|
||||
[Symbol.asyncIterator]();
|
||||
if (cancelled || subscriber.closed) {
|
||||
await iterator.return?.();
|
||||
return;
|
||||
}
|
||||
while (!cancelled && !subscriber.closed) {
|
||||
const next = await iterator.next();
|
||||
if (next.done || cancelled || subscriber.closed) break;
|
||||
subscriber.next({ data: next.value });
|
||||
}
|
||||
if (!subscriber.closed) subscriber.complete();
|
||||
} catch (error: unknown) {
|
||||
if (!subscriber.closed) subscriber.error(error);
|
||||
}
|
||||
})();
|
||||
return (): void => {
|
||||
cancelled = true;
|
||||
void iterator?.return?.();
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@Post('sessions/:sessionId/send')
|
||||
async send(
|
||||
@Param('agentName') agentName: string,
|
||||
@Param('sessionId') sessionId: string,
|
||||
@Body() body: { content?: string; idempotencyKey?: string } = {},
|
||||
@CurrentUser() user: AuthenticatedUserLike,
|
||||
@Headers('x-correlation-id') correlationId?: string,
|
||||
) {
|
||||
this.assertConfiguredAgent(agentName);
|
||||
if (!body.content?.trim() || !body.idempotencyKey?.trim()) {
|
||||
throw new ForbiddenException('Content and idempotency key are required');
|
||||
}
|
||||
const context = this.context(user, correlationId);
|
||||
const snapshot = await this.durable.getSnapshot(sessionId, context);
|
||||
this.assertSessionAgent(snapshot.identity.agentName, agentName);
|
||||
const input = {
|
||||
sessionId,
|
||||
content: body.content,
|
||||
idempotencyKey: body.idempotencyKey,
|
||||
correlationId: context.correlationId,
|
||||
context,
|
||||
};
|
||||
await this.durable.queueProviderSend(input);
|
||||
await this.durable.dispatchProviderOutbox(sessionId, input);
|
||||
return { status: 'queued', sessionId };
|
||||
}
|
||||
|
||||
@Post('sessions/:sessionId/stop')
|
||||
async stop(
|
||||
@Param('agentName') agentName: string,
|
||||
@Param('sessionId') sessionId: string,
|
||||
@Body() body: { approvalRef?: string } = {},
|
||||
@CurrentUser() user: AuthenticatedUserLike,
|
||||
@Headers('x-correlation-id') correlationId?: string,
|
||||
) {
|
||||
this.assertConfiguredAgent(agentName);
|
||||
if (!body.approvalRef?.trim())
|
||||
throw new ForbiddenException('Exact-action approval is required');
|
||||
const context = this.context(user, correlationId);
|
||||
const snapshot = await this.durable.getSnapshot(sessionId, context);
|
||||
this.assertSessionAgent(snapshot.identity.agentName, agentName);
|
||||
await this.runtime.terminate(
|
||||
snapshot.identity.providerId,
|
||||
snapshot.identity.runtimeSessionId,
|
||||
body.approvalRef,
|
||||
context,
|
||||
);
|
||||
return { status: 'stopped', sessionId };
|
||||
}
|
||||
|
||||
@Post('sessions/:sessionId/recover')
|
||||
async recover(
|
||||
@Param('agentName') agentName: string,
|
||||
@Param('sessionId') sessionId: string,
|
||||
@CurrentUser() user: AuthenticatedUserLike,
|
||||
@Headers('x-correlation-id') correlationId?: string,
|
||||
) {
|
||||
this.assertConfiguredAgent(agentName);
|
||||
const context = this.context(user, correlationId);
|
||||
const snapshot = await this.durable.getSnapshot(sessionId, context);
|
||||
this.assertSessionAgent(snapshot.identity.agentName, agentName);
|
||||
await this.durable.recoverProviderSession(sessionId, {
|
||||
sessionId,
|
||||
content: '',
|
||||
idempotencyKey: `recovery:${context.correlationId}`,
|
||||
correlationId: context.correlationId,
|
||||
context,
|
||||
});
|
||||
return { status: 'recovered', sessionId };
|
||||
}
|
||||
|
||||
private context(
|
||||
user: AuthenticatedUserLike,
|
||||
correlationId?: string,
|
||||
): RuntimeProviderRequestContext {
|
||||
const requestCorrelationId = correlationId?.trim();
|
||||
// This non-simple request header is mandatory for mutations. Browser
|
||||
// cross-origin requests cannot set it without a CORS preflight, and the
|
||||
// gateway's allowlist rejects untrusted origins before the handler runs.
|
||||
if (!requestCorrelationId) {
|
||||
throw new ForbiddenException('X-Correlation-Id is required');
|
||||
}
|
||||
return {
|
||||
actorScope: scopeFromUser(user),
|
||||
channelId: 'cli',
|
||||
correlationId: requestCorrelationId,
|
||||
};
|
||||
}
|
||||
|
||||
private assertConfiguredAgent(agentName: string): void {
|
||||
const configured = process.env['MOSAIC_AGENT_NAME']?.trim();
|
||||
if (!configured || configured !== agentName) {
|
||||
throw new ForbiddenException('Interaction agent is not configured for this request');
|
||||
}
|
||||
}
|
||||
|
||||
private assertSessionAgent(sessionAgentName: string, agentName: string): void {
|
||||
if (sessionAgentName !== agentName)
|
||||
throw new ForbiddenException('Interaction session identity mismatch');
|
||||
}
|
||||
|
||||
private requiredProvider(providerId: string): string {
|
||||
if (!providerId?.trim()) throw new ForbiddenException('Runtime provider is required');
|
||||
return providerId;
|
||||
}
|
||||
}
|
||||
@@ -107,7 +107,8 @@ export class ProviderService implements OnModuleInit, OnModuleDestroy {
|
||||
* Interval is configurable via PROVIDER_HEALTH_INTERVAL env (seconds, default 60).
|
||||
*/
|
||||
private startHealthCheckScheduler(): void {
|
||||
const intervalSecs = this.effectiveHealthCheckIntervalSecs();
|
||||
const intervalSecs =
|
||||
parseInt(process.env['PROVIDER_HEALTH_INTERVAL'] ?? '', 10) || DEFAULT_HEALTH_INTERVAL_SECS;
|
||||
const intervalMs = intervalSecs * 1000;
|
||||
|
||||
// Run an initial check immediately (non-blocking)
|
||||
@@ -175,28 +176,6 @@ export class ProviderService implements OnModuleInit, OnModuleDestroy {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the effective provider operational policy without credentials,
|
||||
* endpoints, request content, or provider error details.
|
||||
*/
|
||||
getEffectivePolicyStatus(): {
|
||||
healthCheckIntervalSecs: number;
|
||||
configuredProviders: string[];
|
||||
availableModelCount: number;
|
||||
} {
|
||||
return {
|
||||
healthCheckIntervalSecs: this.effectiveHealthCheckIntervalSecs(),
|
||||
configuredProviders: this.adapters.map((adapter) => adapter.name),
|
||||
availableModelCount: this.registry?.getAvailable().length ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
private effectiveHealthCheckIntervalSecs(): number {
|
||||
return (
|
||||
parseInt(process.env['PROVIDER_HEALTH_INTERVAL'] ?? '', 10) || DEFAULT_HEALTH_INTERVAL_SECS
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Adapter-pattern API
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { ProvidersController } from './providers.controller.js';
|
||||
|
||||
describe('ProvidersController operational status', (): void => {
|
||||
it('reports provider latency and effective policy without exposing provider error details', (): void => {
|
||||
const providerService = {
|
||||
getProvidersHealth: vi.fn(() => [
|
||||
{
|
||||
name: 'fleet',
|
||||
status: 'down',
|
||||
latencyMs: 42,
|
||||
lastChecked: '2026-07-12T00:00:00.000Z',
|
||||
modelCount: 0,
|
||||
error: 'credential-canary=secret-value',
|
||||
},
|
||||
]),
|
||||
getEffectivePolicyStatus: vi.fn(() => ({
|
||||
healthCheckIntervalSecs: 60,
|
||||
configuredProviders: ['fleet'],
|
||||
availableModelCount: 0,
|
||||
})),
|
||||
};
|
||||
const controller = new ProvidersController(providerService as never, {} as never, {} as never);
|
||||
|
||||
const status = controller.status();
|
||||
|
||||
expect(status).toEqual({
|
||||
providers: [
|
||||
{
|
||||
name: 'fleet',
|
||||
status: 'down',
|
||||
latencyMs: 42,
|
||||
lastChecked: '2026-07-12T00:00:00.000Z',
|
||||
modelCount: 0,
|
||||
errorCode: 'provider_unavailable',
|
||||
},
|
||||
],
|
||||
effectivePolicy: {
|
||||
healthCheckIntervalSecs: 60,
|
||||
configuredProviders: ['fleet'],
|
||||
availableModelCount: 0,
|
||||
},
|
||||
});
|
||||
expect(JSON.stringify(status)).not.toContain('secret-value');
|
||||
});
|
||||
});
|
||||
@@ -33,20 +33,7 @@ export class ProvidersController {
|
||||
|
||||
@Get('health')
|
||||
health() {
|
||||
return { providers: this.safeProviderHealth() };
|
||||
}
|
||||
|
||||
/**
|
||||
* Safe operational status for troubleshooting and readiness checks. Provider
|
||||
* errors are reduced to a stable code so credentials and remote responses
|
||||
* cannot leak through this endpoint.
|
||||
*/
|
||||
@Get('status')
|
||||
status() {
|
||||
return {
|
||||
providers: this.safeProviderHealth(),
|
||||
effectivePolicy: this.providerService.getEffectivePolicyStatus(),
|
||||
};
|
||||
return { providers: this.providerService.getProvidersHealth() };
|
||||
}
|
||||
|
||||
@Post('test')
|
||||
@@ -64,13 +51,6 @@ export class ProvidersController {
|
||||
return this.routingService.rank(criteria);
|
||||
}
|
||||
|
||||
private safeProviderHealth() {
|
||||
return this.providerService.getProvidersHealth().map(({ error, ...provider }) => ({
|
||||
...provider,
|
||||
...(error ? { errorCode: 'provider_unavailable' } : {}),
|
||||
}));
|
||||
}
|
||||
|
||||
// ── Credential CRUD ──────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
* to avoid real I/O — they verify the complete classify → match → decide path.
|
||||
*/
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import type { ProviderHealthStatus } from '@mosaicstack/types';
|
||||
import { RoutingEngineService } from './routing-engine.service.js';
|
||||
import { DEFAULT_ROUTING_RULES } from '../routing/default-rules.js';
|
||||
import type { RoutingRule } from './routing.types.js';
|
||||
@@ -18,7 +17,7 @@ import type { RoutingRule } from './routing.types.js';
|
||||
/** Build a RoutingEngineService backed by the given rule set and health map. */
|
||||
function makeService(
|
||||
rules: RoutingRule[],
|
||||
healthMap: Record<string, { status: ProviderHealthStatus }>,
|
||||
healthMap: Record<string, { status: string }>,
|
||||
): RoutingEngineService {
|
||||
const mockDb = {
|
||||
select: vi.fn().mockReturnValue({
|
||||
@@ -68,11 +67,11 @@ function defaultRules(): RoutingRule[] {
|
||||
}
|
||||
|
||||
/** A health map where anthropic, openai, and zai are all healthy. */
|
||||
const allHealthy: Record<string, { status: ProviderHealthStatus }> = {
|
||||
anthropic: { status: 'healthy' },
|
||||
openai: { status: 'healthy' },
|
||||
zai: { status: 'healthy' },
|
||||
ollama: { status: 'healthy' },
|
||||
const allHealthy: Record<string, { status: string }> = {
|
||||
anthropic: { status: 'up' },
|
||||
openai: { status: 'up' },
|
||||
zai: { status: 'up' },
|
||||
ollama: { status: 'up' },
|
||||
};
|
||||
|
||||
// ─── M4-013 E2E tests ─────────────────────────────────────────────────────────
|
||||
@@ -213,10 +212,10 @@ describe('M4-013: routing end-to-end pipeline', () => {
|
||||
// Let's use a simple coding message to target Simple coding → Codex (openai)
|
||||
const message = 'implement a sort function';
|
||||
|
||||
const unhealthyHealth: Record<string, { status: ProviderHealthStatus }> = {
|
||||
const unhealthyHealth = {
|
||||
anthropic: { status: 'down' },
|
||||
openai: { status: 'healthy' },
|
||||
zai: { status: 'healthy' },
|
||||
openai: { status: 'up' },
|
||||
zai: { status: 'up' },
|
||||
ollama: { status: 'down' },
|
||||
};
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { Inject, Injectable, Logger } from '@nestjs/common';
|
||||
import { routingRules, type Db, and, asc, eq, or } from '@mosaicstack/db';
|
||||
import type { ProviderHealthStatus } from '@mosaicstack/types';
|
||||
import { DB } from '../../database/database.module.js';
|
||||
import { ProviderService } from '../provider.service.js';
|
||||
import { classifyTask } from './task-classifier.js';
|
||||
@@ -50,7 +49,7 @@ export class RoutingEngineService {
|
||||
async resolve(
|
||||
message: string,
|
||||
userId?: string,
|
||||
availableProviders?: Record<string, { status: ProviderHealthStatus }>,
|
||||
availableProviders?: Record<string, { status: string }>,
|
||||
): Promise<RoutingDecision> {
|
||||
const classification = classifyTask(message);
|
||||
this.logger.debug(
|
||||
@@ -70,8 +69,9 @@ export class RoutingEngineService {
|
||||
if (!this.matchConditions(rule, classification)) continue;
|
||||
|
||||
const providerStatus = health[rule.action.provider]?.status;
|
||||
const isHealthy = providerStatus === 'up' || providerStatus === 'ok';
|
||||
|
||||
if (!this.isRoutable(providerStatus)) {
|
||||
if (!isHealthy) {
|
||||
this.logger.debug(
|
||||
`Rule "${rule.name}" matched but provider "${rule.action.provider}" is unhealthy (status: ${providerStatus ?? 'unknown'})`,
|
||||
);
|
||||
@@ -111,10 +111,6 @@ export class RoutingEngineService {
|
||||
|
||||
// ─── Private helpers ───────────────────────────────────────────────────────
|
||||
|
||||
private isRoutable(status: ProviderHealthStatus | undefined): boolean {
|
||||
return status === 'healthy' || status === 'degraded';
|
||||
}
|
||||
|
||||
private evaluateCondition(
|
||||
condition: RoutingCondition,
|
||||
classification: TaskClassification,
|
||||
@@ -190,12 +186,11 @@ export class RoutingEngineService {
|
||||
* Walk the fallback chain and return the first healthy provider/model pair.
|
||||
* If none are healthy, return the first entry unconditionally (last resort).
|
||||
*/
|
||||
private applyFallbackChain(
|
||||
health: Record<string, { status: ProviderHealthStatus }>,
|
||||
): RoutingDecision {
|
||||
private applyFallbackChain(health: Record<string, { status: string }>): RoutingDecision {
|
||||
for (const candidate of FALLBACK_CHAIN) {
|
||||
const providerStatus = health[candidate.provider]?.status;
|
||||
if (this.isRoutable(providerStatus)) {
|
||||
const isHealthy = providerStatus === 'up' || providerStatus === 'ok';
|
||||
if (isHealthy) {
|
||||
this.logger.debug(`Fallback resolved: ${candidate.provider}/${candidate.model}`);
|
||||
return {
|
||||
provider: candidate.provider,
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import type { ProviderHealthStatus } from '@mosaicstack/types';
|
||||
import { RoutingEngineService } from './routing-engine.service.js';
|
||||
import type { RoutingRule, TaskClassification } from './routing.types.js';
|
||||
|
||||
@@ -30,7 +29,7 @@ function makeClassification(overrides: Partial<TaskClassification> = {}): TaskCl
|
||||
/** Build a minimal RoutingEngineService with mocked DB and ProviderService. */
|
||||
function makeService(
|
||||
rules: RoutingRule[] = [],
|
||||
healthMap: Record<string, { status: ProviderHealthStatus }> = {},
|
||||
healthMap: Record<string, { status: string }> = {},
|
||||
): RoutingEngineService {
|
||||
const mockDb = {
|
||||
select: vi.fn().mockReturnValue({
|
||||
@@ -218,10 +217,7 @@ describe('RoutingEngineService.resolve — priority ordering', () => {
|
||||
}),
|
||||
];
|
||||
|
||||
const service = makeService(rules, {
|
||||
anthropic: { status: 'healthy' },
|
||||
openai: { status: 'healthy' },
|
||||
});
|
||||
const service = makeService(rules, { anthropic: { status: 'up' }, openai: { status: 'up' } });
|
||||
|
||||
const decision = await service.resolve('implement a function');
|
||||
expect(decision.ruleName).toBe('high priority');
|
||||
@@ -245,10 +241,7 @@ describe('RoutingEngineService.resolve — priority ordering', () => {
|
||||
}),
|
||||
];
|
||||
|
||||
const service = makeService(rules, {
|
||||
anthropic: { status: 'healthy' },
|
||||
openai: { status: 'healthy' },
|
||||
});
|
||||
const service = makeService(rules, { anthropic: { status: 'up' }, openai: { status: 'up' } });
|
||||
|
||||
const decision = await service.resolve('implement a function');
|
||||
expect(decision.ruleName).toBe('coding rule');
|
||||
@@ -277,7 +270,7 @@ describe('RoutingEngineService.resolve — unhealthy provider handling', () => {
|
||||
|
||||
const service = makeService(rules, {
|
||||
anthropic: { status: 'down' }, // primary is unhealthy
|
||||
openai: { status: 'healthy' },
|
||||
openai: { status: 'up' },
|
||||
});
|
||||
|
||||
const decision = await service.resolve('implement a function');
|
||||
@@ -297,7 +290,7 @@ describe('RoutingEngineService.resolve — unhealthy provider handling', () => {
|
||||
];
|
||||
|
||||
const service2 = makeService(unhealthyRules, {
|
||||
anthropic: { status: 'healthy' },
|
||||
anthropic: { status: 'up' },
|
||||
openai: { status: 'down' },
|
||||
});
|
||||
|
||||
@@ -313,7 +306,7 @@ describe('RoutingEngineService.resolve — unhealthy provider handling', () => {
|
||||
|
||||
const service = makeService(rules, {
|
||||
anthropic: { status: 'down' }, // Sonnet is on anthropic — down
|
||||
ollama: { status: 'healthy' }, // Haiku is also on anthropic — use Ollama as next
|
||||
ollama: { status: 'up' }, // Haiku is also on anthropic — use Ollama as next
|
||||
});
|
||||
|
||||
const decision = await service.resolve('hello there');
|
||||
@@ -352,7 +345,7 @@ describe('RoutingEngineService.resolve — empty conditions (fallback rule)', ()
|
||||
}),
|
||||
];
|
||||
|
||||
const service = makeService(rules, { anthropic: { status: 'healthy' } });
|
||||
const service = makeService(rules, { anthropic: { status: 'up' } });
|
||||
|
||||
const decision = await service.resolve('completely unrelated message xyz');
|
||||
expect(decision.ruleName).toBe('catch-all');
|
||||
@@ -376,7 +369,7 @@ describe('RoutingEngineService.resolve — empty conditions (fallback rule)', ()
|
||||
}),
|
||||
];
|
||||
|
||||
const service = makeService(rules, { anthropic: { status: 'healthy' } });
|
||||
const service = makeService(rules, { anthropic: { status: 'up' } });
|
||||
|
||||
const codingDecision = await service.resolve('implement a function');
|
||||
expect(codingDecision.ruleName).toBe('specific coding rule');
|
||||
@@ -408,7 +401,7 @@ describe('RoutingEngineService.resolve — disabled rules', () => {
|
||||
}),
|
||||
];
|
||||
|
||||
const service = makeService(rules, { anthropic: { status: 'healthy' } });
|
||||
const service = makeService(rules, { anthropic: { status: 'up' } });
|
||||
|
||||
const decision = await service.resolve('implement a function');
|
||||
expect(decision.ruleName).toBe('enabled fallback');
|
||||
@@ -459,45 +452,9 @@ describe('RoutingEngineService.resolve — availableProviders override', () => {
|
||||
ps: unknown,
|
||||
) => RoutingEngineService)(mockDb, mockProviderService);
|
||||
|
||||
const preSupplied: Record<string, { status: ProviderHealthStatus }> = {
|
||||
anthropic: { status: 'healthy' },
|
||||
};
|
||||
const preSupplied = { anthropic: { status: 'up' } };
|
||||
await service.resolve('implement a function', undefined, preSupplied);
|
||||
|
||||
expect(mockHealthCheckAll).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── resolve — canonical ProviderHealthStatus values ──────────────────────────
|
||||
|
||||
describe('RoutingEngineService.resolve — canonical health status routing', () => {
|
||||
it('routes healthy and degraded providers by rule, and falls through to fallback when down', async () => {
|
||||
const codingRule = makeRule({
|
||||
name: 'coding rule',
|
||||
priority: 1,
|
||||
conditions: [{ field: 'taskType', operator: 'eq', value: 'coding' }],
|
||||
action: { provider: 'openai', model: 'gpt-4o' },
|
||||
});
|
||||
|
||||
// healthy → selected by its own rule, not the fallback chain
|
||||
const healthyService = makeService([codingRule], { openai: { status: 'healthy' } });
|
||||
const healthyDecision = await healthyService.resolve('implement a function');
|
||||
expect(healthyDecision.ruleName).toBe('coding rule');
|
||||
expect(healthyDecision.provider).toBe('openai');
|
||||
|
||||
// down → rule is skipped as unroutable, falls through to the fallback chain
|
||||
const downService = makeService([codingRule], {
|
||||
openai: { status: 'down' },
|
||||
anthropic: { status: 'healthy' },
|
||||
});
|
||||
const downDecision = await downService.resolve('implement a function');
|
||||
expect(downDecision.ruleName).toBe('fallback');
|
||||
expect(downDecision.provider).toBe('anthropic');
|
||||
|
||||
// degraded → still routable, selected by its own rule, not the fallback chain
|
||||
const degradedService = makeService([codingRule], { openai: { status: 'degraded' } });
|
||||
const degradedDecision = await degradedService.resolve('implement a function');
|
||||
expect(degradedDecision.ruleName).toBe('coding rule');
|
||||
expect(degradedDecision.provider).toBe('openai');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
import { Catch, type ArgumentsHost, type ExceptionFilter } from '@nestjs/common';
|
||||
import { RuntimeApprovalDeniedError } from './runtime-provider-registry.service.js';
|
||||
|
||||
/** Maps a consumed/missing runtime approval to a stable HTTP authorization response. */
|
||||
@Catch(RuntimeApprovalDeniedError)
|
||||
export class RuntimeApprovalDeniedFilter implements ExceptionFilter {
|
||||
catch(_exception: RuntimeApprovalDeniedError, host: ArgumentsHost): void {
|
||||
const response = host.switchToHttp().getResponse<{
|
||||
status(code: number): { send(body: { statusCode: number; message: string }): void };
|
||||
}>();
|
||||
response.status(403).send({ statusCode: 403, message: 'Runtime termination approval denied' });
|
||||
}
|
||||
}
|
||||
@@ -1,500 +0,0 @@
|
||||
import { ForbiddenException, Inject, Injectable, Logger, NotFoundException } from '@nestjs/common';
|
||||
import { AgentRuntimeProviderRegistry } from '@mosaicstack/agent';
|
||||
import {
|
||||
createRuntimeAuditLogEntry,
|
||||
type LogService,
|
||||
type RuntimeAuditErrorCode,
|
||||
} from '@mosaicstack/log';
|
||||
import type {
|
||||
AgentRuntimeProvider,
|
||||
RuntimeAttachHandle,
|
||||
RuntimeAttachMode,
|
||||
RuntimeCapability,
|
||||
RuntimeCapabilitySet,
|
||||
RuntimeHealth,
|
||||
RuntimeMessage,
|
||||
RuntimeScope,
|
||||
RuntimeSession,
|
||||
RuntimeSessionTree,
|
||||
RuntimeStreamEvent,
|
||||
TransitionalCapabilityInventoryEntry,
|
||||
TransitionalCapabilityInventoryProvider,
|
||||
} from '@mosaicstack/types';
|
||||
import type { ActorTenantScope } from '../auth/session-scope.js';
|
||||
import { LOG_SERVICE } from '../log/log.tokens.js';
|
||||
|
||||
export const AGENT_RUNTIME_PROVIDER_REGISTRY = Symbol('AGENT_RUNTIME_PROVIDER_REGISTRY');
|
||||
export const RUNTIME_PROVIDER_AUDIT_SINK = Symbol('RUNTIME_PROVIDER_AUDIT_SINK');
|
||||
export const RUNTIME_APPROVAL_VERIFIER = Symbol('RUNTIME_APPROVAL_VERIFIER');
|
||||
|
||||
export type RuntimeProviderOperation =
|
||||
| RuntimeCapability
|
||||
| 'runtime.capabilities'
|
||||
| 'runtime.health'
|
||||
| 'runtime.transitional-capabilities';
|
||||
export type RuntimeProviderAuditOutcome = 'requested' | 'succeeded' | 'denied' | 'failed';
|
||||
|
||||
/** Trusted server-side context only; it intentionally excludes client-provided identity fields. */
|
||||
export interface RuntimeProviderRequestContext {
|
||||
actorScope: ActorTenantScope;
|
||||
channelId: string;
|
||||
correlationId: string;
|
||||
}
|
||||
|
||||
/** Metadata-only audit record. Message bodies, idempotency keys, and approval refs are excluded. */
|
||||
export interface RuntimeAuditEvent {
|
||||
providerId: string;
|
||||
operation: RuntimeProviderOperation;
|
||||
outcome: RuntimeProviderAuditOutcome;
|
||||
actorId: string;
|
||||
tenantId: string;
|
||||
channelId: string;
|
||||
correlationId: string;
|
||||
resourceId?: string;
|
||||
durationMs?: number;
|
||||
errorCode?: RuntimeAuditErrorCode;
|
||||
}
|
||||
|
||||
export interface RuntimeAuditSink {
|
||||
record(event: RuntimeAuditEvent): Promise<void>;
|
||||
}
|
||||
|
||||
/** Exact action shape that a durable approval implementation must consume once. */
|
||||
export interface RuntimeTerminationAction {
|
||||
providerId: string;
|
||||
sessionId: string;
|
||||
actorId: string;
|
||||
tenantId: string;
|
||||
channelId: string;
|
||||
correlationId: string;
|
||||
agentName: string;
|
||||
}
|
||||
|
||||
export interface RuntimeApprovalVerifier {
|
||||
consume(approvalRef: string, action: RuntimeTerminationAction): Promise<boolean>;
|
||||
}
|
||||
|
||||
function isTransitionalInventoryProvider(
|
||||
provider: AgentRuntimeProvider,
|
||||
): provider is AgentRuntimeProvider & TransitionalCapabilityInventoryProvider {
|
||||
return (
|
||||
typeof (provider as Partial<TransitionalCapabilityInventoryProvider>)
|
||||
.transitionalCapabilityMatrix === 'function'
|
||||
);
|
||||
}
|
||||
|
||||
function configuredAgentName(): string {
|
||||
const agentName = process.env['MOSAIC_AGENT_NAME']?.trim();
|
||||
if (!agentName) throw new RuntimeApprovalDeniedError();
|
||||
return agentName;
|
||||
}
|
||||
|
||||
export class RuntimeApprovalDeniedError extends Error {
|
||||
constructor() {
|
||||
super('Runtime termination approval denied');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The default denies all runtime termination until a durable, exact-action
|
||||
* approval implementation is configured. This is safer than a permissive stub.
|
||||
*/
|
||||
@Injectable()
|
||||
export class DenyRuntimeApprovalVerifier implements RuntimeApprovalVerifier {
|
||||
async consume(_approvalRef: string, _action: RuntimeTerminationAction): Promise<boolean> {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Temporary metadata-only audit sink. M1 observability can replace this token
|
||||
* with a durable audit writer without changing provider call sites.
|
||||
*/
|
||||
@Injectable()
|
||||
export class RuntimeProviderAuditService implements RuntimeAuditSink {
|
||||
private readonly logger = new Logger(RuntimeProviderAuditService.name);
|
||||
|
||||
constructor(@Inject(LOG_SERVICE) private readonly logService: LogService) {}
|
||||
|
||||
async record(event: RuntimeAuditEvent): Promise<void> {
|
||||
const entry = createRuntimeAuditLogEntry(event);
|
||||
await this.logService.logs.ingest(entry);
|
||||
this.logger.log(JSON.stringify({ event: entry.content, metadata: entry.metadata }));
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class RuntimeProviderService {
|
||||
private readonly logger = new Logger(RuntimeProviderService.name);
|
||||
|
||||
constructor(
|
||||
@Inject(AGENT_RUNTIME_PROVIDER_REGISTRY)
|
||||
private readonly registry: AgentRuntimeProviderRegistry,
|
||||
@Inject(RUNTIME_PROVIDER_AUDIT_SINK)
|
||||
private readonly audit: RuntimeAuditSink,
|
||||
@Inject(RUNTIME_APPROVAL_VERIFIER)
|
||||
private readonly approvals: RuntimeApprovalVerifier,
|
||||
) {}
|
||||
|
||||
async capabilities(
|
||||
providerId: string,
|
||||
context: RuntimeProviderRequestContext,
|
||||
): Promise<RuntimeCapabilitySet> {
|
||||
return this.execute(
|
||||
providerId,
|
||||
'runtime.capabilities',
|
||||
undefined,
|
||||
undefined,
|
||||
context,
|
||||
(provider: AgentRuntimeProvider, scope: RuntimeScope): Promise<RuntimeCapabilitySet> =>
|
||||
provider.capabilities(scope),
|
||||
);
|
||||
}
|
||||
|
||||
async health(providerId: string, context: RuntimeProviderRequestContext): Promise<RuntimeHealth> {
|
||||
return this.execute(
|
||||
providerId,
|
||||
'runtime.health',
|
||||
undefined,
|
||||
undefined,
|
||||
context,
|
||||
(provider: AgentRuntimeProvider, scope: RuntimeScope): Promise<RuntimeHealth> =>
|
||||
provider.health(scope),
|
||||
);
|
||||
}
|
||||
|
||||
async transitionalCapabilityMatrix(
|
||||
providerId: string,
|
||||
context: RuntimeProviderRequestContext,
|
||||
): Promise<TransitionalCapabilityInventoryEntry[]> {
|
||||
return this.execute(
|
||||
providerId,
|
||||
'runtime.transitional-capabilities',
|
||||
undefined,
|
||||
undefined,
|
||||
context,
|
||||
async (provider: AgentRuntimeProvider, scope: RuntimeScope) => {
|
||||
if (!isTransitionalInventoryProvider(provider)) {
|
||||
throw new NotFoundException('Runtime provider has no transitional capability inventory');
|
||||
}
|
||||
return provider.transitionalCapabilityMatrix(scope);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async listSessions(
|
||||
providerId: string,
|
||||
context: RuntimeProviderRequestContext,
|
||||
): Promise<RuntimeSession[]> {
|
||||
return this.execute(
|
||||
providerId,
|
||||
'session.list',
|
||||
'session.list',
|
||||
undefined,
|
||||
context,
|
||||
(provider: AgentRuntimeProvider, scope: RuntimeScope): Promise<RuntimeSession[]> =>
|
||||
provider.listSessions(scope),
|
||||
);
|
||||
}
|
||||
|
||||
async getSessionTree(
|
||||
providerId: string,
|
||||
context: RuntimeProviderRequestContext,
|
||||
): Promise<RuntimeSessionTree[]> {
|
||||
return this.execute(
|
||||
providerId,
|
||||
'session.tree',
|
||||
'session.tree',
|
||||
undefined,
|
||||
context,
|
||||
(provider: AgentRuntimeProvider, scope: RuntimeScope): Promise<RuntimeSessionTree[]> =>
|
||||
provider.getSessionTree(scope),
|
||||
);
|
||||
}
|
||||
|
||||
streamSession(
|
||||
providerId: string,
|
||||
sessionId: string,
|
||||
cursor: string | undefined,
|
||||
context: RuntimeProviderRequestContext,
|
||||
): AsyncIterable<RuntimeStreamEvent> {
|
||||
return this.stream(
|
||||
providerId,
|
||||
'session.stream',
|
||||
'session.stream',
|
||||
sessionId,
|
||||
context,
|
||||
(provider: AgentRuntimeProvider, scope: RuntimeScope): AsyncIterable<RuntimeStreamEvent> =>
|
||||
provider.streamSession(sessionId, cursor, scope),
|
||||
);
|
||||
}
|
||||
|
||||
async sendMessage(
|
||||
providerId: string,
|
||||
sessionId: string,
|
||||
message: RuntimeMessage,
|
||||
context: RuntimeProviderRequestContext,
|
||||
): Promise<void> {
|
||||
await this.execute(
|
||||
providerId,
|
||||
'session.send',
|
||||
'session.send',
|
||||
sessionId,
|
||||
context,
|
||||
(provider: AgentRuntimeProvider, scope: RuntimeScope): Promise<void> =>
|
||||
provider.sendMessage(sessionId, message, scope),
|
||||
);
|
||||
}
|
||||
|
||||
async attach(
|
||||
providerId: string,
|
||||
sessionId: string,
|
||||
mode: RuntimeAttachMode,
|
||||
context: RuntimeProviderRequestContext,
|
||||
): Promise<RuntimeAttachHandle> {
|
||||
return this.execute(
|
||||
providerId,
|
||||
'session.attach',
|
||||
'session.attach',
|
||||
sessionId,
|
||||
context,
|
||||
(provider: AgentRuntimeProvider, scope: RuntimeScope): Promise<RuntimeAttachHandle> =>
|
||||
provider.attach(sessionId, mode, scope),
|
||||
);
|
||||
}
|
||||
|
||||
async detach(
|
||||
providerId: string,
|
||||
attachmentId: string,
|
||||
context: RuntimeProviderRequestContext,
|
||||
): Promise<void> {
|
||||
await this.execute(
|
||||
providerId,
|
||||
'session.attach',
|
||||
'session.attach',
|
||||
attachmentId,
|
||||
context,
|
||||
(provider: AgentRuntimeProvider, scope: RuntimeScope): Promise<void> =>
|
||||
provider.detach(attachmentId, scope),
|
||||
);
|
||||
}
|
||||
|
||||
async terminate(
|
||||
providerId: string,
|
||||
sessionId: string,
|
||||
approvalRef: string,
|
||||
context: RuntimeProviderRequestContext,
|
||||
): Promise<void> {
|
||||
await this.execute(
|
||||
providerId,
|
||||
'session.terminate',
|
||||
'session.terminate',
|
||||
sessionId,
|
||||
context,
|
||||
async (provider: AgentRuntimeProvider, scope: RuntimeScope): Promise<void> => {
|
||||
const approved = await this.approvals.consume(approvalRef, {
|
||||
providerId,
|
||||
sessionId,
|
||||
actorId: scope.actorId,
|
||||
tenantId: scope.tenantId,
|
||||
channelId: scope.channelId,
|
||||
correlationId: scope.correlationId,
|
||||
agentName: configuredAgentName(),
|
||||
});
|
||||
if (!approved) {
|
||||
throw new RuntimeApprovalDeniedError();
|
||||
}
|
||||
await provider.terminate(sessionId, approvalRef, scope);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private async execute<T>(
|
||||
providerId: string,
|
||||
operation: RuntimeProviderOperation,
|
||||
requiredCapability: RuntimeCapability | undefined,
|
||||
resourceId: string | undefined,
|
||||
context: RuntimeProviderRequestContext,
|
||||
invoke: (provider: AgentRuntimeProvider, scope: RuntimeScope) => Promise<T>,
|
||||
): Promise<T> {
|
||||
const scope = this.deriveScope(context);
|
||||
const startedAt = Date.now();
|
||||
await this.record(providerId, operation, 'requested', scope, resourceId);
|
||||
let invocationStarted = false;
|
||||
try {
|
||||
const provider = this.provider(providerId);
|
||||
if (requiredCapability) {
|
||||
await this.assertCapability(provider, requiredCapability, scope);
|
||||
}
|
||||
invocationStarted = true;
|
||||
const result = await invoke(provider, scope);
|
||||
await this.recordCompletion(providerId, operation, scope, resourceId, Date.now() - startedAt);
|
||||
return result;
|
||||
} catch (error: unknown) {
|
||||
const durationMs = Date.now() - startedAt;
|
||||
if (invocationStarted && !this.isAuthorizationDenied(error)) {
|
||||
await this.recordFailure(providerId, operation, scope, resourceId, durationMs);
|
||||
} else {
|
||||
await this.record(
|
||||
providerId,
|
||||
operation,
|
||||
'denied',
|
||||
scope,
|
||||
resourceId,
|
||||
durationMs,
|
||||
'policy_denied',
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private async *stream(
|
||||
providerId: string,
|
||||
operation: RuntimeProviderOperation,
|
||||
requiredCapability: RuntimeCapability,
|
||||
resourceId: string,
|
||||
context: RuntimeProviderRequestContext,
|
||||
invoke: (
|
||||
provider: AgentRuntimeProvider,
|
||||
scope: RuntimeScope,
|
||||
) => AsyncIterable<RuntimeStreamEvent>,
|
||||
): AsyncIterable<RuntimeStreamEvent> {
|
||||
const scope = this.deriveScope(context);
|
||||
const startedAt = Date.now();
|
||||
await this.record(providerId, operation, 'requested', scope, resourceId);
|
||||
let invocationStarted = false;
|
||||
try {
|
||||
const provider = this.provider(providerId);
|
||||
await this.assertCapability(provider, requiredCapability, scope);
|
||||
invocationStarted = true;
|
||||
for await (const event of invoke(provider, scope)) {
|
||||
yield event;
|
||||
}
|
||||
await this.recordCompletion(providerId, operation, scope, resourceId, Date.now() - startedAt);
|
||||
} catch (error: unknown) {
|
||||
const durationMs = Date.now() - startedAt;
|
||||
if (invocationStarted) {
|
||||
await this.recordFailure(providerId, operation, scope, resourceId, durationMs);
|
||||
} else {
|
||||
await this.record(
|
||||
providerId,
|
||||
operation,
|
||||
'denied',
|
||||
scope,
|
||||
resourceId,
|
||||
durationMs,
|
||||
'policy_denied',
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private isAuthorizationDenied(error: unknown): boolean {
|
||||
return (
|
||||
error instanceof RuntimeApprovalDeniedError ||
|
||||
error instanceof ForbiddenException ||
|
||||
(typeof error === 'object' &&
|
||||
error !== null &&
|
||||
'code' in error &&
|
||||
(error as { code?: unknown }).code === 'forbidden')
|
||||
);
|
||||
}
|
||||
|
||||
private provider(providerId: string): AgentRuntimeProvider {
|
||||
try {
|
||||
return this.registry.require(providerId);
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : 'Runtime provider is not registered';
|
||||
throw new NotFoundException(message);
|
||||
}
|
||||
}
|
||||
|
||||
private async assertCapability(
|
||||
provider: AgentRuntimeProvider,
|
||||
requiredCapability: RuntimeCapability,
|
||||
scope: RuntimeScope,
|
||||
): Promise<void> {
|
||||
const capabilities = await provider.capabilities(scope);
|
||||
if (!capabilities.supported.includes(requiredCapability)) {
|
||||
throw new ForbiddenException(`Runtime provider capability denied: ${requiredCapability}`);
|
||||
}
|
||||
}
|
||||
|
||||
private deriveScope(context: RuntimeProviderRequestContext): RuntimeScope {
|
||||
const actorId = context.actorScope.userId.trim();
|
||||
const tenantId = context.actorScope.tenantId.trim();
|
||||
const channelId = context.channelId.trim();
|
||||
const correlationId = context.correlationId.trim();
|
||||
if (!actorId || !tenantId || !channelId || !correlationId) {
|
||||
throw new ForbiddenException(
|
||||
'Authenticated runtime actor scope and correlation are required',
|
||||
);
|
||||
}
|
||||
return Object.freeze({ actorId, tenantId, channelId, correlationId });
|
||||
}
|
||||
|
||||
private async recordFailure(
|
||||
providerId: string,
|
||||
operation: RuntimeProviderOperation,
|
||||
scope: RuntimeScope,
|
||||
resourceId: string | undefined,
|
||||
durationMs: number,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await this.record(
|
||||
providerId,
|
||||
operation,
|
||||
'failed',
|
||||
scope,
|
||||
resourceId,
|
||||
durationMs,
|
||||
'provider_error',
|
||||
);
|
||||
} catch {
|
||||
this.logger.error(
|
||||
`Runtime provider failure audit failed provider=${providerId} operation=${operation} correlation=${scope.correlationId}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async recordCompletion(
|
||||
providerId: string,
|
||||
operation: RuntimeProviderOperation,
|
||||
scope: RuntimeScope,
|
||||
resourceId: string | undefined,
|
||||
durationMs: number,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await this.record(providerId, operation, 'succeeded', scope, resourceId, durationMs);
|
||||
} catch {
|
||||
this.logger.error(
|
||||
`Runtime provider completion audit failed provider=${providerId} operation=${operation} correlation=${scope.correlationId}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async record(
|
||||
providerId: string,
|
||||
operation: RuntimeProviderOperation,
|
||||
outcome: RuntimeProviderAuditOutcome,
|
||||
scope: RuntimeScope,
|
||||
resourceId: string | undefined,
|
||||
durationMs?: number,
|
||||
errorCode?: RuntimeAuditErrorCode,
|
||||
): Promise<void> {
|
||||
await this.audit.record({
|
||||
providerId,
|
||||
operation,
|
||||
outcome,
|
||||
actorId: scope.actorId,
|
||||
tenantId: scope.tenantId,
|
||||
channelId: scope.channelId,
|
||||
correlationId: scope.correlationId,
|
||||
...(resourceId ? { resourceId } : {}),
|
||||
...(durationMs !== undefined ? { durationMs } : {}),
|
||||
...(errorCode ? { errorCode } : {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -10,8 +10,6 @@ import {
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { AuthGuard } from '../auth/auth.guard.js';
|
||||
import { CurrentUser } from '../auth/current-user.decorator.js';
|
||||
import { scopeFromUser, type AuthenticatedUserLike } from '../auth/session-scope.js';
|
||||
import { AgentService } from './agent.service.js';
|
||||
|
||||
@Controller('api/sessions')
|
||||
@@ -20,24 +18,23 @@ export class SessionsController {
|
||||
constructor(@Inject(AgentService) private readonly agentService: AgentService) {}
|
||||
|
||||
@Get()
|
||||
list(@CurrentUser() user: AuthenticatedUserLike) {
|
||||
const sessions = this.agentService.listSessions(scopeFromUser(user));
|
||||
list() {
|
||||
const sessions = this.agentService.listSessions();
|
||||
return { sessions, total: sessions.length };
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
findOne(@Param('id') id: string, @CurrentUser() user: AuthenticatedUserLike) {
|
||||
const info = this.agentService.getSessionInfo(id, scopeFromUser(user));
|
||||
findOne(@Param('id') id: string) {
|
||||
const info = this.agentService.getSessionInfo(id);
|
||||
if (!info) throw new NotFoundException('Session not found');
|
||||
return info;
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@HttpCode(HttpStatus.NO_CONTENT)
|
||||
async destroy(@Param('id') id: string, @CurrentUser() user: AuthenticatedUserLike) {
|
||||
const scope = scopeFromUser(user);
|
||||
const info = this.agentService.getSessionInfo(id, scope);
|
||||
async destroy(@Param('id') id: string) {
|
||||
const info = this.agentService.getSessionInfo(id);
|
||||
if (!info) throw new NotFoundException('Session not found');
|
||||
await this.agentService.destroySession(id, scope);
|
||||
await this.agentService.destroySession(id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { createMemoryTools } from './memory-tools.js';
|
||||
|
||||
describe('createMemoryTools operator retrieval binding', () => {
|
||||
const memory = {
|
||||
insights: { searchByEmbedding: vi.fn(), create: vi.fn() },
|
||||
preferences: { findByUserAndCategory: vi.fn(), findByUser: vi.fn(), upsert: vi.fn() },
|
||||
};
|
||||
const scope = { tenantId: 'tenant-a', ownerId: 'owner-a', sessionId: 'session-a' };
|
||||
|
||||
it('uses the configured plugin with the server-derived scope for retrieval and capture', async () => {
|
||||
const plugin = {
|
||||
search: vi.fn(async () => []),
|
||||
capture: vi.fn(async () => ({ id: 'insight-1' })),
|
||||
};
|
||||
const tools = createMemoryTools(memory as never, null, 'owner-a', {
|
||||
plugin: plugin as never,
|
||||
scope,
|
||||
});
|
||||
|
||||
await tools
|
||||
.find((tool) => tool.name === 'memory_search')!
|
||||
.execute('call-1', { query: 'plans' }, undefined, undefined, {} as never);
|
||||
await tools
|
||||
.find((tool) => tool.name === 'memory_save_insight')!
|
||||
.execute(
|
||||
'call-2',
|
||||
{ content: 'secret', category: 'decision' },
|
||||
undefined,
|
||||
undefined,
|
||||
{} as never,
|
||||
);
|
||||
|
||||
expect(plugin.search).toHaveBeenCalledWith(scope, 'plans', 5);
|
||||
expect(plugin.capture).toHaveBeenCalledWith(scope, {
|
||||
content: 'secret',
|
||||
source: 'agent',
|
||||
category: 'decision',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,7 @@
|
||||
import { Type } from '@sinclair/typebox';
|
||||
import type { ToolDefinition } from '@mariozechner/pi-coding-agent';
|
||||
import type {
|
||||
EmbeddingProvider,
|
||||
Memory,
|
||||
OperatorMemoryPlugin,
|
||||
OperatorMemoryScope,
|
||||
} from '@mosaicstack/memory';
|
||||
import type { Memory } from '@mosaicstack/memory';
|
||||
import type { EmbeddingProvider } from '@mosaicstack/memory';
|
||||
|
||||
/**
|
||||
* Create memory tools bound to the session's authenticated userId.
|
||||
@@ -17,10 +13,8 @@ import type {
|
||||
export function createMemoryTools(
|
||||
memory: Memory,
|
||||
embeddingProvider: EmbeddingProvider | null,
|
||||
/** Authenticated user ID from the session. All preference operations are scoped to this user. */
|
||||
/** Authenticated user ID from the session. All memory operations are scoped to this user. */
|
||||
sessionUserId: string | undefined,
|
||||
/** Optional configured retrieval plugin, bound to a server-derived session scope. */
|
||||
operatorMemory?: { plugin: OperatorMemoryPlugin; scope: OperatorMemoryScope },
|
||||
): ToolDefinition[] {
|
||||
/** Return an error result when no session user is bound. */
|
||||
function noUserError() {
|
||||
@@ -52,14 +46,6 @@ export function createMemoryTools(
|
||||
limit?: number;
|
||||
};
|
||||
|
||||
if (operatorMemory) {
|
||||
const results = await operatorMemory.plugin.search(operatorMemory.scope, query, limit ?? 5);
|
||||
return {
|
||||
content: [{ type: 'text' as const, text: JSON.stringify(results, null, 2) }],
|
||||
details: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
if (!embeddingProvider) {
|
||||
return {
|
||||
content: [
|
||||
@@ -172,18 +158,6 @@ export function createMemoryTools(
|
||||
};
|
||||
type Cat = 'decision' | 'learning' | 'preference' | 'fact' | 'pattern' | 'general';
|
||||
|
||||
if (operatorMemory) {
|
||||
const insight = await operatorMemory.plugin.capture(operatorMemory.scope, {
|
||||
content,
|
||||
source: 'agent',
|
||||
category: category ?? 'learning',
|
||||
});
|
||||
return {
|
||||
content: [{ type: 'text' as const, text: JSON.stringify(insight, null, 2) }],
|
||||
details: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
let embedding: number[] | null = null;
|
||||
if (embeddingProvider) {
|
||||
embedding = await embeddingProvider.embed(content);
|
||||
|
||||
@@ -1,624 +0,0 @@
|
||||
import 'reflect-metadata';
|
||||
import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
||||
import * as nodeOs from 'node:os';
|
||||
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
||||
import * as nodeUrl from 'node:url';
|
||||
import { MODULE_METADATA } from '@nestjs/common/constants.js';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import type { MosaicConfig } from '@mosaicstack/config';
|
||||
|
||||
interface ComposedModuleGraph {
|
||||
imports: readonly unknown[];
|
||||
federationModule: unknown;
|
||||
bootLogLines: readonly string[];
|
||||
mosaicConfig: MosaicConfig;
|
||||
resolvedConfigPath: string;
|
||||
}
|
||||
|
||||
type StorageTier = 'local' | 'standalone' | 'federated';
|
||||
|
||||
interface ModuleGraphFixture {
|
||||
tempRoot: string;
|
||||
anchor: string;
|
||||
homePath: string;
|
||||
cwdPath: string;
|
||||
monorepoRootEnvPath: string;
|
||||
gatewayLocalEnvPath: string;
|
||||
daemonEnvPath: string;
|
||||
monorepoRootConfigPath: string;
|
||||
gatewayLocalConfigPath: string;
|
||||
}
|
||||
|
||||
interface ModuleGraphFixtureOptions {
|
||||
rootEnvMode?: 'present' | 'absent';
|
||||
rootTier?: StorageTier;
|
||||
rootEnvContents?: string;
|
||||
redactionMarker?: string;
|
||||
gatewayLocalTier?: StorageTier;
|
||||
gatewayLocalEnvContents?: string;
|
||||
daemonEnvContents?: string;
|
||||
inheritedTier?: StorageTier;
|
||||
expectedProcessTier?: string;
|
||||
setup?: (fixture: ModuleGraphFixture) => Promise<void>;
|
||||
}
|
||||
|
||||
// Each case uses vi.resetModules() and re-imports the full gateway graph for distinct ambient FS/env; CI needs headroom, while this still guards genuine hangs.
|
||||
const MODULE_IMPORT_TIMEOUT_MS = 120_000;
|
||||
const MONOREPO_ROOT_DOTENV_LABEL = 'monorepo-root .env';
|
||||
const DAEMON_DOTENV_LABEL = 'daemon .env';
|
||||
|
||||
function configJson(tier: StorageTier): string {
|
||||
if (tier === 'local') {
|
||||
return JSON.stringify({
|
||||
tier,
|
||||
storage: { type: 'pglite', dataDir: '.mosaic/storage-pglite' },
|
||||
queue: { type: 'local', dataDir: '.mosaic/queue' },
|
||||
memory: { type: 'keyword' },
|
||||
});
|
||||
}
|
||||
|
||||
return JSON.stringify({
|
||||
tier,
|
||||
storage: { type: 'postgres', url: 'postgresql://fixture.invalid/mosaic' },
|
||||
queue: { type: 'bullmq' },
|
||||
memory: { type: tier === 'federated' ? 'pgvector' : 'keyword' },
|
||||
});
|
||||
}
|
||||
|
||||
function snapshotProcessEnv(): Record<string, string | undefined> {
|
||||
return { ...process.env };
|
||||
}
|
||||
|
||||
function restoreProcessEnv(snapshot: Record<string, string | undefined>): void {
|
||||
for (const key of Object.keys(process.env)) {
|
||||
if (!(key in snapshot)) {
|
||||
delete process.env[key];
|
||||
}
|
||||
}
|
||||
|
||||
for (const [key, value] of Object.entries(snapshot)) {
|
||||
if (value === undefined) {
|
||||
delete process.env[key];
|
||||
continue;
|
||||
}
|
||||
|
||||
process.env[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
function expectPathUnderTempRoot(path: string, tempRoot: string): void {
|
||||
const relativePath = relative(tempRoot, path);
|
||||
expect(relativePath === '' || (!relativePath.startsWith('..') && !isAbsolute(relativePath))).toBe(
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
async function writeFixture(path: string, contents: string, tempRoot: string): Promise<void> {
|
||||
expectPathUnderTempRoot(path, tempRoot);
|
||||
await mkdir(dirname(path), { recursive: true });
|
||||
await writeFile(path, contents, 'utf8');
|
||||
}
|
||||
|
||||
interface ConfigModuleProvider {
|
||||
provide: string;
|
||||
useFactory: () => MosaicConfig;
|
||||
}
|
||||
|
||||
function isConfigModuleProvider(value: unknown): value is ConfigModuleProvider {
|
||||
if (typeof value !== 'object' || value === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!('provide' in value) || typeof value.provide !== 'string') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return 'useFactory' in value && typeof value.useFactory === 'function';
|
||||
}
|
||||
|
||||
function singleBootLogLine(bootLogLines: readonly string[]): string {
|
||||
expect(bootLogLines).toHaveLength(1);
|
||||
const [bootLogLine] = bootLogLines;
|
||||
if (bootLogLine === undefined) {
|
||||
throw new Error('Expected a single boot log line');
|
||||
}
|
||||
|
||||
return bootLogLine;
|
||||
}
|
||||
|
||||
function expectBootLogLine(
|
||||
bootLogLines: readonly string[],
|
||||
tier: StorageTier,
|
||||
source: string,
|
||||
): void {
|
||||
const bootLogLine = singleBootLogLine(bootLogLines);
|
||||
|
||||
expect(bootLogLine).toContain(`storage tier=${tier}`);
|
||||
expect(bootLogLine).toContain(`source=${source}`);
|
||||
}
|
||||
|
||||
async function loadModuleGraphFromDotenv(
|
||||
options: ModuleGraphFixtureOptions,
|
||||
): Promise<ComposedModuleGraph> {
|
||||
const originalEnv = snapshotProcessEnv();
|
||||
const tempRoot = await mkdtemp(join(nodeOs.tmpdir(), 'mosaic-gateway-module-'));
|
||||
let consoleInfoSpy: ReturnType<typeof vi.spyOn> | undefined;
|
||||
let cwdSpy: ReturnType<typeof vi.spyOn> | undefined;
|
||||
|
||||
try {
|
||||
const anchor = join(tempRoot, 'anchored', 'apps', 'gateway', 'src');
|
||||
const homePath = join(tempRoot, 'home');
|
||||
const cwdPath = join(tempRoot, 'ambient', 'parent', 'cwd');
|
||||
const fixture: ModuleGraphFixture = {
|
||||
tempRoot,
|
||||
anchor,
|
||||
homePath,
|
||||
cwdPath,
|
||||
monorepoRootEnvPath: resolve(anchor, '../../..', '.env'),
|
||||
gatewayLocalEnvPath: resolve(anchor, '..', '.env'),
|
||||
daemonEnvPath: join(homePath, '.config', 'mosaic', 'gateway', '.env'),
|
||||
monorepoRootConfigPath: resolve(anchor, '../../..', 'mosaic.config.json'),
|
||||
gatewayLocalConfigPath: resolve(anchor, '..', 'mosaic.config.json'),
|
||||
};
|
||||
consoleInfoSpy = vi.spyOn(console, 'info').mockImplementation((): void => undefined);
|
||||
|
||||
for (const path of Object.values(fixture)) {
|
||||
expectPathUnderTempRoot(path, tempRoot);
|
||||
}
|
||||
|
||||
await mkdir(anchor, { recursive: true });
|
||||
await mkdir(cwdPath, { recursive: true });
|
||||
|
||||
if ((options.rootEnvMode ?? 'present') === 'absent') {
|
||||
if (
|
||||
options.rootEnvContents !== undefined ||
|
||||
options.rootTier !== undefined ||
|
||||
options.redactionMarker !== undefined
|
||||
) {
|
||||
throw new Error('Expected no root env fixture values when rootEnvMode is absent');
|
||||
}
|
||||
} else {
|
||||
if (options.rootEnvContents === undefined && options.rootTier === undefined) {
|
||||
throw new Error('Expected rootTier or rootEnvContents');
|
||||
}
|
||||
|
||||
const rootFixture = options.rootEnvContents ?? `MOSAIC_STORAGE_TIER=${options.rootTier}\n`;
|
||||
const rootFixtureWithMarker = options.redactionMarker
|
||||
? `${rootFixture}BETTER_AUTH_SECRET=${options.redactionMarker}\n`
|
||||
: rootFixture;
|
||||
await writeFixture(fixture.monorepoRootEnvPath, rootFixtureWithMarker, tempRoot);
|
||||
}
|
||||
|
||||
if (options.daemonEnvContents !== undefined) {
|
||||
await writeFixture(fixture.daemonEnvPath, options.daemonEnvContents, tempRoot);
|
||||
}
|
||||
|
||||
if (options.gatewayLocalEnvContents !== undefined) {
|
||||
await writeFixture(fixture.gatewayLocalEnvPath, options.gatewayLocalEnvContents, tempRoot);
|
||||
} else if (options.gatewayLocalTier !== undefined) {
|
||||
await writeFixture(
|
||||
fixture.gatewayLocalEnvPath,
|
||||
`MOSAIC_STORAGE_TIER=${options.gatewayLocalTier}\n`,
|
||||
tempRoot,
|
||||
);
|
||||
}
|
||||
|
||||
process.env['HOME'] = homePath;
|
||||
delete process.env['MOSAIC_STORAGE_TIER'];
|
||||
delete process.env['DATABASE_URL'];
|
||||
delete process.env['VALKEY_URL'];
|
||||
delete process.env['MOSAIC_GATEWAY_HOME'];
|
||||
|
||||
await options.setup?.(fixture);
|
||||
|
||||
if (options.inheritedTier !== undefined) {
|
||||
process.env['MOSAIC_STORAGE_TIER'] = options.inheritedTier;
|
||||
}
|
||||
|
||||
vi.resetModules();
|
||||
vi.doMock('node:os', () => ({ ...nodeOs, homedir: (): string => homePath }));
|
||||
vi.doMock('node:url', () => ({
|
||||
...nodeUrl,
|
||||
fileURLToPath: (url: string | URL): string => {
|
||||
const actualPath = nodeUrl.fileURLToPath(url);
|
||||
if (
|
||||
actualPath.endsWith('/apps/gateway/src/env.ts') ||
|
||||
actualPath.endsWith('/apps/gateway/src/env.js')
|
||||
) {
|
||||
return join(anchor, 'env.ts');
|
||||
}
|
||||
return actualPath;
|
||||
},
|
||||
}));
|
||||
cwdSpy = vi.spyOn(process, 'cwd').mockReturnValue(cwdPath);
|
||||
|
||||
if (options.inheritedTier === undefined) {
|
||||
expect(process.env['MOSAIC_STORAGE_TIER']).toBeUndefined();
|
||||
} else {
|
||||
expect(process.env['MOSAIC_STORAGE_TIER']).toBe(options.inheritedTier);
|
||||
}
|
||||
|
||||
const envModule = await import('./env.js');
|
||||
expect(process.env['MOSAIC_STORAGE_TIER']).toBe(
|
||||
options.expectedProcessTier ?? options.rootTier,
|
||||
);
|
||||
|
||||
const { AppModule } = await import('./app.module.js');
|
||||
const { FederationModule } = await import('./federation/federation.module.js');
|
||||
const imports: unknown = Reflect.getMetadata(MODULE_METADATA.IMPORTS, AppModule);
|
||||
|
||||
if (!Array.isArray(imports)) {
|
||||
throw new Error('AppModule imports metadata is not an array');
|
||||
}
|
||||
|
||||
const { ConfigModule, MOSAIC_CONFIG } = await import('./config/config.module.js');
|
||||
const providers: unknown = Reflect.getMetadata(MODULE_METADATA.PROVIDERS, ConfigModule);
|
||||
|
||||
if (!Array.isArray(providers)) {
|
||||
throw new Error('ConfigModule providers metadata is not an array');
|
||||
}
|
||||
|
||||
const configProvider = providers
|
||||
.filter(isConfigModuleProvider)
|
||||
.find((provider: ConfigModuleProvider): boolean => provider.provide === MOSAIC_CONFIG);
|
||||
|
||||
if (!configProvider) {
|
||||
throw new Error('MOSAIC_CONFIG provider factory not found');
|
||||
}
|
||||
|
||||
return {
|
||||
imports,
|
||||
federationModule: FederationModule,
|
||||
bootLogLines: consoleInfoSpy.mock.calls.map((args: readonly unknown[]): string =>
|
||||
args.map((value: unknown): string => String(value)).join(' '),
|
||||
),
|
||||
mosaicConfig: configProvider.useFactory(),
|
||||
resolvedConfigPath: envModule.resolveGatewayConfigPath(),
|
||||
};
|
||||
} finally {
|
||||
cwdSpy?.mockRestore();
|
||||
vi.doUnmock('node:url');
|
||||
vi.doUnmock('node:os');
|
||||
vi.resetModules();
|
||||
consoleInfoSpy?.mockRestore();
|
||||
restoreProcessEnv(originalEnv);
|
||||
await rm(tempRoot, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
describe('AppModule federation gating', (): void => {
|
||||
it('loads dotenv before tracing and AppModule evaluation', async (): Promise<void> => {
|
||||
const mainSource = await readFile(new URL('./main.ts', import.meta.url), 'utf8');
|
||||
const envImportIndex = mainSource.indexOf("import './env.js';");
|
||||
const tracingImportIndex = mainSource.indexOf("import './tracing.js';");
|
||||
const appModuleImportIndex = mainSource.indexOf("import { AppModule } from './app.module.js';");
|
||||
|
||||
expect(envImportIndex).toBeGreaterThan(-1);
|
||||
expect(envImportIndex).toBeLessThan(tracingImportIndex);
|
||||
expect(envImportIndex).toBeLessThan(appModuleImportIndex);
|
||||
});
|
||||
|
||||
it(
|
||||
'ignores ambient cwd/.env and cwd/../.env files',
|
||||
async (): Promise<void> => {
|
||||
const graph = await loadModuleGraphFromDotenv({
|
||||
rootTier: 'local',
|
||||
setup: async (fixture: ModuleGraphFixture): Promise<void> => {
|
||||
await writeFixture(
|
||||
join(fixture.cwdPath, '.env'),
|
||||
'MOSAIC_STORAGE_TIER=federated\n',
|
||||
fixture.tempRoot,
|
||||
);
|
||||
await writeFixture(
|
||||
resolve(fixture.cwdPath, '..', '.env'),
|
||||
'MOSAIC_STORAGE_TIER=federated\n',
|
||||
fixture.tempRoot,
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
expect(graph.imports).not.toContain(graph.federationModule);
|
||||
expectBootLogLine(graph.bootLogLines, 'local', MONOREPO_ROOT_DOTENV_LABEL);
|
||||
},
|
||||
MODULE_IMPORT_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it(
|
||||
'ignores an ambient cwd/mosaic.config.json federated config',
|
||||
async (): Promise<void> => {
|
||||
const graph = await loadModuleGraphFromDotenv({
|
||||
rootTier: 'local',
|
||||
setup: async (fixture: ModuleGraphFixture): Promise<void> => {
|
||||
await writeFixture(
|
||||
join(fixture.cwdPath, 'mosaic.config.json'),
|
||||
configJson('federated'),
|
||||
fixture.tempRoot,
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
expect(graph.imports).not.toContain(graph.federationModule);
|
||||
expectBootLogLine(graph.bootLogLines, 'local', MONOREPO_ROOT_DOTENV_LABEL);
|
||||
},
|
||||
MODULE_IMPORT_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it(
|
||||
'ignores an ambient cwd/../../mosaic.config.json federated config',
|
||||
async (): Promise<void> => {
|
||||
const graph = await loadModuleGraphFromDotenv({
|
||||
rootTier: 'local',
|
||||
setup: async (fixture: ModuleGraphFixture): Promise<void> => {
|
||||
await writeFixture(
|
||||
resolve(fixture.cwdPath, '../..', 'mosaic.config.json'),
|
||||
configJson('federated'),
|
||||
fixture.tempRoot,
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
expect(graph.imports).not.toContain(graph.federationModule);
|
||||
expectBootLogLine(graph.bootLogLines, 'local', MONOREPO_ROOT_DOTENV_LABEL);
|
||||
},
|
||||
MODULE_IMPORT_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it(
|
||||
'anchored gateway-local config wins monorepo-root config and registers FederationModule',
|
||||
async (): Promise<void> => {
|
||||
let gatewayLocalConfigPath = '';
|
||||
const graph = await loadModuleGraphFromDotenv({
|
||||
rootTier: 'local',
|
||||
setup: async (fixture: ModuleGraphFixture): Promise<void> => {
|
||||
gatewayLocalConfigPath = fixture.gatewayLocalConfigPath;
|
||||
await writeFixture(
|
||||
fixture.gatewayLocalConfigPath,
|
||||
configJson('federated'),
|
||||
fixture.tempRoot,
|
||||
);
|
||||
await writeFixture(fixture.monorepoRootConfigPath, configJson('local'), fixture.tempRoot);
|
||||
},
|
||||
});
|
||||
|
||||
expect(graph.resolvedConfigPath).toBe(gatewayLocalConfigPath);
|
||||
expect(graph.mosaicConfig.tier).toBe('federated');
|
||||
expect(graph.imports).toContain(graph.federationModule);
|
||||
expectBootLogLine(graph.bootLogLines, 'federated', 'mosaic.config.json');
|
||||
},
|
||||
MODULE_IMPORT_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it(
|
||||
'resolves the daemon-installed GATEWAY_HOME/mosaic.config.json ahead of gateway-local and monorepo-root configs',
|
||||
async (): Promise<void> => {
|
||||
let daemonConfigPath = '';
|
||||
const graph = await loadModuleGraphFromDotenv({
|
||||
rootEnvMode: 'absent',
|
||||
setup: async (fixture: ModuleGraphFixture): Promise<void> => {
|
||||
const externalGatewayHome = join(fixture.tempRoot, 'external-gateway-home');
|
||||
daemonConfigPath = join(externalGatewayHome, 'mosaic.config.json');
|
||||
await writeFixture(daemonConfigPath, configJson('federated'), fixture.tempRoot);
|
||||
await writeFixture(
|
||||
fixture.gatewayLocalConfigPath,
|
||||
configJson('standalone'),
|
||||
fixture.tempRoot,
|
||||
);
|
||||
await writeFixture(fixture.monorepoRootConfigPath, configJson('local'), fixture.tempRoot);
|
||||
process.env['MOSAIC_GATEWAY_HOME'] = externalGatewayHome;
|
||||
process.env['DATABASE_URL'] = 'postgresql://fixture.invalid/mosaic';
|
||||
},
|
||||
});
|
||||
|
||||
expect(graph.resolvedConfigPath).toBe(daemonConfigPath);
|
||||
expect(graph.mosaicConfig.tier).toBe('federated');
|
||||
expect(graph.imports).toContain(graph.federationModule);
|
||||
expectBootLogLine(graph.bootLogLines, 'federated', 'mosaic.config.json');
|
||||
},
|
||||
MODULE_IMPORT_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it(
|
||||
'logs mosaic.config.json when anchored config and env tiers are both federated',
|
||||
async (): Promise<void> => {
|
||||
const graph = await loadModuleGraphFromDotenv({
|
||||
rootTier: 'federated',
|
||||
setup: async (fixture: ModuleGraphFixture): Promise<void> => {
|
||||
await writeFixture(
|
||||
fixture.monorepoRootConfigPath,
|
||||
configJson('federated'),
|
||||
fixture.tempRoot,
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
expect(graph.imports).toContain(graph.federationModule);
|
||||
expectBootLogLine(graph.bootLogLines, 'federated', 'mosaic.config.json');
|
||||
},
|
||||
MODULE_IMPORT_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it(
|
||||
'logs standalone from a monorepo-root .env DATABASE_URL fallback',
|
||||
async (): Promise<void> => {
|
||||
const graph = await loadModuleGraphFromDotenv({
|
||||
rootEnvContents: 'DATABASE_URL=fixture-database-url\n',
|
||||
});
|
||||
|
||||
expect(graph.imports).not.toContain(graph.federationModule);
|
||||
expectBootLogLine(graph.bootLogLines, 'standalone', MONOREPO_ROOT_DOTENV_LABEL);
|
||||
},
|
||||
MODULE_IMPORT_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it(
|
||||
'attributes an invalid monorepo-root dotenv tier to the default',
|
||||
async (): Promise<void> => {
|
||||
const graph = await loadModuleGraphFromDotenv({
|
||||
rootEnvContents: 'MOSAIC_STORAGE_TIER=invalid\n',
|
||||
expectedProcessTier: 'invalid',
|
||||
});
|
||||
|
||||
expect(graph.imports).not.toContain(graph.federationModule);
|
||||
expectBootLogLine(graph.bootLogLines, 'local', 'default');
|
||||
},
|
||||
MODULE_IMPORT_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it(
|
||||
'attributes DATABASE_URL fallback to daemon .env ahead of inherited local tier',
|
||||
async (): Promise<void> => {
|
||||
const graph = await loadModuleGraphFromDotenv({
|
||||
rootEnvMode: 'absent',
|
||||
daemonEnvContents: 'DATABASE_URL=fixture-database-url\n',
|
||||
inheritedTier: 'local',
|
||||
expectedProcessTier: 'local',
|
||||
});
|
||||
|
||||
expect(graph.imports).not.toContain(graph.federationModule);
|
||||
expectBootLogLine(graph.bootLogLines, 'standalone', DAEMON_DOTENV_LABEL);
|
||||
},
|
||||
MODULE_IMPORT_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it(
|
||||
'daemon .env wins over monorepo-root and gateway-local tier values',
|
||||
async (): Promise<void> => {
|
||||
const graph = await loadModuleGraphFromDotenv({
|
||||
rootTier: 'local',
|
||||
gatewayLocalTier: 'federated',
|
||||
daemonEnvContents: 'MOSAIC_STORAGE_TIER=standalone\n',
|
||||
expectedProcessTier: 'standalone',
|
||||
});
|
||||
|
||||
expect(graph.imports).not.toContain(graph.federationModule);
|
||||
expectBootLogLine(graph.bootLogLines, 'standalone', DAEMON_DOTENV_LABEL);
|
||||
},
|
||||
MODULE_IMPORT_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it(
|
||||
'inherits process.env.MOSAIC_STORAGE_TIER over daemon, monorepo-root, and gateway-local dotenv values',
|
||||
async (): Promise<void> => {
|
||||
const graph = await loadModuleGraphFromDotenv({
|
||||
rootTier: 'local',
|
||||
gatewayLocalTier: 'federated',
|
||||
daemonEnvContents: 'MOSAIC_STORAGE_TIER=federated\n',
|
||||
inheritedTier: 'standalone',
|
||||
expectedProcessTier: 'standalone',
|
||||
});
|
||||
|
||||
expect(graph.imports).not.toContain(graph.federationModule);
|
||||
expectBootLogLine(graph.bootLogLines, 'standalone', 'process environment');
|
||||
},
|
||||
MODULE_IMPORT_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it(
|
||||
'gateway-local .env configures the tier and source when the monorepo-root .env is absent',
|
||||
async (): Promise<void> => {
|
||||
const graph = await loadModuleGraphFromDotenv({
|
||||
rootEnvMode: 'absent',
|
||||
gatewayLocalTier: 'federated',
|
||||
expectedProcessTier: 'federated',
|
||||
});
|
||||
|
||||
expect(graph.imports).toContain(graph.federationModule);
|
||||
expectBootLogLine(graph.bootLogLines, 'federated', 'gateway-local .env');
|
||||
},
|
||||
MODULE_IMPORT_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it(
|
||||
'monorepo-root .env wins over gateway-local tier values',
|
||||
async (): Promise<void> => {
|
||||
const graph = await loadModuleGraphFromDotenv({
|
||||
rootTier: 'standalone',
|
||||
gatewayLocalTier: 'federated',
|
||||
});
|
||||
|
||||
expect(graph.imports).not.toContain(graph.federationModule);
|
||||
expectBootLogLine(graph.bootLogLines, 'standalone', MONOREPO_ROOT_DOTENV_LABEL);
|
||||
},
|
||||
MODULE_IMPORT_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it.each(['local', 'standalone'] as const)(
|
||||
'does not register FederationModule for the %s tier',
|
||||
async (tier): Promise<void> => {
|
||||
const graph = await loadModuleGraphFromDotenv({ rootTier: tier });
|
||||
|
||||
expect(graph.imports).not.toContain(graph.federationModule);
|
||||
expectBootLogLine(graph.bootLogLines, tier, MONOREPO_ROOT_DOTENV_LABEL);
|
||||
},
|
||||
MODULE_IMPORT_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it(
|
||||
'registers FederationModule when federated tier is supplied by the anchored monorepo root .env',
|
||||
async (): Promise<void> => {
|
||||
const redactionMarker = 'redaction-fixture-marker';
|
||||
const graph = await loadModuleGraphFromDotenv({
|
||||
rootTier: 'federated',
|
||||
redactionMarker,
|
||||
});
|
||||
|
||||
expect(graph.imports).toContain(graph.federationModule);
|
||||
expectBootLogLine(graph.bootLogLines, 'federated', MONOREPO_ROOT_DOTENV_LABEL);
|
||||
expect(singleBootLogLine(graph.bootLogLines)).not.toContain(redactionMarker);
|
||||
},
|
||||
MODULE_IMPORT_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it(
|
||||
'MOSAIC_CONFIG provider ignores an ambient cwd/mosaic.config.json config',
|
||||
async (): Promise<void> => {
|
||||
const graph = await loadModuleGraphFromDotenv({
|
||||
rootTier: 'local',
|
||||
setup: async (fixture: ModuleGraphFixture): Promise<void> => {
|
||||
await writeFixture(
|
||||
join(fixture.cwdPath, 'mosaic.config.json'),
|
||||
JSON.stringify({
|
||||
tier: 'federated',
|
||||
storage: {
|
||||
type: 'postgres',
|
||||
url: 'postgresql://ambient-attacker.invalid/mosaic',
|
||||
enableVector: true,
|
||||
},
|
||||
queue: { type: 'bullmq' },
|
||||
memory: { type: 'pgvector' },
|
||||
}),
|
||||
fixture.tempRoot,
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
expect(graph.mosaicConfig.tier).toBe('local');
|
||||
expect(graph.mosaicConfig.storage).not.toEqual(
|
||||
expect.objectContaining({ url: 'postgresql://ambient-attacker.invalid/mosaic' }),
|
||||
);
|
||||
},
|
||||
MODULE_IMPORT_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it(
|
||||
'MOSAIC_CONFIG provider resolves from the anchored monorepo-root mosaic.config.json',
|
||||
async (): Promise<void> => {
|
||||
const graph = await loadModuleGraphFromDotenv({
|
||||
rootTier: 'local',
|
||||
setup: async (fixture: ModuleGraphFixture): Promise<void> => {
|
||||
await writeFixture(
|
||||
fixture.monorepoRootConfigPath,
|
||||
configJson('federated'),
|
||||
fixture.tempRoot,
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
expect(graph.mosaicConfig.tier).toBe('federated');
|
||||
expect(graph.mosaicConfig.storage).toEqual(
|
||||
expect.objectContaining({ url: 'postgresql://fixture.invalid/mosaic' }),
|
||||
);
|
||||
},
|
||||
MODULE_IMPORT_TIMEOUT_MS,
|
||||
);
|
||||
});
|
||||
@@ -21,22 +21,11 @@ import { AdminModule } from './admin/admin.module.js';
|
||||
import { CommandsModule } from './commands/commands.module.js';
|
||||
import { PreferencesModule } from './preferences/preferences.module.js';
|
||||
import { GCModule } from './gc/gc.module.js';
|
||||
import { HarnessModule } from './harness/harness.module.js';
|
||||
import { ReloadModule } from './reload/reload.module.js';
|
||||
import { WorkspaceModule } from './workspace/workspace.module.js';
|
||||
import { QueueModule } from './queue/queue.module.js';
|
||||
import { FederationModule } from './federation/federation.module.js';
|
||||
import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler';
|
||||
import { loadConfig } from '@mosaicstack/config';
|
||||
import { resolveGatewayConfigPath } from './env.js';
|
||||
|
||||
// Federation (step-ca client, enrollment, federation verbs) is only wired for
|
||||
// tier 'federated' — CaService hard-requires STEP_CA_* at construction, which
|
||||
// must not gate standalone/local boots (docker-compose.federated.yml: the
|
||||
// federation profile "must not start in non-federated dev"). The gateway
|
||||
// entrypoint loads env.ts before evaluating this module so dotenv-backed tier
|
||||
// configuration is visible here.
|
||||
const federationEnabled = loadConfig(resolveGatewayConfigPath()).tier === 'federated';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -61,11 +50,10 @@ const federationEnabled = loadConfig(resolveGatewayConfigPath()).tier === 'feder
|
||||
PreferencesModule,
|
||||
CommandsModule,
|
||||
GCModule,
|
||||
HarnessModule,
|
||||
QueueModule,
|
||||
ReloadModule,
|
||||
WorkspaceModule,
|
||||
...(federationEnabled ? [FederationModule] : []),
|
||||
FederationModule,
|
||||
],
|
||||
controllers: [HealthController],
|
||||
providers: [
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
export interface AuthenticatedUserLike {
|
||||
id: string;
|
||||
tenantId?: string | null;
|
||||
teamId?: string | null;
|
||||
organizationId?: string | null;
|
||||
orgId?: string | null;
|
||||
}
|
||||
|
||||
export interface ActorTenantScope {
|
||||
userId: string;
|
||||
tenantId: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the immutable server-derived scope used for Tess session operations.
|
||||
* Current Mosaic auth is user-scoped; future org/team claims can populate one
|
||||
* of the tenant fields without allowing clients to choose another tenant.
|
||||
*/
|
||||
export function scopeFromUser(user: AuthenticatedUserLike): ActorTenantScope {
|
||||
return {
|
||||
userId: user.id,
|
||||
tenantId: user.tenantId ?? user.teamId ?? user.organizationId ?? user.orgId ?? user.id,
|
||||
};
|
||||
}
|
||||
@@ -1,24 +1,10 @@
|
||||
import 'reflect-metadata';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { ValidationPipe, type ArgumentMetadata } from '@nestjs/common';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { validateSync, type ValidationError } from 'class-validator';
|
||||
import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { HarnessAdapter, HarnessConversationService } from '@mosaicstack/types';
|
||||
import { AgentService } from '../../agent/agent.service.js';
|
||||
import { AuthGuard } from '../../auth/auth.guard.js';
|
||||
import { HarnessRegistry } from '../../harness/harness.registry.js';
|
||||
import { HARNESS_REGISTRY } from '../../harness/harness.tokens.js';
|
||||
import type { AuthenticatedUserLike } from '../../auth/session-scope.js';
|
||||
import { validateSync } from 'class-validator';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { SendMessageDto } from '../../conversations/conversations.dto.js';
|
||||
import { ChatController } from '../chat.controller.js';
|
||||
import { ChatGateway } from '../chat.gateway.js';
|
||||
import { ChatRuntimeRouter } from '../chat-runtime-router.js';
|
||||
import { EmbeddedChatRuntime } from '../embedded-chat.runtime.js';
|
||||
import { HarnessChatRuntime } from '../harness-chat.runtime.js';
|
||||
import type { ChatRuntime } from '../chat-runtime.js';
|
||||
import { ChatRequestDto, HarnessTurnSendDto } from '../chat.dto.js';
|
||||
import { ChatRequestDto } from '../chat.dto.js';
|
||||
import { validateSocketSession } from '../chat.gateway-auth.js';
|
||||
|
||||
describe('Chat controller source hardening', () => {
|
||||
@@ -26,330 +12,7 @@ describe('Chat controller source hardening', () => {
|
||||
const source = readFileSync(resolve('src/chat/chat.controller.ts'), 'utf8');
|
||||
|
||||
expect(source).toContain('@UseGuards(AuthGuard)');
|
||||
expect(source).toContain('@CurrentUser() user: AuthenticatedUserLike');
|
||||
expect(source).toContain('const scope = scopeFromUser(user);');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Chat runtime routing hardening (Task Five)', () => {
|
||||
it('routes /api/chat through the exclusive ChatRuntimeRouter, never the embedded AgentService', () => {
|
||||
const source = readFileSync(resolve('src/chat/chat.controller.ts'), 'utf8');
|
||||
|
||||
// pi-rpc /api/chat must resolve execution through the one runtime router and never
|
||||
// reach into embedded agent execution. Legacy embedded behaviour lives behind
|
||||
// EmbeddedChatRuntime, reachable only via the router in legacy mode.
|
||||
expect(source).toContain('ChatRuntimeRouter');
|
||||
expect(source).not.toContain('@Inject(AgentService)');
|
||||
expect(source).not.toContain("from '../agent/agent.service.js'");
|
||||
});
|
||||
|
||||
it('gateway no longer injects the embedded AgentService or RoutingEngineService', () => {
|
||||
const source = readFileSync(resolve('src/chat/chat.gateway.ts'), 'utf8');
|
||||
|
||||
expect(source).toContain('ChatRuntimeRouter');
|
||||
expect(source).not.toContain('@Inject(AgentService)');
|
||||
expect(source).not.toContain('@Inject(RoutingEngineService)');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Harness turn:send DTO validation (Task Five, group 2 — frozen wire contract, production pipe)', () => {
|
||||
// Correction #2 (Scrappy fe3e02): drive PLAIN wire payloads through the EXACT production
|
||||
// validation the gateway applies to inbound bodies — the global ValidationPipe in
|
||||
// apps/gateway/src/main.ts: { whitelist, forbidNonWhitelisted, transform }. This exercises
|
||||
// the real plainToInstance transform, nested @Type/@ValidateNested recursion, and whitelist
|
||||
// stripping — the path a turn:send actually travels — rather than a hand-built class instance
|
||||
// fed to validateSync (which never runs @Type and is masked green by class-validator's
|
||||
// empty-metadata unknownValue behaviour). Anti-masking: every VALUE-rule red asserts the field
|
||||
// carries a REAL value constraint (not `whitelistValidation`/`unknownValue`), which the
|
||||
// decorator-less stub can NEVER produce; every authority-field red asserts the forbidden field
|
||||
// is rejected while a valid field is NOT — false against the stub, which over-rejects everything.
|
||||
const PRODUCTION_PIPE = () =>
|
||||
new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true });
|
||||
// Same production configuration, but hand back the raw ValidationError[] instead of throwing a
|
||||
// BadRequestException, so the test can inspect per-field constraint keys and nested children.
|
||||
const failPipe = new ValidationPipe({
|
||||
whitelist: true,
|
||||
forbidNonWhitelisted: true,
|
||||
transform: true,
|
||||
exceptionFactory: (errs: ValidationError[]) => errs as unknown as Error,
|
||||
});
|
||||
const asBody = (metatype: ArgumentMetadata['metatype']): ArgumentMetadata => ({
|
||||
type: 'body',
|
||||
metatype,
|
||||
data: '',
|
||||
});
|
||||
|
||||
const UUID_V4 = '11111111-1111-4111-8111-111111111111';
|
||||
const validSelection = () => ({ harnessId: 'pi', providerId: 'anthropic', modelId: 'claude' });
|
||||
const validPayload = () => ({
|
||||
conversationId: UUID_V4,
|
||||
content: 'hello there',
|
||||
selection: validSelection(),
|
||||
idempotencyKey: UUID_V4,
|
||||
});
|
||||
|
||||
// Constraint keys that mean "the field was rejected for existing", NOT "its VALUE failed a real
|
||||
// rule". The decorator-less RED stub can only ever emit these (or nothing), so requiring a REAL
|
||||
// value constraint on a field is unmaskable until Step Three attaches the decorators.
|
||||
const NON_VALUE = new Set(['whitelistValidation', 'unknownValue']);
|
||||
|
||||
// Flatten the error tree to `dotted.path -> Set<constraintKey>` (parent + nested children).
|
||||
const collect = (errors: ValidationError[], prefix = ''): Map<string, Set<string>> => {
|
||||
const map = new Map<string, Set<string>>();
|
||||
const add = (path: string, keys: Iterable<string>): void => {
|
||||
const set = map.get(path) ?? new Set<string>();
|
||||
for (const key of keys) set.add(key);
|
||||
map.set(path, set);
|
||||
};
|
||||
for (const error of errors) {
|
||||
const path = prefix ? `${prefix}.${error.property}` : error.property;
|
||||
if (error.constraints) add(path, Object.keys(error.constraints));
|
||||
if (error.children?.length) for (const [p, s] of collect(error.children, path)) add(p, s);
|
||||
}
|
||||
return map;
|
||||
};
|
||||
|
||||
// Run the production pipe over a plain payload; return the ValidationError[] it raised (empty
|
||||
// when the payload is accepted).
|
||||
const errorsFor = async (
|
||||
payload: unknown,
|
||||
metatype: ArgumentMetadata['metatype'] = HarnessTurnSendDto,
|
||||
): Promise<ValidationError[]> => {
|
||||
try {
|
||||
await failPipe.transform(payload, asBody(metatype));
|
||||
return [];
|
||||
} catch (thrown) {
|
||||
return thrown as ValidationError[];
|
||||
}
|
||||
};
|
||||
|
||||
// True when `path` is rejected by a REAL value rule (IsUUID, IsNotEmpty, MaxLength, …), i.e. a
|
||||
// constraint that is not a mere existence/whitelist rejection.
|
||||
const hasValueConstraint = async (
|
||||
payload: unknown,
|
||||
path: string,
|
||||
metatype: ArgumentMetadata['metatype'] = HarnessTurnSendDto,
|
||||
): Promise<boolean> => {
|
||||
const keys = collect(await errorsFor(payload, metatype)).get(path);
|
||||
return keys ? [...keys].some((key) => !NON_VALUE.has(key)) : false;
|
||||
};
|
||||
|
||||
// Paths rejected purely for existing outside the whitelist (authority / unknown-field defence).
|
||||
const forbiddenFields = async (payload: unknown): Promise<string[]> => {
|
||||
const out: string[] = [];
|
||||
for (const [path, keys] of collect(await errorsFor(payload))) {
|
||||
if (keys.has('whitelistValidation')) out.push(path);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
// --- GREEN controls: prove the production pipe machinery genuinely accepts a well-formed,
|
||||
// already-decorated DTO AND enforces its constraints — so the group's reds below are the
|
||||
// STUB's missing decorators, not a broken harness. Both pass today. ---
|
||||
it('GREEN control: the production pipe accepts a well-formed, decorated ChatRequestDto', async () => {
|
||||
await expect(
|
||||
PRODUCTION_PIPE().transform({ content: 'hello there' }, asBody(ChatRequestDto)),
|
||||
).resolves.toBeTruthy();
|
||||
});
|
||||
|
||||
it('GREEN control: the same production pipe rejects over-long ChatRequestDto content (engine truly enforces)', async () => {
|
||||
expect(
|
||||
await hasValueConstraint({ content: 'x'.repeat(10_001) }, 'content', ChatRequestDto),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
// --- RED value-rule fence: each asserts the turn:send field is rejected by a REAL value rule.
|
||||
// All fail against the decorator-less stub; they go green when Step Three adds the decorators.
|
||||
// No validation implementation is permitted during RED collection. ---
|
||||
it('requires a conversation id (rejects a missing conversationId)', async () => {
|
||||
expect(
|
||||
await hasValueConstraint({ ...validPayload(), conversationId: undefined }, 'conversationId'),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('requires a UUID conversation id (rejects a non-UUID conversationId)', async () => {
|
||||
expect(
|
||||
await hasValueConstraint(
|
||||
{ ...validPayload(), conversationId: 'not-a-uuid' },
|
||||
'conversationId',
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects empty / whitespace-only content (content is trimmed 1..10000)', async () => {
|
||||
expect(await hasValueConstraint({ ...validPayload(), content: ' ' }, 'content')).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects content above 10000 characters', async () => {
|
||||
expect(
|
||||
await hasValueConstraint({ ...validPayload(), content: 'x'.repeat(10_001) }, 'content'),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('requires the nested selection triple (rejects a missing selection)', async () => {
|
||||
expect(await hasValueConstraint({ ...validPayload(), selection: undefined }, 'selection')).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects malformed selection nesting (a non-object selection)', async () => {
|
||||
expect(
|
||||
await hasValueConstraint(
|
||||
{ ...validPayload(), selection: 'pi/anthropic/claude' },
|
||||
'selection',
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects a selection with a blank harnessId (each id must be non-empty)', async () => {
|
||||
const payload = {
|
||||
...validPayload(),
|
||||
selection: { harnessId: '', providerId: 'anthropic', modelId: 'claude' },
|
||||
};
|
||||
expect(await hasValueConstraint(payload, 'selection.harnessId')).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects a selection missing the modelId', async () => {
|
||||
const payload = { ...validPayload(), selection: { harnessId: 'pi', providerId: 'anthropic' } };
|
||||
expect(await hasValueConstraint(payload, 'selection.modelId')).toBe(true);
|
||||
});
|
||||
|
||||
it('requires a UUID-v4 idempotency key (rejects a missing key)', async () => {
|
||||
expect(
|
||||
await hasValueConstraint({ ...validPayload(), idempotencyKey: undefined }, 'idempotencyKey'),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects a non-UUID-v4 idempotency key', async () => {
|
||||
expect(
|
||||
await hasValueConstraint(
|
||||
{ ...validPayload(), idempotencyKey: 'not-a-key' },
|
||||
'idempotencyKey',
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
// --- RED authority/unknown-field fence: the forbidden field is rejected while a valid field is
|
||||
// NOT spuriously rejected. False against the stub (which over-rejects every field, including
|
||||
// `content`); true only once Step Three whitelists the legitimate fields. ---
|
||||
it('rejects a top-level authority field (provider) without flagging valid fields', async () => {
|
||||
const forbidden = await forbiddenFields({ ...validPayload(), provider: 'openai' });
|
||||
expect(forbidden).toContain('provider');
|
||||
expect(forbidden).not.toContain('content');
|
||||
});
|
||||
|
||||
it('rejects a top-level modelId authority field without flagging valid fields', async () => {
|
||||
const forbidden = await forbiddenFields({ ...validPayload(), modelId: 'gpt-5' });
|
||||
expect(forbidden).toContain('modelId');
|
||||
expect(forbidden).not.toContain('content');
|
||||
});
|
||||
|
||||
it('rejects an attachments field (not part of the frozen turn:send contract)', async () => {
|
||||
const forbidden = await forbiddenFields({ ...validPayload(), attachments: [{ id: 'a1' }] });
|
||||
expect(forbidden).toContain('attachments');
|
||||
expect(forbidden).not.toContain('content');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Chat runtime routing — behavioural /api/chat fence (Task Five, group 3)', () => {
|
||||
// The router's own runtime tokens. The controller must reach chat execution ONLY through the
|
||||
// router; the embedded AgentService below is the forbidden path proven untouched.
|
||||
const embedded: ChatRuntime = { kind: 'embedded' };
|
||||
const harness: ChatRuntime = { kind: 'harness' };
|
||||
|
||||
// Structurally-complete, non-sentinel conversation service; its methods are never invoked here.
|
||||
const boundConversationService = {
|
||||
attach: () => Promise.reject(new Error('unused')),
|
||||
detach: () => Promise.reject(new Error('unused')),
|
||||
send: () => Promise.reject(new Error('unused')),
|
||||
|
||||
subscribeFrom: async function* () {
|
||||
throw new Error('unused');
|
||||
},
|
||||
} as unknown as HarnessConversationService;
|
||||
|
||||
it('handles an /api/chat turn without invoking the embedded AgentService (behavioural, zero calls)', async () => {
|
||||
const calls = { getSession: 0, createSession: 0, onEvent: 0, prompt: 0 };
|
||||
// A spy standing in for the forbidden embedded runtime. `createSession` rejects so today's
|
||||
// controller bails immediately (never reaching the 120s agent-response wait) while still
|
||||
// recording that it reached into the embedded path — the RED anchor. Under Step Three the
|
||||
// router owns execution and this spy is never touched, so every counter stays 0 (GREEN).
|
||||
// Any masking mutation that re-enters embedded execution flips a counter and re-reds the test.
|
||||
const agentSpy = {
|
||||
getSession: () => {
|
||||
calls.getSession += 1;
|
||||
return undefined;
|
||||
},
|
||||
createSession: () => {
|
||||
calls.createSession += 1;
|
||||
return Promise.reject(new Error('spy: embedded AgentService must not be used'));
|
||||
},
|
||||
onEvent: () => {
|
||||
calls.onEvent += 1;
|
||||
return () => {};
|
||||
},
|
||||
prompt: () => {
|
||||
calls.prompt += 1;
|
||||
return Promise.resolve();
|
||||
},
|
||||
};
|
||||
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
controllers: [ChatController],
|
||||
providers: [
|
||||
{ provide: AgentService, useValue: agentSpy },
|
||||
{
|
||||
// Provided so the Step-Three controller (which injects the router) still resolves here;
|
||||
// the real, empty registry seeded with a pi adapter keeps the router pi-rpc-ready.
|
||||
provide: HARNESS_REGISTRY,
|
||||
useFactory: () => {
|
||||
const registry = new HarnessRegistry();
|
||||
registry.register({
|
||||
id: 'pi',
|
||||
describe: () => Promise.reject(new Error('unused')),
|
||||
catalog: () => Promise.reject(new Error('unused')),
|
||||
create: () => Promise.reject(new Error('unused')),
|
||||
resume: () => Promise.reject(new Error('unused')),
|
||||
} as HarnessAdapter);
|
||||
return registry;
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: ChatRuntimeRouter,
|
||||
useFactory: (registry: HarnessRegistry) =>
|
||||
new ChatRuntimeRouter(registry, boundConversationService, embedded, harness, 'pi-rpc'),
|
||||
inject: [HARNESS_REGISTRY],
|
||||
},
|
||||
],
|
||||
})
|
||||
// ChatController's @UseGuards(AuthGuard) is resolved during instance loading; AuthGuard
|
||||
// injects AUTH, an HTTP-only concern never exercised by a direct handler call. Stub it so
|
||||
// the graph resolves and the test reds on BEHAVIOUR, not on a DI collection error.
|
||||
.overrideGuard(AuthGuard)
|
||||
.useValue({ canActivate: () => true })
|
||||
.compile();
|
||||
|
||||
try {
|
||||
const controller = moduleRef.get(ChatController, { strict: false });
|
||||
const user = { id: 'user-1' } as AuthenticatedUserLike;
|
||||
try {
|
||||
await controller.chat({ content: 'route me' } as ChatRequestDto, user);
|
||||
} catch {
|
||||
// Today: SERVICE_UNAVAILABLE from the rejecting spy. Under Step Three: the router path may
|
||||
// reject on the deliberately-unbound fake conversation service. Either way the
|
||||
// embedded-call counters below are the contract, not the handler's return value.
|
||||
}
|
||||
expect(calls).toEqual({ getSession: 0, createSession: 0, onEvent: 0, prompt: 0 });
|
||||
} finally {
|
||||
await moduleRef.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('wires the exclusive ChatRuntimeRouter into the chat module graph (defense-in-depth source check)', () => {
|
||||
const source = readFileSync(resolve('src/chat/chat.module.ts'), 'utf8');
|
||||
// The controller can only inject the router if the module actually provides it. RED today:
|
||||
// ChatModule provides only ChatGateway. GREEN once Step Three registers ChatRuntimeRouter.
|
||||
expect(source).toContain('ChatRuntimeRouter');
|
||||
expect(source).toContain('@CurrentUser() user: { id: string }');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -383,634 +46,6 @@ describe('WebSocket session authentication', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('Non-Discord ("Telegram-equivalent") socket ingress rejection (Task Five, both runtime modes)', () => {
|
||||
// Scrappy C adjudication regression: a non-Discord service socket — modelled as a "Telegram"
|
||||
// client presenting a handshake token the gateway does NOT honour and carrying no Better-Auth
|
||||
// session — must be DISCONNECTED at handleConnection, never gain the `discordService` trust flag
|
||||
// or any user scope, receive no manifest and no ack, and reach NEITHER the embedded runtime NOR
|
||||
// the harness. This must hold in BOTH legacy and pi-rpc modes: introducing the exclusive
|
||||
// ChatRuntimeRouter / pi-rpc path must not open a second, non-Discord service ingress. This is a
|
||||
// GREEN control (it holds on this branch and must keep holding through Step Three); no Telegram
|
||||
// production route or plugin exists or is added — the assertion is that no such surface is
|
||||
// reachable. The runtime slot is fronted with a REAL, ready ChatRuntimeRouter over
|
||||
// EmbeddedChatRuntime + HarnessChatRuntime so that any accidental dispatch would flip a spy
|
||||
// rather than silently pass; the router is never resolved because the socket is rejected first.
|
||||
let priorMode: string | undefined;
|
||||
beforeEach(() => {
|
||||
priorMode = process.env['CHAT_HARNESS_RUNTIME'];
|
||||
});
|
||||
afterEach(() => {
|
||||
if (priorMode === undefined) delete process.env['CHAT_HARNESS_RUNTIME'];
|
||||
else process.env['CHAT_HARNESS_RUNTIME'] = priorMode;
|
||||
});
|
||||
|
||||
// A pi-ready registry so a pi-rpc router resolves the harness cleanly at onModuleInit — modelling
|
||||
// the hostile condition where the harness is live yet the non-Discord socket is still rejected.
|
||||
const readyPiRegistry = (): HarnessRegistry => {
|
||||
const registry = new HarnessRegistry();
|
||||
registry.register({
|
||||
id: 'pi',
|
||||
describe: () => Promise.reject(new Error('unused')),
|
||||
catalog: () => Promise.reject(new Error('unused')),
|
||||
create: () => Promise.reject(new Error('unused')),
|
||||
resume: () => Promise.reject(new Error('unused')),
|
||||
} as HarnessAdapter);
|
||||
return registry;
|
||||
};
|
||||
|
||||
// Non-sentinel conversation service so pi-rpc onModuleInit resolves the harness (does not throw
|
||||
// conversation_service_unavailable); its methods must never be invoked on the rejection path.
|
||||
const availableConversationService = {
|
||||
attach: () => Promise.reject(new Error('unused')),
|
||||
detach: () => Promise.reject(new Error('unused')),
|
||||
send: () => Promise.reject(new Error('unused')),
|
||||
|
||||
subscribeFrom: async function* () {
|
||||
throw new Error('unused');
|
||||
},
|
||||
} as unknown as HarnessConversationService;
|
||||
|
||||
const readyRouter = (
|
||||
mode: 'legacy' | 'pi-rpc',
|
||||
agentService: unknown,
|
||||
harnessConversations: unknown,
|
||||
): ChatRuntimeRouter => {
|
||||
const embedded = new EmbeddedChatRuntime(agentService as never);
|
||||
const harness = new HarnessChatRuntime(harnessConversations as never);
|
||||
const router = new ChatRuntimeRouter(
|
||||
readyPiRegistry(),
|
||||
availableConversationService,
|
||||
embedded,
|
||||
harness,
|
||||
mode,
|
||||
);
|
||||
router.onModuleInit();
|
||||
return router;
|
||||
};
|
||||
|
||||
it.each(['legacy', 'pi-rpc'] as const)(
|
||||
'disconnects a Telegram-shaped unauthenticated socket and dispatches to no runtime (%s mode)',
|
||||
async (mode) => {
|
||||
process.env['CHAT_HARNESS_RUNTIME'] = mode;
|
||||
const agentService = {
|
||||
getSession: vi.fn().mockReturnValue(undefined),
|
||||
createSession: vi.fn(),
|
||||
recordMessage: vi.fn(),
|
||||
onEvent: vi.fn().mockReturnValue((): void => undefined),
|
||||
addChannel: vi.fn(),
|
||||
prompt: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const harnessConversations = { append: vi.fn() };
|
||||
// Auth stub that resolves NO session for the Telegram socket's headers — the sole gate a
|
||||
// non-Discord client must pass, and does not.
|
||||
const auth = { api: { getSession: vi.fn().mockResolvedValue(null) } };
|
||||
const gateway = new ChatGateway(
|
||||
readyRouter(mode, agentService, harnessConversations) as never,
|
||||
auth as never,
|
||||
{ conversations: { addMessage: vi.fn().mockResolvedValue(undefined) } } as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
);
|
||||
|
||||
const client = {
|
||||
id: `telegram-raw-${mode}`,
|
||||
// A non-Discord service handshake: the gateway only honours `discordServiceToken`, so this
|
||||
// token is ignored, and there is no session cookie for validateSocketSession to resolve.
|
||||
handshake: { auth: { telegramServiceToken: 'ignored-non-discord-token' }, headers: {} },
|
||||
data: {} as Record<string, unknown>,
|
||||
emit: vi.fn(),
|
||||
disconnect: vi.fn(),
|
||||
};
|
||||
|
||||
await gateway.handleConnection(client as never);
|
||||
|
||||
// Rejected at the door: disconnected, no trust flag, no user scope, no manifest, and — the
|
||||
// Task 5 send-capability rule — no send-protocol advertisement to an unauthenticated socket.
|
||||
expect(client.disconnect).toHaveBeenCalled();
|
||||
expect(client.data.discordService).not.toBe(true);
|
||||
expect(client.data.user).toBeUndefined();
|
||||
expect(client.emit).not.toHaveBeenCalledWith('commands:manifest', expect.anything());
|
||||
expect(client.emit).not.toHaveBeenCalledWith('chat:send-capability', expect.anything());
|
||||
|
||||
// Even if the ignored socket then attempts a message, it carries no scope, so the send path
|
||||
// never begins and no runtime is dispatched.
|
||||
await gateway.handleMessage(
|
||||
client as never,
|
||||
{
|
||||
conversationId: 'Nova:telegram:chat-1',
|
||||
content: 'via telegram',
|
||||
} as never,
|
||||
);
|
||||
|
||||
expect(client.emit).not.toHaveBeenCalledWith('message:ack', expect.anything());
|
||||
expect(agentService.createSession).not.toHaveBeenCalled();
|
||||
expect(agentService.prompt).not.toHaveBeenCalled();
|
||||
expect(harnessConversations.append).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
// A minimal authenticated-browser connection harness for the send-capability advertisement.
|
||||
const connectAuthedBrowser = async (
|
||||
mode: 'legacy' | 'pi-rpc',
|
||||
clientId: string,
|
||||
): Promise<{ emit: ReturnType<typeof vi.fn>; disconnect: ReturnType<typeof vi.fn> }> => {
|
||||
process.env['CHAT_HARNESS_RUNTIME'] = mode;
|
||||
const agentService = {
|
||||
getSession: vi.fn().mockReturnValue(undefined),
|
||||
createSession: vi.fn(),
|
||||
recordMessage: vi.fn(),
|
||||
onEvent: vi.fn().mockReturnValue((): void => undefined),
|
||||
addChannel: vi.fn(),
|
||||
prompt: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const harnessConversations = { append: vi.fn() };
|
||||
const auth = {
|
||||
api: {
|
||||
getSession: vi
|
||||
.fn()
|
||||
.mockResolvedValue({ user: { id: 'user-a' }, session: { id: 'session-a' } }),
|
||||
},
|
||||
};
|
||||
const gateway = new ChatGateway(
|
||||
readyRouter(mode, agentService, harnessConversations) as never,
|
||||
auth as never,
|
||||
{ conversations: { addMessage: vi.fn().mockResolvedValue(undefined) } } as never,
|
||||
{ getManifest: vi.fn().mockReturnValue({ commands: [] }) } as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
);
|
||||
const client = {
|
||||
id: clientId,
|
||||
handshake: { auth: {}, headers: { cookie: 'session=abc' } },
|
||||
data: {} as Record<string, unknown>,
|
||||
emit: vi.fn(),
|
||||
disconnect: vi.fn(),
|
||||
};
|
||||
await gateway.handleConnection(client as never);
|
||||
return client as never;
|
||||
};
|
||||
|
||||
it('advertises legacy-message exactly once to an authenticated browser in legacy mode (Task 5 MAJOR-1)', async () => {
|
||||
const client = await connectAuthedBrowser('legacy', 'browser-cap-legacy');
|
||||
|
||||
// Legacy mode: the connected Gateway handles the `message` event, so it advertises
|
||||
// `legacy-message` — targeted, connection-bound, exactly once.
|
||||
expect(client.emit).toHaveBeenCalledWith('chat:send-capability', {
|
||||
protocol: 'legacy-message',
|
||||
connectionId: 'browser-cap-legacy',
|
||||
});
|
||||
const capabilityCalls = client.emit.mock.calls.filter(
|
||||
(call: unknown[]) => call[0] === 'chat:send-capability',
|
||||
);
|
||||
expect(capabilityCalls).toHaveLength(1);
|
||||
expect(client.disconnect).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('advertises unavailable (never turn-send) to an authenticated browser in pi-rpc mode (Task 5 MAJOR-1)', async () => {
|
||||
const client = await connectAuthedBrowser('pi-rpc', 'browser-cap-pirpc');
|
||||
|
||||
// pi-rpc mode: the legacy `message` handler fails closed and the authenticated `turn:send`
|
||||
// handler lands in Task 15, so Task 5 advertises `unavailable` — never `turn-send`.
|
||||
expect(client.emit).toHaveBeenCalledWith('chat:send-capability', {
|
||||
protocol: 'unavailable',
|
||||
connectionId: 'browser-cap-pirpc',
|
||||
});
|
||||
const capabilityCalls = client.emit.mock.calls.filter(
|
||||
(call: unknown[]) => call[0] === 'chat:send-capability',
|
||||
);
|
||||
expect(capabilityCalls).toHaveLength(1);
|
||||
expect(capabilityCalls[0]?.[1]).not.toMatchObject({ protocol: 'turn-send' });
|
||||
});
|
||||
|
||||
it.each(['legacy', 'pi-rpc'] as const)(
|
||||
'never advertises send-capability to a Discord service socket (%s mode, Task 5 MAJOR-1)',
|
||||
async (mode) => {
|
||||
process.env['CHAT_HARNESS_RUNTIME'] = mode;
|
||||
process.env['DISCORD_SERVICE_TOKEN'] = 'super-secret-discord-token';
|
||||
const agentService = {
|
||||
getSession: vi.fn().mockReturnValue(undefined),
|
||||
createSession: vi.fn(),
|
||||
recordMessage: vi.fn(),
|
||||
onEvent: vi.fn().mockReturnValue((): void => undefined),
|
||||
addChannel: vi.fn(),
|
||||
prompt: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const gateway = new ChatGateway(
|
||||
readyRouter(mode, agentService, { append: vi.fn() }) as never,
|
||||
{ api: { getSession: vi.fn() } } as never,
|
||||
{ conversations: { addMessage: vi.fn().mockResolvedValue(undefined) } } as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
);
|
||||
const client = {
|
||||
id: `discord-service-${mode}`,
|
||||
handshake: { auth: { discordServiceToken: 'super-secret-discord-token' }, headers: {} },
|
||||
data: {} as Record<string, unknown>,
|
||||
emit: vi.fn(),
|
||||
disconnect: vi.fn(),
|
||||
};
|
||||
|
||||
await gateway.handleConnection(client as never);
|
||||
|
||||
// The trusted Discord service socket is not a browser; it never receives a browser
|
||||
// send-protocol advertisement.
|
||||
expect(client.data.discordService).toBe(true);
|
||||
expect(client.emit).not.toHaveBeenCalledWith('chat:send-capability', expect.anything());
|
||||
delete process.env['DISCORD_SERVICE_TOKEN'];
|
||||
},
|
||||
);
|
||||
|
||||
// Record-and-forward instrumentation at the REAL returned-lease boundary: wrap the lease's own
|
||||
// dispatch/dispose so the test observes the Gateway's invocation counts through the real
|
||||
// ChatRuntimeRouter -> EmbeddedChatRuntime path — no canned lease, synthesized method, or shim.
|
||||
const instrumentLease = (
|
||||
router: ChatRuntimeRouter,
|
||||
order: string[],
|
||||
counters: { dispatch: number; dispose: number },
|
||||
): void => {
|
||||
const realPrepare = router.prepareLegacySocketTurn.bind(router) as (
|
||||
...args: unknown[]
|
||||
) => Promise<{ ok: boolean; value?: { dispatch: () => unknown; dispose: () => unknown } }>;
|
||||
vi.spyOn(router, 'prepareLegacySocketTurn').mockImplementation((async (...args: unknown[]) => {
|
||||
const result = await realPrepare(...args);
|
||||
if (result.ok && result.value) {
|
||||
const lease = result.value;
|
||||
const realDispatch = lease.dispatch.bind(lease);
|
||||
const realDispose = lease.dispose.bind(lease);
|
||||
lease.dispatch = (): unknown => {
|
||||
counters.dispatch += 1;
|
||||
order.push('dispatch');
|
||||
return realDispatch();
|
||||
};
|
||||
lease.dispose = (): unknown => {
|
||||
counters.dispose += 1;
|
||||
return realDispose();
|
||||
};
|
||||
}
|
||||
return result;
|
||||
}) as never);
|
||||
};
|
||||
|
||||
it('orders a legacy browser turn persist -> ack -> lease.dispatch -> prompt, each exactly once (Task 5 G2)', async () => {
|
||||
process.env['CHAT_HARNESS_RUNTIME'] = 'legacy';
|
||||
const order: string[] = [];
|
||||
const counters = { dispatch: 0, dispose: 0 };
|
||||
const session = {
|
||||
provider: 'configured-provider',
|
||||
modelId: 'configured-model',
|
||||
piSession: {
|
||||
thinkingLevel: 'medium',
|
||||
getAvailableThinkingLevels: (): string[] => ['medium'],
|
||||
},
|
||||
};
|
||||
const agentService = {
|
||||
getSession: vi.fn().mockReturnValue(undefined),
|
||||
createSession: vi.fn().mockResolvedValue(session),
|
||||
recordMessage: vi.fn(),
|
||||
onEvent: vi.fn().mockReturnValue((): void => undefined),
|
||||
addChannel: vi.fn(),
|
||||
removeChannel: vi.fn(),
|
||||
prompt: vi.fn().mockImplementation(async (): Promise<void> => {
|
||||
order.push('prompt');
|
||||
}),
|
||||
};
|
||||
const harnessConversations = { append: vi.fn() };
|
||||
const brain = {
|
||||
conversations: {
|
||||
findById: vi.fn().mockResolvedValue({ id: 'conversation-order-1' }),
|
||||
findMessages: vi.fn().mockResolvedValue([]),
|
||||
create: vi.fn().mockResolvedValue(undefined),
|
||||
update: vi.fn().mockResolvedValue(undefined),
|
||||
addMessage: vi.fn().mockImplementation(async (): Promise<{ id: string }> => {
|
||||
order.push('persist');
|
||||
return { id: 'message-order-1' };
|
||||
}),
|
||||
},
|
||||
};
|
||||
const router = readyRouter('legacy', agentService, harnessConversations);
|
||||
instrumentLease(router, order, counters);
|
||||
const gateway = new ChatGateway(
|
||||
router as never,
|
||||
{ api: { getSession: vi.fn() } } as never,
|
||||
brain as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
);
|
||||
const client = {
|
||||
id: 'browser-order-1',
|
||||
data: { user: { id: 'user-a' } },
|
||||
emit: vi.fn().mockImplementation((event: string): void => {
|
||||
if (event === 'message:ack') order.push('ack');
|
||||
}),
|
||||
};
|
||||
|
||||
await gateway.handleMessage(
|
||||
client as never,
|
||||
{
|
||||
conversationId: 'conversation-order-1',
|
||||
content: 'ordered hello',
|
||||
} as never,
|
||||
);
|
||||
|
||||
// The Gateway persists the user turn, THEN acks, THEN invokes the one-shot lease dispatch which
|
||||
// finally prompts. Observed at the real lease boundary: dispatch is invoked exactly once and the
|
||||
// runtime prompts exactly once.
|
||||
expect(order).toEqual(['persist', 'ack', 'dispatch', 'prompt']);
|
||||
expect(counters.dispatch).toBe(1);
|
||||
expect(agentService.prompt).toHaveBeenCalledTimes(1);
|
||||
expect(harnessConversations.append).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('drops a legacy browser turn on persistence failure: zero info/ack/dispatch/prompt, one clean disposal (Task 5 G2)', async () => {
|
||||
process.env['CHAT_HARNESS_RUNTIME'] = 'legacy';
|
||||
const order: string[] = [];
|
||||
const counters = { dispatch: 0, dispose: 0 };
|
||||
const unsub = vi.fn();
|
||||
const session = {
|
||||
provider: 'configured-provider',
|
||||
modelId: 'configured-model',
|
||||
piSession: {
|
||||
thinkingLevel: 'medium',
|
||||
getAvailableThinkingLevels: (): string[] => ['medium'],
|
||||
},
|
||||
};
|
||||
const agentService = {
|
||||
getSession: vi.fn().mockReturnValue(undefined),
|
||||
createSession: vi.fn().mockResolvedValue(session),
|
||||
recordMessage: vi.fn(),
|
||||
onEvent: vi.fn().mockReturnValue(unsub),
|
||||
addChannel: vi.fn(),
|
||||
removeChannel: vi.fn(),
|
||||
prompt: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const harnessConversations = { append: vi.fn() };
|
||||
const brain = {
|
||||
conversations: {
|
||||
findById: vi.fn().mockResolvedValue({ id: 'conversation-fail-1' }),
|
||||
findMessages: vi.fn().mockResolvedValue([]),
|
||||
create: vi.fn().mockResolvedValue(undefined),
|
||||
update: vi.fn().mockResolvedValue(undefined),
|
||||
addMessage: vi.fn().mockRejectedValue(new Error('persistence unavailable')),
|
||||
},
|
||||
};
|
||||
const router = readyRouter('legacy', agentService, harnessConversations);
|
||||
instrumentLease(router, order, counters);
|
||||
const gateway = new ChatGateway(
|
||||
router as never,
|
||||
{ api: { getSession: vi.fn() } } as never,
|
||||
brain as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
);
|
||||
const client = {
|
||||
id: 'browser-fail-1',
|
||||
data: { user: { id: 'user-a' } },
|
||||
emit: vi.fn(),
|
||||
};
|
||||
|
||||
await gateway.handleMessage(
|
||||
client as never,
|
||||
{
|
||||
conversationId: 'conversation-fail-1',
|
||||
content: 'will fail persistence',
|
||||
} as never,
|
||||
);
|
||||
|
||||
// A failed user-message persistence aborts the turn with no accept-then-lose: no session:info,
|
||||
// no ack, the lease never dispatches or prompts, and the just-prepared lease is disposed exactly
|
||||
// once (listener/channel cleanup) without throwing. The fixed safe error is surfaced.
|
||||
expect(client.emit).not.toHaveBeenCalledWith('session:info', expect.anything());
|
||||
expect(client.emit).not.toHaveBeenCalledWith('message:ack', expect.anything());
|
||||
expect(counters.dispatch).toBe(0);
|
||||
expect(agentService.prompt).not.toHaveBeenCalled();
|
||||
expect(counters.dispose).toBe(1);
|
||||
expect(unsub).toHaveBeenCalledTimes(1);
|
||||
expect(client.emit).toHaveBeenCalledWith(
|
||||
'error',
|
||||
expect.objectContaining({ code: 'persist_failed' }),
|
||||
);
|
||||
expect(harnessConversations.append).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('drops a legacy browser turn when persistence RESOLVES nullish (not only on rejection): zero info/ack/dispatch/prompt, one clean disposal (Task 5 finding 2)', async () => {
|
||||
// Companion to the rejected-promise case above. A brain adapter that resolves `undefined`/`null`
|
||||
// instead of throwing must be treated as a persistence FAILURE, never as a saved message — the
|
||||
// pre-fix code accepted a nullish resolve and dispatched a turn whose user message was never
|
||||
// durably stored. RED before finding-2: the turn acks + dispatches + prompts on a phantom persist.
|
||||
process.env['CHAT_HARNESS_RUNTIME'] = 'legacy';
|
||||
const order: string[] = [];
|
||||
const counters = { dispatch: 0, dispose: 0 };
|
||||
const unsub = vi.fn();
|
||||
const session = {
|
||||
provider: 'configured-provider',
|
||||
modelId: 'configured-model',
|
||||
piSession: {
|
||||
thinkingLevel: 'medium',
|
||||
getAvailableThinkingLevels: (): string[] => ['medium'],
|
||||
},
|
||||
};
|
||||
const agentService = {
|
||||
getSession: vi.fn().mockReturnValue(undefined),
|
||||
createSession: vi.fn().mockResolvedValue(session),
|
||||
recordMessage: vi.fn(),
|
||||
onEvent: vi.fn().mockReturnValue(unsub),
|
||||
addChannel: vi.fn(),
|
||||
removeChannel: vi.fn(),
|
||||
prompt: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const harnessConversations = { append: vi.fn() };
|
||||
const brain = {
|
||||
conversations: {
|
||||
findById: vi.fn().mockResolvedValue({ id: 'conversation-nullish-1' }),
|
||||
findMessages: vi.fn().mockResolvedValue([]),
|
||||
create: vi.fn().mockResolvedValue(undefined),
|
||||
update: vi.fn().mockResolvedValue(undefined),
|
||||
// Resolves nullish rather than throwing: the fix must still fail the turn closed.
|
||||
addMessage: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
};
|
||||
const router = readyRouter('legacy', agentService, harnessConversations);
|
||||
instrumentLease(router, order, counters);
|
||||
const gateway = new ChatGateway(
|
||||
router as never,
|
||||
{ api: { getSession: vi.fn() } } as never,
|
||||
brain as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
);
|
||||
const client = {
|
||||
id: 'browser-nullish-1',
|
||||
data: { user: { id: 'user-a' } },
|
||||
emit: vi.fn(),
|
||||
};
|
||||
|
||||
await gateway.handleMessage(
|
||||
client as never,
|
||||
{
|
||||
conversationId: 'conversation-nullish-1',
|
||||
content: 'persist resolves undefined',
|
||||
} as never,
|
||||
);
|
||||
|
||||
expect(client.emit).not.toHaveBeenCalledWith('session:info', expect.anything());
|
||||
expect(client.emit).not.toHaveBeenCalledWith('message:ack', expect.anything());
|
||||
expect(counters.dispatch).toBe(0);
|
||||
expect(agentService.prompt).not.toHaveBeenCalled();
|
||||
expect(counters.dispose).toBe(1);
|
||||
expect(unsub).toHaveBeenCalledTimes(1);
|
||||
expect(client.emit).toHaveBeenCalledWith(
|
||||
'error',
|
||||
expect.objectContaining({ code: 'persist_failed' }),
|
||||
);
|
||||
expect(harnessConversations.append).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("fails a legacy browser send closed when the supplied conversationId is not the sender's: conversation_unavailable, zero persist/mint/dispatch/prompt (Task 5 finding 1)", async () => {
|
||||
// A browser socket that supplies a conversationId it does not own must be refused at admission,
|
||||
// BEFORE any runtime effect. Pre-fix, an unresolved/foreign id fell through to session mint +
|
||||
// dispatch, letting a caller attach to (or resurrect) a conversation outside their scope.
|
||||
process.env['CHAT_HARNESS_RUNTIME'] = 'legacy';
|
||||
const order: string[] = [];
|
||||
const counters = { dispatch: 0, dispose: 0 };
|
||||
const agentService = {
|
||||
getSession: vi.fn().mockReturnValue(undefined),
|
||||
createSession: vi.fn().mockResolvedValue(undefined),
|
||||
recordMessage: vi.fn(),
|
||||
onEvent: vi.fn().mockReturnValue((): void => undefined),
|
||||
addChannel: vi.fn(),
|
||||
removeChannel: vi.fn(),
|
||||
prompt: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const harnessConversations = { append: vi.fn() };
|
||||
const addMessage = vi.fn().mockResolvedValue({ id: 'must-not-persist' });
|
||||
const brain = {
|
||||
conversations: {
|
||||
// Scoped lookup: the sender does not own this id, so admission resolves undefined.
|
||||
findById: vi.fn().mockResolvedValue(undefined),
|
||||
findMessages: vi.fn().mockResolvedValue([]),
|
||||
create: vi.fn().mockResolvedValue(undefined),
|
||||
update: vi.fn().mockResolvedValue(undefined),
|
||||
addMessage,
|
||||
},
|
||||
};
|
||||
const router = readyRouter('legacy', agentService, harnessConversations);
|
||||
instrumentLease(router, order, counters);
|
||||
const gateway = new ChatGateway(
|
||||
router as never,
|
||||
{ api: { getSession: vi.fn() } } as never,
|
||||
brain as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
);
|
||||
const client = {
|
||||
id: 'browser-foreign-1',
|
||||
data: { user: { id: 'user-a' } },
|
||||
emit: vi.fn(),
|
||||
};
|
||||
|
||||
await gateway.handleMessage(
|
||||
client as never,
|
||||
{
|
||||
conversationId: 'conversation-foreign-1',
|
||||
content: 'let me into a conversation I do not own',
|
||||
} as never,
|
||||
);
|
||||
|
||||
// Admission consults the scoped durable record with the SENDER's id, then fails closed: no
|
||||
// persist, no session mint, no lease dispatch/dispose, no prompt, no ack — only the typed refusal.
|
||||
expect(brain.conversations.findById).toHaveBeenCalledWith('conversation-foreign-1', 'user-a');
|
||||
expect(addMessage).not.toHaveBeenCalled();
|
||||
expect(brain.conversations.create).not.toHaveBeenCalled();
|
||||
expect(agentService.createSession).not.toHaveBeenCalled();
|
||||
expect(agentService.onEvent).not.toHaveBeenCalled();
|
||||
expect(agentService.addChannel).not.toHaveBeenCalled();
|
||||
expect(agentService.prompt).not.toHaveBeenCalled();
|
||||
expect(counters.dispatch).toBe(0);
|
||||
expect(counters.dispose).toBe(0);
|
||||
expect(client.emit).not.toHaveBeenCalledWith('message:ack', expect.anything());
|
||||
expect(client.emit).toHaveBeenCalledWith(
|
||||
'error',
|
||||
expect.objectContaining({ code: 'conversation_unavailable' }),
|
||||
);
|
||||
expect(harnessConversations.append).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('admits a legacy browser send with NO conversationId by minting a scoped durable record first, then dispatches once (Task 5 finding 1)', async () => {
|
||||
// The distinct server-minted-new path: a client that omits conversationId is a brand-new
|
||||
// conversation. Admission must CREATE the durable record (scoped to the sender) before the turn
|
||||
// persists/dispatches, and must not consult the ownership lookup (there is nothing to authorize
|
||||
// yet). This guards the fix from over-reaching and breaking new-conversation creation.
|
||||
process.env['CHAT_HARNESS_RUNTIME'] = 'legacy';
|
||||
const order: string[] = [];
|
||||
const counters = { dispatch: 0, dispose: 0 };
|
||||
const session = {
|
||||
provider: 'configured-provider',
|
||||
modelId: 'configured-model',
|
||||
piSession: {
|
||||
thinkingLevel: 'medium',
|
||||
getAvailableThinkingLevels: (): string[] => ['medium'],
|
||||
},
|
||||
};
|
||||
const agentService = {
|
||||
getSession: vi.fn().mockReturnValue(undefined),
|
||||
createSession: vi.fn().mockResolvedValue(session),
|
||||
recordMessage: vi.fn(),
|
||||
onEvent: vi.fn().mockReturnValue((): void => undefined),
|
||||
addChannel: vi.fn(),
|
||||
removeChannel: vi.fn(),
|
||||
prompt: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const harnessConversations = { append: vi.fn() };
|
||||
const create = vi.fn().mockResolvedValue(undefined);
|
||||
const brain = {
|
||||
conversations: {
|
||||
findById: vi.fn().mockResolvedValue(undefined),
|
||||
findMessages: vi.fn().mockResolvedValue([]),
|
||||
create,
|
||||
update: vi.fn().mockResolvedValue(undefined),
|
||||
addMessage: vi.fn().mockResolvedValue({ id: 'persisted-new' }),
|
||||
},
|
||||
};
|
||||
const router = readyRouter('legacy', agentService, harnessConversations);
|
||||
instrumentLease(router, order, counters);
|
||||
const gateway = new ChatGateway(
|
||||
router as never,
|
||||
{ api: { getSession: vi.fn() } } as never,
|
||||
brain as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
);
|
||||
const client = {
|
||||
id: 'browser-new-1',
|
||||
data: { user: { id: 'user-a' } },
|
||||
emit: vi.fn(),
|
||||
};
|
||||
|
||||
await gateway.handleMessage(
|
||||
client as never,
|
||||
{
|
||||
content: 'first message with no conversationId',
|
||||
} as never,
|
||||
);
|
||||
|
||||
// The durable record is minted for the sender (create with the same server id the turn persists
|
||||
// under), and the admitted new-conversation turn dispatches exactly once.
|
||||
expect(create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: expect.any(String), userId: 'user-a' }),
|
||||
);
|
||||
expect(counters.dispatch).toBe(1);
|
||||
expect(agentService.prompt).toHaveBeenCalledTimes(1);
|
||||
expect(harnessConversations.append).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Chat DTO validation', () => {
|
||||
it('rejects unsupported message roles', () => {
|
||||
const dto = Object.assign(new SendMessageDto(), {
|
||||
|
||||
@@ -1,920 +0,0 @@
|
||||
import 'reflect-metadata';
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { Test, type TestingModule } from '@nestjs/testing';
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest';
|
||||
import type { HarnessAdapter, HarnessConversationService } from '@mosaicstack/types';
|
||||
import { AgentService } from '../agent/agent.service.js';
|
||||
import { AuthGuard } from '../auth/auth.guard.js';
|
||||
import { CommandsModule } from '../commands/commands.module.js';
|
||||
import { HarnessModule } from '../harness/harness.module.js';
|
||||
import { ChatModule } from './chat.module.js';
|
||||
import { ChatGateway } from './chat.gateway.js';
|
||||
import { HarnessRegistry } from '../harness/harness.registry.js';
|
||||
import {
|
||||
HARNESS_CONVERSATION_SERVICE,
|
||||
HARNESS_CONVERSATION_SERVICE_UNAVAILABLE,
|
||||
HARNESS_REGISTRY,
|
||||
type HarnessConversationServiceBinding,
|
||||
} from '../harness/harness.tokens.js';
|
||||
import { ChatRuntimeRouter } from './chat-runtime-router.js';
|
||||
import {
|
||||
ChatRuntimeUnavailableError,
|
||||
ownConversation,
|
||||
type ChatRuntime,
|
||||
type ChatRuntimeMode,
|
||||
type LegacyEmbeddedChatPort,
|
||||
type LegacyRuntimeStream,
|
||||
type LegacySessionPresentation,
|
||||
type LegacySocketTurnLease,
|
||||
type OwnedConversationContext,
|
||||
} from './chat-runtime.js';
|
||||
import { AppModule } from '../app.module.js';
|
||||
import { ProviderService } from '../agent/provider.service.js';
|
||||
|
||||
/**
|
||||
* Task Five, Step One (router). Proves the `ChatRuntimeRouter` resolves exactly one
|
||||
* runtime by mode, fails closed at init when `pi-rpc` preconditions are unmet, and
|
||||
* never downgrades `pi-rpc` to embedded execution. Red-first: the router is an
|
||||
* unimplemented stub, so every behavioural assertion below fails until Step Three.
|
||||
*/
|
||||
|
||||
const embedded: ChatRuntime = { kind: 'embedded' };
|
||||
const harness: ChatRuntime = { kind: 'harness' };
|
||||
|
||||
/** A structurally-complete, non-sentinel conversation service. Its methods are never invoked here. */
|
||||
const boundConversationService = {
|
||||
attach: () => Promise.reject(new Error('unused')),
|
||||
detach: () => Promise.reject(new Error('unused')),
|
||||
send: () => Promise.reject(new Error('unused')),
|
||||
|
||||
subscribeFrom: async function* () {
|
||||
throw new Error('unused');
|
||||
},
|
||||
} as unknown as HarnessConversationService;
|
||||
|
||||
function registryWith(adapterIds: readonly string[]): HarnessRegistry {
|
||||
const registry = new HarnessRegistry();
|
||||
for (const id of adapterIds) {
|
||||
registry.register({
|
||||
id,
|
||||
describe: () => Promise.reject(new Error('unused')),
|
||||
catalog: () => Promise.reject(new Error('unused')),
|
||||
create: () => Promise.reject(new Error('unused')),
|
||||
resume: () => Promise.reject(new Error('unused')),
|
||||
} as HarnessAdapter);
|
||||
}
|
||||
return registry;
|
||||
}
|
||||
|
||||
function buildRouter(
|
||||
mode: ChatRuntimeMode,
|
||||
opts: { adapters: readonly string[]; service: HarnessConversationServiceBinding },
|
||||
): ChatRuntimeRouter {
|
||||
return new ChatRuntimeRouter(registryWith(opts.adapters), opts.service, embedded, harness, mode);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tear down a module that was deliberately driven to a fail-closed init.
|
||||
* `NestApplicationContext.close()` re-awaits the module's `initializationPromise` before disposing
|
||||
* (nest-application-context.js:127); when `init()` rejected, that await re-throws the SAME typed
|
||||
* startup error, this time into teardown. Each caller here has already captured and asserted that
|
||||
* exact `ChatRuntimeUnavailableError` via `initError`, so the re-throw is expected teardown noise —
|
||||
* swallow ONLY that error, and surface anything else so a genuine teardown fault still fails loudly.
|
||||
*/
|
||||
async function closeIgnoringFailedInit(moduleRef: TestingModule): Promise<void> {
|
||||
await moduleRef.close().catch((err: unknown) => {
|
||||
if (err instanceof ChatRuntimeUnavailableError) return;
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
|
||||
describe('ChatRuntimeRouter', () => {
|
||||
it('resolves only the harness runtime in pi-rpc mode when pi adapter and conversation service are present', () => {
|
||||
const router = buildRouter('pi-rpc', {
|
||||
adapters: ['pi'],
|
||||
service: boundConversationService,
|
||||
});
|
||||
|
||||
expect(() => router.onModuleInit()).not.toThrow();
|
||||
expect(router.active).toBe(harness);
|
||||
expect(router.active.kind).toBe('harness');
|
||||
});
|
||||
|
||||
it('resolves only the embedded runtime in legacy mode and skips the pi preconditions', () => {
|
||||
// Empty registry + unavailable service: legacy must ignore both and still start.
|
||||
const router = buildRouter('legacy', {
|
||||
adapters: [],
|
||||
service: HARNESS_CONVERSATION_SERVICE_UNAVAILABLE,
|
||||
});
|
||||
|
||||
expect(() => router.onModuleInit()).not.toThrow();
|
||||
expect(router.active).toBe(embedded);
|
||||
expect(router.active.kind).toBe('embedded');
|
||||
});
|
||||
|
||||
it('fails closed at init when pi-rpc mode has no registered pi adapter', () => {
|
||||
const router = buildRouter('pi-rpc', {
|
||||
adapters: [],
|
||||
service: boundConversationService,
|
||||
});
|
||||
|
||||
expect(() => router.onModuleInit()).toThrow(ChatRuntimeUnavailableError);
|
||||
try {
|
||||
router.onModuleInit();
|
||||
expect.unreachable('onModuleInit must throw when the pi adapter is absent');
|
||||
} catch (err) {
|
||||
expect(err).toBeInstanceOf(ChatRuntimeUnavailableError);
|
||||
expect((err as ChatRuntimeUnavailableError).reason).toBe('adapter_unavailable');
|
||||
expect((err as ChatRuntimeUnavailableError).code).toBe('runtime_unsupported');
|
||||
}
|
||||
});
|
||||
|
||||
it('fails closed at init when pi-rpc mode has the unavailable conversation-service sentinel', () => {
|
||||
const router = buildRouter('pi-rpc', {
|
||||
adapters: ['pi'],
|
||||
service: HARNESS_CONVERSATION_SERVICE_UNAVAILABLE,
|
||||
});
|
||||
|
||||
try {
|
||||
router.onModuleInit();
|
||||
expect.unreachable('onModuleInit must throw when the conversation service is unbound');
|
||||
} catch (err) {
|
||||
expect(err).toBeInstanceOf(ChatRuntimeUnavailableError);
|
||||
expect((err as ChatRuntimeUnavailableError).reason).toBe('conversation_service_unavailable');
|
||||
expect((err as ChatRuntimeUnavailableError).code).toBe('runtime_unsupported');
|
||||
}
|
||||
});
|
||||
|
||||
it('never falls back to embedded execution when pi-rpc preconditions are unmet', () => {
|
||||
const router = buildRouter('pi-rpc', {
|
||||
adapters: [],
|
||||
service: HARNESS_CONVERSATION_SERVICE_UNAVAILABLE,
|
||||
});
|
||||
|
||||
expect(() => router.onModuleInit()).toThrow(ChatRuntimeUnavailableError);
|
||||
// A failed pi-rpc init must not silently expose the embedded runtime.
|
||||
expect(() => router.active).toThrow();
|
||||
let leaked: ChatRuntime | undefined;
|
||||
try {
|
||||
leaked = router.active;
|
||||
} catch {
|
||||
leaked = undefined;
|
||||
}
|
||||
expect(leaked).not.toBe(embedded);
|
||||
});
|
||||
|
||||
it('exposes only fixed, browser-safe failure text (no raw provider or exception detail)', () => {
|
||||
const router = buildRouter('pi-rpc', {
|
||||
adapters: [],
|
||||
service: boundConversationService,
|
||||
});
|
||||
|
||||
try {
|
||||
router.onModuleInit();
|
||||
expect.unreachable('onModuleInit must throw');
|
||||
} catch (err) {
|
||||
const message = (err as ChatRuntimeUnavailableError).message;
|
||||
expect(message).toBe(
|
||||
'The pi-rpc chat runtime is unavailable: no "pi" harness adapter is registered.',
|
||||
);
|
||||
expect(message).not.toMatch(/Error:|\bat \b|node_modules|Symbol\(/);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Task Five, Step Three — legacy port operations fail closed under pi-rpc (direct valid-input).
|
||||
*
|
||||
* The unit suite above constructs the router but never invokes a legacy port operation, so the
|
||||
* six per-operation inner `if (this.mode === 'pi-rpc')` guards are unexercised — a mutation that
|
||||
* deletes one of them SURVIVES for lack of a test that drives that operation. This group closes
|
||||
* that gap the right way: it drives each of the six operations DIRECTLY, in pi-rpc mode, with a
|
||||
* valid branded {@link OwnedConversationContext} and valid input, against a recording embedded
|
||||
* stub whose method returns a distinguishable `ok:true` success and increments a per-op counter.
|
||||
*
|
||||
* For each operation:
|
||||
* - pi-rpc test asserts the exact frozen `{ ok:false, code:'runtime_unsupported', retryable:false }`
|
||||
* result AND that the embedded stub was touched zero times (no effects);
|
||||
* - the paired legacy test proves that same stub method IS reached and returns its distinguishable
|
||||
* success when the mode does not refuse — so the pi-rpc zero-invocation assertion is meaningful,
|
||||
* not vacuously true because the stub could never be called.
|
||||
*
|
||||
* Deleting ONLY one operation's inner guard makes THAT operation's pi-rpc test behaviorally RED
|
||||
* (the router returns the embedded `ok:true` value and records the call), with every outer guard
|
||||
* and the other five inner guards intact. `next` is untouched; nothing here changes production.
|
||||
*/
|
||||
describe('ChatRuntimeRouter — legacy port ops fail closed under pi-rpc (Task Five, Step Three)', () => {
|
||||
const RUNTIME_UNSUPPORTED = {
|
||||
ok: false,
|
||||
code: 'runtime_unsupported',
|
||||
retryable: false,
|
||||
} as const;
|
||||
|
||||
const PRESENTATION: LegacySessionPresentation = {
|
||||
provider: 'embedded-provider',
|
||||
modelId: 'embedded-model',
|
||||
thinkingLevel: 'low',
|
||||
availableThinkingLevels: ['low', 'high'],
|
||||
};
|
||||
|
||||
const stream: LegacyRuntimeStream = {
|
||||
channelId: 'websocket:test-socket',
|
||||
onEvent: () => {},
|
||||
};
|
||||
|
||||
const ctx = (): OwnedConversationContext =>
|
||||
ownConversation('conversation-1', { userId: 'user-1', tenantId: 'tenant-1' });
|
||||
|
||||
/**
|
||||
* Per-operation invocation counters with declared keys (not an index signature) so each
|
||||
* `calls.<op>` is definitely `number` under `noUncheckedIndexedAccess`.
|
||||
*/
|
||||
type LegacyPortCallCounts = {
|
||||
completeLegacyRestTurn: number;
|
||||
prepareLegacySocketTurn: number;
|
||||
setLegacyThinking: number;
|
||||
abortLegacyTurn: number;
|
||||
applyLegacyModelOverride: number;
|
||||
readLegacySessionPresentation: number;
|
||||
dispatchVerifiedDiscordIngress: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* An embedded port that records every invocation and returns a distinguishable `ok:true`
|
||||
* value per operation. If a router op reaches it (its guard removed), both the recorded call
|
||||
* count and the returned `ok:true` value diverge from the frozen `runtime_unsupported` result.
|
||||
*/
|
||||
function recordingEmbeddedPort(): {
|
||||
port: ChatRuntime & LegacyEmbeddedChatPort;
|
||||
calls: LegacyPortCallCounts;
|
||||
} {
|
||||
const calls: LegacyPortCallCounts = {
|
||||
completeLegacyRestTurn: 0,
|
||||
prepareLegacySocketTurn: 0,
|
||||
setLegacyThinking: 0,
|
||||
abortLegacyTurn: 0,
|
||||
applyLegacyModelOverride: 0,
|
||||
readLegacySessionPresentation: 0,
|
||||
dispatchVerifiedDiscordIngress: 0,
|
||||
};
|
||||
const lease: LegacySocketTurnLease = {
|
||||
presentation: PRESENTATION,
|
||||
dispatch: () => Promise.resolve({ ok: true, value: undefined }),
|
||||
dispose: () => Promise.resolve(),
|
||||
};
|
||||
const port: ChatRuntime & LegacyEmbeddedChatPort = {
|
||||
kind: 'embedded',
|
||||
completeLegacyRestTurn: () => {
|
||||
calls.completeLegacyRestTurn += 1;
|
||||
return Promise.resolve({
|
||||
ok: true,
|
||||
value: { text: 'EMBEDDED-REST', presentation: PRESENTATION },
|
||||
});
|
||||
},
|
||||
prepareLegacySocketTurn: () => {
|
||||
calls.prepareLegacySocketTurn += 1;
|
||||
return Promise.resolve({ ok: true, value: lease });
|
||||
},
|
||||
setLegacyThinking: () => {
|
||||
calls.setLegacyThinking += 1;
|
||||
return { ok: true, value: PRESENTATION };
|
||||
},
|
||||
abortLegacyTurn: () => {
|
||||
calls.abortLegacyTurn += 1;
|
||||
return Promise.resolve({ ok: true, value: undefined });
|
||||
},
|
||||
applyLegacyModelOverride: () => {
|
||||
calls.applyLegacyModelOverride += 1;
|
||||
return { ok: true, value: PRESENTATION };
|
||||
},
|
||||
readLegacySessionPresentation: () => {
|
||||
calls.readLegacySessionPresentation += 1;
|
||||
return { ok: true, value: PRESENTATION };
|
||||
},
|
||||
dispatchVerifiedDiscordIngress: () => {
|
||||
calls.dispatchVerifiedDiscordIngress += 1;
|
||||
return Promise.resolve({
|
||||
ok: true,
|
||||
value: {
|
||||
presentation: PRESENTATION,
|
||||
dispatch: () => Promise.resolve({ ok: true, value: undefined }),
|
||||
dispose: () => Promise.resolve(),
|
||||
},
|
||||
});
|
||||
},
|
||||
};
|
||||
return { port, calls };
|
||||
}
|
||||
|
||||
function piRouter(port: ChatRuntime & LegacyEmbeddedChatPort): ChatRuntimeRouter {
|
||||
return new ChatRuntimeRouter(
|
||||
registryWith(['pi']),
|
||||
boundConversationService,
|
||||
port,
|
||||
harness,
|
||||
'pi-rpc',
|
||||
);
|
||||
}
|
||||
function legacyRouter(port: ChatRuntime & LegacyEmbeddedChatPort): ChatRuntimeRouter {
|
||||
return new ChatRuntimeRouter(
|
||||
registryWith([]),
|
||||
boundConversationService,
|
||||
port,
|
||||
harness,
|
||||
'legacy',
|
||||
);
|
||||
}
|
||||
|
||||
// completeLegacyRestTurn ---------------------------------------------------
|
||||
it('completeLegacyRestTurn refuses with runtime_unsupported and never touches embedded under pi-rpc', async () => {
|
||||
const { port, calls } = recordingEmbeddedPort();
|
||||
const result = await piRouter(port).completeLegacyRestTurn(ctx(), { content: 'hello' });
|
||||
expect(result).toEqual(RUNTIME_UNSUPPORTED);
|
||||
expect(calls.completeLegacyRestTurn).toBe(0);
|
||||
});
|
||||
it('completeLegacyRestTurn delegates to embedded under legacy (guard is the sole gate)', async () => {
|
||||
const { port, calls } = recordingEmbeddedPort();
|
||||
const result = await legacyRouter(port).completeLegacyRestTurn(ctx(), { content: 'hello' });
|
||||
expect(result.ok).toBe(true);
|
||||
expect(calls.completeLegacyRestTurn).toBe(1);
|
||||
});
|
||||
|
||||
// prepareLegacySocketTurn --------------------------------------------------
|
||||
it('prepareLegacySocketTurn refuses with runtime_unsupported and never touches embedded under pi-rpc', async () => {
|
||||
const { port, calls } = recordingEmbeddedPort();
|
||||
const result = await piRouter(port).prepareLegacySocketTurn(
|
||||
ctx(),
|
||||
{ content: 'hello' },
|
||||
stream,
|
||||
);
|
||||
expect(result).toEqual(RUNTIME_UNSUPPORTED);
|
||||
expect(calls.prepareLegacySocketTurn).toBe(0);
|
||||
});
|
||||
it('prepareLegacySocketTurn delegates to embedded under legacy (guard is the sole gate)', async () => {
|
||||
const { port, calls } = recordingEmbeddedPort();
|
||||
const result = await legacyRouter(port).prepareLegacySocketTurn(
|
||||
ctx(),
|
||||
{ content: 'hello' },
|
||||
stream,
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
expect(calls.prepareLegacySocketTurn).toBe(1);
|
||||
});
|
||||
|
||||
// setLegacyThinking (sync) -------------------------------------------------
|
||||
it('setLegacyThinking refuses with runtime_unsupported and never touches embedded under pi-rpc', () => {
|
||||
const { port, calls } = recordingEmbeddedPort();
|
||||
const result = piRouter(port).setLegacyThinking(ctx(), 'high');
|
||||
expect(result).toEqual(RUNTIME_UNSUPPORTED);
|
||||
expect(calls.setLegacyThinking).toBe(0);
|
||||
});
|
||||
it('setLegacyThinking delegates to embedded under legacy (guard is the sole gate)', () => {
|
||||
const { port, calls } = recordingEmbeddedPort();
|
||||
const result = legacyRouter(port).setLegacyThinking(ctx(), 'high');
|
||||
expect(result.ok).toBe(true);
|
||||
expect(calls.setLegacyThinking).toBe(1);
|
||||
});
|
||||
|
||||
// abortLegacyTurn ----------------------------------------------------------
|
||||
it('abortLegacyTurn refuses with runtime_unsupported and never touches embedded under pi-rpc', async () => {
|
||||
const { port, calls } = recordingEmbeddedPort();
|
||||
const result = await piRouter(port).abortLegacyTurn(ctx());
|
||||
expect(result).toEqual(RUNTIME_UNSUPPORTED);
|
||||
expect(calls.abortLegacyTurn).toBe(0);
|
||||
});
|
||||
it('abortLegacyTurn delegates to embedded under legacy (guard is the sole gate)', async () => {
|
||||
const { port, calls } = recordingEmbeddedPort();
|
||||
const result = await legacyRouter(port).abortLegacyTurn(ctx());
|
||||
expect(result.ok).toBe(true);
|
||||
expect(calls.abortLegacyTurn).toBe(1);
|
||||
});
|
||||
|
||||
// applyLegacyModelOverride (sync) ------------------------------------------
|
||||
it('applyLegacyModelOverride refuses with runtime_unsupported and never touches embedded under pi-rpc', () => {
|
||||
const { port, calls } = recordingEmbeddedPort();
|
||||
const result = piRouter(port).applyLegacyModelOverride(ctx(), 'model-x');
|
||||
expect(result).toEqual(RUNTIME_UNSUPPORTED);
|
||||
expect(calls.applyLegacyModelOverride).toBe(0);
|
||||
});
|
||||
it('applyLegacyModelOverride delegates to embedded under legacy (guard is the sole gate)', () => {
|
||||
const { port, calls } = recordingEmbeddedPort();
|
||||
const result = legacyRouter(port).applyLegacyModelOverride(ctx(), 'model-x');
|
||||
expect(result.ok).toBe(true);
|
||||
expect(calls.applyLegacyModelOverride).toBe(1);
|
||||
});
|
||||
|
||||
// readLegacySessionPresentation (sync) -------------------------------------
|
||||
it('readLegacySessionPresentation refuses with runtime_unsupported and never touches embedded under pi-rpc', () => {
|
||||
const { port, calls } = recordingEmbeddedPort();
|
||||
const result = piRouter(port).readLegacySessionPresentation(ctx());
|
||||
expect(result).toEqual(RUNTIME_UNSUPPORTED);
|
||||
expect(calls.readLegacySessionPresentation).toBe(0);
|
||||
});
|
||||
it('readLegacySessionPresentation delegates to embedded under legacy (guard is the sole gate)', () => {
|
||||
const { port, calls } = recordingEmbeddedPort();
|
||||
const result = legacyRouter(port).readLegacySessionPresentation(ctx());
|
||||
expect(result.ok).toBe(true);
|
||||
expect(calls.readLegacySessionPresentation).toBe(1);
|
||||
});
|
||||
|
||||
// dispatchVerifiedDiscordIngress delegates in BOTH modes (embedded-only, no guard) ---------
|
||||
it('dispatchVerifiedDiscordIngress delegates to embedded under pi-rpc (embedded-only, no mode guard)', async () => {
|
||||
const { port, calls } = recordingEmbeddedPort();
|
||||
const discordCtx = ctx() as unknown as Parameters<
|
||||
ChatRuntimeRouter['dispatchVerifiedDiscordIngress']
|
||||
>[0];
|
||||
const result = await piRouter(port).dispatchVerifiedDiscordIngress(discordCtx, stream);
|
||||
expect(result.ok).toBe(true);
|
||||
expect(calls.dispatchVerifiedDiscordIngress).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Task Five, Step Two — group 1 (real Nest module-graph readiness).
|
||||
*
|
||||
* The unit suite above constructs the router directly. This group drives the SAME contract
|
||||
* through a real NestJS graph: it imports the production `HarnessModule` (the proven-booting
|
||||
* idiom from harness.controller.spec.ts) so the router resolves the REAL, empty `HarnessRegistry`
|
||||
* via the real `HARNESS_REGISTRY` token, then runs the router's `OnModuleInit` through the Nest
|
||||
* lifecycle (`moduleRef.init()`). Red-first: the router is an unimplemented stub whose
|
||||
* `onModuleInit` throws a generic Error, so:
|
||||
* - readiness cases fail because the graph never comes up (init rejects), and
|
||||
* - fail-closed cases fail because a generic stub throw is NOT the SPECIFIC typed
|
||||
* `ChatRuntimeUnavailableError` (reason/code) the contract demands — a stub that
|
||||
* "throws anything" cannot mask these greens.
|
||||
* The router is NOT wired into a production module yet, so it is provided here via a factory
|
||||
* over the real registry token. Importing the real `ChatModule` bare is deliberately avoided:
|
||||
* it injects `AgentService` without importing `AgentModule`, so its graph fails to RESOLVE — a
|
||||
* collection/DI error, not a behavioural red. `next` is untouched; nothing here implements the router.
|
||||
*/
|
||||
describe('ChatRuntimeRouter — real Nest module-graph readiness (Task Five, Step Two group 1)', () => {
|
||||
async function bootRouterGraph(
|
||||
mode: ChatRuntimeMode,
|
||||
opts: { adapters: readonly string[]; service: HarnessConversationServiceBinding },
|
||||
) {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [HarnessModule],
|
||||
providers: [
|
||||
{
|
||||
provide: ChatRuntimeRouter,
|
||||
useFactory: (registry: HarnessRegistry) =>
|
||||
new ChatRuntimeRouter(registry, opts.service, embedded, harness, mode),
|
||||
inject: [HARNESS_REGISTRY],
|
||||
},
|
||||
],
|
||||
})
|
||||
// The imported HarnessModule's controllers reference AuthGuard (an HTTP-only concern,
|
||||
// never exercised here); stub it so the graph resolves. The registry is NOT overridden —
|
||||
// group 1 asserts against the genuine production HarnessRegistry.
|
||||
.overrideGuard(AuthGuard)
|
||||
.useValue({ canActivate: () => true })
|
||||
.compile();
|
||||
|
||||
// Resolve the production registry singleton and register the requested adapters ON IT, so
|
||||
// the router (which injects the same singleton) sees them when its lifecycle hook runs.
|
||||
const registry = moduleRef.get<HarnessRegistry>(HARNESS_REGISTRY, { strict: false });
|
||||
for (const id of opts.adapters) {
|
||||
registry.register({
|
||||
id,
|
||||
describe: () => Promise.reject(new Error('unused')),
|
||||
catalog: () => Promise.reject(new Error('unused')),
|
||||
create: () => Promise.reject(new Error('unused')),
|
||||
resume: () => Promise.reject(new Error('unused')),
|
||||
} as HarnessAdapter);
|
||||
}
|
||||
return moduleRef;
|
||||
}
|
||||
|
||||
// Capture an init rejection without letting a resolved init masquerade as success.
|
||||
const initError = (moduleRef: { init(): Promise<unknown> }): Promise<unknown> =>
|
||||
moduleRef.init().then(
|
||||
() => new Error('module init resolved but the contract requires it to reject'),
|
||||
(err: unknown) => err,
|
||||
);
|
||||
|
||||
it('brings the graph up and resolves only the harness runtime in pi-rpc mode (pi adapter + bound service)', async () => {
|
||||
const moduleRef = await bootRouterGraph('pi-rpc', {
|
||||
adapters: ['pi'],
|
||||
service: boundConversationService,
|
||||
});
|
||||
try {
|
||||
await moduleRef.init();
|
||||
const router = moduleRef.get(ChatRuntimeRouter, { strict: false });
|
||||
expect(router.active).toBe(harness);
|
||||
expect(router.active.kind).toBe('harness');
|
||||
} finally {
|
||||
await moduleRef.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('brings the graph up in legacy mode over the REAL empty HarnessRegistry and resolves only the embedded runtime', async () => {
|
||||
const moduleRef = await bootRouterGraph('legacy', {
|
||||
adapters: [],
|
||||
service: HARNESS_CONVERSATION_SERVICE_UNAVAILABLE,
|
||||
});
|
||||
try {
|
||||
// Defense-in-depth: the production module wires the genuine registry, empty by default —
|
||||
// guards against a test-double registry silently satisfying the readiness check.
|
||||
const registry = moduleRef.get<HarnessRegistry>(HARNESS_REGISTRY, { strict: false });
|
||||
expect(registry).toBeInstanceOf(HarnessRegistry);
|
||||
expect(registry.list()).toHaveLength(0);
|
||||
|
||||
await moduleRef.init();
|
||||
const router = moduleRef.get(ChatRuntimeRouter, { strict: false });
|
||||
expect(router.active).toBe(embedded);
|
||||
expect(router.active.kind).toBe('embedded');
|
||||
} finally {
|
||||
await moduleRef.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('fails closed at module init when pi-rpc mode has no registered pi adapter (specific typed error, not a stub throw)', async () => {
|
||||
const moduleRef = await bootRouterGraph('pi-rpc', {
|
||||
adapters: [],
|
||||
service: boundConversationService,
|
||||
});
|
||||
try {
|
||||
const err = await initError(moduleRef);
|
||||
expect(err).toBeInstanceOf(ChatRuntimeUnavailableError);
|
||||
expect((err as ChatRuntimeUnavailableError).reason).toBe('adapter_unavailable');
|
||||
expect((err as ChatRuntimeUnavailableError).code).toBe('runtime_unsupported');
|
||||
} finally {
|
||||
await closeIgnoringFailedInit(moduleRef);
|
||||
}
|
||||
});
|
||||
|
||||
it('fails closed at module init when pi-rpc mode has the unavailable conversation-service sentinel', async () => {
|
||||
const moduleRef = await bootRouterGraph('pi-rpc', {
|
||||
adapters: ['pi'],
|
||||
service: HARNESS_CONVERSATION_SERVICE_UNAVAILABLE,
|
||||
});
|
||||
try {
|
||||
const err = await initError(moduleRef);
|
||||
expect(err).toBeInstanceOf(ChatRuntimeUnavailableError);
|
||||
expect((err as ChatRuntimeUnavailableError).reason).toBe('conversation_service_unavailable');
|
||||
expect((err as ChatRuntimeUnavailableError).code).toBe('runtime_unsupported');
|
||||
} finally {
|
||||
await closeIgnoringFailedInit(moduleRef);
|
||||
}
|
||||
});
|
||||
|
||||
it('surfaces only fixed, browser-safe failure text when the graph fails closed (no stub/exception detail)', async () => {
|
||||
const moduleRef = await bootRouterGraph('pi-rpc', {
|
||||
adapters: [],
|
||||
service: boundConversationService,
|
||||
});
|
||||
try {
|
||||
const err = await initError(moduleRef);
|
||||
expect(err).toBeInstanceOf(ChatRuntimeUnavailableError);
|
||||
const message = (err as ChatRuntimeUnavailableError).message;
|
||||
expect(message).toBe(
|
||||
'The pi-rpc chat runtime is unavailable: no "pi" harness adapter is registered.',
|
||||
);
|
||||
expect(message).not.toMatch(/Error:|\bat \b|node_modules|Symbol\(|not implemented/);
|
||||
} finally {
|
||||
await closeIgnoringFailedInit(moduleRef);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Task Five, Step Two — group 1b (production ChatModule wiring, declaration proof).
|
||||
*
|
||||
* Correction #1 (Scrappy fe3e02) asked for a red that imports the real `ChatModule` and calls
|
||||
* `module.init()`. Investigated and found impractical/masking-prone: `ChatModule` provides
|
||||
* `ChatGateway`, whose 10-argument constructor injects app-global providers (AgentService, AUTH,
|
||||
* BRAIN, RoutingEngineService) plus the Commands/GC/Mcp/Reload subsystems across a forwardRef
|
||||
* cycle. Booting it in isolation is a full-app integration boot — "override only unrelated
|
||||
* dependencies" balloons into faking ~4 subsystems, and `overrideProvider` cannot even grant the
|
||||
* cross-module export-scope visibility ChatGateway needs (probe: `ChatGateway` unresolved at
|
||||
* `CommandExecutorService`). That is exactly the STOP-and-return branch of the directive.
|
||||
*
|
||||
* The faithful, unmaskable cover instead of a fragile boot: read the PRODUCTION `ChatModule`'s own
|
||||
* Nest `@Module` metadata to prove it DECLARES the exclusive router provider and imports the real
|
||||
* `HarnessModule` (the genuine registry source). This inspects the actual module object — not
|
||||
* source text, not a test factory — so nothing can mask it. Group 1 above separately proves the
|
||||
* router RESOLVES against the real, empty `HarnessRegistry` through the Nest lifecycle; the union
|
||||
* of the two covers "the router is wired through ChatModule to the real registry" without the
|
||||
* impractical single-graph boot. RED today (ChatModule provides only ChatGateway and imports only
|
||||
* CommandsModule); GREEN once Step Three registers the router and imports HarnessModule.
|
||||
*/
|
||||
describe('ChatModule production wiring (Task Five, Step Two group 1b — declaration proof)', () => {
|
||||
// Unwrap a forwardRef(() => Module) import to the module it references; pass others through.
|
||||
const resolveImport = (imp: unknown): unknown =>
|
||||
imp &&
|
||||
typeof imp === 'object' &&
|
||||
typeof (imp as { forwardRef?: unknown }).forwardRef === 'function'
|
||||
? (imp as { forwardRef: () => unknown }).forwardRef()
|
||||
: imp;
|
||||
|
||||
// A provider entry is either a class (shorthand) or a { provide, ... } object; take its token.
|
||||
const providerToken = (provider: unknown): unknown =>
|
||||
typeof provider === 'function' ? provider : (provider as { provide?: unknown })?.provide;
|
||||
|
||||
it('declares the exclusive ChatRuntimeRouter as a provider on the production ChatModule', () => {
|
||||
const providers: unknown[] = Reflect.getMetadata('providers', ChatModule) ?? [];
|
||||
expect(providers.map(providerToken)).toContain(ChatRuntimeRouter);
|
||||
});
|
||||
|
||||
it('imports the real HarnessModule into the production ChatModule (registry source, not a test double)', () => {
|
||||
const imports: unknown[] = Reflect.getMetadata('imports', ChatModule) ?? [];
|
||||
expect(imports.map(resolveImport)).toContain(HarnessModule);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Task Five, Step Two — group 1c (bounded real-`ChatModule` boot).
|
||||
*
|
||||
* Scrappy adjudication d67d2b (option c): boot the ACTUAL production `ChatModule` as the SUT and
|
||||
* assert the exclusive router resolves THROUGH it — the single-graph proof group 1 (router over the
|
||||
* real registry) and group 1b (production-module metadata) each cover only a half of. The heavy,
|
||||
* UNRELATED cycle is the only thing bounded away, per the established isolation pattern in
|
||||
* `apps/gateway/src/agent/hermes-runtime-reachability.e2e.test.ts`:
|
||||
* - `CommandsModule` (drags the Commands <-> Reload <-> Chat forwardRef cycle plus GC/Mcp/queue)
|
||||
* is replaced wholesale with an empty module via `.overrideModule(...).useModule(...)`;
|
||||
* - `ChatGateway` (10-arg constructor, an HTTP/socket concern never exercised here) is replaced
|
||||
* with an inert value;
|
||||
* - the sole legacy-controller dependency, `AgentService`, is supplied by a tiny `@Global()` stub;
|
||||
* - the HTTP-only `AuthGuard` is stubbed.
|
||||
* Nothing about the router, `HarnessModule`, the registry, or the conversation-service binding is
|
||||
* faked in the production-legacy case — those are retrieved from the REAL `ChatModule` graph. Mode
|
||||
* is driven only through the production `CHAT_HARNESS_RUNTIME` env contract (`resolveChatRuntimeMode`).
|
||||
*
|
||||
* Red-first: today `ChatModule` neither imports `HarnessModule` nor provides `ChatRuntimeRouter`, so
|
||||
* the booted graph contains no router/registry/conversation-service tokens. `init()` may resolve
|
||||
* (there is no router lifecycle hook yet to reject), so every case fails on the MISSING actual
|
||||
* router/registry/service wiring — not on unrelated DI, which is bounded away. GREEN at Step Three
|
||||
* once `ChatModule` imports `HarnessModule`, provides the exclusive router, and binds the
|
||||
* conversation-service token (defaulting to the unavailable sentinel).
|
||||
*/
|
||||
describe('ChatModule bounded real boot (Task Five, Step Two group 1c)', () => {
|
||||
// The unrelated heavy cycle, replaced wholesale — not stubbed provider-by-provider.
|
||||
@Module({})
|
||||
class EmptyCommandsModule {}
|
||||
|
||||
// The ONLY genuine legacy dependency of the real ChatController, supplied inertly and globally so
|
||||
// the pre-refactor controller instantiates without dragging AgentModule into the graph.
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [{ provide: AgentService, useValue: {} }],
|
||||
exports: [AgentService],
|
||||
})
|
||||
class LegacyControllerDepsModule {}
|
||||
|
||||
const ORIGINAL_RUNTIME_ENV = process.env['CHAT_HARNESS_RUNTIME'];
|
||||
afterEach(() => {
|
||||
if (ORIGINAL_RUNTIME_ENV === undefined) delete process.env['CHAT_HARNESS_RUNTIME'];
|
||||
else process.env['CHAT_HARNESS_RUNTIME'] = ORIGINAL_RUNTIME_ENV;
|
||||
});
|
||||
|
||||
/**
|
||||
* Boot the real ChatModule with only the unrelated cycle bounded away. `mode` is set through the
|
||||
* genuine production env contract before providers instantiate. The optional overrides replace
|
||||
* the registry / conversation-service the router injects, exercising the pi-rpc precondition
|
||||
* branches through the ACTUAL module (they are no-ops today because those tokens are not yet in
|
||||
* the graph — which is exactly why the router-retrieval assertions go red).
|
||||
*/
|
||||
async function bootChatModule(
|
||||
mode: ChatRuntimeMode,
|
||||
overrides: {
|
||||
registryAdapters?: readonly string[];
|
||||
conversationService?: HarnessConversationServiceBinding;
|
||||
} = {},
|
||||
): Promise<TestingModule> {
|
||||
if (mode === 'pi-rpc') process.env['CHAT_HARNESS_RUNTIME'] = 'pi-rpc';
|
||||
else delete process.env['CHAT_HARNESS_RUNTIME'];
|
||||
|
||||
let builder = Test.createTestingModule({
|
||||
imports: [LegacyControllerDepsModule, ChatModule],
|
||||
})
|
||||
.overrideModule(CommandsModule)
|
||||
.useModule(EmptyCommandsModule)
|
||||
.overrideProvider(ChatGateway)
|
||||
.useValue({})
|
||||
.overrideGuard(AuthGuard)
|
||||
.useValue({ canActivate: () => true });
|
||||
|
||||
if (overrides.registryAdapters) {
|
||||
builder = builder
|
||||
.overrideProvider(HARNESS_REGISTRY)
|
||||
.useValue(registryWith(overrides.registryAdapters));
|
||||
}
|
||||
if (overrides.conversationService !== undefined) {
|
||||
builder = builder
|
||||
.overrideProvider(HARNESS_CONVERSATION_SERVICE)
|
||||
.useValue(overrides.conversationService);
|
||||
}
|
||||
return builder.compile();
|
||||
}
|
||||
|
||||
// Capture an init rejection without letting a resolved init masquerade as success.
|
||||
const initError = (moduleRef: TestingModule): Promise<unknown> =>
|
||||
moduleRef.init().then(
|
||||
() => new Error('module init resolved but the contract requires it to reject'),
|
||||
(err: unknown) => err,
|
||||
);
|
||||
|
||||
it('legacy mode: the actual router resolves the embedded runtime, the actual registry is empty, and the conversation-service token is the unavailable sentinel', async () => {
|
||||
const moduleRef = await bootChatModule('legacy');
|
||||
try {
|
||||
await moduleRef.init();
|
||||
const router = moduleRef.get(ChatRuntimeRouter, { strict: false });
|
||||
expect(router.active.kind).toBe('embedded');
|
||||
|
||||
const registry = moduleRef.get<HarnessRegistry>(HARNESS_REGISTRY, { strict: false });
|
||||
expect(registry).toBeInstanceOf(HarnessRegistry);
|
||||
expect(registry.list()).toHaveLength(0);
|
||||
|
||||
const service = moduleRef.get<HarnessConversationServiceBinding>(
|
||||
HARNESS_CONVERSATION_SERVICE,
|
||||
{
|
||||
strict: false,
|
||||
},
|
||||
);
|
||||
expect(service).toBe(HARNESS_CONVERSATION_SERVICE_UNAVAILABLE);
|
||||
} finally {
|
||||
await moduleRef.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('pi-rpc mode over the REAL empty registry fails closed at init with the typed adapter-unavailable error', async () => {
|
||||
const moduleRef = await bootChatModule('pi-rpc');
|
||||
try {
|
||||
const err = await initError(moduleRef);
|
||||
expect(err).toBeInstanceOf(ChatRuntimeUnavailableError);
|
||||
expect((err as ChatRuntimeUnavailableError).reason).toBe('adapter_unavailable');
|
||||
expect((err as ChatRuntimeUnavailableError).code).toBe('runtime_unsupported');
|
||||
} finally {
|
||||
await closeIgnoringFailedInit(moduleRef);
|
||||
}
|
||||
});
|
||||
|
||||
it('pi-rpc mode with a pi adapter present but the sentinel conversation service fails closed with the typed conversation-service-unavailable error', async () => {
|
||||
const moduleRef = await bootChatModule('pi-rpc', {
|
||||
registryAdapters: ['pi'],
|
||||
conversationService: HARNESS_CONVERSATION_SERVICE_UNAVAILABLE,
|
||||
});
|
||||
try {
|
||||
const err = await initError(moduleRef);
|
||||
expect(err).toBeInstanceOf(ChatRuntimeUnavailableError);
|
||||
expect((err as ChatRuntimeUnavailableError).reason).toBe('conversation_service_unavailable');
|
||||
expect((err as ChatRuntimeUnavailableError).code).toBe('runtime_unsupported');
|
||||
} finally {
|
||||
await closeIgnoringFailedInit(moduleRef);
|
||||
}
|
||||
});
|
||||
|
||||
it('pi-rpc mode with a pi adapter and a bound conversation service: the actual router selects the harness runtime', async () => {
|
||||
const moduleRef = await bootChatModule('pi-rpc', {
|
||||
registryAdapters: ['pi'],
|
||||
conversationService: boundConversationService,
|
||||
});
|
||||
try {
|
||||
await moduleRef.init();
|
||||
const router = moduleRef.get(ChatRuntimeRouter, { strict: false });
|
||||
expect(router.active.kind).toBe('harness');
|
||||
} finally {
|
||||
await moduleRef.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Task Five, Step Two — group 2 (WHOLE production `AppModule` boot, legacy end-to-end wiring).
|
||||
*
|
||||
* The groups above bound away the heavy cycle to isolate the router. This group instead boots the
|
||||
* ACTUAL production `AppModule` (the exact graph `main.ts` runs) in the default LEGACY chat-runtime
|
||||
* mode, overriding ONLY the storage/network side-effect adapters so the boot is bounded and offline
|
||||
* — never the chat/router/harness/reload/commands surface under test. The bounded fakes are exactly
|
||||
* the disk/network leaves:
|
||||
* - `ProviderService` (the #1 hang risk: its real `onModuleInit` starts an unref'd health-check
|
||||
* `setInterval` and fetches Ollama over HTTP) → inert no-op instance;
|
||||
* - `DB_HANDLE`/`DB` → a fake Drizzle-shaped handle that satisfies `runPgliteMigrations` (the local
|
||||
* tier's `DatabaseModule.onModuleInit`) AND `DefaultRoutingRulesSeed.onModuleInit` (which reads a
|
||||
* system-rule count — the fake reports rules already present so the seed insert is skipped),
|
||||
* opening no real database;
|
||||
* - `STORAGE_ADAPTER`/`MEMORY`/`MEMORY_ADAPTER`/`AUTH`/`BRAIN`/`LOG_SERVICE` → inert fakes so no
|
||||
* storage/auth/log backend is contacted.
|
||||
* Local tier (the repo's `mosaic.config.json`) already disables BullMQ/Redis and the queue handles;
|
||||
* Discord/Telegram/MCP plugins are env-gated and disarmed by deleting their tokens. Nothing about the
|
||||
* router, `ChatModule`, `HarnessModule`, or `ChatGateway` is faked — those come from the REAL graph.
|
||||
*
|
||||
* The boot+init MUST SUCCEED cleanly (proven by `beforeAll` completing and the ChatGateway test
|
||||
* passing). Red-first: on this branch `ChatRuntimeRouter` is registered in NO module (ChatModule
|
||||
* provides only ChatGateway), so `moduleRef.get(ChatRuntimeRouter)` throws `UnknownElementException`
|
||||
* — a WIRING gap, NOT an init failure. That single retrieval is the intended behavioural red; it
|
||||
* flips green once Step Three registers the exclusive router. The ChatGateway retrieval and its
|
||||
* browser-facing method surface are asserted alongside and pass today, pinning that the boot itself
|
||||
* is healthy so the router failure cannot be mistaken for a mis-shaped fake or an unbounded side
|
||||
* effect.
|
||||
*/
|
||||
describe('AppModule production boot — legacy ChatRuntimeRouter wiring (Task Five, Step Two group 2)', () => {
|
||||
// A Drizzle-shaped fake that satisfies both DB consumers reached during a local-tier init:
|
||||
// • runPgliteMigrations(): reads handle.db.$client.exec + handle.db.execute(SELECT hashes);
|
||||
// exec is a no-op and execute yields an empty ledger, so migration statements no-op through.
|
||||
// • DefaultRoutingRulesSeed.seedDefaultRules(): db.select().from().where() must resolve to a
|
||||
// row set — we report a non-zero system-rule count so the seeding INSERT branch is skipped.
|
||||
const fakeDb = {
|
||||
$client: { exec: async (): Promise<void> => {} },
|
||||
execute: async (): Promise<{ rows: unknown[] }> => ({ rows: [] }),
|
||||
select: () => ({
|
||||
from: () => ({
|
||||
where: async (): Promise<Array<{ count: number }>> => [{ count: 1 }],
|
||||
}),
|
||||
}),
|
||||
insert: () => ({ values: async (): Promise<void> => {} }),
|
||||
};
|
||||
const fakeDbHandle = { db: fakeDb, close: async (): Promise<void> => {} };
|
||||
const fakeStorageAdapter = {
|
||||
name: 'fake',
|
||||
migrate: async (): Promise<void> => {},
|
||||
close: async (): Promise<void> => {},
|
||||
};
|
||||
// Inert stand-in for the real ProviderService: no health-check interval, no Ollama fetch.
|
||||
const fakeProviderService = {
|
||||
onModuleInit: async (): Promise<void> => {},
|
||||
onModuleDestroy: (): void => {},
|
||||
getRegistry: () => ({
|
||||
getAvailable: () => [],
|
||||
getAll: () => [],
|
||||
find: () => undefined,
|
||||
}),
|
||||
getDefaultModel: () => undefined,
|
||||
listAvailableModels: () => [],
|
||||
listProviders: () => [],
|
||||
getAdapter: () => undefined,
|
||||
getProvidersHealth: () => [],
|
||||
};
|
||||
const fakeBrain = { conversations: {}, agents: {} };
|
||||
|
||||
const BOOT_TIMEOUT_MS = 120_000;
|
||||
|
||||
let moduleRef: TestingModule;
|
||||
let envSnapshot: Record<string, string | undefined>;
|
||||
|
||||
beforeAll(async () => {
|
||||
envSnapshot = { ...process.env };
|
||||
// Env hygiene: disarm the network-facing plugins/adapters and pin the legacy runtime mode.
|
||||
delete process.env['DATABASE_URL'];
|
||||
delete process.env['DISCORD_BOT_TOKEN'];
|
||||
delete process.env['TELEGRAM_BOT_TOKEN'];
|
||||
delete process.env['MCP_SERVERS'];
|
||||
delete process.env['CHAT_HARNESS_RUNTIME']; // resolveChatRuntimeMode → 'legacy'
|
||||
process.env['MOSAIC_STORAGE_TIER'] = 'local';
|
||||
|
||||
moduleRef = await Test.createTestingModule({ imports: [AppModule] })
|
||||
// Storage/network side-effect adapters ONLY — never the router/chat/harness surface under test.
|
||||
.overrideProvider('DB_HANDLE')
|
||||
.useValue(fakeDbHandle)
|
||||
.overrideProvider('DB')
|
||||
.useValue(fakeDb)
|
||||
.overrideProvider('STORAGE_ADAPTER')
|
||||
.useValue(fakeStorageAdapter)
|
||||
.overrideProvider('AUTH')
|
||||
.useValue({})
|
||||
.overrideProvider('BRAIN')
|
||||
.useValue(fakeBrain)
|
||||
.overrideProvider('LOG_SERVICE')
|
||||
.useValue({})
|
||||
.overrideProvider('MEMORY')
|
||||
.useValue({})
|
||||
.overrideProvider('MEMORY_ADAPTER')
|
||||
.useValue({})
|
||||
.overrideProvider(ProviderService)
|
||||
.useValue(fakeProviderService)
|
||||
.compile();
|
||||
|
||||
// The boot itself MUST succeed cleanly — a rejection here is a bounding failure, not the red.
|
||||
await moduleRef.init();
|
||||
}, BOOT_TIMEOUT_MS);
|
||||
|
||||
afterAll(async () => {
|
||||
if (moduleRef) await moduleRef.close();
|
||||
for (const key of Object.keys(process.env)) {
|
||||
if (!(key in envSnapshot)) delete process.env[key];
|
||||
}
|
||||
for (const [key, value] of Object.entries(envSnapshot)) {
|
||||
if (value === undefined) delete process.env[key];
|
||||
else process.env[key] = value;
|
||||
}
|
||||
});
|
||||
|
||||
// Passes TODAY: the real ChatGateway is provided by the real ChatModule and its browser-facing
|
||||
// surface exists. This pins that the whole-AppModule boot came up healthy, so the router failure
|
||||
// below is unambiguously a wiring gap and not a mis-shaped fake or an unbounded side effect.
|
||||
it('boots the whole AppModule and exposes the real ChatGateway with its browser-facing methods', () => {
|
||||
const gateway = moduleRef.get(ChatGateway, { strict: false });
|
||||
expect(typeof gateway.broadcastReload).toBe('function');
|
||||
expect(typeof gateway.getModelOverride).toBe('function');
|
||||
expect(typeof gateway.setModelOverride).toBe('function');
|
||||
expect(typeof gateway.broadcastSessionInfo).toBe('function');
|
||||
});
|
||||
|
||||
// RED TODAY: ChatRuntimeRouter is registered in no module on this branch, so this retrieval throws
|
||||
// UnknownElementException — the intended red-first wiring failure. GREEN once Step Three registers
|
||||
// the exclusive router in the production graph, where legacy mode resolves the embedded runtime.
|
||||
it('resolves the exclusive ChatRuntimeRouter to the embedded runtime in legacy mode', () => {
|
||||
const router = moduleRef.get(ChatRuntimeRouter, { strict: false });
|
||||
expect(router.active.kind).toBe('embedded');
|
||||
});
|
||||
});
|
||||
@@ -1,173 +0,0 @@
|
||||
import { Injectable, type OnModuleInit } from '@nestjs/common';
|
||||
import { HarnessRegistry } from '../harness/harness.registry.js';
|
||||
import {
|
||||
isHarnessConversationServiceAvailable,
|
||||
type HarnessConversationServiceBinding,
|
||||
} from '../harness/harness.tokens.js';
|
||||
import type {
|
||||
ChatRuntime,
|
||||
ChatRuntimeMode,
|
||||
LegacyBrowserMessagePayload,
|
||||
LegacyEmbeddedChatPort,
|
||||
LegacyRuntimeResult,
|
||||
LegacyRuntimeStream,
|
||||
LegacySessionPresentation,
|
||||
LegacySocketTurnLease,
|
||||
OwnedConversationContext,
|
||||
VerifiedDiscordIngressContext,
|
||||
VerifiedDiscordTurnLease,
|
||||
} from './chat-runtime.js';
|
||||
import { ChatRuntimeUnavailableError, resolveChatRuntimeMode } from './chat-runtime.js';
|
||||
|
||||
/** The fixed fail-closed result for a legacy browser operation issued under `pi-rpc`. */
|
||||
const RUNTIME_UNSUPPORTED = {
|
||||
ok: false as const,
|
||||
code: 'runtime_unsupported' as const,
|
||||
retryable: false as const,
|
||||
};
|
||||
|
||||
/**
|
||||
* Resolves the one live {@link ChatRuntime} for this process and enforces the
|
||||
* `pi-rpc` readiness preconditions at module init — before the gateway accepts
|
||||
* traffic. It never falls back from `pi-rpc` to embedded execution: an unmet
|
||||
* `pi-rpc` precondition is a typed startup failure ({@link ChatRuntimeUnavailableError}),
|
||||
* and until `onModuleInit` selects a runtime, {@link active} throws rather than
|
||||
* exposing any runtime — a failed `pi-rpc` init can never leak the embedded one.
|
||||
*/
|
||||
@Injectable()
|
||||
export class ChatRuntimeRouter implements OnModuleInit, LegacyEmbeddedChatPort {
|
||||
private readonly mode: ChatRuntimeMode;
|
||||
|
||||
/** The single resolved runtime. Undefined until a successful `onModuleInit`. */
|
||||
private resolved: ChatRuntime | undefined;
|
||||
|
||||
constructor(
|
||||
private readonly harnessRegistry: HarnessRegistry,
|
||||
private readonly conversationService: HarnessConversationServiceBinding,
|
||||
private readonly embedded: ChatRuntime,
|
||||
private readonly harness: ChatRuntime,
|
||||
mode: ChatRuntimeMode = resolveChatRuntimeMode(),
|
||||
) {
|
||||
this.mode = mode;
|
||||
}
|
||||
|
||||
onModuleInit(): void {
|
||||
if (this.mode === 'legacy') {
|
||||
// Legacy ignores the pi-rpc preconditions entirely and always runs embedded.
|
||||
this.resolved = this.embedded;
|
||||
return;
|
||||
}
|
||||
|
||||
// pi-rpc: both preconditions are hard startup failures, checked in a fixed order.
|
||||
if (!this.harnessRegistry.has('pi')) {
|
||||
this.resolved = undefined;
|
||||
throw new ChatRuntimeUnavailableError('adapter_unavailable');
|
||||
}
|
||||
if (!isHarnessConversationServiceAvailable(this.conversationService)) {
|
||||
this.resolved = undefined;
|
||||
throw new ChatRuntimeUnavailableError('conversation_service_unavailable');
|
||||
}
|
||||
|
||||
this.resolved = this.harness;
|
||||
}
|
||||
|
||||
get active(): ChatRuntime {
|
||||
if (this.resolved === undefined) {
|
||||
// Reached only if init has not run or failed closed; never expose a runtime here.
|
||||
throw new Error('The chat runtime is not available: startup did not resolve a runtime.');
|
||||
}
|
||||
return this.resolved;
|
||||
}
|
||||
|
||||
/**
|
||||
* The process-wide mode, available before {@link onModuleInit}. Production handlers read
|
||||
* this to fail a legacy browser turn closed under `pi-rpc` *before* parsing the payload as
|
||||
* either browser-legacy input or a Discord envelope — never to branch into a fallback.
|
||||
*/
|
||||
get runtimeMode(): ChatRuntimeMode {
|
||||
return this.mode;
|
||||
}
|
||||
|
||||
/**
|
||||
* The embedded runtime narrowed to its port. Only reached on the legacy path (and for the
|
||||
* verified-Discord op in both modes), where the injected runtime is always a real
|
||||
* `EmbeddedChatRuntime`. The router spec constructs the router with a bare `{ kind }` stub
|
||||
* but never invokes a port op, so this narrowing is never exercised against the stub.
|
||||
*/
|
||||
private get embeddedPort(): LegacyEmbeddedChatPort {
|
||||
return this.embedded as unknown as LegacyEmbeddedChatPort;
|
||||
}
|
||||
|
||||
// --- LegacyEmbeddedChatPort: legacy browser operations fail closed under pi-rpc ---
|
||||
|
||||
completeLegacyRestTurn(
|
||||
context: OwnedConversationContext,
|
||||
input: Readonly<{ content: string }>,
|
||||
): Promise<
|
||||
LegacyRuntimeResult<Readonly<{ text: string; presentation: LegacySessionPresentation }>>
|
||||
> {
|
||||
if (this.mode === 'pi-rpc') {
|
||||
return Promise.resolve(RUNTIME_UNSUPPORTED);
|
||||
}
|
||||
return this.embeddedPort.completeLegacyRestTurn(context, input);
|
||||
}
|
||||
|
||||
prepareLegacySocketTurn(
|
||||
context: OwnedConversationContext,
|
||||
input: LegacyBrowserMessagePayload,
|
||||
stream: LegacyRuntimeStream,
|
||||
): Promise<LegacyRuntimeResult<LegacySocketTurnLease>> {
|
||||
if (this.mode === 'pi-rpc') {
|
||||
return Promise.resolve(RUNTIME_UNSUPPORTED);
|
||||
}
|
||||
return this.embeddedPort.prepareLegacySocketTurn(context, input, stream);
|
||||
}
|
||||
|
||||
setLegacyThinking(
|
||||
context: OwnedConversationContext,
|
||||
level: string,
|
||||
): LegacyRuntimeResult<LegacySessionPresentation> {
|
||||
if (this.mode === 'pi-rpc') {
|
||||
return RUNTIME_UNSUPPORTED;
|
||||
}
|
||||
return this.embeddedPort.setLegacyThinking(context, level);
|
||||
}
|
||||
|
||||
abortLegacyTurn(context: OwnedConversationContext): Promise<LegacyRuntimeResult<void>> {
|
||||
if (this.mode === 'pi-rpc') {
|
||||
return Promise.resolve(RUNTIME_UNSUPPORTED);
|
||||
}
|
||||
return this.embeddedPort.abortLegacyTurn(context);
|
||||
}
|
||||
|
||||
applyLegacyModelOverride(
|
||||
context: OwnedConversationContext,
|
||||
modelId: string,
|
||||
): LegacyRuntimeResult<LegacySessionPresentation> {
|
||||
if (this.mode === 'pi-rpc') {
|
||||
return RUNTIME_UNSUPPORTED;
|
||||
}
|
||||
return this.embeddedPort.applyLegacyModelOverride(context, modelId);
|
||||
}
|
||||
|
||||
readLegacySessionPresentation(
|
||||
context: OwnedConversationContext,
|
||||
): LegacyRuntimeResult<LegacySessionPresentation> {
|
||||
if (this.mode === 'pi-rpc') {
|
||||
return RUNTIME_UNSUPPORTED;
|
||||
}
|
||||
return this.embeddedPort.readLegacySessionPresentation(context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verified Discord ingress bypasses browser mode: it is embedded-only in BOTH modes and
|
||||
* never reaches the harness or routing-engine selection. It is reached only through a
|
||||
* {@link VerifiedDiscordIngressContext}, which exists only after every ingress check.
|
||||
*/
|
||||
dispatchVerifiedDiscordIngress(
|
||||
context: VerifiedDiscordIngressContext,
|
||||
stream: LegacyRuntimeStream,
|
||||
): Promise<LegacyRuntimeResult<VerifiedDiscordTurnLease>> {
|
||||
return this.embeddedPort.dispatchVerifiedDiscordIngress(context, stream);
|
||||
}
|
||||
}
|
||||
@@ -1,273 +0,0 @@
|
||||
import type { ChannelAttachmentDto, RoutingDecisionInfo } from '@mosaicstack/types';
|
||||
|
||||
/**
|
||||
* The single chat execution strategy resolved by {@link ChatRuntimeRouter}.
|
||||
*
|
||||
* Exactly one runtime is live per process. There is no union that lets a
|
||||
* `pi-rpc` deployment silently fall back to embedded execution: an unmet
|
||||
* `pi-rpc` precondition is a typed startup failure, never a downgrade.
|
||||
*/
|
||||
export type ChatRuntimeMode = 'legacy' | 'pi-rpc';
|
||||
|
||||
export type ChatRuntimeKind = 'embedded' | 'harness';
|
||||
|
||||
/** The resolved runtime. Slice Zero exposes only its immutable {@link ChatRuntimeKind}. */
|
||||
export interface ChatRuntime {
|
||||
readonly kind: ChatRuntimeKind;
|
||||
}
|
||||
|
||||
/** Why the `pi-rpc` runtime could not be made ready. Both are hard startup failures. */
|
||||
export type ChatRuntimeUnavailableReason =
|
||||
| 'adapter_unavailable'
|
||||
| 'conversation_service_unavailable';
|
||||
|
||||
/**
|
||||
* Raised at module init when `pi-rpc` mode is selected but its preconditions are
|
||||
* unmet. Carries only fixed, browser-safe text — never a raw exception message,
|
||||
* stack, or provider detail — and reports the frozen ack code `runtime_unsupported`.
|
||||
*/
|
||||
export class ChatRuntimeUnavailableError extends Error {
|
||||
readonly code = 'runtime_unsupported' as const;
|
||||
readonly reason: ChatRuntimeUnavailableReason;
|
||||
|
||||
constructor(reason: ChatRuntimeUnavailableReason) {
|
||||
super(
|
||||
reason === 'adapter_unavailable'
|
||||
? 'The pi-rpc chat runtime is unavailable: no "pi" harness adapter is registered.'
|
||||
: 'The pi-rpc chat runtime is unavailable: the harness conversation service is not bound.',
|
||||
);
|
||||
this.name = 'ChatRuntimeUnavailableError';
|
||||
this.reason = reason;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the process-wide chat runtime mode from the environment. Anything other
|
||||
* than the exact opt-in token `pi-rpc` keeps the legacy embedded runtime.
|
||||
*/
|
||||
export function resolveChatRuntimeMode(
|
||||
env: Record<string, string | undefined> = process.env,
|
||||
): ChatRuntimeMode {
|
||||
return env['CHAT_HARNESS_RUNTIME'] === 'pi-rpc' ? 'pi-rpc' : 'legacy';
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Transitional embedded chat port (Task Five).
|
||||
//
|
||||
// The legacy embedded browser behaviour is moved behind this exact interface so
|
||||
// neither the controller nor the gateway retains AgentService, RoutingEngine,
|
||||
// session, `piSession`, metric, listener, or channel access. `EmbeddedChatRuntime`
|
||||
// implements the port; `ChatRuntimeRouter` exposes the same narrowly named
|
||||
// operations and returns `runtime_unsupported` before touching Embedded for legacy
|
||||
// browser operations when the mode is `pi-rpc`.
|
||||
//
|
||||
// The names are frozen (spec jarvis-brain@1c629b06). Legacy REST completion,
|
||||
// legacy Socket streaming, P3 harness turns, and verified Discord are distinct
|
||||
// transport/trust capabilities — there is deliberately no generic
|
||||
// `sendConversationTurn` nor an AgentService-shaped mirror on the router.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Phantom brand keeping {@link OwnedConversationContext} nominally distinct so browser
|
||||
* DTOs are never structurally assignable to it. The factory that mints one may be called
|
||||
* only after authentication with `scopeFromUser(...)`, never with payload authority fields.
|
||||
*/
|
||||
declare const ownedConversationContextBrand: unique symbol;
|
||||
|
||||
/** Gateway-only ownership context. Embedded rechecks owner+tenant on every operation. */
|
||||
export interface OwnedConversationContext {
|
||||
readonly [ownedConversationContextBrand]: true;
|
||||
readonly conversationId: string;
|
||||
readonly scope: Readonly<{ userId: string; tenantId: string }>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every non-`ok` legacy runtime outcome. Missing, foreign, and no-longer-owned
|
||||
* conversations all collapse to `conversation_unavailable`. Ownership/mode/validation
|
||||
* failures are total results and never throw.
|
||||
*/
|
||||
export type LegacyRuntimeFailure =
|
||||
| { readonly ok: false; readonly code: 'runtime_unsupported'; readonly retryable: false }
|
||||
| { readonly ok: false; readonly code: 'conversation_unavailable'; readonly retryable: false }
|
||||
| { readonly ok: false; readonly code: 'request_invalid'; readonly retryable: false }
|
||||
| {
|
||||
readonly ok: false;
|
||||
readonly code: 'thinking_level_invalid';
|
||||
readonly retryable: false;
|
||||
readonly availableThinkingLevels: readonly string[];
|
||||
}
|
||||
| { readonly ok: false; readonly code: 'runtime_unavailable'; readonly retryable: true }
|
||||
| { readonly ok: false; readonly code: 'turn_already_dispatched'; readonly retryable: false }
|
||||
| { readonly ok: false; readonly code: 'operation_failed'; readonly retryable: boolean }
|
||||
| { readonly ok: false; readonly code: 'timeout'; readonly retryable: true };
|
||||
|
||||
/** Total result: an `ok` value or one of the fixed {@link LegacyRuntimeFailure} codes. */
|
||||
export type LegacyRuntimeResult<T> =
|
||||
| { readonly ok: true; readonly value: T }
|
||||
| LegacyRuntimeFailure;
|
||||
|
||||
/** User-facing session projection. Carries no session object, handle, or credential path. */
|
||||
export interface LegacySessionPresentation {
|
||||
readonly provider: string;
|
||||
readonly modelId: string;
|
||||
readonly thinkingLevel: string;
|
||||
readonly availableThinkingLevels: readonly string[];
|
||||
readonly agentName?: string;
|
||||
readonly routingDecision?: RoutingDecisionInfo;
|
||||
}
|
||||
|
||||
/** Terminal usage stats, normalized by Embedded from AgentService metrics. */
|
||||
export interface LegacyUsage {
|
||||
readonly provider: string;
|
||||
readonly modelId: string;
|
||||
readonly thinkingLevel: string;
|
||||
readonly tokens: Readonly<{
|
||||
input: number;
|
||||
output: number;
|
||||
cacheRead: number;
|
||||
cacheWrite: number;
|
||||
total: number;
|
||||
}>;
|
||||
readonly cost: number;
|
||||
readonly context: Readonly<{ percent: number | null; window: number }>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalized stream event. Exposes no `AgentSession`, `piSession`, native handle, raw
|
||||
* exception, tool arguments, or credential-bearing path — the gateway sees only these.
|
||||
*/
|
||||
export type LegacyRuntimeEvent =
|
||||
| { readonly type: 'started' }
|
||||
| { readonly type: 'text_delta'; readonly text: string }
|
||||
| { readonly type: 'thinking_delta'; readonly text: string }
|
||||
| {
|
||||
readonly type: 'tool_started';
|
||||
readonly toolCallId: string;
|
||||
readonly toolName: string;
|
||||
}
|
||||
| {
|
||||
readonly type: 'tool_finished';
|
||||
readonly toolCallId: string;
|
||||
readonly toolName: string;
|
||||
readonly isError: boolean;
|
||||
}
|
||||
| { readonly type: 'settled'; readonly usage?: LegacyUsage };
|
||||
|
||||
/** Legacy browser message input. Authority fields are advisory only; scope comes from the context. */
|
||||
export interface LegacyBrowserMessagePayload {
|
||||
readonly content: string;
|
||||
readonly provider?: string;
|
||||
readonly modelId?: string;
|
||||
readonly agentId?: string;
|
||||
readonly attachments?: readonly ChannelAttachmentDto[];
|
||||
}
|
||||
|
||||
/** A prepared-but-not-yet-dispatched legacy socket turn. */
|
||||
export interface LegacySocketTurnLease {
|
||||
readonly presentation: LegacySessionPresentation;
|
||||
/**
|
||||
* Atomically one-shot and scope-rechecking. A second call returns
|
||||
* `turn_already_dispatched` and performs zero prompt/tool effects.
|
||||
*/
|
||||
dispatch(): Promise<LegacyRuntimeResult<void>>;
|
||||
/** Idempotent, non-throwing. Removes listener and channel, including partial setup. */
|
||||
dispose(): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Phantom brand for {@link VerifiedDiscordIngressContext}. Minted only after service-token
|
||||
* auth plus signature, allowlist, binding, expected-route, replay, configured-agent,
|
||||
* forced-scope, and attachment-normalization checks.
|
||||
*/
|
||||
declare const verifiedDiscordIngressContextBrand: unique symbol;
|
||||
|
||||
/** Fully-verified Discord ingress. Contains no socket, envelope, signature, token, or escape hatch. */
|
||||
export interface VerifiedDiscordIngressContext {
|
||||
readonly [verifiedDiscordIngressContextBrand]: true;
|
||||
readonly conversationId: string;
|
||||
readonly scope: Readonly<{ userId: string; tenantId: string }>;
|
||||
readonly configuredAgent: Readonly<{ agentConfigId: string; instanceId: string }>;
|
||||
readonly content: string;
|
||||
readonly attachments?: readonly ChannelAttachmentDto[];
|
||||
readonly correlationId: string;
|
||||
readonly discordMessageId: string;
|
||||
readonly discordUserId: string;
|
||||
}
|
||||
|
||||
/** Verified-Discord turn lease. Same atomic one-shot dispatch and idempotent dispose rules. */
|
||||
export interface VerifiedDiscordTurnLease {
|
||||
readonly presentation: LegacySessionPresentation;
|
||||
dispatch(): Promise<LegacyRuntimeResult<void>>;
|
||||
dispose(): Promise<void>;
|
||||
}
|
||||
|
||||
/** Server-owned egress projection the runtime pushes normalized events into. */
|
||||
export interface LegacyRuntimeStream {
|
||||
/** Server-derived, e.g. `websocket:<socket-id>`. Never client-supplied. */
|
||||
readonly channelId: string;
|
||||
onEvent(event: LegacyRuntimeEvent): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The exact transitional port. `EmbeddedChatRuntime` implements it; `ChatRuntimeRouter`
|
||||
* mirrors the operation names and fails closed with `runtime_unsupported` for legacy
|
||||
* browser operations under `pi-rpc`.
|
||||
*/
|
||||
export interface LegacyEmbeddedChatPort {
|
||||
completeLegacyRestTurn(
|
||||
context: OwnedConversationContext,
|
||||
input: Readonly<{ content: string }>,
|
||||
): Promise<
|
||||
LegacyRuntimeResult<Readonly<{ text: string; presentation: LegacySessionPresentation }>>
|
||||
>;
|
||||
|
||||
prepareLegacySocketTurn(
|
||||
context: OwnedConversationContext,
|
||||
input: LegacyBrowserMessagePayload,
|
||||
stream: LegacyRuntimeStream,
|
||||
): Promise<LegacyRuntimeResult<LegacySocketTurnLease>>;
|
||||
|
||||
setLegacyThinking(
|
||||
context: OwnedConversationContext,
|
||||
level: string,
|
||||
): LegacyRuntimeResult<LegacySessionPresentation>;
|
||||
|
||||
abortLegacyTurn(context: OwnedConversationContext): Promise<LegacyRuntimeResult<void>>;
|
||||
|
||||
applyLegacyModelOverride(
|
||||
context: OwnedConversationContext,
|
||||
modelId: string,
|
||||
): LegacyRuntimeResult<LegacySessionPresentation>;
|
||||
|
||||
readLegacySessionPresentation(
|
||||
context: OwnedConversationContext,
|
||||
): LegacyRuntimeResult<LegacySessionPresentation>;
|
||||
|
||||
dispatchVerifiedDiscordIngress(
|
||||
context: VerifiedDiscordIngressContext,
|
||||
stream: LegacyRuntimeStream,
|
||||
): Promise<LegacyRuntimeResult<VerifiedDiscordTurnLease>>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mints an {@link OwnedConversationContext} from a server-derived scope. Callers must pass
|
||||
* a scope produced by `scopeFromUser(...)` after authentication — never a client-supplied
|
||||
* authority field. The brand is phantom, so this is the only way to obtain the branded type.
|
||||
*/
|
||||
export function ownConversation(
|
||||
conversationId: string,
|
||||
scope: Readonly<{ userId: string; tenantId: string }>,
|
||||
): OwnedConversationContext {
|
||||
return { conversationId, scope } as unknown as OwnedConversationContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mints a {@link VerifiedDiscordIngressContext}. Callers must have already completed every
|
||||
* ingress check (service-token auth, signature, allowlist, binding, expected-route, replay,
|
||||
* configured-agent, forced-scope, attachment normalization) before calling this.
|
||||
*/
|
||||
export function verifyDiscordIngress(
|
||||
fields: Omit<VerifiedDiscordIngressContext, typeof verifiedDiscordIngressContextBrand>,
|
||||
): VerifiedDiscordIngressContext {
|
||||
return { ...fields } as unknown as VerifiedDiscordIngressContext;
|
||||
}
|
||||
@@ -5,18 +5,16 @@ import {
|
||||
Logger,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
NotFoundException,
|
||||
Inject,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import type { AgentSessionEvent } from '@mariozechner/pi-coding-agent';
|
||||
import { Throttle } from '@nestjs/throttler';
|
||||
import { AgentService } from '../agent/agent.service.js';
|
||||
import { AuthGuard } from '../auth/auth.guard.js';
|
||||
import { CurrentUser } from '../auth/current-user.decorator.js';
|
||||
import { scopeFromUser, type AuthenticatedUserLike } from '../auth/session-scope.js';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
import { ChatRequestDto } from './chat.dto.js';
|
||||
import { ChatRuntimeRouter } from './chat-runtime-router.js';
|
||||
import { ownConversation } from './chat-runtime.js';
|
||||
import type { LegacyRuntimeFailure } from './chat-runtime.js';
|
||||
|
||||
interface ChatResponse {
|
||||
conversationId: string;
|
||||
@@ -28,49 +26,65 @@ interface ChatResponse {
|
||||
export class ChatController {
|
||||
private readonly logger = new Logger(ChatController.name);
|
||||
|
||||
constructor(private readonly runtime: ChatRuntimeRouter) {}
|
||||
constructor(@Inject(AgentService) private readonly agentService: AgentService) {}
|
||||
|
||||
@Post()
|
||||
@Throttle({ default: { limit: 10, ttl: 60_000 } })
|
||||
async chat(
|
||||
@Body() body: ChatRequestDto,
|
||||
@CurrentUser() user: AuthenticatedUserLike,
|
||||
@CurrentUser() user: { id: string },
|
||||
): Promise<ChatResponse> {
|
||||
const conversationId = body.conversationId ?? uuid();
|
||||
const scope = scopeFromUser(user);
|
||||
|
||||
try {
|
||||
let agentSession = this.agentService.getSession(conversationId);
|
||||
if (!agentSession) {
|
||||
agentSession = await this.agentService.createSession(conversationId);
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.error(
|
||||
`Session creation failed for conversation=${conversationId}`,
|
||||
err instanceof Error ? err.stack : String(err),
|
||||
);
|
||||
throw new HttpException('Agent session unavailable', HttpStatus.SERVICE_UNAVAILABLE);
|
||||
}
|
||||
|
||||
this.logger.debug(`Handling chat request for user=${user.id}, conversation=${conversationId}`);
|
||||
|
||||
// The one exclusive runtime owns execution. In legacy mode this reaches the embedded runtime;
|
||||
// in pi-rpc it fails closed with `runtime_unsupported` before ever touching embedded execution.
|
||||
const result = await this.runtime.completeLegacyRestTurn(
|
||||
ownConversation(conversationId, scope),
|
||||
{ content: body.content },
|
||||
);
|
||||
let responseText = '';
|
||||
|
||||
if (result.ok) {
|
||||
return { conversationId, text: result.value.text };
|
||||
const done = new Promise<void>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
cleanup();
|
||||
this.logger.error(`Agent response timed out after 120s for conversation=${conversationId}`);
|
||||
reject(new Error('Agent response timed out'));
|
||||
}, 120_000);
|
||||
|
||||
const cleanup = this.agentService.onEvent(conversationId, (event: AgentSessionEvent) => {
|
||||
if (event.type === 'message_update' && event.assistantMessageEvent.type === 'text_delta') {
|
||||
responseText += event.assistantMessageEvent.delta;
|
||||
}
|
||||
if (event.type === 'agent_end') {
|
||||
clearTimeout(timer);
|
||||
cleanup();
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
try {
|
||||
await this.agentService.prompt(conversationId, body.content);
|
||||
await done;
|
||||
} catch (err) {
|
||||
if (err instanceof HttpException) throw err;
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
if (message.includes('timed out')) {
|
||||
throw new HttpException('Agent response timed out', HttpStatus.GATEWAY_TIMEOUT);
|
||||
}
|
||||
this.logger.error(`Chat prompt failed for conversation=${conversationId}`, String(err));
|
||||
throw new HttpException('Agent processing failed', HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
throw this.toHttpException(result, conversationId);
|
||||
}
|
||||
|
||||
/** Maps a total {@link LegacyRuntimeFailure} to the fixed browser-safe HTTP surface. */
|
||||
private toHttpException(failure: LegacyRuntimeFailure, conversationId: string): HttpException {
|
||||
switch (failure.code) {
|
||||
case 'conversation_unavailable':
|
||||
return new NotFoundException('Session not found');
|
||||
case 'request_invalid':
|
||||
case 'thinking_level_invalid':
|
||||
return new HttpException('Invalid chat request', HttpStatus.BAD_REQUEST);
|
||||
case 'timeout':
|
||||
return new HttpException('Agent response timed out', HttpStatus.GATEWAY_TIMEOUT);
|
||||
case 'runtime_unsupported':
|
||||
case 'runtime_unavailable':
|
||||
return new HttpException('Agent runtime unavailable', HttpStatus.SERVICE_UNAVAILABLE);
|
||||
default:
|
||||
this.logger.error(`Chat turn failed for conversation=${conversationId}: ${failure.code}`);
|
||||
return new HttpException('Agent processing failed', HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
return { conversationId, text: responseText };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,4 @@
|
||||
import type { ChannelAttachmentDto } from '@mosaicstack/types';
|
||||
import { Transform, Type } from 'class-transformer';
|
||||
import {
|
||||
IsNotEmpty,
|
||||
IsObject,
|
||||
IsOptional,
|
||||
IsString,
|
||||
IsUUID,
|
||||
MaxLength,
|
||||
ValidateNested,
|
||||
} from 'class-validator';
|
||||
import { IsOptional, IsString, IsUUID, MaxLength } from 'class-validator';
|
||||
|
||||
export class ChatRequestDto {
|
||||
@IsOptional()
|
||||
@@ -42,60 +32,4 @@ export class ChatSocketMessageDto {
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
agentId?: string;
|
||||
|
||||
/** Validated channel attachment references; binary content is not embedded. */
|
||||
attachments?: readonly ChannelAttachmentDto[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Task Five, group 2 — the frozen pi-rpc `turn:send` selection triple.
|
||||
*
|
||||
* Each id is a required, non-empty, bounded string. There is no `@IsOptional` and no extra
|
||||
* field: under `forbidNonWhitelisted` an unknown selection key is rejected, and a missing id
|
||||
* fails `@IsString` (undefined is not a string) rather than silently passing.
|
||||
*/
|
||||
export class HarnessTurnSelectionDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(255)
|
||||
harnessId!: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(255)
|
||||
providerId!: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(255)
|
||||
modelId!: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Task Five, group 2 — the frozen wire contract for a pi-rpc `turn:send`.
|
||||
*
|
||||
* Validated through the production `ValidationPipe({ whitelist, forbidNonWhitelisted, transform })`:
|
||||
* a UUID conversation id; `content` trimmed then bounded to 1..10_000 characters (whitespace-only
|
||||
* collapses to empty and fails `@IsNotEmpty`); a nested `selection` object recursed with an
|
||||
* explicit `@Type` (a bare `@ValidateNested` is masked green by class-validator's empty-metadata
|
||||
* `unknownValue`); and a UUID-v4 idempotency key. No `provider`/`modelId`/`attachments` or other
|
||||
* authority field is declared, so `forbidNonWhitelisted` rejects every unknown top-level key.
|
||||
*/
|
||||
export class HarnessTurnSendDto {
|
||||
@IsUUID()
|
||||
conversationId!: string;
|
||||
|
||||
@Transform(({ value }) => (typeof value === 'string' ? value.trim() : value))
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(10_000)
|
||||
content!: string;
|
||||
|
||||
@IsObject()
|
||||
@ValidateNested()
|
||||
@Type(() => HarnessTurnSelectionDto)
|
||||
selection!: HarnessTurnSelectionDto;
|
||||
|
||||
@IsUUID('4')
|
||||
idempotencyKey!: string;
|
||||
}
|
||||
|
||||
@@ -1,204 +0,0 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import type { SlashCommandPayload } from '@mosaicstack/types';
|
||||
import { ChatGateway } from './chat.gateway.js';
|
||||
|
||||
const payload: SlashCommandPayload = {
|
||||
command: 'gc',
|
||||
conversationId: 'conversation-1',
|
||||
approvalId: 'approval-1',
|
||||
};
|
||||
|
||||
/**
|
||||
* Task 5 fence (F, existing control): gateway-owned command authorization/approval must
|
||||
* cause ZERO chat-runtime dispatch. Placed in the gateway's chat-runtime-router slot (the
|
||||
* former direct `AgentService` slot) so any accidental chat-runtime resolution throws
|
||||
* loudly instead of silently passing. Because execute/approval run entirely through the
|
||||
* command executor dependency and never resolve a chat runtime, this fixture is never
|
||||
* triggered and the ingress stays a GREEN control.
|
||||
*/
|
||||
function failIfUsedChatRuntimeRouter() {
|
||||
return {
|
||||
onModuleInit: () => {
|
||||
throw new Error('chat runtime router must not initialise on the command approval path');
|
||||
},
|
||||
get active(): never {
|
||||
throw new Error('chat runtime must not be resolved on the command approval path');
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function buildGateway(commandExecutor: {
|
||||
execute: ReturnType<typeof vi.fn>;
|
||||
createApproval: ReturnType<typeof vi.fn>;
|
||||
}): ChatGateway {
|
||||
return new ChatGateway(
|
||||
failIfUsedChatRuntimeRouter() as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
commandExecutor as never,
|
||||
{} as never,
|
||||
);
|
||||
}
|
||||
|
||||
describe('ChatGateway command approval ingress', () => {
|
||||
it('passes the client approval ID through to command execution while deriving the actor server-side', async (): Promise<void> => {
|
||||
const commandExecutor = {
|
||||
execute: vi.fn().mockResolvedValue({ ...payload, success: true }),
|
||||
createApproval: vi.fn(),
|
||||
};
|
||||
const gateway = buildGateway(commandExecutor);
|
||||
const client = { data: { user: { id: 'admin-1' } }, emit: vi.fn() };
|
||||
|
||||
await gateway.handleCommandExecute(client as never, payload);
|
||||
|
||||
expect(commandExecutor.execute).toHaveBeenCalledWith(payload, {
|
||||
userId: 'admin-1',
|
||||
tenantId: 'admin-1',
|
||||
});
|
||||
expect(client.emit).toHaveBeenCalledWith(
|
||||
'command:result',
|
||||
expect.objectContaining({ success: true }),
|
||||
);
|
||||
});
|
||||
|
||||
it('issues a durable approval only for the authenticated actor', async (): Promise<void> => {
|
||||
const commandExecutor = {
|
||||
execute: vi.fn(),
|
||||
createApproval: vi.fn().mockResolvedValue({
|
||||
approvalId: 'approval-1',
|
||||
expiresAt: '2026-07-12T00:05:00.000Z',
|
||||
}),
|
||||
};
|
||||
const gateway = buildGateway(commandExecutor);
|
||||
const client = { data: { user: { id: 'admin-1' } }, emit: vi.fn() };
|
||||
|
||||
await gateway.handleCommandApproval(client as never, {
|
||||
command: 'gc',
|
||||
conversationId: 'conversation-1',
|
||||
});
|
||||
|
||||
expect(commandExecutor.createApproval).toHaveBeenCalledWith(
|
||||
{ command: 'gc', conversationId: 'conversation-1' },
|
||||
{ userId: 'admin-1', tenantId: 'admin-1' },
|
||||
);
|
||||
expect(client.emit).toHaveBeenCalledWith('command:approval', {
|
||||
command: 'gc',
|
||||
conversationId: 'conversation-1',
|
||||
success: true,
|
||||
approvalId: 'approval-1',
|
||||
expiresAt: '2026-07-12T00:05:00.000Z',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Task 5 (G3) command runtime fence. Under pi-rpc there is no embedded chat session, so
|
||||
* embedded slash-commands (/model, /agent, and every other non-audited command) are fixed
|
||||
* "unsupported" and MUST fail closed BEFORE reaching the command executor — never a silent
|
||||
* fall-through to embedded execution. Only runtime-independent audited system commands
|
||||
* (/reload) pass through as a positive control, and the approval path stays runtime-independent.
|
||||
* The router stub here carries `runtimeMode: 'pi-rpc'` and throws if any runtime is resolved, so
|
||||
* a fence bypass surfaces as a thrown error rather than a silent embedded dispatch.
|
||||
*/
|
||||
function buildPiRpcGateway(commandExecutor: {
|
||||
execute: ReturnType<typeof vi.fn>;
|
||||
createApproval: ReturnType<typeof vi.fn>;
|
||||
}): ChatGateway {
|
||||
const piRpcRouter = {
|
||||
runtimeMode: 'pi-rpc' as const,
|
||||
onModuleInit: () => {
|
||||
throw new Error('chat runtime router must not initialise on the pi-rpc command path');
|
||||
},
|
||||
get active(): never {
|
||||
throw new Error('chat runtime must not be resolved on the pi-rpc command path');
|
||||
},
|
||||
};
|
||||
return new ChatGateway(
|
||||
piRpcRouter as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
commandExecutor as never,
|
||||
{} as never,
|
||||
);
|
||||
}
|
||||
|
||||
describe('ChatGateway command runtime fence (Task 5 G3, pi-rpc)', () => {
|
||||
const UNSUPPORTED = 'Slash commands are not available on this deployment.';
|
||||
|
||||
it.each(['model', 'agent', 'gc'])(
|
||||
'fails /%s closed before the executor under pi-rpc (execute never called)',
|
||||
async (command): Promise<void> => {
|
||||
const commandExecutor = {
|
||||
execute: vi
|
||||
.fn()
|
||||
.mockResolvedValue({ command, conversationId: 'conversation-1', success: true }),
|
||||
createApproval: vi.fn(),
|
||||
};
|
||||
const gateway = buildPiRpcGateway(commandExecutor);
|
||||
const client = { data: { user: { id: 'admin-1' } }, emit: vi.fn() };
|
||||
|
||||
await gateway.handleCommandExecute(client as never, {
|
||||
command,
|
||||
conversationId: 'conversation-1',
|
||||
});
|
||||
|
||||
expect(commandExecutor.execute).toHaveBeenCalledTimes(0);
|
||||
expect(client.emit).toHaveBeenCalledWith('command:result', {
|
||||
command,
|
||||
conversationId: 'conversation-1',
|
||||
success: false,
|
||||
message: UNSUPPORTED,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it('passes the audited /reload system command through as a positive control under pi-rpc', async (): Promise<void> => {
|
||||
const reloadResult = { command: 'reload', conversationId: 'conversation-1', success: true };
|
||||
const commandExecutor = {
|
||||
execute: vi.fn().mockResolvedValue(reloadResult),
|
||||
createApproval: vi.fn(),
|
||||
};
|
||||
const gateway = buildPiRpcGateway(commandExecutor);
|
||||
const client = { data: { user: { id: 'admin-1' } }, emit: vi.fn() };
|
||||
|
||||
await gateway.handleCommandExecute(client as never, {
|
||||
command: 'reload',
|
||||
conversationId: 'conversation-1',
|
||||
});
|
||||
|
||||
expect(commandExecutor.execute).toHaveBeenCalledTimes(1);
|
||||
expect(commandExecutor.execute).toHaveBeenCalledWith(
|
||||
{ command: 'reload', conversationId: 'conversation-1' },
|
||||
{ userId: 'admin-1', tenantId: 'admin-1' },
|
||||
);
|
||||
expect(client.emit).toHaveBeenCalledWith('command:result', reloadResult);
|
||||
});
|
||||
|
||||
it('keeps command approval runtime-independent under pi-rpc (createApproval still runs)', async (): Promise<void> => {
|
||||
const commandExecutor = {
|
||||
execute: vi.fn(),
|
||||
createApproval: vi.fn().mockResolvedValue({
|
||||
approvalId: 'approval-1',
|
||||
expiresAt: '2026-07-12T00:05:00.000Z',
|
||||
}),
|
||||
};
|
||||
const gateway = buildPiRpcGateway(commandExecutor);
|
||||
const client = { data: { user: { id: 'admin-1' } }, emit: vi.fn() };
|
||||
|
||||
await gateway.handleCommandApproval(client as never, {
|
||||
command: 'gc',
|
||||
conversationId: 'conversation-1',
|
||||
});
|
||||
|
||||
expect(commandExecutor.createApproval).toHaveBeenCalledWith(
|
||||
{ command: 'gc', conversationId: 'conversation-1' },
|
||||
{ userId: 'admin-1', tenantId: 'admin-1' },
|
||||
);
|
||||
expect(client.emit).toHaveBeenCalledWith(
|
||||
'command:approval',
|
||||
expect.objectContaining({ success: true, approvalId: 'approval-1' }),
|
||||
);
|
||||
});
|
||||
});
|
||||
Binary file not shown.
+420
-1121
File diff suppressed because it is too large
Load Diff
@@ -1,59 +1,12 @@
|
||||
import { forwardRef, Module } from '@nestjs/common';
|
||||
import { CommandsModule } from '../commands/commands.module.js';
|
||||
import { HarnessModule } from '../harness/harness.module.js';
|
||||
import { HarnessRegistry } from '../harness/harness.registry.js';
|
||||
import {
|
||||
HARNESS_CONVERSATION_SERVICE,
|
||||
HARNESS_REGISTRY,
|
||||
type HarnessConversationServiceBinding,
|
||||
} from '../harness/harness.tokens.js';
|
||||
import type { HarnessConversationService } from '@mosaicstack/types';
|
||||
import { ChatGateway } from './chat.gateway.js';
|
||||
import { ChatController } from './chat.controller.js';
|
||||
import { ChatRuntimeRouter } from './chat-runtime-router.js';
|
||||
import { EmbeddedChatRuntime } from './embedded-chat.runtime.js';
|
||||
import { HarnessChatRuntime } from './harness-chat.runtime.js';
|
||||
|
||||
/**
|
||||
* Task Five wiring. The exclusive {@link ChatRuntimeRouter} is the single chat-execution
|
||||
* authority: the controller and gateway inject only the router, never `AgentService`,
|
||||
* `RoutingEngineService`, or a session/`piSession` handle. The router resolves exactly one
|
||||
* runtime at module init — {@link EmbeddedChatRuntime} in legacy mode, {@link HarnessChatRuntime}
|
||||
* in `pi-rpc` — over the REAL {@link HarnessModule} registry and conversation-service binding.
|
||||
*
|
||||
* The router and the harness runtime are constructed through factories because their
|
||||
* dependencies are interface/union types with no runtime injection token (the registry and
|
||||
* conversation-service arrive via the string tokens exported by `HarnessModule`); the embedded
|
||||
* runtime injects the class-typed `AgentService` and is provided directly.
|
||||
*/
|
||||
@Module({
|
||||
imports: [forwardRef(() => CommandsModule), HarnessModule],
|
||||
imports: [forwardRef(() => CommandsModule)],
|
||||
controllers: [ChatController],
|
||||
providers: [
|
||||
ChatGateway,
|
||||
EmbeddedChatRuntime,
|
||||
{
|
||||
provide: HarnessChatRuntime,
|
||||
useFactory: (conversationService: HarnessConversationServiceBinding) =>
|
||||
new HarnessChatRuntime(conversationService as HarnessConversationService),
|
||||
inject: [HARNESS_CONVERSATION_SERVICE],
|
||||
},
|
||||
{
|
||||
provide: ChatRuntimeRouter,
|
||||
useFactory: (
|
||||
registry: HarnessRegistry,
|
||||
conversationService: HarnessConversationServiceBinding,
|
||||
embedded: EmbeddedChatRuntime,
|
||||
harness: HarnessChatRuntime,
|
||||
) => new ChatRuntimeRouter(registry, conversationService, embedded, harness),
|
||||
inject: [
|
||||
HARNESS_REGISTRY,
|
||||
HARNESS_CONVERSATION_SERVICE,
|
||||
EmbeddedChatRuntime,
|
||||
HarnessChatRuntime,
|
||||
],
|
||||
},
|
||||
],
|
||||
exports: [ChatGateway, ChatRuntimeRouter],
|
||||
providers: [ChatGateway],
|
||||
exports: [ChatGateway],
|
||||
})
|
||||
export class ChatModule {}
|
||||
|
||||
@@ -1,515 +0,0 @@
|
||||
import { ForbiddenException, Injectable, Logger, NotFoundException } from '@nestjs/common';
|
||||
import type { AgentSessionEvent } from '@mariozechner/pi-coding-agent';
|
||||
import { AgentService, type AgentSession } from '../agent/agent.service.js';
|
||||
import type { ActorTenantScope } from '../auth/session-scope.js';
|
||||
import type {
|
||||
ChatRuntime,
|
||||
LegacyBrowserMessagePayload,
|
||||
LegacyEmbeddedChatPort,
|
||||
LegacyRuntimeEvent,
|
||||
LegacyRuntimeResult,
|
||||
LegacySessionPresentation,
|
||||
LegacySocketTurnLease,
|
||||
LegacyUsage,
|
||||
OwnedConversationContext,
|
||||
VerifiedDiscordIngressContext,
|
||||
VerifiedDiscordTurnLease,
|
||||
LegacyRuntimeStream,
|
||||
} from './chat-runtime.js';
|
||||
|
||||
/** Fixed timeout for a synchronous REST turn, matching the historical controller budget. */
|
||||
const REST_TURN_TIMEOUT_MS = 120_000;
|
||||
|
||||
/**
|
||||
* The `legacy` chat runtime and the sole implementation of {@link LegacyEmbeddedChatPort}.
|
||||
*
|
||||
* It owns the embedded in-process execution path — the `AgentService` stack that the
|
||||
* `ChatController` and `ChatGateway` drove directly before Task Five. Once the
|
||||
* {@link import('./chat-runtime-router.js').ChatRuntimeRouter} fronts it, the browser
|
||||
* HTTP/WebSocket legacy path and verified-Discord ingress route through THIS runtime, so
|
||||
* neither the controller nor the gateway retains `AgentService`, `piSession`, session,
|
||||
* listener, channel, or metric access. Ownership (`userId`/`tenantId`) is re-checked by
|
||||
* `AgentService` on every operation; a missing, foreign, or no-longer-owned conversation
|
||||
* collapses to `conversation_unavailable` and never throws out of the port.
|
||||
*/
|
||||
@Injectable()
|
||||
export class EmbeddedChatRuntime implements ChatRuntime, LegacyEmbeddedChatPort {
|
||||
readonly kind = 'embedded' as const;
|
||||
private readonly logger = new Logger(EmbeddedChatRuntime.name);
|
||||
|
||||
constructor(readonly agentService: AgentService) {}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Legacy REST completion (op A)
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
async completeLegacyRestTurn(
|
||||
context: OwnedConversationContext,
|
||||
input: Readonly<{ content: string }>,
|
||||
): Promise<
|
||||
LegacyRuntimeResult<Readonly<{ text: string; presentation: LegacySessionPresentation }>>
|
||||
> {
|
||||
const scope = toScope(context.scope);
|
||||
const { conversationId } = context;
|
||||
|
||||
const resolved = await this.resolveOrCreate(conversationId, scope, {});
|
||||
if (!resolved.ok) return resolved;
|
||||
|
||||
let responseText = '';
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let detach: (() => void) | undefined;
|
||||
let disposed = false;
|
||||
// One idempotent teardown owned OUTSIDE the completion promise: it clears the timeout and
|
||||
// detaches the event listener exactly once, whichever of agent_end, timeout, or a prompt
|
||||
// rejection fires first. Without this, a prompt() rejection surfaced through the catch below
|
||||
// would return while leaving the listener attached (free to consume a later turn's events) and
|
||||
// the 120s timer live (its rejection later going unobserved).
|
||||
const dispose = (): void => {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
if (timer !== undefined) clearTimeout(timer);
|
||||
detach?.();
|
||||
};
|
||||
const done = new Promise<void>((resolve, reject) => {
|
||||
timer = setTimeout(() => {
|
||||
dispose();
|
||||
reject(new Error('Agent response timed out'));
|
||||
}, REST_TURN_TIMEOUT_MS);
|
||||
|
||||
detach = this.agentService.onEvent(
|
||||
conversationId,
|
||||
(event: AgentSessionEvent) => {
|
||||
if (
|
||||
event.type === 'message_update' &&
|
||||
event.assistantMessageEvent.type === 'text_delta'
|
||||
) {
|
||||
responseText += event.assistantMessageEvent.delta;
|
||||
}
|
||||
if (event.type === 'agent_end') {
|
||||
dispose();
|
||||
resolve();
|
||||
}
|
||||
},
|
||||
scope,
|
||||
);
|
||||
});
|
||||
|
||||
try {
|
||||
await this.agentService.prompt(conversationId, input.content, scope);
|
||||
await done;
|
||||
} catch (err) {
|
||||
dispose();
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
if (message.includes('timed out')) {
|
||||
return { ok: false, code: 'timeout', retryable: true };
|
||||
}
|
||||
this.logger.error(`Legacy REST turn failed for conversation=${conversationId}`, message);
|
||||
return { ok: false, code: 'operation_failed', retryable: false };
|
||||
}
|
||||
|
||||
const presentation = this.presentationFor(conversationId, scope) ?? resolved.presentation;
|
||||
return { ok: true, value: { text: responseText, presentation } };
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Legacy Socket streaming (op B)
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
async prepareLegacySocketTurn(
|
||||
context: OwnedConversationContext,
|
||||
input: LegacyBrowserMessagePayload,
|
||||
stream: LegacyRuntimeStream,
|
||||
): Promise<LegacyRuntimeResult<LegacySocketTurnLease>> {
|
||||
const scope = toScope(context.scope);
|
||||
const { conversationId } = context;
|
||||
|
||||
const resolved = await this.resolveOrCreate(conversationId, scope, {
|
||||
...(input.provider ? { provider: input.provider } : {}),
|
||||
...(input.modelId ? { modelId: input.modelId } : {}),
|
||||
...(input.agentId ? { agentConfigId: input.agentId } : {}),
|
||||
});
|
||||
if (!resolved.ok) return resolved;
|
||||
|
||||
let detach: () => void;
|
||||
try {
|
||||
detach = this.subscribe(conversationId, scope, stream);
|
||||
} catch (err) {
|
||||
// A partial listener/channel setup rolled itself back inside subscribe(); surface a total
|
||||
// safe failure instead of throwing out of the port. Retryable — the attach is transient.
|
||||
this.logger.error(
|
||||
`Embedded socket subscription failed for conversation=${conversationId}`,
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
return { ok: false, code: 'runtime_unavailable', retryable: true };
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
value: this.buildLease(
|
||||
conversationId,
|
||||
scope,
|
||||
input.content,
|
||||
input.attachments,
|
||||
detach,
|
||||
resolved.presentation,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Thinking level (op C) — synchronous, total
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
setLegacyThinking(
|
||||
context: OwnedConversationContext,
|
||||
level: string,
|
||||
): LegacyRuntimeResult<LegacySessionPresentation> {
|
||||
const scope = toScope(context.scope);
|
||||
const session = this.agentService.getSession(context.conversationId, scope);
|
||||
if (!session) return CONVERSATION_UNAVAILABLE;
|
||||
|
||||
const availableThinkingLevels = session.piSession.getAvailableThinkingLevels();
|
||||
if (!(availableThinkingLevels as readonly string[]).includes(level)) {
|
||||
return {
|
||||
ok: false,
|
||||
code: 'thinking_level_invalid',
|
||||
retryable: false,
|
||||
availableThinkingLevels,
|
||||
};
|
||||
}
|
||||
|
||||
session.piSession.setThinkingLevel(level as never);
|
||||
return { ok: true, value: this.presentationForSession(session) };
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Abort (op D)
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
async abortLegacyTurn(context: OwnedConversationContext): Promise<LegacyRuntimeResult<void>> {
|
||||
const scope = toScope(context.scope);
|
||||
const session = this.agentService.getSession(context.conversationId, scope);
|
||||
if (!session) return CONVERSATION_UNAVAILABLE;
|
||||
|
||||
try {
|
||||
await session.piSession.abort();
|
||||
} catch (err) {
|
||||
this.logger.error(
|
||||
`Legacy abort failed for conversation=${context.conversationId}`,
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
return { ok: false, code: 'operation_failed', retryable: false };
|
||||
}
|
||||
return { ok: true, value: undefined };
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Model override (synchronous, total)
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
applyLegacyModelOverride(
|
||||
context: OwnedConversationContext,
|
||||
modelId: string,
|
||||
): LegacyRuntimeResult<LegacySessionPresentation> {
|
||||
const scope = toScope(context.scope);
|
||||
const session = this.agentService.getSession(context.conversationId, scope);
|
||||
if (!session) return CONVERSATION_UNAVAILABLE;
|
||||
|
||||
this.agentService.updateSessionModel(context.conversationId, modelId, scope);
|
||||
const refreshed = this.agentService.getSession(context.conversationId, scope) ?? session;
|
||||
return { ok: true, value: this.presentationForSession(refreshed) };
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Presentation read (synchronous, total)
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
readLegacySessionPresentation(
|
||||
context: OwnedConversationContext,
|
||||
): LegacyRuntimeResult<LegacySessionPresentation> {
|
||||
const scope = toScope(context.scope);
|
||||
const session = this.agentService.getSession(context.conversationId, scope);
|
||||
if (!session) return CONVERSATION_UNAVAILABLE;
|
||||
return { ok: true, value: this.presentationForSession(session) };
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Verified Discord ingress (embedded-only in both modes)
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
async dispatchVerifiedDiscordIngress(
|
||||
context: VerifiedDiscordIngressContext,
|
||||
stream: LegacyRuntimeStream,
|
||||
): Promise<LegacyRuntimeResult<VerifiedDiscordTurnLease>> {
|
||||
const scope = toScope(context.scope);
|
||||
const { conversationId } = context;
|
||||
|
||||
const resolved = await this.resolveOrCreate(
|
||||
conversationId,
|
||||
scope,
|
||||
{ agentConfigId: context.configuredAgent.agentConfigId },
|
||||
{
|
||||
agentConfigId: context.configuredAgent.agentConfigId,
|
||||
instanceId: context.configuredAgent.instanceId,
|
||||
},
|
||||
);
|
||||
if (!resolved.ok) return resolved;
|
||||
|
||||
let detach: () => void;
|
||||
try {
|
||||
detach = this.subscribe(conversationId, scope, stream);
|
||||
} catch (err) {
|
||||
// A partial listener/channel setup rolled itself back inside subscribe(); surface a total
|
||||
// safe failure instead of throwing out of the port. Retryable — the attach is transient.
|
||||
this.logger.error(
|
||||
`Embedded Discord subscription failed for conversation=${conversationId}`,
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
return { ok: false, code: 'runtime_unavailable', retryable: true };
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
value: this.buildLease(
|
||||
conversationId,
|
||||
scope,
|
||||
context.content,
|
||||
context.attachments,
|
||||
detach,
|
||||
resolved.presentation,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Shared helpers
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Resolves the owned session, creating it on first use. Ownership/scope rejections
|
||||
* (`Forbidden`/`NotFound`) collapse to `conversation_unavailable`; any other creation
|
||||
* failure surfaces as the retryable `runtime_unavailable`. On success returns the
|
||||
* session presentation so callers avoid a redundant `getSession`.
|
||||
*/
|
||||
private async resolveOrCreate(
|
||||
conversationId: string,
|
||||
scope: ActorTenantScope,
|
||||
extraOptions: Readonly<{ provider?: string; modelId?: string; agentConfigId?: string }>,
|
||||
expectedAgent?: Readonly<{ agentConfigId: string; instanceId: string }>,
|
||||
): Promise<
|
||||
| { readonly ok: true; readonly presentation: LegacySessionPresentation }
|
||||
| Exclude<LegacyRuntimeResult<never>, { ok: true }>
|
||||
> {
|
||||
let session = this.agentService.getSession(conversationId, scope);
|
||||
if (session && expectedAgent) {
|
||||
// A verified-Discord turn reuses an existing in-process session only when its configured
|
||||
// identity still matches the reconciled agent record. A pre-existing same-scope session
|
||||
// carrying a different configured agent (config id or resolved name) is rejected rather than
|
||||
// executed under the verified label — never silently run a different prompt/model/tool policy.
|
||||
if (
|
||||
session.agentConfigId !== expectedAgent.agentConfigId ||
|
||||
session.agentName !== expectedAgent.instanceId
|
||||
) {
|
||||
return CONVERSATION_UNAVAILABLE;
|
||||
}
|
||||
}
|
||||
if (!session) {
|
||||
try {
|
||||
session = await this.agentService.createSession(conversationId, {
|
||||
userId: scope.userId,
|
||||
tenantId: scope.tenantId,
|
||||
...extraOptions,
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof ForbiddenException || err instanceof NotFoundException) {
|
||||
return CONVERSATION_UNAVAILABLE;
|
||||
}
|
||||
this.logger.error(
|
||||
`Embedded session creation failed for conversation=${conversationId}`,
|
||||
err instanceof Error ? err.stack : String(err),
|
||||
);
|
||||
return { ok: false, code: 'runtime_unavailable', retryable: true };
|
||||
}
|
||||
}
|
||||
return { ok: true, presentation: this.presentationForSession(session) };
|
||||
}
|
||||
|
||||
/** Installs a normalizing event listener that forwards to the server-owned stream. */
|
||||
private subscribe(
|
||||
conversationId: string,
|
||||
scope: ActorTenantScope,
|
||||
stream: LegacyRuntimeStream,
|
||||
): () => void {
|
||||
const unsubscribe = this.agentService.onEvent(
|
||||
conversationId,
|
||||
(event: AgentSessionEvent) => {
|
||||
const normalized = this.normalizeEvent(conversationId, scope, event);
|
||||
if (normalized) stream.onEvent(normalized);
|
||||
},
|
||||
scope,
|
||||
);
|
||||
try {
|
||||
this.agentService.addChannel(conversationId, stream.channelId, scope);
|
||||
} catch (err) {
|
||||
// Partial setup: the listener was acquired but the channel attach failed. Roll back
|
||||
// exactly what was acquired (the listener) before the failure escapes, so no leaked
|
||||
// subscription survives; the caller converts the rethrow into a total safe failure.
|
||||
try {
|
||||
unsubscribe();
|
||||
} catch {
|
||||
/* idempotent teardown */
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
return () => {
|
||||
try {
|
||||
unsubscribe();
|
||||
} catch {
|
||||
/* idempotent teardown */
|
||||
}
|
||||
try {
|
||||
this.agentService.removeChannel(conversationId, stream.channelId, scope);
|
||||
} catch {
|
||||
/* idempotent teardown */
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** Builds an atomically one-shot, scope-rechecking dispatch lease. */
|
||||
private buildLease(
|
||||
conversationId: string,
|
||||
scope: ActorTenantScope,
|
||||
content: string,
|
||||
attachments: VerifiedDiscordIngressContext['attachments'],
|
||||
detach: () => void,
|
||||
presentation: LegacySessionPresentation,
|
||||
): LegacySocketTurnLease & VerifiedDiscordTurnLease {
|
||||
let dispatched = false;
|
||||
let disposed = false;
|
||||
return {
|
||||
presentation,
|
||||
dispatch: async (): Promise<LegacyRuntimeResult<void>> => {
|
||||
if (dispatched) {
|
||||
return { ok: false, code: 'turn_already_dispatched', retryable: false };
|
||||
}
|
||||
dispatched = true;
|
||||
try {
|
||||
await this.agentService.prompt(conversationId, content, scope, attachments);
|
||||
} catch (err) {
|
||||
this.logger.error(
|
||||
`Legacy dispatch failed for conversation=${conversationId}`,
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
return { ok: false, code: 'operation_failed', retryable: false };
|
||||
}
|
||||
return { ok: true, value: undefined };
|
||||
},
|
||||
dispose: async (): Promise<void> => {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
detach();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Normalizes a raw agent event into the redaction-agnostic transport event, or drops it. */
|
||||
private normalizeEvent(
|
||||
conversationId: string,
|
||||
scope: ActorTenantScope,
|
||||
event: AgentSessionEvent,
|
||||
): LegacyRuntimeEvent | undefined {
|
||||
switch (event.type) {
|
||||
case 'agent_start':
|
||||
return { type: 'started' };
|
||||
case 'agent_end':
|
||||
return { type: 'settled', ...this.usageFor(conversationId, scope) };
|
||||
case 'message_update': {
|
||||
const assistant = event.assistantMessageEvent;
|
||||
if (assistant.type === 'text_delta') return { type: 'text_delta', text: assistant.delta };
|
||||
if (assistant.type === 'thinking_delta') {
|
||||
return { type: 'thinking_delta', text: assistant.delta };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
case 'tool_execution_start':
|
||||
return { type: 'tool_started', toolCallId: event.toolCallId, toolName: event.toolName };
|
||||
case 'tool_execution_end':
|
||||
return {
|
||||
type: 'tool_finished',
|
||||
toolCallId: event.toolCallId,
|
||||
toolName: event.toolName,
|
||||
isError: event.isError,
|
||||
};
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gathers terminal usage from the Pi session and records it into session metrics.
|
||||
* Embedded owns AgentService metrics; the gateway never touches `piSession` stats.
|
||||
*/
|
||||
private usageFor(conversationId: string, scope: ActorTenantScope): { usage?: LegacyUsage } {
|
||||
const session = this.agentService.getSession(conversationId, scope);
|
||||
const piSession = session?.piSession;
|
||||
const stats = piSession?.getSessionStats();
|
||||
if (!session || !stats) return {};
|
||||
const contextUsage = piSession?.getContextUsage();
|
||||
|
||||
const tokens = {
|
||||
input: stats.tokens?.input ?? 0,
|
||||
output: stats.tokens?.output ?? 0,
|
||||
cacheRead: stats.tokens?.cacheRead ?? 0,
|
||||
cacheWrite: stats.tokens?.cacheWrite ?? 0,
|
||||
total: stats.tokens?.total ?? 0,
|
||||
};
|
||||
|
||||
this.agentService.recordTokenUsage(conversationId, { ...tokens });
|
||||
|
||||
return {
|
||||
usage: {
|
||||
provider: session.provider,
|
||||
modelId: session.modelId,
|
||||
thinkingLevel: piSession?.thinkingLevel ?? 'off',
|
||||
tokens,
|
||||
cost: stats.cost ?? 0,
|
||||
context: {
|
||||
percent: contextUsage?.percent ?? null,
|
||||
window: contextUsage?.contextWindow ?? 0,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Presentation from a live session id, or undefined when no owned session exists. */
|
||||
private presentationFor(
|
||||
conversationId: string,
|
||||
scope: ActorTenantScope,
|
||||
): LegacySessionPresentation | undefined {
|
||||
const session = this.agentService.getSession(conversationId, scope);
|
||||
return session ? this.presentationForSession(session) : undefined;
|
||||
}
|
||||
|
||||
/** User-facing projection carrying no session handle, credential, or raw stats. */
|
||||
private presentationForSession(session: AgentSession): LegacySessionPresentation {
|
||||
return {
|
||||
provider: session.provider,
|
||||
modelId: session.modelId,
|
||||
thinkingLevel: session.piSession.thinkingLevel,
|
||||
availableThinkingLevels: session.piSession.getAvailableThinkingLevels(),
|
||||
...(session.agentName ? { agentName: session.agentName } : {}),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** The shared terminal `conversation_unavailable` failure (missing/foreign/lost ownership). */
|
||||
const CONVERSATION_UNAVAILABLE = {
|
||||
ok: false as const,
|
||||
code: 'conversation_unavailable' as const,
|
||||
retryable: false as const,
|
||||
};
|
||||
|
||||
/** Narrows a branded context scope to the `AgentService` actor/tenant scope (identical shape). */
|
||||
function toScope(scope: Readonly<{ userId: string; tenantId: string }>): ActorTenantScope {
|
||||
return { userId: scope.userId, tenantId: scope.tenantId };
|
||||
}
|
||||
@@ -1,170 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type {
|
||||
AttachConversation,
|
||||
ConversationSnapshot,
|
||||
DetachConversation,
|
||||
HarnessActorContext,
|
||||
HarnessConversationService,
|
||||
HarnessEventEnvelope,
|
||||
HarnessSelection,
|
||||
SendHarnessTurn,
|
||||
TurnReceipt,
|
||||
} from '@mosaicstack/types';
|
||||
import { HarnessChatRuntime } from './harness-chat.runtime.js';
|
||||
|
||||
/**
|
||||
* Task Five, Step One (harness runtime). Proves the `pi-rpc` runtime executes
|
||||
* exclusively through the {@link HarnessConversationService} RPC boundary and
|
||||
* forwards the caller's exact selection tuple and idempotency key without
|
||||
* substitution. Red-first: the runtime is an unimplemented stub, so every
|
||||
* delegation assertion fails until Step Three.
|
||||
*/
|
||||
|
||||
const context: HarnessActorContext = {
|
||||
actorId: 'actor-1',
|
||||
tenantId: 'tenant-1',
|
||||
seatId: 'seat-1',
|
||||
correlationId: 'corr-1',
|
||||
};
|
||||
|
||||
const selection: HarnessSelection = {
|
||||
harnessId: 'pi',
|
||||
providerId: 'anthropic',
|
||||
modelId: 'claude-opus-4-8',
|
||||
};
|
||||
|
||||
const conversationId = '11111111-1111-4111-8111-111111111111';
|
||||
const idempotencyKey = '22222222-2222-4222-8222-222222222222';
|
||||
|
||||
const sendInput: SendHarnessTurn & { idempotencyKey: string } = {
|
||||
context,
|
||||
conversationId,
|
||||
selection,
|
||||
turnId: 'turn-abc',
|
||||
correlationId: 'corr-1',
|
||||
content: 'hello',
|
||||
idempotencyKey,
|
||||
};
|
||||
|
||||
const attachInput: AttachConversation & { afterSequence?: number } = {
|
||||
context,
|
||||
conversationId,
|
||||
clientId: 'client-1',
|
||||
selection,
|
||||
afterSequence: 0,
|
||||
};
|
||||
|
||||
const detachInput: DetachConversation = {
|
||||
context,
|
||||
conversationId,
|
||||
clientId: 'client-1',
|
||||
};
|
||||
|
||||
interface RecordedCalls {
|
||||
attach: (AttachConversation & { afterSequence?: number })[];
|
||||
detach: DetachConversation[];
|
||||
send: (SendHarnessTurn & { idempotencyKey: string })[];
|
||||
subscribeFrom: { conversationId: string; afterSequence: number }[];
|
||||
}
|
||||
|
||||
const snapshot: ConversationSnapshot = {
|
||||
session: {
|
||||
conversationId,
|
||||
nativeSessionId: 'native-1',
|
||||
seatId: 'seat-1',
|
||||
selection,
|
||||
state: 'idle',
|
||||
attachedClientIds: ['client-1'],
|
||||
},
|
||||
lastSequence: 0,
|
||||
replay: [],
|
||||
};
|
||||
|
||||
function build(): { runtime: HarnessChatRuntime; calls: RecordedCalls } {
|
||||
const calls: RecordedCalls = { attach: [], detach: [], send: [], subscribeFrom: [] };
|
||||
const service: HarnessConversationService = {
|
||||
attach: (input) => {
|
||||
calls.attach.push(input);
|
||||
return Promise.resolve(snapshot);
|
||||
},
|
||||
detach: (input) => {
|
||||
calls.detach.push(input);
|
||||
return Promise.resolve();
|
||||
},
|
||||
send: (input) => {
|
||||
calls.send.push(input);
|
||||
// The service echoes only the requested tuple; there is no representable substitute.
|
||||
const receipt: TurnReceipt = {
|
||||
conversationId: input.conversationId,
|
||||
turnId: 'turn-server',
|
||||
correlationId: input.correlationId,
|
||||
state: 'accepted',
|
||||
selection: input.selection,
|
||||
};
|
||||
return Promise.resolve(receipt);
|
||||
},
|
||||
subscribeFrom: (id, afterSequence) => {
|
||||
calls.subscribeFrom.push({ conversationId: id, afterSequence });
|
||||
|
||||
return (async function* (): AsyncIterable<HarnessEventEnvelope> {
|
||||
return;
|
||||
})();
|
||||
},
|
||||
};
|
||||
return { runtime: new HarnessChatRuntime(service), calls };
|
||||
}
|
||||
|
||||
describe('HarnessChatRuntime', () => {
|
||||
it('is the harness runtime kind and needs only a HarnessConversationService', () => {
|
||||
const { runtime } = build();
|
||||
expect(runtime.kind).toBe('harness');
|
||||
});
|
||||
|
||||
it('delegates send to the conversation service with the exact tuple and idempotency key', async () => {
|
||||
const { runtime, calls } = build();
|
||||
|
||||
const receipt = await runtime.send(sendInput);
|
||||
|
||||
expect(calls.send).toHaveLength(1);
|
||||
const firstSend = calls.send[0]!;
|
||||
expect(firstSend).toEqual(sendInput);
|
||||
expect(firstSend.idempotencyKey).toBe(idempotencyKey);
|
||||
expect(firstSend.selection).toEqual(selection);
|
||||
// The runtime must not substitute an effective tuple onto the receipt.
|
||||
expect(receipt.selection).toEqual(selection);
|
||||
});
|
||||
|
||||
it('delegates attach to the conversation service and returns its snapshot', async () => {
|
||||
const { runtime, calls } = build();
|
||||
|
||||
const result = await runtime.attach(attachInput);
|
||||
|
||||
expect(calls.attach).toHaveLength(1);
|
||||
expect(calls.attach[0]).toEqual(attachInput);
|
||||
expect(result).toBe(snapshot);
|
||||
});
|
||||
|
||||
it('delegates detach to the conversation service', async () => {
|
||||
const { runtime, calls } = build();
|
||||
|
||||
await runtime.detach(detachInput);
|
||||
|
||||
expect(calls.detach).toHaveLength(1);
|
||||
expect(calls.detach[0]).toEqual(detachInput);
|
||||
});
|
||||
|
||||
it('delegates subscribeFrom to the conversation service journal replay', async () => {
|
||||
const { runtime, calls } = build();
|
||||
|
||||
const iterable = runtime.subscribeFrom(conversationId, 7);
|
||||
// Drain to prove it is the service-backed async iterable, not a fabricated one.
|
||||
const drained: unknown[] = [];
|
||||
for await (const event of iterable) {
|
||||
drained.push(event);
|
||||
}
|
||||
expect(drained).toHaveLength(0);
|
||||
|
||||
expect(calls.subscribeFrom).toHaveLength(1);
|
||||
expect(calls.subscribeFrom[0]).toEqual({ conversationId, afterSequence: 7 });
|
||||
});
|
||||
});
|
||||
@@ -1,47 +0,0 @@
|
||||
import type {
|
||||
AttachConversation,
|
||||
ConversationSnapshot,
|
||||
DetachConversation,
|
||||
HarnessConversationService,
|
||||
HarnessEventEnvelope,
|
||||
SendHarnessTurn,
|
||||
TurnReceipt,
|
||||
} from '@mosaicstack/types';
|
||||
import type { ChatRuntime } from './chat-runtime.js';
|
||||
|
||||
/**
|
||||
* The `pi-rpc` chat runtime. It executes browser chat exclusively through the
|
||||
* harness-neutral {@link HarnessConversationService} RPC boundary — it never
|
||||
* touches the embedded `AgentService`/`ProviderService`/`RoutingEngineService`
|
||||
* stack, and it forwards the caller's exact selection tuple and idempotency key
|
||||
* without substitution.
|
||||
*
|
||||
* It owns no state and adds no policy: every method forwards the caller's exact
|
||||
* argument to the injected {@link HarnessConversationService} and returns its
|
||||
* result unchanged, so the requested selection tuple and idempotency key can
|
||||
* never be substituted on the way through.
|
||||
*/
|
||||
export class HarnessChatRuntime implements ChatRuntime {
|
||||
readonly kind = 'harness' as const;
|
||||
|
||||
constructor(private readonly conversations: HarnessConversationService) {}
|
||||
|
||||
attach(input: AttachConversation & { afterSequence?: number }): Promise<ConversationSnapshot> {
|
||||
return this.conversations.attach(input);
|
||||
}
|
||||
|
||||
detach(input: DetachConversation): Promise<void> {
|
||||
return this.conversations.detach(input);
|
||||
}
|
||||
|
||||
send(input: SendHarnessTurn & { idempotencyKey: string }): Promise<TurnReceipt> {
|
||||
return this.conversations.send(input);
|
||||
}
|
||||
|
||||
subscribeFrom(
|
||||
conversationId: string,
|
||||
afterSequence: number,
|
||||
): AsyncIterable<HarnessEventEnvelope> {
|
||||
return this.conversations.subscribeFrom(conversationId, afterSequence);
|
||||
}
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { CommandDef, SlashCommandPayload } from '@mosaicstack/types';
|
||||
import { CommandAuthorizationService } from './command-authorization.service.js';
|
||||
|
||||
const adminCommand: CommandDef = {
|
||||
name: 'gc',
|
||||
description: 'GC',
|
||||
aliases: [],
|
||||
scope: 'admin',
|
||||
execution: 'socket',
|
||||
available: true,
|
||||
};
|
||||
const payload: SlashCommandPayload = { command: 'gc', conversationId: 'conversation-1' };
|
||||
|
||||
function createService(
|
||||
role: string,
|
||||
entries: Map<string, string> = new Map<string, string>(),
|
||||
): CommandAuthorizationService {
|
||||
const db = {
|
||||
select: () => ({ from: () => ({ where: () => ({ limit: async () => [{ role }] }) }) }),
|
||||
};
|
||||
const redis = {
|
||||
get: async (key: string) => entries.get(key) ?? null,
|
||||
set: async (key: string, value: string) => {
|
||||
entries.set(key, value);
|
||||
},
|
||||
del: async (key: string) => Number(entries.delete(key)),
|
||||
};
|
||||
return new CommandAuthorizationService(db as never, redis);
|
||||
}
|
||||
|
||||
describe('CommandAuthorizationService', () => {
|
||||
it('consumes one exact actor-bound approval once', async (): Promise<void> => {
|
||||
const service = createService('admin');
|
||||
const approval = await service.createApproval(adminCommand, payload, 'admin-1');
|
||||
expect(approval).not.toBeNull();
|
||||
expect(
|
||||
(await service.authorize(adminCommand, payload, 'admin-1', approval!.approvalId)).allowed,
|
||||
).toBe(true);
|
||||
expect(
|
||||
(await service.authorize(adminCommand, payload, 'admin-1', approval!.approvalId)).allowed,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects an approval when the structured action is mutated', async (): Promise<void> => {
|
||||
const service = createService('admin');
|
||||
const approval = await service.createApproval(adminCommand, payload, 'admin-1');
|
||||
const mutated = { ...payload, conversationId: 'other-conversation' };
|
||||
expect(approval).not.toBeNull();
|
||||
expect(
|
||||
(await service.authorize(adminCommand, mutated, 'admin-1', approval!.approvalId)).allowed,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('denies an admin command to a member before approval is considered', async (): Promise<void> => {
|
||||
const service = createService('member');
|
||||
const approval = await service.createApproval(adminCommand, payload, 'member-1');
|
||||
expect(approval).toBeNull();
|
||||
expect(
|
||||
(await service.authorize(adminCommand, payload, 'member-1', 'forged-approval-id')).allowed,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('denies a malformed durable approval expiry instead of treating it as unexpired', async (): Promise<void> => {
|
||||
const entries = new Map<string, string>();
|
||||
const action = {
|
||||
providerId: 'fleet',
|
||||
sessionId: 'nova',
|
||||
actorId: 'admin-1',
|
||||
tenantId: 'tenant-1',
|
||||
channelId: 'discord:operator',
|
||||
correlationId: 'correlation-malformed-expiry',
|
||||
agentName: 'Nova',
|
||||
};
|
||||
const service = createService('admin', entries);
|
||||
const approval = await service.createRuntimeTerminationApproval(action);
|
||||
expect(approval).not.toBeNull();
|
||||
const key = `agent:Nova:command-approval:${approval!.approvalId}`;
|
||||
const stored = entries.get(key);
|
||||
expect(stored).toBeDefined();
|
||||
entries.set(key, JSON.stringify({ ...JSON.parse(stored!), expiresAt: 'not-a-date' }));
|
||||
|
||||
expect(await service.consumeRuntimeTerminationApproval(approval!.approvalId, action)).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it('persists and consumes one exact runtime termination approval across a service restart', async (): Promise<void> => {
|
||||
const entries = new Map<string, string>();
|
||||
const action = {
|
||||
providerId: 'fleet',
|
||||
sessionId: 'nova',
|
||||
actorId: 'admin-1',
|
||||
tenantId: 'tenant-1',
|
||||
channelId: 'discord:operator',
|
||||
correlationId: 'correlation-1',
|
||||
agentName: 'Nova',
|
||||
};
|
||||
const beforeRestart = createService('admin', entries);
|
||||
const approval = await beforeRestart.createRuntimeTerminationApproval(action);
|
||||
|
||||
const afterRestart = createService('admin', entries);
|
||||
expect(
|
||||
await afterRestart.consumeRuntimeTerminationApproval(approval!.approvalId, {
|
||||
...action,
|
||||
sessionId: 'forged-session',
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(await afterRestart.consumeRuntimeTerminationApproval(approval!.approvalId, action)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(await afterRestart.consumeRuntimeTerminationApproval(approval!.approvalId, action)).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,268 +0,0 @@
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { eq, users as usersTable, type Db } from '@mosaicstack/db';
|
||||
import type { CommandDef, SlashCommandPayload } from '@mosaicstack/types';
|
||||
import { DB } from '../database/database.module.js';
|
||||
import { COMMANDS_REDIS } from './commands.tokens.js';
|
||||
|
||||
export type CommandRole = 'admin' | 'member' | 'viewer';
|
||||
|
||||
export interface CommandApproval {
|
||||
approvalId: string;
|
||||
actionDigest: string;
|
||||
actorId: string;
|
||||
command: string;
|
||||
expiresAt: string;
|
||||
}
|
||||
|
||||
/** Exact immutable binding for a privileged runtime termination. */
|
||||
export interface RuntimeTerminationApprovalAction {
|
||||
providerId: string;
|
||||
sessionId: string;
|
||||
actorId: string;
|
||||
tenantId: string;
|
||||
channelId: string;
|
||||
correlationId: string;
|
||||
/** Provisioned roster identity; isolates approvals between interaction agents. */
|
||||
agentName: string;
|
||||
}
|
||||
|
||||
export interface RuntimeTerminationApproval extends RuntimeTerminationApprovalAction {
|
||||
approvalId: string;
|
||||
actionDigest: string;
|
||||
expiresAt: string;
|
||||
}
|
||||
|
||||
export interface CommandAuthorizationResult {
|
||||
allowed: boolean;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class CommandAuthorizationService {
|
||||
constructor(
|
||||
@Inject(DB) private readonly db: Db,
|
||||
@Inject(COMMANDS_REDIS)
|
||||
private readonly redis: {
|
||||
get(key: string): Promise<string | null>;
|
||||
set(key: string, value: string, ...args: string[]): Promise<unknown>;
|
||||
del(key: string): Promise<number>;
|
||||
},
|
||||
) {}
|
||||
|
||||
async authorize(
|
||||
command: CommandDef,
|
||||
payload: SlashCommandPayload,
|
||||
actorId: string,
|
||||
approvalId?: string,
|
||||
): Promise<CommandAuthorizationResult> {
|
||||
const role = await this.resolveRole(actorId);
|
||||
if (!role || !this.hasScope(role, command.scope)) {
|
||||
return { allowed: false, reason: 'not authorized for this command scope' };
|
||||
}
|
||||
if (command.scope !== 'admin') return { allowed: true };
|
||||
if (!approvalId) return { allowed: false, reason: 'durable approval is required' };
|
||||
const actionDigest = this.actionDigest(command.name, payload);
|
||||
const approved = await this.consumeApproval(approvalId, actorId, actionDigest);
|
||||
return approved
|
||||
? { allowed: true }
|
||||
: {
|
||||
allowed: false,
|
||||
reason: 'approval is invalid, expired, replayed, or does not match this action',
|
||||
};
|
||||
}
|
||||
|
||||
async createApproval(
|
||||
command: CommandDef,
|
||||
payload: SlashCommandPayload,
|
||||
actorId: string,
|
||||
): Promise<CommandApproval | null> {
|
||||
const role = await this.resolveRole(actorId);
|
||||
if (!role || command.scope !== 'admin' || !this.hasScope(role, command.scope)) return null;
|
||||
|
||||
const approvalId = randomUUID();
|
||||
const expiresAt = new Date(Date.now() + 5 * 60_000).toISOString();
|
||||
const approval: CommandApproval = {
|
||||
approvalId,
|
||||
actionDigest: this.actionDigest(command.name, payload),
|
||||
actorId,
|
||||
command: command.name,
|
||||
expiresAt,
|
||||
};
|
||||
await this.redis.set(this.key(approvalId), JSON.stringify(approval), 'EX', '300');
|
||||
return approval;
|
||||
}
|
||||
|
||||
/**
|
||||
* Uses the same `interaction:command-approval:*` store and one-time deletion rule as
|
||||
* command approvals. This deliberately avoids a parallel approval database.
|
||||
*/
|
||||
async createRuntimeTerminationApproval(
|
||||
action: RuntimeTerminationApprovalAction,
|
||||
): Promise<RuntimeTerminationApproval | null> {
|
||||
if (!this.hasRuntimeTerminationAction(action)) return null;
|
||||
const role = await this.resolveRole(action.actorId);
|
||||
if (role !== 'admin') return null;
|
||||
|
||||
const approval: RuntimeTerminationApproval = {
|
||||
approvalId: randomUUID(),
|
||||
actionDigest: this.runtimeActionDigest(action),
|
||||
...action,
|
||||
expiresAt: new Date(Date.now() + 5 * 60_000).toISOString(),
|
||||
};
|
||||
await this.redis.set(
|
||||
this.runtimeKey(action.agentName, approval.approvalId),
|
||||
JSON.stringify(approval),
|
||||
'EX',
|
||||
'300',
|
||||
);
|
||||
return approval;
|
||||
}
|
||||
|
||||
async consumeRuntimeTerminationApproval(
|
||||
approvalId: string,
|
||||
action: RuntimeTerminationApprovalAction,
|
||||
): Promise<boolean> {
|
||||
const encoded = await this.redis.get(this.runtimeKey(action.agentName, approvalId));
|
||||
if (!encoded) return false;
|
||||
let approval: unknown;
|
||||
try {
|
||||
approval = JSON.parse(encoded);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
!this.isRuntimeTerminationApproval(approval) ||
|
||||
approval.actionDigest !== this.runtimeActionDigest(action) ||
|
||||
approval.actorId !== action.actorId ||
|
||||
approval.tenantId !== action.tenantId ||
|
||||
!this.isUnexpired(approval.expiresAt)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if ((await this.resolveRole(approval.actorId)) !== 'admin') return false;
|
||||
return (await this.redis.del(this.runtimeKey(action.agentName, approvalId))) === 1;
|
||||
}
|
||||
|
||||
private async resolveRole(actorId: string): Promise<CommandRole | null> {
|
||||
const [user] = await this.db
|
||||
.select({ role: usersTable.role })
|
||||
.from(usersTable)
|
||||
.where(eq(usersTable.id, actorId))
|
||||
.limit(1);
|
||||
const role = user?.role;
|
||||
return role === 'admin' || role === 'member' || role === 'viewer' ? role : null;
|
||||
}
|
||||
|
||||
private hasScope(role: CommandRole, scope: CommandDef['scope']): boolean {
|
||||
if (role === 'admin') return true;
|
||||
return role === 'member' && (scope === 'core' || scope === 'agent');
|
||||
}
|
||||
|
||||
private async consumeApproval(
|
||||
approvalId: string,
|
||||
actorId: string,
|
||||
actionDigest: string,
|
||||
): Promise<boolean> {
|
||||
const key = this.key(approvalId);
|
||||
const encoded = await this.redis.get(key);
|
||||
if (!encoded) return false;
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(encoded);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
!this.isCommandApproval(parsed) ||
|
||||
parsed.actorId !== actorId ||
|
||||
parsed.actionDigest !== actionDigest ||
|
||||
!this.isUnexpired(parsed.expiresAt)
|
||||
)
|
||||
return false;
|
||||
return (await this.redis.del(key)) === 1;
|
||||
}
|
||||
|
||||
private actionDigest(command: string, payload: SlashCommandPayload): string {
|
||||
return createHash('sha256')
|
||||
.update(
|
||||
JSON.stringify({
|
||||
command,
|
||||
args: payload.args?.trim() ?? '',
|
||||
conversationId: payload.conversationId,
|
||||
}),
|
||||
)
|
||||
.digest('hex');
|
||||
}
|
||||
|
||||
private hasRuntimeTerminationAction(action: RuntimeTerminationApprovalAction): boolean {
|
||||
return [
|
||||
action.providerId,
|
||||
action.sessionId,
|
||||
action.actorId,
|
||||
action.tenantId,
|
||||
action.channelId,
|
||||
action.correlationId,
|
||||
action.agentName,
|
||||
].every((value: string): boolean => value.trim().length > 0);
|
||||
}
|
||||
|
||||
private runtimeActionDigest(action: RuntimeTerminationApprovalAction): string {
|
||||
return createHash('sha256')
|
||||
.update(
|
||||
JSON.stringify({
|
||||
providerId: action.providerId,
|
||||
sessionId: action.sessionId,
|
||||
actorId: action.actorId,
|
||||
tenantId: action.tenantId,
|
||||
channelId: action.channelId,
|
||||
correlationId: action.correlationId,
|
||||
agentName: action.agentName,
|
||||
}),
|
||||
)
|
||||
.digest('hex');
|
||||
}
|
||||
|
||||
private isUnexpired(expiresAt: unknown): expiresAt is string {
|
||||
if (typeof expiresAt !== 'string') return false;
|
||||
const expiresAtMs = Date.parse(expiresAt);
|
||||
return Number.isFinite(expiresAtMs) && expiresAtMs > Date.now();
|
||||
}
|
||||
|
||||
private isCommandApproval(value: unknown): value is CommandApproval {
|
||||
return (
|
||||
typeof value === 'object' &&
|
||||
value !== null &&
|
||||
'approvalId' in value &&
|
||||
'actionDigest' in value &&
|
||||
'actorId' in value &&
|
||||
'expiresAt' in value &&
|
||||
'command' in value
|
||||
);
|
||||
}
|
||||
|
||||
private isRuntimeTerminationApproval(value: unknown): value is RuntimeTerminationApproval {
|
||||
return (
|
||||
typeof value === 'object' &&
|
||||
value !== null &&
|
||||
'approvalId' in value &&
|
||||
'actionDigest' in value &&
|
||||
'actorId' in value &&
|
||||
'tenantId' in value &&
|
||||
'providerId' in value &&
|
||||
'sessionId' in value &&
|
||||
'channelId' in value &&
|
||||
'correlationId' in value &&
|
||||
'agentName' in value &&
|
||||
'expiresAt' in value
|
||||
);
|
||||
}
|
||||
|
||||
private key(approvalId: string): string {
|
||||
return `interaction:command-approval:${approvalId}`;
|
||||
}
|
||||
|
||||
private runtimeKey(agentName: string, approvalId: string): string {
|
||||
return `agent:${encodeURIComponent(agentName)}:command-approval:${approvalId}`;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { CommandExecutorService } from './command-executor.service.js';
|
||||
import type { SlashCommandPayload } from '@mosaicstack/types';
|
||||
@@ -13,7 +12,6 @@ const mockRegistry = {
|
||||
{ name: 'agent', aliases: ['a'], scope: 'agent', execution: 'socket', available: true },
|
||||
{ name: 'prdy', aliases: [], scope: 'agent', execution: 'socket', available: true },
|
||||
{ name: 'tools', aliases: [], scope: 'agent', execution: 'socket', available: true },
|
||||
{ name: 'mcp', aliases: [], scope: 'agent', execution: 'socket', available: true },
|
||||
],
|
||||
skills: [],
|
||||
})),
|
||||
@@ -74,37 +72,23 @@ const mockChatGateway = {
|
||||
broadcastSessionInfo: vi.fn(),
|
||||
};
|
||||
|
||||
const mockMcpClient = {
|
||||
reconnectServer: vi.fn().mockResolvedValue(undefined),
|
||||
getServerStatuses: vi.fn(() => []),
|
||||
getToolDefinitions: vi.fn(() => []),
|
||||
};
|
||||
|
||||
function buildService(
|
||||
redis: typeof mockRedis | null = mockRedis,
|
||||
mcpClient: {
|
||||
reconnectServer: ReturnType<typeof vi.fn>;
|
||||
getServerStatuses: ReturnType<typeof vi.fn>;
|
||||
getToolDefinitions: ReturnType<typeof vi.fn>;
|
||||
} = mockMcpClient,
|
||||
): CommandExecutorService {
|
||||
function buildService(): CommandExecutorService {
|
||||
return new CommandExecutorService(
|
||||
mockRegistry as never,
|
||||
mockAgentService as never,
|
||||
mockSystemOverride as never,
|
||||
mockSessionGC as never,
|
||||
redis as never,
|
||||
mockRedis as never,
|
||||
mockBrain as never,
|
||||
null,
|
||||
mockChatGateway as never,
|
||||
mcpClient as never,
|
||||
null,
|
||||
);
|
||||
}
|
||||
|
||||
describe('CommandExecutorService — P8-012 commands', () => {
|
||||
let service: CommandExecutorService;
|
||||
const userId = 'user-123';
|
||||
const userScope = { userId, tenantId: userId };
|
||||
const conversationId = 'conv-456';
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -115,26 +99,31 @@ describe('CommandExecutorService — P8-012 commands', () => {
|
||||
// /provider login — missing provider name
|
||||
it('/provider login with no provider name returns usage error', async () => {
|
||||
const payload: SlashCommandPayload = { command: 'provider', args: 'login', conversationId };
|
||||
const result = await service.execute(payload, userScope);
|
||||
const result = await service.execute(payload, userId);
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.message).toContain('Usage: /provider login');
|
||||
expect(result.command).toBe('provider');
|
||||
});
|
||||
|
||||
// /provider login anthropic — no bearer token or auth URL reaches chat output
|
||||
it('/provider login <name> keeps its one-time token out of chat output', async () => {
|
||||
// /provider login anthropic — success with URL containing poll token
|
||||
it('/provider login <name> returns success with URL and poll token', async () => {
|
||||
const payload: SlashCommandPayload = {
|
||||
command: 'provider',
|
||||
args: 'login anthropic',
|
||||
conversationId,
|
||||
};
|
||||
const result = await service.execute(payload, userScope);
|
||||
const result = await service.execute(payload, userId);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.command).toBe('provider');
|
||||
expect(result.message).toContain('anthropic');
|
||||
expect(result.message).not.toContain('http');
|
||||
expect(result.message).not.toContain('token=');
|
||||
expect(result.data).toEqual({ provider: 'anthropic' });
|
||||
expect(result.message).toContain('http');
|
||||
// data should contain loginUrl and pollToken
|
||||
expect(result.data).toBeDefined();
|
||||
const data = result.data as Record<string, unknown>;
|
||||
expect(typeof data['loginUrl']).toBe('string');
|
||||
expect(typeof data['pollToken']).toBe('string');
|
||||
expect(data['loginUrl'] as string).toContain('anthropic');
|
||||
expect(data['loginUrl'] as string).toContain(data['pollToken'] as string);
|
||||
// Verify Valkey was called
|
||||
expect(mockRedis.set).toHaveBeenCalledOnce();
|
||||
const [key, value, , ttl] = mockRedis.set.mock.calls[0] as [string, string, string, number];
|
||||
@@ -146,26 +135,10 @@ describe('CommandExecutorService — P8-012 commands', () => {
|
||||
expect(ttl).toBe(300);
|
||||
});
|
||||
|
||||
it('/provider login remains available without Redis on the local tier', async () => {
|
||||
const localService = buildService(null);
|
||||
const payload: SlashCommandPayload = {
|
||||
command: 'provider',
|
||||
args: 'login anthropic',
|
||||
conversationId,
|
||||
};
|
||||
|
||||
const result = await localService.execute(payload, userScope);
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.message).not.toContain('token=');
|
||||
expect(result.data).toEqual({ provider: 'anthropic' });
|
||||
expect(mockRedis.set).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// /provider with no args — returns usage
|
||||
it('/provider with no args returns usage message', async () => {
|
||||
const payload: SlashCommandPayload = { command: 'provider', conversationId };
|
||||
const result = await service.execute(payload, userScope);
|
||||
const result = await service.execute(payload, userId);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.message).toContain('Usage: /provider');
|
||||
});
|
||||
@@ -173,7 +146,7 @@ describe('CommandExecutorService — P8-012 commands', () => {
|
||||
// /provider list
|
||||
it('/provider list returns success', async () => {
|
||||
const payload: SlashCommandPayload = { command: 'provider', args: 'list', conversationId };
|
||||
const result = await service.execute(payload, userScope);
|
||||
const result = await service.execute(payload, userId);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.command).toBe('provider');
|
||||
});
|
||||
@@ -181,7 +154,7 @@ describe('CommandExecutorService — P8-012 commands', () => {
|
||||
// /provider logout with no name — usage error
|
||||
it('/provider logout with no name returns error', async () => {
|
||||
const payload: SlashCommandPayload = { command: 'provider', args: 'logout', conversationId };
|
||||
const result = await service.execute(payload, userScope);
|
||||
const result = await service.execute(payload, userId);
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.message).toContain('Usage: /provider logout');
|
||||
});
|
||||
@@ -193,7 +166,7 @@ describe('CommandExecutorService — P8-012 commands', () => {
|
||||
args: 'unknown',
|
||||
conversationId,
|
||||
};
|
||||
const result = await service.execute(payload, userScope);
|
||||
const result = await service.execute(payload, userId);
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.message).toContain('Unknown subcommand');
|
||||
});
|
||||
@@ -201,7 +174,7 @@ describe('CommandExecutorService — P8-012 commands', () => {
|
||||
// /mission status
|
||||
it('/mission status returns stub message', async () => {
|
||||
const payload: SlashCommandPayload = { command: 'mission', args: 'status', conversationId };
|
||||
const result = await service.execute(payload, userScope);
|
||||
const result = await service.execute(payload, userId);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.command).toBe('mission');
|
||||
expect(result.message).toContain('Mission status');
|
||||
@@ -210,7 +183,7 @@ describe('CommandExecutorService — P8-012 commands', () => {
|
||||
// /mission with no args
|
||||
it('/mission with no args returns status stub', async () => {
|
||||
const payload: SlashCommandPayload = { command: 'mission', conversationId };
|
||||
const result = await service.execute(payload, userScope);
|
||||
const result = await service.execute(payload, userId);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.message).toContain('Mission status');
|
||||
});
|
||||
@@ -222,7 +195,7 @@ describe('CommandExecutorService — P8-012 commands', () => {
|
||||
args: 'set my-mission-123',
|
||||
conversationId,
|
||||
};
|
||||
const result = await service.execute(payload, userScope);
|
||||
const result = await service.execute(payload, userId);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.message).toContain('my-mission-123');
|
||||
});
|
||||
@@ -230,7 +203,7 @@ describe('CommandExecutorService — P8-012 commands', () => {
|
||||
// /agent list
|
||||
it('/agent list returns stub message', async () => {
|
||||
const payload: SlashCommandPayload = { command: 'agent', args: 'list', conversationId };
|
||||
const result = await service.execute(payload, userScope);
|
||||
const result = await service.execute(payload, userId);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.command).toBe('agent');
|
||||
expect(result.message).toContain('agent');
|
||||
@@ -239,7 +212,7 @@ describe('CommandExecutorService — P8-012 commands', () => {
|
||||
// /agent with no args
|
||||
it('/agent with no args returns usage', async () => {
|
||||
const payload: SlashCommandPayload = { command: 'agent', conversationId };
|
||||
const result = await service.execute(payload, userScope);
|
||||
const result = await service.execute(payload, userId);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.message).toContain('Usage: /agent');
|
||||
});
|
||||
@@ -251,7 +224,7 @@ describe('CommandExecutorService — P8-012 commands', () => {
|
||||
args: 'my-agent-id',
|
||||
conversationId,
|
||||
};
|
||||
const result = await service.execute(payload, userScope);
|
||||
const result = await service.execute(payload, userId);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.message).toContain('my-agent-id');
|
||||
});
|
||||
@@ -259,7 +232,7 @@ describe('CommandExecutorService — P8-012 commands', () => {
|
||||
// /prdy
|
||||
it('/prdy returns PRD wizard message', async () => {
|
||||
const payload: SlashCommandPayload = { command: 'prdy', conversationId };
|
||||
const result = await service.execute(payload, userScope);
|
||||
const result = await service.execute(payload, userId);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.command).toBe('prdy');
|
||||
expect(result.message).toContain('mosaic prdy');
|
||||
@@ -268,129 +241,9 @@ describe('CommandExecutorService — P8-012 commands', () => {
|
||||
// /tools
|
||||
it('/tools returns tools stub message', async () => {
|
||||
const payload: SlashCommandPayload = { command: 'tools', conversationId };
|
||||
const result = await service.execute(payload, userScope);
|
||||
const result = await service.execute(payload, userId);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.command).toBe('tools');
|
||||
expect(result.message).toContain('tools');
|
||||
});
|
||||
|
||||
// Top-level catch sanitization (P3-4 re-review finding #1): a rejected
|
||||
// Redis `set` inside /provider login is the only reachable path into the
|
||||
// top-level catch in `execute()`. The raw exception must be logged
|
||||
// server-side but never handed back to the socket client.
|
||||
it('sanitizes the top-level command catch, logging the raw exception but never returning it to the client', async () => {
|
||||
const distinctiveRawFailure = 'ECONNREFUSED distinctive-raw-redis-failure-token-9f31';
|
||||
const rawError = new Error(distinctiveRawFailure);
|
||||
const failingRedis = {
|
||||
set: vi.fn().mockRejectedValue(rawError),
|
||||
get: vi.fn(),
|
||||
del: vi.fn(),
|
||||
};
|
||||
const failingService = buildService(failingRedis as unknown as typeof mockRedis);
|
||||
const loggerErrorSpy = vi.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined);
|
||||
|
||||
const payload: SlashCommandPayload = {
|
||||
command: 'provider',
|
||||
args: 'login anthropic',
|
||||
conversationId,
|
||||
};
|
||||
const result = await failingService.execute(payload, userScope);
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.command).toBe('provider');
|
||||
expect(result.message).toBe('Command failed due to an internal error.');
|
||||
expect(result.message).not.toContain(distinctiveRawFailure);
|
||||
expect(result.message).not.toContain('ECONNREFUSED');
|
||||
|
||||
// The real exception is still logged server-side, as the raw Error
|
||||
// object itself (not stringified/interpolated into the log message).
|
||||
expect(loggerErrorSpy).toHaveBeenCalled();
|
||||
const loggedRawError = loggerErrorSpy.mock.calls.some((call) => call.includes(rawError));
|
||||
expect(loggedRawError).toBe(true);
|
||||
|
||||
loggerErrorSpy.mockRestore();
|
||||
});
|
||||
|
||||
// Inner catch sanitization (P3-5 operator ruling): every catch in
|
||||
// command-executor.service.ts that returns a SlashCommandResultPayload
|
||||
// must sanitize the client-facing message the same way the top-level
|
||||
// catch does, while still logging the raw exception server-side.
|
||||
it('/agent new sanitizes agent-creation failures, logging the raw exception but never returning it to the client', async () => {
|
||||
const marker = new Error('distinctive-agent-create-failure-token-A17f');
|
||||
mockBrain.agents.create.mockRejectedValueOnce(marker);
|
||||
const loggerErrorSpy = vi.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined);
|
||||
|
||||
const payload: SlashCommandPayload = {
|
||||
command: 'agent',
|
||||
args: 'new my-new-agent',
|
||||
conversationId,
|
||||
};
|
||||
const result = await service.execute(payload, userScope);
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.command).toBe('agent');
|
||||
expect(result.message).toBe('Failed to create agent due to an internal error.');
|
||||
expect(result.message).not.toContain('distinctive-agent-create-failure-token-A17f');
|
||||
|
||||
expect(loggerErrorSpy).toHaveBeenCalled();
|
||||
const loggedRawError = loggerErrorSpy.mock.calls.some((call) => call.includes(marker));
|
||||
expect(loggedRawError).toBe(true);
|
||||
|
||||
loggerErrorSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('/agent <name> switch sanitizes agent-lookup failures, logging the raw exception but never returning it to the client', async () => {
|
||||
const marker = new Error('distinctive-agent-switch-failure-token-B29c');
|
||||
mockBrain.agents.findByName.mockRejectedValueOnce(marker);
|
||||
const loggerErrorSpy = vi.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined);
|
||||
|
||||
const payload: SlashCommandPayload = {
|
||||
command: 'agent',
|
||||
args: 'some-other-agent',
|
||||
conversationId,
|
||||
};
|
||||
const result = await service.execute(payload, userScope);
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.command).toBe('agent');
|
||||
expect(result.message).toBe('Failed to switch agent due to an internal error.');
|
||||
expect(result.message).not.toContain('distinctive-agent-switch-failure-token-B29c');
|
||||
|
||||
expect(loggerErrorSpy).toHaveBeenCalled();
|
||||
const loggedRawError = loggerErrorSpy.mock.calls.some((call) => call.includes(marker));
|
||||
expect(loggedRawError).toBe(true);
|
||||
|
||||
loggerErrorSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('/mcp reconnect sanitizes MCP client failures, logging the raw exception but never returning it to the client', async () => {
|
||||
const marker = new Error('distinctive-mcp-reconnect-failure-token-C33e');
|
||||
const mockMcpClient = {
|
||||
reconnectServer: vi.fn().mockRejectedValue(marker),
|
||||
getServerStatuses: vi.fn(() => []),
|
||||
getToolDefinitions: vi.fn(() => []),
|
||||
};
|
||||
const mcpService = buildService(mockRedis, mockMcpClient);
|
||||
const loggerErrorSpy = vi.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined);
|
||||
|
||||
const payload: SlashCommandPayload = {
|
||||
command: 'mcp',
|
||||
args: 'reconnect my-server',
|
||||
conversationId,
|
||||
};
|
||||
const result = await mcpService.execute(payload, userScope);
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.command).toBe('mcp');
|
||||
expect(result.message).toBe(
|
||||
'Failed to reconnect MCP server "my-server" due to an internal error.',
|
||||
);
|
||||
expect(result.message).not.toContain('distinctive-mcp-reconnect-failure-token-C33e');
|
||||
|
||||
expect(loggerErrorSpy).toHaveBeenCalled();
|
||||
const loggedRawError = loggerErrorSpy.mock.calls.some((call) => call.includes(marker));
|
||||
expect(loggedRawError).toBe(true);
|
||||
|
||||
loggerErrorSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,118 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { SlashCommandPayload } from '@mosaicstack/types';
|
||||
import { CommandAuthorizationService } from './command-authorization.service.js';
|
||||
import { CommandExecutorService } from './command-executor.service.js';
|
||||
|
||||
const registry = {
|
||||
getManifest: vi.fn(() => ({
|
||||
version: 1,
|
||||
commands: [
|
||||
{
|
||||
name: 'gc',
|
||||
description: 'System-wide garbage collection',
|
||||
aliases: [],
|
||||
scope: 'admin' as const,
|
||||
execution: 'socket' as const,
|
||||
available: true,
|
||||
},
|
||||
],
|
||||
skills: [],
|
||||
})),
|
||||
};
|
||||
|
||||
const sessionGc = {
|
||||
sweepOrphans: vi.fn().mockResolvedValue({ orphanedSessions: 1, totalCleaned: [], duration: 1 }),
|
||||
};
|
||||
|
||||
const scope = (userId: string) => ({ userId, tenantId: 'tenant-1' });
|
||||
|
||||
const authorization = {
|
||||
authorize: vi.fn((_command: unknown, _payload: unknown, actorId: string) =>
|
||||
Promise.resolve(
|
||||
actorId === 'member-1'
|
||||
? { allowed: false, reason: 'durable approval is required' }
|
||||
: { allowed: false, reason: 'not authorized for this command scope' },
|
||||
),
|
||||
),
|
||||
};
|
||||
|
||||
const mockMcpClient = {
|
||||
getServerStatuses: vi.fn(() => []),
|
||||
getToolDefinitions: vi.fn(() => []),
|
||||
reconnectServer: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
|
||||
function buildExecutor(authorizationService: unknown = authorization): CommandExecutorService {
|
||||
return new CommandExecutorService(
|
||||
registry as never,
|
||||
{ getSession: vi.fn() } as never,
|
||||
{ clear: vi.fn(), set: vi.fn() } as never,
|
||||
sessionGc as never,
|
||||
{ set: vi.fn() } as never,
|
||||
{ agents: {} } as never,
|
||||
null,
|
||||
null,
|
||||
mockMcpClient as never,
|
||||
authorizationService as never,
|
||||
);
|
||||
}
|
||||
|
||||
function createDurableAuthorization(): CommandAuthorizationService {
|
||||
const entries = new Map<string, string>();
|
||||
const db = {
|
||||
select: () => ({ from: () => ({ where: () => ({ limit: async () => [{ role: 'admin' }] }) }) }),
|
||||
};
|
||||
const redis = {
|
||||
get: async (key: string) => entries.get(key) ?? null,
|
||||
set: async (key: string, value: string) => {
|
||||
entries.set(key, value);
|
||||
},
|
||||
del: async (key: string) => Number(entries.delete(key)),
|
||||
};
|
||||
return new CommandAuthorizationService(db as never, redis);
|
||||
}
|
||||
|
||||
describe('TESS-M1-SEC-001 command authorization abuse cases', () => {
|
||||
const payload: SlashCommandPayload = { command: 'gc', conversationId: 'conversation-1' };
|
||||
|
||||
beforeEach((): void => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('denies a forged admin identity and does not execute a system-wide command', async (): Promise<void> => {
|
||||
const result = await buildExecutor().execute(payload, scope('admin-forged-by-client'));
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.message).toContain('not authorized');
|
||||
expect(sessionGc.sweepOrphans).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('denies a privileged command without a server-bound durable approval', async (): Promise<void> => {
|
||||
const result = await buildExecutor().execute(payload, scope('member-1'));
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.message).toContain('approval');
|
||||
expect(sessionGc.sweepOrphans).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('executes an admin command only after a valid durable approval is issued and supplied', async (): Promise<void> => {
|
||||
const executor = buildExecutor(createDurableAuthorization());
|
||||
|
||||
const adminScope = scope('admin-1');
|
||||
const denied = await executor.execute(payload, adminScope);
|
||||
const approval = await executor.createApproval(payload, adminScope);
|
||||
const approved = await executor.execute(
|
||||
{ ...payload, approvalId: approval?.approvalId },
|
||||
adminScope,
|
||||
);
|
||||
|
||||
expect(denied.success).toBe(false);
|
||||
expect(denied.message).toContain('approval');
|
||||
expect(approval).not.toBeNull();
|
||||
// A valid durable approval is consumed, but cannot authorize an unimplemented
|
||||
// global retention operation. Session-scoped cleanup remains lifecycle-only.
|
||||
expect(approved.success).toBe(false);
|
||||
expect(approved.message).toContain('Global GC is disabled');
|
||||
expect(sessionGc.sweepOrphans).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,6 @@ import type { QueueHandle } from '@mosaicstack/queue';
|
||||
import type { Brain } from '@mosaicstack/brain';
|
||||
import type { SlashCommandPayload, SlashCommandResultPayload } from '@mosaicstack/types';
|
||||
import { AgentService } from '../agent/agent.service.js';
|
||||
import type { ActorTenantScope } from '../auth/session-scope.js';
|
||||
import { ChatGateway } from '../chat/chat.gateway.js';
|
||||
import { SessionGCService } from '../gc/session-gc.service.js';
|
||||
import { SystemOverrideService } from '../preferences/system-override.service.js';
|
||||
@@ -11,7 +10,6 @@ import { ReloadService } from '../reload/reload.service.js';
|
||||
import { McpClientService } from '../mcp-client/mcp-client.service.js';
|
||||
import { BRAIN } from '../brain/brain.tokens.js';
|
||||
import { COMMANDS_REDIS } from './commands.tokens.js';
|
||||
import { CommandAuthorizationService } from './command-authorization.service.js';
|
||||
import { CommandRegistryService } from './command-registry.service.js';
|
||||
|
||||
@Injectable()
|
||||
@@ -23,10 +21,7 @@ export class CommandExecutorService {
|
||||
@Inject(AgentService) private readonly agentService: AgentService,
|
||||
@Inject(SystemOverrideService) private readonly systemOverride: SystemOverrideService,
|
||||
@Inject(SessionGCService) private readonly sessionGC: SessionGCService,
|
||||
// On Local tier COMMANDS_REDIS is null — provider login caching is skipped.
|
||||
@Optional()
|
||||
@Inject(COMMANDS_REDIS)
|
||||
private readonly redis: QueueHandle['redis'] | null,
|
||||
@Inject(COMMANDS_REDIS) private readonly redis: QueueHandle['redis'],
|
||||
@Inject(BRAIN) private readonly brain: Brain,
|
||||
@Optional()
|
||||
@Inject(forwardRef(() => ReloadService))
|
||||
@@ -34,18 +29,13 @@ export class CommandExecutorService {
|
||||
@Optional()
|
||||
@Inject(forwardRef(() => ChatGateway))
|
||||
private readonly chatGateway: ChatGateway | null,
|
||||
@Inject(McpClientService) private readonly mcpClient: McpClientService,
|
||||
@Optional()
|
||||
@Inject(CommandAuthorizationService)
|
||||
private readonly authorization: CommandAuthorizationService | null = null,
|
||||
@Inject(McpClientService)
|
||||
private readonly mcpClient: McpClientService | null,
|
||||
) {}
|
||||
|
||||
async execute(
|
||||
payload: SlashCommandPayload,
|
||||
scope: ActorTenantScope,
|
||||
): Promise<SlashCommandResultPayload> {
|
||||
async execute(payload: SlashCommandPayload, userId: string): Promise<SlashCommandResultPayload> {
|
||||
const { command, args, conversationId } = payload;
|
||||
const userId = scope.userId;
|
||||
|
||||
const def = this.registry.getManifest().commands.find((c) => c.name === command);
|
||||
if (!def) {
|
||||
@@ -57,24 +47,14 @@ export class CommandExecutorService {
|
||||
};
|
||||
}
|
||||
|
||||
const authorization = await this.authorization?.authorize(
|
||||
def,
|
||||
payload,
|
||||
userId,
|
||||
payload.approvalId,
|
||||
);
|
||||
if (authorization && !authorization.allowed) {
|
||||
return { command, conversationId, success: false, message: authorization.reason };
|
||||
}
|
||||
|
||||
try {
|
||||
switch (command) {
|
||||
case 'model':
|
||||
return await this.handleModel(args ?? null, conversationId, scope);
|
||||
return await this.handleModel(args ?? null, conversationId);
|
||||
case 'thinking':
|
||||
return await this.handleThinking(args ?? null, conversationId);
|
||||
case 'system':
|
||||
return await this.handleSystem(args ?? null, conversationId, scope);
|
||||
return await this.handleSystem(args ?? null, conversationId);
|
||||
case 'new':
|
||||
return {
|
||||
command,
|
||||
@@ -103,17 +83,18 @@ export class CommandExecutorService {
|
||||
success: true,
|
||||
message: 'Retry last message requested.',
|
||||
};
|
||||
case 'gc':
|
||||
// Global retention requires a separate, authorized and audited job.
|
||||
// Session cleanup is performed only through the session lifecycle.
|
||||
case 'gc': {
|
||||
// Admin-only: system-wide GC sweep across all sessions
|
||||
const result = await this.sessionGC.sweepOrphans();
|
||||
return {
|
||||
command: 'gc',
|
||||
success: false,
|
||||
message: 'Global GC is disabled pending an authorized retention job.',
|
||||
success: true,
|
||||
message: `GC sweep complete: ${result.orphanedSessions} orphaned sessions cleaned in ${result.duration}ms.`,
|
||||
conversationId,
|
||||
};
|
||||
}
|
||||
case 'agent':
|
||||
return await this.handleAgent(args ?? null, conversationId, scope);
|
||||
return await this.handleAgent(args ?? null, conversationId, userId);
|
||||
case 'provider':
|
||||
return await this.handleProvider(args ?? null, userId, conversationId);
|
||||
case 'mission':
|
||||
@@ -157,32 +138,18 @@ export class CommandExecutorService {
|
||||
};
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.error(`Command /${command} failed`, err);
|
||||
return {
|
||||
command,
|
||||
conversationId,
|
||||
success: false,
|
||||
message: 'Command failed due to an internal error.',
|
||||
};
|
||||
this.logger.error(`Command /${command} failed: ${err}`);
|
||||
return { command, conversationId, success: false, message: String(err) };
|
||||
}
|
||||
}
|
||||
|
||||
async createApproval(payload: SlashCommandPayload, scope: ActorTenantScope) {
|
||||
const def = this.registry
|
||||
.getManifest()
|
||||
.commands.find((command) => command.name === payload.command);
|
||||
if (!def || !this.authorization) return null;
|
||||
return this.authorization.createApproval(def, payload, scope.userId);
|
||||
}
|
||||
|
||||
private async handleModel(
|
||||
args: string | null,
|
||||
conversationId: string,
|
||||
scope: ActorTenantScope,
|
||||
): Promise<SlashCommandResultPayload> {
|
||||
if (!args || args.trim().length === 0) {
|
||||
// Show current override or usage hint
|
||||
const currentOverride = this.chatGateway?.getModelOverride(conversationId, scope);
|
||||
const currentOverride = this.chatGateway?.getModelOverride(conversationId);
|
||||
if (currentOverride) {
|
||||
return {
|
||||
command: 'model',
|
||||
@@ -204,7 +171,7 @@ export class CommandExecutorService {
|
||||
|
||||
// /model clear removes the override and re-enables automatic routing
|
||||
if (modelName === 'clear') {
|
||||
this.chatGateway?.setModelOverride(conversationId, null, scope);
|
||||
this.chatGateway?.setModelOverride(conversationId, null);
|
||||
return {
|
||||
command: 'model',
|
||||
conversationId,
|
||||
@@ -214,9 +181,9 @@ export class CommandExecutorService {
|
||||
}
|
||||
|
||||
// Set the sticky per-session override (M4-007)
|
||||
this.chatGateway?.setModelOverride(conversationId, modelName, scope);
|
||||
this.chatGateway?.setModelOverride(conversationId, modelName);
|
||||
|
||||
const session = this.agentService.getSession(conversationId, scope);
|
||||
const session = this.agentService.getSession(conversationId);
|
||||
if (!session) {
|
||||
return {
|
||||
command: 'model',
|
||||
@@ -257,11 +224,10 @@ export class CommandExecutorService {
|
||||
private async handleSystem(
|
||||
args: string | null,
|
||||
conversationId: string,
|
||||
scope: ActorTenantScope,
|
||||
): Promise<SlashCommandResultPayload> {
|
||||
if (!args || args.trim().length === 0) {
|
||||
// Clear the override when called with no args
|
||||
await this.systemOverride.clear(conversationId, scope);
|
||||
await this.systemOverride.clear(conversationId);
|
||||
return {
|
||||
command: 'system',
|
||||
conversationId,
|
||||
@@ -270,7 +236,7 @@ export class CommandExecutorService {
|
||||
};
|
||||
}
|
||||
|
||||
await this.systemOverride.set(conversationId, args.trim(), scope);
|
||||
await this.systemOverride.set(conversationId, args.trim());
|
||||
return {
|
||||
command: 'system',
|
||||
conversationId,
|
||||
@@ -282,9 +248,8 @@ export class CommandExecutorService {
|
||||
private async handleAgent(
|
||||
args: string | null,
|
||||
conversationId: string,
|
||||
scope: ActorTenantScope,
|
||||
userId: string,
|
||||
): Promise<SlashCommandResultPayload> {
|
||||
const userId = scope.userId;
|
||||
if (!args) {
|
||||
return {
|
||||
command: 'agent',
|
||||
@@ -339,11 +304,11 @@ export class CommandExecutorService {
|
||||
data: { agentId: newAgent.id, agentName: newAgent.name },
|
||||
};
|
||||
} catch (err) {
|
||||
this.logger.error(`Failed to create agent "${namePart}" for user ${userId}`, err);
|
||||
this.logger.error(`Failed to create agent: ${err}`);
|
||||
return {
|
||||
command: 'agent',
|
||||
success: false,
|
||||
message: 'Failed to create agent due to an internal error.',
|
||||
message: `Failed to create agent: ${String(err)}`,
|
||||
conversationId,
|
||||
};
|
||||
}
|
||||
@@ -373,14 +338,11 @@ export class CommandExecutorService {
|
||||
conversationId,
|
||||
agentConfig.id,
|
||||
agentConfig.name,
|
||||
scope,
|
||||
agentConfig.model ?? undefined,
|
||||
);
|
||||
|
||||
// Broadcast updated session:info so TUI TopBar reflects new agent/model
|
||||
this.chatGateway?.broadcastSessionInfo(conversationId, scope, {
|
||||
agentName: agentConfig.name,
|
||||
});
|
||||
this.chatGateway?.broadcastSessionInfo(conversationId, { agentName: agentConfig.name });
|
||||
|
||||
this.logger.log(
|
||||
`Agent switched to "${agentConfig.name}" (${agentConfig.id}) for conversation ${conversationId} (M5-003)`,
|
||||
@@ -394,11 +356,11 @@ export class CommandExecutorService {
|
||||
data: { agentId: agentConfig.id, agentName: agentConfig.name, model: agentConfig.model },
|
||||
};
|
||||
} catch (err) {
|
||||
this.logger.error(`Failed to switch agent "${agentName}"`, err);
|
||||
this.logger.error(`Failed to switch agent "${agentName}": ${err}`);
|
||||
return {
|
||||
command: 'agent',
|
||||
success: false,
|
||||
message: 'Failed to switch agent due to an internal error.',
|
||||
message: `Failed to switch agent: ${String(err)}`,
|
||||
conversationId,
|
||||
};
|
||||
}
|
||||
@@ -441,30 +403,22 @@ export class CommandExecutorService {
|
||||
};
|
||||
}
|
||||
const pollToken = crypto.randomUUID();
|
||||
const tokenDigest = await crypto.subtle.digest(
|
||||
'SHA-256',
|
||||
new TextEncoder().encode(pollToken),
|
||||
const key = `mosaic:auth:poll:${pollToken}`;
|
||||
// Store pending state in Valkey (TTL 5 minutes)
|
||||
await this.redis.set(
|
||||
key,
|
||||
JSON.stringify({ status: 'pending', provider: providerName, userId }),
|
||||
'EX',
|
||||
300,
|
||||
);
|
||||
const tokenHash = Array.from(new Uint8Array(tokenDigest), (byte: number): string =>
|
||||
byte.toString(16).padStart(2, '0'),
|
||||
).join('');
|
||||
const key = `mosaic:auth:poll:${tokenHash}`;
|
||||
if (this.redis) {
|
||||
// Persist only a short-lived token digest. The raw token is delivered only by
|
||||
// the authenticated dashboard flow, never in chat output or command metadata.
|
||||
await this.redis.set(
|
||||
key,
|
||||
JSON.stringify({ status: 'pending', provider: providerName, userId }),
|
||||
'EX',
|
||||
300,
|
||||
);
|
||||
}
|
||||
// In production this would construct an OAuth URL
|
||||
const loginUrl = `${process.env['MOSAIC_BASE_URL'] ?? 'http://localhost:3000'}/auth/provider/${providerName}?token=${pollToken}`;
|
||||
return {
|
||||
command: 'provider',
|
||||
success: true,
|
||||
message: `Provider login for ${providerName} is ready. Continue in the authenticated dashboard.`,
|
||||
message: `Open this URL to authenticate with ${providerName}:\n${loginUrl}`,
|
||||
conversationId,
|
||||
data: { provider: providerName },
|
||||
data: { loginUrl, pollToken, provider: providerName },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -546,6 +500,15 @@ export class CommandExecutorService {
|
||||
args: string | null,
|
||||
conversationId: string,
|
||||
): Promise<SlashCommandResultPayload> {
|
||||
if (!this.mcpClient) {
|
||||
return {
|
||||
command: 'mcp',
|
||||
conversationId,
|
||||
success: false,
|
||||
message: 'MCP client service is not available.',
|
||||
};
|
||||
}
|
||||
|
||||
const action = args?.trim().split(/\s+/)[0] ?? 'status';
|
||||
|
||||
switch (action) {
|
||||
@@ -602,12 +565,11 @@ export class CommandExecutorService {
|
||||
message: `MCP server "${serverName}" reconnected successfully.`,
|
||||
};
|
||||
} catch (err) {
|
||||
this.logger.error(`Failed to reconnect MCP server "${serverName}"`, err);
|
||||
return {
|
||||
command: 'mcp',
|
||||
conversationId,
|
||||
success: false,
|
||||
message: `Failed to reconnect MCP server "${serverName}" due to an internal error.`,
|
||||
message: `Failed to reconnect MCP server "${serverName}": ${err instanceof Error ? err.message : String(err)}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,8 +11,6 @@
|
||||
* - Unknown command returns descriptive error
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { CommandsModule } from './commands.module.js';
|
||||
import { McpClientModule } from '../mcp-client/mcp-client.module.js';
|
||||
import { CommandRegistryService } from './command-registry.service.js';
|
||||
import { CommandExecutorService } from './command-executor.service.js';
|
||||
import type { SlashCommandPayload } from '@mosaicstack/types';
|
||||
@@ -49,12 +47,6 @@ const mockBrain = {
|
||||
},
|
||||
};
|
||||
|
||||
const mockMcpClient = {
|
||||
getServerStatuses: vi.fn(() => []),
|
||||
getToolDefinitions: vi.fn(() => []),
|
||||
reconnectServer: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
|
||||
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
function buildRegistry(): CommandRegistryService {
|
||||
@@ -73,7 +65,7 @@ function buildExecutor(registry: CommandRegistryService): CommandExecutorService
|
||||
mockBrain as never,
|
||||
null, // reloadService (optional)
|
||||
null, // chatGateway (optional)
|
||||
mockMcpClient as never,
|
||||
null, // mcpClient (optional)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -161,22 +153,12 @@ describe('CommandRegistryService — integration', () => {
|
||||
}
|
||||
});
|
||||
|
||||
// ─── Module Wiring Tests ──────────────────────────────────────────────────────
|
||||
|
||||
describe('CommandsModule — Nest wiring', () => {
|
||||
it('CommandsModule imports McpClientModule in its Nest metadata', () => {
|
||||
const imports = Reflect.getMetadata('imports', CommandsModule) ?? [];
|
||||
expect(imports).toContain(McpClientModule);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Executor Tests ───────────────────────────────────────────────────────────
|
||||
|
||||
describe('CommandExecutorService — integration', () => {
|
||||
let registry: CommandRegistryService;
|
||||
let executor: CommandExecutorService;
|
||||
const userId = 'user-integ-001';
|
||||
const userScope = { userId, tenantId: userId };
|
||||
const conversationId = 'conv-integ-001';
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -188,26 +170,28 @@ describe('CommandExecutorService — integration', () => {
|
||||
// Unknown command returns error
|
||||
it('unknown command returns success:false with descriptive message', async () => {
|
||||
const payload: SlashCommandPayload = { command: 'nonexistent', conversationId };
|
||||
const result = await executor.execute(payload, userScope);
|
||||
const result = await executor.execute(payload, userId);
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.message).toContain('nonexistent');
|
||||
expect(result.command).toBe('nonexistent');
|
||||
});
|
||||
|
||||
it('/gc refuses an unaudited global sweep', async () => {
|
||||
// /gc handler calls SessionGCService.sweepOrphans (admin-only, no userId arg)
|
||||
it('/gc calls SessionGCService.sweepOrphans without arguments', async () => {
|
||||
const payload: SlashCommandPayload = { command: 'gc', conversationId };
|
||||
const result = await executor.execute(payload, userScope);
|
||||
expect(mockSessionGC.sweepOrphans).not.toHaveBeenCalled();
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.message).toContain('disabled pending an authorized retention job');
|
||||
const result = await executor.execute(payload, userId);
|
||||
expect(mockSessionGC.sweepOrphans).toHaveBeenCalledWith();
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.message).toContain('GC sweep complete');
|
||||
expect(result.message).toContain('3 orphaned sessions');
|
||||
});
|
||||
|
||||
// /system with args calls SystemOverrideService.set
|
||||
it('/system with text calls SystemOverrideService.set', async () => {
|
||||
const override = 'You are a helpful assistant.';
|
||||
const payload: SlashCommandPayload = { command: 'system', args: override, conversationId };
|
||||
const result = await executor.execute(payload, userScope);
|
||||
expect(mockSystemOverride.set).toHaveBeenCalledWith(conversationId, override, userScope);
|
||||
const result = await executor.execute(payload, userId);
|
||||
expect(mockSystemOverride.set).toHaveBeenCalledWith(conversationId, override);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.message).toContain('override set');
|
||||
});
|
||||
@@ -215,8 +199,8 @@ describe('CommandExecutorService — integration', () => {
|
||||
// /system with no args clears the override
|
||||
it('/system with no args calls SystemOverrideService.clear', async () => {
|
||||
const payload: SlashCommandPayload = { command: 'system', conversationId };
|
||||
const result = await executor.execute(payload, userScope);
|
||||
expect(mockSystemOverride.clear).toHaveBeenCalledWith(conversationId, userScope);
|
||||
const result = await executor.execute(payload, userId);
|
||||
expect(mockSystemOverride.clear).toHaveBeenCalledWith(conversationId);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.message).toContain('cleared');
|
||||
});
|
||||
@@ -228,7 +212,7 @@ describe('CommandExecutorService — integration', () => {
|
||||
args: 'claude-3-opus',
|
||||
conversationId,
|
||||
};
|
||||
const result = await executor.execute(payload, userScope);
|
||||
const result = await executor.execute(payload, userId);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.command).toBe('model');
|
||||
expect(result.message).toContain('claude-3-opus');
|
||||
@@ -237,7 +221,7 @@ describe('CommandExecutorService — integration', () => {
|
||||
// /thinking with valid level returns success
|
||||
it('/thinking with valid level returns success', async () => {
|
||||
const payload: SlashCommandPayload = { command: 'thinking', args: 'high', conversationId };
|
||||
const result = await executor.execute(payload, userScope);
|
||||
const result = await executor.execute(payload, userId);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.message).toContain('high');
|
||||
});
|
||||
@@ -245,7 +229,7 @@ describe('CommandExecutorService — integration', () => {
|
||||
// /thinking with invalid level returns usage message
|
||||
it('/thinking with invalid level returns usage message', async () => {
|
||||
const payload: SlashCommandPayload = { command: 'thinking', args: 'invalid', conversationId };
|
||||
const result = await executor.execute(payload, userScope);
|
||||
const result = await executor.execute(payload, userId);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.message).toContain('Usage:');
|
||||
});
|
||||
@@ -253,7 +237,7 @@ describe('CommandExecutorService — integration', () => {
|
||||
// /new command returns success
|
||||
it('/new returns success', async () => {
|
||||
const payload: SlashCommandPayload = { command: 'new', conversationId };
|
||||
const result = await executor.execute(payload, userScope);
|
||||
const result = await executor.execute(payload, userId);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.command).toBe('new');
|
||||
});
|
||||
@@ -261,7 +245,7 @@ describe('CommandExecutorService — integration', () => {
|
||||
// /reload without reloadService returns failure
|
||||
it('/reload without ReloadService returns failure', async () => {
|
||||
const payload: SlashCommandPayload = { command: 'reload', conversationId };
|
||||
const result = await executor.execute(payload, userScope);
|
||||
const result = await executor.execute(payload, userId);
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.message).toContain('ReloadService');
|
||||
});
|
||||
@@ -271,19 +255,9 @@ describe('CommandExecutorService — integration', () => {
|
||||
for (const cmd of stubCommands) {
|
||||
it(`/${cmd} returns success (stub)`, async () => {
|
||||
const payload: SlashCommandPayload = { command: cmd, conversationId };
|
||||
const result = await executor.execute(payload, userScope);
|
||||
const result = await executor.execute(payload, userId);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.command).toBe(cmd);
|
||||
});
|
||||
}
|
||||
|
||||
// /mcp status reaches the required McpClientService and never reports it unavailable
|
||||
it('/mcp status calls the wired McpClientService and reports the no-servers message', async () => {
|
||||
const payload: SlashCommandPayload = { command: 'mcp', conversationId };
|
||||
const result = await executor.execute(payload, userScope);
|
||||
expect(mockMcpClient.getServerStatuses).toHaveBeenCalledOnce();
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.message).toContain('No MCP servers configured.');
|
||||
expect(result.message).not.toBe('MCP client service is not available.');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,62 +1,37 @@
|
||||
import { forwardRef, Inject, Module, Optional, type OnApplicationShutdown } from '@nestjs/common';
|
||||
import { forwardRef, Inject, Module, type OnApplicationShutdown } from '@nestjs/common';
|
||||
import { createQueue, type QueueHandle } from '@mosaicstack/queue';
|
||||
import type { MosaicConfig } from '@mosaicstack/config';
|
||||
import { MOSAIC_CONFIG } from '../config/config.module.js';
|
||||
import { ChatModule } from '../chat/chat.module.js';
|
||||
import { GCModule } from '../gc/gc.module.js';
|
||||
import { McpClientModule } from '../mcp-client/mcp-client.module.js';
|
||||
import { ReloadModule } from '../reload/reload.module.js';
|
||||
import { CommandAuthorizationService } from './command-authorization.service.js';
|
||||
import { CommandExecutorService } from './command-executor.service.js';
|
||||
import { CommandRegistryService } from './command-registry.service.js';
|
||||
import { CommandRuntimeApprovalVerifier } from './runtime-approval-verifier.js';
|
||||
import { COMMANDS_REDIS } from './commands.tokens.js';
|
||||
|
||||
const COMMANDS_QUEUE_HANDLE = 'COMMANDS_QUEUE_HANDLE';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
GCModule,
|
||||
McpClientModule,
|
||||
forwardRef(() => ReloadModule),
|
||||
forwardRef(() => ChatModule),
|
||||
],
|
||||
imports: [GCModule, forwardRef(() => ReloadModule), forwardRef(() => ChatModule)],
|
||||
providers: [
|
||||
{
|
||||
provide: COMMANDS_QUEUE_HANDLE,
|
||||
useFactory: (config: MosaicConfig | null): QueueHandle | null => {
|
||||
// On Local tier there is no Redis — skip the ioredis connection.
|
||||
// CommandExecutorService falls back to no-cache for /provider login on local.
|
||||
if (config?.queue?.type === 'local') return null;
|
||||
useFactory: (): QueueHandle => {
|
||||
return createQueue();
|
||||
},
|
||||
inject: [MOSAIC_CONFIG],
|
||||
},
|
||||
{
|
||||
provide: COMMANDS_REDIS,
|
||||
useFactory: (handle: QueueHandle | null) => handle?.redis ?? null,
|
||||
useFactory: (handle: QueueHandle) => handle.redis,
|
||||
inject: [COMMANDS_QUEUE_HANDLE],
|
||||
},
|
||||
CommandRegistryService,
|
||||
CommandAuthorizationService,
|
||||
CommandRuntimeApprovalVerifier,
|
||||
CommandExecutorService,
|
||||
],
|
||||
exports: [
|
||||
CommandRegistryService,
|
||||
CommandAuthorizationService,
|
||||
CommandRuntimeApprovalVerifier,
|
||||
CommandExecutorService,
|
||||
],
|
||||
exports: [CommandRegistryService, CommandExecutorService],
|
||||
})
|
||||
export class CommandsModule implements OnApplicationShutdown {
|
||||
constructor(
|
||||
@Optional()
|
||||
@Inject(COMMANDS_QUEUE_HANDLE)
|
||||
private readonly handle: QueueHandle | null,
|
||||
) {}
|
||||
constructor(@Inject(COMMANDS_QUEUE_HANDLE) private readonly handle: QueueHandle) {}
|
||||
|
||||
async onApplicationShutdown(): Promise<void> {
|
||||
await this.handle?.close().catch(() => {});
|
||||
await this.handle.close().catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import type {
|
||||
RuntimeApprovalVerifier,
|
||||
RuntimeTerminationAction,
|
||||
} from '../agent/runtime-provider-registry.service.js';
|
||||
import { CommandAuthorizationService } from './command-authorization.service.js';
|
||||
|
||||
/**
|
||||
* Adapter from the provider registry's exact termination action to the shared,
|
||||
* Redis-backed `interaction:command-approval:*` store. It has no separate approval
|
||||
* persistence or replay semantics.
|
||||
*/
|
||||
@Injectable()
|
||||
export class CommandRuntimeApprovalVerifier implements RuntimeApprovalVerifier {
|
||||
constructor(
|
||||
@Inject(CommandAuthorizationService)
|
||||
private readonly authorization: CommandAuthorizationService,
|
||||
) {}
|
||||
|
||||
async consume(approvalRef: string, action: RuntimeTerminationAction): Promise<boolean> {
|
||||
return this.authorization.consumeRuntimeTerminationApproval(approvalRef, action);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { loadConfig, type MosaicConfig } from '@mosaicstack/config';
|
||||
import { resolveGatewayConfigPath } from '../env.js';
|
||||
|
||||
export const MOSAIC_CONFIG = 'MOSAIC_CONFIG';
|
||||
|
||||
@@ -9,7 +8,7 @@ export const MOSAIC_CONFIG = 'MOSAIC_CONFIG';
|
||||
providers: [
|
||||
{
|
||||
provide: MOSAIC_CONFIG,
|
||||
useFactory: (): MosaicConfig => loadConfig(resolveGatewayConfigPath()),
|
||||
useFactory: (): MosaicConfig => loadConfig(),
|
||||
},
|
||||
],
|
||||
exports: [MOSAIC_CONFIG],
|
||||
|
||||
@@ -1,116 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { ChatRuntimeMode } from '../chat/chat-runtime.js';
|
||||
import { ConversationsController } from './conversations.controller.js';
|
||||
|
||||
/**
|
||||
* Task 5 harness fence for the conversations REST write path.
|
||||
*
|
||||
* Under `pi-rpc` the durable/harness conversation path (Task 15) owns message persistence, so the
|
||||
* legacy direct-repository write via `POST /api/conversations/:id/messages` must be refused with a
|
||||
* fixed typed `runtime_unsupported` BEFORE the repository is touched — never a duplicate write.
|
||||
* Under `legacy` the endpoint keeps its current behaviour and writes through `brain.conversations`.
|
||||
*
|
||||
* Item 3 (single runtime-mode source of truth): the mode is the router's ONE init-time resolution,
|
||||
* injected into the controller and read as `router.runtimeMode`. It is NOT re-derived from
|
||||
* `process.env` at request time. The two "env is flipped after construction" tests below are the
|
||||
* load-bearing guard: they pass only because the controller reads the fixed injected mode, and turn
|
||||
* RED the instant the fence is reverted to `resolveChatRuntimeMode(process.env)`.
|
||||
*/
|
||||
const CONVERSATION_ID = '22222222-2222-4222-8222-222222222222';
|
||||
const USER = { id: 'user-1' };
|
||||
|
||||
function sendMessageDto() {
|
||||
return {
|
||||
role: 'user' as const,
|
||||
content: 'hello from the legacy REST write path',
|
||||
metadata: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function brainWithMessageSpy() {
|
||||
const addMessage = vi.fn().mockResolvedValue({
|
||||
id: 'message-1',
|
||||
conversationId: CONVERSATION_ID,
|
||||
role: 'user',
|
||||
content: 'hello from the legacy REST write path',
|
||||
});
|
||||
return {
|
||||
brain: { conversations: { addMessage } } as never,
|
||||
addMessage,
|
||||
};
|
||||
}
|
||||
|
||||
/** The controller only needs the router's immutable `runtimeMode`; supply exactly that. */
|
||||
function routerFixedTo(mode: ChatRuntimeMode) {
|
||||
return { runtimeMode: mode };
|
||||
}
|
||||
|
||||
let priorMode: string | undefined;
|
||||
|
||||
describe('conversations REST write path — Task 5 harness fence', () => {
|
||||
beforeEach(() => {
|
||||
priorMode = process.env['CHAT_HARNESS_RUNTIME'];
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (priorMode === undefined) delete process.env['CHAT_HARNESS_RUNTIME'];
|
||||
else process.env['CHAT_HARNESS_RUNTIME'] = priorMode;
|
||||
});
|
||||
|
||||
it('refuses the legacy repository write when the router resolved pi-rpc, before any write', async () => {
|
||||
const { brain, addMessage } = brainWithMessageSpy();
|
||||
const controller = new ConversationsController(brain, routerFixedTo('pi-rpc'));
|
||||
|
||||
await expect(
|
||||
controller.addMessage(CONVERSATION_ID, sendMessageDto(), USER),
|
||||
).rejects.toMatchObject({ code: 'runtime_unsupported' });
|
||||
|
||||
// Load-bearing: the durable/harness path owns pi-rpc persistence — the legacy repo must not be
|
||||
// written, so no duplicate message can be produced.
|
||||
expect(addMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('writes through the repository when the router resolved legacy (GREEN control)', async () => {
|
||||
const { brain, addMessage } = brainWithMessageSpy();
|
||||
const controller = new ConversationsController(brain, routerFixedTo('legacy'));
|
||||
|
||||
const result = await controller.addMessage(CONVERSATION_ID, sendMessageDto(), USER);
|
||||
|
||||
expect(addMessage).toHaveBeenCalledWith(
|
||||
{
|
||||
conversationId: CONVERSATION_ID,
|
||||
role: 'user',
|
||||
content: 'hello from the legacy REST write path',
|
||||
metadata: undefined,
|
||||
},
|
||||
USER.id,
|
||||
);
|
||||
expect(result).toMatchObject({ id: 'message-1', conversationId: CONVERSATION_ID });
|
||||
});
|
||||
|
||||
it('keeps refusing under a pi-rpc router even when CHAT_HARNESS_RUNTIME is flipped to legacy after startup', async () => {
|
||||
// The runtime mode is fixed at module init. A later env mutation must not reopen the fence:
|
||||
// a request-time `resolveChatRuntimeMode(process.env)` read would see `legacy` and wrongly write.
|
||||
process.env['CHAT_HARNESS_RUNTIME'] = 'legacy';
|
||||
const { brain, addMessage } = brainWithMessageSpy();
|
||||
const controller = new ConversationsController(brain, routerFixedTo('pi-rpc'));
|
||||
|
||||
await expect(
|
||||
controller.addMessage(CONVERSATION_ID, sendMessageDto(), USER),
|
||||
).rejects.toMatchObject({ code: 'runtime_unsupported' });
|
||||
|
||||
expect(addMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps writing under a legacy router even when CHAT_HARNESS_RUNTIME is flipped to pi-rpc after startup', async () => {
|
||||
// Symmetric guard: a legacy-resolved router must keep writing regardless of the live env, so a
|
||||
// request-time env read of `pi-rpc` cannot spuriously refuse a legitimate legacy write.
|
||||
process.env['CHAT_HARNESS_RUNTIME'] = 'pi-rpc';
|
||||
const { brain, addMessage } = brainWithMessageSpy();
|
||||
const controller = new ConversationsController(brain, routerFixedTo('legacy'));
|
||||
|
||||
await controller.addMessage(CONVERSATION_ID, sendMessageDto(), USER);
|
||||
|
||||
expect(addMessage).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
ForbiddenException,
|
||||
Get,
|
||||
HttpCode,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Inject,
|
||||
NotFoundException,
|
||||
@@ -20,7 +19,6 @@ import type { Brain } from '@mosaicstack/brain';
|
||||
import { BRAIN } from '../brain/brain.tokens.js';
|
||||
import { AuthGuard } from '../auth/auth.guard.js';
|
||||
import { CurrentUser } from '../auth/current-user.decorator.js';
|
||||
import { ChatRuntimeRouter } from '../chat/chat-runtime-router.js';
|
||||
import {
|
||||
CreateConversationDto,
|
||||
UpdateConversationDto,
|
||||
@@ -28,41 +26,10 @@ import {
|
||||
SearchMessagesDto,
|
||||
} from './conversations.dto.js';
|
||||
|
||||
/**
|
||||
* Under `pi-rpc` the durable/harness conversation path (Task 15) owns message persistence, so the
|
||||
* legacy direct-repository write must fail closed with a fixed typed `runtime_unsupported` before
|
||||
* the repository is touched — never a duplicate write. The `code` field is exposed at the top level
|
||||
* so callers can discriminate the refusal while the 503 status carries the browser-safe surface.
|
||||
*/
|
||||
class HarnessRuntimeWriteUnsupportedException extends HttpException {
|
||||
readonly code = 'runtime_unsupported' as const;
|
||||
|
||||
constructor() {
|
||||
super(
|
||||
{
|
||||
code: 'runtime_unsupported',
|
||||
message:
|
||||
'Conversation message writes are handled by the harness runtime on this deployment.',
|
||||
},
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@Controller('api/conversations')
|
||||
@UseGuards(AuthGuard)
|
||||
export class ConversationsController {
|
||||
/**
|
||||
* `router` supplies the ONE immutable runtime mode resolved at module init (Task 5, item 3).
|
||||
* The pre-write fence reads `router.runtimeMode`, never `resolveChatRuntimeMode(process.env)` at
|
||||
* request time — a single source of truth, so the controller cannot disagree with the router
|
||||
* about the live runtime if the environment is mutated after startup. Narrowed to `runtimeMode`
|
||||
* so this class depends on nothing else the router exposes.
|
||||
*/
|
||||
constructor(
|
||||
@Inject(BRAIN) private readonly brain: Brain,
|
||||
@Inject(ChatRuntimeRouter) private readonly router: Pick<ChatRuntimeRouter, 'runtimeMode'>,
|
||||
) {}
|
||||
constructor(@Inject(BRAIN) private readonly brain: Brain) {}
|
||||
|
||||
@Get()
|
||||
async list(@CurrentUser() user: { id: string }) {
|
||||
@@ -127,13 +94,6 @@ export class ConversationsController {
|
||||
@Body() dto: SendMessageDto,
|
||||
@CurrentUser() user: { id: string },
|
||||
) {
|
||||
// Fail the legacy repository write closed under pi-rpc BEFORE touching the repository — the
|
||||
// harness path owns persistence there, so a direct write would duplicate the message. The mode
|
||||
// comes from the router's init-time resolution, not a request-time env read.
|
||||
if (this.router.runtimeMode === 'pi-rpc') {
|
||||
throw new HarnessRuntimeWriteUnsupportedException();
|
||||
}
|
||||
|
||||
const message = await this.brain.conversations.addMessage(
|
||||
{
|
||||
conversationId: id,
|
||||
|
||||
@@ -1,14 +1,7 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ChatModule } from '../chat/chat.module.js';
|
||||
import { ConversationsController } from './conversations.controller.js';
|
||||
|
||||
/**
|
||||
* Imports {@link ChatModule} solely to inject its exported {@link ChatRuntimeRouter} into
|
||||
* {@link ConversationsController}, so the REST write fence reads the same init-time runtime mode the
|
||||
* router resolved — one source of truth, no duplicate provider, no global token, no AppModule edit.
|
||||
*/
|
||||
@Module({
|
||||
imports: [ChatModule],
|
||||
controllers: [ConversationsController],
|
||||
})
|
||||
export class ConversationsModule {}
|
||||
|
||||
@@ -1,32 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { InMemoryInteractionCoordinationPort } from '@mosaicstack/coord';
|
||||
import { CoordService } from './coord.service.js';
|
||||
import { CoordController } from './coord.controller.js';
|
||||
import { InteractionCoordinationController } from './interaction-coordination.controller.js';
|
||||
import {
|
||||
COORDINATION_CONFIG,
|
||||
COORDINATION_PORT,
|
||||
InteractionCoordinationService,
|
||||
} from './interaction-coordination.service.js';
|
||||
|
||||
@Module({
|
||||
providers: [
|
||||
CoordService,
|
||||
{
|
||||
provide: COORDINATION_PORT,
|
||||
useFactory: (): InMemoryInteractionCoordinationPort =>
|
||||
new InMemoryInteractionCoordinationPort(),
|
||||
},
|
||||
{
|
||||
provide: COORDINATION_CONFIG,
|
||||
useFactory: () => ({
|
||||
interactionAgentId: process.env['MOSAIC_AGENT_NAME'],
|
||||
orchestrationAgentId: process.env['MOSAIC_ORCHESTRATOR_AGENT_NAME'],
|
||||
}),
|
||||
},
|
||||
InteractionCoordinationService,
|
||||
],
|
||||
controllers: [CoordController, InteractionCoordinationController],
|
||||
exports: [CoordService, InteractionCoordinationService],
|
||||
providers: [CoordService],
|
||||
controllers: [CoordController],
|
||||
exports: [CoordService],
|
||||
})
|
||||
export class CoordModule {}
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
const PATH_METADATA = 'path';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { InteractionCoordinationController } from './interaction-coordination.controller.js';
|
||||
|
||||
const user = { id: 'operator-1', tenantId: 'tenant-a' };
|
||||
|
||||
describe('InteractionCoordinationController', () => {
|
||||
it('exposes the neutral canonical route and Mos compatibility alias over identical handlers', () => {
|
||||
expect(Reflect.getMetadata(PATH_METADATA, InteractionCoordinationController)).toEqual([
|
||||
'api/coord/interaction',
|
||||
'api/coord/mos',
|
||||
]);
|
||||
expect(InteractionCoordinationController.prototype.handoff).toBeTypeOf('function');
|
||||
expect(InteractionCoordinationController.prototype.observe).toBeTypeOf('function');
|
||||
expect(InteractionCoordinationController.prototype.result).toBeTypeOf('function');
|
||||
});
|
||||
|
||||
it('derives actor and tenant from the authenticated user rather than handoff input', async () => {
|
||||
const coordination = {
|
||||
handoff: vi.fn(async () => ({ handoffId: 'handoff-1' })),
|
||||
observe: vi.fn(),
|
||||
result: vi.fn(),
|
||||
};
|
||||
const controller = new InteractionCoordinationController(coordination as never);
|
||||
|
||||
await controller.handoff({ idempotencyKey: 'request-1', summary: 'Implement' }, user, 'corr-1');
|
||||
|
||||
expect(coordination.handoff).toHaveBeenCalledWith(
|
||||
{ idempotencyKey: 'request-1', summary: 'Implement' },
|
||||
expect.objectContaining({
|
||||
actorScope: { userId: 'operator-1', tenantId: 'tenant-a' },
|
||||
channelId: 'cli',
|
||||
correlationId: 'corr-1',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('requires a correlation header before invoking the coordination service', async () => {
|
||||
const coordination = { handoff: vi.fn(), observe: vi.fn(), result: vi.fn() };
|
||||
const controller = new InteractionCoordinationController(coordination as never);
|
||||
|
||||
await expect(
|
||||
controller.handoff({ idempotencyKey: 'request-1', summary: 'Implement' }, user, undefined),
|
||||
).rejects.toThrow('X-Correlation-Id is required');
|
||||
expect(coordination.handoff).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,75 +0,0 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
ForbiddenException,
|
||||
Get,
|
||||
Headers,
|
||||
Inject,
|
||||
Param,
|
||||
Post,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { AuthGuard } from '../auth/auth.guard.js';
|
||||
import { CurrentUser } from '../auth/current-user.decorator.js';
|
||||
import { scopeFromUser, type AuthenticatedUserLike } from '../auth/session-scope.js';
|
||||
import type { RuntimeProviderRequestContext } from '../agent/runtime-provider-registry.service.js';
|
||||
import type {
|
||||
InteractionCoordinationObservationDto,
|
||||
InteractionCoordinationResponseDto,
|
||||
InteractionCoordinationResultDto,
|
||||
CreateHandoffDto,
|
||||
} from './interaction-coordination.dto.js';
|
||||
import { InteractionCoordinationService } from './interaction-coordination.service.js';
|
||||
|
||||
/** Authenticated interaction-plane boundary for the handoff/observe/result-only interaction coordination contract. */
|
||||
/** `api/coord/interaction` is canonical; the Mos path remains a compatibility alias. */
|
||||
@Controller(['api/coord/interaction', 'api/coord/mos'])
|
||||
@UseGuards(AuthGuard)
|
||||
export class InteractionCoordinationController {
|
||||
constructor(
|
||||
@Inject(InteractionCoordinationService)
|
||||
private readonly coordination: InteractionCoordinationService,
|
||||
) {}
|
||||
|
||||
@Post('handoff')
|
||||
async handoff(
|
||||
@Body() request: CreateHandoffDto,
|
||||
@CurrentUser() user: AuthenticatedUserLike,
|
||||
@Headers('x-correlation-id') correlationId?: string,
|
||||
): Promise<InteractionCoordinationResponseDto> {
|
||||
return { receipt: await this.coordination.handoff(request, this.context(user, correlationId)) };
|
||||
}
|
||||
|
||||
@Get(':handoffId/observe')
|
||||
async observe(
|
||||
@Param('handoffId') handoffId: string,
|
||||
@CurrentUser() user: AuthenticatedUserLike,
|
||||
@Headers('x-correlation-id') correlationId?: string,
|
||||
): Promise<InteractionCoordinationObservationDto> {
|
||||
return {
|
||||
observation: await this.coordination.observe(handoffId, this.context(user, correlationId)),
|
||||
};
|
||||
}
|
||||
|
||||
@Get(':handoffId/result')
|
||||
async result(
|
||||
@Param('handoffId') handoffId: string,
|
||||
@CurrentUser() user: AuthenticatedUserLike,
|
||||
@Headers('x-correlation-id') correlationId?: string,
|
||||
): Promise<InteractionCoordinationResultDto> {
|
||||
return { result: await this.coordination.result(handoffId, this.context(user, correlationId)) };
|
||||
}
|
||||
|
||||
private context(
|
||||
user: AuthenticatedUserLike,
|
||||
correlationId?: string,
|
||||
): RuntimeProviderRequestContext {
|
||||
const requestCorrelationId = correlationId?.trim();
|
||||
if (!requestCorrelationId) throw new ForbiddenException('X-Correlation-Id is required');
|
||||
return {
|
||||
actorScope: scopeFromUser(user),
|
||||
channelId: 'cli',
|
||||
correlationId: requestCorrelationId,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
import 'reflect-metadata';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { CoordModule } from './coord.module.js';
|
||||
import { InteractionCoordinationService } from './interaction-coordination.service.js';
|
||||
import { AuthGuard } from '../auth/auth.guard.js';
|
||||
|
||||
describe('CoordModule DI (compiled-metadata boot)', () => {
|
||||
it('resolves InteractionCoordinationService through Nest DI', async () => {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [CoordModule] })
|
||||
.overrideGuard(AuthGuard)
|
||||
.useValue({ canActivate: (): boolean => true })
|
||||
.compile();
|
||||
expect(moduleRef.get(InteractionCoordinationService)).toBeInstanceOf(
|
||||
InteractionCoordinationService,
|
||||
);
|
||||
await moduleRef.close();
|
||||
});
|
||||
});
|
||||
@@ -1,25 +0,0 @@
|
||||
import type {
|
||||
CoordinationObservation,
|
||||
CoordinationResult,
|
||||
HandoffReceipt,
|
||||
} from '@mosaicstack/coord';
|
||||
|
||||
/** Input accepted at the gateway coordination boundary. Agent identity is not caller-controlled. */
|
||||
export interface CreateHandoffDto {
|
||||
idempotencyKey: string;
|
||||
summary: string;
|
||||
context?: string;
|
||||
missionId?: string;
|
||||
}
|
||||
|
||||
export interface InteractionCoordinationResponseDto {
|
||||
receipt: HandoffReceipt;
|
||||
}
|
||||
|
||||
export interface InteractionCoordinationObservationDto {
|
||||
observation: CoordinationObservation;
|
||||
}
|
||||
|
||||
export interface InteractionCoordinationResultDto {
|
||||
result: CoordinationResult;
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
import 'reflect-metadata';
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { FastifyAdapter, type NestFastifyApplication } from '@nestjs/platform-fastify';
|
||||
import { AUTH } from '../auth/auth.tokens.js';
|
||||
import { AuthGuard } from '../auth/auth.guard.js';
|
||||
import { InteractionCoordinationController } from './interaction-coordination.controller.js';
|
||||
import { InteractionCoordinationService } from './interaction-coordination.service.js';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [
|
||||
{
|
||||
provide: AUTH,
|
||||
useValue: {
|
||||
api: {
|
||||
getSession: vi.fn(async ({ headers }: { headers: Headers }) =>
|
||||
headers.get('cookie') === 'session=trusted'
|
||||
? { user: { id: 'operator-1', tenantId: 'tenant-1' }, session: { id: 'session-1' } }
|
||||
: null,
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
AuthGuard,
|
||||
],
|
||||
exports: [AUTH, AuthGuard],
|
||||
})
|
||||
class AuthenticatedRequestModule {}
|
||||
|
||||
describe('InteractionCoordinationController route aliases', (): void => {
|
||||
let app: NestFastifyApplication | undefined;
|
||||
const coordination = {
|
||||
handoff: vi.fn(async () => ({ handoffId: 'handoff-1' })),
|
||||
observe: vi.fn(async () => ({ status: 'running' })),
|
||||
result: vi.fn(async () => ({ status: 'completed' })),
|
||||
};
|
||||
|
||||
beforeAll(async (): Promise<void> => {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [AuthenticatedRequestModule],
|
||||
controllers: [InteractionCoordinationController],
|
||||
providers: [{ provide: InteractionCoordinationService, useValue: coordination }],
|
||||
}).compile();
|
||||
app = moduleRef.createNestApplication<NestFastifyApplication>(new FastifyAdapter());
|
||||
await app.init();
|
||||
await app.getHttpAdapter().getInstance().ready();
|
||||
});
|
||||
afterAll(async (): Promise<void> => app?.close());
|
||||
|
||||
it('routes handoff, observe, and result through the same AuthGuard-protected service for both prefixes', async (): Promise<void> => {
|
||||
if (!app) throw new Error('test app was not initialized');
|
||||
for (const prefix of ['/api/coord/interaction', '/api/coord/mos']) {
|
||||
const headers = { cookie: 'session=trusted', 'x-correlation-id': `corr-${prefix}` };
|
||||
expect(
|
||||
(
|
||||
await app.inject({
|
||||
method: 'POST',
|
||||
url: `${prefix}/handoff`,
|
||||
headers,
|
||||
payload: { idempotencyKey: `key-${prefix}`, summary: 'handoff' },
|
||||
})
|
||||
).statusCode,
|
||||
).toBe(201);
|
||||
expect(
|
||||
(await app.inject({ method: 'GET', url: `${prefix}/handoff-1/observe`, headers }))
|
||||
.statusCode,
|
||||
).toBe(200);
|
||||
expect(
|
||||
(await app.inject({ method: 'GET', url: `${prefix}/handoff-1/result`, headers }))
|
||||
.statusCode,
|
||||
).toBe(200);
|
||||
}
|
||||
expect(coordination.handoff).toHaveBeenCalledTimes(2);
|
||||
expect(coordination.observe).toHaveBeenCalledTimes(2);
|
||||
expect(coordination.result).toHaveBeenCalledTimes(2);
|
||||
expect(
|
||||
(
|
||||
await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/coord/interaction/handoff',
|
||||
payload: { idempotencyKey: 'denied', summary: 'x' },
|
||||
})
|
||||
).statusCode,
|
||||
).toBe(401);
|
||||
});
|
||||
});
|
||||
@@ -1,217 +0,0 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
InMemoryInteractionCoordinationPort,
|
||||
type InteractionCoordinationPort,
|
||||
type Handoff,
|
||||
} from '@mosaicstack/coord';
|
||||
import type { RuntimeProviderRequestContext } from '../agent/runtime-provider-registry.service.js';
|
||||
import {
|
||||
InteractionCoordinationService,
|
||||
type InteractionCoordinationConfig,
|
||||
type InteractionCoordinationGatewayError,
|
||||
} from './interaction-coordination.service.js';
|
||||
|
||||
const context: RuntimeProviderRequestContext = {
|
||||
actorScope: { userId: 'operator-1', tenantId: 'tenant-a' },
|
||||
channelId: 'cli',
|
||||
correlationId: 'corr-1',
|
||||
};
|
||||
|
||||
const config: InteractionCoordinationConfig = {
|
||||
interactionAgentId: 'Nova',
|
||||
orchestrationAgentId: 'Conductor',
|
||||
};
|
||||
|
||||
function service(
|
||||
port: InteractionCoordinationPort = new InMemoryInteractionCoordinationPort(),
|
||||
options: {
|
||||
config?: InteractionCoordinationConfig;
|
||||
handoffIdFactory?: () => string;
|
||||
} = {},
|
||||
): InteractionCoordinationService {
|
||||
return new InteractionCoordinationService(
|
||||
port,
|
||||
options.config ?? config,
|
||||
options.handoffIdFactory ?? (() => 'handoff-1'),
|
||||
);
|
||||
}
|
||||
|
||||
describe('InteractionCoordinationService authority boundary', (): void => {
|
||||
it('derives identity and actor/tenant scope server-side, then round-trips the native adapter', async (): Promise<void> => {
|
||||
const adapter = new InMemoryInteractionCoordinationPort();
|
||||
const coordination = service(adapter);
|
||||
|
||||
await expect(
|
||||
coordination.handoff(
|
||||
{ idempotencyKey: 'request-1', summary: 'Implement the requested feature' },
|
||||
context,
|
||||
),
|
||||
).resolves.toEqual({
|
||||
handoffId: 'handoff-1',
|
||||
targetAgentId: 'Conductor',
|
||||
status: 'queued',
|
||||
correlationId: 'corr-1',
|
||||
});
|
||||
|
||||
adapter.recordActivity('handoff-1', 'running', 'Orchestrator accepted the request');
|
||||
adapter.recordResult('handoff-1', 'completed', 'Merged by orchestrator');
|
||||
|
||||
const followUpContext = { ...context, correlationId: 'corr-2' };
|
||||
await expect(coordination.observe('handoff-1', followUpContext)).resolves.toMatchObject({
|
||||
targetAgentId: 'Conductor',
|
||||
status: 'completed',
|
||||
});
|
||||
await expect(coordination.result('handoff-1', followUpContext)).resolves.toMatchObject({
|
||||
targetAgentId: 'Conductor',
|
||||
status: 'completed',
|
||||
summary: 'Merged by orchestrator',
|
||||
});
|
||||
});
|
||||
|
||||
it('fails closed without calling a port when the interaction requester is unconfigured', async (): Promise<void> => {
|
||||
const adapter = new InMemoryInteractionCoordinationPort();
|
||||
const handoff = vi.spyOn(adapter, 'handoff');
|
||||
const coordination = service(adapter, {
|
||||
config: { interactionAgentId: '', orchestrationAgentId: 'Conductor' },
|
||||
});
|
||||
|
||||
await expect(
|
||||
coordination.handoff(
|
||||
{ idempotencyKey: 'request-1', summary: 'Implement the requested feature' },
|
||||
context,
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
code: 'unconfigured_requester',
|
||||
} satisfies Partial<InteractionCoordinationGatewayError>);
|
||||
expect(handoff).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects self-delegation configuration before delivering work', async (): Promise<void> => {
|
||||
const adapter = new InMemoryInteractionCoordinationPort();
|
||||
const handoff = vi.spyOn(adapter, 'handoff');
|
||||
const coordination = service(adapter, {
|
||||
config: { interactionAgentId: 'Nova', orchestrationAgentId: 'Nova' },
|
||||
});
|
||||
|
||||
await expect(
|
||||
coordination.handoff(
|
||||
{ idempotencyKey: 'request-1', summary: 'Implement the requested feature' },
|
||||
context,
|
||||
),
|
||||
).rejects.toThrow('Interaction and orchestration identities must differ');
|
||||
expect(handoff).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('denies cross-tenant observe and result before calling the adapter', async (): Promise<void> => {
|
||||
const adapter = new InMemoryInteractionCoordinationPort();
|
||||
const observe = vi.spyOn(adapter, 'observe');
|
||||
const result = vi.spyOn(adapter, 'result');
|
||||
const coordination = service(adapter);
|
||||
await coordination.handoff(
|
||||
{ idempotencyKey: 'request-1', summary: 'Implement the requested feature' },
|
||||
context,
|
||||
);
|
||||
|
||||
const otherTenant = {
|
||||
...context,
|
||||
actorScope: { ...context.actorScope, tenantId: 'tenant-b' },
|
||||
};
|
||||
await expect(coordination.observe('handoff-1', otherTenant)).rejects.toMatchObject({
|
||||
code: 'cross_tenant_forbidden',
|
||||
} satisfies Partial<InteractionCoordinationGatewayError>);
|
||||
await expect(coordination.result('handoff-1', otherTenant)).rejects.toMatchObject({
|
||||
code: 'cross_tenant_forbidden',
|
||||
} satisfies Partial<InteractionCoordinationGatewayError>);
|
||||
expect(observe).not.toHaveBeenCalled();
|
||||
expect(result).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('scopes idempotency by actor and joins concurrent retries without duplicate delivery', async (): Promise<void> => {
|
||||
let handoffSequence = 0;
|
||||
let release: (() => void) | undefined;
|
||||
const delivered = new Promise<void>((resolve: () => void): void => {
|
||||
release = resolve;
|
||||
});
|
||||
const adapter: InteractionCoordinationPort = {
|
||||
handoff: vi.fn(async (handoff: Handoff) => {
|
||||
await delivered;
|
||||
return {
|
||||
handoffId: handoff.handoffId,
|
||||
targetAgentId: handoff.targetAgentId,
|
||||
status: 'queued' as const,
|
||||
correlationId: handoff.scope.correlationId,
|
||||
};
|
||||
}),
|
||||
observe: vi.fn(),
|
||||
result: vi.fn(),
|
||||
};
|
||||
const coordination = service(adapter, {
|
||||
handoffIdFactory: (): string => `handoff-${++handoffSequence}`,
|
||||
});
|
||||
const request = { idempotencyKey: 'request-1', summary: 'Implement the requested feature' };
|
||||
|
||||
const first = coordination.handoff(request, context);
|
||||
const retry = coordination.handoff(request, context);
|
||||
expect(adapter.handoff).toHaveBeenCalledTimes(1);
|
||||
release?.();
|
||||
await expect(Promise.all([first, retry])).resolves.toEqual([
|
||||
expect.objectContaining({ handoffId: 'handoff-1' }),
|
||||
expect.objectContaining({ handoffId: 'handoff-1' }),
|
||||
]);
|
||||
|
||||
await expect(
|
||||
coordination.handoff(request, {
|
||||
...context,
|
||||
actorScope: { ...context.actorScope, userId: 'operator-2' },
|
||||
}),
|
||||
).resolves.toMatchObject({ handoffId: 'handoff-2' });
|
||||
expect(adapter.handoff).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('rejects idempotency-key payload drift and malformed handoff input before delivery', async (): Promise<void> => {
|
||||
const adapter = new InMemoryInteractionCoordinationPort();
|
||||
const handoff = vi.spyOn(adapter, 'handoff');
|
||||
const coordination = service(adapter);
|
||||
await coordination.handoff(
|
||||
{ idempotencyKey: 'request-1', summary: 'Implement the requested feature' },
|
||||
context,
|
||||
);
|
||||
|
||||
await expect(
|
||||
coordination.handoff({ idempotencyKey: 'request-1', summary: 'Different work' }, context),
|
||||
).rejects.toMatchObject({
|
||||
code: 'handoff_conflict',
|
||||
} satisfies Partial<InteractionCoordinationGatewayError>);
|
||||
await expect(
|
||||
coordination.handoff({ idempotencyKey: 'request-2', summary: '' }, context),
|
||||
).rejects.toMatchObject({
|
||||
code: 'invalid_request',
|
||||
} satisfies Partial<InteractionCoordinationGatewayError>);
|
||||
await expect(
|
||||
coordination.handoff({ idempotencyKey: 'request-3', summary: 'x'.repeat(2_049) }, context),
|
||||
).rejects.toMatchObject({
|
||||
code: 'invalid_request',
|
||||
} satisfies Partial<InteractionCoordinationGatewayError>);
|
||||
expect(handoff).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('fails closed when the port reports a target that drifts from configuration', async (): Promise<void> => {
|
||||
const adapter: InteractionCoordinationPort = {
|
||||
handoff: vi.fn(async (handoff: Handoff) => ({
|
||||
handoffId: handoff.handoffId,
|
||||
targetAgentId: 'Unexpected',
|
||||
status: 'accepted' as const,
|
||||
correlationId: handoff.scope.correlationId,
|
||||
})),
|
||||
observe: vi.fn(),
|
||||
result: vi.fn(),
|
||||
};
|
||||
|
||||
await expect(
|
||||
service(adapter).handoff(
|
||||
{ idempotencyKey: 'request-1', summary: 'Implement the requested feature' },
|
||||
context,
|
||||
),
|
||||
).rejects.toMatchObject({ code: 'target_drift' });
|
||||
});
|
||||
});
|
||||
@@ -1,306 +0,0 @@
|
||||
import { Inject, Injectable, Optional } from '@nestjs/common';
|
||||
import {
|
||||
InteractionCoordinationClient,
|
||||
type CoordinationObservation,
|
||||
type CoordinationResult,
|
||||
type CoordinationScope,
|
||||
type InteractionCoordinationIdentity,
|
||||
type InteractionCoordinationPort,
|
||||
type HandoffReceipt,
|
||||
} from '@mosaicstack/coord';
|
||||
import type { RuntimeProviderRequestContext } from '../agent/runtime-provider-registry.service.js';
|
||||
import type { CreateHandoffDto } from './interaction-coordination.dto.js';
|
||||
|
||||
export const COORDINATION_PORT = Symbol('COORDINATION_PORT');
|
||||
export const COORDINATION_CONFIG = Symbol('COORDINATION_CONFIG');
|
||||
export const HANDOFF_ID_FACTORY = Symbol('HANDOFF_ID_FACTORY');
|
||||
|
||||
const HANDOFF_TRACKING_TTL_MS = 60 * 60 * 1_000;
|
||||
const MAX_TRACKED_HANDOFFS = 1_000;
|
||||
const MAX_IDEMPOTENCY_KEY_LENGTH = 128;
|
||||
const MAX_SUMMARY_LENGTH = 2_048;
|
||||
const MAX_CONTEXT_LENGTH = 8_192;
|
||||
const MAX_MISSION_ID_LENGTH = 128;
|
||||
|
||||
export interface InteractionCoordinationConfig {
|
||||
interactionAgentId?: string;
|
||||
orchestrationAgentId?: string;
|
||||
}
|
||||
|
||||
interface HandoffOwner {
|
||||
actorId: string;
|
||||
tenantId: string;
|
||||
requesterAgentId: string;
|
||||
correlationId: string;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
interface NormalizedHandoffRequest {
|
||||
idempotencyKey: string;
|
||||
summary: string;
|
||||
context?: string;
|
||||
missionId?: string;
|
||||
}
|
||||
|
||||
interface TrackedHandoff {
|
||||
request: NormalizedHandoffRequest;
|
||||
receipt: Promise<HandoffReceipt>;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gateway authority boundary for the interaction agent. It derives requester,
|
||||
* actor, and tenant from trusted server configuration and authentication; no
|
||||
* channel request can name a target or gain orchestrator-owned orchestration verbs.
|
||||
*/
|
||||
@Injectable()
|
||||
export class InteractionCoordinationService {
|
||||
private readonly owners = new Map<string, HandoffOwner>();
|
||||
private readonly handoffsByIdempotencyKey = new Map<string, TrackedHandoff>();
|
||||
|
||||
constructor(
|
||||
@Inject(COORDINATION_PORT) private readonly port: InteractionCoordinationPort,
|
||||
@Inject(COORDINATION_CONFIG) private readonly config: InteractionCoordinationConfig,
|
||||
@Optional()
|
||||
@Inject(HANDOFF_ID_FACTORY)
|
||||
private readonly handoffIdFactory: () => string = (): string => crypto.randomUUID(),
|
||||
) {}
|
||||
|
||||
async handoff(
|
||||
request: CreateHandoffDto,
|
||||
context: RuntimeProviderRequestContext,
|
||||
): Promise<HandoffReceipt> {
|
||||
this.pruneExpiredTracking();
|
||||
const normalized = this.normalizeRequest(request);
|
||||
const scope = this.scope(context);
|
||||
const idempotencyKey = this.idempotencyKey(normalized.idempotencyKey, scope);
|
||||
const existing = this.handoffsByIdempotencyKey.get(idempotencyKey);
|
||||
if (existing !== undefined) {
|
||||
if (!sameRequest(existing.request, normalized)) {
|
||||
throw new InteractionCoordinationGatewayError(
|
||||
'handoff_conflict',
|
||||
'Handoff idempotency key is already bound to different immutable input',
|
||||
);
|
||||
}
|
||||
return existing.receipt;
|
||||
}
|
||||
|
||||
const pending = this.deliverHandoff(this.handoffIdFactory(), normalized, scope);
|
||||
const tracked: TrackedHandoff = {
|
||||
request: normalized,
|
||||
receipt: pending,
|
||||
expiresAt: this.expiresAt(),
|
||||
};
|
||||
this.handoffsByIdempotencyKey.set(idempotencyKey, tracked);
|
||||
this.enforceTrackingLimit(this.handoffsByIdempotencyKey);
|
||||
try {
|
||||
return await pending;
|
||||
} catch (error: unknown) {
|
||||
if (this.handoffsByIdempotencyKey.get(idempotencyKey) === tracked) {
|
||||
this.handoffsByIdempotencyKey.delete(idempotencyKey);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async observe(
|
||||
handoffId: string,
|
||||
context: RuntimeProviderRequestContext,
|
||||
): Promise<CoordinationObservation> {
|
||||
this.pruneExpiredTracking();
|
||||
const scope = this.scope(context);
|
||||
const owner = this.ownerFor(handoffId, scope);
|
||||
return this.client().observe(handoffId, { ...scope, correlationId: owner.correlationId });
|
||||
}
|
||||
|
||||
async result(
|
||||
handoffId: string,
|
||||
context: RuntimeProviderRequestContext,
|
||||
): Promise<CoordinationResult> {
|
||||
this.pruneExpiredTracking();
|
||||
const scope = this.scope(context);
|
||||
const owner = this.ownerFor(handoffId, scope);
|
||||
return this.client().result(handoffId, { ...scope, correlationId: owner.correlationId });
|
||||
}
|
||||
|
||||
private async deliverHandoff(
|
||||
handoffId: string,
|
||||
request: NormalizedHandoffRequest,
|
||||
scope: CoordinationScope,
|
||||
): Promise<HandoffReceipt> {
|
||||
const receipt = await this.client((): string => handoffId).handoff(request, scope);
|
||||
const owner: HandoffOwner = {
|
||||
actorId: scope.actorId,
|
||||
tenantId: scope.tenantId,
|
||||
requesterAgentId: scope.requesterAgentId,
|
||||
correlationId: scope.correlationId,
|
||||
expiresAt: this.expiresAt(),
|
||||
};
|
||||
const existing = this.owners.get(receipt.handoffId);
|
||||
if (existing !== undefined && !sameOwner(existing, owner)) {
|
||||
throw new InteractionCoordinationGatewayError(
|
||||
'handoff_conflict',
|
||||
'Handoff ID is already bound to a different authenticated scope',
|
||||
);
|
||||
}
|
||||
this.owners.set(receipt.handoffId, owner);
|
||||
this.enforceTrackingLimit(this.owners);
|
||||
return receipt;
|
||||
}
|
||||
|
||||
private client(handoffIdFactory?: () => string): InteractionCoordinationClient {
|
||||
return new InteractionCoordinationClient(this.identity(), this.port, handoffIdFactory);
|
||||
}
|
||||
|
||||
private identity(): InteractionCoordinationIdentity {
|
||||
const interactionAgentId = this.config.interactionAgentId?.trim();
|
||||
const orchestrationAgentId = this.config.orchestrationAgentId?.trim();
|
||||
if (!interactionAgentId) {
|
||||
throw new InteractionCoordinationGatewayError(
|
||||
'unconfigured_requester',
|
||||
'Interaction agent identity is not configured',
|
||||
);
|
||||
}
|
||||
if (!orchestrationAgentId) {
|
||||
throw new InteractionCoordinationGatewayError(
|
||||
'unconfigured_target',
|
||||
'Orchestration agent identity is not configured',
|
||||
);
|
||||
}
|
||||
return { interactionAgentId, orchestrationAgentId };
|
||||
}
|
||||
|
||||
private scope(context: RuntimeProviderRequestContext): CoordinationScope {
|
||||
const identity = this.identity();
|
||||
return Object.freeze({
|
||||
actorId: context.actorScope.userId,
|
||||
tenantId: context.actorScope.tenantId,
|
||||
correlationId: context.correlationId,
|
||||
requesterAgentId: identity.interactionAgentId,
|
||||
});
|
||||
}
|
||||
|
||||
private normalizeRequest(request: CreateHandoffDto): NormalizedHandoffRequest {
|
||||
if (typeof request !== 'object' || request === null) {
|
||||
throw new InteractionCoordinationGatewayError(
|
||||
'invalid_request',
|
||||
'Handoff request is invalid',
|
||||
);
|
||||
}
|
||||
const idempotencyKey = this.requiredString(
|
||||
request.idempotencyKey,
|
||||
'idempotency key',
|
||||
MAX_IDEMPOTENCY_KEY_LENGTH,
|
||||
);
|
||||
const summary = this.requiredString(request.summary, 'summary', MAX_SUMMARY_LENGTH);
|
||||
const context = this.optionalString(request.context, 'context', MAX_CONTEXT_LENGTH);
|
||||
const missionId = this.optionalString(request.missionId, 'mission ID', MAX_MISSION_ID_LENGTH);
|
||||
return Object.freeze({
|
||||
idempotencyKey,
|
||||
summary,
|
||||
...(context === undefined ? {} : { context }),
|
||||
...(missionId === undefined ? {} : { missionId }),
|
||||
});
|
||||
}
|
||||
|
||||
private idempotencyKey(requestKey: string, scope: CoordinationScope): string {
|
||||
return `${scope.tenantId}\u0000${scope.actorId}\u0000${scope.requesterAgentId}\u0000${requestKey}`;
|
||||
}
|
||||
|
||||
private requiredString(value: unknown, field: string, maximumLength: number): string {
|
||||
if (typeof value !== 'string') {
|
||||
throw new InteractionCoordinationGatewayError(
|
||||
'invalid_request',
|
||||
`Handoff ${field} must be a string`,
|
||||
);
|
||||
}
|
||||
const normalized = value.trim();
|
||||
if (normalized.length === 0 || normalized.length > maximumLength) {
|
||||
throw new InteractionCoordinationGatewayError(
|
||||
'invalid_request',
|
||||
`Handoff ${field} is invalid`,
|
||||
);
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private optionalString(value: unknown, field: string, maximumLength: number): string | undefined {
|
||||
if (value === undefined) return undefined;
|
||||
return this.requiredString(value, field, maximumLength);
|
||||
}
|
||||
|
||||
private expiresAt(): number {
|
||||
return Date.now() + HANDOFF_TRACKING_TTL_MS;
|
||||
}
|
||||
|
||||
private pruneExpiredTracking(): void {
|
||||
const now = Date.now();
|
||||
for (const [key, tracked] of this.handoffsByIdempotencyKey) {
|
||||
if (tracked.expiresAt <= now) this.handoffsByIdempotencyKey.delete(key);
|
||||
}
|
||||
for (const [key, owner] of this.owners) {
|
||||
if (owner.expiresAt <= now) this.owners.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
private enforceTrackingLimit<T>(entries: Map<string, T>): void {
|
||||
while (entries.size > MAX_TRACKED_HANDOFFS) {
|
||||
const oldest = entries.keys().next().value;
|
||||
if (typeof oldest !== 'string') return;
|
||||
entries.delete(oldest);
|
||||
}
|
||||
}
|
||||
|
||||
private ownerFor(handoffId: string, scope: CoordinationScope): HandoffOwner {
|
||||
const owner = this.owners.get(handoffId);
|
||||
if (owner === undefined) {
|
||||
throw new InteractionCoordinationGatewayError('not_found', 'Handoff was not found');
|
||||
}
|
||||
if (
|
||||
owner.tenantId !== scope.tenantId ||
|
||||
owner.actorId !== scope.actorId ||
|
||||
owner.requesterAgentId !== scope.requesterAgentId
|
||||
) {
|
||||
throw new InteractionCoordinationGatewayError(
|
||||
'cross_tenant_forbidden',
|
||||
'Handoff is outside the authenticated scope',
|
||||
);
|
||||
}
|
||||
return owner;
|
||||
}
|
||||
}
|
||||
|
||||
export type InteractionCoordinationGatewayErrorCode =
|
||||
| 'cross_tenant_forbidden'
|
||||
| 'handoff_conflict'
|
||||
| 'invalid_request'
|
||||
| 'not_found'
|
||||
| 'unconfigured_requester'
|
||||
| 'unconfigured_target';
|
||||
|
||||
function sameOwner(left: HandoffOwner, right: HandoffOwner): boolean {
|
||||
return (
|
||||
left.actorId === right.actorId &&
|
||||
left.tenantId === right.tenantId &&
|
||||
left.requesterAgentId === right.requesterAgentId
|
||||
);
|
||||
}
|
||||
|
||||
function sameRequest(left: NormalizedHandoffRequest, right: NormalizedHandoffRequest): boolean {
|
||||
return (
|
||||
left.idempotencyKey === right.idempotencyKey &&
|
||||
left.summary === right.summary &&
|
||||
left.context === right.context &&
|
||||
left.missionId === right.missionId
|
||||
);
|
||||
}
|
||||
|
||||
export class InteractionCoordinationGatewayError extends Error {
|
||||
constructor(
|
||||
readonly code: InteractionCoordinationGatewayErrorCode,
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
this.name = InteractionCoordinationGatewayError.name;
|
||||
}
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
import { config } from 'dotenv';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { detectFromEnv, loadConfig } from '@mosaicstack/config';
|
||||
|
||||
type TierSource =
|
||||
| 'process environment'
|
||||
| 'daemon .env'
|
||||
| 'monorepo-root .env'
|
||||
| 'gateway-local .env'
|
||||
| 'default';
|
||||
|
||||
type BootSource = TierSource | 'mosaic.config.json';
|
||||
|
||||
export interface GatewayDotenvPaths {
|
||||
daemonEnv: string;
|
||||
monorepoRootEnv: string;
|
||||
gatewayLocalEnv: string;
|
||||
}
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
export function resolveGatewayDotenvPaths(
|
||||
anchor: string = here,
|
||||
homeBase: string = homedir(),
|
||||
): GatewayDotenvPaths {
|
||||
return {
|
||||
daemonEnv: join(homeBase, '.config', 'mosaic', 'gateway', '.env'),
|
||||
monorepoRootEnv: resolve(anchor, '../../..', '.env'),
|
||||
gatewayLocalEnv: resolve(anchor, '..', '.env'),
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveGatewayConfigPath(anchor: string = here): string {
|
||||
// GATEWAY_HOME is daemon-created 0700; its env override adds no authority because env can set MOSAIC_STORAGE_TIER.
|
||||
const gatewayHome = resolve(
|
||||
process.env['MOSAIC_GATEWAY_HOME'] ?? join(homedir(), '.config', 'mosaic', 'gateway'),
|
||||
);
|
||||
const daemonConfig = join(gatewayHome, 'mosaic.config.json');
|
||||
const gatewayLocalConfig = resolve(anchor, '..', 'mosaic.config.json');
|
||||
const monorepoRootConfig = resolve(anchor, '../../..', 'mosaic.config.json');
|
||||
|
||||
if (existsSync(daemonConfig)) {
|
||||
return daemonConfig;
|
||||
}
|
||||
if (existsSync(gatewayLocalConfig)) {
|
||||
return gatewayLocalConfig;
|
||||
}
|
||||
if (existsSync(monorepoRootConfig)) {
|
||||
return monorepoRootConfig;
|
||||
}
|
||||
|
||||
return monorepoRootConfig;
|
||||
}
|
||||
|
||||
export function loadGatewayEnv(anchor: string = here, homeBase: string = homedir()): void {
|
||||
const { daemonEnv, monorepoRootEnv, gatewayLocalEnv } = resolveGatewayDotenvPaths(
|
||||
anchor,
|
||||
homeBase,
|
||||
);
|
||||
const inheritedTier = process.env['MOSAIC_STORAGE_TIER'];
|
||||
let tierSource: TierSource = inheritedTier === undefined ? 'default' : 'process environment';
|
||||
const inheritedDatabaseUrl = process.env['DATABASE_URL'];
|
||||
let databaseUrlSource: TierSource =
|
||||
inheritedDatabaseUrl === undefined ? 'default' : 'process environment';
|
||||
|
||||
function loadAnchoredDotenv(
|
||||
path: string,
|
||||
sourceLabel: Exclude<TierSource, 'process environment' | 'default'>,
|
||||
): void {
|
||||
if (!existsSync(path)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const beforeTier = process.env['MOSAIC_STORAGE_TIER'];
|
||||
const beforeDatabaseUrl = process.env['DATABASE_URL'];
|
||||
config({ path, quiet: true });
|
||||
|
||||
if (
|
||||
beforeTier === undefined &&
|
||||
process.env['MOSAIC_STORAGE_TIER'] !== undefined &&
|
||||
tierSource === 'default'
|
||||
) {
|
||||
tierSource = sourceLabel;
|
||||
}
|
||||
|
||||
if (
|
||||
beforeDatabaseUrl === undefined &&
|
||||
process.env['DATABASE_URL'] !== undefined &&
|
||||
databaseUrlSource === 'default'
|
||||
) {
|
||||
databaseUrlSource = sourceLabel;
|
||||
}
|
||||
}
|
||||
|
||||
// Load .env from daemon config dir (global install / daemon mode) first.
|
||||
// It takes precedence over file-based local-dev configuration.
|
||||
loadAnchoredDotenv(daemonEnv, 'daemon .env');
|
||||
|
||||
// Load .env from the anchored monorepo root, then fill any remaining values
|
||||
// from apps/gateway/.env when present.
|
||||
loadAnchoredDotenv(monorepoRootEnv, 'monorepo-root .env');
|
||||
loadAnchoredDotenv(gatewayLocalEnv, 'gateway-local .env');
|
||||
|
||||
const envOnlyTier = detectFromEnv().tier;
|
||||
const configPath = resolveGatewayConfigPath(anchor);
|
||||
const anchoredConfigExists = existsSync(configPath);
|
||||
const resolvedTier = loadConfig(configPath).tier;
|
||||
const configuredTier = process.env['MOSAIC_STORAGE_TIER'];
|
||||
const databaseUrlDeterminesTier = envOnlyTier === 'standalone' && configuredTier !== 'standalone';
|
||||
const recognizedTierDeterminesTier =
|
||||
(configuredTier === 'federated' ||
|
||||
configuredTier === 'standalone' ||
|
||||
configuredTier === 'local') &&
|
||||
configuredTier === envOnlyTier;
|
||||
|
||||
let source: BootSource;
|
||||
if (anchoredConfigExists) {
|
||||
source = 'mosaic.config.json';
|
||||
} else if (databaseUrlDeterminesTier && databaseUrlSource !== 'default') {
|
||||
source = databaseUrlSource;
|
||||
} else if (recognizedTierDeterminesTier && tierSource !== 'default') {
|
||||
source = tierSource;
|
||||
} else {
|
||||
source = 'default';
|
||||
}
|
||||
|
||||
console.info(`[gateway env] storage tier=${resolvedTier} source=${source}`);
|
||||
}
|
||||
|
||||
loadGatewayEnv();
|
||||
@@ -5,8 +5,6 @@ import { EnrollmentController } from './enrollment.controller.js';
|
||||
import { EnrollmentService } from './enrollment.service.js';
|
||||
import { FederationController } from './federation.controller.js';
|
||||
import { CapabilitiesController } from './server/verbs/capabilities.controller.js';
|
||||
import { GetController } from './server/verbs/get.controller.js';
|
||||
import { FederationGetQueryService } from './server/verbs/get-query.service.js';
|
||||
import { GrantsService } from './grants.service.js';
|
||||
import { FederationClientService, QuerySourceService } from './client/index.js';
|
||||
import { FederationAuthGuard, FederationScopeService } from './server/index.js';
|
||||
@@ -14,13 +12,7 @@ import { ListController } from './server/verbs/list.controller.js';
|
||||
import { FederationListQueryService } from './server/verbs/list-query.service.js';
|
||||
|
||||
@Module({
|
||||
controllers: [
|
||||
EnrollmentController,
|
||||
FederationController,
|
||||
CapabilitiesController,
|
||||
ListController,
|
||||
GetController,
|
||||
],
|
||||
controllers: [EnrollmentController, FederationController, CapabilitiesController, ListController],
|
||||
providers: [
|
||||
AdminGuard,
|
||||
CaService,
|
||||
@@ -31,7 +23,6 @@ import { FederationListQueryService } from './server/verbs/list-query.service.js
|
||||
FederationAuthGuard,
|
||||
FederationScopeService,
|
||||
FederationListQueryService,
|
||||
FederationGetQueryService,
|
||||
],
|
||||
exports: [
|
||||
CaService,
|
||||
@@ -42,7 +33,6 @@ import { FederationListQueryService } from './server/verbs/list-query.service.js
|
||||
FederationAuthGuard,
|
||||
FederationScopeService,
|
||||
FederationListQueryService,
|
||||
FederationGetQueryService,
|
||||
],
|
||||
})
|
||||
export class FederationModule {}
|
||||
|
||||
@@ -1,348 +0,0 @@
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
createPgliteDb,
|
||||
missionTasks,
|
||||
missions,
|
||||
projects,
|
||||
runPgliteMigrations,
|
||||
teams,
|
||||
users,
|
||||
type Db,
|
||||
type DbHandle,
|
||||
} from '@mosaicstack/db';
|
||||
import type { FederationScopeQueryFilter } from '../../scope.service.js';
|
||||
import { FederationGetQueryService } from '../get-query.service.js';
|
||||
|
||||
const CREDENTIAL_FILTER: FederationScopeQueryFilter = {
|
||||
resource: 'credentials',
|
||||
subjectUserId: 'user-1',
|
||||
includePersonal: true,
|
||||
teamIds: [],
|
||||
limit: 1,
|
||||
maxRowsPerQuery: 25,
|
||||
};
|
||||
|
||||
const SUBJECT_USER_ID = 'fed-m3-06-subject';
|
||||
const OTHER_USER_ID = 'fed-m3-06-other';
|
||||
const TEAM_ID = '06000000-0000-4000-8000-000000000001';
|
||||
const UNAUTHORIZED_TEAM_ID = '06000000-0000-4000-8000-000000000002';
|
||||
const PERSONAL_PROJECT_ID = '06000000-0000-4000-8000-000000000101';
|
||||
const TEAM_PROJECT_ID = '06000000-0000-4000-8000-000000000102';
|
||||
const UNAUTHORIZED_PROJECT_ID = '06000000-0000-4000-8000-000000000103';
|
||||
const PERSONAL_MISSION_ID = '06000000-0000-4000-8000-000000000201';
|
||||
const TEAM_MISSION_ID = '06000000-0000-4000-8000-000000000202';
|
||||
const UNAUTHORIZED_MISSION_ID = '06000000-0000-4000-8000-000000000203';
|
||||
const SUBJECT_TEAM_NOTE_ID = '06000000-0000-4000-8000-000000000301';
|
||||
const OTHER_TEAM_NOTE_ID = '06000000-0000-4000-8000-000000000302';
|
||||
const SUBJECT_PERSONAL_NOTE_ID = '06000000-0000-4000-8000-000000000303';
|
||||
const SUBJECT_UNAUTHORIZED_NOTE_ID = '06000000-0000-4000-8000-000000000304';
|
||||
|
||||
let dbHandle: DbHandle | undefined;
|
||||
|
||||
function makeService() {
|
||||
return new FederationGetQueryService({} as Db);
|
||||
}
|
||||
|
||||
function makeDbService() {
|
||||
if (!dbHandle) {
|
||||
throw new Error('test DB not initialized');
|
||||
}
|
||||
return new FederationGetQueryService(dbHandle.db);
|
||||
}
|
||||
|
||||
async function seedNotesFixture() {
|
||||
if (!dbHandle) {
|
||||
throw new Error('test DB not initialized');
|
||||
}
|
||||
|
||||
await dbHandle.db.insert(users).values([
|
||||
{
|
||||
id: SUBJECT_USER_ID,
|
||||
name: 'Federation Subject',
|
||||
email: `${SUBJECT_USER_ID}@example.test`,
|
||||
emailVerified: false,
|
||||
},
|
||||
{
|
||||
id: OTHER_USER_ID,
|
||||
name: 'Federation Other',
|
||||
email: `${OTHER_USER_ID}@example.test`,
|
||||
emailVerified: false,
|
||||
},
|
||||
]);
|
||||
|
||||
await dbHandle.db.insert(teams).values([
|
||||
{
|
||||
id: TEAM_ID,
|
||||
name: 'FED-M3-06 Team',
|
||||
slug: 'fed-m3-06-team',
|
||||
ownerId: SUBJECT_USER_ID,
|
||||
managerId: SUBJECT_USER_ID,
|
||||
},
|
||||
{
|
||||
id: UNAUTHORIZED_TEAM_ID,
|
||||
name: 'FED-M3-06 Unauthorized Team',
|
||||
slug: 'fed-m3-06-unauthorized-team',
|
||||
ownerId: OTHER_USER_ID,
|
||||
managerId: OTHER_USER_ID,
|
||||
},
|
||||
]);
|
||||
|
||||
await dbHandle.db.insert(projects).values([
|
||||
{
|
||||
id: PERSONAL_PROJECT_ID,
|
||||
name: 'FED-M3-06 Personal Project',
|
||||
ownerId: SUBJECT_USER_ID,
|
||||
ownerType: 'user',
|
||||
},
|
||||
{
|
||||
id: TEAM_PROJECT_ID,
|
||||
name: 'FED-M3-06 Team Project',
|
||||
teamId: TEAM_ID,
|
||||
ownerType: 'team',
|
||||
},
|
||||
{
|
||||
id: UNAUTHORIZED_PROJECT_ID,
|
||||
name: 'FED-M3-06 Unauthorized Project',
|
||||
teamId: UNAUTHORIZED_TEAM_ID,
|
||||
ownerType: 'team',
|
||||
},
|
||||
]);
|
||||
|
||||
await dbHandle.db.insert(missions).values([
|
||||
{
|
||||
id: PERSONAL_MISSION_ID,
|
||||
name: 'FED-M3-06 Personal Mission',
|
||||
projectId: PERSONAL_PROJECT_ID,
|
||||
userId: SUBJECT_USER_ID,
|
||||
},
|
||||
{
|
||||
id: TEAM_MISSION_ID,
|
||||
name: 'FED-M3-06 Team Mission',
|
||||
projectId: TEAM_PROJECT_ID,
|
||||
userId: SUBJECT_USER_ID,
|
||||
},
|
||||
{
|
||||
id: UNAUTHORIZED_MISSION_ID,
|
||||
name: 'FED-M3-06 Unauthorized Mission',
|
||||
projectId: UNAUTHORIZED_PROJECT_ID,
|
||||
userId: SUBJECT_USER_ID,
|
||||
},
|
||||
]);
|
||||
|
||||
await dbHandle.db.insert(missionTasks).values([
|
||||
{
|
||||
id: SUBJECT_TEAM_NOTE_ID,
|
||||
missionId: TEAM_MISSION_ID,
|
||||
userId: SUBJECT_USER_ID,
|
||||
notes: 'subject note on team mission',
|
||||
createdAt: new Date('2026-06-24T03:00:00.000Z'),
|
||||
updatedAt: new Date('2026-06-24T03:00:00.000Z'),
|
||||
},
|
||||
{
|
||||
id: OTHER_TEAM_NOTE_ID,
|
||||
missionId: TEAM_MISSION_ID,
|
||||
userId: OTHER_USER_ID,
|
||||
notes: 'other user note on team mission',
|
||||
createdAt: new Date('2026-06-24T02:00:00.000Z'),
|
||||
updatedAt: new Date('2026-06-24T02:00:00.000Z'),
|
||||
},
|
||||
{
|
||||
id: SUBJECT_PERSONAL_NOTE_ID,
|
||||
missionId: PERSONAL_MISSION_ID,
|
||||
userId: SUBJECT_USER_ID,
|
||||
notes: 'subject note on personal mission',
|
||||
createdAt: new Date('2026-06-24T01:00:00.000Z'),
|
||||
updatedAt: new Date('2026-06-24T01:00:00.000Z'),
|
||||
},
|
||||
{
|
||||
id: SUBJECT_UNAUTHORIZED_NOTE_ID,
|
||||
missionId: UNAUTHORIZED_MISSION_ID,
|
||||
userId: SUBJECT_USER_ID,
|
||||
notes: 'subject note outside grant-visible missions',
|
||||
createdAt: new Date('2026-06-24T04:00:00.000Z'),
|
||||
updatedAt: new Date('2026-06-24T04:00:00.000Z'),
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
describe('FederationGetQueryService', () => {
|
||||
beforeAll(async () => {
|
||||
dbHandle = createPgliteDb(`memory://fed-m3-06-get-${Date.now()}`);
|
||||
await runPgliteMigrations(dbHandle);
|
||||
await seedNotesFixture();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await dbHandle?.close();
|
||||
dbHandle = undefined;
|
||||
});
|
||||
|
||||
it('denies sensitive resources in native RBAC for M3 get reads', async () => {
|
||||
const service = makeService();
|
||||
|
||||
await expect(
|
||||
service.evaluateReadAccess({
|
||||
grantId: 'grant-1',
|
||||
peerId: 'peer-1',
|
||||
subjectUserId: 'user-1',
|
||||
resource: 'credentials',
|
||||
}),
|
||||
).resolves.toMatchObject({
|
||||
allowed: false,
|
||||
reason: 'credentials federation get access is not implemented in M3',
|
||||
});
|
||||
});
|
||||
|
||||
it('allows personal memory reads without requiring team lookup', async () => {
|
||||
const service = makeService();
|
||||
|
||||
await expect(
|
||||
service.evaluateReadAccess({
|
||||
grantId: 'grant-1',
|
||||
peerId: 'peer-1',
|
||||
subjectUserId: 'user-1',
|
||||
resource: 'memory',
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
allowed: true,
|
||||
access: { includePersonal: true, teamIds: [] },
|
||||
});
|
||||
});
|
||||
|
||||
it('uses subject team membership as the native RBAC upper bound for task and note reads', async () => {
|
||||
const service = makeService();
|
||||
const listSubjectTeamIds = vi.fn().mockResolvedValue(['team-1', 'team-2']);
|
||||
(
|
||||
service as unknown as {
|
||||
listSubjectTeamIds: (subjectUserId: string) => Promise<string[]>;
|
||||
}
|
||||
).listSubjectTeamIds = listSubjectTeamIds;
|
||||
|
||||
await expect(
|
||||
service.evaluateReadAccess({
|
||||
grantId: 'grant-1',
|
||||
peerId: 'peer-1',
|
||||
subjectUserId: 'user-1',
|
||||
resource: 'tasks',
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
allowed: true,
|
||||
access: { includePersonal: true, teamIds: ['team-1', 'team-2'] },
|
||||
});
|
||||
expect(listSubjectTeamIds).toHaveBeenCalledWith('user-1');
|
||||
});
|
||||
|
||||
it('does not query storage for sensitive get resources even if scope allowed them', async () => {
|
||||
const service = makeService();
|
||||
|
||||
await expect(service.get({ filter: CREDENTIAL_FILTER, id: 'cred-1' })).resolves.toEqual({
|
||||
status: 'denied',
|
||||
reason: 'credentials federation get is not implemented',
|
||||
});
|
||||
});
|
||||
|
||||
it('fails closed for unsupported resources instead of returning undefined', async () => {
|
||||
const service = makeService();
|
||||
|
||||
await expect(
|
||||
service.get({
|
||||
filter: {
|
||||
...CREDENTIAL_FILTER,
|
||||
resource: 'unknown-resource' as FederationScopeQueryFilter['resource'],
|
||||
},
|
||||
id: 'row-1',
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
status: 'denied',
|
||||
reason: 'Unsupported federation get resource: unknown-resource',
|
||||
});
|
||||
});
|
||||
|
||||
it('does not leak another user mission task note through team-scoped get reads', async () => {
|
||||
const service = makeDbService();
|
||||
|
||||
await expect(
|
||||
service.get({
|
||||
filter: {
|
||||
resource: 'notes',
|
||||
subjectUserId: SUBJECT_USER_ID,
|
||||
includePersonal: false,
|
||||
teamIds: [TEAM_ID],
|
||||
limit: 1,
|
||||
maxRowsPerQuery: 10,
|
||||
},
|
||||
id: OTHER_TEAM_NOTE_ID,
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
status: 'denied',
|
||||
reason: 'Note is outside the federated scope',
|
||||
});
|
||||
});
|
||||
|
||||
it('does not return subject notes from missions outside the grant-visible project set', async () => {
|
||||
const service = makeDbService();
|
||||
|
||||
await expect(
|
||||
service.get({
|
||||
filter: {
|
||||
resource: 'notes',
|
||||
subjectUserId: SUBJECT_USER_ID,
|
||||
includePersonal: true,
|
||||
teamIds: [TEAM_ID],
|
||||
limit: 1,
|
||||
maxRowsPerQuery: 10,
|
||||
},
|
||||
id: SUBJECT_UNAUTHORIZED_NOTE_ID,
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
status: 'denied',
|
||||
reason: 'Note is outside the federated scope',
|
||||
});
|
||||
});
|
||||
|
||||
it('returns a subject note only when subject ownership and authorized mission intersect', async () => {
|
||||
const service = makeDbService();
|
||||
|
||||
await expect(
|
||||
service.get({
|
||||
filter: {
|
||||
resource: 'notes',
|
||||
subjectUserId: SUBJECT_USER_ID,
|
||||
includePersonal: false,
|
||||
teamIds: [TEAM_ID],
|
||||
limit: 1,
|
||||
maxRowsPerQuery: 10,
|
||||
},
|
||||
id: SUBJECT_TEAM_NOTE_ID,
|
||||
}),
|
||||
).resolves.toMatchObject({
|
||||
status: 'found',
|
||||
item: {
|
||||
id: SUBJECT_TEAM_NOTE_ID,
|
||||
missionId: TEAM_MISSION_ID,
|
||||
content: 'subject note on team mission',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('does not return subject personal notes when includePersonal is false', async () => {
|
||||
const service = makeDbService();
|
||||
|
||||
await expect(
|
||||
service.get({
|
||||
filter: {
|
||||
resource: 'notes',
|
||||
subjectUserId: SUBJECT_USER_ID,
|
||||
includePersonal: false,
|
||||
teamIds: [TEAM_ID],
|
||||
limit: 1,
|
||||
maxRowsPerQuery: 10,
|
||||
},
|
||||
id: SUBJECT_PERSONAL_NOTE_ID,
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
status: 'denied',
|
||||
reason: 'Note is outside the federated scope',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,207 +0,0 @@
|
||||
import 'reflect-metadata';
|
||||
import { RequestMethod } from '@nestjs/common';
|
||||
import type { FastifyRequest } from 'fastify';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { FederationAuthGuard } from '../../federation-auth.guard.js';
|
||||
import type {
|
||||
FederationScopeEvaluationResult,
|
||||
FederationScopeQueryFilter,
|
||||
} from '../../scope.service.js';
|
||||
import { GetController } from '../get.controller.js';
|
||||
import type { FederationGetQueryResult } from '../get-query.service.js';
|
||||
|
||||
const FEDERATION_CONTEXT = {
|
||||
grantId: 'grant-1',
|
||||
peerId: 'peer-1',
|
||||
subjectUserId: 'user-1',
|
||||
scope: { resources: ['tasks'], max_rows_per_query: 25 },
|
||||
};
|
||||
|
||||
const TASK_FILTER: FederationScopeQueryFilter = {
|
||||
resource: 'tasks',
|
||||
subjectUserId: 'user-1',
|
||||
includePersonal: true,
|
||||
teamIds: ['team-1'],
|
||||
limit: 1,
|
||||
maxRowsPerQuery: 25,
|
||||
};
|
||||
|
||||
function makeRequest(): FastifyRequest {
|
||||
return { federationContext: FEDERATION_CONTEXT } as unknown as FastifyRequest;
|
||||
}
|
||||
|
||||
function allowedScope(
|
||||
filter: FederationScopeQueryFilter = TASK_FILTER,
|
||||
): FederationScopeEvaluationResult {
|
||||
return { allowed: true, filter };
|
||||
}
|
||||
|
||||
function makeController(opts?: {
|
||||
scopeResult?: FederationScopeEvaluationResult;
|
||||
queryResult?: FederationGetQueryResult;
|
||||
}) {
|
||||
const scope = {
|
||||
evaluateAccess: vi.fn().mockResolvedValue(opts?.scopeResult ?? allowedScope()),
|
||||
};
|
||||
const query = {
|
||||
evaluateReadAccess: vi.fn(),
|
||||
get: vi.fn().mockResolvedValue(
|
||||
opts?.queryResult ?? {
|
||||
status: 'found',
|
||||
item: {
|
||||
id: 'task-1',
|
||||
title: 'Federated task',
|
||||
createdAt: new Date('2026-06-24T00:00:00.000Z'),
|
||||
},
|
||||
},
|
||||
),
|
||||
};
|
||||
|
||||
return {
|
||||
controller: new GetController(scope as never, query as never),
|
||||
scope,
|
||||
query,
|
||||
};
|
||||
}
|
||||
|
||||
describe('GetController', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('declares POST /api/federation/v1/get/:resource/:id protected only by FederationAuthGuard', () => {
|
||||
expect(Reflect.getMetadata('path', GetController)).toBe('api/federation/v1/get');
|
||||
expect(Reflect.getMetadata('path', GetController.prototype.get)).toBe(':resource/:id');
|
||||
expect(Reflect.getMetadata('method', GetController.prototype.get)).toBe(RequestMethod.POST);
|
||||
expect(Reflect.getMetadata('__guards__', GetController)).toEqual([FederationAuthGuard]);
|
||||
});
|
||||
|
||||
it('runs AuthGuard context through ScopeService and returns one local-source tagged row', async () => {
|
||||
const { controller, scope, query } = makeController();
|
||||
|
||||
const response = await controller.get('tasks', 'task-1', makeRequest());
|
||||
|
||||
expect(scope.evaluateAccess).toHaveBeenCalledWith({
|
||||
context: FEDERATION_CONTEXT,
|
||||
resource: 'tasks',
|
||||
requestedLimit: 1,
|
||||
nativeRbac: query,
|
||||
});
|
||||
expect(query.get).toHaveBeenCalledWith({ filter: TASK_FILTER, id: 'task-1' });
|
||||
expect(response).toEqual({
|
||||
item: {
|
||||
id: 'task-1',
|
||||
title: 'Federated task',
|
||||
createdAt: new Date('2026-06-24T00:00:00.000Z'),
|
||||
_source: 'local',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('returns a federation error envelope when auth guard context is missing', async () => {
|
||||
const { controller, scope, query } = makeController();
|
||||
|
||||
await expect(
|
||||
controller.get('tasks', 'task-1', {} as unknown as FastifyRequest),
|
||||
).rejects.toMatchObject({
|
||||
response: {
|
||||
error: {
|
||||
code: 'unauthorized',
|
||||
message: 'Federation context missing',
|
||||
},
|
||||
},
|
||||
status: 401,
|
||||
});
|
||||
expect(scope.evaluateAccess).not.toHaveBeenCalled();
|
||||
expect(query.get).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns a federation error envelope when scope evaluation denies access', async () => {
|
||||
const { controller, query } = makeController({
|
||||
scopeResult: {
|
||||
allowed: false,
|
||||
deny: {
|
||||
code: 'resource_excluded',
|
||||
stage: 'resource_exclusion',
|
||||
statusCode: 403,
|
||||
message: 'Requested federation resource is explicitly excluded by grant scope',
|
||||
grantId: 'grant-1',
|
||||
peerId: 'peer-1',
|
||||
subjectUserId: 'user-1',
|
||||
resource: 'credentials',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await expect(controller.get('credentials', 'cred-1', makeRequest())).rejects.toMatchObject({
|
||||
response: {
|
||||
error: {
|
||||
code: 'scope_violation',
|
||||
message: 'Requested federation resource is explicitly excluded by grant scope',
|
||||
},
|
||||
},
|
||||
status: 403,
|
||||
});
|
||||
expect(query.get).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns 404 when the scoped query layer cannot find the resource id', async () => {
|
||||
const { controller } = makeController({ queryResult: { status: 'not_found' } });
|
||||
|
||||
await expect(controller.get('tasks', 'missing-task', makeRequest())).rejects.toMatchObject({
|
||||
response: { error: { code: 'not_found' } },
|
||||
status: 404,
|
||||
});
|
||||
});
|
||||
|
||||
it('returns 403 when the resource exists outside the RBAC/scope intersection', async () => {
|
||||
const { controller } = makeController({
|
||||
queryResult: { status: 'denied', reason: 'Task is outside the federated scope' },
|
||||
});
|
||||
|
||||
await expect(controller.get('tasks', 'task-2', makeRequest())).rejects.toMatchObject({
|
||||
response: {
|
||||
error: {
|
||||
code: 'scope_violation',
|
||||
message: 'Task is outside the federated scope',
|
||||
},
|
||||
},
|
||||
status: 403,
|
||||
});
|
||||
});
|
||||
|
||||
it('fails closed when the query layer denies an unsupported resource', async () => {
|
||||
const unsupportedFilter: FederationScopeQueryFilter = {
|
||||
...TASK_FILTER,
|
||||
resource: 'unknown-resource' as FederationScopeQueryFilter['resource'],
|
||||
};
|
||||
const { controller } = makeController({
|
||||
scopeResult: allowedScope(unsupportedFilter),
|
||||
queryResult: {
|
||||
status: 'denied',
|
||||
reason: 'Unsupported federation get resource: unknown-resource',
|
||||
},
|
||||
});
|
||||
|
||||
await expect(controller.get('unknown-resource', 'row-1', makeRequest())).rejects.toMatchObject({
|
||||
response: {
|
||||
error: {
|
||||
code: 'scope_violation',
|
||||
message: 'Unsupported federation get resource: unknown-resource',
|
||||
},
|
||||
},
|
||||
status: 403,
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects empty ids before evaluating scope', async () => {
|
||||
const { controller, scope, query } = makeController();
|
||||
|
||||
await expect(controller.get('tasks', ' ', makeRequest())).rejects.toMatchObject({
|
||||
response: { error: { code: 'invalid_request' } },
|
||||
status: 400,
|
||||
});
|
||||
expect(scope.evaluateAccess).not.toHaveBeenCalled();
|
||||
expect(query.get).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,311 +0,0 @@
|
||||
/**
|
||||
* Federation get query layer (FED-M3-06).
|
||||
*
|
||||
* Read-only DB adapter used by GetController after FederationAuthGuard and
|
||||
* FederationScopeService have established the subject user, allowed resource,
|
||||
* native-RBAC intersection, and row cap. Audit writes are intentionally
|
||||
* deferred to M4.
|
||||
*/
|
||||
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import {
|
||||
and,
|
||||
eq,
|
||||
inArray,
|
||||
insights,
|
||||
or,
|
||||
missionTasks,
|
||||
missions,
|
||||
preferences,
|
||||
projects,
|
||||
tasks,
|
||||
teamMembers,
|
||||
type Db,
|
||||
} from '@mosaicstack/db';
|
||||
import { DB } from '../../../database/database.module.js';
|
||||
import type {
|
||||
FederationNativeRbacEvaluator,
|
||||
FederationNativeRbacRequest,
|
||||
FederationNativeRbacResult,
|
||||
FederationScopeQueryFilter,
|
||||
} from '../scope.service.js';
|
||||
|
||||
export interface FederationGetQueryRequest {
|
||||
readonly filter: FederationScopeQueryFilter;
|
||||
readonly id: string;
|
||||
}
|
||||
|
||||
export interface FederationGetQueryFoundResult<T extends object = Record<string, unknown>> {
|
||||
readonly status: 'found';
|
||||
readonly item: T;
|
||||
}
|
||||
|
||||
export interface FederationGetQueryNotFoundResult {
|
||||
readonly status: 'not_found';
|
||||
}
|
||||
|
||||
export interface FederationGetQueryDeniedResult {
|
||||
readonly status: 'denied';
|
||||
readonly reason: string;
|
||||
}
|
||||
|
||||
export type FederationGetQueryResult<T extends object = Record<string, unknown>> =
|
||||
| FederationGetQueryFoundResult<T>
|
||||
| FederationGetQueryNotFoundResult
|
||||
| FederationGetQueryDeniedResult;
|
||||
|
||||
type RowObject = Record<string, unknown>;
|
||||
|
||||
function firstRow<T>(rows: T[]): T | undefined {
|
||||
return rows[0];
|
||||
}
|
||||
|
||||
function rowBelongsToAccessibleProjectOrMission(
|
||||
row: { projectId?: string | null; missionId?: string | null },
|
||||
projectIds: readonly string[],
|
||||
missionIds: readonly string[],
|
||||
): boolean {
|
||||
return (
|
||||
(typeof row.projectId === 'string' && projectIds.includes(row.projectId)) ||
|
||||
(typeof row.missionId === 'string' && missionIds.includes(row.missionId))
|
||||
);
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class FederationGetQueryService implements FederationNativeRbacEvaluator {
|
||||
constructor(@Inject(DB) private readonly db: Db) {}
|
||||
|
||||
async evaluateReadAccess(
|
||||
request: FederationNativeRbacRequest,
|
||||
): Promise<FederationNativeRbacResult> {
|
||||
if (request.resource === 'credentials' || request.resource === 'api_keys') {
|
||||
return {
|
||||
allowed: false,
|
||||
reason: `${request.resource} federation get access is not implemented in M3`,
|
||||
details: { resource: request.resource },
|
||||
};
|
||||
}
|
||||
|
||||
if (request.resource === 'memory') {
|
||||
return { allowed: true, access: { includePersonal: true, teamIds: [] } };
|
||||
}
|
||||
|
||||
const teamIds = await this.listSubjectTeamIds(request.subjectUserId);
|
||||
return { allowed: true, access: { includePersonal: true, teamIds } };
|
||||
}
|
||||
|
||||
async get<T extends RowObject = RowObject>(
|
||||
request: FederationGetQueryRequest,
|
||||
): Promise<FederationGetQueryResult<T>> {
|
||||
return this.getByResource(request.filter, request.id) as Promise<FederationGetQueryResult<T>>;
|
||||
}
|
||||
|
||||
private async getByResource(
|
||||
filter: FederationScopeQueryFilter,
|
||||
id: string,
|
||||
): Promise<FederationGetQueryResult> {
|
||||
switch (filter.resource) {
|
||||
case 'tasks':
|
||||
return this.getTask(filter, id);
|
||||
case 'notes':
|
||||
return this.getNote(filter, id);
|
||||
case 'memory':
|
||||
return this.getMemory(filter, id);
|
||||
case 'credentials':
|
||||
case 'api_keys':
|
||||
return { status: 'denied', reason: `${filter.resource} federation get is not implemented` };
|
||||
default:
|
||||
return {
|
||||
status: 'denied',
|
||||
reason: `Unsupported federation get resource: ${String(filter.resource)}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private async listSubjectTeamIds(subjectUserId: string): Promise<string[]> {
|
||||
const rows = await this.db
|
||||
.select({ teamId: teamMembers.teamId })
|
||||
.from(teamMembers)
|
||||
.where(eq(teamMembers.userId, subjectUserId));
|
||||
|
||||
return rows.map((row) => row.teamId);
|
||||
}
|
||||
|
||||
private async listAccessibleProjectIds(filter: FederationScopeQueryFilter): Promise<string[]> {
|
||||
const clauses = [];
|
||||
if (filter.includePersonal) {
|
||||
clauses.push(and(eq(projects.ownerType, 'user'), eq(projects.ownerId, filter.subjectUserId)));
|
||||
}
|
||||
if (filter.teamIds.length > 0) {
|
||||
// Project team ownership follows TeamsService.canAccessProject: team-owned
|
||||
// rows are authorized through projects.teamId, while ownerId remains the
|
||||
// user who created/bootstrapped the project.
|
||||
clauses.push(
|
||||
and(eq(projects.ownerType, 'team'), inArray(projects.teamId, [...filter.teamIds])),
|
||||
);
|
||||
}
|
||||
|
||||
if (clauses.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const rows = await this.db
|
||||
.select({ id: projects.id })
|
||||
.from(projects)
|
||||
.where(clauses.length === 1 ? clauses[0] : or(...clauses));
|
||||
|
||||
return rows.map((row) => row.id);
|
||||
}
|
||||
|
||||
private async listMissionIds(projectIds: readonly string[]): Promise<string[]> {
|
||||
if (projectIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const rows = await this.db
|
||||
.select({ id: missions.id })
|
||||
.from(missions)
|
||||
.where(inArray(missions.projectId, [...projectIds]));
|
||||
|
||||
return rows.map((row) => row.id);
|
||||
}
|
||||
|
||||
private async getTask(
|
||||
filter: FederationScopeQueryFilter,
|
||||
id: string,
|
||||
): Promise<FederationGetQueryResult> {
|
||||
const row = firstRow(
|
||||
await this.db
|
||||
.select({
|
||||
id: tasks.id,
|
||||
title: tasks.title,
|
||||
description: tasks.description,
|
||||
status: tasks.status,
|
||||
priority: tasks.priority,
|
||||
projectId: tasks.projectId,
|
||||
missionId: tasks.missionId,
|
||||
assignee: tasks.assignee,
|
||||
tags: tasks.tags,
|
||||
dueDate: tasks.dueDate,
|
||||
metadata: tasks.metadata,
|
||||
createdAt: tasks.createdAt,
|
||||
updatedAt: tasks.updatedAt,
|
||||
})
|
||||
.from(tasks)
|
||||
.where(eq(tasks.id, id))
|
||||
.limit(1),
|
||||
);
|
||||
|
||||
if (!row) {
|
||||
return { status: 'not_found' };
|
||||
}
|
||||
|
||||
const projectIds = await this.listAccessibleProjectIds(filter);
|
||||
const missionIds = await this.listMissionIds(projectIds);
|
||||
if (!rowBelongsToAccessibleProjectOrMission(row, projectIds, missionIds)) {
|
||||
return { status: 'denied', reason: 'Task is outside the federated scope' };
|
||||
}
|
||||
|
||||
return { status: 'found', item: row as RowObject };
|
||||
}
|
||||
|
||||
private async getNote(
|
||||
filter: FederationScopeQueryFilter,
|
||||
id: string,
|
||||
): Promise<FederationGetQueryResult> {
|
||||
const row = firstRow(
|
||||
await this.db
|
||||
.select({
|
||||
id: missionTasks.id,
|
||||
missionId: missionTasks.missionId,
|
||||
taskId: missionTasks.taskId,
|
||||
userId: missionTasks.userId,
|
||||
status: missionTasks.status,
|
||||
content: missionTasks.notes,
|
||||
createdAt: missionTasks.createdAt,
|
||||
updatedAt: missionTasks.updatedAt,
|
||||
})
|
||||
.from(missionTasks)
|
||||
.where(eq(missionTasks.id, id))
|
||||
.limit(1),
|
||||
);
|
||||
|
||||
if (!row || row.content === null || row.content === '') {
|
||||
return { status: 'not_found' };
|
||||
}
|
||||
|
||||
const projectIds = await this.listAccessibleProjectIds(filter);
|
||||
const missionIds = await this.listMissionIds(projectIds);
|
||||
|
||||
// mission_tasks rows are user-scoped even when the mission belongs to a team.
|
||||
// Scope-visible missions must intersect with subject ownership; team scope
|
||||
// narrows mission IDs but never widens note reads to another user's rows.
|
||||
if (row.userId !== filter.subjectUserId || !missionIds.includes(row.missionId)) {
|
||||
return { status: 'denied', reason: 'Note is outside the federated scope' };
|
||||
}
|
||||
|
||||
const item = { ...row } as RowObject;
|
||||
delete item['userId'];
|
||||
return { status: 'found', item };
|
||||
}
|
||||
|
||||
private async getMemory(
|
||||
filter: FederationScopeQueryFilter,
|
||||
id: string,
|
||||
): Promise<FederationGetQueryResult> {
|
||||
const [insightRow, preferenceRow] = await Promise.all([
|
||||
this.db
|
||||
.select({
|
||||
id: insights.id,
|
||||
userId: insights.userId,
|
||||
kind: insights.source,
|
||||
content: insights.content,
|
||||
category: insights.category,
|
||||
relevanceScore: insights.relevanceScore,
|
||||
metadata: insights.metadata,
|
||||
createdAt: insights.createdAt,
|
||||
updatedAt: insights.updatedAt,
|
||||
})
|
||||
.from(insights)
|
||||
.where(eq(insights.id, id))
|
||||
.limit(1)
|
||||
.then(firstRow),
|
||||
this.db
|
||||
.select({
|
||||
id: preferences.id,
|
||||
userId: preferences.userId,
|
||||
kind: preferences.category,
|
||||
key: preferences.key,
|
||||
value: preferences.value,
|
||||
source: preferences.source,
|
||||
mutable: preferences.mutable,
|
||||
createdAt: preferences.createdAt,
|
||||
updatedAt: preferences.updatedAt,
|
||||
})
|
||||
.from(preferences)
|
||||
.where(eq(preferences.id, id))
|
||||
.limit(1)
|
||||
.then(firstRow),
|
||||
]);
|
||||
|
||||
const candidates = [insightRow, preferenceRow].filter(
|
||||
(row): row is NonNullable<typeof row> => row !== undefined,
|
||||
);
|
||||
if (candidates.length === 0) {
|
||||
return { status: 'not_found' };
|
||||
}
|
||||
|
||||
if (!filter.includePersonal) {
|
||||
return { status: 'denied', reason: 'Memory personal rows are outside the federated scope' };
|
||||
}
|
||||
|
||||
const accessible = candidates.find((row) => row.userId === filter.subjectUserId);
|
||||
if (!accessible) {
|
||||
return { status: 'denied', reason: 'Memory row belongs to another subject user' };
|
||||
}
|
||||
|
||||
const item = { ...accessible } as RowObject;
|
||||
delete item['userId'];
|
||||
return { status: 'found', item };
|
||||
}
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
/**
|
||||
* Federation get verb (FED-M3-06).
|
||||
*
|
||||
* POST /api/federation/v1/get/:resource/:id
|
||||
*
|
||||
* Pipeline: FederationAuthGuard attaches the active grant context, then
|
||||
* FederationScopeService enforces grant scope + native RBAC intersection, then
|
||||
* the read-only query layer fetches one local row and tags it with `_source`.
|
||||
* Read audit-log writes are deferred to M4; this controller does not persist
|
||||
* request or response bodies.
|
||||
*/
|
||||
|
||||
import { Controller, HttpException, Inject, Param, Post, Req, UseGuards } from '@nestjs/common';
|
||||
import type { FastifyRequest } from 'fastify';
|
||||
import {
|
||||
FederationInvalidRequestError,
|
||||
FederationNotFoundError,
|
||||
FederationScopeViolationError,
|
||||
FederationUnauthorizedError,
|
||||
SOURCE_LOCAL,
|
||||
type FederationGetResponse,
|
||||
type SourceTag,
|
||||
} from '@mosaicstack/types';
|
||||
import { FederationAuthGuard } from '../federation-auth.guard.js';
|
||||
import '../federation-context.js';
|
||||
import { FederationScopeService } from '../scope.service.js';
|
||||
import { FederationGetQueryService } from './get-query.service.js';
|
||||
|
||||
type FederatedRow = Record<string, unknown> & SourceTag;
|
||||
|
||||
function scopeDenyToHttpException(deny: {
|
||||
readonly statusCode: 400 | 403;
|
||||
readonly message: string;
|
||||
}): HttpException {
|
||||
const ErrorClass =
|
||||
deny.statusCode === 400 ? FederationInvalidRequestError : FederationScopeViolationError;
|
||||
return new HttpException(new ErrorClass(deny.message, deny).toEnvelope(), deny.statusCode);
|
||||
}
|
||||
|
||||
@Controller('api/federation/v1/get')
|
||||
@UseGuards(FederationAuthGuard)
|
||||
export class GetController {
|
||||
constructor(
|
||||
@Inject(FederationScopeService) private readonly scope: FederationScopeService,
|
||||
@Inject(FederationGetQueryService) private readonly query: FederationGetQueryService,
|
||||
) {}
|
||||
|
||||
@Post(':resource/:id')
|
||||
async get(
|
||||
@Param('resource') resource: string,
|
||||
@Param('id') id: string,
|
||||
@Req() request: FastifyRequest,
|
||||
): Promise<FederationGetResponse<FederatedRow>> {
|
||||
if (!request.federationContext) {
|
||||
throw new HttpException(
|
||||
new FederationUnauthorizedError('Federation context missing').toEnvelope(),
|
||||
401,
|
||||
);
|
||||
}
|
||||
if (id.trim().length === 0) {
|
||||
throw new HttpException(
|
||||
new FederationInvalidRequestError('Federation get id must not be empty').toEnvelope(),
|
||||
400,
|
||||
);
|
||||
}
|
||||
|
||||
const scopeResult = await this.scope.evaluateAccess({
|
||||
context: request.federationContext,
|
||||
resource,
|
||||
requestedLimit: 1,
|
||||
nativeRbac: this.query,
|
||||
});
|
||||
|
||||
if (!scopeResult.allowed) {
|
||||
throw scopeDenyToHttpException(scopeResult.deny);
|
||||
}
|
||||
|
||||
const result = await this.query.get({ filter: scopeResult.filter, id });
|
||||
if (result.status === 'not_found') {
|
||||
throw new HttpException(
|
||||
new FederationNotFoundError('Requested federation resource was not found').toEnvelope(),
|
||||
404,
|
||||
);
|
||||
}
|
||||
if (result.status === 'denied') {
|
||||
throw new HttpException(
|
||||
new FederationScopeViolationError(result.reason, {
|
||||
resource,
|
||||
id,
|
||||
grantId: request.federationContext.grantId,
|
||||
peerId: request.federationContext.peerId,
|
||||
subjectUserId: request.federationContext.subjectUserId,
|
||||
}).toEnvelope(),
|
||||
403,
|
||||
);
|
||||
}
|
||||
|
||||
return { item: { ...result.item, _source: SOURCE_LOCAL } };
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
import { Module, type OnApplicationShutdown, Inject, Optional } from '@nestjs/common';
|
||||
import { Module, type OnApplicationShutdown, Inject } from '@nestjs/common';
|
||||
import { createQueue, type QueueHandle } from '@mosaicstack/queue';
|
||||
import type { MosaicConfig } from '@mosaicstack/config';
|
||||
import { MOSAIC_CONFIG } from '../config/config.module.js';
|
||||
import { SessionGCService } from './session-gc.service.js';
|
||||
import { REDIS } from './gc.tokens.js';
|
||||
|
||||
@@ -11,17 +9,13 @@ const GC_QUEUE_HANDLE = 'GC_QUEUE_HANDLE';
|
||||
providers: [
|
||||
{
|
||||
provide: GC_QUEUE_HANDLE,
|
||||
useFactory: (config: MosaicConfig | null): QueueHandle | null => {
|
||||
// On Local tier there is no Redis — skip the ioredis connection entirely.
|
||||
// The Valkey GC sweep is a no-op on Local (no session keys stored there).
|
||||
if (config?.queue?.type === 'local') return null;
|
||||
useFactory: (): QueueHandle => {
|
||||
return createQueue();
|
||||
},
|
||||
inject: [MOSAIC_CONFIG],
|
||||
},
|
||||
{
|
||||
provide: REDIS,
|
||||
useFactory: (handle: QueueHandle | null) => handle?.redis ?? null,
|
||||
useFactory: (handle: QueueHandle) => handle.redis,
|
||||
inject: [GC_QUEUE_HANDLE],
|
||||
},
|
||||
SessionGCService,
|
||||
@@ -29,13 +23,9 @@ const GC_QUEUE_HANDLE = 'GC_QUEUE_HANDLE';
|
||||
exports: [SessionGCService],
|
||||
})
|
||||
export class GCModule implements OnApplicationShutdown {
|
||||
constructor(
|
||||
@Optional()
|
||||
@Inject(GC_QUEUE_HANDLE)
|
||||
private readonly handle: QueueHandle | null,
|
||||
) {}
|
||||
constructor(@Inject(GC_QUEUE_HANDLE) private readonly handle: QueueHandle) {}
|
||||
|
||||
async onApplicationShutdown(): Promise<void> {
|
||||
await this.handle?.close().catch(() => {});
|
||||
await this.handle.close().catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ import { Logger } from '@nestjs/common';
|
||||
import type { QueueHandle } from '@mosaicstack/queue';
|
||||
import type { LogService } from '@mosaicstack/log';
|
||||
import { SessionGCService } from './session-gc.service.js';
|
||||
import { CommandAuthorizationService } from '../commands/command-authorization.service.js';
|
||||
|
||||
type MockRedis = {
|
||||
scan: ReturnType<typeof vi.fn>;
|
||||
@@ -13,12 +12,7 @@ type MockRedis = {
|
||||
describe('SessionGCService', () => {
|
||||
let service: SessionGCService;
|
||||
let mockRedis: MockRedis;
|
||||
let mockLogService: {
|
||||
logs: {
|
||||
promoteSessionToWarm: ReturnType<typeof vi.fn>;
|
||||
promoteToWarm: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
};
|
||||
let mockLogService: { logs: { promoteToWarm: ReturnType<typeof vi.fn> } };
|
||||
|
||||
/**
|
||||
* Helper: build a scan mock that returns all provided keys in a single
|
||||
@@ -36,7 +30,6 @@ describe('SessionGCService', () => {
|
||||
|
||||
mockLogService = {
|
||||
logs: {
|
||||
promoteSessionToWarm: vi.fn().mockResolvedValue(0),
|
||||
promoteToWarm: vi.fn().mockResolvedValue(0),
|
||||
},
|
||||
};
|
||||
@@ -66,89 +59,54 @@ describe('SessionGCService', () => {
|
||||
expect(result.cleaned.valkeyKeys).toBeUndefined();
|
||||
});
|
||||
|
||||
it('escapes glob metacharacters in a session identifier', async () => {
|
||||
await service.collect('abc*?[tenant]\\escape');
|
||||
|
||||
expect(mockRedis.scan).toHaveBeenCalledWith(
|
||||
'0',
|
||||
'MATCH',
|
||||
'mosaic:session:abc\\*\\?\\[tenant\\]\\\\escape:*',
|
||||
'COUNT',
|
||||
100,
|
||||
);
|
||||
});
|
||||
|
||||
it('preserves a valid durable approval after session GC', async () => {
|
||||
const entries = new Map<string, string>();
|
||||
const redis = {
|
||||
scan: vi.fn().mockResolvedValue(['0', ['mosaic:session:owned:state']]),
|
||||
get: vi.fn(async (key: string) => entries.get(key) ?? null),
|
||||
set: vi.fn(async (key: string, value: string) => entries.set(key, value)),
|
||||
del: vi.fn(async (...keys: string[]) => {
|
||||
let deleted = 0;
|
||||
for (const key of keys) deleted += Number(entries.delete(key));
|
||||
return deleted;
|
||||
}),
|
||||
};
|
||||
const authorization = new CommandAuthorizationService(
|
||||
{
|
||||
select: () => ({
|
||||
from: () => ({ where: () => ({ limit: async () => [{ role: 'admin' }] }) }),
|
||||
}),
|
||||
} as never,
|
||||
redis,
|
||||
);
|
||||
const command = {
|
||||
name: 'gc',
|
||||
description: 'System-wide garbage collection',
|
||||
aliases: [],
|
||||
scope: 'admin',
|
||||
execution: 'socket',
|
||||
available: true,
|
||||
} as never;
|
||||
const payload = { command: 'gc', conversationId: 'owned' };
|
||||
const approval = await authorization.createApproval(command, payload, 'admin-1');
|
||||
const approvalKey = `interaction:command-approval:${approval!.approvalId}`;
|
||||
const gc = new SessionGCService(redis as never, mockLogService as unknown as LogService);
|
||||
|
||||
await gc.collect('owned');
|
||||
|
||||
expect(entries.has(approvalKey)).toBe(true);
|
||||
await expect(
|
||||
authorization.authorize(command, payload, 'admin-1', approval!.approvalId),
|
||||
).resolves.toEqual({ allowed: true });
|
||||
});
|
||||
|
||||
it('collect() skips Valkey but still demotes only the requested session on local tier', async () => {
|
||||
const localService = new SessionGCService(null, mockLogService as unknown as LogService);
|
||||
|
||||
const result = await localService.collect('local-session');
|
||||
|
||||
expect(result.sessionId).toBe('local-session');
|
||||
expect(result.cleaned.valkeyKeys).toBeUndefined();
|
||||
expect(mockLogService.logs.promoteSessionToWarm).toHaveBeenCalledWith(
|
||||
'local-session',
|
||||
expect.any(Date),
|
||||
);
|
||||
});
|
||||
|
||||
it('collect() returns sessionId in result', async () => {
|
||||
const result = await service.collect('test-session-id');
|
||||
expect(result.sessionId).toBe('test-session-id');
|
||||
});
|
||||
|
||||
it('collect() demotes logs only for the requested session', async () => {
|
||||
await service.collect('owned-session');
|
||||
|
||||
expect(mockLogService.logs.promoteSessionToWarm).toHaveBeenCalledWith(
|
||||
'owned-session',
|
||||
expect.any(Date),
|
||||
);
|
||||
expect(mockLogService.logs.promoteToWarm).not.toHaveBeenCalled();
|
||||
it('fullCollect() deletes all session keys', async () => {
|
||||
mockRedis.scan = makeScanMock(['mosaic:session:abc:system', 'mosaic:session:xyz:foo']);
|
||||
const result = await service.fullCollect();
|
||||
expect(mockRedis.del).toHaveBeenCalled();
|
||||
expect(result.valkeyKeys).toBe(2);
|
||||
});
|
||||
|
||||
it('does not expose automatic global GC entry points', () => {
|
||||
expect('fullCollect' in service).toBe(false);
|
||||
expect('sweepOrphans' in service).toBe(false);
|
||||
it('fullCollect() with no keys returns 0 valkeyKeys', async () => {
|
||||
mockRedis.scan = makeScanMock([]);
|
||||
const result = await service.fullCollect();
|
||||
expect(result.valkeyKeys).toBe(0);
|
||||
expect(mockRedis.del).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('fullCollect() returns duration', async () => {
|
||||
const result = await service.fullCollect();
|
||||
expect(result.duration).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
|
||||
it('sweepOrphans() extracts unique session IDs and collects them', async () => {
|
||||
// First scan call returns the global session list; subsequent calls return
|
||||
// per-session keys during collect().
|
||||
mockRedis.scan = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce([
|
||||
'0',
|
||||
['mosaic:session:abc:system', 'mosaic:session:abc:messages', 'mosaic:session:xyz:system'],
|
||||
])
|
||||
// collect('abc') scan
|
||||
.mockResolvedValueOnce(['0', ['mosaic:session:abc:system', 'mosaic:session:abc:messages']])
|
||||
// collect('xyz') scan
|
||||
.mockResolvedValueOnce(['0', ['mosaic:session:xyz:system']]);
|
||||
mockRedis.del.mockResolvedValue(1);
|
||||
|
||||
const result = await service.sweepOrphans();
|
||||
expect(result.orphanedSessions).toBeGreaterThanOrEqual(0);
|
||||
expect(result.duration).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
|
||||
it('sweepOrphans() returns empty when no session keys', async () => {
|
||||
mockRedis.scan = makeScanMock([]);
|
||||
const result = await service.sweepOrphans();
|
||||
expect(result.orphanedSessions).toBe(0);
|
||||
expect(result.totalCleaned).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Inject, Injectable, Optional } from '@nestjs/common';
|
||||
import { Inject, Injectable, Logger, type OnModuleInit } from '@nestjs/common';
|
||||
import type { QueueHandle } from '@mosaicstack/queue';
|
||||
import type { LogService } from '@mosaicstack/log';
|
||||
import { LOG_SERVICE } from '../log/log.tokens.js';
|
||||
@@ -13,29 +13,55 @@ export interface GCResult {
|
||||
};
|
||||
}
|
||||
|
||||
/** Escape Redis glob metacharacters so a session identifier is always literal. */
|
||||
function escapeRedisGlobLiteral(value: string): string {
|
||||
return value.replace(/[\\*?\[\]]/g, '\\$&');
|
||||
export interface GCSweepResult {
|
||||
orphanedSessions: number;
|
||||
totalCleaned: GCResult[];
|
||||
duration: number;
|
||||
}
|
||||
|
||||
export interface FullGCResult {
|
||||
valkeyKeys: number;
|
||||
logsDemoted: number;
|
||||
jobsPurged: number;
|
||||
tempFilesRemoved: number;
|
||||
duration: number;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class SessionGCService {
|
||||
export class SessionGCService implements OnModuleInit {
|
||||
private readonly logger = new Logger(SessionGCService.name);
|
||||
|
||||
constructor(
|
||||
// Local tier has no Redis; lifecycle cleanup still demotes this session's logs.
|
||||
@Optional()
|
||||
@Inject(REDIS)
|
||||
private readonly redis: QueueHandle['redis'] | null,
|
||||
@Inject(REDIS) private readonly redis: QueueHandle['redis'],
|
||||
@Inject(LOG_SERVICE) private readonly logService: LogService,
|
||||
) {}
|
||||
|
||||
onModuleInit(): void {
|
||||
// Fire-and-forget: run full GC asynchronously so it does not block the
|
||||
// NestJS bootstrap chain. Cold-start GC typically takes 100–500 ms
|
||||
// depending on Valkey key count; deferring it removes that latency from
|
||||
// the TTFB of the first HTTP request.
|
||||
this.fullCollect()
|
||||
.then((result) => {
|
||||
this.logger.log(
|
||||
`Full GC complete: ${result.valkeyKeys} Valkey keys, ` +
|
||||
`${result.logsDemoted} logs demoted, ` +
|
||||
`${result.jobsPurged} jobs purged, ` +
|
||||
`${result.tempFilesRemoved} temp dirs removed ` +
|
||||
`(${result.duration}ms)`,
|
||||
);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
this.logger.error('Cold-start GC failed', err instanceof Error ? err.stack : String(err));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan Valkey for all keys matching a pattern using SCAN (non-blocking).
|
||||
* KEYS is avoided because it blocks the Valkey event loop for the full scan
|
||||
* duration, which can cause latency spikes under production key volumes.
|
||||
* Returns an empty population on the Local tier where Redis is disabled.
|
||||
*/
|
||||
private async scanKeys(pattern: string): Promise<string[]> {
|
||||
if (!this.redis) return [];
|
||||
const collected: string[] = [];
|
||||
let cursor = '0';
|
||||
do {
|
||||
@@ -52,23 +78,87 @@ export class SessionGCService {
|
||||
async collect(sessionId: string): Promise<GCResult> {
|
||||
const result: GCResult = { sessionId, cleaned: {} };
|
||||
|
||||
// 1. Valkey: delete all session-scoped keys (skipped on Local tier).
|
||||
if (this.redis) {
|
||||
const pattern = `mosaic:session:${escapeRedisGlobLiteral(sessionId)}:*`;
|
||||
const valkeyKeys = await this.scanKeys(pattern);
|
||||
if (valkeyKeys.length > 0) {
|
||||
await this.redis.del(...valkeyKeys);
|
||||
result.cleaned.valkeyKeys = valkeyKeys.length;
|
||||
}
|
||||
// 1. Valkey: delete all session-scoped keys
|
||||
const pattern = `mosaic:session:${sessionId}:*`;
|
||||
const valkeyKeys = await this.scanKeys(pattern);
|
||||
if (valkeyKeys.length > 0) {
|
||||
await this.redis.del(...valkeyKeys);
|
||||
result.cleaned.valkeyKeys = valkeyKeys.length;
|
||||
}
|
||||
|
||||
// 2. PG: demote hot-tier agent logs for this session only.
|
||||
const cutoff = new Date();
|
||||
const logsDemoted = await this.logService.logs.promoteSessionToWarm(sessionId, cutoff);
|
||||
// 2. PG: demote hot-tier agent_logs for this session to warm
|
||||
const cutoff = new Date(); // demote all hot logs for this session
|
||||
const logsDemoted = await this.logService.logs.promoteToWarm(cutoff);
|
||||
if (logsDemoted > 0) {
|
||||
result.cleaned.logsDemoted = logsDemoted;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sweep GC — find orphaned artifacts from dead sessions.
|
||||
* System-wide operation: only call from admin-authorized paths or internal
|
||||
* scheduled jobs. Individual session cleanup is handled by collect().
|
||||
*/
|
||||
async sweepOrphans(): Promise<GCSweepResult> {
|
||||
const start = Date.now();
|
||||
const cleaned: GCResult[] = [];
|
||||
|
||||
// 1. Find all session-scoped Valkey keys (non-blocking SCAN)
|
||||
const allSessionKeys = await this.scanKeys('mosaic:session:*');
|
||||
|
||||
// Extract unique session IDs from keys
|
||||
const sessionIds = new Set<string>();
|
||||
for (const key of allSessionKeys) {
|
||||
const match = key.match(/^mosaic:session:([^:]+):/);
|
||||
if (match) sessionIds.add(match[1]!);
|
||||
}
|
||||
|
||||
// 2. For each session ID, collect stale keys
|
||||
for (const sessionId of sessionIds) {
|
||||
const gcResult = await this.collect(sessionId);
|
||||
if (Object.keys(gcResult.cleaned).length > 0) {
|
||||
cleaned.push(gcResult);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
orphanedSessions: cleaned.length,
|
||||
totalCleaned: cleaned,
|
||||
duration: Date.now() - start,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Full GC — aggressive collection for cold start.
|
||||
* Assumes no sessions survived the restart.
|
||||
*/
|
||||
async fullCollect(): Promise<FullGCResult> {
|
||||
const start = Date.now();
|
||||
|
||||
// 1. Valkey: delete ALL session-scoped keys (non-blocking SCAN)
|
||||
const sessionKeys = await this.scanKeys('mosaic:session:*');
|
||||
if (sessionKeys.length > 0) {
|
||||
await this.redis.del(...sessionKeys);
|
||||
}
|
||||
|
||||
// 2. NOTE: channel keys are NOT collected on cold start
|
||||
// (discord/telegram plugins may reconnect and resume)
|
||||
|
||||
// 3. PG: demote stale hot-tier logs older than 24h to warm
|
||||
const hotCutoff = new Date(Date.now() - 24 * 60 * 60 * 1000);
|
||||
const logsDemoted = await this.logService.logs.promoteToWarm(hotCutoff);
|
||||
|
||||
// 4. No summarization job purge API available yet
|
||||
const jobsPurged = 0;
|
||||
|
||||
return {
|
||||
valkeyKeys: sessionKeys.length,
|
||||
logsDemoted,
|
||||
jobsPurged,
|
||||
tempFilesRemoved: 0,
|
||||
duration: Date.now() - start,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,164 +0,0 @@
|
||||
import 'reflect-metadata';
|
||||
import {
|
||||
type CanActivate,
|
||||
type ExecutionContext,
|
||||
type INestApplication,
|
||||
ValidationPipe,
|
||||
} from '@nestjs/common';
|
||||
import { FastifyAdapter, type NestFastifyApplication } from '@nestjs/platform-fastify';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import request from 'supertest';
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { AuthGuard } from '../auth/auth.guard.js';
|
||||
import { HarnessRegistry } from './harness.registry.js';
|
||||
import { HARNESS_REGISTRY } from './harness.tokens.js';
|
||||
import { HarnessSelectionRepository } from './harness-selection.repository.js';
|
||||
import { FakeHarnessAdapter } from './testing/fake-harness.adapter.js';
|
||||
// Import the REAL module (not a hand-listed controllers+mocks list) so an
|
||||
// unresolved provider fails at app.init() — the #1145-class DI-boot guard.
|
||||
import { HarnessModule } from './harness.module.js';
|
||||
|
||||
// A known-available tuple from the fake adapter's default catalog.
|
||||
const VALID = { harnessId: 'fake', providerId: 'fake-openai', modelId: 'fake-mini' };
|
||||
// A tuple whose provider/model are not in any catalog.
|
||||
const UNKNOWN = { harnessId: 'fake', providerId: 'ghost-provider', modelId: 'ghost-model' };
|
||||
// A tuple that is known in the catalog but flagged unavailable.
|
||||
const UNAVAILABLE = { harnessId: 'fake', providerId: 'fake-openai', modelId: 'fake-legacy' };
|
||||
|
||||
const authGuard: CanActivate = {
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const requestContext = context.switchToHttp().getRequest<{ user?: { id: string } }>();
|
||||
requestContext.user = { id: 'user-1' };
|
||||
return true;
|
||||
},
|
||||
};
|
||||
|
||||
function registryWithFake(): HarnessRegistry {
|
||||
const registry = new HarnessRegistry();
|
||||
registry.register(new FakeHarnessAdapter({ id: 'fake' }));
|
||||
return registry;
|
||||
}
|
||||
|
||||
describe('Harness selection HTTP surface', () => {
|
||||
let app: INestApplication;
|
||||
let repository: HarnessSelectionRepository;
|
||||
|
||||
beforeAll(async () => {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [HarnessModule],
|
||||
})
|
||||
.overrideGuard(AuthGuard)
|
||||
.useValue(authGuard)
|
||||
.overrideProvider(HARNESS_REGISTRY)
|
||||
.useValue(registryWithFake())
|
||||
.compile();
|
||||
|
||||
// Real in-memory repository from the module graph — proves the module wired it.
|
||||
repository = moduleRef.get(HarnessSelectionRepository);
|
||||
|
||||
app = moduleRef.createNestApplication<NestFastifyApplication>(new FastifyAdapter());
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }),
|
||||
);
|
||||
await app.init();
|
||||
await app.getHttpAdapter().getInstance().ready();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
// Reset owner-scoped state between tests via the public API surface.
|
||||
repository.set({ userId: 'user-1', tenantId: 'user-1' }, VALID);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('GET selection is server-scoped and ignores caller-supplied scope in the query', async () => {
|
||||
const response = await request(app.getHttpServer())
|
||||
.get('/api/chat/preferences/selection')
|
||||
.query({ userId: 'attacker', tenantId: 'attacker-tenant', seatId: 'attacker-seat' });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
// The returned selection is user-1's (guard-derived scope), not the query's.
|
||||
expect(response.body.selection).toEqual(VALID);
|
||||
});
|
||||
|
||||
it('PUT with a valid structured tuple persists and round-trips via GET', async () => {
|
||||
const next = { harnessId: 'fake', providerId: 'fake-openai', modelId: 'fake-pro' };
|
||||
|
||||
const put = await request(app.getHttpServer())
|
||||
.put('/api/chat/preferences/selection')
|
||||
.send(next)
|
||||
.set('Content-Type', 'application/json');
|
||||
expect(put.status).toBe(200);
|
||||
expect(put.body.selection).toEqual(next);
|
||||
|
||||
const get = await request(app.getHttpServer()).get('/api/chat/preferences/selection');
|
||||
expect(get.status).toBe(200);
|
||||
expect(get.body.selection).toEqual(next);
|
||||
});
|
||||
|
||||
it('PUT with FREE TEXT is rejected 400 and does not mutate the stored selection', async () => {
|
||||
const response = await request(app.getHttpServer())
|
||||
.put('/api/chat/preferences/selection')
|
||||
.send({ selection: 'gpt-4o' })
|
||||
.set('Content-Type', 'application/json');
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
|
||||
const get = await request(app.getHttpServer()).get('/api/chat/preferences/selection');
|
||||
expect(get.body.selection).toEqual(VALID);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['seatId', { ...VALID, seatId: 'attacker-seat' }],
|
||||
['tenantId', { ...VALID, tenantId: 'attacker-tenant' }],
|
||||
['userId', { ...VALID, userId: 'attacker' }],
|
||||
['nativeSessionPath', { ...VALID, nativeSessionPath: '/var/native/x.jsonl' }],
|
||||
['executable', { ...VALID, executable: '/usr/bin/evil' }],
|
||||
['home', { ...VALID, home: '/home/attacker' }],
|
||||
['cwd', { ...VALID, cwd: '/tmp/attacker' }],
|
||||
])(
|
||||
'PUT with an extra authority-bearing field (%s) is rejected 400 and does not mutate stored selection',
|
||||
async (_name, body) => {
|
||||
const response = await request(app.getHttpServer())
|
||||
.put('/api/chat/preferences/selection')
|
||||
.send(body)
|
||||
.set('Content-Type', 'application/json');
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
|
||||
const get = await request(app.getHttpServer()).get('/api/chat/preferences/selection');
|
||||
expect(get.body.selection).toEqual(VALID);
|
||||
},
|
||||
);
|
||||
|
||||
it('PUT with an UNKNOWN tuple returns selection_invalid, unchanged and echoed unchanged (no fallback)', async () => {
|
||||
const response = await request(app.getHttpServer())
|
||||
.put('/api/chat/preferences/selection')
|
||||
.send(UNKNOWN)
|
||||
.set('Content-Type', 'application/json');
|
||||
|
||||
expect(response.status).toBe(422);
|
||||
expect(response.body.code).toBe('selection_invalid');
|
||||
// Echoed back unchanged: no first-row / first-provider substitution.
|
||||
expect(response.body.selection).toEqual(UNKNOWN);
|
||||
|
||||
const get = await request(app.getHttpServer()).get('/api/chat/preferences/selection');
|
||||
expect(get.body.selection).toEqual(VALID);
|
||||
});
|
||||
|
||||
it('PUT with a KNOWN-but-UNAVAILABLE tuple returns model_unavailable, unchanged (distinct from selection_invalid)', async () => {
|
||||
const response = await request(app.getHttpServer())
|
||||
.put('/api/chat/preferences/selection')
|
||||
.send(UNAVAILABLE)
|
||||
.set('Content-Type', 'application/json');
|
||||
|
||||
expect(response.status).toBe(422);
|
||||
expect(response.body.code).toBe('model_unavailable');
|
||||
expect(response.body.selection).toEqual(UNAVAILABLE);
|
||||
|
||||
const get = await request(app.getHttpServer()).get('/api/chat/preferences/selection');
|
||||
expect(get.body.selection).toEqual(VALID);
|
||||
});
|
||||
});
|
||||
@@ -1,46 +0,0 @@
|
||||
import { Body, Controller, Get, HttpException, HttpStatus, Put, UseGuards } from '@nestjs/common';
|
||||
import { AuthGuard } from '../auth/auth.guard.js';
|
||||
import { CurrentUser } from '../auth/current-user.decorator.js';
|
||||
import { scopeFromUser, type AuthenticatedUserLike } from '../auth/session-scope.js';
|
||||
import { HarnessOperationError } from './harness.registry.js';
|
||||
import { HarnessSelectionService } from './harness-selection.service.js';
|
||||
import { HarnessSelectionInputDto, type SelectionResponseDto } from './harness.dto.js';
|
||||
|
||||
/**
|
||||
* Chat-preferences selection surface. The scope is ALWAYS derived on the server
|
||||
* from the authenticated user (`scopeFromUser(CurrentUser)`); the request body and
|
||||
* query string can never name another user, tenant, or seat. A typed selection
|
||||
* failure (unknown tuple → `selection_invalid`, known-but-unavailable →
|
||||
* `model_unavailable`) is returned as 422 with the requested tuple echoed back
|
||||
* unchanged, and never mutates the stored selection.
|
||||
*/
|
||||
@Controller('api/chat/preferences/selection')
|
||||
@UseGuards(AuthGuard)
|
||||
export class HarnessSelectionController {
|
||||
constructor(private readonly selection: HarnessSelectionService) {}
|
||||
|
||||
@Get()
|
||||
get(@CurrentUser() user: AuthenticatedUserLike): SelectionResponseDto {
|
||||
return { selection: this.selection.getSelection(scopeFromUser(user)) };
|
||||
}
|
||||
|
||||
@Put()
|
||||
async put(
|
||||
@CurrentUser() user: AuthenticatedUserLike,
|
||||
@Body() dto: HarnessSelectionInputDto,
|
||||
): Promise<SelectionResponseDto> {
|
||||
try {
|
||||
const stored = await this.selection.setSelection(scopeFromUser(user), {
|
||||
harnessId: dto.harnessId,
|
||||
providerId: dto.providerId,
|
||||
modelId: dto.modelId,
|
||||
});
|
||||
return { selection: stored };
|
||||
} catch (error) {
|
||||
if (error instanceof HarnessOperationError) {
|
||||
throw new HttpException(error.dto, HttpStatus.UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -1,90 +0,0 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import type { HarnessSelection } from '@mosaicstack/types';
|
||||
import type { ActorTenantScope } from '../auth/session-scope.js';
|
||||
import {
|
||||
HarnessAdapterUnavailableError,
|
||||
HarnessRegistry,
|
||||
operationError,
|
||||
} from './harness.registry.js';
|
||||
import { HARNESS_REGISTRY } from './harness.tokens.js';
|
||||
import { readContextFromScope } from './harness.dto.js';
|
||||
import { HarnessSelectionRepository } from './harness-selection.repository.js';
|
||||
|
||||
/**
|
||||
* Selection logic for the Slice-Zero chat-preferences surface. It validates the
|
||||
* requested harness/provider/model tuple against the live catalog with NO
|
||||
* fallback substitution, then persists it owner-scoped. The stored selection is
|
||||
* only ever mutated when the tuple is valid AND available.
|
||||
*/
|
||||
@Injectable()
|
||||
export class HarnessSelectionService {
|
||||
constructor(
|
||||
@Inject(HARNESS_REGISTRY) private readonly registry: HarnessRegistry,
|
||||
private readonly repository: HarnessSelectionRepository,
|
||||
) {}
|
||||
|
||||
getSelection(scope: ActorTenantScope): HarnessSelection | null {
|
||||
return this.repository.get(scope);
|
||||
}
|
||||
|
||||
async setSelection(
|
||||
scope: ActorTenantScope,
|
||||
selection: HarnessSelection,
|
||||
): Promise<HarnessSelection> {
|
||||
// Throws HarnessOperationError (selection_invalid / model_unavailable) with the
|
||||
// requested tuple echoed back unchanged. The store is untouched on any throw.
|
||||
await this.assertSelectionAvailable(scope, selection);
|
||||
return this.repository.set(scope, selection);
|
||||
}
|
||||
|
||||
private async assertSelectionAvailable(
|
||||
scope: ActorTenantScope,
|
||||
selection: HarnessSelection,
|
||||
): Promise<void> {
|
||||
const correlationId = randomUUID();
|
||||
|
||||
let adapter;
|
||||
try {
|
||||
adapter = this.registry.get(selection.harnessId);
|
||||
} catch (error) {
|
||||
if (error instanceof HarnessAdapterUnavailableError) {
|
||||
// An unknown harness makes the whole tuple invalid — no fallback adapter.
|
||||
throw operationError(
|
||||
'selection_invalid',
|
||||
'The requested harness/provider/model tuple is not in the catalog.',
|
||||
selection,
|
||||
correlationId,
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const catalog = await adapter.catalog(readContextFromScope(scope));
|
||||
const entry = catalog.models.find(
|
||||
(candidate) =>
|
||||
candidate.harnessId === selection.harnessId &&
|
||||
candidate.providerId === selection.providerId &&
|
||||
candidate.modelId === selection.modelId,
|
||||
);
|
||||
|
||||
if (!entry) {
|
||||
// No first-row / first-provider fallback: reject the requested tuple unchanged.
|
||||
throw operationError(
|
||||
'selection_invalid',
|
||||
'The requested harness/provider/model tuple is not in the catalog.',
|
||||
selection,
|
||||
correlationId,
|
||||
);
|
||||
}
|
||||
if (entry.availability === 'unavailable') {
|
||||
throw operationError(
|
||||
'model_unavailable',
|
||||
'The requested model is currently unavailable.',
|
||||
selection,
|
||||
correlationId,
|
||||
true,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
import 'reflect-metadata';
|
||||
import {
|
||||
type CanActivate,
|
||||
type ExecutionContext,
|
||||
type INestApplication,
|
||||
ValidationPipe,
|
||||
} from '@nestjs/common';
|
||||
import { FastifyAdapter, type NestFastifyApplication } from '@nestjs/platform-fastify';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import request from 'supertest';
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { AuthGuard } from '../auth/auth.guard.js';
|
||||
import { HarnessRegistry } from './harness.registry.js';
|
||||
import { HARNESS_REGISTRY } from './harness.tokens.js';
|
||||
import { FakeHarnessAdapter } from './testing/fake-harness.adapter.js';
|
||||
// The real module under test — importing it (not a hand-listed controllers/mocks
|
||||
// list) is what makes an unresolved provider fail loudly at app.init() (#1145 guard).
|
||||
import { HarnessModule } from './harness.module.js';
|
||||
|
||||
// Fields that must NEVER surface on a browser-facing catalog/list response.
|
||||
const FORBIDDEN_KEYS = [
|
||||
'executable',
|
||||
'executablePath',
|
||||
'home',
|
||||
'homeDir',
|
||||
'cwd',
|
||||
'workingDir',
|
||||
'workingDirectory',
|
||||
'nativeSessionPath',
|
||||
'sessionPath',
|
||||
'env',
|
||||
'secret',
|
||||
'secrets',
|
||||
'token',
|
||||
'apiKey',
|
||||
];
|
||||
|
||||
function assertNoForbiddenLeak(payload: unknown): void {
|
||||
const serialized = JSON.stringify(payload).toLowerCase();
|
||||
for (const key of FORBIDDEN_KEYS) {
|
||||
expect(serialized).not.toContain(key.toLowerCase());
|
||||
}
|
||||
}
|
||||
|
||||
const authGuard: CanActivate = {
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const requestContext = context.switchToHttp().getRequest<{ user?: { id: string } }>();
|
||||
requestContext.user = { id: 'user-1' };
|
||||
return true;
|
||||
},
|
||||
};
|
||||
|
||||
function registryWithFake(): HarnessRegistry {
|
||||
const registry = new HarnessRegistry();
|
||||
registry.register(new FakeHarnessAdapter({ id: 'fake' }));
|
||||
return registry;
|
||||
}
|
||||
|
||||
describe('Harness catalog HTTP surface', () => {
|
||||
let app: INestApplication;
|
||||
|
||||
beforeAll(async () => {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [HarnessModule],
|
||||
})
|
||||
.overrideGuard(AuthGuard)
|
||||
.useValue(authGuard)
|
||||
.overrideProvider(HARNESS_REGISTRY)
|
||||
.useValue(registryWithFake())
|
||||
.compile();
|
||||
|
||||
app = moduleRef.createNestApplication<NestFastifyApplication>(new FastifyAdapter());
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }),
|
||||
);
|
||||
await app.init();
|
||||
await app.getHttpAdapter().getInstance().ready();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('boots the real HarnessModule so all providers resolve at app.init()', () => {
|
||||
// If HarnessModule failed to resolve a provider, beforeAll's app.init() would
|
||||
// have thrown and this suite would never reach here.
|
||||
expect(app).toBeDefined();
|
||||
});
|
||||
|
||||
it('GET /api/harnesses returns 200 with safe fields only', async () => {
|
||||
const response = await request(app.getHttpServer()).get('/api/harnesses');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(Array.isArray(response.body)).toBe(true);
|
||||
expect(response.body.length).toBeGreaterThan(0);
|
||||
const summary = response.body[0];
|
||||
expect(Object.keys(summary).sort()).toEqual(['capabilities', 'displayName', 'id']);
|
||||
expect(summary.id).toBe('fake');
|
||||
expect(typeof summary.displayName).toBe('string');
|
||||
expect(Array.isArray(summary.capabilities)).toBe(true);
|
||||
assertNoForbiddenLeak(response.body);
|
||||
});
|
||||
|
||||
it('GET /api/harnesses/:harnessId/catalog returns 200 with safe catalog fields only', async () => {
|
||||
const response = await request(app.getHttpServer()).get('/api/harnesses/fake/catalog');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body.harnessId).toBe('fake');
|
||||
expect(typeof response.body.version).toBe('string');
|
||||
expect(typeof response.body.fingerprint).toBe('string');
|
||||
expect(Array.isArray(response.body.models)).toBe(true);
|
||||
expect(response.body.models.length).toBeGreaterThan(0);
|
||||
const entry = response.body.models[0];
|
||||
// Whitelisted catalog-entry fields only (no executables/paths/secrets).
|
||||
expect(Object.keys(entry).sort()).toEqual(
|
||||
[
|
||||
'authState',
|
||||
'availability',
|
||||
'displayName',
|
||||
'harnessId',
|
||||
'inputTypes',
|
||||
'modelId',
|
||||
'providerId',
|
||||
'reasoningCapability',
|
||||
].sort(),
|
||||
);
|
||||
assertNoForbiddenLeak(response.body);
|
||||
});
|
||||
|
||||
it('GET catalog for an unknown harnessId returns a typed adapter_unavailable error, never a fallback catalog', async () => {
|
||||
const response = await request(app.getHttpServer()).get('/api/harnesses/ghost-harness/catalog');
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
expect(response.body.code).toBe('adapter_unavailable');
|
||||
// A fallback catalog would carry a models array; a typed error must not.
|
||||
expect(response.body.models).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,65 +0,0 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Inject,
|
||||
Param,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { AuthGuard } from '../auth/auth.guard.js';
|
||||
import { CurrentUser } from '../auth/current-user.decorator.js';
|
||||
import { scopeFromUser, type AuthenticatedUserLike } from '../auth/session-scope.js';
|
||||
import { HarnessAdapterUnavailableError, HarnessRegistry } from './harness.registry.js';
|
||||
import { HARNESS_REGISTRY } from './harness.tokens.js';
|
||||
import {
|
||||
readContextFromScope,
|
||||
toHarnessSummary,
|
||||
toSafeCatalog,
|
||||
type HarnessCatalogDto,
|
||||
type HarnessSummaryDto,
|
||||
} from './harness.dto.js';
|
||||
|
||||
/**
|
||||
* Generic harness catalog surface. It exposes only harness-neutral, browser-safe
|
||||
* fields (identity, capabilities, provider/model catalog) — never executables,
|
||||
* native paths, home/cwd, env, or secrets. There is NO provider-probe route here;
|
||||
* `/api/providers` and `POST /api/providers/test` are intentionally out of scope.
|
||||
*/
|
||||
@Controller('api/harnesses')
|
||||
@UseGuards(AuthGuard)
|
||||
export class HarnessController {
|
||||
constructor(@Inject(HARNESS_REGISTRY) private readonly registry: HarnessRegistry) {}
|
||||
|
||||
@Get()
|
||||
async list(@CurrentUser() user: AuthenticatedUserLike): Promise<HarnessSummaryDto[]> {
|
||||
const context = readContextFromScope(scopeFromUser(user));
|
||||
const summaries: HarnessSummaryDto[] = [];
|
||||
for (const adapter of this.registry.list()) {
|
||||
summaries.push(toHarnessSummary(await adapter.describe(context)));
|
||||
}
|
||||
return summaries;
|
||||
}
|
||||
|
||||
@Get(':harnessId/catalog')
|
||||
async catalog(
|
||||
@CurrentUser() user: AuthenticatedUserLike,
|
||||
@Param('harnessId') harnessId: string,
|
||||
): Promise<HarnessCatalogDto> {
|
||||
const context = readContextFromScope(scopeFromUser(user));
|
||||
let adapter;
|
||||
try {
|
||||
adapter = this.registry.get(harnessId);
|
||||
} catch (error) {
|
||||
if (error instanceof HarnessAdapterUnavailableError) {
|
||||
// Typed failure — NEVER a fallback catalog for an unknown harness id.
|
||||
throw new HttpException(
|
||||
{ code: error.code, message: error.message, harnessId },
|
||||
HttpStatus.NOT_FOUND,
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
return toSafeCatalog(await adapter.catalog(context));
|
||||
}
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
import type {
|
||||
HarnessActorContext,
|
||||
HarnessAuthState,
|
||||
HarnessCapability,
|
||||
HarnessCatalog,
|
||||
HarnessCatalogEntry,
|
||||
HarnessDescriptor,
|
||||
HarnessInputType,
|
||||
HarnessModelAvailability,
|
||||
HarnessSelection,
|
||||
} from '@mosaicstack/types';
|
||||
import type { ActorTenantScope } from '../auth/session-scope.js';
|
||||
|
||||
/**
|
||||
* Structured selection tuple accepted on `PUT /api/chat/preferences/selection`.
|
||||
*
|
||||
* The body is a STRUCTURED tuple (harness + provider + model), never a free-text
|
||||
* model string. With `ValidationPipe({ whitelist: true, forbidNonWhitelisted: true })`
|
||||
* any extra property — including smuggled server-authority fields such as
|
||||
* `seatId`, `tenantId`, `userId`, `nativeSessionPath`, `executable`, `home`, `cwd` —
|
||||
* is rejected with 400. There is deliberately no field through which a caller can
|
||||
* name a scope; scope is derived on the server from the authenticated session.
|
||||
*/
|
||||
export class HarnessSelectionInputDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
harnessId!: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
providerId!: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
modelId!: string;
|
||||
}
|
||||
|
||||
/** Browser-safe harness summary — identity and capabilities only. */
|
||||
export interface HarnessSummaryDto {
|
||||
readonly id: string;
|
||||
readonly displayName: string;
|
||||
readonly capabilities: readonly HarnessCapability[];
|
||||
}
|
||||
|
||||
/** Browser-safe catalog entry — no executables, paths, secrets, or env. */
|
||||
export interface HarnessCatalogEntryDto {
|
||||
readonly harnessId: string;
|
||||
readonly providerId: string;
|
||||
readonly modelId: string;
|
||||
readonly displayName: string;
|
||||
readonly reasoningCapability: boolean;
|
||||
readonly inputTypes: readonly HarnessInputType[];
|
||||
readonly authState: HarnessAuthState;
|
||||
readonly availability: HarnessModelAvailability;
|
||||
}
|
||||
|
||||
/** Browser-safe catalog envelope. */
|
||||
export interface HarnessCatalogDto {
|
||||
readonly harnessId: string;
|
||||
readonly version: string;
|
||||
readonly fingerprint: string;
|
||||
readonly models: readonly HarnessCatalogEntryDto[];
|
||||
}
|
||||
|
||||
/** Response envelope for the caller's current selection (null when unset). */
|
||||
export interface SelectionResponseDto {
|
||||
readonly selection: HarnessSelection | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive a server-trusted {@link HarnessActorContext} for read operations from the
|
||||
* session-derived {@link ActorTenantScope}. All authority originates on the server;
|
||||
* nothing here is caller-supplied. A fresh correlation id is minted per call.
|
||||
*/
|
||||
export function readContextFromScope(scope: ActorTenantScope): HarnessActorContext {
|
||||
return {
|
||||
actorId: scope.userId,
|
||||
tenantId: scope.tenantId,
|
||||
seatId: scope.userId,
|
||||
correlationId: randomUUID(),
|
||||
};
|
||||
}
|
||||
|
||||
/** Project a descriptor onto the browser-safe summary shape (whitelist by construction). */
|
||||
export function toHarnessSummary(descriptor: HarnessDescriptor): HarnessSummaryDto {
|
||||
return {
|
||||
id: descriptor.id,
|
||||
displayName: descriptor.displayName,
|
||||
capabilities: [...descriptor.capabilities],
|
||||
};
|
||||
}
|
||||
|
||||
/** Project a catalog onto the browser-safe shape (whitelist by construction). */
|
||||
export function toSafeCatalog(catalog: HarnessCatalog): HarnessCatalogDto {
|
||||
return {
|
||||
harnessId: catalog.harnessId,
|
||||
version: catalog.version,
|
||||
fingerprint: catalog.fingerprint,
|
||||
models: catalog.models.map(toSafeCatalogEntry),
|
||||
};
|
||||
}
|
||||
|
||||
function toSafeCatalogEntry(entry: HarnessCatalogEntry): HarnessCatalogEntryDto {
|
||||
return {
|
||||
harnessId: entry.harnessId,
|
||||
providerId: entry.providerId,
|
||||
modelId: entry.modelId,
|
||||
displayName: entry.displayName,
|
||||
reasoningCapability: entry.reasoningCapability,
|
||||
inputTypes: [...entry.inputTypes],
|
||||
authState: entry.authState,
|
||||
availability: entry.availability,
|
||||
};
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { HarnessRegistry } from './harness.registry.js';
|
||||
import { HarnessService } from './harness.service.js';
|
||||
import {
|
||||
HARNESS_CONVERSATION_SERVICE,
|
||||
HARNESS_CONVERSATION_SERVICE_UNAVAILABLE,
|
||||
HARNESS_REGISTRY,
|
||||
HARNESS_SERVICE,
|
||||
} from './harness.tokens.js';
|
||||
import { HarnessController } from './harness.controller.js';
|
||||
import { HarnessSelectionController } from './harness-selection.controller.js';
|
||||
import { HarnessSelectionService } from './harness-selection.service.js';
|
||||
import { HarnessSelectionRepository } from './harness-selection.repository.js';
|
||||
|
||||
/**
|
||||
* Wires the harness-neutral registry/service (Task Two) together with the
|
||||
* Slice-Zero catalog and selection HTTP surfaces (Task Three).
|
||||
*
|
||||
* The registry is provided empty here; real harness adapters are registered in a
|
||||
* later task. Because the controllers/services resolve their collaborators through
|
||||
* this real module graph, an unresolved provider fails loudly at `app.init()`.
|
||||
*/
|
||||
@Module({
|
||||
controllers: [HarnessController, HarnessSelectionController],
|
||||
providers: [
|
||||
{ provide: HARNESS_REGISTRY, useFactory: () => new HarnessRegistry() },
|
||||
{ provide: HARNESS_SERVICE, useClass: HarnessService },
|
||||
// Task Five: bind the conversation-service token to its explicit "not yet bound"
|
||||
// sentinel. The pi-rpc router treats this as a hard, typed startup failure; Task 14
|
||||
// replaces it with a real service. Exported so ChatModule's router can inject it.
|
||||
{ provide: HARNESS_CONVERSATION_SERVICE, useValue: HARNESS_CONVERSATION_SERVICE_UNAVAILABLE },
|
||||
HarnessSelectionRepository,
|
||||
HarnessSelectionService,
|
||||
],
|
||||
exports: [HARNESS_REGISTRY, HARNESS_SERVICE, HARNESS_CONVERSATION_SERVICE],
|
||||
})
|
||||
export class HarnessModule {}
|
||||
@@ -1,69 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
HarnessAdapterUnavailableError,
|
||||
HarnessRegistrationError,
|
||||
HarnessRegistry,
|
||||
} from './harness.registry.js';
|
||||
import { FakeHarnessAdapter } from './testing/fake-harness.adapter.js';
|
||||
|
||||
describe('HarnessRegistry', () => {
|
||||
it('registers and looks up an adapter by harness id', () => {
|
||||
const registry = new HarnessRegistry();
|
||||
const adapter = new FakeHarnessAdapter({ id: 'fake' });
|
||||
|
||||
registry.register(adapter);
|
||||
|
||||
expect(registry.get('fake')).toBe(adapter);
|
||||
expect(registry.has('fake')).toBe(true);
|
||||
expect(registry.list().map((entry) => entry.id)).toEqual(['fake']);
|
||||
});
|
||||
|
||||
it('rejects a blank adapter id', () => {
|
||||
const registry = new HarnessRegistry();
|
||||
|
||||
let error: unknown;
|
||||
try {
|
||||
registry.register(new FakeHarnessAdapter({ id: ' ' }));
|
||||
} catch (caught) {
|
||||
error = caught;
|
||||
}
|
||||
|
||||
expect(error).toBeInstanceOf(HarnessRegistrationError);
|
||||
expect((error as HarnessRegistrationError).reason).toBe('blank_id');
|
||||
expect(registry.list()).toEqual([]);
|
||||
});
|
||||
|
||||
it('rejects a duplicate adapter id', () => {
|
||||
const registry = new HarnessRegistry();
|
||||
registry.register(new FakeHarnessAdapter({ id: 'fake' }));
|
||||
|
||||
let error: unknown;
|
||||
try {
|
||||
registry.register(new FakeHarnessAdapter({ id: 'fake' }));
|
||||
} catch (caught) {
|
||||
error = caught;
|
||||
}
|
||||
|
||||
expect(error).toBeInstanceOf(HarnessRegistrationError);
|
||||
expect((error as HarnessRegistrationError).reason).toBe('duplicate_id');
|
||||
expect((error as HarnessRegistrationError).harnessId).toBe('fake');
|
||||
// The original registration is untouched.
|
||||
expect(registry.list()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('returns adapter_unavailable for an unknown harness id', () => {
|
||||
const registry = new HarnessRegistry();
|
||||
|
||||
let error: unknown;
|
||||
try {
|
||||
registry.get('missing');
|
||||
} catch (caught) {
|
||||
error = caught;
|
||||
}
|
||||
|
||||
expect(error).toBeInstanceOf(HarnessAdapterUnavailableError);
|
||||
expect((error as HarnessAdapterUnavailableError).code).toBe('adapter_unavailable');
|
||||
expect((error as HarnessAdapterUnavailableError).harnessId).toBe('missing');
|
||||
expect(registry.has('missing')).toBe(false);
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user