Repository navigation
fix(archive): classify runtime artifacts as non-prose - #836
Conversation
Problem: Claude Code can serialize task notifications, command wrappers, local command caveats, and skill/context payloads through ordinary user-role text channels. Projection filters that only looked at role or content-block shape let those protocol artifacts leak into user-prose context packs. The packaged MCP entrypoint was also vulnerable to ambient Python environment leakage, and Nix path-input builds could fail when the Hatch hook tried live git metadata despite embedded build info. What changed: add shared runtime artifact classification for context versus protocol text, make message_type authoritative for tool/context/protocol filtering, classify Claude Code and Codex parser output consistently, and exclude noise from session enrichment. Package entrypoints now scrub ambient Python variables, the MCP console script is exposed directly, and the Hatch hook prefers embedded build metadata inside sandboxed builds. Verification: ruff check on touched files; focused parser/projection/message tests; semantic facts/message law tests; CLI message tests; Nix package build and MCP help smoke.
|
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 selected for processing (4)
📝 WalkthroughWalkthroughThis PR introduces two new message classification types— ChangesMessage Type Classification and Integration
Build Infrastructure Updates
Sequence Diagram(s)sequenceDiagram
actor Parser as Parser<br/>(Claude/Codex)
participant Text as Message Text
participant Classifier as classify_text_message_type()
participant Runtime as MessageRuntimeMixin
participant Projection as Content Projection
participant Storage as Message Storage
Parser->>Text: Extract message content
Text->>Classifier: Strip reminders, check markers
Classifier->>Runtime: Return MessageType.CONTEXT/<br/>PROTOCOL/MESSAGE
Runtime->>Runtime: Set message_type enum
Runtime->>Runtime: Compute is_protocol_artifact<br/>and is_noise flags
Runtime->>Projection: Route via is_noise check
Projection->>Projection: Strip system-reminder blocks<br/>if SYSTEM_NOISE
Projection->>Storage: Persist classified message<br/>and semantic facts
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Possibly related PRs
Suggested labels
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: fa73f24ced
ℹ️ 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.
Pull request overview
This PR introduces first-class classification of provider runtime/control-plane artifacts as non-prose message types (context / protocol) so projections and filters (notably --prose-only / --no-tool-outputs / --no-file-reads) stop treating command wrappers, task notifications, and injected skill/context payloads as user-authored text. It also includes packaging fixes for the MCP entrypoint and sandboxed build metadata discovery.
Changes:
- Add a shared runtime-artifact classifier and wire it into Claude Code + Codex parsers, plus new
MessageTypevalues (context,protocol). - Make projections/enrichment/range-signal collection treat
context/protocolas “noise” and strip Claude Code<system-reminder>wrappers. - Update CLI/docs and packaging (Hatch build metadata selection; Nix wrappers unsetting ambient Python env vars for all shipped entrypoints).
Reviewed changes
Copilot reviewed 22 out of 22 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| tests/unit/sources/test_parsers_codex.py | Adds coverage ensuring Codex “developer/system” and protocol wrapper messages are typed as context/protocol. |
| tests/unit/sources/test_parsers_claude_code_artifacts.py | New test covering Claude Code runtime artifact classification into context/protocol. |
| tests/unit/core/test_message_types.py | Extends normalization/sql-value tests to include context/protocol. |
| tests/unit/core/test_content_projection.py | Adds projection test ensuring prose-only drops protocol/context noise and strips <system-reminder> wrappers. |
| polylogue/storage/sqlite/queries/message_query_reads.py | Extends allowed message-type filter literals for SQLite reads. |
| polylogue/storage/insights/session/profiles.py | Excludes is_noise (now including protocol/context/tool/system noise) from enrichment text bands. |
| polylogue/sources/parsers/codex.py | Assigns message_type using role + artifact classifier for Codex messages. |
| polylogue/sources/parsers/claude/code_parser.py | Assigns message_type using artifact classifier + meta-record detection for Claude Code messages. |
| polylogue/cli/click_option_groups.py | Updates --message-type help to include context/protocol. |
| polylogue/archive/semantic/models.py | Extends semantic facts model with is_protocol_artifact / is_noise. |
| polylogue/archive/semantic/facts.py | Plumbs new semantic fact fields through build_message_semantic_facts. |
| polylogue/archive/semantic/content_projection.py | Treats context/protocol as system noise in projections and strips Claude Code <system-reminder> blocks. |
| polylogue/archive/message/types.py | Adds MessageType.CONTEXT and MessageType.PROTOCOL. |
| polylogue/archive/message/roles.py | Normalizes developer role into Role.SYSTEM and includes it in SQL role mappings. |
| polylogue/archive/message/model_runtime.py | Adds stored message_type and derives is_tool_use / is_context_dump / is_protocol_artifact / is_noise using message_type + artifact classifier. |
| polylogue/archive/message/artifacts.py | New shared classifier + system-reminder stripping utilities for provider-serialized runtime artifacts. |
| polylogue/archive/conversation/extraction.py | Excludes is_noise messages from range-signal collection. |
| hatch_build.py | Prefers existing embedded polylogue/_build_info.py before requiring a git checkout for build metadata. |
| flake.nix | Wraps polylogue, polylogued, and polylogue-mcp to unset ambient Python env vars. |
| docs/topology-status.md | Updates rendered topology counts to reflect the new module. |
| docs/plans/topology-target.yaml | Registers the new artifacts module and updates LOC metadata for touched files. |
| docs/cli-reference.md | Updates documented CLI options to include context/protocol message types. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| def _text_block_segments(block: Mapping[str, object]) -> list[_Segment]: | ||
| text = _block_text(block) | ||
| if text is None: | ||
| return [_Segment(ContentKind.PROSE, None, block=dict(block))] | ||
| if "<system-reminder>" not in text: | ||
| return [_Segment(ContentKind.PROSE, text, block=dict(block))] | ||
| cleaned = strip_system_reminders(text) | ||
| if not cleaned: | ||
| return [_Segment(ContentKind.SYSTEM_NOISE, text, block=dict(block))] | ||
| return [_Segment(ContentKind.PROSE, cleaned)] | ||
|
|
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@polylogue/archive/semantic/content_projection.py`:
- Around line 260-269: The helper _text_block_segments currently treats any
block containing "<system-reminder>" as SYSTEM_NOISE or drops the block after
cleaning; change it to import and use strip_leading_system_reminders (instead of
strip_system_reminders) so only leading reminder wrappers are removed, and
ensure that when cleaned text remains you return a PROSE _Segment with the
cleaned text and preserve block metadata (i.e., return
[_Segment(ContentKind.PROSE, cleaned, block=dict(block))]) rather than returning
an empty block or SYSTEM_NOISE; keep the existing behavior of returning
SYSTEM_NOISE only when the cleaned result is empty.
In `@tests/unit/sources/test_parsers_claude_code_artifacts.py`:
- Around line 53-57: The test currently builds by_id =
{message.provider_message_id: message for message in result.messages} which can
hide duplicates; add a cardinality check to assert the parser produced the
expected number of messages and that provider_message_id values are unique by
asserting both len(result.messages) == 4 and len(by_id) == 4 (matching the four
expected ids task-1, command-1, skill-1, prompt-1) after calling parse_code() /
inspecting result.messages so duplicates or extra messages fail the test.
🪄 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: 27859552-3b54-4f4f-96af-196d3afdc638
📒 Files selected for processing (22)
docs/cli-reference.mddocs/plans/topology-target.yamldocs/topology-status.mdflake.nixhatch_build.pypolylogue/archive/conversation/extraction.pypolylogue/archive/message/artifacts.pypolylogue/archive/message/model_runtime.pypolylogue/archive/message/roles.pypolylogue/archive/message/types.pypolylogue/archive/semantic/content_projection.pypolylogue/archive/semantic/facts.pypolylogue/archive/semantic/models.pypolylogue/cli/click_option_groups.pypolylogue/sources/parsers/claude/code_parser.pypolylogue/sources/parsers/codex.pypolylogue/storage/insights/session/profiles.pypolylogue/storage/sqlite/queries/message_query_reads.pytests/unit/core/test_content_projection.pytests/unit/core/test_message_types.pytests/unit/sources/test_parsers_claude_code_artifacts.pytests/unit/sources/test_parsers_codex.py
Problem: the build hook fell back to an embedded polylogue/_build_info.py before checking whether the source tree was a live git checkout. That avoided sandbox failures but could ship stale provenance in ordinary local builds. The projection code also stripped Claude Code system-reminder text without preserving the cleaned text block, which could make structured renderers drop prose from mixed-block messages. What changed: resolve git metadata first when .git is present and usable, fall back to embedded metadata only when git metadata cannot be resolved, and preserve cleaned text blocks after reminder stripping. Extend the projection test to cover the retained cleaned block.
Problem: text-block projection removed any system-reminder tag anywhere in a block, which could strip user-authored inline examples. The Claude Code artifact parser test also keyed assertions by provider_message_id without proving that the parser emitted exactly the expected unique messages. What changed: use strip_leading_system_reminders for text-block projection, preserve the cleaned content block metadata, cover inline system-reminder prose, and assert parser output cardinality/uniqueness in the artifact classification test.
## Summary Classifies provider runtime artifacts as first-class non-prose message types so context-pack and prose projections stop treating Claude Code command wrappers, task notifications, local-command caveats, and injected skill/context payloads as user-authored text. Also fixes the packaged Polylogue MCP entrypoint and Nix sandbox build metadata behavior found while debugging the systemwide schema-version mismatch. ## Problem Claude Code serializes some runtime/control-plane payloads through ordinary user-role text channels. Filtering only by role or tool-result content blocks allowed those messages to leak into `--message-role user --prose-only --no-tool-outputs --no-file-reads` reads. The system wrapper also pointed MCP startup through the stale top-level CLI path, and packaged entrypoints could inherit ambient Python env vars. ## Solution Add a shared runtime-artifact classifier with explicit `context` and `protocol` message types, wire it into Claude Code and Codex parsing, make `message_type` authoritative for projection, and exclude context/protocol noise from session enrichment. Package entrypoints now unset ambient Python variables, `polylogue-mcp` is smoke-tested, and Hatch build metadata prefers embedded `_build_info.py` in sandboxed builds. ## Verification - `direnv exec /realm/project/polylogue pytest tests/unit/sources/test_parsers_claude_code_artifacts.py tests/unit/sources/test_parsers_base.py tests/unit/core/test_content_projection.py tests/unit/sources/test_parsers_codex.py -q` -> `129 passed` - `direnv exec /realm/project/polylogue pytest tests/unit/sources/test_parsers_base.py tests/unit/sources/test_parsers_props.py::test_claude_code_message_type_contract tests/unit/core/test_semantic_facts.py tests/unit/cli/test_messages.py -q` -> `106 passed` - `direnv exec /realm/project/polylogue ruff check ...` -> `All checks passed!` - `direnv exec /realm/project/polylogue devtools render-all --check` -> all generated surfaces in sync - `direnv exec /realm/project/polylogue git push -u origin feature/fix/chatlog-runtime-artifact-ontology` pre-push gate -> `verify: all checks passed` - `nix build /realm/project/polylogue#polylogue --no-link --print-out-paths` -> built package - Built package smoke: `polylogue --version` and `polylogue-mcp --help` - Live legacy archive projection check returned zero messages for a protocol-only Claude Code conversation while reporting `total: 3` <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit ## Release Notes * **New Features** * Added `context` and `protocol` message types to CLI and message classification system. * Enhanced artifact detection for runtime-generated message content. * **Improvements** * Refined message filtering logic for improved content classification. * Improved system reminder and protocol artifact handling in content projection. * Extended `developer` role support in message processing. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
PR #836 taught projections how to avoid treating Claude Code / Codex protocol artifacts as user prose, but stored rows still contained context and protocol artifacts as inline message text or legacy `message_type` values, forcing runtime classifiers to compensate at every read. - `polylogue/pipeline/materialization_runtime.py`: persists `MessageType.CONTEXT` and `MessageType.PROTOCOL` directly on the materialized rows so the archive table represents the semantic entity instead of leaving classification to hydration. - `polylogue/archive/message/{artifacts,model_runtime}.py`: hydration trusts the persisted type and only falls back to the runtime classifier when the row predates the materializer change. Refs #839
Two acceptance-criteria leftovers. - #839 (semantic artifacts): adds the resilience-fallback section to `polylogue/archive/message/model_runtime.py` documenting when the runtime classifier falls back from stored `message_type` to inline-text inspection — a behavior PR #836 introduced but had not yet documented in code comments. - #829 (config): consolidates four remaining `os.environ.get()` calls in `cli/query_progress.py`, `cli/shared/formatting.py`, `logging.py`, and `pipeline/services/validation_flow.py` through `load_polylogue_config()`, finishing the env-consolidation pass started in PR #910. Refs #829, #839
PR #836 taught projections how to avoid treating Claude Code / Codex protocol artifacts as user prose, but stored rows still contained context and protocol artifacts as inline message text or legacy `message_type` values, forcing runtime classifiers to compensate at every read. - `polylogue/pipeline/materialization_runtime.py`: persists `MessageType.CONTEXT` and `MessageType.PROTOCOL` directly on the materialized rows so the archive table represents the semantic entity instead of leaving classification to hydration. - `polylogue/archive/message/{artifacts,model_runtime}.py`: hydration trusts the persisted type and only falls back to the runtime classifier when the row predates the materializer change. Refs #839
Two acceptance-criteria leftovers. - #839 (semantic artifacts): adds the resilience-fallback section to `polylogue/archive/message/model_runtime.py` documenting when the runtime classifier falls back from stored `message_type` to inline-text inspection — a behavior PR #836 introduced but had not yet documented in code comments. - #829 (config): consolidates four remaining `os.environ.get()` calls in `cli/query_progress.py`, `cli/shared/formatting.py`, `logging.py`, and `pipeline/services/validation_flow.py` through `load_polylogue_config()`, finishing the env-consolidation pass started in PR #910. Refs #829, #839
Problem Auditing ops maintenance/doctor manual repair surfaces against the automagic-invariants doctrine (polylogue-cfvvt) against PR #3286's own precedent found an inconsistency: that PR added daemon/blob_gc_periodic.py's periodic_blob_gc_check (reclaiming eligible blobs automatically every 900s in bounded batches through the write coordinator) and, in the same change, removed embedding-orphan-reconcile's --yes apply path because its own periodic reconciler made it redundant. blob-gc's --yes survived that PR by omission even though the identical reasoning applies: the manual mutate path is now doing nothing periodic_blob_gc_check doesn't already do. Solution - polylogue/cli/commands/maintenance/_blob_gc.py: removed --yes and the apply branch from blob_gc_command; the command is now always a dry-run preview (mutates always False), matching embedding-orphan-reconcile's read-only shape. gc-history (audit trail read) is untouched. storage/blob_gc.py (run_blob_gc_report, dry_run param) is untouched -- the daemon's periodic caller still uses it with dry_run=False. - Updated the command's help text in maintenance/__init__.py and replaced test_blob_gc_cli_yes_deletes_and_records_generation with test_blob_gc_cli_has_no_mutate_flag, mirroring test_embedding_orphan_reconcile_cli_has_no_mutate_flag's exit-code-2/--yes-rejected assertion pattern. - polylogue/storage/message_type_backfill.py: added a docstring paragraph documenting why this doctor-repair target is KEEP (finite one-time legacy-row remediation, no recurring daemon condition since new-ingest rows are classified correctly since PR #836/#944) as part of the same audit. The audit's other findings (blob-reference-prune-orphans/ replace-from-source and embeddings-rescue: KEEP, no daemon path exists and both require genuine judgment or are one-time migrations; doctor's 5 destructive cleanup targets: KEEP, destructive=True by design with no daemon caller; doctor's session_insights repair target: proven redundant by the same shape but scoped out to a dedicated follow-up, polylogue-ygfwa, given its wider surface coupling) required no code changes and are recorded in polylogue-cfvvt's notes. Verification - devtools test tests/unit/cli/test_archive_maintenance_cli.py -k blob_gc -- 3 passed - devtools test tests/unit/daemon/test_blob_gc_periodic.py -- 4 passed - devtools render all --check -- clean, no "out of sync" surfaces - devtools verify --quick -- exit 0, all 19 steps green - tests/unit/storage/test_blob_gc.py's 7 failures are pre-existing (clock_guard time.time() violations in code this change never touches) and unrelated to this diff Ref polylogue-cfvvt Co-Authored-By: Claude <[email protected]>
## Summary Audits four candidate manual `ops maintenance`/`ops doctor` repair surfaces (polylogue-cfvvt) against the automagic-invariants doctrine and deletes the one confirmed-redundant mutate path found: `ops maintenance blob-gc --yes`. ## Problem PR #3286 added `daemon/blob_gc_periodic.py`'s `periodic_blob_gc_check` (reclaims eligible, aged-out, unreferenced blobs automatically every 900s in bounded batches of 200 through the write coordinator) and, in the same change, removed `embedding-orphan-reconcile`'s `--yes` apply path because its own periodic reconciler made manual apply redundant. `blob-gc`'s `--yes` survived that PR by omission even though the identical reasoning applies: the manual mutate path does nothing `periodic_blob_gc_check` doesn't already do on its own. ## Solution - `polylogue/cli/commands/maintenance/_blob_gc.py`: removed `--yes` and the apply branch from `blob_gc_command`; the command is now always a dry-run preview (`mutates` always `False`), matching `embedding-orphan-reconcile`'s read-only shape. `gc-history` (audit-trail read) is untouched. `storage/blob_gc.py` (`run_blob_gc_report`, `dry_run` param) is untouched — the daemon's periodic caller still uses it with `dry_run=False`. - Updated the command's catalog help text in `maintenance/__init__.py`. - Replaced `test_blob_gc_cli_yes_deletes_and_records_generation` with `test_blob_gc_cli_has_no_mutate_flag`, mirroring `test_embedding_orphan_reconcile_cli_has_no_mutate_flag`'s exit-code-2/`--yes`-rejected assertion pattern. - `polylogue/storage/message_type_backfill.py`: added a docstring paragraph documenting why this doctor-repair target is a legitimate KEEP (finite one-time legacy-row remediation; no recurring daemon condition since new-ingest rows are classified correctly since PR #836/#944), recorded as part of the same audit. The audit's other findings required no code changes and are recorded in `polylogue-cfvvt`'s notes: - `blob-reference-prune-orphans`/`blob-reference-replace-from-source`: KEEP — no daemon path exists for `blob_refs` debt at all, and both commands require genuine judgment per missing blob. - `embeddings-rescue`: KEEP — already documented as an explicit one-time break-glass migration, structurally undetectable by daemon convergence. - Doctor's 5 destructive cleanup targets (`orphaned_messages`, `empty_sessions`, `orphaned_attachments`, `orphaned_blobs`, `superseded_raw_snapshots`): KEEP — `destructive=True` by catalog design, zero daemon caller, genuinely consent-gated. - Doctor's `session_insights` repair target: proven to have the same redundancy shape (covered by both a per-ingest `ConvergenceStage` and a dedicated periodic `convergence_debt` retry loop), but scoped out to a dedicated follow-up (`polylogue-ygfwa`) given its wider surface coupling (`REPAIR_HANDLERS`, maintenance planner/replay, archive-debt status reporting) versus `blob-gc`'s single CLI file. ## Verification - `devtools test tests/unit/cli/test_archive_maintenance_cli.py -k blob_gc` — 3 passed - `devtools test tests/unit/daemon/test_blob_gc_periodic.py` — 4 passed - `devtools render all --check` — clean, no "out of sync" surfaces - `devtools verify --quick` — exit 0, all 19 steps green - `tests/unit/storage/test_blob_gc.py`'s 7 failures are pre-existing (`clock_guard` `time.time()` violations in code this change never touches) and unrelated to this diff Ref polylogue-cfvvt
|
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
Classifies provider runtime artifacts as first-class non-prose message types so context-pack and prose projections stop treating Claude Code command wrappers, task notifications, local-command caveats, and injected skill/context payloads as user-authored text. Also fixes the packaged Polylogue MCP entrypoint and Nix sandbox build metadata behavior found while debugging the systemwide schema-version mismatch.
Problem
Claude Code serializes some runtime/control-plane payloads through ordinary user-role text channels. Filtering only by role or tool-result content blocks allowed those messages to leak into
--message-role user --prose-only --no-tool-outputs --no-file-readsreads. The system wrapper also pointed MCP startup through the stale top-level CLI path, and packaged entrypoints could inherit ambient Python env vars.Solution
Add a shared runtime-artifact classifier with explicit
contextandprotocolmessage types, wire it into Claude Code and Codex parsing, makemessage_typeauthoritative for projection, and exclude context/protocol noise from session enrichment. Package entrypoints now unset ambient Python variables,polylogue-mcpis smoke-tested, and Hatch build metadata prefers embedded_build_info.pyin sandboxed builds.Verification
direnv exec /realm/project/polylogue pytest tests/unit/sources/test_parsers_claude_code_artifacts.py tests/unit/sources/test_parsers_base.py tests/unit/core/test_content_projection.py tests/unit/sources/test_parsers_codex.py -q->129 passeddirenv exec /realm/project/polylogue pytest tests/unit/sources/test_parsers_base.py tests/unit/sources/test_parsers_props.py::test_claude_code_message_type_contract tests/unit/core/test_semantic_facts.py tests/unit/cli/test_messages.py -q->106 passeddirenv exec /realm/project/polylogue ruff check ...->All checks passed!direnv exec /realm/project/polylogue devtools render-all --check-> all generated surfaces in syncdirenv exec /realm/project/polylogue git push -u origin feature/fix/chatlog-runtime-artifact-ontologypre-push gate ->verify: all checks passednix build /realm/project/polylogue#polylogue --no-link --print-out-paths-> built packagepolylogue --versionandpolylogue-mcp --helptotal: 3Summary by CodeRabbit
Release Notes
New Features
contextandprotocolmessage types to CLI and message classification system.Improvements
developerrole support in message processing.