memory-cli 0.1.0__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.
- memory_cli/__init__.py +1 -0
- memory_cli/__main__.py +49 -0
- memory_cli/capture/__init__.py +7 -0
- memory_cli/capture/codex_rollout.py +164 -0
- memory_cli/capture/event_lines.py +66 -0
- memory_cli/capture/extract.py +458 -0
- memory_cli/capture/state.py +183 -0
- memory_cli/commands/__init__.py +21 -0
- memory_cli/commands/admin.py +363 -0
- memory_cli/commands/common.py +609 -0
- memory_cli/commands/curate.py +1189 -0
- memory_cli/commands/diagnostics.py +126 -0
- memory_cli/commands/edit.py +1282 -0
- memory_cli/commands/hooks.py +730 -0
- memory_cli/commands/import_recovery.py +45 -0
- memory_cli/commands/install.py +152 -0
- memory_cli/commands/integrate.py +480 -0
- memory_cli/commands/memory.py +2152 -0
- memory_cli/commands/read.py +1290 -0
- memory_cli/commands/sources.py +766 -0
- memory_cli/commands/split.py +97 -0
- memory_cli/commands/split_plan.py +196 -0
- memory_cli/commands/split_transaction.py +230 -0
- memory_cli/commands/synthesis.py +1122 -0
- memory_cli/core/__init__.py +16 -0
- memory_cli/core/auto_state.py +30 -0
- memory_cli/core/codex_pass.py +109 -0
- memory_cli/core/config.py +87 -0
- memory_cli/core/file_journal.py +163 -0
- memory_cli/core/headless.py +130 -0
- memory_cli/core/jobs.py +130 -0
- memory_cli/core/resources.py +57 -0
- memory_cli/core/runner.py +398 -0
- memory_cli/core/safe_io.py +155 -0
- memory_cli/core/store_git.py +407 -0
- memory_cli/core/yaml_load.py +14 -0
- memory_cli/corroborate/__init__.py +11 -0
- memory_cli/corroborate/cli.py +267 -0
- memory_cli/corroborate/decide.py +893 -0
- memory_cli/corroborate/digest.py +425 -0
- memory_cli/corroborate/fill.py +744 -0
- memory_cli/corroborate/job.py +15 -0
- memory_cli/corroborate/reword.py +446 -0
- memory_cli/corroborate/run.py +1142 -0
- memory_cli/corroborate/state.py +300 -0
- memory_cli/digest/__init__.py +4 -0
- memory_cli/digest/lessons.py +483 -0
- memory_cli/entry/__init__.py +12 -0
- memory_cli/entry/auto.py +660 -0
- memory_cli/entry/capture.py +1403 -0
- memory_cli/entry/corroborate.py +214 -0
- memory_cli/entry/integrate.py +684 -0
- memory_cli/entry/integrate_self_check.py +203 -0
- memory_cli/entry/research.py +9 -0
- memory_cli/entry/settle.py +614 -0
- memory_cli/entry/split_auto.py +460 -0
- memory_cli/entry/synthesize.py +22 -0
- memory_cli/integrate/__init__.py +9 -0
- memory_cli/integrate/answers.py +42 -0
- memory_cli/integrate/briefs/check-brief.md +16 -0
- memory_cli/integrate/briefs/place-brief.md +26 -0
- memory_cli/integrate/log.py +43 -0
- memory_cli/integrate/plan.py +125 -0
- memory_cli/integrate/rows.py +99 -0
- memory_cli/integrate/state.py +158 -0
- memory_cli/integrate/undo.py +143 -0
- memory_cli/mem.py +1180 -0
- memory_cli/memories/__init__.py +16 -0
- memory_cli/memories/fingerprints.py +51 -0
- memory_cli/memories/journal.py +93 -0
- memory_cli/memories/locations.py +282 -0
- memory_cli/memories/matching.py +451 -0
- memory_cli/memories/model.py +205 -0
- memory_cli/memories/parse.py +237 -0
- memory_cli/memories/records.py +266 -0
- memory_cli/memories/rules.py +291 -0
- memory_cli/memories/sightings.py +314 -0
- memory_cli/memories/terms.py +148 -0
- memory_cli/memories/write.py +358 -0
- memory_cli/notes/__init__.py +13 -0
- memory_cli/notes/check.py +806 -0
- memory_cli/notes/due.py +260 -0
- memory_cli/notes/fields.py +217 -0
- memory_cli/notes/index.py +230 -0
- memory_cli/notes/links.py +170 -0
- memory_cli/notes/note.py +222 -0
- memory_cli/notes/search.py +391 -0
- memory_cli/notes/split_candidates.py +72 -0
- memory_cli/research/__init__.py +5 -0
- memory_cli/research/checks.py +1065 -0
- memory_cli/research/pipeline.py +952 -0
- memory_cli/session/__init__.py +5 -0
- memory_cli/session/handoff.py +139 -0
- memory_cli/session/notices.py +111 -0
- memory_cli/settle/__init__.py +5 -0
- memory_cli/settle/state.py +111 -0
- memory_cli/settle/verdicts.py +693 -0
- memory_cli/split/briefs/checker-brief.md +5 -0
- memory_cli/split/briefs/editor-brief.md +20 -0
- memory_cli/syntheses/__init__.py +8 -0
- memory_cli/syntheses/document.py +400 -0
- memory_cli/syntheses/edit.py +581 -0
- memory_cli/syntheses/project.py +384 -0
- memory_cli/syntheses/split_conservation.py +50 -0
- memory_cli/syntheses/units.py +427 -0
- memory_cli/synthesize/__init__.py +9 -0
- memory_cli/synthesize/backfill.py +431 -0
- memory_cli/synthesize/briefs/backfill-brief.md +26 -0
- memory_cli/synthesize/briefs/checker-brief.md +13 -0
- memory_cli/synthesize/briefs/fixer-brief.md +19 -0
- memory_cli/synthesize/briefs/memory-brief.md +30 -0
- memory_cli/synthesize/briefs/settle-brief.md +32 -0
- memory_cli/synthesize/briefs/verdict-brief.md +50 -0
- memory_cli/synthesize/briefs/web-brief.md +33 -0
- memory_cli/synthesize/cli.py +311 -0
- memory_cli/synthesize/pipeline.py +764 -0
- memory_cli/synthesize/references.py +164 -0
- memory_cli/synthesize/run.py +150 -0
- memory_cli/synthesize/topics.py +528 -0
- memory_cli/templates/knowledge.md +23 -0
- memory_cli/templates/literature.md +25 -0
- memory_cli/templates/research.md +23 -0
- memory_cli/templates/synthesis.md +6 -0
- memory_cli-0.1.0.dist-info/METADATA +102 -0
- memory_cli-0.1.0.dist-info/RECORD +128 -0
- memory_cli-0.1.0.dist-info/WHEEL +4 -0
- memory_cli-0.1.0.dist-info/entry_points.txt +9 -0
- memory_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,451 @@
|
|
|
1
|
+
"""Matching memories by shared terms: tokens, containment, the related-record lists, and the pairs that may duplicate or refute each other (similarity, the comparison budget, the words that differ)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import datetime
|
|
6
|
+
import re
|
|
7
|
+
import unicodedata
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import TYPE_CHECKING, NamedTuple, Required, TypedDict, Unpack
|
|
10
|
+
|
|
11
|
+
from memory_cli.memories.model import is_live
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from collections.abc import Callable, Collection, Iterable, Iterator, Mapping, Sequence
|
|
15
|
+
|
|
16
|
+
from memory_cli.memories.model import Memory
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _terms(tokens: Iterable[str]) -> frozenset[str]:
|
|
20
|
+
"""The distinct terms `containment` counts: no all-digit token, no stop word."""
|
|
21
|
+
return frozenset(t for t in tokens if not t.isdigit()) - STOPWORDS
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _containment_of_terms(terms: frozenset[str], other_tokens: Collection[str]) -> float:
|
|
25
|
+
"""`containment` over precomputed terms."""
|
|
26
|
+
if len(terms) < MIN_TERMS:
|
|
27
|
+
return 0.0
|
|
28
|
+
return len(terms.intersection(other_tokens)) / len(terms)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
STOPWORDS = frozenset([
|
|
32
|
+
"a",
|
|
33
|
+
"an",
|
|
34
|
+
"the",
|
|
35
|
+
"and",
|
|
36
|
+
"or",
|
|
37
|
+
"but",
|
|
38
|
+
"nor",
|
|
39
|
+
"of",
|
|
40
|
+
"in",
|
|
41
|
+
"on",
|
|
42
|
+
"at",
|
|
43
|
+
"to",
|
|
44
|
+
"for",
|
|
45
|
+
"from",
|
|
46
|
+
"by",
|
|
47
|
+
"with",
|
|
48
|
+
"about",
|
|
49
|
+
"as",
|
|
50
|
+
"into",
|
|
51
|
+
"over",
|
|
52
|
+
"under",
|
|
53
|
+
"is",
|
|
54
|
+
"are",
|
|
55
|
+
"was",
|
|
56
|
+
"were",
|
|
57
|
+
"be",
|
|
58
|
+
"been",
|
|
59
|
+
"being",
|
|
60
|
+
"am",
|
|
61
|
+
"do",
|
|
62
|
+
"does",
|
|
63
|
+
"did",
|
|
64
|
+
"has",
|
|
65
|
+
"have",
|
|
66
|
+
"had",
|
|
67
|
+
"will",
|
|
68
|
+
"would",
|
|
69
|
+
"can",
|
|
70
|
+
"could",
|
|
71
|
+
"should",
|
|
72
|
+
"may",
|
|
73
|
+
"might",
|
|
74
|
+
"must",
|
|
75
|
+
"i",
|
|
76
|
+
"you",
|
|
77
|
+
"he",
|
|
78
|
+
"she",
|
|
79
|
+
"it",
|
|
80
|
+
"we",
|
|
81
|
+
"they",
|
|
82
|
+
"me",
|
|
83
|
+
"him",
|
|
84
|
+
"her",
|
|
85
|
+
"us",
|
|
86
|
+
"them",
|
|
87
|
+
"my",
|
|
88
|
+
"your",
|
|
89
|
+
"his",
|
|
90
|
+
"its",
|
|
91
|
+
"our",
|
|
92
|
+
"their",
|
|
93
|
+
"this",
|
|
94
|
+
"that",
|
|
95
|
+
"these",
|
|
96
|
+
"those",
|
|
97
|
+
"what",
|
|
98
|
+
"which",
|
|
99
|
+
"who",
|
|
100
|
+
"whom",
|
|
101
|
+
"whose",
|
|
102
|
+
"when",
|
|
103
|
+
"where",
|
|
104
|
+
"why",
|
|
105
|
+
"how",
|
|
106
|
+
"not",
|
|
107
|
+
"no",
|
|
108
|
+
"if",
|
|
109
|
+
"then",
|
|
110
|
+
"than",
|
|
111
|
+
"so",
|
|
112
|
+
"there",
|
|
113
|
+
"here",
|
|
114
|
+
])
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class MatchOptions(TypedDict, total=False):
|
|
118
|
+
"""The keyword options of `match_memories`."""
|
|
119
|
+
|
|
120
|
+
tokenize: Required[Callable[[str], list[str]]]
|
|
121
|
+
limit: int # 3
|
|
122
|
+
include_dead: bool # False
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def match_memories(
|
|
126
|
+
memories: Sequence[Memory],
|
|
127
|
+
query_tokens: Sequence[str],
|
|
128
|
+
today: datetime.date,
|
|
129
|
+
**options: Unpack[MatchOptions],
|
|
130
|
+
) -> list[Memory]:
|
|
131
|
+
"""Memories holding at least half (rounded up) of the query's non-stop-word terms, best first."""
|
|
132
|
+
tokenize, limit = options["tokenize"], options.get("limit", 3)
|
|
133
|
+
include_dead = options.get("include_dead", False)
|
|
134
|
+
terms = set(query_tokens) - STOPWORDS
|
|
135
|
+
if not terms:
|
|
136
|
+
return []
|
|
137
|
+
need = (len(terms) + 1) // 2
|
|
138
|
+
scored = []
|
|
139
|
+
for m in memories:
|
|
140
|
+
if m.error is not None or not (include_dead or is_live(m, today)):
|
|
141
|
+
continue
|
|
142
|
+
in_claim = terms & set(tokenize(m.claim))
|
|
143
|
+
overall = terms & set(tokenize(" ".join([m.claim, m.context or "", m.body])))
|
|
144
|
+
if len(overall) >= need:
|
|
145
|
+
scored.append((m, len(in_claim), len(overall)))
|
|
146
|
+
scored.sort(
|
|
147
|
+
key=lambda t: (
|
|
148
|
+
-t[1],
|
|
149
|
+
-t[2],
|
|
150
|
+
-t[0].observed,
|
|
151
|
+
-(t[0].created or datetime.date.min).toordinal(),
|
|
152
|
+
t[0].handle,
|
|
153
|
+
)
|
|
154
|
+
)
|
|
155
|
+
return [m for m, _, _ in scored[:limit]]
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
STRONG = 0.6 # chosen on evals/signal/set.json by the rule in the stage 6 plan
|
|
159
|
+
POSSIBLE = 0.5 # counted only, never named
|
|
160
|
+
MIN_TERMS = 2
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
_TOKEN = re.compile(r"[a-z0-9]+")
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def tokenize(text: str) -> list[str]:
|
|
167
|
+
"""Lowercase [a-z0-9]+ tokens after NFKD with combining marks removed (García -> garcia)."""
|
|
168
|
+
decomposed = unicodedata.normalize("NFKD", text)
|
|
169
|
+
return _TOKEN.findall("".join(c for c in decomposed if not unicodedata.combining(c)).lower())
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def containment(claim_tokens: Iterable[str], text_tokens: Collection[str]) -> float:
|
|
173
|
+
"""Share of the claim's distinct non-stop-word terms found in the text; 0.0 under MIN_TERMS terms.
|
|
174
|
+
|
|
175
|
+
Measured from the claim's side: a brief has hundreds of words and a claim about ten. A token of only digits
|
|
176
|
+
(a year, a count) is not a term: it matches unrelated briefs."""
|
|
177
|
+
return _containment_of_terms(_terms(claim_tokens), set(text_tokens))
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
class Related(NamedTuple):
|
|
181
|
+
handle: str
|
|
182
|
+
kind: str # "m" memory, "n" note
|
|
183
|
+
score: float
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def related_records(
|
|
187
|
+
memories: Sequence[Memory],
|
|
188
|
+
note_stems: Sequence[str],
|
|
189
|
+
text: str,
|
|
190
|
+
today: datetime.date,
|
|
191
|
+
*,
|
|
192
|
+
tokenize: Callable[[str], list[str]],
|
|
193
|
+
) -> tuple[list[Related], list[Related]]:
|
|
194
|
+
"""Records whose claim (a note: its file stem) is largely contained in the text: (strong, possible).
|
|
195
|
+
|
|
196
|
+
A record whose handle occurs in the text as a whole token, with or without "m:", is left out: the text already
|
|
197
|
+
names it."""
|
|
198
|
+
text_tokens = set(tokenize(text))
|
|
199
|
+
found: list[Related] = []
|
|
200
|
+
candidates = [(m.handle, "m", m.claim) for m in memories if is_live(m, today)]
|
|
201
|
+
candidates += [(stem, "n", stem.replace("-", " ")) for stem in note_stems]
|
|
202
|
+
for handle, kind, claim in candidates:
|
|
203
|
+
if re.search(rf"(?<![\w-]){re.escape(handle)}(?![\w-])", text):
|
|
204
|
+
continue
|
|
205
|
+
score = containment(tokenize(claim), text_tokens)
|
|
206
|
+
if score >= POSSIBLE:
|
|
207
|
+
found.append(Related(handle, kind, score))
|
|
208
|
+
found.sort(key=lambda r: (-r.score, r.kind != "m", r.handle))
|
|
209
|
+
return ([r for r in found if r.score >= STRONG], [r for r in found if r.score < STRONG])
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def similarity(a: Iterable[str], b: Iterable[str]) -> float:
|
|
213
|
+
sa, sb = set(a), set(b)
|
|
214
|
+
if not sa or not sb:
|
|
215
|
+
return 0.0
|
|
216
|
+
return len(sa & sb) / len(sa | sb)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
@dataclass
|
|
220
|
+
class Budget:
|
|
221
|
+
"""Claim comparisons a caller lets pair searches spend, shared by passing one object to several searches.
|
|
222
|
+
|
|
223
|
+
`left` counts down by one per comparison. `exhausted` turns True when a search needed a comparison and `left`
|
|
224
|
+
was 0: `left == 0` alone does not say it, because a budget spent to the last comparison compared everything."""
|
|
225
|
+
|
|
226
|
+
left: int
|
|
227
|
+
exhausted: bool = False
|
|
228
|
+
|
|
229
|
+
def spend(self) -> bool:
|
|
230
|
+
if self.left <= 0:
|
|
231
|
+
self.exhausted = True
|
|
232
|
+
return False
|
|
233
|
+
self.left -= 1
|
|
234
|
+
return True
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _among_order(
|
|
238
|
+
live: Sequence[Memory], index: Mapping[str, int], among: Sequence[str]
|
|
239
|
+
) -> Iterator[tuple[int, int]]:
|
|
240
|
+
"""Index pairs with at least one `among` memory, each pair once, in the order of `among`."""
|
|
241
|
+
seen: set[str] = set()
|
|
242
|
+
for h in among:
|
|
243
|
+
i = index.get(h)
|
|
244
|
+
if i is None or h in seen:
|
|
245
|
+
continue
|
|
246
|
+
seen.add(h)
|
|
247
|
+
for j in range(len(live)):
|
|
248
|
+
if j != i and live[j].handle not in seen:
|
|
249
|
+
yield min(i, j), max(i, j)
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
@dataclass(frozen=True)
|
|
253
|
+
class PairSearch:
|
|
254
|
+
"""How `pairs` searches: `among` (handles, in the order to search) limits it to pairs with at least one of them,
|
|
255
|
+
each pair once; `budget` spends 1 per comparison and stops the search when spent (the caller reads
|
|
256
|
+
`budget.exhausted`); `floor` is the lowest containment kept, STRONG unless a caller whose pairs a model judges
|
|
257
|
+
lowers it."""
|
|
258
|
+
|
|
259
|
+
among: Sequence[str] | None = None
|
|
260
|
+
budget: Budget | None = None
|
|
261
|
+
floor: float = STRONG
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def pairs(
|
|
265
|
+
memories: Sequence[Memory],
|
|
266
|
+
today: datetime.date,
|
|
267
|
+
*,
|
|
268
|
+
tokenize: Callable[[str], list[str]],
|
|
269
|
+
among: Sequence[str] | None = None,
|
|
270
|
+
budget: Budget | None = None,
|
|
271
|
+
) -> list[tuple[Memory, Memory, float]]:
|
|
272
|
+
"""Pairs of live memories whose claims contain each other with at least STRONG, in either direction.
|
|
273
|
+
|
|
274
|
+
A claim and its negation score as high as a near-copy: a pair means "same or opposite", never "duplicate".
|
|
275
|
+
`among` and `budget` as in `PairSearch`."""
|
|
276
|
+
return pairs_by(memories, today, tokenize, PairSearch(among=among, budget=budget))
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def pairs_by(
|
|
280
|
+
memories: Sequence[Memory],
|
|
281
|
+
today: datetime.date,
|
|
282
|
+
tokenize: Callable[[str], list[str]],
|
|
283
|
+
how: PairSearch,
|
|
284
|
+
) -> list[tuple[Memory, Memory, float]]:
|
|
285
|
+
"""`pairs` with every choice of `PairSearch`, the floor included."""
|
|
286
|
+
live = sorted((m for m in memories if is_live(m, today)), key=lambda m: m.handle)
|
|
287
|
+
index = {m.handle: i for i, m in enumerate(live)}
|
|
288
|
+
tokens = [set(tokenize(m.claim)) for m in live]
|
|
289
|
+
terms = [_terms(t) for t in tokens]
|
|
290
|
+
if how.among is None:
|
|
291
|
+
order = ((i, j) for i in range(len(live)) for j in range(i + 1, len(live)))
|
|
292
|
+
else:
|
|
293
|
+
order = _among_order(live, index, how.among)
|
|
294
|
+
found = []
|
|
295
|
+
for i, j in order:
|
|
296
|
+
a, b = live[i], live[j]
|
|
297
|
+
if b.handle in a.distinct_from or a.handle in b.distinct_from:
|
|
298
|
+
continue
|
|
299
|
+
if how.budget is not None and not how.budget.spend():
|
|
300
|
+
break
|
|
301
|
+
score = max(
|
|
302
|
+
_containment_of_terms(terms[i], tokens[j]), _containment_of_terms(terms[j], tokens[i])
|
|
303
|
+
)
|
|
304
|
+
if score >= how.floor:
|
|
305
|
+
found.append((a, b, score))
|
|
306
|
+
found.sort(key=lambda t: (-t[2], t[0].handle, t[1].handle))
|
|
307
|
+
return found
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _claim_terms(
|
|
311
|
+
claim: str, tokenize: Callable[[str], list[str]]
|
|
312
|
+
) -> tuple[set[str], frozenset[str]]:
|
|
313
|
+
tokens = set(tokenize(claim))
|
|
314
|
+
return tokens, _terms(tokens)
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _may_refute(live: Memory, dead: Memory) -> bool:
|
|
318
|
+
"""Whether `live` could refute-contradict `dead`: not recorded as distinct, and written after the refutation."""
|
|
319
|
+
if dead.handle in live.distinct_from or live.handle in dead.distinct_from:
|
|
320
|
+
return False
|
|
321
|
+
since = dead.refuted or dead.created
|
|
322
|
+
return live.created is not None and (since is None or live.created > since)
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _refuted_scores(
|
|
326
|
+
live: Memory,
|
|
327
|
+
dead: Sequence[Memory],
|
|
328
|
+
tokenize: Callable[[str], list[str]],
|
|
329
|
+
dead_seen: dict[str, tuple[set[str], frozenset[str]]],
|
|
330
|
+
budget: Budget | None,
|
|
331
|
+
) -> tuple[list[tuple[Memory, Memory, float]], bool]:
|
|
332
|
+
"""The pairs of `live` with a refuted memory that reach STRONG, and whether the budget ran out."""
|
|
333
|
+
found = []
|
|
334
|
+
mine: tuple[set[str], frozenset[str]] | None = None
|
|
335
|
+
for r in dead:
|
|
336
|
+
if not _may_refute(live, r):
|
|
337
|
+
continue
|
|
338
|
+
if budget is not None and not budget.spend():
|
|
339
|
+
return found, True
|
|
340
|
+
mine = mine or _claim_terms(live.claim, tokenize)
|
|
341
|
+
if r.handle not in dead_seen:
|
|
342
|
+
dead_seen[r.handle] = _claim_terms(r.claim, tokenize)
|
|
343
|
+
(ta, terms_a), (tr, terms_r) = mine, dead_seen[r.handle]
|
|
344
|
+
score = max(_containment_of_terms(terms_a, tr), _containment_of_terms(terms_r, ta))
|
|
345
|
+
if score >= STRONG:
|
|
346
|
+
found.append((live, r, score))
|
|
347
|
+
return found, False
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def refuted_pairs(
|
|
351
|
+
memories: Sequence[Memory],
|
|
352
|
+
today: datetime.date,
|
|
353
|
+
*,
|
|
354
|
+
tokenize: Callable[[str], list[str]],
|
|
355
|
+
among: Sequence[str] | None = None,
|
|
356
|
+
budget: Budget | None = None,
|
|
357
|
+
) -> list[tuple[Memory, Memory, float]]:
|
|
358
|
+
"""(live, refuted, score): a live memory whose claim and a refuted one's contain each other with at least STRONG,
|
|
359
|
+
unless the two are recorded as distinct or the live one is not strictly newer than the refutation
|
|
360
|
+
(its `refuted` date, else the refuted memory's `created`).
|
|
361
|
+
|
|
362
|
+
`among` and `budget` work as in `pairs`; `among` restricts the live memories, in its order."""
|
|
363
|
+
live = sorted((m for m in memories if is_live(m, today)), key=lambda m: m.handle)
|
|
364
|
+
if among is not None:
|
|
365
|
+
by_handle = {m.handle: m for m in live}
|
|
366
|
+
live = [by_handle[h] for h in dict.fromkeys(among) if h in by_handle]
|
|
367
|
+
dead = sorted(
|
|
368
|
+
(m for m in memories if m.error is None and m.status == "refuted"), key=lambda m: m.handle
|
|
369
|
+
)
|
|
370
|
+
dead_seen: dict[str, tuple[set[str], frozenset[str]]] = {} # tokenized when first compared
|
|
371
|
+
found: list[tuple[Memory, Memory, float]] = []
|
|
372
|
+
for a in live:
|
|
373
|
+
scored, spent = _refuted_scores(a, dead, tokenize, dead_seen, budget)
|
|
374
|
+
found.extend(scored)
|
|
375
|
+
if spent:
|
|
376
|
+
break
|
|
377
|
+
found.sort(key=lambda t: (-t[2], t[0].handle, t[1].handle))
|
|
378
|
+
return found
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
_WORD = re.compile(r"[a-z0-9]+(?:[.'\u2019][a-z0-9]+)*")
|
|
382
|
+
_NEGATIONS = frozenset({"not", "no", "never", "cannot", "without"})
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def _claim_words(claim: str) -> set[str]:
|
|
386
|
+
return set(_WORD.findall(claim.casefold()))
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def differing_words(a: str, b: str) -> list[str]:
|
|
390
|
+
"""The words that occur in only one of the two claims, sorted; stop words are left out except negations,
|
|
391
|
+
digits stay. Empty when nothing is left."""
|
|
392
|
+
return sorted(
|
|
393
|
+
w for w in _claim_words(a) ^ _claim_words(b) if w in _NEGATIONS or w not in STOPWORDS
|
|
394
|
+
)
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
# Pairs of words that make two claims opposites; either member of a pair may be the one in each claim.
|
|
398
|
+
OPPOSITES = [
|
|
399
|
+
"works/fails",
|
|
400
|
+
"work/fail",
|
|
401
|
+
"passes/fails",
|
|
402
|
+
"pass/fail",
|
|
403
|
+
"enable/disable",
|
|
404
|
+
"enabled/disabled",
|
|
405
|
+
"allow/deny",
|
|
406
|
+
"allowed/denied",
|
|
407
|
+
"before/after",
|
|
408
|
+
"always/never",
|
|
409
|
+
"on/off",
|
|
410
|
+
"safe/unsafe",
|
|
411
|
+
"increase/decrease",
|
|
412
|
+
"with/without",
|
|
413
|
+
"can/cannot",
|
|
414
|
+
"must/may",
|
|
415
|
+
"add/remove",
|
|
416
|
+
"start/stop",
|
|
417
|
+
"true/false",
|
|
418
|
+
"required/optional",
|
|
419
|
+
"sync/async",
|
|
420
|
+
"up/down",
|
|
421
|
+
]
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def _partners() -> dict[str, set[str]]:
|
|
425
|
+
found: dict[str, set[str]] = {}
|
|
426
|
+
for pair in OPPOSITES:
|
|
427
|
+
x, y = pair.split("/")
|
|
428
|
+
found.setdefault(x, set()).add(y)
|
|
429
|
+
found.setdefault(y, set()).add(x)
|
|
430
|
+
return found
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
_PARTNERS = _partners()
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def flagged_words(a: str, b: str) -> list[str]:
|
|
437
|
+
"""The words that differ between two claims and may mean opposites or different versions: any token with a
|
|
438
|
+
digit, a negation, and a word of OPPOSITES whose partner is among the other claim's differing words."""
|
|
439
|
+
wa, wb = _claim_words(a), _claim_words(b)
|
|
440
|
+
only_a, only_b = wa - wb, wb - wa
|
|
441
|
+
flagged = set()
|
|
442
|
+
for mine, other in ((only_a, only_b), (only_b, only_a)):
|
|
443
|
+
for w in mine:
|
|
444
|
+
if (
|
|
445
|
+
w in _NEGATIONS
|
|
446
|
+
or w.endswith(("n't", "n\u2019t"))
|
|
447
|
+
or any(c.isdigit() for c in w)
|
|
448
|
+
or _PARTNERS.get(w, set()) & other
|
|
449
|
+
):
|
|
450
|
+
flagged.add(w)
|
|
451
|
+
return sorted(flagged)
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"""The memory record as data: its fields, the vocabularies of its fields, and the checks on one-line text, including the code check that a short form is not stronger than its claim (`short_problems`).
|
|
2
|
+
|
|
3
|
+
Pure: imports nothing from the engine."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import re
|
|
8
|
+
import unicodedata
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from typing import TYPE_CHECKING
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
import datetime
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
KINDS = ("decision", "constraint", "pitfall", "lesson", "finding", "document", "state")
|
|
17
|
+
ORIGINS = ("web", "pipeline", "transcript")
|
|
18
|
+
REACHES = ("project", "general")
|
|
19
|
+
WEIGHTS = ("light", "medium", "strong")
|
|
20
|
+
# Distinct sessions that establish a transcript memory, by weight; a memory with no weight counts as medium.
|
|
21
|
+
SIGHTINGS_NEEDED = {"light": 1, "medium": 2, "strong": 3}
|
|
22
|
+
UNCONFIRMED_DAYS = 30
|
|
23
|
+
SESSION_PREFIX = "session "
|
|
24
|
+
OUTCOMES = ("worked", "failed", "seen")
|
|
25
|
+
TRIAGES = ("pending",)
|
|
26
|
+
PROJECT_KEY_LEN = 12
|
|
27
|
+
SHORT_DATE_LEN = 10 # characters of an ISO date
|
|
28
|
+
GLOBAL_MIN_PROJECTS = 2 # distinct projects that establish a global memory
|
|
29
|
+
SHORT_LIMIT = 120 # characters of the one-line form a lesson loads as at session start
|
|
30
|
+
TOPIC_LIMIT = 24
|
|
31
|
+
_TOPIC = re.compile(r"[a-z0-9][a-z0-9-]*( [a-z0-9][a-z0-9-]*)?")
|
|
32
|
+
STATUSES = ("active", "refuted", "superseded", "forgotten")
|
|
33
|
+
PROJECT_DIR = ".memory"
|
|
34
|
+
GLOBAL_DIR = "memories"
|
|
35
|
+
STORE_MARKER = "mem-store.yaml"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass
|
|
39
|
+
class Memory:
|
|
40
|
+
scope: str
|
|
41
|
+
path: Path
|
|
42
|
+
handle: str
|
|
43
|
+
kind: str
|
|
44
|
+
claim: str
|
|
45
|
+
created: datetime.date | None
|
|
46
|
+
observed: int
|
|
47
|
+
status: str
|
|
48
|
+
context: str | None
|
|
49
|
+
valid_until: datetime.date | None
|
|
50
|
+
sources: list[str]
|
|
51
|
+
body: str
|
|
52
|
+
error: str | None
|
|
53
|
+
last_observed: datetime.date | None = None
|
|
54
|
+
distinct_from: list[str] = field(default_factory=list)
|
|
55
|
+
promote: str | None = None
|
|
56
|
+
refuted: datetime.date | None = None
|
|
57
|
+
superseded_by: str | None = None
|
|
58
|
+
origin: str | None = None # "web", "pipeline" or "transcript"; None: written in a session
|
|
59
|
+
reach: str | None = None # "project" or "general": how far the lesson reaches
|
|
60
|
+
weight: str | None = None # "light", "medium" or "strong": how much it weighs
|
|
61
|
+
owner_confirmed: datetime.date | None = (
|
|
62
|
+
None # the owner vouched for the lesson: it is established
|
|
63
|
+
)
|
|
64
|
+
triage: str | None = None # "pending": a global record that left quarantine and awaits triage
|
|
65
|
+
triage_reason: str | None = (
|
|
66
|
+
None # why a lesson is held at triage; meaningful only while triage is "pending"
|
|
67
|
+
)
|
|
68
|
+
released: datetime.date | None = None # the day a global record left quarantine
|
|
69
|
+
general: str | None = None # handle of the global record a project record was generalized into
|
|
70
|
+
short: str | None = (
|
|
71
|
+
None # the claim in one line of at most SHORT_LIMIT characters, as it loads at session start
|
|
72
|
+
)
|
|
73
|
+
short_by: str | None = (
|
|
74
|
+
None # "model": the short form was written by a model and the owner has not read it
|
|
75
|
+
)
|
|
76
|
+
topic: str | None = None # one or two lowercase words that group rules
|
|
77
|
+
from_repository: bool = False # a repository commits the file: its owner_confirmed is not the reader's (mark_repository)
|
|
78
|
+
load: str | None = (
|
|
79
|
+
None # "no": the owner turned this lesson's rule off; "index": only counted by topic
|
|
80
|
+
)
|
|
81
|
+
log: list[str] = field(
|
|
82
|
+
default_factory=list
|
|
83
|
+
) # valid case entries "<date> session <id> <outcome>", in file order
|
|
84
|
+
versions: list[str] = field(
|
|
85
|
+
default_factory=list
|
|
86
|
+
) # valid entries "<date> <short form>", sorted by date
|
|
87
|
+
reviewed: datetime.date | None = None # the day the owner looked at a lesson that got worse
|
|
88
|
+
reworded: datetime.date | None = (
|
|
89
|
+
None # the day the automatic step reworded the short form (once, for good)
|
|
90
|
+
)
|
|
91
|
+
reword_failed: datetime.date | None = (
|
|
92
|
+
None # the date of the version the automatic step gave up on
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class FieldTypeError(ValueError):
|
|
97
|
+
"""A frontmatter value of the wrong type; a ValueError so every caller that catches one still catches it."""
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def valid_short(text) -> bool:
|
|
101
|
+
return (
|
|
102
|
+
isinstance(text, str)
|
|
103
|
+
and bool(text.strip())
|
|
104
|
+
and text == text.strip()
|
|
105
|
+
and len(text) <= SHORT_LIMIT
|
|
106
|
+
and len(text.splitlines()) == 1
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
TRIAGE_REASON_LIMIT = 200
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def valid_triage_reason(text) -> bool:
|
|
114
|
+
return (
|
|
115
|
+
isinstance(text, str)
|
|
116
|
+
and bool(text.strip())
|
|
117
|
+
and text == text.strip()
|
|
118
|
+
and len(text) <= TRIAGE_REASON_LIMIT
|
|
119
|
+
and len(text.splitlines()) == 1
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def valid_topic(text) -> bool:
|
|
124
|
+
return (
|
|
125
|
+
isinstance(text, str)
|
|
126
|
+
and len(text) <= TOPIC_LIMIT
|
|
127
|
+
and text != "other"
|
|
128
|
+
and _TOPIC.fullmatch(text) is not None
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def slug_of(claim: str) -> str:
|
|
133
|
+
ascii_text = unicodedata.normalize("NFKD", claim).encode("ascii", "ignore").decode()
|
|
134
|
+
words = re.findall(r"[a-z0-9]+", ascii_text.lower())[:8]
|
|
135
|
+
slug = "-".join(words)[:60].strip("-")
|
|
136
|
+
return slug or "memory"
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def is_live(memory: Memory, today: datetime.date) -> bool:
|
|
140
|
+
return (
|
|
141
|
+
memory.error is None
|
|
142
|
+
and memory.status == "active"
|
|
143
|
+
and (memory.valid_until is None or memory.valid_until >= today)
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
HEDGES = frozenset([
|
|
148
|
+
"may",
|
|
149
|
+
"might",
|
|
150
|
+
"can",
|
|
151
|
+
"could",
|
|
152
|
+
"sometimes",
|
|
153
|
+
"often",
|
|
154
|
+
"usually",
|
|
155
|
+
"once",
|
|
156
|
+
"untested",
|
|
157
|
+
"provisional",
|
|
158
|
+
"seems",
|
|
159
|
+
"seemed",
|
|
160
|
+
"likely",
|
|
161
|
+
"probably",
|
|
162
|
+
"consider",
|
|
163
|
+
"perhaps",
|
|
164
|
+
])
|
|
165
|
+
ABSOLUTES = frozenset([
|
|
166
|
+
"always",
|
|
167
|
+
"never",
|
|
168
|
+
"must",
|
|
169
|
+
"every",
|
|
170
|
+
"all",
|
|
171
|
+
"only",
|
|
172
|
+
"none",
|
|
173
|
+
"cannot",
|
|
174
|
+
"can't",
|
|
175
|
+
"guarantees",
|
|
176
|
+
"ensures",
|
|
177
|
+
"proves",
|
|
178
|
+
])
|
|
179
|
+
|
|
180
|
+
_WORD = re.compile(r"[a-z']+")
|
|
181
|
+
_LINK = re.compile(r"https?://|www\.", re.IGNORECASE)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _words(text: str) -> list[str]:
|
|
185
|
+
# a typographic apostrophe is the plain one; quoting apostrophes are stripped, an inner one (can't) stays
|
|
186
|
+
found = _WORD.findall(text.lower().replace("\u2019", "'").replace("\u2018", "'"))
|
|
187
|
+
return [w for w in (m.strip("'") for m in found) if w]
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def short_problems(claim: str, short: str) -> list[str]:
|
|
191
|
+
"""English reasons the short form is stronger than its claim; [] when it passes."""
|
|
192
|
+
claim_words, short_words = _words(claim), _words(short)
|
|
193
|
+
out = []
|
|
194
|
+
if HEDGES.intersection(claim_words) and not HEDGES.intersection(short_words):
|
|
195
|
+
out.append("the claim is hedged and the short form is not")
|
|
196
|
+
seen = set()
|
|
197
|
+
for w in short_words:
|
|
198
|
+
if w in ABSOLUTES and w not in claim_words and w not in seen:
|
|
199
|
+
seen.add(w)
|
|
200
|
+
out.append(f'the short form says "{w}" and the claim does not')
|
|
201
|
+
if _LINK.search(short):
|
|
202
|
+
out.append("the short form holds a link")
|
|
203
|
+
if any(w in {"owner", "owner's", "owners"} for w in short_words):
|
|
204
|
+
out.append('the short form says "owner": say "the user"')
|
|
205
|
+
return out
|