Repository navigation
feat(query): bind query_units continuations to the archive epoch - #3068
Conversation
Problem: an external "phase-one QueryTransaction kernel" handoff (polylogue-z9gh.9) claimed to introduce archive-epoch-bound, serialization-budget-exact continuations against a stale base commit. Reconciling it against current master found the claimed kernel already landed via PR #2964 (execution_control.py) and PR #3018 (archive/query/transaction.py's QueryTransaction/QueryContinuation/ QueryResultPage) — the handoff's patch failed `git apply --check` on every file it touched, and its execution-control primitives duplicated a more mature admission/cancellation layer already on master. One real gap remained: query_units continuations carry no archive-frame identity, so a continuation issued before a session was written/mutated would resume against a moved relation with plain offset pagination — exactly the duplicate/skip risk polylogue-z9gh.9 AC #5 calls out ("enumerate each row exactly once against a declared archive epoch"). Solution: add `archive_index_epoch()` (schema version + session count/rowid/watermark — stronger than production_evaluator.py's existing watermark-only `_index_epoch`, which misses a session admitted before its `updated_at_ms` backfill), bind it into `QueryTransactionRequest.archive_epoch` and the epoch-aware `result_ref` property, and thread it through `QueryContinuation` encode/decode. `validate_continuation_epoch()` rejects a drifted continuation with a new `QueryContinuationStaleError` (`query_continuation_stale`), wired into the MCP `query_units` tool's resume path. A continuation with an empty (legacy/unframed) epoch is never rejected, so this lands without invalidating anything already issued. Unified the three near-identical `QueryTransactionRequest` construction blocks (API `Polylogue.query_units`, MCP `query_units` tool, daemon HTTP `/api/query-units`) behind one `query_units_transaction_request()` constructor so epoch-binding lands in one place instead of three independently-maintained call sites (the #2472/#2470 partitioning-bug shape). Also fixed a real inconsistency this surfaced: `QueryTransaction.__init__`'s own `result_ref` computation (hash of query_ref+projection+stable_order) diverged from `unit_results.query_unit_envelope`'s (a bare query_ref prefix swap, ignoring projection/stable_order entirely) — both now delegate to the same `QueryTransactionRequest.result_ref` property. Deferred: HTTP's `/api/query-units` does not accept a `continuation` query parameter at all (no resume path exists there today), so this PR only ensures its issued continuations carry the current epoch; wiring HTTP resume is separate, larger scope, noted in polylogue-z9gh.9. Verification: - devtools test tests/unit/archive/query/test_transaction.py tests/unit/mcp/test_server_surfaces.py -> 94 passed - devtools test tests/unit/archive/query/ tests/unit/api/test_facade_contracts.py tests/unit/daemon/test_web_reader.py -> 566 passed, 6 failed; the same 6 fail identically against unmodified master (verified via git stash), classified pre-existing/unrelated (an "unable to open database file" resource-contention shape plus one owner_ref-naming mismatch predating this change) - python3 -m mypy polylogue --strict -> Success: no issues found in 1031 source files - devtools verify --quick -> exit_code 0 - devtools render all --check -> OK (no new module added; topology projection unaffected) - Anti-vacuity: removing the `validate_continuation_epoch` call site in server_tools.py makes test_query_units_tool_rejects_continuation_after_archive_epoch_drift fail (confirmed, then restored) Ref polylogue-z9gh.9 Co-Authored-By: Claude <[email protected]>
|
Important Review skippedToo many files! This PR contains 158 files, which is 58 over the limit of 100. To get a review, narrow the scope: Upgrade to a paid plan to raise the limit. ⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: ⛔ Files ignored due to path filters (9)
📒 Files selected for processing (158)
You can disable this status message by setting the Use the checkbox below for a quick retry:
📝 WalkthroughWalkthroughQuery-unit transaction requests now bind result identities and continuation tokens to the archive index epoch. Shared request construction is used across API, HTTP, and MCP paths, with stale continuation validation and coverage for index changes and archive drift. ChangesQuery epoch binding
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant MCP query_units
participant query_units_transaction_request
participant index.db
participant QueryTransaction
MCP query_units->>query_units_transaction_request: build epoch-bound request
query_units_transaction_request->>index.db: read archive index epoch
index.db-->>query_units_transaction_request: archive_epoch
query_units_transaction_request-->>QueryTransaction: QueryTransactionRequest
QueryTransaction-->>MCP query_units: result and epoch-bound continuation
Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ 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: 8898356aca
ℹ️ 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".
Retain the epoch-bound continuation contract while preserving the merged malformed-token regression coverage.
There was a problem hiding this comment.
Actionable comments posted: 6
🤖 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/query/transaction.py`:
- Around line 159-182: Defer archive epoch binding in
query_units_transaction_request until the archive read transaction is opened,
and obtain it through that transaction’s SQLite connection so the epoch matches
the result-row snapshot. In polylogue/archive/query/transaction.py lines
159-182, remove the separate archive_index_epoch(Path(archive_root) /
"index.db") probe and pass or capture the connection-derived epoch; in
polylogue/archive/query/unit_results.py lines 520-540, use the epoch captured by
the row query instead of probing index.db after execution.
- Around line 71-75: Update the archive epoch calculation in the transaction
method containing the sessions COUNT/MAX query so it includes a generation value
that changes on every relevant session mutation, rather than relying only on
MAX(updated_at_ms). Maintain the existing epoch format and ensure the generation
is updated transactionally for inserts, updates, and deletes so any mutation
invalidates continuations.
- Around line 193-197: Update continuation-token versioning and validation so
newly issued q1 tokens require a present archive epoch. Grant the empty
archive_epoch legacy bypass only when the decoded token explicitly uses the old
token version; do not infer legacy status from an empty or removed field. Apply
this consistently across the related validation paths.
In `@polylogue/archive/query/unit_results.py`:
- Around line 529-544: Replace the manual fallback construction in the
query-unit result flow with the shared query_units_transaction_request builder,
preserving the existing request, pagination, and archive-epoch inputs. Ensure
the builder’s "terminal-unit-envelope" projection is used so direct-storage and
adapter calls produce the same canonical result_ref; keep the operation
validation and result_ref handling unchanged.
In `@polylogue/daemon/http.py`:
- Around line 3753-3761: Update the HTTP handler around the continuation replay
logic to call validate_continuation_epoch before resuming pagination, applying
the same stale-continuation response handling used by the MCP path. Correct the
adjacent comment to state that the route accepts and replays the continuation
query parameter, and remove the inaccurate follow-on-scope claim.
In `@polylogue/mcp/server_tools.py`:
- Around line 325-328: Update the continuation validation flow around
validate_continuation_epoch to distinguish an unreadable live archive epoch (the
index:unknown result caused by SQLite errors) from genuine archive drift. Return
a retryable archive-read error through hooks.error_json with the appropriate
archive-read code and tool context, while preserving query_continuation_stale
for actual epoch mismatches.
🪄 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: 6d6e2ca1-0635-4662-8395-de6307954236
📒 Files selected for processing (7)
polylogue/api/archive.pypolylogue/archive/query/transaction.pypolylogue/archive/query/unit_results.pypolylogue/daemon/http.pypolylogue/mcp/server_tools.pytests/unit/archive/query/test_transaction.pytests/unit/mcp/test_server_surfaces.py
Problem The previous index-only probe raced the reader snapshot and missed user-tier assertion mutations plus many relation rewrites that retain timestamps. What changed Compose a durable index-and-user archive frame from trigger-maintained relation epochs inside the result reader snapshot. Require frames for new continuation tokens, retain an explicit q1 compatibility path, and make unit envelopes, MCP, and HTTP consume the same canonical request identity. Compatibility/migration Index tier v40 rebuilds with relation-frame triggers. User tier v10 is an additive migration that adds its assertion-frame state and triggers. Co-Authored-By: Codex <[email protected]>
Reconcile parser-truthful query discovery with snapshot-bound query-unit continuations.\n\nThe shared transaction module keeps v2 archive-frame tokens, including user-tier\nvalidation, and exports the discovery result-semantics contract used by the\nparser-backed capability surfaces. Regenerate the topology projection. Co-Authored-By: Codex <[email protected]>
…nt kit (#3061) ## Summary Adds `polylogue.agent_integration`: a typed spec, generated manual/deep-reference/manifest/recipes assets, a native installer for Claude Code/Codex/Gemini/Hermes, a role-scoped runtime manifest, a `polylogue agent` CLI, and a Home Manager module. ## Problem The consumer-owned skill/SessionStart text agents currently see is stale, reports the wrong tool surface, and has no generated, verified, drift-checked path from the actual MCP declarations to what an agent is taught. Ref polylogue-3gd.2, polylogue-3gd.3. ## Solution The manual/reference are generated from the existing 104-tool declaration registry (`t46.8.1`, landed in #3004) and stage the target six-tool contract (`query`/`read`/`get`/`explain`/`context`/`status` + `write`/`judge`/`run`/`operate`) without claiming the cutover has landed — installation and instruction injection fail closed until exact role-scoped tool names and a `live-verified` schema marker both exist. Retains the beads-06 native installer architecture (managed MCP entries, idempotent upgrade, drift detection, lossless uninstall) rather than forking it. **External provenance:** recovered GPT Pro result package `mcp-01-agent-manual-r01.zip`, SHA-256 verified against snapshot commit `536a53efac0cbe4a2473ad379e4db49ef3fce74d`. The patch applied cleanly except the two generated topology files, which were regenerated locally (`devtools render topology-projection && devtools render topology-status`) rather than patched. Fixed post-apply: missing `-f`/`--format` short-flag aliases on all 6 new `agent` subcommands, a redundant `cast` flagged by mypy, and 5 undocumented CLI surfaces caught by `devtools verify docs-coverage` (added a CLI-commands section to the generated standing manual generator). ## Not claimed This is the installer/manual foundation, not the six-tool cutover itself: no compatibility tool is removed, FastMCP signatures are not yet `live-verified`, and instruction injection stays staged until `t46.8.2`/`t46.8.3` land the real read/context/judgment migration. ## Verification - `devtools test tests/unit/agent_integration/ tests/unit/mcp/test_server_surfaces.py tests/unit/cli/` — 2731 passed, 1 skipped. The 11 remaining failures are pre-existing on unpatched master (confirmed by rerunning them there): `read_timeout` TypeError in `test_diagnostics.py`/`test_json_output.py`, schema-version snapshot drift (37→39) in `test_plain_cli_snapshots.py`, and a `source_debt is locked` sqlite contention in `test_insights.py` — none related to this change. - `devtools verify --quick` — 16/16 steps passed (format, lint, mypy, render-all, topology, layering, closure-matrix, docs-coverage, manifests, ci-workflows, doc-commands, test-infra-currency, test-clock-hygiene, pytest-timeout-overrides, degrade-loudly). 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude <[email protected]>
…candidates (#3057) ## Summary Repairs resume-candidate file-overlap scoring so that historical paths which no longer resolve under the current checkout layout (after a refactor/rename) no longer poison exact-path Jaccard, while still not counting still-dead paths in the union denominator. Adds an offline hit@1/hit@3/MRR ranking evaluator with a versioned, lineage-grounded fixture. ## Problem Bead `polylogue-v1vo` found, from a live-archive analysis, that resume ranking's file-overlap component computes lexical exact-path Jaccard over raw `file_paths_touched`. On the live archive, 43% of historical file touches no longer exist under the current repo layout (e.g. `storage/repository.py` -> `storage/repository/__init__.py`), so a session that is a true refactor ancestor of the caller's current work scores near-zero overlap and gets anti-selected below unrelated sessions. Additionally, a candidate with extra dead paths in its touch set gets a larger union denominator than an otherwise-identical candidate, so it scores *lower* purely for having more (dead) history recorded — the opposite of what should happen. ## Solution - `polylogue/insights/resume.py`: adds a per-ranking-call `_PathResolutionContext` that resolves the caller's repo root once and caches filesystem existence checks. Candidate paths are partitioned into resolvable (exact current-checkout match, or file-to-package correction when a missing `foo.py` resolves to `foo/__init__.py`) vs. dead. Dead candidate paths are matched one-to-one against not-yet-matched recent caller files by deepest-prefix, root-rejecting parent-directory continuity (`_directory_overlap_pairs`). The Jaccard denominator becomes `caller identities ∪ resolvable candidate identities` — still-dead paths never enter the union. Falls back to the previous lexical behavior when no valid repo root is available. - Result is exposed additively via `ResumeCandidate.overlap_basis` (`exact` / `dir` / `dead_excluded`); `score_breakdown.file_overlap` keeps its existing float contract and the `0.25` weight is unchanged. - Threaded through consumers: `Polylogue.resume_brief` (optional `repo_path`/`recent_files`), MCP `get_resume_brief`, CLI `continue --candidates` (JSON + terminal), and the SessionStart context preamble (via a typed `ContextPreambleOverlapBasis` projection crossing the surface boundary through `model_dump`/`model_validate`, not a direct insights import). - `RESUME_BRIEF_MATERIALIZER_VERSION` bumped `1 -> 2` (additive optional field). - No schema/migration touched; no stored profile rewritten — adaptation happens at query time only. - `devtools/resume_ranking_eval.py` + `tests/data/resume-ranking-eval-v1.json`: durable offline evaluator comparing `legacy` vs `refactor-aware` scoring over lineage-derived ground truth (no hand-authored relevance labels). This patch originated as an externally-generated (GPT Pro) packet against bead `polylogue-v1vo`. It was independently re-verified against current `master` in this session (not merely re-run per its own claimed HANDOFF/TESTS docs) before being committed here. ## Verification - `devtools test tests/unit/core/test_resume.py tests/unit/devtools/test_resume_ranking_eval.py tests/unit/mcp/test_contract_evidence.py tests/unit/mcp/test_compose_context_preamble.py tests/unit/mcp/test_server_surfaces.py tests/unit/cli/test_continue_absorption.py` → `154 passed in 23.06s`. - Anti-vacuity: neutered `_directory_overlap_pairs` to unconditionally `return ()` (disabling directory recovery), reran the core/evaluator tests → `5 failed, 13 passed`, including `test_resume_candidates_recover_100_percent_dead_session_by_directory` (`assert 0.0 > 0`) and the evaluator's own partition invariant (`recovered=0` vs expected 254/430). Reverted the neutering and confirmed the file is byte-identical to the pre-mutation patched state (`diff` clean) before rerunning → `18 passed in 11.14s`. - `devtools render all --check` → exit 0, no `out of sync` lines (grepped the full log per the repo's documented gotcha). - `uv run --frozen mypy` on all 9 changed production/evaluator modules → `Success: no issues found in 9 source files`. - `devtools test tests/unit/mcp/test_tool_declarations.py tests/unit/mcp/test_tool_discovery.py tests/unit/mcp/test_server_surfaces.py tests/unit/mcp/test_query_tool_schema_derivation.py tests/unit/cli/test_cli_output_schemas.py` → `1 failed, 206 passed`. The one failure (`test_target_algebra_preserves_semantic_dimensions_without_self_authorizing`, an 8-vs-9 `TARGET_RESOURCES` count assertion) is pre-existing drift unrelated to this patch — confirmed by diffing `polylogue/mcp/declarations/registry.py` against `origin/master`, which shows only a `get_resume_brief` tool-description string change, nothing touching `TARGET_RESOURCES`. - `uv run --frozen python -m devtools.resume_ranking_eval` reproduces the claimed fixture metrics exactly: overall hit@1 `20.0% -> 100.0%`, MRR `0.390 -> 1.000`; seeded 1,000-path evidence sample `57.0% -> 82.4%` usable, `254/430` (59.1%) dead-path directory recovery. - `git push` ran the pre-push `devtools verify --quick` gate: all 16 steps passed (ruff format/check, mypy, render all, topology/layering/closure-matrix, schema roundtrip, manifests, ci-workflows, doc-commands, docs-coverage, test-infra-currency, test-clock-hygiene, pytest-timeout-overrides, degrade-loudly). **Not run**: replay against the live 4,264-session/27,785-touch archive (unavailable in this environment — the `57% -> 82%` improvement is a seeded/fixture reproduction of the bead's reported proportions, not an independent live-corpus rerun); full non-quick `devtools verify --all`. Ref polylogue-v1vo Co-authored-by: Claude <[email protected]>
## Summary
Modern Codex Code Mode wraps nested tool operations (`exec_command`,
`apply_patch`, `write_stdin`, `update_plan`, `wait`, web search, image,
MCP resource calls) inside a JavaScript envelope that is itself the
argument to an outer `exec`/`functions.exec` `function_call`. Polylogue
previously only saw the outer transport call, so a session full of
nested Code Mode calls produced zero normalized file paths and zero
structured outcomes on the child operations even when the child results
carried real structured outcomes.
## Problem
In a 100-session live sample cited on the tracking bead, every session
had nested `tools.*` calls: 14,004 envelopes held child operations and
19,180 results yielded zero structured paths/outcomes, although 1,444 of
those result texts *textually* contained `exit_code` — Polylogue had no
way to see any of that structure because it only parsed the outer
transport call.
## Solution
- `polylogue/sources/parsers/codex.py`: a conservative JS-literal
scanner
(`_JsLiteralParser` + `_scan_code_mode_child_calls`) walks
`tools.*`/`functions.*` member-call syntax in the Code Mode source
string without ever evaluating JavaScript. It recognizes a typed
registry of child kinds (`exec_command`, `apply_patch`, `write_stdin`,
`update_plan`, `wait`, `web`, `image`, `mcp`, `unknown`). Unparseable or
dynamic arguments are retained as raw evidence with
`parse_state="malformed"` rather than guessed. Each child call/result
is lowered into an ordinary `tool_use`/`tool_result` block pair with a
deterministic `tool_id` (`<transport_tool_id>::polylogue-child::<n>`),
transport-linked via a `_polylogue` provenance object on `tool_input`.
**Outcome fields (`is_error`/`exit_code`) are populated only from
structural JSON fields** (top-level or nested under
`metadata`/`result`/`output`) — free text containing `"exit_code=N"` is
never promoted to a structural outcome. Repeated calls sharing one
transport `tool_id` pair deterministically by occurrence rank (Nth use
to Nth result), including when a result record precedes its call in
the stream — no recovery/guessing is invented.
- `polylogue/archive/viewport/tools.py`: adds `apply_patch` to
`FILE_EDIT` and `wait` to the Codex agent-tool alias set so the new
child tool names classify correctly on query/facet surfaces.
- `devtools/codex_exec_child_census.py` (new): a reporting-only script
that counts transport vs. typed-child actions, paired/orphaned
results, path and structured-outcome coverage, plus an explicit
outer-transport-only counterfactual baseline, over one or more Codex
session files.
- New fixtures
`tests/data/codex_event_stream/functions_exec_{single,multiple}.jsonl`:
the `multiple` fixture spans every registry type plus one unknown and
one malformed call, and includes two results whose free text contains
`"exit_code=7"`/`"exit_code=9"` that must **not** be promoted.
- `tests/unit/sources/test_codex_event_stream_contract.py`
(`TestFunctionsExecLowering`): pins per-fixture lowering, repeated/
out-of-order `call_id` pairing (exercised against the production
`action_pairs` SQL, not a test-local reimplementation), structured-vs-
prose outcome handling, and asserts `session_content_hash` differs
between the lowered projection and an outer-only projection of the
same parsed session.
- `tests/unit/cli/test_query_expression.py` and
`tests/unit/sources/test_tool_aliases.py` gain coverage for the new
child action names/categories.
## Compatibility / migration notes
This adds new `tool_use`/`tool_result` blocks to existing Codex sessions
that use `functions.exec`/`exec` with nested Code Mode calls. **Session
content hashes for those sessions will change** — this is asserted
directly by
`TestFunctionsExecLowering.test_lowered_blocks_change_semantic_content_hash`
—
so the next `polylogued run` / reprocess will re-parse and
re-materialize
affected sessions (expected, not a regression).
No `source.db`/`user.db` migration and no `index.db` schema version
bump: `polylogue/storage/sqlite/action_pairs.py` is unmodified by this
PR — it already pairs `tool_use`/`tool_result` rows per
`(session_id, tool_id)` via `ROW_NUMBER()`, so the new deterministic
child `tool_id` scheme (`<transport>::polylogue-child::<n>`) is paired
by the existing relation with zero new DDL.
## Verification
```
devtools test tests/unit/sources/test_codex_event_stream_contract.py \
tests/unit/sources/test_tool_aliases.py \
tests/unit/devtools/test_codex_exec_child_census.py \
tests/unit/cli/test_query_expression.py
-> 458 passed, 1 skipped
python -m devtools.codex_exec_child_census \
tests/data/codex_event_stream/functions_exec_single.jsonl \
tests/data/codex_event_stream/functions_exec_multiple.jsonl
-> transport_actions=2, typed_child_actions=11, paired_child_results=11,
child_actions_with_path=3, child_results_with_structured_outcome=3
devtools verify --quick -> exit 0 (ruff format, ruff check, mypy --strict, render all --check)
devtools render all --check -> no drift (no polylogue/ module was added; devtools/ is outside the topology projection's tracked tree)
```
Anti-vacuity: temporarily forcing `_code_mode_exec_envelopes()` to
return
`{}` (disabling child lowering entirely, i.e. the historical outer-only
behavior) makes all 9 lowering-dependent tests fail, including the
content-hash test and the census test — confirming the tests actually
exercise the new lowering path rather than passing vacuously. Reverted
after confirming the failure; suite is green again.
Ref polylogue-j2zz
Co-authored-by: Claude <[email protected]>
…3067) ## Summary Replaces four divergent embedding-freshness selectors (per-source convergence, daemon bulk backlog, manual `embed` backfill, and preflight) with one shared exact-key predicate driven by a new storage-neutral `DerivationKey` value shape, and makes success/error/resolution writes conditionally scoped to the exact generation/key they were issued for — closing the terminal-write race that could clobber a newer config-change mark with an older attempt's outcome. ## Problem `polylogue-hash-boundary` census (polylogue-9e5.6) found that only one of four production embedding-selection call sites compared `message_embeddings_meta.content_hash` against current message content; the other three (`_drain_archive_embedding_backlog_once`, `_run_archive_backfill`, `_select_archive_pending_window`) passed `include_stale_checks=False` and trusted a `needs_reindex` flag alone. Separately, `mark_session_embedding_error` unconditionally cleared `needs_reindex` on a non-retryable terminal error, which could clobber a concurrent config-change bulk-mark that landed mid-flight (the same race class already fixed for the success path in polylogue-y337, but left open on the error path — polylogue-iqd3). polylogue-0k6's same-ID/same-count changed-text staleness gap is the content-generation instance of the same underlying defect: selection and terminal writes did not consume one monotonic freshness generation. ## Solution - New `polylogue/storage/derivation_identity.py`: a storage-neutral `DerivationKey`/`DerivationIdentity`/`DerivationSubject` value/protocol type (subject + exact source identity + computational recipe identity + output contract, SHA-256 digested with domain separators). Deliberately excludes attempt generation, producer/resource data, eligibility/privacy, retryability, and result hashes — those remain domain-owned. No universal derivation table or lifecycle was added. - New `polylogue/storage/embeddings/identity.py`: maps embeddings onto that shape. `EmbeddingRecipe` declares all twelve computational fields from polylogue-303r.7 (canonicalization, record selector, chunking version, provider, model, model revision, dimensions, task, input type, normalization, tool implementation, input/schema version); changing any one produces a different `recipe_hash`. - `_archive_embedding_freshness_predicate()` in `materialization.py` is now the sole v3 freshness classification (fresh / blocked / pending), consumed identically by all four production call sites: - `polylogue/daemon/convergence_stages.py::_archive_pending_embedding_session_ids` (also fixes config reconciliation, which previously ran against `index.db` even though embedding state lives in the sibling `embeddings.db` — now `_reconcile_archive_embedding_config_change` targets the correct file) - `polylogue/daemon/embedding_backlog.py::_drain_archive_embedding_backlog_once` - `polylogue/cli/commands/embed.py::_run_archive_backfill` - `polylogue/storage/embeddings/preflight.py::_select_archive_pending_window` The `include_stale_checks` bypass parameter is removed entirely (zero production references remain). - `polylogue/storage/sqlite/archive_tiers/embedding_write.py`: `complete_embedding_attempt_success` and `record_embedding_failure`/`mark_session_embedding_error` now validate and commit inside one transaction guarded by `WHERE session_id = ? AND generation = ? AND derivation_key = ? AND attempt_state = 'pending'`; a stale attempt's write touches zero rows and is recorded only as `superseded` evidence. `resolve_embedding_failure` applies the same generation/key scoping so a late acknowledgement of an old failure cannot clear a newer pending mark. - `EMBEDDINGS_SCHEMA_VERSION` 2 -> 3 in the canonical DDL (`embedding_derivation_state`, extended `message_embeddings_meta`/`embedding_failures`, new index). No migration chain — per repo doctrine `embeddings.db` is a rebuildable-but-expensive tier; the change edits canonical DDL directly, and `docs/schema.md` is updated to document it. ## Verification - `devtools test tests/unit/storage/test_embedding_freshness_invariant.py tests/unit/storage/test_embedding_contracts.py tests/unit/storage/test_embedding_orphan_reconcile.py tests/unit/cli/test_embed_status_fast.py tests/unit/daemon/test_embedding_convergence_progress.py` -> `119 passed`. - Anti-vacuity (both reverted after confirming, no residual diff): - Removed `task` from `EmbeddingRecipe.identity()`'s field mapping -> the 12-field parametrized mutation test failed exactly `[task-changed-task]`, all 11 others stayed green. - Removed the `generation`/`derivation_key` WHERE guard from `record_embedding_failure`'s conditional UPDATE -> `test_config_change_then_old_terminal_error_cannot_clear_new_generation` failed (`assert 'failed_terminal' == 'pending'`), proving the guard is load-bearing against the exact race polylogue-iqd3/wmsc target. - `devtools verify --quick` -> clean (ruff format, ruff check, mypy --strict, render-all-check, layering, degrade-loudly, manifests, ci-workflows, doc-commands, docs-coverage, test-infra-currency, test-clock-hygiene, pytest-timeout-overrides all `ok`, `exit_code: 0`). - Fixed real defects found by the above gates before this could be considered mergeable (see below). - `devtools render topology-projection && devtools render topology-status` regenerated for the two new files (`polylogue/storage/derivation_identity.py`, `polylogue/storage/embeddings/identity.py`); `devtools render all --check` passes clean (no "out of sync"). - Broader regression sweep across ~22 embedding/daemon/CLI-adjacent test files: 636 passed, 1 pre-existing unrelated failure (`test_web_reader.py::...redact_configured_archive_paths`, an `sqlite3.OperationalError: unable to open database file` reproduced identically on unpatched `origin/master`). ### Defects found and fixed during independent verification (not present in the original external patch) - `mypy --strict` found 13 errors across 5 files, including one real bug: `_archive_embedding_session_state_exact_with_timeout` returned a 2-tuple `(0, 0)` on a missing-table `OperationalError` from a function typed (and unpacked at its call site into three variables) as `tuple[int, int, int] | None` -- a guaranteed `ValueError: not enough values to unpack` at runtime on that path. Fixed to `(0, 0, 0)`. The remaining errors were narrow stub-typing gaps (sqlite3's `_AggregateProtocol.step` stub only models single-int-arg aggregates; several `object`/`bytes` narrowing sites) and test-only typing, fixed with narrow casts/ignores or proper `isinstance` narrowing. - `ruff format` needed 4 files reformatted. - `devtools verify layering` failed: the new public writer entrypoints `begin_embedding_attempt`, `supersede_embedding_attempt`, `complete_embedding_attempt_success` were added to `embedding_write.py` without updating its declared entrypoint list in `docs/plans/layering.yaml`. Fixed. - `devtools verify degrade-loudly` failed: the new `_qualified_table_columns` helper repeats the existing narrow-schema-probe `except sqlite3.Error` pattern of its sibling `_table_columns`/`_qualified_table_exists` (both already allowlisted) but had no allowlist entry of its own. Added one with the same rationale. ## Migration notes **BREAKING CHANGE (schema, operator-actionable, not automatic):** `EMBEDDINGS_SCHEMA_VERSION` moves from 2 to 3. Per repo doctrine, `embeddings.db` is a rebuildable-but-expensive derived tier with **no migration chain** -- this is a canonical-DDL edit, not an in-place `ALTER`/migration script (`git diff origin/master -- polylogue/storage/sqlite/migrations/` is empty). Verified this is **not** a silent auto-rebuild hazard: `initialize_archive_database` (`polylogue/storage/sqlite/archive_tiers/bootstrap.py`, unchanged by this PR) raises `RuntimeError("... schema version 2 is not the current embeddings tier version 3; move it aside and rebuild the archive root")` for an existing v2 file, because `ArchiveTier.EMBEDDINGS` is not in `DURABLE_MIGRATION_TIERS`. The daemon's periodic embedding-backlog check catches this as a logged warning and retries every 60s rather than deleting/reinitializing anything -- an operator must explicitly move `embeddings.db`/`-wal`/`-shm` aside before the tier is rebuilt via fresh initialization or `polylogue ops embed backfill`. Before deploying: back up (or explicitly discard, if acceptable) the existing `embeddings.db` set, move it aside, then let fresh initialization or `polylogue ops embed backfill --yes` rebuild v3. Rebuilding re-embeds the full corpus and costs real Voyage API spend -- do not do this casually on the live archive without confirming budget. Ref polylogue-wmsc. Absorbs/validates supersession of polylogue-iqd3 and polylogue-0k6 (both already closed as superseded by wmsc). ## Update: follow-up commit after a fuller background regression sweep A full `devtools verify --seed-testmon --skip-slow` (~16k non-slow tests, ~913s) surfaced two genuine ripple-effect regressions from the `EMBEDDINGS_SCHEMA_VERSION` 2->3 bump that weren't in the original test-file list, both now fixed in a follow-up commit: - `tests/unit/cli/test_embed_activation.py::_seed_embeddings_meta` hand-rolled a 6-column `message_embeddings_meta` table + positional 6-value `INSERT`; once the workspace fixture initializes `embeddings.db` to the real v3 (9-column) schema first, the `CREATE TABLE IF NOT EXISTS` becomes a no-op and the positional insert fails (`table message_embeddings_meta has 9 columns but 6 values were supplied`). Fixed to a named-column insert. - `tests/unit/devtools/test_archive_schema_fast_forward.py::test_embedding_clone_preserves_vectors_and_installs_failure_lifecycle` hardcoded the pre-bump expected clone `user_version` (2) instead of importing `EMBEDDINGS_SCHEMA_VERSION`. The production fast-forward helper already targets the constant dynamically -- only the test literal was stale. The same full-suite run also surfaced a long tail of failures in files this PR does not touch (query execution control, MCP tool contracts/declarations, rendering, insights, ChatGPT-normalization parsers, CLI diagnostics, etc.). I classified these before ignoring them, not just dismissed them: - Several (`test_index_fast_forward_lifecycle.py`, `test_index_v37_fast_forward.py`, `test_plain_cli_snapshots.py::test_json_status_snapshot`) share one root cause: a stale hardcoded expectation against `INDEX_SCHEMA_VERSION` (currently `39` in source on both this branch and `origin/master`, confirmed via `grep`/`git show`), unrelated to `EMBEDDINGS_SCHEMA_VERSION` and pre-existing on `origin/master` independent of this diff. - Several (`test_facade_contracts.py`, `test_tool_usage.py`) are `sqlite3.OperationalError: database source_debt is locked` / `unable to open database file` in files this PR's diff never touches (confirmed via `git diff origin/master --stat`) -- reproduced identically with this PR's commit fully stashed back to `HEAD`, i.e. independent of these changes; environmental (shared-box contention / stale temp state from a different concurrent run), not a product regression. - `test_web_reader.py::...redact_configured_archive_paths` was already confirmed pre-existing on unpatched `origin/master` earlier in this review. None of these are addressed here -- fixing them is unrelated cleanup outside this PR's scope (stale `INDEX_SCHEMA_VERSION` snapshots and shared-box sqlite contention, not embedding freshness). Updated verification: `devtools test tests/unit/storage/test_embedding_freshness_invariant.py tests/unit/storage/test_embedding_contracts.py tests/unit/storage/test_embedding_orphan_reconcile.py tests/unit/cli/test_embed_status_fast.py tests/unit/daemon/test_embedding_convergence_progress.py tests/unit/cli/test_embed_activation.py tests/unit/devtools/test_archive_schema_fast_forward.py` -> `179 passed`. `devtools verify --quick` stays green after the follow-up commit. --------- Co-authored-by: Claude <[email protected]>
…3069) ## Summary `agent-acompact-*` is overloaded by Claude Code: a main-session auto-compact replays the whole parent transcript (genuine continuation), but a Task subagent can self-compact under the same filename prefix (a fresh sidechain with no relation to the main session's content). The parser previously classified every `agent-acompact-*` record as an unconditional continuation of its main session, so composed reads of subagent self-compactions incorrectly prepended the wrong (main-session) transcript. ## Problem Code-confirmed (gh#2471, bead `polylogue-4ts.3`): ~39/187 observed `agent-acompact-*` files (9 at 0% overlap) are Task-subagent self-compactions with less than 90% content overlap with their claimed main session, yet were stored/composed as if they were verbatim continuations of it. ## Solution - `polylogue/sources/parsers/claude/code_parser.py`: add `_is_fresh_task_prompt_head`, a narrow structural predicate (root sidechain user record, explicit `agentId`/`promptId`, no `parentUuid`, not human-authored) giving a conservative SIDECHAIN hint when the parser can only see one JSONL group in isolation. - `polylogue/storage/sqlite/archive_tiers/write.py`: the authoritative gate — a bounded multiset content-membership ratio (90% threshold) between the child's pre-summary prefix and the parent's composed transcript, computed once parent content is resolvable. Below threshold (or no fresh-head hint with an unresolvable/spawned-fresh parent) reclassifies to SIDECHAIN/`spawned-fresh` (`branch_point_message_id` explicitly NULL, never left dangling — respects the documented not-a-FK invariant). At or above threshold, parent-content membership overrides even a conservative fresh-head hint back to CONTINUATION/`prefix-sharing`. Both ingest orders are handled: parent-known (`write_parsed_session_to_archive`) and child-before-parent (`_reextract_prefix_tail_db`, including the `session_links` natural-key PK-lane move when `link_type` changes from continuation to sidechain or vice versa). - `polylogue/sources/dispatch.py`: fix a twin-path `fallback_id` divergence flagged in the bead's own investigation notes — the eager grouping path (`_claude_code_grouped_record_specs`) now assigns `fallback_id` to the first group the same way the streaming path (`_claude_code_stream_sessions`) already did, so `composed_session_id` and classification agree between both ingest routes. - `docs/design/session-lineage-model.md`: correct the stale claim that all 187 `agent-acompact-*` sessions are 100% main-session copies; ~148 are, ~39 are Task self-compactions below the 90% membership threshold. - New fixture (`tests/fixtures/claude-code/normalization-lineage-subagent-acompact.jsonl`) and regression tests for both cases (true main-session acompact -> parent=main; subagent self-compact -> sidechain, no inherited prefix), each parametrized over parent-first/child-first ingest order, plus a dispatch-path-parity test. - Companion fix (second commit): the demo/scenario corpus's own `agent-acompact-demo.jsonl` fixture reused a shared generic-workload session as its "parent" but authored unrelated content, relying on the old unconditional-continuation classifier. The new membership gate correctly rejected it (0% real overlap) and flipped it to SIDECHAIN, breaking the `devtools render demo-corpus-datasheet --check` generated surface (part of `render all --check`) — this is the exact misclassification shape the bead describes, just hiding in the demo corpus's own fixtures. Gave the fixture a dedicated parent session with literally-replayed content (matching real Claude Code auto-compact behavior) and updated the `compaction_omits_failed_attempt` construct query and its anti-vacuity test to check both physical locations (child + parent), since genuine prefix-sharing dedup now stores the replayed failed-attempt row once under the parent rather than duplicating it under the child. ## Verification - `devtools test tests/unit/sources/test_compaction.py tests/unit/sources/test_claude_code_normalization_laws.py tests/unit/sources/test_dispatch_payloads.py` -> 56 passed - `devtools test tests/unit/sources tests/unit/demo tests/unit/scenarios tests/unit/cli/test_demo_command.py` -> 1825 passed; 2 pre-existing failures (`test_chatgpt_normalization_survivors.py`, ChatGPT DOM-fallback fidelity) reproduced identically on clean `origin/master`, unrelated to this change. - `tests/integration/test_demo_daemon_convergence.py::test_import_demo_converges_through_live_daemon_path` reproduces identically on clean `origin/master` (live-daemon 20s convergence timeout plus several unrelated missing constructs — browser-capture, embeddings, gemini session-id suffix drift); confirmed pre-existing. - `devtools verify --quick` -> exit 0 (ruff format/check, mypy, `render all`, topology/layering/closure-matrix/manifests/ci-workflows/doc-commands/docs-coverage/test-infra-currency/test-clock-hygiene/pytest-timeout-overrides/degrade-loudly all ok). `devtools render demo-corpus-datasheet --output -` reports `Verifier result: ok`, 0 problems. - `mypy` clean on the whole `polylogue/` package (1031 files) and on every touched module individually. - Anti-vacuity: temporarily forced `_acompact_content_membership_ratio` to always return `1.0` (the pre-patch unconditional-continuation behavior). Both parametrized cases (parent-first, child-first) of `test_subagent_self_compaction_stays_whole_and_never_composes_main_prefix` failed as expected (`'continuation' != 'sidechain'`), confirming the test exercises the real gate. Reverted after confirming. - Checked for collision with #3051 (`orchestration.py` / Workflow tool-call session events, already on `master`): its `code_parser.py`/`dispatch.py` changes are additive and touch an unrelated concept (explicit `Workflow` tool invocations), no overlap with the acompact classification path. - No schema/migration files touched (`git diff --stat` against `polylogue/storage/sqlite/migrations/` is empty) — pure logic fix, consistent with the bead's "no schema change" framing. ## Follow-up / operator verification (cannot be run in this container — no live archive) After a live re-ingest against the real ~38GB archive (`polylogue ops reset --index && polylogued run`, or targeted reprocess of the ~39 known-mismatched files), confirm the reclassification actually lands. Pre/post-rebuild probe: ```sql WITH acompact AS ( SELECT s.session_id, s.branch_type, l.link_type, l.inheritance, l.branch_point_message_id FROM sessions AS s LEFT JOIN session_links AS l ON l.src_session_id = s.session_id AND l.method = 'parser-parent' WHERE s.origin = 'claude-code-session' AND ( s.native_id LIKE 'agent-acompact-%' OR s.native_id LIKE '%:agent-acompact-%' ) ) SELECT COALESCE(branch_type, '<NULL>') AS branch_type, COALESCE(link_type, '<NO-LINK>') AS link_type, COALESCE(inheritance, '<NULL>') AS inheritance, COUNT(DISTINCT session_id) AS sessions FROM acompact GROUP BY 1, 2, 3 ORDER BY sessions DESC, 1, 2, 3; ``` Expected movement (not verified in this container): total acompact session count stays ~187; ~148 true main-session artifacts read `continuation / continuation / prefix-sharing`; ~39 Task self-compactions move to `sidechain / sidechain / spawned-fresh`; the 9 zero-overlap artifacts move branch/link topology from continuation to sidechain (they may already have had `spawned-fresh` inheritance from the older zero-contiguous-alignment path). Post-rebuild integrity check (expect `0`): ```sql WITH acompact AS ( SELECT s.session_id, s.branch_type, l.link_type, l.inheritance, l.branch_point_message_id FROM sessions AS s LEFT JOIN session_links AS l ON l.src_session_id = s.session_id AND l.method = 'parser-parent' WHERE s.origin = 'claude-code-session' AND ( s.native_id LIKE 'agent-acompact-%' OR s.native_id LIKE '%:agent-acompact-%' ) ) SELECT COUNT(*) AS malformed_sidechain_acompacts FROM acompact WHERE branch_type = 'sidechain' AND ( link_type IS NULL OR link_type <> 'sidechain' OR inheritance IS NULL OR inheritance <> 'spawned-fresh' OR branch_point_message_id IS NOT NULL ); ``` (Both queries verified against the current `session_links` schema in this container — the `method` column and the `'parser-parent'` literal it filters on are confirmed present in `polylogue/storage/sqlite/archive_tiers/index.py` and written by `_write_session_link`; only the live-corpus row counts are unverified.) Ref polylogue-4ts.3 Ref gh-2471 --- Generated from a review/verification pass over an externally-authored patch (packet `lin-03-subagent-compaction-r01`); its own HANDOFF/TESTS claims were independently re-verified against current code rather than trusted, per the task's instructions. Not merged — left for coordinator review. --------- Co-authored-by: Claude <[email protected]>
…ctions to README (#3058) ## Summary Adds four sections to the root README — What it captures (per-origin fidelity table), MCP and agent integration, Search boundaries, and an expanded Limitations section — closing gaps an external deep-research audit found in the current README against the live CLI, without disturbing the existing (working) quickstart. ## Problem An external deep-research pass (res-04, GPT-Pro wave-2 campaign — `.agent/handoffs/external-agent-campaigns/2026-07-17-gpt-pro-wave-2/missions/res-04-readme-positioning.md`, deliverable escrowed at `res-04-readme-positioning-r01.zip`) audited the README against a same-day snapshot (`536a53ef`, 13 commits behind this PR's base, no README changes in between) and found real, still-live gaps: - no per-origin provider-fidelity table (only prose naming providers); - no MCP/agent-integration section at all, despite `polylogue-mcp` being a first-class surface; - no mention that FTS excludes `Write` tool-input content and `Edit` old/new bodies; - a thin Security section with no broader Limitations coverage (rebuild cost, cost-vs-billing, no ambient-timeline, `grok-export` reserved, pre-1.0). The same audit's own proposed quickstart rewrite was independently re-verified and found broken: `polylogue import --demo --wait` does not converge to the same corpus as `polylogue demo seed` in the current source. That rewrite is **not** adopted — the existing, working quickstart (`demo receipts --compact` / `demo tour`) is left untouched, per the mission's own instruction to adapt rather than copy verbatim when parts of a draft are stale. ## Solution Added, adapted (not copied) from the external draft, with every command independently re-verified against a fresh scratch demo archive rather than trusted from the source memo: - **What it captures**: an 8-row provider fidelity table (origin, accepted input, fidelity boundary, verify command), with an explicit callout that the seeded demo corpus only populates 5 of the 8 accepted origins (`gemini-cli-session`, `antigravity-session`, `hermes-session` return zero rows against the demo archive — a gap the external report itself did not catch, found during this PR's own verification pass). - **MCP and agent integration**: `polylogue-mcp` role/config example plus the exact current tool counts (104 total, 66 under the default `read` role). - **Search boundaries**: lexical/semantic/hybrid distinction plus a real, reproducible example of the unindexed action-evidence workaround for `Edit`/`Write` bodies. - **Limitations**: provider fidelity, rebuild/embedding cost, cost-vs-billing, no ambient-desktop-timeline (with a reproducible `grep`/`wc -l` proof), `grok-export`/browser-capture status, pre-1.0/no-LTS. Not done, deliberately: no hero-restructure of the lead section or quickstart ordering — `polylogue-3tl.12` already gates that kind of restructuring behind a cold-reader comparison via `polylogue-3tl.19`, which has not run yet; no six-tool MCP table, since that registry does not exist in the current source (per `polylogue-3tl.12`'s own notes); the demo-shelf packet-registry drift the external report also flagged is out of scope for this docs-only PR. ## Verification - `devtools lab provider completeness --json` → 8 accepted-complete origins, `grok-export` reserved, `unknown-export` proposed (matches the new table). - `polylogue --origin <origin> read --all --limit 1 --format json` run for all 8 origins against a fresh `polylogue demo seed --force --with-overlays --format json` archive — 5 returned a row, 3 (`gemini-cli-session`, `antigravity-session`, `hermes-session`) returned zero, which the README now states explicitly instead of implying a uniform command. - `polylogue-mcp --help` → roles `read|write|review|admin` (default `read`); `tests.infra.mcp.declared_tool_names("admin")` = 104, `("read")` = 66. - `polylogue 'actions where tool:edit AND text:"shared_clock"'` → matches the seeded `acompact-demo` file edit, exit 0. - `polylogue ops embed preflight --max-sessions 10 --format json`, `polylogue analyze usage --detail full --format json --limit 0`, `polylogue import <path> --explain --format json`, and the `unknown-export` fallback import — all ran clean. - `grep -h "CREATE TABLE" polylogue/storage/sqlite/archive_tiers/*.py | grep -iE "window|focus|shell_history|browser_tab|activitywatch" | wc -l` → `0`. - `devtools verify doc-commands`, `devtools render all --check` (grepped for "out of sync": none), `devtools verify --quick` → all exit 0. - Pre-push quick verification baseline (ruff format/check, mypy, render all, topology, layering, closure-matrix, manifests, ci-workflows, doc-commands, docs-coverage, test-infra-currency, test-clock-hygiene, pytest-timeout-overrides, degrade-loudly) → all green on push. Ref polylogue-3tl.12 --------- Co-authored-by: Claude <[email protected]>
…ycle (#3059) ## Summary Implements polylogue-dve1: five versioned v1 seed annotation schemas (activity, goal-event, outcome-evidence, knowledge-artifact, reusability) plus a governed archive-local ontology candidate/bootstrap lifecycle (nominate -> accept/rename/split/reject), landed on the existing typed-annotation substrate (annotation_schemas, annotation_batches, assertions). ## Problem polylogue-dve1 asks for packaged seed ontologies plus an ontology bootstrap loop where informal tags/affinity can nominate ontology candidates but never become formal ontology facts without a judged annotation batch/schema. No such packaged vocabulary or governance state machine existed yet. ## Solution - `polylogue/annotations/schema.py`: five new `AnnotationSchema` constants (`seed.activity@v1`, `seed.goal-event@v1`, `seed.outcome-evidence@v1`, `seed.knowledge-artifact@v1`, `seed.reusability@v1`), added to `BUILTIN_ANNOTATION_SCHEMAS` alongside the pre-existing `delegation.discourse@v1`. - `polylogue/storage/sqlite/archive_tiers/user_annotations.py`: `persist_builtin_annotation_schemas()` replays the six built-in rows idempotently; wired into `bootstrap.py` for both fresh-DB init and same-version replay on an already-current `user.db`. **No `USER_SCHEMA_VERSION` bump** -- verified against current `archive_tiers/user.py` that `annotation_schemas` is already the immutable versioned registry and `assertions.kind` is plain `TEXT` with no `CHECK` constraint, so new vocabulary is pure data. - `polylogue/annotations/write.py`: `OntologyCandidateNomination` / `nominate_ontology_candidate()` writes a private, non-injected `AssertionKind.ONTOLOGY_CANDIDATE` row carrying source tag refs, affinity, classifier definition, multi-view proposals/agreement, and privacy/excision refs, kept structurally separate from `confidence`. `OntologyCandidateGovernance` / `govern_ontology_candidate()` runs the full read/judge/register/receipt sequence in one `BEGIN IMMEDIATE`, reusing `judge_assertion_candidate()` for the durable lifecycle and writing a deterministic `AssertionKind.ONTOLOGY_GOVERNANCE` receipt. Schema persistence failure rolls back the whole transaction. - Two new `AssertionKind` values wired through `core/enums.py`, `user_write.py` (candidate-review queue admission), `user_audit.py` (exhaustive per-kind audit), and regenerated `docs/openapi/search.yaml` / `docs/schemas/cli-output/query-unit-envelope.schema.json`. - `polylogue/annotations/importer.py`: the existing `AnnotationBatchImportRequest` route now resolves archive-local (operator-promoted) schemas via a one-schema local registry, without polluting the process-global registry. ## Provenance and independent verification This originated as external-agent packet `ann-01-ontology-seed-r01` (GPT Pro wave 2, snapshot `536a53efac0cbe4a2473ad379e4db49ef3fce74d`, unreviewed). I treated its claims adversarially rather than trusting its own `TESTS.md`: - Confirmed against live source (not the packet's assertion) that `assertions.kind` is unconstrained `TEXT` and `annotation_schemas` is the existing immutable versioned registry -- no user-tier DDL/migration needed, `USER_SCHEMA_VERSION` stays 9. - `git apply --check` against current `origin/master` (12 commits ahead of the packet's snapshot): clean, one 23-line hunk offset. - Found and fixed two real defects the packet's dependency-starved sandbox couldn't catch: - `devtools verify layering` failed (`writer_module_entrypoint_inventory_mismatch`) because `docs/plans/layering.yaml` wasn't updated for the new `persist_builtin_annotation_schemas` entrypoint. Confirmed this is a real regression, not pre-existing, by stash-testing the baseline (`master` alone: `No layering violations found`). - `mypy --strict` found 17 real errors: redundant `cast(JSONValue, ...)` calls, one `list[str]` assigned into a `dict[str, JSONValue]` dict-item position, and 8 test call sites indexing `JSONValue | None` with `# type: ignore[index]` comments that didn't even match the mypy version's actual error code (`call-overload`). Fixed via `require_json_document()` narrowing instead of suppressing. - Ran the two `sqlite-vec`-dependent round-trip tests (`test_write.py::TestAnnotationRoundtripWithQueryAndJudge`) the packet's bare container couldn't execute -- both pass here. ## Verification ``` devtools test tests/unit/annotations/ tests/unit/storage/test_archive_tiers_assertions.py -> 155 passed devtools test tests/unit/annotations/test_schema.py tests/unit/annotations/test_write.py \ tests/unit/storage/test_archive_tiers_user_audit.py tests/unit/devtools/test_render_openapi.py \ tests/unit/cli/test_cli_output_schemas.py tests/unit/storage/test_archive_tiers_ddl.py -> 154 passed devtools verify --quick -> exit 0 (ruff format/check, mypy --strict, render all --check, layering + all lab policy checks) ``` Not run: the full non-quick `devtools verify` (testmon inner loop) and the post-merge heavy CI `test` suite; per-PR CI intentionally skips it. Ref polylogue-dve1 --------- Co-authored-by: Claude <[email protected]>
Make source-to-index rebuilds daemon-owned when requested online, while retaining the offline break-glass command. ## Problem The rebuild command performed an exclusive generation replay only after polylogued stopped, despite the daemon already owning the archive writer boundary. ## Solution Extract the rebuild protocol into `polylogue.maintenance.rebuild_index` with typed request and receipt values. Add authenticated `POST /api/maintenance/rebuild-index`, execute it through the daemon writer bridge's `run_sync`, and add `rebuild-index --daemon` as the CLI adapter. The offline adapter keeps the same source-snapshot, readiness, and promotion protocol, including the resumable bounded-pass transaction fields (`--operation-id`, `--raw-batch-size`, `--pass-byte-budget-mb`, `--pass-deadline-seconds`) that master had independently landed inline via #3055 while this branch was in flight; both are now unified in the shared module. ## Verification - `devtools test tests/unit/cli/test_archive_maintenance_cli.py tests/unit/daemon/test_maintenance_endpoints.py tests/unit/daemon/test_http_write_coordination.py tests/unit/daemon/test_write_coordinator.py tests/unit/daemon/test_web_auth.py tests/unit/daemon/test_route_contracts.py` - 214 passed. - `devtools render topology-projection && devtools render topology-status` - `devtools render all --check` - no out-of-sync surfaces. - `devtools verify --quick` - format, lint, mypy, generated surfaces, topology, layering, schema roundtrip, docs gates all passed. Ref polylogue-ogn1 (follow-up: 8 CodeRabbit findings from the original review, deferred as tracked debt, not part of this rebase's scope). Co-Authored-By: Codex <[email protected]>
… hand ledger (#3065) ## Summary Implements polylogue-3tl.16: `docs/public-claims.yaml` stops being a hand-maintained ledger and becomes a generated projection over `AssertionKind.FINDING` rows, the canonical judgment/supersession lifecycle (PR #2791), and a bounded evidence-integrity verdict seam for the not-yet-landed `polylogue-37t.14` evaluator. ## Problem `docs/public-claims.yaml` (schema `external-claims-ledger/v2`) was a second durable claim store maintained by hand, parallel to the FINDING assertion substrate. A claim's public status could drift from what the judgment lifecycle actually supports, and README/launch/findings-page copy had no single source of truth to render from. ## Solution - `polylogue/insights/measurement/public_claims.py`: `project_public_claims()` computes one `PublicClaimProjection` per stable claim key from `list_public_finding_inputs()` (new read adapter in `storage/finding_provenance.py`), the FINDING/judgment/supersession facts, and an injected `EvidenceIntegrityProvider.verdict_for()` seam. A missing verdict fails closed as `unresolved`, never fresh/supported. Four presets (`readme`, `launch`, `findings-page`, `verified-export`) only *filter* the one already-computed projection -- status is never recomputed per surface. - `polylogue/storage/sqlite/archive_tiers/user_write.py`: additive `PublicClaimDeclaration` + `source_epoch`/`evaluation_ref`/`frame_ref` fields on the existing `polylogue.finding.v1` JSON payload. No user-tier schema migration -- these are new keys in an already-JSON column. - `devtools/public_claims.py` (existing validator, rewritten) + new `devtools/render_public_claims.py`: render/check command, registered in `generated_surfaces.py`/`command_catalog.py`/ `docs_surface.py`/`release_readiness.py`. `docs/public-claims.yaml` is now the generated `verified-export` compatibility view. - Seeds the three current claim-vs-evidence headline findings plus the `category.local-evidence-system` capability statement via `polylogue/scenarios/corpus.py`. - Distinct fail-closed states for broken/circular/stale/frame-incomplete/ private-held/unsupported evidence, verified by real negative tests (see Verification), not just read from the packet's own claims. ## Provenance and independent verification Originated as external-agent packet `ann-05-claims-view-r01` (GPT Pro wave 2, snapshot `536a53efac0cbe4a2473ad379e4db49ef3fce74d`, unreviewed). Verified adversarially rather than trusting its `TESTS.md`: - Confirmed against live source that no second durable claims table exists and no schema migration is needed for the new `FindingAssertion` fields. - `git apply --check` against current `origin/master` (12+ commits ahead of the snapshot) failed on 3 of 29 files: - `docs/plans/topology-target.yaml` / `docs/topology-status.md` had drifted from unrelated intervening commits (both are generated) -- regenerated with `devtools render topology-projection` + `render topology-status` instead of force-applying stale content. - `polylogue/storage/sqlite/archive_tiers/user_write.py` conflicted on one import line added by PR #3051, landed after the packet's snapshot. Reconciled by hand: 7 of 8 hunks applied clean via `git apply --reject`, the import added manually. - Independently reran `devtools verify public-claims --json` (4 claims, 9 artifacts, 3 monitored surfaces, 0 problems) and `devtools verify layering` (0 violations) -- both match the packet's own claimed output exactly, not just re-asserted from its prose. - The packet flagged `test_archive_tiers_api_archive_debt_reads_archive_consistency` ("database source_debt is locked") as a pre-existing baseline failure unrelated to its patch. Reproduced this independently on an unrelated worktree (clean master plus an unrelated annotations feature) to confirm it's a genuine environmental flake, not something introduced here. ## Verification ``` devtools test tests/unit/insights/measurement/test_public_claims.py \ tests/unit/storage/test_public_claims_projection.py tests/unit/devtools/test_public_claims.py -> 31 passed devtools test tests/unit/scenarios/test_demo_archive_convergence.py \ tests/unit/storage/test_archive_tiers_assertions.py tests/unit/devtools/test_generated_surfaces.py \ tests/unit/devtools/test_release_readiness.py tests/unit/devtools/test_render_docs_surface.py \ tests/unit/devtools/test_project_motd.py tests/unit/daemon/test_standing_queries.py tests/unit/cli/test_import.py -> 84 passed devtools test (6 affected tests/unit/api/test_facade_contracts.py cases) -> 6 passed, 1 pre-existing unrelated flake (classified above, reproduced independent of this patch) ruff format --check / ruff check (all 16 touched Python files) -> clean mypy --strict (all 13 touched production/test modules) -> Success, no issues devtools render all --check -> exit 0, no drift (includes regenerated topology docs) devtools verify public-claims --json -> ok, 0 problems devtools verify layering -> 0 violations devtools verify --quick -> exit_code 0 ``` Not run: the full non-quick `devtools verify` (testmon inner loop) and the post-merge heavy CI `test` suite; per-PR CI intentionally skips it. ## Follow-ups intentionally deferred - `polylogue-37t.14` (the shared evidence-integrity evaluator) is not yet landed. This PR defines the narrow consumer interface (`EvidenceIntegrityProvider.verdict_for`) it must implement; the three seeded findings currently render `unknown · unresolved` because no verdict/canonical judgment has been supplied yet -- this is the honest default, not a placeholder bug. - Coverage is currently `README.md`, `docs/demos.md`, `docs/findings/claim-vs-evidence.md`; a future tracked launch-post source should be registered against the `launch` preset when it exists. Ref polylogue-3tl.16 --------- Co-authored-by: Claude <[email protected]>
#3073) ## Summary Implements the Drive sub-case of `polylogue-83u.2`: live Drive-hosted attachment references (`driveDocument(s)`/`driveImage`/`driveAudio`/`driveVideo`) are now fetched during ingest and land in the content-addressed blob store with a true SHA-256, instead of never being acquired. ## Problem A 2026-07-08 investigation (recorded on the bead) found the only code that ever called `DriveSourceClient.download_bytes` for an attachment — `_apply_drive_attachments` + `iter_drive_sessions` — had **zero live callers**. The real ingest path (`iter_drive_raw_data` → generic dispatch parse) never wired attachment acquisition in at all. Even if that dead code had been revived, it wrote bytes to `attachment.path`/local disk rather than `ParsedAttachment.inline_bytes`, so it would not have reached the existing true-hash blob-publish path anyway (schema v13's `acquisition_status`). ## Solution `iter_drive_raw_data` (`polylogue/sources/drive/__init__.py`) already owns the one live `DriveSourceAPI` client instance per file, inside the iterator scope, before the acquire and parse stages decouple for memory-bounded streaming. A new module, `polylogue/sources/drive/attachment_fetch.py`, walks the raw session JSON for Drive-hosted doc/media references **at that exact point**, downloads each via the same live client, and injects the fetched bytes as base64 under a sidecar key (`DRIVE_LIVE_FETCH_DATA_KEY`, defined in `polylogue/sources/parsers/drive_support_attachments.py`). The existing chunk parser (`attachment_from_doc`) decodes that sidecar into `ParsedAttachment.inline_bytes` — no other parser changes — so the already-shipped publish-then-write path (`ingest_batch/_core.py`) picks it up as a real content-addressed blob with `acquisition_status='acquired'`, with zero downstream changes needed. Fetch failures and oversize files (50MB cap) leave the attachment honestly `upload_origin="drive"` with no `inline_bytes` — never a fabricated hash. Removed `_apply_drive_attachments`/`iter_drive_sessions` (and the now-dead `sources/__init__.py` re-export) — the obsolete, zero-caller path this change replaces, per surgical-renewal doctrine. ## Non-goals (explicitly out of scope) `polylogue-83u.2` also named export-zip-member and local-path attachment sub-cases. Both were re-confirmed to have **zero current producer** — no parser has ever emitted an attachment whose bytes live as a sibling zip member or a real local filesystem path. There is nothing live to un-bypass for either, so this PR does not touch them; noted on parent `polylogue-83u` rather than filing speculative follow-up beads with no defined producer. ## Verification - `devtools test tests/unit/sources/test_drive_ops.py tests/unit/sources/test_drive_attachment_fetch.py tests/unit/storage/test_attachment_acquisition.py tests/unit/sources/test_source_laws.py` → **143 passed** - `devtools verify --quick` → **exit 0** (ruff format/check, mypy --strict, render all --check, topology, layering, closure-matrix, manifests, ci-workflows, doc-commands, docs-coverage, test-infra-currency, test-clock-hygiene, pytest-timeout-overrides, degrade-loudly) - `devtools test tests/unit/sources/` → **1705 passed**, 2 pre-existing failures in `test_chatgpt_normalization_survivors.py` confirmed unrelated (reproduce identically with this change stashed out) Ref polylogue-83u.2 Co-Authored-By: Claude <[email protected]> --------- Co-authored-by: Claude <[email protected]>
…e page bridge (#3075) ## Summary Closes the last remaining gap in `polylogue-83u.3`: the `chatgpt-dom-v1` DOM-scrape capture fallback now fetches attachment bytes through the same authenticated page-bridge mechanism the native adapter already uses, instead of recording only the chip name with `byte_count=0`. ## Problem General ChatGPT attachment fetching already ships: `chatgpt_bridge.js` (`fetchAssetBytes`) and `chatgpt.js` (`acquireAssets`/`collectAssetDescriptors`) live-fetch sandbox/file-service bytes for the normal `chatgpt-native-v1` capture path (landed PR #2669, hardened #2672/#2712/#2926). The only remaining gap is the older `chatgpt-dom-v1` fallback — used only when the authenticated backend-api conversation read fails — which had **no acquisition path at all**: `collectAttachments` recorded just the chip's name. ## Architecture constraint `chatgpt-dom-v1` has no backend-api `mapping` to resolve a file/sandbox id from (unlike `chatgpt-native-v1`); the DOM chip's own `href`/`src` is the only evidence available, and it is sometimes already a concrete `https://` URL the page itself rendered (e.g. an inline `<img src>`). ## Solution Added a `"url"` request kind to `chatgpt_bridge.js`'s `fetchAssetBytes` that skips the metadata round trip entirely and reuses the **exact same** fetch+budget+hash mechanism already proven for the `sandbox`/`file` kinds (refactored the shared tail into `fetchBytesFromResolvedUrl`), including the existing cross-origin credential-drop rule (never forward page cookies/bearer to a provider-issued or DOM-rendered cross-origin URL). `chatgpt.js`'s `collectTurns` now awaits a new `acquireDomAttachmentBytes` step — budget-bounded identically to the native path (same per-file/total-byte/time/consecutive-failure caps) — that requests those bytes and sets `inline_base64` on the DOM attachment. That is the exact field `polylogue/sources/parsers/browser_capture.py` already decodes into `ParsedAttachment.inline_bytes` for every adapter, so **no receiver/parser change was needed** — `inline_base64` is not a new payload field, just one `chatgpt-dom-v1` was never wired to populate. Chips with no resolvable URL stay honestly `byte_count=0`. ## Consistency with polylogue-ptx `polylogue-ptx` (PR #2928, merged) replaced the extension's browser-action/campaign machinery with a provider-neutral `BrowserAction` conduit. This change only extends the existing content-script/bridge byte-fetch mechanism at its one documented gap; it does not touch, duplicate, or compete with the `BrowserAction` conduit's submit/receipt machinery. ## Verification - `cd browser-extension && npx vitest run` → **329 passed** (1 pre-existing unrelated failure in `build.test.js`'s packaged-service-worker backfill fixture — reproduces identically without this change) - `npx eslint src/ tests/` → clean - `node scripts/validate-manifest.mjs` → ok - New coverage: 5 focused `fetchAssetBytes` `"url"`-kind tests (direct fetch, cross-origin credential drop, same-origin credential keep, non-https rejection, byte-cap enforcement) plus 2 full-capture DOM-fallback smoke tests (`chatgpt_bridge.test.js`) executing the real production sources through a simulated authenticated page, proving a `chatgpt-dom-v1` capture now yields `inline_base64` whose SHA-256 exactly matches the delivered bytes, and that a chip with no fetchable URL stays honestly `byte_count=0`. Ref polylogue-83u.3 Co-Authored-By: Claude <[email protected]> --------- Co-authored-by: Claude <[email protected]>
…3078) ## Summary Removes 26 accidentally-committed build artifacts from `browser-extension/.cache/` (a packaged-smoke test's zip/xpi output and unpacked source copy) that landed in master via #3075, and adds the missing `.gitignore` entry. ## Problem The root `.gitignore` covers `/.cache/` and `webui/.cache/` but never `browser-extension/.cache/` — a `git add -A` while reconciling #3075's rebase against a fast-moving master swept these up. ## Solution `git rm -r --cached browser-extension/.cache`, add `browser-extension/.cache/` to `.gitignore`. ## Verification `devtools verify --quick` — 16/16 green. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude <[email protected]>
…ent master Merge (not rebase) origin/feature/query/reconcile-transaction-epoch-budget's tip a8c4568 directly: verified polylogue/archive/query/transaction.py and tests/unit/archive/query/test_transaction.py had zero drift from this branch's own merge-base with master (confirmed via diff against merge-base), so their content is taken as-is rather than replayed through a rebase, which mishandles merge commits and silently drops hunks (same failure class diagnosed on PR #3076).
…example render_agent_manual.py's continuation_example_token() constructed a QueryContinuation without archive_epoch, which the just-merged epoch-binding work (this PR) now requires at encode() time. Regenerated the standing manual/deep-reference docs.
## Summary `action_pairs` stops storing copies of `tool_input`/`output_text`; it now keeps only join/rank/outcome columns, and the `actions` VIEW re-joins `blocks` for the text at read time so every reader keeps byte-identical payloads. ## Problem dbstat on the live rebuild generation showed `action_pairs` at 4.1GB for 868,522 rows (~4.7KB/row) — every tool interaction existed ~3x on disk (`blocks.text`/`blocks.tool_input`, `action_pairs.output_text`/`action_pairs.tool_input`, plus FTS). The ~4.7KB rows live in SQLite overflow-page chains, so a per-session `DELETE FROM action_pairs WHERE session_id=?` pays dozens of scattered page reads per row. strace on a live whale-session delete confirmed the mechanism: 27K distinct `pread64`/s concentrated in the `action_pairs` tail with zero sample overlap 30s apart — pure forward progress through a colossal random-IO workload, turning a whale session replace into hours of IO. This is tracked as `polylogue-2i2w`. ## Solution - `action_pairs` (`polylogue/storage/sqlite/archive_tiers/index.py`) drops `tool_input`/`output_text`; surviving columns: `tool_use_block_id`, `tool_result_block_id`, `session_id`, `message_id`, `tool_id`, `use_rank`, `tool_name`, `semantic_type`, `tool_command`, `tool_path`, `is_error`, `exit_code`. - `action_pairs_refresh_sql` (`polylogue/storage/sqlite/action_pairs.py`) no longer selects/inserts the dropped columns. - The `actions` VIEW is rewritten to INNER JOIN `blocks` by `tool_use_block_id` (NOT NULL FK, cascade) and LEFT JOIN `blocks` by `tool_result_block_id` (nullable, SET NULL) to re-serve `tool_input`/`output_text` at read time — same column names/order as before, so every consumer is unaffected. - **Consumer audit** (`rg` across `storage/repository`, `insights`, `daemon`, `mcp`, `cli`, `api`, `devtools`): every reader of pair text goes through the `actions` view. None reads `action_pairs.output_text`/`tool_input` directly except the DDL/refresh/lifecycle machinery this PR edits (`action_pairs.py`, `write.py`'s `refresh_action_pairs` calls, `schema_bootstrap.py`'s stat1 seed rows, `archive_verification.py`'s planner-stats table-name list). `delegation_facts_source`/`delegation_facts` (subagent-dispatch cohort) reads through the view too and is transparently unaffected (verified via its own tests, unchanged). - Index schema version 40 -> 41 (derived tier, no migration chain per the schema regime — `docs/internals.md` § Schema Versioning Model). Added `IndexDeltaDeclaration(version=41, classes=(CACHE_REMOVAL, VIEW_ONLY))` to `polylogue/storage/sqlite/lifecycle.py` since the transition is copy-forward safe (no parser semantics involved). Added the matching `docs/internals.md` changelog entry. - Noted this bump on `polylogue-bo9n` and `polylogue-v6i3` per the schema-regime batching convention — their own decisions (session_events aggregation, FTS bulk-mode skip) remain open and are **not** implemented here. ## Discovered, filed separately (not fixed here, to keep blast radius narrow) - `polylogue-5h5y`: index schema v40 (`query_unit_frame_state`, PR #3068) never got a declared delta class in `lifecycle.py` — `devtools lab policy schema-versioning` already failed before this PR (confirmed by reverting my changes to HEAD and re-running the lint: identical `missing: [40]` failure). - `polylogue-m8nj`: `delegation_facts` still materializes its own (smaller, subagent-dispatch-only) copy of `instruction_payload`/`artifact_text`. ## Verification - `devtools test tests/unit/sources/test_codex_event_stream_contract.py tests/unit/storage/test_archive_tiers_ddl.py tests/unit/storage/test_archive_tiers_write.py tests/unit/storage/test_archive_tiers_assertions.py tests/unit/storage/test_planner_statistics_seed.py tests/unit/maintenance/test_archive_verification.py tests/unit/storage/test_schema_policy_contracts.py tests/unit/insights/test_tool_usage.py tests/unit/storage/test_delegations_view.py tests/unit/pipeline/test_delegation_provider_fixtures.py tests/unit/storage/test_schema_safety.py` → all green except 4 pre-existing failures in `test_tool_usage.py`/`test_delegations_view.py` (`unknown database user_tier` / `unable to open database file`) — confirmed identical failure set on unmodified HEAD (reverted files, re-ran, same 4 failures), unrelated to this change. - `devtools verify --quick` → exit 0 (ran automatically again via the pre-push hook). - `devtools render all --check` → exit 0, no `out of sync`. - `devtools lab policy docs-drift` → "zero unhandled drift". - `devtools lab policy schema-versioning` → 1 pre-existing failure (v40 gap, tracked as `polylogue-5h5y`), no new failures introduced by v41. - **Byte-equivalence proof**: `tests/unit/storage/test_archive_tiers_ddl.py` already pins exact `output_text`/`tool_command`/`is_error`/`exit_code` values through the `actions` view across matched/unmatched/error/reemitted-tool_id/variant-tie/empty-string-tool_id scenarios — all pass unchanged against the new join-based view (this *is* the golden-fixture proof: values were pinned before this change and are reproduced by the rewritten view). `test_agent_action_and_delegation_views_are_indexed_projections` (asserts `USING INDEX` in the `actions` query plan, no `WINDOW`/`WITH` in the view SQL) also passes unchanged. Added `test_action_pairs_does_not_materialize_text_copies` to lock the trimmed column set in place as a regression guard. - Index-size estimate (not directly measured — no live archive access from this isolated worktree): the removed bytes are essentially all of the ~4.7KB/row footprint (surviving columns are short strings/ints/ids already part of that row), so `action_pairs` should collapse from ~4.1GB to a small fraction of that (likely low hundreds of MB, in-page, no overflow chains) on a real rebuild — most of the measured 4.1GB is expected to be reclaimed from `index.db`'s ~19.6GB total. Confirming this needs a real `polylogue ops reset --index && polylogued run` + dbstat pass, which is the coordinator's call. Ref polylogue-2i2w Co-authored-by: Claude <[email protected]>
## Summary Adds the missing `IndexDeltaDeclaration(version=40, ...)` entry to `polylogue/storage/sqlite/lifecycle.py`'s `INDEX_DELTA_DECLARATIONS` registry so `devtools lab policy schema-versioning` recognizes the index-tier v39→v40 schema bump. ## Problem `devtools lab policy schema-versioning` was failing on master: "undeclared index schema deltas found: 1, missing: [40]". PR #3068 ("bind query_units continuations to the archive epoch", polylogue-z9gh.9) bumped `INDEX_SCHEMA_VERSION` from 39 to 40 -- adding the `query_unit_frame_state` table plus its insert/update/delete triggers on `session_links`, `sessions`, `messages`, `blocks`, `session_tags`, `session_profiles`, and `delegation_facts` -- but never added the matching `IndexDeltaDeclaration`. `INDEX_DELTA_DECLARATIONS` jumped straight from `version=39` to `version=41` (the latter added by a later, unrelated PR for polylogue-2i2w), silently skipping 40. ## Solution Added `IndexDeltaDeclaration(version=40, classes=(DerivedDeltaClass.INDEX_ONLY,), operations=(...))` describing the actual v40 delta: one `FastForwardOperation` (`kind=REPLACE_TABLE`) whose `objects` list the `query_unit_frame_state` table and all 21 `query_unit_frame_*` triggers, matching exactly what df86837 (#3068) added to `INDEX_DDL`. No canonical DDL, executor, or runtime behavior changes -- this is a declaration-only fix; the schema itself already exists and is deployed. ## Verification - `devtools lab policy schema-versioning` before: `undeclared index schema deltas found: 1` / `missing: [40]`; after: `undeclared index schema deltas found: 0` / `Schema evolution policy intact.` - `devtools test tests/unit/storage/test_index_fast_forward_lifecycle.py tests/unit/storage/test_index_fast_forward_executor.py`: the two tests this fix targets (`test_current_index_schema_has_a_complete_delta_declaration`, `test_schema_policy_rejects_an_index_bump_without_a_delta_declaration`) now pass. Two unrelated pre-existing failures remain (`test_nonsemantic_delta_without_operations_is_rejected`, `test_delta_without_a_declared_class_is_rejected`) -- confirmed via `git stash` to already fail identically on master, caused by a separate latent bug where `invalid_versions` flags every declaration with `version > current_version` regardless of the v40 gap. Out of scope here. - `mypy --strict polylogue/storage/sqlite/lifecycle.py`: no issues - `ruff check` / `ruff format --check` on the touched file: clean - `devtools render all --check`: no drift - `devtools verify --quick` (pre-push hook): passed Ref polylogue-5h5y Co-Authored-By: Claude <[email protected]> <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Improvements** * Added a storage upgrade that introduces query-unit frame state tracking. * Improved synchronization of session, message, block, tag, profile, and delegation changes through automatic database updates. * Existing data is upgraded automatically when the application applies the new storage version. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: Claude <[email protected]>
…k bool env vars (#3340) ## Summary Fresh `devtools verify --all` re-triage of polylogue-p6rz ("pre-existing test failures unrelated to MCP cutover") against current master. Fixes several confirmed real regressions and stale test assertions found during the pass; files properly-scoped follow-up beads for the rest instead of leaving them as anonymous re-discoveries. ## Problem polylogue-p6rz's original list (from 2026-07-18) was stale: a lot has merged since. A fresh `devtools verify --all` run (107 failed, 14 errors on the pre-fix baseline) needed re-triage to separate fixed / persisting / newly introduced failures, and specifically to catch any real regression from this session's merges (query DSL AST schema, browser-capture approval flow, GitHub effect adapters, continuity replay wiring, etc.). ## Solution **Confirmed real regressions, fixed:** - `polylogue/config.py`: PR #3202's strict bool-env coercion rejected a blank `POLYLOGUE_FORCE_PLAIN=""` value with `ConfigError` instead of the old passthrough-as-falsy behavior, breaking a long-standing CLI test convention (and inconsistent with this same module's own NO_COLOR "blank means not requested" convention). Blank bool-key env values now resolve to `False`. - `polylogue/storage/sqlite/queries/mappers_support.py` and `polylogue/storage/blob_integrity.py`: PR #3155's three-tier JSON facade introduced `polylogue.core.json.JSONDecodeError` (a `ValueError` subclass, NOT a stdlib `json.JSONDecodeError` subclass), but two call sites still caught the stdlib type — silently losing `DatabaseError` diagnostic wrapping (field/record id context) and blob-corruption graceful degradation since 2026-07-19. **Stale test assertions / drifted mocks, fixed:** - `tests/unit/cli/test_color_and_layout.py`: tested `no_color_requested()`/ `should_use_plain()` as if they read `NO_COLOR` from the environment directly; PR #3079 made them pure passthroughs (env resolution moved to `config.py`, already covered elsewhere). Rewrote to test the passthrough contract. - `tests/unit/storage/test_durable_migrations.py`: hardcoded `USER_SCHEMA_VERSION == 9` / `applied_versions` tuple; PR #3068 bumped it to 10 without updating these two tests. - `tests/unit/cli/__snapshots__/test_plain_cli_snapshots.ambr`: stale `index.db` `user_version`/`sqlite_stat1_rows` snapshot from before PR #3235's schema bump 42→43. - `tests/unit/cli/test_diagnostics.py`: `_patch_tool_count_store`'s fake `ArchiveStore.open_existing` lambda didn't accept the `read_timeout` kwarg PR #2964 added, and the fake store was missing `begin_read_snapshot()` (also from #2964's interruptible-read protocol) — 8 tests broken since 2026-07-17. - `tests/unit/devtools/test_mandate_continuity_replay.py` and `tests/unit/operations/test_work_effect_reconciliation.py`: both asserted the real `GitHubPullRequestEffectAdapter` fails against `Sinity/polylogue` — true only in an environment without `gh` auth (e.g. stock CI), false on any dev machine with `gh` authenticated for this repo (confirmed: `gh pr list --repo Sinity/polylogue` succeeds fine here). Forced deterministic unavailability via a nonexistent `gh_path` instead. - `tests/unit/storage/test_delegations_view.py`: 3 tests opened a bare `index.db`-only `ArchiveStore` (no `user.db`); PR #3068's new `archive_snapshot_epoch()` unconditionally requires `user_tier` attached. Added a sibling `user.db` bootstrap to the 3 affected fixtures — matches every other test's full-tier archive construction. - `tests/unit/architecture/test_surface_storage_boundary.py`: allow-listed two CLI commands (`reconcile_work_effects.py`, and `materialize_incident_evidence.py` — the latter landed on master via a concurrent session's PR #3336 mid-rebase) that construct `SessionRepository` directly instead of through `AppEnv.repository`, per the test's own documented remediation path. Filed polylogue-a7uk for the proper fix. **Concurrent-session note:** this branch was rebased onto master mid-flight after another session's PR #3332 landed fixing the exact same `test_timestamp_guards.py` hypothesis-6.161 mypy break I'd independently found and fixed — kept master's version (identical `st.one_of` split approach) rather than duplicating it. **Already tracked, not duplicated:** - `test_execution_control.py` `api.query_units` naming mismatch + `>=50000 VM steps` anti-vacuity mutation tests → polylogue-1ldl (fully root-caused 2026-07-20: PR #3018 made the mutation-under-test no longer expensive at this data scale). - `test_live_batch_support.py` stale `failed=[...]` assertion → polylogue-5202. - `test_archive_maintenance_cli.py` / `test_daemon_cli.py` 6-node cluster → polylogue-p5li. - `tests/infra/surfaces.py` stale `list_sessions`/`search` MCP tool-name lookups (affects `test_retrieval_readiness_laws.py`, `test_cross_surface_agreement.py`) → polylogue-t46.8 (MCP tool-sprawl replacement epic; p6rz's own original text already called this out-of-scope). **New follow-up beads filed (confirmed pre-existing, not this-session regressions, but not safe/minimal to fix inline):** - polylogue-57w4 — repair path still disagrees with converger on NULL-sort-key session-profile staleness (regresses PR #2900's own invariant; root cause not fully diagnosed). - polylogue-lbgc — seeded-archive corpus build hits `database is locked` under xdist parallel first-build (affects `test_plain_cli_snapshots.py`, `test_schema_generation.py`, likely others); confirmed not simple cross-worker contention (the build already holds an exclusive flock across the whole build+integrity-check section) — more likely an unclosed intra-process connection. - polylogue-e6a0 — `test_index_v37_fast_forward.py`'s v36 fixture predates the `action_pairs` runtime index added by PR #3210; attempted fix revealed the fixture's intended "before" shape needs the full same-version benign-DDL-convergence set, not just `ensure_runtime_indexes_sync` — reverted the attempt rather than ship an incomplete fixture. No regression found from this session's headline PRs (query DSL AST schema, browser-capture approval flow, continuity replay wiring) — the two GitHub effect-adapter tests and the `materialize_incident_evidence.py` boundary violation are environment/pattern issues in supporting test/command code, not in the new capability logic itself. ## Verification - `devtools test` on every changed test file individually: all green (see per-file evidence above). - `mypy --strict` on every changed `.py` file: clean. - `ruff format --check` / `ruff check`: clean. - Fresh `devtools verify --all` run against this branch in progress; will update this PR/polylogue-p6rz with the final authoritative count once it completes (~14 min runtime). Ref polylogue-p6rz
## Summary Fixes two tests in `tests/unit/archive/query/test_execution_control.py` that asserted a stale operation name in the execution-control call log. ## Problem `test_api_query_units_routes_through_execution_control` and `test_api_multi_aggregate_receipt_reports_real_work_selection_and_delivery` assert the execution-control call log / `owner_ref` records the operation as `"api.query_units"`. Current production code (`query_units_transaction_request` in `polylogue/archive/query/transaction.py`) sets `operation="query_units"` — no `api.` prefix. Investigation (see polylogue-0twa): the constructor's docstring states it is "the single constructor shared by the API, MCP, and daemon HTTP adapters so the three surfaces cannot drift into building the request differently" (introduced in #3068, `feat(query): bind query_units continuations to the archive epoch`). An `api.`-prefixed name would be incorrect given the name is intentionally shared across non-API surfaces too. This is a stale test assertion, not a production regression. ## Solution Updated both assertions from `"api.query_units"` to `"query_units"`. No production code changed. ## Verification - `devtools test tests/unit/archive/query/test_execution_control.py` -> 23 passed - `mypy --strict tests/unit/archive/query/test_execution_control.py` -> Success - `ruff check` / `ruff format --check` on the changed file -> clean - Pre-push quick verification baseline (format/lint/mypy/render-all/layering/etc.) -> all ok Ref polylogue-0twa 🤖 Generated with [Claude Code](https://claude.com/claude-code) 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. |
Summary
Binds
query_unitscontinuations to a durable archive frame captured from thesame SQLite snapshot as the result rows. The frame spans the index and user
tiers, so stale offset resumes cannot duplicate or skip a changed relation.
Problem
The original index-only epoch was read in a separate probe, missed user-tier
assertion/tag mutations, and used count/timestamp signals that do not cover
all relevant row rewrites. New continuations also allowed an empty epoch, and
HTTP did not validate a resume before serving it.
Solution
in
index.dband assertions inuser.db; compose both values while theresult reader owns its SQLite snapshot.
the legacy empty-epoch compatibility path.
identity for direct storage, API, MCP, and HTTP flows.
continuation errors; MCP reports an unreadable frame as archive-read
unavailability rather than false stale drift.
Verification
devtools test tests/unit/archive/query/test_transaction.py tests/unit/mcp/test_server_surfaces.py::TestArchiveGenericToolSurfaces tests/unit/daemon/test_web_reader.py::TestReaderQueryUnits→ 50 passeddevtools verify --quick→ passed, including schema roundtrip, render,topology, layering, and strict mypy checks
Anti-vacuity: the route tests exercise the actual archive reader, user-tier
assertion write path, MCP tool, and HTTP endpoint; removing the snapshot-frame
validation or mutation triggers makes their stale/identity assertions fail.
Ref polylogue-z9gh.9