Server-beta: Postgres storage + independent runtime + BullMQ queue (Phases 1–3) (#2351)

* Add server beta runtime foundation

* Address server beta review findings

* Resolve server beta review comments

* Tighten server beta review follow-ups

* Harden server beta auth and search

* Avoid unnecessary FTS rebuilds

* Block scoped keys from creating projects

* Release BullMQ claims best effort on close

* Address server beta review blockers

* Reset BullMQ claims best effort

* Add Postgres observation storage foundation

* feat(server-beta): add independent runtime service

Introduce src/server/runtime/ as a self-contained server-beta runtime
that owns its lifecycle, Postgres bootstrap, and HTTP boundary without
depending on WorkerService.

ServerBetaService wraps the existing Server class, exposes
/healthz and /v1/info with runtime="server-beta", and persists state
to dedicated paths (.server-beta.pid|.port|.runtime.json). The four
boundary managers (queue, generation worker, provider registry, event
broadcaster) are intentionally disabled in this phase and report their
status through /v1/info; later phases activate them.

Adds plans/2026-05-07-finish-bullmq-branch-ship-plan.md to track the
remaining work for this branch.

Phase 2 of plans/2026-05-07-server-beta-independent-bullmq-observation-runtime.md.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(server-beta): route CLI lifecycle and bundle separate runtime

scripts/build-hooks.js now produces plugin/scripts/server-beta-service.cjs
as a separate Node CJS bundle, alongside the existing worker-service
bundle. The server-beta runtime is now installable independently.

src/npx-cli/commands/server.ts routes start|stop|restart|status to the
server-beta lifecycle instead of the legacy worker. The worker keeps its
own start|stop|restart|status under the worker namespace; the two
runtimes can be operated independently.

src/services/worker-service.ts adds a server-* command parser branch
that delegates to the sibling server-beta-service.cjs bundle so
direct worker-service invocations still route to the right runtime.

tests/npx-cli-server-namespace.test.ts updated to expect server-beta
lifecycle routing.

Includes rebuilt plugin/scripts/*.cjs bundles produced by
build-and-sync.

Phase 2 of plans/2026-05-07-server-beta-independent-bullmq-observation-runtime.md.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(server-beta): add BullMQ job queue primitives

Introduce src/server/jobs/ as the queue-side primitives that Phase 3 of
the server-beta runtime needs to operate.

types.ts defines a discriminated union over the four job kinds (event,
event-batch, summary, reindex) and maps each to a per-kind BullMQ queue
name and deterministic-ID prefix.

job-id.ts builds deterministic, colon-free BullMQ jobIds from
(kind, team, project, source). The colon ban exists because BullMQ uses
':' as a Redis key separator internally; embedding ':' in jobIds
breaks scan and state lookups.

ServerJobQueue.ts is a thin wrapper over BullMQ Queue + Worker that
enforces autorun:false, default concurrency 1, and an attached error
listener — all per BullMQ docs requirements. Test seams accept queue
and worker factories so unit tests do not need Redis.

outbox.ts publishes through the Postgres ObservationGenerationJob
repository as canonical history. enqueueOutbox writes the row first,
then publishes to BullMQ; if BullMQ throws, the row is transitioned to
failed and a failed event is appended. reconcileOnStartup re-enqueues
queued + processing rows after a restart, replacing terminal BullMQ
jobs that may still be holding the deterministic ID slot. markCompleted
and markFailed wrap transitionStatus and append the matching event row.

Includes 20 unit tests covering deterministic ID stability, colon-free
output, queue lifecycle, error-listener attachment, double-start
refusal, idempotent enqueue, BullMQ failure rollback, startup
reconciliation, max-attempts skipping, and completion / failure /
retry transitions.

Phase 3 commit 1 of plans/2026-05-07-server-beta-independent-bullmq-observation-runtime.md.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(server-beta): activate queue boundary in runtime service

Wire ActiveServerBetaQueueManager into the server-beta runtime graph.
The active manager owns one ServerJobQueue per generation kind (event,
event-batch, summary, reindex) and surfaces lane metadata through
boundary health.

Selection is opt-in and fail-fast: if CLAUDE_MEM_QUEUE_ENGINE is set to
bullmq the active manager is constructed (and any Redis/config error
throws — no silent fallback to SQLite, per Phase 3 anti-pattern guard).
For any other engine the disabled boundary remains so worker-era and
test setups stay compatible.

Widens ServerBetaBoundaryHealth.status to a discriminated union
('disabled' | 'active' | 'errored') with optional details. The disabled
adapter still emits status='disabled', which keeps the existing
server-beta-service test green.

ServerBetaService receives the manager through a new optional
queueManager field on CreateServerBetaServiceOptions so test graphs
and Phase 4 wiring can inject custom managers.

Adds tests/server/runtime/active-queue-manager.test.ts covering bullmq
guard, active health shape, per-kind queue access, close behavior, and
post-close errored health.

Phase 3 commit 2 of plans/2026-05-07-server-beta-independent-bullmq-observation-runtime.md.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(server-beta): cap /v1/events/batch at 500 events

Prevents unbounded array DoS surface flagged in PR review.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Alex Newman
2026-05-08 01:20:07 -07:00
committed by GitHub
parent 0a43ab7632
commit 36b0929fae
183 changed files with 35709 additions and 2033 deletions
+264
View File
@@ -0,0 +1,264 @@
// SPDX-License-Identifier: Apache-2.0
import type { Application, Request, Response } from 'express';
import type { Database } from 'bun:sqlite';
import { z, type ZodTypeAny } from 'zod';
import type { RouteHandler } from '../../../services/server/Server.js';
import { CreateAgentEventSchema } from '../../../core/schemas/agent-event.js';
import { CreateMemoryItemSchema } from '../../../core/schemas/memory-item.js';
import { CreateProjectSchema } from '../../../core/schemas/project.js';
import { CreateServerSessionSchema } from '../../../core/schemas/session.js';
import {
AgentEventsRepository,
AuthRepository,
MemoryItemsRepository,
ProjectsRepository,
ServerSessionsRepository,
} from '../../../storage/sqlite/index.js';
import { requireServerAuth } from '../../middleware/auth.js';
declare const __DEFAULT_PACKAGE_VERSION__: string;
const BUILT_IN_VERSION = typeof __DEFAULT_PACKAGE_VERSION__ !== 'undefined'
? __DEFAULT_PACKAGE_VERSION__
: 'development';
export interface ServerV1RoutesOptions {
getDatabase: () => Database;
authMode?: string;
runtime?: string;
allowLocalDevBypass?: boolean;
}
export class ServerV1Routes implements RouteHandler {
constructor(private readonly options: ServerV1RoutesOptions) {}
setupRoutes(app: Application): void {
const readAuth = requireServerAuth(this.options.getDatabase, {
authMode: this.options.authMode,
allowLocalDevBypass: this.options.allowLocalDevBypass,
requiredScopes: ['memories:read'],
});
const writeAuth = requireServerAuth(this.options.getDatabase, {
authMode: this.options.authMode,
allowLocalDevBypass: this.options.allowLocalDevBypass,
requiredScopes: ['memories:write'],
});
app.get('/healthz', (_req, res) => {
res.json({ status: 'ok' });
});
app.get('/v1/info', (_req, res) => {
res.json({
name: 'claude-mem-server',
version: BUILT_IN_VERSION,
...(this.options.runtime ? { runtime: this.options.runtime } : {}),
authMode: this.options.authMode ?? process.env.CLAUDE_MEM_AUTH_MODE ?? 'api-key',
});
});
app.get('/v1/projects', readAuth, (req, res) => {
const repo = new ProjectsRepository(this.options.getDatabase());
const projects = req.authContext?.projectId
? [repo.getById(req.authContext.projectId)].filter(project => project !== null)
: repo.list();
res.json({ projects });
this.audit(req, 'projects.list');
});
app.post('/v1/projects', writeAuth, this.handleCreate(CreateProjectSchema, (req, res, body) => {
if (req.authContext?.projectId) {
res.status(403).json({ error: 'Forbidden', message: 'Project-scoped API keys cannot create projects' });
return;
}
const project = new ProjectsRepository(this.options.getDatabase()).create(body);
this.audit(req, 'project.create', project.id);
res.status(201).json({ project });
}));
app.get('/v1/projects/:id', readAuth, (req, res) => {
const id = this.routeParam(req.params.id);
if (!this.ensureProjectAllowed(req, res, id)) return;
const project = new ProjectsRepository(this.options.getDatabase()).getById(id);
if (!project) {
res.status(404).json({ error: 'NotFound', message: 'Project not found' });
return;
}
this.audit(req, 'project.read', project.id);
res.json({ project });
});
app.post('/v1/sessions/start', writeAuth, this.handleCreate(CreateServerSessionSchema, (req, res, body) => {
if (!this.ensureProjectAllowed(req, res, body.projectId)) return;
const session = new ServerSessionsRepository(this.options.getDatabase()).create(body);
this.audit(req, 'session.start', session.id, session.projectId);
res.status(201).json({ session });
}));
app.post('/v1/sessions/:id/end', writeAuth, (req, res) => {
const id = this.routeParam(req.params.id);
const repo = new ServerSessionsRepository(this.options.getDatabase());
const existing = repo.getById(id);
if (!existing) {
res.status(404).json({ error: 'NotFound', message: 'Session not found' });
return;
}
if (!this.ensureProjectAllowed(req, res, existing.projectId)) return;
const session = repo.markCompleted(id);
this.audit(req, 'session.end', id, existing.projectId);
res.json({ session });
});
app.get('/v1/sessions/:id', readAuth, (req, res) => {
const id = this.routeParam(req.params.id);
const session = new ServerSessionsRepository(this.options.getDatabase()).getById(id);
if (!session) {
res.status(404).json({ error: 'NotFound', message: 'Session not found' });
return;
}
if (!this.ensureProjectAllowed(req, res, session.projectId)) return;
this.audit(req, 'session.read', session.id, session.projectId);
res.json({ session });
});
app.post('/v1/events', writeAuth, this.handleCreate(CreateAgentEventSchema, (req, res, body) => {
if (!this.ensureProjectAllowed(req, res, body.projectId)) return;
const event = new AgentEventsRepository(this.options.getDatabase()).create(body);
this.audit(req, 'event.write', event.id, event.projectId);
res.status(201).json({ event });
}));
app.post('/v1/events/batch', writeAuth, this.handleCreate(z.array(CreateAgentEventSchema).min(1).max(500), (req, res, body) => {
for (const event of body) {
if (!this.ensureProjectAllowed(req, res, event.projectId)) return;
}
const db = this.options.getDatabase();
const repo = new AgentEventsRepository(db);
const insertEvents = db.transaction((eventsToCreate: typeof body) => {
return eventsToCreate.map(event => repo.create(event));
});
const events = insertEvents(body);
this.audit(req, 'event.batch_write');
res.status(201).json({ events });
}));
app.get('/v1/events/:id', readAuth, (req, res) => {
const id = this.routeParam(req.params.id);
const event = new AgentEventsRepository(this.options.getDatabase()).getById(id);
if (!event) {
res.status(404).json({ error: 'NotFound', message: 'Event not found' });
return;
}
if (!this.ensureProjectAllowed(req, res, event.projectId)) return;
this.audit(req, 'event.read', event.id, event.projectId);
res.json({ event });
});
app.post('/v1/memories', writeAuth, this.handleCreate(CreateMemoryItemSchema, (req, res, body) => {
if (!this.ensureProjectAllowed(req, res, body.projectId)) return;
const memory = new MemoryItemsRepository(this.options.getDatabase()).create(body);
this.audit(req, 'memory.write', memory.id, memory.projectId);
res.status(201).json({ memory });
}));
app.get('/v1/memories/:id', readAuth, (req, res) => {
const id = this.routeParam(req.params.id);
const memory = new MemoryItemsRepository(this.options.getDatabase()).getById(id);
if (!memory) {
res.status(404).json({ error: 'NotFound', message: 'Memory not found' });
return;
}
if (!this.ensureProjectAllowed(req, res, memory.projectId)) return;
this.audit(req, 'memory.read', memory.id, memory.projectId);
res.json({ memory });
});
app.patch('/v1/memories/:id', writeAuth, this.handleCreate(CreateMemoryItemSchema.partial(), (req, res, body) => {
const id = this.routeParam(req.params.id);
const repo = new MemoryItemsRepository(this.options.getDatabase());
const existing = repo.getById(id);
if (!existing) {
res.status(404).json({ error: 'NotFound', message: 'Memory not found' });
return;
}
if (!this.ensureProjectAllowed(req, res, existing.projectId)) return;
if (body.projectId && body.projectId !== existing.projectId) {
res.status(400).json({ error: 'ValidationError', message: 'projectId cannot be changed' });
return;
}
const memory = repo.update(id, body);
this.audit(req, 'memory.update', id, existing.projectId);
res.json({ memory });
}));
app.post('/v1/search', readAuth, this.handleCreate(z.object({
projectId: z.string().min(1),
query: z.string().min(1),
limit: z.number().int().positive().max(100).optional(),
}), (req, res, body) => {
if (!this.ensureProjectAllowed(req, res, body.projectId)) return;
const memories = new MemoryItemsRepository(this.options.getDatabase()).search(body.projectId, body.query, body.limit ?? 20);
this.audit(req, 'memory.search', null, body.projectId);
res.json({ memories });
}));
app.post('/v1/context', readAuth, this.handleCreate(z.object({
projectId: z.string().min(1),
query: z.string().min(1),
limit: z.number().int().positive().max(50).optional(),
}), (req, res, body) => {
if (!this.ensureProjectAllowed(req, res, body.projectId)) return;
const memories = new MemoryItemsRepository(this.options.getDatabase()).search(body.projectId, body.query, body.limit ?? 10);
this.audit(req, 'memory.context', null, body.projectId);
res.json({ memories, context: memories.map(memory => memory.narrative ?? memory.text ?? memory.title).filter(Boolean).join('\n\n') });
}));
app.get('/v1/audit', readAuth, (req, res) => {
const projectId = String(req.query.projectId ?? '');
if (!projectId) {
res.status(400).json({ error: 'ValidationError', message: 'projectId query parameter is required' });
return;
}
if (!this.ensureProjectAllowed(req, res, projectId)) return;
res.json({ audit: new AuthRepository(this.options.getDatabase()).listAuditLogByProject(projectId) });
});
}
private handleCreate<S extends ZodTypeAny, T = z.infer<S>>(
schema: S,
handler: (req: Request, res: Response, body: T) => void,
) {
return (req: Request, res: Response) => {
const result = schema.safeParse(req.body);
if (!result.success) {
res.status(400).json({ error: 'ValidationError', issues: result.error.issues });
return;
}
handler(req, res, result.data as T);
};
}
private ensureProjectAllowed(req: Request, res: Response, projectId: string): boolean {
if (req.authContext?.projectId && req.authContext.projectId !== projectId) {
res.status(403).json({ error: 'Forbidden', message: 'API key is scoped to a different project' });
return false;
}
return true;
}
private routeParam(value: string | string[]): string {
return Array.isArray(value) ? value[0] ?? '' : value;
}
private audit(req: Request, action: string, targetId: string | null = null, projectId: string | null = null): void {
new AuthRepository(this.options.getDatabase()).createAuditLog({
teamId: req.authContext?.teamId ?? null,
projectId: projectId ?? req.authContext?.projectId ?? null,
actorType: req.authContext?.apiKeyId ? 'api_key' : 'system',
actorId: req.authContext?.apiKeyId ?? null,
action,
targetType: targetId ? action.split('.')[0] : null,
targetId,
});
}
}