> built 2026-11-23 21:36 UTC from 977f9d6 (main) · ductus 0.0.21. Details: build_info.json

# index.html.md

<!-- generated by epythet -->

# ductus

Gauge which parts of a text read as machine-written, and say why — with every finding anchored to the exact characters that carry it.

```python
from ductus import gauge

report = gauge(open("draft.md").read())
report.document.label  # 'mixed-signals'
report.segments[3].lean  # +0.62  (-1 human … +1 machine)
report.segments[3].signals[0].note
# "a colon introducing a three-part parallel enumeration -- a textbook assistant construction"
```

```bash
pip install ductus
ductus gauge draft.md                                  # a readable diagnosis
ductus gauge draft.md --format html --out report.html  # shaded, hover for the reason
ductus gauge draft.md --format json                    # for a program
```

In palaeography the *ductus* is the characteristic manner and sequence of strokes by which a scribe’s hand is recognised. This package looks for the equivalent in prose.

## There is no percentage in this package, and that is the point

Every detector on the market emits a number like “87% AI”. That number reads as a calibrated probability, is not one, and is how people get falsely accused. What you get here instead is three things you can argue with: a **lean** in [-1, +1], an **evidence strength**, and a coarse **label**. Behind each of them is a list of signals, each with a direction, a weight, the detector that produced it, a plain-language reason, and the exact span it came from.

Four things are true and belong in any report you make from this:

- **Heavily-edited human writing and model-assisted writing look the same.** Re-reading a hard message ten times sands off exactly the irregularity that marks it as human.
- **Detectors over-flag non-native English writers** — 61.3% false positives across seven commercial detectors on non-native TOEFL essays, against near-zero on native-speaker controls [1].
- **Register contamination is real**: people who read model output all day start writing like it, unassisted.
- **No detector survives a motivated adversary**, and that is a proven result rather than a gap in current tooling [2].

So this package describes *text*. It does not make claims about *people*, and it should not be used to.

### And this package’s own false-positive rate is measured

It would be cheap to quote other people’s numbers and not measure our own. Across 350 human-written texts with known proficiency levels, the shipped defaults call a document `leans-machine` — always wrongly, every text in that corpus was written by a person — this often:

|                                         | beginner    | intermediate   | advanced    | native control   |
|-----------------------------------------|-------------|----------------|-------------|------------------|
| **per document** (paragraph / sentence) | 0.0% / 0.8% | 2.0% / 1.0%    | 1.4% / 1.4% | 0.0% / 0.0%      |
| per sentence                            | 0.4%        | 1.6%           | 2.0%        | 0.4%             |

On 1,500 further non-native essays held out from the calibration, the document rate is 0.9% (paragraph) and 0.8% (sentence). **It was bought with recall, and the price is steep**: the document verdict now calls 2 of 100 machine-written essays `leans-machine` where it called 25, so a document label is rare in both directions and the flagged *sentences*, which did not change, are where the evidence is. [`non-native-calibration.md`]() has the pre-registered procedure and every number.

That is down from 20.6% overall, then 6.0%, and the way it came down is worth knowing. Three rules were found to be matching **nothing** in machine-written text while implicating 86 human documents between them — two of them were simply broken, catching ordinary negation (“I did not eat from the tree but from the bush”) and the everyday correlative (“not only fast, but also simple”). And the document-level verdict was rebuilt so that it stops treating *accumulation* as *corroboration*: a long document used to be more likely to be accused for being long. [`reducing-false-accusations.md`]() has the per-rule table and what it cost (nothing: not one correctly-flagged machine segment was lost).

Two things still to take from it. **A single flagged sentence is much better evidence than a flagged document.** And the bias does **not** run the way the literature predicts: it tracks *formal, fluent, essayistic* writing rather than simple writing, because the deterministic detectors look for rhetorical constructions that good writers also use. Before the document threshold was calibrated (addaix/ductus#30), what remained was concentrated in intermediate and advanced non-native writers, at 10%.

## What it looks at

Four detectors ship, all deterministic, all free, none needing a model or a key.

| Detector   | Finds                                                  | Example                                                                                                    |
|------------|--------------------------------------------------------|------------------------------------------------------------------------------------------------------------|
| `tells`    | Catalogue phrases models overuse, tiered by confidence | “delve”, “it’s important to note”, “In conclusion,”                                                        |
| `forensic` | Mechanical traces of how the text was produced         | a hard line break mid-sentence, mixed straight-and-curly apostrophes, trailing whitespace, em-dash density |
| `rhetoric` | Sentence *shapes* a phrase list cannot see             | “not X but Y”, a colon introducing a three-part parallel enumeration, concession-then-pivot                |
| `rhythm`   | Burstiness — how much sentence length varies           | metronomic paragraphs                                                                                      |

Note that several of these argue *for* a human. A detector that can only ever accuse is not a measuring instrument. In practice the mechanical signals are often the most decisive thing in a file, in either direction.

The deterministic pass finds phrases, artifacts and a few shapes. **It cannot find prose that is machine-written and bland** — for that a model has to read it, which is what the shipped agent skills are for.

Two model-based detectors also ship, behind the `[local]` extra and **off by default**:

| Detector          | Finds                                                                                                                           | Cost                                    |
|-------------------|---------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------|
| `fast-detect-gpt` | Passages a language model finds markedly more predictable — or more surprising — than the rest of the same document             | one CPU pass with `gpt2`                |
| `binoculars`      | The same comparison, via the cross-perplexity of a paired observer and performer, which generalises better to unseen generators | two CPU passes with `distilgpt2`/`gpt2` |
```bash
pip install "ductus[local]"
ductus gauge draft.md --detectors fast-detect-gpt,binoculars
```

They stay opt-in because they need `torch` and a model download, which the default must not. **But if you have installed the extra, turn them on — at their default models.** Measured against a second fixture whose machine text was *not* written to blend into its surroundings, they find 12 of 75 machine-written sentences at 86% precision where the deterministic set finds 0 of 75 — and they falsely accuse human writers far *less* often than the deterministic default does (6.3% of 350 human texts for `binoculars`, against 20.6%).

Do not assume a bigger proxy model is an upgrade. A stronger Binoculars pair was measured, found more machine text on both fixtures, and **nearly doubled its false accusations on human writing** — so the defaults stayed where they were. If you change `model=`, `observer=` or `performer=`, re-run `python misc/measure_false_positives.py --pair-check` for your pair. The numbers, including the unflattering ones, are in [`phase-1-results.md`]() and [`phase-2-results.md`](); why a continuous score becomes a banded signal rather than a weight is [`curvature-as-evidence.md`]().

Note what they do *not* do: they compare passages **within** a document and so cannot say whether a whole text is machine-written. Answering that honestly needs a calibration this package does not have yet.

## How it fits together

The three amber boxes are the seams — each is one keyword argument. Everything below `Report` is a renderer, and renderers are pure functions of it: nothing in the analysis knows or cares which one you call, and adding a fourth changes nothing upstream.

## Renderings

One analysis, three outputs. Pick by who is reading.

| Renderer                  | CLI                               | Output                                                                                           | Reach for it when                                                                             |
|---------------------------|-----------------------------------|--------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------|
| `to_markdown(report)`     | `ductus gauge draft.md`           | A synopsis, a table of flagged segments, then a *Why* section quoting each signal and its reason | A terminal, a PR comment, a document, an agent that needs to reason about the result in prose |
| `to_html(report, text=…)` | `--format html --out report.html` | One self-contained file — no build step, no CDN, no network                                      | You want to *see* where the evidence is, and read why without losing your place               |
| `to_json(report)`         | `--format json`                   | The full structure: every span, signal, weight and reason                                        | A frontend, a pipeline, a calibration run, anything that is not a person                      |

### The HTML rendering

![Hovering a highlighted span in a ductus HTML report: the reason, direction, weight and detector appear beside it](https://raw.githubusercontent.com/thorwhalen/ductus/main/misc/demo/ductus-report.gif)

Hover (or keyboard-focus) any highlight and the reason appears beside it — which detector fired, which direction it argues, and what it weighs. Paragraphs carry a left border and a lean badge; the bar under each one is its evidence, one segment per signal.

Two deliberate choices, both from the annotation-systems research in [`misc/docs/research/`]():

- **Hue encodes score, and only score.** A perceptually-uniform ramp, warm for machine-leaning and cool for human-leaning, with lightness re-clamped per theme so it works in light and dark mode. Overlap is shown *structurally*, in the lane under the paragraph, never by blending colours — stacking translucent fills is what makes overlapping highlights unreadable.
- **The reason is anchored to the highlight**, not parked in a corner, so the eye does not have to leave the text to find out why. Below 640px it falls back to a bottom sheet.

The GIF above was recorded with [`walkthru`](https://github.com/thorwhalen/walkthru) driving a real browser — the script is [`misc/demo/make_gif.py`](), and it is the whole pipeline: measure where the highlights are, build a demo document whose camera zooms to them, play it against a recording page, render the capture to a GIF.

## Agent skills

The primary surface. Two skills and a subagent ship inside the package and install with one command:

```bash
ductus install-skills --write          # links them into ~/.claude/skills
```

- **`ductus`** — what may and may not be claimed from a text, and which task is which.
- **`ductus-gauge`** — the full reading: the deterministic scan, then a judgment pass with rubrics for the nine machine-leaning and six human-leaning *shapes* that regular expressions miss, then the write-up.
- **`ductus-reader`** (subagent) — does the whole reading in its own context and returns a finished diagnosis.

An agent’s own reading folds back in beside the deterministic signals, anchored by quote:

```bash
ductus gauge draft.md --judgments judgments.json --format html --out report.html
```

A quote that no longer occurs is dropped rather than mis-anchored, so re-running after an edit is safe.

### Several readers, and a baseline to read them beside

One reader’s judgments turn out to be too noisy to measure a rewrite with. Fresh, strict close readers each flagged about 40 machine-leaning shapes in every version of a 3,700-word essay across five rounds of rewrites, mostly on text the previous reader had passed, so the raw count could not tell a round that helped from one that did not. What did move was the number of **sentences that independent readers both flag**. So `--judgments` can be given once per reader:

```bash
ductus gauge essay.md --judgments essay.a.json --judgments essay.b.json --judgments essay.c.json
```

With two or more readers the report gets a **Readers** section: each reader’s count of flagged sentences (machine- and human-leaning, plus any quotes that were not found), and the **consensus** — sentences flagged by at least `k` readers (`-k`, default 2) — as a density per 1,000 words. Only the consensus is folded into the segments; a single reader’s flags are a reading, not a finding.

A density on its own is a bare number. `baseline` takes the same measure on reference texts, typically the author’s own writing from before the question arose:

```bash
ductus baseline 2019-essay.md 2020-essay.md --out baseline.json   # readers: 2019-essay.*.json, or 2019-essay/*.json
ductus gauge essay.md --judgments essay.a.json --judgments essay.b.json --baseline baseline.json
```

The baseline pools the texts by words and keeps the per-text range, because two reference essays at 2.4 and 9.3 per 1,000 words say something a pooled 5.0 hides. Its output carries counts only, never a sentence from the reference texts. When the reference texts had a different number of readers, or were read at a different `k`, the report says the comparison is not like-for-like rather than comparing silently. The prompt for spawning the independent readers is in the `ductus-gauge` skill.

None of this is a probability. It describes how a text reads to these readers next to how the author’s own writing reads to them; it says nothing about who wrote either.

## MCP

The same verbs the CLI dispatches, as MCP tools:

```bash
pip install "ductus[mcp]"
ductus-mcp                    # stdio, for a local agent host
```

`gauge`, `baseline`, `detectors`, `segmenters` and `tells`. `install_skills` is deliberately absent: it symlinks into an agent host’s skills directory, and a person typing that at a CLI chose to in a way a remote caller did not.

There is **no second verb list**. `ductus.mcp.TOOL_REFS` is derived from the one list the CLI already dispatches, so the two surfaces cannot drift — and a verb that changes the host declares that at its own definition rather than by appearing in some other list. `middleware=` and `auth=` pass straight through `mk_mcp()` for a deployed server.

## HTTP

The same verbs again, over HTTP:

```bash
pip install "ductus[http]"
ductus-http                   # http://127.0.0.1:8000, and /docs for the OpenAPI UI
```

```bash
curl -s localhost:8000/gauge -H 'content-type: application/json' \
  -d '{"source": "Great question! Let us delve in.", "format": "json"}'
```

Same rule as MCP, one layer further: `ductus.http.ROUTED_FUNCS` is *derived* from the CLI’s list, so a third surface still means no second implementation and no parity test. The typed TypeScript client the frontend imports is generated from this app’s own OpenAPI (`ductus.http.export_client()`), so a changed Python signature becomes a TypeScript type error rather than a runtime surprise.

**This surface found something the other two could not.** `gauge(source=...)` reads a file when the string names one, and `gauge(out=...)` writes one. That is exactly right when you typed the command yourself — and an arbitrary file read and an arbitrary file write when the caller is a stranger. Neither the CLI nor a local stdio MCP host can see it, because on those surfaces it is not a bug. The verbs now declare which of their parameters address the filesystem (`@host_paths(source="read", out="write")`, a sibling of the existing `@host_mutating`), and the HTTP adapter refuses them by reading that declaration rather than by knowing anything about `gauge`. `mk_app(guard_host_paths=False)` turns it off for a loopback service you run for yourself.

## The editor: score, edit, score again

An example frontend lives in [`frontend/`]() — paste a text, read it, edit it, read it again, with every finding anchored to the characters that carry it.

```bash
pip install 'ductus[http]'
cd frontend && npm install && npm run build
ductus-http                     # serves the UI and the API from one origin
```

Three things decide its design, and the first two are correctness rather than taste:

- **The editor does not tidy the text.** A normal rich-text editor turns `'` into `’`, trims trailing whitespace and collapses lone newlines. This package reads all three as evidence, and `mixed-apostrophes` and `trailing-whitespace` argue for a **human**. An editor that quietly normalised the text would be deleting the evidence that exonerates people. So the ProseMirror schema is one whitespace-preserving block, which also makes a plain offset `o` exactly position `o + 1`.
- **An edit invalidates, it never re-anchors.** Positions are kept exact through every keystroke (ProseMirror’s `Mapping`); validity is not inherited. A finding whose text has changed goes hatched and reads “unverified” until you read again — re-attaching an old score to new text is a false claim, not a stale cache. A finding is invalidated when the edit touches its characters *or anywhere in its segment*, because segment scores are per unit of text; the document verdict is invalidated by any edit at all.
- **The TypeScript is generated from the Python.** `frontend/src/generated/client.ts` from the service’s OpenAPI, `report.ts` from the dataclasses in `base.py`. `tests/test_generated_sources.py` fails if they drift, so a renamed field is a failing `pytest` run rather than an `undefined` in a browser.

The stack is Vite + TypeScript + ProseMirror and deliberately no framework, no state library and no persistence. Why, and what each of those costs, is in [`misc/docs/frontend-stack-decision.md`]().

**The interface holds the same line the reports do.** No percentage anywhere. The measured false-positive rate sits beside the verdict rather than in a footer, loudest in the one case where the verdict is a claim about a person — because an interface makes a verdict feel authoritative in a way a paragraph does not, and the person most likely to be wronged by this page is the careful essayist whose prose it just lit up.

## Seams

Three, each one keyword argument, each defaulting to something that genuinely works:

```python
gauge(text, segmenter="sentence")  # or "paragraph", "document", or a callable
gauge(
    text, detectors=["forensic", "rhetoric"]
)  # or your own (text, span) -> Iterator[Signal]
gauge(text, aggregate=my_scorer)  # (signals, *, n_chars) -> (lean, strength, label)
```

The `aggregate=` default is `density_aggregate`, which divides evidence by how much text produced it: two stray signals mean something different in 600 characters than in 3000. The length-blind `aggregate` it replaced is still exported, and the measurement that chose between them is in [`phase-2-results.md`]() — it cut false accusations on human text from 34.3% to 20.6% at no measured cost in findings.

A detector is a plain function `(text, span) -> Iterator[Signal]`. Fast-DetectGPT and Binoculars are exactly that and nothing more — `ductus/curvature.py` adds no base class, no core change and no import cost. A vendor API would be one more function of the same shape; see [the roadmap]().

`DETECTORS` is the registry of everything nameable; `DEFAULT_DETECTORS` is what `detectors=None` means. They are deliberately different lists — a detector joins the default by beating what is already there on `tests/fixtures/mixed_authorship.json`, which `python misc/measure_detectors.py` measures.

For long documents, `iter_segments` is the streaming core and `gauge` is the batch facade over it.

## Spans survive editing

Every `Span` carries character offsets *and* the W3C Web Annotation redundant selectors (`quote`, `prefix`, `suffix`), because plain offsets do not survive an edit to the text. That is what lets a viewer re-find a finding after the document changed, and what a future edit-and-re-score UI is built on.

## Relationship to `deslop`

`ductus` is the read side: *where does this text read as machine-written, and why*. [`acquaint`](https://github.com/thorwhalen/acquaint)’s `deslop` is the write side: *make my draft not read that way, in my voice, calibrated to this reader*. They share this package’s tells catalogue — `acquaint` imports it — and compose naturally: gauge, deslop the flagged spans, gauge again.

They are separate packages because they have different inputs. `deslop` needs a model of the reader; `ductus` must work on a stranger’s text with nothing but the text.

## Install

```bash
pip install ductus              # the core: pyyaml and cw, nothing else
pip install "ductus[local]"     # + Fast-DetectGPT and Binoculars: offline, no API key, opt-in
pip install "ductus[api]"       # + vendor detector adapters
pip install "ductus[mcp]"       # + the MCP server (`ductus-mcp`)
pip install "ductus[http]"      # + the HTTP service (`ductus-http`) and its typed client
```

## References

[1] [Liang W, Yuksekgonul M, Mao Y, Wu E, Zou J. GPT detectors are biased against non-native English writers. *Patterns* 2023.](https://arxiv.org/abs/2304.02819)

[2] [Sadasivan VS, Kumar A, Balasubramanian S, Wang W, Feizi S. Can AI-Generated Text be Reliably Detected?](https://arxiv.org/abs/2303.11156)

[3] [Sanderson R, Ciccarese P, Young B. Web Annotation Data Model. W3C Recommendation, 2017.](https://www.w3.org/TR/annotation-model/)

[4] [Tolstykh I, et al. LLMTrace: A Corpus for Classification and Fine-Grained Localization of AI-Written Text. arXiv:2509.21269.](https://arxiv.org/abs/2509.21269) — the ground-truth fixture in `tests/fixtures/` is a slice of this, Apache-2.0.

<p class="epythet-aggregates">This documentation as a single file: <a href="ductus.md">ductus.md</a> (Markdown, for agents).</p>


# _autosummary/ductus.base.html.md

# ductus.base

The data model: where a finding lives, what it claims, and how much it weighs.

Four types, and they are the whole contract every other module speaks in.

A [`Span`](_autosummary/ductus.base.html.md#ductus.base.Span) says *where*. It carries character offsets **and** the W3C Web
Annotation redundant selectors (quote, prefix, suffix) so a finding can be
re-anchored after the text is edited, which plain offsets cannot survive.

A [`Signal`](_autosummary/ductus.base.html.md#ductus.base.Signal) is one piece of evidence: a direction, a weight, who produced
it, and a human-readable reason. Signals are never merged or averaged away –
the reason a passage scored the way it did is always recoverable.

A [`Segment`](_autosummary/ductus.base.html.md#ductus.base.Segment) is a unit of text plus the signals that landed on it and the
lean derived from them. A [`Report`](_autosummary/ductus.base.html.md#ductus.base.Report) is the document-level roll-up.

```pycon
>>> text = "The cat sat. It was a fine evening."
>>> span = Span.of(text, 4, 7)
>>> span.quote, span.prefix
('cat', 'The ')
>>> Signal("test", "machine", 0.5, "demo", note="an example").direction
'machine'
```

### Module Attributes

| [`SCHEMA_VERSION`](_autosummary/ductus.base.html.md#ductus.base.SCHEMA_VERSION)   | Bumped when the serialized shape of a Report changes incompatibly.   |
|-------------------------------------------------------------------|----------------------------------------------------------------------|
| [`DIRECTIONS`](_autosummary/ductus.base.html.md#ductus.base.DIRECTIONS)       | What a signal can argue for.                                         |
| [`LABELS`](_autosummary/ductus.base.html.md#ductus.base.LABELS)           | The coarse vocabulary a segment is labelled with.                    |

### Classes

| [`Report`](_autosummary/ductus.base.html.md#ductus.base.Report)(text_sha256, n_chars, document, ...)      | Everything a downstream consumer needs, and nothing it has to guess at.   |
|---------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------|
| [`Segment`](_autosummary/ductus.base.html.md#ductus.base.Segment)(span[, signals, lean, strength, label])  | A unit of text, the signals on it, and the lean they add up to.           |
| [`Signal`](_autosummary/ductus.base.html.md#ductus.base.Signal)(name, direction, weight, detector[, ...]) | One piece of evidence about one span.                                     |
| [`Span`](_autosummary/ductus.base.html.md#ductus.base.Span)(start, end, quote[, prefix, suffix, level]) | A character range, with redundant selectors so it survives an edit.       |

### ductus.base.DIRECTIONS *= ('machine', 'human', 'neutral')*

What a signal can argue for. `neutral` records evidence that is real but
does not discriminate – it is kept because hiding it would be dishonest.

### ductus.base.LABELS *= ('leans-machine', 'leans-human', 'mixed-signals', 'uncertain', 'no-evidence')*

The coarse vocabulary a segment is labelled with. Deliberately not a
percentage: see `docs/why-no-percentage.md`.

### *class* ductus.base.Report(text_sha256, n_chars, document, segments, detectors, segmenter, schema_version='1', calibration='uncalibrated', meta=dict())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Everything a downstream consumer needs, and nothing it has to guess at.

#### *property* signals *: [tuple](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[Signal](_autosummary/ductus.base.html.md#ductus.base.Signal), ...]*

Every signal in the report, in document order.

### ductus.base.SCHEMA_VERSION *= '1'*

Bumped when the serialized shape of a Report changes incompatibly.

### *class* ductus.base.Segment(span, signals=(), lean=0.0, strength=0.0, label='no-evidence')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A unit of text, the signals on it, and the lean they add up to.

`lean` runs from -1 (every signal argues human) to +1 (every signal argues
machine). `strength` is how much evidence there is at all – a lean of
+1.0 from a single weak signal is not the same claim as +1.0 from six.

### *class* ductus.base.Signal(name, direction, weight, detector, value=None, note='', span=None)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One piece of evidence about one span.

`weight` is how much this moves the needle, in `0..1`. It is a weight,
not a probability: two 0.5 signals pointing the same way are stronger than
one, and nothing here claims to be calibrated.

```pycon
>>> Signal("em-dash", "machine", 0.2, "forensic", value=3).name
'em-dash'
```

### *class* ductus.base.Span(start, end, quote, prefix='', suffix='', level='segment')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A character range, with redundant selectors so it survives an edit.

Offsets count **code points** (Python `str` indices), not bytes and not
UTF-16 units – a JavaScript client must convert after any astral character.

`start`/`end` are a `TextPositionSelector`; `quote` with `prefix`
and `suffix` is a `TextQuoteSelector`. Keeping both is what lets a
viewer re-find a finding after the text around it changed.

```pycon
>>> s = Span.of("one two three", 4, 7, level="sentence")
>>> (s.start, s.end, s.quote, s.level)
(4, 7, 'two', 'sentence')
>>> s.length
3
```

#### contains(other)

Whether `other` falls entirely inside this span.

```pycon
>>> a, b = Span.of("abcdef", 0, 6), Span.of("abcdef", 2, 4)
>>> a.contains(b), b.contains(a)
(True, False)
```

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

#### *classmethod* of(text, start, end, , level='segment')

Build a span over `text`, capturing its re-anchoring context.

```pycon
>>> Span.of("abcdef", 2, 4).suffix
'ef'
```

* **Return type:**
  [`Span`](_autosummary/ductus.base.html.md#ductus.base.Span)


# _autosummary/ductus.consensus.html.md

# ductus.consensus

Several close readers, and the sentences at least `k` of them agree on.

One reader’s judgments are noisy in a way that hides the thing being measured. Fresh,
strict readers given the same instructions each flag dozens of shapes in a long essay,
mostly on text the previous reader passed, so a raw count does not move when a rewrite
helps and does not move when it does not. What does move is the set of \*\*sentences
that independent readers both flag\*\*. That is what this module counts.

Two numbers come out, and both are descriptions of how a text reads, never of who
wrote it:

- **per-reader counts** – how many sentences each reader flagged, each direction. Large
  and unequal is normal; it is the reader variance this module exists to see past.
- **consensus density** – sentences flagged by at least `k` readers, per 1,000 words.
  A density on its own is a bare number. [`pooled()`](_autosummary/ductus.consensus.html.md#ductus.consensus.pooled) takes the same measure over
  reference texts – the author’s own earlier writing – so a report can put the two
  side by side instead.

The unit is the sentence, from the same segmenter `gauge(segmenter="sentence")` uses,
so a judgment and a sentence are anchored by the same rule as everywhere else: a quote
that no longer occurs in the text is **dropped and counted**, never re-anchored.

Pure functions over judgment records (dicts); nothing here reads a file.

```pycon
>>> text = "It is a pattern. You decide, invest, regret. Sent it Friday."
>>> a = [{"quote": "You decide, invest, regret", "direction": "machine"}]
>>> b = [{"quote": "invest, regret.", "direction": "machine"},
...      {"quote": "It is a pattern", "direction": "machine"}]
>>> c = consensus(text, [a, b], names=["a", "b"])
>>> [(r["name"], r["machine"]) for r in c["readers"]]
[('a', 1), ('b', 2)]
>>> c["machine"]["count"], [u["quote"] for u in c["machine"]["units"]]
(1, ['You decide, invest, regret.'])
```

### Module Attributes

| [`DEFAULT_K`](_autosummary/ductus.consensus.html.md#ductus.consensus.DEFAULT_K)   | How many readers must flag a sentence for it to count.   |
|--------------------------------------------------------------|----------------------------------------------------------|

### Functions

| [`anchor_judgment`](_autosummary/ductus.consensus.html.md#ductus.consensus.anchor_judgment)(text, judgment)               | Where a judgment lands in `text`, or `None` when its quote is gone.             |
|------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------|
| [`consensus`](_autosummary/ductus.consensus.html.md#ductus.consensus.consensus)(text, readers, \*[, k, names, ...]) | Per-reader counts and the sentences at least `k` readers flag, each direction.  |
| [`consensus_signals`](_autosummary/ductus.consensus.html.md#ductus.consensus.consensus_signals)(text, result)               | One signal per consensus unit, anchored to the unit's own characters.           |
| [`pooled`](_autosummary/ductus.consensus.html.md#ductus.consensus.pooled)(results)                               | The same measure over several texts, pooled by words, with the per-text spread. |

### ductus.consensus.DEFAULT_K *= 2*

How many readers must flag a sentence for it to count. Two is the smallest number
that is agreement rather than one reader’s taste.

### ductus.consensus.anchor_judgment(text, judgment)

Where a judgment lands in `text`, or `None` when its quote is gone.

A judgment carries a `quote` (anchored at its first occurrence) or explicit
`start`/`end` offsets. A quote that does not occur is dropped by every caller –
mis-anchoring would attach a reason to text it was never about.

```pycon
>>> anchor_judgment("one two three", {"quote": "two"})
(4, 7)
>>> anchor_judgment("one two three", {"quote": "four"}) is None
True
>>> anchor_judgment("one two three", {"start": 0, "end": 3})
(0, 3)
```

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`int`](https://docs.python.org/3/builtins/functions.html#int), [`int`](https://docs.python.org/3/builtins/functions.html#int)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)

### ductus.consensus.consensus(text, readers, , k=2, names=None, segmenter='sentence')

Per-reader counts and the sentences at least `k` readers flag, each direction.

`readers` is one list of judgment records per reader. `names` labels them in the
result (default `reader 1`, `reader 2`, …). `segmenter` is the unit readers
must agree on – a sentence by default, any of [`ductus.segment.SEGMENTERS`](_autosummary/ductus.segment.html.md#ductus.segment.SEGMENTERS) or
a callable.

Everything returned is JSON-ready: counts, densities per 1,000 words, and each
consensus unit with its offsets, its quote, the readers that flagged it and the
shapes they named.

```pycon
>>> t = "One. Two. Three."
>>> r = [[{"quote": "Two.", "direction": "human"}]] * 3
>>> c = consensus(t, r, k=3)
>>> c["human"]["count"], c["machine"]["count"], c["n_words"]
(1, 0, 3)
>>> consensus(t, r, k=4)
Traceback (most recent call last):
    ...
ValueError: k=4 needs at least 4 readers; got 3
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### ductus.consensus.consensus_signals(text, result)

One signal per consensus unit, anchored to the unit’s own characters.

This is what a multi-reader reading contributes to a report: not every reader’s
every flag – most of which the next reader would not have made – but the units
they agree on, weighted by the mean of the agreeing readers’ weights.

```pycon
>>> t = "One. Two. Three."
>>> c = consensus(t, [[{"quote": "Two", "direction": "machine", "name": "x"}]] * 2)
>>> s = consensus_signals(t, c)[0]
>>> s.name, s.detector, s.span.quote, s.note
('reader-consensus', 'readers', 'Two.', 'flagged by 2 of 2 readers (reader 1, reader 2): x')
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`Signal`](_autosummary/ductus.base.html.md#ductus.base.Signal)]

### ductus.consensus.pooled(results)

The same measure over several texts, pooled by words, with the per-text spread.

Pooled means total consensus units over total words – a long reference text counts
for more than a short one, as it should. The per-text range is reported beside it,
because two reference essays at 2.4 and 9.3 per 1,000 words say something a single
pooled 5.0 hides.

```pycon
>>> a = {"k": 2, "n_readers": 2, "unit": "sentence", "n_words": 1000,
...      "machine": {"count": 2}, "human": {"count": 1}}
>>> b = {**a, "n_words": 500, "machine": {"count": 5}, "human": {"count": 0}}
>>> p = pooled([a, b])
>>> p["machine"]
{'count': 7, 'per_1000_words': 4.67, 'range': [2.0, 10.0]}
>>> p["n_texts"], p["n_words"]
(2, 1500)
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]


# _autosummary/ductus.core.html.md

# ductus.core

The core: stream segments, or take the whole report. Everything else is a surface.

Two entry points, and the second is a facade over the first:

[`iter_segments()`](_autosummary/ductus.core.html.md#ductus.core.iter_segments) yields one [`Segment`](_autosummary/ductus.base.html.md#ductus.base.Segment) at a time as it
scores them – the streaming surface, for long documents and for a UI that wants
to paint as results arrive.

[`gauge()`](_autosummary/ductus.core.html.md#ductus.core.gauge) collects them into a [`Report`](_autosummary/ductus.base.html.md#ductus.base.Report).

The three seams are keyword arguments, each defaulting to something that
genuinely works rather than to a stub. The `aggregate=` default normalises evidence
by how much text produced it; the length-blind [`ductus.score.aggregate()`](_autosummary/ductus.score.html.md#ductus.score.aggregate) is still
there, and `misc/docs/phase-2-results.md` has the measurement that chose between
them – on human-written text the length-blind scorer’s false-accusation rate ran from
11% to 74% with document length alone.

| seam         | v1 default                                                                                                       | swap in                                                                                          |
|--------------|------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------|
| `segmenter=` | `"paragraph"`                                                                                                    | `"sentence"`, a callable                                                                         |
| `detectors=` | all four deterministic detectors                                                                                 | a model-based detector                                                                           |
| `aggregate=` | [`ductus.score.density_aggregate()`](_autosummary/ductus.score.html.md#ductus.score.density_aggregate) | [`ductus.score.aggregate()`](_autosummary/ductus.score.html.md#ductus.score.aggregate) |

`extra_signals=` is not a seam but an input: evidence produced elsewhere –
by an agent reading the text, by a vendor API – attached to the segment that
contains it. It is how the shipped skills feed a model’s reading back in.

```pycon
>>> report = gauge("Great question! Let's delve into this robust tapestry.")
>>> report.document.label
'leans-machine'
>>> report = gauge("Sent the export Friday. Two sites, not five. Call if it breaks.")
>>> report.document.label
'no-evidence'
```

### Functions

| [`gauge`](_autosummary/ductus.core.html.md#ductus.core.gauge)(text, \*[, segmenter, detectors, ...])   | Score `text` and roll the segments up into a report.   |
|-------------------------------------------------------------------------------------------------|--------------------------------------------------------|
| [`iter_segments`](_autosummary/ductus.core.html.md#ductus.core.iter_segments)(text, \*[, segmenter, ...])      | Yield one scored segment at a time.                    |

### ductus.core.gauge(text, \*, segmenter='paragraph', detectors=None, aggregate=<function density_aggregate>, extra_signals=())

Score `text` and roll the segments up into a report.

The document-level verdict is computed from the **segment verdicts**, by
[`ductus.score.roll_up()`](_autosummary/ductus.score.html.md#ductus.score.roll_up), not from the pooled signals. Pooling every signal in
the document and scoring the heap is what made a long human document more likely
to be accused for being long: with a ~3% per-segment false-flag rate, the chance
that something fires grows with the segment count. What is asked instead is what
*fraction* of the segments carry directional evidence and which way they point –
length-normalised by construction. `misc/docs/document-verdict-decision.md` has
the argument and what it cost.

The segments themselves are untouched by this, and remain the better evidence: a
flagged sentence says much more than a flagged document.

```pycon
>>> r = gauge("It is important to note that this is a robust tapestry.")
>>> r.document.lean > 0 and r.n_chars == 55
True
>>> r.segmenter, len(r.detectors)
('paragraph', 4)
```

* **Return type:**
  [`Report`](_autosummary/ductus.base.html.md#ductus.base.Report)

### ductus.core.iter_segments(text, \*, segmenter='paragraph', detectors=None, aggregate=<function density_aggregate>, extra_signals=())

Yield one scored segment at a time.

```pycon
>>> segs = list(iter_segments("Let's delve in.\n\nSent it Friday."))
>>> len(segs), segs[0].label
(2, 'leans-machine')
```

* **Return type:**
  [`Iterator`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterator)[[`Segment`](_autosummary/ductus.base.html.md#ductus.base.Segment)]


# _autosummary/ductus.curvature.html.md

# ductus.curvature

Model-based detectors – the `[local]` extra. Two more functions of the same shape.

[`fast_detect_gpt()`](_autosummary/ductus.curvature.html.md#ductus.curvature.fast_detect_gpt) and [`binoculars()`](_autosummary/ductus.curvature.html.md#ductus.curvature.binoculars) are `(text, span) -> Iterator[Signal]`
like every other detector here. They differ in one way that matters: their evidence
is a number a reader cannot inspect, produced by a language model rather than quoted
from the text. The whole design of how that number becomes a [`Signal`](_autosummary/ductus.base.html.md#ductus.base.Signal)
is argued in `misc/docs/curvature-as-evidence.md`; the short version is:

* the statistic is the published one, evaluated over the span’s tokens;
* it is compared to **the same statistic over the rest of this document**, never to a
  threshold lifted from a paper’s benchmark – so no calibration is claimed anywhere;
* the standing is banded, not mapped continuously: a mid-range score emits *nothing*,
  because a mid-range score is this detector having nothing to say;
* both directions are emitted, because a detector that can only accuse is not a
  measuring instrument.

The consequence, accepted knowingly: these detectors cannot say whether a whole
document is machine-written. With no rest-of-the-document to compare against, they
return nothing.

`torch` and `transformers` are imported only when a detector actually runs, so
`import ductus` stays as cheap as it was.

```pycon
>>> band_of(0.9) is None, band_of(1.8), band_of(-3.0)
(True, 0.3, 0.45)
>>> round(robust_z(10.0, [1.0, 2.0, 3.0, 4.0, 5.0]), 2)
4.72
```

### Module Attributes

| [`FAST_DETECT_MODEL`](_autosummary/ductus.curvature.html.md#ductus.curvature.FAST_DETECT_MODEL)   | Single model, used as both the scoring and the sampling model (the analytic same-model setting of Fast-DetectGPT).   |
|----------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------|
| [`BINOCULARS_OBSERVER`](_autosummary/ductus.curvature.html.md#ductus.curvature.BINOCULARS_OBSERVER) | Binoculars needs a *closely related* pair sharing one tokenizer, not an arbitrary strong/weak combination.           |
| [`BANDS`](_autosummary/ductus.curvature.html.md#ductus.curvature.BANDS)               | `(|z| threshold, weight)`, lowest first.                                                                             |
| [`MIN_WINDOWS`](_autosummary/ductus.curvature.html.md#ductus.curvature.MIN_WINDOWS)         | Fewer comparable windows than this and there is no reference distribution worth the name, so nothing is emitted.     |
| [`MIN_TOKENS`](_autosummary/ductus.curvature.html.md#ductus.curvature.MIN_TOKENS)          | A span shorter than this is too few tokens for the statistic to mean anything -- roughly a sentence's worth.         |

### Functions

| [`band_of`](_autosummary/ductus.curvature.html.md#ductus.curvature.band_of)(z[, bands])                           | The weight for a standing of `z`, or `None` when it says nothing.                |
|------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------|
| [`binoculars`](_autosummary/ductus.curvature.html.md#ductus.curvature.binoculars)(text, span, \*[, observer, ...])   | Cross-perplexity of a paired observer and performer, as a standing in this text. |
| [`fast_detect_gpt`](_autosummary/ductus.curvature.html.md#ductus.curvature.fast_detect_gpt)(text, span, \*[, model, ...]) | Conditional probability curvature, read as a standing within this document.      |
| [`robust_z`](_autosummary/ductus.curvature.html.md#ductus.curvature.robust_z)(value, reference)                    | How far `value` stands out from `reference`, in MADs.                            |

### ductus.curvature.BANDS *: [tuple](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[tuple](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[float](https://docs.python.org/3/builtins/functions.html#float), [float](https://docs.python.org/3/builtins/functions.html#float)], ...]* *= ((1.5, 0.3), (2.5, 0.45))*

`(|z| threshold, weight)`, lowest first. Below the first threshold the detector
emits nothing at all – the dead zone is the point, not an oversight. Neither
weight exceeds the strongest deterministic signal: a statistic the reader cannot
inspect does not get to outvote one they can.

### ductus.curvature.BINOCULARS_OBSERVER *= 'distilgpt2'*

Binoculars needs a *closely related* pair sharing one tokenizer, not an
arbitrary strong/weak combination. `distilgpt2` is a distillation of `gpt2`.
The documented upgrade is the paper’s `tiiuae/falcon-7b` pair.

### ductus.curvature.FAST_DETECT_MODEL *= 'gpt2'*

Single model, used as both the scoring and the sampling model (the analytic
same-model setting of Fast-DetectGPT). Small enough for CPU; the documented
upgrade is `EleutherAI/gpt-neo-2.7B`.

### ductus.curvature.MIN_TOKENS *= 16*

A span shorter than this is too few tokens for the statistic to mean anything –
roughly a sentence’s worth.

### ductus.curvature.MIN_WINDOWS *= 6*

Fewer comparable windows than this and there is no reference distribution worth
the name, so nothing is emitted.

### ductus.curvature.band_of(z, bands=((1.5, 0.3), (2.5, 0.45)))

The weight for a standing of `z`, or `None` when it says nothing.

```pycon
>>> band_of(1.49) is None
True
>>> band_of(1.5), band_of(2.49), band_of(2.5), band_of(-9.0)
(0.3, 0.3, 0.45, 0.45)
```

* **Return type:**
  [`float`](https://docs.python.org/3/builtins/functions.html#float) | [`None`](https://docs.python.org/3/builtins/constants.html#None)

### ductus.curvature.binoculars(text, span, , observer='distilgpt2', performer='gpt2', bands=((1.5, 0.3), (2.5, 0.45)), min_windows=6, min_tokens=16, device=None)

Cross-perplexity of a paired observer and performer, as a standing in this text.

Where [`fast_detect_gpt()`](_autosummary/ductus.curvature.html.md#ductus.curvature.fast_detect_gpt) asks how predictable a passage is, this asks whether
two closely related models are *unusually unsurprised in the same places* – which
generalises better to generators neither model has seen.

Needs the `[local]` extra, and observer and performer must share a tokenizer.

* **Return type:**
  [`Iterator`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterator)[[`Signal`](_autosummary/ductus.base.html.md#ductus.base.Signal)]

### ductus.curvature.fast_detect_gpt(text, span, , model='gpt2', bands=((1.5, 0.3), (2.5, 0.45)), min_windows=6, min_tokens=16, device=None)

Conditional probability curvature, read as a standing within this document.

A passage a model finds unusually *predictable* compared to the rest of the
document leans machine; an unusually surprising one leans human. Neither claim
is absolute, and none of the paper’s benchmark thresholds are used.

Needs the `[local]` extra. The first call downloads and caches the proxy model;
later calls on the same text cost no model time at all.

* **Return type:**
  [`Iterator`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterator)[[`Signal`](_autosummary/ductus.base.html.md#ductus.base.Signal)]

### ductus.curvature.robust_z(value, reference)

How far `value` stands out from `reference`, in MADs.

Median and MAD rather than mean and standard deviation: on a mixed document the
machine-written stretches are exactly the outliers that would drag a mean toward
themselves and hide the thing being looked for.

A degenerate reference (every value identical) yields `0.0`, which falls in the
dead zone and so emits nothing.

```pycon
>>> robust_z(3.0, [1.0, 2.0, 3.0, 4.0, 5.0])
0.0
>>> robust_z(1.0, [1.0, 1.0, 1.0])
0.0
```

* **Return type:**
  [`float`](https://docs.python.org/3/builtins/functions.html#float)


# _autosummary/ductus.data.html.md

# ductus.data

Bundled non-code data: the tells catalogue, agent skills, and the reader subagent.


# _autosummary/ductus.detect.html.md

# ductus.detect

The detectors – the `detectors=` seam. Each one turns a span into evidence.

A detector is a plain function `(text, span) -> Iterator[Signal]`. That is the
entire interface; there is no base class and nothing to register. Four ship, all
deterministic and dependency-free:

`tells`
: Catalogue phrase matches (see [`ductus.tells`](_autosummary/ductus.tells.html.md#module-ductus.tells)). Finds vocabulary.

`forensic`
: Typographic and mechanical artifacts – em dashes, mixed apostrophes, a hard
  line break mid-sentence, trailing whitespace. The cheapest signal in the
  package and often the most decisive, because these are traces of *how* the
  text was produced rather than of how it reads.

`rhetoric`
: Sentence *shapes* a catalogue cannot see: the “not X but Y” antithesis, a
  colon introducing a three-part parallel enumeration, concession-then-pivot.

`rhythm`
: Burstiness – the variance of sentence length. Weak evidence, and reported
  as weak.

Two more ship behind the `[local]` extra – `fast-detect-gpt` and
`binoculars`, in [`ductus.curvature`](_autosummary/ductus.curvature.html.md#module-ductus.curvature). They are registered here so they can be
named, but whether they belong in [`DEFAULT_DETECTORS`](_autosummary/ductus.detect.html.md#ductus.detect.DEFAULT_DETECTORS) is settled by
measurement, not by being new – see `misc/docs/phase-1-results.md`.

Adding another one – a vendor API, a supervised classifier – means writing one more
function of this shape. Nothing else in the package changes.

```pycon
>>> from ductus.base import Span
>>> t = "The results were not merely good, but transformative."
>>> [s.name for s in rhetoric(t, Span.of(t, 0, len(t)))]
['not-x-but-y']
>>> t2 = "It matters — a lot — and always has."
>>> [s.name for s in forensic(t2, Span.of(t2, 0, len(t2)))]
['em-dash', 'em-dash']
```

### Module Attributes

| [`DETECTORS`](_autosummary/ductus.detect.html.md#ductus.detect.DETECTORS)         | The registry the `detectors=` seam resolves names against.                                                                      |
|--------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------|
| [`DEFAULT_DETECTORS`](_autosummary/ductus.detect.html.md#ductus.detect.DEFAULT_DETECTORS) | a detector joins this tuple only after it has measurably beaten what is already here on `tests/fixtures/mixed_authorship.json`. |

### Functions

| [`binoculars`](_autosummary/ductus.detect.html.md#ductus.detect.binoculars)(text, span, \*[, observer, ...])   | Cross-perplexity of a paired observer and performer, as a standing in this text.   |
|------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------|
| [`detectors_from`](_autosummary/ductus.detect.html.md#ductus.detect.detectors_from)(names)                         | Resolve a detector spec into callables and their names.                            |
| [`fast_detect_gpt`](_autosummary/ductus.detect.html.md#ductus.detect.fast_detect_gpt)(text, span, \*[, model, ...]) | Conditional probability curvature, read as a standing within this document.        |
| [`forensic`](_autosummary/ductus.detect.html.md#ductus.detect.forensic)(text, span)                          | Typographic and mechanical artifacts of how the text was produced.                 |
| [`rhetoric`](_autosummary/ductus.detect.html.md#ductus.detect.rhetoric)(text, span)                          | Sentence shapes a phrase catalogue cannot see.                                     |
| [`rhythm`](_autosummary/ductus.detect.html.md#ductus.detect.rhythm)(text, span)                            | Burstiness: how much sentence length varies.                                       |
| [`tells`](_autosummary/ductus.detect.html.md#ductus.detect.tells)(text, span)                             | Catalogue phrase matches, as signals.                                              |

### ductus.detect.DEFAULT_DETECTORS *: [tuple](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), ...]* *= ('tells', 'forensic', 'rhetoric', 'rhythm')*

a detector
joins this tuple only after it has measurably beaten what is already here on
`tests/fixtures/mixed_authorship.json`. See `misc/docs/phase-1-results.md`.

* **Type:**
  What `detectors=None` means. Deliberately *not* `list(DETECTORS)`

### ductus.detect.DETECTORS *: [dict](https://docs.python.org/3/builtins/stdtypes.html#dict)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), [Callable](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[[str](https://docs.python.org/3/builtins/stdtypes.html#str), [Span](_autosummary/ductus.base.html.md#ductus.base.Span)], [Iterator](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterator)[[Signal](_autosummary/ductus.base.html.md#ductus.base.Signal)]]]* *= {'binoculars': <function binoculars>, 'fast-detect-gpt': <function fast_detect_gpt>, 'forensic': <function forensic>, 'rhetoric': <function rhetoric>, 'rhythm': <function rhythm>, 'tells': <function tells>}*

The registry the `detectors=` seam resolves names against. It holds more than
the default: the model-based detectors are nameable here so `--detectors
fast-detect-gpt` works, without being on by default. Registering is cheap –
[`ductus.curvature`](_autosummary/ductus.curvature.html.md#module-ductus.curvature) imports nothing heavier than [`ductus.base`](_autosummary/ductus.base.html.md#module-ductus.base) until one
of its detectors is actually called.

### ductus.detect.binoculars(text, span, , observer='distilgpt2', performer='gpt2', bands=((1.5, 0.3), (2.5, 0.45)), min_windows=6, min_tokens=16, device=None)

Cross-perplexity of a paired observer and performer, as a standing in this text.

Where [`fast_detect_gpt()`](_autosummary/ductus.detect.html.md#ductus.detect.fast_detect_gpt) asks how predictable a passage is, this asks whether
two closely related models are *unusually unsurprised in the same places* – which
generalises better to generators neither model has seen.

Needs the `[local]` extra, and observer and performer must share a tokenizer.

* **Return type:**
  [`Iterator`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterator)[[`Signal`](_autosummary/ductus.base.html.md#ductus.base.Signal)]

### ductus.detect.detectors_from(names)

Resolve a detector spec into callables and their names.

```pycon
>>> fns, names = detectors_from(["forensic"])
>>> names
('forensic',)
>>> _, names = detectors_from(None)
>>> names
('tells', 'forensic', 'rhetoric', 'rhythm')
```

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Span`](_autosummary/ductus.base.html.md#ductus.base.Span)], [`Iterator`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterator)[[`Signal`](_autosummary/ductus.base.html.md#ductus.base.Signal)]]], [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`...`](https://docs.python.org/3/builtins/constants.html#Ellipsis)]]

### ductus.detect.fast_detect_gpt(text, span, , model='gpt2', bands=((1.5, 0.3), (2.5, 0.45)), min_windows=6, min_tokens=16, device=None)

Conditional probability curvature, read as a standing within this document.

A passage a model finds unusually *predictable* compared to the rest of the
document leans machine; an unusually surprising one leans human. Neither claim
is absolute, and none of the paper’s benchmark thresholds are used.

Needs the `[local]` extra. The first call downloads and caches the proxy model;
later calls on the same text cost no model time at all.

* **Return type:**
  [`Iterator`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterator)[[`Signal`](_autosummary/ductus.base.html.md#ductus.base.Signal)]

### ductus.detect.forensic(text, span)

Typographic and mechanical artifacts of how the text was produced.

Several of these argue for a *human*, which is the point: a detector that can
only ever accuse is not a measuring instrument.

```pycon
>>> from ductus.base import Span
>>> t = "he said\nand then left"
>>> [s.name for s in forensic(t, Span.of(t, 0, len(t)))]
['mid-sentence-newline', 'no-terminal-punctuation']
```

* **Return type:**
  [`Iterator`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterator)[[`Signal`](_autosummary/ductus.base.html.md#ductus.base.Signal)]

### ductus.detect.rhetoric(text, span)

Sentence shapes a phrase catalogue cannot see.

These are the patterns that survive a model being told to avoid “AI words”,
which is why they matter more than vocabulary as models improve.

```pycon
>>> from ductus.base import Span
>>> t = "This is a pattern: you plan it, you build it, and you ship it."
>>> [s.name for s in rhetoric(t, Span.of(t, 0, len(t)))]
['colon-tricolon']
```

* **Return type:**
  [`Iterator`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterator)[[`Signal`](_autosummary/ductus.base.html.md#ductus.base.Signal)]

### ductus.detect.rhythm(text, span)

Burstiness: how much sentence length varies.

Uniform lengths lean machine, uneven lengths lean human. This is the weakest
detector here and the thresholds come from the shared catalogue metrics, not
from a fitted model – treat it as a tiebreaker, never as a finding.

```pycon
>>> from ductus.base import Span
>>> t = ("One two three four five six. " * 7)
>>> [s.name for s in rhythm(t, Span.of(t, 0, len(t)))]
['low-burstiness']
```

* **Return type:**
  [`Iterator`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterator)[[`Signal`](_autosummary/ductus.base.html.md#ductus.base.Signal)]

### ductus.detect.tells(text, span)

Catalogue phrase matches, as signals. Quoted text is skipped.

```pycon
>>> from ductus.base import Span
>>> t = "Let's delve into it."
>>> [(s.name, s.direction) for s in tells(t, Span.of(t, 0, len(t)))]
[('ai-vocabulary', 'machine')]
>>> q = 'Models overuse "delve", so avoid it.'
>>> list(tells(q, Span.of(q, 0, len(q))))
[]
```

* **Return type:**
  [`Iterator`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterator)[[`Signal`](_autosummary/ductus.base.html.md#ductus.base.Signal)]


# _autosummary/ductus.html.md

# ductus

ductus – gauge which parts of a text read as machine-written, and why.

In palaeography the *ductus* is the characteristic manner and sequence of strokes
by which a scribe’s hand is recognised. This package looks for the equivalent in
prose: not a verdict about who wrote something, but evidence about how it reads,
attached to the exact characters that carry it.

```pycon
>>> from ductus import gauge
>>> report = gauge("Great question! Let's delve into this robust tapestry.")
>>> report.document.label
'leans-machine'
>>> report.segments[0].signals[0].name
'chat-leftover'
```

Every finding is a [`Signal`](_autosummary/ductus.html.md#ductus.Signal) with a direction, a weight, the detector that
produced it, a reason, and a [`Span`](_autosummary/ductus.html.md#ductus.Span) carrying both character offsets and
W3C-style quote/prefix/suffix selectors, so highlights survive an edit.

**There is no percentage anywhere in this package, and that is deliberate.** A
number like “87% AI” reads as a calibrated probability, is not one, and is how
people get falsely accused. What you get instead is a lean in [-1, +1], an
evidence strength, and a coarse label you can argue with. See
[`ductus.score`](_autosummary/ductus.score.html.md#module-ductus.score).

Three seams, each one keyword argument with a working default:
`segmenter=` (how the text is cut up), `detectors=` (what produces evidence),
`aggregate=` (how evidence becomes a lean).

**This package’s own false-positive rate is measured**: 0.9% of human-written
documents are called `leans-machine` by the shipped defaults (20.6% before the rules,
the roll-up and the document threshold were corrected), and a flagged *sentence* is much
better evidence than a flagged *document*, which is now rarely called either way. See
`misc/docs/non-native-calibration.md` before reporting anything from this.

### Functions

| [`aggregate`](_autosummary/ductus.html.md#ductus.aggregate)(signals, \*[, n_chars])                | Reduce evidence to `(lean, strength, label)`.                                                                         |
|---------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------|
| [`density_aggregate`](_autosummary/ductus.html.md#ductus.density_aggregate)(signals, \*[, n_chars])        | Like [`aggregate()`](_autosummary/ductus.html.md#ductus.aggregate), but `strength` is an evidence *rate*, not a total. |
| [`gauge`](_autosummary/ductus.html.md#ductus.gauge)(text, \*[, segmenter, detectors, ...])     | Score `text` and roll the segments up into a report.                                                                  |
| [`iter_segments`](_autosummary/ductus.html.md#ductus.iter_segments)(text, \*[, segmenter, ...])        | Yield one scored segment at a time.                                                                                   |
| [`iter_tell_matches`](_autosummary/ductus.html.md#ductus.iter_tell_matches)(text, \*[, rules, tiers, ...]) | Every catalogue hit in `text`, in document order.                                                                     |
| [`load_rules`](_autosummary/ductus.html.md#ductus.load_rules)([path])                               | The catalogue's rules, compiled.                                                                                      |
| [`to_html`](_autosummary/ductus.html.md#ductus.to_html)(report, \*[, text, title, subtitle])     | A single self-contained HTML file.                                                                                    |
| [`to_json`](_autosummary/ductus.html.md#ductus.to_json)(report, \*[, indent])                    | The whole report, serialized.                                                                                         |
| [`to_markdown`](_autosummary/ductus.html.md#ductus.to_markdown)(report, \*[, text, title])           | A readable diagnosis: synopsis first, then the flagged segments.                                                      |

### Classes

| [`Report`](_autosummary/ductus.html.md#ductus.Report)(text_sha256, n_chars, document, ...)      | Everything a downstream consumer needs, and nothing it has to guess at.   |
|---------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------|
| [`Segment`](_autosummary/ductus.html.md#ductus.Segment)(span[, signals, lean, strength, label])  | A unit of text, the signals on it, and the lean they add up to.           |
| [`Signal`](_autosummary/ductus.html.md#ductus.Signal)(name, direction, weight, detector[, ...]) | One piece of evidence about one span.                                     |
| [`Span`](_autosummary/ductus.html.md#ductus.Span)(start, end, quote[, prefix, suffix, level]) | A character range, with redundant selectors so it survives an edit.       |
| [`TellMatch`](_autosummary/ductus.html.md#ductus.TellMatch)(rule_id, tier, message, start, ...)    | Where a rule fired, and on what text.                                     |
| [`TellRule`](_autosummary/ductus.html.md#ductus.TellRule)(id, tier, message, patterns[, ...])     | One named rule: a tier, a message, and the patterns that trigger it.      |

### *class* ductus.Report(text_sha256, n_chars, document, segments, detectors, segmenter, schema_version='1', calibration='uncalibrated', meta=dict())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Everything a downstream consumer needs, and nothing it has to guess at.

#### *property* signals *: [tuple](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[Signal](_autosummary/ductus.base.html.md#ductus.base.Signal), ...]*

Every signal in the report, in document order.

### *class* ductus.Segment(span, signals=(), lean=0.0, strength=0.0, label='no-evidence')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A unit of text, the signals on it, and the lean they add up to.

`lean` runs from -1 (every signal argues human) to +1 (every signal argues
machine). `strength` is how much evidence there is at all – a lean of
+1.0 from a single weak signal is not the same claim as +1.0 from six.

### *class* ductus.Signal(name, direction, weight, detector, value=None, note='', span=None)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One piece of evidence about one span.

`weight` is how much this moves the needle, in `0..1`. It is a weight,
not a probability: two 0.5 signals pointing the same way are stronger than
one, and nothing here claims to be calibrated.

```pycon
>>> Signal("em-dash", "machine", 0.2, "forensic", value=3).name
'em-dash'
```

### *class* ductus.Span(start, end, quote, prefix='', suffix='', level='segment')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A character range, with redundant selectors so it survives an edit.

Offsets count **code points** (Python `str` indices), not bytes and not
UTF-16 units – a JavaScript client must convert after any astral character.

`start`/`end` are a `TextPositionSelector`; `quote` with `prefix`
and `suffix` is a `TextQuoteSelector`. Keeping both is what lets a
viewer re-find a finding after the text around it changed.

```pycon
>>> s = Span.of("one two three", 4, 7, level="sentence")
>>> (s.start, s.end, s.quote, s.level)
(4, 7, 'two', 'sentence')
>>> s.length
3
```

#### contains(other)

Whether `other` falls entirely inside this span.

```pycon
>>> a, b = Span.of("abcdef", 0, 6), Span.of("abcdef", 2, 4)
>>> a.contains(b), b.contains(a)
(True, False)
```

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

#### *classmethod* of(text, start, end, , level='segment')

Build a span over `text`, capturing its re-anchoring context.

```pycon
>>> Span.of("abcdef", 2, 4).suffix
'ef'
```

* **Return type:**
  [`Span`](_autosummary/ductus.base.html.md#ductus.base.Span)

### *class* ductus.TellMatch(rule_id, tier, message, start, end, matched, weight=0.0)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Where a rule fired, and on what text.

#### weight *: [float](https://docs.python.org/3/builtins/functions.html#float)* *= 0.0*

The rule’s evidential weight – its per-rule override when it has one, else its
tier’s. Carried here so a consumer never has to re-derive it from `tier`, which
would silently discard the override. Defaulted so existing constructions still
work; [`iter_tell_matches()`](_autosummary/ductus.html.md#ductus.iter_tell_matches) always fills it in.

### *class* ductus.TellRule(id, tier, message, patterns, weight_override=None)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One named rule: a tier, a message, and the patterns that trigger it.

#### *property* weight *: [float](https://docs.python.org/3/builtins/functions.html#float)*

the per-rule override when set, else the tier’s.

```pycon
>>> TellRule("x", "E", "m", (), weight_override=0.15).weight
0.15
>>> TellRule("x", "E", "m", ()).weight
0.5
```

* **Type:**
  Evidential weight

#### weight_override *: [float](https://docs.python.org/3/builtins/functions.html#float) | [None](https://docs.python.org/3/builtins/constants.html#None)* *= None*

An optional per-rule override of the tier’s weight, read from `weight:` in
the catalogue. It exists because a rule’s **tier** and its \*\*evidential
weight\*\* answer different questions, and a rule can be right about one and
wrong about the other: `summary-closer` catches “In conclusion,” which is
reasonable style advice (`acquaint` enforces tiers) and almost worthless as
evidence about *who wrote the text* (`ductus` uses weights). Overriding the
weight changes this package only – `acquaint` reads `tier` and never
`weight`. Changing a tier is a two-package decision; see
`misc/docs/document-verdict-decision.md`.

### ductus.aggregate(signals, , n_chars=None)

Reduce evidence to `(lean, strength, label)`. Length-blind, by construction.

Neutral signals count toward `strength` but never toward `lean` – they
are real evidence that the passage is unusual without being evidence about
who wrote it.

`n_chars` is accepted and **deliberately ignored**. The seam passes it so a
scorer *can* reason about how much text produced the evidence; this one does not,
which is a choice with a measured cost: on human-written text the chance of a
false accusation rises from 11% to 74% with document length alone, because two
stray signals weigh the same in 600 characters as in 3000. See
[`density_aggregate()`](_autosummary/ductus.html.md#ductus.density_aggregate) and `misc/docs/phase-2-results.md`.

```pycon
>>> from ductus.base import Signal
>>> aggregate([Signal("x", "human", 0.6, "d")])
(-1.0, 0.4, 'leans-human')
>>> aggregate([Signal("x", "neutral", 0.9, "d")])
(0.0, 0.6, 'uncertain')
```

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### ductus.density_aggregate(signals, , n_chars=None)

Like [`aggregate()`](_autosummary/ductus.html.md#ductus.aggregate), but `strength` is an evidence *rate*, not a total.

Two signals in 600 characters is a different claim from two in 3000, and the
length-blind scorer cannot tell them apart. This one divides the evidence by how
much text produced it, above a reference length of `REFERENCE_CHARS`.

`lean` is untouched. It still reads ±1.0 off a single weak signal, and that
jaggedness is deliberate – smoothing it is how `lean` would quietly become a
quantity-integrating score, which is to say a probability. See
`misc/docs/what-calibration-means-here.md`.

The scaling only ever *divides*, never multiplies, so this scorer can only remove
accusations, never add one. Short passages behave exactly as before.

```pycon
>>> from ductus.base import Signal
>>> evidence = [Signal("x", "machine", 0.4, "d")]
>>> density_aggregate(evidence, n_chars=500)        # short: unchanged
(1.0, 0.267, 'leans-machine')
>>> density_aggregate(evidence, n_chars=4000)       # the same evidence, spread thin
(1.0, 0.067, 'no-evidence')
>>> density_aggregate(evidence) == aggregate(evidence)  # no length, no opinion
True
```

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### ductus.gauge(text, \*, segmenter='paragraph', detectors=None, aggregate=<function density_aggregate>, extra_signals=())

Score `text` and roll the segments up into a report.

The document-level verdict is computed from the **segment verdicts**, by
[`ductus.score.roll_up()`](_autosummary/ductus.score.html.md#ductus.score.roll_up), not from the pooled signals. Pooling every signal in
the document and scoring the heap is what made a long human document more likely
to be accused for being long: with a ~3% per-segment false-flag rate, the chance
that something fires grows with the segment count. What is asked instead is what
*fraction* of the segments carry directional evidence and which way they point –
length-normalised by construction. `misc/docs/document-verdict-decision.md` has
the argument and what it cost.

The segments themselves are untouched by this, and remain the better evidence: a
flagged sentence says much more than a flagged document.

```pycon
>>> r = gauge("It is important to note that this is a robust tapestry.")
>>> r.document.lean > 0 and r.n_chars == 55
True
>>> r.segmenter, len(r.detectors)
('paragraph', 4)
```

* **Return type:**
  [`Report`](_autosummary/ductus.base.html.md#ductus.base.Report)

### ductus.iter_segments(text, \*, segmenter='paragraph', detectors=None, aggregate=<function density_aggregate>, extra_signals=())

Yield one scored segment at a time.

```pycon
>>> segs = list(iter_segments("Let's delve in.\n\nSent it Friday."))
>>> len(segs), segs[0].label
(2, 'leans-machine')
```

* **Return type:**
  [`Iterator`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterator)[[`Segment`](_autosummary/ductus.base.html.md#ductus.base.Segment)]

### ductus.iter_tell_matches(text, , rules=None, tiers=None, offset=0)

Every catalogue hit in `text`, in document order.

`offset` is added to every position, so a caller scanning one segment of a
larger document gets offsets into the document.

```pycon
>>> [m.rule_id for m in iter_tell_matches("In conclusion, it's important to note this.")]
['summary-closer', 'throat-clearing']
>>> [m.start for m in iter_tell_matches("delve", offset=100)]
[100]
>>> [m.rule_id for m in iter_tell_matches("delve", tiers=["E"])]
[]
```

* **Return type:**
  [`Iterator`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterator)[[`TellMatch`](_autosummary/ductus.tells.html.md#ductus.tells.TellMatch)]

### ductus.load_rules(path=None)

The catalogue’s rules, compiled.

```pycon
>>> rules = load_rules()
>>> len(rules) > 10 and all(r.patterns for r in rules)
True
>>> sorted({r.tier for r in rules})
['E', 'S', 'W']
```

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`TellRule`](_autosummary/ductus.tells.html.md#ductus.tells.TellRule), [`...`](https://docs.python.org/3/builtins/constants.html#Ellipsis)]

### ductus.to_html(report, , text=None, title='Where this reads as machine-written', subtitle='')

A single self-contained HTML file. `text` defaults to the spans’ own quotes.

```pycon
>>> from ductus.core import gauge
>>> h = to_html(gauge("Let's delve in."))
>>> "<mark" in h and "prefers-color-scheme" in h
True
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### ductus.to_json(report, , indent=2)

The whole report, serialized.

```pycon
>>> from ductus.core import gauge
>>> d = __import__("json").loads(to_json(gauge("delve")))
>>> d["segments"][0]["signals"][0]["detector"]
'tells'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### ductus.to_markdown(report, , text=None, title='Reading')

A readable diagnosis: synopsis first, then the flagged segments.

```pycon
>>> from ductus.core import gauge
>>> md = to_markdown(gauge("In conclusion, this is a robust tapestry."))
>>> md.splitlines()[0].startswith("# ")
True
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### Modules

| [`base`](_autosummary/ductus.base.html.md#module-ductus.base)           | The data model: where a finding lives, what it claims, and how much it weighs.     |
|------------------------------------------------------------------------------------|------------------------------------------------------------------------------------|
| [`consensus`](_autosummary/ductus.consensus.html.md#module-ductus.consensus) | Several close readers, and the sentences at least `k` of them agree on.            |
| [`core`](_autosummary/ductus.core.html.md#module-ductus.core)           | The core: stream segments, or take the whole report.                               |
| [`curvature`](_autosummary/ductus.curvature.html.md#module-ductus.curvature) | Model-based detectors -- the `[local]` extra.                                      |
| [`data`](_autosummary/ductus.data.html.md#module-ductus.data)           | Bundled non-code data: the tells catalogue, agent skills, and the reader subagent. |
| [`detect`](_autosummary/ductus.detect.html.md#module-ductus.detect)       | The detectors -- the `detectors=` seam.                                            |
| [`http`](_autosummary/ductus.http.html.md#module-ductus.http)           | The HTTP surface: the same verbs the CLI dispatches, served over HTTP.             |
| [`limits`](_autosummary/ductus.limits.html.md#module-ductus.limits)       | The measured limits of the shipped defaults: the one place their numbers live.     |
| [`mcp`](_autosummary/ductus.mcp.html.md#module-ductus.mcp)             | The MCP surface: the same verbs the CLI dispatches, emitted as MCP tools.          |
| [`render`](_autosummary/ductus.render.html.md#module-ductus.render)       | Turning a report into something a person reads: JSON, Markdown, or HTML.           |
| [`score`](_autosummary/ductus.score.html.md#module-ductus.score)         | Turning evidence into a lean -- the `aggregate=` seam.                             |
| [`segment`](_autosummary/ductus.segment.html.md#module-ductus.segment)     | Cutting a text into the units that get scored -- the `segmenter=` seam.            |
| [`tells`](_autosummary/ductus.tells.html.md#module-ductus.tells)         | The tells catalogue: named regular-expression patterns, tiered by confidence.      |
| [`tools`](_autosummary/ductus.tools.html.md#module-ductus.tools)         | The verb SSOT: plain functions, JSON-ready in, JSON-ready out.                     |


# _autosummary/ductus.http.html.md

# ductus.http

The HTTP surface: the same verbs the CLI dispatches, served over HTTP.

Like [`ductus.mcp`](_autosummary/ductus.mcp.html.md#module-ductus.mcp), there is **no second verb list here**. [`ROUTED_FUNCS`](_autosummary/ductus.http.html.md#ductus.http.ROUTED_FUNCS)
is *derived* from `ductus.tools._dispatch_funcs` – the one list `cw` builds
the CLI from – so no two surfaces can drift apart and there is no parity test to
write. `qh.mk_app` turns those callables into a FastAPI app; `qh.export_ts_client`
turns the same app’s OpenAPI into the typed client the frontend imports. One registry,
three emitters.

The core did not change to make this work, which is the roadmap’s standing claim.
`ductus.tools` still imports nothing about HTTP, and `qh` lives in the `[http]`
extra, so `import ductus` is unaffected by installing it.

**What this surface found.** A verb list that is safe at a CLI is not automatically
safe when the caller is a stranger. `gauge(source=...)` reads a file when the string
names one, and `gauge(out=...)` writes one – exactly right when you typed the
command yourself, an arbitrary file read and an arbitrary file write when you did not.
Neither the CLI nor a local stdio MCP host can see that, because on those surfaces it
is not a bug. `_guard()` refuses both, driven by the `host_paths` declaration on
the verb itself rather than by this module knowing anything about `gauge`.

Run it:

```default
pip install 'ductus[http]'
ductus-http                     # http://127.0.0.1:8000, /docs for the OpenAPI UI
```

```pycon
>>> ROUTED_FUNCS[0].__name__
'gauge'
>>> "install_skills" in [f.__name__ for f in ROUTED_FUNCS]  # host-mutating, left out
False
```

### Module Attributes

| [`ROUTED_FUNCS`](_autosummary/ductus.http.html.md#ductus.http.ROUTED_FUNCS)   | One callable per read-only verb, derived from the CLI's own list.   |
|-----------------------------------------------------------------|---------------------------------------------------------------------|
| [`DESCRIPTION`](_autosummary/ductus.http.html.md#ductus.http.DESCRIPTION)    | The service description, carried into the OpenAPI document.         |

### Functions

| [`export_client`](_autosummary/ductus.http.html.md#ductus.http.export_client)(\*[, class_name, base_url, app])   | The TypeScript client for this surface, generated from its own OpenAPI.   |
|---------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------|
| [`export_types`](_autosummary/ductus.http.html.md#ductus.http.export_types)()                                   | TypeScript interfaces for the report shape, read off the dataclasses.     |
| [`main`](_autosummary/ductus.http.html.md#ductus.http.main)()                                           | Serve on `127.0.0.1:8000`.                                                |
| [`mk_app`](_autosummary/ductus.http.html.md#ductus.http.mk_app)(\*[, funcs, title, description, ...])     | Build a FastAPI app serving `funcs`, one POST endpoint per verb.          |

### ductus.http.DESCRIPTION *= 'Gauge which parts of a text read as machine-written, with every finding anchored to\\nthe exact characters that carry it.\\n\\nThis service never returns a percentage, a confidence, or a verdict about a person,\\nand a caller should not synthesise one from what it does return. It gives a lean in\\n[-1, +1], an evidence strength, a coarse label, and the signals behind them -- each\\nwith a quote that can be checked against the text.\\n\\nIts false-positive rate on human-written text is measured: with the default\\ndetectors, 0.9% of human-written documents are called \`leans-machine\`. Every one\\nof those is wrong. That rate was bought with recall: the document label is now rare on\\nmachine-written text too, so an unflagged document has not been cleared. A flagged\\n\*sentence\* is much better evidence than a flagged \*document\* -- the per-sentence rate\\nis 0.4-2%.\\n\\nThe bias runs toward formal, fluent, essayistic prose, not toward simple prose. In\\nthe measured corpus the native-speaker control was the most-accused group.\\n\\n"No findings" is a weak result, not a clean bill.\\n'*

The service description, carried into the OpenAPI document. An HTTP client that
reads anything at all reads this, so the limits belong here and not only in a
README. The numbers come from [`ductus.limits`](_autosummary/ductus.limits.html.md#module-ductus.limits).

### ductus.http.ROUTED_FUNCS *: [tuple](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[Callable](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[..., [Any](https://docs.python.org/3/library/typing.html#typing.Any)], ...]* *= (<function gauge>, <function baseline>, <function detectors>, <function segmenters>, <function tells>)*

One callable per read-only verb, derived from the CLI’s own list. Never
hand-written. The filter reads `mutates_host`, declared at each verb’s own
definition – the same rule, and the same reason, as [`ductus.mcp`](_autosummary/ductus.mcp.html.md#module-ductus.mcp).

### ductus.http.export_client(, class_name='DuctusClient', base_url='', app=None)

The TypeScript client for this surface, generated from its own OpenAPI.

The frontend imports the result rather than hand-writing fetch calls, so a
changed Python signature becomes a TypeScript type error instead of a runtime
surprise. `base_url` defaults to empty, which makes every request relative –
correct when the app and the UI are served from the same origin, as
[`mk_app()`](_autosummary/ductus.http.html.md#ductus.http.mk_app) arranges.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### ductus.http.export_types()

TypeScript interfaces for the report shape, read off the dataclasses.

`gauge(format="json")` serialises a [`Report`](_autosummary/ductus.base.html.md#ductus.base.Report) with
`dataclasses.asdict`, so the wire shape *is* the dataclass shape. Generating the
TypeScript from the same definitions is what stops a renamed field from becoming a
silent `undefined` in a browser rather than a failing test.

The generated client types `gauge` as returning `string`, because it does –
a JSON document. [`export_types()`](_autosummary/ductus.http.html.md#ductus.http.export_types) supplies what is inside it.

```pycon
>>> ts = export_types()
>>> "export interface Report {" in ts and "text_sha256: string;" in ts
True
>>> "signals: Signal[];" in ts
True
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### ductus.http.main()

Serve on `127.0.0.1:8000`. The `ductus-http` console script.

Host and port come from `DUCTUS_HTTP_HOST` / `DUCTUS_HTTP_PORT` so a
container can move them without a code change. The default binds to loopback:
a tool that can call a text machine-written should not appear on a network
because someone ran it to look at it.

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

### ductus.http.mk_app(\*, funcs=(<function gauge>, <function baseline>, <function detectors>, <function segmenters>, <function tells>), title='ductus', description='Gauge which parts of a text read as machine-written, with every finding anchored to\\nthe exact characters that carry it.\\n\\nThis service never returns a percentage, a confidence, or a verdict about a person,\\nand a caller should not synthesise one from what it does return. It gives a lean in\\n[-1, +1], an evidence strength, a coarse label, and the signals behind them -- each\\nwith a quote that can be checked against the text.\\n\\nIts false-positive rate on human-written text is measured: with the default\\ndetectors, 0.9% of human-written documents are called \`leans-machine\`. Every one\\nof those is wrong. That rate was bought with recall: the document label is now rare on\\nmachine-written text too, so an unflagged document has not been cleared. A flagged\\n\*sentence\* is much better evidence than a flagged \*document\* -- the per-sentence rate\\nis 0.4-2%.\\n\\nThe bias runs toward formal, fluent, essayistic prose, not toward simple prose. In\\nthe measured corpus the native-speaker control was the most-accused group.\\n\\n"No findings" is a weak result, not a clean bill.\\n', guard_host_paths=True, ui=None, \*\*qh_kwargs)

Build a FastAPI app serving `funcs`, one POST endpoint per verb.

`guard_host_paths` is the seam for the one case that wants it off: a service
bound to loopback for your own use, where reading a local file by name is the
convenience it is at a CLI. It defaults to on, because the safe reading of an
ambiguous deployment is the one that does not hand out the filesystem.

`ui` is a directory of built frontend assets to serve at `/`. When it is
`None`, `DUCTUS_UI_DIR` or `frontend/dist` beside the package is used if it
exists and skipped if it does not – so the API works with no frontend built, and
the two are served same-origin when one is, which is also what lets a browser test
drive the whole thing without CORS. A directory named explicitly and not found is
an error; only the *default* is allowed to be silently absent.

Extra keyword arguments pass straight through to `qh.mk_app`.

Raises [`ImportError`](https://docs.python.org/3/builtins/exceptions.html#ImportError) with an actionable message when the extra is missing.


# _autosummary/ductus.limits.html.md

# ductus.limits

The measured limits of the shipped defaults: the one place their numbers live.

Every surface that states how often this package is wrong (the rendered report’s
footer, the MCP instructions, the OpenAPI description, the frontend’s panels through a
generated `limits.ts`) formats its text from here, and `tests/test_limits.py` checks
that the prose which cannot be formatted (README, the skills, the package docstring)
quotes the same numbers. Re-measure with `misc/measure_false_positives.py` and
`misc/measure_document_threshold.py` after any change to rules, weights or thresholds,
then change the numbers here, once.

They are operating characteristics of the instrument, measured on corpora of known
authorship, never a probability about a document.

```pycon
>>> f"about one in {DOCUMENT_ONE_IN}"
'about one in a hundred'
```

### Module Attributes

| [`SOURCE`](_autosummary/ductus.limits.html.md#ductus.limits.SOURCE)                         | Where the numbers come from.                                                                                                                                          |
|---------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`DOCUMENT_FALSE_ACCUSATION_RATE`](_autosummary/ductus.limits.html.md#ductus.limits.DOCUMENT_FALSE_ACCUSATION_RATE) | Human-written documents called `leans-machine` by the defaults (held-out non-native essays and the 350-document W&I+LOCNESS dev set, both granularities, rounded up). |
| [`DOCUMENT_ONE_IN`](_autosummary/ductus.limits.html.md#ductus.limits.DOCUMENT_ONE_IN)                | The same, as the natural frequency the interfaces use next to a verdict: "about one human-written document in {DOCUMENT_ONE_IN}".                                     |
| [`MACHINE_DOCUMENT_RECALL`](_autosummary/ductus.limits.html.md#ductus.limits.MACHINE_DOCUMENT_RECALL)        | the recall the rate above was bought with.                                                                                                                            |
| [`SENTENCE_FALSE_FLAG_RANGE`](_autosummary/ductus.limits.html.md#ductus.limits.SENTENCE_FALSE_FLAG_RANGE)      | Human-written sentences flagged `leans-machine`, across proficiency bands.                                                                                            |

### Functions

| [`as_typescript`](_autosummary/ductus.limits.html.md#ductus.limits.as_typescript)()   | The constants as a TypeScript module, for `frontend/src/generated/limits.ts`.   |
|--------------------------------------------------------------------|---------------------------------------------------------------------------------|

### ductus.limits.DOCUMENT_FALSE_ACCUSATION_RATE *= '0.9%'*

Human-written documents called `leans-machine` by the defaults (held-out non-native
essays and the 350-document W&I+LOCNESS dev set, both granularities, rounded up).

### ductus.limits.DOCUMENT_ONE_IN *= 'a hundred'*

The same, as the natural frequency the interfaces use next to a verdict:
“about one human-written document in {DOCUMENT_ONE_IN}”.

### ductus.limits.MACHINE_DOCUMENT_RECALL *= 'about 2%'*

the recall the
rate above was bought with.

* **Type:**
  Machine-written essays the document verdict calls `leans-machine`

### ductus.limits.SENTENCE_FALSE_FLAG_RANGE *= '0.4-2%'*

Human-written sentences flagged `leans-machine`, across proficiency bands.

### ductus.limits.SOURCE *= 'misc/docs/non-native-calibration.md'*

Where the numbers come from.

### ductus.limits.as_typescript()

The constants as a TypeScript module, for `frontend/src/generated/limits.ts`.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)


# _autosummary/ductus.mcp.html.md

# ductus.mcp

The MCP surface: the same verbs the CLI dispatches, emitted as MCP tools.

There is **no second verb list here**, and that is the whole design. [`TOOL_REFS`](_autosummary/ductus.mcp.html.md#ductus.mcp.TOOL_REFS)
is *derived* from `ductus.tools._dispatch_funcs` – the same list `cw` builds
the CLI from – so the two surfaces cannot drift apart. The roadmap’s rule is that a
parity test between two surfaces means there are two implementations; the fix is to
have one list, not two lists and a test that watches them.

The refs are **strings**, resolved by `py2mcp` at call time, so `ductus.tools`
never imports MCP and neither does the core. `py2mcp` lives in the `[mcp]` extra
and is imported only when a server is actually built.

Verbs marked [`ductus.tools.host_mutating()`](_autosummary/ductus.tools.html.md#ductus.tools.host_mutating) are left out. `install_skills`
symlinks into an agent host’s skills directory: a person typing it at a CLI chose to,
a remote caller did not necessarily. That filter reads a property declared at the
function’s own definition, so it is still one list.

`gauge(out=...)` writes a file, and is *not* excluded – writing the report you asked
for is the verb doing its job. A deployed server that should not write anywhere is what
`middleware=` is for; it is passed straight through, along with `auth=`.

Run it:

```default
pip install 'ductus[mcp]'
ductus-mcp                      # stdio, for a local agent host
```

```pycon
>>> TOOL_REFS[:2]
('ductus.tools:gauge', 'ductus.tools:baseline')
>>> all(ref.startswith("ductus.tools:") for ref in TOOL_REFS)
True
>>> "ductus.tools:install_skills" in TOOL_REFS  # host-mutating, left out
False
```

### Module Attributes

| [`TOOL_REFS`](_autosummary/ductus.mcp.html.md#ductus.mcp.TOOL_REFS)    | One ref per read-only verb, derived from the CLI's own list.   |
|---------------------------------------------------------------|----------------------------------------------------------------|
| [`INSTRUCTIONS`](_autosummary/ductus.mcp.html.md#ductus.mcp.INSTRUCTIONS) | What the server tells a model about itself.                    |

### Functions

| [`main`](_autosummary/ductus.mcp.html.md#ductus.mcp.main)()                                      | Serve on stdio.                               |
|----------------------------------------------------------------------------------------------|-----------------------------------------------|
| [`mk_mcp`](_autosummary/ductus.mcp.html.md#ductus.mcp.mk_mcp)(\*[, name, refs, instructions, ...]) | Build an MCP server exposing `refs` as tools. |

### ductus.mcp.INSTRUCTIONS *= 'Gauge which parts of a text read as machine-written, with every finding anchored to\\nthe exact characters that carry it.\\n\\nThis server never returns a percentage, a confidence, or a verdict about a person, and\\na caller should not synthesise one from what it does return. It gives a lean in\\n[-1, +1], an evidence strength, a coarse label, and the signals behind them -- each\\nwith a quote that can be checked against the text.\\n\\nIts false-positive rate on human-written text is measured: with the default detectors,\\n0.9% of human-written documents are called leans-machine, and every one\\nof those is wrong. That rate was bought with recall: the document label is now rare on\\nmachine-written text too (about 2% of machine-written essays), so a document that\\nis not flagged has not been cleared. A flagged \*sentence\* is much better evidence than\\na flagged \*document\* -- the per-sentence rate is 0.4-2%. The bias runs toward\\nformal, fluent, essayistic prose\\nrather than toward simple prose; in the measured corpus the native-speaker control was\\nthe most-accused group.\\n\\n"No findings" is a weak result, not a clean bill.\\n'*

What the server tells a model about itself. The limits are here rather than in a
README because this is the only description an MCP client ever reads.

### ductus.mcp.TOOL_REFS *: [tuple](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), ...]* *= ('ductus.tools:gauge', 'ductus.tools:baseline', 'ductus.tools:detectors', 'ductus.tools:segmenters', 'ductus.tools:tells')*

One ref per read-only verb, derived from the CLI’s own list. Never hand-written.

### ductus.mcp.main()

Serve on stdio. The `ductus-mcp` console script.

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

### ductus.mcp.mk_mcp(, name='ductus', refs=('ductus.tools:gauge', 'ductus.tools:baseline', 'ductus.tools:detectors', 'ductus.tools:segmenters', 'ductus.tools:tells'), instructions='Gauge which parts of a text read as machine-written, with every finding anchored to\\nthe exact characters that carry it.\\n\\nThis server never returns a percentage, a confidence, or a verdict about a person, and\\na caller should not synthesise one from what it does return. It gives a lean in\\n[-1, +1], an evidence strength, a coarse label, and the signals behind them -- each\\nwith a quote that can be checked against the text.\\n\\nIts false-positive rate on human-written text is measured: with the default detectors,\\n0.9% of human-written documents are called leans-machine, and every one\\nof those is wrong. That rate was bought with recall: the document label is now rare on\\nmachine-written text too (about 2% of machine-written essays), so a document that\\nis not flagged has not been cleared. A flagged \*sentence\* is much better evidence than\\na flagged \*document\* -- the per-sentence rate is 0.4-2%. The bias runs toward\\nformal, fluent, essayistic prose\\nrather than toward simple prose; in the measured corpus the native-speaker control was\\nthe most-accused group.\\n\\n"No findings" is a weak result, not a clean bill.\\n', middleware=None, auth=None)

Build an MCP server exposing `refs` as tools.

`middleware=` and `auth=` pass straight through to `py2mcp`. They are where
a deployed connector attaches metering and authentication without the core
learning that either exists.

Raises [`ImportError`](https://docs.python.org/3/builtins/exceptions.html#ImportError) with an actionable message when the extra is missing.


# _autosummary/ductus.render.html.md

# ductus.render

Turning a report into something a person reads: JSON, Markdown, or HTML.

Three renderers, all pure functions of a [`Report`](_autosummary/ductus.base.html.md#ductus.base.Report):

[`to_json()`](_autosummary/ductus.render.html.md#ductus.render.to_json)
: The full structure, for a frontend or another program.

[`to_markdown()`](_autosummary/ductus.render.html.md#ductus.render.to_markdown)
: A synopsis, then one section per flagged segment with its stats and the
  reason each signal fired.

[`to_html()`](_autosummary/ductus.render.html.md#ductus.render.to_html)
: A single self-contained file – no build step, no CDN – showing the text
  with the flagged spans shaded, the reason on hover, light and dark themes.

The HTML follows the two-channel rule for annotated text: \*\*hue encodes score
only\*\* (a perceptually-uniform ramp, lightness re-clamped per theme), while
overlap is shown structurally in a separate lane under each paragraph. Loading
both meanings into one colour is what makes overlapping highlights unreadable.

```pycon
>>> from ductus.core import gauge
>>> r = gauge("Let's delve into this robust tapestry.")
>>> "delve" in to_markdown(r)
True
>>> to_html(r).startswith("<!doctype html>")
True
>>> import json; json.loads(to_json(r))["schema_version"]
'1'
```

### Functions

| [`to_html`](_autosummary/ductus.render.html.md#ductus.render.to_html)(report, \*[, text, title, subtitle])   | A single self-contained HTML file.                               |
|-------------------------------------------------------------------------------------------------|------------------------------------------------------------------|
| [`to_json`](_autosummary/ductus.render.html.md#ductus.render.to_json)(report, \*[, indent])                  | The whole report, serialized.                                    |
| [`to_markdown`](_autosummary/ductus.render.html.md#ductus.render.to_markdown)(report, \*[, text, title])         | A readable diagnosis: synopsis first, then the flagged segments. |

### ductus.render.to_html(report, , text=None, title='Where this reads as machine-written', subtitle='')

A single self-contained HTML file. `text` defaults to the spans’ own quotes.

```pycon
>>> from ductus.core import gauge
>>> h = to_html(gauge("Let's delve in."))
>>> "<mark" in h and "prefers-color-scheme" in h
True
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### ductus.render.to_json(report, , indent=2)

The whole report, serialized.

```pycon
>>> from ductus.core import gauge
>>> d = __import__("json").loads(to_json(gauge("delve")))
>>> d["segments"][0]["signals"][0]["detector"]
'tells'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### ductus.render.to_markdown(report, , text=None, title='Reading')

A readable diagnosis: synopsis first, then the flagged segments.

```pycon
>>> from ductus.core import gauge
>>> md = to_markdown(gauge("In conclusion, this is a robust tapestry."))
>>> md.splitlines()[0].startswith("# ")
True
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)


# _autosummary/ductus.score.html.md

# ductus.score

Turning evidence into a lean – the `aggregate=` seam.

The deliberate design choice of this package lives here: \*\*there is no
percentage\*\*. Every commercial detector emits a number like “87% AI”, and that
number is how people get falsely accused, because it reads as a calibrated
probability and is nothing of the kind.

What comes out instead is three things a reader can argue with:

`lean`
: -1 (all evidence argues human) to +1 (all evidence argues machine). It is a
  ratio of the weights present, not a probability of anything.

`strength`
: 0 to 1: how much evidence there was at all. A lean of +1.0 from one weak
  signal is a different claim from +1.0 from six, and collapsing those into
  one number is exactly the lie this module refuses to tell.

`label`
: One of [`ductus.base.LABELS`](_autosummary/ductus.base.html.md#ductus.base.LABELS), and never finer than the evidence.

Replacing this with a scorer calibrated on labelled data is one keyword
argument; see `misc/docs/roadmap.md`.

```pycon
>>> from ductus.base import Signal
>>> aggregate([Signal("a", "machine", 0.5, "d"), Signal("b", "machine", 0.4, "d")])
(1.0, 0.6, 'leans-machine')
>>> aggregate([Signal("a", "machine", 0.5, "d"), Signal("b", "human", 0.5, "d")])
(0.0, 0.667, 'mixed-signals')
>>> aggregate([])
(0.0, 0.0, 'no-evidence')
```

### Module Attributes

| [`LEAN_THRESHOLD`](_autosummary/ductus.score.html.md#ductus.score.LEAN_THRESHOLD)    | Beyond this, a segment is called as leaning one way.                                                                                                                               |
|--------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`STRENGTH_FLOOR`](_autosummary/ductus.score.html.md#ductus.score.STRENGTH_FLOOR)    | Below this much total evidence, no label is claimed at all.                                                                                                                        |
| [`EVIDENCE_FULL`](_autosummary/ductus.score.html.md#ductus.score.EVIDENCE_FULL)     | The total signal weight at which `strength` saturates at 1.0.                                                                                                                      |
| [`REFERENCE_CHARS`](_autosummary/ductus.score.html.md#ductus.score.REFERENCE_CHARS)   | How much text [`density_aggregate()`](_autosummary/ductus.score.html.md#ductus.score.density_aggregate) treats as one "unit" of reading.                                                                |
| [`SEGMENT_RATE_FULL`](_autosummary/ductus.score.html.md#ductus.score.SEGMENT_RATE_FULL) | The fraction of a document's segments that must carry directional evidence before [`roll_up()`](_autosummary/ductus.score.html.md#ductus.score.roll_up) calls the document's `strength` full. |

### Functions

| [`aggregate`](_autosummary/ductus.score.html.md#ductus.score.aggregate)(signals, \*[, n_chars])         | Reduce evidence to `(lean, strength, label)`.                                                                         |
|--------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------|
| [`density_aggregate`](_autosummary/ductus.score.html.md#ductus.score.density_aggregate)(signals, \*[, n_chars]) | Like [`aggregate()`](_autosummary/ductus.score.html.md#ductus.score.aggregate), but `strength` is an evidence *rate*, not a total. |
| [`roll_up`](_autosummary/ductus.score.html.md#ductus.score.roll_up)(segments, \*[, n_chars])          | A document verdict computed from the **segment verdicts**, not the signal pool.                                       |

### ductus.score.EVIDENCE_FULL *= 1.5*

The total signal weight at which `strength` saturates at 1.0. Not fitted –
it is “about three moderate signals”, chosen to be legible rather than exact.

### ductus.score.LEAN_THRESHOLD *= 0.45*

Beyond this, a segment is called as leaning one way.

### ductus.score.REFERENCE_CHARS *= 1000*

How much text [`density_aggregate()`](_autosummary/ductus.score.html.md#ductus.score.density_aggregate) treats as one “unit” of reading. Above this
length a passage must produce proportionally more evidence to reach the same
`strength`. Selected on human-written text; see `misc/docs/phase-2-results.md`.

### ductus.score.SEGMENT_RATE_FULL *= 0.35*

The fraction of a document’s segments that must carry directional evidence before
[`roll_up()`](_autosummary/ductus.score.html.md#ductus.score.roll_up) calls the document’s `strength` full. A *rate*, not a count, which
is what makes the roll-up length-normalised by construction.

### ductus.score.STRENGTH_FLOOR *= 0.2*

Below this much total evidence, no label is claimed at all.

### ductus.score.aggregate(signals, , n_chars=None)

Reduce evidence to `(lean, strength, label)`. Length-blind, by construction.

Neutral signals count toward `strength` but never toward `lean` – they
are real evidence that the passage is unusual without being evidence about
who wrote it.

`n_chars` is accepted and **deliberately ignored**. The seam passes it so a
scorer *can* reason about how much text produced the evidence; this one does not,
which is a choice with a measured cost: on human-written text the chance of a
false accusation rises from 11% to 74% with document length alone, because two
stray signals weigh the same in 600 characters as in 3000. See
[`density_aggregate()`](_autosummary/ductus.score.html.md#ductus.score.density_aggregate) and `misc/docs/phase-2-results.md`.

```pycon
>>> from ductus.base import Signal
>>> aggregate([Signal("x", "human", 0.6, "d")])
(-1.0, 0.4, 'leans-human')
>>> aggregate([Signal("x", "neutral", 0.9, "d")])
(0.0, 0.6, 'uncertain')
```

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### ductus.score.density_aggregate(signals, , n_chars=None)

Like [`aggregate()`](_autosummary/ductus.score.html.md#ductus.score.aggregate), but `strength` is an evidence *rate*, not a total.

Two signals in 600 characters is a different claim from two in 3000, and the
length-blind scorer cannot tell them apart. This one divides the evidence by how
much text produced it, above a reference length of [`REFERENCE_CHARS`](_autosummary/ductus.score.html.md#ductus.score.REFERENCE_CHARS).

`lean` is untouched. It still reads ±1.0 off a single weak signal, and that
jaggedness is deliberate – smoothing it is how `lean` would quietly become a
quantity-integrating score, which is to say a probability. See
`misc/docs/what-calibration-means-here.md`.

The scaling only ever *divides*, never multiplies, so this scorer can only remove
accusations, never add one. Short passages behave exactly as before.

```pycon
>>> from ductus.base import Signal
>>> evidence = [Signal("x", "machine", 0.4, "d")]
>>> density_aggregate(evidence, n_chars=500)        # short: unchanged
(1.0, 0.267, 'leans-machine')
>>> density_aggregate(evidence, n_chars=4000)       # the same evidence, spread thin
(1.0, 0.067, 'no-evidence')
>>> density_aggregate(evidence) == aggregate(evidence)  # no length, no opinion
True
```

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### ductus.score.roll_up(segments, , n_chars=None)

A document verdict computed from the **segment verdicts**, not the signal pool.

Pooling every signal in a document and scoring the heap is why length hurt: with a
per-segment false-flag rate of about 3%, the chance that *something* fires grows
with the number of segments, and by thirty segments it is a coin toss. Pooling
treats accumulation as though it were corroboration.

This asks a different question – \*what fraction of this document’s segments carry
directional evidence, and which way do they point\* – and it is length-normalised
by construction rather than by a fitted constant. One flagged segment in twenty is
the same claim whether the document has twenty segments or two hundred.

The two axes keep exactly the meanings they have one level down, which is what
stops “what proportion of segments lean machine” from becoming “what percentage is
AI”:

`lean`
: unchanged: the *direction ratio* over the document’s signal weights, exactly as
  [`aggregate()`](_autosummary/ductus.score.html.md#ductus.score.aggregate) computes it. Counting segment *labels* instead was tried and
  reverted – it silently discards evidence in segments that did not reach a
  label, and that evidence is disproportionately human-leaning, which this
  package treats as first-class. It still reaches ±1.0 off a single signal.

`strength`
: how much evidence there is, judged **two ways, and believed at its weakest**:
  the *rate* of directional segments relative to [`SEGMENT_RATE_FULL`](_autosummary/ductus.score.html.md#ductus.score.SEGMENT_RATE_FULL), and
  the evidence *density* per unit text that [`density_aggregate()`](_autosummary/ductus.score.html.md#ductus.score.density_aggregate) uses. Each
  guards a failure the other misses – the rate view catches a long document with
  many segments and one stray flag, the density view catches a long document cut
  into two paragraphs where one stray flag is half of them. A document has to
  satisfy both to be called, which is the conservative direction and the one this
  package’s asymmetry asks for.

Neither axis alone, nor the pair, can be inverted into “how much of this is
machine-written”. See `misc/docs/document-verdict-decision.md`.

```pycon
>>> from ductus.base import Segment, Signal, Span
>>> def seg(label, lean):
...     found = () if label == "no-evidence" else (Signal("t", "machine", 0.5, "d"),)
...     return Segment(span=Span(0, 1, "x"), signals=found, lean=lean,
...                    strength=1.0, label=label)
>>> many = [seg("no-evidence", 0.0)] * 19 + [seg("leans-machine", 1.0)]
>>> roll_up(many)              # one flagged sentence in twenty: a rate of 5%
(1.0, 0.143, 'no-evidence')
>>> few = [seg("leans-machine", 1.0)] * 8 + [seg("no-evidence", 0.0)] * 12
>>> roll_up(few)               # eight in twenty, all pointing the same way
(1.0, 1.0, 'leans-machine')
>>> roll_up([])
(0.0, 0.0, 'no-evidence')
```

One flagged paragraph out of two is a rate of 50% – but not if those two
paragraphs are four thousand characters of text carrying one signal:

```pycon
>>> strong = Segment(span=Span(0, 1, "x"), lean=1.0, strength=1.0,
...                  signals=(Signal("t", "machine", 1.0, "d"),), label="leans-machine")
>>> pair = [strong, seg("no-evidence", 0.0)]
>>> roll_up(pair)[2]
'leans-machine'
>>> roll_up(pair, n_chars=4000)[2]
'no-evidence'
```

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]


# _autosummary/ductus.segment.html.md

# ductus.segment

Cutting a text into the units that get scored – the `segmenter=` seam.

Two segmenters ship. `paragraph` is the default because it is the unit a
reader actually perceives as “a part of the text”, and because scores over very
short spans are noise. `sentence` is there for finer localisation.

Both are pure generators over exact character offsets: a segmenter never copies
or normalises the text, so every offset it yields indexes the original.

```pycon
>>> list(spans_of("One two.\n\nThree four.", "paragraph"))[1].quote
'Three four.'
>>> [s.quote for s in spans_of("A short one. And a second.", "sentence")]
['A short one.', 'And a second.']
```

### Module Attributes

| [`SEGMENTERS`](_autosummary/ductus.segment.html.md#ductus.segment.SEGMENTERS)   | The registry the `segmenter=` seam resolves names against.   |
|---------------------------------------------------------------|--------------------------------------------------------------|

### Functions

| [`paragraph_spans`](_autosummary/ductus.segment.html.md#ductus.segment.paragraph_spans)(text)     | Yield one span per paragraph.                                      |
|----------------------------------------------------------------------------|--------------------------------------------------------------------|
| [`sentence_spans`](_autosummary/ductus.segment.html.md#ductus.segment.sentence_spans)(text)      | Yield one span per sentence, never crossing a paragraph boundary.  |
| [`spans_of`](_autosummary/ductus.segment.html.md#ductus.segment.spans_of)(text, segmenter) | Resolve `segmenter` (a name or a callable) and run it over `text`. |

### ductus.segment.SEGMENTERS *: [dict](https://docs.python.org/3/builtins/stdtypes.html#dict)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), [Callable](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[[str](https://docs.python.org/3/builtins/stdtypes.html#str)], [Iterator](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterator)[[Span](_autosummary/ductus.base.html.md#ductus.base.Span)]]]* *= {'document': <function document_spans>, 'paragraph': <function paragraph_spans>, 'sentence': <function sentence_spans>}*

The registry the `segmenter=` seam resolves names against.

### ductus.segment.paragraph_spans(text)

Yield one span per paragraph.

```pycon
>>> [ (s.start, s.end) for s in paragraph_spans("ab\n\ncd") ]
[(0, 2), (4, 6)]
```

* **Return type:**
  [`Iterator`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterator)[[`Span`](_autosummary/ductus.base.html.md#ductus.base.Span)]

### ductus.segment.sentence_spans(text)

Yield one span per sentence, never crossing a paragraph boundary.

```pycon
>>> [s.quote for s in sentence_spans("Hi there! Bye.")]
['Hi there!', 'Bye.']
```

* **Return type:**
  [`Iterator`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterator)[[`Span`](_autosummary/ductus.base.html.md#ductus.base.Span)]

### ductus.segment.spans_of(text, segmenter)

Resolve `segmenter` (a name or a callable) and run it over `text`.

```pycon
>>> len(list(spans_of("a\n\nb", "paragraph")))
2
>>> len(list(spans_of("a b", lambda t: iter([Span.of(t, 0, 1)]))))
1
```

* **Return type:**
  [`Iterator`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterator)[[`Span`](_autosummary/ductus.base.html.md#ductus.base.Span)]


# _autosummary/ductus.tells.html.md

# ductus.tells

The tells catalogue: named regular-expression patterns, tiered by confidence.

This is the cheap floor of detection – it finds *phrases* a model overuses, and
by construction it cannot find *shapes* (see [`ductus.detect`](_autosummary/ductus.detect.html.md#module-ductus.detect) for those). It
is fast, it needs nothing installed, and every hit points at the exact characters
that matched, which is what makes it useful for highlighting rather than scoring.

The catalogue is data (`ductus/data/tells.yaml`) and a keyword argument, so a
list derived from one author’s own writing can replace it without code changes.

`acquaint` consumes [`iter_tell_matches()`](_autosummary/ductus.tells.html.md#ductus.tells.iter_tell_matches) directly for the deterministic
half of its `deslop` check, and layers recipient calibration on top.

```pycon
>>> ms = list(iter_tell_matches("Great question! Let's delve into this tapestry."))
>>> sorted({m.rule_id for m in ms})
['ai-vocabulary', 'chat-leftover', 'exclamation']
>>> m = next(m for m in ms if m.rule_id == 'chat-leftover')
>>> m.tier, m.matched.lower()
('E', 'great question')
>>> list(iter_tell_matches("Sending the export on Friday. Two sites, not five."))
[]
```

### Module Attributes

| [`TIER_WEIGHT`](_autosummary/ductus.tells.html.md#ductus.tells.TIER_WEIGHT)   | How much each tier is worth as evidence, on the 0..1 Signal scale.   |
|----------------------------------------------------------------|----------------------------------------------------------------------|

### Functions

| [`iter_tell_matches`](_autosummary/ductus.tells.html.md#ductus.tells.iter_tell_matches)(text, \*[, rules, tiers, ...])   | Every catalogue hit in `text`, in document order.   |
|-----------------------------------------------------------------------------------------------------|-----------------------------------------------------|
| [`load_catalogue`](_autosummary/ductus.tells.html.md#ductus.tells.load_catalogue)([path])                             | Read the catalogue file.                            |
| [`load_rules`](_autosummary/ductus.tells.html.md#ductus.tells.load_rules)([path])                                 | The catalogue's rules, compiled.                    |
| [`metrics`](_autosummary/ductus.tells.html.md#ductus.tells.metrics)([path])                                    | The catalogue's shared numeric thresholds.          |

### Classes

| [`TellMatch`](_autosummary/ductus.tells.html.md#ductus.tells.TellMatch)(rule_id, tier, message, start, ...)   | Where a rule fired, and on what text.                                |
|--------------------------------------------------------------------------------------------------|----------------------------------------------------------------------|
| [`TellRule`](_autosummary/ductus.tells.html.md#ductus.tells.TellRule)(id, tier, message, patterns[, ...])    | One named rule: a tier, a message, and the patterns that trigger it. |

### ductus.tells.TIER_WEIGHT *= {'E': 0.5, 'S': 0.15, 'W': 0.3}*

How much each tier is worth as evidence, on the 0..1 Signal scale.
E is near-certain but still not 1.0 – a quoted model output is not a
model-written document, and nothing in this package claims certainty.

### *class* ductus.tells.TellMatch(rule_id, tier, message, start, end, matched, weight=0.0)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Where a rule fired, and on what text.

#### weight *: [float](https://docs.python.org/3/builtins/functions.html#float)* *= 0.0*

The rule’s evidential weight – its per-rule override when it has one, else its
tier’s. Carried here so a consumer never has to re-derive it from `tier`, which
would silently discard the override. Defaulted so existing constructions still
work; [`iter_tell_matches()`](_autosummary/ductus.tells.html.md#ductus.tells.iter_tell_matches) always fills it in.

### *class* ductus.tells.TellRule(id, tier, message, patterns, weight_override=None)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One named rule: a tier, a message, and the patterns that trigger it.

#### *property* weight *: [float](https://docs.python.org/3/builtins/functions.html#float)*

the per-rule override when set, else the tier’s.

```pycon
>>> TellRule("x", "E", "m", (), weight_override=0.15).weight
0.15
>>> TellRule("x", "E", "m", ()).weight
0.5
```

* **Type:**
  Evidential weight

#### weight_override *: [float](https://docs.python.org/3/builtins/functions.html#float) | [None](https://docs.python.org/3/builtins/constants.html#None)* *= None*

An optional per-rule override of the tier’s weight, read from `weight:` in
the catalogue. It exists because a rule’s **tier** and its \*\*evidential
weight\*\* answer different questions, and a rule can be right about one and
wrong about the other: `summary-closer` catches “In conclusion,” which is
reasonable style advice (`acquaint` enforces tiers) and almost worthless as
evidence about *who wrote the text* (`ductus` uses weights). Overriding the
weight changes this package only – `acquaint` reads `tier` and never
`weight`. Changing a tier is a two-package decision; see
`misc/docs/document-verdict-decision.md`.

### ductus.tells.iter_tell_matches(text, , rules=None, tiers=None, offset=0)

Every catalogue hit in `text`, in document order.

`offset` is added to every position, so a caller scanning one segment of a
larger document gets offsets into the document.

```pycon
>>> [m.rule_id for m in iter_tell_matches("In conclusion, it's important to note this.")]
['summary-closer', 'throat-clearing']
>>> [m.start for m in iter_tell_matches("delve", offset=100)]
[100]
>>> [m.rule_id for m in iter_tell_matches("delve", tiers=["E"])]
[]
```

* **Return type:**
  [`Iterator`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterator)[[`TellMatch`](_autosummary/ductus.tells.html.md#ductus.tells.TellMatch)]

### ductus.tells.load_catalogue(path=None)

Read the catalogue file. Cached; pass a path to use a different one.

```pycon
>>> sorted(load_catalogue())
['metrics', 'rules']
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### ductus.tells.load_rules(path=None)

The catalogue’s rules, compiled.

```pycon
>>> rules = load_rules()
>>> len(rules) > 10 and all(r.patterns for r in rules)
True
>>> sorted({r.tier for r in rules})
['E', 'S', 'W']
```

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`TellRule`](_autosummary/ductus.tells.html.md#ductus.tells.TellRule), [`...`](https://docs.python.org/3/builtins/constants.html#Ellipsis)]

### ductus.tells.metrics(path=None)

The catalogue’s shared numeric thresholds.

```pycon
>>> metrics()["min_sentences_for_rhythm"] > 0
True
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]


# _autosummary/ductus.tools.html.md

# ductus.tools

The verb SSOT: plain functions, JSON-ready in, JSON-ready out.

Deliberately surface-agnostic. Nothing here prints, exits, or knows what a CLI,
an MCP server or an HTTP request is – `__main__` runs these through `cw`,
`py2mcp.mk_mcp_from_refs(['ductus.tools:gauge', ...])` would expose the same
functions as MCP tools, and `qh.mk_app` would serve them over HTTP, all from
this one list. Adding a surface never means writing a second implementation.

```pycon
>>> out = gauge("Great question! Let's delve in.", format="json")
>>> import json; json.loads(out)["document"]["label"]
'leans-machine'
>>> [d["name"] for d in detectors()][:2]
['tells', 'forensic']
```

Several readers’ judgments go to the same `judgments` argument, one source each; what
enters the report is then the sentences at least `k` of them agree on, with the
per-reader counts beside it ([`ductus.consensus`](_autosummary/ductus.consensus.html.md#module-ductus.consensus)). [`baseline()`](_autosummary/ductus.tools.html.md#ductus.tools.baseline) takes the same
measure on reference texts, and `gauge(baseline=...)` sets the two side by side.

### Functions

| [`baseline`](_autosummary/ductus.tools.html.md#ductus.tools.baseline)(sources, \*[, judgments_dir, k, ...])   | The multi-reader consensus density on reference texts, to read a new text beside.   |
|---------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------|
| [`detectors`](_autosummary/ductus.tools.html.md#ductus.tools.detectors)()                                      | The available detectors and what each one looks at.                                 |
| [`gauge`](_autosummary/ductus.tools.html.md#ductus.tools.gauge)(source, \*[, format, segmenter, ...])      | Gauge how machine-written a text reads, and render the result.                      |
| [`host_mutating`](_autosummary/ductus.tools.html.md#ductus.tools.host_mutating)(fn)                                | Mark a verb that changes the machine it runs on, rather than only reading.          |
| [`host_paths`](_autosummary/ductus.tools.html.md#ductus.tools.host_paths)(\*\*roles)                            | Declare which parameters of a verb address the machine's own filesystem.            |
| [`install_skills`](_autosummary/ductus.tools.html.md#ductus.tools.install_skills)(\*[, target, write])              | Link this package's shipped skills into an agent host's skills directory.           |
| [`segmenters`](_autosummary/ductus.tools.html.md#ductus.tools.segmenters)()                                     | The available ways of cutting the text into scored units.                           |
| [`tells`](_autosummary/ductus.tools.html.md#ductus.tools.tells)(\*[, tier])                                | The tells catalogue, optionally filtered to one tier (E, W or S).                   |

### ductus.tools.baseline(sources, , judgments_dir=None, k=2, format='json', out=None)

The multi-reader consensus density on reference texts, to read a new text beside.

`sources` are files – typically the author’s own writing from before the
question arose. Each one’s readers are found by name: `<stem>.*.json` in
`judgments_dir` (default: beside the file), or `<stem>/*.json` under it. Every
text needs at least `k` readers.

The result pools the texts by words and keeps the per-text spread; pass the JSON to
`gauge(baseline=...)` so a report can say *next to this author’s own writing*
instead of giving a bare number. `format` is json or markdown. Quotes from the
reference texts are not included – only counts.

It works on files only, so over HTTP (which refuses server paths) it always
refuses; it is for the CLI, a local MCP host, and the library.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### ductus.tools.detectors()

The available detectors and what each one looks at.

```pycon
>>> {d["name"] for d in detectors()} == set(DETECTORS)
True
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]]

### ductus.tools.gauge(source, , format='markdown', segmenter='paragraph', detectors=None, judgments=None, k=2, baseline=None, out=None, title=None)

Gauge how machine-written a text reads, and render the result.

`source` is a file path, a literal string, or `-` for stdin.
`format` is one of markdown, json, html. `detectors` is a comma-separated
subset of the available detectors. `title` overrides the heading of the
markdown and html renderings (each has its own default). `judgments` is a path to a JSON file of
an agent’s own readings, folded in alongside the deterministic ones. With
`out`, the result is written there and a one-line summary is returned.

Give `judgments` several times – one file per independent reader – and what is
folded in is no longer each reader’s flags but the sentences at least `k` readers
flag; the report shows each reader’s count and that consensus per 1,000 words.
`baseline` is the output of [`baseline()`](_autosummary/ductus.tools.html.md#ductus.tools.baseline) on reference texts (a path, the
JSON text, or the parsed dict), shown beside the consensus; a previous reading’s
`meta["readers"]` works too, as a one-text baseline.

```pycon
>>> gauge("Sent it Friday. Two sites, not five.").splitlines()[0]
'# Reading'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### ductus.tools.host_mutating(fn)

Mark a verb that changes the machine it runs on, rather than only reading.

Declared at the definition site so surfaces can filter on it without anyone
writing a second list of verbs. A CLI user invoking one of these chose to; a
remote MCP caller did not necessarily, so [`ductus.mcp`](_autosummary/ductus.mcp.html.md#module-ductus.mcp) leaves them out.

```pycon
>>> host_mutating(lambda: None).mutates_host
True
>>> getattr(segmenters, "mutates_host", False)
False
```

### ductus.tools.host_paths(\*\*roles)

Declare which parameters of a verb address the machine’s own filesystem.

A sibling of [`host_mutating()`](_autosummary/ductus.tools.html.md#ductus.tools.host_mutating), and the same idea: the fact is stated once,
at the verb’s own definition, and every surface reads it from there. A surface
that never writes a second verb list also never writes a second list of which
arguments are dangerous on it.

`role` is `"read"` for a parameter the verb may read a file from, and
`"write"` for one it may write a file to. Both are ordinary, correct behaviour
at a CLI, where the caller and the filesystem belong to the same person. They are
an arbitrary file read and an arbitrary file write on a surface where they do not
– so [`ductus.http`](_autosummary/ductus.http.html.md#module-ductus.http) refuses them, driven by this declaration rather than by
knowing anything about `gauge`.

```pycon
>>> sorted(gauge.host_paths.items())
[('baseline', 'read'), ('judgments', 'read'), ('out', 'write'), ('source', 'read')]
>>> getattr(segmenters, "host_paths", {})
{}
```

### ductus.tools.install_skills(, target=None, write=False)

Link this package’s shipped skills into an agent host’s skills directory.

Defaults to `~/.claude/skills`. Dry-run unless `write` is passed.

```pycon
>>> r = install_skills()
>>> r["dry_run"], len(r["skills"]) > 0
(True, True)
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### ductus.tools.segmenters()

The available ways of cutting the text into scored units.

```pycon
>>> segmenters()
['paragraph', 'sentence', 'document']
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### ductus.tools.tells(, tier=None)

The tells catalogue, optionally filtered to one tier (E, W or S).

```pycon
>>> len(tells()) > 10
True
>>> {t["tier"] for t in tells(tier="E")}
{'E'}
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]


# about-this-build.html.md

<!-- generated by epythet -->

# About this build

This documentation was built on **2026-11-23 21:36 UTC** from commit <a href="https://github.com/addaix/ductus/commit/977f9d6d8a50171560ff7bec669475e3e94287dc"><code>977f9d6</code></a> on branch <code>main</code>, for **ductus 0.0.21** (from <code>pyproject.toml</code>).

#### WARNING
The documentation and the package may be misaligned:

- The documented version (0.0.21) is behind the latest release on PyPI (0.0.22): `pip install ductus` gives newer code than these docs describe.

## Source

|                     |                                                                                                                                                      |
|---------------------|------------------------------------------------------------------------------------------------------------------------------------------------------|
| Commit              | <a href="https://github.com/addaix/ductus/commit/977f9d6d8a50171560ff7bec669475e3e94287dc"><code>977f9d6d8a50171560ff7bec669475e3e94287dc</code></a> |
| Branch              | <code>main</code>                                                                                                                                    |
| Tags at this commit | none                                                                                                                                                 |
| Working tree        | clean                                                                                                                                                |
| Remote              | <code>https://github.com/addaix/ductus</code>                                                                                                        |

## Continuous integration

|              |                                                                                            |
|--------------|--------------------------------------------------------------------------------------------|
| Repository   | <code>addaix/ductus</code>                                                                 |
| Run          | <a href="https://github.com/addaix/ductus/actions/runs/45271214720">45271214720</a>        |
| Ref          | <code>refs/heads/main</code>                                                               |
| Event commit | <code>977f9d6d8a50171560ff7bec669475e3e94287dc</code> (in the history of the built commit) |

## Tools

|          |         |
|----------|---------|
| epythet  | 0.2.25  |
| Sphinx   | 9.1.1   |
| docutils | 0.22.4  |
| Python   | 3.12.16 |

## Configuration as resolved

|               |                                                                   |
|---------------|-------------------------------------------------------------------|
| theme         | <code>auto</code> (Sphinx theme <code>sphinxawesome_theme</code>) |
| accent        | <code>#5e4698</code>                                              |
| api_generator | <code>autosummary</code>                                          |
| ignore        | <code>tests/</code>, <code>scrap/</code>, <code>examples/</code>  |
| agent_outputs | <code>true</code>                                                 |
| aggregates    | <code>md</code>                                                   |
| ai_artifacts  | <code>true</code>                                                 |

## Package on PyPI

Latest release: <a href="https://pypi.org/project/ductus/0.0.22/">0.0.22</a>, newer than the documented version (0.0.21).

## Reproduce

```bash
git clone https://github.com/addaix/ductus && cd ductus
git checkout 977f9d6d8a50171560ff7bec669475e3e94287dc
pip install "epythet==0.2.25"
epythet quickstart . --ignore tests/ scrap/ examples/
```

The same data, for machines: <a href="build_info.json"><code>build_info.json</code></a> (schema version 1).


# ai-agents.html.md

<!-- generated by epythet -->

# For AI agents

`ductus` ships artifacts for coding agents alongside its code. This page lists
them, says where each lives in the repository, and points at the
machine-readable copies of this documentation.

## Skills

Skills are folders holding a `SKILL.md` (the [Agent Skills](https://agentskills.io) format): a description that tells an agent when to use it and a body with the procedure. Install one into your agent with `gh skill` (any host: `--agent claude-code`, `copilot`, `cursor`, `codex`, `gemini`), or use the copy bundled in the wheel.

### `ductus`

Gauge which parts of a text read as machine-written, and say why, with the evidence anchored to exact characters. Use whenever someone asks whether text was AI-generated, wants to know which passages “sound like AI”, asks you to check a draft before sending it, or says “is this AI”, “did a model write this”, “which parts sound generated”, “AI detection”, “AI-written”, “run a detector on this”, “how AI does this read”. Also use before the deslop skill, to find what needs rewriting, and after it, to check the rewrite. Read this skill before reaching for any AI-detector service; it owns what can and cannot honestly be claimed from a text.

```bash
gh skill install addaix/ductus ductus --agent claude-code
```

Source: [`ductus/data/skills/ductus`](https://github.com/addaix/ductus/tree/HEAD/ductus/data/skills/ductus) (bundled with the pip package).

### `ductus-gauge`

Do a full reading of a text for machine-written prose — run the deterministic detectors, add your own judgment pass for the shapes a regular expression cannot see, and produce a markdown or HTML report with evidence anchored to exact characters. Use when asked which parts of a text read as AI-generated, to analyse or diagnose a document’s authorship signals, to check a draft before sending, or to verify a rewrite. Triggers on “which parts sound like AI”, “analyse this text”, “gauge this”, “is this AI-written”, “run the detectors”, “AI reading of this document”, “check this draft”. Read the `ductus` skill first for what may and may not be claimed.

```bash
gh skill install addaix/ductus ductus-gauge --agent claude-code
```

Source: [`ductus/data/skills/ductus-gauge`](https://github.com/addaix/ductus/tree/HEAD/ductus/data/skills/ductus-gauge) (bundled with the pip package).

The bundled skills are also on disk after `pip install ductus`, under the package’s `data/skills/` directory; link them into an agent without network access with `skill link-skills <that directory>`.

## Subagents

Subagents are Markdown files with a frontmatter (`name`, `description`, `tools`) and a system prompt as the body. Copy one into your project’s `.claude/agents/` (or your agent host’s equivalent) to delegate the task it describes.

### `ductus-reader`

Reads a text for machine-written prose in its own context and returns a finished diagnosis — the deterministic scan plus its own judgment pass, written up with the evidence and the limits. Use when asked which parts of a document read as AI-generated, or to check a draft, and you want the reading done without the document’s full text landing in the main thread. Read-only with respect to the source; it writes its report beside the source file.

Source: [`ductus/data/agents/ductus-reader.md`](https://github.com/addaix/ductus/tree/HEAD/ductus/data/agents/ductus-reader.md); tools: `Bash, Read, Write, Glob, Grep`.

## Instruction files

Files agents read before working in this repository.

- [`CLAUDE.md`](https://github.com/addaix/ductus/tree/HEAD/CLAUDE.md): read by Claude Code

## Machine-readable documentation

This site publishes the same documentation in forms that fit an agent’s context window:

- [`llms.txt`](https://addaix.github.io/ductus/llms.txt): an index of every page with a one-line description ([llms.txt](https://llmstxt.org) format)
- [`ductus.md`](https://addaix.github.io/ductus/ductus.md): the whole documentation as one Markdown file
- `<page>.html.md`: a rendered Markdown twin of every page, advertised from each page’s `<head>` with `<link rel="alternate" type="text/markdown">`
- [`objects.inv`](https://addaix.github.io/ductus/objects.inv): the Sphinx inventory: a symbol-to-URL index (`sphobjinv convert plain objects.inv -`)


# api.html.md

# API reference

| [`ductus`](_autosummary/ductus.html.md#module-ductus)   | ductus -- gauge which parts of a text read as machine-written, and why.   |
|-------------------------------------------------------------------------|---------------------------------------------------------------------------|


