Skip to content

fix(sources): require positive conversation evidence before session classification - #3428

Merged
Sinity merged 1 commit into
masterfrom
feature/sources/positive-session-classification
Jul 31, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/sources/positive-session-classification

Conversation

@Sinity

@Sinity Sinity commented Jul 31, 2026

Copy link
Copy Markdown
Owner

Summary

The ingest path's default disposition for an unclassified record was "this is a session" — a record only avoided becoming a session if some specific rule refused it. This PR flips two of the weakest link-in-the-chain heuristics from "type-only is sufficient" to requiring genuine conversation-record envelope evidence, and unifies the two places that decide whether to attempt session parsing at all (live ingest vs. rebuild replay), which previously disagreed.

Problem

Bead polylogue-9ykn (P0): measured against the live archive, 5,255 of 23,296 sessions (22.6%) have zero messages. The single largest contributor (polylogue-gvgi) is conversation_relationships.jsonl — a sinex analysis artifact recording conversation parent/child graph edges, sitting under a watched Claude Code directory — misclassified as a claude-code-session with 96,748 empty messages (~95% of the archive's zero-block messages).

Root cause, traced to source:

  • archive/artifact_taxonomy/support.py:looks_like_record_entry() treated a bare "type" key as sufficient positive evidence of a conversation record (_RECORDISH_KEYS). A relationship-index row's type value happens to be the generic role word "assistant"/"user", so it passed.
  • sources/parsers/claude/code_detection.py:looks_like_code() had the identical defect one layer up: a bare type in {"user", "assistant"} match was treated as sufficient Claude Code evidence on its own.
  • An existing regression test for this exact scenario (test_relationship_index_jsonl_is_metadata_not_session_stream) used a guessed field name ("session") that does not match the real corpus's field name ("conversation") — giving false confidence the defect was already handled. Verified live: with the real field name, the pre-fix classifier returned SESSION_RECORD_STREAM/parse_as_session=True.
  • Separately, the two decision points that gate "should this record even be parsed as a session" disagreed: pipeline/services/ingest_worker.py (live daemon ingest) already runs every sampled JSONL payload through archive.artifact_taxonomy.classify_artifact before parsing. sources/revision_backfill.py (used by polylogue ops reset --index rebuild replay and historical backfill) only consulted the narrower path-pattern-only artifact_rule_for_path (OriginSpec). A record with no matching path rule — like conversation_relationships.jsonl, which sits in an analysis/index/ subdirectory no rule pattern matches — sailed through the rebuild path unchanged even after the live path learned to refuse it. Any future ops reset --index rebuild would silently resurrect exactly the phantoms the live gate now catches.

Solution

  • polylogue/archive/artifact_taxonomy/support.py: looks_like_record_entry() no longer treats a bare "type" key as sufficient on its own; it must co-occur with a genuine record-envelope marker (uuid/sessionId/parentUuid/message/payload/cwd/version). Both observed relationship-index field-name variants ("session" and the real corpus's "conversation") are guarded explicitly, as defense in depth alongside the general fix.
  • polylogue/sources/parsers/claude/code_detection.py: looks_like_code()'s ambiguous role-word types ("user"/"assistant") now require a companion envelope marker. Claude-Code-specific unambiguous types (file-history-snapshot, queue-operation, custom-title, summary, progress, result) are unchanged — they're specific enough to stand alone.
  • polylogue/sources/revision_backfill.py: _is_declared_non_session_artifact() now also runs classify_artifact() against a bounded 64-record content sample (mirroring the live path's own sample bound) when no OriginSpec path rule already decided the question, so _parse_one/_parse_stream (rebuild replay) enforce the same policy as live ingest. The true-streaming path (_parse_stream, used for multi-GiB Claude Code JSONL) stays memory-bounded via itertools.islice/chain — only the sample is materialized, the rest of the stream is chained back on unread.
  • polylogue/cli/commands/status.py: polylogue ops status now surfaces a live "Unidentified artifacts" count (raw_artifacts.artifact_kind='unknown' in source.db) so a novel unrecognized artifact class is noticed the week it appears. This ledger already existed and was already populated for every acquired record (pipeline/services/acquisition_persistence.py → inspect_raw_artifact → save_artifact_observation, run unconditionally on acquisition) — the gap was never "no ledger", it was the classifier feeding it misclassifying some non-conversational content as a session before the ledger ever saw it as unidentified. The full per-kind/per-provider breakdown is already reachable via polylogue check --check-artifact-coverage --check-cohorts.

Chokepoint findings (as requested)

Exactly one literal INSERT INTO sessions exists in the whole codebase (storage/sqlite/archive_tiers/write.py:516, inside write_parsed_session_to_archive) — the row-write chokepoint is real and singular; aggz invariant 2 holds at that layer.

Upstream of that single writer, three distinct call sites decide whether to even attempt producing a ParsedSession destined for it:

  1. pipeline/services/ingest_worker.py (live daemon ingest, default validation_mode=advisory) — already gated by classify_artifact.
  2. sources/revision_backfill.py (polylogue ops reset --index rebuild replay, historical backfill) — previously gated only by the narrower artifact_rule_for_path; unified with (1) by this PR.
  3. sources/live/append_ingest.py (_ingest_append_plans_archive, live incremental append for an already-watched growing file) — calls dispatch.parse_payload directly with no classify_artifact consultation at all.

(3) was not touched by this PR, for lack of time to verify it safely. It is very likely safe-by-construction (append plans should only ever be created for a path sources/live/batch.py's discovery phase already classified as a session stream when first registered for tracking), but this was not empirically proven. Filed polylogue-xwkh to verify and, if needed, close that gap.

unknown-export/ZIP absorption (polylogue-hs3y, raised by a sibling investigation) is a separate, origin-acquisition-level gap — which Origin a raw ZIP gets at acquisition time — not fixed here and not in conflict with this PR's artifact-kind-level classification fix.

Regression-direction guard (per-shape classification, verified)

All four required real shapes now refuse to become a session (regression tests added), while a real Claude Code record with genuine envelope evidence is unaffected:

  • agent-*.meta.json sidecar — before: refused (pre-existing, polylogue-b508); after: refused (pinned).
  • conversation_relationships.jsonl graph-edge index (conversation/parent/child/type/timestamp) — before: admitted as session; after: refused, classified METADATA_DOCUMENT.
  • workflows/wf_*.json run snapshot — before: refused (pre-existing, path-rule); after: refused (pinned).
  • bare toolu_* tool-result-shaped record — before: refused (pre-existing, generic-unrecognized fallback); after: refused (pinned) — polylogue-omsw owns the tool-result acquisition-scope fix specifically.
  • real Claude Code session record (uuid/sessionId/message) — before: admitted; after: still admitted (no regression).

No schema change: raw_artifacts already carries artifact_kind/classification_reason/support_status; the ops status addition is a read-only query against the existing derived surface.

Deliberately not done here (follow-up beads filed)

  • polylogue-zqph: repair pass for the ~5,257 existing empty-session rows already in the live archive. This PR only stops new phantoms going forward; dataset cleanup needs explicit operator sign-off and careful reclassification logic (polylogue-ne6k found a blanket empty-session delete is unsafe — it would delete the 832 sessions the 2026-07-22 hook-inflation postmortem deliberately retained).
  • polylogue-xwkh: verify/close the append_ingest.py gap noted above.
  • polylogue-gvgi's own scoped purge of the live conversation_relationships.jsonl phantom, and polylogue-omsw's workflow/tool-result acquisition-scope dedup, are not reimplemented here — this PR's looks_like_record_entry/looks_like_code fixes are a general byproduct that also prevents their shapes from recurring, but those sibling lanes own their own AC and evidence.

No rows were deleted or modified in any tier by this PR.

Verification

  • devtools verify --quick (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/hash-boundary-census, lab policy schema-versioning, schema promotion audit) — all green, exit_code: 0 (ran twice: once locally, once via the pre-push hook).
  • devtools test tests/unit/sources/test_revision_backfill.py tests/unit/sources/test_artifact_taxonomy.py tests/unit/sources/test_dispatch_ordering.py tests/unit/cli/commands/test_status.py tests/unit/cli/test_status.py tests/unit/sources/test_parsers_props.py tests/unit/sources/parsers/test_origin_regression_pack.py tests/unit/sources/test_parser_crashlessness.py tests/unit/sources/test_origin_specs.py — 320 passed.
  • python3 -m mypy on every touched source and test file — Success: no issues found.
  • Not run: the full devtools test tests/unit suite (anti-pattern per this repo's Verification discipline — testmon-affected selection is the intended inner loop) and any command touching the live archive (/realm/db/polylogue) — read-only sqlite3 ... ?mode=ro evidence gathering only, no writes, per the task's hard constraint.

Ref polylogue-9ykn

…lassification

Problem: the ingest path's disposition for an unclassified record was "this
is a session" -- a record only avoided becoming a session if some specific
rule refused it. classify_artifact()'s looks_like_record_entry() treated a
bare "type" key as sufficient evidence on its own (_RECORDISH_KEYS), and
claude.looks_like_code() treated a bare type value of "user"/"assistant" as
sufficient Claude Code evidence on its own. Both are generic field/value
names that also appear on non-conversational structured data sitting under a
watched Claude Code directory -- e.g. a sinex analysis artifact recording
conversation/parent/child/type/timestamp graph edges
(conversation_relationships.jsonl, the single largest contributor to the
archive's zero-block messages: 96,748 of 101,765, ~95%, per polylogue-gvgi's
live-archive measurement) misclassified as a claude-code session.

Separately, the two decision points that gate "should this record even be
parsed as a session" disagreed: pipeline/services/ingest_worker.py (live
daemon ingest) already ran every sampled JSONL payload through
archive.artifact_taxonomy.classify_artifact, but
sources/revision_backfill.py (used by `polylogue ops reset --index` rebuild
replay and historical backfill) only consulted the narrower path-pattern-only
artifact_rule_for_path. A record with no matching path rule sailed through
the rebuild path unchanged even after the live path learned to refuse it --
so a full rebuild would resurrect exactly the phantoms the live gate now
catches.

Solution:
- polylogue/archive/artifact_taxonomy/support.py: looks_like_record_entry()
  no longer treats a bare "type" key as sufficient; it must co-occur with a
  genuine record-envelope marker (uuid/sessionId/parentUuid/message/payload/
  cwd/version). Both observed relationship-index field-name variants
  ("session" and the real corpus's "conversation") are guarded explicitly.
- polylogue/sources/parsers/claude/code_detection.py: looks_like_code()'s
  ambiguous role-word types ("user"/"assistant") now require a companion
  envelope marker; unambiguous Claude-Code-specific types
  (file-history-snapshot, queue-operation, etc.) are unchanged.
- polylogue/sources/revision_backfill.py: _is_declared_non_session_artifact()
  now also runs classify_artifact() against a bounded 64-record content
  sample when no OriginSpec path rule already decided the question, so
  _parse_one/_parse_stream (rebuild replay) enforce the same policy as live
  ingest. The streaming path stays memory-bounded (itertools.islice + chain)
  for multi-GiB Claude Code JSONL.
- polylogue/cli/commands/status.py: `polylogue ops status` now surfaces a
  live "Unidentified artifacts" count (raw_artifacts.artifact_kind='unknown'
  in source.db, already durably ledgered by every acquisition via
  inspect_raw_artifact -> save_artifact_observation) so a novel unrecognized
  artifact class is noticed the week it appears rather than sitting silent.

Findings for the record:
- Exactly one literal `INSERT INTO sessions` exists (write.py:516,
  write_parsed_session_to_archive) -- the row-write chokepoint is real and
  singular. But THREE distinct upstream call sites decide whether to even
  attempt parsing a ParsedSession destined for that writer: (1)
  ingest_worker.py (already gated), (2) revision_backfill.py (now unified
  with (1) by this change), and (3) sources/live/append_ingest.py
  (_ingest_append_plans_archive, live incremental append) which calls
  parse_payload directly with no classify_artifact consultation at all.
  (3) is very likely safe-by-construction (append plans are only created for
  paths batch.py's discovery phase already classified as session streams),
  but was not verified in this change for lack of time -- filed
  polylogue-xwkh to verify/close that gap.
- unknown-export/ZIP absorption (polylogue-hs3y) is a separate,
  origin-acquisition-level gap, not fixed here: that is about which Origin a
  raw ZIP gets at acquisition time, not whether an already-acquired record's
  content positively evidences a conversation. Both mechanisms are real and
  distinct; this change does not touch hs3y's surface.
- The durable, countable, queryable "unidentified artifact" ledger the
  general fix needs already exists (source.db's raw_artifacts table +
  archive.artifact_taxonomy.classify_artifact +
  `polylogue check --check-artifact-coverage --check-cohorts`) -- it was
  already populated for every acquired record via
  pipeline/services/acquisition_persistence.py. The gap was never "no
  ledger"; it was the classifier feeding it misclassifying some
  non-conversational content as a session before the ledger ever saw it as
  unidentified, plus the rebuild path bypassing that ledger's own gate.
- Existing regression coverage for this exact scenario
  (test_artifact_taxonomy.py::test_relationship_index_jsonl_is_metadata_not_session_stream)
  used a guessed field name ("session") that does not match the real
  corpus's field name ("conversation"), giving false confidence the
  defect was already handled. Added a sibling test using the real field
  name plus the other three required shapes (agent-*.meta.json sidecar,
  workflows/wf_*.json run snapshot, bare toolu_* tool-result record).

Deliberately NOT done here (filed as follow-up beads):
- polylogue-zqph: repair pass for the ~5,257 existing empty-session rows
  already in the live archive. This PR only stops new phantoms; dataset
  cleanup needs explicit operator sign-off and careful reclassification
  logic (see polylogue-ne6k on why a blanket empty-session delete is unsafe).
- polylogue-xwkh: verify/close the append_ingest.py gap noted above.
- polylogue-gvgi and polylogue-omsw's own scoped fixes (the specific
  conversation_relationships.jsonl phantom purge, and workflow/tool-result
  acquisition-scope dedup) are not reimplemented here; this change's
  looks_like_record_entry/looks_like_code fixes are a byproduct that also
  prevents their shapes from recurring, but the sibling lanes own their own
  AC.

Verification:
- devtools verify --quick: 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/hash-boundary-census, lab
  policy schema-versioning, schema promotion audit -- all green (exit 0).
- devtools test tests/unit/sources/test_revision_backfill.py
  tests/unit/sources/test_artifact_taxonomy.py
  tests/unit/sources/test_dispatch_ordering.py
  tests/unit/cli/commands/test_status.py tests/unit/cli/test_status.py
  tests/unit/sources/test_parsers_props.py
  tests/unit/sources/parsers/test_origin_regression_pack.py
  tests/unit/sources/test_parser_crashlessness.py
  tests/unit/sources/test_origin_specs.py -- 320 passed.
- No schema change (no new table/column): raw_artifacts already carries
  artifact_kind/classification_reason/support_status; the ops-status
  addition is a read-only query against the existing derived surface.

Ref polylogue-9ykn

Co-Authored-By: Claude <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2461d51f5c

ℹ️ 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".

Comment on lines 780 to +781
"raw_records": _archive_source_raw_count(conn, configured_root=configured_root),
"unidentified_artifacts": _archive_unidentified_artifact_count(conn, configured_root=configured_root),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Surface unidentified artifacts through daemon status

When the daemon is reachable—the normal runtime—show_status returns after rendering /api/status and never calls _direct_archive_counts; the daemon status producer and _show_daemon_status also have no unidentified_artifacts handling anywhere in the repository. Consequently this new count is visible only in the daemon-down SQLite fallback, so routine status checks while ingestion is running cannot provide the promised warning. Add the count to the daemon status payload and render it on that path as well.

AGENTS.md reference: AGENTS.md:L139-L142

Useful? React with 👍 / 👎.

Comment on lines +89 to 92
if (
_RELATIONSHIP_INDEX_KEYS.issubset(payload) or _RELATIONSHIP_INDEX_KEYS_CONVERSATION.issubset(payload)
) and not has_envelope_marker:
return False

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep relationship rows excluded when weak markers appear

For the already-supported session relationship-index shape, adding an otherwise generic cwd or version field now sets has_envelope_marker, bypasses this exclusion, and then satisfies the new "type" in payload and has_envelope_marker branch. A stream of those rows is therefore classified as a session again; before this commit, the explicit relationship guard still rejected that input because cwd and version were not exceptions. The relationship signature should remain decisive rather than allowing these weak markers to override it.

Useful? React with 👍 / 👎.

@coderabbitai

coderabbitai Bot commented Jul 31, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@Sinity, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 44 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 45c65ae7-3789-441c-8af5-ddabe724a358

📥 Commits

Reviewing files that changed from the base of the PR and between 5525446 and 2461d51.

📒 Files selected for processing (8)
  • polylogue/archive/artifact_taxonomy/support.py
  • polylogue/cli/commands/status.py
  • polylogue/sources/parsers/claude/code_detection.py
  • polylogue/sources/revision_backfill.py
  • tests/unit/cli/commands/test_status.py
  • tests/unit/sources/test_artifact_taxonomy.py
  • tests/unit/sources/test_dispatch_ordering.py
  • tests/unit/sources/test_revision_backfill.py

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Sinity
Sinity merged commit ab8a92c into master Jul 31, 2026
3 checks passed
@Sinity
Sinity deleted the feature/sources/positive-session-classification branch July 31, 2026 07:33
Sinity added a commit that referenced this pull request Jul 31, 2026
…low-artifact reparse (#3433)

## Summary

Two related aggz-invariant-2 follow-ups ("exactly one chokepoint may
write a
session"):

1. **polylogue-xwkh** — closes the third of three chokepoints that
decide
   whether a raw record becomes a session. PR #3428 unified live daemon
   ingest and rebuild replay behind `classify_artifact`/
   `artifact_rule_for_path`; live incremental append
   (`sources/live/append_ingest.py`) had no such gate at all.
2. **polylogue-lzh8** — declares the missing `SEMANTIC_REPARSE`
index-version
   bump for PR #3088 (1e0246d), which shipped a classification fix for
   Claude Workflow artifacts with no version declaration, so already-
   materialized wrong rows never got a reparse signal.

Also investigates (per polylogue-xwkh/lzh8's own framing) why
`devtools lab policy schema-versioning` didn't stop #3088's undeclared
bump,
and files a follow-up bead rather than rushing a fix.

## Problem

**xwkh**: `_ingest_append_plans_archive` called `parse_payload` on every
append unconditionally. Empirically verified (fresh in-memory archive,
`ingest_append_plans` called directly) that a growing
OriginSpec-declared
"fact" artifact (`subagents/workflows/<run>/journal.jsonl`,
`parse_policy="fact"`) reaching append tracking — e.g. after an ops.db
cursor reset resynthesizes a cursor from a durable `full` baseline
already
recorded in source.db (`batch.py`'s `_resynthesize_cursor_from_source`,
which consults only byte-provenance, never classification) — did **not**
leak a phantom session, but only by accident:
`parse_retained_raw_sessions`
(used later, for replay) already applies the same gate and returns zero
sessions, tripping the `did not replay to exactly one session`
`RuntimeError`. That still meant a wasted raw write, a wasted parse, and
a
crash-shaped failure log on **every single observation of the file,
forever**, since a failed append never advances its cursor.

**lzh8**: measured live impact on `index.db` (read-only query,
`/realm/db/polylogue/index.db`, 2026-07-31): 5,193 zero-message
`claude-code-session` rows total, of which 172 join to a `workflows/`
artifact family under the pre-fix classification (164
`agent_sidecar_meta`,
7 `workflow_run_snapshot`, 1 other), all acquired 2026-07-14..07-26 —
entirely before the deployed daemon build contained 1e0246d (sinnix's
polylogue pin only advanced past it 2026-07-29).

**Lint gap**: `devtools/verify_schema_upgrade_lane.py`'s
`index_delta_declaration_report(INDEX_SCHEMA_VERSION)` only checks that
the
declaration table is internally complete/consistent up to the *current*
`INDEX_SCHEMA_VERSION` constant. It never inspects `origin_specs.py`,
`artifact_taxonomy/`, or any other classification source — a commit that
changes classification semantics without touching the version constant
is
invisible to it by construction. It can only catch an **undeclared
bump**,
never a **missing bump**. A real fix (content-fingerprinting the
classification tables, versioned and diffed at lint time) is a genuine
architecture addition, not a small local patch, so filed as follow-up
polylogue-qs4b instead of rushed here.

## Solution

- `polylogue/sources/live/append_ingest.py`: import
`revision_backfill._is_declared_non_session_artifact` (the same check
the
  other two chokepoints already consult) and apply it to the append's
  decoded record sample (`sample=payloads[:64]`, same bound as the live
daemon path) before calling `parse_payload`. A refused record now fails
  cleanly (`mark_raw_parse_failed` + `failed.append`) instead of via an
  uncaught-looking `RuntimeError`, with no wasted parse work.
- `polylogue/storage/sqlite/archive_tiers/index.py`: bump
`INDEX_SCHEMA_VERSION` to 48, with a header comment citing
1e0246d/#3088
  and the measured counts.
- `polylogue/storage/sqlite/lifecycle.py`: add the matching
  `IndexDeltaDeclaration(version=48, classes=(SEMANTIC_REPARSE,))` — no
  fast-forward operations, same "values depend on parser semantics, no
clone-safe SQL delta" shape as v42/v44/v45/v46. **This commit does not
run
  any rebuild.**
- `.beads/issues.jsonl`: close polylogue-xwkh, polylogue-lzh8; file
  polylogue-qs4b for the lint-gap follow-up.

### Operator action required

This PR declares the delta; it does **not** apply it. To reclassify the
172
contaminated rows, the operator must deliberately run:

```
polylogue ops reset --index && polylogued run
```

against the live archive. This was intentionally **not** run from this
branch/session per polylogue-lzh8's explicit instruction (consequential
live-daemon action, extended downtime rebuilding ~20K sessions, needs
deliberate scheduling).

## AC disposition

**polylogue-xwkh** (no formal AC list, task framed as
investigate+verify+fix+test):
- Verified empirically what append_ingest.py currently admits —
satisfied (see Problem).
- Routed through the same classify_artifact gate the other two
chokepoints use — satisfied.
- Regression test proving a record refused by the other paths is now
also refused here — satisfied
(`test_live_append_refuses_declared_non_session_artifact`).

**polylogue-lzh8**:
1. `lifecycle.py` gets a new `IndexDeltaDeclaration` bumping
`INDEX_SCHEMA_VERSION` with `classes=(SEMANTIC_REPARSE,)`, comment
naming 1e0246d/#3088 and the measured counts — satisfied.
2. PR body explicitly tells the operator a rebuild is now required —
satisfied (see above).
3. After the rebuild, the 172+ contaminated sessions reclassify —
**deferred**: not executed per the bead's own DO-NOT-EXECUTE
instruction; operator must run it deliberately.
4. `devtools lab policy schema-versioning` stays green — satisfied.
5. (informal ask) Investigate why the lint didn't catch #3088's original
miss — satisfied, see Problem/Solution; **misframed as an inline fix**:
filed polylogue-qs4b instead, since a real fix needs design work, not a
rushed patch riding this PR.

## Verification

- `devtools test tests/unit/storage/test_raw_revision_authority.py -k
test_live_append` → 3 passed.
- `devtools lab policy schema-versioning` → "Schema evolution policy
intact."
- `devtools test tests/unit/storage/test_index_fast_forward_lifecycle.py
tests/unit/storage/test_index_fast_forward_executor.py
tests/unit/devtools/test_archive_schema_fast_forward.py
tests/unit/storage/test_schema_policy_contracts.py` → 53 passed.
- `devtools verify --quick` → exit 0 (format, lint, mypy --strict,
render all --check, schema-versioning lint, schema promotion audit) —
ran twice (pre-commit local + pre-push hook).
- Not run: `devtools verify --all` (full non-integration suite) — left
for CI's post-merge heavy `test` job per this repo's per-PR test-skip
convention; not run against the live archive (read-only queries only, no
writes, no daemon run).

Ref polylogue-xwkh, polylogue-lzh8, polylogue-qs4b

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude <[email protected]>
Sinity added a commit that referenced this pull request Jul 31, 2026
… retry (#3439)

## Summary

Fixes two of three "mechanism exists but doesn't run" bugs verified live
tonight against the operator's archive:
`session_profiles.cost_usd`/`cost_credits`/`priced_with`/`priced_at_ms`
were structurally 100% NULL (polylogue-f2qv.6), and there was no feeder
for FTS-orphan drift introduced outside the write path (polylogue-5vbs).
The third bug investigated (polylogue-m3p9, growing
`sessions.created_at_ms` NULLs) turned out to already be fixed by a
same-day upstream commit; no additional code change was needed or made
for it.

## Problem

**polylogue-f2qv.6 — cost columns 100% NULL.** Live census: all 23,318
`session_profiles` rows had
`cost_usd`/`cost_credits`/`priced_with`/`priced_at_ms` NULL, despite
`session_model_usage` (the single per-model cost authority) carrying
real catalog-priced `cost_usd` for 10,222 of 18,655 rows for the same
sessions. Root cause: `upsert_session_profile_costs`
(`storage/sqlite/archive_tiers/write.py`) is the only writer ever
declared for these four columns and had zero production callers —
grepped the whole repo to confirm. The value was never computed and
dropped; it was simply never wired into session-profile materialization.
`_SESSION_PROFILE_BASE_COLUMNS`/`session_profile_insert_values` (the
actual INSERT the materializer uses) never referenced these column names
at all.

**polylogue-5vbs — FTS orphan feeder gap.** The bead's design section
named a real gap: `make_fts_stage`'s path-scoped `check`/`check_many`
are deliberate no-ops in archive/split-file mode (in-transaction writes
already repair FTS with an abort-on-failure policy), but nothing fed the
real, working session-scoped `check_sessions`/`execute_sessions` retry
primitives a subject for drift introduced *outside* the write path
(external DB surgery, partial migration, a future writer bug). Live
measurement before/after this investigation showed the orphan count
swinging from the bead's own same-day 10,837 down to 0 under heavy
concurrent multi-agent write load — a moving target, not proof the
underlying gap was closed. Tracing found two `sources/live/batch.py`
call sites (added 2026-07-26, after the bead's original framing) that
*do* feed session-scoped debt, but only for their own two deferred-FTS
writes — nothing covers drift from any other source.

**polylogue-m3p9 — NULL created_at_ms growth.** Live re-measurement
matched the bead's own 5,382 figure exactly. Drilling into the 5,263
`claude-code-session` NULL rows (98.7% of the total): every sampled row
(30 of 5,192 zero-message rows, plus all 71 non-empty-message rows) is
either genuinely message-less or has zero timestamped messages. This is
exactly the shape PR #3428 (commit `ab8a92c1a`, merged the same day just
before this investigation) already fixed: non-conversational records
misclassified as `claude-code-session`. The storage-tier
derive-from-messages fallback
(`write.py::_derive_session_timestamps_from_messages`) is correct and
already landed via a prior PR; it honors its own documented "genuinely
undatable stays NULL" contract. The one residual gap
(`sources/live/append_ingest.py` skipping `classify_artifact`) is
already tracked as `polylogue-xwkh` and is `sources/`-scoped, outside
this PR's allowed area.

## Solution

**Cost columns** (`polylogue/archive/session/models.py`, `documents.py`,
`runtime.py`, `storage/insights/session/{records,profiles,storage}.py`):
extended the real materialization pipeline rather than routing through
the disconnected `upsert_session_profile_costs` helper (which a
DELETE-then-INSERT full profile replace would immediately clobber on the
next rebuild). `SessionProfile` gains nullable
`cost_usd`/`cost_credits`/`priced_with` fields, computed in
`build_session_profile` from the same `cost_summary` already used for
`total_cost_usd`/`total_credit_cost`, gated on the model actually being
in the `PRICING` catalog (mirrors `session_model_usage`'s "no
fabrication" contract — NULL when nothing was catalog-priced, not a fake
$0.00). `SessionProfileRecord` gains the same fields plus `priced_at_ms`
(derived from the record's own `materialized_at`).
`upsert_session_profile_costs` is left in place — four test files use it
as a seeding helper for unrelated read-path tests; it's harmless dead
weight, not part of this fix.

**FTS orphan feeder** (`polylogue/daemon/fts_orphan_audit.py`, new
module): a bounded, hourly sweep — `find_orphaned_fts_sessions_sync`
anti-joins `blocks` (via the existing `idx_blocks_search_text_populated`
partial index) against `messages_fts_docsize` to find sessions with a
block missing its FTS row, and `run_fts_orphan_audit_once_sync` records
that as retryable `stage="fts", subject_type="session_id"` convergence
debt. Wired into `daemon/cli.py`'s periodic-loop family as
`periodic_fts_orphan_audit`, following the existing
`periodic_fts_identity_drift_recompute` shape (a standalone asyncio
loop, not a new `ConvergenceStage` — `convergence_stages.py`'s own
1498-cascade retro verdict is "refactor before adding a fourth stage").

## Verification

```
devtools test tests/unit/storage/test_session_profile_cost_columns.py   # 3 passed
devtools test tests/unit/daemon/test_fts_orphan_audit.py                # 7 passed
devtools test tests/unit/daemon/test_convergence_stages.py \
  tests/unit/storage/test_session_profile_model_usage_consistency.py \
  tests/unit/storage/test_archive_tiers_write.py \
  tests/unit/insights/test_cost_rollup_summary_path.py \
  tests/unit/cli/test_insights.py \
  tests/unit/api/test_facade_contracts.py \
  tests/unit/storage/test_session_usage_reconciliation.py               # 397/398 passed
devtools verify --quick                                                 # exit 0 (mypy --strict, ruff, render all --check)
```

The one pre-existing failure
(`test_archive_tiers_api_raw_artifacts_read_source_tier`, a
clock-hygiene gap where `frozen_clock` doesn't patch a `parsed_at`
timestamp) reproduces identically via `git stash` on the base commit —
unrelated to this change, not touched.

New tests exercise the real production pipeline, not toy replicas:
- Cost columns: `write_parsed_session_to_archive` +
`rebuild_session_insights_sync` (the real ingest→materialize path). A
catalog-priced model populates all four columns with `cost_usd ==
total_cost_usd` (same source computation); an unrecognized model leaves
all four NULL; `priced_at_ms` advances on a later rebuild.
- FTS orphan audit: hand-orphans a block's `messages_fts` row directly
(simulating drift outside the write path), proves the audit finds and
records debt for it, then proves the *already-existing*
`make_fts_stage.check_sessions`/`execute_sessions` genuinely repairs it
— anti-vacuity closing the loop end to end, not just recording debt
nothing drains.

## Not done here

- `storage/sqlite/archive_tiers/archive.py`'s
`_session_cost_insight_from_archive_row` still checks `cost_provenance
== "exact"`, a literal string `SessionCostSummary` never actually
produces (`"provider_reported"`/`"mixed"` instead) — a separate
read-path bug in a file outside this PR's allowed area, now unblocked
(cost_usd is no longer structurally NULL) but not fixed here.
- No live-archive data repair (backfilling existing NULL/orphaned rows)
— per instruction, that's a separate lane's job; this PR is code-path
fixes only.
- polylogue-m3p9 needed no code change; findings recorded on the bead.

Ref polylogue-f2qv.6, polylogue-5vbs, polylogue-m3p9

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
Sinity added a commit that referenced this pull request Jul 31, 2026
…eation (#3497)

## Summary

Two-part fix for the classification-gate correctness problem: (1)
repairs a genuine regression introduced by the polylogue-9ykn
content-classification gate (PR #3428) that refused genuine Claude Code
session records, and (2) implements the general "session requires
positive conversational evidence" invariant at the parse/ingest
chokepoint, with a read-only reconciliation of the 5,257 zero-message
sessions currently in the live archive.

## Problem

**polylogue-6mpy** (failing test on clean master):
`tests/unit/sources/test_revision_backfill.py::test_parse_one_still_replays_real_claude_code_sessions_with_no_path_rule`
failed with `assert 0 == 1`. Root cause: `classify_artifact`'s content
gate (added for polylogue-9ykn, PR #3428) consulted
`classify_artifact_path` first and returned unconditionally — any source
path containing an `analysis/` directory segment was refused as a
self-generated side-output artifact **regardless of record content**, so
a genuine Claude Code session record (`role=user`, real `sessionId`,
real timestamp) sitting under such a path was silently dropped on
replay.

**polylogue-9ykn** (P0): the ingest path's default disposition was "this
is a session" — anything not positively recognised as something else
still became one. Measured against the live archive (2026-07-31,
read-only queries against `/realm/db/polylogue/{index,source}.db`):

```sql
SELECT COUNT(*) FROM sessions;                                   -- 23,496
SELECT origin, COUNT(*) FROM sessions WHERE message_count=0
  GROUP BY origin ORDER BY 2 DESC;
  -- claude-code-session  5,193
  -- claude-ai-export         47
  -- codex-session            17
  -- total: 5,257 (22.4%)

-- C4 overlap (created_at_ms NULL population):
SELECT COUNT(*) FROM sessions WHERE created_at_ms IS NULL;       -- 5,383
SELECT COUNT(*) FROM sessions
  WHERE message_count=0 AND created_at_ms IS NULL;                -- 5,192
```

5,192 of the 5,193 empty `claude-code-session` rows (and 5,192/5,193
overall) also carry `created_at_ms IS NULL` — this **is** the C4
population (the one row with a non-NULL `created_at_ms` is
`problems_index`, a self-generated analysis artifact with its own real
acquisition timestamp).

## Solution

### polylogue-6mpy

`polylogue/archive/artifact_taxonomy/runtime.py`: split
`classify_artifact_path` into a weak, content-blind
`analysis/`-directory heuristic
(`_self_generated_artifact_dir_classification`) and the strong,
definitive path rules (`_classify_artifact_path_strong`: OriginSpec
rules, known sidecar filenames, Hermes/Antigravity path markers).
`classify_artifact` (content-aware) now checks strong path rules first
(unconditional, unchanged), then content classification, and only falls
back to the weak `analysis/` heuristic when content shows no positive
session evidence — so a relationship-index pointer record (no envelope
markers) is still refused, but a genuine session record wins on content
regardless of directory naming.

### polylogue-9ykn

`polylogue/sources/dispatch.py` gains
`require_positive_conversational_evidence()` +
`message_carries_authored_content()`: a session is kept only if at least
one message has real text or a content block.

**Deliberately not folded into `parse_payload`/`parse_stream_payload`
themselves** — those two functions are pure provider-routing dispatch,
pinned by a large "law" test surface (`test_source_laws.py` and friends)
that monkeypatches provider parsers with zero-message stubs specifically
to test *routing* independent of content. Folding the gate in there
broke 20+ of those tests. Instead every real production write path
applies the filter explicitly after calling
`parse_payload`/`parse_stream_payload`:

- `sources/live/batch.py`'s full-ingest loop (reuses the *existing*
`mark_raw_parse_failed` "recorded, bounded failure" mechanism — a
filtered-to-empty result trips the same `if not sessions:` branch a
genuinely-unparseable payload already hits)
- `pipeline/services/ingest_worker.py`'s `_parse_plan_sessions`
(subprocess decode/parse worker; reuses the existing `"parse: session
artifact produced no materializable sessions"` error path)
- `sources/live/append_ingest.py` (incremental append)
- `sources/revision_backfill.py`'s `_parse_one`/`_parse_stream` (offline
replay/rebuild, alongside its own polylogue-6mpy path/shape gate —
catches the sibling case where the shape is recognised but parsed
content still carries no message)

Checking message *content*, not just message *count*, closes a sibling
gap found while testing: an unrecognized single-record document with no
known provider markers fell through Claude Code's generic
single-document lowering into a one-message session whose sole message
had empty text and no blocks — structurally "has a message" but zero
actual evidence.

### Reconciliation (AC b) — read-only, `?mode=ro`

Joining `index.db.sessions` to `source.db.raw_sessions` via `raw_id`:

| Class | Count | Disposition |
|---|---|---|
| `agent-*.meta` sidecars | 4,945 | Artifact — already refused by
`classify_artifact`'s path rule (pre-dates this PR); pending purge |
| JSONL files with only non-conversational envelope records
(`file-history-snapshot`/`progress`/`bridge-session`/`custom-title`/`agent-name`)
| 228+ | Artifact — genuine per-session JSONL files whose entire content
is Claude Code checkpoint/protocol records, never a real message.
**Eliminated at source by this PR's gate.** |
| `tool-results/*.json` sidecars mis-dispatched as sessions | 3 |
Artifact — wrong-provider-dispatch of a single-JSON-object sidecar file
as if it were a session-shaped stream |
| `.gemini/` paths misdetected as `claude-code-session` | 2 | Artifact |
| `claude-ai-export` conversations with a real title but `chat_messages:
[]` | 47 | Content-legitimate export entity, but carries no conversation
— refused by this PR's gate too |
| `codex-session` empty rows | 17 | Mixed: some are zero-byte
scan/write-race captures (now refused instead of silently materializing,
see `test_full_ingest_empty_jsonl_is_not_misclassified_as_truncated`); a
few (996KB/1.4MB blobs) look like a **separate, unrelated Codex
message-extraction defect** — flagged as a residual, not fixed here (out
of scope; see Residuals) |

**On the 832 ne6k-retained rows**: polylogue-ne6k's own 2026-07-31
investigation (same day) already superseded the original "832
intentionally-retained genuinely-empty sessions" framing — its corrected
note states "the 832 the hook-inflation postmortem retained were
retained precisely BECAUSE the blanket predicate could not tell them
apart, not because they were verified worth keeping" and "no 'genuinely
empty session' is a legitimate construct." This PR's gate is therefore
consistent with that corrected finding — it does not carve out a
legitimacy exception for any zero-message row.

**AC (c) — eliminated at source**: the gate above stops all classes
above from ever entering the index again, in one place, for every
ingest/replay route. Existing phantom rows in the live archive are left
for the already-planned v46→v50 index rebuild (polylogue-x1gd) per this
lane's non-goals — **no live-archive writes were made by this PR**.

## Anti-vacuity statement

Production callers exercising the new surface:
`polylogue/sources/live/batch.py:2086` (daemon full-ingest, in-process),
`polylogue/pipeline/services/ingest_worker.py:_parse_plan_sessions`
(subprocess decode/parse worker),
`polylogue/sources/live/append_ingest.py` (incremental append),
`polylogue/sources/revision_backfill.py:_parse_one`/`_parse_stream`
(offline replay/rebuild). Mutation that makes the tests fail: removing
the message-content check from
`require_positive_conversational_evidence` (or reverting it to a
message-*count* check) makes
`test_parse_payload_generic_unrecognized_record_shape_manufactures_only_a_content_free_message`
fail; removing the `require_positive_conversational_evidence` call from
any of the four call sites makes that call site's corresponding fixture
test in
`test_live_batch_support.py`/`test_resilience.py`/`test_revision_backfill.py`
fail (each asserts the specific refused/empty outcome, not merely "no
crash").

## AC matrix

| AC | Status |
|---|---|
| 6mpy: content evidence overrides weak path heuristic; test passes |
Satisfied |
| 6mpy: relationship-index / evidence-free shape stays refused |
Satisfied (regression-pinned,
`test_parse_one_refuses_non_conversational_content_with_no_path_rule`) |
| 9ykn (a): default disposition for unrecognised record is
refusal-with-reason, regression-pinned, no session created | Satisfied —
3 new tests in `test_dispatch_payloads.py` pin
`require_positive_conversational_evidence` against a session-meta-only
stream, a `chat_messages: []` export conversation, and the
unrecognized-shape single-message case |
| 9ykn (b): 5,255/5,257 empty-session population explained (intentional
vs artifact) | Satisfied — see reconciliation table above; no
intentional/legitimate subset remains per ne6k's corrected finding |
| 9ykn (b): C4 `created_at_ms` NULL overlap reported with proving query
| Satisfied — 5,192/5,193 overlap, query above |
| 9ykn (c): artifact class eliminated at ingest source (code fix) |
Satisfied for the classes measured above; existing rows deferred to the
v46→v50 rebuild (non-goal: no live writes) |
| 9ykn: regression test pins unrecognized record ≠ session | Satisfied |

## Verification

```
python -m devtools test tests/unit/sources/test_revision_backfill.py tests/unit/sources/test_artifact_taxonomy.py
  -> 65 passed

python -m devtools test tests/infra/pipeline_roundtrip.py tests/unit/sources/test_dispatch_payloads.py \
  tests/unit/sources/test_dispatch_ordering.py tests/unit/sources/test_source_laws.py \
  tests/unit/sources/test_revision_backfill.py tests/unit/sources/test_artifact_taxonomy.py \
  tests/unit/sources/test_live_batch_support.py tests/unit/pipeline/test_resilience.py \
  tests/unit/daemon/test_ingest_worker_handoff.py tests/unit/pipeline/test_ingest_worker_assembly.py
  -> 334 passed, 5 failed

python -m devtools verify --quick
  -> exit 0 (ruff format/check, mypy --strict, render all --check, topology,
     layering, closure-matrix, schema/manifest/policy lab checks all pass)
```

The 5 remaining failures were each reproduced against a clean-master
baseline worktree (`git worktree add --detach <tmp> 4477b96`, the
commit immediately before this branch) and confirmed to fail identically
there — pre-existing, unrelated to this change:
-
`test_dispatch_payloads.py::test_parse_stream_payload_codex_long_rollout_with_repeated_session_meta_yields_messages`
-
`test_pipeline/test_resilience.py::test_validation_law_matches_mode_and_payload_contract`
-
`test_live_batch_support.py::test_append_multi_session_payload_is_rejected_before_index_write`
-
`test_live_batch_support.py::test_full_ingest_skips_durably_excised_content_without_aborting_batch`
-
`test_live_batch_support.py::test_full_ingest_writes_archive_with_route_observability`

(A wider batch also confirmed as pre-existing this way:
`test_web_reader.py::test_archive_filter_kwargs_cover_every_storage_lowerable_spec_field`,
`test_synthetic_semantics.py`'s two antigravity parametrizations,
`test_claude_code_normalization_laws.py::test_family_fixture_detector_and_streaming_paths_preserve_one_normalized_identity`.)

`devtools verify` (full testmon-affected run) was not run: this fresh
worktree has no seeded testmon database (`.cache/testmon/testmondata`
absent) and `--seed-testmon` would run the full non-integration suite,
which is out of the narrow-node-reproduction budget for this lane. The
targeted file list above plus `--quick`'s static/generated gates are the
verification evidence for this PR.

## Residuals / follow-ups

- A handful of `codex-session` zero-message rows (2 of the 17) have
large (996KB/1.4MB) raw blobs that look like genuine conversations whose
messages failed to extract for an unrelated reason — flagged for a
follow-up bead, not investigated further here (out of scope: this lane
is about the classification/evidence gate, not a Codex parser defect).
- Other in-flight worktrees in this repo have branches named
`feature/sources/positive-session-classification` and
`feature/sources/self-generated-analysis-artifact-refusal` (no open PRs
found for either at push time) — their scope may overlap this PR's;
worth a coordinator check before merge.
- `raw_sessions.detection_warnings_json` (the durable per-raw-revision
warning sink) is not fed by `require_positive_conversational_evidence`'s
refusal — the filter runs after a `ParsedSession` already exists in
memory, with no natural session-scoped event sink to write to since no
session is created. The refusal is currently recorded via
`logger.warning` plus the existing `mark_raw_parse_failed`/`"produced no
materializable sessions"` bounded-error paths at each call site. Wiring
a `claude_parse_coverage`-family detection event for this specific
refusal reason (PR #3419) would need a raw-revision-scoped (not
session-scoped) sink and is left as a follow-up rather than invented ad
hoc here.

Ref polylogue-6mpy, polylogue-9ykn

---------

Co-authored-by: Claude <[email protected]>
Sinity added a commit that referenced this pull request Aug 2, 2026
2qx.3: AC1 complete for all 9 providers (codex/claude-code full-corpus
regenerate both byte-identical to HEAD). gvgi/zqph: confirm the #3428
classifier fix is already deployed and the planned full reindex will
resolve both without a separate targeted-repair script.

Co-Authored-By: Claude <[email protected]>
Sinity added a commit that referenced this pull request Aug 2, 2026
## Summary

Adds `devtools lab policy classifier-fingerprints`, a new static
verification gate that detects when a parser/classifier's acceptance
decision changes for identical input bytes without a declared reparse.
This closes the gap named in polylogue-gucv: the existing
schema-versioning lint is keyed entirely to a version integer and cannot
see this class of change.

## Problem

`devtools lab policy schema-versioning`
(`devtools/verify_schema_upgrade_lane.py`) enforces the
durable-vs-derived schema evolution policy boundary, but every one of
its four checks reads from `INDEX_SCHEMA_VERSION` or `lifecycle.py`'s
version-keyed declarations. It has zero visibility into
`polylogue/sources/**` or `polylogue/archive/artifact_taxonomy/**`,
where the actual "is this raw payload a session?" decision is made.

PR #3428 (`ab8a92c1a`, "require positive conversation evidence before
session classification") is the confirmed case: it tightened
`looks_like_record_entry` and `looks_like_code` so that a payload the
classifier used to admit is now refused, for identical bytes.
`INDEX_SCHEMA_VERSION` stayed unchanged, `lifecycle.py` gained no new
declaration, and `devtools lab policy schema-versioning` ran green —
correctly per its own contract, uselessly for this defect.
Already-indexed rows under the old classification went silently stale
with no signal a reparse was ever needed. CLAUDE.md's own claim ("a bump
without a declaration is a policy violation") only holds for the
version-bump case; a same-version classifier change bypasses it
entirely.

Related, not duplicated: polylogue-9rw0 owns the
fast-forward/equivalence-proof mechanism (its own notes already concede
"parser-content drift is NOT covered"); polylogue-zqph owns the
data-side repair of the ~5,257 existing phantom rows. This PR is the
missing gate only.

## Solution

`devtools/verify_classifier_fingerprints.py`:

1. Discovers every module-level function under the two classification
directories whose name matches `looks_like*` or `classify_artifact*` (36
functions currently — the exact naming convention this codebase already
uses for payload-shape/acceptance decisions).
2. Fingerprints each one as a SHA-256 hash of its AST with the leading
docstring stripped, so reformatting, comment edits, and docstring
rewrites never trip the gate, but a change to the function's actual
logic always does.
3. Compares against a committed manifest
(`docs/plans/classifier-fingerprints.json`). A fingerprint mismatch is
*undeclared drift* and fails the gate unless the manifest entry names
one of:
- `semantic_reparse_version` — an `INDEX_SCHEMA_VERSION` bump whose
`lifecycle.py` declaration actually carries `SEMANTIC_REPARSE` for that
version (cross-checked against `INDEX_DELTA_DECLARATIONS`, not just
asserted).
- `acknowledged_safe` — an explicit reason (≥20 chars) plus a bead/issue
ref (`polylogue-xxxx` or `#N`), for cases judged safe without a reparse
(e.g. only tightening a shape that never validly matched).
4. A brand-new classifier function with no manifest entry, or a manifest
entry whose function no longer exists, both fail — the manifest must
track exactly the live set.

A `--ack <qualname> --reason ... --ref ... [--semantic-reparse N]`
maintenance mode upserts a manifest entry at the function's current
fingerprint after validating the covered_by shape.

Wired into `devtools verify`'s default (non-`--commit`) path immediately
next to `lab policy schema-versioning` — static, archive-independent,
sub-second (0.61s measured).

The initial manifest bootstraps all 36 discovered functions as
`acknowledged_safe`. The two functions PR #3428 actually changed
(`looks_like_record_entry`, `looks_like_code`) are acknowledged with a
reason naming that PR and a ref to polylogue-zqph, which owns the
existing-row repair — this PR does not touch live data or trigger a
reindex.

Both `devtools/verify_schema_upgrade_lane.py`'s module docstring and
`docs/internals.md`'s Schema Versioning Model section now state the
scope gap explicitly, per the bead's AC: a green `lab policy
schema-versioning` run is no longer readable as "no reparse needed"
without checking the classifier-fingerprint gate too.

## Verification

- `devtools test
tests/unit/devtools/test_verify_classifier_fingerprints.py` — 10 passed,
including a historical regression test that reconstructs the
pre-PR-#3428 manifest state (`git show
ab8a92c~1:polylogue/sources/parsers/claude/code_detection.py`,
fingerprinted the same way) and asserts the new gate flags
`looks_like_code` as undeclared drift — proving this gate would have
caught PR #3428 before it landed.
- `mypy` on the new module and test file: `Success: no issues found in 2
source files`.
- `ruff format --check` / `ruff check` on all changed files: clean.
- `devtools render all --check`: no `out of sync` lines.
- `devtools verify closure-matrix`: `closure-matrix: clean (33
domains)`.
- `devtools verify --quick`: full local static gate, `exit_code: 0`,
including the new `lab policy classifier-fingerprints` step (0.61s).
Re-ran automatically and passed again via the pre-push hook.

Not run: the heavy `devtools test tests/unit` full suite (per-PR CI
convention skips it; this change touches only `devtools/` + one new test
file, no `polylogue/` runtime module, so the topology projection did not
need regeneration).

Ref polylogue-gucv

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **New Features**
  - Added a classifier-fingerprint policy check to the verification lab.
- Detects missing, orphaned, invalid, or changed classifier
fingerprints.
  - Supports JSON reporting and recording acknowledged fingerprints.

- **Documentation**
- Documented classifier-fingerprint verification, acknowledgment
requirements, and schema-check limitations.
  - Added the new command to the developer tools catalog.

- **Tests**
- Added comprehensive coverage for fingerprint discovery, drift
detection, manifest validation, and stability.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude <[email protected]>
Sinity added a commit that referenced this pull request Aug 2, 2026
… detection (#3537)

## Summary

Adds a structured per-file acquisition decision log and an
unclaimed-file sweep to the daemon/ingest acquisition path, and tightens
the loosest remaining "guess and proceed" detector
(`claude.looks_like_ai`) to require positive structural evidence. This
is the observability + fail-closed acquisition lane ahead of a planned
index reindex.

## Problem

The acquisition path had no per-file trail: nothing recorded what a
watched file was classified as, what evidence decided that
classification, or how long detection took. A file under a watched root
that no detector claimed left no record it was ever seen at all.

Separately, `docs/architecture.md` names ChatGPT/Claude-web/Gemini's
loose dict-key checks as the highest-risk remaining "guess and proceed"
detectors, in the same shape PR #3428 closed for Claude Code's
`looks_like_code` (a bare ambiguous `type` value used to be sufficient
evidence on its own; it now requires a genuine record-envelope marker).
Auditing the three: ChatGPT's `looks_like`/`looks_like_fragment` were
already tightened to Pydantic-validated node shapes in an earlier change
(the architecture doc's framing is partially stale there).
`claude.looks_like_ai` was not: `isinstance(payload, dict) and
isinstance(payload.get("chat_messages"), list)` accepted any dict
carrying a bare `chat_messages` key -- even an empty list -- as a
claude.ai export.

A third finding surfaced independently this session:
`sources/live/batch.py`'s `_append_payload_for_provider` unconditionally
prepends a synthetic `session_meta` line ahead of every Codex
append-mode capture before hashing, with no logged rationale (see `bd
show polylogue-u19l --json`).

## Solution

- `polylogue/sources/dispatch.py`: `detect_provider_evidence` and
`detect_provider_from_raw_bytes_evidence` are now the sole
implementations of record/sequence/raw-bytes detection, each tagging the
specific detector rule that decided the outcome.
`detect_provider`/`_detect_provider_from_raw_bytes` become thin wrappers
that discard the evidence label -- there is no separate "logging" copy
of the decision tree that can silently drift from the real one.
- `polylogue/sources/live/acquisition_log.py` (new):
`log_file_acquisition_decision` / `log_unclaimed_file` structured log
events (existing `polylogue.logging` structlog convention, no new
framework), an `AcquisitionStageTimings` helper for per-stage elapsed
time, a `.git`-excluding directory walk (`iter_files_excluding_git`,
pruned at the `os.walk` level so a `.git` directory anywhere under a
watched root -- not only at its top -- is never opened, stat'd, or
read), and `sweep_unclaimed_files` + `default_file_claim_check` for a
real shape-detection-backed unclaimed-file sweep (not a path-membership
check).
-
`polylogue/sources/source_acquisition_components.py:read_plain_source_file`
-- the real per-file production acquisition entry point (every non-ZIP
file a `WatchSource` accepts passes through here) -- now times the
detect stage and emits one `file_acquisition_decision` log record per
file: path, size, mtime, origin (or `UNRECOGNIZED`), and the deciding
evidence string.
- `polylogue/sources/live/watcher.py:_scan_catch_up_candidates` -- the
real catch-up scan, run at daemon startup and on every periodic sweep --
now logs `file_acquisition_unclaimed` for a file whose suffix no
configured source accepts, instead of silently skipping it.
- `polylogue/sources/live/batch.py:_append_payload_for_provider` -- the
synthetic Codex `session_meta` header injection is now a declared,
evidenced decision (`codex_append_synthetic_session_meta_injected` log
event naming the recovered identity and why the transform is necessary)
instead of a silent one.
- `polylogue/sources/parsers/claude/ai_parser.py:looks_like_ai` --
tightened to require at least one `chat_messages` entry with positive
structural evidence (a role/sender field alongside a text/content field,
matching what `normalize_chat_messages` itself reads), sibling fix to
#3428.

**Deferred / not fixed here:** Gemini/Drive's `looks_like` still accepts
an empty `chunkedPrompt.chunks` envelope as sufficient evidence. Lower
risk than claude-ai's bare-key check (the `chunkedPrompt` key
combination is distinctive and rare), but a residual guess-branch.
Recommend a follow-up bead for it; the coordinator should file one
(`polylogue-drive-chunkedprompt-empty-envelope` or similar, cannot `bd
create` from this worktree).

**Non-goals honored:** no changes to `sources/dispatch.py`'s
tightness-order architecture itself; no live reindex or production-data
mutation; no new logging framework (reused
`polylogue.logging.get_logger`); no new persisted table (log-only, no
schema change).

## Verification

- `devtools test tests/unit/sources/test_acquisition_log.py
tests/unit/sources/test_dispatch_evidence.py
tests/unit/sources/test_parsers_chatgpt.py
tests/unit/sources/test_dispatch_ordering.py
tests/unit/sources/test_parsers_claude_ai_catalog.py
tests/unit/sources/test_parsers_claude_design.py` -- 181 passed.
- `devtools test tests/unit/sources/test_live_watcher.py
tests/unit/sources/test_live_batch_support.py
tests/unit/sources/test_live_batch_observability.py
tests/unit/sources/test_acquisition_encoding.py` -- 4 pre-existing
failures (durable-excise / multi-session-append / route-observability /
durable-attempt tests) reproduce identically on unmodified master
(verified via `git stash`); unrelated to this change.
- `devtools verify --quick` -- ruff format/check, mypy --strict, `render
all --check` (including `devtools render topology-projection` for the
new module), layering, schema-versioning policy: all green.
- `devtools verify layering` -- no new violations against the baseline.

## Acceptance criteria (per the observability/fail-closed mission)

1. Per-file structured decision trail with evidence + timing: satisfied
via `test_dispatch_evidence.py` (evidence-tagged detection) and
`test_acquisition_log.py::test_log_file_acquisition_decision_emits_evidence_and_timings`,
wired into `read_plain_source_file` (real production path, named above).
2. Unclaimed-file sweep + `.git` exclusion at the walk level: satisfied
via
`test_acquisition_log.py::test_iter_files_excluding_git_never_descends_into_git_directory`
and `test_sweep_unclaimed_files_logs_unrecognized_file_and_skips_git`;
wired into `watcher.py:_scan_catch_up_candidates` (real daemon catch-up
scan).
3. At least one loose detector now refuses-and-logs instead of guessing:
`claude.looks_like_ai`, regression-tested in `test_parsers_chatgpt.py`
(the previous `{"chat_messages": []}` → `True` case now asserts
`False`).
4. Detectors tightened vs. deferred stated above; production caller
named per new log path above.

Co-authored-by: Claude <[email protected]>
Sinity added a commit that referenced this pull request Aug 2, 2026
…tifact rules (#3563)

## Summary

Extends `devtools lab policy classifier-fingerprints` (PR #3532) to also fingerprint `origin_specs.py`'s `OriginSpec.artifact_rules` declarative table, closing the specific gap named in polylogue-qs4b that the function-only gate did not cover.

## Problem

polylogue-qs4b's investigation asked whether the schema-versioning lint (`devtools/verify_schema_upgrade_lane.py`) could be made to catch an undeclared classification-semantic change, citing PR #3088 as the concrete case: it changed `parse_as_session` for four Claude Workflow artifact kinds by editing `origin_specs.py`'s `artifact_rules` table (a `parse_policy` field per `OriginArtifactRule`), with no `INDEX_SCHEMA_VERSION` bump at all.

By the time this session started, the sibling bead polylogue-gucv (a narrower but related finding about the same lint's blindness to `looks_like*`/`classify_artifact*` function drift, concrete case PR #3428) had already merged a fix: PR #3532 added `devtools lab policy classifier-fingerprints`, an AST-fingerprint gate over classification functions.

Reproduced live in this session: mutating an `OriginArtifactRule.parse_policy` (`session` -> `fact`) with no version bump passed **both** `devtools lab policy schema-versioning` and the pre-PR-#3532 `classifier-fingerprints` gate, because `OriginArtifactRule` entries are data, not `looks_like*`/`classify_artifact*` function bodies, so they were never in scope for the existing AST scan.

## Solution

`devtools/verify_classifier_fingerprints.py`:

- `collect_origin_artifact_rules()`: walks `ORIGIN_SPECS`, fingerprinting each `OriginArtifactRule` as a SHA-256 hash of its classification-relevant fields (`path_pattern`, `parse_policy`, `parser_path`, `coverage_role`, `path_suffixes` as canonical JSON). `fidelity_note` is excluded as prose documentation, mirroring how a function's leading docstring is stripped before hashing.
- `collect_all_classification_surfaces()`: merges function fingerprints and artifact-rule fingerprints into one dict, now the default `current` for `compute_drift_report` and the lookup used by `--ack`.
- Bootstrapped the 7 live Claude Code artifact rules into `docs/plans/classifier-fingerprints.json` as `acknowledged_safe` baseline entries (same mechanism PR #3532 used for the initial 36 functions).
- Updated the module docstring, `_format_report` wording ("classification functions" -> "classification surfaces" where it now covers both kinds), and `docs/internals.md`'s Schema regimes section to describe both fingerprinted surfaces and name PR #3088 as the case this half of the gate exists for.

## Verification

- Reproduced the exact failure mode before the fix: mutated `agent_transcript`'s `parse_policy` from `session` to `fact` (the same class of edit as PR #3088) with no `INDEX_SCHEMA_VERSION` bump. Confirmed `devtools lab policy schema-versioning` stayed green and the pre-fix `classifier-fingerprints` gate also stayed green (didn't see the rule at all). Reverted, applied the fix, repeated the mutation: `devtools lab policy classifier-fingerprints` now fails with `exit 1`, naming `polylogue/sources/origin_specs.py:artifact_rule:claude-code-session:agent_transcript` as undeclared drift, while `schema-versioning` alone still stays green (expected -- it is not this lint's job). Reverted the mutation again; both gates green on the clean tree.
- `devtools test tests/unit/devtools/test_verify_classifier_fingerprints.py`: 16 passed (12 pre-existing + 4 new -- artifact-rule discovery, fingerprint-changes-on-`parse_policy`-drift, fingerprint-stable-on-`fidelity_note`-edit, and a historical regression test replaying the #3088 mutation shape and asserting the gate flags it as drift).
- `devtools verify --quick`: `exit_code: 0` (ruff format/check, mypy --strict, `render all --check`, topology, layering, closure-matrix, both `lab policy` gates, schema promotion audit).

Not run: the heavy `devtools test tests/unit` full suite (per-PR CI convention skips it; this change touches only `devtools/` + `docs/` + one test file, no `polylogue/` runtime module).

Ref polylogue-qs4b
Sinity added a commit that referenced this pull request Aug 2, 2026
Problem: polylogue-21qj found 6 non-transcript files under watched
~/.claude/projects trees (a sinex analysis-index, a tool-result spill file
x3, a workflow journal, a derived duplicate-messages index) had been
ingested as claude-code-session rows. Investigation found 5 of the 6 shapes
are already refused at detection time by prior work (#3426, #3428,
c6190d7, and the pre-existing workflow_journal OriginArtifactRule) --
verified live by rerunning each real file's exact byte content (read from
source.db + the blob store, since 2 of 3 sinex files no longer exist on
disk) through classify_artifact/detect_provider_evidence.

For cleanup, polylogue-ne6k had already built the classifier+dry-run-gated
maintenance-repair pattern this bead asked for (repair.py's `empty_sessions`
target, wired through `polylogue maintenance repair --target
empty_sessions`) -- but scoped to literally message-less sessions
(`NOT EXISTS messages`). claude-code-session:conversation_relationships has
96,748 MESSAGE ROWS, every one carrying zero blocks/words, so it fell
outside that predicate entirely and was never even a repair candidate.

Solution: widen `_empty_session_candidate_ids` (renamed from
`_empty_session_message_less_candidates`) to also propose sessions where
`sessions.word_count = 0` regardless of message_count. The existing
positive-classification gate (`_raw_artifact_positively_fails_classification`)
remains the sole deletion authority, so a legitimate all-tool-use session
with no text turns is still retained (its raw artifact still carries real
Claude Code envelope markers and passes classification).

Also added the one missing regression pin: analysis/signal/high_value_
messages.jsonl (the 6th named shape) was already refused via the
analysis/ directory heuristic but had no dedicated test using its real
field shape (file/timestamp/type/content). That session is deliberately
excluded from the empty_sessions purge (word_count=827,894, real content)
-- investigation found its real source session is stuck
revision_authority='quarantined' and never parsed, so it is currently the
archive's only queryable copy of that conversation; deferred to
polylogue-6bebe rather than deciding blanket deletion here.

Verification:
- devtools test tests/unit/storage/test_empty_session_repair_provenance.py
  tests/unit/sources/test_artifact_taxonomy.py -- 15 passed. New tests pin
  both the widened-predicate debris case and its "legit all-tool-use"
  sibling that must NOT be swept in, plus the high_value_messages shape.
- devtools verify --quick -- exit 0, all 19 steps green.
- Read-only measurement against the live archive (/realm/db/polylogue):
  before this change, conversation_relationships was absent from
  `_empty_session_debris_session_ids`'s output; after, it is flagged
  alongside problems_index/journal/3x toolu_*. Total flagged debris across
  the archive went from 5023 to 5076 rows (+53, this generalization also
  catches other same-shaped phantoms, not only the 5 named here).
- Pre-existing, unrelated failure noted and NOT fixed here: tests/unit/
  maintenance/test_planner_contract.py and test_planner_filter_narrowing.py
  fail with a TypeError (row_factory not set on a test fixture's index
  connection) on master (120cf6f) before this change too (confirmed via
  git stash) -- filed as polylogue-9rdky.

Ref polylogue-21qj, polylogue-gvgi (closed as duplicate), polylogue-6bebe,
polylogue-9rdky

Co-Authored-By: Claude <[email protected]>
Sinity added a commit that referenced this pull request Aug 2, 2026
Problem: polylogue-21qj found 6 non-transcript files under watched
~/.claude/projects trees (a sinex analysis-index, a tool-result spill file
x3, a workflow journal, a derived duplicate-messages index) had been
ingested as claude-code-session rows. Investigation found 5 of the 6 shapes
are already refused at detection time by prior work (#3426, #3428,
c6190d7, and the pre-existing workflow_journal OriginArtifactRule) --
verified live by rerunning each real file's exact byte content (read from
source.db + the blob store, since 2 of 3 sinex files no longer exist on
disk) through classify_artifact/detect_provider_evidence.

For cleanup, polylogue-ne6k had already built the classifier+dry-run-gated
maintenance-repair pattern this bead asked for (repair.py's `empty_sessions`
target, wired through `polylogue maintenance repair --target
empty_sessions`) -- but scoped to literally message-less sessions
(`NOT EXISTS messages`). claude-code-session:conversation_relationships has
96,748 MESSAGE ROWS, every one carrying zero blocks/words, so it fell
outside that predicate entirely and was never even a repair candidate.

Solution: widen `_empty_session_candidate_ids` (renamed from
`_empty_session_message_less_candidates`) to also propose sessions where
`sessions.word_count = 0` regardless of message_count. The existing
positive-classification gate (`_raw_artifact_positively_fails_classification`)
remains the sole deletion authority, so a legitimate all-tool-use session
with no text turns is still retained (its raw artifact still carries real
Claude Code envelope markers and passes classification).

Also added the one missing regression pin: analysis/signal/high_value_
messages.jsonl (the 6th named shape) was already refused via the
analysis/ directory heuristic but had no dedicated test using its real
field shape (file/timestamp/type/content). That session is deliberately
excluded from the empty_sessions purge (word_count=827,894, real content)
-- investigation found its real source session is stuck
revision_authority='quarantined' and never parsed, so it is currently the
archive's only queryable copy of that conversation; deferred to
polylogue-6bebe rather than deciding blanket deletion here.

Verification:
- devtools test tests/unit/storage/test_empty_session_repair_provenance.py
  tests/unit/sources/test_artifact_taxonomy.py -- 15 passed. New tests pin
  both the widened-predicate debris case and its "legit all-tool-use"
  sibling that must NOT be swept in, plus the high_value_messages shape.
- devtools verify --quick -- exit 0, all 19 steps green.
- Read-only measurement against the live archive (/realm/db/polylogue):
  before this change, conversation_relationships was absent from
  `_empty_session_debris_session_ids`'s output; after, it is flagged
  alongside problems_index/journal/3x toolu_*. Total flagged debris across
  the archive went from 5023 to 5076 rows (+53, this generalization also
  catches other same-shaped phantoms, not only the 5 named here).
- Pre-existing, unrelated failure noted and NOT fixed here: tests/unit/
  maintenance/test_planner_contract.py and test_planner_filter_narrowing.py
  fail with a TypeError (row_factory not set on a test fixture's index
  connection) on master (120cf6f) before this change too (confirmed via
  git stash) -- filed as polylogue-9rdky.

Ref polylogue-21qj, polylogue-gvgi (closed as duplicate), polylogue-6bebe,
polylogue-9rdky

Co-Authored-By: Claude <[email protected]>
Sinity added a commit that referenced this pull request Aug 2, 2026
Problem: polylogue-21qj found 6 non-transcript files under watched
~/.claude/projects trees (a sinex analysis-index, a tool-result spill file
x3, a workflow journal, a derived duplicate-messages index) had been
ingested as claude-code-session rows. Investigation found 5 of the 6 shapes
are already refused at detection time by prior work (#3426, #3428,
c6190d7, and the pre-existing workflow_journal OriginArtifactRule) --
verified live by rerunning each real file's exact byte content (read from
source.db + the blob store, since 2 of 3 sinex files no longer exist on
disk) through classify_artifact/detect_provider_evidence.

For cleanup, polylogue-ne6k had already built the classifier+dry-run-gated
maintenance-repair pattern this bead asked for (repair.py's `empty_sessions`
target, wired through `polylogue maintenance repair --target
empty_sessions`) -- but scoped to literally message-less sessions
(`NOT EXISTS messages`). claude-code-session:conversation_relationships has
96,748 MESSAGE ROWS, every one carrying zero blocks/words, so it fell
outside that predicate entirely and was never even a repair candidate.

Solution: widen `_empty_session_candidate_ids` (renamed from
`_empty_session_message_less_candidates`) to also propose sessions where
`sessions.word_count = 0` regardless of message_count. The existing
positive-classification gate (`_raw_artifact_positively_fails_classification`)
remains the sole deletion authority, so a legitimate all-tool-use session
with no text turns is still retained (its raw artifact still carries real
Claude Code envelope markers and passes classification).

Also added the one missing regression pin: analysis/signal/high_value_
messages.jsonl (the 6th named shape) was already refused via the
analysis/ directory heuristic but had no dedicated test using its real
field shape (file/timestamp/type/content). That session is deliberately
excluded from the empty_sessions purge (word_count=827,894, real content)
-- investigation found its real source session is stuck
revision_authority='quarantined' and never parsed, so it is currently the
archive's only queryable copy of that conversation; deferred to
polylogue-6bebe rather than deciding blanket deletion here.

Verification:
- devtools test tests/unit/storage/test_empty_session_repair_provenance.py
  tests/unit/sources/test_artifact_taxonomy.py -- 15 passed. New tests pin
  both the widened-predicate debris case and its "legit all-tool-use"
  sibling that must NOT be swept in, plus the high_value_messages shape.
- devtools verify --quick -- exit 0, all 19 steps green.
- Read-only measurement against the live archive (/realm/db/polylogue):
  before this change, conversation_relationships was absent from
  `_empty_session_debris_session_ids`'s output; after, it is flagged
  alongside problems_index/journal/3x toolu_*. Total flagged debris across
  the archive went from 5023 to 5076 rows (+53, this generalization also
  catches other same-shaped phantoms, not only the 5 named here).
- Pre-existing, unrelated failure noted and NOT fixed here: tests/unit/
  maintenance/test_planner_contract.py and test_planner_filter_narrowing.py
  fail with a TypeError (row_factory not set on a test fixture's index
  connection) on master (120cf6f) before this change too (confirmed via
  git stash) -- filed as polylogue-9rdky.

Ref polylogue-21qj, polylogue-gvgi (closed as duplicate), polylogue-6bebe,
polylogue-9rdky

Co-Authored-By: Claude <[email protected]>
Sinity added a commit that referenced this pull request Aug 2, 2026
…oms (#3583)

## Summary

Widens `polylogue/storage/repair.py`'s `empty_sessions` maintenance-repair target so it also catches sessions that have message rows but zero real content (all-zero-word messages), not only literally message-less sessions. Adds the one missing regression test among 6 named phantom-artifact shapes.

## Problem

polylogue-21qj found 6 non-transcript files under watched `~/.claude/projects` trees had been ingested as `claude-code-session` rows in the live archive: a sinex analysis-index (`conversation_relationships.jsonl`, 96,748 empty messages), a derived duplicate-messages index (`high_value_messages.jsonl`, 8,763 real duplicate messages), an empty problem-index (`problems_index.jsonl`), 3x oversized-tool-output spill files (`tool-results/toolu_*.json`), and a workflow journal (`journal.jsonl`).

Investigating against the live archive (read-only, `/realm/db/polylogue`) and the current checkout found **5 of the 6 shapes are already refused at detection time** by prior merged work (#3426 self-generated `analysis/` dir guard, #3428 `looks_like_code` envelope-marker requirement, c6190d7 letting record content override the `analysis/` guard, and the pre-existing `workflow_journal` `OriginArtifactRule`). Verified live: reran each real file's exact byte content (read from `source.db` + the blob store, since 2 of 3 sinex files no longer exist on disk) through `classify_artifact`/`detect_provider_evidence` — all return `parse_as_session=False`.

For cleanup, `polylogue-ne6k` had already built exactly the classifier + dry-run-gated actuator pattern this bead asked for (`repair.py`'s `empty_sessions` target, wired through `polylogue maintenance repair --target empty_sessions`, dry-run by default) — but scoped to literally message-less sessions (`NOT EXISTS messages`). `conversation_relationships` has 96,748 message rows (every one carrying zero blocks/words), so it fell outside that predicate and was never even a repair candidate.

## Solution

- Widened `_empty_session_candidate_ids` (renamed from `_empty_session_message_less_candidates`) to also propose sessions where `sessions.word_count = 0` regardless of `message_count`. The existing positive-classification gate (`_raw_artifact_positively_fails_classification`) remains the sole deletion authority — a legitimate all-tool-use session with no text turns still passes classification and is retained (pinned by `test_all_empty_content_session_with_legit_raw_is_retained`).
- Added `test_all_empty_content_session_with_phantom_raw_counts_as_debris`, pinning that a `conversation_relationships`-shaped session (many zero-word message rows, relationship-index-shaped raw artifact under `analysis/`) is now flagged.
- Added `test_analysis_signal_duplicate_messages_are_not_a_session` to `test_artifact_taxonomy.py`, the missing regression pin for the 6th named shape (`high_value_messages.jsonl`'s real field shape: `file`/`timestamp`/`type`/`content`).
- Updated the `empty_sessions` maintenance-target description to reflect the broader predicate.

`high_value_messages.jsonl` (8,763 non-empty messages, 827,894 words) is deliberately excluded from the purge — its content is real duplicated conversation text, and investigation found the real source session (`bad69218-...`) is stuck `revision_authority='quarantined'` and never parsed, so this phantom is currently the archive's only queryable copy of that content. Blanket deletion would be real data loss, not garbage collection. Deferred to polylogue-6bebe.

## Verification

- `devtools test tests/unit/storage/test_empty_session_repair_provenance.py tests/unit/sources/test_artifact_taxonomy.py` — 15 passed.
- `devtools verify --quick` — exit 0, all 19 steps green (also ran again automatically via the pre-push hook).
- Read-only measurement against the live archive: before this change, `conversation_relationships` was absent from `_empty_session_debris_session_ids`'s output; after, it is flagged alongside the already-flagged `problems_index`/`journal`/3x `toolu_*`. Total flagged debris across the archive went from 5023 to 5076 rows (+53 — this generalization also catches other same-shaped phantoms archive-wide, not only the 5 named in this bead).
- Pre-existing, unrelated failure found and **not** fixed here: `tests/unit/maintenance/test_planner_contract.py` and `test_planner_filter_narrowing.py` fail with a `TypeError` (row_factory not set on a test fixture's index connection) on master (120cf6f) too, confirmed via `git stash` before this change. Filed as polylogue-9rdky.

Ref polylogue-21qj, polylogue-gvgi (closed as duplicate), polylogue-6bebe, polylogue-9rdky
Sinity added a commit that referenced this pull request Aug 3, 2026
## Summary

Tightens `drive.looks_like` (the sole auto-detection call site for the
Gemini/AI-Studio-Drive `chunkedPrompt` wire shape) to require at least
one genuine chunk with role/content evidence, instead of accepting a
present-but-empty (or wrong-typed) `chunks` list as sufficient evidence
on its own.

## Problem

`polylogue-mvcbi`: a residual guess-instead-of-verify branch, sibling to
the classifier-tightening pattern already landed in #3428 (Claude Code's
bare `type` check) and #3537 (claude.ai's bare `chat_messages` check).
Before this change:

```
detect_provider({"chunkedPrompt": {"chunks": []}}))  # -> Provider.GEMINI (wrong)
```

`drive._looks_like_chunks` had an `allow_empty` flag that was `True` for
the named `chunkedPrompt.chunks` envelope but `False` for the bare
top-level `chunks` key — the same shape was treated inconsistently
depending only on nesting. An empty envelope was never a real
Gemini/Drive conversation; no genuine session has zero chunks.

## Solution

- `polylogue/sources/parsers/drive.py`: `_looks_like_chunks` drops the
`allow_empty` parameter entirely (both call sites now require the same
thing: a non-empty list where every entry passes `looks_like_chunk`).
`looks_like` now requires a genuine chunk for the `chunkedPrompt.chunks`
envelope, matching the already-strict top-level `chunks` case.
- `tests/unit/sources/test_gemini_drive_normalization_laws.py`: new
regression test
(`test_empty_chunked_prompt_envelope_is_not_detected_as_gemini`) pinning
the empty-list, wrong-type (`"not-a-list"`, `{}`), and genuine-chunk
cases.
- `tests/unit/sources/test_source_laws.py`:
`test_iter_source_raw_data_keeps_source_family_hints_for_mixed_zip_sources`
hardcoded the exact buggy empty envelope as its "gemini" zip-entry
fixture (relying on the bug to pass); updated to a genuine single-chunk
envelope so it still exercises mixed-zip provider-hint detection rather
than the now-fixed bug.
- `docs/plans/classifier-fingerprints.json`: `devtools lab policy
classifier-fingerprints` flags any `looks_like*` function whose AST
changed without a declared reparse or explicit safety acknowledgment.
Acknowledged safe (not a `SEMANTIC_REPARSE` `INDEX_SCHEMA_VERSION` bump)
via `devtools lab policy classifier-fingerprints --ack ... --ref
polylogue-mvcbi`, since the tightening only rejects a shape that never
validly represented a real conversation — the escape hatch the tool's
own docstring describes for exactly this case. A schema-version bump
belongs to `storage/`, out of this change's scope.

**Interplay checked:** an empty envelope no longer detects as any
provider; `parse_payload` falls through to a zero-message `unknown`
session, and `require_positive_conversational_evidence` (the production
content gate every real write path already calls) refuses it with a
logged warning — no crash, no silent write.

**Out of scope (per assignment):** `daemon/`, `storage/`, `migrations/`,
artifact-classification/sidecar code, and detector precedence in
`sources/dispatch.py` (tightness order unchanged — verified via
`test_detector_order_is_tight_and_one_document_streams_keep_specificity`,
which still passes). `parse_drive_payload`'s explicit-provider route
(`dispatch.py:1823`, `"chunkedPrompt" in record or "chunks" in record`)
is intentionally more tolerant than auto-detection (see
`has_chunk_container`'s docstring) and is untouched.

## Verification

- Red-first: `devtools test
tests/unit/sources/test_gemini_drive_normalization_laws.py -k
test_empty_chunked_prompt_envelope_is_not_detected_as_gemini` failed
before the fix (`AssertionError: assert <Provider.GEMINI: 'gemini'> is
None`), committed as a separate commit, then green after the fix commit.
- `devtools test
tests/unit/sources/test_gemini_drive_normalization_laws.py
tests/unit/sources/test_parsers_drive.py
tests/unit/sources/test_dispatch_ordering.py
tests/unit/sources/test_dispatch_payloads.py
tests/unit/sources/test_gemini_chunked_prompt_contract.py
tests/unit/sources/test_parsers_drive_catalog.py
tests/unit/sources/test_source_laws.py` — 248 passed, 2 failed. Both
failures reproduce identically on unmodified master (verified via `git
stash`):
`test_iter_source_raw_data_avoids_whole_blob_provider_detection_for_zip_entries`
and
`test_iter_source_raw_data_splits_multi_session_zip_entries_for_non_grouped_providers[...]`
(a stale `_detect_provider_from_raw_bytes` monkeypatch target and an
unrelated claude-ai `UNKNOWN` detection gap) — pre-existing, unrelated
to this change.
- `devtools verify --quick` — ruff format/check, mypy --strict, render
all --check,
topology/layering/closure-matrix/manifests/ci-workflows/doc-commands/docs-coverage/test-infra-currency/pytest-timeout-overrides/degrade-loudly/hash-boundary-census,
lab policy schema-versioning, `lab policy classifier-fingerprints`
(initially failed on undeclared drift, fixed via the `--ack` commit
above), lab policy
demo-tour-freshness/raw-payload-hash-purity/position-derived-identity/raw-authority-frontier-executability,
schema promotion audit — all green, `exit_code: 0` (ran via the pre-push
hook).
- `devtools verify --seed-testmon --skip-slow` — attempted for the full
testmon-affected inner loop, but this worktree's host is shared by
several other concurrent agent lanes each running the identical heavy
seed simultaneously; the seed run itself timed out under that contention
(18,575 passed / 14 failed / 2 interrupted / 1 timeout across the whole
non-slow suite) rather than completing cleanly. None of the unsuccessful
node IDs touch `sources/parsers/drive.py`, `sources/dispatch.py`, or
either test file this PR changed. The targeted `devtools test` runs
above are the load-bearing verification for this change's actual
surface.

Ref polylogue-mvcbi.

---------

Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant