@claude-flow/plugin-agent-federation 1.0.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/README.md +45 -0
  2. package/dist/application/federation-breaker-service.d.ts +182 -0
  3. package/dist/application/federation-breaker-service.d.ts.map +1 -0
  4. package/dist/application/federation-breaker-service.js +251 -0
  5. package/dist/application/federation-breaker-service.js.map +1 -0
  6. package/dist/application/federation-coordinator.d.ts +166 -0
  7. package/dist/application/federation-coordinator.d.ts.map +1 -0
  8. package/dist/application/federation-coordinator.js +412 -0
  9. package/dist/application/federation-coordinator.js.map +1 -0
  10. package/dist/application/inbound-dispatcher.d.ts +59 -0
  11. package/dist/application/inbound-dispatcher.d.ts.map +1 -0
  12. package/dist/application/inbound-dispatcher.js +96 -0
  13. package/dist/application/inbound-dispatcher.js.map +1 -0
  14. package/dist/application/policy-engine.d.ts +41 -0
  15. package/dist/application/policy-engine.d.ts.map +1 -0
  16. package/dist/application/policy-engine.js +184 -0
  17. package/dist/application/policy-engine.js.map +1 -0
  18. package/dist/application/spend-reporter.d.ts +150 -0
  19. package/dist/application/spend-reporter.d.ts.map +1 -0
  20. package/dist/application/spend-reporter.js +128 -0
  21. package/dist/application/spend-reporter.js.map +1 -0
  22. package/dist/application/trust-evaluator.d.ts +42 -0
  23. package/dist/application/trust-evaluator.d.ts.map +1 -0
  24. package/dist/application/trust-evaluator.js +132 -0
  25. package/dist/application/trust-evaluator.js.map +1 -0
  26. package/dist/bin.d.ts +13 -0
  27. package/dist/bin.d.ts.map +1 -0
  28. package/dist/bin.js +189 -0
  29. package/dist/bin.js.map +1 -0
  30. package/dist/cli-commands.d.ts +7 -0
  31. package/dist/cli-commands.d.ts.map +1 -0
  32. package/dist/cli-commands.js +198 -0
  33. package/dist/cli-commands.js.map +1 -0
  34. package/dist/domain/entities/federation-envelope.d.ts +45 -0
  35. package/dist/domain/entities/federation-envelope.d.ts.map +1 -0
  36. package/dist/domain/entities/federation-envelope.js +71 -0
  37. package/dist/domain/entities/federation-envelope.js.map +1 -0
  38. package/dist/domain/entities/federation-node.d.ts +104 -0
  39. package/dist/domain/entities/federation-node.d.ts.map +1 -0
  40. package/dist/domain/entities/federation-node.js +152 -0
  41. package/dist/domain/entities/federation-node.js.map +1 -0
  42. package/dist/domain/entities/federation-session.d.ts +55 -0
  43. package/dist/domain/entities/federation-session.d.ts.map +1 -0
  44. package/dist/domain/entities/federation-session.js +105 -0
  45. package/dist/domain/entities/federation-session.js.map +1 -0
  46. package/dist/domain/entities/trust-level.d.ts +17 -0
  47. package/dist/domain/entities/trust-level.d.ts.map +1 -0
  48. package/dist/domain/entities/trust-level.js +35 -0
  49. package/dist/domain/entities/trust-level.js.map +1 -0
  50. package/dist/domain/services/audit-service.d.ts +69 -0
  51. package/dist/domain/services/audit-service.d.ts.map +1 -0
  52. package/dist/domain/services/audit-service.js +149 -0
  53. package/dist/domain/services/audit-service.js.map +1 -0
  54. package/dist/domain/services/discovery-service.d.ts +51 -0
  55. package/dist/domain/services/discovery-service.d.ts.map +1 -0
  56. package/dist/domain/services/discovery-service.js +140 -0
  57. package/dist/domain/services/discovery-service.js.map +1 -0
  58. package/dist/domain/services/handshake-service.d.ts +48 -0
  59. package/dist/domain/services/handshake-service.d.ts.map +1 -0
  60. package/dist/domain/services/handshake-service.js +94 -0
  61. package/dist/domain/services/handshake-service.js.map +1 -0
  62. package/dist/domain/services/pii-pipeline-service.d.ts +65 -0
  63. package/dist/domain/services/pii-pipeline-service.d.ts.map +1 -0
  64. package/dist/domain/services/pii-pipeline-service.js +208 -0
  65. package/dist/domain/services/pii-pipeline-service.js.map +1 -0
  66. package/dist/domain/services/routing-service.d.ts +51 -0
  67. package/dist/domain/services/routing-service.d.ts.map +1 -0
  68. package/dist/domain/services/routing-service.js +147 -0
  69. package/dist/domain/services/routing-service.js.map +1 -0
  70. package/dist/domain/value-objects/federation-budget.d.ts +89 -0
  71. package/dist/domain/value-objects/federation-budget.d.ts.map +1 -0
  72. package/dist/domain/value-objects/federation-budget.js +165 -0
  73. package/dist/domain/value-objects/federation-budget.js.map +1 -0
  74. package/dist/domain/value-objects/federation-node-state.d.ts +92 -0
  75. package/dist/domain/value-objects/federation-node-state.d.ts.map +1 -0
  76. package/dist/domain/value-objects/federation-node-state.js +100 -0
  77. package/dist/domain/value-objects/federation-node-state.js.map +1 -0
  78. package/dist/index.d.ts +17 -0
  79. package/dist/index.d.ts.map +1 -0
  80. package/dist/index.js +17 -0
  81. package/dist/index.js.map +1 -0
  82. package/dist/mcp-tools.d.ts +8 -0
  83. package/dist/mcp-tools.d.ts.map +1 -0
  84. package/dist/mcp-tools.js +343 -0
  85. package/dist/mcp-tools.js.map +1 -0
  86. package/dist/plugin.d.ts +18 -0
  87. package/dist/plugin.d.ts.map +1 -0
  88. package/dist/plugin.js +376 -0
  89. package/dist/plugin.js.map +1 -0
  90. package/package.json +44 -0
@@ -0,0 +1,184 @@
1
+ import { TrustLevel, isOperationAllowed } from '../domain/entities/trust-level.js';
2
+ const DEFAULT_SECURITY_POLICY = {
3
+ maxMessageSizeBytes: 1_048_576,
4
+ maxMessagesPerMinute: 120,
5
+ allowedMessageTypes: [
6
+ 'task-assignment', 'memory-query', 'memory-response',
7
+ 'context-share', 'status-broadcast', 'heartbeat',
8
+ 'trust-change', 'topology-change', 'agent-spawn',
9
+ ],
10
+ requirePiiScan: true,
11
+ requireAiDefenceScan: true,
12
+ minTrustLevelForWrite: TrustLevel.ATTESTED,
13
+ minTrustLevelForMemory: TrustLevel.TRUSTED,
14
+ minTrustLevelForSpawn: TrustLevel.PRIVILEGED,
15
+ };
16
+ const CLAIMS_FOR_MESSAGE_TYPE = {
17
+ 'task-assignment': ['federation:write'],
18
+ 'memory-query': ['federation:read', 'federation:memory'],
19
+ 'memory-response': ['federation:read', 'federation:memory'],
20
+ 'context-share': ['federation:write'],
21
+ 'status-broadcast': ['federation:read'],
22
+ 'trust-change': ['federation:admin'],
23
+ 'topology-change': ['federation:admin'],
24
+ 'agent-spawn': ['federation:spawn'],
25
+ 'heartbeat': ['federation:connect'],
26
+ 'challenge': ['federation:connect'],
27
+ 'challenge-response': ['federation:connect'],
28
+ 'handshake-init': ['federation:connect'],
29
+ 'handshake-accept': ['federation:connect'],
30
+ 'handshake-reject': ['federation:connect'],
31
+ 'session-terminate': ['federation:connect'],
32
+ // ADR-101 Component C — federated claims operations.
33
+ // claim-event: broadcasts a ClaimDomainEvent (state mutation across peers),
34
+ // same authorization shape as task-assignment.
35
+ 'claim-event': ['federation:write'],
36
+ // agent-handoff: transfers claim ownership to a remote agent. Requires
37
+ // both the write capability (state mutation) AND spawn-lifecycle authority
38
+ // (handoff is a sibling of agent-spawn — both reshape who owns work).
39
+ // Matches the consensus-gated security posture in ADR-101.
40
+ 'agent-handoff': ['federation:write', 'federation:spawn'],
41
+ };
42
+ export class PolicyEngine {
43
+ deps;
44
+ securityPolicy;
45
+ piiPolicy;
46
+ rateLimitCounters;
47
+ constructor(deps, securityPolicy, piiPolicy) {
48
+ this.deps = deps;
49
+ this.securityPolicy = { ...DEFAULT_SECURITY_POLICY, ...securityPolicy };
50
+ this.piiPolicy = piiPolicy ?? {
51
+ defaultAction: 'redact',
52
+ overrides: {},
53
+ hashAlgorithm: 'sha256',
54
+ hashSalt: '',
55
+ redactionPlaceholder: '[REDACTED:{type}]',
56
+ };
57
+ this.rateLimitCounters = new Map();
58
+ }
59
+ evaluateMessage(messageType, trustLevel, messageSizeBytes, sourceNodeId) {
60
+ if (!this.securityPolicy.allowedMessageTypes.includes(messageType)) {
61
+ return {
62
+ allowed: false,
63
+ reason: `Message type '${messageType}' is not allowed by security policy`,
64
+ requiredClaims: [],
65
+ trustLevelSufficient: false,
66
+ };
67
+ }
68
+ if (messageSizeBytes > this.securityPolicy.maxMessageSizeBytes) {
69
+ return {
70
+ allowed: false,
71
+ reason: `Message size ${messageSizeBytes} exceeds maximum ${this.securityPolicy.maxMessageSizeBytes}`,
72
+ requiredClaims: [],
73
+ trustLevelSufficient: true,
74
+ };
75
+ }
76
+ if (!this.checkRateLimit(sourceNodeId)) {
77
+ return {
78
+ allowed: false,
79
+ reason: `Rate limit exceeded for node ${sourceNodeId}`,
80
+ requiredClaims: [],
81
+ trustLevelSufficient: true,
82
+ };
83
+ }
84
+ const requiredClaims = CLAIMS_FOR_MESSAGE_TYPE[messageType] ?? [];
85
+ const missingClaims = requiredClaims.filter(c => !this.deps.checkClaim(c));
86
+ if (missingClaims.length > 0) {
87
+ return {
88
+ allowed: false,
89
+ reason: `Missing required claims: ${missingClaims.join(', ')}`,
90
+ requiredClaims,
91
+ trustLevelSufficient: true,
92
+ };
93
+ }
94
+ const operationForType = this.getOperationForMessageType(messageType);
95
+ if (!isOperationAllowed(trustLevel, operationForType)) {
96
+ return {
97
+ allowed: false,
98
+ reason: `Trust level ${trustLevel} insufficient for operation '${operationForType}'`,
99
+ requiredClaims,
100
+ trustLevelSufficient: false,
101
+ };
102
+ }
103
+ return {
104
+ allowed: true,
105
+ reason: 'Policy check passed',
106
+ requiredClaims,
107
+ trustLevelSufficient: true,
108
+ };
109
+ }
110
+ evaluatePiiDetection(detection, trustLevel) {
111
+ const override = this.piiPolicy.overrides[detection.type];
112
+ if (override?.trustLevelOverride?.[trustLevel]) {
113
+ return override.trustLevelOverride[trustLevel];
114
+ }
115
+ if (override?.action) {
116
+ return override.action;
117
+ }
118
+ return this.piiPolicy.defaultAction;
119
+ }
120
+ evaluateTrustChange(currentLevel, proposedLevel) {
121
+ if (proposedLevel > currentLevel && proposedLevel === TrustLevel.PRIVILEGED) {
122
+ return {
123
+ allowed: true,
124
+ requiresHumanApproval: true,
125
+ reason: 'Elevation to PRIVILEGED requires institutional attestation and human approval',
126
+ };
127
+ }
128
+ if (proposedLevel > currentLevel) {
129
+ return {
130
+ allowed: true,
131
+ requiresHumanApproval: false,
132
+ reason: `Trust upgrade from ${currentLevel} to ${proposedLevel} allowed`,
133
+ };
134
+ }
135
+ if (proposedLevel < currentLevel) {
136
+ return {
137
+ allowed: true,
138
+ requiresHumanApproval: false,
139
+ reason: `Trust downgrade from ${currentLevel} to ${proposedLevel} allowed`,
140
+ };
141
+ }
142
+ return {
143
+ allowed: false,
144
+ requiresHumanApproval: false,
145
+ reason: 'No trust level change',
146
+ };
147
+ }
148
+ checkRateLimit(nodeId) {
149
+ const now = Date.now();
150
+ const counter = this.rateLimitCounters.get(nodeId);
151
+ if (!counter || now - counter.windowStart > 60_000) {
152
+ this.rateLimitCounters.set(nodeId, { count: 1, windowStart: now });
153
+ return true;
154
+ }
155
+ counter.count++;
156
+ return counter.count <= this.securityPolicy.maxMessagesPerMinute;
157
+ }
158
+ getOperationForMessageType(messageType) {
159
+ switch (messageType) {
160
+ case 'memory-query':
161
+ case 'memory-response':
162
+ return 'query-redacted';
163
+ case 'context-share':
164
+ return 'share-context';
165
+ case 'task-assignment':
166
+ return 'send';
167
+ case 'agent-spawn':
168
+ return 'remote-spawn';
169
+ case 'status-broadcast':
170
+ return 'status';
171
+ case 'heartbeat':
172
+ case 'challenge':
173
+ case 'challenge-response':
174
+ case 'handshake-init':
175
+ case 'handshake-accept':
176
+ case 'handshake-reject':
177
+ case 'session-terminate':
178
+ return 'ping';
179
+ default:
180
+ return 'send';
181
+ }
182
+ }
183
+ }
184
+ //# sourceMappingURL=policy-engine.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"policy-engine.js","sourceRoot":"","sources":["../../src/application/policy-engine.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,kBAAkB,EAAE,MAAM,mCAAmC,CAAC;AAgCnF,MAAM,uBAAuB,GAAmB;IAC9C,mBAAmB,EAAE,SAAS;IAC9B,oBAAoB,EAAE,GAAG;IACzB,mBAAmB,EAAE;QACnB,iBAAiB,EAAE,cAAc,EAAE,iBAAiB;QACpD,eAAe,EAAE,kBAAkB,EAAE,WAAW;QAChD,cAAc,EAAE,iBAAiB,EAAE,aAAa;KACjD;IACD,cAAc,EAAE,IA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B,KAAK,cAAc,CAAC;YACpB,KAAK,iBAAiB;gBACpB,OAAO,gBAAgB,CAAC;YAC1B,KAAK,eAAe;gBAClB,OAAO,eAAe,CAAC;YACzB,KAAK,iBAAiB;gBACpB,OAAO,MAAM,CAAC;YAChB,KAAK,aAAa;gBAChB,OAAO,cAAc,CAAC;YACxB,KAAK,kBAAkB;gBACrB,OAAO,QAAQ,CAAC;YAClB,KAAK,WAAW,CAAC;YACjB,KAAK,WAAW,CAAC;YACjB,KAAK,oBAAoB,CAAC;YAC1B,KAAK,gBAAgB,CAAC;YACtB,KAAK,kBAAkB,CAAC;YACxB,KAAK,kBAAkB,CAAC;YACxB,KAAK,mBAAmB;gBACtB,OAAO,MAAM,CAAC;YAChB;gBACE,OAAO,MAAM,CAAC;QAClB,CAAC;IACH,CAAC;CACF"}
@@ -0,0 +1,150 @@
1
+ /**
2
+ * Federation spend-reporting interface (ADR-097 Phase 3 upstream).
3
+ *
4
+ * The federation layer doesn't own model pricing — it can't know how much
5
+ * a downstream agent's work cost until the integrator tells it. So the
6
+ * coordinator exposes a `reportSpend()` method that callers invoke after
7
+ * their downstream completes, and that method fans out to:
8
+ *
9
+ * 1. The injected SpendReporter (if any) — typically wires to the
10
+ * cost-tracker bus / `federation-spend` memory namespace
11
+ * 2. The injected FederationBreakerService (if any) — its in-memory
12
+ * buffer becomes a transparent cache when the cost-tracker
13
+ * subscriber lands
14
+ *
15
+ * Both deps are constructor-optional. A coordinator with neither still
16
+ * accepts reportSpend() calls (silent no-op) so callers don't need to
17
+ * branch on which integrations are wired.
18
+ *
19
+ * Event shape matches the consumer contract pinned by
20
+ * plugins/ruflo-cost-tracker/scripts/federation.mjs:
21
+ *
22
+ * { peerId, taskId, tokensUsed, usdSpent, ts }
23
+ *
24
+ * Storage layout (consumer convention): namespace `federation-spend`,
25
+ * key `fed-spend-<peerId>-<ts>`. The interface is storage-agnostic; the
26
+ * default in-memory reporter included here is for tests + a reference
27
+ * implementation. Production integrators write a thin adapter that
28
+ * persists to ruflo memory / Redis / Datadog / their accounting system.
29
+ */
30
+ /** A single per-send cost report from the integrator. */
31
+ export interface FederationSpendEvent {
32
+ /** Peer this cost was incurred against. */
33
+ readonly peerId: string;
34
+ /** Optional task correlation key — not all callers will have one. */
35
+ readonly taskId?: string;
36
+ /** Tokens consumed (input + output). Negative values clamped to 0 by sink. */
37
+ readonly tokensUsed: number;
38
+ /** USD spent. Negative values clamped to 0 by sink. */
39
+ readonly usdSpent: number;
40
+ /** ISO 8601 timestamp. Caller-supplied for testability; auto-filled if omitted by reportSpend. */
41
+ readonly ts: string;
42
+ /** Whether the underlying send succeeded (drives breaker failure-ratio). */
43
+ readonly success: boolean;
44
+ }
45
+ /**
46
+ * Strategy interface the coordinator calls when reportSpend() fires.
47
+ * Integrators implement this to push the event to whatever backend they
48
+ * want — cost-tracker bus, Datadog, accounting DB, etc.
49
+ *
50
+ * Implementations must be tolerant: dropping or persisting later is
51
+ * acceptable, but throwing here will surface to the integrator's caller.
52
+ * Buffer and retry inside the implementation.
53
+ */
54
+ export interface SpendReporter {
55
+ reportSpend(event: FederationSpendEvent): Promise<void>;
56
+ }
57
+ /**
58
+ * In-memory reporter for tests + a reference implementation. Production
59
+ * code should wire a real SpendReporter that persists to durable storage.
60
+ *
61
+ * Buffer is unbounded — fine for tests, NOT fine for long-running
62
+ * production. The cost-tracker consumer reads from durable storage, not
63
+ * from this buffer.
64
+ */
65
+ export declare class InMemorySpendReporter implements SpendReporter {
66
+ private readonly buffer;
67
+ reportSpend(event: FederationSpendEvent): Promise<void>;
68
+ /** Snapshot of all reported events (test inspection). */
69
+ getEvents(): readonly FederationSpendEvent[];
70
+ /** Drop everything (test cleanup). */
71
+ clear(): void;
72
+ }
73
+ /**
74
+ * Minimal memory-backend interface (ADR-110). The integrator wires this
75
+ * to whatever store satisfies their durability/consistency needs:
76
+ * ruflo memory, Redis, DynamoDB, file-backed JSON, etc. The federation
77
+ * plugin doesn't import any specific memory client — pluggable by
78
+ * design.
79
+ */
80
+ export interface MemoryStore {
81
+ /** Persist a value under (namespace, key). Optional TTL in seconds. */
82
+ store(args: {
83
+ namespace: string;
84
+ key: string;
85
+ value: string;
86
+ ttl?: number;
87
+ }): Promise<void>;
88
+ }
89
+ /** Configuration for `MemorySpendReporter`. See ADR-110. */
90
+ export interface MemorySpendReporterConfig {
91
+ /** Memory store impl. Required. */
92
+ readonly memoryStore: MemoryStore;
93
+ /** Namespace per the cost-tracker consumer contract. Default: `federation-spend`. */
94
+ readonly namespace?: string;
95
+ /** Optional TTL in seconds. Default: 7 days. Cost-tracker rolling windows are 1h/24h/7d, so anything older is irrelevant. */
96
+ readonly ttlSeconds?: number;
97
+ }
98
+ /** Default namespace per cost-tracker's `plugins/ruflo-cost-tracker/scripts/federation.mjs`. */
99
+ export declare const DEFAULT_FEDERATION_SPEND_NAMESPACE = "federation-spend";
100
+ /** Default TTL: 7 days, matching cost-tracker's longest rolling window. */
101
+ export declare const DEFAULT_FEDERATION_SPEND_TTL_SECONDS: number;
102
+ /**
103
+ * Production reporter (ADR-110) that satisfies the cost-tracker
104
+ * consumer contract: writes to namespace `federation-spend`, key
105
+ * `fed-spend-<peerId>-<ts>`. The consumer
106
+ * (`plugins/ruflo-cost-tracker/scripts/federation.mjs`) `memory list`s
107
+ * the namespace, retrieves each key, and aggregates into rolling
108
+ * windows.
109
+ *
110
+ * Storage-agnostic: the integrator injects a `MemoryStore`
111
+ * implementation. Common wirings:
112
+ *
113
+ * // ruflo memory MCP
114
+ * new MemorySpendReporter({
115
+ * memoryStore: {
116
+ * store: async (a) => mcpClient.call('memory_store', a),
117
+ * },
118
+ * });
119
+ *
120
+ * // ruflo memory CLI shell-out
121
+ * new MemorySpendReporter({
122
+ * memoryStore: {
123
+ * store: async ({namespace, key, value, ttl}) => {
124
+ * await execFile('npx', ['ruflo', 'memory', 'store',
125
+ * '--namespace', namespace, '--key', key, '--value', value]);
126
+ * },
127
+ * },
128
+ * });
129
+ *
130
+ * Errors from the memory backend BUBBLE UP — the reporter does not
131
+ * retry/swallow. Wrap with the integrator's preferred retry strategy
132
+ * if needed.
133
+ *
134
+ * Negative `tokensUsed` / `usdSpent` are persisted as-is. Clamping is
135
+ * the breaker's responsibility (see federation-breaker-service.ts);
136
+ * the audit/spend log is an honest mirror of what the integrator
137
+ * reported.
138
+ */
139
+ export declare class MemorySpendReporter implements SpendReporter {
140
+ private readonly memoryStore;
141
+ private readonly namespace;
142
+ private readonly ttlSeconds;
143
+ constructor(config: MemorySpendReporterConfig);
144
+ reportSpend(event: FederationSpendEvent): Promise<void>;
145
+ /** Read configured namespace (for the doctor/debug surface). */
146
+ getNamespace(): string;
147
+ /** Read configured TTL in seconds. */
148
+ getTtlSeconds(): number;
149
+ }
150
+ //# sourceMappingURL=spend-reporter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"spend-reporter.d.ts","sourceRoot":"","sources":["../../src/application/spend-reporter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAEH,yDAAyD;AACzD,MAAM,WAAW,oBAAoB;IACnC,2CAA2C;IAC3C,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,qEAAqE;IACrE,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IACzB,8EAA8E;IAC9E,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,uDAAuD;IACvD,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,kGAAkG;IAClG,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,4EAA4E;IAC5E,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;CAC3B;AAED;;;;;;;;GAQG;AACH,MAAM,WAAW,aAAa;IAC5B,WAAW,CAAC,KAAK,EAAE,oBAAoB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACzD;AAED;;;;;;;GAOG;AACH,qBAAa,qBAAsB,YAAW,aAAa;IACzD,OAAO,CAAC,QAA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* Federation spend-reporting interface (ADR-097 Phase 3 upstream).
3
+ *
4
+ * The federation layer doesn't own model pricing — it can't know how much
5
+ * a downstream agent's work cost until the integrator tells it. So the
6
+ * coordinator exposes a `reportSpend()` method that callers invoke after
7
+ * their downstream completes, and that method fans out to:
8
+ *
9
+ * 1. The injected SpendReporter (if any) — typically wires to the
10
+ * cost-tracker bus / `federation-spend` memory namespace
11
+ * 2. The injected FederationBreakerService (if any) — its in-memory
12
+ * buffer becomes a transparent cache when the cost-tracker
13
+ * subscriber lands
14
+ *
15
+ * Both deps are constructor-optional. A coordinator with neither still
16
+ * accepts reportSpend() calls (silent no-op) so callers don't need to
17
+ * branch on which integrations are wired.
18
+ *
19
+ * Event shape matches the consumer contract pinned by
20
+ * plugins/ruflo-cost-tracker/scripts/federation.mjs:
21
+ *
22
+ * { peerId, taskId, tokensUsed, usdSpent, ts }
23
+ *
24
+ * Storage layout (consumer convention): namespace `federation-spend`,
25
+ * key `fed-spend-<peerId>-<ts>`. The interface is storage-agnostic; the
26
+ * default in-memory reporter included here is for tests + a reference
27
+ * implementation. Production integrators write a thin adapter that
28
+ * persists to ruflo memory / Redis / Datadog / their accounting system.
29
+ */
30
+ /**
31
+ * In-memory reporter for tests + a reference implementation. Production
32
+ * code should wire a real SpendReporter that persists to durable storage.
33
+ *
34
+ * Buffer is unbounded — fine for tests, NOT fine for long-running
35
+ * production. The cost-tracker consumer reads from durable storage, not
36
+ * from this buffer.
37
+ */
38
+ export class InMemorySpendReporter {
39
+ buffer = [];
40
+ async reportSpend(event) {
41
+ this.buffer.push(event);
42
+ }
43
+ /** Snapshot of all reported events (test inspection). */
44
+ getEvents() {
45
+ return [...this.buffer];
46
+ }
47
+ /** Drop everything (test cleanup). */
48
+ clear() {
49
+ this.buffer.length = 0;
50
+ }
51
+ }
52
+ /** Default namespace per cost-tracker's `plugins/ruflo-cost-tracker/scripts/federation.mjs`. */
53
+ export const DEFAULT_FEDERATION_SPEND_NAMESPACE = 'federation-spend';
54
+ /** Default TTL: 7 days, matching cost-tracker's longest rolling window. */
55
+ export const DEFAULT_FEDERATION_SPEND_TTL_SECONDS = 7 * 24 * 60 * 60;
56
+ /**
57
+ * Production reporter (ADR-110) that satisfies the cost-tracker
58
+ * consumer contract: writes to namespace `federation-spend`, key
59
+ * `fed-spend-<peerId>-<ts>`. The consumer
60
+ * (`plugins/ruflo-cost-tracker/scripts/federation.mjs`) `memory list`s
61
+ * the namespace, retrieves each key, and aggregates into rolling
62
+ * windows.
63
+ *
64
+ * Storage-agnostic: the integrator injects a `MemoryStore`
65
+ * implementation. Common wirings:
66
+ *
67
+ * // ruflo memory MCP
68
+ * new MemorySpendReporter({
69
+ * memoryStore: {
70
+ * store: async (a) => mcpClient.call('memory_store', a),
71
+ * },
72
+ * });
73
+ *
74
+ * // ruflo memory CLI shell-out
75
+ * new MemorySpendReporter({
76
+ * memoryStore: {
77
+ * store: async ({namespace, key, value, ttl}) => {
78
+ * await execFile('npx', ['ruflo', 'memory', 'store',
79
+ * '--namespace', namespace, '--key', key, '--value', value]);
80
+ * },
81
+ * },
82
+ * });
83
+ *
84
+ * Errors from the memory backend BUBBLE UP — the reporter does not
85
+ * retry/swallow. Wrap with the integrator's preferred retry strategy
86
+ * if needed.
87
+ *
88
+ * Negative `tokensUsed` / `usdSpent` are persisted as-is. Clamping is
89
+ * the breaker's responsibility (see federation-breaker-service.ts);
90
+ * the audit/spend log is an honest mirror of what the integrator
91
+ * reported.
92
+ */
93
+ export class MemorySpendReporter {
94
+ memoryStore;
95
+ namespace;
96
+ ttlSeconds;
97
+ constructor(config) {
98
+ this.memoryStore = config.memoryStore;
99
+ this.namespace = config.namespace ?? DEFAULT_FEDERATION_SPEND_NAMESPACE;
100
+ this.ttlSeconds = config.ttlSeconds ?? DEFAULT_FEDERATION_SPEND_TTL_SECONDS;
101
+ }
102
+ async reportSpend(event) {
103
+ const key = `fed-spend-${event.peerId}-${event.ts}`;
104
+ const value = JSON.stringify({
105
+ peerId: event.peerId,
106
+ taskId: event.taskId ?? null,
107
+ tokensUsed: event.tokensUsed,
108
+ usdSpent: event.usdSpent,
109
+ success: event.success,
110
+ ts: event.ts,
111
+ });
112
+ await this.memoryStore.store({
113
+ namespace: this.namespace,
114
+ key,
115
+ value,
116
+ ttl: this.ttlSeconds,
117
+ });
118
+ }
119
+ /** Read configured namespace (for the doctor/debug surface). */
120
+ getNamespace() {
121
+ return this.namespace;
122
+ }
123
+ /** Read configured TTL in seconds. */
124
+ getTtlSeconds() {
125
+ return this.ttlSeconds;
126
+ }
127
+ }
128
+ //# sourceMappingURL=spend-reporter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"spend-reporter.js","sourceRoot":"","sources":["../../src/application/spend-reporter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AA+BH;;;;;;;GAOG;AACH,MAAM,OAAO,qBAAqB;IACf,MAAM,GAA2B,EAAE,CAAC;IAErD,KAAK,CAAC,WAAW,CAAC,KAA2B;QAC3C,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC1B,CAAC;IAED,yDAAyD;IACzD,SAAS;QACP,OAAO,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;IAC1B,CAAC;IAED,sCAAsC;IACtC,KAAK;QACH,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC;IACzB,CAAC;CACF;AA6BD,gGAAgG;AAChG,MAAM,CAAC,MAAM,kCAAkC,GAAG,kBAAkB,CAAC;AAErE,2EAA2E;AAC3E,MAAM,CAAC,MAAM,oCAAoC,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC;AAErE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,MAAM,OAAO,mBAAmB;IACb,WAAW,CAAc;IACzB,SAAS,CAAS;IAClB,UAAU,CAAS;IAEpC,YAAY,MAAiC;QAC3C,IAAI,CAAC,WAAW,GAAG,MAAM,CAAC,WAAW,CAAC;QACtC,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC,SAAS,IAAI,kCAAkC,CAAC;QACxE,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,UAAU,IAAI,oCAAoC,CAAC;IAC9E,CAAC;IAED,KAAK,CAAC,WAAW,CAAC,KAA2B;QAC3C,MAAM,GAAG,GAAG,aAAa,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,EAAE,EAAE,CAAC;QACpD,MAAM,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC;YAC3B,MAAM,EAAE,KAAK,CAAC,MAAM;YACpB,MAAM,EAAE,KAAK,CAAC,MAAM,IAAI,IAAI;YAC5B,UAAU,EAAE,KAAK,CAAC,UAAU;YAC5B,QAAQ,EAAE,KAAK,CAAC,QAAQ;YACxB,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,EAAE,EAAE,KAAK,CAAC,EAAE;SACb,CAAC,CAAC;QACH,MAAM,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC;YAC3B,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,GAAG;YACH,KAAK;YACL,GAAG,EAAE,IAAI,CAAC,UAAU;SACrB,CAAC,CAAC;IACL,CAAC;IAED,gEAAgE;IAChE,YAAY;QACV,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IAED,sCAAsC;IACtC,aAAa;QACX,OAAO,IAAI,CAAC,UAAU,CAAC;IACzB,CAAC;CACF"}
@@ -0,0 +1,42 @@
1
+ import { TrustLevel } from '../domain/entities/trust-level.js';
2
+ import { FederationNode } from '../domain/entities/federation-node.js';
3
+ import { type SessionMetrics } from '../domain/entities/federation-session.js';
4
+ export interface TrustScoreComponents {
5
+ readonly successRate: number;
6
+ readonly uptime: number;
7
+ readonly threatPenalty: number;
8
+ readonly dataIntegrityScore: number;
9
+ }
10
+ export interface TrustTransitionResult {
11
+ readonly previousLevel: TrustLevel;
12
+ readonly newLevel: TrustLevel;
13
+ readonly score: number;
14
+ readonly components: TrustScoreComponents;
15
+ readonly reason: string;
16
+ readonly requiresHumanApproval: boolean;
17
+ }
18
+ export type ImmediateDowngradeReason = 'repeated-threat-detection' | 'hmac-verification-failure' | 'session-hijack-attempt';
19
+ export interface TrustEvaluatorDeps {
20
+ onTrustChange?: (nodeId: string, result: TrustTransitionResult) => void;
21
+ }
22
+ export interface ThreatWindow {
23
+ readonly detections: Date[];
24
+ readonly windowMs: number;
25
+ readonly threshold: number;
26
+ }
27
+ export declare class TrustEvaluator {
28
+ private readonly deps;
29
+ private readonly threatWindows;
30
+ constructor(deps?: TrustEvaluatorDeps);
31
+ computeScore(metrics: SessionMetrics, uptimeRatio: number): {
32
+ score: number;
33
+ components: TrustScoreComponents;
34
+ };
35
+ evaluateTransition(node: FederationNode, metrics: SessionMetrics, uptimeRatio: number, hasInstitutionalAttestation?: boolean): TrustTransitionResult | null;
36
+ downgrade(node: FederationNode, reason: ImmediateDowngradeReason): TrustTransitionResult;
37
+ recordThreatDetection(nodeId: string): boolean;
38
+ private checkUpgrade;
39
+ private checkDowngrade;
40
+ private computeThreatPenalty;
41
+ }
42
+ //# sourceMappingURL=trust-evaluator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trust-evaluator.d.ts","sourceRoot":"","sources":["../../src/application/trust-evaluator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAA+B,MAAM,mCAAmC,CAAC;AAC5F,OAAO,EAAE,cAAc,EAAE,MAAM,uCAAuC,CAAC;AACvE,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,0CAA0C,CAAC;AAE/E,MAAM,WAAW,oBAAoB;IACnC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,kBAAkB,EAAE,MAAM,CAAC;CACrC;AAED,MAAM,WAAW,q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wBpB,OAAO,CAAC,cAAc;IAetB,OAAO,CAAC,oBAAoB;CAK7B"}
@@ -0,0 +1,132 @@
1
+ import { TrustLevel, TRUST_TRANSITION_THRESHOLDS } from '../domain/entities/trust-level.js';
2
+ const THREAT_WINDOW_CONFIG = {
3
+ detections: [],
4
+ windowMs: 3_600_000,
5
+ threshold: 2,
6
+ };
7
+ export class TrustEvaluator {
8
+ deps;
9
+ threatWindows;
10
+ constructor(deps = {}) {
11
+ this.deps = deps;
12
+ this.threatWindows = new Map();
13
+ }
14
+ computeScore(metrics, uptimeRatio) {
15
+ const totalAttempted = metrics.messagesSent + metrics.messagesReceived;
16
+ const successRate = totalAttempted > 0
17
+ ? (totalAttempted - metrics.hmacFailures) / totalAttempted
18
+ : 0;
19
+ const uptime = Math.max(0, Math.min(1, uptimeRatio));
20
+ const threatPenalty = this.computeThreatPenalty(metrics.threatDetections, totalAttempted);
21
+ const dataIntegrityScore = totalAttempted > 0
22
+ ? 1 - (metrics.hmacFailures / totalAttempted)
23
+ : 1;
24
+ const score = 0.4 * successRate +
25
+ 0.2 * uptime +
26
+ 0.2 * (1 - threatPenalty) +
27
+ 0.2 * dataIntegrityScore;
28
+ const components = {
29
+ successRate,
30
+ uptime,
31
+ threatPenalty,
32
+ dataIntegrityScore,
33
+ };
34
+ return { score: Math.max(0, Math.min(1, score)), components };
35
+ }
36
+ evaluateTransition(node, metrics, uptimeRatio, hasInstitutionalAttestation = false) {
37
+ const { score, components } = this.computeScore(metrics, uptimeRatio);
38
+ const currentLevel = node.trustLevel;
39
+ node.updateTrustScore(score);
40
+ const upgrade = this.checkUpgrade(currentLevel, score, metrics.totalInteractions, hasInstitutionalAttestation);
41
+ if (upgrade !== null) {
42
+ const result = {
43
+ previousLevel: currentLevel,
44
+ newLevel: upgrade,
45
+ score,
46
+ components,
47
+ reason: `Score ${score.toFixed(3)} meets upgrade threshold for level ${upgrade}`,
48
+ requiresHumanApproval: upgrade === TrustLevel.PRIVILEGED,
49
+ };
50
+ if (!result.requiresHumanApproval) {
51
+ node.updateTrustLevel(upgrade);
52
+ }
53
+ this.deps.onTrustChange?.(node.nodeId, result);
54
+ return result;
55
+ }
56
+ const downgrade = this.checkDowngrade(currentLevel, score);
57
+ if (downgrade !== null) {
58
+ const result = {
59
+ previousLevel: currentLevel,
60
+ newLevel: downgrade,
61
+ score,
62
+ components,
63
+ reason: `Score ${score.toFixed(3)} dropped below downgrade threshold for level ${currentLevel}`,
64
+ requiresHumanApproval: false,
65
+ };
66
+ node.updateTrustLevel(downgrade);
67
+ this.deps.onTrustChange?.(node.nodeId, result);
68
+ return result;
69
+ }
70
+ return null;
71
+ }
72
+ downgrade(node, reason) {
73
+ const previousLevel = node.trustLevel;
74
+ node.updateTrustLevel(TrustLevel.UNTRUSTED);
75
+ node.updateTrustScore(0);
76
+ const result = {
77
+ previousLevel,
78
+ newLevel: TrustLevel.UNTRUSTED,
79
+ score: 0,
80
+ components: { successRate: 0, uptime: 0, threatPenalty: 1, dataIntegrityScore: 0 },
81
+ reason: `Immediate downgrade: ${reason}`,
82
+ requiresHumanApproval: false,
83
+ };
84
+ this.deps.onTrustChange?.(node.nodeId, result);
85
+ return result;
86
+ }
87
+ recordThreatDetection(nodeId) {
88
+ const now = new Date();
89
+ const detections = this.threatWindows.get(nodeId) ?? [];
90
+ detections.push(now);
91
+ const windowStart = now.getTime() - THREAT_WINDOW_CONFIG.windowMs;
92
+ const recentDetections = detections.filter(d => d.getTime() > windowStart);
93
+ this.threatWindows.set(nodeId, recentDetections);
94
+ return recentDetections.length >= THREAT_WINDOW_CONFIG.threshold;
95
+ }
96
+ checkUpgrade(currentLevel, score, totalInteractions, hasInstitutionalAttestation) {
97
+ if (currentLevel >= TrustLevel.PRIVILEGED)
98
+ return null;
99
+ const nextLevel = currentLevel + 1;
100
+ const transitionKey = `${currentLevel}->${nextLevel}`;
101
+ const threshold = TRUST_TRANSITION_THRESHOLDS[transitionKey];
102
+ if (!threshold)
103
+ return null;
104
+ if (score < threshold.upgradeScore)
105
+ return null;
106
+ if (totalInteractions < threshold.minInteractions)
107
+ return null;
108
+ if (nextLevel === TrustLevel.PRIVILEGED && !hasInstitutionalAttestation) {
109
+ return null;
110
+ }
111
+ return nextLevel;
112
+ }
113
+ checkDowngrade(currentLevel, score) {
114
+ if (currentLevel <= TrustLevel.UNTRUSTED)
115
+ return null;
116
+ const transitionKey = `${currentLevel - 1}->${currentLevel}`;
117
+ const threshold = TRUST_TRANSITION_THRESHOLDS[transitionKey];
118
+ if (!threshold)
119
+ return null;
120
+ if (score < threshold.downgradeScore) {
121
+ return (currentLevel - 1);
122
+ }
123
+ return null;
124
+ }
125
+ computeThreatPenalty(threatCount, totalMessages) {
126
+ if (totalMessages === 0)
127
+ return 0;
128
+ const ratio = threatCount / totalMessages;
129
+ return Math.min(1, ratio * 10);
130
+ }
131
+ }
132
+ //# sourceMappingURL=trust-evaluator.js.map