npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@takk/bayeschangepoint

v1.0.0

Published

BayesChangepoint: Bayesian Online Changepoint Detection that tells production Massive Intelligence (IM) metrics, latency, cost, hallucination rate, tool success, apart from noise in real time. A zero-runtime-dependency, TypeScript-first library implementi

Readme

BayesChangepoint

status: stable license version node tests coverage runtime deps

Star History Chart

Universal, zero-runtime-dependency NPM library and CLI that tells production metrics apart from noise in real time, using exact Bayesian Online Changepoint Detection instead of fragile threshold rules.

BayesChangepoint is the seismograph for your production metrics. Latency, cost, hallucination rate, tool success rate, embedding quality, every metric drifts; the hard part is separating ordinary statistical noise from a real regime change, a silent provider deprecation, an infrastructure issue, a data drift. Threshold alerts cannot tell them apart, so they either miss the gradual shift or page you on every spike. BayesChangepoint feeds each new observation into the exact run-length recursion of Adams and MacKay (2007), maintains a posterior over the time since the last changepoint, and reports a calibrated probability that the regime just changed, in linear time, online, with no training run.

Core promise: zero required runtime dependencies, single-function setup, ergonomic TypeScript types, ESM + CJS dual distribution, a node-free core that runs in Node, edge runtimes, and the browser, SLSA provenance on every release.

This is infrastructure for the Massive Intelligence (IM) stack: regime-change detection becomes a calibrated probabilistic decision with a posterior, not a heuristic threshold guessed at design time. It is the calibrated, zero-dependency alternative to fragile threshold alerts.


Install

pnpm add @takk/bayeschangepoint
# or: npm install @takk/bayeschangepoint
# or: yarn add @takk/bayeschangepoint
# or: bun add @takk/bayeschangepoint

The core has no runtime dependencies at all. The @takk/* family packages are optional peers; install only the ones you compose with.


Quickstart

// src/example.ts
import { createDetector } from '@takk/bayeschangepoint';

// warmup auto-calibrates the prior to the metric's scale (milliseconds, dollars,
// rates), so detection works out of the box without manual tuning.
const detector = createDetector({
  expectedRunLength: 250, // prior on how long a regime lasts, in observations
  warmup: 50,             // first 50 points calibrate, then live detection begins
});

for (const latencyMs of latencyStream) {
  const step = detector.observe(latencyMs);
  if (step.isChangepoint) {
    console.log(`regime change at observation ${step.index}`, {
      probability: step.changepointProbability,
      newLevel: step.predictiveMean,
    });
  }
}

Each observation folds into the run-length posterior in closed form, so inference adds no latency. The reported changepointProbability is the posterior probability that a changepoint occurred within the recent detection window; it stays near zero in a stable regime and spikes toward one for the few steps after a real change.


Clean alarms with the alert engine

A raw threshold crossing fires for several consecutive steps around one change, and the run-length posterior is legitimately small at stream start. The alert engine collapses that into one deduplicated event per regime change, with hysteresis, a cooldown, and a segment summary (previous level, new level, magnitude, direction) for incident reports and downstream automation.

import { createDetector } from '@takk/bayeschangepoint';
import { AlertEngine } from '@takk/bayeschangepoint/alert';

const detector = createDetector({ warmup: 50 });
const alerts = new AlertEngine({ threshold: 0.5, cooldown: 30 });

for (const value of stream) {
  const event = alerts.push(detector.observe(value));
  if (event) {
    console.log(`changepoint at ${event.index}: ${event.direction}`, {
      from: event.previousMean,
      to: event.newMean,
      magnitude: event.magnitude,
    });
  }
}

See examples/ for runnable demos against the compiled artifact.


How it works

The engine maintains a posterior over the run length r_t, the number of observations since the last changepoint. A hazard function H(r) encodes the prior probability of a change at each step. For every new observation it passes two messages, growth (the run continues) and changepoint (the run resets to zero), and renormalizes. The whole recursion runs in log space for numerical stability.

The observation model is conjugate, so the posterior predictive is closed form. Pick the one that matches your metric:

| Metric type | Observation model | Posterior predictive | |---|---|---| | Real-valued (latency, cost, score) | Gaussian, unknown mean and variance | Normal-Inverse-Gamma, Student-t predictive | | Counts and rates (errors per minute, tool calls) | Poisson | Gamma-Poisson, Negative Binomial predictive | | Outlier-prone real-valued | robust beta-divergence (density power divergence) | bounded-surprise message + density-power-weighted update |

The reported changepointProbability is the posterior mass on short run lengths, the calibrated probability that a changepoint occurred within the detection window. The cost is O(maxRunLength) per observation, linear and bounded.


Differentiators

  1. Probabilistic, not threshold-based. Output is a calibrated posterior probability of regime change per observation, not a brittle static threshold that misses gradual shifts and fires on noise.
  2. Configurable hazard. The prior on regime duration is explicit and tunable, instead of a magic number buried in an alert rule.
  3. Robust to outliers. The robust model uses the real beta-divergence (density power divergence, Altamirano et al, 2023): a lone spike is ignored, a sustained shift is still detected.
  4. Multivariate. Watch several correlated metrics at once and get the probability that any of them changed, honestly scoped as independent streams.
  5. Turnkey ingestion. Drop-in receivers parse the Prometheus text exposition format and OpenTelemetry data points, so it slots into the pipeline you already run.
  6. Embeddable and node-free. No SaaS, no sidecar, no Python service. It is a library you pnpm add, with a node-free core for edge and browser, and a CLI.

Subpath exports

The facade wires everything together, and every layer is also a standalone entry point for callers who want only the math.

| Import | Surface | |---|---| | @takk/bayeschangepoint | createDetector facade plus re-exports of the node-free core | | @takk/bayeschangepoint/bocd | The BOCD engine: run-length recursion, snapshot, restore | | @takk/bayeschangepoint/hazard | Hazard functions: constantHazard, clampHazard, custom | | @takk/bayeschangepoint/predictive | The PredictiveModel contract | | @takk/bayeschangepoint/gaussian | Normal-Inverse-Gamma predictive plus calibrateGaussianPrior | | @takk/bayeschangepoint/poisson | Gamma-Poisson predictive for counts and rates | | @takk/bayeschangepoint/robust | Beta-divergence (density power) robust predictive | | @takk/bayeschangepoint/multivariate | Independent-streams multivariate detector | | @takk/bayeschangepoint/alert | Alert engine: deduplicated changepoint events with a segment summary | | @takk/bayeschangepoint/store | Snapshot encode, decode, validate, and restore | | @takk/bayeschangepoint/node | createFileStore, the only entry that touches node:fs, atomic JSON persistence | | @takk/bayeschangepoint/edge | The node-free core re-exported for edge runtimes and the browser | | @takk/bayeschangepoint/audit | Append-only SHA-256 hash-chain of changepoint events, via the Web Crypto API | | @takk/bayeschangepoint/receivers | Prometheus, OpenTelemetry, and generic time-series parsers |


CLI

BayesChangepoint also works from the shell. simulate prints a synthetic regime-change series; detect reads whitespace-separated numbers from a file or stdin and prints the confirmed changepoints as JSON.

# Print a synthetic series with one regime change.
npx @takk/bayeschangepoint simulate --n 200 --change-at 100 --before 100 --after 160 --std 8

# Pipe it straight into the detector.
npx @takk/bayeschangepoint simulate --n 200 --change-at 100 | npx @takk/bayeschangepoint detect --warmup 30

# Detect changepoints in your own newline-separated metric dump.
npx @takk/bayeschangepoint detect ./latency.txt --window 5 --hazard 250 --warmup 50

Exit codes follow the sysexits convention: 0 ok, 1 error, 64 usage, 65 data, 66 no input.


Receivers

Turn the metric formats you already emit into the number streams the detector consumes, with zero dependencies.

import { createDetector } from '@takk/bayeschangepoint';
import { parsePrometheus, selectSeries } from '@takk/bayeschangepoint/receivers';

const samples = parsePrometheus(await scrape('http://app:9090/metrics'));
const latency = selectSeries(samples, 'http_request_duration_ms', { route: '/v1/chat' });

const detector = createDetector({ warmup: 50 });
for (const value of latency) detector.observe(value);

fromOpenTelemetry and fromTimeSeries cover OpenTelemetry numeric data points and any generic { value } series.


Persistence

The detector state lives in memory. To survive a restart with no database, snapshot it and reload through the file store:

import { Bocd, constantHazard, GaussianPredictive } from '@takk/bayeschangepoint';
import { snapshotBocd, restoreBocd } from '@takk/bayeschangepoint/store';
import { createFileStore } from '@takk/bayeschangepoint/node';

const store = createFileStore('./detector.json');
const bocd = new Bocd({ hazard: constantHazard(250), predictive: new GaussianPredictive() });
// ... feed observations ...
store.save(snapshotBocd(bocd)); // atomic write

// Later, in a fresh process:
const saved = store.load();
const restored = saved ? restoreBocd(saved, { hazard: constantHazard(250) }) : bocd;

A snapshot is portable JSON, so state moves cleanly between an edge runtime and a worker.


Audit trail

For compliance in defense, finance, and healthcare, every confirmed changepoint event can be appended to a tamper-evident SHA-256 hash chain, built on the Web Crypto API, never a Node built-in, so it runs in Node, on the edge, and in the browser:

import { AuditLog } from '@takk/bayeschangepoint/audit';

const log = new AuditLog();
await log.append(event);             // a ChangepointEvent from the alert engine
const head = log.seal();             // the head hash that binds the full history
const intact = await log.verify();   // false if any entry was edited or reordered

Changing, reordering, inserting, or dropping any entry breaks the chain, so the seal proves the incident log is intact.


Benchmark and calibration

The detection quality is not asserted, it is measured. The benchmarks/ directory runs the compiled build three ways: detection on the public Well Log series from the Turing Change Point Dataset (675 observations with five human annotations), where BayesChangepoint beats a rolling z-score baseline (F1 54.5% versus 52.2% at equal recall); a robustness benchmark where the robust beta-divergence model cuts outlier false alarms roughly eightfold versus the standard Gaussian (7.8% versus 58.9% of injected spikes); and a calibration study over seeded synthetic series with exact ground truth, where the reported probability is well calibrated (expected calibration error 0.017, Brier 0.026) and high-confidence alarms are reliable. Every number comes from running benchmarks/bench.mjs against the compiled artifact, never from a guess. See the benchmark README for the methodology, the honest caveats, and how to reproduce.


Quality

  • 68 tests across 15 suites, all passing under Vitest 4.
  • Coverage: statements 98.5%, branches 94.2%, functions 100%, lines 98.9%.
  • Lint clean under Biome 2.
  • Typecheck clean under TypeScript 6 in maximum strict mode (exactOptionalPropertyTypes, useUnknownInCatchVariables, noUncheckedIndexedAccess).
  • publint clean, attw clean across all subpaths for both ESM and CJS.
  • Bundle budgets enforced with size-limit (the core is about 2.5 kB brotli).
  • A distribution smoke test exercises the compiled ESM and CJS artifacts and spawns the compiled CLI as a single Node process.
  • Validated on the CI matrix across Node 20, 22, and 24.
  • Published with --provenance (SLSA attestation by GitHub Actions).

See SPEC.md for the formal specification, public surface, and stability promise.


FAQ

Why not Datadog Watchdog? Watchdog does anomaly detection, not probabilistic changepoint detection, and it is a hosted product tied to the Datadog platform. BayesChangepoint is a TypeScript-native library that gives you a calibrated changepoint probability you can act on, embeddable in any Node, Bun, or Deno process, with a node-free core for the edge.

Why not Prometheus alerting rules? Threshold rules are brittle: a fixed bound misses a gradual shift and pages on every noisy spike. BayesChangepoint distinguishes noise from a real regime change with a calibrated posterior, and the receivers ingest your existing Prometheus metrics directly.

Why not statsmodels or a CUSUM in Python? Classical CUSUM needs manual tuning and lives in the Python data stack, not your Node service. BayesChangepoint ships an exact, performant BOCD with a configurable hazard, a robust beta-divergence variant, and a multivariate mode, as a zero-dependency TypeScript library.

Does this work in Cloudflare Workers, Vercel Edge, Bun, or Deno? Yes. The core and the edge entry are node-free, including the audit seal. Only the node file store touches node:fs.

How does it ignore one-off spikes but still catch a real shift? Use the robust predictive. It implements the beta-divergence (density power divergence): a lone outlier is downweighted to near zero, while a sustained shift still moves the posterior and triggers a detection.

Does it call my metric source for me? No. You feed it observations; it tells you when the regime changed. The receivers help you turn Prometheus or OpenTelemetry data into that stream, but you stay in control of the scrape.


Contributing

See .github/CONTRIBUTING.md for the contributor guide. Substantive proposals open a GitHub Issue first; trivial fixes can go straight to a PR. All commits require DCO sign-off (git commit -s). Non-trivial contributions are governed by the Contributor License Agreement.

Community and support

  • Issues and feature requests. Open a GitHub issue at davccavalcante/bayeschangepoint/issues. Include the package version, a minimal reproduction, expected versus actual behavior, and where relevant the changepointProbability series or a detector snapshot.
  • Security disclosures. Do NOT open public issues for vulnerabilities. Follow the responsible-disclosure flow in SECURITY.md, contact [email protected] with the [SECURITY] prefix.
  • Code of Conduct. This project follows the Contributor Covenant 2.1. Participation in any BayesChangepoint space implies agreement.

Author

Created by David C Cavalcante, [email protected] (preferred), [email protected] (Takk relay), linkedin.com/in/hellodav, x.com/davccavalcante, takk.ag.

BayesChangepoint is part of a broader portfolio of NPM packages building the probabilistic layer of Massive Intelligence (IM) infrastructure for 2026 to 2030, built at Takk Innovate Studio.


Related research by the author

The architectural philosophy behind BayesChangepoint, decisions under uncertainty made explicit, calibrated, and auditable, echoes the author's research frameworks:

  • MAIC (Massive Artificial Intelligence Consciousness), the Universe, the framework: a systemic intelligence framework that coordinates, supervises, and governs large-scale Massive Intelligence (IM) ecosystems, providing global context awareness, alignment, and orchestration across models, agents, and decision layers.
  • HIM (Hybrid Entity Intelligence Model), the spirit, the model: a hybrid intelligence layer that integrates Massive Intelligence (IM) with human-defined logic, rules, and strategic intent, structuring decision-making before and after model execution.
  • NHE (Noumenal Higher-order Entity), the reincarnated body, the agent: a non-human entity with a defined functional identity and operational agency, operating through coordinated intelligence layers while keeping a non-anthropomorphic identity.

These frameworks are published independently of BayesChangepoint and are separate works:


Sponsors

Join the journey as the portfolio continues to ship the probabilistic layer of Massive Intelligence (IM) infrastructure. Your support is the cornerstone of this work.


Privacy

BayesChangepoint runs entirely inside your own process and infrastructure. It makes no outbound calls to the author, collects no telemetry, and ships no analytics. The only state it keeps is the run-length posterior and sufficient statistics you accumulate, in memory or in the store you configure. See PRIVACY.md for the full data-handling notice, including how the optional file store persists state on disk.


License

Licensed under the Apache License 2.0. See LICENSE for the full text and NOTICE for attribution. You may use, modify, and distribute the code under the terms of that license, including its patent grant and attribution requirements.