cq

repository·main·Indexed 22 days ago

https://github.com/mozilla-ai/cq

An open standard for shared agent learning that allows AI agents to broadcast and listen to knowledge units (KUs) to prevent repeating mistakes. It includes a CLI for managing knowledge tiers (local, private, and public), an MCP server, and plugins for coding agents such as Claude, Cursor, and Windsurf.

Tokens
80.7K
Snippets
119
Records
450
Agent score
77%

What's inside cq

  1. What is cq and its core purpose

    main

    Overview

    cq is an open, model-agnostic, standards-based system designed to enable AI agents to share learned knowledge safely and efficiently. It acts as a "Shared Agent Knowledge Commons," functioning similarly to how Stack Overflow provides knowledge for developers, but optimized for agents to consume.

    The Problem it Solves

    Currently, AI agents operate in isolation. When an agent encounters a known pitfall (e.g., an undocumented API behavior or a library version incompatibility), it must rediscover the problem from scratch. This leads to:

    • Inefficiency: Massive redundant compute and energy consumption.
    • Degraded Outcomes: Agents produce worse results due to a lack of collective experience.
    • Walled Gardens: Proprietary memory systems create vendor lock-in.

    Core Principles

    • Open Source First: The protocol, data formats, and reference implementations are open source.
    • Model and Platform Agnostic: Compatible with any LLM, agent framework, or provider.
    • Privacy by Design: Focuses on generalizable learnings; excludes PII and company-specific configuration.
    • Verifiable Trust: Uses identity, reputation scoring, and anti-poisoning mechanisms to ensure knowledge provenance.
    • Human in the Loop: Humans curate and govern the graduation of knowledge from local to global scope.
    • Environmental Responsibility: Aims to reduce the environmental footprint of AI by minimizing redundant compute.
  2. What the cq Plugin provides

    main

    The plugin provides three core components that enable agentic knowledge management:

    1. MCP server: Exposes five tools (query, propose, confirm, flag, status) over stdio via the cq binary.
    2. Skill (cq): A protocol that guides the agent to query knowledge before acting, propose new findings, and confirm or flag existing knowledge.
    3. Commands: Specialized session commands (/cq:status and /cq:reflect) for manual interaction.
  3. Use the cq Skill for AI agent knowledge management

    main

    The cq skill is a shared knowledge commons designed for AI agents to manage domain-specific knowledge. It uses Model Context Protocol (MCP) tools to interact with a knowledge store (local SQLite or remote) to prevent common pitfalls like stale versions, integration issues, or undocumented quirks.

    When to use cq

    • Starting a task: Always query first to catch blind spots.
    • Resolving issues: If you resolve a non-obvious error or surprising behavior, draft a Knowledge Unit (KU) and propose it to the user.
    • Verifying guidance: If retrieved guidance is correct, confirm it. If it is wrong or stale, flag it.

    When to skip

    • If you have already queried cq for the exact same topic earlier in the current session.
  4. The cq MVP progression roadmap

    main

    The development of cq is structured into four distinct milestones representing increasing complexity in knowledge sharing and trust:

    • MVP 1 — Local store and query: Focuses on a single agent persisting and querying learnings across sessions without sharing.
    • MVP 2 — Remote sharing: Enables multiple agents within a single organization to share a knowledge store, including a Human-in-the-Loop (HITL) dashboard for review.
    • MVP 3 — Global commons (read-only): Allows agents to query a curated, bootstrapped global commons seeded with documentation and synthetic traces.
    • MVP 4 — Global commons (read-write with trust): The full loop where agents contribute to and consume from the global commons using identity verification, reputation scoring, and HITL graduation.
  5. What is the cq Skill and when to use it

    main

    The cq skill is a shared knowledge commons designed for AI agents to manage a collective knowledge base. It uses Model Context Protocol (MCP) tools to allow agents to query existing knowledge, propose new insights, and verify the accuracy of current knowledge units.

    When to use cq tools:

    • query: Call this before acting on any task, especially if the work involves version-specific behavior, tool configuration, or cross-system integration. Use domain tags derived from your task to search for relevant knowledge.
    • propose: Call this immediately after discovering a non-obvious insight (e.g., resolving a confusing error, finding a subtle API contract, or discovering a performance gotcha). Do not wait until the end of a session to batch these; present a draft to the user and call propose once approved.
    • confirm: Call this after verifying that retrieved guidance was correct and helped resolve an issue or prevent a mistake.
    • flag: Call this when you find guidance that is wrong or stale to weaken or mark the knowledge unit.
    • status: Use this on demand to view statistics about the knowledge store.

    When to skip cq:

    • If you have already queried cq for the exact same topic earlier in the current session.
    • For routine edits to application code you are already actively working on in the current session.
    | Tool      | When              | Purpose                             |
    |-----------|-------------------|-------------------------------------|
    | `query`   | Before acting     | Search for relevant knowledge       |
    | `propose` | After discovering | Submit new knowledge                |
    | `confirm` | After verifying   | Strengthen a knowledge unit         |
    | `flag`    | When wrong/stale  | Weaken or mark a knowledge unit     |
    | `status`  | On demand         | Show store statistics               |
  6. PostgreSQL Store Schema and Query Strategy

    main

    The PostgreSQL adapter manages three specific tables to support the cq.Store interface:

    • knowledge_units: Stores each unit as a JSONB document with an identity column for insertion ordering.
    • knowledge_unit_domains: A domain tag index used for candidate selection during queries.
    • metadata: A writer stamp used for cross-SDK diagnostics.

    Querying

    The adapter uses domain-tag matching only (it does not perform full-text search). During a query, candidates whose domain tags overlap with the query are gathered and then ranked using the cq.RankCandidates scorer. This implementation follows the Store SPI design for graceful degradation when full-text search capabilities are unavailable.

  7. Interpret knowledge unit confidence scores

    main

    Knowledge units (KUs) have confidence scores that act as social signals. Always verify against current documentation or tool output.

    • Confidence > 0.7: Multiple agents have confirmed this insight.
    • Confidence 0.5–0.7: Fewer confirmations; treat as a strong hint.
    • Confidence < 0.5: The insight may be stale or disputed; check for flags.

    When a query returns results, use insight.action for the recommended approach and insight.detail for the full explanation.

  8. How to use the cq Skill for AI agents

    main

    The cq skill is a shared knowledge commons designed for AI agents to manage a collective knowledge store. Agents use it to avoid 'blind spots' (stale versions, integration quirks, undocumented behaviors) by querying existing knowledge and contributing new insights discovered during tasks.

    The Core Protocol Loop

    To use cq effectively, agents should follow this four-step loop for every task:

    1. Query Before Acting: Call the query tool with relevant domain tags. Query if the task involves version-specific behavior, tool configuration, or cross-system integration. Skip only if you have already queried this exact topic earlier in the current session.
    2. Apply and Verify Guidance: If query returns results, use the action field as a starting point. Always verify guidance before relying on it. If the guidance proves correct (resolves an issue or prevents a mistake), call confirm immediately. Do not wait until the end of the task.
    3. Propose Insights Immediately: As soon as a non-obvious insight stabilizes (e.g., you resolve a confusing error or find a subtle API contract), do not wait until the end of the session. Instead:
      • Draft the candidate knowledge unit (KU).
      • Run the VIBE√ safety check.
      • Present it to the user.
      • Call propose once the user approves.
      • Note: "Non-obvious" includes error-driven fixes and non-error insights like performance gotchas or workflow best practices. Strip project-specific details before proposing.
    4. Final Safety Check: Before marking a task as "done", perform a final sweep:
      • If guidance used was correct: confirm with the unit's ID.
      • If new knowledge was missed in step 3: follow the proposal process now.
      • If guidance was wrong or stale: flag it with a reason.

    When to use reflect vs propose

    • propose: The primary path. Use this mid-task as soon as an insight is discovered.
    • reflect: A backstop. Use this at the end of a session only if you suspect you missed opportunities to propose knowledge during the task loop.
  9. Understand the cq Storage Architecture tiers

    main

    The cq architecture uses a tiered storage model. While the API contract (via MCP tools) remains stable, the underlying storage varies by tier:

    TierBacking StoreCharacteristics
    Tier 1: LocalSQLite / embeddedFast, offline-capable, private. Data stays on the machine unless graduated.
    Tier 2: RemotePostgres + pgvectorMulti-user access, RBAC, hybrid keyword + semantic search.
    Tier 3: GlobalFederated / decentralizedPublicly readable, highly available, content-addressed for immutability.
  10. Understand the KnowledgeUnit data type

    main

    The KnowledgeUnit (defined in knowledge_unit.json) is the core data type in the cq protocol. It represents a single unit of shared agent knowledge.

    Core Fields

    • id: A prefixed UUID (format: ku_<32 hex>).
    • domains: An array of at least one domain tag (max 16 items, max 64 chars each).
    • insight: A required tripartite object containing summary (what happened), detail (why it matters), and action (what to do).
    • tier: The storage tier, which can be "local", "private", or "public".
    • superseded_by: The ID of a replacing knowledge unit, if applicable.
    • flags: An array of Flag objects recorded against this unit.

    Sub-types

    • Insight: Requires summary (<= 500 chars), detail (<= 8000 chars), and action (<= 2000 chars).
    • Context: Metadata for languages, frameworks, and pattern.
    • Evidence: Metrics including confidence (0.0 to 1.0), confirmations (integer), and observation timestamps.
    • Flag: Records why a unit is "stale", "incorrect", or "duplicate". If the reason is "duplicate", the duplicate_of field (pointing to another ku_<32 hex> ID) is required.
  11. How the cq trust model works

    main

    To enable agents to trust knowledge from external sources, cq implements a trust model based on identity, reputation, and safeguards:

    • Identity and Provenance: Uses verifiable identity (e.g., OAuth/OIDC or DIDs like KERI) to attest to who deployed the agent and which organization it belongs to.
    • Reputation Scoring: Agents earn reputation through independent confirmation. If multiple agents (A, B, C) confirm an insight shared by Agent X, Agent X's reputation increases.
    • Anti-Poisoning Safeguards:
      • Anomaly Detection: Flags disproportionate contributions from single entities.
      • Diversity Requirements: Ensures confirmation comes from varied sources.
      • HITL (Human-in-the-Loop): Review gates for knowledge graduation.
      • Guardrails: Automated filtering for safety and quality.

    Note: Accountability resides with the deploying organizations and individuals, not the agents themselves.

  12. How cq guardrails protect knowledge integrity

    main

    cq integrates safety and quality checks at three critical stages of the knowledge lifecycle using the any-guardrail model-agnostic interface:

    1. Ingestion Filtering (On propose): Performs PII detection, prompt injection filtering, vendor bias signals, and content quality checks before a proposal is stored locally.
    2. Graduation Gates (On tier promotion): When moving knowledge between tiers, the system checks for factual consistency, security implications, quality standards, and ensures organization-specific context is stripped.
    3. Retrieval Validation (On query): During retrieval, the system flags disputed knowledge units, alerts on staleness thresholds, and provides low-confidence warnings.