Repository navigation
feat(sources): live filesystem watcher for Claude Code + Codex - #541
Conversation
|
Warning Rate limit exceeded
To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (16)
📝 WalkthroughWalkthroughIntroduces a realtime JSONL ingestion system via a new Changes
Sequence Diagram(s)sequenceDiagram
actor User
participant CLI as polylogue watch CLI
participant Watcher as LiveWatcher
participant FileSystem as FileSystem<br/>(watchfiles)
participant CursorStore as CursorStore<br/>(SQLite)
participant Parser as parse_file()
participant Archive as Polylogue<br/>Archive
User->>CLI: polylogue watch --root=...
activate CLI
CLI->>Watcher: __init__ + startup
activate Watcher
Watcher->>FileSystem: _catch_up scan roots
FileSystem-->>Watcher: existing *.jsonl files
loop For each unseen file
Watcher->>CursorStore: get(path)
CursorStore-->>Watcher: byte_offset=0 (default)
Watcher->>FileSystem: read from offset
FileSystem-->>Watcher: file content
Watcher->>Parser: parse_file(path)
Parser->>Archive: ingest records
Watcher->>CursorStore: set(path, new_byte_size)
end
rect rgba(100, 150, 200, 0.5)
Note over Watcher,FileSystem: Continuous watch loop
Watcher->>FileSystem: awatch(roots) - monitor changes
activate FileSystem
FileSystem-->>Watcher: file modification event
deactivate FileSystem
Watcher->>Watcher: debounce_s quiet period
Watcher->>CursorStore: get(path)
CursorStore-->>Watcher: byte_offset
Watcher->>FileSystem: read current size
FileSystem-->>Watcher: size
alt File has grown
Watcher->>FileSystem: read from offset
FileSystem-->>Watcher: new content
Watcher->>Parser: parse_file(path)
Parser->>Archive: ingest new records
Watcher->>CursorStore: set(path, new_byte_size)
else File unchanged or shrunk
Watcher->>Watcher: skip (no growth)
end
end
User->>CLI: Ctrl+C
CLI->>Watcher: stop()
deactivate Watcher
deactivate CLI
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 20785eff71
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@polylogue/sources/live/watcher.py`:
- Around line 89-97: The current _catch_up builds a full in-memory list of files
which can OOM; instead, stream files and process each immediately: in _catch_up
iterate each root and then loop over root.rglob("*.jsonl"), for each p call
p.is_file() and if true immediately await self._ingest_if_grown(p) while
maintaining a simple counter to track how many files were processed; update the
logger to report the processed count (logger.info) after or during the streaming
loop rather than preloading all paths. Ensure you modify the references in
_catch_up (and keep using self._ingest_if_grown and logger) so no intermediate
list like files is created.
- Around line 99-117: The debounce logic can miss updates and never removes
entries from _pending; fix _schedule and _debounced: in _schedule always update
entry.last_change_at (before checking/creating a task) and ensure a task is
created only if none exists, and in _debounced after the sleep/ingest cycle
remove the entry from self._pending when this task is the current
entry.pending_task and there have been no new changes during the ingest;
additionally, after calling _ingest_if_grown(entry.path) check whether
entry.last_change_at changed during ingestion and if so continue the debounce
loop (or let a new loop run) instead of exiting so in-flight changes are not
missed; use the existing symbols _schedule, _debounced, _pending, _PendingFile,
entry.pending_task, entry.last_change_at, _debounce_s and _ingest_if_grown to
implement this behavior.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 0a336589-caca-4f28-93f5-39a4f8972f73
⛔ Files ignored due to path filters (1)
uv.lockis excluded by!**/*.lock,!**/*.lock
📒 Files selected for processing (14)
docs/cli-reference.mddocs/plans/topology-target.yamldocs/test-quality-workflows.mddocs/topology-status.mddocs/verification-catalog.mdpolylogue/cli/click_command_registration.pypolylogue/cli/commands/watch.pypolylogue/sources/live/__init__.pypolylogue/sources/live/cursor.pypolylogue/sources/live/watcher.pypyproject.tomltests/unit/cli/__snapshots__/test_terminal_snapshots.ambrtests/unit/cli/test_click_app.pytests/unit/sources/test_live_watcher.py
| async def _catch_up(self, roots: list[Path]) -> None: | ||
| files: list[Path] = [] | ||
| for root in roots: | ||
| files.extend(p for p in root.rglob("*.jsonl") if p.is_file()) | ||
| if not files: | ||
| return | ||
| logger.info("live.watcher: catch-up scan over %d file(s)", len(files)) | ||
| for path in files: | ||
| await self._ingest_if_grown(path) |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Avoid preloading all catch-up files before ingest
This builds a full in-memory list of every *.jsonl before processing. For large histories, startup memory and time-to-first-ingest increase unnecessarily. Stream files directly and count as you go.
♻️ Proposed refactor
async def _catch_up(self, roots: list[Path]) -> None:
- files: list[Path] = []
- for root in roots:
- files.extend(p for p in root.rglob("*.jsonl") if p.is_file())
- if not files:
- return
- logger.info("live.watcher: catch-up scan over %d file(s)", len(files))
- for path in files:
- await self._ingest_if_grown(path)
+ processed = 0
+ for root in roots:
+ for path in root.rglob("*.jsonl"):
+ if not path.is_file():
+ continue
+ processed += 1
+ await self._ingest_if_grown(path)
+ if processed:
+ logger.info("live.watcher: catch-up scan over %d file(s)", processed)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/sources/live/watcher.py` around lines 89 - 97, The current
_catch_up builds a full in-memory list of files which can OOM; instead, stream
files and process each immediately: in _catch_up iterate each root and then loop
over root.rglob("*.jsonl"), for each p call p.is_file() and if true immediately
await self._ingest_if_grown(p) while maintaining a simple counter to track how
many files were processed; update the logger to report the processed count
(logger.info) after or during the streaming loop rather than preloading all
paths. Ensure you modify the references in _catch_up (and keep using
self._ingest_if_grown and logger) so no intermediate list like files is created.
| def _schedule(self, path: Path) -> None: | ||
| entry = self._pending.get(path) | ||
| if entry is None: | ||
| entry = _PendingFile(path=path) | ||
| self._pending[path] = entry | ||
|
|
||
| loop = asyncio.get_running_loop() | ||
| entry.last_change_at = loop.time() | ||
| if entry.pending_task is None or entry.pending_task.done(): | ||
| entry.pending_task = asyncio.create_task(self._debounced(entry)) | ||
|
|
||
| async def _debounced(self, entry: _PendingFile) -> None: | ||
| loop = asyncio.get_running_loop() | ||
| while True: | ||
| await asyncio.sleep(self._debounce_s) | ||
| if loop.time() - entry.last_change_at >= self._debounce_s: | ||
| break | ||
| await self._ingest_if_grown(entry.path) | ||
|
|
There was a problem hiding this comment.
Debounce task can miss in-flight changes and leaks _pending entries
At Line 107, new events only update last_change_at when a task is already running. If a change lands while Line 116 is ingesting, no second task is queued; that event may not be ingested until a future change. Also, finished entries are never removed from _pending, so memory grows with unique paths seen.
💡 Proposed fix
async def _debounced(self, entry: _PendingFile) -> None:
loop = asyncio.get_running_loop()
- while True:
- await asyncio.sleep(self._debounce_s)
- if loop.time() - entry.last_change_at >= self._debounce_s:
- break
- await self._ingest_if_grown(entry.path)
+ try:
+ while True:
+ await asyncio.sleep(self._debounce_s)
+ if loop.time() - entry.last_change_at < self._debounce_s:
+ continue
+
+ last_seen_change = entry.last_change_at
+ await self._ingest_if_grown(entry.path)
+
+ # If another event arrived during ingest, debounce and ingest again.
+ if entry.last_change_at <= last_seen_change:
+ break
+ finally:
+ current = self._pending.get(entry.path)
+ if current is entry:
+ self._pending.pop(entry.path, None)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/sources/live/watcher.py` around lines 99 - 117, The debounce logic
can miss updates and never removes entries from _pending; fix _schedule and
_debounced: in _schedule always update entry.last_change_at (before
checking/creating a task) and ensure a task is created only if none exists, and
in _debounced after the sleep/ingest cycle remove the entry from self._pending
when this task is the current entry.pending_task and there have been no new
changes during the ingest; additionally, after calling
_ingest_if_grown(entry.path) check whether entry.last_change_at changed during
ingestion and if so continue the debounce loop (or let a new loop run) instead
of exiting so in-flight changes are not missed; use the existing symbols
_schedule, _debounced, _pending, _PendingFile, entry.pending_task,
entry.last_change_at, _debounce_s and _ingest_if_grown to implement this
behavior.
Adds polylogue/sources/live/ with watchfiles-based watcher and a SQLite byte-size cursor; ingests new + appended JSONL records into the archive within seconds of being written. Idempotent via content-hash dedup; the cursor only suppresses re-parsing files that have not grown since last seen. There is no "live session" concept — any JSONL under the watch roots may grow at any moment, including ones years old (resume). CLI: polylogue watch (foreground; sinnix service in a follow-up). Tests: 25 unit tests over cursor round-trip, ingest-skip logic, catch-up bootstrap, debounce, and end-to-end via the watchfiles event loop. Ref #539 Co-Authored-By: Claude <[email protected]>
20785ef to
f32be0e
Compare
## Summary \`polylogue watch\` (#539, landed in #541) imports \`watchfiles\` at runtime; the pyproject dep was added but \`flake.nix\` hardcodes \`propagatedBuildInputs\` separately and \`watchfiles\` was missed there. Nix-built binary fails with \`ModuleNotFoundError: No module named 'watchfiles'\` when \`polylogue-watch.service\` starts. ## Problem The \`polylogue\` Nix derivation lists Python deps explicitly, not from pyproject. Anyone deploying via \`pkgs.polylogue\` (sinnix) gets a binary missing \`watchfiles\`. ## Solution Add \`watchfiles\` to the \`propagatedBuildInputs\` list. ## Verification \`\`\`bash nix build .#polylogue ./result/bin/polylogue watch --help # exits 0; previously crashed \`\`\` Repro of the underlying failure: starting \`polylogue-watch.service\` on a host with the master version pre-fix produces: \`\`\` ModuleNotFoundError: No module named 'watchfiles' \`\`\` Co-authored-by: Claude <[email protected]>
## Summary Adds \`polylogue/sources/live/\` with a \`watchfiles\`-based watcher and a SQLite byte-size cursor. Ingests new and appended JSONL records into the archive within seconds of being written. Idempotent via content-hash dedup; the cursor only suppresses re-parsing files that haven't grown since last seen. There is no "live session" concept — any JSONL under the watch roots may grow at any moment, including ones years old (resume). CLI: \`polylogue watch\` (foreground; sinnix service swap is a follow-up). Closes #539. ## Problem Polylogue ingested via an hourly systemd timer (\`polylogue-run.timer\` → \`polylogue run acquire parse materialize render index\`). \`polylogue run --watch\` existed but \`WatchRunner\` was \`while True: full_pipeline(); sleep(interval)\` — the polling pattern we wanted gone. The downstream goal is **session-recall** (#540): a fresh Claude Code session must see what happened in recent sessions, which requires conversations in the archive within seconds, not on the next hourly tick. Both target sources are append-only JSONL; \`~/.claude/projects/<encoded-cwd>/<uuid>.jsonl\` and \`~/.codex/sessions/YYYY/MM/<uuid>.jsonl\`. ## Solution \`polylogue/sources/live/\`: - \`cursor.py\` — \`CursorStore\` over a small \`live_cursor\` table inside the archive SQLite (\`CREATE IF NOT EXISTS\`, no schema-version bump). - \`watcher.py\` — \`LiveWatcher\` runs \`watchfiles.awatch\` recursively over the source roots. On modify/create of \`*.jsonl\` it debounces 2s of inactivity, checks the cursor, and runs \`Polylogue.parse_file()\` if the file has grown. - \`default_sources()\` — returns the canonical roots (\`claude_code_path()\`, \`codex_path()\`). CLI: \`polylogue watch [--root PATH ...] [--debounce-s N]\`. Long-running foreground command. \`polylogue run\` keeps its bulk-mode purpose. Catch-up behaviour: on watcher start, \`_catch_up\` walks all files in roots and ingests anything that's grown past its cursor. Handles "watcher offline for a week, multiple files appended" and "year-old conversation resumed while watcher was off" identically. Failure handling: parse errors don't advance the cursor — next event retries. Missing files are silent. ## Verification \`\`\`bash nix develop -c devtools verify --quick # green (format, lint, mypy, render-all, all 5 topology lints) nix develop -c pytest -q tests/unit/sources/test_live_watcher.py # 25 passed nix develop -c pytest -q --ignore=tests/integration # 5642 passed (no regressions) \`\`\` Coverage: - CursorStore: round-trip, default, upsert, isolation, persistence, table creation, ISO-8601 timestamps. - ingest_if_grown: skip-when-unchanged, re-ingest-on-grow, year-old-resume, missing-file-silent, parse-failure-no-cursor-advance, retry-on-next-event, source_name=parent-dir. - catch_up: pre-existing files, skip-already-processed, recursive walk, non-jsonl ignored, empty roots. - Debounce: rapid changes coalesced. - End-to-end via \`watchfiles.awatch\`: modify-triggers-ingest, new-file-triggers-ingest, deletion-doesn't-ingest. ## Follow-ups - Sinnix sibling PR: replace \`polylogue-run.timer\` with \`polylogue-watch.service\` (\`Type=simple, Restart=always, MemoryMax=2G\`); retire hourly polling. - Retire \`polylogue/pipeline/watch.py:WatchRunner\` once \`polylogue watch\` covers all watch use cases. - #540 (MCP + CLI session-recall surface). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added `polylogue watch` command to monitor source directories and ingest sessions live with configurable debounce and custom root paths. * **Documentation** * Updated CLI reference, topology plans, and verification catalog to reflect new watch functionality. * **Tests** * Added comprehensive test coverage for live filesystem watching and cursor persistence. * **Chores** * Added filesystem watching dependency. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: Claude <[email protected]>
## Summary \`polylogue watch\` (#539, landed in #541) imports \`watchfiles\` at runtime; the pyproject dep was added but \`flake.nix\` hardcodes \`propagatedBuildInputs\` separately and \`watchfiles\` was missed there. Nix-built binary fails with \`ModuleNotFoundError: No module named 'watchfiles'\` when \`polylogue-watch.service\` starts. ## Problem The \`polylogue\` Nix derivation lists Python deps explicitly, not from pyproject. Anyone deploying via \`pkgs.polylogue\` (sinnix) gets a binary missing \`watchfiles\`. ## Solution Add \`watchfiles\` to the \`propagatedBuildInputs\` list. ## Verification \`\`\`bash nix build .#polylogue ./result/bin/polylogue watch --help # exits 0; previously crashed \`\`\` Repro of the underlying failure: starting \`polylogue-watch.service\` on a host with the master version pre-fix produces: \`\`\` ModuleNotFoundError: No module named 'watchfiles' \`\`\` Co-authored-by: Claude <[email protected]>
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
Summary
Adds `polylogue/sources/live/` with a `watchfiles`-based watcher and a SQLite byte-size cursor. Ingests new and appended JSONL records into the archive within seconds of being written. Idempotent via content-hash dedup; the cursor only suppresses re-parsing files that haven't grown since last seen.
There is no "live session" concept — any JSONL under the watch roots may grow at any moment, including ones years old (resume).
CLI: `polylogue watch` (foreground; sinnix service swap is a follow-up).
Closes #539.
Problem
Polylogue ingested via an hourly systemd timer (`polylogue-run.timer` → `polylogue run acquire parse materialize render index`). `polylogue run --watch` existed but `WatchRunner` was `while True: full_pipeline(); sleep(interval)` — the polling pattern we wanted gone. The downstream goal is session-recall (#540): a fresh Claude Code session must see what happened in recent sessions, which requires conversations in the archive within seconds, not on the next hourly tick.
Both target sources are append-only JSONL; `
/.claude/projects//.jsonl` and `/.codex/sessions/YYYY/MM/.jsonl`.Solution
`polylogue/sources/live/`:
CLI: `polylogue watch [--root PATH ...] [--debounce-s N]`. Long-running foreground command. `polylogue run` keeps its bulk-mode purpose.
Catch-up behaviour: on watcher start, `_catch_up` walks all files in roots and ingests anything that's grown past its cursor. Handles "watcher offline for a week, multiple files appended" and "year-old conversation resumed while watcher was off" identically.
Failure handling: parse errors don't advance the cursor — next event retries. Missing files are silent.
Verification
```bash
nix develop -c devtools verify --quick # green (format, lint, mypy, render-all, all 5 topology lints)
nix develop -c pytest -q tests/unit/sources/test_live_watcher.py # 25 passed
nix develop -c pytest -q --ignore=tests/integration # 5642 passed (no regressions)
```
Coverage:
Follow-ups
Summary by CodeRabbit
New Features
polylogue watchcommand to monitor source directories and ingest sessions live with configurable debounce and custom root paths.Documentation
Tests
Chores