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
In this repository4 other files it gives its agents.
- meridian-etlSkill
- meridian-mcpSkill
- meridian-uiSkill
- releaseSkill
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
- Distinctive: line 9
Do what has been asked; nothing more, nothing less
- Distinctive: line 11
NEVER create files unless absolutely necessary — prefer editing existing files
- Distinctive: line 12
NEVER create documentation files unless explicitly requested
- Distinctive: line 13
ALWAYS read a file before editing it
- Very specific: line 14
NEVER commit secrets, credentials, or .env files
- Distinctive: line 15
Keep files under 500 lines.
- Distinctive: line 17
NEVER run git reset, git push --force, or delete local code — other agents may be working on the codebase in parallel
- Distinctive: line 18
NEVER merge a PR automatically — open/update PRs as needed, but leave the actual merge to a human reviewer
- Very specific: line 20
ALWAYS use a separate branch per feature/fix — branch name format: type/short-description (e.g.
- Very specific: line 28
Every .rs, .ts, and .tsx file must start with this comment as its very first line:
- Distinctive: line 268
No network, no auth, no HTTP server, local-only SQLite
- Very specific: line 278
Read cursor (etl_cursor, last processed frame_id)
- Very specific: line 280
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, …
- Very specific: line 282
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 …
- Distinctive: line 315
When the repowise MCP server is available, use it as part of every code change, not just when convenient:
- Very specific: line 326
Read docs/testing.md first.
- Very specific: line 352
Avoid unwrap() outside tests.
- Very specific: line 377
Add a new numbered file in src/migrations/ — never modify an existing migration
- Very specific: line 574
Read src/db/meridian.rs or src/db/screenpipe.rs
- Very specific: line 575
Follow the sqlx::query_as + .context("description") pattern
- Very specific: line 581
Read src/etl/extractor.rs and src/db/screenpipe.rs
- Very specific: line 582
Add the screenpipe read query in screenpipe.rs
- Very specific: line 584
Update build_active_session and merge_into_active in runner.rs
- Very specific: line 585
Add a migration if the signal needs its own column.
- Very specific: line 586
Add an integration test in tests/integration_etl.rs
- Very specific: line 595
Follow Coding Conventions → "Porting a dashboard route to Rust" instead — the same playbook applies to a brand-new reader, not just a …
- Very specific: line 609
Read docs/notifications.md first — it is the integration guide for the notification service (outbox → deliver → respond → consume …
- Very specific: line 626
Read packages/meridian-mcp/dist/index.js to understand existing tool structure
- Very specific: line 628
Run npm run build in packages/meridian-mcp/ and verify dist/index.js is updated
- Very specific: line 636
Update roadmap if upcoming plans changed — status is in-progress | planned | considering.
- Very specific: line 637
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.
- Very specific: line 645
After a stable release is published, use GitHub Actions workflow .github/workflows/minimum-version.yml:
- Distinctive: line 656
Only the DMG/Tauri updater path uses this policy.
- Very specific: line 750
Commit message style: type(scope): short description — e.g.
- Very specific: line 754
Never skip hooks with --no-verify
- Distinctive: line 756
Never amend a commit that has already been pushed to main
- Very specific: line 768
Read docs/ci-cd.md before changing any workflow, release script, branch policy, cache key, updater channel, or product-smoke path.
- Very specific: line 775
every successful main CI run emits a traceable candidate-<sha> metadata artifact.
- Very specific: line 783
Do not reconstruct retired pre-main, *-staging.*, rolling staging updater, cache-warm, automatic branch-push release, or stable-rebuild …
≈ “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.
Files
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.dbconnection 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
.envfiles - 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 tomain. All features, fixes, and other changes targetmain, which is the development trunk. Merging tomaindoes 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.shnow asserts that rather than printing a reminder about it — afterup -dit 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 — a200fails 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-testexercises the status classifier offline;--verify-onlyruns 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 thoughtfulSECURITY: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 productivitySQL migration files use the SQL comment form:
-- ambient dev tool that watches what you do and updates your PM tickets automatically, boosting developer productivityThe 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 scriptDashboard → 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/apiroutes. DB-backed reads live inmeridian-coreas 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 Tauriinvoke/events throughui/lib/bridge.ts(load/mutate→invoke;subscribe→ the event bus — the browser/apifetch +EventSourcefallbacks 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-tailtailer); the tray poll loop is HTTP-free (directmeridian-corereads). Response types live inui/lib/api-types.ts(moved out of the deleted routes). Asset layout:frontendDist→../../ui/out; the build copies the tray popover intoout/popover/and the main window loadspopover/index.html; dashboard/setup windows loadWebviewUrl::App("today"/"setup")→out/<route>/index.html(trailingSlash: true). The popover works in BOTH profiles:tauri.conf.json'sbeforeDevCommandrunsnode scripts/sync-popover.mjs dev, which copiestray/src/intoui/public/popover/fornext devto serve, and the build does the same intoout/popover/. (This used to be a documented "404s undertauri 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!bundlesui/out); the standalone-Node-server release machinery (thecom.meridiona.uiplist,ui-start.sh, theui.tar.gzpacking, the pinned Node runtime + better-sqlite3 ABI dance) was retired, andbackend_install.rsboots out any leftovercom.meridiona.uiagent on update. The tray callsmeridian::observability::init("meridian-tray")unconditionally in every build — the old dev-onlyotelfeature was removed, because the tray is the process the user actually clicks and it was otherwise dark in release. Rationale + full scope: ObsidianDecisions/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 fmtAlways pass
--workspace.members = [".", "meridian-core", "meridian-oauth", "tray/src-tauri"]makes the repo root itself a package, so a barecargo test/cargo clippyruns 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 reddb_cryptotests for days with every gate green; CI and the pre-push hook now pass--workspacefor 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 buildMCP server (packages/meridian-mcp/)
cd packages/meridian-mcp
npm install
npm run build # compiles TypeScript → dist/index.jsTauri 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 testThe 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
| Variable | Default | Purpose |
MERIDIAN_DB | ~/.meridian/meridian.db | Path 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_SECS | 60 | ETL poll cadence in seconds |
RUST_LOG | meridian=info | Tracing filter |
SQLX_OFFLINE | true (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_AUTH | DEPRECATED — ignored everywhere | OO 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_MB | 10 | Size 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_REPO | BAAI/bge-small-en-v1.5 | Override the HuggingFace repo the embedder weights are fetched from. |
DISTILLER_SEM_DEDUP_THR | 0.86 | Cosine threshold for the distiller's semantic dedup (src/worklog_pipeline/distiller/). |
MERIDIAN_CAPTURE_RETENTION_DAYS | 30 | Age 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_runsremoves partial sessions left by a previous crash, then runs the first ETL pass immediately before entering the poll loop - Poll loop:
tokio::select!overSIGINT/SIGTERMand a sleep timer; on each tick callsrun_etl() - Graceful shutdown closes both pools
ETL pipeline (src/etl/runner.rs)
run_etl() is the single entry point called every poll interval:
- Read cursor (
etl_cursor, last processedframe_id) - Insert an ETL run row with
status = 'running' - Cross-run gap check: if
active_sessionexists from a previous run and the first new frame is >300 s later, classify and record the gap, then close the stale session - Process frames in batches of 500 (
BATCH_SIZE), maintaining a block state machine keyed onapp_name - Intra-batch gap check: before every frame, if the inter-frame gap exceeds
GAP_THRESHOLD_SECS(300 s), close the current block at its realended_at, record the gap, then start fresh - App-switch close (
close_block): whenapp_namechanges, close the old block intoapp_sessions; apply Option C (ui_event refinesended_at) and Option D (single-frame sessions usenext_frame_ts) - Active session upsert (
upsert_open_block): the still-open block at end of all batches goes intoactive_session(single-row table,id = 1) - Advance cursor, mark ETL run
success(orfailedwith 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)
| Table | Role |
app_sessions | Completed sessions — append-only, never updated after insert |
active_session | Single-row in-progress block, upserted every poll |
etl_runs | Audit log — one row per run_etl() call |
etl_cursor | Single-row cursor tracking last_frame_id |
gaps | Sleep/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
capturefeature): the forkedscreenpipe-screen+screenpipe-a11ycrates produce a11y-tree/OCR frames + input events, whichmeridian_core::capturewrites intocapture_frames/capture_ui_eventsinmeridian.db. The daemon ETL reads those tables (viasrc/db/screenpipe.rs, name unchanged for now) from the meridian pool — there is no screenpipe DB/process/pool anymore. Implication: a build with thecapturefeature OFF has no data source (the daemon produces no sessions); the shipping DMG must enable it. Audio is dropped (get_audio_snippetsstubbed empty) and gaps all classifysystem_sleep(no in-process idle detection yet —capture_triggeris NULL); both are accepted v1 degradations with idle-detection/audio as future slices. TheSCREENPIPE_DBenv var +Config::screenpipe_dbfield have been removed (the daemon never reads a screenpipe DB anymore).Column contract:
capture_framesmirrors screenpipe'sframesread-subset (app_name/window_name/browser_url/timestamp/capture_trigger+full_text(OCR)/accessibility_text(a11y)/text_source, resolved byCOALESCE(full_text, accessibility_text));capture_ui_eventsmirrors theui_eventsread-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:
- Orient —
get_overview(new area) orget_contexton the files you expect to touch. - Find the blast radius —
get_symbolfor callers/callees of anything you change; read the*_basisfield before concluding "nothing calls this". - Check risk —
get_change_risk/get_riskon each file before modifying it;get_whywhen the code looks odd, to learn the decision behind it before undoing it. - Verify freshness — every response carries
_meta.indexed_commit. Compare it withgit 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 inapp_sessions - An app switch closes the old block into
app_sessionswith correctframe_countandduration_s duration_snever includes gap time — the pre-gap block closes at the last real frame timestamp- Option C applies only when the
ui_eventtimestamp 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_runsdeletes partial sessions and marks the runabortedidle_frame_countreflects screenpipecapture_trigger = 'idle'frames only
Product decisions
Read docs/vision.md first.
Coding Conventions
Rust
- Error handling:
anyhow::Resultthroughout; 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 warningsenforced in.cargo/config.tomland CI) - Argument limit: clippy's 7-argument limit applies; group related params into a struct (see
BlockBoundsinrunner.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).
- Place it by data source. A DB-backed read → a new module under
meridian-core/src/readers/, added toreaders/mod.rsand re-exported flat fromlib.rs(pub use readers::<name>;) so the public path staysmeridian_core::<name>(the daemon re-exports it if it needs it too). Reusemeridian-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 tomeridian) → a module undertray/src-tauri/src/commands/(grouped by domain), declared + glob-re-exported incommands.rs; keepmeridian-coreDB-only. - 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. aBTreeMapsorts keys vs the route's insertion order — fine when consumers read by key). - 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 inlib.rs'sinvoke_handler!. Every new window label must be added tocapabilities/default.jsonor itsinvokes are silently denied. - Document it (required). Module
//!header with: one-line purpose + which route it ports, a# Who calls this(the command + the frontend consumer), and a# Relatedsection linking sibling modules / dependent fns via intra-doc links ([`crate::tasks`]). Everypubfn/struct gets a///covering purpose, key params, return, and any non-obvious behaviour carried from the source. - 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; atracing::info!(…)summary on serve;tracing::warn!(error = %e, …)on the command's error path. All of it exports to OpenObserve under the trayotelfeature / the daemon'sobservability::init. - 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/apifetch/EventSourcefallbacks were removed at cutover);apiPathis vestigial (documents the former route). Response types go inui/lib/api-types.ts, never a route file. A live stream also needs an emitter intray/src-tauri/src/poll/live.rs(or the log tailer) and the event covered by the window'score:eventpermission. - Test it. Pure mappers/parsers →
#[cfg(test)]unit tests in-module (seehygiene.rs). DB readers → an in-memory seeded test inmeridian-core/tests/readers.rs(single-connection:memory:pool, hand-computed rows; place date-bounded rows relative tolocal_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 overbetter-sqlite3after native-module ABI mismatches across Node versions/platforms caused real distribution pain (seepackages/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
anytypes 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'sWKUIDelegate, and nothing in the stack installs one (wry,tauri-runtime-wry,tauri,tauri-utilswere each grepped forConfirmPanel|AlertPanel|WKUIDelegate— all empty), soconfirm()always returnsfalseandalert()is a no-op. The damage is silence: a falsyconfirm()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 thedb.corruptRepair Database button shipped dead in 1.83.0 — recovery had to be driven by hand from a terminal. Use@/components/ConfirmDialog(ConfirmDialogfor consent,AlertDialogfor failures).__tests__/no-native-dialogs.test.tsfails the build if they come back.tauri-plugin-dialogwould also work but is not a dependency, and adding one costs a capability grant for a box the webview can render itself. - Spawning the
meridianbinary: ALWAYS usecrate::install::meridian_bin()(Rust), never a bare"meridian"and never a hand-rolled candidate list. This moved:@/lib/meridian-binand itsselectMeridianBinary(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'snode, so the#!/usr/bin/env nodewrapper at~/.local/bin/meridiandies withenv: 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 baremeridianon$PATH.MERIDIAN_BINoverrides everything (logged; ignored with a warning if it points at nothing). On Windows the staged name ismeridian.exe— the candidate list must match exactly or every shell-out silently falls through to the$PATHlast 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 bycargo 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.
- The
EnvFilterdecides what is captured at all — before the spool, before severity, before redaction.EnvFiltermatches directives against targets by string prefix, so themeridiandirective coversmeridian_core::*,meridian_tray_lib::*andmeridian_oauth::*for free — but nothing else. Any crate whose target does not start withmeridianis discarded entirely unless named inobservability::filter. That is whyCAPTURE_TARGETSexists (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 itswarn!/error!bodies first: third-party crates were written to print to a terminal and may interpolate content that must never egress. The attribute allowlist is keyed on the names you actually type.
tracing::warn!(error = %e, …)emits the attribute keyerror, not the semconverror.message. Anything not onredact::SAFE_STRING_KEYSis 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_errorJSON pointer aspath, reasoned correctly in a comment that a field path is safe to ship — and lost it anyway, becausepathis deliberately denied as a filesystem path. It ships now asjson_pointer. Wideningpathwould have traded a real protection for a diagnostic; renaming the field was the cheaper half. Likewise a full binary path (bin) stays denied whilebin_source— a closed set of literals frominstall::bin_source— ships in its place.- 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 ameridiansubprocess'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_bodywalks every workspace source tree and fails the build on a new interpolated WARN+/ERROR body, withINTERPOLABLEas 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 logsrenders them; export bundles carry the raw spool) and dropped on the ship leg — that is the two-tier design working, and it is whystderr_tailcosts the engineer debugging their own machine nothing. Deleting the value instead is #867's mistake wearing #872's clothes. A
u64field is not shipped as a number.tracing-opentelemetry0.28'sVisitimpl has norecord_u64, sotracing::field::Visit's default applies and forwards torecord_debug— which emits a StringValue. The field then misses the allowlist (nobody liststimeout_sas a string key) and is dropped, while the identical field written asf64ori64ships fine. In production this meant everycli_exec.rstimeout shippedtimeout_s = nullwhile the distiller'sas_secs_f64()shipped210.0on 3,329 records — same name, same severity, kept or dropped purely by Rust type.redact::is_bare_numbernow rescues these: aStringValuewhose ENTIRE value parses as a finite number is kept. That is a type rescue, not a key exemption —IntValue/DoubleValuewere 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 realrecord_debugoutput (?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,Basicauth, full fidelity (no redaction). Unchanged. - Canonical (packaged DMG) → Meridian's central OpenObserve via the
ingest gateway (
ops/central-observability/), gated on theerror_reporting_enabledsetting (opt-out, default true),Bearerauth with a release-baked write-only token, and redacted + error-only (telemetry_spool::redact). The endpoint and token are release-injectedoption_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. Seesrc/llm/resolver.rs'sllm.callspan tree (request → infer → response) andsrc/worklog_pipeline/distiller'sdistil.runspan 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 awarning/errorwith.context/extraat 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
- Read
src/db/meridian.rsorsrc/db/screenpipe.rs - Follow the
sqlx::query_as+.context("description")pattern - Export from
src/db/mod.rsif needed - Run
cargo clippy --workspace --all-targets -- -D warnings && cargo test --workspace
Add a new ETL extraction signal
- Read
src/etl/extractor.rsandsrc/db/screenpipe.rs - Add the screenpipe read query in
screenpipe.rs - Extend
BlockContextinextractor.rsand wire it inextract_block_context() - Update
build_active_sessionandmerge_into_activeinrunner.rs - Add a migration if the signal needs its own column; otherwise store as JSON in
signals - 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:
- Plain: one
notifications::enqueue(...)call with a scopeddedup_key(src/notifications.rs). Never gate on settings in the producer — policy lives inmeridian-coreat drain time. - 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 insrc/notification_responses.rs(handlers must be idempotent). - Interactive toasts only work in packaged builds (
UNUserNotificationCenterneeds a.appbundle) — test per the recipe indocs/notifications.md.
Add a new MCP tool
- Read
packages/meridian-mcp/dist/index.jsto understand existing tool structure - Edit the TypeScript source in
packages/meridian-mcp/src/ - Run
npm run buildinpackages/meridian-mcp/and verifydist/index.jsis 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).
- Edit
tray/src-tauri/resources/whats-new.json(compiled into the tray binary viainclude_str!, not Tauri resource-bundling — a rebuild always picks up the change). - Add a new object to the front of
releases(newest-first):version,date, anditems— 1-3, each a shorttitle(≤44 chars) plus abodyof 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_shortinwhats_new.rsfails 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. - Update
roadmapif upcoming plans changed —statusisin-progress|planned|considering. - 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. cargo test -p meridian-tray(fromtray/src-tauri/) coverswhats_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.Zarms the floor after verifying thatvX.Y.Zis a published stable release and is not newer than latest.action=clearremoves 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_versionremains 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
| Agent | Store | Adapter | app_name / session_text_source |
| Claude Code | ~/.claude/projects/**/<uuid>.jsonl | jsonl.rs (legacy path) | Claude Code / claude_jsonl |
| Codex | ~/.codex/sessions/**/rollout-*.jsonl | jsonl.rs (legacy path) | Codex / codex_jsonl |
| GitHub Copilot CLI | ~/.copilot/session-state/<uuid>/events.jsonl | sources/copilot_cli.rs | GitHub Copilot / copilot_events_jsonl |
| Copilot VS Code chat | …/Code/User/**/chatSessions/*.jsonl (op-log: kind 0 snapshot / 1 set / 2 append) | sources/copilot_vscode.rs | GitHub Copilot / copilot_chat_jsonl |
| Cursor (sidebar + IDE agent) | state.vscdb → cursorDiskKV (composerData: + bubbleId:) | sources/cursor.rs | Cursor Agent / cursor_vscdb |
| cursor-agent CLI | ~/.cursor/chats/<ws>/<uuid>/store.db (content-addressed blobs) | sources/cursor_cli.rs | Cursor Agent / cursor_cli_store |
| Antigravity | detection-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-hookis 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.shutdownmarker force-seals at registration; otherwise a per-tickps -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); writessession_summary+summary_source, flipstask_methodtosummarised. cursor-agent is auth-probed lazily on first use, and auto-installed only behind theCURSOR_AGENT_AUTO_INSTALL=1opt-in (cursor_agent_init.rs). CLI:meridian coding-agent-summarise. Seesummariser/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 carriesSUMMARY_PROMPT_MARKER(log:skipping summariser-artifact session). This is the loop cut — do not remove it. - Worklog trigger:
summarisedrows are picked up by the worklog pipeline (src/worklog_pipeline/) viasession_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 launchdWorkingDirectoryand stops at the first.env. Both install types converge on the canonical~/.meridian/.env(the same file the tray writes tracker creds to): the.appDMG (the tray stages the daemon viatray/src-tauri/src/backend_install.rs) setsWorkingDirectoryto~/.meridianand 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(thenmeridian 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_linksandsession_dimensionswrites must be idempotent. Both tables have UNIQUE / composite-PK constraints with explicitON CONFLICT … DO UPDATEpolicies. New writers must use the same UPSERT pattern. NeverDELETEthenINSERT.- Coding-agent segment idempotency: the
(claude_session_uuid, segment_started_at)unique index is the key (migration 027;day_utcwas dropped in 028). The UPSERT refreshes a LIVE row but carriesWHERE 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 stoppedDatabase 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_checkat daemon startup, plusintegrity::is_corrupt_erroron the ETL error path. On a positive the daemon raises thedb.corruptnotice and latches: it stops callingrun_etlfor 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, someridian db repairrefuses to run while either is alive. It rebuilds into a fresh file and swaps it in; the damaged original is kept asmeridian.db.corrupt-backup-<ts>and never deleted. - Repair-in-place is impossible — on a corrupt tree both
REINDEXandDROP TABLEthemselves raiseSQLITE_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; evencount(*) … NOT INDEXEDmisses 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-msghook validates conventional commits format — fix message before retryingpre-commithook runscargo fmt --all --checkandcargo clippy --workspace --all-targets -- -D warningspre-pushhook 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).mainis the development trunk. - Pull requests are gated by the required
Fast PR gatestatus check. .github/workflows/pr-fast.ymlalso supportsmerge_groupevents, 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
maindoes 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:
mainis the only development trunk;pre-mainand 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
mainCI run emits a traceablecandidate-<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.ymlis the observability tool for cache usage;cache-prune.ymlis 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.
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
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.

