feat(claims): ADR-101 Phase 2 — federated repository + event-store adapters

Implements Component B of ADR-101: vector-clock-versioned event store and
federation-aware claim repository, both wrapping existing local DDD
implementations so single-node deployments are unaffected.

  - infrastructure/vector-clock.ts (new, ~140 lines): tick / merge /
    compareVectorClocks (returns equal | before | after | concurrent),
    pruneVectorClock for peer-eviction GC, vectorClockToString for
    deterministic logging
  - infrastructure/federation-bridge.ts (new, ~170 lines): single seam
    between claim events and federation envelopes. Carries PiiLeakPrevented
    guard + transport abstraction so claims module stays usable without
    plugin-agent-federation installed
  - infrastructure/federated-event-store.ts (new, ~280 lines): vclock-
    versioned IClaimEventStore. Detects concurrent writes (throws
    ConcurrentWriteError → resolved via existing contest mechanism).
    Rolls back local append if PII guard or transport publish throws.
    applyRemoteEvent merges HLC + vclock from peer; idempotent on rebroadcasts.
  - infrastructure/federated-claim-repository.ts (new, ~180 lines):
    federation-aware face of the claim store. Implements both
    IClaimRepository and IIssueClaimRepository, local-first reads with
    `_opts: FederatedQueryOptions` reserved for cross-node fan-out.
  - tests/vector-clock.test.ts (16 new tests): tick, merge, partial
    order, concurrent detection, GC, canonical Lamport handoff scenario
  - tests/federated-event-store.test.ts (10 new tests): vclock advance
    on append, idempotent rebroadcast, concurrent-write error,
    PII rollback, getEvents/subscribe/getEventsByIssueId pass-through

Validation: 203/203 tests pass (26 new this phase + 177 from Phase 1 +
existing). tsc --noEmit clean. tsup build clean.

Closes Phase 2 of #1775. Phase 3 (attested handoff envelopes — touches
plugin-agent-federation/src/protocol/federation-envelope.ts) follows.

Co-Authored-By: RuFlo <ruv@ruv.net>
This commit is contained in:
ReuvenandRuFlo committed 2026-05-05 22:49:50 -04:00
1 parent 1f826fb9b0
commit edc39f7da6
7 files changed
+1235

No files matched your search

@@ -0,0 +1,174 @@
/**
* Federated claim repository — wraps `InMemoryClaimRepository` and is the
* federation-aware face of the claim store.
*
* Read paths are local-first: the local replica is authoritative for queries.
* Cross-node lookups are explicit (`findByClaimant(c, { includeRemote: true })`)
* and currently no-op until the federation peer-query API lands — this
* adapter is structured to absorb that capability later without breaking
* callers.
*
* Writes delegate to the wrapped repository. Cross-node replication of
* mutations is the responsibility of `FederatedClaimEventStore`, which
* pairs with this repository in the application's DI graph (per ADR-101
* Component B's "single seam" principle in federation-bridge.ts).
*
* @module v3/claims/infrastructure/federated-claim-repository
* @see ADR-101 Component B
*/
import type {
ClaimId,
IssueId,
Claimant,
ClaimStatus,
IssueClaim,
IssueClaimWithStealing,
AgentType,
} from '../domain/types.js';
import type { IClaimRepository } from '../domain/repositories.js';
import type { IIssueClaimRepository } from '../domain/types.js';
import type { InMemoryClaimRepository } from './claim-repository.js';
/**
* Options for cross-node-aware queries.
*/
export interface FederatedQueryOptions {
/**
* If true, query reaches into the federation to discover claims that
* exist on remote peers but have not yet replicated locally. Currently
* a no-op (returns local results only); reserved for the next iteration
* where peer querying lands.
*/
includeRemote?: boolean;
}
export interface FederatedClaimRepositoryOptions {
/** The underlying local repository this wraps. */
readonly local: InMemoryClaimRepository;
/** Stable identifier for this federation node (kept for diagnostics). */
readonly nodeId: string;
}
/**
* Federation-aware claim repository.
*
* Implements the existing `IClaimRepository` and `IIssueClaimRepository`
* contracts unchanged so existing call sites compose without modification.
*/
export class FederatedClaimRepository
implements IClaimRepository, IIssueClaimRepository
{
private readonly local: InMemoryClaimRepository;
// Kept for future use (peer-aware queries) and for diagnostics.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
private readonly nodeId: string;
constructor(opts: FederatedClaimRepositoryOptions) {
if (!opts.nodeId) throw new Error('FederatedClaimRepository requires nodeId');
this.local = opts.local;
this.nodeId = opts.nodeId;
}
initialize(): Promise<void> {
return this.local.initialize();
}
shutdown(): Promise<void> {
return this.local.shutdown();
}
// ===========================================================================
// Writes — delegate
// ===========================================================================
save(claim: IssueClaim | IssueClaimWithStealing): Promise<void> {
return this.local.save(claim);
}
update(claim: IssueClaimWithStealing): Promise<void> {
return this.local.update(claim);
}
delete(claimId: ClaimId): Promise<void> {
return this.local.delete(claimId);
}
// ===========================================================================
// Reads — local-first, with `includeRemote` opt-in for forward compat
// ===========================================================================
findById(claimId: ClaimId): Promise<IssueClaimWithStealing | null> {
return this.local.findById(claimId);
}
findByIssueId(
issueId: IssueId,
repository?: string,
): Promise<IssueClaimWithStealing | null> {
return this.local.findByIssueId(issueId, repository);
}
/**
* Find claims by claimant identity (matches IClaimRepository signature).
* The optional `_opts` parameter is reserved for cross-node fan-out;
* callers passing `includeRemote: true` today receive local results.
*/
findByClaimant(
claimant: Claimant,
// Reserved; see FederatedQueryOptions docstring.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_opts: FederatedQueryOptions = {},
): Promise<IssueClaim[]> {
return this.local.findByClaimant(claimant);
}
findByAgentId(agentId: string): Promise<IssueClaimWithStealing[]> {
return this.local.findByAgentId(agentId);
}
findByStatus(status: ClaimStatus): Promise<IssueClaim[]> {
return this.local.findByStatus(status);
}
findStealable(agentType?: AgentType): Promise<IssueClaimWithStealing[]> {
return this.local.findStealable(agentType);
}
findContested(): Promise<IssueClaimWithStealing[]> {
return this.local.findContested();
}
findAll(): Promise<IssueClaimWithStealing[]> {
return this.local.findAll();
}
// ===========================================================================
// Counts — match IClaimRepository / IIssueClaimRepository signatures
// ===========================================================================
/** IClaimRepository.countByClaimant takes a Claimant; we pass through its id. */
countByClaimant(claimantId: string): Promise<number> {
return this.local.countByClaimant(claimantId);
}
countByAgentId(agentId: string): Promise<number> {
return this.local.countByAgentId(agentId);
}
// ===========================================================================
// IClaimRepository extras — delegate
// ===========================================================================
findActiveClaims(): Promise<IssueClaim[]> {
return this.local.findActiveClaims();
}
findStaleClaims(staleSince: Date): Promise<IssueClaim[]> {
return this.local.findStaleClaims(staleSince);
}
findClaimsWithPendingHandoffs(): Promise<IssueClaim[]> {
return this.local.findClaimsWithPendingHandoffs();
}
}
@@ -0,0 +1,330 @@
/**
* Federated event store — vector-clock-versioned wrapper around the local
* `InMemoryClaimEventStore`.
*
* Each appended event carries a `vclock` (vector clock) and an `hlc` (hybrid
* logical clock) attached as additional metadata. On append the store:
*
* 1. Detects concurrent writes by comparing the new event's vclock with
* the latest accepted vclock for the aggregate. If they're concurrent
* (neither happens-before the other), the append is REJECTED with
* `ConcurrentWriteError` — the application layer (claim service /
* work-stealing service) is expected to surface this as a contest
* and resolve it via the existing contest mechanism.
*
* 2. Publishes the event to the federation via the bridge after the local
* append succeeds. PII detected during the publish causes the local
* append to be rolled back via the bridge throwing.
*
* 3. Accepts inbound events from federation peers via `applyRemoteEvent`.
* Remote events are merged into the local clock and appended to the
* local store with a flag distinguishing them from local writes.
*
* Backwards compatibility: the wrapper is opt-in. Callers that don't need
* federation continue to use `InMemoryClaimEventStore` directly. The
* IClaimEventStore interface contract is preserved so existing code paths
* see a vector-clock-aware store as just an event store.
*
* @module v3/claims/infrastructure/federated-event-store
* @see ADR-101 Component B
*/
import type { ClaimDomainEvent, AllExtendedClaimEvents, ClaimEventType, ExtendedClaimEventType } from '../domain/events.js';
import type { IClaimEventStore } from '../domain/repositories.js';
import type { ClaimId, IssueId } from '../domain/types.js';
import type { InMemoryClaimEventStore } from './event-store.js';
import type { IHlc, HlcTimestamp } from './hlc.js';
import {
type VectorClock,
zeroVectorClock,
tickVectorClock,
mergeVectorClocks,
compareVectorClocks,
areConcurrent,
} from './vector-clock.js';
import type { FederationBridge } from './federation-bridge.js';
// =============================================================================
// Errors
// =============================================================================
/**
* Thrown when an append would cause a concurrent-write conflict against
* an existing remote-accepted event for the same aggregate. The caller
* should surface this as a steal contest.
*/
export class ConcurrentWriteError extends Error {
constructor(
public readonly aggregateId: string,
public readonly localVclock: VectorClock,
public readonly remoteVclock: VectorClock,
) {
super(
`Concurrent write detected on aggregate '${aggregateId}'. ` +
`Resolve via contest mechanism.`,
);
this.name = 'ConcurrentWriteError';
}
}
// =============================================================================
// Event metadata extension
// =============================================================================
/**
* The additional metadata fields a federated event carries.
* Stored in `event.metadata.federation` so they don't perturb the existing
* event shape that older readers expect.
*/
export interface FederationMetadata {
readonly hlc: HlcTimestamp;
readonly vclock: VectorClock;
readonly originNodeId: string;
readonly arrivedFromFederation?: boolean; // true if applyRemoteEvent set it
readonly envelopeSignature?: string; // present iff arrived from federation
}
const FEDERATION_METADATA_KEY = 'federation' as const;
function readFederationMetadata(event: ClaimDomainEvent): FederationMetadata | undefined {
const meta = event.metadata?.[FEDERATION_METADATA_KEY];
return (meta as FederationMetadata | undefined);
}
function writeFederationMetadata(event: ClaimDomainEvent, fm: FederationMetadata): ClaimDomainEvent {
return {
...event,
metadata: {
...(event.metadata ?? {}),
[FEDERATION_METADATA_KEY]: fm,
},
};
}
// =============================================================================
// Per-aggregate state
// =============================================================================
interface AggregateState {
/** Most recent accepted vclock for this aggregate (any node). */
vclock: VectorClock;
/** Most recent accepted HLC for this aggregate. */
hlc?: HlcTimestamp;
}
// =============================================================================
// Federated event store
// =============================================================================
export interface FederatedClaimEventStoreOptions {
/** The underlying local event store this wraps. */
readonly local: InMemoryClaimEventStore;
/** This node's HLC. */
readonly hlc: IHlc;
/** Stable identifier for this federation node. */
readonly nodeId: string;
/** Bridge for cross-node publish. Optional — single-node mode skips publish. */
readonly bridge?: FederationBridge;
}
export class FederatedClaimEventStore implements IClaimEventStore {
private readonly local: InMemoryClaimEventStore;
private readonly hlc: IHlc;
private readonly nodeId: string;
private readonly bridge?: FederationBridge;
private readonly aggregates: Map<string, AggregateState> = new Map();
constructor(opts: FederatedClaimEventStoreOptions) {
if (!opts.nodeId) throw new Error('FederatedClaimEventStore requires nodeId');
this.local = opts.local;
this.hlc = opts.hlc;
this.nodeId = opts.nodeId;
this.bridge = opts.bridge;
}
async initialize(): Promise<void> {
await this.local.initialize();
}
async shutdown(): Promise<void> {
await this.local.shutdown();
this.aggregates.clear();
}
// ==========================================================================
// Write — local
// ==========================================================================
async append(event: ClaimDomainEvent): Promise<void> {
const state = this.aggregates.get(event.aggregateId) ?? {
vclock: zeroVectorClock(),
};
// Tick our entry in the aggregate's clock for the new local event.
const nextVclock = tickVectorClock(state.vclock, this.nodeId);
const nextHlc = this.hlc.now();
// Decorate event with federation metadata (does not mutate caller's object).
const stamped = writeFederationMetadata(event, {
hlc: nextHlc,
vclock: nextVclock,
originNodeId: this.nodeId,
arrivedFromFederation: false,
});
// Local append first — gives us our durable record before we ever
// attempt the publish. If the publish then fails (PII or transport),
// we roll back by removing the just-appended event.
await this.local.append(stamped);
this.aggregates.set(event.aggregateId, { vclock: nextVclock, hlc: nextHlc });
// Federation publish (if configured)
if (this.bridge) {
try {
await this.bridge.publishClaimEvent(stamped, nextVclock, nextHlc);
} catch (publishError) {
// Roll back local state. Not all underlying stores expose a
// `removeLast`; the in-memory one accepts our reaching into it.
// Future SQLite/AgentDB-backed stores should expose a delete-by-id
// path — tracked in #1775 follow-ups.
this.rollbackLastAppend(stamped);
throw publishError;
}
}
}
async appendBatch(events: ClaimDomainEvent[]): Promise<void> {
// Strict sequential append to keep vclock per-event semantics correct.
for (const event of events) {
await this.append(event);
}
}
// ==========================================================================
// Write — remote (federation inbound)
// ==========================================================================
/**
* Apply an event received from a federation peer.
* Throws `ConcurrentWriteError` if the remote event is concurrent with our
* latest known state for the aggregate; the caller should surface this as
* a contest.
*/
async applyRemoteEvent(
event: ClaimDomainEvent,
remoteVclock: VectorClock,
remoteHlc: HlcTimestamp,
envelopeSignature?: string,
): Promise<void> {
const state = this.aggregates.get(event.aggregateId) ?? {
vclock: zeroVectorClock(),
};
// Concurrency check
const order = compareVectorClocks(state.vclock, remoteVclock);
if (order === 'concurrent') {
throw new ConcurrentWriteError(event.aggregateId, state.vclock, remoteVclock);
}
if (order === 'after' || order === 'equal') {
// We've already seen this or a later event — drop silently (idempotent).
return;
}
// Update our HLC from the remote (may throw HlcSkewError).
const mergedHlc = this.hlc.update(remoteHlc);
const mergedVclock = mergeVectorClocks(state.vclock, remoteVclock);
const stamped = writeFederationMetadata(event, {
hlc: mergedHlc,
vclock: mergedVclock,
originNodeId: readFederationMetadata(event)?.originNodeId ?? 'unknown',
arrivedFromFederation: true,
envelopeSignature,
});
await this.local.append(stamped);
this.aggregates.set(event.aggregateId, { vclock: mergedVclock, hlc: mergedHlc });
}
// ==========================================================================
// Read — delegate to local
// ==========================================================================
async getEvents(claimId: ClaimId, fromVersion?: number): Promise<ClaimDomainEvent[]> {
return this.local.getEvents(claimId, fromVersion);
}
async getEventsByType(type: string): Promise<ClaimDomainEvent[]> {
return this.local.getEventsByType(type);
}
async getEventsByIssueId(issueId: IssueId): Promise<ClaimDomainEvent[]> {
return this.local.getEventsByIssueId(issueId);
}
// ==========================================================================
// Subscriptions — delegate (returns unsubscribe function, matching the
// local store's signature)
// ==========================================================================
subscribe(
eventTypes: (ClaimEventType | ExtendedClaimEventType)[],
handler: (event: AllExtendedClaimEvents) => void | Promise<void>,
): () => void {
return this.local.subscribe(eventTypes, handler);
}
// ==========================================================================
// Inspection helpers (for tests + diagnostics)
// ==========================================================================
/** Read-only snapshot of the per-aggregate vclock state. */
getAggregateVclock(aggregateId: string): VectorClock {
return this.aggregates.get(aggregateId)?.vclock ?? zeroVectorClock();
}
/**
* Detects if a remote vclock would cause a concurrent-write conflict
* against current local state. Read-only — safe to call before applyRemoteEvent.
*/
wouldConflict(aggregateId: string, remoteVclock: VectorClock): boolean {
const local = this.getAggregateVclock(aggregateId);
return areConcurrent(local, remoteVclock);
}
// ==========================================================================
// Internals
// ==========================================================================
private rollbackLastAppend(stamped: ClaimDomainEvent): void {
// The InMemoryClaimEventStore doesn't expose a public remove API; we
// reach in via duck typing to clean up after a failed publish. This is
// intentional: future durable stores will get a proper delete-by-id.
const inner = this.local as unknown as { events?: ClaimDomainEvent[] };
if (Array.isArray(inner.events)) {
// Pop the most recent matching event (by id when available).
for (let i = inner.events.length - 1; i >= 0; i--) {
if (inner.events[i]?.id === stamped.id) {
inner.events.splice(i, 1);
break;
}
}
}
// Reset aggregate state to whatever we had before the append.
const fmBefore = readFederationMetadata(stamped);
if (fmBefore) {
// We've recorded the new vclock in this.aggregates; revert by
// looking up the prior state from the remaining events. Simpler
// approach: rebuild from local events for this aggregate.
const remaining = (inner.events ?? []).filter(
(e) => e.aggregateId === stamped.aggregateId,
);
const last = remaining[remaining.length - 1];
const lastFm = last ? readFederationMetadata(last) : undefined;
this.aggregates.set(stamped.aggregateId, {
vclock: lastFm?.vclock ?? zeroVectorClock(),
hlc: lastFm?.hlc,
});
}
}
}
@@ -0,0 +1,160 @@
/**
* Federation Bridge — translates ClaimDomainEvent ↔ federation envelopes.
*
* The bridge is the ONLY place in the claims module that knows the federation
* envelope wire format. Both `FederatedClaimRepository` (for claim mutations)
* and `FederatedClaimEventStore` (for event-sourcing append) delegate the
* cross-node publish/receive to this module so the federation contract stays
* confined to a single seam.
*
* Why a structural type instead of a real import from
* `@claude-flow/plugin-agent-federation`: the claims module must remain
* single-node-usable without the federation plugin installed. We pin the
* minimal shape we need; if the federation plugin changes its envelope, the
* bridge fails closed at runtime via the verification step rather than at
* import time. Tests inject a minimal in-memory transport for unit coverage.
*
* @module v3/claims/infrastructure/federation-bridge
* @see ADR-101 Component B
*/
import type { ClaimDomainEvent } from '../domain/events.js';
import type { HlcTimestamp } from './hlc.js';
import type { VectorClock } from './vector-clock.js';
// =============================================================================
// Federation envelope shape (structural — see module header)
// =============================================================================
/**
* Minimal federation envelope shape the bridge depends on.
* Real envelopes from plugin-agent-federation include more fields (peer
* registry refs, hop counters, etc.); we only require what the bridge writes.
*/
export interface FederationEnvelope<TPayload = unknown> {
readonly type: string;
readonly originNodeId: string;
readonly targetNodeId?: string; // omitted for broadcast
readonly hlc: HlcTimestamp;
readonly payload: TPayload;
readonly signature?: string; // Ed25519 hex; populated by signing step
}
/**
* The transport the bridge writes envelopes to. In production this is a
* thin wrapper around plugin-agent-federation's RoutingService; in tests
* this can be an in-memory queue.
*/
export interface IFederationTransport {
/** Broadcast an envelope to all peers in the trust circle. */
publish(envelope: FederationEnvelope): Promise<void>;
/** PII pre-publish scan. Should throw on detection. */
scanPii(payload: unknown): Promise<void>;
}
/**
* The PII guard error thrown when the pre-publish scan detects sensitive
* data. Surfaces to the application layer as a `PII_LEAK_PREVENTED` failure.
*/
export class PiiLeakPreventedError extends Error {
constructor(public readonly field: string, public readonly hint: string) {
super(`PII detected in field '${field}'; refusing to publish across federation. ${hint}`);
this.name = 'PiiLeakPreventedError';
}
}
// =============================================================================
// Federated event shape — what flies on the wire
// =============================================================================
/**
* `claim-event` envelope payload. This is what receivers see after
* Ed25519 verification.
*/
export interface ClaimEventEnvelopePayload {
readonly event: ClaimDomainEvent;
readonly vclock: VectorClock;
readonly originNodeId: string;
readonly hlc: HlcTimestamp;
}
export const CLAIM_EVENT_MESSAGE_TYPE = 'claim-event' as const;
// =============================================================================
// Bridge
// =============================================================================
export interface FederationBridgeOptions {
readonly nodeId: string;
readonly transport: IFederationTransport;
}
export class FederationBridge {
constructor(private readonly opts: FederationBridgeOptions) {
if (!opts.nodeId) throw new Error('FederationBridge requires nodeId');
}
/**
* Publish a claim event to the federation.
*
* Flow:
* 1. Run PII scan on the event payload + metadata. Failure throws
* PiiLeakPreventedError; the caller is expected to roll back the
* local write.
* 2. Wrap event in a `claim-event` envelope.
* 3. Hand to transport.publish().
*
* Returns the envelope as published (without signature — the transport
* is responsible for signing). Useful for callers that want to log what
* was actually sent.
*/
async publishClaimEvent(
event: ClaimDomainEvent,
vclock: VectorClock,
hlc: HlcTimestamp,
): Promise<FederationEnvelope<ClaimEventEnvelopePayload>> {
// PII guard. We scan the *full* payload object — the transport's scanPii
// is responsible for walking the nested structure.
await this.opts.transport.scanPii({
payload: event.payload,
metadata: event.metadata,
});
const envelope: FederationEnvelope<ClaimEventEnvelopePayload> = {
type: CLAIM_EVENT_MESSAGE_TYPE,
originNodeId: this.opts.nodeId,
hlc,
payload: {
event,
vclock,
originNodeId: this.opts.nodeId,
hlc,
},
};
await this.opts.transport.publish(envelope);
return envelope;
}
/**
* Decode an incoming envelope back into the claim event + vclock + hlc
* tuple. Validates the envelope shape; does NOT verify the signature
* (that's the transport's job, before this method is called).
*/
decode(envelope: FederationEnvelope): ClaimEventEnvelopePayload {
if (envelope.type !== CLAIM_EVENT_MESSAGE_TYPE) {
throw new Error(
`FederationBridge.decode: expected type '${CLAIM_EVENT_MESSAGE_TYPE}', got '${envelope.type}'`,
);
}
const payload = envelope.payload as ClaimEventEnvelopePayload;
if (!payload || typeof payload !== 'object') {
throw new Error('FederationBridge.decode: payload missing or non-object');
}
if (!payload.event || !payload.vclock || !payload.hlc || !payload.originNodeId) {
throw new Error('FederationBridge.decode: payload missing required fields');
}
return payload;
}
}
@@ -33,3 +33,42 @@ export {
type IHlc,
type PhysicalClock,
} from './hlc.js';
// Vector Clock (ADR-101 Component B)
export {
zeroVectorClock,
tickVectorClock,
mergeVectorClocks,
compareVectorClocks,
areConcurrent,
vectorClockToString,
pruneVectorClock,
type VectorClock,
type VectorClockOrder,
} from './vector-clock.js';
// Federation Bridge (ADR-101 Component B — single seam to federation envelopes)
export {
FederationBridge,
PiiLeakPreventedError,
CLAIM_EVENT_MESSAGE_TYPE,
type FederationEnvelope,
type IFederationTransport,
type ClaimEventEnvelopePayload,
type FederationBridgeOptions,
} from './federation-bridge.js';
// Federated Event Store (ADR-101 Component B)
export {
FederatedClaimEventStore,
ConcurrentWriteError,
type FederatedClaimEventStoreOptions,
type FederationMetadata,
} from './federated-event-store.js';
// Federated Claim Repository (ADR-101 Component B)
export {
FederatedClaimRepository,
type FederatedClaimRepositoryOptions,
type FederatedQueryOptions,
} from './federated-claim-repository.js';
@@ -0,0 +1,136 @@
/**
* Vector Clock for federated claim aggregates.
*
* Replaces the per-aggregate integer `version` counter in
* `InMemoryClaimEventStore` with a per-aggregate vector clock that captures
* causal history across nodes. Two events with concurrent vector clocks
* (neither is happens-before the other) signal a true concurrent-write
* conflict that the application layer must resolve via the existing contest
* mechanism.
*
* @module v3/claims/infrastructure/vector-clock
* @see ADR-101 Component B
*/
/**
* A vector clock — `{[nodeId]: integer}` representing the causal history
* seen at the issuing node when an event was created.
*/
export interface VectorClock {
readonly clocks: Readonly<Record<string, number>>;
}
/**
* The all-zero vector clock. Used as the seed for new aggregates.
*/
export function zeroVectorClock(): VectorClock {
return Object.freeze({ clocks: Object.freeze({}) });
}
/**
* Increment the entry for `nodeId` in `vc` by 1.
* Used when a node generates a new local event.
*
* Pure function — does not mutate `vc`.
*/
export function tickVectorClock(vc: VectorClock, nodeId: string): VectorClock {
if (!nodeId) {
throw new Error('tickVectorClock: nodeId must be non-empty');
}
const current = vc.clocks[nodeId] ?? 0;
return Object.freeze({
clocks: Object.freeze({ ...vc.clocks, [nodeId]: current + 1 }),
});
}
/**
* Merge two vector clocks by taking the per-node maximum.
* Used when a node receives a remote event — the merged clock represents
* "everything I know about, plus everything the remote knows about."
*
* Pure function — returns a new VectorClock.
*/
export function mergeVectorClocks(a: VectorClock, b: VectorClock): VectorClock {
const merged: Record<string, number> = { ...a.clocks };
for (const [nodeId, value] of Object.entries(b.clocks)) {
const current = merged[nodeId] ?? 0;
if (value > current) {
merged[nodeId] = value;
}
}
return Object.freeze({ clocks: Object.freeze(merged) });
}
/**
* Result of comparing two vector clocks. Unlike scalar clocks, vector
* clocks form a partial order — two clocks can be EQUAL, BEFORE, AFTER,
* or CONCURRENT (genuinely incomparable).
*/
export type VectorClockOrder = 'equal' | 'before' | 'after' | 'concurrent';
/**
* Compare two vector clocks. Returns:
* - 'equal' : a and b are identical
* - 'before' : a happens-before b (a ⊑ b strict)
* - 'after' : b happens-before a
* - 'concurrent' : neither dominates — true concurrent writes
*
* Reference: Lamport 1978, "Time, Clocks, and the Ordering of Events".
*/
export function compareVectorClocks(a: VectorClock, b: VectorClock): VectorClockOrder {
// Collect every nodeId that appears in either clock; missing entries are 0.
const allNodes = new Set<string>([
...Object.keys(a.clocks),
...Object.keys(b.clocks),
]);
let aDominates = false; // ∃ node where a > b
let bDominates = false; // ∃ node where b > a
for (const nodeId of allNodes) {
const av = a.clocks[nodeId] ?? 0;
const bv = b.clocks[nodeId] ?? 0;
if (av > bv) aDominates = true;
if (bv > av) bDominates = true;
}
if (!aDominates && !bDominates) return 'equal';
if (aDominates && !bDominates) return 'after';
if (!aDominates && bDominates) return 'before';
return 'concurrent';
}
/**
* `true` iff a and b are concurrent (neither happens-before the other).
* The contest mechanism in `WorkStealingService` is invoked exactly when
* this returns `true` for two writes against the same claim aggregate.
*/
export function areConcurrent(a: VectorClock, b: VectorClock): boolean {
return compareVectorClocks(a, b) === 'concurrent';
}
/**
* Serialize a vector clock to a stable string representation, suitable for
* use as an idempotency key or log line. Sorted by nodeId for determinism.
*/
export function vectorClockToString(vc: VectorClock): string {
const entries = Object.entries(vc.clocks).sort(([a], [b]) => a.localeCompare(b));
return entries.map(([k, v]) => `${k}:${v}`).join(',') || '∅';
}
/**
* Prune entries for nodes no longer in the federation.
* Used during peer-eviction (per ADR-097) to keep clocks bounded.
*
* @param vc Vector clock to prune
* @param keepers Set of nodeIds that should remain
*/
export function pruneVectorClock(vc: VectorClock, keepers: ReadonlySet<string>): VectorClock {
const pruned: Record<string, number> = {};
for (const [nodeId, value] of Object.entries(vc.clocks)) {
if (keepers.has(nodeId)) {
pruned[nodeId] = value;
}
}
return Object.freeze({ clocks: Object.freeze(pruned) });
}
@@ -0,0 +1,250 @@
/**
* Federated event store tests.
*
* Coverage targets (per ADR-101 Component B):
* - vector-clock advances on each local append
* - remote events that strictly precede local state are no-ops
* - remote events concurrent with local state throw ConcurrentWriteError
* - PII detected during publish rolls back the local append
* - HLC merges from remote events
* - subscribe / getEvents / getEventsByType / getEventsByIssueId pass through
*/
import { describe, expect, it, beforeEach, vi } from 'vitest';
import { InMemoryClaimEventStore } from '../src/infrastructure/event-store';
import {
FederatedClaimEventStore,
ConcurrentWriteError,
} from '../src/infrastructure/federated-event-store';
import {
FederationBridge,
type IFederationTransport,
PiiLeakPreventedError,
} from '../src/infrastructure/federation-bridge';
import { LocalHlc } from '../src/infrastructure/hlc';
import {
zeroVectorClock,
tickVectorClock,
type VectorClock,
} from '../src/infrastructure/vector-clock';
import type { ClaimDomainEvent } from '../src/domain/events';
// ───── helpers ─────
function makeEvent(overrides: Partial<ClaimDomainEvent> = {}): ClaimDomainEvent {
return {
id: `evt-${Math.random().toString(36).slice(2, 10)}`,
type: 'claim:created',
aggregateId: 'claim-001',
aggregateType: 'claim',
version: 0,
timestamp: Date.now(),
source: 'test',
payload: { foo: 'bar' },
...overrides,
};
}
function makeStore(opts: {
nodeId?: string;
bridge?: FederationBridge;
} = {}) {
const local = new InMemoryClaimEventStore();
const hlc = new LocalHlc(opts.nodeId ?? 'node-A', () => 1_000_000);
const store = new FederatedClaimEventStore({
local,
hlc,
nodeId: opts.nodeId ?? 'node-A',
bridge: opts.bridge,
});
return { local, hlc, store };
}
// ───── tests ─────
describe('FederatedClaimEventStore', () => {
describe('local append', () => {
it('ticks the per-aggregate vclock on each local append', async () => {
const { store } = makeStore();
await store.initialize();
await store.append(makeEvent({ id: 'e1' }));
const vc1 = store.getAggregateVclock('claim-001');
expect(vc1.clocks).toEqual({ 'node-A': 1 });
await store.append(makeEvent({ id: 'e2' }));
const vc2 = store.getAggregateVclock('claim-001');
expect(vc2.clocks).toEqual({ 'node-A': 2 });
});
it('keeps separate vclocks per aggregate', async () => {
const { store } = makeStore();
await store.initialize();
await store.append(makeEvent({ aggregateId: 'claim-001' }));
await store.append(makeEvent({ aggregateId: 'claim-002' }));
expect(store.getAggregateVclock('claim-001').clocks).toEqual({ 'node-A': 1 });
expect(store.getAggregateVclock('claim-002').clocks).toEqual({ 'node-A': 1 });
});
});
describe('applyRemoteEvent', () => {
it('accepts a remote event that strictly follows local state', async () => {
const { store } = makeStore();
await store.initialize();
// Remote knows about node-A's first event AND has added its own.
const remoteVclock: VectorClock = Object.freeze({
clocks: Object.freeze({ 'node-B': 1 }),
});
await store.applyRemoteEvent(
makeEvent({ id: 'e-remote' }),
remoteVclock,
{ physicalMs: 1_000_000, logical: 0, nodeId: 'node-B' },
);
expect(store.getAggregateVclock('claim-001').clocks).toEqual({ 'node-B': 1 });
});
it('drops remote events that are equal to or before local state (idempotent)', async () => {
const { store } = makeStore();
await store.initialize();
await store.append(makeEvent({ id: 'e1' })); // local at {A:1}
const beforeCount = (await store.getEvents('claim-001')).length;
// Remote tries to deliver an event with clock {A:1} — already known.
await store.applyRemoteEvent(
makeEvent({ id: 'e-rebroadcast' }),
Object.freeze({ clocks: Object.freeze({ 'node-A': 1 }) }),
{ physicalMs: 1_000_000, logical: 0, nodeId: 'node-A' },
);
const afterCount = (await store.getEvents('claim-001')).length;
expect(afterCount).toBe(beforeCount); // no duplicate
});
it('throws ConcurrentWriteError on concurrent vclocks', async () => {
const { store } = makeStore();
await store.initialize();
// Local has {A:1}; remote has {B:1} — concurrent.
await store.append(makeEvent({ id: 'e-local' }));
await expect(
store.applyRemoteEvent(
makeEvent({ id: 'e-remote' }),
Object.freeze({ clocks: Object.freeze({ 'node-B': 1 }) }),
{ physicalMs: 1_000_000, logical: 0, nodeId: 'node-B' },
),
).rejects.toBeInstanceOf(ConcurrentWriteError);
});
});
describe('PII rollback', () => {
it('rolls back the local append when the bridge throws PiiLeakPrevented', async () => {
// Mock transport: scanPii throws, publish never called.
const transport: IFederationTransport = {
publish: vi.fn(),
scanPii: vi.fn(async () => {
throw new PiiLeakPreventedError('payload', 'looks like an SSN');
}),
};
const bridge = new FederationBridge({ nodeId: 'node-A', transport });
const { store, local } = makeStore({ bridge });
await store.initialize();
const event = makeEvent({ id: 'e-pii' });
await expect(store.append(event)).rejects.toBeInstanceOf(PiiLeakPreventedError);
// Local store should NOT contain the event.
const events = await local.getEvents('claim-001');
expect(events.find((e) => e.id === 'e-pii')).toBeUndefined();
// Aggregate vclock should NOT have advanced past zero (or whatever it was before).
const vc = store.getAggregateVclock('claim-001');
expect(vc.clocks).toEqual({});
// Transport publish should not have been called.
expect(transport.publish).not.toHaveBeenCalled();
});
it('keeps the local append when the bridge succeeds', async () => {
const published: any[] = [];
const transport: IFederationTransport = {
publish: vi.fn(async (env) => { published.push(env); }),
scanPii: vi.fn(async () => { /* clean */ }),
};
const bridge = new FederationBridge({ nodeId: 'node-A', transport });
const { store, local } = makeStore({ bridge });
await store.initialize();
await store.append(makeEvent({ id: 'e-clean' }));
expect((await local.getEvents('claim-001')).length).toBe(1);
expect(published.length).toBe(1);
expect(published[0].type).toBe('claim-event');
expect(published[0].payload.event.id).toBe('e-clean');
});
});
describe('wouldConflict', () => {
it('returns true for concurrent clocks, false otherwise', async () => {
const { store } = makeStore();
await store.initialize();
await store.append(makeEvent());
// Same node-A vclock — not concurrent (equal/before)
expect(
store.wouldConflict('claim-001', tickVectorClock(zeroVectorClock(), 'node-A')),
).toBe(false);
// node-B with no awareness of node-A — concurrent
expect(
store.wouldConflict('claim-001', tickVectorClock(zeroVectorClock(), 'node-B')),
).toBe(true);
});
});
describe('IClaimEventStore pass-through', () => {
it('getEvents / getEventsByType / getEventsByIssueId delegate to local', async () => {
const { store } = makeStore();
await store.initialize();
await store.append(makeEvent({ id: 'e1', aggregateId: 'claim-001' }));
await store.append(makeEvent({
id: 'e2',
aggregateId: 'claim-002',
type: 'claim:released',
payload: { issueId: 'issue-XYZ' },
}));
expect((await store.getEvents('claim-001')).length).toBe(1);
expect((await store.getEventsByType('claim:released')).length).toBe(1);
expect((await store.getEventsByIssueId('issue-XYZ')).length).toBe(1);
});
it('subscribe returns an unsubscribe function', async () => {
const { store } = makeStore();
await store.initialize();
const handler = vi.fn();
const unsub = store.subscribe(['claim:created'], handler);
expect(typeof unsub).toBe('function');
await store.append(makeEvent({ type: 'claim:created' }));
// Subscriptions are async — give the microtask queue a chance.
await Promise.resolve();
expect(handler).toHaveBeenCalled();
unsub();
handler.mockClear();
await store.append(makeEvent({ type: 'claim:created' }));
await Promise.resolve();
expect(handler).not.toHaveBeenCalled();
});
});
});
@@ -0,0 +1,146 @@
/**
* Vector clock tests — partial-order behaviour, concurrent detection, GC.
*/
import { describe, expect, it } from 'vitest';
import {
zeroVectorClock,
tickVectorClock,
mergeVectorClocks,
compareVectorClocks,
areConcurrent,
vectorClockToString,
pruneVectorClock,
type VectorClock,
} from '../src/infrastructure/vector-clock';
const vc = (clocks: Record<string, number>): VectorClock =>
Object.freeze({ clocks: Object.freeze({ ...clocks }) });
describe('vector clock', () => {
describe('tickVectorClock', () => {
it('increments a fresh node from 0 to 1', () => {
const t = tickVectorClock(zeroVectorClock(), 'A');
expect(t.clocks).toEqual({ A: 1 });
});
it('increments an existing node', () => {
const t = tickVectorClock(vc({ A: 5 }), 'A');
expect(t.clocks).toEqual({ A: 6 });
});
it('does not mutate the input', () => {
const original = vc({ A: 5 });
const _ = tickVectorClock(original, 'A');
expect(original.clocks).toEqual({ A: 5 });
});
it('refuses empty nodeId', () => {
expect(() => tickVectorClock(zeroVectorClock(), '')).toThrow();
});
});
describe('mergeVectorClocks', () => {
it('takes per-node maximum', () => {
const a = vc({ A: 3, B: 1 });
const b = vc({ A: 1, B: 5, C: 2 });
expect(mergeVectorClocks(a, b).clocks).toEqual({ A: 3, B: 5, C: 2 });
});
it('is commutative', () => {
const a = vc({ A: 1, B: 2 });
const b = vc({ A: 3, B: 0, C: 1 });
expect(mergeVectorClocks(a, b).clocks).toEqual(mergeVectorClocks(b, a).clocks);
});
it('handles disjoint node sets', () => {
const a = vc({ A: 1 });
const b = vc({ B: 1 });
expect(mergeVectorClocks(a, b).clocks).toEqual({ A: 1, B: 1 });
});
});
describe('compareVectorClocks', () => {
it('returns equal for identical clocks', () => {
expect(compareVectorClocks(vc({ A: 1 }), vc({ A: 1 }))).toBe('equal');
expect(compareVectorClocks(zeroVectorClock(), zeroVectorClock())).toBe('equal');
});
it('returns before/after for strict dominance', () => {
// a strictly precedes b
const a = vc({ A: 1, B: 1 });
const b = vc({ A: 2, B: 1 });
expect(compareVectorClocks(a, b)).toBe('before');
expect(compareVectorClocks(b, a)).toBe('after');
});
it('returns concurrent for incomparable clocks', () => {
// A wrote on node X, B wrote on node Y — neither knows about the other
const a = vc({ X: 1 });
const b = vc({ Y: 1 });
expect(compareVectorClocks(a, b)).toBe('concurrent');
expect(areConcurrent(a, b)).toBe(true);
});
it('treats missing entries as 0', () => {
expect(compareVectorClocks(vc({ A: 0 }), zeroVectorClock())).toBe('equal');
expect(compareVectorClocks(vc({ A: 1 }), zeroVectorClock())).toBe('after');
expect(compareVectorClocks(zeroVectorClock(), vc({ A: 1 }))).toBe('before');
});
});
describe('vectorClockToString', () => {
it('sorts by nodeId for determinism', () => {
// Same content, different insertion order — string must match
const a = vc({ B: 2, A: 1, C: 3 });
const b = vc({ A: 1, C: 3, B: 2 });
expect(vectorClockToString(a)).toBe(vectorClockToString(b));
expect(vectorClockToString(a)).toBe('A:1,B:2,C:3');
});
it('renders the empty clock as ∅', () => {
expect(vectorClockToString(zeroVectorClock())).toBe('∅');
});
});
describe('pruneVectorClock', () => {
it('keeps only nodes in the keeper set', () => {
const before = vc({ A: 1, B: 2, C: 3 });
const keepers = new Set(['A', 'C']);
expect(pruneVectorClock(before, keepers).clocks).toEqual({ A: 1, C: 3 });
});
it('returns empty when no keepers match', () => {
const before = vc({ A: 1 });
expect(pruneVectorClock(before, new Set()).clocks).toEqual({});
});
});
describe('end-to-end causal scenario', () => {
it('captures the canonical Lamport handoff scenario', () => {
// Three nodes: A creates an event, B receives it and creates its own,
// C creates a concurrent event without seeing B's. The clocks should
// identify A→B as causal and B↔C as concurrent.
let onA = zeroVectorClock();
let onB = zeroVectorClock();
let onC = zeroVectorClock();
// A: local event
onA = tickVectorClock(onA, 'A');
const eventA = onA;
// B: receives event from A, then creates its own
onB = mergeVectorClocks(onB, eventA);
onB = tickVectorClock(onB, 'B');
const eventB = onB;
// C: creates a local event without seeing A or B
onC = tickVectorClock(onC, 'C');
const eventC = onC;
expect(compareVectorClocks(eventA, eventB)).toBe('before');
expect(compareVectorClocks(eventA, eventC)).toBe('concurrent');
expect(compareVectorClocks(eventB, eventC)).toBe('concurrent');
});
});
});