Files
wehub-resource-sync 23f7624596
ADR-166 MCP Bridge Security Lock / Static-source security lock (push) Failing after 0s
ADR-166 MCP Bridge Security Lock / Compose default binds loopback + Mongo has auth (push) Failing after 2s
CodeQL Advanced / Analyze (rust) (push) Failing after 0s
ADR-166 MCP Bridge Security Lock / plugin-agent-federation bindHost default (push) Failing after 1s
ADR-166 MCP Bridge Security Lock / Runtime behavior — 401 + terminal gate + fail-closed (push) Failing after 4s
business-pods-smoke / smoke (push) Failing after 1s
all-plugins-smoke / smoke-all (push) Failing after 2s
CI/CD Pipeline / Security & Code Quality (push) Failing after 1s
CI/CD Pipeline / Test Suite (ubuntu-latest) (push) Failing after 1s
CI/CD Pipeline / Build & Package (macos-latest) (push) Has been skipped
CI/CD Pipeline / Build & Package (ubuntu-latest) (push) Has been skipped
CI/CD Pipeline / Build & Package (windows-latest) (push) Has been skipped
CI/CD Pipeline / Documentation & Examples (push) Failing after 1s
Clone Tracker (14-day rolling) / Snapshot clones for ruflo ecosystem (push) Failing after 1s
CodeQL Advanced / Analyze (actions) (push) Failing after 1s
CodeQL Advanced / Analyze (javascript-typescript) (push) Failing after 1s
federation-peer-rust / stable-noop (push) Failing after 1s
metaharness-ci / score (push) Failing after 1s
metaharness-ci / router-compat (push) Failing after 0s
metaharness-ci / similarity-tests (push) Failing after 0s
no-agentbbs-smoke / smoke-without-agentbbs (push) Failing after 1s
V3 CI/CD Pipeline / Build V3 (windows-latest) (push) Has been skipped
codex-integration-audit / Codex integration audit (push) Failing after 1s
helpers-manifest-guard / guard (push) Failing after 1s
🔗 Cross-Agent Integration Tests / 🤝 Agent Coordination Tests (push) Has been skipped
🔗 Cross-Agent Integration Tests / 🧠 Memory Sharing Integration (push) Has been skipped
🔗 Cross-Agent Integration Tests / 🛡️ Fault Tolerance Tests (push) Has been skipped
🔗 Cross-Agent Integration Tests / ⚡ Performance Integration Tests (push) Has been skipped
metaharness-ci / mcp-scan (push) Failing after 1s
metaharness-ci / eject-dryrun (push) Failing after 1s
metaharness-ci / metaharness-real-data (push) Failing after 0s
no-cli-optdep-bloat-2561 / guard (push) Failing after 1s
no-metaharness-smoke / smoke-without-metaharness (push) Failing after 1s
no-phantom-agentic-flow-subpath / guard (push) Failing after 1s
🔄 Automated Rollback Manager / 🚨 Failure Detection (push) Failing after 1s
V3 CI/CD Pipeline / Plugin hooks smoke / ubuntu-latest / Node 22 (push) Failing after 1s
V3 CI/CD Pipeline / ruflo-graph-intelligence build + test smoke (#2044, ADR-123) (push) Failing after 1s
CVE Audit Gate / Audit root (critical-blocking) (push) Failing after 2s
cost-tracker-smoke / smoke (push) Failing after 3s
oia-audit-weekly / audit (push) Failing after 2s
ruflo-agent-smoke / ruflo-agent structural smoke (push) Failing after 1s
📊 Status Badges Update / 📊 Update Status Badges (push) Failing after 1s
V3 CI/CD Pipeline / Static regression guards (#2267 YAML + (push) Failing after 1s
V3 CI/CD Pipeline / Test V3 Packages (push) Failing after 0s
V3 CI/CD Pipeline / agent_execute provider routing smoke (#2042) (push) Failing after 0s
CVE Audit Gate / Audit v3 (critical-blocking) (push) Failing after 1s
federation-peer-rust / stable-native (push) Failing after 2s
🔗 Cross-Agent Integration Tests / 🚀 Integration Test Setup (push) Failing after 2s
neural-trader-smoke / runtime-smoke (push) Failing after 1s
V3 CI/CD Pipeline / Build V3 (macos-latest) (push) Has been skipped
V3 CI/CD Pipeline / Build V3 (ubuntu-latest) (push) Has been skipped
V3 CI/CD Pipeline / Type Check V3 (push) Failing after 1s
V3 CI/CD Pipeline / Smoke (no better-sqlite3) / ubuntu-latest / Node 24 (push) Failing after 1s
V3 CI/CD Pipeline / Smoke (no better-sqlite3) / ubuntu-latest / Node 22 (push) Failing after 2s
V3 CI/CD Pipeline / browser rvf create flag smoke (#2015) (push) Failing after 0s
V3 CI/CD Pipeline / Dependency review (#2046) (push) Has been skipped
V3 CI/CD Pipeline / Supply-chain audit (#2046) (push) Failing after 0s
V3 CI/CD Pipeline / witness marker drift smoke (#2021) (push) Failing after 1s
V3 CI/CD Pipeline / neural-trader portfolio CG smoke (#2068, ADR-126 Phase 3) (push) Failing after 1s
V3 CI/CD Pipeline / neural-trader backtest signing smoke (#2068, ADR-126 Phase 4) (push) Failing after 1s
V3 CI/CD Pipeline / kg-extract type-import classification smoke (#2049) (push) Failing after 0s
V3 CI/CD Pipeline / witness verify precondition smoke (#1880) (push) Failing after 2s
V3 CI/CD Pipeline / neural-trader pipeline risk-gate smoke (#2068, ADR-126 Phase 5) (push) Failing after 0s
V3 CI/CD Pipeline / neural-trader feature attribution smoke (#2068, ADR-126 Phase 6) (push) Failing after 0s
V3 CI/CD Pipeline / plugin-registry signature verification smoke (#1922, CWE-347) (push) Failing after 4s
V3 CI/CD Pipeline / memory stats legacy-DB smoke (#2120) (push) Failing after 4s
V3 CI/CD Pipeline / github deprecated actions smoke (#2089, ADR-127 Phase 3) (push) Failing after 1s
V3 CI/CD Pipeline / graph query + pathfinder smoke (ADR-130 P2+P5) (push) Has been skipped
V3 CI/CD Pipeline / graph trajectory hooks smoke (ADR-130 P3) (push) Has been skipped
V3 CI/CD Pipeline / graph plugin adapter smoke (ADR-130 P4) (push) Has been skipped
V3 CI/CD Pipeline / graph benchmark (ADR-130 P6) (push) Has been skipped
V3 CI/CD Pipeline / statusline generator delegation smoke (#2195) (push) Failing after 1s
V3 CI/CD Pipeline / wizard init regression guard (#2206 (push) Failing after 1s
V3 CI/CD Pipeline / memory no-stray-db smoke (ADR-125 P7) (push) Failing after 1s
V3 CI/CD Pipeline / github-safe injection smoke (#2089, ADR-127 Phase 1) (push) Failing after 1s
V3 CI/CD Pipeline / github actions pin smoke (#2089, ADR-127 Phase 1) (push) Failing after 1s
V3 CI/CD Pipeline / github attribution opt-in smoke (#2089, ADR-127 Phase 4) (push) Failing after 1s
V3 CI/CD Pipeline / pre-bash hook safety smoke (#2017) (push) Failing after 1s
V3 CI/CD Pipeline / Memory import smoke / ubuntu-latest (push) Failing after 0s
V3 CI/CD Pipeline / MCP protocol smoke / ubuntu-latest (push) Failing after 2s
V3 CI/CD Pipeline / ruvllm WASM auto-init smoke (#2086) (push) Failing after 4s
V3 CI/CD Pipeline / MCP paired-tool round-trip smoke (#1889) (push) Failing after 1s
V3 CI/CD Pipeline / Plugin package install-safety (#1902/#1903/#1904) (push) Failing after 1s
V3 CI/CD Pipeline / Tool description discoverability (ADR-112) (push) Failing after 3s
V3 CI/CD Pipeline / CLI npx-install smoke (#1147 / (22) (push) Failing after 1s
V3 CI/CD Pipeline / CLI npx-install smoke (#1147 / (24) (push) Failing after 1s
V3 CI/CD Pipeline / Windows hook shim smoke (#2132) / ubuntu-latest (push) Failing after 2s
V3 CI/CD Pipeline / Windows hook execution smoke (#2132) / ubuntu-latest (push) Failing after 1s
V3 CI/CD Pipeline / Windows init hooks smoke (#2132) / ubuntu-latest (push) Failing after 1s
V3 CI/CD Pipeline / Vector-index dimension audit (#1947) (push) Failing after 0s
V3 CI/CD Pipeline / Hook-command install safety (#1921) (push) Failing after 1s
V3 CI/CD Pipeline / ToolOutputGuardrail smoke (ADR-131, (push) Failing after 1s
V3 CI/CD Pipeline / init-bundle invariants smoke (#2095, ADR-128 Phase 5) (push) Failing after 1s
V3 CI/CD Pipeline / wasm provider bridge smoke (ADR-129 P1) (push) Failing after 2s
V3 CI/CD Pipeline / wasm gallery CRUD smoke (ADR-129 P3) (push) Failing after 1s
V3 CI/CD Pipeline / wasm plugin bridge smoke (ADR-129 P4) (push) Failing after 0s
V3 CI/CD Pipeline / wasm compose smoke (ADR-129 P2) (push) Failing after 4s
V3 CI/CD Pipeline / graph schema smoke (ADR-130 P1) (push) Failing after 0s
Validate Marketplace / validate (push) Failing after 1s
🔍 Verification Pipeline / 🚀 Setup Verification (push) Failing after 1s
🔍 Verification Pipeline / 🛡️ Security Verification (push) Has been skipped
🔍 Verification Pipeline / 📝 Code Quality (push) Has been skipped
🔍 Verification Pipeline / 🧪 Test Verification (${{ matrix.os }}, Node ${{ matrix.node }}) (push) Has been skipped
🔍 Verification Pipeline / 🏗️ Build Verification (push) Has been skipped
🔍 Verification Pipeline / 📚 Documentation Verification (push) Has been skipped
CVE Audit Gate / High-severity report (warn only) (push) Has been cancelled
🔄 Automated Rollback Manager / 🔄 Execute Rollback (push) Has been cancelled
🔄 Automated Rollback Manager / ✅ Post-Rollback Verification (push) Has been cancelled
🔄 Automated Rollback Manager / 📊 Rollback Monitoring (push) Has been cancelled
V3 CI/CD Pipeline / Windows init hooks smoke (#2132) / windows-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows hook execution smoke (#2132) / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows hook execution smoke (#2132) / windows-latest (push) Has been cancelled
🔄 Automated Rollback Manager / ⏳ Manual Rollback Approval (push) Has been cancelled
V3 CI/CD Pipeline / MCP protocol smoke / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Memory import smoke / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows hook shim smoke (#2132) / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows hook shim smoke (#2132) / windows-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows init hooks smoke (#2132) / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Witness verify (signed manifest) / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Witness verify (signed manifest) / ubuntu-latest (push) Has been cancelled
V3 CI/CD Pipeline / Witness verify (signed manifest) / windows-latest (push) Has been cancelled
V3 CI/CD Pipeline / Publish to npm (alpha) (push) Has been cancelled
V3 CI/CD Pipeline / Smoke (no better-sqlite3) / macos-latest / Node 22 (push) Has been cancelled
V3 CI/CD Pipeline / Plugin hooks smoke / macos-latest / Node 22 (push) Has been cancelled
CI/CD Pipeline / Deploy & Release (push) Has been cancelled
CI/CD Pipeline / CI Status (push) Has been cancelled
🔗 Cross-Agent Integration Tests / 📊 Integration Test Report (push) Has been cancelled
🔄 Automated Rollback Manager / 🔍 Pre-Rollback Validation (push) Has been cancelled
🔍 Verification Pipeline / ⚡ Performance Verification (push) Has been cancelled
🔍 Verification Pipeline / 📊 Verification Report (push) Has been cancelled
chore: import upstream snapshot with attribution
2026-07-13 12:02:19 +08:00

687 lines
24 KiB
TypeScript

/**
* Tests for the Artifact Ledger system
*/
import { describe, it, expect, beforeEach } from 'vitest';
import {
ArtifactLedger,
createArtifactLedger,
} from '../src/artifacts.js';
import type {
Artifact,
ArtifactKind,
ArtifactLineage,
RecordArtifactParams,
} from '../src/artifacts.js';
// ============================================================================
// Helpers
// ============================================================================
function createMockLineage(overrides: Partial<ArtifactLineage> = {}): ArtifactLineage {
return {
parentArtifacts: [],
sourceRunId: 'run-1',
sourceTraceRef: 'envelope-1',
toolCallIds: ['tc-1'],
memoryReads: ['key-1'],
...overrides,
};
}
function createMockParams(overrides: Partial<RecordArtifactParams> = {}): RecordArtifactParams {
return {
runId: 'run-1',
cellId: 'cell-coder-1',
tenantId: 'tenant-acme',
kind: 'code',
name: 'main.ts',
description: 'Main application entry point',
content: 'console.log("hello");',
metadata: { language: 'typescript' },
lineage: createMockLineage(),
tags: ['entry-point', 'typescript'],
...overrides,
};
}
// ============================================================================
// Tests
// ============================================================================
describe('ArtifactLedger', () => {
let ledger: ArtifactLedger;
beforeEach(() => {
ledger = createArtifactLedger({ signingKey: 'test-artifact-key' });
});
// --------------------------------------------------------------------------
// Recording artifacts
// --------------------------------------------------------------------------
describe('record', () => {
it('should create an artifact with correct fields and signature', () => {
const artifact = ledger.record(createMockParams());
expect(artifact.artifactId).toMatch(
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,
);
expect(artifact.runId).toBe('run-1');
expect(artifact.cellId).toBe('cell-coder-1');
expect(artifact.tenantId).toBe('tenant-acme');
expect(artifact.kind).toBe('code');
expect(artifact.name).toBe('main.ts');
expect(artifact.description).toBe('Main application entry point');
expect(artifact.content).toBe('console.log("hello");');
expect(artifact.metadata).toEqual({ language: 'typescript' });
expect(artifact.tags).toEqual(['entry-point', 'typescript']);
expect(artifact.createdAt).toBeGreaterThan(0);
expect(artifact.contentHash).toMatch(/^[a-f0-9]{64}$/);
expect(artifact.contentSize).toBeGreaterThan(0);
expect(artifact.signature).toMatch(/^[a-f0-9]{64}$/);
expect(artifact.lineage.parentArtifacts).toEqual([]);
expect(artifact.lineage.sourceRunId).toBe('run-1');
expect(artifact.lineage.sourceTraceRef).toBe('envelope-1');
});
it('should default metadata to empty object when not provided', () => {
const artifact = ledger.record(createMockParams({ metadata: undefined }));
expect(artifact.metadata).toEqual({});
});
it('should default tags to empty array when not provided', () => {
const artifact = ledger.record(createMockParams({ tags: undefined }));
expect(artifact.tags).toEqual([]);
});
it('should produce unique artifact IDs', () => {
const a1 = ledger.record(createMockParams());
const a2 = ledger.record(createMockParams());
expect(a1.artifactId).not.toBe(a2.artifactId);
});
it('should compute correct content size for string content', () => {
const content = 'hello world';
const artifact = ledger.record(createMockParams({ content }));
expect(artifact.contentSize).toBe(Buffer.byteLength(content, 'utf-8'));
});
it('should compute correct content size for object content', () => {
const content = { data: [1, 2, 3], nested: { key: 'value' } };
const artifact = ledger.record(createMockParams({ content }));
expect(artifact.contentSize).toBe(
Buffer.byteLength(JSON.stringify(content), 'utf-8'),
);
});
it('should handle all artifact kinds', () => {
const kinds: ArtifactKind[] = [
'code', 'report', 'dataset', 'model-output',
'memory-delta', 'config', 'trace-export', 'checkpoint',
];
for (const kind of kinds) {
const artifact = ledger.record(createMockParams({ kind }));
expect(artifact.kind).toBe(kind);
}
});
});
// --------------------------------------------------------------------------
// Verification
// --------------------------------------------------------------------------
describe('verify', () => {
it('should detect valid artifacts', () => {
const artifact = ledger.record(createMockParams());
const result = ledger.verify(artifact.artifactId);
expect(result.verified).toBe(true);
expect(result.signatureValid).toBe(true);
expect(result.contentIntact).toBe(true);
expect(result.lineageComplete).toBe(true);
expect(result.verifiedAt).toBeGreaterThan(0);
});
it('should detect tampered content', () => {
const artifact = ledger.record(createMockParams());
// Tamper with content directly (bypass signature)
const stored = ledger.get(artifact.artifactId)!;
(stored as any).content = 'TAMPERED CONTENT';
const result = ledger.verify(artifact.artifactId);
expect(result.verified).toBe(false);
expect(result.contentIntact).toBe(false);
});
it('should detect invalid signature', () => {
const artifact = ledger.record(createMockParams());
// Tamper with signature
const stored = ledger.get(artifact.artifactId)!;
(stored as any).signature = 'f'.repeat(64);
const result = ledger.verify(artifact.artifactId);
expect(result.verified).toBe(false);
expect(result.signatureValid).toBe(false);
});
it('should detect incomplete lineage (missing parent)', () => {
const artifact = ledger.record(createMockParams({
lineage: createMockLineage({
parentArtifacts: ['nonexistent-parent-id'],
}),
}));
const result = ledger.verify(artifact.artifactId);
expect(result.verified).toBe(false);
expect(result.lineageComplete).toBe(false);
// Signature and content should still be valid
expect(result.signatureValid).toBe(true);
expect(result.contentIntact).toBe(true);
});
it('should verify complete lineage when parents exist', () => {
const parent = ledger.record(createMockParams({ name: 'parent.ts' }));
const child = ledger.record(createMockParams({
name: 'child.ts',
lineage: createMockLineage({
parentArtifacts: [parent.artifactId],
}),
}));
const result = ledger.verify(child.artifactId);
expect(result.verified).toBe(true);
expect(result.lineageComplete).toBe(true);
});
it('should return all-false for unknown artifact ID', () => {
const result = ledger.verify('nonexistent-id');
expect(result.verified).toBe(false);
expect(result.signatureValid).toBe(false);
expect(result.contentIntact).toBe(false);
expect(result.lineageComplete).toBe(false);
});
it('should use different signatures for different signing keys', () => {
const ledgerA = createArtifactLedger({ signingKey: 'key-a' });
const ledgerB = createArtifactLedger({ signingKey: 'key-b' });
const artifactA = ledgerA.record(createMockParams());
const artifactB = ledgerB.record(createMockParams());
expect(artifactA.signature).not.toBe(artifactB.signature);
});
});
// --------------------------------------------------------------------------
// Retrieval
// --------------------------------------------------------------------------
describe('get', () => {
it('should return the artifact by ID', () => {
const artifact = ledger.record(createMockParams());
const found = ledger.get(artifact.artifactId);
expect(found).toBeDefined();
expect(found!.artifactId).toBe(artifact.artifactId);
});
it('should return undefined for unknown ID', () => {
expect(ledger.get('nonexistent')).toBeUndefined();
});
});
// --------------------------------------------------------------------------
// getByRun
// --------------------------------------------------------------------------
describe('getByRun', () => {
it('should return all artifacts for a run', () => {
ledger.record(createMockParams({ runId: 'run-alpha', name: 'a.ts' }));
ledger.record(createMockParams({ runId: 'run-alpha', name: 'b.ts' }));
ledger.record(createMockParams({ runId: 'run-beta', name: 'c.ts' }));
const results = ledger.getByRun('run-alpha');
expect(results).toHaveLength(2);
expect(results.every(a => a.runId === 'run-alpha')).toBe(true);
});
it('should return empty array for unknown run', () => {
expect(ledger.getByRun('nonexistent')).toEqual([]);
});
it('should return artifacts sorted by creation time', () => {
ledger.record(createMockParams({ runId: 'run-1', name: 'first.ts' }));
ledger.record(createMockParams({ runId: 'run-1', name: 'second.ts' }));
const results = ledger.getByRun('run-1');
expect(results[0].createdAt).toBeLessThanOrEqual(results[1].createdAt);
});
});
// --------------------------------------------------------------------------
// getByKind
// --------------------------------------------------------------------------
describe('getByKind', () => {
it('should return all artifacts of a specific kind', () => {
ledger.record(createMockParams({ kind: 'code', name: 'app.ts' }));
ledger.record(createMockParams({ kind: 'report', name: 'coverage.json' }));
ledger.record(createMockParams({ kind: 'code', name: 'utils.ts' }));
const codeArtifacts = ledger.getByKind('code');
expect(codeArtifacts).toHaveLength(2);
expect(codeArtifacts.every(a => a.kind === 'code')).toBe(true);
});
it('should return empty array when no artifacts match', () => {
ledger.record(createMockParams({ kind: 'code' }));
expect(ledger.getByKind('dataset')).toEqual([]);
});
});
// --------------------------------------------------------------------------
// getByCell
// --------------------------------------------------------------------------
describe('getByCell', () => {
it('should return all artifacts from a specific cell', () => {
ledger.record(createMockParams({ cellId: 'cell-coder', name: 'code.ts' }));
ledger.record(createMockParams({ cellId: 'cell-tester', name: 'test.ts' }));
ledger.record(createMockParams({ cellId: 'cell-coder', name: 'util.ts' }));
const results = ledger.getByCell('cell-coder');
expect(results).toHaveLength(2);
expect(results.every(a => a.cellId === 'cell-coder')).toBe(true);
});
});
// --------------------------------------------------------------------------
// getLineage
// --------------------------------------------------------------------------
describe('getLineage', () => {
it('should traverse ancestry depth-first', () => {
const grandparent = ledger.record(createMockParams({
name: 'grandparent.ts',
lineage: createMockLineage({ parentArtifacts: [] }),
}));
const parent = ledger.record(createMockParams({
name: 'parent.ts',
lineage: createMockLineage({
parentArtifacts: [grandparent.artifactId],
}),
}));
const child = ledger.record(createMockParams({
name: 'child.ts',
lineage: createMockLineage({
parentArtifacts: [parent.artifactId],
}),
}));
const lineage = ledger.getLineage(child.artifactId);
expect(lineage).toHaveLength(2);
expect(lineage[0].artifactId).toBe(parent.artifactId);
expect(lineage[1].artifactId).toBe(grandparent.artifactId);
});
it('should handle multiple parents', () => {
const parentA = ledger.record(createMockParams({ name: 'a.ts' }));
const parentB = ledger.record(createMockParams({ name: 'b.ts' }));
const child = ledger.record(createMockParams({
name: 'merged.ts',
lineage: createMockLineage({
parentArtifacts: [parentA.artifactId, parentB.artifactId],
}),
}));
const lineage = ledger.getLineage(child.artifactId);
expect(lineage).toHaveLength(2);
const lineageIds = lineage.map(a => a.artifactId);
expect(lineageIds).toContain(parentA.artifactId);
expect(lineageIds).toContain(parentB.artifactId);
});
it('should handle diamond ancestry without duplicates', () => {
const root = ledger.record(createMockParams({ name: 'root.ts' }));
const leftParent = ledger.record(createMockParams({
name: 'left.ts',
lineage: createMockLineage({ parentArtifacts: [root.artifactId] }),
}));
const rightParent = ledger.record(createMockParams({
name: 'right.ts',
lineage: createMockLineage({ parentArtifacts: [root.artifactId] }),
}));
const child = ledger.record(createMockParams({
name: 'diamond.ts',
lineage: createMockLineage({
parentArtifacts: [leftParent.artifactId, rightParent.artifactId],
}),
}));
const lineage = ledger.getLineage(child.artifactId);
// Should have left, right, and root - no duplicates
const uniqueIds = new Set(lineage.map(a => a.artifactId));
expect(uniqueIds.size).toBe(lineage.length);
expect(uniqueIds.size).toBe(3);
});
it('should return empty array for artifact with no parents', () => {
const artifact = ledger.record(createMockParams());
expect(ledger.getLineage(artifact.artifactId)).toEqual([]);
});
it('should return empty array for unknown artifact ID', () => {
expect(ledger.getLineage('nonexistent')).toEqual([]);
});
it('should handle missing parent gracefully', () => {
const child = ledger.record(createMockParams({
lineage: createMockLineage({
parentArtifacts: ['deleted-parent-id'],
}),
}));
const lineage = ledger.getLineage(child.artifactId);
expect(lineage).toEqual([]);
});
});
// --------------------------------------------------------------------------
// search
// --------------------------------------------------------------------------
describe('search', () => {
beforeEach(() => {
// Seed ledger with diverse artifacts
ledger.record(createMockParams({
runId: 'run-1', kind: 'code', tags: ['frontend', 'react'],
}));
ledger.record(createMockParams({
runId: 'run-1', kind: 'report', tags: ['coverage'],
}));
ledger.record(createMockParams({
runId: 'run-2', kind: 'code', tags: ['backend', 'api'],
}));
ledger.record(createMockParams({
runId: 'run-2', kind: 'dataset', tags: ['training'],
}));
});
it('should filter by kind', () => {
const results = ledger.search({ kind: 'code' });
expect(results).toHaveLength(2);
expect(results.every(a => a.kind === 'code')).toBe(true);
});
it('should filter by runId', () => {
const results = ledger.search({ runId: 'run-2' });
expect(results).toHaveLength(2);
expect(results.every(a => a.runId === 'run-2')).toBe(true);
});
it('should filter by tags (AND logic)', () => {
const results = ledger.search({ tags: ['frontend', 'react'] });
expect(results).toHaveLength(1);
expect(results[0].tags).toContain('frontend');
expect(results[0].tags).toContain('react');
});
it('should filter by time range (since)', () => {
const now = Date.now();
const results = ledger.search({ since: now + 100_000 });
expect(results).toHaveLength(0);
});
it('should filter by time range (until)', () => {
const results = ledger.search({ until: 0 });
expect(results).toHaveLength(0);
});
it('should combine multiple filters with AND', () => {
const results = ledger.search({ kind: 'code', runId: 'run-1' });
expect(results).toHaveLength(1);
expect(results[0].kind).toBe('code');
expect(results[0].runId).toBe('run-1');
});
it('should return all artifacts with empty query', () => {
const results = ledger.search({});
expect(results).toHaveLength(4);
});
it('should return empty array when no artifacts match', () => {
const results = ledger.search({ kind: 'checkpoint' });
expect(results).toEqual([]);
});
});
// --------------------------------------------------------------------------
// Export / Import roundtrip
// --------------------------------------------------------------------------
describe('export and import', () => {
it('should roundtrip all artifacts through export/import', () => {
ledger.record(createMockParams({ name: 'a.ts', kind: 'code' }));
ledger.record(createMockParams({ name: 'b.json', kind: 'report' }));
ledger.record(createMockParams({ name: 'c.csv', kind: 'dataset' }));
const exported = ledger.export();
expect(exported.artifacts).toHaveLength(3);
expect(exported.version).toBe(1);
expect(exported.createdAt).toBeTruthy();
const restored = createArtifactLedger({ signingKey: 'test-artifact-key' });
restored.import(exported);
const stats = restored.getStats();
expect(stats.totalArtifacts).toBe(3);
});
it('should preserve artifact contents through roundtrip', () => {
const original = ledger.record(createMockParams({
name: 'preserved.ts',
content: 'const x = 42;',
tags: ['important'],
}));
const exported = ledger.export();
const restored = createArtifactLedger({ signingKey: 'test-artifact-key' });
restored.import(exported);
const reimported = restored.get(original.artifactId);
expect(reimported).toBeDefined();
expect(reimported!.name).toBe('preserved.ts');
expect(reimported!.content).toBe('const x = 42;');
expect(reimported!.tags).toEqual(['important']);
expect(reimported!.signature).toBe(original.signature);
expect(reimported!.contentHash).toBe(original.contentHash);
});
it('should verify imported artifacts with the same signing key', () => {
const original = ledger.record(createMockParams());
const exported = ledger.export();
const restored = createArtifactLedger({ signingKey: 'test-artifact-key' });
restored.import(exported);
const result = restored.verify(original.artifactId);
expect(result.verified).toBe(true);
expect(result.signatureValid).toBe(true);
expect(result.contentIntact).toBe(true);
});
it('should reject imports with unsupported version', () => {
const bad: any = {
artifacts: [],
createdAt: new Date().toISOString(),
version: 999,
};
expect(() => ledger.import(bad)).toThrow(/Unsupported artifact ledger version/);
});
it('should replace existing ledger contents on import', () => {
ledger.record(createMockParams({ name: 'old.ts' }));
ledger.record(createMockParams({ name: 'old2.ts' }));
expect(ledger.getStats().totalArtifacts).toBe(2);
const other = createArtifactLedger({ signingKey: 'test-artifact-key' });
other.record(createMockParams({ name: 'new.ts' }));
const exported = other.export();
ledger.import(exported);
expect(ledger.getStats().totalArtifacts).toBe(1);
});
});
// --------------------------------------------------------------------------
// getStats
// --------------------------------------------------------------------------
describe('getStats', () => {
it('should count artifacts correctly', () => {
ledger.record(createMockParams({ kind: 'code' }));
ledger.record(createMockParams({ kind: 'code' }));
ledger.record(createMockParams({ kind: 'report' }));
ledger.record(createMockParams({ kind: 'dataset' }));
ledger.record(createMockParams({ kind: 'checkpoint' }));
const stats = ledger.getStats();
expect(stats.totalArtifacts).toBe(5);
expect(stats.byKind.code).toBe(2);
expect(stats.byKind.report).toBe(1);
expect(stats.byKind.dataset).toBe(1);
expect(stats.byKind.checkpoint).toBe(1);
expect(stats.byKind['model-output']).toBe(0);
expect(stats.byKind['memory-delta']).toBe(0);
expect(stats.byKind.config).toBe(0);
expect(stats.byKind['trace-export']).toBe(0);
});
it('should return zeros for empty ledger', () => {
const stats = ledger.getStats();
expect(stats.totalArtifacts).toBe(0);
expect(stats.totalSize).toBe(0);
expect(Object.values(stats.byKind).every(v => v === 0)).toBe(true);
});
it('should track total content size', () => {
ledger.record(createMockParams({ content: 'short' }));
ledger.record(createMockParams({ content: 'a longer piece of content' }));
const stats = ledger.getStats();
const expectedSize =
Buffer.byteLength('short', 'utf-8') +
Buffer.byteLength('a longer piece of content', 'utf-8');
expect(stats.totalSize).toBe(expectedSize);
});
it('should include all artifact kinds in byKind even when zero', () => {
const stats = ledger.getStats();
const expectedKinds: ArtifactKind[] = [
'code', 'report', 'dataset', 'model-output',
'memory-delta', 'config', 'trace-export', 'checkpoint',
];
for (const kind of expectedKinds) {
expect(stats.byKind).toHaveProperty(kind);
expect(stats.byKind[kind]).toBe(0);
}
});
});
// --------------------------------------------------------------------------
// Capacity / eviction
// --------------------------------------------------------------------------
describe('capacity management', () => {
it('should evict oldest artifact when exceeding maxArtifacts', () => {
const smallLedger = createArtifactLedger({
signingKey: 'test-artifact-key',
maxArtifacts: 3,
});
const first = smallLedger.record(createMockParams({ name: 'first.ts' }));
smallLedger.record(createMockParams({ name: 'second.ts' }));
smallLedger.record(createMockParams({ name: 'third.ts' }));
// Recording a 4th should evict the first
smallLedger.record(createMockParams({ name: 'fourth.ts' }));
expect(smallLedger.getStats().totalArtifacts).toBe(3);
expect(smallLedger.get(first.artifactId)).toBeUndefined();
});
});
// --------------------------------------------------------------------------
// Factory function
// --------------------------------------------------------------------------
describe('createArtifactLedger factory', () => {
it('should throw when no signingKey is provided', () => {
expect(() => createArtifactLedger()).toThrow('requires an explicit signingKey');
});
it('should create a ledger with an explicit signing key', () => {
const ledger = createArtifactLedger({ signingKey: 'test-key' });
const artifact = ledger.record(createMockParams());
expect(artifact.signature).toMatch(/^[a-f0-9]{64}$/);
const result = ledger.verify(artifact.artifactId);
expect(result.verified).toBe(true);
});
it('should create a ledger with custom signing key', () => {
const customLedger = createArtifactLedger({ signingKey: 'custom-key' });
const artifact = customLedger.record(createMockParams());
expect(customLedger.verify(artifact.artifactId).verified).toBe(true);
});
});
});