diff --git a/CHANGES.md b/CHANGES.md index 4610e1f..5617c9b 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -14,13 +14,14 @@ place only: `instructions/dev/version-parts.md` § The candidate model. --- -## 10.1.1-beta.2 - 2026-10-16 - Publish-, Sync-Hilfe und Log-Vorlage nennen den reinen Log-Zusatz beim Abgleich +## 10.2.0-beta.1 - 2026-11-17 - Ingest: Präzisierungen des Operators als Begleitdatei im Bundle der Quelle - neuer Befehl raw clarify (#241) **Author:** Torben Nehmer **Medium impact** - Reine Lesevorgänge schreiben keinen Log-Eintrag mehr, und ein offener Log-Eintrag allein lässt den Katalog beim Abgleich unangetastet +- Ingest: Präzisierungen des Operators als Begleitdatei im Bundle der Quelle - neuer Befehl raw clarify (#241) **Low impact** - Publish-, Sync-Hilfe und Log-Vorlage nennen den reinen Log-Zusatz beim Abgleich diff --git a/VERSION b/VERSION index d1c545a..d0488f0 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -10.1.1-beta.2 +10.2.0-beta.1 diff --git a/docs/how-to/ingest-a-source.md b/docs/how-to/ingest-a-source.md index db404f5..336d3a1 100644 --- a/docs/how-to/ingest-a-source.md +++ b/docs/how-to/ingest-a-source.md @@ -82,6 +82,12 @@ same context, it names that reason once and then does. ## Where the agent asks you +- **When the source lacks something only you know** - the date of a recorded meeting, who took + part, what an abbreviation stands for. The agent asks, and writes your short answers with + `tools/wikitool raw clarify` as `.clarifications.md` beside the source; it is promoted with + the source into one folder in `raw/` and cited from the source page, instead of becoming a + second source. Only what the agent asked about the source goes in. New content you add + unprompted is still a source of its own. - **Before promoting the file into `raw/`**, the agent asks how faithful the capture is (`fidelity`) and what the material may claim about its subject (`authority`). Both are recorded once and never guessed: you know the answers now, and nobody can recover them later. diff --git a/docs/reference/commands/README.md b/docs/reference/commands/README.md index 285cab7..d164cef 100644 --- a/docs/reference/commands/README.md +++ b/docs/reference/commands/README.md @@ -82,6 +82,7 @@ Full records: [raw-material-and-uploads.md](raw-material-and-uploads.md) - [`raw fetch`](raw-material-and-uploads.md#raw-fetch) - 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`](raw-material-and-uploads.md#raw-login) - 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`](raw-material-and-uploads.md#raw-derive) - 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`](raw-material-and-uploads.md#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. - [`raw capture`](raw-material-and-uploads.md#raw-capture) - Capture documentation from a git repository into `incoming//`, with a manifest naming the repository, ref rule and commit, for `raw accept` to promote. - [`raw status`](raw-material-and-uploads.md#raw-status) - Report which captured bundles under `raw/` have fallen behind their repository, with each changed file as `A`/`M`/`D`. - [`raw pending`](raw-material-and-uploads.md#raw-pending) - List what waits in `incoming/`, oldest first, and name the entry an ingest without an argument takes next. diff --git a/docs/reference/commands/raw-material-and-uploads.md b/docs/reference/commands/raw-material-and-uploads.md index 516b178..bfbe73b 100644 --- a/docs/reference/commands/raw-material-and-uploads.md +++ b/docs/reference/commands/raw-material-and-uploads.md @@ -8,6 +8,7 @@ Bringing new material into `raw/`: fetching and capturing it, seeing what is wai - [`raw fetch`](#raw-fetch) - [`raw login`](#raw-login) - [`raw derive`](#raw-derive) +- [`raw clarify`](#raw-clarify) - [`raw capture`](#raw-capture) - [`raw status`](#raw-status) - [`raw pending`](#raw-pending) @@ -223,6 +224,64 @@ tools/wikitool raw derive incoming/scans.zip - `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/ --item "" [--item "" ...]` - A file, a file of a stem bundle, or a folder in `incoming/`: write `.clarifications.md` beside it, or `clarifications.md` inside the folder +- `wikitool raw clarify --page "" --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 + +**Options** + +```text +Arguments: + entry A file or folder directly in incoming/ (omit with --page) + +Options: + --item <str> One answer, one line; repeat for more + --page <str> Clarify the source of this existing page instead of an entry of + incoming/ + -h, --help Show this message and exit. +``` + +**Examples** + +```bash +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" +``` + +**Behaviour** + +- 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. + +**Properties** + +- Changes files: yes +- Idempotent: no +- Atomic: Yes - everything is checked before the one write, and the file is created exclusively, so an existing file is never overwritten +- Counts toward the session call budget: yes +- Can reach the network: no + +**Exit codes** + +- `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:` + +**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. diff --git a/instructions/wiki-ingest/SKILL.md b/instructions/wiki-ingest/SKILL.md index 530fca1..1ddc456 100644 --- a/instructions/wiki-ingest/SKILL.md +++ b/instructions/wiki-ingest/SKILL.md @@ -280,6 +280,24 @@ validator complains - and the ticked list is the only record that they happened. No commitment either way in this source? Skip straight to step 5 - the knowledge side runs on its own exactly as before. + **A question about the source itself - the date of a recording, who took part, what an + abbreviation stands for, a transcription error - is asked here, and the answer is kept with + the source, not as a second one.** Ask it as one short question, then write the answers down + exactly as given, one `--item` each: + + ```bash + tools/wikitool raw clarify incoming/<entry> --item "Termindatum: 2026-11-12" [--item "..."] + ``` + + The command writes `incoming/<stem>.clarifications.md` (inside a folder: + `clarifications.md`); step 5 promotes it with the original in the same `raw accept`. **The + test for what goes in:** this session asked about it and the operator answered in a few + points, and it is context of the *recording* - date, participants, occasion, project, + an abbreviation, a transcription error. What the operator adds unprompted, or says about a + subject of its own, is new content and stays a source of its own (the normal route, a file in + `incoming/`). A source already in `raw/` is clarified with `raw clarify --page "<Title>" + --item "..."`, which prints the `raw accept --page` line that adds the file to its bundle. + 5. **Promote from `incoming/` if that is where the file sits.** Read `raw/CONTRACT.md` "Getting a file in" and "Capture fields" if you have not this session - the directory and any bundling are computed, never chosen by hand, but the @@ -299,8 +317,12 @@ validator complains - and the ticked list is the only record that they happened. incoming/<file> [incoming/<other-file> ...] ``` - List every file this one source produced (e.g. a `raw fetch` pair) - in the same call, so they land bundled together rather than as two independent promotions. A + List every file this one source produced (e.g. a `raw fetch` pair, or the + `<stem>.clarifications.md` that step 4's `raw clarify` wrote) in the same call, so they land + bundled together rather than as two independent promotions - the bundle is named after the + original, whichever file comes first. The companion file inherits the bundle's one + `--fidelity`/`--authority` pair; step 6 lists it in `raw_files:`, and a claim that rests on it + is cited to it with `cite add`, so that the page shows it as the operator's statement. A file already in `raw/` skips this step entirely. A folder is accepted as a whole, on its own: ```bash @@ -542,7 +564,7 @@ validator complains - and the ticked list is the only record that they happened. ## wikitool commands used -`raw pending`, `raw fetch`, `raw derive`, `raw accept`, `raw status`, `raw capture`, `search`, `types describe`, `task new`, `task list`, `task close`, +`raw pending`, `raw fetch`, `raw derive`, `raw clarify`, `raw accept`, `raw status`, `raw capture`, `search`, `types describe`, `task new`, `task list`, `task close`, `new project`, `new source`, `new entity`, `new concept`, `touch`, `cite add`, `xref add`, `xref link-source`, `sources coverage`, `sources rebuild-index`, `index rebuild`, `log append`, `log status`, `publish` diff --git a/raw/CONTRACT.md b/raw/CONTRACT.md index fa13962..c93d2c4 100644 --- a/raw/CONTRACT.md +++ b/raw/CONTRACT.md @@ -95,6 +95,25 @@ That is what keeps the clean-up safe: only directories the moves emptied are rem can go with them. A file *inside* a subdirectory is never accepted on its own; the refusal names both ways out - the whole folder, or the file moved up into `incoming/`. +**What the operator answers about a source goes beside it, not into a second source.** An ingest +often has one question only the operator can answer - the date of a recorded meeting, who took +part, an abbreviation. `tools/wikitool raw clarify incoming/<entry> --item "..."` writes the +answers as a companion file in `incoming/`: `<stem>.clarifications.md` beside a file or stem +bundle, `clarifications.md` inside a folder (`-2`, `-3` before the extension when the name is +taken). Name and place are computed; the file starts with a fixed header and holds one bullet per +`--item`, word for word. `raw pending` counts `<stem>.clarifications.md` with its original as one +`bundle`, and `raw accept` promotes both together under `raw/<YYYY>/<MM>/<stem>/`, named after the +original whatever order the files are passed in. A companion file with no original - neither in +the call nor, with `--page`, among the page's `raw_files:` - is refused: a clarification of +nothing is not a source. For a source already in `raw/`, `raw clarify --page "<Title>"` writes the +file to `incoming/` and prints the `raw accept --page` line that folds it into the bundle. Only +what the ingest session asked about *this* source and the operator answered in a few points +belongs in it - context of the recording, an abbreviation, a transcription error; what the +operator adds unprompted, or says about a subject of its own, is a source of its own. The file +sits in `raw/`, is listed in the page's `raw_files:` and is cited like any raw file, so it is +within [`kb/CONTRACT.md`](../kb/CONTRACT.md)'s source and provenance rules rather than an +exception to them. + **An export never comes back in.** A file that carries the stack's export marker is this stack's own output and `raw accept` refuses it, given on its own, inside a folder, or as `--replaces`/`--replaces-bundle` material, naming each one. The marker is either a first line @@ -624,6 +643,11 @@ OK Promoted 1 file(s) to raw/2026/09/handbuch.pdf. --set source_type=<category> ``` +**A clarification inherits the pair of its bundle.** A bundle has exactly one +`fidelity`/`authority` pair, so a `<stem>.clarifications.md` promoted with a `published` + +`normative` source formally carries `normative` too. That is accepted: its fixed header marks it +as the operator's own statement, and what may go in it is limited to context of the recording. + **Fixed once, correctable only as a new edition.** `wikitool touch --set fidelity=<value>` writes a capture field only while it is absent; once set, it refuses and points at the one sanctioned way to correct it - `raw accept --replaces`, which alone may pass `--fidelity`/`--authority` to diff --git a/tools/CONTRACT.md b/tools/CONTRACT.md index 6879e9f..337764c 100644 --- a/tools/CONTRACT.md +++ b/tools/CONTRACT.md @@ -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. diff --git a/tools/chemenu/cli_contract.py b/tools/chemenu/cli_contract.py index 6020ebe..3355da1 100644 --- a/tools/chemenu/cli_contract.py +++ b/tools/chemenu/cli_contract.py @@ -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", ( diff --git a/tools/chemenu/commands/raw/__init__.py b/tools/chemenu/commands/raw/__init__.py index 999a8bd..692c026 100644 --- a/tools/chemenu/commands/raw/__init__.py +++ b/tools/chemenu/commands/raw/__init__.py @@ -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) diff --git a/tools/chemenu/commands/raw/_common.py b/tools/chemenu/commands/raw/_common.py index c759219..12e2fe9 100644 --- a/tools/chemenu/commands/raw/_common.py +++ b/tools/chemenu/commands/raw/_common.py @@ -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]] = [] diff --git a/tools/chemenu/commands/raw/clarify.py b/tools/chemenu/commands/raw/clarify.py new file mode 100644 index 0000000..159c2ec --- /dev/null +++ b/tools/chemenu/commands/raw/clarify.py @@ -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." + )) diff --git a/tools/chemenu/commands/raw/pending.py b/tools/chemenu/commands/raw/pending.py index 645383e..770f589 100644 --- a/tools/chemenu/commands/raw/pending.py +++ b/tools/chemenu/commands/raw/pending.py @@ -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( diff --git a/tools/chemenu/tests/test_raw_clarify.py b/tools/chemenu/tests/test_raw_clarify.py new file mode 100644 index 0000000..f647cf0 --- /dev/null +++ b/tools/chemenu/tests/test_raw_clarify.py @@ -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 diff --git a/types/source.guidance.md b/types/source.guidance.md index 4720959..0a2c588 100644 --- a/types/source.guidance.md +++ b/types/source.guidance.md @@ -28,6 +28,7 @@ knowledge). One source page stands for **one logical source**, which may span se - `source_type` has **no default** - `wikitool new source` refuses without an explicit value. Where the category is unclear, set `unclassified` rather than guessing; that is a visible catalog slot with an advisory `lint` finding, not a dumping ground. What separates `analysis` from `document`, and which area holds which value, is a call this instance's own collection contract makes - see `kb/sources/COLLECTION.md` - `raw_files` lists every raw file this source covers (one source page per logical source, not per file) - `fidelity` and `authority` are **capture fields** (`capture_fields:` on this type): recorded at the drop point and not freely changeable afterwards. `wikitool raw accept --fidelity <value> --authority <value>` refuses without both; without `--page` it instead prints the ready-made `new source --set fidelity=... --set authority=...` line, which `new source` in turn refuses without both values. `wikitool touch --set fidelity=<value>` only writes while the field is absent - where a value already stands, it refuses and points at `raw accept --replaces` as the one correction path (a corrected capture is a new edition, not an edit). `unknown` is backfill-only: only `wikitool touch` may write it, never `raw accept` or `new source` - the same construction as `source_language` uses for pages that predate this rule. What the values mean and how they differ: [raw/CONTRACT.md](../raw/CONTRACT.md#getting-a-file-in-incoming) +- A `<stem>.clarifications.md` in `raw_files` is the operator's answers to what the ingest asked about the source (`raw clarify`): cite what rests on it to that file with `cite add`, so that the page shows it as the operator's statement and not as the source's own text - For external articles, always set `source_url` to the origin URL - Set `source_language` to the raw material's language, not the page's - The page is written in the KB language, whatever language the source is in; verbatim passages are quoted in the original (`kb/CONVENTIONS.md` § "Language")