@gusto/baerly-storage 0.2.0 → 0.3.0

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 (122) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +29 -0
  3. package/README.md +93 -52
  4. package/dist/API.md +151 -109
  5. package/dist/CHANGELOG.md +144 -0
  6. package/dist/THIRD-PARTY-LICENSES.txt +312 -0
  7. package/dist/{app-config-C0Bbw_Z6.d.ts → app-config-BIzyAKzy.d.ts} +14 -2
  8. package/dist/app-config.d.ts +1 -1
  9. package/dist/auth.d.ts +1 -1
  10. package/dist/auth.js +288 -288
  11. package/dist/auth.js.map +1 -1
  12. package/dist/baerly.js +10 -10
  13. package/dist/baerly.js.map +1 -1
  14. package/dist/bytes-BXdamO3L.js.map +1 -1
  15. package/dist/{client-DYZfoZb9.d.ts → client-BJXF3XJA.d.ts} +10 -10
  16. package/dist/client-react.d.ts +3 -3
  17. package/dist/client-react.js.map +1 -1
  18. package/dist/client.d.ts +3 -3
  19. package/dist/client.js.map +1 -1
  20. package/dist/{cloudflare-CINJPKCW.js → cloudflare-Cn2ibODt.js} +178 -2
  21. package/dist/cloudflare-Cn2ibODt.js.map +1 -0
  22. package/dist/cloudflare.d.ts +4 -4
  23. package/dist/cloudflare.js +10 -11
  24. package/dist/cloudflare.js.map +1 -1
  25. package/dist/{subcommand-DZcHcsYp.js → config-CGyBopy3.js} +643 -439
  26. package/dist/config-CGyBopy3.js.map +1 -0
  27. package/dist/context-DRZ3tZ5l.js.map +1 -1
  28. package/dist/{cost-CQt1YRkA.js → cost-BZ_MDBmn.js} +6 -4
  29. package/dist/cost-BZ_MDBmn.js.map +1 -0
  30. package/dist/{current-json-C-EyJqs0.js → current-json-DsN7FNY1.js} +47 -13
  31. package/dist/current-json-DsN7FNY1.js.map +1 -0
  32. package/dist/{db-BM3y2JQw.d.ts → db-CCT6tDfY.d.ts} +26 -108
  33. package/dist/{deploy-CrAbfgCq.js → deploy-BKKyGlSJ.js} +11 -4
  34. package/dist/deploy-BKKyGlSJ.js.map +1 -0
  35. package/dist/dev-vite.d.ts +5 -5
  36. package/dist/dev-vite.js +5 -5
  37. package/dist/dev-vite.js.map +1 -1
  38. package/dist/dev.d.ts +1 -1
  39. package/dist/dev.js +1 -1
  40. package/dist/{doctor-Db-hzPmE.js → doctor-BVU4GNXN.js} +13 -132
  41. package/dist/doctor-BVU4GNXN.js.map +1 -0
  42. package/dist/{dump-BYA55NLP.js → dump-DPEAKub6.js} +5 -3
  43. package/dist/dump-DPEAKub6.js.map +1 -0
  44. package/dist/errors-DOdL95kK.js.map +1 -1
  45. package/dist/{export-Bhbz90-z.js → export-BcuCLFFe.js} +6 -4
  46. package/dist/{export-Bhbz90-z.js.map → export-BcuCLFFe.js.map} +1 -1
  47. package/dist/{fsck-CPPZWt9p.js → fsck-RXgLOaJG.js} +23 -11
  48. package/dist/fsck-RXgLOaJG.js.map +1 -0
  49. package/dist/{http-Cw8p6y5b.js → http-Bd4byR4n.js} +45 -61
  50. package/dist/http-Bd4byR4n.js.map +1 -0
  51. package/dist/http.d.ts +15 -15
  52. package/dist/http.js +1 -1
  53. package/dist/{index-cUY-36AN.d.ts → index-BDceQQi-.d.ts} +20 -4
  54. package/dist/{index-C3JAH1Yo.d.ts → index-Cmsxx-ZN.d.ts} +9 -9
  55. package/dist/{index-DSvwEUeF.d.ts → index-DW7GT6M2.d.ts} +50 -42
  56. package/dist/{index-DwDTWPSU.d.ts → index-DnBGSeuU.d.ts} +10 -7
  57. package/dist/index.d.ts +6 -6
  58. package/dist/index.js +4 -4
  59. package/dist/{indexes-DAu2AkTW.d.ts → indexes-Cx7uMXm0.d.ts} +2 -2
  60. package/dist/{inspect-Bdbzvi-_.js → inspect-DhI49PSi.js} +16 -8
  61. package/dist/inspect-DhI49PSi.js.map +1 -0
  62. package/dist/{snapshot-SS8USDUF.js → log-tail-DXeDkWEp.js} +154 -83
  63. package/dist/log-tail-DXeDkWEp.js.map +1 -0
  64. package/dist/{maintenance-BRrThz8V.d.ts → maintenance-BkhUr72A.d.ts} +91 -26
  65. package/dist/{maintenance-ClzBC1Vv.js → maintenance-CWBQpZ2y.js} +368 -161
  66. package/dist/maintenance-CWBQpZ2y.js.map +1 -0
  67. package/dist/{maintenance-BvOv6BMM.js → maintenance-C_KSkVjd.js} +204 -82
  68. package/dist/maintenance-C_KSkVjd.js.map +1 -0
  69. package/dist/maintenance.d.ts +3 -2
  70. package/dist/maintenance.js +3 -2
  71. package/dist/node.d.ts +13 -8
  72. package/dist/node.js +1 -1
  73. package/dist/normalize-XWY25_sG.js.map +1 -1
  74. package/dist/{observability-CpOiEN0k.js → observability-BYd-RzEx.js} +63 -55
  75. package/dist/observability-BYd-RzEx.js.map +1 -0
  76. package/dist/observability.d.ts +3 -3
  77. package/dist/observability.js +1 -1
  78. package/dist/{plan-DOTl21vq.js → plan-DIu_B6fy.js} +7 -4
  79. package/dist/plan-DIu_B6fy.js.map +1 -0
  80. package/dist/{query-BmiQy328.js → query-sQNO5vU_.js} +1071 -1099
  81. package/dist/query-sQNO5vU_.js.map +1 -0
  82. package/dist/{rebuild-index-DC_nR6wP.js → rebuild-index-DP4CqSSs.js} +5 -4
  83. package/dist/rebuild-index-DP4CqSSs.js.map +1 -0
  84. package/dist/{restore-C6IcmLeA.js → restore-DpQYef6r.js} +362 -328
  85. package/dist/restore-DpQYef6r.js.map +1 -0
  86. package/dist/shared-secret-BJdSwpgw.js.map +1 -1
  87. package/dist/{src-QQ7jDeL2.js → src-CWpkSbvJ.js} +40 -20
  88. package/dist/src-CWpkSbvJ.js.map +1 -0
  89. package/dist/{src-DU1sCMlr.js → src-D24wDpzR.js} +269 -258
  90. package/dist/src-D24wDpzR.js.map +1 -0
  91. package/dist/{src-zhEAmmF7.js → src-Db4-qVtM.js} +36 -96
  92. package/dist/src-Db4-qVtM.js.map +1 -0
  93. package/dist/subcommand-CP9NY2J4.js +159 -0
  94. package/dist/subcommand-CP9NY2J4.js.map +1 -0
  95. package/dist/{usage-CLjirdD-.js → usage-CTfDq9HR.js} +3 -3
  96. package/dist/{usage-CLjirdD-.js.map → usage-CTfDq9HR.js.map} +1 -1
  97. package/dist/{validate-DCq_0DIn.js → validate-DtljsCh1.js} +51 -51
  98. package/dist/{validate-DCq_0DIn.js.map → validate-DtljsCh1.js.map} +1 -1
  99. package/package.json +40 -29
  100. package/dist/cloudflare-CINJPKCW.js.map +0 -1
  101. package/dist/config-DVfDGyw1.js +0 -278
  102. package/dist/config-DVfDGyw1.js.map +0 -1
  103. package/dist/cost-CQt1YRkA.js.map +0 -1
  104. package/dist/current-json-C-EyJqs0.js.map +0 -1
  105. package/dist/deploy-CrAbfgCq.js.map +0 -1
  106. package/dist/doctor-Db-hzPmE.js.map +0 -1
  107. package/dist/dump-BYA55NLP.js.map +0 -1
  108. package/dist/fsck-CPPZWt9p.js.map +0 -1
  109. package/dist/http-Cw8p6y5b.js.map +0 -1
  110. package/dist/inspect-Bdbzvi-_.js.map +0 -1
  111. package/dist/maintenance-BvOv6BMM.js.map +0 -1
  112. package/dist/maintenance-ClzBC1Vv.js.map +0 -1
  113. package/dist/observability-CpOiEN0k.js.map +0 -1
  114. package/dist/plan-DOTl21vq.js.map +0 -1
  115. package/dist/query-BmiQy328.js.map +0 -1
  116. package/dist/rebuild-index-DC_nR6wP.js.map +0 -1
  117. package/dist/restore-C6IcmLeA.js.map +0 -1
  118. package/dist/snapshot-SS8USDUF.js.map +0 -1
  119. package/dist/src-DU1sCMlr.js.map +0 -1
  120. package/dist/src-QQ7jDeL2.js.map +0 -1
  121. package/dist/src-zhEAmmF7.js.map +0 -1
  122. package/dist/subcommand-DZcHcsYp.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"context-DRZ3tZ5l.js","names":["#counters","#gauges","#histograms"],"sources":["../packages/protocol/src/metrics.ts","../packages/server/src/observability/recorder.ts","../packages/server/src/observability/context.ts"],"sourcesContent":["/**\n * `MetricsRecorder` — internal emission contract for the six\n * load-bearing kernel metrics. Writer / compactor / GC emit through\n * an instance of this interface; in production the instance is the\n * per-request `RequestScopedMetricsRecorder` on the active\n * `ObservabilityContext`, and emissions flow onto the canonical line\n * via `summarize()`. Tests use a local `InMemoryMetricsRecorder` and\n * wrap their workload in `runWithContext` to attach it.\n *\n * Operators do not wire a custom sink against this interface — the\n * operator's view of kernel emissions is the canonical line on\n * stdout (one JSON object per HTTP request).\n *\n * **Naming convention** matches the load-bearing metrics:\n * - `db.write.class_a_ops_per_logical_write` — histogram (p99 alert at 5).\n * Includes one Class A op per index PUT + index DELETE emitted\n * in the commit's fence. Idle-reader cost is unchanged.\n * - `db.r2.put.412_total` — counter (CAS conflict / If-Match-or-None-Match loss)\n * - `db.r2.put.429_total` — counter (R2 prefix-partition rate-limit)\n * - `db.write.index_ops_per_logical_write` — histogram.\n * `K (PUT) + L (DELETE)` per commit. Per-collection label.\n * - `db.manifest.lag_window_depth` — gauge (alert at >100)\n * - `db.gc.entries_swept_per_second` — gauge (livelock indicator when <writes/s)\n * - `db.orphan.candidate_count` — gauge (`gc/pending.json` depth)\n * - `db.compact.entries_folded` — histogram (entries folded per run)\n * - `db.gc.swept_total` — counter (labelled by reason)\n *\n * Names follow `db.<subsystem>.<metric>`, dot-separated, all-lowercase\n * snake_case segments. Labels are flat\n * `Readonly<Record<string, string>>` — no numbers, no nested objects.\n *\n * Metric emissions never throw on the hot path; the default\n * `noopMetricsRecorder` cannot throw.\n */\nexport interface MetricsRecorder {\n /** Monotonically-incrementing event count. */\n counter(name: string, value: number, labels?: Readonly<Record<string, string>>): void;\n /** Point-in-time value. */\n gauge(name: string, value: number, labels?: Readonly<Record<string, string>>): void;\n /** Distribution sample. */\n histogram(name: string, value: number, labels?: Readonly<Record<string, string>>): void;\n}\n\n/**\n * No-op recorder. Safe default when no operator sink is wired —\n * emission sites that read `getCurrentContext()?.recorder` fall\n * back to this outside an active `runWithContext` scope.\n */\nexport const noopMetricsRecorder: MetricsRecorder = {\n counter: (): void => {},\n gauge: (): void => {},\n histogram: (): void => {},\n};\n","/**\n * Per-request `MetricsRecorder` whose primary product is the\n * canonical-line attribute set.\n *\n * `RequestScopedMetricsRecorder` is a deliberately tiny extension to\n * the {@link MetricsRecorder} interface that adds two readers\n * (`snapshot()` for tests / debug, `summarize()` for the canonical\n * log line). Every method just appends a row to a flat array — no\n * sorting, no JSON, no aggregation on the hot path. The work happens\n * once at end-of-request inside `summarize()`.\n *\n * The shape mirrors {@link InMemoryMetricsRecorder} from\n * `../_internal/in-memory-metrics.ts` but adds the per-request product. We do\n * NOT extend that class — composition over inheritance, and the\n * observability layer wants `summarize()` to be the only side-channel.\n */\n\nimport type { MetricsRecorder } from \"@baerly/protocol\";\n\n/** One observation row, kept in insertion order. */\nexport interface ObservationRow {\n readonly name: string;\n readonly value: number;\n readonly labels: Readonly<Record<string, string>>;\n}\n\n/** Result of {@link RequestScopedMetricsRecorder.snapshot}. */\nexport interface MetricsSnapshot {\n readonly counters: readonly ObservationRow[];\n readonly gauges: readonly ObservationRow[];\n readonly histograms: readonly ObservationRow[];\n}\n\n/** Flat per-metric aggregation as consumed by the canonical line. */\nexport type MetricsSummary = Record<string, number>;\n\n/**\n * Implementation. Allocations:\n *\n * - Three arrays at construction time, grown on each emission.\n * - On `summarize()` we materialize one extra `Map` per metric-\n * family (counter / gauge / histogram) plus a copy of each\n * histogram's values for sorting.\n *\n * CPU-ms budget on Workers is tight; we deliberately defer all of\n * that to flush time.\n */\nexport class RequestScopedMetricsRecorder implements MetricsRecorder {\n readonly #counters: ObservationRow[] = [];\n readonly #gauges: ObservationRow[] = [];\n readonly #histograms: ObservationRow[] = [];\n\n counter(name: string, value: number, labels: Readonly<Record<string, string>> = {}): void {\n this.#counters.push({ name, value, labels });\n }\n gauge(name: string, value: number, labels: Readonly<Record<string, string>> = {}): void {\n this.#gauges.push({ name, value, labels });\n }\n histogram(name: string, value: number, labels: Readonly<Record<string, string>> = {}): void {\n this.#histograms.push({ name, value, labels });\n }\n\n /**\n * Read-only view of every observation seen so far. Intended for\n * tests + structured debugging; the canonical-line flusher uses\n * {@link summarize} instead.\n *\n * @internal Not part of the published observability surface; tests\n * import via relative path. Production reads via {@link summarize}.\n */\n snapshot(): MetricsSnapshot {\n return {\n counters: this.#counters.slice(),\n gauges: this.#gauges.slice(),\n histograms: this.#histograms.slice(),\n };\n }\n\n /**\n * Flat aggregation, keyed by metric name with suffixes baked in:\n *\n * - Counter `db.foo.bar` → `db.foo.bar_total` (sum of all observations)\n * - Gauge `db.foo.bar` → `db.foo.bar` (last value seen)\n * - Histogram `db.foo.bar` → `db.foo.bar_count` (number of observations)\n * + `db.foo.bar_sum` (sum of values)\n *\n * Histogram aggregation is a single pass in insertion order — no\n * sort. Returns numbers only — labels are NOT collapsed into keys;\n * if a metric is emitted with different label sets, its\n * observations are aggregated together by `name` alone. The\n * canonical line is per-request anyway; per-label fan-out belongs\n * to the operator's long-term recorder.\n */\n summarize(): MetricsSummary {\n const out: MetricsSummary = {};\n\n // Counters: sum.\n for (const row of this.#counters) {\n // Counter convention: prefer the emitter's name verbatim. If the\n // emitter already namespaced its counter with `_total` (Prometheus\n // convention — see packages/server/src/observability/storage.ts),\n // do not double-append. Otherwise append for canonical-line\n // consumers that key off the `_total` suffix.\n const key = row.name.endsWith(\"_total\") ? row.name : `${row.name}_total`;\n out[key] = (out[key] ?? 0) + row.value;\n }\n\n // Gauges: last write wins per name (observations are in\n // insertion order; iterate forward and overwrite).\n for (const row of this.#gauges) {\n out[row.name] = row.value;\n }\n\n // Histograms: bucket-by-name, then emit `_count` + `_sum`.\n const buckets = new Map<string, { count: number; sum: number }>();\n for (const row of this.#histograms) {\n let agg = buckets.get(row.name);\n if (agg === undefined) {\n agg = { count: 0, sum: 0 };\n buckets.set(row.name, agg);\n }\n agg.count += 1;\n agg.sum += row.value;\n }\n for (const [name, { count, sum }] of buckets) {\n out[`${name}_count`] = count;\n out[`${name}_sum`] = sum;\n }\n\n return out;\n }\n}\n","/**\n * Per-request observability context.\n *\n * One `ObservabilityContext` is created at the entry of each unit-of-\n * work (HTTP request, maintenance tick, GC sweep, rebuild run) and\n * carried through the call tree via {@link runWithContext} /\n * {@link getCurrentContext}, which delegates to a single module-level\n * `AsyncLocalStorage` instance.\n *\n * The context is intentionally tiny: an externally-set\n * {@link request_id}, a high-resolution `started_at`, and a mutable\n * {@link fields} bag used to accumulate canonical-line attributes\n * during the unit's lifecycle.\n *\n * The context shape is `readonly` everywhere it can be — only the\n * contents of `fields` are intended to mutate during a request. The\n * {@link fields} map itself is not `readonly` because callers (the\n * canonical-line emitter, middleware, the collection API once Dispatch\n * 3+ wires it up) need to set entries.\n *\n * The context carries no sampling state — every unit-of-work emits\n * one canonical line unconditionally; there is nothing to gate.\n *\n * ## Time source\n *\n * `started_at` uses `performance.now()` so durations can be\n * computed without worrying about wall-clock skew (NTP step,\n * leap-second smearing). `performance.now()` is part of both Node\n * 18+ and the Workers Runtime; we don't fall back to `Date.now()`.\n *\n * @example\n * ```ts\n * const ctx = createObservabilityContext({});\n * await runWithContext(ctx, async () => {\n * const inner = getCurrentContext();\n * inner?.fields.set(\"collection\", \"tickets\");\n * await doWork();\n * });\n * ```\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n// Type-only import — `maintenance.ts` imports this module's runtime\n// values (`getCurrentContext`), so a value import here would form a\n// runtime cycle. A type-only edge erases at build time, so tsgo /\n// rolldown see no cycle.\nimport type { MaintenanceDispatch } from \"../maintenance.ts\";\nimport { RequestScopedMetricsRecorder } from \"./recorder.ts\";\n\n/** Read-mostly per-request observability state. */\nexport interface ObservabilityContext {\n /** Externally-correlatable request identifier (UUID-ish). */\n readonly request_id: string;\n /** Monotonic `performance.now()` reading captured at construction. */\n readonly started_at: number;\n /**\n * Mutable bag for canonical-line attributes. Callers `obs.fields.set(\"k\", v)`;\n * the canonical-line flusher spreads this onto the emitted properties at\n * end-of-request.\n */\n readonly fields: Map<string, unknown>;\n /**\n * Per-request metrics bag. Lives on the context so adapters can\n * reach it from inside the `Db`'s `MetricsRecorder` callback via\n * `getCurrentContext()?.recorder` — no parallel `AsyncLocalStorage`\n * lookup. The canonical-line flusher reads its `summarize()` at\n * end-of-request and spreads the result onto the emitted line.\n */\n readonly recorder: RequestScopedMetricsRecorder;\n /**\n * Per-request write-tick maintenance dispatch config. Set by the\n * adapter (NOT `Db.create`) so the inherently-per-request\n * `dispatch = ctx.waitUntil` and the env-var-derived caps ride the\n * same scope the kernel write-tick reads from. The {@link Writer}\n * consults `getCurrentContext()?.maintenance` at the post-CAS\n * dispatch point. Absent ⇒ inline dispatch + CF-free-safe caps.\n */\n readonly maintenance?: MaintenanceDispatch;\n}\n\n/**\n * Optional construction inputs. All fields are optional so callers in\n * unit-of-work entry middleware (HTTP router, maintenance scheduler)\n * can pass only what they have. Defaults:\n *\n * - `request_id`: a fresh `crypto.randomUUID()`. Pass an externally-\n * supplied id (`X-Request-Id` header, scheduler-supplied tag) to\n * propagate correlation downstream.\n * - `recorder`: a fresh {@link RequestScopedMetricsRecorder}. Tests can\n * pass an externally-constructed recorder to assert on its\n * `snapshot()` after the unit-of-work completes; production callers\n * should accept the default.\n */\nexport interface ObservabilityContextInit {\n readonly request_id?: string;\n readonly recorder?: RequestScopedMetricsRecorder;\n /** Write-tick maintenance dispatch config. See {@link ObservabilityContext.maintenance}. */\n readonly maintenance?: MaintenanceDispatch;\n}\n\n/**\n * Factory for {@link ObservabilityContext}. We use a factory rather\n * than a class so consumers can structural-type the result and so\n * the `AsyncLocalStorage` slot type stays a plain interface — no\n * surprises around `instanceof` across realms (Workers vs Node).\n */\nexport const createObservabilityContext = (\n init: ObservabilityContextInit = {},\n): ObservabilityContext => ({\n request_id: init.request_id ?? crypto.randomUUID(),\n started_at: performance.now(),\n fields: new Map(),\n recorder: init.recorder ?? new RequestScopedMetricsRecorder(),\n ...(init.maintenance !== undefined && { maintenance: init.maintenance }),\n});\n\n/**\n * Module-level slot. One instance per process — the Workers\n * Runtime's `nodejs_compat` flag wires `node:async_hooks` to a\n * per-request scope, so cross-request bleed is impossible there.\n */\nconst als = new AsyncLocalStorage<ObservabilityContext>();\n\n/**\n * Run `fn` with `ctx` active as the current observability context.\n * Inside `fn` (and any `await`-chained continuation rooted in `fn`),\n * {@link getCurrentContext} returns `ctx`. Outside, it returns the\n * previously-active context (or `undefined`).\n *\n * `runWithContext` is async-safe via `AsyncLocalStorage`; it propagates\n * through `await`, `Promise.all`, `setTimeout`, and `queueMicrotask`.\n *\n * Returns `fn`'s return value verbatim — including its promise\n * identity, so callers can `await` or chain off it without extra\n * indirection.\n */\nexport const runWithContext = <T>(\n ctx: ObservabilityContext,\n fn: () => T | Promise<T>,\n): T | Promise<T> => als.run(ctx, fn);\n\n/** Returns the currently-active context, or `undefined` outside one. */\nexport const getCurrentContext = (): ObservabilityContext | undefined => als.getStore();\n"],"mappings":";;;;;;;AAgDA,MAAa,sBAAuC;CAClD,eAAqB,CAAC;CACtB,aAAmB,CAAC;CACpB,iBAAuB,CAAC;AAC1B;;;;;;;;;;;;;;ACLA,IAAa,+BAAb,MAAqE;CACnE,YAAuC,CAAC;CACxC,UAAqC,CAAC;CACtC,cAAyC,CAAC;CAE1C,QAAQ,MAAc,OAAe,SAA2C,CAAC,GAAS;EACxF,KAAKA,UAAU,KAAK;GAAE;GAAM;GAAO;EAAO,CAAC;CAC7C;CACA,MAAM,MAAc,OAAe,SAA2C,CAAC,GAAS;EACtF,KAAKC,QAAQ,KAAK;GAAE;GAAM;GAAO;EAAO,CAAC;CAC3C;CACA,UAAU,MAAc,OAAe,SAA2C,CAAC,GAAS;EAC1F,KAAKC,YAAY,KAAK;GAAE;GAAM;GAAO;EAAO,CAAC;CAC/C;;;;;;;;;CAUA,WAA4B;EAC1B,OAAO;GACL,UAAU,KAAKF,UAAU,MAAM;GAC/B,QAAQ,KAAKC,QAAQ,MAAM;GAC3B,YAAY,KAAKC,YAAY,MAAM;EACrC;CACF;;;;;;;;;;;;;;;;CAiBA,YAA4B;EAC1B,MAAM,MAAsB,CAAC;EAG7B,KAAK,MAAM,OAAO,KAAKF,WAAW;GAMhC,MAAM,MAAM,IAAI,KAAK,SAAS,QAAQ,IAAI,IAAI,OAAO,GAAG,IAAI,KAAK;GACjE,IAAI,QAAQ,IAAI,QAAQ,KAAK,IAAI;EACnC;EAIA,KAAK,MAAM,OAAO,KAAKC,SACrB,IAAI,IAAI,QAAQ,IAAI;EAItB,MAAM,0BAAU,IAAI,IAA4C;EAChE,KAAK,MAAM,OAAO,KAAKC,aAAa;GAClC,IAAI,MAAM,QAAQ,IAAI,IAAI,IAAI;GAC9B,IAAI,QAAQ,KAAA,GAAW;IACrB,MAAM;KAAE,OAAO;KAAG,KAAK;IAAE;IACzB,QAAQ,IAAI,IAAI,MAAM,GAAG;GAC3B;GACA,IAAI,SAAS;GACb,IAAI,OAAO,IAAI;EACjB;EACA,KAAK,MAAM,CAAC,MAAM,EAAE,OAAO,UAAU,SAAS;GAC5C,IAAI,GAAG,KAAK,WAAW;GACvB,IAAI,GAAG,KAAK,SAAS;EACvB;EAEA,OAAO;CACT;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACzBA,MAAa,8BACX,OAAiC,CAAC,OACR;CAC1B,YAAY,KAAK,cAAc,OAAO,WAAW;CACjD,YAAY,YAAY,IAAI;CAC5B,wBAAQ,IAAI,IAAI;CAChB,UAAU,KAAK,YAAY,IAAI,6BAA6B;CAC5D,GAAI,KAAK,gBAAgB,KAAA,KAAa,EAAE,aAAa,KAAK,YAAY;AACxE;;;;;;AAOA,MAAM,MAAM,IAAI,kBAAwC;;;;;;;;;;;;;;AAexD,MAAa,kBACX,KACA,OACmB,IAAI,IAAI,KAAK,EAAE;;AAGpC,MAAa,0BAA4D,IAAI,SAAS"}
1
+ {"version":3,"file":"context-DRZ3tZ5l.js","names":["#counters","#gauges","#histograms"],"sources":["../packages/protocol/src/metrics.ts","../packages/server/src/observability/recorder.ts","../packages/server/src/observability/context.ts"],"sourcesContent":["/**\n * `MetricsRecorder` — internal emission contract for the six\n * load-bearing kernel metrics. Writer / compactor / GC emit through\n * an instance of this interface; in production the instance is the\n * per-request `RequestScopedMetricsRecorder` on the active\n * `ObservabilityContext`, and emissions flow onto the canonical line\n * via `summarize()`. Tests use a local `InMemoryMetricsRecorder` and\n * wrap their workload in `runWithContext` to attach it.\n *\n * Operators do not wire a custom sink against this interface — the\n * operator's view of kernel emissions is the canonical line on\n * stdout (one JSON object per HTTP request).\n *\n * **Naming convention** matches the load-bearing metrics:\n * - `db.write.class_a_ops_per_logical_write` — histogram (recommend p99 alert ~5; not gated).\n * Includes one Class A op per index PUT + index DELETE emitted\n * in the commit's fence. Idle-reader cost is unchanged.\n * - `db.r2.put.412_total` — counter (CAS conflict / If-Match-or-None-Match loss)\n * - `db.r2.put.429_total` — counter (R2 prefix-partition rate-limit)\n * - `db.write.index_ops_per_logical_write` — histogram.\n * `K (PUT) + L (DELETE)` per commit. Per-collection label.\n * - `db.manifest.lag_window_depth` — gauge (alert at >100)\n * - `db.gc.entries_swept_per_second` — gauge (livelock indicator when <writes/s)\n * - `db.orphan.candidate_count` — gauge (`gc/pending.json` depth)\n * - `db.compact.entries_folded` — histogram (entries folded per run)\n * - `db.gc.swept_total` — counter (labelled by reason)\n *\n * Names follow `db.<subsystem>.<metric>`, dot-separated, all-lowercase\n * snake_case segments. Labels are flat\n * `Readonly<Record<string, string>>` — no numbers, no nested objects.\n *\n * Metric emissions never throw on the hot path; the default\n * `noopMetricsRecorder` cannot throw.\n */\nexport interface MetricsRecorder {\n /** Monotonically-incrementing event count. */\n counter(name: string, value: number, labels?: Readonly<Record<string, string>>): void;\n /** Point-in-time value. */\n gauge(name: string, value: number, labels?: Readonly<Record<string, string>>): void;\n /** Distribution sample. */\n histogram(name: string, value: number, labels?: Readonly<Record<string, string>>): void;\n}\n\n/**\n * No-op recorder. Safe default when no operator sink is wired —\n * emission sites that read `getCurrentContext()?.recorder` fall\n * back to this outside an active `runWithContext` scope.\n */\nexport const noopMetricsRecorder: MetricsRecorder = {\n counter: (): void => {},\n gauge: (): void => {},\n histogram: (): void => {},\n};\n","/**\n * Per-request `MetricsRecorder` whose primary product is the\n * canonical-line attribute set.\n *\n * `RequestScopedMetricsRecorder` is a deliberately tiny extension to\n * the {@link MetricsRecorder} interface that adds two readers\n * (`snapshot()` for tests / debug, `summarize()` for the canonical\n * log line). Every method just appends a row to a flat array — no\n * sorting, no JSON, no aggregation on the hot path. The work happens\n * once at end-of-request inside `summarize()`.\n *\n * The shape mirrors {@link InMemoryMetricsRecorder} from\n * `../_internal/in-memory-metrics.ts` but adds the per-request product. We do\n * NOT extend that class — composition over inheritance, and the\n * observability layer wants `summarize()` to be the only side-channel.\n */\n\nimport type { MetricsRecorder } from \"@baerly/protocol\";\n\n/** One observation row, kept in insertion order. */\nexport interface ObservationRow {\n readonly name: string;\n readonly value: number;\n readonly labels: Readonly<Record<string, string>>;\n}\n\n/** Result of {@link RequestScopedMetricsRecorder.snapshot}. */\nexport interface MetricsSnapshot {\n readonly counters: readonly ObservationRow[];\n readonly gauges: readonly ObservationRow[];\n readonly histograms: readonly ObservationRow[];\n}\n\n/** Flat per-metric aggregation as consumed by the canonical line. */\nexport type MetricsSummary = Record<string, number>;\n\n/**\n * Implementation. Allocations:\n *\n * - Three arrays at construction time, grown on each emission.\n * - On `summarize()` we materialize one extra `Map` per metric-\n * family (counter / gauge / histogram) plus a copy of each\n * histogram's values for sorting.\n *\n * CPU-ms budget on Workers is tight; we deliberately defer all of\n * that to flush time.\n */\nexport class RequestScopedMetricsRecorder implements MetricsRecorder {\n readonly #counters: ObservationRow[] = [];\n readonly #gauges: ObservationRow[] = [];\n readonly #histograms: ObservationRow[] = [];\n\n counter(name: string, value: number, labels: Readonly<Record<string, string>> = {}): void {\n this.#counters.push({ name, value, labels });\n }\n gauge(name: string, value: number, labels: Readonly<Record<string, string>> = {}): void {\n this.#gauges.push({ name, value, labels });\n }\n histogram(name: string, value: number, labels: Readonly<Record<string, string>> = {}): void {\n this.#histograms.push({ name, value, labels });\n }\n\n /**\n * Read-only view of every observation seen so far. Intended for\n * tests + structured debugging; the canonical-line flusher uses\n * {@link summarize} instead.\n *\n * @internal Not part of the published observability surface; tests\n * import via relative path. Production reads via {@link summarize}.\n */\n snapshot(): MetricsSnapshot {\n return {\n counters: this.#counters.slice(),\n gauges: this.#gauges.slice(),\n histograms: this.#histograms.slice(),\n };\n }\n\n /**\n * Flat aggregation, keyed by metric name with suffixes baked in:\n *\n * - Counter `db.foo.bar` → `db.foo.bar_total` (sum of all observations)\n * - Gauge `db.foo.bar` → `db.foo.bar` (last value seen)\n * - Histogram `db.foo.bar` → `db.foo.bar_count` (number of observations)\n * + `db.foo.bar_sum` (sum of values)\n *\n * Histogram aggregation is a single pass in insertion order — no\n * sort. Returns numbers only — labels are NOT collapsed into keys;\n * if a metric is emitted with different label sets, its\n * observations are aggregated together by `name` alone. The\n * canonical line is per-request anyway; per-label fan-out belongs\n * to the operator's long-term recorder.\n */\n summarize(): MetricsSummary {\n const out: MetricsSummary = {};\n\n // Counters: sum.\n for (const row of this.#counters) {\n // Counter convention: prefer the emitter's name verbatim. If the\n // emitter already namespaced its counter with `_total` (Prometheus\n // convention — see packages/server/src/observability/storage.ts),\n // do not double-append. Otherwise append for canonical-line\n // consumers that key off the `_total` suffix.\n const key = row.name.endsWith(\"_total\") ? row.name : `${row.name}_total`;\n out[key] = (out[key] ?? 0) + row.value;\n }\n\n // Gauges: last write wins per name (observations are in\n // insertion order; iterate forward and overwrite).\n for (const row of this.#gauges) {\n out[row.name] = row.value;\n }\n\n // Histograms: bucket-by-name, then emit `_count` + `_sum`.\n const buckets = new Map<string, { count: number; sum: number }>();\n for (const row of this.#histograms) {\n let agg = buckets.get(row.name);\n if (agg === undefined) {\n agg = { count: 0, sum: 0 };\n buckets.set(row.name, agg);\n }\n agg.count += 1;\n agg.sum += row.value;\n }\n for (const [name, { count, sum }] of buckets) {\n out[`${name}_count`] = count;\n out[`${name}_sum`] = sum;\n }\n\n return out;\n }\n}\n","/**\n * Per-request observability context.\n *\n * One `ObservabilityContext` is created at the entry of each unit-of-\n * work (HTTP request, maintenance tick, GC sweep, rebuild run) and\n * carried through the call tree via {@link runWithContext} /\n * {@link getCurrentContext}, which delegates to a single module-level\n * `AsyncLocalStorage` instance.\n *\n * The context is intentionally tiny: an externally-set\n * {@link request_id}, a high-resolution `started_at`, and a mutable\n * {@link fields} bag used to accumulate canonical-line attributes\n * during the unit's lifecycle.\n *\n * The context shape is `readonly` everywhere it can be — only the\n * contents of `fields` are intended to mutate during a request. The\n * {@link fields} map itself is not `readonly` because callers (the\n * canonical-line emitter, middleware, the collection API once Dispatch\n * 3+ wires it up) need to set entries.\n *\n * The context carries no sampling state — every unit-of-work emits\n * one canonical line unconditionally; there is nothing to gate.\n *\n * ## Time source\n *\n * `started_at` uses `performance.now()` so durations can be\n * computed without worrying about wall-clock skew (NTP step,\n * leap-second smearing). `performance.now()` is part of both Node\n * 18+ and the Workers Runtime; we don't fall back to `Date.now()`.\n *\n * @example\n * ```ts\n * const ctx = createObservabilityContext({});\n * await runWithContext(ctx, async () => {\n * const inner = getCurrentContext();\n * inner?.fields.set(\"collection\", \"tickets\");\n * await doWork();\n * });\n * ```\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n// Type-only import — `maintenance.ts` imports this module's runtime\n// values (`getCurrentContext`), so a value import here would form a\n// runtime cycle. A type-only edge erases at build time, so tsgo /\n// rolldown see no cycle.\nimport type { MaintenanceDispatch } from \"../maintenance.ts\";\nimport { RequestScopedMetricsRecorder } from \"./recorder.ts\";\n\n/** Read-mostly per-request observability state. */\nexport interface ObservabilityContext {\n /** Externally-correlatable request identifier (UUID-ish). */\n readonly request_id: string;\n /** Monotonic `performance.now()` reading captured at construction. */\n readonly started_at: number;\n /**\n * Mutable bag for canonical-line attributes. Callers `obs.fields.set(\"k\", v)`;\n * the canonical-line flusher spreads this onto the emitted properties at\n * end-of-request.\n */\n readonly fields: Map<string, unknown>;\n /**\n * Per-request metrics bag. Lives on the context so adapters can\n * reach it from inside the `Db`'s `MetricsRecorder` callback via\n * `getCurrentContext()?.recorder` — no parallel `AsyncLocalStorage`\n * lookup. The canonical-line flusher reads its `summarize()` at\n * end-of-request and spreads the result onto the emitted line.\n */\n readonly recorder: RequestScopedMetricsRecorder;\n /**\n * Per-request write-tick maintenance dispatch config. Set by the\n * adapter (NOT `Db.create`) so the inherently-per-request\n * `dispatch = ctx.waitUntil` and the env-var-derived caps ride the\n * same scope the kernel write-tick reads from. The {@link Writer}\n * consults `getCurrentContext()?.maintenance` at the post-commit\n * dispatch point. Absent ⇒ inline dispatch + CF-free-safe caps.\n */\n readonly maintenance?: MaintenanceDispatch;\n}\n\n/**\n * Optional construction inputs. All fields are optional so callers in\n * unit-of-work entry middleware (HTTP router, maintenance scheduler)\n * can pass only what they have. Defaults:\n *\n * - `request_id`: a fresh `crypto.randomUUID()`. Pass an externally-\n * supplied id (`X-Request-Id` header, scheduler-supplied tag) to\n * propagate correlation downstream.\n * - `recorder`: a fresh {@link RequestScopedMetricsRecorder}. Tests can\n * pass an externally-constructed recorder to assert on its\n * `snapshot()` after the unit-of-work completes; production callers\n * should accept the default.\n */\nexport interface ObservabilityContextInit {\n readonly request_id?: string;\n readonly recorder?: RequestScopedMetricsRecorder;\n /** Write-tick maintenance dispatch config. See {@link ObservabilityContext.maintenance}. */\n readonly maintenance?: MaintenanceDispatch;\n}\n\n/**\n * Factory for {@link ObservabilityContext}. We use a factory rather\n * than a class so consumers can structural-type the result and so\n * the `AsyncLocalStorage` slot type stays a plain interface — no\n * surprises around `instanceof` across realms (Workers vs Node).\n */\nexport const createObservabilityContext = (\n init: ObservabilityContextInit = {},\n): ObservabilityContext => ({\n request_id: init.request_id ?? crypto.randomUUID(),\n started_at: performance.now(),\n fields: new Map(),\n recorder: init.recorder ?? new RequestScopedMetricsRecorder(),\n ...(init.maintenance !== undefined && { maintenance: init.maintenance }),\n});\n\n/**\n * Module-level slot. One instance per process — the Workers\n * Runtime's `nodejs_compat` flag wires `node:async_hooks` to a\n * per-request scope, so cross-request bleed is impossible there.\n */\nconst als = new AsyncLocalStorage<ObservabilityContext>();\n\n/**\n * Run `fn` with `ctx` active as the current observability context.\n * Inside `fn` (and any `await`-chained continuation rooted in `fn`),\n * {@link getCurrentContext} returns `ctx`. Outside, it returns the\n * previously-active context (or `undefined`).\n *\n * `runWithContext` is async-safe via `AsyncLocalStorage`; it propagates\n * through `await`, `Promise.all`, `setTimeout`, and `queueMicrotask`.\n *\n * Returns `fn`'s return value verbatim — including its promise\n * identity, so callers can `await` or chain off it without extra\n * indirection.\n */\nexport const runWithContext = <T>(\n ctx: ObservabilityContext,\n fn: () => T | Promise<T>,\n): T | Promise<T> => als.run(ctx, fn);\n\n/** Returns the currently-active context, or `undefined` outside one. */\nexport const getCurrentContext = (): ObservabilityContext | undefined => als.getStore();\n"],"mappings":";;;;;;;AAgDA,MAAa,sBAAuC;CAClD,eAAqB,CAAC;CACtB,aAAmB,CAAC;CACpB,iBAAuB,CAAC;AAC1B;;;;;;;;;;;;;;ACLA,IAAa,+BAAb,MAAqE;CACnE,YAAuC,CAAC;CACxC,UAAqC,CAAC;CACtC,cAAyC,CAAC;CAE1C,QAAQ,MAAc,OAAe,SAA2C,CAAC,GAAS;EACxF,KAAKA,UAAU,KAAK;GAAE;GAAM;GAAO;EAAO,CAAC;CAC7C;CACA,MAAM,MAAc,OAAe,SAA2C,CAAC,GAAS;EACtF,KAAKC,QAAQ,KAAK;GAAE;GAAM;GAAO;EAAO,CAAC;CAC3C;CACA,UAAU,MAAc,OAAe,SAA2C,CAAC,GAAS;EAC1F,KAAKC,YAAY,KAAK;GAAE;GAAM;GAAO;EAAO,CAAC;CAC/C;;;;;;;;;CAUA,WAA4B;EAC1B,OAAO;GACL,UAAU,KAAKF,UAAU,MAAM;GAC/B,QAAQ,KAAKC,QAAQ,MAAM;GAC3B,YAAY,KAAKC,YAAY,MAAM;EACrC;CACF;;;;;;;;;;;;;;;;CAi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yBopy3.js";
2
2
  import { i as isJsonMode, o as BaerlyError, r as emitSuccess } from "./baerly.js";
3
- import { estimateWritesPerMin } from "./usage-CLjirdD-.js";
3
+ import { n as defineBaerlySubcommand, t as assertCollectionArg } from "./subcommand-CP9NY2J4.js";
4
+ import { estimateWritesPerMin } from "./usage-CTfDq9HR.js";
4
5
  //#region src/cost/provider.ts
5
6
  const detectProvider = (args) => {
6
7
  if (args.override !== void 0) return args.override;
@@ -70,7 +71,7 @@ const pricingFor = (provider) => {
70
71
  */
71
72
  const GRADUATION_CLASS_A_PER_MONTH = 5e7;
72
73
  /** Minutes per month × write-amp = Class A ops/month per write/min. */
73
- const OPS_PER_WPM_PER_MONTH = 1440 * 30 * 3;
74
+ const OPS_PER_WPM_PER_MONTH = 1440 * 30 * 2;
74
75
  /**
75
76
  * Project a `writesPerMin` rate (typically from
76
77
  * `estimateWritesPerMin`) into a monthly cost trajectory.
@@ -175,6 +176,7 @@ const bundle = defineBaerlySubcommand({
175
176
  app: args.app,
176
177
  tenant: args.tenant
177
178
  });
179
+ assertCollectionArg(args.collection, "baerly cost");
178
180
  const override = typeof args.provider === "string" && args.provider.length > 0 ? args.provider : void 0;
179
181
  const provider = detectProvider({
180
182
  bucketUri: args.bucket,
@@ -199,4 +201,4 @@ bundle.run;
199
201
  //#endregion
200
202
  export { cost };
201
203
 
202
- //# sourceMappingURL=cost-CQt1YRkA.js.map
204
+ //# sourceMappingURL=cost-BZ_MDBmn.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cost-BZ_MDBmn.js","names":[],"sources":["../packages/cli/src/cost/provider.ts","../packages/cli/src/cost/project.ts","../packages/cli/src/cost.ts"],"sourcesContent":["/**\n * Provider sniffer: maps a bucket URI + optional S3 endpoint into a\n * pricing tag, and resolves that tag into a `ProviderPricing`\n * record. Pure — zero I/O.\n *\n * Detection rules (first match wins):\n * - `file://*` → \"dev\"\n * - `memory://*` → \"dev\"\n * - `s3://*` + endpoint matching `*.r2.cloudflarestorage.com` → \"r2\"\n * - `s3://*` + endpoint matching `*.amazonaws.com` → \"aws-s3\"\n * - `s3://*` + no endpoint → \"aws-s3\"\n * - everything else (Minio, Backblaze, on-prem, unknown s3 endpoint) → \"self-hosted\"\n *\n * `override` skips detection entirely — used by the\n * `baerly inspect --provider=...` CLI flag when auto-detection picks\n * wrong (e.g., a self-hosted S3 gateway in front of R2).\n */\n\nimport type { ProviderPricing } from \"./project.ts\";\n\nexport type ProviderTag = ProviderPricing[\"provider\"];\n\nexport interface DetectArgs {\n /** Raw bucket URI as passed on the CLI (s3://, file://, memory://). */\n readonly bucketUri: string;\n /** Effective S3 endpoint at parse time (typically `process.env[\"BAERLY_S3_ENDPOINT\"]`). */\n readonly s3Endpoint?: string;\n /** When set, skip detection and return this tag. */\n readonly override?: ProviderTag;\n}\n\nexport const detectProvider = (args: DetectArgs): ProviderTag => {\n if (args.override !== undefined) {\n return args.override;\n }\n if (args.bucketUri.startsWith(\"file://\")) {\n return \"dev\";\n }\n if (args.bucketUri.startsWith(\"memory://\")) {\n return \"dev\";\n }\n if (!args.bucketUri.startsWith(\"s3://\")) {\n return \"self-hosted\";\n }\n // s3:// branch — look at the endpoint.\n const endpoint = args.s3Endpoint ?? \"\";\n if (endpoint === \"\") {\n return \"aws-s3\";\n } // default AWS\n if (/\\.r2\\.cloudflarestorage\\.com(:\\d+)?\\/?$/i.test(endpoint)) {\n return \"r2\";\n }\n if (/\\.amazonaws\\.com(:\\d+)?\\/?$/i.test(endpoint)) {\n return \"aws-s3\";\n }\n return \"self-hosted\";\n};\n\n/**\n * R2 price table.\n * Source: <https://developers.cloudflare.com/r2/pricing/> (review date 2026-05-17).\n * Change-control: pair every edit with a `docs/about/pricing-log.md` entry.\n */\nconst R2_PRICING: ProviderPricing = {\n provider: \"r2\",\n freeClassAPerMonth: 1_000_000,\n usdPerMillionClassA: 4.5,\n freeStorageGb: 10,\n usdPerGbMonth: 0.015,\n};\n\n/**\n * AWS S3 (Standard) price table.\n * Source: <https://aws.amazon.com/s3/pricing/> (review date 2026-05-17).\n * The 12-month new-account free tier is intentionally excluded\n * (most operators are past it; reporting $0 to them would lie).\n */\nconst AWS_S3_PRICING: ProviderPricing = {\n provider: \"aws-s3\",\n freeClassAPerMonth: 0,\n usdPerMillionClassA: 5,\n freeStorageGb: 0,\n usdPerGbMonth: 0.023,\n};\n\nconst SELF_HOSTED_PRICING: ProviderPricing = {\n provider: \"self-hosted\",\n freeClassAPerMonth: 0,\n usdPerMillionClassA: Number.NaN,\n freeStorageGb: 0,\n usdPerGbMonth: Number.NaN,\n};\n\nconst DEV_PRICING: ProviderPricing = {\n provider: \"dev\",\n freeClassAPerMonth: 0,\n usdPerMillionClassA: Number.NaN,\n freeStorageGb: 0,\n usdPerGbMonth: Number.NaN,\n};\n\nexport const pricingFor = (provider: ProviderTag): ProviderPricing => {\n switch (provider) {\n case \"r2\": {\n return R2_PRICING;\n }\n case \"aws-s3\": {\n return AWS_S3_PRICING;\n }\n case \"self-hosted\": {\n return SELF_HOSTED_PRICING;\n }\n case \"dev\": {\n return DEV_PRICING;\n }\n }\n};\n","/**\n * Pure projection math for the `baerly inspect` cost-trajectory\n * footer. Zero I/O. Price tables live as top-level constants; every\n * change MUST be paired with a `docs/about/pricing-log.md` entry.\n *\n * Three rules:\n * 1. `classAPerMonth = writesPerMin × 60 × 24 × 30 × 3`. The `× 3`\n * is the protocol's enforced write-amp ceiling\n * (`docs/about/cost-model.md:43-44`); snapshot writes\n * amortize and are excluded from the headline.\n * 2. `projectedUsdPerMonth = 0` exactly when both `classAPerMonth\n * ≤ pricing.freeClassAPerMonth` AND `storedBytes ≤\n * pricing.freeStorageGb × 1GB`. Say `$0`, not `$0.00`. `null`\n * for self-hosted/dev (no $ model).\n * 3. Returns `null` when `writesPerMin` is non-finite (no-data case\n * from `estimateWritesPerMin`); inspect renders no footer.\n */\n\n/** R2 / AWS S3 / self-hosted / dev price table. */\nexport interface ProviderPricing {\n readonly provider: \"r2\" | \"aws-s3\" | \"self-hosted\" | \"dev\";\n /** Free-tier Class A ops per month; 0 if no free tier. */\n readonly freeClassAPerMonth: number;\n /** $/1M Class A above free tier. NaN for \"self-hosted\" / \"dev\". */\n readonly usdPerMillionClassA: number;\n /** Free-tier stored GB; 0 if no free tier. */\n readonly freeStorageGb: number;\n /** $/GB-month above free tier. NaN for \"self-hosted\" / \"dev\". */\n readonly usdPerGbMonth: number;\n}\n\n/**\n * Graduation triggers — sustained for 7 days, any one of these\n * means the workload has outgrown Baerly's positioning.\n *\n * Source: `docs/about/cost-model.md:159-163`.\n */\nexport const GRADUATION_CLASS_A_PER_MONTH = 50_000_000;\n// GRADUATION_WRITE_AMP = 6 — sustained write-amp at this level\n// suggests the workload is too bursty for the M-size positioning.\n// Not yet wired into project(); kept for the storedBytes follow-up.\n// GRADUATION_STORED_BYTES = 5 * 1024 * 1024 * 1024 — storage graduation\n// trigger (~5 GB). Not yet wired; deferred alongside write-amp gating.\n\n/** What the inspect footer renders from. */\nexport interface Trajectory {\n readonly writesPerMin: number;\n readonly classAPerMonth: number;\n /** Percent of provider's free-tier Class A budget. `null` when the provider has no free tier (aws-s3) or no $ model (self-hosted/dev). */\n readonly percentOfFreeTier: number | null;\n /** Percent of the 50M/mo graduation trigger. Always a finite number. */\n readonly percentOfGraduation: number;\n /** Projected USD/month. `0` when fully inside the free tier. `null` when the provider has no $ model (self-hosted/dev). */\n readonly projectedUsdPerMonth: number | null;\n readonly withinFreeTier: boolean;\n readonly provider: ProviderPricing[\"provider\"];\n}\n\n/**\n * Protocol write-amp ceiling: every logical write produces exactly\n * 2 Class A ops (PUT content + the committing `log/<seq>` create).\n * There is no `current.json` CAS on the commit path — the winning\n * log create IS the commit. Source: `docs/about/cost-model.md:43-44`.\n */\nconst PROTOCOL_WRITE_AMP = 2;\n\n/** Minutes per month × write-amp = Class A ops/month per write/min. */\nconst OPS_PER_WPM_PER_MONTH = 60 * 24 * 30 * PROTOCOL_WRITE_AMP;\n\n/**\n * Project a `writesPerMin` rate (typically from\n * `estimateWritesPerMin`) into a monthly cost trajectory.\n *\n * Returns `null` when `writesPerMin` is non-finite. The caller\n * (inspect) renders no footer in that case.\n */\nexport const project = (\n writesPerMin: number,\n storedBytes: number,\n pricing: ProviderPricing,\n): Trajectory | null => {\n if (!Number.isFinite(writesPerMin)) {\n return null;\n }\n\n const classAPerMonth = writesPerMin * OPS_PER_WPM_PER_MONTH;\n\n const percentOfGraduation = (classAPerMonth / GRADUATION_CLASS_A_PER_MONTH) * 100;\n\n const percentOfFreeTier =\n pricing.freeClassAPerMonth > 0 ? (classAPerMonth / pricing.freeClassAPerMonth) * 100 : null;\n\n const storedGb = storedBytes / (1024 * 1024 * 1024);\n const withinFreeTier =\n pricing.freeClassAPerMonth > 0 &&\n classAPerMonth <= pricing.freeClassAPerMonth &&\n storedGb <= pricing.freeStorageGb;\n\n let projectedUsdPerMonth: number | null;\n if (Number.isNaN(pricing.usdPerMillionClassA)) {\n projectedUsdPerMonth = null;\n } else if (withinFreeTier) {\n projectedUsdPerMonth = 0;\n } else {\n const classAOverage = Math.max(0, classAPerMonth - pricing.freeClassAPerMonth);\n const storageOverage = Math.max(0, storedGb - pricing.freeStorageGb);\n projectedUsdPerMonth =\n (classAOverage / 1_000_000) * pricing.usdPerMillionClassA +\n storageOverage * pricing.usdPerGbMonth;\n }\n\n return {\n writesPerMin,\n classAPerMonth,\n percentOfFreeTier,\n percentOfGraduation,\n projectedUsdPerMonth,\n withinFreeTier,\n provider: pricing.provider,\n };\n};\n","/**\n * `baerly cost` — projected cost trajectory for one collection.\n *\n * Sniffs the writes/min rate over the trailing log sample for one\n * collection and projects it into a free-tier-aware monthly Class A\n * + storage cost projection vs. the M-size graduation trigger\n * (50M Class A/mo). Read-only; never mutates anything.\n *\n * Args:\n * --bucket Required. Bucket URI.\n * --app Required (or via baerly.config.ts).\n * --tenant Required (or via baerly.config.ts).\n * --collection Required. Collection name.\n * --provider Optional. r2 | aws-s3 | self-hosted | dev. Overrides\n * the auto-detected provider (bucket URI +\n * BAERLY_S3_ENDPOINT).\n * --json JSON envelope.\n *\n * Cost shape:\n * 1 LIST log/ prefix\n * + up to 120 GETs for trailing log entries (`SAMPLE_SIZE`)\n *\n * Exit codes:\n * 0 — projection rendered.\n * 1 — InvalidConfig (bad bucket URI, missing args, unknown flag,\n * insufficient log entries to estimate, dev backend).\n * 2 — Storage / Network error.\n * 3 — Protocol invariant (Conflict / Internal / InvalidResponse).\n */\n\nimport { type ArgsDef } from \"citty\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { parseBucketUri } from \"./bucket-uri.ts\";\nimport { emitSuccess, isJsonMode } from \"./output.ts\";\nimport { detectProvider, pricingFor, type ProviderTag } from \"./cost/provider.ts\";\nimport { project, type Trajectory } from \"./cost/project.ts\";\nimport { estimateWritesPerMin } from \"./admin/usage.ts\";\nimport { assertCollectionArg, defineBaerlySubcommand } from \"./subcommand.ts\";\n\nconst COST_ARGS = {\n bucket: {\n type: \"string\",\n required: true,\n description: \"Bucket URI (s3://<bucket>[/<prefix>], file:///<abs>, memory://<bucket>)\",\n valueHint: \"bucket-uri\",\n },\n app: {\n type: \"string\",\n required: false,\n description: \"Application name segment (defaults to baerly.config.ts).\",\n valueHint: \"app\",\n },\n tenant: {\n type: \"string\",\n required: false,\n description: \"Tenant name segment (defaults to baerly.config.ts).\",\n valueHint: \"tenant\",\n },\n collection: {\n type: \"string\",\n required: true,\n description: \"Collection name.\",\n valueHint: \"name\",\n },\n provider: {\n type: \"string\",\n required: false,\n description:\n \"Override pricing provider (r2|aws-s3|self-hosted|dev). Auto-detected from bucket URI + BAERLY_S3_ENDPOINT.\",\n valueHint: \"r2|aws-s3|self-hosted|dev\",\n },\n json: {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n },\n} as const satisfies ArgsDef;\n\n/** Compact \"1.5M\" / \"22k\" / \"842\" rendering for Class A op counts. */\nconst formatOps = (n: number): string => {\n if (n >= 1_000_000) {\n return `${(n / 1_000_000).toFixed(1)}M`;\n }\n if (n >= 1_000) {\n return `${(n / 1_000).toFixed(0)}k`;\n }\n return n.toFixed(0);\n};\n\n/** Two-line trajectory block. Three output states per design spec §4.2. */\nconst renderTrajectory = (t: Trajectory): string => {\n const wpm = t.writesPerMin.toFixed(t.writesPerMin < 10 ? 1 : 0);\n const classA = formatOps(t.classAPerMonth);\n // State 2: ops-only — provider known but no $ model. Today only\n // self-hosted reaches this (dev is filtered out upstream).\n if (t.projectedUsdPerMonth === null) {\n return [\n ` trajectory: ~${wpm} writes/min → ~${classA} Class A/mo`,\n ` ${t.percentOfGraduation.toFixed(2)}% of 50M/mo graduation trigger. Self-hosted — bill model not modelled.`,\n ].join(\"\\n\");\n }\n // Only \"r2\" can reach withinFreeTier===true (aws-s3 has freeClassAPerMonth: 0).\n // self-hosted/dev are filtered upstream.\n const usd = t.withinFreeTier\n ? `~$0 (R2 free tier)`\n : `~$${t.projectedUsdPerMonth!.toFixed(2)}/mo`;\n // Invariant: withinFreeTier===true implies pricing.freeClassAPerMonth>0,\n // which in turn implies percentOfFreeTier!==null (see project.ts).\n const tail = t.withinFreeTier\n ? `${t.percentOfFreeTier!.toFixed(0)}% of free-tier Class A budget. ${t.percentOfFreeTier! < 50 ? \"Well inside the promise.\" : \"Approaching free-tier ceiling.\"}`\n : `${t.percentOfGraduation.toFixed(2)}% of 50M/mo graduation trigger.`;\n return [\n ` trajectory: ~${wpm} writes/min → ~${classA} Class A/mo → ${usd}`,\n ` ${tail}`,\n ].join(\"\\n\");\n};\n\nconst PROVIDER_TAGS: ReadonlySet<string> = new Set([\"r2\", \"aws-s3\", \"self-hosted\", \"dev\"]);\n\nconst bundle = defineBaerlySubcommand({\n name: \"cost\",\n meta: {\n description: \"Project a collection's monthly Class A + storage cost trajectory.\",\n },\n args: COST_ARGS,\n handler: async (args, ctx) => {\n if (typeof args.provider === \"string\" && args.provider.length > 0) {\n if (!PROVIDER_TAGS.has(args.provider)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly cost: --provider must be one of r2|aws-s3|self-hosted|dev (got ${JSON.stringify(args.provider)})`,\n );\n }\n }\n const bucket = await parseBucketUri(args.bucket);\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n assertCollectionArg(args.collection, \"baerly cost\");\n\n const override =\n typeof args.provider === \"string\" && args.provider.length > 0\n ? (args.provider as ProviderTag)\n : undefined;\n const provider = detectProvider({\n bucketUri: args.bucket,\n s3Endpoint: process.env[\"BAERLY_S3_ENDPOINT\"],\n override,\n });\n if (provider === \"dev\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly cost: dev backends (file://, memory://) have no $ model; pass --provider=r2|aws-s3|self-hosted to project against one.`,\n );\n }\n\n const verdict = await estimateWritesPerMin(bucket.storage, app, tenant, args.collection, {\n keyPrefix: bucket.keyPrefix,\n });\n const trajectory = project(verdict.writesPerMin, 0, pricingFor(provider));\n if (trajectory === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly cost: not enough log entries under ${args.collection} to estimate writes/min (need >= 2)`,\n );\n }\n\n if (isJsonMode()) {\n emitSuccess({ command: \"cost\", collection: args.collection, trajectory });\n } else {\n process.stdout.write(`baerly cost ${args.collection}\\n${renderTrajectory(trajectory)}\\n`);\n }\n return 0;\n },\n});\n\n/** citty `defineCommand` block for `baerly cost`. */\nexport const cost = bundle.cmd;\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runCost = bundle.run;\n"],"mappings":";;;;;AA+BA,MAAa,kBAAkB,SAAkC;CAC/D,IAAI,KAAK,aAAa,KAAA,GACpB,OAAO,KAAK;CAEd,IAAI,KAAK,UAAU,WAAW,SAAS,GACrC,OAAO;CAET,IAAI,KAAK,UAAU,WAAW,WAAW,GACvC,OAAO;CAET,IAAI,CAAC,KAAK,UAAU,WAAW,OAAO,GACpC,OAAO;CAGT,MAAM,WAAW,KAAK,cAAc;CAC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AAK,WAAW,IAAI,iBAAiB,UAAU,EAAE,GAAG;EAE1F,OAAO;CACT;AACF,CAAC;;AAGD,MAAa,OAAO,OAAO;AAOJ,OAAO"}
@@ -9,11 +9,27 @@ const decodeJsonBytes = (bytes) => JSON.parse(new TextDecoder().decode(bytes));
9
9
  //#endregion
10
10
  //#region packages/protocol/src/constants.ts
11
11
  /**
12
+ * Max total object-key length S3 and R2 accept (UTF-8 bytes). A key
13
+ * over this fails the PUT with an opaque provider 400; baerly surfaces
14
+ * it early as InvalidConfig. See docs/spec/storage-compatibility.md.
15
+ */
16
+ const MAX_KEY_BYTES = 1024;
17
+ /**
12
18
  * Backoff (in milliseconds) inserted between LIST attempts when S3
13
19
  * returns 429 (rate-limited).
14
20
  */
15
21
  const RATE_LIMIT_BACKOFF_MILLIS = 1e3;
16
22
  /**
23
+ * Runaway guard on the tolerant forward-probe walk (`probeTailFrom`):
24
+ * max `log/<seq>` GETs past `tail_hint` before it THROWS `Internal`
25
+ * (rather than silently truncating reads). A runaway alarm only — the
26
+ * maintenance tick keeps `tail_hint` near the tail, so a >cap gap means
27
+ * maintenance is off or the collection is far past graduation.
28
+ *
29
+ * @see packages/server/src/log-tail.ts (`probeTailFrom`)
30
+ */
31
+ const LOG_FORWARD_PROBE_CAP = 1e5;
32
+ /**
17
33
  * MIME type written for `current.json` PUTs. S3 round-trips this on
18
34
  * subsequent GETs; useful for diagnostics when staring at a bucket
19
35
  * via the AWS console.
@@ -109,13 +125,31 @@ const CF_FREE_MAX_SAFE_FOLD_BYTES = 1024 * 1024;
109
125
  /**
110
126
  * SNAPSHOT-rebuild ceiling `E`, per-entry CPU axis: gates `snapshot_rows` (per-entry
111
127
  * parse/merge/serialize is ~half of fold CPU and scales with ROW COUNT not bytes, VLDB 2021
112
- * Sarkar — a tiny-doc snapshot can blow CPU under C). PROVISIONAL — calibrate via the
113
- * Task 3 bench, pin in graduation.md.
128
+ * Sarkar — a tiny-doc snapshot can blow CPU under C). PROVISIONAL — bench
129
+ * landed; paid recalibration deferred.
114
130
  *
115
131
  * @see docs/about/graduation.md
116
132
  * @see packages/server/src/maintenance.ts
117
133
  */
118
134
  const MAINTENANCE_MAX_FOLD_ROWS = 2048;
135
+ /** CF-free profile; the absent-context default. */
136
+ const MAINTENANCE_PROFILE_CF_FREE = {
137
+ gcInterval: 4,
138
+ gcMaxMarks: 20,
139
+ gcMaxSweeps: 10,
140
+ maxFoldEntriesPerPass: 20,
141
+ maxFoldBytes: MAINTENANCE_MAX_FOLD_BYTES_DEFAULT,
142
+ maxFoldRows: MAINTENANCE_MAX_FOLD_ROWS
143
+ };
144
+ /** Node profile; 10× CF-free caps. */
145
+ const MAINTENANCE_PROFILE_NODE = {
146
+ gcInterval: 2,
147
+ gcMaxMarks: 200,
148
+ gcMaxSweeps: 100,
149
+ maxFoldEntriesPerPass: 200,
150
+ maxFoldBytes: MAINTENANCE_MAX_FOLD_BYTES_DEFAULT,
151
+ maxFoldRows: MAINTENANCE_MAX_FOLD_ROWS
152
+ };
119
153
  /**
120
154
  * Rate-limit the defer-warn off SHARED current.json.last_warned_seq (not per-isolate
121
155
  * memory — CF recycles isolates). ~once per this many writes.
@@ -127,7 +161,7 @@ const MAINTENANCE_WARN_INTERVAL_WRITES = 1e3;
127
161
  /**
128
162
  * Placeholder for `CurrentJson.snapshot === null` in the
129
163
  * `_meta.manifest_pointer` cursor emitted on read responses. The
130
- * wire format is `"<snapshot>@<next_seq>"`, and `null` snapshots
164
+ * wire format is `"<snapshot>@<tail_hint>"`, and `null` snapshots
131
165
  * serialise as this literal so the cursor is never empty and stays
132
166
  * byte-stable when destructured by operators.
133
167
  *
@@ -174,8 +208,8 @@ const SHARED_SECRET_MISSING_MESSAGE = "baerly: auth=\"shared-secret\" but SHARED
174
208
  //#endregion
175
209
  //#region packages/protocol/src/coordination/current-json.ts
176
210
  /**
177
- * `current.json` — the per-collection CAS-protected control object — and
178
- * its embedded {@link WriterFence} epoch token.
211
+ * `current.json` — the per-collection compaction-state control object —
212
+ * and its embedded, currently dormant {@link WriterFence} epoch token.
179
213
  *
180
214
  * A dedicated `coordination/` namespace (parallel to `storage/`) holds
181
215
  * primitives whose contract is "atomic agreement over a small JSON
@@ -300,7 +334,7 @@ async function casUpdateCurrentJson(storage, key, mutator, opts) {
300
334
  }
301
335
  /**
302
336
  * Read `current.json.log_seq_start` — the low-water mark of the live
303
- * log range `[log_seq_start, next_seq)`. The field is always present
337
+ * log range `[log_seq_start, tail_hint)`. The field is always present
304
338
  * on disk (every `createCurrentJson` write seeds it; the compactor
305
339
  * advances it on every fold); this helper exists to document intent
306
340
  * at call sites that walk the log range or assert the snapshot
@@ -317,12 +351,12 @@ const encodeJson = (json) => encodeJsonBytes(json);
317
351
  const assertCurrentJson = (parsed, key) => {
318
352
  if (parsed === null || typeof parsed !== "object") throw new BaerlyError("InvalidResponse", `current.json at ${key}: parsed body is not an object`);
319
353
  const r = parsed;
320
- if (r["schema_version"] === 1) throw new BaerlyError("InvalidResponse", `current.json at ${key} is schema v1 (pre-maintenance); this build requires v2. Pre-launch, no production buckets — delete and re-seed the local-fs/Minio/Verdaccio scratch bucket, or recreate the R2/S3 bucket.`);
321
- if (r["schema_version"] !== 2) throw new BaerlyError("InvalidResponse", `current.json at ${key}: unsupported schema_version ${String(r["schema_version"])}; expected 2`);
354
+ if (r["schema_version"] === 1 || r["schema_version"] === 2) throw new BaerlyError("InvalidResponse", `current.json at ${key} is a pre-single-write-commit current.json; re-provision the bucket. Pre-launch, no production buckets — delete and re-seed the local-fs/Minio/Verdaccio scratch bucket, or recreate the R2/S3 bucket.`);
355
+ if (r["schema_version"] !== 3) throw new BaerlyError("InvalidResponse", `current.json at ${key}: unsupported schema_version ${String(r["schema_version"])}; this build requires 3. This almost always means stale scratch data from a different build — wipe the local dev bucket (e.g. \`rm -rf .baerly-data\`) or recreate the R2/S3 bucket, then retry.`);
322
356
  if (!(typeof r["snapshot"] === "string" || r["snapshot"] === null)) throw new BaerlyError("InvalidResponse", `current.json at ${key}: snapshot must be string|null`);
323
- if (typeof r["next_seq"] !== "number" || !Number.isInteger(r["next_seq"]) || r["next_seq"] < 0) throw new BaerlyError("InvalidResponse", `current.json at ${key}: next_seq must be a non-negative integer`);
357
+ if (typeof r["tail_hint"] !== "number" || !Number.isInteger(r["tail_hint"]) || r["tail_hint"] < 0) throw new BaerlyError("InvalidResponse", `current.json at ${key}: tail_hint must be a non-negative integer`);
324
358
  if (typeof r["log_seq_start"] !== "number" || !Number.isInteger(r["log_seq_start"]) || r["log_seq_start"] < 0) throw new BaerlyError("InvalidResponse", `current.json at ${key}: log_seq_start must be a non-negative integer`);
325
- if (r["log_seq_start"] > r["next_seq"]) throw new BaerlyError("InvalidResponse", `current.json at ${key}: log_seq_start ${String(r["log_seq_start"])} > next_seq ${String(r["next_seq"])}`);
359
+ if (r["log_seq_start"] > r["tail_hint"]) throw new BaerlyError("InvalidResponse", `current.json at ${key}: log_seq_start ${String(r["log_seq_start"])} > tail_hint ${String(r["tail_hint"])}`);
326
360
  const fence = r["writer_fence"];
327
361
  if (fence === null || typeof fence !== "object") throw new BaerlyError("InvalidResponse", `current.json at ${key}: writer_fence missing`);
328
362
  const f = fence;
@@ -330,10 +364,10 @@ const assertCurrentJson = (parsed, key) => {
330
364
  if (typeof f["owner"] !== "string") throw new BaerlyError("InvalidResponse", `current.json at ${key}: writer_fence.owner must be a string`);
331
365
  if (typeof f["claimed_at"] !== "string") throw new BaerlyError("InvalidResponse", `current.json at ${key}: writer_fence.claimed_at must be a string`);
332
366
  if (f["lease_until"] !== void 0 && typeof f["lease_until"] !== "string") throw new BaerlyError("InvalidResponse", `current.json at ${key}: writer_fence.lease_until must be string if present`);
333
- if (typeof r["tail_bytes"] !== "number" || !Number.isInteger(r["tail_bytes"]) || r["tail_bytes"] < 0) throw new BaerlyError("InvalidResponse", `current.json at ${key}: tail_bytes must be a non-negative integer`);
334
367
  if (typeof r["snapshot_bytes"] !== "number" || !Number.isInteger(r["snapshot_bytes"]) || r["snapshot_bytes"] < 0) throw new BaerlyError("InvalidResponse", `current.json at ${key}: snapshot_bytes must be a non-negative integer`);
335
368
  if (typeof r["snapshot_rows"] !== "number" || !Number.isInteger(r["snapshot_rows"]) || r["snapshot_rows"] < 0) throw new BaerlyError("InvalidResponse", `current.json at ${key}: snapshot_rows must be a non-negative integer`);
336
369
  if (r["last_warned_seq"] !== void 0 && (typeof r["last_warned_seq"] !== "number" || !Number.isInteger(r["last_warned_seq"]) || r["last_warned_seq"] < 0)) throw new BaerlyError("InvalidResponse", `current.json at ${key}: last_warned_seq must be a non-negative integer if present`);
370
+ if (r["mean_entry_bytes"] !== void 0 && (typeof r["mean_entry_bytes"] !== "number" || !Number.isInteger(r["mean_entry_bytes"]) || r["mean_entry_bytes"] < 0)) throw new BaerlyError("InvalidResponse", `current.json at ${key}: mean_entry_bytes must be a non-negative integer if present`);
337
371
  return parsed;
338
372
  };
339
373
  /**
@@ -349,6 +383,6 @@ const translateCasError = (e, key) => {
349
383
  return new BaerlyError("InvalidResponse", `current.json write at ${key} failed: ${String(e)}`, e);
350
384
  };
351
385
  //#endregion
352
- export { SHARED_SECRET_MISSING_MESSAGE as _, CF_FREE_MAX_SAFE_FOLD_BYTES as a, GC_MAX_PENDING_CANDIDATES as c, MAINTENANCE_MAX_FOLD_ROWS as d, MAINTENANCE_MIN_LIVE_BYTES as f, RATE_LIMIT_BACKOFF_MILLIS as g, NO_AUTH_CONFIGURED_MESSAGE as h, readCurrentJson as i, GC_PENDING_CONTENT_TYPE as l, MANIFEST_POINTER_EMPTY_SNAPSHOT as m, createCurrentJson as n, FORBIDDEN_MERGE_KEYS as o, MAINTENANCE_WARN_INTERVAL_WRITES as p, logSeqStartOf as r, GC_GRACE_PERIOD_MILLIS as s, casUpdateCurrentJson as t, MAINTENANCE_MAX_FOLD_BYTES_DEFAULT as u, decodeJsonBytes as v, encodeJsonBytes as y };
386
+ export { NO_AUTH_CONFIGURED_MESSAGE as _, CF_FREE_MAX_SAFE_FOLD_BYTES as a, decodeJsonBytes as b, GC_MAX_PENDING_CANDIDATES as c, MAINTENANCE_MIN_LIVE_BYTES as d, MAINTENANCE_PROFILE_CF_FREE as f, MAX_KEY_BYTES as g, MANIFEST_POINTER_EMPTY_SNAPSHOT as h, readCurrentJson as i, GC_PENDING_CONTENT_TYPE as l, MAINTENANCE_WARN_INTERVAL_WRITES as m, createCurrentJson as n, FORBIDDEN_MERGE_KEYS as o, MAINTENANCE_PROFILE_NODE as p, logSeqStartOf as r, GC_GRACE_PERIOD_MILLIS as s, casUpdateCurrentJson as t, LOG_FORWARD_PROBE_CAP as u, RATE_LIMIT_BACKOFF_MILLIS as v, encodeJsonBytes as x, SHARED_SECRET_MISSING_MESSAGE as y };
353
387
 
354
- //# sourceMappingURL=current-json-C-EyJqs0.js.map
388
+ //# sourceMappingURL=current-json-DsN7FNY1.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"current-json-DsN7FNY1.js","names":[],"sources":["../packages/protocol/src/bytes.ts","../packages/protocol/src/constants.ts","../packages/protocol/src/coordination/current-json.ts"],"sourcesContent":["/**\n * UTF-8 JSON byte helpers — names the encode/decode idiom used by\n * every content body, log entry, snapshot, and current.json payload.\n */\n\nexport const encodeJsonBytes = (value: unknown): Uint8Array =>\n new TextEncoder().encode(JSON.stringify(value));\n\nexport const decodeJsonBytes = <T = unknown>(bytes: Uint8Array): T =>\n JSON.parse(new TextDecoder().decode(bytes)) as T;\n","/**\n * Max total object-key length S3 and R2 accept (UTF-8 bytes). A key\n * over this fails the PUT with an opaque provider 400; baerly surfaces\n * it early as InvalidConfig. See docs/spec/storage-compatibility.md.\n */\nexport const MAX_KEY_BYTES = 1024;\n\n/**\n * Half-window (in milliseconds) within which a `LogEntry`'s embedded\n * `commit_ts` must agree with wall-clock time for downstream consumers\n * to accept the entry as causally ordered. Bound on tolerated\n * client/server clock skew across the protocol.\n *\n * 5 s is the protocol's tolerance for client/server clock skew.\n * Tightening this can cause spurious rejections on machines that\n * haven't synced NTP; loosening it widens the window during which\n * causal ordering can be disturbed by skew.\n *\n * @see docs/spec/sync-protocol.md\n * @see packages/protocol/src/storage/types.ts (`Storage` JSDoc)\n */\nexport const LAG_WINDOW_MILLIS: number = 5000;\n\n/**\n * Bit width of the descending base-32 seq segment in every LSN\n * (`<base32-time>_<session>_<seq>`, minted in `Writer.commit`).\n * The output character width is `Math.ceil(COUNT_BIT_WIDTH / 5) = 11`.\n *\n * **Domain:** 0 .. `Number.MAX_SAFE_INTEGER` (2^53 − 1). A collection\n * would need 2^53 writes before the seq counter could overflow — an\n * unreachable ceiling in practice.\n *\n * **Why 53 bits:** JavaScript numbers are IEEE-754 doubles; the safe\n * integer range is exactly [0, 2^53 − 1]. Encoding at this width keeps\n * the arithmetic in the encoder and decoder (`uint2strDesc` /\n * `str2uintDesc` in `packages/protocol/src/types.ts`) exact and\n * leaves no headroom for the negative-overflow path that manifested\n * at the old 10-bit width (domain 0..1023).\n *\n * **Ordering property:** fixed-width base-32 encoding preserves\n * descending lex order across the entire domain\n * (`countKey(a) > countKey(b)` iff `a < b`), which the reverse-walk\n * on `Storage.list` relies on.\n *\n * **Three production consumers** must all agree on this value:\n * 1. Encoder — `countKey` in `packages/protocol/src/types.ts`\n * 2. Decoder — `lsnParts` in `packages/protocol/src/log.ts`\n * 3. Validator regex — `LSN_RE` in `packages/server/src/http/since.ts`\n * (derives its `{N}` from `Math.ceil(COUNT_BIT_WIDTH / 5)`)\n *\n * The independent shape-assertion literal in\n * `tests/fixtures/collection-api-cascade.ts` is kept hand-written and\n * is NOT a consumer of this constant (importing the production\n * validator into the test that checks it would make the assertion\n * a tautology).\n *\n * Changing this constant is a protocol-breaking change — it reshapes\n * every emitted LSN cursor.\n *\n * @see packages/protocol/src/types.ts (`countKey`, `uint2strDesc`)\n * @see packages/protocol/src/log.ts (`lsnParts`, `str2uintDesc` call)\n * @see packages/server/src/http/since.ts (`LSN_RE`)\n * @see docs/spec/log-entry-shape.md\n */\nexport const COUNT_BIT_WIDTH: number = 53;\n\n/**\n * Bit width of the base-32 timestamp prefix encoded into every\n * {@link LogEntry.lsn} (`<base32-time>_<session>_<seq>`, minted in\n * `Writer.commit`). 42 bits gives ~139 years of millisecond\n * precision, which is enough for the protocol's lifetime.\n *\n * Changing this is a protocol-breaking change — it would re-shape\n * every emitted LSN.\n *\n * @see packages/protocol/src/time.ts (`timestamp`)\n * @see packages/server/src/writer.ts (`Writer.commit`)\n * @see docs/spec/sync-protocol.md\n */\nexport const TIMESTAMP_BIT_WIDTH: number = 42;\n\n/**\n * Length of the random-prefix `session` segment embedded in every\n * {@link LogEntry.lsn} (`<base32-time>_<session>_<seq>`). 6 hex chars\n * from `crypto.randomUUID()` give 16⁶ ≈ 1.7 × 10⁷ distinct sessions;\n * birthday-collision rate at N=100 is ~3 × 10⁻⁴, comfortably below\n * the 1 % bound asserted in `tests/regressions.test.ts`. Collisions\n * within a single commit's writer set are also disambiguated by the\n * trailing `<seq>` counter.\n *\n * @see packages/server/src/writer.ts (`Writer.commit` —\n * `session = uuid().slice(0, SESSION_ID_LENGTH)`)\n */\nexport const SESSION_ID_LENGTH: number = 6;\n\n/**\n * Maximum attempts `S3HttpStorage.list` will make per page when the\n * server replies 429 (rate-limited). After this many in a row, it\n * gives up with `NetworkError`. Separate from the inner transient-\n * failure budget so a single hot page can't burn the whole retry\n * allowance.\n */\nexport const LIST_OBJECT_MAX_RETRIES: number = 10;\n\n/**\n * Backoff (in milliseconds) inserted between LIST attempts when S3\n * returns 429 (rate-limited).\n */\nexport const RATE_LIMIT_BACKOFF_MILLIS: number = 1000;\n\n/**\n * Upper clamp on a server-provided `Retry-After` hint, in seconds.\n * RFC 7231 §7.1.3 allows arbitrary delta-seconds or HTTP-dates, but a\n * client that blindly honours a multi-hour hint hands a misbehaving\n * proxy a denial-of-service primitive. 60s covers any plausible S3-\n * compatible throttle while keeping the worst-case bounded.\n *\n * @see packages/protocol/src/storage/s3-http.ts (`parseRetryAfter`)\n */\nexport const RETRY_AFTER_MAX_SECONDS: number = 60;\n\n/**\n * Default retry budget for `S3HttpStorage.retry` (the wrapper around\n * each of the four `Storage` methods). Bounded so that permanent\n * failures (CORS misconfig, NXDOMAIN, persistent 5xx) surface to\n * callers as rejected promises instead of retrying forever and\n * leaving `Writer.commit()` permanently pending.\n *\n * 8 attempts at the existing 100ms→×1.5→10s schedule covers ~30s of\n * transient turbulence, which is enough to ride out a leader election\n * or a brief network blip without papering over a real outage.\n */\nexport const S3_REQUEST_MAX_RETRIES: number = 8;\n\n/**\n * Maximum concurrent log-entry GETs issued by a single `walkLogRange`\n * call. Bounds Class-B fan-out per read and per CAS attempt — without\n * a bound, a reader on a collection whose compactor has fallen behind\n * fans out one GET per live-tail entry (typically 50-100 on the free-\n * tier profile), and a contended writer multiplies that by the CAS\n * retry budget ({@link S3_REQUEST_MAX_RETRIES}).\n *\n * 16 keeps the worst-case under retry to `16 * 8 = 128` concurrent\n * GETs — comfortably under the Workers subrequest cap (50 concurrent\n * / 1000 total) and leaving headroom for the writer's content / index\n * / log / CAS PUTs sharing the same isolate.\n *\n * @see packages/server/src/log-walk.ts (`walkLogRange`)\n */\nexport const MAX_PARALLEL_LOG_READS: number = 16;\n\n/**\n * Runaway guard on the tolerant forward-probe walk (`probeTailFrom`):\n * max `log/<seq>` GETs past `tail_hint` before it THROWS `Internal`\n * (rather than silently truncating reads). A runaway alarm only — the\n * maintenance tick keeps `tail_hint` near the tail, so a >cap gap means\n * maintenance is off or the collection is far past graduation.\n *\n * @see packages/server/src/log-tail.ts (`probeTailFrom`)\n */\nexport const LOG_FORWARD_PROBE_CAP: number = 100_000;\n\n/**\n * Current major version of the `current.json` control-object schema.\n * Readers MUST reject unknown versions with\n * `BaerlyError{code:\"InvalidResponse\"}` rather than try to coerce.\n *\n * Bump only on a breaking change to `CurrentJson` field semantics.\n * Adding a new optional field is NOT breaking; renaming or removing\n * a field IS breaking.\n *\n * @see packages/protocol/src/coordination/current-json.ts\n */\nexport const CURRENT_JSON_SCHEMA_VERSION = 3 as const;\n\n/**\n * MIME type written for `current.json` PUTs. S3 round-trips this on\n * subsequent GETs; useful for diagnostics when staring at a bucket\n * via the AWS console.\n *\n * @see packages/protocol/src/coordination/current-json.ts\n */\nexport const CURRENT_JSON_CONTENT_TYPE: string = \"application/json\";\n\n/**\n * Current major version of the `gc/pending.json` control-object\n * schema. Readers MUST reject unknown versions with\n * `BaerlyError{code:\"InvalidResponse\"}` rather than try to coerce.\n *\n * Bump only on a breaking change to `GcPending` field semantics.\n * Adding a new optional field is NOT breaking; renaming or removing\n * a field IS breaking.\n *\n * @see packages/protocol/src/coordination/gc-pending.ts\n */\nexport const GC_PENDING_SCHEMA_VERSION = 1 as const;\n\n/**\n * MIME type written for `gc/pending.json` PUTs.\n *\n * @see packages/protocol/src/coordination/gc-pending.ts\n */\nexport const GC_PENDING_CONTENT_TYPE: string = \"application/json\";\n\n/**\n * Default grace period between \"marking\" a key for GC and \"sweeping\"\n * (deleting) it. 7 days, chosen to span the worst plausible writer-\n * retry window (a paused-process writer that resumes hours later\n * should still find its idempotency anchor on the bucket). The\n * `runGc()` function accepts an override for tests.\n *\n * Why 7 days specifically:\n * - **1 day is too aggressive for batch workloads.** Worker isolate\n * scheduling pauses, cross-region replication lag, and\n * {@link RATE_LIMIT_BACKOFF_MILLIS} retry cascades can plausibly\n * exceed an hour under pathological conditions.\n * - **30 days is conservative beyond the worst plausible pause.**\n * Doubles `gc/pending.json` size at steady state and slows\n * visibility into \"did GC actually run?\" by 4×.\n * - **7 days spans the realistic upper bound** — long-running batch\n * jobs, multi-region propagation delays, queue backlogs, and\n * downstream outages the writer is retrying through. The protocol\n * is unaffected by the choice of value within the [hours, weeks]\n * range; this constant is the operator-tunable knob.\n *\n * Production code MUST NOT call `runGc` with `graceMillis` below the\n * default outside maintenance windows — going below the longest\n * plausible writer-retry latency risks deleting an anchor a writer\n * is about to find on retry. Test code that sets `graceMillis: 0` is\n * exercising the sweep path deliberately, not modelling production.\n *\n * @see packages/server/src/gc.ts\n */\n// Stryker disable next-line ArithmeticOperator: internal tuning value, not an off-process contract — asserting the literal would be a tautological change-detector. See docs/contributing/mutation-testing.md constants policy.\nexport const GC_GRACE_PERIOD_MILLIS: number = 7 * 24 * 60 * 60 * 1000;\n\n/**\n * Cap on candidates kept in `gc/pending.json` to bound the size of\n * the file. The compactor marks at most this many candidates per\n * pass; subsequent passes pick up the rest. Larger collections will\n * lag GC by one pass per `GC_MAX_PENDING_CANDIDATES` orphans, which\n * is acceptable.\n *\n * @see packages/server/src/gc.ts\n */\nexport const GC_MAX_PENDING_CANDIDATES: number = 1000;\n\n/**\n * Bounded retry cap for the `gc/pending.json` CAS read-modify-write\n * loop in {@link casUpdateGcPending}. On `Conflict` (a concurrent GC\n * pass landed between this pass's read and its write) the loop\n * re-reads `latest` and re-applies the pure merge mutator, retrying up\n * to this many total attempts before surfacing `Conflict`. Safe to\n * retry because the mutator is pure and the sweep DELETEs are\n * idempotent and already performed; a re-merge against fresh state\n * never loses a concurrently-marked candidate. Small fixed cap — under\n * one writer per collection at steady state, contention is rare; this\n * just bounds the worst case so a pathological storm can't spin.\n *\n * @see packages/protocol/src/coordination/gc-pending.ts\n */\nexport const GC_PENDING_CAS_MAX_ATTEMPTS: number = 3;\n\n/**\n * Fold-trigger ratio: fold fires at tail ≥ R×snapshot. Pure READ-AMP / fold-frequency\n * knob — with the ceiling on the snapshot axis (Decision 3a, tail sliced) the\n * auto-maintained snapshot ceiling is S_max = C, NOT C/(1+R). R=1.0 caps steady-state\n * read-amp at ~2× and keeps compaction write-amp (≈1+1/R) moderate. See\n * docs/about/graduation.md for the derivation.\n *\n * @see docs/about/graduation.md\n * @see packages/server/src/maintenance.ts\n */\nexport const MAINTENANCE_TARGET_RATIO: number = 1;\n\n/**\n * Floor for the ratio denominator — avoid div-by-tiny on a fresh collection. Also\n * sets the first-fold threshold: until a snapshot exists, fold fires at tail ≈ this.\n *\n * @see packages/server/src/maintenance.ts\n */\n// Stryker disable next-line ArithmeticOperator: internal tuning value, not an off-process contract — asserting the literal would be a tautological change-detector. See docs/contributing/mutation-testing.md constants policy.\nexport const MAINTENANCE_MIN_LIVE_BYTES: number = 64 * 1024;\n\n/**\n * Cold-start per-entry byte estimate for the ratio TRIGGER's derived live-tail\n * size (`estimateTailBytes`), used until the compactor stamps a real\n * `current.json.mean_entry_bytes` on the first fold. Folding too-few entries is\n * barred by Gate-1's entry-count floor (`minEntriesToCompact`), NOT by this\n * value — so over-estimating is equally safe; this is a first-fold-TIMING\n * choice. A small typical log-entry size keeps the first fold's cadence close\n * to a precisely measured path for typical entries; must be non-zero so a\n * bare `Db.create()` still bootstraps its first auto-fold (a 0 fallback leaves\n * the ratio dead pre-stamp). Large-body collections see a bounded first-fold\n * delay; after it stamps a real mean the estimate tracks the exact tail.\n *\n * @see packages/server/src/maintenance.ts (`estimateTailBytes`)\n */\n// Stryker disable next-line ArithmeticOperator: internal cold-start tuning value, not an off-process contract — asserting the literal would be a tautological change-detector. See docs/contributing/mutation-testing.md constants policy.\nexport const MAINTENANCE_COLD_START_ENTRY_BYTES: number = 128;\n\n/**\n * Per-tick GC budget — these are DEFAULTS (= the most-constrained tier, CF free, reusing\n * the TESTED `CLOUDFLARE_FREE_TIER` values in maintenance.ts / maintenance.budget.test.ts).\n * The adapter THREADS per-tier overrides into the context (§8.4); Node/CF-paid raise them.\n * NOT universal constants — a Node-sized value here would silently kill every CF-free fold\n * (round-4 Tier-1). gc pass ≈ 6 + maxMarks + maxSweeps subrequests (both GET/DELETE the\n * bucket — §3.1). Cadence is BOUNDARY-CROSSING (§3.1), not modulo.\n *\n * @see packages/server/src/maintenance.ts\n * @see packages/server/src/maintenance.budget.test.ts\n */\nexport const WRITE_TICK_GC_INTERVAL: number = 4; // tuned so maxSweeps/interval ≥ p (§7.1)\n\n/**\n * Fold-starvation guard (critique A): on `phasesPerTick:\"single\"`, every Nth GC-interval is a\n * HARD GC boundary the fold may NOT preempt, so a long fold-heavy drain can't starve GC to zero.\n * Stateless (seq-derived) — no per-isolate preemption counter (CF recycles isolates). At 4 a\n * sustained drain still yields ~1 GC tick per 4 GC-intervals.\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const GC_STARVATION_GUARD: number = 4;\n\n/**\n * Maximum GC marks per write-tick pass (M in 6+M+S; GETs the live tail to hash).\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const WRITE_TICK_GC_MAX_MARKS: number = 20;\n\n/**\n * Maximum GC sweeps per write-tick pass (S in 6+M+S; DELETE subrequests).\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const WRITE_TICK_GC_MAX_SWEEPS: number = 10;\n\n/**\n * Per-pass tail SLICE default — compact()'s maxEntriesPerRun. Fold ≤ this+3 subrequests, so\n * a large tail drains incrementally over write-ticks (Decision 3). Adapter-overridable.\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const WRITE_TICK_FOLD_ENTRIES_PER_PASS: number = 20;\n\n/**\n * compact()'s minEntriesToCompact, set EXPLICITLY by the runner so it agrees with Gate 1\n * rather than inheriting compact()'s silent default 100 (which would contradict the 64 KB\n * first-fold story — round-4 Tier-3). Adapter-overridable; CF-free value.\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const WRITE_TICK_MIN_ENTRIES_TO_COMPACT: number = 50;\n\n/**\n * Node-tier write-tick maintenance caps — a MODERATE multiple of the CF-free `WRITE_TICK_*`\n * defaults, threaded into the per-request observability context by `baerlyNode` /\n * `createFetchHandler` (§8.4). Node v1 runs maintenance INLINE on the commit path (no\n * `waitUntil`), so the cap is NOT the CF subrequest wall — it's the worst-case single-write\n * added latency. A maintenance tick only fires on a ratio/boundary trip (rare), and when it\n * does it costs ~`maxFoldEntriesPerPass` + (6 + `gcMaxMarks` + `gcMaxSweeps`) storage\n * round-trips against a co-located S3/R2 — sub-second on the occasional boundary write at a\n * 10× multiple. These are deliberately BOUNDED (10× CF-free), NOT unbounded: the deleted\n * scheduled full-tail sweep folded the entire live tail in one shot, which a 100× multiple here\n * would reintroduce as multi-second commit stalls. Raise the snapshot ceiling separately via\n * `BAERLY_MAINTENANCE_MAX_FOLD_BYTES`; these caps slice the per-pass work, not the ceiling.\n *\n * @see packages/adapter-node/src/server.ts\n * @see packages/server/src/maintenance.ts\n * @see docs/about/graduation.md\n */\nexport const NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS: number = 200;\n\n/** Node-tier GC marks per pass (M in 6+M+S). 10× CF-free. @see {@link NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS} */\nexport const NODE_MAINTENANCE_GC_MAX_MARKS: number = 200;\n\n/** Node-tier GC sweeps per pass (S in 6+M+S). 10× CF-free. @see {@link NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS} */\nexport const NODE_MAINTENANCE_GC_MAX_SWEEPS: number = 100;\n\n/**\n * Node-tier GC cadence (boundary-crossing). Shorter than the CF-free `WRITE_TICK_GC_INTERVAL`\n * (4) so the per-write sweep budget keeps up: `gcMaxSweeps / gcInterval = 100 / 2 = 50`\n * comfortably clears the garbage-per-write rate `p` (the `maxSweeps/interval ≥ p` invariant,\n * §7.1) with a wide margin.\n *\n * @see {@link NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS}\n */\nexport const NODE_MAINTENANCE_GC_INTERVAL: number = 2;\n\n/**\n * SNAPSHOT-rebuild ceiling `C` (the unsliceable axis — Decision 3a), memory. Default sized\n * ~5.5 ms under CF-free ~10 ms. Raise via BAERLY_MAINTENANCE_MAX_FOLD_BYTES on capable\n * hosts. Auto-maintained snapshot ceiling S_max = C. NOT snapshot+tail (tail is sliced).\n *\n * @see docs/about/graduation.md\n * @see packages/server/src/maintenance.ts\n */\n// Stryker disable next-line ArithmeticOperator: internal tuning value, not an off-process contract — asserting the literal would be a tautological change-detector. See docs/contributing/mutation-testing.md constants policy.\nexport const MAINTENANCE_MAX_FOLD_BYTES_DEFAULT: number = 512 * 1024;\n\n/**\n * The largest snapshot a Cloudflare **free-tier** isolate can safely\n * rebuild in ONE fold under the ~10 ms CPU budget. This is the WARN\n * THRESHOLD, not a runtime cap: an operator who raises\n * `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` ABOVE this value on a free Worker\n * risks a snapshot rebuild that exceeds the ~10 ms CPU limit and gets\n * CPU-killed MID-REBUILD — the CAS never lands, so the fold silently\n * never advances `log_seq_start` and the tail grows unbounded.\n *\n * Sized at 2× {@link MAINTENANCE_MAX_FOLD_BYTES_DEFAULT}. The default\n * (512 KiB) rebuilds in ~5.5 ms under the CF-free ~10 ms budget\n * (constants.ts default JSDoc); linear-extrapolating, ~1 MiB is the\n * point where one-shot rebuild fills the budget with little margin, so\n * anything strictly larger is no longer free-tier-safe. On CF **paid**\n * (raised CPU limits), Node, or once §11 chunked snapshots land, a\n * larger ceiling is fine — hence this is a one-time `console.warn` at\n * handler init, NOT a hard rejection.\n *\n * @see packages/adapter-cloudflare/src/worker.ts\n * @see packages/server/src/maintenance.ts\n * @see docs/about/graduation.md\n */\n// Stryker disable next-line ArithmeticOperator: internal tuning value, not an off-process contract — asserting the literal would be a tautological change-detector. See docs/contributing/mutation-testing.md constants policy.\nexport const CF_FREE_MAX_SAFE_FOLD_BYTES: number = 1024 * 1024;\n\n/**\n * SNAPSHOT-rebuild ceiling `E`, per-entry CPU axis: gates `snapshot_rows` (per-entry\n * parse/merge/serialize is ~half of fold CPU and scales with ROW COUNT not bytes, VLDB 2021\n * Sarkar — a tiny-doc snapshot can blow CPU under C). PROVISIONAL — bench\n * landed; paid recalibration deferred.\n *\n * @see docs/about/graduation.md\n * @see packages/server/src/maintenance.ts\n */\nexport const MAINTENANCE_MAX_FOLD_ROWS: number = 2048;\n\n// Declared here (not the nominal server `MaintenanceProfile`) to avoid a server→protocol cycle; keep field-identical to it.\ntype MaintenanceProfileShape = Readonly<{\n gcInterval: number;\n gcMaxMarks: number;\n gcMaxSweeps: number;\n maxFoldEntriesPerPass: number;\n maxFoldBytes: number;\n maxFoldRows: number;\n}>;\n\n/** CF-free profile; the absent-context default. */\nexport const MAINTENANCE_PROFILE_CF_FREE: MaintenanceProfileShape = {\n gcInterval: WRITE_TICK_GC_INTERVAL,\n gcMaxMarks: WRITE_TICK_GC_MAX_MARKS,\n gcMaxSweeps: WRITE_TICK_GC_MAX_SWEEPS,\n maxFoldEntriesPerPass: WRITE_TICK_FOLD_ENTRIES_PER_PASS,\n maxFoldBytes: MAINTENANCE_MAX_FOLD_BYTES_DEFAULT,\n maxFoldRows: MAINTENANCE_MAX_FOLD_ROWS,\n};\n\n/** Node profile; 10× CF-free caps. */\nexport const MAINTENANCE_PROFILE_NODE: MaintenanceProfileShape = {\n gcInterval: NODE_MAINTENANCE_GC_INTERVAL,\n gcMaxMarks: NODE_MAINTENANCE_GC_MAX_MARKS,\n gcMaxSweeps: NODE_MAINTENANCE_GC_MAX_SWEEPS,\n maxFoldEntriesPerPass: NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS,\n maxFoldBytes: MAINTENANCE_MAX_FOLD_BYTES_DEFAULT,\n maxFoldRows: MAINTENANCE_MAX_FOLD_ROWS,\n};\n\n/**\n * Rate-limit the defer-warn off SHARED current.json.last_warned_seq (not per-isolate\n * memory — CF recycles isolates). ~once per this many writes.\n *\n * @see packages/protocol/src/coordination/current-json.ts\n * @see packages/server/src/maintenance.ts\n */\nexport const MAINTENANCE_WARN_INTERVAL_WRITES: number = 1000;\n\n/**\n * Rate-limit for the maintenance tick's `tail_hint` advance on the\n * DEFER path (HR-2). When the fold defers (snapshot over the CF-CPU-kill\n * ceiling) the compactor never stamps `tail_hint` via its Step-7 fold\n * CAS, so the gap `(true_tail − tail_hint)` would grow without bound and\n * every read would re-walk the whole live tail via `probeTailFrom`. The\n * runner therefore advances `tail_hint` toward the observed tail with a\n * best-effort `current.json` CAS — but only once per this many writes,\n * so it is NOT a per-commit `current.json` write (which is exactly what\n * single-write commit removed).\n *\n * Sized at 128: it bounds a deferring collection's worst-case\n * read-walk to ≤128 forward GETs (≈one extra read-page sweep — a\n * negligible per-read latency cost), keeps the gap two-to-three orders\n * of magnitude below {@link LOG_FORWARD_PROBE_CAP} (so the cap-throw is a\n * pure runaway guard, never reached in normal operation), and holds the\n * hint-advance CAS rate under ~1% of the commit rate (negligible\n * Class-A cost, amortized). Smaller would tighten the read-walk at a\n * higher CAS rate; larger would loosen it — 128 is the modest middle.\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const MAINTENANCE_TAIL_HINT_REFRESH_WRITES: number = 128;\n\n/**\n * Placeholder for `CurrentJson.snapshot === null` in the\n * `_meta.manifest_pointer` cursor emitted on read responses. The\n * wire format is `\"<snapshot>@<tail_hint>\"`, and `null` snapshots\n * serialise as this literal so the cursor is never empty and stays\n * byte-stable when destructured by operators.\n *\n * @see packages/server/src/contract.ts (HttpOkMeta)\n */\nexport const MANIFEST_POINTER_EMPTY_SNAPSHOT: string = \"none\";\n\n/**\n * Keys that must never propagate through {@link merge}: assigning to\n * them on a plain object pollutes the prototype chain. The literal\n * `{ __proto__: ... }` syntax is a prototype-setter (not an own key)\n * and bypasses `Object.keys`, but `JSON.parse('{\"__proto__\":...}')`\n * produces a real own property — which is exactly how a malicious\n * HTTP PATCH body would arrive on the wire.\n *\n * Lifted to a constant so every iteration path that touches a\n * caller-supplied object can re-use the same defence without\n * duplicating the keyword list.\n *\n * @see packages/protocol/src/json.ts (merge)\n * @see docs/spec/json-merge-patch.md\n */\nexport const FORBIDDEN_MERGE_KEYS: ReadonlySet<string> = new Set([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n]);\n\n/**\n * Architecturally-enforced ceiling: storage ops per logical write.\n *\n * Two Class A ops: PUT content + the committing `log/<seq>` create\n * (`If-None-Match: \"*\"`). There is no `current.json` CAS on the commit\n * path — the winning log create IS the commit. The cost-model page\n * derives the free-tier write budget from this multiplier; the phase-5\n * end-to-end test asserts it at CI time. Changing this constant is a\n * cost-model-breaking change.\n *\n * @see docs/about/cost-model.md §\"Cost ceiling\"\n * @see tests/integration/phase5-end-to-end.test.ts\n */\nexport const STORAGE_OPS_PER_LOGICAL_WRITE: number = 2;\n\n/**\n * Canonical auth posture identifiers consumed by `BaerlyAppConfig.auth`,\n * the adapter resolution path (`packages/adapter-cloudflare/src/worker.ts`,\n * `packages/adapter-node/src/baerly-node.ts`), and `baerly doctor`.\n *\n * - `\"none\"` — no header check; pin every request to `config.tenant`.\n * For local dev, intranet, CLI tools — contexts where the network\n * seam itself is the trust boundary.\n * - `\"shared-secret\"` — bearer-token check; reads `SHARED_SECRET` from\n * the runtime env and pins every request to `config.tenant`.\n *\n * Custom verifiers (`cloudflareAccess`, `bearerJwt`, SigV4, …) bypass\n * this enum — pass a `Verifier` to the adapter factory's `verifier:`\n * option instead.\n */\nexport const AUTH_CONFIG_VALUES = [\"none\", \"shared-secret\"] as const;\n\n/**\n * Locked error wording for the \"no auth configured\" failure mode. The\n * adapter throws this when neither `config.auth` nor `verifier:`\n * resolves a real `Verifier`. Pinned via a regression test so future\n * refactors do not drift the operator-facing wording.\n *\n * Consumed by:\n * - `packages/adapter-cloudflare/src/worker.ts` (first-fetch throw)\n * - `packages/adapter-node/src/server.ts` (first-fetch throw)\n * - `packages/cli/src/doctor/cloudflare.ts` (FAIL finding mirrors it)\n */\nexport const NO_AUTH_CONFIGURED_MESSAGE: string =\n 'baerly: no auth configured. Set `auth` in baerly.config.ts (\"none\", \"shared-secret\") or pass `verifier` on the adapter factory.';\n\n/**\n * Locked error wording for `auth: \"shared-secret\"` + missing env var.\n * Same pinning rationale as {@link NO_AUTH_CONFIGURED_MESSAGE}.\n */\nexport const SHARED_SECRET_MISSING_MESSAGE: string =\n 'baerly: auth=\"shared-secret\" but SHARED_SECRET env is empty/unset. Cloudflare: `wrangler secret put SHARED_SECRET`, or add to .dev.vars for local dev. Node: set in process env.';\n","/**\n * `current.json` — the per-collection compaction-state control object —\n * and its embedded, currently dormant {@link WriterFence} epoch token.\n *\n * A dedicated `coordination/` namespace (parallel to `storage/`) holds\n * primitives whose contract is \"atomic agreement over a small JSON\n * object\" rather than \"byte I/O.\" Future siblings (compactor\n * manifest, sweeper checkpoint) join here, not at the top\n * level. The module lives inside `@baerly/protocol` because it is pure\n * (no Node imports, no `node:fs`, no `Buffer`, no `node:crypto`,\n * no implicit globals) and must remain Worker-bundleable — every byte\n * of network traffic threads through the {@link Storage} seam.\n *\n * Contract surface:\n * - {@link readCurrentJson} — fetch + parse + validate\n * - {@link createCurrentJson} — create-only (CAS via `If-None-Match:\"*\"`)\n * - {@link casUpdateCurrentJson} — read-modify-write (CAS via `If-Match`)\n * - {@link claimWriter} — bump epoch + stamp server-clock claim time\n *\n * Why the two-round-trip claim protocol: `claimed_at` MUST come from\n * `StoragePutResult.serverDate` (the single shared clock across\n * instances), not the local clock. `serverDate` is only known *after*\n * the CAS PUT lands, so {@link claimWriter} writes the record with\n * `claimed_at: \"\"` first, then overwrites itself with the correct\n * `serverDate.toISOString()` in a second CAS. The epoch bump is\n * already durable from the first put either way; a peer landing\n * between the two writes loses cleanly with `Conflict`.\n *\n * Why CAS errors are wrapped: every in-tree {@link Storage} impl\n * surfaces a lost CAS as `BaerlyError{code:\"Conflict\"}`. Downstream\n * callers — the Writer, the compactor, the sweeper —\n * discriminate by `code` to decide whether to retry.\n * We re-wrap here only to add the `current.json at <key>` location\n * context to the message; the `code` is unchanged.\n */\n\nimport { encodeJsonBytes } from \"../bytes.ts\";\nimport { CURRENT_JSON_CONTENT_TYPE, CURRENT_JSON_SCHEMA_VERSION } from \"../constants.ts\";\nimport { BaerlyError } from \"../errors.ts\";\nimport type { Storage, StoragePutOptions, StoragePutResult } from \"../storage/types.ts\";\n\n/**\n * Per-collection control object. CAS-protected. One per\n * `(tenant, collection)` key — for example\n * `<tenant>/<collection>/current.json`. The compactor swaps snapshot\n * generations by CAS-writing this object; the Writer reads it on every\n * commit to find the snapshot pointer and a non-authoritative\n * tail-probe floor. The numbered log create mints the next integer\n * `seq`; no commit-path code CAS-advances `current.json`.\n *\n * The schema is forward-compatible: adding a new optional field is\n * non-breaking. Renaming or removing a field requires bumping\n * {@link CURRENT_JSON_SCHEMA_VERSION}; readers MUST reject\n * unknown major versions with `BaerlyError{code:\"InvalidResponse\"}`.\n */\nexport interface CurrentJson {\n /**\n * Schema version. Today: `3`. Bump on any breaking change to\n * field semantics; readers must reject unknown major versions\n * with `BaerlyError{code:\"InvalidResponse\"}`.\n */\n schema_version: 3;\n\n /**\n * Pointer to the current snapshot generation. `null` before the\n * first compaction has produced a snapshot — readers fall back\n * to log-only replay. Shape is opaque-to-this-module; the\n * compactor owns its interpretation.\n */\n snapshot: string | null;\n\n /**\n * Non-authoritative monotone lower bound on the committed log tail.\n * The authoritative tail is discovered by forward-probe (log-tail.ts);\n * never trust this as the head. Durable advancement is owned by\n * compaction folds, write-tick tail refreshes, and explicit\n * operator/import paths; ordinary writer commits do not refresh it.\n */\n tail_hint: number;\n\n /**\n * Lowest live log sequence number. Entries with `seq < log_seq_start`\n * have been folded into the snapshot at {@link snapshot} (or, if\n * `snapshot === null`, have been dropped because the collection was\n * truncated). Readers walk `[log_seq_start, tail_hint)`. Always\n * present on disk — fresh `current.json` writes via\n * {@link createCurrentJson} set this to `0`; the compactor advances\n * it on every fold.\n *\n * Invariants the compactor maintains:\n * - `0 <= log_seq_start <= tail_hint`\n * - `log_seq_start` advances monotonically (never decreases)\n * - `log_seq_start > 0` implies `snapshot !== null` (the snapshot\n * covers `[0, log_seq_start)`)\n */\n log_seq_start: number;\n\n /**\n * Embedded write-fence epoch. See {@link WriterFence}.\n */\n writer_fence: WriterFence;\n\n // New in v2:\n\n /** Byte size of the snapshot pointed to by `snapshot`. */\n snapshot_bytes: number;\n\n /**\n * Row count of the snapshot (= compactor `base.size`, free). With\n * `tail_hint - log_seq_start` (trusted tail entries) this gives the\n * fold's entry count for the ENTRY ceiling `E`. Seeded 0.\n */\n snapshot_rows: number;\n\n /**\n * Optional compactor-stamped mean folded-entry byte size. Maintenance\n * derives live-tail bytes as `entry_count × mean_entry_bytes` without\n * an exact stored counter; absent until first fold.\n */\n mean_entry_bytes?: number;\n\n /**\n * Baseline for rate-limiting the graduation defer-warn off SHARED\n * durable state, not per-isolate memory. The warn fires when the\n * observed/probed tail minus `last_warned_seq` reaches\n * MAINTENANCE_WARN_INTERVAL_WRITES, and that firing CASes\n * `last_warned_seq` to the observed/probed tail. Absent → 0.\n */\n last_warned_seq?: number;\n}\n\n/**\n * Fence-token sub-shape embedded in {@link CurrentJson}. The\n * monotonically-bumped `epoch` is the only safety-critical field —\n * `owner` is informational and may be missing in older records;\n * `claimed_at` is the server response date at claim time, NOT the\n * local clock; `lease_until` is reserved for manual rotation and is not\n * consumed by the current kernel. Log entries are not stamped with this\n * epoch; the fence is dormant authority metadata, not a reader replay\n * filter.\n *\n * Borrowed from FoundationDB's `recoveryCount` on cstate, IsleDB's\n * `writer_fence` on `manifest/CURRENT`, and TigerBeetle's VSR view\n * number. In the earlier two-write commit design, every commit checked\n * the epoch before continuing under `current.json` authority. Under\n * single-write commit no production path reads or writes the fence.\n */\nexport interface WriterFence {\n /**\n * Monotonic unsigned integer. Bumped only by an explicit\n * {@link claimWriter} call — do NOT bump on every cold start, do\n * NOT bump on every commit. Under single-write commit this is retained\n * as an explicit admin/testing primitive only; no production commit\n * path claims or verifies the fence.\n */\n epoch: number;\n\n /**\n * Owner identifier — debug only, NOT consulted for safety.\n * Suggested shape: `<worker_id>@<deploy_id>`. May be the empty\n * string when claim provenance is unknown (e.g. initial\n * creation). Safety derives from `epoch`, not from `owner`.\n */\n owner: string;\n\n /**\n * ISO-8601 timestamp from the `StoragePutResult.serverDate` on\n * the successful CAS PUT. **Never use `new Date()` or\n * `Date.now()` to populate this field** — under multi-instance\n * deployment the local clock may disagree with peers; the\n * server's clock is the only one all instances share. Format\n * via `serverDate.toISOString()`. The empty string `\"\"` means\n * \"claim time unknown\" — readers MUST treat it as such rather\n * than parsing it.\n */\n claimed_at: string;\n\n /**\n * Optional explicit lease horizon, also ISO-8601. Reserved for\n * future manual rotation workflows; current code only writes\n * the field through if a caller supplies it and does not read\n * it.\n */\n lease_until?: string;\n}\n\n/**\n * Return shape from {@link readCurrentJson} et al.: the parsed JSON\n * plus the ETag needed for a follow-up CAS write.\n */\nexport interface CurrentJsonRead {\n readonly json: CurrentJson;\n readonly etag: string;\n}\n\n/**\n * Read + parse `current.json` at `key`. Returns `null` on not-found.\n *\n * @throws BaerlyError{code:\"InvalidResponse\"} — body is not valid\n * JSON, or `schema_version` is unknown, or the shape fails\n * the runtime guard.\n */\nexport async function readCurrentJson(\n storage: Storage,\n key: string,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead | null> {\n const got = await storage.get(key, opts);\n if (got === null) {\n return null;\n }\n const text = new TextDecoder().decode(got.body);\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: body is not valid JSON`,\n error,\n );\n }\n return { json: assertCurrentJson(parsed, key), etag: got.etag };\n}\n\n/**\n * Create `current.json` if-and-only-if it does not exist (S3\n * `If-None-Match: \"*\"`). Use this once per collection at provisioning\n * time; subsequent updates go through {@link casUpdateCurrentJson}.\n *\n * @throws BaerlyError{code:\"Conflict\"} — the key already exists.\n * Caller decides whether to read + reconcile or surface.\n * @throws BaerlyError{code:\"InvalidResponse\"} — `initial` fails the\n * runtime shape guard.\n */\nexport async function createCurrentJson(\n storage: Storage,\n key: string,\n initial: CurrentJson,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n // Catch shape bugs in callers before they hit storage. Cheap.\n assertCurrentJson(initial, key);\n const body = encodeJson(initial);\n const putOpts: StoragePutOptions = {\n ifNoneMatch: \"*\",\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let result: StoragePutResult;\n try {\n result = await storage.put(key, body, putOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n return { json: initial, etag: result.etag };\n}\n\n/**\n * Read-modify-write `current.json` under CAS. The `mutator` receives\n * a deep clone of the current parsed JSON (mutate freely) and returns\n * the new state. The new state is written with `If-Match:\n * <currentEtag>`; on conflict, throws.\n *\n * `mutator` MUST be synchronous and deterministic — it may be called\n * multiple times if the caller wraps this in a retry loop, so it\n * must not have side effects.\n *\n * @throws BaerlyError{code:\"Conflict\"} — another writer landed a write\n * between this function's read and write. Caller decides\n * whether to retry (read + remutate + rewrite).\n * @throws BaerlyError{code:\"InvalidResponse\"} — `key` does not exist\n * (use {@link createCurrentJson} instead) or body doesn't\n * parse / fails the shape guard.\n */\nexport async function casUpdateCurrentJson(\n storage: Storage,\n key: string,\n mutator: (current: CurrentJson) => CurrentJson,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n const existing = await readCurrentJson(storage, key, opts);\n if (existing === null) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key} does not exist; use createCurrentJson first`,\n );\n }\n // Defensive deep clone so a mutator that mutates its argument can't\n // corrupt the original record on the caller's retry path.\n // `structuredClone` is a global on Node ≥17 and Workers; the package\n // targets Node ≥24 so it is safe.\n const next = mutator(structuredClone(existing.json));\n assertCurrentJson(next, key);\n const body = encodeJson(next);\n const putOpts: StoragePutOptions = {\n ifMatch: existing.etag,\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let result: StoragePutResult;\n try {\n result = await storage.put(key, body, putOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n return { json: next, etag: result.etag };\n}\n\n/**\n * Claim ownership of the dormant write fence by bumping `epoch` and\n * stamping `claimed_at` from `StoragePutResult.serverDate`. Under\n * single-write commit there is no production commit-path call site;\n * this is retained for explicit admin/testing workflows and future\n * rotation designs.\n *\n * `owner` is informational — see {@link WriterFence.owner}. Safety\n * derives from the monotonic `epoch`, not from `owner`.\n *\n * Implementation note (two round-trips): because\n * `StoragePutResult.serverDate` is only known *after* the CAS PUT\n * lands, this function writes the record with `claimed_at: \"\"`\n * first, then overwrites itself with the correct\n * `serverDate.toISOString()` in a second CAS. A peer landing between\n * the two writes loses cleanly with `Conflict` — the epoch bump is\n * already durable from the first put either way. If `serverDate` is\n * `undefined` on the first PUT (impl doesn't surface it), the second\n * write is skipped and `claimed_at` remains the empty string;\n * readers MUST treat the empty string as \"unknown claim time\"\n * rather than parsing it.\n *\n * @see {@link ../../../../docs/spec/writer-fence-adversarial-model.md} —\n * the full failure envelope (absent / lying / non-monotonic Date,\n * peer-between-PUTs, bounded clock skew).\n * @see {@link ../../../../docs/spec/writer-fence-adversarial-model.md} —\n * the \"Differentiation from mps3\" subsection that frames the §103\n * non-obviousness story.\n * @see {@link ../../../../docs/spec/prior-art.md} —\n * IDS-shaped prior-art differentiation against mps3, SlateDB,\n * Iceberg, Delta, and the broader S3-leader-election literature.\n *\n * @throws BaerlyError{code:\"Conflict\"} — another writer claimed the\n * fence between this call's read and write. Caller decides\n * whether to retry.\n * @throws BaerlyError{code:\"InvalidResponse\"} — `key` does not exist.\n */\nexport async function claimWriter(\n storage: Storage,\n key: string,\n owner: string,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n const existing = await readCurrentJson(storage, key, opts);\n if (existing === null) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key} does not exist; use createCurrentJson first`,\n );\n }\n const provisional: CurrentJson = {\n ...existing.json,\n writer_fence: {\n epoch: existing.json.writer_fence.epoch + 1,\n owner,\n // Will be overwritten with serverDate.toISOString() once the put\n // returns, when the impl surfaces it. Stays `\"\"` (\"unknown\") if\n // the impl doesn't.\n claimed_at: \"\",\n // Stryker disable next-line ConditionalExpression: `→true` spreads `{lease_until: undefined}` which JSON.stringify omits, so the stored bytes are identical to the normal `→false` path (no key emitted). Genuine equivalent mutant.\n ...(existing.json.writer_fence.lease_until !== undefined && {\n lease_until: existing.json.writer_fence.lease_until,\n }),\n },\n };\n const body = encodeJson(provisional);\n const putOpts: StoragePutOptions = {\n ifMatch: existing.etag,\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let result: StoragePutResult;\n try {\n result = await storage.put(key, body, putOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n // No server clock surfaced — leave `claimed_at` empty. The epoch\n // bump is durable; safety is unaffected.\n if (result.serverDate === undefined) {\n return { json: provisional, etag: result.etag };\n }\n // Stamp the server clock through a second CAS-on-our-own-etag. A\n // peer landing between the two writes loses cleanly with Conflict\n // (the fence is safe — next claim will bump past both).\n const stamped: CurrentJson = {\n ...provisional,\n writer_fence: {\n ...provisional.writer_fence,\n claimed_at: result.serverDate.toISOString(),\n },\n };\n const stampedBody = encodeJson(stamped);\n const stampPutOpts: StoragePutOptions = {\n ifMatch: result.etag,\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let stampResult: StoragePutResult;\n try {\n stampResult = await storage.put(key, stampedBody, stampPutOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n return { json: stamped, etag: stampResult.etag };\n}\n\n/**\n * Read `current.json.log_seq_start` — the low-water mark of the live\n * log range `[log_seq_start, tail_hint)`. The field is always present\n * on disk (every `createCurrentJson` write seeds it; the compactor\n * advances it on every fold); this helper exists to document intent\n * at call sites that walk the log range or assert the snapshot\n * invariants.\n */\nexport const logSeqStartOf = (c: CurrentJson): number => c.log_seq_start;\n\n// ---------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------\n\nconst encodeJson = (json: CurrentJson): Uint8Array => encodeJsonBytes(json);\n\n/**\n * Runtime guard for `parsed` to be a {@link CurrentJson}. Throws\n * `BaerlyError{code:\"InvalidResponse\"}` rather than coercing. Tolerant\n * reader: unknown keys ignored, new required fields bump\n * `schema_version` (move (b), ADR-007).\n */\nconst assertCurrentJson = (parsed: unknown, key: string): CurrentJson => {\n if (parsed === null || typeof parsed !== \"object\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: parsed body is not an object`,\n );\n }\n const r = parsed as Record<string, unknown>;\n if (r[\"schema_version\"] === 1 || r[\"schema_version\"] === 2) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key} is a pre-single-write-commit current.json; re-provision the bucket. Pre-launch, no production buckets — delete and re-seed the local-fs/Minio/Verdaccio scratch bucket, or recreate the R2/S3 bucket.`,\n );\n }\n if (r[\"schema_version\"] !== CURRENT_JSON_SCHEMA_VERSION) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: unsupported schema_version ${String(r[\"schema_version\"])}; this build requires ${CURRENT_JSON_SCHEMA_VERSION}. This almost always means stale scratch data from a different build — wipe the local dev bucket (e.g. \\`rm -rf .baerly-data\\`) or recreate the R2/S3 bucket, then retry.`,\n );\n }\n if (!(typeof r[\"snapshot\"] === \"string\" || r[\"snapshot\"] === null)) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: snapshot must be string|null`,\n );\n }\n // Stryker disable next-line ConditionalExpression,StringLiteral: three equivalent mutants on this line — (1) `typeof r[\"tail_hint\"] !== \"number\"` → false is subsumed by !Number.isInteger (which rejects all non-numbers); (2) `r[\"tail_hint\"] < 0` → false is subsumed by the downstream `log_seq_start > tail_hint` cross-check (log_seq_start ≥ 0, so log_seq_start > negative_tail_hint always fires); (3) StringLiteral \"tail_hint\" → \"\" turns r[\"\"] → undefined → !Number.isInteger(undefined) still true → still throws.\n if (\n typeof r[\"tail_hint\"] !== \"number\" ||\n !Number.isInteger(r[\"tail_hint\"]) ||\n r[\"tail_hint\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: tail_hint must be a non-negative integer`,\n );\n }\n if (\n // Stryker disable next-line ConditionalExpression: `typeof r[\"log_seq_start\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers anyway, making the typeof check fully subsumed.\n typeof r[\"log_seq_start\"] !== \"number\" ||\n !Number.isInteger(r[\"log_seq_start\"]) ||\n r[\"log_seq_start\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: log_seq_start must be a non-negative integer`,\n );\n }\n if (r[\"log_seq_start\"] > r[\"tail_hint\"]) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: log_seq_start ${String(r[\"log_seq_start\"])} > tail_hint ${String(r[\"tail_hint\"])}`,\n );\n }\n const fence = r[\"writer_fence\"];\n if (fence === null || typeof fence !== \"object\") {\n throw new BaerlyError(\"InvalidResponse\", `current.json at ${key}: writer_fence missing`);\n }\n const f = fence as Record<string, unknown>;\n // Stryker disable next-line ConditionalExpression: `typeof f[\"epoch\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof guard fully subsumed.\n if (typeof f[\"epoch\"] !== \"number\" || !Number.isInteger(f[\"epoch\"]) || f[\"epoch\"] < 0) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.epoch must be a non-negative integer`,\n );\n }\n if (typeof f[\"owner\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.owner must be a string`,\n );\n }\n if (typeof f[\"claimed_at\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.claimed_at must be a string`,\n );\n }\n if (f[\"lease_until\"] !== undefined && typeof f[\"lease_until\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.lease_until must be string if present`,\n );\n }\n if (\n // Stryker disable next-line ConditionalExpression: `typeof r[\"snapshot_bytes\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof check fully subsumed.\n typeof r[\"snapshot_bytes\"] !== \"number\" ||\n !Number.isInteger(r[\"snapshot_bytes\"]) ||\n r[\"snapshot_bytes\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: snapshot_bytes must be a non-negative integer`,\n );\n }\n if (\n // Stryker disable next-line ConditionalExpression: `typeof r[\"snapshot_rows\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof check fully subsumed.\n typeof r[\"snapshot_rows\"] !== \"number\" ||\n !Number.isInteger(r[\"snapshot_rows\"]) ||\n r[\"snapshot_rows\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: snapshot_rows must be a non-negative integer`,\n );\n }\n if (\n r[\"last_warned_seq\"] !== undefined &&\n // Stryker disable next-line ConditionalExpression: `typeof r[\"last_warned_seq\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof check fully subsumed.\n (typeof r[\"last_warned_seq\"] !== \"number\" ||\n !Number.isInteger(r[\"last_warned_seq\"]) ||\n r[\"last_warned_seq\"] < 0)\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: last_warned_seq must be a non-negative integer if present`,\n );\n }\n if (\n r[\"mean_entry_bytes\"] !== undefined &&\n // Stryker disable next-line ConditionalExpression: typeof → false is subsumed by !Number.isInteger.\n (typeof r[\"mean_entry_bytes\"] !== \"number\" ||\n !Number.isInteger(r[\"mean_entry_bytes\"]) ||\n r[\"mean_entry_bytes\"] < 0)\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: mean_entry_bytes must be a non-negative integer if present`,\n );\n }\n return parsed as CurrentJson;\n};\n\n/**\n * Wrap a storage-level error with `current.json at <key>` location\n * context. `Conflict` (the storage layer's CAS-lost signal) is\n * re-thrown with an annotated message; other `BaerlyError`s pass\n * through; non-`BaerlyError` falls through as `InvalidResponse` (in\n * practice unreachable — every in-tree `Storage` impl wraps).\n */\nconst translateCasError = (e: unknown, key: string): BaerlyError => {\n if (e instanceof BaerlyError && e.code === \"Conflict\") {\n return new BaerlyError(\"Conflict\", `current.json CAS lost at ${key}: ${e.message}`, e);\n }\n if (e instanceof BaerlyError) {\n return e;\n }\n return new BaerlyError(\"InvalidResponse\", `current.json write at ${key} failed: ${String(e)}`, e);\n};\n"],"mappings":";;;;;;AAKA,MAAa,mBAAmB,UAC9B,IAAI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