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

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

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

View File

@@ -17,9 +17,6 @@ const mocks = vi.hoisted(() => ({
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
vi.mock('@/components/os/apps/cockpit/ComplianceDashboard', () => ({
default: () => <div data-testid="compliance-dashboard" />,
}));
import CockpitApp from './CockpitApp';

View File

@@ -4,7 +4,6 @@ import { adapter } from '@/lib/adapter';
import { DATE_LOCALE } from '@/lib/date-locale';
import type { CronJob } from '@/lib/types';
import { describeCronExpr } from '@/lib/cron-presets';
import ComplianceDashboard from './cockpit/ComplianceDashboard';
interface CockpitData {
health?: { status: string; uptime: number; services: { name: string; status: string }[] };
@@ -318,8 +317,6 @@ const CockpitApp = () => {
</div>
</div>
)}
{/* AI Act Compliance */}
<ComplianceDashboard />
</div>
);
};

View File

@@ -1,79 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { TooltipProvider } from '@/components/ui/tooltip';
const mocks = vi.hoisted(() => ({
adapter: {
listComplianceTemplates: vi.fn(),
getComplianceStatus: vi.fn(),
getHarvestSources: vi.fn(),
exportComplianceReport: vi.fn(),
exportComplianceReportPdf: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
import ComplianceDashboard from './ComplianceDashboard';
beforeEach(() => {
mocks.adapter.listComplianceTemplates.mockResolvedValue({ templates: [] });
mocks.adapter.getHarvestSources.mockResolvedValue({ sources: [] });
mocks.adapter.getComplianceStatus.mockResolvedValue({
overall: 'compliant',
art12Logging: { status: 'compliant', detail: 'ok', totalInteractions: 1 },
art14Oversight: { status: 'compliant', detail: 'ok', humanActions: 1, approvalRate: 1 },
art19Retention: { status: 'compliant', detail: 'ok', oldestLogDate: null, retentionDays: 30 },
art26Monitoring: { status: 'compliant', detail: 'ok', activeMonitors: [] },
art50Transparency: { status: 'compliant', detail: 'ok', modelsDisclosed: true },
});
});
afterEach(() => {
cleanup();
vi.clearAllMocks();
});
describe('ComplianceDashboard action names', () => {
it('exposes report option fields with stable metadata and focus rings', async () => {
render(
<TooltipProvider>
<ComplianceDashboard />
</TooltipProvider>,
);
fireEvent.click(await screen.findByRole('button', { name: /show report options/i }));
const template = screen.getByRole('combobox', { name: /template/i });
expect(template).toHaveAttribute('name', 'complianceReportTemplateId');
expect(template).toHaveAttribute('autocomplete', 'off');
expect(template.className).toContain('focus-visible:ring-2');
expect(template.className).toContain('focus-visible:ring-[var(--focus-ring)]');
const from = screen.getByLabelText(/^from$/i);
expect(from).toHaveAttribute('name', 'complianceReportFromDate');
expect(from).toHaveAttribute('autocomplete', 'off');
expect(from.className).toContain('focus-visible:ring-2');
expect(from.className).toContain('focus-visible:ring-[var(--focus-ring)]');
const to = screen.getByLabelText(/^to$/i);
expect(to).toHaveAttribute('name', 'complianceReportToDate');
expect(to).toHaveAttribute('autocomplete', 'off');
expect(to.className).toContain('focus-visible:ring-2');
expect(to.className).toContain('focus-visible:ring-[var(--focus-ring)]');
});
it('uses a sequential heading and names report actions', async () => {
render(
<TooltipProvider>
<ComplianceDashboard />
</TooltipProvider>,
);
expect(await screen.findByRole('button', { name: /refresh compliance status/i })).toBeInTheDocument();
expect(screen.getByRole('heading', { level: 3, name: /eu ai act compliance/i })).toBeInTheDocument();
expect(screen.getByRole('button', { name: /show report options/i })).toBeInTheDocument();
expect(screen.getByRole('button', { name: /download compliance json report/i })).toBeInTheDocument();
expect(screen.getByRole('button', { name: /download compliance pdf report/i })).toBeInTheDocument();
});
});

View File

@@ -1,572 +0,0 @@
/**
* ComplianceDashboard — AI Act compliance status card for CockpitApp.
*
* Shows real-time compliance status per EU AI Act article,
* workspace risk badges, and audit report export button.
*/
import { useState, useEffect, useCallback } from 'react';
import {
Shield, CheckCircle2, AlertTriangle, XCircle, Download,
Loader2, Activity, Eye, Clock, Database, RefreshCw, HardDrive, FileText, Settings as SettingsIcon,
LayoutTemplate,
} from 'lucide-react';
import { adapter } from '@/lib/adapter';
import { useRevalidateOnError } from '@/hooks/useRevalidateOnError';
import { HintTooltip } from '@/components/ui/hint-tooltip';
import { ComplianceTemplateModal, type ComplianceTemplate, type ComplianceTemplateSections } from './ComplianceTemplateModal';
interface ArticleStatus {
status: 'compliant' | 'warning' | 'non-compliant';
detail: string;
}
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 };
}
interface HarvestSourceSummary {
id: number;
source: string;
displayName: string;
lastSyncedAt: string | null;
itemsImported: number;
framesCreated: number;
}
const STATUS_ICONS = {
compliant: <CheckCircle2 className="w-3 h-3 text-emerald-400" />,
warning: <AlertTriangle className="w-3 h-3 text-amber-400" />,
'non-compliant': <XCircle className="w-3 h-3 text-destructive" />,
};
const STATUS_COLORS = {
compliant: 'text-emerald-400 bg-emerald-500/10 border-emerald-500/20',
warning: 'text-amber-400 bg-amber-500/10 border-amber-500/20',
'non-compliant': 'text-destructive bg-destructive/10 border-destructive/20',
};
function formatRelative(iso: string | null): string {
if (!iso) return 'never';
const then = new Date(iso).getTime();
if (!Number.isFinite(then)) return 'unknown';
const diffMs = Date.now() - then;
if (diffMs < 0) return 'just now';
const sec = Math.round(diffMs / 1000);
if (sec < 60) return `${sec}s ago`;
const min = Math.round(sec / 60);
if (min < 60) return `${min}m ago`;
const hr = Math.round(min / 60);
if (hr < 24) return `${hr}h ago`;
const day = Math.round(hr / 24);
if (day < 30) return `${day}d ago`;
const mo = Math.round(day / 30);
if (mo < 12) return `${mo}mo ago`;
return `${Math.round(mo / 12)}y ago`;
}
const ComplianceDashboard = () => {
const [status, setStatus] = useState<ComplianceStatus | null>(null);
const [harvestSources, setHarvestSources] = useState<HarvestSourceSummary[]>([]);
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [exporting, setExporting] = useState(false);
const [exportingPdf, setExportingPdf] = useState(false);
const [lastRefreshed, setLastRefreshed] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [exportNotice, setExportNotice] = useState<string | null>(null);
// M-04: report options. Defaults to the last 30 days of data with all
// major sections on. FRIA (Fundamental Rights Impact Assessment) is off
// by default — it's only relevant for high-risk systems.
const [showOptions, setShowOptions] = useState(false);
const defaultFrom = () => new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
const defaultTo = () => new Date().toISOString().split('T')[0];
const [fromDate, setFromDate] = useState<string>(defaultFrom());
const [toDate, setToDate] = useState<string>(defaultTo());
const [includeInteractions, setIncludeInteractions] = useState(true);
const [includeOversight, setIncludeOversight] = useState(true);
const [includeModels, setIncludeModels] = useState(true);
const [includeProvenance, setIncludeProvenance] = useState(true);
const [includeRiskAssessment, setIncludeRiskAssessment] = useState(true);
const [includeFria, setIncludeFria] = useState(false);
// M-03: template picker. When a template is chosen, its sections MERGE (union)
// with the runtime toggles above — a template can only add sections, never hide
// ones the user toggled on. Risk class + org name + footer text from the template
// flow through the export body.
const [templates, setTemplates] = useState<ComplianceTemplate[]>([]);
const [templateId, setTemplateId] = useState<number | null>(null);
const [templatesModalOpen, setTemplatesModalOpen] = useState(false);
const [templatesErrored, setTemplatesErrored] = useState(false);
const refreshTemplates = useCallback(async () => {
try {
const { templates: list } = await adapter.listComplianceTemplates();
setTemplates(list as ComplianceTemplate[]);
setTemplatesErrored(false);
} catch {
// Non-fatal: leave templates empty and let the picker show "no templates".
// P1b D3 plus-clause: flagged errored so the empty list is no longer
// cached as valid for the session — revalidates on focus/connect-settled.
setTemplates([]);
setTemplatesErrored(true);
}
}, []);
useEffect(() => {
void refreshTemplates();
}, [refreshTemplates]);
useRevalidateOnError(templatesErrored, () => { void refreshTemplates(); });
const selectedTemplate = templateId !== null
? templates.find(t => t.id === templateId) ?? null
: null;
const mergeSections = (
template: ComplianceTemplateSections,
runtime: ComplianceTemplateSections,
): ComplianceTemplateSections => ({
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,
});
const buildExportRequest = useCallback(() => {
const runtime: ComplianceTemplateSections = {
interactions: includeInteractions,
oversight: includeOversight,
models: includeModels,
provenance: includeProvenance,
riskAssessment: includeRiskAssessment,
fria: includeFria,
};
const include = selectedTemplate
? mergeSections(selectedTemplate.sections, runtime)
: runtime;
return {
from: fromDate,
to: toDate,
format: 'json' as const,
include,
// Template-sourced overrides travel in the body so the server can use them
// when rendering the PDF header/footer. /export (JSON) ignores these today
// but accepts them without error.
templateOrgName: selectedTemplate?.orgName ?? null,
templateFooterText: selectedTemplate?.footerText ?? null,
templateRiskClassification: selectedTemplate?.riskClassification ?? null,
};
}, [fromDate, toDate, includeInteractions, includeOversight, includeModels, includeProvenance, includeRiskAssessment, includeFria, selectedTemplate]);
const fetchStatus = useCallback(async ({ silent = false }: { silent?: boolean } = {}) => {
if (!silent) setRefreshing(true);
setError(null);
try {
const [statusData, harvestData] = await Promise.all([
adapter.getComplianceStatus(),
adapter.getHarvestSources().catch(() => ({ sources: [] })),
]);
setStatus(statusData);
setHarvestSources(
Array.isArray(harvestData?.sources) ? harvestData.sources as HarvestSourceSummary[] : [],
);
setLastRefreshed(new Date().toISOString());
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load compliance status');
} finally {
setLoading(false);
setRefreshing(false);
}
}, []);
useEffect(() => {
fetchStatus({ silent: true });
}, [fetchStatus]);
const handleExport = async () => {
setExporting(true);
setExportNotice(null);
try {
const request = buildExportRequest();
const report = await adapter.exportComplianceReport(request);
// Download as JSON file
const blob = new Blob([JSON.stringify(report, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `waggle-compliance-report-${request.from}-to-${request.to}.json`;
a.click();
URL.revokeObjectURL(url);
setExportNotice('JSON report downloaded');
} catch (err) {
setExportNotice(err instanceof Error ? `Export failed: ${err.message}` : 'Export failed');
} finally {
setExporting(false);
// Clear the toast after 4s so the surface stays clean
setTimeout(() => setExportNotice(null), 4000);
}
};
// M-02 / M-04: download the same AuditReport rendered through pdfmake
// as a Hive-DS-styled boardroom PDF. Uses the current Report Options
// state so users can scope the output.
const handleExportPdf = async () => {
setExportingPdf(true);
setExportNotice(null);
try {
const request = buildExportRequest();
const blob = await adapter.exportComplianceReportPdf(request);
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `ai-act-compliance-${request.from}-to-${request.to}.pdf`;
a.click();
URL.revokeObjectURL(url);
setExportNotice('PDF report downloaded');
} catch (err) {
setExportNotice(err instanceof Error ? `PDF export failed: ${err.message}` : 'PDF export failed');
} finally {
setExportingPdf(false);
setTimeout(() => setExportNotice(null), 4000);
}
};
if (loading) {
return (
<div className="p-4 rounded-xl bg-secondary/30 border border-border/30">
<div className="flex items-center gap-2 mb-3">
<Shield className="w-4 h-4 text-muted-foreground" />
<h3 className="text-xs font-display font-semibold text-foreground">EU AI Act Compliance</h3>
</div>
<Loader2 className="w-4 h-4 animate-spin text-muted-foreground mx-auto" />
</div>
);
}
if (!status) {
return (
<div className="p-4 rounded-xl bg-secondary/30 border border-border/30">
<div className="flex items-center gap-2">
<Shield className="w-4 h-4 text-muted-foreground" />
<h3 className="text-xs font-display font-semibold text-foreground">EU AI Act Compliance</h3>
</div>
{error ? (
<p className="text-[11px] text-destructive mt-2">{error}</p>
) : (
<p className="text-[11px] text-muted-foreground mt-2">Compliance monitoring initializing...</p>
)}
<button
onClick={() => fetchStatus()}
disabled={refreshing}
className="mt-2 text-[11px] text-honey hover:text-honey/80 transition-colors disabled:opacity-50"
>
{refreshing ? 'Retrying…' : 'Retry'}
</button>
</div>
);
}
// When no interactions have been logged yet, per-article numeric metrics
// are meaningless — show an em-dash so the user doesn't read "0 oversight
// actions" as a compliance issue. Article status badges still reflect
// the real state.
const hasInteractions = (status.art12Logging?.totalInteractions ?? 0) > 0;
const articles = [
{
key: 'art12',
label: 'Art. 12 Logging',
data: status.art12Logging,
icon: <Activity className="w-3 h-3" />,
metric: hasInteractions ? status.art12Logging.totalInteractions.toLocaleString() : '—',
hint: hasInteractions ? 'interactions logged' : 'no interactions yet',
},
{
key: 'art14',
label: 'Art. 14 Oversight',
data: status.art14Oversight,
icon: <Eye className="w-3 h-3" />,
metric: hasInteractions ? `${status.art14Oversight.humanActions}` : '—',
hint: hasInteractions ? 'human actions' : 'awaiting activity',
},
{
key: 'art19',
label: 'Art. 19 Retention',
data: status.art19Retention,
icon: <Clock className="w-3 h-3" />,
metric: (status.art19Retention?.retentionDays ?? 0) > 0 ? `${status.art19Retention.retentionDays}d` : '∞',
hint: (status.art19Retention?.retentionDays ?? 0) > 0 ? 'days retained' : 'permanent',
},
{
key: 'art26',
label: 'Art. 26 Monitor',
data: status.art26Monitoring,
icon: <Database className="w-3 h-3" />,
metric: `${status.art26Monitoring?.activeMonitors?.length ?? 0}`,
hint: 'active monitors',
},
];
const totalFramesHarvested = harvestSources.reduce((acc, s) => acc + (s.framesCreated ?? 0), 0);
const mostRecentSync = harvestSources
.map(s => s.lastSyncedAt)
.filter((v): v is string => Boolean(v))
.sort()
.pop() ?? null;
return (
<div className="p-4 rounded-xl bg-secondary/30 border border-border/30">
{/* Header */}
<div className="flex items-center justify-between mb-3">
<div className="flex items-center gap-2 min-w-0">
<Shield className="w-4 h-4 text-honey shrink-0" />
<h3 className="text-xs font-display font-semibold text-foreground">EU AI Act Compliance</h3>
{lastRefreshed && (
<span className="text-[11px] text-muted-foreground truncate">
· updated {formatRelative(lastRefreshed)}
</span>
)}
</div>
<div className="flex items-center gap-1.5 shrink-0">
<HintTooltip
content={
status.overall === 'warning'
? 'One or more articles need attention — hover each card for details. Most commonly: no interactions logged yet (Article 12).'
: status.overall === 'non-compliant'
? 'Critical gap — at least one article requirement is unmet. See per-article cards below.'
: 'All monitored articles meet their requirements.'
}
>
<span
className={`px-2 py-0.5 rounded-full text-[11px] font-display font-semibold border ${STATUS_COLORS[status.overall]}`}
tabIndex={0}
>
{status.overall.toUpperCase()}
</span>
</HintTooltip>
<HintTooltip content="Refresh compliance status">
<button
type="button"
onClick={() => fetchStatus()}
disabled={refreshing}
aria-label="Refresh compliance status"
className="p-1 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted/50 transition-colors disabled:opacity-50"
>
<RefreshCw className={`w-3.5 h-3.5 ${refreshing ? 'animate-spin' : ''}`} />
</button>
</HintTooltip>
<HintTooltip content="Report options">
<button
type="button"
onClick={() => setShowOptions(s => !s)}
aria-label={showOptions ? 'Hide report options' : 'Show report options'}
aria-expanded={showOptions}
className={`p-1 rounded-lg transition-colors ${
showOptions ? 'text-honey bg-primary/10' : 'text-muted-foreground hover:text-foreground hover:bg-muted/50'
}`}
>
<SettingsIcon className="w-3.5 h-3.5" />
</button>
</HintTooltip>
<HintTooltip content="Download JSON report">
<button
type="button"
onClick={handleExport}
disabled={exporting || exportingPdf}
aria-label="Download compliance JSON report"
className="p-1 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted/50 transition-colors disabled:opacity-50"
>
{exporting ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Download className="w-3.5 h-3.5" />}
</button>
</HintTooltip>
<HintTooltip content="Download PDF report (boardroom-styled)">
<button
type="button"
onClick={handleExportPdf}
disabled={exporting || exportingPdf}
aria-label="Download compliance PDF report"
className="p-1 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted/50 transition-colors disabled:opacity-50"
>
{exportingPdf ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <FileText className="w-3.5 h-3.5" />}
</button>
</HintTooltip>
</div>
</div>
{/* M-04: report options — expanded when the user clicks the gear */}
{showOptions && (
<div className="mb-3 p-3 rounded-lg bg-background/40 border border-border/30 space-y-2">
{/* M-03: template picker + manage button */}
<div className="flex items-end gap-2">
<div className="flex-1 min-w-0">
<label htmlFor="compliance-report-template" className="text-[10px] uppercase tracking-wide text-muted-foreground flex items-center gap-1">
<LayoutTemplate className="w-3 h-3" />
Template
</label>
<select
id="compliance-report-template"
name="complianceReportTemplateId"
autoComplete="off"
value={templateId ?? ''}
onChange={e => setTemplateId(e.target.value ? Number(e.target.value) : null)}
className="w-full px-2 py-1 mt-0.5 bg-background/60 border border-border/40 rounded text-[11px] text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] focus-visible:ring-offset-2 focus-visible:ring-offset-background"
>
<option value="">No template (runtime toggles only)</option>
{templates.map(t => (
<option key={t.id} value={t.id}>
{t.name}
{t.riskClassification ? ` · ${t.riskClassification}` : ''}
</option>
))}
</select>
</div>
<HintTooltip content="Create or edit templates">
<button
onClick={() => setTemplatesModalOpen(true)}
className="px-2 py-1 rounded text-[11px] text-muted-foreground hover:text-foreground hover:bg-muted/50 border border-border/40 transition-colors shrink-0"
>
Manage
</button>
</HintTooltip>
</div>
{selectedTemplate && (
<p className="text-[10px] text-muted-foreground/80 leading-tight">
Template sections merge with runtime toggles (union). Template can add sections, never hide them.
</p>
)}
<div className="grid grid-cols-2 gap-2">
<div>
<label htmlFor="compliance-report-from-date" className="text-[10px] uppercase tracking-wide text-muted-foreground">From</label>
<input
id="compliance-report-from-date"
name="complianceReportFromDate"
type="date"
autoComplete="off"
value={fromDate}
onChange={e => setFromDate(e.target.value)}
max={toDate}
className="w-full px-2 py-1 mt-0.5 bg-background/60 border border-border/40 rounded text-[11px] text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] focus-visible:ring-offset-2 focus-visible:ring-offset-background"
/>
</div>
<div>
<label htmlFor="compliance-report-to-date" className="text-[10px] uppercase tracking-wide text-muted-foreground">To</label>
<input
id="compliance-report-to-date"
name="complianceReportToDate"
type="date"
autoComplete="off"
value={toDate}
onChange={e => setToDate(e.target.value)}
min={fromDate}
max={defaultTo()}
className="w-full px-2 py-1 mt-0.5 bg-background/60 border border-border/40 rounded text-[11px] text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] focus-visible:ring-offset-2 focus-visible:ring-offset-background"
/>
</div>
</div>
<div className="flex flex-wrap gap-1.5 pt-1">
{([
['Interactions', includeInteractions, setIncludeInteractions],
['Oversight', includeOversight, setIncludeOversight],
['Models', includeModels, setIncludeModels],
['Provenance', includeProvenance, setIncludeProvenance],
['Risk', includeRiskAssessment, setIncludeRiskAssessment],
['FRIA', includeFria, setIncludeFria],
] as const).map(([label, on, setOn]) => (
<button
key={label}
onClick={() => setOn(!on)}
className={`px-2 py-0.5 rounded text-[10px] border transition-colors ${
on
? 'bg-primary/20 text-honey border-primary/30'
: 'bg-background/30 text-muted-foreground border-border/30 hover:text-foreground'
}`}
>
{label}
</button>
))}
</div>
</div>
)}
{/* Stale-data + export notice strip */}
{(error || exportNotice) && (
<div className={`mb-2 px-2 py-1 rounded text-[11px] ${
error ? 'bg-destructive/10 text-destructive' : 'bg-emerald-500/10 text-emerald-400'
}`}>
{error ?? exportNotice}
</div>
)}
{/* Article status grid */}
<div className="grid grid-cols-2 gap-2">
{articles.map(art => (
<HintTooltip key={art.key} content={art.data.detail}>
<div
className="p-2 rounded-lg bg-background/50 border border-border/20"
tabIndex={0}
>
<div className="flex items-center justify-between mb-1">
<div className="flex items-center gap-1 text-muted-foreground">
{art.icon}
<span className="text-[11px]">{art.label}</span>
</div>
{STATUS_ICONS[art.data.status]}
</div>
<p className="text-sm font-display font-semibold text-foreground">{art.metric}</p>
<p className="text-[10px] text-muted-foreground/70 truncate">{art.hint}</p>
</div>
</HintTooltip>
))}
</div>
{/* Art. 50 - model transparency */}
<div className="flex items-center justify-between mt-2 px-1">
<span className="text-[11px] text-muted-foreground">Art. 50 Model Transparency</span>
{STATUS_ICONS[status.art50Transparency.status]}
</div>
<ComplianceTemplateModal
open={templatesModalOpen}
onClose={() => setTemplatesModalOpen(false)}
onChange={() => {
void refreshTemplates();
}}
/>
{/* Harvest provenance — shows the actual imported memory surface so
the dashboard is not a wall of zeros when no chat interactions
have been logged yet. */}
{harvestSources.length > 0 && (
<div className="mt-3 pt-3 border-t border-border/20">
<div className="flex items-center justify-between mb-1.5">
<div className="flex items-center gap-1.5 text-muted-foreground">
<HardDrive className="w-3 h-3" />
<span className="text-[11px] font-display font-medium">Data Provenance</span>
</div>
<span className="text-[11px] text-muted-foreground">
{harvestSources.length} source{harvestSources.length === 1 ? '' : 's'}
{' · '}{totalFramesHarvested.toLocaleString()} frames
</span>
</div>
<p className="text-[11px] text-muted-foreground/80">
Last sync {formatRelative(mostRecentSync)}
{harvestSources.length > 0 && (
<> · {harvestSources.slice(0, 3).map(s => s.displayName).join(', ')}</>
)}
{harvestSources.length > 3 && <> +{harvestSources.length - 3}</>}
</p>
</div>
)}
</div>
);
};
export default ComplianceDashboard;

View File

@@ -1,427 +0,0 @@
/**
* ComplianceTemplateModal — list/create/edit compliance report templates (M-03).
*
* Lives next to ComplianceDashboard so it can be opened via the dashboard's
* "Edit templates" action. Templates are stored on the personal mind via the
* CRUD routes at /api/compliance/templates.
*
* Keeps UI state local (useState) rather than pulling in TanStack Query to
* match the rest of CockpitApp's patterns.
*/
import { useState, useEffect, useCallback } from 'react';
import { X, Plus, Loader2, Trash2, Pencil } from 'lucide-react';
import { adapter } from '@/lib/adapter';
import { useFocusTrap } from '@/hooks/useFocusTrap';
import { ApprovalModal, type ApprovalRequest } from '@/components/ui/approval-modal';
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: 'minimal' | 'limited' | 'high-risk' | 'unacceptable' | null;
orgName: string | null;
footerText: string | null;
createdAt: string;
updatedAt: string;
}
const ALL_ON: ComplianceTemplateSections = {
interactions: true,
oversight: true,
models: true,
provenance: true,
riskAssessment: true,
fria: false,
};
const SECTION_LABELS: { key: keyof ComplianceTemplateSections; label: string }[] = [
{ key: 'interactions', label: 'Interactions' },
{ key: 'oversight', label: 'Oversight' },
{ key: 'models', label: 'Models' },
{ key: 'provenance', label: 'Provenance' },
{ key: 'riskAssessment', label: 'Risk' },
{ key: 'fria', label: 'FRIA' },
];
interface ComplianceTemplateModalProps {
open: boolean;
onClose: () => void;
onChange?: () => void;
}
export function ComplianceTemplateModal({ open, onClose, onChange }: ComplianceTemplateModalProps) {
// A11y (WCAG 2.1.1/2.4.3): Escape closes, Tab is trapped, focus restores on close.
const dialogRef = useFocusTrap<HTMLDivElement>(open, onClose);
const [templates, setTemplates] = useState<ComplianceTemplate[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [editing, setEditing] = useState<ComplianceTemplate | null>(null);
const [isCreating, setIsCreating] = useState(false);
const [saving, setSaving] = useState(false);
const [pendingDelete, setPendingDelete] = useState<ComplianceTemplate | null>(null);
const [deletingId, setDeletingId] = useState<number | null>(null);
const [formName, setFormName] = useState('');
const [formDescription, setFormDescription] = useState('');
const [formSections, setFormSections] = useState<ComplianceTemplateSections>(ALL_ON);
const [formRisk, setFormRisk] = useState<ComplianceTemplate['riskClassification']>(null);
const [formOrgName, setFormOrgName] = useState('');
const [formFooter, setFormFooter] = useState('');
const refresh = useCallback(async () => {
setLoading(true);
setError(null);
try {
const { templates: list } = await adapter.listComplianceTemplates();
setTemplates(list as ComplianceTemplate[]);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load templates');
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
if (open) void refresh();
}, [open, refresh]);
const startCreate = () => {
setEditing(null);
setIsCreating(true);
setFormName('');
setFormDescription('');
setFormSections({ ...ALL_ON });
setFormRisk(null);
setFormOrgName('');
setFormFooter('');
};
const startEdit = (t: ComplianceTemplate) => {
setIsCreating(false);
setEditing(t);
setFormName(t.name);
setFormDescription(t.description ?? '');
setFormSections({ ...t.sections });
setFormRisk(t.riskClassification);
setFormOrgName(t.orgName ?? '');
setFormFooter(t.footerText ?? '');
};
const cancelForm = () => {
setIsCreating(false);
setEditing(null);
};
const save = async () => {
if (!formName.trim()) {
setError('Template name is required');
return;
}
setSaving(true);
setError(null);
try {
const payload = {
name: formName.trim(),
description: formDescription.trim() || null,
sections: formSections,
riskClassification: formRisk,
orgName: formOrgName.trim() || null,
footerText: formFooter.trim() || null,
};
if (editing) {
await adapter.updateComplianceTemplate(editing.id, payload);
} else {
await adapter.createComplianceTemplate(payload);
}
await refresh();
cancelForm();
onChange?.();
} catch (err) {
setError(err instanceof Error ? err.message : 'Save failed');
} finally {
setSaving(false);
}
};
const remove = async (t: ComplianceTemplate) => {
setPendingDelete(t);
};
const deleteApproval: ApprovalRequest | null = pendingDelete
? {
action: `Delete compliance template: ${pendingDelete.name}`,
riskLevel: 'medium',
scope: [
'Deletes this saved report shape.',
'Existing generated reports are not deleted.',
'This cannot be undone.',
],
}
: null;
const confirmDelete = async () => {
if (!pendingDelete) return;
const target = pendingDelete;
setError(null);
setDeletingId(target.id);
try {
await adapter.deleteComplianceTemplate(target.id);
if (editing?.id === target.id) cancelForm();
setPendingDelete(null);
await refresh();
onChange?.();
} catch (err) {
setError(err instanceof Error ? err.message : 'Delete failed');
} finally {
setDeletingId(null);
}
};
if (!open) return null;
const showForm = isCreating || editing !== null;
return (
<div
ref={dialogRef}
tabIndex={-1}
className="fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm focus:outline-none"
role="dialog"
aria-modal="true"
aria-labelledby="compliance-template-modal-title"
>
<div className="w-full max-w-2xl max-h-[85vh] overflow-y-auto rounded-xl bg-secondary border border-border/40 shadow-2xl">
{/* Header */}
<div className="flex items-center justify-between px-4 py-3 border-b border-border/30">
<h3 id="compliance-template-modal-title" className="text-sm font-display font-semibold text-foreground">Compliance report templates</h3>
<button
onClick={onClose}
className="p-1 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted/50 transition-colors"
aria-label="Close"
>
<X className="w-4 h-4" />
</button>
</div>
{error && (
<div className="mx-4 mt-3 px-2 py-1 rounded text-[11px] bg-destructive/10 text-destructive">
{error}
</div>
)}
{/* Template list */}
<div className="px-4 py-3 space-y-2">
{loading ? (
<div className="flex justify-center py-6">
<Loader2 className="w-4 h-4 animate-spin text-muted-foreground" />
</div>
) : templates.length === 0 ? (
<p className="text-[12px] text-muted-foreground text-center py-4">
No templates yet. Create one to save a preferred report shape.
</p>
) : (
templates.map(t => (
<div
key={t.id}
className={`p-2.5 rounded-lg border transition-colors ${
editing?.id === t.id
? 'bg-primary/10 border-primary/30'
: 'bg-background/40 border-border/20 hover:border-border/40'
}`}
>
<div className="flex items-start justify-between gap-2">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5">
<span className="text-[12px] font-display font-semibold text-foreground truncate">
{t.name}
</span>
{t.riskClassification && (
<span className="px-1.5 py-0.5 rounded text-[10px] bg-amber-500/10 text-amber-400 border border-amber-500/20">
{t.riskClassification}
</span>
)}
</div>
{t.description && (
<p className="text-[11px] text-muted-foreground/80 mt-0.5 truncate">{t.description}</p>
)}
<p className="text-[10px] text-muted-foreground/60 mt-1">
{SECTION_LABELS.filter(s => t.sections[s.key]).map(s => s.label).join(' · ') || 'no sections'}
</p>
</div>
<div className="flex items-center gap-1 shrink-0">
<button
onClick={() => startEdit(t)}
className="p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted/50 transition-colors"
aria-label={`Edit ${t.name}`}
>
<Pencil className="w-3 h-3" />
</button>
<button
onClick={() => remove(t)}
className="p-1 rounded text-muted-foreground hover:text-destructive hover:bg-destructive/10 transition-colors"
aria-label={`Delete ${t.name}`}
>
<Trash2 className="w-3 h-3" />
</button>
</div>
</div>
</div>
))
)}
{!showForm && (
<button
onClick={startCreate}
className="w-full flex items-center justify-center gap-1.5 py-2 rounded-lg text-[11px] text-muted-foreground hover:text-foreground border border-dashed border-border/40 hover:border-border/60 transition-colors"
>
<Plus className="w-3 h-3" />
New template
</button>
)}
</div>
{/* Create/Edit form */}
{showForm && (
<div className="px-4 pb-4 space-y-2 border-t border-border/30 pt-3">
<h4 className="text-[11px] font-display font-semibold uppercase tracking-wide text-muted-foreground">
{editing ? `Edit "${editing.name}"` : 'New template'}
</h4>
<div>
<label htmlFor="compliance-template-name" className="text-[10px] uppercase tracking-wide text-muted-foreground">Name</label>
<input
id="compliance-template-name"
name="complianceTemplateName"
type="text"
autoComplete="off"
value={formName}
onChange={e => setFormName(e.target.value)}
placeholder="e.g. KVARK enterprise audit"
className="w-full px-2 py-1 mt-0.5 bg-background/60 border border-border/40 rounded text-[11px] text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] focus-visible:ring-offset-2 focus-visible:ring-offset-background"
/>
</div>
<div>
<label htmlFor="compliance-template-description" className="text-[10px] uppercase tracking-wide text-muted-foreground">Description</label>
<input
id="compliance-template-description"
name="complianceTemplateDescription"
type="text"
autoComplete="off"
value={formDescription}
onChange={e => setFormDescription(e.target.value)}
placeholder="optional"
className="w-full px-2 py-1 mt-0.5 bg-background/60 border border-border/40 rounded text-[11px] text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] focus-visible:ring-offset-2 focus-visible:ring-offset-background"
/>
</div>
<div>
<label className="text-[10px] uppercase tracking-wide text-muted-foreground">Sections</label>
<div className="flex flex-wrap gap-1.5 mt-0.5">
{SECTION_LABELS.map(({ key, label }) => (
<button
key={key}
onClick={() => setFormSections(s => ({ ...s, [key]: !s[key] }))}
type="button"
className={`px-2 py-0.5 rounded text-[10px] border transition-colors ${
formSections[key]
? 'bg-primary/20 text-honey border-primary/30'
: 'bg-background/30 text-muted-foreground border-border/30 hover:text-foreground'
}`}
>
{label}
</button>
))}
</div>
</div>
<div className="grid grid-cols-2 gap-2">
<div>
<label htmlFor="compliance-template-risk-class" className="text-[10px] uppercase tracking-wide text-muted-foreground">Risk class</label>
<select
id="compliance-template-risk-class"
name="complianceTemplateRiskClass"
autoComplete="off"
value={formRisk ?? ''}
onChange={e => setFormRisk((e.target.value || null) as ComplianceTemplate['riskClassification'])}
className="w-full px-2 py-1 mt-0.5 bg-background/60 border border-border/40 rounded text-[11px] text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] focus-visible:ring-offset-2 focus-visible:ring-offset-background"
>
<option value="">inherit from workspace</option>
<option value="minimal">minimal</option>
<option value="limited">limited</option>
<option value="high-risk">high-risk</option>
<option value="unacceptable">unacceptable</option>
</select>
</div>
<div>
<label htmlFor="compliance-template-org-name" className="text-[10px] uppercase tracking-wide text-muted-foreground">Org name</label>
<input
id="compliance-template-org-name"
name="complianceTemplateOrgName"
type="text"
autoComplete="organization"
value={formOrgName}
onChange={e => setFormOrgName(e.target.value)}
placeholder="optional"
className="w-full px-2 py-1 mt-0.5 bg-background/60 border border-border/40 rounded text-[11px] text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] focus-visible:ring-offset-2 focus-visible:ring-offset-background"
/>
</div>
</div>
<div>
<label htmlFor="compliance-template-footer-text" className="text-[10px] uppercase tracking-wide text-muted-foreground">Footer text</label>
<input
id="compliance-template-footer-text"
name="complianceTemplateFooterText"
type="text"
autoComplete="off"
value={formFooter}
onChange={e => setFormFooter(e.target.value)}
placeholder="e.g. Confidential — internal only"
className="w-full px-2 py-1 mt-0.5 bg-background/60 border border-border/40 rounded text-[11px] text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] focus-visible:ring-offset-2 focus-visible:ring-offset-background"
/>
</div>
<div className="flex justify-end gap-2 pt-2">
<button
onClick={cancelForm}
disabled={saving}
className="px-3 py-1 rounded-lg text-[11px] text-muted-foreground hover:text-foreground hover:bg-muted/50 transition-colors disabled:opacity-50"
>
Cancel
</button>
<button
onClick={save}
disabled={saving || !formName.trim()}
className="px-3 py-1 rounded-lg text-[11px] bg-primary text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50 flex items-center gap-1"
>
{saving && <Loader2 className="w-3 h-3 animate-spin" />}
{editing ? 'Save' : 'Create'}
</button>
</div>
</div>
)}
</div>
<ApprovalModal
request={deleteApproval}
approveLabel={deletingId !== null ? 'Deleting...' : 'Delete template'}
busy={deletingId !== null}
onApprove={() => { void confirmDelete(); }}
onCancel={() => {
if (deletingId === null) setPendingDelete(null);
}}
/>
</div>
);
}

View File

@@ -3833,80 +3833,6 @@ class LocalAdapter {
return res.json();
}
// --- Compliance ---
async getComplianceStatus(workspaceId?: string): Promise<any> {
const url = workspaceId ? `/api/compliance/status?workspaceId=${workspaceId}` : '/api/compliance/status';
const res = await this.fetch(url);
return res.json();
}
/**
* M-02: download an AI-Act-compliance PDF. Accepts the same request
* shape as exportComplianceReport. Returns a Blob so the caller can
* trigger a browser download via URL.createObjectURL.
*/
async exportComplianceReportPdf(request: any): Promise<Blob> {
const res = await this.fetch('/api/compliance/export-pdf', {
method: 'POST', body: JSON.stringify(request),
});
if (!res.ok) {
const body = await res.json().catch(() => ({ error: res.statusText }));
throw new Error(body.error ?? `PDF export failed (${res.status})`);
}
return res.blob();
}
async exportComplianceReport(request: any): Promise<any> {
const res = await this.fetch('/api/compliance/export', { method: 'POST', body: JSON.stringify(request) });
return res.json();
}
async getComplianceInteractions(limit?: number): Promise<any> {
const res = await this.fetch(`/api/compliance/interactions?limit=${limit ?? 20}`);
return res.json();
}
async getComplianceModels(): Promise<any> {
const res = await this.fetch('/api/compliance/models');
return res.json();
}
// --- Compliance templates (M-03) ---
async listComplianceTemplates(): Promise<{ templates: any[] }> {
const res = await this.fetch('/api/compliance/templates');
return res.json();
}
async createComplianceTemplate(input: any): Promise<{ template: any }> {
const res = await this.fetch('/api/compliance/templates', {
method: 'POST', body: JSON.stringify(input),
});
if (!res.ok) {
const body = await res.json().catch(() => ({ error: res.statusText }));
throw new Error(body.error ?? `Create template failed (${res.status})`);
}
return res.json();
}
async updateComplianceTemplate(id: number, patch: any): Promise<{ template: any }> {
const res = await this.fetch(`/api/compliance/templates/${id}`, {
method: 'PATCH', body: JSON.stringify(patch),
});
if (!res.ok) {
const body = await res.json().catch(() => ({ error: res.statusText }));
throw new Error(body.error ?? `Update template failed (${res.status})`);
}
return res.json();
}
async deleteComplianceTemplate(id: number): Promise<void> {
const res = await this.fetch(`/api/compliance/templates/${id}`, { method: 'DELETE' });
if (!res.ok) {
const body = await res.json().catch(() => ({ error: res.statusText }));
throw new Error(body.error ?? `Delete template failed (${res.status})`);
}
}
// --- WebSocket ---
connectWebSocket(onMessage: (data: unknown) => void): () => void {
if (this.managedDesktop && (!this.desktopEndpoint || !this.desktopEndpointReady)) {

View File

@@ -31,7 +31,7 @@
// no-external build: never lazy-loads remote chunks (config.js, recorder,
// surveys) from us-assets.i.posthog.com. Combined with advanced_disable_decide
// this keeps script-src 'self' intact — no third-party script executes in the
// desktop webview, preserving Waggle/KVARK's data-sovereignty posture. Only
// desktop webview, preserving Waggle's data-sovereignty posture. Only
// the capture endpoint (us.i.posthog.com) is ever contacted.
import posthog from 'posthog-js/dist/module.no-external';

View File

@@ -1,106 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
const mocks = vi.hoisted(() => ({
adapter: {
listComplianceTemplates: vi.fn(),
deleteComplianceTemplate: vi.fn(),
updateComplianceTemplate: vi.fn(),
createComplianceTemplate: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
import { ComplianceTemplateModal, type ComplianceTemplate } from '@/components/os/apps/cockpit/ComplianceTemplateModal';
const template: ComplianceTemplate = {
id: 7,
name: 'High Risk Template',
description: 'EU AI Act evidence packet',
sections: {
interactions: true,
oversight: true,
models: true,
provenance: true,
riskAssessment: true,
fria: true,
},
riskClassification: 'high-risk',
orgName: 'Egzakta',
footerText: null,
createdAt: '2026-07-08T08:00:00.000Z',
updatedAt: '2026-07-08T09:00:00.000Z',
};
beforeEach(() => {
vi.clearAllMocks();
mocks.adapter.listComplianceTemplates.mockResolvedValue({ templates: [template] });
mocks.adapter.deleteComplianceTemplate.mockResolvedValue({ ok: true });
});
afterEach(() => {
cleanup();
vi.restoreAllMocks();
});
describe('ComplianceTemplateModal trust flows', () => {
it('exposes template form fields with stable metadata and focus rings', async () => {
render(<ComplianceTemplateModal open onClose={vi.fn()} />);
await screen.findByText('High Risk Template');
fireEvent.click(screen.getByRole('button', { name: /new template/i }));
const name = screen.getByRole('textbox', { name: /^name$/i });
expect(name).toHaveAttribute('name', 'complianceTemplateName');
expect(name).toHaveAttribute('autocomplete', 'off');
expect(name.className).toContain('focus-visible:ring-2');
expect(name.className).toContain('focus-visible:ring-[var(--focus-ring)]');
const description = screen.getByRole('textbox', { name: /description/i });
expect(description).toHaveAttribute('name', 'complianceTemplateDescription');
expect(description).toHaveAttribute('autocomplete', 'off');
expect(description.className).toContain('focus-visible:ring-2');
expect(description.className).toContain('focus-visible:ring-[var(--focus-ring)]');
const riskClass = screen.getByRole('combobox', { name: /risk class/i });
expect(riskClass).toHaveAttribute('name', 'complianceTemplateRiskClass');
expect(riskClass).toHaveAttribute('autocomplete', 'off');
expect(riskClass.className).toContain('focus-visible:ring-2');
expect(riskClass.className).toContain('focus-visible:ring-[var(--focus-ring)]');
const orgName = screen.getByRole('textbox', { name: /org name/i });
expect(orgName).toHaveAttribute('name', 'complianceTemplateOrgName');
expect(orgName).toHaveAttribute('autocomplete', 'organization');
expect(orgName.className).toContain('focus-visible:ring-2');
expect(orgName.className).toContain('focus-visible:ring-[var(--focus-ring)]');
const footerText = screen.getByRole('textbox', { name: /footer text/i });
expect(footerText).toHaveAttribute('name', 'complianceTemplateFooterText');
expect(footerText).toHaveAttribute('autocomplete', 'off');
expect(footerText.className).toContain('focus-visible:ring-2');
expect(footerText.className).toContain('focus-visible:ring-[var(--focus-ring)]');
});
it('asks in-app before deleting a compliance template', async () => {
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false);
const onChange = vi.fn();
render(<ComplianceTemplateModal open onClose={vi.fn()} onChange={onChange} />);
await screen.findByText('High Risk Template');
fireEvent.click(screen.getByRole('button', { name: /delete high risk template/i }));
expect(confirmSpy).not.toHaveBeenCalled();
expect(mocks.adapter.deleteComplianceTemplate).not.toHaveBeenCalled();
const modal = await screen.findByTestId('approval-modal');
expect(modal).toHaveTextContent(/delete compliance template/i);
expect(modal).toHaveTextContent(/high risk template/i);
expect(modal).toHaveTextContent(/saved report shape/i);
fireEvent.click(screen.getByTestId('approval-modal-approve'));
await waitFor(() => expect(mocks.adapter.deleteComplianceTemplate).toHaveBeenCalledWith(7));
expect(onChange).toHaveBeenCalledTimes(1);
});
});