Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

ADR-101: Federated Claims β€” cross-node work coordination (Phases 1-3) (#1777)

rUv9d4a9ea968d9
diff --git a/v3/@claude-flow/claims/src/application/work-stealing-service.ts b/v3/@claude-flow/claims/src/application/work-stealing-service.ts
index 993c04cac3..54a9b6209e 100644
--- a/v3/@claude-flow/claims/src/application/work-stealing-service.ts
+++ b/v3/@claude-flow/claims/src/application/work-stealing-service.ts
@@ -171,13 +171,30 @@ export class InMemoryWorkStealingEventBus implements IWorkStealingEventBus {
*/
export class WorkStealingService implements IWorkStealingService {
private readonly config: WorkStealingConfig;
+ // ADR-101 Component A: optional HLC for skew-tolerant time comparisons
+ // across federated nodes. Single-node deployments leave this undefined and
+ // continue to use Date.now() β€” preserving backwards compatibility.
+ private readonly hlc: import('../infrastructure/hlc.js').IHlc | undefined;
constructor(
private readonly repository: IIssueClaimRepository,
private readonly eventBus: IWorkStealingEventBus,
- config: Partial<WorkStealingConfig> = {}
+ config: Partial<WorkStealingConfig> = {},
+ hlc?: import('../infrastructure/hlc.js').IHlc,
) {
this.config = { ...DEFAULT_WORK_STEALING_CONFIG, ...config };
+ this.hlc = hlc;
+ }
+
+ /**
+ * Get the current "now" as an epoch ms.
+ *
+ * When an HLC is wired in (federated mode), use its physicalMs which is
+ * monotonic across the federation. Otherwise fall back to wall clock.
+ */
+ private nowMs(): number {
+ if (this.hlc) return this.hlc.now().physicalMs;
+ return Date.now();
}
// ===========================================================================
@@ -354,8 +371,9 @@ export class WorkStealingService implements IWorkStealingService {
throw new Error('Contest has already been resolved');
}
- const now = new Date();
- if (now > claim.contestInfo.windowEndsAt) {
+ const nowMs = this.nowMs();
+ const windowEndsAtMs = new Date(claim.contestInfo.windowEndsAt).getTime();
+ if (nowMs > windowEndsAtMs) {
throw new Error('Contest window has expired');
}
@@ -366,7 +384,7 @@ export class WorkStealingService implements IWorkStealingService {
// Update contest info with reason
claim.contestInfo.reason = reason;
- claim.contestInfo.contestedAt = now;
+ claim.contestInfo.contestedAt = new Date(nowMs);
await this.repository.update(claim);
@@ -539,9 +557,9 @@ export class WorkStealingService implements IWorkStealingService {
*/
private isInGracePeriodWithConfig(claim: IssueClaimWithStealing, config: WorkStealingConfig): boolean {
const gracePeriodMs = config.gracePeriodMinutes * 60 * 1000;
- const now = new Date();
- const claimedAt = new Date(claim.claimedAt);
- return now.getTime() - claimedAt.getTime() < gracePeriodMs;
+ const nowMs = this.nowMs();
+ const claimedAtMs = new Date(claim.claimedAt).getTime();
+ return nowMs - claimedAtMs < gracePeriodMs;
}
/**
diff --git a/v3/@claude-flow/claims/src/infrastructure/federated-claim-repository.ts b/v3/@claude-flow/claims/src/infrastructure/federated-claim-repository.ts
new file mode 100644
index 0000000000..a9bc4be559
--- /dev/null
+++ b/v3/@claude-flow/claims/src/infrastructure/federated-claim-repository.ts
@@ -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();
+ }
+}
diff --git a/v3/@claude-flow/claims/src/infrastructure/federated-event-store.ts b/v3/@claude-flow/claims/src/infrastructure/federated-event-store.ts
new file mode 100644
index 0000000000..2fc8018c68
--- /dev/null
+++ b/v3/@claude-flow/claims/src/infrastructure/federated-event-store.ts
@@ -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,
+ });
+ }
+ }
+}
diff --git a/v3/@claude-flow/claims/src/infrastructure/federation-bridge.ts b/v3/@claude-flow/claims/src/infrastructure/federation-bridge.ts
new file mode 100644
index 0000000000..aff8507bf8
--- /dev/null
+++ b/v3/@claude-flow/claims/src/infrastructure/federation-bridge.ts
@@ -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;
+ }
+}
diff --git a/v3/@claude-flow/claims/src/infrastructure/hlc.ts b/v3/@claude-flow/claims/src/infrastructure/hlc.ts
new file mode 100644
index 0000000000..369d88f751
--- /dev/null
+++ b/v3/@claude-flow/claims/src/infrastructure/hlc.ts
@@ -0,0 +1,198 @@
+/**
+ * Hybrid Logical Clock (HLC).
+ *
+ * Implements Kulkarni et al. 2014 β€” 64-bit-ish timestamps that:
+ * - monotonically advance on every event, even when wall clock goes backward,
+ * - track causality across nodes the way Lamport clocks do,
+ * - stay within a small bounded skew of physical time so they remain
+ * human-readable for debugging.
+ *
+ * In single-node mode the HLC degenerates: `physicalMs` tracks the wall clock
+ * exactly and `logical` stays at 0, so HLC values are pairwise-comparable to
+ * plain Unix timestamps. This is the property that lets ADR-101 wire HLC into
+ * existing Date-based callsites without breaking single-node deployments.
+ *
+ * @module v3/claims/infrastructure/hlc
+ * @see ADR-101 Component A
+ */
+
+/**
+ * Maximum skew (ms) we will accept from a remote HLC before clamping.
+ * Default 30 s. Configurable per federation.
+ */
+export const DEFAULT_MAX_SKEW_MS = 30_000;
+
+/**
+ * A point in HLC time.
+ *
+ * Encoding choice: a plain object rather than a packed bigint. We store these
+ * in JSON-serialized federation envelopes and in event logs that are read by
+ * humans during postmortems. Readability beats 8-byte packing at this scale.
+ */
+export interface HlcTimestamp {
+ /** Wall-clock millis at issuance, possibly bumped forward by causal events. */
+ readonly physicalMs: number;
+ /** Tie-breaker: monotonic counter incremented when two HLCs share a physicalMs. */
+ readonly logical: number;
+ /** Issuing node identifier. Lets `compare` deterministically order HLCs from different nodes that share (physicalMs, logical). */
+ readonly nodeId: string;
+}
+
+/**
+ * The all-zero HLC. Used to represent "no clock seen yet" β€” e.g., events
+ * loaded from a pre-HLC store that need an HLC field for the new code paths.
+ * Always sorts before any real HLC.
+ */
+export function zeroHlc(nodeId = ''): HlcTimestamp {
+ return Object.freeze({ physicalMs: 0, logical: 0, nodeId });
+}
+
+/**
+ * Pluggable physical-time source. Tests inject a mock; production uses Date.now.
+ */
+export type PhysicalClock = () => number;
+
+const SYSTEM_CLOCK: PhysicalClock = () => Date.now();
+
+/**
+ * The clock errors we throw on policy violations. Callers can catch these
+ * specifically rather than relying on string matching.
+ */
+export class HlcSkewError extends Error {
+ constructor(
+ public readonly receivedPhysicalMs: number,
+ public readonly localPhysicalMs: number,
+ public readonly maxSkewMs: number,
+ ) {
+ super(
+ `HLC skew exceeded: received physicalMs=${receivedPhysicalMs} ` +
+ `vs local=${localPhysicalMs} (max=${maxSkewMs}ms)`,
+ );
+ this.name = 'HlcSkewError';
+ }
+}
+
+/**
+ * The clock interface that ClaimService and WorkStealingService depend on.
+ * Pure interface so single-node deployments can pass a `LocalHlc` and
+ * federated deployments can pass an instance backed by federation gossip.
+ */
+export interface IHlc {
+ /** Generate a new HLC timestamp for a local event. */
+ now(): HlcTimestamp;
+ /** Update the clock from a received HLC. Returns the updated local time. */
+ update(received: HlcTimestamp): HlcTimestamp;
+ /** Read-only access to the most recently observed HLC. */
+ peek(): HlcTimestamp;
+}
+
+/**
+ * Local HLC implementation.
+ *
+ * Construction notes:
+ * - `nodeId` should be stable for the lifetime of a process. For federation
+ * it must be unique across the trust circle; in single-node mode any
+ * constant works.
+ * - The clock is mutable; treat the instance as a process-wide singleton.
+ */
+export class LocalHlc implements IHlc {
+ private last: HlcTimestamp;
+
+ constructor(
+ public readonly nodeId: string,
+ private readonly physicalClock: PhysicalClock = SYSTEM_CLOCK,
+ public readonly maxSkewMs: number = DEFAULT_MAX_SKEW_MS,
+ ) {
+ if (!nodeId) {
+ throw new Error('LocalHlc requires a non-empty nodeId');
+ }
+ // Seed with the smallest possible timestamp so the first now() always
+ // takes the "wall clock advanced" branch and produces logical=0. Without
+ // this seed, the first now() would see (last.physicalMs == wall) and
+ // bump logical to 1, breaking single-node degeneracy with wall-clock ms.
+ this.last = { physicalMs: -1, logical: 0, nodeId };
+ }
+
+ now(): HlcTimestamp {
+ const wall = this.physicalClock();
+ let physicalMs: number;
+ let logical: number;
+
+ if (wall > this.last.physicalMs) {
+ // Wall clock advanced β€” adopt it, reset logical counter.
+ physicalMs = wall;
+ logical = 0;
+ } else {
+ // Wall clock didn't advance (or went backward); keep last physical and bump logical.
+ physicalMs = this.last.physicalMs;
+ logical = this.last.logical + 1;
+ }
+
+ this.last = { physicalMs, logical, nodeId: this.nodeId };
+ return this.last;
+ }
+
+ update(received: HlcTimestamp): HlcTimestamp {
+ const wall = this.physicalClock();
+
+ // Skew guard: refuse HLCs that are too far in the future.
+ // We DO NOT jump local clock forward to match β€” a misbehaving peer would
+ // poison the global timeline. Instead we throw and let the caller decide.
+ if (received.physicalMs > wall + this.maxSkewMs) {
+ throw new HlcSkewError(received.physicalMs, wall, this.maxSkewMs);
+ }
+
+ const maxPhysical = Math.max(wall, this.last.physicalMs, received.physicalMs);
+
+ let logical: number;
+ if (maxPhysical === this.last.physicalMs && maxPhysical === received.physicalMs) {
+ logical = Math.max(this.last.logical, received.logical) + 1;
+ } else if (maxPhysical === this.last.physicalMs) {
+ logical = this.last.logical + 1;
+ } else if (maxPhysical === received.physicalMs) {
+ logical = received.logical + 1;
+ } else {
+ logical = 0;
+ }
+
+ this.last = { physicalMs: maxPhysical, logical, nodeId: this.nodeId };
+ return this.last;
+ }
+
+ peek(): HlcTimestamp {
+ return this.last;
+ }
+}
+
+/**
+ * Compare two HLC timestamps. Returns -1, 0, or +1 like Date comparison.
+ *
+ * Order: physicalMs, then logical, then nodeId (lexicographic). The nodeId
+ * tiebreaker is what makes this a total order across the federation.
+ */
+export function compareHlc(a: HlcTimestamp, b: HlcTimestamp): -1 | 0 | 1 {
+ if (a.physicalMs < b.physicalMs) return -1;
+ if (a.physicalMs > b.physicalMs) return 1;
+ if (a.logical < b.logical) return -1;
+ if (a.logical > b.logical) return 1;
+ if (a.nodeId < b.nodeId) return -1;
+ if (a.nodeId > b.nodeId) return 1;
+ return 0;
+}
+
+/**
+ * Convert HLC to a plain millisecond timestamp for legacy comparisons.
+ * Lossy by design β€” the logical bits are dropped. Only use this on the
+ * boundary with code that can't be HLC-ified yet.
+ */
+export function hlcToWallMs(t: HlcTimestamp): number {
+ return t.physicalMs;
+}
+
+/**
+ * Lift a wall-clock millisecond into HLC space at logical=0. Useful for
+ * upgrading legacy events on read.
+ */
+export function wallMsToHlc(ms: number, nodeId: string): HlcTimestamp {
+ return Object.freeze({ physicalMs: ms, logical: 0, nodeId });
+}
diff --git a/v3/@claude-flow/claims/src/infrastructure/index.ts b/v3/@claude-flow/claims/src/infrastructure/index.ts
index 3f464c0ec9..a3105803b9 100644
--- a/v3/@claude-flow/claims/src/infrastructure/index.ts
+++ b/v3/@claude-flow/claims/src/infrastructure/index.ts
@@ -19,3 +19,56 @@ export {
type EventFilter,
type EventSubscription,
} from './event-store.js';
+
+// Hybrid Logical Clock (ADR-101 Component A)
+export {
+ LocalHlc,
+ HlcSkewError,
+ compareHlc,
+ hlcToWallMs,
+ wallMsToHlc,
+ zeroHlc,
+ DEFAULT_MAX_SKEW_MS,
+ type HlcTimestamp,
+ 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';
diff --git a/v3/@claude-flow/claims/src/infrastructure/vector-clock.ts b/v3/@claude-flow/claims/src/infrastructure/vector-clock.ts
new file mode 100644
index 0000000000..85d97a1a1a
--- /dev/null
+++ b/v3/@claude-flow/claims/src/infrastructure/vector-clock.ts
@@ -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) });
+}
diff --git a/v3/@claude-flow/claims/tests/federated-event-store.test.ts b/v3/@claude-flow/claims/tests/federated-event-store.test.ts
new file mode 100644
index 0000000000..d037513eec
--- /dev/null
+++ b/v3/@claude-flow/claims/tests/federated-event-store.test.ts
@@ -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();
+ });
+ });
+});
diff --git a/v3/@claude-flow/claims/tests/hlc.test.ts b/v3/@claude-flow/claims/tests/hlc.test.ts
new file mode 100644
index 0000000000..a937e7daf6
--- /dev/null
+++ b/v3/@claude-flow/claims/tests/hlc.test.ts
@@ -0,0 +1,216 @@
+/**
+ * Hybrid Logical Clock tests.
+ *
+ * Coverage targets (per ADR-101 Component A):
+ * - monotonic advance under wall-clock advance
+ * - logical bumps when wall clock stalls
+ * - logical bumps when wall clock goes backward
+ * - update() merges remote causality correctly
+ * - skew guard rejects far-future remote HLCs
+ * - compare yields a total order across nodes
+ * - degeneracy: single-node HLCs are wall-clock-equivalent
+ */
+
+import { describe, expect, it } from 'vitest';
+import {
+ LocalHlc,
+ HlcSkewError,
+ compareHlc,
+ zeroHlc,
+ hlcToWallMs,
+ wallMsToHlc,
+ DEFAULT_MAX_SKEW_MS,
+ type HlcTimestamp,
+} from '../src/infrastructure/hlc';
+
+/** Build a controllable physical-clock function for tests. */
+function fakeClock(start: number) {
+ let t = start;
+ return {
+ advance(ms: number) { t += ms; },
+ setTo(ms: number) { t = ms; },
+ read: () => t,
+ };
+}
+
+describe('LocalHlc', () => {
+ it('refuses an empty nodeId', () => {
+ expect(() => new LocalHlc('')).toThrow(/non-empty nodeId/);
+ });
+
+ describe('now()', () => {
+ it('advances physicalMs when wall clock advances', () => {
+ const wall = fakeClock(1_000);
+ const hlc = new LocalHlc('node-A', wall.read);
+ const t0 = hlc.now();
+ wall.advance(500);
+ const t1 = hlc.now();
+ expect(t1.physicalMs).toBe(1_500);
+ expect(t1.logical).toBe(0);
+ expect(compareHlc(t0, t1)).toBe(-1);
+ });
+
+ it('bumps logical when wall clock has not advanced', () => {
+ const wall = fakeClock(1_000);
+ const hlc = new LocalHlc('node-A', wall.read);
+ const t0 = hlc.now();
+ const t1 = hlc.now();
+ const t2 = hlc.now();
+ // wall clock didn't move β€” logical should monotonically increase
+ expect(t1.physicalMs).toBe(t0.physicalMs);
+ expect(t1.logical).toBe(t0.logical + 1);
+ expect(t2.logical).toBe(t1.logical + 1);
+ expect(compareHlc(t0, t1)).toBe(-1);
+ expect(compareHlc(t1, t2)).toBe(-1);
+ });
+
+ it('bumps logical when wall clock goes backward', () => {
+ const wall = fakeClock(2_000);
+ const hlc = new LocalHlc('node-A', wall.read);
+ const t0 = hlc.now();
+ wall.setTo(1_000); // NTP correction, VM resume, etc.
+ const t1 = hlc.now();
+ // physical does NOT regress; logical bumps to keep monotonicity
+ expect(t1.physicalMs).toBe(t0.physicalMs);
+ expect(t1.logical).toBeGreaterThan(t0.logical);
+ expect(compareHlc(t0, t1)).toBe(-1);
+ });
+ });
+
+ describe('update()', () => {
+ it('takes the max physical and bumps logical when remote is concurrent', () => {
+ const wall = fakeClock(1_000);
+ const local = new LocalHlc('node-A', wall.read);
+ // Remote is at physical 1000, logical 7 β€” same physical as ours
+ const remote: HlcTimestamp = { physicalMs: 1_000, logical: 7, nodeId: 'node-B' };
+ const merged = local.update(remote);
+ expect(merged.physicalMs).toBe(1_000);
+ expect(merged.logical).toBe(8); // max(0, 7) + 1
+ expect(merged.nodeId).toBe('node-A');
+ });
+
+ it('adopts remote physical when remote is ahead', () => {
+ const wall = fakeClock(1_000);
+ const local = new LocalHlc('node-A', wall.read);
+ const remote: HlcTimestamp = { physicalMs: 1_500, logical: 3, nodeId: 'node-B' };
+ const merged = local.update(remote);
+ expect(merged.physicalMs).toBe(1_500);
+ expect(merged.logical).toBe(4); // remote.logical + 1
+ });
+
+ it('keeps local physical when remote is in the past', () => {
+ const wall = fakeClock(2_000);
+ const local = new LocalHlc('node-A', wall.read);
+ const t0 = local.now();
+ const remote: HlcTimestamp = { physicalMs: 500, logical: 99, nodeId: 'node-B' };
+ const merged = local.update(remote);
+ expect(merged.physicalMs).toBe(t0.physicalMs);
+ // local's physical wins, logical bumps
+ expect(merged.logical).toBeGreaterThan(t0.logical);
+ });
+
+ it('throws HlcSkewError when remote is too far in the future', () => {
+ const wall = fakeClock(1_000);
+ const local = new LocalHlc('node-A', wall.read, 5_000); // 5s skew tolerance
+ const farFuture: HlcTimestamp = {
+ physicalMs: 1_000 + 6_000, // 6s ahead
+ logical: 0,
+ nodeId: 'node-B',
+ };
+ expect(() => local.update(farFuture)).toThrow(HlcSkewError);
+ });
+
+ it('accepts remote within the skew window', () => {
+ const wall = fakeClock(1_000);
+ const local = new LocalHlc('node-A', wall.read, 5_000);
+ const justInside: HlcTimestamp = {
+ physicalMs: 1_000 + 4_999,
+ logical: 0,
+ nodeId: 'node-B',
+ };
+ expect(() => local.update(justInside)).not.toThrow();
+ });
+
+ it('default skew tolerance is 30s', () => {
+ const wall = fakeClock(0);
+ const local = new LocalHlc('node-A', wall.read);
+ expect(local.maxSkewMs).toBe(DEFAULT_MAX_SKEW_MS);
+ expect(DEFAULT_MAX_SKEW_MS).toBe(30_000);
+ });
+ });
+
+ describe('compareHlc', () => {
+ it('orders by physical first, then logical, then nodeId', () => {
+ const aEarly: HlcTimestamp = { physicalMs: 1, logical: 0, nodeId: 'A' };
+ const aLate: HlcTimestamp = { physicalMs: 2, logical: 0, nodeId: 'A' };
+ const aLogical: HlcTimestamp = { physicalMs: 1, logical: 1, nodeId: 'A' };
+ const bSame: HlcTimestamp = { physicalMs: 1, logical: 0, nodeId: 'B' };
+
+ expect(compareHlc(aEarly, aLate)).toBe(-1);
+ expect(compareHlc(aLate, aEarly)).toBe(1);
+ expect(compareHlc(aEarly, aLogical)).toBe(-1);
+ expect(compareHlc(aEarly, bSame)).toBe(-1); // A < B lex
+ expect(compareHlc(bSame, aEarly)).toBe(1);
+ expect(compareHlc(aEarly, aEarly)).toBe(0);
+ });
+
+ it('produces a total order on a randomized set', () => {
+ const items: HlcTimestamp[] = [];
+ for (let i = 0; i < 50; i++) {
+ items.push({
+ physicalMs: Math.floor(Math.random() * 100),
+ logical: Math.floor(Math.random() * 10),
+ nodeId: ['A', 'B', 'C', 'D'][Math.floor(Math.random() * 4)]!,
+ });
+ }
+ const sorted = [...items].sort(compareHlc);
+ for (let i = 1; i < sorted.length; i++) {
+ expect(compareHlc(sorted[i - 1]!, sorted[i]!)).toBeLessThanOrEqual(0);
+ }
+ });
+ });
+
+ describe('helpers', () => {
+ it('hlcToWallMs returns physicalMs', () => {
+ expect(hlcToWallMs({ physicalMs: 42, logical: 99, nodeId: 'X' })).toBe(42);
+ });
+
+ it('wallMsToHlc lifts wall ms at logical=0', () => {
+ const lifted = wallMsToHlc(42, 'X');
+ expect(lifted).toEqual({ physicalMs: 42, logical: 0, nodeId: 'X' });
+ });
+
+ it('zeroHlc sorts before everything', () => {
+ const z = zeroHlc('A');
+ const real: HlcTimestamp = { physicalMs: 1, logical: 0, nodeId: 'A' };
+ expect(compareHlc(z, real)).toBe(-1);
+ });
+ });
+
+ describe('single-node degeneracy', () => {
+ it('produces wall-clock-equivalent ordering when no updates ever arrive', () => {
+ // ADR-101 promise: in single-node mode, HLC physicalMs tracks wall clock
+ // and is pairwise-comparable to plain Unix timestamps.
+ const wall = fakeClock(1_000);
+ const hlc = new LocalHlc('solo', wall.read);
+
+ const t0 = hlc.now();
+ wall.advance(100);
+ const t1 = hlc.now();
+ wall.advance(50);
+ const t2 = hlc.now();
+
+ // Each timestamp should match wall when wall advanced
+ expect(t0.physicalMs).toBe(1_000);
+ expect(t1.physicalMs).toBe(1_100);
+ expect(t2.physicalMs).toBe(1_150);
+ // Logical stays at 0 because wall advanced each time
+ expect(t0.logical).toBe(0);
+ expect(t1.logical).toBe(0);
+ expect(t2.logical).toBe(0);
+ // β†’ comparing physicalMs yields the same order as comparing HLCs
+ expect(t0.physicalMs < t1.physicalMs).toBe(true);
+ expect(t1.physicalMs < t2.physicalMs).toBe(true);
+ });
+ });
+});
diff --git a/v3/@claude-flow/claims/tests/vector-clock.test.ts b/v3/@claude-flow/claims/tests/vector-clock.test.ts
new file mode 100644
index 0000000000..5f4f36f2fb
--- /dev/null
+++ b/v3/@claude-flow/claims/tests/vector-clock.test.ts
@@ -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');
+ });
+ });
+});
diff --git a/v3/@claude-flow/plugin-agent-federation/__tests__/unit/federation-envelope-claims.test.ts b/v3/@claude-flow/plugin-agent-federation/__tests__/unit/federation-envelope-claims.test.ts
new file mode 100644
index 0000000000..feacea8120
--- /dev/null
+++ b/v3/@claude-flow/plugin-agent-federation/__tests__/unit/federation-envelope-claims.test.ts
@@ -0,0 +1,109 @@
+/**
+ * Tests for ADR-101 Component C additions to FederationMessageType.
+ *
+ * Asserts that:
+ * - 'claim-event' and 'agent-handoff' are valid FederationMessageType members
+ * - 'agent-handoff' is in CONSENSUS_REQUIRED_TYPES (high-trust deployments
+ * can require validator quorum)
+ * - 'claim-event' is NOT in CONSENSUS_REQUIRED_TYPES (steady-state gossip
+ * would deadlock under quorum requirement)
+ * - existing message types are unchanged (no accidental removals)
+ * - existing CONSENSUS_REQUIRED_TYPES members are unchanged
+ */
+
+import { describe, expect, it } from 'vitest';
+import {
+ FederationEnvelope,
+ CONSENSUS_REQUIRED_TYPES,
+ type FederationMessageType,
+} from '../../src/domain/entities/federation-envelope';
+
+describe('FederationMessageType β€” ADR-101 additions', () => {
+ it('accepts claim-event as a valid message type', () => {
+ const env = new FederationEnvelope({
+ envelopeId: 'env-1',
+ sourceNodeId: 'A',
+ targetNodeId: 'B',
+ sessionId: 'sess-1',
+ messageType: 'claim-event',
+ payload: { event: 'placeholder' },
+ timestamp: new Date(),
+ nonce: 'n-1',
+ hmacSignature: '',
+ piiScanResult: FederationEnvelope.emptyScanResult(),
+ });
+ expect(env.messageType).toBe('claim-event');
+ });
+
+ it('accepts agent-handoff as a valid message type', () => {
+ const env = new FederationEnvelope({
+ envelopeId: 'env-2',
+ sourceNodeId: 'A',
+ targetNodeId: 'B',
+ sessionId: 'sess-1',
+ messageType: 'agent-handoff',
+ payload: { claimId: 'claim-001', from: 'a@A', to: 'b@B' },
+ timestamp: new Date(),
+ nonce: 'n-2',
+ hmacSignature: '',
+ piiScanResult: FederationEnvelope.emptyScanResult(),
+ });
+ expect(env.messageType).toBe('agent-handoff');
+ });
+
+ it('agent-handoff requires consensus by default', () => {
+ expect(CONSENSUS_REQUIRED_TYPES.has('agent-handoff')).toBe(true);
+ });
+
+ it('claim-event does NOT require consensus (steady-state gossip)', () => {
+ expect(CONSENSUS_REQUIRED_TYPES.has('claim-event')).toBe(false);
+ });
+
+ it('preserves the pre-ADR-101 consensus-required set', () => {
+ // Snapshot the existing membership so future additions don't silently
+ // expand the consensus-required set.
+ expect(CONSENSUS_REQUIRED_TYPES.has('trust-change')).toBe(true);
+ expect(CONSENSUS_REQUIRED_TYPES.has('topology-change')).toBe(true);
+ expect(CONSENSUS_REQUIRED_TYPES.has('agent-spawn')).toBe(true);
+ });
+
+ it('preserves existing message types', () => {
+ // Type-level smoke test β€” these must compile.
+ const existing: FederationMessageType[] = [
+ 'task-assignment',
+ 'memory-query',
+ 'memory-response',
+ 'context-share',
+ 'status-broadcast',
+ 'trust-change',
+ 'topology-change',
+ 'agent-spawn',
+ 'heartbeat',
+ 'challenge',
+ 'challenge-response',
+ 'handshake-init',
+ 'handshake-accept',
+ 'handshake-reject',
+ 'session-terminate',
+ ];
+ expect(existing.length).toBe(15);
+ });
+
+ it('toSignablePayload includes the new message type when set', () => {
+ const env = new FederationEnvelope({
+ envelopeId: 'env-3',
+ sourceNodeId: 'A',
+ targetNodeId: 'B',
+ sessionId: 'sess-1',
+ messageType: 'agent-handoff',
+ payload: { claimId: 'claim-001' },
+ timestamp: new Date('2026-05-05T12:00:00Z'),
+ nonce: 'n-3',
+ hmacSignature: '',
+ piiScanResult: FederationEnvelope.emptyScanResult(),
+ });
+ const signable = env.toSignablePayload();
+ expect(signable).toContain('"messageType":"agent-handoff"');
+ expect(signable).toContain('"claim-001"');
+ });
+});
diff --git a/v3/@claude-flow/plugin-agent-federation/__tests__/unit/federation-envelope.test.ts b/v3/@claude-flow/plugin-agent-federation/__tests__/unit/federation-envelope.test.ts
index f97b1d7e1f..bb02a70cc0 100644
--- a/v3/@claude-flow/plugin-agent-federation/__tests__/unit/federation-envelope.test.ts
+++ b/v3/@claude-flow/plugin-agent-federation/__tests__/unit/federation-envelope.test.ts
@@ -212,8 +212,8 @@ describe('FederationEnvelope', () => {
expect(CONSENSUS_REQUIRED_TYPES.has('agent-spawn')).toBe(true);
});
- it('should contain exactly 3 entries', () => {
- expect(CONSENSUS_REQUIRED_TYPES.size).toBe(3);
+ it('should contain exactly 4 entries (ADR-101 added agent-handoff)', () => {
+ expect(CONSENSUS_REQUIRED_TYPES.size).toBe(4);
});
});
@@ -234,17 +234,20 @@ describe('FederationEnvelope', () => {
'handshake-accept',
'handshake-reject',
'session-terminate',
+ // ADR-101 Component C
+ 'claim-event',
+ 'agent-handoff',
];
- it('should accept all 15 message types as valid', () => {
+ it('should accept all 17 message types as valid', () => {
for (const msgType of allMessageTypes) {
const envelope = new FederationEnvelope(makeProps({ messageType: msgType }));
expect(envelope.messageType).toBe(msgType);
}
});
- it('should have exactly 15 known message types', () => {
- expect(allMessageTypes).toHaveLength(15);
+ it('should have exactly 17 known message types (15 base + 2 from ADR-101)', () => {
+ expect(allMessageTypes).toHaveLength(17);
});
});
});
diff --git a/v3/@claude-flow/plugin-agent-federation/src/domain/entities/federation-envelope.ts b/v3/@claude-flow/plugin-agent-federation/src/domain/entities/federation-envelope.ts
index 1ae5795438..03ed7d97f8 100644
--- a/v3/@claude-flow/plugin-agent-federation/src/domain/entities/federation-envelope.ts
+++ b/v3/@claude-flow/plugin-agent-federation/src/domain/entities/federation-envelope.ts
@@ -13,7 +13,10 @@ export type FederationMessageType =
| 'handshake-init'
| 'handshake-accept'
| 'handshake-reject'
- | 'session-terminate';
+ | 'session-terminate'
+ // ADR-101 Component C: cross-node claims operations
+ | 'claim-event' // gossip a ClaimDomainEvent across the federation
+ | 'agent-handoff'; // request to transfer ownership of a claim to a remote agent
export type PIIScanAction = 'pass' | 'redact' | 'hash' | 'block';
@@ -116,4 +119,7 @@ export const CONSENSUS_REQUIRED_TYPES: ReadonlySet<FederationMessageType> = new
'trust-change',
'topology-change',
'agent-spawn',
+ // ADR-101 Component C: handoffs cross trust boundaries β€” optionally
+ // require quorum from validators in high-trust deployments.
+ 'agent-handoff',
]);
diff --git a/v3/docs/adr/ADR-101-federated-claims.md b/v3/docs/adr/ADR-101-federated-claims.md
new file mode 100644
index 0000000000..1a3677418e
--- /dev/null
+++ b/v3/docs/adr/ADR-101-federated-claims.md
@@ -0,0 +1,347 @@
+# ADR-101: Federated Claims β€” Cross-Node Work Coordination via the Federation Plane
+
+**Status**: Proposed
+**Date**: 2026-05-05
+**Version**: target v3.8.0 (post v3.7.x stabilization)
+**Supersedes**: nothing
+**Related**: ADR-086 (Agent Federation), ADR-097 (Federation budget circuit breaker), commit `6f495369` (G2 Ed25519 signing in federation), `v3/@claude-flow/claims/` (existing local-only claims module), `v3/@claude-flow/plugin-agent-federation/` (existing federation runtime)
+
+## Context
+
+The claims module (`v3/@claude-flow/claims/`) is a Domain-Driven-Design implementation of a work-coordination protocol β€” agents and humans claim issues, hand them off, mark them stealable, and contest steals through a Cilk-style work-stealing scheduler. Today it operates **strictly in-process**: every claim, every handoff, every steal happens against `InMemoryClaimEventStore` with monotonic per-aggregate integer versions, and every consumer of the claim service is assumed to be on the same node.
+
+Federation (`v3/@claude-flow/plugin-agent-federation/`) is the cross-node trust plane: Ed25519-signed envelopes, peer registry, trust scoring, and a `RoutingService` for sending typed messages between Ruflo installations. ADR-097 added budget circuit breakers; ADR-086 established the core Ed25519 protocol.
+
+These two modules have been built independently and have **never been wired together**. As a consequence:
+
+- A user running Ruflo on three nodes β€” say, a developer laptop, a CI runner, and a long-running cloud worker β€” cannot have an agent on the laptop hand a claim off to an idle agent on the cloud worker. The work happens locally or not at all.
+- Plugin authors who want to express "the most-loaded node should hand its overflow to the least-loaded node in the trust circle" have no path to do so. The load balancer (`load-balancer.ts:345`) computes globally optimal assignments inside a single process; the result cannot leave that process.
+- The work-stealing scheduler β€” designed exactly for the case where one worker has nothing to do and another has a backlog β€” only works when both workers share memory. The cross-machine case, where stealing matters most, is the case we don't support.
+
+A read-only architectural review (recorded in this conversation) confirmed the integration is **YELLOW** rather than RED: the DI shape of claims is correct, the federation envelope already supports signing, and three specific changes turn the local-only system into a federated one.
+
+This ADR is the design document for those three changes plus the contracts, rollout, test strategy, and migration plan that go around them.
+
+### Existing surface to build on
+
+| Component | Path | Today |
+|---|---|---|
+| Claim service | `v3/@claude-flow/claims/src/application/claim-service.ts:147–240` | Pure DI through `IClaimRepository`, `IClaimantRepository`, `IClaimEventStore` |
+| Work-stealing service | `v3/@claude-flow/claims/src/application/work-stealing-service.ts:172–305` | Repo-driven; `contestInfo` window already exists for race resolution |
+| Load balancer | `v3/@claude-flow/claims/src/application/load-balancer.ts:345–793` | Pure functions of claim-count / progress / priority β€” federates trivially |
+| Event store | `v3/@claude-flow/claims/src/infrastructure/event-store.ts:50–286` | Local in-memory, integer per-aggregate versions |
+| Domain types | `v3/@claude-flow/claims/src/domain/types.ts:91,513` | `Claimant.id` opaque `string`, no locality assumption |
+| Federation envelope | `v3/@claude-flow/plugin-agent-federation/src/protocol/federation-envelope.ts:91–101` | `toSignablePayload()`, `hmacSignature`, Ed25519 verify |
+| Federation routing | `v3/@claude-flow/plugin-agent-federation/src/transport/routing-service.ts:36,61` | `send()`, `scanPii()` already wired; supports `task-assignment` envelope type |
+| Federation message catalog | `federation-envelope.ts:1–16` | Enumerates `task-assignment`, `consensus-vote`, `peer-status`; no `claim-*` member yet |
+
+## Decision
+
+Wire claims into the federation plane via three additive components, kept in the same `@claude-flow/claims` package and gated behind a feature flag for the entire v3.8 alpha cycle. Each component is independently shippable; the dependencies form a strict topological order.
+
+### Component A β€” Hybrid Logical Clock (HLC) timestamps
+
+**Problem.** `WorkStealingService` compares `new Date()` against `claim.claimedAt` and `contestInfo.windowEndsAt` (`work-stealing-service.ts:540–545`, `:357–360`). Across nodes these timestamps come from clocks that disagree. Even 200 ms of skew β€” typical on a residential connection β€” turns "this claim is past its grace period" into a non-deterministic answer that depends on which node is asking.
+
+**Decision.** Replace raw `Date` comparisons inside the work-stealing and handoff timing logic with a hybrid logical clock (HLC, Kulkarni et al. 2014). HLC produces 64-bit timestamps that:
+
+- monotonically advance on every event, even when the wall clock goes backward
+- track causality across nodes in the same way Lamport clocks do, but
+- stay within a small bounded skew of physical time (so they remain human-readable for debugging)
+
+```ts
+// v3/@claude-flow/claims/src/infrastructure/hlc.ts
+export interface HlcTimestamp {
+ readonly physicalMs: number; // wall clock at issuance
+ readonly logical: number; // tie-breaker, monotonic per (node, physicalMs)
+ readonly nodeId: string; // who issued it
+}
+
+export class HybridLogicalClock {
+ private last: HlcTimestamp;
+
+ /** Generate a new HLC timestamp for a local event. */
+ now(): HlcTimestamp { … }
+
+ /** Update the clock from a received timestamp. Returns the new local time. */
+ update(received: HlcTimestamp): HlcTimestamp { … }
+
+ /** Compare two HLC timestamps. Returns -1, 0, +1 like Date comparison. */
+ static compare(a: HlcTimestamp, b: HlcTimestamp): -1 | 0 | 1 { … }
+}
+```
+
+The HLC is held by a singleton scoped to the federation node. When any claim event is created or received, the clock is fed the event's HLC and produces a new local HLC. Comparisons inside `WorkStealingService` change from `Date.now() > windowEndsAt` to `HLC.compare(now, windowEndsAt) > 0`.
+
+To preserve backwards compatibility with existing in-memory deployments (single-node, no federation), the HLC degenerates gracefully: when no remote events are ever received, `physicalMs` tracks the wall clock exactly and `logical` stays at 0 β€” i.e., HLC values are pairwise-comparable to plain Unix timestamps. The local-only test suite continues to pass without changes.
+
+**Skew tolerance.** The HLC tolerates a maximum skew configured per federation (default 30 s). Events arriving with `physicalMs > localPhysicalMs + maxSkewMs` are clamped and logged β€” they're treated as "from the near future" but the clock does not jump forward to match, preventing a misbehaving peer from poisoning the global timeline.
+
+### Component B β€” Federated repository + event-store adapters
+
+**Problem.** Even with HLC timestamps, the `InMemoryClaimEventStore` (`event-store.ts:50–286`) uses **integer versions** per aggregate. Two nodes simultaneously appending events to the same claim aggregate will both produce `version 5`, and the in-memory store will accept whichever wins the local race β€” silently corrupting causal history.
+
+**Decision.** Introduce two new infrastructure adapters that satisfy the existing repository / event-store interfaces and route writes through federation:
+
+```
+v3/@claude-flow/claims/src/infrastructure/
+ hlc.ts # Component A
+ federated-claim-repository.ts # implements IClaimRepository
+ federated-event-store.ts # implements IClaimEventStore
+ vector-clock.ts # supporting type
+ federation-bridge.ts # internal: bridges claim events ↔ federation envelopes
+```
+
+#### Federated event store
+
+Replace integer versions with **vector clocks**. Each event carries a vector `{[nodeId]: integer}` representing the causal history seen at the issuing node. On read, events are sorted by vector-clock partial order; on write, the store rejects events whose vector clock contradicts an event already accepted (concurrent writes are detected and surfaced as `CONCURRENT_WRITE` errors that the application layer can resolve via the existing contest mechanism).
+
+```ts
+export interface VectorClock {
+ readonly clocks: Readonly<Record<string, number>>;
+}
+
+export interface FederatedClaimEvent extends ClaimDomainEvent {
+ readonly hlc: HlcTimestamp;
+ readonly vclock: VectorClock;
+ readonly originNodeId: string;
+ readonly envelopeSignature?: string; // present iff this event arrived via federation
+}
+```
+
+Existing event consumers see the additional fields as opaque metadata; they do not need to change.
+
+#### Federated claim repository
+
+`FederatedClaimRepository` wraps the existing in-memory or SQLite repository and:
+
+1. **Reads** are local-first. The local replica is authoritative for queries; cross-node lookups are explicit (`findByClaimantId(id, { includeRemote: true })`).
+2. **Writes** publish a `claim-event` federation envelope to all peers in the trust circle whose `trustLevel >= CLAIMS_MIN_TRUST` (configurable, default `WORKING`).
+3. **Conflict resolution** uses last-writer-wins by HLC for non-causal fields (e.g., `notes`) and concurrent-write rejection for causal events (e.g., two `release` events with overlapping vector clocks β†’ both fail; the contest mechanism arbitrates).
+4. **Privacy.** Before publishing any event, the bridge runs the existing `RoutingServiceDeps.scanPii` (`routing-service.ts:36`). PII detected in `Claimant.metadata` or `Claim.notes` aborts the publish and the local write is rolled back with a `PII_LEAK_PREVENTED` error returned to the caller β€” fail-loud, not fail-silent.
+
+### Component C β€” Attested handoff envelopes
+
+**Problem.** A handoff (`claim-service.ts:293–415`) is the moment one agent transfers ownership of work to another. Across a trust boundary, this is exactly when an attestation is most valuable: did the originator actually authorize this handoff, or did a malicious peer fabricate the request?
+
+**Decision.** Add a new federation message type and route handoff events through the existing signing infrastructure:
+
+```ts
+// v3/@claude-flow/plugin-agent-federation/src/protocol/federation-envelope.ts
+export type FederationMessageType =
+ | 'task-assignment'
+ | 'task-result'
+ | 'consensus-vote'
+ | 'peer-status'
+ | 'agent-handoff'; // ← new (Component C)
+```
+
+The new type is gated by `CONSENSUS_REQUIRED_TYPES` so handoffs to high-trust peers can optionally require consensus from a quorum of validators (matching the existing pattern for `task-assignment`).
+
+#### Wire shape
+
+```ts
+interface AgentHandoffPayload {
+ readonly claimId: ClaimId;
+ readonly from: ClaimantId; // current owner
+ readonly to: ClaimantId; // proposed owner
+ readonly reason: HandoffReason; // re-uses existing domain enum
+ readonly hlc: HlcTimestamp;
+ readonly vclock: VectorClock;
+ readonly originNodeId: string;
+}
+```
+
+The envelope's `toSignablePayload()` already canonicalizes JSON for deterministic signing; the receiving peer:
+
+1. Verifies the Ed25519 signature against the sender's public key from the peer registry.
+2. Verifies the HLC is within the configured skew window.
+3. Verifies the local claim's current owner matches `from` (rejects forged "I'm handing your work off" attacks).
+4. If verification passes, calls the local `ClaimService.requestHandoff()` with `{ federated: true }` so audit logs preserve the cross-node provenance.
+
+#### Why a dedicated message type
+
+Could we ride on the existing `task-assignment` type? Yes, and the YELLOW review suggested it as a quick path. The reason for a dedicated type:
+
+- `task-assignment` carries arbitrary payloads; reusing it for handoffs means `payload.kind = 'agent-handoff'` discrimination scattered across the receiving handler.
+- A dedicated type lets us add `agent-handoff` to `CONSENSUS_REQUIRED_TYPES` without affecting other task assignments.
+- Audit logs become greppable: a security review can ask "who handed off claim X" and the federation event log surfaces every cross-node transfer.
+
+The cost is one new enum member and ~20 lines of dispatch in the federation receive loop β€” small relative to the readability win.
+
+## Architecture diagram
+
+```
+β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ Node A (laptop) ──────────────────────┐
+β”‚ β”‚
+β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
+β”‚ β”‚ ClaimSvc │────▢│ FederatedClaim │───▢│ FederationRout │──┐
+β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ Repository β”‚ β”‚ Service β”‚ β”‚
+β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
+β”‚ β–Ό β”‚ β”‚ β”‚
+β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚
+β”‚ β”‚ HLC β”‚ β”‚ Vector β”‚ β”‚ β”‚
+β”‚ β”‚ Clock β”‚ β”‚ Clock β”‚ β”‚ β”‚
+β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚
+β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
+ β”‚ Ed25519-signed
+ β”‚ envelope
+ (claim-event,
+ agent-handoff)
+ β”‚
+β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+β”‚ Node B (cloud worker) β–Ό β”‚
+β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
+β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ FederationRout β”‚ β”‚
+β”‚ β”‚ ClaimSvc │◀────│ FederatedClaim │◀───│ Service β”‚ β”‚
+β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ Repository β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
+β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
+β”‚ β–Ό β–² β”‚
+β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
+β”‚ β”‚ HLC β”‚ β”‚ Vector β”‚ β”‚
+β”‚ β”‚ Clock β”‚ β”‚ Clock β”‚ β”‚
+β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
+β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
+```
+
+## Consequences
+
+### Positive
+
+- **Cross-node work-stealing becomes possible.** A node with no work to do can pull a stealable claim from a peer; the contest window already handles the race.
+- **Cross-node handoff with attestation.** The receiving node has cryptographic proof the handoff was authorized β€” solving a real trust gap that has blocked enterprise federation deployments.
+- **Distributed load balancing.** `LoadBalancer` operates on `IAgentRegistry` + `ILoadBalancerClaimRepository`. Backing the registry with federation peer data and the repository with the federated adapter turns the existing load balancer into a federation-wide one with zero changes to the balancer itself.
+- **No breaking changes to local users.** The HLC degenerates to wall-clock-equivalent in single-node mode; the federated adapters are opt-in via DI.
+
+### Negative
+
+- **Operational complexity.** Vector clocks require all participating nodes to share a node-id space. Adding a new node to a long-running federation requires a one-time coordination ceremony (the new node starts at vclock `{}` and reconciles in O(events) time on first sync). This is not free; the rollout plan below includes specific tooling.
+- **Latency on writes.** Every claim mutation now incurs network round-trips to peers. Mitigation: writes are async-by-default (return locally, replicate in the background) with a configurable strong-consistency mode for security-critical operations like handoffs.
+- **Quorum failures.** If the trust circle drops below a configurable minimum size, federated writes fail-closed. Single-node operation continues to work because the federated adapters are opt-in; the failure mode is "federation off, claims still work locally."
+
+### Neutral
+
+- **Bigger event payloads.** Vector clocks add ~50–200 bytes per event. At the scale claims operates at (typically <100 events/sec/node), this is invisible.
+- **Privacy surface widens.** Every claim event now traverses the network. The PII scan on publish is the mitigation; the audit trail in `RoutingService` is the after-the-fact verification.
+
+## Alternatives considered
+
+### A1. CRDT-based event log instead of vector clocks
+
+A pure CRDT (e.g., G-set of events with deterministic ordering) would give us strong eventual consistency without explicit conflict-rejection. Rejected because:
+
+- Claims have **causal** semantics (you cannot release a claim that was never created); CRDTs don't naturally capture "must-happen-after" constraints without auxiliary structures.
+- CRDT serialization adds ~20% to event size at our scale, vs ~5% for vector clocks.
+- The existing contest mechanism already handles the "two writers, who wins" case; reusing it costs nothing.
+
+### A2. Single-leader replication (Raft within the federation)
+
+Pick one node as the claims leader; all writes go through it. Rejected because:
+
+- Federation is fundamentally peer-to-peer with variable trust; electing a single leader contradicts the trust model (whoever the leader is, they see all claims globally).
+- Leader failover requires consensus, which contradicts ADR-097's circuit-breaker model.
+- The work-stealing scheduler is **specifically designed** to be distributed; a leader would serialize the very thing we're trying to parallelize.
+
+### A3. Re-use `task-assignment` for handoffs (YELLOW review's quick option)
+
+Discussed in Component C above. Rejected for readability + auditability reasons (one new enum member is cheap; scattered discriminator dispatch is not).
+
+### A4. Federate only handoffs, leave the rest local
+
+A minimal-touch alternative: just sign handoff envelopes, skip the federated repo entirely. Rejected because:
+
+- Without federated state, the receiving node can't verify the handoff against current claim ownership β€” the attestation has nothing to attest *against*.
+- Cross-node steal would still be impossible.
+- Half the value of the integration would be missing for half the work.
+
+### A5. Build federation-aware claims as a sibling package
+
+A separate `@claude-flow/federated-claims` that depends on both `@claude-flow/claims` and `@claude-flow/plugin-agent-federation`. Rejected because:
+
+- The existing `IClaimRepository` and `IClaimEventStore` interfaces are already the right extension points. A sibling package would either duplicate them or re-export them, both of which add noise.
+- npm dependency graphs already track this fan-in; a sibling package buys nothing the existing package can't deliver via opt-in DI.
+
+## Implementation plan
+
+Three phases, each independently mergeable. Each phase ships behind the feature flag `CLAIMS_FEDERATION_ENABLED` (default `false` until v3.8.0).
+
+### Phase 1 β€” HLC clock + skew-tolerant comparisons (1–2 days)
+
+| Task | File | Notes |
+|---|---|---|
+| Implement HLC | `v3/@claude-flow/claims/src/infrastructure/hlc.ts` (new) | Pure module, ~100 lines, exhaustive unit tests |
+| Replace `Date.now()` comparisons in work-stealing | `work-stealing-service.ts:540–545,357–360` | Two callsites, accept HLC via DI on construction |
+| Add HLC to all event types | `domain/events.ts` | Optional field; older events read with `hlc: zeroHlc()` |
+| Wire HLC into `ClaimService` | `application/claim-service.ts` | Constructor injection of `IHlc` interface |
+| Migration test | `__tests__/hlc-migration.test.ts` | Old-style events still consumable with new code |
+
+Phase 1 closes on a green local test run. No federation involvement yet.
+
+### Phase 2 β€” Federated repository + event-store adapters (3–5 days)
+
+| Task | File | Notes |
+|---|---|---|
+| Vector clock module | `infrastructure/vector-clock.ts` (new) | ~80 lines, partial-order tests |
+| Federation bridge | `infrastructure/federation-bridge.ts` (new) | Translates `ClaimDomainEvent` ↔ federation envelopes |
+| `FederatedClaimRepository` | `infrastructure/federated-claim-repository.ts` (new) | Wraps existing repo, publishes on write |
+| `FederatedClaimEventStore` | `infrastructure/federated-event-store.ts` (new) | Vector-clock-versioned event store |
+| Concurrent-write rejection tests | `__tests__/federated-event-store.test.ts` | Two simulated nodes writing to same aggregate |
+| PII pre-publish scan | within bridge | Re-uses `RoutingServiceDeps.scanPii` |
+
+Phase 2 closes on a green local test run + a multi-node simulation test that proves a `claim` on node A is visible on node B within bounded time.
+
+### Phase 3 β€” Attested handoff envelopes (1–2 days)
+
+| Task | File | Notes |
+|---|---|---|
+| Add `agent-handoff` to `FederationMessageType` | `plugin-agent-federation/src/protocol/federation-envelope.ts:1–16` | Enum addition, no breakage |
+| Add to `CONSENSUS_REQUIRED_TYPES` (optional) | same file | Gated by config |
+| Receive-side handler | `plugin-agent-federation/src/transport/routing-service.ts` | Verify β†’ call `ClaimService.requestHandoff({ federated: true })` |
+| Send-side hook in `ClaimService.requestHandoff` | `application/claim-service.ts:293–415` | If target is remote claimant, publish envelope; await ack with timeout |
+| End-to-end attestation test | `__tests__/federated-handoff.test.ts` | Two nodes; verify rejection of forged handoff |
+
+Phase 3 closes on a green CI run including the new e2e test on Linux + macOS + Windows runners.
+
+### Phase 4 β€” Validate, optimize, publish, merge
+
+- `npm run lint && npm run typecheck && npm test` for both `@claude-flow/claims` and `@claude-flow/plugin-agent-federation`
+- Run the federation soak test for 30 minutes (3 nodes, 1000 simulated claims, 200 handoffs/min) and assert no orphaned claims, no signature failures, no PII leaks
+- Bump `@claude-flow/claims` from `3.0.0-alpha.X` β†’ `3.1.0-alpha.0` (new minor; opt-in feature flag preserves SemVer)
+- Bump `@claude-flow/plugin-agent-federation` from `1.0.0-alpha.X` β†’ `1.1.0-alpha.0`
+- Update `verification.md` with a Post-witness validation entry for ADR-101
+- Open PR; require green CI on all three OSes; merge after one approving review
+
+## Test strategy
+
+| Layer | Tests |
+|---|---|
+| Unit | HLC arithmetic, vector-clock partial order, envelope sign/verify |
+| Integration | Two simulated nodes via in-memory transport β€” claim/handoff/release roundtrips |
+| Property | Generators for arbitrary event interleavings; assert convergence after gossip |
+| E2E | Three-node Docker compose; real Ed25519 keys; soak test for 30 min |
+| Adversarial | Forged handoff attempts; clock-skew attacks; PII smuggling tests |
+
+The adversarial layer is non-negotiable β€” every Component-C handoff path must have a corresponding "what if a peer lies" test.
+
+## Open questions
+
+1. **Should claims federation share the trust registry with `federation_send`, or have its own?** Sharing is simpler; separating gives operators the option to allow general federation without claims federation (lower-trust posture). Default plan: share, gate via `CLAIMS_MIN_TRUST` config.
+2. **What's the right behavior on partition?** When the trust circle is split, should each partition continue independently and reconcile on heal, or fail-closed? Default plan: continue independently for non-causal events, fail-closed for handoffs (where attestation requires real-time peer verification).
+3. **Garbage collection of vector clocks.** As nodes join and leave a federation, vector clocks accumulate dead entries. Default plan: prune via `peer-status: EVICTED` events from ADR-097's circuit breaker.
+
+These are deferred to implementation; this ADR commits to the contracts, not the GC strategy.
+
+## References
+
+- Kulkarni et al., "Logical Physical Clocks and Consistent Snapshots in Globally Distributed Databases" (2014) β€” the HLC paper
+- Lamport, "Time, Clocks, and the Ordering of Events in a Distributed System" (1978) β€” the foundational result
+- Vogels, "Eventually Consistent" (2008) β€” the CRDT/eventual-consistency framing
+- ADR-086 (in-repo) β€” Federation foundations, Ed25519 trust
+- ADR-097 (in-repo) β€” Federation budget circuit breaker; this ADR's trust-scoring dependencies
+- `verification.md` Post-witness validations β€” where this ADR's runtime evidence will land
+
+## Approval
+
+**Proposed by**: Reuven (this ADR)
+**Reviewers**: federation-coordinator agent (architectural fit assessment captured in PR description)
+**Sign-off required from**: maintainers of `@claude-flow/claims` and `@claude-flow/plugin-agent-federation`