krokai 0.7.5__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- krokai/__init__.py +19 -0
- krokai/__main__.py +28 -0
- krokai/_datadir.py +59 -0
- krokai/address.py +178 -0
- krokai/bank.py +242 -0
- krokai/channels.json +217 -0
- krokai/citations.py +384 -0
- krokai/cli.py +943 -0
- krokai/config.py +195 -0
- krokai/consult.py +1131 -0
- krokai/corpus.py +440 -0
- krokai/extract.py +162 -0
- krokai/fetch.py +608 -0
- krokai/hooks/_bootstrap.py +86 -0
- krokai/hooks/bank_queue.py +193 -0
- krokai/hooks/quote_guard.py +215 -0
- krokai/hooks/session_anchor.py +106 -0
- krokai/install.py +173 -0
- krokai/keys.py +173 -0
- krokai/library.py +197 -0
- krokai/mutations.py +162 -0
- krokai/normalize.py +390 -0
- krokai/packs/us-federal.json +98 -0
- krokai/packs/us-immigration.json +125 -0
- krokai/packs/us-tax.json +79 -0
- krokai/prompts.py +280 -0
- krokai/readers.py +376 -0
- krokai/redact.py +596 -0
- krokai/review.py +197 -0
- krokai/run.py +345 -0
- krokai/selftest.py +2112 -0
- krokai/sidecar.py +161 -0
- krokai/templates/CLAUDE.md.snippet +70 -0
- krokai/verdicts.py +223 -0
- krokai/verify.py +447 -0
- krokai-0.7.5.dist-info/METADATA +364 -0
- krokai-0.7.5.dist-info/RECORD +40 -0
- krokai-0.7.5.dist-info/WHEEL +4 -0
- krokai-0.7.5.dist-info/entry_points.txt +2 -0
- krokai-0.7.5.dist-info/licenses/LICENSE +21 -0
krokai/__init__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""krokai - a citation safety harness for AI-assisted legal work.
|
|
3
|
+
|
|
4
|
+
The one sentence that explains the whole package:
|
|
5
|
+
|
|
6
|
+
**A grounded citation does not prove the quotation is real.**
|
|
7
|
+
|
|
8
|
+
Measured, on video, in a real matter: a model was asked to open a specific regulation and quote it.
|
|
9
|
+
It fetched the correct page, attached a correct and verifiable link to the correct URL, and then
|
|
10
|
+
**invented the text of the rule**. Every automated "did it check its sources" audit reported that
|
|
11
|
+
answer as 1/1 grounded and perfectly clean.
|
|
12
|
+
|
|
13
|
+
Only comparing the words against the actual document catches that. This package does that
|
|
14
|
+
comparison, and everything else here exists to make the comparison happen without anybody having to
|
|
15
|
+
remember to run it.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
__version__ = "0.7.5"
|
|
19
|
+
__all__ = ["__version__"]
|
krokai/__main__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""`python -m krokai ...` AND `python <clone>/krokai ...` - the paths that need no installation.
|
|
3
|
+
|
|
4
|
+
Copying the folder and running this is a supported install method on purpose: the audience includes
|
|
5
|
+
people who are not allowed to run `pip install` on a work machine, and a tool a paralegal cannot
|
|
6
|
+
install is a tool that does not exist.
|
|
7
|
+
|
|
8
|
+
π΄ THE SECOND FORM WAS DOCUMENTED AND HAD NEVER WORKED. `INSTALL-FOR-AI.md` told the assistant to
|
|
9
|
+
run `python ~/tools/krokai/krokai init .` from the matter folder - and running a package DIRECTORY
|
|
10
|
+
executes this file as a top-level script with no parent package, so the relative import below blew
|
|
11
|
+
up with `attempted relative import with no known parent package`. Found on 2026-08-03 by executing
|
|
12
|
+
the install document end to end in a scratch folder, which no one had done: every earlier test ran
|
|
13
|
+
`-m` from inside the clone, where the working directory quietly supplies what the documented
|
|
14
|
+
command does not. A document is tested by executing it, on a machine where nothing is already set
|
|
15
|
+
up - reading it proves nothing.
|
|
16
|
+
"""
|
|
17
|
+
import os
|
|
18
|
+
import sys
|
|
19
|
+
|
|
20
|
+
if __package__ in (None, ""):
|
|
21
|
+
# Directory-run: put the CLONE root (the package's parent) on sys.path and import absolutely.
|
|
22
|
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
23
|
+
from krokai.cli import main
|
|
24
|
+
else:
|
|
25
|
+
from .cli import main
|
|
26
|
+
|
|
27
|
+
if __name__ == "__main__":
|
|
28
|
+
sys.exit(main())
|
krokai/_datadir.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Find the data this package ships - `packs/`, `templates/`, `hooks/` - in BOTH install layouts.
|
|
3
|
+
|
|
4
|
+
π΄ WHY THIS FILE EXISTS. Three modules located their data by walking one level *up* out of the
|
|
5
|
+
package directory:
|
|
6
|
+
|
|
7
|
+
krokai/citations.py PACKS_DIR = <pkg>/../packs
|
|
8
|
+
krokai/cli.py ROOT = <pkg>/.. -> ../templates/CLAUDE.md.snippet
|
|
9
|
+
krokai/install.py hooks_dir = <pkg>/../hooks
|
|
10
|
+
|
|
11
|
+
That is correct for a git clone, where `krokai/` and `packs/` are siblings, and it is wrong the
|
|
12
|
+
moment the package is installed: `<site-packages>/krokai/..` is `<site-packages>` itself, and
|
|
13
|
+
there is no `packs` directory there. The failure is silent rather than loud - `available_packs()`
|
|
14
|
+
returns `[]` when the directory is missing - so `pip install krokai` would have produced a tool
|
|
15
|
+
that starts, runs, reports success, and checks **nothing**. The count of citations it verified
|
|
16
|
+
would be zero and the output would not say so.
|
|
17
|
+
|
|
18
|
+
Both layouts are supported on purpose, so the resolver checks both rather than picking one:
|
|
19
|
+
|
|
20
|
+
1. `<pkg>/<name>` - the installed wheel. The build maps the top-level directories into the
|
|
21
|
+
package (see `force-include` in pyproject.toml), so the data travels
|
|
22
|
+
with the code and needs no `..`.
|
|
23
|
+
2. `<pkg>/../<name>` - the git clone, and the "copy the folder and run it" install that
|
|
24
|
+
`__main__.py` documents as supported for people who may not run pip.
|
|
25
|
+
|
|
26
|
+
The order matters. Package-internal wins, so an installed copy can never be silently served data
|
|
27
|
+
from an unrelated directory that happens to sit next to `site-packages`.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
import os
|
|
31
|
+
|
|
32
|
+
__all__ = ["data_dir", "data_file"]
|
|
33
|
+
|
|
34
|
+
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def data_dir(name):
|
|
38
|
+
"""Absolute path to a shipped data directory. Returns the in-package path if neither
|
|
39
|
+
candidate exists, so an error message names a stable location rather than a `..` chain."""
|
|
40
|
+
inside = os.path.join(_HERE, name)
|
|
41
|
+
beside = os.path.join(os.path.dirname(_HERE), name)
|
|
42
|
+
if os.path.isdir(inside):
|
|
43
|
+
return inside
|
|
44
|
+
if os.path.isdir(beside):
|
|
45
|
+
return beside
|
|
46
|
+
return inside
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def data_file(name):
|
|
50
|
+
"""Same search, for a single shipped file. `channels.json` is the one that needs it: its
|
|
51
|
+
fallback path was `<pkg>/../channels.json`, so `krokai review` raised SystemExit on every
|
|
52
|
+
installed copy while working perfectly from a clone."""
|
|
53
|
+
inside = os.path.join(_HERE, name)
|
|
54
|
+
beside = os.path.join(os.path.dirname(_HERE), name)
|
|
55
|
+
if os.path.isfile(inside):
|
|
56
|
+
return inside
|
|
57
|
+
if os.path.isfile(beside):
|
|
58
|
+
return beside
|
|
59
|
+
return inside
|
krokai/address.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Address binding: "found in the corpus" is not the same claim as "found where you said".
|
|
3
|
+
|
|
4
|
+
WHAT THIS ANSWERS
|
|
5
|
+
-----------------
|
|
6
|
+
``verify.check()`` answers *"are these words in some primary source?"*. That is a real question and
|
|
7
|
+
it catches fabrication. It is also, on its own, the reason a checker can bless a citation that
|
|
8
|
+
sends the reader to the wrong page - and an opposing reader who follows a pincite and finds nothing
|
|
9
|
+
has been handed a free argument about your care.
|
|
10
|
+
|
|
11
|
+
So this layer answers the second question: *"were the words found in the document whose address is
|
|
12
|
+
printed next to them?"*
|
|
13
|
+
|
|
14
|
+
FOUR OUTCOMES, AND "COULD NOT TELL" IS ONE OF THEM
|
|
15
|
+
--------------------------------------------------
|
|
16
|
+
``MATCHED`` Β· ``MISMATCH`` Β· ``NO_NEARBY_CITATION`` Β· ``ADDRESS_NOT_IN_CORPUS``
|
|
17
|
+
|
|
18
|
+
The last two exist so that *"I could not check"* never quietly renders as *"it checked out"*. That
|
|
19
|
+
distinction is the whole ethic of this toolkit: for a document that gets filed,
|
|
20
|
+
``NO_NEARBY_CITATION`` means **do not award a green** - not because something is wrong, but because
|
|
21
|
+
nothing can be verified about an address that was never written down.
|
|
22
|
+
|
|
23
|
+
ANCHOR-MISS REPAIR, AND WHY IT NEEDS A FLOOR
|
|
24
|
+
--------------------------------------------
|
|
25
|
+
When the global search landed in file X but the cited address points at file Y, one possibility is
|
|
26
|
+
that the quotation is fine and the *global anchor* simply found another copy first - the same
|
|
27
|
+
provision is reprinted in several places. So the text is re-tested inside file Y, and if it is
|
|
28
|
+
there, the verdict is repaired to VERIFIED with an explicit note that the previous verdict was an
|
|
29
|
+
anchor miss.
|
|
30
|
+
|
|
31
|
+
π΄ The repair is gated at 60 characters, contributed by one reviewer. A short stock phrase
|
|
32
|
+
("not substantially justified") can occur by coincidence inside the file at the cited address, and
|
|
33
|
+
without the floor the repair would bless a coincidence.
|
|
34
|
+
"""
|
|
35
|
+
from __future__ import annotations
|
|
36
|
+
|
|
37
|
+
import os
|
|
38
|
+
|
|
39
|
+
from .normalize import normalise, alnum, dehyph
|
|
40
|
+
|
|
41
|
+
__all__ = ["KeyMap", "address_check", "repair_anchor_miss", "fold", "ADDRESS_CLEAN"]
|
|
42
|
+
|
|
43
|
+
# Verdicts for which a mismatched address is worth upgrading into its own finding. If the text
|
|
44
|
+
# already failed on its own, the address note is appended rather than promoted - two complaints
|
|
45
|
+
# about one quotation read as two defects.
|
|
46
|
+
ADDRESS_CLEAN = ("VERIFIED", "PUNCTUATION", "TYPESETTING", "ASSEMBLED", "SCATTERED")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class KeyMap(object):
|
|
50
|
+
"""address key -> the corpus files that could plausibly hold it.
|
|
51
|
+
|
|
52
|
+
Resolution is computed once per key and cached: there are a few dozen distinct addresses and the
|
|
53
|
+
corpus is megabytes, so re-walking it for each of several thousand quotations would cost more
|
|
54
|
+
than the whole check.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
def __init__(self, corpus, packs):
|
|
58
|
+
self.corpus = corpus
|
|
59
|
+
self.packs = packs
|
|
60
|
+
self._cache = {}
|
|
61
|
+
|
|
62
|
+
def resolve(self, key):
|
|
63
|
+
if key not in self._cache:
|
|
64
|
+
hits = []
|
|
65
|
+
for path, text in zip(self.corpus.paths, self.corpus.texts):
|
|
66
|
+
try:
|
|
67
|
+
if self.packs.file_matches(key, path, text):
|
|
68
|
+
hits.append(path)
|
|
69
|
+
except Exception:
|
|
70
|
+
continue
|
|
71
|
+
self._cache[key] = hits
|
|
72
|
+
return self._cache[key]
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def address_check(near_cites, found_path, keymap, packs):
|
|
76
|
+
"""Compare the address printed beside a quotation with the file the text was found in."""
|
|
77
|
+
keys = packs.keys(near_cites)
|
|
78
|
+
if not keys:
|
|
79
|
+
return {"status": "NO_NEARBY_CITATION", "keys": []}
|
|
80
|
+
mapped = {k: keymap.resolve(k) for k in keys}
|
|
81
|
+
known = {k: v for k, v in mapped.items() if v}
|
|
82
|
+
if not known:
|
|
83
|
+
return {"status": "ADDRESS_NOT_IN_CORPUS",
|
|
84
|
+
"keys": sorted(packs.label(k) for k in keys)}
|
|
85
|
+
for k, paths in known.items():
|
|
86
|
+
if found_path in paths:
|
|
87
|
+
return {"status": "MATCHED", "matched": packs.label(k),
|
|
88
|
+
"keys": sorted(packs.label(x) for x in keys)}
|
|
89
|
+
better = sorted({p for v in known.values() for p in v})
|
|
90
|
+
return {"status": "MISMATCH",
|
|
91
|
+
"keys": sorted(packs.label(k) for k in known),
|
|
92
|
+
"expected_files": better}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def repair_anchor_miss(quote, addr, corpus, min_len=60):
|
|
96
|
+
"""Is the quotation actually present in one of the files the address points at?
|
|
97
|
+
|
|
98
|
+
Returns the path if so. This is the measured case where a statute's declaration clause was
|
|
99
|
+
compared against an unrelated regulation and flagged for a changed operative word, while the
|
|
100
|
+
file holding the real provision sat on the same disk.
|
|
101
|
+
"""
|
|
102
|
+
n = normalise(quote)
|
|
103
|
+
if len(n) < min_len:
|
|
104
|
+
return None
|
|
105
|
+
for path in (addr.get("expected_files") or [])[:10]:
|
|
106
|
+
try:
|
|
107
|
+
t = corpus.text_of(path)
|
|
108
|
+
except (KeyError, ValueError):
|
|
109
|
+
continue
|
|
110
|
+
if n in t or alnum(n) in alnum(t) or dehyph(n) in dehyph(t):
|
|
111
|
+
return path
|
|
112
|
+
return None
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def fold(quote, verdict, path, detail, near_cites, corpus, keymap, packs):
|
|
116
|
+
"""Fold the address layer into a text verdict. Returns `(verdict, path, detail, address)`.
|
|
117
|
+
|
|
118
|
+
π΄ The address is taken from the NEAR ring only (see ``extract.citation_window``). The wide ring
|
|
119
|
+
stays available to the miss classifier, because a neighbour in the same paragraph tells you
|
|
120
|
+
whether the source ought to be downloaded - but it is not this quotation's address, and treating
|
|
121
|
+
it as one produced accusations against innocent documents in the first build of this layer.
|
|
122
|
+
"""
|
|
123
|
+
if not path:
|
|
124
|
+
# π΄ THE MISS THAT IS NOT A MISS. Until 2026-08-03 the address layer was skipped entirely
|
|
125
|
+
# whenever the text was not located - so a quotation of a source the user simply does not
|
|
126
|
+
# have was graded exactly like one the authority never wrote. `NOT_FOUND`'s own meaning
|
|
127
|
+
# string admitted the ambiguity ("either the source is not downloaded, or invented") and
|
|
128
|
+
# the tool had what it needed to resolve it sitting right there: the citation printed
|
|
129
|
+
# beside the quotation.
|
|
130
|
+
#
|
|
131
|
+
# Measured in the sister project on a real filing: 20 of 37 flagged items were quotations
|
|
132
|
+
# of agency press releases and FAQ pages, whose sources are not in a corpus of law by
|
|
133
|
+
# construction. Two thirds of the list was unactionable, and the genuine misses were
|
|
134
|
+
# hiding in it.
|
|
135
|
+
#
|
|
136
|
+
# π΄ The guard against this becoming an escape hatch is the `ADDRESS_NOT_IN_CORPUS` test,
|
|
137
|
+
# not a softer word. If the cited authority IS on disk and the words are not in it, that is
|
|
138
|
+
# the fabrication shape and the verdict stays `NOT_FOUND` - said louder, not quieter.
|
|
139
|
+
if verdict == "NOT_FOUND" and near_cites:
|
|
140
|
+
a = address_check(near_cites, None, keymap, packs)
|
|
141
|
+
if a["status"] == "ADDRESS_NOT_IN_CORPUS":
|
|
142
|
+
return ("NO_SOURCE_ON_DISK", None,
|
|
143
|
+
"not checked: %s is not in your sources folder. Download it and run again "
|
|
144
|
+
"- this is not a pass" % "; ".join(a["keys"]), a)
|
|
145
|
+
if a["status"] in ("MISMATCH", "MATCHED"):
|
|
146
|
+
names = a.get("keys") or []
|
|
147
|
+
detail = ("the cited source IS on disk (%s) and these words are not in it%s"
|
|
148
|
+
% ("; ".join(names), (" - " + detail) if detail else ""))
|
|
149
|
+
return verdict, path, detail, a
|
|
150
|
+
return verdict, path, detail, None
|
|
151
|
+
if not near_cites:
|
|
152
|
+
return verdict, path, detail, {"status": "NO_NEARBY_CITATION", "keys": []}
|
|
153
|
+
|
|
154
|
+
addr = address_check(near_cites, path, keymap, packs)
|
|
155
|
+
if addr["status"] != "MISMATCH":
|
|
156
|
+
return verdict, path, detail, addr
|
|
157
|
+
|
|
158
|
+
repaired = repair_anchor_miss(quote, addr, corpus)
|
|
159
|
+
if repaired:
|
|
160
|
+
if verdict != "VERIFIED":
|
|
161
|
+
detail = ("correct at the cited address Β«%sΒ»; the global anchor pointed at Β«%sΒ» - the "
|
|
162
|
+
"previous verdict %s was an anchor miss"
|
|
163
|
+
% (os.path.basename(repaired), os.path.basename(path), verdict))
|
|
164
|
+
return ("VERIFIED", repaired, detail,
|
|
165
|
+
{"status": "MATCHED", "matched": "after binding", "keys": addr["keys"]})
|
|
166
|
+
|
|
167
|
+
if verdict in ADDRESS_CLEAN:
|
|
168
|
+
detail = ("found verbatim in Β«%sΒ», but the address printed beside it (%s) points at %s - "
|
|
169
|
+
"and the string is NOT there%s"
|
|
170
|
+
% (os.path.basename(path), "; ".join(addr["keys"]),
|
|
171
|
+
"; ".join(os.path.basename(b) for b in addr["expected_files"][:3]),
|
|
172
|
+
("" if not detail else ". Previously: " + detail)))
|
|
173
|
+
return "FOUND_ELSEWHERE", path, detail, addr
|
|
174
|
+
|
|
175
|
+
detail = (detail + " Β· " if detail else "") + (
|
|
176
|
+
"address mismatch: cited %s, found in Β«%sΒ»"
|
|
177
|
+
% ("; ".join(addr["keys"]), os.path.basename(path)))
|
|
178
|
+
return verdict, path, detail, addr
|
krokai/bank.py
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""The quote bank and the queue: two files that do opposite jobs.
|
|
3
|
+
|
|
4
|
+
THE BANK is a decision. *"This quotation matters to the matter, here is its address, here is where
|
|
5
|
+
the source sits on disk, here is how to re-check it in a minute, and here is what it does NOT
|
|
6
|
+
prove."* A person writes it. Nothing writes to it automatically, ever.
|
|
7
|
+
|
|
8
|
+
THE QUEUE is a list of undone work. A quotation appeared in an answer, it is not in the bank, so
|
|
9
|
+
something must be decided about it. A hook writes it after every turn.
|
|
10
|
+
|
|
11
|
+
π΄ WHY THEY ARE NOT ONE FILE
|
|
12
|
+
-----------------------------
|
|
13
|
+
Because automatic entry would turn the bank into a dump. Measured in the source project: a single
|
|
14
|
+
turn produced 65 legal quotations. Writing all of them into the bank would bury the four that
|
|
15
|
+
mattered under sixty-one that did not, and a bank you cannot read is a bank nobody opens. The queue
|
|
16
|
+
poses the question; the bank stores the answer.
|
|
17
|
+
|
|
18
|
+
π΄ WHY THE BANK NEEDS A "WHAT THIS DOES NOT PROVE" FIELD
|
|
19
|
+
---------------------------------------------------------
|
|
20
|
+
Paid for twice. A decision was quoted in a filed checklist under the footnote number of a
|
|
21
|
+
*different* decision, with the clause that limited it removed - and the case itself had come out
|
|
22
|
+
against a party in the same position as the client. Every character of the quotation was correct.
|
|
23
|
+
The field is where you write down, at the moment of banking, the thing that will be obvious to the
|
|
24
|
+
other side and invisible to you three weeks later.
|
|
25
|
+
|
|
26
|
+
π΄ WHY THERE IS AN "AGAINST US" SECTION
|
|
27
|
+
-----------------------------------------
|
|
28
|
+
A bank holding only the convenient quotations is a way of learning the inconvenient ones from the
|
|
29
|
+
adjudicator instead of from yourself.
|
|
30
|
+
"""
|
|
31
|
+
from __future__ import annotations
|
|
32
|
+
|
|
33
|
+
import io
|
|
34
|
+
import os
|
|
35
|
+
import re
|
|
36
|
+
import time
|
|
37
|
+
|
|
38
|
+
from .normalize import normalise, strip_markdown, latin_share
|
|
39
|
+
from .verdicts import CLEAN, UNCHECKABLE
|
|
40
|
+
|
|
41
|
+
__all__ = ["read_bank", "in_bank", "bank_quotes", "append_queue", "queue_open_items",
|
|
42
|
+
"candidates", "BANK_HEADER"]
|
|
43
|
+
|
|
44
|
+
BANK_HEADER = """# Quote bank
|
|
45
|
+
|
|
46
|
+
Every quotation below has been **opened in the primary source by a person** and copied from it.
|
|
47
|
+
|
|
48
|
+
> ## Rules for this file
|
|
49
|
+
> 1. A quotation enters only **verbatim** and only after someone opened the source. A paraphrase is
|
|
50
|
+
> not a quotation. A row without `On disk` and `How to re-check` is incomplete.
|
|
51
|
+
> 2. The field **What this does NOT prove** is mandatory. It is what catches a dropped proviso and
|
|
52
|
+
> a pincite to the wrong page - the two defects a string check can never see.
|
|
53
|
+
> 3. The section **against us** is not optional. A bank of only helpful quotations is a way to hear
|
|
54
|
+
> the unhelpful ones from the other side first.
|
|
55
|
+
>
|
|
56
|
+
> π΄ Note on this header: it deliberately contains no long English text inside quotation marks.
|
|
57
|
+
> This file is itself checked, and prose in quotes would be extracted as a quotation of law and
|
|
58
|
+
> reported as NOT FOUND - a false alarm produced by the tool's own template. Measured on the first
|
|
59
|
+
> real run.
|
|
60
|
+
> 4. Run `krokai check` before anything is filed, and read every flag rather than binning it.
|
|
61
|
+
|
|
62
|
+
Weight legend: π’ primary text, personally verified Β· π‘ my inference, or a quotation with a
|
|
63
|
+
caveat Β· π΄ not personally verified - open the source before this goes anywhere.
|
|
64
|
+
|
|
65
|
+
---
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
ENTRY_TEMPLATE = """
|
|
69
|
+
### {id} {weight} {claim}
|
|
70
|
+
|
|
71
|
+
> {quote}
|
|
72
|
+
|
|
73
|
+
| | |
|
|
74
|
+
|---|---|
|
|
75
|
+
| **Address** | {address} |
|
|
76
|
+
| **On disk** | `{on_disk}` |
|
|
77
|
+
| **How to re-check** | {recheck} |
|
|
78
|
+
| **Verified** | {who}, {when}{edition} |
|
|
79
|
+
| **Used in** | {used_in} |
|
|
80
|
+
| **Neighbours** | before β {before} Β· after β {after} |
|
|
81
|
+
| **What this does NOT prove** | {not_proved} |
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
QUEUE_HEADER = """# Quote queue - not yet banked
|
|
85
|
+
|
|
86
|
+
Written automatically after each turn. This is a **list of undone work**, not a second bank:
|
|
87
|
+
anything that appeared in an answer and is not in the quote bank lands here.
|
|
88
|
+
|
|
89
|
+
**Closing a line:** open the source β decide whether the matter needs the quotation β if yes, bank
|
|
90
|
+
it with its address, its location on disk and a "what this does NOT prove" note β tick the box.
|
|
91
|
+
If not, tick the box and write one line saying why.
|
|
92
|
+
|
|
93
|
+
π΄ A green mark means the checker found the words verbatim. It does **not** mean the quotation is
|
|
94
|
+
apt: a dropped proviso and a wrong pincite are caught by eyes, not by string comparison.
|
|
95
|
+
|
|
96
|
+
π΄π΄ And it does not mean the quotation is *right*: the corpus is a set of downloads and can be
|
|
97
|
+
silently incomplete. Measured - a scraped copy of one agency chapter was missing two of its six
|
|
98
|
+
bullet points, so a correct quotation of that chapter came back flagged. **A flag can mean the
|
|
99
|
+
CORPUS is wrong, not the quotation.**
|
|
100
|
+
"""
|
|
101
|
+
|
|
102
|
+
# Not a rule of law: our own prose, channel telemetry, exhibit labels, code, paths.
|
|
103
|
+
NOISE = re.compile(
|
|
104
|
+
r"\bmax_tokens\b|\btool_use\b|\bexit \d|\bHTTP \d|Exhibit\s|Screenshot|"
|
|
105
|
+
r"\.py\b|\.md\b|\.json\b|https?://|%TEMP%|\$\{|\bTODO\b|\bFIXME\b", re.I)
|
|
106
|
+
|
|
107
|
+
_QUOTE_RE = re.compile(r'[Β«"β]([^«»"ββ\n]{55,700})[Β»"β]')
|
|
108
|
+
_BLOCKQ_RE = re.compile(r"(?m)^>\s?(.{55,})$")
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def read_bank(path):
|
|
112
|
+
try:
|
|
113
|
+
return io.open(path, encoding="utf-8", errors="replace").read()
|
|
114
|
+
except OSError:
|
|
115
|
+
return ""
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
_BQ_BLOCK_RE = re.compile(r"(?m)^(?:>.*\n?)+")
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def bank_quotes(bank_text):
|
|
122
|
+
"""Every blockquote in the bank as one normalised, lower-cased string per block."""
|
|
123
|
+
out = set()
|
|
124
|
+
for m in _BQ_BLOCK_RE.finditer(bank_text or ""):
|
|
125
|
+
q = normalise(strip_markdown(m.group(0))).lower()
|
|
126
|
+
if q:
|
|
127
|
+
out.add(q)
|
|
128
|
+
return out
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def in_bank(quote, bank_text):
|
|
132
|
+
"""Normalised containment, both sides.
|
|
133
|
+
|
|
134
|
+
π΄ Both sides. A blockquote captured together with its guillemets normalises to straight
|
|
135
|
+
quotes, the bank has none, and the substring stops matching - so a quotation that was banked
|
|
136
|
+
yesterday raises an alarm today. That exact false positive appeared on the first run of the
|
|
137
|
+
guard hook, and it is the one that teaches people to ignore the guard.
|
|
138
|
+
"""
|
|
139
|
+
if not bank_text:
|
|
140
|
+
return False
|
|
141
|
+
n = normalise(strip_markdown(quote)).lower()
|
|
142
|
+
# π΄ 40, not 20. An outside review traced a 25-character stock phrase ("in his discretion
|
|
143
|
+
# grant theβ¦") to a containment hit anywhere in the bank, silently keeping a NEW quotation
|
|
144
|
+
# out of the queue. The extraction pipeline's own floor is 45, so nothing legitimate arrives
|
|
145
|
+
# shorter - and the failure directions are asymmetric: a false "not banked" is one visible
|
|
146
|
+
# queue line, a false "banked" is a quotation nobody ever decides about.
|
|
147
|
+
if len(n) < 40:
|
|
148
|
+
return False
|
|
149
|
+
# π΄ EQUALITY against the bank's own quotations, not containment in the whole file. Two
|
|
150
|
+
# containment defects were traced by execution on the same day this was rewritten:
|
|
151
|
+
# * two different quotations sharing an opening formula collapsed into one under a
|
|
152
|
+
# first-60-characters key, so the second never reached the queue;
|
|
153
|
+
# * worse, a TRUNCATED variant of a banked quotation is a substring of the full one, so
|
|
154
|
+
# containment blessed exactly the cut-off-condition shape this toolkit exists to catch -
|
|
155
|
+
# the full quotation was banked, the truncated copy walked in under its name.
|
|
156
|
+
# So the bank's `> ` blocks are extracted (consecutive lines joined, so a hand-wrapped entry
|
|
157
|
+
# still counts as one quotation) and the candidate must EQUAL one of them. A drafter quoting
|
|
158
|
+
# a legitimate subset gets one visible queue line - the cheap direction.
|
|
159
|
+
return n in bank_quotes(bank_text)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def candidates(text, min_len=55, min_latin_share=0.75):
|
|
163
|
+
"""Long quoted spans in a piece of prose that could be quotations of law.
|
|
164
|
+
|
|
165
|
+
π΄ The obvious test is wrong, and it shipped. The first version required 40 CONSECUTIVE latin
|
|
166
|
+
letters, which never occurs in English because words are separated by spaces; the check
|
|
167
|
+
silently returned "0 quotations" on a file full of them. The right signal is the latin
|
|
168
|
+
**share**, never a run.
|
|
169
|
+
"""
|
|
170
|
+
out, seen = [], []
|
|
171
|
+
for m in list(_BLOCKQ_RE.finditer(text or "")) + list(_QUOTE_RE.finditer(text or "")):
|
|
172
|
+
q = " ".join(m.group(1).split())
|
|
173
|
+
if len(q) < min_len or NOISE.search(q):
|
|
174
|
+
continue
|
|
175
|
+
if latin_share(q) < min_latin_share:
|
|
176
|
+
continue
|
|
177
|
+
# The same span is caught both as a blockquote and as a quoted string. Without dedup the
|
|
178
|
+
# guard showed it twice in a row, which reads as two problems.
|
|
179
|
+
if any(q in s or s in q for s in seen):
|
|
180
|
+
continue
|
|
181
|
+
seen.append(q)
|
|
182
|
+
out.append(q)
|
|
183
|
+
return out
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def append_queue(path, rows, dropped=0, cap=0, stamp=None):
|
|
187
|
+
"""Append one turn's findings. `rows` is `[(quote, verdict, source_name, detail), ...]`.
|
|
188
|
+
|
|
189
|
+
π΄ EVERYTHING fresh goes in, including verdicts that came back clean. "Found verbatim" is not
|
|
190
|
+
"appropriate": the "what this does not prove" analysis exists only in a bank entry, and that is
|
|
191
|
+
what catches an excised condition.
|
|
192
|
+
"""
|
|
193
|
+
header = "" if os.path.exists(path) else QUEUE_HEADER
|
|
194
|
+
stamp = stamp or time.strftime("%Y-%m-%d %H:%M")
|
|
195
|
+
out = ["\n## %s - %d quotation(s) not in the bank\n" % (stamp, len(rows))]
|
|
196
|
+
for quote, verdict, src, detail in rows:
|
|
197
|
+
# `?` for the uncheckable one: it is not green, and marking it π΄π΄ would put "you have
|
|
198
|
+
# not downloaded this yet" above a dropped proviso in the reader's eye.
|
|
199
|
+
mark = ("π’" if verdict in CLEAN else
|
|
200
|
+
"?" if verdict in UNCHECKABLE else
|
|
201
|
+
"π΄" if verdict in ("NOT_FOUND", "ERROR") else "π΄π΄")
|
|
202
|
+
out.append("- [ ] %s **%s** Β· source: `%s`" % (mark, verdict, src or "β"))
|
|
203
|
+
if detail:
|
|
204
|
+
out.append(" detail: %s" % detail[:220])
|
|
205
|
+
out.append(" > %s" % quote[:400])
|
|
206
|
+
out.append("")
|
|
207
|
+
if dropped:
|
|
208
|
+
# π΄ Silent truncation reads as "everything is covered". Say it out loud.
|
|
209
|
+
out.append("- [ ] β οΈ **%d** further quotation(s) from this turn were NOT checked: "
|
|
210
|
+
"per-turn cap %d\n" % (dropped, cap))
|
|
211
|
+
d = os.path.dirname(path)
|
|
212
|
+
if d:
|
|
213
|
+
os.makedirs(d, exist_ok=True)
|
|
214
|
+
with io.open(path, "a", encoding="utf-8", newline="\n") as fh:
|
|
215
|
+
if header:
|
|
216
|
+
fh.write(header)
|
|
217
|
+
fh.write("\n".join(out))
|
|
218
|
+
return len(rows)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def queue_open_items(path):
|
|
222
|
+
"""`(open, done, [first lines of open items])`. The second half of the hook: something has to
|
|
223
|
+
refuse to close the round while the queue is not empty, or the file is read exactly as often as
|
|
224
|
+
an instruction is obeyed - which is to say, by mood."""
|
|
225
|
+
if not os.path.exists(path):
|
|
226
|
+
return 0, 0, []
|
|
227
|
+
t = io.open(path, encoding="utf-8", errors="replace").read()
|
|
228
|
+
open_items = re.findall(r"(?m)^\s*-\s*\[ \]\s*(.{0,110})", t)
|
|
229
|
+
done = len(re.findall(r"(?m)^\s*-\s*\[[xX]\]", t))
|
|
230
|
+
return len(open_items), done, open_items
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def render_entry(**kw):
|
|
234
|
+
"""Render a bank entry. Fields left empty are rendered as an explicit TO DO rather than blank,
|
|
235
|
+
because a blank cell reads as "nothing to say here" and an empty "what this does not prove" is
|
|
236
|
+
the single most common way a bad quotation survives."""
|
|
237
|
+
d = {"id": "Β§?", "weight": "π΄", "claim": "", "quote": "", "address": "",
|
|
238
|
+
"on_disk": "", "recheck": "", "who": "", "when": time.strftime("%Y-%m-%d"),
|
|
239
|
+
"edition": "", "used_in": "", "before": "", "after": "",
|
|
240
|
+
"not_proved": "π΄ TO DO - an entry without this field is not finished"}
|
|
241
|
+
d.update({k: v for k, v in kw.items() if v})
|
|
242
|
+
return ENTRY_TEMPLATE.format(**d)
|