# @kojihq/core-sqlite

> SQLite cache adapter for @kojihq/core (CLI use only, native dep)

Latest version **0.1.0-beta.13** (published 2026-09-24) · MIT license · 0 weekly downloads

## Install

```sh
npm install @kojihq/core-sqlite
pnpm add @kojihq/core-sqlite
yarn add @kojihq/core-sqlite
bun add @kojihq/core-sqlite
```

## Health

**Score 70/100 (B)** — status: active.

Positive: has types; esm support; no vulnerabilities; recently updated; high maintenance score; high quality score.

Warnings: low downloads; pre 1.0.

## Facts

| | |
|---|---|
| Version | 0.1.0-beta.13 |
| Published | 2026-09-24 |
| First published | 2026-05-02 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 3 |
| Unpacked size | 55 KB |
| Known vulnerabilities | 0 (+1 in 1 direct dependencies) |
| Install scripts | no |
| GitHub stars | 1 |
| Author | 株式会社クインクエ |
| Maintainers | ryoki.eto |
| Keywords | claude-code, sqlite, cache, koji-lens |

## Links

- npm: https://www.npmjs.com/package/@kojihq/core-sqlite
- Repository: https://github.com/etoryoki/koji-lens
- Homepage: https://lens.kojihq.com
- Issues: https://github.com/etoryoki/koji-lens/issues
- npm.io page: https://npm.io/package/@kojihq/core-sqlite

## Dependencies (3)

- [drizzle-orm](https://npm.io/package/drizzle-orm.md) ^0.36.0
- [@kojihq/core](https://npm.io/package/@kojihq/core.md) 0.1.0-beta.13
- [better-sqlite3](https://npm.io/package/better-sqlite3.md) ^12.9.0

## Alternatives

- [memory-cache](https://npm.io/package/memory-cache.md) — 795.0K weekly downloads
- [@httptoolkit/proxy-agent](https://npm.io/package/@httptoolkit/proxy-agent.md) — 11.2K weekly downloads
- [express-cache-controller](https://npm.io/package/express-cache-controller.md) — 5.3K weekly downloads
- [http-cache-middleware](https://npm.io/package/http-cache-middleware.md) — 4.5K weekly downloads
- [cache2](https://npm.io/package/cache2.md) — 1.5K weekly downloads

## Recent versions

- 0.1.0-beta.13 (latest) — 2026-09-24
- 0.1.0-beta.12 — 2026-05-19
- 0.1.0-beta.11 — 2026-05-18
- 0.1.0-beta.10 — 2026-05-11
- 0.1.0-beta.9 — 2026-05-11
- 0.1.0-beta.8 — 2026-05-08
- 0.1.0-beta.7 — 2026-05-08
- 0.1.0-beta.6 — 2026-05-08
- 0.1.0-beta.5 — 2026-05-08
- 0.1.0-beta.4 — 2026-05-02

## README

# koji-lens

[![npm beta](https://img.shields.io/npm/v/@kojihq/lens/beta.svg?label=@kojihq/lens)](https://www.npmjs.com/package/@kojihq/lens)
[![license](https://img.shields.io/npm/l/@kojihq/lens.svg)](./LICENSE)
[![node](https://img.shields.io/node/v/@kojihq/lens/beta.svg)](https://nodejs.org/)
[![CI](https://img.shields.io/badge/CI-Linux%20%7C%20macOS%20%7C%20Windows-success)](https://github.com/etoryoki/koji-lens/actions)
[![X](https://img.shields.io/badge/X-@kojihq__jp-000000?logo=x&logoColor=white)](https://x.com/kojihq_jp)
[![Bluesky](https://img.shields.io/badge/Bluesky-@kojihq.com-0085ff?logo=bluesky&logoColor=white)](https://bsky.app/profile/kojihq.com)

> **Visualize your AI coding usage.** — [lens.kojihq.com](https://lens.kojihq.com) ([English](https://lens.kojihq.com/en))

Your local Claude Code usage analyzer. No servers, no signup — reads your local JSONL logs and shows your token usage with API-equivalent cost.

> **Prerequisite**: koji-lens reads JSONL files that Claude Code writes to `~/.claude/projects/` (Windows: `%USERPROFILE%\.claude\projects\`). If you haven't run Claude Code yet, this directory may be empty and `koji-lens summary` will show no data. Run Claude Code for a few minutes first to generate JSONL logs.

> **Note**: Cost figures are calculated as `tokens × Anthropic API price`. If you use Claude Code via API key, this matches your actual spend. If you use Claude Code via Claude Pro / Max subscription, this is a reference figure — your actual billing is the flat subscription fee. See [FAQ](#faq).

> **Status**: β (public beta). Install with `@beta` tag. See [Known limitations](#known-limitations).

---

## What can you do with this?

Two common situations where koji-lens earns its place.

### Story 1 — Claude Pro / Max subscriber: see what your subscription is really worth

You pay a flat $20/month for Pro (or $200 for Max). But are you using it like a $20 subscription, or like a $500 one? Anthropic doesn't show the answer anywhere.

```bash
$ koji-lens summary --since 30d
TOTAL
  cost: $874.12 (API-equivalent)
  models: opus×1562, sonnet×60
  note: Cost is API-rate equivalent.
        Subscribers pay a flat fee regardless.
```

That `$874.12` is what 30 days of usage would have cost on the API. If you're a $20/month Pro user, you just got 40× your subscription back. That's information you can't get from the Claude Code dashboard or the Anthropic Console — only from your local logs.

### Story 2 — API user: catch overspend before month-end

You pay per token via the API. You suspect Claude Code is burning through Opus on tasks Sonnet could handle, but you want numbers, not hunches.

```bash
$ koji-lens summary --since 7d
TOTAL
  cost:  $187.45
  cost by model:
    claude-opus-4-7    $173.21 (92%)
    claude-sonnet-4-6  $14.24  ( 8%)
  models: opus×238, sonnet×12
```

Now you have evidence: 92% of your spend is Opus. Switch the easy turns to Sonnet, run `koji-lens summary --since 7d` again next week, and see the difference. (A built-in `compare` command lands in a future release; for now you can pipe to `--format json` and diff yourself.)

---

## Install

```bash
pnpm add -g @kojihq/lens@beta
# or: npm i -g @kojihq/lens@beta
```

Node.js 22+ required. **Verified on Linux, macOS, and Windows** (CI matrix runs typecheck + tests + smoke check on all three on every push).

After install, both `koji-lens` and the short alias `lens` are available — same commands work both ways. (`lens` is a koji-lens shorthand and is unrelated to the Kubernetes Lens IDE.)

## 30-second tour

```bash
# Total cost / tokens / tool usage for the last 24 hours
koji-lens summary --since 24h
# or with the short alias: lens summary --since 24h

# Recent sessions (default: last 7 days, top 20)
koji-lens sessions

# Deep dive into one session
koji-lens session <session-id>

# Launch the local web dashboard (charts + session table)
koji-lens serve
# → http://127.0.0.1:3210
```

All commands read directly from `~/.claude/projects/**/*.jsonl` — nothing leaves your machine.

## Commands

### `summary`

Shows aggregated metrics for a period: cost, tokens (input/output/cache), assistant turns, tool usage, top sessions.

```bash
koji-lens summary --since 24h
koji-lens summary --since 7d --format json      # machine-readable
koji-lens summary --since 2w --usd-jpy 160      # override FX rate
koji-lens summary --since 24h --no-cache        # bypass SQLite cache
```

Options: `--since <expr>` (e.g. `24h`, `7d`, `2w`, or ISO date), `--format text|json`, `--dir <path>`, `--usd-jpy <rate>`, `--no-cache`.

### `sessions`

Lists sessions in a period (one line per session: id, ended_at, duration, cost, turns, tools).

```bash
koji-lens sessions                   # last 7 days, 20 sessions
koji-lens sessions --since 30d --limit 50
```

### `session <id>`

Full detail of a single session: file path, time range, duration, per-turn counts, models, tools, cost breakdown.

```bash
koji-lens session 9b1f92a5-8f67-4f2a-91d3-f930adeb0c5f
koji-lens session <id> --format json
```

### `compare`

Compare two periods (e.g., before vs. after switching from Opus to Sonnet) and surface cost / token / model distribution deltas with rule-based insights.

```bash
koji-lens compare --before 30d --after 7d
koji-lens compare --before 2026-04-01..2026-04-30 --after 2026-05-01..2026-05-31
koji-lens compare --before 30d --after 7d --format json
```

Options: `--before <range>`, `--after <range>` (both required), `--format text|json`, `--dir <path>`, `--usd-jpy <rate>`, `--no-cache`.

### `trend`

Weekly trend view of cache efficiency, p95 response time, and other time-series metrics over the last N weeks.

```bash
koji-lens trend                       # default = last 4 weeks
koji-lens trend --weeks 12
koji-lens trend --with-attribution    # Pro: vendor/user attribution
```

Options: `--weeks <num>` (1-52, default 4), `--with-attribution` (Pro), `--format text|json`, `--dir <path>`, `--no-cache`.

### `budget`

Monthly budget tracker. Shows month-to-date cumulative cost, linear forecast, and an over-budget warning.

```bash
koji-lens budget --budget 200
koji-lens budget --budget 200 --with-alerts          # Pro
koji-lens budget --budget 200 --project frontend     # Pro: per-project
koji-lens budget --list                              # Pro: all per-project budgets
```

Options: `--budget <usd>` (required), `--with-alerts` / `--project <key>` / `--list` (Pro), `--format text|json`, `--dir <path>`, `--no-cache`.

### `export`

Export usage data as CSV or JSON for spreadsheets / pipelines. Stays local — no transmission.

```bash
koji-lens export --since 30d                            # CSV to stdout
koji-lens export --since 30d --format json
koji-lens export --since 30d --format csv --out usage.csv
```

Options: `--since <expr>` (required), `--format csv|json` (default csv), `--out <path>` (stdout if omitted), `--dir <path>`, `--no-cache`.

### `hook <state>`

Cross-platform helper that updates `~/.koji-lens/state.json` so the statusline can show the agent state icon (⚡/💤/🛑). Designed to be called from Claude Code hooks — no per-OS shell script needed (no `set-state.ps1` / `set-state.sh`).

```bash
koji-lens hook thinking
koji-lens hook running
koji-lens hook idle
koji-lens hook awaiting_approval
```

States: `thinking` | `running` | `idle` | `awaiting_approval`. Writes silently (no stdout). See the statusline section below for a complete `~/.claude/settings.json` example.

### `serve`

Starts a local web dashboard (Next.js, no external requests).

```bash
koji-lens serve                      # port 3210
koji-lens serve --port 3500
```

Dashboard includes cost/session bar chart, tokens stacked bar, tool usage pie, and a sortable session table.

### `statusline`

Prints a one-glance savings signal comparing this month vs. last month. Designed for [Claude Code's `statusLine` integration](https://docs.claude.com/en/docs/claude-code/settings#status-line) — pick the density that fits your status bar real estate. Drill into details via `koji-lens summary` or the web dashboard.

```bash
koji-lens statusline                       # 💚 -40% 💎 78%                              (default = normal)
koji-lens statusline --mode minimal        # 💚 💎                                       (icons only, max compact)
koji-lens statusline --mode detailed       # 💚 -40% vs last month | $40 saved | 💎 78% cache
koji-lens statusline --no-state            # suppress state icon (⚡/💤/🛑)
koji-lens statusline --no-spend            # suppress spend trend (💚/💛/🚨/⚪)
koji-lens statusline --no-cache-rate       # suppress cache signal (💎)
koji-lens statusline --format json         # full CompareResult + cache rate for scripting
koji-lens statusline --combined            # prepend external statusline output (cross-platform)
```

The cache signal shows this month's prompt-cache hit rate (cache read / (cache read + new input tokens)). Higher = more cache reuse = lower cost per turn. Icon shifts with the rate so you can read the state at a glance without checking the number: 💎 ≥ 70% (excellent) / 🧊 30–70% (cool) / 💧 < 30% (low). koji-lens's independent axis from spend trend.

**Mode selection guide**: `minimal` when you run alongside another statusline and want the smallest possible footprint / `normal` for standalone use / `detailed` when statusline is your only spend dashboard.

#### Optional: koji-buddy (🍙)

Append a small fermentation mascot to the right of the signals. Opt-in via `--buddy`, with optional sayings via `--buddy-speech`.

```bash
koji-lens statusline --mode minimal --buddy                          # 💚 💎 🍙·            (decoration only)
koji-lens statusline --mode minimal --buddy --buddy-speech           # 💚 💎 🍙· < ぽつぽつ…?  (with JA saying, default)
koji-lens statusline --mode minimal --buddy --buddy-speech --buddy-locale en  # 💚 💎 🍙· < Drip... drop...?  (EN saying)
koji-lens statusline --buddy-only                                    # 🍙· < ぽつぽつ…?      (buddy only, suppresses spend/cache/state)
```

**Lv evolution by total session count** (~3 years to Max for heavy users):

| Lv | Decoration | Threshold | Lv | Decoration | Threshold |
|---|---|---|---|---|---|
| 1 | `🍙·` | < 30 | 6 | `🍙★★★` | 3,000 |
| 2 | `🍙+` | 30 | 7 | `🍙❀` | 10,000 |
| 3 | `🍙✦` | 100 | 8 | `🍙✿` | 30,000 |
| 4 | `🍙★` | 300 | 9 | `🍙❋` | 60,000 |
| 5 | `🍙★★` | 1,000 | 10 | `🍙❀❀` | 100,000 (Max) |

Saying state (sick / overfed / healthy / resting / awaiting) is computed from cost trend + agent state. **50 sayings total** (5 states × 10 levels), inspired by Japanese fermentation philosophy. Available in **JA (default) / EN** via `--buddy-locale`. Persist enable/disable + locale with `KOJI_LENS_BUDDY=1` / `KOJI_LENS_BUDDY_LOCALE=en` env vars.

**Flags**: `--buddy` (enable) / `--buddy-speech` (sayings) / `--buddy-type <koji|owl|cat>` (default `koji`; owl/cat coming later) / `--buddy-locale <ja|en>` (default `ja`) / `--buddy-only` (buddy-only display, suppresses spend/cache/state).

#### Optional: agent state icon (⚡ / 💤 / 🛑)

If you write Claude Code's current state to `~/.koji-lens/state.json` from hooks, koji-lens appends an icon: ⚡ running / 💤 idle / 🛑 awaiting approval. The icon disappears automatically after 60 seconds of staleness (so a crashed session doesn't leave a permanent ⚡).

State file schema:

```json
{ "state": "thinking" | "running" | "idle" | "awaiting_approval", "since": 1714680000000, "tool": "Bash" }
```

Example `~/.claude/settings.json` (cross-platform, recommended — uses the built-in `koji-lens hook` command):

```json
{
  "statusLine": {
    "type": "command",
    "command": "koji-lens statusline --mode minimal --combined --buddy --buddy-speech",
    "padding": 0,
    "refreshInterval": 1
  },
  "hooks": {
    "UserPromptSubmit": [{ "hooks": [{ "type": "command", "command": "koji-lens hook thinking" }] }],
    "PreToolUse":       [{ "matcher": "*", "hooks": [{ "type": "command", "command": "koji-lens hook running" }] }],
    "PostToolUse":      [{ "matcher": "*", "hooks": [{ "type": "command", "command": "koji-lens hook thinking" }] }],
    "Notification":     [{ "hooks": [{ "type": "command", "command": "koji-lens hook awaiting_approval" }] }],
    "Stop":             [{ "hooks": [{ "type": "command", "command": "koji-lens hook idle" }] }]
  }
}
```

This single-tool config works on Windows / macOS / Linux (no per-OS shell scripts needed). Pass `--no-state` to `koji-lens statusline` to opt out of the icon entirely.

<details>
<summary>Legacy: PowerShell-wrapper example (pre-beta.7, kept for reference)</summary>

```json
{
  "hooks": {
    "UserPromptSubmit": [{ "hooks": [{ "type": "command", "command": "powershell -NoProfile -ExecutionPolicy Bypass -File C:/Users/<you>/.koji-lens/set-state.ps1 -State thinking" }] }],
    "PreToolUse":       [{ "matcher": "*", "hooks": [{ "type": "command", "command": "powershell -NoProfile -ExecutionPolicy Bypass -File C:/Users/<you>/.koji-lens/set-state.ps1 -State running" }] }]
  }
}
```

The `set-state.ps1` script was Windows-only and never bundled with the CLI; users had to write their own. The `koji-lens hook <state>` command (beta.7+) replaces this entirely.

</details>

Emoji legend: 💚 cost dropped > 10% / 💛 within ±10% / 🚨 cost rose > 10% / ⚪ no last-month data.

### `audit`

Tool-use audit log with PII redaction (11 patterns: email, UUID, JWT, AWS access key, GitHub PAT, Slack webhook, Stripe key, Bearer, card, phone US/JP). Detects anomalies (new MCP server, high-freq exec, sensitive writes).

`audit` uses a SQLite cache (`~/.koji-lens/cache.db`) keyed by file mtime + size:

- First run on a project: parses all JSONL files (typically a few seconds for ~100-200 sessions)
- Subsequent runs: cache hit on unchanged files, only re-parses modified files (typically under a second)
- Speedup varies with your session count, file sizes, and disk I/O.

```bash
koji-lens audit --since 7d                  # list audit events (text)
koji-lens audit --since 7d --explain        # show warnings + 次に何すべきか hint
koji-lens audit --learn-mcp                 # whitelist current MCP servers (clear ⚠)
koji-lens audit --no-cache                  # disable SQLite cache (default: enabled)
```

### `tools`

Per-tool invocation breakdown (Bash / Read / Edit / Write / etc.) with frequency + bar chart.

```bash
koji-lens tools --since 7d                  # top 20 tools, bar chart
koji-lens tools --since 7d --format json    # JSON for scripting
```

### `dashboard`

Alias for `serve` (browser-based local web UI).

```bash
koji-lens dashboard                         # equivalent to `koji-lens serve`
```

### `status`

Show sync status (last synced time, errors, recovery hints).

### `sync` / `login`

Cloud sync to koji-lens Pro (requires login). **The Pro service is currently paused**, so these commands (and the `(Pro)` options below) are not available. Everything else works locally without an account.

### `config`

Persisted in `~/.koji-lens/config.json`.

```bash
koji-lens config list
koji-lens config set logDir "/custom/path/to/.claude/projects"
koji-lens config set usdJpy 160
koji-lens config unset usdJpy
koji-lens config path                # where the file lives
```

## How it works

- **Reads local JSONL directly.** No telemetry, no network calls, no account.
- **SQLite cache** at `~/.koji-lens/cache.db` speeds up repeated runs (~7× faster on the measured case). Pass `--no-cache` to bypass.
- **Per-session streaming parse** with [zod](https://zod.dev). Unrecognized records are skipped silently so format changes in Claude Code don't break the whole analysis.
- **Model pricing** is shipped as `pricing.json` inside the package. Override is possible by editing `node_modules/@kojihq/core/dist/pricing.json` until runtime config lands.

## Known limitations

- β. APIs and CLI flags may change before 1.0.
- Model pricing is kept current at release time. If Anthropic announces a price change, we ship a patch release within a few days.
- Windows is supported (primary dev environment), macOS and Linux are expected to work. File an issue if you hit OS-specific trouble.
- Old sessions from before `~/.claude/projects` existed are not analyzed (use `--dir` if your logs live elsewhere).

## FAQ

**Does this send my logs to any server?**
No. `@kojihq/lens` runs entirely locally. `koji-lens serve` binds to `127.0.0.1` only.

**Can I use it without installing globally?**
Yes: `pnpm dlx @kojihq/lens@beta summary --since 24h` (or `npx @kojihq/lens@beta ...`).

**Why `@beta` tag?**
The `latest` tag also points to the current β now, so `pnpm add @kojihq/lens` works too. We keep `@beta` usage in docs to make it obvious that 1.0 has not shipped yet.

**Does the cost figure match my Claude Code bill?**
It depends on how you use Claude Code:
- **API key (pay-as-you-go)**: Yes, the cost figure matches your actual spend.
- **Claude Pro / Max subscription**: No. Subscribers pay a flat monthly fee regardless of token usage. The cost figure shown here is "what it would have cost on the API" — useful as a reference for comparing usage patterns or evaluating whether the subscription is worth it, but it is not your actual bill.

We're working on subscription-aware features (rate-limit forecasting, usage-balance insights) that are more directly useful to subscribers — see the roadmap.

**Is there a Pro/cloud plan?**
Not at the moment. A cloud-sync Pro plan was in beta but is paused. The local-first experience will always be free.

## Feedback

Using koji-lens? Tell us what numbers surprised you, what's missing, or just say hi.

- **Share your `koji-lens summary` output**: drop a screenshot in [GitHub Discussions #10](https://github.com/etoryoki/koji-lens/discussions/10) — even a single screenshot helps shape the roadmap.
- **Report a bug / request a feature**: [Issues](https://github.com/etoryoki/koji-lens/issues) (use the 💬 Feedback / experience template if you just want to share a reaction)
- **Bluesky**: [@kojihq.com](https://bsky.app/profile/kojihq.com)

We read every reply during β.

## Development

This is a pnpm monorepo. Contributions welcome — file an issue first for non-trivial changes.

```
koji-lens/
├── apps/
│   ├── cli/             @kojihq/lens         (commander-based CLI, public)
│   └── web/             @kojihq/web          (Next.js 16, App Router, Tailwind v4, Recharts; private internal app)
└── packages/
    ├── core/            @kojihq/core         (zod schema, aggregator, pricing, public)
    ├── core-sqlite/     @kojihq/core-sqlite  (SQLite cache adapter for CLI use, public)
    ├── core-pg/         @kojihq/core-pg      (Postgres adapter for Pro cloud sync, public)
    └── ccsg-poc/        @kojihq/ccsg-poc     (Claude Code Security Gateway PoC, private)
```

```bash
pnpm install
pnpm -r build
pnpm -r typecheck
pnpm --filter @kojihq/core test    # vitest, 146 tests
```

Run locally without installing globally:

```bash
node ./apps/cli/dist/index.js summary --since 24h
```

Publishing: see [`docs/publish.md`](./docs/publish.md).

## License

[MIT](./LICENSE) © 2026 Koji

---
_Source: https://npm.io/package/@kojihq/core-sqlite · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
