fix(recovery): restore source removed by production documentation merge

This commit is contained in:
2026-11-10 03:42:10 +01:00
parent 585bdd4b44
commit 3d2fc6f913
957 changed files with 115754 additions and 0 deletions
@@ -0,0 +1,52 @@
import { describe, expect, it } from 'vitest';
import { TOOL_CANDIDATES, candidatesForRole } from '../../src/document-workbench/candidate-catalog';
describe('candidate catalog', () => {
it('includes the selected and alternative tools without marking them ready', () => {
const ids = TOOL_CANDIDATES.map((tool) => tool.id);
expect(new Set(ids).size).toBe(ids.length);
expect(ids).toEqual(
expect.arrayContaining([
'docling',
'unstructured',
'tika',
'tesseract',
'paddleocr',
'duckdb',
'polars',
'frictionless',
'pandera',
'great-expectations',
'valentine',
'rapidfuzz',
'splink',
'assistant-ui',
'temporal',
'langgraph',
'openmeter',
'openrouter',
]),
);
expect(TOOL_CANDIDATES.every((tool) => tool.status === 'qualification_required')).toBe(true);
});
it('finds alternatives by role and flags restricted services for extra review', () => {
expect(candidatesForRole('ocr').map((tool) => tool.id)).toEqual(
expect.arrayContaining(['tesseract', 'paddleocr', 'ocrmypdf']),
);
for (const id of ['pymupdf', 'marker', 'mineru', 'dify', 'n8n', 'open-webui', 'openrouter']) {
expect(TOOL_CANDIDATES.find((tool) => tool.id === id)?.review).toBe(
'additional_license_or_service_review',
);
}
});
it('records bounded-decision, agent and evaluation candidates without authorizing execution', () => {
expect(candidatesForRole('decision').map((tool) => tool.id)).toContain('jev');
expect(candidatesForRole('agent').map((tool) => tool.id)).toEqual(
expect.arrayContaining(['langgraph', 'pydantic-ai', 'microsoft-agent-framework', 'crewai']),
);
expect(candidatesForRole('evaluation').map((tool) => tool.id)).toEqual(
expect.arrayContaining(['promptfoo', 'deepeval', 'ragas', 'langfuse']),
);
expect(TOOL_CANDIDATES.every((tool) => tool.status === 'qualification_required')).toBe(true);
});
});
@@ -0,0 +1,267 @@
import fs from 'node:fs/promises';
import postgres from 'postgres';
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
import { PostgresCreditLedger } from '../../src/document-workbench/credit-ledger';
import { PostgresCreditPurchaseStore } from '../../src/document-workbench/credit-purchase-store';
import { Pay0CreditVerifier } from '../../src/document-workbench/pay0-credit-verification';
import { reconcileCreditPurchase } from '../../src/document-workbench/reconcile-credit-purchase';
const url = process.env.CREDIT_LEDGER_TEST_DATABASE_URL;
const schema = `credit_test_${process.pid}_${Date.now()}`;
const role = `credit_role_${process.pid}_${Date.now()}`;
let admin: ReturnType<typeof postgres>;
let scopedUrl: string;
let sql: ReturnType<typeof postgres>;
let ledger: PostgresCreditLedger;
describe.skipIf(!url)('credit ledger against isolated PostgreSQL schema', () => {
afterEach(() => vi.unstubAllGlobals());
beforeAll(async () => {
if (process.env.CREDIT_LEDGER_TEST_ALLOW_LOCAL !== '1' || new URL(url!).hostname !== '127.0.0.1') {
throw new Error('Only an explicitly enabled isolated loopback database may be used');
}
admin = postgres(url!, { max: 1, prepare: false, connection: { search_path: schema } });
await admin.unsafe(`CREATE SCHEMA ${schema}`);
await admin.unsafe(`CREATE ROLE ${role} LOGIN NOSUPERUSER NOBYPASSRLS`);
await admin.unsafe(await fs.readFile('sql/017_document_credits.sql', 'utf8'));
await admin.unsafe(await fs.readFile('sql/019_document_credit_rls.sql', 'utf8'));
await admin.unsafe(`GRANT USAGE ON SCHEMA ${schema} TO ${role}`);
await admin.unsafe(`GRANT SELECT, INSERT, UPDATE ON ALL TABLES IN SCHEMA ${schema} TO ${role}`);
await admin.unsafe(`GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA ${schema} TO ${role}`);
const appUrl = new URL(url!);
appUrl.username = role;
scopedUrl = appUrl.toString();
sql = postgres(scopedUrl, { max: 8, prepare: false, connection: { search_path: schema } });
ledger = new PostgresCreditLedger(sql);
});
afterAll(async () => {
if (sql) await sql.end();
if (admin) {
try {
await admin.unsafe(`DROP SCHEMA IF EXISTS ${schema} CASCADE`);
await admin.unsafe(`DROP ROLE IF EXISTS ${role}`);
} finally { await admin.end({ timeout: 2 }); }
}
});
it('rejects superusers and does not expose rows without a tenant scope', async () => {
await expect(new PostgresCreditLedger(admin).apply({ tenantId: 'a', idempotencyKey: 'bad-role', kind: 'verified_payment', reference: 'bad-role', amount: 1 })).rejects.toThrow(/RLS-enforced/);
expect(await sql`SELECT * FROM opt_credit_accounts`).toEqual([]);
expect(await sql`SELECT * FROM opt_credit_purchases`).toEqual([]);
});
it('fails before writing when the isolation migration is not fully active', async () => {
await admin.unsafe('ALTER TABLE opt_credit_accounts DISABLE ROW LEVEL SECURITY');
try {
await expect(ledger.apply({ tenantId: 'unscoped', idempotencyKey: 'disabled-rls', kind: 'verified_payment', reference: 'disabled-rls', amount: 1 })).rejects.toThrow(/isolation migration/);
} finally { await admin.unsafe('ALTER TABLE opt_credit_accounts ENABLE ROW LEVEL SECURITY'); }
const rows = await admin`SELECT * FROM opt_credit_accounts WHERE tenant_id = 'unscoped'`;
expect(rows).toEqual([]);
});
it('grants verified payments only once and rejects a payment reused across tenants', async () => {
const payment = {
tenantId: 'a',
idempotencyKey: 'p1',
kind: 'verified_payment' as const,
reference: 'stripe:account:payment-1',
amount: 100,
};
expect((await ledger.apply(payment)).balance).toEqual({ available: 100, reserved: 0 });
expect((await ledger.apply(payment)).replay).toBe(true);
await expect(ledger.apply({ ...payment, amount: 101 })).rejects.toThrow(/Idempotency/);
await expect(ledger.apply({ ...payment, tenantId: 'b' })).rejects.toThrow();
});
it('serializes concurrent reservations and prevents overspending', async () => {
const command = { tenantId: 'a', kind: 'reserve' as const, amount: 80 };
const outcomes = await Promise.allSettled([
ledger.apply({ ...command, idempotencyKey: 'r1', reference: 'job1' }),
ledger.apply({ ...command, idempotencyKey: 'r2', reference: 'job2' }),
]);
expect(outcomes.filter((item) => item.status === 'fulfilled')).toHaveLength(1);
expect(outcomes.filter((item) => item.status === 'rejected')).toHaveLength(1);
const won = outcomes.find((item) => item.status === 'fulfilled') as PromiseFulfilledResult<{
replay: boolean;
balance: { available: number; reserved: number };
}>;
expect(won.value.balance).toEqual({ available: 20, reserved: 80 });
const rows = await sql.begin(async (tx) => {
await tx`SELECT set_config('app.opt_credit_tenant_id', 'a', true)`;
return tx<{ reservation_id: string }[]>`SELECT reservation_id FROM opt_credit_reservations`;
});
const reservationId = rows[0]!.reservation_id;
await expect(
ledger.apply({
tenantId: 'a',
idempotencyKey: 'over',
kind: 'settle',
reference: reservationId,
amount: 81,
}),
).rejects.toThrow(/exceeds/);
const settled = await ledger.apply({
tenantId: 'a',
idempotencyKey: 's1',
kind: 'settle',
reference: reservationId,
amount: 30,
});
expect(settled.balance).toEqual({ available: 70, reserved: 0 });
await expect(
ledger.apply({
tenantId: 'a',
idempotencyKey: 's2',
kind: 'settle',
reference: reservationId,
amount: 30,
}),
).rejects.toThrow(/not found/);
});
it("cannot release another tenant's reservation and returns unused credits on release", async () => {
await ledger.apply({
tenantId: 'a',
idempotencyKey: 'r3',
kind: 'reserve',
reference: 'job3',
amount: 40,
});
await expect(
ledger.apply({
tenantId: 'b',
idempotencyKey: 'release-foreign',
kind: 'release',
reference: 'job3',
amount: 0,
}),
).rejects.toThrow(/not found/);
expect(
(
await ledger.apply({
tenantId: 'a',
idempotencyKey: 'release-own',
kind: 'release',
reference: 'job3',
amount: 0,
})
).balance,
).toEqual({ available: 70, reserved: 0 });
});
it('deduplicates concurrent payment callbacks and preserves the account across connections', async () => {
const payment = {
tenantId: 'c',
idempotencyKey: 'concurrent-payment',
kind: 'verified_payment' as const,
reference: 'stripe:account:payment-2',
amount: 25,
};
const results = await Promise.all([ledger.apply(payment), ledger.apply(payment)]);
expect(results.map((item) => item.replay).sort()).toEqual([false, true]);
const secondSql = postgres(scopedUrl, { max: 1, prepare: false, connection: { search_path: schema } });
try {
const replay = await new PostgresCreditLedger(secondSql).apply(payment);
expect(replay).toEqual({ replay: true, balance: { available: 25, reserved: 0 } });
} finally {
await secondSql.end();
}
});
it('stores a tenant-scoped price snapshot and rejects changed or reused checkout data', async () => {
const store = new PostgresCreditPurchaseStore(sql);
const purchase = {
tenantId: 'a',
purchaseId: 'purchase-1',
checkoutSessionId: 'cs-1',
amountMinor: 1000,
currency: 'SEK',
credits: 25,
};
expect(await store.create(purchase)).toEqual(purchase);
expect(await store.create(purchase)).toEqual(purchase);
expect(await store.get('b', 'purchase-1')).toBeUndefined();
await expect(store.create({ ...purchase, credits: 500 })).rejects.toThrow(/different price snapshot/);
await expect(store.create({ ...purchase, tenantId: 'b', purchaseId: 'purchase-2' })).rejects.toThrow();
});
it('reconciles a stored purchase through PAY0 and grants exactly once', async () => {
const purchases = new PostgresCreditPurchaseStore(sql);
await purchases.create({
tenantId: 'd',
purchaseId: 'purchase-d',
checkoutSessionId: 'cs-d',
amountMinor: 1000,
currency: 'SEK',
credits: 25,
});
const common = {
tenant_id: 'd',
payable_type: '0pt_credit_purchase',
payable_ref: 'purchase-d',
currency: 'SEK',
};
vi.stubGlobal(
'fetch',
vi.fn(
async (url: string) =>
new Response(
JSON.stringify({
data: url.includes('checkout-sessions')
? {
...common,
id: 'cs-d',
payment_intent_id: 'pi-d',
amount_snapshot: 1000,
status: 'completed',
provider: 'stripe',
provider_reference: 'psp-d',
}
: {
...common,
id: 'pi-d',
amount: 1000,
canonical_status: 'captured',
captured_amount: 1000,
refunded_amount: 0,
},
}),
{ status: 200 },
),
),
);
const context = {
tenantId: 'd',
actorId: 'svc-0pt',
capability: '0pt.credit.purchase',
correlationId: 'req-d',
};
const deps = { purchases, ledger, pay0: new Pay0CreditVerifier('https://pay0.test', 'service-token') };
expect(await reconcileCreditPurchase(deps, 'd', 'purchase-d', context)).toEqual({
replay: false,
balance: { available: 25, reserved: 0 },
});
expect(await reconcileCreditPurchase(deps, 'd', 'purchase-d', context)).toEqual({
replay: true,
balance: { available: 25, reserved: 0 },
});
await expect(
reconcileCreditPurchase(deps, 'd', 'purchase-d', { ...context, tenantId: 'other' }),
).rejects.toThrow(/scope/);
});
it('enforces tenant filters even when a query omits its predicate', async () => {
const visible = await sql.begin(async (tx) => {
await tx`SELECT set_config('app.opt_credit_tenant_id', 'a', true)`;
const accounts = await tx<{ tenant_id: string }[]>`SELECT tenant_id FROM opt_credit_accounts`;
const purchases = await tx<{ tenant_id: string }[]>`SELECT tenant_id FROM opt_credit_purchases`;
return { accounts, purchases };
});
expect(visible.accounts).toEqual([{ tenant_id: 'a' }]);
expect(visible.purchases).toEqual([{ tenant_id: 'a' }]);
expect(await sql`SELECT * FROM opt_credit_accounts`).toEqual([]);
await expect(sql.begin(async (tx) => {
await tx`SELECT set_config('app.opt_credit_tenant_id', 'b', true)`;
await tx`INSERT INTO opt_credit_accounts (tenant_id) VALUES ('wrong-tenant')`;
})).rejects.toThrow();
});
});
@@ -0,0 +1,30 @@
import { describe, expect, it } from 'vitest';
import { quoteMaximumCredits } from '../../src/document-workbench/credit-quote';
describe('credit quote', () => {
it('rounds each component up exactly and retains the price book version', () => {
expect(
quoteMaximumCredits('v1', [
{ metric: 'pages', maxUnits: 11, creditsPerBlock: 3, unitsPerBlock: 10 },
{ metric: 'tokens', maxUnits: 2000, creditsPerBlock: 2, unitsPerBlock: 1000 },
]),
).toMatchObject({ priceBookVersion: 'v1', maximumCredits: 10 });
});
it('does not charge an unused component', () => {
expect(
quoteMaximumCredits('v1', [{ metric: 'pages', maxUnits: 0, creditsPerBlock: 1, unitsPerBlock: 10 }])
.maximumCredits,
).toBe(0);
});
it('rejects fractional, negative, duplicate and overflowing quantities', () => {
const line = { metric: 'pages', maxUnits: 1, creditsPerBlock: 1, unitsPerBlock: 1 };
expect(() => quoteMaximumCredits('', [line])).toThrow();
expect(() => quoteMaximumCredits('v1', [line, line])).toThrow();
expect(() => quoteMaximumCredits('v1', [{ ...line, maxUnits: 0.5 }])).toThrow();
expect(() => quoteMaximumCredits('v1', [{ ...line, creditsPerBlock: -1 }])).toThrow();
expect(() => quoteMaximumCredits('v1', [{ ...line, unitsPerBlock: 0 }])).toThrow();
expect(() =>
quoteMaximumCredits('v1', [{ ...line, maxUnits: Number.MAX_SAFE_INTEGER, creditsPerBlock: 2 }]),
).toThrow();
});
});
@@ -0,0 +1,123 @@
import { describe, expect, it } from 'vitest';
import {
DecisionOllamaGatewayClient,
assertTrustedDecisionOllamaUrl,
} from '../../src/document-workbench/decision-ollama-client';
import { Inf0OutcomeUnknownError } from '../../src/document-workbench/inf0-gateway-client';
import { createInf0Gateway } from '../../src/document-workbench/inf0-gateway';
const context = {
tenantId: 't_0pt',
projectId: 'prj_default',
actorId: 'user_1',
capability: '0pt.document.structure.v1',
correlationId: 'corr-1',
};
const admission = {
tenantId: 't_0pt',
projectId: 'prj_default',
jobId: 'job-1',
modelId: 'hermes-qwen3.5:9b',
dataClass: 'low',
maxInputTokens: 1000,
maxOutputTokens: 200,
maximumCredits: 0,
};
const policy = {
tenantId: 't_0pt',
projectId: 'prj_default',
allowedModelIds: ['hermes-qwen3.5:9b'],
allowedDataClasses: ['low'],
destination: 'internal' as const,
externalTransferAllowed: false,
maxInputTokens: 1000,
maxOutputTokens: 200,
};
const messages = [
{ role: 'system' as const, content: 'system' },
{ role: 'user' as const, content: 'data' },
];
function client(fetchImpl: typeof fetch, model = 'hermes-qwen3.5:9b') {
return new DecisionOllamaGatewayClient({
baseUrl: 'http://100.96.133.104:11434',
model,
fetchImpl,
});
}
describe('decision server Ollama gateway', () => {
it('accepts tailnet/RFC1918 HTTP but refuses a public HTTP endpoint', () => {
expect(() => assertTrustedDecisionOllamaUrl('http://100.96.133.104:11434')).not.toThrow();
expect(() => assertTrustedDecisionOllamaUrl('http://192.168.1.10:11434')).not.toThrow();
expect(() => assertTrustedDecisionOllamaUrl('https://ai.example.test')).not.toThrow();
expect(() => assertTrustedDecisionOllamaUrl('http://8.8.8.8:11434')).toThrow();
expect(() => assertTrustedDecisionOllamaUrl('http://user:pass@100.96.133.104:11434')).toThrow();
});
it('maps a native Ollama chat response into the INF0 receipt', async () => {
const c = client(async (url, init) => {
expect(String(url)).toMatch(/\/api\/chat$/);
const body = JSON.parse(String(init?.body));
expect(body.format).toBe('json');
expect(body.think).toBe(false);
return Response.json({
model: 'hermes-qwen3.5:9b',
message: { role: 'assistant', content: '{"value":{}}' },
done: true,
done_reason: 'stop',
prompt_eval_count: 12,
eval_count: 8,
});
});
await expect(
c.complete({ context, admission, policy, reservation: undefined, inputTokens: 12, messages }),
).resolves.toMatchObject({
status: 'model_stopped',
modelExecuted: 'hermes-qwen3.5:9b',
providerKind: 'local',
totalTokens: 20,
});
});
it('refuses an external destination and malformed usage', async () => {
const c = client(async () =>
Response.json({
model: 'hermes-qwen3.5:9b',
message: { role: 'assistant', content: 'x' },
done: true,
done_reason: 'stop',
prompt_eval_count: 1,
eval_count: 5000,
}),
);
await expect(
c.complete({
context,
admission,
policy: { ...policy, destination: 'external' },
reservation: undefined,
inputTokens: 1,
messages,
}),
).rejects.toThrow(/denied/i);
await expect(
c.complete({ context, admission, policy, reservation: undefined, inputTokens: 1, messages }),
).rejects.toBeInstanceOf(Inf0OutcomeUnknownError);
});
it('is preferred over the INF0/LiteLLM path when configured', () => {
expect(
createInf0Gateway({
DECISION_OLLAMA_URL: 'http://100.96.133.104:11434',
DECISION_OLLAMA_MODEL: 'hermes-qwen3.5:9b',
INF0_GATEWAY_LITELLM_KEY: 'sk-test',
} as unknown as NodeJS.ProcessEnv),
).toBeInstanceOf(DecisionOllamaGatewayClient);
expect(
createInf0Gateway({
INF0_GATEWAY_LITELLM_KEY: 'sk-test',
} as unknown as NodeJS.ProcessEnv),
).not.toBeInstanceOf(DecisionOllamaGatewayClient);
});
});
@@ -0,0 +1,69 @@
import { createHash } from 'node:crypto';
import { describe, expect, it, vi } from 'vitest';
import { Doc0SourceClient, Doc0SourceUnavailableError } from '../../src/document-workbench/doc0-source-client';
const hash = (value: string) => createHash('sha256').update(value).digest('hex');
const receipt = { documentId: 'doc-a', versionId: 'version-a', checksumSha256: 'a'.repeat(64), pipelineStage: 'parsed' };
const input = { tenantId: 'tenant-a', projectId: 'project-a', actorId: 'user-a', requestId: 'request-a', receipt };
const text = 'Acme 😀';
const metadata = { tenantId: input.tenantId, documentId: receipt.documentId, versionId: receipt.versionId,
documentTextId: 'text-a', parserRunId: 'run-a', segmentsTruncated: false, segmentCount: 1, charCount: text.length, textSha256: hash(text) };
const segment = { tenantId: input.tenantId, documentId: receipt.documentId, versionId: receipt.versionId,
documentTextId: 'text-a', parserRunId: 'run-a', segmentId: 'segment-a', sequence: 0, text, charStart: 0,
charEnd: text.length, segmentSha256: hash(text), sourceVersionSha256: receipt.checksumSha256 };
const payload = { offset: 0, texts: [metadata], segments: [segment] };
describe('DOC0 extracted source client', () => {
it('reads scoped, checksum-bound segment text without caching or redirects', async () => {
const fetchImpl = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
expect(String(url)).toContain('/v1/doc0/documents/doc-a/versions/version-a/segments?limit=100&offset=0');
expect(new Headers(init?.headers).get('x-tenant-id')).toBe('tenant-a');
expect(new Headers(init?.headers).get('x-actor-id')).toBe('user-a');
expect(init?.redirect).toBe('error');
expect(init?.cache).toBe('no-store');
return Response.json(payload);
});
const client = new Doc0SourceClient({ baseUrl: 'https://doc0.test', serviceToken: 'test', fetchImpl });
expect(await client.read(input)).toEqual({ sources: [{ id: 'segment-a', text }], reportedTextSha256: hash(text) });
});
it('rejects incomplete, forged, cross-tenant or inconsistent text instead of passing it to a model', async () => {
const bad = [
{ ...payload, texts: [{ ...metadata, segmentsTruncated: true }] },
{ ...payload, texts: [{ ...metadata, segmentCount: 2 }] },
{ ...payload, texts: [{ ...metadata, tenantId: 'tenant-b' }] },
{ ...payload, texts: [metadata, metadata] },
{ ...payload, segments: [{ ...segment, sourceVersionSha256: 'b'.repeat(64) }] },
{ ...payload, segments: [{ ...segment, text: 'fabricated' }] },
{ ...payload, segments: [{ ...segment, tenantId: 'tenant-b' }] },
{ ...payload, segments: [{ ...segment, sequence: 1 }] },
{ ...payload, segments: [{ ...segment, charEnd: 5 }] },
{ ...payload, offset: 1 },
];
for (const candidate of bad) {
const client = new Doc0SourceClient({ baseUrl: 'https://doc0.test', serviceToken: 'test', fetchImpl: async () => Response.json(candidate) });
await expect(client.read(input)).rejects.toBeInstanceOf(Doc0SourceUnavailableError);
}
});
it('rejects empty, oversized, unavailable and unparsed sources', async () => {
const fetchImpl = vi.fn(async () => Response.json(payload));
const client = new Doc0SourceClient({ baseUrl: 'https://doc0.test', serviceToken: 'test', fetchImpl });
await expect(client.read({ ...input, receipt: { ...receipt, pipelineStage: 'parse_failed' } })).rejects.toBeInstanceOf(Doc0SourceUnavailableError);
expect(fetchImpl).not.toHaveBeenCalled();
for (const response of [Response.json({ ...payload, texts: [] }), new Response('x'.repeat(1024 * 1024 + 1)), new Response('', { status: 503 })]) {
const bad = new Doc0SourceClient({ baseUrl: 'https://doc0.test', serviceToken: 'test', fetchImpl: async () => response });
await expect(bad.read(input)).rejects.toBeInstanceOf(Doc0SourceUnavailableError);
}
});
it('pins the original scope and validated credential during an in-flight read', async () => {
const mutable = structuredClone(input);
const config = { baseUrl: 'https://doc0.test', serviceToken: 'original', fetchImpl: async (_url: string | URL | Request, init?: RequestInit) => {
expect(new Headers(init?.headers).get('authorization')).toBe('Bearer original');
mutable.tenantId = 'tenant-b';
mutable.receipt.checksumSha256 = 'b'.repeat(64);
return Response.json(payload);
} };
const client = new Doc0SourceClient(config);
config.serviceToken = 'changed';
expect(await client.read(mutable)).toMatchObject({ sources: [{ id: 'segment-a', text }] });
});
});
@@ -0,0 +1,211 @@
import { createHash } from 'node:crypto';
import { describe, expect, it, vi } from 'vitest';
import { Doc0UploadClient, Doc0UploadOutcomeUnknownError, Doc0InspectionUnavailableError, prepareDoc0UploadIdentity } from '../../src/document-workbench/doc0-upload-client';
const bytes = new TextEncoder().encode('source bytes');
const input = {
tenantId: 'tenant-a',
projectId: 'project-a',
actorId: 'user-a',
requestId: 'req-a',
idempotencyKey: 'idem-a',
filename: 'test.txt',
mimeType: 'text/plain',
classification: 'confidential' as const,
bytes,
};
const receipt = {
document: { documentId: 'doc-a', tenantId: 'tenant-a', projectId: 'project-a', currentVersionId: 'v1' },
currentVersion: {
versionId: 'v1',
tenantId: 'tenant-a',
documentId: 'doc-a',
checksumSha256: createHash('sha256').update(bytes).digest('hex'),
sizeBytes: bytes.length,
pipelineStage: 'parsed',
},
};
describe('DOC0 upload client', () => {
it('validates the receipt against the original scope even if the caller mutates its input during dispatch', async () => {
const mutable = { ...input, bytes: new Uint8Array(input.bytes) };
const fetchImpl = async () => {
mutable.tenantId = 'tenant-b';
mutable.projectId = 'project-b';
return Response.json({ ...receipt,
document: { ...receipt.document, tenantId: 'tenant-b', projectId: 'project-b' },
currentVersion: { ...receipt.currentVersion, tenantId: 'tenant-b' },
}, { status: 201 });
};
const client = new Doc0UploadClient({ baseUrl: 'https://doc0.test', serviceToken: 'test', maxBytes: 100, fetchImpl });
await expect(client.upload(mutable)).rejects.toBeInstanceOf(Doc0UploadOutcomeUnknownError);
});
it('accepts a matching receipt for the bytes and scope actually dispatched', async () => {
const mutable = { ...input, bytes: new Uint8Array(input.bytes) };
const fetchImpl = async (_url: string | URL | Request, init?: RequestInit) => {
mutable.tenantId = 'tenant-b';
mutable.bytes.fill(0);
const sentFile = (init?.body as FormData).get('file') as Blob;
expect(await sentFile.text()).toBe('source bytes');
return Response.json(receipt, { status: 201 });
};
const client = new Doc0UploadClient({ baseUrl: 'https://doc0.test', serviceToken: 'test', maxBytes: 100, fetchImpl });
await expect(client.upload(mutable)).resolves.toMatchObject({ documentId: 'doc-a' });
});
it('pins validated client configuration rather than trusting later mutations', async () => {
const fetchImpl = vi.fn(async (_url: string | URL | Request, init?: RequestInit) => {
expect(new Headers(init?.headers).get('authorization')).toBe('Bearer test');
return Response.json(receipt, { status: 201 });
});
const config = { baseUrl: 'https://doc0.test', serviceToken: 'test', maxBytes: 100, timeoutMs: 1000, fetchImpl };
const client = new Doc0UploadClient(config);
config.serviceToken = 'changed';
config.maxBytes = 1;
config.timeoutMs = 0;
await expect(client.upload(input)).resolves.toMatchObject({ documentId: 'doc-a' });
});
it('sends real bytes and validates a tenant-scoped checksum-bound receipt', async () => {
const fetchImpl = vi.fn(async (_url: string | URL | Request, init?: RequestInit) => {
expect(new Headers(init?.headers).get('x-tenant-id')).toBe('tenant-a');
expect(new Headers(init?.headers).get('x-idempotency-key')).toBe('idem-a');
expect(init?.redirect).toBe('error');
const form = init?.body as FormData;
expect(await (form.get('file') as Blob).text()).toBe('source bytes');
return new Response(JSON.stringify(receipt), { status: 201 });
});
const client = new Doc0UploadClient({
baseUrl: 'https://doc0.test',
serviceToken: 'test',
maxBytes: 100,
fetchImpl: fetchImpl as typeof fetch,
});
expect(await client.upload(input)).toMatchObject({
documentId: 'doc-a',
versionId: 'v1',
pipelineStage: 'parsed',
});
});
it.each(['rapport åäö.xlsx', 'folder/name.txt', 'Back\\path.txt', 'A"B.txt', 'row\r\nname.txt'])(
'uses stable multipart metadata while retaining original name: %s', async (filename) => {
const fixture = { ...input, filename, mimeType: 'APPLICATION/PDF' };
const identity = prepareDoc0UploadIdentity(fixture);
const fetchImpl = vi.fn(async (_url: string | URL | Request, init?: RequestInit) => {
const form = init?.body as FormData;
expect(JSON.parse(form.get('input') as string).displayName).toBe(filename);
expect((form.get('file') as File).name).toBe(identity.wireFilename);
expect((form.get('file') as File).type).toBe('application/pdf');
return Response.json(receipt, { status: 201 });
});
await new Doc0UploadClient({ baseUrl: 'https://doc0.test', serviceToken: 'test', maxBytes: 100, fetchImpl }).upload(fixture);
expect(identity.sourceSha256).toBe(receipt.currentVersion.checksumSha256);
expect(identity.requestFingerprint).toMatch(/^[0-9a-f]{64}$/);
expect(fetchImpl).toHaveBeenCalledOnce();
},
);
it('rejects non-canonical identity headers before any upload', async () => {
const fetchImpl = vi.fn();
const client = new Doc0UploadClient({ baseUrl: 'https://doc0.test', serviceToken: 'test', maxBytes: 100, fetchImpl });
for (const tenantId of [' tenant-a', 'tenant-a ', 'tenant-å', 'tenant-\n']) {
await expect(client.upload({ ...input, tenantId })).rejects.toThrow(/Invalid/);
}
expect(fetchImpl).not.toHaveBeenCalled();
});
it('rejects ambiguous MIME values before any upload', async () => {
const fetchImpl = vi.fn();
const client = new Doc0UploadClient({ baseUrl: 'https://doc0.test', serviceToken: 'test', maxBytes: 100, fetchImpl });
for (const mimeType of ['text/plain; charset=utf-8', 'text/å', ' text/plain', 'not-a-mime']) {
await expect(client.upload({ ...input, mimeType })).rejects.toThrow(/MIME/);
}
expect(fetchImpl).not.toHaveBeenCalled();
});
it.each([
{ document: { ...receipt.document, tenantId: 'tenant-b' } },
{ document: { ...receipt.document, projectId: 'other' } },
{ currentVersion: { ...receipt.currentVersion, checksumSha256: 'bad' } },
{ currentVersion: { ...receipt.currentVersion, documentId: 'other' } },
])('rejects an incorrect receipt', async (change) => {
const client = new Doc0UploadClient({
baseUrl: 'https://doc0.test',
serviceToken: 'test',
maxBytes: 100,
fetchImpl: async () => new Response(JSON.stringify({ ...receipt, ...change }), { status: 201 }),
});
await expect(client.upload(input)).rejects.toThrow(/receipt/);
});
it('rejects empty or oversized inputs before calling DOC0', async () => {
const fetchImpl = vi.fn();
const client = new Doc0UploadClient({
baseUrl: 'https://doc0.test',
serviceToken: 'test',
maxBytes: 2,
fetchImpl,
});
await expect(client.upload(input)).rejects.toThrow(/Invalid/);
await expect(client.upload({ ...input, bytes: new Uint8Array() })).rejects.toThrow(/Invalid/);
expect(fetchImpl).not.toHaveBeenCalled();
});
it('rejects insecure endpoints, embedded credentials and invalid timeouts', () => {
const base = { serviceToken: 'test', maxBytes: 100 };
for (const baseUrl of ['http://doc0.test', 'https://doc0.test?token=x', 'file:///tmp/doc0', 'not a URL']) {
expect(() => new Doc0UploadClient({ ...base, baseUrl })).toThrow(/HTTPS/);
}
const credentialUrl = new URL('https://doc0.test');
credentialUrl.username = 'fixture';
credentialUrl.password = 'fixture';
expect(() => new Doc0UploadClient({ ...base, baseUrl: credentialUrl.toString() })).toThrow(/HTTPS/);
expect(() => new Doc0UploadClient({ ...base, baseUrl: 'https://doc0.test', timeoutMs: 0 })).toThrow(/limits/);
});
it('treats transport failure and non-success responses as unknown outcomes without retrying', async () => {
for (const response of [new Error('connection reset'), new Response('unavailable', { status: 503 })]) {
const fetchImpl = vi.fn(async () => { if (response instanceof Error) throw response; return response; });
const client = new Doc0UploadClient({ baseUrl: 'https://doc0.test', serviceToken: 'test', maxBytes: 100, fetchImpl });
await expect(client.upload(input)).rejects.toBeInstanceOf(Doc0UploadOutcomeUnknownError);
expect(fetchImpl).toHaveBeenCalledOnce();
}
});
it('rejects broken, malformed and oversized receipts as unknown outcomes', async () => {
const broken = new ReadableStream<Uint8Array>({ start(controller) { controller.error(new Error('broken')); } });
const locked = new Response('{}');
const lock = locked.body!.getReader();
for (const response of [new Response(broken), new Response('{'), new Response('x'.repeat(128 * 1024 + 1)), locked]) {
const client = new Doc0UploadClient({ baseUrl: 'https://doc0.test', serviceToken: 'test', maxBytes: 100, fetchImpl: async () => response });
await expect(client.upload(input)).rejects.toBeInstanceOf(Doc0UploadOutcomeUnknownError);
}
lock.releaseLock();
});
});
describe('DOC0 upload inspection', () => {
const inspection = { tenantId: 'tenant-a', projectId: 'project-a', actorId: 'actor-a', requestId: 'req-a', idempotencyKey: 'idem-a', sourceSha256: 'a'.repeat(64), sourceSizeBytes: 12, requestFingerprint: 'b'.repeat(64) };
it('sends only scoped metadata and returns the recorded journal state without retry', async () => {
const fetchImpl = vi.fn(async (_url: string | URL | Request, init?: RequestInit) => {
expect(init?.redirect).toBe('error');
expect(init?.cache).toBe('no-store');
expect(new Headers(init?.headers).get('x-idempotency-key')).toBe('idem-a');
expect(JSON.parse(String(init?.body))).toEqual({ projectId: 'project-a', sourceSha256: 'a'.repeat(64), sourceSizeBytes: 12, requestFingerprint: 'b'.repeat(64) });
return Response.json({ status: 'completed_recorded', documentId: 'doc', versionId: 'v1' });
});
const client = new Doc0UploadClient({ baseUrl: 'https://doc0.test', serviceToken: 'test', maxBytes: 100, fetchImpl });
expect(await client.inspect(inspection)).toEqual({ status: 'completed_recorded', documentId: 'doc', versionId: 'v1' });
expect(fetchImpl).toHaveBeenCalledOnce();
});
it('preserves weaker states without turning them into successful uploads', async () => {
for (const status of ['not_found', 'in_progress', 'reconciliation_required'] as const) {
const client = new Doc0UploadClient({ baseUrl: 'https://doc0.test', serviceToken: 'test', maxBytes: 100, fetchImpl: async () => Response.json({ status }) });
expect(await client.inspect(inspection)).toEqual({ status });
}
});
it('fails closed on unknown, malformed, excessive or unavailable responses', async () => {
const responses = [Response.json({ status: 'completed' }), Response.json({ status: 'completed_recorded', documentId: 'doc' }), Response.json({ status: 'not_found', documentId: 'unexpected' }), new Response('x'.repeat(128 * 1024 + 1)), new Response('unavailable', { status: 503 })];
for (const response of responses) {
const client = new Doc0UploadClient({ baseUrl: 'https://doc0.test', serviceToken: 'test', maxBytes: 100, fetchImpl: async () => response });
await expect(client.inspect(inspection)).rejects.toBeInstanceOf(Doc0InspectionUnavailableError);
}
});
it('rejects invalid fingerprints before sending a request', async () => {
const fetchImpl = vi.fn();
const client = new Doc0UploadClient({ baseUrl: 'https://doc0.test', serviceToken: 'test', maxBytes: 100, fetchImpl });
await expect(client.inspect({ ...inspection, requestFingerprint: 'bad' })).rejects.toThrow(/Invalid/);
expect(fetchImpl).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,49 @@
import { describe, expect, it } from 'vitest';
import { exportValidatedOutput } from '../../src/document-workbench/export-validated-output';
const fields = [
{ name: 'name', type: 'string' as const, required: true },
{ name: 'count', type: 'integer' as const, required: true },
];
const sources = [{ id: 'source', text: 'Acme, "North"\n-2' }];
const evidence = [
{ field: 'name', sourceId: 'source', start: 0, end: 13, transform: 'exact' as const },
{ field: 'count', sourceId: 'source', start: 14, end: 16, transform: 'integer' as const },
];
const input = { fields, sources, evidence, value: { name: 'Acme, "North"', count: -2 } };
describe('validated document exports', () => {
it('preserves JSON values and produces correctly escaped, ordered CSV', () => {
const json = exportValidatedOutput({ ...input, format: 'json' });
expect(json.status).toBe('ready');
if (json.status === 'ready') expect(JSON.parse(json.content)).toEqual(input.value);
expect(exportValidatedOutput({ ...input, format: 'csv' })).toEqual({
status: 'ready', mediaType: 'text/csv', content: '"name","count"\r\n"Acme, ""North""","-2"\r\n',
});
});
it('revalidates evidence and refuses unsupported or absent data', () => {
expect(exportValidatedOutput({ ...input, value: { ...input.value, name: 'invented' }, format: 'json' }).status).toBe('needs_review');
expect(exportValidatedOutput({ ...input, evidence: [], format: 'csv' }).status).toBe('needs_review');
const optional = { ...input, fields: [...fields, { name: 'note', type: 'string' as const, required: false }] };
expect(exportValidatedOutput({ ...optional, format: 'csv' })).toMatchObject({ status: 'needs_review', issues: [{ field: 'note', code: 'csv_missing_value' }] });
expect(exportValidatedOutput({ ...optional, format: 'json' }).status).toBe('ready');
expect(exportValidatedOutput({ ...input, format: 'xml' as 'json' })).toMatchObject({ status: 'needs_review', issues: [{ code: 'unsupported_export_format' }] });
});
it('rejects formula-like CSV values and headers without changing JSON', () => {
const bad = { fields: [{ name: 'cell', type: 'string' as const, required: true }], sources: [{ id: 's', text: ' =1+1' }], evidence: [{ field: 'cell', sourceId: 's', start: 0, end: 6, transform: 'exact' as const }], value: { cell: ' =1+1' } };
expect(exportValidatedOutput({ ...bad, format: 'csv' })).toMatchObject({ status: 'needs_review', issues: [{ code: 'csv_unsafe_cell' }] });
expect(exportValidatedOutput({ ...bad, format: 'json' }).status).toBe('ready');
const header = { fields: [{ name: '=header', type: 'string' as const, required: true }], sources: [{ id: 's', text: 'safe' }], evidence: [{ field: '=header', sourceId: 's', start: 0, end: 4, transform: 'exact' as const }], value: { '=header': 'safe' } };
expect(exportValidatedOutput({ ...header, format: 'csv' })).toMatchObject({ status: 'needs_review', issues: [{ code: 'csv_unsafe_cell' }] });
});
it('preserves a source-backed decimal as text without floating-point rounding', () => {
const text = '9007199254740993.20';
const decimal = { fields: [{ name: 'amount', type: 'decimal' as const, required: true }], sources: [{ id: 's', text }], evidence: [{ field: 'amount', sourceId: 's', start: 0, end: text.length, transform: 'decimal' as const }], value: { amount: text } };
const result = exportValidatedOutput({ ...decimal, format: 'json' });
expect(result.status).toBe('ready');
if (result.status === 'ready') expect(JSON.parse(result.content)).toEqual({ amount: text });
});
});
@@ -0,0 +1,46 @@
import { describe, expect, it } from 'vitest';
import {
bindOperationToUploadIdentity,
prepareDoc0UploadIdentity,
type Doc0UploadInput,
} from '../../src/document-workbench/doc0-upload-client';
const input: Doc0UploadInput = {
tenantId: 't1', projectId: 'p1', actorId: 'a1', requestId: 'r1', idempotencyKey: 'k1',
filename: 'rapport.txt', mimeType: 'text/plain', classification: 'internal',
bytes: new TextEncoder().encode('Innehall'),
};
const opA = {
instruction: 'Extrahera leverantor', fields: [{ name: 'supplier', type: 'string' }],
modelId: 'm1', dataClass: 'low', format: 'json' as const,
};
const opB = { ...opA, instruction: 'Extrahera belopp' };
describe('operation-scoped upload identity', () => {
it('same file + same operation binds to one identity', () => {
expect(prepareDoc0UploadIdentity(bindOperationToUploadIdentity(input, opA)))
.toEqual(prepareDoc0UploadIdentity(bindOperationToUploadIdentity(input, opA)));
});
it('same file + DIFFERENT instruction = DIFFERENT identity (not the same operation)', () => {
const a = prepareDoc0UploadIdentity(bindOperationToUploadIdentity(input, opA));
const b = prepareDoc0UploadIdentity(bindOperationToUploadIdentity(input, opB));
expect(a.requestFingerprint).not.toBe(b.requestFingerprint);
});
it('changed model or data class also changes the operation identity', () => {
const c = prepareDoc0UploadIdentity(bindOperationToUploadIdentity(input, { ...opA, modelId: 'm2' }));
const d = prepareDoc0UploadIdentity(bindOperationToUploadIdentity(input, { ...opA, dataClass: 'high' }));
const e = prepareDoc0UploadIdentity(bindOperationToUploadIdentity(input, { ...opA, format: 'csv' }));
expect(c.requestFingerprint).not.toBe(prepareDoc0UploadIdentity(bindOperationToUploadIdentity(input, opA)).requestFingerprint);
expect(d.requestFingerprint).not.toBe(prepareDoc0UploadIdentity(bindOperationToUploadIdentity(input, opA)).requestFingerprint);
expect(e.requestFingerprint).not.toBe(prepareDoc0UploadIdentity(bindOperationToUploadIdentity(input, opA)).requestFingerprint);
});
it('raw bytes checksum stays stable across operations', () => {
const a = prepareDoc0UploadIdentity(bindOperationToUploadIdentity(input, opA));
const b = prepareDoc0UploadIdentity(bindOperationToUploadIdentity(input, opB));
expect(a.sourceSha256).toBe(b.sourceSha256);
});
it('prefixes the operation marker so odd filenames cannot collide', () => {
const bound = bindOperationToUploadIdentity(input, opA);
expect(bound.filename.startsWith('rapport.txt#')).toBe(true);
});
});
@@ -0,0 +1,59 @@
import { describe, expect, it, vi } from 'vitest';
import { Inf0GatewayClient, Inf0OutcomeUnknownError } from '../../src/document-workbench/inf0-gateway-client';
import type { ModelAdmissionRequest, ModelBudgetReservation, ModelExecutionPolicy } from '../../src/document-workbench/model-admission';
import type { SiaxRequestContext } from '../../src/platform/siax-context';
const context: SiaxRequestContext = { tenantId: 'a', projectId: 'p', actorId: 'user', capability: 'inf0.complete', correlationId: 'corr' };
const admission: ModelAdmissionRequest = { tenantId: 'a', projectId: 'p', jobId: 'j', modelId: 'local_only', dataClass: 'high', maxInputTokens: 100, maxOutputTokens: 20, maximumCredits: 5 };
const policy: ModelExecutionPolicy = { tenantId: 'a', projectId: 'p', allowedModelIds: ['local_only'], allowedDataClasses: ['high'], destination: 'internal', externalTransferAllowed: false, maxInputTokens: 100, maxOutputTokens: 20 };
const reservation: ModelBudgetReservation = { tenantId: 'a', projectId: 'p', jobId: 'j', status: 'reserved', credits: 5 };
const input = { context, admission, policy, reservation, inputTokens: 10, messages: [{ role: 'user' as const, content: 'source' }] };
const result = { content: '{"name":"Acme"}', modelExecuted: 'model-v1', finishReason: 'stop', routeDecision: { route: 'local_only', providerKind: 'local' }, cost: { promptTokens: 10, completionTokens: 5, totalTokens: 15 } };
describe('INF0 gateway adapter', () => {
it('admits and scopes a request using the Wave-2 contract without inventing cost', async () => {
const fetchMock = vi.fn(async () => Response.json(result));
const client = new Inf0GatewayClient({ baseUrl: 'https://inf0.example.test', serviceToken: 'test', fetchImpl: fetchMock });
const receipt = await client.complete(input);
expect(receipt).toMatchObject({ status: 'model_stopped', modelExecuted: 'model-v1', totalTokens: 15 });
expect(receipt.costUsd).toBeUndefined();
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
expect(url).toBe('https://inf0.example.test/v1/inf0/gateway/complete');
expect(JSON.parse(String(init.body))).toMatchObject({ route: 'local_only', data_classification: 'high', risk_level: 'L3', max_tokens: 20 });
expect(init.redirect).toBe('error');
});
it('denies an unreserved or cross-tenant job before network access', async () => {
const fetchMock = vi.fn();
const client = new Inf0GatewayClient({ baseUrl: 'https://inf0.example.test', serviceToken: 'test', fetchImpl: fetchMock });
await expect(client.complete({ ...input, reservation: undefined })).rejects.toThrow('reservation_required');
await expect(client.complete({ ...input, context: { ...context, tenantId: 'other' } })).rejects.toThrow('Invalid scoped');
expect(fetchMock).not.toHaveBeenCalled();
});
it('reports incomplete output for truncation or absent usage', async () => {
const fetchMock = vi.fn(async () => Response.json({ ...result, finishReason: 'length', cost: { promptTokens: 0, completionTokens: 0, totalTokens: 0 } }));
const client = new Inf0GatewayClient({ baseUrl: 'https://inf0.example.test', serviceToken: 'test', fetchImpl: fetchMock });
expect((await client.complete(input)).status).toBe('needs_review');
});
it('does not retry unknown results, mismatched destinations or transport failures', async () => {
const fetchMock = vi.fn(async () => Response.json({ ...result, routeDecision: { route: 'local_only', providerKind: 'external' } }));
const client = new Inf0GatewayClient({ baseUrl: 'https://inf0.example.test', serviceToken: 'test', fetchImpl: fetchMock });
await expect(client.complete(input)).rejects.toBeInstanceOf(Inf0OutcomeUnknownError);
expect(fetchMock).toHaveBeenCalledOnce();
const failing = vi.fn(async () => { throw new Error('socket closed'); });
await expect(new Inf0GatewayClient({ baseUrl: 'https://inf0.example.test', serviceToken: 'test', fetchImpl: failing }).complete(input)).rejects.toBeInstanceOf(Inf0OutcomeUnknownError);
expect(failing).toHaveBeenCalledOnce();
});
it('checks the provider and usage against the policy fixed at dispatch time', async () => {
const mutable = structuredClone(input);
const fetchMock = vi.fn(async () => {
mutable.policy.destination = 'external';
mutable.admission.maxOutputTokens = 1000;
return Response.json({ ...result, routeDecision: { route: 'local_only', providerKind: 'external' },
cost: { promptTokens: 10, completionTokens: 100, totalTokens: 110 } });
});
const client = new Inf0GatewayClient({ baseUrl: 'https://inf0.example.test', serviceToken: 'test', fetchImpl: fetchMock });
await expect(client.complete(mutable)).rejects.toBeInstanceOf(Inf0OutcomeUnknownError);
expect(fetchMock).toHaveBeenCalledOnce();
});
});
@@ -0,0 +1,171 @@
import { describe, expect, it } from 'vitest';
import { LiteLlmGatewayClient } from '../../src/document-workbench/litellm-gateway-client';
import { Inf0OutcomeUnknownError } from '../../src/document-workbench/inf0-gateway-client';
import { createInf0Gateway } from '../../src/document-workbench/inf0-gateway';
const context = {
tenantId: 't_0pt',
projectId: 'prj_alpha',
actorId: 'user_1',
capability: '0pt.document.structure.v1',
correlationId: 'corr-1',
};
const admission = {
tenantId: 't_0pt',
projectId: 'prj_alpha',
jobId: 'job-1',
modelId: 'inf0-standard',
dataClass: 'low',
maxInputTokens: 1000,
maxOutputTokens: 200,
maximumCredits: 5,
};
const policy = {
tenantId: 't_0pt',
projectId: 'prj_alpha',
allowedModelIds: ['inf0-standard'],
allowedDataClasses: ['low'],
destination: 'external' as const,
externalTransferAllowed: true,
maxInputTokens: 1000,
maxOutputTokens: 200,
};
const messages = [
{ role: 'system' as const, content: 'system' },
{ role: 'user' as const, content: 'data' },
];
function gateway(fetchImpl: typeof fetch, providerKind: 'local' | 'external' = 'external') {
return new LiteLlmGatewayClient({
baseUrl: 'https://ai-gateway.siax.io/v1',
apiKey: 'sk-test',
providerKind,
fetchImpl,
});
}
function ok(payload: unknown): Response {
return new Response(JSON.stringify(payload), { status: 200 });
}
describe('LiteLLM INF0 adapter', () => {
it('maps an OpenAI-compatible response into the INF0 receipt', async () => {
const client = gateway(async () =>
ok({
model: 'inf0-standard',
choices: [{ message: { content: '{"ok":true}' }, finish_reason: 'stop' }],
usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 },
}),
);
await expect(
client.complete({
context,
admission,
policy,
reservation: {
tenantId: 't_0pt',
projectId: 'prj_alpha',
jobId: 'job-1',
status: 'reserved',
credits: 5,
},
inputTokens: 10,
messages,
}),
).resolves.toMatchObject({
status: 'model_stopped',
content: '{"ok":true}',
modelExecuted: 'inf0-standard',
providerKind: 'external',
totalTokens: 15,
});
});
it('denies a model outside the allow-list before any request', async () => {
let called = false;
const client = gateway(async () => {
called = true;
return ok({});
});
await expect(
client.complete({
context,
admission: { ...admission, modelId: 'inf0-frontier' },
policy,
reservation: undefined,
inputTokens: 10,
messages,
}),
).rejects.toThrow(/denied/i);
expect(called).toBe(false);
});
it('refuses an external provider when the policy requires internal', async () => {
const client = gateway(
async () =>
ok({
model: 'inf0-standard',
choices: [{ message: { content: 'x' }, finish_reason: 'stop' }],
usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
}),
'external',
);
await expect(
client.complete({
context,
admission,
policy: { ...policy, destination: 'internal' },
reservation: {
tenantId: 't_0pt',
projectId: 'prj_alpha',
jobId: 'job-1',
status: 'reserved',
credits: 5,
},
inputTokens: 1,
messages,
}),
).rejects.toBeInstanceOf(Inf0OutcomeUnknownError);
});
it('treats malformed or inconsistent usage as an unknown outcome', async () => {
const client = gateway(async () =>
ok({
model: 'inf0-standard',
choices: [{ message: { content: 'x' }, finish_reason: 'stop' }],
usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 99 },
}),
);
await expect(
client.complete({
context,
admission,
policy,
reservation: {
tenantId: 't_0pt',
projectId: 'prj_alpha',
jobId: 'job-1',
status: 'reserved',
credits: 5,
},
inputTokens: 1,
messages,
}),
).rejects.toBeInstanceOf(Inf0OutcomeUnknownError);
});
it('prefers the live LiteLLM key and falls back to the native surface', () => {
expect(createInf0Gateway({} as unknown as NodeJS.ProcessEnv)).toBeUndefined();
expect(
createInf0Gateway({
INF0_GATEWAY_LITELLM_KEY: 'sk-test',
} as unknown as NodeJS.ProcessEnv),
).toBeInstanceOf(LiteLlmGatewayClient);
expect(
createInf0Gateway({
INF0_URL: 'https://api.inf0.siax.io',
INF0_API_TOKEN: 'token',
} as unknown as NodeJS.ProcessEnv),
).toBeDefined();
});
});
@@ -0,0 +1,33 @@
import { describe, expect, it } from 'vitest';
import { admitModelExecution, type ModelAdmissionRequest, type ModelBudgetReservation, type ModelExecutionPolicy } from '../../src/document-workbench/model-admission';
const request: ModelAdmissionRequest = { tenantId: 'a', projectId: 'p', jobId: 'j', modelId: 'model', dataClass: 'medium', maxInputTokens: 100, maxOutputTokens: 50, maximumCredits: 10 };
const policy: ModelExecutionPolicy = { tenantId: 'a', projectId: 'p', allowedModelIds: ['model'], allowedDataClasses: ['medium'], destination: 'external', externalTransferAllowed: true, maxInputTokens: 100, maxOutputTokens: 50 };
const hold: ModelBudgetReservation = { tenantId: 'a', projectId: 'p', jobId: 'j', status: 'reserved', credits: 10 };
describe('model execution admission', () => {
it('requires a scoped allowed model, data policy and sufficient reservation', () => {
expect(admitModelExecution(request, policy, hold)).toEqual({ allowed: true });
expect(admitModelExecution(request, { ...policy, projectId: 'other' }, hold)).toEqual({ allowed: false, reason: 'scope_mismatch' });
expect(admitModelExecution(request, { ...policy, allowedModelIds: [] }, hold)).toEqual({ allowed: false, reason: 'model_not_allowed' });
expect(admitModelExecution(request, { ...policy, allowedDataClasses: [] }, hold)).toEqual({ allowed: false, reason: 'data_class_not_allowed' });
expect(admitModelExecution(request, { ...policy, externalTransferAllowed: false }, hold)).toEqual({ allowed: false, reason: 'external_transfer_denied' });
expect(admitModelExecution({ ...request, dataClass: 'high' }, { ...policy, allowedDataClasses: ['high'] }, hold)).toEqual({ allowed: false, reason: 'external_transfer_denied' });
expect(admitModelExecution({ ...request, dataClass: 'restricted' }, { ...policy, allowedDataClasses: ['restricted'] }, hold)).toEqual({ allowed: false, reason: 'external_transfer_denied' });
expect(admitModelExecution({ ...request, maxOutputTokens: 51 }, policy, hold)).toEqual({ allowed: false, reason: 'token_limit_exceeded' });
expect(admitModelExecution(request, policy, { ...hold, credits: 9 })).toEqual({ allowed: false, reason: 'reservation_required' });
expect(admitModelExecution(request, policy, { ...hold, status: 'settled' })).toEqual({ allowed: false, reason: 'reservation_required' });
expect(admitModelExecution(request, policy, { ...hold, jobId: 'other' })).toEqual({ allowed: false, reason: 'reservation_required' });
});
it('pilot mode (maximumCredits 0) requires no reservation but still enforces every other rule', () => {
const pilot = { ...request, maximumCredits: 0 };
expect(admitModelExecution(pilot, policy, undefined)).toEqual({ allowed: true });
expect(admitModelExecution(pilot, { ...policy, allowedModelIds: [] }, undefined)).toEqual({ allowed: false, reason: 'model_not_allowed' });
expect(admitModelExecution(pilot, { ...policy, projectId: 'other' }, undefined)).toEqual({ allowed: false, reason: 'scope_mismatch' });
expect(admitModelExecution({ ...pilot, maximumCredits: -1 }, policy, undefined)).toEqual({ allowed: false, reason: 'invalid_request' });
expect(admitModelExecution(request, policy, undefined)).toEqual({ allowed: false, reason: 'reservation_required' });
});
it('rejects invalid limits and never treats an unknown destination as local', () => {
expect(admitModelExecution({ ...request, maxInputTokens: NaN }, policy, hold).allowed).toBe(false);
expect(admitModelExecution(request, { ...policy, destination: 'unknown' as never }, hold).allowed).toBe(false);
});
});
@@ -0,0 +1,101 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { Pay0CreditVerifier } from '../../src/document-workbench/pay0-credit-verification';
const snapshot = {
tenantId: 'tenant-a',
purchaseId: 'purchase-1',
checkoutSessionId: 'session-1',
amountMinor: 1000,
currency: 'SEK',
credits: 50,
};
const context = {
tenantId: 'tenant-a',
actorId: 'svc-0pt',
capability: '0pt.credit.purchase',
correlationId: 'req-1',
};
const checkout = {
id: 'session-1',
tenant_id: 'tenant-a',
payment_intent_id: 'intent-1',
payable_type: '0pt_credit_purchase',
payable_ref: 'purchase-1',
amount_snapshot: 1000,
currency: 'SEK',
status: 'completed',
provider: 'stripe',
provider_reference: 'stripe-session',
};
const intent = {
id: 'intent-1',
tenant_id: 'tenant-a',
payable_type: '0pt_credit_purchase',
payable_ref: 'purchase-1',
amount: 1000,
currency: 'SEK',
canonical_status: 'captured',
captured_amount: 1000,
refunded_amount: 0,
};
function mockPay0(checkoutPatch: Record<string, unknown> = {}, intentPatch: Record<string, unknown> = {}) {
return vi.stubGlobal(
'fetch',
vi.fn(
async (url: string) =>
new Response(
JSON.stringify({
data: url.includes('checkout-sessions')
? { ...checkout, ...checkoutPatch }
: { ...intent, ...intentPatch },
}),
{ status: 200, headers: { 'content-type': 'application/json' } },
),
),
);
}
afterEach(() => vi.unstubAllGlobals());
describe('PAY0 credit verification', () => {
it('derives a deterministic credit command only after both PAY0 reads match', async () => {
mockPay0();
const command = await new Pay0CreditVerifier('https://pay0.test', 'service-token').verify(
snapshot,
context,
);
expect(command).toEqual({
tenantId: 'tenant-a',
idempotencyKey: 'pay0:credit-purchase:purchase-1',
kind: 'verified_payment',
reference: 'pay0:intent:intent-1',
amount: 50,
});
expect(fetch).toHaveBeenCalledTimes(2);
});
it.each([
[{ tenant_id: 'tenant-b' }, {}],
[{ status: 'processing' }, {}],
[{ amount_snapshot: 1 }, {}],
[{ provider_reference: undefined }, {}],
[{}, { canonical_status: 'processing' }],
[{}, { refunded_amount: 1 }],
[{}, { captured_amount: 999 }],
[{}, { payable_ref: 'other' }],
])('rejects mismatched or unconfirmed payment state', async (checkoutPatch, intentPatch) => {
mockPay0(checkoutPatch, intentPatch);
await expect(
new Pay0CreditVerifier('https://pay0.test', 'service-token').verify(snapshot, context),
).rejects.toThrow();
});
it('rejects mismatched tenant before any call', async () => {
mockPay0();
await expect(
new Pay0CreditVerifier('https://pay0.test', 'service-token').verify(snapshot, {
...context,
tenantId: 'other',
}),
).rejects.toThrow();
expect(fetch).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,49 @@
import { describe, expect, it } from 'vitest';
import {
creditsForUsage,
findPack,
parseCreditPriceBook,
readCreditPriceBook,
} from '../../src/document-workbench/price-book';
const valid = {
version: '2026-11-01',
currency: 'SEK',
packs: [
{ id: 'starter', credits: 100, amountMinor: 9900 },
{ id: 'pro', credits: 2000, amountMinor: 129900 },
],
metering: { pagesPerCredit: 5, inputTokensPerCredit: 20000, outputTokensPerCredit: 4000 },
};
describe('credit price book', () => {
it('parses a valid server-owned price book', () => {
const book = parseCreditPriceBook(valid);
expect(book.packs).toHaveLength(2);
expect(findPack(book, 'pro')?.credits).toBe(2000);
});
it('fails closed when the env price book is absent or invalid', () => {
expect(readCreditPriceBook({} as unknown as NodeJS.ProcessEnv)).toBeUndefined();
expect(readCreditPriceBook({ OPT_CREDIT_PRICE_BOOK: '{not json' } as unknown as NodeJS.ProcessEnv)).toBeUndefined();
expect(
readCreditPriceBook({
OPT_CREDIT_PRICE_BOOK: JSON.stringify({ ...valid, currency: 'sek' }),
} as unknown as NodeJS.ProcessEnv),
).toBeUndefined();
});
it('rejects duplicate pack ids, unknown currencies and non-integer money', () => {
expect(() => parseCreditPriceBook({ ...valid, packs: [valid.packs[0], valid.packs[0]] })).toThrow();
expect(() =>
parseCreditPriceBook({ ...valid, packs: [{ id: 'x', credits: 1, amountMinor: 1.5 }] }),
).toThrow();
});
it('rounds every metered component up to its billing block', () => {
const book = parseCreditPriceBook(valid);
expect(creditsForUsage(book, { pages: 0, inputTokens: 0, outputTokens: 0 })).toBe(0);
expect(creditsForUsage(book, { pages: 1, inputTokens: 1, outputTokens: 1 })).toBe(3);
expect(creditsForUsage(book, { pages: 6, inputTokens: 40001, outputTokens: 8001 })).toBe(8);
});
});
@@ -0,0 +1,45 @@
import { describe, expect, it } from 'vitest';
import {
createProjectAuthorizer,
parseProjectGrants,
projectAuthorizationConfigured,
} from '../../src/document-workbench/project-access';
const scope = { tenantId: 't_0pt', projectId: 'prj_alpha', actorId: 'user_1' };
describe('project authorization', () => {
it('fails closed when neither OpenFGA nor explicit grants are configured', async () => {
const env = {} as unknown as NodeJS.ProcessEnv;
expect(projectAuthorizationConfigured(env)).toBe(false);
await expect(createProjectAuthorizer(env)(scope)).resolves.toBe(false);
});
it('honours an exact actor grant and rejects a different actor or project', async () => {
const env = {
OPT_PROJECT_GRANTS: JSON.stringify([{ tenantId: 't_0pt', projectId: 'prj_alpha', actorId: 'user_1' }]),
} as unknown as NodeJS.ProcessEnv;
const authorize = createProjectAuthorizer(env);
await expect(authorize(scope)).resolves.toBe(true);
await expect(authorize({ ...scope, actorId: 'user_2' })).resolves.toBe(false);
await expect(authorize({ ...scope, projectId: 'prj_beta' })).resolves.toBe(false);
await expect(authorize({ ...scope, tenantId: 't_other' })).resolves.toBe(false);
});
it('supports a tenant-wide wildcard actor', async () => {
const env = {
OPT_PROJECT_GRANTS: JSON.stringify([{ tenantId: 't_0pt', projectId: 'prj_alpha', actorId: '*' }]),
} as unknown as NodeJS.ProcessEnv;
await expect(createProjectAuthorizer(env)({ ...scope, actorId: 'anyone' })).resolves.toBe(true);
});
it('treats an invalid grant document as unconfigured', () => {
expect(parseProjectGrants('{not json')).toBeUndefined();
expect(parseProjectGrants(JSON.stringify([]))).toBeUndefined();
expect(parseProjectGrants(JSON.stringify([{ tenantId: 't', projectId: 'p' }]))).toBeUndefined();
expect(
projectAuthorizationConfigured({
OPT_PROJECT_GRANTS: 'not-json',
} as unknown as NodeJS.ProcessEnv),
).toBe(false);
});
});
@@ -0,0 +1,116 @@
import { describe, expect, it } from 'vitest';
import type Stripe from 'stripe';
import {
StripeCreditVerificationError,
verifyStripeCreditPurchase,
type StripeCheckoutReader,
} from '../../src/document-workbench/stripe-credit-verification';
const snapshot = {
tenantId: 't_0pt',
purchaseId: 'purchase-1',
checkoutSessionId: 'cs_test_1',
amountMinor: 9900,
currency: 'SEK',
credits: 100,
};
function stripeReturning(session: unknown): StripeCheckoutReader {
return {
checkout: {
sessions: {
retrieve: async () => session as Stripe.Checkout.Session,
},
},
};
}
function session(overrides: Record<string, unknown> = {}) {
return {
id: 'cs_test_1',
metadata: {
kind: '0pt_credit_purchase',
tenant_id: 't_0pt',
purchase_id: 'purchase-1',
},
amount_total: 9900,
currency: 'sek',
payment_status: 'paid',
payment_intent: {
id: 'pi_123',
status: 'succeeded',
currency: 'sek',
amount_received: 9900,
},
...overrides,
};
}
describe('Stripe credit verification', () => {
it('derives an idempotent verified-payment command from the re-read session', async () => {
const command = await verifyStripeCreditPurchase(stripeReturning(session()), snapshot, {
tenantId: 't_0pt',
});
expect(command).toEqual({
tenantId: 't_0pt',
idempotencyKey: 'credit_purchase:t_0pt:purchase-1',
kind: 'verified_payment',
reference: 'pi_123',
amount: 100,
});
});
it('refuses a session that belongs to another tenant or purchase', async () => {
await expect(
verifyStripeCreditPurchase(
stripeReturning(
session({ metadata: { kind: '0pt_credit_purchase', tenant_id: 't_b', purchase_id: 'purchase-1' } }),
),
snapshot,
{ tenantId: 't_0pt' },
),
).rejects.toBeInstanceOf(StripeCreditVerificationError);
});
it('refuses an amount that differs from the server price snapshot', async () => {
await expect(
verifyStripeCreditPurchase(stripeReturning(session({ amount_total: 100 })), snapshot, {
tenantId: 't_0pt',
}),
).rejects.toMatchObject({ reason: 'mismatch' });
});
it('refuses an unpaid session or a non-succeeded payment intent', async () => {
await expect(
verifyStripeCreditPurchase(stripeReturning(session({ payment_status: 'unpaid' })), snapshot, {
tenantId: 't_0pt',
}),
).rejects.toMatchObject({ reason: 'not_paid' });
await expect(
verifyStripeCreditPurchase(
stripeReturning(
session({
payment_intent: { id: 'pi_123', status: 'processing', currency: 'sek', amount_received: 0 },
}),
),
snapshot,
{ tenantId: 't_0pt' },
),
).rejects.toMatchObject({ reason: 'not_paid' });
});
it('refuses a mismatched caller tenant before any Stripe call', async () => {
const reader = {
checkout: {
sessions: {
retrieve: async () => {
throw new Error('should not be called');
},
},
},
} as unknown as StripeCheckoutReader;
await expect(verifyStripeCreditPurchase(reader, snapshot, { tenantId: 't_b' })).rejects.toMatchObject({
reason: 'mismatch',
});
});
});
@@ -0,0 +1,245 @@
import { describe, expect, it, vi } from 'vitest';
import { structureDocument } from '../../src/document-workbench/structure-document';
import { Inf0GatewayClient, type Inf0GatewayReceipt } from '../../src/document-workbench/inf0-gateway-client';
type Req = Omit<Parameters<Inf0GatewayClient['complete']>[0], 'messages' | 'inputTokens'>;
const request = {
context: { tenantId: 'a', projectId: 'p', actorId: 'u', capability: 'inf0.complete', correlationId: 'c' },
admission: {
tenantId: 'a',
projectId: 'p',
jobId: 'j',
modelId: 'local_only',
dataClass: 'high',
maxInputTokens: 200,
maxOutputTokens: 100,
maximumCredits: 5,
},
policy: {
tenantId: 'a',
projectId: 'p',
allowedModelIds: ['local_only'],
allowedDataClasses: ['high'],
destination: 'internal',
externalTransferAllowed: false,
maxInputTokens: 200,
maxOutputTokens: 100,
},
reservation: { tenantId: 'a', projectId: 'p', jobId: 'j', status: 'reserved', credits: 5 },
} satisfies Req;
const response: Inf0GatewayReceipt = {
status: 'model_stopped',
content: JSON.stringify({
value: { name: 'Acme' },
evidence: [{ field: 'name', sourceId: 'page1', start: 6, end: 10, transform: 'exact' }],
}),
modelExecuted: 'm1',
providerKind: 'local',
promptTokens: 50,
completionTokens: 20,
totalTokens: 70,
};
const base = {
request,
countTokens: vi.fn(async () => 50),
instructions: 'Extract the customer name',
fields: [{ name: 'name', type: 'string' as const, required: true }],
sources: [{ id: 'page1', text: 'Name: Acme' }],
};
describe('structure document workflow', () => {
it('returns only source-supported values and carries model usage without raw prompt', async () => {
const complete = vi.fn(async () => response);
const out = await structureDocument({ ...base, gateway: { complete } });
expect(out).toMatchObject({
status: 'mechanically_validated',
value: { name: 'Acme' },
model: { modelExecuted: 'm1' },
});
expect(out.model).not.toHaveProperty('content');
expect(complete).toHaveBeenCalledOnce();
});
it('sends hallucinated data, invalid JSON and truncated output to review', async () => {
const fake = {
...response,
content: JSON.stringify({
value: { name: 'Other' },
evidence: [{ field: 'name', sourceId: 'page1', start: 6, end: 10, transform: 'exact' }],
}),
};
expect(
(await structureDocument({ ...base, gateway: { complete: vi.fn(async () => fake) } })).status,
).toBe('needs_review');
expect(
(
await structureDocument({
...base,
gateway: { complete: vi.fn(async () => ({ ...response, content: 'not json' })) },
})
).status,
).toBe('needs_review');
expect(
(
await structureDocument({
...base,
gateway: { complete: vi.fn(async () => ({ ...response, status: 'needs_review' as const })) },
})
).status,
).toBe('needs_review');
});
it('runs through the real INF0 adapter and rejects an ungrounded response', async () => {
const fetchMock = vi.fn(async () =>
Response.json({
content: response.content,
modelExecuted: 'm1',
finishReason: 'stop',
routeDecision: { route: 'local_only', providerKind: 'local' },
cost: { promptTokens: 50, completionTokens: 20, totalTokens: 70 },
}),
);
const gateway = new Inf0GatewayClient({
baseUrl: 'https://inf0.example.test',
serviceToken: 'test',
fetchImpl: fetchMock,
});
const out = await structureDocument({ ...base, gateway });
expect(out).toMatchObject({ status: 'mechanically_validated', value: { name: 'Acme' } });
const call = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
const body = JSON.parse(String(call[1].body));
expect(body.messages[1].content).toContain('Name: Acme');
expect(body.data_classification).toBe('high');
});
it('computes evidence deterministically when a local model returns values only', async () => {
const out = await structureDocument({
...base,
gateway: {
complete: vi.fn(async () => ({ ...response, content: JSON.stringify({ value: { name: 'Acme' } }) })),
},
});
expect(out).toMatchObject({ status: 'mechanically_validated', value: { name: 'Acme' } });
if (out.status !== 'mechanically_validated') throw new Error('expected validated');
expect(out.evidence).toEqual([
{ field: 'name', sourceId: 'page1', start: 6, end: 10, transform: 'exact' },
]);
});
it('accepts a flat object or a fenced JSON object from a small local model', async () => {
const flat = await structureDocument({
...base,
gateway: { complete: vi.fn(async () => ({ ...response, content: JSON.stringify({ name: 'Acme' }) })) },
});
expect(flat).toMatchObject({ status: 'mechanically_validated', value: { name: 'Acme' } });
const fenced = await structureDocument({
...base,
gateway: {
complete: vi.fn(async () => ({ ...response, content: '```json\n{"value":{"name":"Acme"}}\n```' })),
},
});
expect(fenced).toMatchObject({ status: 'mechanically_validated', value: { name: 'Acme' } });
});
it('refuses ambiguous or absent values when computing evidence itself', async () => {
const twice = await structureDocument({
...base,
sources: [{ id: 'p1', text: 'Acme AB and Acme AB' }],
gateway: {
complete: vi.fn(async () => ({
...response,
content: JSON.stringify({ value: { name: 'Acme AB' } }),
})),
},
});
expect(twice.status).toBe('needs_review');
const absent = await structureDocument({
...base,
gateway: {
complete: vi.fn(async () => ({
...response,
content: JSON.stringify({ value: { name: 'Globex' } }),
})),
},
});
expect(absent.status).toBe('needs_review');
});
it('derives evidence for decimals and dates from locale-formatted source text', async () => {
const out = await structureDocument({
request,
countTokens: vi.fn(async () => 50),
instructions: 'Extract amount and due date',
fields: [
{ name: 'amount', type: 'decimal' as const, required: true },
{ name: 'due', type: 'date' as const, required: true },
],
sources: [{ id: 'p1', text: 'Belopp: 12 500,00 SEK\nFörfallodatum: 14/10/2026' }],
gateway: {
complete: vi.fn(async () => ({
...response,
content: JSON.stringify({ value: { amount: '12500.00', due: '2026-10-14' } }),
})),
},
});
expect(out.status).toBe('mechanically_validated');
if (out.status !== 'mechanically_validated') throw new Error('expected validated');
expect(out.evidence.map((e) => e.transform)).toEqual(['decimal', 'date']);
expect(out.evidence[0]).toMatchObject({ start: 8, end: 17 });
});
it('rewrites a JSON-number decimal to the exact source string (no rounding)', async () => {
const out = await structureDocument({
request,
countTokens: vi.fn(async () => 50),
instructions: 'Extract the amount',
fields: [{ name: 'amount', type: 'decimal' as const, required: true }],
sources: [{ id: 'p1', text: 'Belopp: 12 500,00 SEK' }],
gateway: {
complete: vi.fn(async () => ({ ...response, content: JSON.stringify({ amount: 12500 }) })),
},
});
expect(out.status).toBe('mechanically_validated');
if (out.status !== 'mechanically_validated') throw new Error('expected validated');
expect(out.value.amount).toBe('12500.00');
});
it('rejects malformed contracts before a model call', async () => {
const complete = vi.fn(async () => response);
await expect(structureDocument({ ...base, fields: [], gateway: { complete } })).rejects.toThrow(
'Invalid structure',
);
expect(complete).not.toHaveBeenCalled();
});
it('validates against the exact source and field contract supplied before async tokenization', async () => {
const sources = [{ id: 'page1', text: 'Name: Evil' }];
const fields = [{ name: 'name', type: 'string' as const, required: true }];
const countTokens = vi.fn(async () => {
sources[0]!.text = 'Name: Acme';
fields[0]!.required = false;
return 50;
});
const complete = vi.fn<Inf0GatewayClient['complete']>(async () => response);
const result = await structureDocument({ ...base, sources, fields, countTokens, gateway: { complete } });
expect(result).toMatchObject({
status: 'needs_review',
issues: [{ field: 'name', code: 'evidence_mismatch' }],
});
expect(complete.mock.calls[0]?.[0]?.messages[1]?.content).toContain('Name: Evil');
});
it('uses the original admission and policy even if the caller mutates its request during tokenization', async () => {
const mutableRequest = structuredClone(request);
const countTokens = vi.fn(async () => {
mutableRequest.admission.modelId = 'changed';
mutableRequest.policy.allowedModelIds.push('changed');
return 50;
});
const complete = vi.fn<Inf0GatewayClient['complete']>(async () => response);
await structureDocument({ ...base, request: mutableRequest, countTokens, gateway: { complete } });
expect(complete.mock.calls[0]?.[0]?.admission.modelId).toBe('local_only');
expect(complete.mock.calls[0]?.[0]?.policy.allowedModelIds).toEqual(['local_only']);
});
it('keeps tokenizer input identical to the message sent to the gateway', async () => {
const countTokens = vi.fn(async (messages: Parameters<Inf0GatewayClient['complete']>[0]['messages']) => {
expect(Object.isFrozen(messages)).toBe(true);
expect(Object.isFrozen(messages[1])).toBe(true);
return 50;
});
const complete = vi.fn<Inf0GatewayClient['complete']>(async () => response);
await structureDocument({ ...base, countTokens, gateway: { complete } });
expect(complete.mock.calls[0]?.[0]?.messages).toEqual(countTokens.mock.calls[0]?.[0]);
});
});
@@ -0,0 +1,91 @@
import { describe, expect, it, vi } from 'vitest';
import { validateStructuredBatch, exportValidatedBatch } from '../../src/document-workbench/structured-batch';
import { structureDocumentBatch } from '../../src/document-workbench/structure-document-batch';
import { Inf0GatewayClient, type Inf0GatewayReceipt } from '../../src/document-workbench/inf0-gateway-client';
const fields = [{ name: 'name', type: 'string' as const, required: true }];
const sources = [{ id: 's1', text: 'Acme\nBeta' }];
const records = [
{ value: { name: 'Acme' }, evidence: [{ field: 'name', sourceId: 's1', start: 0, end: 4, transform: 'exact' as const }] },
{ value: { name: 'Beta' }, evidence: [{ field: 'name', sourceId: 's1', start: 5, end: 9, transform: 'exact' as const }] },
];
const request = {
context: { tenantId: 'a', projectId: 'p', actorId: 'u', capability: 'inf0.complete', correlationId: 'c' },
admission: { tenantId: 'a', projectId: 'p', jobId: 'j', modelId: 'local_only', dataClass: 'high', maxInputTokens: 200, maxOutputTokens: 100, maximumCredits: 5 },
policy: { tenantId: 'a', projectId: 'p', allowedModelIds: ['local_only'], allowedDataClasses: ['high'], destination: 'internal', externalTransferAllowed: false, maxInputTokens: 200, maxOutputTokens: 100 },
reservation: { tenantId: 'a', projectId: 'p', jobId: 'j', status: 'reserved', credits: 5 },
} satisfies Omit<Parameters<Inf0GatewayClient['complete']>[0], 'messages' | 'inputTokens'>;
const receipt: Inf0GatewayReceipt = { status: 'model_stopped', content: JSON.stringify({ records }), modelExecuted: 'm1', providerKind: 'local', promptTokens: 50, completionTokens: 20, totalTokens: 70 };
describe('evidence-bound document batches', () => {
it('serializes every supported row in order to JSON and CSV', () => {
const json = exportValidatedBatch({ format: 'json', fields, sources, records });
expect(json.status).toBe('ready');
if (json.status === 'ready') expect(JSON.parse(json.content)).toEqual([{ name: 'Acme' }, { name: 'Beta' }]);
expect(exportValidatedBatch({ format: 'csv', fields, sources, records })).toEqual({
status: 'ready', mediaType: 'text/csv', content: '"name"\r\n"Acme"\r\n"Beta"\r\n',
});
});
it('rejects the entire output when one row is unsupported or malformed', () => {
const altered = [records[0], { ...records[1]!, value: { name: 'Invented' } }];
expect(exportValidatedBatch({ format: 'json', fields, sources, records: altered })).toMatchObject({ status: 'needs_review', issues: [{ row: 1, field: 'name', code: 'evidence_mismatch' }] });
expect(validateStructuredBatch({ fields, sources, records: [null] })).toMatchObject({ status: 'needs_review', issues: [{ row: 0, code: 'invalid_record' }] });
expect(validateStructuredBatch({ fields, sources, records: [] })).toMatchObject({ status: 'needs_review' });
expect(validateStructuredBatch({ fields, sources, records: Array(201).fill(records[0]) })).toMatchObject({ status: 'needs_review' });
});
it('blocks spreadsheet formulas in any row while JSON preserves the literal value', () => {
const source = [{ id: 's1', text: 'Acme\n=1+1' }];
const unsafe = [records[0]!, { value: { name: '=1+1' }, evidence: [{ field: 'name', sourceId: 's1', start: 5, end: 9, transform: 'exact' }] }];
expect(exportValidatedBatch({ format: 'csv', fields, sources: source, records: unsafe })).toMatchObject({ status: 'needs_review', issues: [{ row: 1, code: 'csv_unsafe_cell' }] });
expect(exportValidatedBatch({ format: 'json', fields, sources: source, records: unsafe }).status).toBe('ready');
});
it('preserves quoted multiline headers and cells in a multi-row CSV', () => {
const f = [{ name: 'company\r\nname', type: 'string' as const, required: true }];
const s = [{ id: 's', text: 'A\r\nB,C' }];
const r = [{ value: { 'company\r\nname': 'A\r\nB' }, evidence: [{ field: 'company\r\nname', sourceId: 's', start: 0, end: 4, transform: 'exact' }] },
{ value: { 'company\r\nname': ',C' }, evidence: [{ field: 'company\r\nname', sourceId: 's', start: 4, end: 6, transform: 'exact' }] }];
expect(exportValidatedBatch({ format: 'csv', fields: f, sources: s, records: r })).toMatchObject({ status: 'ready', content: '"company\r\nname"\r\n"A\r\nB"\r\n",C"\r\n' });
});
it('extracts multiple records and keeps their evidence tied to the original source', async () => {
const mutable = structuredClone(sources);
const complete = vi.fn<Inf0GatewayClient['complete']>(async () => receipt);
const countTokens = vi.fn(async (messages: Parameters<Inf0GatewayClient['complete']>[0]['messages']) => {
expect(Object.isFrozen(messages[1])).toBe(true);
mutable[0]!.text = 'Evil\nBeta';
return 50;
});
const result = await structureDocumentBatch({ request, fields, sources: mutable, instructions: 'Extract companies', countTokens, gateway: { complete } });
expect(result).toMatchObject({ status: 'mechanically_validated', records });
expect(result.model).not.toHaveProperty('content');
expect(complete.mock.calls[0]?.[0]?.messages).toEqual(countTokens.mock.calls[0]?.[0]);
});
it('runs a batch through the real INF0 client with scoped policy and usage checks', async () => {
const fetchImpl = vi.fn(async () => Response.json({ content: receipt.content, modelExecuted: 'm1', finishReason: 'stop',
routeDecision: { route: 'local_only', providerKind: 'local' }, cost: { promptTokens: 50, completionTokens: 20, totalTokens: 70 } }));
const gateway = new Inf0GatewayClient({ baseUrl: 'https://inf0.example.test', serviceToken: 'test', fetchImpl });
const result = await structureDocumentBatch({ request, fields, sources, instructions: 'Extract companies', countTokens: async () => 50, gateway });
expect(result).toMatchObject({ status: 'mechanically_validated', records });
if (result.status !== 'mechanically_validated') throw new Error('Expected a verified batch');
const exported = exportValidatedBatch({ format: 'json', fields, sources, records: result.records });
expect(exported.status).toBe('ready');
if (exported.status === 'ready') expect(JSON.parse(exported.content)).toEqual([{ name: 'Acme' }, { name: 'Beta' }]);
expect(fetchImpl).toHaveBeenCalledOnce();
});
it('requires review for CSV if any optional field is absent in any row', () => {
const optional = [...fields, { name: 'reference', type: 'string' as const, required: false }];
expect(exportValidatedBatch({ format: 'json', fields: optional, sources, records }).status).toBe('ready');
expect(exportValidatedBatch({ format: 'csv', fields: optional, sources, records })).toMatchObject({
status: 'needs_review', issues: [{ row: 0, field: 'reference', code: 'csv_missing_value' }],
});
});
it('routes truncated, empty, malformed and unsupported model results to review', async () => {
for (const r of [
{ ...receipt, status: 'needs_review' as const }, { ...receipt, content: '{' },
{ ...receipt, content: JSON.stringify({ records: [] }) },
{ ...receipt, content: JSON.stringify({ records: [{ ...records[0], value: { name: 'Wrong' } }] }) },
]) {
const result = await structureDocumentBatch({ request, fields, sources, instructions: 'Extract companies', countTokens: async () => 50, gateway: { complete: async () => r } });
expect(result.status).toBe('needs_review');
}
});
});
@@ -0,0 +1,139 @@
import { describe, expect, it } from 'vitest';
import { validateStructuredOutput } from '../../src/document-workbench/structured-output-validation';
const sample = {
fields: [
{ name: 'name', type: 'string' as const, required: true },
{ name: 'count', type: 'integer' as const, required: true },
],
value: { name: 'Acme', count: 12 },
sources: [{ id: 'page-1', text: 'Name: Acme\nCount: 12' }],
evidence: [
{ field: 'name', sourceId: 'page-1', start: 6, end: 10, transform: 'exact' as const },
{ field: 'count', sourceId: 'page-1', start: 18, end: 20, transform: 'integer' as const },
],
};
describe('structured output mechanical validation', () => {
it('accepts typed fields with matching source ranges', () => {
expect(validateStructuredOutput(sample).status).toBe('mechanically_validated');
});
it('does not accept invented, mistyped or extra values', () => {
const result = validateStructuredOutput({ ...sample, value: { name: 'Other', count: '12', extra: 1 } });
expect(result).toMatchObject({
status: 'needs_review',
issues: expect.arrayContaining([
{ field: 'name', code: 'evidence_mismatch' },
{ field: 'count', code: 'invalid_type' },
{ field: 'extra', code: 'unexpected_field' },
]),
});
});
it('rejects absent, duplicate or out-of-range evidence and ambiguous sources', () => {
expect(validateStructuredOutput({ ...sample, evidence: [] }).status).toBe('needs_review');
expect(
validateStructuredOutput({ ...sample, evidence: [...sample.evidence, sample.evidence[0]!] }).status,
).toBe('needs_review');
expect(
validateStructuredOutput({
...sample,
evidence: [{ ...sample.evidence[0]!, end: 999 }, sample.evidence[1]!],
}).status,
).toBe('needs_review');
expect(
validateStructuredOutput({ ...sample, sources: [...sample.sources, sample.sources[0]!] }).status,
).toBe('needs_review');
});
it('refuses unsafe integers and absent required fields', () => {
expect(
validateStructuredOutput({ ...sample, value: { name: 'Acme', count: Number.MAX_SAFE_INTEGER + 1 } })
.status,
).toBe('needs_review');
expect(
validateStructuredOutput({ ...sample, value: { name: 'Acme' }, evidence: [sample.evidence[0]!] })
.status,
).toBe('needs_review');
});
it('preserves exact decimal precision and accepts real ISO calendar dates', () => {
const text = '9007199254740993.20 2024-02-29';
const input = {
fields: [
{ name: 'amount', type: 'decimal' as const, required: true },
{ name: 'date', type: 'date' as const, required: true },
],
value: { amount: '9007199254740993.20', date: '2024-02-29' },
sources: [{ id: 'p', text }],
evidence: [
{ field: 'amount', sourceId: 'p', start: 0, end: 19, transform: 'decimal' as const },
{ field: 'date', sourceId: 'p', start: 20, end: 30, transform: 'date' as const },
],
};
expect(validateStructuredOutput(input).status).toBe('mechanically_validated');
expect(
validateStructuredOutput({ ...input, value: { ...input.value, amount: 9007199254740994 } }).status,
).toBe('needs_review');
expect(
validateStructuredOutput({ ...input, value: { ...input.value, amount: '9007199254740993.2' } }).status,
).toBe('needs_review');
});
it.each(['2023-02-29', '1900-02-29', '2024-13-01', '2024-04-31', '0000-01-01'])(
'rejects invalid date %s even if present in the source',
(text) => {
expect(
validateStructuredOutput({
fields: [{ name: 'date', type: 'date', required: true }],
value: { date: text },
sources: [{ id: 'p', text }],
evidence: [{ field: 'date', sourceId: 'p', start: 0, end: text.length, transform: 'date' }],
}).status,
).toBe('needs_review');
},
);
it.each(['01.0', '1e3', '1,25', '+1.0', '.5'])(
'rejects ambiguous decimal %s rather than guessing',
(text) => {
expect(
validateStructuredOutput({
fields: [{ name: 'amount', type: 'decimal', required: true }],
value: { amount: text },
sources: [{ id: 'p', text }],
evidence: [{ field: 'amount', sourceId: 'p', start: 0, end: text.length, transform: 'decimal' }],
}).status,
).toBe('needs_review');
},
);
});
describe('locale-aware evidence (decimal + date)', () => {
const fields = [
{ name: 'amount', type: 'decimal' as const, required: true },
{ name: 'due', type: 'date' as const, required: true },
];
const sources = [{ id: 's1', text: 'Belopp: 12 500,00 SEK\nFörfallodatum: 14/10/2026' }];
const span = (needle: string) => {
const start = sources[0]!.text.indexOf(needle);
return { start, end: start + needle.length };
};
it('accepts an unambiguous locale amount and day-first date', () => {
const out = validateStructuredOutput({
fields,
sources,
value: { amount: '12500.00', due: '2026-10-14' },
evidence: [
{ field: 'amount', sourceId: 's1', ...span('12 500,00'), transform: 'decimal' },
{ field: 'due', sourceId: 's1', ...span('14/10/2026'), transform: 'date' },
],
});
expect(out.status).toBe('mechanically_validated');
});
it('refuses a date that is ambiguous between day-first and month-first', () => {
const ambiguous = [{ id: 's1', text: 'Datum: 01/02/2026' }];
const start = ambiguous[0]!.text.indexOf('01/02/2026');
const out = validateStructuredOutput({
fields: [{ name: 'due', type: 'date', required: true }],
sources: ambiguous,
value: { due: '2026-02-01' },
evidence: [{ field: 'due', sourceId: 's1', start, end: start + 10, transform: 'date' }],
});
expect(out.status).toBe('needs_review');
});
});
@@ -0,0 +1,66 @@
import { describe, expect, it } from 'vitest';
import { selectDocumentTool, type DocumentTool } from '../../src/document-workbench/tool-selection';
const parser: DocumentTool = {
id: 'pdf-ocr',
version: '1',
installed: true,
licenseApproved: true,
supportedMimeTypes: ['application/pdf'],
supportedDataClasses: ['confidential'],
externalTransfer: false,
};
const policy = {
allowedToolIds: [parser.id],
allowedExternalToolIds: [] as string[],
dataClass: 'confidential',
};
const base = { proposedToolId: parser.id, detectedMimeType: 'application/pdf', registry: [parser], policy };
describe('document tool admission', () => {
it('accepts a licensed, installed and explicitly authorized compatible tool', () => {
expect(selectDocumentTool(base)).toEqual({ allowed: true, tool: parser });
});
it('rejects an agent-invented tool and an ambiguous registry', () => {
expect(selectDocumentTool({ ...base, proposedToolId: 'shell' })).toMatchObject({
reason: 'unknown_tool',
});
expect(selectDocumentTool({ ...base, registry: [parser, parser] })).toMatchObject({
reason: 'ambiguous_registry',
});
});
it('fails closed for missing authorization, license, installation or version', () => {
expect(selectDocumentTool({ ...base, policy: { ...policy, allowedToolIds: [] } })).toMatchObject({
reason: 'not_authorized',
});
for (const tool of [
{ ...parser, installed: false },
{ ...parser, licenseApproved: false },
{ ...parser, version: '' },
{ ...parser, externalTransfer: undefined } as unknown as DocumentTool,
]) {
expect(selectDocumentTool({ ...base, registry: [tool] })).toMatchObject({ reason: 'not_ready' });
}
});
it('rejects incorrect content types and unapproved data classes', () => {
expect(selectDocumentTool({ ...base, detectedMimeType: 'application/zip' })).toMatchObject({
reason: 'unsupported_format',
});
expect(selectDocumentTool({ ...base, policy: { ...policy, dataClass: 'restricted' } })).toMatchObject({
reason: 'unsupported_data_class',
});
});
it('requires an explicit external-transfer permission even for an otherwise allowed tool', () => {
const external = { ...parser, externalTransfer: true };
expect(selectDocumentTool({ ...base, registry: [external] })).toMatchObject({
reason: 'external_transfer_denied',
});
expect(
selectDocumentTool({
...base,
registry: [external],
policy: { ...policy, allowedExternalToolIds: [external.id] },
}).allowed,
).toBe(true);
});
});
@@ -0,0 +1,25 @@
import { describe, expect, it, vi } from 'vitest';
import { ensureTrialCredits, readTrialCredits } from '../../src/document-workbench/trial-credits';
describe('trial credits', () => {
it('is disabled by default and rejects invalid amounts', () => {
expect(readTrialCredits({} as unknown as NodeJS.ProcessEnv)).toBe(0);
expect(readTrialCredits({ OPT_TRIAL_CREDITS: '-5' } as unknown as NodeJS.ProcessEnv)).toBe(0);
expect(readTrialCredits({ OPT_TRIAL_CREDITS: 'abc' } as unknown as NodeJS.ProcessEnv)).toBe(0);
expect(readTrialCredits({ OPT_TRIAL_CREDITS: '100' } as unknown as NodeJS.ProcessEnv)).toBe(100);
});
it('applies one idempotent grant and does nothing for zero', async () => {
const apply = vi.fn(async () => ({ replay: false }));
await ensureTrialCredits({ apply }, 't_0pt', 100);
expect(apply).toHaveBeenCalledWith({
tenantId: 't_0pt',
idempotencyKey: 'trial:t_0pt',
kind: 'grant',
reference: 'trial:t_0pt',
amount: 100,
});
await ensureTrialCredits({ apply }, 't_0pt', 0);
expect(apply).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,75 @@
import { readFile } from 'node:fs/promises';
import postgres from 'postgres';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { DocumentUploadCoordinator } from '../../src/document-workbench/upload-coordinator';
import { PostgresUploadAttemptStore, type UploadAttemptIdentity } from '../../src/document-workbench/upload-attempt-store';
const url = process.env.OPT_ATTEMPT_TEST_DATABASE_URL;
describe.skipIf(!url)('upload attempt manifest with real PostgreSQL RLS', () => {
let admin: ReturnType<typeof postgres>;
let app: ReturnType<typeof postgres>;
let store: PostgresUploadAttemptStore;
let scopedUrl: string;
const sample: UploadAttemptIdentity = {
tenantId: 'tenant-a', projectId: 'project-a', actorId: 'actor-a', attemptId: 'attempt-a',
sourceSha256: 'a'.repeat(64), sourceSizeBytes: 12, requestFingerprint: 'b'.repeat(64),
};
beforeAll(async () => {
if (process.env.OPT_ATTEMPT_TEST_ALLOW_LOCAL !== '1' || new URL(url!).hostname !== '127.0.0.1') {
throw new Error('Only an explicitly enabled isolated loopback test database may be used');
}
admin = postgres(url!, { max: 1, prepare: false });
await admin.unsafe(await readFile('sql/018_document_upload_attempts.sql', 'utf8'));
await admin.unsafe('CREATE ROLE opt_attempt_test LOGIN NOSUPERUSER NOBYPASSRLS');
await admin.unsafe('GRANT USAGE ON SCHEMA public TO opt_attempt_test');
await admin.unsafe('GRANT SELECT, INSERT, UPDATE ON opt_document_upload_attempts TO opt_attempt_test');
const appUrl = new URL(url!);
appUrl.username = 'opt_attempt_test';
scopedUrl = appUrl.toString();
app = postgres(scopedUrl, { max: 8, prepare: false });
store = new PostgresUploadAttemptStore(app);
});
afterAll(async () => { await app?.end(); await admin?.end(); });
it('rejects a database role which bypasses RLS', async () => {
await expect(new PostgresUploadAttemptStore(admin).prepare(sample)).rejects.toThrow(/RLS-enforced/);
});
it('persists matching retries and rejects changed or differently scoped identities', async () => {
expect(await store.prepare(sample)).toEqual({ state: 'prepared', replay: false });
expect(await store.prepare(sample)).toEqual({ state: 'prepared', replay: true });
await expect(store.prepare({ ...sample, sourceSha256: 'c'.repeat(64) })).rejects.toThrow();
await expect(store.prepare({ ...sample, projectId: 'project-b' })).rejects.toThrow('Document upload attempt cannot be reused');
await expect(store.prepare({ ...sample, actorId: 'actor-b' })).rejects.toThrow('Document upload attempt cannot be reused');
expect(await store.prepare({ ...sample, tenantId: 'tenant-b' })).toEqual({ state: 'prepared', replay: false });
expect(await app`SELECT * FROM opt_document_upload_attempts`).toHaveLength(0);
});
it('allows only one concurrent dispatch claimant and survives a new connection', async () => {
const attempt = { ...sample, attemptId: 'race' };
expect(await store.startDispatch(attempt)).toBe(false);
await store.prepare(attempt);
expect(await store.startDispatch({ ...attempt, actorId: 'actor-b' })).toBe(false);
expect(await store.startDispatch({ ...attempt, sourceSha256: 'c'.repeat(64) })).toBe(false);
const results = await Promise.all(Array.from({ length: 8 }, () => store.startDispatch(attempt)));
expect(results.filter(Boolean)).toHaveLength(1);
expect(await store.startDispatch(attempt)).toBe(false);
expect(await store.prepare(attempt)).toEqual({ state: 'dispatch_started', replay: true });
const second = postgres(scopedUrl, { max: 1, prepare: false });
try { expect(await new PostgresUploadAttemptStore(second).prepare(attempt)).toEqual({ state: 'dispatch_started', replay: true }); }
finally { await second.end(); }
});
it('coordinates concurrent uploads through the real RLS store without resending', async () => {
const doc0 = { upload: vi.fn(async () => ({ documentId: 'doc', versionId: 'v', checksumSha256: 'fixture', pipelineStage: 'accepted' })),
inspect: vi.fn(async () => ({ status: 'not_found' as const })) };
const coordinator = new DocumentUploadCoordinator({ attempts: store, doc0, authorize: async () => true, maxBytes: 100 });
const input = { tenantId: 'tenant-a', projectId: 'project-a', actorId: 'actor-a', requestId: 'request', idempotencyKey: 'coordinator-race',
filename: 'fil åäö.txt', mimeType: 'text/plain', classification: 'confidential' as const, bytes: new TextEncoder().encode('fixture') };
const results = await Promise.all(Array.from({ length: 8 }, () => coordinator.execute(input)));
expect(results.filter((result) => result.status === 'receipt_verified')).toHaveLength(1);
expect(results.filter((result) => result.status === 'outcome_unknown')).toHaveLength(7);
expect(doc0.upload).toHaveBeenCalledOnce();
await expect(coordinator.execute({ ...input, bytes: new TextEncoder().encode('different') })).rejects.toThrow(/cannot be reused/);
expect(doc0.upload).toHaveBeenCalledOnce();
});
});
@@ -0,0 +1,143 @@
import { describe, expect, it, vi } from 'vitest';
import {
Doc0UploadOutcomeUnknownError,
prepareDoc0UploadIdentity,
type Doc0UploadClient,
} from '../../src/document-workbench/doc0-upload-client';
import { DocumentUploadCoordinator } from '../../src/document-workbench/upload-coordinator';
import type { PostgresUploadAttemptStore } from '../../src/document-workbench/upload-attempt-store';
const input = {
tenantId: 't1',
projectId: 'p1',
actorId: 'a1',
requestId: 'r1',
idempotencyKey: 'i1',
filename: 'rapport åäö.txt',
mimeType: 'text/plain',
classification: 'confidential' as const,
bytes: new TextEncoder().encode('original'),
};
const receipt = { documentId: 'd1', versionId: 'v1', checksumSha256: 'test', pipelineStage: 'accepted' };
function fixture() {
const attempts = {
prepare: vi.fn<PostgresUploadAttemptStore['prepare']>(async () => ({
state: 'prepared' as const,
replay: false,
})),
startDispatch: vi.fn<PostgresUploadAttemptStore['startDispatch']>(async () => true),
recordReceipt: vi.fn<PostgresUploadAttemptStore['recordReceipt']>(async () => undefined),
getReceipt: vi.fn<PostgresUploadAttemptStore['getReceipt']>(async () => undefined),
};
const doc0 = {
upload: vi.fn<Doc0UploadClient['upload']>(async () => receipt),
inspect: vi.fn<Doc0UploadClient['inspect']>(async () => ({ status: 'not_found' as const })),
};
const authorize = vi.fn(async () => true);
const coordinator = new DocumentUploadCoordinator({ attempts, doc0, authorize, maxBytes: 100 });
return { attempts, doc0, authorize, coordinator };
}
describe('document upload coordination', () => {
it('authorizes and persists the exact fingerprint before a single write', async () => {
const f = fixture();
expect(await f.coordinator.execute(input)).toEqual({ status: 'receipt_verified', receipt });
expect(f.authorize).toHaveBeenCalledWith({ tenantId: 't1', projectId: 'p1', actorId: 'a1' });
const attempt = f.attempts.prepare.mock.calls[0][0];
expect(attempt).toEqual({
tenantId: 't1',
projectId: 'p1',
actorId: 'a1',
attemptId: 'i1',
sourceSha256: prepareDoc0UploadIdentity(input).sourceSha256,
sourceSizeBytes: input.bytes.length,
requestFingerprint: prepareDoc0UploadIdentity(input).requestFingerprint,
});
expect(f.attempts.startDispatch).toHaveBeenCalledWith(attempt);
expect(f.attempts.prepare.mock.invocationCallOrder[0]).toBeLessThan(
f.attempts.startDispatch.mock.invocationCallOrder[0],
);
expect(f.attempts.startDispatch.mock.invocationCallOrder[0]).toBeLessThan(
f.doc0.upload.mock.invocationCallOrder[0],
);
});
it('denies before persistence or network when authorization fails', async () => {
const f = fixture();
f.authorize.mockResolvedValueOnce(false);
await expect(f.coordinator.execute(input)).rejects.toThrow(/not authorized/);
expect(f.attempts.prepare).not.toHaveBeenCalled();
expect(f.doc0.upload).not.toHaveBeenCalled();
});
it('rejects truthy but non-boolean authorization results', async () => {
const f = fixture();
f.authorize.mockResolvedValueOnce('allow' as unknown as boolean);
await expect(f.coordinator.execute(input)).rejects.toThrow(/not authorized/);
expect(f.attempts.prepare).not.toHaveBeenCalled();
});
it('does not dispatch after a failed or ambiguous database transition', async () => {
const f = fixture();
f.attempts.startDispatch.mockRejectedValueOnce(new Error('connection lost'));
await expect(f.coordinator.execute(input)).rejects.toThrow(/connection lost/);
expect(f.doc0.upload).not.toHaveBeenCalled();
expect(f.doc0.inspect).not.toHaveBeenCalled();
});
it('only observes a previously started attempt and never sends a second POST', async () => {
const f = fixture();
f.attempts.startDispatch.mockResolvedValueOnce(false);
expect(await f.coordinator.execute(input)).toEqual({
status: 'outcome_unknown',
observation: { status: 'not_found' },
});
expect(f.doc0.upload).not.toHaveBeenCalled();
expect(f.doc0.inspect).toHaveBeenCalledOnce();
});
it('persists the verified receipt after a successful upload', async () => {
const f = fixture();
expect(await f.coordinator.execute(input)).toEqual({ status: 'receipt_verified', receipt });
expect(f.attempts.recordReceipt).toHaveBeenCalledWith(
expect.objectContaining({ attemptId: 'i1' }),
receipt,
);
});
it('returns the SAME verified receipt on an idempotent retry without a second POST', async () => {
const f = fixture();
f.attempts.startDispatch.mockResolvedValueOnce(false);
f.attempts.getReceipt.mockResolvedValueOnce(receipt);
expect(await f.coordinator.execute(input)).toEqual({ status: 'receipt_verified', receipt });
expect(f.doc0.upload).not.toHaveBeenCalled();
expect(f.doc0.inspect).not.toHaveBeenCalled();
});
it('keeps a journaled completion distinct from a verified receipt', async () => {
const f = fixture();
f.attempts.startDispatch.mockResolvedValueOnce(false);
f.doc0.inspect.mockResolvedValueOnce({
status: 'completed_recorded',
documentId: 'doc',
versionId: 'version',
});
expect(await f.coordinator.execute(input)).toEqual({
status: 'outcome_unknown',
observation: { status: 'completed_recorded', documentId: 'doc', versionId: 'version' },
});
expect(f.doc0.upload).not.toHaveBeenCalled();
});
it('keeps a possibly committed upload unknown even when inspection is unavailable', async () => {
const f = fixture();
f.doc0.upload.mockRejectedValueOnce(new Doc0UploadOutcomeUnknownError());
f.doc0.inspect.mockRejectedValueOnce(new Error('unavailable'));
expect(await f.coordinator.execute(input)).toEqual({ status: 'outcome_unknown' });
expect(f.doc0.upload).toHaveBeenCalledOnce();
expect(f.doc0.inspect).toHaveBeenCalledOnce();
});
it('snapshots bytes and metadata before asynchronous authorization', async () => {
const f = fixture();
const mutable = { ...input, bytes: new Uint8Array(input.bytes) };
f.authorize.mockImplementationOnce(async () => {
mutable.bytes.fill(0);
mutable.filename = 'changed.txt';
return true;
});
await f.coordinator.execute(mutable);
expect(f.doc0.upload.mock.calls[0][0].filename).toBe(input.filename);
expect(new TextDecoder().decode(f.doc0.upload.mock.calls[0][0].bytes)).toBe('original');
});
});