Cleaning an agent's memory is easy. Knowing when to clean it is the part most people get wrong.
Run it too often and you burn tokens on nothing. Run it too rarely and your agent keeps acting on stale notes. agentdream ships a small scheduler that answers the "when" question with three triggers and 164 lines of standard-library Python. This post walks through how it works, using the real code.
Quick context
agentdream is an open source tool for "dreaming": it reads an agent's memory store plus recent session transcripts, then writes a new, cleaned-up store and a report. Duplicates get merged, stale values get replaced, and wrong notes get corrected with citations to transcript lines. By default it is a dry run. Nothing touches your real memory until you accept.
You can run a dream by hand:
agentdream dream --memory examples/memory --sessions examples/sessions But nobody remembers to do that. So the project has agentdream schedule.
The dishwasher analogy
Think of a dishwasher in a shared kitchen. There are three sensible rules for starting it:
- It is full. Enough dirty dishes have piled up.
- Dinner is over. Nobody has added a plate for a while.
- It is 11 pm. A fixed time, but only if there is at least one dirty dish inside.
Nobody runs an empty dishwasher. And nobody starts it while people are still eating.
agentdream's scheduler has the same three rules. The dishes are session transcripts.
agentdream schedule -m ./memory -s "./logs/*.jsonl" --idle 30m # after 30 min without new transcript activity agentdream schedule -m ./memory -s ./logs --every 6h # on an interval (when there are new sessions) agentdream schedule -m ./memory -s ./logs --new-sessions 5 --once # check once (cron-friendly) and exit Those three lines come straight from the README. You can combine the flags. At least one is required, or the constructor raises "give at least one trigger: every, idle or new_sessions".
What counts as a "new" session?
Every trigger depends on one idea: which transcripts has the scheduler not dreamed over yet?
The scheduler does not parse transcripts to find out. It builds a cheap signature for each file:
def _sig(p: Path) -> str: # nanosecond mtimes: a session rewritten within the same second (same size) still counts as new. # (HFS+ only has 1s resolution; APFS/ext4/NTFS are fine.) st = p.stat() return f"{st.st_size}:{st.st_mtime_ns}" Size plus nanosecond modification time. The state file stores one signature per resolved file path. A session is "pending" when its current signature does not match the stored one:
def pending_sessions(self) -> list[Path]: try: files = expand_sources(self.sessions) except Exception: return [] dreamed = self.state.get("dreamed", {}) return [f for f in files if dreamed.get(str(f.resolve())) != _sig(f)] This has a nice side effect. If an old session file grows because the agent resumed it, the signature changes and it becomes pending again. And if the sessions folder disappears, the check returns an empty list instead of crashing. There is an edge test for exactly that, test_sessions_dir_disappears.
The three triggers, in order
The whole decision lives in one method, check(). It returns a Trigger with a human-readable reason, or None.
1. The dishwasher is full.
if self.new_sessions is not None and len(pending) >= self.new_sessions: return Trigger(f"{len(pending)} new session(s) >= {self.new_sessions}", names) 2. Dinner is over. The scheduler looks at the newest pending file. If even the newest one has been quiet for the idle period, the agent has stopped working:
if self.idle is not None and pending: try: latest = max(p.stat().st_mtime for p in pending) except OSError: # a session vanished between listing and stat: check again next time return None if now - latest >= self.idle: return Trigger(...) Note the and pending. Idle time with zero new sessions never fires.
3. It is 11 pm. The interval trigger:
if now - last >= self.every and (pending or not self.only_new): return Trigger(f"interval of {int(self.every)}s elapsed", names) only_new defaults to True, so an elapsed interval with nothing new does nothing. The test for it is short and clear:
def test_interval_without_new_sessions_does_not_fire(tmp_path): """With only_new (default), an elapsed interval and no new sessions does nothing.""" clock = Clock() sch, _s, _calls = _sched(tmp_path, clock, every="1m") sch.check() clock.t += 3600 assert sch.run_once() is None All three triggers fire at their threshold with >=. The module docstring says so directly: "idle for exactly N minutes, exactly N new sessions, exactly one interval since the last run." No off-by-one guessing.
Durations are parsed by a small helper. The tests show what it accepts: "30m", "6h", "1d", "90s", "1h30m", and a bare number, which means seconds.
What happens when a trigger fires
run_once() calls the dream function, then updates state. Two details matter here.
First, with the default only_new, the dream receives only the pending sessions, not the whole folder. You do not pay to re-read last month's transcripts.
Second, sessions are marked as done only when the dream finished:
status = getattr(job, "status", "completed") if status == "completed": for s in trig.new_sessions: p = Path(s) if p.exists(): self.state.setdefault("dreamed", {})[str(p.resolve())] = _sig(p) A failed dream leaves its sessions pending, so the next check retries them. The edge suite proves it with a fake dream that fails once and then succeeds:
assert sch.run_once().status == "failed" assert sch.run_once().status == "completed" assert sch.run_once() is None The state file also keeps a history of the last 50 runs, each with a time, the trigger reason, the job id and the status. It is written with an atomic JSON write, and it lives at .agentdream/scheduler-state.json by default.
The boring failure cases are handled
Schedulers usually break on boring things. This one names them in its docstring and tests each.
Clock goes backwards. An NTP step or a VM restore can move "now" before the last run. A naive interval check would then stall until the clock catches up. Here the baseline resets:
if now < last: # clock went backwards (NTP step, VM restore): restart the interval from now self.state["last_run"] = now self._save_state() return None Files from the future. A session with a modification time ahead of the clock is "not idle yet". The math now - latest is negative, so the idle trigger simply does not fire.
Corrupt state file. _load_state() catches read and parse errors and starts fresh. It also filters entries one by one: a stored signature must match \d+:\d+, or it is dropped. A half-broken file cannot poison the scheduler.
Restarts. State is loaded in the constructor, so a restarted scheduler does not re-dream old sessions. See test_state_survives_restart.
Daemon or cron? Both work
Without --once, the command loops: check, log, sleep for the poll period (default 60s), repeat. Each pass prints either no trigger or dreamed: <job id> (<status>), prefixed with [agentdream schedule].
With --once, it checks a single time and exits. That makes it a good fit for cron or a CI schedule:
# crontab: every 15 minutes, dream if 5 or more new sessions are waiting */15 * * * * cd ~/code/myrepo && agentdream schedule -m ./memory -s ./logs --new-sessions 5 --once Because state is on disk, each cron run knows what earlier runs already handled.
You can also put defaults in config so the command needs fewer flags. From docs/CONFIG.md:
[schedule] # defaults for `agentdream schedule` every = "6h" idle = "30m" new_sessions = 5 poll = "60s" state_file = ".agentdream/scheduler-state.json" It is still a dry run
A scheduled dream does not rewrite your memory. Like every dream, it stages a new store and a report. The scheduler only passes apply=True when you add --apply yourself. After a scheduled run you review as usual:
agentdream list agentdream show <job-id> agentdream accept <job-id> Testable by design
One last design choice worth copying. The Scheduler constructor takes clock, sleep and dream_fn as arguments. Tests pass a fake clock and a fake dream, then move time forward by setting a number. No real sleeping, no flaky timing. That is why the edge suite can test "idle for exactly N minutes" at the exact boundary.
You can use the same hook to schedule something else entirely. The architecture doc lists Scheduler(dream_fn=...) as an extension point.
Takeaways
- Schedule memory cleanup on activity, not just on the clock. agentdream offers three triggers:
--new-sessions N,--idle 30m,--every 6h. - "New" is tracked by file path plus
size:mtime_ns. Cheap, and resumed sessions count again. - An interval with nothing new does nothing. No empty dishwasher runs.
- Failed dreams keep their sessions pending. Completed ones are never re-dreamed, even after a restart.
- Clock jumps and corrupt state files are handled and tested.
- Use
--oncefor cron. Results are a dry run unless you pass--apply.
Repo: github.com/mvplab-ai/agentdream. The scheduler is in src/agentdream/scheduler.py, and its tests are in tests/test_scheduler.py and tests/edge/test_scheduler_edges.py.

