agentleFS
MeridionaMeridiona/meridian/CLAUDE.md

meridian

CLAUDE.md404 starsChanged 6 months agoMITView on GitHub

Meridian is a single-process Rust daemon that normalises raw screen-capture frames into structured, app-based activity sessions stored in its own SQLite database at ~/.meridian/meridian.db. A Next.js dashboard and a TypeScript MCP server sit alongside the daemon. (Capture source: historically screenpipe's SQLite DB; since the Bucket-2 cutover on feat/in-process-capture the frames are produced in-process by the tray and the daemon reads meridian.db's own capture tables — see "Capture source — in-process" below.)

  • Reads credentials
  • Deletes or force-pushes
  • Installs packages
  • Commits and pushes

The file

Show its rules and text

We split this CLAUDE.md into the rules it gives an agent

39 rules. About 0 are common, 11 are distinctive, and 28 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈11

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 28

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  • could be automatic: a setting could enforce it
  1. Distinctive:

    Do what has been asked; nothing more, nothing less

    line 9
  2. Distinctive:

    NEVER create files unless absolutely necessary — prefer editing existing files

    line 11
  3. Distinctive:

    NEVER create documentation files unless explicitly requested

    line 12
  4. Distinctive:

    ALWAYS read a file before editing it

    line 13
  5. Very specific:

    NEVER commit secrets, credentials, or .env files

    line 14
  6. Distinctive:

    Keep files under 500 lines.

    line 15
  7. Distinctive:

    NEVER run git reset, git push --force, or delete local code — other agents may be working on the codebase in parallel

    line 17
  8. Distinctive:

    NEVER merge a PR automatically — open/update PRs as needed, but leave the actual merge to a human reviewer

    line 18
  9. Very specific:

    ALWAYS use a separate branch per feature/fix — branch name format: type/short-description (e.g.

    line 20
  10. Very specific:

    Every .rs, .ts, and .tsx file must start with this comment as its very first line:

    line 28
  11. Distinctive:

    No network, no auth, no HTTP server, local-only SQLite

    line 268
  12. Very specific:

    Read cursor (etl_cursor, last processed frame_id)

    line 278
  13. Very specific:

    Cross-run gap check: if active_session exists from a previous run and the first new frame is >300 s later, classify and record the gap, …

    line 280
  14. Very specific:

    Intra-batch gap check: before every frame, if the inter-frame gap exceeds GAP_THRESHOLD_SECS (300 s), close the current block at its real …

    line 282
  15. Distinctive:

    When the repowise MCP server is available, use it as part of every code change, not just when convenient:

    line 315
  16. Very specific:

    Read docs/testing.md first.

    line 326
  17. Very specific:

    Avoid unwrap() outside tests.

    line 352
  18. Very specific:

    Add a new numbered file in src/migrations/ — never modify an existing migration

    line 377
  19. Very specific:

    Read src/db/meridian.rs or src/db/screenpipe.rs

    line 574
  20. Very specific:

    Follow the sqlx::query_as + .context("description") pattern

    line 575
  21. Very specific:

    Read src/etl/extractor.rs and src/db/screenpipe.rs

    line 581
  22. Very specific:

    Add the screenpipe read query in screenpipe.rs

    line 582
  23. Very specific:

    Update build_active_session and merge_into_active in runner.rs

    line 584
  24. Very specific:

    Add a migration if the signal needs its own column.

    line 585
  25. Very specific:

    Add an integration test in tests/integration_etl.rs

    line 586
  26. Very specific:

    Follow Coding Conventions → "Porting a dashboard route to Rust" instead — the same playbook applies to a brand-new reader, not just a …

    line 595
  27. Very specific:

    Read docs/notifications.md first — it is the integration guide for the notification service (outbox → deliver → respond → consume …

    line 609
  28. Very specific:

    Read packages/meridian-mcp/dist/index.js to understand existing tool structure

    line 626
  29. Very specific:

    Run npm run build in packages/meridian-mcp/ and verify dist/index.js is updated

    line 628
  30. Very specific:

    Update roadmap if upcoming plans changed — status is in-progress | planned | considering.

    line 636
  31. Very specific:

    Every string in this file is user-facing app text — plain hyphen - only, no em-dash, per the Hard Rules at the top of this file.

    line 637
  32. Very specific:

    After a stable release is published, use GitHub Actions workflow .github/workflows/minimum-version.yml:

    line 645
  33. Distinctive:

    Only the DMG/Tauri updater path uses this policy.

    line 656
  34. Very specific:

    Commit message style: type(scope): short description — e.g.

    line 750
  35. Very specific:

    Never skip hooks with --no-verify

    line 754
  36. Distinctive:

    Never amend a commit that has already been pushed to main

    line 756
  37. Very specific:

    Read docs/ci-cd.md before changing any workflow, release script, branch policy, cache key, updater channel, or product-smoke path.

    line 768
  38. Very specific:

    every successful main CI run emits a traceable candidate-<sha> metadata artifact.

    line 775
  39. Very specific:

    Do not reconstruct retired pre-main, *-staging.*, rolling staging updater, cache-warm, automatic branch-push release, or stable-rebuild …

    line 783

≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

Meridian — Claude Code Instructions

Meridian is a single-process Rust daemon that normalises raw screen-capture frames into structured, app-based activity sessions stored in its own SQLite database at ~/.meridian/meridian.db. A Next.js dashboard and a TypeScript MCP server sit alongside the daemon. (Capture source: historically screenpipe's SQLite DB; since the Bucket-2 cutover on feat/in-process-capture the frames are produced in-process by the tray and the daemon reads meridian.db's own capture tables — see "Capture source — in-process" below.)


Hard Rules

  • Do what has been asked; nothing more, nothing less
  • Meridian has real users running it in production right now — this is not a sandbox, and a bug here can silently destroy someone's data. Weigh every change by its blast radius, not just whether it compiles and the existing tests pass: a change with even a small chance of corrupting data, losing a signed-in session, or crash-looping the daemon/tray must not ship until you've actually reasoned through the failure paths (concurrent writers, a process dying mid-operation, a network drop, an empty/malformed payload) and, where practical, written a test that would have caught it — "it built and the happy path worked" is not the bar. This is not hypothetical: a race where the tray held a meridian.db connection open across a daemon restart, with no WAL checkpoint on either side, shipped to production and left a real alpha tester (issue #851) with a database so corrupted that even raw SQLCipher page reads with the correct key failed — unrecoverable, days of tracked activity gone. Nothing in CI caught it; only live use did. When you're not sure a change is safe, say so and ask, rather than pushing it and hoping — "does it currently pass" and "is it actually safe" are different questions, and only the second one is the one that matters here.
  • NEVER create files unless absolutely necessary — prefer editing existing files
  • NEVER create documentation files unless explicitly requested
  • ALWAYS read a file before editing it
  • NEVER commit secrets, credentials, or .env files
  • Keep files under 500 lines; split when a file grows beyond that
  • Validate all input at system boundaries (config load, DB open, frame parsing)
  • NEVER run git reset, git push --force, or delete local code — other agents may be working on the codebase in parallel
  • NEVER merge a PR automatically — open/update PRs as needed, but leave the actual merge to a human reviewer
  • NEVER push directly to main — always create a separate feature branch, commit there, and raise a PR to main. All features, fixes, and other changes target main, which is the development trunk. Merging to main does not publish a release; release promotion is a separate maintainer action after post-merge validation
  • ALWAYS use a separate branch per feature/fix — branch name format: type/short-description (e.g. feat/trello-oauth, fix/ui-disconnect)
  • In all user-facing app text — window titles, wizard/UI copy, button and menu labels, notification bodies, tray tooltips, any string the user reads — use a plain hyphen - only. NEVER an em-dash (—), en-dash (–), or double hyphen (--). Use it spaced (-) where a dash separates clauses. (This rule is about displayed strings; code comments and docs are exempt.)
  • Any publicly reachable service we deploy must authenticate every request, validate its origin, allowlist the paths it serves, and rate-limit — and it gets deleted the day its last caller does. "Authenticate" is separate from "validate the origin" on purpose: an origin check alone is a header a caller controls, and reading the two as one requirement is what permits an unauthenticated public service. An unauthenticated request must be rejected outright with a 401, and scripts/deploy-gateway.sh now asserts that rather than printing a reminder about it — after up -d it probes both public hostnames four ways (ingest and OO UI × no credentials and wrong credentials) and exits non-zero unless every one answers 401, so a gateway that started answering 200 unauthenticated fails the deploy instead of going green. The wrong-credential probes are not redundant: an unauthenticated 401 still passes if an authenticator were swapped for one that merely checks a header is present. Two properties are load-bearing and easy to regress — a 200 fails immediately rather than being retried, and an exhausted retry budget (000/5xx, i.e. the stack never came up) fails rather than falling through to success, which is exactly the shape of the bug it replaced. bash scripts/deploy-gateway.sh --self-test exercises the status classifier offline; --verify-only runs the four probes against the live gateway without deploying. infra/hf-proxy (hf.meridiona.com) was an unauthenticated reverse proxy to huggingface.co. Its header carried a thoughtful SECURITY: block about cache-key poisoning and auth headers leaking into a shared cache; it never asked who may call this. When the MLX stack that used it was deleted it kept running with no callers and a public DNS record — and Cloudflare publishes every hostname to the Certificate Transparency logs the moment it issues the cert, so scanners find it whether or not you advertise it. It reached 173,088 requests in a day against a 100k/day account-wide cap and took meridiona.com down with Error 1027 for traffic the site did not generate. Assume every hostname you provision is public knowledge immediately.

File Header Requirement

Every .rs, .ts, and .tsx file must start with this comment as its very first line:

//ambient dev tool that watches what you do and updates your PM tickets automatically, boosting developer productivity

SQL migration files use the SQL comment form:

-- ambient dev tool that watches what you do and updates your PM tickets automatically, boosting developer productivity

The commit-msg hook enforces conventional commit format. The pre-commit hook enforces cargo fmt and cargo clippy. The pre-push hook runs the full suite: fmt + clippy + cargo test + UI build + UI tests.


Repository Layout

meridian/
  src/
    main.rs              # daemon entry point — tokio::main, signal handling, poll loop
    lib.rs               # public crate root
    config.rs            # Config::from_env() — reads env vars, expands ~
    notifications.rs     # notification outbox producer API — enqueue/retract (see docs/notifications.md)
    notification_responses.rs # consumer for interactive-toast answers (snooze, …)
    db/
      mod.rs
      meridian.rs        # writes app_sessions, active_session, etl_runs, etl_cursor, gaps
      screenpipe.rs      # read-only queries against screenpipe's frames/ocr/audio/ui_events
    etl/
      mod.rs
      runner.rs          # run_etl() — batch loop, gap detection, block state machine
      extractor.rs       # extract_block_context() — OCR, audio, signals, window titles
    migrations/
      001_initial.sql    # app_sessions, active_session, etl_runs, etl_cursor
      002_gaps.sql       # gaps table, idle_frame_count columns
  meridian-core/         # lean shared data layer — used by BOTH the daemon and the Tauri dashboard
    src/
      lib.rs             # thin manifest: declares modules + curated `pub use` re-exports (stable public API)
      db.rs              # ActiveSession + open_existing + get_active_session (daemon re-exports these)
      settings.rs        # settings.json runtime config reader (daemon re-exports)
      util/              # DB-free helpers, re-exported flat (meridian_core::{intervals,date,hygiene})
        intervals.rs     # wall-clock interval math (port of ui/lib/intervals.ts)
        date.rs          # local-day bounds (port of ui/lib/date-utils.ts)
        hygiene.rs       # board-hygiene reason → hint/fix mapping
      readers/           # the ported /api/* DB readers, re-exported flat (meridian_core::today, ::tasks, …)
        active.rs  coding_agents.rs  integrations.rs  tasks.rs  triage.rs  week.rs  worklogs.rs
        today/           # mod.rs + types.rs (size split — types co-located per module)
  tests/
    integration_etl.rs   # integration tests — in-memory SQLite, no network
  ui/
    app/
      layout.tsx         # root layout
      page.tsx           # dashboard home
      sessions/          # session list and detail pages
      apps/              # per-app breakdown pages
      api/               # Next.js route handlers (active, sessions, stats, timeline)
    components/          # ActiveSessionCard, AppTable, DayTimeline, FocusDonut, Nav, …
  packages/
    meridian-mcp/        # TypeScript MCP server — exposes meridian.db to AI clients
      dist/index.js      # compiled output (committed)
  tray/
    src-tauri/           # Tauri shell (Rust + Tauri framework)
      src/
        main.rs          # Tauri entry point
        lib.rs           # thin app bootstrap (builder, db pool, tray install, invoke_handler)
        tray.rs          # tray menu builder + menu-event dispatch + window openers
        sys.rs           # shared helpers: uid_str, notify, ui_base (deduped)
        install.rs       # install-mode detection + meridian_db_path / .env resolution
        state.rs         # app state and health tracking
        format.rs        # duration formatting helpers (with unit tests)
        reopen.rs        # re-activation routing + onboarding_complete gate (pure, tested)
        window_panel.rs  # popover placement + macOS NSPanel behaviour
        poll/            # background poll loop
          mod.rs         # loop + tick cadence + tray-sync (emit/tooltip/menu)
          refresh.rs     # refresh_health/active/today/worklogs
          notifications.rs # outbox drain + notifications_allowed
        commands.rs      # commands module root: declares submodules + glob re-exports (commands::<fn>)
        commands/        # the #[tauri::command] surface, grouped by domain
          dashboard.rs   # DB reads (get_active/today/week/coding_agents/worklogs/tasks/triage/settings)
          daemon.rs      # restart/toggle/get_status/get_daemon_status
          system.rs      # open_dashboard/open_worklogs/open_permission_pane
          health.rs  logs.rs  openobserve.rs  integrations.rs  parents.rs  version.rs
      Cargo.toml         # Tauri dependencies
    src/
      index.html         # popover UI template
      app.js             # event listeners, UI rendering
      style.css          # popover styling
    package.json         # npm/Node build config
    create-icons.sh      # icon generation script

Dashboard → Tauri fold (cutover landed — branch spike/meridian-core). The Next.js dashboard now runs only inside the Tauri webview as a static export (output: 'export' → ui/out) — no Node server, no /api routes. DB-backed reads live in meridian-core as the single source of truth (the daemon re-exports them, its code unchanged; the tray depends on them directly); file/env/process routes are tray commands (tray/src-tauri/src/). Frontend consumers reach Rust only via Tauri invoke/events through ui/lib/bridge.ts (load/mutate → invoke; subscribe → the event bus — the browser /api fetch + EventSource fallbacks were removed at cutover). The four SSE streams (health/notices/notifications/logs) are now Tauri events the tray poll loop emits (tray/src-tauri/src/poll/live.rs

  • the log-tail tailer); the tray poll loop is HTTP-free (direct meridian-core reads). Response types live in ui/lib/api-types.ts (moved out of the deleted routes). Asset layout: frontendDist → ../../ui/out; the build copies the tray popover into out/popover/ and the main window loads popover/index.html; dashboard/setup windows load WebviewUrl::App("today"/"setup") → out/<route>/index.html (trailingSlash: true). The popover works in BOTH profiles: tauri.conf.json's beforeDevCommand runs node scripts/sync-popover.mjs dev, which copies tray/src/ into ui/public/popover/ for next dev to serve, and the build does the same into out/popover/. (This used to be a documented "404s under tauri dev" limitation; the sync script closed it.) When adding a route, follow the playbook in Coding Conventions → "Porting a dashboard route to Rust"; exemplars: meridian-core/src/readers/triage.rs, tray/src-tauri/src/commands/parents.rs. The dashboard ships embedded in the tray binary (tauri build → generate_context! bundles ui/out); the standalone-Node-server release machinery (the com.meridiona.ui plist, ui-start.sh, the ui.tar.gz packing, the pinned Node runtime + better-sqlite3 ABI dance) was retired, and backend_install.rs boots out any leftover com.meridiona.ui agent on update. The tray calls meridian::observability::init("meridian-tray") unconditionally in every build — the old dev-only otel feature was removed, because the tray is the process the user actually clicks and it was otherwise dark in release. Rationale + full scope: Obsidian Decisions/Dashboard frontend - keep Next in Tauri.md, ~/.claude/plans/meridian-next-fold.md.

Per-OS Tauri config — tauri.windows.conf.json (read before editing bundle.resources)

Tauri auto-merges tauri.<platform>.conf.json into tauri.conf.json when building for that platform (no flag; detected from the target). Meridian uses tray/src-tauri/tauri.windows.conf.json for everything Windows-specific — bundle.targets, the daemon resource, NSIS options — so tauri.conf.json stays the macOS source of truth and is never edited for Windows.

The gotcha: the merge is JSON Merge Patch (RFC 7396), which merges objects key by key rather than replacing them. bundle.resources is a map, so the macOS entries (target/release/meridian, com.meridiona.daemon.plist) would otherwise survive into the Windows bundle and fail the build — the file names differ (.exe) and a plist is meaningless there. They are explicitly set to null, which is how RFC 7396 spells "delete this key".

So: adding a resource to tauri.conf.json means also deciding what Windows does with it. If it is macOS-only, null it out in tauri.windows.conf.json. Arrays and scalars (e.g. bundle.targets) replace wholesale and need no such care.


Build, Test, Lint

Rust daemon

# Build (SQLX_OFFLINE=true is set automatically via .cargo/config.toml)
cargo build --release

# Run all tests — `--workspace` is REQUIRED, see the warning below
cargo test --workspace

# Lint (must pass before committing)
cargo clippy --workspace --all-targets -- -D warnings

# Format (must pass before committing)
cargo fmt

Always pass --workspace. members = [".", "meridian-core", "meridian-oauth", "tray/src-tauri"] makes the repo root itself a package, so a bare cargo test / cargo clippy runs against that package alone and silently skips the other three. They still compile (the daemon depends on them), which is what makes the omission so convincing — they are simply never tested and their test code is never linted. This hid two red db_crypto tests for days with every gate green; CI and the pre-push hook now pass --workspace for exactly this reason.

Rust toolchain is pinned to 1.93.1 via rust-toolchain.toml.

Next.js dashboard (ui/)

cd ui
npm install
npm run dev    # development server
npm run build  # production build

MCP server (packages/meridian-mcp/)

cd packages/meridian-mcp
npm install
npm run build  # compiles TypeScript → dist/index.js

Tauri tray app (tray/)

cd tray

# Development (hot reload)
npm install
npm run tauri dev

# Production build
bash create-icons.sh
npm install
npm run tauri build  # outputs binary to src-tauri/target/release/meridian-tray

# Rust linting & testing (src-tauri/)
cd src-tauri
cargo fmt --check
cargo clippy -- -D warnings
cargo test

The dashboard has a bun test suite — ui/__tests__/ (409 tests across 29 files as of 1.83.0), run with bun test from ui/. Many are source-scanning rather than behavioural (cursor-pointer.test.ts, no-native-dialogs.test.ts): they read the .tsx and assert on what it contains, which is the only available guard for things a headless run cannot exercise. New JS/TS tests go under ui/__tests__/, packages/meridian-mcp/src/__tests__/, or tray/src-tauri/src/__tests__/.


Environment Variables

VariableDefaultPurpose
MERIDIAN_DB~/.meridian/meridian.dbPath to meridian's output SQLite file
MERIDIAN_DB_KEY(unset → unencrypted)64-hex-char SQLCipher raw key for meridian.db. Generated once by the tray (tray/src-tauri/src/db_key.rs, stored in the OS keychain) and mirrored into .env for the daemon to read — never set this by hand except for local testing (see meridian-core/src/db_crypto.rs).
POLL_INTERVAL_SECS60ETL poll cadence in seconds
RUST_LOGmeridian=infoTracing filter
SQLX_OFFLINEtrue (via .cargo/config.toml)Prevents sqlx from hitting the DB at compile time
MERIDIAN_OTLP_ENDPOINT(unset → default http://localhost:5080/api/default/v1/traces)OpenObserve OTLP/HTTP traces endpoint override — consulted only on the DEV/bare shipping path (a packaged install ships to the release-baked central gateway instead; see the Observability section below)
MERIDIAN_OO_AUTHDEPRECATED — ignored everywhereOO credentials live in settings.json (oo_email/oo_password)
MERIDIAN_TELEMETRY_DISABLED(unset → capture always on)Hard kill switch for OTel span/log capture to the local spool — the sole log/trace sink; disabling it leaves only launchd's raw stdout/stderr crash-safety-net files.
MERIDIAN_LAUNCHD_LOG_MAX_MB10Size cap for each launchd-redirected raw log file (daemon.log, etc.); capped via copytruncate on the telemetry shipper's tick (src/telemetry_spool/shipper.rs).
MERIDIAN_EMBEDDER_DIR~/.meridian/models/<repo-basename>/Override the on-disk directory the session-distiller embedding weights live in (src/embedder/provision.rs).
MERIDIAN_EMBEDDER_REPOBAAI/bge-small-en-v1.5Override the HuggingFace repo the embedder weights are fetched from.
DISTILLER_SEM_DEDUP_THR0.86Cosine threshold for the distiller's semantic dedup (src/worklog_pipeline/distiller/).
MERIDIAN_CAPTURE_RETENTION_DAYS30Age floor for the capture_frames/capture_ui_events/capture_secondary_screens retention sweep (src/etl/capture_retention.rs) — only prunes rows both older than this AND already consumed by the ETL cursor.

Tilde expansion is handled by Config::from_env(). Never hardcode paths.


Architecture

Single-process Rust daemon

  • No network, no auth, no HTTP server, local-only SQLite
  • Two connection pools: screenpipe (read-only WAL), meridian (read-write WAL)
  • On startup: cleanup_incomplete_runs removes partial sessions left by a previous crash, then runs the first ETL pass immediately before entering the poll loop
  • Poll loop: tokio::select! over SIGINT/SIGTERM and a sleep timer; on each tick calls run_etl()
  • Graceful shutdown closes both pools

ETL pipeline (src/etl/runner.rs)

run_etl() is the single entry point called every poll interval:

  1. Read cursor (etl_cursor, last processed frame_id)
  2. Insert an ETL run row with status = 'running'
  3. Cross-run gap check: if active_session exists from a previous run and the first new frame is >300 s later, classify and record the gap, then close the stale session
  4. Process frames in batches of 500 (BATCH_SIZE), maintaining a block state machine keyed on app_name
  5. Intra-batch gap check: before every frame, if the inter-frame gap exceeds GAP_THRESHOLD_SECS (300 s), close the current block at its real ended_at, record the gap, then start fresh
  6. App-switch close (close_block): when app_name changes, close the old block into app_sessions; apply Option C (ui_event refines ended_at) and Option D (single-frame sessions use next_frame_ts)
  7. Active session upsert (upsert_open_block): the still-open block at end of all batches goes into active_session (single-row table, id = 1)
  8. Advance cursor, mark ETL run success (or failed with error text on error)

Gap classification

count_frames_in_window(screenpipe, from, to) counts all frames inside the gap window, including frames with NULL app_name. If idle_count * 2 >= total_count → user_idle, else → system_sleep. A gap of exactly 300 s does not trigger (threshold is strictly greater than).

DB schema (meridian.db)

TableRole
app_sessionsCompleted sessions — append-only, never updated after insert
active_sessionSingle-row in-progress block, upserted every poll
etl_runsAudit log — one row per run_etl() call
etl_cursorSingle-row cursor tracking last_frame_id
gapsSleep/idle periods — user_idle or system_sleep

JSON columns (window_titles, ocr_samples, elements_samples, audio_snippets, signals) store structured sub-documents. ocr_samples and elements_samples are capped at 20 entries per session via OCR_SAMPLE_CAP. Audio snippets are uncapped. Window title counts are merged and re-sorted descending on each upsert.

Capture source — in-process (Gap-2 Bucket 2 cutover, branch feat/in-process-capture)

The daemon no longer reads screenpipe. Since the slice-4b cutover, capture runs in-process in the tray (behind the capture feature): the forked screenpipe-screen + screenpipe-a11y crates produce a11y-tree/OCR frames + input events, which meridian_core::capture writes into capture_frames / capture_ui_events in meridian.db. The daemon ETL reads those tables (via src/db/screenpipe.rs, name unchanged for now) from the meridian pool — there is no screenpipe DB/process/pool anymore. Implication: a build with the capture feature OFF has no data source (the daemon produces no sessions); the shipping DMG must enable it. Audio is dropped (get_audio_snippets stubbed empty) and gaps all classify system_sleep (no in-process idle detection yet — capture_trigger is NULL); both are accepted v1 degradations with idle-detection/audio as future slices. The SCREENPIPE_DB env var + Config::screenpipe_db field have been removed (the daemon never reads a screenpipe DB anymore).

Column contract: capture_frames mirrors screenpipe's frames read-subset (app_name/window_name/browser_url/timestamp/capture_trigger + full_text(OCR)/accessibility_text(a11y)/text_source, resolved by COALESCE(full_text, accessibility_text)); capture_ui_events mirrors the ui_events read-subset (event_type/app_name/text_content/timestamp). Inverted ownership: these tables are written by the tray, read by the daemon.


Before Making Changes

Use repowise (MCP) before editing code

When the repowise MCP server is available, use it as part of every code change, not just when convenient:

  1. Orient — get_overview (new area) or get_context on the files you expect to touch.
  2. Find the blast radius — get_symbol for callers/callees of anything you change; read the *_basis field before concluding "nothing calls this".
  3. Check risk — get_change_risk / get_risk on each file before modifying it; get_why when the code looks odd, to learn the decision behind it before undoing it.
  4. Verify freshness — every response carries _meta.indexed_commit. Compare it with git rev-parse HEAD; if they differ, treat repowise answers as a lead and confirm against the live files.

Repowise does not replace reading the file: it returns signatures and line ranges, never source bodies, so always read the real file before editing it.

ETL logic, DB schema, or migrations

Read docs/testing.md first. Integration tests live in tests/integration_etl.rs and use in-memory SQLite — they must continue to pass after any ETL or schema change. Run cargo test before committing.

Key invariants the tests enforce:

  • A block with no app switch stays in active_session, never in app_sessions
  • An app switch closes the old block into app_sessions with correct frame_count and duration_s
  • duration_s never includes gap time — the pre-gap block closes at the last real frame timestamp
  • Option C applies only when the ui_event timestamp is strictly after the last frame timestamp
  • A gap of exactly 299 s must not produce a gap row (threshold is strictly greater than 300)
  • cleanup_incomplete_runs deletes partial sessions and marks the run aborted
  • idle_frame_count reflects screenpipe capture_trigger = 'idle' frames only

Product decisions

Read docs/vision.md first.


Coding Conventions

Rust

  • Error handling: anyhow::Result throughout; add .context("…") to every ? in DB calls
  • Logging: tracing::info!/warn!/error!/debug! with structured fields — no format strings for data values
  • Clippy: all warnings are errors (-D warnings enforced in .cargo/config.toml and CI)
  • Argument limit: clippy's 7-argument limit applies; group related params into a struct (see BlockBounds in runner.rs)
  • Avoid unwrap() outside tests; use ? or explicit error handling
  • ETL state machine lives in runner.rs — add sub-step helpers inside that module rather than new top-level modules

Porting a dashboard route to Rust (Next-fold playbook)

The fold replaces every ui/app/api/* route with a Rust command the frontend calls over Tauri invoke. This is the standard for the work — follow every step when porting a route. Exemplars to copy: meridian-core/src/readers/triage.rs (DB read) and tray/src-tauri/src/commands/parents.rs (shell-out).

  1. Place it by data source. A DB-backed read → a new module under meridian-core/src/readers/, added to readers/mod.rs and re-exported flat from lib.rs (pub use readers::<name>;) so the public path stays meridian_core::<name> (the daemon re-exports it if it needs it too). Reuse meridian-core::{intervals,date} — never re-derive time/day math. Anything reading files / env / a process / external HTTP (settings.json, .env, launchctl, npm registry, shelling out to meridian) → a module under tray/src-tauri/src/commands/ (grouped by domain), declared + glob-re-exported in commands.rs; keep meridian-core DB-only.
  2. Match the route byte-for-byte. Replicate its shaping exactly: defaults, null → '' coercions, truncation, ordering, and graceful missing-table/column detection (sqlite_master / pragma_table_info). Comment any deliberate divergence (e.g. a BTreeMap sorts keys vs the route's insertion order — fine when consumers read by key).
  3. Thin command wrapper. A #[tauri::command] resolves request-scoped values (today / now / day) and calls the core fn, so the core stays deterministic and testable. Register it in lib.rs's invoke_handler!. Every new window label must be added to capabilities/default.json or its invokes are silently denied.
  4. Document it (required). Module //! header with: one-line purpose + which route it ports, a # Who calls this (the command + the frontend consumer), and a # Related section linking sibling modules / dependent fns via intra-doc links ([`crate::tasks`]). Every pub fn/struct gets a /// covering purpose, key params, return, and any non-obvious behaviour carried from the source.
  5. Trace it (required). #[tracing::instrument(skip(pool))] on both the command and the core fn; wrap each query in .instrument(tracing::debug_span!("<module>.read.<table>")); tracing::debug!(rows = …) after a query; a tracing::info!(…) summary on serve; tracing::warn!(error = %e, …) on the command's error path. All of it exports to OpenObserve under the tray otel feature / the daemon's observability::init.
  6. Wire the consumer. Call the command through @/lib/bridge: load(apiPath, 'command', args) for a read, mutate(apiPath, 'command', body, method) for a write, subscribe(apiPath, 'command'|null, eventName, onData) for a live stream. These are Tauri-only now (the /api fetch/EventSource fallbacks were removed at cutover); apiPath is vestigial (documents the former route). Response types go in ui/lib/api-types.ts, never a route file. A live stream also needs an emitter in tray/src-tauri/src/poll/live.rs (or the log tailer) and the event covered by the window's core:event permission.
  7. Test it. Pure mappers/parsers → #[cfg(test)] unit tests in-module (see hygiene.rs). DB readers → an in-memory seeded test in meridian-core/tests/readers.rs (single-connection :memory: pool, hand-computed rows; place date-bounded rows relative to local_day_bounds(today) so the test is timezone-independent).

TypeScript / Next.js

  • The MCP server uses sql.js (pure WASM, no native compile step) — deliberately chosen over better-sqlite3 after native-module ABI mismatches across Node versions/platforms caused real distribution pain (see packages/meridian-mcp/src/db-cache.ts's header comment). Do not swap it back.
  • UI API routes live in ui/app/api/; keep them thin — query, transform, return JSON
  • No any types unless unavoidable and justified with a comment
  • NEVER window.confirm / window.alert / window.prompt — they do nothing in the packaged tray. WKWebView routes JS dialogs through the host app's WKUIDelegate, and nothing in the stack installs one (wry, tauri-runtime-wry, tauri, tauri-utils were each grepped for ConfirmPanel|AlertPanel|WKUIDelegate — all empty), so confirm() always returns false and alert() is a no-op. The damage is silence: a falsy confirm() is indistinguishable from the user clicking Cancel, so the gated action quietly never runs while every log, gate and test still passes. That is how the db.corrupt Repair Database button shipped dead in 1.83.0 — recovery had to be driven by hand from a terminal. Use @/components/ConfirmDialog (ConfirmDialog for consent, AlertDialog for failures). __tests__/no-native-dialogs.test.ts fails the build if they come back. tauri-plugin-dialog would also work but is not a dependency, and adding one costs a capability grant for a box the webview can render itself.
  • Spawning the meridian binary: ALWAYS use crate::install::meridian_bin() (Rust), never a bare "meridian" and never a hand-rolled candidate list. This moved: @/lib/meridian-bin and its selectMeridianBinary(meridianCandidates()) no longer exist — the dashboard is a static export with no server-side process spawning, so every shell-out is a tray command now. The ordering rationale carried over intact and is why the helper exists: a process started under launchd has a minimal PATH without Homebrew's node, so the #!/usr/bin/env node wrapper at ~/.local/bin/meridian dies with env: node: No such file or directory. meridian_bin() therefore probes the native staged binary first (~/.meridian/bin/meridian, no runtime deps), falls back to the user-local wrapper, and only then to bare meridian on $PATH. MERIDIAN_BIN overrides everything (logged; ignored with a warning if it points at nothing). On Windows the staged name is meridian.exe — the candidate list must match exactly or every shell-out silently falls through to the $PATH last resort, which is usually empty on a per-user install.

SQL migrations

  • Add a new numbered file in src/migrations/ — never modify an existing migration
  • Include the file header comment on line 1
  • The integration test helper make_meridian_db() runs all migrations; new migrations are covered automatically by cargo test

Observability (logs & traces — local-only capture; dev ships full-fidelity to its own OO, packaged ships redacted error-only to central)

Any new or changed code path that does real work (daemon stages, the distiller/embedder, the worklog pipeline, coding-agent ingest) must emit structured logs and traces — not just println! to a terminal. Add proper logs and traces as you write the code, not as an afterthought.

One pipeline, no duplicates. The local OTel telemetry spool (~/.meridian/telemetry/{pending,sent,quarantine}/, raw OTLP protobuf) is the sole log/trace sink — there is no separate JSONL file and no tracing-driven stdout/stderr mirror. Every tracing::*! call goes through this one pipeline, unconditionally (a local disk write, not a network call, so it never depends on otlp_enabled or OpenObserve being reachable — the only escape hatch is MERIDIAN_TELEMETRY_DISABLED, a dev/test kill switch). meridian logs [--service <name>] [-n N] [-f] (src/telemetry_spool/render.rs) decodes this same spool back into human-readable lines on demand — this is the one supported way to read logs locally, replacing the old JSONL-tailing UI and the old bash meridian logs (which used to tail launchd-redirected stdout/stderr text).

Four couplings that silently delete error coverage - or cause an egress. Each has bitten at least once; none fails loudly, and none is visible from the call site.

  1. The EnvFilter decides what is captured at all — before the spool, before severity, before redaction. EnvFilter matches directives against targets by string prefix, so the meridian directive covers meridian_core::*, meridian_tray_lib::* and meridian_oauth::* for free — but nothing else. Any crate whose target does not start with meridian is discarded entirely unless named in observability::filter. That is why CAPTURE_TARGETS exists (screenpipe_screen/screenpipe_a11y — the OCR + accessibility stack, ~48 error sites that were invisible). Adding a dependency that does real work means adding its bare crate name to that list — every log level then picks it up automatically — and auditing its warn!/error! bodies first: third-party crates were written to print to a terminal and may interpolate content that must never egress.
  2. The attribute allowlist is keyed on the names you actually type. tracing::warn!(error = %e, …) emits the attribute key error, not the semconv error.message. Anything not on redact::SAFE_STRING_KEYS is dropped from the ship leg, so a well-instrumented error can arrive as a bare static string with its cause stripped. When adding a field to a WARN/ERROR site that you would need in order to debug it remotely, check it is on that list — and if it names the user's data (ticket key, file path, app name, window title, hour/day) it must stay off, so put the diagnostic value in the message or an allowlisted key instead.

    Two corollaries, both measured on 2026-08-24 and both fixed since: allowlisting is keyed on the exact word you typed, and some words are banned for an unrelated reason. The clerk plugin logged a serde_path_to_error JSON pointer as path, reasoned correctly in a comment that a field path is safe to ship — and lost it anyway, because path is deliberately denied as a filesystem path. It ships now as json_pointer. Widening path would have traded a real protection for a diagnostic; renaming the field was the cheaper half. Likewise a full binary path (bin) stays denied while bin_source — a closed set of literals from install::bin_source — ships in its place.

  3. The log BODY is not an attribute, and nothing filters it. The allowlist governs attribute KEYS; the body is the record, so it always ships, having passed only scrub_text's URL/email/blob patterns — which know nothing about ticket keys, window titles, or a tracker's error payload. CLAUDE.md has said "structured fields — never format data values into the message string" from the start, and nothing enforced it, so it drifted at three tray call sites that spliced a meridian subprocess's stderr into a WARN body. Issue #872 measured the result: a real user's ticket key (ENG-7041) in central OpenObserve, from a value the allowlist denies as an attribute. It is now enforced — errors.rs::no_user_data_interpolated_into_a_log_body walks every workspace source tree and fails the build on a new interpolated WARN+/ERROR body, with INTERPOLABLE as the deliberate, justified exemption list. The corollary when you fix one: move the value to an UNALLOWLISTED attribute rather than deleting it. Unallowlisted attributes are captured at full fidelity locally (meridian logs renders them; export bundles carry the raw spool) and dropped on the ship leg — that is the two-tier design working, and it is why stderr_tail costs the engineer debugging their own machine nothing. Deleting the value instead is #867's mistake wearing #872's clothes.
  4. A u64 field is not shipped as a number. tracing-opentelemetry 0.28's Visit impl has no record_u64, so tracing::field::Visit's default applies and forwards to record_debug — which emits a StringValue. The field then misses the allowlist (nobody lists timeout_s as a string key) and is dropped, while the identical field written as f64 or i64 ships fine. In production this meant every cli_exec.rs timeout shipped timeout_s = null while the distiller's as_secs_f64() shipped 210.0 on 3,329 records — same name, same severity, kept or dropped purely by Rust type.

    redact::is_bare_number now rescues these: a StringValue whose ENTIRE value parses as a finite number is kept. That is a type rescue, not a key exemption — IntValue/DoubleValue were already kept unconditionally for every key, so this restores the intended semantics rather than widening egress. Requiring the whole value to parse is what still excludes real record_debug output (?args → ["plan-task-draft", "--note", "…"], ?path → a home directory).

The only thing this pipeline structurally can't capture is a hard crash (panic before init runs, segfault, OOM kill) — for that, launchd's own stdout/stderr redirect (~/.meridian/logs/<service>.log / <service>-error.log, unrelated to tracing/logging) is the OS-level safety net. It has no log volume during normal operation (nothing mirrors into it deliberately) and is size-capped (MERIDIAN_LAUNCHD_LOG_MAX_MB, copytruncate, telemetry_spool::shipper) and folded into diagnostics export bundles alongside the spool.

Shipping has TWO modes, split by install type (src/observability/otlp_target.rs::resolve_otlp_target). The daemon's telemetry_spool::shipper background task is still the ONLY thing that ever ships spooled files anywhere:

  • Dev / Bare checkout → the engineer's OWN local OpenObserve, gated on otlp_enabled + oo_email/oo_password, Basic auth, full fidelity (no redaction). Unchanged.
  • Canonical (packaged DMG) → Meridian's central OpenObserve via the ingest gateway (ops/central-observability/), gated on the error_reporting_enabled setting (opt-out, default true), Bearer auth with a release-baked write-only token, and redacted + error-only (telemetry_spool::redact). The endpoint and token are release-injected option_env! constants, so a source build is inert and can never ship to prod by accident.

Redaction applies to the ship leg only — it produces a separate stripped copy to POST, so local capture and meridian logs stay full-fidelity. Two things it guarantees that are easy to regress: only WARN+ logs / ERROR-status spans egress at all, and host.name is replaced by a stable pseudonym (redact::local_host_pseudonym) rather than shipping the raw hostname, which on macOS is routinely the account holder's real name. The tray's Sentry before_send applies the identical pseudonym to event.server_name.

The pseudonym is seeded from a hardware id, NOT the hostname — and the ship leg replaces host.name rather than hashing whatever was captured. This is not a stylistic choice: on macOS HostName is unset by default, so the kernel hostname is derived from the network (measured on a dev Mac, hostname was byte-identical to the router's reverse-DNS record for the current IP, itself derived from a per-network randomised Wi-Fi MAC). Seeding from it gave the same machine a new identity on every network change, silently breaking the grouping the value exists for. See telemetry_spool::machine_id before touching any of this; pseudonym_is_independent_of_the_captured_hostname pins it.

ALPHA EXCEPTION (until 2026-12-31, redact::ALPHA_ACCOUNT_OVERRIDE_EXPIRES_UNIX): while Meridian is in hand-picked-tester alpha, the two paragraphs above and below are only true when signed out. While a tester is signed in, local_host_pseudonym deliberately seeds from a salted hash of their Clerk account email instead (redact::pseudonymize_account, mirrored into settings.json's account_pseudonym by the tray on sign-in/out — never the raw email) — so support can trace one tester's errors across their Mac and Windows machines, at the cost of the pseudonym now being genuinely tied to an account rather than only a machine. redact::support_id_is_account_scoped reports which mode is currently active (surfaced in Settings → Account's copy) so this state is never asserted where it isn't true. Past the expiry date every install reverts to the per-machine-only behaviour described below, automatically, with no deploy required.

That pseudonym is the ONLY identifier on an error row — nothing associates it with an account, and the hash is one-way. So it is surfaced to the user as Support ID (Settings → Account, and bundle-info.txt inside an export bundle), which is what makes a support ticket traceable to its error rows at all. Both the displayed value and the shipped one come from redact::local_host_pseudonym on purpose — computing either side separately would let them drift, and the user would quote an ID matching nothing, silently (displayed_pseudonym_matches_shipped pins this).

Which resource attributes actually ship is a separate question from the allowlist, and the two are easy to confuse: redact::SAFE_STRING_KEYS lists many keys that nothing populates (service.instance.id, os.version, app.version, app.install_mode, …). observability::init's Resource::new sets exactly: service.name, service.version, host.name, deployment.environment, os.type, host.arch — and Resource::new runs NO detectors, so the SDK contributes nothing either. Allowlisted ≠ present: before relying on an attribute in a query or dashboard, check it is set here. Note observability::init runs in BOTH the daemon and the tray, so any attribute added there must be correct for both — app.install_mode is deliberately left unset for exactly this reason (see the comment there).

Export Diagnostics remains the manual path, unchanged and independent of consent: tray Settings → Account → Export Diagnostics (or meridian telemetry export) bundles the spool + the launchd crash-safety-net logs into a .tar.gz the user hands to support, imported by hand with meridian telemetry import <bundle> --endpoint <url> --auth <base64>. The bundle also carries a synthesized bundle-info.txt (Support ID, version, channel, os, arch) so a hand-delivered archive can be joined to that machine's already- ingested rows. The bundle is NOT redacted, and it is a superset of what the automatic ship leg sends — build_export_bundle copies pending/ and sent/ verbatim, and the spool is captured at full fidelity, so the archive carries INFO/DEBUG records and unredacted attributes that the WARN+-only, redacted ship leg strips. (An earlier version of this line claimed the opposite; it was wrong, and docs/privacy.md now tells users to inspect the archive before sending it.) Retention (default 7 days, MERIDIAN_TELEMETRY_RETENTION_DAYS) applies to both pending/ and sent/, regardless of shipping status.

  • Rust: tracing::info!/warn!/error!/debug! with structured fields — never format data values into the message string (already enforced).
  • Wrap discrete operations in spans (tracing::info_span! / debug_span!) and put the meaningful inputs, outputs, and metrics as span attributes, not buried in log lines. For an LLM/model call, capture the EXACT input as sent and output as received (post-cap/post-template — reflect any truncation that actually happened), plus real token counts/latency. See src/llm/resolver.rs's llm.call span tree (request → infer → response) and src/worklog_pipeline/distiller's distil.run span for the reference shape.
  • No duplication, no truncation of debug data: emit each fact once, on the span that owns it; don't truncate the values you'd actually need to debug a misclassification. Keep static/identical-every-call blobs (e.g. the full system prompt) out of every trace where a size + a single archived copy suffices.
  • Set span status ERROR (with a message) on failures, and log a warning/error with .context/extra at the failure boundary.
  • Shipping degrades silently: code must never crash because OpenObserve is unreachable or export is disabled — capture (the only thing every install can rely on) is unaffected either way.

Common Tasks

Add a new DB query

  1. Read src/db/meridian.rs or src/db/screenpipe.rs
  2. Follow the sqlx::query_as + .context("description") pattern
  3. Export from src/db/mod.rs if needed
  4. Run cargo clippy --workspace --all-targets -- -D warnings && cargo test --workspace

Add a new ETL extraction signal

  1. Read src/etl/extractor.rs and src/db/screenpipe.rs
  2. Add the screenpipe read query in screenpipe.rs
  3. Extend BlockContext in extractor.rs and wire it in extract_block_context()
  4. Update build_active_session and merge_into_active in runner.rs
  5. Add a migration if the signal needs its own column; otherwise store as JSON in signals
  6. Add an integration test in tests/integration_etl.rs

Add a new dashboard data source (there are no UI API routes)

ui/app/api/ does not exist. The Next-fold deleted every route handler: the dashboard is a static export inside the tray webview, with no Node server to host them. There is nowhere to put a route.ts, and better-sqlite3 is not a dependency of ui/.

Follow Coding Conventions → "Porting a dashboard route to Rust" instead — the same playbook applies to a brand-new reader, not just a ported one. In short: a DB-backed read becomes a module under meridian-core/src/readers/; anything touching files, env, a process, or external HTTP becomes a #[tauri::command] under tray/src-tauri/src/commands/; the frontend reaches it through ui/lib/bridge.ts (load/mutate/subscribe), and its response type goes in ui/lib/api-types.ts.

Spawning the meridian binary is a Rust concern now: use crate::install::meridian_bin(), never a bare "meridian". It is the Rust port of the old Node helper and keeps the same ordering rationale (native staged binary first, because it has no runtime deps and survives launchd's minimal PATH).

Add a notification (plain toast or interactive nudge)

Read docs/notifications.md first — it is the integration guide for the notification service (outbox → deliver → respond → consume lifecycle, category registry, response handlers, expiry/persistence semantics, plugin gotchas, and the packaged-build test recipe). In short:

  1. Plain: one notifications::enqueue(...) call with a scoped dedup_key (src/notifications.rs). Never gate on settings in the producer — policy lives in meridian-core at drain time.
  2. Interactive: add the category (id + buttons JSON) to meridian-core/src/notifications.rs::categories, stamp it on the row via .category()/.actions(), and handle the answer with a match arm in src/notification_responses.rs (handlers must be idempotent).
  3. Interactive toasts only work in packaged builds (UNUserNotificationCenter needs a .app bundle) — test per the recipe in docs/notifications.md.

Add a new MCP tool

  1. Read packages/meridian-mcp/dist/index.js to understand existing tool structure
  2. Edit the TypeScript source in packages/meridian-mcp/src/
  3. Run npm run build in packages/meridian-mcp/ and verify dist/index.js is updated

Add a What's New entry per release

The dashboard's "What's New" modal (ui/components/timeline/WhatsNewModal.tsx, opened via the toolbar nav pill or auto-opened once per app version by the tray's poll::whats_new_auto_open) is hand-curated, deliberately separate from the auto-generated CHANGELOG.md — that file is commit-level and too internal to show end users (e.g. hf-proxy: bake MERIDIAN_HF_ENDPOINT into the staging channel).

  1. Edit tray/src-tauri/resources/whats-new.json (compiled into the tray binary via include_str!, not Tauri resource-bundling — a rebuild always picks up the change).
  2. Add a new object to the front of releases (newest-first): version, date, and items — 1-3, each a short title (≤44 chars) plus a body of one short sentence (≤160 chars). There is deliberately no highlights/fixes split: which bucket a change came from is our concern, not the reader's, and the split doubled the length of every entry. release_notes_stay_short in whats_new.rs fails the build if these limits are exceeded — they are the feature, not a style preference, because notes nobody finishes reading are notes nobody reads. Pick the two or three changes a user would actually notice and drop the rest; never paste a commit message verbatim.
  3. Update roadmap if upcoming plans changed — status is in-progress | planned | considering.
  4. Every string in this file is user-facing app text — plain hyphen - only, no em-dash, per the Hard Rules at the top of this file.
  5. cargo test -p meridian-tray (from tray/src-tauri/) covers whats_new_json_parses, which fails the build if the JSON doesn't match the expected shape.

Make a DMG release mandatory (force-install on old versions)

Minimum supported version is post-stable fleet policy, not source/build configuration. Do not add back tray/minimum-version.

After a stable release is published, use GitHub Actions workflow .github/workflows/minimum-version.yml:

  • action=set, minimum_version=X.Y.Z arms the floor after verifying that vX.Y.Z is a published stable release and is not newer than latest.
  • action=clear removes the floor and restores consent-based updates.
  • The workflow mutates only the latest stable release's latest.json; it never rebuilds, signs, tags, or republishes binaries.
  • Stable promotion preserves any existing floor across later stable releases.
  • update::enforce_minimum_version remains the app-side enforcer.

Only the DMG/Tauri updater path uses this policy.


Coding-agent pipeline (src/coding_agent_session_ingest/)

The coding-agent indexer + summariser run inside the Rust daemon (src/coding_agent_session_ingest/), spawned as gated tokio tasks from main.rs. They turn coding-agent conversations into segmented app_sessions rows, summarise sealed segments with each agent's own CLI (no cross-engine fallback), and write the summary for the worklog pipeline to pick up. Lifecycle is the task_method column: coding_agent_live → pending_summariser → summarised.

Ingested agents

AgentStoreAdapterapp_name / session_text_source
Claude Code~/.claude/projects/**/<uuid>.jsonljsonl.rs (legacy path)Claude Code / claude_jsonl
Codex~/.codex/sessions/**/rollout-*.jsonljsonl.rs (legacy path)Codex / codex_jsonl
GitHub Copilot CLI~/.copilot/session-state/<uuid>/events.jsonlsources/copilot_cli.rsGitHub Copilot / copilot_events_jsonl
Copilot VS Code chat…/Code/User/**/chatSessions/*.jsonl (op-log: kind 0 snapshot / 1 set / 2 append)sources/copilot_vscode.rsGitHub Copilot / copilot_chat_jsonl
Cursor (sidebar + IDE agent)state.vscdb → cursorDiskKV (composerData: + bubbleId:)sources/cursor.rsCursor Agent / cursor_vscdb
cursor-agent CLI~/.cursor/chats/<ws>/<uuid>/store.db (content-addressed blobs)sources/cursor_cli.rsCursor Agent / cursor_cli_store
Antigravitydetection-only stub (store format unpinned)sources/antigravity.rs— (logs presence, ingests nothing)

New sources plug into the AgentSource enum in sources/mod.rs and are swept by the same indexer tick; everything downstream (segmentation, sealing, summarising, classifying) is agent-blind NormRecords.

  • Indexer (indexer.rs): per tick (INDEXER_POLL_INTERVAL_S, 600 s) seals settled rows, re-parses changed stores, sweeps the source adapters. Backfill is today-only. meridian coding-agent-hook is the Claude SessionEnd entry (seals one session immediately).
  • Session completion: Claude seals via hook; CLI agents (codex / copilot / cursor-agent) seal promptly on Ctrl+C / exit (Copilot's session.shutdown marker force-seals at registration; otherwise a per-tick ps -axo args= probe seals every live row of a CLI whose process is gone) and on /clear · /new (a newer session of the same source supersedes older live rows). IDE chats and crashes fall back to the idle seal (INDEXER_SEAL_IDLE_S, 1 h). All acceleration paths only hasten what the idle backstop would do — a wrong call costs a segment split, never data.
  • Summariser (summariser/): routes each row to its own agent CLI — claude.rs / codex.rs / copilot.rs / cursor_agent.rs (2 attempts, no cross-engine fallback; a failed row is left pending for a later drain); writes session_summary + summary_source, flips task_method to summarised. cursor-agent is auth-probed lazily on first use, and auto-installed only behind the CURSOR_AGENT_AUTO_INSTALL=1 opt-in (cursor_agent_init.rs). CLI: meridian coding-agent-summarise. See summariser/README.md.
  • Self-ingest guard: copilot/cursor-agent persist their own summary runs into stores we ingest; sources::sweep() drops any conversation whose first user prompt carries SUMMARY_PROMPT_MARKER (log: skipping summariser-artifact session). This is the loop cut — do not remove it.
  • Worklog trigger: summarised rows are picked up by the worklog pipeline (src/worklog_pipeline/) via session_summary IS NOT NULL — folded verbatim into the hour's activity summary alongside the distilled OCR sessions, then matched to tasks and drafted.

Source-adapter env overrides: COPILOT_SESSION_STATE_DIR, VSCODE_USER_DIR, CURSOR_STATE_VSCDB, CURSOR_CLI_CHATS_DIR, ANTIGRAVITY_APP_DIR.

Daemon config gotcha: the daemon loads env via dotenvy::dotenv_override(), which walks UP from its launchd WorkingDirectory and stops at the first .env. Both install types converge on the canonical ~/.meridian/.env (the same file the tray writes tracker creds to): the .app DMG (the tray stages the daemon via tray/src-tauri/src/backend_install.rs) sets WorkingDirectory to ~/.meridian and reads it directly; source/dev reads the repo .env. (The old npm bundle install was retired - the DMG is the only packaged distribution now.) Edit ~/.meridian/.env (then meridian restart) to tune daemon env on an installed system.

The pipeline is fully in Rust. The former Python coding_agent_indexer + coding_agent_summariser packages and the entire Python services/ tree (the MLX server, agents, eval harness, runtime packaging) have been removed. Generation runs only through the user's chosen third-party CLI provider (src/llm/), and the session distiller's embedder now runs in-process via candle (src/embedder/, src/worklog_pipeline/distiller/). There is no Python and no on-device generative model anymore; a failing/rate-limited provider leaves work pending for the next cycle.

DB write invariants (enforced in the Rust path)

  • ticket_links and session_dimensions writes must be idempotent. Both tables have UNIQUE / composite-PK constraints with explicit ON CONFLICT … DO UPDATE policies. New writers must use the same UPSERT pattern. Never DELETE then INSERT.
  • Coding-agent segment idempotency: the (claude_session_uuid, segment_started_at) unique index is the key (migration 027; day_utc was dropped in 028). The UPSERT refreshes a LIVE row but carries WHERE sealed_at IS NULL, so a SEALED row is immutable — the summariser only ever reads sealed rows.

Quick command reference

# coding-agent ingest — runs inside the daemon; these are the one-shot CLIs
echo '{"transcript_path":"~/.claude/projects/.../<uuid>.jsonl"}' | meridian coding-agent-hook  # SessionEnd: seal one session
meridian coding-agent-summarise [--dry-run] [--day YYYY-MM-DD] [--limit N]                     # summarise the pending queue

# database corruption — diagnose and recover (see "Database corruption" below)
meridian db check    # per-table scan; exit 0 healthy, 1 damaged
meridian db repair   # rebuild into a fresh file; requires the daemon AND tray stopped

Database corruption (src/db/integrity.rs, src/db/repair/)

SQLite b-tree damage is detected and recovered explicitly; it is not something the daemon can shrug off.

  • Detection — quick_check at daemon startup, plus integrity::is_corrupt_error on the ETL error path. On a positive the daemon raises the db.corrupt notice and latches: it stops calling run_etl for the rest of the process's life, because the condition cannot clear without an operator and retrying only re-reads damaged pages. Everything else in the poll loop keeps running.
  • Recovery is never automatic. Two processes write meridian.db (daemon + tray), and the daemon cannot ask the tray to stop, so meridian db repair refuses to run while either is alive. It rebuilds into a fresh file and swaps it in; the damaged original is kept as meridian.db.corrupt-backup-<ts> and never deleted.
  • Repair-in-place is impossible — on a corrupt tree both REINDEX and DROP TABLE themselves raise SQLITE_CORRUPT. Salvage into a new file is the only primitive that works.
  • Never test table health with count(*). It is answered from an index and reports a corrupt table as fine; even count(*) … NOT INDEXED misses overflow pages. Only a full column read is authoritative — integrity::scan_tables.

Both modules' headers carry the full reasoning and the measured numbers. Test fixtures that produce genuinely corrupt files live in src/db/test_corrupt.rs (cargo test covers them; sqlite::memory: cannot be corrupted).


Git Hygiene

  • Commit message style: type(scope): short description — e.g. fix(etl): detect sleep gaps that span ETL run boundaries
  • commit-msg hook validates conventional commits format — fix message before retrying
  • pre-commit hook runs cargo fmt --all --check and cargo clippy --workspace --all-targets -- -D warnings
  • pre-push hook runs the full suite: cargo fmt + cargo clippy --workspace + UI build + UI tests + security audit (claude CLI) + cargo test --workspace
  • Never skip hooks with --no-verify
  • Install hooks after cloning: bash scripts/setup-hooks.sh
  • Never amend a commit that has already been pushed to main

PR target branch — main

  • Every feature/fix PR targets main (gh pr create --base main). main is the development trunk.
  • Pull requests are gated by the required Fast PR gate status check.
  • .github/workflows/pr-fast.yml also supports merge_group events, so it is compatible with GitHub Merge Queue when that repository setting is enabled.
  • Full macOS/Windows workspace validation runs after merge on main; it is deliberately not the PR merge blocker.
  • Merging to main does not publish production. RC and stable releases are explicit promotion actions.

CI/CD source of truth

Read docs/ci-cd.md before changing any workflow, release script, branch policy, cache key, updater channel, or product-smoke path. It is the canonical description of the current pipeline.

Load-bearing invariants:

  • main is the only development trunk; pre-main and staging release branches are retired.
  • PRs get fast, path-routed checks and aggregate into the required Fast PR gate.
  • exhaustive macOS/Windows validation is post-merge.
  • every successful main CI run emits a traceable candidate-<sha> metadata artifact; RC creation must name that exact current-main candidate SHA.
  • RC promotion builds/signs/notarizes/packages the product exactly once.
  • stable promotion reuses the exact proven RC binaries and rewrites only release/updater metadata; stable must never rebuild the product.
  • RC/stable is distribution metadata, not a compile-time binary channel.
  • PRs should consume shared caches rather than create durable per-PR target caches.
  • debug/test CI caches and release-profile caches stay separate.
  • cache-audit.yml is the observability tool for cache usage; cache-prune.yml is housekeeping.

Do not reconstruct retired pre-main, *-staging.*, rolling staging updater, cache-warm, automatic branch-push release, or stable-rebuild architecture from git history or stale comments.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.