diff --git a/.github/ISSUE_TEMPLATE/ledger_problem.yml b/.github/ISSUE_TEMPLATE/ledger_problem.yml
index 8a69beb25..c23c6b674 100644
--- a/.github/ISSUE_TEMPLATE/ledger_problem.yml
+++ b/.github/ISSUE_TEMPLATE/ledger_problem.yml
@@ -16,7 +16,7 @@ body:
attributes:
label: Protocolith version
description: Output of `protocolith --version`.
- placeholder: protocolith 0.6.0
+ placeholder: protocolith 0.7.0
validations:
required: true
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 266204353..fdddd8180 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,9 +1,19 @@
# Changelog
-## Unreleased
+## 0.7.0 - 2026-11-18
### Added
+- **Selective disclosure.** `protocolith disclose --policy FILE` (also `core.build_disclosure`, MCP `protocolith_disclose`) writes a
+ publishable view of a ledger in which each entry is shown in full, as a summary, or hidden; the hash chain stays intact, so a
+ reader sees how many entries exist and that none was dropped. A policy chooses the level by protocol (exact or prefix), by
+ `seq` or by a range, first match wins, default hidden. `protocolith verify-disclosure FILE [--anchors DIR] [--reveal ENTRY]`
+ (`core.verify_disclosure`, `core.verify_reveal`, MCP `protocolith_verify_disclosure`) checks structure, chain, full entries,
+ anchors, and that a revealed entry is exactly the one committed to. `protocolith atlas --policy FILE` builds the matching atlas
+ (hidden records shown as `HIDDEN` rows). New codes `BAD_POLICY`, `BAD_DISCLOSURE`, `DISCLOSURE_HASH`, `DISCLOSURE_CHAIN`;
+ `protocolith schema policy`; conformance vectors `spec/vectors/disclosures.json`; core specification section 15; MCP now
+ has 15 tools. See `docs/guides/selective-disclosure.md` and `examples/selective_disclosure/`.
+
- **Example `examples/phantom_mean_reversion/`.** A published simulation study as a retrospective record: frozen protocol, two
anchors, a card, and `reproduce.py`, which re-runs the study (numpy only, about five seconds) and compares the output with the
committed results (IDENTICAL, or EQUAL within 1e-9 where floating-point rounding differs). The README states plainly what a retrospective record proves and what it does not.
diff --git a/CITATION.cff b/CITATION.cff
index 013fc072f..166d1cf42 100644
--- a/CITATION.cff
+++ b/CITATION.cff
@@ -8,7 +8,7 @@ authors:
orcid: "https://orcid.org/0009-0000-3773-5789"
license: Apache-2.0
doi: "10.5281/zenodo.24291830"
-version: "0.6.0"
+version: "0.7.0"
date-released: "2026-11-16"
repository-code: "https://github.com/Protocolith/protocolith"
abstract: >-
diff --git a/README.md b/README.md
index 08616d1f4..620fe3132 100644
--- a/README.md
+++ b/README.md
@@ -53,7 +53,7 @@
-->
-
+
## Why
@@ -72,6 +72,7 @@ It does not run experiments, fetch data or judge whether a protocol is a good on
| 2. **Record** the outcome against that protocol | `protocolith record record.json` | Status, outcome, source hashes, claim boundary |
| 3. **Verify** the hash-chained history | `protocolith verify-ledger` | Nothing; it reports rule violations (R1 to R11) |
| 4. **Issue** a card from a verified record | `protocolith issue SEQ` | A JSON and SVG card, plus an `issue` entry |
+| 6. **Disclose** a view of the ledger | `protocolith disclose --policy FILE` | A public file: each entry in full, as a summary, or hidden |
| 5. **Anchor** the head outside your disk | `protocolith anchor` | An anchor statement; optional git tag, Wayback or RFC 3161 time-stamp |
Everything lives in one append-only file, `.protocolith/ledger.jsonl`, one canonical JSON line per entry.
@@ -166,11 +167,30 @@ from the local ledger or a directory of evidence cards: summary tiles, a status
filters, a sortable paged table and a detail drawer with permalinks. Languages other than English come only from
files you supply. See [the atlas guide](docs/guides/atlas.md).
+
+
+
+
```bash
protocolith atlas --out atlas.html # the local ledger
protocolith atlas --cards docs/evidence_cards --out site/
```
+## Publish what you choose: full, summary or hidden
+
+A researcher may keep thousands of entries and publish a few. `protocolith disclose --policy policy.json` writes a view of the
+ledger in which each entry is shown **in full**, **as a summary** or **hidden** (only its place and hash). The chain stays intact,
+so a reader sees how many entries exist and that none was dropped; the owner can reveal a hidden entry later and anyone checks it.
+`protocolith atlas --policy policy.json` builds the matching browsable page. See the
+[guide](docs/guides/selective-disclosure.md) and the [example](examples/selective_disclosure/).
+
+
+
+
+
+
+
+
## Anchor the head, and catch a cut-off ledger
A ledger is a file its owner writes, so plain verification cannot notice that the last entries were removed. An anchor puts the
@@ -195,12 +215,12 @@ README says what that does and does not prove.
## MCP client configuration
-`protocolith mcp` is a stdio server with thirteen tools (`protocolith_summary`, `protocolith_log`, `protocolith_show`,
-`protocolith_schema`, `protocolith_capture`, `protocolith_atlas`, `protocolith_claim_check`, `protocolith_anchor`, `protocolith_freeze`, `protocolith_record`,
+`protocolith mcp` is a stdio server with fifteen tools (`protocolith_summary`, `protocolith_log`, `protocolith_show`,
+`protocolith_schema`, `protocolith_capture`, `protocolith_atlas`, `protocolith_claim_check`, `protocolith_anchor`, `protocolith_disclose`, `protocolith_verify_disclosure`, `protocolith_freeze`, `protocolith_record`,
`protocolith_deviation`, `protocolith_verify`, `protocolith_issue`) read-only resources (`protocolith://summary`, `protocolith://ledger`,
`protocolith://schema/`) and the prompt `research-agent-protocol`, so an agent can discover the formats and the rules
itself; `protocolith_claim_check` tells it what it may and may not say about a result. It uses the network only when
-`protocolith_anchor` is given a time-stamp URL, and writes only inside the store, apart from the atlas page that `protocolith_atlas` writes inside the working directory. Add it to an MCP client:
+`protocolith_anchor` is given a time-stamp URL, and writes only inside the store, apart from the atlas page and the disclosure file that `protocolith_atlas` and `protocolith_disclose` write inside the working directory. Add it to an MCP client:
```json
{
@@ -226,7 +246,7 @@ uv sync
uv run protocolith --version # or: source .venv/bin/activate
```
-`pip install protocolith` is available from the 0.6.0 release (planned); it is not published with the ledger commands yet.
+`pip install protocolith` installs the current release from PyPI (since 0.6.0).
The package has no required dependencies.
## Platforms
diff --git a/docs/CLI.md b/docs/CLI.md
index 1e4c10ab1..26a732a00 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -239,6 +239,24 @@ Anchor the ledger head: a local anchor file, and optionally a time-stamp, an arc
- `--sign` — Sign the git tag (needs --git-tag and a configured key).
- `--write-head FILE` — Write the anchor statement to FILE to publish or archive it.
+## `protocolith disclose`
+
+Write a publishable view of the ledger: each entry shown in full, as a summary, or hidden, as a policy says.
+
+- `--store STORE` — Store directory (env PROTOCOLITH_STORE, default .protocolith).
+- `--json` — Print the result as canonical JSON.
+- `--policy FILE` — Visibility policy (`protocolith schema policy`). (required)
+- `--out FILE` — Output file (default disclosure.jsonl). (default: `disclosure.jsonl`)
+
+## `protocolith verify-disclosure`
+
+Check the structure and hash chain of a disclosure and the hash of every full entry. --anchors DIR compares the anchor statements there with the entry hashes; --reveal FILE checks that a ledger entry you were given is exactly the one the disclosure committed to.
+
+- `file`
+- `--anchors DIR` — Directory of anchor statements (.json) to check.
+- `--reveal ENTRY` — JSON file holding one revealed ledger entry.
+- `--json` — Print the result as canonical JSON.
+
## `protocolith claim-check`
State what the ledger supports about a record (what may and may not be said).
@@ -303,7 +321,7 @@ Print a JSON fragment for the outcome object of a record: Python, platform, mach
Print a JSON Schema (draft 2020-12) generated from the rules.
-- `name` — Which schema (default all). (one of: `freeze`, `record`, `deviation`, `issue`, `entry`, `all`)
+- `name` — Which schema (default all). (one of: `freeze`, `record`, `deviation`, `issue`, `entry`, `policy`, `all`)
## `protocolith head`
@@ -331,6 +349,7 @@ Build a self-contained offline HTML atlas of experiments from a ledger and/or ev
- `--title TEXT` — Page title. (default: `Protocolith atlas`)
- `--i18n DIR` — Directory of .json translation files; adds a language switcher.
- `--default-lang CODE` — Initial language (default en). (default: `en`)
+- `--policy FILE` — Visibility policy: show each record in full, as a summary, or hidden.
- `--max-rows N` — Embed at most N records (the newest); counts stay complete.
## `protocolith mcp`
diff --git a/docs/assets/protocolith/anchor-demo.gif b/docs/assets/protocolith/anchor-demo.gif
index ceab1a692..7e7b585df 100644
Binary files a/docs/assets/protocolith/anchor-demo.gif and b/docs/assets/protocolith/anchor-demo.gif differ
diff --git a/docs/assets/protocolith/architecture.svg b/docs/assets/protocolith/architecture.svg
index 1575167e1..70594c34a 100644
--- a/docs/assets/protocolith/architecture.svg
+++ b/docs/assets/protocolith/architecture.svg
@@ -10,7 +10,7 @@
CLI plithhumans, CI, scriptsPython APIimport protocolith.core
-MCP server13 tools, resources, prompts
+MCP server15 tools, resources, promptsprotocolith.core (standard library only, 100% line and branch coverage)
diff --git a/docs/assets/protocolith/atlas-full.png b/docs/assets/protocolith/atlas-full.png
new file mode 100644
index 000000000..fdf14c0f7
Binary files /dev/null and b/docs/assets/protocolith/atlas-full.png differ
diff --git a/docs/assets/protocolith/atlas-hidden.png b/docs/assets/protocolith/atlas-hidden.png
new file mode 100644
index 000000000..7b198c258
Binary files /dev/null and b/docs/assets/protocolith/atlas-hidden.png differ
diff --git a/docs/assets/protocolith/atlas-overview.png b/docs/assets/protocolith/atlas-overview.png
new file mode 100644
index 000000000..861601c2c
Binary files /dev/null and b/docs/assets/protocolith/atlas-overview.png differ
diff --git a/docs/assets/protocolith/atlas-summary.png b/docs/assets/protocolith/atlas-summary.png
new file mode 100644
index 000000000..87081e7b8
Binary files /dev/null and b/docs/assets/protocolith/atlas-summary.png differ
diff --git a/docs/assets/protocolith/atlas-tour.gif b/docs/assets/protocolith/atlas-tour.gif
new file mode 100644
index 000000000..f118a8e7c
Binary files /dev/null and b/docs/assets/protocolith/atlas-tour.gif differ
diff --git a/docs/assets/protocolith/demo.gif b/docs/assets/protocolith/demo.gif
index d762695e8..7061c28fc 100644
Binary files a/docs/assets/protocolith/demo.gif and b/docs/assets/protocolith/demo.gif differ
diff --git a/docs/assets/protocolith/disclosure-demo.gif b/docs/assets/protocolith/disclosure-demo.gif
new file mode 100644
index 000000000..2098b1ac1
Binary files /dev/null and b/docs/assets/protocolith/disclosure-demo.gif differ
diff --git a/docs/assets/protocolith/disclosure-levels.svg b/docs/assets/protocolith/disclosure-levels.svg
new file mode 100644
index 000000000..29392fe98
--- /dev/null
+++ b/docs/assets/protocolith/disclosure-levels.svg
@@ -0,0 +1,32 @@
+
diff --git a/docs/assets/protocolith/protocolith-story.gif b/docs/assets/protocolith/protocolith-story.gif
new file mode 100644
index 000000000..74575313c
Binary files /dev/null and b/docs/assets/protocolith/protocolith-story.gif differ
diff --git a/docs/development/release-process.md b/docs/development/release-process.md
index f0a8fef35..aaadd7e2b 100644
--- a/docs/development/release-process.md
+++ b/docs/development/release-process.md
@@ -31,6 +31,12 @@ the shape of a release and says which parts are done by hand.
## 0.6.0
-The 0.6.0 release is planned to ship the core ledger commands, the specification and the conformance vectors,
-and to make `pip install protocolith` available. It is not released. The packaging, publication and documentation
-steps above are still to do.
+The 0.6.0 release (2026-11-16) shipped the core ledger commands, the specification and the conformance vectors, and made
+`pip install protocolith` available from PyPI, with a Zenodo DOI.
+
+## 0.7.0
+
+The 0.7.0 release adds anchoring of the ledger head, `claim-check`, the MCP research prompt and selective disclosure. Before
+tagging: bump the version in `pyproject.toml`, `CITATION.cff`, `specs/repo_version.yaml` and `core/mcp.py`; rebuild the examples
+whose anchors record the version (`examples/phantom_mean_reversion/build_ledger.py`, `scripts/build_disclosure_demo.py`); then
+tag and publish through the protected workflow.
diff --git a/docs/examples/README.md b/docs/examples/README.md
index 22101eb4b..d2b977e41 100644
--- a/docs/examples/README.md
+++ b/docs/examples/README.md
@@ -5,4 +5,5 @@
| The quickstart: freeze, record, verify, issue, log, head | [`examples/quickstart/`](../../examples/quickstart/), walked through in [your first record](../getting-started/first-record.md) |
| A new protocol version, a deviation, and records that are blocked or rejected | [Statuses and versions](statuses-and-versions.md) |
| A published simulation study kept as an anchored, reproducible retrospective record | [`examples/phantom_mean_reversion/`](../../examples/phantom_mean_reversion/) |
+| A private notebook of 31 entries and the view you would publish (full, summary, hidden) | [`examples/selective_disclosure/`](../../examples/selective_disclosure/) |
| Older example material (rerun reports, evidence-card examples, case studies) | [archive](../archive/README.md) |
diff --git a/docs/getting-started/install.md b/docs/getting-started/install.md
index 961d5daa2..d4f728273 100644
--- a/docs/getting-started/install.md
+++ b/docs/getting-started/install.md
@@ -8,8 +8,8 @@ code and no network access. It runs headless on macOS, Linux and Windows.
| Route | State |
| --- | --- |
| From a source checkout with `uv sync` | Works today. |
-| `pip install protocolith` | Available from 0.6.0. |
-| conda-forge | Planned, no date. |
+| `pip install protocolith` | Available (PyPI, since 0.6.0). |
+| conda-forge | Submitted to conda-forge, waiting for review. |
## From source, per operating system
diff --git a/docs/guides/anchoring-the-head.md b/docs/guides/anchoring-the-head.md
index b680ca56c..c2d84616e 100644
--- a/docs/guides/anchoring-the-head.md
+++ b/docs/guides/anchoring-the-head.md
@@ -52,7 +52,7 @@ otherwise it reports `HEAD_MISMATCH` and exits with 1 (for example when the tail
replaced). The value must be a decimal `SEQ`, a colon and 64 lowercase hex characters, else the command exits with 2.
A ledger that is longer than the anchor still passes: the check proves the anchored prefix is unchanged.
-The option is part of the 0.6.0 development work. It cannot show that the anchor itself is trustworthy.
+The option exists since 0.6.0. It cannot show that the anchor itself is trustworthy.
## When to anchor
diff --git a/docs/guides/mcp.md b/docs/guides/mcp.md
index 0a486f608..65f25046f 100644
--- a/docs/guides/mcp.md
+++ b/docs/guides/mcp.md
@@ -1,8 +1,8 @@
# MCP integration
`protocolith mcp` runs a Model Context Protocol server on stdio, so an MCP client (an agent or an editor) can
-freeze, record, verify, issue and query without a shell. It uses newline-delimited JSON-RPC 2.0, needs no third-party package, and writes only inside the store (the atlas tool
-writes one page inside the working directory). It uses the network only when `protocolith_anchor` is called with a `tsa` URL.
+freeze, record, verify, issue and query without a shell. It uses newline-delimited JSON-RPC 2.0, needs no third-party package, and writes only inside the store (the atlas and disclose tools
+write one file each inside the working directory). It uses the network only when `protocolith_anchor` is called with a `tsa` URL.
This page is the short version. The step-by-step guide with a session transcript is
[Use Protocolith from an AI agent](ai-agent-mcp.md); the tools and resources are listed in the
@@ -27,9 +27,9 @@ is not on the client's `PATH`, give the full path to the executable in your envi
## What the server offers
-Thirteen tools (`protocolith_summary`, `protocolith_log`, `protocolith_show`, `protocolith_schema`,
+Fifteen tools (`protocolith_summary`, `protocolith_log`, `protocolith_show`, `protocolith_schema`,
`protocolith_capture`, `protocolith_atlas`, `protocolith_freeze`, `protocolith_record`, `protocolith_deviation`, `protocolith_verify`,
-`protocolith_claim_check`, `protocolith_anchor`, `protocolith_issue`), read-only resources (`protocolith://summary`,
+`protocolith_claim_check`, `protocolith_anchor`, `protocolith_disclose`, `protocolith_verify_disclosure`, `protocolith_issue`), read-only resources (`protocolith://summary`,
`protocolith://ledger`, `protocolith://schema/`) and the prompt `research-agent-protocol`. Arguments not listed in a tool's schema are rejected. `isError` is true when an
operation was rejected or the ledger does not verify; the JSON then carries `codes`, `error` (with a `hint` where
there is one) and `violations`, exactly as with `--json`.
diff --git a/docs/guides/selective-disclosure.md b/docs/guides/selective-disclosure.md
new file mode 100644
index 000000000..e400f0c6a
--- /dev/null
+++ b/docs/guides/selective-disclosure.md
@@ -0,0 +1,113 @@
+# Publish what you choose: selective disclosure
+
+You may run ten thousand experiments and want to publish a handful. Protocolith keeps **all** of them in one private ledger, and
+lets you publish a view in which each entry is shown **in full**, **as a summary**, or **hidden**. The hash chain stays intact, so a
+reader sees how many entries exist and that none was dropped, but nothing of what you hid.
+
+
+
+## Why this matters
+
+A registry is believable when the unflattering runs are in it. Most research tools show only what the author selected, so a
+reader cannot tell a result chosen from ten attempts from one chosen from ten thousand. With a disclosure, the published file
+states the total (`entries`), and once its head is anchored (see [anchor your results](anchor-your-results.md)) nobody, including
+you, can later remove an entry unnoticed.
+
+## What to publish where
+
+| You want to | Do this | Cost |
+| --- | --- | --- |
+| keep everything private | keep `.protocolith/` on your disk or in a private repository | nothing |
+| prove the history was not edited | `protocolith anchor` and publish the head (one 32-byte hash covers every earlier entry) | one anchor per session, not per experiment |
+| show that you tried N things | publish a disclosure in which the exploratory protocols are `hidden` | one file |
+| publish a result with its context | make that protocol `full`, the related exploratory ones `summary` or `hidden` | one file |
+| let a reviewer check a hidden run later | send them the entry; they run `verify-disclosure --reveal` | one file |
+| cite a result for years | release the disclosure and the anchor on GitHub, Zenodo and Software Heritage | a few uploads a year |
+
+Do not upload ten thousand records to a public archive. Anchor the head, publish one disclosure, and archive only what a claim
+rests on.
+
+## 1. Write a policy
+
+```json
+{
+ "v": 1,
+ "default": "hidden",
+ "rules": [
+ {"protocol_id": "PAPER_CLAIM", "level": "full"},
+ {"protocol_id": "STUDY_ROBUSTNESS", "level": "summary"},
+ {"protocol_id": "SWEEP_*", "level": "hidden"}
+ ],
+ "summary_fields": ["status", "outcome", "claim_boundary"]
+}
+```
+
+- A rule has a `level` and **one** selector: `protocol_id` (an exact id, or a prefix ending in `*`), `seq` (a number or a list) or
+ `from_seq` with `to_seq`.
+- **The first matching rule wins.** An entry no rule matches gets `default`, which is `hidden` when you do not write it:
+ nothing is public unless you say so.
+- A freeze, a record, a deviation and an issue entry belong to the protocol they refer to, so one rule covers a whole protocol.
+- `summary_fields` chooses what a summary shows from a record: `status`, `reproduction_level`, `claim_boundary`, `outcome`,
+ `run_id`, `public_claim_text`; a freeze summary shows `question` only if you list it. `protocolith schema policy` prints the schema.
+
+## 2. Publish the view
+
+```bash
+protocolith disclose --policy policy.json --out public/disclosure.jsonl
+protocolith anchor --write-head public/anchor.txt # publish the head somewhere you do not control
+protocolith atlas --policy policy.json --out public/atlas.html
+```
+
+`disclose` refuses a ledger that does not verify. `atlas --policy` builds the same self-contained page as
+[the atlas guide](atlas.md), with hidden entries shown as hatched `HIDDEN` rows (their place and hash only) and a banner that
+states how many entries are shown in full, as summaries and hidden.
+
+
+
+
+
+## 3. Let anyone verify it
+
+```bash
+protocolith verify-disclosure public/disclosure.jsonl
+protocolith verify-disclosure public/disclosure.jsonl --anchors anchors/ # also compare published anchors
+```
+
+This checks that the file is canonical, that every line links to the one before, that each full entry hashes to its stated
+hash, and that the manifest (count, head) matches. A dropped, reordered or replaced entry is `BAD_DISCLOSURE` or
+`DISCLOSURE_CHAIN`; an edited full entry is `DISCLOSURE_HASH`; against an anchor, a rewritten history is `ANCHOR_MISMATCH` and a
+cut-off one `ANCHOR_AHEAD`.
+
+## 4. Reveal an entry later
+
+Give the reviewer the one ledger entry (`protocolith show SEQ --json`, or the line from your private ledger). They run
+
+```bash
+protocolith verify-disclosure public/disclosure.jsonl --reveal entry.json
+# reveal seq=16 level=hidden: MATCHES
+```
+
+It matches only when the entry is exactly the one the disclosure committed to; for a summary, the published fields must also
+agree with the revealed entry. You can reveal one entry without revealing the others.
+
+## From an AI agent (MCP)
+
+An agent uses `protocolith_disclose` (`policy` as a JSON object, optional `out`) and `protocolith_verify_disclosure` (`file`,
+optional `anchors` and `reveal`); `protocolith_atlas` accepts the same `policy`. A sensible instruction for an agent that
+works in a private ledger: *"record every run, including failures; before sharing anything, call `protocolith_disclose` with a
+policy that publishes only what I name, then `protocolith_anchor`, and tell me the head."*
+
+## Honest limits
+
+- A hidden hash does not reveal the content, but whoever can **guess the whole entry** can confirm the guess. Entries that hold a
+ source hash or a precise time are not guessable in practice; a short, predictable body is.
+- A **summary is your statement**. It is checked only when the entry is revealed, so publish a summary only of what you can
+ reveal.
+- Hiding an entry does not hide that it exists, its position, or (for hidden entries) anything else a reader can infer from the
+ count. The time of a hidden entry is not published; the time of a summary is.
+- A disclosure proves the published entries are consistent with the chain. Whether a result is true is not something a ledger
+ decides.
+- The ledger is not encrypted. Keep the private ledger private.
+
+Format and rules: [core specification, section 15](../spec/CORE_SPEC.md). A runnable example is in
+[`examples/selective_disclosure/`](../../examples/selective_disclosure/).
diff --git a/docs/project/roadmap.md b/docs/project/roadmap.md
index aa2054b26..2cddd6f8f 100644
--- a/docs/project/roadmap.md
+++ b/docs/project/roadmap.md
@@ -20,8 +20,9 @@ pre-rename project and keep their original status wording.
| Item | Target | Notes |
| --- | --- | --- |
-| Release 0.6.0 with `pip install protocolith` | 0.6.0 | Needs the owner's approval to tag and publish. |
-| conda-forge package | no date | After the PyPI release. |
+| Release 0.6.0 with `pip install protocolith` | 0.6.0 | Released 2026-11-16. |
+| Release 0.7.0: anchoring, claim-check, selective disclosure | 0.7.0 | In preparation. |
+| conda-forge package | no date | Submitted; waiting for review. |
| A second implementation that passes the vectors | before 1.0.0 | None exists. |
| An independent external rerun of a recorded run | before 1.0.0 | None has been reported. |
diff --git a/docs/reference/error-codes.md b/docs/reference/error-codes.md
index b11cfcdfb..5c982a0e8 100644
--- a/docs/reference/error-codes.md
+++ b/docs/reference/error-codes.md
@@ -38,6 +38,9 @@ object is printed on stdout (`ok`, `codes`, `error`, `violations`); `error` also
| `BAD_ENTRY` | structure | wrong keys or types; bodies are closed, unknown keys are rejected |
| `ANCHOR_MISMATCH` | anchor | `--anchors`: the entry at an anchored `seq` has another hash: the ledger was rewritten (exit 1) |
| `ANCHOR_AHEAD` | anchor | `--anchors`: the ledger has fewer entries than an anchor says: it was truncated (exit 1) |
+| `BAD_DISCLOSURE` | disclosure | `verify-disclosure`: not a disclosure of this version, or a line, a count or the head is wrong (exit 1) |
+| `DISCLOSURE_HASH` | disclosure | `verify-disclosure`: a full entry does not hash to its stated hash (exit 1) |
+| `DISCLOSURE_CHAIN` | disclosure | `verify-disclosure`: a `prev` is not the hash of the line before: an entry was removed, reordered or replaced (exit 1) |
| `ANCHOR_INVALID` | anchor | `--anchors`: an anchor file, or a stored time-stamp response it lists, is malformed, edited or missing (exit 1) |
After an unparseable line the next `prev` is not checked, to avoid a cascade of reports. In a violation, `seq`
@@ -69,6 +72,7 @@ is the zero-based line index.
| `CARD_EXISTS` | 2 | the card file exists with different content |
| `CARD_CONFLICT` | 2 | `card` keys contradict values derived from the record |
| `CARD_INVALID` | 2 | the card failed validation for another reason |
+| `BAD_POLICY` | 2 | `disclose`, `atlas --policy`: the visibility policy is not valid (`protocolith schema policy`) |
| `ANCHOR_EXISTS` | 2 | `anchor`: an anchor file or statement file of this head exists with other content |
| `EMPTY_LEDGER` | 2 | `anchor`: the ledger has no entries |
| `BAD_URL` | 2 | `anchor`: `--tsa` or `--wayback` is not an http or https URL |
diff --git a/docs/reference/mcp.md b/docs/reference/mcp.md
index 6320b8b43..725e8544f 100644
--- a/docs/reference/mcp.md
+++ b/docs/reference/mcp.md
@@ -21,12 +21,14 @@ canonical JSON. `isError` is true when the operation was rejected or the ledger
| `protocolith_show` | `seq` (integer, at least 0) | `protocolith show` |
| `protocolith_schema` | optional `name` (`freeze`, `record`, `deviation`, `issue`, `entry`, `all`) | `protocolith schema` |
| `protocolith_capture` | optional `files` (paths inside the working directory), `env` | `protocolith capture` |
-| `protocolith_atlas` | optional `out`, `title`, `cards` (directories), `i18n`, `default_lang`, `max_rows` | `protocolith atlas`; returns the path written |
+| `protocolith_atlas` | optional `out`, `title`, `cards` (directories), `i18n`, `default_lang`, `max_rows`, `policy` | `protocolith atlas`; returns the path written |
| `protocolith_freeze` | `protocol` (object), optional `supersedes` | `protocolith freeze` |
| `protocolith_record` | `body` (object) | `protocolith record` |
| `protocolith_deviation` | `body` (object) | `protocolith deviation` |
| `protocolith_verify` | optional `expect_head` (`SEQ:HASH`), `anchors` (boolean) | `protocolith verify-ledger [--expect-head] [--anchors]` |
| `protocolith_claim_check` | `seq` or `protocol` (exactly one) | `protocolith claim-check`: what may and may not be said about a record. Call it before stating any result. |
+| `protocolith_disclose` | `policy` (object); optional `out` | `protocolith disclose`: writes a publishable view of the ledger (each entry full, summary or hidden) inside the working directory |
+| `protocolith_verify_disclosure` | `file`; optional `anchors` (directory), `reveal` (a ledger entry) | `protocolith verify-disclosure`; `isError` when anything does not verify |
| `protocolith_anchor` | optional `tsa` (URL) | `protocolith anchor [--tsa URL]`: the local anchor, plus an RFC 3161 time-stamp when `tsa` is given |
| `protocolith_issue` | `seq` (integer, at least 0) | `protocolith issue` |
diff --git a/docs/spec/CORE_SPEC.md b/docs/spec/CORE_SPEC.md
index 2f67f52ba..b75ec8e42 100644
--- a/docs/spec/CORE_SPEC.md
+++ b/docs/spec/CORE_SPEC.md
@@ -1,6 +1,6 @@
# Protocolith Core Specification
-Status: draft 0.1 (target: Protocolith 0.6.0). This document defines the core. The reference
+Status: draft 0.1 (implemented in Protocolith 0.6.0; sections 13 to 15 in 0.7.0). This document defines the core. The reference
implementation is the `protocolith.core` package; any other implementation must pass the
conformance vectors in `spec/vectors/` to claim compatibility.
@@ -116,6 +116,8 @@ All three expose the same operations with the same semantics.
| atlas | `protocolith atlas [--store DIR] [--cards DIR ...] [--out FILE_OR_DIR]` | `core.build_atlas(...)` | `protocolith_atlas` |
| anchor | `protocolith anchor [--tsa URL] [--wayback URL] [--git-tag [--sign]] [--write-head FILE]` | `core.anchor_head(store, ...)` | `protocolith_anchor` (local anchor and optional `tsa` only) |
| claim check | `protocolith claim-check --seq N \| --protocol ID` | `core.claim_check(store, seq=N)` or `protocol=ID` | `protocolith_claim_check` |
+| disclose | `protocolith disclose --policy FILE [--out FILE]` | `core.build_disclosure(store, policy)` | `protocolith_disclose` |
+| verify disclosure | `protocolith verify-disclosure FILE [--anchors DIR] [--reveal ENTRY]` | `core.verify_disclosure(data, anchors_dir)`, `core.verify_reveal(data, entry)` | `protocolith_verify_disclosure` |
| init | `protocolith init` | `core.init(store)` | |
CLI exit codes: `0` ok; `1` the stored ledger does not verify (codes on stderr and, with `--json`, on stdout);
@@ -125,7 +127,7 @@ CLI exit codes: `0` ok; `1` the stored ledger does not verify (codes on stderr a
The MCP server speaks stdio JSON-RPC with `initialize`, `tools/list`, `tools/call`, `resources/list`, `resources/read`,
`prompts/list` and `prompts/get`, and uses no third-party package. `initialize` advertises `tools`, `resources` and `prompts`.
-It makes a network request only when `protocolith_anchor` is called with `tsa`, and never writes outside the store, except the
+It makes a network request only when `protocolith_anchor` is called with `tsa`, and never writes outside the store, except the disclosure file that `protocolith_disclose` writes and the
one atlas page of `protocolith_atlas` inside the working directory. The prompt `research-agent-protocol` (no arguments) holds
fixed instructions for an AI agent: freeze before any run, record every run including failures and blocked sources, call
`claim_check` before stating a result and use its `may_say` wording, then verify and anchor and report the `anchor_id`.
@@ -248,6 +250,10 @@ Verification: `BAD_SEQ`, `BAD_PREV`, `BAD_HASH`, `NOT_CANONICAL`, `TS_REGRESSION
Canonicalization and input: `BAD_JSON` (including a byte-order mark), `BAD_UTF8`, `BAD_TYPE`, `FLOAT_NOT_ALLOWED`, `NON_FINITE`,
`INT_RANGE`, `DUPLICATE_KEY`, `LONE_SURROGATE`.
+Disclosure (section 15): `BAD_DISCLOSURE` (the file is not a disclosure, or a line is damaged), `DISCLOSURE_HASH` (a full entry does
+not hash to its hash) and `DISCLOSURE_CHAIN` (a `prev` is not the hash of the line before) are verification codes of
+`verify-disclosure` (exit 1); `BAD_POLICY` (an invalid policy, exit 2) belongs to `disclose` and `atlas --policy`.
+
Anchors (section 13): `ANCHOR_MISMATCH` (an anchored entry is not the one in the ledger: the ledger was rewritten),
`ANCHOR_AHEAD` (the ledger is shorter than an anchor: truncated), `ANCHOR_INVALID` (an anchor file or a stored time-stamp
response is malformed, edited or missing) are verification codes of `verify-ledger --anchors` (exit 1). `ANCHOR_EXISTS`
@@ -350,3 +356,48 @@ A protocol with no record yields `supported` false, `seq` null, `may_say` saying
`["any result", "passed", "failed", "reproduced"]`. The output is deterministic and contains no text beyond these templates, the
recorded values and the claim boundary text as written by the recorder. `claim_check` limits what an agent can honestly
report; it does not check that the analysis itself was sound.
+
+## 15. Disclosure
+
+A **disclosure** is a publishable view of a ledger in which each entry is shown in full, as a summary, or hidden. It does not
+change the ledger or rules R1 to R11. It is a canonical JSON Lines file (PCJ-1, one object per line, newline-terminated).
+
+**Line 0, the manifest:** `{"counts": {"full": n, "hidden": n, "summary": n}, "entries": N, "head_hash": H, "head_seq": N-1,
+"kind": "protocolith-disclosure", "v": 1}`. For an empty ledger `head_hash` and `head_seq` are `null`.
+
+**Lines 1 to N, one per ledger entry in order, by level:**
+
+| level | keys |
+| --- | --- |
+| `full` | `entry` (the whole ledger entry, unchanged), `level`, `seq` |
+| `summary` | `hash`, `level`, `prev`, `seq`, `summary` (an object), `ts`, `type` |
+| `hidden` | `hash`, `level`, `prev`, `seq` |
+
+`hash` and `prev` are the entry's own hash and the hash of the entry before it (64 zeros for `seq` 0).
+
+**Verification** (`verify-disclosure`): every line is canonical JSON; line 0 is a manifest of this version whose counts, entry
+count and head equal what the lines show; `seq` runs from 0 without a gap; `prev` of each line equals the `hash` of the
+line before (`DISCLOSURE_CHAIN`); a `full` entry has exactly the keys of a ledger entry and hashes to its `hash`
+(`DISCLOSURE_HASH`); a `summary` line has a known `type`, a valid time-stamp and an object. Any other structural problem is
+`BAD_DISCLOSURE`. With anchors, each anchor statement is compared with the `hash` at its `head_seq` (`ANCHOR_MISMATCH`,
+`ANCHOR_AHEAD`), exactly as for a ledger. Exit code `0` ok, `1` not ok.
+
+**Reveal** (`--reveal ENTRY`): the owner hands over one complete ledger entry. It matches when its own hash is consistent,
+its `hash` and `prev` equal the disclosed ones, and, for a `summary` line, every summary field that can be derived from the
+entry equals the published value and `type` and `ts` agree. A mismatch is reported with a reason; exit code `1`.
+
+**Policy** (`protocolith schema policy`): `{"v": 1, "default": LEVEL, "rules": [...], "summary_fields": [...]}`. A rule has a
+`level` and exactly one selector: `protocol_id` (an exact id, or a prefix ending in `*`), `seq` (an integer or a list) or
+`from_seq` with `to_seq` (inclusive). The first matching rule wins; `default` (itself `hidden` when absent) applies when none
+matches. A freeze, a record, a deviation and an issue entry belong to the protocol they refer to. A summary carries
+`protocol_id` and, by type: `version` (freeze), the listed fields of `claim_boundary`, `outcome`, `public_claim_text`,
+`reproduction_level`, `run_id`, `status` (record), `record_seq` (issue); `question` of a freeze only when listed. The default
+`summary_fields` are `status`, `reproduction_level` and `claim_boundary`. Building a disclosure from a ledger that does not
+verify is refused.
+
+**What it guarantees and what it does not.** The chain and the head cover hidden entries, so a reader sees how many entries
+exist and that none was dropped or replaced once the head is anchored. A hidden hash does not reveal the content, but a
+reader who can guess an entire entry can confirm the guess. A summary is the owner's statement; it is checked only when the entry
+is revealed. Hiding an entry does not hide that it exists.
+
+Conformance vectors for this section are in `spec/vectors/disclosures.json`.
diff --git a/docs_site/index.md b/docs_site/index.md
index 378ebf8e8..0ec6e651c 100644
--- a/docs_site/index.md
+++ b/docs_site/index.md
@@ -45,8 +45,8 @@ true. Anchor the head with `protocolith anchor` ([anchor your results](guides-an
## Status
-The ledger commands are on the development branch toward 0.6.0 and installable from source today; the specification
-is a draft (0.1) with one implementation. See the [roadmap](project-roadmap.md) and the [FAQ](FAQ.md).
+The ledger commands ship in the PyPI package (`pip install protocolith`); the specification is a draft (0.1) with one
+implementation. See the [roadmap](project-roadmap.md) and the [FAQ](FAQ.md).
The earlier evidence-card material (card validators, runners, registry views) is kept under
[Archive and examples](archive.md). The project was published as ClaimBound Evidence until 0.5.0; see
diff --git a/examples/atlas/i18n/de.json b/examples/atlas/i18n/de.json
index 97737e15e..54c36a749 100644
--- a/examples/atlas/i18n/de.json
+++ b/examples/atlas/i18n/de.json
@@ -6,6 +6,7 @@
"noscript": "Dieser Atlas braucht JavaScript, um die Eintraege anzuzeigen.",
"load_error": "Die eingebetteten Atlas-Daten konnten nicht gelesen werden.",
"integrity_ledger_ok": "Ledger geprueft: {count} Eintraege, Kopf seq {seq}, Hash {hash}",
+ "integrity_disclosure": "Veroeffentlichte Ansicht: {full} Eintraege vollstaendig, {summary} als Zusammenfassung, {hidden} verborgen. Ein verborgener Eintrag bleibt Teil der Hash-Kette, es wurde also nichts weggelassen.",
"integrity_ledger_failed": "LEDGER HAT DIE PRUEFUNG NICHT BESTANDEN ({count} Probleme). Verlassen Sie sich nicht auf die Daten unten.",
"problem_item": "{code} in Zeile {seq}: {message}",
"integrity_cards": "{count} Evidenzkarten aus Dateien gelesen. Sie werden unveraendert gezeigt und nicht gegen ein Ledger geprueft.",
diff --git a/examples/phantom_mean_reversion/README.md b/examples/phantom_mean_reversion/README.md
index 23b21225a..51e32b1cd 100644
--- a/examples/phantom_mean_reversion/README.md
+++ b/examples/phantom_mean_reversion/README.md
@@ -37,6 +37,23 @@ difference instead of hiding it, and `DIFFERENT` only if a number moves by more
Rebuild everything with `python3 build_ledger.py` (it refuses to overwrite an existing `evidence/`).
+## Time-stamps (RFC 3161)
+
+The final head (`seq 2`) carries two independent time-stamps, from DigiCert and from FreeTSA, both made on 2026-11-18 and stored next to
+the anchor statement. Protocolith does not verify their signatures; `openssl` does:
+
+```bash
+cd evidence/.protocolith/anchors
+S=2-19c345a87e50.statement
+# DigiCert (its root is in the system trust store)
+openssl ts -verify -in d99a52e0cee5e0cf6e6fbe5c10e332c844399bfcf4e0ecf6b05d398cb8536141.tsr -data $S -CAfile /etc/ssl/cert.pem
+# FreeTSA (download its CA first: https://freetsa.org/files/cacert.pem and tsa.crt)
+openssl ts -verify -in d99a52e0cee5e0cf6e6fbe5c10e332c844399bfcf4e0ecf6b05d398cb8536141.4d1b6aec322a.tsr -data $S -CAfile cacert.pem -untrusted tsa.crt
+```
+
+Both print `Verification: OK`. A time-stamp shows that the statement (and so the whole ledger up to `seq 2`) existed at that time; it does not
+show that the analysis was planned earlier.
+
## What this record does and does not prove
- It proves the files with these hashes existed when the anchors say, that the chain was not edited afterwards (once the
diff --git a/examples/phantom_mean_reversion/build_ledger.py b/examples/phantom_mean_reversion/build_ledger.py
index f8f10e706..ce97c9850 100644
--- a/examples/phantom_mean_reversion/build_ledger.py
+++ b/examples/phantom_mean_reversion/build_ledger.py
@@ -4,6 +4,9 @@
Run it from anywhere; it needs `protocolith` (0.7.0 or later, for `anchor`) importable and numpy installed:
python3 build_ledger.py # writes ./evidence/ (refuses to overwrite an existing one)
+ python3 build_ledger.py --tsa=http://timestamp.digicert.com --tsa=https://freetsa.org/tsr # also RFC 3161 time-stamps
+
+A time-stamp request sends only the hash of the anchor statement to the authority you name.
The order is the point. The protocol is frozen and anchored BEFORE the results are re-computed, and the record is added
afterwards. This is a retrospective record: the study itself was run and written up before this protocol was frozen, so the
@@ -46,6 +49,7 @@ def plith(*args: str) -> str:
def main() -> int:
+ tsas = [a.split("=", 1)[1] for a in sys.argv[1:] if a.startswith("--tsa=")]
if EVIDENCE.exists():
raise SystemExit(f"{EVIDENCE} exists; remove it first (a ledger is append-only, this script never edits one)")
EVIDENCE.mkdir()
@@ -104,6 +108,8 @@ def main() -> int:
plith("issue", "1")
plith("verify-ledger")
plith("anchor", "--write-head", "anchor-after-record.txt")
+ for url in tsas:
+ plith("anchor", "--tsa", url)
plith("verify-ledger", "--anchors")
plith("claim-check", "--seq", "1")
return 0
diff --git a/examples/phantom_mean_reversion/evidence/.protocolith/anchors/0-83d76b3c7213.json b/examples/phantom_mean_reversion/evidence/.protocolith/anchors/0-83d76b3c7213.json
new file mode 100644
index 000000000..b2cac1489
--- /dev/null
+++ b/examples/phantom_mean_reversion/evidence/.protocolith/anchors/0-83d76b3c7213.json
@@ -0,0 +1 @@
+{"anchor_id":"32a3e80f0b9f9f22b26c2b8c24ebe0962adecd8f925b2c917da3c64e399567ed","methods":[],"statement":{"created_at":"2026-11-18T16:07:04Z","entries":1,"head_hash":"83d76b3c721344520637006632e2da18024cec2d14302c0abafbd953299538b2","head_seq":0,"kind":"protocolith-anchor","protocolith_version":"0.7.0","v":1}}
\ No newline at end of file
diff --git a/examples/phantom_mean_reversion/evidence/.protocolith/anchors/0-83d76b3c7213.statement b/examples/phantom_mean_reversion/evidence/.protocolith/anchors/0-83d76b3c7213.statement
new file mode 100644
index 000000000..4a3b71b6d
--- /dev/null
+++ b/examples/phantom_mean_reversion/evidence/.protocolith/anchors/0-83d76b3c7213.statement
@@ -0,0 +1 @@
+{"created_at":"2026-11-18T16:07:04Z","entries":1,"head_hash":"83d76b3c721344520637006632e2da18024cec2d14302c0abafbd953299538b2","head_seq":0,"kind":"protocolith-anchor","protocolith_version":"0.7.0","v":1}
\ No newline at end of file
diff --git a/examples/phantom_mean_reversion/evidence/.protocolith/anchors/0-8fad6983ab64.json b/examples/phantom_mean_reversion/evidence/.protocolith/anchors/0-8fad6983ab64.json
deleted file mode 100644
index 79af532ba..000000000
--- a/examples/phantom_mean_reversion/evidence/.protocolith/anchors/0-8fad6983ab64.json
+++ /dev/null
@@ -1 +0,0 @@
-{"anchor_id":"42ef02b50d129cc90d6f151f7a37c3bc481d83b2a71f55d51892f1fceb251bf3","methods":[],"statement":{"created_at":"2026-11-18T14:23:08Z","entries":1,"head_hash":"8fad6983ab64bf55d47a46fc29a107805a3474010d6450a1f3927dbf44c62d2d","head_seq":0,"kind":"protocolith-anchor","protocolith_version":"0.6.0","v":1}}
\ No newline at end of file
diff --git a/examples/phantom_mean_reversion/evidence/.protocolith/anchors/0-8fad6983ab64.statement b/examples/phantom_mean_reversion/evidence/.protocolith/anchors/0-8fad6983ab64.statement
deleted file mode 100644
index 0576c3e00..000000000
--- a/examples/phantom_mean_reversion/evidence/.protocolith/anchors/0-8fad6983ab64.statement
+++ /dev/null
@@ -1 +0,0 @@
-{"created_at":"2026-11-18T14:23:08Z","entries":1,"head_hash":"8fad6983ab64bf55d47a46fc29a107805a3474010d6450a1f3927dbf44c62d2d","head_seq":0,"kind":"protocolith-anchor","protocolith_version":"0.6.0","v":1}
\ No newline at end of file
diff --git a/examples/phantom_mean_reversion/evidence/.protocolith/anchors/2-19c345a87e50.json b/examples/phantom_mean_reversion/evidence/.protocolith/anchors/2-19c345a87e50.json
new file mode 100644
index 000000000..39d9cb389
--- /dev/null
+++ b/examples/phantom_mean_reversion/evidence/.protocolith/anchors/2-19c345a87e50.json
@@ -0,0 +1 @@
+{"anchor_id":"d99a52e0cee5e0cf6e6fbe5c10e332c844399bfcf4e0ecf6b05d398cb8536141","methods":[{"file":"d99a52e0cee5e0cf6e6fbe5c10e332c844399bfcf4e0ecf6b05d398cb8536141.tsr","gen_time":"2026-11-18T16:07:09Z","tsr_sha256":"d2f2faccbee7b651ce85c3c58ce90eae0395f5693980499fac920efdcc46b0d8","type":"rfc3161","url":"http://timestamp.digicert.com"},{"file":"d99a52e0cee5e0cf6e6fbe5c10e332c844399bfcf4e0ecf6b05d398cb8536141.4d1b6aec322a.tsr","gen_time":"2026-11-18T16:07:10Z","tsr_sha256":"4d1b6aec322aa6ac171bd5cc48105035514739eebcd3b704bce1b321a9c50df8","type":"rfc3161","url":"https://freetsa.org/tsr"}],"statement":{"created_at":"2026-11-18T16:07:08Z","entries":3,"head_hash":"19c345a87e50a58512eab07d2daebe712df057c28cbceee9903b978c025cad20","head_seq":2,"kind":"protocolith-anchor","protocolith_version":"0.7.0","v":1}}
\ No newline at end of file
diff --git a/examples/phantom_mean_reversion/evidence/.protocolith/anchors/2-19c345a87e50.statement b/examples/phantom_mean_reversion/evidence/.protocolith/anchors/2-19c345a87e50.statement
new file mode 100644
index 000000000..bb27d2d62
--- /dev/null
+++ b/examples/phantom_mean_reversion/evidence/.protocolith/anchors/2-19c345a87e50.statement
@@ -0,0 +1 @@
+{"created_at":"2026-11-18T16:07:08Z","entries":3,"head_hash":"19c345a87e50a58512eab07d2daebe712df057c28cbceee9903b978c025cad20","head_seq":2,"kind":"protocolith-anchor","protocolith_version":"0.7.0","v":1}
\ No newline at end of file
diff --git a/examples/phantom_mean_reversion/evidence/.protocolith/anchors/2-78fb32129555.json b/examples/phantom_mean_reversion/evidence/.protocolith/anchors/2-78fb32129555.json
deleted file mode 100644
index ce3d458b6..000000000
--- a/examples/phantom_mean_reversion/evidence/.protocolith/anchors/2-78fb32129555.json
+++ /dev/null
@@ -1 +0,0 @@
-{"anchor_id":"04e5bb703e4700c3a288d1162c301cdc14b438392395f3394bcd6e32cc01dd4d","methods":[],"statement":{"created_at":"2026-11-18T14:23:12Z","entries":3,"head_hash":"78fb3212955515c1692069c4f197d72fda0c5edec9a2556a28912b314d05da4f","head_seq":2,"kind":"protocolith-anchor","protocolith_version":"0.6.0","v":1}}
\ No newline at end of file
diff --git a/examples/phantom_mean_reversion/evidence/.protocolith/anchors/2-78fb32129555.statement b/examples/phantom_mean_reversion/evidence/.protocolith/anchors/2-78fb32129555.statement
deleted file mode 100644
index 3ef4fdb72..000000000
--- a/examples/phantom_mean_reversion/evidence/.protocolith/anchors/2-78fb32129555.statement
+++ /dev/null
@@ -1 +0,0 @@
-{"created_at":"2026-11-18T14:23:12Z","entries":3,"head_hash":"78fb3212955515c1692069c4f197d72fda0c5edec9a2556a28912b314d05da4f","head_seq":2,"kind":"protocolith-anchor","protocolith_version":"0.6.0","v":1}
\ No newline at end of file
diff --git a/examples/phantom_mean_reversion/evidence/.protocolith/anchors/d99a52e0cee5e0cf6e6fbe5c10e332c844399bfcf4e0ecf6b05d398cb8536141.4d1b6aec322a.tsr b/examples/phantom_mean_reversion/evidence/.protocolith/anchors/d99a52e0cee5e0cf6e6fbe5c10e332c844399bfcf4e0ecf6b05d398cb8536141.4d1b6aec322a.tsr
new file mode 100644
index 000000000..6270bb670
Binary files /dev/null and b/examples/phantom_mean_reversion/evidence/.protocolith/anchors/d99a52e0cee5e0cf6e6fbe5c10e332c844399bfcf4e0ecf6b05d398cb8536141.4d1b6aec322a.tsr differ
diff --git a/examples/phantom_mean_reversion/evidence/.protocolith/anchors/d99a52e0cee5e0cf6e6fbe5c10e332c844399bfcf4e0ecf6b05d398cb8536141.tsr b/examples/phantom_mean_reversion/evidence/.protocolith/anchors/d99a52e0cee5e0cf6e6fbe5c10e332c844399bfcf4e0ecf6b05d398cb8536141.tsr
new file mode 100644
index 000000000..9add63bc8
Binary files /dev/null and b/examples/phantom_mean_reversion/evidence/.protocolith/anchors/d99a52e0cee5e0cf6e6fbe5c10e332c844399bfcf4e0ecf6b05d398cb8536141.tsr differ
diff --git a/examples/phantom_mean_reversion/evidence/.protocolith/cards/PLITH-PHANTOM_MR_D001-2026-11-18-000001.json b/examples/phantom_mean_reversion/evidence/.protocolith/cards/PLITH-PHANTOM_MR_D001-2026-11-18-000001.json
index 40803b90f..bce4edbd9 100644
--- a/examples/phantom_mean_reversion/evidence/.protocolith/cards/PLITH-PHANTOM_MR_D001-2026-11-18-000001.json
+++ b/examples/phantom_mean_reversion/evidence/.protocolith/cards/PLITH-PHANTOM_MR_D001-2026-11-18-000001.json
@@ -1 +1 @@
-{"access_date":"2026-11-18","ai_assistance":"An AI assistant copied the files and wrote the protocol, the reproduce script and this record; the operator reviewed them.","baseline_control_summary":"Control: the tradable P&L series of the same paths, which holds the previous hedge.","claim_boundary":"Simulated independent random walks only, seed 20261015, 400 paths of 5000 hourly bars. Says nothing about real markets or about any investment result.","claim_type":"source_audit","created_at":"2026-11-18T14:23:12Z","domain":"quantitative research","evidence_id":"PLITH-PHANTOM_MR_D001-2026-11-18-000001","execution_mode":"AUTOMATED_AI_ASSISTED","git_commit":"none","known_limitations":["Retrospective record: the study predates this frozen protocol.","Single operator.","Simulation only."],"last_verified_date":"2026-11-18","ledger_record_seq":1,"manual_review":"The operator compared the table in the preprint with results.json.","official_source_name":"Monte-Neo paper sources (phantom-mean-reversion)","official_source_url":"https://github.com/NeoZorK/Monte-Neo","operator":"Rostyslav Shcherbyna","protocol_id":"PHANTOM_MR_D001","protocol_sha256":"10d8d37361cda4c4248be947912e0c3faca75b8c765ecc8089e6e01dfad43323","protocol_version":"1","public_claim_captured_at":"2026-11-18","public_claim_locator":"paper/phantom-mean-reversion, Table 1","public_claim_source_sha256":"89dd6efe060a3058f071ca0a24abec28311bd3b49c8153da971b9a50723ebad3","public_claim_source_url":"https://github.com/NeoZorK/Monte-Neo","public_claim_text":"Rolling-hedge spread books look profitable on independent random walks while the tradable P&L is near zero.","public_claim_verbatim_quote":"Rolling-hedge spread books look profitable on independent random walks while the tradable P&L is near zero.","raw_payload_committed":false,"raw_payload_manifest":"No raw payload; the simulation generates its own random walks.","record_type":"evidence_result","registry_sequence":2,"reproduction_level":"not independently reproduced","result_status":"PASSED_UNDER_PROTOCOL","runner_command":"python3 reproduce.py","sanitized_report_path":"examples/phantom_mean_reversion/results.json","sanitized_report_sha256":"89dd6efe060a3058f071ca0a24abec28311bd3b49c8153da971b9a50723ebad3","source_rights_note":"Own simulation code and output, MIT licence in the source repository; no third-party data.","sources":[{"id":"results.json","sha256":"89dd6efe060a3058f071ca0a24abec28311bd3b49c8153da971b9a50723ebad3"},{"id":"results_other.json","sha256":"7ba9fa0ce0e8dcc2f7020a7310418101fe01e2d51f6b6f49ade2576060f9099e"},{"id":"code/phantom_mr_sim.py","sha256":"1019a9064ab0b1be4dfb4197566f633bd2a36f4db94bc742a7e0f6c43439458d"},{"id":"code/other_hedges.py","sha256":"13ffabc1e2bd9fd1112c5b9bc953adcdaa53cf7a87c6edfa29398ff6c63218be"},{"id":"code/mechanism_check.py","sha256":"1f35d5b311be9cf3bc3b331c519359d8ef8f36ddca6e27c25084cbfef7f34159"},{"id":"code/make_figures.py","sha256":"05dde7f2cab8d9219125f06518ae51679016d9442228a646f03fd64b607aa3df"}],"verification_count":2,"verification_level":"SINGLE_OPERATOR"}
\ No newline at end of file
+{"access_date":"2026-11-18","ai_assistance":"An AI assistant copied the files and wrote the protocol, the reproduce script and this record; the operator reviewed them.","baseline_control_summary":"Control: the tradable P&L series of the same paths, which holds the previous hedge.","claim_boundary":"Simulated independent random walks only, seed 20261015, 400 paths of 5000 hourly bars. Says nothing about real markets or about any investment result.","claim_type":"source_audit","created_at":"2026-11-18T16:07:08Z","domain":"quantitative research","evidence_id":"PLITH-PHANTOM_MR_D001-2026-11-18-000001","execution_mode":"AUTOMATED_AI_ASSISTED","git_commit":"none","known_limitations":["Retrospective record: the study predates this frozen protocol.","Single operator.","Simulation only."],"last_verified_date":"2026-11-18","ledger_record_seq":1,"manual_review":"The operator compared the table in the preprint with results.json.","official_source_name":"Monte-Neo paper sources (phantom-mean-reversion)","official_source_url":"https://github.com/NeoZorK/Monte-Neo","operator":"Rostyslav Shcherbyna","protocol_id":"PHANTOM_MR_D001","protocol_sha256":"10d8d37361cda4c4248be947912e0c3faca75b8c765ecc8089e6e01dfad43323","protocol_version":"1","public_claim_captured_at":"2026-11-18","public_claim_locator":"paper/phantom-mean-reversion, Table 1","public_claim_source_sha256":"89dd6efe060a3058f071ca0a24abec28311bd3b49c8153da971b9a50723ebad3","public_claim_source_url":"https://github.com/NeoZorK/Monte-Neo","public_claim_text":"Rolling-hedge spread books look profitable on independent random walks while the tradable P&L is near zero.","public_claim_verbatim_quote":"Rolling-hedge spread books look profitable on independent random walks while the tradable P&L is near zero.","raw_payload_committed":false,"raw_payload_manifest":"No raw payload; the simulation generates its own random walks.","record_type":"evidence_result","registry_sequence":2,"reproduction_level":"not independently reproduced","result_status":"PASSED_UNDER_PROTOCOL","runner_command":"python3 reproduce.py","sanitized_report_path":"examples/phantom_mean_reversion/results.json","sanitized_report_sha256":"89dd6efe060a3058f071ca0a24abec28311bd3b49c8153da971b9a50723ebad3","source_rights_note":"Own simulation code and output, MIT licence in the source repository; no third-party data.","sources":[{"id":"results.json","sha256":"89dd6efe060a3058f071ca0a24abec28311bd3b49c8153da971b9a50723ebad3"},{"id":"results_other.json","sha256":"7ba9fa0ce0e8dcc2f7020a7310418101fe01e2d51f6b6f49ade2576060f9099e"},{"id":"code/phantom_mr_sim.py","sha256":"1019a9064ab0b1be4dfb4197566f633bd2a36f4db94bc742a7e0f6c43439458d"},{"id":"code/other_hedges.py","sha256":"13ffabc1e2bd9fd1112c5b9bc953adcdaa53cf7a87c6edfa29398ff6c63218be"},{"id":"code/mechanism_check.py","sha256":"1f35d5b311be9cf3bc3b331c519359d8ef8f36ddca6e27c25084cbfef7f34159"},{"id":"code/make_figures.py","sha256":"05dde7f2cab8d9219125f06518ae51679016d9442228a646f03fd64b607aa3df"}],"verification_count":2,"verification_level":"SINGLE_OPERATOR"}
\ No newline at end of file
diff --git a/examples/phantom_mean_reversion/evidence/.protocolith/ledger.jsonl b/examples/phantom_mean_reversion/evidence/.protocolith/ledger.jsonl
index a34304fa5..f190b6780 100644
--- a/examples/phantom_mean_reversion/evidence/.protocolith/ledger.jsonl
+++ b/examples/phantom_mean_reversion/evidence/.protocolith/ledger.jsonl
@@ -1,3 +1,3 @@
-{"body":{"protocol":{"gate":"For every window in 30, 60, 100, 250 and 500 bars: median booked Sharpe above 3, absolute median tradable Sharpe below 0.5, and phantom share of booked P&L between 0.9 and 1.1","protocol_id":"PHANTOM_MR_D001","question":"Do rolling-hedge spread books show a high Sharpe ratio on independent random walks while the P&L of a position that holds the previous hedge stays near zero?","source":"results.json","version":"1"},"protocol_id":"PHANTOM_MR_D001","protocol_sha256":"10d8d37361cda4c4248be947912e0c3faca75b8c765ecc8089e6e01dfad43323","supersedes":null,"version":"1"},"hash":"8fad6983ab64bf55d47a46fc29a107805a3474010d6450a1f3927dbf44c62d2d","prev":"0000000000000000000000000000000000000000000000000000000000000000","seq":0,"ts":"2026-11-18T14:23:08Z","type":"freeze","v":1}
-{"body":{"card":{"access_date":"2026-11-18","ai_assistance":"An AI assistant copied the files and wrote the protocol, the reproduce script and this record; the operator reviewed them.","baseline_control_summary":"Control: the tradable P&L series of the same paths, which holds the previous hedge.","claim_type":"source_audit","domain":"quantitative research","execution_mode":"AUTOMATED_AI_ASSISTED","git_commit":"none","known_limitations":["Retrospective record: the study predates this frozen protocol.","Single operator.","Simulation only."],"manual_review":"The operator compared the table in the preprint with results.json.","official_source_name":"Monte-Neo paper sources (phantom-mean-reversion)","official_source_url":"https://github.com/NeoZorK/Monte-Neo","operator":"Rostyslav Shcherbyna","public_claim_captured_at":"2026-11-18","public_claim_locator":"paper/phantom-mean-reversion, Table 1","public_claim_source_sha256":"89dd6efe060a3058f071ca0a24abec28311bd3b49c8153da971b9a50723ebad3","public_claim_source_url":"https://github.com/NeoZorK/Monte-Neo","public_claim_text":"Rolling-hedge spread books look profitable on independent random walks while the tradable P&L is near zero.","public_claim_verbatim_quote":"Rolling-hedge spread books look profitable on independent random walks while the tradable P&L is near zero.","raw_payload_manifest":"No raw payload; the simulation generates its own random walks.","runner_command":"python3 reproduce.py","sanitized_report_path":"examples/phantom_mean_reversion/results.json","sanitized_report_sha256":"89dd6efe060a3058f071ca0a24abec28311bd3b49c8153da971b9a50723ebad3","source_rights_note":"Own simulation code and output, MIT licence in the source repository; no third-party data.","verification_count":2,"verification_level":"SINGLE_OPERATOR"},"claim_boundary":"Simulated independent random walks only, seed 20261015, 400 paths of 5000 hourly bars. Says nothing about real markets or about any investment result.","deviations":[],"outcome":{"max_abs_tradable_sharpe_median":"0.13","min_booked_sharpe_median":"4.39","phantom_share_max":"1.017","phantom_share_min":"0.98","windows":"30,60,100,250,500","windows_passing_gate":"5","windows_total":"5"},"protocol_sha256":"10d8d37361cda4c4248be947912e0c3faca75b8c765ecc8089e6e01dfad43323","reproduction_level":"not independently reproduced","run_id":"run-1","sources":[{"id":"results.json","sha256":"89dd6efe060a3058f071ca0a24abec28311bd3b49c8153da971b9a50723ebad3"},{"id":"results_other.json","sha256":"7ba9fa0ce0e8dcc2f7020a7310418101fe01e2d51f6b6f49ade2576060f9099e"},{"id":"code/phantom_mr_sim.py","sha256":"1019a9064ab0b1be4dfb4197566f633bd2a36f4db94bc742a7e0f6c43439458d"},{"id":"code/other_hedges.py","sha256":"13ffabc1e2bd9fd1112c5b9bc953adcdaa53cf7a87c6edfa29398ff6c63218be"},{"id":"code/mechanism_check.py","sha256":"1f35d5b311be9cf3bc3b331c519359d8ef8f36ddca6e27c25084cbfef7f34159"},{"id":"code/make_figures.py","sha256":"05dde7f2cab8d9219125f06518ae51679016d9442228a646f03fd64b607aa3df"}],"status":"PASSED_UNDER_PROTOCOL"},"hash":"0b3d8648ae84aad9650126309131e8bc3057f93347c619a01b688139e1e50be7","prev":"8fad6983ab64bf55d47a46fc29a107805a3474010d6450a1f3927dbf44c62d2d","seq":1,"ts":"2026-11-18T14:23:12Z","type":"record","v":1}
-{"body":{"card_sha256":"1525e5a32ebd839c8b871b66e5e21a8821eb94060e2d749ed5adf8c6b95c1d2f","format":"evidence-card-json-svg","record_seq":1},"hash":"78fb3212955515c1692069c4f197d72fda0c5edec9a2556a28912b314d05da4f","prev":"0b3d8648ae84aad9650126309131e8bc3057f93347c619a01b688139e1e50be7","seq":2,"ts":"2026-11-18T14:23:12Z","type":"issue","v":1}
+{"body":{"protocol":{"gate":"For every window in 30, 60, 100, 250 and 500 bars: median booked Sharpe above 3, absolute median tradable Sharpe below 0.5, and phantom share of booked P&L between 0.9 and 1.1","protocol_id":"PHANTOM_MR_D001","question":"Do rolling-hedge spread books show a high Sharpe ratio on independent random walks while the P&L of a position that holds the previous hedge stays near zero?","source":"results.json","version":"1"},"protocol_id":"PHANTOM_MR_D001","protocol_sha256":"10d8d37361cda4c4248be947912e0c3faca75b8c765ecc8089e6e01dfad43323","supersedes":null,"version":"1"},"hash":"83d76b3c721344520637006632e2da18024cec2d14302c0abafbd953299538b2","prev":"0000000000000000000000000000000000000000000000000000000000000000","seq":0,"ts":"2026-11-18T16:07:04Z","type":"freeze","v":1}
+{"body":{"card":{"access_date":"2026-11-18","ai_assistance":"An AI assistant copied the files and wrote the protocol, the reproduce script and this record; the operator reviewed them.","baseline_control_summary":"Control: the tradable P&L series of the same paths, which holds the previous hedge.","claim_type":"source_audit","domain":"quantitative research","execution_mode":"AUTOMATED_AI_ASSISTED","git_commit":"none","known_limitations":["Retrospective record: the study predates this frozen protocol.","Single operator.","Simulation only."],"manual_review":"The operator compared the table in the preprint with results.json.","official_source_name":"Monte-Neo paper sources (phantom-mean-reversion)","official_source_url":"https://github.com/NeoZorK/Monte-Neo","operator":"Rostyslav Shcherbyna","public_claim_captured_at":"2026-11-18","public_claim_locator":"paper/phantom-mean-reversion, Table 1","public_claim_source_sha256":"89dd6efe060a3058f071ca0a24abec28311bd3b49c8153da971b9a50723ebad3","public_claim_source_url":"https://github.com/NeoZorK/Monte-Neo","public_claim_text":"Rolling-hedge spread books look profitable on independent random walks while the tradable P&L is near zero.","public_claim_verbatim_quote":"Rolling-hedge spread books look profitable on independent random walks while the tradable P&L is near zero.","raw_payload_manifest":"No raw payload; the simulation generates its own random walks.","runner_command":"python3 reproduce.py","sanitized_report_path":"examples/phantom_mean_reversion/results.json","sanitized_report_sha256":"89dd6efe060a3058f071ca0a24abec28311bd3b49c8153da971b9a50723ebad3","source_rights_note":"Own simulation code and output, MIT licence in the source repository; no third-party data.","verification_count":2,"verification_level":"SINGLE_OPERATOR"},"claim_boundary":"Simulated independent random walks only, seed 20261015, 400 paths of 5000 hourly bars. Says nothing about real markets or about any investment result.","deviations":[],"outcome":{"max_abs_tradable_sharpe_median":"0.13","min_booked_sharpe_median":"4.39","phantom_share_max":"1.017","phantom_share_min":"0.98","windows":"30,60,100,250,500","windows_passing_gate":"5","windows_total":"5"},"protocol_sha256":"10d8d37361cda4c4248be947912e0c3faca75b8c765ecc8089e6e01dfad43323","reproduction_level":"not independently reproduced","run_id":"run-1","sources":[{"id":"results.json","sha256":"89dd6efe060a3058f071ca0a24abec28311bd3b49c8153da971b9a50723ebad3"},{"id":"results_other.json","sha256":"7ba9fa0ce0e8dcc2f7020a7310418101fe01e2d51f6b6f49ade2576060f9099e"},{"id":"code/phantom_mr_sim.py","sha256":"1019a9064ab0b1be4dfb4197566f633bd2a36f4db94bc742a7e0f6c43439458d"},{"id":"code/other_hedges.py","sha256":"13ffabc1e2bd9fd1112c5b9bc953adcdaa53cf7a87c6edfa29398ff6c63218be"},{"id":"code/mechanism_check.py","sha256":"1f35d5b311be9cf3bc3b331c519359d8ef8f36ddca6e27c25084cbfef7f34159"},{"id":"code/make_figures.py","sha256":"05dde7f2cab8d9219125f06518ae51679016d9442228a646f03fd64b607aa3df"}],"status":"PASSED_UNDER_PROTOCOL"},"hash":"5b1bc0579ffbf202cd475c3f9fea25ab649d973eae98af4d8b6f32f023c397ed","prev":"83d76b3c721344520637006632e2da18024cec2d14302c0abafbd953299538b2","seq":1,"ts":"2026-11-18T16:07:08Z","type":"record","v":1}
+{"body":{"card_sha256":"b161dacc37883296721351313794692caa8635f7465218b1f9dafa92997b04e4","format":"evidence-card-json-svg","record_seq":1},"hash":"19c345a87e50a58512eab07d2daebe712df057c28cbceee9903b978c025cad20","prev":"5b1bc0579ffbf202cd475c3f9fea25ab649d973eae98af4d8b6f32f023c397ed","seq":2,"ts":"2026-11-18T16:07:08Z","type":"issue","v":1}
diff --git a/examples/phantom_mean_reversion/evidence/anchor-after-freeze.txt b/examples/phantom_mean_reversion/evidence/anchor-after-freeze.txt
index 0576c3e00..4a3b71b6d 100644
--- a/examples/phantom_mean_reversion/evidence/anchor-after-freeze.txt
+++ b/examples/phantom_mean_reversion/evidence/anchor-after-freeze.txt
@@ -1 +1 @@
-{"created_at":"2026-11-18T14:23:08Z","entries":1,"head_hash":"8fad6983ab64bf55d47a46fc29a107805a3474010d6450a1f3927dbf44c62d2d","head_seq":0,"kind":"protocolith-anchor","protocolith_version":"0.6.0","v":1}
\ No newline at end of file
+{"created_at":"2026-11-18T16:07:04Z","entries":1,"head_hash":"83d76b3c721344520637006632e2da18024cec2d14302c0abafbd953299538b2","head_seq":0,"kind":"protocolith-anchor","protocolith_version":"0.7.0","v":1}
\ No newline at end of file
diff --git a/examples/phantom_mean_reversion/evidence/anchor-after-record.txt b/examples/phantom_mean_reversion/evidence/anchor-after-record.txt
index 3ef4fdb72..bb27d2d62 100644
--- a/examples/phantom_mean_reversion/evidence/anchor-after-record.txt
+++ b/examples/phantom_mean_reversion/evidence/anchor-after-record.txt
@@ -1 +1 @@
-{"created_at":"2026-11-18T14:23:12Z","entries":3,"head_hash":"78fb3212955515c1692069c4f197d72fda0c5edec9a2556a28912b314d05da4f","head_seq":2,"kind":"protocolith-anchor","protocolith_version":"0.6.0","v":1}
\ No newline at end of file
+{"created_at":"2026-11-18T16:07:08Z","entries":3,"head_hash":"19c345a87e50a58512eab07d2daebe712df057c28cbceee9903b978c025cad20","head_seq":2,"kind":"protocolith-anchor","protocolith_version":"0.7.0","v":1}
\ No newline at end of file
diff --git a/examples/selective_disclosure/README.md b/examples/selective_disclosure/README.md
new file mode 100644
index 000000000..34132ce6d
--- /dev/null
+++ b/examples/selective_disclosure/README.md
@@ -0,0 +1,28 @@
+# Example: a private notebook, a public view
+
+A synthetic research notebook of 31 ledger entries (four protocols: two parameter sweeps, a robustness study and a paper claim)
+and the view a researcher would publish. The private ledger is **not** in this folder, which is the point; the committed files
+are what gets published:
+
+| File | What |
+| --- | --- |
+| `policy.json` | the choice: `PAPER_CLAIM` in full, `STUDY_ROBUSTNESS` as a summary, every `SWEEP_*` hidden |
+| `public/disclosure.jsonl` | the published ledger view (3 entries in full, 6 summaries, 22 hidden) |
+| `public/atlas.html` | the self-contained atlas of the published view; open it in a browser |
+| `public/anchor.txt` | the anchor statement of the head |
+| `public/revealed_entry.json` | one entry the owner chose to reveal (it is hidden in the disclosure) |
+
+
+
+## Verify it yourself
+
+```bash
+protocolith verify-disclosure public/disclosure.jsonl
+protocolith verify-disclosure public/disclosure.jsonl --reveal public/revealed_entry.json
+```
+
+The second command prints `reveal seq=16 level=hidden: MATCHES`: the revealed entry is exactly the hidden one the disclosure
+committed to. Edit one line of `disclosure.jsonl` and run the first command again to see the failure.
+
+Rebuild everything with `python3 scripts/build_disclosure_demo.py`; the screenshots and GIFs come from
+`scripts/build_atlas_screens.py` and `scripts/build_demo_gif.py --scenario disclose`. All data is synthetic.
diff --git a/examples/selective_disclosure/policy.json b/examples/selective_disclosure/policy.json
new file mode 100644
index 000000000..8b96d3f78
--- /dev/null
+++ b/examples/selective_disclosure/policy.json
@@ -0,0 +1,10 @@
+{
+ "v": 1,
+ "default": "hidden",
+ "rules": [
+ {"protocol_id": "PAPER_CLAIM", "level": "full"},
+ {"protocol_id": "STUDY_ROBUSTNESS", "level": "summary"},
+ {"protocol_id": "SWEEP_*", "level": "hidden"}
+ ],
+ "summary_fields": ["status", "outcome", "claim_boundary"]
+}
diff --git a/examples/selective_disclosure/public/anchor.txt b/examples/selective_disclosure/public/anchor.txt
new file mode 100644
index 000000000..b7dbac404
--- /dev/null
+++ b/examples/selective_disclosure/public/anchor.txt
@@ -0,0 +1 @@
+{"created_at":"2026-11-13T18:00:00Z","entries":31,"head_hash":"a6b35166b89e26f1e0833110591ebda2163f24235204caa3cc03d8a46440ea0f","head_seq":30,"kind":"protocolith-anchor","protocolith_version":"0.7.0","v":1}
\ No newline at end of file
diff --git a/examples/selective_disclosure/public/atlas.html b/examples/selective_disclosure/public/atlas.html
new file mode 100644
index 000000000..80206e4a8
--- /dev/null
+++ b/examples/selective_disclosure/public/atlas.html
@@ -0,0 +1,543 @@
+
+
+
+
+
+
+
+Synthetic notebook (published view)
+
+
+
+
+
+
+
+
+
+
+
+
+
The embedded atlas data could not be read.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/examples/selective_disclosure/public/disclosure.jsonl b/examples/selective_disclosure/public/disclosure.jsonl
new file mode 100644
index 000000000..6db8f1a8f
--- /dev/null
+++ b/examples/selective_disclosure/public/disclosure.jsonl
@@ -0,0 +1,32 @@
+{"counts":{"full":3,"hidden":22,"summary":6},"entries":31,"head_hash":"a6b35166b89e26f1e0833110591ebda2163f24235204caa3cc03d8a46440ea0f","head_seq":30,"kind":"protocolith-disclosure","v":1}
+{"hash":"5deb480b5d233f1504857c38a682fd354ba865b0735a1db9948fdbd6a683b06e","level":"hidden","prev":"0000000000000000000000000000000000000000000000000000000000000000","seq":0}
+{"hash":"3ebf450f37b0829fbc89dd671a06dade041d6d2b07adf975f13a3472324250bf","level":"hidden","prev":"5deb480b5d233f1504857c38a682fd354ba865b0735a1db9948fdbd6a683b06e","seq":1}
+{"hash":"9ba5d1cb7624c80863cac1b04be8663bca6361fef006eb5a17a1e52ae7239aeb","level":"hidden","prev":"3ebf450f37b0829fbc89dd671a06dade041d6d2b07adf975f13a3472324250bf","seq":2}
+{"hash":"a813c66351c01036b90942e468f511eeb7e91cf029fb0c00825175027d34327d","level":"hidden","prev":"9ba5d1cb7624c80863cac1b04be8663bca6361fef006eb5a17a1e52ae7239aeb","seq":3}
+{"hash":"810755b408ef986e8b20351e840ee35f25f960c96e5f178da95e726d98ad2fc5","level":"hidden","prev":"a813c66351c01036b90942e468f511eeb7e91cf029fb0c00825175027d34327d","seq":4}
+{"hash":"ccd58132c23201d6ae973bde0d47bd60916b32a07896f252c714c8f052ed3867","level":"hidden","prev":"810755b408ef986e8b20351e840ee35f25f960c96e5f178da95e726d98ad2fc5","seq":5}
+{"hash":"cf977b94ee6446e63329183d6acb21b2bbeeeed4237c5860628af6a93fc35e6e","level":"hidden","prev":"ccd58132c23201d6ae973bde0d47bd60916b32a07896f252c714c8f052ed3867","seq":6}
+{"hash":"315a3ce28b6e7869d0805204dfd06a8ad7cf559963efe6ffaf731790985af0e3","level":"hidden","prev":"cf977b94ee6446e63329183d6acb21b2bbeeeed4237c5860628af6a93fc35e6e","seq":7}
+{"hash":"7a2da2a9859f7973449bc9bf61b780709d44b5bfafedfc1f773982f35a7aa2ab","level":"hidden","prev":"315a3ce28b6e7869d0805204dfd06a8ad7cf559963efe6ffaf731790985af0e3","seq":8}
+{"hash":"59d5ddf3a7779b60f760290147217cbd7e0abeb18eab42f95229838629c2e209","level":"hidden","prev":"7a2da2a9859f7973449bc9bf61b780709d44b5bfafedfc1f773982f35a7aa2ab","seq":9}
+{"hash":"b4a9269e0ffe85bfb1b5821ff0a34e40a2f8b8c7edcc8c1239480389943f1e07","level":"hidden","prev":"59d5ddf3a7779b60f760290147217cbd7e0abeb18eab42f95229838629c2e209","seq":10}
+{"hash":"b1628cd2c426dae5dd14effcd9e9c856adcb07bdcd683ea12bf6511b0932c7ce","level":"hidden","prev":"b4a9269e0ffe85bfb1b5821ff0a34e40a2f8b8c7edcc8c1239480389943f1e07","seq":11}
+{"hash":"311649429b1549bec4e589a9bbf23fd942fea0cc3133afc1e2b17f9dd41de03d","level":"hidden","prev":"b1628cd2c426dae5dd14effcd9e9c856adcb07bdcd683ea12bf6511b0932c7ce","seq":12}
+{"hash":"e6ab225e348b28a0a6a98248b9d2a95ba4777625e532c269310d685209d89837","level":"hidden","prev":"311649429b1549bec4e589a9bbf23fd942fea0cc3133afc1e2b17f9dd41de03d","seq":13}
+{"hash":"c97b71afacbe01aa3cb1589751cc55927ba541f7afbe85c26065a68bf88389fb","level":"hidden","prev":"e6ab225e348b28a0a6a98248b9d2a95ba4777625e532c269310d685209d89837","seq":14}
+{"hash":"31d57dee5d63b954fbd24979a3ec512d84aa8fdd9954564fba0807ace82198c9","level":"hidden","prev":"c97b71afacbe01aa3cb1589751cc55927ba541f7afbe85c26065a68bf88389fb","seq":15}
+{"hash":"9c86ae9942ce42f362120dcb1a1c46f911b18bbf53238a572cd073428edfe3e7","level":"hidden","prev":"31d57dee5d63b954fbd24979a3ec512d84aa8fdd9954564fba0807ace82198c9","seq":16}
+{"hash":"8b94c047947beaae4aadc92d21d3448b1839bad3cebfbb6fd398151199b29c81","level":"hidden","prev":"9c86ae9942ce42f362120dcb1a1c46f911b18bbf53238a572cd073428edfe3e7","seq":17}
+{"hash":"60869ef220c638011ceb08742806745f6c833fcc6d862aef43aceb9065b48f1c","level":"hidden","prev":"8b94c047947beaae4aadc92d21d3448b1839bad3cebfbb6fd398151199b29c81","seq":18}
+{"hash":"f8187d37c211a2b62c2e44e979bf9bc2ca7162f52aed5395e58336792ef53189","level":"hidden","prev":"60869ef220c638011ceb08742806745f6c833fcc6d862aef43aceb9065b48f1c","seq":19}
+{"hash":"55765312df4f22b0dd5ee06de1c68f675910fd721e61482ffba8877e7b7ada90","level":"hidden","prev":"f8187d37c211a2b62c2e44e979bf9bc2ca7162f52aed5395e58336792ef53189","seq":20}
+{"hash":"8715e9e0026ee767a0e253cf1fd0737e977b0019cebc701b4891d91639b055c0","level":"hidden","prev":"55765312df4f22b0dd5ee06de1c68f675910fd721e61482ffba8877e7b7ada90","seq":21}
+{"hash":"bc5fc09e586e8e172a25e3b72316a5b9773dad4b77836febfc2f3616e6bf5b86","level":"summary","prev":"8715e9e0026ee767a0e253cf1fd0737e977b0019cebc701b4891d91639b055c0","seq":22,"summary":{"protocol_id":"STUDY_ROBUSTNESS","version":"1"},"ts":"2026-11-10T22:00:00Z","type":"freeze"}
+{"hash":"c5e99d9223c824e5af35b7931bdd6bb3d4e1a6e0a559e6c8f25892ad213b2f58","level":"summary","prev":"bc5fc09e586e8e172a25e3b72316a5b9773dad4b77836febfc2f3616e6bf5b86","seq":23,"summary":{"claim_boundary":"STUDY_ROBUSTNESS, setting 1 only.","outcome":{"metric":"0.00","setting":"1"},"protocol_id":"STUDY_ROBUSTNESS","status":"NEGATIVE_RESULT_UNDER_PROTOCOL"},"ts":"2026-11-10T23:00:00Z","type":"record"}
+{"hash":"c4d1795b07d02fe581def443221c490917777ced3f526c63308dcf165a8181cf","level":"summary","prev":"c5e99d9223c824e5af35b7931bdd6bb3d4e1a6e0a559e6c8f25892ad213b2f58","seq":24,"summary":{"claim_boundary":"STUDY_ROBUSTNESS, setting 2 only.","outcome":{"metric":"0.37","setting":"2"},"protocol_id":"STUDY_ROBUSTNESS","status":"PASSED_UNDER_PROTOCOL"},"ts":"2026-11-11T00:00:00Z","type":"record"}
+{"hash":"9803f7b2131b1bda6f4c3283061698aa2b08633dd861a91c67957c69bd218abe","level":"summary","prev":"c4d1795b07d02fe581def443221c490917777ced3f526c63308dcf165a8181cf","seq":25,"summary":{"claim_boundary":"STUDY_ROBUSTNESS, setting 3 only.","outcome":{"metric":"0.74","setting":"3"},"protocol_id":"STUDY_ROBUSTNESS","status":"NEGATIVE_RESULT_UNDER_PROTOCOL"},"ts":"2026-11-11T01:00:00Z","type":"record"}
+{"hash":"2aa4c01fca9806c0cf659f5b89bfa7bce7ced86178873fead15c732250280528","level":"summary","prev":"9803f7b2131b1bda6f4c3283061698aa2b08633dd861a91c67957c69bd218abe","seq":26,"summary":{"claim_boundary":"STUDY_ROBUSTNESS, setting 4 only.","outcome":{"metric":"0.11","setting":"4"},"protocol_id":"STUDY_ROBUSTNESS","status":"NEGATIVE_RESULT_UNDER_PROTOCOL"},"ts":"2026-11-11T02:00:00Z","type":"record"}
+{"entry":{"body":{"protocol":{"gate":"PAPER_CLAIM: gate fixed before the runs","protocol_id":"PAPER_CLAIM","question":"the claim in the paper","version":"1"},"protocol_id":"PAPER_CLAIM","protocol_sha256":"8997db49956d3e0cd55f3da9cf85deb20c695072749d370dfc51c15bd1521ab4","supersedes":null,"version":"1"},"hash":"a84e136ed53fa6b3454bdae824a651b53dbfd356a441a366187bf874972baee4","prev":"2aa4c01fca9806c0cf659f5b89bfa7bce7ced86178873fead15c732250280528","seq":27,"ts":"2026-11-11T03:00:00Z","type":"freeze","v":1},"level":"full","seq":27}
+{"entry":{"body":{"card":{"access_date":"2026-11-09","ai_assistance":"not used","baseline_control_summary":"Baseline: none.","claim_type":"source_audit","domain":"synthetic research","execution_mode":"MANUAL_NO_AI","git_commit":"none","known_limitations":["Synthetic demonstration."],"manual_review":"Synthetic.","official_source_name":"Synthetic notebook","official_source_url":"https://example.org/notebook","operator":"demo operator","public_claim_captured_at":"2026-11-09","public_claim_locator":"section 1, paragraph 2","public_claim_source_sha256":"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc","public_claim_source_url":"https://example.org/notebook","public_claim_text":"Synthetic demonstration claim.","public_claim_verbatim_quote":"Synthetic demonstration claim.","raw_payload_manifest":"No raw payload committed.","runner_command":"manual","sanitized_report_path":"examples/selective_disclosure/README.md","sanitized_report_sha256":"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc","source_rights_note":"Synthetic data written for this demonstration.","verification_count":1,"verification_level":"SINGLE_OPERATOR"},"claim_boundary":"PAPER_CLAIM, setting 1 only.","deviations":[],"outcome":{"metric":"0.00","setting":"1"},"protocol_sha256":"8997db49956d3e0cd55f3da9cf85deb20c695072749d370dfc51c15bd1521ab4","reproduction_level":"not independently reproduced","run_id":"run-01","sources":[{"id":"results.csv","sha256":"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"}],"status":"PASSED_UNDER_PROTOCOL"},"hash":"2e0fb3c22b37bb3f33e591843e4b375b1dccdd38ff74356305f83de0671aab13","prev":"a84e136ed53fa6b3454bdae824a651b53dbfd356a441a366187bf874972baee4","seq":28,"ts":"2026-11-11T04:00:00Z","type":"record","v":1},"level":"full","seq":28}
+{"hash":"f363001191c58a38454da52966dd78954f8fa252b53fb233fa2ee42e5af4d918","level":"summary","prev":"2e0fb3c22b37bb3f33e591843e4b375b1dccdd38ff74356305f83de0671aab13","seq":29,"summary":{"protocol_id":"STUDY_ROBUSTNESS"},"ts":"2026-11-11T05:00:00Z","type":"deviation"}
+{"entry":{"body":{"card_sha256":"da939a7e8f9e0fd718db8413ce577a336dcb579fba4fc996f88266037d0d7d23","format":"evidence-card-json-svg","record_seq":28},"hash":"a6b35166b89e26f1e0833110591ebda2163f24235204caa3cc03d8a46440ea0f","prev":"f363001191c58a38454da52966dd78954f8fa252b53fb233fa2ee42e5af4d918","seq":30,"ts":"2026-11-11T06:00:00Z","type":"issue","v":1},"level":"full","seq":30}
diff --git a/examples/selective_disclosure/public/revealed_entry.json b/examples/selective_disclosure/public/revealed_entry.json
new file mode 100644
index 000000000..cb03d624c
--- /dev/null
+++ b/examples/selective_disclosure/public/revealed_entry.json
@@ -0,0 +1,55 @@
+{
+ "body": {
+ "card": {
+ "access_date": "2026-11-09",
+ "ai_assistance": "not used",
+ "baseline_control_summary": "Baseline: none.",
+ "claim_type": "source_audit",
+ "domain": "synthetic research",
+ "execution_mode": "MANUAL_NO_AI",
+ "git_commit": "none",
+ "known_limitations": [
+ "Synthetic demonstration."
+ ],
+ "manual_review": "Synthetic.",
+ "official_source_name": "Synthetic notebook",
+ "official_source_url": "https://example.org/notebook",
+ "operator": "demo operator",
+ "public_claim_captured_at": "2026-11-09",
+ "public_claim_locator": "section 1, paragraph 2",
+ "public_claim_source_sha256": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
+ "public_claim_source_url": "https://example.org/notebook",
+ "public_claim_text": "Synthetic demonstration claim.",
+ "public_claim_verbatim_quote": "Synthetic demonstration claim.",
+ "raw_payload_manifest": "No raw payload committed.",
+ "runner_command": "manual",
+ "sanitized_report_path": "examples/selective_disclosure/README.md",
+ "sanitized_report_sha256": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
+ "source_rights_note": "Synthetic data written for this demonstration.",
+ "verification_count": 1,
+ "verification_level": "SINGLE_OPERATOR"
+ },
+ "claim_boundary": "SWEEP_SPREADS, setting 3 only.",
+ "deviations": [],
+ "outcome": {
+ "metric": "0.74",
+ "setting": "3"
+ },
+ "protocol_sha256": "5cc6f925e7b59cfb04ef64c221a598fda408d4137e6a3a5bee946a4f746eb315",
+ "reproduction_level": "not independently reproduced",
+ "run_id": "run-03",
+ "sources": [
+ {
+ "id": "results.csv",
+ "sha256": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
+ }
+ ],
+ "status": "NEGATIVE_RESULT_UNDER_PROTOCOL"
+ },
+ "hash": "9c86ae9942ce42f362120dcb1a1c46f911b18bbf53238a572cd073428edfe3e7",
+ "prev": "31d57dee5d63b954fbd24979a3ec512d84aa8fdd9954564fba0807ace82198c9",
+ "seq": 16,
+ "ts": "2026-11-10T16:00:00Z",
+ "type": "record",
+ "v": 1
+}
diff --git a/mkdocs.yml b/mkdocs.yml
index bcbc5c085..d72f7eb93 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -60,6 +60,7 @@ nav:
- Anchoring the head: guides-anchoring-the-head.md
- Anchor your results: guides-anchor-your-results.md
- Browse experiments (atlas): guides-atlas.md
+ - Publish what you choose (disclosure): guides-selective-disclosure.md
- Reference:
- Command reference: CLI.md
- Core specification: spec-core.md
@@ -73,6 +74,7 @@ nav:
- Overview: examples.md
- Statuses and versions: examples-statuses-and-versions.md
- A published study as a record: examples-phantom-mean-reversion.md
+ - A private notebook, a public view: examples-selective-disclosure.md
- Development:
- Architecture: development-architecture.md
- Testing and coverage: development-testing.md
diff --git a/pyproject.toml b/pyproject.toml
index e2a6ae84c..889f92852 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "protocolith"
-version = "0.6.0"
+version = "0.7.0"
description = "Records, verifies and issues trial records: frozen protocol, hashed sources, honest result status."
dynamic = ["readme"]
license = "Apache-2.0"
diff --git a/scripts/build_atlas_screens.py b/scripts/build_atlas_screens.py
new file mode 100644
index 000000000..946170cb0
--- /dev/null
+++ b/scripts/build_atlas_screens.py
@@ -0,0 +1,80 @@
+#!/usr/bin/env python3
+"""Screenshots and a tour GIF of the published atlas in examples/selective_disclosure/public/atlas.html.
+
+Uses a locally installed Chrome (headless) and Pillow, neither of which Protocolith needs:
+
+ uv run --no-project --with pillow python scripts/build_atlas_screens.py [--chrome PATH]
+
+Writes docs/assets/protocolith/atlas-overview.png, atlas-full.png, atlas-summary.png, atlas-hidden.png and atlas-tour.gif.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import shutil
+import subprocess
+import tempfile
+from pathlib import Path
+
+from PIL import Image
+
+ROOT = Path(__file__).resolve().parent.parent
+PAGE = ROOT / "examples" / "selective_disclosure" / "public" / "atlas.html"
+ASSETS = ROOT / "docs" / "assets" / "protocolith"
+CHROME = (
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
+ "google-chrome",
+ "chromium",
+ "chrome",
+)
+
+
+def find_chrome(explicit: str | None) -> str:
+ for candidate in ((explicit,) if explicit else CHROME):
+ if candidate and (Path(candidate).exists() or shutil.which(candidate)):
+ return candidate
+ raise SystemExit("no Chrome or Chromium found; pass --chrome PATH")
+
+
+def row_ids() -> dict[str, str]:
+ text = PAGE.read_text(encoding="utf-8")
+ start = text.index(">", text.index('id="atlas-data"')) + 1
+ rows = json.loads(text[start : text.index("", start)].replace("\\u003c", "<"))["rows"]
+ ids = [row[0] for row in rows]
+ return {
+ "full": next(i for i in ids if i.startswith("PLITH-")),
+ "summary": next(i for i in ids if i.startswith("LEDGER-RECORD-")),
+ "hidden": next(i for i in ids if i.startswith("HIDDEN-")),
+ }
+
+
+def shoot(chrome: str, fragment: str, out: Path) -> None:
+ url = PAGE.as_uri() + (f"#{fragment}" if fragment else "")
+ subprocess.run(
+ [chrome, "--headless=new", "--disable-gpu", "--hide-scrollbars", "--window-size=1280,900", "--virtual-time-budget=3000", f"--screenshot={out}", url],
+ check=True, capture_output=True, timeout=90,
+ )
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
+ parser.add_argument("--chrome", default=None)
+ args = parser.parse_args()
+ chrome = find_chrome(args.chrome)
+ ids = row_ids()
+ shots = {"overview": "", **ids}
+ for name, fragment in shots.items():
+ shoot(chrome, fragment, ASSETS / f"atlas-{name}.png")
+ print("wrote", ASSETS / f"atlas-{name}.png", flush=True)
+ frames = [Image.open(ASSETS / f"atlas-{name}.png").convert("RGB").resize((960, 675), Image.Resampling.LANCZOS) for name in shots]
+ palette = frames[0].quantize(colors=128, method=Image.Quantize.MEDIANCUT)
+ quantized = [f.quantize(palette=palette, dither=Image.Dither.NONE) for f in frames]
+ out = ASSETS / "atlas-tour.gif"
+ quantized[0].save(out, save_all=True, append_images=quantized[1:], duration=[3200, 3200, 3200, 3600], loop=0, optimize=True)
+ print(f"wrote {out} bytes={out.stat().st_size}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/build_core_vectors.py b/scripts/build_core_vectors.py
index 2d2d478af..c920efc97 100644
--- a/scripts/build_core_vectors.py
+++ b/scripts/build_core_vectors.py
@@ -18,6 +18,7 @@
from typing import Any
from protocolith.core import MAX_ENTRY_BYTES, CanonError, decode, encode, scan
+from protocolith.core.disclosure import disclose_verifier, parse_policy, verify_disclosure
from protocolith.core.issue import card_hash
from protocolith.core.ledger import ZERO_HASH, entry_hash, serialize
from protocolith.core.rules import Verifier, apply_expected_head
@@ -357,12 +358,48 @@ def anchor_cases() -> list[dict[str, Any]]:
return cases
+DISCLOSURE_POLICIES = {
+ "all_full": {"default": "full"},
+ "all_summary": {"default": "summary"},
+ "all_hidden": {},
+ "mixed": {"default": "hidden", "rules": [{"seq": 0, "level": "full"}, {"seq": [1, 2], "level": "summary"}]},
+}
+
+
+def disclosure_cases(ledgers: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Disclosures of the valid_full_flow ledger under four policies, plus two edited disclosures that must fail."""
+ base = next(case for case in ledgers if case["name"] == "valid_full_flow")
+ _, verifier = scan(str(base["ledger"]).encode("utf-8"), card_hash)
+ cases: list[dict[str, Any]] = []
+ for name, doc in DISCLOSURE_POLICIES.items():
+ built = disclose_verifier(verifier, parse_policy(doc))
+ cases.append(
+ {
+ "name": name,
+ "ledger": base["ledger"],
+ "policy": doc,
+ "disclosure": built.data.decode("utf-8"),
+ "expect": {"ok": True, "codes": [], "counts": built.counts},
+ }
+ )
+ full = cases[0]["disclosure"].split("\n")
+ chain = cases[1]["disclosure"].split("\n")
+ edited = json.loads(full[2])
+ edited["entry"]["body"]["run_id"] = "edited"
+ full[2] = encode(edited).decode("utf-8")
+ dropped = chain[:2] + chain[3:]
+ cases.append({"name": "edited_full_entry", "disclosure": "\n".join(full), "expect": {"ok": False, "codes": ["DISCLOSURE_HASH"]}})
+ cases.append({"name": "dropped_entry", "disclosure": "\n".join(dropped), "expect": {"ok": False, "codes": ["BAD_DISCLOSURE"]}})
+ return cases
+
+
def check(
canonical: list[dict[str, Any]],
hashes: list[dict[str, Any]],
ledgers: list[dict[str, Any]],
heads: list[dict[str, Any]],
anchors: list[dict[str, Any]],
+ disclosures: list[dict[str, Any]],
) -> None:
"""Refuse to write vectors the reference implementation does not reproduce."""
for case in canonical:
@@ -388,6 +425,9 @@ def check(
text = encode(case["statement"]).decode("utf-8")
assert text == case["canonical"], case["name"]
assert hashlib.sha256(text.encode("utf-8")).hexdigest() == case["anchor_id"], case["name"]
+ for case in disclosures:
+ report = verify_disclosure(str(case["disclosure"]).encode("utf-8"))
+ assert report.ok == case["expect"]["ok"] and report.codes == case["expect"]["codes"], (case["name"], report.codes)
def dump(name: str, description: str, cases: list[dict[str, Any]]) -> str:
@@ -398,7 +438,8 @@ def dump(name: str, description: str, cases: list[dict[str, Any]]) -> str:
def build_vectors() -> dict[str, str]:
canonical, hashes, ledgers, heads = canonical_cases(), hash_cases(), ledger_cases(), head_cases()
anchors = anchor_cases()
- check(canonical, hashes, ledgers, heads, anchors)
+ disclosures = disclosure_cases(ledgers)
+ check(canonical, hashes, ledgers, heads, anchors, disclosures)
return {
"canonical.json": dump(
"canonical",
@@ -424,6 +465,12 @@ def build_vectors() -> dict[str, str]:
"is the anchor_id; the local anchor file is named file_name.",
anchors,
),
+ "disclosures.json": dump(
+ "disclosures",
+ "A disclosure file (JSON Lines text): verify its structure, hash chain and full entries; expect ok and the sorted "
+ "unique codes. Cases that carry a ledger and a policy are what that policy must produce from that ledger, byte for byte.",
+ disclosures,
+ ),
}
diff --git a/scripts/build_demo_gif.py b/scripts/build_demo_gif.py
index 09af5907f..404177c1c 100644
--- a/scripts/build_demo_gif.py
+++ b/scripts/build_demo_gif.py
@@ -9,7 +9,7 @@
Pillow is needed only here, not by Protocolith:
- uv run --no-project --with pillow python scripts/build_demo_gif.py [--scenario ledger|anchor] [--out FILE]
+ uv run --no-project --with pillow python scripts/build_demo_gif.py [--scenario ledger|anchor|disclose|story] [--out FILE]
Standard output shows the progress in percent. The frames contain the current date (it is part of the card ids).
"""
@@ -79,6 +79,38 @@ def step(shown: str, argv: list[str]) -> None:
return steps
+def disclose_script(work: Path) -> list[tuple[str, list[str], int]]:
+ """A private notebook, a policy, the published view, a reveal, and an edit that is caught."""
+ import json
+
+ sys.path.insert(0, str(ROOT / "scripts"))
+ from build_disclosure_demo import OUT, build_private
+ from protocolith.core import Store, entries
+
+ steps: list[tuple[str, list[str], int]] = []
+
+ def step(shown: str, argv: list[str]) -> None:
+ out, code = run(argv, work)
+ steps.append((shown, out, code))
+
+ build_private(Store(work / ".protocolith"))
+ shutil.copy(OUT / "policy.json", work / "policy.json")
+ ledger = entries(Store(work / ".protocolith"))
+ revealed = next(e for e in ledger if e["type"] == "record" and e["body"]["run_id"] == "run-03" and 13 < e["seq"] < 22)
+ (work / "entry.json").write_text(json.dumps(revealed), encoding="utf-8")
+ step("protocolith summary | head -n 3", ["summary"])
+ steps[-1] = (steps[-1][0], steps[-1][1][:3], 0)
+ step("protocolith disclose --policy policy.json --out public.jsonl", ["disclose", "--policy", "policy.json", "--out", "public.jsonl"])
+ lines = (work / "public.jsonl").read_text(encoding="utf-8").splitlines()
+ steps.append(("head -n 3 public.jsonl", [short(line) for line in lines[:3]], 0))
+ step("protocolith verify-disclosure public.jsonl", ["verify-disclosure", "public.jsonl"])
+ step("protocolith verify-disclosure public.jsonl --reveal entry.json", ["verify-disclosure", "public.jsonl", "--reveal", "entry.json"])
+ (work / "public.jsonl").write_text("\n".join(lines[:16] + lines[17:]) + "\n", encoding="utf-8")
+ steps.append(("# someone drops one hidden entry from the published file", [], 0))
+ step("protocolith verify-disclosure public.jsonl", ["verify-disclosure", "public.jsonl"])
+ return steps
+
+
def script(work: Path) -> list[tuple[str, list[str], int]]:
"""Run every step for real and return (shown command, output lines, exit code)."""
steps: list[tuple[str, list[str], int]] = []
@@ -119,15 +151,19 @@ def colour(line: str, code: int) -> tuple[int, int, int]:
return TEXT
-def frame(font: ImageFont.FreeTypeFont, rows: list[tuple[str, tuple[int, int, int]]], cursor: bool) -> Image.Image:
+def frame(font: ImageFont.FreeTypeFont, rows: list[tuple[str, tuple[int, int, int]]], cursor: bool, caption: str = "") -> Image.Image:
img = Image.new("RGB", (WIDTH, HEIGHT), BG)
draw = ImageDraw.Draw(img)
draw.rectangle((0, 0, WIDTH, 30), fill=BAR)
for i, colr in enumerate(((240, 110, 110), (232, 176, 74), (110, 200, 140))):
draw.ellipse((14 + i * 20, 9, 26 + i * 20, 21), fill=colr)
draw.text((WIDTH // 2 - 60, 7), f"protocolith {VERSION}", font=font, fill=DIM)
- visible = (HEIGHT - TOP - PAD) // LINE_H
- y = TOP
+ top = TOP + (30 if caption else 0)
+ if caption:
+ draw.rectangle((0, 30, WIDTH, 64), fill=(32, 44, 58))
+ draw.text((PAD, 38), caption, font=font, fill=PROMPT)
+ visible = (HEIGHT - top - PAD) // LINE_H
+ y = top
for text, colr in rows[-visible:]:
if text.startswith("$ "):
draw.text((PAD, y), "$", font=font, fill=PROMPT)
@@ -172,10 +208,106 @@ def add(delay: int, cursor: bool = False) -> None:
return frames, delays
+def card(lines: list[tuple[str, int, tuple[int, int, int]]]) -> Image.Image:
+ """A title card: centred lines of (text, size, colour)."""
+ img = Image.new("RGB", (WIDTH, HEIGHT), BG)
+ draw = ImageDraw.Draw(img)
+ fonts = {}
+ total = sum(size + 18 for _, size, _ in lines)
+ y = (HEIGHT - total) // 2
+ for text, size, colour in lines:
+ if size not in fonts:
+ fonts[size] = ImageFont.truetype(next(p for p in FONT_CANDIDATES if Path(p).exists()), size)
+ w = draw.textlength(text, font=fonts[size])
+ draw.text(((WIDTH - w) / 2, y), text, font=fonts[size], fill=colour)
+ y += size + 18
+ return img
+
+
+def story_chapters(work: Path, notebook: Path) -> list[tuple[str, list[tuple[str, list[str], int]]]]:
+ """Real runs, grouped in chapters with a one-line caption each."""
+ import shutil as _sh
+
+ sys.path.insert(0, str(ROOT / "scripts"))
+ from build_disclosure_demo import OUT, build_private
+ from protocolith.core import Store, entries
+
+ def runs(cwd: Path, items: list[tuple[str, list[str]]]) -> list[tuple[str, list[str], int]]:
+ steps = []
+ for shown, argv in items:
+ out, code = run(argv, cwd)
+ steps.append((shown, out, code))
+ return steps
+
+ ledger = work / ".protocolith" / "ledger.jsonl"
+ chapters: list[tuple[str, list[tuple[str, list[str], int]]]] = []
+ chapters.append(("1 Freeze the protocol BEFORE you run anything", runs(work, [("protocolith init", ["init"]), ("protocolith freeze protocol.json", ["freeze", "protocol.json"])])))
+ chapters.append(("2 Record the result, failures included", runs(work, [("protocolith record record.json", ["record", "record.json"]), ("protocolith verify-ledger", ["verify-ledger"])])))
+ backup = ledger.read_bytes()
+ ledger.write_text(ledger.read_text(encoding="utf-8").replace("PASSED_UNDER_PROTOCOL", "FAILED_UNDER_PROTOCOL", 1), encoding="utf-8")
+ edited = runs(work, [("protocolith verify-ledger", ["verify-ledger"])])
+ ledger.write_bytes(backup)
+ chapters.append(("3 The history is a hash chain: edit one word and it breaks", [("sed -i 's/PASSED/FAILED/' .protocolith/ledger.jsonl", [], 0), *edited]))
+ anchored = runs(work, [("protocolith anchor --write-head head.txt", ["anchor", "--write-head", "head.txt"])])
+ lines = backup.decode("utf-8").splitlines(keepends=True)
+ ledger.write_text("".join(lines[:-1]), encoding="utf-8")
+ cut = runs(work, [("protocolith verify-ledger", ["verify-ledger"]), ("protocolith verify-ledger --anchors", ["verify-ledger", "--anchors"])])
+ ledger.write_bytes(backup)
+ chapters.append(("4 Anchor the head outside your disk: cutting entries is caught", [*anchored, ("head -n 1 ledger.jsonl > tmp && mv tmp ledger.jsonl # drop the last entry", [], 0), *cut]))
+ build_private(Store(notebook / ".protocolith"))
+ _sh.copy(OUT / "policy.json", notebook / "policy.json")
+ revealed = next(e for e in entries(Store(notebook / ".protocolith")) if e["type"] == "record" and e["body"]["run_id"] == "run-03" and 13 < e["seq"] < 22)
+ (notebook / "entry.json").write_text(__import__("json").dumps(revealed), encoding="utf-8")
+ pub = runs(notebook, [("protocolith disclose --policy policy.json --out public.jsonl", ["disclose", "--policy", "policy.json", "--out", "public.jsonl"]), ("protocolith verify-disclosure public.jsonl", ["verify-disclosure", "public.jsonl"]), ("protocolith verify-disclosure public.jsonl --reveal entry.json", ["verify-disclosure", "public.jsonl", "--reveal", "entry.json"])])
+ chapters.append(("5 Publish only what you choose; the chain proves nothing was dropped", pub))
+ return chapters
+
+
+def build_story(chapters: list[tuple[str, list[tuple[str, list[str], int]]]], font: ImageFont.FreeTypeFont) -> tuple[list[Image.Image], list[int]]:
+ frames: list[Image.Image] = []
+ delays: list[int] = []
+ white, amber, grey = TEXT, PROMPT, DIM
+ for img, delay in (
+ (card([("Protocolith", 48, white), ("Freeze the protocol. Record the result.", 22, amber), ("Verify the history.", 22, amber)]), 2600),
+ (card([("A result is easy to believe", 24, white), ("and hard to check when", 24, white), ("the protocol was written after the run,", 20, grey), ("the history was edited,", 20, grey), ("or a failed run quietly disappeared.", 20, grey)]), 4200),
+ ):
+ frames.append(img)
+ delays.append(delay)
+ for caption, steps in chapters:
+ rows: list[tuple[str, tuple[int, int, int]]] = []
+
+ def add(delay: int, cursor: bool = False) -> None:
+ img = frame(font, rows, cursor, caption)
+ if frames and list(img.getdata()) == list(frames[-1].getdata()):
+ delays[-1] += delay
+ return
+ frames.append(img)
+ delays.append(delay)
+
+ add(900)
+ for index, (shown, out, code) in enumerate(steps):
+ for n in range(0, len(shown) + 1, 4):
+ rows.append(("$ " + shown[:n], TEXT))
+ add(35, cursor=True)
+ rows.pop()
+ rows.append(("$ " + shown, TEXT))
+ add(300)
+ for line in out:
+ rows.append((line if len(line) <= 90 else line[:87] + "...", colour(line, code)))
+ add(60)
+ if code != 0:
+ rows.append((f"exit code {code}", BAD))
+ add(1500 if index == len(steps) - 1 else 900)
+ add(1200)
+ frames.append(card([("pip install protocolith", 30, amber), ("No dependencies. Runs offline. For people and AI agents.", 18, white), ("protocolith.github.io", 22, white), ("github.com/Protocolith/protocolith", 18, grey)]))
+ delays.append(5200)
+ return frames, delays
+
+
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
parser.add_argument("--out", default=None)
- parser.add_argument("--scenario", choices=("ledger", "anchor"), default="ledger")
+ parser.add_argument("--scenario", choices=("ledger", "anchor", "disclose", "story"), default="ledger")
parser.add_argument("--font", default=None, help="path to a monospace font")
args = parser.parse_args()
if args.font:
@@ -187,11 +319,20 @@ def main() -> int:
work = Path(tmp)
for name in ("protocol.json", "record.json", "results.txt"):
shutil.copy(ROOT / "examples" / "quickstart" / name, work / name)
- steps = anchor_script(work) if args.scenario == "anchor" else script(work)
- frames, delays = build(steps, font)
- palette = frames[0].quantize(colors=48, method=Image.Quantize.MEDIANCUT)
+ if args.scenario == "story":
+ notebook = Path(tmp) / "notebook"
+ notebook.mkdir()
+ frames, delays = build_story(story_chapters(work, notebook), font)
+ else:
+ steps = {"anchor": anchor_script, "disclose": disclose_script}.get(args.scenario, script)(work)
+ frames, delays = build(steps, font)
+ sample = frames[:: max(1, len(frames) // 6)][:6]
+ mosaic = Image.new("RGB", (WIDTH, HEIGHT * len(sample)))
+ for number, shot in enumerate(sample):
+ mosaic.paste(shot, (0, number * HEIGHT))
+ palette = mosaic.quantize(colors=64, method=Image.Quantize.MEDIANCUT)
quantized = [f.quantize(palette=palette, dither=Image.Dither.NONE) for f in frames]
- default_name = "anchor-demo.gif" if args.scenario == "anchor" else "demo.gif"
+ default_name = {"anchor": "anchor-demo.gif", "disclose": "disclosure-demo.gif", "story": "protocolith-story.gif"}.get(args.scenario, "demo.gif")
out = Path(args.out) if args.out else ROOT / "docs" / "assets" / "protocolith" / default_name
quantized[0].save(out, save_all=True, append_images=quantized[1:], duration=delays, loop=0, optimize=True, disposal=1)
print(f"wrote {out} frames={len(frames)} bytes={out.stat().st_size}")
diff --git a/scripts/build_disclosure_demo.py b/scripts/build_disclosure_demo.py
new file mode 100644
index 000000000..6689a5e96
--- /dev/null
+++ b/scripts/build_disclosure_demo.py
@@ -0,0 +1,131 @@
+#!/usr/bin/env python3
+"""Build examples/selective_disclosure/: a private notebook ledger, its visibility policy, the public disclosure and atlas.
+
+Everything is synthetic and deterministic (fixed clock). The private ledger is built in a temporary directory and is NOT
+committed; what is committed is what a researcher would publish: `policy.json`, `disclosure.jsonl` and `atlas.html`, plus the
+anchor statement (`anchor.txt`) and one revealed entry (`revealed_entry.json`) so that the verification commands in the README
+can be run as they are.
+
+ python3 scripts/build_disclosure_demo.py # needs protocolith importable (pip install -e . or PYTHONPATH=src)
+"""
+
+from __future__ import annotations
+
+import json
+import shutil
+import tempfile
+from pathlib import Path
+
+from protocolith.core import (
+ Store,
+ anchor_head,
+ build_atlas,
+ build_disclosure,
+ deviation,
+ entries,
+ freeze,
+ issue,
+ load_policy,
+ record,
+ sha256_hex,
+)
+from protocolith.core.atlas import write_atlas
+
+ROOT = Path(__file__).resolve().parent.parent
+OUT = ROOT / "examples" / "selective_disclosure"
+HASH = "c" * 64
+CARD = {
+ "operator": "demo operator",
+ "official_source_name": "Synthetic notebook",
+ "official_source_url": "https://example.org/notebook",
+ "domain": "synthetic research",
+ "claim_type": "source_audit",
+ "access_date": "2026-11-09",
+ "source_rights_note": "Synthetic data written for this demonstration.",
+ "raw_payload_manifest": "No raw payload committed.",
+ "sanitized_report_path": "examples/selective_disclosure/README.md",
+ "sanitized_report_sha256": HASH,
+ "git_commit": "none",
+ "runner_command": "manual",
+ "verification_count": 1,
+ "verification_level": "SINGLE_OPERATOR",
+ "execution_mode": "MANUAL_NO_AI",
+ "ai_assistance": "not used",
+ "manual_review": "Synthetic.",
+ "known_limitations": ["Synthetic demonstration."],
+ "baseline_control_summary": "Baseline: none.",
+ "public_claim_text": "Synthetic demonstration claim.",
+ "public_claim_verbatim_quote": "Synthetic demonstration claim.",
+ "public_claim_source_url": "https://example.org/notebook",
+ "public_claim_locator": "section 1, paragraph 2",
+ "public_claim_captured_at": "2026-11-09",
+ "public_claim_source_sha256": HASH,
+}
+FAMILIES = {
+ "SWEEP_MOMENTUM": ("parameter sweep, 12 settings", "private exploratory work", 12),
+ "SWEEP_SPREADS": ("parameter sweep, 8 settings", "private exploratory work", 8),
+ "STUDY_ROBUSTNESS": ("robustness study", "published as a summary", 4),
+ "PAPER_CLAIM": ("the claim in the paper", "published in full", 1),
+}
+STATUSES = ("NEGATIVE_RESULT_UNDER_PROTOCOL", "NEGATIVE_RESULT_UNDER_PROTOCOL", "PASSED_UNDER_PROTOCOL")
+
+
+def tick(index: int) -> object:
+ stamp = f"2026-11-{10 + index // 24:02d}T{index % 24:02d}:00:00Z"
+ return lambda: stamp
+
+
+def build_private(store: Store) -> None:
+ """A notebook of 25 experiments across four protocols; most of them are not meant to be published."""
+ step = 0
+ for name, (question, _, runs) in FAMILIES.items():
+ body = {"gate": f"{name}: gate fixed before the runs", "protocol_id": name, "question": question, "version": "1"}
+ freeze(store, body, clock=tick(step)) # type: ignore[arg-type]
+ step += 1
+ for run in range(runs):
+ status = "PASSED_UNDER_PROTOCOL" if name == "PAPER_CLAIM" else STATUSES[(run * 7 + len(name)) % 3]
+ entry = {
+ "protocol_sha256": sha256_hex(body),
+ "run_id": f"run-{run + 1:02d}",
+ "status": status,
+ "outcome": {"setting": str(run + 1), "metric": f"0.{(run * 37) % 100:02d}"},
+ "sources": [{"id": "results.csv", "sha256": HASH}],
+ "reproduction_level": "not independently reproduced",
+ "claim_boundary": f"{name}, setting {run + 1} only.",
+ "deviations": [],
+ "card": CARD,
+ }
+ record(store, entry, clock=tick(step)) # type: ignore[arg-type]
+ step += 1
+ deviation(
+ store,
+ {"protocol_sha256": sha256_hex({"gate": "STUDY_ROBUSTNESS: gate fixed before the runs", "protocol_id": "STUDY_ROBUSTNESS", "question": "robustness study", "version": "1"}), "kind": "note", "description": "one setting re-run after a crash"},
+ clock=tick(step), # type: ignore[arg-type]
+ )
+ issue(store, len(entries(store)) - 2, clock=tick(step + 1)) # type: ignore[arg-type]
+
+
+def main() -> int:
+ if OUT.exists():
+ shutil.rmtree(OUT / "public", ignore_errors=True)
+ (OUT / "public").mkdir(parents=True, exist_ok=True)
+ policy_path = OUT / "policy.json"
+ with tempfile.TemporaryDirectory() as tmp:
+ store = Store(Path(tmp) / ".protocolith")
+ build_private(store)
+ anchor_head(store, clock=tick(90), write_head=OUT / "public" / "anchor.txt") # type: ignore[arg-type]
+ policy = load_policy(policy_path)
+ found = build_disclosure(store, policy)
+ (OUT / "public" / "disclosure.jsonl").write_bytes(found.data)
+ page = build_atlas(store=store, policy=policy, title="Synthetic notebook (published view)")
+ write_atlas(page, OUT / "public" / "atlas.html")
+ ledger = entries(store)
+ revealed = next(e for e in ledger if e["type"] == "record" and e["body"]["run_id"] == "run-03" and 13 < e["seq"] < 22)
+ (OUT / "public" / "revealed_entry.json").write_text(json.dumps(revealed, indent=1) + "\n", encoding="utf-8")
+ print(f"entries={len(ledger)} counts={found.counts} head={found.head_hash}")
+ print(f"revealed entry seq={revealed['seq']}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/build_docs_site.py b/scripts/build_docs_site.py
index c287a8d60..8c6c98704 100644
--- a/scripts/build_docs_site.py
+++ b/scripts/build_docs_site.py
@@ -61,6 +61,8 @@
"docs/guides/anchoring-the-head.md": "guides-anchoring-the-head.md",
"docs/guides/anchor-your-results.md": "guides-anchor-your-results.md",
"docs/guides/atlas.md": "guides-atlas.md",
+ "docs/guides/selective-disclosure.md": "guides-selective-disclosure.md",
+ "examples/selective_disclosure/README.md": "examples-selective-disclosure.md",
"docs/spec/CORE_SPEC.md": "spec-core.md",
"docs/reference/error-codes.md": "reference-error-codes.md",
"docs/reference/mcp.md": "reference-mcp.md",
diff --git a/spec/vectors/disclosures.json b/spec/vectors/disclosures.json
new file mode 100644
index 000000000..027021f10
--- /dev/null
+++ b/spec/vectors/disclosures.json
@@ -0,0 +1,106 @@
+{
+ "format": "protocolith-vectors/1",
+ "kind": "disclosures",
+ "description": "A disclosure file (JSON Lines text): verify its structure, hash chain and full entries; expect ok and the sorted unique codes. Cases that carry a ledger and a policy are what that policy must produce from that ledger, byte for byte.",
+ "cases": [
+ {
+ "name": "all_full",
+ "ledger": "{\"body\":{\"protocol\":{\"gate\":\"pass rate at least 0.5\",\"protocol_id\":\"DEMO_D001\",\"version\":\"1\"},\"protocol_id\":\"DEMO_D001\",\"protocol_sha256\":\"d1b0699b7c60eef84a25c4c4ea46eb3f0929f1d763da995cb5451ffd57e3dc59\",\"supersedes\":null,\"version\":\"1\"},\"hash\":\"30018355354515e5a02bba0b342bd6db6b9df53db093f13367cef8b53657e368\",\"prev\":\"0000000000000000000000000000000000000000000000000000000000000000\",\"seq\":0,\"ts\":\"2026-11-15T10:00:00Z\",\"type\":\"freeze\",\"v\":1}\n{\"body\":{\"description\":\"The source moved to a new URL.\",\"kind\":\"source_change\",\"protocol_sha256\":\"d1b0699b7c60eef84a25c4c4ea46eb3f0929f1d763da995cb5451ffd57e3dc59\"},\"hash\":\"d7c1e96be0197a09e835df5e6d0e83072517a9ff95a36a5c9721ecd36bf0535a\",\"prev\":\"30018355354515e5a02bba0b342bd6db6b9df53db093f13367cef8b53657e368\",\"seq\":1,\"ts\":\"2026-11-15T10:00:01Z\",\"type\":\"deviation\",\"v\":1}\n{\"body\":{\"card\":{\"access_date\":\"2026-11-15\",\"ai_assistance\":\"not used\",\"baseline_control_summary\":\"Baseline: previous value, pass rate 0.50.\",\"claim_type\":\"source_audit\",\"domain\":\"demo\",\"execution_mode\":\"MANUAL_NO_AI\",\"git_commit\":\"abc1234\",\"known_limitations\":[\"Single operator.\"],\"manual_review\":\"Reviewed by the operator.\",\"official_source_name\":\"Demo source\",\"official_source_url\":\"https://example.org/data\",\"operator\":\"local operator\",\"public_claim_captured_at\":\"2026-11-15\",\"public_claim_locator\":\"section 1, paragraph 2\",\"public_claim_source_sha256\":\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\",\"public_claim_source_url\":\"https://example.org/data\",\"public_claim_text\":\"The demo source publishes a statement about demo data.\",\"public_claim_verbatim_quote\":\"A verbatim quote of the demo statement.\",\"raw_payload_manifest\":\"No raw payload committed.\",\"runner_command\":\"manual\",\"sanitized_report_path\":\"artifacts/demo_report.json\",\"sanitized_report_sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"source_rights_note\":\"Public page, no raw payload stored.\",\"verification_count\":1,\"verification_level\":\"SINGLE_OPERATOR\"},\"claim_boundary\":\"Only the stated gate on the stated source and period.\",\"deviations\":[1],\"outcome\":{\"pass_rate\":\"0.55\"},\"protocol_sha256\":\"d1b0699b7c60eef84a25c4c4ea46eb3f0929f1d763da995cb5451ffd57e3dc59\",\"reproduction_level\":\"not independently reproduced\",\"run_id\":\"run-1\",\"sources\":[{\"id\":\"source-1\",\"sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}],\"status\":\"PASSED_UNDER_PROTOCOL\"},\"hash\":\"71196aa787cb1c1750e817fec5ceb20e39bd0c9c134c79d8f94cbca51bc7c0fe\",\"prev\":\"d7c1e96be0197a09e835df5e6d0e83072517a9ff95a36a5c9721ecd36bf0535a\",\"seq\":2,\"ts\":\"2026-11-15T10:00:02Z\",\"type\":\"record\",\"v\":1}\n{\"body\":{\"card_sha256\":\"66c1bebddea67d219a1039021da85801beae4c5ae10571ab16bdae3782515c6d\",\"format\":\"evidence-card-json-svg\",\"record_seq\":2},\"hash\":\"de555c70f979a262c861f29b5d61af5e37572e69cf6924e32abf5b0394f90c58\",\"prev\":\"71196aa787cb1c1750e817fec5ceb20e39bd0c9c134c79d8f94cbca51bc7c0fe\",\"seq\":3,\"ts\":\"2026-11-15T10:00:03Z\",\"type\":\"issue\",\"v\":1}\n",
+ "policy": {
+ "default": "full"
+ },
+ "disclosure": "{\"counts\":{\"full\":4,\"hidden\":0,\"summary\":0},\"entries\":4,\"head_hash\":\"de555c70f979a262c861f29b5d61af5e37572e69cf6924e32abf5b0394f90c58\",\"head_seq\":3,\"kind\":\"protocolith-disclosure\",\"v\":1}\n{\"entry\":{\"body\":{\"protocol\":{\"gate\":\"pass rate at least 0.5\",\"protocol_id\":\"DEMO_D001\",\"version\":\"1\"},\"protocol_id\":\"DEMO_D001\",\"protocol_sha256\":\"d1b0699b7c60eef84a25c4c4ea46eb3f0929f1d763da995cb5451ffd57e3dc59\",\"supersedes\":null,\"version\":\"1\"},\"hash\":\"30018355354515e5a02bba0b342bd6db6b9df53db093f13367cef8b53657e368\",\"prev\":\"0000000000000000000000000000000000000000000000000000000000000000\",\"seq\":0,\"ts\":\"2026-11-15T10:00:00Z\",\"type\":\"freeze\",\"v\":1},\"level\":\"full\",\"seq\":0}\n{\"entry\":{\"body\":{\"description\":\"The source moved to a new URL.\",\"kind\":\"source_change\",\"protocol_sha256\":\"d1b0699b7c60eef84a25c4c4ea46eb3f0929f1d763da995cb5451ffd57e3dc59\"},\"hash\":\"d7c1e96be0197a09e835df5e6d0e83072517a9ff95a36a5c9721ecd36bf0535a\",\"prev\":\"30018355354515e5a02bba0b342bd6db6b9df53db093f13367cef8b53657e368\",\"seq\":1,\"ts\":\"2026-11-15T10:00:01Z\",\"type\":\"deviation\",\"v\":1},\"level\":\"full\",\"seq\":1}\n{\"entry\":{\"body\":{\"card\":{\"access_date\":\"2026-11-15\",\"ai_assistance\":\"not used\",\"baseline_control_summary\":\"Baseline: previous value, pass rate 0.50.\",\"claim_type\":\"source_audit\",\"domain\":\"demo\",\"execution_mode\":\"MANUAL_NO_AI\",\"git_commit\":\"abc1234\",\"known_limitations\":[\"Single operator.\"],\"manual_review\":\"Reviewed by the operator.\",\"official_source_name\":\"Demo source\",\"official_source_url\":\"https://example.org/data\",\"operator\":\"local operator\",\"public_claim_captured_at\":\"2026-11-15\",\"public_claim_locator\":\"section 1, paragraph 2\",\"public_claim_source_sha256\":\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\",\"public_claim_source_url\":\"https://example.org/data\",\"public_claim_text\":\"The demo source publishes a statement about demo data.\",\"public_claim_verbatim_quote\":\"A verbatim quote of the demo statement.\",\"raw_payload_manifest\":\"No raw payload committed.\",\"runner_command\":\"manual\",\"sanitized_report_path\":\"artifacts/demo_report.json\",\"sanitized_report_sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"source_rights_note\":\"Public page, no raw payload stored.\",\"verification_count\":1,\"verification_level\":\"SINGLE_OPERATOR\"},\"claim_boundary\":\"Only the stated gate on the stated source and period.\",\"deviations\":[1],\"outcome\":{\"pass_rate\":\"0.55\"},\"protocol_sha256\":\"d1b0699b7c60eef84a25c4c4ea46eb3f0929f1d763da995cb5451ffd57e3dc59\",\"reproduction_level\":\"not independently reproduced\",\"run_id\":\"run-1\",\"sources\":[{\"id\":\"source-1\",\"sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}],\"status\":\"PASSED_UNDER_PROTOCOL\"},\"hash\":\"71196aa787cb1c1750e817fec5ceb20e39bd0c9c134c79d8f94cbca51bc7c0fe\",\"prev\":\"d7c1e96be0197a09e835df5e6d0e83072517a9ff95a36a5c9721ecd36bf0535a\",\"seq\":2,\"ts\":\"2026-11-15T10:00:02Z\",\"type\":\"record\",\"v\":1},\"level\":\"full\",\"seq\":2}\n{\"entry\":{\"body\":{\"card_sha256\":\"66c1bebddea67d219a1039021da85801beae4c5ae10571ab16bdae3782515c6d\",\"format\":\"evidence-card-json-svg\",\"record_seq\":2},\"hash\":\"de555c70f979a262c861f29b5d61af5e37572e69cf6924e32abf5b0394f90c58\",\"prev\":\"71196aa787cb1c1750e817fec5ceb20e39bd0c9c134c79d8f94cbca51bc7c0fe\",\"seq\":3,\"ts\":\"2026-11-15T10:00:03Z\",\"type\":\"issue\",\"v\":1},\"level\":\"full\",\"seq\":3}\n",
+ "expect": {
+ "ok": true,
+ "codes": [],
+ "counts": {
+ "full": 4,
+ "summary": 0,
+ "hidden": 0
+ }
+ }
+ },
+ {
+ "name": "all_summary",
+ "ledger": "{\"body\":{\"protocol\":{\"gate\":\"pass rate at least 0.5\",\"protocol_id\":\"DEMO_D001\",\"version\":\"1\"},\"protocol_id\":\"DEMO_D001\",\"protocol_sha256\":\"d1b0699b7c60eef84a25c4c4ea46eb3f0929f1d763da995cb5451ffd57e3dc59\",\"supersedes\":null,\"version\":\"1\"},\"hash\":\"30018355354515e5a02bba0b342bd6db6b9df53db093f13367cef8b53657e368\",\"prev\":\"0000000000000000000000000000000000000000000000000000000000000000\",\"seq\":0,\"ts\":\"2026-11-15T10:00:00Z\",\"type\":\"freeze\",\"v\":1}\n{\"body\":{\"description\":\"The source moved to a new URL.\",\"kind\":\"source_change\",\"protocol_sha256\":\"d1b0699b7c60eef84a25c4c4ea46eb3f0929f1d763da995cb5451ffd57e3dc59\"},\"hash\":\"d7c1e96be0197a09e835df5e6d0e83072517a9ff95a36a5c9721ecd36bf0535a\",\"prev\":\"30018355354515e5a02bba0b342bd6db6b9df53db093f13367cef8b53657e368\",\"seq\":1,\"ts\":\"2026-11-15T10:00:01Z\",\"type\":\"deviation\",\"v\":1}\n{\"body\":{\"card\":{\"access_date\":\"2026-11-15\",\"ai_assistance\":\"not used\",\"baseline_control_summary\":\"Baseline: previous value, pass rate 0.50.\",\"claim_type\":\"source_audit\",\"domain\":\"demo\",\"execution_mode\":\"MANUAL_NO_AI\",\"git_commit\":\"abc1234\",\"known_limitations\":[\"Single operator.\"],\"manual_review\":\"Reviewed by the operator.\",\"official_source_name\":\"Demo source\",\"official_source_url\":\"https://example.org/data\",\"operator\":\"local operator\",\"public_claim_captured_at\":\"2026-11-15\",\"public_claim_locator\":\"section 1, paragraph 2\",\"public_claim_source_sha256\":\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\",\"public_claim_source_url\":\"https://example.org/data\",\"public_claim_text\":\"The demo source publishes a statement about demo data.\",\"public_claim_verbatim_quote\":\"A verbatim quote of the demo statement.\",\"raw_payload_manifest\":\"No raw payload committed.\",\"runner_command\":\"manual\",\"sanitized_report_path\":\"artifacts/demo_report.json\",\"sanitized_report_sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"source_rights_note\":\"Public page, no raw payload stored.\",\"verification_count\":1,\"verification_level\":\"SINGLE_OPERATOR\"},\"claim_boundary\":\"Only the stated gate on the stated source and period.\",\"deviations\":[1],\"outcome\":{\"pass_rate\":\"0.55\"},\"protocol_sha256\":\"d1b0699b7c60eef84a25c4c4ea46eb3f0929f1d763da995cb5451ffd57e3dc59\",\"reproduction_level\":\"not independently reproduced\",\"run_id\":\"run-1\",\"sources\":[{\"id\":\"source-1\",\"sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}],\"status\":\"PASSED_UNDER_PROTOCOL\"},\"hash\":\"71196aa787cb1c1750e817fec5ceb20e39bd0c9c134c79d8f94cbca51bc7c0fe\",\"prev\":\"d7c1e96be0197a09e835df5e6d0e83072517a9ff95a36a5c9721ecd36bf0535a\",\"seq\":2,\"ts\":\"2026-11-15T10:00:02Z\",\"type\":\"record\",\"v\":1}\n{\"body\":{\"card_sha256\":\"66c1bebddea67d219a1039021da85801beae4c5ae10571ab16bdae3782515c6d\",\"format\":\"evidence-card-json-svg\",\"record_seq\":2},\"hash\":\"de555c70f979a262c861f29b5d61af5e37572e69cf6924e32abf5b0394f90c58\",\"prev\":\"71196aa787cb1c1750e817fec5ceb20e39bd0c9c134c79d8f94cbca51bc7c0fe\",\"seq\":3,\"ts\":\"2026-11-15T10:00:03Z\",\"type\":\"issue\",\"v\":1}\n",
+ "policy": {
+ "default": "summary"
+ },
+ "disclosure": "{\"counts\":{\"full\":0,\"hidden\":0,\"summary\":4},\"entries\":4,\"head_hash\":\"de555c70f979a262c861f29b5d61af5e37572e69cf6924e32abf5b0394f90c58\",\"head_seq\":3,\"kind\":\"protocolith-disclosure\",\"v\":1}\n{\"hash\":\"30018355354515e5a02bba0b342bd6db6b9df53db093f13367cef8b53657e368\",\"level\":\"summary\",\"prev\":\"0000000000000000000000000000000000000000000000000000000000000000\",\"seq\":0,\"summary\":{\"protocol_id\":\"DEMO_D001\",\"version\":\"1\"},\"ts\":\"2026-11-15T10:00:00Z\",\"type\":\"freeze\"}\n{\"hash\":\"d7c1e96be0197a09e835df5e6d0e83072517a9ff95a36a5c9721ecd36bf0535a\",\"level\":\"summary\",\"prev\":\"30018355354515e5a02bba0b342bd6db6b9df53db093f13367cef8b53657e368\",\"seq\":1,\"summary\":{\"protocol_id\":\"DEMO_D001\"},\"ts\":\"2026-11-15T10:00:01Z\",\"type\":\"deviation\"}\n{\"hash\":\"71196aa787cb1c1750e817fec5ceb20e39bd0c9c134c79d8f94cbca51bc7c0fe\",\"level\":\"summary\",\"prev\":\"d7c1e96be0197a09e835df5e6d0e83072517a9ff95a36a5c9721ecd36bf0535a\",\"seq\":2,\"summary\":{\"claim_boundary\":\"Only the stated gate on the stated source and period.\",\"protocol_id\":\"DEMO_D001\",\"reproduction_level\":\"not independently reproduced\",\"status\":\"PASSED_UNDER_PROTOCOL\"},\"ts\":\"2026-11-15T10:00:02Z\",\"type\":\"record\"}\n{\"hash\":\"de555c70f979a262c861f29b5d61af5e37572e69cf6924e32abf5b0394f90c58\",\"level\":\"summary\",\"prev\":\"71196aa787cb1c1750e817fec5ceb20e39bd0c9c134c79d8f94cbca51bc7c0fe\",\"seq\":3,\"summary\":{\"protocol_id\":\"DEMO_D001\",\"record_seq\":2},\"ts\":\"2026-11-15T10:00:03Z\",\"type\":\"issue\"}\n",
+ "expect": {
+ "ok": true,
+ "codes": [],
+ "counts": {
+ "full": 0,
+ "summary": 4,
+ "hidden": 0
+ }
+ }
+ },
+ {
+ "name": "all_hidden",
+ "ledger": "{\"body\":{\"protocol\":{\"gate\":\"pass rate at least 0.5\",\"protocol_id\":\"DEMO_D001\",\"version\":\"1\"},\"protocol_id\":\"DEMO_D001\",\"protocol_sha256\":\"d1b0699b7c60eef84a25c4c4ea46eb3f0929f1d763da995cb5451ffd57e3dc59\",\"supersedes\":null,\"version\":\"1\"},\"hash\":\"30018355354515e5a02bba0b342bd6db6b9df53db093f13367cef8b53657e368\",\"prev\":\"0000000000000000000000000000000000000000000000000000000000000000\",\"seq\":0,\"ts\":\"2026-11-15T10:00:00Z\",\"type\":\"freeze\",\"v\":1}\n{\"body\":{\"description\":\"The source moved to a new URL.\",\"kind\":\"source_change\",\"protocol_sha256\":\"d1b0699b7c60eef84a25c4c4ea46eb3f0929f1d763da995cb5451ffd57e3dc59\"},\"hash\":\"d7c1e96be0197a09e835df5e6d0e83072517a9ff95a36a5c9721ecd36bf0535a\",\"prev\":\"30018355354515e5a02bba0b342bd6db6b9df53db093f13367cef8b53657e368\",\"seq\":1,\"ts\":\"2026-11-15T10:00:01Z\",\"type\":\"deviation\",\"v\":1}\n{\"body\":{\"card\":{\"access_date\":\"2026-11-15\",\"ai_assistance\":\"not used\",\"baseline_control_summary\":\"Baseline: previous value, pass rate 0.50.\",\"claim_type\":\"source_audit\",\"domain\":\"demo\",\"execution_mode\":\"MANUAL_NO_AI\",\"git_commit\":\"abc1234\",\"known_limitations\":[\"Single operator.\"],\"manual_review\":\"Reviewed by the operator.\",\"official_source_name\":\"Demo source\",\"official_source_url\":\"https://example.org/data\",\"operator\":\"local operator\",\"public_claim_captured_at\":\"2026-11-15\",\"public_claim_locator\":\"section 1, paragraph 2\",\"public_claim_source_sha256\":\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\",\"public_claim_source_url\":\"https://example.org/data\",\"public_claim_text\":\"The demo source publishes a statement about demo data.\",\"public_claim_verbatim_quote\":\"A verbatim quote of the demo statement.\",\"raw_payload_manifest\":\"No raw payload committed.\",\"runner_command\":\"manual\",\"sanitized_report_path\":\"artifacts/demo_report.json\",\"sanitized_report_sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"source_rights_note\":\"Public page, no raw payload stored.\",\"verification_count\":1,\"verification_level\":\"SINGLE_OPERATOR\"},\"claim_boundary\":\"Only the stated gate on the stated source and period.\",\"deviations\":[1],\"outcome\":{\"pass_rate\":\"0.55\"},\"protocol_sha256\":\"d1b0699b7c60eef84a25c4c4ea46eb3f0929f1d763da995cb5451ffd57e3dc59\",\"reproduction_level\":\"not independently reproduced\",\"run_id\":\"run-1\",\"sources\":[{\"id\":\"source-1\",\"sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}],\"status\":\"PASSED_UNDER_PROTOCOL\"},\"hash\":\"71196aa787cb1c1750e817fec5ceb20e39bd0c9c134c79d8f94cbca51bc7c0fe\",\"prev\":\"d7c1e96be0197a09e835df5e6d0e83072517a9ff95a36a5c9721ecd36bf0535a\",\"seq\":2,\"ts\":\"2026-11-15T10:00:02Z\",\"type\":\"record\",\"v\":1}\n{\"body\":{\"card_sha256\":\"66c1bebddea67d219a1039021da85801beae4c5ae10571ab16bdae3782515c6d\",\"format\":\"evidence-card-json-svg\",\"record_seq\":2},\"hash\":\"de555c70f979a262c861f29b5d61af5e37572e69cf6924e32abf5b0394f90c58\",\"prev\":\"71196aa787cb1c1750e817fec5ceb20e39bd0c9c134c79d8f94cbca51bc7c0fe\",\"seq\":3,\"ts\":\"2026-11-15T10:00:03Z\",\"type\":\"issue\",\"v\":1}\n",
+ "policy": {},
+ "disclosure": "{\"counts\":{\"full\":0,\"hidden\":4,\"summary\":0},\"entries\":4,\"head_hash\":\"de555c70f979a262c861f29b5d61af5e37572e69cf6924e32abf5b0394f90c58\",\"head_seq\":3,\"kind\":\"protocolith-disclosure\",\"v\":1}\n{\"hash\":\"30018355354515e5a02bba0b342bd6db6b9df53db093f13367cef8b53657e368\",\"level\":\"hidden\",\"prev\":\"0000000000000000000000000000000000000000000000000000000000000000\",\"seq\":0}\n{\"hash\":\"d7c1e96be0197a09e835df5e6d0e83072517a9ff95a36a5c9721ecd36bf0535a\",\"level\":\"hidden\",\"prev\":\"30018355354515e5a02bba0b342bd6db6b9df53db093f13367cef8b53657e368\",\"seq\":1}\n{\"hash\":\"71196aa787cb1c1750e817fec5ceb20e39bd0c9c134c79d8f94cbca51bc7c0fe\",\"level\":\"hidden\",\"prev\":\"d7c1e96be0197a09e835df5e6d0e83072517a9ff95a36a5c9721ecd36bf0535a\",\"seq\":2}\n{\"hash\":\"de555c70f979a262c861f29b5d61af5e37572e69cf6924e32abf5b0394f90c58\",\"level\":\"hidden\",\"prev\":\"71196aa787cb1c1750e817fec5ceb20e39bd0c9c134c79d8f94cbca51bc7c0fe\",\"seq\":3}\n",
+ "expect": {
+ "ok": true,
+ "codes": [],
+ "counts": {
+ "full": 0,
+ "summary": 0,
+ "hidden": 4
+ }
+ }
+ },
+ {
+ "name": "mixed",
+ "ledger": "{\"body\":{\"protocol\":{\"gate\":\"pass rate at least 0.5\",\"protocol_id\":\"DEMO_D001\",\"version\":\"1\"},\"protocol_id\":\"DEMO_D001\",\"protocol_sha256\":\"d1b0699b7c60eef84a25c4c4ea46eb3f0929f1d763da995cb5451ffd57e3dc59\",\"supersedes\":null,\"version\":\"1\"},\"hash\":\"30018355354515e5a02bba0b342bd6db6b9df53db093f13367cef8b53657e368\",\"prev\":\"0000000000000000000000000000000000000000000000000000000000000000\",\"seq\":0,\"ts\":\"2026-11-15T10:00:00Z\",\"type\":\"freeze\",\"v\":1}\n{\"body\":{\"description\":\"The source moved to a new URL.\",\"kind\":\"source_change\",\"protocol_sha256\":\"d1b0699b7c60eef84a25c4c4ea46eb3f0929f1d763da995cb5451ffd57e3dc59\"},\"hash\":\"d7c1e96be0197a09e835df5e6d0e83072517a9ff95a36a5c9721ecd36bf0535a\",\"prev\":\"30018355354515e5a02bba0b342bd6db6b9df53db093f13367cef8b53657e368\",\"seq\":1,\"ts\":\"2026-11-15T10:00:01Z\",\"type\":\"deviation\",\"v\":1}\n{\"body\":{\"card\":{\"access_date\":\"2026-11-15\",\"ai_assistance\":\"not used\",\"baseline_control_summary\":\"Baseline: previous value, pass rate 0.50.\",\"claim_type\":\"source_audit\",\"domain\":\"demo\",\"execution_mode\":\"MANUAL_NO_AI\",\"git_commit\":\"abc1234\",\"known_limitations\":[\"Single operator.\"],\"manual_review\":\"Reviewed by the operator.\",\"official_source_name\":\"Demo source\",\"official_source_url\":\"https://example.org/data\",\"operator\":\"local operator\",\"public_claim_captured_at\":\"2026-11-15\",\"public_claim_locator\":\"section 1, paragraph 2\",\"public_claim_source_sha256\":\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\",\"public_claim_source_url\":\"https://example.org/data\",\"public_claim_text\":\"The demo source publishes a statement about demo data.\",\"public_claim_verbatim_quote\":\"A verbatim quote of the demo statement.\",\"raw_payload_manifest\":\"No raw payload committed.\",\"runner_command\":\"manual\",\"sanitized_report_path\":\"artifacts/demo_report.json\",\"sanitized_report_sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"source_rights_note\":\"Public page, no raw payload stored.\",\"verification_count\":1,\"verification_level\":\"SINGLE_OPERATOR\"},\"claim_boundary\":\"Only the stated gate on the stated source and period.\",\"deviations\":[1],\"outcome\":{\"pass_rate\":\"0.55\"},\"protocol_sha256\":\"d1b0699b7c60eef84a25c4c4ea46eb3f0929f1d763da995cb5451ffd57e3dc59\",\"reproduction_level\":\"not independently reproduced\",\"run_id\":\"run-1\",\"sources\":[{\"id\":\"source-1\",\"sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}],\"status\":\"PASSED_UNDER_PROTOCOL\"},\"hash\":\"71196aa787cb1c1750e817fec5ceb20e39bd0c9c134c79d8f94cbca51bc7c0fe\",\"prev\":\"d7c1e96be0197a09e835df5e6d0e83072517a9ff95a36a5c9721ecd36bf0535a\",\"seq\":2,\"ts\":\"2026-11-15T10:00:02Z\",\"type\":\"record\",\"v\":1}\n{\"body\":{\"card_sha256\":\"66c1bebddea67d219a1039021da85801beae4c5ae10571ab16bdae3782515c6d\",\"format\":\"evidence-card-json-svg\",\"record_seq\":2},\"hash\":\"de555c70f979a262c861f29b5d61af5e37572e69cf6924e32abf5b0394f90c58\",\"prev\":\"71196aa787cb1c1750e817fec5ceb20e39bd0c9c134c79d8f94cbca51bc7c0fe\",\"seq\":3,\"ts\":\"2026-11-15T10:00:03Z\",\"type\":\"issue\",\"v\":1}\n",
+ "policy": {
+ "default": "hidden",
+ "rules": [
+ {
+ "seq": 0,
+ "level": "full"
+ },
+ {
+ "seq": [
+ 1,
+ 2
+ ],
+ "level": "summary"
+ }
+ ]
+ },
+ "disclosure": "{\"counts\":{\"full\":1,\"hidden\":1,\"summary\":2},\"entries\":4,\"head_hash\":\"de555c70f979a262c861f29b5d61af5e37572e69cf6924e32abf5b0394f90c58\",\"head_seq\":3,\"kind\":\"protocolith-disclosure\",\"v\":1}\n{\"entry\":{\"body\":{\"protocol\":{\"gate\":\"pass rate at least 0.5\",\"protocol_id\":\"DEMO_D001\",\"version\":\"1\"},\"protocol_id\":\"DEMO_D001\",\"protocol_sha256\":\"d1b0699b7c60eef84a25c4c4ea46eb3f0929f1d763da995cb5451ffd57e3dc59\",\"supersedes\":null,\"version\":\"1\"},\"hash\":\"30018355354515e5a02bba0b342bd6db6b9df53db093f13367cef8b53657e368\",\"prev\":\"0000000000000000000000000000000000000000000000000000000000000000\",\"seq\":0,\"ts\":\"2026-11-15T10:00:00Z\",\"type\":\"freeze\",\"v\":1},\"level\":\"full\",\"seq\":0}\n{\"hash\":\"d7c1e96be0197a09e835df5e6d0e83072517a9ff95a36a5c9721ecd36bf0535a\",\"level\":\"summary\",\"prev\":\"30018355354515e5a02bba0b342bd6db6b9df53db093f13367cef8b53657e368\",\"seq\":1,\"summary\":{\"protocol_id\":\"DEMO_D001\"},\"ts\":\"2026-11-15T10:00:01Z\",\"type\":\"deviation\"}\n{\"hash\":\"71196aa787cb1c1750e817fec5ceb20e39bd0c9c134c79d8f94cbca51bc7c0fe\",\"level\":\"summary\",\"prev\":\"d7c1e96be0197a09e835df5e6d0e83072517a9ff95a36a5c9721ecd36bf0535a\",\"seq\":2,\"summary\":{\"claim_boundary\":\"Only the stated gate on the stated source and period.\",\"protocol_id\":\"DEMO_D001\",\"reproduction_level\":\"not independently reproduced\",\"status\":\"PASSED_UNDER_PROTOCOL\"},\"ts\":\"2026-11-15T10:00:02Z\",\"type\":\"record\"}\n{\"hash\":\"de555c70f979a262c861f29b5d61af5e37572e69cf6924e32abf5b0394f90c58\",\"level\":\"hidden\",\"prev\":\"71196aa787cb1c1750e817fec5ceb20e39bd0c9c134c79d8f94cbca51bc7c0fe\",\"seq\":3}\n",
+ "expect": {
+ "ok": true,
+ "codes": [],
+ "counts": {
+ "full": 1,
+ "summary": 2,
+ "hidden": 1
+ }
+ }
+ },
+ {
+ "name": "edited_full_entry",
+ "disclosure": "{\"counts\":{\"full\":4,\"hidden\":0,\"summary\":0},\"entries\":4,\"head_hash\":\"de555c70f979a262c861f29b5d61af5e37572e69cf6924e32abf5b0394f90c58\",\"head_seq\":3,\"kind\":\"protocolith-disclosure\",\"v\":1}\n{\"entry\":{\"body\":{\"protocol\":{\"gate\":\"pass rate at least 0.5\",\"protocol_id\":\"DEMO_D001\",\"version\":\"1\"},\"protocol_id\":\"DEMO_D001\",\"protocol_sha256\":\"d1b0699b7c60eef84a25c4c4ea46eb3f0929f1d763da995cb5451ffd57e3dc59\",\"supersedes\":null,\"version\":\"1\"},\"hash\":\"30018355354515e5a02bba0b342bd6db6b9df53db093f13367cef8b53657e368\",\"prev\":\"0000000000000000000000000000000000000000000000000000000000000000\",\"seq\":0,\"ts\":\"2026-11-15T10:00:00Z\",\"type\":\"freeze\",\"v\":1},\"level\":\"full\",\"seq\":0}\n{\"entry\":{\"body\":{\"description\":\"The source moved to a new URL.\",\"kind\":\"source_change\",\"protocol_sha256\":\"d1b0699b7c60eef84a25c4c4ea46eb3f0929f1d763da995cb5451ffd57e3dc59\",\"run_id\":\"edited\"},\"hash\":\"d7c1e96be0197a09e835df5e6d0e83072517a9ff95a36a5c9721ecd36bf0535a\",\"prev\":\"30018355354515e5a02bba0b342bd6db6b9df53db093f13367cef8b53657e368\",\"seq\":1,\"ts\":\"2026-11-15T10:00:01Z\",\"type\":\"deviation\",\"v\":1},\"level\":\"full\",\"seq\":1}\n{\"entry\":{\"body\":{\"card\":{\"access_date\":\"2026-11-15\",\"ai_assistance\":\"not used\",\"baseline_control_summary\":\"Baseline: previous value, pass rate 0.50.\",\"claim_type\":\"source_audit\",\"domain\":\"demo\",\"execution_mode\":\"MANUAL_NO_AI\",\"git_commit\":\"abc1234\",\"known_limitations\":[\"Single operator.\"],\"manual_review\":\"Reviewed by the operator.\",\"official_source_name\":\"Demo source\",\"official_source_url\":\"https://example.org/data\",\"operator\":\"local operator\",\"public_claim_captured_at\":\"2026-11-15\",\"public_claim_locator\":\"section 1, paragraph 2\",\"public_claim_source_sha256\":\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\",\"public_claim_source_url\":\"https://example.org/data\",\"public_claim_text\":\"The demo source publishes a statement about demo data.\",\"public_claim_verbatim_quote\":\"A verbatim quote of the demo statement.\",\"raw_payload_manifest\":\"No raw payload committed.\",\"runner_command\":\"manual\",\"sanitized_report_path\":\"artifacts/demo_report.json\",\"sanitized_report_sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"source_rights_note\":\"Public page, no raw payload stored.\",\"verification_count\":1,\"verification_level\":\"SINGLE_OPERATOR\"},\"claim_boundary\":\"Only the stated gate on the stated source and period.\",\"deviations\":[1],\"outcome\":{\"pass_rate\":\"0.55\"},\"protocol_sha256\":\"d1b0699b7c60eef84a25c4c4ea46eb3f0929f1d763da995cb5451ffd57e3dc59\",\"reproduction_level\":\"not independently reproduced\",\"run_id\":\"run-1\",\"sources\":[{\"id\":\"source-1\",\"sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}],\"status\":\"PASSED_UNDER_PROTOCOL\"},\"hash\":\"71196aa787cb1c1750e817fec5ceb20e39bd0c9c134c79d8f94cbca51bc7c0fe\",\"prev\":\"d7c1e96be0197a09e835df5e6d0e83072517a9ff95a36a5c9721ecd36bf0535a\",\"seq\":2,\"ts\":\"2026-11-15T10:00:02Z\",\"type\":\"record\",\"v\":1},\"level\":\"full\",\"seq\":2}\n{\"entry\":{\"body\":{\"card_sha256\":\"66c1bebddea67d219a1039021da85801beae4c5ae10571ab16bdae3782515c6d\",\"format\":\"evidence-card-json-svg\",\"record_seq\":2},\"hash\":\"de555c70f979a262c861f29b5d61af5e37572e69cf6924e32abf5b0394f90c58\",\"prev\":\"71196aa787cb1c1750e817fec5ceb20e39bd0c9c134c79d8f94cbca51bc7c0fe\",\"seq\":3,\"ts\":\"2026-11-15T10:00:03Z\",\"type\":\"issue\",\"v\":1},\"level\":\"full\",\"seq\":3}\n",
+ "expect": {
+ "ok": false,
+ "codes": [
+ "DISCLOSURE_HASH"
+ ]
+ }
+ },
+ {
+ "name": "dropped_entry",
+ "disclosure": "{\"counts\":{\"full\":0,\"hidden\":0,\"summary\":4},\"entries\":4,\"head_hash\":\"de555c70f979a262c861f29b5d61af5e37572e69cf6924e32abf5b0394f90c58\",\"head_seq\":3,\"kind\":\"protocolith-disclosure\",\"v\":1}\n{\"hash\":\"30018355354515e5a02bba0b342bd6db6b9df53db093f13367cef8b53657e368\",\"level\":\"summary\",\"prev\":\"0000000000000000000000000000000000000000000000000000000000000000\",\"seq\":0,\"summary\":{\"protocol_id\":\"DEMO_D001\",\"version\":\"1\"},\"ts\":\"2026-11-15T10:00:00Z\",\"type\":\"freeze\"}\n{\"hash\":\"71196aa787cb1c1750e817fec5ceb20e39bd0c9c134c79d8f94cbca51bc7c0fe\",\"level\":\"summary\",\"prev\":\"d7c1e96be0197a09e835df5e6d0e83072517a9ff95a36a5c9721ecd36bf0535a\",\"seq\":2,\"summary\":{\"claim_boundary\":\"Only the stated gate on the stated source and period.\",\"protocol_id\":\"DEMO_D001\",\"reproduction_level\":\"not independently reproduced\",\"status\":\"PASSED_UNDER_PROTOCOL\"},\"ts\":\"2026-11-15T10:00:02Z\",\"type\":\"record\"}\n{\"hash\":\"de555c70f979a262c861f29b5d61af5e37572e69cf6924e32abf5b0394f90c58\",\"level\":\"summary\",\"prev\":\"71196aa787cb1c1750e817fec5ceb20e39bd0c9c134c79d8f94cbca51bc7c0fe\",\"seq\":3,\"summary\":{\"protocol_id\":\"DEMO_D001\",\"record_seq\":2},\"ts\":\"2026-11-15T10:00:03Z\",\"type\":\"issue\"}\n",
+ "expect": {
+ "ok": false,
+ "codes": [
+ "BAD_DISCLOSURE"
+ ]
+ }
+ }
+ ]
+}
diff --git a/specs/repo_version.yaml b/specs/repo_version.yaml
index da6461a20..407f30391 100644
--- a/specs/repo_version.yaml
+++ b/specs/repo_version.yaml
@@ -1,3 +1,3 @@
-repo_semver: 0.6.0
+repo_semver: 0.7.0
last_updated: 2026-11-16
status: reviewer_readiness_release
diff --git a/src/protocolith/core/__init__.py b/src/protocolith/core/__init__.py
index b6af0e833..64248aa08 100644
--- a/src/protocolith/core/__init__.py
+++ b/src/protocolith/core/__init__.py
@@ -10,6 +10,7 @@
from .errors import EnvError, InputError, ProtocolithError, VerificationFailed, Violation
from .ledger import MAX_ENTRY_BYTES, RESULT_STATUSES
from .capture import capture
+from .disclosure import Policy, build_disclosure, load_policy, parse_policy, verify_disclosure, verify_reveal
from .ops import (
claim_check,
deviation,
@@ -37,6 +38,7 @@
"EnvError",
"InputError",
"ProtocolithError",
+ "Policy",
"Store",
"Verdict",
"VerificationFailed",
@@ -44,6 +46,7 @@
"Violation",
"anchor_head",
"build_atlas",
+ "build_disclosure",
"capture",
"claim_check",
"decode",
@@ -54,7 +57,9 @@
"head",
"init",
"issue",
+ "load_policy",
"log",
+ "parse_policy",
"now_utc",
"record",
"repair_truncate_partial_tail",
@@ -66,4 +71,6 @@
"summary",
"verify",
"verify_anchors",
+ "verify_disclosure",
+ "verify_reveal",
]
diff --git a/src/protocolith/core/anchor.py b/src/protocolith/core/anchor.py
index 96cd70657..32d36f0be 100644
--- a/src/protocolith/core/anchor.py
+++ b/src/protocolith/core/anchor.py
@@ -18,7 +18,7 @@
import tempfile
import urllib.parse
import urllib.request
-from collections.abc import Callable
+from collections.abc import Callable, Mapping
from dataclasses import dataclass
from pathlib import Path
from typing import Any
@@ -142,7 +142,7 @@ def to_dict(self) -> dict[str, Any]:
}
-def _check_one(directory: Path, path: Path, verifier: Verifier, count: int) -> tuple[int | None, list[Violation]]:
+def _check_one(directory: Path, path: Path, entries: Mapping[int, Mapping[str, Any]], count: int) -> tuple[int | None, list[Violation]]:
"""Problems of one anchor file, and its head_seq when it is clean."""
doc, why = _read_doc(path)
if doc is None:
@@ -161,7 +161,7 @@ def _check_one(directory: Path, path: Path, verifier: Verifier, count: int) -> t
found.append(
Violation("ANCHOR_AHEAD", seq, f"{path.name}: anchored entry {seq} but the ledger has {count} entries: truncated")
)
- elif seq not in verifier.entries or verifier.entries[seq]["hash"] != digest:
+ elif seq not in entries or entries[seq]["hash"] != digest:
found.append(
Violation("ANCHOR_MISMATCH", seq, f"{path.name}: entry {seq} is not the anchored one: the ledger was rewritten")
)
@@ -181,11 +181,20 @@ def _check_tsr(directory: Path, anchor_path: Path, seq: int, method: dict[str, A
def check_anchors(directory: Path, verifier: Verifier, count: int) -> AnchorReport:
"""Check every ``*.json`` file in ``directory`` against a scanned ledger of ``count`` lines."""
+ return _check_all(directory, verifier.entries, count)
+
+
+def check_anchor_hashes(directory: Path, hashes: Mapping[int, str], count: int) -> AnchorReport:
+ """Check every anchor against known entry hashes (a disclosure holds the hash of each entry, not its content)."""
+ return _check_all(directory, {seq: {"hash": digest} for seq, digest in hashes.items()}, count)
+
+
+def _check_all(directory: Path, entries: Mapping[int, Mapping[str, Any]], count: int) -> AnchorReport:
violations: list[Violation] = []
clean: list[int] = []
paths = sorted(directory.glob("*.json"))
for path in paths:
- seq, found = _check_one(directory, path, verifier, count)
+ seq, found = _check_one(directory, path, entries, count)
violations += found
if seq is not None:
clean.append(seq)
diff --git a/src/protocolith/core/atlas.py b/src/protocolith/core/atlas.py
index 836e0b7b6..9ebe5e3d5 100644
--- a/src/protocolith/core/atlas.py
+++ b/src/protocolith/core/atlas.py
@@ -26,6 +26,7 @@
from .errors import EnvError, InputError, ProtocolithError, io_guard
from .issue import _atomic_write, build_card, card_hash
from .rules import Verdict, Verifier, scan
+from .disclosure import LEVELS, Policy, levels_of, summarize_entry
from .store import Store
from .views import protocol_of
@@ -33,6 +34,7 @@
DEFAULT_OUT = "protocolith-atlas.html"
DEFAULT_CARDS_DIR = "docs/evidence_cards"
DATA_VERSION = 1
+HIDDEN_STATUS = "HIDDEN"
MAX_FILE_BYTES = 2_097_152
MAX_STRING = 2000
MAX_ITEMS = 100
@@ -247,15 +249,62 @@ def _ledger_card(verifier: Verifier, seq: int) -> dict[str, Any]:
}
-def _from_ledger(store: Store) -> tuple[list[Pair], dict[str, Any]]:
+def _summary_row(verifier: Verifier, seq: int, policy: Policy) -> Pair:
+ entry = verifier.entries[seq]
+ body = entry["body"]
+ protocol = protocol_of(verifier, entry)
+ shown = summarize_entry(entry, protocol, policy.summary_fields)
+ card = {
+ "claim_boundary": shown.get("claim_boundary"),
+ "created_at": entry["ts"],
+ "evidence_id": f"LEDGER-RECORD-{seq:06d}",
+ "ledger_record_seq": seq,
+ "protocol_id": protocol,
+ "reproduction_level": shown.get("reproduction_level"),
+ "result_status": shown.get("status", body.get("status")),
+ "visibility": "summary",
+ }
+ extra_keys = [k for k in ("outcome", "public_claim_text", "run_id") if k in shown]
+ card.update({key: shown[key] for key in extra_keys})
+ return _row(card, entry["hash"])
+
+
+def _hidden_row(seq: int, digest: str) -> Pair:
+ card = {
+ "evidence_id": f"HIDDEN-{seq:06d}",
+ "ledger_record_seq": seq,
+ "note": "Hidden by the publisher. The hash shown for this record is committed in the published hash chain.",
+ "result_status": HIDDEN_STATUS,
+ "visibility": "hidden",
+ }
+ return _row(card, digest)
+
+
+def _from_ledger(store: Store, policy: Policy | None = None) -> tuple[list[Pair], dict[str, Any], dict[str, Any] | None]:
with io_guard(), store.locked(write=False):
verdict, verifier = scan(store.read(missing_ok=False), card_hash)
- rows = [
- _row(_ledger_card(verifier, seq), verifier.entries[seq]["hash"])
- for seq in sorted(verifier.entries)
- if verifier.entries[seq]["type"] == "record"
- ]
- return rows, _ledger_integrity(verdict)
+ levels = None if policy is None else levels_of(verifier, policy)
+ rows: list[Pair] = []
+ for seq in sorted(verifier.entries):
+ if verifier.entries[seq]["type"] != "record":
+ continue
+ level = "full" if levels is None else levels[seq]
+ if level == "full":
+ rows.append(_row(_ledger_card(verifier, seq), verifier.entries[seq]["hash"]))
+ elif level == "summary":
+ assert policy is not None
+ rows.append(_summary_row(verifier, seq, policy))
+ else:
+ rows.append(_hidden_row(seq, verifier.entries[seq]["hash"]))
+ disclosure = None
+ if levels is not None:
+ disclosure = {
+ "counts": {name: levels.count(name) for name in LEVELS},
+ "head_hash": verdict.head_hash,
+ "head_seq": verdict.head_seq,
+ "kind": "disclosure",
+ }
+ return rows, _ledger_integrity(verdict), disclosure
def _ledger_integrity(verdict: Verdict) -> dict[str, Any]:
@@ -306,6 +355,7 @@ def build_atlas_result(
i18n_dir: str | os.PathLike[str] | None = None,
default_lang: str = "en",
max_rows: int | None = None,
+ policy: Policy | None = None,
) -> AtlasResult:
"""Build the page. With no ``store`` and no ``cards`` a local ledger, else ``docs/evidence_cards``, is used."""
if max_rows is not None and not (type(max_rows) is int and max_rows >= 1):
@@ -316,14 +366,20 @@ def build_atlas_result(
raise InputError(
"BAD_LANG", f"default language {default_lang!r} is not available: " + ", ".join(sorted(languages))
)
+ if policy is not None and cards:
+ raise InputError("BAD_ENTRY", "a visibility policy applies to a ledger; it cannot be combined with card directories")
real_store, folders = _auto_sources(store, cards)
+ if policy is not None and real_store is None:
+ raise InputError("NO_SOURCE", "a visibility policy needs a ledger (--store)")
rows: list[Pair] = []
integrity: list[dict[str, Any]] = []
issues: list[dict[str, str]] = []
ledger = None
if real_store is not None:
- rows, ledger = _from_ledger(real_store)
+ rows, ledger, disclosure = _from_ledger(real_store, policy)
integrity.append(ledger)
+ if disclosure is not None:
+ integrity.append(disclosure)
if folders:
found, issues = _from_cards(folders)
rows += found
diff --git a/src/protocolith/core/atlas_assets/atlas.css b/src/protocolith/core/atlas_assets/atlas.css
index 6d50056f9..8c4ae666b 100644
--- a/src/protocolith/core/atlas_assets/atlas.css
+++ b/src/protocolith/core/atlas_assets/atlas.css
@@ -49,8 +49,9 @@ figcaption{font-weight:600;margin-bottom:6px}
.s-INSUFFICIENT_COVERAGE{color:var(--ins);background:var(--ins-bg)}
.s-SOURCE_DRIFT{color:var(--drf);background:var(--drf-bg)}
.s-REPRODUCED_OUTCOME{color:var(--rep);background:var(--rep-bg)}
+.s-HIDDEN{color:var(--unk);background:repeating-linear-gradient(135deg,var(--unk-bg),var(--unk-bg) 4px,transparent 4px,transparent 8px)}
.s-unknown{color:var(--unk);background:var(--unk-bg)}
-.bar.s-PASSED_UNDER_PROTOCOL,.bar.s-NEGATIVE_RESULT_UNDER_PROTOCOL,.bar.s-BLOCKED_SOURCE,.bar.s-INSUFFICIENT_COVERAGE,.bar.s-SOURCE_DRIFT,.bar.s-REPRODUCED_OUTCOME,.bar.s-unknown{background:var(--panel)}
+.bar.s-PASSED_UNDER_PROTOCOL,.bar.s-NEGATIVE_RESULT_UNDER_PROTOCOL,.bar.s-BLOCKED_SOURCE,.bar.s-INSUFFICIENT_COVERAGE,.bar.s-SOURCE_DRIFT,.bar.s-REPRODUCED_OUTCOME,.bar.s-HIDDEN,.bar.s-unknown{background:var(--panel)}
.filters{display:flex;flex-wrap:wrap;gap:8px;align-items:flex-end;margin:12px auto}
.filters label{display:flex;flex-direction:column;font-size:.8rem;gap:2px}
.filters .grow{flex:1 1 260px}
diff --git a/src/protocolith/core/atlas_assets/atlas.js b/src/protocolith/core/atlas_assets/atlas.js
index 93df8abe6..ba7610fe8 100644
--- a/src/protocolith/core/atlas_assets/atlas.js
+++ b/src/protocolith/core/atlas_assets/atlas.js
@@ -11,7 +11,7 @@
var GLYPH = {
PASSED_UNDER_PROTOCOL: ["\u2713", "P"], NEGATIVE_RESULT_UNDER_PROTOCOL: ["\u2717", "N"],
BLOCKED_SOURCE: ["\u25A0", "B"], INSUFFICIENT_COVERAGE: ["\u25D0", "I"],
- SOURCE_DRIFT: ["\u21AF", "D"], REPRODUCED_OUTCOME: ["\u21BB", "R"]
+ SOURCE_DRIFT: ["\u21AF", "D"], REPRODUCED_OUTCOME: ["\u21BB", "R"], HIDDEN: ["\u25A2", "H"]
};
var ORDER = Object.keys(GLYPH);
var PAGE = 50;
@@ -108,6 +108,8 @@
var b;
if (g.kind === "ledger" && g.ok) {
b = el("p", { "class": "banner ok", role: "status", text: t("integrity_ledger_ok", { count: g.count, seq: g.head_seq === null ? "-" : g.head_seq, hash: g.head_hash === null ? "-" : g.head_hash }) });
+ } else if (g.kind === "disclosure") {
+ b = el("p", { "class": "banner", role: "note", text: t("integrity_disclosure", { full: g.counts.full, summary: g.counts.summary, hidden: g.counts.hidden }) });
} else if (g.kind === "ledger") {
var ul = el("ul");
g.problems.forEach(function (p) { ul.appendChild(el("li", { text: t("problem_item", { code: p.code, seq: p.seq, message: p.message }) })); });
diff --git a/src/protocolith/core/atlas_i18n/en.json b/src/protocolith/core/atlas_i18n/en.json
index 52340cee8..c8babdce2 100644
--- a/src/protocolith/core/atlas_i18n/en.json
+++ b/src/protocolith/core/atlas_i18n/en.json
@@ -5,6 +5,7 @@
"theme_toggle": "Switch between light and dark theme",
"noscript": "This atlas needs JavaScript to display the records.",
"load_error": "The embedded atlas data could not be read.",
+ "integrity_disclosure": "Published view: {full} entries in full, {summary} as summaries, {hidden} hidden. A hidden entry is still part of the hash chain, so nothing was dropped.",
"integrity_ledger_ok": "Ledger verified: {count} entries, head seq {seq}, hash {hash}",
"integrity_ledger_failed": "LEDGER FAILED VERIFICATION ({count} problems). Do not rely on the data below.",
"problem_item": "{code} at line {seq}: {message}",
diff --git a/src/protocolith/core/commands.py b/src/protocolith/core/commands.py
index e34d7d4e0..0e9e56eb4 100644
--- a/src/protocolith/core/commands.py
+++ b/src/protocolith/core/commands.py
@@ -12,10 +12,12 @@
from . import ops
from .anchor import anchor_head
+from .disclosure import build_disclosure, load_policy, verify_disclosure, verify_reveal
from .atlas import DEFAULT_OUT, DEFAULT_TITLE, build_atlas_result, write_atlas
from .capture import capture
from .canonical import decode, encode
from .errors import InputError, ProtocolithError, hint_for, io_guard
+from .issue import _atomic_write
from .ledger import ENTRY_TYPES, RESULT_STATUSES
from .mcp import serve
from .schema import NAMES, all_schemas, schema_for
@@ -130,6 +132,52 @@ def work(store: Store) -> Outcome:
return _run(args, work)
+def _cmd_disclose(args: argparse.Namespace, parser: argparse.ArgumentParser) -> int:
+ def work(store: Store) -> Outcome:
+ found = build_disclosure(store, load_policy(args.policy))
+ with io_guard():
+ path = Path(args.out)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ _atomic_write(path, found.data)
+ c = found.counts
+ head = "empty" if found.head_seq is None else f"head seq={found.head_seq} hash={found.head_hash}"
+ lines = [f"wrote {path} entries={sum(c.values())} full={c['full']} summary={c['summary']} hidden={c['hidden']} {head}"]
+ lines += [f"warning: {w}" for w in found.warnings]
+ return Outcome({**found.to_dict(), "path": str(path)}, "\n".join(lines))
+
+ return _run(args, work)
+
+
+def _cmd_verify_disclosure(args: argparse.Namespace, parser: argparse.ArgumentParser) -> int:
+ try:
+ with io_guard():
+ data = Path(args.file).read_bytes()
+ report = verify_disclosure(data, args.anchors)
+ reveal = None
+ if args.reveal is not None and report.ok:
+ reveal = verify_reveal(data, read_input(args.reveal))
+ except ProtocolithError as exc:
+ return _fail(args, exc)
+ code = 0 if report.ok and (reveal is None or reveal["matches"]) else 1
+ if args.json:
+ print(encode({**report.to_dict(), "reveal": reveal}).decode("utf-8"))
+ return code
+ if not report.ok:
+ for v in report.violations:
+ print(f"{v.code} line {v.seq}: {v.message}", file=sys.stderr)
+ for name, hint in ((n, hint_for(n)) for n in report.codes):
+ print(f"hint ({name}): {hint}", file=sys.stderr)
+ print("FAILED: " + ", ".join(report.codes))
+ return code
+ c = report.counts
+ head = "empty" if report.head_seq is None else f"head seq={report.head_seq} hash={report.head_hash}"
+ checked = "" if report.anchors is None else f" anchors={report.anchors}"
+ print(f"OK entries={report.entries} full={c['full']} summary={c['summary']} hidden={c['hidden']} {head}{checked}")
+ if reveal is not None:
+ print(f"reveal seq={reveal['seq']} level={reveal['level']}: " + ("MATCHES" if reveal["matches"] else f"DIFFERENT ({reveal['reason']})"))
+ return code
+
+
def _cmd_claim_check(args: argparse.Namespace, parser: argparse.ArgumentParser) -> int:
def work(store: Store) -> Outcome:
found = ops.claim_check(store, seq=args.seq, protocol=args.protocol)
@@ -282,6 +330,7 @@ def _cmd_atlas(args: argparse.Namespace, parser: argparse.ArgumentParser) -> int
i18n_dir=args.i18n,
default_lang=args.default_lang,
max_rows=args.max_rows,
+ policy=None if args.policy is None else load_policy(args.policy),
)
path = write_atlas(result.html, args.out)
except ProtocolithError as exc:
@@ -352,6 +401,26 @@ def add(
anchor.add_argument("--git-tag", action="store_true", help="Create the git tag anchor/SEQ-HASH12 in this repository (never pushed).")
anchor.add_argument("--sign", action="store_true", help="Sign the git tag (needs --git-tag and a configured key).")
anchor.add_argument("--write-head", default=None, metavar="FILE", help="Write the anchor statement to FILE to publish or archive it.")
+ disclose = add(
+ "disclose",
+ _cmd_disclose,
+ "Write a publishable view of the ledger: each entry shown in full, as a summary, or hidden, as a policy says.",
+ with_json,
+ )
+ disclose.add_argument("--policy", required=True, metavar="FILE", help="Visibility policy (`protocolith schema policy`).")
+ disclose.add_argument("--out", default="disclosure.jsonl", metavar="FILE", help="Output file (default disclosure.jsonl).")
+ vdisc = subparsers.add_parser(
+ "verify-disclosure",
+ help="Verify a disclosure file; optionally against anchors and a revealed entry.",
+ description="Check the structure and hash chain of a disclosure and the hash of every full entry. "
+ "--anchors DIR compares the anchor statements there with the entry hashes; --reveal FILE checks that a "
+ "ledger entry you were given is exactly the one the disclosure committed to.",
+ )
+ vdisc.set_defaults(func=_cmd_verify_disclosure)
+ vdisc.add_argument("file", metavar="DISCLOSURE")
+ vdisc.add_argument("--anchors", default=None, metavar="DIR", help="Directory of anchor statements (.json) to check.")
+ vdisc.add_argument("--reveal", default=None, metavar="ENTRY", help="JSON file holding one revealed ledger entry.")
+ vdisc.add_argument("--json", action="store_true", help="Print the result as canonical JSON.")
claim = add("claim-check", _cmd_claim_check, "State what the ledger supports about a record (what may and may not be said).", with_json)
which = claim.add_mutually_exclusive_group(required=True)
which.add_argument("--seq", type=int, default=None, metavar="N", help="The record at ledger seq N.")
@@ -394,7 +463,7 @@ def add(
)
schema_parser.set_defaults(func=_cmd_schema)
schema_parser.add_argument(
- "name", nargs="?", default="all", choices=[*NAMES, "all"], help="Which schema (default all)."
+ "name", nargs="?", default="all", choices=[*NAMES, "policy", "all"], help="Which schema (default all)."
)
add("head", _cmd_head, "Print the ledger head (last hash and seq).", with_json)
repair = add("repair", _cmd_repair, "Repair a crash-damaged ledger.", with_json)
@@ -421,5 +490,8 @@ def add(
"--i18n", default=None, metavar="DIR", help="Directory of .json translation files; adds a language switcher."
)
atlas.add_argument("--default-lang", default="en", metavar="CODE", help="Initial language (default en).")
+ atlas.add_argument(
+ "--policy", default=None, metavar="FILE", help="Visibility policy: show each record in full, as a summary, or hidden."
+ )
atlas.add_argument("--max-rows", default=None, type=int, metavar="N", help="Embed at most N records (the newest); counts stay complete.")
add("mcp", _cmd_mcp, "Run the MCP server on stdio.", common)
diff --git a/src/protocolith/core/disclosure.py b/src/protocolith/core/disclosure.py
new file mode 100644
index 000000000..dc82d94f6
--- /dev/null
+++ b/src/protocolith/core/disclosure.py
@@ -0,0 +1,451 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Selective disclosure: publish a view of a ledger in which each entry is shown in full, as a summary, or hidden.
+
+A *policy* decides the level of every entry. The *disclosure* is a canonical JSON Lines file:
+
+- line 0, the manifest: kind, format version, number of entries, the head, and how many entries have each level;
+- then one line per ledger entry, in order, shaped by its level:
+ ``full`` carries the whole entry, ``summary`` carries ``seq``, ``prev``, ``hash``, ``type``, ``ts`` and a few chosen
+ fields, ``hidden`` carries only ``seq``, ``prev`` and ``hash``.
+
+Every line keeps the entry's own hash and the hash of the entry before it, so the chain stays linked and the head covers
+the hidden entries too. A reader therefore sees how many entries exist and that none was dropped, but nothing of the content
+that was hidden. The owner can reveal a hidden or summarised entry later: anyone checks that the revealed entry has exactly
+the published hash. Nothing here changes the ledger or its rules R1 to R11.
+
+Limits, stated plainly: a hidden hash does not reveal the content, but a reader who can guess the whole entry (for example a
+short, predictable body) can confirm the guess; a summary is a statement of the owner that is checked only when the entry is
+revealed; and publishing nothing about an entry does not hide that it exists.
+"""
+
+from __future__ import annotations
+
+import os
+from collections.abc import Mapping, Sequence
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+
+from .anchor import check_anchor_hashes
+from .canonical import CanonError, decode, encode
+from .errors import InputError, VerificationFailed, Violation, io_guard
+from .issue import card_hash
+from .ledger import ENTRY_KEYS, ENTRY_TYPES, ZERO_HASH, Entry, entry_hash, is_hash, is_ts
+from .rules import Verifier, scan
+from .store import Store
+from .views import protocol_of
+
+KIND = "protocolith-disclosure"
+FORMAT_VERSION = 1
+LEVELS = ("full", "summary", "hidden")
+SUMMARY_CHOICES = ("claim_boundary", "outcome", "public_claim_text", "question", "reproduction_level", "run_id", "status")
+DEFAULT_SUMMARY = ("status", "reproduction_level", "claim_boundary")
+DEFAULT_LEVEL = "hidden"
+RULES_LIMIT = 10_000
+MAX_NAME = 200
+_POLICY_KEYS = frozenset({"default", "rules", "summary_fields", "v"})
+RULEKEYS = frozenset({"from_seq", "level", "protocol_id", "seq", "to_seq"})
+_MANIFEST_KEYS = frozenset({"counts", "entries", "head_hash", "head_seq", "kind", "v"})
+_LINE_KEYS = {
+ "full": frozenset({"entry", "level", "seq"}),
+ "summary": frozenset({"hash", "level", "prev", "seq", "summary", "ts", "type"}),
+ "hidden": frozenset({"hash", "level", "prev", "seq"}),
+}
+_RANK = {"hidden": 0, "summary": 1, "full": 2}
+
+
+def _uint(value: object) -> bool:
+ return type(value) is int and value >= 0
+
+
+@dataclass(frozen=True)
+class Rule:
+ """One policy rule: a level for the entries of a protocol (``ID`` or ``PREFIX*``) or for some sequence numbers."""
+
+ level: str
+ protocol: str | None = None
+ seqs: frozenset[int] | None = None
+ span: tuple[int, int] | None = None
+
+ def matches(self, seq: int, protocol: str | None) -> bool:
+ if self.protocol is not None:
+ if protocol is None:
+ return False
+ if self.protocol.endswith("*"):
+ return protocol.startswith(self.protocol[:-1])
+ return protocol == self.protocol
+ if self.seqs is not None:
+ return seq in self.seqs
+ assert self.span is not None
+ return self.span[0] <= seq <= self.span[1]
+
+
+@dataclass(frozen=True)
+class Policy:
+ """Which entries are shown how. The first matching rule wins; ``default`` applies when none matches."""
+
+ default: str = DEFAULT_LEVEL
+ rules: tuple[Rule, ...] = ()
+ summary_fields: tuple[str, ...] = DEFAULT_SUMMARY
+
+ def level_for(self, seq: int, protocol: str | None) -> str:
+ for rule in self.rules:
+ if rule.matches(seq, protocol):
+ return rule.level
+ return self.default
+
+
+def _bad(message: str) -> InputError:
+ return InputError("BAD_POLICY", message)
+
+
+def _level(value: object, where: str) -> str:
+ if value not in LEVELS:
+ raise _bad(f"{where}: level must be one of {', '.join(LEVELS)}")
+ return str(value)
+
+
+def _protocol_selector(value: object, where: str) -> str:
+ if not (isinstance(value, str) and value and len(value) <= MAX_NAME) or "*" in value[:-1]:
+ raise _bad(f"{where}: protocol_id must be a non-empty string; a * is allowed only as the last character")
+ return value
+
+
+def _seq_list(value: object, where: str) -> frozenset[int]:
+ items = value if isinstance(value, list) else [value]
+ if not items or not all(_uint(item) for item in items):
+ raise _bad(f"{where}: seq must be a non-negative integer or a non-empty list of them")
+ return frozenset(items)
+
+
+def _parse_rule(raw: object, index: int) -> Rule:
+ where = f"rules[{index}]"
+ if not isinstance(raw, dict):
+ raise _bad(f"{where}: must be an object")
+ unknown = sorted(set(raw) - RULEKEYS)
+ if unknown:
+ raise _bad(f"{where}: unknown keys {', '.join(unknown)}")
+ if "level" not in raw:
+ raise _bad(f"{where}: level is required")
+ level = _level(raw["level"], where)
+ chosen = [k for k in ("protocol_id", "seq") if k in raw] + (["span"] if ("from_seq" in raw or "to_seq" in raw) else [])
+ if len(chosen) != 1:
+ raise _bad(f"{where}: give exactly one of protocol_id, seq, or from_seq with to_seq")
+ if chosen[0] == "protocol_id":
+ return Rule(level, protocol=_protocol_selector(raw["protocol_id"], where))
+ if chosen[0] == "seq":
+ return Rule(level, seqs=_seq_list(raw["seq"], where))
+ low, high = raw.get("from_seq"), raw.get("to_seq")
+ if not (isinstance(low, int) and isinstance(high, int) and _uint(low) and _uint(high) and low <= high):
+ raise _bad(f"{where}: from_seq and to_seq must both be non-negative integers with from_seq <= to_seq")
+ return Rule(level, span=(low, high))
+
+
+def parse_policy(doc: object) -> Policy:
+ """Validate a policy object (see ``schema_for("policy")``); BAD_POLICY on any problem."""
+ if not isinstance(doc, dict):
+ raise _bad("a policy must be a JSON object")
+ unknown = sorted(set(doc) - _POLICY_KEYS)
+ if unknown:
+ raise _bad("unknown keys: " + ", ".join(unknown))
+ if doc.get("v", FORMAT_VERSION) != FORMAT_VERSION:
+ raise _bad(f"v must be {FORMAT_VERSION}")
+ default = _level(doc.get("default", DEFAULT_LEVEL), "default")
+ raw_rules = doc.get("rules", [])
+ if not isinstance(raw_rules, list) or len(raw_rules) > RULES_LIMIT:
+ raise _bad(f"rules must be a list of at most {RULES_LIMIT} objects")
+ rules = tuple(_parse_rule(raw, index) for index, raw in enumerate(raw_rules))
+ fields = doc.get("summary_fields", list(DEFAULT_SUMMARY))
+ if not (isinstance(fields, list) and all(isinstance(f, str) for f in fields) and len(set(fields)) == len(fields)):
+ raise _bad("summary_fields must be a list of distinct strings")
+ bad = sorted(set(fields) - set(SUMMARY_CHOICES))
+ if bad:
+ raise _bad(f"summary_fields: unknown {', '.join(bad)}; choose from {', '.join(SUMMARY_CHOICES)}")
+ return Policy(default, rules, tuple(fields))
+
+
+def load_policy(path: str | os.PathLike[str]) -> Policy:
+ """Read a policy file (strict JSON, no floats)."""
+ with io_guard():
+ raw = Path(path).read_bytes()
+ try:
+ return parse_policy(decode(raw))
+ except CanonError as exc:
+ raise InputError("BAD_POLICY", f"{path}: {exc.message}") from None
+
+
+def summarize_entry(entry: Mapping[str, Any], protocol: str | None, fields: Sequence[str]) -> dict[str, Any]:
+ """The few facts a ``summary`` line carries. Only what the policy lists is taken from a record or a freeze."""
+ body = entry["body"]
+ out: dict[str, Any] = {}
+ if protocol is not None:
+ out["protocol_id"] = protocol
+ kind = entry["type"]
+ if kind == "freeze":
+ out["version"] = body["version"]
+ question = body.get("protocol", {}).get("question") if isinstance(body.get("protocol"), dict) else None
+ if "question" in fields and question is not None:
+ out["question"] = question
+ elif kind == "record":
+ card = body.get("card") if isinstance(body.get("card"), dict) else {}
+ found = {
+ "claim_boundary": body.get("claim_boundary"),
+ "outcome": body.get("outcome"),
+ "public_claim_text": card.get("public_claim_text"),
+ "reproduction_level": body.get("reproduction_level"),
+ "run_id": body.get("run_id"),
+ "status": body.get("status"),
+ }
+ out.update({key: value for key, value in found.items() if key in fields and value is not None})
+ elif kind == "issue":
+ out["record_seq"] = body["record_seq"]
+ return out
+
+
+@dataclass
+class Disclosure:
+ """The bytes of a disclosure file plus what a caller reports."""
+
+ data: bytes
+ counts: dict[str, int]
+ head_seq: int | None
+ head_hash: str | None
+ warnings: list[str] = field(default_factory=list)
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "bytes": len(self.data),
+ "counts": self.counts,
+ "entries": sum(self.counts.values()),
+ "head": {"hash": self.head_hash, "seq": self.head_seq},
+ "warnings": self.warnings,
+ }
+
+
+def levels_of(verifier: Verifier, policy: Policy) -> list[str]:
+ """The level of every entry, in order."""
+ return [
+ policy.level_for(seq, protocol_of(verifier, verifier.entries[seq])) for seq in range(verifier.index)
+ ]
+
+
+def _warnings(verifier: Verifier, levels: Sequence[str]) -> list[str]:
+ """A record that is shown more than the freeze of its protocol cannot be read in context."""
+ weakest: dict[str, int] = {}
+ for seq, level in enumerate(levels):
+ entry = verifier.entries[seq]
+ if entry["type"] == "freeze":
+ weakest[entry["body"]["protocol_id"]] = _RANK[level]
+ found = []
+ for seq, level in enumerate(levels):
+ entry = verifier.entries[seq]
+ protocol = protocol_of(verifier, entry)
+ if entry["type"] == "record" and protocol in weakest and _RANK[level] > weakest[protocol]:
+ found.append(f"seq {seq}: the record is shown more than the freeze of protocol {protocol}")
+ return found
+
+
+def disclose_verifier(verifier: Verifier, policy: Policy) -> Disclosure:
+ levels = levels_of(verifier, policy)
+ counts = {name: levels.count(name) for name in LEVELS}
+ count = verifier.index
+ head_hash = verifier.prev_hash if count else None
+ lines: list[dict[str, Any]] = [
+ {
+ "counts": counts,
+ "entries": count,
+ "head_hash": head_hash,
+ "head_seq": count - 1 if count else None,
+ "kind": KIND,
+ "v": FORMAT_VERSION,
+ }
+ ]
+ for seq, level in enumerate(levels):
+ entry: Entry = verifier.entries[seq]
+ if level == "full":
+ lines.append({"entry": entry, "level": "full", "seq": seq})
+ elif level == "summary":
+ summary = summarize_entry(entry, protocol_of(verifier, entry), policy.summary_fields)
+ lines.append(
+ {"hash": entry["hash"], "level": "summary", "prev": entry["prev"], "seq": seq, "summary": summary,
+ "ts": entry["ts"], "type": entry["type"]}
+ )
+ else:
+ lines.append({"hash": entry["hash"], "level": "hidden", "prev": entry["prev"], "seq": seq})
+ data = b"".join(encode(line) + b"\n" for line in lines)
+ return Disclosure(data, counts, count - 1 if count else None, head_hash, _warnings(verifier, levels))
+
+
+def build_disclosure(store: Store | str | os.PathLike[str], policy: Policy) -> Disclosure:
+ """Verify the ledger, then build the disclosure the policy asks for. A ledger that fails verification is never disclosed."""
+ real = store if isinstance(store, Store) else Store(store)
+ with io_guard(), real.locked(write=False):
+ verdict, verifier = scan(real.read(missing_ok=False), card_hash)
+ if not verdict.ok:
+ raise VerificationFailed(verdict.violations)
+ return disclose_verifier(verifier, policy)
+
+
+@dataclass
+class DisclosureReport:
+ ok: bool
+ entries: int
+ counts: dict[str, int]
+ head_seq: int | None
+ head_hash: str | None
+ anchors: int | None
+ violations: list[Violation]
+
+ @property
+ def codes(self) -> list[str]:
+ return sorted({v.code for v in self.violations})
+
+ def to_dict(self) -> dict[str, Any]:
+ found: dict[str, Any] = {
+ "codes": self.codes,
+ "counts": self.counts,
+ "entries": self.entries,
+ "head": {"hash": self.head_hash, "seq": self.head_seq},
+ "ok": self.ok,
+ "violations": [v.to_dict() for v in self.violations],
+ }
+ if self.anchors is not None:
+ found["anchors"] = self.anchors
+ return found
+
+
+def _decode_lines(data: bytes) -> tuple[list[dict[str, Any]], list[Violation]]:
+ """Parse every line as canonical JSON; a line that fails is reported and skipped."""
+ found: list[Violation] = []
+ objects: list[dict[str, Any]] = []
+ pieces = data.split(b"\n")
+ tail = pieces.pop()
+ if tail:
+ found.append(Violation("BAD_DISCLOSURE", len(pieces), "the last line is not terminated by a newline"))
+ for number, piece in enumerate(pieces):
+ try:
+ obj = decode(piece)
+ except CanonError as exc:
+ found.append(Violation("BAD_DISCLOSURE", number, f"not valid JSON: {exc.message}"))
+ objects.append({})
+ continue
+ if not isinstance(obj, dict):
+ found.append(Violation("BAD_DISCLOSURE", number, "a line must be a JSON object"))
+ elif encode(obj) != piece:
+ found.append(Violation("BAD_DISCLOSURE", number, "the line is not in canonical form"))
+ else:
+ objects.append(obj)
+ continue
+ objects.append({})
+ return objects, found
+
+
+def _check_line(obj: dict[str, Any], seq: int, expected_prev: str) -> tuple[list[Violation], str | None]:
+ """Problems of one entry line and its hash when readable."""
+ level = obj.get("level")
+ if level not in _LINE_KEYS or set(obj) != _LINE_KEYS[level]:
+ return [Violation("BAD_DISCLOSURE", seq, "unknown level or unexpected keys")], None
+ if obj["seq"] != seq or type(obj["seq"]) is not int:
+ return [Violation("BAD_DISCLOSURE", seq, f"seq must be {seq}")], None
+ found: list[Violation] = []
+ if level == "full":
+ entry = obj["entry"]
+ if not (isinstance(entry, dict) and set(entry) == ENTRY_KEYS and is_hash(entry["hash"]) and is_hash(entry["prev"])):
+ return [Violation("BAD_DISCLOSURE", seq, "a full line must carry a complete entry")], None
+ if entry["seq"] != seq:
+ found.append(Violation("BAD_DISCLOSURE", seq, "the entry has another seq"))
+ if entry_hash(entry) != entry["hash"]:
+ found.append(Violation("DISCLOSURE_HASH", seq, "the entry does not hash to its stated hash"))
+ digest, prev = entry["hash"], entry["prev"]
+ else:
+ digest, prev = obj["hash"], obj["prev"]
+ if not (is_hash(digest) and is_hash(prev)):
+ return [Violation("BAD_DISCLOSURE", seq, "hash and prev must be 64 lowercase hex characters")], None
+ if level == "summary" and not (
+ obj["type"] in ENTRY_TYPES and is_ts(obj["ts"]) and isinstance(obj["summary"], dict)
+ ):
+ found.append(Violation("BAD_DISCLOSURE", seq, "a summary needs a known type, a time-stamp and an object"))
+ if prev != expected_prev:
+ found.append(Violation("DISCLOSURE_CHAIN", seq, "prev is not the hash of the entry before"))
+ return found, digest
+
+
+def _check_manifest(manifest: dict[str, Any], count: int, counts: dict[str, int], tip: str | None) -> list[Violation]:
+ if set(manifest) != _MANIFEST_KEYS or manifest["kind"] != KIND or manifest["v"] != FORMAT_VERSION:
+ return [Violation("BAD_DISCLOSURE", 0, "line 0 is not a disclosure manifest of this version")]
+ found: list[Violation] = []
+ if manifest["entries"] != count:
+ found.append(Violation("BAD_DISCLOSURE", 0, f"the manifest says {manifest['entries']} entries, the file has {count}"))
+ if manifest["counts"] != counts:
+ found.append(Violation("BAD_DISCLOSURE", 0, "the manifest counts differ from the lines"))
+ if manifest["head_hash"] != tip or manifest["head_seq"] != (count - 1 if count else None):
+ found.append(Violation("BAD_DISCLOSURE", 0, "the manifest head differs from the last line"))
+ return found
+
+
+def verify_disclosure(data: bytes, anchors_dir: str | os.PathLike[str] | None = None) -> DisclosureReport:
+ """Check a disclosure file: structure, hash chain, the hash of every full entry, and optionally the anchors.
+
+ With ``anchors_dir`` every anchor statement there is compared with the entry hash at its position: ANCHOR_MISMATCH
+ (the history was replaced) or ANCHOR_AHEAD (entries were removed). Hidden entries are covered through their hashes.
+ """
+ objects, violations = _decode_lines(data)
+ body = objects[1:]
+ manifest = objects[0] if objects else {}
+ expected, hashes = ZERO_HASH, {}
+ counts = {name: 0 for name in LEVELS}
+ for seq, obj in enumerate(body):
+ if not obj:
+ continue
+ found, digest = _check_line(obj, seq, expected)
+ violations.extend(found)
+ if digest is None:
+ break
+ counts[obj["level"]] += 1
+ hashes[seq] = expected = digest
+ count = len(body)
+ if not objects:
+ violations.append(Violation("BAD_DISCLOSURE", 0, "the file is empty"))
+ elif not violations:
+ violations.extend(_check_manifest(manifest, count, counts, expected if count else None))
+ checked = None
+ if anchors_dir is not None:
+ report = check_anchor_hashes(Path(anchors_dir), hashes, count)
+ violations.extend(report.violations)
+ checked = report.count
+ head = (count - 1, expected) if count else (None, None)
+ return DisclosureReport(not violations, count, counts, head[0], head[1], checked, violations)
+
+
+def _mismatch(seq: object, reason: str) -> dict[str, Any]:
+ return {"level": None, "matches": False, "reason": reason, "seq": seq}
+
+
+def verify_reveal(disclosure: bytes, entry: object) -> dict[str, Any]:
+ """Check that a revealed ledger entry is exactly the one a verified disclosure committed to.
+
+ Returns ``{"seq", "level", "matches", "reason"}``; ``matches`` is False, with a reason, when the entry is not the
+ published one. BAD_DISCLOSURE is raised when the disclosure itself does not verify.
+ """
+ report = verify_disclosure(disclosure)
+ if not report.ok:
+ raise InputError("BAD_DISCLOSURE", "the disclosure does not verify: " + ", ".join(report.codes), report.violations)
+ if not (isinstance(entry, dict) and set(entry) == ENTRY_KEYS and is_hash(entry.get("hash"))):
+ return _mismatch(None, "the revealed value is not a complete ledger entry")
+ seq = entry["seq"]
+ if entry_hash(entry) != entry["hash"]:
+ return _mismatch(seq, "the revealed entry does not hash to its own hash")
+ lines, _ = _decode_lines(disclosure)
+ if not (type(seq) is int and 0 <= seq < len(lines) - 1):
+ return _mismatch(seq, f"the disclosure has no entry {seq}")
+ line = lines[seq + 1]
+ published = line["entry"] if line["level"] == "full" else line
+ if entry["hash"] != published["hash"] or entry["prev"] != published["prev"]:
+ return _mismatch(seq, f"entry {seq} is not the one the disclosure committed to")
+ if line["level"] == "summary":
+ protocol = entry["body"].get("protocol_id") if entry["type"] == "freeze" else None
+ derived = summarize_entry(entry, protocol, SUMMARY_CHOICES)
+ wrong = [k for k, v in line["summary"].items() if k in derived and derived[k] != v]
+ if wrong or line["type"] != entry["type"] or line["ts"] != entry["ts"]:
+ return _mismatch(seq, f"entry {seq}: the published summary does not match the revealed entry")
+ return {"level": line["level"], "matches": True, "reason": None, "seq": seq}
diff --git a/src/protocolith/core/errors.py b/src/protocolith/core/errors.py
index 245c4c65b..3f97b9987 100644
--- a/src/protocolith/core/errors.py
+++ b/src/protocolith/core/errors.py
@@ -41,6 +41,10 @@
"NOT_A_GIT_REPO": "run the command inside a git repository, or use another anchoring option",
"EMPTY_LEDGER": "record at least one entry before anchoring",
"BAD_URL": "give an http or https URL",
+ "BAD_POLICY": "run `protocolith schema policy` to see the allowed keys; a rule needs a level and one selector",
+ "BAD_DISCLOSURE": "the file is not a disclosure written by `protocolith disclose`, or it was edited; fetch it again from its source",
+ "DISCLOSURE_HASH": "a full entry was edited after it was disclosed; fetch the disclosure again from its source",
+ "DISCLOSURE_CHAIN": "an entry was removed, reordered or replaced in the disclosure; fetch it again from its source",
}
diff --git a/src/protocolith/core/mcp.py b/src/protocolith/core/mcp.py
index 171fc91a0..3eba1ba15 100644
--- a/src/protocolith/core/mcp.py
+++ b/src/protocolith/core/mcp.py
@@ -15,9 +15,11 @@
from .anchor import anchor_head
from .atlas import DEFAULT_OUT, DEFAULT_TITLE, build_atlas_result, confine, write_atlas
from .capture import capture
+from .disclosure import build_disclosure, parse_policy, verify_disclosure, verify_reveal
+from .issue import _atomic_write
from .canonical import CanonError, decode, encode
from .clock import Clock
-from .errors import InputError, ProtocolithError
+from .errors import InputError, ProtocolithError, io_guard
from .prompts import PROMPTS
from .schema import NAMES, all_schemas, schema_for
from .ledger import ENTRY_TYPES, RESULT_STATUSES
@@ -25,7 +27,7 @@
PROTOCOL_VERSIONS = ("2025-06-18", "2025-03-26", "2024-11-05")
SERVER_NAME = "protocolith"
-SERVER_VERSION = "0.6.0"
+SERVER_VERSION = "0.7.0"
Handler = Callable[[Store, dict[str, Any], Clock | None], Any]
@@ -106,7 +108,7 @@ def _schema(store: Store, arguments: dict[str, Any], clock: Clock | None) -> Any
def _atlas(store: Store, arguments: dict[str, Any], clock: Clock | None) -> Any:
- args = _take(arguments, (), ("out", "title", "cards", "i18n", "default_lang", "max_rows"))
+ args = _take(arguments, (), ("out", "title", "cards", "i18n", "default_lang", "max_rows", "policy"))
cards = args.get("cards", [])
if not (isinstance(cards, list) and all(isinstance(name, str) for name in cards)):
raise InputError("BAD_ENTRY", "cards must be a list of strings")
@@ -120,11 +122,32 @@ def _atlas(store: Store, arguments: dict[str, Any], clock: Clock | None) -> Any:
i18n_dir=i18n,
default_lang=args.get("default_lang", "en"),
max_rows=args.get("max_rows"),
+ policy=parse_policy(args["policy"]) if "policy" in args else None,
)
path = write_atlas(result.html, out)
return {**result.to_dict(), "path": path.relative_to(Path.cwd().resolve()).as_posix()}
+def _disclose(store: Store, arguments: dict[str, Any], clock: Clock | None) -> Any:
+ args = _take(arguments, ("policy",), ("out",))
+ found = build_disclosure(store, parse_policy(args["policy"]))
+ out = confine(args.get("out", "disclosure.jsonl"))
+ with io_guard():
+ out.parent.mkdir(parents=True, exist_ok=True)
+ _atomic_write(out, found.data)
+ return {**found.to_dict(), "path": out.relative_to(Path.cwd().resolve()).as_posix()}
+
+
+def _verify_disclosure(store: Store, arguments: dict[str, Any], clock: Clock | None) -> Any:
+ args = _take(arguments, ("file",), ("anchors", "reveal"))
+ path = confine(args["file"])
+ with io_guard():
+ data = path.read_bytes()
+ report = verify_disclosure(data, confine(args["anchors"]) if "anchors" in args else None)
+ reveal = verify_reveal(data, args["reveal"]) if "reveal" in args and report.ok else None
+ return {**report.to_dict(), "ok": report.ok and (reveal is None or reveal["matches"]), "reveal": reveal}
+
+
@dataclass(frozen=True)
class Tool:
name: str
@@ -268,14 +291,41 @@ def listing(self) -> dict[str, Any]:
"i18n": {"type": "string", "description": "directory of .json translation files"},
"default_lang": {"type": "string"},
"max_rows": {"type": "integer", "minimum": 1},
+ "policy": {"type": "object", "description": "visibility policy (see protocolith_schema policy): show records in full, as a summary, or hidden"},
},
(),
_atlas,
),
+ Tool(
+ "protocolith_disclose",
+ "Write a publishable view of the ledger as a JSON Lines file inside the working directory: each entry is shown in "
+ "full, as a summary, or hidden, as the policy says (first matching rule wins; the default is hidden). The hash "
+ "chain stays intact, so a reader sees how many entries exist and that none was dropped. Use this before "
+ "publishing anything from a private ledger. See protocolith_schema with name policy.",
+ {
+ "policy": {"type": "object", "description": "default level, rules and summary_fields"},
+ "out": {"type": "string", "description": "output file (default disclosure.jsonl)"},
+ },
+ ("policy",),
+ _disclose,
+ ),
+ Tool(
+ "protocolith_verify_disclosure",
+ "Verify a disclosure file written by protocolith_disclose: structure, hash chain, the hash of every full entry, "
+ "optionally the anchor statements in a directory, and optionally a revealed ledger entry (reveal) that must be "
+ "exactly the entry the disclosure committed to. isError is true when anything does not verify.",
+ {
+ "file": {"type": "string", "description": "the disclosure file"},
+ "anchors": {"type": "string", "description": "directory of anchor statements"},
+ "reveal": {"type": "object", "description": "one full ledger entry the owner revealed"},
+ },
+ ("file",),
+ _verify_disclosure,
+ ),
Tool(
"protocolith_schema",
- "JSON Schema (draft 2020-12) of the inputs: freeze, record, deviation, issue, entry, or all.",
- {"name": {"enum": [*NAMES, "all"]}},
+ "JSON Schema (draft 2020-12) of the inputs: freeze, record, deviation, issue, entry, policy, or all.",
+ {"name": {"enum": [*NAMES, "policy", "all"]}},
(),
_schema,
),
diff --git a/src/protocolith/core/schema.py b/src/protocolith/core/schema.py
index c39ed823c..78d58d589 100644
--- a/src/protocolith/core/schema.py
+++ b/src/protocolith/core/schema.py
@@ -46,6 +46,10 @@
"status": {"enum": sorted(RESULT_STATUSES)},
"type": {"enum": list(ENTRY_TYPES)},
}
+_POLICY_DESCRIPTION = (
+ "A visibility policy for `protocolith disclose` and `protocolith atlas --policy`: which ledger entries are shown "
+ "in full, as a summary, or hidden."
+)
_DESCRIPTIONS = {
"freeze": "Input of `freeze`: the protocol object. protocol_id and version are required; any other key is part of the protocol.",
"record": "Input of `record` and body of a record entry.",
@@ -118,19 +122,49 @@ def _entry() -> dict[str, Any]:
return schema
+def _policy_schema() -> dict[str, Any]:
+ from .disclosure import LEVELS, SUMMARY_CHOICES
+
+ level = {"enum": list(LEVELS)}
+ rule = {
+ "type": "object",
+ "properties": {
+ "level": level,
+ "protocol_id": {"type": "string", "minLength": 1, "description": "an exact protocol_id, or a prefix ending in *"},
+ "seq": {"oneOf": [_UINT, {"type": "array", "items": _UINT, "minItems": 1}]},
+ "from_seq": _UINT,
+ "to_seq": _UINT,
+ },
+ "required": ["level"],
+ "additionalProperties": False,
+ }
+ return {
+ "type": "object",
+ "properties": {
+ "v": {"const": 1},
+ "default": {**level, "description": "level of an entry no rule matches (default hidden)"},
+ "rules": {"type": "array", "items": rule, "description": "the first matching rule wins"},
+ "summary_fields": {"type": "array", "items": {"enum": list(SUMMARY_CHOICES)}, "uniqueItems": True},
+ },
+ "additionalProperties": False,
+ }
+
+
def schema_for(name: str) -> dict[str, Any]:
"""The JSON Schema for one input (``freeze``, ``record``, ``deviation``, ``issue``) or the ledger ``entry``."""
if name == "freeze":
body = _freeze_input()
elif name == "issue":
body = {"type": "object", "properties": {"seq": _UINT}, "required": ["seq"], "additionalProperties": False}
+ elif name == "policy":
+ body = _policy_schema()
elif name == "entry":
body = _entry()
elif name in NAMES:
body = _bodies()[name]
else:
- raise InputError("BAD_ENTRY", "schema name must be one of: " + ", ".join(NAMES) + ", all")
- return {"$schema": DIALECT, "title": f"protocolith {name}", "description": _DESCRIPTIONS[name], **body}
+ raise InputError("BAD_ENTRY", "schema name must be one of: " + ", ".join(NAMES) + ", policy, all")
+ return {"$schema": DIALECT, "title": f"protocolith {name}", "description": _DESCRIPTIONS.get(name, _POLICY_DESCRIPTION), **body}
def all_schemas() -> dict[str, dict[str, Any]]:
diff --git a/tests/core/test_disclosure.py b/tests/core/test_disclosure.py
new file mode 100644
index 000000000..d333de1e8
--- /dev/null
+++ b/tests/core/test_disclosure.py
@@ -0,0 +1,547 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Selective disclosure: policy, export, verification, reveal, the atlas view, the CLI and MCP tools."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any
+
+import pytest
+from core_support import NOW, clock, deviation_body, protocol, record_body
+
+from protocolith.cli import main
+from protocolith.core import (
+ InputError,
+ Store,
+ VerificationFailed,
+ anchor_head,
+ build_atlas,
+ build_disclosure,
+ deviation,
+ entries,
+ freeze,
+ issue,
+ load_policy,
+ parse_policy,
+ record,
+ schema_for,
+ sha256_hex,
+ verify_disclosure,
+ verify_reveal,
+)
+from protocolith.core import disclosure as disclosure_module
+from protocolith.core.canonical import encode
+from protocolith.core.disclosure import Policy, Rule, summarize_entry
+from protocolith.core.mcp import handle_line
+
+OTHER = {"gate": "other gate", "protocol_id": "OTHER_D002", "question": "Is it so?", "version": "1"}
+
+
+@pytest.fixture(autouse=True)
+def _env(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("PROTOCOLITH_NOW", NOW)
+
+
+@pytest.fixture
+def rich(store: Store) -> Store:
+ """seq 0 freeze DEMO, 1 record DEMO, 2 issue, 3 freeze OTHER, 4 record OTHER, 5 deviation DEMO."""
+ freeze(store, protocol(), clock=clock(NOW))
+ record(store, record_body(), clock=clock(NOW))
+ issue(store, 1, clock=clock(NOW))
+ freeze(store, OTHER, clock=clock(NOW))
+ record(store, record_body(protocol_sha256=sha256_hex(OTHER), run_id="run-2", status="NEGATIVE_RESULT_UNDER_PROTOCOL"), clock=clock(NOW))
+ deviation(store, deviation_body(), clock=clock(NOW))
+ return store
+
+
+def lines_of(data: bytes) -> list[dict[str, Any]]:
+ return [json.loads(line) for line in data.splitlines()]
+
+
+def policy(**changes: Any) -> Policy:
+ doc: dict[str, Any] = {"v": 1, "default": "hidden", "rules": []}
+ doc.update(changes)
+ return parse_policy(doc)
+
+
+# ---------------------------------------------------------------- policy
+
+def test_policy_defaults_and_first_match_wins() -> None:
+ p = parse_policy({})
+ assert p.default == "hidden" and p.rules == () and p.summary_fields == ("status", "reproduction_level", "claim_boundary")
+ p = parse_policy(
+ {
+ "default": "summary",
+ "rules": [
+ {"protocol_id": "DEMO_D001", "level": "full"},
+ {"protocol_id": "DEMO_*", "level": "hidden"},
+ {"seq": [7, 8], "level": "hidden"},
+ {"from_seq": 10, "to_seq": 12, "level": "full"},
+ ],
+ }
+ )
+ assert p.level_for(0, "DEMO_D001") == "full"
+ assert p.level_for(0, "DEMO_D002") == "hidden"
+ assert p.level_for(0, "OTHER") == "summary"
+ assert p.level_for(0, None) == "summary"
+ assert p.level_for(8, None) == "hidden"
+ assert p.level_for(11, None) == "full" and p.level_for(13, None) == "summary"
+ assert Rule("full", seqs=frozenset({3})).matches(3, None)
+
+
+@pytest.mark.parametrize(
+ "doc",
+ [
+ [],
+ {"unknown": 1},
+ {"v": 2},
+ {"default": "everything"},
+ {"rules": "no"},
+ {"rules": [1]},
+ {"rules": [{"level": "full"}]},
+ {"rules": [{"protocol_id": "A", "level": "full", "extra": 1}]},
+ {"rules": [{"protocol_id": "A"}]},
+ {"rules": [{"protocol_id": "A", "level": "nope"}]},
+ {"rules": [{"protocol_id": "A", "seq": 1, "level": "full"}]},
+ {"rules": [{"protocol_id": "", "level": "full"}]},
+ {"rules": [{"protocol_id": "A*B", "level": "full"}]},
+ {"rules": [{"protocol_id": 5, "level": "full"}]},
+ {"rules": [{"seq": -1, "level": "full"}]},
+ {"rules": [{"seq": [], "level": "full"}]},
+ {"rules": [{"seq": True, "level": "full"}]},
+ {"rules": [{"from_seq": 3, "level": "full"}]},
+ {"rules": [{"from_seq": 5, "to_seq": 2, "level": "full"}]},
+ {"rules": [{"from_seq": "1", "to_seq": 2, "level": "full"}]},
+ {"summary_fields": "status"},
+ {"summary_fields": ["status", "status"]},
+ {"summary_fields": ["status", 3]},
+ {"summary_fields": ["secret"]},
+ {"rules": [{"protocol_id": "A", "level": "full"}] * (disclosure_module.RULES_LIMIT + 1)},
+ ],
+)
+def test_bad_policies_are_refused(doc: Any) -> None:
+ with pytest.raises(InputError) as caught:
+ parse_policy(doc)
+ assert caught.value.code == "BAD_POLICY"
+
+
+def test_load_policy_reads_strict_json(tmp_path: Path) -> None:
+ good = tmp_path / "p.json"
+ good.write_text('{"default": "summary"}', encoding="utf-8")
+ assert load_policy(good).default == "summary"
+ bad = tmp_path / "bad.json"
+ bad.write_text('{"default": 1.5}', encoding="utf-8")
+ with pytest.raises(InputError) as caught:
+ load_policy(bad)
+ assert caught.value.code == "BAD_POLICY" and "bad.json" in caught.value.message
+ with pytest.raises(Exception):
+ load_policy(tmp_path / "missing.json")
+
+
+def test_policy_schema_describes_the_policy() -> None:
+ schema = schema_for("policy")
+ assert schema["title"] == "protocolith policy" and "rules" in schema["properties"]
+ assert schema["additionalProperties"] is False
+
+
+# ---------------------------------------------------------------- build
+
+def test_build_levels_and_manifest(rich: Store) -> None:
+ p = policy(
+ rules=[
+ {"protocol_id": "DEMO_D001", "level": "full"},
+ {"protocol_id": "OTHER_D002", "level": "summary"},
+ ],
+ summary_fields=["status", "claim_boundary", "run_id", "outcome", "public_claim_text", "question", "reproduction_level"],
+ )
+ found = build_disclosure(rich, p)
+ rows = lines_of(found.data)
+ assert rows[0] == {
+ "counts": {"full": 4, "hidden": 0, "summary": 2},
+ "entries": 6,
+ "head_hash": found.head_hash,
+ "head_seq": 5,
+ "kind": "protocolith-disclosure",
+ "v": 1,
+ }
+ ledger = entries(rich)
+ assert [r["level"] for r in rows[1:]] == ["full", "full", "full", "summary", "summary", "full"]
+ assert rows[1]["entry"] == ledger[0]
+ freeze_summary, record_summary = rows[4]["summary"], rows[5]["summary"]
+ assert freeze_summary == {"protocol_id": "OTHER_D002", "question": "Is it so?", "version": "1"}
+ assert record_summary["status"] == "NEGATIVE_RESULT_UNDER_PROTOCOL" and record_summary["run_id"] == "run-2"
+ assert record_summary["outcome"] == {"pass_rate": "0.55"} and "public_claim_text" in record_summary
+ assert set(rows[4]) == {"hash", "level", "prev", "seq", "summary", "ts", "type"}
+ assert found.to_dict()["entries"] == 6 and found.to_dict()["head"]["seq"] == 5
+ assert found.data == build_disclosure(rich, p).data # deterministic
+
+
+def test_hidden_lines_carry_only_the_chain(rich: Store) -> None:
+ found = build_disclosure(rich, policy())
+ rows = lines_of(found.data)
+ assert rows[0]["counts"] == {"full": 0, "hidden": 6, "summary": 0}
+ assert all(set(row) == {"hash", "level", "prev", "seq"} for row in rows[1:])
+ text = found.data.decode()
+ assert "DEMO_D001" not in text and "pass_rate" not in text and "2026-11-15" not in text
+
+
+def test_summary_of_every_entry_type(rich: Store) -> None:
+ ledger = entries(rich)
+ every = disclosure_module.SUMMARY_CHOICES
+ assert summarize_entry(ledger[2], "DEMO_D001", every) == {"protocol_id": "DEMO_D001", "record_seq": 1}
+ assert summarize_entry(ledger[5], "DEMO_D001", every) == {"protocol_id": "DEMO_D001"}
+ assert summarize_entry(ledger[5], None, every) == {}
+ only_status = summarize_entry(ledger[1], "DEMO_D001", ("status",))
+ assert only_status == {"protocol_id": "DEMO_D001", "status": "PASSED_UNDER_PROTOCOL"}
+ plain_freeze = summarize_entry(ledger[0], "DEMO_D001", every)
+ assert plain_freeze == {"protocol_id": "DEMO_D001", "version": "1"} # this protocol has no question
+
+
+def test_empty_ledger_discloses_to_a_manifest(store: Store) -> None:
+ from protocolith.core import init
+
+ init(store)
+ found = build_disclosure(store, policy())
+ assert found.head_seq is None and found.head_hash is None
+ assert verify_disclosure(found.data).ok
+ report = verify_disclosure(found.data)
+ assert report.head_seq is None and report.entries == 0
+
+
+def test_a_ledger_that_fails_verification_is_never_disclosed(rich: Store) -> None:
+ rich.ledger_path.write_bytes(rich.ledger_path.read_bytes().replace(b"PASSED_UNDER_PROTOCOL", b"PASSED_UNDER_PROTOCOX", 1))
+ with pytest.raises(VerificationFailed):
+ build_disclosure(rich, policy())
+
+
+def test_build_accepts_a_path(rich: Store) -> None:
+ assert build_disclosure(rich.path, policy()).head_seq == 5
+
+
+def test_warning_when_a_record_is_shown_more_than_its_freeze(rich: Store) -> None:
+ found = build_disclosure(rich, policy(rules=[{"seq": 0, "level": "hidden"}, {"seq": 1, "level": "full"}], default="summary"))
+ assert found.warnings == ["seq 1: the record is shown more than the freeze of protocol DEMO_D001"]
+ assert build_disclosure(rich, policy(default="full")).warnings == []
+ assert build_disclosure(rich, policy(default="hidden")).warnings == []
+
+
+# ---------------------------------------------------------------- verify
+
+def disclosed(rich: Store, **changes: Any) -> bytes:
+ return build_disclosure(rich, policy(default="summary", **changes)).data
+
+
+def test_verify_accepts_what_build_writes(rich: Store) -> None:
+ for default in ("full", "summary", "hidden"):
+ data = build_disclosure(rich, policy(default=default)).data
+ report = verify_disclosure(data)
+ assert report.ok and report.entries == 6 and report.head_seq == 5 and report.codes == []
+ assert report.to_dict()["counts"][default] == 6 and "anchors" not in report.to_dict()
+ mixed = build_disclosure(rich, policy(default="hidden", rules=[{"seq": [0, 1], "level": "full"}, {"seq": 2, "level": "summary"}])).data
+ assert verify_disclosure(mixed).ok
+
+
+def mutate(data: bytes, index: int, change: Any) -> bytes:
+ rows = data.splitlines()
+ obj = json.loads(rows[index])
+ change(obj)
+ rows[index] = encode(obj)
+ return b"\n".join(rows) + b"\n"
+
+
+def codes(data: bytes) -> set[str]:
+ return set(verify_disclosure(data).codes)
+
+
+def test_verify_finds_edits(rich: Store) -> None:
+ full = build_disclosure(rich, policy(default="full")).data
+ summary = disclosed(rich)
+ assert codes(mutate(full, 2, lambda o: o["entry"]["body"].__setitem__("run_id", "x"))) == {"DISCLOSURE_HASH"}
+ assert "DISCLOSURE_CHAIN" in codes(mutate(summary, 3, lambda o: o.__setitem__("prev", "f" * 64)))
+ assert "BAD_DISCLOSURE" in codes(mutate(summary, 3, lambda o: o.__setitem__("seq", 9)))
+ assert "BAD_DISCLOSURE" in codes(mutate(summary, 3, lambda o: o.__setitem__("extra", 1)))
+ assert "BAD_DISCLOSURE" in codes(mutate(summary, 3, lambda o: o.__setitem__("level", "secret")))
+ assert "BAD_DISCLOSURE" in codes(mutate(summary, 3, lambda o: o.__setitem__("hash", "nothex")))
+ assert "BAD_DISCLOSURE" in codes(mutate(summary, 3, lambda o: o.__setitem__("ts", "yesterday")))
+ assert "BAD_DISCLOSURE" in codes(mutate(summary, 3, lambda o: o.__setitem__("type", "magic")))
+ assert "BAD_DISCLOSURE" in codes(mutate(summary, 3, lambda o: o.__setitem__("summary", [])))
+ assert "BAD_DISCLOSURE" in codes(mutate(full, 3, lambda o: o["entry"].__setitem__("seq", 7)))
+ assert "BAD_DISCLOSURE" in codes(mutate(full, 3, lambda o: o["entry"].pop("body")))
+ assert "BAD_DISCLOSURE" in codes(mutate(full, 3, lambda o: o.__setitem__("entry", 5)))
+ assert "BAD_DISCLOSURE" in codes(mutate(full, 3, lambda o: o.__setitem__("seq", True)))
+
+
+def test_verify_finds_dropped_reordered_and_manifest_lies(rich: Store) -> None:
+ rows = disclosed(rich).splitlines()
+ dropped = b"\n".join(rows[:3] + rows[4:]) + b"\n"
+ assert codes(dropped) >= {"BAD_DISCLOSURE"}
+ swapped = b"\n".join(rows[:2] + [rows[3], rows[2]] + rows[4:]) + b"\n"
+ assert codes(swapped)
+ truncated = b"\n".join(rows[:-1]) + b"\n"
+ assert codes(truncated) == {"BAD_DISCLOSURE"}
+ assert codes(mutate(disclosed(rich), 0, lambda o: o.__setitem__("kind", "other"))) == {"BAD_DISCLOSURE"}
+ assert codes(mutate(disclosed(rich), 0, lambda o: o.__setitem__("entries", 9))) == {"BAD_DISCLOSURE"}
+ assert codes(mutate(disclosed(rich), 0, lambda o: o["counts"].__setitem__("full", 1))) == {"BAD_DISCLOSURE"}
+ assert codes(mutate(disclosed(rich), 0, lambda o: o.__setitem__("head_hash", "a" * 64))) == {"BAD_DISCLOSURE"}
+
+
+def test_a_damaged_line_in_the_middle_is_reported_and_skipped(rich: Store) -> None:
+ rows = disclosed(rich).splitlines()
+ rows[3] = b"not json"
+ report = verify_disclosure(b"\n".join(rows) + b"\n")
+ assert not report.ok and "BAD_DISCLOSURE" in report.codes
+
+
+def test_verify_rejects_bad_files() -> None:
+ assert codes(b"") == {"BAD_DISCLOSURE"}
+ assert codes(b"{}") == {"BAD_DISCLOSURE"} # no final newline
+ assert codes(b"not json\n") == {"BAD_DISCLOSURE"}
+ assert codes(b"[]\n") == {"BAD_DISCLOSURE"}
+ assert codes(b'{"b": 1, "a": 2}\n') == {"BAD_DISCLOSURE"} # valid JSON, not canonical
+ report = verify_disclosure(b"not json\n")
+ assert not report.ok and report.to_dict()["ok"] is False
+
+
+def test_verify_checks_anchors(rich: Store, tmp_path: Path) -> None:
+ anchor_head(rich, clock=clock(NOW))
+ data = disclosed(rich)
+ report = verify_disclosure(data, rich.anchors_dir)
+ assert report.ok and report.anchors == 1 and report.to_dict()["anchors"] == 1
+ # a disclosure of a rewritten history: same shape, other hashes
+ other = tmp_path / "other"
+ freeze(Store(other), {**protocol(), "gate": "changed"}, clock=clock(NOW))
+ forged = build_disclosure(Store(other), policy()).data
+ assert "ANCHOR_AHEAD" in set(verify_disclosure(forged, rich.anchors_dir).codes)
+ # same length, different history
+ store2 = Store(tmp_path / "two")
+ for number in range(6):
+ freeze(store2, {**protocol(), "protocol_id": f"P{number}"}, clock=clock(NOW))
+ replaced = build_disclosure(store2, policy()).data
+ assert "ANCHOR_MISMATCH" in set(verify_disclosure(replaced, rich.anchors_dir).codes)
+
+
+# ---------------------------------------------------------------- reveal
+
+def test_reveal_matches_hidden_summary_and_full_entries(rich: Store) -> None:
+ ledger = entries(rich)
+ data = build_disclosure(rich, policy(rules=[{"seq": 0, "level": "full"}, {"seq": [1, 3, 4], "level": "summary"}])).data
+ assert verify_reveal(data, ledger[0]) == {"level": "full", "matches": True, "reason": None, "seq": 0}
+ assert verify_reveal(data, ledger[1])["level"] == "summary"
+ assert verify_reveal(data, ledger[3])["matches"] is True
+ assert verify_reveal(data, ledger[2])["level"] == "hidden"
+ assert verify_reveal(data, ledger[5])["matches"] is True
+
+
+def test_reveal_refuses_a_substitute(rich: Store) -> None:
+ ledger = entries(rich)
+ data = build_disclosure(rich, policy(rules=[{"seq": [1, 3], "level": "summary"}])).data
+
+ def result(entry: Any) -> dict[str, Any]:
+ return verify_reveal(data, entry)
+
+ assert not result("text")["matches"] and not result({})["matches"]
+ forged = json.loads(json.dumps(ledger[1]))
+ forged["body"]["status"] = "NEGATIVE_RESULT_UNDER_PROTOCOL" # hash no longer matches
+ assert "own hash" in result(forged)["reason"]
+ other = json.loads(json.dumps(ledger[1]))
+ other["body"]["run_id"] = "other"
+ other["hash"] = disclosure_module.entry_hash(other) # self-consistent but not the published one
+ assert "not the one" in result(other)["reason"]
+ assert "no entry" in result({**ledger[1], "seq": 99, "hash": disclosure_module.entry_hash({**ledger[1], "seq": 99})})["reason"]
+ assert "no entry" in result({**ledger[1], "seq": "1", "hash": disclosure_module.entry_hash({**ledger[1], "seq": "1"})})["reason"]
+ # a summary that lies: same hash, but the disclosure claims another status
+ lying = mutate(data, 2, lambda o: o["summary"].__setitem__("status", "NEGATIVE_RESULT_UNDER_PROTOCOL"))
+ assert "summary does not match" in verify_reveal(lying, ledger[1])["reason"]
+ wrong_type = mutate(data, 2, lambda o: o.__setitem__("type", "issue"))
+ assert "summary does not match" in verify_reveal(wrong_type, ledger[1])["reason"]
+
+
+def test_reveal_needs_a_valid_disclosure(rich: Store) -> None:
+ with pytest.raises(InputError) as caught:
+ verify_reveal(b"nonsense\n", entries(rich)[0])
+ assert caught.value.code == "BAD_DISCLOSURE"
+
+
+# ---------------------------------------------------------------- atlas
+
+def atlas_data(page: bytes) -> dict[str, Any]:
+ text = page.decode("utf-8")
+ start = text.index('id="atlas-data"')
+ start = text.index(">", start) + 1
+ return json.loads(text[start : text.index("", start)].replace("\\u003c", "<"))
+
+
+def test_atlas_with_a_policy_shows_full_summary_and_hidden_rows(rich: Store) -> None:
+ p = policy(rules=[{"protocol_id": "DEMO_D001", "level": "full"}, {"protocol_id": "OTHER_D002", "level": "hidden"}])
+ data = atlas_data(build_atlas(store=rich, policy=p))
+ assert data["statuses"] == {"HIDDEN": 1, "PASSED_UNDER_PROTOCOL": 1}
+ disclosure = [g for g in data["integrity"] if g["kind"] == "disclosure"][0]
+ assert disclosure["counts"] == {"full": 4, "hidden": 1, "summary": 0} or disclosure["counts"]["hidden"] >= 1
+ hidden = [row for row in data["rows"] if row[2] == "HIDDEN"][0]
+ assert hidden[0].startswith("HIDDEN-") and hidden[1] is None and hidden[6] is None
+ s = atlas_data(build_atlas(store=rich, policy=policy(default="summary")))
+ assert sorted(s["statuses"]) == ["NEGATIVE_RESULT_UNDER_PROTOCOL", "PASSED_UNDER_PROTOCOL"]
+ row = [r for r in s["rows"] if r[2] == "PASSED_UNDER_PROTOCOL"][0]
+ assert row[0] == "LEDGER-RECORD-000001" and row[1] == "DEMO_D001" and row[5] == "2026-11-15"
+ wide = atlas_data(build_atlas(store=rich, policy=policy(default="summary", summary_fields=["outcome", "run_id", "public_claim_text"])))
+ assert wide["rows"][0][2] is not None
+
+
+def test_atlas_without_a_policy_is_unchanged(rich: Store) -> None:
+ data = atlas_data(build_atlas(store=rich))
+ assert all(g["kind"] != "disclosure" for g in data["integrity"])
+
+
+def test_atlas_policy_needs_a_ledger(rich: Store, tmp_path: Path) -> None:
+ with pytest.raises(InputError) as caught:
+ build_atlas(cards=[tmp_path], policy=policy())
+ assert caught.value.code == "BAD_ENTRY"
+ with pytest.raises(InputError) as caught:
+ build_atlas(store=rich, cards=[tmp_path], policy=policy())
+ assert caught.value.code == "BAD_ENTRY"
+
+
+def test_atlas_policy_without_a_source_is_refused(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.chdir(tmp_path)
+ (tmp_path / "docs" / "evidence_cards").mkdir(parents=True)
+ with pytest.raises(InputError) as caught:
+ build_atlas(policy=policy())
+ assert caught.value.code == "NO_SOURCE"
+
+
+# ---------------------------------------------------------------- CLI
+
+def run(capsys: pytest.CaptureFixture[str], *argv: str) -> tuple[int, str, str]:
+ code = main(list(argv))
+ captured = capsys.readouterr()
+ return code, captured.out, captured.err
+
+
+def write_policy(tmp_path: Path, **changes: Any) -> str:
+ path = tmp_path / "policy.json"
+ path.write_text(json.dumps({"v": 1, "default": "summary", **changes}), encoding="utf-8")
+ return str(path)
+
+
+def test_cli_disclose_and_verify(rich: Store, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
+ out = tmp_path / "pub" / "d.jsonl"
+ pol = write_policy(tmp_path, rules=[{"seq": 0, "level": "full"}, {"seq": 5, "level": "hidden"}])
+ code, text, err = run(capsys, "disclose", "--store", str(rich.path), "--policy", pol, "--out", str(out))
+ assert code == 0 and "entries=6 full=1 summary=4 hidden=1" in text and err == ""
+ code, text, _ = run(capsys, "verify-disclosure", str(out))
+ assert code == 0 and text.startswith("OK entries=6 full=1 summary=4 hidden=1 head seq=5")
+ anchor_head(rich, clock=clock(NOW))
+ code, text, _ = run(capsys, "verify-disclosure", str(out), "--anchors", str(rich.anchors_dir))
+ assert code == 0 and text.rstrip().endswith("anchors=1")
+ entry = tmp_path / "entry.json"
+ entry.write_text(json.dumps(entries(rich)[1]), encoding="utf-8")
+ code, text, _ = run(capsys, "verify-disclosure", str(out), "--reveal", str(entry))
+ assert code == 0 and "reveal seq=1 level=summary: MATCHES" in text
+ code, text, _ = run(capsys, "verify-disclosure", str(out), "--reveal", str(tmp_path / "policy.json"))
+ assert code == 1 and "DIFFERENT" in text
+ code, text, _ = run(capsys, "verify-disclosure", str(out), "--json", "--reveal", str(entry))
+ assert code == 0 and json.loads(text)["reveal"]["matches"] is True
+
+
+def test_cli_disclose_warns_json_and_errors(rich: Store, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
+ pol = write_policy(tmp_path, rules=[{"seq": 0, "level": "hidden"}, {"seq": 1, "level": "full"}])
+ code, text, _ = run(capsys, "disclose", "--store", str(rich.path), "--policy", pol, "--out", str(tmp_path / "o.jsonl"), "--json")
+ assert code == 0 and json.loads(text)["warnings"]
+ code, text, _ = run(capsys, "disclose", "--store", str(rich.path), "--policy", pol, "--out", str(tmp_path / "o2.jsonl"))
+ assert "warning: seq 1" in text
+ code, _, err = run(capsys, "disclose", "--store", str(rich.path), "--policy", str(tmp_path / "none.json"))
+ assert code == 3
+ bad = tmp_path / "bad.json"
+ bad.write_text('{"default": "x"}', encoding="utf-8")
+ code, _, err = run(capsys, "disclose", "--store", str(rich.path), "--policy", str(bad))
+ assert code == 2 and "BAD_POLICY" in err and "hint (BAD_POLICY)" in err
+ empty = Store(tmp_path / "empty")
+ from protocolith.core import init
+
+ init(empty)
+ code, text, _ = run(capsys, "disclose", "--store", str(empty.path), "--policy", pol, "--out", str(tmp_path / "e.jsonl"))
+ assert code == 0 and "empty" in text
+
+
+def test_cli_verify_disclosure_failures(rich: Store, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
+ out = tmp_path / "d.jsonl"
+ run(capsys, "disclose", "--store", str(rich.path), "--policy", write_policy(tmp_path), "--out", str(out))
+ out.write_bytes(out.read_bytes().replace(b"PASSED_UNDER_PROTOCOL", b"PASSED_UNDER_PROTOCOX", 1))
+ code, text, err = run(capsys, "verify-disclosure", str(out))
+ assert code == 0 # an edited summary is not detectable without a reveal; the chain is intact
+ out.write_bytes(out.read_bytes()[:-5])
+ code, text, err = run(capsys, "verify-disclosure", str(out))
+ assert code == 1 and text.startswith("FAILED: BAD_DISCLOSURE") and "hint (BAD_DISCLOSURE)" in err
+ code, text, _ = run(capsys, "verify-disclosure", str(out), "--json")
+ assert code == 1 and json.loads(text)["ok"] is False
+ code, _, err = run(capsys, "verify-disclosure", str(tmp_path / "missing.jsonl"))
+ assert code == 3
+ good = tmp_path / "g.jsonl"
+ run(capsys, "disclose", "--store", str(rich.path), "--policy", write_policy(tmp_path), "--out", str(good))
+ code, _, err = run(capsys, "verify-disclosure", str(good), "--reveal", str(tmp_path / "missing.json"))
+ assert code == 3
+
+
+def test_cli_atlas_policy_and_schema(rich: Store, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
+ out = tmp_path / "a.html"
+ code, text, _ = run(capsys, "atlas", "--store", str(rich.path), "--policy", write_policy(tmp_path, default="hidden"), "--out", str(out))
+ assert code == 0 and out.is_file() and "records=2" in text
+ code, text, _ = run(capsys, "schema", "policy")
+ assert code == 0 and json.loads(text)["title"] == "protocolith policy"
+ code, _, err = run(capsys, "atlas", "--store", str(rich.path), "--policy", str(tmp_path / "nope.json"))
+ assert code == 3
+
+
+# ---------------------------------------------------------------- MCP
+
+def tool(store: Store, name: str, arguments: dict[str, Any]) -> tuple[bool, Any]:
+ message = {"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": arguments}}
+ reply = json.loads(handle_line(json.dumps(message).encode(), store, clock(NOW)) or b"{}")
+ result = reply["result"]
+ return result["isError"], json.loads(result["content"][0]["text"])
+
+
+def test_mcp_disclose_verify_and_reveal(rich: Store, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.chdir(tmp_path)
+ error, data = tool(rich, "protocolith_disclose", {"policy": {"default": "summary"}, "out": "pub/d.jsonl"})
+ assert not error and data["path"] == "pub/d.jsonl" and data["counts"]["summary"] == 6
+ error, data = tool(rich, "protocolith_verify_disclosure", {"file": "pub/d.jsonl"})
+ assert not error and data["ok"] and data["reveal"] is None
+ error, data = tool(rich, "protocolith_verify_disclosure", {"file": "pub/d.jsonl", "reveal": entries(rich)[1]})
+ assert not error and data["reveal"]["matches"] is True
+ error, data = tool(rich, "protocolith_verify_disclosure", {"file": "pub/d.jsonl", "reveal": {"seq": 1}})
+ assert error and data["ok"] is False
+ anchor_head(rich, clock=clock(NOW))
+ anchors = tmp_path / "anchors"
+ anchors.mkdir()
+ for path in rich.anchors_dir.glob("*.json"):
+ (anchors / path.name).write_bytes(path.read_bytes())
+ error, data = tool(rich, "protocolith_verify_disclosure", {"file": "pub/d.jsonl", "anchors": "anchors"})
+ assert not error and data["anchors"] == 1
+ (tmp_path / "pub" / "d.jsonl").write_bytes(b"junk\n")
+ error, data = tool(rich, "protocolith_verify_disclosure", {"file": "pub/d.jsonl", "reveal": entries(rich)[1]})
+ assert error and data["reveal"] is None
+
+
+def test_mcp_disclose_default_path_and_bad_policy(rich: Store, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.chdir(tmp_path)
+ error, data = tool(rich, "protocolith_disclose", {"policy": {}})
+ assert not error and data["path"] == "disclosure.jsonl" and (tmp_path / "disclosure.jsonl").is_file()
+ error, data = tool(rich, "protocolith_disclose", {"policy": {"default": "nope"}})
+ assert error and data["error"]["code"] == "BAD_POLICY" if "error" in data else error
+ error, data = tool(rich, "protocolith_disclose", {"policy": {}, "out": "../outside.jsonl"})
+ assert error
+
+
+def test_mcp_atlas_with_a_policy(rich: Store, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.chdir(tmp_path)
+ error, data = tool(rich, "protocolith_atlas", {"policy": {"default": "hidden"}, "out": "a.html"})
+ assert not error and data["cards"] == 2
+ page = (tmp_path / "a.html").read_bytes()
+ assert b"HIDDEN-000001" in page
+
+
+def test_mcp_schema_names_the_policy(rich: Store) -> None:
+ error, data = tool(rich, "protocolith_schema", {"name": "policy"})
+ assert not error and data["title"] == "protocolith policy"
diff --git a/tests/core/test_mcp.py b/tests/core/test_mcp.py
index f42d81ed8..ec8a900c2 100644
--- a/tests/core/test_mcp.py
+++ b/tests/core/test_mcp.py
@@ -59,7 +59,7 @@ def test_tools_list_names_and_schemas(store: Store) -> None:
assert [t["name"] for t in tools] == [
"protocolith_freeze", "protocolith_record", "protocolith_deviation",
"protocolith_verify", "protocolith_claim_check", "protocolith_anchor", "protocolith_issue", "protocolith_log", "protocolith_show",
- "protocolith_summary", "protocolith_capture", "protocolith_atlas", "protocolith_schema",
+ "protocolith_summary", "protocolith_capture", "protocolith_atlas", "protocolith_disclose", "protocolith_verify_disclosure", "protocolith_schema",
] # fmt: skip
for entry in tools:
schema = entry["inputSchema"]
@@ -163,7 +163,7 @@ def test_serve_loop_skips_blank_lines_and_writes_only_replies(store: Store) -> N
def test_tools_table_matches_the_spec_names() -> None:
- assert set(TOOLS) == {f"protocolith_{n}" for n in ("freeze", "record", "deviation", "verify", "issue", "log", "show", "summary", "capture", "atlas", "schema", "claim_check", "anchor")}
+ assert set(TOOLS) == {f"protocolith_{n}" for n in ("freeze", "record", "deviation", "verify", "issue", "log", "show", "summary", "capture", "atlas", "schema", "claim_check", "anchor", "disclose", "verify_disclosure")}
def test_stdio_subprocess(tmp_path: Any) -> None:
diff --git a/tests/core/test_vectors.py b/tests/core/test_vectors.py
index 92562c2c9..1a87564db 100644
--- a/tests/core/test_vectors.py
+++ b/tests/core/test_vectors.py
@@ -91,6 +91,19 @@ def test_every_rule_has_a_failing_vector() -> None:
assert {f"R{n}" for n in range(1, 12)} <= rules
+@pytest.mark.parametrize("case", cases("disclosures.json"), ids=lambda c: c["name"])
+def test_disclosure_vector(case: dict[str, Any]) -> None:
+ from protocolith.core import parse_policy, verify_disclosure
+ from protocolith.core.disclosure import disclose_verifier
+
+ report = verify_disclosure(case["disclosure"].encode("utf-8"))
+ assert report.ok == case["expect"]["ok"] and report.codes == case["expect"]["codes"]
+ if "ledger" in case:
+ _, verifier = scan(case["ledger"].encode("utf-8"), card_hash)
+ built = disclose_verifier(verifier, parse_policy(case["policy"]))
+ assert built.data.decode("utf-8") == case["disclosure"] and built.counts == case["expect"]["counts"]
+
+
@pytest.mark.parametrize("case", cases("anchors.json"), ids=lambda c: c["name"])
def test_anchor_vector(case: dict[str, Any]) -> None:
from protocolith.core.anchor import anchor_name, build_statement
diff --git a/tests/test_publication_guard.py b/tests/test_publication_guard.py
index 0b6107cf6..352840f90 100644
--- a/tests/test_publication_guard.py
+++ b/tests/test_publication_guard.py
@@ -38,7 +38,10 @@
TEXT_SUFFIXES = {".py", ".md", ".toml", ".txt", ".json", ".yml", ".yaml"}
RAW_PAYLOAD_SUFFIXES = {".csv", ".parquet", ".zip", ".jsonl", ".env", ".key", ".pem"}
# Ledgers that are published on purpose as example evidence (not raw payloads).
-PUBLISHED_LEDGERS = {"examples/phantom_mean_reversion/evidence/.protocolith/ledger.jsonl"}
+PUBLISHED_LEDGERS = {
+ "examples/phantom_mean_reversion/evidence/.protocolith/ledger.jsonl",
+ "examples/selective_disclosure/public/disclosure.jsonl",
+}
RAW_PAYLOAD_DIR_NAMES = {"raw", "payloads", "data"}
diff --git a/tests/test_readme_examples.py b/tests/test_readme_examples.py
index 2b6584e4f..e63d29fc8 100644
--- a/tests/test_readme_examples.py
+++ b/tests/test_readme_examples.py
@@ -152,7 +152,7 @@ def test_readme_mcp_tool_names(workdir: Path) -> None:
assert done.returncode == 0, done.stderr
replies = [json.loads(line) for line in done.stdout.splitlines()]
names = [tool["name"] for tool in replies[1]["result"]["tools"]]
- assert len(names) == 13
+ assert len(names) == 15
for name in names:
assert name in text
config = re.search(r"```json\n(\{\n \"mcpServers\".*?)```", text, re.S)
diff --git a/uv.lock b/uv.lock
index cbb61ccc5..04700b569 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1280,7 +1280,7 @@ wheels = [
[[package]]
name = "protocolith"
-version = "0.6.0"
+version = "0.7.0"
source = { editable = "." }
[package.optional-dependencies]