feat: add guarded document workbench foundations
CI (SIAX Cloud) / integration (push) Skipped
CI (SIAX Cloud) / sonar (push) Skipped
masterplan-lock / check (push) Successful in 5s
Security Scan (SIAX Cloud) / security (push) Successful in 15s
CI (SIAX Cloud) / security (push) Successful in 16s
CI (SIAX Cloud) / sonar (pull_request) Skipped
masterplan-lock / check (pull_request) Successful in 7s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 21s
CI (SIAX Cloud) / security (pull_request) Successful in 25s
CI (SIAX Cloud) / quality (push) Successful in 1m17s
CI (SIAX Cloud) / integration (pull_request) Successful in 54s
CI (SIAX Cloud) / quality (pull_request) Successful in 1m7s
CI (SIAX Cloud) / integration (push) Skipped
CI (SIAX Cloud) / sonar (push) Skipped
masterplan-lock / check (push) Successful in 5s
Security Scan (SIAX Cloud) / security (push) Successful in 15s
CI (SIAX Cloud) / security (push) Successful in 16s
CI (SIAX Cloud) / sonar (pull_request) Skipped
masterplan-lock / check (pull_request) Successful in 7s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 21s
CI (SIAX Cloud) / security (pull_request) Successful in 25s
CI (SIAX Cloud) / quality (push) Successful in 1m17s
CI (SIAX Cloud) / integration (pull_request) Successful in 54s
CI (SIAX Cloud) / quality (pull_request) Successful in 1m7s
This commit is contained in:
@@ -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,226 @@
|
||||
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()}`;
|
||||
let sql: ReturnType<typeof postgres>;
|
||||
let ledger: PostgresCreditLedger;
|
||||
|
||||
describe.skipIf(!url)('credit ledger against isolated PostgreSQL schema', () => {
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
beforeAll(async () => {
|
||||
const admin = postgres(url!, { max: 1 });
|
||||
try {
|
||||
await admin.unsafe(`CREATE SCHEMA ${schema}`);
|
||||
} finally {
|
||||
await admin.end({ timeout: 2 });
|
||||
}
|
||||
sql = postgres(url!, { max: 8, prepare: false, connection: { search_path: schema } });
|
||||
await sql.unsafe(await fs.readFile('sql/017_document_credits.sql', 'utf8'));
|
||||
ledger = new PostgresCreditLedger(sql);
|
||||
});
|
||||
afterAll(async () => {
|
||||
if (sql) await sql.end();
|
||||
const admin = postgres(url!, { max: 1 });
|
||||
try {
|
||||
await admin.unsafe(`DROP SCHEMA IF EXISTS ${schema} CASCADE`);
|
||||
} finally {
|
||||
await admin.end({ timeout: 2 });
|
||||
}
|
||||
});
|
||||
|
||||
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<
|
||||
{ reservation_id: string }[]
|
||||
>`SELECT reservation_id FROM opt_credit_reservations WHERE tenant_id = 'a'`;
|
||||
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(url!, { 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/);
|
||||
});
|
||||
});
|
||||
@@ -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,76 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { Doc0UploadClient } 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('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');
|
||||
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([
|
||||
{ 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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
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('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,48 @@
|
||||
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('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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
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');
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user