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

584 lines
20 KiB
TypeScript

/**
* Tests for the Proof Envelope system
*/
import { describe, it, expect, beforeEach } from 'vitest';
import {
ProofChain,
createProofChain,
} from '../src/proof.js';
import type {
ProofEnvelope,
ToolCallRecord,
MemoryOperation,
} from '../src/proof.js';
import type { RunEvent } from '../src/types.js';
// ============================================================================
// Helpers
// ============================================================================
function createMockEvent(overrides: Partial<RunEvent> = {}): RunEvent {
return {
eventId: `evt-${Math.random().toString(36).slice(2, 8)}`,
taskId: 'task-1',
guidanceHash: 'abc123',
retrievedRuleIds: ['R001', 'R002'],
toolsUsed: ['Read', 'Edit', 'Bash'],
filesTouched: ['src/main.ts', 'src/utils.ts'],
diffSummary: { linesAdded: 50, linesRemoved: 10, filesChanged: 2 },
testResults: { ran: true, passed: 10, failed: 0, skipped: 1 },
violations: [],
outcomeAccepted: true,
reworkLines: 5,
intent: 'feature',
timestamp: Date.now(),
durationMs: 5000,
sessionId: 'session-1',
...overrides,
};
}
function createMockToolCall(overrides: Partial<ToolCallRecord> = {}): ToolCallRecord {
return {
callId: `call-${Math.random().toString(36).slice(2, 8)}`,
toolName: 'Edit',
params: { file_path: '/src/main.ts', old_string: 'foo', new_string: 'bar' },
result: { success: true },
timestamp: Date.now(),
durationMs: 120,
...overrides,
};
}
function createMockMemoryOp(overrides: Partial<MemoryOperation> = {}): MemoryOperation {
return {
key: 'agent/status',
namespace: 'coordination',
operation: 'write',
valueHash: 'a'.repeat(64),
timestamp: Date.now(),
...overrides,
};
}
// ============================================================================
// Tests
// ============================================================================
describe('ProofChain', () => {
let chain: ProofChain;
beforeEach(() => {
chain = createProofChain({ signingKey: 'test-secret-key' });
});
// --------------------------------------------------------------------------
// Genesis envelope
// --------------------------------------------------------------------------
describe('genesis envelope', () => {
it('should create the first envelope with previousHash of all zeros', () => {
const event = createMockEvent();
const envelope = chain.append(event);
expect(envelope.previousHash).toBe('0'.repeat(64));
});
it('should set the runEventId to the event ID', () => {
const event = createMockEvent({ eventId: 'evt-genesis' });
const envelope = chain.append(event);
expect(envelope.runEventId).toBe('evt-genesis');
});
it('should have a valid ISO 8601 timestamp', () => {
const event = createMockEvent();
const envelope = chain.append(event);
expect(() => new Date(envelope.timestamp)).not.toThrow();
expect(new Date(envelope.timestamp).toISOString()).toBe(envelope.timestamp);
});
it('should have a non-empty content hash', () => {
const event = createMockEvent();
const envelope = chain.append(event);
expect(envelope.contentHash).toMatch(/^[a-f0-9]{64}$/);
});
it('should have a non-empty HMAC signature', () => {
const event = createMockEvent();
const envelope = chain.append(event);
expect(envelope.signature).toMatch(/^[a-f0-9]{64}$/);
});
it('should produce a unique envelope ID', () => {
const event = createMockEvent();
const e1 = chain.append(event);
const e2 = chain.append(createMockEvent());
expect(e1.envelopeId).not.toBe(e2.envelopeId);
});
});
// --------------------------------------------------------------------------
// Hash chaining
// --------------------------------------------------------------------------
describe('hash chaining', () => {
it('should link the second envelope to the first via contentHash', () => {
const first = chain.append(createMockEvent());
const second = chain.append(createMockEvent());
expect(second.previousHash).toBe(first.contentHash);
});
it('should form a valid chain across multiple envelopes', () => {
const envelopes: ProofEnvelope[] = [];
for (let i = 0; i < 5; i++) {
envelopes.push(chain.append(createMockEvent()));
}
expect(envelopes[0].previousHash).toBe('0'.repeat(64));
for (let i = 1; i < envelopes.length; i++) {
expect(envelopes[i].previousHash).toBe(envelopes[i - 1].contentHash);
}
});
it('should produce different content hashes for different events', () => {
const e1 = chain.append(createMockEvent({ taskId: 'task-a', reworkLines: 0 }));
const e2 = chain.append(createMockEvent({ taskId: 'task-b', reworkLines: 99 }));
expect(e1.contentHash).not.toBe(e2.contentHash);
});
});
// --------------------------------------------------------------------------
// Signature verification
// --------------------------------------------------------------------------
describe('signature verification', () => {
it('should verify a valid envelope', () => {
const envelope = chain.append(createMockEvent());
expect(chain.verify(envelope)).toBe(true);
});
it('should reject an envelope with a tampered contentHash', () => {
const envelope = chain.append(createMockEvent());
// Tamper with the content hash
const tampered: ProofEnvelope = { ...envelope, contentHash: 'f'.repeat(64) };
expect(chain.verify(tampered)).toBe(false);
});
it('should reject an envelope with a tampered guidanceHash', () => {
const envelope = chain.append(createMockEvent());
const tampered: ProofEnvelope = { ...envelope, guidanceHash: 'tampered' };
expect(chain.verify(tampered)).toBe(false);
});
it('should reject an envelope with a tampered metadata field', () => {
const envelope = chain.append(createMockEvent(), [], [], {
agentId: 'agent-1',
sessionId: 'session-1',
});
const tampered: ProofEnvelope = {
...envelope,
metadata: { ...envelope.metadata, agentId: 'attacker' },
};
expect(chain.verify(tampered)).toBe(false);
});
it('should reject an envelope signed with a different key', () => {
const otherChain = createProofChain({ signingKey: 'other-key' });
const event = createMockEvent();
const envelope = otherChain.append(event);
// Verify with the original chain (different key)
expect(chain.verify(envelope)).toBe(false);
});
});
// --------------------------------------------------------------------------
// Full chain verification
// --------------------------------------------------------------------------
describe('chain verification', () => {
it('should verify an empty chain', () => {
expect(chain.verifyChain()).toBe(true);
});
it('should verify a single-envelope chain', () => {
chain.append(createMockEvent());
expect(chain.verifyChain()).toBe(true);
});
it('should verify a multi-envelope chain', () => {
for (let i = 0; i < 10; i++) {
chain.append(createMockEvent());
}
expect(chain.verifyChain()).toBe(true);
});
it('should detect a broken chain when an envelope signature is tampered', () => {
chain.append(createMockEvent());
chain.append(createMockEvent());
chain.append(createMockEvent());
// Export, tamper, and reimport
const serialized = chain.export();
serialized.envelopes[1].signature = 'bad'.repeat(21) + 'b';
const tamperedChain = createProofChain({ signingKey: 'test-secret-key' });
tamperedChain.import(serialized);
expect(tamperedChain.verifyChain()).toBe(false);
});
it('should detect a broken chain when previousHash is tampered', () => {
chain.append(createMockEvent());
chain.append(createMockEvent());
const serialized = chain.export();
// Tamper with the second envelope's previousHash
serialized.envelopes[1] = {
...serialized.envelopes[1],
previousHash: 'f'.repeat(64),
};
// Re-sign would be needed, but since we tampered the field the
// signature itself will also fail, which is the desired behavior.
const tamperedChain = createProofChain({ signingKey: 'test-secret-key' });
tamperedChain.import(serialized);
expect(tamperedChain.verifyChain()).toBe(false);
});
it('should detect a chain with a wrong genesis hash', () => {
chain.append(createMockEvent());
const serialized = chain.export();
serialized.envelopes[0] = {
...serialized.envelopes[0],
previousHash: 'a'.repeat(64),
};
const tamperedChain = createProofChain({ signingKey: 'test-secret-key' });
tamperedChain.import(serialized);
expect(tamperedChain.verifyChain()).toBe(false);
});
});
// --------------------------------------------------------------------------
// Tool call hashing
// --------------------------------------------------------------------------
describe('tool call hashing', () => {
it('should include tool call hashes in the envelope', () => {
const call1 = createMockToolCall({ callId: 'c1', toolName: 'Read' });
const call2 = createMockToolCall({ callId: 'c2', toolName: 'Edit' });
const envelope = chain.append(createMockEvent(), [call1, call2]);
expect(Object.keys(envelope.toolCallHashes)).toHaveLength(2);
expect(envelope.toolCallHashes['c1']).toMatch(/^[a-f0-9]{64}$/);
expect(envelope.toolCallHashes['c2']).toMatch(/^[a-f0-9]{64}$/);
});
it('should produce different hashes for different tool calls', () => {
const call1 = createMockToolCall({
callId: 'c1',
toolName: 'Read',
params: { file: 'a.ts' },
result: 'content-a',
});
const call2 = createMockToolCall({
callId: 'c2',
toolName: 'Read',
params: { file: 'b.ts' },
result: 'content-b',
});
const envelope = chain.append(createMockEvent(), [call1, call2]);
expect(envelope.toolCallHashes['c1']).not.toBe(envelope.toolCallHashes['c2']);
});
it('should produce the same hash for identical tool calls', () => {
const sharedParams = { file: 'same.ts' };
const sharedResult = { ok: true };
const call1 = createMockToolCall({
callId: 'c1',
toolName: 'Read',
params: sharedParams,
result: sharedResult,
});
const call2 = createMockToolCall({
callId: 'c2',
toolName: 'Read',
params: sharedParams,
result: sharedResult,
});
const envelope = chain.append(createMockEvent(), [call1, call2]);
// Same tool name + params + result => same hash
expect(envelope.toolCallHashes['c1']).toBe(envelope.toolCallHashes['c2']);
});
it('should handle empty tool calls', () => {
const envelope = chain.append(createMockEvent(), []);
expect(Object.keys(envelope.toolCallHashes)).toHaveLength(0);
});
});
// --------------------------------------------------------------------------
// Memory lineage tracking
// --------------------------------------------------------------------------
describe('memory lineage tracking', () => {
it('should include memory operations in the envelope', () => {
const ops: MemoryOperation[] = [
createMockMemoryOp({ key: 'status', namespace: 'agent', operation: 'write' }),
createMockMemoryOp({ key: 'config', namespace: 'system', operation: 'read' }),
];
const envelope = chain.append(createMockEvent(), [], ops);
expect(envelope.memoryLineage).toHaveLength(2);
expect(envelope.memoryLineage[0]).toEqual({
key: 'status',
namespace: 'agent',
operation: 'write',
hash: 'a'.repeat(64),
});
expect(envelope.memoryLineage[1]).toEqual({
key: 'config',
namespace: 'system',
operation: 'read',
hash: 'a'.repeat(64),
});
});
it('should handle all operation types', () => {
const ops: MemoryOperation[] = [
createMockMemoryOp({ operation: 'read', valueHash: 'r'.repeat(64) }),
createMockMemoryOp({ operation: 'write', valueHash: 'w'.repeat(64) }),
createMockMemoryOp({ operation: 'delete', valueHash: 'd'.repeat(64) }),
];
const envelope = chain.append(createMockEvent(), [], ops);
expect(envelope.memoryLineage[0].operation).toBe('read');
expect(envelope.memoryLineage[0].hash).toBe('r'.repeat(64));
expect(envelope.memoryLineage[1].operation).toBe('write');
expect(envelope.memoryLineage[1].hash).toBe('w'.repeat(64));
expect(envelope.memoryLineage[2].operation).toBe('delete');
expect(envelope.memoryLineage[2].hash).toBe('d'.repeat(64));
});
it('should handle empty memory operations', () => {
const envelope = chain.append(createMockEvent(), [], []);
expect(envelope.memoryLineage).toHaveLength(0);
});
});
// --------------------------------------------------------------------------
// Export / Import roundtrip
// --------------------------------------------------------------------------
describe('export and import', () => {
it('should roundtrip a chain through export/import', () => {
chain.append(createMockEvent({ taskId: 'task-1' }));
chain.append(createMockEvent({ taskId: 'task-2' }));
chain.append(createMockEvent({ taskId: 'task-3' }));
const exported = chain.export();
expect(exported.envelopes).toHaveLength(3);
expect(exported.version).toBe(1);
expect(exported.createdAt).toBeTruthy();
const restored = createProofChain({ signingKey: 'test-secret-key' });
restored.import(exported);
expect(restored.getChainLength()).toBe(3);
expect(restored.verifyChain()).toBe(true);
});
it('should preserve envelope contents through roundtrip', () => {
const toolCalls = [createMockToolCall({ callId: 'tc-1' })];
const memOps = [createMockMemoryOp({ key: 'k1', namespace: 'ns1' })];
const original = chain.append(
createMockEvent({ eventId: 'evt-rt' }),
toolCalls,
memOps,
{ agentId: 'agent-a', sessionId: 'sess-a' },
);
const exported = chain.export();
const restored = createProofChain({ signingKey: 'test-secret-key' });
restored.import(exported);
const reimported = restored.getEnvelope(original.envelopeId);
expect(reimported).toBeDefined();
expect(reimported!.runEventId).toBe('evt-rt');
expect(reimported!.toolCallHashes['tc-1']).toBe(original.toolCallHashes['tc-1']);
expect(reimported!.memoryLineage).toEqual(original.memoryLineage);
expect(reimported!.metadata.agentId).toBe('agent-a');
expect(reimported!.signature).toBe(original.signature);
});
it('should reject imports with an unsupported version', () => {
const bad: any = { envelopes: [], createdAt: new Date().toISOString(), version: 999 };
expect(() => chain.import(bad)).toThrow(/Unsupported proof chain version/);
});
it('should replace existing chain on import', () => {
chain.append(createMockEvent());
chain.append(createMockEvent());
expect(chain.getChainLength()).toBe(2);
const other = createProofChain({ signingKey: 'test-secret-key' });
other.append(createMockEvent());
const exported = other.export();
chain.import(exported);
expect(chain.getChainLength()).toBe(1);
});
});
// --------------------------------------------------------------------------
// Retrieval helpers
// --------------------------------------------------------------------------
describe('retrieval helpers', () => {
it('getEnvelope should return undefined for unknown ID', () => {
expect(chain.getEnvelope('nonexistent')).toBeUndefined();
});
it('getEnvelope should find an envelope by ID', () => {
const envelope = chain.append(createMockEvent());
const found = chain.getEnvelope(envelope.envelopeId);
expect(found).toBeDefined();
expect(found!.envelopeId).toBe(envelope.envelopeId);
});
it('getChainTip should return undefined for empty chain', () => {
expect(chain.getChainTip()).toBeUndefined();
});
it('getChainTip should return the latest envelope', () => {
chain.append(createMockEvent({ taskId: 'first' }));
const last = chain.append(createMockEvent({ taskId: 'last' }));
expect(chain.getChainTip()?.envelopeId).toBe(last.envelopeId);
});
it('getChainLength should return zero for empty chain', () => {
expect(chain.getChainLength()).toBe(0);
});
it('getChainLength should count all envelopes', () => {
chain.append(createMockEvent());
chain.append(createMockEvent());
chain.append(createMockEvent());
expect(chain.getChainLength()).toBe(3);
});
});
// --------------------------------------------------------------------------
// Factory function
// --------------------------------------------------------------------------
describe('createProofChain factory', () => {
it('should throw when no signingKey is provided', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect(() => createProofChain({} as any)).toThrow('requires an explicit signingKey');
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect(() => createProofChain(undefined as any)).toThrow();
});
it('should create a ProofChain with an explicit signing key', () => {
const chain = createProofChain({ signingKey: 'test-key' });
const envelope = chain.append(createMockEvent());
expect(envelope.signature).toMatch(/^[a-f0-9]{64}$/);
expect(chain.verify(envelope)).toBe(true);
});
it('should create a ProofChain with a custom signing key', () => {
const customChain = createProofChain({ signingKey: 'my-custom-key' });
const envelope = customChain.append(createMockEvent());
expect(customChain.verify(envelope)).toBe(true);
// A chain with a different key should not verify the same envelope
const otherChain = createProofChain({ signingKey: 'different-key' });
expect(otherChain.verify(envelope)).toBe(false);
});
});
// --------------------------------------------------------------------------
// Guidance hash propagation
// --------------------------------------------------------------------------
describe('guidance hash', () => {
it('should capture the guidanceHash from the RunEvent', () => {
const event = createMockEvent({ guidanceHash: 'policy-sha256-hash' });
const envelope = chain.append(event);
expect(envelope.guidanceHash).toBe('policy-sha256-hash');
});
});
// --------------------------------------------------------------------------
// Metadata
// --------------------------------------------------------------------------
describe('metadata', () => {
it('should use provided metadata', () => {
const envelope = chain.append(createMockEvent(), [], [], {
agentId: 'coder-1',
sessionId: 'sess-42',
parentEnvelopeId: 'parent-env-1',
});
expect(envelope.metadata.agentId).toBe('coder-1');
expect(envelope.metadata.sessionId).toBe('sess-42');
expect(envelope.metadata.parentEnvelopeId).toBe('parent-env-1');
});
it('should default to unknown agent and event sessionId', () => {
const event = createMockEvent({ sessionId: 'from-event' });
const envelope = chain.append(event);
expect(envelope.metadata.agentId).toBe('unknown');
expect(envelope.metadata.sessionId).toBe('from-event');
});
it('should default sessionId to unknown when event has none', () => {
const event = createMockEvent();
delete (event as any).sessionId;
const envelope = chain.append(event);
expect(envelope.metadata.sessionId).toBe('unknown');
});
});
});