Metadata-Version: 2.4
Name: sieve-referee
Version: 1.5.2
Summary: Deterministic, zero-dependency plagiarism and text structure screening engine (Sieve-Core plugin)
Author: Kai IWASAKI
License-Expression: MIT
Project-URL: Bug Tracker, https://github.com/neguseatama/sieve-referee/issues
Project-URL: Homepage, https://github.com/neguseatama/sieve-referee
Project-URL: Repository, https://github.com/neguseatama/sieve-referee.git
Project-URL: Related Project (Sieve-Core), https://github.com/neguseatama/sieve-core
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Education
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Text Processing :: Linguistic
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: sieve-core-engine>=1.0.0
Dynamic: license-file

# Sieve Referee v1.5.1

English | [日本語](README.ja.md)

> **"Should we really use probabilistic AI models to evaluate text generated by other probabilistic AI models?"**
> A fully local, zero-dependency, and deterministic (100% reproducible) text structure and plagiarism screening engine. Developed as an extended application of [Sieve-Core](https://github.com/neguseatama/sieve-core).

[![PyPI Version](https://img.shields.io/pypi/v/sieve-referee.svg)](https://pypi.org/project/sieve-referee/)
[![Python Version](https://img.shields.io/pypi/pyversions/sieve-referee.svg)](https://pypi.org/project/sieve-referee/)
[![CI](https://github.com/neguseatama/sieve-referee/actions/workflows/tests.yml/badge.svg)](https://github.com/neguseatama/sieve-referee/actions/workflows/tests.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)

---

## 💡 Concept & Philosophy

`Sieve-Core` is the core engine that applies the design philosophy of "Sieve-AI"—a "sieve of set theory" inspired by the Sieve of Eratosthenes—to the more general domain of text and data processing. `Sieve Referee`, designed by adding a "sieve of combinatorics" to this `Sieve-Core`, is a zero-dependency Python library that extracts reliable information from noise based on corroboration from multiple independent sources.

When evaluating text that may have been generated by probabilistic models (such as LLMs), relying on another probabilistic model to calculate a similarity score makes it difficult to mathematically trace *why* that score was produced.

`Sieve Referee` was built to address this problem: to ensure every judgment is mathematically traceable, 100% reproducible, and fully explainable.

- **Deterministic Approach**: Evaluation is based on a 16-state Look-Up Table (LUT with 15 classified states). Identical inputs always produce identical outputs no matter how many times it is run.
- **Explainable by Design**: Every result carries a `reason` string and a 4-bit hypothesis `mask`, so the basis of a judgment can always be inspected.
- **Careful Classification to Avoid False Accusations**: A shared template or boilerplate format is classified separately as `COINCIDENTAL_FORMAT_MATCH` (`1100` / `YELLOW`), rather than being treated the same as an actual content match.
- **Indirect ("Telephone Game") Chain Safety**: A pair with no direct similarity evidence (e.g. `A <-> C`, where `A <-> B` and `B <-> C` are both flagged) is never silently upgraded to a positive match solely based on cluster membership. Such pairs are reported separately on the dashboard as an "indirect chain (telephone game) warning," and the direct comparison result itself is left unmodified.

---

## 🎯 Primary Use Cases

Built with zero external dependencies and in-memory execution, `sieve_referee` is well suited as an embedded, privacy-focused screening engine.

### 1. Education & Learning Management Systems (EdTech / LMS)
Screen student submissions without uploading personal data or copyrighted text to a third-party cloud service. Common assignment templates are classified as `YELLOW`; unattributed copying or paraphrasing is flagged as `RED`.

### 2. Digital Publishing & CMS
Detect rewritten or recycled content submitted by freelance writers at draft-save time, without incurring LLM API costs for every check.

### 3. LLM Training Data Deduplication
Use as a deterministic pre-processing stage to remove near-duplicate or paraphrased records from a fine-tuning dataset, without GPU acceleration.

### 4. Legal, Contract & RFP Review
Separate boilerplate clauses (`COINCIDENTAL_FORMAT_MATCH`) from intentionally altered wording across contract revisions or vendor proposals.

### 5. CI/CD Documentation Auditing
Run in a GitHub Actions workflow or pre-commit hook to catch unauthorized copy-pasting across internal wikis or specification documents.

### 6. LLM-Generated Article Screening (Hallucination Gate)
Before publishing AI-assisted drafts, run the quantifier audit lane to catch ungrounded universal claims ("always", "never", "all ...") that carry neither a proof nor a complete enumeration — a deterministic footprint of hallucination.

---

## ⚡ Key Technical Advantages

1. **Near-zero cold start** — no PyTorch, no Transformers, no model loading; well suited to AWS Lambda or other serverless environments.
2. **Zero per-call cost** — everything runs on local CPU.
3. **Zero maintenance burden** — zero third-party dependencies means no exposure to upstream CVEs or breaking API changes.

---

## 📦 Installation

```bash
pip install git+https://github.com/neguseatama/sieve-referee.git
```

or, from a local clone:

```bash
git clone https://github.com/neguseatama/sieve-referee.git
cd sieve-referee
pip install .
```

---

## 🐍 Usage (Python Library)

```python
from sieve_referee import batch_evaluate, EvaluationResult

# 1. Prepare input documents in memory
documents = {
    "doc_a.txt": "Quantum computing relies on superposition and entanglement to achieve fast factorization.",
    "doc_b.txt": "To achieve fast factorization, quantum computing makes use of entanglement and superposition."
}

# 2. Run the screening
results: list[EvaluationResult] = batch_evaluate(documents)

# 3. Read the results
for res in results:
    print(f"Pair:    {res.item_id} <-> {res.matched_peer_id}")
    print(f"Signal:  {res.evaluation_signal.value}")  # -> RED
    print(f"Mask:    {res.mask}")                      # -> 0010
    print(f"Pattern: {res.pattern_name}")               # -> UNFORMATTED_CONTENT_COPY
    print(f"Reason:  {res.reason}")
    print("-" * 40)
```

### Screening files on disk from the library

To read a directory the way the CLI does, call `collect_txt_documents`: it
returns the readable documents plus a `skipped` report (same closed
vocabulary `empty_input` / `unreadable`, entries sorted by path) instead of
silently dropping empty or undecodable files.

```python
from sieve_referee.io_utils import collect_txt_documents

documents, skipped = collect_txt_documents("path/to/dir")
for entry in skipped:
    print(entry["path"], entry["reason"])   # e.g. empty.txt empty_input
```

### `EvaluationResult` fields

| Property | Type | Description |
|---|---|---|
| `item_id` | `str` | Primary document identifier |
| `matched_peer_id` | `str` | Comparison peer document identifier |
| `evaluation_signal` | `SignalColor` | Result signal (`.value` returns `"GREEN"`, `"YELLOW"`, or `"RED"`) |
| `mask` | `str` | 4-bit hypothesis mask, e.g. `"1010"` |
| `pattern_name` | `str` | LUT pattern name, e.g. `"PARAPHRASE_DETECTED"` |
| `reason` | `str` | Human-readable explanation of the judgment |

---

## 💻 Usage (CLI Tool)

```bash
# Basic directory scan (writes reports/sieve_dashboard.html)
sieve-referee ./target_documents

# Single self-contained HTML report (no diff_htmls/ subfolder)
sieve-referee ./target_documents --standalone --output-dir ./reports

# JSON output for automated pipelines, with a non-zero exit code on RED
sieve-referee ./target_documents --json --fail-on-risk

# Multi-core evaluation
sieve-referee ./target_documents -j 4
```

| Option | Type | Description |
|---|---|---|
| `target_dir` | positional | Directory containing the `.txt` files to screen |
| `--output-dir` | string | Report output directory (default: `reports`) |
| `--standalone` | flag | Emit a single self-contained HTML report instead of a report + `diff_htmls/` folder |
| `--json` | flag | Print results as JSON to stdout |
| `--json-file` | string | Save results as JSON to the given path |
| `--fail-on-risk` | flag | Exit with status code `1` if any `RED` signal is found |
| `-j`, `--jobs` | int | Number of worker processes for evaluation (default: CPU count) |

Reports are safe by default: file names and document text are escaped in every
HTML output, the standalone report embeds its JSON so that hostile file names
cannot break the page, the dashboard shows direct RED pairs and indirect-chain
warnings separately, and files that could not be evaluated (empty or unreadable)
are listed under the JSON `skipped` key with a closed vocabulary of reasons
(`empty_input` / `unreadable`) instead of vanishing silently.

---

## 📊 16-State Look-Up Table (LUT)

Four independent hypotheses (`H1`–`H4`) are combined into a 4-bit mask, which maps deterministically to a signal, pattern name, and reason.

| Mask | Signal | Pattern Name | Description |
|:---:|:---:|:---|:---|
| `1000` | 🟢 GREEN | `STANDARD_STRUCTURE_UNIQUE` | Independent document, no structural or content overlap detected. |
| `1100` | 🟡 YELLOW | `COINCIDENTAL_FORMAT_MATCH` | Shared format/template only; content itself is independent. |
| `1010` | 🔴 RED | `PARAPHRASE_DETECTED` | Content overlap despite a different structure (paraphrasing). |
| `1011` | 🔴 RED | `CLUSTER_PARAPHRASE_GROUP` | Paraphrased reuse confirmed within a 3+ document cluster. |
| `1111` | 🔴 RED | `CLUSTER_EXACT_COPY` | Exact/templated copy confirmed within a 3+ document cluster. |
| `0111` | 🔴 RED | `CLUSTER_FORMATTED_PARAPHRASE` | Paraphrased reuse in shared structure recurring within a 3+ document cluster. |
| `0101` | 🟡 YELLOW | `CLUSTER_FORMAT_ONLY_MATCH` | Shared template structure within a 3+ document cluster; content independent. |
| `0011` | 🔴 RED | `CLUSTER_UNFORMATTED_CONTENT_COPY` | Unformatted content copy recurring within a 3+ document cluster. |

(The LUT classifies 15 of the 16 possible mask states. Exactly two states, `0001` and `1001`, where cluster membership would stand without any direct similarity evidence, are structurally unreachable; `1001` is defined in the table but is not producible by the current pipeline, and `0001` is the single state without a table entry. Three further states, `0011`, `0101`, and `0111`, arise via cluster promotion and are classified by their dedicated LUT entries.)

> **`H4` (cluster membership) and indirect chains**
> `H4` is only set when a pair has *both* direct similarity evidence (`H2` or `H3`) *and* cluster membership of size ≥ 3. A pair with no direct evidence is never upgraded through cluster membership alone — such "telephone game" chains are reported separately as an indirect-chain warning on the dashboard, and the direct pair's own result is left unmodified.

---

## 🔍 Universal Quantifier Audit Lane (introduced in v1.3.0)

Alongside pairwise similarity, `sieve_referee` provides a **separate-axis audit lane** that screens drafts for **ungrounded universal propositions** — a deterministic footprint of LLM hallucination.

> **Operative definition**
> *Closing a universal scope with neither a derivability backing (`⊢` — formal derivation) nor a finite-model exhaustion backing (`⊨_fin` — an actually-run complete enumeration) constitutes an **ungrounded universalization**. The audit lane detects it deterministically. Whether the detected universalization is a hallucination is a human disposition.*

The engine **never evaluates truth values**; it only checks whether the author attached a backing tag. This makes it structurally immune to vacuous truths (universals over empty domains that are formally true) and keeps every judgment 100% reproducible.

**Pipeline (every stage deterministic):**

1. Sentence segmentation (`ja`: 。`！` `？` + newline / `en`: `.` with decimal, next-char and abbreviation guards + `!` `?` newline)
2. Exhaustive enumeration of universal-quantifier vocabulary (`ja`: 21 patterns, recall-first / `en`: 17 lowercase patterns matched at word boundaries)
3. `sentence_sha256` fingerprinting (the tagfile key)
4. Human tagfile (`backing` / `scope`) — the engine never guesses
5. 8-state audit LUT + `--fail-on-unverified` CI gate

**Backing semantics (aligned with modern logic semantics):**

| Tag | Logic semantics | Signal (universal scope) |
|---|---|---|
| `theorem` | `⊢` — derivability within a declared formal system | 🟢 GREEN |
| `enumerated` | `⊨_fin` — finite-model exhaustion, actually executed | 🟢 GREEN |
| `sample` | finite sample + explicit scope declaration | 🟡 YELLOW |
| *(no tag)* | none of the above | 🔴 RED (`UNBACKED_UNIVERSAL`) |

First-order validity over unrestricted domains (`⊨`) is undecidable (Church's theorem), so the engine accepts only the decidable fragment — `⊢` and `⊨_fin`. This is the theoretical form of the "the engine does not guess" principle.

**Added in v1.3.0 — certainty markers:** co-occurrence of a universal quantifier with an epistemic intensifier (e.g. 「確実に」 "certainly", 「明白に」 "evidently") in the same sentence is annotated as `certainty_markers` on the human worksheet. Annotations never alter signals — GREEN/YELLOW/RED is decided solely by tags.

**Added in v1.4.0 — English profile (`--lang`):** the audit lane now runs a dedicated English profile. `--lang {ja,en,auto}` selects the vocabulary, sentence splitting, matching and reason strings as one unit (default `ja` keeps v1.3.1 behavior byte-identical):

- **`en` vocabulary (17 lowercase patterns):** all / every / everyone / everybody / everything / each / any / none / neither / both / no / must / without exception, plus the temporal-absolute low-risk subset added in v1.5.0 (invariably / without fail / around the clock / 24/7). `always`, `never` and `permanently` remain permanently excluded for the same false-positive reason as on the Japanese side (systematic non-assertive frames such as *not always / never mind / as always*) — settled as a permanent decision in v1.5.0.
- **Word-boundary matching** (case-insensitive, length-preserving lowering): `all` no longer matches inside *ballot / allow / small / alloy*; `no` not inside *notify / nobody*; `every` not inside *everywhere*.
- **Exclusion phrases (34, deterministic):** an occurrence overlapping a boundary-aligned phrase — *not all, at all, after all, all but, all rights, each other, every now and then, if any, no longer, no doubt, no., ...* — is dropped per occurrence; the sentence itself stays in scope. `All rights are reserved.` produces no candidate, while `All nodes must sync.` does.
- **Interrogative exclusion:** sentences ending with `?` are out of audit scope for `en` (any questions are not universal claims). Japanese `？` sentences remain candidates, exactly as before.
- **Reason strings:** the audit lane's `reason` field has a full English table (`AUDIT_LUT_REASONS_EN`) with the same 8 states, signals and `pattern_name` values as the Japanese LUT.
- **`auto`** resolves deterministically by the kana (hiragana + katakana) ratio over all loaded documents: ratio ≥ 0.05 → `ja`, else `en`. CI runs should pass `--lang` explicitly; `auto` is a convenience.
- A 54-case ja↔en parallel corpus (equivalent universals, exclusion traps, boundary traps, interrogatives, intensifier co-occurrence, backed pairs) pins the cross-lingual behavior in `tests/test_quantifier_audit_en.py`.

**Added in v1.5.0 — modal/temporal scope (`#1`):** the vocabularies gain the approved low-risk subset of modal/temporal expressions:

- **ja quantifiers +3 (18 → 21):** 絶えず / 四六時中 / 24時間365日. Rejected on false-positive risk: 常時 (substring collision with 非常時 "emergency"), 24時間 (deadline usage such as 24時間以内 "within 24 hours"), 全く (bare intensifier). The existing 18 Japanese patterns are kept verbatim.
- **en quantifiers +4 (13 → 17):** invariably / without fail / around the clock / 24/7. `forever` is rejected for idiom collisions (*nothing lasts forever*); *at all times* / *every time* are redundant because `all` / `every` already match them at word boundaries. Known collision: date notations such as `24/7/2025` may produce a candidate (recall-first; disposed by a human in seconds).
- **ja modifiers +7 (10 → 17) / en modifiers +8 (9 → 17), annotation-only:** 必然的に / 不可避的に / 自ずと / おのずと / 疑いようがない / 疑いようもない / 言うまでもなく and unquestionably / indisputably / beyond doubt / by definition / self-evidently / manifestly / as everyone knows / it goes without saying. Epistemic-necessity markers never change GREEN/YELLOW/RED (LUT semantics untouched). Structural-necessity phrasings (構造上 / *by design* / *structurally*) are excluded by design — they describe design constraints, not epistemic overreach. Japanese adverbs are adopted only in adverbial form so that negative forms such as 「必然ではない」 are not annotated.
- **Corpus +24 cases (sections F/G/H):** temporal equivalents (both languages RED), new-marker annotations (signal unchanged, GREEN under a theorem tag), rejected-word tripwires and polarity guards (「疑問の余地がある」 annotates nothing) — 78 cases total (74 section entries + 4 backed pairs).

**Added in v1.5.0 — positional Audit Risk Index (`--risk-index`, `#4`):** RED dispositions get a deterministic triage score built from three position-based signals only (the dependency-based plan was discarded):

- **Heading depth** — markdown ATX headings (`#`..`######`, fenced code blocks ignored) are scanned deterministically; a candidate inherits the depth of the last heading before it. Depth 0 (executive summary before any heading) weighs highest. Numbered headings ("1.1", "第 1 章") are treated as plain text.
- **Section order** — the candidate's rank inside its section (the first claim is the thesis claim) weighs highest.
- **In-sentence density** — the number of quantifier patterns in the sentence (1 / 2 / 3+).

`risk_index = round_half_up(0.40·H(d) + 0.30·O(rank) + 0.30·D(n))`, a 35–100 integer. All weights are frozen per-mille constants recorded in the receipt; the computation is pure integer arithmetic (round-half-up, no float rounding). `--risk-index` is **off by default**: without it, receipts and reports stay byte-identical to previous versions. With it, each candidate carries `risk_index` + `risk_factors`, and the human report gains a `PRIORITY` section listing RED candidates in descending score. Signals are never changed.

```bash
# Audit an English draft directory
sieve-referee ./draft_en --audit --lang en --fail-on-unverified

# Language resolved deterministically from the documents themselves
sieve-referee ./mixed_dir --audit --lang auto
```

**Audit lane CLI options:**

| Option | Description |
|---|---|
| `--audit` | Enable the audit lane |
| `--audit-vocab PATH` | Quantifier vocabulary file (default: built-in 21 patterns) |
| `--audit-tags PATH` | Tagfile (JSON) keyed by `sentence_sha256` |
| `--audit-modifier-vocab PATH` | Intensifier vocabulary file (v1.3.0) |
| `--lang ja\|en\|auto` | Audit language profile (v1.4.0; default `ja`) |
| `--risk-index` | Positional Audit Risk Index (v1.5.0; adds `risk_index`/`risk_factors` + RED `PRIORITY` section; default off) |
| `--fail-on-unverified` | Exit code `1` if any unbacked universal (RED) remains |

```bash
# Audit a draft directory (non-zero exit on RED remnants)
sieve-referee ./draft_dir --audit --fail-on-unverified

# After human tagging (worksheet prints sentence hashes), re-run to verify
sieve-referee ./draft_dir --audit --audit-tags tags.json --fail-on-unverified
```

Known limits: universal phrasings outside the vocabulary are missed (false-negative class); the truth of the tags themselves is the verifier's responsibility (recorded in the tagfile's `evidence` field). English-specific: the `en` vocabulary is surface-literal and lowercase-declared (morphological variants such as *anybody/nobody* are not enumerated and are missed); the fixed abbreviation guard list cannot cover every abbreviation; and the exclusion phrase list is empirical — it is pinned and extended through the parallel corpus, not derived from a grammar. v1.5.0 additions: the heading scan behind `--risk-index` is markdown-ATX-only (numbered/Japanese-style headings count as plain text); the modifier (intensifier) lane has no negation guard, so e.g. "not necessarily" is annotated as a certainty marker (recall-first); `24/7` may collide with date notations; temporal absolutes `always`/`never` are still missed on the `en` side (permanent decision) while the Japanese side keeps its v1.3.0 coverage (常に/決して/…).

---

## ⚠️ Known Limitation: Threshold Calibration Is Japanese-Specific

All four thresholds (`H1 = 0.35`, `H2 = 0.80`, `H3 = 0.45`, cluster size `≥ 3`)
were calibrated using real-data testing on **Japanese** text (roughly 1,300+
pairs across unrelated documents, paraphrase pairs, and formal academic
prose).

The `H1` density metric in particular (`len(set(text)) / len(text)`) behaves
very differently across scripts: Japanese text draws from a large set of
kanji, so unique-character ratios tend to be high, while English and other
alphabetic-script text reuses a small ~26-letter alphabet and will
systematically score lower on this metric, independent of how generic or
templated the content actually is. As a result, non-Japanese text may be
under- or over-classified against the current defaults.

Multi-encoding file reading (UTF-8, Shift_JIS, CP932, EUC-JP) and NFKC
normalization work for any text regardless of language. What has **not**
been separately validated is the semantic quality of `H2`/`H3` splitting,
or the appropriateness of the default thresholds, for languages other than
Japanese. If you use this on non-Japanese corpora, re-run the false-positive
check described in [ARCHITECTURE.md](docs/ARCHITECTURE.md) against your own
data before trusting the default thresholds.

Additionally, the `reason` string of the **pair-evaluation lane** (`EvaluationResult.reason`) is currently hard-coded in Japanese regardless of the input document's language, as shown in the example output above. The **audit lane** localizes its `reason` strings since v1.4.0 via `--lang` (see above); the pair lane has no English (or other-language) localization of these messages yet.

---

## 📚 Documentation

- 🔌 [API & Integration Guide](docs/INTEGRATION.md) — using `sieve_referee` as a Python library or FastAPI microservice
- 🚀 [Deployment Guide](docs/DEPLOYMENT.md) — Docker and Terraform for Google Cloud Run
- 🔐 [CI/CD & Security Guide](docs/CI_CD_SETUP.md) — keyless GCP deployment via Workload Identity Federation
- 🏛️ [Architecture Specification](docs/ARCHITECTURE.md) — the mathematical model and safety invariants in detail

## 📄 License

MIT License. See [LICENSE](LICENSE).
