agenthub/tests/server.test.ts
chahinebrini 6d088648da feat(hub): Korrektheits- und Realtime-Härtung — Alias, Lifecycle, Presence, Architekten-Pulse (TSK-0242/0245/0249)
Drei vom Architekten abgenommene Tasks, gebündelt als Checkpoint:

- TSK-0242: Agent-Alias-Mapping (kimi-ah → kimi kanonisiert, Rollen → preferredAgent),
  reopenTask räumt claimedBy ab, fsWatch reindiziert direkte Datei-Edits,
  work-Default 300s → 50s, task_list mit Limit.
- TSK-0245: zwei Agent-Klassen (dispatch loop|architect). Watchdog mahnt
  architekt-getriebene Agenten nur noch EINMAL statt im Minutentakt;
  `task dispatch` startet sie explizit, `task record` trägt extern
  erledigte Arbeit mit origin=external nach.
- TSK-0249: Lifecycle wird serverseitig erzwungen (open→review scheitert mit
  klarer Meldung), claimedBy/doneBy überleben bis done, Presence pro Agent,
  Review-Watchdog, GET /architect/pulse (1.4 kB statt 34 kB, since-Cursor,
  omitted statt stillem Abschneiden), unbekannter Agent → 400 statt 500.

Alle Punkte live am laufenden Hub nachgemessen, nicht aus Agenten-Logs übernommen.
Tests: 242 → 279 grün, tsc sauber.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-29 17:48:24 +02:00

440 lines
22 KiB
TypeScript

import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { mkdtempSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { buildApp } from '../src/server/index.js';
import { init } from '../src/cli/commands/init.js';
import { loadConfig, saveConfig } from '../src/core/config.js';
describe('server routes', () => {
let cwd: string;
let app: ReturnType<typeof buildApp>;
beforeEach(() => {
cwd = mkdtempSync(join(tmpdir(), 'ah-server-'));
init(cwd, { projectName: 'server-test', yes: true });
app = buildApp(cwd);
});
afterEach(() => {
rmSync(cwd, { recursive: true, force: true });
});
it('creates a task via POST /tasks', async () => {
const res = await app.inject({
method: 'POST',
url: '/tasks',
payload: { title: 'API task', role: 'implementer' },
});
expect(res.statusCode).toBe(200);
const task = JSON.parse(res.payload);
expect(task.id).toBe('TSK-0001');
});
it('lists tasks via GET /tasks', async () => {
await app.inject({ method: 'POST', url: '/tasks', payload: { title: 'A', role: 'implementer' } });
const res = await app.inject({ method: 'GET', url: '/tasks' });
expect(res.headers['cache-control']).toContain('no-store');
expect(JSON.parse(res.payload)).toHaveLength(1);
});
it('returns a compact architect pulse with reviews, dormant agents, messages, and event delta', async () => {
await app.inject({
method: 'POST', url: '/tasks',
payload: { title: 'Pulse review', role: 'implementer', assignedTo: 'codex' },
});
await app.inject({ method: 'PATCH', url: '/tasks/TSK-0001', payload: { status: 'in_progress' } });
await app.inject({ method: 'PATCH', url: '/tasks/TSK-0001', payload: { status: 'review' } });
await app.inject({ method: 'POST', url: '/agents/codex/loop', payload: { active: true } });
await app.inject({
method: 'POST', url: '/agents/codex/loop',
payload: { active: false, reason: 'turn ended' },
});
await app.inject({
method: 'POST', url: '/messages',
payload: { from: 'codex', to: 'architect', text: 'review ready' },
});
const res = await app.inject({ method: 'GET', url: '/architect/pulse?sinceSeq=0' });
expect(res.statusCode).toBe(200);
const pulse = JSON.parse(res.payload);
expect(pulse.reviews).toEqual([
expect.objectContaining({ id: 'TSK-0001', assignedTo: 'codex' }),
]);
expect(pulse.dormantAgents).toEqual([
expect.objectContaining({ name: 'codex', loopExitReason: 'turn ended' }),
]);
expect(pulse.messages).toEqual([
expect.objectContaining({ from: 'codex' }),
]);
expect(pulse.events.length).toBeGreaterThan(0);
expect(pulse.nextSeq).toBeGreaterThan(0);
expect(pulse.omitted).toEqual(expect.objectContaining({ messages: 0, events: expect.any(Number) }));
expect(pulse.reviews[0].title).toBeUndefined();
const delta = await app.inject({ method: 'GET', url: `/architect/pulse?since=${pulse.nextSeq}` });
const deltaPulse = JSON.parse(delta.payload);
expect(deltaPulse.events).toEqual([]);
expect(deltaPulse.nextSeq).toBe(pulse.nextSeq);
expect(delta.payload.length).toBeLessThan(1000);
});
it('returns 400 when assigning to an unknown agent', async () => {
const config = loadConfig(cwd);
config.agents = { codex: { role: 'implementer', dispatch: 'loop' } };
saveConfig(cwd, config);
await app.inject({ method: 'POST', url: '/tasks', payload: { title: 'A', role: 'implementer' } });
const res = await app.inject({ method: 'PATCH', url: '/tasks/TSK-0001', payload: { assignedTo: 'unknown-agent' } });
expect(res.statusCode).toBe(400);
expect(res.payload).toContain('Unknown agent');
});
it('returns 404 for unknown task', async () => {
const res = await app.inject({ method: 'GET', url: '/tasks/TSK-9999' });
expect(res.statusCode).toBe(404);
});
it('returns 400 for unsupported patch', async () => {
await app.inject({ method: 'POST', url: '/tasks', payload: { title: 'A', role: 'implementer' } });
const res = await app.inject({ method: 'PATCH', url: '/tasks/TSK-0001', payload: { status: 'unknown' } });
expect(res.statusCode).toBe(400);
});
it('claims manually when setting in_progress without assignedTo', async () => {
await app.inject({ method: 'POST', url: '/tasks', payload: { title: 'A', role: 'implementer' } });
const res = await app.inject({ method: 'PATCH', url: '/tasks/TSK-0001', payload: { status: 'in_progress' } });
expect(res.statusCode).toBe(200);
expect(JSON.parse(res.payload)).toMatchObject({ status: 'in_progress', assignedTo: 'manual', claimedBy: 'manual' });
});
it('claims with the existing assignee when setting in_progress without assignedTo', async () => {
await app.inject({ method: 'POST', url: '/tasks', payload: { title: 'A', role: 'implementer', assignedTo: 'codex' } });
const res = await app.inject({ method: 'PATCH', url: '/tasks/TSK-0001', payload: { status: 'in_progress' } });
expect(res.statusCode).toBe(200);
expect(JSON.parse(res.payload)).toMatchObject({ status: 'in_progress', assignedTo: 'codex', claimedBy: 'codex' });
});
it('PATCH /tasks/:id → review', async () => {
await app.inject({ method: 'POST', url: '/tasks', payload: { title: 'A', role: 'implementer' } });
await app.inject({ method: 'PATCH', url: '/tasks/TSK-0001', payload: { status: 'in_progress', assignedTo: 'codex' } });
const res = await app.inject({ method: 'PATCH', url: '/tasks/TSK-0001', payload: { status: 'review' } });
expect(res.statusCode).toBe(200);
expect(JSON.parse(res.payload).status).toBe('review');
});
it('rejects open → review and records the failed transition in the task log', async () => {
await app.inject({ method: 'POST', url: '/tasks', payload: { title: 'A', role: 'implementer' } });
const res = await app.inject({ method: 'PATCH', url: '/tasks/TSK-0001', payload: { status: 'review' } });
expect(res.statusCode).toBe(400);
expect(JSON.parse(res.payload).error).toMatch(/open.*review/i);
const log = JSON.parse((await app.inject({ method: 'GET', url: '/tasks/TSK-0001/log' })).payload).log;
expect(log.some((entry: { text: string }) => entry.text.includes('Rejected transition'))).toBe(true);
});
it('preserves claimedBy through review and done', async () => {
await app.inject({ method: 'POST', url: '/tasks', payload: { title: 'A', role: 'implementer' } });
await app.inject({
method: 'PATCH', url: '/tasks/TSK-0001',
payload: { status: 'in_progress', assignedTo: 'codex' },
});
await app.inject({ method: 'PATCH', url: '/tasks/TSK-0001', payload: { status: 'review' } });
const done = await app.inject({ method: 'PATCH', url: '/tasks/TSK-0001', payload: { status: 'done' } });
expect(done.statusCode).toBe(200);
expect(JSON.parse(done.payload)).toMatchObject({ status: 'done', claimedBy: 'codex', doneBy: 'codex' });
});
it('a second claim of the same task returns a clean 400 (race guard, board does not 500) — TSK-0007', async () => {
await app.inject({ method: 'POST', url: '/tasks', payload: { title: 'A', role: 'implementer' } });
const first = await app.inject({ method: 'PATCH', url: '/tasks/TSK-0001', payload: { status: 'in_progress', assignedTo: 'kimi' } });
expect(first.statusCode).toBe(200);
// Another agent tries to claim the now in-progress task.
const second = await app.inject({ method: 'PATCH', url: '/tasks/TSK-0001', payload: { status: 'in_progress', assignedTo: 'codex' } });
expect(second.statusCode).toBe(400);
// The original claim is intact — not clobbered.
const still = JSON.parse((await app.inject({ method: 'GET', url: '/tasks/TSK-0001' })).payload) as { task: { claimedBy?: string } };
expect(still.task.claimedBy).toBe('kimi');
});
it('PATCH /tasks/:id → review accepts reviewer separately from assignedTo', async () => {
await app.inject({ method: 'POST', url: '/tasks', payload: { title: 'A', role: 'implementer', assignedTo: 'codex' } });
await app.inject({ method: 'PATCH', url: '/tasks/TSK-0001', payload: { status: 'in_progress' } });
const res = await app.inject({ method: 'PATCH', url: '/tasks/TSK-0001', payload: { status: 'review', reviewer: 'claude' } });
expect(res.statusCode).toBe(200);
const task = JSON.parse(res.payload);
expect(task.status).toBe('review');
expect(task.assignedTo).toBe('codex');
expect(task.reviewer).toBe('claude');
const listRes = await app.inject({ method: 'GET', url: '/tasks' });
expect(JSON.parse(listRes.payload)[0]).toMatchObject({ assignedTo: 'codex', reviewer: 'claude' });
});
it('PATCH /tasks/:id → cancelled', async () => {
await app.inject({ method: 'POST', url: '/tasks', payload: { title: 'A', role: 'implementer' } });
const res = await app.inject({ method: 'PATCH', url: '/tasks/TSK-0001', payload: { status: 'cancelled' } });
expect(res.statusCode).toBe(200);
expect(JSON.parse(res.payload).status).toBe('cancelled');
});
it('PATCH /tasks/:id → open (reopen)', async () => {
await app.inject({ method: 'POST', url: '/tasks', payload: { title: 'A', role: 'implementer' } });
await app.inject({ method: 'PATCH', url: '/tasks/TSK-0001', payload: { status: 'in_progress', assignedTo: 'codex' } });
await app.inject({ method: 'PATCH', url: '/tasks/TSK-0001', payload: { status: 'review' } });
const res = await app.inject({ method: 'PATCH', url: '/tasks/TSK-0001', payload: { status: 'open' } });
expect(res.statusCode).toBe(200);
expect(JSON.parse(res.payload).status).toBe('open');
});
it('review and cancelled tasks appear in GET /tasks list', async () => {
await app.inject({ method: 'POST', url: '/tasks', payload: { title: 'A', role: 'implementer' } });
await app.inject({ method: 'POST', url: '/tasks', payload: { title: 'B', role: 'implementer' } });
await app.inject({ method: 'PATCH', url: '/tasks/TSK-0001', payload: { status: 'in_progress', assignedTo: 'codex' } });
await app.inject({ method: 'PATCH', url: '/tasks/TSK-0001', payload: { status: 'review' } });
await app.inject({ method: 'PATCH', url: '/tasks/TSK-0002', payload: { status: 'cancelled' } });
const allRes = await app.inject({ method: 'GET', url: '/tasks' });
const all = JSON.parse(allRes.payload) as Array<{ status: string }>;
const statuses = all.map((t) => t.status);
expect(statuses).toContain('review');
expect(statuses).toContain('cancelled');
});
it('updates status via POST /status/update', async () => {
await app.inject({ method: 'POST', url: '/tasks', payload: { title: 'A', role: 'implementer' } });
const res = await app.inject({ method: 'POST', url: '/status/update' });
expect(res.statusCode).toBe(200);
expect(JSON.parse(res.payload).body).toContain('Active tasks: 1');
});
it('searches memory via GET /memory/search', async () => {
await app.inject({ method: 'POST', url: '/memory', payload: { title: 'DNS cache', category: 'technical', content: 'Use TTL' } });
const res = await app.inject({ method: 'GET', url: '/memory/search?q=TTL' });
expect(res.statusCode).toBe(200);
expect(JSON.parse(res.payload)).toHaveLength(1);
});
it('serves the task board as HTML via GET /board', async () => {
const res = await app.inject({ method: 'GET', url: '/board' });
expect(res.statusCode).toBe(200);
expect(res.headers['content-type']).toContain('text/html');
const html = res.payload;
expect(html).toContain('<title>agenthub — Board</title>');
// The three active lanes are present in the static markup (board v2).
for (const col of ['open', 'in_progress', 'review']) {
expect(html).toContain(`data-column="${col}"`);
}
// Board polling stays wired; handoffs/decisions now live on dedicated pages.
expect(html).toContain("getJSON('/tasks')");
expect(html).toContain("cache: 'no-store'");
expect(html).toContain("window.addEventListener('pageshow'");
expect(html).toContain("document.addEventListener('visibilitychange'");
expect(html).toContain("var agent = assigned || titledAgent || 'manual'");
expect(html).toContain('setInterval(refresh');
expect(html).toContain('Token Insights');
expect(html).toContain('data-budget-mode="session"');
});
// ── Activity timeline endpoint ─────────────────────────────────────────
it('GET /tasks/:id/activity returns 404 for unknown task', async () => {
const res = await app.inject({ method: 'GET', url: '/tasks/TSK-9999/activity' });
expect(res.statusCode).toBe(404);
});
it('GET /tasks/:id/activity returns a created event', async () => {
await app.inject({ method: 'POST', url: '/tasks', payload: { title: 'Auth', role: 'implementer' } });
const res = await app.inject({ method: 'GET', url: '/tasks/TSK-0001/activity' });
expect(res.statusCode).toBe(200);
const items = JSON.parse(res.payload) as Array<{ kind: string; summary: string }>;
expect(items.some((i) => i.kind === 'created')).toBe(true);
});
it('GET /tasks/:id/activity includes handoff events linked by taskId', async () => {
await app.inject({ method: 'POST', url: '/tasks', payload: { title: 'Auth', role: 'implementer' } });
await app.inject({
method: 'POST',
url: '/handoffs',
payload: { fromRole: 'architect', toRole: 'implementer', taskId: 'TSK-0001', summary: 'Design done' },
});
const res = await app.inject({ method: 'GET', url: '/tasks/TSK-0001/activity' });
const items = JSON.parse(res.payload) as Array<{ kind: string; summary: string }>;
const handoff = items.find((i) => i.kind === 'handoff');
expect(handoff).toBeDefined();
expect(handoff!.summary).toBe('Design done');
});
it('GET /tasks/:id/activity includes memory result events linked by relatedTasks', async () => {
await app.inject({ method: 'POST', url: '/tasks', payload: { title: 'DNS task', role: 'implementer' } });
await app.inject({
method: 'POST',
url: '/memory',
payload: { title: 'TTL insight', category: 'technical', content: 'Use 300s', relatedTasks: ['TSK-0001'] },
});
const res = await app.inject({ method: 'GET', url: '/tasks/TSK-0001/activity' });
const items = JSON.parse(res.payload) as Array<{ kind: string; summary: string }>;
const result = items.find((i) => i.kind === 'result');
expect(result).toBeDefined();
expect(result!.summary).toBe('TTL insight');
});
it('GET /tasks/:id/activity includes tokens/duration from done metadata', async () => {
await app.inject({ method: 'POST', url: '/tasks', payload: { title: 'Work', role: 'implementer' } });
await app.inject({ method: 'PATCH', url: '/tasks/TSK-0001', payload: { status: 'in_progress', assignedTo: 'codex' } });
await app.inject({ method: 'PATCH', url: '/tasks/TSK-0001', payload: { status: 'review' } });
await app.inject({
method: 'PATCH',
url: '/tasks/TSK-0001',
payload: { status: 'done', doneTokens: 5000, doneDuration: 60000, doneBy: 'claude' },
});
const res = await app.inject({ method: 'GET', url: '/tasks/TSK-0001/activity' });
const items = JSON.parse(res.payload) as Array<{ kind: string; meta?: Record<string, unknown> }>;
const status = items.find((i) => i.kind === 'status');
expect(status).toBeDefined();
expect(status!.meta?.tokens).toBe(5000);
expect(status!.meta?.duration).toBe(60000);
expect(status!.meta?.by).toBe('claude');
});
it('board HTML keeps cards slim and links to task detail pages', async () => {
const res = await app.inject({ method: 'GET', url: '/board' });
const html = res.payload;
// Cards carry data-id for realtime refresh bookkeeping and link to detail pages.
expect(html).toContain('data-id');
expect(html).toContain('href="/tasks/');
expect(html).not.toContain('class="timeline"');
// Cards must not expand inline (aria-expanded on the composer button is fine).
expect(html).not.toMatch(/class="[^"]*\bexpanded\b/);
expect(html).not.toContain("'/tasks/' + encodeURIComponent(id) + '/activity'");
});
it('task detail HTML shows activity metadata and linked decisions with reasoning', async () => {
await app.inject({ method: 'POST', url: '/tasks', payload: { title: 'Detail transparency', role: 'implementer' } });
await app.inject({
method: 'POST',
url: '/decisions',
payload: {
title: 'Keep cards slim',
context: 'Transparency belongs on the task detail page.',
decision: 'Task cards link to detail pages instead of expanding inline.',
},
});
await app.inject({
method: 'POST',
url: '/handoffs',
payload: {
fromRole: 'architect',
toRole: 'implementer',
taskId: 'TSK-0001',
summary: 'Implement detail view',
decisions: ['DEC-0001'],
},
});
await app.inject({
method: 'PATCH',
url: '/tasks/TSK-0001',
payload: { status: 'in_progress', assignedTo: 'codex' },
});
await app.inject({
method: 'PATCH',
url: '/tasks/TSK-0001',
payload: { status: 'review' },
});
await app.inject({
method: 'PATCH',
url: '/tasks/TSK-0001',
payload: { status: 'done', doneTokens: 3210, doneDuration: 65000, doneBy: 'codex' },
});
const res = await app.inject({ method: 'GET', url: '/tasks/TSK-0001', headers: { accept: 'text/html' } });
expect(res.statusCode).toBe(200);
expect(res.headers['content-type']).toContain('text/html');
expect(res.payload).toContain('Decisions &amp; Reasoning');
expect(res.payload).toContain('Keep cards slim');
expect(res.payload).toContain('Transparency belongs on the task detail page.');
expect(res.payload).toContain('3210&thinsp;tok');
expect(res.payload).toContain('1m');
});
it('serves the activity page with tasks only — messaging split out to /messages', async () => {
await app.inject({ method: 'POST', url: '/tasks', payload: { title: 'Done item', role: 'implementer' } });
await app.inject({ method: 'PATCH', url: '/tasks/TSK-0001', payload: { status: 'in_progress', assignedTo: 'codex' } });
await app.inject({ method: 'PATCH', url: '/tasks/TSK-0001', payload: { status: 'review' } });
await app.inject({
method: 'PATCH',
url: '/tasks/TSK-0001',
payload: { status: 'done', doneBy: 'codex' },
});
await app.inject({
method: 'POST',
url: '/messages',
payload: { from: 'claude', to: 'codex', text: 'Please check the board', taskId: 'TSK-0001' },
});
const res = await app.inject({ method: 'GET', url: '/activity' });
expect(res.statusCode).toBe(200);
expect(res.headers['content-type']).toContain('text/html');
expect(res.payload).toContain('Recent Activity');
expect(res.payload).toContain('Done Archive');
expect(res.payload).toContain('TSK-0001');
// Hard separation: no message rows leak into /activity anymore.
expect(res.payload).not.toContain('MSG-0001');
expect(res.payload).not.toContain('kind-message');
});
it('serves the /messages conversation view (HTML) with a conversation list', async () => {
await app.inject({ method: 'POST', url: '/messages', payload: { from: 'claude', to: 'codex', text: 'Please check the board' } });
const res = await app.inject({ method: 'GET', url: '/messages', headers: { accept: 'text/html' } });
expect(res.statusCode).toBe(200);
expect(res.headers['content-type']).toContain('text/html');
expect(res.payload).toContain('Conversations');
expect(res.payload).toContain('MSG-0001');
expect(res.payload).toContain('Please check the board');
// JSON contract unchanged: no accept header → JSON list, not HTML.
const json = await app.inject({ method: 'GET', url: '/messages' });
expect(() => JSON.parse(json.payload)).not.toThrow();
});
it('read-receipt chain: create → inbox(delivered) → read → ack', async () => {
await app.inject({ method: 'POST', url: '/messages', payload: { from: 'codex', to: 'claude', text: 'ping' } });
// create → unread
const listed = JSON.parse((await app.inject({ method: 'GET', url: '/messages' })).payload) as Array<{ id: string; status: string }>;
expect(listed[0].status).toBe('unread');
// inbox fetch → delivered (agent-scoped side effect)
const inbox = JSON.parse((await app.inject({ method: 'GET', url: '/messages?agent=claude' })).payload) as Array<{ id: string; status: string }>;
expect(inbox[0].status).toBe('delivered');
// read
const read = JSON.parse((await app.inject({ method: 'POST', url: '/messages/MSG-0001/read' })).payload) as { status: string };
expect(read.status).toBe('read');
// ack
const acked = JSON.parse((await app.inject({ method: 'POST', url: '/messages/MSG-0001/ack', payload: { by: 'claude' } })).payload) as { status: string };
expect(acked.status).toBe('acked');
});
it('GET /handoffs returns fromRole and toRole fields', async () => {
await app.inject({
method: 'POST',
url: '/handoffs',
payload: {
fromRole: 'architect',
toRole: 'implementer',
fromAgent: 'claude',
toAgent: 'codex',
summary: 'Design done',
context: 'See decisions',
},
});
const res = await app.inject({ method: 'GET', url: '/handoffs' });
expect(res.statusCode).toBe(200);
const items = JSON.parse(res.payload) as Array<Record<string, unknown>>;
expect(items).toHaveLength(1);
expect(items[0].fromRole).toBe('architect');
expect(items[0].toRole).toBe('implementer');
expect(items[0].fromAgent).toBe('claude');
expect(items[0].toAgent).toBe('codex');
});
});