Repository navigation
feat(hermes): lifecycle-event spool, ATIF importer, delivery correlation - #2876
Conversation
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Warning Review limit reached
Next review available in: 59 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (26)
✨ 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 |
PR #2876 was never merged -- an earlier bead-tracking commit incorrectly stated it was. It's open and correctly held pending the same fix-round that hit the session rate limit, same as polylogue-layg/polylogue-hleq. Co-Authored-By: Claude <[email protected]>
…hema Problem: an adversarial review of PR #2876 found looks_like_atif_payload matched only a synthetic polylogue_artifact: "hermes_atif_trace" marker key invented by this repo's own marker_payload() test fixture -- it could never recognize a real, unmodified Hermes/NeMo Relay ATIF export. No Hermes source access was available when the original detector was written. What changed: the detector/parser now match the real, externally-published NVIDIA NeMo Relay ATIF-v1.7 trajectory schema -- confirmed field-for-field against docs.nvidia.com/nemo/relay, github.com/NVIDIA/NeMo-Relay, and the upstream hermes-agent-fork/plugins/observability/nemo_relay README (top-level schema_version/session_id/agent/steps/subagent_trajectories; step fields source/tool_calls/observation/message) before trusting the fix. Tool-call steps become tool execution spans, message-only steps become bounded LLM-response evidence (character length only, never the text itself), subagent_trajectories become delegation evidence. Unrecognized step shapes and malformed entries are counted and surfaced, never silently dropped or coerced into a known kind. Residual honesty gap, now smaller and disclosed prominently: no live- generated ATIF sample was available to confirm exact field semantics byte-for-byte, so import_fidelity_declaration() still caps every capability at "inferred", never "exact". This is now surfaced in docs/architecture.md's provider table (not only the module docstring) so the caveat is visible without reading source. Follow-up bead the prior notes flagged as "not yet created" is now filed: polylogue-fs1.2.1. Also fixes a real circular import (archive.artifact_taxonomy.runtime -> sources.parsers.hermes_spans -> sources/__init__ -> ... -> archive.artifact_taxonomy) introduced by the original module-level import, via the same deferred-import pattern already used elsewhere in this file for an equivalent cycle. And fixes two dead `is None` checks against json_document() (which returns `{}`, never `None`, on coercion failure) that mypy --strict flagged and that let a non-object step silently become a fabricated "unrecognized shape" event instead of being skipped-and-counted as the docstring already claimed. Verification: devtools test tests/unit/sources/parsers/test_hermes_spans.py -- 10 passed. mypy --strict polylogue/sources/parsers/hermes_spans.py polylogue/archive/artifact_taxonomy/runtime.py -- clean. Ref polylogue-segf. Co-Authored-By: Claude <[email protected]>
…g order-dependence Problem: an adversarial review of PR #2876 found reconcile_lifecycle_events unit-tested only against synthetic fixtures, unreachable from any production surface -- nothing read the durable raw_hook_events spool and the ingested session snapshot and fed them through it, so fs1.7's own AC ("an incomplete event stream is reconciled visibly against the session snapshot") was not actually true at the product level. What changed: new context/hermes_lifecycle_reconciliation.py is the read-side join over two durable tiers (source.db lifecycle spool, index.db ingested snapshot), mirroring the pattern context.hermes_delivery_correlation already established. Wired onto the public facade as Polylogue.reconcile_hermes_session_lifecycle (added to BESPOKE_METHODS + a dedicated facade contract test that drains real spool events against a real seeded index.db snapshot). Separately, the review asked for adversarial/malformed-shape fixture coverage rather than only the happy path -- doing that surfaced a real, previously-undetected bug in reconcile_lifecycle_events' own pairing algorithm: it processed events in temporal (observed_at_ms) order, so a finish event with an earlier timestamp than its start (clock skew, or a delayed-but-earlier-stamped delivery) was incorrectly reported as an unpaired gap, and a duplicate (redelivered) start marker for the same correlation id silently overwrote the earlier event id as the "open" pointer. Rewrote the pairing to be order-independent (correlation-id-set membership, not temporal scan) with first-occurrence-wins on duplicates -- backward compatible with every existing happy-path test. Four new adversarial tests cover out-of-order finish-before-start, duplicate start markers, duplicate on_session_finalize markers, and a genuine gap surviving alongside a duplicate/out-of-order pairing (proving the rewrite doesn't paper over real gaps). Also fixes the MINOR "corruption vs absence collapsed silently" finding on both Hermes facade read seams in api/archive.py (_archive_correlate_hermes_context_deliveries and the new _archive_reconcile_hermes_session_lifecycle): both caught (sqlite3.Error, ValueError) around the whole read and returned the same empty result whether the archive was simply not initialized yet or present but corrupted, with zero distinguishing signal. Both now log a warning specifically on the corruption path -- the empty-result contract to callers is unchanged (a larger, separate decision), but an operator/log scan can no longer confuse "nothing ingested yet" with "archive present but unreadable". Two new tests corrupt source.db directly and assert the warning fires only in that case. Verification: devtools test tests/unit/sources/parsers/test_hermes_lifecycle.py tests/unit/context/test_hermes_lifecycle_reconciliation.py -- 13 passed. devtools test tests/unit/api/test_facade_contracts.py -k hermes -- 6 passed. devtools render topology-projection && devtools render topology-status -- new module reflected. Ref polylogue-segf. Co-Authored-By: Claude <[email protected]>
…e drift Problem: an adversarial review of PR #2876 found two MINOR issues in sources/hooks.py: 1. _persist_record's origin lookup defaulted any unrecognized provider token to "codex-session" (_ORIGIN_TOKEN_BY_PROVIDER.get(provider_token, "codex-session")) instead of raising. _validated_record already rejects any provider outside _SUPPORTED_PROVIDERS before a record reaches this point, making the default dead code in the current call path -- but a future drift between _SUPPORTED_PROVIDERS and _ORIGIN_TOKEN_BY_PROVIDER (e.g. a provider added to one set but not the other) would have silently misclassified a genuinely-unknown provider as Codex. 2. _reject_duplicated_transcript's field-list/threshold policy is copied (not importable-shared) across three independent runtime boundaries: the main package, the standalone polylogue-hooks pip distribution (explicitly documented as having no dependency on the main polylogue package), and the dependency-free contrib/polylogue-hook bash script -- with zero drift protection beyond one fixed-value behavioral test per producer. What changed: (1) raises HookSpoolRecordError instead of defaulting, with a direct regression test that bypasses upstream validation to exercise the defense-in-depth path itself, independent of _validated_record ever being correct. (2) a single bash script and a deliberately dependency-free pip package cannot share a literal Python helper across that boundary without breaking the isolation that boundary exists for -- instead added a drift guard (test_transcript_duplication_policy_stays_in_sync_across_hook_producers) that cross-checks the literal keys/threshold across all three copies via subprocess introspection + source-text regex, so a future edit to one copy that forgets the other two fails loudly in CI instead of silently. Also adds a truncated/malformed-JSON-envelope-alongside-a-valid-event spool test (a crash-mid-write or producer-bug scenario the adversarial review asked for): confirms drain_hook_event_spool leaves the malformed file inspectable rather than crashing the batch, and still materializes the other valid pending event in the same pass. Verification: devtools test tests/unit/sources/test_hook_spool.py -- 23 passed. Ref polylogue-segf. Co-Authored-By: Claude <[email protected]>
…rt contract Problem: fs1.7 -- Hermes lifecycle hooks are best-effort (a synchronous call can be lost during a Polylogue outage), and Hermes has no stable archival export contract to couple against instead of its private state.db schema. Polylogue already had exactly the durable-spool machinery this needs (sources/hooks.py, built for Claude Code/Codex hook events) but it only accepted those two providers. Solution: - Extend sources/hooks.py to accept provider="hermes" through the same atomic-enqueue/idempotent-drain contract, plus a payload hygiene guard (_reject_duplicated_transcript) enforcing that lifecycle events carry ids/hashes/timings/outcomes, never a second copy of message text. - Add sources/parsers/hermes_lifecycle.py: the runtime lifecycle-event taxonomy (model attempts/retries/fallbacks, tool start/finish/failure/ denial, approvals, subagent start/finish, compaction, rewind, the on_session_end/on_session_finalize distinction, context_injected) and reconcile_lifecycle_events(), which renders an incomplete event stream visible against a session snapshot (unpaired events, events referencing unknown message ids) rather than silently accepting a gap. - Add schemas/hermes_export_contract.py: a versioned per-session export schema (HermesArchivalExportV1) covering every active/inactive/rewound/ compacted/observed message, cost provenance, parent relationship, archive/handoff state, and repository context, with a checked-in fixture. An unrecognized schema_version fails loudly (HermesExportSchemaError) rather than being silently coerced. - Extend both hook-event producers (contrib/polylogue-hook, packaging/polylogue-hooks) with the Hermes event vocabulary and the same duplicated-transcript guard -- exercised end-to-end via subprocess, not mocked. - docs/design/hermes-archival-export-contract.md documents the contract, the file-watch fallback (the existing LiveWatcher path, not a new mechanism), and is explicit that the upstream Hermes-repo commit is an external artifact this session could not author (no write access to that repo) -- this is the Polylogue-side half plus the handoff proposal. Verification: devtools test tests/unit/sources/test_hook_spool.py tests/unit/sources/test_hermes_export_contract.py tests/unit/sources/parsers/test_hermes_lifecycle.py -- 25 passed (subset of the 43-test combined run reported in the PR). devtools verify --quick clean (format/lint/mypy --strict over polylogue+tests+devtools/render-all/topology). Ref polylogue-fs1.7. Co-Authored-By: Claude <[email protected]>
Problem: fs1.2 -- Hermes's observer-layer plugin (NeMo Relay) exports runtime span evidence (pre/post_api_request, pre/post_tool_call, approval, subagent, error hooks) that Polylogue has no origin contract for. Honesty constraint: the exact wire shape of Hermes's own ATOF JSONL/ATIF JSON export was not independently verifiable from this workspace (no local checkout of the Hermes observer-plugin source was available). The marker-based document shape and per-hook_type mapping in sources/parsers/hermes_spans.py are therefore a documented, testable, best-effort schema derived from the fs1.2 design notes and the shared lifecycle-event taxonomy (hermes_lifecycle.py) -- every fidelity capability tops out at "inferred", never "exact", for exactly this reason. Solution: - New marker-based detector/parser (HERMES_ATIF_TRACE_MARKER), wired into the same dispatch pipeline every other origin uses (detect_provider, lowering, parse_payload) and a new artifact-taxonomy classification. - pre/post_api_request -> hermes_llm_request_span; pre/post_tool_call -> hermes_tool_execution_span; approval_request/response -> hermes_decision_point; subagent_start/stop -> hermes_subagent_span; error -> hermes_error_taxonomy. An unrecognized hook_type becomes a generic hermes_observer_span event rather than being dropped or misclassified (ambiguous input handled deterministically, per AC). - Unpaired spans (a hook fired but its counterpart never arrived) are never silently dropped: they are counted and surfaced as an explicit degraded fidelity capability with a caveat. - Session correlation: spans land as their own observer-evidence session (observer:<hermes_session_id>) rather than being physically merged into the state-db-ingested conversational session's message tree -- that merge is a session-identity/lineage design decision (topology_edges / session_links) explicitly deferred, not silently assumed. Read-side correlation by the shared Hermes session id is available today via hermes_observer_session_id_for(). Verification: devtools test tests/unit/sources/parsers/test_hermes_spans.py -- covers detection, real dispatch-pipeline parsing (not a bespoke test-only call), idempotent/deterministic replay, unpaired-span visibility, ambiguous hook_type handling, and malformed-span skip-and-count behavior. Ref polylogue-fs1.2. Co-Authored-By: Claude <[email protected]>
… receipts Problem: fs1.11 shipped a minimal read-only Hermes recall leg (#2792: get_context_delivery API/MCP lookup over the existing context_deliveries ledger) but deferred auth/scheduler to polylogue-37t.11 (open, out of this cluster). The 2026-07-10 Nous follow-up refinement separately asked to "persist the context token budget and rendered-token estimate alongside the exact rendered-byte hash" and "correlate each delivery with the Hermes snapshot revision and the durable context-delivered event from fs1.7/fs1.2" -- fs1.7's spool (this branch, prior commits) is what that correlation needed and did not exist before now. Finding: token budget and rendered-token estimate were already persisted (context.compiler.context_snapshot_record_from_image writes metadata["max_tokens"]/metadata["token_estimate"]) -- no new write needed there, only exposure. The event-correlation half was genuinely missing. Solution: context/hermes_delivery_correlation.py is a read-side join, not a new write path or schema (consistent with fs1.11's own design directive to extend the existing ledger rather than create another manifest): a Hermes producer that injects a compiled context pack emits a context_injected lifecycle event (fs1.7's spool) whose payload carries the snapshot_ref it received; this module resolves that id against the existing context_deliveries receipt across the two durable tiers (source.db spool + user.db ledger). An event with no resolvable receipt renders an explicit available=False row with a caveat -- archive outage or a not-yet-committed write is visible, never silently skipped (fs1.11 AC). Wired onto the public facade as Polylogue.correlate_hermes_context_deliveries (added to BESPOKE_METHODS + a dedicated contract test, per the existing "every public async method is categorized" completeness gate). No new MCP tool: extending the MCP tool surface has ripple costs (EXPECTED_TOOL_NAMES, tool contracts, generated docs, and role-allowlist config that lives in the sinnix repo, not here) disproportionate to this pass; the API method is fully queryable/testable without it, and adding the MCP tool is a small, clean, separately-reviewable follow-up. Verification: devtools test tests/unit/context/test_hermes_delivery_correlation.py tests/unit/api/test_facade_contracts.py -k "hermes or context_delivery" -- 9 passed, including the exact-bytes-hash/token-budget/rendered-estimate correlation happy path, a missing-receipt caveat, and a malformed (no snapshot_ref) event caveat. Ref polylogue-fs1.11. Co-Authored-By: Claude <[email protected]>
…hema Problem: an adversarial review of PR #2876 found looks_like_atif_payload matched only a synthetic polylogue_artifact: "hermes_atif_trace" marker key invented by this repo's own marker_payload() test fixture -- it could never recognize a real, unmodified Hermes/NeMo Relay ATIF export. No Hermes source access was available when the original detector was written. What changed: the detector/parser now match the real, externally-published NVIDIA NeMo Relay ATIF-v1.7 trajectory schema -- confirmed field-for-field against docs.nvidia.com/nemo/relay, github.com/NVIDIA/NeMo-Relay, and the upstream hermes-agent-fork/plugins/observability/nemo_relay README (top-level schema_version/session_id/agent/steps/subagent_trajectories; step fields source/tool_calls/observation/message) before trusting the fix. Tool-call steps become tool execution spans, message-only steps become bounded LLM-response evidence (character length only, never the text itself), subagent_trajectories become delegation evidence. Unrecognized step shapes and malformed entries are counted and surfaced, never silently dropped or coerced into a known kind. Residual honesty gap, now smaller and disclosed prominently: no live- generated ATIF sample was available to confirm exact field semantics byte-for-byte, so import_fidelity_declaration() still caps every capability at "inferred", never "exact". This is now surfaced in docs/architecture.md's provider table (not only the module docstring) so the caveat is visible without reading source. Follow-up bead the prior notes flagged as "not yet created" is now filed: polylogue-fs1.2.1. Also fixes a real circular import (archive.artifact_taxonomy.runtime -> sources.parsers.hermes_spans -> sources/__init__ -> ... -> archive.artifact_taxonomy) introduced by the original module-level import, via the same deferred-import pattern already used elsewhere in this file for an equivalent cycle. And fixes two dead `is None` checks against json_document() (which returns `{}`, never `None`, on coercion failure) that mypy --strict flagged and that let a non-object step silently become a fabricated "unrecognized shape" event instead of being skipped-and-counted as the docstring already claimed. Verification: devtools test tests/unit/sources/parsers/test_hermes_spans.py -- 10 passed. mypy --strict polylogue/sources/parsers/hermes_spans.py polylogue/archive/artifact_taxonomy/runtime.py -- clean. Ref polylogue-segf. Co-Authored-By: Claude <[email protected]>
…g order-dependence Problem: an adversarial review of PR #2876 found reconcile_lifecycle_events unit-tested only against synthetic fixtures, unreachable from any production surface -- nothing read the durable raw_hook_events spool and the ingested session snapshot and fed them through it, so fs1.7's own AC ("an incomplete event stream is reconciled visibly against the session snapshot") was not actually true at the product level. What changed: new context/hermes_lifecycle_reconciliation.py is the read-side join over two durable tiers (source.db lifecycle spool, index.db ingested snapshot), mirroring the pattern context.hermes_delivery_correlation already established. Wired onto the public facade as Polylogue.reconcile_hermes_session_lifecycle (added to BESPOKE_METHODS + a dedicated facade contract test that drains real spool events against a real seeded index.db snapshot). Separately, the review asked for adversarial/malformed-shape fixture coverage rather than only the happy path -- doing that surfaced a real, previously-undetected bug in reconcile_lifecycle_events' own pairing algorithm: it processed events in temporal (observed_at_ms) order, so a finish event with an earlier timestamp than its start (clock skew, or a delayed-but-earlier-stamped delivery) was incorrectly reported as an unpaired gap, and a duplicate (redelivered) start marker for the same correlation id silently overwrote the earlier event id as the "open" pointer. Rewrote the pairing to be order-independent (correlation-id-set membership, not temporal scan) with first-occurrence-wins on duplicates -- backward compatible with every existing happy-path test. Four new adversarial tests cover out-of-order finish-before-start, duplicate start markers, duplicate on_session_finalize markers, and a genuine gap surviving alongside a duplicate/out-of-order pairing (proving the rewrite doesn't paper over real gaps). Also fixes the MINOR "corruption vs absence collapsed silently" finding on both Hermes facade read seams in api/archive.py (_archive_correlate_hermes_context_deliveries and the new _archive_reconcile_hermes_session_lifecycle): both caught (sqlite3.Error, ValueError) around the whole read and returned the same empty result whether the archive was simply not initialized yet or present but corrupted, with zero distinguishing signal. Both now log a warning specifically on the corruption path -- the empty-result contract to callers is unchanged (a larger, separate decision), but an operator/log scan can no longer confuse "nothing ingested yet" with "archive present but unreadable". Two new tests corrupt source.db directly and assert the warning fires only in that case. Verification: devtools test tests/unit/sources/parsers/test_hermes_lifecycle.py tests/unit/context/test_hermes_lifecycle_reconciliation.py -- 13 passed. devtools test tests/unit/api/test_facade_contracts.py -k hermes -- 6 passed. devtools render topology-projection && devtools render topology-status -- new module reflected. Ref polylogue-segf. Co-Authored-By: Claude <[email protected]>
…e drift Problem: an adversarial review of PR #2876 found two MINOR issues in sources/hooks.py: 1. _persist_record's origin lookup defaulted any unrecognized provider token to "codex-session" (_ORIGIN_TOKEN_BY_PROVIDER.get(provider_token, "codex-session")) instead of raising. _validated_record already rejects any provider outside _SUPPORTED_PROVIDERS before a record reaches this point, making the default dead code in the current call path -- but a future drift between _SUPPORTED_PROVIDERS and _ORIGIN_TOKEN_BY_PROVIDER (e.g. a provider added to one set but not the other) would have silently misclassified a genuinely-unknown provider as Codex. 2. _reject_duplicated_transcript's field-list/threshold policy is copied (not importable-shared) across three independent runtime boundaries: the main package, the standalone polylogue-hooks pip distribution (explicitly documented as having no dependency on the main polylogue package), and the dependency-free contrib/polylogue-hook bash script -- with zero drift protection beyond one fixed-value behavioral test per producer. What changed: (1) raises HookSpoolRecordError instead of defaulting, with a direct regression test that bypasses upstream validation to exercise the defense-in-depth path itself, independent of _validated_record ever being correct. (2) a single bash script and a deliberately dependency-free pip package cannot share a literal Python helper across that boundary without breaking the isolation that boundary exists for -- instead added a drift guard (test_transcript_duplication_policy_stays_in_sync_across_hook_producers) that cross-checks the literal keys/threshold across all three copies via subprocess introspection + source-text regex, so a future edit to one copy that forgets the other two fails loudly in CI instead of silently. Also adds a truncated/malformed-JSON-envelope-alongside-a-valid-event spool test (a crash-mid-write or producer-bug scenario the adversarial review asked for): confirms drain_hook_event_spool leaves the malformed file inspectable rather than crashing the batch, and still materializes the other valid pending event in the same pass. Verification: devtools test tests/unit/sources/test_hook_spool.py -- 23 passed. Ref polylogue-segf. Co-Authored-By: Claude <[email protected]>
Mechanical regeneration after rebasing the Hermes review-fix branch onto current master (topology projection is derived from the full module tree, not hand-edited). Co-Authored-By: Claude <[email protected]>
01a552c to
77efdfa
Compare
…cycle-spool-and-bridge # Conflicts: # docs/topology-status.md
|
| GitGuardian id | GitGuardian status | Secret | Commit | Filename | |
|---|---|---|---|---|---|
| 34803688 | Triggered | Generic High Entropy Secret | 529d2ef | tests/unit/security/test_secret_scan.py | View secret |
🛠 Guidelines to remediate hardcoded secrets
- Understand the implications of revoking this secret by investigating where it is used in your code.
- Replace and store your secret safely. Learn here the best practices.
- Revoke and rotate this secret.
- If possible, rewrite git history. Rewriting git history is not a trivial act. You might completely break other contributing developers' workflow and you risk accidentally deleting legitimate data.
To avoid such incidents in the future consider
- following these best practices for managing and storing secrets including API keys and other credentials
- install secret detection on pre-commit to catch secret before it leaves your machine and ease remediation.
🦉 GitGuardian detects secrets in your source code to help developers and security teams secure the modern development process. You are seeing this because you or someone else with access to this repository has authorized GitGuardian to scan your pull request.
Problem: rebasing feature/refactor/sqlite-leak-sweep-and-staleness-unify onto origin/master (which gained #2875/#2876/#2877 since this branch was cut) produced conflicts in the generated topology-target.yaml and topology-status.md artifacts. Both sides had regenerated these independently from source, so a manual merge would desync them from the actual module graph. What changed: resolved the conflicts with a placeholder (--ours), then ran `devtools render topology-projection && devtools render topology-status` to regenerate both files from the post-rebase source tree, matching this repo's documented policy for generated-surface conflicts. Verification: `devtools render all --check` reports no "out of sync" lines (all surfaces sync OK).
…enter decomposition (#2900) ## Summary Implements the Architecture cluster (polylogue-1r9c + a7xr features/bugs): a source-grounded hotspot map for Polylogue's largest execution control centers with a first coherent extraction slice landed against it, plus six real bugs/features from the a7xr substrate-consolidation set. ## Problem Production Python grew from ~255k to ~281k lines while the largest execution hubs (storage tier, API facade, daemon HTTP, write tier, storage repair) kept expanding faster than the codebase average, with no committed map of their call boundaries, ownership seams, or a prioritized decomposition sequence. Alongside that, a cluster of real substrate bugs and abstraction-audit findings (sqlite connection leaks, a converger/repair staleness disagreement, dead abstractions with zero production consumers, a hard-coded write-effects choke point) had accumulated as separately tracked beads. ## Solution **polylogue-1r9c** (`docs/architecture-hotspots.md`, new): maps all eight named control centers with file:line evidence, call-boundary/ownership-seam analysis, and a prioritized extraction sequence with explicit non-goals. Lands one coherent slice: `session_annotations_write.py` extracts the self-contained session tag/work-event/phase CRUD contract out of `storage/sqlite/archive_tiers/write.py` (4,595 → 4,210 lines, −8.4%), with `write.py` re-exporting the same public names unchanged (no duplicate execution path). Files seven durable child beads for the remaining seven control centers (`polylogue-redt`, `-u5dw`, `-1vzf`, `-gikp`, `-kchb`, `-avmq`, `-w9di`), each with an explicit non-goal. The layering-policy fix this required also corrected a pre-existing, now-exposed imprecision in `archive_tiers/archive.py`'s `raw-revision-authority` twin-write contract (a coarse tier-attribution artifact, not a behavior change). **polylogue-0aj** (write-effects registry, slice 1 of 2): `archive/write_effects.py`'s hard-coded FTS-repair/cache-invalidation branches become a declared `WriteEffect` registry (name, phase, should_run, failure_policy) that the choke point walks generically — behavior-identical for the three existing effects, with the phase/failure-policy declarations now explicit for future consumers (embedding scheduling, SSE announce) to register against. **polylogue-yp0** (daemon event bus, partial — honestly not fully closed): lands the typed in-process pub/sub core (`daemon/event_bus.py`, 5 event types, full failure-isolation test coverage) but not a live producer/consumer wiring — that's sequenced as follow-up (`polylogue-14t7`) per the bead's own design note, since touching a live daemon polling loop needs its own focused pass against the lock/starvation invariants `polylogue-9e5.7` mapped. **polylogue-c9y** (package-topology doctrine): `docs/architecture.md`'s placement rules become an 8-question decision procedure with worked examples, plus the insights-vs-analytics vocabulary rule recorded ahead of `analytics/` landing. `core/` absorbs the former top-level `errors.py`/ `protocols.py`/`types.py` (165 import sites updated, zero behavior change). **Prior-session work on this branch** (a7xr.1/.2/.10/.13/.14/.17, all committed before this PR turn but included here): sqlite connection-leak sweep across ~9 sites, unified `session_profile_stale_predicate` between converger and repair, killed the zero-consumer FTS5/Hybrid search-provider lane, deleted the api/contracts shadow-adapter layer, collapsed the one-operation operations-contract framework to concrete Import models, and added an import-resolution drift gate for operation/artifact catalog `code_refs`. **Discovered, filed, not fixed in this PR** (out of scope for this cluster, flagged rather than silently absorbed): `polylogue-0puw` (a stale `blob_publication_reservations` row survives an ingest batch that should drain it — confirmed pre-existing, reproduces with `write_effects.py` reverted), `polylogue-g99u` (`'codex' is not a valid Origin` ValueError in two facade contract tests — confirmed unrelated to the write-tier extraction, the extracted code never touches origin/provider resolution), and `polylogue-ihp0` (`test_fresh_user_tier_has_no_legacy_overlay_tables` asserts a stale exact table-set literal that migrations 007/008 — both merged well before this branch's own base commit — already invalidated; confirmed pre-existing via `git merge-base --is-ancestor`, unrelated to the `session_annotations_write.py` extraction which the dedicated write-tier suite proves behavior-identical, 63/63). **Rebase onto current `origin/master`** (post-review): this branch was 3 commits behind `origin/master` (missing #2875/#2876/#2877) when first opened, with GitHub reporting `mergeable: CONFLICTING`. Rebased cleanly; resolved a trivial resolve-both import-block conflict in `polylogue/api/archive.py` (this branch's `protocols.py`→`core/protocols.py` move landed on the same import line master's Hermes-delivery-correlation import touched) and regenerated the two generated-artifact conflicts (`docs/plans/topology-target.yaml`, `docs/topology-status.md`) via `devtools render topology-projection && devtools render topology-status` rather than merging them by hand. Also closed a self-consistency gap in `polylogue-a7xr.10`'s own acceptance criteria: its FTS5/Hybrid provider kill decision requires `polylogue-mhx.3` to record that it now owns lane construction now that the shared `SearchProvider` abstraction is gone — that note was missing and has been appended. ## Verification - `devtools verify --quick` green end to end (ruff format/check, `mypy --strict`, `render all --check` with zero "out of sync"/"unindexed" findings, topology/layering/closure-matrix/manifests/ci-workflows/doc-commands/ test-infra-currency/test-clock-hygiene/pytest-timeout-overrides/degrade-loudly all pass) — run repeatedly across the session, last clean at HEAD. - `devtools test tests/unit/archive/test_write_effects.py tests/unit/archive/test_write_gateway.py` — 12 passed (new registry tests + full existing gateway suite). - `devtools test tests/unit/storage/test_archive_tiers_write.py tests/unit/storage/test_archive_tiers_self_verify.py` — 64 passed (full behavioral parity for the write-tier extraction). - `devtools test tests/unit/storage/test_revision_replay.py` — 16 passed (covers `apply_raw_membership_classification`, the entrypoint whose layering contract was corrected). - `devtools test tests/unit/daemon/test_event_bus.py` — 10 passed (event bus pub/sub core, failure isolation, immutability). - `devtools render topology-projection && devtools render topology-status` regenerated for every new module (`session_annotations_write.py`, `daemon/event_bus.py`). - Three pre-existing, unrelated test failures found and filed as follow-ups rather than silently ignored (`polylogue-0puw`, `polylogue-g99u`, `polylogue-ihp0`) — all confirmed to reproduce independent of this PR's changes (`ihp0` additionally confirmed via `git merge-base --is-ancestor` to predate this branch's base commit). - Post-rebase re-verification: `devtools verify --quick` green again (39.76s, 15/15 steps); `devtools test` across the branch's new/touched test files (`test_write_effects.py`, `test_event_bus.py`, `test_session_profile_staleness_predicate.py`, `test_sqlite_connection_hygiene.py`, `test_code_refs_resolve.py`) — 232 passed; `tests/unit/storage/test_archive_tiers_write.py` — 63 passed (write-tier extraction behavioral parity, re-confirmed post-rebase). ## Not run Full `devtools verify --all` / broad directory test sweeps (per repo policy — testmon-affected/focused selection is the default, not blanket directory runs). Per-PR CI is disabled repo-wide (billing-locked). --------- Co-authored-by: Claude <[email protected]>
Summary
Implements the frontier of the Hermes bridge cluster as one coherent system: a durable local lifecycle-event spool (fs1.7), a NeMo Relay observer-trace importer that consumes the shared event taxonomy (fs1.2), and a read-side correlation between Hermes
context_injectedevents and the existing context-delivery ledger (fs1.11's Nous follow-up refinement). Also does small, real fixes to two standalone hook-producer scripts (contrib/polylogue-hook,packaging/polylogue-hooks) to speak the new Hermes vocabulary.Problem
Three separate but related gaps in
polylogue-fs1(Hermes bridge epic):state.dbschema.context_injectedevent — which didn't exist until this PR's fs1.7 work created it.Solution
fs1.7 —
polylogue/sources/hooks.pyalready had exactly the durable-spool machinery this needs (built for Claude Code/Codex); extended to acceptprovider="hermes"through the same atomic-enqueue/idempotent-drain contract, plus a payload hygiene guard (_reject_duplicated_transcript) so lifecycle events can never smuggle in a second copy of message text. Newsources/parsers/hermes_lifecycle.pyowns the event-type taxonomy (including the hardon_session_endvson_session_finalizedistinction) andreconcile_lifecycle_events(), which renders an incomplete event stream visible (unpaired events, events referencing unknown message ids) rather than silently accepting a gap. Newcontext/hermes_lifecycle_reconciliation.pyis the read-side join wiring that reconciliation to real archive tiers (source.dbspool +index.dbingested snapshot), exposed on the public facade asPolylogue.reconcile_hermes_session_lifecycle— see Review fixes below. Newschemas/hermes_export_contract.pydefines a versioned per-session export schema (HermesArchivalExportV1) with a checked-in fixture; an unrecognizedschema_versionfails loudly rather than being silently coerced.docs/design/hermes-archival-export-contract.mdis the full writeup, including an explicit, honest note that the upstream Hermes-repo commit is an external artifact this session could not author.fs1.2 —
sources/parsers/hermes_spans.py, wired into the real dispatch pipeline (detector → lowering → parser, same path every other origin uses). The detector/parser now match the real, externally-published NVIDIA NeMo Relay ATIF-v1.7 trajectory schema (schema_version/session_id/agent/steps/subagent_trajectories; step fieldssource/tool_calls/observation/message) — confirmed againstdocs.nvidia.com/nemo/relay,github.com/NVIDIA/NeMo-Relay, and the upstreamhermes-agent-fork/plugins/observability/nemo_relayplugin README, not invented. See Review fixes below for what changed and what's still unconfirmed. Tool-call steps → tool execution spans, message-only steps → LLM-response evidence,subagent_trajectories→ delegation evidence. Unrecognized step shapes and malformed entries are counted and surfaced as explicit fidelity capabilities, never silently dropped or fabricated into a known kind. Spans land as their own observer-evidence session (observer:<id>) rather than being physically merged into the state-db-ingested conversational session — that merge is a session-identity/lineage decision explicitly deferred, not silently assumed.fs1.11 —
context/hermes_delivery_correlation.pyis a read-side join (no new schema/write path, per the design's own "extend the ledger, don't create another manifest" directive): resolves a Hermescontext_injectedevent'ssnapshot_refagainst the existingcontext_deliveriesreceipt across the two durable tiers it bridges (source.db spool, user.db ledger). Acontext_injectedevent with no resolvable receipt renders an explicitavailable=False+ caveat rather than being silently skipped. Token budget and rendered-token estimate turned out to already be persisted (context_snapshot_record_from_image) — this just exposes them. Wired onto the public facade asPolylogue.correlate_hermes_context_deliveries(added to the completeness-gatedBESPOKE_METHODSset + a dedicated contract test). No new MCP tool in this pass — see Follow-ups.Review fixes (2026-07-14)
An independent adversarial review of the original diff found 5 real issues. All 5 are addressed on this branch:
looks_like_atif_payloadoriginally matched only a syntheticpolylogue_artifact: "hermes_atif_trace"marker key this repo's own test helper invented — it could never recognize a real Hermes/NeMo Relay export. Fixed: the detector/parser now match the real, published ATIF-v1.7 top-level shape (schema_versionprefixed"ATIF",session_id,steps) and step shape (source/tool_calls/observation/message), grounded in the external sources cited above (hermes_spans.pymodule docstring has the full citation list). Residual gap, now smaller and disclosed prominently (not just in code): no live-generated ATIF sample was available to confirm exact field semantics byte-for-byte, soimport_fidelity_declaration()still caps every capability atinferred, neverexact. This is now surfaced indocs/architecture.md's provider table (not only the module docstring), and the follow-up bead the original notes flagged as "not yet created" is now filed:polylogue-fs1.2.1.reconcile_lifecycle_eventswas unit-tested but nothing read the durable spool + ingested snapshot and fed them through it. Fixed: newcontext/hermes_lifecycle_reconciliation.pyis that read-side join, wired ontoPolylogue.reconcile_hermes_session_lifecycle(facade contract test drains real spool events against a real seeded snapshot). Separately,reconcile_lifecycle_events's pairing algorithm itself had a real, previously-undetected bug this review's adversarial-fixture requirement surfaced: it processed events in temporal (observed_at_ms) order, so a finish event with an earlier timestamp than its start (clock skew, or a delayed-but-earlier-stamped delivery) was incorrectly reported as an unpaired gap, and a duplicate (redelivered) start marker for the same correlation id silently overwrote the earlier event id. Fixed to be order-independent (membership-based pairing, first-occurrence-wins on duplicates) — 4 new adversarial tests cover out-of-order finish-before-start, duplicate start markers, duplicateon_session_finalizemarkers, and a genuine gap surviving alongside a duplicate/out-of-order pairing. Also added a truncated-JSON-envelope-alongside-a-valid-event spool test (crash-mid-write producer scenario)._TRANSCRIPT_LIKE_KEYS/_MAX_TRANSCRIPT_LIKE_FIELD_CHARSare genuinely copied (not importable-shared) across three independent runtime boundaries: the main package, the standalonepolylogue-hookspip distribution (explicitly dependency-free from the main package by design), and the dependency-freecontrib/polylogue-hookbash script — a single Python helper cannot span all three. Rather than force an architecturally-wrong shared import, added a drift-guard test (test_transcript_duplication_policy_stays_in_sync_across_hook_producers) that cross-checks the literal keys/threshold across all three copies, so future drift fails loudly instead of silently._persist_record's origin lookup defaulted any unrecognized provider token tocodex-sessioninstead of raising._validated_recordalready rejects unsupported providers upstream today, making this dead code in the current call path — but a future drift between_SUPPORTED_PROVIDERSand_ORIGIN_TOKEN_BY_PROVIDERwould have silently misclassified a genuinely-unknown provider as Codex. Fixed to raiseHookSpoolRecordErrorinstead, with a direct regression test that bypasses upstream validation to prove the defense-in-depth path itself._archive_correlate_hermes_context_deliveries/_archive_reconcile_hermes_session_lifecyclecaught(sqlite3.Error, ValueError)around the whole read and returned the same empty result as "archive not initialized yet," with zero distinguishing signal. Both now log a warning (hermes_context_deliveries read failed/hermes_session_lifecycle reconciliation read failed) specifically on the corruption path, leaving the not-yet-initialized path silent — the empty-result contract is unchanged (a larger, separate decision), but the two cases are no longer indistinguishable to an operator/log scan. Two new tests corruptsource.dbdirectly and assert the warning fires only in that case.A real circular import (
archive.artifact_taxonomy.runtime→sources.parsers.hermes_spans→sources/__init__→ ... →archive.artifact_taxonomy) and 4 mypy--stricterrors (two deadis Nonechecks againstjson_document(), which always returns{}rather thanNone— fixed tonot step/not tool_call/not subagent, which also fixed a real bug where a non-object step was silently coerced into a fabricated "unrecognized shape" event instead of being skipped-and-counted as the docstring already claimed) were found and fixed while restoringdevtools verify --quickto green.Verification
devtools test tests/unit/sources/test_hook_spool.py tests/unit/sources/test_hermes_export_contract.py tests/unit/sources/parsers/test_hermes_lifecycle.py tests/unit/sources/parsers/test_hermes_spans.py tests/unit/context/test_hermes_delivery_correlation.py tests/unit/context/test_hermes_lifecycle_reconciliation.py— 50 passed.devtools test tests/unit/api/test_facade_contracts.py(full file, not just-k hermes) — 326 passed, 6 pre-existing failures (ValueError: 'codex' is not a valid Origin×5, onesqlite3.OperationalError: trigger ... already exists), all confirmed viagit stashto reproduce identically before this review-fix work, unrelated to Hermes.devtools verify --quick— exit 0 (ruff format, ruff check,mypy --strict,render all --check, topology/layering/closure-matrix/lab-schema-roundtrip/manifests/ci-workflows/doc-commands/test-infra-currency/test-clock-hygiene/pytest-timeout-overrides/degrade-loudly).docs.nvidia.com/nemo/relay,github.com/NVIDIA/NeMo-Relay,raw.githubusercontent.com/HexLab98/hermes-agent-fork/.../nemo_relay/README.md) before trusting the citation, not taken on faith from the diff.Scope notes for the rest of the Hermes-bridge cluster
This PR covers fs1.7, fs1.2, and the fs1.11 extension. The remaining assigned beads in this cluster (fs1.4, fs1.5, fs1.8, fs1.10, fs1.13, ox0) are not in this PR — each has a bead comment explaining why (composition-already-covers-it, external precondition unmet, blocked on out-of-cluster open beads, or a permission-system denial). Summary:
compile_postmortem_bundle(topology/economy/tool-profile/failure-patterns, origin-agnostic, zero Hermes-specific branches) andinsights/session_commit.py(local causal footprint). The one real gap is a named regeneration surface (CLI/read --view) and the claim-vs-evidence ledger the bead's own notes say to reuse rather than reinvent (doesn't exist yet). Left as a bead comment with the concrete composition map rather than building a redundant data path.chat.nousresearch.comredirects tohermes-agent.nousresearch.com, a static marketing page for a CLI tool with no chat DOM at all. The bead's own precondition ("when Nous Chat web usage starts") does not hold yet; fabricating CSS selectors against a nonexistent product would be fiction, not an adapter.polylogue-37t.10andpolylogue-7aw, both open and not in this cluster — genuinely blocked.~/.codex/state_5.sqlite/goals_1.sqlitewas denied by the auto-mode permission classifier as out-of-scope credential exploration; per instructions I did not attempt to route around that denial. Only the top-level table names (already visible before the denial) are recorded.Follow-ups
get_hermes_context_delivery_correlation-style MCP tool overcorrelate_hermes_context_deliveries(small, clean, needsEXPECTED_TOOL_NAMES+ tool-contract + docs regen). Same forreconcile_hermes_session_lifecycle.polylogue-fs1.2.1(filed): re-verify the ATIF wire shape against a real Hermes-generated export once a live Hermes/NeMo-Relay checkout is available, and tighten fidelity frominferredtoexactwherever confirmed.