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

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

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

View File

@@ -1,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';

View File

@@ -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,
};
}
}

View File

@@ -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;
}
}

View File

@@ -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,
};
}
}

View File

@@ -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,
};
}
}

View File

@@ -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',
};

View File

@@ -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';