Skip to content

feat(lock): near-duplicate lock-dedup hygiene at write time + audit (#1016) - #1035

Merged
github-actions[bot] merged 2 commits into
mainfrom
feat/issue-1016-lock-dedup-hygiene
Jun 30, 2026
Merged

feat(lock): near-duplicate lock-dedup hygiene at write time + audit (#1016)#1035
github-actions[bot] merged 2 commits into
mainfrom
feat/issue-1016-lock-dedup-hygiene

Conversation

@robotrocketscience

@robotrocketscience robotrocketscience commented Jun 30, 2026

Copy link
Copy Markdown
Owner

Part of #1016 — the #1016-C (lock hygiene) sub-task. Does not close the umbrella (frozen/reference tiers, lock-vs-hook docs remain).

Why

Locks are injected unbounded and never trimmed (#379), so re-locking slightly-reworded ground truth quietly accumulates near-duplicate locks that inflate the injection budget (#1016). Evidence on the real 24-lock store: a 3-lock cluster that is one fact ("v3.0 #592 eval-harness status") re-locked with κ/kappa wording drift (pairwise J≥0.92, L≥0.88) — 12.5%, matching the ~14% estimate. 2 of those 3 are redundant.

Design note — dedup, not distillation

The issue's AC-C originally framed hygiene as "char-cap / distillation." Prior R&D found distillation weak (locks are already dense, ~1.08× compression) and dedup/supersession the real lever, so this implements dedup. Flagging the deviation explicitly.

What

Reuses the existing dedup engine (Jaccard ≥ 0.8 AND Levenshtein ≥ 0.85) — no new similarity code:

  1. Write-time guardrailaelf lock prints a hygiene warning when the new lock near-duplicates an existing lock, naming it and suggesting aelf unlock/aelf delete. Warning only; the lock still writes (it is user-asserted ground truth).
  2. Backlog auditaelf doctor --dedup --dedup-locks scopes the dedup audit to the user-locked set, so the existing cluster is findable without wading through the full-store report. Live store shows the 3-member cluster.

New dedup.find_near_duplicate_locks() + a locked_only flag on dedup_audit(). The default full-store audit is byte-identical. No belief is auto-deleted — locks are ground truth, so cleanup stays user-confirmed.

Tests

tests/test_dedup.py: find_near_duplicate_locks (finds / excludes self / ignores unlocked / below-threshold / blank), dedup_audit(locked_only=True) (scopes to locks, default unchanged), and a --dedup-locks CLI test. tests/test_cli_lock_via_worker.py: write-time warning fires on a near-dup and stays silent otherwise.

Verification

  • pytest tests/test_dedup.py tests/test_cli_lock_via_worker.py tests/test_lock_management.py tests/test_lock_contract.py tests/test_slash_commands.py → 249 passed, 1 skipped.
  • uvx vulture … --min-confidence 80 → clean. uvx typos → clean.
  • Live: aelf doctor --dedup --dedup-locks surfaces the 3-lock cluster.

🤖 Generated with Claude Code

Summary by Sourcery

Add lock-scoped near-duplicate detection and auditing to improve lock hygiene without changing existing dedup behavior.

New Features:

  • Introduce write-time near-duplicate detection for aelf lock that warns when a new lock closely matches existing user-locked beliefs.
  • Add a lock-scoped dedup audit mode via aelf doctor --dedup --dedup-locks that limits the report to user-locked beliefs.

Enhancements:

  • Extend the dedup engine with find_near_duplicate_locks and a locked_only option on dedup_audit while keeping the default full-store audit unchanged.
  • Update CLI doctor and lock commands to surface lock-specific dedup information, including a flag to scan only locked beliefs and a summary note in the output.

Documentation:

  • Document the new lock-dedup hygiene behavior and lock-scoped audit in the v3 changelog.

Tests:

  • Add unit and CLI tests covering lock near-duplicate detection, the locked-only dedup audit mode, and the new --dedup-locks flag.

Summary by CodeRabbit

  • New Features

    • aelf lock now warns when a new lock is very similar to an existing one, helping prevent duplicate locks from piling up.
    • aelf doctor --dedup-locks adds a locked-only deduplication scan for checking user-locked beliefs separately.
  • Bug Fixes

    • Improved duplicate detection so near-matches are reported more clearly, while locked items are not automatically removed.

…1016)

Locks are injected unbounded and never trimmed (#379), so re-locking
slightly-reworded ground truth accumulates near-duplicate locks that
inflate the injection (a real 24-lock store had a 3-lock cluster = one
fact re-locked with wording drift, 12.5%). Implement the #1016-C
sub-task as dedup (the R&D-validated lever; distillation tested weak),
reusing the existing dedup engine (Jaccard>=0.8 AND Levenshtein>=0.85):

- aelf lock warns when the new lock near-duplicates an existing one,
  naming it and suggesting unlock/delete. Warning only; the lock still
  writes (user ground truth).
- aelf doctor --dedup --dedup-locks scopes the audit to locked beliefs
  so the backlog cluster is findable.

New dedup.find_near_duplicate_locks() + a locked_only flag on
dedup_audit() (full-store audit byte-identical by default). No
auto-delete: cleanup stays user-confirmed.
@sourcery-ai

sourcery-ai Bot commented Jun 30, 2026

Copy link
Copy Markdown

Reviewer's Guide

Implements lock-specific dedup hygiene by reusing the existing similarity engine: write-time near-duplicate warnings for aelf lock, and a lock-scoped dedup audit mode exposed via aelf doctor --dedup --dedup-locks, with tests and changelog updates.

Sequence diagram for aelf lock write-time near-duplicate warning

sequenceDiagram
    actor User
    participant CLI as _cmd_lock
    participant Store as MemoryStore
    participant Dedup as find_near_duplicate_locks

    User->>CLI: aelf lock --statement
    CLI->>Store: lock_belief
    Store-->>CLI: actual_id
    CLI->>Dedup: find_near_duplicate_locks(store, statement, exclude_id=actual_id)
    Dedup->>Store: _locked_beliefs_for_indexing(store)
    Store-->>Dedup: list_locked_beliefs
    Dedup-->>CLI: [DuplicatePair]
    alt [near_dups is non-empty]
        CLI->>User: print warning about near-duplicate locks
    else [near_dups is empty]
        CLI->>User: no hygiene warning
    end
Loading

File-Level Changes

Change Details Files
Add lock-scoped near-duplicate detection helper that scans only locked beliefs and returns similarity-scored pairs for a candidate text.
  • Introduce _locked_beliefs_for_indexing to return active locked beliefs as (id, content) sorted by id ASC for dedup pairing
  • Implement find_near_duplicate_locks that tokenizes a candidate lock statement, compares it against locked beliefs using existing Jaccard and Levenshtein thresholds, and returns sorted DuplicatePairs excluding a specified id
  • Ensure blank candidate text and blank locked contents are ignored and results are ordered by strongest match
src/aelfrice/dedup.py
Extend the dedup audit to optionally operate on locked beliefs only and wire this mode into the aelf doctor CLI.
  • Add locked_only boolean parameter to dedup_audit and keep default behavior identical to the previous full-store scan
  • Use _locked_beliefs_for_indexing when locked_only=True, otherwise continue using list_beliefs_for_indexing
  • Update _cmd_doctor_dedup to parse a new --dedup-locks flag, pass locked_only through to dedup_audit, and print an explanatory line when lock-only mode is enabled
  • Add CLI argument definition for --dedup-locks with help text describing lock hygiene intent
src/aelfrice/dedup.py
src/aelfrice/cli.py
Add write-time lock hygiene warning to the aelf lock command when the new lock is near-duplicate of existing locked beliefs. src/aelfrice/cli.py
Add unit tests covering lock-specific dedup behavior, lock-only audit mode, CLI flag behavior, and lock-time warning semantics.
  • Introduce _insert_lock helper for creating locked beliefs in tests
  • Add TestFindNearDuplicateLocks verifying detection, self-exclusion, ignoring unlocked beliefs, threshold behavior, and blank-text handling
  • Add TestDedupAuditLockedOnly verifying that lock-only mode ignores unlocked near-dups, finds locked clusters, leaves default audit unchanged, and that --dedup-locks CLI reports scoped stats
  • Add CLI tests in test_cli_lock_via_worker.py verifying that locking a near-duplicate emits a hygiene warning referencing the prior lock and issue number, and that non-duplicates emit no warning
tests/test_dedup.py
tests/test_cli_lock_via_worker.py
Document the new lock-dedup hygiene feature in the v3 changelog.
  • Add an "Added" entry describing near-duplicate detection at lock time, the lock-scoped dedup audit, reuse of the existing dedup engine, and non-destructive nature of cleanup
CHANGELOG/v3.md

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@github-actions

github-actions Bot commented Jun 30, 2026

Copy link
Copy Markdown

PR-size soft cap

This PR is over the advisory size threshold:

  • 274 changed lines (limit: 200)
  • 5 changed files (limit: 3)

Bigger PRs collide with more open work, which under the parallel-session workflow tends to produce repeated attn:merge-conflict cycles (see #602). When practical, split into smaller PRs that each touch a focused surface.

This is advisory only — nothing is blocked. If the size is intentional (large refactor, module removal, generated code), apply the size:override label and this comment will be removed on the next push.

@sourcery-ai sourcery-ai 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.

Hey - I've found 1 issue, and left some high level feedback:

  • The find_near_duplicate_locks path does a full scan over all locked beliefs on every lock write; if the locked set grows large this could become noticeably slow, so consider a configurable cap, early-exit behavior, or reusing any existing index/FTS machinery to bound the cost.
  • dedup_audit(locked_only=True) currently signals the scope only via a separate CLI print; if you expect other callers or tooling to use this mode, it may be clearer to surface the locked_only flag directly in DedupAuditReport so consumers can inspect the scope programmatically.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The `find_near_duplicate_locks` path does a full scan over all locked beliefs on every lock write; if the locked set grows large this could become noticeably slow, so consider a configurable cap, early-exit behavior, or reusing any existing index/FTS machinery to bound the cost.
- `dedup_audit(locked_only=True)` currently signals the scope only via a separate CLI print; if you expect other callers or tooling to use this mode, it may be clearer to surface the `locked_only` flag directly in `DedupAuditReport` so consumers can inspect the scope programmatically.

## Individual Comments

### Comment 1
<location path="src/aelfrice/cli.py" line_range="4975" />
<code_context>
         ),
     )

+    locked_only = bool(getattr(args, "dedup_locks", False))
     store = _open_store()
     try:
</code_context>
<issue_to_address>
**nitpick:** The `getattr`/`bool` wrapping around `args.dedup_locks` seems unnecessary.

Because this argument is declared with `action="store_true"` and `default=False`, `args.dedup_locks` should always be present and already boolean. Unless there is a known caller that omits it, using `locked_only = args.dedup_locks` would be clearer and would surface any unexpected missing attribute instead of silently defaulting to `False`.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread src/aelfrice/cli.py Outdated
@coderabbitai

coderabbitai Bot commented Jun 30, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@robotrocketscience, 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: CHILL

Plan: Pro

Run ID: f7e7cc36-2672-4345-aa68-2aac685daafb

📥 Commits

Reviewing files that changed from the base of the PR and between 2a7acd4 and 33548e9.

📒 Files selected for processing (1)
  • src/aelfrice/cli.py
📝 Walkthrough

Walkthrough

Adds lock-dedup hygiene: a new find_near_duplicate_locks() function scans existing user-locked beliefs for near-duplicates at lock time and emits a warning. dedup_audit() gains a locked_only parameter, and a new --dedup-locks CLI flag restricts the dedup audit to the locked belief set only.

Changes

Lock dedup hygiene

Layer / File(s) Summary
dedup.py: find_near_duplicate_locks and locked_only audit
src/aelfrice/dedup.py
Adds _locked_beliefs_for_indexing() helper, new public find_near_duplicate_locks() using Jaccard + Levenshtein thresholds with optional exclude_id, and extends dedup_audit() with locked_only: bool = False parameter that switches the belief scan source.
CLI wiring: post-lock warning, --dedup-locks flag, doctor integration
src/aelfrice/cli.py, CHANGELOG/v3.md
Post-lock scan calls find_near_duplicate_locks() and prints a warning with up to three near-duplicate ids. Adds --dedup-locks argparse flag and passes locked_only into dedup_audit in _cmd_doctor_dedup. Changelog updated.
Tests
tests/test_dedup.py, tests/test_cli_lock_via_worker.py
Covers find_near_duplicate_locks edge cases (self-exclusion, unlocked ignored, below-threshold, blank input), dedup_audit(locked_only=True) clustering, full-audit regression, and CLI integration for both the lock warning and --dedup-locks flag.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise, specific, and accurately summarizes the main lock hygiene and audit changes.
Description check ✅ Passed The description covers the why, behavior changes, tests, and verification, though it does not fully follow the template headings.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/issue-1016-lock-dedup-hygiene

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.

… review)

store_true already yields a bool; keep getattr for sibling-arg
consistency and direct-Namespace test safety. Addresses Sourcery.
@robotrocketscience robotrocketscience added the ready-to-merge Trigger merge-train: FF main to this PR's head label Jun 30, 2026
@github-actions
github-actions Bot merged commit 33548e9 into main Jun 30, 2026
29 checks passed
@github-actions github-actions Bot removed the ready-to-merge Trigger merge-train: FF main to this PR's head label Jun 30, 2026
@github-actions

Copy link
Copy Markdown

merge-train: merged 33548e9main via FF push.

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