refactor: remove KVARK, enterprise packs and the compliance subsystem (P1.4, P1.6)

KVARK is the commercial enterprise product and is not part of the community
edition. The agent's KVARK tools were never wired into the server, so
removing them changes no runtime behaviour beyond the routes listed here.

- agent: delete kvark-tools; CombinedRetrieval and formatCombinedResult now
  merge workspace and personal memory only (no KVARK lane, no source
  conflict note); connector substrate is always 'waggle'
- agent: promote_skill stops at workspace scope; team and enterprise scopes
  answer "not available in this edition" instead of an upgrade prompt
- server: delete src/kvark and GET /api/marketplace/enterprise-packs
- marketplace: delete ENTERPRISE_PACKS
- compliance (EU AI Act dashboard, its templates and the KVARK template
  seeded on every boot): delete core/src/compliance, the /api/compliance/*
  routes, agent compliance-pdf and the Cockpit compliance panel. The
  ai_interactions table lives in the memory substrate and goes with P1.5.
This commit is contained in:
shumeiko.it
2026-10-20 00:27:02 +02:00
parent 10ad678547
commit b734c1d3d2
53 changed files with 56 additions and 6936 deletions

View File

@@ -1,23 +0,0 @@
export { KvarkClient } from './kvark-client.js';
export { KvarkAuth } from './kvark-auth.js';
export { getKvarkConfig, type VaultLike } from './kvark-config.js';
export type {
KvarkClientConfig,
KvarkLoginRequest,
KvarkLoginResponse,
KvarkUser,
KvarkSearchResult,
KvarkSearchResponse,
KvarkAskRequest,
KvarkAskResponse,
KvarkChatEvent,
KvarkTokenUsage,
KvarkErrorResponse,
} from './kvark-types.js';
export {
KvarkAuthError,
KvarkNotFoundError,
KvarkNotImplementedError,
KvarkServerError,
KvarkUnavailableError,
} from './kvark-types.js';

View File

@@ -1,106 +0,0 @@
/**
* KVARK Auth — login, token caching, auto-refresh on 401.
*
* Manages the JWT lifecycle for KVARK API access:
* - Calls POST /api/auth/login to obtain a Bearer token
* - Caches the token in memory (re-login on server restart is fine)
* - Re-authenticates automatically on 401 responses
*/
import type { KvarkLoginResponse } from './kvark-types.js';
import { KvarkAuthError, KvarkUnavailableError } from './kvark-types.js';
export interface KvarkAuthConfig {
baseUrl: string;
identifier: string;
password: string;
timeoutMs?: number;
}
export class KvarkAuth {
private token: string | null = null;
private tokenObtainedAt: number = 0;
private readonly config: KvarkAuthConfig;
private readonly timeoutMs: number;
/** Injectable fetch for testing */
private readonly fetchFn: typeof globalThis.fetch;
constructor(config: KvarkAuthConfig, fetchFn?: typeof globalThis.fetch) {
this.config = config;
this.timeoutMs = config.timeoutMs ?? 30_000;
this.fetchFn = fetchFn ?? globalThis.fetch;
}
/**
* Get a valid Bearer token. Logs in if no token cached.
* Throws KvarkAuthError on auth failure, KvarkUnavailableError on network error.
*/
async getToken(): Promise<string> {
if (this.token) return this.token;
return this.login();
}
/**
* Force a fresh login (used after 401 responses).
*/
async login(): Promise<string> {
this.token = null;
let res: Response;
try {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
res = await this.fetchFn(`${this.config.baseUrl}/api/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
identifier: this.config.identifier,
password: this.config.password,
}),
signal: controller.signal,
});
clearTimeout(timeout);
} catch (err) {
if (err instanceof DOMException && err.name === 'AbortError') {
throw new KvarkUnavailableError('KVARK login timed out');
}
throw new KvarkUnavailableError(`KVARK unreachable: ${err instanceof Error ? err.message : String(err)}`);
}
if (!res.ok) {
const detail = await res.text().catch(() => 'Unknown error');
throw new KvarkAuthError(`KVARK login failed (${res.status}): ${detail}`);
}
const body = await res.json() as KvarkLoginResponse;
if (!body.success || !body.access_token) {
throw new KvarkAuthError(body.error ?? 'KVARK login returned no token');
}
this.token = body.access_token;
this.tokenObtainedAt = Date.now();
return this.token;
}
/**
* Clear cached token (called when a 401 is received, before retry).
*/
invalidate(): void {
this.token = null;
}
/** Whether a token is currently cached. */
get hasToken(): boolean {
return this.token !== null;
}
/** Milliseconds since token was obtained (0 if no token). */
get tokenAgeMs(): number {
if (!this.token) return 0;
return Date.now() - this.tokenObtainedAt;
}
}

View File

@@ -1,248 +0,0 @@
/**
* KvarkClient — the single boundary between Waggle and KVARK.
*
* All Waggle-side KVARK interaction flows through this client.
* Handles auth, request formatting, response normalization, and errors.
* Uses KvarkAuth for automatic token management.
*
* Design rules:
* - Waggle never calls KVARK endpoints directly — always through KvarkClient
* - Waggle never re-ranks KVARK results
* - Waggle never duplicates KVARK's retrieval logic
* - KVARK remains a black box from KvarkClient's perspective
*/
import { KvarkAuth } from './kvark-auth.js';
import type {
KvarkActionRequest,
KvarkActionResponse,
KvarkAskRequest,
KvarkAskResponse,
KvarkClientConfig,
KvarkFeedbackRequest,
KvarkFeedbackResponse,
KvarkSearchResponse,
KvarkUser,
} from './kvark-types.js';
import {
KvarkAuthError,
KvarkNotFoundError,
KvarkNotImplementedError,
KvarkServerError,
KvarkUnavailableError,
} from './kvark-types.js';
export class KvarkClient {
private readonly auth: KvarkAuth;
private readonly baseUrl: string;
private readonly timeoutMs: number;
private readonly retryOnServerError: boolean;
private readonly fetchFn: typeof globalThis.fetch;
constructor(config: KvarkClientConfig, fetchFn?: typeof globalThis.fetch) {
const fetch = fetchFn ?? globalThis.fetch;
this.auth = new KvarkAuth(
{ baseUrl: config.baseUrl, identifier: config.identifier, password: config.password, timeoutMs: config.timeoutMs },
fetch,
);
this.baseUrl = config.baseUrl.replace(/\/+$/, '');
this.timeoutMs = config.timeoutMs ?? 30_000;
this.retryOnServerError = config.retryOnServerError ?? true;
this.fetchFn = fetch;
}
// ── Public API ─────────────────────────────────────────────────────────
/**
* Search KVARK's document index.
* GET /api/search?q=...&limit=...&offset=...
*/
async search(query: string, opts?: { limit?: number; offset?: number }): Promise<KvarkSearchResponse> {
const params = new URLSearchParams({ q: query });
if (opts?.limit) params.set('limit', String(opts.limit));
if (opts?.offset) params.set('offset', String(opts.offset));
return this.get<KvarkSearchResponse>(`/api/search?${params}`);
}
/**
* Ask a focused question about a specific document.
* POST /api/chat/ask
* Note: This endpoint is currently stubbed (501) on KVARK — Waggle handles gracefully.
*/
async askDocument(documentId: string, question: string): Promise<KvarkAskResponse> {
const body: KvarkAskRequest = { document_id: documentId, question };
return this.post<KvarkAskResponse>('/api/chat/ask', body);
}
/**
* Send retrieval feedback to KVARK's reinforcement system.
* POST /api/feedback
* Fire-and-ack — Waggle should not treat this as a reasoning step.
*/
async feedback(documentId: number, query: string, useful: boolean, reason?: string): Promise<KvarkFeedbackResponse> {
const body: KvarkFeedbackRequest = {
feedbackType: 'search_result',
target: { documentId },
signal: {
rating: useful ? 'positive' : 'negative',
label: useful ? 'useful' : 'not_useful',
comment: reason,
},
context: { query },
};
return this.post<KvarkFeedbackResponse>('/api/feedback', body);
}
/**
* Execute a governed enterprise action via KVARK.
* POST /api/actions
* Requires user approval. KVARK enforces its own governance policy.
*/
async action(
actionType: string,
target: { entityType: string; entityId: string },
payload: Record<string, unknown>,
reason: string,
approvalReference?: string,
workspaceId?: string,
): Promise<KvarkActionResponse> {
const body: KvarkActionRequest = {
actionType,
target,
payload,
governance: { userApproved: true, approvalReference },
context: { workspaceId, reason },
};
return this.post<KvarkActionResponse>('/api/actions', body);
}
/**
* Verify KVARK connectivity and auth.
* GET /api/auth/me — returns current user if token is valid.
*/
async ping(): Promise<KvarkUser> {
return this.get<KvarkUser>('/api/auth/me');
}
// ── Internal HTTP methods ──────────────────────────────────────────────
private async get<T>(path: string): Promise<T> {
return this.request<T>('GET', path);
}
private async post<T>(path: string, body: unknown): Promise<T> {
return this.request<T>('POST', path, body);
}
private async request<T>(method: string, path: string, body?: unknown): Promise<T> {
const MAX_RETRIES = 3;
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
const token = await this.auth.getToken();
const result = await this.doFetch<T>(method, path, token, body);
// On 401, re-auth once and retry
if (result.status === 401) {
this.auth.invalidate();
const freshToken = await this.auth.login();
const retry = await this.doFetch<T>(method, path, freshToken, body);
if (retry.status === 401) {
throw new KvarkAuthError('KVARK authentication failed after re-login');
}
return this.handleResponse<T>(retry);
}
// W5.3: On 429 rate-limit, wait with exponential backoff and retry
if (result.status === 429) {
if (attempt >= MAX_RETRIES) {
throw new KvarkServerError(`KVARK rate limit exceeded after ${MAX_RETRIES} retries`, 429);
}
const retryAfter = parseInt(result.error ?? '', 10) || 0;
const backoffMs = retryAfter > 0 ? retryAfter * 1000 : Math.min(1000 * Math.pow(2, attempt), 30_000);
await new Promise(resolve => setTimeout(resolve, backoffMs));
continue;
}
// W5.3: On transient 5xx (not 501 Not Implemented), retry with exponential backoff
if (result.status >= 500 && result.status !== 501 && this.retryOnServerError && attempt < MAX_RETRIES) {
const backoffMs = Math.min(1000 * Math.pow(2, attempt), 10_000);
await new Promise(resolve => setTimeout(resolve, backoffMs));
continue;
}
return this.handleResponse<T>(result);
}
// Should not reach here, but TypeScript needs it
throw new KvarkServerError('KVARK request failed after max retries', 500);
}
private async doFetch<T>(
method: string,
path: string,
token: string,
body?: unknown,
): Promise<{ status: number; data?: T; error?: string }> {
let res: Response;
try {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
const headers: Record<string, string> = {
'Authorization': `Bearer ${token}`,
'Accept': 'application/json',
};
if (body !== undefined) {
headers['Content-Type'] = 'application/json';
}
res = await this.fetchFn(`${this.baseUrl}${path}`, {
method,
headers,
body: body !== undefined ? JSON.stringify(body) : undefined,
signal: controller.signal,
});
clearTimeout(timeout);
} catch (err) {
if (err instanceof DOMException && err.name === 'AbortError') {
throw new KvarkUnavailableError(`KVARK request timed out: ${method} ${path}`);
}
throw new KvarkUnavailableError(`KVARK unreachable: ${err instanceof Error ? err.message : String(err)}`);
}
if (res.ok) {
const data = await res.json() as T;
return { status: res.status, data };
}
const errorText = await res.text().catch(() => 'Unknown error');
return { status: res.status, error: errorText };
}
private handleResponse<T>(result: { status: number; data?: T; error?: string }): T {
if (result.data !== undefined) return result.data;
const detail = result.error ?? 'Unknown error';
switch (result.status) {
case 401:
throw new KvarkAuthError(detail);
case 403:
// W5.4: Explicit 403 handling — governance/permission denial
throw new KvarkServerError(`KVARK access denied (forbidden): ${detail}`, 403);
case 404:
throw new KvarkNotFoundError(detail);
case 429:
// W5.3: Should be handled in request() retry loop, but catch here as fallback
throw new KvarkServerError(`KVARK rate limited: ${detail}`, 429);
case 501:
throw new KvarkNotImplementedError(detail);
default:
if (result.status >= 500) {
throw new KvarkServerError(detail, result.status);
}
throw new KvarkServerError(`KVARK error (${result.status}): ${detail}`, result.status);
}
}
}

View File

@@ -1,44 +0,0 @@
/**
* KVARK Config — reads KVARK connection details from the Waggle vault.
*
* Credentials stored in vault as 'kvark:connection' with JSON value:
* { "baseUrl": "http://localhost:8000", "identifier": "user@example.com", "password": "..." }
*/
import type { KvarkClientConfig } from './kvark-types.js';
/** Minimal vault interface — matches VaultStore.get() signature */
export interface VaultLike {
get(name: string): { value: string } | null;
}
/**
* Load KVARK client config from vault. Returns null if not configured.
*/
export function getKvarkConfig(vault: VaultLike): KvarkClientConfig | null {
const entry = vault.get('kvark:connection');
if (!entry) return null;
try {
const parsed = JSON.parse(entry.value) as Record<string, unknown>;
const baseUrl = parsed.baseUrl;
const identifier = parsed.identifier;
const password = parsed.password;
if (typeof baseUrl !== 'string' || typeof identifier !== 'string' || typeof password !== 'string') {
return null;
}
if (!baseUrl || !identifier || !password) {
return null;
}
return {
baseUrl,
identifier,
password,
timeoutMs: typeof parsed.timeoutMs === 'number' ? parsed.timeoutMs : undefined,
};
} catch {
return null;
}
}

View File

@@ -1,202 +0,0 @@
/**
* KVARK TypeScript types — verified from GitHub KVARK Pydantic DTOs.
*
* Source: github.com/UkisAI-Egzakta/KVARK backend/src/models/dto/
* These types are the contract between Waggle and KVARK.
* All KVARK interaction flows through KvarkClient using these types.
*/
// ── Auth ─────────────────────────────────────────────────────────────────
export interface KvarkLoginRequest {
identifier: string;
password: string;
}
export interface KvarkUser {
id: number;
identifier: string;
first_name: string | null;
last_name: string | null;
admin: boolean;
developer: boolean;
status: string | null;
created_at: string | null;
}
export interface KvarkLoginResponse {
success: boolean;
access_token: string | null;
token_type: string;
user: KvarkUser | null;
error: string | null;
}
// ── Search ───────────────────────────────────────────────────────────────
export interface KvarkSearchResult {
document_id: number;
title: string;
snippet: string;
score: number;
document_type: string | null;
// Future enrichment (KVARK-side):
// connector?: string;
// source_path?: string;
// page?: number;
// citation_label?: string;
}
export interface KvarkSearchResponse {
results: KvarkSearchResult[];
total: number;
query: string;
}
// ── Document Ask ─────────────────────────────────────────────────────────
export interface KvarkAskRequest {
document_id: string;
question: string;
}
export interface KvarkAskResponse {
answer: string;
sources: string[];
}
// ── Feedback ─────────────────────────────────────────────────────────────
export interface KvarkFeedbackRequest {
feedbackType: 'search_result';
target: {
documentId: number;
};
signal: {
rating: 'positive' | 'negative';
label: 'useful' | 'not_useful';
comment?: string;
};
context: {
query: string;
};
}
export interface KvarkFeedbackResponse {
ok: boolean;
data: {
stored: boolean;
feedbackId?: string;
};
error: string | null;
}
// ── Governed Actions ─────────────────────────────────────────────────────
export interface KvarkActionRequest {
actionType: string;
target: {
entityType: string;
entityId: string;
};
payload: Record<string, unknown>;
governance: {
userApproved: boolean;
approvalReference?: string;
};
context: {
workspaceId?: string;
reason: string;
};
}
export interface KvarkActionResponse {
ok: boolean;
data: {
status: 'executed' | 'denied' | 'queued';
actionId?: string;
auditRef?: string;
result?: Record<string, unknown>;
} | null;
error: {
code: string;
message: string;
details?: Record<string, unknown>;
} | null;
}
// ── Chat SSE Events ──────────────────────────────────────────────────────
export interface KvarkTokenUsage {
input_tokens: number;
output_tokens: number;
latency_ms: number;
}
export type KvarkChatEvent =
| { type: 'status'; msg: string }
| { type: 'token'; chunk: string }
| { type: 'tool_call'; name: string; args: Record<string, unknown> }
| { type: 'tool_result'; name: string; summary: string; duration_ms: number }
| { type: 'thought'; text: string }
| { type: 'done'; session_id: number; answer: string; usage?: KvarkTokenUsage }
| { type: 'error'; msg: string };
// ── Errors ───────────────────────────────────────────────────────────────
/** Standard FastAPI HTTPException shape */
export interface KvarkErrorResponse {
detail: string;
}
// ── Client Config ────────────────────────────────────────────────────────
export interface KvarkClientConfig {
/** KVARK API base URL, e.g. "http://localhost:8000" */
baseUrl: string;
/** Login identifier (username or email) */
identifier: string;
/** Login password */
password: string;
/** Request timeout in ms (default: 30000) */
timeoutMs?: number;
/** Retry once on 5xx errors (default: true) */
retryOnServerError?: boolean;
}
// ── Typed Errors ─────────────────────────────────────────────────────────
export class KvarkAuthError extends Error {
constructor(message: string) {
super(message);
this.name = 'KvarkAuthError';
}
}
export class KvarkNotFoundError extends Error {
constructor(message: string) {
super(message);
this.name = 'KvarkNotFoundError';
}
}
export class KvarkNotImplementedError extends Error {
constructor(message: string) {
super(message);
this.name = 'KvarkNotImplementedError';
}
}
export class KvarkServerError extends Error {
constructor(message: string, public statusCode: number) {
super(message);
this.name = 'KvarkServerError';
}
}
export class KvarkUnavailableError extends Error {
constructor(message: string) {
super(message);
this.name = 'KvarkUnavailableError';
}
}

View File

@@ -10,7 +10,7 @@ import Fastify, { type FastifyInstance, type FastifyRequest } from 'fastify';
import cors from '@fastify/cors';
import fastifyStatic from '@fastify/static';
import websocket from '@fastify/websocket';
import { MindDB, MultiMind, MultiMindCache, WorkspaceManager, WaggleConfig, createEmbeddingProvider, type EmbeddingProviderConfig, type EmbeddingProviderInstance, FrameStore, SessionStore, SuppressionStore, InstallAuditStore, CronStore, AwarenessLayer, VaultStore, SkillHashStore, OptimizationLogStore, ImprovementSignalStore, HarvestSourceStore, ClaudeCodeAdapter, reconcileIndexes, TeamSync, TelemetryStore, TELEMETRY_EVENTS, ExecutionTraceStore, EvolutionRunStore, ComplianceTemplateStore, harvestSetHash, type WorkspaceConfig } from '@waggle/core';
import { MindDB, MultiMind, MultiMindCache, WorkspaceManager, WaggleConfig, createEmbeddingProvider, type EmbeddingProviderConfig, type EmbeddingProviderInstance, FrameStore, SessionStore, SuppressionStore, InstallAuditStore, CronStore, AwarenessLayer, VaultStore, SkillHashStore, OptimizationLogStore, ImprovementSignalStore, HarvestSourceStore, ClaudeCodeAdapter, reconcileIndexes, TeamSync, TelemetryStore, TELEMETRY_EVENTS, ExecutionTraceStore, EvolutionRunStore, harvestSetHash, type WorkspaceConfig } from '@waggle/core';
import { corsOriginAllowed } from './cors-config.js';
import { getBoundTeamServer } from './team-server-binding.js';
import { fetchTeamServer } from './team-server-egress.js';
@@ -172,7 +172,6 @@ import { identityRoutes } from './routes/identity.js';
import { agentRunRoutes } from './routes/agent-run.js';
import { agentRunsRoutes } from './routes/agent-runs.js';
import { localInferenceRoutes } from './routes/local-inference.js';
import { complianceRoutes } from './routes/compliance.js';
import { OfflineManager } from './offline-manager.js';
import { listOllamaChatModelIds } from './model-availability.js';
import { log, createLogger } from './logger.js';
@@ -528,17 +527,6 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
const auditStore = new InstallAuditStore(multiMind.personal);
server.decorate('auditStore', auditStore);
// M-06: seed the built-in KVARK enterprise template on first boot.
// Idempotent — subsequent boots see the row and no-op.
try {
const templateStore = new ComplianceTemplateStore(multiMind.personal);
templateStore.seedKvarkTemplateIfMissing();
} catch (err) {
// Non-fatal: users can create the template manually from the UI if the
// seed fails (disk full, schema drift, etc.).
server.log.warn({ err }, 'Failed to seed KVARK compliance template');
}
// Cron store — SQLite-backed schedule persistence for Solo
const cronStore = new CronStore(multiMind.personal);
server.decorate('cronStore', cronStore);
@@ -2890,7 +2878,6 @@ Return ONLY the improved system prompt text. No commentary, no markdown fences,
await server.register(agentRunRoutes);
await server.register(agentRunsRoutes);
await server.register(localInferenceRoutes);
await server.register(complianceRoutes);
// ── Static file serving for web mode ──────────────────────────
// When WAGGLE_FRONTEND_DIR is set, serve the React frontend as static files.

View File

@@ -1,312 +0,0 @@
/**
* Compliance Routes — AI Act compliance API endpoints.
*
* GET /api/compliance/status — get compliance status
* POST /api/compliance/export — generate audit report
* GET /api/compliance/interactions — list recent interactions
* POST /api/compliance/interactions — record an interaction (internal use)
*/
import type { FastifyInstance } from 'fastify';
import { z } from 'zod';
import {
InteractionStore, ComplianceStatusChecker, ReportGenerator,
HarvestSourceStore, ComplianceTemplateStore,
type RecordInteractionInput, type AuditReportRequest,
type CreateComplianceTemplateInput, type UpdateComplianceTemplateInput,
type AIActRiskLevel,
} from '@waggle/core';
import { renderComplianceReportPdf, type PdfTemplateOverrides } from '@waggle/agent';
/**
* M-03: the `/export` and `/export-pdf` routes accept three optional template-
* sourced overrides on the request body. They do not change section selection
* (which is already merged client-side into `include`) — they only affect how
* the PDF renders org name, footer text, and the risk-classification label.
*/
interface TemplateOverrideFields {
templateOrgName?: string | null;
templateFooterText?: string | null;
templateRiskClassification?: AIActRiskLevel | null;
}
function extractPdfOverrides(body: unknown): PdfTemplateOverrides | undefined {
if (!body || typeof body !== 'object') return undefined;
const b = body as TemplateOverrideFields;
if (b.templateOrgName == null && b.templateFooterText == null && b.templateRiskClassification == null) {
return undefined;
}
return {
orgName: b.templateOrgName ?? null,
footerText: b.templateFooterText ?? null,
riskClassification: b.templateRiskClassification ?? null,
};
}
const sectionsSchema = z.object({
interactions: z.boolean(),
oversight: z.boolean(),
models: z.boolean(),
provenance: z.boolean(),
riskAssessment: z.boolean(),
fria: z.boolean(),
});
const riskSchema = z.enum(['minimal', 'limited', 'high-risk', 'unacceptable']);
const createTemplateSchema = z.object({
name: z.string().min(1),
description: z.string().nullable().optional(),
sections: sectionsSchema,
riskClassification: riskSchema.nullable().optional(),
orgName: z.string().nullable().optional(),
footerText: z.string().nullable().optional(),
});
const updateTemplateSchema = z.object({
name: z.string().min(1).optional(),
description: z.string().nullable().optional(),
sections: sectionsSchema.optional(),
riskClassification: riskSchema.nullable().optional(),
orgName: z.string().nullable().optional(),
footerText: z.string().nullable().optional(),
});
export async function complianceRoutes(fastify: FastifyInstance) {
// GET /api/compliance/status — evaluate current compliance
fastify.get<{ Querystring: { workspaceId?: string } }>('/api/compliance/status', async (_request, reply) => {
const personalDb = fastify.multiMind?.personal;
if (!personalDb) {
return reply.code(503).send({ error: 'Personal mind not available' });
}
const store = new InteractionStore(personalDb);
const checker = new ComplianceStatusChecker(store);
const workspaceId = _request.query?.workspaceId;
return checker.check(workspaceId || undefined);
});
// POST /api/compliance/export — generate audit report
fastify.post('/api/compliance/export', async (request, reply) => {
const personalDb = fastify.multiMind?.personal;
if (!personalDb) {
return reply.code(503).send({ error: 'Personal mind not available' });
}
const body = request.body as AuditReportRequest;
if (!body.from || !body.to) {
return reply.code(400).send({ error: 'from and to dates are required' });
}
const interactionStore = new InteractionStore(personalDb);
const harvestStore = new HarvestSourceStore(personalDb);
const wsManager = fastify.workspaceManager;
const generator = new ReportGenerator({
interactionStore,
harvestStore,
getWorkspaceName: (id) => wsManager?.get(id)?.name ?? id,
getWorkspaceRisk: (id) => wsManager?.get(id)?.riskLevel ?? 'minimal',
getWorkspaceRiskClassifiedAt: (id) => wsManager?.get(id)?.riskClassifiedAt ?? null,
});
const report = generator.generate({
workspaceId: body.workspaceId,
from: body.from,
to: body.to,
format: body.format ?? 'json',
include: body.include ?? {
interactions: true,
oversight: true,
models: true,
provenance: true,
riskAssessment: true,
fria: false,
},
});
return report;
});
// GET /api/compliance/interactions — list recent interactions
fastify.get('/api/compliance/interactions', async (request, reply) => {
const personalDb = fastify.multiMind?.personal;
if (!personalDb) {
return reply.code(503).send({ error: 'Personal mind not available' });
}
const store = new InteractionStore(personalDb);
const { limit, workspaceId } = request.query as { limit?: string; workspaceId?: string };
const parsedLimit = Math.min(Number(limit) || 20, 100);
if (workspaceId) {
return { interactions: store.getByWorkspace(workspaceId) };
}
return { interactions: store.getRecent(parsedLimit) };
});
// POST /api/compliance/interactions — record an AI interaction
fastify.post('/api/compliance/interactions', async (request, reply) => {
const personalDb = fastify.multiMind?.personal;
if (!personalDb) {
return reply.code(503).send({ error: 'Personal mind not available' });
}
const body = request.body as RecordInteractionInput;
if (!body.model || !body.provider) {
return reply.code(400).send({ error: 'model and provider are required' });
}
const store = new InteractionStore(personalDb);
const entry = store.record(body);
return entry;
});
// POST /api/compliance/export-pdf — M-02: renders the same AuditReport
// shape as /export through the compliance-pdf module and returns a PDF
// binary. Body accepts the full AuditReportRequest, identical to /export,
// so the UI can reuse its existing "which sections should we include"
// state. Returns application/pdf with a Content-Disposition hint so
// browsers trigger a Save dialog.
fastify.post('/api/compliance/export-pdf', async (request, reply) => {
const personalDb = fastify.multiMind?.personal;
if (!personalDb) {
return reply.code(503).send({ error: 'Personal mind not available' });
}
const body = request.body as AuditReportRequest;
if (!body.from || !body.to) {
return reply.code(400).send({ error: 'from and to dates are required' });
}
const interactionStore = new InteractionStore(personalDb);
const harvestStore = new HarvestSourceStore(personalDb);
const wsManager = fastify.workspaceManager;
const generator = new ReportGenerator({
interactionStore,
harvestStore,
getWorkspaceName: (id) => wsManager?.get(id)?.name ?? id,
getWorkspaceRisk: (id) => wsManager?.get(id)?.riskLevel ?? 'minimal',
getWorkspaceRiskClassifiedAt: (id) => wsManager?.get(id)?.riskClassifiedAt ?? null,
});
const report = generator.generate({
workspaceId: body.workspaceId,
from: body.from,
to: body.to,
format: body.format ?? 'json',
include: body.include ?? {
interactions: true,
oversight: true,
models: true,
provenance: true,
riskAssessment: true,
fria: false,
},
});
try {
const pdfBuffer = await renderComplianceReportPdf(report, extractPdfOverrides(body));
const filename = `ai-act-compliance-${body.from.slice(0, 10)}-to-${body.to.slice(0, 10)}.pdf`;
return reply
.header('Content-Type', 'application/pdf')
.header('Content-Disposition', `attachment; filename="${filename}"`)
.send(pdfBuffer);
} catch (err) {
return reply.code(500).send({
error: err instanceof Error ? err.message : 'PDF generation failed',
});
}
});
// GET /api/compliance/models — get model inventory
fastify.get('/api/compliance/models', async (request, reply) => {
const personalDb = fastify.multiMind?.personal;
if (!personalDb) {
return reply.code(503).send({ error: 'Personal mind not available' });
}
const store = new InteractionStore(personalDb);
const { from, to, workspaceId } = request.query as { from?: string; to?: string; workspaceId?: string };
return { models: store.getModelInventory(from, to, workspaceId) };
});
// ── M-03: Compliance templates CRUD ──
// Templates are stored on the personal mind (same DB as ai_interactions) so a
// single "My templates" list is visible across all workspaces. Sections merge
// with the runtime /export body's `include` flags (union semantics); the
// merge happens in the UI layer before the POST, not here, so the /export
// and /export-pdf routes stay template-agnostic.
fastify.get('/api/compliance/templates', async (_request, reply) => {
const personalDb = fastify.multiMind?.personal;
if (!personalDb) return reply.code(503).send({ error: 'Personal mind not available' });
const store = new ComplianceTemplateStore(personalDb);
return { templates: store.list() };
});
fastify.get<{ Params: { id: string } }>(
'/api/compliance/templates/:id',
async (request, reply) => {
const personalDb = fastify.multiMind?.personal;
if (!personalDb) return reply.code(503).send({ error: 'Personal mind not available' });
const id = Number(request.params.id);
if (!Number.isFinite(id)) return reply.code(400).send({ error: 'Invalid id' });
const store = new ComplianceTemplateStore(personalDb);
const template = store.getById(id);
if (!template) return reply.code(404).send({ error: 'Template not found' });
return { template };
},
);
fastify.post('/api/compliance/templates', async (request, reply) => {
const personalDb = fastify.multiMind?.personal;
if (!personalDb) return reply.code(503).send({ error: 'Personal mind not available' });
const parsed = createTemplateSchema.safeParse(request.body);
if (!parsed.success) {
return reply.code(400).send({ error: 'Invalid template body', detail: parsed.error.issues });
}
const store = new ComplianceTemplateStore(personalDb);
try {
const template = store.create(parsed.data as CreateComplianceTemplateInput);
return reply.code(201).send({ template });
} catch (err) {
return reply.code(400).send({ error: err instanceof Error ? err.message : 'Create failed' });
}
});
fastify.patch<{ Params: { id: string } }>(
'/api/compliance/templates/:id',
async (request, reply) => {
const personalDb = fastify.multiMind?.personal;
if (!personalDb) return reply.code(503).send({ error: 'Personal mind not available' });
const id = Number(request.params.id);
if (!Number.isFinite(id)) return reply.code(400).send({ error: 'Invalid id' });
const parsed = updateTemplateSchema.safeParse(request.body);
if (!parsed.success) {
return reply.code(400).send({ error: 'Invalid template patch', detail: parsed.error.issues });
}
const store = new ComplianceTemplateStore(personalDb);
try {
const template = store.update(id, parsed.data as UpdateComplianceTemplateInput);
if (!template) return reply.code(404).send({ error: 'Template not found' });
return { template };
} catch (err) {
return reply.code(400).send({ error: err instanceof Error ? err.message : 'Update failed' });
}
},
);
fastify.delete<{ Params: { id: string } }>(
'/api/compliance/templates/:id',
async (request, reply) => {
const personalDb = fastify.multiMind?.personal;
if (!personalDb) return reply.code(503).send({ error: 'Personal mind not available' });
const id = Number(request.params.id);
if (!Number.isFinite(id)) return reply.code(400).send({ error: 'Invalid id' });
const store = new ComplianceTemplateStore(personalDb);
const deleted = store.delete(id);
if (!deleted) return reply.code(404).send({ error: 'Template not found' });
return { deleted: true };
},
);
}

View File

@@ -12,11 +12,10 @@ import type { FastifyInstance, FastifyReply } from 'fastify';
import { existsSync, readFileSync } from 'fs';
import { join } from 'path';
import { homedir } from 'os';
import { MarketplaceDB, MarketplaceInstaller, MarketplaceSync, SecurityGate, ENTERPRISE_PACKS, PACKAGE_CATEGORIES, recategorizeAll, isCiscoScannerAvailable, resolveSkillSource, SkillSourceError, createMarketplaceMcpProvenance } from '@waggle/marketplace';
import { MarketplaceDB, MarketplaceInstaller, MarketplaceSync, SecurityGate, PACKAGE_CATEGORIES, recategorizeAll, isCiscoScannerAvailable, resolveSkillSource, SkillSourceError, createMarketplaceMcpProvenance } from '@waggle/marketplace';
import type { InstallationType, SearchSort, ScanResult, MarketplacePackage, MarketplaceMcpProvenance, MarketplaceApprovalIdentity, FetchFn } from '@waggle/marketplace';
import { validateSkillMd } from '@waggle/sdk';
import { safeFetch, assertUrlAllowed, scanForInjection } from '@waggle/agent';
import { getKvarkConfig } from '../../kvark/kvark-config.js';
import { emitNotification } from './notifications.js';
import { loadMcpConfig, removeMcpServerEntry } from '../mcp-config.js';
import { enqueueHeldAction } from '../held-action-executor.js';
@@ -182,30 +181,6 @@ export async function marketplaceRoutes(fastify: FastifyInstance) {
return result;
});
// ── GET /api/marketplace/enterprise-packs ─────────────────────────────
// Returns enterprise packs that require KVARK. Only populated when
// KVARK credentials are configured in the vault.
fastify.get('/api/marketplace/enterprise-packs', async (request, reply) => {
const vault = fastify.vault;
const kvarkConfigured = vault ? getKvarkConfig(vault) !== null : false;
if (!kvarkConfigured) {
return {
packs: [],
total: 0,
kvarkRequired: true,
hint: 'Enterprise packs require a KVARK connection. Configure KVARK credentials in the vault to unlock.',
};
}
return {
packs: ENTERPRISE_PACKS,
total: ENTERPRISE_PACKS.length,
kvarkRequired: false,
};
});
// ── POST /api/marketplace/install ───────────────────────────────────
// Install a package from the marketplace with SecurityGate pre-scan.
// Severity-based gating:

View File

@@ -319,8 +319,6 @@ const UNSAFE_WORKSPACE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
*/
const VIEWER_READ_ONLY_POST_EXEMPT_PATHS = new Set([
'/api/export',
'/api/compliance/export',
'/api/compliance/export-pdf',
'/api/automations/test',
'/api/command/interpret',
]);

View File

@@ -1,101 +0,0 @@
/**
* KVARK Auth — tests with mocked fetch.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { KvarkAuth } from '../../src/kvark/kvark-auth.js';
import { KvarkAuthError, KvarkUnavailableError } from '../../src/kvark/kvark-types.js';
function mockFetch(responses: Array<{ status: number; body: unknown }>): typeof globalThis.fetch {
let callIndex = 0;
return vi.fn(async () => {
const resp = responses[callIndex++] ?? { status: 500, body: { detail: 'No mock response' } };
return new Response(JSON.stringify(resp.body), {
status: resp.status,
headers: { 'Content-Type': 'application/json' },
});
}) as unknown as typeof globalThis.fetch;
}
const BASE_CONFIG = { baseUrl: 'http://kvark:8000', identifier: 'admin', password: 'secret' };
describe('KvarkAuth', () => {
it('login calls POST /api/auth/login and returns token', async () => {
const fetch = mockFetch([{
status: 200,
body: { success: true, access_token: 'jwt-123', token_type: 'bearer', user: { id: 1, identifier: 'admin' }, error: null },
}]);
const auth = new KvarkAuth(BASE_CONFIG, fetch);
const token = await auth.login();
expect(token).toBe('jwt-123');
expect(auth.hasToken).toBe(true);
expect(fetch).toHaveBeenCalledOnce();
const [url, opts] = (fetch as ReturnType<typeof vi.fn>).mock.calls[0];
expect(url).toBe('http://kvark:8000/api/auth/login');
expect(opts.method).toBe('POST');
expect(JSON.parse(opts.body)).toEqual({ identifier: 'admin', password: 'secret' });
});
it('getToken returns cached token without re-login', async () => {
const fetch = mockFetch([{
status: 200,
body: { success: true, access_token: 'jwt-cached', token_type: 'bearer', user: null, error: null },
}]);
const auth = new KvarkAuth(BASE_CONFIG, fetch);
const t1 = await auth.getToken();
const t2 = await auth.getToken();
expect(t1).toBe('jwt-cached');
expect(t2).toBe('jwt-cached');
expect(fetch).toHaveBeenCalledOnce(); // only one login call
});
it('invalidate clears token, next getToken re-logins', async () => {
const fetch = mockFetch([
{ status: 200, body: { success: true, access_token: 'token-1', token_type: 'bearer', user: null, error: null } },
{ status: 200, body: { success: true, access_token: 'token-2', token_type: 'bearer', user: null, error: null } },
]);
const auth = new KvarkAuth(BASE_CONFIG, fetch);
const t1 = await auth.getToken();
expect(t1).toBe('token-1');
auth.invalidate();
expect(auth.hasToken).toBe(false);
const t2 = await auth.getToken();
expect(t2).toBe('token-2');
expect(fetch).toHaveBeenCalledTimes(2);
});
it('throws KvarkAuthError on login failure', async () => {
const fetch = mockFetch([{
status: 401,
body: { detail: 'Invalid credentials' },
}]);
const auth = new KvarkAuth(BASE_CONFIG, fetch);
await expect(auth.login()).rejects.toThrow(KvarkAuthError);
});
it('throws KvarkAuthError when success=false in response', async () => {
const fetch = mockFetch([{
status: 200,
body: { success: false, access_token: null, token_type: 'bearer', user: null, error: 'Account disabled' },
}]);
const auth = new KvarkAuth(BASE_CONFIG, fetch);
await expect(auth.login()).rejects.toThrow('Account disabled');
});
it('throws KvarkUnavailableError on network failure', async () => {
const fetch = vi.fn(async () => { throw new Error('ECONNREFUSED'); }) as unknown as typeof globalThis.fetch;
const auth = new KvarkAuth(BASE_CONFIG, fetch);
await expect(auth.login()).rejects.toThrow(KvarkUnavailableError);
});
});

View File

@@ -1,279 +0,0 @@
/**
* KvarkClient — tests with mocked fetch.
* Verifies search, askDocument, ping, error handling, and 401 retry.
*/
import { describe, it, expect, vi } from 'vitest';
import { KvarkClient } from '../../src/kvark/kvark-client.js';
import {
KvarkAuthError,
KvarkNotFoundError,
KvarkNotImplementedError,
KvarkServerError,
KvarkUnavailableError,
} from '../../src/kvark/kvark-types.js';
const LOGIN_OK = {
status: 200,
body: { success: true, access_token: 'test-token', token_type: 'bearer', user: { id: 1, identifier: 'test' }, error: null },
};
const SEARCH_OK = {
status: 200,
body: {
results: [
{ document_id: 42, title: 'Project Status', snippet: 'API review postponed...', score: 0.92, document_type: 'pdf' },
{ document_id: 108, title: 'Q1 Budget', snippet: 'Budget allocation...', score: 0.87, document_type: 'spreadsheet' },
],
total: 12,
query: 'project status',
},
};
const ASK_OK = {
status: 200,
body: { answer: 'The blocker is identity boundary design', sources: ['doc_42'] },
};
const PING_OK = {
status: 200,
body: { id: 1, identifier: 'admin', first_name: 'Admin', last_name: 'User', admin: true, developer: false, status: 'Active', created_at: null },
};
type MockResponse = { status: number; body: unknown };
function createMockFetch(responses: MockResponse[]): typeof globalThis.fetch {
let callIndex = 0;
return vi.fn(async (url: string) => {
// Login calls always return the login response
if (url.toString().includes('/api/auth/login')) {
return new Response(JSON.stringify(LOGIN_OK.body), { status: LOGIN_OK.status, headers: { 'Content-Type': 'application/json' } });
}
const resp = responses[callIndex++] ?? { status: 500, body: { detail: 'No mock' } };
return new Response(JSON.stringify(resp.body), { status: resp.status, headers: { 'Content-Type': 'application/json' } });
}) as unknown as typeof globalThis.fetch;
}
const BASE_CONFIG = { baseUrl: 'http://kvark:8000', identifier: 'admin', password: 'secret' };
describe('KvarkClient', () => {
describe('search', () => {
it('calls GET /api/search with query params and returns results', async () => {
const fetch = createMockFetch([SEARCH_OK]);
const client = new KvarkClient(BASE_CONFIG, fetch);
const result = await client.search('project status', { limit: 10 });
expect(result.results).toHaveLength(2);
expect(result.total).toBe(12);
expect(result.query).toBe('project status');
expect(result.results[0].document_id).toBe(42);
expect(result.results[0].title).toBe('Project Status');
// Verify URL
const calls = (fetch as ReturnType<typeof vi.fn>).mock.calls;
const searchCall = calls.find(c => c[0].toString().includes('/api/search'));
expect(searchCall).toBeDefined();
expect(searchCall![0]).toContain('q=project+status');
expect(searchCall![0]).toContain('limit=10');
});
it('passes Authorization Bearer header', async () => {
const fetch = createMockFetch([SEARCH_OK]);
const client = new KvarkClient(BASE_CONFIG, fetch);
await client.search('test');
const calls = (fetch as ReturnType<typeof vi.fn>).mock.calls;
const searchCall = calls.find(c => c[0].toString().includes('/api/search'));
expect(searchCall![1].headers.Authorization).toBe('Bearer test-token');
});
});
describe('askDocument', () => {
it('calls POST /api/chat/ask with document_id and question', async () => {
const fetch = createMockFetch([ASK_OK]);
const client = new KvarkClient(BASE_CONFIG, fetch);
const result = await client.askDocument('42', 'What is the blocker?');
expect(result.answer).toBe('The blocker is identity boundary design');
expect(result.sources).toContain('doc_42');
const calls = (fetch as ReturnType<typeof vi.fn>).mock.calls;
const askCall = calls.find(c => c[0].toString().includes('/api/chat/ask'));
expect(askCall).toBeDefined();
expect(askCall![1].method).toBe('POST');
expect(JSON.parse(askCall![1].body)).toEqual({ document_id: '42', question: 'What is the blocker?' });
});
it('throws KvarkNotImplementedError on 501', async () => {
const fetch = createMockFetch([{ status: 501, body: { detail: 'Not implemented yet' } }]);
const client = new KvarkClient(BASE_CONFIG, fetch);
await expect(client.askDocument('42', 'test')).rejects.toThrow(KvarkNotImplementedError);
});
});
describe('ping', () => {
it('calls GET /api/auth/me and returns user', async () => {
const fetch = createMockFetch([PING_OK]);
const client = new KvarkClient(BASE_CONFIG, fetch);
const user = await client.ping();
expect(user.id).toBe(1);
expect(user.identifier).toBe('admin');
});
});
describe('error handling', () => {
it('throws KvarkNotFoundError on 404', async () => {
const fetch = createMockFetch([{ status: 404, body: { detail: 'Document not found' } }]);
const client = new KvarkClient(BASE_CONFIG, fetch);
await expect(client.search('missing')).rejects.toThrow(KvarkNotFoundError);
});
it('throws KvarkServerError on 500', async () => {
const fetch = createMockFetch([{ status: 500, body: { detail: 'Internal error' } }]);
const client = new KvarkClient(BASE_CONFIG, fetch);
await expect(client.search('broken')).rejects.toThrow(KvarkServerError);
});
it('throws KvarkUnavailableError on network failure', async () => {
let loginDone = false;
const fetch = vi.fn(async (url: string) => {
if (url.toString().includes('/api/auth/login')) {
loginDone = true;
return new Response(JSON.stringify(LOGIN_OK.body), { status: 200, headers: { 'Content-Type': 'application/json' } });
}
throw new Error('ECONNREFUSED');
}) as unknown as typeof globalThis.fetch;
const client = new KvarkClient(BASE_CONFIG, fetch);
await expect(client.search('unreachable')).rejects.toThrow(KvarkUnavailableError);
});
it('retries once on 401 with fresh token', async () => {
let searchAttempt = 0;
const fetch = vi.fn(async (url: string, opts?: RequestInit) => {
if (url.toString().includes('/api/auth/login')) {
return new Response(
JSON.stringify({ success: true, access_token: `token-${searchAttempt}`, token_type: 'bearer', user: null, error: null }),
{ status: 200, headers: { 'Content-Type': 'application/json' } },
);
}
searchAttempt++;
if (searchAttempt === 1) {
// First search attempt → 401
return new Response(JSON.stringify({ detail: 'Token expired' }), { status: 401, headers: { 'Content-Type': 'application/json' } });
}
// Second attempt → success
return new Response(JSON.stringify(SEARCH_OK.body), { status: 200, headers: { 'Content-Type': 'application/json' } });
}) as unknown as typeof globalThis.fetch;
const client = new KvarkClient(BASE_CONFIG, fetch);
const result = await client.search('retry-test');
expect(result.results).toHaveLength(2);
expect(searchAttempt).toBe(2); // first failed, second succeeded
});
});
describe('feedback', () => {
const FEEDBACK_OK = {
status: 200,
body: { ok: true, data: { stored: true, feedbackId: 'fb_001' }, error: null },
};
it('calls POST /api/feedback with correct body', async () => {
const fetch = createMockFetch([FEEDBACK_OK]);
const client = new KvarkClient(BASE_CONFIG, fetch);
const result = await client.feedback(42, 'project status', true, 'Very helpful');
expect(result.ok).toBe(true);
// Verify request
const calls = (fetch as ReturnType<typeof vi.fn>).mock.calls;
const feedbackCall = calls.find(c => c[0].toString().includes('/api/feedback'));
expect(feedbackCall).toBeDefined();
expect(feedbackCall![1].method).toBe('POST');
const body = JSON.parse(feedbackCall![1].body);
expect(body.feedbackType).toBe('search_result');
expect(body.target.documentId).toBe(42);
expect(body.signal.rating).toBe('positive');
expect(body.signal.label).toBe('useful');
expect(body.signal.comment).toBe('Very helpful');
expect(body.context.query).toBe('project status');
});
it('sends negative feedback correctly', async () => {
const fetch = createMockFetch([FEEDBACK_OK]);
const client = new KvarkClient(BASE_CONFIG, fetch);
await client.feedback(108, 'budget', false);
const calls = (fetch as ReturnType<typeof vi.fn>).mock.calls;
const feedbackCall = calls.find(c => c[0].toString().includes('/api/feedback'));
const body = JSON.parse(feedbackCall![1].body);
expect(body.signal.rating).toBe('negative');
expect(body.signal.label).toBe('not_useful');
expect(body.signal.comment).toBeUndefined();
});
it('throws on server error', async () => {
const fetch = createMockFetch([{ status: 500, body: { detail: 'Internal error' } }]);
const client = new KvarkClient(BASE_CONFIG, fetch);
await expect(client.feedback(42, 'test', true)).rejects.toThrow(KvarkServerError);
});
});
describe('action', () => {
const ACTION_OK = {
status: 200,
body: { ok: true, data: { status: 'executed', actionId: 'act_001', auditRef: 'aud_001', result: { entityType: 'jira_comment', entityId: 'comment_987' } }, error: null },
};
it('calls POST /api/actions with correct body shape', async () => {
const fetch = createMockFetch([ACTION_OK]);
const client = new KvarkClient(BASE_CONFIG, fetch);
const result = await client.action(
'jira.create_comment',
{ entityType: 'issue', entityId: 'PROJ-142' },
{ comment: 'Follow-up from Waggle' },
'User requested',
'approval_ref_001',
'ws_proj_x',
);
expect(result.ok).toBe(true);
expect(result.data!.status).toBe('executed');
const calls = (fetch as ReturnType<typeof vi.fn>).mock.calls;
const actionCall = calls.find(c => c[0].toString().includes('/api/actions'));
expect(actionCall).toBeDefined();
expect(actionCall![1].method).toBe('POST');
const body = JSON.parse(actionCall![1].body);
expect(body.actionType).toBe('jira.create_comment');
expect(body.target.entityType).toBe('issue');
expect(body.target.entityId).toBe('PROJ-142');
expect(body.payload.comment).toBe('Follow-up from Waggle');
expect(body.governance.userApproved).toBe(true);
expect(body.governance.approvalReference).toBe('approval_ref_001');
expect(body.context.reason).toBe('User requested');
expect(body.context.workspaceId).toBe('ws_proj_x');
});
it('throws KvarkNotImplementedError on 501', async () => {
const fetch = createMockFetch([{ status: 501, body: { detail: 'Not implemented' } }]);
const client = new KvarkClient(BASE_CONFIG, fetch);
await expect(client.action('test', { entityType: 'x', entityId: '1' }, {}, 'test')).rejects.toThrow(KvarkNotImplementedError);
});
});
});

View File

@@ -1,84 +0,0 @@
/**
* KVARK Config — vault-backed configuration tests.
*/
import { describe, it, expect } from 'vitest';
import { getKvarkConfig, type VaultLike } from '../../src/kvark/kvark-config.js';
function mockVault(entries: Record<string, string>): VaultLike {
return {
get(name: string) {
const value = entries[name];
return value !== undefined ? { value } : null;
},
};
}
describe('getKvarkConfig', () => {
it('returns config from valid vault entry', () => {
const vault = mockVault({
'kvark:connection': JSON.stringify({
baseUrl: 'http://kvark:8000',
identifier: 'admin@test.com',
password: 'secret123',
}),
});
const config = getKvarkConfig(vault);
expect(config).not.toBeNull();
expect(config!.baseUrl).toBe('http://kvark:8000');
expect(config!.identifier).toBe('admin@test.com');
expect(config!.password).toBe('secret123');
});
it('returns null when vault has no kvark entry', () => {
const vault = mockVault({});
expect(getKvarkConfig(vault)).toBeNull();
});
it('returns null when vault entry is invalid JSON', () => {
const vault = mockVault({ 'kvark:connection': 'not-json' });
expect(getKvarkConfig(vault)).toBeNull();
});
it('returns null when required fields are missing', () => {
const vault = mockVault({
'kvark:connection': JSON.stringify({ baseUrl: 'http://kvark:8000' }),
});
expect(getKvarkConfig(vault)).toBeNull();
});
it('returns null when fields are empty strings', () => {
const vault = mockVault({
'kvark:connection': JSON.stringify({ baseUrl: '', identifier: 'admin', password: 'pass' }),
});
expect(getKvarkConfig(vault)).toBeNull();
});
it('includes optional timeoutMs when present', () => {
const vault = mockVault({
'kvark:connection': JSON.stringify({
baseUrl: 'http://kvark:8000',
identifier: 'admin',
password: 'pass',
timeoutMs: 60000,
}),
});
const config = getKvarkConfig(vault);
expect(config!.timeoutMs).toBe(60000);
});
it('omits timeoutMs when not in vault entry', () => {
const vault = mockVault({
'kvark:connection': JSON.stringify({
baseUrl: 'http://kvark:8000',
identifier: 'admin',
password: 'pass',
}),
});
const config = getKvarkConfig(vault);
expect(config!.timeoutMs).toBeUndefined();
});
});

View File

@@ -1,212 +0,0 @@
/**
* KVARK Integration Smoke — end-to-end mocked path.
*
* Validates the full chain: vault config → KvarkClient → auth → tools → output.
* All HTTP is mocked via injected fetch. No live KVARK dependency.
*
* This is the Milestone A gate test. When KVARK is live, these same
* assertions should pass with real HTTP (replace mockFetch with globalThis.fetch).
*/
import { describe, it, expect, vi } from 'vitest';
import { KvarkClient } from '../../src/kvark/kvark-client.js';
import { getKvarkConfig, type VaultLike } from '../../src/kvark/kvark-config.js';
import { createKvarkTools, parseSearchResults } from '@waggle/agent';
import {
KvarkUnavailableError,
KvarkNotImplementedError,
type KvarkClientConfig,
} from '../../src/kvark/kvark-types.js';
// ── Mock KVARK server ────────────────────────────────────────────────────
const MOCK_USER = { id: 1, identifier: 'admin', first_name: 'Admin', last_name: 'User', admin: true, developer: false, status: 'Active', created_at: null };
const MOCK_SEARCH_RESULTS = {
results: [
{ document_id: 42, title: 'Project Status Update', snippet: 'API design review was postponed to next sprint.', score: 0.92, document_type: 'pdf' },
{ document_id: 108, title: 'Q1 Budget Analysis', snippet: 'Engineering budget increased by 15%.', score: 0.87, document_type: 'spreadsheet' },
],
total: 8,
query: 'project',
};
const MOCK_ASK_RESPONSE = {
answer: 'The blocker is the unresolved identity boundary design.',
sources: ['Project Status Update.pdf'],
};
function createMockKvarkServer(): typeof globalThis.fetch {
return vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
const urlStr = url.toString();
// POST /api/auth/login
if (urlStr.includes('/api/auth/login') && init?.method === 'POST') {
return new Response(JSON.stringify({
success: true, access_token: 'mock-jwt-token', token_type: 'bearer', user: MOCK_USER, error: null,
}), { status: 200, headers: { 'Content-Type': 'application/json' } });
}
// GET /api/auth/me
if (urlStr.includes('/api/auth/me')) {
const auth = (init?.headers as Record<string, string>)?.Authorization;
if (auth !== 'Bearer mock-jwt-token') {
return new Response(JSON.stringify({ detail: 'Unauthorized' }), { status: 401, headers: { 'Content-Type': 'application/json' } });
}
return new Response(JSON.stringify(MOCK_USER), { status: 200, headers: { 'Content-Type': 'application/json' } });
}
// GET /api/search
if (urlStr.includes('/api/search')) {
return new Response(JSON.stringify(MOCK_SEARCH_RESULTS), { status: 200, headers: { 'Content-Type': 'application/json' } });
}
// POST /api/chat/ask — simulates 501 (current KVARK reality)
if (urlStr.includes('/api/chat/ask') && init?.method === 'POST') {
return new Response(JSON.stringify({ detail: 'Not implemented yet' }), { status: 501, headers: { 'Content-Type': 'application/json' } });
}
return new Response(JSON.stringify({ detail: 'Not found' }), { status: 404, headers: { 'Content-Type': 'application/json' } });
}) as unknown as typeof globalThis.fetch;
}
function createMockKvarkServerWithAsk(): typeof globalThis.fetch {
const base = createMockKvarkServer();
return vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
const urlStr = url.toString();
if (urlStr.includes('/api/chat/ask') && init?.method === 'POST') {
return new Response(JSON.stringify(MOCK_ASK_RESPONSE), { status: 200, headers: { 'Content-Type': 'application/json' } });
}
return (base as (u: string | URL | Request, i?: RequestInit) => Promise<Response>)(url, init);
}) as unknown as typeof globalThis.fetch;
}
function unreachableServer(): typeof globalThis.fetch {
return vi.fn(async () => { throw new Error('ECONNREFUSED'); }) as unknown as typeof globalThis.fetch;
}
const VAULT_CONFIG = { baseUrl: 'http://kvark:8000', identifier: 'admin', password: 'secret' };
// ── Integration smoke tests ──────────────────────────────────────────────
describe('KVARK Integration Smoke (Milestone A gate)', () => {
describe('Full path: vault → client → auth → search → tool output', () => {
it('vault config → client creation → successful search', async () => {
const vault: VaultLike = {
get: (name: string) => name === 'kvark:connection' ? { value: JSON.stringify(VAULT_CONFIG) } : null,
};
// Step 1: Read config from vault
const config = getKvarkConfig(vault);
expect(config).not.toBeNull();
// Step 2: Create client with mocked HTTP
const client = new KvarkClient(config!, createMockKvarkServer());
// Step 3: Search (triggers auto-login + search)
const results = await client.search('project', { limit: 5 });
expect(results.results).toHaveLength(2);
expect(results.total).toBe(8);
expect(results.results[0].title).toBe('Project Status Update');
});
it('client → tool → formatted agent output', async () => {
const client = new KvarkClient(VAULT_CONFIG, createMockKvarkServer());
const tools = createKvarkTools({ client });
const searchTool = tools.find(t => t.name === 'kvark_search')!;
const output = await searchTool.execute({ query: 'project' });
expect(output).toContain('KVARK Search: "project"');
expect(output).toContain('2 of 8 results');
expect(output).toContain('[pdf] Project Status Update');
expect(output).toContain('score: 0.92');
expect(output).toContain('ID: 42');
});
it('search results parseable for Milestone B structured consumption', async () => {
const client = new KvarkClient(VAULT_CONFIG, createMockKvarkServer());
const response = await client.search('project');
const structured = parseSearchResults(response);
expect(structured).toHaveLength(2);
expect(structured[0].attribution).toBe('[KVARK: pdf: Project Status Update]');
expect(structured[0].documentId).toBe(42);
expect(structured[0].score).toBe(0.92);
expect(structured[1].attribution).toBe('[KVARK: spreadsheet: Q1 Budget Analysis]');
});
});
describe('auth/me (ping) path', () => {
it('ping succeeds with valid token', async () => {
const client = new KvarkClient(VAULT_CONFIG, createMockKvarkServer());
const user = await client.ping();
expect(user.identifier).toBe('admin');
expect(user.admin).toBe(true);
});
});
describe('askDocument path', () => {
it('returns KvarkNotImplementedError when KVARK returns 501', async () => {
const client = new KvarkClient(VAULT_CONFIG, createMockKvarkServer());
await expect(client.askDocument('42', 'What is the blocker?')).rejects.toThrow(KvarkNotImplementedError);
});
it('tool handles 501 gracefully with user-facing message', async () => {
const client = new KvarkClient(VAULT_CONFIG, createMockKvarkServer());
const tools = createKvarkTools({ client });
const askTool = tools.find(t => t.name === 'kvark_ask_document')!;
const output = await askTool.execute({ document_id: '42', question: 'What is the blocker?' });
expect(output).toContain('not yet available');
expect(output).toContain('kvark_search');
});
it('returns real answer when KVARK implements /api/chat/ask', async () => {
const client = new KvarkClient(VAULT_CONFIG, createMockKvarkServerWithAsk());
const tools = createKvarkTools({ client });
const askTool = tools.find(t => t.name === 'kvark_ask_document')!;
const output = await askTool.execute({ document_id: '42', question: 'What is the blocker?' });
expect(output).toContain('KVARK Document Answer (doc #42)');
expect(output).toContain('identity boundary design');
expect(output).toContain('Sources: Project Status Update.pdf');
});
});
describe('Graceful degradation', () => {
it('KVARK unreachable → search tool returns workspace-fallback message', async () => {
const client = new KvarkClient(VAULT_CONFIG, unreachableServer());
const tools = createKvarkTools({ client });
const searchTool = tools.find(t => t.name === 'kvark_search')!;
const output = await searchTool.execute({ query: 'test' });
expect(output).toContain('not reachable');
expect(output).toContain('workspace memory');
});
it('KVARK unreachable → ask tool returns same fallback', async () => {
const client = new KvarkClient(VAULT_CONFIG, unreachableServer());
const tools = createKvarkTools({ client });
const askTool = tools.find(t => t.name === 'kvark_ask_document')!;
const output = await askTool.execute({ document_id: '42', question: 'test' });
expect(output).toContain('not reachable');
});
});
describe('Solo/Team safe: no KVARK config', () => {
it('empty vault → no config → no tools registered', () => {
const vault: VaultLike = { get: () => null };
const config = getKvarkConfig(vault);
expect(config).toBeNull();
// In the real wiring (index.ts), this null means the if(kvarkConfig) block is skipped
// and allTools remains unchanged — Solo/Team behavior preserved
});
});
});

View File

@@ -1,112 +0,0 @@
/**
* KVARK Types — shape validation tests.
* Verifies TypeScript types match GitHub KVARK Pydantic DTOs.
*/
import { describe, it, expect } from 'vitest';
import type {
KvarkLoginRequest,
KvarkLoginResponse,
KvarkUser,
KvarkSearchResult,
KvarkSearchResponse,
KvarkAskRequest,
KvarkAskResponse,
KvarkChatEvent,
KvarkClientConfig,
} from '../../src/kvark/kvark-types.js';
import {
KvarkAuthError,
KvarkNotFoundError,
KvarkNotImplementedError,
KvarkServerError,
KvarkUnavailableError,
} from '../../src/kvark/kvark-types.js';
describe('KVARK Types', () => {
it('LoginRequest has identifier and password', () => {
const req: KvarkLoginRequest = { identifier: 'user@test.com', password: 'secret' };
expect(req.identifier).toBe('user@test.com');
expect(req.password).toBe('secret');
});
it('LoginResponse matches KVARK shape', () => {
const res: KvarkLoginResponse = {
success: true,
access_token: 'jwt-token-here',
token_type: 'bearer',
user: { id: 1, identifier: 'test', first_name: 'Test', last_name: 'User', admin: false, developer: false, status: 'Active', created_at: null },
error: null,
};
expect(res.success).toBe(true);
expect(res.access_token).toBeTruthy();
expect(res.user?.id).toBe(1);
});
it('SearchResult matches KVARK shape', () => {
const result: KvarkSearchResult = {
document_id: 42,
title: 'Project Status',
snippet: 'API review postponed...',
score: 0.92,
document_type: 'pdf',
};
expect(result.document_id).toBe(42);
expect(result.score).toBe(0.92);
expect(result.document_type).toBe('pdf');
});
it('SearchResponse wraps results with total and query', () => {
const res: KvarkSearchResponse = {
results: [{ document_id: 1, title: 'Doc', snippet: 'text', score: 0.8, document_type: null }],
total: 15,
query: 'test query',
};
expect(res.results).toHaveLength(1);
expect(res.total).toBe(15);
expect(res.query).toBe('test query');
});
it('AskRequest and AskResponse match KVARK shape', () => {
const req: KvarkAskRequest = { document_id: '42', question: 'What is the blocker?' };
const res: KvarkAskResponse = { answer: 'The identity boundary design', sources: ['doc_42'] };
expect(req.document_id).toBe('42');
expect(res.answer).toBeTruthy();
expect(res.sources).toHaveLength(1);
});
it('ChatEvent discriminated union covers all types', () => {
const events: KvarkChatEvent[] = [
{ type: 'status', msg: 'Thinking...' },
{ type: 'token', chunk: 'The ' },
{ type: 'tool_call', name: 'search', args: { q: 'test' } },
{ type: 'tool_result', name: 'search', summary: 'Found 3', duration_ms: 120 },
{ type: 'thought', text: 'Analyzing results...' },
{ type: 'done', session_id: 1, answer: 'Here is the answer', usage: { input_tokens: 100, output_tokens: 50, latency_ms: 1200 } },
{ type: 'error', msg: 'Something went wrong' },
];
expect(events).toHaveLength(7);
expect(events[0].type).toBe('status');
expect(events[5].type).toBe('done');
});
it('typed errors have correct names', () => {
expect(new KvarkAuthError('test').name).toBe('KvarkAuthError');
expect(new KvarkNotFoundError('test').name).toBe('KvarkNotFoundError');
expect(new KvarkNotImplementedError('test').name).toBe('KvarkNotImplementedError');
expect(new KvarkServerError('test', 500).name).toBe('KvarkServerError');
expect(new KvarkServerError('test', 500).statusCode).toBe(500);
expect(new KvarkUnavailableError('test').name).toBe('KvarkUnavailableError');
});
it('KvarkClientConfig has required fields', () => {
const config: KvarkClientConfig = {
baseUrl: 'http://localhost:8000',
identifier: 'admin',
password: 'pass',
};
expect(config.baseUrl).toBeTruthy();
expect(config.timeoutMs).toBeUndefined(); // optional
expect(config.retryOnServerError).toBeUndefined(); // optional
});
});

View File

@@ -1,84 +0,0 @@
/**
* KVARK Wiring — tests that KVARK tools register conditionally.
*
* Validates:
* - getKvarkConfig returns null → no KVARK tools
* - getKvarkConfig returns config → createKvarkTools called
* - Solo/Team behavior unaffected when vault has no KVARK entry
*/
import { describe, it, expect } from 'vitest';
import { getKvarkConfig, type VaultLike } from '../../src/kvark/kvark-config.js';
import { createKvarkTools, type KvarkClientLike } from '@waggle/agent';
function emptyVault(): VaultLike {
return { get: () => null };
}
function kvarkVault(): VaultLike {
return {
get: (name: string) => {
if (name === 'kvark:connection') {
return { value: JSON.stringify({ baseUrl: 'http://kvark:8000', identifier: 'admin', password: 'pass' }) };
}
return null;
},
};
}
function stubClient(): KvarkClientLike {
return {
search: async () => ({ results: [], total: 0, query: '' }),
askDocument: async () => ({ answer: '', sources: [] }),
};
}
describe('KVARK Wiring', () => {
it('no KVARK config → getKvarkConfig returns null', () => {
const config = getKvarkConfig(emptyVault());
expect(config).toBeNull();
});
it('with KVARK config → getKvarkConfig returns valid config', () => {
const config = getKvarkConfig(kvarkVault());
expect(config).not.toBeNull();
expect(config!.baseUrl).toBe('http://kvark:8000');
});
it('no KVARK config → zero additional tools', () => {
const config = getKvarkConfig(emptyVault());
// When config is null, no tools created — simulates the if(kvarkConfig) guard
const toolCount = config ? createKvarkTools({ client: stubClient() }).length : 0;
expect(toolCount).toBe(0);
});
it('with KVARK config → exactly 4 tools registered', () => {
const config = getKvarkConfig(kvarkVault());
expect(config).not.toBeNull();
const tools = createKvarkTools({ client: stubClient() });
expect(tools).toHaveLength(4);
expect(tools.map(t => t.name)).toEqual(['kvark_search', 'kvark_feedback', 'kvark_action', 'kvark_ask_document']);
});
it('KVARK tools are ToolDefinition-compatible (name, description, parameters, execute)', () => {
const tools = createKvarkTools({ client: stubClient() });
for (const tool of tools) {
expect(typeof tool.name).toBe('string');
expect(typeof tool.description).toBe('string');
expect(tool.parameters).toBeDefined();
expect(typeof tool.execute).toBe('function');
}
});
it('KVARK tools can be appended to an existing tool array', () => {
const existingTools = [
{ name: 'search_memory', description: 'test', parameters: {}, execute: async () => '' },
{ name: 'save_memory', description: 'test', parameters: {}, execute: async () => '' },
];
const kvarkTools = createKvarkTools({ client: stubClient() });
const allTools = [...existingTools, ...kvarkTools];
expect(allTools).toHaveLength(6);
expect(allTools.map(t => t.name)).toEqual(['search_memory', 'save_memory', 'kvark_search', 'kvark_feedback', 'kvark_action', 'kvark_ask_document']);
});
});

View File

@@ -1,235 +0,0 @@
/**
* Compliance Template Routes Tests (M-03)
*
* Covers the 5-endpoint CRUD surface:
* GET /api/compliance/templates
* GET /api/compliance/templates/:id
* POST /api/compliance/templates
* PATCH /api/compliance/templates/:id
* DELETE /api/compliance/templates/:id
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import type { FastifyInstance } from 'fastify';
import { MindDB, SessionStore, FrameStore } from '@waggle/core';
import { buildLocalServer } from '../../src/local/index.js';
import { injectWithAuth } from '../test-utils.js';
const ALL_ON = {
interactions: true,
oversight: true,
models: true,
provenance: true,
riskAssessment: true,
fria: true,
};
const ALL_OFF = {
interactions: false,
oversight: false,
models: false,
provenance: false,
riskAssessment: false,
fria: false,
};
describe('Compliance Template Routes (M-03)', () => {
let server: FastifyInstance;
let tmpDir: string;
beforeAll(async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-compliance-templates-test-'));
const mind = new MindDB(path.join(tmpDir, 'personal.mind'));
const sessions = new SessionStore(mind);
const frames = new FrameStore(mind);
const s = sessions.create('template-test-seed');
frames.createIFrame(s.gop_id, 'seed', 'normal');
mind.close();
server = await buildLocalServer({ dataDir: tmpDir });
});
afterAll(async () => {
await server.close();
fs.rmSync(tmpDir, { recursive: true, force: true });
});
describe('POST /api/compliance/templates', () => {
it('creates a template with 201 + returns the full row', async () => {
const res = await injectWithAuth(server, {
method: 'POST',
url: '/api/compliance/templates',
payload: {
name: 'Test template',
description: 'unit test',
sections: ALL_ON,
riskClassification: 'high-risk',
orgName: 'Acme',
footerText: 'Confidential',
},
});
expect(res.statusCode).toBe(201);
const body = res.json();
expect(body.template.id).toBeGreaterThan(0);
expect(body.template.name).toBe('Test template');
expect(body.template.sections).toEqual(ALL_ON);
expect(body.template.riskClassification).toBe('high-risk');
});
it('400s on missing name', async () => {
const res = await injectWithAuth(server, {
method: 'POST',
url: '/api/compliance/templates',
payload: { sections: ALL_OFF },
});
expect(res.statusCode).toBe(400);
});
it('400s on missing sections', async () => {
const res = await injectWithAuth(server, {
method: 'POST',
url: '/api/compliance/templates',
payload: { name: 'no sections' },
});
expect(res.statusCode).toBe(400);
});
it('400s on invalid risk classification', async () => {
const res = await injectWithAuth(server, {
method: 'POST',
url: '/api/compliance/templates',
payload: { name: 'bad risk', sections: ALL_OFF, riskClassification: 'catastrophic' },
});
expect(res.statusCode).toBe(400);
});
});
describe('GET /api/compliance/templates', () => {
it('returns the list of all templates', async () => {
const res = await injectWithAuth(server, {
method: 'GET',
url: '/api/compliance/templates',
});
expect(res.statusCode).toBe(200);
const body = res.json();
expect(Array.isArray(body.templates)).toBe(true);
expect(body.templates.length).toBeGreaterThan(0);
});
});
describe('GET /api/compliance/templates/:id', () => {
it('returns a specific template', async () => {
const create = await injectWithAuth(server, {
method: 'POST',
url: '/api/compliance/templates',
payload: { name: 'fetch-me', sections: ALL_OFF },
});
const id = create.json().template.id;
const res = await injectWithAuth(server, {
method: 'GET',
url: `/api/compliance/templates/${id}`,
});
expect(res.statusCode).toBe(200);
expect(res.json().template.id).toBe(id);
});
it('404s on missing id', async () => {
const res = await injectWithAuth(server, {
method: 'GET',
url: '/api/compliance/templates/999999',
});
expect(res.statusCode).toBe(404);
});
it('400s on non-numeric id', async () => {
const res = await injectWithAuth(server, {
method: 'GET',
url: '/api/compliance/templates/not-a-number',
});
expect(res.statusCode).toBe(400);
});
});
describe('PATCH /api/compliance/templates/:id', () => {
it('updates partial fields and returns the new row', async () => {
const create = await injectWithAuth(server, {
method: 'POST',
url: '/api/compliance/templates',
payload: { name: 'orig', description: 'old', sections: ALL_OFF, orgName: 'X' },
});
const id = create.json().template.id;
const patch = await injectWithAuth(server, {
method: 'PATCH',
url: `/api/compliance/templates/${id}`,
payload: { name: 'renamed', orgName: null },
});
expect(patch.statusCode).toBe(200);
const body = patch.json();
expect(body.template.name).toBe('renamed');
expect(body.template.description).toBe('old'); // preserved
expect(body.template.orgName).toBeNull(); // cleared
});
it('404s on missing id', async () => {
const res = await injectWithAuth(server, {
method: 'PATCH',
url: '/api/compliance/templates/999999',
payload: { name: 'x' },
});
expect(res.statusCode).toBe(404);
});
it('400s on invalid body shape', async () => {
const create = await injectWithAuth(server, {
method: 'POST',
url: '/api/compliance/templates',
payload: { name: 'for-bad-patch', sections: ALL_OFF },
});
const id = create.json().template.id;
const res = await injectWithAuth(server, {
method: 'PATCH',
url: `/api/compliance/templates/${id}`,
payload: { sections: { interactions: true } }, // missing other 5 flags
});
expect(res.statusCode).toBe(400);
});
});
describe('DELETE /api/compliance/templates/:id', () => {
it('deletes an existing template + returns { deleted: true }', async () => {
const create = await injectWithAuth(server, {
method: 'POST',
url: '/api/compliance/templates',
payload: { name: 'doomed', sections: ALL_OFF },
});
const id = create.json().template.id;
const del = await injectWithAuth(server, {
method: 'DELETE',
url: `/api/compliance/templates/${id}`,
});
expect(del.statusCode).toBe(200);
expect(del.json().deleted).toBe(true);
const refetch = await injectWithAuth(server, {
method: 'GET',
url: `/api/compliance/templates/${id}`,
});
expect(refetch.statusCode).toBe(404);
});
it('404s on missing id', async () => {
const res = await injectWithAuth(server, {
method: 'DELETE',
url: '/api/compliance/templates/999999',
});
expect(res.statusCode).toBe(404);
});
});
});

View File

@@ -856,8 +856,6 @@ describe('Team viewer read-only enforcement', () => {
server.patch('/api/artifacts/:id', mutate);
server.delete('/api/artifacts/:id', mutate);
server.post('/api/export', async () => ({ ok: true, readOnly: true }));
server.post('/api/compliance/export', async () => ({ ok: true, readOnly: true }));
server.post('/api/compliance/export-pdf', async () => ({ ok: true, readOnly: true }));
server.post('/api/automations/test', async () => ({ ok: true, readOnly: true }));
server.post('/api/command/interpret', async () => ({ ok: true, readOnly: true }));
server.get('/api/workspaces/:workspaceId/files', async () => ({ ok: true, readOnly: true }));
@@ -1312,8 +1310,6 @@ describe('Team viewer read-only enforcement', () => {
it.each([
'/api/export',
'/api/compliance/export',
'/api/compliance/export-pdf',
'/api/automations/test',
'/api/command/interpret',
])('allows a viewer to use the read-only POST projection %s', async (url) => {