@agentbadge/database 0.6.14 → 0.6.16

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.
@@ -766,6 +766,20 @@
766
766
  "kind": "scalar"
767
767
  }
768
768
  },
769
+ "retractReason": {
770
+ "nullable": true,
771
+ "type": {
772
+ "codecId": "pg/text@1",
773
+ "kind": "scalar"
774
+ }
775
+ },
776
+ "retractedAtMs": {
777
+ "nullable": true,
778
+ "type": {
779
+ "codecId": "pg/int8@1",
780
+ "kind": "scalar"
781
+ }
782
+ },
769
783
  "sourceRequestId": {
770
784
  "nullable": false,
771
785
  "type": {
@@ -809,6 +823,12 @@
809
823
  "response": {
810
824
  "column": "response"
811
825
  },
826
+ "retractReason": {
827
+ "column": "retractReason"
828
+ },
829
+ "retractedAtMs": {
830
+ "column": "retractedAtMs"
831
+ },
812
832
  "sourceRequestId": {
813
833
  "column": "sourceRequestId"
814
834
  },
@@ -895,6 +915,13 @@
895
915
  "kind": "scalar"
896
916
  }
897
917
  },
918
+ "publishToQa": {
919
+ "nullable": false,
920
+ "type": {
921
+ "codecId": "pg/bool@1",
922
+ "kind": "scalar"
923
+ }
924
+ },
898
925
  "respondedAtMs": {
899
926
  "nullable": true,
900
927
  "type": {
@@ -971,6 +998,9 @@
971
998
  "payload": {
972
999
  "column": "payload"
973
1000
  },
1001
+ "publishToQa": {
1002
+ "column": "publishToQa"
1003
+ },
974
1004
  "respondedAtMs": {
975
1005
  "column": "respondedAtMs"
976
1006
  },
@@ -7825,6 +7855,16 @@
7825
7855
  "nativeType": "json",
7826
7856
  "nullable": false
7827
7857
  },
7858
+ "retractReason": {
7859
+ "codecId": "pg/text@1",
7860
+ "nativeType": "text",
7861
+ "nullable": true
7862
+ },
7863
+ "retractedAtMs": {
7864
+ "codecId": "pg/int8@1",
7865
+ "nativeType": "int8",
7866
+ "nullable": true
7867
+ },
7828
7868
  "sourceRequestId": {
7829
7869
  "codecId": "pg/text@1",
7830
7870
  "nativeType": "text",
@@ -7933,6 +7973,15 @@
7933
7973
  "nativeType": "json",
7934
7974
  "nullable": true
7935
7975
  },
7976
+ "publishToQa": {
7977
+ "codecId": "pg/bool@1",
7978
+ "default": {
7979
+ "kind": "literal",
7980
+ "value": false
7981
+ },
7982
+ "nativeType": "bool",
7983
+ "nullable": false
7984
+ },
7936
7985
  "respondedAtMs": {
7937
7986
  "codecId": "pg/int8@1",
7938
7987
  "nativeType": "int8",
@@ -12118,14 +12167,6 @@
12118
12167
  "name": "refundIntent_status_createdAtMs_idx_95013a06",
12119
12168
  "prefix": "refundIntent_status_createdAtMs_idx",
12120
12169
  "unique": false
12121
- },
12122
- {
12123
- "columns": [
12124
- "txHash"
12125
- ],
12126
- "name": "refundIntent_txHash_idx_3fbe8b55",
12127
- "prefix": "refundIntent_txHash_idx",
12128
- "unique": false
12129
12170
  }
12130
12171
  ],
12131
12172
  "primaryKey": {
@@ -12133,7 +12174,13 @@
12133
12174
  "id"
12134
12175
  ]
12135
12176
  },
12136
- "uniques": []
12177
+ "uniques": [
12178
+ {
12179
+ "columns": [
12180
+ "txHash"
12181
+ ]
12182
+ }
12183
+ ]
12137
12184
  },
12138
12185
  "reputationFact": {
12139
12186
  "columns": {
@@ -13172,7 +13219,7 @@
13172
13219
  "kind": "postgres-schema"
13173
13220
  }
13174
13221
  },
13175
- "storageHash": "174bbe13adcd8dd1ef05efb4b4ab5e7a9b30646347d508ceedf1f228d4298d7b"
13222
+ "storageHash": "5cc05c7580b7916ed4b358c580b28b24d76b9c2825fbe72c359888fb6df0a582"
13176
13223
  },
13177
13224
  "execution": {
13178
13225
  "executionHash": "cda992afecb515ff2c2dd351b5c0b83fb88ef1603d7125472d90da7e198b024b",
@@ -14,6 +14,7 @@ export interface AgentRequestUpsert {
14
14
  verified?: boolean;
15
15
  response?: JsonValue | null;
16
16
  spamFlag?: boolean;
17
+ publishToQa?: boolean;
17
18
  idempotencyKey?: string | null;
18
19
  expiresAtMs: number;
19
20
  createdAtMs: number;
@@ -50,6 +51,7 @@ export declare class AgentRequestRepository {
50
51
  purgePayload(id: string): Promise<boolean>;
51
52
  delete(id: string): Promise<boolean>;
52
53
  upsertQaPair(qa: AgentQAPairUpsert): Promise<QaRow>;
54
+ retractQaPair(id: string, reason: string, retractedAtMs: number): Promise<QaRow | null>;
53
55
  getQaByHash(questionHash: string): Promise<QaRow | null>;
54
56
  searchQa(substring: string, limit?: number): Promise<QaRow[]>;
55
57
  }
@@ -19,6 +19,7 @@ export class AgentRequestRepository {
19
19
  verified: r.verified ?? false,
20
20
  response: r.response ?? null,
21
21
  spamFlag: r.spamFlag ?? false,
22
+ publishToQa: r.publishToQa ?? false,
22
23
  idempotencyKey: r.idempotencyKey ?? null,
23
24
  expiresAtMs: toBig(r.expiresAtMs),
24
25
  createdAtMs: toBig(r.createdAtMs),
@@ -128,10 +129,24 @@ export class AgentRequestRepository {
128
129
  createdAtMs: BigInt(qa.createdAtMs),
129
130
  });
130
131
  }
132
+ async retractQaPair(id, reason, retractedAtMs) {
133
+ const existing = await this.db.orm.public.AgentQAPair.where({
134
+ id,
135
+ }).first();
136
+ if (!existing)
137
+ return null;
138
+ if (existing.retractedAtMs != null)
139
+ return existing;
140
+ return this.db.orm.public.AgentQAPair.where({ id }).update({
141
+ retractedAtMs: BigInt(retractedAtMs),
142
+ retractReason: reason,
143
+ });
144
+ }
131
145
  async getQaByHash(questionHash) {
132
- return this.db.orm.public.AgentQAPair.where({
146
+ const row = await this.db.orm.public.AgentQAPair.where({
133
147
  questionHash,
134
148
  }).first();
149
+ return row != null && row.retractedAtMs == null ? row : null;
135
150
  }
136
151
  async searchQa(substring, limit = 50) {
137
152
  const needle = substring.toLowerCase();
@@ -139,7 +154,8 @@ export class AgentRequestRepository {
139
154
  .limit(500)
140
155
  .all();
141
156
  return rows
142
- .filter((r) => r.question.toLowerCase().includes(needle))
157
+ .filter((r) => r.retractedAtMs == null &&
158
+ r.question.toLowerCase().includes(needle))
143
159
  .slice(0, limit);
144
160
  }
145
161
  }
@@ -73,5 +73,14 @@ export declare class CommercePaymentRepository implements CommercePaymentStore {
73
73
  getById(id: string): Promise<CommercePaymentRow | null>;
74
74
  getByAgreement(agreementId: string): Promise<CommercePaymentRow | null>;
75
75
  applyStatus(id: string, expectedFrom: string, to: string, patch?: PaymentStatusPatch): Promise<CommercePaymentRow | null>;
76
+ list(opts?: {
77
+ mode?: string;
78
+ status?: string;
79
+ statuses?: readonly string[];
80
+ recordedSinceMs?: number;
81
+ recordedUntilMs?: number;
82
+ limit?: number;
83
+ offset?: number;
84
+ }): Promise<CommercePaymentRow[]>;
76
85
  }
77
86
  export declare function createPrismaCommerceStores(db: PrismaDb): CommerceStores;
@@ -500,6 +500,30 @@ export class CommercePaymentRepository {
500
500
  });
501
501
  return row ? toPaymentRow(row) : null;
502
502
  }
503
+ async list(opts = {}) {
504
+ const statusSet = opts.statuses !== undefined
505
+ ? new Set(opts.statuses)
506
+ : opts.status !== undefined
507
+ ? new Set([opts.status])
508
+ : undefined;
509
+ const eq = {};
510
+ if (opts.mode !== undefined)
511
+ eq["mode"] = opts.mode;
512
+ const candidates = await this.orm.where(eq).all();
513
+ const stamp = (r) => r.recordedAtMs ?? Date.parse(r.createdAt);
514
+ const out = candidates
515
+ .map(toPaymentRow)
516
+ .filter((r) => (statusSet === undefined || statusSet.has(r.status)) &&
517
+ (opts.recordedSinceMs === undefined ||
518
+ (r.recordedAtMs != null &&
519
+ r.recordedAtMs >= opts.recordedSinceMs)) &&
520
+ (opts.recordedUntilMs === undefined ||
521
+ (r.recordedAtMs != null &&
522
+ r.recordedAtMs <= opts.recordedUntilMs)));
523
+ out.sort((a, b) => stamp(b) - stamp(a));
524
+ const offset = opts.offset ?? 0;
525
+ return out.slice(offset, opts.limit === undefined ? undefined : offset + opts.limit);
526
+ }
503
527
  }
504
528
  export function createPrismaCommerceStores(db) {
505
529
  const bundle = (client) => ({
@@ -179,6 +179,15 @@ export interface CommercePaymentStore {
179
179
  getById(id: string): Promise<CommercePaymentRow | null>;
180
180
  getByAgreement(agreementId: string): Promise<CommercePaymentRow | null>;
181
181
  applyStatus(id: string, expectedFrom: string, to: string, patch?: PaymentStatusPatch): Promise<CommercePaymentRow | null>;
182
+ list(opts?: {
183
+ mode?: string;
184
+ status?: string;
185
+ statuses?: readonly string[];
186
+ recordedSinceMs?: number;
187
+ recordedUntilMs?: number;
188
+ limit?: number;
189
+ offset?: number;
190
+ }): Promise<CommercePaymentRow[]>;
182
191
  }
183
192
  export interface CommerceStores {
184
193
  tasks: CommerceTaskStore;
@@ -249,5 +258,14 @@ export declare class InMemoryCommercePaymentStore implements CommercePaymentStor
249
258
  getById(id: string): Promise<CommercePaymentRow | null>;
250
259
  getByAgreement(agreementId: string): Promise<CommercePaymentRow | null>;
251
260
  applyStatus(id: string, expectedFrom: string, to: string, patch?: PaymentStatusPatch): Promise<CommercePaymentRow | null>;
261
+ list(opts?: {
262
+ mode?: string;
263
+ status?: string;
264
+ statuses?: readonly string[];
265
+ recordedSinceMs?: number;
266
+ recordedUntilMs?: number;
267
+ limit?: number;
268
+ offset?: number;
269
+ }): Promise<CommercePaymentRow[]>;
252
270
  }
253
271
  export declare function createInMemoryCommerceStores(): CommerceStores;
@@ -301,6 +301,25 @@ export class InMemoryCommercePaymentStore {
301
301
  this.rows.set(id, next);
302
302
  return next;
303
303
  }
304
+ async list(opts = {}) {
305
+ const statusSet = opts.statuses !== undefined
306
+ ? new Set(opts.statuses)
307
+ : opts.status !== undefined
308
+ ? new Set([opts.status])
309
+ : undefined;
310
+ const stamp = (r) => r.recordedAtMs ?? Date.parse(r.createdAt);
311
+ const out = [...this.rows.values()].filter((r) => (opts.mode === undefined || r.mode === opts.mode) &&
312
+ (statusSet === undefined || statusSet.has(r.status)) &&
313
+ (opts.recordedSinceMs === undefined ||
314
+ (r.recordedAtMs != null &&
315
+ r.recordedAtMs >= opts.recordedSinceMs)) &&
316
+ (opts.recordedUntilMs === undefined ||
317
+ (r.recordedAtMs != null &&
318
+ r.recordedAtMs <= opts.recordedUntilMs)));
319
+ out.sort((a, b) => stamp(b) - stamp(a));
320
+ const offset = opts.offset ?? 0;
321
+ return out.slice(offset, opts.limit === undefined ? undefined : offset + opts.limit);
322
+ }
304
323
  }
305
324
  function cloneRows(value) {
306
325
  if (value === null || typeof value !== "object")
@@ -1,5 +1,6 @@
1
1
  import type { PrismaDb } from "./event-repository.js";
2
2
  import type { AdminActionInsert, AdminActionRow, AdminActionStore, FinopsStores, ReconciliationExceptionInsert, ReconciliationExceptionRow, ReconciliationExceptionStore, RefundIntentInsert, RefundIntentRow, RefundIntentStore } from "./finops-store.js";
3
+ export declare const decimalFromDb: (v: unknown) => string;
3
4
  export declare class AdminActionRepository implements AdminActionStore {
4
5
  private readonly db;
5
6
  constructor(db: PrismaDb);
@@ -21,10 +22,13 @@ export declare class RefundIntentRepository implements RefundIntentStore {
21
22
  private get orm();
22
23
  create(r: RefundIntentInsert): Promise<RefundIntentRow | null>;
23
24
  getById(id: string): Promise<RefundIntentRow | null>;
25
+ getByTxHash(txHash: string): Promise<RefundIntentRow | null>;
24
26
  listByPayment(paymentId: string): Promise<RefundIntentRow[]>;
25
27
  list(opts?: {
26
28
  status?: string;
27
29
  limit?: number;
30
+ completedSinceMs?: number;
31
+ completedUntilMs?: number;
28
32
  }): Promise<RefundIntentRow[]>;
29
33
  complete(id: string, txHash: string, completedBy: string, completedAtMs: number): Promise<RefundIntentRow | null>;
30
34
  }
@@ -1,6 +1,27 @@
1
+ function isUniqueViolation(e) {
2
+ if (e === null || typeof e !== "object")
3
+ return false;
4
+ const code = e.code;
5
+ if (code === "23505")
6
+ return true;
7
+ const msg = e instanceof Error ? e.message : String(e);
8
+ return /unique constraint|duplicate key/i.test(msg);
9
+ }
1
10
  const num = (v) => Number(v);
2
11
  const numOrNull = (v) => v === null || v === undefined ? null : Number(v);
3
- const dec = (v) => String(v);
12
+ export const decimalFromDb = (v) => {
13
+ const s = String(v);
14
+ if (/[eE]/.test(s))
15
+ throw new Error(`exponent form from DB: ${s}`);
16
+ const m = /^(-?\d+)(?:\.(\d+))?$/.exec(s);
17
+ if (!m)
18
+ throw new Error(`non-canonical decimal from DB: ${s}`);
19
+ const frac = (m[2] ?? "").replace(/0+$/, "");
20
+ if (frac.length > 6) {
21
+ throw new Error(`decimal exceeds 6dp scale from DB: ${s}`);
22
+ }
23
+ return frac ? `${m[1]}.${frac}` : m[1];
24
+ };
4
25
  const toActionRow = (r) => ({
5
26
  id: r.id,
6
27
  action: r.action,
@@ -15,7 +36,7 @@ const toRefundRow = (r) => ({
15
36
  id: r.id,
16
37
  paymentId: r.paymentId,
17
38
  payee: r.payee,
18
- amount: dec(r.amount),
39
+ amount: decimalFromDb(r.amount),
19
40
  currency: r.currency,
20
41
  reason: r.reason,
21
42
  evidence: r.evidence ?? undefined,
@@ -116,7 +137,7 @@ export class RefundIntentRepository {
116
137
  status: r.status,
117
138
  operator: r.operator,
118
139
  createdAtMs: BigInt(r.createdAtMs),
119
- payload: (r.payload ?? null),
140
+ payload: (r.payload ?? {}),
120
141
  });
121
142
  return toRefundRow(row);
122
143
  }
@@ -124,6 +145,10 @@ export class RefundIntentRepository {
124
145
  const r = await this.orm.where({ id }).first();
125
146
  return r ? toRefundRow(r) : null;
126
147
  }
148
+ async getByTxHash(txHash) {
149
+ const r = await this.orm.where({ txHash }).first();
150
+ return r ? toRefundRow(r) : null;
151
+ }
127
152
  async listByPayment(paymentId) {
128
153
  const rows = await this.orm
129
154
  .orderBy((e) => e.createdAtMs.desc())
@@ -134,18 +159,31 @@ export class RefundIntentRepository {
134
159
  async list(opts = {}) {
135
160
  const q = this.orm.orderBy((e) => e.createdAtMs.desc());
136
161
  const scoped = opts.status !== undefined ? q.where({ status: opts.status }) : q;
137
- const rows = opts.limit !== undefined
138
- ? await scoped.limit(opts.limit).all()
139
- : await scoped.all();
140
- return rows.map(toRefundRow);
162
+ let rows = (await scoped.all())
163
+ .map(toRefundRow)
164
+ .filter((r) => (opts.completedSinceMs === undefined ||
165
+ (r.completedAtMs ?? 0) >= opts.completedSinceMs) &&
166
+ (opts.completedUntilMs === undefined ||
167
+ (r.completedAtMs ?? 0) <= opts.completedUntilMs));
168
+ if (opts.limit !== undefined)
169
+ rows = rows.slice(0, opts.limit);
170
+ return rows;
141
171
  }
142
172
  async complete(id, txHash, completedBy, completedAtMs) {
143
- const row = await this.orm.where({ id, status: "OPEN" }).update({
144
- status: "COMPLETED",
145
- txHash,
146
- completedBy,
147
- completedAtMs: BigInt(completedAtMs),
148
- });
173
+ let row;
174
+ try {
175
+ row = await this.orm.where({ id, status: "OPEN" }).update({
176
+ status: "COMPLETED",
177
+ txHash,
178
+ completedBy,
179
+ completedAtMs: BigInt(completedAtMs),
180
+ });
181
+ }
182
+ catch (e) {
183
+ if (isUniqueViolation(e))
184
+ return null;
185
+ throw e;
186
+ }
149
187
  return row ? toRefundRow(row) : null;
150
188
  }
151
189
  }
@@ -1,5 +1,5 @@
1
1
  import type { JsonValue } from "@prisma/orm-postgres/target/codec-types";
2
- export declare const ADMIN_ACTIONS: readonly ["REVIEW", "RETRY_VERIFY", "MARK_EXTERNAL_REVIEWED", "REFUND", "RESOLVE_EXCEPTION"];
2
+ export declare const ADMIN_ACTIONS: readonly ["REVIEW", "RETRY_VERIFY", "MARK_EXTERNAL_REVIEWED", "REFUND", "RESOLVE_EXCEPTION", "DETECT_EXCEPTIONS"];
3
3
  export type AdminActionKind = (typeof ADMIN_ACTIONS)[number];
4
4
  export interface AdminActionInsert {
5
5
  id: string;
@@ -48,10 +48,13 @@ export interface RefundIntentRow extends RefundIntentInsert {
48
48
  export interface RefundIntentStore {
49
49
  create(r: RefundIntentInsert): Promise<RefundIntentRow | null>;
50
50
  getById(id: string): Promise<RefundIntentRow | null>;
51
+ getByTxHash(txHash: string): Promise<RefundIntentRow | null>;
51
52
  listByPayment(paymentId: string): Promise<RefundIntentRow[]>;
52
53
  list(opts?: {
53
54
  status?: string;
54
55
  limit?: number;
56
+ completedSinceMs?: number;
57
+ completedUntilMs?: number;
55
58
  }): Promise<RefundIntentRow[]>;
56
59
  complete(id: string, txHash: string, completedBy: string, completedAtMs: number): Promise<RefundIntentRow | null>;
57
60
  }
@@ -107,10 +110,13 @@ export declare class InMemoryRefundIntentStore implements RefundIntentStore {
107
110
  private readonly rows;
108
111
  create(r: RefundIntentInsert): Promise<RefundIntentRow | null>;
109
112
  getById(id: string): Promise<RefundIntentRow | null>;
113
+ getByTxHash(txHash: string): Promise<RefundIntentRow | null>;
110
114
  listByPayment(paymentId: string): Promise<RefundIntentRow[]>;
111
115
  list(opts?: {
112
116
  status?: string;
113
117
  limit?: number;
118
+ completedSinceMs?: number;
119
+ completedUntilMs?: number;
114
120
  }): Promise<RefundIntentRow[]>;
115
121
  complete(id: string, txHash: string, completedBy: string, completedAtMs: number): Promise<RefundIntentRow | null>;
116
122
  }
@@ -4,6 +4,7 @@ export const ADMIN_ACTIONS = [
4
4
  "MARK_EXTERNAL_REVIEWED",
5
5
  "REFUND",
6
6
  "RESOLVE_EXCEPTION",
7
+ "DETECT_EXCEPTIONS",
7
8
  ];
8
9
  export const RECONCILIATION_EXCEPTION_TYPES = [
9
10
  "AMOUNT_MISMATCH",
@@ -71,13 +72,24 @@ export class InMemoryRefundIntentStore {
71
72
  async getById(id) {
72
73
  return this.rows.get(id) ?? null;
73
74
  }
75
+ async getByTxHash(txHash) {
76
+ for (const r of this.rows.values()) {
77
+ if (r.txHash === txHash)
78
+ return r;
79
+ }
80
+ return null;
81
+ }
74
82
  async listByPayment(paymentId) {
75
83
  return [...this.rows.values()]
76
84
  .filter((r) => r.paymentId === paymentId)
77
85
  .sort((a, b) => b.createdAtMs - a.createdAtMs);
78
86
  }
79
87
  async list(opts = {}) {
80
- let out = [...this.rows.values()].filter((r) => opts.status === undefined || r.status === opts.status);
88
+ let out = [...this.rows.values()].filter((r) => (opts.status === undefined || r.status === opts.status) &&
89
+ (opts.completedSinceMs === undefined ||
90
+ (r.completedAtMs ?? 0) >= opts.completedSinceMs) &&
91
+ (opts.completedUntilMs === undefined ||
92
+ (r.completedAtMs ?? 0) <= opts.completedUntilMs));
81
93
  out.sort((a, b) => b.createdAtMs - a.createdAtMs);
82
94
  if (opts.limit !== undefined)
83
95
  out = out.slice(0, opts.limit);
@@ -87,6 +99,10 @@ export class InMemoryRefundIntentStore {
87
99
  const row = this.rows.get(id);
88
100
  if (!row || row.status !== "OPEN")
89
101
  return null;
102
+ for (const r of this.rows.values()) {
103
+ if (r.id !== id && r.txHash === txHash)
104
+ return null;
105
+ }
90
106
  const next = {
91
107
  ...row,
92
108
  status: "COMPLETED",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentbadge/database",
3
- "version": "0.6.14",
3
+ "version": "0.6.16",
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",