Skip to main content

KLYD

Decision memory for coding agents.

Coding agents can generate code quickly but often lose the architectural decisions that shaped a repository.

Klyd records, retrieves, and reintroduces those decisions so future agent sessions can work with the project's existing reasoning instead of repeatedly rediscovering it.

PyPI: klyd · GitHub · License: MIT


The problem

A coding agent may know the current files but not the reasons behind them:

  • why a database choice was made;
  • why a workaround exists;
  • why an API must remain stable;
  • why a previous approach was rejected;
  • which architectural constraints are non-negotiable.

Without that context, agents can produce locally plausible changes that violate the system's existing design. Over multiple sessions, a codebase accumulates conflicting architectural patterns, turning into a patchwork of fragmented decisions.


The workflow

Klyd operates invisibly through standard Git hooks without requiring a background daemon or wrapping agent subprocesses with intrusive proxies:

graph TD
    A[Developer commits] --> B["post-commit hook
    kl extract-commit"]
    B --> C["LLM Extraction
    classify: NEW / REINFORCE / CONTRADICT"]
    C -->|NEW or REINFORCE| D[("SQLite Store
    .klyd/memory.db")]
    C -->|CONTRADICT| E["Flagged for Review
    kl review"]
    E -->|Resolve: Accept / Merge / Edit| D

    F[Agent stages changes] --> G["pre-commit hook
    kl prepare-injection"]
    G --> H["Single-pass query:
    glob match + cosine similarity"]
    H --> D
    H --> I[".klyd/injection.txt
    formatted context"]
    I --> J["kl run aider
    context injected"]

All state remains strictly local to .klyd/ inside the target git repository.


Example

A repository previously decided:

Authentication must remain inside the existing WebCrypto-based boundary. External token libraries must not be introduced.

Months later, an autonomous agent tasked with fixing an auth endpoint proposes adding a third-party token parser.

Before the change is committed, Klyd inspects the staged files, retrieves the earlier decision and its rationale from .klyd/memory.db, and injects the constraint directly into the agent's context window. The agent refactors the code within the established WebCrypto pattern instead of introducing an incompatible dependency.

(Note: This is an illustrative example of an architectural boundary constraint captured from commit history and reintroduced to guide subsequent agent turns).


Technical design

Klyd currently uses:

  • SQLite for persistent decision storage: Embedded relational database maintaining schema versions, embeddings, and decision records.
  • Git hooks for repository lifecycle integration: post-commit extracts decisions asynchronously from diffs; pre-commit prepares context from staged changes.
  • Semantic similarity for retrieval: Optional vector embeddings paired with lexical glob matching for relevant context ranking.
  • Recursive decision ancestry: Tracking parent-child relationships across decision versions using recursive Common Table Expressions.
  • Conflict resolution between related decisions: Interactive terminal UI (kl review) supporting accept, reject, manual edit, and LLM-assisted decision merging.
  • Multiple model-provider integrations: Bring-Your-Own-Key (BYOK) support for Anthropic, OpenAI, OpenRouter, Google Gemini, and Groq.
  • CLI-oriented workflow for coding-agent environments: Direct compatibility flags for tools like aider and opencode.

Design choice: SQLite

SQLite keeps the decision history:

  • local to the repository or workspace;
  • inspectable with standard SQL tools or CLI commands;
  • easy to back up by copying .klyd/;
  • usable without requiring any cloud service, daemon, or database server;
  • available to low-latency command-line workflows and shell scripts.

The trade-off is that Klyd prioritizes local developer infrastructure and explicit Git workflow integration over centralized multi-user cloud coordination.


Engineering details

In-database custom multi-glob matching

When staged files are evaluated (e.g. auth/login.py), Klyd must match them against comma-separated glob patterns (e.g. auth/*, security/*) stored in the decisions table. Standard SQL lacks native glob-list evaluation, and loading all rows into Python memory for full-table scanning creates unnecessary overhead.

Klyd solves this by registering a custom Python callback function (match_files) directly into the SQLite C-runtime using sqlite3.Connection.create_function:

def _match_any_file(file_patterns: str, file_list_str: str) -> int:
    patterns = [p.strip() for p in file_patterns.split(",")]
    files = file_list_str.split("|")
    for f in files:
        for p in patterns:
            if fnmatch.fnmatch(f, p):
                return 1
    return 0

conn.create_function("match_files", 2, _match_any_file)

This allows the SQLite query planner to filter rows atomically in a single pass at the database layer before sorting by relevance and recency.

Decision lineage with recursive CTEs

When conflicting decisions are merged or updated during human review, older decisions are soft-archived rather than overwritten. Lineage is tracked through parent_decision_id, allowing complete evolutionary trees to be reconstructed using recursive Common Table Expressions:

WITH RECURSIVE ancestors(id, decision, parent_decision_id) AS (
    SELECT id, decision, parent_decision_id FROM decisions WHERE id = ?
    UNION ALL
    SELECT d.id, d.decision, d.parent_decision_id
    FROM decisions d JOIN ancestors a ON d.id = a.parent_decision_id
)
SELECT * FROM ancestors;

Quickstart

1. Install Klyd

0.2.5 is the current release. The 0.2.2 wheel was missing its hook templates and SQL schema; 0.2.3 fixed packaging, 0.2.4 fixed the CLI defects found by exercising every command against the published wheel, and 0.2.5 bounds the provider request so a stalled model cannot hang the git hook. Install the current release:

pip install klyd==0.2.5

2. Initialize a repository

Run inside the root of your Git repository:

kl init

This creates .klyd/memory.db, initializes the configuration file, and installs the Git hooks into .git/hooks/.

3. Configure a model provider

Set your preferred API key (BYOK):

kl config --api-key sk-ant-...
# or: kl config --openai-key sk-...
# or: kl config --gemini-key ...
# or: kl config --groq-key ...

Inspect active configuration:

kl config --show

Provider requests time out after 90 seconds so a stalled gateway cannot hang the post-commit hook. Override the limit in seconds with KLYD_HTTP_TIMEOUT:

KLYD_HTTP_TIMEOUT=180 kl extract-commit

A timeout exits non-zero, names the provider URL, and writes the traceback to .klyd/errors.log.

4. Record decisions from commits

Decisions are automatically extracted by the post-commit hook whenever you make a Git commit:

git commit -m "refactor(db): use SQLite connection pooling instead of global instances"

You can also trigger extraction manually for the latest commit:

kl extract-commit

5. Retrieve relevant decisions

View stored architectural decisions in a table:

kl status

Filter decisions by search keyword:

kl status --search "database"

View decisions grouped by module hierarchy:

kl status --tree

6. Run an agent with decision memory

Launch your coding agent wrapped with Klyd context:

kl run aider

For custom agent invocations, generate the injection context directly:

kl prepare-injection
# Context is written to .klyd/injection.txt

Commands reference

Command Description
kl init Initialise .klyd/ storage and install Git hooks.
kl config Configure model API keys, templates, and extraction thresholds.
kl extract-commit Extract architectural decisions from the latest Git commit.
kl prepare-injection Query matching decisions for staged files and generate .klyd/injection.txt.
kl preview-injection Preview the injection prompt without writing it to disk.
kl status Display active decisions, conflict summaries, and drift statistics.
kl review Interactive CLI to resolve flagged architectural conflicts (accept, merge, edit, reject).
kl pin <id> Pin a non-negotiable architectural constraint so it is always injected.
kl unpin <id> Remove a pinned decision constraint.
kl run <agent> Execute a coding agent with memory injected via command-line arguments.
kl metrics Display aggregated decision counts, average confidence, and conflict rates.

Current status

Klyd is an actively developed developer-tooling project (v0.2.5 distributed on PyPI).

The current implementation is focused on local decision persistence, retrieval, Git lifecycle integration, and terminal coding-agent workflows.

  • Local scope: Designed for single-developer repository workspaces. Remote peer sync and multi-user concurrent locking are not included.
  • LLM extraction dependency: Quality of extracted decisions correlates with commit message clarity and the reasoning capabilities of the configured model.
  • Agent support: Native argument injection is configured for aider and opencode; other agents receive the injection as a final positional argument. The same text is written to .klyd/injection.txt for agents that take a context-file flag.

License

MIT License — see LICENSE.

Metadata

Release files for klyd 0.2.5

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for klyd 0.2.5
File Size Uploaded Provenance Actions
klyd-0.2.5.tar.gz 39.2 kB Without provenance Details for klyd-0.2.5.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for klyd 0.2.5
File Interpreter ABI Platform Actions
klyd-0.2.5-py3-none-any.whl Python 3 none any Details for klyd-0.2.5-py3-none-any.whl

Total release size: 77.5 kB

Release files / klyd-0.2.5.tar.gz

Download URL klyd-0.2.5.tar.gz
Size 39.2 kB
Tags Source
SHA-256 checksum
How to use checksums
d42cf71fe18d01b49b91e86bf6547ff2f0ca818b631ef5d6ad18411e9ad82bf5
BLAKE2b-256 checksum
How to use checksums
6ff69f0640ec74d30927532f17274ae4361b7afdfe1210325d9c0c9f51fd189a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.18

Release files / klyd-0.2.5-py3-none-any.whl

Download URL klyd-0.2.5-py3-none-any.whl
Size 38.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
93c39bdff6ba0a698865f8bfd05015acf419dc921275104f63af4f8c6441dd51
BLAKE2b-256 checksum
How to use checksums
b48a21bbbebb65f0cac0fbec9c5205b43f11d13aad090ad7f942e91b27d14790
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.18

Security for klyd 0.2.5

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page