@lunora/observability 1.0.0-alpha.2 → 1.0.0-alpha.200

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 (43) hide show
  1. package/README.md +2 -4
  2. package/dist/index.d.mts +1021 -386
  3. package/dist/index.d.ts +1021 -386
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/AUTH_METRICS_BUCKETS_TABLE-BpH1ZAgX.mjs +22 -0
  6. package/dist/packem_shared/DEFAULT_EXPLAIN_ISSUE_MODEL-BkFTgdkd.mjs +3 -0
  7. package/dist/packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-Dha-40Hv.mjs +56 -0
  8. package/dist/packem_shared/ISSUE_SEVERITIES-0SJ0glV4.mjs +15 -0
  9. package/dist/packem_shared/LogBuffer-BmD4CfV0.mjs +1 -0
  10. package/dist/packem_shared/MIN_ADMIN_TOKEN_LENGTH-DSOQ6rno.mjs +1 -0
  11. package/dist/packem_shared/MetricBuffer-BUw1hK3f.mjs +1 -0
  12. package/dist/packem_shared/NO_SENSITIVE_SCOPE-z-NXXakX.mjs +1 -0
  13. package/dist/packem_shared/SpanBuffer-C8-8zvYg.mjs +1 -0
  14. package/dist/packem_shared/applyHostRootSpan-DToRfMn8.mjs +1 -0
  15. package/dist/packem_shared/createDatabaseTally-BNj6kmo2.mjs +2 -0
  16. package/dist/packem_shared/createMetrics-C6AXtDTF.mjs +1 -0
  17. package/dist/packem_shared/findDanglingReferences-BaOyIdxz.mjs +1 -0
  18. package/dist/packem_shared/latencyBucketIndex--kZoW0vc.mjs +32 -0
  19. package/dist/packem_shared/otlp-DR7601NL.mjs +1 -0
  20. package/dist/packem_shared/prune-marker-CksedkkK.mjs +1 -0
  21. package/dist/packem_shared/readMetricHistory-BjPDSBkS.mjs +31 -0
  22. package/dist/packem_shared/request-log-B7gOe-_k.mjs +24 -0
  23. package/dist/packem_shared/resolveTraceAnchor-DDAPZRBB.mjs +1 -0
  24. package/dist/packem_shared/run-sql-0aPgJkIw.mjs +1 -0
  25. package/package.json +6 -5
  26. package/dist/packem_shared/AUTH_METRICS_BUCKETS_TABLE-C2V-DiGu.mjs +0 -22
  27. package/dist/packem_shared/DEFAULT_EXPLAIN_ISSUE_MODEL-xF11R4vX.mjs +0 -3
  28. package/dist/packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-B1U7xWMo.mjs +0 -56
  29. package/dist/packem_shared/ISSUE_SEVERITIES-Js6lGUG5.mjs +0 -15
  30. package/dist/packem_shared/LogBuffer-bIvCelI-.mjs +0 -1
  31. package/dist/packem_shared/MIN_ADMIN_TOKEN_LENGTH-T-zuwRVR.mjs +0 -1
  32. package/dist/packem_shared/MetricBuffer-CYrLuEsz.mjs +0 -1
  33. package/dist/packem_shared/REQUEST_LOG_TABLE-Q_BYgAzY.mjs +0 -20
  34. package/dist/packem_shared/SpanBuffer-BR6Ff0M-.mjs +0 -1
  35. package/dist/packem_shared/createDatabaseTally-BTqRpC0j.mjs +0 -1
  36. package/dist/packem_shared/createMetrics-fpVig63l.mjs +0 -1
  37. package/dist/packem_shared/findDanglingReferences-D-x9LvY0.mjs +0 -1
  38. package/dist/packem_shared/log-fields-d5ouN1Pe.mjs +0 -1
  39. package/dist/packem_shared/metric-buffer-CdgXal7w.mjs +0 -1
  40. package/dist/packem_shared/readMetricHistory-DtnhufUq.mjs +0 -31
  41. package/dist/packem_shared/readQueryInsights-CwSKB0I1.mjs +0 -32
  42. package/dist/packem_shared/resolveTraceAnchor-IAN8riI0.mjs +0 -1
  43. package/dist/packem_shared/trace-context-DrdF960P.mjs +0 -1
package/dist/index.d.mts CHANGED
@@ -64,9 +64,9 @@ declare const ensureAuthMetricsTables: (sql: SqlExec) => void;
64
64
  * `failures` advances only when `outcome === "fail"`. `since_ms` is set once on
65
65
  * the first attempt and never moved (so it stays a true first-seen marker).
66
66
  *
67
- * Exactly two `INSERT … ON CONFLICT … DO UPDATE` statements plus a bounded
68
- * `DELETE`, all keyed by primary key — cheap enough to fire off the auth
69
- * response path without blocking it.
67
+ * Exactly two `INSERT … ON CONFLICT … DO UPDATE` statements, all keyed by
68
+ * primary key, plus a bounded `DELETE` that runs once per bucket window —
69
+ * cheap enough to fire off the auth response path without blocking it.
70
70
  */
71
71
  declare const recordAuthEvent: (sql: SqlExec, input: RecordAuthEventInput) => void;
72
72
  /**
@@ -160,6 +160,20 @@ interface EvaluationInput {
160
160
  /** The numeric score (typically `[0, 1]`), emitted as the `.score` attribute. */
161
161
  score: number;
162
162
  }
163
+ /** The unredacted facts about a thrown value, for observability sinks only. */
164
+ interface ErrorDetail {
165
+ /** The `LunoraError` taxonomy code, when the thrown value carries one. */
166
+ code?: string;
167
+ /**
168
+ * The operator-only `internal` context of a `LunoraError`, when it is JSON-safe.
169
+ * Attached by the shard only on the detail header (see {@link describeInternal}),
170
+ * never by {@link describeError}, so it cannot leak into a log-event `error`.
171
+ */
172
+ internal?: Record<string, unknown>;
173
+ message: string;
174
+ name: string;
175
+ stack?: string;
176
+ }
163
177
  /**
164
178
  * Severity of a `ctx.log.*` call. The five console method names (`log` is the
165
179
  * default level, distinct from `info`) plus `trace`/`fatal`, so the logger spans
@@ -173,6 +187,14 @@ type ContextLogLevel = "debug" | "error" | "fatal" | "info" | "log" | "trace" |
173
187
  interface LogEvent {
174
188
  /** Raw arguments passed to the `ctx.log.*` call, in order. */
175
189
  args: unknown[];
190
+ /**
191
+ * The first `Error` the call was handed, as an argument
192
+ * (`ctx.log.error("failed", err)`) or a fields value (`{ err }`): its `name`,
193
+ * unredacted `message`, `stack`, and `code` when it carries one. Absent when
194
+ * the line logged no `Error`. An error tracker reads this rather than parsing
195
+ * the rendered `message`.
196
+ */
197
+ error?: ErrorDetail;
176
198
  /**
177
199
  * OTel `LogRecord.eventName` — set when the line was emitted as a **structured
178
200
  * event** via `ctx.log.event(name, fields)` rather than as a human-readable
@@ -200,6 +222,12 @@ interface LogEvent {
200
222
  level: ContextLogLevel;
201
223
  /** Display string — the message, or the console-style args rendered and space-joined. */
202
224
  message: string;
225
+ /**
226
+ * Cloudflare Ray ID of the request this line was emitted under (see
227
+ * `shared/ray-id.ts`) — search Cloudflare Traces by it. Absent off the edge
228
+ * and for dispatches no HTTP request started (an alarm, a subscription re-run).
229
+ */
230
+ rayId?: string;
203
231
  /** Shard key for single-shard calls; absent for the unnamed root DO. */
204
232
  shardKey?: string;
205
233
  /** Span id of the RPC this line was emitted under (trace correlation), or absent. */
@@ -320,10 +348,50 @@ interface SpanHandle {
320
348
  * `@opentelemetry/api` bridge parenting a third-party library's spans — to
321
349
  * reach around the API for it.
322
350
  */
323
- spanContext: () => {
324
- spanId: string;
325
- traceId: string;
326
- };
351
+ spanContext: () => SpanContextIds;
352
+ }
353
+ /**
354
+ * The W3C identity of one span, plus the trace's settled sampling verdict.
355
+ *
356
+ * `sampled` is the propagated head decision (absent means "no verdict reached
357
+ * this tier", which every consumer reads as keep). It rides alongside the ids
358
+ * because everything that needs the ids to announce this span downstream — a
359
+ * hand-built `traceparent`, the `@opentelemetry/api` bridge's `SpanContext` —
360
+ * needs the flag in the same breath, and announcing `sampled` on a trace that
361
+ * was sampled OUT is what leaves a collector holding the middle of a trace.
362
+ */
363
+ interface SpanContextIds {
364
+ /** The trace's settled W3C `sampled` verdict; absent when none was propagated. */
365
+ sampled?: boolean;
366
+ /** This span's id (16-hex). */
367
+ spanId: string;
368
+ /** The trace this span belongs to (32-hex). */
369
+ traceId: string;
370
+ }
371
+ /**
372
+ * Caller-supplied ids for one `ctx.trace` span, passed as the tracer's fourth
373
+ * argument.
374
+ *
375
+ * For adapters that must hand a span's identity to somebody else BEFORE the span
376
+ * body runs — the `@opentelemetry/api` bridge returns a `SpanContext`
377
+ * synchronously from `startSpan`, and a library builds a `traceparent` from it —
378
+ * so the id the adapter published is the id that reaches the collector rather
379
+ * than a phantom. `parentSpanId` overrides the enclosing span for the same
380
+ * reason: an adapter that tracks its own parent/child structure (OTel's
381
+ * `Context`) can express it without an ambient span stack.
382
+ *
383
+ * Not part of the ordinary `ctx.trace(name, fn, attributes)` call — a handler
384
+ * never mints its own ids.
385
+ *
386
+ * Both ids are required: an adapter that has published one has published the
387
+ * other, and `identity` is itself optional — omitting it, not passing a partial
388
+ * object, is how a caller says "no adapter involved".
389
+ */
390
+ interface SpanIdentity {
391
+ /** Parent to this span id instead of the enclosing `ctx.trace` / dispatch span. */
392
+ parentSpanId: string;
393
+ /** Record the span under this id (16-hex) instead of a freshly minted one. */
394
+ spanId: string;
327
395
  }
328
396
  /** Options accepted by `ctx.trace(name, fn, options)` beyond the plain attribute bag. */
329
397
  interface SpanOptions {
@@ -402,6 +470,24 @@ interface SpanEvent {
402
470
  * the outermost span, which is why the fold prefers it as a trace's anchor.
403
471
  */
404
472
  dispatch?: boolean;
473
+ /**
474
+ * Cloudflare Ray ID of the request this span ran under (see
475
+ * `shared/ray-id.ts`), exported as `cloudflare.ray_id`. Absent off the edge.
476
+ */
477
+ rayId?: string;
478
+ /**
479
+ * The trace's settled W3C `sampled` verdict, stamped as the span leaves for a
480
+ * sink. Absent means no verdict reached this tier, which every consumer reads
481
+ * as keep.
482
+ *
483
+ * Carried because the OTLP encoders write it into the span's `flags` field,
484
+ * and a span exported with no `flags` reads as UNSAMPLED (0) at the collector
485
+ * — on EVERY span, including the ones it is meant to keep. It is genuinely
486
+ * per-span rather than derivable from "it was exported at all": a trace the
487
+ * tail bias rescued (head-sampled out, then errored) is exported with the bit
488
+ * CLEAR, and saying otherwise misreports the trace's verdict.
489
+ */
490
+ sampled?: boolean;
405
491
  /** Shard key for single-shard calls; absent for the unnamed root DO. */
406
492
  shardKey?: string;
407
493
  /** This span's own id (16-hex). */
@@ -413,35 +499,6 @@ interface SpanEvent {
413
499
  /** Acting userId, or absent when anonymous. */
414
500
  userId?: string;
415
501
  }
416
- /**
417
- * Structural shape of the `ctx.trace` span factory (see the server
418
- * `LunoraTracer`). Declared here rather than imported so `@lunora/do` takes no
419
- * dependency on `@lunora/server`; a cross-package assignability guard in
420
- * `@lunora/testing` fails the build if the two drift apart.
421
- *
422
- * The body's second argument is the enclosing span's {@link SpanHandle}, through
423
- * which it can attach attributes only known *after* it resolves (post-hoc). It is
424
- * a trailing parameter, so a `(trace) => …` body that ignores it still conforms.
425
- */
426
- type ContextTracer = <T>(name: string, function_: (trace: ContextTracer, span: SpanHandle) => Promise<T> | T, options?: LogFields | SpanOptions) => Promise<T>;
427
- /** Structural shape of the `ctx.metrics` recorder (see the server `LunoraMetrics`). */
428
- interface ContextMetrics {
429
- count: (name: string, value?: number, attributes?: LogFields) => void;
430
- gauge: (name: string, value: number, attributes?: LogFields) => void;
431
- record: (name: string, value: number, attributes?: LogFields) => void;
432
- }
433
- /** The trace a ctx's spans hang off: the shared id, and the span they parent to. */
434
- interface TraceAnchor {
435
- rootSpanId: string;
436
- /**
437
- * The W3C `sampled` verdict for this trace, inherited from the inbound
438
- * `traceparent` when there was one. Carried on the anchor rather than
439
- * re-derived per outbound call so every `ctx.fetch` of one dispatch
440
- * propagates the same answer.
441
- */
442
- sampled?: boolean;
443
- traceId: string;
444
- }
445
502
  /**
446
503
  * Minimal structural shape of one **host-native custom span** — the object a
447
504
  * `tracing.enterSpan(name, (span) => …)` callback receives (GA 2026-06-16). Only
@@ -465,8 +522,28 @@ interface HostSpanLike {
465
522
  * a span nobody will read.
466
523
  */
467
524
  readonly isTraced: boolean;
525
+ /**
526
+ * Record an OTel `exception` event on the span (CF 2026-09-25). Optional and
527
+ * feature-detected: older runtimes only have `setAttribute`.
528
+ */
529
+ recordException?: (exception: {
530
+ message: string;
531
+ name: string;
532
+ }) => unknown;
468
533
  /** Attach one primitive attribute to the CF span. */
469
- setAttribute: (key: string, value: boolean | number | string | undefined) => void;
534
+ setAttribute: (key: string, value: boolean | number | string | undefined) => unknown;
535
+ /** Attach several attributes in one call (CF 2026-09-25). Optional, like `recordException`. */
536
+ setAttributes?: (attributes: Record<string, boolean | number | string>) => unknown;
537
+ /**
538
+ * Set the span's OTel status (workers-types 5.20260929). Optional and
539
+ * feature-detected, like `recordException`: older runtimes lack it. The
540
+ * bridge only ever sets `"error"` — OTel instrumentation leaves a successful
541
+ * span `"unset"` rather than marking it `"ok"`.
542
+ */
543
+ setStatus?: (status: {
544
+ code: "error" | "ok" | "unset";
545
+ message?: string;
546
+ }) => unknown;
470
547
  }
471
548
  /**
472
549
  * Minimal structural shape of the `tracing` namespace exported by
@@ -475,6 +552,11 @@ interface HostSpanLike {
475
552
  */
476
553
  interface HostTracingLike {
477
554
  enterSpan: <T>(name: string, callback: (span: HostSpanLike) => T) => T;
555
+ /**
556
+ * The currently active span; outside any custom span, the invocation's root
557
+ * span (CF 2026-09-25). Optional and feature-detected: absent on older runtimes.
558
+ */
559
+ getActiveSpan?: () => HostSpanLike | undefined;
478
560
  }
479
561
  /**
480
562
  * Resolves CF's `tracing` namespace, or `undefined` when it is unavailable —
@@ -484,10 +566,535 @@ interface HostTracingLike {
484
566
  * supplies the real resolver, tests a fake or `undefined`.
485
567
  */
486
568
  type HostTracingResolver = () => HostTracingLike | Promise<HostTracingLike | undefined> | undefined;
569
+ /**
570
+ * Copy an attribute bag onto a host span, best-effort: one native
571
+ * `setAttributes` call where the runtime has it, a `setAttribute` loop where it
572
+ * does not. Skipped for an untraced span; non-primitive values are dropped,
573
+ * since CF's setters take `string | number | boolean` only.
574
+ */
575
+ declare const setHostSpanAttributes: (span: HostSpanLike, attributes: Record<string, LogFields[string]>) => void;
576
+ /**
577
+ * Mirror a finished dispatch onto the host's invocation span — the one
578
+ * `tracing.getActiveSpan()` returns once every `ctx.trace` custom span has
579
+ * ended. Pure and fully best-effort: a missing `getActiveSpan`, an untraced span
580
+ * or a throwing setter is a silent no-op, never an error for the dispatch.
581
+ *
582
+ * `attributes` is the dispatch root span's already-redacted wide event, when it
583
+ * recorded one. `error` is set when the dispatch failed; its `serverFault` is the
584
+ * CALLER's verdict on whether that failure is the server's: the status of the
585
+ * response it actually sent (>= 500) for an RPC, always `true` for a trigger
586
+ * that threw. Only a server fault marks the span failed; a 4xx is an expected
587
+ * client outcome that OTel's server-span convention leaves `"unset"`. `message`
588
+ * must already be redacted.
589
+ *
590
+ * The status is written before the attributes so a throwing attribute setter
591
+ * cannot drop it.
592
+ */
593
+ declare const applyHostRootSpan: (tracing: HostTracingLike | undefined, root: {
594
+ attributes?: Record<string, LogFields[string]>;
595
+ error?: {
596
+ message: string;
597
+ serverFault: boolean;
598
+ };
599
+ }) => void;
600
+ /** Reserved table holding one triage-state row per Issue fingerprint. Auto-hidden by the `__lunora` prefix. */
601
+ declare const ISSUE_STATE_TABLE = "__lunora_issue_state__";
602
+ /**
603
+ * Triage status of an Issue. `open` is the implicit default (no state row); a
604
+ * developer moves it to `resolved` (fixed, but a *new* matching error re-opens
605
+ * it — see {@link readIssueStates}'s consumer) or `ignored` (deliberately muted,
606
+ * and stays muted regardless of new occurrences).
607
+ */
608
+ type IssueStatus = "ignored" | "open" | "resolved";
609
+ /** Ordered severity a developer can tag an Issue with; drives the Studio badge palette. */
610
+ type IssueSeverity = "critical" | "high" | "low" | "medium";
611
+ /** The persisted triage state for one Issue fingerprint. */
612
+ interface IssueState {
613
+ /** Free-form assignee (a userId or a name); absent when unassigned. */
614
+ assignee?: string;
615
+ /** Stable 16-char fingerprint hash — the same key `readErrorIssues` folds on. */
616
+ hash: string;
617
+ /** Developer-tagged severity; absent when untriaged. */
618
+ severity?: IssueSeverity;
619
+ /** Current triage status. */
620
+ status: IssueStatus;
621
+ /** Wall-clock millis the state was last changed — compared against an Issue's `lastSeen` to detect a regression. */
622
+ updatedAt: number;
623
+ /** Acting userId that last changed the state, when known. */
624
+ updatedBy?: string;
625
+ }
626
+ /** Patch applied by an admin write; every field is optional so a caller can change one facet at a time. */
627
+ interface IssueStatePatch {
628
+ assignee?: null | string;
629
+ severity?: IssueSeverity | null;
630
+ status?: IssueStatus;
631
+ }
632
+ /** The valid {@link IssueStatus} values, for arg validation at the admin boundary. */
633
+ declare const ISSUE_STATUSES: ReadonlyArray<IssueStatus>;
634
+ /** The valid {@link IssueSeverity} values, for arg validation at the admin boundary. */
635
+ declare const ISSUE_SEVERITIES: ReadonlyArray<IssueSeverity>;
636
+ /**
637
+ * Apply a triage patch to one Issue, upserting its state row. A `null` in the
638
+ * patch clears the field (unassign, untag severity); an omitted field is left
639
+ * unchanged. Returns the resulting {@link IssueState} so the caller can echo it.
640
+ *
641
+ * Uses `ON CONFLICT(hash) DO UPDATE` with `COALESCE(?, column)` per optional
642
+ * field so a partial patch touches only what it names — except the explicit
643
+ * `null` sentinels for assignee/severity, which are threaded separately so a
644
+ * clear can win over `COALESCE`.
645
+ */
646
+ declare const upsertIssueState: (sql: SqlExec, hash: string, patch: IssueStatePatch, updatedAt: number, updatedBy?: string) => IssueState;
647
+ /** Reserved append-only table backing the studio Logs tab. Auto-hidden from the data browser by the `__lunora` prefix. */
648
+ declare const REQUEST_LOG_TABLE = "__lunora_reqlog__";
649
+ /** Outcome of one dispatch — `ok` for a returned result, `error` for a thrown handler. */
650
+ type RequestOutcome = "error" | "ok";
651
+ /** One recorded `/rpc` dispatch, in monotonic `seq` order. */
652
+ interface RequestLogEntry {
653
+ /** Whether the result was served from the reactive cache; `undefined` when the cache is disabled or the path isn't cached (a write/action). */
654
+ cacheHit?: boolean;
655
+ /** Worker deployment id from the `CF_VERSION_METADATA` binding; `undefined` when the binding isn't declared. Group on this to answer "did this start with a deploy?". */
656
+ deploymentId?: string;
657
+ /** Handler wall-clock duration in milliseconds (before the subscription write-flush, matching the per-function metrics). */
658
+ durationMs: number;
659
+ /** Error message when `outcome === "error"`, redacted like args/identity; absent on success. */
660
+ errorMessage?: string;
661
+ /** The `<file>:<function>` identifier dispatched, e.g. `messages:list`. */
662
+ functionPath: string;
663
+ /** Identity-claim envelope forwarded by the runtime, JSON-decoded; leaf values are redacted (the claims are PII), so only the shape survives. Absent for anonymous requests. Correlate on `userId` instead. */
664
+ identity?: Record<string, unknown>;
665
+ /** `ok` for a returned result, `error` for a thrown handler. */
666
+ outcome: RequestOutcome;
667
+ /** Call args with leaf values redacted by default (keys/shape preserved); absent when no args were sent. */
668
+ redactedArgs?: unknown;
669
+ /** Monotonic per-shard cursor — strictly increasing, never reused. */
670
+ seq: number;
671
+ /** Shard key (the DO id name), or `undefined` for the unnamed `__root__` DO. */
672
+ shardKey?: string;
673
+ /** Count of subscriptions re-run by the write this dispatch triggered; `0` when none (or not measured at the dispatch site). */
674
+ subscriptionsReRun: number;
675
+ /** Tables the handler read (from the dependency tracker); empty when the reactive cache is off or the path read nothing. */
676
+ tablesRead: string[];
677
+ /** Tables the handler wrote (from the change tracker); empty for a read-only dispatch. */
678
+ tablesWritten: string[];
679
+ /** W3C trace id (32-hex) of the dispatch; `undefined` on a row appended before this column existed. See the module docstring on the retention asymmetry. */
680
+ traceId?: string;
681
+ /** Wall-clock millis when the dispatch completed. */
682
+ ts: number;
683
+ /** Acting userId forwarded by the runtime, or `undefined` when anonymous. */
684
+ userId?: string;
685
+ /** Worker version tag from the `CF_VERSION_METADATA` binding; `undefined` when the binding isn't declared or the deploy carried no tag. */
686
+ versionTag?: string;
687
+ }
688
+ /** Fields accepted when appending one request-log entry; `seq` is assigned by the table. */
689
+ interface AppendRequestLogEntry {
690
+ cacheHit?: boolean;
691
+ deploymentId?: string;
692
+ durationMs: number;
693
+ errorMessage?: string;
694
+ functionPath: string;
695
+ identity?: Record<string, unknown>;
696
+ outcome: RequestOutcome;
697
+ /**
698
+ * Cloudflare Ray ID of the request (see `shared/ray-id.ts`). Rides the
699
+ * Workers Logs / Logpush event only — the durable `__lunora_reqlog__` row
700
+ * keeps its `trace_id` join key and has no column for it.
701
+ */
702
+ rayId?: string;
703
+ redactedArgs?: unknown;
704
+ shardKey?: string;
705
+ subscriptionsReRun?: number;
706
+ tablesRead?: string[];
707
+ tablesWritten?: string[];
708
+ traceId?: string;
709
+ ts: number;
710
+ userId?: string;
711
+ versionTag?: string;
712
+ }
713
+ /** Knobs the dispatch site threads into a request-log write. */
714
+ interface RequestLogWriteOptions {
715
+ /** When `true` (development only), skip args/identity redaction so a developer sees raw values. Defaults to `false` (production-safe). */
716
+ captureRaw?: boolean;
717
+ /** Rows to keep after the append-time trim; defaults to {@link REQUEST_LOG_RETENTION}. The operator's `LUNORA_REQUEST_LOG_RETENTION` override. */
718
+ retention?: number;
719
+ }
720
+ /** Filters for {@link readRequestLog}, all AND-combined; every value is a bound SQL parameter, so nothing here injects SQL. */
721
+ interface ReadRequestLogOptions {
722
+ /** Functions whose path begins with this prefix (a `<file>:` or `<file>:<fn>` correlation). */
723
+ functionPathPrefix?: string;
724
+ /** Upper bound on returned rows, clamped to [1, 10000]. */
725
+ limit?: number;
726
+ /** Keep only `ok` / `error` outcomes. */
727
+ outcome?: RequestOutcome;
728
+ /** Exact shard-key match. */
729
+ shardKey?: string;
730
+ /**
731
+ * Only entries strictly after this cursor. Setting it switches the read to
732
+ * ASCENDING order — see {@link readRequestLog} — because that is the only
733
+ * ordering under which advancing the cursor to the last returned `seq`
734
+ * actually pages forward without a hole.
735
+ */
736
+ sinceSeq?: number;
737
+ /** Keep only entries whose read OR written table set contains this table. */
738
+ tableTouched?: string;
739
+ /** Exact acting-userId match. */
740
+ userId?: string;
741
+ }
742
+ /** Payload of a `__lunora_admin__:getRequestLog` call: the recorded entries, newest first — or oldest first when the request paged forward with `sinceSeq` (see {@link readRequestLog}). */
743
+ interface RequestLogResult {
744
+ entries: RequestLogEntry[];
745
+ }
746
+ /**
747
+ * One grouped error **Issue**: many `error`-outcome request-log rows that share a
748
+ * fingerprint folded into a single triage row. The `hash` is the same stable key
749
+ * a cloud Incident groups on, so a local Issue and a cloud Incident are the same
750
+ * object.
751
+ */
752
+ interface ErrorIssue {
753
+ /** Assignee (a userId or a name) from the persisted triage state; absent when unassigned. */
754
+ assignee?: string;
755
+ /** Number of `error` rows folded into this Issue within the scanned window. */
756
+ count: number;
757
+ /** The `<file>:<function>` (or `container:<name>`) the errors came from. */
758
+ culprit: string;
759
+ /** Wall-clock millis of the oldest folded row. */
760
+ firstSeen: number;
761
+ /**
762
+ * Stable 16-char grouping hash over `functionPath :: bucket(message)`,
763
+ * computed from the RAW (pre-redaction) message at write time and stored on
764
+ * the row — see {@link appendRequestLogEntry} — so redacting `sampleMessage`
765
+ * below can't change the grouping.
766
+ */
767
+ hash: string;
768
+ /** Wall-clock millis of the newest folded row. */
769
+ lastSeen: number;
770
+ /** A representative error message (redacted, like the durable row) — taken from the most recent folded row. */
771
+ sampleMessage: string;
772
+ /** Developer-tagged severity from the persisted triage state; absent when untriaged. */
773
+ severity?: IssueSeverity;
774
+ /**
775
+ * Wall-clock millis the persisted triage state was last changed; absent when
776
+ * the Issue has never been triaged. Compared against `lastSeen` to detect a
777
+ * regression (a new error after a resolve).
778
+ */
779
+ stateUpdatedAt?: number;
780
+ /**
781
+ * Triage status folded in from the persisted state (`open` by default). A
782
+ * `resolved` Issue whose `lastSeen` is newer than `stateUpdatedAt` is
783
+ * auto-reopened to `open` here (a regression), so a fresh occurrence never
784
+ * hides behind a stale resolution; `ignored` stays sticky by design.
785
+ */
786
+ status: IssueStatus;
787
+ /** Human-readable title (first line of the sample message, capped). */
788
+ title: string;
789
+ }
790
+ /** Payload of a `__lunora_admin__:getIssues` call: grouped error Issues, most-recently-active first. */
791
+ interface IssuesResult {
792
+ issues: ErrorIssue[];
793
+ }
794
+ /** Filters for {@link readErrorIssues}; forwarded to {@link readRequestLog} with `outcome` forced to `error`. */
795
+ interface ReadIssuesOptions {
796
+ /** Functions whose path begins with this prefix (a `<file>:` or `<file>:<fn>` correlation). */
797
+ functionPathPrefix?: string;
798
+ /** Upper bound on error rows scanned before grouping, clamped to [1, 10000]. */
799
+ limit?: number;
800
+ /** Exact shard-key match. */
801
+ shardKey?: string;
802
+ /** Keep only Issues in this triage status, applied AFTER the persisted-state fold + auto-reopen. */
803
+ status?: IssueStatus;
804
+ /** Exact acting-userId match. */
805
+ userId?: string;
806
+ }
807
+ /**
808
+ * Mask credentials only, leaving PII alone: `maskCredentials` — credential key
809
+ * names, `name=value` pairs, auth schemes, JWTs, PEM keys, URL query / fragment
810
+ * / userinfo. For span, event, link and metric attributes: {@link redactArgs}'
811
+ * PII rules key on names like `id`, `url` and `date` and mask uuids, so they
812
+ * would erase the very `order.id` / `url` attributes a trace is read by, and
813
+ * `@visulima/redact`'s regexes cost ~20 µs per call on the Durable Object's only
814
+ * thread, where every span, event and metric pays it. `captureRaw` as in
815
+ * {@link redactArgs}.
816
+ */
817
+ declare const redactCredentials: (value: unknown, captureRaw?: boolean) => unknown;
818
+ /**
819
+ * Redact the secrets / PII out of a value before it reaches the durable log, a
820
+ * Logpush event, a function-metrics row or a span's error message:
821
+ * `maskCredentials`, then `@visulima/redact`'s `standardRules`. `null` /
822
+ * `undefined` pass through unchanged.
823
+ *
824
+ * On a KEYED object (`args`, `identity`), a key that names a credential
825
+ * (`accessToken`, `client_secret`, `X-Api-Key`, `sessionId`, `otp`, `pin`,
826
+ * `DATABASE_URL`) has its value masked, numbers included; a key that measures
827
+ * credentials (`maxTokens`, `tokenUsage`) keeps its numbers. See
828
+ * `shared/credential-redaction.ts` for how keys are judged.
829
+ *
830
+ * On a STRING (`errorMessage`, a URL, a log line), every URL loses its query,
831
+ * fragment and userinfo; `name=value`, `name: value` and `"name":"value"` pairs
832
+ * with a credential name are masked; `Basic …`, `Bearer …` and `Digest …` are
833
+ * masked; and so is a bare token in prose with no name attached, when its format
834
+ * has a distinctive vendor prefix (`failed with sk_live_…`, `ghp_…`, `xoxb-…`,
835
+ * `AKIA…`, JWTs, … — see `SECRET_VALUE_RULES`), all by `maskCredentials`.
836
+ * `standardRules`' value patterns (emails, long digit runs) then mask PII. Every
837
+ * string is truncated to 4 KiB in what is stored, and once 16 KiB of one value has
838
+ * been examined the remaining strings are replaced with a marker, so no arg can
839
+ * hold the Durable Object in regex work.
840
+ *
841
+ * Still NOT caught: a bare secret with no name attached and no vendor prefix (a
842
+ * random hex key, a password in a sentence). This is a credential-and-PII net,
843
+ * not proof that no secret can reach the log.
844
+ *
845
+ * `captureRaw` is the development escape hatch: in a dev environment the dispatch
846
+ * site (`isDevEnvironment`) passes `true` to skip redaction so a developer can
847
+ * see real arg/identity/error values; production always redacts. The dev
848
+ * decision is made at the call site from the deployment env, never inferred
849
+ * here — so a real deploy that omits the env var stays redacted.
850
+ */
851
+ declare const redactArgs: (value: unknown, captureRaw?: boolean) => unknown;
852
+ /** What a `v.sensitive` argument is replaced with before it reaches any log row, Logpush event or dev capture. */
853
+ declare const SENSITIVE_ARG_MASK = "«sensitive»";
854
+ /**
855
+ * Replace the named arguments of one dispatch with {@link SENSITIVE_ARG_MASK},
856
+ * leaving every other argument as it was. Applied BEFORE {@link redactArgs}: the
857
+ * `captureRaw` development escape hatch skips redaction entirely, so masking
858
+ * inside `redactArgs` would leak a marked value in dev. Returns `args` itself when
859
+ * nothing is sensitive, and never mutates the caller's object.
860
+ */
861
+ declare const maskSensitiveArgs: (args: Record<string, unknown>, sensitive: ReadonlySet<string>) => Record<string, unknown>;
862
+ declare const sensitiveValues: (args: Record<string, unknown>, sensitive: ReadonlySet<string>) => string[];
863
+ /**
864
+ * The property names of the marked arguments, taken from every object under them. A
865
+ * marked key can be used as a log field or span-attribute name, so it is matched as a
866
+ * whole field name only (see {@link SecretSet}): a name such as `value` is ordinary
867
+ * prose and must not be masked wherever it appears in text.
868
+ */
869
+ declare const sensitiveNames: (args: Record<string, unknown>, sensitive: ReadonlySet<string>) => string[];
870
+ /**
871
+ * The sensitive values of ONE invocation, handed by value to everything that
872
+ * records on its behalf (ctx.log, ctx.trace, ctx.span, ctx.fetch, ctx.metrics and
873
+ * the dispatch's root span). It is the only place the values live: a scope is
874
+ * built when the dispatch starts and {@link SensitiveScope.clear}ed when it
875
+ * settles, after which it scrubs nothing. Nothing reads it from shared state, so
876
+ * two concurrent dispatches on one shard each scrub only their own values.
877
+ */
878
+ interface SensitiveScope {
879
+ /**
880
+ * Admit more values into the invocation: a composed call runs inside the
881
+ * caller's invocation, so its own marked arguments are scrubbed from here on.
882
+ * `names` are that call's marked property names (see {@link sensitiveNames}).
883
+ * A no-op once the scope is cleared.
884
+ */
885
+ add: (values: ReadonlyArray<string>, names?: ReadonlyArray<string>) => void;
886
+ /**
887
+ * Mark the dispatch settled. The values are forgotten once no `hold` is
888
+ * outstanding, so a record still open when the dispatch returns is scrubbed.
889
+ */
890
+ clear: () => void;
891
+ /** Scrub a field bag; `undefined` passes through. */
892
+ fields: <T extends Record<string, unknown> | undefined>(bag: T) => T;
893
+ /**
894
+ * Keep the values for a record opened under this scope and not yet written.
895
+ * Returns the release, which is idempotent. A record opened while the scope is
896
+ * live is scrubbed from the values as they stand then.
897
+ */
898
+ hold: () => () => void;
899
+ /**
900
+ * Scrub a telemetry name (an event, span or metric name, or a plain log message). A name that is exactly
901
+ * a marked property name masks whole; any other name is scrubbed as free text.
902
+ */
903
+ name: (name: string) => string;
904
+ /** Scrub a free-text string. */
905
+ text: (text: string) => string;
906
+ /** Scrub one structured value. */
907
+ value: <T>(value: T) => T;
908
+ }
909
+ /**
910
+ * Build the scope for one invocation from the values and property names of its marked
911
+ * arguments (see {@link sensitiveValues} and {@link sensitiveNames}). The arrays are
912
+ * copied, so the caller keeps no handle on the values it passed in.
913
+ */
914
+ declare const createSensitiveScope: (values: ReadonlyArray<string>, names?: ReadonlyArray<string>) => SensitiveScope;
915
+ /**
916
+ * The scope of an invocation with no marked arguments. Scrubs nothing, and admits
917
+ * nothing: it is shared by every such invocation, so `add` must not reach it.
918
+ */
919
+ declare const NO_SENSITIVE_SCOPE: SensitiveScope;
920
+ /**
921
+ * Create the `__lunora_reqlog__` table. `seq` is an `AUTOINCREMENT` primary
922
+ * key, giving each shard a monotonic cursor the Logs tab pages through; the
923
+ * `args`/`identity`/`tables_read`/`tables_written` columns hold JSON and are
924
+ * `NULL`/empty when none was recorded. Idempotent, so read and write paths can
925
+ * call it defensively.
926
+ *
927
+ * `error_fingerprint` is the {@link fingerprintError} grouping hash captured
928
+ * from the RAW `error_message` at write time, before {@link appendRequestLogEntry}
929
+ * redacts it — see that function's docstring. `trace_id` is the dispatch's W3C
930
+ * trace id, the correlation key to the span ring and to whatever collector
931
+ * `otlpSink` ships to.
932
+ *
933
+ * Both are also added via a guarded `ALTER TABLE`, mirroring
934
+ * `function-metrics.ts`'s `ensureFunctionMetricsTables`, so a shard whose
935
+ * `__lunora_reqlog__` predates a column gains it on the next call without a
936
+ * migration. SQLite has no `ADD COLUMN IF NOT EXISTS`, so the duplicate-column
937
+ * error from a re-run (or from the freshly-created schema above) is swallowed
938
+ * per column — the loop is what keeps one column's duplicate from skipping the
939
+ * next column's add.
940
+ */
941
+ declare const ensureRequestLogTable: (sql: SqlExec) => void;
942
+ /**
943
+ * Append one dispatch to the request log, then — once per
944
+ * {@link REQUEST_LOG_PRUNE_WINDOW_MS} window — trim the log back to the most
945
+ * recent `retention` rows (default {@link REQUEST_LOG_RETENTION}). Creates the
946
+ * table first so callers needn't. Args/identity/error message are redacted here
947
+ * so a raw value never reaches the durable table — callers pass the unredacted
948
+ * entry and rely on this, unless `captureRaw` (dev only) is set. `retention` is
949
+ * the operator's `LUNORA_REQUEST_LOG_RETENTION` override, threaded in by the
950
+ * dispatch site.
951
+ *
952
+ * The error-grouping fingerprint is computed from `entry.errorMessage` BEFORE
953
+ * it's redacted below, and the resulting hash is persisted in
954
+ * `error_fingerprint`. `readErrorIssues` groups off that stored hash instead of
955
+ * recomputing `fingerprintError` from the (redacted) `error_message` column, so
956
+ * masking a PII-bearing value — e.g. two different `<n>`-bucketed IDs that
957
+ * redact to two different tag lengths (`<DL>` vs `<BANKACC>`) — can't split an
958
+ * existing Issue or change its identity.
959
+ */
960
+ declare const appendRequestLogEntry: (sql: SqlExec, entry: AppendRequestLogEntry, options?: RequestLogWriteOptions) => void;
961
+ /**
962
+ * Emit one structured request event to `console` so Cloudflare's Workers Logs /
963
+ * Logpush pipeline carries it to external sinks (SIEMs) — PLAN3 §3.3. This does
964
+ * NOT reimplement a transport: it produces a richer, lunora-attributed event and
965
+ * lets CF's existing trace-log pipe ship it. The event mirrors the durable
966
+ * `__lunora_reqlog__` row (function path, shard, user, outcome, duration, tables
967
+ * read/written, cache hit), with `args`, `identity`, AND `error` redacted
968
+ * exactly like the durable write so no raw PII/secret reaches the log pipeline.
969
+ *
970
+ * An `error` outcome goes to `console.error` (surfacing at error level in the
971
+ * trace so a SIEM can alert on it); everything else to `console.log`. The
972
+ * `source: "lunora"` / `type: "request"` envelope lets a consumer filter these
973
+ * events out of the raw Workers-trace firehose. `captureRaw` (dev only) skips
974
+ * redaction, mirroring the durable write. Best-effort by contract — the caller
975
+ * wraps it so a serialization hiccup can never fail the served request.
976
+ */
977
+ declare const emitRequestLogEvent: (entry: AppendRequestLogEntry, options?: RequestLogWriteOptions) => void;
978
+ /**
979
+ * The `ctx.log` event contract (shape + severity union) lives in
980
+ * `shared/log-event.ts` (inlined into each `dist`) so the DO that builds these
981
+ * events and the `@lunora/runtime` sink that consumes them agree by construction.
982
+ * `LogEventInput` is the DO's historical name for the shared `LogEvent`.
983
+ */
984
+ type LogEventInput = LogEvent;
985
+ /**
986
+ * Split a `ctx.log.<level>(...)` call's raw arguments into a display `message`
987
+ * and optional structured `fields`. The structured form — a message string plus
988
+ * a plain-object fields bag — is matched only for exactly `(string, object)`;
989
+ * every other shape is console-style and rendered whole (so existing
990
+ * `console`-shaped calls are unchanged). Bound `.with(...)` fields merge under
991
+ * the per-call fields (per-call wins); the result is normalized to a fresh bag
992
+ * of JSON-safe primitives, or `undefined` when empty (see `normalizeLogFields`).
993
+ */
994
+ declare const parseLogArgs: (args: unknown[], boundFields?: LogFields) => {
995
+ fields?: LogFields;
996
+ message: string;
997
+ };
998
+ /**
999
+ * Emit one application-log event from a `ctx.log.*` call to `console`, tagged
1000
+ * `{ source: "lunora", type: "log" }` so the CLI / Vite formatter can pretty-print
1001
+ * it in the dev terminal and a Logpush/SIEM consumer can filter it out of the
1002
+ * raw Workers-trace firehose.
1003
+ *
1004
+ * Only the rendered `message` is emitted here, NOT the structured `args` array:
1005
+ * the console event rides CF Workers Logs / Logpush to prod, and shipping raw,
1006
+ * un-redacted arg objects on a `source: "lunora"` line a SIEM is told to trust
1007
+ * would be a surprising PII/secret surface. The raw `args` stay on the in-process
1008
+ * `sink.onLog` path (`recordUserLog`), which the operator opts into and controls.
1009
+ * `message` already carries the developer's rendered values, exactly like a raw
1010
+ * `console.log` line.
1011
+ *
1012
+ * `error`/`fatal` go to `console.error`, `warn` to `console.warn` (so they
1013
+ * surface at the right level in the trace); every other level to `console.log`.
1014
+ *
1015
+ * Structured `fields` (plus `traceId`/`spanId` for correlation) ARE emitted here
1016
+ * — they are intentional metadata a log pipeline filters on, unlike raw `args`.
1017
+ * Unlike `args`, `fields` IS redacted before it rides this console line — a
1018
+ * developer can attach anything to a fields bag (`ctx.log.info("charged",
1019
+ * { email, cardLast4 })`), and this is the one line that's told to a SIEM as
1020
+ * trustworthy, exactly like the request-log `args`/`identity`/`error` columns.
1021
+ * `options.captureRaw` (dev only) skips it, mirroring every other redaction
1022
+ * point in this module; the sole current caller (`ShardDO.recordUserLog`)
1023
+ * doesn't yet thread a dev flag through, so `fields` redacts unconditionally
1024
+ * there today — a conservative default, never a correctness gap. A field value
1025
+ * that can't be serialised (a circular object) would make `JSON.stringify`
1026
+ * throw and drop the whole line, so serialisation falls back to a fields-free
1027
+ * line rather than losing the event.
1028
+ */
1029
+ declare const emitLogEvent: (input: LogEventInput, options?: RequestLogWriteOptions) => void;
1030
+ /**
1031
+ * Read request-log entries, AND-combining the supplied filters (function-path
1032
+ * prefix, exact userId/shardKey/outcome, and a table-touched match against the
1033
+ * read OR written table sets), up to `limit` (clamped to [1, 10000]). Each value
1034
+ * is a bound parameter, so no filter can inject SQL. Creates the table first so
1035
+ * reads on a never-logged shard return `[]` instead of throwing. Mirrors
1036
+ * `readAuditLog`/`readCdcChanges`.
1037
+ *
1038
+ * **Ordering follows `sinceSeq`.** Without a cursor this is a "show me the tail"
1039
+ * read and returns NEWEST FIRST, which is what the studio's Logs tab renders.
1040
+ * With `sinceSeq` it is forward paging and returns OLDEST FIRST, starting at the
1041
+ * cursor: descending there silently loses rows, because `ORDER BY seq DESC LIMIT
1042
+ * n` answers "the newest n after the cursor", so a consumer that advances to the
1043
+ * largest returned `seq` skips everything between `sinceSeq` and that page
1044
+ * whenever more than `limit` rows accumulated between polls — the more traffic
1045
+ * the shard takes, the more it drops.
1046
+ */
1047
+ declare const readRequestLog: (sql: SqlExec, options?: ReadRequestLogOptions) => RequestLogEntry[];
1048
+ declare const readErrorIssues: (sql: SqlExec, options?: ReadIssuesOptions) => ErrorIssue[];
1049
+ /**
1050
+ * Structural shape of the `ctx.trace` span factory (see the server
1051
+ * `LunoraTracer`). Declared here rather than imported so `@lunora/do` takes no
1052
+ * dependency on `@lunora/server`; a cross-package assignability guard in
1053
+ * `@lunora/testing` fails the build if the two drift apart.
1054
+ *
1055
+ * The body's second argument is the enclosing span's {@link SpanHandle}, through
1056
+ * which it can attach attributes only known *after* it resolves (post-hoc). It is
1057
+ * a trailing parameter, so a `(trace) => …` body that ignores it still conforms.
1058
+ */
1059
+ type ContextTracer = <T>(name: string, function_: (trace: ContextTracer, span: SpanHandle) => Promise<T> | T, options?: LogFields | SpanOptions, identity?: SpanIdentity) => Promise<T>;
1060
+ /** Structural shape of the `ctx.metrics` recorder (see the server `LunoraMetrics`). */
1061
+ interface ContextMetrics {
1062
+ count: (name: string, value?: number, attributes?: LogFields) => void;
1063
+ gauge: (name: string, value: number, attributes?: LogFields) => void;
1064
+ record: (name: string, value: number, attributes?: LogFields) => void;
1065
+ }
1066
+ /** The trace a ctx's spans hang off: the shared id, and the span they parent to. */
1067
+ interface TraceAnchor {
1068
+ /**
1069
+ * Cloudflare Ray ID of the request this dispatch serves, forwarded by the
1070
+ * runtime alongside `traceparent`. Carried on the anchor so every span and
1071
+ * log line of the dispatch stamps the same value. Absent off the edge.
1072
+ * Informational only, as `parseRayId` in `shared/ray-id.ts` defines it.
1073
+ */
1074
+ rayId?: string;
1075
+ rootSpanId: string;
1076
+ /**
1077
+ * The W3C `sampled` verdict for this trace, inherited from the inbound
1078
+ * `traceparent` when there was one. Carried on the anchor rather than
1079
+ * re-derived per outbound call so every `ctx.fetch` of one dispatch
1080
+ * propagates the same answer.
1081
+ */
1082
+ sampled?: boolean;
1083
+ traceId: string;
1084
+ }
487
1085
  /** What {@link createTracer} needs from the shard to build a span. */
488
1086
  interface TracerDeps {
489
1087
  /** The trace this ctx's spans belong to. */
490
1088
  anchor: TraceAnchor;
1089
+ /**
1090
+ * Whether to record a span body's error message (and a `recordException`
1091
+ * stacktrace) verbatim rather than redacted. Mirrors the request log's
1092
+ * `captureRaw`: `true` in dev (`isDevEnvironment`), `false` in production —
1093
+ * the span pipeline is the one sink third-party collectors (Datadog/Axiom
1094
+ * via `otlpSink`) receive, so it must not ship raw PII/internals by default
1095
+ * the way the request log and function-metrics sinks already don't.
1096
+ */
1097
+ captureRaw?: boolean;
491
1098
  /** Function path the spans are attributed to. */
492
1099
  functionPath: string;
493
1100
  /**
@@ -513,6 +1120,11 @@ interface TracerDeps {
513
1120
  * calls it.
514
1121
  */
515
1122
  resolveHostTracing?: HostTracingResolver;
1123
+ /**
1124
+ * The invocation's `v.sensitive` values (see {@link SensitiveScope}). Applied
1125
+ * to every span this tracer records, and to the body's own collector.
1126
+ */
1127
+ scope?: SensitiveScope;
516
1128
  /** Shard key for single-shard calls; absent for the unnamed root DO. */
517
1129
  shardKey: string | undefined;
518
1130
  /** Read lazily — the acting user is resolved per span, not per ctx. */
@@ -522,6 +1134,8 @@ interface TracerDeps {
522
1134
  interface MetricsDeps {
523
1135
  functionPath: string;
524
1136
  record: (event: MetricEvent) => void;
1137
+ /** The invocation's `v.sensitive` values, applied to each measurement's attributes. */
1138
+ scope?: SensitiveScope;
525
1139
  shardKey: string | undefined;
526
1140
  }
527
1141
  /** Everything a {@link SpanHandle}'s body attached, ready to merge into the recorded span. */
@@ -544,11 +1158,19 @@ interface SpanCollector {
544
1158
  * attributes become the canonical one-event-per-request summary. Sharing the
545
1159
  * implementation is what makes those two feel like the same API instead of two
546
1160
  * that happen to resemble each other.
1161
+ *
1162
+ * `captureRaw` (default `false`) gates `recordException`'s `exception.message`/
1163
+ * `exception.stacktrace` the same way {@link createTracer} gates a span's own
1164
+ * error message — a stack is file paths and internals by definition, the exact
1165
+ * class `isInternalCode` redaction exists for, so it rides the same dev-only
1166
+ * escape hatch rather than shipping to a third-party collector by default.
1167
+ *
1168
+ * `scope` scrubs the invocation's `v.sensitive` values out of everything written
1169
+ * here, at write time, so the collector never holds the raw value. It is applied
1170
+ * whatever `captureRaw` says: the dev escape hatch exists for stacks and
1171
+ * internals, not for a marked argument.
547
1172
  */
548
- declare const createSpanCollector: (ids: {
549
- spanId: string;
550
- traceId: string;
551
- }) => SpanCollector;
1173
+ declare const createSpanCollector: (ids: SpanContextIds, captureRaw?: boolean, scope?: SensitiveScope) => SpanCollector;
552
1174
  /**
553
1175
  * Build the `ctx.trace` span factory for one dispatched function.
554
1176
  *
@@ -590,7 +1212,7 @@ declare const createSpanCollector: (ids: {
590
1212
  *
591
1213
  * **DO async-context caveat (EXPERIMENTAL, partially workerd-validated).**
592
1214
  * `tracing.enterSpan` is now confirmed to EXIST and RUN inside a real Durable
593
- * Object under `@cloudflare/vitest-pool-workers` (see
1215
+ * Object under `@cloudflare/vitest-plugin` (see
594
1216
  * `__tests__/workerd/context-telemetry-cf-bridge.workerd.test.ts`): it resolves
595
1217
  * from `cloudflare:workers`, its callback executes and returns the body value
596
1218
  * without throwing, `span.isTraced` is a real boolean, and — the key additive
@@ -610,6 +1232,14 @@ declare const createTracer: (deps: TracerDeps) => ContextTracer;
610
1232
  interface TracedFetchDeps {
611
1233
  /** The trace the CLIENT spans belong to. */
612
1234
  anchor: TraceAnchor;
1235
+ /**
1236
+ * Whether to record a failed fetch's error message verbatim rather than
1237
+ * redacted. Same dev-only escape hatch as {@link TracerDeps.captureRaw}, and
1238
+ * the same reason: a `fetch` TypeError embeds the request URL, so a key in a
1239
+ * query string would otherwise reach the collector in the clear on the very
1240
+ * span whose `url.full` is scrubbed by `redactUrl`.
1241
+ */
1242
+ captureRaw?: boolean;
613
1243
  /** Function path the spans are attributed to. */
614
1244
  functionPath: string;
615
1245
  /**
@@ -619,6 +1249,8 @@ interface TracedFetchDeps {
619
1249
  propagate?: ((url: URL) => boolean) | boolean;
620
1250
  /** Hand a finished span to the buffer + sink. */
621
1251
  record: (span: SpanEvent) => void;
1252
+ /** The invocation's `v.sensitive` values; a query string or path can carry one. */
1253
+ scope?: SensitiveScope;
622
1254
  /** Shard key for single-shard calls; absent for the unnamed root DO. */
623
1255
  shardKey: string | undefined;
624
1256
  /** Read lazily — the acting user is resolved per span. */
@@ -645,6 +1277,15 @@ type ContextFetch = (input: Request | string | URL, init?: RequestInit) => Promi
645
1277
  * Kind is `client` rather than `internal` — that is what lets a collector draw
646
1278
  * the edge to the downstream service in a service map.
647
1279
  *
1280
+ * **Parenting is the DISPATCH, not the enclosing `ctx.trace`.** `ctx.fetch` is
1281
+ * built once per dispatch, and the enclosing span is threaded explicitly rather
1282
+ * than kept on an ambient stack (no `AsyncLocalStorage` in the Durable Object
1283
+ * profile — the same constraint `ctx.trace` and the `@opentelemetry/api` bridge
1284
+ * document), so a fetch inside `ctx.trace("stripe", …)` renders as that span's
1285
+ * SIBLING under the dispatch, not its child. The duration and the ordering are
1286
+ * right and the span is never lost; only the nesting is flat. Wrap the call in
1287
+ * the span whose bar you want it under and read the two side by side.
1288
+ *
648
1289
  * Failures are recorded and re-thrown untouched, and a non-2xx response is
649
1290
  * recorded as an ERROR span (it is a failed call from the caller's point of
650
1291
  * view) while still being returned normally — instrumentation, never flow
@@ -673,6 +1314,14 @@ declare const createMetrics: (deps: MetricsDeps) => ContextMetrics;
673
1314
  */
674
1315
  declare const dispatchRootSpan: (input: {
675
1316
  anchor: TraceAnchor;
1317
+ /**
1318
+ * Whether to record the failure message verbatim rather than redacted —
1319
+ * the same dev-only escape hatch as {@link TracerDeps.captureRaw}. This
1320
+ * synthetic root span carries the SAME error message the request log and
1321
+ * function-metrics sinks already redact by default, so it must not be the
1322
+ * one durable copy that ships it raw to a third-party collector.
1323
+ */
1324
+ captureRaw?: boolean;
676
1325
  /**
677
1326
  * What the handler attached to the dispatch through `ctx.span` — the **wide
678
1327
  * event**. These are the attributes that would otherwise have been scattered
@@ -686,6 +1335,8 @@ declare const dispatchRootSpan: (input: {
686
1335
  thrown: unknown;
687
1336
  } | undefined;
688
1337
  functionPath: string;
1338
+ /** The invocation's `v.sensitive` values; the failure message can quote one. */
1339
+ scope?: SensitiveScope;
689
1340
  shardKey: string | undefined;
690
1341
  startTs: number;
691
1342
  userId: string | undefined;
@@ -700,7 +1351,12 @@ interface DatabaseTally {
700
1351
  spansTruncated: boolean;
701
1352
  }
702
1353
  /**
703
- * How much detail `ctx.db` auto-instrumentation produces.
1354
+ * Which instrumented surface a tally belongs to, and the key prefix
1355
+ * {@link formatTally} folds it under: `db` for `ctx.db`, `sql` for `ctx.sql`.
1356
+ */
1357
+ type TallySurface = "db" | "sql";
1358
+ /**
1359
+ * How much detail `ctx.db` / `ctx.sql` auto-instrumentation produces.
704
1360
  *
705
1361
  * `"summary"` (default) — aggregate counters on the dispatch's wide event: no
706
1362
  * extra spans, no extra log records, and a cost that does not grow with call count.
@@ -711,16 +1367,34 @@ interface DatabaseTally {
711
1367
  * `"off"` — no database telemetry at all.
712
1368
  */
713
1369
  type DatabaseInstrumentation = "off" | "spans" | "summary";
714
- /** What {@link instrumentDatabase} needs to record what it observes. */
1370
+ /**
1371
+ * The structural slice of `@lunora/hyperdrive`'s `SqlClient` the `ctx.sql`
1372
+ * instrumenter needs — declared here so this package takes no dependency on
1373
+ * hyperdrive.
1374
+ */
1375
+ interface SqlClientLike {
1376
+ /** OTel `db.system.name` the driver adapter stamped; `other_sql` when absent. */
1377
+ readonly dbSystem?: string;
1378
+ query: (text: string, params?: ReadonlyArray<unknown>) => Promise<unknown>;
1379
+ }
1380
+ /** What {@link instrumentDatabase} / {@link instrumentSqlClient} need to record what they observe. */
715
1381
  interface DatabaseTelemetryDeps {
716
1382
  /** The trace produced spans belong to (`"spans"` mode only). */
717
1383
  anchor: TraceAnchor;
1384
+ /**
1385
+ * Whether to record a failed call's error message verbatim (`"spans"` mode
1386
+ * only) — the same dev-only escape hatch as `TracerDeps.captureRaw`. See
1387
+ * {@link failureMessage} for what each surface records without it.
1388
+ */
1389
+ captureRaw?: boolean;
718
1390
  /** Function path spans and attributes are attributed to. */
719
1391
  functionPath: string;
720
1392
  /** Detail level; see {@link DatabaseInstrumentation}. */
721
1393
  mode: DatabaseInstrumentation;
722
1394
  /** Hand a finished span to the buffer + sink (`"spans"` mode only). */
723
1395
  record: (span: SpanEvent) => void;
1396
+ /** The invocation's `v.sensitive` values; a driver's error message can quote one. */
1397
+ scope?: SensitiveScope;
724
1398
  /** Shard key for single-shard calls; absent for the unnamed root DO. */
725
1399
  shardKey: string | undefined;
726
1400
  /**
@@ -728,14 +1402,20 @@ interface DatabaseTelemetryDeps {
728
1402
  * increments numbers on it; the shard reads it ONCE at the dispatch boundary
729
1403
  * and formats it with {@link formatTally}.
730
1404
  *
731
- * Two properties fall out of that split. Per-call cost stays at a few integer
732
- * increments — no object allocation, no lookup — which matters because this is
733
- * on the path of every query. And because nothing is written through the
734
- * dispatch's `SpanHandle`, the wide-event collector is never materialized, so
735
- * a handler that instrumented nothing still doesn't trip the root-span gate.
1405
+ * Per-call cost stays at a few integer increments — no object allocation, no
1406
+ * lookup — which matters because this is on the path of every query. Nothing
1407
+ * is written through the dispatch's `SpanHandle` either, so the wide-event
1408
+ * collector is never materialized by instrumentation alone: a dispatch that
1409
+ * ran queries gets a root span carrying these counters, but no `lunora.dispatch`
1410
+ * log record unless the handler actually opened `ctx.span`.
736
1411
  */
737
1412
  tally: DatabaseTally;
738
- /** Read lazily — the acting user is resolved per span. */
1413
+ /**
1414
+ * The acting user, read when a span is built. Callers resolve it ONCE, when
1415
+ * they instrument the client, and return that captured value: a span is
1416
+ * built after the call's await, and per-request shared state read by then
1417
+ * may already belong to a concurrent request.
1418
+ */
739
1419
  userId: () => string | undefined;
740
1420
  }
741
1421
  /**
@@ -744,24 +1424,42 @@ interface DatabaseTelemetryDeps {
744
1424
  * Returns the database unchanged when `mode` is `"off"`, so the default-disabled
745
1425
  * path costs nothing — not even a proxy indirection.
746
1426
  *
747
- * Implemented as a `Proxy` rather than by enumerating and rebinding methods:
748
- * `DatabaseWriterLike` has optional members that a given backend may or may not
749
- * implement, plus properties (`system`) and builder factories (`query`) that
750
- * must pass through untouched. A proxy instruments exactly what it is asked to
751
- * and is transparently correct for everything else, including members added
752
- * later — an enumeration would silently stop covering them.
1427
+ * A proxy rather than an enumerated, rebound copy: `DatabaseWriterLike` has
1428
+ * optional members that a given backend may or may not implement, plus
1429
+ * properties (`system`) and builder factories (`query`) that must pass through
1430
+ * untouched. A proxy instruments exactly what it is asked to and is
1431
+ * transparently correct for everything else, including members added later —
1432
+ * an enumeration would silently stop covering them.
753
1433
  */
754
1434
  declare const instrumentDatabase: <T extends object>(database: T, deps: DatabaseTelemetryDeps) => T;
1435
+ /**
1436
+ * Wrap the action-only `ctx.sql` client so every `query` is instrumented — the
1437
+ * `ctx.sql` twin of {@link instrumentDatabase}, at the same levels and through
1438
+ * the same {@link observeCall}. `deps.tally` must be a tally of its own (folded
1439
+ * as `sql.*`), never `ctx.db`'s.
1440
+ *
1441
+ * Its span carries no statement text and no parameters — only the
1442
+ * leading-keyword operation, the system, and the returned row count. No
1443
+ * `db.collection.name` either: naming the table means parsing past
1444
+ * `FROM`/`INTO` through joins, CTEs and quoting, which is neither cheap nor
1445
+ * safe. A failure records its TYPE (see {@link failureMessage}).
1446
+ *
1447
+ * `query` is the whole `SqlClient` surface: there is no transaction or batch
1448
+ * method to cover. Everything else on the client passes through untouched, and
1449
+ * `"off"` returns the client itself.
1450
+ */
1451
+ declare const instrumentSqlClient: <T extends SqlClientLike>(client: T, deps: DatabaseTelemetryDeps) => T;
755
1452
  /** A zero'd tally for one dispatch. */
756
1453
  declare const createDatabaseTally: () => DatabaseTally;
757
1454
  /**
758
- * Render the running tally as span attributes.
1455
+ * Render the running tally as span attributes, under its surface's prefix
1456
+ * ({@link TallySurface}).
759
1457
  *
760
1458
  * Called ONCE per dispatch, from the shard's root-span recorder — not per query.
761
- * Building this object on every call was pure waste on a hot path. It is a handful of keys, so the per-call cost is a small object
762
- * assignment — the property that makes `"summary"` mode scale to any call count.
1459
+ * It is a handful of keys, so the per-call cost is a small object assignment —
1460
+ * the property that makes `"summary"` mode scale to any call count.
763
1461
  */
764
- declare const formatTally: (tally: DatabaseTally) => LogFields;
1462
+ declare const formatTally: (tally: DatabaseTally, surface?: TallySurface) => LogFields;
765
1463
  /** Reserved per-function accumulator table. Auto-hidden from the data browser by the `__lunora` prefix. */
766
1464
  declare const FUNCTION_METRICS_TABLE = "__lunora_metrics";
767
1465
  /** Reserved coarse time-series table: per-function call/error counts bucketed by a fixed window. */
@@ -786,13 +1484,23 @@ declare const FUNCTION_METRICS_BUCKET_RETENTION = 1440;
786
1484
  /**
787
1485
  * Maximum distinct function `path`s tracked in the accumulator table. Mirrors
788
1486
  * `query-metrics.ts`'s `QUERY_METRICS_MAX_STATEMENTS` cap (and exists for the
789
- * same reason): the `path` is attacker-reachable — an unregistered/`FUNCTION_NOT_FOUND`
790
- * dispatch still records a row keyed by the caller-supplied `functionPath` — so
791
- * without a cap a flood of distinct random paths would grow `__lunora_metrics`
792
- * (and its bucket/scan satellites) without bound, eventually filling the shard's
793
- * SQLite store shared with the app's real data. A few thousand registered
794
- * functions is already far beyond any real app, so a new path past this cap is
795
- * dropped while already-tracked paths keep accumulating.
1487
+ * same reason): the real bound is the app's own registered-function set plus
1488
+ * deploy churn (a rename/removal leaves its old path's row in place, still
1489
+ * counted against the cap, until an operator's own retention/cleanup
1490
+ * process — there is none built in today) — a few thousand registered
1491
+ * functions is already far beyond any real app. `shard-do.ts`'s dispatch
1492
+ * handler explicitly does NOT record per-function metrics for an
1493
+ * unregistered/`FUNCTION_NOT_FOUND` dispatch (see the guard next to its
1494
+ * `FUNCTION_NOT_FOUND` check), so a caller cannot mint arbitrary `path`s here
1495
+ * the way a raw caller-supplied SQL shape can in `query-metrics.ts`. Without a
1496
+ * cap, deploy churn across the app's lifetime would still grow
1497
+ * `__lunora_metrics` (and its bucket/scan satellites) without bound,
1498
+ * eventually filling the shard's SQLite store shared with the app's real
1499
+ * data. At the cap, a brand-new path is refused — protecting the incumbent
1500
+ * leaderboard from a flood of one-off paths is the point, so admission is
1501
+ * refused rather than evicting an existing path to make room; already-tracked
1502
+ * paths keep accumulating past the cap. `readFunctionMetricsTotals`'s
1503
+ * `capped` is the read-side signal for this.
796
1504
  */
797
1505
  declare const FUNCTION_METRICS_MAX_PATHS = 5e3;
798
1506
  /**
@@ -814,6 +1522,22 @@ interface FunctionMetricBucket {
814
1522
  /** Subset of `calls` that threw. */
815
1523
  errors: number;
816
1524
  }
1525
+ /** {@link readFunctionMetricBuckets} result: the time-series window plus whether the read limit cut it short. */
1526
+ interface FunctionMetricBucketsResult {
1527
+ buckets: (FunctionMetricBucket & {
1528
+ path: string;
1529
+ })[];
1530
+ /**
1531
+ * True when more rows existed than {@link FUNCTION_METRICS_READ_LIMIT} could
1532
+ * return, so `buckets` is a partial (newest) window rather than the app's
1533
+ * full retained history. Mirrors `readQueryInsights`'s `capped` and
1534
+ * `foldTraces`'s `total`: a silently truncated read looks identical to a
1535
+ * complete one to a caller that doesn't check for it — the Metrics chart's
1536
+ * window would appear to shrink as the app grows, with a wrong leftmost
1537
+ * bar, and nothing would say why.
1538
+ */
1539
+ truncated: boolean;
1540
+ }
817
1541
  /** One declared index a dispatch exercised (used to narrow a read). */
818
1542
  interface IndexHit {
819
1543
  /** The declared index name. */
@@ -830,8 +1554,15 @@ interface FunctionMetricIndexHit {
830
1554
  /** The table the index is declared on. */
831
1555
  table: string;
832
1556
  }
833
- /** Fields recorded for one completed dispatch. `errored` advances the failure counters. */
1557
+ /**
1558
+ * Fields recorded for one completed dispatch, or for a coalesced delta of
1559
+ * several. `errored` advances the failure counters. The optional count-carrying
1560
+ * fields let a caller that batched N dispatches write their exact sum in one
1561
+ * upsert; omitted, every field defaults to the single-dispatch value.
1562
+ */
834
1563
  interface RecordFunctionMetricInput {
1564
+ /** Dispatches this record stands for. Default `1`. */
1565
+ calls?: number;
835
1566
  /**
836
1567
  * Whether the dispatch failed on an optimistic-concurrency (OCC) write
837
1568
  * conflict — a compare-and-swap that lost to a concurrent commit. Advances
@@ -840,12 +1571,29 @@ interface RecordFunctionMetricInput {
840
1571
  * Omitted/false on the common path, keeping the hot path unchanged.
841
1572
  */
842
1573
  conflicted?: boolean;
1574
+ /** Conflicts in a coalesced delta. Default `conflicted ? 1 : 0`. */
1575
+ conflicts?: number;
1576
+ /** Longest handler time in a coalesced delta. Default `durationMs`. */
1577
+ durationMaxMs?: number;
1578
+ /** Shortest handler time in a coalesced delta. Default `durationMs`. */
1579
+ durationMinMs?: number;
843
1580
  /** Wall-clock millis the handler took. */
844
1581
  durationMs: number;
1582
+ /** Summed handler time of a coalesced delta. Default `durationMs`. */
1583
+ durationTotalMs?: number;
845
1584
  /** Whether the dispatch threw. */
846
1585
  errored: boolean;
847
1586
  /** Most recent failure message, recorded only when `errored`. */
848
1587
  errorMessage?: string;
1588
+ /** Failed dispatches in a coalesced delta. Default `errored ? 1 : 0`. */
1589
+ errors?: number;
1590
+ /**
1591
+ * Per-`(table, index)` hit counts of a coalesced delta (one per dispatch that
1592
+ * used the index). When set, replaces {@link RecordFunctionMetricInput.indexHits}.
1593
+ */
1594
+ indexHitCounts?: ReadonlyArray<IndexHit & {
1595
+ count: number;
1596
+ }>;
849
1597
  /**
850
1598
  * Distinct declared indexes this dispatch exercised (used to narrow a read),
851
1599
  * collected from the `onIndexUse` signal. Each entry bumps the
@@ -854,8 +1602,18 @@ interface RecordFunctionMetricInput {
854
1602
  * dispatch used no declared index, keeping the hot path unchanged.
855
1603
  */
856
1604
  indexHits?: ReadonlyArray<IndexHit>;
857
- /** The `&lt;file>:&lt;function>` identifier. */
1605
+ /** Epoch-ms of the latest failure in a coalesced delta. Default `errored ? ts : null`. */
1606
+ lastErrorAt?: number | null;
1607
+ /** The `<file>:<function>` identifier. */
858
1608
  path: string;
1609
+ /**
1610
+ * Per-table full-scan counts of a coalesced delta (one per dispatch that
1611
+ * scanned the table). When set, replaces {@link RecordFunctionMetricInput.scannedTables}.
1612
+ */
1613
+ scanCounts?: ReadonlyArray<{
1614
+ count: number;
1615
+ table: string;
1616
+ }>;
859
1617
  /**
860
1618
  * Distinct tables this dispatch full-scanned (read with no index / point
861
1619
  * lookup), collected from the `SCAN_DEP` reads. Each entry bumps the
@@ -879,7 +1637,9 @@ interface RecordFunctionMetricInput {
879
1637
  * than baked into the `CREATE` so a shard whose `__lunora_metrics` predates the
880
1638
  * causal-attribution feature gains the column on the next call without a
881
1639
  * migration. SQLite has no `ADD COLUMN IF NOT EXISTS`, so the duplicate-column
882
- * error from a re-run is swallowed.
1640
+ * error from a re-run is swallowed. Both the `CREATE`s and the back-fill only
1641
+ * run once per handle (see {@link ensuredHandles}) — a handle already marked
1642
+ * ensured returns immediately.
883
1643
  */
884
1644
  declare const ensureFunctionMetricsTables: (sql: SqlExec) => void;
885
1645
  /**
@@ -934,18 +1694,21 @@ declare const readFunctionMetrics: (sql: SqlExec) => FunctionCallStat[];
934
1694
  /**
935
1695
  * Read the coarse time-series buckets for `path` (every path when omitted),
936
1696
  * oldest-bucket first so a chart can plot them left-to-right. Creates the table
937
- * first so reads on a never-called shard return `[]`.
1697
+ * first so reads on a never-called shard return `{ buckets: [], truncated: false }`.
938
1698
  */
939
- declare const readFunctionMetricBuckets: (sql: SqlExec, path?: string) => (FunctionMetricBucket & {
940
- path: string;
941
- })[];
1699
+ declare const readFunctionMetricBuckets: (sql: SqlExec, path?: string) => FunctionMetricBucketsResult;
942
1700
  /**
943
1701
  * Aggregate the persisted accumulators into the lifetime totals the metrics
944
- * health snapshot reports: total calls (`requests`), total `errors`, and the
945
- * earliest `last_called_at` seen — a best-effort "since" marker for durable
946
- * data. Returns zeroes on a never-called shard.
1702
+ * health snapshot reports: total calls (`requests`), total `errors`. Returns
1703
+ * zeroes on a never-called shard.
1704
+ *
1705
+ * `capped` is true when the distinct-path cap ({@link FUNCTION_METRICS_MAX_PATHS})
1706
+ * has been reached — the write-side signal that a brand-new function path is
1707
+ * currently being refused (see `admitPath`), mirroring `readQueryInsights`'s
1708
+ * `capped` for query-metrics and `readMetricHistory`'s for metric-history.
947
1709
  */
948
1710
  declare const readFunctionMetricsTotals: (sql: SqlExec) => {
1711
+ capped: boolean;
949
1712
  errors: number;
950
1713
  requests: number;
951
1714
  };
@@ -978,7 +1741,7 @@ interface AiRunBinding {
978
1741
  }
979
1742
  /** Parsed `__lunora_admin__:explainIssue` payload: the folded Issue's identifying facts, plus an optional model override. */
980
1743
  interface ExplainIssueArgs {
981
- /** The Issue's culprit (`&lt;file>:&lt;function>` or `container:&lt;name>`), for grounding context. */
1744
+ /** The Issue's culprit (`<file>:<function>` or `container:<name>`), for grounding context. */
982
1745
  culprit?: string;
983
1746
  /** Per-request model-id override; falls back to the caller's `defaultModel`, then {@link DEFAULT_EXPLAIN_ISSUE_MODEL}. */
984
1747
  model?: string;
@@ -1048,67 +1811,20 @@ type ExplainIssueResult = ExplainIssueDegraded | ExplainIssueSuccess;
1048
1811
  * `sampleMessage` alone left `title`/`culprit` as an open door onto the same
1049
1812
  * prompt budget.
1050
1813
  */
1051
- declare const parseExplainIssueArgs: (args: Record<string, unknown>) => ExplainIssueArgs;
1052
- /**
1053
- * Run the full explain flow for one Issue: validate the payload, ground it in the
1054
- * catalog, and — when `binding` is a usable Workers AI binding — ask the model for
1055
- * a plain-language rewrite. Never throws for an AI-side failure; every such path
1056
- * returns the `degraded: true` arm carrying the grounded hint, so the caller
1057
- * always has something to render. Only a malformed payload throws (a 400).
1058
- *
1059
- * `binding` is `unknown` so the caller can hand over `env.AI` untyped — the shape
1060
- * check lives here rather than at each call site.
1061
- */
1062
- declare const explainIssue: (binding: unknown, args: Record<string, unknown>, options?: {
1063
- defaultModel?: string;
1064
- }) => Promise<ExplainIssueResult>;
1065
- /** Reserved table holding one triage-state row per Issue fingerprint. Auto-hidden by the `__lunora` prefix. */
1066
- declare const ISSUE_STATE_TABLE = "__lunora_issue_state__";
1067
- /**
1068
- * Triage status of an Issue. `open` is the implicit default (no state row); a
1069
- * developer moves it to `resolved` (fixed, but a *new* matching error re-opens
1070
- * it — see {@link readIssueStates}'s consumer) or `ignored` (deliberately muted,
1071
- * and stays muted regardless of new occurrences).
1072
- */
1073
- type IssueStatus = "ignored" | "open" | "resolved";
1074
- /** Ordered severity a developer can tag an Issue with; drives the Studio badge palette. */
1075
- type IssueSeverity = "critical" | "high" | "low" | "medium";
1076
- /** The persisted triage state for one Issue fingerprint. */
1077
- interface IssueState {
1078
- /** Free-form assignee (a userId or a name); absent when unassigned. */
1079
- assignee?: string;
1080
- /** Stable 16-char fingerprint hash — the same key `readErrorIssues` folds on. */
1081
- hash: string;
1082
- /** Developer-tagged severity; absent when untriaged. */
1083
- severity?: IssueSeverity;
1084
- /** Current triage status. */
1085
- status: IssueStatus;
1086
- /** Wall-clock millis the state was last changed — compared against an Issue's `lastSeen` to detect a regression. */
1087
- updatedAt: number;
1088
- /** Acting userId that last changed the state, when known. */
1089
- updatedBy?: string;
1090
- }
1091
- /** Patch applied by an admin write; every field is optional so a caller can change one facet at a time. */
1092
- interface IssueStatePatch {
1093
- assignee?: null | string;
1094
- severity?: IssueSeverity | null;
1095
- status?: IssueStatus;
1096
- }
1097
- /** The valid {@link IssueStatus} values, for arg validation at the admin boundary. */
1098
- declare const ISSUE_STATUSES: ReadonlyArray<IssueStatus>;
1099
- /** The valid {@link IssueSeverity} values, for arg validation at the admin boundary. */
1100
- declare const ISSUE_SEVERITIES: ReadonlyArray<IssueSeverity>;
1814
+ declare const parseExplainIssueArgs: (args: Record<string, unknown>) => ExplainIssueArgs;
1101
1815
  /**
1102
- * Apply a triage patch to one Issue, upserting its state row. A `null` in the
1103
- * patch clears the field (unassign, untag severity); an omitted field is left
1104
- * unchanged. Returns the resulting {@link IssueState} so the caller can echo it.
1816
+ * Run the full explain flow for one Issue: validate the payload, ground it in the
1817
+ * catalog, and — when `binding` is a usable Workers AI binding — ask the model for
1818
+ * a plain-language rewrite. Never throws for an AI-side failure; every such path
1819
+ * returns the `degraded: true` arm carrying the grounded hint, so the caller
1820
+ * always has something to render. Only a malformed payload throws (a 400).
1105
1821
  *
1106
- * Uses `ON CONFLICT(hash) DO UPDATE` with `COALESCE(?, column)` per optional
1107
- * field so a partial patch touches only what it names — except the explicit
1108
- * `null` sentinels for assignee/severity, which are threaded separately so a
1109
- * clear can win over `COALESCE`.
1822
+ * `binding` is `unknown` so the caller can hand over `env.AI` untyped — the shape
1823
+ * check lives here rather than at each call site.
1110
1824
  */
1111
- declare const upsertIssueState: (sql: SqlExec, hash: string, patch: IssueStatePatch, updatedAt: number, updatedBy?: string) => IssueState;
1825
+ declare const explainIssue: (binding: unknown, args: Record<string, unknown>, options?: {
1826
+ defaultModel?: string;
1827
+ }) => Promise<ExplainIssueResult>;
1112
1828
  /**
1113
1829
  * Severity of a buffered log entry — the full seven-tier `ctx.log` ramp
1114
1830
  * (`trace`→`fatal`), not a console-shaped subset. The buffer used to fold the
@@ -1127,13 +1843,15 @@ type LogLevel = ContextLogLevel;
1127
1843
  */
1128
1844
  interface LogEntry {
1129
1845
  exitCode?: number;
1130
- /** Structured fields from a `ctx.log.&lt;level>(message, fields)` / `ctx.log.with(fields)` call, when present. */
1846
+ /** Structured fields from a `ctx.log.<level>(message, fields)` / `ctx.log.with(fields)` call, when present. */
1131
1847
  fields?: Record<string, unknown>;
1132
1848
  functionPath?: string;
1133
1849
  instance?: string;
1134
1850
  level: LogLevel;
1135
1851
  message: string;
1136
1852
  timestamp: number;
1853
+ /** Trace the line was emitted under; absent outside a dispatch (container lifecycle, hibernation-path errors). What the Studio joins a log line to its waterfall on. */
1854
+ traceId?: string;
1137
1855
  }
1138
1856
  /**
1139
1857
  * A bounded, in-memory ring buffer of recent {@link LogEntry} records.
@@ -1154,10 +1872,21 @@ declare class LogBuffer {
1154
1872
  /** Backing store, kept in insertion order (oldest first). */
1155
1873
  private readonly buffer;
1156
1874
  private readonly capacity;
1875
+ /** How many entries the ring has evicted since it was last cleared. */
1876
+ private droppedCount;
1157
1877
  constructor(capacity?: number);
1878
+ /**
1879
+ * Entries evicted for capacity since the last {@link LogBuffer.clear}.
1880
+ *
1881
+ * Without it a full ring is indistinguishable from a quiet instance that
1882
+ * happened to log exactly `capacity` lines: the reader sees 500 entries
1883
+ * either way and cannot tell whether 500 lines happened or 50,000 did. The
1884
+ * count is what turns "the newest 500" into an honest statement.
1885
+ */
1886
+ get dropped(): number;
1158
1887
  /** Number of entries currently buffered. */
1159
1888
  get size(): number;
1160
- /** Drop every buffered entry. */
1889
+ /** Drop every buffered entry, including the eviction count. */
1161
1890
  clear(): void;
1162
1891
  /**
1163
1892
  * Snapshot of the buffered entries, **newest first** so the panel renders
@@ -1261,6 +1990,17 @@ interface MetricHistorySeries {
1261
1990
  }
1262
1991
  /** {@link readMetricHistory} result: every tracked series with its buckets. */
1263
1992
  interface MetricHistoryResult {
1993
+ /**
1994
+ * True when the distinct-series cap has been reached — a **write-side**
1995
+ * signal ("this shard can no longer admit a brand-new series", see
1996
+ * `admitNewSeries`), not a read-side truncation flag. It is computed over
1997
+ * the whole table regardless of `options.sinceMs`/the row-count read
1998
+ * limit, so it can be `true` even when every series `readMetricHistory`
1999
+ * actually returned fits comfortably: the caller should read it as "a
2000
+ * flood of new series would currently be refused", the same thing
2001
+ * `readQueryInsights`'s `capped` already signals for query-metrics.
2002
+ */
2003
+ capped: boolean;
1264
2004
  series: MetricHistorySeries[];
1265
2005
  }
1266
2006
  /**
@@ -1269,7 +2009,14 @@ interface MetricHistoryResult {
1269
2009
  * omitted field keeps the historical behaviour.
1270
2010
  */
1271
2011
  interface MetricHistoryOptions {
1272
- /** Distinct series tracked before a brand-new one is dropped (default {@link METRIC_HISTORY_MAX_SERIES}). */
2012
+ /**
2013
+ * Distinct series tracked before a brand-new one is REFUSED admission
2014
+ * (default {@link METRIC_HISTORY_MAX_SERIES}). Nothing is evicted: an
2015
+ * already-tracked series keeps accumulating past the cap, and a flood of
2016
+ * one-off series cannot displace the app's real ones — see
2017
+ * {@link admitNewSeries}. `readMetricHistory`'s `capped` flag is the
2018
+ * read-side signal that admission is being refused.
2019
+ */
1273
2020
  maxSeries?: number;
1274
2021
  /** Minute-buckets kept per series before older rows are trimmed (default {@link METRIC_HISTORY_BUCKET_RETENTION}). */
1275
2022
  retentionBuckets?: number;
@@ -1306,9 +2053,12 @@ declare const recordMetricHistory: (sql: SqlExec, event: MetricEvent, exemplarTr
1306
2053
  * trend line reads oldest→newest.
1307
2054
  *
1308
2055
  * `options.sinceMs`, when set, returns only buckets at or after this epoch-ms —
1309
- * the studio's time-window selector.
2056
+ * the studio's time-window selector. `options.maxSeries`, mirroring the write
2057
+ * side's tunable, is only used to compute `capped` — it does not affect which
2058
+ * rows are read.
1310
2059
  */
1311
2060
  declare const readMetricHistory: (sql: SqlExec, options?: {
2061
+ maxSeries?: number;
1312
2062
  sinceMs?: number;
1313
2063
  }) => MetricHistoryResult;
1314
2064
  /** One row of the `__lunora_metrics_queries` table, as returned by `readQueryMetrics`. */
@@ -1317,13 +2067,15 @@ interface QueryStatEntry {
1317
2067
  execCount: number;
1318
2068
  /** Normalised SQL text (literals stripped, truncated). */
1319
2069
  normalizedSql: string;
1320
- /** Total rows read across all executions (SELECT result sizes). */
2070
+ /** Total rows SCANNED across all executions (the billed number, not the result-set size). */
1321
2071
  rowsRead: number;
1322
- /** Total rows written across all executions. */
2072
+ /** Total rows WRITTEN across all executions. */
1323
2073
  rowsWritten: number;
1324
2074
  /** Total wall-clock milliseconds across all executions. */
1325
2075
  totalDurationMs: number;
1326
2076
  }
2077
+ /** Index of the first histogram edge at or above `durationMs`; the last index is the overflow bucket. */
2078
+ declare const latencyBucketIndex: (durationMs: number) => number;
1327
2079
  /** One statement's activity within a chosen time range. */
1328
2080
  interface QueryInsightEntry {
1329
2081
  /** Mean milliseconds per execution across the range. */
@@ -1369,243 +2121,29 @@ interface QueryInsightsResult {
1369
2121
  */
1370
2122
  declare const readQueryInsights: (sql: SqlExec, rangeMs: number, now?: number) => QueryInsightsResult;
1371
2123
  /**
1372
- * Record one statement execution. Creates the table on first call. Silently
2124
+ * Record one statement's activity. Creates the table on first call. Silently
1373
2125
  * skips recording when the normalised statement is empty (shouldn't happen
1374
2126
  * in practice) or when the table is already at the
1375
2127
  * {@link QUERY_METRICS_MAX_STATEMENTS} cap and the statement is not yet
1376
- * tracked. The cap check is a single cheap `COUNT(*)` on the primary-key
1377
- * index, so the hot-path cost is minimal.
2128
+ * tracked. See `admitStatement` for how the cap check avoids an unconditional
2129
+ * `COUNT(*)` on every execution.
2130
+ *
2131
+ * `execCount` (default 1) lets a caller fold several executions of the SAME
2132
+ * statement into one call — `shard-do.ts` does this per dispatch so a
2133
+ * query-in-a-loop handler pays one upsert here instead of one per raw
2134
+ * execution. `durationMs`/`rowsRead`/`rowsWritten` are then the SUM across
2135
+ * `execCount` executions, exactly as `exec_count`/`total_duration_ms` already
2136
+ * accumulate sums across separate calls — folding before calling is
2137
+ * indistinguishable, from this table's point of view, from `execCount`
2138
+ * separate calls with the same totals.
1378
2139
  */
1379
- declare const recordQueryMetric: (sql: SqlExec, rawSql: string, durationMs: number, rowsRead: number, rowsWritten: number, now?: number) => void;
2140
+ declare const recordQueryMetric: (sql: SqlExec, rawSql: string, durationMs: number, rowsRead: number, rowsWritten: number, now?: number, execCount?: number) => void;
1380
2141
  /**
1381
2142
  * Read all tracked statement aggregates, ordered by `total_duration_ms DESC`
1382
2143
  * (the leaderboard's default). Creates the table first so a read on a
1383
2144
  * never-called shard returns `[]`.
1384
2145
  */
1385
2146
  declare const readQueryMetrics: (sql: SqlExec) => QueryStatEntry[];
1386
- /** Reserved append-only table backing the studio Logs tab. Auto-hidden from the data browser by the `__lunora` prefix. */
1387
- declare const REQUEST_LOG_TABLE = "__lunora_reqlog__";
1388
- /** Outcome of one dispatch — `ok` for a returned result, `error` for a thrown handler. */
1389
- type RequestOutcome = "error" | "ok";
1390
- /** One recorded `/rpc` dispatch, in monotonic `seq` order. */
1391
- interface RequestLogEntry {
1392
- /** Whether the result was served from the reactive cache; `undefined` when the cache is disabled or the path isn't cached (a write/action). */
1393
- cacheHit?: boolean;
1394
- /** Handler wall-clock duration in milliseconds (before the subscription write-flush, matching the per-function metrics). */
1395
- durationMs: number;
1396
- /** Error message when `outcome === "error"`; absent on success. */
1397
- errorMessage?: string;
1398
- /** The `&lt;file>:&lt;function>` identifier dispatched, e.g. `messages:list`. */
1399
- functionPath: string;
1400
- /** Identity-claim envelope forwarded by the runtime, JSON-decoded; leaf values are redacted (the claims are PII), so only the shape survives. Absent for anonymous requests. Correlate on `userId` instead. */
1401
- identity?: Record<string, unknown>;
1402
- /** `ok` for a returned result, `error` for a thrown handler. */
1403
- outcome: RequestOutcome;
1404
- /** Call args with leaf values redacted by default (keys/shape preserved); absent when no args were sent. */
1405
- redactedArgs?: unknown;
1406
- /** Monotonic per-shard cursor — strictly increasing, never reused. */
1407
- seq: number;
1408
- /** Shard key (the DO id name), or `undefined` for the unnamed `__root__` DO. */
1409
- shardKey?: string;
1410
- /** Count of subscriptions re-run by the write this dispatch triggered; `0` when none (or not measured at the dispatch site). */
1411
- subscriptionsReRun: number;
1412
- /** Tables the handler read (from the dependency tracker); empty when the reactive cache is off or the path read nothing. */
1413
- tablesRead: string[];
1414
- /** Tables the handler wrote (from the change tracker); empty for a read-only dispatch. */
1415
- tablesWritten: string[];
1416
- /** Wall-clock millis when the dispatch completed. */
1417
- ts: number;
1418
- /** Acting userId forwarded by the runtime, or `undefined` when anonymous. */
1419
- userId?: string;
1420
- }
1421
- /** Fields accepted when appending one request-log entry; `seq` is assigned by the table. */
1422
- interface AppendRequestLogEntry {
1423
- cacheHit?: boolean;
1424
- durationMs: number;
1425
- errorMessage?: string;
1426
- functionPath: string;
1427
- identity?: Record<string, unknown>;
1428
- outcome: RequestOutcome;
1429
- redactedArgs?: unknown;
1430
- shardKey?: string;
1431
- subscriptionsReRun?: number;
1432
- tablesRead?: string[];
1433
- tablesWritten?: string[];
1434
- ts: number;
1435
- userId?: string;
1436
- }
1437
- /** Knobs the dispatch site threads into a request-log write. */
1438
- interface RequestLogWriteOptions {
1439
- /** When `true` (development only), skip args/identity redaction so a developer sees raw values. Defaults to `false` (production-safe). */
1440
- captureRaw?: boolean;
1441
- /** Rows to keep after the append-time trim; defaults to {@link REQUEST_LOG_RETENTION}. The operator's `LUNORA_REQUEST_LOG_RETENTION` override. */
1442
- retention?: number;
1443
- }
1444
- /** Filters for {@link readRequestLog}, all AND-combined; every value is a bound SQL parameter, so nothing here injects SQL. */
1445
- interface ReadRequestLogOptions {
1446
- /** Functions whose path begins with this prefix (a `&lt;file>:` or `&lt;file>:&lt;fn>` correlation). */
1447
- functionPathPrefix?: string;
1448
- /** Upper bound on returned rows, clamped to [1, 10000]. */
1449
- limit?: number;
1450
- /** Keep only `ok` / `error` outcomes. */
1451
- outcome?: RequestOutcome;
1452
- /** Exact shard-key match. */
1453
- shardKey?: string;
1454
- /** Only entries strictly after this cursor (forward paging). */
1455
- sinceSeq?: number;
1456
- /** Keep only entries whose read OR written table set contains this table. */
1457
- tableTouched?: string;
1458
- /** Exact acting-userId match. */
1459
- userId?: string;
1460
- }
1461
- /** Payload of a `__lunora_admin__:getRequestLog` call: the recorded entries, newest first. */
1462
- interface RequestLogResult {
1463
- entries: RequestLogEntry[];
1464
- }
1465
- /**
1466
- * One grouped error **Issue**: many `error`-outcome request-log rows that share a
1467
- * fingerprint folded into a single triage row. The `hash` is the same stable key
1468
- * a cloud Incident groups on, so a local Issue and a cloud Incident are the same
1469
- * object.
1470
- */
1471
- interface ErrorIssue {
1472
- /** Assignee (a userId or a name) from the persisted triage state; absent when unassigned. */
1473
- assignee?: string;
1474
- /** Number of `error` rows folded into this Issue within the scanned window. */
1475
- count: number;
1476
- /** The `&lt;file>:&lt;function>` (or `container:&lt;name>`) the errors came from. */
1477
- culprit: string;
1478
- /** Wall-clock millis of the oldest folded row. */
1479
- firstSeen: number;
1480
- /** Stable 16-char grouping hash over `functionPath :: bucket(message)`. */
1481
- hash: string;
1482
- /** Wall-clock millis of the newest folded row. */
1483
- lastSeen: number;
1484
- /** A representative raw error message — taken from the most recent folded row. */
1485
- sampleMessage: string;
1486
- /** Developer-tagged severity from the persisted triage state; absent when untriaged. */
1487
- severity?: IssueSeverity;
1488
- /**
1489
- * Wall-clock millis the persisted triage state was last changed; absent when
1490
- * the Issue has never been triaged. Compared against `lastSeen` to detect a
1491
- * regression (a new error after a resolve).
1492
- */
1493
- stateUpdatedAt?: number;
1494
- /**
1495
- * Triage status folded in from the persisted state (`open` by default). A
1496
- * `resolved` Issue whose `lastSeen` is newer than `stateUpdatedAt` is
1497
- * auto-reopened to `open` here (a regression), so a fresh occurrence never
1498
- * hides behind a stale resolution; `ignored` stays sticky by design.
1499
- */
1500
- status: IssueStatus;
1501
- /** Human-readable title (first line of the sample message, capped). */
1502
- title: string;
1503
- }
1504
- /** Payload of a `__lunora_admin__:getIssues` call: grouped error Issues, most-recently-active first. */
1505
- interface IssuesResult {
1506
- issues: ErrorIssue[];
1507
- }
1508
- /** Filters for {@link readErrorIssues}; forwarded to {@link readRequestLog} with `outcome` forced to `error`. */
1509
- interface ReadIssuesOptions {
1510
- /** Functions whose path begins with this prefix (a `&lt;file>:` or `&lt;file>:&lt;fn>` correlation). */
1511
- functionPathPrefix?: string;
1512
- /** Upper bound on error rows scanned before grouping, clamped to [1, 10000]. */
1513
- limit?: number;
1514
- /** Exact shard-key match. */
1515
- shardKey?: string;
1516
- /** Keep only Issues in this triage status, applied AFTER the persisted-state fold + auto-reopen. */
1517
- status?: IssueStatus;
1518
- /** Exact acting-userId match. */
1519
- userId?: string;
1520
- }
1521
- /**
1522
- * Create the `__lunora_reqlog__` table. `seq` is an `AUTOINCREMENT` primary
1523
- * key, giving each shard a monotonic cursor the Logs tab pages through; the
1524
- * `args`/`identity`/`tables_read`/`tables_written` columns hold JSON and are
1525
- * `NULL`/empty when none was recorded. Idempotent, so read and write paths can
1526
- * call it defensively.
1527
- */
1528
- declare const ensureRequestLogTable: (sql: SqlExec) => void;
1529
- /**
1530
- * Append one dispatch to the request log, then trim the log back to the most
1531
- * recent `retention` rows (default {@link REQUEST_LOG_RETENTION}). Creates the
1532
- * table first so callers needn't. Args/identity are redacted here so a raw value
1533
- * never reaches the durable table — callers pass the unredacted entry and rely on
1534
- * this, unless `captureRaw` (dev only) is set. `retention` is the operator's
1535
- * `LUNORA_REQUEST_LOG_RETENTION` override, threaded in by the dispatch site.
1536
- */
1537
- declare const appendRequestLogEntry: (sql: SqlExec, entry: AppendRequestLogEntry, options?: RequestLogWriteOptions) => void;
1538
- /**
1539
- * Emit one structured request event to `console` so Cloudflare's Workers Logs /
1540
- * Logpush pipeline carries it to external sinks (SIEMs) — PLAN3 §3.3. This does
1541
- * NOT reimplement a transport: it produces a richer, lunora-attributed event and
1542
- * lets CF's existing trace-log pipe ship it. The event mirrors the durable
1543
- * `__lunora_reqlog__` row (function path, shard, user, outcome, duration, tables
1544
- * read/written, cache hit), with `args` AND `identity` redacted exactly like the
1545
- * durable write so no raw PII/secret reaches the log pipeline.
1546
- *
1547
- * An `error` outcome goes to `console.error` (surfacing at error level in the
1548
- * trace so a SIEM can alert on it); everything else to `console.log`. The
1549
- * `source: "lunora"` / `type: "request"` envelope lets a consumer filter these
1550
- * events out of the raw Workers-trace firehose. `captureRaw` (dev only) skips
1551
- * redaction, mirroring the durable write. Best-effort by contract — the caller
1552
- * wraps it so a serialization hiccup can never fail the served request.
1553
- */
1554
- declare const emitRequestLogEvent: (entry: AppendRequestLogEntry, options?: RequestLogWriteOptions) => void;
1555
- /**
1556
- * The `ctx.log` event contract (shape + severity union) lives in
1557
- * `shared/log-event.ts` (inlined into each `dist`) so the DO that builds these
1558
- * events and the `@lunora/runtime` sink that consumes them agree by construction.
1559
- * `LogEventInput` is the DO's historical name for the shared `LogEvent`.
1560
- */
1561
- type LogEventInput = LogEvent;
1562
- /**
1563
- * Split a `ctx.log.&lt;level>(...)` call's raw arguments into a display `message`
1564
- * and optional structured `fields`. The structured form — a message string plus
1565
- * a plain-object fields bag — is matched only for exactly `(string, object)`;
1566
- * every other shape is console-style and rendered whole (so existing
1567
- * `console`-shaped calls are unchanged). Bound `.with(...)` fields merge under
1568
- * the per-call fields (per-call wins); the result is normalized to a fresh bag
1569
- * of JSON-safe primitives, or `undefined` when empty (see `normalizeLogFields`).
1570
- */
1571
- declare const parseLogArgs: (args: unknown[], boundFields?: LogFields) => {
1572
- fields?: LogFields;
1573
- message: string;
1574
- };
1575
- /**
1576
- * Emit one application-log event from a `ctx.log.*` call to `console`, tagged
1577
- * `{ source: "lunora", type: "log" }` so the CLI / Vite formatter can pretty-print
1578
- * it in the dev terminal and a Logpush/SIEM consumer can filter it out of the
1579
- * raw Workers-trace firehose.
1580
- *
1581
- * Only the rendered `message` is emitted here, NOT the structured `args` array:
1582
- * the console event rides CF Workers Logs / Logpush to prod, and shipping raw,
1583
- * un-redacted arg objects on a `source: "lunora"` line a SIEM is told to trust
1584
- * would be a surprising PII/secret surface. The raw `args` stay on the in-process
1585
- * `sink.onLog` path (`recordUserLog`), which the operator opts into and controls.
1586
- * `message` already carries the developer's rendered values, exactly like a raw
1587
- * `console.log` line.
1588
- *
1589
- * `error`/`fatal` go to `console.error`, `warn` to `console.warn` (so they
1590
- * surface at the right level in the trace); every other level to `console.log`.
1591
- *
1592
- * Structured `fields` (plus `traceId`/`spanId` for correlation) ARE emitted here
1593
- * — they are intentional metadata a log pipeline filters on, unlike raw `args`.
1594
- * A field value that can't be serialised (a circular object) would make
1595
- * `JSON.stringify` throw and drop the whole line, so serialisation falls back to
1596
- * a fields-free line rather than losing the event.
1597
- */
1598
- declare const emitLogEvent: (input: LogEventInput) => void;
1599
- /**
1600
- * Read request-log entries newest-first, AND-combining the supplied filters
1601
- * (function-path prefix, exact userId/shardKey/outcome, and a table-touched
1602
- * match against the read OR written table sets), up to `limit` (clamped to
1603
- * [1, 10000]). Each value is a bound parameter, so no filter can inject SQL.
1604
- * Creates the table first so reads on a never-logged shard return `[]` instead
1605
- * of throwing. Mirrors `readAuditLog`/`readCdcChanges`.
1606
- */
1607
- declare const readRequestLog: (sql: SqlExec, options?: ReadRequestLogOptions) => RequestLogEntry[];
1608
- declare const readErrorIssues: (sql: SqlExec, options?: ReadIssuesOptions) => ErrorIssue[];
1609
2147
  /**
1610
2148
  * Ordering/visual weight of a security finding — mirrors the studio's insight
1611
2149
  * severities so the Security Advisor and the Performance Advisor (Insights) share
@@ -1620,7 +2158,7 @@ type SecurityFindingLevel = "error" | "info" | "warning";
1620
2158
  *
1621
2159
  * `admin-token-weak`: `LUNORA_ADMIN_TOKEN` is set but short enough to be brute-forceable. (An *unset* token disables admin introspection entirely, so this audit — itself admin-gated — only ever runs with a token present.)
1622
2160
  *
1623
- * `ws-gate-open`: admin HTTP RPCs require the bearer, but `LUNORA_WS_BEARER` is unset so the WebSocket upgrade gate defaults open — live admin subscriptions (Logs, Metrics, …) are reachable without a credential.
2161
+ * `ws-gate-open`: `LUNORA_WS_BEARER` is unset, so the WebSocket upgrade gate defaults open and anyone who can reach the worker can open a socket and run ordinary USER subscriptions (whatever `ctx.auth` / RLS then allows them to read). Admin subscriptions are NOT part of this: they require the socket's `admin` stamp, which the upgrade sets only from `LUNORA_ADMIN_TOKEN` or a minted admin sub-token, so an unset `LUNORA_WS_BEARER` never exposes Logs/Metrics/introspection. Which is why this is a posture finding about the app's own live-query surface, not an admin hole — set the var when subscribers are expected to present a shared credential.
1624
2162
  *
1625
2163
  * `dev-args-unredacted`: the worker reports a development environment, so the durable request log captures raw, un-redacted args and identity (PII). A production deploy mislabeled as dev would persist sensitive payloads.
1626
2164
  *
@@ -1692,6 +2230,15 @@ interface TraceSpan {
1692
2230
  message: string;
1693
2231
  type: string;
1694
2232
  };
2233
+ /**
2234
+ * Timestamped occurrences inside the span — `span.addEvent(...)` and
2235
+ * `span.recordException(...)`. Carried through so a handled retry or a
2236
+ * swallowed exception is visible on the span it happened in, which is the
2237
+ * only place it is interpretable. Absent when the body recorded none.
2238
+ */
2239
+ events?: SpanEventPoint[];
2240
+ /** OTel `SpanKind`; absent means `"internal"`. */
2241
+ kind?: OtlpSpanKind;
1695
2242
  name: string;
1696
2243
  /** Start of this span relative to the trace's start, in ms. */
1697
2244
  offsetMs: number;
@@ -1710,12 +2257,25 @@ interface TraceSummary {
1710
2257
  rootName: string;
1711
2258
  shardKey?: string;
1712
2259
  /**
1713
- * Spans ordered by `(offsetMs, depth)`, ready to render as waterfall rows.
1714
- * Start time alone is not enough to order them: spans are recorded on
1715
- * completion and `startTs` has millisecond resolution, so a parent and its
1716
- * child routinely tie. Breaking that tie by depth makes the sequence a valid
1717
- * pre-order traversal of the span tree, so indenting each row by its `depth`
1718
- * yields the nesting without a separate tree walk.
2260
+ * Spans in **pre-order**, ready to render as waterfall rows: every span is
2261
+ * immediately followed by its own subtree, siblings in start order. So
2262
+ * indenting each row by its `depth` yields the real nesting — the row above
2263
+ * a `depth`-`n+1` row is genuinely its parent.
2264
+ *
2265
+ * This is a tree walk, not a sort, because no ordering on `(offsetMs,
2266
+ * depth)` can produce it. Given a parent, its child `a`, `a`'s child `a1`
2267
+ * and `a`'s sibling `b` all at offset 0, that comparator yields
2268
+ * `parent, a, b, a1` — which renders `a1` indented beneath `b`, under a
2269
+ * parent it does not belong to.
2270
+ *
2271
+ * **Why they tie is not millisecond resolution.** On the Workers runtime
2272
+ * `Date.now()` is pinned to the time of the last I/O — a Spectre mitigation,
2273
+ * not a bug — so it does not advance at all across pure computation. Every
2274
+ * duration in this package is `Date.now() - startTs`, which means a span
2275
+ * wrapping CPU-only work reports `0`, and a parent whose child performed no
2276
+ * I/O shares its exact start and end. See `docs/concepts/observability`
2277
+ * ("Span durations on Workers"); the practical consequence is that a `0 ms`
2278
+ * span means "no I/O happened here", not "this was fast".
1719
2279
  */
1720
2280
  spans: TraceSpan[];
1721
2281
  startTs: number;
@@ -1730,20 +2290,34 @@ interface TraceSummary {
1730
2290
  declare class SpanBuffer {
1731
2291
  private readonly buffer;
1732
2292
  private readonly capacity;
2293
+ /**
2294
+ * Buffered span count per trace, so {@link SpanBuffer.hasTrace} — run on
2295
+ * every dispatch, usually a miss against a full ring — is a lookup, not a scan.
2296
+ */
2297
+ private readonly traceCounts;
2298
+ /** How many spans the ring has evicted since it was last cleared. */
2299
+ private droppedCount;
1733
2300
  constructor(capacity?: number);
2301
+ /**
2302
+ * Spans evicted for capacity since the last {@link SpanBuffer.clear}. The
2303
+ * ring silently drops its oldest span once full, which makes a busy instance
2304
+ * look identical to one that recorded exactly `capacity` spans; this count
2305
+ * is the difference between the two.
2306
+ */
2307
+ get dropped(): number;
1734
2308
  /** Number of spans currently buffered. */
1735
2309
  get size(): number;
1736
- /** Drop every buffered span. */
2310
+ /** Drop every buffered span, including the eviction count. */
1737
2311
  clear(): void;
1738
2312
  /** Snapshot of the buffered spans in insertion order. Fresh array per call. */
1739
2313
  entries(): SpanEvent[];
2314
+ /** Whether any buffered span belongs to `traceId`, as it was when pushed. */
2315
+ hasTrace(traceId: string): boolean;
1740
2316
  /**
1741
- * Whether any buffered span belongs to `traceId`. A membership test rather
1742
- * than `entries().some(...)` so the per-dispatch check that decides whether
1743
- * to record a root span doesn't copy the whole ring on every request.
2317
+ * Append a span, evicting the oldest when at capacity. A frozen shallow copy
2318
+ * is stored, never the caller's object (which is shared with the sink and
2319
+ * stays writable), so the span and its `traceCounts` entry cannot diverge.
1744
2320
  */
1745
- hasTrace(traceId: string): boolean;
1746
- /** Append a span, evicting the oldest when at capacity. */
1747
2321
  push(span: SpanEvent): void;
1748
2322
  }
1749
2323
  /** {@link foldTraces} result: the folded waterfalls plus the total distinct traces available before the `limit`. */
@@ -1809,10 +2383,71 @@ declare const findDanglingReferences: (sql: SqlExec, storageColumns: Record<stri
1809
2383
  * worker's trace and any container's beneath it), else freshly minted so a
1810
2384
  * dispatch with no inbound context — a subscription re-run, a server-initiated
1811
2385
  * call — still produces a coherent, self-contained local trace.
2386
+ *
2387
+ * `rayHeader` is the Cloudflare Ray ID the runtime forwarded alongside the
2388
+ * `traceparent` (`x-lunora-ray-id`). It is re-validated here and carried on the
2389
+ * anchor so every span and log line of the dispatch stamps it; absent or
2390
+ * malformed, the anchor simply has none. Informational only — see
2391
+ * {@link parseRayId}.
1812
2392
  */
1813
- declare const resolveTraceAnchor: (traceparent: string | undefined) => {
1814
- rootSpanId: string;
2393
+ declare const resolveTraceAnchor: (traceparent: string | undefined, rayHeader?: null | string) => TraceAnchor & {
1815
2394
  sampled: boolean;
1816
- traceId: string;
1817
2395
  };
1818
- export { AUTH_METRICS_BUCKETS_TABLE, AUTH_METRICS_BUCKET_MS, AUTH_METRICS_BUCKET_RETENTION, AUTH_METRICS_TABLE, type AiRunBinding, type AppendRequestLogEntry, type AuthMetrics, type AuthMetricsBucket, type ContextFetch, type ContextLogLevel, type ContextMetrics, type ContextTracer, DEFAULT_EXPLAIN_ISSUE_MODEL, type DatabaseInstrumentation, type DatabaseTally, type ExplainIssueArgs, type ExplainIssueDegradedReason, type ExplainIssueGrounding, type ExplainIssueResult, FUNCTION_METRICS_BUCKETS_TABLE, FUNCTION_METRICS_BUCKET_MS, FUNCTION_METRICS_BUCKET_RETENTION, FUNCTION_METRICS_INDEX_TABLE, FUNCTION_METRICS_MAX_PATHS, FUNCTION_METRICS_READ_LIMIT, FUNCTION_METRICS_SCANS_TABLE, FUNCTION_METRICS_TABLE, type FunctionMetricBucket, type FunctionMetricIndexHit, type HostTracingLike, ISSUE_SEVERITIES, ISSUE_STATE_TABLE, ISSUE_STATUSES, type IndexHit, type IssueSeverity, type IssueState, type IssueStatePatch, type IssueStatus, type IssuesResult, LogBuffer, type LogEntry, type LogEventInput, type LogLevel, MIN_ADMIN_TOKEN_LENGTH, MIN_AUTH_SECRET_LENGTH, MetricBuffer, type MetricHistoryOptions, type MetricHistoryPoint, type MetricHistorySeries, type MetricSeries, type MetricsDeps, type QueryStatEntry, REQUEST_LOG_TABLE, type RecordAuthEventInput, type RecordFunctionMetricInput, type RequestLogResult, type RequestLogWriteOptions, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, SpanBuffer, type SpanCollection, type SpanCollector, type SpanHandle, type TraceAnchor, type TraceSpan, type TraceSummary, type TracerDeps, appendRequestLogEntry, buildSecurityAudit, createDatabaseTally, createMetrics, createSpanCollector, createTracedFetch, createTracer, dispatchRootSpan, emitLogEvent, emitRequestLogEvent, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureRequestLogTable, explainIssue, findDanglingReferences, foldTraces, formatTally, instrumentDatabase, mergeScanAttribution, parseExplainIssueArgs, parseLogArgs, readAuthMetrics, readErrorIssues, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetricScans, readFunctionMetrics, readFunctionMetricsTotals, readMetricHistory, readQueryInsights, readQueryMetrics, readRequestLog, recordAuthEvent, recordFunctionMetric, recordMetricHistory, recordQueryMetric, resolveTraceAnchor, upsertIssueState };
2396
+ export { AUTH_METRICS_BUCKETS_TABLE, AUTH_METRICS_BUCKET_MS, AUTH_METRICS_BUCKET_RETENTION, AUTH_METRICS_TABLE, type AiRunBinding, type AppendRequestLogEntry,
2397
+ /**
2398
+ * `@lunora/observability` — host-neutral telemetry storage and read models.
2399
+ *
2400
+ * Logs, traces, metrics, issue grouping and the security-audit view: the data
2401
+ * behind the Studio's observability pages. None of it is Cloudflare-specific —
2402
+ * it reads and writes through the SQL handle the engine hands it, and it lived
2403
+ * inside `@lunora/do` only because that is where the Durable Object it
2404
+ * instruments happens to live.
2405
+ *
2406
+ * The dependency runs `@lunora/do` → here → `@lunora/shard-engine`, never the
2407
+ * reverse, which is what makes this reusable by a second host rather than
2408
+ * merely relocated.
2409
+ *
2410
+ * This barrel is deliberately curated rather than `export *`. A star export
2411
+ * would promote every module internal to permanent public API — the exact
2412
+ * mistake `@lunora/do`'s own barrel documents having made once with the search
2413
+ * core. What is exported here is what a consumer actually needs.
2414
+ */
2415
+ type AuthMetrics,
2416
+ /**
2417
+ * `@lunora/observability` — host-neutral telemetry storage and read models.
2418
+ *
2419
+ * Logs, traces, metrics, issue grouping and the security-audit view: the data
2420
+ * behind the Studio's observability pages. None of it is Cloudflare-specific —
2421
+ * it reads and writes through the SQL handle the engine hands it, and it lived
2422
+ * inside `@lunora/do` only because that is where the Durable Object it
2423
+ * instruments happens to live.
2424
+ *
2425
+ * The dependency runs `@lunora/do` → here → `@lunora/shard-engine`, never the
2426
+ * reverse, which is what makes this reusable by a second host rather than
2427
+ * merely relocated.
2428
+ *
2429
+ * This barrel is deliberately curated rather than `export *`. A star export
2430
+ * would promote every module internal to permanent public API — the exact
2431
+ * mistake `@lunora/do`'s own barrel documents having made once with the search
2432
+ * core. What is exported here is what a consumer actually needs.
2433
+ */
2434
+ type AuthMetricsBucket, type ContextFetch, type ContextLogLevel, type ContextMetrics, type ContextTracer, DEFAULT_EXPLAIN_ISSUE_MODEL, type DanglingReference, type DanglingReferenceResult, type DatabaseInstrumentation, type DatabaseTally, type DatabaseTelemetryDeps, type ErrorIssue, type ExplainIssueArgs, type ExplainIssueDegradedReason, type ExplainIssueGrounding, type ExplainIssueResult, FUNCTION_METRICS_BUCKETS_TABLE, FUNCTION_METRICS_BUCKET_MS, FUNCTION_METRICS_BUCKET_RETENTION, FUNCTION_METRICS_INDEX_TABLE, FUNCTION_METRICS_MAX_PATHS, FUNCTION_METRICS_READ_LIMIT, FUNCTION_METRICS_SCANS_TABLE, FUNCTION_METRICS_TABLE, type FoldedTraces, type FunctionMetricBucket, type FunctionMetricBucketsResult, type FunctionMetricIndexHit, type HostSpanLike, type HostTracingLike, type HostTracingResolver, ISSUE_SEVERITIES, ISSUE_STATE_TABLE, ISSUE_STATUSES, type IndexHit, type IssueSeverity, type IssueState, type IssueStatePatch, type IssueStatus, type IssuesResult, LogBuffer, type LogEntry, type LogEventInput, type LogLevel, MIN_ADMIN_TOKEN_LENGTH, MIN_AUTH_SECRET_LENGTH, MetricBuffer, type MetricEvent, type MetricHistoryOptions, type MetricHistoryPoint, type MetricHistoryResult, type MetricHistorySeries, type MetricKind, type MetricSeries, type MetricsDeps, NO_SENSITIVE_SCOPE, type QueryInsightBucket, type QueryInsightEntry, type QueryInsightsResult, type QueryStatEntry, REQUEST_LOG_TABLE, type ReadIssuesOptions, type ReadRequestLogOptions,
2435
+ /**
2436
+ * `@lunora/observability` — host-neutral telemetry storage and read models.
2437
+ *
2438
+ * Logs, traces, metrics, issue grouping and the security-audit view: the data
2439
+ * behind the Studio's observability pages. None of it is Cloudflare-specific —
2440
+ * it reads and writes through the SQL handle the engine hands it, and it lived
2441
+ * inside `@lunora/do` only because that is where the Durable Object it
2442
+ * instruments happens to live.
2443
+ *
2444
+ * The dependency runs `@lunora/do` → here → `@lunora/shard-engine`, never the
2445
+ * reverse, which is what makes this reusable by a second host rather than
2446
+ * merely relocated.
2447
+ *
2448
+ * This barrel is deliberately curated rather than `export *`. A star export
2449
+ * would promote every module internal to permanent public API — the exact
2450
+ * mistake `@lunora/do`'s own barrel documents having made once with the search
2451
+ * core. What is exported here is what a consumer actually needs.
2452
+ */
2453
+ type RecordAuthEventInput, type RecordFunctionMetricInput, type RequestLogEntry, type RequestLogResult, type RequestLogWriteOptions, type RequestOutcome, SENSITIVE_ARG_MASK, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, type SensitiveScope, SpanBuffer, type SpanCollection, type SpanCollector, type SpanEvent, type SpanEventPoint, type SpanHandle, type OtlpSpanKind as SpanKind, type SpanLink, type SpanOptions, type SqlClientLike, type TallySurface, type TraceAnchor, type TraceSpan, type TraceSummary, type TracedFetchDeps, type TracerDeps, appendRequestLogEntry, applyHostRootSpan, buildSecurityAudit, createDatabaseTally, createMetrics, createSensitiveScope, createSpanCollector, createTracedFetch, createTracer, dispatchRootSpan, emitLogEvent, emitRequestLogEvent, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureRequestLogTable, explainIssue, findDanglingReferences, foldTraces, formatTally, instrumentDatabase, instrumentSqlClient, latencyBucketIndex, maskSensitiveArgs, mergeScanAttribution, parseExplainIssueArgs, parseLogArgs, readAuthMetrics, readErrorIssues, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetricScans, readFunctionMetrics, readFunctionMetricsTotals, readMetricHistory, readQueryInsights, readQueryMetrics, readRequestLog, recordAuthEvent, recordFunctionMetric, recordMetricHistory, recordQueryMetric, redactArgs, redactCredentials, resolveTraceAnchor, sensitiveNames, sensitiveValues, setHostSpanAttributes, upsertIssueState };