Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,22 @@ All notable changes to SkillEvaluator are documented in this file.
dimensions, 362 at 4,096), which the incomplete-scan error and the JSON
`work_limit` record now report as `effective_chunk_limit`, next to the
skill's own `chunk_count`.
- Tier 2 context deduplication no longer stops skills with many repeated
sections at the `llm_cluster_member_limit` work limit. A candidate cluster
with more than 64 members was reported as incomplete even when its review
prompt fit the 64,000-character budget. The member limit now equals the
512-chunk ceiling, which the chunk check already enforces, so it is only a
guard and never stops a scan on its own; the per-cluster prompt, total
prompt, and cluster-count limits decide. When a cluster's request (system
prompt plus cluster text) would exceed 64,000 characters, each exactly
repeated text is sent once as `SHARED CONTENT n`. A Markdown section is
compared without its own heading line, so the same body under different
headings is shared too. Every occurrence keeps its own entry with its file,
section, line range, and heading line. Distinct text is never dropped or
sampled, so a cluster still over the budget stays incomplete with
`llm_prompt_size_limit`. Duplicate and `llm_refused` finding messages name
at most 64 member locations and source files and count the rest; the JSON
`source_files` list stays complete.
- Local-mode verifier uploads now copy directly to the absent destination,
avoiding an unnecessary rollback snapshot of an empty tests directory.
Inputs and rewritten scripts are prepared privately before publication,
Expand Down Expand Up @@ -459,8 +475,8 @@ All notable changes to SkillEvaluator are documented in this file.

- A skill that exceeds a Tier 2 context-deduplication work limit (more than
512 content chunks, too much pairwise comparison work, or an LLM-review limit:
more than 50 candidate clusters, more than 64 members in one cluster, or an
oversized per-cluster or total review prompt) is now reported as
more than 50 candidate clusters or an oversized per-cluster or total
review prompt) is now reported as
**INCOMPLETE** instead of failing with a CRITICAL `chunk_count_limit`,
`scalar_comparison_limit`, `llm_cluster_count_limit`,
`llm_cluster_member_limit`, `llm_prompt_size_limit`, or
Expand Down
25 changes: 22 additions & 3 deletions docs/tier2-deduplication.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -149,14 +149,29 @@ Duplicate findings map to severities by confidence:
| `DUPLICATE` with confidence < 0.70 | MEDIUM — advisory |
| Short, same-file duplicate dominated by comment or configuration-style text | Capped at LOW — advisory |

Each candidate cluster is reviewed in one chat-LLM request that carries every
member's file, section, line range, and text. When that request (the system
prompt plus the cluster text) would exceed 64,000 characters, text that repeats
exactly is listed once as `SHARED CONTENT n`. A Markdown section's text starts
with its own heading line, so the text compared is the body after that line:
the same body under different headings is listed once too. Each occurrence
keeps its own entry with its file, section, line range, and heading line, plus
a reference to the shared text. Distinct text, including text that differs by a
single character, is always sent in full; nothing is sampled or dropped to fit.
A cluster that is still over 64,000 characters stops the scan as incomplete
(`llm_prompt_size_limit`), as described below. A duplicate or
`llm_refused` finding names up to 64 member locations and source files and
counts the rest; its `source_files` metadata in the JSON report lists every
file.

If chat-LLM analysis fails for a candidate cluster, Tier 2 reports the
incomplete analysis as a blocking error rather than treating the content as
clean.

The same applies when a skill exceeds a work limit on content that was
already collected: the content-chunk or comparison-work limit, or a limit on
the LLM review (candidate clusters, members in one cluster, or prompt size per
cluster or in total). Tier 2 stops and reports the scan as **INCOMPLETE**, not
the LLM review (the number of candidate clusters, or prompt size per cluster
or in total). Tier 2 stops and reports the scan as **INCOMPLETE**, not
as a duplicate-content finding, with an execution error that names the limit;
the JSON report records it under `work_limit`. A policy severity override
cannot turn the incomplete scan into a pass. Split the skill or remove repeated
Expand Down Expand Up @@ -341,6 +356,10 @@ you intend to skip Tier 2 entirely.
| High-confidence duplicate boundary | `0.70` | Maps actionable duplicate verdicts to HIGH rather than MEDIUM |
| Intra-skill content chunks | 512 | Per-skill ceiling, checked before any embedding request |
| Intra-skill comparison work | 267,911,168 scalar comparisons | Bounds all-pairs clustering; allows all 512 chunks with embeddings of up to 2,048 dimensions, 418 chunks at 3,072, and 362 at 4,096 |
| Intra-skill LLM review clusters | 50 | Most candidate clusters sent for chat-LLM review in one skill |
| Intra-skill cluster members | 512 | Same as the chunk ceiling, so it never stops a scan on its own; the review prompt limits decide |
| Intra-skill review prompt | 64,000 characters | One cluster's request, system prompt included; exactly repeated text (a Markdown section's body after its heading line) is listed once before this limit applies |
| Intra-skill review prompts in total | 1,000,000 characters | All cluster requests for one skill, checked before the first chat-LLM call |

Intra-skill clustering compares every pair of chunks, so its work is
`n * (n - 1) / 2 * dimensions`. A skill over the chunk ceiling stops before any
Expand Down Expand Up @@ -400,7 +419,7 @@ handling terms before sending confidential skill content to a hosted endpoint.
| Skill carries large generated snapshots (`evals`, `.evals`, `results`, `.results`, `versions`, `.versions`) | Excluded directories are pruned during traversal, so their contents never count toward the discovered-path limit |
| A directory is a Windows junction or other reparse point | Rejected during the walk, like symbolic links |
| Embedding or chat-LLM analysis is incomplete | Reports an error; does not claim a clean result |
| Skill exceeds the content-chunk, comparison-work, or LLM-review limit (candidate clusters, cluster members, or prompt size) | Stops before the remaining analysis and reports the scan as incomplete; no duplicate-content finding is added |
| Skill exceeds the content-chunk, comparison-work, or LLM-review limit (candidate clusters or prompt size) | Stops before the remaining analysis and reports the scan as incomplete; no duplicate-content finding is added |
| The chat LLM declines to classify a cluster | Reports an advisory MEDIUM `llm_refused` finding for that cluster's sections |
</Accordion>
<Accordion title="Inter-skill analysis">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
CONTENT_DEDUP_SIMILARITY_THRESHOLD,
CONTENT_DEDUP_TRIVIAL_DUP_MAX_CHARS,
)
from skillevaluator.deduplication.intra_skill import llm_analyzer
from skillevaluator.deduplication.intra_skill.llm_analyzer import (
SYSTEM_PROMPT,
analyze_cluster,
Expand All @@ -48,9 +49,14 @@
# config assignment. Used to recognize repeated config/comment snippets.
_COMMENT_PREFIXES = ("#", ";", "//", "--", "!")
_CONFIG_KV_RE = re.compile(r"^[\w.\-/]+\s*[=:]\s*\S")
CONTENT_DEDUP_MAX_CLUSTER_MEMBERS = 64
CONTENT_DEDUP_MAX_LLM_PROMPT_CHARS = 64_000
# One cluster may hold every chunk of the scan. The per-call and aggregate
# prompt budgets bound paid review; a fixed member cap below the chunk ceiling
# would refuse large repeated-content clusters whose prompt fits.
CONTENT_DEDUP_MAX_CLUSTER_MEMBERS = CONTENT_DEDUP_MAX_CHUNKS
Comment thread
rng1995 marked this conversation as resolved.
Resolved
CONTENT_DEDUP_MAX_TOTAL_LLM_PROMPT_CHARS = 1_000_000
# Most member locations and source files named in one finding message. The
# rest are counted, so a finding for a 512-member cluster stays a few kilobytes.
_MAX_REPORTED_LOCATIONS = 64

# Scan label recorded when a work limit stops duplicate analysis early.
_WORK_LIMIT_SCAN = "context-deduplication"
Expand Down Expand Up @@ -112,6 +118,27 @@ def _is_trivial_intra_file_duplicate(cluster: ContentCluster) -> bool:
return all(_chunk_is_short_config(member) for member in cluster.members)


def _cluster_location_text(cluster: ContentCluster) -> tuple[str, str]:
"""Return the finding scope and member location list, bounded in length."""
distinct_files = sorted({c.source_file for c in cluster.members})
if len(distinct_files) == 1:
scope = f"within {distinct_files[0]}"
else:
scope = f"across {' and '.join(distinct_files[:_MAX_REPORTED_LOCATIONS])}"
if (omitted_files := len(distinct_files) - _MAX_REPORTED_LOCATIONS) > 0:
scope += f" and {omitted_files} more file{'s' if omitted_files != 1 else ''}"

locations = [
f'"{c.heading}" in {c.source_file} (lines {c.start_line}-{c.end_line})'
for c in cluster.members[:_MAX_REPORTED_LOCATIONS]
]
location_text = "\n vs ".join(locations)
if (omitted := len(cluster.members) - _MAX_REPORTED_LOCATIONS) > 0:
noun = "locations" if omitted != 1 else "location"
location_text += f"\n and {omitted} more {noun} ({len(cluster.members)} in total)"
return scope, location_text


def _mark_work_limit_incomplete(
result: ValidationResult,
check_name: str,
Expand Down Expand Up @@ -319,7 +346,9 @@ def validate(self, skill_path: Path, *, _collected_files: list[CollectedFile] |
),
(
prompt_chars,
CONTENT_DEDUP_MAX_LLM_PROMPT_CHARS,
# Read at call time: build_user_prompt shares repeated text
# against this same attribute, so one value sets both.
llm_analyzer.MAX_PROMPT_CHARS,
"llm_prompt_size_limit",
"an LLM review prompt of {actual} characters exceeds the limit of {limit}.",
),
Expand Down Expand Up @@ -418,15 +447,7 @@ def analyze_one(cluster):
continue

distinct_files = sorted({c.source_file for c in cluster.members})

locations = []
for c in cluster.members:
locations.append(f'"{c.heading}" in {c.source_file} (lines {c.start_line}-{c.end_line})')
location_text = "\n vs ".join(locations)
if len(distinct_files) == 1:
scope = f"within {distinct_files[0]}"
else:
scope = f"across {' and '.join(distinct_files)}"
scope, location_text = _cluster_location_text(cluster)

if verdict is None:
# Report the refused overlap so the author can review it, but
Expand Down
64 changes: 62 additions & 2 deletions src/skillevaluator/deduplication/intra_skill/llm_analyzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,22 @@

from __future__ import annotations

from collections import Counter
from typing import TYPE_CHECKING, Any

from skillevaluator.inference import LLMClient, LLMClientError, LLMVerdict
from skillevaluator.models.result import Severity

if TYPE_CHECKING:
from skillevaluator.deduplication.intra_skill.semantic_clustering import ContentCluster
from skillevaluator.deduplication.utils.chunker import ContentChunk

VALID_VERDICTS = {"DUPLICATE", "INTENTIONAL_DETAIL", "RELATED_BUT_DISTINCT"}

# Per-call budget for one review request: SYSTEM_PROMPT plus the user prompt.
# The validator refuses a cluster whose request is still over it.
MAX_PROMPT_CHARS = 64_000

VERDICT_JSON_SCHEMA: dict[str, Any] = {
"type": "object",
"properties": {
Expand Down Expand Up @@ -55,15 +61,69 @@


def build_user_prompt(cluster: ContentCluster) -> str:
"""Build the user prompt from cluster member chunks."""
"""Build the user prompt from cluster member chunks.

Every member is rendered with its full text. When the request
(``SYSTEM_PROMPT`` plus this prompt) would exceed ``MAX_PROMPT_CHARS``,
each exactly repeated text is listed once as ``SHARED CONTENT n``. A
Markdown section's text opens with its own heading line, so the text
compared is the body after that line: the same body under different
headings is listed once too. Every occurrence keeps its own ``CHUNK``
entry with file, section and lines, its own heading line, and a
``[SHARED CONTENT n]`` reference in place of the shared text. Distinct
text is never dropped or shortened, so a request still over budget stays
over budget.
"""
prompt = _render_user_prompt(cluster)
if len(SYSTEM_PROMPT) + len(prompt) <= MAX_PROMPT_CHARS:
return prompt
counts = Counter(_split_own_heading(chunk)[1] for chunk in cluster.members)
repeated = (text for text, count in counts.items() if count > 1)
shared = {text: index for index, text in enumerate(repeated, start=1)}
if not shared:
return prompt
compact = _render_user_prompt(cluster, shared)
return compact if len(compact) < len(prompt) else prompt


def _split_own_heading(chunk: ContentChunk) -> tuple[str, str]:
"""Return the chunk's own heading line and the text after it.

A Markdown section chunk opens with its heading line, so the same body
under different headings differs only in that line. Text that does not
open with the chunk's heading line, or has nothing after it, is returned
whole with an empty heading line. When a heading line is returned,
``heading_line + "\n" + body`` is exactly the chunk text.
"""
first_line, newline, body = chunk.text.partition("\n")
if newline and body.strip() and first_line.rstrip() == chunk.heading:
return first_line, body
return "", chunk.text


def _render_user_prompt(cluster: ContentCluster, shared: dict[str, int] | None = None) -> str:
"""Render every member; texts in ``shared`` are listed once and referenced."""
parts: list[str] = []
if shared:
parts.append(
"Identical content is listed once below. In a chunk's content, [SHARED CONTENT n] stands for "
"the exact text of that shared block. Review every occurrence in its own file, section and "
"line context. No chunks were omitted."
)
parts.extend(f"---SHARED CONTENT {index}---\n{text}" for text, index in shared.items())
for i, chunk in enumerate(cluster.members, start=1):
content = chunk.text
if shared:
heading_line, body = _split_own_heading(chunk)
if body in shared:
reference = f"[SHARED CONTENT {shared[body]}]"
content = f"{heading_line}\n{reference}" if heading_line else reference
parts.append(
f"---CHUNK {i}---\n"
f"File: {chunk.source_file}\n"
f"Section: {chunk.heading}\n"
f"Lines: {chunk.start_line}-{chunk.end_line}\n"
f"Content:\n{chunk.text}"
f"Content:\n{content}"
)

parts.append(f"\nEmbedding similarity: {cluster.max_similarity:.3f}")
Expand Down
Loading
Loading