Repository navigation
Add blueprint validation, guarded editing, and review workflows - #3
Merged
Merged
Conversation
…b genitive chains - calibration: sentence_burstiness / sentence_entropy / connective_density are now scored only when the reference profile carries a measured baseline, matching the existing paragraph_shape_cv pattern and the documented 'skip zero-valued baselines' contract. An empty baseline previously fabricated a connective-density hit via the rate floor and added dead weight, so the 8 Sep paper numbers (14/15, 0.261-0.724, outlier 0.183) were no longer reproducible. They are now. - reference: from_json no longer maps legacy windowed_ttr (TTR ~0.5-0.6) onto mtld (scale ~10-30); stale profiles load with an empty mtld distribution instead of a category error. - rules: light-verb reduction (nominalization NLP path + kancelaryzm) is skipped when the complement noun heads a genitive chain, so the engine never emits a dangling genitive (e.g. 'aby zweryfikować poprawności wykonania'). Conservative: skip the reduction rather than re-case. - tests: regression test locks the 15-doc reproduction (14/15 above 0.25, outlier ai_legal_10 = 0.183, no shape signal scored against an empty baseline); NLIValidator mocked in the hybrid-fallback fixture test. 422/422 tests pass.
morfeusz2 is required by nlp/morfeusz.py (morphology wrapper); add the remaining [all] extras (gradio UI, build/hatchling, pytest, ruff) and a requirements.txt documenting the full install.
…y section (frequency as metadata); form-field line filter in is_heading; title-based corpus partition tool (WIP)
…rom details JSON, --resume flag)
…) filename recovery
- humanize_pl/nli.py: check_document_against_blueprint, one LLM call per section, conservative tie-break (unsure -> entailed), lenient on bad JSON and endpoint failure, redaction preserved - blueprint.py: optional Section.expects (clauses a section must say) - llm.py: complete_json() for non-rewrite JSON questions (reuses transport) - cli.py: 'nli' command (document.docx --blueprint skeleton.yaml) - tests/test_nli.py: 20 synthetic tests, no network, no external data On feat/nli-blueprints only; main untouched.
The operating point in README was measured on held-out judgments, and the split that produced them was done once by hand and never written down. saos_train.jsonl and saos_holdout.jsonl are referenced by derive_patterns.py, validate_structural_signals.py and the README, and no code in the repository created them, so the published numbers were not reproducible. Assignment is a hash of the record id rather than a shuffle. A seeded shuffle is reproducible only while somebody keeps the seed and the corpus stays the same length; a hash survives both, so fetching more judgments later leaves every existing document on the side it was already on and a profile cannot quietly start training on its own holdout. build_reference_profile.py now passes `families`. Without it a profile records only the families its corpus happened to contain and calibration silently stops measuring the rest - the failure mode humanize_pl/corpus/profile.py documents as producing the blindest baseline of all. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
It exists because the alternative failed silently. A reference profile records only the families its corpus happened to contain, the quality gate constrains only the families someone remembered to write a constraint for, and nothing compared the two lists. typography_artifact fell through both. The detector fires it, the shipped profile had never heard of it and neither had the gate, so the em dash - the most recognisable AI tell in Polish, and one the engine already rewrites - was measured and then dropped on the floor twice: it could not raise the calibrated score and it could not produce a single gate violation. A family added here and nowhere else now fails a test, which is the point. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The shipped profile predated four metrics. `from_json` fills a missing field with an empty distribution and drops keys it does not recognise, so an out-of-date profile loaded without complaint and calibration then skipped the metric through `if not profile.<metric>.is_empty`. Measured: the signal list for an AI document contained no sentence_burstiness, no sentence_entropy and no connective_density at all, while the file carried a windowed_ttr nothing reads. Rebuilt from the training split (1804 judgments) with the canonical family list, and a test now compares the two key sets directly. sentence_burstiness is recorded and never scored, for two independent reasons. Dividing (sd - mean) / (sd + mean) through by the mean gives (cv - 1)/(cv + 1), a strictly increasing function of sentence_length_cv - the same quantity on a compressed scale, and cv already carries the heaviest weight there is. Worse, that scale is negative across the whole human range, and _exceedance_low returns 0.0 for any non-positive median, so the signal could never fire and would sit in the weighted average contributing a permanent zero. Contracts get their own profile, measured on 51 approved documents from one firm, all of which read as human against SAOS. This settles the genre caveat the README carried from the start: compared against contracts rather than judgments, the populations separate again (human max 0.1137, AI min 0.2009). The repository ships the derived statistics only; the documents stay local. Thresholds move with the profile, because a calibrated score is a weighted mean exceedance above ONE human range and means "how far past these particular humans". Measured on 27 full-length generated documents against 300 held-out judgments and 51 contracts: filings 0.15 at 100% recall and 3.0% FPR, contracts 0.08 at 78% and 5.9%. The old global 0.25 catches 22% of real filings and no contracts at all - it was fitted to documents of 89-160 words, where the score is inflated and unstable. sentence_length_cv moves to structural.py as the single definition, so the detector and the rhythm layer cannot drift apart on the same formula. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Below roughly 150 words the calibrated score stops being a measurement. Every family signal is a rate per 1000 words and every shape signal a distribution over sentences, so in a 55-word answer one em dash reads as 18.2 per 1000 - enough to saturate any human baseline by itself - and seven sentences cannot produce a human spread of lengths no matter who wrote them. The reference corpus is judgments thousands of words long, so a short answer is not a small sample of that population but a different kind of object. The gate exists for exactly those short answers, so raising the threshold or blunting the rules would have traded away the case it was built for. It now judges a short answer on how many different machine frames it reaches for. Measured on the two fixtures, both ~55 words: the machine-drafted one fires six distinct families, the human-drafted one fires two, and both of those are hygiene rather than register - an em dash and a nominalisation. The score is still reported, because hiding it would invite someone to compute their own, and `score_is_meaningful` says it did not decide. Also adds the typography_artifact constraint the gate had been missing, so a detected em dash can finally produce a violation. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
"Mając powyższe na uwadze" came out as "Mając te na uwadze", which is not Polish, and shipped that way into paper_evaluation/engine_results.md. The inflection table was not at fault: "to" is present for neuter singular and is found on the first lookup, without relaxation. "te" is reachable only with Number=Plur, which is never relaxed. The bad input came from the tagger - "powyższe" is homographic between neuter singular and non-masculine-personal plural, Stanza chose plural for the standalone use, and _build_replacement copies the token's features verbatim. None of the three existing guards could express the distinction, because they all compare lemmas and what separates the two readings is the presence of a head noun. `require_right_upos` adds that, and all four rules that swap to `ten` now carry it - each can be substantivised in legal Polish. An unknown guard name is now refused rather than ignored. It used to be swallowed silently, so a typo disabled a safety measure without a trace. Two rules were dead: transparentny and finalny had no inflection paradigm for their targets, so _build_replacement always returned None and neither could ever fire. tools/rules_lemma_audit.py has detected this from the beginning and nothing ran it - it is now wired into both `make release-check` and humanize-pl-release-check, and the missing paradigms are derived. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The detector has always measured these and the engine could only describe them, handing the caller a regeneration constraint. This moves them instead, through the same safety gates every other rewrite passes. No word changes: sentences join on a semicolon or by undoing a transition the engine itself produced, and split only at points rules/sentence_flow.py already accepts. The target is the band, not the maximum. A document whose sentences all run the same length reads as machine-written; so does one alternating between three words and sixty. The detector only scores the first, because it measures "how far below the median", so a layer trusting the detector's own view would optimise straight past the human range and report success. band_distance is therefore two-sided and the loop stops on entry to the band. Two things only came out in measurement. Capping the merge on its parts admitted exactly the merges that move the metric the wrong way - joining two short sentences replaces two below-mean values with one near-mean value, which lowers the coefficient of variation. On a real document every short merge dropped CV and only merges producing 28+ words raised it. The cap is now on the result. And band_distance saturates at 1.0, correct for scoring and flat for search: a document far outside the band ties every candidate at zero gain exactly when there is most to do, so ranking uses the unsaturated distance while the stop condition keeps the detector's own. Measured on 15 corpus documents in standard mode: 10 were changed, every one of them toward the human median (e.g. 0.4339 -> 0.6079), and none changed its paragraph count. Expect little of it. Closing both axes completely is worth about 0.045 of calibrated score against an UNCERTAIN_BAND of 0.035, and in DOCX - where the paragraph axis is unavailable because a changed paragraph count makes the flow discard the entire rewrite - the ceiling is 0.014. The layer is built to be correct and to refuse when unsure, not to be decisive. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`expects` was optional in the loader and empty in all seven shipped skeletons, so expected_clauses fell back to the section's own label and the clause check degraded from "does this section say what it owes" to "does this section mention its own name" - a much weaker question, asked silently. All 61 sections now declare their clauses: 83 of them, written for a person to read. A test refuses a skeleton that ships with an empty `expects`, and one whose clause only restates the label. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Three changes that belong together because they share run_all_layers. A document missing a section its category owes is not ready to send, however clean its prose. BlueprintReport.blocking has carried that distinction since blueprints were added and nothing consumed it, so blueprint.py promised that `required` blocks readiness while every such document came out ready_with_warnings - indistinguishable from one with a stylistic note. The processing axis is untouched: `status` stays "ok" and batch exit codes do not move, and summarise gains `not_ready` so the three readiness counts still add up to `ok`. The PDF label changes from "błąd" to "niegotowy", because the run succeeded and the text is there; what is missing is a clause. The skeleton now reaches the rewrite prompt, but only the section the fragment sits in. Shown every section a document owes, a model reads a missing one as an invitation to write it, and this pass redrafts one sentence. Segmentation reuses nli.locate_sections so the prompt and the clause check cannot disagree about where a section starts. The rhythm pass runs on text the rules have already cleaned and before the hosted model sees it, so the model reads the shape we intend. DOCX coerces the scope to sentences_only and says so: structural_differences compares the paragraph count, and a mismatch makes the flow restore the source and discard every edit in the document. llm.py gains complete_text with a temperature parameter, for asking a model to write rather than judge, and reports where a reasoning model's token budget went instead of calling the result an empty response. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Mostly work that was already in the tree when this session started: a single `humanize()` returning FlowResult, both console scripts pointing at one Typer app, and flows/cli.py reduced to a shim so existing imports keep working. What this adds is the removal of the second engine hiding inside `run`. A folder was handed to _process_docx_directory whenever --report was given without --llm, --style-profile, --profile-from, --blueprint or --nli. That implementation called process_docx directly and ran no detection, no calibration, no structure check, no tone comparison and no quality gate, and emitted a different JSON schema. So `run docs/` and `run docs/ --report r.json` produced materially different results from the same input, and which engine you got depended on whether you asked for a report. 107 lines, gone. Removing it exposed the other half: --report was then silently ignored for a folder. The run always wrote flow-report.json into the output directory and the requested path was never created, so `--report batch.json` produced no batch.json and said nothing. `run` is now a real superset - it gained --rewrite-backend, --require-llm, --require-renderer and --no-report - and --llm stays a shorthand while no longer conflating "use the model if it is there" with "fail without it". test_cli_batch pinned the old report schema, which was the second output format. It now pins the canonical one, plus a regression test that the report flag does not change which engine runs. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
corpus_prompts.yaml has been in the repository since the corpus was first
described and nothing read it: `{zadanie}` was never filled in by any code, so
the documents it was meant to produce were written by hand instead. Eight of
the fifteen fixtures carry generated_by: unknown, and that folder's README
says they were written to contain the patterns the detector looks for.
Measuring a detector against text authored to be caught is circular, and it
inflated the published separation: those eight score 0.318-0.682 while real
model output scores 0.192-0.335.
The runner closes that loop. It walks scenario x register x temperature
deterministically, records which model wrote each document under which
settings, and keeps the word count because the calibrated score is not stable
below roughly 600 words - truncating one document to 150 words doubled its
score, and the same happens to human text.
The grid gains the temperature axis its own header described and never
carried, and the esej_prawniczy category, whose absence made the one corpus
document without a skeleton impossible to reproduce.
MAX_TOKENS is 16000 rather than 4000. The lower budget failed in a way that
looked like the model refusing: a reasoning model emits its trace first, and
4000 tokens went entirely on ~12k characters of reasoning_content, returning
finish_reason: length and an empty answer on four of eight categories. The
four that survived were the ones it happened to think about briefly - so the
budget was silently selecting which documents entered the corpus, which is the
provenance artifact this tool exists to remove.
partition_corpus.py loses two positional defaults pointing at one developer's
Documents folder, which made it runnable by exactly one person.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The previous version ran on paper_evaluation/dataset/ - forty documents of four sentences each, assembled by random.choice from lists that are literally the detector's own signal families: openings is discourse_frame, empty_emphasis is abstract_frame, typographical is the em-dash artifact, connectors is transition_marker. It tested twelve of the forty, and its baseline half was a chat session no script could reproduce. Numbers from that setup do not support a claim about the engine; they report how well the engine finds patterns planted for it to find. The generator also emits ungrammatical Polish, so part of what the engine appeared to "fix" was cleanup after it. evaluate_engine.py now runs on docs_tests/ai_generated/, on every document, and splits results by generated_by. That split is not a detail: the eight hand-written fixtures score 0.318-0.682 while the seven real model outputs score 0.192-0.335, so a result quoted over the pooled set is carried substantially by documents written to be caught. generate_dataset.py stays as a deterministic fixture generator for rule regressions, where planting the pattern is the point, with a header saying so. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Three claims in this README did not survive contact with a corpus of full-length documents generated from the prompt grid. The operating point. 0.25 at 86% recall was fitted to documents of 89-160 words. On full-length documents it catches 22% of filings and no contracts at all. Measured per family: filings 0.15 at 100% and 3.0% FPR, contracts 0.08 at 78% and 5.9%, with the contract populations still overlapping. Burstiness as the strongest discriminator. Human 0.83 against AI 0.45-0.53 was measured with hand-written imitations on the AI side. Separated by provenance, real model output sits at 0.73 against a human 0.80 - it barely discriminates at all. Paragraph shape holds up in both groups and is the stronger signal. sentence_burstiness is also algebraically the same quantity as sentence_length_cv, which the text now says. Population separation. Human max 0.2309 against AI min 0.1919: they touch. The previously reported gap came substantially from the hand-written fixtures. Adds three sections for what the measurements turned up: eight of fourteen signal families never fire on an actual contract, pleading, terms of service, demand letter or official letter - they live in essayistic prose, which is also why fixtures written to "look like AI" scored so high; short texts and the gate; and the contract profile that settles the genre caveat. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
"What changed" needs a left column and three layers had none. The AI signal always carried signal_before/signal_after and family_counts_before/after; style compliance, house tone and structure were computed on text_out alone, one field each. So the report could say "signal 0.31 -> 0.22" and could not say "four forbidden phrases, now none" - it had never looked at the input. A document arriving with three style departures and leaving with one showed "1 departure", which reads as a fault rather than an improvement of two. A document that arrived clean showed the same thing. Each of the four layers is now a pair. The unsuffixed names survive as properties meaning "the state the document left in", because reports/pdf_pl.py, flows/replay.py and the UI all read them and changing that here would have meant changing everything at once. Three of the four are free on the way in: two are regex passes and compare_tone reads metrics the input detection already computed - measured at 2.85 ms for the most expensive. Clause coverage is the exception, costing one model call per section, so its "before" is taken only when a rewrite actually changed the text; on identical text the answer is identical and billing twice buys nothing. A detail file written before the split carries only the unsuffixed key, which held the output state, so from_json maps it onto _after. Dropping it would turn "measured, clean" into "not measured" on resume, and those read the same in a report while meaning the opposite. This is the prerequisite for the per-axis "what changed" section of the final report: style, words and structure, each before and after. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`rewritable` drives `findings_rewritable`, the number that tells a reader how much of what was found the engine could have fixed. Nominalisation density said True for every occurrence, and measured on twelve corpus documents it found 69 and the engine fixed 2. The nominalisation rules act on light verb plus deverbal noun - "dokonać analizy" into "przeanalizować", 130 such pairs. What actually drives the density in generated filings is bare deverbal nouns in subject and object position: "podporządkowanie", "ustalenie", "naruszenie", "nieważność". Those come out only by restructuring the sentence, which is the one thing this engine refuses to do. Light verbs occur at 3.73 per 1000 words against a nominalisation density of 6.45, and most are not in a rewritable pair. vague_reference_density, computed three lines above, has always said False for exactly this reason. The signal stays - it earns its place. AI filings nominalise at 6.45 per 1000 words against 1.68 for human judgments, four times as often. But it belongs in "worth telling the author about", not in "the engine will fix this". On the same twelve documents the rewritable share drops from an inflated figure to 44%, which is what it was all along. Worth recording alongside: of 131 applied changes on those documents, 90 were `cleanup_spacing_and_em_dash`. Two thirds of what the engine reports as edits is whitespace and punctuation. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The rest of the report answers "what was found". This answers the question a reader actually opens it with: did anything get better. Three rows - house style, words, structure - each with a before and an after, right under the headline numbers. It could not be written until every layer was measured on the way in as well as out; two of the three rows had no left-hand column at all. Three rules it has to keep, because each was a way of misleading the reader: An axis with nothing behind it says "nie dotyczy" and names the reason, rather than printing a zero. "No office profile supplied", "no skeleton for this category" and "checked, clean" are three different pieces of information and a lawyer acts differently on each; collapsing them into 0 says the document passed a check that never ran. Words are counted per 1000, not raw. A 2700-word document and a 300-word one are not comparable on totals, and the corpus spans exactly that range. A diagnosis-only run shows two equal columns rather than an empty left one. `--no-rewrite` is not an improvement of zero. Numbered 1.1 rather than 2: the section numbers in this file are literals and two other sections already start at 2, so renumbering would have been a much larger change for no gain. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
An office profile carries `preferred_terms` - pairs the firm wrote down in its style guide - and nothing acted on them. They reached the hosted model's prompt as a line of text, and the compliance check reported which ones were still wrong. The rules engine, the part that actually edits, never saw them. So the axis this product is meant to own - sounding like this firm rather than like a firm - was the one axis that only ever produced a note. These are phrases, not lemmas, so they cannot go through `lemma_engine`: that path needs an inflection paradigm for the target and the table ships three. A new rule matches the phrase the office wrote down and swaps it, carrying the source's capitalisation, longest entry first so "umowa zlecenia" beats "umowa". It runs in standard and strong only - house terminology is a preference, and conservative exists for people who accept no stylistic risk. The preposition guard is the part worth reading. Being literal is safe only while the grammar around the phrase stays put. Measured on the first version: "w drodze uchwały", with an entry "w drodze -> przez", came out as "przez uchwały" - `przez` governs the accusative and the genitive left behind it no longer fits. The agreement gate does not catch this, because it checks adjective-noun agreement rather than what case a preposition governs. So the candidate is refused before it exists, on a crude and strict test: the same prepositions in the same order on both sides. That admits "w przedmiocie -> w sprawie" and refuses the other, which is the distinction that matters. Renaming a party still fails, and should. `legal_anchor_retention` refuses "Zleceniobiorca -> Wykonawca" because a rename applied one sentence at a time leaves the document disagreeing with itself - a clause elsewhere saying "Zleceniodawca zapłaci Zleceniobiorcy" would no longer match. A consistent rename is a document-level operation, not a per-sentence candidate, and the test pins the refusal rather than working around it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The "what changed" section had unit tests and had never been produced by a
real run. One command against a real office profile found both of these.
The CLI died on Windows. A console on a legacy code page cannot encode the
arrow in the progress line ("sygnał 0.31 → 0.22"), so every run raised
UnicodeEncodeError after the document had already been processed - the work
was done and thrown away at the last step. stdout and stderr are now
reconfigured to UTF-8 at import, which also stops Polish diacritics coming out
mangled. Reconfiguring rather than telling the user to set PYTHONIOENCODING:
the tool writes Polish by design, so a console that cannot show it is the
tool's problem.
A blocked readiness was overwritten one call later. `run_all_layers` marks a
document missing a required section as not ready, and the DOCX flow then
raised anything carrying a warning to "ready_with_warnings" unconditionally -
and such a document always carries warnings, because the missing section is
one of them. So the distinction `BlueprintReport.blocking` exists to draw was
undone by its own caller, and a contract missing its performance-deadline
clause reported as merely annotated. Verified on a real document: it now comes
out "niegotowe: 1".
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The inventory guard compares paragraph counts, so anything that adds a paragraph made the flow discard the entire rewrite and restore the source. That is right for a rewrite, which has no business changing the shape of a document, and wrong for the one operation that must: supplying a clause the document owed its category. The delta is declared in advance and checked for equality, not as a ceiling. "Paragraphs may grow" would let a run drop one clause while adding another and still pass; "paragraphs must grow by exactly three" fails the moment anything else moves. Every other count stays exact, so this widens the guard in one dimension, by one declared amount, and nowhere else. Tested on the case a ceiling would have hidden: declaring one, adding one and removing one, where the net count is right and the document is not. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The third axis stopped at "brakuje klauzuli odpowiedzialności". A
humanizer that knows a section is missing and what it has to say should
write it, so the flow now drafts every missing `required` section with
the hosted model, from the skeleton's own `expects`, and puts it where
the skeleton says it belongs.
The clause enters the document unmarked, by the owner's decision, which
puts the weight on everything around it:
- facts are never supplied: the model leaves "…" where an amount, date,
party or article number belongs, and a draft carrying a figure, date,
legal reference or identifier the document does not have is refused;
- a draft that restates the requirement ("Umowa określa…") instead of
meeting it, or that the structure check would not recognise, is sent
back once with the reason, then refused;
- a section gets a unit of its own: "§ 2a" between existing units, the
next number after the last one, no "§" for the signature block
(`unit: false`), so no cross-reference is renumbered;
- a DOCX gains exactly the announced paragraphs, formatted like their
neighbours, and the inventory guard checks that figure; if the save is
withdrawn the drafts are reported as proposals and readiness reverts;
- a document with a drafted clause is never `ready`, and the PDF lists
every draft in full in section 1.2, right after the before/after table.
Spreadsheet cells are answers, not documents, and are never drafted into.
`--no-draft-missing` turns it off.
Two prompt corrections came from running the configured model: it read
the ban on "przepisów" as a ban on naming the Civil Code, and it copied a
requirement into the document as a clause.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The families table lists what was found, so every family missing from it reads as checked and clean. Measured on the AI corpus (27 documents from qwen-local), ten of the fourteen families never occur in AI-written contracts or court filings either: the model writes "Warto zauważyć, że" in an essay, not in a payment clause. In those documents their absence cannot tell AI from human. `tools/family_activity.py` records, per document family, which signal families the model produced at all, into data/family_activity.json. The report adds a note under 5.3 naming the families whose absence proves nothing for the kinds of document in the batch, with the size of the measurement and its single generator. A family found in the batch despite never appearing in the corpus stays out of that list. The families are still detected: another generator may produce them, and a hit is still a hit. Two families (balanced_pair, concessive_reversal) fired in no genre at all, essays included. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Found by running the engine on real model output instead of hand-written fixtures: - "---" became "– -" in 25 of 27 documents: the double-hyphen rule replaced the first two hyphens of a markdown rule and left the third; - "zawarta w dniu ……… r." became "w dniu………": the space-before- punctuation rule treated a blank to fill in as a full stop. The first one also flattered the numbers. The detector counted "---" as a typography artifact and did not recognise "– -", so "223 → 0" was mostly this bug; measured honestly, 268 → 259. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…alling markdown a dash
Run on real model output, the engine missed what gives such output away
first. Measured on 27 model documents against 2396 court judgments:
**bold** in 25 of 27 (1 judgment), "#" headings in 26 (0), "---" lines in
25 (0), markdown tables in 5 (0), asides to the user ("Poniżej znajdziesz
gotowy wzór…") in 12 (0), "[data]"-style fields in 17 (2).
These are traces of the channel, not of style, so they get a layer of
their own (humanize_pl/artifacts.py) instead of a place in the calibrated
score, which would otherwise measure which window the text was copied
from. Bold and heading markers are removed and rule lines emptied, line
for line so DOCX paragraphs and protected indices hold. Tables, asides
and fields are reported and keep the document from reading as ready.
Hyphen lists (756 judgments) and dotted blanks (52) are not traces; a
dotted blank still counts as a field to fill.
The dash detector counted "--" inside "---" and "|---|": 259 of the 268
"em dashes" in the corpus were markdown. Fixed, and the consequence is
recorded rather than hidden: at the current thresholds filings are caught
6 of 12 instead of 12 of 12, contracts 0 of 9 instead of 7 of 9. The
contract operating point was detecting markdown. Thresholds are left as
they are until re-measured on purpose; README and calibration.py say so.
The report's "Co się zmieniło" table gains two rows: tool traces and
fields to fill, before and after.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The enumeration protector matched "^\s*1\. " with MULTILINE, so on a blank line "^" matched and "\s*" swallowed the newline. The placeholder then opened a paragraph, and the spacing cleanup stripped the whitespace the placeholder restored: a real model contract lost 53 of its 92 blank lines. Content survived, but a .txt output has no other paragraph breaks. Spaces and tabs only now. All 27 corpus documents keep their line count exactly. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The before/after table existed only in the PDF, so a batch could not be aggregated from flow-report.json and a spreadsheet user never saw it. The rows are now computed once, in humanize_pl/reports/axes.py, and read by all three: the PDF prints them as before, `summary.what_changed` carries them as numbers (an axis that does not apply has `before: null` and a reason, never a zero), and the XLSX flow adds one "przed → po" column per axis that applies to at least one row. tools/build_ai_corpus.py: `--missing-only` completes a run that lost documents instead of repeating it, `--timeout` overrides the endpoint limit - the five lost documents all died on ReadTimeout and were the long ones, so the timeout was biasing the corpus toward short documents - and the manifest is written after every document, so a run that dies midway leaves no text of unknown provenance. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…k that exists
Bielik drafted a second signature block into a contract that had one:
"ZLECENIODAWCA" over a dotted line, "ZLECENIOBIORCA" over another. The
skeleton knew the words "podpis", "zamawiający:" and "wykonawca:", and a
false "missing" is costly once missing sections are written in - it puts
a duplicate into the document.
The role as a word is in every clause, so no substring can tell the
block from the body. Sections may now carry `patterns:`, regular
expressions over the lowered text; the contract's signature block is a
party's role alone on a line over a dotted line or "(podpis)". A
section's position is taken from where its match starts, and the
insertion boundary for a drafted clause locates later sections on the
whole text, so one found by a pattern still keeps a final clause from
landing after the signatures.
Also from the same run: a number alone on its line ("2.") now joins the
line after it instead of becoming a paragraph of its own.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Any unresolved finding used to hold a document below "ready", and 291 of 300 held-out court judgments carry at least one, so "ready" and "ready with warnings" did not distinguish anything. Readiness now reads compliance - the share of sentences no unresolved finding points at - against READY_COMPLIANCE, 0.96, the number the owner chose. The gate's verdict (score past the threshold, drafted clauses, chatbot asides, fields to fill) and warnings still hold a document back as before. Measured when it was set and kept beside the constant: 26 of 300 judgments reach 96% (median 91.7%), 14 of 32 model documents after the rewrite (median 94.9%). The measure counts flagged sentences; it does not say a text reads as human, and at 90% 217 of the judgments would pass. Compliance is in every item's JSON, on its console and browser line, and in the report's readiness column, which now also states the rule. The hosted model declining fragments is a run note, not a warning. tools/build_ai_corpus.py gains --max-tokens: the default is sized for a reasoning model and, with the prompt, would overrun a 16k context. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…after blanks Bielik's "termin i sposób wykonania" for a contract with no attachments put the schedule "w załączniku nr 1" and the reports "w załączniku nr 2" - references to documents nobody wrote. An attachment number absent from the document is now an invented particular like a date or an amount. The same draft wrote "… (np. 15. dzień każdego miesiąca)": a hint for whoever fills the blank, not contract text, and a place for an invented term to hide. The hint is dropped and the blank kept, with a space so it still counts as a field; the period check also knows "dzień" now. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
One corpus per generator, pooled: a family silent for one model says something about that model, silent for every model measured it says something about the genre. Ready for the Bielik corpus being generated. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Every finding about AI legal text here was measured first on one model. This lays the same measurements side by side per corpus - tool traces, style families silent in document genres, recall at each family's threshold on text as it would read in Word, classifier accuracy - so a claim reads as true of one model or of all measured. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The superseded operating-point table quotes an FPR "on 592 held-out judgments", while the older 0.25 measurement quotes 599. Both are true and they are different splits: 592 is the held-out part of the on-disk split of the 2396 corpus (1804/592, the 1804 being what the shipped SAOS profile was built on), 599 the earlier 1797/599 split. One sentence in each place says so; no number changes. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…n threshold The legend told users the 0.25 threshold "daje 100% wykrycia przy 0% fałszywych alarmów" on 599 held-out judgments. That was measured on nine short documents and the README has since shown it does not hold on full-length ones; after the dash fix contracts are not separated at all. The legend now says the threshold depends on the kind of document, that a score past it asks for a review and proves nothing, and that tool traces are what give chatbot output away. The verbal reading used 0.25 for every document, so a contract at 0.10 read "jak u ludzi" while the flow, at 0.08, flagged it. It takes the family's threshold now, and the batch summary words the mean only when every item shares one. Contracts were also listed as uncalibrated; they are compared with the firm's contracts. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The Bielik endpoint dropped twice during corpus generation, and each time the runner raced through the remaining jobs in minutes: 5 documents written, 23 marked failed. A connect error, a timeout or a 502/503 now means the server is gone rather than that it answered badly; the runner polls it every 30 s for up to --wait seconds (default 30 min), retries the same job when it returns, and stops the run cleanly if it does not. Each poll uses a fresh client, because probe() remembers its first answer and would report a dead server as ready. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
A run can now be started while the server is down and begins when it is back. The poll uses a 15 s limit of its own: with the generation timeout one attempt on a dead host would have lasted twenty minutes. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…e model's habit A Bielik 7B corpus (bielik-minitron-7b-dflash, the same 32-prompt grid) was generated and compared with qwen-local's using tools/compare_generators.py: - the ten rhetorical style families silent in document genres are silent for both models, 48 documents in all: a property of the genre, not of a generator. data/family_activity.json now pools both corpora, and the report's note says "none of the models measured" when there are several; - markdown was qwen-local's habit: Bielik wrote not one marker on 32 documents. Fields to fill are common to both (21 and 23 of 32), asides to the user less so (26 and 11). README and the artifacts docstring now show both columns instead of generalising from one model; - on text without markdown, contracts are caught 0/12 for qwen and 3/12 for Bielik, filings 7/12 and 6/12. Bielik writes half as long (median 414 words) and a length control is inconclusive; README says so rather than claiming either reading. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…ording The aside pattern was read off qwen-local's output and caught Bielik's in 11 of 32 documents - it was measuring the pattern, not the model. Bielik opens almost every document "Oto przykładowy / kompletny …" and closes with "może wymagać dostosowania", "dostosować do konkretnych potrzeb", "Pamiętaj, że…", "skonsultować się z prawnikiem". With those shapes, each measured against the 2396 judgments first: 25 of 32 for Bielik, 26 of 32 for qwen-local, 2 of 2396 judgments. Asides are common to both models after all; only markdown is one model's habit. README and the artifacts docstring say so. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
qwen-local and Bielik 7B, 32 documents each plus the manifest with the prompt, style and temperature of every one. Generated from the prompt grid in tools/build_ai_corpus.py, so no client text; the generation logs stay out under *.log. The SAOS judgments and other downloads remain local. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…youts The role-specific pattern wanted the party's name over the dots. The firm puts the dots over the names, pads the name line with long runs of spaces, runs two names together where a tab stop was, or closes with two dotted places and nothing under them. On the firm's 50 contract-family documents the old pattern found 0 signature blocks, so every services contract reported one missing - and with drafting on, the model would have written a second signature block into it. `signature_block: true` on a section adds the shared shapes (`blueprint.SIGNATURE_BLOCK`): found in 45 of the 50 (the other five have no party signatures), in none of the 592 held-out judgments. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…artition
tools/audit_blueprints.py puts two numbers side by side, because a missing
section is drafted into the document: how many of the firm's own complete
documents the check would supplement (27 of 28 at the start), and whether
a titled section cut out of a document is still noticed. Loosening a
pattern moves the first and can quietly cost the second. The firm's
documents split into fixed halves for tuning and checking; counts only.
partition_corpus.ascii_skeleton dropped non-ASCII before mapping Polish
letters, and "ł" does not decompose - "usług" became "usug", and 21 of 100
documents (service contracts, powers of attorney, company resolutions)
fell into "inne". Two rules never matched either ("rozwiązanie" with a
Polish letter the skeleton has none of; "o dzelo").
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…'s court
Measured with tools/audit_blueprints.py. Firm documents the check would
supplement: 13/13 -> 10/13 in the tuning half, 14/15 -> 12/15 in the
unseen half; what is left is pisma, regulaminy and a misfiled patient
notice, each waiting on a decision. No service contract section is falsely
missing any more, and cut sections are still noticed as often (termination
6/7, subject 7/8, term 8/9) - lists that silenced the same drafts but cost
a noticed gap ("wypowiedzeni", "będzie wykonywał", "zobowiązuje się do
świadczenia") were measured and left out.
Pozew: a form's "Sąd ……" at the head of the page, and "wnoszę o:",
"domagam się" for the claim. No firm pozew was in the tuning half; both of
its false gaps went in the unseen half.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Only `run` had it; from `docx`, drafting could be switched off only by switching the hosted model off, and with it every other use of the model. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…r picks `--document-type general` (UI: "tekst ogólny"). Nothing chooses it on its own, so the legal path is untouched: all 633 earlier tests pass unchanged. Measured before built, on ŚMIGIEL (PolEval 2025), Wolne Lektury prose and 314 Polish ChatGPT answers from WildChat-1M written on request: - profile `general_polish` from 1390 human texts of 150+ words; the other 1391 set the threshold. AUC 0.92 against the ChatGPT answers; 0.15 flags 2.1% of human texts and 40% of model ones. - the em dash is ordinary Polish typography, commoner in human text (55-86%) than in ChatGPT's (14%), and opens every line of dialogue in prose. A profile can now declare `ignored_families`; the detector drops those findings wherever the profile is used, so a dash neither scores nor counts against a sentence. Legal profiles declare none - their behaviour is the same. - a genre can switch rules off (`GenreProfile.disabled_rules`): the em dash, passive to impersonal, sentence splits, "w dużej mierze" -> "w znacznym stopniu", "polega na tym" -> "oznacza to" - each changed human text as often as model text or more. - no legal category, skeleton, drafting or rhythm; under 150 words the report says the score cannot be trusted (AUC 0.48 under 50 words). - the hosted model is told it edits a text, not a legal document. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
"to właśnie" was written back as "To" wherever it stood, so a ChatGPT answer came out as "Myślę, że To nazywane jest miłością." Found while reading Bielik's general-mode output; the rule runs on the legal path too. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Asked to remove a tic, a model can write a new one: in the general-mode
run Bielik rewrote "W kościołach znajdowały się ołtarze…" as "ołtarze
pełniły kluczową rolę…". A proposal with more of any signal family than
its source is now rejected ("rejected:adds_ai_signal") and the rules'
version stands. Only what the detector counts is caught - "kluczowa rola"
itself is not a signal, and measured it would be a weak one (2.2% of
ChatGPT answers, 0.6% of human texts).
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Measured on 48 ChatGPT answers and 24 human texts, Bielik's rewriting took 14% of the tics at two minutes a text, changed 13 of the human texts, and lost half its answers to broken JSON: - structured output in the shape llama.cpp reads: after the OpenAI `json_schema`, the same schema under `json_object`, before falling back to the strict prompt; the shape that worked is remembered for the batch. The source echo is compared without regard to spacing. - in general text only assistant tics go to the model (`llm_families`): summary and abstract frames, concessive reversal - 3-20x commoner in ChatGPT answers than in human text. Nominalisation and enumeration are within 1.5x, and those sentences are where human text got changed. - a proposal bringing in a capitalised word mid-sentence that the source lacks is turned down: "PiS-u" and "Guillermo" came in from neighbouring paragraphs. Compared by four-letter stem, so "Polska"/"Polsce" passes. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
On the firm's documents the vocabulary put a deed of gift, two leases of
land, a data-processing agreement and two brokerage contracts among the
leases, image and copyright licences among the NDAs, notices of
termination among official letters and a patients'-rights notice among
privacy policies - and each would have been checked, and supplemented,
against a skeleton not its own.
- a title (first short heading-like line in the first twelve, two-line
titles read whole) naming a catalogued kind settles the category; the
kind named first wins ("Umowa o dzieło i przeniesienie praw autorskich");
a contract title naming none gives `umowa_inna`, which has no skeleton;
"UMOWA" alone leaves it to the vocabulary.
- gate markers every contract carries ("zawarta w dniu", "niniejsza
umowa") open the gate but score nothing: scored, they gave every
contract the same three points and alphabetical order picked the lease.
- new: umowa_dzierzawy, umowa_darowizny, umowa_posrednictwa,
umowa_powierzenia_danych, umowa_licencyjna, porozumienie, oswiadczenie,
klauzula_informacyjna, umowa_inna. None has a skeleton yet.
Measured: firm documents given another kind's skeleton 9 -> 1; firm
documents the check would falsely supplement 22 of 28 -> 14 of 20 (the
rest are official letters and a regulamin, waiting on the lawyer's
decisions); model corpora classified right 26 -> 27 and 19 -> 21 of 32.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Qwen 3.5 (the owner's mtplx server) answers with a "Thinking Process"
first: 60 tokens in, it had not yet begun the answer, and the capability
probe waited minutes. With `chat_template_kwargs: {"enable_thinking":
false}` the same question came back in 2 s. Off by default - a server that
does not know the field may refuse the request. The same server refuses
both structured-output shapes without llguidance, so the strict prompt
carries the format there.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…alone
Both found reading the Qwen general-mode run on ChatGPT answers; both rules
run on the legal path too.
- "w celu + gerund" -> "aby + infinitive" left the gerund's object in the
genitive: "aby zapewnić sprawnego i skutecznego zarządzania", "aby
przeprowadzić kontroli" (the old test asserted that very output). It now
fires only when nothing, "się" or a preposition follows, and puts the
comma a mid-sentence "aby" needs. The engine already skips a light-verb
reduction that would leave a genitive dangling; this rule did not.
- spacing cleanup turned pasted C++ into "=:: CreateFileA(...)" and
")!= 0"; a sentence that looks like code ("::", "->", "!=", "==", braces,
a call ending in ";") is left as it is.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The structure check looks for phrases, and the firm writes the same clause in its own words: on its complete documents it called 14 of 20 incomplete, and each would have got a second, machine-written clause. Before drafting a missing required section the model is now asked whether the document already has it, in any words, and must quote the passage: - "no" -> drafted as before; - "yes" with a passage that really is in the document (masked or restored) -> not drafted; the quote goes to the report (`sections_found_by_model`) and the section no longer fails the document, which stays held back by the warning; - anything else - no verdict, an invented quote, an endpoint error, a document too long to send whole -> not drafted, and still failing. Owner's choice between this and drafting only on request. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Add general editing profiles, proposal review, privacy masking, retention, runtime diagnostics, resumable flows, and document fidelity improvements. Consolidate evaluation tooling and add locked dependencies and CI coverage.
empios
added a commit
that referenced
this pull request
Nov 17, 2026
Local main is the source of truth. origin/main's 68 commits (PR #3: drafting of missing sections, rhythm, nli.py, unified flow/CLI, UI privacy controls) stay in history but none of their changes are kept. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Legal documents can contain a required section without matching its heading, while general prose needs a different editing policy. This change adds section-presence and meaning checks before drafting missing clauses, dedicated general-text editing profiles, and reviewable proposals across the CLI and browser UI.
Changes
Validation
uv.lockwith the CI extras and ANSI colors enabled: 981 tests passed, 4 optional tests skipped; Ruff, the 9-rule lemma audit, the 15-document basic benchmark, and wheel build all passed.Human review on an approved corpus and visual DOCX acceptance remain outstanding, as documented in the README.