Skip to content

feat(security): local excision + secret-candidate detection (polylogue-27m) - #2875

Merged
Sinity merged 3 commits into
masterfrom
feature/security/excision-secret-hygiene-27m
Jul 14, 2026
Merged

Sinity merged 3 commits into
masterfrom
feature/security/excision-secret-hygiene-27m

Conversation

@Sinity

@Sinity Sinity commented Jul 14, 2026 •

Copy link
Copy Markdown
Owner

Summary

Implements the local-excision and secret-hygiene mechanics for polylogue-27m
("the archive can forget on purpose"): a candidate-only secret scanner, an
authoritative standalone/off-mode excision engine, and the mirror/primary
durable lifecycle-request/outbox mechanism exercised against a
fault-injecting versioned Sinex contract fake.

Problem

Before this PR there was no excision mechanism at all (no schema, no
code) and no candidate-only secret detector for captured content.
docs/plans/security-privacy-coverage.yaml tracked this as an explicit
major severity gap (security.captured-content-secret-detection, owner
security-privacy, bead: polylogue-27m, next_evidence: devtools test -k secret_candidate). reset --session tombstones a session in user.db and
deletes its index.db rows, but nothing prevented an ordinary re-ingest of
the same unmodified source file from silently resurrecting the deleted
content once index.db is rebuilt from source.db — there was no durable
removed-hash marker anywhere.

Solution

polylogue/security/secret_scan.py — candidate-only detector.
Credential-shaped regex rules (AWS/GitHub/Slack/OpenAI/Anthropic key
shapes, PEM private-key headers, JWTs, an entropy-filtered generic
key=value rule) find spans in text. scan_text_for_secret_candidates
never returns, stores, or logs the matched literal — only a SHA-256
fingerprint, byte length, pattern id, and span offsets survive.
record_secret_candidates writes AssertionKind.SECRET_CANDIDATE rows via
the shared upsert_assertion chokepoint with author_kind="detector",
which unconditionally coerces the row to a non-injectable CANDIDATE
status (the same invariant PATHOLOGY/TRANSFORM_CANDIDATE findings
already use — a detector can never self-promote a finding to
authoritative/injectable context).

polylogue/security/excision.py — standalone/off-mode excision,
authoritative. apply_session_excision removes a session's rows from
embeddings.db (message vectors), index.db (sessions cascades to
messages/blocks/session_links/FTS via ON DELETE CASCADE + triggers),
and source.db (blob_refs + raw_sessions, cascading to
raw_session_memberships/raw_membership_census), then records a durable
removed-hash marker per blob in the new excised_content table
(migration 011_excised_content.sql, SOURCE_SCHEMA_VERSION 10→11 --
renumbered from the original 9→10 during a master-sync merge that resolved
a genuine collision with another PR's independently-landed 010_*
migration; both additive migrations are kept, sinex_publication_obligations
at 010 and excised_content at 011) and
writes one AssertionKind.EXCISION_RECORD audit receipt to user.db
(reason, actor, removed hashes, per-tier counts). Content-bearing
assertions targeting the excised refs are removed too, so no dangling
annotation can quote deleted content. Blob bytes are never force-unlinked:
removing the referencing rows un-references the blob and the existing
reference-counted blob GC (polylogue-83u) reclaims it on its own next run
under its own lease discipline.

Anti-resurrection gate: write_source_raw_session
(polylogue/storage/sqlite/archive_tiers/source_write.py) is the single
acquire-time write choke point shared by the CLI polylogue import path
and the daemon polylogued run watch path (both funnel through
pipeline.services.archive_ingest.parse_sources_archive →
ArchiveStore.write_raw_and_parsed_result → write_source_raw_session). It
now checks is_blob_hash_excised before inserting and raises
ContentExcisedError on a match. write_pair in archive_ingest.py
catches this specifically and skips just that one file
(ParseResult.excised_skips) — a batch import is never aborted by an
excised file. No change was needed to the daemon's reprocess/materialize
path: it only ever operates on an already-stored raw_sessions row, so
once acquire refuses re-storage there is nothing left to reprocess.

polylogue/security/lifecycle.py — mirror/primary durable
lifecycle-request/outbox mechanics. A durable AssertionKind.EXCISION_REQUEST
row lives in user.db (never ops.db, so an ops reset cannot erase a
pending request). drive_lifecycle_request advances a pending → acknowledged → confirmed (or pending → rejected, terminal) state
machine against any ExcisionLifecycleContract. SinexContractFake is a
test-only fault-injecting implementation (can drop N requests to
simulate network loss, or force a rejection). primary_may_invalidate_locally
/ apply_primary_invalidation_if_confirmed guarantee primary-mode local
invalidation happens only after a confirmed state — a rejected,
still-pending, or unknown request always returns success=False with an
explicit reason and never touches the archive. A "process restart" is
modeled in tests by constructing a new SinexContractFake instance and
re-driving the same durable request id: the outcome is identical because
the durable row, not client memory, is authoritative.

polylogue ops excise CLI command
(--session ID --reason "..." [--dry-run] [--yes] [--mode standalone|mirror|primary] [--json]), following reset's
dry-run/confirm/--json conventions (MutationResultPayload).

Explicit non-goal (per the bead's own scope)

This PR does not claim a real Sinex purge, a clean Sinex rebuild,
disconnected-replica closure, or a backup-restore proof.
polylogue ops excise --mode mirror|primary only records the durable
local request today; nothing in this repository drives it against a real
Sinex confirmation yet. SinexContractFake is explicitly test-only.
Binding this mechanism to Sinex's real privacy_invalidation_scope, purge
authority, and non-resurrection proof across backups/replicas is tracked
separately as polylogue-303r.6, and a contract-fake-only test run must
never be read as satisfying that scope.

Verification

devtools verify --quick
# exit_code: 0 (ruff format/check, mypy --strict over 1968 files,
# render all --check with zero "out of sync" lines, verify
# layering/topology/manifests/closure-matrix)

devtools test tests/unit/security/test_secret_scan.py \
  tests/unit/security/test_excision.py \
  tests/unit/security/test_excision_lifecycle.py \
  tests/unit/cli/test_excise.py
# 41 passed in 77.97s

devtools test tests/unit/storage/test_durable_migrations.py
# 33 passed in 272.14s (confirms migration 010 applies cleanly from
# v1/v2/v3/v7 fixtures; 4 pre-existing tests needed their hardcoded
# applied_versions tuples/fixture DDL updated for the new version)

devtools test tests/unit/security/test_no_secret_leak_in_logs.py
# 2 passed (secret-log-hygiene AST guard -- confirms the new modules
# never interpolate a secret-shaped variable into a log/print call)

python3 -m devtools lab policy schema-versioning
# "Schema evolution policy intact."

Anti-vacuity notes:

  • test_reingest_does_not_resurrect_excised_content and
    test_reingest_batch_skips_excised_file_without_aborting exercise the
    real write_source_raw_session/ContentExcisedError gate through a
    real parse_sources_archive round trip built from the shared
    synthetic-corpus fixture generator (SyntheticCorpus/
    build_default_corpus_specs, the same machinery
    tests/unit/pipeline/test_archive_ingest_commit_batching.py uses) —
    not a hand-rolled JSONL literal. Removing the gate check, or reverting
    the write_pair skip-not-abort handling, makes these fail.
  • test_apply_removes_rows_from_every_tier asserts zero rows remain in
    each of sessions/messages/blocks/raw_sessions/blob_refs/
    message_embeddings/embedding_status against real archive-tier
    schemas; commenting out any one tier's delete in apply_session_excision
    makes the corresponding assertion fail.
  • test_rejection_cannot_report_success and
    test_pending_and_acknowledged_cannot_report_success assert
    LifecycleInvalidationOutcome.success is False with an explicit
    reason for every non-confirmed state; only
    test_confirmed_request_actually_excises_the_local_replica reaches
    success=True, and it verifies the session row is actually gone from
    index.db afterward.

Not run: the full non-integration suite (devtools verify --all) —
reserved for a final pre-merge diagnostic per repo convention; the
testmon-affected slice above plus verify --quick is the standard inner
loop.

Fix round (2026-07-14): adversarial review findings, Ref polylogue-layg

An independent adversarial review found four real issues, held this PR off
merge. All four are addressed on this branch:

  • BLOCKER — second write chokepoint bypassed the excision gate.
    write_source_raw_session checked is_blob_hash_excised before insert,
    but write_source_raw_session_blob_ref (the daemon's memory-bounded
    streaming write route for multi-GiB files, used via
    sources.live.batch.LiveBatchProcessor._ingest_full_records_archive) did
    not — a sibling real production write path could silently resurrect
    excised content. Fixed: the same gate now runs in both functions, and
    _ingest_full_records_archive catches ContentExcisedError and skips
    just that record (_ArchiveFullWriteResult.excised_skips), mirroring the
    CLI path's write_pair skip-not-abort handling. New regression coverage
    at both layers: test_blob_ref_reingest_does_not_resurrect_excised_content
    (direct function call) and
    test_full_ingest_skips_durably_excised_content_without_aborting_batch
    (full LiveBatchProcessor orchestration, anti-vacuity-checked by
    temporarily reverting the gate and confirming the test fails).

  • MAJOR — excision resolved only session_id-keyed rows, missing related
    rows.
    Two concrete gaps, both closed:

    • Lineage: a prefix-sharing lineage parent (fork/resume/auto-compaction)
      could be excised without touching its dependents, silently breaking
      every dependent child's composed transcript read (a dangling
      branch_point_message_id with no bytes behind it).
      apply_session_excision now resolves the full transitive
      prefix-sharing lineage (find_lineage_dependents) and refuses by
      default (LineageDependentsError) unless --cascade-lineage is
      passed, in which case the whole lineage is excised together.
      plan_session_excision/--dry-run surfaces dependents up front.
    • Attachments: blob_refs groups every blob published under one raw
      ingestion by a shared ref_id (ref_type IN ('raw_payload', 'attachment', 'sidecar')). The excised-content marker was previously
      recorded only for the raw payload's own hash, not an attachment's
      (which can differ) — so an attachment blob's blob_refs row was
      un-referenced and deleted, but not durably marked excised. Fixed:
      every distinct blob hash under the ref_id now gets its own marker.
      Verified separately (no code change needed, already correct):
      attachment_refs.session_id/message_id carry ON DELETE CASCADE to
      sessions/messages, so a content-hash-deduplicated attachment still
      referenced by a different, non-excised session is correctly left
      alone — only the excised session's own reference is removed.
  • MAJOR — security-privacy-coverage.yaml claimed
    captured_content_secret_detection: implemented: true without a
    production caller.
    True: secret_scan.py's regex/entropy rules and
    record_secret_candidates write path existed, but nothing in a running
    archive ever invoked them — only tests called the functions directly.
    Fixed by adding the missing production caller rather than downgrading the
    claim: scan_session_for_secret_candidates reads a session's real block
    text/tool-input from index.db and records real candidates, wired to a
    new polylogue ops scan-secrets --session <id> CLI command. The coverage
    doc now also states explicitly what implemented: true does not mean
    here: there is no bulk/archive-wide scan yet (an operator must invoke it
    per session id), tracked as a separate follow-up, polylogue-layg.1.

  • MINOR — one-shot sqlite3.connect() calls in excision.py omitted
    PRAGMA busy_timeout.
    Fixed via _connect_ro/_connect_rw helpers
    using the shared READ_DB_TIMEOUT/DB_TIMEOUT constants (same one-shot
    pattern already used in storage/blob_publication.py); applied to the
    new secret_scan.py connections too.

Verification for this round:

devtools test tests/unit/security/test_secret_scan.py \
  tests/unit/security/test_excision.py \
  tests/unit/security/test_excision_lifecycle.py \
  tests/unit/cli/test_excise.py tests/unit/cli/test_scan_secrets.py
# 61 passed in 77.49s

devtools test tests/unit/sources/test_live_batch_support.py \
  -k test_full_ingest_skips_durably_excised_content_without_aborting_batch
# 1 passed; anti-vacuity-checked (temporarily reverted the write gate,
# confirmed the test fails: assert 0 == 1)

devtools test tests/unit/sources/test_live_batch_support.py  # full file
# 17 pre-existing failures, byte-identical test names/assertions reproduced
# against the unmodified baseline (git stash of only this file) -- order/
# parallelism-sensitive flakiness unrelated to this change, not introduced
# by it

devtools verify --quick
# exit_code: 0 (ruff format/check, mypy --strict, render all --check with
# zero "out of sync" lines, topology/layering/closure-matrix/manifests/
# ci-workflows/doc-commands/test-infra-currency/test-clock-hygiene/
# pytest-timeout-overrides/degrade-loudly all ok)

Master-sync merge note. Master had moved 9 commits since this branch
diverged, including another PR's own 010_* source-tier migration
(sinex_publication_obligations) landing independently at
SOURCE_SCHEMA_VERSION 10 -- the exact version this PR also claimed for
excised_content. Resolved by renumbering this PR's migration to
011_excised_content.sql / SOURCE_SCHEMA_VERSION 11 (both tables kept,
sinex_publication_obligations first, excised_content second) and
updating the hardcoded applied_versions tuples in
tests/unit/storage/test_durable_migrations.py. Re-verified after the
merge: devtools test tests/unit/storage/test_durable_migrations.py (36
passed), devtools verify --quick (exit 0), devtools render all --check
(zero "out of sync" lines).

GitGuardian flags a "Generic High Entropy Secret" at
tests/unit/security/test_secret_scan.py ("token: ghp_" + "a" * 40, a
synthetic fixture matching the GitHub-token regex shape under test, not a
real credential; pre-existing from the base commit, out of this fix
round's scope). Triaged in a PR comment; not a required status check on
this repo.

Follow-ups

  • polylogue-303r.6 (already tracked, dependent of this bead): bind the
    mirror/primary local mechanics proven here to a real Sinex confirmation,
    purge, residual, rebuild, and backup non-resurrection proof.
  • polylogue-layg.1 (new, filed this round): add a bulk/archive-wide
    secret-candidate scan (CLI --all or a daemon convergence stage) so an
    operator does not have to already know which session id to scan.

Ref polylogue-27m. Ref polylogue-layg.

…e-27m)

Problem: the archive could not forget on purpose. There was no excision
mechanism at all (no code, no schema), and no candidate-only secret
detector for captured content -- both explicit gaps tracked by
polylogue-27m and the security-privacy-coverage.yaml
captured-content-secret-detection gap.

What changed:
- polylogue/security/secret_scan.py: candidate-only credential detector
  (AWS/GitHub/Slack/OpenAI/Anthropic key shapes, PEM headers, JWTs, an
  entropy-filtered generic key=value rule). Never returns/stores/logs the
  matched literal -- only a SHA-256 fingerprint, length, pattern id, and
  span offsets. Writes AssertionKind.SECRET_CANDIDATE via the shared
  upsert_assertion chokepoint with author_kind="detector", which
  unconditionally coerces the row to a non-injectable CANDIDATE status.
- polylogue/security/excision.py: standalone/off-mode local excision,
  authoritative. Removes a session from embeddings.db, index.db (FK
  cascade to messages/blocks/FTS/session_links), and source.db
  (blob_refs + raw_sessions), records a durable removed-hash marker, and
  writes one AssertionKind.EXCISION_RECORD audit receipt.
- polylogue/storage/sqlite/archive_tiers/source_write.py: new
  `excised_content` durable ledger (migration 010, SOURCE_SCHEMA_VERSION
  9->10) consulted at the single acquire-time write choke point
  (write_source_raw_session, shared by CLI import and the daemon watch
  path). A re-acquire of excised bytes raises ContentExcisedError instead
  of silently resurrecting the row.
- polylogue/pipeline/services/archive_ingest.py: `write_pair` catches
  ContentExcisedError and skips just that one file (ParseResult
  .excised_skips) instead of aborting the whole batch.
- polylogue/security/lifecycle.py: mirror/primary durable
  lifecycle-request/outbox mechanics (AssertionKind.EXCISION_REQUEST,
  user.db so an ops.db reset cannot erase it), proven against a
  fault-injecting SinexContractFake -- network-loss retry, restart
  recovers state from the durable row (not client memory), rejection can
  never report success, primary-mode invalidation happens only after a
  synthetic confirmation. Mechanism only: no real Sinex client exists
  here, and this bead does not claim a real Sinex purge, clean rebuild,
  disconnected-replica closure, or backup-restore proof (polylogue-303r.6
  owns binding this to a real Sinex confirmation).
- polylogue/cli/commands/excise.py: `polylogue ops excise --session ID
  --reason "..."` (--dry-run/--yes/--mode standalone|mirror|primary),
  following the reset command's dry-run/confirm/--json conventions.

Solution notes:
- write_source_raw_session is the correct single choke point: both the
  CLI `polylogue import` path and the daemon `polylogued run` watch path
  funnel through pipeline.services.archive_ingest.parse_sources_archive
  -> ArchiveStore.write_raw_and_parsed_result -> write_source_raw_session.
  No change to the daemon reprocess/materialize path was needed: it only
  operates on an already-stored raw_sessions row, so once the acquire gate
  refuses re-storage there is nothing left to reprocess.
- Excision does not force-unlink blob bytes: it removes the referencing
  blob_refs/raw_sessions rows and lets the existing reference-counted
  blob GC (polylogue-83u) reclaim them on its next run under its own
  lease discipline.
- Fixed 4 tests/unit/storage/test_durable_migrations.py assertions that
  hardcoded the prior SOURCE_SCHEMA_VERSION=9 applied_versions tuples/
  fixture DDL for migration 010.

Verification:
- devtools verify --quick -> exit_code 0 (ruff format/check, mypy --strict
  over 1968 files, render all --check with zero "out of sync" lines,
  verify layering/topology/manifests/closure-matrix/schema-versioning).
- devtools test tests/unit/security/test_secret_scan.py
  tests/unit/security/test_excision.py
  tests/unit/security/test_excision_lifecycle.py
  tests/unit/cli/test_excise.py -> 41 passed in 77.97s
- devtools test tests/unit/storage/test_durable_migrations.py -> 33
  passed in 272.14s (confirms migration 010 applies cleanly from v1/v2/v3/
  v7 fixtures)
- devtools test tests/unit/security/test_no_secret_leak_in_logs.py -> 2
  passed (secret-log-hygiene AST guard, unaffected by the new modules)
- python3 -m devtools lab policy schema-versioning -> "Schema evolution
  policy intact."
- Not run: the full non-integration suite (devtools verify --all) --
  reserved for the PR's pre-merge diagnostic per repo convention; the
  testmon-affected slice above plus verify --quick is the standard inner
  loop.

Ref polylogue-27m.

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

gitguardian Bot commented Jul 14, 2026

Copy link
Copy Markdown

⚠️ GitGuardian has uncovered 1 secret following the scan of your pull request.

Please consider investigating the findings and remediating the incidents. Failure to do so may lead to compromising the associated services or software components.

🔎 Detected hardcoded secret in your pull request
GitGuardian id GitGuardian status Secret Commit Filename
34803688 Triggered Generic High Entropy Secret 0665472 tests/unit/security/test_secret_scan.py View secret
🛠 Guidelines to remediate hardcoded secrets
  1. Understand the implications of revoking this secret by investigating where it is used in your code.
  2. Replace and store your secret safely. Learn here the best practices.
  3. Revoke and rotate this secret.
  4. If possible, rewrite git history. Rewriting git history is not a trivial act. You might completely break other contributing developers' workflow and you risk accidentally deleting legitimate data.

To avoid such incidents in the future consider


🦉 GitGuardian detects secrets in your source code to help developers and security teams secure the modern development process. You are seeing this because you or someone else with access to this repository has authorized GitGuardian to scan your pull request.

@coderabbitai

coderabbitai Bot commented Jul 14, 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: 52 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

Run ID: 55e308f5-e9c4-45c8-9d4c-6bd486ee1911

📥 Commits

Reviewing files that changed from the base of the PR and between 3796f54 and 3e99b07.

📒 Files selected for processing (32)
  • docs/cli-reference.md
  • docs/openapi/search.yaml
  • docs/plans/layering.yaml
  • docs/plans/security-privacy-coverage.yaml
  • docs/plans/topology-target.yaml
  • docs/schemas/cli-output/mutation-result.schema.json
  • docs/schemas/cli-output/query-unit-envelope.schema.json
  • docs/security.md
  • docs/topology-status.md
  • polylogue/cli/click_command_registration.py
  • polylogue/cli/commands/excise.py
  • polylogue/cli/commands/scan_secrets.py
  • polylogue/core/enums.py
  • polylogue/pipeline/payload_types.py
  • polylogue/pipeline/services/archive_ingest.py
  • polylogue/pipeline/services/parsing_models.py
  • polylogue/security/__init__.py
  • polylogue/security/excision.py
  • polylogue/security/lifecycle.py
  • polylogue/security/secret_scan.py
  • polylogue/sources/live/batch.py
  • polylogue/storage/sqlite/archive_tiers/source.py
  • polylogue/storage/sqlite/archive_tiers/source_write.py
  • polylogue/storage/sqlite/migrations/source/011_excised_content.sql
  • polylogue/surfaces/payloads.py
  • tests/unit/cli/test_excise.py
  • tests/unit/cli/test_scan_secrets.py
  • tests/unit/security/test_excision.py
  • tests/unit/security/test_excision_lifecycle.py
  • tests/unit/security/test_secret_scan.py
  • tests/unit/sources/test_live_batch_support.py
  • tests/unit/storage/test_durable_migrations.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/security/excision-secret-hygiene-27m

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.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

Sinity and others added 2 commits July 14, 2026 11:56
Ref polylogue-layg (adversarial review of #2875, polylogue-27m).

Problem: an independent adversarial review of the local-excision/secret-
hygiene PR found the non-resurrection guarantee was bypassable through a
second write chokepoint, excision left lineage-dependent sessions and
sibling attachment blobs uncovered, and the secret scanner had zero
production callers despite the coverage doc claiming implemented:true.

What changed:
- write_source_raw_session_blob_ref (the daemon's memory-bounded streaming
  write route) now gates on is_blob_hash_excised before insert, matching
  write_source_raw_session. LiveBatchProcessor._ingest_full_records_archive
  catches ContentExcisedError from either route and skips just that record
  (_ArchiveFullWriteResult.excised_skips), mirroring the CLI path's
  write_pair skip-not-abort handling.
- apply_session_excision now resolves the transitive prefix-sharing lineage
  of a target session (find_lineage_dependents) and refuses by default
  (LineageDependentsError) rather than silently deleting bytes a
  fork/resume child's composed transcript depends on; --cascade-lineage
  excises the whole lineage together. plan_session_excision/--dry-run
  surfaces dependents up front.
- _apply_single_session_excision now records an excised_content marker for
  every distinct blob hash grouped under a raw ingestion's ref_id, not just
  the raw payload's hash -- blob_refs shares one ref_id across
  ref_type IN ('raw_payload', 'attachment', 'sidecar'), so an attachment's
  own content hash (which can differ from the raw payload's) now gets its
  own non-resurrection marker. Verified attachment_refs.session_id/
  message_id already CASCADE on session delete, so a shared (still
  referenced by another session) attachment row is correctly left alone.
- Added scan_session_for_secret_candidates (secret_scan.py) as the real
  production entrypoint, wired to `polylogue ops scan-secrets --session
  <id>` (new cli/commands/scan_secrets.py). Previously the regex/entropy
  rules and non-injectable write path existed but nothing in a running
  archive ever called them. security-privacy-coverage.yaml now documents
  the verified scope of implemented:true (real detection + real production
  caller) versus what it does NOT mean (no bulk/archive-wide scan yet,
  tracked as polylogue-layg.1).
- One-shot sqlite3.connect() calls in excision.py/secret_scan.py now set
  PRAGMA busy_timeout explicitly (via _connect_ro/_connect_rw helpers and
  the shared READ_DB_TIMEOUT/DB_TIMEOUT constants), matching every other
  one-shot write chokepoint in the codebase (e.g. blob_publication.py).

Verification:
  devtools test tests/unit/security/test_secret_scan.py
    tests/unit/security/test_excision.py
    tests/unit/security/test_excision_lifecycle.py
    tests/unit/cli/test_excise.py tests/unit/cli/test_scan_secrets.py
  # 61 passed in 77.49s

  devtools test tests/unit/sources/test_live_batch_support.py
    -k test_full_ingest_skips_durably_excised_content_without_aborting_batch
  # 1 passed; anti-vacuity checked by temporarily reverting the
  # write_source_raw_session gate -- test fails (assert 0 == 1) as expected,
  # confirming it exercises the real gate through the full daemon
  # orchestration path, not a mock.

  devtools test tests/unit/sources/test_live_batch_support.py (full file)
  # 17 pre-existing failures reproduced identically against the unmodified
  # baseline (git stash of this file, same 17 test names/assertions) --
  # unrelated order/parallelism-sensitive flakiness in this large file, not
  # caused by this change.

  devtools verify --quick
  # exit_code: 0 (ruff format/check, mypy --strict, render all --check
  # zero "out of sync" lines, topology/layering/closure-matrix/manifests/
  # ci-workflows/doc-commands/test-infra-currency/test-clock-hygiene/
  # pytest-timeout-overrides/degrade-loudly all ok)

Not run: full devtools verify --all (reserved for final pre-merge
diagnostic per repo convention).

Co-Authored-By: Claude <[email protected]>
…cision-secret-hygiene-27m

# Conflicts:
#	docs/plans/topology-target.yaml
#	polylogue/storage/sqlite/archive_tiers/source.py
@Sinity

Sinity commented Jul 14, 2026

Copy link
Copy Markdown
Owner Author

GitGuardian false positive triage: the flagged "Generic High Entropy Secret" at tests/unit/security/test_secret_scan.py (originally line 51, commit 0665472) is "token: ghp_" + "a" * 40 — a synthetic all-repeated-character string built specifically to match the GitHub-token shape the regex detector under test looks for. It is not, and cannot be, a real credential. This is a pre-existing test fixture from the base commit, not introduced by the fix-round commits on this branch; not modifying it as part of this fix round since it's out of the four findings' scope, but flagging the triage here so it isn't mistaken for an unaddressed real leak.

GitGuardian is not a required status check on this repo (no required_status_checks configured in branch protection), so it does not block merge.

@Sinity
Sinity merged commit c2fd1e9 into master Jul 14, 2026
1 of 2 checks passed
@Sinity
Sinity deleted the feature/security/excision-secret-hygiene-27m branch July 14, 2026 11:14
Sinity added a commit that referenced this pull request Jul 14, 2026
Ref polylogue-t0dy, polylogue-lkrc.3, polylogue-hleq.

Summary: fixes a TOCTOU race in repair_duplicate_raw_identity's apply-mode
receipt write (was a single unlocked write_text() gated only by a racy
exists-check; now uses this codebase's established locked/atomic receipt
pattern). Fixes a stale-read bug in the byte-frontier competing-head branch
of _browser_canonical_authority_conflict_witness, which re-read the
competing raw mid-function without re-proving it against the original
proof snapshot. inspect_browser_canonical_authority_conflicts() and
record_browser_canonical_authority_conflict_blockers() give lkrc.3 a
structured evidence path for conflicting browser canonical authority
(competing head hash/frontier_kind/decision, blocking membership row) as a
durable candidate assertion.

Verification: focused suites for both new actuators, devtools verify
--quick 15/15. Independent adversarial re-review approved, with two
documented gaps: the operator-judged-row guard test doesn't fully exercise
the new read_assertion_envelope check (tracked as a fast-follow, same
pattern as #2875's test-tightening item), and the apply path doesn't
acquire RebuildLease unlike its two sibling actuators (also tracked).
Neither blocks merge; both are test/hardening tightening on already-real
production code, independently confirmed present via direct diff review.
Sinity added a commit that referenced this pull request Jul 14, 2026
## Summary

Closes three small pieces of independent-reviewer-flagged residual debt
from Wave 1's merged clusters (excision #2875, raw-identity #2877, sinex
evidence mode #2873). Done directly, without a separate
implementer/reviewer Workflow round, per operator instruction.

## Problem

Each item is a real gap an independent adversarial reviewer found in an
already-merged PR:

- **polylogue-re4a**: the excision-bypass regression test routed through
the pre-existing small-payload gate, never touching the new streaming
blob-ref gate it claimed to prove.
- **polylogue-iwth**: (1) the operator-judgment-guard test asserted only
fields that are deterministically identical whether or not the guard
fires, so it would pass even with the guard removed; (2)
`repair_duplicate_raw_identity`'s apply path skipped `RebuildLease`,
unlike its sibling actuators.
- **polylogue-ihwv**: sinex_mode's own fix was independently re-verified
correct (existing targeted tests green); two residual nits:
`material_adapter.py` silently dropped unrecognized blocks without
declaring a fidelity gap, and `ObligationStatus.PUBLISHING` was declared
but never written.

## Solution

- `tests/unit/sources/test_live_batch_support.py`: patch
`_STREAMING_FULL_INGEST_BYTES` down to 1 (existing pattern in this file)
so the excised/normal fixtures route through the blob-ref write path.
Verified as a genuine anti-vacuity check with an in-memory `mock.patch`
on `is_blob_hash_excised` (not a file edit to the production gate — the
auto-mode classifier correctly blocked that as a security-weakening
action).
- `tests/unit/storage/test_browser_capture_origin_repair.py` +
`polylogue/storage/repair.py`: added an `updated_at_ms`-unchanged
assertion — the one field `upsert_assertion`'s `ON CONFLICT` always
moves regardless of the guard, so it's the only observable proof the
guard short-circuited before writing. Verified as a genuine negative
control with an in-memory mock (side_effect returning `None` only for
the guard's own read, real behavior otherwise) — bypassing the guard
moves `updated_at_ms` as predicted. Wrapped
`repair_duplicate_raw_identity`'s apply block in
`RebuildLease(archive_root)`.
- `polylogue/sinex/material_adapter.py` + test:
`session_material_from_session` now emits a
`FidelityGapInput(gap_kind="dropped_block")` per dropped block. Extended
the existing fixture's assertions (it already had a
`"not-a-real-block-type"` block commented "must be dropped, not raise").
- `polylogue/sinex/obligations.py` + `service.py` + test: added
`mark_publishing()`, a pre-attempt transition distinct from
`mark_attempt` (no attempt_count/receipt outcome yet).
`PublicationService._attempt` now durably marks the obligation
`PUBLISHING` immediately before the transport call, in its own short
transaction, so a crash mid-attempt is now observably distinguishable
from a never-tried `pending` row — consistent with `pending()`/`lag()`
already including `PUBLISHING` in their filters.

## Verification

- `devtools test tests/unit/sources/test_live_batch_support.py -k
test_full_ingest_skips_durably_excised_content_without_aborting_batch` —
1 passed
- `devtools test
tests/unit/storage/test_browser_capture_origin_repair.py -k
test_record_conflict_blockers_never_clobbers_an_operator_judged_row` — 1
passed
- `devtools test
tests/unit/storage/test_duplicate_raw_identity_repair.py` — 13 passed
- `devtools test tests/unit/sinex/` — 25 passed
- `devtools verify --quick` — exit 0, all 16 steps green

Ref polylogue-re4a. Ref polylogue-iwth. Ref polylogue-ihwv.
Sinity added a commit that referenced this pull request Jul 14, 2026
Problem: rebasing feature/refactor/sqlite-leak-sweep-and-staleness-unify
onto origin/master (which gained #2875/#2876/#2877 since this branch was
cut) produced conflicts in the generated topology-target.yaml and
topology-status.md artifacts. Both sides had regenerated these
independently from source, so a manual merge would desync them from the
actual module graph.

What changed: resolved the conflicts with a placeholder (--ours), then
ran `devtools render topology-projection && devtools render
topology-status` to regenerate both files from the post-rebase source
tree, matching this repo's documented policy for generated-surface
conflicts.

Verification: `devtools render all --check` reports no "out of sync"
lines (all surfaces sync OK).
Sinity added a commit that referenced this pull request Jul 14, 2026
…enter decomposition (#2900)

## Summary

Implements the Architecture cluster (polylogue-1r9c + a7xr
features/bugs):
a source-grounded hotspot map for Polylogue's largest execution control
centers with a first coherent extraction slice landed against it, plus
six real bugs/features from the a7xr substrate-consolidation set.

## Problem

Production Python grew from ~255k to ~281k lines while the largest
execution hubs (storage tier, API facade, daemon HTTP, write tier,
storage
repair) kept expanding faster than the codebase average, with no
committed
map of their call boundaries, ownership seams, or a prioritized
decomposition sequence. Alongside that, a cluster of real substrate bugs
and abstraction-audit findings (sqlite connection leaks, a
converger/repair
staleness disagreement, dead abstractions with zero production
consumers,
a hard-coded write-effects choke point) had accumulated as separately
tracked beads.

## Solution

**polylogue-1r9c** (`docs/architecture-hotspots.md`, new): maps all
eight
named control centers with file:line evidence,
call-boundary/ownership-seam
analysis, and a prioritized extraction sequence with explicit non-goals.
Lands one coherent slice: `session_annotations_write.py` extracts the
self-contained session tag/work-event/phase CRUD contract out of
`storage/sqlite/archive_tiers/write.py` (4,595 → 4,210 lines, −8.4%),
with
`write.py` re-exporting the same public names unchanged (no duplicate
execution path). Files seven durable child beads for the remaining seven
control centers (`polylogue-redt`, `-u5dw`, `-1vzf`, `-gikp`, `-kchb`,
`-avmq`, `-w9di`), each with an explicit non-goal. The layering-policy
fix
this required also corrected a pre-existing, now-exposed imprecision in
`archive_tiers/archive.py`'s `raw-revision-authority` twin-write
contract
(a coarse tier-attribution artifact, not a behavior change).

**polylogue-0aj** (write-effects registry, slice 1 of 2):
`archive/write_effects.py`'s
hard-coded FTS-repair/cache-invalidation branches become a declared
`WriteEffect` registry (name, phase, should_run, failure_policy) that
the
choke point walks generically — behavior-identical for the three
existing
effects, with the phase/failure-policy declarations now explicit for
future
consumers (embedding scheduling, SSE announce) to register against.

**polylogue-yp0** (daemon event bus, partial — honestly not fully
closed):
lands the typed in-process pub/sub core (`daemon/event_bus.py`, 5 event
types, full failure-isolation test coverage) but not a live
producer/consumer
wiring — that's sequenced as follow-up (`polylogue-14t7`) per the bead's
own
design note, since touching a live daemon polling loop needs its own
focused
pass against the lock/starvation invariants `polylogue-9e5.7` mapped.

**polylogue-c9y** (package-topology doctrine): `docs/architecture.md`'s
placement rules become an 8-question decision procedure with worked
examples, plus the insights-vs-analytics vocabulary rule recorded ahead
of
`analytics/` landing. `core/` absorbs the former top-level `errors.py`/
`protocols.py`/`types.py` (165 import sites updated, zero behavior
change).

**Prior-session work on this branch** (a7xr.1/.2/.10/.13/.14/.17, all
committed before this PR turn but included here): sqlite connection-leak
sweep across ~9 sites, unified `session_profile_stale_predicate` between
converger and repair, killed the zero-consumer FTS5/Hybrid
search-provider
lane, deleted the api/contracts shadow-adapter layer, collapsed the
one-operation operations-contract framework to concrete Import models,
and
added an import-resolution drift gate for operation/artifact catalog
`code_refs`.

**Discovered, filed, not fixed in this PR** (out of scope for this
cluster, flagged rather than silently absorbed): `polylogue-0puw` (a
stale
`blob_publication_reservations` row survives an ingest batch that should
drain it — confirmed pre-existing, reproduces with `write_effects.py`
reverted), `polylogue-g99u` (`'codex' is not a valid Origin` ValueError
in two facade contract tests — confirmed unrelated to the write-tier
extraction, the extracted code never touches origin/provider
resolution),
and `polylogue-ihp0`
(`test_fresh_user_tier_has_no_legacy_overlay_tables`
asserts a stale exact table-set literal that migrations 007/008 — both
merged well before this branch's own base commit — already invalidated;
confirmed pre-existing via `git merge-base --is-ancestor`, unrelated to
the `session_annotations_write.py` extraction which the dedicated
write-tier suite proves behavior-identical, 63/63).

**Rebase onto current `origin/master`** (post-review): this branch was
3 commits behind `origin/master` (missing #2875/#2876/#2877) when first
opened, with GitHub reporting `mergeable: CONFLICTING`. Rebased cleanly;
resolved a trivial resolve-both import-block conflict in
`polylogue/api/archive.py` (this branch's
`protocols.py`→`core/protocols.py`
move landed on the same import line master's Hermes-delivery-correlation
import touched) and regenerated the two generated-artifact conflicts
(`docs/plans/topology-target.yaml`, `docs/topology-status.md`) via
`devtools render topology-projection && devtools render topology-status`
rather than merging them by hand. Also closed a self-consistency gap in
`polylogue-a7xr.10`'s own acceptance criteria: its FTS5/Hybrid provider
kill decision requires `polylogue-mhx.3` to record that it now owns lane
construction now that the shared `SearchProvider` abstraction is gone —
that note was missing and has been appended.

## Verification

- `devtools verify --quick` green end to end (ruff format/check, `mypy
--strict`,
  `render all --check` with zero "out of sync"/"unindexed" findings,
  topology/layering/closure-matrix/manifests/ci-workflows/doc-commands/

test-infra-currency/test-clock-hygiene/pytest-timeout-overrides/degrade-loudly
  all pass) — run repeatedly across the session, last clean at HEAD.
- `devtools test tests/unit/archive/test_write_effects.py
tests/unit/archive/test_write_gateway.py`
  — 12 passed (new registry tests + full existing gateway suite).
- `devtools test tests/unit/storage/test_archive_tiers_write.py
tests/unit/storage/test_archive_tiers_self_verify.py`
  — 64 passed (full behavioral parity for the write-tier extraction).
- `devtools test tests/unit/storage/test_revision_replay.py` — 16 passed
  (covers `apply_raw_membership_classification`, the entrypoint whose
  layering contract was corrected).
- `devtools test tests/unit/daemon/test_event_bus.py` — 10 passed (event
  bus pub/sub core, failure isolation, immutability).
- `devtools render topology-projection && devtools render
topology-status`
  regenerated for every new module (`session_annotations_write.py`,
  `daemon/event_bus.py`).
- Three pre-existing, unrelated test failures found and filed as
follow-ups
  rather than silently ignored (`polylogue-0puw`, `polylogue-g99u`,
`polylogue-ihp0`) — all confirmed to reproduce independent of this PR's
  changes (`ihp0` additionally confirmed via `git merge-base
  --is-ancestor` to predate this branch's base commit).
- Post-rebase re-verification: `devtools verify --quick` green again
  (39.76s, 15/15 steps); `devtools test` across the branch's new/touched
  test files (`test_write_effects.py`, `test_event_bus.py`,
  `test_session_profile_staleness_predicate.py`,
  `test_sqlite_connection_hygiene.py`, `test_code_refs_resolve.py`) —
  232 passed; `tests/unit/storage/test_archive_tiers_write.py` — 63
  passed (write-tier extraction behavioral parity, re-confirmed
  post-rebase).

## Not run

Full `devtools verify --all` / broad directory test sweeps (per repo
policy — testmon-affected/focused selection is the default, not blanket
directory runs). Per-PR CI is disabled repo-wide (billing-locked).

---------

Co-authored-by: Claude <[email protected]>
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