@dvmkit/dvm-cli 0.4.0 → 0.4.2

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.
package/README.md CHANGED
@@ -11,7 +11,7 @@ dvm init
11
11
 
12
12
  If the earlier `@dvmkit/cli` package is installed globally, remove it first with `npm uninstall --global @dvmkit/cli` and then install `@dvmkit/dvm-cli`, because both packages declare the same `dvm` binary.
13
13
 
14
- The bundled agent skill is exported as `@dvmkit/dvm-cli/skill`. Documentation lives at [dvmkit.ai](https://dvmkit.ai).
14
+ The bundled agent skill is exported as `@dvmkit/dvm-cli/skill`. That export resolves its entry file; copy the whole containing directory into your agent's skill directory so its calling, wallet, credit, and recovery procedures are available too. Keep the skill and CLI on the same package version. The [agent setup guide](https://dvmkit.com/docs/agent-setup) has installation commands for supported harnesses.
15
15
 
16
16
  ## Community
17
17
 
@@ -4279,7 +4279,7 @@ var schnorr = /* @__PURE__ */ (() => {
4279
4279
  };
4280
4280
  })();
4281
4281
 
4282
- // node_modules/@dvmkit/sdk/dist/chunk-CGKZDODG.js
4282
+ // node_modules/@dvmkit/sdk/dist/chunk-MG67KXU7.js
4283
4283
  var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
4284
4284
  import {
4285
4285
  appendFileSync,
@@ -4299,7 +4299,6 @@ var PROTECTED_CONFIG_FIELDS = ["nwcUri", "defaultIdentity", "tempo", "x402"];
4299
4299
  var ProtectedFieldAuthorization = class {
4300
4300
  /** Targets this authorization covers. A field also covers its own leaves. */
4301
4301
  targets;
4302
- /** Prefer {@link authorizeProtectedRemoval}; this exists for it to call. */
4303
4302
  constructor(targets) {
4304
4303
  this.targets = [...targets];
4305
4304
  }
@@ -4573,11 +4572,7 @@ function protectedRemovalError(targets, reason) {
4573
4572
  }
4574
4573
  var PROTECTED_FIELDS = {
4575
4574
  nwcUri: { aliases: [], credentialLeaves: [], secret: true, hexCredential: false },
4576
- // A pointer at a key, not a key: worth protecting from removal, and never
4577
- // worth stripping out of a stored copy — that is recovery lost for nothing.
4578
4575
  defaultIdentity: { aliases: [], credentialLeaves: [], secret: false, hexCredential: false },
4579
- // `mpp` is the pre-internal-review name; a caller who has not run a mutating command
4580
- // since the rename still has their private key under it.
4581
4576
  tempo: { aliases: ["mpp"], credentialLeaves: ["apiKey"], secret: true, hexCredential: true },
4582
4577
  x402: { aliases: [], credentialLeaves: ["privateKey"], secret: true, hexCredential: true }
4583
4578
  };
@@ -2,10 +2,11 @@
2
2
  import { createRequire as __dvmCreateRequire } from "node:module";
3
3
  const require = __dvmCreateRequire(import.meta.url);
4
4
  import {
5
+ diagnosticConsole,
5
6
  withSdkInitLock
6
- } from "./chunk-3SWX5BQP.js";
7
+ } from "./chunk-PRN4FHDY.js";
7
8
 
8
- // node_modules/@dvmkit/sdk/dist/chunk-6BQM7TOW.js
9
+ // node_modules/@dvmkit/sdk/dist/chunk-Y7JZLO5J.js
9
10
  import { createHash, randomUUID } from "crypto";
10
11
  var MemoryX402BatchStore = class {
11
12
  batches = /* @__PURE__ */ new Map();
@@ -38,7 +39,6 @@ var PostgresX402BatchStore = class {
38
39
  this.db = db;
39
40
  }
40
41
  db;
41
- /** Create the table (idempotent), under the SDK init lock like every other boot DDL. */
42
42
  async init() {
43
43
  await withSdkInitLock(this.db, async () => {
44
44
  await this.db.query(`
@@ -158,7 +158,6 @@ var PayoutReporter = class {
158
158
  this.intervalMs = opts.snapshotIntervalMs ?? PAYOUT_SNAPSHOT_INTERVAL_MS;
159
159
  this.now = opts.now ?? Date.now;
160
160
  }
161
- /** Boot DDL for the durable batch store, when this reporter owns one. */
162
161
  async init() {
163
162
  if (this.ownsBatchStore && this.batches instanceof PostgresX402BatchStore) {
164
163
  await this.batches.init();
@@ -203,8 +202,6 @@ var PayoutReporter = class {
203
202
  warn("payout_flush_failed", { error: message(err) });
204
203
  }
205
204
  }
206
- // ── cashu ─────────────────────────────────────────────────────────────
207
- /** The hook `mark-melted` runs inside its transaction: the mark and its payout commit together. */
208
205
  meltHook() {
209
206
  return {
210
207
  enqueue: (event, tx) => this.cashuMelted(event, tx),
@@ -215,17 +212,9 @@ var PayoutReporter = class {
215
212
  };
216
213
  }
217
214
  /**
218
- * A melt completed: the accumulator rows are SPENT at the mint and the
219
- * Lightning payment reached the builder's destination. One payout per mint
220
- * in the call — a `mark-melted` normally names one, since a melt quote
221
- * belongs to one mint. The amount is the face value melted; the mint's fee
222
- * and the Lightning amount received are builder-machine facts this DVM does
223
- * not see.
224
- *
225
- * Queued through `tx` when the caller is inside the transaction that marks
226
- * the rows, and a failure is thrown rather than swallowed so that mark rolls
227
- * back with it — see {@link TransactionalPayoutHook}. Without `tx` the rows
228
- * are queued on their own and delivered at once.
215
+ * Report melted face value per mint, not the Lightning amount received after fees. Hash the
216
+ * payment preimage; do not publish it. With tx, propagate enqueue failures and defer
217
+ * delivery until commit. Without tx, enqueue independently and start delivery.
229
218
  */
230
219
  async cashuMelted(event, tx) {
231
220
  const byMint = /* @__PURE__ */ new Map();
@@ -265,8 +254,6 @@ var PayoutReporter = class {
265
254
  void this.snapshotCashu();
266
255
  }
267
256
  }
268
- // ── tempo ─────────────────────────────────────────────────────────────
269
- /** The host attaches the session store and ledger readers once they exist. */
270
257
  attachTempo(reader) {
271
258
  this.tempo = reader;
272
259
  }
@@ -299,7 +286,6 @@ var PayoutReporter = class {
299
286
  }
300
287
  void this.snapshotTempo();
301
288
  }
302
- /** The hook `reconcile-tempo-drain` runs inside its transaction: the booking and its payout commit together. */
303
289
  tempoRepairHook() {
304
290
  return {
305
291
  enqueue: (event, tx) => this.tempoCloseReconciled(event, tx),
@@ -310,14 +296,9 @@ var PayoutReporter = class {
310
296
  };
311
297
  }
312
298
  /**
313
- * The operator repaired a wedged cooperative close (internal-review). The close's
314
- * payee side landed on chain when the close did; if the live hook reported
315
- * it, this upgrades that row to `repair`, otherwise it is the row. The
316
- * figure is the receipt's payee total for the channel.
317
- *
318
- * Queued through `tx` when the caller is inside the transaction that books
319
- * the drain, and thrown rather than swallowed so that booking rolls back
320
- * with it — see {@link TransactionalPayoutHook}.
299
+ * Report the receipt’s payee total under the live close’s transaction ID, flagged repaired.
300
+ * The platform upgrades a live row if one exists. Join tx and propagate enqueue failures;
301
+ * this does not report the caller refund.
321
302
  */
322
303
  async tempoCloseReconciled(event, tx) {
323
304
  const settled = BigInt(event.settledToPayee);
@@ -348,8 +329,6 @@ var PayoutReporter = class {
348
329
  void this.snapshotTempo();
349
330
  }
350
331
  }
351
- // ── x402 ──────────────────────────────────────────────────────────────
352
- /** The observer the batch-settlement server attaches to and routes its manager through. */
353
332
  x402Observer() {
354
333
  return {
355
334
  attach: (ctx) => {
@@ -369,13 +348,9 @@ var PayoutReporter = class {
369
348
  };
370
349
  }
371
350
  /**
372
- * Wrap the upstream channel manager so every claim grows the open batch and
373
- * every settle closes it. The claim delta is read off storage rather than
374
- * off upstream's result, which carries only a voucher count; under the
375
- * fleet lock the before/after read is consistent. A channel the claim
376
- * removed on its way through — a refund's claim-then-delete (internal-review) —
377
- * moved whatever it still owed before it went, and that value reaches
378
- * `pay_to` in this batch too, so it counts at its pre-claim figure.
351
+ * Read claim deltas from storage because upstream returns voucher counts. Under the fleet
352
+ * lock, before/after reads are consistent. A deleted channel contributes its pre-claim
353
+ * unclaimed value, including refund claim-then-delete.
379
354
  */
380
355
  trackX402Manager(manager) {
381
356
  const claim = async (...args) => {
@@ -505,7 +480,6 @@ var PayoutReporter = class {
505
480
  warn("payout_batch_track_failed", { scope: ctx.scope, error: message(trackErr) });
506
481
  }
507
482
  }
508
- // ── snapshots ─────────────────────────────────────────────────────────
509
483
  /** Every rail this reporter can read, each on its own failure boundary. */
510
484
  async snapshot() {
511
485
  await this.snapshotCashu();
@@ -642,7 +616,7 @@ var PayoutReporter = class {
642
616
  /**
643
617
  * Tempo: each active channel's spent-but-unsettled balance — earned, not
644
618
  * yet paid to the recipient — and the cooperative closes wedged between
645
- * chain and ledger (internal-review), aged past the same floor the repair queue
619
+ * chain and ledger, aged past the same floor the repair queue
646
620
  * uses so an in-flight close is not reported as stuck.
647
621
  */
648
622
  async snapshotTempo() {
@@ -749,7 +723,7 @@ function message(err) {
749
723
  return err instanceof Error ? err.message : String(err);
750
724
  }
751
725
  function warn(level, fields) {
752
- console.warn(JSON.stringify({ level, ...fields }));
726
+ diagnosticConsole.warn({ level, ...fields });
753
727
  }
754
728
 
755
729
  export {
@@ -2,12 +2,14 @@
2
2
  import { createRequire as __dvmCreateRequire } from "node:module";
3
3
  const require = __dvmCreateRequire(import.meta.url);
4
4
  import {
5
+ diagnosticConsole,
5
6
  withSdkInitLock
6
- } from "./chunk-3SWX5BQP.js";
7
+ } from "./chunk-PRN4FHDY.js";
7
8
 
8
- // node_modules/@dvmkit/sdk/dist/chunk-EVBK675R.js
9
+ // node_modules/@dvmkit/sdk/dist/chunk-LHN75BTX.js
9
10
  import { randomUUID } from "crypto";
10
11
  var ENDPOINTS = {
12
+ job_terminal: "/_internal/job-terminal",
11
13
  revenue: "/_internal/job-revenue",
12
14
  cost: "/_internal/job-cost",
13
15
  deposit: "/_internal/credit-deposit",
@@ -54,7 +56,6 @@ var RevenueReporter = class _RevenueReporter {
54
56
  async init() {
55
57
  await withSdkInitLock(this.db, () => this.createTables());
56
58
  }
57
- /** The boot DDL itself — always runs under {@link withSdkInitLock} (internal-review). */
58
59
  async createTables() {
59
60
  await this.db.query(`
60
61
  CREATE TABLE IF NOT EXISTS ${PENDING_DVM_REPORTS_TABLE} (
@@ -68,6 +69,10 @@ var RevenueReporter = class _RevenueReporter {
68
69
  kind TEXT NOT NULL DEFAULT 'revenue'
69
70
  )
70
71
  `);
72
+ await this.db.query(`CREATE TABLE IF NOT EXISTS reported_job_terminals (
73
+ dvm_id TEXT NOT NULL, job_id TEXT NOT NULL, created_at BIGINT NOT NULL,
74
+ PRIMARY KEY (dvm_id, job_id)
75
+ )`);
71
76
  await this.assertSdkTableShape(PENDING_DVM_REPORTS_TABLE);
72
77
  await this.db.query(
73
78
  `ALTER TABLE ${PENDING_DVM_REPORTS_TABLE} ADD COLUMN IF NOT EXISTS stale_reason TEXT`
@@ -77,7 +82,6 @@ var RevenueReporter = class _RevenueReporter {
77
82
  );
78
83
  await this.migrateLegacySdkOutbox();
79
84
  }
80
- /** Copy rows from the old SDK-owned table without touching the platform's table of that name. */
81
85
  async migrateLegacySdkOutbox() {
82
86
  const columns = await this.tableColumns(LEGACY_PENDING_REPORTS_TABLE);
83
87
  if (columns.size === 0) return;
@@ -109,7 +113,6 @@ var RevenueReporter = class _RevenueReporter {
109
113
  )
110
114
  `);
111
115
  }
112
- /** Refuse a pre-existing relation whose columns cannot safely serve as the SDK outbox. */
113
116
  async assertSdkTableShape(tableName) {
114
117
  this.assertSdkColumns(tableName, await this.tableColumns(tableName));
115
118
  }
@@ -133,6 +136,21 @@ var RevenueReporter = class _RevenueReporter {
133
136
  async report(payload) {
134
137
  return this.enqueue("revenue", payload, payload.jobId);
135
138
  }
139
+ /** The permanent deduplication claim and outbox insert commit together.
140
+ * The claim survives successful delivery, including for custom job stores.
141
+ */
142
+ async reportTerminal(payload) {
143
+ const id = randomUUID();
144
+ const { rowCount } = await this.db.query(
145
+ `WITH claimed AS (
146
+ INSERT INTO reported_job_terminals (dvm_id, job_id, created_at)
147
+ VALUES ($5, $1, $4) ON CONFLICT DO NOTHING RETURNING job_id
148
+ ) INSERT INTO ${PENDING_DVM_REPORTS_TABLE} (id, payload, created_at, kind)
149
+ SELECT $2, $3::jsonb, $4, 'job_terminal' FROM claimed`,
150
+ [payload.jobId, id, JSON.stringify(payload), Date.now(), payload.dvmId]
151
+ );
152
+ if (rowCount) void this.attemptDelivery(id, payload, "job_terminal", payload.jobId).catch(() => void 0);
153
+ }
136
154
  /** Persist a zero-revenue job cost and attempt immediate delivery. */
137
155
  async reportCost(payload) {
138
156
  return this.enqueue("cost", payload, payload.jobId);
@@ -152,23 +170,15 @@ var RevenueReporter = class _RevenueReporter {
152
170
  await this.insertPending(tx, "release", payload);
153
171
  }
154
172
  /**
155
- * Join a credit drain to the transaction that made it terminal (internal-review).
156
- *
157
- * Same discipline as {@link enqueueDeposit} and the same reason: no network
158
- * I/O here, only the durable queue row, written through `tx` so the report
159
- * and the status CAS commit or roll back together. A drain whose row was
160
- * lost between the two would overstate outstanding liability forever —
161
- * the mirror image of a lost deposit.
162
- *
163
- * Named for the payload rather than the verb because `drain` already means
164
- * "flush the queue" in this class (see {@link drainPending}).
173
+ * Await durable queue insertion through tx so the terminal drain and its
174
+ * report commit or roll back together; no network I/O here.
165
175
  */
166
176
  async enqueueCreditDrain(tx, payload) {
167
177
  await this.insertPending(tx, "drain", payload);
168
178
  }
169
179
  /**
170
180
  * Join a payout to the transaction that commits the movement it reports
171
- * (internal-review) — the batch close, the accumulator mark, the drain booking.
181
+ * the batch close, the accumulator mark, the drain booking.
172
182
  * No network I/O, only the durable queue row through `tx`, the discipline
173
183
  * {@link enqueueCreditDrain} set and for the same reason: the money has
174
184
  * already moved on a rail this ledger does not own, so the platform row is
@@ -190,7 +200,7 @@ var RevenueReporter = class _RevenueReporter {
190
200
  return this.enqueue("payout", payload, payload.payoutId);
191
201
  }
192
202
  /**
193
- * Report one rail's pending-pool snapshot (internal-review). Best-effort and
203
+ * Report one rail's pending-pool snapshot. Best-effort and
194
204
  * fire-and-forget, deliberately unlike {@link reportPayout}: a snapshot is
195
205
  * replaced by the next tick, so queueing a stale one behind an outage would
196
206
  * only deliver figures the platform already has newer ones for.
@@ -208,39 +218,33 @@ var RevenueReporter = class _RevenueReporter {
208
218
  signal: AbortSignal.timeout(1e4)
209
219
  });
210
220
  if (!res.ok) {
211
- console.warn(
212
- JSON.stringify({
221
+ diagnosticConsole.warn(
222
+ {
213
223
  level: "payout_pending_report_failed",
214
224
  rail: payload.rail,
215
225
  status: res.status
216
- })
226
+ }
217
227
  );
218
228
  }
219
- } catch (err) {
220
- console.warn(
221
- JSON.stringify({
229
+ } catch (_err) {
230
+ diagnosticConsole.warn(
231
+ {
222
232
  level: "payout_pending_report_failed",
223
233
  rail: payload.rail,
224
- error: err instanceof Error ? err.message : String(err)
225
- })
234
+ error: void 0
235
+ }
226
236
  );
227
237
  }
228
238
  }
229
239
  /**
230
- * Join a credit-expiry release — or the revival that reverses one — to the
231
- * transaction that made it true (internal-review).
232
- *
233
- * Same discipline as {@link enqueueCreditDrain}: no network I/O, only the
234
- * durable queue row written through `tx`. A release whose row was lost after
235
- * the sweep committed would understate committed value forever; a lost
236
- * reversal would overstate it, which is the worse direction — the builder
237
- * would see money as theirs that a revived credit can still buy work with.
240
+ * Await durable queue insertion through tx so expiry release or reversal and
241
+ * its report commit together. A missing reversal would overstate builder value.
238
242
  */
239
243
  async enqueueCreditExpiryRelease(tx, payload) {
240
244
  await this.insertPending(tx, "expiry_release", payload);
241
245
  }
242
246
  /**
243
- * Report a reaper-force-failed paid job to the platform (internal-review) so the
247
+ * Report a reaper-force-failed paid job to the platform so the
244
248
  * operator receives an ambient notice that a DVM died or wedged mid-job.
245
249
  * Best-effort and fire-and-forget: unlike {@link report} there is no local
246
250
  * durable queue — a non-2xx or transport failure is structured-logged
@@ -261,26 +265,26 @@ var RevenueReporter = class _RevenueReporter {
261
265
  signal: AbortSignal.timeout(1e4)
262
266
  });
263
267
  if (!res.ok) {
264
- console.warn(
265
- JSON.stringify({
268
+ diagnosticConsole.warn(
269
+ {
266
270
  level: "paid_job_death_report_failed",
267
271
  jobId: payload.jobId,
268
272
  status: res.status
269
- })
273
+ }
270
274
  );
271
275
  }
272
- } catch (err) {
273
- console.warn(
274
- JSON.stringify({
276
+ } catch (_err) {
277
+ diagnosticConsole.warn(
278
+ {
275
279
  level: "paid_job_death_report_failed",
276
280
  jobId: payload.jobId,
277
- error: err instanceof Error ? err.message : String(err)
278
- })
281
+ error: void 0
282
+ }
279
283
  );
280
284
  }
281
285
  }
282
286
  /**
283
- * Report a settled draw whose revenue event was skipped (internal-review).
287
+ * Report a settled draw whose revenue event was skipped.
284
288
  * Best-effort and fire-and-forget: the SDK's structured
285
289
  * `revenue_skipped_no_rail` log is the durable backstop, so a failed notice
286
290
  * must never wedge terminal handling or the orphan-draw reconciler.
@@ -298,29 +302,28 @@ var RevenueReporter = class _RevenueReporter {
298
302
  signal: AbortSignal.timeout(1e4)
299
303
  });
300
304
  if (!res.ok) {
301
- console.warn(
302
- JSON.stringify({
305
+ diagnosticConsole.warn(
306
+ {
303
307
  level: "revenue_skipped_no_rail_report_failed",
304
308
  jobId: payload.jobId,
305
309
  drawId: payload.drawId,
306
310
  reason: payload.reason,
307
311
  status: res.status
308
- })
312
+ }
309
313
  );
310
314
  }
311
- } catch (err) {
312
- console.warn(
313
- JSON.stringify({
315
+ } catch (_err) {
316
+ diagnosticConsole.warn(
317
+ {
314
318
  level: "revenue_skipped_no_rail_report_failed",
315
319
  jobId: payload.jobId,
316
320
  drawId: payload.drawId,
317
321
  reason: payload.reason,
318
- error: err instanceof Error ? err.message : String(err)
319
- })
322
+ error: void 0
323
+ }
320
324
  );
321
325
  }
322
326
  }
323
- /** Report the self-relay's Base gas gauge for platform-side paging and recovery. */
324
327
  async reportX402SelfRelayGasBalance(payload) {
325
328
  const url = `${this.platformUrl}/_internal/x402-self-relay-gas-balance`;
326
329
  try {
@@ -334,25 +337,24 @@ var RevenueReporter = class _RevenueReporter {
334
337
  signal: AbortSignal.timeout(1e4)
335
338
  });
336
339
  if (!res.ok) {
337
- console.warn(
338
- JSON.stringify({
340
+ diagnosticConsole.warn(
341
+ {
339
342
  level: "x402_self_relay_gas_balance_report_failed",
340
343
  address: payload.address,
341
344
  status: res.status
342
- })
345
+ }
343
346
  );
344
347
  }
345
- } catch (err) {
346
- console.warn(
347
- JSON.stringify({
348
+ } catch (_err) {
349
+ diagnosticConsole.warn(
350
+ {
348
351
  level: "x402_self_relay_gas_balance_report_failed",
349
352
  address: payload.address,
350
- error: err instanceof Error ? err.message : String(err)
351
- })
353
+ error: void 0
354
+ }
352
355
  );
353
356
  }
354
357
  }
355
- /** Report redacted self-relay RPC health for platform-side paging and recovery. */
356
358
  async reportX402SelfRelayRpcHealth(payload) {
357
359
  const url = `${this.platformUrl}/_internal/x402-self-relay-rpc-health`;
358
360
  try {
@@ -366,29 +368,27 @@ var RevenueReporter = class _RevenueReporter {
366
368
  signal: AbortSignal.timeout(1e4)
367
369
  });
368
370
  if (!res.ok) {
369
- console.warn(
370
- JSON.stringify({
371
+ diagnosticConsole.warn(
372
+ {
371
373
  level: "x402_self_relay_rpc_health_report_failed",
372
374
  address: payload.address,
373
375
  status: res.status
374
- })
376
+ }
375
377
  );
376
378
  }
377
379
  } catch {
378
- console.warn(
379
- JSON.stringify({
380
+ diagnosticConsole.warn(
381
+ {
380
382
  level: "x402_self_relay_rpc_health_report_failed",
381
383
  address: payload.address,
382
384
  reason: "transport"
383
- })
385
+ }
384
386
  );
385
387
  }
386
388
  }
387
- /** Report the Tempo operator's fee-token gauge for paging and recovery. */
388
389
  async reportTempoSettlementBalance(payload) {
389
390
  await this.postTempoSettlementReadiness("balance", payload);
390
391
  }
391
- /** Report a redacted operator fee rejection immediately. */
392
392
  async reportTempoSettlementFailure(payload) {
393
393
  await this.postTempoSettlementReadiness("failure", payload);
394
394
  }
@@ -405,34 +405,32 @@ var RevenueReporter = class _RevenueReporter {
405
405
  signal: AbortSignal.timeout(1e4)
406
406
  });
407
407
  if (!res.ok) {
408
- console.warn(
409
- JSON.stringify({
408
+ diagnosticConsole.warn(
409
+ {
410
410
  level: "tempo_settlement_readiness_report_failed",
411
411
  kind,
412
412
  address: payload.address,
413
413
  status: res.status
414
- })
414
+ }
415
415
  );
416
416
  }
417
417
  } catch {
418
- console.warn(
419
- JSON.stringify({
418
+ diagnosticConsole.warn(
419
+ {
420
420
  level: "tempo_settlement_readiness_report_failed",
421
421
  kind,
422
422
  address: payload.address,
423
423
  reason: "transport"
424
- })
424
+ }
425
425
  );
426
426
  }
427
427
  }
428
- /** Start the background retry loop. */
429
428
  startRetryLoop() {
430
429
  if (this.retryTimer) return;
431
430
  this.retryTimer = setInterval(() => {
432
431
  void this.drainPending();
433
432
  }, _RevenueReporter.RETRY_INTERVAL_MS);
434
433
  }
435
- /** Stop the background retry loop. */
436
434
  stop() {
437
435
  if (this.retryTimer) {
438
436
  clearInterval(this.retryTimer);
@@ -469,8 +467,8 @@ var RevenueReporter = class _RevenueReporter {
469
467
  /**
470
468
  * Deliver one bounded batch from the durable queue.
471
469
  *
472
- * Public so startup/recovery tests and operator tooling can drive the same
473
- * drain the background timer uses without reaching into private state.
470
+ * Processes due, non-stale rows; failures back off up to five minutes and
471
+ * become terminal after 24 hours. Successful deliveries remove their rows.
474
472
  */
475
473
  async drainPending() {
476
474
  try {
@@ -488,8 +486,8 @@ var RevenueReporter = class _RevenueReporter {
488
486
  const retryCount = row.retry_count + 1;
489
487
  if (Date.now() - Number(row.created_at) >= _RevenueReporter.ABANDON_AFTER_MS) {
490
488
  await this.markStale(row.id, "abandoned");
491
- console.warn(
492
- JSON.stringify({
489
+ diagnosticConsole.warn(
490
+ {
493
491
  level: "revenue_reporter_abandoned",
494
492
  id: row.id,
495
493
  kind: row.kind,
@@ -500,7 +498,7 @@ var RevenueReporter = class _RevenueReporter {
500
498
  // carries `rail`. An abandoned row is the one place an
501
499
  // operator sees this payload at all, so don't log it blank.
502
500
  rail: row.payload.rail ?? row.payload.method
503
- })
501
+ }
504
502
  );
505
503
  continue;
506
504
  }
@@ -517,16 +515,14 @@ var RevenueReporter = class _RevenueReporter {
517
515
  }
518
516
  }
519
517
  } catch (err) {
520
- console.error("[revenue-reporter] Retry loop error:", err);
518
+ diagnosticConsole.error("[revenue-reporter] Retry loop error:", err);
521
519
  }
522
520
  }
523
- /** Durably queue one report of either kind, then try it once immediately. */
524
521
  async enqueue(kind, payload, label) {
525
522
  const id = await this.insertPending(this.db, kind, payload);
526
523
  void this.attemptDelivery(id, payload, kind, label).catch(() => {
527
524
  });
528
525
  }
529
- /** Insert one pending report through either the pool or an open transaction. */
530
526
  async insertPending(q, kind, payload) {
531
527
  const id = randomUUID();
532
528
  await q.query(
@@ -551,34 +547,33 @@ var RevenueReporter = class _RevenueReporter {
551
547
  });
552
548
  } catch (err) {
553
549
  const reason = err instanceof Error ? err.message : String(err);
554
- console.warn(
550
+ diagnosticConsole.warn(
555
551
  `[revenue-reporter] delivery failed for ${id}: transport error (${reason}) \u2014 will retry`
556
552
  );
557
553
  throw err;
558
554
  }
559
555
  if (res.ok) {
560
556
  await this.db.query(`DELETE FROM ${PENDING_DVM_REPORTS_TABLE} WHERE id = $1`, [id]);
561
- console.log(`[revenue-reporter] reported ${kind} ${label}`);
557
+ diagnosticConsole.log(`[revenue-reporter] reported ${kind} ${label}`);
562
558
  return;
563
559
  }
564
560
  if (res.status === 401) {
565
561
  await this.markStale(id, "token_rotated");
566
- console.warn(
562
+ diagnosticConsole.warn(
567
563
  `[revenue-reporter] Report ${id} got 401 \u2014 marking stale (token likely rotated)`
568
564
  );
569
565
  return;
570
566
  }
571
567
  if (res.status >= 400 && res.status < 500) {
572
568
  await this.markStale(id, `client_error:${res.status}`);
573
- console.warn(
569
+ diagnosticConsole.warn(
574
570
  `[revenue-reporter] Report ${id} got HTTP ${res.status} \u2014 marking stale (permanent client error, will not retry)`
575
571
  );
576
572
  return;
577
573
  }
578
- console.warn(`[revenue-reporter] delivery failed for ${id}: HTTP ${res.status} \u2014 will retry`);
574
+ diagnosticConsole.warn(`[revenue-reporter] delivery failed for ${id}: HTTP ${res.status} \u2014 will retry`);
579
575
  throw new Error(`Platform returned ${res.status}`);
580
576
  }
581
- /** Mark a pending row terminal (stale) with a classification reason. */
582
577
  async markStale(id, reason) {
583
578
  await this.db.query(
584
579
  `UPDATE ${PENDING_DVM_REPORTS_TABLE} SET stale = true, stale_reason = $1 WHERE id = $2`,