@lunora/observability 1.0.0-alpha.16 → 1.0.0-alpha.161

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 (44) hide show
  1. package/README.md +2 -4
  2. package/dist/index.d.mts +1161 -682
  3. package/dist/index.d.ts +1161 -682
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/AUTH_METRICS_BUCKETS_TABLE-C-qbQA-w.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-CHV71isV.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-BXUByUZ9.mjs +1 -0
  13. package/dist/packem_shared/SpanBuffer-DnYOc8uk.mjs +1 -0
  14. package/dist/packem_shared/applyHostRootSpan-DToRfMn8.mjs +1 -0
  15. package/dist/packem_shared/createDatabaseTally-BgyXiKtq.mjs +2 -0
  16. package/dist/packem_shared/createMetrics-CJCccwhm.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-B4An9Nuj.mjs +1 -0
  21. package/dist/packem_shared/readMetricHistory-BjPDSBkS.mjs +31 -0
  22. package/dist/packem_shared/request-log-CQL8SsZX.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-DpVJl1bU.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-BXPeggfa.mjs +0 -56
  29. package/dist/packem_shared/ISSUE_SEVERITIES-E91cPcjt.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-DEHWxkC0.mjs +0 -1
  34. package/dist/packem_shared/SpanBuffer-BR6Ff0M-.mjs +0 -1
  35. package/dist/packem_shared/createDatabaseTally-_X8tMObq.mjs +0 -1
  36. package/dist/packem_shared/createMetrics-1k6z1bld.mjs +0 -1
  37. package/dist/packem_shared/findDanglingReferences-D-x9LvY0.mjs +0 -1
  38. package/dist/packem_shared/metric-buffer-CdgXal7w.mjs +0 -1
  39. package/dist/packem_shared/readMetricHistory-BdC01ptv.mjs +0 -31
  40. package/dist/packem_shared/readQueryInsights-BprtfEp-.mjs +0 -32
  41. package/dist/packem_shared/request-log-CHl9HlyL.mjs +0 -21
  42. package/dist/packem_shared/resolveTraceAnchor-IAN8riI0.mjs +0 -1
  43. package/dist/packem_shared/run-sql-BP8BI9zV.mjs +0 -1
  44. package/dist/packem_shared/trace-context-DrdF960P.mjs +0 -1
package/dist/index.d.ts 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,166 +566,700 @@ interface HostTracingLike {
484
566
  * supplies the real resolver, tests a fake or `undefined`.
485
567
  */
486
568
  type HostTracingResolver = () => HostTracingLike | Promise<HostTracingLike | undefined> | undefined;
487
- /** What {@link createTracer} needs from the shard to build a span. */
488
- interface TracerDeps {
489
- /** The trace this ctx's spans belong to. */
490
- anchor: TraceAnchor;
491
- /**
492
- * Whether to record a span body's error message (and a `recordException`
493
- * stacktrace) verbatim rather than redacted. Mirrors the request log's
494
- * `captureRaw`: `true` in dev (`isDevEnvironment`), `false` in production —
495
- * the span pipeline is the one sink third-party collectors (Datadog/Axiom
496
- * via `otlpSink`) receive, so it must not ship raw PII/internals by default
497
- * the way the request log and function-metrics sinks already don't.
498
- */
499
- captureRaw?: boolean;
500
- /** Function path the spans are attributed to. */
501
- functionPath: string;
502
- /**
503
- * **Opt-in, EXPERIMENTAL, default off.** When `true` *and*
504
- * {@link TracerDeps.resolveHostTracing} yields a working
505
- * `tracing.enterSpan`, each `ctx.trace` span is ALSO emitted as a host-native
506
- * **custom span**, so it nests inside CF's native binding/fetch/handler trace
507
- * tree on the hosted path. This only ADDS a CF-side span — the recorded
508
- * {@link SpanEvent} (our `SpanBuffer`/`otlpSink`) is untouched and remains the
509
- * source of truth plus the local studio waterfall. The `enterSpan` call itself
510
- * is now workerd-validated as available and side-effect-free inside a Durable
511
- * Object; CF's exported parent-linking under sampling remains unverified. See
512
- * {@link createTracer} for the double-export and Durable-Object async-context
513
- * caveats.
514
- */
515
- fuseHostSpans?: boolean;
516
- /** Hand a finished span to the buffer + sink. */
517
- record: (span: SpanEvent) => void;
518
- /**
519
- * Injected resolver for CF's `tracing` namespace (see
520
- * {@link HostTracingResolver}). Only consulted when
521
- * {@link TracerDeps.fuseHostSpans} is `true`, so the default path never
522
- * calls it.
523
- */
524
- resolveHostTracing?: HostTracingResolver;
525
- /** Shard key for single-shard calls; absent for the unnamed root DO. */
526
- shardKey: string | undefined;
527
- /** Read lazily — the acting user is resolved per span, not per ctx. */
528
- userId: () => string | undefined;
529
- }
530
- /** What {@link createMetrics} needs from the shard to build a measurement. */
531
- interface MetricsDeps {
532
- functionPath: string;
533
- record: (event: MetricEvent) => void;
534
- shardKey: string | undefined;
535
- }
536
- /** Everything a {@link SpanHandle}'s body attached, ready to merge into the recorded span. */
537
- interface SpanCollection {
538
- attributes: Record<string, LogFields[string]>;
539
- events: SpanEventPoint[];
540
- links: SpanLink[];
541
- }
542
- /** A {@link SpanHandle} plus read access to what it has collected so far. */
543
- interface SpanCollector {
544
- collected: SpanCollection;
545
- handle: SpanHandle;
546
- }
547
569
  /**
548
- * Build a span's post-hoc collection surface: the {@link SpanHandle} handed to a
549
- * `ctx.trace` body, and the bag it writes into.
550
- *
551
- * Factored out because the same surface backs two things — every `ctx.trace`
552
- * span, and the per-dispatch **wide event** (`ctx.span`), where the accumulated
553
- * attributes become the canonical one-event-per-request summary. Sharing the
554
- * implementation is what makes those two feel like the same API instead of two
555
- * that happen to resemble each other.
556
- *
557
- * `captureRaw` (default `false`) gates `recordException`'s `exception.message`/
558
- * `exception.stacktrace` the same way {@link createTracer} gates a span's own
559
- * error message — a stack is file paths and internals by definition, the exact
560
- * class `isInternalCode` redaction exists for, so it rides the same dev-only
561
- * escape hatch rather than shipping to a third-party collector by default.
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.
562
574
  */
563
- declare const createSpanCollector: (ids: {
564
- spanId: string;
565
- traceId: string;
566
- }, captureRaw?: boolean) => SpanCollector;
575
+ declare const setHostSpanAttributes: (span: HostSpanLike, attributes: Record<string, LogFields[string]>) => void;
567
576
  /**
568
- * Build the `ctx.trace` span factory for one dispatched function.
569
- *
570
- * **Nesting is explicit, not ambient.** Each span's body receives a tracer bound
571
- * to that span; calling it is what makes a child. An earlier design kept an
572
- * ambient stack of "the currently open span" and parented to its top, which
573
- * reads nicer but is unfixably wrong under concurrency: in
574
- * `Promise.all([trace("a", …), trace("b", …)])`, `b` starts while `a` is on the
575
- * stack and is recorded as a *child* of `a` rather than its sibling — and
576
- * parallel fan-out is one of the main things people reach for a tracer to
577
- * measure. Distinguishing "called inside a's body" from "called concurrently
578
- * with a" needs `AsyncLocalStorage`, which this package deliberately avoids (see
579
- * `dependency-tracker.ts` — shard DOs run under a slimmer compat profile than
580
- * `nodejs_compat`). So the parent is threaded, exactly like the dependency
581
- * tracker and the subscription identity: correct in every case, and visible at
582
- * the call site.
583
- *
584
- * The anchor is passed in for the same reason. `ShardDO.currentRequestTrace` is
585
- * cleared in the dispatch `finally`, and a subscription re-run builds its ctx
586
- * during* the writing mutation's flush — so reading that shared field at span
587
- * time would file the re-run's spans under the mutation's trace.
588
- *
589
- * **Cloudflare custom-spans bridge (opt-in, EXPERIMENTAL).** When
590
- * `deps.fuseHostSpans` is `true` and `deps.resolveHostTracing` yields
591
- * a working `tracing.enterSpan` (`cloudflare:workers`, GA 2026-06-16), each span
592
- * body runs inside a CF custom span so our span nests under CF's native
593
- * binding/fetch/handler trace tree on the hosted path, and the finished span's
594
- * key attributes are mirrored onto it (gated on `span.isTraced`). Two deliberate
595
- * boundaries hold.
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.
596
581
  *
597
- * **No double-export by default, and never a replacement.** The bridge only ADDS a
598
- * CF-side span; the recorded {@link SpanEvent} handed to `record` (our
599
- * `SpanBuffer`/`otlpSink`) is byte-for-byte the same as without the bridge and
600
- * stays the source of truth. It is off unless explicitly enabled precisely
601
- * because, once on, a deployment that ALSO ships our `otlpSink` to a collector
602
- * AND lets CF export its trace tree emits the same logical span down two
603
- * pipelines — an intentional, documented trade the operator opts into, not a
604
- * default.
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.
605
589
  *
606
- * **DO async-context caveat (EXPERIMENTAL, partially workerd-validated).**
607
- * `tracing.enterSpan` is now confirmed to EXIST and RUN inside a real Durable
608
- * Object under `@cloudflare/vitest-pool-workers` (see
609
- * `__tests__/workerd/context-telemetry-cf-bridge.workerd.test.ts`): it resolves
610
- * from `cloudflare:workers`, its callback executes and returns the body value
611
- * without throwing, `span.isTraced` is a real boolean, and — the key additive
612
- * guarantee — our recorded {@link SpanEvent} tree (parent/child via the threaded
613
- * `parentSpanId`) is byte-for-byte identical with the bridge on vs off. What that
614
- * harness CANNOT prove is CF's own *exported* parent-linking: with no trace head
615
- * attached the run is unsampled (`isTraced === false`), so CF records nothing and
616
- * its span tree is not introspectable. So `enterSpan`'s ambient-span parent-linking
617
- * inside a DO stays unverified upstream, and this remains capability-probed: an
618
- * absent/undefined `tracing`, a missing `enterSpan`, or an off-CF/unsampled run all
619
- * resolve to `undefined`/no-op — exact prior behavior. If CF's ambient-span linkage
620
- * misbehaves in a DO, the worst case is a mis-parented CF span; our own recorded
621
- * waterfall is unaffected.
590
+ * The status is written before the attributes so a throwing attribute setter
591
+ * cannot drop it.
622
592
  */
623
- declare const createTracer: (deps: TracerDeps) => ContextTracer;
624
- /** What {@link createTracedFetch} needs from the shard. */
625
- interface TracedFetchDeps {
626
- /** The trace the CLIENT spans belong to. */
627
- anchor: TraceAnchor;
628
- /** Function path the spans are attributed to. */
629
- functionPath: string;
630
- /**
631
- * Whether to inject `traceparent` into the outbound request — and, with a
632
- * predicate, to which destinations. Default `true`.
633
- */
634
- propagate?: ((url: URL) => boolean) | boolean;
635
- /** Hand a finished span to the buffer + sink. */
636
- record: (span: SpanEvent) => void;
637
- /** Shard key for single-shard calls; absent for the unnamed root DO. */
638
- shardKey: string | undefined;
639
- /** Read lazily — the acting user is resolved per span. */
640
- userId: () => string | undefined;
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;
641
625
  }
642
- /** The `fetch` shape `ctx.fetch` exposes — the platform global's, narrowed to what we wrap. */
643
- type ContextFetch = (input: Request | string | URL, init?: RequestInit) => Promise<Response>;
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>;
644
636
  /**
645
- * Build `ctx.fetch`: the platform `fetch`, wrapped so every outbound call
646
- * becomes a **CLIENT span** and carries W3C trace context to the callee.
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 trim the log back to the most
944
+ * recent `retention` rows (default {@link REQUEST_LOG_RETENTION}). Creates the
945
+ * table first so callers needn't. Args/identity/error message are redacted here
946
+ * so a raw value never reaches the durable table — callers pass the unredacted
947
+ * entry and rely on this, unless `captureRaw` (dev only) is set. `retention` is
948
+ * the operator's `LUNORA_REQUEST_LOG_RETENTION` override, threaded in by the
949
+ * dispatch site.
950
+ *
951
+ * The error-grouping fingerprint is computed from `entry.errorMessage` BEFORE
952
+ * it's redacted below, and the resulting hash is persisted in
953
+ * `error_fingerprint`. `readErrorIssues` groups off that stored hash instead of
954
+ * recomputing `fingerprintError` from the (redacted) `error_message` column, so
955
+ * masking a PII-bearing value — e.g. two different `<n>`-bucketed IDs that
956
+ * redact to two different tag lengths (`<DL>` vs `<BANKACC>`) — can't split an
957
+ * existing Issue or change its identity.
958
+ */
959
+ declare const appendRequestLogEntry: (sql: SqlExec, entry: AppendRequestLogEntry, options?: RequestLogWriteOptions) => void;
960
+ /**
961
+ * Emit one structured request event to `console` so Cloudflare's Workers Logs /
962
+ * Logpush pipeline carries it to external sinks (SIEMs) — PLAN3 §3.3. This does
963
+ * NOT reimplement a transport: it produces a richer, lunora-attributed event and
964
+ * lets CF's existing trace-log pipe ship it. The event mirrors the durable
965
+ * `__lunora_reqlog__` row (function path, shard, user, outcome, duration, tables
966
+ * read/written, cache hit), with `args`, `identity`, AND `error` redacted
967
+ * exactly like the durable write so no raw PII/secret reaches the log pipeline.
968
+ *
969
+ * An `error` outcome goes to `console.error` (surfacing at error level in the
970
+ * trace so a SIEM can alert on it); everything else to `console.log`. The
971
+ * `source: "lunora"` / `type: "request"` envelope lets a consumer filter these
972
+ * events out of the raw Workers-trace firehose. `captureRaw` (dev only) skips
973
+ * redaction, mirroring the durable write. Best-effort by contract — the caller
974
+ * wraps it so a serialization hiccup can never fail the served request.
975
+ */
976
+ declare const emitRequestLogEvent: (entry: AppendRequestLogEntry, options?: RequestLogWriteOptions) => void;
977
+ /**
978
+ * The `ctx.log` event contract (shape + severity union) lives in
979
+ * `shared/log-event.ts` (inlined into each `dist`) so the DO that builds these
980
+ * events and the `@lunora/runtime` sink that consumes them agree by construction.
981
+ * `LogEventInput` is the DO's historical name for the shared `LogEvent`.
982
+ */
983
+ type LogEventInput = LogEvent;
984
+ /**
985
+ * Split a `ctx.log.<level>(...)` call's raw arguments into a display `message`
986
+ * and optional structured `fields`. The structured form — a message string plus
987
+ * a plain-object fields bag — is matched only for exactly `(string, object)`;
988
+ * every other shape is console-style and rendered whole (so existing
989
+ * `console`-shaped calls are unchanged). Bound `.with(...)` fields merge under
990
+ * the per-call fields (per-call wins); the result is normalized to a fresh bag
991
+ * of JSON-safe primitives, or `undefined` when empty (see `normalizeLogFields`).
992
+ */
993
+ declare const parseLogArgs: (args: unknown[], boundFields?: LogFields) => {
994
+ fields?: LogFields;
995
+ message: string;
996
+ };
997
+ /**
998
+ * Emit one application-log event from a `ctx.log.*` call to `console`, tagged
999
+ * `{ source: "lunora", type: "log" }` so the CLI / Vite formatter can pretty-print
1000
+ * it in the dev terminal and a Logpush/SIEM consumer can filter it out of the
1001
+ * raw Workers-trace firehose.
1002
+ *
1003
+ * Only the rendered `message` is emitted here, NOT the structured `args` array:
1004
+ * the console event rides CF Workers Logs / Logpush to prod, and shipping raw,
1005
+ * un-redacted arg objects on a `source: "lunora"` line a SIEM is told to trust
1006
+ * would be a surprising PII/secret surface. The raw `args` stay on the in-process
1007
+ * `sink.onLog` path (`recordUserLog`), which the operator opts into and controls.
1008
+ * `message` already carries the developer's rendered values, exactly like a raw
1009
+ * `console.log` line.
1010
+ *
1011
+ * `error`/`fatal` go to `console.error`, `warn` to `console.warn` (so they
1012
+ * surface at the right level in the trace); every other level to `console.log`.
1013
+ *
1014
+ * Structured `fields` (plus `traceId`/`spanId` for correlation) ARE emitted here
1015
+ * — they are intentional metadata a log pipeline filters on, unlike raw `args`.
1016
+ * Unlike `args`, `fields` IS redacted before it rides this console line — a
1017
+ * developer can attach anything to a fields bag (`ctx.log.info("charged",
1018
+ * { email, cardLast4 })`), and this is the one line that's told to a SIEM as
1019
+ * trustworthy, exactly like the request-log `args`/`identity`/`error` columns.
1020
+ * `options.captureRaw` (dev only) skips it, mirroring every other redaction
1021
+ * point in this module; the sole current caller (`ShardDO.recordUserLog`)
1022
+ * doesn't yet thread a dev flag through, so `fields` redacts unconditionally
1023
+ * there today — a conservative default, never a correctness gap. A field value
1024
+ * that can't be serialised (a circular object) would make `JSON.stringify`
1025
+ * throw and drop the whole line, so serialisation falls back to a fields-free
1026
+ * line rather than losing the event.
1027
+ */
1028
+ declare const emitLogEvent: (input: LogEventInput, options?: RequestLogWriteOptions) => void;
1029
+ /**
1030
+ * Read request-log entries, AND-combining the supplied filters (function-path
1031
+ * prefix, exact userId/shardKey/outcome, and a table-touched match against the
1032
+ * read OR written table sets), up to `limit` (clamped to [1, 10000]). Each value
1033
+ * is a bound parameter, so no filter can inject SQL. Creates the table first so
1034
+ * reads on a never-logged shard return `[]` instead of throwing. Mirrors
1035
+ * `readAuditLog`/`readCdcChanges`.
1036
+ *
1037
+ * **Ordering follows `sinceSeq`.** Without a cursor this is a "show me the tail"
1038
+ * read and returns NEWEST FIRST, which is what the studio's Logs tab renders.
1039
+ * With `sinceSeq` it is forward paging and returns OLDEST FIRST, starting at the
1040
+ * cursor: descending there silently loses rows, because `ORDER BY seq DESC LIMIT
1041
+ * n` answers "the newest n after the cursor", so a consumer that advances to the
1042
+ * largest returned `seq` skips everything between `sinceSeq` and that page
1043
+ * whenever more than `limit` rows accumulated between polls — the more traffic
1044
+ * the shard takes, the more it drops.
1045
+ */
1046
+ declare const readRequestLog: (sql: SqlExec, options?: ReadRequestLogOptions) => RequestLogEntry[];
1047
+ declare const readErrorIssues: (sql: SqlExec, options?: ReadIssuesOptions) => ErrorIssue[];
1048
+ /**
1049
+ * Structural shape of the `ctx.trace` span factory (see the server
1050
+ * `LunoraTracer`). Declared here rather than imported so `@lunora/do` takes no
1051
+ * dependency on `@lunora/server`; a cross-package assignability guard in
1052
+ * `@lunora/testing` fails the build if the two drift apart.
1053
+ *
1054
+ * The body's second argument is the enclosing span's {@link SpanHandle}, through
1055
+ * which it can attach attributes only known *after* it resolves (post-hoc). It is
1056
+ * a trailing parameter, so a `(trace) => …` body that ignores it still conforms.
1057
+ */
1058
+ type ContextTracer = <T>(name: string, function_: (trace: ContextTracer, span: SpanHandle) => Promise<T> | T, options?: LogFields | SpanOptions, identity?: SpanIdentity) => Promise<T>;
1059
+ /** Structural shape of the `ctx.metrics` recorder (see the server `LunoraMetrics`). */
1060
+ interface ContextMetrics {
1061
+ count: (name: string, value?: number, attributes?: LogFields) => void;
1062
+ gauge: (name: string, value: number, attributes?: LogFields) => void;
1063
+ record: (name: string, value: number, attributes?: LogFields) => void;
1064
+ }
1065
+ /** The trace a ctx's spans hang off: the shared id, and the span they parent to. */
1066
+ interface TraceAnchor {
1067
+ /**
1068
+ * Cloudflare Ray ID of the request this dispatch serves, forwarded by the
1069
+ * runtime alongside `traceparent`. Carried on the anchor so every span and
1070
+ * log line of the dispatch stamps the same value. Absent off the edge.
1071
+ * Informational only, as `parseRayId` in `shared/ray-id.ts` defines it.
1072
+ */
1073
+ rayId?: string;
1074
+ rootSpanId: string;
1075
+ /**
1076
+ * The W3C `sampled` verdict for this trace, inherited from the inbound
1077
+ * `traceparent` when there was one. Carried on the anchor rather than
1078
+ * re-derived per outbound call so every `ctx.fetch` of one dispatch
1079
+ * propagates the same answer.
1080
+ */
1081
+ sampled?: boolean;
1082
+ traceId: string;
1083
+ }
1084
+ /** What {@link createTracer} needs from the shard to build a span. */
1085
+ interface TracerDeps {
1086
+ /** The trace this ctx's spans belong to. */
1087
+ anchor: TraceAnchor;
1088
+ /**
1089
+ * Whether to record a span body's error message (and a `recordException`
1090
+ * stacktrace) verbatim rather than redacted. Mirrors the request log's
1091
+ * `captureRaw`: `true` in dev (`isDevEnvironment`), `false` in production —
1092
+ * the span pipeline is the one sink third-party collectors (Datadog/Axiom
1093
+ * via `otlpSink`) receive, so it must not ship raw PII/internals by default
1094
+ * the way the request log and function-metrics sinks already don't.
1095
+ */
1096
+ captureRaw?: boolean;
1097
+ /** Function path the spans are attributed to. */
1098
+ functionPath: string;
1099
+ /**
1100
+ * **Opt-in, EXPERIMENTAL, default off.** When `true` *and*
1101
+ * {@link TracerDeps.resolveHostTracing} yields a working
1102
+ * `tracing.enterSpan`, each `ctx.trace` span is ALSO emitted as a host-native
1103
+ * **custom span**, so it nests inside CF's native binding/fetch/handler trace
1104
+ * tree on the hosted path. This only ADDS a CF-side span — the recorded
1105
+ * {@link SpanEvent} (our `SpanBuffer`/`otlpSink`) is untouched and remains the
1106
+ * source of truth plus the local studio waterfall. The `enterSpan` call itself
1107
+ * is now workerd-validated as available and side-effect-free inside a Durable
1108
+ * Object; CF's exported parent-linking under sampling remains unverified. See
1109
+ * {@link createTracer} for the double-export and Durable-Object async-context
1110
+ * caveats.
1111
+ */
1112
+ fuseHostSpans?: boolean;
1113
+ /** Hand a finished span to the buffer + sink. */
1114
+ record: (span: SpanEvent) => void;
1115
+ /**
1116
+ * Injected resolver for CF's `tracing` namespace (see
1117
+ * {@link HostTracingResolver}). Only consulted when
1118
+ * {@link TracerDeps.fuseHostSpans} is `true`, so the default path never
1119
+ * calls it.
1120
+ */
1121
+ resolveHostTracing?: HostTracingResolver;
1122
+ /**
1123
+ * The invocation's `v.sensitive` values (see {@link SensitiveScope}). Applied
1124
+ * to every span this tracer records, and to the body's own collector.
1125
+ */
1126
+ scope?: SensitiveScope;
1127
+ /** Shard key for single-shard calls; absent for the unnamed root DO. */
1128
+ shardKey: string | undefined;
1129
+ /** Read lazily — the acting user is resolved per span, not per ctx. */
1130
+ userId: () => string | undefined;
1131
+ }
1132
+ /** What {@link createMetrics} needs from the shard to build a measurement. */
1133
+ interface MetricsDeps {
1134
+ functionPath: string;
1135
+ record: (event: MetricEvent) => void;
1136
+ /** The invocation's `v.sensitive` values, applied to each measurement's attributes. */
1137
+ scope?: SensitiveScope;
1138
+ shardKey: string | undefined;
1139
+ }
1140
+ /** Everything a {@link SpanHandle}'s body attached, ready to merge into the recorded span. */
1141
+ interface SpanCollection {
1142
+ attributes: Record<string, LogFields[string]>;
1143
+ events: SpanEventPoint[];
1144
+ links: SpanLink[];
1145
+ }
1146
+ /** A {@link SpanHandle} plus read access to what it has collected so far. */
1147
+ interface SpanCollector {
1148
+ collected: SpanCollection;
1149
+ handle: SpanHandle;
1150
+ }
1151
+ /**
1152
+ * Build a span's post-hoc collection surface: the {@link SpanHandle} handed to a
1153
+ * `ctx.trace` body, and the bag it writes into.
1154
+ *
1155
+ * Factored out because the same surface backs two things — every `ctx.trace`
1156
+ * span, and the per-dispatch **wide event** (`ctx.span`), where the accumulated
1157
+ * attributes become the canonical one-event-per-request summary. Sharing the
1158
+ * implementation is what makes those two feel like the same API instead of two
1159
+ * that happen to resemble each other.
1160
+ *
1161
+ * `captureRaw` (default `false`) gates `recordException`'s `exception.message`/
1162
+ * `exception.stacktrace` the same way {@link createTracer} gates a span's own
1163
+ * error message — a stack is file paths and internals by definition, the exact
1164
+ * class `isInternalCode` redaction exists for, so it rides the same dev-only
1165
+ * escape hatch rather than shipping to a third-party collector by default.
1166
+ *
1167
+ * `scope` scrubs the invocation's `v.sensitive` values out of everything written
1168
+ * here, at write time, so the collector never holds the raw value. It is applied
1169
+ * whatever `captureRaw` says: the dev escape hatch exists for stacks and
1170
+ * internals, not for a marked argument.
1171
+ */
1172
+ declare const createSpanCollector: (ids: SpanContextIds, captureRaw?: boolean, scope?: SensitiveScope) => SpanCollector;
1173
+ /**
1174
+ * Build the `ctx.trace` span factory for one dispatched function.
1175
+ *
1176
+ * **Nesting is explicit, not ambient.** Each span's body receives a tracer bound
1177
+ * to that span; calling it is what makes a child. An earlier design kept an
1178
+ * ambient stack of "the currently open span" and parented to its top, which
1179
+ * reads nicer but is unfixably wrong under concurrency: in
1180
+ * `Promise.all([trace("a", …), trace("b", …)])`, `b` starts while `a` is on the
1181
+ * stack and is recorded as a *child* of `a` rather than its sibling — and
1182
+ * parallel fan-out is one of the main things people reach for a tracer to
1183
+ * measure. Distinguishing "called inside a's body" from "called concurrently
1184
+ * with a" needs `AsyncLocalStorage`, which this package deliberately avoids (see
1185
+ * `dependency-tracker.ts` — shard DOs run under a slimmer compat profile than
1186
+ * `nodejs_compat`). So the parent is threaded, exactly like the dependency
1187
+ * tracker and the subscription identity: correct in every case, and visible at
1188
+ * the call site.
1189
+ *
1190
+ * The anchor is passed in for the same reason. `ShardDO.currentRequestTrace` is
1191
+ * cleared in the dispatch `finally`, and a subscription re-run builds its ctx
1192
+ * during* the writing mutation's flush — so reading that shared field at span
1193
+ * time would file the re-run's spans under the mutation's trace.
1194
+ *
1195
+ * **Cloudflare custom-spans bridge (opt-in, EXPERIMENTAL).** When
1196
+ * `deps.fuseHostSpans` is `true` and `deps.resolveHostTracing` yields
1197
+ * a working `tracing.enterSpan` (`cloudflare:workers`, GA 2026-06-16), each span
1198
+ * body runs inside a CF custom span so our span nests under CF's native
1199
+ * binding/fetch/handler trace tree on the hosted path, and the finished span's
1200
+ * key attributes are mirrored onto it (gated on `span.isTraced`). Two deliberate
1201
+ * boundaries hold.
1202
+ *
1203
+ * **No double-export by default, and never a replacement.** The bridge only ADDS a
1204
+ * CF-side span; the recorded {@link SpanEvent} handed to `record` (our
1205
+ * `SpanBuffer`/`otlpSink`) is byte-for-byte the same as without the bridge and
1206
+ * stays the source of truth. It is off unless explicitly enabled precisely
1207
+ * because, once on, a deployment that ALSO ships our `otlpSink` to a collector
1208
+ * AND lets CF export its trace tree emits the same logical span down two
1209
+ * pipelines — an intentional, documented trade the operator opts into, not a
1210
+ * default.
1211
+ *
1212
+ * **DO async-context caveat (EXPERIMENTAL, partially workerd-validated).**
1213
+ * `tracing.enterSpan` is now confirmed to EXIST and RUN inside a real Durable
1214
+ * Object under `@cloudflare/vitest-plugin` (see
1215
+ * `__tests__/workerd/context-telemetry-cf-bridge.workerd.test.ts`): it resolves
1216
+ * from `cloudflare:workers`, its callback executes and returns the body value
1217
+ * without throwing, `span.isTraced` is a real boolean, and — the key additive
1218
+ * guarantee — our recorded {@link SpanEvent} tree (parent/child via the threaded
1219
+ * `parentSpanId`) is byte-for-byte identical with the bridge on vs off. What that
1220
+ * harness CANNOT prove is CF's own *exported* parent-linking: with no trace head
1221
+ * attached the run is unsampled (`isTraced === false`), so CF records nothing and
1222
+ * its span tree is not introspectable. So `enterSpan`'s ambient-span parent-linking
1223
+ * inside a DO stays unverified upstream, and this remains capability-probed: an
1224
+ * absent/undefined `tracing`, a missing `enterSpan`, or an off-CF/unsampled run all
1225
+ * resolve to `undefined`/no-op — exact prior behavior. If CF's ambient-span linkage
1226
+ * misbehaves in a DO, the worst case is a mis-parented CF span; our own recorded
1227
+ * waterfall is unaffected.
1228
+ */
1229
+ declare const createTracer: (deps: TracerDeps) => ContextTracer;
1230
+ /** What {@link createTracedFetch} needs from the shard. */
1231
+ interface TracedFetchDeps {
1232
+ /** The trace the CLIENT spans belong to. */
1233
+ anchor: TraceAnchor;
1234
+ /**
1235
+ * Whether to record a failed fetch's error message verbatim rather than
1236
+ * redacted. Same dev-only escape hatch as {@link TracerDeps.captureRaw}, and
1237
+ * the same reason: a `fetch` TypeError embeds the request URL, so a key in a
1238
+ * query string would otherwise reach the collector in the clear on the very
1239
+ * span whose `url.full` is scrubbed by `redactUrl`.
1240
+ */
1241
+ captureRaw?: boolean;
1242
+ /** Function path the spans are attributed to. */
1243
+ functionPath: string;
1244
+ /**
1245
+ * Whether to inject `traceparent` into the outbound request — and, with a
1246
+ * predicate, to which destinations. Default `true`.
1247
+ */
1248
+ propagate?: ((url: URL) => boolean) | boolean;
1249
+ /** Hand a finished span to the buffer + sink. */
1250
+ record: (span: SpanEvent) => void;
1251
+ /** The invocation's `v.sensitive` values; a query string or path can carry one. */
1252
+ scope?: SensitiveScope;
1253
+ /** Shard key for single-shard calls; absent for the unnamed root DO. */
1254
+ shardKey: string | undefined;
1255
+ /** Read lazily — the acting user is resolved per span. */
1256
+ userId: () => string | undefined;
1257
+ }
1258
+ /** The `fetch` shape `ctx.fetch` exposes — the platform global's, narrowed to what we wrap. */
1259
+ type ContextFetch = (input: Request | string | URL, init?: RequestInit) => Promise<Response>;
1260
+ /**
1261
+ * Build `ctx.fetch`: the platform `fetch`, wrapped so every outbound call
1262
+ * becomes a **CLIENT span** and carries W3C trace context to the callee.
647
1263
  *
648
1264
  * Two gaps close here. First, an uninstrumented `fetch` makes the single most
649
1265
  * common source of latency — waiting on somebody else's service — invisible: a
@@ -660,6 +1276,15 @@ type ContextFetch = (input: Request | string | URL, init?: RequestInit) => Promi
660
1276
  * Kind is `client` rather than `internal` — that is what lets a collector draw
661
1277
  * the edge to the downstream service in a service map.
662
1278
  *
1279
+ * **Parenting is the DISPATCH, not the enclosing `ctx.trace`.** `ctx.fetch` is
1280
+ * built once per dispatch, and the enclosing span is threaded explicitly rather
1281
+ * than kept on an ambient stack (no `AsyncLocalStorage` in the Durable Object
1282
+ * profile — the same constraint `ctx.trace` and the `@opentelemetry/api` bridge
1283
+ * document), so a fetch inside `ctx.trace("stripe", …)` renders as that span's
1284
+ * SIBLING under the dispatch, not its child. The duration and the ordering are
1285
+ * right and the span is never lost; only the nesting is flat. Wrap the call in
1286
+ * the span whose bar you want it under and read the two side by side.
1287
+ *
663
1288
  * Failures are recorded and re-thrown untouched, and a non-2xx response is
664
1289
  * recorded as an ERROR span (it is a failed call from the caller's point of
665
1290
  * view) while still being returned normally — instrumentation, never flow
@@ -709,6 +1334,8 @@ declare const dispatchRootSpan: (input: {
709
1334
  thrown: unknown;
710
1335
  } | undefined;
711
1336
  functionPath: string;
1337
+ /** The invocation's `v.sensitive` values; the failure message can quote one. */
1338
+ scope?: SensitiveScope;
712
1339
  shardKey: string | undefined;
713
1340
  startTs: number;
714
1341
  userId: string | undefined;
@@ -723,7 +1350,12 @@ interface DatabaseTally {
723
1350
  spansTruncated: boolean;
724
1351
  }
725
1352
  /**
726
- * How much detail `ctx.db` auto-instrumentation produces.
1353
+ * Which instrumented surface a tally belongs to, and the key prefix
1354
+ * {@link formatTally} folds it under: `db` for `ctx.db`, `sql` for `ctx.sql`.
1355
+ */
1356
+ type TallySurface = "db" | "sql";
1357
+ /**
1358
+ * How much detail `ctx.db` / `ctx.sql` auto-instrumentation produces.
727
1359
  *
728
1360
  * `"summary"` (default) — aggregate counters on the dispatch's wide event: no
729
1361
  * extra spans, no extra log records, and a cost that does not grow with call count.
@@ -734,16 +1366,24 @@ interface DatabaseTally {
734
1366
  * `"off"` — no database telemetry at all.
735
1367
  */
736
1368
  type DatabaseInstrumentation = "off" | "spans" | "summary";
737
- /** What {@link instrumentDatabase} needs to record what it observes. */
1369
+ /**
1370
+ * The structural slice of `@lunora/hyperdrive`'s `SqlClient` the `ctx.sql`
1371
+ * instrumenter needs — declared here so this package takes no dependency on
1372
+ * hyperdrive.
1373
+ */
1374
+ interface SqlClientLike {
1375
+ /** OTel `db.system.name` the driver adapter stamped; `other_sql` when absent. */
1376
+ readonly dbSystem?: string;
1377
+ query: (text: string, params?: ReadonlyArray<unknown>) => Promise<unknown>;
1378
+ }
1379
+ /** What {@link instrumentDatabase} / {@link instrumentSqlClient} need to record what they observe. */
738
1380
  interface DatabaseTelemetryDeps {
739
1381
  /** The trace produced spans belong to (`"spans"` mode only). */
740
1382
  anchor: TraceAnchor;
741
1383
  /**
742
- * Whether to record a failed call's error message verbatim rather than
743
- * redacted (`"spans"` mode only) — the same dev-only escape hatch as
744
- * `TracerDeps.captureRaw`. A constraint-error message quotes the
745
- * conflicting row, so this CLIENT span gets the same default-redacted
746
- * posture as the request log and function-metrics sinks.
1384
+ * Whether to record a failed call's error message verbatim (`"spans"` mode
1385
+ * only) — the same dev-only escape hatch as `TracerDeps.captureRaw`. See
1386
+ * {@link failureMessage} for what each surface records without it.
747
1387
  */
748
1388
  captureRaw?: boolean;
749
1389
  /** Function path spans and attributes are attributed to. */
@@ -752,6 +1392,8 @@ interface DatabaseTelemetryDeps {
752
1392
  mode: DatabaseInstrumentation;
753
1393
  /** Hand a finished span to the buffer + sink (`"spans"` mode only). */
754
1394
  record: (span: SpanEvent) => void;
1395
+ /** The invocation's `v.sensitive` values; a driver's error message can quote one. */
1396
+ scope?: SensitiveScope;
755
1397
  /** Shard key for single-shard calls; absent for the unnamed root DO. */
756
1398
  shardKey: string | undefined;
757
1399
  /**
@@ -759,14 +1401,20 @@ interface DatabaseTelemetryDeps {
759
1401
  * increments numbers on it; the shard reads it ONCE at the dispatch boundary
760
1402
  * and formats it with {@link formatTally}.
761
1403
  *
762
- * Two properties fall out of that split. Per-call cost stays at a few integer
763
- * increments — no object allocation, no lookup — which matters because this is
764
- * on the path of every query. And because nothing is written through the
765
- * dispatch's `SpanHandle`, the wide-event collector is never materialized, so
766
- * a handler that instrumented nothing still doesn't trip the root-span gate.
1404
+ * Per-call cost stays at a few integer increments — no object allocation, no
1405
+ * lookup — which matters because this is on the path of every query. Nothing
1406
+ * is written through the dispatch's `SpanHandle` either, so the wide-event
1407
+ * collector is never materialized by instrumentation alone: a dispatch that
1408
+ * ran queries gets a root span carrying these counters, but no `lunora.dispatch`
1409
+ * log record unless the handler actually opened `ctx.span`.
767
1410
  */
768
1411
  tally: DatabaseTally;
769
- /** Read lazily — the acting user is resolved per span. */
1412
+ /**
1413
+ * The acting user, read when a span is built. Callers resolve it ONCE, when
1414
+ * they instrument the client, and return that captured value: a span is
1415
+ * built after the call's await, and per-request shared state read by then
1416
+ * may already belong to a concurrent request.
1417
+ */
770
1418
  userId: () => string | undefined;
771
1419
  }
772
1420
  /**
@@ -775,24 +1423,42 @@ interface DatabaseTelemetryDeps {
775
1423
  * Returns the database unchanged when `mode` is `"off"`, so the default-disabled
776
1424
  * path costs nothing — not even a proxy indirection.
777
1425
  *
778
- * Implemented as a `Proxy` rather than by enumerating and rebinding methods:
779
- * `DatabaseWriterLike` has optional members that a given backend may or may not
780
- * implement, plus properties (`system`) and builder factories (`query`) that
781
- * must pass through untouched. A proxy instruments exactly what it is asked to
782
- * and is transparently correct for everything else, including members added
783
- * later — an enumeration would silently stop covering them.
1426
+ * A proxy rather than an enumerated, rebound copy: `DatabaseWriterLike` has
1427
+ * optional members that a given backend may or may not implement, plus
1428
+ * properties (`system`) and builder factories (`query`) that must pass through
1429
+ * untouched. A proxy instruments exactly what it is asked to and is
1430
+ * transparently correct for everything else, including members added later —
1431
+ * an enumeration would silently stop covering them.
784
1432
  */
785
1433
  declare const instrumentDatabase: <T extends object>(database: T, deps: DatabaseTelemetryDeps) => T;
1434
+ /**
1435
+ * Wrap the action-only `ctx.sql` client so every `query` is instrumented — the
1436
+ * `ctx.sql` twin of {@link instrumentDatabase}, at the same levels and through
1437
+ * the same {@link observeCall}. `deps.tally` must be a tally of its own (folded
1438
+ * as `sql.*`), never `ctx.db`'s.
1439
+ *
1440
+ * Its span carries no statement text and no parameters — only the
1441
+ * leading-keyword operation, the system, and the returned row count. No
1442
+ * `db.collection.name` either: naming the table means parsing past
1443
+ * `FROM`/`INTO` through joins, CTEs and quoting, which is neither cheap nor
1444
+ * safe. A failure records its TYPE (see {@link failureMessage}).
1445
+ *
1446
+ * `query` is the whole `SqlClient` surface: there is no transaction or batch
1447
+ * method to cover. Everything else on the client passes through untouched, and
1448
+ * `"off"` returns the client itself.
1449
+ */
1450
+ declare const instrumentSqlClient: <T extends SqlClientLike>(client: T, deps: DatabaseTelemetryDeps) => T;
786
1451
  /** A zero'd tally for one dispatch. */
787
1452
  declare const createDatabaseTally: () => DatabaseTally;
788
1453
  /**
789
- * Render the running tally as span attributes.
1454
+ * Render the running tally as span attributes, under its surface's prefix
1455
+ * ({@link TallySurface}).
790
1456
  *
791
1457
  * Called ONCE per dispatch, from the shard's root-span recorder — not per query.
792
- * 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
793
- * assignment — the property that makes `"summary"` mode scale to any call count.
1458
+ * It is a handful of keys, so the per-call cost is a small object assignment —
1459
+ * the property that makes `"summary"` mode scale to any call count.
794
1460
  */
795
- declare const formatTally: (tally: DatabaseTally) => LogFields;
1461
+ declare const formatTally: (tally: DatabaseTally, surface?: TallySurface) => LogFields;
796
1462
  /** Reserved per-function accumulator table. Auto-hidden from the data browser by the `__lunora` prefix. */
797
1463
  declare const FUNCTION_METRICS_TABLE = "__lunora_metrics";
798
1464
  /** Reserved coarse time-series table: per-function call/error counts bucketed by a fixed window. */
@@ -887,8 +1553,15 @@ interface FunctionMetricIndexHit {
887
1553
  /** The table the index is declared on. */
888
1554
  table: string;
889
1555
  }
890
- /** Fields recorded for one completed dispatch. `errored` advances the failure counters. */
1556
+ /**
1557
+ * Fields recorded for one completed dispatch, or for a coalesced delta of
1558
+ * several. `errored` advances the failure counters. The optional count-carrying
1559
+ * fields let a caller that batched N dispatches write their exact sum in one
1560
+ * upsert; omitted, every field defaults to the single-dispatch value.
1561
+ */
891
1562
  interface RecordFunctionMetricInput {
1563
+ /** Dispatches this record stands for. Default `1`. */
1564
+ calls?: number;
892
1565
  /**
893
1566
  * Whether the dispatch failed on an optimistic-concurrency (OCC) write
894
1567
  * conflict — a compare-and-swap that lost to a concurrent commit. Advances
@@ -897,12 +1570,29 @@ interface RecordFunctionMetricInput {
897
1570
  * Omitted/false on the common path, keeping the hot path unchanged.
898
1571
  */
899
1572
  conflicted?: boolean;
1573
+ /** Conflicts in a coalesced delta. Default `conflicted ? 1 : 0`. */
1574
+ conflicts?: number;
1575
+ /** Longest handler time in a coalesced delta. Default `durationMs`. */
1576
+ durationMaxMs?: number;
1577
+ /** Shortest handler time in a coalesced delta. Default `durationMs`. */
1578
+ durationMinMs?: number;
900
1579
  /** Wall-clock millis the handler took. */
901
1580
  durationMs: number;
1581
+ /** Summed handler time of a coalesced delta. Default `durationMs`. */
1582
+ durationTotalMs?: number;
902
1583
  /** Whether the dispatch threw. */
903
1584
  errored: boolean;
904
1585
  /** Most recent failure message, recorded only when `errored`. */
905
1586
  errorMessage?: string;
1587
+ /** Failed dispatches in a coalesced delta. Default `errored ? 1 : 0`. */
1588
+ errors?: number;
1589
+ /**
1590
+ * Per-`(table, index)` hit counts of a coalesced delta (one per dispatch that
1591
+ * used the index). When set, replaces {@link RecordFunctionMetricInput.indexHits}.
1592
+ */
1593
+ indexHitCounts?: ReadonlyArray<IndexHit & {
1594
+ count: number;
1595
+ }>;
906
1596
  /**
907
1597
  * Distinct declared indexes this dispatch exercised (used to narrow a read),
908
1598
  * collected from the `onIndexUse` signal. Each entry bumps the
@@ -911,8 +1601,18 @@ interface RecordFunctionMetricInput {
911
1601
  * dispatch used no declared index, keeping the hot path unchanged.
912
1602
  */
913
1603
  indexHits?: ReadonlyArray<IndexHit>;
1604
+ /** Epoch-ms of the latest failure in a coalesced delta. Default `errored ? ts : null`. */
1605
+ lastErrorAt?: number | null;
914
1606
  /** The `<file>:<function>` identifier. */
915
1607
  path: string;
1608
+ /**
1609
+ * Per-table full-scan counts of a coalesced delta (one per dispatch that
1610
+ * scanned the table). When set, replaces {@link RecordFunctionMetricInput.scannedTables}.
1611
+ */
1612
+ scanCounts?: ReadonlyArray<{
1613
+ count: number;
1614
+ table: string;
1615
+ }>;
916
1616
  /**
917
1617
  * Distinct tables this dispatch full-scanned (read with no index / point
918
1618
  * lookup), collected from the `SCAN_DEP` reads. Each entry bumps the
@@ -1110,67 +1810,20 @@ type ExplainIssueResult = ExplainIssueDegraded | ExplainIssueSuccess;
1110
1810
  * `sampleMessage` alone left `title`/`culprit` as an open door onto the same
1111
1811
  * prompt budget.
1112
1812
  */
1113
- declare const parseExplainIssueArgs: (args: Record<string, unknown>) => ExplainIssueArgs;
1114
- /**
1115
- * Run the full explain flow for one Issue: validate the payload, ground it in the
1116
- * catalog, and — when `binding` is a usable Workers AI binding — ask the model for
1117
- * a plain-language rewrite. Never throws for an AI-side failure; every such path
1118
- * returns the `degraded: true` arm carrying the grounded hint, so the caller
1119
- * always has something to render. Only a malformed payload throws (a 400).
1120
- *
1121
- * `binding` is `unknown` so the caller can hand over `env.AI` untyped — the shape
1122
- * check lives here rather than at each call site.
1123
- */
1124
- declare const explainIssue: (binding: unknown, args: Record<string, unknown>, options?: {
1125
- defaultModel?: string;
1126
- }) => Promise<ExplainIssueResult>;
1127
- /** Reserved table holding one triage-state row per Issue fingerprint. Auto-hidden by the `__lunora` prefix. */
1128
- declare const ISSUE_STATE_TABLE = "__lunora_issue_state__";
1129
- /**
1130
- * Triage status of an Issue. `open` is the implicit default (no state row); a
1131
- * developer moves it to `resolved` (fixed, but a *new* matching error re-opens
1132
- * it — see {@link readIssueStates}'s consumer) or `ignored` (deliberately muted,
1133
- * and stays muted regardless of new occurrences).
1134
- */
1135
- type IssueStatus = "ignored" | "open" | "resolved";
1136
- /** Ordered severity a developer can tag an Issue with; drives the Studio badge palette. */
1137
- type IssueSeverity = "critical" | "high" | "low" | "medium";
1138
- /** The persisted triage state for one Issue fingerprint. */
1139
- interface IssueState {
1140
- /** Free-form assignee (a userId or a name); absent when unassigned. */
1141
- assignee?: string;
1142
- /** Stable 16-char fingerprint hash — the same key `readErrorIssues` folds on. */
1143
- hash: string;
1144
- /** Developer-tagged severity; absent when untriaged. */
1145
- severity?: IssueSeverity;
1146
- /** Current triage status. */
1147
- status: IssueStatus;
1148
- /** Wall-clock millis the state was last changed — compared against an Issue's `lastSeen` to detect a regression. */
1149
- updatedAt: number;
1150
- /** Acting userId that last changed the state, when known. */
1151
- updatedBy?: string;
1152
- }
1153
- /** Patch applied by an admin write; every field is optional so a caller can change one facet at a time. */
1154
- interface IssueStatePatch {
1155
- assignee?: null | string;
1156
- severity?: IssueSeverity | null;
1157
- status?: IssueStatus;
1158
- }
1159
- /** The valid {@link IssueStatus} values, for arg validation at the admin boundary. */
1160
- declare const ISSUE_STATUSES: ReadonlyArray<IssueStatus>;
1161
- /** The valid {@link IssueSeverity} values, for arg validation at the admin boundary. */
1162
- declare const ISSUE_SEVERITIES: ReadonlyArray<IssueSeverity>;
1163
- /**
1164
- * Apply a triage patch to one Issue, upserting its state row. A `null` in the
1165
- * patch clears the field (unassign, untag severity); an omitted field is left
1166
- * unchanged. Returns the resulting {@link IssueState} so the caller can echo it.
1813
+ declare const parseExplainIssueArgs: (args: Record<string, unknown>) => ExplainIssueArgs;
1814
+ /**
1815
+ * Run the full explain flow for one Issue: validate the payload, ground it in the
1816
+ * catalog, and — when `binding` is a usable Workers AI binding — ask the model for
1817
+ * a plain-language rewrite. Never throws for an AI-side failure; every such path
1818
+ * returns the `degraded: true` arm carrying the grounded hint, so the caller
1819
+ * always has something to render. Only a malformed payload throws (a 400).
1167
1820
  *
1168
- * Uses `ON CONFLICT(hash) DO UPDATE` with `COALESCE(?, column)` per optional
1169
- * field so a partial patch touches only what it names — except the explicit
1170
- * `null` sentinels for assignee/severity, which are threaded separately so a
1171
- * clear can win over `COALESCE`.
1821
+ * `binding` is `unknown` so the caller can hand over `env.AI` untyped — the shape
1822
+ * check lives here rather than at each call site.
1172
1823
  */
1173
- declare const upsertIssueState: (sql: SqlExec, hash: string, patch: IssueStatePatch, updatedAt: number, updatedBy?: string) => IssueState;
1824
+ declare const explainIssue: (binding: unknown, args: Record<string, unknown>, options?: {
1825
+ defaultModel?: string;
1826
+ }) => Promise<ExplainIssueResult>;
1174
1827
  /**
1175
1828
  * Severity of a buffered log entry — the full seven-tier `ctx.log` ramp
1176
1829
  * (`trace`→`fatal`), not a console-shaped subset. The buffer used to fold the
@@ -1196,6 +1849,8 @@ interface LogEntry {
1196
1849
  level: LogLevel;
1197
1850
  message: string;
1198
1851
  timestamp: number;
1852
+ /** 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. */
1853
+ traceId?: string;
1199
1854
  }
1200
1855
  /**
1201
1856
  * A bounded, in-memory ring buffer of recent {@link LogEntry} records.
@@ -1216,10 +1871,21 @@ declare class LogBuffer {
1216
1871
  /** Backing store, kept in insertion order (oldest first). */
1217
1872
  private readonly buffer;
1218
1873
  private readonly capacity;
1874
+ /** How many entries the ring has evicted since it was last cleared. */
1875
+ private droppedCount;
1219
1876
  constructor(capacity?: number);
1877
+ /**
1878
+ * Entries evicted for capacity since the last {@link LogBuffer.clear}.
1879
+ *
1880
+ * Without it a full ring is indistinguishable from a quiet instance that
1881
+ * happened to log exactly `capacity` lines: the reader sees 500 entries
1882
+ * either way and cannot tell whether 500 lines happened or 50,000 did. The
1883
+ * count is what turns "the newest 500" into an honest statement.
1884
+ */
1885
+ get dropped(): number;
1220
1886
  /** Number of entries currently buffered. */
1221
1887
  get size(): number;
1222
- /** Drop every buffered entry. */
1888
+ /** Drop every buffered entry, including the eviction count. */
1223
1889
  clear(): void;
1224
1890
  /**
1225
1891
  * Snapshot of the buffered entries, **newest first** so the panel renders
@@ -1341,421 +2007,142 @@ interface MetricHistoryResult {
1341
2007
  * `metricHistory` option. Each falls back to its module-constant default, so an
1342
2008
  * omitted field keeps the historical behaviour.
1343
2009
  */
1344
- interface MetricHistoryOptions {
1345
- /** Distinct series tracked before the least-recently-updated one is evicted to admit a new one (default {@link METRIC_HISTORY_MAX_SERIES}). */
1346
- maxSeries?: number;
1347
- /** Minute-buckets kept per series before older rows are trimmed (default {@link METRIC_HISTORY_BUCKET_RETENTION}). */
1348
- retentionBuckets?: number;
1349
- }
1350
- /**
1351
- * Fold one measurement into its `(series, minute)` bucket. Runs per
1352
- * `ctx.metrics.*` call (unlike `function-metrics.ts`, which runs once per
1353
- * dispatch), so it's tuned for the in-minute repeat: a bucket this instance has
1354
- * already written is a single upsert (no reads), a bucket only in the DB costs one
1355
- * PK point-lookup + upsert, and only a genuinely new bucket also pays the
1356
- * distinct-series cap scan + retention trim. Still a durable SQLite write per
1357
- * measurement, so a hot loop recording thousands of points a second should
1358
- * pre-aggregate and record once (see `shared/metric-event.ts`). Creates the table
1359
- * first so callers needn't.
1360
- *
1361
- * `exemplarTraceId` (the recording dispatch's trace, when it had one) is stored on
1362
- * the bucket so the studio can link a chart point back to a trace. Latest wins:
1363
- * a later sample carrying a trace replaces an earlier bucket's exemplar.
1364
- *
1365
- * `options` tunes the distinct-series cap and retention window from the sink's
1366
- * `metricHistory` flag (see {@link MetricHistoryOptions}); each defaults to its
1367
- * module constant.
1368
- */
1369
- declare const recordMetricHistory: (sql: SqlExec, event: MetricEvent, exemplarTraceId?: string, options?: MetricHistoryOptions) => void;
1370
- /**
1371
- * Read the durable history, grouped into one {@link MetricHistorySeries} per
1372
- * series with its buckets in ascending time order.
1373
- *
1374
- * Rows are fetched most-recent-first (`bucket_ms DESC`) under the row cap, NOT
1375
- * `series_key`-ordered: all active series write the same recent minutes, so this
1376
- * windows every series to a recent slice fairly, instead of handing the
1377
- * alphabetically-first series its full 1440-bucket history and starving the rest
1378
- * once the cap is hit. Each series' points are re-sorted ascending below, since a
1379
- * trend line reads oldest→newest.
1380
- *
1381
- * `options.sinceMs`, when set, returns only buckets at or after this epoch-ms —
1382
- * the studio's time-window selector. `options.maxSeries`, mirroring the write
1383
- * side's tunable, is only used to compute `capped` — it does not affect which
1384
- * rows are read.
1385
- */
1386
- declare const readMetricHistory: (sql: SqlExec, options?: {
1387
- maxSeries?: number;
1388
- sinceMs?: number;
1389
- }) => MetricHistoryResult;
1390
- /** One row of the `__lunora_metrics_queries` table, as returned by `readQueryMetrics`. */
1391
- interface QueryStatEntry {
1392
- /** Total number of times this statement was executed. */
1393
- execCount: number;
1394
- /** Normalised SQL text (literals stripped, truncated). */
1395
- normalizedSql: string;
1396
- /** Total rows read across all executions (SELECT result sizes). */
1397
- rowsRead: number;
1398
- /** Total rows written across all executions. */
1399
- rowsWritten: number;
1400
- /** Total wall-clock milliseconds across all executions. */
1401
- totalDurationMs: number;
1402
- }
1403
- /** One statement's activity within a chosen time range. */
1404
- interface QueryInsightEntry {
1405
- /** Mean milliseconds per execution across the range. */
1406
- avgDurationMs: number;
1407
- execCount: number;
1408
- normalizedSql: string;
1409
- /** Interpolated 50th percentile latency, in milliseconds. */
1410
- p50DurationMs: number;
1411
- /** Interpolated 95th percentile latency, in milliseconds. */
1412
- p95DurationMs: number;
1413
- rowsRead: number;
1414
- rowsWritten: number;
1415
- totalDurationMs: number;
1416
- }
1417
- /** One point on the throughput/latency charts. */
1418
- interface QueryInsightBucket {
1419
- /** Mean milliseconds per execution in this window, across all statements. */
1420
- avgDurationMs: number;
1421
- /** Bucket start, epoch millis. */
1422
- bucketMs: number;
1423
- execCount: number;
1424
- }
1425
- /** What `getQueryInsights` returns. */
1426
- interface QueryInsightsResult {
1427
- /** Time series across the whole range, all statements combined. */
1428
- buckets: QueryInsightBucket[];
1429
- /**
1430
- * True when the tracked-statement cap has been reached, so the caller can say
1431
- * "showing N of a capped set" rather than implying totality. Silent
1432
- * truncation reads as complete coverage when it is not.
1433
- */
1434
- capped: boolean;
1435
- entries: QueryInsightEntry[];
1436
- /** How many distinct statements the lifetime table is tracking. */
1437
- trackedStatements: number;
1438
- }
1439
- /**
1440
- * Per-statement activity within `rangeMs` of `now`, plus a combined time series.
1441
- *
1442
- * Reads the bucket table (not the lifetime one) so the numbers answer "what is
1443
- * hot right now"; the statement TEXT is joined back from the lifetime table,
1444
- * which is the only place it is stored.
1445
- */
1446
- declare const readQueryInsights: (sql: SqlExec, rangeMs: number, now?: number) => QueryInsightsResult;
1447
- /**
1448
- * Record one statement's activity. Creates the table on first call. Silently
1449
- * skips recording when the normalised statement is empty (shouldn't happen
1450
- * in practice) or when the table is already at the
1451
- * {@link QUERY_METRICS_MAX_STATEMENTS} cap and the statement is not yet
1452
- * tracked. See `admitStatement` for how the cap check avoids an unconditional
1453
- * `COUNT(*)` on every execution.
1454
- *
1455
- * `execCount` (default 1) lets a caller fold several executions of the SAME
1456
- * statement into one call — `shard-do.ts` does this per dispatch so a
1457
- * query-in-a-loop handler pays one upsert here instead of one per raw
1458
- * execution. `durationMs`/`rowsRead`/`rowsWritten` are then the SUM across
1459
- * `execCount` executions, exactly as `exec_count`/`total_duration_ms` already
1460
- * accumulate sums across separate calls — folding before calling is
1461
- * indistinguishable, from this table's point of view, from `execCount`
1462
- * separate calls with the same totals.
1463
- */
1464
- declare const recordQueryMetric: (sql: SqlExec, rawSql: string, durationMs: number, rowsRead: number, rowsWritten: number, now?: number, execCount?: number) => void;
1465
- /**
1466
- * Read all tracked statement aggregates, ordered by `total_duration_ms DESC`
1467
- * (the leaderboard's default). Creates the table first so a read on a
1468
- * never-called shard returns `[]`.
1469
- */
1470
- declare const readQueryMetrics: (sql: SqlExec) => QueryStatEntry[];
1471
- /** Reserved append-only table backing the studio Logs tab. Auto-hidden from the data browser by the `__lunora` prefix. */
1472
- declare const REQUEST_LOG_TABLE = "__lunora_reqlog__";
1473
- /** Outcome of one dispatch — `ok` for a returned result, `error` for a thrown handler. */
1474
- type RequestOutcome = "error" | "ok";
1475
- /** One recorded `/rpc` dispatch, in monotonic `seq` order. */
1476
- interface RequestLogEntry {
1477
- /** Whether the result was served from the reactive cache; `undefined` when the cache is disabled or the path isn't cached (a write/action). */
1478
- cacheHit?: boolean;
1479
- /** Handler wall-clock duration in milliseconds (before the subscription write-flush, matching the per-function metrics). */
1480
- durationMs: number;
1481
- /** Error message when `outcome === "error"`, redacted like args/identity; absent on success. */
1482
- errorMessage?: string;
1483
- /** The `<file>:<function>` identifier dispatched, e.g. `messages:list`. */
1484
- functionPath: string;
1485
- /** 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. */
1486
- identity?: Record<string, unknown>;
1487
- /** `ok` for a returned result, `error` for a thrown handler. */
1488
- outcome: RequestOutcome;
1489
- /** Call args with leaf values redacted by default (keys/shape preserved); absent when no args were sent. */
1490
- redactedArgs?: unknown;
1491
- /** Monotonic per-shard cursor — strictly increasing, never reused. */
1492
- seq: number;
1493
- /** Shard key (the DO id name), or `undefined` for the unnamed `__root__` DO. */
1494
- shardKey?: string;
1495
- /** Count of subscriptions re-run by the write this dispatch triggered; `0` when none (or not measured at the dispatch site). */
1496
- subscriptionsReRun: number;
1497
- /** Tables the handler read (from the dependency tracker); empty when the reactive cache is off or the path read nothing. */
1498
- tablesRead: string[];
1499
- /** Tables the handler wrote (from the change tracker); empty for a read-only dispatch. */
1500
- tablesWritten: string[];
1501
- /** Wall-clock millis when the dispatch completed. */
1502
- ts: number;
1503
- /** Acting userId forwarded by the runtime, or `undefined` when anonymous. */
1504
- userId?: string;
1505
- }
1506
- /** Fields accepted when appending one request-log entry; `seq` is assigned by the table. */
1507
- interface AppendRequestLogEntry {
1508
- cacheHit?: boolean;
1509
- durationMs: number;
1510
- errorMessage?: string;
1511
- functionPath: string;
1512
- identity?: Record<string, unknown>;
1513
- outcome: RequestOutcome;
1514
- redactedArgs?: unknown;
1515
- shardKey?: string;
1516
- subscriptionsReRun?: number;
1517
- tablesRead?: string[];
1518
- tablesWritten?: string[];
1519
- ts: number;
1520
- userId?: string;
1521
- }
1522
- /** Knobs the dispatch site threads into a request-log write. */
1523
- interface RequestLogWriteOptions {
1524
- /** When `true` (development only), skip args/identity redaction so a developer sees raw values. Defaults to `false` (production-safe). */
1525
- captureRaw?: boolean;
1526
- /** Rows to keep after the append-time trim; defaults to {@link REQUEST_LOG_RETENTION}. The operator's `LUNORA_REQUEST_LOG_RETENTION` override. */
1527
- retention?: number;
1528
- }
1529
- /** Filters for {@link readRequestLog}, all AND-combined; every value is a bound SQL parameter, so nothing here injects SQL. */
1530
- interface ReadRequestLogOptions {
1531
- /** Functions whose path begins with this prefix (a `<file>:` or `<file>:<fn>` correlation). */
1532
- functionPathPrefix?: string;
1533
- /** Upper bound on returned rows, clamped to [1, 10000]. */
1534
- limit?: number;
1535
- /** Keep only `ok` / `error` outcomes. */
1536
- outcome?: RequestOutcome;
1537
- /** Exact shard-key match. */
1538
- shardKey?: string;
1539
- /** Only entries strictly after this cursor (forward paging). */
1540
- sinceSeq?: number;
1541
- /** Keep only entries whose read OR written table set contains this table. */
1542
- tableTouched?: string;
1543
- /** Exact acting-userId match. */
1544
- userId?: string;
1545
- }
1546
- /** Payload of a `__lunora_admin__:getRequestLog` call: the recorded entries, newest first. */
1547
- interface RequestLogResult {
1548
- entries: RequestLogEntry[];
1549
- }
1550
- /**
1551
- * One grouped error **Issue**: many `error`-outcome request-log rows that share a
1552
- * fingerprint folded into a single triage row. The `hash` is the same stable key
1553
- * a cloud Incident groups on, so a local Issue and a cloud Incident are the same
1554
- * object.
1555
- */
1556
- interface ErrorIssue {
1557
- /** Assignee (a userId or a name) from the persisted triage state; absent when unassigned. */
1558
- assignee?: string;
1559
- /** Number of `error` rows folded into this Issue within the scanned window. */
1560
- count: number;
1561
- /** The `<file>:<function>` (or `container:<name>`) the errors came from. */
1562
- culprit: string;
1563
- /** Wall-clock millis of the oldest folded row. */
1564
- firstSeen: number;
1565
- /**
1566
- * Stable 16-char grouping hash over `functionPath :: bucket(message)`,
1567
- * computed from the RAW (pre-redaction) message at write time and stored on
1568
- * the row — see {@link appendRequestLogEntry} — so redacting `sampleMessage`
1569
- * below can't change the grouping.
1570
- */
1571
- hash: string;
1572
- /** Wall-clock millis of the newest folded row. */
1573
- lastSeen: number;
1574
- /** A representative error message (redacted, like the durable row) — taken from the most recent folded row. */
1575
- sampleMessage: string;
1576
- /** Developer-tagged severity from the persisted triage state; absent when untriaged. */
1577
- severity?: IssueSeverity;
1578
- /**
1579
- * Wall-clock millis the persisted triage state was last changed; absent when
1580
- * the Issue has never been triaged. Compared against `lastSeen` to detect a
1581
- * regression (a new error after a resolve).
1582
- */
1583
- stateUpdatedAt?: number;
2010
+ interface MetricHistoryOptions {
1584
2011
  /**
1585
- * Triage status folded in from the persisted state (`open` by default). A
1586
- * `resolved` Issue whose `lastSeen` is newer than `stateUpdatedAt` is
1587
- * auto-reopened to `open` here (a regression), so a fresh occurrence never
1588
- * hides behind a stale resolution; `ignored` stays sticky by design.
2012
+ * Distinct series tracked before a brand-new one is REFUSED admission
2013
+ * (default {@link METRIC_HISTORY_MAX_SERIES}). Nothing is evicted: an
2014
+ * already-tracked series keeps accumulating past the cap, and a flood of
2015
+ * one-off series cannot displace the app's real ones — see
2016
+ * {@link admitNewSeries}. `readMetricHistory`'s `capped` flag is the
2017
+ * read-side signal that admission is being refused.
1589
2018
  */
1590
- status: IssueStatus;
1591
- /** Human-readable title (first line of the sample message, capped). */
1592
- title: string;
1593
- }
1594
- /** Payload of a `__lunora_admin__:getIssues` call: grouped error Issues, most-recently-active first. */
1595
- interface IssuesResult {
1596
- issues: ErrorIssue[];
1597
- }
1598
- /** Filters for {@link readErrorIssues}; forwarded to {@link readRequestLog} with `outcome` forced to `error`. */
1599
- interface ReadIssuesOptions {
1600
- /** Functions whose path begins with this prefix (a `<file>:` or `<file>:<fn>` correlation). */
1601
- functionPathPrefix?: string;
1602
- /** Upper bound on error rows scanned before grouping, clamped to [1, 10000]. */
1603
- limit?: number;
1604
- /** Exact shard-key match. */
1605
- shardKey?: string;
1606
- /** Keep only Issues in this triage status, applied AFTER the persisted-state fold + auto-reopen. */
1607
- status?: IssueStatus;
1608
- /** Exact acting-userId match. */
1609
- userId?: string;
2019
+ maxSeries?: number;
2020
+ /** Minute-buckets kept per series before older rows are trimmed (default {@link METRIC_HISTORY_BUCKET_RETENTION}). */
2021
+ retentionBuckets?: number;
1610
2022
  }
1611
2023
  /**
1612
- * Redact the secrets / PII out of a value before it reaches the durable log or a
1613
- * Logpush event, via `@visulima/redact`'s `standardRules`. Unlike a blunt
1614
- * type-tag stamp this masks sensitive values by PATTERN (not just by key name)
1615
- * while leaving benign values readable, so the studio's args/identity columns
1616
- * stay useful. `null` / `undefined` pass through unchanged.
1617
- *
1618
- * What `standardRules` actually catches differs by shape, verified against its
1619
- * real behavior rather than assumed from its name: on a KEYED object (`args`,
1620
- * `identity`) it also matches by key name, so `{ password: "hunter2" }` and
1621
- * `{ token: "…" }` ARE masked regardless of the value's shape. On a PLAIN
1622
- * STRING — which is what `errorMessage`/log `fields`-as-rendered-text are —
1623
- * only pattern-shaped matches apply: emails, long digit runs / structured
1624
- * numeric IDs (credit-card, phone, SSN, AWS-access-key-style), and an explicit
1625
- * `Bearer <token>` / `token=…`-shaped substring. A free-text `password=hunter2`
1626
- * or a bare provider API key embedded in prose (e.g. `sk-live-…`) is NOT
1627
- * caught on a plain string — there is no key to match against, and neither is
1628
- * a recognized value pattern. So this is a PII-pattern net for rendered text,
1629
- * not a general secrets scrubber; a handler that echoes a raw credential into
1630
- * an error message or a log string can still leak it through here. Works on a
1631
- * plain string too (`redact` traverses whatever value it's handed), which is
1632
- * how {@link appendRequestLogEntry} and {@link emitRequestLogEvent} reuse this
1633
- * for `errorMessage` — a validation error echoes the offending value, a
1634
- * constraint error quotes the conflicting row, so the error message is at
1635
- * least as PII-dense as args and gets the same treatment (with the free-text
1636
- * caveat above).
2024
+ * Fold one measurement into its `(series, minute)` bucket. Runs per
2025
+ * `ctx.metrics.*` call (unlike `function-metrics.ts`, which runs once per
2026
+ * dispatch), so it's tuned for the in-minute repeat: a bucket this instance has
2027
+ * already written is a single upsert (no reads), a bucket only in the DB costs one
2028
+ * PK point-lookup + upsert, and only a genuinely new bucket also pays the
2029
+ * distinct-series cap scan + retention trim. Still a durable SQLite write per
2030
+ * measurement, so a hot loop recording thousands of points a second should
2031
+ * pre-aggregate and record once (see `shared/metric-event.ts`). Creates the table
2032
+ * first so callers needn't.
1637
2033
  *
1638
- * `captureRaw` is the development escape hatch: in a dev environment the dispatch
1639
- * site (`isDevEnvironment`) passes `true` to skip redaction so a developer can
1640
- * see real arg/identity/error values; production always redacts. The dev
1641
- * decision is made at the call site from the deployment env, never inferred
1642
- * here — so a real deploy that omits the env var stays redacted.
1643
- */
1644
- declare const redactArgs: (value: unknown, captureRaw?: boolean) => unknown;
1645
- /**
1646
- * Create the `__lunora_reqlog__` table. `seq` is an `AUTOINCREMENT` primary
1647
- * key, giving each shard a monotonic cursor the Logs tab pages through; the
1648
- * `args`/`identity`/`tables_read`/`tables_written` columns hold JSON and are
1649
- * `NULL`/empty when none was recorded. Idempotent, so read and write paths can
1650
- * call it defensively.
2034
+ * `exemplarTraceId` (the recording dispatch's trace, when it had one) is stored on
2035
+ * the bucket so the studio can link a chart point back to a trace. Latest wins:
2036
+ * a later sample carrying a trace replaces an earlier bucket's exemplar.
1651
2037
  *
1652
- * `error_fingerprint` is the {@link fingerprintError} grouping hash captured
1653
- * from the RAW `error_message` at write time, before {@link appendRequestLogEntry}
1654
- * redacts it — see that function's docstring. It is added via a guarded
1655
- * `ALTER TABLE` rather than baked into the `CREATE`, mirroring
1656
- * `function-metrics.ts`'s `ensureFunctionMetricsTables`, so a shard whose
1657
- * `__lunora_reqlog__` predates this column gains it on the next call without a
1658
- * migration. SQLite has no `ADD COLUMN IF NOT EXISTS`, so the duplicate-column
1659
- * error from a re-run (or the freshly-created schema above) is swallowed.
2038
+ * `options` tunes the distinct-series cap and retention window from the sink's
2039
+ * `metricHistory` flag (see {@link MetricHistoryOptions}); each defaults to its
2040
+ * module constant.
1660
2041
  */
1661
- declare const ensureRequestLogTable: (sql: SqlExec) => void;
2042
+ declare const recordMetricHistory: (sql: SqlExec, event: MetricEvent, exemplarTraceId?: string, options?: MetricHistoryOptions) => void;
1662
2043
  /**
1663
- * Append one dispatch to the request log, then trim the log back to the most
1664
- * recent `retention` rows (default {@link REQUEST_LOG_RETENTION}). Creates the
1665
- * table first so callers needn't. Args/identity/error message are redacted here
1666
- * so a raw value never reaches the durable table — callers pass the unredacted
1667
- * entry and rely on this, unless `captureRaw` (dev only) is set. `retention` is
1668
- * the operator's `LUNORA_REQUEST_LOG_RETENTION` override, threaded in by the
1669
- * dispatch site.
2044
+ * Read the durable history, grouped into one {@link MetricHistorySeries} per
2045
+ * series with its buckets in ascending time order.
1670
2046
  *
1671
- * The error-grouping fingerprint is computed from `entry.errorMessage` BEFORE
1672
- * it's redacted below, and the resulting hash is persisted in
1673
- * `error_fingerprint`. `readErrorIssues` groups off that stored hash instead of
1674
- * recomputing `fingerprintError` from the (redacted) `error_message` column, so
1675
- * masking a PII-bearing value — e.g. two different `<n>`-bucketed IDs that
1676
- * redact to two different tag lengths (`<DL>` vs `<BANKACC>`) — can't split an
1677
- * existing Issue or change its identity.
1678
- */
1679
- declare const appendRequestLogEntry: (sql: SqlExec, entry: AppendRequestLogEntry, options?: RequestLogWriteOptions) => void;
1680
- /**
1681
- * Emit one structured request event to `console` so Cloudflare's Workers Logs /
1682
- * Logpush pipeline carries it to external sinks (SIEMs) — PLAN3 §3.3. This does
1683
- * NOT reimplement a transport: it produces a richer, lunora-attributed event and
1684
- * lets CF's existing trace-log pipe ship it. The event mirrors the durable
1685
- * `__lunora_reqlog__` row (function path, shard, user, outcome, duration, tables
1686
- * read/written, cache hit), with `args`, `identity`, AND `error` redacted
1687
- * exactly like the durable write so no raw PII/secret reaches the log pipeline.
2047
+ * Rows are fetched most-recent-first (`bucket_ms DESC`) under the row cap, NOT
2048
+ * `series_key`-ordered: all active series write the same recent minutes, so this
2049
+ * windows every series to a recent slice fairly, instead of handing the
2050
+ * alphabetically-first series its full 1440-bucket history and starving the rest
2051
+ * once the cap is hit. Each series' points are re-sorted ascending below, since a
2052
+ * trend line reads oldest→newest.
1688
2053
  *
1689
- * An `error` outcome goes to `console.error` (surfacing at error level in the
1690
- * trace so a SIEM can alert on it); everything else to `console.log`. The
1691
- * `source: "lunora"` / `type: "request"` envelope lets a consumer filter these
1692
- * events out of the raw Workers-trace firehose. `captureRaw` (dev only) skips
1693
- * redaction, mirroring the durable write. Best-effort by contract — the caller
1694
- * wraps it so a serialization hiccup can never fail the served request.
1695
- */
1696
- declare const emitRequestLogEvent: (entry: AppendRequestLogEntry, options?: RequestLogWriteOptions) => void;
1697
- /**
1698
- * The `ctx.log` event contract (shape + severity union) lives in
1699
- * `shared/log-event.ts` (inlined into each `dist`) so the DO that builds these
1700
- * events and the `@lunora/runtime` sink that consumes them agree by construction.
1701
- * `LogEventInput` is the DO's historical name for the shared `LogEvent`.
2054
+ * `options.sinceMs`, when set, returns only buckets at or after this epoch-ms —
2055
+ * the studio's time-window selector. `options.maxSeries`, mirroring the write
2056
+ * side's tunable, is only used to compute `capped` — it does not affect which
2057
+ * rows are read.
1702
2058
  */
1703
- type LogEventInput = LogEvent;
2059
+ declare const readMetricHistory: (sql: SqlExec, options?: {
2060
+ maxSeries?: number;
2061
+ sinceMs?: number;
2062
+ }) => MetricHistoryResult;
2063
+ /** One row of the `__lunora_metrics_queries` table, as returned by `readQueryMetrics`. */
2064
+ interface QueryStatEntry {
2065
+ /** Total number of times this statement was executed. */
2066
+ execCount: number;
2067
+ /** Normalised SQL text (literals stripped, truncated). */
2068
+ normalizedSql: string;
2069
+ /** Total rows SCANNED across all executions (the billed number, not the result-set size). */
2070
+ rowsRead: number;
2071
+ /** Total rows WRITTEN across all executions. */
2072
+ rowsWritten: number;
2073
+ /** Total wall-clock milliseconds across all executions. */
2074
+ totalDurationMs: number;
2075
+ }
2076
+ /** Index of the first histogram edge at or above `durationMs`; the last index is the overflow bucket. */
2077
+ declare const latencyBucketIndex: (durationMs: number) => number;
2078
+ /** One statement's activity within a chosen time range. */
2079
+ interface QueryInsightEntry {
2080
+ /** Mean milliseconds per execution across the range. */
2081
+ avgDurationMs: number;
2082
+ execCount: number;
2083
+ normalizedSql: string;
2084
+ /** Interpolated 50th percentile latency, in milliseconds. */
2085
+ p50DurationMs: number;
2086
+ /** Interpolated 95th percentile latency, in milliseconds. */
2087
+ p95DurationMs: number;
2088
+ rowsRead: number;
2089
+ rowsWritten: number;
2090
+ totalDurationMs: number;
2091
+ }
2092
+ /** One point on the throughput/latency charts. */
2093
+ interface QueryInsightBucket {
2094
+ /** Mean milliseconds per execution in this window, across all statements. */
2095
+ avgDurationMs: number;
2096
+ /** Bucket start, epoch millis. */
2097
+ bucketMs: number;
2098
+ execCount: number;
2099
+ }
2100
+ /** What `getQueryInsights` returns. */
2101
+ interface QueryInsightsResult {
2102
+ /** Time series across the whole range, all statements combined. */
2103
+ buckets: QueryInsightBucket[];
2104
+ /**
2105
+ * True when the tracked-statement cap has been reached, so the caller can say
2106
+ * "showing N of a capped set" rather than implying totality. Silent
2107
+ * truncation reads as complete coverage when it is not.
2108
+ */
2109
+ capped: boolean;
2110
+ entries: QueryInsightEntry[];
2111
+ /** How many distinct statements the lifetime table is tracking. */
2112
+ trackedStatements: number;
2113
+ }
1704
2114
  /**
1705
- * Split a `ctx.log.<level>(...)` call's raw arguments into a display `message`
1706
- * and optional structured `fields`. The structured form — a message string plus
1707
- * a plain-object fields bag — is matched only for exactly `(string, object)`;
1708
- * every other shape is console-style and rendered whole (so existing
1709
- * `console`-shaped calls are unchanged). Bound `.with(...)` fields merge under
1710
- * the per-call fields (per-call wins); the result is normalized to a fresh bag
1711
- * of JSON-safe primitives, or `undefined` when empty (see `normalizeLogFields`).
2115
+ * Per-statement activity within `rangeMs` of `now`, plus a combined time series.
2116
+ *
2117
+ * Reads the bucket table (not the lifetime one) so the numbers answer "what is
2118
+ * hot right now"; the statement TEXT is joined back from the lifetime table,
2119
+ * which is the only place it is stored.
1712
2120
  */
1713
- declare const parseLogArgs: (args: unknown[], boundFields?: LogFields) => {
1714
- fields?: LogFields;
1715
- message: string;
1716
- };
2121
+ declare const readQueryInsights: (sql: SqlExec, rangeMs: number, now?: number) => QueryInsightsResult;
1717
2122
  /**
1718
- * Emit one application-log event from a `ctx.log.*` call to `console`, tagged
1719
- * `{ source: "lunora", type: "log" }` so the CLI / Vite formatter can pretty-print
1720
- * it in the dev terminal and a Logpush/SIEM consumer can filter it out of the
1721
- * raw Workers-trace firehose.
1722
- *
1723
- * Only the rendered `message` is emitted here, NOT the structured `args` array:
1724
- * the console event rides CF Workers Logs / Logpush to prod, and shipping raw,
1725
- * un-redacted arg objects on a `source: "lunora"` line a SIEM is told to trust
1726
- * would be a surprising PII/secret surface. The raw `args` stay on the in-process
1727
- * `sink.onLog` path (`recordUserLog`), which the operator opts into and controls.
1728
- * `message` already carries the developer's rendered values, exactly like a raw
1729
- * `console.log` line.
1730
- *
1731
- * `error`/`fatal` go to `console.error`, `warn` to `console.warn` (so they
1732
- * surface at the right level in the trace); every other level to `console.log`.
2123
+ * Record one statement's activity. Creates the table on first call. Silently
2124
+ * skips recording when the normalised statement is empty (shouldn't happen
2125
+ * in practice) or when the table is already at the
2126
+ * {@link QUERY_METRICS_MAX_STATEMENTS} cap and the statement is not yet
2127
+ * tracked. See `admitStatement` for how the cap check avoids an unconditional
2128
+ * `COUNT(*)` on every execution.
1733
2129
  *
1734
- * Structured `fields` (plus `traceId`/`spanId` for correlation) ARE emitted here
1735
- * — they are intentional metadata a log pipeline filters on, unlike raw `args`.
1736
- * Unlike `args`, `fields` IS redacted before it rides this console line — a
1737
- * developer can attach anything to a fields bag (`ctx.log.info("charged",
1738
- * { email, cardLast4 })`), and this is the one line that's told to a SIEM as
1739
- * trustworthy, exactly like the request-log `args`/`identity`/`error` columns.
1740
- * `options.captureRaw` (dev only) skips it, mirroring every other redaction
1741
- * point in this module; the sole current caller (`ShardDO.recordUserLog`)
1742
- * doesn't yet thread a dev flag through, so `fields` redacts unconditionally
1743
- * there today — a conservative default, never a correctness gap. A field value
1744
- * that can't be serialised (a circular object) would make `JSON.stringify`
1745
- * throw and drop the whole line, so serialisation falls back to a fields-free
1746
- * line rather than losing the event.
2130
+ * `execCount` (default 1) lets a caller fold several executions of the SAME
2131
+ * statement into one call — `shard-do.ts` does this per dispatch so a
2132
+ * query-in-a-loop handler pays one upsert here instead of one per raw
2133
+ * execution. `durationMs`/`rowsRead`/`rowsWritten` are then the SUM across
2134
+ * `execCount` executions, exactly as `exec_count`/`total_duration_ms` already
2135
+ * accumulate sums across separate calls — folding before calling is
2136
+ * indistinguishable, from this table's point of view, from `execCount`
2137
+ * separate calls with the same totals.
1747
2138
  */
1748
- declare const emitLogEvent: (input: LogEventInput, options?: RequestLogWriteOptions) => void;
2139
+ declare const recordQueryMetric: (sql: SqlExec, rawSql: string, durationMs: number, rowsRead: number, rowsWritten: number, now?: number, execCount?: number) => void;
1749
2140
  /**
1750
- * Read request-log entries newest-first, AND-combining the supplied filters
1751
- * (function-path prefix, exact userId/shardKey/outcome, and a table-touched
1752
- * match against the read OR written table sets), up to `limit` (clamped to
1753
- * [1, 10000]). Each value is a bound parameter, so no filter can inject SQL.
1754
- * Creates the table first so reads on a never-logged shard return `[]` instead
1755
- * of throwing. Mirrors `readAuditLog`/`readCdcChanges`.
2141
+ * Read all tracked statement aggregates, ordered by `total_duration_ms DESC`
2142
+ * (the leaderboard's default). Creates the table first so a read on a
2143
+ * never-called shard returns `[]`.
1756
2144
  */
1757
- declare const readRequestLog: (sql: SqlExec, options?: ReadRequestLogOptions) => RequestLogEntry[];
1758
- declare const readErrorIssues: (sql: SqlExec, options?: ReadIssuesOptions) => ErrorIssue[];
2145
+ declare const readQueryMetrics: (sql: SqlExec) => QueryStatEntry[];
1759
2146
  /**
1760
2147
  * Ordering/visual weight of a security finding — mirrors the studio's insight
1761
2148
  * severities so the Security Advisor and the Performance Advisor (Insights) share
@@ -1770,7 +2157,7 @@ type SecurityFindingLevel = "error" | "info" | "warning";
1770
2157
  *
1771
2158
  * `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.)
1772
2159
  *
1773
- * `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.
2160
+ * `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.
1774
2161
  *
1775
2162
  * `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.
1776
2163
  *
@@ -1842,6 +2229,15 @@ interface TraceSpan {
1842
2229
  message: string;
1843
2230
  type: string;
1844
2231
  };
2232
+ /**
2233
+ * Timestamped occurrences inside the span — `span.addEvent(...)` and
2234
+ * `span.recordException(...)`. Carried through so a handled retry or a
2235
+ * swallowed exception is visible on the span it happened in, which is the
2236
+ * only place it is interpretable. Absent when the body recorded none.
2237
+ */
2238
+ events?: SpanEventPoint[];
2239
+ /** OTel `SpanKind`; absent means `"internal"`. */
2240
+ kind?: OtlpSpanKind;
1845
2241
  name: string;
1846
2242
  /** Start of this span relative to the trace's start, in ms. */
1847
2243
  offsetMs: number;
@@ -1860,12 +2256,25 @@ interface TraceSummary {
1860
2256
  rootName: string;
1861
2257
  shardKey?: string;
1862
2258
  /**
1863
- * Spans ordered by `(offsetMs, depth)`, ready to render as waterfall rows.
1864
- * Start time alone is not enough to order them: spans are recorded on
1865
- * completion and `startTs` has millisecond resolution, so a parent and its
1866
- * child routinely tie. Breaking that tie by depth makes the sequence a valid
1867
- * pre-order traversal of the span tree, so indenting each row by its `depth`
1868
- * yields the nesting without a separate tree walk.
2259
+ * Spans in **pre-order**, ready to render as waterfall rows: every span is
2260
+ * immediately followed by its own subtree, siblings in start order. So
2261
+ * indenting each row by its `depth` yields the real nesting — the row above
2262
+ * a `depth`-`n+1` row is genuinely its parent.
2263
+ *
2264
+ * This is a tree walk, not a sort, because no ordering on `(offsetMs,
2265
+ * depth)` can produce it. Given a parent, its child `a`, `a`'s child `a1`
2266
+ * and `a`'s sibling `b` all at offset 0, that comparator yields
2267
+ * `parent, a, b, a1` — which renders `a1` indented beneath `b`, under a
2268
+ * parent it does not belong to.
2269
+ *
2270
+ * **Why they tie is not millisecond resolution.** On the Workers runtime
2271
+ * `Date.now()` is pinned to the time of the last I/O — a Spectre mitigation,
2272
+ * not a bug — so it does not advance at all across pure computation. Every
2273
+ * duration in this package is `Date.now() - startTs`, which means a span
2274
+ * wrapping CPU-only work reports `0`, and a parent whose child performed no
2275
+ * I/O shares its exact start and end. See `docs/concepts/observability`
2276
+ * ("Span durations on Workers"); the practical consequence is that a `0 ms`
2277
+ * span means "no I/O happened here", not "this was fast".
1869
2278
  */
1870
2279
  spans: TraceSpan[];
1871
2280
  startTs: number;
@@ -1880,10 +2289,19 @@ interface TraceSummary {
1880
2289
  declare class SpanBuffer {
1881
2290
  private readonly buffer;
1882
2291
  private readonly capacity;
2292
+ /** How many spans the ring has evicted since it was last cleared. */
2293
+ private droppedCount;
1883
2294
  constructor(capacity?: number);
2295
+ /**
2296
+ * Spans evicted for capacity since the last {@link SpanBuffer.clear}. The
2297
+ * ring silently drops its oldest span once full, which makes a busy instance
2298
+ * look identical to one that recorded exactly `capacity` spans; this count
2299
+ * is the difference between the two.
2300
+ */
2301
+ get dropped(): number;
1884
2302
  /** Number of spans currently buffered. */
1885
2303
  get size(): number;
1886
- /** Drop every buffered span. */
2304
+ /** Drop every buffered span, including the eviction count. */
1887
2305
  clear(): void;
1888
2306
  /** Snapshot of the buffered spans in insertion order. Fresh array per call. */
1889
2307
  entries(): SpanEvent[];
@@ -1959,10 +2377,71 @@ declare const findDanglingReferences: (sql: SqlExec, storageColumns: Record<stri
1959
2377
  * worker's trace and any container's beneath it), else freshly minted so a
1960
2378
  * dispatch with no inbound context — a subscription re-run, a server-initiated
1961
2379
  * call — still produces a coherent, self-contained local trace.
2380
+ *
2381
+ * `rayHeader` is the Cloudflare Ray ID the runtime forwarded alongside the
2382
+ * `traceparent` (`x-lunora-ray-id`). It is re-validated here and carried on the
2383
+ * anchor so every span and log line of the dispatch stamps it; absent or
2384
+ * malformed, the anchor simply has none. Informational only — see
2385
+ * {@link parseRayId}.
1962
2386
  */
1963
- declare const resolveTraceAnchor: (traceparent: string | undefined) => {
1964
- rootSpanId: string;
2387
+ declare const resolveTraceAnchor: (traceparent: string | undefined, rayHeader?: null | string) => TraceAnchor & {
1965
2388
  sampled: boolean;
1966
- traceId: string;
1967
2389
  };
1968
- 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 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, type QueryInsightBucket, type QueryInsightEntry, type QueryInsightsResult, type QueryStatEntry, REQUEST_LOG_TABLE, type ReadIssuesOptions, type ReadRequestLogOptions, type RecordAuthEventInput, type RecordFunctionMetricInput, type RequestLogEntry, type RequestLogResult, type RequestLogWriteOptions, type RequestOutcome, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, SpanBuffer, type SpanCollection, type SpanCollector, type SpanEvent, type SpanEventPoint, type SpanHandle, type OtlpSpanKind as SpanKind, type SpanLink, type SpanOptions, type TraceAnchor, type TraceSpan, type TraceSummary, type TracedFetchDeps, 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, redactArgs, resolveTraceAnchor, upsertIssueState };
2390
+ export { AUTH_METRICS_BUCKETS_TABLE, AUTH_METRICS_BUCKET_MS, AUTH_METRICS_BUCKET_RETENTION, AUTH_METRICS_TABLE, type AiRunBinding, type AppendRequestLogEntry,
2391
+ /**
2392
+ * `@lunora/observability` — host-neutral telemetry storage and read models.
2393
+ *
2394
+ * Logs, traces, metrics, issue grouping and the security-audit view: the data
2395
+ * behind the Studio's observability pages. None of it is Cloudflare-specific —
2396
+ * it reads and writes through the SQL handle the engine hands it, and it lived
2397
+ * inside `@lunora/do` only because that is where the Durable Object it
2398
+ * instruments happens to live.
2399
+ *
2400
+ * The dependency runs `@lunora/do` → here → `@lunora/shard-engine`, never the
2401
+ * reverse, which is what makes this reusable by a second host rather than
2402
+ * merely relocated.
2403
+ *
2404
+ * This barrel is deliberately curated rather than `export *`. A star export
2405
+ * would promote every module internal to permanent public API — the exact
2406
+ * mistake `@lunora/do`'s own barrel documents having made once with the search
2407
+ * core. What is exported here is what a consumer actually needs.
2408
+ */
2409
+ type AuthMetrics,
2410
+ /**
2411
+ * `@lunora/observability` — host-neutral telemetry storage and read models.
2412
+ *
2413
+ * Logs, traces, metrics, issue grouping and the security-audit view: the data
2414
+ * behind the Studio's observability pages. None of it is Cloudflare-specific —
2415
+ * it reads and writes through the SQL handle the engine hands it, and it lived
2416
+ * inside `@lunora/do` only because that is where the Durable Object it
2417
+ * instruments happens to live.
2418
+ *
2419
+ * The dependency runs `@lunora/do` → here → `@lunora/shard-engine`, never the
2420
+ * reverse, which is what makes this reusable by a second host rather than
2421
+ * merely relocated.
2422
+ *
2423
+ * This barrel is deliberately curated rather than `export *`. A star export
2424
+ * would promote every module internal to permanent public API — the exact
2425
+ * mistake `@lunora/do`'s own barrel documents having made once with the search
2426
+ * core. What is exported here is what a consumer actually needs.
2427
+ */
2428
+ 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,
2429
+ /**
2430
+ * `@lunora/observability` — host-neutral telemetry storage and read models.
2431
+ *
2432
+ * Logs, traces, metrics, issue grouping and the security-audit view: the data
2433
+ * behind the Studio's observability pages. None of it is Cloudflare-specific —
2434
+ * it reads and writes through the SQL handle the engine hands it, and it lived
2435
+ * inside `@lunora/do` only because that is where the Durable Object it
2436
+ * instruments happens to live.
2437
+ *
2438
+ * The dependency runs `@lunora/do` → here → `@lunora/shard-engine`, never the
2439
+ * reverse, which is what makes this reusable by a second host rather than
2440
+ * merely relocated.
2441
+ *
2442
+ * This barrel is deliberately curated rather than `export *`. A star export
2443
+ * would promote every module internal to permanent public API — the exact
2444
+ * mistake `@lunora/do`'s own barrel documents having made once with the search
2445
+ * core. What is exported here is what a consumer actually needs.
2446
+ */
2447
+ 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 };