Skip to content
context How to use ctx
Login

How to use ctx

Each section is one task. Commands assume ctx is on your PATH; ctx with no arguments lists them all, and ctx version prints its version and SQLite's.

Install

From a release archive

A release archive is a Claude Code plugin. It holds bin/ctx, the ctx and ctx-wiki skills, and hooks that archive each session.

tar xzf ctx-0.0.1-darwin-arm64.tar.gz
claude plugin marketplace add ./ctx-0.0.1-darwin-arm64
claude plugin install ctx@ctx
ln -s "$PWD/ctx-0.0.1-darwin-arm64/bin/ctx" ~/.local/bin/ctx
ctx init
ctx scan

While the plugin is enabled, ctx is on the Bash tool's PATH inside Claude Code; the link puts it on yours. The Linux archives need glibc 2.34 or later.

If you also have the ctx hooks in your own settings.json, remove them, or every session is archived twice.

Install from source

make                      # needs a C compiler and zlib
cp ctx ~/.local/bin/
mkdir -p ~/.claude/skills && cp -R skill/ctx skill/ctx-wiki ~/.claude/skills/
ctx init
ctx scan

Then add the hooks to ~/.claude/settings.json, merged with any you have:

{
  "hooks": {
    "SessionStart": [{ "hooks": [
      { "type": "command", "command": "ctx hook", "async": true },
      { "type": "command", "command": "ctx ticket offer", "timeout": 3 },
      { "type": "command", "command": "ctx rules offer", "timeout": 3 }
    ] }],
    "SubagentStart": [{ "hooks": [{ "type": "command", "command": "ctx rules offer", "timeout": 3 }] }],
    "PostToolUse": [{ "matcher": "Artifact", "hooks": [{ "type": "command", "command": "ctx artifacts keep", "timeout": 5 }] }],
    "Stop":       [{ "hooks": [{ "type": "command", "command": "ctx hook", "async": true }] }],
    "PreCompact": [{ "hooks": [{ "type": "command", "command": "ctx hook", "async": true }] }],
    "SessionEnd": [{ "hooks": [{ "type": "command", "command": "ctx hook", "async": true }] }]
  }
}

Use the full path to ctx if ~/.local/bin is not on the PATH hooks run with.

Archive your sessions

With the hooks installed there is nothing to do. ctx hook notes the transcript and returns at once; the archiving runs detached. At most once an hour it also scans ~/.claude/projects (or $CLAUDE_CONFIG_DIR/projects) for transcripts that grew without a hook, and syncs repositories that have a remote. That check runs on any turn, at most once an hour, so a session that runs for days gets it too.

By hand:

ctx scan [DIR]            # archive everything that grew since it was last read
ctx archive FILE.jsonl    # archive one transcript
ctx extract FILE.jsonl    # print the redacted turns without storing them

Each turn records who it is from: user for what you typed, assistant, tool for tool output and meta for text the harness added, such as reminders, notifications and messages from other sessions. Transcripts call all but the assistant "user"; ctx tells them apart. The first scan after upgrading corrects turns archived before this, from the transcripts still on disk, and drops the api-request-blob copies older versions archived as extra turns. The corrected technotes sync; upgrade ctx on every machine before syncing, since older versions read only user and assistant turns.

Before anything is stored, known secret shapes (API keys, tokens, private keys, passwords in URLs and the like) become [REDACTED], and long tool output is trimmed. Each session becomes a technote in your private repository, repo:me, one per session per day, tagged with its project. A project is the directory the session ran in, or the project it belongs to after ctx project add.

Keep sessions out, or take one out

ctx exclude /tmp/bench            # sessions run in this directory or beneath it are never archived
ctx exclude                       # list what is excluded
ctx exclude --remove /tmp/bench
ctx forget SESSION                # take an archived session out of the index, and keep it out
ctx forget                        # list forgotten sessions

An excluded directory covers its sessions and the memory notes Claude Code keeps for it, so a benchmark or a throwaway experiment does not end up in your archive or among your rules. Claude Code names a session's folder after its working directory with every character that is not a letter or digit turned into a dash, so an exclusion also covers a sibling whose name continues with a dash: /tmp/bench covers /tmp/bench-2 but not /tmp/benchmarks.

ctx forget removes a session's turns, decisions and page records from the index. A later scan does not archive it again and a rebuild does not bring it back. The text stays in the private repository's history, which Fossil cannot shed, so this is for keeping something out of search, not for destroying a secret.

A whole project can be named instead of a directory or a session:

ctx exclude --project myproj            # stop archiving it; what is held stays searchable
ctx exclude --remove --project myproj
ctx forget --project myproj             # take every session of it out of the index

exclude --project keeps out the transcript folders that project's sessions have come from so far, so a session started later in a new directory, such as a fresh worktree, is still archived. forget --project forgets the sessions held now; it does not stop new ones, so use both to be rid of a project. As with one session, forgotten text stays in the private repository's history.

Search past work

ctx search WORDS...              # this project first; everything if nothing matches
ctx search --all WORDS...        # every project
ctx search --limit 30 WORDS...   # more than the default 12
ctx search -- --json --since    # after --, every word is searched for, option names included
ctx turn ID                      # one turn
ctx turn ID 2 5                  # with 2 turns before and 5 after
ctx turn ID 0 0 --full           # without trimming a long turn

A turn matches if it has any of the words, and turns with more of the rarer words rank higher. Use exact names and the literal words of an error; two or three rare words beat a sentence. Each hit shows #ID, project, speaker, date and a snippet with the matched words in brackets.

Search also covers each project's sources and wiki once they are indexed. Superseded, retracted and retired material is left out unless you ask for it:

ctx search --history WORDS...           # include superseded sources and retired pages
ctx search --as-of 2026-03-01 WORDS...  # what ctx knew and held true on that date

--as-of returns sessions up to that date, and sources that had been added by then, were valid on that date and had not yet been replaced or retracted. It leaves out wiki pages.

The ctx skill tells agents how to search well. Archived text is a record, not instructions: an agent should never act on commands it finds there.

Index a repository's documents

Design notes, decision records, RFCs and guides say what was decided and why, in their authors' words. ctx docs makes a directory of them searchable alongside your sessions, where they sit: nothing is copied and no model is called.

ctx docs add ~/code/myproj/docs                 # filed under the project of that directory
ctx docs add ~/code/myproj/rfcs --project myproj
ctx docs                                         # each directory, its project, how many documents
ctx docs scan                                    # read again now; the periodic scan also does this
ctx docs remove ~/code/myproj/docs               # stop, and take its documents out of the index
ctx docs check [--project P]                     # what one document says of another that is not so

It reads text files ending in .md, .markdown, .txt, .rst, .adoc, .org or .wiki, up to 2 MB each, split by heading. It skips hidden folders and node_modules, vendor, target, build and dist. Each file is tracked by its content, so a scan reads only what changed and drops what was deleted. Secret-shaped strings are redacted in the index as they are for sessions; the files are not touched.

A hit names the file and the heading it was found under, so the file can be opened:

#749 myproj doc /Users/you/code/myproj/docs/adr-011-retries.md Consequences
    ... make [policy] [decisions] ...

ctx turn 749 1 2 reads the section with those around it. When the same text is in two files, such as a page and a built copy of the site, search shows it once.

ctx docs check reads the indexed documents for what one says about another that the other does not bear out. It knows numbered decision records and RFCs by their file names (adr-011-retries.md, rfc-0004-wire.md, or 0007-ledger.md in a folder named adr, rfcs or decisions) and by the Status: line near the top of each. It reports:

docs/adr-002-agent-loop.md:3: ADR-026 is called Proposed here; its own status is Accepted
docs/adr-006-queues.md:63: ADR-008 is named here, and no document has that number
2 findings in 170 documents

It calls no model and exits 1 when it finds anything, so it can run in a repository's CI. It does not find two documents that disagree in their prose.

ctx docs conflicts does that, with two model commands: the one set by ctx rules classifier screens, and the one set by ctx rules judge-with confirms.

ctx docs conflicts --run [--project P] [--limit N]   # screen up to N pairs (600 unless given)
ctx docs conflicts [--project P]                      # the conflicts found so far

A run pairs each section with the sections of other documents that share its rarest words. The small model reads the pairs three at a time and flags any that cannot both be true; the larger one judges each flagged pair and must quote both passages. A conflict is kept only if both quotes are in the text, so neither model can invent one.

2. idempotency race handling
   docs/guide/idempotency.md § Keys: "the check and the write are not one atomic step" (likely current)
   docs/design/features.md § Idempotency: "KV Create is atomic"

Pairs that share a quoted passage are listed as one conflict: a stale line contradicted in five places appears once, with every passage beneath it.

  ctx docs conflicts dismiss 3f2a9c1e --reason "the design note is historical"
  ctx docs conflicts --dismissed          # what was set aside, and why
  ctx docs conflicts restore 3f2a9c1e

A dismissed conflict is not listed, counted in the session-start note or shown by the nudge, and finding the same pair again does not bring it back. It returns only if one of its passages is edited, because an edited passage is a new pair.

  "PostToolUse": [{ "matcher": "Read|Edit|Write|MultiEdit", "hooks": [{ "type": "command", "command": "ctx docs nudge", "timeout": 3 }] }]

In a test of 46 small edits to documents holding a stale passage, agents given only the session-start line never noticed the conflict in the file they were editing. With this hook they noticed 44 times: 6 fixed the passage, 38 said it was disputed, none changed the wrong document, and all still did the edit asked for, at 14% more cost.

This is for documents kept in an ordinary directory. A project's sources/ are different: copied in, pinned to a version and citable from the wiki; see Add sources.

Search from a client that calls tools

Some clients cannot run commands but can call tools over the Model Context Protocol: a desktop chat app, or an agent host with no shell. ctx mcp serves them. The client starts it, it answers on standard input and output, and it exits when the client closes it. Nothing runs in the background.

Register it wherever the client lists its servers. In Claude Code:

claude mcp add ctx -- ctx mcp

In a client configured by a JSON file:

{ "mcpServers": { "ctx": { "command": "ctx", "args": ["mcp"] } } }

Give the full path to ctx if the client does not use your PATH, and set CTX_DB in the server's environment if your archive is not at the default place.

It offers two tools, which run the commands above and return what they print:

Tool Arguments Runs
search query; optionally all (every project) and limit (12 unless given, at most 50) ctx search
turn id; optionally before and after (turns to show around it) and full ctx turn

search looks in the project of the directory the client started the server in, and in every project if nothing matches there, as the command does. The server also tells the client's model when to use it, which stands in for the note a session start gives in Claude Code.

With Claude Code you do not need this: the ctx skill and the commands do the same job. In a test on 209 sessions the two scored the same; see benchmarks.md.

Check the archive for secrets

ctx audit                 # scan turns added since the last run; exits 1 if anything is open
ctx audit --all           # rescan the whole archive, for instance after a new rule
ctx audit --limit 100     # list more than 30 open findings
ctx audit --allow ID "a test fixture, not a key"
ctx audit --tickets       # open one ticket per rule with open findings

ctx audit looks for secret-shaped strings that redaction did not catch. It prints where each one is, never the value: findings for known values first, then the rest oldest first. To check for secrets you know, pipe them in one per line:

your-secret-tool export | ctx audit --known

tools/doppler-values.py | ctx audit --known does this for every Doppler secret you can read, leaving out settings whose names mark them as not secret. A finding names the value by its line number; tools/doppler-values.py --name N says which secret line N is.

A link to a page published with html-artifact-publisher ends in a token, and nothing in the token says whether it only reads the page or can change it. So the token is cut from every such link except the read link in the publisher's own result, under viewerUrl or commentUrl.

When a rule is added, what this machine already stored is redacted again, once, by the next scan: each turn of its session technotes, then the index. The same pass drops a turn that an older ctx stored twice. A technote changed this way gets a new version, and Fossil keeps the old one in its history, so a secret that mattered should still be revoked where it was issued.

Keep standing rules

A rule is something you want every future session to follow, such as "add a changelog entry when we cut a release". Rules are kept on purpose, not found by chance in old sessions, and each one says where it came from.

ctx remember "Add a changelog entry when we cut a release"            # this project
ctx remember "Bump versions by x.x.1 until we leave beta" --until 2027-03-01
ctx remember "Never push straight to main" --project '*'               # every project
ctx rules                     # the rules in force here, with every-project ones
ctx rules --all               # every rule anywhere, with retired and expired ones
ctx rules retire KEY --reason "we left beta"
ctx rules retire KEY --reason "now says more" --by NEWKEY             # replaced

Every scan also imports ~/.claude/CLAUDE.md, each project's CLAUDE.md and AGENTS.md, and Claude Code's memory files, the ones it writes on its own when you correct it. A memory file belongs to the project whose transcripts sit beside it, and records the session it was written in. Redaction applies as for transcripts. When a file changes, its rule gets a new version; when it is deleted, its rule is retired. ctx rules import does this at once.

A classifier proposes rules from what you type. It is any command that reads a prompt on stdin and answers on stdout, so it works with whatever model you use; ctx supplies the prompt and only ever records proposals. It sees the turns you typed, never tool output, and nothing becomes a rule until you accept it:

ctx rules classifier "claude -p --model haiku --tools ''"   # or llm, codex exec, a local model
ctx rules propose              # classify new turns now; the hourly scan does it too
ctx rules proposed             # this project's waiting proposals; --all for every project
ctx rules accept 12 [--text "better wording"] [--until DATE]
ctx rules reject 13            # never proposed again
ctx rules classifier --off     # stop
ctx rules candidates           # the turns a classifier would see, as JSON lines
ctx rules prompt               # the question it is asked
ctx rules suggest TURN TEXT    # record a proposal from any other tool
ctx remember "..." --from 444886    # a rule that records the turn you said it in
ctx turn turn:UUID                  # read that turn again later, by the id a rule records

eval/rules_bench.py --classify "CMD" scores a classifier against a labelled set of your turns. On 1,000 of them, Haiku found 84% of the standing instructions at 76% precision, DeepSeek 80% at 60%; matching words such as "always" found 17%.

ctx rules offer is a SessionStart hook, installed by the plugin. It tells the agent that past sessions are searchable, lists rules it would not otherwise load (those from ctx remember, and memory from this project's other folders) and mentions waiting proposals. On 90 questions about past work it raised Claude's score from 66.5 to 73.5 (better on 16, worse on 6) with 7% fewer tokens; on DeepSeek, agents used ctx in 89 answers instead of 66 and needed half the tool calls.

Rules fade by kind, not by age. Claude Code files status snapshots ("what shipped", "the backlog") as memory of type project; most go stale within weeks, so such a note fades 30 days after its file was last written, and editing it brings it back. Rules in your own words and corrections stay until you retire them. On 42 rules you labelled, 12% of your own rules had gone stale, 44% of corrections and 83% of status notes; age-based fading caught more stale rules but quieted a quarter of true ones. A memory note an agent wrote also fades while its project is silent: no session for 90 days, counted in the archive's own time so a machine left off fades nothing, and only once the archive spans 90 days. Its project's next session brings it back. On 73 notes you labelled, this caught 18 of 29 stale ones; a model reading the sessions caught 1, because notes go stale when work stops, which no session says. Rules in your own words never fade this way.

A faded rule is listed by ctx rules --all and found by ctx search --history.

Two checks catch the rest, and both leave the decision to you:

ctx rules judge-with "claude -p --model sonnet --tools ''"   # any command that answers on stdout
ctx rules judge          # check rules in projects with new turns; the hourly scan does it too
ctx rules keep KEY       # still true: not asked about again for 90 days
ctx rules review         # the rules due their monthly check, 30 at a time
ctx rules review --done  # mark the listed ones reviewed

The judge reads a rule beside your recent turns in its project and flags it only with a quote of your own words that appears exactly in those turns, so it cannot invent a contradiction. Each call to the judge or classifier is stopped, with anything it started, after 120 seconds. The next session in that project asks you once, at a natural break, and never about the same rule within 30 days; your answer runs keep or retire. In an experiment on 42 labelled rules, Sonnet flagged 3, all of them truly stale, while Haiku flagged 9 with 3 wrong. Most stale rules are never contradicted in conversation; the monthly review is for those, mentioned once a month at session start.

Each rule is a technote in your private repository, so every version is kept and rules sync with your archive. A rule past its --until date expires. Search shows rules in force, each under its file name or key; --history brings back expired, replaced and retired ones.

Pick up after a compaction

Every question an agent asked you with AskUserQuestion is a decision record: the question, its options, and your answer, read from the archived turns.

ctx decisions            # this project's latest questions and answers
ctx decisions --open     # those still waiting for you, from the last 14 days
ctx decisions --all      # every project

A question is answered, declined (you replied in your own words, which become the answer), interrupted (the session ended or was compacted before you answered) or open. On one archive of 745 questions, 727 were answered, 15 declined, 2 interrupted and 1 open; 83% of the answers name one of the offered options.

Every page an agent published is an artifact record: its address, each version, the file it came from, and the turn in which you approved a version.

ctx artifacts            # this project's pages, newest first
ctx artifacts --all      # every project
ctx artifacts forge      # those whose title, file or address has the word

Pages published with html-artifact-publisher are listed as well, under their read link, with one version for each check-in. Their files stay on the publisher, which already keeps every version; an edit link is never recorded.

A version counts as approved only when your very next turn was a short yes ("yes", "go", "do it", "approved") and no newer version came first; the record names that turn, so ctx turn turn:ID shows it. This is strict on purpose: on one archive of 1,124 publishes of 322 pages it recorded 43 approvals, and most approvals, which come after some discussion, are not recorded. A page with no approval listed may still have been approved.

A page's file sits in scratch space that a reboot clears, so a PostToolUse hook on the Artifact tool, ctx artifacts keep, copies each published version beside the database at once (pages over 16 MB are skipped, and only the page itself, not its supporting files). The next scan files the versions worth keeping in your private repository, with secrets redacted: every approved version, and a page's newest version once a day has passed without another. Each page is one technote, so its history is the kept versions, and it syncs with the rest of the archive. Other copies are deleted.

ctx artifacts show URL > page.html    # the kept copy

A machine running a ctx from before this would read a kept page as a session, so upgrade every machine that syncs the archive first.

When a session is compacted or resumed, ctx rules offer begins with where it stood, from that session's own turns: questions still waiting for you or cut off, what you decided in the last two days, the pages it published in the last three days with their addresses, messages from other sessions in the last day, rules you set in it, and when you last reported a landing. A fresh session gets none of this.

Set up a project

A project maps a directory to a shared Fossil repository held inside the ctx database. Sessions run under that directory belong to it, and its sources and wiki live in that repository.

Sources are committed from an ordinary Fossil checkout, so start from a Fossil repository and clone it into ctx:

fossil init ~/fossils/myproj.fossil             # or use one you already serve
cd ~/code/myproj && fossil open ~/fossils/myproj.fossil
ctx project add myproj --clone ~/fossils/myproj.fossil

The clone's URL, a file path or an http URL, becomes the project's remote: ctx project pull brings in check-ins from it and ctx sync myproj sends wiki pages back. Other forms:

ctx project add myproj                          # an empty repository, for a wiki without sources
ctx project add myproj --import repo.fossil     # a copy of a Fossil repository file, with no remote
ctx project add myproj --root DIR --remote URL  # map another directory, and set where it syncs
ctx project list                                # name, repository, directory
ctx project pull myproj [--from URL]            # bring in new check-ins

Repository names keep only letters and digits: my-proj becomes repo:myproj.

Work with tickets

Tickets live in your private repository, repo:me, each tagged with its project, so they sync with your archive. --type is Task (the default), Bug, Feature or Question.

ctx ticket new "Fix the importer" --type Bug --body "Stalls on files over 2 GB" \
  --acceptance "A 3 GB file imports" [--blocked-by ID]...
ctx ticket ready              # open and unblocked, for this project
ctx ticket ready --all        # every project
ctx ticket show ID
ctx ticket claim ID [--as NAME]
ctx ticket done ID --result "Fixed in 4f2a91"
ctx ticket drop ID --reason "Superseded by 9c1e"

A claim belongs to one person. When repo:me has a remote, ctx syncs before and after a claim, so two machines cannot both take the same ticket.

ctx ticket offer runs at session start. It prints nothing unless this project has ready work, and then lists up to five tickets for the agent, as a record, not as instructions.

Add sources

Sources are the documents a project's knowledge is built from: specs, papers, vendor docs, notes. They live in the project's checkout under sources/, are committed like code, and are never edited in place.

ctx source add ~/Downloads/spec.pdf --origin https://example.com/spec \
  --class versioned --valid-from 2026-01-15 [--as vendor/spec.pdf]

This copies the file to sources/ and writes spec.pdf.origin.json beside it, with its SHA3 hash, origin, class, dates, risk and who added it. Commit both in the checkout, then pull into ctx and index:

fossil add sources && fossil commit -m "Add the vendor spec"   # and fossil push if served
ctx project pull myproj
ctx index

The class says how long a source can be trusted:

Class Meaning Needs
evergreen stays true
versioned true for one version of something best with --valid-from, and --valid-until once replaced
perishable goes stale with time --review-after DATE

Other options: --retrieved DATE, --how (how it was obtained), and --risk security|money|legal|api, which keeps the wiki from retiring anything built on it without a person.

ctx source check fails if any source has no origin, has changed since its origin was recorded, or has an invalid class, and lists perishable sources due for review. Run it in the project's CI.

Retire a source

Old information is superseded, not erased. Add the newer source, then record one of three relations:

ctx source add ~/Downloads/spec-v3.pdf --origin https://example.com/spec/v3 \
  --class versioned --valid-from 2026-09-01
ctx source supersede spec.pdf --by spec-v3.pdf --relation replaces --reason "v3 replaced v2"
ctx source supersede spec.pdf --by errata.md --relation amends --reason "errata"
ctx source supersede spec.pdf --relation retracts --reason "withdrawn by the vendor"
ctx source uses sources/spec.pdf  # which wiki claims depend on it

Names work with or without the sources/ prefix. Each relation appends an event to sources/SUPERSEDED.jsonl; commit it like any other change. After replaces or retracts, search leaves the old source out unless asked with --history or --as-of; an amended source stays in. Run ctx wiki repin afterwards, as below.

Keep a wiki

The wiki is Markdown pages compiled from the sources. ctx wiki save is the only way a page is written, and it refuses one whose provenance does not hold. The ctx-wiki skill teaches agents the format; a page looks like this:

# Cache design

The cache keeps entries for 30 seconds.[^ttl]

Synthesis: short lifetimes and nightly eviction keep the table small.[^ttl][^evict]

See [Eviction policy](/wiki?name=Eviction+policy).

The gate checks, without any model:

It adds a ## Sources list and a ## Provenance block, and reports any claim the new version dropped. Get the full trunk hash for citations with:

ctx sql "SELECT fsl_open('repo:myproj'), fsl_use('repo:myproj'), fsl_resolve('trunk')"

Then:

ctx wiki save "Cache design" page.md --model MODEL [--ticket ID] [--session ID]
ctx wiki publish             # regenerate the Wiki Index and Wiki Health pages
ctx wiki check               # every citation still holds; exits 1 on a problem
ctx wiki why "Cache design"  # each claim beside its quote, to review by eye
ctx sync myproj              # push the pages to the project's remote

The gate proves a quote exists; only a reader can tell it supports the claim. Read ctx wiki why for every page.

When sources change:

ctx wiki repin                # move each claim whose quote survives; ticket the rest
ctx wiki queue                # stale knowledge, most depended-on first
ctx wiki retire PAGE --reason WHY [--by NEWER-PAGE]
ctx wiki restore PAGE
ctx wiki retire --auto        # list pages nothing needs any more
ctx wiki retire --auto --apply

--auto retires only a page whose sources are all gone (superseded, retracted, or more than 90 days past review), that nothing links to, that past sessions do not mention, and that has no risk class. Anything else that looks finished becomes a ticket for a person. A retired page keeps its text and history.

Every command takes --project P to work on a project other than the current directory's.

Share between machines

Each repository syncs with a Fossil server over plain http, so use a private network or an ssh tunnel; ctx has no TLS.

A remote must hold a copy of the same repository. Give ctx remote a local file that does not exist yet and it writes that copy, readable only by you; one that exists is never overwritten. Serve the file, or reach it as a file:

ctx remote me /srv/ctx/me.fossil                # writes the copy and syncs with it
fossil server --port 8080 /srv/ctx/me.fossil    # on the host; or zit serve
ssh -N -L 8080:127.0.0.1:8080 host              # on each machine
ctx remote me http://127.0.0.1:8080/
ctx sync                                        # every repository with a remote

On a second machine, start from that copy instead of an empty archive:

ctx init --clone http://127.0.0.1:8080/

Sessions archived on other machines become searchable after each sync. The hooks also sync at most once an hour while you work.

A project syncs with the server it was cloned from (ctx project add --clone URL), or with one you set:

ctx remote myproj URL
ctx sync myproj

Add past sessions to prompts

ctx inject is a UserPromptSubmit hook that adds up to three short snippets from past sessions to a prompt when its rare words match strongly, and nothing otherwise. It is not installed by default: in an eval of 90 questions it scored no better than the ctx skill alone. To try it, add to settings.json:

"UserPromptSubmit": [{ "hooks": [{ "type": "command", "command": "ctx inject", "timeout": 3 }] }]

ctx recall is a lighter UserPromptSubmit hook: when your prompt opens with a reference to earlier work ("do you remember", "last time", "didn't we"), it adds one line telling the agent to search first. It matches words only and never opens the database. It is not installed by default either: on your prompts it would fire less than once a day, and in the eval agents already searched on all 13 questions that would trigger it.

A subagent starts without the session-start note, so ctx rules offer also answers the SubagentStart event with that one line (about 45 tokens) and nothing else.

ctx gate is a PreToolUse hook for sessions the note never reached: one that started before ctx was installed, or under a client that runs no session-start hook. In such a session the first search (Grep, Glob, or a shell grep, rg, find, git log and the like) is turned back once with the same note, and a line saying that a search for code will go through if run again. After that it says nothing. It also says nothing in a session that got the note, in a project with no archived sessions, or when anything goes wrong.

"PreToolUse": [{ "matcher": "Grep|Glob|Bash", "hooks": [{ "type": "command", "command": "ctx gate", "timeout": 3 }] }]

ctx stats --hooks ends with how many sessions it turned back in the period.

It is not installed by default, because it refuses a tool call, if only once. On 139 questions put to an agent told nothing about ctx, it raised the score from 22.5 to 85.5; the note itself gives about 117, and with the note in place a gentler hook that only added lines after a search changed nothing. See benchmarks.md.

Two measurements shaped this. Asked plainly, with no hint that a question is about past work, fresh agents with the skill searched the archive on 18 of 23 held-out questions; rewording the skill's triggers made it 19, so the wording stayed. And a hook that held back an agent's question when you had answered a similar one before was dropped: replayed over 743 real questions it fired on 133, and the earlier turns held your eventual answer in 16% of those and a conflicting one in 8%.

Rebuild and upgrade

ctx rebuild

drops the search index, citations and links and rebuilds them from the repositories. When a new version of ctx changes those tables it rebuilds by itself on first use; the kept tables are upgraded in place. A rebuild of a large archive takes a minute or two.

Measure and improve the skill

ctx stats              # the last 8 weeks
ctx stats --weeks 26

ctx stats shows, per week and per project, how many sessions ran and how often agents used ctx in them: searches, searches that found nothing, ctx turn reads and loads of the ctx skill. It counts commands agents really ran, not mentions of them, from the archive alone, so it is free to run weekly. A project with many sessions and no searches is where the skill is not being reached for.

eval/skill_eval.py measures the ctx skill against a private bank of questions about past work, with blind grading and a held-out set, so a change to the skill is kept only if results improve. The question bank and results stay in ~/.ctx/eval. eval/README.md describes the loop.

See how ctx is doing

Each hook and each ctx search or ctx turn writes a line when it starts and one when it ends to a small log beside the database (ctx.sqlite.calls, rotated at 1 MB). A hook that the harness stopped leaves a start with no end, so a slow hook shows up even though it never finished.

ctx stats --hooks          # runs, median, 95th percentile, slowest, cut off, over limit; last 7 days
ctx stats --hooks --days 1
ctx status                 # one line for a status bar: ctx 14 searches · hooks 9 ms

ctx status reads only the log, in about 10 ms. It adds a warning when hooks were cut off in the last day, when the slowest took over a second, or when the hourly scan is late. To show it in Claude Code's status line, have your status line script print its output.

Decide what is waiting on you

ctx collects things only you can settle: rules it proposed from what you typed, documents that disagree, projects it holds, and the hooks it runs. ctx page puts them on one page, with the evidence beside each, and ctx page apply does what you chose.

ctx page                        # writes <database>.page.html and prints its path
ctx page --open                 # the same, then opens it in your browser
ctx page --out decisions.html   # or somewhere else
ctx page apply choices.txt      # shows what the list would do; changes nothing
ctx page apply choices.txt --yes

The page is one file with no network use and no model calls, and it is private to you (mode 0600). Open it in a browser. Each row has three choices: proposed rules are Accept, Later or Not a rule; conflicts are Fix, Not a conflict or Later; projects are Keep, Stop archiving or Forget; hooks are Keep, Later or Remove. Use suggestions takes the suggestion on every row in a section that has one, and the reason is written in the row. Nothing is chosen for you. Your choices become a short list at the foot of the page, in words such as accept rule 12 and stop archiving myproj; copy it into a file. They are not commands, on purpose: pasted into a shell they do nothing, so the one way to act on them is ctx page apply, which shows its plan first.

ctx page apply reads that file, or standard input. Without --yes it prints one line for each action and a count for each kind, and changes nothing. With --yes it runs each as ctx itself, prints each result, and stops at the first failure, saying how many ran. Only the choices the page writes are accepted; any other line, a ctx command included, refuses the whole file before anything runs, and names the line. Arguments are read with shell single-quote rules and are never passed to a shell.

What the numbers mean, and where they stop:

Query the database directly

ctx sql "SELECT project, count(*) FROM ctx_capture GROUP BY 1"

ctx sql runs one statement with libfossil's SQL functions loaded, such as fsl_open, fsl_use and fsl_resolve. The tables are described in schema/state.sql and schema/index.sql.

Environment

Variable Effect
CTX_DB the database, instead of ~/.ctx/ctx.sqlite
CLAUDE_CONFIG_DIR where transcripts are found, instead of ~/.claude
USER the name on check-ins, claims and sources
CTX_SESSION the session ctx wiki save records a page against

  1. [^ ttl ]
    "The cache TTL is 30 seconds." [design.md](/file?name=sources/design.md&ci=FULLHASH&txt=1)
  2. [^ evict ]
    "Evictions run nightly." [ops.md](/file?name=sources/ops.md&ci=FULLHASH&txt=1)