tools, instructions: Begleitdatei - raw clarify legt Präzisierungen des Operators als <stem>.clarifications.md beim Original ab, pending/accept bündeln sie (#241); 10.2.0-beta.1
CI / verify (push) Failing after 12m29s
CI / pwsh (push) Failing after 3m9s
Release / converters (push) Successful in 29s
Release / release (push) Successful in 39s
Release / wiki-mirror (push) Skipped

Files changed:
- CHANGES.md
- VERSION
- docs/how-to/ingest-a-source.md
- docs/reference/commands/README.md
- docs/reference/commands/raw-material-and-uploads.md
- instructions/wiki-ingest/SKILL.md
- raw/CONTRACT.md
- tools/CONTRACT.md
- tools/chemenu/cli_contract.py
- tools/chemenu/commands/raw/__init__.py
- tools/chemenu/commands/raw/_common.py
- tools/chemenu/commands/raw/clarify.py
- tools/chemenu/commands/raw/pending.py
- tools/chemenu/tests/test_raw_clarify.py
- types/source.guidance.md

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015uxGFdBAmyA23g1isCtGEY
This commit is contained in:
torbenandClaude Sonnet 5.5 committed 2026-11-18 06:45:00 +01:00
1 parent 55ddf652cb
commit 832056a0b0
15 files changed
+650 -11

No files matched your search

+54
View File
@@ -126,6 +126,7 @@ sources rebuild-index write idempotent budget:counted exit:0,1
raw fetch write non-idempotent budget:counted exit:0,1,42 Capture a web page the user names into `incoming/`: the HTML as received plus a derived text, for `raw accept` to promote. Pages of a known website are fetched in the website's standard form and cleaned of its page furniture; a host the instance routes so is fetched with the user's own session or through an external fetcher.
raw login write idempotent budget:counted exit:0,1,42 Let the user sign in to a website once, in a visible browser window, and store the session it leaves as a secret outside the working tree, for `raw fetch` to fetch that website's pages with. Only the user runs it.
raw derive write non-idempotent budget:counted exit:0,1 Derive reading text from a PDF, e-mail, Office file or web page in `incoming/`, or unpack a ZIP, and leave the original beside it, for `raw accept` to promote.
raw clarify write non-idempotent budget:counted exit:0,1 Write the operator's answers to an ingest's questions about a source as a companion file in `incoming/`, to be promoted with the source instead of as a source of its own.
raw capture write non-idempotent budget:counted exit:0,1 Capture documentation from a git repository into `incoming/<bundle>/`, with a manifest naming the repository, ref rule and commit, for `raw accept` to promote.
raw status read idempotent budget:counted exit:0 Report which captured bundles under `raw/` have fallen behind their repository, with each changed file as `A`/`M`/`D`.
raw pending read idempotent budget:counted exit:0 List what waits in `incoming/`, oldest first, and name the entry an ingest without an argument takes next.
@@ -1624,6 +1625,59 @@ Derive reading text from a PDF, e-mail, Office file or web page in `incoming/`,
- `wikitool raw accept` - promotes the folder into `raw/`
- `instructions/wiki-ingest/SKILL.md` - where a PDF, mail or Office file to ingest starts
#### `raw clarify`
Write the operator's answers to an ingest's questions about a source as a companion file in `incoming/`, to be promoted with the source instead of as a source of its own.
**SYNOPSIS**
- `wikitool raw clarify incoming/<entry> --item "<answer>" [--item "<answer>" ...]` - A file, a file of a stem bundle, or a folder in `incoming/`: write `<stem>.clarifications.md` beside it, or `clarifications.md` inside the folder
- `wikitool raw clarify --page "<Title>" --item "<answer>" [--item "<answer>" ...]` - A source already in `raw/`: write the companion file to `incoming/` and print the `raw accept --page` line that adds it to the source's bundle
**PROPERTIES**
- effect: write
- idempotent: no
- atomic: Yes - everything is checked before the one write, and the file is created exclusively, so an existing file is never overwritten
- budget: counted
- network: no
**EXAMPLES**
- `tools/wikitool raw clarify incoming/meeting.vtt --item "Termindatum: 2026-11-12"`
- `tools/wikitool raw clarify incoming/workshop --item "Teilnehmer: A, B" --item "KI = künstliche Intelligenz"`
- `tools/wikitool raw clarify --page "Source - Meeting" --item "Projekt: Alpha"`
**EXIT STATUS**
- 0 success
- 1 No `--item`, an empty or multi-line one, an entry that is not directly in `incoming/`, a captured bundle, or neither (or both of) an entry and `--page`
- 1 `--page` names no page, or one without `raw_files:`
**ON FAILURE**
- No `--item`, an empty or multi-line one, an entry that is not directly in `incoming/`, a captured bundle, or neither (or both of) an entry and `--page` -> Nothing was written. Fix the call and retry once
- `--page` names no page, or one without `raw_files:` -> Nothing was written. Check the title with `wikitool search`, then retry once
**NEVER**
- Never put the operator's unprompted new content in a clarification - it is a source of its own.
- Never write a clarification by hand into `raw/`; `raw accept` promotes it.
**NOTES**
- Writes into `incoming/` only, never into `raw/`, and reads no network. The name and the place are computed, never chosen: `incoming/<stem>.clarifications.md` for a file or a stem bundle, `incoming/<folder>/clarifications.md` for a folder; a taken name gets `-2`, `-3` before the extension, and no existing file is overwritten.
- The file starts with a fixed header (`kind`, `written_by`, `clarifies` - the file(s) it belongs to, `answered` - today's date, `by`), then one bullet per `--item`, word for word as passed. An item is one line; its language is the one the operator answered in.
- What belongs in it is what this ingest session asked about this source and the operator answered in a few points - the date of the recording, who took part, an abbreviation, a transcription error. What the operator adds unprompted, or says about a subject of its own, stays a source of its own (`instructions/wiki-ingest/SKILL.md`).
- `raw pending` lists the companion file with its original as one candidate, and `raw accept` promotes both as one bundle named after the original, whatever order the files are passed in. A companion file with no original in the call (or, with `--page`, in the page's raw_files:) is refused.
- `--page` names the file after the stem of the source's first file and prints the `raw accept --page` line with the page's own `fidelity` and `authority` - a bundle has one pair, and the companion file inherits it.
**SEE ALSO**
- `raw/CONTRACT.md` "Getting a file in: incoming/" - the companion file and its bundle
- `wikitool raw accept` - promotes the companion file with its original
- `instructions/wiki-ingest/SKILL.md` - when to ask, and where the answer goes
#### `raw capture`
Capture documentation from a git repository into `incoming/<bundle>/`, with a manifest naming the repository, ref rule and commit, for `raw accept` to promote.
+1 -1
View File
@@ -287,7 +287,7 @@ GROUPS: tuple[tuple[str, tuple[str, ...]], ...] = (
"sources coverage", "sources trace", "sources rebuild-index",
)),
("Raw material and uploads", (
"raw fetch", "raw login", "raw derive", "raw capture", "raw status", "raw pending", "raw accept",
"raw fetch", "raw login", "raw derive", "raw clarify", "raw capture", "raw status", "raw pending", "raw accept",
"upload collect", "upload list", "upload show", "upload accept", "upload reject",
)),
("Git", (
+2 -1
View File
@@ -7,7 +7,7 @@ subcommands are listed in `-h` and in the generated command reference.
"""
import typer
from chemenu.commands.raw import accept, pending, fetch, login, derive, capture
from chemenu.commands.raw import accept, pending, fetch, login, derive, capture, clarify
app = typer.Typer(help="Bring raw material into incoming/, and promote it from there into raw/.")
@@ -16,5 +16,6 @@ app.command("pending")(pending.raw_pending_command)
app.command("fetch")(fetch.raw_fetch_command)
app.command("login")(login.raw_login_command)
app.command("derive")(derive.raw_derive_command)
app.command("clarify")(clarify.raw_clarify_command)
app.command("capture")(capture.raw_capture_command)
app.command("status")(capture.raw_status_command)
+59 -2
View File
@@ -33,6 +33,59 @@ def _incoming_dir() -> Path:
return config.ROOT / "incoming"
# The companion file of a source (Gitea #241): the operator's answers to what the ingest
# asked about it. Beside the original it is `<stem>.clarifications[-N].md`; inside a
# folder it is `clarifications[-N].md`. The pattern stands here and nowhere else -
# `raw clarify` writes the names, `raw pending` and `raw accept` read them.
CLARIFICATIONS_KIND = "clarifications"
_CLARIFICATION_BESIDE = re.compile(r"^(?P<stem>.+)\.clarifications(?:-\d+)?\.md$")
def _clarification_stem(name: str) -> Optional[str]:
"""The stem of the original a companion file named `name` belongs to, or
None when `name` is not one."""
match = _CLARIFICATION_BESIDE.match(name)
return match.group("stem") if match else None
def _is_clarification(path: Path) -> bool:
return _clarification_stem(path.name) is not None
def _source_stem(path: Path) -> str:
"""The stem a top-level file of `incoming/` is grouped and named by: its
own, except that a companion file belongs to its original's."""
return _clarification_stem(path.name) or path.stem
def _clarification_name(stem: str, taken) -> str:
"""`<stem>.clarifications.md`, with `-2`, `-3` before the extension while
`taken(name)` says the name is in use - the rule `raw derive` uses."""
name = f"{stem}.{CLARIFICATIONS_KIND}.md"
number = 2
while taken(name):
name = f"{stem}.{CLARIFICATIONS_KIND}-{number}.md"
number += 1
return name
def _check_clarifications(resolved: list[Path], existing_raw_paths: list[Path]) -> None:
"""A companion file belongs to an original: one in this call or one the
`--page` page already holds, with the same stem. A clarification of nothing
is not a source."""
originals = {p.stem for p in resolved if not _is_clarification(p)}
originals |= {p.stem for p in existing_raw_paths if not _is_clarification(p)}
for path in resolved:
stem = _clarification_stem(path.name)
if stem is not None and stem not in originals:
raise _Refused(
f"{rel_path(path)} is a clarification of {stem!r}, and no file of that name is in "
"this call or already in the --page page's raw_files:. A clarification is not a "
"source of its own - pass its original in the same call, or use --page for a "
"source that is already in raw/."
)
def _resolve(raw: Path) -> Path:
return raw if raw.is_absolute() else config.ROOT / raw
@@ -210,6 +263,7 @@ def _plan_file_moves(
# (Gitea #58 decision 3): from the second file on, never before. Whenever
# --page targets an existing page it always has >=1 raw file already
# (types/source.md requires raw_files:), so bundling always applies there.
_check_clarifications(resolved, existing_raw_paths)
total = len(existing_raw_paths) + len(resolved)
bundle_dir: Optional[Path] = None
if len(existing_raw_paths) >= 2:
@@ -227,10 +281,13 @@ def _plan_file_moves(
# directory, never at today's shard - the file's capture date is
# whatever it always was, and a bundle mixing an old and a new
# shard would have no single correct address.
primary = existing_raw_paths[0]
primary = next(
(p for p in existing_raw_paths if not _is_clarification(p)), existing_raw_paths[0]
)
bundle_dir = primary.parent / primary.stem
else:
primary = resolved[0]
# named after the original, whatever order the call lists it in (Gitea #241)
primary = next((p for p in resolved if not _is_clarification(p)), resolved[0])
bundle_dir = _shard_dir() / primary.stem
moves: list[tuple[Path, Path]] = []
+256
View File
@@ -0,0 +1,256 @@
"""`wikitool raw clarify` - the operator's answers to what an ingest asked about a source,
written as a companion file beside the source instead of as a second source (Gitea #241).
Like `raw fetch` and `raw derive` it ends in `incoming/`, never in `raw/`: `raw accept`
promotes the companion file with its original as one bundle. The name and the place are
computed, never chosen; the answers go in as the operator gave them, one line each.
"""
from __future__ import annotations
import datetime
import os
from pathlib import Path
from typing import Annotated, Optional
import typer
from rich.markup import escape
from chemenu import cli_contract, config, repo_capture, web_capture
from chemenu.commands._util import fail, path_budget_problem_for, rel_path, success
from chemenu.commands.raw._common import (
CLARIFICATIONS_KIND,
_Refused,
_check_directly_in_incoming,
_clarification_name,
_incoming_dir,
_is_clarification,
_refusals_fail,
_resolve,
_shard_dir,
_source_stem,
_walk_folder,
_write_exclusive,
)
from chemenu.kb_scan import load_kb_pages
from chemenu.provenance import source_raw_files
FOLDER_NAME = f"{CLARIFICATIONS_KIND}.md"
_LISTED_FILES = 10
def _check_items(items: list[str]) -> list[str]:
if not items:
raise _Refused("Pass at least one --item: a clarification without an answer is no file.")
cleaned = []
for item in items:
text = item.strip()
if not text:
raise _Refused("An --item is empty.")
if "\n" in text or "\r" in text:
raise _Refused(
f"--item {text.splitlines()[0]!r} spans lines. One item is one line - pass one "
"--item per point."
)
cleaned.append(text)
return cleaned
def _render(items: list[str], files: list[str], *, answered: str) -> bytes:
shown = files[:_LISTED_FILES]
if len(files) > _LISTED_FILES:
shown.append(f"... and {len(files) - _LISTED_FILES} more")
header = web_capture.header([
("kind", CLARIFICATIONS_KIND),
("written_by", "wikitool raw clarify"),
("clarifies", shown),
("answered", answered),
("by", "operator, in the ingest dialog"),
])
body = "\n".join(f"- {item}" for item in items)
return (header + "\n" + body + "\n").encode("utf-8")
def _plan_entry(entry: Path, items: list[str]) -> tuple[Path, bytes]:
"""The file for an entry of `incoming/`: where it goes and what it holds."""
incoming = _incoming_dir()
_check_directly_in_incoming(entry, incoming)
if entry.name.startswith(".") or entry.is_symlink():
raise _Refused(f"{rel_path(entry)} is hidden or a symlink - raw clarify does not take it.")
if entry.is_dir():
if (entry / repo_capture.MANIFEST_NAME).is_file():
raise _Refused(
f"{rel_path(entry)}/ is a captured bundle; its manifest describes exactly what it "
"holds, so a file added to it would not match it."
)
files, _dirs, _refused = _walk_folder(entry)
if not files:
raise _Refused(f"{rel_path(entry)}/ holds no file to clarify.")
name = _clarification_name(
"", lambda n: os.path.lexists(entry / n.removeprefix("."))
).removeprefix(".")
target = entry / name
listed = sorted(p.relative_to(entry).as_posix() for p in files)
listed = [f"{entry.name}/{p}" for p in listed]
budget = _shard_dir() / entry.name / name
else:
if not entry.is_file():
raise _Refused(f"{rel_path(entry)} does not exist.")
if _is_clarification(entry):
raise _Refused(f"{rel_path(entry)} is itself a clarification - clarify its original.")
stem = _source_stem(entry)
name = _clarification_name(stem, lambda n: os.path.lexists(incoming / n))
target = incoming / name
group = sorted(
(p for p in incoming.iterdir()
if p.is_file() and not p.name.startswith(".") and not _is_clarification(p)
and _source_stem(p) == stem),
key=lambda p: os.fsencode(p.name),
)
listed = [p.name for p in group]
budget = _shard_dir() / stem / name
problem = path_budget_problem_for(budget)
if problem:
raise _Refused(f"Cannot write {problem}. The name comes from the source in incoming/: shorten it.")
return target, _render(items, listed, answered=datetime.date.today().isoformat())
def _plan_page(title: str, items: list[str]):
"""The file for a source that is already in `raw/`: named after the stem of
its original, and the `raw accept --page` line that promotes it."""
pages = load_kb_pages(config.KB_DIR)
page = pages.get(title)
if page is None:
raise _Refused(f"No page titled '{title}' found under kb/.")
existing = [config.ROOT / p for p in source_raw_files(page)]
if not existing:
raise _Refused(f"'{title}' has no raw_files: - there is no source to clarify.")
for path in existing:
captured = repo_capture.captured_bundle_of(path, config.RAW_DIR)
if captured is not None:
raise _Refused(
f"'{title}' is a captured bundle ({rel_path(captured)}/); its manifest describes "
"exactly what it holds, so a file added to it would not match it."
)
originals = [p for p in existing if not _is_clarification(p)]
if not originals:
raise _Refused(f"'{title}' holds only clarifications in raw_files:.")
incoming = _incoming_dir()
# names in the directory the source's files sit in - its bundle, or the shard of a lone file
held = {p.name for p in existing}
if existing[0].parent.is_dir():
held |= {c.name for c in existing[0].parent.iterdir()}
stem = originals[0].stem
name = _clarification_name(stem, lambda n: n in held or os.path.lexists(incoming / n))
problem = path_budget_problem_for(originals[0].parent / stem / name)
if problem:
raise _Refused(f"Cannot write {problem}. The name comes from the source's file: it is too long.")
fidelity = page.frontmatter.get("fidelity") or "<fidelity>"
authority = page.frontmatter.get("authority") or "<authority>"
target = incoming / name
content = _render(items, [p.name for p in existing], answered=datetime.date.today().isoformat())
line = (
f'tools/wikitool raw accept --page "{title}" --fidelity {fidelity} '
f"--authority {authority} {rel_path(target)}"
)
return target, content, line
@cli_contract.record(cli_contract.CommandRecord(
path="raw clarify",
summary="Write the operator's answers to an ingest's questions about a source as a companion "
"file in `incoming/`, to be promoted with the source instead of as a source of its own.",
synopsis=(
cli_contract.Variant(
usage='raw clarify incoming/<entry> --item "<answer>" [--item "<answer>" ...]',
notes="A file, a file of a stem bundle, or a folder in `incoming/`: write "
"`<stem>.clarifications.md` beside it, or `clarifications.md` inside the folder",
),
cli_contract.Variant(
usage='raw clarify --page "<Title>" --item "<answer>" [--item "<answer>" ...]',
notes="A source already in `raw/`: write the companion file to `incoming/` and print "
"the `raw accept --page` line that adds it to the source's bundle",
),
),
properties=cli_contract.Properties(
effect=cli_contract.Effect.WRITE,
idempotent=cli_contract.Idempotent.NO,
atomic="Yes - everything is checked before the one write, and the file is created "
"exclusively, so an existing file is never overwritten",
budget=cli_contract.Budget.COUNTED,
network=cli_contract.Network.NO,
),
notes=(
"Writes into `incoming/` only, never into `raw/`, and reads no network. The name and the "
"place are computed, never chosen: `incoming/<stem>.clarifications.md` for a file or a "
"stem bundle, `incoming/<folder>/clarifications.md` for a folder; a taken name gets "
"`-2`, `-3` before the extension, and no existing file is overwritten.",
"The file starts with a fixed header (`kind`, `written_by`, `clarifies` - the file(s) it "
"belongs to, `answered` - today's date, `by`), then one bullet per `--item`, word for "
"word as passed. An item is one line; its language is the one the operator answered in.",
"What belongs in it is what this ingest session asked about this source and the operator "
"answered in a few points - the date of the recording, who took part, an abbreviation, a "
"transcription error. What the operator adds unprompted, or says about a subject of its "
"own, stays a source of its own (`instructions/wiki-ingest/SKILL.md`).",
"`raw pending` lists the companion file with its original as one candidate, and `raw "
"accept` promotes both as one bundle named after the original, whatever order the "
"files are passed in. A companion file with no original in the call (or, with `--page`, "
"in the page's raw_files:) is refused.",
"`--page` names the file after the stem of the source's first file and prints the `raw "
"accept --page` line with the page's own `fidelity` and `authority` - a bundle has one "
"pair, and the companion file inherits it.",
),
failures=(
cli_contract.Failure(
cause="No `--item`, an empty or multi-line one, an entry that is not directly in "
"`incoming/`, a captured bundle, or neither (or both of) an entry and `--page`",
reaction="Nothing was written. Fix the call and retry once",
),
cli_contract.Failure(
cause="`--page` names no page, or one without `raw_files:`",
reaction="Nothing was written. Check the title with `wikitool search`, then retry once",
),
),
examples=(
'tools/wikitool raw clarify incoming/meeting.vtt --item "Termindatum: 2026-11-12"',
'tools/wikitool raw clarify incoming/workshop --item "Teilnehmer: A, B" --item "KI = künstliche Intelligenz"',
'tools/wikitool raw clarify --page "Source - Meeting" --item "Projekt: Alpha"',
),
never=(
"Never put the operator's unprompted new content in a clarification - it is a source of "
"its own.",
"Never write a clarification by hand into `raw/`; `raw accept` promotes it.",
),
see_also=(
"`raw/CONTRACT.md` \"Getting a file in: incoming/\" - the companion file and its bundle",
"`wikitool raw accept` - promotes the companion file with its original",
"`instructions/wiki-ingest/SKILL.md` - when to ask, and where the answer goes",
),
))
def raw_clarify_command(
entry: Annotated[Optional[Path], typer.Argument(
help="A file or folder directly in incoming/ (omit with --page)"
)] = None,
item: Annotated[Optional[list[str]], typer.Option(
"--item", help="One answer, one line; repeat for more"
)] = None,
page: Annotated[Optional[str], typer.Option(
"--page", help="Clarify the source of this existing page instead of an entry of incoming/"
)] = None,
):
"""Write the operator's answers about a source as a companion file in
incoming/. See raw/CONTRACT.md "Getting a file in: incoming/"."""
if (entry is None) == (page is None):
fail("Pass either a file or folder in incoming/, or --page \"<Title>\" - exactly one of them.")
items = _refusals_fail(_check_items, list(item or []))
if page is not None:
target, content, line = _refusals_fail(_plan_page, page, items)
_write_exclusive([(target, content)])
success(escape(f"Wrote {rel_path(target)} ({len(items)} item(s))."))
typer.echo(f" Next:\n {line}")
return
target, content = _refusals_fail(_plan_entry, _resolve(entry), items)
_write_exclusive([(target, content)])
success(escape(
f"Wrote {rel_path(target)} ({len(items)} item(s)). `raw accept` promotes it with its "
"original as one source."
))
+4 -2
View File
@@ -27,6 +27,7 @@ from chemenu.commands.raw._common import (
_check_files,
_derive_hint,
_incoming_dir,
_source_stem,
_plan_captured_folder,
_plan_file_moves,
_plan_folder,
@@ -81,7 +82,8 @@ def _pending_candidates() -> list[_Candidate]:
"""The candidates in `incoming/`, oldest first (Gitea #112 E1/E5).
Only top-level entries count; dotfiles and empty directories are none.
Top-level files sharing a stem are one `bundle` - a `raw fetch` pair. A top-level folder is one `folder`, with every
Top-level files sharing a stem are one `bundle` - a `raw fetch` pair, or a file with its
`<stem>.clarifications.md` (Gitea #241). A top-level folder is one `folder`, with every
file below it. A unit is as new as its newest part, so a bundle or folder
sorts by the newest mtime it holds; a tie goes by the path's bytes."""
incoming = _incoming_dir()
@@ -104,7 +106,7 @@ def _pending_candidates() -> list[_Candidate]:
"folder", (entry,), count, newest, _refusal(check, entry)
))
else:
by_stem.setdefault(entry.stem, []).append(entry)
by_stem.setdefault(_source_stem(entry), []).append(entry)
for paths in by_stem.values():
paths.sort(key=lambda p: os.fsencode(p.name))
candidates.append(_Candidate(
+155
View File
@@ -0,0 +1,155 @@
"""`raw clarify` and the companion file's way through `raw pending` and `raw accept` (Gitea #241)."""
import datetime
import json
import pytest
import typer
from chemenu.commands.raw.accept import raw_accept_command
from chemenu.commands.raw.clarify import raw_clarify_command
from chemenu.commands.raw.pending import raw_pending_command
from chemenu.frontmatter_io import write_page
def _shard() -> str:
today = datetime.date.today()
return f"raw/{today.year:04d}/{today.month:02d}"
@pytest.fixture
def tree(kb_dir):
root = kb_dir.parent
(root / "raw").mkdir(parents=True)
(root / "incoming").mkdir(parents=True, exist_ok=True)
return root
def _clarify(entry=None, items=("Termindatum: 2026-11-12",), page=None):
return raw_clarify_command(entry=entry, item=list(items), page=page)
def _accept(*files, page=None, fidelity="verbatim", authority="reporting"):
return raw_accept_command(
files=list(files), fidelity=fidelity, authority=authority, page=page,
replaces=None, dry_run=False, replaces_bundle=None,
)
def _source(kb_dir, title, raw_files, fidelity="verbatim", authority="reporting"):
write_page(kb_dir / "sources" / f"{title}.md", {
"type": "types/source.md", "source_type": "document", "author": "T",
"raw_files": list(raw_files), "date": "2026-09-01", "fidelity": fidelity,
"authority": authority, "tags": [], "entities": [], "concepts": [],
"summary": "Test source.",
}, f"\n# {title}\n\n## Summary\n\nTest.\n")
def test_clarify_writes_companion_file_with_fixed_header_and_one_item(tree):
(tree / "incoming/meeting.vtt").write_text("WEBVTT\n", encoding="utf-8")
_clarify(tree / "incoming/meeting.vtt")
text = (tree / "incoming/meeting.clarifications.md").read_text(encoding="utf-8")
assert "kind: clarifications" in text
assert "meeting.vtt" in text
assert f"answered: {datetime.date.today().isoformat()}" in text
assert [l for l in text.splitlines() if l.startswith("- ")] == ["- Termindatum: 2026-11-12"]
def test_clarify_without_item_exits_1_and_writes_nothing(tree):
(tree / "incoming/meeting.vtt").write_text("WEBVTT\n", encoding="utf-8")
with pytest.raises(typer.Exit) as exc:
_clarify(tree / "incoming/meeting.vtt", items=())
assert exc.value.exit_code == 1
assert sorted(p.name for p in (tree / "incoming").iterdir()) == ["meeting.vtt"]
def test_clarify_rejects_multiline_item_and_both_or_neither_target(tree):
(tree / "incoming/m.vtt").write_text("x", encoding="utf-8")
with pytest.raises(typer.Exit):
_clarify(tree / "incoming/m.vtt", items=("a\nb",))
with pytest.raises(typer.Exit):
_clarify(None)
with pytest.raises(typer.Exit):
_clarify(tree / "incoming/m.vtt", page="X")
assert [p.name for p in (tree / "incoming").iterdir()] == ["m.vtt"]
def test_clarify_folder_and_never_overwrites(tree):
folder = tree / "incoming/x"
folder.mkdir()
(folder / "a.md").write_text("a", encoding="utf-8")
_clarify(folder)
first = (folder / "clarifications.md").read_text(encoding="utf-8")
_clarify(folder, items=("zweite",))
assert (folder / "clarifications.md").read_text(encoding="utf-8") == first
assert "- zweite" in (folder / "clarifications-2.md").read_text(encoding="utf-8")
def test_clarify_file_name_taken_gets_counter(tree):
(tree / "incoming/m.vtt").write_text("x", encoding="utf-8")
_clarify(tree / "incoming/m.vtt")
_clarify(tree / "incoming/m.vtt", items=("b",))
assert (tree / "incoming/m.clarifications-2.md").is_file()
def test_pending_lists_original_and_companion_as_one_bundle(tree, capsys):
(tree / "incoming/meeting.vtt").write_text("WEBVTT\n", encoding="utf-8")
_clarify(tree / "incoming/meeting.vtt")
capsys.readouterr()
raw_pending_command(json_out=True)
candidates = json.loads(capsys.readouterr().out)
assert len(candidates) == 1
assert candidates[0]["kind"] == "bundle" and candidates[0]["files"] == 2
assert candidates[0]["acceptable"] is True
def test_accept_names_bundle_after_the_original_whatever_the_order(tree):
(tree / "incoming/meeting.vtt").write_text("WEBVTT\n", encoding="utf-8")
_clarify(tree / "incoming/meeting.vtt")
_accept(tree / "incoming/meeting.clarifications.md", tree / "incoming/meeting.vtt")
bundle = tree / _shard() / "meeting"
assert (bundle / "meeting.vtt").is_file()
assert (bundle / "meeting.clarifications.md").is_file()
def test_accept_refuses_companion_without_original_and_moves_nothing(tree):
(tree / "incoming/meeting.vtt").write_text("WEBVTT\n", encoding="utf-8")
_clarify(tree / "incoming/meeting.vtt")
(tree / "incoming/meeting.vtt").unlink()
with pytest.raises(typer.Exit) as exc:
_accept(tree / "incoming/meeting.clarifications.md")
assert exc.value.exit_code == 1
assert (tree / "incoming/meeting.clarifications.md").is_file()
assert not (tree / _shard()).exists()
def test_clarify_page_writes_file_and_prints_accept_line_that_builds_bundle(tree, kb_dir, capsys):
raw = tree / _shard()
raw.mkdir(parents=True)
(raw / "meeting.vtt").write_text("WEBVTT\n", encoding="utf-8")
_source(kb_dir, "Source - Meeting", [f"{_shard()}/meeting.vtt"])
_clarify(page="Source - Meeting", items=("Projekt: Alpha",))
out = capsys.readouterr().out
assert 'raw accept --page "Source - Meeting" --fidelity verbatim --authority reporting' in out
assert "incoming/meeting.clarifications.md" in out
_accept(tree / "incoming/meeting.clarifications.md", page="Source - Meeting")
assert (raw / "meeting/meeting.vtt").is_file()
assert (raw / "meeting/meeting.clarifications.md").is_file()
assert not (raw / "meeting.vtt").exists()
def test_clarify_page_in_existing_bundle_counts_up(tree, kb_dir):
bundle = tree / _shard() / "meeting"
bundle.mkdir(parents=True)
(bundle / "meeting.vtt").write_text("x", encoding="utf-8")
(bundle / "meeting.clarifications.md").write_text("x", encoding="utf-8")
_source(kb_dir, "Source - Meeting", [f"{_shard()}/meeting/meeting.vtt", f"{_shard()}/meeting/meeting.clarifications.md"])
_clarify(page="Source - Meeting")
assert (tree / "incoming/meeting.clarifications-2.md").is_file()
def test_pdf_with_only_a_companion_still_warns_about_missing_derived_text(tree, capsys):
(tree / "incoming/scan.pdf").write_bytes(b"%PDF-1.4\n")
_clarify(tree / "incoming/scan.pdf")
capsys.readouterr()
_accept(tree / "incoming/scan.pdf", tree / "incoming/scan.clarifications.md")
assert "has a text filter and no derived .md" in capsys.readouterr().out