@bastani/atomic 0.10.14 → 0.10.15-alpha.1

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 (341) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/_shared/dist-KOELCESV.js +2 -2
  3. package/dist/_shared/fork-row-index-UAUAQRD5.js +2 -2
  4. package/dist/_shared/lib-4PES5P4V.js +2 -2
  5. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js +3 -3
  6. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +3 -3
  7. package/dist/_shared/mode-shared-2QJSCUM6.js +3 -3
  8. package/dist/_shared/p1a-prewarm-XIU57JHF.js +3 -3
  9. package/dist/_shared/runtime-O4KCSG4C.js +2 -2
  10. package/dist/_shared/{sdk-B5LEWGGI.js → sdk-OHKMDJ74.js} +27 -5
  11. package/dist/_shared/{sdk-B5LEWGGI.js.map → sdk-OHKMDJ74.js.map} +1 -1
  12. package/dist/_shared/session-data-AHTU7IS6.js +2 -2
  13. package/dist/_shared/startup-0-0-Q3MWKUK4.js +2 -2
  14. package/dist/_shared/startup-0-1-M6OWAYHH.js +2 -2
  15. package/dist/_shared/{startup-0-2-5QHPCEON.js → startup-0-2-2HUMCPKX.js} +14 -16
  16. package/dist/_shared/startup-0-2-2HUMCPKX.js.map +1 -0
  17. package/dist/_shared/startup-0-3-4ZYBYQNM.js +3 -3
  18. package/dist/_shared/startup-0-4-ZMJV547D.js +3 -3
  19. package/dist/_shared/startup-0-5-YDW47QX6.js +3 -3
  20. package/dist/_shared/startup-10-0-TDQNBDDL.js +3 -3
  21. package/dist/_shared/startup-14-0-MLX36RBG.js +1 -1
  22. package/dist/_shared/startup-15-0-YUKGAC63.js +1 -1
  23. package/dist/_shared/startup-15-1-4S7FLMNG.js +6 -30
  24. package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
  25. package/dist/_shared/startup-8-0-34CBHPZH.js +3 -3
  26. package/dist/_shared/startup-8-1-LZFXSD3Z.js +3 -3
  27. package/dist/_shared/storage-command-7MGXLJGZ.js +2 -2
  28. package/dist/_shared/storage-status-K7PX2RXA.js +3 -3
  29. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  30. package/dist/_shared/tree-outline-MUEPK5B7.js +2 -2
  31. package/dist/builtin/intercom/index.bundle.mjs +1 -1
  32. package/dist/builtin/intercom/package.json +1 -1
  33. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  34. package/dist/builtin/mcp/package.json +1 -1
  35. package/dist/builtin/subagents/package.json +1 -1
  36. package/dist/builtin/subagents/src/extension/index.bundle.mjs +1 -1
  37. package/dist/builtin/web-access/index.bundle.mjs +1 -1
  38. package/dist/builtin/web-access/package.json +1 -1
  39. package/dist/cli/auth-cli.code.js +1 -1
  40. package/dist/cli/auth-cli.impl.js +3 -3
  41. package/dist/cli/auth-cli.js +3 -3
  42. package/dist/cli/blueprint-command.impl.js +3 -3
  43. package/dist/cli/blueprint-command.js +3 -3
  44. package/dist/cli/intercom-command.code.js +3 -3
  45. package/dist/cli/intercom-command.impl.js +3 -3
  46. package/dist/cli/intercom-command.js +3 -3
  47. package/dist/cli/list-models.impl.js +3 -3
  48. package/dist/cli/list-models.js +3 -3
  49. package/dist/cli/session-picker.code.js +1 -1
  50. package/dist/cli/session-picker.impl.js +3 -3
  51. package/dist/cli/session-picker.js +3 -3
  52. package/dist/cli/startup-ui.code.js +1 -1
  53. package/dist/cli/startup-ui.impl.js +3 -3
  54. package/dist/cli/startup-ui.js +3 -3
  55. package/dist/cli/storage-command.impl.js +3 -3
  56. package/dist/cli/storage-command.js +3 -3
  57. package/dist/cli/storage-search-session.code.js +1 -1
  58. package/dist/cli/storage-search-session.impl.js +3 -3
  59. package/dist/cli/storage-search-session.js +3 -3
  60. package/dist/cli/team-command.code.js +1 -1
  61. package/dist/cli/team-command.impl.js +3 -3
  62. package/dist/cli/team-command.js +3 -3
  63. package/dist/cli.js +2 -2
  64. package/dist/core/compaction/compactor.d.ts +0 -8
  65. package/dist/core/debug.impl.js +3 -3
  66. package/dist/core/debug.js +3 -3
  67. package/dist/core/export-html/card-projection.impl.js +3 -3
  68. package/dist/core/export-html/card-projection.js +3 -3
  69. package/dist/core/export-html/index.code.js +2 -2
  70. package/dist/core/export-html/index.impl.js +3 -3
  71. package/dist/core/export-html/index.js +3 -3
  72. package/dist/core/export-html/json-spans.impl.js +3 -3
  73. package/dist/core/export-html/json-spans.js +3 -3
  74. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  75. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  76. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  77. package/dist/core/export-html/tool-renderer.js +3 -3
  78. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  79. package/dist/core/extensions/jiti-loader.js +3 -3
  80. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  81. package/dist/core/extensions/jiti-static-loader.js +3 -3
  82. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  83. package/dist/core/extensions/loader-host-modules.js +3 -3
  84. package/dist/core/intercom-broker-control-host.code.js +1 -1
  85. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  86. package/dist/core/intercom-broker-control-host.js +3 -3
  87. package/dist/core/intercom-broker-control.code.js +2 -2
  88. package/dist/core/intercom-broker-control.impl.js +3 -3
  89. package/dist/core/intercom-broker-control.js +3 -3
  90. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  91. package/dist/core/package-manager-storage-adapters.js +3 -3
  92. package/dist/core/sdk.code.js +1 -1
  93. package/dist/core/sdk.impl.js +3 -3
  94. package/dist/core/sdk.js +3 -3
  95. package/dist/core/session-manager-core.js +3 -3
  96. package/dist/core/session-manager-list.impl.js +3 -3
  97. package/dist/core/session-manager-list.js +3 -3
  98. package/dist/core/session-manager.impl.js +3 -3
  99. package/dist/core/session-manager.js +3 -3
  100. package/dist/core/session-storage.impl.js +3 -3
  101. package/dist/core/session-storage.js +3 -3
  102. package/dist/core/storage/index.js +2 -2
  103. package/dist/core/storage/node-sqlite-thread.js +2 -2
  104. package/dist/core/storage/node-sqlite.js +2 -2
  105. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  106. package/dist/core/storage/offline-snapshot-file.js +3 -3
  107. package/dist/core/storage/provider.js +2 -2
  108. package/dist/core/storage/selection.js +2 -2
  109. package/dist/core/storage/session/branch-fork-source.code.js +2 -2
  110. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  111. package/dist/core/storage/session/branch-fork-source.js +3 -3
  112. package/dist/core/storage/session/card-view.impl.js +3 -3
  113. package/dist/core/storage/session/card-view.js +3 -3
  114. package/dist/core/storage/session/child-reader.code.js +2 -2
  115. package/dist/core/storage/session/child-reader.impl.js +3 -3
  116. package/dist/core/storage/session/child-reader.js +3 -3
  117. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  118. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  119. package/dist/core/storage/session/expanded-child-details.code.js +2 -2
  120. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  121. package/dist/core/storage/session/expanded-child-details.js +3 -3
  122. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  123. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  124. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  125. package/dist/core/storage/session/fork-row-index.js +3 -3
  126. package/dist/core/storage/session/fork-staging.code.js +1 -1
  127. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  128. package/dist/core/storage/session/fork-staging.js +3 -3
  129. package/dist/core/storage/session/fork-window.code.js +2 -2
  130. package/dist/core/storage/session/fork-window.impl.js +3 -3
  131. package/dist/core/storage/session/fork-window.js +3 -3
  132. package/dist/core/storage/session/history-pages.impl.js +3 -3
  133. package/dist/core/storage/session/history-pages.js +3 -3
  134. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  135. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  136. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  137. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  138. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  139. package/dist/core/storage/session/memory-session-store.js +3 -3
  140. package/dist/core/storage/session/pinned-branch-resume.code.js +2 -2
  141. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  142. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  143. package/dist/core/storage/session/released-history-files.code.js +1 -1
  144. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  145. package/dist/core/storage/session/released-history-files.js +3 -3
  146. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  147. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  148. package/dist/core/storage/session/session-resume.impl.js +3 -3
  149. package/dist/core/storage/session/session-resume.js +3 -3
  150. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  151. package/dist/core/storage/session/snapshot-cut.js +3 -3
  152. package/dist/core/storage/session/snapshot-history.code.js +2 -2
  153. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  154. package/dist/core/storage/session/snapshot-history.js +3 -3
  155. package/dist/core/storage/session/sql-session-store.code.js +1 -1
  156. package/dist/core/storage/session/sql-session-store.impl.js +3 -3
  157. package/dist/core/storage/session/sql-session-store.js +3 -3
  158. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  159. package/dist/core/storage/session/tree-outline.js +3 -3
  160. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  161. package/dist/core/storage/session/tree-presentation.js +3 -3
  162. package/dist/core/storage/storage-status.impl.js +3 -3
  163. package/dist/core/storage/storage-status.js +3 -3
  164. package/dist/core/storage/team.impl.js +3 -3
  165. package/dist/core/storage/team.js +3 -3
  166. package/dist/core/structured-output/index.code.js +1 -1
  167. package/dist/core/structured-output/index.impl.js +3 -3
  168. package/dist/core/structured-output/index.js +3 -3
  169. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  170. package/dist/core/tasks/task-completion-entry.js +3 -3
  171. package/dist/core/tasks/task-file-history.code.js +2 -2
  172. package/dist/core/tasks/task-file-history.impl.js +3 -3
  173. package/dist/core/tasks/task-file-history.js +3 -3
  174. package/dist/core/tasks/task-reference-archive.code.js +2 -2
  175. package/dist/core/tasks/task-reference-archive.js +3 -3
  176. package/dist/core/tasks/task-reference-identity.js +3 -3
  177. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  178. package/dist/core/tasks/task-reference-stream.js +3 -3
  179. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  180. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  181. package/dist/core/tasks/task-view-source.impl.js +3 -3
  182. package/dist/core/tasks/task-view-source.js +3 -3
  183. package/dist/core/tools/read-url.impl.js +3 -3
  184. package/dist/core/tools/read-url.js +3 -3
  185. package/dist/core/worktree-snapshot/blob-store.js +2 -2
  186. package/dist/core/worktree-snapshot/errors.code.js +1 -1
  187. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  188. package/dist/core/worktree-snapshot/errors.js +3 -3
  189. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  190. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  191. package/dist/extensions/codemode/execute.impl.js +3 -3
  192. package/dist/extensions/codemode/execute.js +3 -3
  193. package/dist/extensions/codemode/renderer.impl.js +3 -3
  194. package/dist/extensions/codemode/renderer.js +3 -3
  195. package/dist/extensions/mcp/cli.code.js +1 -1
  196. package/dist/extensions/mcp/cli.impl.js +3 -3
  197. package/dist/extensions/mcp/cli.js +3 -3
  198. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  199. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  200. package/dist/extensions/mcp/cli.lazy.js +3 -3
  201. package/dist/extensions/mcp/runtime.code.js +1 -1
  202. package/dist/extensions/mcp/runtime.impl.js +3 -3
  203. package/dist/extensions/mcp/runtime.js +3 -3
  204. package/dist/index.d.ts +21 -1
  205. package/dist/index.js +2 -2
  206. package/dist/main-first-time-setup.code.js +1 -1
  207. package/dist/main-first-time-setup.impl.js +3 -3
  208. package/dist/main-first-time-setup.js +3 -3
  209. package/dist/modes/interactive/components/stored-tree-view.code.js +2 -2
  210. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  211. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  212. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  213. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  214. package/dist/modes/print-mode.js +1 -1
  215. package/dist/package-manager-cli.code.js +2 -2
  216. package/dist/package-manager-cli.impl.js +3 -3
  217. package/dist/package-manager-cli.js +3 -3
  218. package/dist/startup-files.json +1 -1
  219. package/dist/startup-stages/6.js +1 -1
  220. package/dist/utils/startup-database-spare.code.js +1 -1
  221. package/dist/utils/startup-database-spare.impl.js +3 -3
  222. package/dist/utils/startup-database-spare.js +3 -3
  223. package/dist/utils/tools-manager.impl.js +3 -3
  224. package/dist/utils/tools-manager.js +3 -3
  225. package/docs/background-tasks/reference.md +182 -0
  226. package/docs/background-tasks.md +98 -405
  227. package/docs/build.md +67 -27
  228. package/docs/changelog.mdx +1 -1
  229. package/docs/codemode.md +108 -39
  230. package/docs/compaction/branch-summaries.md +54 -0
  231. package/docs/compaction/custom-compactors.md +161 -0
  232. package/docs/compaction/memory-compaction.md +77 -0
  233. package/docs/compaction/reference.md +86 -38
  234. package/docs/compaction.md +51 -252
  235. package/docs/computer-use.md +169 -321
  236. package/docs/containerization.md +71 -57
  237. package/docs/custom-provider/api-reference.md +119 -25
  238. package/docs/custom-provider/oauth.md +114 -132
  239. package/docs/custom-provider/override.md +37 -27
  240. package/docs/custom-provider/registration.md +107 -83
  241. package/docs/custom-provider/streaming.md +85 -71
  242. package/docs/custom-provider.md +85 -52
  243. package/docs/development.md +39 -29
  244. package/docs/docs.json +76 -63
  245. package/docs/environment-variables.md +94 -44
  246. package/docs/extensions/api-reference.md +86 -43
  247. package/docs/extensions/authoring.md +162 -154
  248. package/docs/extensions/events.md +80 -25
  249. package/docs/extensions/examples.md +90 -85
  250. package/docs/extensions/ui.md +206 -82
  251. package/docs/extensions.md +79 -108
  252. package/docs/getting-started/authentication.md +67 -36
  253. package/docs/getting-started/first-session.md +53 -43
  254. package/docs/getting-started/installation.md +116 -89
  255. package/docs/getting-started/project-instructions.md +48 -34
  256. package/docs/guides/configuration.md +82 -20
  257. package/docs/guides/non-interactive.md +66 -24
  258. package/docs/guides/resume-on-any-machine.md +135 -82
  259. package/docs/guides/team-setup.md +114 -105
  260. package/docs/guides.md +76 -32
  261. package/docs/herdr.md +15 -16
  262. package/docs/how-atomic-works.md +140 -0
  263. package/docs/index.md +58 -44
  264. package/docs/intercom/operations.md +141 -151
  265. package/docs/intercom/reference.md +85 -108
  266. package/docs/intercom.md +84 -145
  267. package/docs/json.md +120 -67
  268. package/docs/keybindings.md +85 -49
  269. package/docs/libraries/agent-core.md +137 -275
  270. package/docs/libraries/ai.md +100 -84
  271. package/docs/libraries/codemode.md +210 -300
  272. package/docs/libraries/schema.md +59 -53
  273. package/docs/libraries/storage-postgres.md +49 -35
  274. package/docs/libraries/telemetry.md +153 -354
  275. package/docs/libraries/tui.md +265 -393
  276. package/docs/libraries.md +42 -26
  277. package/docs/llama-cpp.md +171 -161
  278. package/docs/mcp-servers.md +90 -51
  279. package/docs/models/choose-a-model.md +188 -0
  280. package/docs/models/reference.md +74 -30
  281. package/docs/models.md +153 -88
  282. package/docs/orchestration/migrating-workflows.md +23 -16
  283. package/docs/orchestration/patterns.md +39 -44
  284. package/docs/orchestration.md +65 -26
  285. package/docs/packages/authoring.md +51 -29
  286. package/docs/packages/reference.md +42 -21
  287. package/docs/packages.md +69 -58
  288. package/docs/programmatic.md +118 -24
  289. package/docs/prompt-templates.md +84 -83
  290. package/docs/providers/reference.md +43 -48
  291. package/docs/providers.md +219 -451
  292. package/docs/quickstart.md +140 -120
  293. package/docs/reference/cli.md +135 -97
  294. package/docs/reference.md +20 -18
  295. package/docs/rpc/examples.md +76 -20
  296. package/docs/rpc/extension-ui.md +64 -38
  297. package/docs/rpc/protocol.md +361 -110
  298. package/docs/rpc.md +57 -17
  299. package/docs/sdk/reference.md +409 -534
  300. package/docs/sdk/storage.md +53 -13
  301. package/docs/sdk/structured-decisions.md +82 -56
  302. package/docs/sdk/web-server.md +57 -43
  303. package/docs/sdk.md +106 -84
  304. package/docs/security.md +42 -64
  305. package/docs/session-format.md +62 -38
  306. package/docs/sessions.md +99 -214
  307. package/docs/settings.md +165 -195
  308. package/docs/shell-aliases.md +9 -6
  309. package/docs/skills/authoring.md +69 -48
  310. package/docs/skills/reference.md +51 -20
  311. package/docs/skills.md +99 -148
  312. package/docs/slash-commands.md +129 -0
  313. package/docs/storage/custom-adapters.md +160 -85
  314. package/docs/storage/jsonl.md +81 -66
  315. package/docs/storage/postgres/pgbouncer.md +120 -126
  316. package/docs/storage/postgres/tuning.md +120 -143
  317. package/docs/storage/postgres.md +314 -330
  318. package/docs/storage/sqlite.md +71 -42
  319. package/docs/storage.md +298 -302
  320. package/docs/subagents/authoring.md +55 -38
  321. package/docs/subagents/reference.md +73 -33
  322. package/docs/subagents.md +119 -187
  323. package/docs/terminal-setup.md +50 -38
  324. package/docs/termux.md +67 -41
  325. package/docs/themes/reference.md +23 -19
  326. package/docs/themes.md +142 -127
  327. package/docs/tmux.md +47 -55
  328. package/docs/tools.md +147 -109
  329. package/docs/tui/reference.md +166 -214
  330. package/docs/tui.md +196 -341
  331. package/docs/usage.md +118 -138
  332. package/docs/verification.md +79 -51
  333. package/docs/web-access.md +121 -101
  334. package/docs/windows.md +26 -27
  335. package/docs/worktree-snapshots/reference.md +245 -0
  336. package/docs/worktree-snapshots.md +71 -259
  337. package/package.json +8 -8
  338. package/dist/_shared/startup-0-2-5QHPCEON.js.map +0 -1
  339. package/docs/guides/intercom.md +0 -32
  340. package/docs/guides/orchestration.md +0 -28
  341. package/docs/guides/subagents.md +0 -37
@@ -4,19 +4,15 @@ sidebarTitle: "@bastani/atomic-telemetry"
4
4
  description: "Vendor-neutral telemetry contracts, no-op and in-memory contexts, metrics, trace rendering, and typed telemetry schemas."
5
5
  ---
6
6
 
7
- Vendor-neutral telemetry contracts and typed schema utilities for Atomic's libraries. This package contains no exporter and sends nothing on its own; you supply the adapter. See [Standalone libraries](/libraries) for all standalone packages.
7
+ Vendor-neutral telemetry contracts and typed schema utilities for Atomic's libraries. This package contains no exporter and sends nothing on its own; you supply the adapter for OpenTelemetry, Sentry, logs, or another backend. See [Standalone libraries](/libraries) for all standalone packages.
8
8
 
9
- This package provides:
9
+ Key capabilities:
10
10
 
11
- - An explicit, callback-based `TelemetryContext` and `TelemetrySpan` contract.
12
- - A shared `NOOP_TELEMETRY_CONTEXT`.
13
- - Opaque cross-process propagation and span links.
14
- - Counters, up-down counters, histograms, and typed metric schemas.
15
- - A reference `InMemoryTelemetryContext` implementation.
16
- - Serializable schema definitions with inferred TypeScript types.
17
- - No exporter, global current-span state, or dependency on a telemetry backend.
18
-
19
- Applications can use the in-memory reference or supply an adapter for OpenTelemetry, Sentry, logs, or another backend. Atomic's packages pass telemetry contexts explicitly and define their domain schemas separately.
11
+ - Explicit, callback-based `TelemetryContext` and `TelemetrySpan` contracts with zero ambient global state.
12
+ - Shared `NOOP_TELEMETRY_CONTEXT`, `NOOP_TELEMETRY_METRICS`, and `NOOP_TELEMETRY_PROPAGATION`.
13
+ - Opaque cross-process propagation (`TelemetryCarrier`) and span links.
14
+ - Counters, up-down counters, histograms, and compile-time typed metric and span schemas.
15
+ - Reference `InMemoryTelemetryContext` adapter, `TelemetryStore` queries, trace tree renderer, and conformance test suite.
20
16
 
21
17
  ## Installation
22
18
 
@@ -28,26 +24,26 @@ npm install @bastani/atomic-telemetry
28
24
 
29
25
  ```typescript
30
26
  import {
31
- InMemoryTelemetryContext,
32
- NOOP_TELEMETRY_CONTEXT,
33
- type TelemetryContext,
27
+ InMemoryTelemetryContext,
28
+ NOOP_TELEMETRY_CONTEXT,
29
+ type TelemetryContext,
34
30
  } from "@bastani/atomic-telemetry";
35
31
  import { renderTrace } from "@bastani/atomic-telemetry/render";
36
32
 
37
33
  const accounts = new Map<string, { id: string; plan: string }>([["acct-1", { id: "acct-1", plan: "pro" }]]);
38
34
 
39
35
  async function loadAccount(accountId: string, telemetry: TelemetryContext = NOOP_TELEMETRY_CONTEXT) {
40
- return telemetry.startSpan(
41
- {
42
- name: "example.account.load",
43
- attributes: { "example.account.id": accountId },
44
- },
45
- async (span) => {
46
- const account = accounts.get(accountId);
47
- span.setAttributes({ "example.account.found": account !== undefined });
48
- return account;
49
- },
50
- );
36
+ return telemetry.startSpan(
37
+ {
38
+ name: "example.account.load",
39
+ attributes: { "example.account.id": accountId },
40
+ },
41
+ async (span) => {
42
+ const account = accounts.get(accountId);
43
+ span.setAttributes({ "example.account.found": account !== undefined });
44
+ return account;
45
+ },
46
+ );
51
47
  }
52
48
 
53
49
  const recorder = new InMemoryTelemetryContext();
@@ -59,18 +55,14 @@ if (traces[0]) console.log(renderTrace(traces[0].spans));
59
55
 
60
56
  ## Telemetry concepts
61
57
 
62
- Telemetry describes what a program did while running using spans, attributes, events, statuses, and explicit context:
63
-
64
58
  | Concept | Plain-language meaning |
65
- |---|---|
66
- | **Span** | A timed record of one operation, such as loading an account or making an AI request. It begins before the work and ends when the work finishes. |
67
- | **Parent and child spans** | Operations can contain smaller operations. A request span might contain a cache lookup and a database query. Together they form a tree showing where time was spent. |
68
- | **Attribute** | A named fact attached to a span, such as `provider: "openai"`, `cache.hit: true`, or `item_count: 12`. Attributes describe the operation and its result. |
69
- | **Event** | A named occurrence at a point during a span, such as `retry.scheduled` or `cache.lookup`. Events have no duration and may carry their own attributes. |
70
- | **Status** | The operation's outcome: `ok` or `error`. An error status may include an error name and message. |
71
- | **Context** | A handle identifying where new work belongs in the span tree. Starting a span from a context makes it a child of that context. |
72
-
73
- For example, loading an account produces this structure:
59
+ | --- | --- |
60
+ | **Span** | A timed record of one operation, starting before the work and ending when it settles. |
61
+ | **Parent and child spans** | Operations can nest inside one another, forming a tree showing where time was spent. |
62
+ | **Attribute** | A named fact attached to a span, such as `provider: "openai"` or `cache.hit: true`. |
63
+ | **Event** | A point-in-time occurrence inside a span (such as `retry.scheduled`), optionally carrying its own attributes. |
64
+ | **Status** | The final outcome: `ok` or `error` (optionally with an error name and message). |
65
+ | **Context** | A handle identifying where new child spans belong in the span tree. |
74
66
 
75
67
  ```text
76
68
  example.account.load span
@@ -80,57 +72,26 @@ example.account.load span
80
72
  └─ status: ok final outcome
81
73
  ```
82
74
 
83
- A span is diagnostic data, not business state. An adapter translates these generic concepts into the corresponding concepts used by OpenTelemetry, Sentry, logs, or another backend.
84
-
85
75
  ## Core context API
86
76
 
87
- A `TelemetryContext` starts a span around a callback. The callback receives a `TelemetrySpan`, which is also the explicit parent context for child spans. Contexts may expose their adapter's `metrics?: TelemetryMetrics` and `propagation?: TelemetryPropagation` capabilities, and child spans and extracted parents carry the same capabilities. A tracing adapter that implements only `startSpan()` is still valid.
88
-
89
- ```typescript
90
- import {
91
- NOOP_TELEMETRY_CONTEXT,
92
- type TelemetryContext,
93
- } from '@bastani/atomic-telemetry';
94
-
95
- async function loadAccount(
96
- accountId: string,
97
- telemetryContext: TelemetryContext = NOOP_TELEMETRY_CONTEXT,
98
- ) {
99
- return telemetryContext.startSpan(
100
- {
101
- name: 'example.account.load',
102
- attributes: { 'example.account.id': accountId },
103
- },
104
- async (span) => {
105
- const account = await readAccount(accountId);
106
- span.setAttributes({ 'example.account.found': account !== undefined });
107
- return account;
108
- },
109
- );
110
- }
111
- ```
112
-
113
- Pass the callback span to lower-level work to create explicit nesting:
77
+ `TelemetryContext.startSpan()` starts a span around a callback. The callback receives a `TelemetrySpan` that also serves as the explicit parent context for nested child spans. Contexts may expose optional `metrics?: TelemetryMetrics` and `propagation?: TelemetryPropagation` capabilities, inherited by child spans and extracted parents.
114
78
 
115
79
  ```typescript
116
- return telemetryContext.startSpan({ name: 'example.parent' }, async (parentSpan) => {
117
- return parentSpan.startSpan({ name: 'example.child' }, async (childSpan) => {
118
- childSpan.addEvent('example.cache.lookup', { 'example.cache.hit': true });
80
+ return telemetryContext.startSpan({ name: "example.parent" }, async (parentSpan) => {
81
+ return parentSpan.startSpan({ name: "example.child" }, async (childSpan) => {
82
+ childSpan.addEvent("example.cache.lookup", { "example.cache.hit": true });
119
83
  return performWork();
120
84
  });
121
85
  });
122
86
  ```
123
87
 
124
- There is no public `end()` method. `startSpan()` owns settlement and keeps the span open until the callback's value or promise settles. For an expected failure represented by a normal return value, set the status explicitly:
88
+ There is no public `end()` method—`startSpan()` settles the span automatically when the callback returns, resolves, throws, or rejects. For expected failures returned normally, set the status explicitly:
125
89
 
126
90
  ```typescript
127
- return telemetryContext.startSpan({ name: 'example.save' }, async (span) => {
91
+ return telemetryContext.startSpan({ name: "example.save" }, async (span) => {
128
92
  const result = await save();
129
93
  if (!result.ok) {
130
- span.setStatus({
131
- status: 'error',
132
- error: { name: 'SaveError', message: result.reason },
133
- });
94
+ span.setStatus({ status: "error", error: { name: "SaveError", message: result.reason } });
134
95
  }
135
96
  return result;
136
97
  });
@@ -138,25 +99,19 @@ return telemetryContext.startSpan({ name: 'example.save' }, async (span) => {
138
99
 
139
100
  ## Adapter contract
140
101
 
141
- An adapter implements `TelemetryContext` and bridges the generic API to its backend. Typed inputs are trusted, and malformed inputs have unspecified behavior. Adapters are not required to validate inputs or suppress backend failures.
142
-
143
- The callback and recording contract requires an adapter to:
102
+ Adapters implement `TelemetryContext` and bridge it to a backend. Typed inputs are trusted (adapters do not need to validate inputs or suppress backend errors). Required behaviors:
144
103
 
145
104
  - Create a child span and invoke the callback synchronously, exactly once.
146
- - Expose optional metric and propagation capabilities on its contexts, child spans, and extracted parents, including inert fallback spans.
147
- - Preserve the callback's return value and rejection value, returning a rejected promise with the same error after a synchronous throw.
148
- - Keep the native span open until a returned promise settles.
149
- - Treat normal completion as `ok` and throws or rejections as errors unless an explicit status was set.
150
- - Make repeated `setStatus()` calls last-write-wins.
151
- - Merge `setAttributes()` calls so later defined values replace earlier ones while `undefined` is ignored.
152
- - Make recording methods synchronous.
153
- - Ignore calls made after settlement.
105
+ - Preserve return values and rejections, converting synchronous throws to rejected promises with the same error.
106
+ - Keep the native span open until any returned promise settles; mark normal completion `ok` and throws/rejections `error` unless `setStatus()` was explicitly called.
107
+ - Make `setStatus()` last-write-wins, merge `setAttributes()` (later defined values replace earlier ones; `undefined` is ignored), keep recording methods synchronous, and ignore calls after settlement.
108
+ - Propagate optional `metrics` and `propagation` capabilities onto child spans, extracted parents, and inert fallback spans.
154
109
 
155
- Adapters may activate backend ambient context for automatic instrumentation, while callers pass the parent through `TelemetryContext` arguments. Adapters own exporter buffering, flushing, sampling, backend IDs, and backend-specific context objects. Run the [adapter conformance suite](#adapter-conformance) to verify adapter behavior.
110
+ Run the [adapter conformance suite](#adapter-conformance) to verify any custom adapter.
156
111
 
157
112
  ## Propagation and span links
158
113
 
159
- An adapter may also implement `TelemetryPropagation`. Expose it through `context.propagation` so code can inject or extract using the context it already has. The root, spans, and extracted parents share the adapter's capability object:
114
+ Expose optional cross-process propagation via `context.propagation`:
160
115
 
161
116
  ```typescript
162
117
  interface TelemetryPropagation {
@@ -166,27 +121,27 @@ interface TelemetryPropagation {
166
121
  type TelemetryCarrier = Record<string, string>;
167
122
  ```
168
123
 
169
- A carrier is an opaque JSON-safe string map. Adapters own its format; W3C `traceparent` and `tracestate` fit without requiring them. Transport code sends only the carrier, never a context or span:
124
+ Carriers are opaque JSON-safe string maps (for example W3C `traceparent`/`tracestate`). Transport code sends only the carrier, never a context or span:
170
125
 
171
126
  ```typescript
172
127
  const caller = new InMemoryTelemetryContext();
173
128
  const provider = new InMemoryTelemetryContext();
174
- await caller.startSpan({ name: 'rpc.client' }, async (span) => {
129
+ await caller.startSpan({ name: "rpc.client" }, async (span) => {
175
130
  const wire = JSON.stringify(caller.inject(span));
176
131
  await provider.extract(JSON.parse(wire)).startSpan(
177
- { name: 'rpc.server' },
132
+ { name: "rpc.server" },
178
133
  (serverSpan) => handleRequest(serverSpan),
179
134
  );
180
135
  });
181
136
  ```
182
137
 
183
- Injection returns a detached carrier or `undefined` for roots, no-op contexts, and unsupported contexts. Extraction returns a receiver-owned parent. Absent or unknown carriers fall back to the adapter's root. Extraction checks only that required carrier keys contain strings; identifiers are opaque and need no format validation. Both methods are synchronous. Trace metadata is diagnostics, never authorization. Transport boundaries own carrier size limits.
138
+ `inject()` returns a detached carrier (or `undefined` for roots, no-op contexts, or unsupported contexts). `extract()` returns a receiver-owned parent, falling back to the adapter's root for absent or unknown carriers.
184
139
 
185
- A link relates work without changing its parent. Use `SpanOptions.links` when the target is known at creation, or `span.addLink()` after the span has started:
140
+ Relate spans without changing parentage via `SpanOptions.links` (at creation) or `span.addLink()` (while active):
186
141
 
187
142
  ```typescript
188
143
  await telemetry.startSpan(
189
- { name: 'activation', links: [{ context: firstGetter, attributes: { reason: 'trigger' } }] },
144
+ { name: "activation", links: [{ context: firstGetter, attributes: { reason: "trigger" } }] },
190
145
  async (activation) => {
191
146
  laterGetter.addLink({ context: activation });
192
147
  await activate();
@@ -194,53 +149,46 @@ await telemetry.startSpan(
194
149
  );
195
150
  ```
196
151
 
197
- Link targets are `TelemetryContext` handles, including spans and extracted remote parents. For a remote link, first call `adapter.extract(carrier)`. A settled target remains linkable and injectable; a settled source ignores `addLink()`. Links append in order, copy attributes, and ignore root, no-op, or unsupported contexts. The typed span starter's callback also supports `addLink()`; initial links use the low-level `startSpan()` API.
198
-
199
- `NOOP_TELEMETRY_PROPAGATION` ignores its arguments: injection returns `undefined`, extraction returns `NOOP_TELEMETRY_CONTEXT`.
152
+ Settled targets remain linkable and injectable; settled sources ignore `addLink()`. `NOOP_TELEMETRY_PROPAGATION` returns `undefined` from `inject()` and `NOOP_TELEMETRY_CONTEXT` from `extract()`.
200
153
 
201
154
  ## Metrics
202
155
 
203
- An adapter may implement `TelemetryMetrics` alongside `TelemetryContext` and `TelemetryPropagation`. Applications configure one adapter, not separate backends for each capability. Expose the shared capability through `context.metrics`; child spans retain it, so nested model calls can record metrics without a separate configuration option. The in-memory adapter also implements the factory methods directly:
156
+ Expose optional metrics via `context.metrics` so nested calls can record measurements without separate configuration:
204
157
 
205
158
  ```typescript
206
- const bytes = telemetry.counter('network.bytes', {
207
- description: 'Encoded WebSocket bytes', unit: 'By',
208
- });
209
- bytes.add(encodedSize, { direction: 'out' });
159
+ const bytes = telemetry.counter("network.bytes", { description: "Encoded WebSocket bytes", unit: "By" });
160
+ bytes.add(encodedSize, { direction: "out" });
210
161
 
211
- const active = telemetry.upDownCounter('calls.active');
162
+ const active = telemetry.upDownCounter("calls.active");
212
163
  active.add(1);
213
164
  active.add(-1);
214
165
 
215
- const duration = telemetry.histogram('call.duration', {
216
- unit: 'ms', boundaries: [1, 10, 100, 1000],
217
- });
218
- duration.record(elapsedMs, { method: 'read' }, currentSpan);
166
+ const duration = telemetry.histogram("call.duration", { unit: "ms", boundaries: [1, 10, 100, 1000] });
167
+ duration.record(elapsedMs, { method: "read" }, currentSpan);
219
168
  ```
220
169
 
221
- Factories take an instrument name and optional `InstrumentOptions` (`description`, `unit`). Histograms also accept `HistogramOptions.boundaries` for finite, strictly increasing bucket hints. Backends own aggregation and may translate these hints.
222
-
223
- Callers must supply finite measurements and non-negative counter increments, while up-down counters and histograms accept signed values. Histogram `record(value, attributes?, context?)` optionally correlates a measurement with a span as an exemplar. Counter `add(value, attributes?)` takes no context argument.
224
-
225
- Factories and recording methods are synchronous and trust typed inputs. Adapters do not need to validate measurement values, metadata, attributes, or boundaries, and malformed inputs have unspecified behavior. `NOOP_TELEMETRY_METRICS` returns shared frozen instruments that discard measurements. Record only values already available to application code; do not serialize or measure extra data solely for telemetry.
226
-
227
- Use only low-cardinality attributes with bounded values such as direction or method, rather than request IDs, user IDs, prompts, or arbitrary paths. The low-level attribute bag remains open, so instrumentation code enforces this policy.
170
+ Supply finite values and non-negative counter increments (up-down counters and histograms accept signed values). `histogram.record(value, attributes?, context?)` optionally attaches a span exemplar. Keep metric attributes strictly low-cardinality (direction, method, provider—never request IDs, user IDs, prompts, or arbitrary paths).
228
171
 
229
172
  ### Typed metric schemas
230
173
 
231
- `TelemetrySchemaDefinition.metrics` optionally declares instrument names, kinds, metadata, and required/optional attributes. `createTypedMetrics()` combines one or more schemas and rejects duplicate metric names, incorrect instrument kinds, unknown attributes, and missing required attributes at compile time:
174
+ Declare metrics inside `TelemetrySchemaDefinition.metrics` and bind them with `createTypedMetrics()` for compile-time validation of names, kinds, and low-cardinality attributes:
232
175
 
233
176
  ```typescript
234
177
  const schema = defineTelemetrySchema({
235
178
  version: 1,
236
179
  spans: {},
237
180
  metrics: {
238
- 'network.bytes': {
239
- kind: 'counter', description: 'Encoded bytes', unit: 'By',
181
+ "network.bytes": {
182
+ kind: "counter",
183
+ description: "Encoded bytes",
184
+ unit: "By",
240
185
  attributes: {
241
186
  direction: {
242
- type: 'string', required: true, values: ['in', 'out'],
243
- description: 'Direction', cardinality: 'low',
187
+ type: "string",
188
+ required: true,
189
+ values: ["in", "out"],
190
+ description: "Direction",
191
+ cardinality: "low",
244
192
  },
245
193
  },
246
194
  },
@@ -248,93 +196,45 @@ const schema = defineTelemetrySchema({
248
196
  } as const);
249
197
 
250
198
  const metrics = createTypedMetrics(telemetry, [schema]);
251
- metrics.counter('network.bytes').add(encodedSize, { direction: 'out' });
252
- ```
253
-
254
- Metric definitions use `kind: 'counter' | 'upDownCounter' | 'histogram'`; only histograms may declare `boundaries`. Metric attributes use the same scalar/array definitions as spans, but reject `cardinality: 'high'`. Omitting the cardinality annotation does not waive the low-cardinality policy. Unlike the typed span starter, the metric helper reads and retains schema instrument metadata at runtime. It performs no runtime attribute validation.
255
-
256
- `InMemoryTelemetryContext.getMetrics()` returns ordered, detached `RecordedTelemetryMeasurement` snapshots: `kind`, `name`, optional `description`/`unit`/`boundaries`, `value`, copied `attributes`, and a carrier-shaped exemplar `context` or `null`. This is a measurement log, not aggregated counters or buckets; storage is unbounded. Measurement times are retained privately for store queries, not exposed in these snapshots.
257
-
258
- ## No-op context
259
-
260
- Use `NOOP_TELEMETRY_CONTEXT` when telemetry is optional:
261
-
262
- ```typescript
263
- import { NOOP_TELEMETRY_CONTEXT } from '@bastani/atomic-telemetry';
264
-
265
- const result = await NOOP_TELEMETRY_CONTEXT.startSpan(
266
- { name: 'example.operation' },
267
- () => runOperation(),
268
- );
199
+ metrics.counter("network.bytes").add(encodedSize, { direction: "out" });
269
200
  ```
270
201
 
271
- The no-op context:
202
+ Only `kind: "histogram"` may declare `boundaries`, and metric attributes reject `cardinality: "high"`. `InMemoryTelemetryContext.getMetrics()` returns detached `RecordedTelemetryMeasurement` logs in recording order (unbounded in memory).
272
203
 
273
- - Invokes callbacks synchronously.
274
- - Preserves returned values and asynchronous rejections, and converts a synchronous throw to a promise rejected with the same value.
275
- - Uses one shared frozen inert span, including for nested spans.
276
- - Exposes `NOOP_TELEMETRY_METRICS` and `NOOP_TELEMETRY_PROPAGATION` on its root and spans.
277
- - Does not inspect or retain names, attributes, events, or statuses.
204
+ ## No-op and in-memory contexts
278
205
 
279
- ## In-memory reference adapter
280
-
281
- `InMemoryTelemetryContext` is a backend-neutral reference adapter for tests, local diagnostics, and process-local capture without an exporter:
282
-
283
- ```typescript
284
- import { InMemoryTelemetryContext } from '@bastani/atomic-telemetry';
285
-
286
- const telemetry = new InMemoryTelemetryContext();
287
-
288
- await telemetry.startSpan(
289
- { name: 'example.operation', attributes: { input: 'demo' } },
290
- async (span) => {
291
- span.addEvent('example.started');
292
- span.setAttributes({ output_count: 3 });
293
- },
294
- );
295
-
296
- console.log(telemetry.getSpans());
297
- ```
298
-
299
- `getSpans()` returns detached snapshots in span-start order. Each `RecordedTelemetrySpan` contains a deterministic numeric ID, local parent ID, carrier-shaped `context` and `parentContext` snapshots, ordered `links`, merged attributes, ordered events, final status, settlement state, and deterministic end sequence without timestamps. A remote parent has `parentId: null` and a non-null `parentContext`; a root has both `null`. A `RecordedTelemetryLink` contains a target carrier and copied attributes.
300
-
301
- `InMemoryTelemetryContext` implements `TelemetryPropagation` with JSON-safe carriers that work across independent processes without a shared registry. Treat its carrier keys as opaque and specific to `InMemoryTelemetryContext`, not as a shared wire format for other adapters.
302
-
303
- Storage in `InMemoryTelemetryContext` is unbounded and process-local. Create a fresh instance per test or recording scope, and avoid recording sensitive attributes unless your data policy permits them.
206
+ - **`NOOP_TELEMETRY_CONTEXT`:** Shared passive default when telemetry is disabled. Invokes callbacks synchronously, preserves return values and rejections (converting sync throws to rejections), exposes `NOOP_TELEMETRY_METRICS` and `NOOP_TELEMETRY_PROPAGATION`, and retains nothing.
207
+ - **`InMemoryTelemetryContext`:** Process-local reference adapter for tests and diagnostics with deterministic IDs, JSON-safe cross-process carriers, unbounded in-memory recording, `getSpans()`, `getMetrics()`, and `TelemetryStore` queries. Create a fresh instance per test or recording scope.
304
208
 
305
209
  ## Stored telemetry
306
210
 
307
- `TelemetryStore` separates querying from recording. `InMemoryTelemetryContext` implements it, and persistent adapters can implement it too:
308
-
309
- - `findTraces(query?)` returns `Promise<{ traces: readonly StoredTrace[]; cursor?: string }>`, newest trace start first, where each `StoredTrace` is `{ traceId, spans }`. `TraceQuery` filters include the earliest stored span's `name`, inclusive `startMin` and `startMax`, `errors: true`, `attributes` (scalar equalities that must all match one span anywhere in the trace), `limit` (default `20`), and opaque `cursor` (pass with the same filters to fetch the next page). Equal start times order by `traceId`.
310
- - `getTrace(traceId)` returns `Promise<StoredTrace | undefined>`.
311
- - `findMetrics({ name, startMin?, startMax?, attributes? })` returns `Promise<readonly StoredMetric[]>`, where each `StoredMetric` has `{ intervalMs, name, kind, unit?, attributes, count, sum, min, max }`. Time bounds are inclusive interval-start times. `InMemoryTelemetryContext` maps each raw measurement to a count-one row in its 10-second interval, while persistent stores can aggregate measurements per series and interval.
211
+ `TelemetryStore` separates querying from recording (implemented by `InMemoryTelemetryContext` and persistent adapters):
312
212
 
313
- Only settled spans are returned. A trace ID propagates from the root span with the parent identity. Stores return the spans available locally, so remote or expired parents may be absent and a child can appear before its parent settles. Pagination is not a frozen snapshot across requests because late settlements and retention can change a trace's earliest stored span.
213
+ - `findTraces(query?)` → `Promise<{ traces: readonly StoredTrace[]; cursor?: string }>` (newest trace start first; supports filters `name`, inclusive `startMin`/`startMax`, `errors: true`, scalar `attributes`, `limit` default `20`, and opaque `cursor`).
214
+ - `getTrace(traceId)` → `Promise<StoredTrace | undefined>`.
215
+ - `findMetrics({ name, startMin?, startMax?, attributes? })` → `Promise<readonly StoredMetric[]>` (`{ intervalMs, name, kind, unit?, attributes, count, sum, min, max }`).
314
216
 
315
- `StoredSpan` has `{ id, traceId, parentId?, name, startedMs, endedMs, attributes, events: [{ name, timeMs, attributes }], links: [{ traceId, spanId, attributes? }], status }`. `startedMs` and `endedMs` are epoch milliseconds (`telemetryNow()`), and event `timeMs` values are offsets relative to span start. Durations use a monotonic clock because wall clocks across processes may disagree. Merge spans from multiple stores by `traceId`; parent relationships, not timestamp containment, define the tree.
217
+ Only settled spans are returned. `StoredSpan` records `{ id, traceId, parentId?, name, startedMs, endedMs, attributes, events: [{ name, timeMs, attributes }], links: [{ traceId, spanId, attributes? }], status }` using monotonic durations anchored to epoch milliseconds (`telemetryNow()`).
316
218
 
317
- Trace formatting lives in `@bastani/atomic-telemetry/render`:
219
+ Format stored spans into an indented chronological tree with `@bastani/atomic-telemetry/render`:
318
220
 
319
221
  ```typescript
320
- import { renderTrace } from '@bastani/atomic-telemetry/render';
222
+ import { renderTrace } from "@bastani/atomic-telemetry/render";
321
223
 
322
224
  const page = await telemetry.findTraces({ errors: true, limit: 10 });
323
225
  for (const trace of page.traces) console.log(renderTrace(trace.spans));
324
226
  ```
325
227
 
326
- `renderTrace()` accepts stored spans, deduplicates IDs, treats absent parents as roots, and formats attributes, durations, statuses, event offsets, and cross-trace links. It never follows links or queries a store.
327
-
328
228
  ## Adapter conformance
329
229
 
330
- `@bastani/atomic-telemetry/testing` exports a runner-independent conformance suite modeled as grouped cases. A fixture supplies a fresh context and converts its backend's finished spans into normalized `RecordedTelemetrySpan` snapshots:
230
+ `@bastani/atomic-telemetry/testing` exports a runner-independent conformance suite (`createTelemetryAdapterConformance`) that verifies capability identity, synchronous single invocation, return/rejection preservation, status rules, attribute merging, event ordering, post-settlement inertness, nested/concurrent parentage, span links, and optional propagation and metrics fixtures:
331
231
 
332
232
  ```typescript
333
233
  import {
334
234
  createTelemetryAdapterConformance,
335
235
  type TelemetryAdapterFixture,
336
- } from '@bastani/atomic-telemetry/testing';
337
- import { describe, it } from 'vitest';
236
+ } from "@bastani/atomic-telemetry/testing";
237
+ import { describe, it } from "vitest";
338
238
 
339
239
  const conformance = createTelemetryAdapterConformance(async () => {
340
240
  const adapter = createMyTelemetryAdapter();
@@ -356,168 +256,85 @@ for (const group of new Set(conformance.map((testCase) => testCase.group))) {
356
256
  }
357
257
  ```
358
258
 
359
- The suite verifies capability identity on roots, child spans, extracted parents, and inert spans. It also checks synchronous single invocation, return and rejection identity, automatic and explicit statuses, attribute merging, event ordering, inert post-settlement calls, nested and concurrent parentage, and span links.
360
-
361
- Fixtures may supply `propagation` to verify JSON round trips, multi-adapter hops, and root fallback for absent or unknown carriers. Fixtures may also supply `metrics` and `getMetrics()` to verify ordered measurements, histogram exemplars, and input copying. The suite does not test malformed inputs or require suppressing backend failures. `getSpans()` may flush an asynchronous exporter before returning. `@bastani/atomic-telemetry/testing` uses Node's assertion APIs, while the root package remains runtime-neutral.
259
+ `@bastani/atomic-telemetry/testing` uses Node's assertion APIs, while the root package remains runtime-neutral.
362
260
 
363
261
  ## Typed schemas
364
262
 
365
- The low-level span API intentionally accepts open names and attribute bags so adapters remain generic. Domain packages can define closed, serializable schemas and infer exact TypeScript types from them.
263
+ Define closed, JSON-serializable span and metric vocabularies with `defineTelemetrySchema()` and bind them with `createTypedSpanStarter()`:
366
264
 
367
265
  ```typescript
368
- import {
369
- createTypedSpanStarter,
370
- defineTelemetrySchema,
371
- } from '@bastani/atomic-telemetry';
266
+ import { createTypedSpanStarter, defineTelemetrySchema } from "@bastani/atomic-telemetry";
372
267
 
373
268
  export const EXAMPLE_TELEMETRY_SCHEMA = defineTelemetrySchema({
374
269
  version: 1,
375
270
  spans: {
376
- 'example.read': {
377
- description: 'Read one resource',
378
- parents: { kind: 'any' },
271
+ "example.read": {
272
+ description: "Read one resource",
273
+ parents: { kind: "any" },
379
274
  startAttributes: {
380
- 'example.resource': {
381
- type: 'string',
275
+ "example.resource": {
276
+ type: "string",
382
277
  required: true,
383
- values: ['account', 'project'],
384
- description: 'Resource kind',
278
+ values: ["account", "project"],
279
+ description: "Resource kind",
385
280
  },
386
281
  },
387
282
  endAttributes: {
388
- 'example.item_count': {
389
- type: 'number',
390
- description: 'Number of returned items',
283
+ "example.item_count": {
284
+ type: "number",
285
+ description: "Number of returned items",
391
286
  },
392
287
  },
393
288
  events: {
394
- 'example.cache': {
395
- description: 'Cache lookup result',
289
+ "example.cache": {
290
+ description: "Cache lookup result",
396
291
  attributes: {
397
- 'example.cache.hit': {
398
- type: 'boolean',
292
+ "example.cache.hit": {
293
+ type: "boolean",
399
294
  required: true,
400
- description: 'Whether the cache contained the resource',
295
+ description: "Whether the cache contained the resource",
401
296
  },
402
297
  },
403
298
  },
404
299
  },
405
- status: {
406
- default: 'ok',
407
- errorWhen: 'The read throws or returns an error result',
408
- },
300
+ status: { default: "ok", errorWhen: "The read throws or returns an error result" },
409
301
  },
410
302
  },
411
303
  } as const);
412
304
 
413
- const startSpan = createTypedSpanStarter(
414
- telemetryContext,
415
- [EXAMPLE_TELEMETRY_SCHEMA],
416
- );
417
- ```
305
+ const startSpan = createTypedSpanStarter(telemetryContext, [EXAMPLE_TELEMETRY_SCHEMA]);
418
306
 
419
- The starter exposes one overload per span and checks names and attributes at compile time. Union-valued names must be narrowed before a call, preserving the relationship between each runtime name and its attribute schema. Always pass the second `attributes` argument (pass `{}` when a span declares `startAttributes: {}`), unlike `span.addEvent()` where `attributes` is optional when no attributes are required. Its callback receives a child starter over the same schemas, already bound to the callback span:
307
+ await startSpan("example.read", { "example.resource": "account" }, async (span, startChildSpan) => {
308
+ span.addEvent("example.cache", { "example.cache.hit": true });
309
+ const accounts = await readAccounts();
310
+ span.setAttributes({ "example.item_count": accounts.length });
420
311
 
421
- ```typescript
422
- await startSpan(
423
- 'example.read',
424
- { 'example.resource': 'account' },
425
- async (span, startChildSpan) => {
426
- span.addEvent('example.cache', { 'example.cache.hit': true });
427
- const accounts = await readAccounts();
428
- span.setAttributes({ 'example.item_count': accounts.length });
429
-
430
- await startChildSpan(
431
- 'example.read',
432
- { 'example.resource': 'project' },
433
- async (childSpan) => {
434
- const projects = await readProjects();
435
- childSpan.setAttributes({ 'example.item_count': projects.length });
436
- },
437
- );
312
+ await startChildSpan("example.read", { "example.resource": "project" }, async (childSpan) => {
313
+ const projects = await readProjects();
314
+ childSpan.setAttributes({ "example.item_count": projects.length });
315
+ });
438
316
 
439
- return accounts;
440
- },
441
- );
317
+ return accounts;
318
+ });
442
319
  ```
443
320
 
444
- ### Start and completion attributes
321
+ Always pass the second `attributes` argument to `startSpan()` (`{}` when `startAttributes` is empty). `startSpan()` can compose multiple schemas (`[SCHEMA_A, SCHEMA_B] as const`) and rejects duplicate literal span names, missing required attributes, unknown keys, and invalid closed-set values at compile time. `defineTelemetrySchema()` is a typed identity helper that performs no runtime validation.
445
322
 
446
- `startAttributes` and `endAttributes` describe when an attribute is normally known, not separate runtime storage:
323
+ ### Start and completion attributes
447
324
 
448
325
  | Schema field | How values are recorded | Requiredness |
449
- |---|---|---|
450
- | `startAttributes` | Passed in the typed starter's `attributes` argument when the span is created | Each definition explicitly sets `required: true` or `false` |
451
- | `endAttributes` | Added later through the schema-scoped span's `setAttributes()` method | Always optional |
452
-
453
- Both sets become ordinary attributes on the same backend span. There is no separate end-attribute payload or end callback. In the preceding example, `example.resource` is known when `example.read` starts, while `example.item_count` is known only after `readAccounts()` returns:
454
-
455
- ```typescript
456
- await startSpan(
457
- 'example.read',
458
- { 'example.resource': 'account' }, // required start attribute
459
- async (span) => {
460
- const accounts = await readAccounts();
461
- span.setAttributes({
462
- 'example.item_count': accounts.length, // optional completion attribute
463
- });
464
- return accounts;
465
- },
466
- ); // resolving the callback settles the span
467
- ```
326
+ | --- | --- | --- |
327
+ | `startAttributes` | Passed in `startSpan()`'s `attributes` argument when the span starts | Explicit `required: true` or `false` |
328
+ | `endAttributes` | Added later via `span.setAttributes()` while the callback runs | Always optional (calling zero times is valid) |
468
329
 
469
- "End" means completion enrichment. You can set an end attribute at any point while the callback runs, or omit it when unavailable. Calling `setAttributes()` zero times is valid, which accommodates early failures, cancellation, and provider-specific fields that are not present on every path.
470
-
471
- Repeated `setAttributes()` calls merge into the same attribute bag. A later defined value replaces an earlier value for the same key, while `undefined` is ignored. The schema-scoped method accepts only the current span's declared end attributes.
472
-
473
- Attributes do not end the span. Returning, resolving, throwing, or rejecting from the callback controls settlement; `startSpan()` performs the actual end operation. Adapter calls made after settlement are inert.
474
-
475
- A starter can compose multiple independently versioned schemas, each defined with `defineTelemetrySchema()`:
476
-
477
- ```typescript
478
- const startAppSpan = createTypedSpanStarter(telemetryContext, [
479
- EXAMPLE_TELEMETRY_SCHEMA,
480
- CACHE_TELEMETRY_SCHEMA,
481
- ] as const);
482
- ```
483
-
484
- Inline schema arrays retain their tuple types automatically. Separately declared arrays should use `as const`. Literal duplicate span names across the array are rejected at compile time; schemas are not merged, inspected, or retained at runtime.
485
-
486
- Schema-derived types reject missing required attributes, unknown keys, invalid closed-set values, undeclared events, and attributes on empty schemas. End attributes are always optional enrichment; the type system does not require `setAttributes()` to be called.
487
-
488
- `defineTelemetrySchema()` is a typed identity function. It returns ordinary JSON-serializable data and performs no runtime validation or parent-rule enforcement.
489
-
490
- ## Schema metadata
491
-
492
- Supported attribute types are:
493
-
494
- - `string`, `number`, and `boolean`
495
- - `string[]`, `number[]`, and `boolean[]`
496
-
497
- Attribute definitions support:
498
-
499
- - `values`: a closed set for scalar values
500
- - `elementValues`: a closed set for array elements
501
- - `examples`: documentation examples
502
- - `sensitive`: marks data requiring special handling
503
- - `cardinality`: records expected `low` or `high` cardinality
504
-
505
- Start and event attributes declare `required`. End attributes do not; see [Start and completion attributes](#start-and-completion-attributes).
506
-
507
- Parent metadata is descriptive schema data:
508
-
509
- - `{ kind: 'any' }`: root or any caller span
510
- - `{ kind: 'root_or_external' }`: root or a caller-owned span outside the schema
511
- - `{ kind: 'spans', spans: [...] }`: only the listed schema spans
512
-
513
- Adapters do not need to understand schema objects. Instrumentation helpers and tests use them to keep emitted names and attributes consistent.
330
+ Both sets merge into the same backend span attribute bag (later defined values win; `undefined` is ignored). Supported attribute types are `string`, `number`, `boolean`, and their homogeneous arrays (`string[]`, `number[]`, `boolean[]`), with optional metadata fields `values`, `elementValues`, `examples`, `sensitive`, and `cardinality` (`"low"` | `"high"`). Descriptive `parents` rules accept `{ kind: "any" }`, `{ kind: "root_or_external" }`, or `{ kind: "spans", spans: [...] }`.
514
331
 
515
332
  ## Using with `@bastani/atomic-ai`
516
333
 
517
- Pass a parent `TelemetryContext` to [`@bastani/atomic-ai`](/libraries/ai) through `telemetryContext` in request options:
334
+ Pass a parent `TelemetryContext` to [`@bastani/atomic-ai`](/libraries/ai) via `telemetryContext` in request options:
518
335
 
519
336
  ```typescript
520
- import { InMemoryTelemetryContext } from '@bastani/atomic-telemetry';
337
+ import { InMemoryTelemetryContext } from "@bastani/atomic-telemetry";
521
338
 
522
339
  const telemetry = new InMemoryTelemetryContext();
523
340
  await models.completeSimple(model, context, { telemetryContext: telemetry });
@@ -525,67 +342,58 @@ await models.completeSimple(model, context, { telemetryContext: telemetry });
525
342
 
526
343
  ## Security and portability
527
344
 
528
- Telemetry is diagnostic data, not durable application state. Do not persist a `TelemetryContext`, `TelemetrySpan`, or backend-native trace object in records, messages, snapshots, or deferred handles. An injected `TelemetryCarrier` may cross a transport or be stored as optional diagnostic correlation data. Changing adapters may lose correlation because carriers are not application state.
529
-
530
- Attribute values are limited to scalar values and homogeneous scalar arrays. Avoid recording prompts, completions, tool arguments or output, file contents, provider payloads, headers, credentials, and free-form error details unless your schema and data policy explicitly allow them.
345
+ <Warning>
346
+ Telemetry is diagnostic data, not durable application state. Never persist a `TelemetryContext`, `TelemetrySpan`, or backend trace object inside records, messages, or snapshots, and never record prompts, completions, tool arguments/output, file contents, credentials, or raw headers unless your schema and data policy explicitly permit them.
347
+ </Warning>
531
348
 
532
- This package does not use `AsyncLocalStorage` or any runtime-specific ambient context API. It works in Node.js, Bun, browsers, and workers; backend adapters remain responsible for their own runtime compatibility.
349
+ An injected `TelemetryCarrier` may cross a transport or be stored as optional diagnostic correlation data. This package uses no `AsyncLocalStorage` or runtime-specific globals, so it works in Node.js, Bun, browsers, and workers (backend adapters own their own runtime compatibility).
533
350
 
534
351
  ## API reference
535
352
 
536
353
  ### Core types and values
537
354
 
538
355
  | Export | Purpose |
539
- |---|---|
540
- | `TelemetryContext` | Starts callback-managed child spans and optionally exposes adapter metrics/propagation |
541
- | `TelemetrySpan` | Records attributes, events, and status; also acts as a child context |
542
- | `SpanOptions` | Span name, optional start attributes and links |
543
- | `SpanLink` | Context target and optional link attributes |
544
- | `TelemetryCarrier` | Opaque JSON-safe string map |
545
- | `TelemetryPropagation` | Optional adapter injection and extraction capability |
546
- | `NOOP_TELEMETRY_PROPAGATION` | Shared passive propagation for disabled telemetry |
547
- | `TelemetryMetrics` | Optional adapter instrument factories |
548
- | `TelemetryCounter` / `TelemetryUpDownCounter` | Instruments with `add()` |
549
- | `TelemetryHistogram` | Instrument with `record()` and optional exemplar context |
550
- | `InstrumentOptions` / `HistogramOptions` | Description, unit, and histogram boundary hints |
551
- | `NOOP_TELEMETRY_METRICS` | Shared passive metric instruments |
552
- | `RecordedTelemetryMeasurement` | Captured measurement and optional exemplar |
553
- | `SpanAttributes` / `AttributeValue` | Open adapter-level attribute bag and supported values |
554
- | `SpanStatus` | Explicit `ok` or `error` status |
555
- | `NOOP_TELEMETRY_CONTEXT` | Shared passive context for disabled telemetry |
556
- | `InMemoryTelemetryContext` | Reference adapter with deterministic process-local recording |
557
- | `RecordedTelemetrySpan` | Normalized captured span snapshot |
558
- | `RecordedTelemetryEvent` | Normalized captured event snapshot |
559
- | `RecordedTelemetryLink` | Captured target carrier and link attributes |
560
- | `TelemetryStore` | Settled trace discovery, trace retrieval, and metric queries |
561
- | `StoredSpan` / `StoredTrace` | Backend-independent timed span and trace snapshots |
562
- | `TraceQuery` / `MetricQuery` | Trace filters, pagination, and metric filters |
563
- | `StoredMetric` | Metric interval row with count, sum, minimum, and maximum |
356
+ | --- | --- |
357
+ | `TelemetryContext` / `TelemetrySpan` | Callback-managed span starter and active span handle |
358
+ | `SpanOptions` / `SpanLink` / `SpanAttributes` / `AttributeValue` / `SpanStatus` | Core span creation and recording types |
359
+ | `TelemetryCarrier` / `TelemetryPropagation` | Cross-process opaque carrier and inject/extract contract |
360
+ | `TelemetryMetrics` / `TelemetryCounter` / `TelemetryUpDownCounter` / `TelemetryHistogram` | Metric instrument factories and recorders |
361
+ | `InstrumentOptions` / `HistogramOptions` / `RecordedTelemetryMeasurement` | Metric metadata, bucket hints, and recorded measurement snapshots |
362
+ | `NOOP_TELEMETRY_CONTEXT` / `NOOP_TELEMETRY_METRICS` / `NOOP_TELEMETRY_PROPAGATION` | Shared passive no-op implementations |
363
+ | `InMemoryTelemetryContext` | Deterministic in-memory reference adapter |
364
+ | `RecordedTelemetrySpan` / `RecordedTelemetryEvent` / `RecordedTelemetryLink` | Normalized captured span snapshots |
365
+ | `TelemetryStore` / `StoredSpan` / `StoredTrace` / `StoredMetric` / `TraceQuery` / `MetricQuery` | Backend-independent settled trace and metric query API |
564
366
  | `telemetryNow()` | Monotonic-anchored wall-clock milliseconds used by `StoredSpan` |
565
367
 
566
- ### Render subpath (`@bastani/atomic-telemetry/render`)
368
+ ### Subpaths
567
369
 
568
- | Export | Purpose |
569
- |---|---|
570
- | `renderTrace()` | Formats `StoredSpan[]` into an indented chronological trace tree |
370
+ | Subpath | Exports |
371
+ | --- | --- |
372
+ | `@bastani/atomic-telemetry/render` | `renderTrace()` — formats `StoredSpan[]` into an indented chronological trace tree |
373
+ | `@bastani/atomic-telemetry/testing` | `createTelemetryAdapterConformance()`, `TelemetryAdapterFixture`, `TelemetryAdapterFixtureFactory`, `TelemetryAdapterConformanceCase` |
571
374
 
572
375
  ### Schema definitions and inference
573
376
 
377
+ **Primary helpers:**
378
+
574
379
  | Export | Purpose |
575
- |---|---|
576
- | `defineTelemetrySchema()` | Typed identity helper for serializable schema data |
577
- | `createTypedSpanStarter()` | Binds a parent context to one or more schema vocabularies |
380
+ | --- | --- |
381
+ | `defineTelemetrySchema()` | Typed identity helper for serializable schema definitions |
382
+ | `createTypedSpanStarter()` | Binds a parent context to one or more span schemas |
578
383
  | `createTypedMetrics()` / `TypedTelemetryMetrics` | Binds metric names, kinds, metadata, and attributes to schemas |
579
- | `TelemetryMetricDefinition` / `TelemetryMetricAttributeDefinition` | Serializable instrument metadata and low-cardinality attribute definitions |
580
- | `SchemaTelemetryCounter` / `SchemaTelemetryHistogram` | Schema-constrained recording methods |
581
- | `TypedSpanStarter` | Exact starter type with recursively child-bound callbacks |
582
- | `TelemetrySchemaDefinition` | Top-level schema shape |
583
- | `TelemetrySpanDefinition` | Span metadata, parents, attributes, events, and status rule |
584
- | `TelemetryAttributeType` | Supported scalar and array type names |
384
+ | `TelemetrySchemaDefinition` / `TelemetrySpanDefinition` / `TelemetryMetricDefinition` | Top-level schema, span, and metric definition shapes |
385
+ | `SchemaTelemetrySpan` / `SchemaTelemetryCounter` / `SchemaTelemetryHistogram` | Schema-constrained span and metric views |
386
+ | `TypedSpanStarter` | Exact span starter type with recursively child-bound callbacks |
387
+
388
+ <Accordion title="TypeScript inference utility types">
389
+ | Export | Purpose |
390
+ | --- | --- |
391
+ | `TelemetryAttributeType` | Supported scalar and array attribute type names |
585
392
  | `TelemetryAttributeMetadata` | Description, sensitivity, and cardinality metadata |
586
393
  | `TelemetryAttributeDefinition` | Attribute type, allowed values, examples, and metadata |
587
394
  | `TelemetryStartAttributeDefinition` | Start attribute definition with requiredness |
588
395
  | `TelemetryEventAttributeDefinition` | Event attribute definition with requiredness |
396
+ | `TelemetryMetricAttributeDefinition` | Low-cardinality metric attribute definition |
589
397
  | `TelemetryEventDefinition` | Event description and attribute definitions |
590
398
  | `TelemetryParentDefinition` | Open, external-root, or finite schema-parent rule |
591
399
  | `TelemetrySchemaSpanName` | Union of declared span names |
@@ -593,19 +401,10 @@ This package does not use `AsyncLocalStorage` or any runtime-specific ambient co
593
401
  | `TelemetrySchemaSpanEndAttributes` | Optional inferred end attributes for one span |
594
402
  | `TelemetrySchemaSpanEventName` | Union of events declared by one span |
595
403
  | `TelemetrySchemaSpanEventAttributes` | Exact inferred attributes for one event |
596
- | `SchemaTelemetrySpan` | Span view restricted to one schema span |
597
404
  | `TelemetrySchemaSpanUnion` | Discriminated union of all spans in a schema |
598
405
  | `InferStartAttributes` | Required and optional values inferred from start definitions |
599
406
  | `InferOptionalAttributes` | Optional values inferred from end definitions |
600
407
  | `InferEventAttributes` | Required and optional values inferred from event definitions |
601
408
  | `InferRequiredAndOptionalAttributes` | Shared inference utility for definitions with requiredness |
602
409
  | `ExactTelemetryAttributes` | Rejects keys outside an expected attribute set |
603
-
604
- ### Testing subpath
605
-
606
- | Export | Purpose |
607
- |---|---|
608
- | `createTelemetryAdapterConformance()` | Creates runner-independent adapter conformance cases |
609
- | `TelemetryAdapterFixture` | Fresh context and normalized snapshot reader for one case |
610
- | `TelemetryAdapterFixtureFactory` | Creates isolated fixtures |
611
- | `TelemetryAdapterConformanceCase` | Grouped case that test runners execute |
410
+ </Accordion>