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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +2 -4
  2. package/dist/index.d.mts +1649 -1183
  3. package/dist/index.d.ts +1649 -1183
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/AUTH_METRICS_BUCKETS_TABLE-BpH1ZAgX.mjs +22 -0
  6. package/dist/packem_shared/DEFAULT_EXPLAIN_ISSUE_MODEL-BkFTgdkd.mjs +3 -0
  7. package/dist/packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-Dha-40Hv.mjs +56 -0
  8. package/dist/packem_shared/ISSUE_SEVERITIES-0SJ0glV4.mjs +15 -0
  9. package/dist/packem_shared/LogBuffer-BmD4CfV0.mjs +1 -0
  10. package/dist/packem_shared/MIN_ADMIN_TOKEN_LENGTH-DSOQ6rno.mjs +1 -0
  11. package/dist/packem_shared/MetricBuffer-BUw1hK3f.mjs +1 -0
  12. package/dist/packem_shared/NO_SENSITIVE_SCOPE-z-NXXakX.mjs +1 -0
  13. package/dist/packem_shared/SpanBuffer-C8-8zvYg.mjs +1 -0
  14. package/dist/packem_shared/applyHostRootSpan-DToRfMn8.mjs +1 -0
  15. package/dist/packem_shared/createDatabaseTally-BNj6kmo2.mjs +2 -0
  16. package/dist/packem_shared/createMetrics-C6AXtDTF.mjs +1 -0
  17. package/dist/packem_shared/findDanglingReferences-BaOyIdxz.mjs +1 -0
  18. package/dist/packem_shared/latencyBucketIndex--kZoW0vc.mjs +32 -0
  19. package/dist/packem_shared/otlp-DR7601NL.mjs +1 -0
  20. package/dist/packem_shared/prune-marker-CksedkkK.mjs +1 -0
  21. package/dist/packem_shared/readMetricHistory-BjPDSBkS.mjs +31 -0
  22. package/dist/packem_shared/request-log-B7gOe-_k.mjs +24 -0
  23. package/dist/packem_shared/resolveTraceAnchor-DDAPZRBB.mjs +1 -0
  24. package/dist/packem_shared/run-sql-0aPgJkIw.mjs +1 -0
  25. package/package.json +6 -5
  26. package/dist/packem_shared/AUTH_METRICS_BUCKETS_TABLE-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-C8RqqEFA.mjs +0 -1
  34. package/dist/packem_shared/SpanBuffer-Z-gV9PQk.mjs +0 -1
  35. package/dist/packem_shared/createDatabaseTally-oPXdBqRN.mjs +0 -1
  36. package/dist/packem_shared/createMetrics-BD9PSRte.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-BKVYrL1-.mjs +0 -22
  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,1288 +566,1584 @@ 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.
647
640
  *
648
- * Two gaps close here. First, an uninstrumented `fetch` makes the single most
649
- * common source of latency — waiting on somebody else's service — invisible: a
650
- * handler that spends 900ms in Stripe shows one opaque 900ms bar. Second,
651
- * without an outbound `traceparent` the callee starts a brand-new trace, so the
652
- * two halves of one logical request can never be stitched together, which is the
653
- * entire premise of distributed tracing.
654
- *
655
- * The span id is minted BEFORE the request is sent, precisely so the header
656
- * announces the id the span will actually be recorded under. Deriving it
657
- * afterwards (or reusing the parent's) would produce a `traceparent` naming a
658
- * span that never existed, and a callee parented to nothing.
659
- *
660
- * Kind is `client` rather than `internal` — that is what lets a collector draw
661
- * the edge to the downstream service in a service map.
662
- *
663
- * Failures are recorded and re-thrown untouched, and a non-2xx response is
664
- * recorded as an ERROR span (it is a failed call from the caller's point of
665
- * view) while still being returned normally — instrumentation, never flow
666
- * control.
667
- */
668
- declare const createTracedFetch: (deps: TracedFetchDeps, base: ContextFetch) => ContextFetch;
669
- /**
670
- * Build the `ctx.metrics` recorder for one dispatched function.
671
- *
672
- * Deliberately stateless: each call emits one measurement rather than
673
- * accumulating into a per-dispatch map. Pre-aggregating here would have to pick a
674
- * flush point and a merge rule per instrument kind (sum a counter, last-wins a
675
- * gauge, and a histogram cannot be merged at all without losing the
676
- * distribution) — so the runtime stays a transport and the collector, which is
677
- * built for exactly this, does the aggregation.
678
- */
679
- declare const createMetrics: (deps: MetricsDeps) => ContextMetrics;
680
- /**
681
- * Build the synthetic root span for a finished dispatch — the bar the studio's
682
- * waterfall hangs a request's `ctx.trace` spans under.
683
- *
684
- * Pure: the caller decides whether to record it (only when the dispatch actually
685
- * produced spans) and where to put it. It is never routed to `sink.onSpan`,
686
- * because the runtime already emits the dispatch to `onRpc` and a collector would
687
- * otherwise show it twice.
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`.
688
645
  */
689
- declare const dispatchRootSpan: (input: {
690
- anchor: TraceAnchor;
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;
691
697
  /**
692
- * Whether to record the failure message verbatim rather than redacted —
693
- * the same dev-only escape hatch as {@link TracerDeps.captureRaw}. This
694
- * synthetic root span carries the SAME error message the request log and
695
- * function-metrics sinks already redact by default, so it must not be the
696
- * one durable copy that ships it raw to a third-party collector.
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.
697
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). */
698
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;
699
730
  /**
700
- * What the handler attached to the dispatch through `ctx.span` — the **wide
701
- * event**. These are the attributes that would otherwise have been scattered
702
- * across a dozen `ctx.log` lines; carrying them on the one span that already
703
- * exists per request is the OTel-native way to get a wide event without
704
- * multiplying log records.
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.
705
735
  */
706
- collected?: SpanCollection;
707
- durationMs: number;
708
- failure: {
709
- thrown: unknown;
710
- } | undefined;
711
- functionPath: string;
712
- shardKey: string | undefined;
713
- startTs: number;
714
- userId: string | undefined;
715
- }) => SpanEvent;
716
- /** Running totals for `"summary"` mode; created by the caller, read once at the dispatch boundary. */
717
- interface DatabaseTally {
718
- calls: number;
719
- durationMs: number;
720
- errors: number;
721
- perOperation: Record<string, number>;
722
- spansEmitted: number;
723
- spansTruncated: boolean;
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[];
724
745
  }
725
746
  /**
726
- * How much detail `ctx.db` auto-instrumentation produces.
727
- *
728
- * `"summary"` (default) — aggregate counters on the dispatch's wide event: no
729
- * extra spans, no extra log records, and a cost that does not grow with call count.
730
- *
731
- * `"spans"` — one span per database call. The full waterfall, at the price of a
732
- * span per call; right when diagnosing, noisy as a permanent default.
733
- *
734
- * `"off"` — no database telemetry at all.
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.
735
751
  */
736
- type DatabaseInstrumentation = "off" | "spans" | "summary";
737
- /** What {@link instrumentDatabase} needs to record what it observes. */
738
- interface DatabaseTelemetryDeps {
739
- /** The trace produced spans belong to (`"spans"` mode only). */
740
- anchor: TraceAnchor;
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;
741
761
  /**
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.
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.
747
766
  */
748
- captureRaw?: boolean;
749
- /** Function path spans and attributes are attributed to. */
750
- functionPath: string;
751
- /** Detail level; see {@link DatabaseInstrumentation}. */
752
- mode: DatabaseInstrumentation;
753
- /** Hand a finished span to the buffer + sink (`"spans"` mode only). */
754
- record: (span: SpanEvent) => void;
755
- /** Shard key for single-shard calls; absent for the unnamed root DO. */
756
- shardKey: string | undefined;
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;
757
774
  /**
758
- * Caller-supplied accumulator for `"summary"` mode. The instrumenter only ever
759
- * increments numbers on it; the shard reads it ONCE at the dispatch boundary
760
- * and formats it with {@link formatTally}.
761
- *
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.
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).
767
778
  */
768
- tally: DatabaseTally;
769
- /** Read lazily — the acting user is resolved per span. */
770
- userId: () => string | undefined;
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;
771
806
  }
772
807
  /**
773
- * Wrap a `ctx.db` writer so its storage-touching methods are instrumented.
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.
774
844
  *
775
- * Returns the database unchanged when `mode` is `"off"`, so the default-disabled
776
- * path costs nothing — not even a proxy indirection.
777
- *
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.
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.
784
850
  */
785
- declare const instrumentDatabase: <T extends object>(database: T, deps: DatabaseTelemetryDeps) => T;
786
- /** A zero'd tally for one dispatch. */
787
- declare const createDatabaseTally: () => DatabaseTally;
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»";
788
854
  /**
789
- * Render the running tally as span attributes.
790
- *
791
- * 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.
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.
794
860
  */
795
- declare const formatTally: (tally: DatabaseTally) => LogFields;
796
- /** Reserved per-function accumulator table. Auto-hidden from the data browser by the `__lunora` prefix. */
797
- declare const FUNCTION_METRICS_TABLE = "__lunora_metrics";
798
- /** Reserved coarse time-series table: per-function call/error counts bucketed by a fixed window. */
799
- declare const FUNCTION_METRICS_BUCKETS_TABLE = "__lunora_metrics_buckets";
800
- /** Reserved causal full-scan attribution table: per-(function, table) full-scan counts. */
801
- declare const FUNCTION_METRICS_SCANS_TABLE = "__lunora_metrics_scans";
802
- /** Reserved per-(table, index) hit-counter table backing the advisor dead-index lint. */
803
- declare const FUNCTION_METRICS_INDEX_TABLE = "__lunora_metrics_index";
804
- /**
805
- * Width of one history bucket, in milliseconds. 60s gives a minute-resolution
806
- * time series — fine-grained enough to chart bursts on the studio, coarse
807
- * enough that a single function emits at most one row per minute. Exported so
808
- * consumers (and tests) can align timestamps to the same grid.
809
- */
810
- declare const FUNCTION_METRICS_BUCKET_MS = 6e4;
811
- /**
812
- * Most recent buckets kept per function; older rows are trimmed after each
813
- * write so the time series can't grow unbounded. 1440 minute-buckets ≈ 24h of
814
- * history per function.
815
- */
816
- declare const FUNCTION_METRICS_BUCKET_RETENTION = 1440;
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[];
817
863
  /**
818
- * Maximum distinct function `path`s tracked in the accumulator table. Mirrors
819
- * `query-metrics.ts`'s `QUERY_METRICS_MAX_STATEMENTS` cap (and exists for the
820
- * same reason): the real bound is the app's own registered-function set plus
821
- * deploy churn (a rename/removal leaves its old path's row in place, still
822
- * counted against the cap, until an operator's own retention/cleanup
823
- * process — there is none built in today) — a few thousand registered
824
- * functions is already far beyond any real app. `shard-do.ts`'s dispatch
825
- * handler explicitly does NOT record per-function metrics for an
826
- * unregistered/`FUNCTION_NOT_FOUND` dispatch (see the guard next to its
827
- * `FUNCTION_NOT_FOUND` check), so a caller cannot mint arbitrary `path`s here
828
- * the way a raw caller-supplied SQL shape can in `query-metrics.ts`. Without a
829
- * cap, deploy churn across the app's lifetime would still grow
830
- * `__lunora_metrics` (and its bucket/scan satellites) without bound,
831
- * eventually filling the shard's SQLite store shared with the app's real
832
- * data. At the cap, a brand-new path is refused — protecting the incumbent
833
- * leaderboard from a flood of one-off paths is the point, so admission is
834
- * refused rather than evicting an existing path to make room; already-tracked
835
- * paths keep accumulating past the cap. `readFunctionMetricsTotals`'s
836
- * `capped` is the read-side signal for this.
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.
837
868
  */
838
- declare const FUNCTION_METRICS_MAX_PATHS = 5e3;
869
+ declare const sensitiveNames: (args: Record<string, unknown>, sensitive: ReadonlySet<string>) => string[];
839
870
  /**
840
- * Upper bound on rows the admin reads materialize into DO memory at once. Even
841
- * with the write-side `FUNCTION_METRICS_MAX_PATHS` cap in place, an existing
842
- * shard could already hold a bloated accumulator (rows written before the cap
843
- * landed), so the read path also clamps — a `SELECT *` with no LIMIT would
844
- * otherwise load every row via `.toArray()` and risk OOMing the ~128MB DO when
845
- * the studio Function Stats panel opens. Ordered reads keep the busiest/most
846
- * recent rows; the tail past this limit is simply not returned to the panel.
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.
847
877
  */
848
- declare const FUNCTION_METRICS_READ_LIMIT = 1e3;
849
- /** One coarse time-series sample for a function: call/error counts within `[bucketMs, bucketMs + FUNCTION_METRICS_BUCKET_MS)`. */
850
- interface FunctionMetricBucket {
851
- /** Epoch-ms floor of the bucket window. */
852
- bucketMs: number;
853
- /** Dispatches recorded in this window. */
854
- calls: number;
855
- /** Subset of `calls` that threw. */
856
- errors: number;
857
- }
858
- /** {@link readFunctionMetricBuckets} result: the time-series window plus whether the read limit cut it short. */
859
- interface FunctionMetricBucketsResult {
860
- buckets: (FunctionMetricBucket & {
861
- path: string;
862
- })[];
878
+ interface SensitiveScope {
863
879
  /**
864
- * True when more rows existed than {@link FUNCTION_METRICS_READ_LIMIT} could
865
- * return, so `buckets` is a partial (newest) window rather than the app's
866
- * full retained history. Mirrors `readQueryInsights`'s `capped` and
867
- * `foldTraces`'s `total`: a silently truncated read looks identical to a
868
- * complete one to a caller that doesn't check for it — the Metrics chart's
869
- * window would appear to shrink as the app grows, with a wrong leftmost
870
- * bar, and nothing would say why.
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.
871
884
  */
872
- truncated: boolean;
873
- }
874
- /** One declared index a dispatch exercised (used to narrow a read). */
875
- interface IndexHit {
876
- /** The declared index name. */
877
- index: string;
878
- /** The table the index is declared on. */
879
- table: string;
880
- }
881
- /** One declared index's cumulative recorded read count (durable, non-decaying) — the advisor dead-index lint input. */
882
- interface FunctionMetricIndexHit {
883
- /** The declared index name. */
884
- index: string;
885
- /** Recorded reads that used this index to narrow. */
886
- reads: number;
887
- /** The table the index is declared on. */
888
- table: string;
889
- }
890
- /** Fields recorded for one completed dispatch. `errored` advances the failure counters. */
891
- interface RecordFunctionMetricInput {
885
+ add: (values: ReadonlyArray<string>, names?: ReadonlyArray<string>) => void;
892
886
  /**
893
- * Whether the dispatch failed on an optimistic-concurrency (OCC) write
894
- * conflict — a compare-and-swap that lost to a concurrent commit. Advances
895
- * the durable `conflicts` counter behind the write-contention advisor. A
896
- * conflicted dispatch also `errored`, so conflicts are a subset of errors.
897
- * Omitted/false on the common path, keeping the hot path unchanged.
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.
898
889
  */
899
- conflicted?: boolean;
900
- /** Wall-clock millis the handler took. */
901
- durationMs: number;
902
- /** Whether the dispatch threw. */
903
- errored: boolean;
904
- /** Most recent failure message, recorded only when `errored`. */
905
- errorMessage?: string;
890
+ clear: () => void;
891
+ /** Scrub a field bag; `undefined` passes through. */
892
+ fields: <T extends Record<string, unknown> | undefined>(bag: T) => T;
906
893
  /**
907
- * Distinct declared indexes this dispatch exercised (used to narrow a read),
908
- * collected from the `onIndexUse` signal. Each entry bumps the
909
- * per-`(table, index)` hit counter in `__lunora_metrics_index`, the durable
910
- * producer behind the advisor dead-index lint. Omitted/empty when the
911
- * dispatch used no declared index, keeping the hot path unchanged.
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.
912
897
  */
913
- indexHits?: ReadonlyArray<IndexHit>;
914
- /** The `<file>:<function>` identifier. */
915
- path: string;
898
+ hold: () => () => void;
916
899
  /**
917
- * Distinct tables this dispatch full-scanned (read with no index / point
918
- * lookup), collected from the `SCAN_DEP` reads. Each entry bumps the
919
- * aggregate `scans` counter and the per-`(path, table)` attribution row.
920
- * Omitted/empty when the dispatch didn't full-scan anything (the common
921
- * indexed case), keeping the hot path to the same two upserts as before.
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.
922
902
  */
923
- scannedTables?: ReadonlyArray<string>;
924
- /** Epoch-ms the dispatch completed. */
925
- ts: number;
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;
926
908
  }
927
909
  /**
928
- * Create the four reserved metrics tables. Idempotent, so the read and write
929
- * paths can call it defensively. The accumulator table is keyed by `path` (one
930
- * row per function); the bucket table by `(path, bucketMs)` (one row per
931
- * function per window); the scans table by `(path, table)` (one row per
932
- * function per full-scanned table); the index table by `(table, index)` (one
933
- * row per declared index the app exercises).
934
- *
935
- * The accumulator's `scans` column is added via a guarded `ALTER TABLE` rather
936
- * than baked into the `CREATE` so a shard whose `__lunora_metrics` predates the
937
- * causal-attribution feature gains the column on the next call without a
938
- * migration. SQLite has no `ADD COLUMN IF NOT EXISTS`, so the duplicate-column
939
- * error from a re-run is swallowed. Both the `CREATE`s and the back-fill only
940
- * run once per handle (see {@link ensuredHandles}) — a handle already marked
941
- * ensured returns immediately.
942
- */
943
- declare const ensureFunctionMetricsTables: (sql: SqlExec) => void;
944
- /**
945
- * Persist one completed dispatch: a single upsert into the accumulator row and
946
- * one upsert into the current time bucket, then a bounded trim of old buckets
947
- * for that path. Creates the tables first so callers needn't. This is the hot
948
- * path — exactly two `INSERT … ON CONFLICT … DO UPDATE` statements plus a
949
- * bounded `DELETE`, all keyed by primary key, so it stays cheap.
950
- *
951
- * When the dispatch full-scanned one or more tables (`scannedTables`), the
952
- * aggregate `scans` counter on the accumulator row advances by the distinct
953
- * table count and one extra `(path, table)` upsert fires per scanned table.
954
- * Indexed dispatches (the common case) skip all of that and pay nothing.
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.
955
913
  */
956
- declare const recordFunctionMetric: (sql: SqlExec, input: RecordFunctionMetricInput) => void;
914
+ declare const createSensitiveScope: (values: ReadonlyArray<string>, names?: ReadonlyArray<string>) => SensitiveScope;
957
915
  /**
958
- * Read the per-function full-scan attribution, grouped by function path. The
959
- * returned map keys are `path`; each value is the function's full-scanned
960
- * tables ordered by scan count (busiest scan first), so the causal "slow
961
- * BECAUSE it scanned X" read can lead with the dominant table. Creates the
962
- * table first so reads on a never-called shard return an empty map.
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.
963
918
  */
964
- declare const readFunctionMetricScans: (sql: SqlExec) => Map<string, FunctionScanAttribution[]>;
919
+ declare const NO_SENSITIVE_SCOPE: SensitiveScope;
965
920
  /**
966
- * Read the per-`(table, index)` hit counts — the advisor dead-index lint input.
967
- * Each entry is a declared index and how many recorded reads used it to narrow
968
- * (a cumulative, non-decaying count); the lint reconciles this against the schema
969
- * to flag a declared index that appears with zero reads (or not at all) as dead. Ordered
970
- * by table then index for stable output. Creates the table first so a read on a
971
- * never-exercised shard returns `[]`.
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.
972
940
  */
973
- declare const readFunctionMetricIndexHits: (sql: SqlExec) => FunctionMetricIndexHit[];
941
+ declare const ensureRequestLogTable: (sql: SqlExec) => void;
974
942
  /**
975
- * Fold a dispatch's distinct full-scanned tables into an in-memory attribution
976
- * list, mirroring the per-`(path, table)` upsert {@link recordFunctionMetric}
977
- * applies to the durable `__lunora_metrics_scans` table. Kept here, beside its
978
- * SQL twin, so the one rule (one occurrence = +1 scan for that table, list
979
- * re-sorted busiest-first) lives in a single module — the in-memory copy exists
980
- * only for the warm-instance fallback when the durable read is unavailable.
981
- * Mutates and returns `into`.
943
+ * Append one dispatch to the request log, then — once per
944
+ * {@link REQUEST_LOG_PRUNE_WINDOW_MS} window — trim the log back to the most
945
+ * recent `retention` rows (default {@link REQUEST_LOG_RETENTION}). Creates the
946
+ * table first so callers needn't. Args/identity/error message are redacted here
947
+ * so a raw value never reaches the durable table — callers pass the unredacted
948
+ * entry and rely on this, unless `captureRaw` (dev only) is set. `retention` is
949
+ * the operator's `LUNORA_REQUEST_LOG_RETENTION` override, threaded in by the
950
+ * dispatch site.
951
+ *
952
+ * The error-grouping fingerprint is computed from `entry.errorMessage` BEFORE
953
+ * it's redacted below, and the resulting hash is persisted in
954
+ * `error_fingerprint`. `readErrorIssues` groups off that stored hash instead of
955
+ * recomputing `fingerprintError` from the (redacted) `error_message` column, so
956
+ * masking a PII-bearing value — e.g. two different `<n>`-bucketed IDs that
957
+ * redact to two different tag lengths (`<DL>` vs `<BANKACC>`) — can't split an
958
+ * existing Issue or change its identity.
982
959
  */
983
- declare const mergeScanAttribution: (into: FunctionScanAttribution[], scanned: ReadonlyArray<string>) => FunctionScanAttribution[];
960
+ declare const appendRequestLogEntry: (sql: SqlExec, entry: AppendRequestLogEntry, options?: RequestLogWriteOptions) => void;
984
961
  /**
985
- * Read the persisted per-function accumulators as {@link FunctionCallStat}s,
986
- * newest-called first. Creates the table first so reads on a never-called shard
987
- * return `[]` instead of throwing. The shape is a superset of the legacy
988
- * in-memory `getFunctionStats` rows — the additive `scans` total and
989
- * `scannedTables` causal attribution are folded in here so a single read backs
990
- * the Insights "missing index" / "full scan" signal.
962
+ * Emit one structured request event to `console` so Cloudflare's Workers Logs /
963
+ * Logpush pipeline carries it to external sinks (SIEMs) — PLAN3 §3.3. This does
964
+ * NOT reimplement a transport: it produces a richer, lunora-attributed event and
965
+ * lets CF's existing trace-log pipe ship it. The event mirrors the durable
966
+ * `__lunora_reqlog__` row (function path, shard, user, outcome, duration, tables
967
+ * read/written, cache hit), with `args`, `identity`, AND `error` redacted
968
+ * exactly like the durable write so no raw PII/secret reaches the log pipeline.
969
+ *
970
+ * An `error` outcome goes to `console.error` (surfacing at error level in the
971
+ * trace so a SIEM can alert on it); everything else to `console.log`. The
972
+ * `source: "lunora"` / `type: "request"` envelope lets a consumer filter these
973
+ * events out of the raw Workers-trace firehose. `captureRaw` (dev only) skips
974
+ * redaction, mirroring the durable write. Best-effort by contract — the caller
975
+ * wraps it so a serialization hiccup can never fail the served request.
991
976
  */
992
- declare const readFunctionMetrics: (sql: SqlExec) => FunctionCallStat[];
977
+ declare const emitRequestLogEvent: (entry: AppendRequestLogEntry, options?: RequestLogWriteOptions) => void;
993
978
  /**
994
- * Read the coarse time-series buckets for `path` (every path when omitted),
995
- * oldest-bucket first so a chart can plot them left-to-right. Creates the table
996
- * first so reads on a never-called shard return `{ buckets: [], truncated: false }`.
979
+ * The `ctx.log` event contract (shape + severity union) lives in
980
+ * `shared/log-event.ts` (inlined into each `dist`) so the DO that builds these
981
+ * events and the `@lunora/runtime` sink that consumes them agree by construction.
982
+ * `LogEventInput` is the DO's historical name for the shared `LogEvent`.
997
983
  */
998
- declare const readFunctionMetricBuckets: (sql: SqlExec, path?: string) => FunctionMetricBucketsResult;
984
+ type LogEventInput = LogEvent;
999
985
  /**
1000
- * Aggregate the persisted accumulators into the lifetime totals the metrics
1001
- * health snapshot reports: total calls (`requests`), total `errors`. Returns
1002
- * zeroes on a never-called shard.
1003
- *
1004
- * `capped` is true when the distinct-path cap ({@link FUNCTION_METRICS_MAX_PATHS})
1005
- * has been reached — the write-side signal that a brand-new function path is
1006
- * currently being refused (see `admitPath`), mirroring `readQueryInsights`'s
1007
- * `capped` for query-metrics and `readMetricHistory`'s for metric-history.
986
+ * Split a `ctx.log.<level>(...)` call's raw arguments into a display `message`
987
+ * and optional structured `fields`. The structured form — a message string plus
988
+ * a plain-object fields bag — is matched only for exactly `(string, object)`;
989
+ * every other shape is console-style and rendered whole (so existing
990
+ * `console`-shaped calls are unchanged). Bound `.with(...)` fields merge under
991
+ * the per-call fields (per-call wins); the result is normalized to a fresh bag
992
+ * of JSON-safe primitives, or `undefined` when empty (see `normalizeLogFields`).
1008
993
  */
1009
- declare const readFunctionMetricsTotals: (sql: SqlExec) => {
1010
- capped: boolean;
1011
- errors: number;
1012
- requests: number;
994
+ declare const parseLogArgs: (args: unknown[], boundFields?: LogFields) => {
995
+ fields?: LogFields;
996
+ message: string;
1013
997
  };
1014
998
  /**
1015
- * The Workers AI text model the Issue explainer uses when the caller does not
1016
- * override it. The fp8-fast instruct model the rest of the repo defaults to —
1017
- * the explainer is a short, grounded rewrite (not a reasoning task), so a
1018
- * latency-optimized build beats a larger one. Deliberately not the retired
1019
- * `@cf/meta/llama-3.1-8b-instruct`: a deprecated model-id makes `binding.run`
1020
- * throw, which would silently degrade every explain to `"ai-error"`.
1021
- */
1022
- /**
1023
- * Fallback model id when neither the caller nor the request names one.
999
+ * Emit one application-log event from a `ctx.log.*` call to `console`, tagged
1000
+ * `{ source: "lunora", type: "log" }` so the CLI / Vite formatter can pretty-print
1001
+ * it in the dev terminal and a Logpush/SIEM consumer can filter it out of the
1002
+ * raw Workers-trace firehose.
1024
1003
  *
1025
- * A Workers AI id, which makes it the *host's* default rather than this
1026
- * package's — a second host runs different models and must be able to say so.
1027
- * `explainIssue` therefore takes `defaultModel`, and this constant is only what
1028
- * the Cloudflare host happens to pass. Kept exported so that host has a name to
1029
- * pass rather than a string literal.
1030
- */
1031
- declare const DEFAULT_EXPLAIN_ISSUE_MODEL = "@cf/meta/llama-3.3-70b-instruct-fp8-fast";
1032
- /**
1033
- * Structural projection of the Workers `AI` binding's `run` method — declared
1034
- * locally so `@lunora/do` needs no dependency edge on `@lunora/ai` (nor on
1035
- * `@cloudflare/workers-types`) to reach `env.AI`. Mirrors `AiBindingLike` in
1036
- * `@lunora/ai`.
1004
+ * Only the rendered `message` is emitted here, NOT the structured `args` array:
1005
+ * the console event rides CF Workers Logs / Logpush to prod, and shipping raw,
1006
+ * un-redacted arg objects on a `source: "lunora"` line a SIEM is told to trust
1007
+ * would be a surprising PII/secret surface. The raw `args` stay on the in-process
1008
+ * `sink.onLog` path (`recordUserLog`), which the operator opts into and controls.
1009
+ * `message` already carries the developer's rendered values, exactly like a raw
1010
+ * `console.log` line.
1011
+ *
1012
+ * `error`/`fatal` go to `console.error`, `warn` to `console.warn` (so they
1013
+ * surface at the right level in the trace); every other level to `console.log`.
1014
+ *
1015
+ * Structured `fields` (plus `traceId`/`spanId` for correlation) ARE emitted here
1016
+ * — they are intentional metadata a log pipeline filters on, unlike raw `args`.
1017
+ * Unlike `args`, `fields` IS redacted before it rides this console line — a
1018
+ * developer can attach anything to a fields bag (`ctx.log.info("charged",
1019
+ * { email, cardLast4 })`), and this is the one line that's told to a SIEM as
1020
+ * trustworthy, exactly like the request-log `args`/`identity`/`error` columns.
1021
+ * `options.captureRaw` (dev only) skips it, mirroring every other redaction
1022
+ * point in this module; the sole current caller (`ShardDO.recordUserLog`)
1023
+ * doesn't yet thread a dev flag through, so `fields` redacts unconditionally
1024
+ * there today — a conservative default, never a correctness gap. A field value
1025
+ * that can't be serialised (a circular object) would make `JSON.stringify`
1026
+ * throw and drop the whole line, so serialisation falls back to a fields-free
1027
+ * line rather than losing the event.
1037
1028
  */
1038
- interface AiRunBinding {
1039
- run: (model: string, inputs: Record<string, unknown>, options?: Record<string, unknown>) => Promise<unknown>;
1040
- }
1041
- /** Parsed `__lunora_admin__:explainIssue` payload: the folded Issue's identifying facts, plus an optional model override. */
1042
- interface ExplainIssueArgs {
1043
- /** The Issue's culprit (`<file>:<function>` or `container:<name>`), for grounding context. */
1044
- culprit?: string;
1045
- /** Per-request model-id override; falls back to the caller's `defaultModel`, then {@link DEFAULT_EXPLAIN_ISSUE_MODEL}. */
1046
- model?: string;
1047
- /** A representative raw error message for the Issue — the fact the explanation is grounded in. Required. */
1048
- sampleMessage: string;
1049
- /** The Issue's human-readable title (first line of the sample message), for grounding context. */
1050
- title?: string;
1051
- }
1029
+ declare const emitLogEvent: (input: LogEventInput, options?: RequestLogWriteOptions) => void;
1052
1030
  /**
1053
- * Why the explainer fell back to the grounded hint alone. A closed union rather
1054
- * than a bare `string` so `degraded(reason)` rejects a typo'd sentinel at compile
1055
- * time instead of letting it fall through to the client's generic error copy.
1056
- * Mirrored by `ExplainIssueResult["reason"]` in `@lunora/studio`'s `lib/admin.ts`.
1031
+ * Read request-log entries, AND-combining the supplied filters (function-path
1032
+ * prefix, exact userId/shardKey/outcome, and a table-touched match against the
1033
+ * read OR written table sets), up to `limit` (clamped to [1, 10000]). Each value
1034
+ * is a bound parameter, so no filter can inject SQL. Creates the table first so
1035
+ * reads on a never-logged shard return `[]` instead of throwing. Mirrors
1036
+ * `readAuditLog`/`readCdcChanges`.
1037
+ *
1038
+ * **Ordering follows `sinceSeq`.** Without a cursor this is a "show me the tail"
1039
+ * read and returns NEWEST FIRST, which is what the studio's Logs tab renders.
1040
+ * With `sinceSeq` it is forward paging and returns OLDEST FIRST, starting at the
1041
+ * cursor: descending there silently loses rows, because `ORDER BY seq DESC LIMIT
1042
+ * n` answers "the newest n after the cursor", so a consumer that advances to the
1043
+ * largest returned `seq` skips everything between `sinceSeq` and that page
1044
+ * whenever more than `limit` rows accumulated between polls — the more traffic
1045
+ * the shard takes, the more it drops.
1057
1046
  */
1058
- type ExplainIssueDegradedReason = "ai-error" | "empty-response" | "no-ai-binding";
1047
+ declare const readRequestLog: (sql: SqlExec, options?: ReadRequestLogOptions) => RequestLogEntry[];
1048
+ declare const readErrorIssues: (sql: SqlExec, options?: ReadIssuesOptions) => ErrorIssue[];
1059
1049
  /**
1060
- * The grounding facts both `__lunora_admin__:explainIssue` outcomes carry. Present
1061
- * whenever {@link findIssueSolution} recognized the message — offline,
1062
- * deterministic, and independent of whether the AI path ran at all.
1050
+ * Structural shape of the `ctx.trace` span factory (see the server
1051
+ * `LunoraTracer`). Declared here rather than imported so `@lunora/do` takes no
1052
+ * dependency on `@lunora/server`; a cross-package assignability guard in
1053
+ * `@lunora/testing` fails the build if the two drift apart.
1063
1054
  *
1064
- * The hint BODY is deliberately not on the wire: the client derives it from the
1065
- * same catalog offline (that is the whole point of the grounded layer), so
1066
- * shipping it would be payload nothing reads.
1055
+ * The body's second argument is the enclosing span's {@link SpanHandle}, through
1056
+ * which it can attach attributes only known *after* it resolves (post-hoc). It is
1057
+ * a trailing parameter, so a `(trace) => …` body that ignores it still conforms.
1067
1058
  */
1068
- interface ExplainIssueGrounding {
1059
+ type ContextTracer = <T>(name: string, function_: (trace: ContextTracer, span: SpanHandle) => Promise<T> | T, options?: LogFields | SpanOptions, identity?: SpanIdentity) => Promise<T>;
1060
+ /** Structural shape of the `ctx.metrics` recorder (see the server `LunoraMetrics`). */
1061
+ interface ContextMetrics {
1062
+ count: (name: string, value?: number, attributes?: LogFields) => void;
1063
+ gauge: (name: string, value: number, attributes?: LogFields) => void;
1064
+ record: (name: string, value: number, attributes?: LogFields) => void;
1065
+ }
1066
+ /** The trace a ctx's spans hang off: the shared id, and the span they parent to. */
1067
+ interface TraceAnchor {
1069
1068
  /**
1070
- * The id of the matched catalog/platform solution the prompt was grounded in,
1071
- * absent when nothing recognized the message. The client renders a caveat on
1072
- * absence — an ungrounded explanation is a free-form model guess, not a
1073
- * catalog-backed one, and must not be presented as the latter.
1069
+ * Cloudflare Ray ID of the request this dispatch serves, forwarded by the
1070
+ * runtime alongside `traceparent`. Carried on the anchor so every span and
1071
+ * log line of the dispatch stamps the same value. Absent off the edge.
1072
+ * Informational only, as `parseRayId` in `shared/ray-id.ts` defines it.
1074
1073
  */
1075
- groundedId?: string;
1074
+ rayId?: string;
1075
+ rootSpanId: string;
1076
+ /**
1077
+ * The W3C `sampled` verdict for this trace, inherited from the inbound
1078
+ * `traceparent` when there was one. Carried on the anchor rather than
1079
+ * re-derived per outbound call so every `ctx.fetch` of one dispatch
1080
+ * propagates the same answer.
1081
+ */
1082
+ sampled?: boolean;
1083
+ traceId: string;
1076
1084
  }
1077
- /**
1078
- * The `__lunora_admin__:explainIssue` result — a discriminated union on `degraded`
1079
- * rather than a bag of optionals, so each outcome's guaranteed fields are
1080
- * guaranteed in the type too. The AI `explanation` is best-effort: the degraded
1081
- * arm is returned when no `env.AI` binding is configured or the inference call
1082
- * failed, and the client falls back to its own grounded hint alone.
1083
- *
1084
- * Modelling this as one flat interface let a `degraded` result type-check without a
1085
- * `reason`, which the studio silently renders as the generic AI-error copy.
1086
- */
1087
- /** The arm returned when no inference happened, or it failed. */
1088
- interface ExplainIssueDegraded extends ExplainIssueGrounding {
1089
- /** The AI path was unavailable or failed — render the grounded hint instead. */
1090
- degraded: true;
1091
- /** Why the AI path degraded, for the client to surface. */
1092
- reason: ExplainIssueDegradedReason;
1085
+ /** What {@link createTracer} needs from the shard to build a span. */
1086
+ interface TracerDeps {
1087
+ /** The trace this ctx's spans belong to. */
1088
+ anchor: TraceAnchor;
1089
+ /**
1090
+ * Whether to record a span body's error message (and a `recordException`
1091
+ * stacktrace) verbatim rather than redacted. Mirrors the request log's
1092
+ * `captureRaw`: `true` in dev (`isDevEnvironment`), `false` in production —
1093
+ * the span pipeline is the one sink third-party collectors (Datadog/Axiom
1094
+ * via `otlpSink`) receive, so it must not ship raw PII/internals by default
1095
+ * the way the request log and function-metrics sinks already don't.
1096
+ */
1097
+ captureRaw?: boolean;
1098
+ /** Function path the spans are attributed to. */
1099
+ functionPath: string;
1100
+ /**
1101
+ * **Opt-in, EXPERIMENTAL, default off.** When `true` *and*
1102
+ * {@link TracerDeps.resolveHostTracing} yields a working
1103
+ * `tracing.enterSpan`, each `ctx.trace` span is ALSO emitted as a host-native
1104
+ * **custom span**, so it nests inside CF's native binding/fetch/handler trace
1105
+ * tree on the hosted path. This only ADDS a CF-side span — the recorded
1106
+ * {@link SpanEvent} (our `SpanBuffer`/`otlpSink`) is untouched and remains the
1107
+ * source of truth plus the local studio waterfall. The `enterSpan` call itself
1108
+ * is now workerd-validated as available and side-effect-free inside a Durable
1109
+ * Object; CF's exported parent-linking under sampling remains unverified. See
1110
+ * {@link createTracer} for the double-export and Durable-Object async-context
1111
+ * caveats.
1112
+ */
1113
+ fuseHostSpans?: boolean;
1114
+ /** Hand a finished span to the buffer + sink. */
1115
+ record: (span: SpanEvent) => void;
1116
+ /**
1117
+ * Injected resolver for CF's `tracing` namespace (see
1118
+ * {@link HostTracingResolver}). Only consulted when
1119
+ * {@link TracerDeps.fuseHostSpans} is `true`, so the default path never
1120
+ * calls it.
1121
+ */
1122
+ resolveHostTracing?: HostTracingResolver;
1123
+ /**
1124
+ * The invocation's `v.sensitive` values (see {@link SensitiveScope}). Applied
1125
+ * to every span this tracer records, and to the body's own collector.
1126
+ */
1127
+ scope?: SensitiveScope;
1128
+ /** Shard key for single-shard calls; absent for the unnamed root DO. */
1129
+ shardKey: string | undefined;
1130
+ /** Read lazily — the acting user is resolved per span, not per ctx. */
1131
+ userId: () => string | undefined;
1093
1132
  }
1094
- /** The arm returned when the model ran and produced text. */
1095
- interface ExplainIssueSuccess extends ExplainIssueGrounding {
1096
- /** The AI path ran and produced text. */
1097
- degraded: false;
1098
- /** The AI-generated plain-language explanation. */
1099
- explanation: string;
1100
- /** The Workers AI model-id that produced {@link ExplainIssueSuccess.explanation}. */
1101
- model: string;
1133
+ /** What {@link createMetrics} needs from the shard to build a measurement. */
1134
+ interface MetricsDeps {
1135
+ functionPath: string;
1136
+ record: (event: MetricEvent) => void;
1137
+ /** The invocation's `v.sensitive` values, applied to each measurement's attributes. */
1138
+ scope?: SensitiveScope;
1139
+ shardKey: string | undefined;
1140
+ }
1141
+ /** Everything a {@link SpanHandle}'s body attached, ready to merge into the recorded span. */
1142
+ interface SpanCollection {
1143
+ attributes: Record<string, LogFields[string]>;
1144
+ events: SpanEventPoint[];
1145
+ links: SpanLink[];
1146
+ }
1147
+ /** A {@link SpanHandle} plus read access to what it has collected so far. */
1148
+ interface SpanCollector {
1149
+ collected: SpanCollection;
1150
+ handle: SpanHandle;
1102
1151
  }
1103
- type ExplainIssueResult = ExplainIssueDegraded | ExplainIssueSuccess;
1104
1152
  /**
1105
- * Validate the `__lunora_admin__:explainIssue` payload. Requires a non-empty
1106
- * `sampleMessage` (the grounding fact); `title`, `culprit`, and `model` are
1107
- * optional context/overrides. Throws a 400 `LunoraError` on a bad shape.
1153
+ * Build a span's post-hoc collection surface: the {@link SpanHandle} handed to a
1154
+ * `ctx.trace` body, and the bag it writes into.
1108
1155
  *
1109
- * Every caller-supplied field that reaches the prompt is capped here — capping
1110
- * `sampleMessage` alone left `title`/`culprit` as an open door onto the same
1111
- * prompt budget.
1112
- */
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).
1156
+ * Factored out because the same surface backs two things — every `ctx.trace`
1157
+ * span, and the per-dispatch **wide event** (`ctx.span`), where the accumulated
1158
+ * attributes become the canonical one-event-per-request summary. Sharing the
1159
+ * implementation is what makes those two feel like the same API instead of two
1160
+ * that happen to resemble each other.
1120
1161
  *
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).
1162
+ * `captureRaw` (default `false`) gates `recordException`'s `exception.message`/
1163
+ * `exception.stacktrace` the same way {@link createTracer} gates a span's own
1164
+ * error message — a stack is file paths and internals by definition, the exact
1165
+ * class `isInternalCode` redaction exists for, so it rides the same dev-only
1166
+ * escape hatch rather than shipping to a third-party collector by default.
1167
+ *
1168
+ * `scope` scrubs the invocation's `v.sensitive` values out of everything written
1169
+ * here, at write time, so the collector never holds the raw value. It is applied
1170
+ * whatever `captureRaw` says: the dev escape hatch exists for stacks and
1171
+ * internals, not for a marked argument.
1134
1172
  */
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>;
1173
+ declare const createSpanCollector: (ids: SpanContextIds, captureRaw?: boolean, scope?: SensitiveScope) => SpanCollector;
1163
1174
  /**
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.
1175
+ * Build the `ctx.trace` span factory for one dispatched function.
1167
1176
  *
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`.
1177
+ * **Nesting is explicit, not ambient.** Each span's body receives a tracer bound
1178
+ * to that span; calling it is what makes a child. An earlier design kept an
1179
+ * ambient stack of "the currently open span" and parented to its top, which
1180
+ * reads nicer but is unfixably wrong under concurrency: in
1181
+ * `Promise.all([trace("a", …), trace("b", …)])`, `b` starts while `a` is on the
1182
+ * stack and is recorded as a *child* of `a` rather than its sibling — and
1183
+ * parallel fan-out is one of the main things people reach for a tracer to
1184
+ * measure. Distinguishing "called inside a's body" from "called concurrently
1185
+ * with a" needs `AsyncLocalStorage`, which this package deliberately avoids (see
1186
+ * `dependency-tracker.ts` — shard DOs run under a slimmer compat profile than
1187
+ * `nodejs_compat`). So the parent is threaded, exactly like the dependency
1188
+ * tracker and the subscription identity: correct in every case, and visible at
1189
+ * the call site.
1190
+ *
1191
+ * The anchor is passed in for the same reason. `ShardDO.currentRequestTrace` is
1192
+ * cleared in the dispatch `finally`, and a subscription re-run builds its ctx
1193
+ * during* the writing mutation's flush — so reading that shared field at span
1194
+ * time would file the re-run's spans under the mutation's trace.
1195
+ *
1196
+ * **Cloudflare custom-spans bridge (opt-in, EXPERIMENTAL).** When
1197
+ * `deps.fuseHostSpans` is `true` and `deps.resolveHostTracing` yields
1198
+ * a working `tracing.enterSpan` (`cloudflare:workers`, GA 2026-06-16), each span
1199
+ * body runs inside a CF custom span so our span nests under CF's native
1200
+ * binding/fetch/handler trace tree on the hosted path, and the finished span's
1201
+ * key attributes are mirrored onto it (gated on `span.isTraced`). Two deliberate
1202
+ * boundaries hold.
1203
+ *
1204
+ * **No double-export by default, and never a replacement.** The bridge only ADDS a
1205
+ * CF-side span; the recorded {@link SpanEvent} handed to `record` (our
1206
+ * `SpanBuffer`/`otlpSink`) is byte-for-byte the same as without the bridge and
1207
+ * stays the source of truth. It is off unless explicitly enabled precisely
1208
+ * because, once on, a deployment that ALSO ships our `otlpSink` to a collector
1209
+ * AND lets CF export its trace tree emits the same logical span down two
1210
+ * pipelines — an intentional, documented trade the operator opts into, not a
1211
+ * default.
1212
+ *
1213
+ * **DO async-context caveat (EXPERIMENTAL, partially workerd-validated).**
1214
+ * `tracing.enterSpan` is now confirmed to EXIST and RUN inside a real Durable
1215
+ * Object under `@cloudflare/vitest-plugin` (see
1216
+ * `__tests__/workerd/context-telemetry-cf-bridge.workerd.test.ts`): it resolves
1217
+ * from `cloudflare:workers`, its callback executes and returns the body value
1218
+ * without throwing, `span.isTraced` is a real boolean, and — the key additive
1219
+ * guarantee — our recorded {@link SpanEvent} tree (parent/child via the threaded
1220
+ * `parentSpanId`) is byte-for-byte identical with the bridge on vs off. What that
1221
+ * harness CANNOT prove is CF's own *exported* parent-linking: with no trace head
1222
+ * attached the run is unsampled (`isTraced === false`), so CF records nothing and
1223
+ * its span tree is not introspectable. So `enterSpan`'s ambient-span parent-linking
1224
+ * inside a DO stays unverified upstream, and this remains capability-probed: an
1225
+ * absent/undefined `tracing`, a missing `enterSpan`, or an off-CF/unsampled run all
1226
+ * resolve to `undefined`/no-op — exact prior behavior. If CF's ambient-span linkage
1227
+ * misbehaves in a DO, the worst case is a mis-parented CF span; our own recorded
1228
+ * waterfall is unaffected.
1172
1229
  */
1173
- declare const upsertIssueState: (sql: SqlExec, hash: string, patch: IssueStatePatch, updatedAt: number, updatedBy?: string) => IssueState;
1230
+ declare const createTracer: (deps: TracerDeps) => ContextTracer;
1231
+ /** What {@link createTracedFetch} needs from the shard. */
1232
+ interface TracedFetchDeps {
1233
+ /** The trace the CLIENT spans belong to. */
1234
+ anchor: TraceAnchor;
1235
+ /**
1236
+ * Whether to record a failed fetch's error message verbatim rather than
1237
+ * redacted. Same dev-only escape hatch as {@link TracerDeps.captureRaw}, and
1238
+ * the same reason: a `fetch` TypeError embeds the request URL, so a key in a
1239
+ * query string would otherwise reach the collector in the clear on the very
1240
+ * span whose `url.full` is scrubbed by `redactUrl`.
1241
+ */
1242
+ captureRaw?: boolean;
1243
+ /** Function path the spans are attributed to. */
1244
+ functionPath: string;
1245
+ /**
1246
+ * Whether to inject `traceparent` into the outbound request — and, with a
1247
+ * predicate, to which destinations. Default `true`.
1248
+ */
1249
+ propagate?: ((url: URL) => boolean) | boolean;
1250
+ /** Hand a finished span to the buffer + sink. */
1251
+ record: (span: SpanEvent) => void;
1252
+ /** The invocation's `v.sensitive` values; a query string or path can carry one. */
1253
+ scope?: SensitiveScope;
1254
+ /** Shard key for single-shard calls; absent for the unnamed root DO. */
1255
+ shardKey: string | undefined;
1256
+ /** Read lazily — the acting user is resolved per span. */
1257
+ userId: () => string | undefined;
1258
+ }
1259
+ /** The `fetch` shape `ctx.fetch` exposes — the platform global's, narrowed to what we wrap. */
1260
+ type ContextFetch = (input: Request | string | URL, init?: RequestInit) => Promise<Response>;
1174
1261
  /**
1175
- * Severity of a buffered log entry — the full seven-tier `ctx.log` ramp
1176
- * (`trace`→`fatal`), not a console-shaped subset. The buffer used to fold the
1177
- * ramp onto four tiers, which made `trace` and `fatal` lines indistinguishable
1178
- * from `debug` and `error` in the Studio Logs panel; it now stores the level the
1179
- * caller actually logged at. Container-lifecycle entries only ever use
1180
- * `info`/`error`, which remain part of the union.
1262
+ * Build `ctx.fetch`: the platform `fetch`, wrapped so every outbound call
1263
+ * becomes a **CLIENT span** and carries W3C trace context to the callee.
1264
+ *
1265
+ * Two gaps close here. First, an uninstrumented `fetch` makes the single most
1266
+ * common source of latency — waiting on somebody else's service — invisible: a
1267
+ * handler that spends 900ms in Stripe shows one opaque 900ms bar. Second,
1268
+ * without an outbound `traceparent` the callee starts a brand-new trace, so the
1269
+ * two halves of one logical request can never be stitched together, which is the
1270
+ * entire premise of distributed tracing.
1271
+ *
1272
+ * The span id is minted BEFORE the request is sent, precisely so the header
1273
+ * announces the id the span will actually be recorded under. Deriving it
1274
+ * afterwards (or reusing the parent's) would produce a `traceparent` naming a
1275
+ * span that never existed, and a callee parented to nothing.
1276
+ *
1277
+ * Kind is `client` rather than `internal` — that is what lets a collector draw
1278
+ * the edge to the downstream service in a service map.
1279
+ *
1280
+ * **Parenting is the DISPATCH, not the enclosing `ctx.trace`.** `ctx.fetch` is
1281
+ * built once per dispatch, and the enclosing span is threaded explicitly rather
1282
+ * than kept on an ambient stack (no `AsyncLocalStorage` in the Durable Object
1283
+ * profile — the same constraint `ctx.trace` and the `@opentelemetry/api` bridge
1284
+ * document), so a fetch inside `ctx.trace("stripe", …)` renders as that span's
1285
+ * SIBLING under the dispatch, not its child. The duration and the ordering are
1286
+ * right and the span is never lost; only the nesting is flat. Wrap the call in
1287
+ * the span whose bar you want it under and read the two side by side.
1288
+ *
1289
+ * Failures are recorded and re-thrown untouched, and a non-2xx response is
1290
+ * recorded as an ERROR span (it is a failed call from the caller's point of
1291
+ * view) while still being returned normally — instrumentation, never flow
1292
+ * control.
1181
1293
  */
1182
- type LogLevel = ContextLogLevel;
1294
+ declare const createTracedFetch: (deps: TracedFetchDeps, base: ContextFetch) => ContextFetch;
1183
1295
  /**
1184
- * One buffered log line. `functionPath` is the RPC that produced it (when the
1185
- * entry came from the RPC dispatch site); `timestamp` is `Date.now()` at the
1186
- * moment it was pushed. `instance`/`exitCode` are populated for container
1187
- * lifecycle entries: `instance` correlates the per-instance Durable Object id,
1188
- * `exitCode` carries the process exit code parsed out of a `stop` event.
1296
+ * Build the `ctx.metrics` recorder for one dispatched function.
1297
+ *
1298
+ * Deliberately stateless: each call emits one measurement rather than
1299
+ * accumulating into a per-dispatch map. Pre-aggregating here would have to pick a
1300
+ * flush point and a merge rule per instrument kind (sum a counter, last-wins a
1301
+ * gauge, and a histogram cannot be merged at all without losing the
1302
+ * distribution) — so the runtime stays a transport and the collector, which is
1303
+ * built for exactly this, does the aggregation.
1189
1304
  */
1190
- interface LogEntry {
1191
- exitCode?: number;
1192
- /** Structured fields from a `ctx.log.<level>(message, fields)` / `ctx.log.with(fields)` call, when present. */
1193
- fields?: Record<string, unknown>;
1194
- functionPath?: string;
1195
- instance?: string;
1196
- level: LogLevel;
1197
- message: string;
1198
- timestamp: number;
1199
- /** 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. */
1200
- traceId?: string;
1201
- }
1305
+ declare const createMetrics: (deps: MetricsDeps) => ContextMetrics;
1202
1306
  /**
1203
- * A bounded, in-memory ring buffer of recent {@link LogEntry} records.
1307
+ * Build the synthetic root span for a finished dispatch — the bar the studio's
1308
+ * waterfall hangs a request's `ctx.trace` spans under.
1204
1309
  *
1205
- * In-memory only: like the metrics counters on `ShardDO`, the buffer is a field
1206
- * on the live Durable Object instance and so resets whenever the DO hibernates
1207
- * or restarts. It is a "recent activity on this instance" readout (for the
1208
- * studio's live log panel), NOT a durable log store or a transport.
1209
- * Production log shipping is the platform's job, not ours: use Cloudflare
1210
- * **Workers Logs** (retained, queryable in the studio), **Logpush** (stream
1211
- * to R2 / a SIEM / a log service), or a **Tail Worker** for programmatic
1212
- * capture. Lunora deliberately does not reimplement any of those — this buffer
1213
- * stays a tiny dev/ops readout. Capacity is fixed at construction; once full,
1214
- * the oldest entry is evicted to make room (FIFO), so memory stays bounded
1215
- * regardless of traffic.
1310
+ * Pure: the caller decides whether to record it (only when the dispatch actually
1311
+ * produced spans) and where to put it. It is never routed to `sink.onSpan`,
1312
+ * because the runtime already emits the dispatch to `onRpc` and a collector would
1313
+ * otherwise show it twice.
1216
1314
  */
1217
- declare class LogBuffer {
1218
- /** Backing store, kept in insertion order (oldest first). */
1219
- private readonly buffer;
1220
- private readonly capacity;
1221
- constructor(capacity?: number);
1222
- /** Number of entries currently buffered. */
1223
- get size(): number;
1224
- /** Drop every buffered entry. */
1225
- clear(): void;
1315
+ declare const dispatchRootSpan: (input: {
1316
+ anchor: TraceAnchor;
1226
1317
  /**
1227
- * Snapshot of the buffered entries, **newest first** so the panel renders
1228
- * the most recent activity at the top without re-sorting. Returns a fresh
1229
- * array each call; the caller may mutate it freely.
1318
+ * Whether to record the failure message verbatim rather than redacted —
1319
+ * the same dev-only escape hatch as {@link TracerDeps.captureRaw}. This
1320
+ * synthetic root span carries the SAME error message the request log and
1321
+ * function-metrics sinks already redact by default, so it must not be the
1322
+ * one durable copy that ships it raw to a third-party collector.
1230
1323
  */
1231
- entries(): LogEntry[];
1324
+ captureRaw?: boolean;
1232
1325
  /**
1233
- * Append an entry, evicting the oldest when at capacity so the buffer never
1234
- * grows past its bound.
1326
+ * What the handler attached to the dispatch through `ctx.span` — the **wide
1327
+ * event**. These are the attributes that would otherwise have been scattered
1328
+ * across a dozen `ctx.log` lines; carrying them on the one span that already
1329
+ * exists per request is the OTel-native way to get a wide event without
1330
+ * multiplying log records.
1235
1331
  */
1236
- push(entry: LogEntry): void;
1332
+ collected?: SpanCollection;
1333
+ durationMs: number;
1334
+ failure: {
1335
+ thrown: unknown;
1336
+ } | undefined;
1337
+ functionPath: string;
1338
+ /** The invocation's `v.sensitive` values; the failure message can quote one. */
1339
+ scope?: SensitiveScope;
1340
+ shardKey: string | undefined;
1341
+ startTs: number;
1342
+ userId: string | undefined;
1343
+ }) => SpanEvent;
1344
+ /** Running totals for `"summary"` mode; created by the caller, read once at the dispatch boundary. */
1345
+ interface DatabaseTally {
1346
+ calls: number;
1347
+ durationMs: number;
1348
+ errors: number;
1349
+ perOperation: Record<string, number>;
1350
+ spansEmitted: number;
1351
+ spansTruncated: boolean;
1237
1352
  }
1238
1353
  /**
1239
- * One aggregated metric series: every measurement sharing a `(name, kind,
1240
- * attributes)` identity folded into a single running summary.
1354
+ * Which instrumented surface a tally belongs to, and the key prefix
1355
+ * {@link formatTally} folds it under: `db` for `ctx.db`, `sql` for `ctx.sql`.
1356
+ */
1357
+ type TallySurface = "db" | "sql";
1358
+ /**
1359
+ * How much detail `ctx.db` / `ctx.sql` auto-instrumentation produces.
1241
1360
  *
1242
- * All fields are maintained for every {@link MetricKind} — the fold is uniform
1243
- * and O(1), and letting the panel choose the meaningful projection per kind
1244
- * (counter → `sum`, gauge → `last`, histogram → `sum`/`count` for the mean, plus
1245
- * `min`/`max`) is cheaper and clearer than branching on kind at record time.
1361
+ * `"summary"` (default) — aggregate counters on the dispatch's wide event: no
1362
+ * extra spans, no extra log records, and a cost that does not grow with call count.
1363
+ *
1364
+ * `"spans"` — one span per database call. The full waterfall, at the price of a
1365
+ * span per call; right when diagnosing, noisy as a permanent default.
1366
+ *
1367
+ * `"off"` — no database telemetry at all.
1246
1368
  */
1247
- interface MetricSeries {
1248
- /** The series' dimensions, if any — the attributes that made it distinct. */
1249
- attributes?: LogFields;
1250
- /** Number of measurements folded into this series. */
1251
- count: number;
1252
- /** Trace id of the most recent measurement that carried one — the series' exemplar, for linking to a trace. */
1253
- exemplarTraceId?: string;
1254
- /** Wall-clock millis of the first measurement folded in. */
1255
- firstTs: number;
1256
- /** Function path that recorded the series' most recent measurement. */
1257
- functionPath: string;
1258
- /** Instrument kind; decides which projection the panel shows. */
1259
- kind: MetricKind;
1260
- /** Most recent measured value — the current reading for a `gauge`. */
1261
- last: number;
1262
- /** Wall-clock millis of the most recent measurement. */
1263
- lastTs: number;
1264
- /** Largest measured value seen. */
1265
- max: number;
1266
- /** Smallest measured value seen. */
1267
- min: number;
1268
- /** Instrument name, e.g. `"orders.placed"`. */
1269
- name: string;
1270
- /** Shard key for single-shard calls; absent for the unnamed root DO. */
1271
- shardKey?: string;
1272
- /** Sum of measured values — a `counter`'s total, a `histogram`'s sum. */
1273
- sum: number;
1274
- }
1369
+ type DatabaseInstrumentation = "off" | "spans" | "summary";
1275
1370
  /**
1276
- * A bounded map of running metric aggregates, keyed by series identity. Eviction
1277
- * is least-recently-*updated*: a re-recorded series moves back to the tail (Map
1278
- * insertion order), so the capacity bound sheds cold, high-cardinality series and
1279
- * keeps the ones still receiving traffic — the opposite of a raw ring, which
1280
- * would evict a hot counter's own history.
1371
+ * The structural slice of `@lunora/hyperdrive`'s `SqlClient` the `ctx.sql`
1372
+ * instrumenter needs — declared here so this package takes no dependency on
1373
+ * hyperdrive.
1281
1374
  */
1282
- declare class MetricBuffer {
1283
- private readonly capacity;
1284
- private readonly series;
1285
- constructor(capacity?: number);
1286
- /** Number of distinct series currently aggregated. */
1287
- get size(): number;
1288
- /** Drop every aggregated series. */
1289
- clear(): void;
1375
+ interface SqlClientLike {
1376
+ /** OTel `db.system.name` the driver adapter stamped; `other_sql` when absent. */
1377
+ readonly dbSystem?: string;
1378
+ query: (text: string, params?: ReadonlyArray<unknown>) => Promise<unknown>;
1379
+ }
1380
+ /** What {@link instrumentDatabase} / {@link instrumentSqlClient} need to record what they observe. */
1381
+ interface DatabaseTelemetryDeps {
1382
+ /** The trace produced spans belong to (`"spans"` mode only). */
1383
+ anchor: TraceAnchor;
1290
1384
  /**
1291
- * Snapshot of the aggregated series, most-recently-updated first, each a fresh
1292
- * copy so a caller can't mutate the live aggregate. `series` is kept in
1293
- * update order (tail = newest), so one reverse yields newest-first.
1385
+ * Whether to record a failed call's error message verbatim (`"spans"` mode
1386
+ * only) — the same dev-only escape hatch as `TracerDeps.captureRaw`. See
1387
+ * {@link failureMessage} for what each surface records without it.
1294
1388
  */
1295
- entries(): MetricSeries[];
1296
- /** Fold one measurement into its series, creating or updating the aggregate. */
1297
- push(event: MetricEvent): void;
1298
- }
1299
- /** One time-bucket sample of a series: the aggregate over `[bucketMs, bucketMs + METRIC_HISTORY_BUCKET_MS)`. */
1300
- interface MetricHistoryPoint {
1301
- /** Epoch-ms floor of the bucket window. */
1302
- bucketMs: number;
1303
- /** Measurements folded into this bucket. */
1304
- count: number;
1305
- /** Sample `traceId` of a measurement in this bucket, if one carried trace context — the exemplar. */
1306
- exemplarTraceId?: string;
1307
- /** Last measured value in the bucket — a gauge's reading at the window's end. */
1308
- last: number;
1309
- /** Largest value in the bucket. */
1310
- max: number;
1311
- /** Smallest value in the bucket. */
1312
- min: number;
1313
- /** Sum of values in the bucket — a counter's increment total, a histogram's sum. */
1314
- sum: number;
1315
- }
1316
- /** One series' durable history: its identity plus its time-ordered buckets, oldest first. */
1317
- interface MetricHistorySeries {
1318
- attributes?: LogFields;
1389
+ captureRaw?: boolean;
1390
+ /** Function path spans and attributes are attributed to. */
1319
1391
  functionPath: string;
1320
- kind: MetricKind;
1321
- name: string;
1322
- /** Buckets in ascending `bucketMs` order, ready to chart as a line. */
1323
- points: MetricHistoryPoint[];
1324
- shardKey?: string;
1325
- }
1326
- /** {@link readMetricHistory} result: every tracked series with its buckets. */
1327
- interface MetricHistoryResult {
1392
+ /** Detail level; see {@link DatabaseInstrumentation}. */
1393
+ mode: DatabaseInstrumentation;
1394
+ /** Hand a finished span to the buffer + sink (`"spans"` mode only). */
1395
+ record: (span: SpanEvent) => void;
1396
+ /** The invocation's `v.sensitive` values; a driver's error message can quote one. */
1397
+ scope?: SensitiveScope;
1398
+ /** Shard key for single-shard calls; absent for the unnamed root DO. */
1399
+ shardKey: string | undefined;
1328
1400
  /**
1329
- * True when the distinct-series cap has been reached — a **write-side**
1330
- * signal ("this shard can no longer admit a brand-new series", see
1331
- * `admitNewSeries`), not a read-side truncation flag. It is computed over
1332
- * the whole table regardless of `options.sinceMs`/the row-count read
1333
- * limit, so it can be `true` even when every series `readMetricHistory`
1334
- * actually returned fits comfortably: the caller should read it as "a
1335
- * flood of new series would currently be refused", the same thing
1336
- * `readQueryInsights`'s `capped` already signals for query-metrics.
1401
+ * Caller-supplied accumulator for `"summary"` mode. The instrumenter only ever
1402
+ * increments numbers on it; the shard reads it ONCE at the dispatch boundary
1403
+ * and formats it with {@link formatTally}.
1404
+ *
1405
+ * Per-call cost stays at a few integer increments — no object allocation, no
1406
+ * lookup — which matters because this is on the path of every query. Nothing
1407
+ * is written through the dispatch's `SpanHandle` either, so the wide-event
1408
+ * collector is never materialized by instrumentation alone: a dispatch that
1409
+ * ran queries gets a root span carrying these counters, but no `lunora.dispatch`
1410
+ * log record unless the handler actually opened `ctx.span`.
1337
1411
  */
1338
- capped: boolean;
1339
- series: MetricHistorySeries[];
1412
+ tally: DatabaseTally;
1413
+ /**
1414
+ * The acting user, read when a span is built. Callers resolve it ONCE, when
1415
+ * they instrument the client, and return that captured value: a span is
1416
+ * built after the call's await, and per-request shared state read by then
1417
+ * may already belong to a concurrent request.
1418
+ */
1419
+ userId: () => string | undefined;
1340
1420
  }
1341
1421
  /**
1342
- * Tunable caps for {@link recordMetricHistory}, threaded from the sink's
1343
- * `metricHistory` option. Each falls back to its module-constant default, so an
1344
- * omitted field keeps the historical behaviour.
1422
+ * Wrap a `ctx.db` writer so its storage-touching methods are instrumented.
1423
+ *
1424
+ * Returns the database unchanged when `mode` is `"off"`, so the default-disabled
1425
+ * path costs nothing — not even a proxy indirection.
1426
+ *
1427
+ * A proxy rather than an enumerated, rebound copy: `DatabaseWriterLike` has
1428
+ * optional members that a given backend may or may not implement, plus
1429
+ * properties (`system`) and builder factories (`query`) that must pass through
1430
+ * untouched. A proxy instruments exactly what it is asked to and is
1431
+ * transparently correct for everything else, including members added later —
1432
+ * an enumeration would silently stop covering them.
1345
1433
  */
1346
- interface MetricHistoryOptions {
1347
- /** Distinct series tracked before the least-recently-updated one is evicted to admit a new one (default {@link METRIC_HISTORY_MAX_SERIES}). */
1348
- maxSeries?: number;
1349
- /** Minute-buckets kept per series before older rows are trimmed (default {@link METRIC_HISTORY_BUCKET_RETENTION}). */
1350
- retentionBuckets?: number;
1351
- }
1434
+ declare const instrumentDatabase: <T extends object>(database: T, deps: DatabaseTelemetryDeps) => T;
1352
1435
  /**
1353
- * Fold one measurement into its `(series, minute)` bucket. Runs per
1354
- * `ctx.metrics.*` call (unlike `function-metrics.ts`, which runs once per
1355
- * dispatch), so it's tuned for the in-minute repeat: a bucket this instance has
1356
- * already written is a single upsert (no reads), a bucket only in the DB costs one
1357
- * PK point-lookup + upsert, and only a genuinely new bucket also pays the
1358
- * distinct-series cap scan + retention trim. Still a durable SQLite write per
1359
- * measurement, so a hot loop recording thousands of points a second should
1360
- * pre-aggregate and record once (see `shared/metric-event.ts`). Creates the table
1361
- * first so callers needn't.
1436
+ * Wrap the action-only `ctx.sql` client so every `query` is instrumented — the
1437
+ * `ctx.sql` twin of {@link instrumentDatabase}, at the same levels and through
1438
+ * the same {@link observeCall}. `deps.tally` must be a tally of its own (folded
1439
+ * as `sql.*`), never `ctx.db`'s.
1362
1440
  *
1363
- * `exemplarTraceId` (the recording dispatch's trace, when it had one) is stored on
1364
- * the bucket so the studio can link a chart point back to a trace. Latest wins:
1365
- * a later sample carrying a trace replaces an earlier bucket's exemplar.
1441
+ * Its span carries no statement text and no parameters — only the
1442
+ * leading-keyword operation, the system, and the returned row count. No
1443
+ * `db.collection.name` either: naming the table means parsing past
1444
+ * `FROM`/`INTO` through joins, CTEs and quoting, which is neither cheap nor
1445
+ * safe. A failure records its TYPE (see {@link failureMessage}).
1366
1446
  *
1367
- * `options` tunes the distinct-series cap and retention window from the sink's
1368
- * `metricHistory` flag (see {@link MetricHistoryOptions}); each defaults to its
1369
- * module constant.
1447
+ * `query` is the whole `SqlClient` surface: there is no transaction or batch
1448
+ * method to cover. Everything else on the client passes through untouched, and
1449
+ * `"off"` returns the client itself.
1370
1450
  */
1371
- declare const recordMetricHistory: (sql: SqlExec, event: MetricEvent, exemplarTraceId?: string, options?: MetricHistoryOptions) => void;
1451
+ declare const instrumentSqlClient: <T extends SqlClientLike>(client: T, deps: DatabaseTelemetryDeps) => T;
1452
+ /** A zero'd tally for one dispatch. */
1453
+ declare const createDatabaseTally: () => DatabaseTally;
1372
1454
  /**
1373
- * Read the durable history, grouped into one {@link MetricHistorySeries} per
1374
- * series with its buckets in ascending time order.
1375
- *
1376
- * Rows are fetched most-recent-first (`bucket_ms DESC`) under the row cap, NOT
1377
- * `series_key`-ordered: all active series write the same recent minutes, so this
1378
- * windows every series to a recent slice fairly, instead of handing the
1379
- * alphabetically-first series its full 1440-bucket history and starving the rest
1380
- * once the cap is hit. Each series' points are re-sorted ascending below, since a
1381
- * trend line reads oldest→newest.
1455
+ * Render the running tally as span attributes, under its surface's prefix
1456
+ * ({@link TallySurface}).
1382
1457
  *
1383
- * `options.sinceMs`, when set, returns only buckets at or after this epoch-ms —
1384
- * the studio's time-window selector. `options.maxSeries`, mirroring the write
1385
- * side's tunable, is only used to compute `capped` — it does not affect which
1386
- * rows are read.
1458
+ * Called ONCE per dispatch, from the shard's root-span recorder — not per query.
1459
+ * It is a handful of keys, so the per-call cost is a small object assignment —
1460
+ * the property that makes `"summary"` mode scale to any call count.
1387
1461
  */
1388
- declare const readMetricHistory: (sql: SqlExec, options?: {
1389
- maxSeries?: number;
1390
- sinceMs?: number;
1391
- }) => MetricHistoryResult;
1392
- /** One row of the `__lunora_metrics_queries` table, as returned by `readQueryMetrics`. */
1393
- interface QueryStatEntry {
1394
- /** Total number of times this statement was executed. */
1395
- execCount: number;
1396
- /** Normalised SQL text (literals stripped, truncated). */
1397
- normalizedSql: string;
1398
- /** Total rows read across all executions (SELECT result sizes). */
1399
- rowsRead: number;
1400
- /** Total rows written across all executions. */
1401
- rowsWritten: number;
1402
- /** Total wall-clock milliseconds across all executions. */
1403
- totalDurationMs: number;
1404
- }
1405
- /** One statement's activity within a chosen time range. */
1406
- interface QueryInsightEntry {
1407
- /** Mean milliseconds per execution across the range. */
1408
- avgDurationMs: number;
1409
- execCount: number;
1410
- normalizedSql: string;
1411
- /** Interpolated 50th percentile latency, in milliseconds. */
1412
- p50DurationMs: number;
1413
- /** Interpolated 95th percentile latency, in milliseconds. */
1414
- p95DurationMs: number;
1415
- rowsRead: number;
1416
- rowsWritten: number;
1417
- totalDurationMs: number;
1418
- }
1419
- /** One point on the throughput/latency charts. */
1420
- interface QueryInsightBucket {
1421
- /** Mean milliseconds per execution in this window, across all statements. */
1422
- avgDurationMs: number;
1423
- /** Bucket start, epoch millis. */
1462
+ declare const formatTally: (tally: DatabaseTally, surface?: TallySurface) => LogFields;
1463
+ /** Reserved per-function accumulator table. Auto-hidden from the data browser by the `__lunora` prefix. */
1464
+ declare const FUNCTION_METRICS_TABLE = "__lunora_metrics";
1465
+ /** Reserved coarse time-series table: per-function call/error counts bucketed by a fixed window. */
1466
+ declare const FUNCTION_METRICS_BUCKETS_TABLE = "__lunora_metrics_buckets";
1467
+ /** Reserved causal full-scan attribution table: per-(function, table) full-scan counts. */
1468
+ declare const FUNCTION_METRICS_SCANS_TABLE = "__lunora_metrics_scans";
1469
+ /** Reserved per-(table, index) hit-counter table backing the advisor dead-index lint. */
1470
+ declare const FUNCTION_METRICS_INDEX_TABLE = "__lunora_metrics_index";
1471
+ /**
1472
+ * Width of one history bucket, in milliseconds. 60s gives a minute-resolution
1473
+ * time series — fine-grained enough to chart bursts on the studio, coarse
1474
+ * enough that a single function emits at most one row per minute. Exported so
1475
+ * consumers (and tests) can align timestamps to the same grid.
1476
+ */
1477
+ declare const FUNCTION_METRICS_BUCKET_MS = 6e4;
1478
+ /**
1479
+ * Most recent buckets kept per function; older rows are trimmed after each
1480
+ * write so the time series can't grow unbounded. 1440 minute-buckets ≈ 24h of
1481
+ * history per function.
1482
+ */
1483
+ declare const FUNCTION_METRICS_BUCKET_RETENTION = 1440;
1484
+ /**
1485
+ * Maximum distinct function `path`s tracked in the accumulator table. Mirrors
1486
+ * `query-metrics.ts`'s `QUERY_METRICS_MAX_STATEMENTS` cap (and exists for the
1487
+ * same reason): the real bound is the app's own registered-function set plus
1488
+ * deploy churn (a rename/removal leaves its old path's row in place, still
1489
+ * counted against the cap, until an operator's own retention/cleanup
1490
+ * process — there is none built in today) — a few thousand registered
1491
+ * functions is already far beyond any real app. `shard-do.ts`'s dispatch
1492
+ * handler explicitly does NOT record per-function metrics for an
1493
+ * unregistered/`FUNCTION_NOT_FOUND` dispatch (see the guard next to its
1494
+ * `FUNCTION_NOT_FOUND` check), so a caller cannot mint arbitrary `path`s here
1495
+ * the way a raw caller-supplied SQL shape can in `query-metrics.ts`. Without a
1496
+ * cap, deploy churn across the app's lifetime would still grow
1497
+ * `__lunora_metrics` (and its bucket/scan satellites) without bound,
1498
+ * eventually filling the shard's SQLite store shared with the app's real
1499
+ * data. At the cap, a brand-new path is refused — protecting the incumbent
1500
+ * leaderboard from a flood of one-off paths is the point, so admission is
1501
+ * refused rather than evicting an existing path to make room; already-tracked
1502
+ * paths keep accumulating past the cap. `readFunctionMetricsTotals`'s
1503
+ * `capped` is the read-side signal for this.
1504
+ */
1505
+ declare const FUNCTION_METRICS_MAX_PATHS = 5e3;
1506
+ /**
1507
+ * Upper bound on rows the admin reads materialize into DO memory at once. Even
1508
+ * with the write-side `FUNCTION_METRICS_MAX_PATHS` cap in place, an existing
1509
+ * shard could already hold a bloated accumulator (rows written before the cap
1510
+ * landed), so the read path also clamps — a `SELECT *` with no LIMIT would
1511
+ * otherwise load every row via `.toArray()` and risk OOMing the ~128MB DO when
1512
+ * the studio Function Stats panel opens. Ordered reads keep the busiest/most
1513
+ * recent rows; the tail past this limit is simply not returned to the panel.
1514
+ */
1515
+ declare const FUNCTION_METRICS_READ_LIMIT = 1e3;
1516
+ /** One coarse time-series sample for a function: call/error counts within `[bucketMs, bucketMs + FUNCTION_METRICS_BUCKET_MS)`. */
1517
+ interface FunctionMetricBucket {
1518
+ /** Epoch-ms floor of the bucket window. */
1424
1519
  bucketMs: number;
1425
- execCount: number;
1520
+ /** Dispatches recorded in this window. */
1521
+ calls: number;
1522
+ /** Subset of `calls` that threw. */
1523
+ errors: number;
1426
1524
  }
1427
- /** What `getQueryInsights` returns. */
1428
- interface QueryInsightsResult {
1429
- /** Time series across the whole range, all statements combined. */
1430
- buckets: QueryInsightBucket[];
1525
+ /** {@link readFunctionMetricBuckets} result: the time-series window plus whether the read limit cut it short. */
1526
+ interface FunctionMetricBucketsResult {
1527
+ buckets: (FunctionMetricBucket & {
1528
+ path: string;
1529
+ })[];
1431
1530
  /**
1432
- * True when the tracked-statement cap has been reached, so the caller can say
1433
- * "showing N of a capped set" rather than implying totality. Silent
1434
- * truncation reads as complete coverage when it is not.
1531
+ * True when more rows existed than {@link FUNCTION_METRICS_READ_LIMIT} could
1532
+ * return, so `buckets` is a partial (newest) window rather than the app's
1533
+ * full retained history. Mirrors `readQueryInsights`'s `capped` and
1534
+ * `foldTraces`'s `total`: a silently truncated read looks identical to a
1535
+ * complete one to a caller that doesn't check for it — the Metrics chart's
1536
+ * window would appear to shrink as the app grows, with a wrong leftmost
1537
+ * bar, and nothing would say why.
1435
1538
  */
1436
- capped: boolean;
1437
- entries: QueryInsightEntry[];
1438
- /** How many distinct statements the lifetime table is tracking. */
1439
- trackedStatements: number;
1539
+ truncated: boolean;
1540
+ }
1541
+ /** One declared index a dispatch exercised (used to narrow a read). */
1542
+ interface IndexHit {
1543
+ /** The declared index name. */
1544
+ index: string;
1545
+ /** The table the index is declared on. */
1546
+ table: string;
1547
+ }
1548
+ /** One declared index's cumulative recorded read count (durable, non-decaying) — the advisor dead-index lint input. */
1549
+ interface FunctionMetricIndexHit {
1550
+ /** The declared index name. */
1551
+ index: string;
1552
+ /** Recorded reads that used this index to narrow. */
1553
+ reads: number;
1554
+ /** The table the index is declared on. */
1555
+ table: string;
1440
1556
  }
1441
1557
  /**
1442
- * Per-statement activity within `rangeMs` of `now`, plus a combined time series.
1443
- *
1444
- * Reads the bucket table (not the lifetime one) so the numbers answer "what is
1445
- * hot right now"; the statement TEXT is joined back from the lifetime table,
1446
- * which is the only place it is stored.
1558
+ * Fields recorded for one completed dispatch, or for a coalesced delta of
1559
+ * several. `errored` advances the failure counters. The optional count-carrying
1560
+ * fields let a caller that batched N dispatches write their exact sum in one
1561
+ * upsert; omitted, every field defaults to the single-dispatch value.
1447
1562
  */
1448
- declare const readQueryInsights: (sql: SqlExec, rangeMs: number, now?: number) => QueryInsightsResult;
1449
- /**
1450
- * Record one statement's activity. Creates the table on first call. Silently
1451
- * skips recording when the normalised statement is empty (shouldn't happen
1452
- * in practice) or when the table is already at the
1453
- * {@link QUERY_METRICS_MAX_STATEMENTS} cap and the statement is not yet
1454
- * tracked. See `admitStatement` for how the cap check avoids an unconditional
1455
- * `COUNT(*)` on every execution.
1563
+ interface RecordFunctionMetricInput {
1564
+ /** Dispatches this record stands for. Default `1`. */
1565
+ calls?: number;
1566
+ /**
1567
+ * Whether the dispatch failed on an optimistic-concurrency (OCC) write
1568
+ * conflict — a compare-and-swap that lost to a concurrent commit. Advances
1569
+ * the durable `conflicts` counter behind the write-contention advisor. A
1570
+ * conflicted dispatch also `errored`, so conflicts are a subset of errors.
1571
+ * Omitted/false on the common path, keeping the hot path unchanged.
1572
+ */
1573
+ conflicted?: boolean;
1574
+ /** Conflicts in a coalesced delta. Default `conflicted ? 1 : 0`. */
1575
+ conflicts?: number;
1576
+ /** Longest handler time in a coalesced delta. Default `durationMs`. */
1577
+ durationMaxMs?: number;
1578
+ /** Shortest handler time in a coalesced delta. Default `durationMs`. */
1579
+ durationMinMs?: number;
1580
+ /** Wall-clock millis the handler took. */
1581
+ durationMs: number;
1582
+ /** Summed handler time of a coalesced delta. Default `durationMs`. */
1583
+ durationTotalMs?: number;
1584
+ /** Whether the dispatch threw. */
1585
+ errored: boolean;
1586
+ /** Most recent failure message, recorded only when `errored`. */
1587
+ errorMessage?: string;
1588
+ /** Failed dispatches in a coalesced delta. Default `errored ? 1 : 0`. */
1589
+ errors?: number;
1590
+ /**
1591
+ * Per-`(table, index)` hit counts of a coalesced delta (one per dispatch that
1592
+ * used the index). When set, replaces {@link RecordFunctionMetricInput.indexHits}.
1593
+ */
1594
+ indexHitCounts?: ReadonlyArray<IndexHit & {
1595
+ count: number;
1596
+ }>;
1597
+ /**
1598
+ * Distinct declared indexes this dispatch exercised (used to narrow a read),
1599
+ * collected from the `onIndexUse` signal. Each entry bumps the
1600
+ * per-`(table, index)` hit counter in `__lunora_metrics_index`, the durable
1601
+ * producer behind the advisor dead-index lint. Omitted/empty when the
1602
+ * dispatch used no declared index, keeping the hot path unchanged.
1603
+ */
1604
+ indexHits?: ReadonlyArray<IndexHit>;
1605
+ /** Epoch-ms of the latest failure in a coalesced delta. Default `errored ? ts : null`. */
1606
+ lastErrorAt?: number | null;
1607
+ /** The `<file>:<function>` identifier. */
1608
+ path: string;
1609
+ /**
1610
+ * Per-table full-scan counts of a coalesced delta (one per dispatch that
1611
+ * scanned the table). When set, replaces {@link RecordFunctionMetricInput.scannedTables}.
1612
+ */
1613
+ scanCounts?: ReadonlyArray<{
1614
+ count: number;
1615
+ table: string;
1616
+ }>;
1617
+ /**
1618
+ * Distinct tables this dispatch full-scanned (read with no index / point
1619
+ * lookup), collected from the `SCAN_DEP` reads. Each entry bumps the
1620
+ * aggregate `scans` counter and the per-`(path, table)` attribution row.
1621
+ * Omitted/empty when the dispatch didn't full-scan anything (the common
1622
+ * indexed case), keeping the hot path to the same two upserts as before.
1623
+ */
1624
+ scannedTables?: ReadonlyArray<string>;
1625
+ /** Epoch-ms the dispatch completed. */
1626
+ ts: number;
1627
+ }
1628
+ /**
1629
+ * Create the four reserved metrics tables. Idempotent, so the read and write
1630
+ * paths can call it defensively. The accumulator table is keyed by `path` (one
1631
+ * row per function); the bucket table by `(path, bucketMs)` (one row per
1632
+ * function per window); the scans table by `(path, table)` (one row per
1633
+ * function per full-scanned table); the index table by `(table, index)` (one
1634
+ * row per declared index the app exercises).
1456
1635
  *
1457
- * `execCount` (default 1) lets a caller fold several executions of the SAME
1458
- * statement into one call — `shard-do.ts` does this per dispatch so a
1459
- * query-in-a-loop handler pays one upsert here instead of one per raw
1460
- * execution. `durationMs`/`rowsRead`/`rowsWritten` are then the SUM across
1461
- * `execCount` executions, exactly as `exec_count`/`total_duration_ms` already
1462
- * accumulate sums across separate calls — folding before calling is
1463
- * indistinguishable, from this table's point of view, from `execCount`
1464
- * separate calls with the same totals.
1636
+ * The accumulator's `scans` column is added via a guarded `ALTER TABLE` rather
1637
+ * than baked into the `CREATE` so a shard whose `__lunora_metrics` predates the
1638
+ * causal-attribution feature gains the column on the next call without a
1639
+ * migration. SQLite has no `ADD COLUMN IF NOT EXISTS`, so the duplicate-column
1640
+ * error from a re-run is swallowed. Both the `CREATE`s and the back-fill only
1641
+ * run once per handle (see {@link ensuredHandles}) — a handle already marked
1642
+ * ensured returns immediately.
1465
1643
  */
1466
- declare const recordQueryMetric: (sql: SqlExec, rawSql: string, durationMs: number, rowsRead: number, rowsWritten: number, now?: number, execCount?: number) => void;
1644
+ declare const ensureFunctionMetricsTables: (sql: SqlExec) => void;
1467
1645
  /**
1468
- * Read all tracked statement aggregates, ordered by `total_duration_ms DESC`
1469
- * (the leaderboard's default). Creates the table first so a read on a
1470
- * never-called shard returns `[]`.
1646
+ * Persist one completed dispatch: a single upsert into the accumulator row and
1647
+ * one upsert into the current time bucket, then a bounded trim of old buckets
1648
+ * for that path. Creates the tables first so callers needn't. This is the hot
1649
+ * path — exactly two `INSERT … ON CONFLICT … DO UPDATE` statements plus a
1650
+ * bounded `DELETE`, all keyed by primary key, so it stays cheap.
1651
+ *
1652
+ * When the dispatch full-scanned one or more tables (`scannedTables`), the
1653
+ * aggregate `scans` counter on the accumulator row advances by the distinct
1654
+ * table count and one extra `(path, table)` upsert fires per scanned table.
1655
+ * Indexed dispatches (the common case) skip all of that and pay nothing.
1471
1656
  */
1472
- declare const readQueryMetrics: (sql: SqlExec) => QueryStatEntry[];
1473
- /** Reserved append-only table backing the studio Logs tab. Auto-hidden from the data browser by the `__lunora` prefix. */
1474
- declare const REQUEST_LOG_TABLE = "__lunora_reqlog__";
1475
- /** Outcome of one dispatch — `ok` for a returned result, `error` for a thrown handler. */
1476
- type RequestOutcome = "error" | "ok";
1477
- /** One recorded `/rpc` dispatch, in monotonic `seq` order. */
1478
- interface RequestLogEntry {
1479
- /** Whether the result was served from the reactive cache; `undefined` when the cache is disabled or the path isn't cached (a write/action). */
1480
- cacheHit?: boolean;
1481
- /** Handler wall-clock duration in milliseconds (before the subscription write-flush, matching the per-function metrics). */
1482
- durationMs: number;
1483
- /** Error message when `outcome === "error"`, redacted like args/identity; absent on success. */
1484
- errorMessage?: string;
1485
- /** The `<file>:<function>` identifier dispatched, e.g. `messages:list`. */
1486
- functionPath: string;
1487
- /** 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. */
1488
- identity?: Record<string, unknown>;
1489
- /** `ok` for a returned result, `error` for a thrown handler. */
1490
- outcome: RequestOutcome;
1491
- /** Call args with leaf values redacted by default (keys/shape preserved); absent when no args were sent. */
1492
- redactedArgs?: unknown;
1493
- /** Monotonic per-shard cursor — strictly increasing, never reused. */
1494
- seq: number;
1495
- /** Shard key (the DO id name), or `undefined` for the unnamed `__root__` DO. */
1496
- shardKey?: string;
1497
- /** Count of subscriptions re-run by the write this dispatch triggered; `0` when none (or not measured at the dispatch site). */
1498
- subscriptionsReRun: number;
1499
- /** Tables the handler read (from the dependency tracker); empty when the reactive cache is off or the path read nothing. */
1500
- tablesRead: string[];
1501
- /** Tables the handler wrote (from the change tracker); empty for a read-only dispatch. */
1502
- tablesWritten: string[];
1503
- /** 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. */
1504
- traceId?: string;
1505
- /** Wall-clock millis when the dispatch completed. */
1506
- ts: number;
1507
- /** Acting userId forwarded by the runtime, or `undefined` when anonymous. */
1508
- userId?: string;
1657
+ declare const recordFunctionMetric: (sql: SqlExec, input: RecordFunctionMetricInput) => void;
1658
+ /**
1659
+ * Read the per-function full-scan attribution, grouped by function path. The
1660
+ * returned map keys are `path`; each value is the function's full-scanned
1661
+ * tables ordered by scan count (busiest scan first), so the causal "slow
1662
+ * BECAUSE it scanned X" read can lead with the dominant table. Creates the
1663
+ * table first so reads on a never-called shard return an empty map.
1664
+ */
1665
+ declare const readFunctionMetricScans: (sql: SqlExec) => Map<string, FunctionScanAttribution[]>;
1666
+ /**
1667
+ * Read the per-`(table, index)` hit counts — the advisor dead-index lint input.
1668
+ * Each entry is a declared index and how many recorded reads used it to narrow
1669
+ * (a cumulative, non-decaying count); the lint reconciles this against the schema
1670
+ * to flag a declared index that appears with zero reads (or not at all) as dead. Ordered
1671
+ * by table then index for stable output. Creates the table first so a read on a
1672
+ * never-exercised shard returns `[]`.
1673
+ */
1674
+ declare const readFunctionMetricIndexHits: (sql: SqlExec) => FunctionMetricIndexHit[];
1675
+ /**
1676
+ * Fold a dispatch's distinct full-scanned tables into an in-memory attribution
1677
+ * list, mirroring the per-`(path, table)` upsert {@link recordFunctionMetric}
1678
+ * applies to the durable `__lunora_metrics_scans` table. Kept here, beside its
1679
+ * SQL twin, so the one rule (one occurrence = +1 scan for that table, list
1680
+ * re-sorted busiest-first) lives in a single module — the in-memory copy exists
1681
+ * only for the warm-instance fallback when the durable read is unavailable.
1682
+ * Mutates and returns `into`.
1683
+ */
1684
+ declare const mergeScanAttribution: (into: FunctionScanAttribution[], scanned: ReadonlyArray<string>) => FunctionScanAttribution[];
1685
+ /**
1686
+ * Read the persisted per-function accumulators as {@link FunctionCallStat}s,
1687
+ * newest-called first. Creates the table first so reads on a never-called shard
1688
+ * return `[]` instead of throwing. The shape is a superset of the legacy
1689
+ * in-memory `getFunctionStats` rows — the additive `scans` total and
1690
+ * `scannedTables` causal attribution are folded in here so a single read backs
1691
+ * the Insights "missing index" / "full scan" signal.
1692
+ */
1693
+ declare const readFunctionMetrics: (sql: SqlExec) => FunctionCallStat[];
1694
+ /**
1695
+ * Read the coarse time-series buckets for `path` (every path when omitted),
1696
+ * oldest-bucket first so a chart can plot them left-to-right. Creates the table
1697
+ * first so reads on a never-called shard return `{ buckets: [], truncated: false }`.
1698
+ */
1699
+ declare const readFunctionMetricBuckets: (sql: SqlExec, path?: string) => FunctionMetricBucketsResult;
1700
+ /**
1701
+ * Aggregate the persisted accumulators into the lifetime totals the metrics
1702
+ * health snapshot reports: total calls (`requests`), total `errors`. Returns
1703
+ * zeroes on a never-called shard.
1704
+ *
1705
+ * `capped` is true when the distinct-path cap ({@link FUNCTION_METRICS_MAX_PATHS})
1706
+ * has been reached — the write-side signal that a brand-new function path is
1707
+ * currently being refused (see `admitPath`), mirroring `readQueryInsights`'s
1708
+ * `capped` for query-metrics and `readMetricHistory`'s for metric-history.
1709
+ */
1710
+ declare const readFunctionMetricsTotals: (sql: SqlExec) => {
1711
+ capped: boolean;
1712
+ errors: number;
1713
+ requests: number;
1714
+ };
1715
+ /**
1716
+ * The Workers AI text model the Issue explainer uses when the caller does not
1717
+ * override it. The fp8-fast instruct model the rest of the repo defaults to —
1718
+ * the explainer is a short, grounded rewrite (not a reasoning task), so a
1719
+ * latency-optimized build beats a larger one. Deliberately not the retired
1720
+ * `@cf/meta/llama-3.1-8b-instruct`: a deprecated model-id makes `binding.run`
1721
+ * throw, which would silently degrade every explain to `"ai-error"`.
1722
+ */
1723
+ /**
1724
+ * Fallback model id when neither the caller nor the request names one.
1725
+ *
1726
+ * A Workers AI id, which makes it the *host's* default rather than this
1727
+ * package's — a second host runs different models and must be able to say so.
1728
+ * `explainIssue` therefore takes `defaultModel`, and this constant is only what
1729
+ * the Cloudflare host happens to pass. Kept exported so that host has a name to
1730
+ * pass rather than a string literal.
1731
+ */
1732
+ declare const DEFAULT_EXPLAIN_ISSUE_MODEL = "@cf/meta/llama-3.3-70b-instruct-fp8-fast";
1733
+ /**
1734
+ * Structural projection of the Workers `AI` binding's `run` method — declared
1735
+ * locally so `@lunora/do` needs no dependency edge on `@lunora/ai` (nor on
1736
+ * `@cloudflare/workers-types`) to reach `env.AI`. Mirrors `AiBindingLike` in
1737
+ * `@lunora/ai`.
1738
+ */
1739
+ interface AiRunBinding {
1740
+ run: (model: string, inputs: Record<string, unknown>, options?: Record<string, unknown>) => Promise<unknown>;
1509
1741
  }
1510
- /** Fields accepted when appending one request-log entry; `seq` is assigned by the table. */
1511
- interface AppendRequestLogEntry {
1512
- cacheHit?: boolean;
1513
- durationMs: number;
1514
- errorMessage?: string;
1515
- functionPath: string;
1516
- identity?: Record<string, unknown>;
1517
- outcome: RequestOutcome;
1518
- redactedArgs?: unknown;
1519
- shardKey?: string;
1520
- subscriptionsReRun?: number;
1521
- tablesRead?: string[];
1522
- tablesWritten?: string[];
1523
- traceId?: string;
1524
- ts: number;
1525
- userId?: string;
1742
+ /** Parsed `__lunora_admin__:explainIssue` payload: the folded Issue's identifying facts, plus an optional model override. */
1743
+ interface ExplainIssueArgs {
1744
+ /** The Issue's culprit (`<file>:<function>` or `container:<name>`), for grounding context. */
1745
+ culprit?: string;
1746
+ /** Per-request model-id override; falls back to the caller's `defaultModel`, then {@link DEFAULT_EXPLAIN_ISSUE_MODEL}. */
1747
+ model?: string;
1748
+ /** A representative raw error message for the Issue — the fact the explanation is grounded in. Required. */
1749
+ sampleMessage: string;
1750
+ /** The Issue's human-readable title (first line of the sample message), for grounding context. */
1751
+ title?: string;
1526
1752
  }
1527
- /** Knobs the dispatch site threads into a request-log write. */
1528
- interface RequestLogWriteOptions {
1529
- /** When `true` (development only), skip args/identity redaction so a developer sees raw values. Defaults to `false` (production-safe). */
1530
- captureRaw?: boolean;
1531
- /** Rows to keep after the append-time trim; defaults to {@link REQUEST_LOG_RETENTION}. The operator's `LUNORA_REQUEST_LOG_RETENTION` override. */
1532
- retention?: number;
1753
+ /**
1754
+ * Why the explainer fell back to the grounded hint alone. A closed union rather
1755
+ * than a bare `string` so `degraded(reason)` rejects a typo'd sentinel at compile
1756
+ * time instead of letting it fall through to the client's generic error copy.
1757
+ * Mirrored by `ExplainIssueResult["reason"]` in `@lunora/studio`'s `lib/admin.ts`.
1758
+ */
1759
+ type ExplainIssueDegradedReason = "ai-error" | "empty-response" | "no-ai-binding";
1760
+ /**
1761
+ * The grounding facts both `__lunora_admin__:explainIssue` outcomes carry. Present
1762
+ * whenever {@link findIssueSolution} recognized the message — offline,
1763
+ * deterministic, and independent of whether the AI path ran at all.
1764
+ *
1765
+ * The hint BODY is deliberately not on the wire: the client derives it from the
1766
+ * same catalog offline (that is the whole point of the grounded layer), so
1767
+ * shipping it would be payload nothing reads.
1768
+ */
1769
+ interface ExplainIssueGrounding {
1770
+ /**
1771
+ * The id of the matched catalog/platform solution the prompt was grounded in,
1772
+ * absent when nothing recognized the message. The client renders a caveat on
1773
+ * absence — an ungrounded explanation is a free-form model guess, not a
1774
+ * catalog-backed one, and must not be presented as the latter.
1775
+ */
1776
+ groundedId?: string;
1777
+ }
1778
+ /**
1779
+ * The `__lunora_admin__:explainIssue` result — a discriminated union on `degraded`
1780
+ * rather than a bag of optionals, so each outcome's guaranteed fields are
1781
+ * guaranteed in the type too. The AI `explanation` is best-effort: the degraded
1782
+ * arm is returned when no `env.AI` binding is configured or the inference call
1783
+ * failed, and the client falls back to its own grounded hint alone.
1784
+ *
1785
+ * Modelling this as one flat interface let a `degraded` result type-check without a
1786
+ * `reason`, which the studio silently renders as the generic AI-error copy.
1787
+ */
1788
+ /** The arm returned when no inference happened, or it failed. */
1789
+ interface ExplainIssueDegraded extends ExplainIssueGrounding {
1790
+ /** The AI path was unavailable or failed — render the grounded hint instead. */
1791
+ degraded: true;
1792
+ /** Why the AI path degraded, for the client to surface. */
1793
+ reason: ExplainIssueDegradedReason;
1533
1794
  }
1534
- /** Filters for {@link readRequestLog}, all AND-combined; every value is a bound SQL parameter, so nothing here injects SQL. */
1535
- interface ReadRequestLogOptions {
1536
- /** Functions whose path begins with this prefix (a `<file>:` or `<file>:<fn>` correlation). */
1537
- functionPathPrefix?: string;
1538
- /** Upper bound on returned rows, clamped to [1, 10000]. */
1539
- limit?: number;
1540
- /** Keep only `ok` / `error` outcomes. */
1541
- outcome?: RequestOutcome;
1542
- /** Exact shard-key match. */
1543
- shardKey?: string;
1544
- /** Only entries strictly after this cursor (forward paging). */
1545
- sinceSeq?: number;
1546
- /** Keep only entries whose read OR written table set contains this table. */
1547
- tableTouched?: string;
1548
- /** Exact acting-userId match. */
1549
- userId?: string;
1795
+ /** The arm returned when the model ran and produced text. */
1796
+ interface ExplainIssueSuccess extends ExplainIssueGrounding {
1797
+ /** The AI path ran and produced text. */
1798
+ degraded: false;
1799
+ /** The AI-generated plain-language explanation. */
1800
+ explanation: string;
1801
+ /** The Workers AI model-id that produced {@link ExplainIssueSuccess.explanation}. */
1802
+ model: string;
1550
1803
  }
1551
- /** Payload of a `__lunora_admin__:getRequestLog` call: the recorded entries, newest first. */
1552
- interface RequestLogResult {
1553
- entries: RequestLogEntry[];
1804
+ type ExplainIssueResult = ExplainIssueDegraded | ExplainIssueSuccess;
1805
+ /**
1806
+ * Validate the `__lunora_admin__:explainIssue` payload. Requires a non-empty
1807
+ * `sampleMessage` (the grounding fact); `title`, `culprit`, and `model` are
1808
+ * optional context/overrides. Throws a 400 `LunoraError` on a bad shape.
1809
+ *
1810
+ * Every caller-supplied field that reaches the prompt is capped here — capping
1811
+ * `sampleMessage` alone left `title`/`culprit` as an open door onto the same
1812
+ * prompt budget.
1813
+ */
1814
+ declare const parseExplainIssueArgs: (args: Record<string, unknown>) => ExplainIssueArgs;
1815
+ /**
1816
+ * Run the full explain flow for one Issue: validate the payload, ground it in the
1817
+ * catalog, and — when `binding` is a usable Workers AI binding — ask the model for
1818
+ * a plain-language rewrite. Never throws for an AI-side failure; every such path
1819
+ * returns the `degraded: true` arm carrying the grounded hint, so the caller
1820
+ * always has something to render. Only a malformed payload throws (a 400).
1821
+ *
1822
+ * `binding` is `unknown` so the caller can hand over `env.AI` untyped — the shape
1823
+ * check lives here rather than at each call site.
1824
+ */
1825
+ declare const explainIssue: (binding: unknown, args: Record<string, unknown>, options?: {
1826
+ defaultModel?: string;
1827
+ }) => Promise<ExplainIssueResult>;
1828
+ /**
1829
+ * Severity of a buffered log entry — the full seven-tier `ctx.log` ramp
1830
+ * (`trace`→`fatal`), not a console-shaped subset. The buffer used to fold the
1831
+ * ramp onto four tiers, which made `trace` and `fatal` lines indistinguishable
1832
+ * from `debug` and `error` in the Studio Logs panel; it now stores the level the
1833
+ * caller actually logged at. Container-lifecycle entries only ever use
1834
+ * `info`/`error`, which remain part of the union.
1835
+ */
1836
+ type LogLevel = ContextLogLevel;
1837
+ /**
1838
+ * One buffered log line. `functionPath` is the RPC that produced it (when the
1839
+ * entry came from the RPC dispatch site); `timestamp` is `Date.now()` at the
1840
+ * moment it was pushed. `instance`/`exitCode` are populated for container
1841
+ * lifecycle entries: `instance` correlates the per-instance Durable Object id,
1842
+ * `exitCode` carries the process exit code parsed out of a `stop` event.
1843
+ */
1844
+ interface LogEntry {
1845
+ exitCode?: number;
1846
+ /** Structured fields from a `ctx.log.<level>(message, fields)` / `ctx.log.with(fields)` call, when present. */
1847
+ fields?: Record<string, unknown>;
1848
+ functionPath?: string;
1849
+ instance?: string;
1850
+ level: LogLevel;
1851
+ message: string;
1852
+ timestamp: number;
1853
+ /** Trace the line was emitted under; absent outside a dispatch (container lifecycle, hibernation-path errors). What the Studio joins a log line to its waterfall on. */
1854
+ traceId?: string;
1554
1855
  }
1555
1856
  /**
1556
- * One grouped error **Issue**: many `error`-outcome request-log rows that share a
1557
- * fingerprint folded into a single triage row. The `hash` is the same stable key
1558
- * a cloud Incident groups on, so a local Issue and a cloud Incident are the same
1559
- * object.
1857
+ * A bounded, in-memory ring buffer of recent {@link LogEntry} records.
1858
+ *
1859
+ * In-memory only: like the metrics counters on `ShardDO`, the buffer is a field
1860
+ * on the live Durable Object instance and so resets whenever the DO hibernates
1861
+ * or restarts. It is a "recent activity on this instance" readout (for the
1862
+ * studio's live log panel), NOT a durable log store or a transport.
1863
+ * Production log shipping is the platform's job, not ours: use Cloudflare
1864
+ * **Workers Logs** (retained, queryable in the studio), **Logpush** (stream
1865
+ * to R2 / a SIEM / a log service), or a **Tail Worker** for programmatic
1866
+ * capture. Lunora deliberately does not reimplement any of those — this buffer
1867
+ * stays a tiny dev/ops readout. Capacity is fixed at construction; once full,
1868
+ * the oldest entry is evicted to make room (FIFO), so memory stays bounded
1869
+ * regardless of traffic.
1560
1870
  */
1561
- interface ErrorIssue {
1562
- /** Assignee (a userId or a name) from the persisted triage state; absent when unassigned. */
1563
- assignee?: string;
1564
- /** Number of `error` rows folded into this Issue within the scanned window. */
1565
- count: number;
1566
- /** The `<file>:<function>` (or `container:<name>`) the errors came from. */
1567
- culprit: string;
1568
- /** Wall-clock millis of the oldest folded row. */
1569
- firstSeen: number;
1871
+ declare class LogBuffer {
1872
+ /** Backing store, kept in insertion order (oldest first). */
1873
+ private readonly buffer;
1874
+ private readonly capacity;
1875
+ /** How many entries the ring has evicted since it was last cleared. */
1876
+ private droppedCount;
1877
+ constructor(capacity?: number);
1570
1878
  /**
1571
- * Stable 16-char grouping hash over `functionPath :: bucket(message)`,
1572
- * computed from the RAW (pre-redaction) message at write time and stored on
1573
- * the row — see {@link appendRequestLogEntry} — so redacting `sampleMessage`
1574
- * below can't change the grouping.
1879
+ * Entries evicted for capacity since the last {@link LogBuffer.clear}.
1880
+ *
1881
+ * Without it a full ring is indistinguishable from a quiet instance that
1882
+ * happened to log exactly `capacity` lines: the reader sees 500 entries
1883
+ * either way and cannot tell whether 500 lines happened or 50,000 did. The
1884
+ * count is what turns "the newest 500" into an honest statement.
1575
1885
  */
1576
- hash: string;
1577
- /** Wall-clock millis of the newest folded row. */
1578
- lastSeen: number;
1579
- /** A representative error message (redacted, like the durable row) — taken from the most recent folded row. */
1580
- sampleMessage: string;
1581
- /** Developer-tagged severity from the persisted triage state; absent when untriaged. */
1582
- severity?: IssueSeverity;
1886
+ get dropped(): number;
1887
+ /** Number of entries currently buffered. */
1888
+ get size(): number;
1889
+ /** Drop every buffered entry, including the eviction count. */
1890
+ clear(): void;
1583
1891
  /**
1584
- * Wall-clock millis the persisted triage state was last changed; absent when
1585
- * the Issue has never been triaged. Compared against `lastSeen` to detect a
1586
- * regression (a new error after a resolve).
1892
+ * Snapshot of the buffered entries, **newest first** so the panel renders
1893
+ * the most recent activity at the top without re-sorting. Returns a fresh
1894
+ * array each call; the caller may mutate it freely.
1587
1895
  */
1588
- stateUpdatedAt?: number;
1896
+ entries(): LogEntry[];
1589
1897
  /**
1590
- * Triage status folded in from the persisted state (`open` by default). A
1591
- * `resolved` Issue whose `lastSeen` is newer than `stateUpdatedAt` is
1592
- * auto-reopened to `open` here (a regression), so a fresh occurrence never
1593
- * hides behind a stale resolution; `ignored` stays sticky by design.
1898
+ * Append an entry, evicting the oldest when at capacity so the buffer never
1899
+ * grows past its bound.
1594
1900
  */
1595
- status: IssueStatus;
1596
- /** Human-readable title (first line of the sample message, capped). */
1597
- title: string;
1901
+ push(entry: LogEntry): void;
1598
1902
  }
1599
- /** Payload of a `__lunora_admin__:getIssues` call: grouped error Issues, most-recently-active first. */
1600
- interface IssuesResult {
1601
- issues: ErrorIssue[];
1903
+ /**
1904
+ * One aggregated metric series: every measurement sharing a `(name, kind,
1905
+ * attributes)` identity folded into a single running summary.
1906
+ *
1907
+ * All fields are maintained for every {@link MetricKind} — the fold is uniform
1908
+ * and O(1), and letting the panel choose the meaningful projection per kind
1909
+ * (counter → `sum`, gauge → `last`, histogram → `sum`/`count` for the mean, plus
1910
+ * `min`/`max`) is cheaper and clearer than branching on kind at record time.
1911
+ */
1912
+ interface MetricSeries {
1913
+ /** The series' dimensions, if any — the attributes that made it distinct. */
1914
+ attributes?: LogFields;
1915
+ /** Number of measurements folded into this series. */
1916
+ count: number;
1917
+ /** Trace id of the most recent measurement that carried one — the series' exemplar, for linking to a trace. */
1918
+ exemplarTraceId?: string;
1919
+ /** Wall-clock millis of the first measurement folded in. */
1920
+ firstTs: number;
1921
+ /** Function path that recorded the series' most recent measurement. */
1922
+ functionPath: string;
1923
+ /** Instrument kind; decides which projection the panel shows. */
1924
+ kind: MetricKind;
1925
+ /** Most recent measured value — the current reading for a `gauge`. */
1926
+ last: number;
1927
+ /** Wall-clock millis of the most recent measurement. */
1928
+ lastTs: number;
1929
+ /** Largest measured value seen. */
1930
+ max: number;
1931
+ /** Smallest measured value seen. */
1932
+ min: number;
1933
+ /** Instrument name, e.g. `"orders.placed"`. */
1934
+ name: string;
1935
+ /** Shard key for single-shard calls; absent for the unnamed root DO. */
1936
+ shardKey?: string;
1937
+ /** Sum of measured values — a `counter`'s total, a `histogram`'s sum. */
1938
+ sum: number;
1602
1939
  }
1603
- /** Filters for {@link readErrorIssues}; forwarded to {@link readRequestLog} with `outcome` forced to `error`. */
1604
- interface ReadIssuesOptions {
1605
- /** Functions whose path begins with this prefix (a `<file>:` or `<file>:<fn>` correlation). */
1606
- functionPathPrefix?: string;
1607
- /** Upper bound on error rows scanned before grouping, clamped to [1, 10000]. */
1608
- limit?: number;
1609
- /** Exact shard-key match. */
1940
+ /**
1941
+ * A bounded map of running metric aggregates, keyed by series identity. Eviction
1942
+ * is least-recently-*updated*: a re-recorded series moves back to the tail (Map
1943
+ * insertion order), so the capacity bound sheds cold, high-cardinality series and
1944
+ * keeps the ones still receiving traffic — the opposite of a raw ring, which
1945
+ * would evict a hot counter's own history.
1946
+ */
1947
+ declare class MetricBuffer {
1948
+ private readonly capacity;
1949
+ private readonly series;
1950
+ constructor(capacity?: number);
1951
+ /** Number of distinct series currently aggregated. */
1952
+ get size(): number;
1953
+ /** Drop every aggregated series. */
1954
+ clear(): void;
1955
+ /**
1956
+ * Snapshot of the aggregated series, most-recently-updated first, each a fresh
1957
+ * copy so a caller can't mutate the live aggregate. `series` is kept in
1958
+ * update order (tail = newest), so one reverse yields newest-first.
1959
+ */
1960
+ entries(): MetricSeries[];
1961
+ /** Fold one measurement into its series, creating or updating the aggregate. */
1962
+ push(event: MetricEvent): void;
1963
+ }
1964
+ /** One time-bucket sample of a series: the aggregate over `[bucketMs, bucketMs + METRIC_HISTORY_BUCKET_MS)`. */
1965
+ interface MetricHistoryPoint {
1966
+ /** Epoch-ms floor of the bucket window. */
1967
+ bucketMs: number;
1968
+ /** Measurements folded into this bucket. */
1969
+ count: number;
1970
+ /** Sample `traceId` of a measurement in this bucket, if one carried trace context — the exemplar. */
1971
+ exemplarTraceId?: string;
1972
+ /** Last measured value in the bucket — a gauge's reading at the window's end. */
1973
+ last: number;
1974
+ /** Largest value in the bucket. */
1975
+ max: number;
1976
+ /** Smallest value in the bucket. */
1977
+ min: number;
1978
+ /** Sum of values in the bucket — a counter's increment total, a histogram's sum. */
1979
+ sum: number;
1980
+ }
1981
+ /** One series' durable history: its identity plus its time-ordered buckets, oldest first. */
1982
+ interface MetricHistorySeries {
1983
+ attributes?: LogFields;
1984
+ functionPath: string;
1985
+ kind: MetricKind;
1986
+ name: string;
1987
+ /** Buckets in ascending `bucketMs` order, ready to chart as a line. */
1988
+ points: MetricHistoryPoint[];
1610
1989
  shardKey?: string;
1611
- /** Keep only Issues in this triage status, applied AFTER the persisted-state fold + auto-reopen. */
1612
- status?: IssueStatus;
1613
- /** Exact acting-userId match. */
1614
- userId?: string;
1990
+ }
1991
+ /** {@link readMetricHistory} result: every tracked series with its buckets. */
1992
+ interface MetricHistoryResult {
1993
+ /**
1994
+ * True when the distinct-series cap has been reached — a **write-side**
1995
+ * signal ("this shard can no longer admit a brand-new series", see
1996
+ * `admitNewSeries`), not a read-side truncation flag. It is computed over
1997
+ * the whole table regardless of `options.sinceMs`/the row-count read
1998
+ * limit, so it can be `true` even when every series `readMetricHistory`
1999
+ * actually returned fits comfortably: the caller should read it as "a
2000
+ * flood of new series would currently be refused", the same thing
2001
+ * `readQueryInsights`'s `capped` already signals for query-metrics.
2002
+ */
2003
+ capped: boolean;
2004
+ series: MetricHistorySeries[];
1615
2005
  }
1616
2006
  /**
1617
- * Redact the secrets / PII out of a value before it reaches the durable log or a
1618
- * Logpush event, via `@visulima/redact`'s `standardRules`. Unlike a blunt
1619
- * type-tag stamp this masks sensitive values by PATTERN (not just by key name)
1620
- * while leaving benign values readable, so the studio's args/identity columns
1621
- * stay useful. `null` / `undefined` pass through unchanged.
1622
- *
1623
- * What `standardRules` actually catches differs by shape, verified against its
1624
- * real behavior rather than assumed from its name: on a KEYED object (`args`,
1625
- * `identity`) it also matches by key name, so `{ password: "hunter2" }` and
1626
- * `{ token: "…" }` ARE masked regardless of the value's shape. On a PLAIN
1627
- * STRING — which is what `errorMessage`/log `fields`-as-rendered-text are —
1628
- * only pattern-shaped matches apply: emails, long digit runs / structured
1629
- * numeric IDs (credit-card, phone, SSN, AWS-access-key-style), and an explicit
1630
- * `Bearer <token>` / `token=…`-shaped substring. A free-text `password=hunter2`
1631
- * or a bare provider API key embedded in prose (e.g. `sk-live-…`) is NOT
1632
- * caught on a plain string — there is no key to match against, and neither is
1633
- * a recognized value pattern. So this is a PII-pattern net for rendered text,
1634
- * not a general secrets scrubber; a handler that echoes a raw credential into
1635
- * an error message or a log string can still leak it through here. Works on a
1636
- * plain string too (`redact` traverses whatever value it's handed), which is
1637
- * how {@link appendRequestLogEntry} and {@link emitRequestLogEvent} reuse this
1638
- * for `errorMessage` — a validation error echoes the offending value, a
1639
- * constraint error quotes the conflicting row, so the error message is at
1640
- * least as PII-dense as args and gets the same treatment (with the free-text
1641
- * caveat above).
1642
- *
1643
- * `captureRaw` is the development escape hatch: in a dev environment the dispatch
1644
- * site (`isDevEnvironment`) passes `true` to skip redaction so a developer can
1645
- * see real arg/identity/error values; production always redacts. The dev
1646
- * decision is made at the call site from the deployment env, never inferred
1647
- * here — so a real deploy that omits the env var stays redacted.
2007
+ * Tunable caps for {@link recordMetricHistory}, threaded from the sink's
2008
+ * `metricHistory` option. Each falls back to its module-constant default, so an
2009
+ * omitted field keeps the historical behaviour.
1648
2010
  */
1649
- declare const redactArgs: (value: unknown, captureRaw?: boolean) => unknown;
2011
+ interface MetricHistoryOptions {
2012
+ /**
2013
+ * Distinct series tracked before a brand-new one is REFUSED admission
2014
+ * (default {@link METRIC_HISTORY_MAX_SERIES}). Nothing is evicted: an
2015
+ * already-tracked series keeps accumulating past the cap, and a flood of
2016
+ * one-off series cannot displace the app's real ones — see
2017
+ * {@link admitNewSeries}. `readMetricHistory`'s `capped` flag is the
2018
+ * read-side signal that admission is being refused.
2019
+ */
2020
+ maxSeries?: number;
2021
+ /** Minute-buckets kept per series before older rows are trimmed (default {@link METRIC_HISTORY_BUCKET_RETENTION}). */
2022
+ retentionBuckets?: number;
2023
+ }
1650
2024
  /**
1651
- * Create the `__lunora_reqlog__` table. `seq` is an `AUTOINCREMENT` primary
1652
- * key, giving each shard a monotonic cursor the Logs tab pages through; the
1653
- * `args`/`identity`/`tables_read`/`tables_written` columns hold JSON and are
1654
- * `NULL`/empty when none was recorded. Idempotent, so read and write paths can
1655
- * call it defensively.
2025
+ * Fold one measurement into its `(series, minute)` bucket. Runs per
2026
+ * `ctx.metrics.*` call (unlike `function-metrics.ts`, which runs once per
2027
+ * dispatch), so it's tuned for the in-minute repeat: a bucket this instance has
2028
+ * already written is a single upsert (no reads), a bucket only in the DB costs one
2029
+ * PK point-lookup + upsert, and only a genuinely new bucket also pays the
2030
+ * distinct-series cap scan + retention trim. Still a durable SQLite write per
2031
+ * measurement, so a hot loop recording thousands of points a second should
2032
+ * pre-aggregate and record once (see `shared/metric-event.ts`). Creates the table
2033
+ * first so callers needn't.
1656
2034
  *
1657
- * `error_fingerprint` is the {@link fingerprintError} grouping hash captured
1658
- * from the RAW `error_message` at write time, before {@link appendRequestLogEntry}
1659
- * redacts it — see that function's docstring. `trace_id` is the dispatch's W3C
1660
- * trace id, the correlation key to the span ring and to whatever collector
1661
- * `otlpSink` ships to.
2035
+ * `exemplarTraceId` (the recording dispatch's trace, when it had one) is stored on
2036
+ * the bucket so the studio can link a chart point back to a trace. Latest wins:
2037
+ * a later sample carrying a trace replaces an earlier bucket's exemplar.
1662
2038
  *
1663
- * Both are also added via a guarded `ALTER TABLE`, mirroring
1664
- * `function-metrics.ts`'s `ensureFunctionMetricsTables`, so a shard whose
1665
- * `__lunora_reqlog__` predates a column gains it on the next call without a
1666
- * migration. SQLite has no `ADD COLUMN IF NOT EXISTS`, so the duplicate-column
1667
- * error from a re-run (or from the freshly-created schema above) is swallowed
1668
- * per column — the loop is what keeps one column's duplicate from skipping the
1669
- * next column's add.
2039
+ * `options` tunes the distinct-series cap and retention window from the sink's
2040
+ * `metricHistory` flag (see {@link MetricHistoryOptions}); each defaults to its
2041
+ * module constant.
1670
2042
  */
1671
- declare const ensureRequestLogTable: (sql: SqlExec) => void;
2043
+ declare const recordMetricHistory: (sql: SqlExec, event: MetricEvent, exemplarTraceId?: string, options?: MetricHistoryOptions) => void;
1672
2044
  /**
1673
- * Append one dispatch to the request log, then trim the log back to the most
1674
- * recent `retention` rows (default {@link REQUEST_LOG_RETENTION}). Creates the
1675
- * table first so callers needn't. Args/identity/error message are redacted here
1676
- * so a raw value never reaches the durable table — callers pass the unredacted
1677
- * entry and rely on this, unless `captureRaw` (dev only) is set. `retention` is
1678
- * the operator's `LUNORA_REQUEST_LOG_RETENTION` override, threaded in by the
1679
- * dispatch site.
2045
+ * Read the durable history, grouped into one {@link MetricHistorySeries} per
2046
+ * series with its buckets in ascending time order.
1680
2047
  *
1681
- * The error-grouping fingerprint is computed from `entry.errorMessage` BEFORE
1682
- * it's redacted below, and the resulting hash is persisted in
1683
- * `error_fingerprint`. `readErrorIssues` groups off that stored hash instead of
1684
- * recomputing `fingerprintError` from the (redacted) `error_message` column, so
1685
- * masking a PII-bearing value — e.g. two different `<n>`-bucketed IDs that
1686
- * redact to two different tag lengths (`<DL>` vs `<BANKACC>`) — can't split an
1687
- * existing Issue or change its identity.
1688
- */
1689
- declare const appendRequestLogEntry: (sql: SqlExec, entry: AppendRequestLogEntry, options?: RequestLogWriteOptions) => void;
1690
- /**
1691
- * Emit one structured request event to `console` so Cloudflare's Workers Logs /
1692
- * Logpush pipeline carries it to external sinks (SIEMs) — PLAN3 §3.3. This does
1693
- * NOT reimplement a transport: it produces a richer, lunora-attributed event and
1694
- * lets CF's existing trace-log pipe ship it. The event mirrors the durable
1695
- * `__lunora_reqlog__` row (function path, shard, user, outcome, duration, tables
1696
- * read/written, cache hit), with `args`, `identity`, AND `error` redacted
1697
- * exactly like the durable write so no raw PII/secret reaches the log pipeline.
2048
+ * Rows are fetched most-recent-first (`bucket_ms DESC`) under the row cap, NOT
2049
+ * `series_key`-ordered: all active series write the same recent minutes, so this
2050
+ * windows every series to a recent slice fairly, instead of handing the
2051
+ * alphabetically-first series its full 1440-bucket history and starving the rest
2052
+ * once the cap is hit. Each series' points are re-sorted ascending below, since a
2053
+ * trend line reads oldest→newest.
1698
2054
  *
1699
- * An `error` outcome goes to `console.error` (surfacing at error level in the
1700
- * trace so a SIEM can alert on it); everything else to `console.log`. The
1701
- * `source: "lunora"` / `type: "request"` envelope lets a consumer filter these
1702
- * events out of the raw Workers-trace firehose. `captureRaw` (dev only) skips
1703
- * redaction, mirroring the durable write. Best-effort by contract — the caller
1704
- * wraps it so a serialization hiccup can never fail the served request.
1705
- */
1706
- declare const emitRequestLogEvent: (entry: AppendRequestLogEntry, options?: RequestLogWriteOptions) => void;
1707
- /**
1708
- * The `ctx.log` event contract (shape + severity union) lives in
1709
- * `shared/log-event.ts` (inlined into each `dist`) so the DO that builds these
1710
- * events and the `@lunora/runtime` sink that consumes them agree by construction.
1711
- * `LogEventInput` is the DO's historical name for the shared `LogEvent`.
2055
+ * `options.sinceMs`, when set, returns only buckets at or after this epoch-ms —
2056
+ * the studio's time-window selector. `options.maxSeries`, mirroring the write
2057
+ * side's tunable, is only used to compute `capped` — it does not affect which
2058
+ * rows are read.
1712
2059
  */
1713
- type LogEventInput = LogEvent;
2060
+ declare const readMetricHistory: (sql: SqlExec, options?: {
2061
+ maxSeries?: number;
2062
+ sinceMs?: number;
2063
+ }) => MetricHistoryResult;
2064
+ /** One row of the `__lunora_metrics_queries` table, as returned by `readQueryMetrics`. */
2065
+ interface QueryStatEntry {
2066
+ /** Total number of times this statement was executed. */
2067
+ execCount: number;
2068
+ /** Normalised SQL text (literals stripped, truncated). */
2069
+ normalizedSql: string;
2070
+ /** Total rows SCANNED across all executions (the billed number, not the result-set size). */
2071
+ rowsRead: number;
2072
+ /** Total rows WRITTEN across all executions. */
2073
+ rowsWritten: number;
2074
+ /** Total wall-clock milliseconds across all executions. */
2075
+ totalDurationMs: number;
2076
+ }
2077
+ /** Index of the first histogram edge at or above `durationMs`; the last index is the overflow bucket. */
2078
+ declare const latencyBucketIndex: (durationMs: number) => number;
2079
+ /** One statement's activity within a chosen time range. */
2080
+ interface QueryInsightEntry {
2081
+ /** Mean milliseconds per execution across the range. */
2082
+ avgDurationMs: number;
2083
+ execCount: number;
2084
+ normalizedSql: string;
2085
+ /** Interpolated 50th percentile latency, in milliseconds. */
2086
+ p50DurationMs: number;
2087
+ /** Interpolated 95th percentile latency, in milliseconds. */
2088
+ p95DurationMs: number;
2089
+ rowsRead: number;
2090
+ rowsWritten: number;
2091
+ totalDurationMs: number;
2092
+ }
2093
+ /** One point on the throughput/latency charts. */
2094
+ interface QueryInsightBucket {
2095
+ /** Mean milliseconds per execution in this window, across all statements. */
2096
+ avgDurationMs: number;
2097
+ /** Bucket start, epoch millis. */
2098
+ bucketMs: number;
2099
+ execCount: number;
2100
+ }
2101
+ /** What `getQueryInsights` returns. */
2102
+ interface QueryInsightsResult {
2103
+ /** Time series across the whole range, all statements combined. */
2104
+ buckets: QueryInsightBucket[];
2105
+ /**
2106
+ * True when the tracked-statement cap has been reached, so the caller can say
2107
+ * "showing N of a capped set" rather than implying totality. Silent
2108
+ * truncation reads as complete coverage when it is not.
2109
+ */
2110
+ capped: boolean;
2111
+ entries: QueryInsightEntry[];
2112
+ /** How many distinct statements the lifetime table is tracking. */
2113
+ trackedStatements: number;
2114
+ }
1714
2115
  /**
1715
- * Split a `ctx.log.<level>(...)` call's raw arguments into a display `message`
1716
- * and optional structured `fields`. The structured form — a message string plus
1717
- * a plain-object fields bag — is matched only for exactly `(string, object)`;
1718
- * every other shape is console-style and rendered whole (so existing
1719
- * `console`-shaped calls are unchanged). Bound `.with(...)` fields merge under
1720
- * the per-call fields (per-call wins); the result is normalized to a fresh bag
1721
- * of JSON-safe primitives, or `undefined` when empty (see `normalizeLogFields`).
2116
+ * Per-statement activity within `rangeMs` of `now`, plus a combined time series.
2117
+ *
2118
+ * Reads the bucket table (not the lifetime one) so the numbers answer "what is
2119
+ * hot right now"; the statement TEXT is joined back from the lifetime table,
2120
+ * which is the only place it is stored.
1722
2121
  */
1723
- declare const parseLogArgs: (args: unknown[], boundFields?: LogFields) => {
1724
- fields?: LogFields;
1725
- message: string;
1726
- };
2122
+ declare const readQueryInsights: (sql: SqlExec, rangeMs: number, now?: number) => QueryInsightsResult;
1727
2123
  /**
1728
- * Emit one application-log event from a `ctx.log.*` call to `console`, tagged
1729
- * `{ source: "lunora", type: "log" }` so the CLI / Vite formatter can pretty-print
1730
- * it in the dev terminal and a Logpush/SIEM consumer can filter it out of the
1731
- * raw Workers-trace firehose.
1732
- *
1733
- * Only the rendered `message` is emitted here, NOT the structured `args` array:
1734
- * the console event rides CF Workers Logs / Logpush to prod, and shipping raw,
1735
- * un-redacted arg objects on a `source: "lunora"` line a SIEM is told to trust
1736
- * would be a surprising PII/secret surface. The raw `args` stay on the in-process
1737
- * `sink.onLog` path (`recordUserLog`), which the operator opts into and controls.
1738
- * `message` already carries the developer's rendered values, exactly like a raw
1739
- * `console.log` line.
1740
- *
1741
- * `error`/`fatal` go to `console.error`, `warn` to `console.warn` (so they
1742
- * surface at the right level in the trace); every other level to `console.log`.
2124
+ * Record one statement's activity. Creates the table on first call. Silently
2125
+ * skips recording when the normalised statement is empty (shouldn't happen
2126
+ * in practice) or when the table is already at the
2127
+ * {@link QUERY_METRICS_MAX_STATEMENTS} cap and the statement is not yet
2128
+ * tracked. See `admitStatement` for how the cap check avoids an unconditional
2129
+ * `COUNT(*)` on every execution.
1743
2130
  *
1744
- * Structured `fields` (plus `traceId`/`spanId` for correlation) ARE emitted here
1745
- * — they are intentional metadata a log pipeline filters on, unlike raw `args`.
1746
- * Unlike `args`, `fields` IS redacted before it rides this console line — a
1747
- * developer can attach anything to a fields bag (`ctx.log.info("charged",
1748
- * { email, cardLast4 })`), and this is the one line that's told to a SIEM as
1749
- * trustworthy, exactly like the request-log `args`/`identity`/`error` columns.
1750
- * `options.captureRaw` (dev only) skips it, mirroring every other redaction
1751
- * point in this module; the sole current caller (`ShardDO.recordUserLog`)
1752
- * doesn't yet thread a dev flag through, so `fields` redacts unconditionally
1753
- * there today — a conservative default, never a correctness gap. A field value
1754
- * that can't be serialised (a circular object) would make `JSON.stringify`
1755
- * throw and drop the whole line, so serialisation falls back to a fields-free
1756
- * line rather than losing the event.
2131
+ * `execCount` (default 1) lets a caller fold several executions of the SAME
2132
+ * statement into one call — `shard-do.ts` does this per dispatch so a
2133
+ * query-in-a-loop handler pays one upsert here instead of one per raw
2134
+ * execution. `durationMs`/`rowsRead`/`rowsWritten` are then the SUM across
2135
+ * `execCount` executions, exactly as `exec_count`/`total_duration_ms` already
2136
+ * accumulate sums across separate calls — folding before calling is
2137
+ * indistinguishable, from this table's point of view, from `execCount`
2138
+ * separate calls with the same totals.
1757
2139
  */
1758
- declare const emitLogEvent: (input: LogEventInput, options?: RequestLogWriteOptions) => void;
2140
+ declare const recordQueryMetric: (sql: SqlExec, rawSql: string, durationMs: number, rowsRead: number, rowsWritten: number, now?: number, execCount?: number) => void;
1759
2141
  /**
1760
- * Read request-log entries newest-first, AND-combining the supplied filters
1761
- * (function-path prefix, exact userId/shardKey/outcome, and a table-touched
1762
- * match against the read OR written table sets), up to `limit` (clamped to
1763
- * [1, 10000]). Each value is a bound parameter, so no filter can inject SQL.
1764
- * Creates the table first so reads on a never-logged shard return `[]` instead
1765
- * of throwing. Mirrors `readAuditLog`/`readCdcChanges`.
2142
+ * Read all tracked statement aggregates, ordered by `total_duration_ms DESC`
2143
+ * (the leaderboard's default). Creates the table first so a read on a
2144
+ * never-called shard returns `[]`.
1766
2145
  */
1767
- declare const readRequestLog: (sql: SqlExec, options?: ReadRequestLogOptions) => RequestLogEntry[];
1768
- declare const readErrorIssues: (sql: SqlExec, options?: ReadIssuesOptions) => ErrorIssue[];
2146
+ declare const readQueryMetrics: (sql: SqlExec) => QueryStatEntry[];
1769
2147
  /**
1770
2148
  * Ordering/visual weight of a security finding — mirrors the studio's insight
1771
2149
  * severities so the Security Advisor and the Performance Advisor (Insights) share
@@ -1780,7 +2158,7 @@ type SecurityFindingLevel = "error" | "info" | "warning";
1780
2158
  *
1781
2159
  * `admin-token-weak`: `LUNORA_ADMIN_TOKEN` is set but short enough to be brute-forceable. (An *unset* token disables admin introspection entirely, so this audit — itself admin-gated — only ever runs with a token present.)
1782
2160
  *
1783
- * `ws-gate-open`: admin HTTP RPCs require the bearer, but `LUNORA_WS_BEARER` is unset so the WebSocket upgrade gate defaults open — live admin subscriptions (Logs, Metrics, …) are reachable without a credential.
2161
+ * `ws-gate-open`: `LUNORA_WS_BEARER` is unset, so the WebSocket upgrade gate defaults open and anyone who can reach the worker can open a socket and run ordinary USER subscriptions (whatever `ctx.auth` / RLS then allows them to read). Admin subscriptions are NOT part of this: they require the socket's `admin` stamp, which the upgrade sets only from `LUNORA_ADMIN_TOKEN` or a minted admin sub-token, so an unset `LUNORA_WS_BEARER` never exposes Logs/Metrics/introspection. Which is why this is a posture finding about the app's own live-query surface, not an admin hole — set the var when subscribers are expected to present a shared credential.
1784
2162
  *
1785
2163
  * `dev-args-unredacted`: the worker reports a development environment, so the durable request log captures raw, un-redacted args and identity (PII). A production deploy mislabeled as dev would persist sensitive payloads.
1786
2164
  *
@@ -1879,12 +2257,25 @@ interface TraceSummary {
1879
2257
  rootName: string;
1880
2258
  shardKey?: string;
1881
2259
  /**
1882
- * Spans ordered by `(offsetMs, depth)`, ready to render as waterfall rows.
1883
- * Start time alone is not enough to order them: spans are recorded on
1884
- * completion and `startTs` has millisecond resolution, so a parent and its
1885
- * child routinely tie. Breaking that tie by depth makes the sequence a valid
1886
- * pre-order traversal of the span tree, so indenting each row by its `depth`
1887
- * yields the nesting without a separate tree walk.
2260
+ * Spans in **pre-order**, ready to render as waterfall rows: every span is
2261
+ * immediately followed by its own subtree, siblings in start order. So
2262
+ * indenting each row by its `depth` yields the real nesting — the row above
2263
+ * a `depth`-`n+1` row is genuinely its parent.
2264
+ *
2265
+ * This is a tree walk, not a sort, because no ordering on `(offsetMs,
2266
+ * depth)` can produce it. Given a parent, its child `a`, `a`'s child `a1`
2267
+ * and `a`'s sibling `b` all at offset 0, that comparator yields
2268
+ * `parent, a, b, a1` — which renders `a1` indented beneath `b`, under a
2269
+ * parent it does not belong to.
2270
+ *
2271
+ * **Why they tie is not millisecond resolution.** On the Workers runtime
2272
+ * `Date.now()` is pinned to the time of the last I/O — a Spectre mitigation,
2273
+ * not a bug — so it does not advance at all across pure computation. Every
2274
+ * duration in this package is `Date.now() - startTs`, which means a span
2275
+ * wrapping CPU-only work reports `0`, and a parent whose child performed no
2276
+ * I/O shares its exact start and end. See `docs/concepts/observability`
2277
+ * ("Span durations on Workers"); the practical consequence is that a `0 ms`
2278
+ * span means "no I/O happened here", not "this was fast".
1888
2279
  */
1889
2280
  spans: TraceSpan[];
1890
2281
  startTs: number;
@@ -1899,20 +2290,34 @@ interface TraceSummary {
1899
2290
  declare class SpanBuffer {
1900
2291
  private readonly buffer;
1901
2292
  private readonly capacity;
2293
+ /**
2294
+ * Buffered span count per trace, so {@link SpanBuffer.hasTrace} — run on
2295
+ * every dispatch, usually a miss against a full ring — is a lookup, not a scan.
2296
+ */
2297
+ private readonly traceCounts;
2298
+ /** How many spans the ring has evicted since it was last cleared. */
2299
+ private droppedCount;
1902
2300
  constructor(capacity?: number);
2301
+ /**
2302
+ * Spans evicted for capacity since the last {@link SpanBuffer.clear}. The
2303
+ * ring silently drops its oldest span once full, which makes a busy instance
2304
+ * look identical to one that recorded exactly `capacity` spans; this count
2305
+ * is the difference between the two.
2306
+ */
2307
+ get dropped(): number;
1903
2308
  /** Number of spans currently buffered. */
1904
2309
  get size(): number;
1905
- /** Drop every buffered span. */
2310
+ /** Drop every buffered span, including the eviction count. */
1906
2311
  clear(): void;
1907
2312
  /** Snapshot of the buffered spans in insertion order. Fresh array per call. */
1908
2313
  entries(): SpanEvent[];
2314
+ /** Whether any buffered span belongs to `traceId`, as it was when pushed. */
2315
+ hasTrace(traceId: string): boolean;
1909
2316
  /**
1910
- * Whether any buffered span belongs to `traceId`. A membership test rather
1911
- * than `entries().some(...)` so the per-dispatch check that decides whether
1912
- * to record a root span doesn't copy the whole ring on every request.
2317
+ * Append a span, evicting the oldest when at capacity. A frozen shallow copy
2318
+ * is stored, never the caller's object (which is shared with the sink and
2319
+ * stays writable), so the span and its `traceCounts` entry cannot diverge.
1913
2320
  */
1914
- hasTrace(traceId: string): boolean;
1915
- /** Append a span, evicting the oldest when at capacity. */
1916
2321
  push(span: SpanEvent): void;
1917
2322
  }
1918
2323
  /** {@link foldTraces} result: the folded waterfalls plus the total distinct traces available before the `limit`. */
@@ -1978,10 +2383,71 @@ declare const findDanglingReferences: (sql: SqlExec, storageColumns: Record<stri
1978
2383
  * worker's trace and any container's beneath it), else freshly minted so a
1979
2384
  * dispatch with no inbound context — a subscription re-run, a server-initiated
1980
2385
  * call — still produces a coherent, self-contained local trace.
2386
+ *
2387
+ * `rayHeader` is the Cloudflare Ray ID the runtime forwarded alongside the
2388
+ * `traceparent` (`x-lunora-ray-id`). It is re-validated here and carried on the
2389
+ * anchor so every span and log line of the dispatch stamps it; absent or
2390
+ * malformed, the anchor simply has none. Informational only — see
2391
+ * {@link parseRayId}.
1981
2392
  */
1982
- declare const resolveTraceAnchor: (traceparent: string | undefined) => {
1983
- rootSpanId: string;
2393
+ declare const resolveTraceAnchor: (traceparent: string | undefined, rayHeader?: null | string) => TraceAnchor & {
1984
2394
  sampled: boolean;
1985
- traceId: string;
1986
2395
  };
1987
- 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 };
2396
+ export { AUTH_METRICS_BUCKETS_TABLE, AUTH_METRICS_BUCKET_MS, AUTH_METRICS_BUCKET_RETENTION, AUTH_METRICS_TABLE, type AiRunBinding, type AppendRequestLogEntry,
2397
+ /**
2398
+ * `@lunora/observability` — host-neutral telemetry storage and read models.
2399
+ *
2400
+ * Logs, traces, metrics, issue grouping and the security-audit view: the data
2401
+ * behind the Studio's observability pages. None of it is Cloudflare-specific —
2402
+ * it reads and writes through the SQL handle the engine hands it, and it lived
2403
+ * inside `@lunora/do` only because that is where the Durable Object it
2404
+ * instruments happens to live.
2405
+ *
2406
+ * The dependency runs `@lunora/do` → here → `@lunora/shard-engine`, never the
2407
+ * reverse, which is what makes this reusable by a second host rather than
2408
+ * merely relocated.
2409
+ *
2410
+ * This barrel is deliberately curated rather than `export *`. A star export
2411
+ * would promote every module internal to permanent public API — the exact
2412
+ * mistake `@lunora/do`'s own barrel documents having made once with the search
2413
+ * core. What is exported here is what a consumer actually needs.
2414
+ */
2415
+ type AuthMetrics,
2416
+ /**
2417
+ * `@lunora/observability` — host-neutral telemetry storage and read models.
2418
+ *
2419
+ * Logs, traces, metrics, issue grouping and the security-audit view: the data
2420
+ * behind the Studio's observability pages. None of it is Cloudflare-specific —
2421
+ * it reads and writes through the SQL handle the engine hands it, and it lived
2422
+ * inside `@lunora/do` only because that is where the Durable Object it
2423
+ * instruments happens to live.
2424
+ *
2425
+ * The dependency runs `@lunora/do` → here → `@lunora/shard-engine`, never the
2426
+ * reverse, which is what makes this reusable by a second host rather than
2427
+ * merely relocated.
2428
+ *
2429
+ * This barrel is deliberately curated rather than `export *`. A star export
2430
+ * would promote every module internal to permanent public API — the exact
2431
+ * mistake `@lunora/do`'s own barrel documents having made once with the search
2432
+ * core. What is exported here is what a consumer actually needs.
2433
+ */
2434
+ type AuthMetricsBucket, type ContextFetch, type ContextLogLevel, type ContextMetrics, type ContextTracer, DEFAULT_EXPLAIN_ISSUE_MODEL, type DanglingReference, type DanglingReferenceResult, type DatabaseInstrumentation, type DatabaseTally, type DatabaseTelemetryDeps, type ErrorIssue, type ExplainIssueArgs, type ExplainIssueDegradedReason, type ExplainIssueGrounding, type ExplainIssueResult, FUNCTION_METRICS_BUCKETS_TABLE, FUNCTION_METRICS_BUCKET_MS, FUNCTION_METRICS_BUCKET_RETENTION, FUNCTION_METRICS_INDEX_TABLE, FUNCTION_METRICS_MAX_PATHS, FUNCTION_METRICS_READ_LIMIT, FUNCTION_METRICS_SCANS_TABLE, FUNCTION_METRICS_TABLE, type FoldedTraces, type FunctionMetricBucket, type FunctionMetricBucketsResult, type FunctionMetricIndexHit, type HostSpanLike, type HostTracingLike, type HostTracingResolver, ISSUE_SEVERITIES, ISSUE_STATE_TABLE, ISSUE_STATUSES, type IndexHit, type IssueSeverity, type IssueState, type IssueStatePatch, type IssueStatus, type IssuesResult, LogBuffer, type LogEntry, type LogEventInput, type LogLevel, MIN_ADMIN_TOKEN_LENGTH, MIN_AUTH_SECRET_LENGTH, MetricBuffer, type MetricEvent, type MetricHistoryOptions, type MetricHistoryPoint, type MetricHistoryResult, type MetricHistorySeries, type MetricKind, type MetricSeries, type MetricsDeps, NO_SENSITIVE_SCOPE, type QueryInsightBucket, type QueryInsightEntry, type QueryInsightsResult, type QueryStatEntry, REQUEST_LOG_TABLE, type ReadIssuesOptions, type ReadRequestLogOptions,
2435
+ /**
2436
+ * `@lunora/observability` — host-neutral telemetry storage and read models.
2437
+ *
2438
+ * Logs, traces, metrics, issue grouping and the security-audit view: the data
2439
+ * behind the Studio's observability pages. None of it is Cloudflare-specific —
2440
+ * it reads and writes through the SQL handle the engine hands it, and it lived
2441
+ * inside `@lunora/do` only because that is where the Durable Object it
2442
+ * instruments happens to live.
2443
+ *
2444
+ * The dependency runs `@lunora/do` → here → `@lunora/shard-engine`, never the
2445
+ * reverse, which is what makes this reusable by a second host rather than
2446
+ * merely relocated.
2447
+ *
2448
+ * This barrel is deliberately curated rather than `export *`. A star export
2449
+ * would promote every module internal to permanent public API — the exact
2450
+ * mistake `@lunora/do`'s own barrel documents having made once with the search
2451
+ * core. What is exported here is what a consumer actually needs.
2452
+ */
2453
+ type RecordAuthEventInput, type RecordFunctionMetricInput, type RequestLogEntry, type RequestLogResult, type RequestLogWriteOptions, type RequestOutcome, SENSITIVE_ARG_MASK, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, type SensitiveScope, SpanBuffer, type SpanCollection, type SpanCollector, type SpanEvent, type SpanEventPoint, type SpanHandle, type OtlpSpanKind as SpanKind, type SpanLink, type SpanOptions, type SqlClientLike, type TallySurface, type TraceAnchor, type TraceSpan, type TraceSummary, type TracedFetchDeps, type TracerDeps, appendRequestLogEntry, applyHostRootSpan, buildSecurityAudit, createDatabaseTally, createMetrics, createSensitiveScope, createSpanCollector, createTracedFetch, createTracer, dispatchRootSpan, emitLogEvent, emitRequestLogEvent, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureRequestLogTable, explainIssue, findDanglingReferences, foldTraces, formatTally, instrumentDatabase, instrumentSqlClient, latencyBucketIndex, maskSensitiveArgs, mergeScanAttribution, parseExplainIssueArgs, parseLogArgs, readAuthMetrics, readErrorIssues, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetricScans, readFunctionMetrics, readFunctionMetricsTotals, readMetricHistory, readQueryInsights, readQueryMetrics, readRequestLog, recordAuthEvent, recordFunctionMetric, recordMetricHistory, recordQueryMetric, redactArgs, redactCredentials, resolveTraceAnchor, sensitiveNames, sensitiveValues, setHostSpanAttributes, upsertIssueState };