refactor(server): move the install audit trail from core to the server (P1.2, UF-040)
Core keeps only shared infrastructure, so InstallAuditStore leaves it and lives in packages/server/src/local/install-audit.ts. The trail itself stays: the Audit and Activity tabs, the extend and export routes, and the threat model entry keep working on the same waggle.db table. - @waggle/shared gets RecordAuditInput and the narrow InstallAuditRecorder (record only), which the agent's skill tools now depend on. - The server creates the audit table before the one-time legacy copy, which no longer constructs it in core. - UF-040: GET /api/debug/logs called prepare() on the store's private db wrapper, which has none, so the support bundle never carried recent installs. It now reads them through getRecentSummary().
This commit is contained in:
@@ -2,8 +2,8 @@
|
||||
* Cron Store — SQLite persistence for solo cron schedules.
|
||||
*
|
||||
* Stores cron job definitions with expression validation via cron-parser,
|
||||
* due-job queries, and run tracking. Follows the same pattern as
|
||||
* InstallAuditStore — operates on the .mind DB with lazy table creation.
|
||||
* due-job queries, and run tracking. Operates on waggle.db with lazy table
|
||||
* creation.
|
||||
*/
|
||||
|
||||
import cronParser from 'cron-parser';
|
||||
|
||||
@@ -56,12 +56,6 @@ export { importLegacyMindData, type LegacyMindSource, type LegacyImportReport }
|
||||
|
||||
// ── Waggle-specific orchestration ──
|
||||
export { WaggleConfig, type ProviderEntry } from './config.js';
|
||||
export {
|
||||
InstallAuditStore, INSTALL_AUDIT_TABLE_SQL,
|
||||
type InstallAuditEntry, type RecordAuditInput,
|
||||
type AuditAction, type AuditRiskLevel, type AuditTrustSource,
|
||||
type AuditApprovalClass, type AuditInitiator, type AuditCapabilityType,
|
||||
} from './install-audit.js';
|
||||
export {
|
||||
CronStore, CRON_SCHEDULES_TABLE_SQL, CRON_RUN_LEASES_TABLE_SQL, VALID_JOB_TYPES, cronExprError,
|
||||
type CronSchedule, type CreateScheduleInput, type CronJobType,
|
||||
|
||||
@@ -1,219 +0,0 @@
|
||||
/**
|
||||
* Install Audit Store — persistent audit trail for capability install events.
|
||||
*
|
||||
* Records every install-relevant action (proposed, approved, installed, rejected,
|
||||
* failed) so there is a verifiable history of what was installed, when, why,
|
||||
* and by whom.
|
||||
*
|
||||
* Lives in waggle.db with Waggle's other own data (ADR-0007).
|
||||
*/
|
||||
|
||||
import type { WaggleDB } from './waggle-db.js';
|
||||
import {
|
||||
sqlInList, RISK_LEVELS, APPROVAL_CLASSES, AUDIT_ACTIONS,
|
||||
AUDIT_CAPABILITY_TYPES, AUDIT_INITIATORS, TRUST_SOURCES,
|
||||
} from '@waggle/shared';
|
||||
|
||||
// ── Types ──────────────────────────────────────────────────────────────
|
||||
|
||||
// P7/D15 A2b: the audit vocabulary is now canonical in @waggle/shared. The
|
||||
// Audit*-prefixed names are kept as aliases (re-exported) so every downstream
|
||||
// `import { AuditAction, ... } from '@waggle/core'` keeps working unchanged.
|
||||
// All six sets were already byte-identical to the shared ones (incl. P5/D4's
|
||||
// 'uninstalled'), so this is a pure structural re-point — no value change.
|
||||
export type {
|
||||
AuditAction, AuditCapabilityType, AuditInitiator,
|
||||
RiskLevel as AuditRiskLevel, ApprovalClass as AuditApprovalClass, TrustSource as AuditTrustSource,
|
||||
} from '@waggle/shared';
|
||||
import type {
|
||||
AuditAction, AuditCapabilityType, AuditInitiator,
|
||||
RiskLevel as AuditRiskLevel, ApprovalClass as AuditApprovalClass, TrustSource as AuditTrustSource,
|
||||
} from '@waggle/shared';
|
||||
|
||||
export interface InstallAuditEntry {
|
||||
id: number;
|
||||
timestamp: string;
|
||||
capability_name: string;
|
||||
capability_type: AuditCapabilityType;
|
||||
source: string;
|
||||
version: string | null;
|
||||
risk_level: AuditRiskLevel;
|
||||
trust_source: AuditTrustSource;
|
||||
approval_class: AuditApprovalClass;
|
||||
action: AuditAction;
|
||||
initiator: AuditInitiator;
|
||||
detail: string;
|
||||
}
|
||||
|
||||
export interface RecordAuditInput {
|
||||
capabilityName: string;
|
||||
capabilityType: AuditCapabilityType;
|
||||
source: string;
|
||||
version?: string | null;
|
||||
riskLevel: AuditRiskLevel;
|
||||
trustSource: AuditTrustSource;
|
||||
approvalClass: AuditApprovalClass;
|
||||
action: AuditAction;
|
||||
initiator: AuditInitiator;
|
||||
detail?: string;
|
||||
}
|
||||
|
||||
// ── Table DDL ──────────────────────────────────────────────────────────
|
||||
|
||||
// P7/D15 A3: the CHECK lists are generated from the canonical @waggle/shared
|
||||
// arrays via sqlInList, so the SQLite constraint and the TS union can no longer
|
||||
// drift (divergence #14 — the old comment admitted "drift silently crashes
|
||||
// record()").
|
||||
// P7/D15 #15: trust_source now also carries a CHECK (was unconstrained at the DB
|
||||
// while the TS type claimed a closed set). Every historical value came from the
|
||||
// typed AuditTrustSource (the pre-security-gate 6-set ⊂ the current 7-set), so
|
||||
// the rebuild migration's row copy can never violate it.
|
||||
export const INSTALL_AUDIT_TABLE_SQL = `
|
||||
CREATE TABLE IF NOT EXISTS install_audit (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
timestamp TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
capability_name TEXT NOT NULL,
|
||||
capability_type TEXT NOT NULL CHECK (capability_type IN (${sqlInList(AUDIT_CAPABILITY_TYPES)})),
|
||||
source TEXT NOT NULL,
|
||||
version TEXT,
|
||||
risk_level TEXT NOT NULL CHECK (risk_level IN (${sqlInList(RISK_LEVELS)})),
|
||||
trust_source TEXT NOT NULL CHECK (trust_source IN (${sqlInList(TRUST_SOURCES)})),
|
||||
approval_class TEXT NOT NULL CHECK (approval_class IN (${sqlInList(APPROVAL_CLASSES)})),
|
||||
action TEXT NOT NULL CHECK (action IN (${sqlInList(AUDIT_ACTIONS)})),
|
||||
initiator TEXT NOT NULL CHECK (initiator IN (${sqlInList(AUDIT_INITIATORS)})),
|
||||
detail TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_audit_capability ON install_audit (capability_name, action);
|
||||
CREATE INDEX IF NOT EXISTS idx_audit_timestamp ON install_audit (timestamp DESC);
|
||||
`;
|
||||
|
||||
// ── Store ──────────────────────────────────────────────────────────────
|
||||
|
||||
export class InstallAuditStore {
|
||||
private db: WaggleDB;
|
||||
|
||||
constructor(db: WaggleDB) {
|
||||
this.db = db;
|
||||
this.ensureTable();
|
||||
}
|
||||
|
||||
private ensureTable(): void {
|
||||
const raw = this.db.getDatabase();
|
||||
const existing = raw.prepare(
|
||||
"SELECT sql FROM sqlite_master WHERE type='table' AND name='install_audit'",
|
||||
).get() as { sql: string } | undefined;
|
||||
if (!existing) {
|
||||
raw.exec(INSTALL_AUDIT_TABLE_SQL);
|
||||
return;
|
||||
}
|
||||
// P5/D4 migration: pre-'uninstalled' installs carry a narrower action CHECK
|
||||
// baked into the table DDL. SQLite can't ALTER a CHECK, so rebuild the table
|
||||
// when the stored DDL lacks the new value. Idempotent — a no-op once migrated.
|
||||
// #15: also rebuild when the stored DDL has no trust_source CHECK (the column
|
||||
// was previously unconstrained). "CHECK (trust_source IN" is a safe sentinel —
|
||||
// it appears nowhere else in this DDL.
|
||||
const needsActionWiden = !existing.sql.includes("'uninstalled'");
|
||||
const needsTrustSourceCheck = !existing.sql.includes('CHECK (trust_source IN');
|
||||
if (needsActionWiden || needsTrustSourceCheck) {
|
||||
this.rebuildForWidenedActionCheck(raw);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rebuild install_audit with the widened `action` CHECK, preserving all rows.
|
||||
* Classic SQLite 12-step table redefinition, wrapped in a transaction so a
|
||||
* crash mid-rebuild leaves the original table intact.
|
||||
*/
|
||||
private rebuildForWidenedActionCheck(raw: ReturnType<WaggleDB['getDatabase']>): void {
|
||||
const migrate = raw.transaction(() => {
|
||||
raw.exec('ALTER TABLE install_audit RENAME TO install_audit_legacy');
|
||||
// SQLite carries indexes along with RENAME (still named idx_audit_*), so
|
||||
// INSTALL_AUDIT_TABLE_SQL's CREATE INDEX IF NOT EXISTS would no-op and the
|
||||
// DROP below would take the indexes with the legacy table. Drop them first
|
||||
// so they get recreated on the new table.
|
||||
raw.exec('DROP INDEX IF EXISTS idx_audit_capability');
|
||||
raw.exec('DROP INDEX IF EXISTS idx_audit_timestamp');
|
||||
raw.exec(INSTALL_AUDIT_TABLE_SQL);
|
||||
raw.exec(`
|
||||
INSERT INTO install_audit (
|
||||
id, timestamp, capability_name, capability_type, source, version,
|
||||
risk_level, trust_source, approval_class, action, initiator, detail
|
||||
)
|
||||
SELECT id, timestamp, capability_name, capability_type, source, version,
|
||||
risk_level, trust_source, approval_class, action, initiator, detail
|
||||
FROM install_audit_legacy
|
||||
`);
|
||||
raw.exec('DROP TABLE install_audit_legacy');
|
||||
});
|
||||
migrate();
|
||||
}
|
||||
|
||||
/** Record an install audit event. */
|
||||
record(input: RecordAuditInput): InstallAuditEntry {
|
||||
const raw = this.db.getDatabase();
|
||||
|
||||
raw.prepare(`
|
||||
INSERT INTO install_audit (
|
||||
capability_name, capability_type, source, version,
|
||||
risk_level, trust_source, approval_class, action, initiator, detail
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`).run(
|
||||
input.capabilityName,
|
||||
input.capabilityType,
|
||||
input.source,
|
||||
input.version ?? null,
|
||||
input.riskLevel,
|
||||
input.trustSource,
|
||||
input.approvalClass,
|
||||
input.action,
|
||||
input.initiator,
|
||||
input.detail ?? '',
|
||||
);
|
||||
|
||||
// Return the inserted row
|
||||
return raw.prepare(
|
||||
'SELECT * FROM install_audit ORDER BY id DESC LIMIT 1',
|
||||
).get() as InstallAuditEntry;
|
||||
}
|
||||
|
||||
/** Get audit history for a specific capability. */
|
||||
getByCapability(name: string): InstallAuditEntry[] {
|
||||
return this.db.getDatabase().prepare(
|
||||
'SELECT * FROM install_audit WHERE capability_name = ? ORDER BY id DESC',
|
||||
).all(name) as InstallAuditEntry[];
|
||||
}
|
||||
|
||||
/** Get audit history filtered by action type. */
|
||||
getByAction(action: AuditAction): InstallAuditEntry[] {
|
||||
return this.db.getDatabase().prepare(
|
||||
'SELECT * FROM install_audit WHERE action = ? ORDER BY id DESC',
|
||||
).all(action) as InstallAuditEntry[];
|
||||
}
|
||||
|
||||
/** Get recent audit entries (most recent first). */
|
||||
getRecent(limit: number = 20): InstallAuditEntry[] {
|
||||
return this.db.getDatabase().prepare(
|
||||
'SELECT * FROM install_audit ORDER BY id DESC LIMIT ?',
|
||||
).all(limit) as InstallAuditEntry[];
|
||||
}
|
||||
|
||||
/** Get recent entries for one capability type (most recent first) — backs
|
||||
* the shared Extend-layer audit read (GET /api/extend/audit?type=, C18). */
|
||||
getRecentByType(type: AuditCapabilityType, limit: number = 20): InstallAuditEntry[] {
|
||||
return this.db.getDatabase().prepare(
|
||||
'SELECT * FROM install_audit WHERE capability_type = ? ORDER BY id DESC LIMIT ?',
|
||||
).all(type, limit) as InstallAuditEntry[];
|
||||
}
|
||||
|
||||
/** Get all entries (for testing). */
|
||||
getAll(): InstallAuditEntry[] {
|
||||
return this.db.getDatabase().prepare(
|
||||
'SELECT * FROM install_audit ORDER BY id ASC',
|
||||
).all() as InstallAuditEntry[];
|
||||
}
|
||||
|
||||
/** Clear all entries (for testing). */
|
||||
clear(): void {
|
||||
this.db.getDatabase().prepare('DELETE FROM install_audit').run();
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
/**
|
||||
* Skill Hash Store — SHA-256 content hashing for skill update detection.
|
||||
*
|
||||
* Stores hashes of skill file content in the .mind DB. On server startup,
|
||||
* Stores hashes of skill file content in waggle.db. On server startup,
|
||||
* compares current file hashes to stored hashes to detect changes.
|
||||
* Follows the same ensureTable pattern as CronStore / InstallAuditStore.
|
||||
* Follows the same ensureTable pattern as CronStore.
|
||||
*/
|
||||
|
||||
import * as crypto from 'node:crypto';
|
||||
|
||||
@@ -15,7 +15,6 @@ import { AwarenessLayer } from './awareness.js';
|
||||
import { CronStore } from './cron-store.js';
|
||||
import { ExecutionTraceStore } from './execution-traces.js';
|
||||
import { IdentityLayer } from './identity.js';
|
||||
import { InstallAuditStore } from './install-audit.js';
|
||||
import { SkillHashStore } from './skill-hashes.js';
|
||||
import type { DataScope, WaggleDB } from './waggle-db.js';
|
||||
|
||||
@@ -121,13 +120,15 @@ function copyScopedTables(source: DatabaseType, target: DatabaseType, scope: Dat
|
||||
* Copies Waggle data from each legacy source into `waggleDb`, once per scope.
|
||||
* The personal source also brings the app-wide tables; workspace sources bring
|
||||
* their profile and awareness items.
|
||||
*
|
||||
* Tables owned outside core (install_audit, owned by the server) must be created
|
||||
* by their owner before this call; otherwise they take the legacy definition.
|
||||
*/
|
||||
export function importLegacyMindData(waggleDb: WaggleDB, sources: LegacyMindSource[]): LegacyImportReport[] {
|
||||
// Create every target table with its current schema first.
|
||||
// Create every core target table with its current schema first.
|
||||
new CronStore(waggleDb);
|
||||
new SkillHashStore(waggleDb);
|
||||
new ExecutionTraceStore(waggleDb);
|
||||
new InstallAuditStore(waggleDb);
|
||||
new IdentityLayer(waggleDb);
|
||||
new AwarenessLayer(waggleDb);
|
||||
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
/**
|
||||
* P7/D15 A3 — drift-lock for the install_audit CHECK constraints.
|
||||
*
|
||||
* install-audit.ts generates the table DDL from the canonical @waggle/shared
|
||||
* arrays. This test pins every CHECK list to that single source, so a drift
|
||||
* fails CI instead of crashing auditStore.record() in production.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
sqlInList, RISK_LEVELS, APPROVAL_CLASSES, AUDIT_ACTIONS,
|
||||
AUDIT_CAPABILITY_TYPES, AUDIT_INITIATORS, TRUST_SOURCES,
|
||||
} from '@waggle/shared';
|
||||
import { INSTALL_AUDIT_TABLE_SQL } from '../src/install-audit.js';
|
||||
|
||||
const COLUMNS = [
|
||||
{ col: 'capability_type', values: AUDIT_CAPABILITY_TYPES },
|
||||
{ col: 'risk_level', values: RISK_LEVELS },
|
||||
{ col: 'trust_source', values: TRUST_SOURCES },
|
||||
{ col: 'approval_class', values: APPROVAL_CLASSES },
|
||||
{ col: 'action', values: AUDIT_ACTIONS },
|
||||
{ col: 'initiator', values: AUDIT_INITIATORS },
|
||||
] as const;
|
||||
|
||||
describe('install_audit CHECK parity (A3)', () => {
|
||||
for (const { col, values } of COLUMNS) {
|
||||
const expected = `${col} IN (${sqlInList(values)})`;
|
||||
|
||||
it(`core install-audit DDL pins ${col} to the canonical list`, () => {
|
||||
expect(INSTALL_AUDIT_TABLE_SQL).toContain(expected);
|
||||
});
|
||||
}
|
||||
|
||||
it('the DDL accepts the P5/D4 uninstalled action', () => {
|
||||
expect(INSTALL_AUDIT_TABLE_SQL).toContain("'uninstalled'");
|
||||
});
|
||||
});
|
||||
@@ -1,403 +0,0 @@
|
||||
/**
|
||||
* InstallAuditStore tests. The audit trail lives in waggle.db (ADR-0007).
|
||||
*/
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import * as os from 'node:os';
|
||||
import { WaggleDB } from '../src/waggle-db.js';
|
||||
import { InstallAuditStore, type RecordAuditInput } from '../src/install-audit.js';
|
||||
|
||||
describe('InstallAuditStore', () => {
|
||||
let tmpDir: string;
|
||||
let db: WaggleDB;
|
||||
let store: InstallAuditStore;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-audit-'));
|
||||
db = new WaggleDB(path.join(tmpDir, 'waggle.db'));
|
||||
store = new InstallAuditStore(db);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
db.close();
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function makeInput(overrides?: Partial<RecordAuditInput>): RecordAuditInput {
|
||||
return {
|
||||
capabilityName: 'risk-assessment',
|
||||
capabilityType: 'skill',
|
||||
source: 'starter-pack',
|
||||
riskLevel: 'low',
|
||||
trustSource: 'starter_pack',
|
||||
approvalClass: 'standard',
|
||||
action: 'installed',
|
||||
initiator: 'agent',
|
||||
detail: 'Installed successfully',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
it("records an 'uninstalled' action (P5/D4 — capability removal trail)", () => {
|
||||
const entry = store.record(makeInput({ action: 'uninstalled', initiator: 'agent', detail: 'deleted by agent' }));
|
||||
expect(entry.action).toBe('uninstalled');
|
||||
expect(store.getByAction('uninstalled')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("migrates a legacy-CHECK table to accept 'uninstalled' (P5/D4)", () => {
|
||||
const tmp2 = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-audit-legacy-'));
|
||||
const legacyDb = new WaggleDB(path.join(tmp2, 'waggle.db'));
|
||||
const raw = legacyDb.getDatabase();
|
||||
// Simulate a pre-P5 install: create the table with the OLD narrower action
|
||||
// CHECK (no 'uninstalled'), seeding one row.
|
||||
raw.exec(`
|
||||
CREATE TABLE install_audit (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
timestamp TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
capability_name TEXT NOT NULL,
|
||||
capability_type TEXT NOT NULL CHECK (capability_type IN ('native','skill','plugin','mcp','connector','marketplace')),
|
||||
source TEXT NOT NULL,
|
||||
version TEXT,
|
||||
risk_level TEXT NOT NULL CHECK (risk_level IN ('low','medium','high','critical')),
|
||||
trust_source TEXT NOT NULL,
|
||||
approval_class TEXT NOT NULL CHECK (approval_class IN ('standard','elevated','critical','blocked')),
|
||||
action TEXT NOT NULL CHECK (action IN ('proposed','approved','installed','rejected','failed','blocked')),
|
||||
initiator TEXT NOT NULL CHECK (initiator IN ('agent','user','system')),
|
||||
detail TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
`);
|
||||
raw.prepare(`INSERT INTO install_audit
|
||||
(capability_name, capability_type, source, risk_level, trust_source, approval_class, action, initiator, detail)
|
||||
VALUES ('legacy-skill','skill','starter-pack','low','starter_pack','standard','installed','user','pre-migration row')`).run();
|
||||
|
||||
// Constructing the store triggers ensureTable() → rebuild migration.
|
||||
const migrated = new InstallAuditStore(legacyDb);
|
||||
// Pre-existing row survives the rebuild.
|
||||
expect(migrated.getByCapability('legacy-skill')).toHaveLength(1);
|
||||
// The widened CHECK now accepts 'uninstalled' (would throw on a stale table).
|
||||
const entry = migrated.record(makeInput({ capabilityName: 'legacy-skill', action: 'uninstalled', detail: 'removed' }));
|
||||
expect(entry.action).toBe('uninstalled');
|
||||
// Review #1: the rebuild must NOT drop the declared indexes (SQLite RENAME
|
||||
// carries index names to the legacy table; without an explicit DROP INDEX
|
||||
// they get destroyed with it, leaving the audit table index-less).
|
||||
const idx = raw.prepare(
|
||||
"SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='install_audit' AND name LIKE 'idx_audit_%'",
|
||||
).all() as Array<{ name: string }>;
|
||||
expect(idx.map(i => i.name).sort()).toEqual(['idx_audit_capability', 'idx_audit_timestamp']);
|
||||
|
||||
// #15: the rebuild also added the trust_source CHECK (the legacy table had
|
||||
// trust_source unconstrained). The migrated DDL now carries it, and the
|
||||
// pre-migration row (trust_source 'starter_pack') survived because every
|
||||
// historical value is in the canonical 7-set.
|
||||
const ddl = raw.prepare(
|
||||
"SELECT sql FROM sqlite_master WHERE type='table' AND name='install_audit'",
|
||||
).get() as { sql: string };
|
||||
expect(ddl.sql).toContain('CHECK (trust_source IN');
|
||||
// A bogus trust_source is now rejected at the DB (was previously accepted).
|
||||
expect(() => raw.prepare(
|
||||
`INSERT INTO install_audit
|
||||
(capability_name, capability_type, source, risk_level, trust_source, approval_class, action, initiator, detail)
|
||||
VALUES ('x','skill','s','low','BOGUS_SOURCE','standard','installed','user','')`,
|
||||
).run()).toThrow();
|
||||
|
||||
legacyDb.close();
|
||||
fs.rmSync(tmp2, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('records and retrieves an audit entry', () => {
|
||||
const entry = store.record(makeInput());
|
||||
expect(entry.id).toBeGreaterThan(0);
|
||||
expect(entry.capability_name).toBe('risk-assessment');
|
||||
expect(entry.action).toBe('installed');
|
||||
expect(entry.risk_level).toBe('low');
|
||||
expect(entry.trust_source).toBe('starter_pack');
|
||||
expect(entry.timestamp).toBeTruthy();
|
||||
});
|
||||
|
||||
it('records multiple events for same capability', () => {
|
||||
store.record(makeInput({ action: 'proposed' }));
|
||||
store.record(makeInput({ action: 'approved' }));
|
||||
store.record(makeInput({ action: 'installed' }));
|
||||
|
||||
const history = store.getByCapability('risk-assessment');
|
||||
expect(history).toHaveLength(3);
|
||||
expect(history[0].action).toBe('installed');
|
||||
expect(history[2].action).toBe('proposed');
|
||||
});
|
||||
|
||||
it('queries by action type', () => {
|
||||
store.record(makeInput({ capabilityName: 'draft-memo', action: 'installed' }));
|
||||
store.record(makeInput({ capabilityName: 'code-review', action: 'proposed' }));
|
||||
store.record(makeInput({ capabilityName: 'brainstorm', action: 'installed' }));
|
||||
|
||||
const installed = store.getByAction('installed');
|
||||
expect(installed).toHaveLength(2);
|
||||
expect(installed.map(e => e.capability_name).sort()).toEqual(['brainstorm', 'draft-memo']);
|
||||
});
|
||||
|
||||
it('retrieves recent entries in descending order', () => {
|
||||
store.record(makeInput({ capabilityName: 'first', action: 'proposed' }));
|
||||
store.record(makeInput({ capabilityName: 'second', action: 'installed' }));
|
||||
store.record(makeInput({ capabilityName: 'third', action: 'failed' }));
|
||||
|
||||
const recent = store.getRecent(2);
|
||||
expect(recent).toHaveLength(2);
|
||||
expect(recent[0].capability_name).toBe('third');
|
||||
expect(recent[1].capability_name).toBe('second');
|
||||
});
|
||||
|
||||
it('preserves all fields round-trip', () => {
|
||||
const entry = store.record(makeInput({
|
||||
capabilityName: 'test-skill',
|
||||
capabilityType: 'plugin',
|
||||
source: 'third-party',
|
||||
version: '1.2.3',
|
||||
riskLevel: 'high',
|
||||
trustSource: 'third_party_unverified',
|
||||
approvalClass: 'critical',
|
||||
action: 'failed',
|
||||
initiator: 'user',
|
||||
detail: 'Permission denied by user',
|
||||
}));
|
||||
|
||||
expect(entry.capability_name).toBe('test-skill');
|
||||
expect(entry.capability_type).toBe('plugin');
|
||||
expect(entry.source).toBe('third-party');
|
||||
expect(entry.version).toBe('1.2.3');
|
||||
expect(entry.risk_level).toBe('high');
|
||||
expect(entry.trust_source).toBe('third_party_unverified');
|
||||
expect(entry.approval_class).toBe('critical');
|
||||
expect(entry.action).toBe('failed');
|
||||
expect(entry.initiator).toBe('user');
|
||||
expect(entry.detail).toBe('Permission denied by user');
|
||||
});
|
||||
|
||||
it('handles null version', () => {
|
||||
const entry = store.record(makeInput({ version: null }));
|
||||
expect(entry.version).toBeNull();
|
||||
});
|
||||
|
||||
it('handles empty detail', () => {
|
||||
const entry = store.record(makeInput({ detail: undefined }));
|
||||
expect(entry.detail).toBe('');
|
||||
});
|
||||
|
||||
it('getAll returns entries in insertion order', () => {
|
||||
store.record(makeInput({ capabilityName: 'a' }));
|
||||
store.record(makeInput({ capabilityName: 'b' }));
|
||||
store.record(makeInput({ capabilityName: 'c' }));
|
||||
|
||||
const all = store.getAll();
|
||||
expect(all).toHaveLength(3);
|
||||
expect(all[0].capability_name).toBe('a');
|
||||
expect(all[2].capability_name).toBe('c');
|
||||
});
|
||||
|
||||
it('clear removes all entries', () => {
|
||||
store.record(makeInput({ capabilityName: 'a' }));
|
||||
store.record(makeInput({ capabilityName: 'b' }));
|
||||
expect(store.getAll()).toHaveLength(2);
|
||||
|
||||
store.clear();
|
||||
expect(store.getAll()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('creates table lazily on pre-existing databases', () => {
|
||||
const store2 = new InstallAuditStore(db);
|
||||
const entry = store2.record(makeInput({ capabilityName: 'from-second-store' }));
|
||||
expect(entry.capability_name).toBe('from-second-store');
|
||||
});
|
||||
|
||||
it('records failed validation as audit event', () => {
|
||||
const entry = store.record(makeInput({
|
||||
action: 'failed',
|
||||
riskLevel: 'low',
|
||||
trustSource: 'unknown',
|
||||
detail: 'Skill "nonexistent" not found in the starter pack.',
|
||||
}));
|
||||
expect(entry.action).toBe('failed');
|
||||
expect(entry.detail).toContain('not found');
|
||||
});
|
||||
|
||||
// P0-005/FIX-3: install_audit CHECK constraints drifted behind their TS
|
||||
// type unions. Once marketplace FTS search returned candidates,
|
||||
// acquire_capability recommended a `type:'marketplace'` capability and
|
||||
// auditStore.record() crashed with "CHECK constraint failed: capability_type
|
||||
// IN ('native','skill','plugin','mcp')", throwing the whole tool and
|
||||
// dead-ending the agent. These lock the CHECK <-> type-union alignment.
|
||||
it('records a marketplace-type capability (capability_type CHECK widened)', () => {
|
||||
const entry = store.record(makeInput({ capabilityType: 'marketplace', source: 'marketplace' }));
|
||||
expect(entry.capability_type).toBe('marketplace');
|
||||
});
|
||||
|
||||
it('records a connector-type capability', () => {
|
||||
const entry = store.record(makeInput({ capabilityType: 'connector', source: 'connector' }));
|
||||
expect(entry.capability_type).toBe('connector');
|
||||
});
|
||||
|
||||
it("records the 'blocked' action and 'blocked' approval_class (sibling CHECK drift)", () => {
|
||||
const entry = store.record(makeInput({ action: 'blocked', approvalClass: 'blocked' }));
|
||||
expect(entry.action).toBe('blocked');
|
||||
expect(entry.approval_class).toBe('blocked');
|
||||
});
|
||||
|
||||
// M2 (UX-Refactor Phase 4 / C15): risk_level CHECK lacked 'critical' while
|
||||
// the TS union had it — marketplace.ts's CRITICAL-block audit write was
|
||||
// silently rejected (throw swallowed by `catch {}`). This locks the widened
|
||||
// CHECK on fresh databases.
|
||||
it("records riskLevel 'critical' (M2: risk_level CHECK widened)", () => {
|
||||
const entry = store.record(makeInput({
|
||||
riskLevel: 'critical',
|
||||
approvalClass: 'blocked',
|
||||
action: 'blocked',
|
||||
trustSource: 'security-gate',
|
||||
detail: 'SecurityGate blocked: CRITICAL findings',
|
||||
}));
|
||||
expect(entry.risk_level).toBe('critical');
|
||||
expect(entry.action).toBe('blocked');
|
||||
});
|
||||
|
||||
// C18: type-filtered read backing GET /api/extend/audit?type=
|
||||
it('getRecentByType filters by capability_type, most recent first', () => {
|
||||
store.record(makeInput({ capabilityName: 'a-skill', capabilityType: 'skill' }));
|
||||
store.record(makeInput({ capabilityName: 'a-server', capabilityType: 'mcp' }));
|
||||
store.record(makeInput({ capabilityName: 'b-server', capabilityType: 'mcp' }));
|
||||
store.record(makeInput({ capabilityName: 'a-conn', capabilityType: 'connector' }));
|
||||
|
||||
const mcps = store.getRecentByType('mcp');
|
||||
expect(mcps).toHaveLength(2);
|
||||
expect(mcps[0].capability_name).toBe('b-server');
|
||||
expect(mcps[1].capability_name).toBe('a-server');
|
||||
expect(store.getRecentByType('mcp', 1)).toHaveLength(1);
|
||||
expect(store.getRecentByType('native')).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('InstallAuditStore — legacy CHECK migration', () => {
|
||||
let tmpDir: string;
|
||||
let dbPath: string;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-audit-mig-'));
|
||||
dbPath = path.join(tmpDir, 'waggle.db');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const OLD_DDL = `CREATE TABLE install_audit (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
timestamp TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
capability_name TEXT NOT NULL,
|
||||
capability_type TEXT NOT NULL CHECK (capability_type IN ('native', 'skill', 'plugin', 'mcp')),
|
||||
source TEXT NOT NULL,
|
||||
version TEXT,
|
||||
risk_level TEXT NOT NULL CHECK (risk_level IN ('low', 'medium', 'high')),
|
||||
trust_source TEXT NOT NULL,
|
||||
approval_class TEXT NOT NULL CHECK (approval_class IN ('standard', 'elevated', 'critical')),
|
||||
action TEXT NOT NULL CHECK (action IN ('proposed', 'approved', 'installed', 'rejected', 'failed')),
|
||||
initiator TEXT NOT NULL CHECK (initiator IN ('agent', 'user', 'system')),
|
||||
detail TEXT NOT NULL DEFAULT ''
|
||||
)`;
|
||||
|
||||
it('rebuilds a legacy install_audit table (narrow CHECK) and preserves rows', () => {
|
||||
// 1. Create install_audit with the historical 4-value CHECK and one legacy
|
||||
// row — the shape of an audit table created before connector/marketplace
|
||||
// existed.
|
||||
{
|
||||
const seed = new WaggleDB(dbPath);
|
||||
const raw = seed.getDatabase();
|
||||
raw.prepare(OLD_DDL).run();
|
||||
raw.prepare(`INSERT INTO install_audit
|
||||
(capability_name, capability_type, source, risk_level, trust_source, approval_class, action, initiator, detail)
|
||||
VALUES ('legacy-skill','skill','starter-pack','low','starter_pack','standard','installed','agent','pre-migration row')`).run();
|
||||
seed.close();
|
||||
}
|
||||
|
||||
// 2. Reopen — the store must rebuild install_audit with the widened CHECK.
|
||||
const db = new WaggleDB(dbPath);
|
||||
const store = new InstallAuditStore(db);
|
||||
|
||||
const legacy = store.getByCapability('legacy-skill');
|
||||
expect(legacy).toHaveLength(1);
|
||||
expect(legacy[0].detail).toBe('pre-migration row');
|
||||
|
||||
expect(() => store.record({
|
||||
capabilityName: 'filesystem', capabilityType: 'marketplace', source: 'marketplace',
|
||||
riskLevel: 'medium', trustSource: 'unknown', approvalClass: 'standard',
|
||||
action: 'proposed', initiator: 'agent', detail: 'Proposed for need: read external files',
|
||||
})).not.toThrow();
|
||||
const fs2 = store.getByCapability('filesystem');
|
||||
expect(fs2[0].capability_type).toBe('marketplace');
|
||||
|
||||
db.close();
|
||||
});
|
||||
|
||||
// M2 (UX-Refactor Phase 4 / C15): the FIX-3-era DDL had every list widened
|
||||
// EXCEPT risk_level — the exact shape of audit tables created between FIX-3
|
||||
// (2026-05-17) and Phase 4.
|
||||
const FIX3_ERA_DDL = `CREATE TABLE install_audit (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
timestamp TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
capability_name TEXT NOT NULL,
|
||||
capability_type TEXT NOT NULL CHECK (capability_type IN ('native', 'skill', 'plugin', 'mcp', 'connector', 'marketplace')),
|
||||
source TEXT NOT NULL,
|
||||
version TEXT,
|
||||
risk_level TEXT NOT NULL CHECK (risk_level IN ('low', 'medium', 'high')),
|
||||
trust_source TEXT NOT NULL,
|
||||
approval_class TEXT NOT NULL CHECK (approval_class IN ('standard', 'elevated', 'critical', 'blocked')),
|
||||
action TEXT NOT NULL CHECK (action IN ('proposed', 'approved', 'installed', 'rejected', 'failed', 'blocked')),
|
||||
initiator TEXT NOT NULL CHECK (initiator IN ('agent', 'user', 'system')),
|
||||
detail TEXT NOT NULL DEFAULT ''
|
||||
)`;
|
||||
|
||||
it("M2: rebuilds a FIX-3-era table (risk_level missing 'critical') and preserves rows", () => {
|
||||
{
|
||||
const seed = new WaggleDB(dbPath);
|
||||
const raw = seed.getDatabase();
|
||||
raw.prepare(FIX3_ERA_DDL).run();
|
||||
raw.prepare(`INSERT INTO install_audit
|
||||
(capability_name, capability_type, source, risk_level, trust_source, approval_class, action, initiator, detail)
|
||||
VALUES ('legacy-mcp','mcp','marketplace','high','security-gate','blocked','blocked','system','pre-M2 row')`).run();
|
||||
// Sanity: the legacy CHECK really rejects 'critical' (the live bug)
|
||||
expect(() => raw.prepare(`INSERT INTO install_audit
|
||||
(capability_name, capability_type, source, risk_level, trust_source, approval_class, action, initiator, detail)
|
||||
VALUES ('x','mcp','marketplace','critical','security-gate','blocked','blocked','system','')`).run()
|
||||
).toThrow(/CHECK/);
|
||||
seed.close();
|
||||
}
|
||||
|
||||
// Reopen — the store must rebuild the table with the widened CHECK.
|
||||
const db = new WaggleDB(dbPath);
|
||||
const store = new InstallAuditStore(db);
|
||||
|
||||
const legacy = store.getByCapability('legacy-mcp');
|
||||
expect(legacy).toHaveLength(1);
|
||||
expect(legacy[0].detail).toBe('pre-M2 row');
|
||||
expect(legacy[0].risk_level).toBe('high');
|
||||
|
||||
const critical = store.record({
|
||||
capabilityName: 'evil-pkg', capabilityType: 'marketplace', source: 'marketplace',
|
||||
riskLevel: 'critical', trustSource: 'security-gate', approvalClass: 'blocked',
|
||||
action: 'blocked', initiator: 'system', detail: 'SecurityGate blocked: CRITICAL',
|
||||
});
|
||||
expect(critical.risk_level).toBe('critical');
|
||||
db.close();
|
||||
|
||||
// Idempotence: a second reopen must NOT rebuild again (rows + ids stable).
|
||||
const db2 = new WaggleDB(dbPath);
|
||||
const store2 = new InstallAuditStore(db2);
|
||||
const all = store2.getAll();
|
||||
expect(all).toHaveLength(2);
|
||||
expect(all.map((e) => e.capability_name)).toEqual(['legacy-mcp', 'evil-pkg']);
|
||||
// The rebuilt DDL carries the sentinel, so a third store write still works.
|
||||
expect(() => store2.record({
|
||||
capabilityName: 'again', capabilityType: 'mcp', source: 'mcp',
|
||||
riskLevel: 'critical', trustSource: 'security-gate', approvalClass: 'blocked',
|
||||
action: 'blocked', initiator: 'system',
|
||||
})).not.toThrow();
|
||||
db2.close();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user