Skip to content

Turn any technical book PDF into a Claude Code skill — ready to study, reference, and use while you work.

fix(skill): stop and ask before re-converting an existing skill (re-run guard) (#224)

Neven Sirotić - Scan8610aa5e8561
diff --git a/SKILL.md b/SKILL.md
index 6cc3955..ecc0d97 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -92,10 +92,12 @@ If no arguments are provided, stop and respond:
> "book-to-skill requires a supported document path, folder, or glob pattern. Usage: `book-to-skill <path-to-document-folder-or-glob>... [skill-name-slug]`"
Throughout the workflow:
+- **Resolve the destination root first.** Before any existing-skill lookup, determine where this run would write: the personal or project-local root for the user's host, per the Step 5 table and selection rules — a project-local request uses its project-local root, never the personal root. Below, "the resolved root" means that destination.
- Identify the input paths and the optional skill slug.
- If the last argument is not a file, folder, or glob that exists or matches any files, and it looks like a skill slug (e.g. lowercase hyphens, alphanumeric), treat it as `SKILL_NAME`.
- Treat all other arguments as the list of `INPUT_PATHS`.
-- If any input path is an existing skill directory (contains `SKILL.md` and a `chapters/` sub-folder), or if `SKILL_NAME` matches an existing skill slug in `SKILLS_HOME`, flag this run as an **Update/Fold-in** operation (Mode 4).
+- If any input path is an existing skill directory (contains `SKILL.md` and a `chapters/` sub-folder), or if `SKILL_NAME` matches an existing skill slug in the resolved root, flag this run as an **Update/Fold-in** operation (Mode 4).
+- **Re-run guard.** Before starting extraction for a Full Conversion, derive the prospective skill slug under Step 5's naming options — the author-concept form, the by-title form, and any `SKILL_NAME` given — and check the resolved root for an existing match. On a match, STOP and ask the user: "`<skill-name>` already exists. Choose: (1) Update/Fold-in (Mode 4), (2) verify the existing skill is complete and stop, or (3) force full regeneration." Do not re-extract until the user chooses. On context recovery after an interrupted run (network cut-off, replayed or continued conversation), reuse the extraction work directory that run reported (`Workdir ->` in its output, or the path you set in `BOOK_SKILL_WORKDIR`) **only if it is still intact and still matches the current inputs and options** — the directory exists, its `metadata.json` is readable, the `sources` it lists match the files being converted now one-to-one on filename **and content fingerprint** (the extractor records a per-source `sha256` in `metadata.json`; recompute the fingerprint from each file as it exists now and require an exact match — `reuse_is_safe()` in `book_to_skill/utils.py` is the executable form of this check), and its recorded `extraction_mode` is the mode this run is using (Step 2's "confirm the extraction is the document you asked for" rule). If it is missing (temp cleanup), its `metadata.json` is gone, the sources no longer match (a different filename, or a changed content fingerprint), the recorded metadata has no `sha256` for a source (recorded before fingerprints existed, so freshness cannot be established), or the mode differs, say so and start a fresh extraction instead of resuming. When in doubt, ask the user before discarding or resuming.
---
diff --git a/book_to_skill/pdf_inspector_integration.py b/book_to_skill/pdf_inspector_integration.py
index 2d0d817..cd680f4 100644
--- a/book_to_skill/pdf_inspector_integration.py
+++ b/book_to_skill/pdf_inspector_integration.py
@@ -147,6 +147,12 @@ def _result_from_inspector(
tokens = utils_module.estimate_tokens(text)
try:
file_size_mb = os.path.getsize(input_path) / (1024 * 1024)
+ # Import lazily rather than reaching into the (possibly fake) utils
+ # namespace: existing tests pass a minimal SimpleNamespace as
+ # utils_module, and hashing is a pure function of the file on disk —
+ # it must not depend on which utils object the hook was installed with.
+ from book_to_skill.utils import _sha256_file
+ file_sha256 = _sha256_file(str(input_path))
except OSError as exc:
raise ExtractionError(
f"Could not read file size for {input_path.name}: {exc}"
@@ -158,6 +164,7 @@ def _result_from_inspector(
"format": "pdf",
"extraction_method": "pdf-inspector",
"file_size_mb": round(file_size_mb, 2),
+ "sha256": file_sha256,
"pages": pages,
"pages_label": "pages",
"chars": len(text),
@@ -272,3 +279,4 @@ def enrich_pdf_inspector_metadata(metadata_path: str | Path | None = None) -> No
def _reset_state_for_tests() -> None:
_INSPECTIONS.clear()
+
diff --git a/book_to_skill/utils.py b/book_to_skill/utils.py
index 7b0cff9..bae36bb 100644
--- a/book_to_skill/utils.py
+++ b/book_to_skill/utils.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import glob
+import hashlib
import json
import os
import re
@@ -845,13 +846,84 @@ def resolve_input_files(paths: list[str]) -> list[Path]:
return unique_paths
+def _sha256_file(path: str) -> str:
+ """Streaming sha256 — constant memory for multi-GB sources."""
+ h = hashlib.sha256()
+ with open(path, "rb") as f:
+ for chunk in iter(lambda: f.read(1 << 20), b""):
+ h.update(chunk)
+ return h.hexdigest()
+
+
+def reuse_is_safe(current_inputs, metadata, current_mode):
+ """Decide whether an interrupted run's extraction workdir is safe to resume.
+
+ current_inputs: list of (path, fingerprint) — fingerprint is the sha256
+ hexdigest of each file as it exists NOW, recomputed by the caller
+ (hashlib.sha256(path.read_bytes()).hexdigest(); _sha256_file is available
+ for streaming on large files). Size is deliberately NOT part of matching:
+ metadata.json only records file_size_mb rounded to 2 decimals, so an
+ exact-size comparison is unimplementable — the fingerprint subsumes size
+ entirely.
+
+ metadata: the recorded run's metadata dict (parsed metadata.json).
+ current_mode: the extraction mode THIS run intends ("technical" or "text").
+
+ Returns (ok, reason). ok=True only when ALL hold:
+ - metadata["workdir"] exists and is a directory
+ - metadata["extraction_mode"] == current_mode
+ - the recorded sources match the current inputs one-to-one on
+ filename AND sha256 — the recomputed fingerprints vs the recorded ones
+ Anything else: (False, reason) — the caller must start a fresh
+ extraction (or ask the user when unsure), never resume.
+ """
+ if not isinstance(metadata, dict):
+ return False, "metadata.json unreadable or not an object"
+
+ workdir = metadata.get("workdir")
+ if not workdir or not os.path.isdir(workdir):
+ return False, "workdir missing or unreadable"
+
+ if metadata.get("extraction_mode") != current_mode:
+ return False, (
+ f"mode changed (recorded {metadata.get('extraction_mode')!r}, "
+ f"current is {current_mode!r})"
+ )
+
+ recorded = metadata.get("sources") or []
+ if len(recorded) != len(current_inputs):
+ return False, "sources changed"
+
+ current = {}
+ for path, fingerprint in current_inputs:
+ current[Path(path).name] = fingerprint
+ if len(current) != len(recorded):
+ # Duplicate filenames cannot be matched one-to-one.
+ return False, "sources changed"
+
+ for src in recorded:
+ filename = src.get("filename")
+ if filename not in current:
+ return False, f"sources changed (recorded {filename!r} is not in this run)"
+ recorded_hash = src.get("sha256")
+ if not recorded_hash:
+ return False, (
+ f"no recorded fingerprint for {filename} — legacy metadata "
+ "(recorded before fingerprints existed)"
+ )
+ if recorded_hash != current[filename]:
+ return False, f"content changed for {filename}"
+
+ return True, "workdir intact and all sources match the current inputs"
+
+
def extract_single_file(input_path: Path, extraction_mode: str, install_mode: str) -> dict:
"""Extract text and metadata from a single file path."""
input_str = str(input_path)
-
+
if not input_path.exists():
raise ExtractionError(f"File not found: {input_str}")
-
+
ext = input_path.suffix.lower()
document_format = ext.lstrip(".")
@@ -1050,17 +1122,18 @@ def extract_single_file(input_path: Path, extraction_mode: str, install_mode: st
)
try:
file_size_mb = os.path.getsize(input_str) / (1024 * 1024)
+ file_sha256 = _sha256_file(input_str)
except OSError as exc:
raise ExtractionError(
f"Could not read file size for {input_path.name}: {exc}"
) from exc
-
return {
"source_file": str(input_path.resolve()),
"filename": input_path.name,
"format": document_format,
"extraction_method": method,
"file_size_mb": round(file_size_mb, 2),
+ "sha256": file_sha256,
pages_label: pages,
"pages_label": pages_label,
"pages": pages,
@@ -1254,6 +1327,7 @@ def main():
"format": src["format"],
"extraction_method": src["extraction_method"],
"file_size_mb": src["file_size_mb"],
+ "sha256": src["sha256"],
"pages": src["pages"],
"pages_label": src["pages_label"],
"chars": src["chars"],
@@ -1315,3 +1389,4 @@ def main():
print(f" - {path.name}: {err}")
else:
print_support_note()
+
diff --git a/tests/test_fingerprint.py b/tests/test_fingerprint.py
new file mode 100644
index 0000000..5823d7b
--- /dev/null
+++ b/tests/test_fingerprint.py
@@ -0,0 +1,195 @@
+"""Per-source content fingerprint recorded by the extractor (round-2 ask)."""
+import hashlib
+import json
+from pathlib import Path
+
+from book_to_skill.utils import _sha256_file, extract_single_file, reuse_is_safe
+
+
+def _write(tmp_path: Path, name: str, content: str) -> Path:
+ p = tmp_path / name
+ p.write_text(content, encoding="utf-8")
+ return p
+
+
+def test_metadata_records_sha256_per_source(tmp_path):
+ src = _write(tmp_path, "doc.txt", "chapter one\n" + "body text.\n" * 500)
+ res = extract_single_file(src, "auto", "ask")
+ expected = hashlib.sha256(src.read_bytes()).hexdigest()
+ assert res["sha256"] == expected
+
+
+def test_same_size_different_content_gives_different_fingerprint(tmp_path):
+ # The maintainer's exact scenario: same filename, same byte size,
+ # changed content. Round-1 gate (name+size) passes both; fingerprint must not.
+ a = _write(tmp_path, "doc_a.txt", "Allow sharing.\n" + "x" * 1000)
+ b = _write(tmp_path, "doc_b.txt", "Avoid sharing.\n" + "x" * 1000)
+ assert len(a.read_bytes()) == len(b.read_bytes()) # sanity: same size
+ ra = extract_single_file(a, "auto", "ask")
+ rb = extract_single_file(b, "auto", "ask")
+ assert ra["sha256"] != rb["sha256"]
+
+
+def test_metadata_sources_list_carries_sha256(tmp_path, monkeypatch):
+ # The guard reads metadata.json, so the per-source fingerprint must survive
+ # consolidation. Follows test_metadata_encoding.py's pattern: run main()
+ # end-to-end with OUTPUT_META pointed at a tmp path, then parse the JSON.
+ from book_to_skill.utils import main
+
+ src = _write(tmp_path, "doc.txt", "content\n" * 100)
+ expected = hashlib.sha256(src.read_bytes()).hexdigest()
+
+ out_dir = tmp_path / "output"
+ out_meta = out_dir / "metadata.json"
+ monkeypatch.setenv("BOOK_SKILL_WORKDIR", str(out_dir))
+ monkeypatch.setattr("book_to_skill.utils.OUTPUT_DIR", out_dir)
+ monkeypatch.setattr("book_to_skill.utils.OUTPUT_TEXT", out_dir / "full_text.txt")
+ monkeypatch.setattr("book_to_skill.utils.OUTPUT_META", out_meta)
+ monkeypatch.setattr("book_to_skill.utils.prepare_dependencies", lambda *a: None)
+ monkeypatch.setattr(
+ "sys.argv", ["extract.py", str(src), "--install-missing", "no"]
+ )
+
+ main()
+ meta = json.loads(out_meta.read_text(encoding="utf-8"))
+ assert meta["sources"][0]["sha256"] == expected
+
+
+def test_hook_path_result_carries_sha256(tmp_path, monkeypatch):
+ # Text-mode PDFs take the pdf-inspector fast path, which returns its own
+ # per-source dict. That dict must carry the fingerprint too (review F3).
+ from types import SimpleNamespace
+
+ import book_to_skill.pdf_inspector_integration as pii
+
+ src = _write(tmp_path, "doc.pdf", "%PDF-1.4 fake minimal payload\n" * 50)
+ expected = hashlib.sha256(src.read_bytes()).hexdigest()
+
+ fake_utils = SimpleNamespace(
+ extract_single_file=lambda *a: {"extraction_method": "legacy"},
+ sanitize_extracted_text=lambda text: (text, 0),
+ detect_structure=lambda t: {
+ "chapters_detected": 0,
+ "chapters_method": "none",
+ "has_toc": False,
+ },
+ count_pages=lambda p: 1,
+ estimate_tokens=lambda t: len(t) // 4,
+ )
+ inspection = {
+ "confidence": 0.99,
+ "page_count": 1,
+ "pdf_type": "text_based",
+ "native_markdown_trusted": True,
+ "pages_needing_ocr": [],
+ "has_encoding_issues": False,
+ }
+
+ pii._reset_state_for_tests()
+ # monkeypatch, NOT bare assignment — a bare `pii.inspect_pdf = ...` leaks
+ # across the whole suite (later pdf-inspector tests then see the stub).
+ monkeypatch.setattr(
+ pii, "inspect_pdf", lambda _path: ("# Native Markdown\nBody", inspection)
+ )
+ pii.install_pdf_inspector_hook(fake_utils)
+ res = fake_utils.extract_single_file(src, "text", "ask")
+ assert res["sha256"] == expected
+
+
+# ---------------------------------------------------------------------------
+# Phase 2 — the executable reuse decision (round-2 ask d)
+# ---------------------------------------------------------------------------
+
+
+def _make_metadata(tmp_path, src: Path, mode="text"):
+ res = extract_single_file(src, mode, "ask")
+ workdir = tmp_path / "work"
+ workdir.mkdir(exist_ok=True) # the happy path needs an EXISTING workdir
+ return {
+ "workdir": str(workdir),
+ # extract_single_file's return dict has extraction_METHOD, not
+ # extraction_MODE — the mode key only exists at metadata.json top level.
+ # Take it from the mode parameter.
+ "extraction_mode": mode,
+ "sources": [
+ {k: res[k] for k in ("filename", "file_size_mb", "sha256")}
+ ],
+ }, res
+
+
+def test_scenario_reuse_same_content(tmp_path):
+ src = _write(tmp_path, "doc.txt", "chapter one\n" + "body.\n" * 500)
+ meta, res = _make_metadata(tmp_path, src)
+ ok, reason = reuse_is_safe([(src, res["sha256"])], meta, current_mode="text")
+ assert ok, reason
+
+
+def test_scenario_changed_content_same_size_falls_back(tmp_path):
+ # THE maintainer scenario: "Allow sharing." -> "Avoid sharing."
+ src_a = _write(tmp_path, "doc.txt", "Allow sharing.\n" + "x" * 1000)
+ meta, _ = _make_metadata(tmp_path, src_a)
+ src_b = _write(tmp_path, "doc.txt", "Avoid sharing.\n" + "x" * 1000)
+ assert src_a.stat().st_size == src_b.stat().st_size # sanity: same size
+ ok, reason = reuse_is_safe([(src_b, hashlib.sha256(src_b.read_bytes()).hexdigest())],
+ meta, current_mode="text")
+ assert not ok
+ assert "content changed" in reason
+
+
+def test_scenario_missing_workdir_falls_back(tmp_path):
+ src = _write(tmp_path, "doc.txt", "text\n" * 100)
+ meta, res = _make_metadata(tmp_path, src)
+ import shutil
+ shutil.rmtree(meta["workdir"]) # ONLY this test points at an absent workdir
+ ok, reason = reuse_is_safe([(src, res["sha256"])], meta, current_mode="text")
+ assert not ok
+ assert "workdir" in reason
+
+
+def test_scenario_mode_mismatch_falls_back(tmp_path):
+ # The function OWNS the mode check via current_mode — the docstring's
+ # "caller compares" phrasing would leave the check nowhere. Valid modes are
+ # "technical"/"text" — the parse_arguments enum.
+ src = _write(tmp_path, "doc.txt", "text\n" * 100)
+ meta, res = _make_metadata(tmp_path, src, mode="text")
+ ok, reason = reuse_is_safe([(src, res["sha256"])], meta, current_mode="technical")
+ assert not ok
+
+
+def test_scenario_legacy_metadata_without_sha256_falls_back(tmp_path):
+ # Older workdirs have no fingerprint: cannot establish freshness -> fresh extraction.
+ src = _write(tmp_path, "doc.txt", "text\n" * 100)
+ meta, res = _make_metadata(tmp_path, src)
+ for s in meta["sources"]:
+ del s["sha256"]
+ ok, reason = reuse_is_safe([(src, res["sha256"])], meta, current_mode="text")
+ assert not ok
+
+
+def test_scenario_sources_changed_falls_back(tmp_path):
+ # The contract's remaining clause: recorded sources must match the current
+ # inputs one-to-one on filename. A renamed input cannot reuse the workdir,
+ # and neither can a different number of inputs.
+ src = _write(tmp_path, "doc.txt", "text\n" * 100)
+ meta, res = _make_metadata(tmp_path, src)
+
+ renamed = _write(tmp_path, "other.txt", "text\n" * 100)
+ ok, reason = reuse_is_safe([(renamed, res["sha256"])], meta, current_mode="text")
+ assert not ok
+ assert "sources changed" in reason
+
+ ok, reason = reuse_is_safe(
+ [(src, res["sha256"]), (renamed, res["sha256"])], meta, current_mode="text"
+ )
+ assert not ok
+ assert "sources changed" in reason
+
+
+def test_sha256_file_streams_across_chunks(tmp_path):
+ # _sha256_file reads in 1 MiB chunks; every other fixture here is ~1 KB, so a
+ # truncating bug in the loop would go unnoticed. Real inputs are tens of MB,
+ # and a truncated fingerprint is the silent-stale-accept failure class this
+ # PR closes — so compare a multi-chunk file against hashlib directly.
+ src = _write(tmp_path, "big.txt", "line of text\n" * 200_000) # ~2.6 MB, >2 chunks
+ assert src.stat().st_size > 2 << 20
+ assert _sha256_file(str(src)) == hashlib.sha256(src.read_bytes()).hexdigest()
diff --git a/tests/test_rerun_guard.py b/tests/test_rerun_guard.py
new file mode 100644
index 0000000..bf31195
--- /dev/null
+++ b/tests/test_rerun_guard.py
@@ -0,0 +1,85 @@
+"""Re-run guard contract in the converter spec (Step 0)."""
+
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+SKILL = (ROOT / "SKILL.md").read_text(encoding="utf-8")
+
+
+def test_step0_contains_rerun_guard():
+ step0 = SKILL[SKILL.index("## Step 0"):SKILL.index("## Step 1 ")]
+ assert "Re-run guard" in step0
+ assert "STOP" in step0
+ assert "Update/Fold-in (Mode 4)" in step0 # points the user at the escape hatch
+
+
+def test_guard_covers_both_step5_naming_forms():
+ # Step 5 can name a generated skill either by author-concept or by title.
+ # The guard must check both, or an existing author-concept skill
+ # (e.g. chilukuri-agenticops) is missed when the title differs.
+ step0 = SKILL[SKILL.index("## Step 0"):SKILL.index("## Step 1 ")]
+ assert "author-concept" in step0
+ assert "by-title" in step0
+
+
+def test_guard_runs_before_extraction():
+ # The guard must live in Step 0, i.e. before the extraction step in file order.
+ assert SKILL.index("Re-run guard") < SKILL.index("## Step 2 ")
+
+def _step0():
+ return SKILL[SKILL.index("## Step 0"):SKILL.index("## Step 1 ")]
+
+
+def test_reuse_requires_an_intact_matching_workdir():
+ # Reviewer ask 1: reuse must be gated, not unconditional.
+ guard = _step0()
+ guard = guard[guard.index("Re-run guard"):]
+ assert "only if it is still intact and still matches the current inputs and options" in guard
+ assert "metadata.json" in guard
+ assert "never restart extraction from scratch" not in guard
+
+
+def test_reuse_match_covers_source_and_config():
+ # Reviewer ask 1 said "matching the current source/config" — filenames alone
+ # would let an in-place edit pass; the mode check covers the config half.
+ # Round 2: the content half is a recorded fingerprint, not a size.
+ guard = _step0()
+ guard = guard[guard.index("Re-run guard"):]
+ assert "and content fingerprint" in guard
+ assert "sha256" in guard
+ assert "extraction_mode" in guard
+
+
+def test_missing_or_stale_workdir_falls_back_to_fresh_extraction():
+ # Reviewer ask 1: deleted/cleaned workdir or changed input -> fresh extraction.
+ guard = _step0()
+ guard = guard[guard.index("Re-run guard"):]
+ assert "start a fresh extraction instead of resuming" in guard
+ assert "missing (temp cleanup)" in guard
+ assert "the sources no longer match" in guard
+ assert "ask the user before discarding or resuming" in guard
+
+
+def test_destination_resolved_before_the_step0_lookup():
+ # Reviewer ask 2: resolution must precede the Mode 4 lookup, not follow it.
+ step0 = _step0()
+ assert "Resolve the destination root first" in step0
+ assert step0.index("Resolve the destination root first") < step0.index(
+ "flag this run as an **Update/Fold-in** operation"
+ )
+
+
+def test_step0_lookups_never_use_raw_skills_home():
+ # Reviewer ask 2: SKILLS_HOME is only selected in Step 5, so Step 0 must not
+ # consult it — a project-local request would hit the personal root by accident.
+ assert "SKILLS_HOME" not in _step0()
+
+
+def test_guard_names_the_legacy_metadata_fallback():
+ # Round-2 ask: metadata recorded before fingerprints existed cannot establish
+ # freshness, so the guard must name that fallback rather than let a
+ # sha256-less source be treated as matching.
+ guard = _step0()
+ guard = guard[guard.index("Re-run guard"):]
+ assert "no `sha256` for a source" in guard
+ assert "recorded before fingerprints existed" in guard