fix(api): close contract gaps found by post-merge adversarial audit

A 15-agent audit of the merged tree confirmed 9 envelope/contract bugs;
all fixed here, with live-server contract tests added:

Blockers (fresh-install quick start broken):
- session-ui.js runClaude/runShell unwrapped .data from the /api/cases/:name
  404 error envelope (which has no data key), so a not-yet-created case threw
  TypeError instead of triggering the auto-create fallback. Now '?.data ?? {}'.

Contract violations on the new stable surface:
- Unknown /api routes returned HTTP 404 with {success:true,...} (Fastify's
  default not-found payload was wrapped by the envelope hook). Added a
  setNotFoundHandler returning the standard error envelope for /api paths.
- POST /api/events/subscribe 400 body became {success:true,data:{error}};
  now createErrorResponse(INVALID_INPUT).
- POST /api/clipboard validation error lacked errorCode and shipped HTTP 200;
  now createErrorResponse(INVALID_INPUT) -> 400.
- POST /api/run catch path returned bare {success:false,sessionId,error}
  (HTTP 200, no errorCode); now OPERATION_FAILED envelope -> 422 with the
  dead session id in the message.
- DELETE tail-file/:streamId returned {success: closed}, colliding with the
  envelope discriminator; now returns {closed}.

Dead/regressed UI paths:
- Plan history modal could never open: route returned the bare history array
  under data while the frontend read data.data.history/currentVersion. Route
  now returns {history, currentVersion}; modal task count fixed to stats.total.
- Self-update error toast read j.error.message from the string-typed envelope
  error, always falling back to the generic message; now reads the string.

Cleanup:
- Removed the stale QuickStartResponse type (unreferenced; documented the
  pre-envelope shape and invited success-key collisions).

Tests: new test/http-contract.test.ts boots a real WebServer (port 3168) and
pins the envelope, /api/v1 alias, error statuses, and the /api 404 shape —
the route-test harness does not install the server-level hook, so these need
the live server. Updated file-routes/plan-routes/scheduled-runs tests to the
fixed shapes.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
arkon
2026-06-10 03:41:04 +02:00
co-authored by Claude Opus 4.8
parent 732463b36e
commit c29475ed10
13 changed files with 137 additions and 35 deletions
+92
View File
@@ -0,0 +1,92 @@
/**
* Live-server tests for the stable HTTP contract (docs/api-reference.md):
* the uniform {success,data} envelope, error envelopes with conventional
* HTTP statuses, the /api/v1 alias, and the /api not-found handler.
*
* These behaviors live in server.ts (preSerialization hook, setNotFoundHandler),
* which the route-test harness does not install — so they need a real WebServer.
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { WebServer } from '../src/web/server.js';
const PORT = 3168;
describe('Stable HTTP contract (live server)', () => {
let server: WebServer;
const base = `http://localhost:${PORT}`;
beforeAll(async () => {
server = new WebServer(PORT, false, true);
await server.start();
});
afterAll(async () => {
await server.stop();
});
it('wraps bare payloads as { success: true, data }', async () => {
const res = await fetch(`${base}/api/status`);
expect(res.status).toBe(200);
const body = await res.json();
expect(body.success).toBe(true);
expect(body.data).toBeDefined();
expect(body.data.version).toBeDefined();
});
it('serves the same envelope on the /api/v1 alias', async () => {
const res = await fetch(`${base}/api/v1/status`);
expect(res.status).toBe(200);
const body = await res.json();
expect(body.success).toBe(true);
expect(body.data.version).toBeDefined();
});
it('maps error envelopes to conventional HTTP statuses', async () => {
const res = await fetch(`${base}/api/sessions/nonexistent/terminal`);
expect(res.status).toBe(404);
const body = await res.json();
expect(body.success).toBe(false);
expect(typeof body.error).toBe('string');
expect(body.errorCode).toBe('NOT_FOUND');
});
it('returns a contract-shaped 404 for unknown /api routes', async () => {
const res = await fetch(`${base}/api/this-route-does-not-exist`);
expect(res.status).toBe(404);
const body = await res.json();
expect(body.success).toBe(false);
expect(body.errorCode).toBe('NOT_FOUND');
});
it('returns a contract-shaped 404 for unknown /api/v1 routes', async () => {
const res = await fetch(`${base}/api/v1/this-route-does-not-exist`);
expect(res.status).toBe(404);
const body = await res.json();
expect(body.success).toBe(false);
expect(body.errorCode).toBe('NOT_FOUND');
});
it('rejects a bad /api/events/subscribe body with an error envelope', async () => {
const res = await fetch(`${base}/api/events/subscribe`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({}),
});
expect(res.status).toBe(400);
const body = await res.json();
expect(body.success).toBe(false);
expect(body.errorCode).toBe('INVALID_INPUT');
});
it('keeps validation errors on the envelope with HTTP 400', async () => {
const res = await fetch(`${base}/api/clipboard`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: '' }),
});
expect(res.status).toBe(400);
const body = await res.json();
expect(body.success).toBe(false);
expect(body.errorCode).toBe('INVALID_INPUT');
});
});
+3 -3
View File
@@ -363,11 +363,11 @@ describe('file-routes', () => {
});
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
expect(body.success).toBe(true);
expect(body.closed).toBe(true);
expect(mockedFileStreamManager.closeStream).toHaveBeenCalledWith('stream-1');
});
it('returns false for unknown stream', async () => {
it('returns closed: false for unknown stream', async () => {
mockedFileStreamManager.closeStream.mockReturnValue(false);
const res = await harness.app.inject({
@@ -376,7 +376,7 @@ describe('file-routes', () => {
});
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
expect(body.success).toBe(false);
expect(body.closed).toBe(false);
});
});
+5 -3
View File
@@ -235,13 +235,14 @@ describe('plan-routes', () => {
expect(body.error).toContain('Ralph tracker');
});
it('returns plan version history', async () => {
it('returns plan version history with the current version', async () => {
const mockHistory = [
{ version: 1, timestamp: Date.now() - 60000, itemCount: 10 },
{ version: 2, timestamp: Date.now(), itemCount: 12 },
];
harness.ctx._session.ralphTracker = {
getPlanHistory: vi.fn(() => mockHistory),
planVersion: 2,
} as never;
const res = await harness.app.inject({
@@ -251,8 +252,9 @@ describe('plan-routes', () => {
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
expect(body.success).toBe(true);
expect(body.data).toHaveLength(2);
expect(body.data[1].version).toBe(2);
expect(body.data.history).toHaveLength(2);
expect(body.data.history[1].version).toBe(2);
expect(body.data.currentVersion).toBe(2);
});
});
+8 -2
View File
@@ -205,8 +205,14 @@ describe('Quick Run API', () => {
const data = await response.json();
// On success the payload is wrapped ({ success:true, data:{ sessionId, ... } });
// on failure the handler returns a bare { success:false, sessionId, error }.
expect(data.data?.sessionId ?? data.sessionId).toBeDefined();
// on failure the handler returns the standard error envelope
// ({ success:false, error, errorCode }) with the dead session id in the message.
if (data.success) {
expect(data.data?.sessionId).toBeDefined();
} else {
expect(data.errorCode).toBeDefined();
expect(data.error).toMatch(/session /);
}
// Note: success/failure depends on Claude actually running
});