@agentbadge/database 0.5.4 → 0.6.1

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.
@@ -0,0 +1,183 @@
1
+ export function edgeKey(e) {
2
+ return `${e.fromAgent}|${e.toAgent}|${e.kind}`;
3
+ }
4
+ export function edgeDeltaOf(event, ledgerSeq) {
5
+ if (!event.counterparty)
6
+ return null;
7
+ return {
8
+ fromAgent: event.actor,
9
+ toAgent: event.counterparty,
10
+ kind: event.kind,
11
+ count: 1,
12
+ usdMicros: toMicros(event.amountUsdc),
13
+ firstEventAt: event.at,
14
+ firstEventSeq: ledgerSeq,
15
+ lastEventAt: event.at,
16
+ lastEventSeq: ledgerSeq,
17
+ };
18
+ }
19
+ export function deltasOfAppended(results) {
20
+ const out = [];
21
+ for (const r of results) {
22
+ if (r.duplicate)
23
+ continue;
24
+ const d = edgeDeltaOf(r.event, r.ledgerSeq);
25
+ if (d)
26
+ out.push(d);
27
+ }
28
+ return mergeDeltas(out);
29
+ }
30
+ export function mergeDeltas(deltas) {
31
+ const byKey = new Map();
32
+ for (const d of deltas) {
33
+ const k = edgeKey(d);
34
+ const prev = byKey.get(k);
35
+ if (!prev) {
36
+ byKey.set(k, { ...d });
37
+ continue;
38
+ }
39
+ prev.count += d.count;
40
+ prev.usdMicros += d.usdMicros;
41
+ if (d.firstEventSeq < prev.firstEventSeq) {
42
+ prev.firstEventSeq = d.firstEventSeq;
43
+ prev.firstEventAt = d.firstEventAt;
44
+ }
45
+ if (d.lastEventSeq > prev.lastEventSeq) {
46
+ prev.lastEventSeq = d.lastEventSeq;
47
+ prev.lastEventAt = d.lastEventAt;
48
+ }
49
+ }
50
+ return [...byKey.values()];
51
+ }
52
+ export function applyDelta(edge, d) {
53
+ const earlier = edge.firstEventSeq === null || d.firstEventSeq < edge.firstEventSeq;
54
+ return {
55
+ fromAgent: edge.fromAgent,
56
+ toAgent: edge.toAgent,
57
+ kind: edge.kind,
58
+ eventCount: edge.eventCount + d.count,
59
+ totalUsd: fromMicros(toMicros(edge.totalUsd) + d.usdMicros),
60
+ firstEventAt: earlier ? d.firstEventAt : edge.firstEventAt,
61
+ firstEventSeq: earlier ? d.firstEventSeq : edge.firstEventSeq,
62
+ lastEventAt: d.lastEventSeq > edge.lastEventSeq ? d.lastEventAt : edge.lastEventAt,
63
+ lastEventSeq: d.lastEventSeq > edge.lastEventSeq ? d.lastEventSeq : edge.lastEventSeq,
64
+ };
65
+ }
66
+ export function foldLog(stored) {
67
+ const byKey = new Map();
68
+ for (const s of stored) {
69
+ const d = edgeDeltaOf(s.event, s.ledgerSeq);
70
+ if (!d)
71
+ continue;
72
+ const k = edgeKey(d);
73
+ const prev = byKey.get(k);
74
+ const merged = applyDelta(prev ?? {
75
+ fromAgent: d.fromAgent,
76
+ toAgent: d.toAgent,
77
+ kind: d.kind,
78
+ eventCount: 0,
79
+ totalUsd: "0",
80
+ firstEventAt: null,
81
+ firstEventSeq: null,
82
+ lastEventAt: "",
83
+ lastEventSeq: 0n,
84
+ }, d);
85
+ byKey.set(k, merged);
86
+ }
87
+ return [...byKey.values()];
88
+ }
89
+ export function rowToEdgeRecord(row) {
90
+ return {
91
+ fromAgent: row.fromAgent,
92
+ toAgent: row.toAgent,
93
+ kind: row.kind,
94
+ eventCount: row.eventCount,
95
+ totalUsd: String(row.totalUsd),
96
+ firstEventAt: row.firstEventAt ?? null,
97
+ firstEventSeq: row.firstEventSeq !== null && row.firstEventSeq !== undefined
98
+ ? BigInt(row.firstEventSeq)
99
+ : null,
100
+ lastEventAt: row.lastEventAt,
101
+ lastEventSeq: BigInt(row.lastEventSeq),
102
+ };
103
+ }
104
+ export function toMicros(usd) {
105
+ if (!usd)
106
+ return 0n;
107
+ const neg = usd.startsWith("-");
108
+ const body = neg ? usd.slice(1) : usd;
109
+ const [i, f = ""] = body.split(".");
110
+ const frac = (f + "000000").slice(0, 6);
111
+ const v = BigInt(i || "0") * 1000000n + BigInt(frac);
112
+ return neg ? -v : v;
113
+ }
114
+ export function fromMicros(micros) {
115
+ const neg = micros < 0n;
116
+ const v = neg ? -micros : micros;
117
+ const i = v / 1000000n;
118
+ const f = (v % 1000000n).toString().padStart(6, "0").replace(/0+$/, "");
119
+ return `${neg ? "-" : ""}${i}${f ? "." + f : ""}`;
120
+ }
121
+ export async function rebuildTrustEdges(ledger, edges, opts) {
122
+ const chunk = opts?.chunk ?? 1_000;
123
+ const all = [];
124
+ for (let cursor = 0n;;) {
125
+ const batch = await ledger.scan(cursor, { limit: chunk });
126
+ all.push(...batch);
127
+ if (batch.length < chunk)
128
+ break;
129
+ cursor = batch[batch.length - 1].ledgerSeq + 1n;
130
+ }
131
+ const folded = foldLog(all);
132
+ await edges.replaceAll(folded);
133
+ return { scanned: all.length, written: folded.length };
134
+ }
135
+ export class InMemoryTrustEdgeStore {
136
+ byKey = new Map();
137
+ static key(e) {
138
+ return edgeKey(e);
139
+ }
140
+ async applyDeltasTx(_tx, deltas) {
141
+ await this.applyDeltas(deltas);
142
+ }
143
+ async applyDeltas(deltas) {
144
+ for (const d of mergeDeltas(deltas)) {
145
+ const k = InMemoryTrustEdgeStore.key(d);
146
+ const prev = this.byKey.get(k);
147
+ this.byKey.set(k, prev
148
+ ? applyDelta(prev, d)
149
+ : {
150
+ fromAgent: d.fromAgent,
151
+ toAgent: d.toAgent,
152
+ kind: d.kind,
153
+ eventCount: d.count,
154
+ totalUsd: fromMicros(d.usdMicros),
155
+ firstEventAt: d.firstEventAt,
156
+ firstEventSeq: d.firstEventSeq,
157
+ lastEventAt: d.lastEventAt,
158
+ lastEventSeq: d.lastEventSeq,
159
+ });
160
+ }
161
+ }
162
+ async listFrom(fromAgent) {
163
+ return this.all().filter((e) => e.fromAgent === fromAgent);
164
+ }
165
+ async listTo(toAgent) {
166
+ return this.all().filter((e) => e.toAgent === toAgent);
167
+ }
168
+ async listPair(a, b) {
169
+ return this.all().filter((e) => (e.fromAgent === a && e.toAgent === b) ||
170
+ (e.fromAgent === b && e.toAgent === a));
171
+ }
172
+ async listAll() {
173
+ return this.all();
174
+ }
175
+ async replaceAll(edges) {
176
+ this.byKey.clear();
177
+ for (const e of edges)
178
+ this.byKey.set(InMemoryTrustEdgeStore.key(e), { ...e });
179
+ }
180
+ all() {
181
+ return [...this.byKey.values()].sort((x, y) => x.lastEventSeq > y.lastEventSeq ? -1 : x.lastEventSeq < y.lastEventSeq ? 1 : 0);
182
+ }
183
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentbadge/database",
3
- "version": "0.5.4",
3
+ "version": "0.6.1",
4
4
  "description": "Shared database layer for AgentBadge — Prisma ORM 8 client, repositories, store abstraction",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -50,6 +50,7 @@
50
50
  "vitest": "^2.0.0"
51
51
  },
52
52
  "dependencies": {
53
+ "@agentbadge/econ-events": "^0.1.1",
53
54
  "@prisma/orm-postgres": "8.0.0-rc.11",
54
55
  "dotenv": "^18.0.3"
55
56
  }