ClawMetry Documentation

repository·main·Indexed 18 days ago

https://github.com/vivekchand/clawmetry

A real-time observability platform for AI agent runtimes. ClawMetry provides a centralized dashboard to monitor token usage, costs, tool calls, and security posture across runtimes including OpenClaw, Claude Code, Cursor, and NVIDIA NeMo Agent Toolkit. It supports installation as an OpenClaw plugin, a standalone application, or a self-hosted server with E2E encryption and audit export capabilities.

Tokens
87.7K
Snippets
194
Records
390
Agent score
63%

What's inside ClawMetry

  1. Overview of the Accuracy Harness

    main

    The Accuracy Harness is a testing and validation suite designed to ensure the reliability of ClawMetry's observability features. It validates the end-to-end flow of data from agent runtimes through the dashboard and alerting systems.

    It is structured into specialized sub-harnesses:

    • Tokens: Validates token usage metrics (input, output, cache) across various time windows.
    • Approvals: Verifies the lifecycle of tool-call approvals (pending $\rightarrow$ approved/denied).
    • Alerts: Tests the creation of alert rules, threshold triggers, and webhook dispatching.

    The harness is designed to be idempotent, using unique UUID tags (e.g., ACCURACY_AUDIT_<run_id>) to prevent collisions with real production data or previous test runs.

  2. Overview of ClawMetry Features

    main

    ClawMetry provides real-time observability for AI agent runtimes through several key dashboard views:

    • Flow: Live animated diagram of messages flowing through channels, brain, and tools.
    • Overview: Health checks, activity heatmaps, session counts, and model info.
    • Usage/Tokens: Token and cost tracking with daily/weekly/monthly breakdowns.
    • Sessions: List of active agent sessions including model, tokens, and last activity.
    • Logs: Color-coded real-time log streaming.
    • Memory: Workspace file browser for files like SOUL.md, MEMORY.md, and AGENTS.md.
    • Transcripts: Chat-bubble UI for session history.
    • Alerts: Budget caps, error-rate triggers, and agent-offline detection with webhooks to Slack, Discord, PagerDuty, Telegram, and Email.
    • Approvals: Manual sign-off for risky tool calls (e.g., deletes, sudo, network calls).
  3. Overview of ClawMetry Adapters

    main

    ClawMetry uses adapters to translate data from various agent runtimes into a unified Session / Event schema. This allows the ClawMetry dashboard to provide consistent observability (brain feed, transcripts, cost analytics) regardless of the underlying framework.

    Supported Adapters

    AdapterSource frameworkModeModule
    OpenClawAdapterOpenClawpull (filesystem)openclaw.py
    HermesAdapterHermes Agentpull (SQLite)hermes.py
    NeMoAdapterNVIDIA NeMo Agent Toolkitpush (callback)nemo.py
    • Pull Mode: The adapter scans persisted files or databases (e.g., filesystem or SQLite).
    • Push Mode: The adapter receives events via a callback bus (e.g., NeMo).
  4. Overview of the Accuracy Harness

    main

    The Accuracy Harness is a suite of synthetic ground-truth verifiers designed to ensure ClawMetry dashboard features (like Tokens, Approvals, and Alerts) are reporting data correctly. It prevents silent regressions caused by bugs in data pipelines, timezone bucketing, or cache TTLs by driving known synthetic traffic and asserting that the dashboard metrics match the expected ground truth.

    The Harness Lifecycle

    Every sub-harness follows a consistent six-step pattern:

    1. baseline: Scrape feature endpoints to snapshot current totals.
    2. ground: Drive $N$ synthetic events with known properties (the source of truth).
    3. flush: Poll the sync daemon until the $N$ events have landed.
    4. probe: Re-scrape feature endpoints across all exposed time windows (e.g., 1h, 24h, 7d, 30d).
    5. assert: Verify that (after - before) == ground within a defined tolerance.
    6. report: Output a PASS table or file a GitHub issue if drift is detected.
  5. Overview of ClawMetry Internationalization (i18n) Strategy

    main

    ClawMetry implements a fully automated, zero-build internationalization system designed to support 30+ languages without requiring an npm build step or human translators.

    Core Principles:

    • English as Source of Truth: All new or changed strings are written in English. A CI bot (Claude) automatically translates these into all supported languages during the PR process.
    • No Build Step: To adhere to the project's constraint of having no build step and no npm, the system uses a flat JSON catalog (locales/<lang>.json) and vanilla JavaScript. It avoids heavy frameworks like react-intl or Flask-Babel.
    • Hybrid Rendering:
      • The Landing Site uses locale subpaths (e.g., clawmetry.com/ja/) to ensure per-language SEO and crawlability.
      • The Dashboard uses client-side translation and persisted user preferences, as it is behind a tool and not indexed by search engines.
    • Fallback Mechanism: The system is designed to never crash on a missing translation; it always falls back to English.
    • Localization Scope: The system localizes the interface (chrome, buttons, labels). It does not translate user data (agent transcripts, logs, model outputs) or currency values (costs remain in USD, though number formatting is localized).
  6. Overview of the Harness Observability Audit

    main
    The Harness Observability Audit is a system designed to keep ClawMetry's coverage current as the agent runtimes it monitors evolve. It performs a daily synchronization of upstream sources and uses Claude to compare the observable surface of a harness (sessions, events, tool calls, cost/tokens, cache, telemetry, new features) against what the ClawMetry adapter currently captures. If gaps are found, the system automatically files GitHub issues to ensure new features are observed rather than drifting silently.
  7. What is the MOAT (Mandate and Core Principles)

    main

    The MOAT (Minimum Operational Architecture Threshold) is a set of three non-negotiable architectural mandates for ClawMetry. If any of these principles are violated, the MOAT is considered broken:

    1. DuckDB-First UI: Every UI element must query the local DuckDB. Dashboard panels, charts, and feeds must use _try_local_store_* methods to land on the user's local DuckDB via the daemon-proxy at localhost:4099/local_query/*. Using JSONL walkers, in-memory rings, or direct psutil historical samples is considered a bug.
    2. DuckDB-First Events: Every event must write to DuckDB. OpenClaw v3 events are normalized in clawmetry/sync.py::_parse_v3_event. Synthetic test rows must use real v3 namespaced types (e.g., model.completed, prompt.submitted, session.started) to ensure production compatibility.
    3. Cloud as a Display Layer: The Cloud component is strictly a display layer for E2E-encrypted aggregates. Cloud SQL stores metadata (user_id, plan_tier, last_seen) and opaque aggregates using AES-256-GCM. The cloud layer cannot decrypt event payloads or the pending_queries cache.
  8. Understand the Sync Daemon data streams

    main

    The sync daemon manages the transmission of agent data to the ClawMetry Cloud. Most streams are protected with End-to-End (E2E) encryption using AES-256-GCM.

    StreamCadenceEndpointEncryptedNotes
    Heartbeatevery 15 s/ingest/heartbeatnoalways sent regardless of plan; carries sync_allowed answer back
    Events (Brain)batches of 200/ingest/eventsE2E (AES-256-GCM)gated by sync_allowed
    Sessionson-change/ingest/sessionsE2Emetadata only; transcript content is in events
    Logs (real-time)every 2 s, ≤50 lines/ingest/streamE2Egated
    Logs (batch backfill)per cycle, ≤5000 events/ingest/logsE2Egated
    Memory snapshotshourly + on-change/ingest/memoryE2Egated
    System snapshotevery 5–10 min/ingest/system-snapshotE2Ehardware + security posture
    Cronson-change(via events)E2Ecron_state event type
    Autonomy daily roll-upnightly, 1/node/day/ingest/autonomynosmall aggregate
    Claude Code transcriptswhen detected/ingest/events (parsed first)E2Ereads ~/.claude/projects/*/sessions/*.jsonl
  9. Development constraints for ClawMetry observability

    main

    When developing new features or integrations for ClawMetry, adhere to the following architectural constraints to ensure system stability, security, and performance:

    • Data Ingestion: Follow a DuckDB-first approach. The daemon must ingest data into DuckDB, which is then used for snapshots. Never attempt to read ~/.openclaw, JSONL files, or process stats directly. Always use the daemon's own writer handle; do not use a read_only=True re-open to avoid brick-locking.
    • Security & Encryption: Maintain E2E encryption. The cloud component must not compute anything on OpenClaw data. All new tabs must render client-side from the decrypted snapshot via window.__cmSnap. New routes should default to oss-passthrough.
    • Performance: Adhere to a strict cost/perf budget. New diagnostic polls must share a single cadence and a single snapshot fetch. Avoid per-tab pollers or per-interceptor snapshot fetches. Heavy polls should be gated by the active tab, and new snapshot keys must be bounded and stripped of heavy fields to prevent snapshot bloat.
    • Observability Model: ClawMetry is strictly read-only. It must observe but not change scheduling, approvals, or policy. Approval and policy tabs are intended to be views, not controls (unless a relay-backed write path is explicitly implemented via operator.approvals).
    • Token Scoping: Use the operator.read token scope. All diagnostic RPCs (e.g., diagnostics.stability, tasks.list, tools.catalog, skills.status, usage.status, system-presence) must be read-scoped. Do not attempt to access operator.admin or approvals scopes for observation purposes.
    • Verification: Always verify against live data rather than fixtures. Ensure ingest is smoke-tested against live DuckDB and that cloud snapshots are successfully decrypted.
  10. Analyze LLM Context Construction and Composition

    main

    ClawMetry allows you to inspect how the LLM context is assembled before a call. The context is composed of several distinct sections, which are visible in the Context tab:

    • System Prompt: Includes Tooling (~3k tokens), Safety (~120 tokens), Skills headers (~1.5k tokens), Memory guidance, Workspace info, Heartbeats, and Sandbox info.
    • Bootstrap Files: Injected markdown files like SOUL.md (identity), AGENTS.md (workspace config), TOOLS.md (custom tool instructions), USER.md, IDENTITY.md, MEMORY.md, and HEARTBEAT.md.
    • Tool Schemas: JSON definitions for built-in and plugin tools (these consume tokens even if not visible as text).
    • Conversation History: A mix of compacted summaries for older turns and intact recent messages, including tool call/result pairs.

    Use the Context tab to see a breakdown of token usage per component (e.g., ## Tooling [========--------] 3.0K tokens) to debug why a context window might be filling up.

  11. How the ClawMetry Translation Flywheel works

    main

    ClawMetry uses an automated, delta-only translation workflow to minimize maintenance and cost:

    1. Development: A developer adds or edits an English string in en.json, README.md, or a doc file.
    2. CI Gate: A CI process scans templates for data-i18n or t() calls. It fails the PR if user-facing text is found that is not marked for translation.
    3. Automated Translation: Upon merging to main, a GitHub Action (using Claude) compares en.json against existing <lang>.json files. It translates only the deltas (new or changed keys).
    4. Guardrails:
      • Glossary: Uses locales/_glossary.json to prevent translating product nouns (e.g., "ClawMetry", "OpenClaw").
      • Integrity Checks: Ensures placeholders like {n} or %s and Markdown links survive translation.
      • Orphan Pruning: Automatically removes keys from <lang>.json if they are removed from the English source.
    5. Deployment: The updated locales are picked up in the next release and distributed via PyPI/Cloud.
  12. Understand ClawMetry's Observability Architecture

    main

    ClawMetry provides visibility into the three layers of the OpenClaw architecture to explain not just what an agent did, but why it did it. It observes:

    • Layer 1 (Connectors): Identifies which connector (e.g., Telegram, WhatsApp, Discord) delivered a message and how it was routed to a specific session.
    • Layer 2 (Gateway Controller): Monitors the session lifecycle, including cron execution and memory state management.
    • Layer 3 (Agent Runtime): Tracks LLM calls (model used, token count, cost), tool execution, skill invocation, and sub-agent orchestration.

    This allows you to trace a single response back through its specific LLM calls, the tools it invoked (like exec or read), and the specific channel it originated from.