Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
90 commits
Select commit Hold shift + click to select a range
4789b2b
wip(tdd): red-phase tests + scaffold for reliability overhaul (S1-S6)
mustafa-bharmal-shipveho Sep 4, 2026
fceb7d6
test: de-duplicate sys.path setup in lint/dream tests (promote.py sha…
mustafa-bharmal-shipveho Sep 4, 2026
8c4a570
feat(stats): honest v1.2 metrics with legacy split, rotated-log readi…
mustafa-bharmal-shipveho Sep 4, 2026
a26cdd1
feat(config): per-key layered runtime config; daemon socket + brain_r…
mustafa-bharmal-shipveho Sep 4, 2026
c8984b1
merge: S1 config precedence (dev-hook-A)
mustafa-bharmal-shipveho Sep 4, 2026
350560d
feat(lint): --fix-digests frontmatter backfill; renderer emits name/d…
mustafa-bharmal-shipveho Sep 4, 2026
e9175f9
merge: S6-2 lint --fix-digests + renderer frontmatter (dev-corpus-2)
mustafa-bharmal-shipveho Sep 4, 2026
b0baeac
feat(lint): --dedupe-claims with retraction rows + archive; lint_dirs…
mustafa-bharmal-shipveho Sep 4, 2026
dca7b53
merge: S6-3 lint --dedupe-claims + lint_dirs (dev-corpus-3)
mustafa-bharmal-shipveho Sep 4, 2026
4a113d2
feat(episodic): 20 MiB rotation for episodic/event logs, rolled-file …
mustafa-bharmal-shipveho Sep 4, 2026
dc84b35
feat(health): recall health checks + PENDING_REVIEW health/sync-error…
mustafa-bharmal-shipveho Sep 4, 2026
21a289a
merge: S5-A recall health + PENDING_REVIEW surfacing (dev-guards-A)
mustafa-bharmal-shipveho Sep 4, 2026
1aa532c
feat(rerank): keep RRF score + rerank_score, query(rerank=) override,…
mustafa-bharmal-shipveho Sep 4, 2026
8d61564
feat(sync): 50 MB staging gate, health.json on every exit, provider C…
mustafa-bharmal-shipveho Sep 4, 2026
3dd40d3
merge: S4 reranker plumbing + calibration (dev-hook-D)
mustafa-bharmal-shipveho Sep 4, 2026
6c30be6
merge: S5-C sync size gate + health write + provider fallback (dev-gu…
mustafa-bharmal-shipveho Sep 4, 2026
68db41c
fix(stats): bucket rerank scores as raw logits per S4 calibration
mustafa-bharmal-shipveho Sep 4, 2026
7c16f4c
merge: S6-1 stats v1.2 + utilization (dev-corpus-1)
mustafa-bharmal-shipveho Sep 4, 2026
7963971
test(stats): pin rerank histogram to logit-scale edges from S4 calibr…
mustafa-bharmal-shipveho Sep 4, 2026
c8a9c34
feat(auto-recall): telemetry v1.2 (hit/miss/dedup), session dedup, da…
mustafa-bharmal-shipveho Sep 4, 2026
7dba7e5
merge: S2 telemetry v1.2 + session dedup + daemon-first hook (dev-hoo…
mustafa-bharmal-shipveho Sep 4, 2026
79772b4
merge: S5-B episodic/event rotation + dream_status + dream lint step …
mustafa-bharmal-shipveho Sep 4, 2026
2d90f4a
demo: emit telemetry v1.2 events so the stats beat shows real coverage
mustafa-bharmal-shipveho Sep 4, 2026
77d713e
merge: demo emits telemetry v1.2 (dev-demo-v12)
mustafa-bharmal-shipveho Sep 4, 2026
4913f89
docs(changelog): v0.7.0 reliability overhaul entry; bump version
mustafa-bharmal-shipveho Sep 4, 2026
eeb69e6
fix(rerank): rerank_n caps total pairs across collections
mustafa-bharmal-shipveho Sep 4, 2026
54dfca4
merge: rerank_n caps total pairs across collections (dev-hook-D follo…
mustafa-bharmal-shipveho Sep 4, 2026
827f5a2
chore(version): 0.7.0 in recall/__init__.py, server.json, marketplace…
mustafa-bharmal-shipveho Sep 4, 2026
8ed73c0
feat(daemon): warm recall daemon over unix socket, thin client, daemo…
mustafa-bharmal-shipveho Sep 4, 2026
0666a04
merge: S3 warm recall daemon, thin client, daemon-first CLI/MCP, inst…
mustafa-bharmal-shipveho Sep 4, 2026
b732b72
docs(readme): describe recall stats as coverage/latency, not ROI
mustafa-bharmal-shipveho Sep 4, 2026
1a2c953
fix(cli): recall lint --json emits a single JSON document with manifests
mustafa-bharmal-shipveho Sep 4, 2026
3bd5ec4
fix(rerank): sign-safe demotion of logit scores; single candidate sti…
mustafa-bharmal-shipveho Sep 4, 2026
deba894
merge: sign-safe rerank demotion + single-candidate rerank scoring (f…
mustafa-bharmal-shipveho Sep 4, 2026
6734f23
merge: lint --json single document with manifests (fix-cli)
mustafa-bharmal-shipveho Sep 4, 2026
5de3450
fix(config): daemon socket falls back to brain root without BRAIN_ROO…
mustafa-bharmal-shipveho Sep 4, 2026
de5931c
fix(sync): oversize hold-back restores rename sources like quarantine
mustafa-bharmal-shipveho Sep 4, 2026
a099d19
merge: oversize hold-back restores rename sources (fix-sync)
mustafa-bharmal-shipveho Sep 4, 2026
6d7a022
fix(auto-recall): rerank gate enabled for any numeric threshold incl.…
mustafa-bharmal-shipveho Sep 4, 2026
be65d0e
fix(install): forward --brain-root to every recursive install.sh step
mustafa-bharmal-shipveho Sep 4, 2026
72559c4
merge: rerank gate for any numeric threshold; dream lint rc=1 means f…
mustafa-bharmal-shipveho Sep 4, 2026
7a7dd18
merge: daemon socket fallback without BRAIN_ROOT; min_rerank None mea…
mustafa-bharmal-shipveho Sep 4, 2026
eb8c316
fix(data-policy): utilization sample defaults to the recall cache dir…
mustafa-bharmal-shipveho Sep 4, 2026
38fa23b
fix(sync): oversize summary line reports the configured limit, not a …
mustafa-bharmal-shipveho Sep 4, 2026
51ee39c
docs: auto_recall_min_rerank gate is off when unset (None), not 0.0
mustafa-bharmal-shipveho Sep 4, 2026
ea152b3
fix(health): remote-error scan survives trailing health lines and mat…
mustafa-bharmal-shipveho Sep 4, 2026
d6bc112
merge: health remote-error scan + daemon socket resolver + wording (f…
mustafa-bharmal-shipveho Sep 4, 2026
c3d1d2b
fix(wording): singular doc count, truncation marker, preamble, stats …
mustafa-bharmal-shipveho Sep 4, 2026
a328217
merge: user-facing wording fixes (fix-wording)
mustafa-bharmal-shipveho Sep 4, 2026
f35225a
fix(install): daemon plist rendered via plistlib (no sed injection), …
mustafa-bharmal-shipveho Sep 4, 2026
56baa09
merge: install.sh daemon plist via plistlib, exact placeholder check,…
mustafa-bharmal-shipveho Sep 4, 2026
a4cd6c1
fix(lint): retraction row last + tombstone escaping; quote digest nam…
mustafa-bharmal-shipveho Sep 4, 2026
36c50c6
merge: lint retraction ordering, tombstone escaping, quoted digest ke…
mustafa-bharmal-shipveho Sep 4, 2026
195c991
chore(cli): pass --stub-min-chars to the claim manifest renderer inst…
mustafa-bharmal-shipveho Sep 4, 2026
b0d13fb
fix(stats): daemon errors by reason, faster raw reader, single-pass u…
mustafa-bharmal-shipveho Sep 4, 2026
f13ccf0
merge: daemon errors by reason, faster reader, single-pass utilizatio…
mustafa-bharmal-shipveho Sep 4, 2026
64dd4c8
fix(hook): record dedup after print, shared socket resolver, robust b…
mustafa-bharmal-shipveho Sep 4, 2026
8ca1906
fix(daemon): refresh mutual exclusion, honest busy, bounded queue, um…
mustafa-bharmal-shipveho Sep 4, 2026
718479f
merge: daemon refresh mutual exclusion, honest busy, bounded queue, u…
mustafa-bharmal-shipveho Sep 4, 2026
74f0a2d
fix(daemon-client): forward budget_ms so the daemon bounds its queue …
mustafa-bharmal-shipveho Sep 4, 2026
fc262b1
docs(daemon): client forwards budget_ms
mustafa-bharmal-shipveho Sep 4, 2026
a456d40
merge: dedup record after print, shared socket resolver, robust banne…
mustafa-bharmal-shipveho Sep 4, 2026
be6f014
fix(digests): bounded incremental digests per hourly tick (limit + ti…
mustafa-bharmal-shipveho Sep 4, 2026
c4231b1
merge: bounded incremental digests per hourly tick (fix-digest-budget)
mustafa-bharmal-shipveho Sep 4, 2026
1d50f1a
chore(gitignore): runtime/digest_status.json is machine-local
mustafa-bharmal-shipveho Sep 4, 2026
9933325
chore: one anchored rolled-file rule everywhere; remove scaffold left…
mustafa-bharmal-shipveho Sep 4, 2026
ea38838
merge: anchored rolled-file rule everywhere; remove scaffold leftover…
mustafa-bharmal-shipveho Sep 4, 2026
0581ac5
chore: remove stray :memory:.ses artifact; ignore it
mustafa-bharmal-shipveho Sep 4, 2026
9ad9500
chore: untrack stray :memory:.ses artifact
mustafa-bharmal-shipveho Sep 4, 2026
9f0ad80
refactor(simplify): hot path — throttle dedup prune, parse config lay…
mustafa-bharmal-shipveho Sep 4, 2026
4938176
refactor(simplify): SessionStart path — one read, one config load
mustafa-bharmal-shipveho Sep 4, 2026
1538dfd
refactor(simplify): structured counters instead of regex round-trips
mustafa-bharmal-shipveho Sep 4, 2026
4c1e6cf
refactor(simplify): dedup agent/tools
mustafa-bharmal-shipveho Sep 4, 2026
74fe1a1
refactor(simplify): export BRAIN_ROOT once in install.sh
mustafa-bharmal-shipveho Sep 4, 2026
c7be012
refactor(simplify): flatten the run-boundary condition
mustafa-bharmal-shipveho Sep 4, 2026
9ee220a
refactor(simplify): recall/runtime package cleanups, behaviour-preser…
mustafa-bharmal-shipveho Sep 4, 2026
a17691c
fix(simplify): keep an unreadable sync.log reading as 'missing'
mustafa-bharmal-shipveho Sep 4, 2026
fdf569b
merge: simplify pass, agent tree + install.sh (apply-simplify-agent)
mustafa-bharmal-shipveho Sep 4, 2026
a45dd9a
merge: simplify pass, recall/runtime/eval trees (apply-simplify-recall)
mustafa-bharmal-shipveho Sep 4, 2026
f0484a7
test(dream): make agent/memory win the promote.py name clash regardle…
mustafa-bharmal-shipveho Sep 4, 2026
5d958a1
fix(recall): MCP never falls back into a store a live daemon holds; r…
mustafa-bharmal-shipveho Sep 5, 2026
0e20dbb
fix(exit): leave the hook and the CLI through os._exit so a grpcio te…
mustafa-bharmal-shipveho Sep 8, 2026
445a813
fix(install): seed the brain repo with a local git identity when the …
mustafa-bharmal-shipveho Sep 8, 2026
4a03598
fix(install,hook): report skipped host surfaces honestly; skip two-wo…
mustafa-bharmal-shipveho Sep 8, 2026
d1ab72f
fix(sync): keep stray stderr out of the scanners' way; decide 'wrote …
mustafa-bharmal-shipveho Sep 8, 2026
25874ba
fix(install,hook): never touch the user's launchd under the skip flag…
mustafa-bharmal-shipveho Sep 8, 2026
536a3fd
fix(install): regenerate a stale recall wrapper on upgrade; make the …
mustafa-bharmal-shipveho Sep 8, 2026
0772e72
fix(review): only sync:-prefixed lines end a run; status ignores quot…
mustafa-bharmal-shipveho Sep 8, 2026
2e12b2e
docs(daemon_client): DAEMON_DOWN_REASONS comment names who branches o…
mustafa-bharmal-shipveho Sep 8, 2026
a6aebc1
fix(install): seed the brain identity when nothing explicit is config…
mustafa-bharmal-shipveho Sep 8, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude-plugin/marketplace.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
{
"name": "brainstack-recall",
"description": "Auditable memory for Claude Code: every-prompt recall from your own markdown brain, with a human review gate, provenance, and replay. Exposes the recall_query MCP tool.",
"version": "0.5.1",
"version": "0.7.0",
"source": "https://github.com/mustafa-bharmal-shipveho/brainstack",
"homepage": "https://github.com/mustafa-bharmal-shipveho/brainstack",
"license": "Apache-2.0",
Expand Down
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,6 @@ tmp/
demo/brain/
demo/.cache/
demo/.config/

# sqlite in-memory session artifact accidentally created by tooling
:memory:*
73 changes: 73 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,78 @@
# Changelog

## v0.7.0 (2026-09-04)

**Reliability overhaul: every memory captured, every injection honest, failures visible within a day.**
Driven by the 2026-09-04 audit (`recall` was helping in ~8% of the turns it fired on; 171 Claude
memories never reached the brain; the brain remote had been blocked for 5 days by a 115 MB log;
dream had failed nightly for ~80 cycles; none of it surfaced anywhere a person looks).

- Deterministic exit: the Claude Code hook and the `recall` console script leave through
`os._exit` after flushing and running atexit handlers, so grpcio's occasional abort at
interpreter teardown (exit 134 under load, after the work is done) can no longer make Claude
Code discard an injection that was already printed, or make sync/dream/tests read a good run
as a failure. `recall doctor`'s hook-interpreter probe decides by a stdout sentinel, not by
the return code.
- `recall-mcp`: when the daemon is up but a query fails (timeout, protocol or server error) the
error now reaches the MCP client instead of a silent in-process retry against the store the daemon
holds; only a missing or refused socket falls back.
- `bin/install-recall-cli.sh` regenerates a stale `recall` console-script wrapper (the entry point
moved to `recall.cli:main`), and its `--quiet` mode no longer exits on the first log line — which
had silently skipped the CLI step of every `./install.sh --upgrade`.
- `BRAINSTACK_SKIP_LAUNCHCTL=1` now covers every launchctl call (uninstall, claude-extras): launchd
labels are per-user, so a sandbox uninstall used to unload the real nightly dream and hourly
sync agents. The SessionStart banner now also speaks up when there is no health report but
`sync.log` stopped growing more than 26 h ago (sync agent dead or unloaded).
- Installer first-run fixes: a machine with no git identity gets a repo-local one for the brain
instead of a half-install that dies at the seed commit; the summary says "skipped (not found)"
for host surfaces that do not exist instead of "done"; two-word acks ("ok thanks", "got it")
no longer cost a retrieval query.
- Sync log hygiene: `sync.sh` writes `recall health`'s stderr into `sync.log` prefixed with
`health:` and decides "wrote runtime/health.json" by the file's mtime, not the exit code; the
remote-error, quarantine and oversize scanners anchor on a run's own `sync:` lines, so a stray
traceback after the run's marker no longer blinds them to that run.
- Warm daemon (`recall serve`): a launchd-managed process (`--setup-daemon`, on by default in the
full install, `--no-daemon` to opt out) holds the retriever warm and owns the embedded Qdrant
store; the Claude Code hook, `recall query`, `recall reindex` and `recall-mcp` route through it
over a 0600 unix socket and fall back in-process only when it is not running. The daemon also
owns index freshness (chunked refresh every 5 min), so files mirrored into the brain become
injectable without anyone running the CLI. Hook timeout drops 3000 → 1500 ms.
- Honest telemetry (event schema 1.2): `hit` now means "≥1 doc injected"; new `miss` and `dedup`
outcomes replace phantom hits; full-worker latency is recorded on every outcome including
timeouts; injected paths are logged per doc; legacy 1.1 events stay readable and are reported
separately. `recall stats` reports real coverage, miss/dedup/timeout rates, daemon vs in-process
path, worker vs query latency, and repeat-injection rate; the ROI copy is gone.
`recall stats --utilization` joins injections to Claude transcripts and exports an LLM-judge sample.
- Session dedup: a doc already injected in the same session is not injected again unless its
content changed (`auto_recall_dedup`, 7-day pruning of the per-session store).
- Config precedence fixed: `[tool.recall.runtime]` merges per key across `$RECALL_RUNTIME_CONFIG`,
the project `pyproject.toml` and `~/.agent/runtime/pyproject.toml`, so a project file can no
longer silently disable auto-recall. The repo's own example section moved to `docs/runtime.md`.
- Health (`recall health`, `recall doctor --health`): nine checks (imports freshness, LaunchAgents
loaded, brain push age quoting the real git error, tracked files > 50 MB, log sizes, dream cycle
age + LLM errors, drift, auto-recall enabled from this cwd, daemon alive). Written hourly by
sync to `runtime/health.json`, rendered into `PENDING_REVIEW.md`, and printed as one line per
FAIL in the Claude Code session banner.
- Growth control: sync refuses to stage any file > 50 MB and keeps syncing the rest; raw episodic
and telemetry JSONL are untracked via `templates/brain.gitignore` (appended idempotently on
`--upgrade`); episodic and event logs roll at 20 MiB into dated files that every reader globs;
expired rolled files archive per namespace so the Codex/Claude-session logs stop growing forever.
`runtime/dream_status.json` records each cycle; the dream cycle runs `recall lint --mark` and
reports `lint_findings=`.
- LLM providers find `claude`/`codex` in the usual user-local dirs (`~/.local/bin`, nvm, bun, npm)
even under launchd's minimal PATH, and every LaunchAgent/systemd template includes `~/.local/bin`.
- Corpus hygiene: `recall lint --fix-digests` backfills name/description/type on digests (and the
renderer emits them going forward); `recall lint --dedupe-claims` archives duplicate and
content-free Slack-stub claims with a retraction row so the nightly projection does not
resurrect them; `semantic/archived/**` is excluded from retrieval.
- Reranker plumbing + calibration (`eval/calibrate_rerank_gate.py`): RRF `score` and
`rerank_score` are both kept, `query(rerank=)` overrides per call. Calibrated on 76 labeled
real pairs: no cross-encoder threshold met the precision bar and reranking showed no measurable
ordering gain at 4–13x the latency, so reranking stays OFF by default and `auto_recall_min_rerank`
defaults to 0.0; the numbers are in `eval/RESULTS.md`. `rerank_n` is now a true cap across
collections.
- Demo brain emits schema-1.2 telemetry; `demo/demo.gif` re-recorded.

## v0.5.1 (2026-06-12)

Next release after v0.5.0 (the last tagged release). Supersedes the unreleased
Expand Down
34 changes: 32 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Your coding agents already learn things every session, then forget them by the n

![brainstack: a prompt is auto-enriched with a past lesson, the lesson is traced to its source, and an agent's durable write is refused](demo/demo.gif)

Four beats: the per-prompt hook injects a past lesson before you ask; `recall trace` walks that lesson back to its provenance and originating session; a piped (non-human) `recall remember --reviewed` is refused while the default write lands staged for your review; `recall stats` shows the week's auto-recall ROI. Generated from [`demo/demo.tape`](demo/demo.tape) against a fully synthetic brain built by [`demo/make_demo_brain.py`](demo/make_demo_brain.py) (placeholder names only, safe to publish). Regenerate with `make demo` (requires [vhs](https://github.com/charmbracelet/vhs)).
Four beats: the per-prompt hook injects a past lesson before you ask; `recall trace` walks that lesson back to its provenance and originating session; a piped (non-human) `recall remember --reviewed` is refused while the default write lands staged for your review; `recall stats` shows the week's auto-recall coverage and latency. Generated from [`demo/demo.tape`](demo/demo.tape) against a fully synthetic brain built by [`demo/make_demo_brain.py`](demo/make_demo_brain.py) (placeholder names only, safe to publish). Regenerate with `make demo` (requires [vhs](https://github.com/charmbracelet/vhs)).

## Why you can trust it

Expand Down Expand Up @@ -96,6 +96,7 @@ The full install enables everything. Skip any subset by passing flags to `./inst
| `--no-launchd` | Hourly sync + nightly dream scheduler (launchd agents on macOS, systemd user timers on Linux) | You want to script the schedule yourself |
| `--no-recall-first` | Recall-first directive in `~/.claude/CLAUDE.md`, `~/.codex/AGENTS.md`, `~/.cursor/.cursorrules` | You don't use those agents, or wire elsewhere |
| `--no-auto-recall` | Claude Code UserPromptSubmit hook firing recall on every prompt | Want only agent-driven recall, not the unconditional sweep |
| `--no-daemon` | Warm recall daemon LaunchAgent that keeps the retriever resident; reranking is opt-in (macOS; `--setup-daemon` / `--remove-daemon` manage it directly, see [docs/recall-daemon.md](docs/recall-daemon.md)) | Every query then pays a cold model load; only worth it if you cannot spare a resident process |
| `--setup-systemd` | (Adds systemd user timers explicitly; `--remove-systemd` tears them down) | Wire Linux scheduling without re-running the full install |
| `--yes` | (Accepts the install plan and migrate-discovery prompts non-interactively) | CI / scripted installs |
| `--no-prompt` | (Decline all migrate prompts; still runs the other defaults) | CI / scripted installs |
Expand Down Expand Up @@ -167,6 +168,7 @@ Useful commands:
| `recall reindex` | Rebuild the retrieval cache after large imports/edits. |
| `recall stats --since 7d` | Inspect auto-recall usage and latency. |
| `recall doctor` | Diagnose wiring: hook interpreter, model cache, retrieval mode, scanner, install root. Run this FIRST when something looks wrong. |
| `recall health` | Check the running system: sync backlog, mirror freshness, log sizes, dream cycle, launch agents, drift. Exits 1 on FAIL. See [Health checks](#health-checks). |
| `recall runtime replay` | Reconstruct what entered the agent's context, from logs. |

Retrieval details and benchmark notes: [`recall/README.md`](recall/README.md).
Expand Down Expand Up @@ -254,6 +256,34 @@ recall runtime install-hooks

Hooks are registered with the repo venv's Python interpreter; `recall doctor` verifies the hook interpreter, model cache, retrieval mode, scanner, and install root. Setup details: [`docs/claude-code-setup.md`](docs/claude-code-setup.md).

### Health checks

`recall doctor` checks that brainstack is wired correctly. `recall health` checks that it is still *working*: the background jobs run unattended, so a failure there is silent until something surfaces it.

```bash
recall health # human-readable report; exit 1 on FAIL, 0 on PASS/WARN
recall health --json # same report as JSON
recall doctor --health # doctor output with the health report appended
```

Nine checks run against the live brain:

| Check | Fails when |
|---|---|
| `imports_freshness` | The `~/.claude/projects/*/memory` mirror lags more than 24 h (over 2 h warns). |
| `launch_agents` | A LaunchAgent plist is installed but launchd is not running it. A non-zero last exit warns. |
| `brain_push` | The brain is ahead of its remote and the last successful push is over 3 h old. Quotes the `remote: error:` line from `sync.log`. |
| `large_tracked_files` | A git-tracked file is over 50 MB, so GitHub will reject the push. |
| `log_sizes` | An event log or episodic file is over 20 MB (warn). |
| `dream_cycle` | The last dream cycle is over 36 h old, or the LLM provider was unavailable. |
| `drift` | The brain no longer matches the brainstack checkout it was installed from (warn). |
| `auto_recall_config` | A `pyproject.toml` in your working directory silently shadows the global config and turns auto-recall off. |
| `daemon` | The recall daemon is configured but its socket refuses connections. |

Every failing check carries a `fix:` line with the exact command to run.

The hourly sync agent writes the report to `~/.agent/runtime/health.json`. Two surfaces read that cached file, so a regression reaches you without running anything: the Claude Code `SessionStart` hook prints one line per failure, and `~/.agent/PENDING_REVIEW.md` gains a `## Health` section. A report older than 26 h is reported as stale rather than trusted, because that usually means the hourly agent itself stopped.

## Bring existing memories

The full install discovers `~/.claude/projects/*/memory`, `~/.codex/`, and `~/.cursor/` and prompts y/n before importing each. If you skipped that (minimal install, `--skip-migrate`, `--no-prompt`) or want to import additional sources later:
Expand Down Expand Up @@ -329,7 +359,7 @@ recall remember "always run the exact CI command from the repo config"
recall query "what should I remember before changing CI?"
recall forget ci-command
recall pending --review # review staged candidates
recall stats --since 24h # see auto-recall ROI
recall stats --since 24h # coverage, miss/dedup/timeout rates, latency
recall doctor # diagnose missing wiring
```

Expand Down
71 changes: 70 additions & 1 deletion agent/harness/hooks/_episodic_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
no-op and behavior matches the pre-lock baseline. WSL, git-bash via
Cygwin, macOS, and Linux all provide `fcntl`.
"""
import datetime
import json
import os

Expand All @@ -29,19 +30,82 @@
except ImportError:
_HAVE_FLOCK = False

# S5 rotation threshold (20 MiB) — matches agent/memory/_atomic.ROTATE_BYTES
# and runtime/core/events.EVENT_LOG_ROTATE_BYTES. Read at CALL time by
# `append_jsonl` (the `max_bytes` kwarg defaults to None and resolves to
# this constant inside the body), so callers that thread no threshold
# through — `sdk.append_episodic`, the harness hooks — still pick up a
# monkeypatched value.
ROTATE_BYTES = 20 * 1024 * 1024


def _sentinel_path(data_path: str) -> str:
"""Return the lock sentinel sibling for a data file path."""
return data_path + ".lock"


def append_jsonl(path: str, entry: dict) -> dict:
def _today() -> str:
"""UTC calendar day as `YYYY-MM-DD`, the stamp `rolled_name` inserts."""
return datetime.datetime.now(datetime.timezone.utc).date().isoformat()


def rolled_name(path: str, day: str) -> str:
"""Compute the rotated sibling name for `path` on day `day`.

Only the FINAL suffix counts as the extension, so a compound stem
survives: `AGENT_LEARNINGS.jsonl` -> `AGENT_LEARNINGS.<day>.jsonl`. On
a same-day collision a counter goes before the suffix
(`AGENT_LEARNINGS.<day>.1.jsonl`, `.2`, ...), so a busy day that rolls
several times never overwrites an earlier roll.
"""
directory, name = os.path.split(path)
stem, suffix = os.path.splitext(name)
candidate = os.path.join(directory, f"{stem}.{day}{suffix}")
counter = 0
while os.path.exists(candidate):
counter += 1
candidate = os.path.join(directory, f"{stem}.{day}.{counter}{suffix}")
return candidate


def _rotate_if_oversize(path: str, max_bytes: int) -> str | None:
"""Rename `path` out of the way when it is STRICTLY LARGER than
`max_bytes`, returning the rolled path (or `None` if untouched).

Strictly greater, not at-or-over: a file sitting exactly at the
threshold must not roll, or a brain hovering at the limit would roll on
every single append. Callers must already hold the sentinel lock.
"""
if not max_bytes:
return None
try:
if os.path.getsize(path) <= max_bytes:
return None
except OSError:
return None # missing / unreadable — nothing to roll
rolled = rolled_name(path, _today())
try:
os.rename(path, rolled)
except OSError:
return None # keep appending to the current file
return rolled


def append_jsonl(path: str, entry: dict, *, max_bytes: int | None = None) -> dict:
"""Serialize `entry` to one JSON line and append to `path`.

Lock identity lives on `path + ".lock"` so a concurrent atomic
rewrite of `path` (which swaps its inode) does not invalidate
in-flight appenders' lock acquisitions.

`max_bytes` caps the current file's size (falling back to
`ROTATE_BYTES` when omitted). A file strictly larger than the cap is
renamed to a dated sibling before this entry is appended, so the
append always lands in a file under the cap. The rename happens while
we hold the sentinel lock — the same lock every other appender and the
dream cycle's rewrite take — so a roll can never land between another
writer's open() and write(). Rolled files are never appended to again.

Failure handling: this hook fires per tool call, so any unhandled
exception will dump a traceback to the user's terminal. Catch all
OSErrors (read-only file, full disk, missing dir we can't create,
Expand All @@ -53,6 +117,9 @@ def append_jsonl(path: str, entry: dict) -> dict:
os.makedirs(os.path.dirname(path), exist_ok=True)
except OSError:
return entry # Can't even create the dir — give up silently
# Resolved here, not as a def-time default, so a monkeypatched
# ROTATE_BYTES reaches callers that pass no threshold.
limit = ROTATE_BYTES if max_bytes is None else max_bytes
sentinel = _sentinel_path(path)

if _HAVE_FLOCK:
Expand All @@ -67,6 +134,7 @@ def append_jsonl(path: str, entry: dict) -> dict:
try:
fcntl.flock(lock_fd, fcntl.LOCK_EX)
try:
_rotate_if_oversize(path, limit)
with open(path, "ab") as f:
f.write(payload)
f.flush()
Expand All @@ -83,6 +151,7 @@ def append_jsonl(path: str, entry: dict) -> dict:
else:
# Windows fallback — no locking; matches pre-lock baseline.
try:
_rotate_if_oversize(path, limit)
with open(path, "ab") as f:
f.write(payload)
f.flush()
Expand Down
Loading
Loading