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:
@@ -1,27 +1,20 @@
|
||||
/**
|
||||
* Combined Retrieval — merges workspace memory, personal memory, and KVARK enterprise search.
|
||||
* Combined Retrieval — merges workspace memory and personal memory.
|
||||
*
|
||||
* This is the core merge engine for Milestone B. It does NOT format output for
|
||||
* the agent (that's search_memory's job in B2). It returns structured data with
|
||||
* source attribution so the consumer can format however it needs.
|
||||
* It does NOT format output for the agent (that's search_memory's job). It
|
||||
* returns structured data with source attribution so the consumer can format
|
||||
* however it needs.
|
||||
*
|
||||
* Design:
|
||||
* - Pure data in, pure data out — no side effects, no framework deps
|
||||
* - KVARK is only called when local results are insufficient
|
||||
* - Every result carries explicit source attribution
|
||||
* - KVARK failures degrade gracefully (local results preserved, error captured)
|
||||
*/
|
||||
|
||||
import {
|
||||
parseSearchResults,
|
||||
type KvarkClientLike,
|
||||
type KvarkStructuredResult,
|
||||
} from './kvark-tools.js';
|
||||
import { logTurnEvent } from './turn-context.js';
|
||||
|
||||
// ── Public types ──────────────────────────────────────────────────────────
|
||||
|
||||
export type ResultSource = 'workspace' | 'personal' | 'kvark';
|
||||
export type ResultSource = 'workspace' | 'personal';
|
||||
|
||||
export interface CombinedResult {
|
||||
content: string;
|
||||
@@ -29,13 +22,9 @@ export interface CombinedResult {
|
||||
attribution: string;
|
||||
score: number;
|
||||
metadata: {
|
||||
// Memory-sourced
|
||||
frameId?: number;
|
||||
frameType?: string;
|
||||
importance?: string;
|
||||
// KVARK-sourced
|
||||
documentId?: number;
|
||||
documentType?: string | null;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -43,14 +32,6 @@ export interface CombinedRetrievalResult {
|
||||
query: string;
|
||||
workspaceResults: CombinedResult[];
|
||||
personalResults: CombinedResult[];
|
||||
kvarkResults: CombinedResult[];
|
||||
kvarkAvailable: boolean;
|
||||
kvarkSkipped: boolean;
|
||||
kvarkError?: string;
|
||||
/** True when workspace memory and KVARK results may disagree on the same topic */
|
||||
hasConflict: boolean;
|
||||
/** Human-readable note explaining detected conflict (undefined when no conflict) */
|
||||
conflictNote?: string;
|
||||
}
|
||||
|
||||
export interface CombinedSearchOptions {
|
||||
@@ -83,71 +64,6 @@ export interface MemorySearchResultLike {
|
||||
export interface CombinedRetrievalDeps {
|
||||
workspaceSearch: MemorySearchLike | null;
|
||||
personalSearch: MemorySearchLike;
|
||||
kvarkClient: KvarkClientLike | null;
|
||||
}
|
||||
|
||||
// ── Constants ─────────────────────────────────────────────────────────────
|
||||
|
||||
/** Minimum local results with strong scores before we skip KVARK */
|
||||
const LOCAL_COVERAGE_MIN_COUNT = 3;
|
||||
/** Score threshold to consider a local result "strong" */
|
||||
const LOCAL_COVERAGE_SCORE_THRESHOLD = 0.7;
|
||||
/** Minimum score for a result to participate in conflict detection */
|
||||
const CONFLICT_SCORE_THRESHOLD = 0.6;
|
||||
|
||||
// ── Conflict detection ───────────────────────────────────────────────────
|
||||
|
||||
/** Status/decision keywords grouped by polarity */
|
||||
const POSITIVE_STATUS = ['approved', 'accepted', 'selected', 'chose', 'chosen', 'decided', 'confirmed', 'active', 'completed', 'launched', 'enabled'];
|
||||
const NEGATIVE_STATUS = ['rejected', 'cancelled', 'canceled', 'postponed', 'deprecated', 'deferred', 'suspended', 'disabled', 'abandoned', 'declined', 'revoked'];
|
||||
|
||||
/**
|
||||
* Detect potential conflict between workspace memory and KVARK results.
|
||||
*
|
||||
* Conservative heuristic — only flags when:
|
||||
* 1. Both sources have relevant results (score ≥ threshold)
|
||||
* 2. Top results contain contradictory status/decision language
|
||||
*
|
||||
* Returns null when no conflict detected, or a short explanatory note.
|
||||
*/
|
||||
export function detectConflict(
|
||||
workspaceResults: CombinedResult[],
|
||||
kvarkResults: CombinedResult[],
|
||||
): string | null {
|
||||
// Need strong results from both sources
|
||||
const strongWs = workspaceResults.filter(r => r.score >= CONFLICT_SCORE_THRESHOLD);
|
||||
const strongKvark = kvarkResults.filter(r => r.score >= CONFLICT_SCORE_THRESHOLD);
|
||||
if (strongWs.length === 0 || strongKvark.length === 0) return null;
|
||||
|
||||
// Check top results (up to 3 from each) for status polarity conflict
|
||||
const wsTexts = strongWs.slice(0, 3).map(r => r.content.toLowerCase());
|
||||
const kvarkTexts = strongKvark.slice(0, 3).map(r => r.content.toLowerCase());
|
||||
|
||||
const wsPolarity = extractPolarity(wsTexts);
|
||||
const kvarkPolarity = extractPolarity(kvarkTexts);
|
||||
|
||||
// Conflict: one source is positive, the other is negative
|
||||
if (wsPolarity === 'positive' && kvarkPolarity === 'negative') {
|
||||
return 'Workspace memory contains affirmative language (approved/selected/active) while enterprise documents contain contradictory language (rejected/cancelled/deprecated). These sources may be out of sync.';
|
||||
}
|
||||
if (wsPolarity === 'negative' && kvarkPolarity === 'positive') {
|
||||
return 'Enterprise documents contain affirmative language while workspace memory contains contradictory language. The enterprise source may be more current.';
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
type Polarity = 'positive' | 'negative' | 'neutral';
|
||||
|
||||
function extractPolarity(texts: string[]): Polarity {
|
||||
const combined = texts.join(' ');
|
||||
const hasPositive = POSITIVE_STATUS.some(w => combined.includes(w));
|
||||
const hasNegative = NEGATIVE_STATUS.some(w => combined.includes(w));
|
||||
|
||||
// Only assign polarity when one side dominates
|
||||
if (hasPositive && !hasNegative) return 'positive';
|
||||
if (hasNegative && !hasPositive) return 'negative';
|
||||
return 'neutral';
|
||||
}
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────
|
||||
@@ -170,38 +86,6 @@ export function mapMemoryResult(
|
||||
};
|
||||
}
|
||||
|
||||
/** Map a KvarkStructuredResult into a CombinedResult */
|
||||
export function mapKvarkResult(result: KvarkStructuredResult): CombinedResult {
|
||||
return {
|
||||
content: result.content,
|
||||
source: 'kvark',
|
||||
attribution: result.attribution,
|
||||
score: result.score,
|
||||
metadata: {
|
||||
documentId: result.documentId,
|
||||
documentType: result.documentType,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Check whether local results are strong enough to skip KVARK */
|
||||
export function hasSufficientLocalCoverage(results: CombinedResult[]): boolean {
|
||||
const strongResults = results.filter(r => r.score >= LOCAL_COVERAGE_SCORE_THRESHOLD);
|
||||
return strongResults.length >= LOCAL_COVERAGE_MIN_COUNT;
|
||||
}
|
||||
|
||||
/** Decide whether KVARK should be queried */
|
||||
export function shouldQueryKvark(
|
||||
kvarkClient: KvarkClientLike | null,
|
||||
scope: 'all' | 'personal' | 'workspace',
|
||||
localResults: CombinedResult[],
|
||||
): boolean {
|
||||
if (!kvarkClient) return false;
|
||||
if (scope === 'personal' || scope === 'workspace') return false;
|
||||
if (hasSufficientLocalCoverage(localResults)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── Main class ────────────────────────────────────────────────────────────
|
||||
|
||||
export class CombinedRetrieval {
|
||||
@@ -215,61 +99,15 @@ export class CombinedRetrieval {
|
||||
const { limit = 10, profile = 'balanced', scope = 'all', turnId } = opts;
|
||||
logTurnEvent(turnId, { stage: 'retrieval.enter', queryChars: query.length, limit, profile, scope });
|
||||
|
||||
// 1. Search workspace memory
|
||||
const workspaceResults = await this.searchWorkspace(query, limit, profile, scope);
|
||||
|
||||
// 2. Search personal memory
|
||||
const personalResults = await this.searchPersonal(query, limit, profile, scope);
|
||||
|
||||
// 3. Decide whether to call KVARK
|
||||
const localResults = [...workspaceResults, ...personalResults];
|
||||
const kvarkAvailable = this.deps.kvarkClient !== null;
|
||||
const callKvark = shouldQueryKvark(this.deps.kvarkClient, scope, localResults);
|
||||
|
||||
if (!callKvark) {
|
||||
logTurnEvent(turnId, {
|
||||
stage: 'retrieval.exit',
|
||||
workspaceHits: workspaceResults.length,
|
||||
personalHits: personalResults.length,
|
||||
kvarkHits: 0,
|
||||
kvarkSkipped: kvarkAvailable,
|
||||
});
|
||||
return {
|
||||
query,
|
||||
workspaceResults,
|
||||
personalResults,
|
||||
kvarkResults: [],
|
||||
kvarkAvailable,
|
||||
kvarkSkipped: kvarkAvailable, // skipped only if it was available but we chose not to call
|
||||
hasConflict: false,
|
||||
};
|
||||
}
|
||||
|
||||
// 4. Call KVARK (with graceful degradation)
|
||||
const { kvarkResults, kvarkError } = await this.searchKvark(query, limit);
|
||||
|
||||
// 5. Detect potential conflict between workspace memory and KVARK
|
||||
const conflictNote = detectConflict(workspaceResults, kvarkResults);
|
||||
|
||||
logTurnEvent(turnId, {
|
||||
stage: 'retrieval.exit',
|
||||
workspaceHits: workspaceResults.length,
|
||||
personalHits: personalResults.length,
|
||||
kvarkHits: kvarkResults.length,
|
||||
kvarkError: kvarkError ?? null,
|
||||
hasConflict: conflictNote !== null,
|
||||
});
|
||||
return {
|
||||
query,
|
||||
workspaceResults,
|
||||
personalResults,
|
||||
kvarkResults,
|
||||
kvarkAvailable: true,
|
||||
kvarkSkipped: false,
|
||||
kvarkError,
|
||||
hasConflict: conflictNote !== null,
|
||||
conflictNote: conflictNote ?? undefined,
|
||||
};
|
||||
return { query, workspaceResults, personalResults };
|
||||
}
|
||||
|
||||
private async searchWorkspace(
|
||||
@@ -290,17 +128,4 @@ export class CombinedRetrieval {
|
||||
const results = await this.deps.personalSearch.search(query, { limit, profile });
|
||||
return results.map(r => mapMemoryResult(r, 'personal'));
|
||||
}
|
||||
|
||||
private async searchKvark(
|
||||
query: string, limit: number,
|
||||
): Promise<{ kvarkResults: CombinedResult[]; kvarkError?: string }> {
|
||||
try {
|
||||
const response = await this.deps.kvarkClient!.search(query, { limit });
|
||||
const structured = parseSearchResults(response);
|
||||
return { kvarkResults: structured.map(mapKvarkResult) };
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Unknown KVARK error';
|
||||
return { kvarkResults: [], kvarkError: message };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,343 +0,0 @@
|
||||
/**
|
||||
* Skills 2.0 gap H — boardroom-grade compliance report PDF.
|
||||
*
|
||||
* Consumes an AuditReport (from @waggle/core/compliance) and produces a
|
||||
* multi-page PDF styled with Waggle's Hive DS tokens (honey #E5A000).
|
||||
* The layout is designed for the KVARK sales pitch: readable at arm's
|
||||
* length, executive summary on page 1, detail tables on subsequent
|
||||
* pages, page numbers, metadata header.
|
||||
*
|
||||
* Sections:
|
||||
* 1. Cover — org name, risk level, report period, generated-at
|
||||
* 2. Executive Summary — compliance status + status badges
|
||||
* 3. Article status grid (Art 12/14/19/26/50)
|
||||
* 4. Model Inventory table
|
||||
* 5. Human Oversight Log table
|
||||
* 6. Harvest Provenance table
|
||||
* 7. Closing: totals + signature line
|
||||
*/
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import type { AuditReport, ComplianceStatus, ArticleStatus, AIActRiskLevel } from '@waggle/core';
|
||||
import type { TDocumentDefinitions, Content, TableCell } from 'pdfmake/interfaces.js';
|
||||
|
||||
// Minimal surface of the pdfmake static we use (createPdf().getBuffer()).
|
||||
interface PdfPrinter {
|
||||
getBuffer(cb: (buffer: Buffer) => void): void;
|
||||
}
|
||||
interface PdfMakeStatic {
|
||||
createPdf(docDef: TDocumentDefinitions): PdfPrinter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Optional template-sourced overrides (M-03). Applied over the workspace-derived
|
||||
* values so a single workspace can render under multiple branded templates without
|
||||
* mutating the underlying WorkspaceConfig. Logo is deferred to Bucket 2.
|
||||
*/
|
||||
export interface PdfTemplateOverrides {
|
||||
orgName?: string | null;
|
||||
footerText?: string | null;
|
||||
riskClassification?: AIActRiskLevel | null;
|
||||
}
|
||||
|
||||
/** Hive DS color palette — match design-system conventions */
|
||||
const HIVE_HONEY = '#E5A000';
|
||||
const HIVE_DARK = '#08090C';
|
||||
const HIVE_ACCENT = '#A78BFA';
|
||||
const STATUS_COLORS: Record<ComplianceStatus['overall'], string> = {
|
||||
compliant: '#22A06B',
|
||||
warning: '#E5A000',
|
||||
'non-compliant': '#C4342F',
|
||||
};
|
||||
|
||||
const ARTICLE_LABELS: Record<string, string> = {
|
||||
art12Logging: 'Art. 12 — Logging',
|
||||
art14Oversight: 'Art. 14 — Human Oversight',
|
||||
art19Retention: 'Art. 19 — Data Retention',
|
||||
art26Monitoring: 'Art. 26 — Risk Classification',
|
||||
art50Transparency: 'Art. 50 — Transparency',
|
||||
};
|
||||
|
||||
function statusBadge(status: ArticleStatus['status']): Content {
|
||||
const color = status === 'compliant' ? STATUS_COLORS.compliant
|
||||
: status === 'warning' ? STATUS_COLORS.warning
|
||||
: STATUS_COLORS['non-compliant'];
|
||||
const label = status === 'compliant' ? 'COMPLIANT'
|
||||
: status === 'warning' ? 'WARNING'
|
||||
: 'NON-COMPLIANT';
|
||||
return { text: label, bold: true, color, fontSize: 9 };
|
||||
}
|
||||
|
||||
function coverContent(report: AuditReport, overrides?: PdfTemplateOverrides): Content[] {
|
||||
const wsName = (overrides?.orgName && overrides.orgName.trim()) || report.workspace?.name || 'Personal Mind';
|
||||
const riskLevel = (overrides?.riskClassification ?? report.workspace?.riskLevel ?? 'minimal').toUpperCase();
|
||||
return [
|
||||
{ text: 'AI ACT COMPLIANCE AUDIT', style: 'titleKicker', margin: [0, 120, 0, 6] },
|
||||
{ text: wsName, style: 'title', margin: [0, 0, 0, 12] },
|
||||
{ canvas: [{ type: 'line', x1: 0, y1: 0, x2: 500, y2: 0, lineWidth: 1.5, lineColor: HIVE_HONEY }], margin: [0, 0, 0, 24] },
|
||||
{
|
||||
columns: [
|
||||
[
|
||||
{ text: 'Risk Level', style: 'metaLabel' },
|
||||
{ text: riskLevel, style: 'metaValue', margin: [0, 2, 0, 12] },
|
||||
{ text: 'Period', style: 'metaLabel' },
|
||||
{ text: `${report.report.period.from.slice(0, 10)} → ${report.report.period.to.slice(0, 10)}`, style: 'metaValue', margin: [0, 2, 0, 12] },
|
||||
],
|
||||
[
|
||||
{ text: 'Overall Status', style: 'metaLabel' },
|
||||
{ text: report.complianceStatus.overall.toUpperCase(), style: 'metaValue', color: STATUS_COLORS[report.complianceStatus.overall], margin: [0, 2, 0, 12] },
|
||||
{ text: 'Generated', style: 'metaLabel' },
|
||||
{ text: report.report.generatedAt.slice(0, 19).replace('T', ' ') + ' UTC', style: 'metaValue', margin: [0, 2, 0, 12] },
|
||||
],
|
||||
],
|
||||
},
|
||||
{ text: '', pageBreak: 'after' },
|
||||
];
|
||||
}
|
||||
|
||||
function articleGrid(status: ComplianceStatus): Content {
|
||||
const rows: TableCell[][] = [
|
||||
[
|
||||
{ text: 'Article', style: 'tableHead' },
|
||||
{ text: 'Status', style: 'tableHead' },
|
||||
{ text: 'Detail', style: 'tableHead' },
|
||||
],
|
||||
];
|
||||
for (const [key, label] of Object.entries(ARTICLE_LABELS)) {
|
||||
const article = (status as unknown as Record<string, ArticleStatus>)[key];
|
||||
if (!article) continue;
|
||||
rows.push([
|
||||
{ text: label, bold: true, fontSize: 10 },
|
||||
statusBadge(article.status),
|
||||
{ text: article.detail, fontSize: 9 },
|
||||
]);
|
||||
}
|
||||
return {
|
||||
table: { headerRows: 1, widths: [150, 80, '*'], body: rows },
|
||||
layout: { hLineColor: () => '#E5E5E5', vLineColor: () => '#E5E5E5' },
|
||||
margin: [0, 0, 0, 20],
|
||||
};
|
||||
}
|
||||
|
||||
function modelInventoryTable(report: AuditReport): Content {
|
||||
if (report.modelInventory.length === 0) {
|
||||
return { text: 'No model calls recorded in this period.', italics: true, color: '#6B6B6B', margin: [0, 0, 0, 16] };
|
||||
}
|
||||
const rows: TableCell[][] = [[
|
||||
{ text: 'Model', style: 'tableHead' },
|
||||
{ text: 'Provider', style: 'tableHead' },
|
||||
{ text: 'Calls', style: 'tableHead', alignment: 'right' },
|
||||
{ text: 'Input tok', style: 'tableHead', alignment: 'right' },
|
||||
{ text: 'Output tok', style: 'tableHead', alignment: 'right' },
|
||||
{ text: 'Cost (USD)', style: 'tableHead', alignment: 'right' },
|
||||
]];
|
||||
let totalCalls = 0, totalIn = 0, totalOut = 0, totalCost = 0;
|
||||
for (const m of report.modelInventory) {
|
||||
totalCalls += m.calls;
|
||||
totalIn += m.inputTokens;
|
||||
totalOut += m.outputTokens;
|
||||
totalCost += m.costUsd;
|
||||
rows.push([
|
||||
{ text: m.model, fontSize: 9 },
|
||||
{ text: m.provider, fontSize: 9 },
|
||||
{ text: m.calls.toLocaleString('en-US'), fontSize: 9, alignment: 'right' },
|
||||
{ text: m.inputTokens.toLocaleString('en-US'), fontSize: 9, alignment: 'right' },
|
||||
{ text: m.outputTokens.toLocaleString('en-US'), fontSize: 9, alignment: 'right' },
|
||||
{ text: `$${m.costUsd.toFixed(4)}`, fontSize: 9, alignment: 'right' },
|
||||
]);
|
||||
}
|
||||
rows.push([
|
||||
{ text: 'TOTAL', bold: true, fontSize: 9, fillColor: '#FAFAFA' },
|
||||
{ text: '', fillColor: '#FAFAFA' },
|
||||
{ text: totalCalls.toLocaleString('en-US'), bold: true, fontSize: 9, alignment: 'right', fillColor: '#FAFAFA' },
|
||||
{ text: totalIn.toLocaleString('en-US'), bold: true, fontSize: 9, alignment: 'right', fillColor: '#FAFAFA' },
|
||||
{ text: totalOut.toLocaleString('en-US'), bold: true, fontSize: 9, alignment: 'right', fillColor: '#FAFAFA' },
|
||||
{ text: `$${totalCost.toFixed(4)}`, bold: true, fontSize: 9, alignment: 'right', fillColor: '#FAFAFA' },
|
||||
]);
|
||||
return {
|
||||
table: { headerRows: 1, widths: ['*', 70, 40, 60, 60, 60], body: rows },
|
||||
layout: { hLineColor: () => '#E5E5E5', vLineColor: () => '#E5E5E5' },
|
||||
margin: [0, 0, 0, 20],
|
||||
};
|
||||
}
|
||||
|
||||
function oversightLogTable(report: AuditReport): Content {
|
||||
if (report.humanOversightLog.length === 0) {
|
||||
return { text: 'No human oversight events in this period.', italics: true, color: '#6B6B6B', margin: [0, 0, 0, 16] };
|
||||
}
|
||||
// Cap at 50 most recent events to keep the PDF tight; detail goes in JSON report
|
||||
const shown = report.humanOversightLog.slice(-50);
|
||||
const rows: TableCell[][] = [[
|
||||
{ text: 'Timestamp', style: 'tableHead' },
|
||||
{ text: 'Action', style: 'tableHead' },
|
||||
{ text: 'Tool', style: 'tableHead' },
|
||||
{ text: 'Detail', style: 'tableHead' },
|
||||
]];
|
||||
for (const e of shown) {
|
||||
rows.push([
|
||||
{ text: e.timestamp.slice(0, 19).replace('T', ' '), fontSize: 8 },
|
||||
{ text: e.action, fontSize: 8, bold: true },
|
||||
{ text: e.tool, fontSize: 8 },
|
||||
{ text: e.detail.slice(0, 80), fontSize: 8 },
|
||||
]);
|
||||
}
|
||||
const contents: Content[] = [{
|
||||
table: { headerRows: 1, widths: [95, 60, 80, '*'], body: rows },
|
||||
layout: { hLineColor: () => '#E5E5E5', vLineColor: () => '#E5E5E5' },
|
||||
margin: [0, 0, 0, 8],
|
||||
}];
|
||||
if (report.humanOversightLog.length > 50) {
|
||||
contents.push({
|
||||
text: `Showing last 50 of ${report.humanOversightLog.length} events. Full log in JSON report.`,
|
||||
fontSize: 8, italics: true, color: '#6B6B6B', margin: [0, 0, 0, 16],
|
||||
});
|
||||
}
|
||||
return contents;
|
||||
}
|
||||
|
||||
function provenanceTable(report: AuditReport): Content {
|
||||
if (report.harvestProvenance.length === 0) {
|
||||
return { text: 'No harvest provenance data for this period.', italics: true, color: '#6B6B6B', margin: [0, 0, 0, 16] };
|
||||
}
|
||||
const rows: TableCell[][] = [[
|
||||
{ text: 'Source', style: 'tableHead' },
|
||||
{ text: 'Imported At', style: 'tableHead' },
|
||||
{ text: 'Items', style: 'tableHead', alignment: 'right' },
|
||||
{ text: 'Frames', style: 'tableHead', alignment: 'right' },
|
||||
]];
|
||||
for (const p of report.harvestProvenance) {
|
||||
rows.push([
|
||||
{ text: p.source, fontSize: 9 },
|
||||
{ text: p.importedAt.slice(0, 19).replace('T', ' '), fontSize: 9 },
|
||||
{ text: p.itemsImported.toLocaleString('en-US'), fontSize: 9, alignment: 'right' },
|
||||
{ text: p.framesCreated.toLocaleString('en-US'), fontSize: 9, alignment: 'right' },
|
||||
]);
|
||||
}
|
||||
return {
|
||||
table: { headerRows: 1, widths: ['*', 120, 60, 60], body: rows },
|
||||
layout: { hLineColor: () => '#E5E5E5', vLineColor: () => '#E5E5E5' },
|
||||
margin: [0, 0, 0, 20],
|
||||
};
|
||||
}
|
||||
|
||||
/** Build the pdfmake document definition. Exported for unit-test introspection. */
|
||||
export function buildComplianceDocDefinition(
|
||||
report: AuditReport,
|
||||
overrides?: PdfTemplateOverrides,
|
||||
): TDocumentDefinitions {
|
||||
const wsName = (overrides?.orgName && overrides.orgName.trim()) || report.workspace?.name || 'Personal';
|
||||
const footerExtra = overrides?.footerText?.trim() || null;
|
||||
const content: Content[] = [
|
||||
...coverContent(report, overrides),
|
||||
|
||||
{ text: 'Compliance Status', style: 'h1', margin: [0, 0, 0, 6] },
|
||||
{
|
||||
text: report.complianceStatus.overall === 'compliant'
|
||||
? 'All monitored articles pass. The deployment operates within the AI Act framework for the selected period.'
|
||||
: report.complianceStatus.overall === 'warning'
|
||||
? 'One or more articles report warnings. Review the detail column for remediation.'
|
||||
: 'At least one article is non-compliant. Remediation is required before the next audit.',
|
||||
fontSize: 10, italics: true, color: '#333333', margin: [0, 0, 0, 16],
|
||||
},
|
||||
articleGrid(report.complianceStatus),
|
||||
|
||||
{ text: 'Model Inventory', style: 'h1', margin: [0, 0, 0, 6] },
|
||||
{ text: `Tracked LLM/embedding model calls across the selected period. Totals appear on the bottom row.`, fontSize: 10, color: '#333333', margin: [0, 0, 0, 10] },
|
||||
modelInventoryTable(report),
|
||||
|
||||
{ text: 'Human Oversight Log', style: 'h1', margin: [0, 0, 0, 6] },
|
||||
{ text: `Art. 14 record of human approve/deny/modify actions on agent-proposed tool calls. Total this period: ${report.humanOversightLog.length}.`, fontSize: 10, color: '#333333', margin: [0, 0, 0, 10] },
|
||||
...([] as Content[]).concat(oversightLogTable(report) as Content[] | Content),
|
||||
|
||||
{ text: 'Harvest Provenance', style: 'h1', margin: [0, 0, 0, 6] },
|
||||
{ text: 'Art. 10 data-quality record of conversation imports and their downstream frame counts.', fontSize: 10, color: '#333333', margin: [0, 0, 0, 10] },
|
||||
provenanceTable(report),
|
||||
|
||||
{ text: 'Summary', style: 'h1', margin: [0, 12, 0, 6] },
|
||||
{
|
||||
ul: [
|
||||
`Total interactions logged: ${report.interactionCount.toLocaleString('en-US')}`,
|
||||
`Models in inventory: ${report.modelInventory.length}`,
|
||||
`Oversight events: ${report.humanOversightLog.length}`,
|
||||
`Harvest sources: ${report.harvestProvenance.length}`,
|
||||
],
|
||||
fontSize: 10, color: '#333333', margin: [0, 0, 0, 20],
|
||||
},
|
||||
|
||||
{ canvas: [{ type: 'line', x1: 0, y1: 0, x2: 500, y2: 0, lineWidth: 0.5, lineColor: '#CCCCCC' }], margin: [0, 12, 0, 6] },
|
||||
{
|
||||
text: `Report v${report.report.version} — generated by ${report.report.generatedBy}.`,
|
||||
fontSize: 8, color: '#95A5A6', alignment: 'center',
|
||||
},
|
||||
];
|
||||
|
||||
return {
|
||||
info: {
|
||||
title: `Waggle AI Act Compliance Audit — ${wsName}`,
|
||||
author: 'Waggle OS',
|
||||
creator: 'Waggle OS Compliance Module',
|
||||
subject: `AI Act compliance audit for period ${report.report.period.from} → ${report.report.period.to}`,
|
||||
},
|
||||
pageSize: 'A4',
|
||||
pageMargins: [50, 60, 50, 60],
|
||||
header: (currentPage: number) => currentPage > 1 ? {
|
||||
columns: [
|
||||
{ text: 'Waggle — AI Act Compliance Audit', fontSize: 8, color: '#95A5A6', margin: [50, 20, 0, 0] },
|
||||
{ text: wsName, alignment: 'right', fontSize: 8, color: '#95A5A6', margin: [0, 20, 50, 0] },
|
||||
],
|
||||
} : undefined,
|
||||
footer: (currentPage: number, pageCount: number) => ({
|
||||
columns: [
|
||||
{
|
||||
text: footerExtra
|
||||
? `Generated ${report.report.generatedAt.slice(0, 10)} · ${footerExtra}`
|
||||
: `Generated ${report.report.generatedAt.slice(0, 10)}`,
|
||||
fontSize: 8, color: '#95A5A6', margin: [50, 0, 0, 0],
|
||||
},
|
||||
{ text: `${currentPage} / ${pageCount}`, alignment: 'right', fontSize: 8, color: '#95A5A6', margin: [0, 0, 50, 0] },
|
||||
],
|
||||
}),
|
||||
content,
|
||||
styles: {
|
||||
titleKicker: { fontSize: 11, color: HIVE_HONEY, bold: true, characterSpacing: 2 },
|
||||
title: { fontSize: 30, bold: true, color: HIVE_DARK },
|
||||
metaLabel: { fontSize: 8, color: '#95A5A6', characterSpacing: 1 },
|
||||
metaValue: { fontSize: 14, bold: true, color: HIVE_DARK },
|
||||
h1: { fontSize: 16, bold: true, color: HIVE_HONEY },
|
||||
tableHead: { fontSize: 9, bold: true, color: HIVE_DARK, fillColor: '#FAFAFA' },
|
||||
},
|
||||
defaultStyle: { fontSize: 10, lineHeight: 1.35, color: '#333333' },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Render an AuditReport to a PDF Buffer.
|
||||
* Uses dynamic import so pdfmake is only loaded when PDF generation runs.
|
||||
*/
|
||||
export async function renderComplianceReportPdf(
|
||||
report: AuditReport,
|
||||
overrides?: PdfTemplateOverrides,
|
||||
): Promise<Buffer> {
|
||||
const docDef = buildComplianceDocDefinition(report, overrides);
|
||||
const pdfMakeModule = await import('pdfmake/build/pdfmake.js');
|
||||
const pdfMake = (pdfMakeModule.default ?? pdfMakeModule) as unknown as PdfMakeStatic;
|
||||
const printer = pdfMake.createPdf(docDef);
|
||||
return new Promise<Buffer>((resolve, reject) => {
|
||||
printer.getBuffer((buffer: Buffer) => {
|
||||
if (buffer) resolve(buffer);
|
||||
else reject(new Error('PDF generation returned empty buffer'));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** Convenience: write the PDF to disk. Returns the absolute path. */
|
||||
export async function writeComplianceReportPdf(
|
||||
report: AuditReport,
|
||||
outputPath: string,
|
||||
overrides?: PdfTemplateOverrides,
|
||||
): Promise<string> {
|
||||
const buffer = await renderComplianceReportPdf(report, overrides);
|
||||
fs.mkdirSync(path.dirname(outputPath), { recursive: true });
|
||||
fs.writeFileSync(outputPath, buffer);
|
||||
return path.resolve(outputPath);
|
||||
}
|
||||
@@ -49,7 +49,7 @@ export interface WaggleConnector {
|
||||
*/
|
||||
readonly harvestAction?: { action: string; params?: Record<string, unknown> };
|
||||
/** Which substrate manages this connector */
|
||||
readonly substrate: 'waggle' | 'kvark';
|
||||
readonly substrate: 'waggle';
|
||||
/** CDN URL for SVG logo */
|
||||
readonly logoUrl?: string;
|
||||
/** Connector category */
|
||||
@@ -78,7 +78,7 @@ export abstract class BaseConnector implements WaggleConnector {
|
||||
abstract readonly service: string;
|
||||
abstract readonly authType: 'bearer' | 'oauth2' | 'api_key' | 'basic';
|
||||
abstract readonly actions: ConnectorAction[];
|
||||
abstract readonly substrate: 'waggle' | 'kvark';
|
||||
abstract readonly substrate: 'waggle';
|
||||
readonly logoUrl?: string;
|
||||
readonly category?: 'productivity' | 'development' | 'crm' | 'data' | 'communication' | 'storage' | 'integration';
|
||||
readonly setupGuide?: string;
|
||||
|
||||
@@ -382,11 +382,6 @@ export { CommandRegistry, AGENT_LOOP_REROUTE_PREFIX, type CommandDefinition, typ
|
||||
export { registerWorkflowCommands } from './commands/workflow-commands.js';
|
||||
export { registerMarketplaceCommands } from './commands/marketplace-commands.js';
|
||||
export { createCronTools, type TurnOrigin } from './cron-tools.js';
|
||||
export {
|
||||
createKvarkTools, parseSearchResults,
|
||||
type KvarkClientLike, type KvarkToolsDeps, type KvarkSearchResponseLike,
|
||||
type KvarkAskResponseLike, type KvarkStructuredResult, type KvarkFeedbackResponseLike, type KvarkActionResponseLike,
|
||||
} from './kvark-tools.js';
|
||||
export { PERSONAS, getPersona, listPersonas, composePersonaPrompt, setPersonaDataDir, type AgentPersona } from './personas.js';
|
||||
export {
|
||||
loadCustomPersonas, saveCustomPersona, deleteCustomPersona,
|
||||
@@ -470,12 +465,6 @@ export {
|
||||
type SkillForAudit, type AuditTask, type SkillAuditOptions, type SkillAuditHooks,
|
||||
type SkillAuditOutcome, type SkillAuditReport, type RewriteValidation,
|
||||
} from './skill-audit.js';
|
||||
export {
|
||||
buildComplianceDocDefinition,
|
||||
renderComplianceReportPdf,
|
||||
writeComplianceReportPdf,
|
||||
type PdfTemplateOverrides,
|
||||
} from './compliance-pdf.js';
|
||||
export {
|
||||
watchSkillDirectory,
|
||||
type SkillWatcherOptions, type SkillWatcherHandle,
|
||||
|
||||
@@ -1,311 +0,0 @@
|
||||
/**
|
||||
* KVARK Agent Tools — kvark_search + kvark_ask_document.
|
||||
*
|
||||
* These tools are the agent-facing interface to KVARK's retrieval pipeline.
|
||||
* All KVARK calls go through KvarkClient (from @waggle/server/kvark).
|
||||
* Tools are only registered when KVARK is configured (Business/Enterprise tiers).
|
||||
* Solo/Team users never see these tools.
|
||||
*
|
||||
* Design rules:
|
||||
* - Tools use KvarkClient only — no direct fetch
|
||||
* - Output is formatted text for the agent, not raw DTOs
|
||||
* - Attribution structure preserved for Milestone B combined retrieval
|
||||
* - Graceful degradation on all error paths
|
||||
*/
|
||||
|
||||
import type { ToolDefinition } from './tools.js';
|
||||
|
||||
// ── Types from KVARK client (imported by interface, not package dep) ─────
|
||||
|
||||
/** Minimal KvarkClient interface — matches KvarkClient from @waggle/server/kvark */
|
||||
export interface KvarkClientLike {
|
||||
search(query: string, opts?: { limit?: number; offset?: number }): Promise<KvarkSearchResponseLike>;
|
||||
askDocument(documentId: string, question: string): Promise<KvarkAskResponseLike>;
|
||||
feedback?(documentId: number, query: string, useful: boolean, reason?: string): Promise<KvarkFeedbackResponseLike>;
|
||||
action?(actionType: string, target: { entityType: string; entityId: string }, payload: Record<string, unknown>, reason: string, approvalReference?: string, workspaceId?: string): Promise<KvarkActionResponseLike>;
|
||||
}
|
||||
|
||||
export interface KvarkFeedbackResponseLike {
|
||||
ok: boolean;
|
||||
}
|
||||
|
||||
export interface KvarkActionResponseLike {
|
||||
ok: boolean;
|
||||
data: {
|
||||
status: 'executed' | 'denied' | 'queued';
|
||||
actionId?: string;
|
||||
auditRef?: string;
|
||||
result?: Record<string, unknown>;
|
||||
} | null;
|
||||
error: { code: string; message: string } | null;
|
||||
}
|
||||
|
||||
export interface KvarkSearchResponseLike {
|
||||
results: KvarkSearchResultLike[];
|
||||
total: number;
|
||||
query: string;
|
||||
}
|
||||
|
||||
export interface KvarkSearchResultLike {
|
||||
document_id: number;
|
||||
title: string;
|
||||
snippet: string;
|
||||
score: number;
|
||||
document_type: string | null;
|
||||
}
|
||||
|
||||
export interface KvarkAskResponseLike {
|
||||
answer: string;
|
||||
sources: string[];
|
||||
}
|
||||
|
||||
// ── Structured result for Milestone B consumption ────────────────────────
|
||||
|
||||
/** Structured KVARK search result — used by combined retrieval (Milestone B) */
|
||||
export interface KvarkStructuredResult {
|
||||
content: string;
|
||||
documentId: number;
|
||||
title: string;
|
||||
score: number;
|
||||
documentType: string | null;
|
||||
/** Attribution label for agent responses, e.g. "[KVARK: pdf / Project Status]" */
|
||||
attribution: string;
|
||||
}
|
||||
|
||||
/** Parses KvarkClient search response into structured results */
|
||||
export function parseSearchResults(response: KvarkSearchResponseLike): KvarkStructuredResult[] {
|
||||
return response.results.map(r => ({
|
||||
content: r.snippet,
|
||||
documentId: r.document_id,
|
||||
title: r.title,
|
||||
score: r.score,
|
||||
documentType: r.document_type,
|
||||
attribution: formatKvarkAttribution(r),
|
||||
}));
|
||||
}
|
||||
|
||||
/** Format a KVARK result into an attribution label */
|
||||
function formatKvarkAttribution(result: KvarkSearchResultLike): string {
|
||||
const parts = ['KVARK'];
|
||||
if (result.document_type) parts.push(result.document_type);
|
||||
parts.push(result.title);
|
||||
return `[${parts.join(': ')}]`;
|
||||
// Future: add connector, page when KVARK exposes them
|
||||
// e.g. [KVARK: SharePoint / Project Status.pdf p.3]
|
||||
}
|
||||
|
||||
// ── Tool output formatting ───────────────────────────────────────────────
|
||||
|
||||
function formatSearchOutput(response: KvarkSearchResponseLike, query: string): string {
|
||||
if (response.results.length === 0) {
|
||||
return `KVARK Search: "${query}" — no results found.`;
|
||||
}
|
||||
|
||||
const header = `KVARK Search: "${query}" (${response.results.length} of ${response.total} results)\n`;
|
||||
const items = response.results.map((r, i) => {
|
||||
const typeLabel = r.document_type ? `[${r.document_type}]` : '[document]';
|
||||
const snippet = r.snippet.length > 200 ? r.snippet.slice(0, 197) + '...' : r.snippet;
|
||||
return `${i + 1}. ${typeLabel} ${r.title} (score: ${r.score.toFixed(2)})\n "${snippet}"\n ID: ${r.document_id}`;
|
||||
});
|
||||
|
||||
return header + items.join('\n\n');
|
||||
}
|
||||
|
||||
function formatAskOutput(response: KvarkAskResponseLike, documentId: string): string {
|
||||
const sources = response.sources.length > 0
|
||||
? `\n\nSources: ${response.sources.join(', ')}`
|
||||
: '';
|
||||
return `KVARK Document Answer (doc #${documentId}):\n\n${response.answer}${sources}`;
|
||||
}
|
||||
|
||||
// ── Tool factory ─────────────────────────────────────────────────────────
|
||||
|
||||
export interface KvarkToolsDeps {
|
||||
client: KvarkClientLike;
|
||||
}
|
||||
|
||||
export function createKvarkTools(deps: KvarkToolsDeps): ToolDefinition[] {
|
||||
const { client } = deps;
|
||||
|
||||
return [
|
||||
// ── kvark_search ─────────────────────────────────────────────
|
||||
{
|
||||
name: 'kvark_search',
|
||||
description:
|
||||
'Search enterprise knowledge base via KVARK. Returns documents from connected sources (SharePoint, Jira, Slack, etc.) with relevance scores and source attribution. Use when the user needs information from enterprise systems beyond workspace memory.',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
query: { type: 'string', description: 'Search query' },
|
||||
limit: { type: 'number', description: 'Max results to return (default 10)' },
|
||||
},
|
||||
required: ['query'],
|
||||
},
|
||||
execute: async (args) => {
|
||||
const query = args.query as string;
|
||||
const limit = (args.limit as number) ?? 10;
|
||||
|
||||
try {
|
||||
const response = await client.search(query, { limit });
|
||||
return formatSearchOutput(response, query);
|
||||
} catch (err) {
|
||||
return handleKvarkError(err, 'search');
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
// ── kvark_feedback ─────────────────────────────────────────────
|
||||
{
|
||||
name: 'kvark_feedback',
|
||||
description:
|
||||
'Send feedback to KVARK about whether an enterprise search result was useful. Use this ONLY when a KVARK result materially influenced your answer — not for every search. Helps KVARK improve future retrieval quality.',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
document_id: { type: 'number', description: 'Document ID from kvark_search or search_memory KVARK results' },
|
||||
query: { type: 'string', description: 'The original search query that produced this result' },
|
||||
useful: { type: 'boolean', description: 'Whether the result was useful for answering the user' },
|
||||
reason: { type: 'string', description: 'Brief explanation of why the result was or was not useful (optional)' },
|
||||
},
|
||||
required: ['document_id', 'query', 'useful'],
|
||||
},
|
||||
execute: async (args) => {
|
||||
const documentId = args.document_id as number;
|
||||
const query = args.query as string;
|
||||
const useful = args.useful as boolean;
|
||||
const reason = args.reason as string | undefined;
|
||||
|
||||
if (!client.feedback) {
|
||||
return 'Feedback not supported by this KVARK instance.';
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await client.feedback(documentId, query, useful, reason);
|
||||
return response.ok
|
||||
? `Feedback recorded: ${useful ? 'useful' : 'not useful'} for document #${documentId}.`
|
||||
: 'Feedback was sent but KVARK did not confirm storage.';
|
||||
} catch (err) {
|
||||
return handleKvarkError(err, 'feedback');
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
// ── kvark_action ──────────────────────────────────────────────
|
||||
{
|
||||
name: 'kvark_action',
|
||||
description:
|
||||
'Execute a governed enterprise action through KVARK (e.g., create a Jira ticket, post a Slack message, update a record). Requires user approval before execution. Use only when the user has explicitly asked for an action that touches enterprise systems.',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
action_type: { type: 'string', description: 'Action identifier (e.g., "jira.create_comment", "slack.post_message", "sharepoint.update_file")' },
|
||||
entity_type: { type: 'string', description: 'Target entity type (e.g., "issue", "channel", "document")' },
|
||||
entity_id: { type: 'string', description: 'Target entity ID (e.g., "PROJ-142", "#general", "doc_123")' },
|
||||
payload: { type: 'object', description: 'Action-specific data (e.g., { "comment": "..." } for a comment action)' },
|
||||
reason: { type: 'string', description: 'Why this action is being performed — shown in governance audit trail' },
|
||||
},
|
||||
required: ['action_type', 'entity_type', 'entity_id', 'payload', 'reason'],
|
||||
},
|
||||
execute: async (args) => {
|
||||
const actionType = args.action_type as string;
|
||||
const entityType = args.entity_type as string;
|
||||
const entityId = args.entity_id as string;
|
||||
const payload = (args.payload as Record<string, unknown>) ?? {};
|
||||
const reason = args.reason as string;
|
||||
|
||||
if (!client.action) {
|
||||
return 'Governed actions are not supported by this KVARK instance.';
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await client.action(
|
||||
actionType,
|
||||
{ entityType, entityId },
|
||||
payload,
|
||||
reason,
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
const errMsg = response.error?.message ?? 'Action was denied by KVARK governance policy.';
|
||||
return `Action denied: ${errMsg}`;
|
||||
}
|
||||
|
||||
const data = response.data!;
|
||||
const parts = [`Action executed: ${actionType} on ${entityType}/${entityId}`];
|
||||
if (data.actionId) parts.push(`Action ID: ${data.actionId}`);
|
||||
if (data.auditRef) parts.push(`Audit reference: ${data.auditRef}`);
|
||||
if (data.status === 'queued') parts.push('Status: queued for execution');
|
||||
return parts.join('\n');
|
||||
} catch (err) {
|
||||
return handleKvarkError(err, 'action');
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
// ── kvark_ask_document ───────────────────────────────────────
|
||||
{
|
||||
name: 'kvark_ask_document',
|
||||
description:
|
||||
'Ask a focused question about a specific enterprise document. Returns an answer with source references. Use after kvark_search identifies a relevant document.',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
document_id: { type: 'string', description: 'Document ID from kvark_search results' },
|
||||
question: { type: 'string', description: 'Question about the document' },
|
||||
},
|
||||
required: ['document_id', 'question'],
|
||||
},
|
||||
execute: async (args) => {
|
||||
const documentId = args.document_id as string;
|
||||
const question = args.question as string;
|
||||
|
||||
try {
|
||||
const response = await client.askDocument(documentId, question);
|
||||
return formatAskOutput(response, documentId);
|
||||
} catch (err) {
|
||||
return handleKvarkError(err, 'ask');
|
||||
}
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
// ── Error handling ───────────────────────────────────────────────────────
|
||||
|
||||
function handleKvarkError(err: unknown, operation: 'search' | 'ask' | 'feedback' | 'action'): string {
|
||||
if (!(err instanceof Error)) {
|
||||
return 'KVARK encountered an unexpected error. Try again or use workspace memory.';
|
||||
}
|
||||
|
||||
switch (err.name) {
|
||||
case 'KvarkUnavailableError':
|
||||
return 'KVARK is not reachable. Using workspace memory only. Configure KVARK connection in Settings.';
|
||||
|
||||
case 'KvarkAuthError':
|
||||
return 'KVARK authentication failed. Check KVARK credentials in Settings.';
|
||||
|
||||
case 'KvarkNotImplementedError':
|
||||
if (operation === 'ask') {
|
||||
return 'Document Q&A is not yet available on this KVARK instance. Use kvark_search to find relevant documents instead.';
|
||||
}
|
||||
if (operation === 'feedback') {
|
||||
return 'Feedback is not yet available on this KVARK instance. This is non-blocking — continue normally.';
|
||||
}
|
||||
if (operation === 'action') {
|
||||
return 'Governed actions are not yet available on this KVARK instance. The action was not executed.';
|
||||
}
|
||||
return 'This KVARK feature is not yet available.';
|
||||
|
||||
case 'KvarkNotFoundError':
|
||||
if (operation === 'ask') {
|
||||
return 'Document not found. The document may have been removed or the ID may be incorrect.';
|
||||
}
|
||||
return 'The requested resource was not found in KVARK.';
|
||||
|
||||
case 'KvarkServerError':
|
||||
return `KVARK server error: ${err.message}. Try again in a moment.`;
|
||||
|
||||
default:
|
||||
return `KVARK error: ${err.message}`;
|
||||
}
|
||||
}
|
||||
@@ -42,24 +42,6 @@ export function formatCombinedResult(result: CombinedRetrievalResult, hasWorkspa
|
||||
}
|
||||
}
|
||||
|
||||
// KVARK results
|
||||
if (result.kvarkResults.length > 0) {
|
||||
const header = '## Enterprise Knowledge (KVARK)';
|
||||
// KVARK results: score only, no frame_type/importance
|
||||
const entries = result.kvarkResults.map(r => formatResultEntry(r, false)).join('\n');
|
||||
sections.push(`${header}\n${entries}`);
|
||||
}
|
||||
|
||||
// Source conflict notice
|
||||
if (result.hasConflict && result.conflictNote) {
|
||||
sections.push(`## Source Conflict\n${result.conflictNote}\nReview both sources carefully and note which is more recent or authoritative.`);
|
||||
}
|
||||
|
||||
// KVARK error notice
|
||||
if (result.kvarkError && result.kvarkAvailable) {
|
||||
sections.push(`> Enterprise search encountered an error: ${result.kvarkError}\n> Results shown are from local memory only.`);
|
||||
}
|
||||
|
||||
if (sections.length === 0) {
|
||||
return 'No relevant memories found.';
|
||||
}
|
||||
|
||||
@@ -57,13 +57,10 @@ export interface SkillToolsDeps {
|
||||
/**
|
||||
* Skills 2.0 gap E: promotion infrastructure. Each callback is optional.
|
||||
* - getWorkspaceId / getTeamId resolve scope dirs dynamically at tool-call time.
|
||||
* - hasTeamSkillLibrary / isEnterprise gate tier-restricted scopes.
|
||||
* - improvementSignals records skill_promotion signals on successful moves.
|
||||
*/
|
||||
getWorkspaceId?: () => string | null;
|
||||
getTeamId?: () => string | null;
|
||||
hasTeamSkillLibrary?: () => boolean;
|
||||
isEnterprise?: () => boolean;
|
||||
improvementSignals?: ImprovementSignalStore;
|
||||
/**
|
||||
* Skills 2.0 gap A: session-message accessor for auto-extracting skills
|
||||
@@ -668,14 +665,13 @@ Only use this after acquire_capability has identified a specific installable can
|
||||
},
|
||||
|
||||
// Skills 2.0 gap E: promote_skill — move a skill up one scope rung.
|
||||
// personal → workspace → team → enterprise. Enforces one-step-at-a-time,
|
||||
// tier gates, and records a skill_promotion improvement signal on success.
|
||||
// personal → workspace. Enforces one-step-at-a-time and records a
|
||||
// skill_promotion improvement signal on success.
|
||||
{
|
||||
name: 'promote_skill',
|
||||
description:
|
||||
'Promote an installed skill one scope up (personal → workspace → team → enterprise). '
|
||||
+ 'Team scope requires the teamSkillLibrary capability (TEAMS or ENTERPRISE tier). '
|
||||
+ 'Enterprise scope requires ENTERPRISE tier. '
|
||||
'Promote an installed skill one scope up (personal → workspace). '
|
||||
+ 'Team and enterprise scopes are not available in this edition. '
|
||||
+ 'The file is moved to the appropriate directory, frontmatter is rewritten '
|
||||
+ '(scope + promoted_from history), and a skill_promotion signal is recorded.',
|
||||
parameters: {
|
||||
@@ -746,20 +742,13 @@ Only use this after acquire_capability has identified a specific installable can
|
||||
);
|
||||
}
|
||||
|
||||
// 4. Tier + context gating
|
||||
// 4. Context gating. Team and enterprise skill libraries belong to
|
||||
// team mode, which this edition does not ship.
|
||||
if (target === 'workspace' && !workspaceId) {
|
||||
return `Cannot promote to workspace scope: no active workspace. Switch to a workspace first.`;
|
||||
}
|
||||
if (target === 'team') {
|
||||
if (!deps.hasTeamSkillLibrary?.()) {
|
||||
return `Cannot promote to team scope: your plan does not include the team skill library. Upgrade to TEAMS or ENTERPRISE.`;
|
||||
}
|
||||
if (!teamId) {
|
||||
return `Cannot promote to team scope: this workspace is not linked to a team.`;
|
||||
}
|
||||
}
|
||||
if (target === 'enterprise' && !deps.isEnterprise?.()) {
|
||||
return `Cannot promote to enterprise scope: requires ENTERPRISE tier. Contact sales for KVARK.`;
|
||||
if (target === 'team' || target === 'enterprise') {
|
||||
return `Cannot promote to ${target} scope: team and enterprise skill libraries are not available in this edition.`;
|
||||
}
|
||||
|
||||
// 5. Resolve destination dir + path
|
||||
@@ -818,8 +807,7 @@ Only use this after acquire_capability has identified a specific installable can
|
||||
+ `- Promotion history: ${updatedFrontmatter.promoted_from!.join(' → ')} → ${target}\n`
|
||||
+ `- Signal recorded: skill_promotion\n\n`
|
||||
+ `The skill is available immediately at the new scope. Agents in other `
|
||||
+ `workspaces${target === 'team' ? ' on this team' : target === 'enterprise' ? ' across the enterprise' : ''} `
|
||||
+ `will pick it up on their next skill reload.`
|
||||
+ `sessions will pick it up on their next skill reload.`
|
||||
);
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1,25 +1,17 @@
|
||||
/**
|
||||
* Combined Retrieval — B1 tests.
|
||||
* Combined Retrieval — merge engine tests.
|
||||
*
|
||||
* Tests the merge engine in isolation. All dependencies are mocked:
|
||||
* - MemorySearchLike (workspace + personal HybridSearch)
|
||||
* - KvarkClientLike (KVARK HTTP client)
|
||||
*
|
||||
* No server, no vault, no DB, no wiring.
|
||||
* Tests the merge engine in isolation. MemorySearchLike (workspace + personal
|
||||
* HybridSearch) is mocked. No server, no vault, no DB, no wiring.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import {
|
||||
CombinedRetrieval,
|
||||
mapMemoryResult,
|
||||
mapKvarkResult,
|
||||
hasSufficientLocalCoverage,
|
||||
shouldQueryKvark,
|
||||
type MemorySearchLike,
|
||||
type MemorySearchResultLike,
|
||||
type CombinedResult,
|
||||
} from '../src/combined-retrieval.js';
|
||||
import type { KvarkClientLike, KvarkSearchResponseLike } from '../src/kvark-tools.js';
|
||||
|
||||
// ── Factories ─────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -41,22 +33,6 @@ function makeSearchMock(results: MemorySearchResultLike[] = []): MemorySearchLik
|
||||
return { search: vi.fn(async () => results) };
|
||||
}
|
||||
|
||||
const KVARK_RESPONSE: KvarkSearchResponseLike = {
|
||||
results: [
|
||||
{ document_id: 42, title: 'Project Status Update', snippet: 'API review postponed.', score: 0.92, document_type: 'pdf' },
|
||||
{ document_id: 108, title: 'Q1 Budget', snippet: 'Engineering budget increased.', score: 0.87, document_type: 'spreadsheet' },
|
||||
],
|
||||
total: 8,
|
||||
query: 'project',
|
||||
};
|
||||
|
||||
function makeKvarkClient(overrides?: Partial<KvarkClientLike>): KvarkClientLike {
|
||||
return {
|
||||
search: overrides?.search ?? vi.fn(async () => KVARK_RESPONSE),
|
||||
askDocument: overrides?.askDocument ?? vi.fn(async () => ({ answer: '', sources: [] })),
|
||||
};
|
||||
}
|
||||
|
||||
// ── Helper unit tests ─────────────────────────────────────────────────────
|
||||
|
||||
describe('mapMemoryResult', () => {
|
||||
@@ -83,121 +59,34 @@ describe('mapMemoryResult', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('mapKvarkResult', () => {
|
||||
it('preserves attribution from parseSearchResults', () => {
|
||||
const structured = {
|
||||
content: 'API review postponed.',
|
||||
documentId: 42,
|
||||
title: 'Project Status Update',
|
||||
score: 0.92,
|
||||
documentType: 'pdf' as string | null,
|
||||
attribution: '[KVARK: pdf: Project Status Update]',
|
||||
};
|
||||
|
||||
const result = mapKvarkResult(structured);
|
||||
|
||||
expect(result.source).toBe('kvark');
|
||||
expect(result.attribution).toBe('[KVARK: pdf: Project Status Update]');
|
||||
expect(result.score).toBe(0.92);
|
||||
expect(result.metadata.documentId).toBe(42);
|
||||
expect(result.metadata.documentType).toBe('pdf');
|
||||
});
|
||||
});
|
||||
|
||||
describe('hasSufficientLocalCoverage', () => {
|
||||
it('returns true when 3+ results score >= 0.7', () => {
|
||||
const results: CombinedResult[] = [
|
||||
{ content: '', source: 'workspace', attribution: '', score: 0.9, metadata: {} },
|
||||
{ content: '', source: 'workspace', attribution: '', score: 0.8, metadata: {} },
|
||||
{ content: '', source: 'personal', attribution: '', score: 0.7, metadata: {} },
|
||||
];
|
||||
expect(hasSufficientLocalCoverage(results)).toBe(true);
|
||||
});
|
||||
|
||||
it('returns false when fewer than 3 results score >= 0.7', () => {
|
||||
const results: CombinedResult[] = [
|
||||
{ content: '', source: 'workspace', attribution: '', score: 0.9, metadata: {} },
|
||||
{ content: '', source: 'workspace', attribution: '', score: 0.8, metadata: {} },
|
||||
{ content: '', source: 'personal', attribution: '', score: 0.5, metadata: {} },
|
||||
];
|
||||
expect(hasSufficientLocalCoverage(results)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false for empty results', () => {
|
||||
expect(hasSufficientLocalCoverage([])).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('shouldQueryKvark', () => {
|
||||
const weakLocal: CombinedResult[] = [
|
||||
{ content: '', source: 'workspace', attribution: '', score: 0.3, metadata: {} },
|
||||
];
|
||||
|
||||
it('returns false when kvarkClient is null', () => {
|
||||
expect(shouldQueryKvark(null, 'all', weakLocal)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false when scope is personal', () => {
|
||||
expect(shouldQueryKvark(makeKvarkClient(), 'personal', weakLocal)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false when scope is workspace', () => {
|
||||
expect(shouldQueryKvark(makeKvarkClient(), 'workspace', weakLocal)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false when local coverage is sufficient', () => {
|
||||
const strong: CombinedResult[] = [
|
||||
{ content: '', source: 'workspace', attribution: '', score: 0.9, metadata: {} },
|
||||
{ content: '', source: 'workspace', attribution: '', score: 0.8, metadata: {} },
|
||||
{ content: '', source: 'personal', attribution: '', score: 0.75, metadata: {} },
|
||||
];
|
||||
expect(shouldQueryKvark(makeKvarkClient(), 'all', strong)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns true when client exists, scope=all, and local coverage insufficient', () => {
|
||||
expect(shouldQueryKvark(makeKvarkClient(), 'all', weakLocal)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ── CombinedRetrieval class tests ─────────────────────────────────────────
|
||||
|
||||
describe('CombinedRetrieval', () => {
|
||||
it('returns workspace + personal results when kvarkClient is null', async () => {
|
||||
it('returns workspace + personal results', async () => {
|
||||
const wsResults = [makeMemoryResult({ id: 1, content: 'ws fact', score: 0.9 })];
|
||||
const pResults = [makeMemoryResult({ id: 2, content: 'personal fact', score: 0.8 })];
|
||||
|
||||
const cr = new CombinedRetrieval({
|
||||
workspaceSearch: makeSearchMock(wsResults),
|
||||
personalSearch: makeSearchMock(pResults),
|
||||
kvarkClient: null,
|
||||
});
|
||||
|
||||
const result = await cr.search('test');
|
||||
|
||||
expect(result.workspaceResults).toHaveLength(1);
|
||||
expect(result.personalResults).toHaveLength(1);
|
||||
expect(result.kvarkResults).toHaveLength(0);
|
||||
expect(result.kvarkAvailable).toBe(false);
|
||||
expect(result.kvarkSkipped).toBe(false); // not available, so not "skipped"
|
||||
expect(result.kvarkError).toBeUndefined();
|
||||
expect(result.query).toBe('test');
|
||||
expect(result.workspaceResults.map(r => r.content)).toEqual(['ws fact']);
|
||||
expect(result.personalResults.map(r => r.content)).toEqual(['personal fact']);
|
||||
});
|
||||
|
||||
it('searches only personal memory when scope=personal', async () => {
|
||||
const wsMock = makeSearchMock([makeMemoryResult({ id: 1 })]);
|
||||
const pMock = makeSearchMock([makeMemoryResult({ id: 2, content: 'personal only' })]);
|
||||
|
||||
const cr = new CombinedRetrieval({
|
||||
workspaceSearch: wsMock,
|
||||
personalSearch: pMock,
|
||||
kvarkClient: makeKvarkClient(),
|
||||
});
|
||||
|
||||
const cr = new CombinedRetrieval({ workspaceSearch: wsMock, personalSearch: pMock });
|
||||
const result = await cr.search('test', { scope: 'personal' });
|
||||
|
||||
expect(result.workspaceResults).toHaveLength(0);
|
||||
expect(result.personalResults).toHaveLength(1);
|
||||
expect(result.kvarkResults).toHaveLength(0);
|
||||
expect(result.kvarkSkipped).toBe(true);
|
||||
expect(wsMock.search).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -205,173 +94,57 @@ describe('CombinedRetrieval', () => {
|
||||
const wsMock = makeSearchMock([makeMemoryResult({ id: 1, content: 'ws only' })]);
|
||||
const pMock = makeSearchMock([makeMemoryResult({ id: 2 })]);
|
||||
|
||||
const cr = new CombinedRetrieval({
|
||||
workspaceSearch: wsMock,
|
||||
personalSearch: pMock,
|
||||
kvarkClient: makeKvarkClient(),
|
||||
});
|
||||
|
||||
const cr = new CombinedRetrieval({ workspaceSearch: wsMock, personalSearch: pMock });
|
||||
const result = await cr.search('test', { scope: 'workspace' });
|
||||
|
||||
expect(result.workspaceResults).toHaveLength(1);
|
||||
expect(result.personalResults).toHaveLength(0);
|
||||
expect(result.kvarkResults).toHaveLength(0);
|
||||
expect(result.kvarkSkipped).toBe(true);
|
||||
expect(pMock.search).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('calls KVARK when local results are insufficient', async () => {
|
||||
const searchFn = vi.fn(async () => KVARK_RESPONSE);
|
||||
const cr = new CombinedRetrieval({
|
||||
workspaceSearch: makeSearchMock([makeMemoryResult({ score: 0.3 })]),
|
||||
personalSearch: makeSearchMock([]),
|
||||
kvarkClient: makeKvarkClient({ search: searchFn }),
|
||||
});
|
||||
|
||||
const result = await cr.search('project');
|
||||
|
||||
expect(searchFn).toHaveBeenCalledWith('project', { limit: 10 });
|
||||
expect(result.kvarkResults).toHaveLength(2);
|
||||
expect(result.kvarkResults[0].source).toBe('kvark');
|
||||
expect(result.kvarkResults[0].attribution).toBe('[KVARK: pdf: Project Status Update]');
|
||||
expect(result.kvarkResults[1].attribution).toBe('[KVARK: spreadsheet: Q1 Budget]');
|
||||
expect(result.kvarkAvailable).toBe(true);
|
||||
expect(result.kvarkSkipped).toBe(false);
|
||||
});
|
||||
|
||||
it('skips KVARK when local results are sufficient', async () => {
|
||||
const searchFn = vi.fn(async () => KVARK_RESPONSE);
|
||||
const strongResults = [
|
||||
makeMemoryResult({ id: 1, score: 0.9 }),
|
||||
makeMemoryResult({ id: 2, score: 0.85 }),
|
||||
makeMemoryResult({ id: 3, score: 0.75 }),
|
||||
];
|
||||
|
||||
const cr = new CombinedRetrieval({
|
||||
workspaceSearch: makeSearchMock(strongResults),
|
||||
personalSearch: makeSearchMock([]),
|
||||
kvarkClient: makeKvarkClient({ search: searchFn }),
|
||||
});
|
||||
|
||||
const result = await cr.search('test');
|
||||
|
||||
expect(searchFn).not.toHaveBeenCalled();
|
||||
expect(result.kvarkResults).toHaveLength(0);
|
||||
expect(result.kvarkAvailable).toBe(true);
|
||||
expect(result.kvarkSkipped).toBe(true);
|
||||
});
|
||||
|
||||
it('degrades gracefully when KVARK throws an Error', async () => {
|
||||
const searchFn = vi.fn(async () => { throw new Error('KVARK is down'); });
|
||||
|
||||
const cr = new CombinedRetrieval({
|
||||
workspaceSearch: makeSearchMock([makeMemoryResult({ id: 1, score: 0.4 })]),
|
||||
personalSearch: makeSearchMock([makeMemoryResult({ id: 2, score: 0.3 })]),
|
||||
kvarkClient: makeKvarkClient({ search: searchFn }),
|
||||
});
|
||||
|
||||
const result = await cr.search('test');
|
||||
|
||||
expect(result.workspaceResults).toHaveLength(1);
|
||||
expect(result.personalResults).toHaveLength(1);
|
||||
expect(result.kvarkResults).toHaveLength(0);
|
||||
expect(result.kvarkError).toBe('KVARK is down');
|
||||
expect(result.kvarkAvailable).toBe(true);
|
||||
expect(result.kvarkSkipped).toBe(false);
|
||||
});
|
||||
|
||||
it('captures non-Error throws from KVARK as generic message', async () => {
|
||||
const searchFn = vi.fn(async () => { throw 'string error'; });
|
||||
|
||||
const cr = new CombinedRetrieval({
|
||||
workspaceSearch: makeSearchMock([]),
|
||||
personalSearch: makeSearchMock([]),
|
||||
kvarkClient: makeKvarkClient({ search: searchFn }),
|
||||
});
|
||||
|
||||
const result = await cr.search('test');
|
||||
|
||||
expect(result.kvarkError).toBe('Unknown KVARK error');
|
||||
expect(result.kvarkResults).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('works correctly when no workspace search is available', async () => {
|
||||
const cr = new CombinedRetrieval({
|
||||
workspaceSearch: null,
|
||||
personalSearch: makeSearchMock([makeMemoryResult({ id: 1, content: 'personal fact', score: 0.6 })]),
|
||||
kvarkClient: makeKvarkClient(),
|
||||
});
|
||||
|
||||
const result = await cr.search('test');
|
||||
|
||||
expect(result.workspaceResults).toHaveLength(0);
|
||||
expect(result.personalResults).toHaveLength(1);
|
||||
expect(result.kvarkResults).toHaveLength(2);
|
||||
expect(result.kvarkAvailable).toBe(true);
|
||||
expect(result.kvarkSkipped).toBe(false);
|
||||
});
|
||||
|
||||
it('passes limit and profile through to memory search', async () => {
|
||||
const wsMock = makeSearchMock([]);
|
||||
const pMock = makeSearchMock([]);
|
||||
|
||||
const cr = new CombinedRetrieval({
|
||||
workspaceSearch: wsMock,
|
||||
personalSearch: pMock,
|
||||
kvarkClient: null,
|
||||
});
|
||||
|
||||
const cr = new CombinedRetrieval({ workspaceSearch: wsMock, personalSearch: pMock });
|
||||
await cr.search('test', { limit: 5, profile: 'recent' });
|
||||
|
||||
expect(wsMock.search).toHaveBeenCalledWith('test', { limit: 5, profile: 'recent' });
|
||||
expect(pMock.search).toHaveBeenCalledWith('test', { limit: 5, profile: 'recent' });
|
||||
});
|
||||
|
||||
it('passes limit to KVARK client search', async () => {
|
||||
const searchFn = vi.fn(async () => KVARK_RESPONSE);
|
||||
|
||||
const cr = new CombinedRetrieval({
|
||||
workspaceSearch: makeSearchMock([]),
|
||||
personalSearch: makeSearchMock([]),
|
||||
kvarkClient: makeKvarkClient({ search: searchFn }),
|
||||
});
|
||||
|
||||
await cr.search('query', { limit: 7 });
|
||||
|
||||
expect(searchFn).toHaveBeenCalledWith('query', { limit: 7 });
|
||||
});
|
||||
|
||||
it('uses sensible defaults (limit=10, profile=balanced, scope=all)', async () => {
|
||||
const wsMock = makeSearchMock([]);
|
||||
const pMock = makeSearchMock([]);
|
||||
|
||||
const cr = new CombinedRetrieval({
|
||||
workspaceSearch: wsMock,
|
||||
personalSearch: pMock,
|
||||
kvarkClient: null,
|
||||
});
|
||||
|
||||
const cr = new CombinedRetrieval({ workspaceSearch: wsMock, personalSearch: pMock });
|
||||
await cr.search('test');
|
||||
|
||||
expect(wsMock.search).toHaveBeenCalledWith('test', { limit: 10, profile: 'balanced' });
|
||||
expect(pMock.search).toHaveBeenCalledWith('test', { limit: 10, profile: 'balanced' });
|
||||
});
|
||||
|
||||
it('handles KVARK returning zero results without error', async () => {
|
||||
const emptyResponse: KvarkSearchResponseLike = { results: [], total: 0, query: 'nothing' };
|
||||
const searchFn = vi.fn(async () => emptyResponse);
|
||||
|
||||
it('returns empty lists when nothing matches', async () => {
|
||||
const cr = new CombinedRetrieval({
|
||||
workspaceSearch: makeSearchMock([]),
|
||||
personalSearch: makeSearchMock([]),
|
||||
kvarkClient: makeKvarkClient({ search: searchFn }),
|
||||
});
|
||||
|
||||
const result = await cr.search('nothing');
|
||||
|
||||
expect(result.kvarkResults).toHaveLength(0);
|
||||
expect(result.kvarkAvailable).toBe(true);
|
||||
expect(result.kvarkSkipped).toBe(false);
|
||||
expect(result.kvarkError).toBeUndefined();
|
||||
expect(result.workspaceResults).toHaveLength(0);
|
||||
expect(result.personalResults).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,193 +0,0 @@
|
||||
/**
|
||||
* Skills 2.0 gap H — compliance report PDF generator.
|
||||
*
|
||||
* Tests the doc-definition builder (buildComplianceDocDefinition) without
|
||||
* actually rendering a PDF — that would require pdfmake font bundles that
|
||||
* inflate test time and CI brittleness. The render function itself is a
|
||||
* thin pdfmake wrapper; if the doc def is structurally correct and
|
||||
* pdfmake has its own test coverage upstream, the rendered artifact is
|
||||
* trustworthy.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import type { AuditReport } from '@waggle/core';
|
||||
import { buildComplianceDocDefinition } from '../src/compliance-pdf.js';
|
||||
|
||||
function sampleReport(overrides: Partial<AuditReport> = {}): AuditReport {
|
||||
return {
|
||||
report: {
|
||||
version: '1.0',
|
||||
generatedAt: '2026-04-15T12:00:00.000Z',
|
||||
period: { from: '2026-01-01T00:00:00.000Z', to: '2026-04-15T00:00:00.000Z' },
|
||||
generatedBy: 'Waggle OS',
|
||||
},
|
||||
workspace: {
|
||||
id: 'ws-alpha',
|
||||
name: 'Alpha Corp Legal',
|
||||
riskLevel: 'high-risk',
|
||||
riskClassifiedAt: '2026-01-01T00:00:00.000Z',
|
||||
},
|
||||
complianceStatus: {
|
||||
overall: 'compliant',
|
||||
art12Logging: { status: 'compliant', detail: 'All interactions logged', totalInteractions: 1247 },
|
||||
art14Oversight: { status: 'compliant', detail: '83% approval rate', humanActions: 47, approvalRate: 0.83 },
|
||||
art19Retention: { status: 'warning', detail: 'Oldest log near retention limit', oldestLogDate: '2025-04-15T00:00:00.000Z', retentionDays: 365 },
|
||||
art26Monitoring: { status: 'compliant', detail: 'Active monitors: drift, bias, throughput', activeMonitors: ['drift', 'bias', 'throughput'] },
|
||||
art50Transparency: { status: 'compliant', detail: 'Model disclosure active', modelsDisclosed: true },
|
||||
},
|
||||
modelInventory: [
|
||||
{ model: 'claude-sonnet-4-6', provider: 'anthropic', calls: 500, inputTokens: 1_000_000, outputTokens: 200_000, costUsd: 3.5 },
|
||||
{ model: 'claude-haiku-4-5', provider: 'anthropic', calls: 747, inputTokens: 500_000, outputTokens: 80_000, costUsd: 0.42 },
|
||||
],
|
||||
humanOversightLog: [
|
||||
{ timestamp: '2026-04-10T09:15:00.000Z', action: 'approved', tool: 'save_memory', detail: 'Client contract summary — confirmed' },
|
||||
{ timestamp: '2026-04-11T14:22:00.000Z', action: 'denied', tool: 'send_email', detail: 'Draft to opposing counsel — halted' },
|
||||
],
|
||||
harvestProvenance: [
|
||||
{ source: 'Claude Code exports', importedAt: '2026-03-01T00:00:00.000Z', itemsImported: 156, framesCreated: 89 },
|
||||
],
|
||||
interactionCount: 1247,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('buildComplianceDocDefinition — gap H', () => {
|
||||
it('produces a valid pdfmake doc definition with key metadata', () => {
|
||||
const doc = buildComplianceDocDefinition(sampleReport());
|
||||
expect(doc.info?.title).toContain('Alpha Corp Legal');
|
||||
expect(doc.info?.creator).toContain('Waggle');
|
||||
expect(doc.pageSize).toBe('A4');
|
||||
expect(doc.pageMargins).toEqual([50, 60, 50, 60]);
|
||||
});
|
||||
|
||||
it('includes the workspace name and risk level on the cover', () => {
|
||||
const doc = buildComplianceDocDefinition(sampleReport());
|
||||
const flat = JSON.stringify(doc.content);
|
||||
expect(flat).toContain('Alpha Corp Legal');
|
||||
expect(flat).toContain('HIGH-RISK');
|
||||
expect(flat).toContain('AI ACT COMPLIANCE AUDIT');
|
||||
});
|
||||
|
||||
it('falls back to "Personal Mind" when workspace is null', () => {
|
||||
const doc = buildComplianceDocDefinition(sampleReport({ workspace: null }));
|
||||
const flat = JSON.stringify(doc.content);
|
||||
expect(flat).toContain('Personal Mind');
|
||||
expect(flat).toContain('MINIMAL'); // default risk fallback
|
||||
});
|
||||
|
||||
it('renders a row per article status with matching badges', () => {
|
||||
const doc = buildComplianceDocDefinition(sampleReport());
|
||||
const flat = JSON.stringify(doc.content);
|
||||
// All 5 article labels appear
|
||||
expect(flat).toContain('Art. 12');
|
||||
expect(flat).toContain('Art. 14');
|
||||
expect(flat).toContain('Art. 19');
|
||||
expect(flat).toContain('Art. 26');
|
||||
expect(flat).toContain('Art. 50');
|
||||
// Status badges appear
|
||||
expect(flat).toContain('COMPLIANT');
|
||||
expect(flat).toContain('WARNING');
|
||||
});
|
||||
|
||||
it('includes a model inventory total row', () => {
|
||||
const doc = buildComplianceDocDefinition(sampleReport());
|
||||
const flat = JSON.stringify(doc.content);
|
||||
expect(flat).toContain('claude-sonnet-4-6');
|
||||
expect(flat).toContain('claude-haiku-4-5');
|
||||
// Total calls = 500 + 747 = 1,247
|
||||
expect(flat).toContain('1,247');
|
||||
expect(flat).toContain('TOTAL');
|
||||
});
|
||||
|
||||
it('shows an empty-state message for empty model inventory', () => {
|
||||
const doc = buildComplianceDocDefinition(sampleReport({ modelInventory: [] }));
|
||||
const flat = JSON.stringify(doc.content);
|
||||
expect(flat).toContain('No model calls recorded');
|
||||
});
|
||||
|
||||
it('shows an empty-state message for empty oversight log', () => {
|
||||
const doc = buildComplianceDocDefinition(sampleReport({ humanOversightLog: [] }));
|
||||
const flat = JSON.stringify(doc.content);
|
||||
expect(flat).toContain('No human oversight events');
|
||||
});
|
||||
|
||||
it('caps oversight log display at 50 most-recent entries with a footer', () => {
|
||||
const log = Array.from({ length: 120 }, (_, i) => ({
|
||||
timestamp: `2026-04-${String(i + 1).padStart(2, '0')}T00:00:00.000Z`,
|
||||
action: 'approved' as const,
|
||||
tool: 'save_memory',
|
||||
detail: `Event ${i}`,
|
||||
}));
|
||||
const doc = buildComplianceDocDefinition(sampleReport({ humanOversightLog: log }));
|
||||
const flat = JSON.stringify(doc.content);
|
||||
expect(flat).toContain('Showing last 50 of 120 events');
|
||||
});
|
||||
|
||||
it('empty provenance produces an empty-state message', () => {
|
||||
const doc = buildComplianceDocDefinition(sampleReport({ harvestProvenance: [] }));
|
||||
const flat = JSON.stringify(doc.content);
|
||||
expect(flat).toContain('No harvest provenance data');
|
||||
});
|
||||
|
||||
it('summary lists totals derived from report fields', () => {
|
||||
const doc = buildComplianceDocDefinition(sampleReport());
|
||||
const flat = JSON.stringify(doc.content);
|
||||
expect(flat).toContain('Total interactions logged: 1,247');
|
||||
expect(flat).toContain('Models in inventory: 2');
|
||||
expect(flat).toContain('Oversight events: 2');
|
||||
expect(flat).toContain('Harvest sources: 1');
|
||||
});
|
||||
|
||||
it('styles contain Hive DS honey color', () => {
|
||||
const doc = buildComplianceDocDefinition(sampleReport());
|
||||
const styles = JSON.stringify(doc.styles);
|
||||
expect(styles).toContain('#E5A000'); // HIVE_HONEY
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildComplianceDocDefinition — M-03 template overrides', () => {
|
||||
it('overrides workspace name with templateOrgName in title + header + cover', () => {
|
||||
const doc = buildComplianceDocDefinition(sampleReport(), { orgName: 'KVARK Sovereign Cloud' });
|
||||
expect(doc.info?.title).toContain('KVARK Sovereign Cloud');
|
||||
expect(doc.info?.title).not.toContain('Alpha Corp Legal');
|
||||
const flat = JSON.stringify(doc.content);
|
||||
expect(flat).toContain('KVARK Sovereign Cloud');
|
||||
});
|
||||
|
||||
it('overrides workspace risk level with templateRiskClassification', () => {
|
||||
const doc = buildComplianceDocDefinition(sampleReport(), { riskClassification: 'minimal' });
|
||||
const flat = JSON.stringify(doc.content);
|
||||
expect(flat).toContain('MINIMAL');
|
||||
// Original workspace risk (HIGH-RISK) should no longer appear on the cover
|
||||
// since the cover only renders the override.
|
||||
expect(flat).not.toContain('HIGH-RISK');
|
||||
});
|
||||
|
||||
it('appends footerText to the rendered footer', () => {
|
||||
const doc = buildComplianceDocDefinition(sampleReport(), {
|
||||
footerText: 'Confidential — board only',
|
||||
});
|
||||
// pdfmake `footer` is a function (currentPage, pageCount) => Content.
|
||||
// Invoke it to get the rendered cell tree and stringify that.
|
||||
const footerFn = doc.footer as ((currentPage: number, pageCount: number) => unknown) | undefined;
|
||||
expect(typeof footerFn).toBe('function');
|
||||
const footerContent = JSON.stringify(footerFn!(1, 1));
|
||||
expect(footerContent).toContain('Confidential — board only');
|
||||
});
|
||||
|
||||
it('blank overrides fall back to workspace defaults', () => {
|
||||
const doc = buildComplianceDocDefinition(sampleReport(), {
|
||||
orgName: '',
|
||||
footerText: '',
|
||||
riskClassification: null,
|
||||
});
|
||||
const flat = JSON.stringify(doc.content);
|
||||
expect(flat).toContain('Alpha Corp Legal'); // workspace name still used
|
||||
expect(flat).toContain('HIGH-RISK'); // workspace risk still used
|
||||
});
|
||||
|
||||
it('ignores undefined overrides (no-op call path)', () => {
|
||||
const baseline = buildComplianceDocDefinition(sampleReport());
|
||||
const overridden = buildComplianceDocDefinition(sampleReport(), undefined);
|
||||
expect(JSON.stringify(overridden.info)).toBe(JSON.stringify(baseline.info));
|
||||
});
|
||||
});
|
||||
@@ -1,196 +0,0 @@
|
||||
/**
|
||||
* Conflict detection tests — post-Milestone-B trust slice.
|
||||
*
|
||||
* Tests the detectConflict heuristic and its integration with
|
||||
* CombinedRetrieval and formatCombinedResult.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import {
|
||||
detectConflict,
|
||||
CombinedRetrieval,
|
||||
type CombinedResult,
|
||||
type MemorySearchLike,
|
||||
type MemorySearchResultLike,
|
||||
} from '../src/combined-retrieval.js';
|
||||
import { formatCombinedResult } from '../src/tools.js';
|
||||
import type { KvarkClientLike, KvarkSearchResponseLike } from '../src/kvark-tools.js';
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
function makeResult(source: 'workspace' | 'kvark', content: string, score: number): CombinedResult {
|
||||
return {
|
||||
content,
|
||||
source,
|
||||
attribution: source === 'workspace' ? '[workspace memory]' : '[KVARK: doc]',
|
||||
score,
|
||||
metadata: {},
|
||||
};
|
||||
}
|
||||
|
||||
function makeMemoryResult(id: number, content: string, score: number): MemorySearchResultLike {
|
||||
return { frame: { id, content, frame_type: 'fact', importance: 'normal' }, finalScore: score };
|
||||
}
|
||||
|
||||
function makeSearch(results: MemorySearchResultLike[]): MemorySearchLike {
|
||||
return { search: vi.fn().mockResolvedValue(results) };
|
||||
}
|
||||
|
||||
function makeKvarkClient(results: Array<{ title: string; snippet: string; score: number }>): KvarkClientLike {
|
||||
const response: KvarkSearchResponseLike = {
|
||||
query: 'test',
|
||||
total: results.length,
|
||||
results: results.map((r, i) => ({
|
||||
document_id: i + 1,
|
||||
title: r.title,
|
||||
snippet: r.snippet,
|
||||
score: r.score,
|
||||
document_type: null,
|
||||
})),
|
||||
};
|
||||
return {
|
||||
search: vi.fn().mockResolvedValue(response),
|
||||
askDocument: vi.fn().mockResolvedValue({ answer: '', sources: [] }),
|
||||
};
|
||||
}
|
||||
|
||||
// ── detectConflict unit tests ────────────────────────────────────────────
|
||||
|
||||
describe('detectConflict', () => {
|
||||
it('returns null when only workspace results are present', () => {
|
||||
const ws = [makeResult('workspace', 'project approved by board', 0.9)];
|
||||
expect(detectConflict(ws, [])).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null when only KVARK results are present', () => {
|
||||
const kvark = [makeResult('kvark', 'project cancelled per policy', 0.8)];
|
||||
expect(detectConflict([], kvark)).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null when both sources agree (both positive)', () => {
|
||||
const ws = [makeResult('workspace', 'The migration was approved last week', 0.85)];
|
||||
const kvark = [makeResult('kvark', 'Migration approved and confirmed by CTO', 0.9)];
|
||||
expect(detectConflict(ws, kvark)).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null when both sources agree (both negative)', () => {
|
||||
const ws = [makeResult('workspace', 'Feature was rejected in review', 0.8)];
|
||||
const kvark = [makeResult('kvark', 'Feature rejected — not aligned with roadmap', 0.85)];
|
||||
expect(detectConflict(ws, kvark)).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null when neither source has status language', () => {
|
||||
const ws = [makeResult('workspace', 'The project uses PostgreSQL for data storage', 0.9)];
|
||||
const kvark = [makeResult('kvark', 'Database architecture uses Oracle Enterprise', 0.85)];
|
||||
expect(detectConflict(ws, kvark)).toBeNull();
|
||||
});
|
||||
|
||||
it('flags conflict when workspace is positive and KVARK is negative', () => {
|
||||
const ws = [makeResult('workspace', 'We decided to use the new API and approved the integration', 0.9)];
|
||||
const kvark = [makeResult('kvark', 'API integration has been cancelled due to security review', 0.85)];
|
||||
const result = detectConflict(ws, kvark);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result).toContain('affirmative language');
|
||||
expect(result).toContain('contradictory language');
|
||||
expect(result).toContain('out of sync');
|
||||
});
|
||||
|
||||
it('flags conflict when workspace is negative and KVARK is positive', () => {
|
||||
const ws = [makeResult('workspace', 'The proposal was rejected by the committee', 0.8)];
|
||||
const kvark = [makeResult('kvark', 'Proposal approved and budget confirmed for Q2', 0.9)];
|
||||
const result = detectConflict(ws, kvark);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result).toContain('enterprise source may be more current');
|
||||
});
|
||||
|
||||
it('returns null when results are below score threshold', () => {
|
||||
const ws = [makeResult('workspace', 'project approved', 0.4)];
|
||||
const kvark = [makeResult('kvark', 'project cancelled', 0.5)];
|
||||
expect(detectConflict(ws, kvark)).toBeNull();
|
||||
});
|
||||
|
||||
it('handles mixed polarity within same source (neutral)', () => {
|
||||
const ws = [makeResult('workspace', 'Some features approved, others rejected during review', 0.8)];
|
||||
const kvark = [makeResult('kvark', 'Project cancelled after initial approval', 0.85)];
|
||||
// workspace has both positive AND negative => neutral => no conflict
|
||||
expect(detectConflict(ws, kvark)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ── Integration: CombinedRetrieval with conflict detection ──────────────
|
||||
|
||||
describe('CombinedRetrieval conflict integration', () => {
|
||||
it('sets hasConflict=false when KVARK is not called', async () => {
|
||||
const cr = new CombinedRetrieval({
|
||||
workspaceSearch: makeSearch([makeMemoryResult(1, 'approved by team', 0.9)]),
|
||||
personalSearch: makeSearch([]),
|
||||
kvarkClient: null,
|
||||
});
|
||||
const result = await cr.search('test');
|
||||
expect(result.hasConflict).toBe(false);
|
||||
expect(result.conflictNote).toBeUndefined();
|
||||
});
|
||||
|
||||
it('sets hasConflict=true when workspace and KVARK results conflict', async () => {
|
||||
const cr = new CombinedRetrieval({
|
||||
workspaceSearch: makeSearch([makeMemoryResult(1, 'The vendor was selected and approved', 0.85)]),
|
||||
personalSearch: makeSearch([]),
|
||||
kvarkClient: makeKvarkClient([
|
||||
{ title: 'Vendor Policy', snippet: 'Vendor agreement has been cancelled effective immediately', score: 0.9 },
|
||||
]),
|
||||
});
|
||||
const result = await cr.search('vendor status');
|
||||
expect(result.hasConflict).toBe(true);
|
||||
expect(result.conflictNote).toBeDefined();
|
||||
expect(result.conflictNote).toContain('out of sync');
|
||||
});
|
||||
|
||||
it('sets hasConflict=false when sources do not conflict', async () => {
|
||||
const cr = new CombinedRetrieval({
|
||||
workspaceSearch: makeSearch([makeMemoryResult(1, 'project status is active and healthy', 0.8)]),
|
||||
personalSearch: makeSearch([]),
|
||||
kvarkClient: makeKvarkClient([
|
||||
{ title: 'Status', snippet: 'Project confirmed active with full funding', score: 0.85 },
|
||||
]),
|
||||
});
|
||||
const result = await cr.search('project status');
|
||||
expect(result.hasConflict).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ── formatCombinedResult with conflict ──────────────────────────────────
|
||||
|
||||
describe('formatCombinedResult conflict rendering', () => {
|
||||
it('includes Source Conflict section when hasConflict is true', () => {
|
||||
const output = formatCombinedResult({
|
||||
query: 'test',
|
||||
workspaceResults: [makeResult('workspace', 'approved', 0.9)],
|
||||
personalResults: [],
|
||||
kvarkResults: [makeResult('kvark', 'cancelled', 0.85)],
|
||||
kvarkAvailable: true,
|
||||
kvarkSkipped: false,
|
||||
hasConflict: true,
|
||||
conflictNote: 'Sources may disagree.',
|
||||
}, true);
|
||||
|
||||
expect(output).toContain('## Source Conflict');
|
||||
expect(output).toContain('Sources may disagree.');
|
||||
expect(output).toContain('Review both sources carefully');
|
||||
});
|
||||
|
||||
it('omits Source Conflict section when hasConflict is false', () => {
|
||||
const output = formatCombinedResult({
|
||||
query: 'test',
|
||||
workspaceResults: [makeResult('workspace', 'some fact', 0.9)],
|
||||
personalResults: [],
|
||||
kvarkResults: [makeResult('kvark', 'some other fact', 0.85)],
|
||||
kvarkAvailable: true,
|
||||
kvarkSkipped: false,
|
||||
hasConflict: false,
|
||||
}, true);
|
||||
|
||||
expect(output).not.toContain('## Source Conflict');
|
||||
});
|
||||
});
|
||||
@@ -1,138 +0,0 @@
|
||||
/**
|
||||
* KVARK Pipeline Smoke - assembled path validation (Milestone E1).
|
||||
* Exercises real B1-B4 + conflict + C pipeline code.
|
||||
* Only KVARK HTTP boundary is mocked via KvarkClientLike.
|
||||
*/
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { CombinedRetrieval, detectConflict, type MemorySearchLike, type MemorySearchResultLike } from '../src/combined-retrieval.js';
|
||||
import { formatCombinedResult } from '../src/tools.js';
|
||||
import { createKvarkTools, type KvarkClientLike, type KvarkSearchResponseLike } from '../src/kvark-tools.js';
|
||||
|
||||
function memStub(r: Array<{ id: number; content: string; score: number; type?: string }>): MemorySearchLike {
|
||||
const m: MemorySearchResultLike[] = r.map(x => ({ frame: { id: x.id, content: x.content, frame_type: x.type ?? 'fact', importance: 'normal' }, finalScore: x.score }));
|
||||
return { search: vi.fn().mockResolvedValue(m) };
|
||||
}
|
||||
|
||||
function kStub(r: Array<{ id: number; title: string; snippet: string; score: number; type?: string }>): KvarkClientLike {
|
||||
const resp: KvarkSearchResponseLike = { query: 'q', total: r.length, results: r.map(x => ({ document_id: x.id, title: x.title, snippet: x.snippet, score: x.score, document_type: x.type ?? null })) };
|
||||
return { search: vi.fn().mockResolvedValue(resp), askDocument: vi.fn().mockResolvedValue({ answer: '', sources: [] }), feedback: vi.fn().mockResolvedValue({ ok: true }) };
|
||||
}
|
||||
|
||||
describe('Pipeline: happy path', () => {
|
||||
it('all sources produce formatted output with attribution', async () => {
|
||||
const cr = new CombinedRetrieval({
|
||||
workspaceSearch: memStub([{ id: 1, content: 'We use PostgreSQL', score: 0.75, type: 'decision' }]),
|
||||
personalSearch: memStub([{ id: 2, content: 'User prefers concise', score: 0.5 }]),
|
||||
kvarkClient: kStub([{ id: 42, title: 'ADR', snippet: 'PostgreSQL selected', score: 0.88, type: 'pdf' }]),
|
||||
});
|
||||
const r = await cr.search('db');
|
||||
const o = formatCombinedResult(r, true);
|
||||
expect(o).toContain('## Workspace Memory');
|
||||
expect(o).toContain('## Personal Memory');
|
||||
expect(o).toContain('## Enterprise Knowledge (KVARK)');
|
||||
expect(o).toContain('[workspace memory]');
|
||||
expect(o).toContain('[personal memory]');
|
||||
expect(o).toContain('[KVARK: pdf: ADR]');
|
||||
expect(o).not.toContain('## Source Conflict');
|
||||
expect(r.hasConflict).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Pipeline: conflict detection', () => {
|
||||
it('approved vs cancelled triggers conflict', async () => {
|
||||
const cr = new CombinedRetrieval({
|
||||
workspaceSearch: memStub([{ id: 1, content: 'Vendor approved and confirmed', score: 0.85 }]),
|
||||
personalSearch: memStub([]),
|
||||
kvarkClient: kStub([{ id: 99, title: 'Policy', snippet: 'Vendor cancelled due to compliance', score: 0.9 }]),
|
||||
});
|
||||
const r = await cr.search('vendor');
|
||||
expect(r.hasConflict).toBe(true);
|
||||
const o = formatCombinedResult(r, true);
|
||||
expect(o).toContain('## Source Conflict');
|
||||
expect(o).toContain('## Workspace Memory');
|
||||
expect(o).toContain('## Enterprise Knowledge');
|
||||
});
|
||||
|
||||
it('detectConflict consistent with CombinedRetrieval', async () => {
|
||||
const cr = new CombinedRetrieval({
|
||||
workspaceSearch: memStub([{ id: 1, content: 'Project rejected', score: 0.8 }]),
|
||||
personalSearch: memStub([]),
|
||||
kvarkClient: kStub([{ id: 50, title: 'Minutes', snippet: 'Project approved', score: 0.85 }]),
|
||||
});
|
||||
const r = await cr.search('status');
|
||||
const d = detectConflict(r.workspaceResults, r.kvarkResults);
|
||||
expect(r.hasConflict).toBe(d !== null);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Pipeline: KVARK skip', () => {
|
||||
it('strong local results skip KVARK', async () => {
|
||||
const k = kStub([{ id: 1, title: 'D', snippet: 't', score: 0.9 }]);
|
||||
const cr = new CombinedRetrieval({
|
||||
workspaceSearch: memStub([{ id: 1, content: 'A', score: 0.9 }, { id: 2, content: 'B', score: 0.85 }, { id: 3, content: 'C', score: 0.75 }]),
|
||||
personalSearch: memStub([]), kvarkClient: k,
|
||||
});
|
||||
const r = await cr.search('test');
|
||||
expect(r.kvarkSkipped).toBe(true);
|
||||
expect(k.search).not.toHaveBeenCalled();
|
||||
expect(formatCombinedResult(r, true)).not.toContain('Enterprise');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Pipeline: KVARK failure', () => {
|
||||
it('local results preserved on error', async () => {
|
||||
const cr = new CombinedRetrieval({
|
||||
workspaceSearch: memStub([{ id: 1, content: 'Local fact', score: 0.6 }]),
|
||||
personalSearch: memStub([{ id: 2, content: 'Note', score: 0.4 }]),
|
||||
kvarkClient: { search: vi.fn().mockRejectedValue(new Error('down')), askDocument: vi.fn() },
|
||||
});
|
||||
const r = await cr.search('x');
|
||||
const o = formatCombinedResult(r, true);
|
||||
expect(r.kvarkError).toBe('down');
|
||||
expect(r.hasConflict).toBe(false);
|
||||
expect(o).toContain('Local fact');
|
||||
expect(o).toContain('error');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Pipeline: feedback round-trip', () => {
|
||||
it('search doc IDs valid for feedback', async () => {
|
||||
const fb = vi.fn().mockResolvedValue({ ok: true });
|
||||
const k = kStub([{ id: 42, title: 'Q3', snippet: 'Rev up', score: 0.9, type: 'pdf' }]);
|
||||
k.feedback = fb;
|
||||
const cr = new CombinedRetrieval({ workspaceSearch: memStub([]), personalSearch: memStub([]), kvarkClient: k });
|
||||
const s = await cr.search('rev');
|
||||
const did = s.kvarkResults[0].metadata.documentId;
|
||||
expect(did).toBe(42);
|
||||
const t = createKvarkTools({ client: k }).find(x => x.name === 'kvark_feedback')!;
|
||||
const o = await t.execute({ document_id: did, query: 'rev', useful: true });
|
||||
expect(fb).toHaveBeenCalledWith(42, 'rev', true, undefined);
|
||||
expect(o).toContain('Feedback');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Pipeline: scope filtering', () => {
|
||||
it('personal skips workspace and KVARK', async () => {
|
||||
const w = memStub([{ id: 1, content: 'ws', score: 0.8 }]);
|
||||
const p = memStub([{ id: 2, content: 'pers', score: 0.7 }]);
|
||||
const k = kStub([{ id: 42, title: 'D', snippet: 'e', score: 0.9 }]);
|
||||
const cr = new CombinedRetrieval({ workspaceSearch: w, personalSearch: p, kvarkClient: k });
|
||||
const r = await cr.search('t', { scope: 'personal' });
|
||||
expect(r.workspaceResults).toHaveLength(0);
|
||||
expect(r.kvarkResults).toHaveLength(0);
|
||||
expect(w.search).not.toHaveBeenCalled();
|
||||
expect(k.search).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('workspace skips personal and KVARK', async () => {
|
||||
const w = memStub([{ id: 1, content: 'ws', score: 0.8 }]);
|
||||
const p = memStub([{ id: 2, content: 'pers', score: 0.7 }]);
|
||||
const k = kStub([{ id: 42, title: 'D', snippet: 'e', score: 0.9 }]);
|
||||
const cr = new CombinedRetrieval({ workspaceSearch: w, personalSearch: p, kvarkClient: k });
|
||||
const r = await cr.search('t', { scope: 'workspace' });
|
||||
expect(r.personalResults).toHaveLength(0);
|
||||
expect(r.kvarkResults).toHaveLength(0);
|
||||
expect(p.search).not.toHaveBeenCalled();
|
||||
expect(k.search).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,431 +0,0 @@
|
||||
/**
|
||||
* KVARK Agent Tools — tests with mocked KvarkClient.
|
||||
*
|
||||
* Tests mock the KvarkClient interface, NOT HTTP.
|
||||
* This validates tool behavior: output formatting, error handling, attribution.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import {
|
||||
createKvarkTools,
|
||||
parseSearchResults,
|
||||
type KvarkClientLike,
|
||||
type KvarkSearchResponseLike,
|
||||
type KvarkAskResponseLike,
|
||||
} from '../src/kvark-tools.js';
|
||||
|
||||
// ── Mock client factory ──────────────────────────────────────────────────
|
||||
|
||||
function mockClient(overrides?: Partial<KvarkClientLike>): KvarkClientLike {
|
||||
return {
|
||||
search: overrides?.search ?? vi.fn(async () => SEARCH_RESPONSE),
|
||||
askDocument: overrides?.askDocument ?? vi.fn(async () => ASK_RESPONSE),
|
||||
feedback: overrides?.feedback ?? vi.fn(async () => ({ ok: true })),
|
||||
action: overrides?.action ?? vi.fn(async () => ({ ok: true, data: { status: 'executed' as const, actionId: 'act_001', auditRef: 'aud_001' }, error: null })),
|
||||
};
|
||||
}
|
||||
|
||||
const SEARCH_RESPONSE: KvarkSearchResponseLike = {
|
||||
results: [
|
||||
{ document_id: 42, title: 'Project Status Update', snippet: 'API design review was postponed to next sprint due to unresolved auth decisions.', score: 0.92, document_type: 'pdf' },
|
||||
{ document_id: 108, title: 'Q1 Budget Analysis', snippet: 'Budget allocation for engineering increased by 15%.', score: 0.87, document_type: 'spreadsheet' },
|
||||
{ document_id: 215, title: 'Architecture Decision Records', snippet: 'Auth boundary decision pending review by security team.', score: 0.81, document_type: null },
|
||||
],
|
||||
total: 12,
|
||||
query: 'project status',
|
||||
};
|
||||
|
||||
const ASK_RESPONSE: KvarkAskResponseLike = {
|
||||
answer: 'The blocker is unresolved identity boundary design, which delayed the API review to next sprint.',
|
||||
sources: ['Project Status Update.pdf'],
|
||||
};
|
||||
|
||||
// ── Tests ────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('KVARK Agent Tools', () => {
|
||||
describe('kvark_search', () => {
|
||||
it('calls client.search with query and limit', async () => {
|
||||
const searchFn = vi.fn(async () => SEARCH_RESPONSE);
|
||||
const client = mockClient({ search: searchFn });
|
||||
const tools = createKvarkTools({ client });
|
||||
const tool = tools.find(t => t.name === 'kvark_search')!;
|
||||
|
||||
await tool.execute({ query: 'project status', limit: 5 });
|
||||
|
||||
expect(searchFn).toHaveBeenCalledWith('project status', { limit: 5 });
|
||||
});
|
||||
|
||||
it('formats search results with type, title, score, snippet, and ID', async () => {
|
||||
const client = mockClient();
|
||||
const tools = createKvarkTools({ client });
|
||||
const tool = tools.find(t => t.name === 'kvark_search')!;
|
||||
|
||||
const output = await tool.execute({ query: 'project status' });
|
||||
|
||||
expect(output).toContain('KVARK Search: "project status"');
|
||||
expect(output).toContain('3 of 12 results');
|
||||
expect(output).toContain('[pdf] Project Status Update');
|
||||
expect(output).toContain('score: 0.92');
|
||||
expect(output).toContain('ID: 42');
|
||||
expect(output).toContain('[spreadsheet] Q1 Budget');
|
||||
expect(output).toContain('[document] Architecture Decision Records'); // null type → [document]
|
||||
});
|
||||
|
||||
it('returns clear message on empty results', async () => {
|
||||
const client = mockClient({
|
||||
search: vi.fn(async () => ({ results: [], total: 0, query: 'nonexistent' })),
|
||||
});
|
||||
const tools = createKvarkTools({ client });
|
||||
const tool = tools.find(t => t.name === 'kvark_search')!;
|
||||
|
||||
const output = await tool.execute({ query: 'nonexistent' });
|
||||
|
||||
expect(output).toContain('no results found');
|
||||
});
|
||||
|
||||
it('returns graceful message when KVARK is unavailable', async () => {
|
||||
const err = new Error('KVARK unreachable');
|
||||
err.name = 'KvarkUnavailableError';
|
||||
const client = mockClient({ search: vi.fn(async () => { throw err; }) });
|
||||
const tools = createKvarkTools({ client });
|
||||
const tool = tools.find(t => t.name === 'kvark_search')!;
|
||||
|
||||
const output = await tool.execute({ query: 'test' });
|
||||
|
||||
expect(output).toContain('not reachable');
|
||||
expect(output).toContain('workspace memory');
|
||||
});
|
||||
|
||||
it('returns graceful message on auth failure', async () => {
|
||||
const err = new Error('Invalid token');
|
||||
err.name = 'KvarkAuthError';
|
||||
const client = mockClient({ search: vi.fn(async () => { throw err; }) });
|
||||
const tools = createKvarkTools({ client });
|
||||
const tool = tools.find(t => t.name === 'kvark_search')!;
|
||||
|
||||
const output = await tool.execute({ query: 'test' });
|
||||
|
||||
expect(output).toContain('authentication failed');
|
||||
});
|
||||
|
||||
it('defaults limit to 10 when not specified', async () => {
|
||||
const searchFn = vi.fn(async () => SEARCH_RESPONSE);
|
||||
const client = mockClient({ search: searchFn });
|
||||
const tools = createKvarkTools({ client });
|
||||
const tool = tools.find(t => t.name === 'kvark_search')!;
|
||||
|
||||
await tool.execute({ query: 'test' });
|
||||
|
||||
expect(searchFn).toHaveBeenCalledWith('test', { limit: 10 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('kvark_ask_document', () => {
|
||||
it('calls client.askDocument with document_id and question', async () => {
|
||||
const askFn = vi.fn(async () => ASK_RESPONSE);
|
||||
const client = mockClient({ askDocument: askFn });
|
||||
const tools = createKvarkTools({ client });
|
||||
const tool = tools.find(t => t.name === 'kvark_ask_document')!;
|
||||
|
||||
await tool.execute({ document_id: '42', question: 'What is the blocker?' });
|
||||
|
||||
expect(askFn).toHaveBeenCalledWith('42', 'What is the blocker?');
|
||||
});
|
||||
|
||||
it('formats answer with document ID and sources', async () => {
|
||||
const client = mockClient();
|
||||
const tools = createKvarkTools({ client });
|
||||
const tool = tools.find(t => t.name === 'kvark_ask_document')!;
|
||||
|
||||
const output = await tool.execute({ document_id: '42', question: 'test' });
|
||||
|
||||
expect(output).toContain('KVARK Document Answer (doc #42)');
|
||||
expect(output).toContain('identity boundary design');
|
||||
expect(output).toContain('Sources: Project Status Update.pdf');
|
||||
});
|
||||
|
||||
it('returns graceful message when endpoint returns 501', async () => {
|
||||
const err = new Error('Not implemented');
|
||||
err.name = 'KvarkNotImplementedError';
|
||||
const client = mockClient({ askDocument: vi.fn(async () => { throw err; }) });
|
||||
const tools = createKvarkTools({ client });
|
||||
const tool = tools.find(t => t.name === 'kvark_ask_document')!;
|
||||
|
||||
const output = await tool.execute({ document_id: '42', question: 'test' });
|
||||
|
||||
expect(output).toContain('not yet available');
|
||||
expect(output).toContain('kvark_search');
|
||||
});
|
||||
|
||||
it('returns graceful message when document not found', async () => {
|
||||
const err = new Error('Not found');
|
||||
err.name = 'KvarkNotFoundError';
|
||||
const client = mockClient({ askDocument: vi.fn(async () => { throw err; }) });
|
||||
const tools = createKvarkTools({ client });
|
||||
const tool = tools.find(t => t.name === 'kvark_ask_document')!;
|
||||
|
||||
const output = await tool.execute({ document_id: '999', question: 'test' });
|
||||
|
||||
expect(output).toContain('not found');
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseSearchResults (Milestone B helper)', () => {
|
||||
it('converts search response to structured results with attribution', () => {
|
||||
const results = parseSearchResults(SEARCH_RESPONSE);
|
||||
|
||||
expect(results).toHaveLength(3);
|
||||
|
||||
// First result
|
||||
expect(results[0].documentId).toBe(42);
|
||||
expect(results[0].title).toBe('Project Status Update');
|
||||
expect(results[0].score).toBe(0.92);
|
||||
expect(results[0].documentType).toBe('pdf');
|
||||
expect(results[0].attribution).toBe('[KVARK: pdf: Project Status Update]');
|
||||
expect(results[0].content).toContain('API design review');
|
||||
|
||||
// Null document_type → attribution without type segment
|
||||
expect(results[2].attribution).toBe('[KVARK: Architecture Decision Records]');
|
||||
});
|
||||
|
||||
it('returns empty array for empty results', () => {
|
||||
const results = parseSearchResults({ results: [], total: 0, query: 'empty' });
|
||||
expect(results).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('tool definitions', () => {
|
||||
it('creates exactly 4 tools', () => {
|
||||
const tools = createKvarkTools({ client: mockClient() });
|
||||
expect(tools).toHaveLength(4);
|
||||
expect(tools.map(t => t.name)).toEqual(['kvark_search', 'kvark_feedback', 'kvark_action', 'kvark_ask_document']);
|
||||
});
|
||||
|
||||
it('kvark_search requires query parameter', () => {
|
||||
const tools = createKvarkTools({ client: mockClient() });
|
||||
const search = tools[0];
|
||||
expect((search.parameters as Record<string, unknown>).required).toEqual(['query']);
|
||||
});
|
||||
|
||||
it('kvark_ask_document requires document_id and question', () => {
|
||||
const tools = createKvarkTools({ client: mockClient() });
|
||||
const ask = tools.find(t => t.name === 'kvark_ask_document')!;
|
||||
expect((ask.parameters as Record<string, unknown>).required).toEqual(['document_id', 'question']);
|
||||
});
|
||||
|
||||
it('kvark_feedback requires document_id, query, useful', () => {
|
||||
const tools = createKvarkTools({ client: mockClient() });
|
||||
const feedback = tools.find(t => t.name === 'kvark_feedback')!;
|
||||
expect(feedback).toBeDefined();
|
||||
expect((feedback.parameters as Record<string, unknown>).required).toEqual(['document_id', 'query', 'useful']);
|
||||
});
|
||||
|
||||
it('kvark_action requires action_type, entity_type, entity_id, payload, reason', () => {
|
||||
const tools = createKvarkTools({ client: mockClient() });
|
||||
const action = tools.find(t => t.name === 'kvark_action')!;
|
||||
expect(action).toBeDefined();
|
||||
expect((action.parameters as Record<string, unknown>).required).toEqual(['action_type', 'entity_type', 'entity_id', 'payload', 'reason']);
|
||||
});
|
||||
});
|
||||
|
||||
// ── kvark_feedback ────────────────────────────────────────────────
|
||||
|
||||
describe('kvark_feedback', () => {
|
||||
it('calls client.feedback with correct parameters', async () => {
|
||||
const feedbackFn = vi.fn(async () => ({ ok: true }));
|
||||
const client = mockClient({ feedback: feedbackFn });
|
||||
const tools = createKvarkTools({ client });
|
||||
const tool = tools.find(t => t.name === 'kvark_feedback')!;
|
||||
|
||||
await tool.execute({ document_id: 42, query: 'project status', useful: true, reason: 'Exactly what I needed' });
|
||||
|
||||
expect(feedbackFn).toHaveBeenCalledWith(42, 'project status', true, 'Exactly what I needed');
|
||||
});
|
||||
|
||||
it('returns confirmation on success', async () => {
|
||||
const client = mockClient();
|
||||
const tools = createKvarkTools({ client });
|
||||
const tool = tools.find(t => t.name === 'kvark_feedback')!;
|
||||
|
||||
const output = await tool.execute({ document_id: 42, query: 'test', useful: true });
|
||||
|
||||
expect(output).toContain('Feedback recorded');
|
||||
expect(output).toContain('useful');
|
||||
expect(output).toContain('42');
|
||||
});
|
||||
|
||||
it('returns negative feedback message', async () => {
|
||||
const client = mockClient();
|
||||
const tools = createKvarkTools({ client });
|
||||
const tool = tools.find(t => t.name === 'kvark_feedback')!;
|
||||
|
||||
const output = await tool.execute({ document_id: 108, query: 'budget', useful: false });
|
||||
|
||||
expect(output).toContain('not useful');
|
||||
expect(output).toContain('108');
|
||||
});
|
||||
|
||||
it('handles feedback failure gracefully', async () => {
|
||||
const err = new Error('Network error');
|
||||
err.name = 'KvarkUnavailableError';
|
||||
const client = mockClient({ feedback: vi.fn(async () => { throw err; }) });
|
||||
const tools = createKvarkTools({ client });
|
||||
const tool = tools.find(t => t.name === 'kvark_feedback')!;
|
||||
|
||||
const output = await tool.execute({ document_id: 42, query: 'test', useful: true });
|
||||
|
||||
expect(output).toContain('not reachable');
|
||||
});
|
||||
|
||||
it('handles 501 Not Implemented gracefully', async () => {
|
||||
const err = new Error('Not implemented');
|
||||
err.name = 'KvarkNotImplementedError';
|
||||
const client = mockClient({ feedback: vi.fn(async () => { throw err; }) });
|
||||
const tools = createKvarkTools({ client });
|
||||
const tool = tools.find(t => t.name === 'kvark_feedback')!;
|
||||
|
||||
const output = await tool.execute({ document_id: 42, query: 'test', useful: true });
|
||||
|
||||
expect(output).toContain('not yet available');
|
||||
expect(output).toContain('non-blocking');
|
||||
});
|
||||
|
||||
it('handles client without feedback method', async () => {
|
||||
const client: KvarkClientLike = {
|
||||
search: vi.fn(async () => SEARCH_RESPONSE),
|
||||
askDocument: vi.fn(async () => ASK_RESPONSE),
|
||||
// no feedback method
|
||||
};
|
||||
const tools = createKvarkTools({ client });
|
||||
const tool = tools.find(t => t.name === 'kvark_feedback')!;
|
||||
|
||||
const output = await tool.execute({ document_id: 42, query: 'test', useful: true });
|
||||
|
||||
expect(output).toContain('not supported');
|
||||
});
|
||||
|
||||
it('works without optional reason parameter', async () => {
|
||||
const feedbackFn = vi.fn(async () => ({ ok: true }));
|
||||
const client = mockClient({ feedback: feedbackFn });
|
||||
const tools = createKvarkTools({ client });
|
||||
const tool = tools.find(t => t.name === 'kvark_feedback')!;
|
||||
|
||||
await tool.execute({ document_id: 42, query: 'test', useful: false });
|
||||
|
||||
expect(feedbackFn).toHaveBeenCalledWith(42, 'test', false, undefined);
|
||||
});
|
||||
});
|
||||
|
||||
// ── kvark_action ──────────────────────────────────────────────────
|
||||
|
||||
describe('kvark_action', () => {
|
||||
it('calls client.action with correct parameters', async () => {
|
||||
const actionFn = vi.fn(async () => ({ ok: true, data: { status: 'executed' as const, actionId: 'act_001' }, error: null }));
|
||||
const client = mockClient({ action: actionFn });
|
||||
const tools = createKvarkTools({ client });
|
||||
const tool = tools.find(t => t.name === 'kvark_action')!;
|
||||
|
||||
await tool.execute({
|
||||
action_type: 'jira.create_comment',
|
||||
entity_type: 'issue',
|
||||
entity_id: 'PROJ-142',
|
||||
payload: { comment: 'Follow-up from Waggle' },
|
||||
reason: 'User requested follow-up',
|
||||
});
|
||||
|
||||
expect(actionFn).toHaveBeenCalledWith(
|
||||
'jira.create_comment',
|
||||
{ entityType: 'issue', entityId: 'PROJ-142' },
|
||||
{ comment: 'Follow-up from Waggle' },
|
||||
'User requested follow-up',
|
||||
);
|
||||
});
|
||||
|
||||
it('returns confirmation on successful execution', async () => {
|
||||
const client = mockClient();
|
||||
const tools = createKvarkTools({ client });
|
||||
const tool = tools.find(t => t.name === 'kvark_action')!;
|
||||
|
||||
const output = await tool.execute({
|
||||
action_type: 'jira.create_comment',
|
||||
entity_type: 'issue',
|
||||
entity_id: 'PROJ-142',
|
||||
payload: { comment: 'test' },
|
||||
reason: 'test',
|
||||
});
|
||||
|
||||
expect(output).toContain('Action executed');
|
||||
expect(output).toContain('jira.create_comment');
|
||||
expect(output).toContain('act_001');
|
||||
});
|
||||
|
||||
it('reports denial from KVARK governance', async () => {
|
||||
const actionFn = vi.fn(async () => ({
|
||||
ok: false,
|
||||
data: null,
|
||||
error: { code: 'approval_required_or_denied', message: 'Action not permitted under current policy.' },
|
||||
}));
|
||||
const client = mockClient({ action: actionFn });
|
||||
const tools = createKvarkTools({ client });
|
||||
const tool = tools.find(t => t.name === 'kvark_action')!;
|
||||
|
||||
const output = await tool.execute({
|
||||
action_type: 'jira.create_comment',
|
||||
entity_type: 'issue',
|
||||
entity_id: 'X-1',
|
||||
payload: {},
|
||||
reason: 'test',
|
||||
});
|
||||
|
||||
expect(output).toContain('Action denied');
|
||||
expect(output).toContain('not permitted');
|
||||
});
|
||||
|
||||
it('handles 501 Not Implemented gracefully', async () => {
|
||||
const err = new Error('Not implemented');
|
||||
err.name = 'KvarkNotImplementedError';
|
||||
const client = mockClient({ action: vi.fn(async () => { throw err; }) });
|
||||
const tools = createKvarkTools({ client });
|
||||
const tool = tools.find(t => t.name === 'kvark_action')!;
|
||||
|
||||
const output = await tool.execute({
|
||||
action_type: 'test', entity_type: 'x', entity_id: '1', payload: {}, reason: 'test',
|
||||
});
|
||||
|
||||
expect(output).toContain('not yet available');
|
||||
expect(output).toContain('not executed');
|
||||
});
|
||||
|
||||
it('handles client without action method', async () => {
|
||||
const client: KvarkClientLike = {
|
||||
search: vi.fn(async () => SEARCH_RESPONSE),
|
||||
askDocument: vi.fn(async () => ASK_RESPONSE),
|
||||
};
|
||||
const tools = createKvarkTools({ client });
|
||||
const tool = tools.find(t => t.name === 'kvark_action')!;
|
||||
|
||||
const output = await tool.execute({
|
||||
action_type: 'test', entity_type: 'x', entity_id: '1', payload: {}, reason: 'test',
|
||||
});
|
||||
|
||||
expect(output).toContain('not supported');
|
||||
});
|
||||
|
||||
it('reports queued status correctly', async () => {
|
||||
const actionFn = vi.fn(async () => ({
|
||||
ok: true,
|
||||
data: { status: 'queued' as const, actionId: 'act_q1' },
|
||||
error: null,
|
||||
}));
|
||||
const client = mockClient({ action: actionFn });
|
||||
const tools = createKvarkTools({ client });
|
||||
const tool = tools.find(t => t.name === 'kvark_action')!;
|
||||
|
||||
const output = await tool.execute({
|
||||
action_type: 'email.send', entity_type: 'contact', entity_id: 'c_1', payload: { subject: 'hi' }, reason: 'outreach',
|
||||
});
|
||||
|
||||
expect(output).toContain('queued');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,9 @@
|
||||
/**
|
||||
* Skills 2.0 gap E — promote_skill tool.
|
||||
*
|
||||
* Tests the one-step promotion chain personal → workspace → team → enterprise,
|
||||
* tier gating, frontmatter rewrite with promoted_from history, file move,
|
||||
* and skill_promotion improvement signal emission.
|
||||
* Tests the one-step promotion personal → workspace, the refusal of team and
|
||||
* enterprise scopes in this edition, frontmatter rewrite with promoted_from
|
||||
* history, file move, and skill_promotion improvement signal emission.
|
||||
*/
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import * as fs from 'node:fs';
|
||||
@@ -32,8 +32,6 @@ describe('promote_skill — gap E', () => {
|
||||
onSkillsChanged: () => { reloadCount++; },
|
||||
getWorkspaceId: () => 'ws-alpha',
|
||||
getTeamId: () => 'team-bravo',
|
||||
hasTeamSkillLibrary: () => true,
|
||||
isEnterprise: () => true,
|
||||
improvementSignals: signals,
|
||||
...overrides,
|
||||
});
|
||||
@@ -87,22 +85,6 @@ describe('promote_skill — gap E', () => {
|
||||
// onSkillsChanged fired
|
||||
expect(reloadCount).toBe(1);
|
||||
});
|
||||
|
||||
it('appends to existing promoted_from across multiple hops', async () => {
|
||||
const wsDir = getSkillDirForScope(tmpDir, 'workspace', { workspaceId: 'ws-alpha' })!;
|
||||
// Skill already promoted once (personal → workspace), now promote to team
|
||||
fs.mkdirSync(wsDir, { recursive: true });
|
||||
const content = `---\nname: already-moved\nscope: workspace\npromoted_from: [personal]\n---\nbody`;
|
||||
fs.writeFileSync(path.join(wsDir, 'already-moved.md'), content, 'utf-8');
|
||||
const tools = createTools();
|
||||
|
||||
await run(tools, 'promote_skill', { skill_name: 'already-moved' });
|
||||
|
||||
const teamDir = getSkillDirForScope(tmpDir, 'team', { teamId: 'team-bravo' })!;
|
||||
const parsed = parseSkillFrontmatter(fs.readFileSync(path.join(teamDir, 'already-moved.md'), 'utf-8'));
|
||||
expect(parsed.frontmatter.scope).toBe('team');
|
||||
expect(parsed.frontmatter.promoted_from).toEqual(['personal', 'workspace']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('validation', () => {
|
||||
@@ -136,30 +118,22 @@ describe('promote_skill — gap E', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('tier gating', () => {
|
||||
it('denies team promotion when hasTeamSkillLibrary is false', async () => {
|
||||
describe('edition limits', () => {
|
||||
it('refuses team promotion and leaves the skill in place', async () => {
|
||||
const wsDir = getSkillDirForScope(tmpDir, 'workspace', { workspaceId: 'ws-alpha' })!;
|
||||
seedSkill(wsDir, 'paid-feature', 'workspace');
|
||||
const tools = createTools({ hasTeamSkillLibrary: () => false });
|
||||
const out = await run(tools, 'promote_skill', { skill_name: 'paid-feature' });
|
||||
expect(out).toContain('your plan does not include');
|
||||
expect(out).toContain('TEAMS or ENTERPRISE');
|
||||
seedSkill(wsDir, 'shared-helper', 'workspace');
|
||||
const out = await run(createTools(), 'promote_skill', { skill_name: 'shared-helper' });
|
||||
expect(out).toContain('not available in this edition');
|
||||
expect(fs.existsSync(path.join(wsDir, 'shared-helper.md'))).toBe(true);
|
||||
expect(signals.getByCategory('skill_promotion')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('denies team promotion when no team is linked even if capability allows', async () => {
|
||||
const wsDir = getSkillDirForScope(tmpDir, 'workspace', { workspaceId: 'ws-alpha' })!;
|
||||
seedSkill(wsDir, 'solo-ws', 'workspace');
|
||||
const tools = createTools({ getTeamId: () => null });
|
||||
const out = await run(tools, 'promote_skill', { skill_name: 'solo-ws' });
|
||||
expect(out).toContain('not linked to a team');
|
||||
});
|
||||
|
||||
it('denies enterprise promotion without isEnterprise', async () => {
|
||||
it('refuses enterprise promotion', async () => {
|
||||
const teamDir = getSkillDirForScope(tmpDir, 'team', { teamId: 'team-bravo' })!;
|
||||
seedSkill(teamDir, 'hot-skill', 'team');
|
||||
const tools = createTools({ isEnterprise: () => false });
|
||||
const out = await run(tools, 'promote_skill', { skill_name: 'hot-skill' });
|
||||
expect(out).toContain('requires ENTERPRISE tier');
|
||||
const out = await run(createTools(), 'promote_skill', { skill_name: 'hot-skill' });
|
||||
expect(out).toContain('Cannot promote to enterprise scope');
|
||||
expect(out).toContain('not available in this edition');
|
||||
});
|
||||
|
||||
it('denies workspace promotion when no workspace is active', async () => {
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
/**
|
||||
* B2 wiring tests — search_memory integration with CombinedRetrieval.
|
||||
*
|
||||
* Tests the search_memory tool's behavior with and without kvarkClient,
|
||||
* and the formatCombinedResult helper.
|
||||
* formatCombinedResult — renders a CombinedRetrieval result for the agent.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { formatCombinedResult } from '../src/tools.js';
|
||||
import type { CombinedRetrievalResult, CombinedResult } from '../src/combined-retrieval.js';
|
||||
|
||||
@@ -26,10 +23,6 @@ function makeRetrievalResult(overrides: Partial<CombinedRetrievalResult> = {}):
|
||||
query: overrides.query ?? 'test',
|
||||
workspaceResults: overrides.workspaceResults ?? [],
|
||||
personalResults: overrides.personalResults ?? [],
|
||||
kvarkResults: overrides.kvarkResults ?? [],
|
||||
kvarkAvailable: overrides.kvarkAvailable ?? false,
|
||||
kvarkSkipped: overrides.kvarkSkipped ?? false,
|
||||
kvarkError: overrides.kvarkError,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -88,92 +81,14 @@ describe('formatCombinedResult', () => {
|
||||
expect(result).toContain('some pref');
|
||||
});
|
||||
|
||||
it('formats KVARK results with Enterprise Knowledge header and attribution', () => {
|
||||
const result = formatCombinedResult(makeRetrievalResult({
|
||||
kvarkResults: [
|
||||
makeCombinedResult({
|
||||
source: 'kvark',
|
||||
attribution: '[KVARK: pdf: Q3 Report]',
|
||||
content: 'Revenue grew 15%',
|
||||
score: 0.92,
|
||||
metadata: { documentId: 42, documentType: 'pdf' },
|
||||
}),
|
||||
],
|
||||
kvarkAvailable: true,
|
||||
}), true);
|
||||
|
||||
expect(result).toContain('## Enterprise Knowledge (KVARK)');
|
||||
expect(result).toContain('[KVARK: pdf: Q3 Report]');
|
||||
expect(result).toContain('Revenue grew 15%');
|
||||
expect(result).toContain('score: 0.920');
|
||||
});
|
||||
|
||||
it('appends KVARK error note while preserving local results', () => {
|
||||
const result = formatCombinedResult(makeRetrievalResult({
|
||||
workspaceResults: [
|
||||
makeCombinedResult({ content: 'local fact', score: 0.7 }),
|
||||
],
|
||||
kvarkError: 'Connection refused',
|
||||
kvarkAvailable: true,
|
||||
}), true);
|
||||
|
||||
expect(result).toContain('local fact');
|
||||
expect(result).toContain('Enterprise search encountered an error: Connection refused');
|
||||
expect(result).toContain('Results shown are from local memory only');
|
||||
});
|
||||
|
||||
it('formats all three sources together correctly', () => {
|
||||
it('formats workspace and personal sources in order', () => {
|
||||
const result = formatCombinedResult(makeRetrievalResult({
|
||||
workspaceResults: [makeCombinedResult({ content: 'ws data', score: 0.9 })],
|
||||
personalResults: [makeCombinedResult({ source: 'personal', content: 'personal data', score: 0.7 })],
|
||||
kvarkResults: [makeCombinedResult({ source: 'kvark', attribution: '[KVARK: doc]', content: 'enterprise data', score: 0.85 })],
|
||||
kvarkAvailable: true,
|
||||
}), true);
|
||||
|
||||
expect(result).toContain('## Workspace Memory');
|
||||
expect(result).toContain('## Personal Memory');
|
||||
expect(result).toContain('## Enterprise Knowledge (KVARK)');
|
||||
// Verify ordering: workspace → personal → KVARK
|
||||
const wsIdx = result.indexOf('## Workspace Memory');
|
||||
const pIdx = result.indexOf('## Personal Memory');
|
||||
const kIdx = result.indexOf('## Enterprise Knowledge');
|
||||
expect(wsIdx).toBeLessThan(pIdx);
|
||||
expect(pIdx).toBeLessThan(kIdx);
|
||||
});
|
||||
|
||||
it('KVARK results use score-only format (no frame_type/importance)', () => {
|
||||
const result = formatCombinedResult(makeRetrievalResult({
|
||||
kvarkResults: [
|
||||
makeCombinedResult({
|
||||
source: 'kvark',
|
||||
attribution: '[KVARK: pdf: Doc]',
|
||||
content: 'content',
|
||||
score: 0.9,
|
||||
}),
|
||||
],
|
||||
kvarkAvailable: true,
|
||||
}), true);
|
||||
|
||||
// KVARK results should NOT have frame_type or importance
|
||||
expect(result).not.toContain('type:');
|
||||
expect(result).not.toContain('importance:');
|
||||
expect(result).toContain('score: 0.900');
|
||||
});
|
||||
});
|
||||
|
||||
// ── MindToolDeps.kvarkClient integration (structural tests) ─────────────
|
||||
|
||||
describe('MindToolDeps kvarkClient integration', () => {
|
||||
it('MindToolDeps accepts optional kvarkClient', async () => {
|
||||
// This is a compile-time test — if MindToolDeps didn't have kvarkClient,
|
||||
// TypeScript would catch it. We verify the type exists by importing it.
|
||||
const { type } = await import('../src/tools.js');
|
||||
// If we got here, the import succeeded and the type exists
|
||||
expect(true).toBe(true);
|
||||
});
|
||||
|
||||
it('OrchestratorConfig accepts optional kvarkClient', async () => {
|
||||
const { type } = await import('../src/orchestrator.js');
|
||||
expect(true).toBe(true);
|
||||
expect(result.indexOf('## Workspace Memory')).toBeLessThan(result.indexOf('## Personal Memory'));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@waggle/core",
|
||||
"version": "0.1.0",
|
||||
"description": "Waggle-specific orchestration: config, multi-mind, workspace, vault, telemetry, install-audit, cron, skills, file-store, file-indexer, memory-import, optimization-log, compliance. Re-exports substrate from @waggle/hive-mind-core for backward compatibility.",
|
||||
"description": "Waggle-specific orchestration: config, multi-mind, workspace, vault, telemetry, install-audit, cron, skills, file-store, file-indexer, memory-import, optimization-log. Re-exports substrate from @waggle/hive-mind-core for backward compatibility.",
|
||||
"type": "module",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
export * from './types.js';
|
||||
export { InteractionStore } from './interaction-store.js';
|
||||
export { ComplianceStatusChecker } from './status-checker.js';
|
||||
export { ReportGenerator } from './report-generator.js';
|
||||
export { ComplianceTemplateStore } from './template-store.js';
|
||||
@@ -1,208 +0,0 @@
|
||||
/**
|
||||
* InteractionStore — CRUD for ai_interactions table (EU AI Act Art. 12).
|
||||
*
|
||||
* Records every AI interaction with model, tokens, cost, tools, and human oversight.
|
||||
* Operates on the .mind DB alongside FrameStore and InstallAuditStore.
|
||||
*/
|
||||
|
||||
import type { MindDB } from '@waggle/hive-mind-core';
|
||||
import type { AIInteraction, RecordInteractionInput, HumanAction, ModelInventoryEntry, OversightLogEntry } from './types.js';
|
||||
|
||||
export class InteractionStore {
|
||||
private db: MindDB;
|
||||
|
||||
constructor(db: MindDB) {
|
||||
this.db = db;
|
||||
// Review Major #8: previously ensureTable() duplicated the DDL from schema.ts and
|
||||
// drifted whenever the canonical schema changed. Now schema.ts + MindDB.runMigrations()
|
||||
// own the table definition, including the input_text/output_text columns and the
|
||||
// append-only triggers (Critical #1, #3).
|
||||
}
|
||||
|
||||
/** Record an AI interaction event. */
|
||||
record(input: RecordInteractionInput): AIInteraction {
|
||||
const raw = this.db.getDatabase();
|
||||
|
||||
// Review Major #4: use lastInsertRowid from .run() instead of reading back
|
||||
// ORDER BY id DESC LIMIT 1 — under concurrent writes (WaggleDance multi-agent),
|
||||
// the LIMIT 1 row may belong to a different writer.
|
||||
const result = raw.prepare(`
|
||||
INSERT INTO ai_interactions (
|
||||
workspace_id, session_id, model, provider,
|
||||
input_tokens, output_tokens, cost_usd,
|
||||
tools_called, human_action, risk_context, imported_from, persona,
|
||||
input_text, output_text
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`).run(
|
||||
input.workspaceId ?? null,
|
||||
input.sessionId ?? null,
|
||||
input.model,
|
||||
input.provider,
|
||||
input.inputTokens,
|
||||
input.outputTokens,
|
||||
input.costUsd,
|
||||
JSON.stringify(input.toolsCalled ?? []),
|
||||
input.humanAction ?? 'none',
|
||||
input.riskContext ?? null,
|
||||
input.importedFrom ?? null,
|
||||
input.persona ?? null,
|
||||
input.inputText ?? null,
|
||||
input.outputText ?? null,
|
||||
);
|
||||
|
||||
const row = raw.prepare('SELECT * FROM ai_interactions WHERE id = ?').get(result.lastInsertRowid) as Record<string, unknown>;
|
||||
return this.rowToInteraction(row);
|
||||
}
|
||||
|
||||
/** Get interactions for a workspace within a date range. */
|
||||
getByWorkspace(workspaceId: string, from?: string, to?: string): AIInteraction[] {
|
||||
if (from && !/^\d{4}-\d{2}-\d{2}/.test(from)) throw new Error('Invalid date format');
|
||||
if (to && !/^\d{4}-\d{2}-\d{2}/.test(to)) throw new Error('Invalid date format');
|
||||
|
||||
const raw = this.db.getDatabase();
|
||||
let sql = 'SELECT * FROM ai_interactions WHERE workspace_id = ?';
|
||||
const params: unknown[] = [workspaceId];
|
||||
|
||||
if (from) { sql += ' AND timestamp >= ?'; params.push(from); }
|
||||
if (to) { sql += ' AND timestamp <= ?'; params.push(to); }
|
||||
sql += ' ORDER BY timestamp DESC LIMIT 1000';
|
||||
|
||||
return (raw.prepare(sql).all(...params) as Record<string, unknown>[]).map(r => this.rowToInteraction(r));
|
||||
}
|
||||
|
||||
/** Get all interactions within a date range. */
|
||||
getByDateRange(from: string, to: string, workspaceId?: string): AIInteraction[] {
|
||||
if (from && !/^\d{4}-\d{2}-\d{2}/.test(from)) throw new Error('Invalid date format');
|
||||
if (to && !/^\d{4}-\d{2}-\d{2}/.test(to)) throw new Error('Invalid date format');
|
||||
|
||||
const raw = this.db.getDatabase();
|
||||
let sql = 'SELECT * FROM ai_interactions WHERE timestamp >= ? AND timestamp <= ?';
|
||||
const params: unknown[] = [from, to];
|
||||
|
||||
if (workspaceId) { sql += ' AND workspace_id = ?'; params.push(workspaceId); }
|
||||
sql += ' ORDER BY timestamp DESC LIMIT 1000';
|
||||
|
||||
return (raw.prepare(sql).all(...params) as Record<string, unknown>[]).map(r => this.rowToInteraction(r));
|
||||
}
|
||||
|
||||
/** Get total interaction count. */
|
||||
count(workspaceId?: string): number {
|
||||
const raw = this.db.getDatabase();
|
||||
if (workspaceId) {
|
||||
const row = raw.prepare('SELECT COUNT(*) as cnt FROM ai_interactions WHERE workspace_id = ?').get(workspaceId) as { cnt: number };
|
||||
return row.cnt;
|
||||
}
|
||||
const row = raw.prepare('SELECT COUNT(*) as cnt FROM ai_interactions').get() as { cnt: number };
|
||||
return row.cnt;
|
||||
}
|
||||
|
||||
/** Get the oldest log timestamp (Art. 19 retention check). */
|
||||
getOldestTimestamp(): string | null {
|
||||
const raw = this.db.getDatabase();
|
||||
const row = raw.prepare('SELECT MIN(timestamp) as oldest FROM ai_interactions').get() as { oldest: string | null };
|
||||
return row.oldest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the `first_run_at` timestamp from the MindDB's `meta` table — set on
|
||||
* schema initialization and backfilled for pre-existing DBs. Used by the Art. 19
|
||||
* retention checker to distinguish 'new system' from 'pruned logs'.
|
||||
*/
|
||||
getFirstRunAt(): string | null {
|
||||
return this.db.getFirstRunAt();
|
||||
}
|
||||
|
||||
/** Get model inventory (aggregated usage per model). */
|
||||
getModelInventory(from?: string, to?: string, workspaceId?: string): ModelInventoryEntry[] {
|
||||
const raw = this.db.getDatabase();
|
||||
let sql = `
|
||||
SELECT model, provider,
|
||||
COUNT(*) as calls,
|
||||
SUM(input_tokens) as input_tokens,
|
||||
SUM(output_tokens) as output_tokens,
|
||||
SUM(cost_usd) as cost_usd
|
||||
FROM ai_interactions WHERE 1=1
|
||||
`;
|
||||
const params: unknown[] = [];
|
||||
|
||||
if (from) { sql += ' AND timestamp >= ?'; params.push(from); }
|
||||
if (to) { sql += ' AND timestamp <= ?'; params.push(to); }
|
||||
if (workspaceId) { sql += ' AND workspace_id = ?'; params.push(workspaceId); }
|
||||
sql += ' GROUP BY model, provider ORDER BY calls DESC';
|
||||
|
||||
return (raw.prepare(sql).all(...params) as Record<string, unknown>[]).map(r => ({
|
||||
model: r.model as string,
|
||||
provider: r.provider as string,
|
||||
calls: r.calls as number,
|
||||
inputTokens: r.input_tokens as number,
|
||||
outputTokens: r.output_tokens as number,
|
||||
costUsd: r.cost_usd as number,
|
||||
}));
|
||||
}
|
||||
|
||||
/** Get human oversight actions (Art. 14). */
|
||||
getOversightLog(from?: string, to?: string, workspaceId?: string): OversightLogEntry[] {
|
||||
const raw = this.db.getDatabase();
|
||||
let sql = "SELECT * FROM ai_interactions WHERE human_action != 'none' AND human_action IS NOT NULL";
|
||||
const params: unknown[] = [];
|
||||
|
||||
if (from) { sql += ' AND timestamp >= ?'; params.push(from); }
|
||||
if (to) { sql += ' AND timestamp <= ?'; params.push(to); }
|
||||
if (workspaceId) { sql += ' AND workspace_id = ?'; params.push(workspaceId); }
|
||||
sql += ' ORDER BY timestamp DESC';
|
||||
|
||||
return (raw.prepare(sql).all(...params) as Record<string, unknown>[]).map(r => ({
|
||||
timestamp: r.timestamp as string,
|
||||
action: r.human_action as HumanAction,
|
||||
tool: (JSON.parse(r.tools_called as string) as string[])[0] ?? 'none',
|
||||
detail: r.persona ? `Persona: ${r.persona}` : '',
|
||||
}));
|
||||
}
|
||||
|
||||
/** Get human oversight counts for compliance check. */
|
||||
getOversightCounts(workspaceId?: string): { total: number; approved: number; denied: number; modified: number } {
|
||||
const raw = this.db.getDatabase();
|
||||
let sql = "SELECT human_action, COUNT(*) as cnt FROM ai_interactions WHERE human_action != 'none' AND human_action IS NOT NULL";
|
||||
const params: unknown[] = [];
|
||||
if (workspaceId) { sql += ' AND workspace_id = ?'; params.push(workspaceId); }
|
||||
sql += ' GROUP BY human_action';
|
||||
|
||||
const rows = raw.prepare(sql).all(...params) as { human_action: string; cnt: number }[];
|
||||
const counts = { total: 0, approved: 0, denied: 0, modified: 0 };
|
||||
for (const row of rows) {
|
||||
counts.total += row.cnt;
|
||||
if (row.human_action === 'approved') counts.approved = row.cnt;
|
||||
if (row.human_action === 'denied') counts.denied = row.cnt;
|
||||
if (row.human_action === 'modified') counts.modified = row.cnt;
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
|
||||
/** Get recent interactions. */
|
||||
getRecent(limit: number = 20): AIInteraction[] {
|
||||
const raw = this.db.getDatabase();
|
||||
return (raw.prepare('SELECT * FROM ai_interactions ORDER BY id DESC LIMIT ?').all(limit) as Record<string, unknown>[])
|
||||
.map(r => this.rowToInteraction(r));
|
||||
}
|
||||
|
||||
private rowToInteraction(row: Record<string, unknown>): AIInteraction {
|
||||
return {
|
||||
id: row.id as number,
|
||||
timestamp: row.timestamp as string,
|
||||
workspaceId: row.workspace_id as string | null,
|
||||
sessionId: row.session_id as string | null,
|
||||
model: row.model as string,
|
||||
provider: row.provider as string,
|
||||
inputTokens: row.input_tokens as number,
|
||||
outputTokens: row.output_tokens as number,
|
||||
costUsd: row.cost_usd as number,
|
||||
toolsCalled: JSON.parse(row.tools_called as string) as string[],
|
||||
humanAction: (row.human_action as HumanAction) ?? 'none',
|
||||
riskContext: row.risk_context as string | null,
|
||||
importedFrom: row.imported_from as string | null,
|
||||
persona: row.persona as string | null,
|
||||
inputText: (row.input_text as string | null | undefined) ?? null,
|
||||
outputText: (row.output_text as string | null | undefined) ?? null,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
/**
|
||||
* ReportGenerator — generates AI Act compliance audit reports.
|
||||
*
|
||||
* Produces JSON reports (PDF generation deferred to document tooling).
|
||||
* Reports cover: compliance status, model inventory, oversight log,
|
||||
* harvest provenance, and interaction counts.
|
||||
*/
|
||||
|
||||
import type { InteractionStore } from './interaction-store.js';
|
||||
import type { HarvestSourceStore } from '@waggle/hive-mind-core';
|
||||
import { ComplianceStatusChecker } from './status-checker.js';
|
||||
import type { AuditReport, AuditReportRequest, AIActRiskLevel } from './types.js';
|
||||
|
||||
const REPORT_VERSION = '1.0';
|
||||
|
||||
export interface ReportGeneratorDeps {
|
||||
interactionStore: InteractionStore;
|
||||
harvestStore: HarvestSourceStore;
|
||||
getWorkspaceRisk?: (workspaceId: string) => AIActRiskLevel;
|
||||
getWorkspaceName?: (workspaceId: string) => string;
|
||||
/**
|
||||
* Return the ISO timestamp of the last risk classification for this
|
||||
* workspace, or null if the workspace has no persisted classification
|
||||
* date (e.g., was created before the field existed).
|
||||
*/
|
||||
getWorkspaceRiskClassifiedAt?: (workspaceId: string) => string | null;
|
||||
}
|
||||
|
||||
export class ReportGenerator {
|
||||
private interactions: InteractionStore;
|
||||
private harvest: HarvestSourceStore;
|
||||
private getWorkspaceRisk: (id: string) => AIActRiskLevel;
|
||||
private getWorkspaceName: (id: string) => string;
|
||||
private getWorkspaceRiskClassifiedAt: (id: string) => string | null;
|
||||
|
||||
constructor(deps: ReportGeneratorDeps) {
|
||||
this.interactions = deps.interactionStore;
|
||||
this.harvest = deps.harvestStore;
|
||||
this.getWorkspaceRisk = deps.getWorkspaceRisk ?? (() => 'minimal');
|
||||
this.getWorkspaceName = deps.getWorkspaceName ?? ((id) => id);
|
||||
this.getWorkspaceRiskClassifiedAt = deps.getWorkspaceRiskClassifiedAt ?? (() => null);
|
||||
}
|
||||
|
||||
/** Generate a full audit report. */
|
||||
generate(request: AuditReportRequest): AuditReport {
|
||||
const checker = new ComplianceStatusChecker(this.interactions);
|
||||
const complianceStatus = checker.check(request.workspaceId);
|
||||
|
||||
const report: AuditReport = {
|
||||
report: {
|
||||
version: REPORT_VERSION,
|
||||
generatedAt: new Date().toISOString(),
|
||||
period: { from: request.from, to: request.to },
|
||||
generatedBy: 'Waggle OS',
|
||||
},
|
||||
workspace: request.workspaceId ? {
|
||||
id: request.workspaceId,
|
||||
name: this.getWorkspaceName(request.workspaceId),
|
||||
riskLevel: this.getWorkspaceRisk(request.workspaceId),
|
||||
riskClassifiedAt: this.getWorkspaceRiskClassifiedAt(request.workspaceId),
|
||||
} : null,
|
||||
complianceStatus,
|
||||
modelInventory: [],
|
||||
humanOversightLog: [],
|
||||
harvestProvenance: [],
|
||||
interactionCount: 0,
|
||||
};
|
||||
|
||||
// Model inventory
|
||||
if (request.include.models) {
|
||||
report.modelInventory = this.interactions.getModelInventory(
|
||||
request.from, request.to, request.workspaceId,
|
||||
);
|
||||
}
|
||||
|
||||
// Human oversight log
|
||||
if (request.include.oversight) {
|
||||
report.humanOversightLog = this.interactions.getOversightLog(
|
||||
request.from, request.to, request.workspaceId,
|
||||
);
|
||||
}
|
||||
|
||||
// Harvest provenance
|
||||
if (request.include.provenance) {
|
||||
const sources = this.harvest.getAll();
|
||||
report.harvestProvenance = sources.map(s => ({
|
||||
source: s.displayName,
|
||||
importedAt: s.lastSyncedAt ?? s.createdAt,
|
||||
itemsImported: s.itemsImported,
|
||||
framesCreated: s.framesCreated,
|
||||
}));
|
||||
}
|
||||
|
||||
// Interaction count
|
||||
if (request.include.interactions) {
|
||||
const interactions = this.interactions.getByDateRange(
|
||||
request.from, request.to, request.workspaceId,
|
||||
);
|
||||
report.interactionCount = interactions.length;
|
||||
}
|
||||
|
||||
return report;
|
||||
}
|
||||
}
|
||||
@@ -1,175 +0,0 @@
|
||||
/**
|
||||
* ComplianceStatusChecker — evaluates AI Act compliance per workspace.
|
||||
*
|
||||
* Checks:
|
||||
* - Art. 12: Automatic event logging (ai_interactions count)
|
||||
* - Art. 14: Human oversight (approval/denial actions recorded)
|
||||
* - Art. 19: Log retention (oldest log >= 6 months ago)
|
||||
* - Art. 26: Deployer monitoring (active monitors)
|
||||
* - Art. 50: Model transparency (models disclosed)
|
||||
*/
|
||||
|
||||
import type { InteractionStore } from './interaction-store.js';
|
||||
import type { ComplianceStatus, ArticleStatus } from './types.js';
|
||||
|
||||
const SIX_MONTHS_MS = 180 * 24 * 60 * 60 * 1000;
|
||||
|
||||
export class ComplianceStatusChecker {
|
||||
private store: InteractionStore;
|
||||
|
||||
constructor(store: InteractionStore) {
|
||||
this.store = store;
|
||||
}
|
||||
|
||||
/** Evaluate full compliance status for a workspace (or all workspaces if null). */
|
||||
check(workspaceId?: string): ComplianceStatus {
|
||||
const art12 = this.checkArt12(workspaceId);
|
||||
const art14 = this.checkArt14(workspaceId);
|
||||
const art19 = this.checkArt19();
|
||||
const art26 = this.checkArt26();
|
||||
const art50 = this.checkArt50(workspaceId);
|
||||
|
||||
const statuses = [art12.status, art14.status, art19.status, art26.status, art50.status];
|
||||
const overall = statuses.includes('non-compliant') ? 'non-compliant'
|
||||
: statuses.includes('warning') ? 'warning'
|
||||
: 'compliant';
|
||||
|
||||
return {
|
||||
overall,
|
||||
art12Logging: art12,
|
||||
art14Oversight: art14,
|
||||
art19Retention: art19,
|
||||
art26Monitoring: art26,
|
||||
art50Transparency: art50,
|
||||
};
|
||||
}
|
||||
|
||||
/** Art. 12: Automatic recording of events. */
|
||||
private checkArt12(workspaceId?: string): ArticleStatus & { totalInteractions: number } {
|
||||
const total = this.store.count(workspaceId);
|
||||
|
||||
if (total === 0) {
|
||||
// M11: if the DB has been active for >24h with zero interactions, escalate to non-compliant
|
||||
const firstRun = this.store.getFirstRunAt();
|
||||
const activeOver24h = firstRun
|
||||
? (Date.now() - new Date(firstRun).getTime()) > 24 * 60 * 60 * 1000
|
||||
: false;
|
||||
|
||||
return {
|
||||
status: activeOver24h ? 'non-compliant' : 'warning',
|
||||
detail: activeOver24h
|
||||
? 'No interactions logged despite system being active for over 24 hours. Verify logging pipeline.'
|
||||
: 'No interactions logged yet. Logging activates automatically on first AI interaction.',
|
||||
totalInteractions: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
status: 'compliant',
|
||||
detail: `${total} interactions logged with full model, token, cost, and tool tracking.`,
|
||||
totalInteractions: total,
|
||||
};
|
||||
}
|
||||
|
||||
/** Art. 14: Human oversight capability. */
|
||||
private checkArt14(workspaceId?: string): ArticleStatus & { humanActions: number; approvalRate: number } {
|
||||
const counts = this.store.getOversightCounts(workspaceId);
|
||||
|
||||
if (counts.total === 0) {
|
||||
return {
|
||||
status: 'compliant',
|
||||
detail: 'Human oversight capabilities available (approval gates, tool deny lists). No oversight actions recorded yet.',
|
||||
humanActions: 0,
|
||||
approvalRate: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const approvalRate = counts.total > 0
|
||||
? Math.round((counts.approved / counts.total) * 100)
|
||||
: 0;
|
||||
|
||||
return {
|
||||
status: 'compliant',
|
||||
detail: `${counts.total} human oversight actions: ${counts.approved} approved, ${counts.denied} denied, ${counts.modified} modified.`,
|
||||
humanActions: counts.total,
|
||||
approvalRate,
|
||||
};
|
||||
}
|
||||
|
||||
/** Art. 19: Log retention (minimum 6 months). */
|
||||
private checkArt19(): ArticleStatus & { oldestLogDate: string | null; retentionDays: number } {
|
||||
const oldest = this.store.getOldestTimestamp();
|
||||
|
||||
if (!oldest) {
|
||||
return {
|
||||
status: 'compliant',
|
||||
detail: 'No logs to retain yet. Retention policy is permanent by default.',
|
||||
oldestLogDate: null,
|
||||
retentionDays: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const oldestDate = new Date(oldest);
|
||||
const now = new Date();
|
||||
const retentionMs = now.getTime() - oldestDate.getTime();
|
||||
const retentionDays = Math.floor(retentionMs / (24 * 60 * 60 * 1000));
|
||||
|
||||
// Review Critical #2: the previous expression was a tautology
|
||||
// (`retentionMs >= SIX_MONTHS_MS || retentionDays < 180`) that covered every
|
||||
// non-negative value of retentionDays. A deployment that pruned logs after 30
|
||||
// days still reported compliant.
|
||||
//
|
||||
// Proper fix requires distinguishing 'system is young' from 'logs were pruned'.
|
||||
// We track system age via MindDB's `meta.first_run_at` entry (set on schema init,
|
||||
// backfilled for pre-existing DBs). If the system has been running for 180+ days
|
||||
// but the oldest log is younger than that, something pruned the logs and we
|
||||
// correctly report warning.
|
||||
const firstRun = this.store.getFirstRunAt();
|
||||
const systemAgeMs = firstRun ? now.getTime() - new Date(firstRun).getTime() : retentionMs;
|
||||
const hasBeenRunning6Months = systemAgeMs >= SIX_MONTHS_MS;
|
||||
const logsOlderThan6Months = retentionMs >= SIX_MONTHS_MS;
|
||||
const meetsMinimum = !hasBeenRunning6Months || logsOlderThan6Months;
|
||||
|
||||
return {
|
||||
status: meetsMinimum ? 'compliant' : 'warning',
|
||||
detail: meetsMinimum
|
||||
? hasBeenRunning6Months
|
||||
? `Logs retained since ${oldest.split('T')[0]} (${retentionDays} days). Art. 19 minimum (180 days) met.`
|
||||
: `Logs retained since ${oldest.split('T')[0]} (${retentionDays} days). System is still within its first 180 days — retention compliance will be enforceable after 2026-${(new Date(firstRun ?? now).getMonth() + 7).toString().padStart(2, '0')}.`
|
||||
: `Oldest log: ${oldest.split('T')[0]} (${retentionDays} days) but system is ${Math.floor(systemAgeMs / (24 * 60 * 60 * 1000))} days old. Logs appear to have been pruned — EU AI Act Art. 19 requires 180-day minimum retention.`,
|
||||
oldestLogDate: oldest,
|
||||
retentionDays,
|
||||
};
|
||||
}
|
||||
|
||||
/** Art. 26: Deployer monitoring obligations. */
|
||||
private checkArt26(): ArticleStatus & { activeMonitors: string[] } {
|
||||
// Waggle always has these monitors active
|
||||
const monitors = [
|
||||
'cost_tracking', // CostTracker in packages/agent
|
||||
'tool_logging', // Tool calls logged per interaction
|
||||
'model_identification', // Model recorded per interaction
|
||||
'persona_tracking', // Persona recorded per interaction
|
||||
];
|
||||
|
||||
return {
|
||||
status: 'compliant',
|
||||
detail: `${monitors.length} active monitors: cost, tools, model ID, persona.`,
|
||||
activeMonitors: monitors,
|
||||
};
|
||||
}
|
||||
|
||||
/** Art. 50: Transparency — models disclosed. */
|
||||
private checkArt50(workspaceId?: string): ArticleStatus & { modelsDisclosed: boolean } {
|
||||
const inventory = this.store.getModelInventory(undefined, undefined, workspaceId);
|
||||
const modelsDisclosed = inventory.length > 0;
|
||||
|
||||
return {
|
||||
status: 'compliant',
|
||||
detail: modelsDisclosed
|
||||
? `${inventory.length} model(s) in use, all identified in StatusBar and interaction logs.`
|
||||
: 'Model identification active. Models will be disclosed on first interaction.',
|
||||
modelsDisclosed,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,242 +0,0 @@
|
||||
/**
|
||||
* ComplianceTemplateStore — CRUD for user-editable compliance report templates.
|
||||
*
|
||||
* M-03: Templates let a user save a named "report shape" (which sections to include,
|
||||
* a risk-class override, and optional org/footer text) and re-apply it to subsequent
|
||||
* audit-report exports. Sections MERGE with the runtime selection (union semantics).
|
||||
*
|
||||
* Logo support is deferred to Bucket 2. See docs/plans/COMPLIANCE-AUDIT-2026-04-20.md.
|
||||
*
|
||||
* DDL is self-contained here (following HarvestRunStore pattern) rather than threaded
|
||||
* through mind/schema.ts — compliance_templates is not part of the Art. 12 audit
|
||||
* substrate and doesn't need append-only triggers or cross-layer migration tracking.
|
||||
*/
|
||||
|
||||
import type { MindDB } from '@waggle/hive-mind-core';
|
||||
import type {
|
||||
AIActRiskLevel,
|
||||
ComplianceTemplate,
|
||||
ComplianceTemplateSections,
|
||||
CreateComplianceTemplateInput,
|
||||
UpdateComplianceTemplateInput,
|
||||
} from './types.js';
|
||||
|
||||
const CREATE_TABLE_SQL = `
|
||||
CREATE TABLE IF NOT EXISTS compliance_templates (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
sections_json TEXT NOT NULL DEFAULT '{}',
|
||||
risk_classification TEXT CHECK (risk_classification IN ('minimal', 'limited', 'high-risk', 'unacceptable')),
|
||||
org_name TEXT,
|
||||
footer_text TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
)
|
||||
`;
|
||||
// TODO Bucket 2 (M-05 custom branding): add `logo_blob BLOB` + `logo_mime TEXT`
|
||||
// columns. The `Edit templates` modal will grow a file-picker; renderComplianceReportPdf
|
||||
// will render the blob into the PDF header when present.
|
||||
|
||||
const CREATE_INDEX_SQL = `
|
||||
CREATE INDEX IF NOT EXISTS idx_compliance_templates_name ON compliance_templates (name)
|
||||
`;
|
||||
|
||||
const DEFAULT_SECTIONS: ComplianceTemplateSections = {
|
||||
interactions: true,
|
||||
oversight: true,
|
||||
models: true,
|
||||
provenance: true,
|
||||
riskAssessment: true,
|
||||
fria: false,
|
||||
};
|
||||
|
||||
/**
|
||||
* Canonical name for the seeded KVARK template. Used for idempotency — the
|
||||
* seed only fires when no row with this exact name exists.
|
||||
*/
|
||||
export const KVARK_TEMPLATE_NAME = 'KVARK Enterprise Audit';
|
||||
|
||||
export class ComplianceTemplateStore {
|
||||
private db: MindDB;
|
||||
|
||||
constructor(db: MindDB) {
|
||||
this.db = db;
|
||||
this.ensureTable();
|
||||
}
|
||||
|
||||
private ensureTable(): void {
|
||||
const raw = this.db.getDatabase();
|
||||
const existsRow = raw.prepare(
|
||||
"SELECT name FROM sqlite_master WHERE type='table' AND name='compliance_templates'",
|
||||
).get();
|
||||
if (existsRow) return;
|
||||
raw.prepare(CREATE_TABLE_SQL).run();
|
||||
raw.prepare(CREATE_INDEX_SQL).run();
|
||||
}
|
||||
|
||||
create(input: CreateComplianceTemplateInput): ComplianceTemplate {
|
||||
const name = input.name.trim();
|
||||
if (!name) throw new Error('Template name is required');
|
||||
|
||||
const raw = this.db.getDatabase();
|
||||
const result = raw.prepare(`
|
||||
INSERT INTO compliance_templates (
|
||||
name, description, sections_json, risk_classification, org_name, footer_text
|
||||
) VALUES (?, ?, ?, ?, ?, ?)
|
||||
`).run(
|
||||
name,
|
||||
input.description ?? null,
|
||||
JSON.stringify(this.normalizeSections(input.sections)),
|
||||
input.riskClassification ?? null,
|
||||
input.orgName ?? null,
|
||||
input.footerText ?? null,
|
||||
);
|
||||
return this.getById(Number(result.lastInsertRowid))!;
|
||||
}
|
||||
|
||||
getById(id: number): ComplianceTemplate | null {
|
||||
const raw = this.db.getDatabase();
|
||||
const row = raw.prepare('SELECT * FROM compliance_templates WHERE id = ?').get(id) as
|
||||
| Record<string, unknown>
|
||||
| undefined;
|
||||
return row ? this.rowToTemplate(row) : null;
|
||||
}
|
||||
|
||||
list(): ComplianceTemplate[] {
|
||||
const raw = this.db.getDatabase();
|
||||
return (
|
||||
raw
|
||||
.prepare('SELECT * FROM compliance_templates ORDER BY updated_at DESC')
|
||||
.all() as Record<string, unknown>[]
|
||||
).map(r => this.rowToTemplate(r));
|
||||
}
|
||||
|
||||
update(id: number, patch: UpdateComplianceTemplateInput): ComplianceTemplate | null {
|
||||
const existing = this.getById(id);
|
||||
if (!existing) return null;
|
||||
|
||||
const next: ComplianceTemplate = {
|
||||
...existing,
|
||||
name: patch.name !== undefined ? patch.name.trim() : existing.name,
|
||||
description: patch.description !== undefined ? patch.description : existing.description,
|
||||
sections: patch.sections !== undefined ? this.normalizeSections(patch.sections) : existing.sections,
|
||||
riskClassification:
|
||||
patch.riskClassification !== undefined ? patch.riskClassification : existing.riskClassification,
|
||||
orgName: patch.orgName !== undefined ? patch.orgName : existing.orgName,
|
||||
footerText: patch.footerText !== undefined ? patch.footerText : existing.footerText,
|
||||
};
|
||||
if (!next.name) throw new Error('Template name is required');
|
||||
|
||||
const raw = this.db.getDatabase();
|
||||
raw.prepare(`
|
||||
UPDATE compliance_templates SET
|
||||
name = ?,
|
||||
description = ?,
|
||||
sections_json = ?,
|
||||
risk_classification = ?,
|
||||
org_name = ?,
|
||||
footer_text = ?,
|
||||
updated_at = datetime('now')
|
||||
WHERE id = ?
|
||||
`).run(
|
||||
next.name,
|
||||
next.description,
|
||||
JSON.stringify(next.sections),
|
||||
next.riskClassification,
|
||||
next.orgName,
|
||||
next.footerText,
|
||||
id,
|
||||
);
|
||||
return this.getById(id);
|
||||
}
|
||||
|
||||
/** Returns true if the row existed and was removed, false otherwise. */
|
||||
delete(id: number): boolean {
|
||||
const raw = this.db.getDatabase();
|
||||
const info = raw.prepare('DELETE FROM compliance_templates WHERE id = ?').run(id);
|
||||
return info.changes > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge a template's section flags with runtime flags. Union semantics: a section
|
||||
* is included if EITHER the template OR the runtime toggle turns it on. This keeps
|
||||
* the template's role "additive" — it can never silently hide a section the user
|
||||
* asked for in the current export.
|
||||
*/
|
||||
static mergeSections(
|
||||
template: ComplianceTemplateSections,
|
||||
runtime: ComplianceTemplateSections,
|
||||
): ComplianceTemplateSections {
|
||||
return {
|
||||
interactions: template.interactions || runtime.interactions,
|
||||
oversight: template.oversight || runtime.oversight,
|
||||
models: template.models || runtime.models,
|
||||
provenance: template.provenance || runtime.provenance,
|
||||
riskAssessment: template.riskAssessment || runtime.riskAssessment,
|
||||
fria: template.fria || runtime.fria,
|
||||
};
|
||||
}
|
||||
|
||||
private normalizeSections(s: Partial<ComplianceTemplateSections> | undefined): ComplianceTemplateSections {
|
||||
return { ...DEFAULT_SECTIONS, ...(s ?? {}) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Idempotent: seed the built-in "KVARK Enterprise Audit" template if no
|
||||
* template with that exact name exists yet (M-06).
|
||||
*
|
||||
* The KVARK template is a sensible-default shape for sovereign enterprise
|
||||
* deployments — every section on (including FRIA, since KVARK serves
|
||||
* high-risk enterprise systems), risk pinned at `high-risk`, and org/footer
|
||||
* text that signals the sovereign-deployment narrative.
|
||||
*
|
||||
* Custom KVARK-specific sections (per-department risk breakdown, IAM
|
||||
* audit columns, data-residency attestation text) are deferred to
|
||||
* Bucket 2 along with the logo field — the current template schema
|
||||
* doesn't support custom sections yet.
|
||||
*
|
||||
* Returns the seeded template, or null if one already existed.
|
||||
*/
|
||||
seedKvarkTemplateIfMissing(): ComplianceTemplate | null {
|
||||
const raw = this.db.getDatabase();
|
||||
const existing = raw.prepare(
|
||||
'SELECT id FROM compliance_templates WHERE name = ? LIMIT 1',
|
||||
).get(KVARK_TEMPLATE_NAME) as { id: number } | undefined;
|
||||
if (existing) return null;
|
||||
return this.create({
|
||||
name: KVARK_TEMPLATE_NAME,
|
||||
description:
|
||||
'Sovereign AI Act audit shape for enterprise on-prem deployments. ' +
|
||||
'Includes all monitored articles (12/14/19/26/50) plus FRIA since KVARK ' +
|
||||
'customers typically operate high-risk systems. Data never leaves the ' +
|
||||
"customer perimeter; this template's org + footer text signal that " +
|
||||
'posture directly on every exported report.',
|
||||
sections: { ...DEFAULT_SECTIONS, fria: true },
|
||||
riskClassification: 'high-risk',
|
||||
orgName: 'KVARK Sovereign — Enterprise Deployment',
|
||||
footerText:
|
||||
'Confidential · EU AI Act attestation · KVARK sovereign deployment · Data remains within customer perimeter',
|
||||
});
|
||||
}
|
||||
|
||||
private rowToTemplate(row: Record<string, unknown>): ComplianceTemplate {
|
||||
let sections: ComplianceTemplateSections;
|
||||
try {
|
||||
sections = this.normalizeSections(JSON.parse((row.sections_json as string) ?? '{}'));
|
||||
} catch {
|
||||
sections = { ...DEFAULT_SECTIONS };
|
||||
}
|
||||
return {
|
||||
id: row.id as number,
|
||||
name: row.name as string,
|
||||
description: (row.description as string | null) ?? null,
|
||||
sections,
|
||||
riskClassification: (row.risk_classification as AIActRiskLevel | null) ?? null,
|
||||
orgName: (row.org_name as string | null) ?? null,
|
||||
footerText: (row.footer_text as string | null) ?? null,
|
||||
createdAt: row.created_at as string,
|
||||
updatedAt: row.updated_at as string,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,201 +0,0 @@
|
||||
/**
|
||||
* AI Act Compliance Types — interaction audit, risk classification, report format.
|
||||
*/
|
||||
|
||||
// ── Risk Classification (Art. 26) ──
|
||||
|
||||
export type AIActRiskLevel = 'minimal' | 'limited' | 'high-risk' | 'unacceptable';
|
||||
|
||||
export type HumanAction = 'approved' | 'denied' | 'modified' | 'none';
|
||||
|
||||
// ── Interaction Audit (Art. 12) ──
|
||||
|
||||
export interface AIInteraction {
|
||||
id: number;
|
||||
timestamp: string;
|
||||
workspaceId: string | null;
|
||||
sessionId: string | null;
|
||||
model: string;
|
||||
provider: string;
|
||||
inputTokens: number;
|
||||
outputTokens: number;
|
||||
costUsd: number;
|
||||
toolsCalled: string[];
|
||||
humanAction: HumanAction;
|
||||
riskContext: string | null;
|
||||
importedFrom: string | null;
|
||||
persona: string | null;
|
||||
// Review Critical #3 (compliance): EU AI Act Art. 12.1(a) requires recording the
|
||||
// actual inputs and outputs of the system, not just token counts. Nullable because
|
||||
// pre-existing DBs may have rows from before the columns were added.
|
||||
inputText: string | null;
|
||||
outputText: string | null;
|
||||
}
|
||||
|
||||
export interface RecordInteractionInput {
|
||||
workspaceId?: string;
|
||||
sessionId?: string;
|
||||
model: string;
|
||||
provider: string;
|
||||
inputTokens: number;
|
||||
outputTokens: number;
|
||||
costUsd: number;
|
||||
toolsCalled?: string[];
|
||||
humanAction?: HumanAction;
|
||||
riskContext?: string;
|
||||
importedFrom?: string;
|
||||
persona?: string;
|
||||
// Review Critical #3: optional because echo-mode interactions may not have meaningful
|
||||
// content. Callers on the live agent path SHOULD pass these; record() does not reject
|
||||
// absent values but the compliance status checker flags them as a gap.
|
||||
inputText?: string;
|
||||
outputText?: string;
|
||||
}
|
||||
|
||||
// ── Compliance Status ──
|
||||
|
||||
export interface ArticleStatus {
|
||||
status: 'compliant' | 'warning' | 'non-compliant';
|
||||
detail: string;
|
||||
}
|
||||
|
||||
export interface ComplianceStatus {
|
||||
overall: 'compliant' | 'warning' | 'non-compliant';
|
||||
art12Logging: ArticleStatus & { totalInteractions: number };
|
||||
art14Oversight: ArticleStatus & { humanActions: number; approvalRate: number };
|
||||
art19Retention: ArticleStatus & { oldestLogDate: string | null; retentionDays: number };
|
||||
art26Monitoring: ArticleStatus & { activeMonitors: string[] };
|
||||
art50Transparency: ArticleStatus & { modelsDisclosed: boolean };
|
||||
}
|
||||
|
||||
// ── Audit Report ──
|
||||
|
||||
export interface ModelInventoryEntry {
|
||||
model: string;
|
||||
provider: string;
|
||||
calls: number;
|
||||
inputTokens: number;
|
||||
outputTokens: number;
|
||||
costUsd: number;
|
||||
}
|
||||
|
||||
export interface OversightLogEntry {
|
||||
timestamp: string;
|
||||
action: HumanAction;
|
||||
tool: string;
|
||||
detail: string;
|
||||
user?: string;
|
||||
}
|
||||
|
||||
export interface HarvestProvenanceEntry {
|
||||
source: string;
|
||||
importedAt: string;
|
||||
itemsImported: number;
|
||||
framesCreated: number;
|
||||
}
|
||||
|
||||
export interface AuditReportRequest {
|
||||
workspaceId?: string;
|
||||
from: string;
|
||||
to: string;
|
||||
format: 'json' | 'pdf' | 'both';
|
||||
include: {
|
||||
interactions: boolean;
|
||||
oversight: boolean;
|
||||
models: boolean;
|
||||
provenance: boolean;
|
||||
riskAssessment: boolean;
|
||||
fria: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
export interface AuditReport {
|
||||
report: {
|
||||
version: string;
|
||||
generatedAt: string;
|
||||
period: { from: string; to: string };
|
||||
generatedBy: string;
|
||||
};
|
||||
workspace: {
|
||||
id: string | null;
|
||||
name: string;
|
||||
riskLevel: AIActRiskLevel;
|
||||
riskClassifiedAt: string | null;
|
||||
} | null;
|
||||
complianceStatus: ComplianceStatus;
|
||||
modelInventory: ModelInventoryEntry[];
|
||||
humanOversightLog: OversightLogEntry[];
|
||||
harvestProvenance: HarvestProvenanceEntry[];
|
||||
interactionCount: number;
|
||||
}
|
||||
|
||||
// ── Compliance Templates (M-03) ──
|
||||
//
|
||||
// Templates let a user save a preferred audit-report shape (sections + risk class +
|
||||
// org/footer overrides) and re-apply it to exports. Sections MERGE (union) with the
|
||||
// user's runtime section toggles — a template only turns sections ON, never off.
|
||||
// `riskClassification` overrides the workspace's risk level for that one report.
|
||||
// Logo support is deferred to Bucket 2 (post-launch).
|
||||
|
||||
export interface ComplianceTemplateSections {
|
||||
interactions: boolean;
|
||||
oversight: boolean;
|
||||
models: boolean;
|
||||
provenance: boolean;
|
||||
riskAssessment: boolean;
|
||||
fria: boolean;
|
||||
}
|
||||
|
||||
export interface ComplianceTemplate {
|
||||
id: number;
|
||||
name: string;
|
||||
description: string | null;
|
||||
sections: ComplianceTemplateSections;
|
||||
riskClassification: AIActRiskLevel | null;
|
||||
orgName: string | null;
|
||||
footerText: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface CreateComplianceTemplateInput {
|
||||
name: string;
|
||||
description?: string | null;
|
||||
sections: ComplianceTemplateSections;
|
||||
riskClassification?: AIActRiskLevel | null;
|
||||
orgName?: string | null;
|
||||
footerText?: string | null;
|
||||
}
|
||||
|
||||
export interface UpdateComplianceTemplateInput {
|
||||
name?: string;
|
||||
description?: string | null;
|
||||
sections?: ComplianceTemplateSections;
|
||||
riskClassification?: AIActRiskLevel | null;
|
||||
orgName?: string | null;
|
||||
footerText?: string | null;
|
||||
}
|
||||
|
||||
// ── Template auto-suggestion ──
|
||||
|
||||
export const TEMPLATE_RISK_MAP: Record<string, AIActRiskLevel> = {
|
||||
'legal-review': 'high-risk',
|
||||
'hr-management': 'high-risk',
|
||||
'recruiting': 'high-risk',
|
||||
'finance': 'high-risk',
|
||||
'insurance': 'high-risk',
|
||||
'credit-scoring': 'high-risk',
|
||||
'sales-pipeline': 'limited',
|
||||
'marketing-campaign': 'limited',
|
||||
'research-project': 'minimal',
|
||||
'code-review': 'minimal',
|
||||
'product-launch': 'limited',
|
||||
'agency-consulting': 'limited',
|
||||
'blank': 'minimal',
|
||||
'content-creation': 'minimal',
|
||||
'customer-support': 'limited',
|
||||
'data-analysis': 'limited',
|
||||
'project-management': 'minimal',
|
||||
'education': 'limited',
|
||||
'healthcare': 'high-risk',
|
||||
};
|
||||
@@ -12,7 +12,7 @@
|
||||
// Waggle-specific (non-extracted) modules below the substrate re-exports stay
|
||||
// in this package: config, multi-mind, workspace orchestration, vault, telemetry,
|
||||
// install-audit, cron-store, skill-hashes, team-sync, file-store, file-indexer,
|
||||
// memory-import, optimization-log, compliance/.
|
||||
// memory-import, optimization-log.
|
||||
|
||||
// ── Substrate re-exports from @waggle/hive-mind-core (Apache 2.0 OSS) ──
|
||||
export {
|
||||
@@ -148,17 +148,3 @@ export {
|
||||
OptimizationLogStore, OPTIMIZATION_LOG_TABLE_SQL,
|
||||
type OptimizationLogEntry, type CreateOptimizationLogInput,
|
||||
} from './optimization-log.js';
|
||||
|
||||
// ── Compliance (AI Act) — stays in @waggle/core; excluded by curated export ──
|
||||
export { InteractionStore } from './compliance/interaction-store.js';
|
||||
export { ComplianceStatusChecker } from './compliance/status-checker.js';
|
||||
export { ReportGenerator, type ReportGeneratorDeps } from './compliance/report-generator.js';
|
||||
export { ComplianceTemplateStore, KVARK_TEMPLATE_NAME } from './compliance/template-store.js';
|
||||
export { TEMPLATE_RISK_MAP } from './compliance/types.js';
|
||||
export type {
|
||||
AIActRiskLevel, HumanAction, AIInteraction, RecordInteractionInput,
|
||||
ComplianceStatus, ArticleStatus, AuditReport, AuditReportRequest,
|
||||
ModelInventoryEntry, OversightLogEntry, HarvestProvenanceEntry,
|
||||
ComplianceTemplate, ComplianceTemplateSections,
|
||||
CreateComplianceTemplateInput, UpdateComplianceTemplateInput,
|
||||
} from './compliance/types.js';
|
||||
|
||||
@@ -1,254 +0,0 @@
|
||||
/**
|
||||
* ComplianceTemplateStore unit tests (M-03)
|
||||
*
|
||||
* Covers CRUD + section merge semantics + default section fill-in + risk-class CHECK
|
||||
* constraint + deletion. Following HarvestRunStore test shape (in-memory MindDB).
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { MindDB } from '@waggle/hive-mind-core';
|
||||
import { ComplianceTemplateStore, KVARK_TEMPLATE_NAME } from '../../src/compliance/template-store.js';
|
||||
import type { ComplianceTemplateSections } from '../../src/compliance/types.js';
|
||||
|
||||
const ALL_ON: ComplianceTemplateSections = {
|
||||
interactions: true,
|
||||
oversight: true,
|
||||
models: true,
|
||||
provenance: true,
|
||||
riskAssessment: true,
|
||||
fria: true,
|
||||
};
|
||||
const ALL_OFF: ComplianceTemplateSections = {
|
||||
interactions: false,
|
||||
oversight: false,
|
||||
models: false,
|
||||
provenance: false,
|
||||
riskAssessment: false,
|
||||
fria: false,
|
||||
};
|
||||
|
||||
describe('ComplianceTemplateStore', () => {
|
||||
let db: MindDB;
|
||||
let store: ComplianceTemplateStore;
|
||||
|
||||
beforeEach(() => {
|
||||
db = new MindDB(':memory:');
|
||||
store = new ComplianceTemplateStore(db);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
db.close();
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
it('persists a template with all fields', () => {
|
||||
const t = store.create({
|
||||
name: 'KVARK enterprise',
|
||||
description: 'Full AI Act package for enterprise on-prem',
|
||||
sections: ALL_ON,
|
||||
riskClassification: 'high-risk',
|
||||
orgName: 'KVARK Sovereign',
|
||||
footerText: 'Confidential — internal only',
|
||||
});
|
||||
expect(t.id).toBeGreaterThan(0);
|
||||
expect(t.name).toBe('KVARK enterprise');
|
||||
expect(t.description).toBe('Full AI Act package for enterprise on-prem');
|
||||
expect(t.sections).toEqual(ALL_ON);
|
||||
expect(t.riskClassification).toBe('high-risk');
|
||||
expect(t.orgName).toBe('KVARK Sovereign');
|
||||
expect(t.footerText).toBe('Confidential — internal only');
|
||||
expect(t.createdAt).toBeTruthy();
|
||||
expect(t.updatedAt).toBeTruthy();
|
||||
});
|
||||
|
||||
it('defaults optional fields to null', () => {
|
||||
const t = store.create({ name: 'Bare', sections: ALL_OFF });
|
||||
expect(t.description).toBeNull();
|
||||
expect(t.riskClassification).toBeNull();
|
||||
expect(t.orgName).toBeNull();
|
||||
expect(t.footerText).toBeNull();
|
||||
});
|
||||
|
||||
it('trims whitespace from name', () => {
|
||||
const t = store.create({ name: ' Spaced ', sections: ALL_OFF });
|
||||
expect(t.name).toBe('Spaced');
|
||||
});
|
||||
|
||||
it('rejects empty name', () => {
|
||||
expect(() => store.create({ name: ' ', sections: ALL_OFF })).toThrow(/name is required/i);
|
||||
});
|
||||
|
||||
it('fills in missing section keys with defaults', () => {
|
||||
const t = store.create({
|
||||
name: 'Partial',
|
||||
// Only interactions specified; others should fall back to DEFAULT_SECTIONS.
|
||||
sections: { interactions: false } as ComplianceTemplateSections,
|
||||
});
|
||||
expect(t.sections.interactions).toBe(false);
|
||||
expect(t.sections.oversight).toBe(true); // default
|
||||
expect(t.sections.fria).toBe(false); // default
|
||||
});
|
||||
});
|
||||
|
||||
describe('getById', () => {
|
||||
it('returns null for missing id', () => {
|
||||
expect(store.getById(999)).toBeNull();
|
||||
});
|
||||
|
||||
it('round-trips a created template', () => {
|
||||
const a = store.create({ name: 'A', sections: ALL_ON, riskClassification: 'limited' });
|
||||
const b = store.getById(a.id);
|
||||
expect(b).not.toBeNull();
|
||||
expect(b?.name).toBe('A');
|
||||
expect(b?.sections).toEqual(ALL_ON);
|
||||
expect(b?.riskClassification).toBe('limited');
|
||||
});
|
||||
});
|
||||
|
||||
describe('list', () => {
|
||||
it('returns empty array when none exist', () => {
|
||||
expect(store.list()).toEqual([]);
|
||||
});
|
||||
|
||||
it('returns templates newest-updated first', async () => {
|
||||
store.create({ name: 'Old', sections: ALL_OFF });
|
||||
await new Promise(resolve => setTimeout(resolve, 1100)); // datetime('now') is second-resolution
|
||||
store.create({ name: 'New', sections: ALL_OFF });
|
||||
const list = store.list();
|
||||
expect(list).toHaveLength(2);
|
||||
expect(list[0].name).toBe('New');
|
||||
expect(list[1].name).toBe('Old');
|
||||
});
|
||||
});
|
||||
|
||||
describe('update', () => {
|
||||
it('returns null for missing id', () => {
|
||||
expect(store.update(999, { name: 'nope' })).toBeNull();
|
||||
});
|
||||
|
||||
it('updates only the fields provided', () => {
|
||||
const t = store.create({
|
||||
name: 'Orig',
|
||||
description: 'desc',
|
||||
sections: ALL_ON,
|
||||
orgName: 'Acme',
|
||||
});
|
||||
const updated = store.update(t.id, { name: 'Renamed' });
|
||||
expect(updated?.name).toBe('Renamed');
|
||||
expect(updated?.description).toBe('desc'); // preserved
|
||||
expect(updated?.sections).toEqual(ALL_ON); // preserved
|
||||
expect(updated?.orgName).toBe('Acme'); // preserved
|
||||
});
|
||||
|
||||
it('clears a field when explicitly set to null', () => {
|
||||
const t = store.create({
|
||||
name: 'T',
|
||||
sections: ALL_ON,
|
||||
orgName: 'To remove',
|
||||
footerText: 'also remove',
|
||||
});
|
||||
const updated = store.update(t.id, { orgName: null, footerText: null });
|
||||
expect(updated?.orgName).toBeNull();
|
||||
expect(updated?.footerText).toBeNull();
|
||||
});
|
||||
|
||||
it('replaces sections wholesale', () => {
|
||||
const t = store.create({ name: 'T', sections: ALL_ON });
|
||||
const updated = store.update(t.id, { sections: ALL_OFF });
|
||||
expect(updated?.sections).toEqual(ALL_OFF);
|
||||
});
|
||||
|
||||
it('rejects an empty rename', () => {
|
||||
const t = store.create({ name: 'T', sections: ALL_OFF });
|
||||
expect(() => store.update(t.id, { name: ' ' })).toThrow(/name is required/i);
|
||||
});
|
||||
|
||||
it('bumps updated_at', async () => {
|
||||
const t = store.create({ name: 'T', sections: ALL_OFF });
|
||||
await new Promise(resolve => setTimeout(resolve, 1100));
|
||||
const updated = store.update(t.id, { name: 'T2' });
|
||||
expect(updated?.updatedAt).not.toBe(t.updatedAt);
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete', () => {
|
||||
it('returns false for missing id', () => {
|
||||
expect(store.delete(999)).toBe(false);
|
||||
});
|
||||
|
||||
it('removes an existing row and returns true', () => {
|
||||
const t = store.create({ name: 'T', sections: ALL_OFF });
|
||||
expect(store.delete(t.id)).toBe(true);
|
||||
expect(store.getById(t.id)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('risk_classification CHECK constraint', () => {
|
||||
it('accepts all four AIActRiskLevel values', () => {
|
||||
for (const level of ['minimal', 'limited', 'high-risk', 'unacceptable'] as const) {
|
||||
const t = store.create({ name: `T-${level}`, sections: ALL_OFF, riskClassification: level });
|
||||
expect(t.riskClassification).toBe(level);
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects an invalid risk class at the SQL layer', () => {
|
||||
expect(() =>
|
||||
store.create({
|
||||
name: 'Bad',
|
||||
sections: ALL_OFF,
|
||||
riskClassification: 'super-dangerous' as never,
|
||||
}),
|
||||
).toThrow(); // better-sqlite3 surfaces the CHECK violation
|
||||
});
|
||||
});
|
||||
|
||||
describe('seedKvarkTemplateIfMissing (M-06)', () => {
|
||||
it('creates the KVARK template on first run', () => {
|
||||
const seeded = store.seedKvarkTemplateIfMissing();
|
||||
expect(seeded).not.toBeNull();
|
||||
expect(seeded!.name).toBe(KVARK_TEMPLATE_NAME);
|
||||
expect(seeded!.riskClassification).toBe('high-risk');
|
||||
expect(seeded!.sections.fria).toBe(true);
|
||||
expect(seeded!.orgName).toContain('KVARK');
|
||||
expect(seeded!.footerText).toContain('sovereign');
|
||||
});
|
||||
|
||||
it('is idempotent — second call returns null', () => {
|
||||
store.seedKvarkTemplateIfMissing();
|
||||
expect(store.seedKvarkTemplateIfMissing()).toBeNull();
|
||||
// Only one KVARK row exists.
|
||||
const all = store.list().filter(t => t.name === KVARK_TEMPLATE_NAME);
|
||||
expect(all).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('does not seed when the user already created a same-named template', () => {
|
||||
store.create({
|
||||
name: KVARK_TEMPLATE_NAME,
|
||||
sections: ALL_OFF,
|
||||
});
|
||||
expect(store.seedKvarkTemplateIfMissing()).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('mergeSections (static)', () => {
|
||||
it('unions template + runtime flags', () => {
|
||||
const template: ComplianceTemplateSections = { ...ALL_OFF, interactions: true, fria: true };
|
||||
const runtime: ComplianceTemplateSections = { ...ALL_OFF, oversight: true };
|
||||
const merged = ComplianceTemplateStore.mergeSections(template, runtime);
|
||||
expect(merged.interactions).toBe(true); // from template
|
||||
expect(merged.oversight).toBe(true); // from runtime
|
||||
expect(merged.fria).toBe(true); // from template
|
||||
expect(merged.models).toBe(false);
|
||||
});
|
||||
|
||||
it('never hides a section the runtime requested (union semantics)', () => {
|
||||
const merged = ComplianceTemplateStore.mergeSections(ALL_OFF, ALL_ON);
|
||||
expect(merged).toEqual(ALL_ON);
|
||||
});
|
||||
|
||||
it('never hides a section the template requested', () => {
|
||||
const merged = ComplianceTemplateStore.mergeSections(ALL_ON, ALL_OFF);
|
||||
expect(merged).toEqual(ALL_ON);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,52 +0,0 @@
|
||||
/**
|
||||
* Enterprise Packs — KVARK-conditional capability packs.
|
||||
*
|
||||
* These packs only appear when KVARK is connected (vault has 'kvark:connection').
|
||||
* They represent enterprise-grade capabilities that depend on KVARK's
|
||||
* semantic search, governance, and entity resolution subsystems.
|
||||
*
|
||||
* The skills referenced may not all exist yet — packs are metadata
|
||||
* that describe what will be available once KVARK features are fully wired.
|
||||
*/
|
||||
|
||||
export interface EnterprisePack {
|
||||
slug: string;
|
||||
display_name: string;
|
||||
description: string;
|
||||
target_roles: string;
|
||||
icon: string;
|
||||
/** Skills included in this pack */
|
||||
skills: string[];
|
||||
/** Which KVARK features this pack requires */
|
||||
kvarkRequirements: string[];
|
||||
}
|
||||
|
||||
export const ENTERPRISE_PACKS: EnterprisePack[] = [
|
||||
{
|
||||
slug: 'enterprise-document-qa',
|
||||
display_name: 'Enterprise Document Q&A',
|
||||
description: 'Ask questions across your organization\'s document library using KVARK\'s semantic search and retrieval pipeline',
|
||||
target_roles: 'knowledge-worker,analyst,researcher',
|
||||
icon: '\u{1F4DA}',
|
||||
skills: ['kvark_ask_document', 'kvark_search', 'document_summary'],
|
||||
kvarkRequirements: ['search', 'ask_document'],
|
||||
},
|
||||
{
|
||||
slug: 'compliance-workflow',
|
||||
display_name: 'Compliance Workflow',
|
||||
description: 'Governed document processing with audit trails — every action logged and traceable through KVARK\'s governance layer',
|
||||
target_roles: 'compliance,legal,admin',
|
||||
icon: '\u{1F6E1}\uFE0F',
|
||||
skills: ['kvark_action', 'audit_trail_query', 'compliance_check'],
|
||||
kvarkRequirements: ['governed_action'],
|
||||
},
|
||||
{
|
||||
slug: 'knowledge-graph-enrichment',
|
||||
display_name: 'Knowledge Graph Enrichment',
|
||||
description: 'Automatically link entities, extract relationships, and build knowledge graphs using KVARK\'s entity resolution',
|
||||
target_roles: 'researcher,analyst,knowledge-manager',
|
||||
icon: '\u{1F578}\uFE0F',
|
||||
skills: ['kvark_search', 'entity_extraction', 'relationship_mapping'],
|
||||
kvarkRequirements: ['search', 'entity_resolution'],
|
||||
},
|
||||
];
|
||||
@@ -38,8 +38,6 @@ export { seedNewSources, NEW_SOURCES } from './sources-seed.js';
|
||||
export { SecurityGate } from './security.js';
|
||||
export { isCiscoScannerAvailable, ciscoScan, getCiscoScannerVersion, resetAvailabilityCache, setExecFile } from './cisco-scanner.js';
|
||||
export type { CiscoScanResult, CiscoScanIssue } from './cisco-scanner.js';
|
||||
export { ENTERPRISE_PACKS } from './enterprise-packs.js';
|
||||
export type { EnterprisePack } from './enterprise-packs.js';
|
||||
export { MCP_SERVERS, seedMcpServers } from './mcp-registry.js';
|
||||
export type { McpServerEntry } from './mcp-registry.js';
|
||||
export { createMarketplaceMcpProvenance } from './install-security.js';
|
||||
|
||||
@@ -1,107 +0,0 @@
|
||||
/**
|
||||
* Enterprise Packs — unit tests for KVARK-conditional pack definitions
|
||||
* and the enterprise-packs endpoint behavior.
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { ENTERPRISE_PACKS, type EnterprisePack } from '../src/enterprise-packs';
|
||||
|
||||
describe('ENTERPRISE_PACKS definitions', () => {
|
||||
it('has at least 3 enterprise packs', () => {
|
||||
expect(ENTERPRISE_PACKS.length).toBeGreaterThanOrEqual(3);
|
||||
});
|
||||
|
||||
it('every pack has required fields', () => {
|
||||
for (const pack of ENTERPRISE_PACKS) {
|
||||
expect(typeof pack.slug).toBe('string');
|
||||
expect(pack.slug.length).toBeGreaterThan(0);
|
||||
|
||||
expect(typeof pack.display_name).toBe('string');
|
||||
expect(pack.display_name.length).toBeGreaterThan(0);
|
||||
|
||||
expect(typeof pack.description).toBe('string');
|
||||
expect(pack.description.length).toBeGreaterThan(0);
|
||||
|
||||
expect(typeof pack.target_roles).toBe('string');
|
||||
expect(pack.target_roles.length).toBeGreaterThan(0);
|
||||
|
||||
expect(typeof pack.icon).toBe('string');
|
||||
expect(pack.icon.length).toBeGreaterThan(0);
|
||||
|
||||
expect(Array.isArray(pack.skills)).toBe(true);
|
||||
expect(pack.skills.length).toBeGreaterThan(0);
|
||||
|
||||
expect(Array.isArray(pack.kvarkRequirements)).toBe(true);
|
||||
expect(pack.kvarkRequirements.length).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
|
||||
it('all slugs are unique', () => {
|
||||
const slugs = ENTERPRISE_PACKS.map(p => p.slug);
|
||||
expect(new Set(slugs).size).toBe(slugs.length);
|
||||
});
|
||||
|
||||
it('slugs are kebab-case (no spaces or uppercase)', () => {
|
||||
for (const pack of ENTERPRISE_PACKS) {
|
||||
expect(pack.slug).toMatch(/^[a-z0-9]+(-[a-z0-9]+)*$/);
|
||||
}
|
||||
});
|
||||
|
||||
it('every pack references at least one kvark skill', () => {
|
||||
for (const pack of ENTERPRISE_PACKS) {
|
||||
const hasKvarkSkill = pack.skills.some(s => s.startsWith('kvark_'));
|
||||
expect(hasKvarkSkill).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('contains the expected pack slugs', () => {
|
||||
const slugs = ENTERPRISE_PACKS.map(p => p.slug);
|
||||
expect(slugs).toContain('enterprise-document-qa');
|
||||
expect(slugs).toContain('compliance-workflow');
|
||||
expect(slugs).toContain('knowledge-graph-enrichment');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Enterprise packs endpoint behavior (simulated)', () => {
|
||||
// Simulate the endpoint logic without starting a real Fastify server.
|
||||
// The real endpoint uses getKvarkConfig(vault) to decide.
|
||||
|
||||
function simulateEndpoint(kvarkConfigured: boolean) {
|
||||
if (!kvarkConfigured) {
|
||||
return {
|
||||
packs: [] as EnterprisePack[],
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
it('returns packs when KVARK is configured', () => {
|
||||
const result = simulateEndpoint(true);
|
||||
expect(result.packs.length).toBeGreaterThanOrEqual(3);
|
||||
expect(result.total).toBe(ENTERPRISE_PACKS.length);
|
||||
expect(result.kvarkRequired).toBe(false);
|
||||
});
|
||||
|
||||
it('returns empty array when KVARK is not configured', () => {
|
||||
const result = simulateEndpoint(false);
|
||||
expect(result.packs).toEqual([]);
|
||||
expect(result.total).toBe(0);
|
||||
expect(result.kvarkRequired).toBe(true);
|
||||
expect(result.hint).toBeDefined();
|
||||
});
|
||||
|
||||
it('no packs leak when KVARK is absent', () => {
|
||||
const result = simulateEndpoint(false);
|
||||
expect(result.packs).toHaveLength(0);
|
||||
// Ensure the response shape is consistent
|
||||
expect(result).toHaveProperty('kvarkRequired', true);
|
||||
expect(result).toHaveProperty('total', 0);
|
||||
});
|
||||
});
|
||||
@@ -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';
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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';
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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 };
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -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:
|
||||
|
||||
@@ -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',
|
||||
]);
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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
|
||||
});
|
||||
});
|
||||
@@ -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']);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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) => {
|
||||
|
||||
@@ -212,7 +212,7 @@ export function applyPromptArgTemplate(template: readonly string[], prompt: stri
|
||||
|
||||
/**
|
||||
* Per-tool human-readable display name. Centralized so the launcher
|
||||
* UI, sidecar logs, and KVARK governance reports all agree.
|
||||
* UI and sidecar logs agree.
|
||||
*/
|
||||
export const TOOL_DISPLAY_NAMES = Object.fromEntries(
|
||||
BUILTIN_TOOL_MANIFESTS.map((m) => [m.id, m.displayName]),
|
||||
|
||||
@@ -323,7 +323,7 @@ export interface ConnectorDefinition {
|
||||
/** What the connector can do */
|
||||
capabilities: ('read' | 'write' | 'search')[];
|
||||
/** Which substrate manages this connector */
|
||||
substrate: 'waggle' | 'kvark';
|
||||
substrate: 'waggle';
|
||||
/** Agent tools this connector provides when connected */
|
||||
tools: string[];
|
||||
/** Connector-specific config */
|
||||
|
||||
Reference in New Issue
Block a user