Repository navigation
Stop caching file: text; validate DOI quotes against local full text and sign excerpts - #176
Conversation
…and sign excerpts #173: file: references are no longer written to any cache unless cache_local_files is set, and file: IDs are named relative to reference_base_dir (or CWD) so entries carry no home directory. #174: local_full_text / local_full_text_dir map a cited reference ID to a local file whose text is matched but never cached. New `excerpts sign` writes snippet-only bundles with a verification record (source SHA-256, validator version, date) and source_char_count. Optional signed_excerpts_require_verification makes validation ignore unrecorded excerpts. Also fixes __version__ always reporting 0.0.0, and moves schema-free evidence extraction to validation/evidence_items.py for reuse. Closes #173 Closes #174 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Claude finished @caufieldjh's task in 1m 44s —— View job PR review: stop caching
|
…esolution - local_full_text_dir resolves a relative directory against reference_base_dir, like local_full_text values. - excerpts sign uses the same bundle names as validation (usual, then disambiguated stem) and never merges into a bundle recording another reference_id. - A bundle whose merged quotes exceed max_total_chars_per_reference or max_reference_fraction is not written; nor is one whose source changed while its quotes were checked. - New --prune removes excerpts this command signed earlier that are no longer cited; excerpts from elsewhere are kept. - Docs recommend reference_base_dir with cache_local_files. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Claude finished @caufieldjh's task in 1m 10s —— View job PR review (after
|
| # | Point | Status |
|---|---|---|
| 1 | Relative local_full_text_dir |
✅ Now resolved with FileSource.resolve_path, with a test |
| 2 | _bundle_path naming collisions |
✅ Tries the same file names as validation, skips a bundle whose reference_id is different, has a doctest and a test (see point 3 below for one leftover gap) |
| 3 | Bundle growing past the caps | ✅ Caps are checked on the whole merged bundle, and --prune was added |
| 4 | Relative file: IDs |
✅ Docs now recommend reference_base_dir |
| 5 | Hash vs. text checked | ✅ The hash is compared before and after checking, and the bundle isn't written if it changed |
| – | Docstring, cache reference test |
✅ |
New problems
1. --prune can delete signed quotes when it shouldn't (excerpt_signing.py:372, _merge).
- A wrong local file wipes the bundle. If every quote fails (for example, the mapping points at the preprint instead of the published paper),
verifiedis empty.--prunethen goes ahead and removes every excerpt this command signed earlier. The bundle is still written, even though the command exits 1. Failures don't stop the write, so one wrong file deletes good excerpts.- Suggestion: skip pruning for any reference that had a failed quote in this run, or don't write the bundle at all when there are failures.
- Running on some of the data files.
excerpts sign one_file.yaml --pruneremoves quotes for the same reference that are cited in data files you didn't pass. The docs should say to pass every data file with--prune. - References no longer cited are never pruned. The loop only covers references found in
collect_quotes. If a reference is dropped from the data entirely, its bundle keeps every excerpt. The docs say--pruneremoves excerpts "the data no longer cites", which isn't true for this case.- Either document that, or with
--prunealso go through the bundles indirectorywhose reference has local text but no quotes this run. (Pruning without local text could also work, since it needs no verification.)
- Either document that, or with
2. The cap is only checked when the bundle changes (excerpt_signing.py:385). _bundle_cap_problem runs only after _merge returns True. An over-cap bundle that doesn't change is reported as "unchanged" and exits 0, including under --check. That happens if the bundle was edited by hand or by an agent, or if the caps were lowered later. Since --check is what CI runs, it would be worth checking the cap on every bundle it visits. Also, the over-cap message could suggest --prune, because without it the user can't get back under the cap except by editing the file.
3. The signer and the validator compare reference_id differently (excerpt_signing.py:149). The validator normalizes the stored ID first: _same_reference_id(self.fetcher.normalize_reference_id(str(stored_id)), normalized_id) in supporting_text_validator.py:639. _bundle_path compares the raw stored string. Suppose a hand-written bundle records reference_id: pmid:1, PMID: 1 or a https://doi.org/... form. The signer treats it as another reference's bundle and writes a new one under the disambiguated name. The validator still matches the usual name first, so the newly signed quotes are never read. To fix this, normalize stored with the fetcher, as the validator does (pass the fetcher, or a normalize callable, into _bundle_path).
4. Unlikely edge case in _bundle_path. When the usual name is taken, the fallback returns stems[1] even if that file exists and records a third reference ID. That would need a hash prefix collision, so it's very unlikely. Returning a distinct name, or raising, would make it fail loudly rather than merge into the wrong bundle.
Minor
- The CLI summary now says
N problem(s). Failures with no quote text print on one line, which is fine. _source_text_statsreads the file twice per reference. The cost is negligible.
Test coverage
The new tests cover the collision, both cumulative caps, pruning, a file edited mid-run, the relative directory and cache reference. Tests worth adding:
--prunewhen every quote for a reference fails, so a wrong local file doesn't wipe the bundle (point 1).--checkon an over-cap bundle that hasn't changed (point 2).- A bundle whose
reference_idis written in a non-normalized form (point 3).
Not run
The project's dependencies (uv, pydantic) aren't installed in this runner, so I couldn't run the tests, mypy or ruff. This review comes from reading the code.
…rmalization - --prune skips a reference with any failed quote, so a wrongly mapped file cannot delete good excerpts; it also prunes signed excerpts from bundles for references the data no longer cites. - Fair-use caps are checked on every bundle visited, so --check reports an unchanged bundle that is over them; the message suggests --prune. - Bundle lookup normalizes the stored reference_id as validation does. - When other references hold both bundle names, report a failure instead of merging into the wrong bundle. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Claude finished @caufieldjh's task in 1m 6s —— View job PR review (after
|
| # | Point | Status |
|---|---|---|
| 1 | --prune deleting good excerpts |
✅ A reference with any failed quote is not pruned (prune_here), and that is tested. The docs now say to pass every data file. References the data no longer cites are now pruned, except when --reference is given. |
| 2 | Cap only checked when a bundle changes | ✅ _update_bundle checks the caps before the unchanged early return, and the message points to --prune |
| 3 | reference_id not normalized |
✅ _bundle_path takes a normalize callable, and the signer passes fetcher.normalize_reference_id |
| 4 | Both bundle names taken | ✅ Returns None, which is reported as a failure |
New problems
1. The pass over uncited bundles can write the wrong file (excerpt_signing.py:409-421).
The loop globs every *.yaml/*.yml in the directory and reads its reference_id. It then calls _update_bundle(normalized_id, …), which looks the bundle up again with _bundle_path. That second lookup only tries the cache-stem names, so it can return a different file from the one the loop is visiting:
- A bundle with a non-standard name, e.g. a hand-named
smith2020.yamlcontainingreference_id: PMID:5._bundle_pathreturnsPMID_5.yaml, which doesn't exist._update_bundlestarts a freshCommentedMap, and_mergesetsexcerpts = []and returnschanged=True. The result is a new emptyPMID_5.yaml, andsmith2020.yamlis never pruned. With--check --prunethe first run reports it as out of date. - Both
X.yamlandX.ymlfor one reference. Both resolve toX.yaml, so that file is processed twice and the.ymlfile is never pruned.
Validation ignores files with non-standard names, so this doesn't break validation. It does write junk files and leave the excerpts it meant to remove. The simplest fix is to skip a file unless _bundle_path(directory, normalized, normalize) == path. Another option is to pass path into _update_bundle directly.
2. A small gap in the "every bundle visited" cap check (excerpt_signing.py:394). if not verified and not prune_here: continue runs before _update_bundle. If every quote for a reference fails and --prune isn't given, that reference's bundle is not cap-checked. This barely matters, since those failures already make the command exit 1. The docs ("checked for every bundle visited") are still accurate if "visited" is read narrowly.
3. Uncited bundles that are still over the cap fail every --prune run. An uncited bundle can hold entries from a private store that --prune keeps. If those alone exceed max_total_chars_per_reference, the uncited pass reports a cap failure on every --prune run, and the user can't fix it with the signer. That is arguably correct behaviour, but a sentence in the docs would save someone some confusion.
Code quality
_update_bundletakes 12 parameters, and both call sites pass them all positionally (report, yaml, directory, normalized, …, [], None, None, None, True, dry_run). The second call is hard to check by eye. Passing them by keyword, at least fromverifiedonward, would help.- In the uncited pass,
verification or {"source_sha256": ""}is never read becauseverifiedis empty. It's harmless, but_mergecould acceptOptional[dict]instead.
Performance and security
No concerns. The new pass reads each bundle once with YAML(typ="safe") and does no network calls. normalize_reference_id only rewrites strings (and resolves paths for file: IDs).
Test coverage
The six new tests match the commit's changes. Worth adding:
--prunewith a bundle whose file name is non-standard and whose reference the data no longer cites (point 1).- A
.yaml/.ymlpair for one reference under--prune.
Not run
uv and the project's dependencies (pydantic, ruamel.yaml) aren't installed in this runner, so I couldn't run the tests, mypy or ruff. This review comes from reading the code.
…ndle The uncited-bundle prune pass now skips a file unless it is the one _bundle_path resolves for its reference, so a hand-named bundle or the .yml twin of a .yaml is not mistaken for another file and no empty bundle is written. Docs note that excerpts from elsewhere over a cap are reported on every --prune run. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Claude finished @caufieldjh's task in 42s —— View job PR review (after
|
| # | Point | Status |
|---|---|---|
| 1 | The pass over uncited bundles could write the wrong file | ✅ Fixed. A file is now skipped unless _bundle_path(directory, normalized, normalize) == path (excerpt_signing.py:426). The new test covers a hand-named smith2020.yaml (no empty PMID_5.yaml is written) and a .yaml/.yml pair (processed once). |
| 2 | Cap check skipped when a reference's quotes all failed | ✅ The docs now say "every bundle the command would write to", which matches the code |
| 3 | Uncited bundles still over the cap fail every --prune run |
✅ Documented, with "trim it by hand" |
| – | 12 positional arguments to _update_bundle |
✅ Arguments after validator are keyword-only (*) |
| – | Placeholder {"source_sha256": ""} |
✅ _merge accepts Optional[dict] and returns early when it is None. Pruning runs before that return, so it still happens. |
I followed the uncited pass through _merge with verification=None, prune=True and verified=[]. It removes every entry signed with local_full_text, keeps entries from elsewhere, and doesn't add anything. That is correct.
Remaining minor points (none blocking)
1. One bad YAML file in signed_excerpts_dir stops the whole --prune run. The uncited pass calls _stored_reference_id on every *.yaml/*.yml file (excerpt_signing.py:416). That uses YAML(typ="safe").load, which raises on malformed YAML. One broken or unrelated file in the directory therefore crashes excerpts sign --prune with a traceback. _bundle_path has the same problem for the two candidate names, but globbing the whole directory makes it far more likely. Reading files the user controls is a case CLAUDE.md allows a try/except for. Catching YAMLError there and recording a SignFailure (or a warning) naming the file would fail more gracefully.
2. A fully pruned bundle is left as an empty file. When every excerpt in an uncited bundle was signed by this command, --prune writes excerpts: [] and keeps the file. That's harmless, since validation just finds no excerpts. Deleting the file might be what users expect, or the docs could say the file is kept. Related: an uncited bundle with no excerpts key gets excerpts: [] added and is reported as written, so --check --prune flags it as out of date once.
3. Test gap: a mixed uncited bundle under --prune. The tests cover pruning signed entries and keeping hand-written ones separately. A test with one uncited bundle holding both kinds would pin down the verification is None early-return path in _merge.
Code quality, performance, security
- The comments and the
_mergedocstring ("verificationmay be None only whenverifiedis empty") are clear. Anassert verification is not None or not verifiedwould enforce that contract cheaply. - Performance: the uncited pass reads each bundle up to three times (
_stored_reference_id,_bundle_path, then the round-trip load in_update_bundle). That's negligible for bundle-sized files. - Security: no new concerns. All loads use safe or round-trip mode, there are no network calls, and writes stay inside
signed_excerpts_dir.
Overall
In my view the PR is ready to merge. The privacy guarantees hold: file: text and local full text are never cached. The attestation model is documented honestly, and the bundle merge/prune/cap behaviour now holds up in the edge cases raised across the three earlier reviews.
Not run
uv isn't installed in this runner, so I couldn't run pytest, mypy or ruff. This review comes from reading the code.
… lists A bundle that is not valid YAML is reported as a sign failure naming the file, rather than stopping the run with a traceback. A bundle with no excerpts list is left untouched when there is nothing to add or prune, so --check --prune does not flag it. Adds a test for pruning a bundle that mixes signed and external entries. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Claude finished @caufieldjh's task in 1m 0s —— View job PR review (after
|
| # | Point | Status |
|---|---|---|
| 1 | A malformed YAML file stops the --prune run |
✅ The uncited pass catches YAMLError and records a SignFailure that names the file. _update_bundle catches it around _bundle_path and the round-trip load. Tested with broken.yaml. |
| 2 | Empty excerpts: [] added to a bundle that had no list |
✅ _merge returns early when there is no list and nothing was verified, so --check --prune no longer flags the file. Tested, and the test checks the file bytes are unchanged. |
| 3 | No test for a mixed uncited bundle | ✅ test_prune_of_a_mixed_uncited_bundle_keeps_entries_from_elsewhere |
I traced the early return in _merge. It comes after the title and source_char_count updates, so those still apply to a bundle with no list. The only caller that reaches it with verified=[] is the uncited pass, which passes None for both, so nothing changes. That is correct.
Small remaining gaps (none blocking)
1. Valid YAML that isn't a mapping still crashes (excerpt_signing.py:485). Take a PMID_1.yaml whose content is a list (- text: foo) or a plain scalar:
_stored_reference_idreturnsNone._bundle_paththen accepts that file.existingis a list, andbundle = existing or CommentedMap(...)passes it to_merge, which callsbundle.get("title"). That raisesAttributeErrorand the run ends with a traceback.
The uncited pass is safe because a None stored ID is skipped, but the main signing path is not. This is the same "user-controlled file" case as the YAMLError handling. The simplest fix is to report a failure when existing is not None and not isinstance(existing, dict), with no extra try.
2. One _bundle_path call is still unguarded (excerpt_signing.py:434). In the uncited pass, if _bundle_path(directory, normalized, ...) != path can read other candidate files for that ID, such as the .yml twin or the disambiguated name. That call is outside the new try, so a malformed sibling still crashes the run. It would take an unusual directory layout. Moving the check inside the try, or letting _bundle_path treat an unreadable candidate as taken, would close this.
3. Non-UTF-8 files. path.read_text(encoding="utf-8") raises UnicodeDecodeError, which isn't a YAMLError. A stray binary or Latin-1 .yaml file in signed_excerpts_dir still crashes --prune. Catching (YAMLError, UnicodeDecodeError) in both places would cover it.
4. Message wording.
- The
_update_bundlefailure says "existing bundle is not valid YAML" but doesn't name the file. The uncited pass does name it. Addingpath.namewould make the two consistent, since with the disambiguated stem the user can't easily tell which file is meant. - The CLI prints these as
NOT signed: broken.yaml is not valid YAML…. That reads a little oddly for a file that has nothing to do with signing.problem:orskipped:might be clearer. This is cosmetic.
5. Exit behaviour, worth documenting. A malformed file anywhere in signed_excerpts_dir now makes every excerpts sign --prune run exit 1. That includes --check --prune in CI, even when the file isn't a bundle. That is a reasonable choice, since it fails loudly rather than silently. A sentence in use-signed-excerpts.md would tell users the directory should contain only bundles. Note that the "malformed bundle … exit 2" line in that doc is about excerpts sync, not sign, so it doesn't conflict with this.
Code quality, performance, security
- Both new
tryblocks are narrow, catch one specific exception type, and have comments explaining why. That fits the CLAUDE.md guidance ontry/except. - No performance changes.
- No security concerns: loads stay in safe or round-trip mode, and nothing is written outside
signed_excerpts_dir.
Test coverage
The three new tests match the commit. A test for gap 1 (a list-valued bundle for a cited reference) would be the one worth adding.
Overall
I still consider this ready to merge. Gaps 1–3 are the same kind of robustness fix as this commit and would each take a few lines. They could go in this PR or a follow-up.
Not run
uv and the project's dependencies (ruamel.yaml, pydantic) aren't installed in this runner, so I couldn't run pytest, mypy or ruff. This review comes from reading the code.
_read_bundle reports a file that is not UTF-8, not valid YAML, or not a mapping as a BundleReadError naming it, and every read of an existing bundle (including the _bundle_path sibling checks in the prune pass) goes through it, so a stray file is reported instead of crashing the run. Docs say signed_excerpts_dir should hold only bundles. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Claude finished @caufieldjh's task in 45s —— View job PR review (after
|
| # | Point | Status |
|---|---|---|
| 1 | A bundle that is valid YAML but not a mapping crashed _merge |
✅ _read_bundle raises BundleReadError for anything that isn't a dict or None, and _update_bundle turns that into a SignFailure. Tested with the list-valued case at the usual stem. |
| 2 | The _bundle_path call in the uncited pass wasn't guarded |
✅ It now sits inside the try. _bundle_path reads through _stored_reference_id → _read_bundle, so a bad sibling is also reported rather than raised. Tested with the .yml twin. |
| 3 | Non-UTF-8 files | ✅ UnicodeDecodeError is caught next to YAMLError. Tested with a Latin-1 café. |
| 4 | Failure message didn't name the file | ✅ The message now always includes path.name, with the prefix nothing written: or skipped: |
| 5 | Exit behaviour wasn't documented | ✅ use-signed-excerpts.md now says to keep only bundles in signed_excerpts_dir |
What I checked
- Round-trip loads still pass the mapping check.
_update_bundlepasses the round-tripyamlto_read_bundle. That loader returns aCommentedMap, which is adictsubclass, so theisinstance(data, dict)check accepts it. Comment and order preservation is unaffected. - Empty file. It loads as
None._stored_reference_idreturnsNoneand the uncited pass skips the file. In the main path,existing or CommentedMap(...)starts a new bundle, the same as before. - Duplicate keys.
DuplicateKeyErrorin ruamel is aMarkedYAMLError, which is aYAMLErrorsubclass, so it is caught too. - The
.ymltest case.PMID_9.yamlis visited first, and_bundle_pathmatches it before it ever reads the.ymlfile. The.ymlfile is then visited on its own, raises, and is reported. The test does check the sibling path it means to cover. - The
tryblock. It is still narrow and catches only a project-specific exception. The oneexceptin_read_bundleis commented as covering user-controlled files. Both follow the CLAUDE.md guidance. - Doctest. The one on
_read_bundlegives the fully qualified exception name on the last line, which doctest accepts.
Minor (cosmetic, not blocking)
- CLI wording. At
cli/excerpts.py:222a failure with no quote text is printed asNOT signed: skipped: broken.yaml is not a bundle: …. That doubles the prefix, and a stray file wasn't something being signed in the first place. Printing these asproblem: …would read better, either whenreference_idis empty or forBundleReadErrorfailures in general. - A broken file blocks a cited reference. If the bundle at the usual stem is unreadable, the cited reference gets
nothing writtenand the command exits 1. I think that is right, since overwriting a file the user may want to recover would be worse. The doc line only mentions--prune, though. It could add that a broken bundle for a cited reference also stops that reference from being signed.
Performance and security
- Performance: no change apart from one extra
isinstancecheck per read. - Security: loads stay in safe or round-trip mode. Nothing is written outside
signed_excerpts_dir. A bad file is now reported, never overwritten.
Test coverage
The three cases in the new parametrized test (not a mapping, not UTF-8, malformed sibling) match the three earlier gaps. Coverage of the signer is thorough.
Overall
Ready to merge. Across the five review rounds, the privacy guarantees (no caching of file: text or local full text), the attestation model, and the merge, prune and cap behaviour have held up, and each fix has a test.
Not run
uv and the project's dependencies aren't installed in this runner, so I couldn't run pytest, mypy or ruff. This review comes from reading the code.
Closes #173. Closes #174.
#173:
file:text is no longer cachedfile:references (text, SVG, drawio) are not written tocache_diror any cache. Validation never read these entries back (Always read file: references from the file, under one canonical id #148), and the file is often a paper the project may not redistribute.cache_local_files: truerestores the old write for your own notes.file:IDs are named relative toreference_base_dir(or the working directory if unset), sofile:/home/me/repo/papers/a.mdbecomesfile:papers/a.mdand cache entries carry no home directory. Files outside it keep their absolute path.cache reference file:...says the file was read but not cached.content_type: local_fileentries written by ≤0.6.0.#174: local full text and
excerpts signlocal_full_text: {DOI:...: papers/x.md}orlocal_full_text_dir(files named by cache stem,.md/.txt,~expanded). If the file exists, quotes for that ID are matched against it, ahead of any fetched text. Metadata is fetched and cached as usual. The file's text is never cached or kept in the memory cache. If the file is absent (CI), behaviour is unchanged.excerpts sign DATA_FILES... [--reference ID] [--check]. Validates each quote against the local file, applying the normal matcher and fair-use caps. Passing quotes go tosigned_excerpts_dir/<stem>.yaml:verification: {method, source_sha256, validator_version, verified_at}. The bundle also getssource_char_count, so CI can applymax_reference_fraction.target_repo) are kept, and an excerpt already verified against the same hash is left alone.--checkfinds drift; 2 for usage errors.signed_excerpts_require_verification(default off) makes validation ignore excerpts with noverification.source_sha256.Also
_version.pycalledversion(__name__), so__version__was always0.0.0. It now reports the package version, which bundles record.cli/repair.pytovalidation/evidence_items.py(still re-exported fromcli/repair.py).Tests
tests/test_file_reference_not_cached.py,tests/test_local_full_text.py,tests/test_excerpts_sign.py(written first).file:is always cached now setcache_local_files=Trueor expect relative IDs.mypyandruff. Remaining failures are intest_pmid_network,test_wikipedia_sourceandtest_bookshelf_provider, where local test servers time out in my sandbox. They fail identically on a cleanmaincheckout.🤖 Generated with Claude Code