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,893 @@
|
|
|
1
|
+
"""`corroborate`: what the background corroboration pass reads and what it does with the groups a model returns.
|
|
2
|
+
|
|
3
|
+
Pure: no model call, no file write, no subprocess. The command builds on it; this module only decides."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import datetime
|
|
8
|
+
import hashlib
|
|
9
|
+
import json
|
|
10
|
+
import re
|
|
11
|
+
from collections.abc import Mapping
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import TYPE_CHECKING
|
|
15
|
+
|
|
16
|
+
from memory_cli.capture import extract as capture_extract
|
|
17
|
+
from memory_cli.memories import model, records, rules
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
from collections.abc import Collection, Sequence
|
|
21
|
+
|
|
22
|
+
MAX_LESSONS = 150
|
|
23
|
+
MAX_GROUPS = 30
|
|
24
|
+
FILL_CAP = 30 # lessons one `fill` session is asked about
|
|
25
|
+
# automatic fills that may fail to give a lesson a short form before it is left alone
|
|
26
|
+
FILL_ATTEMPTS = 2
|
|
27
|
+
FILL_FAILURES = 3
|
|
28
|
+
REWORD_CAP = 5 # lessons one automatic rewording session is asked about
|
|
29
|
+
REWORD_ATTEMPTS = 2 # refused proposals for one version before the step gives up on it
|
|
30
|
+
LAPSED_DAYS = 60 # an unconfirmed lesson stays readable this long after its valid_until
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def counted_projects(registry: Mapping[str, Mapping[str, str]]) -> list[Path]:
|
|
34
|
+
"""Registered paths that exist, hold a memory folder and are not under a temporary folder; sorted."""
|
|
35
|
+
found = set()
|
|
36
|
+
for entry in registry.values():
|
|
37
|
+
raw = entry.get("path") if isinstance(entry, Mapping) else None
|
|
38
|
+
if not isinstance(raw, str) or not raw:
|
|
39
|
+
continue
|
|
40
|
+
path = Path(raw)
|
|
41
|
+
if path.is_dir() and records.project_dir(path).is_dir() and not records.under_temp(path):
|
|
42
|
+
found.add(path)
|
|
43
|
+
return sorted(found)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def project_memories(project: Path) -> list[records.Memory]:
|
|
47
|
+
"""The project's memories that its repository does not commit: corroboration never lifts a tracked memory into
|
|
48
|
+
a global one, adds a sighting from it or writes into its file."""
|
|
49
|
+
tracked = records.tracked_memories(project)
|
|
50
|
+
if tracked is None:
|
|
51
|
+
return []
|
|
52
|
+
return [
|
|
53
|
+
m
|
|
54
|
+
for m in records.load_memories(records.project_dir(project), "project")
|
|
55
|
+
if m.handle not in tracked
|
|
56
|
+
]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass(frozen=True)
|
|
60
|
+
class Lesson:
|
|
61
|
+
id: str # "g:<handle>" or "p<n>:<handle>": no project name reaches the model
|
|
62
|
+
scope: str # "project" or "global"
|
|
63
|
+
project: Path | None
|
|
64
|
+
memory: records.Memory
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _readable(m: records.Memory, today: datetime.date) -> bool:
|
|
68
|
+
if m.error is not None or m.status != "active" or m.origin != "transcript":
|
|
69
|
+
return False
|
|
70
|
+
if records.is_live(m, today):
|
|
71
|
+
return True
|
|
72
|
+
return (
|
|
73
|
+
m.valid_until is not None
|
|
74
|
+
and records.standing(m) == "unconfirmed"
|
|
75
|
+
and 0 < (today - m.valid_until).days <= LAPSED_DAYS
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _newest_first(lessons: list[Lesson]) -> list[Lesson]:
|
|
80
|
+
lessons.sort(key=lambda x: x.memory.handle)
|
|
81
|
+
lessons.sort(key=lambda x: x.memory.created or datetime.date.min, reverse=True)
|
|
82
|
+
return lessons
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def collect(
|
|
86
|
+
projects: Sequence[Path], global_folder: Path | None, today: datetime.date
|
|
87
|
+
) -> list[Lesson]:
|
|
88
|
+
"""Active transcript lessons, live or unconfirmed and lapsed for at most LAPSED_DAYS; a project record with
|
|
89
|
+
`promote: no` or already linked to a global record is left out. Newest first, cut at MAX_LESSONS."""
|
|
90
|
+
out: list[Lesson] = []
|
|
91
|
+
for n, project in enumerate(projects, start=1):
|
|
92
|
+
out.extend(
|
|
93
|
+
Lesson(f"p{n}:{m.handle}", "project", project, m)
|
|
94
|
+
for m in project_memories(project)
|
|
95
|
+
if _readable(m, today) and m.promote != "no" and not m.general
|
|
96
|
+
)
|
|
97
|
+
out.extend(
|
|
98
|
+
Lesson(f"g:{m.handle}", "global", None, m)
|
|
99
|
+
for m in records.load_memories(global_folder, "global")
|
|
100
|
+
if _readable(m, today)
|
|
101
|
+
)
|
|
102
|
+
return _newest_first(out)[:MAX_LESSONS]
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _reach(lesson: Lesson) -> str:
|
|
106
|
+
return "general" if lesson.scope == "global" else (lesson.memory.reach or "project")
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _encoded(lesson: Lesson) -> str:
|
|
110
|
+
"""JSON of what the model is shown plus the sources, so two different lessons never give the same text."""
|
|
111
|
+
m = lesson.memory
|
|
112
|
+
return json.dumps(
|
|
113
|
+
[lesson.id, _reach(lesson), m.claim, m.context, sorted(m.sources)], ensure_ascii=False
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def lesson_fingerprint(lesson: Lesson) -> str:
|
|
118
|
+
return hashlib.sha1(_encoded(lesson).encode("utf-8", "replace")).hexdigest()
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def fingerprint(lessons: Sequence[Lesson]) -> str:
|
|
122
|
+
"""Changes when a lesson appears, goes, gains a source or changes what the model is shown (reach, claim,
|
|
123
|
+
context); not with the order of the lessons."""
|
|
124
|
+
text = json.dumps(sorted(_encoded(x) for x in lessons), ensure_ascii=False)
|
|
125
|
+
return hashlib.sha1(text.encode("utf-8", "replace")).hexdigest()
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _line(text: str | None) -> str:
|
|
129
|
+
return " ".join((text or "").split())
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def lesson_lines(lessons: Sequence[Lesson]) -> list[str]:
|
|
133
|
+
r"""`<id>\\t<reach, or "general" for a global record>\\t<claim>\\t<context>`, one line each."""
|
|
134
|
+
return [
|
|
135
|
+
f"{x.id}\t{_reach(x)}\t{_line(x.memory.claim)}\t{_line(x.memory.context)}" for x in lessons
|
|
136
|
+
]
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
@dataclass(frozen=True)
|
|
140
|
+
class Group:
|
|
141
|
+
ids: list[str]
|
|
142
|
+
claim: str
|
|
143
|
+
context: str
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _group_shape(item: object) -> tuple[list[str], str, str] | None:
|
|
147
|
+
"""(ids, claim, context) of an item of the shape {"ids": [str], "claim": str, "context": str (optional)}."""
|
|
148
|
+
if not isinstance(item, dict):
|
|
149
|
+
return None
|
|
150
|
+
ids, claim, context = item.get("ids"), item.get("claim"), item.get("context", "")
|
|
151
|
+
if not isinstance(ids, list) or not ids or not all(isinstance(x, str) for x in ids):
|
|
152
|
+
return None
|
|
153
|
+
if not isinstance(claim, str) or not (context is None or isinstance(context, str)):
|
|
154
|
+
return None
|
|
155
|
+
return ids, claim, context or ""
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _id_problem(ids: list[str], by_id: Mapping[str, Lesson], used: set[str]) -> str | None:
|
|
159
|
+
unknown = [x for x in ids if x not in by_id]
|
|
160
|
+
if unknown:
|
|
161
|
+
return f"unknown id {unknown[0]}"
|
|
162
|
+
if len(set(ids)) != len(ids):
|
|
163
|
+
return "names an id more than once"
|
|
164
|
+
if any(x in used for x in ids):
|
|
165
|
+
return "shares an id with an earlier group"
|
|
166
|
+
return None
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _content_problem(
|
|
170
|
+
ids: list[str], claim: str, by_id: Mapping[str, Lesson], kept: int
|
|
171
|
+
) -> str | None:
|
|
172
|
+
if not _line(claim):
|
|
173
|
+
return "empty claim"
|
|
174
|
+
if len(ids) == 1 and (by_id[ids[0]].scope == "global" or _reach(by_id[ids[0]]) != "general"):
|
|
175
|
+
return "one member that is global or of reach project"
|
|
176
|
+
if kept >= MAX_GROUPS:
|
|
177
|
+
return f"more than {MAX_GROUPS} groups"
|
|
178
|
+
return None
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _judge_group(
|
|
182
|
+
item: object, by_id: Mapping[str, Lesson], used: set[str], kept: int
|
|
183
|
+
) -> Group | str:
|
|
184
|
+
"""The group an item makes, or the reason it is dropped."""
|
|
185
|
+
shape = _group_shape(item)
|
|
186
|
+
if shape is None:
|
|
187
|
+
return "not an object with ids, claim and context"
|
|
188
|
+
ids, claim, context = shape
|
|
189
|
+
why = _id_problem(ids, by_id, used) or _content_problem(ids, claim, by_id, kept)
|
|
190
|
+
return why or Group(ids, _line(claim), _line(context))
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def validate_groups(raw: object, lessons: Sequence[Lesson]) -> tuple[list[Group], list[str]]:
|
|
194
|
+
"""`raw` is the model's whole answer, {"groups": [...]}; anything else keeps nothing and gives one reason.
|
|
195
|
+
The groups that hold and, for each one dropped, a reason. Dropped: not an object of the shape
|
|
196
|
+
{"ids": [str], "claim": str, "context": str (optional)}, an unknown id, an id repeated inside the group, an id
|
|
197
|
+
of an earlier group, an empty claim, or one member that is global or of reach `project`. At most MAX_GROUPS
|
|
198
|
+
are kept."""
|
|
199
|
+
items = raw.get("groups") if isinstance(raw, dict) else None
|
|
200
|
+
if not isinstance(items, list):
|
|
201
|
+
return [], ["the answer is not an object with a list `groups`"]
|
|
202
|
+
by_id = {x.id: x for x in lessons}
|
|
203
|
+
kept: list[Group] = []
|
|
204
|
+
reasons: list[str] = []
|
|
205
|
+
used: set[str] = set()
|
|
206
|
+
for i, item in enumerate(items, start=1):
|
|
207
|
+
judged = _judge_group(item, by_id, used, len(kept))
|
|
208
|
+
if isinstance(judged, str):
|
|
209
|
+
reasons.append(f"group {i}: {judged}")
|
|
210
|
+
continue
|
|
211
|
+
used.update(judged.ids)
|
|
212
|
+
kept.append(judged)
|
|
213
|
+
return kept, reasons
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def verification_lines(groups: Sequence[Group], lessons: Mapping[str, Lesson]) -> list[str]:
|
|
217
|
+
r"""For each group a block for the verifying session: `group <n>`, one `<id>\\t<claim>\\t<context>` line per
|
|
218
|
+
member, then `proposed\\t<claim>\\t<context>`. `<n>` counts from 1."""
|
|
219
|
+
out: list[str] = []
|
|
220
|
+
for n, g in enumerate(groups, start=1):
|
|
221
|
+
out.append(f"group {n}")
|
|
222
|
+
for i in g.ids:
|
|
223
|
+
m = lessons[i].memory
|
|
224
|
+
out.append(f"{i}\t{_line(m.claim)}\t{_line(m.context)}")
|
|
225
|
+
out.append(f"proposed\t{_line(g.claim)}\t{_line(g.context)}")
|
|
226
|
+
return out
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
_ANSWERS = ("same", "faithful", "general")
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _by_group(items: list, count: int) -> dict[int, list[dict]] | None:
|
|
233
|
+
"""The verdicts by the number of the group they name; None when one cannot be placed (it may be a refusal of
|
|
234
|
+
any group)."""
|
|
235
|
+
by_group: dict[int, list[dict]] = {}
|
|
236
|
+
for item in items:
|
|
237
|
+
n = item.get("group") if isinstance(item, dict) else None
|
|
238
|
+
if isinstance(n, bool) or not isinstance(n, int) or not 1 <= n <= count:
|
|
239
|
+
return None
|
|
240
|
+
by_group.setdefault(n, []).append(item)
|
|
241
|
+
return by_group
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _verdict_failures(v: dict, g: Group) -> list[str]:
|
|
245
|
+
failed = []
|
|
246
|
+
reason = v.get("reason")
|
|
247
|
+
if not (isinstance(reason, str) and reason.strip()):
|
|
248
|
+
failed.append("reason is empty or missing")
|
|
249
|
+
for key in _ANSWERS:
|
|
250
|
+
if key == "faithful" and any(i.startswith("g:") for i in g.ids):
|
|
251
|
+
continue # a group with a global member keeps that record's wording: the proposed claim is not used
|
|
252
|
+
answer = v.get(key, True if key == "same" and len(g.ids) == 1 else None)
|
|
253
|
+
if answer is not True:
|
|
254
|
+
failed.append(f"{key} is not true")
|
|
255
|
+
return failed
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _group_failures(found: list[dict], g: Group) -> list[str]:
|
|
259
|
+
if not found:
|
|
260
|
+
return ["no verdict"]
|
|
261
|
+
if len(found) > 1:
|
|
262
|
+
return ["more than one verdict"]
|
|
263
|
+
return _verdict_failures(found[0], g)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def validate_verdicts(raw: object, groups: Sequence[Group]) -> tuple[list[Group], list[str]]:
|
|
267
|
+
"""`raw` is {"verdicts": [{"group": n, "reason": str, "same": bool, "faithful": bool, "general": bool}]}.
|
|
268
|
+
A group is kept only with exactly one verdict naming it, a non-empty reason and all three answers exactly
|
|
269
|
+
`true` (a group of one needs no `same`; a group with a global member needs no `faithful`, because the global
|
|
270
|
+
record's wording stays). Every group not kept gives a reason line; a malformed answer keeps
|
|
271
|
+
nothing. Never raises."""
|
|
272
|
+
items = raw.get("verdicts") if isinstance(raw, dict) else None
|
|
273
|
+
if not isinstance(items, list):
|
|
274
|
+
return [], ["the answer is not an object with a list `verdicts`"]
|
|
275
|
+
by_group = _by_group(items, len(groups))
|
|
276
|
+
if by_group is None:
|
|
277
|
+
return [], ["a verdict does not name an existing group by its number: nothing is kept"]
|
|
278
|
+
kept: list[Group] = []
|
|
279
|
+
reasons: list[str] = []
|
|
280
|
+
for n, g in enumerate(groups, start=1):
|
|
281
|
+
failed = _group_failures(by_group.get(n, []), g)
|
|
282
|
+
if failed:
|
|
283
|
+
reasons.append(f"group {n}: " + "; ".join(failed))
|
|
284
|
+
else:
|
|
285
|
+
kept.append(g)
|
|
286
|
+
return kept, reasons
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
@dataclass(frozen=True)
|
|
290
|
+
class Action:
|
|
291
|
+
"""What the pass does for one group; `kind` decides which fields are used.
|
|
292
|
+
|
|
293
|
+
merge: `keep`, `drop` (lesson ids, one project), `project`.
|
|
294
|
+
merge_global: `keep`, `drop` (lesson ids of two global records).
|
|
295
|
+
write_global: `claim`, `context`, `record_kind`, `weight`, `entries` (sighting entries, each session once with
|
|
296
|
+
the key of the first project that holds it), `members` (ids of the kept project records that stand for it,
|
|
297
|
+
after merges), `cases` (raw `log` entries of the member records for these sessions).
|
|
298
|
+
sighting: `target` (a global handle; None when the target is this group's write_global), `entry`, `cases` (raw
|
|
299
|
+
`log` entries of the member records for its session).
|
|
300
|
+
cases: `target` (a global handle that already counts the session), `entry`, `cases` (only the raw `log` entries of
|
|
301
|
+
the members that the target lacks).
|
|
302
|
+
link: `member` (lesson id), `project`, `target` (as for sighting)."""
|
|
303
|
+
|
|
304
|
+
kind: str
|
|
305
|
+
keep: str | None = None
|
|
306
|
+
drop: str | None = None
|
|
307
|
+
project: Path | None = None
|
|
308
|
+
claim: str | None = None
|
|
309
|
+
context: str | None = None
|
|
310
|
+
record_kind: str | None = None
|
|
311
|
+
weight: str | None = None
|
|
312
|
+
entries: list[str] = field(default_factory=list)
|
|
313
|
+
members: list[str] = field(default_factory=list)
|
|
314
|
+
target: str | None = None
|
|
315
|
+
entry: str | None = None
|
|
316
|
+
member: str | None = None
|
|
317
|
+
cases: list[str] = field(default_factory=list)
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _oldest(lessons: Sequence[Lesson]) -> Lesson:
|
|
321
|
+
return min(lessons, key=lambda x: (x.memory.created or datetime.date.max, x.memory.handle))
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def _cases_of(lessons: Sequence[Lesson], sessions: set[str]) -> list[str]:
|
|
325
|
+
"""The raw `log` entries of `lessons` whose case is for one of `sessions`, each once, by date (stable): of two
|
|
326
|
+
records' entries for one session and outcome, the earlier is applied first."""
|
|
327
|
+
found = ((e, records.case(e)) for y in lessons for e in y.memory.log)
|
|
328
|
+
wanted = {e: c for e, c in found if c and c.session in sessions}
|
|
329
|
+
return sorted(wanted, key=lambda e: wanted[e].on)
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _project_merges(members: Sequence[Lesson]) -> tuple[list[Action], dict[str, list[Lesson]]]:
|
|
333
|
+
"""The merges inside each project, and the lessons each kept project lesson stands for."""
|
|
334
|
+
out: list[Action] = []
|
|
335
|
+
stands: dict[str, list[Lesson]] = {}
|
|
336
|
+
by_project: dict[Path, list[Lesson]] = {}
|
|
337
|
+
for x in members:
|
|
338
|
+
if x.scope == "project" and x.project is not None:
|
|
339
|
+
by_project.setdefault(x.project, []).append(x)
|
|
340
|
+
for project in sorted(by_project):
|
|
341
|
+
same = by_project[project]
|
|
342
|
+
keep = _oldest(same)
|
|
343
|
+
stands[keep.id] = list(same)
|
|
344
|
+
dropped = sorted((x for x in same if x is not keep), key=lambda x: x.id)
|
|
345
|
+
out.extend(
|
|
346
|
+
Action("merge", keep=keep.id, drop=other.id, project=project) for other in dropped
|
|
347
|
+
)
|
|
348
|
+
return out, stands
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def _global_merges(members: Sequence[Lesson]) -> tuple[list[Action], Lesson | None]:
|
|
352
|
+
"""The merges of the global members, and the one that is kept."""
|
|
353
|
+
globals_ = [x for x in members if x.scope == "global"]
|
|
354
|
+
if not globals_:
|
|
355
|
+
return [], None
|
|
356
|
+
gkeep = _oldest(globals_)
|
|
357
|
+
dropped = sorted((x for x in globals_ if x is not gkeep), key=lambda x: x.id)
|
|
358
|
+
return [Action("merge_global", keep=gkeep.id, drop=other.id) for other in dropped], gkeep
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def _first_entries(general: Sequence[Lesson], sess_of: Mapping[str, list[str]]) -> dict[str, str]:
|
|
362
|
+
"""session -> sighting entry of the first member, in order, that holds it."""
|
|
363
|
+
first: dict[str, str] = {}
|
|
364
|
+
for x in general:
|
|
365
|
+
key = records.project_key(x.project) if x.project is not None else None
|
|
366
|
+
for s in sess_of[x.id]:
|
|
367
|
+
first.setdefault(s, records.sighting_entry(s, key))
|
|
368
|
+
return first
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def _write_global(
|
|
372
|
+
group: Group, general: Sequence[Lesson], held: Sequence[Lesson], first: Mapping[str, str]
|
|
373
|
+
) -> Action:
|
|
374
|
+
origin = _oldest(held)
|
|
375
|
+
weights = [y.memory.weight or "medium" for y in held]
|
|
376
|
+
return Action(
|
|
377
|
+
"write_global",
|
|
378
|
+
claim=group.claim,
|
|
379
|
+
context=group.context or None,
|
|
380
|
+
record_kind=origin.memory.kind,
|
|
381
|
+
weight=max(weights, key=records.WEIGHTS.index),
|
|
382
|
+
entries=list(first.values()),
|
|
383
|
+
members=[x.id for x in general],
|
|
384
|
+
cases=_cases_of(held, set(first)),
|
|
385
|
+
)
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def _target_actions(
|
|
389
|
+
target: records.Memory, entries: Sequence[str], held: Sequence[Lesson]
|
|
390
|
+
) -> list[Action]:
|
|
391
|
+
"""A sighting for each entry the target lacks, a `cases` action for an entry it counts but lacks cases of."""
|
|
392
|
+
out: list[Action] = []
|
|
393
|
+
for e in entries:
|
|
394
|
+
key = records.session_key(e) or ""
|
|
395
|
+
carried = _cases_of(held, {key})
|
|
396
|
+
if not records.counted(target, e):
|
|
397
|
+
out.append(Action("sighting", target=target.handle, entry=e, cases=carried))
|
|
398
|
+
continue
|
|
399
|
+
missing = [
|
|
400
|
+
r
|
|
401
|
+
for r in carried
|
|
402
|
+
if (c := records.case(r)) and not records.has_case(target, key, c.outcome)
|
|
403
|
+
]
|
|
404
|
+
if missing:
|
|
405
|
+
out.append(Action("cases", target=target.handle, entry=e, cases=missing))
|
|
406
|
+
return out
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def _general_actions(
|
|
410
|
+
group: Group,
|
|
411
|
+
lessons: Mapping[str, Lesson],
|
|
412
|
+
stands: Mapping[str, list[Lesson]],
|
|
413
|
+
gkeep: Lesson | None,
|
|
414
|
+
) -> list[Action]:
|
|
415
|
+
sess_of = {
|
|
416
|
+
k: list(dict.fromkeys(s for y in held for s in records.sessions(y.memory)))
|
|
417
|
+
for k, held in stands.items()
|
|
418
|
+
}
|
|
419
|
+
# a member with no session holds no evidence: it is neither written, sighted nor linked
|
|
420
|
+
general = sorted(
|
|
421
|
+
(
|
|
422
|
+
lessons[k]
|
|
423
|
+
for k, held in stands.items()
|
|
424
|
+
if sess_of[k] and any(_reach(y) == "general" for y in held)
|
|
425
|
+
),
|
|
426
|
+
key=lambda x: x.id,
|
|
427
|
+
)
|
|
428
|
+
if not general:
|
|
429
|
+
return []
|
|
430
|
+
first = _first_entries(general, sess_of)
|
|
431
|
+
held = [y for x in general for y in stands[x.id]]
|
|
432
|
+
if gkeep is None:
|
|
433
|
+
out = [_write_global(group, general, held, first)]
|
|
434
|
+
handle = None
|
|
435
|
+
else:
|
|
436
|
+
handle = gkeep.memory.handle
|
|
437
|
+
out = _target_actions(gkeep.memory, list(first.values()), held)
|
|
438
|
+
out.extend(Action("link", member=x.id, project=x.project, target=handle) for x in general)
|
|
439
|
+
return out
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def actions(group: Group, lessons: Mapping[str, Lesson]) -> list[Action]:
|
|
443
|
+
"""The steps for one group, in order: merges inside a project, a merge of global members, then for the
|
|
444
|
+
members of reach `general` left: a write_global unless a global record is the target, one sighting per entry
|
|
445
|
+
the target lacks (a `cases` action for an entry it counts but lacks cases of), one link per project member. A merged record stands for the ones dropped into it: its
|
|
446
|
+
sessions are their union, and it is general when any of them is. Members of reach `project` from different
|
|
447
|
+
projects produce no action. Only a global member of the group is a target: a global record that merely shares
|
|
448
|
+
a session with a member may state another lesson of that session, so a pass that stopped half way may write a
|
|
449
|
+
second global record, which a later pass joins with the first as two global members."""
|
|
450
|
+
members = [lessons[i] for i in group.ids]
|
|
451
|
+
out, stands = _project_merges(members)
|
|
452
|
+
merged, gkeep = _global_merges(members)
|
|
453
|
+
return [*out, *merged, *_general_actions(group, lessons, stands, gkeep)]
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def fill_records(
|
|
457
|
+
projects: Sequence[Path], global_folder: Path | None
|
|
458
|
+
) -> list[tuple[str, Path | None, records.Memory]]:
|
|
459
|
+
"""Every readable record, as (id, project path or None, memory), with the ids of `collect`: `p<n>:<handle>` for
|
|
460
|
+
the n-th project and `g:<handle>` for a global record."""
|
|
461
|
+
out: list[tuple[str, Path | None, records.Memory]] = []
|
|
462
|
+
for n, project in enumerate(projects, start=1):
|
|
463
|
+
out += [
|
|
464
|
+
(f"p{n}:{m.handle}", project, m) for m in project_memories(project) if m.error is None
|
|
465
|
+
]
|
|
466
|
+
out += [
|
|
467
|
+
(f"g:{m.handle}", None, m)
|
|
468
|
+
for m in records.load_memories(global_folder, "global")
|
|
469
|
+
if m.error is None
|
|
470
|
+
]
|
|
471
|
+
return out
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def fill_key(project: Path | None, handle: str) -> str:
|
|
475
|
+
"""The name of a lesson that does not change between runs (the ids of `fill_records` depend on the registry)."""
|
|
476
|
+
return f"g:{handle}" if project is None else f"{records.project_key(project)}:{handle}"
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def _fill_wanted(m: records.Memory, today: datetime.date) -> bool:
|
|
480
|
+
"""Could load as a rule, is not awaiting triage, and lacks a valid short form or topic."""
|
|
481
|
+
if not rules.eligible(m, today) or m.triage == "pending":
|
|
482
|
+
return False
|
|
483
|
+
return not (records.valid_short(m.short) and records.valid_topic(m.topic))
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def _fill_left_alone(m: records.Memory, project: Path | None, attempts: dict) -> bool:
|
|
487
|
+
"""The automatic fill's view: a lesson it will not try."""
|
|
488
|
+
if attempt_count(attempts.get(fill_key(project, m.handle)), claim_digest(m)) >= FILL_ATTEMPTS:
|
|
489
|
+
return True
|
|
490
|
+
if project is not None and m.weight == "strong" and m.owner_confirmed is None:
|
|
491
|
+
return True
|
|
492
|
+
return records.valid_short(m.short)
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
def fill_candidates(
|
|
496
|
+
projects: Sequence[Path],
|
|
497
|
+
global_folder: Path | None,
|
|
498
|
+
today: datetime.date,
|
|
499
|
+
cap: int = FILL_CAP,
|
|
500
|
+
attempts: dict | None = None,
|
|
501
|
+
) -> list[tuple[str, records.Memory]]:
|
|
502
|
+
"""(id, memory) of the lessons that could load as a rule (`rules.eligible`) and are not awaiting triage, but
|
|
503
|
+
lack a valid short form or topic. The confirmed first, then the most corroborated; at most `cap`.
|
|
504
|
+
With `attempts` (`fill_key` -> {"digest", "count"}), the automatic fill's view: a lesson tried `FILL_ATTEMPTS`
|
|
505
|
+
times on its present claim, a strong project lesson the owner has not confirmed, and a lesson that already has
|
|
506
|
+
a valid short form (it may be one the owner read: the pass never replaces a short form), leave before the cap."""
|
|
507
|
+
found = []
|
|
508
|
+
for i, p, m in fill_records(projects, global_folder):
|
|
509
|
+
if not _fill_wanted(m, today):
|
|
510
|
+
continue
|
|
511
|
+
if attempts is not None and _fill_left_alone(m, p, attempts):
|
|
512
|
+
continue
|
|
513
|
+
found.append((i, m))
|
|
514
|
+
found.sort(
|
|
515
|
+
key=lambda x: (
|
|
516
|
+
x[1].owner_confirmed is None,
|
|
517
|
+
-len(records.projects(x[1])),
|
|
518
|
+
-len(records.sessions(x[1])),
|
|
519
|
+
x[0],
|
|
520
|
+
)
|
|
521
|
+
)
|
|
522
|
+
return found[:cap]
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
def fill_wont_write(
|
|
526
|
+
m: records.Memory, project: Path | None, attempts: dict, today: datetime.date
|
|
527
|
+
) -> bool:
|
|
528
|
+
"""True when the automatic fill will not write a short form for this lesson, so only the owner can
|
|
529
|
+
(`mem memory edit --short`). The lesson could load as a rule (`rules.eligible`, not awaiting triage, loads in
|
|
530
|
+
full) and has no valid short form, and: the fill gave up after `FILL_ATTEMPTS` failed fills on its present claim,
|
|
531
|
+
or it is a project lesson the fill never attempts (repository-tracked, see `project_memories`; strong and not
|
|
532
|
+
confirmed by the owner, see `fill_candidates`). `m` is marked by `records.mark_repository`; `project` is the
|
|
533
|
+
project root, None for a global lesson."""
|
|
534
|
+
if not (rules.eligible(m, today) and m.triage != "pending" and m.load != "index"):
|
|
535
|
+
return False
|
|
536
|
+
if records.valid_short(m.short):
|
|
537
|
+
return False
|
|
538
|
+
if attempt_count(attempts.get(fill_key(project, m.handle)), claim_digest(m)) >= FILL_ATTEMPTS:
|
|
539
|
+
return True
|
|
540
|
+
return project is not None and (
|
|
541
|
+
m.from_repository or (m.weight == "strong" and m.owner_confirmed is None)
|
|
542
|
+
)
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def attempt_count(entry: object, digest: str) -> int:
|
|
546
|
+
"""Attempts stored for a lesson on this claim digest; anything malformed (a bool included) reads as zero."""
|
|
547
|
+
if not isinstance(entry, dict) or entry.get("digest") != digest:
|
|
548
|
+
return 0
|
|
549
|
+
count = entry.get("count")
|
|
550
|
+
return count if isinstance(count, int) and not isinstance(count, bool) else 0
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def claim_digest(m: records.Memory) -> str:
|
|
554
|
+
"""Identifies the claim as stored, so a proposal for an older wording is never written."""
|
|
555
|
+
return hashlib.sha256((m.claim or "").encode("utf-8", "replace")).hexdigest()
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
def fill_lines(candidates: Sequence[tuple[str, records.Memory]]) -> str:
|
|
559
|
+
"""What the model reads: one block per lesson (id, claim, context), blocks separated by a blank line."""
|
|
560
|
+
blocks = []
|
|
561
|
+
for ident, m in candidates:
|
|
562
|
+
block = [f"id: {ident}", f"claim: {_line(m.claim)}"]
|
|
563
|
+
if _line(m.context):
|
|
564
|
+
block.append(f"context: {_line(m.context)}")
|
|
565
|
+
blocks.append("\n".join(block))
|
|
566
|
+
return "\n\n".join(blocks) + ("\n" if blocks else "")
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
def fill_problem(short: str, topic: str) -> str | None:
|
|
570
|
+
"""Why a proposed short form or topic cannot be applied, in English, or None when both can."""
|
|
571
|
+
found = []
|
|
572
|
+
if not short.strip():
|
|
573
|
+
found.append("short is empty")
|
|
574
|
+
elif short != short.strip():
|
|
575
|
+
found.append("short has spaces at its ends")
|
|
576
|
+
elif len(short.splitlines()) != 1:
|
|
577
|
+
found.append("short must be one line")
|
|
578
|
+
elif not records.valid_short(short):
|
|
579
|
+
found.append(f"short has {len(short)} characters, at most {records.SHORT_LIMIT}")
|
|
580
|
+
if not records.valid_topic(topic):
|
|
581
|
+
found.append("topic must be one or two lowercase words")
|
|
582
|
+
return "; ".join(found) or None
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
def check_lines(items: Sequence[tuple[str, str, str | None, str]]) -> str:
|
|
586
|
+
"""What the checking model reads: (id, claim, context, short) as blocks of one line a field, blank line between."""
|
|
587
|
+
blocks = []
|
|
588
|
+
for ident, claim, context, short in items:
|
|
589
|
+
block = [f"id: {ident}", f"claim: {_line(claim)}"]
|
|
590
|
+
if _line(context):
|
|
591
|
+
block.append(f"context: {_line(context)}")
|
|
592
|
+
block.append(f"short: {_line(short)}")
|
|
593
|
+
blocks.append("\n".join(block))
|
|
594
|
+
return "\n\n".join(blocks) + ("\n" if blocks else "")
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
def validate_check(payload: object, ids: Sequence[str]) -> dict[str, bool] | None:
|
|
598
|
+
"""`payload` is {"verdicts": [{"id", "reason", "faithful"}]}: id -> faithful, where only an exact `true` counts.
|
|
599
|
+
None when the answer is unusable: not an object with a list, or not exactly one verdict for every id asked
|
|
600
|
+
(a verdict for an id not asked is ignored)."""
|
|
601
|
+
verdicts = payload.get("verdicts") if isinstance(payload, dict) else None
|
|
602
|
+
if not isinstance(verdicts, list):
|
|
603
|
+
return None
|
|
604
|
+
seen: dict[str, bool] = {}
|
|
605
|
+
known = set(ids)
|
|
606
|
+
for v in verdicts:
|
|
607
|
+
ident = v.get("id") if isinstance(v, dict) else None
|
|
608
|
+
if not isinstance(ident, str) or ident not in known:
|
|
609
|
+
continue
|
|
610
|
+
if ident in seen:
|
|
611
|
+
return None
|
|
612
|
+
seen[ident] = v.get("faithful") is True
|
|
613
|
+
return seen if len(seen) == len(known) else None
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
def validate_fill(payload: object, ids: Sequence[str]) -> tuple[dict[str, dict], list[str]]:
|
|
617
|
+
"""`payload` is the model's whole answer, {"items": [{"id", "short", "topic"}]}. The items by id, as {"short",
|
|
618
|
+
"topic"} plus a "problem" (see `fill_problem`) when either is invalid: that item keeps the model's text (a
|
|
619
|
+
short cut to 300 characters, a value that is not a string as "") so the owner can repair it. The first item of
|
|
620
|
+
a known id decides. A reason for each dropped item: no usable id, unknown id, repeated id."""
|
|
621
|
+
items = payload.get("items") if isinstance(payload, dict) else None
|
|
622
|
+
if not isinstance(items, list):
|
|
623
|
+
return {}, ["the answer is not an object with a list `items`"]
|
|
624
|
+
known = set(ids)
|
|
625
|
+
kept: dict[str, dict] = {}
|
|
626
|
+
reasons: list[str] = []
|
|
627
|
+
for n, item in enumerate(items, start=1):
|
|
628
|
+
ident = item.get("id") if isinstance(item, dict) else None
|
|
629
|
+
if not isinstance(ident, str):
|
|
630
|
+
reasons.append(f"item {n}: not an object with an id")
|
|
631
|
+
elif ident not in known:
|
|
632
|
+
reasons.append(f"item {n}: unknown id {ident}")
|
|
633
|
+
elif ident in kept:
|
|
634
|
+
reasons.append(f"item {n}: repeats {ident}")
|
|
635
|
+
else:
|
|
636
|
+
short, topic = item.get("short"), item.get("topic")
|
|
637
|
+
short = short if isinstance(short, str) else ""
|
|
638
|
+
topic = topic if isinstance(topic, str) else ""
|
|
639
|
+
problem = fill_problem(short, topic)
|
|
640
|
+
kept[ident] = {
|
|
641
|
+
"short": short[:300],
|
|
642
|
+
"topic": topic,
|
|
643
|
+
**({"problem": problem} if problem else {}),
|
|
644
|
+
}
|
|
645
|
+
return kept, reasons
|
|
646
|
+
|
|
647
|
+
|
|
648
|
+
# --- automatic rewording of a loaded lesson that got worse ---
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
def reword_key(project: Path | None, handle: str) -> str:
|
|
652
|
+
"""The key of a lesson in the rewording's state: the fill's, one per lesson."""
|
|
653
|
+
return fill_key(project, handle)
|
|
654
|
+
|
|
655
|
+
|
|
656
|
+
def _entry(state: Mapping, key: str) -> Mapping:
|
|
657
|
+
lessons = state.get("lessons") if isinstance(state, Mapping) else None
|
|
658
|
+
entry = lessons.get(key) if isinstance(lessons, Mapping) else None
|
|
659
|
+
return entry if isinstance(entry, Mapping) else {}
|
|
660
|
+
|
|
661
|
+
|
|
662
|
+
def _count(entry: Mapping, version: datetime.date) -> int:
|
|
663
|
+
count = entry.get("count")
|
|
664
|
+
if (
|
|
665
|
+
entry.get("version") != version.isoformat()
|
|
666
|
+
or not isinstance(count, int)
|
|
667
|
+
or isinstance(count, bool)
|
|
668
|
+
):
|
|
669
|
+
return 0
|
|
670
|
+
return count
|
|
671
|
+
|
|
672
|
+
|
|
673
|
+
def reword_open(m: records.Memory, last: datetime.date) -> bool:
|
|
674
|
+
"""False when the version dated `last` (the present one) is the pass's own rewording or the one the owner kept.
|
|
675
|
+
Versions are one per day: an owner's version of the same day as `reworded` reads as the pass's own."""
|
|
676
|
+
return m.reworded != last and not (m.reviewed is not None and m.reviewed >= last)
|
|
677
|
+
|
|
678
|
+
|
|
679
|
+
def _loading(
|
|
680
|
+
recs: Sequence[tuple[str, Path | None, records.Memory]],
|
|
681
|
+
project: Path | None,
|
|
682
|
+
today: datetime.date,
|
|
683
|
+
) -> set[int]:
|
|
684
|
+
"""`id()` of the records that load, or are left out only for the size limit, in the view of `project`."""
|
|
685
|
+
glob = [m for _, p, m in recs if p is None]
|
|
686
|
+
mine = [m for _, p, m in recs if p is not None and p == project]
|
|
687
|
+
choice = rules.choose(mine, glob, today)
|
|
688
|
+
return {id(m) for m in choice.loaded} | {id(m) for m, why in choice.left if why == rules.OVER}
|
|
689
|
+
|
|
690
|
+
|
|
691
|
+
def _reword_skipped(m: records.Memory, entry: Mapping, every: bool) -> bool:
|
|
692
|
+
versions = records.version_list(m)
|
|
693
|
+
if (
|
|
694
|
+
not versions
|
|
695
|
+
or (not every and not records.got_worse(m))
|
|
696
|
+
or not reword_open(m, versions[-1][0])
|
|
697
|
+
):
|
|
698
|
+
return True
|
|
699
|
+
last = versions[-1][0]
|
|
700
|
+
spent = entry.get("spent") is True and entry.get("version") == last.isoformat()
|
|
701
|
+
return m.reword_failed == last or spent or _count(entry, last) >= REWORD_ATTEMPTS
|
|
702
|
+
|
|
703
|
+
|
|
704
|
+
def reword_candidates(
|
|
705
|
+
projects: Sequence[Path],
|
|
706
|
+
gfolder: Path | None,
|
|
707
|
+
today: datetime.date,
|
|
708
|
+
state: Mapping,
|
|
709
|
+
*,
|
|
710
|
+
every: bool = False,
|
|
711
|
+
) -> list[tuple[str, records.Memory]]:
|
|
712
|
+
"""(id, memory) of the lessons the automatic rewording may take: loading (or left out only for the size limit
|
|
713
|
+
of the block) in some project's view, got worse, whatever its weight, and not: the pass's own rewording
|
|
714
|
+
(`reworded` is the present version's date), the version the owner kept (`reviewed` on or after it), given up
|
|
715
|
+
on, or spent for the present version (`spent` is a fact about the version its entry names). Most failed on the present version first; at most `REWORD_CAP`.
|
|
716
|
+
With `every`, the lessons that did not get worse are taken too, and there is no cap."""
|
|
717
|
+
recs = fill_records(projects, gfolder)
|
|
718
|
+
found: dict[str, tuple[str, records.Memory]] = {}
|
|
719
|
+
for project in projects or [None]:
|
|
720
|
+
taken = _loading(recs, project, today)
|
|
721
|
+
for i, p, m in recs:
|
|
722
|
+
if id(m) in taken and (p is None or p == project):
|
|
723
|
+
found.setdefault(reword_key(p, m.handle), (i, m))
|
|
724
|
+
out = []
|
|
725
|
+
for key, (i, m) in found.items():
|
|
726
|
+
if not _reword_skipped(m, _entry(state, key), every):
|
|
727
|
+
out.append((i, m))
|
|
728
|
+
out.sort(key=lambda x: (-records.tallies(x[1])[-1].failed, x[0]))
|
|
729
|
+
return out if every else out[:REWORD_CAP]
|
|
730
|
+
|
|
731
|
+
|
|
732
|
+
_SEEN_AGAIN = re.compile(r"Seen again \(([^)]*)\)")
|
|
733
|
+
|
|
734
|
+
|
|
735
|
+
def _failure_signals(body: str) -> list[str]:
|
|
736
|
+
seen: list[str] = []
|
|
737
|
+
for text in (body or "").splitlines():
|
|
738
|
+
found = _SEEN_AGAIN.search(text)
|
|
739
|
+
if (
|
|
740
|
+
found
|
|
741
|
+
and capture_extract.outcome(found.group(1)) == "failed"
|
|
742
|
+
and found.group(1) not in seen
|
|
743
|
+
):
|
|
744
|
+
seen.append(found.group(1))
|
|
745
|
+
return seen
|
|
746
|
+
|
|
747
|
+
|
|
748
|
+
def reword_blocks(items: Sequence[tuple[str, records.Memory]]) -> str:
|
|
749
|
+
"""What the writing session reads: one block per lesson (id, claim, context, each version with its tally, the
|
|
750
|
+
failure signals recorded in the body; never an evidence quote), blank line between."""
|
|
751
|
+
blocks = []
|
|
752
|
+
for ident, m in items:
|
|
753
|
+
block = [f"id: {ident}", f"claim: {_line(m.claim)}"]
|
|
754
|
+
if _line(m.context):
|
|
755
|
+
block.append(f"context: {_line(m.context)}")
|
|
756
|
+
found = records.tallies(m)
|
|
757
|
+
for t in found:
|
|
758
|
+
mark = " (present)" if t is found[-1] else ""
|
|
759
|
+
block.append(
|
|
760
|
+
f"version {t.number} (worked {t.worked}, failed {t.failed}): {_line(t.text)}{mark}"
|
|
761
|
+
)
|
|
762
|
+
signals = _failure_signals(m.body)
|
|
763
|
+
block.append(f"failed after it loaded: {', '.join(signals) if signals else 'not recorded'}")
|
|
764
|
+
blocks.append("\n".join(block))
|
|
765
|
+
return "\n\n".join(blocks) + ("\n" if blocks else "")
|
|
766
|
+
|
|
767
|
+
|
|
768
|
+
def same_text(a: str, b: str) -> bool:
|
|
769
|
+
def norm(x: str) -> str:
|
|
770
|
+
return " ".join(x.lower().split()).strip(" .!;:")
|
|
771
|
+
|
|
772
|
+
return norm(a) == norm(b)
|
|
773
|
+
|
|
774
|
+
|
|
775
|
+
def reword_problem(short: str, memory: records.Memory) -> str | None:
|
|
776
|
+
"""Why a proposed short form cannot be applied, or None."""
|
|
777
|
+
if not short.strip():
|
|
778
|
+
return "short is empty"
|
|
779
|
+
if short != short.strip():
|
|
780
|
+
return "short has spaces at its ends"
|
|
781
|
+
if len(short.splitlines()) != 1:
|
|
782
|
+
return "short must be one line"
|
|
783
|
+
if not records.valid_short(short):
|
|
784
|
+
return f"short has {len(short)} characters, at most {records.SHORT_LIMIT}"
|
|
785
|
+
if any(same_text(short, text) for _, text in records.version_list(memory)):
|
|
786
|
+
return "same as an earlier wording"
|
|
787
|
+
return None
|
|
788
|
+
|
|
789
|
+
|
|
790
|
+
def _items_of(payload: object) -> list | None:
|
|
791
|
+
listed = payload.get("items") if isinstance(payload, dict) else None
|
|
792
|
+
return listed if isinstance(listed, list) else None
|
|
793
|
+
|
|
794
|
+
|
|
795
|
+
def validate_reword(
|
|
796
|
+
payload: object, items: Sequence[tuple[str, records.Memory]]
|
|
797
|
+
) -> dict[str, dict]:
|
|
798
|
+
"""The writer's answer {"items": [{"id", "short"}]} as {id: {"short", "problem"}} for the ids asked; an id the
|
|
799
|
+
answer lacks is absent; the first item of an id wins. ValueError when the answer is not an object with a list."""
|
|
800
|
+
listed = _items_of(payload)
|
|
801
|
+
if listed is None:
|
|
802
|
+
raise ValueError("the answer is not an object with a list `items`")
|
|
803
|
+
memories = dict(items)
|
|
804
|
+
out: dict[str, dict] = {}
|
|
805
|
+
for item in listed:
|
|
806
|
+
ident = item.get("id") if isinstance(item, dict) else None
|
|
807
|
+
if not isinstance(ident, str) or ident not in memories or ident in out:
|
|
808
|
+
continue
|
|
809
|
+
short = item.get("short")
|
|
810
|
+
short = short if isinstance(short, str) else ""
|
|
811
|
+
out[ident] = {"short": short[:300], "problem": reword_problem(short, memories[ident])}
|
|
812
|
+
return out
|
|
813
|
+
|
|
814
|
+
|
|
815
|
+
def reword_survivors(
|
|
816
|
+
proposed: Mapping[str, dict], items: Sequence[tuple[str, records.Memory]]
|
|
817
|
+
) -> tuple[list[tuple[str, records.Memory, str]], dict[str, str]]:
|
|
818
|
+
"""The proposals fit to go to the checking session, as (id, memory, short), and a refusal word for each other
|
|
819
|
+
proposal: `same_text` (an earlier wording), `refused_code` (any other problem, or `short_problems`). An id the writer
|
|
820
|
+
did not answer is in neither."""
|
|
821
|
+
kept: list[tuple[str, records.Memory, str]] = []
|
|
822
|
+
refused: dict[str, str] = {}
|
|
823
|
+
for ident, m in items:
|
|
824
|
+
got = proposed.get(ident)
|
|
825
|
+
if got is None:
|
|
826
|
+
continue
|
|
827
|
+
if got.get("problem") == "same as an earlier wording":
|
|
828
|
+
refused[ident] = "same_text"
|
|
829
|
+
elif got.get("problem") or model.short_problems(m.claim, got["short"]):
|
|
830
|
+
refused[ident] = "refused_code"
|
|
831
|
+
else:
|
|
832
|
+
kept.append((ident, m, got["short"]))
|
|
833
|
+
return kept, refused
|
|
834
|
+
|
|
835
|
+
|
|
836
|
+
def reword_outcome(
|
|
837
|
+
items: Sequence[tuple[str, records.Memory]],
|
|
838
|
+
proposed: Mapping[str, dict],
|
|
839
|
+
accepted: Collection[str],
|
|
840
|
+
) -> dict[str, str]:
|
|
841
|
+
"""One word per candidate: written, same_text, refused_code, refused_check or no_proposal (the writer's answer has
|
|
842
|
+
no item for it). The step itself adds `changed` and `failed_edit`, which count no attempt."""
|
|
843
|
+
kept, refused = reword_survivors(proposed, items)
|
|
844
|
+
survivors = {ident for ident, _, _ in kept}
|
|
845
|
+
out = {}
|
|
846
|
+
for ident, _ in items:
|
|
847
|
+
if ident in refused:
|
|
848
|
+
out[ident] = refused[ident]
|
|
849
|
+
elif ident in survivors:
|
|
850
|
+
out[ident] = "written" if ident in accepted else "refused_check"
|
|
851
|
+
else:
|
|
852
|
+
out[ident] = "no_proposal"
|
|
853
|
+
return out
|
|
854
|
+
|
|
855
|
+
|
|
856
|
+
def _key_of(m: records.Memory) -> str:
|
|
857
|
+
return reword_key(None if m.scope == "global" else m.path.parent.parent, m.handle)
|
|
858
|
+
|
|
859
|
+
|
|
860
|
+
def reword_state_after(
|
|
861
|
+
state: Mapping,
|
|
862
|
+
items: Sequence[tuple[str, records.Memory]],
|
|
863
|
+
outcome: Mapping[str, str],
|
|
864
|
+
today: datetime.date,
|
|
865
|
+
) -> tuple[dict, list[str]]:
|
|
866
|
+
"""The state once the step has run, and the ids to give up on (a `reword_failed` mark): `written` spends the
|
|
867
|
+
version it was written from (the present one of `items`, so an undo leaves the lesson skipped and a newer
|
|
868
|
+
version of the owner's takes it once more); a refusal or a missing proposal counts an attempt against its present version (a count for another
|
|
869
|
+
version starts again); `changed` and `failed_edit` change nothing. `state` is not mutated."""
|
|
870
|
+
lessons = {
|
|
871
|
+
k: dict(v) for k, v in (state.get("lessons") or {}).items() if isinstance(v, Mapping)
|
|
872
|
+
}
|
|
873
|
+
new = {**{k: v for k, v in state.items() if k != "lessons"}, "lessons": lessons}
|
|
874
|
+
giveup: list[str] = []
|
|
875
|
+
for ident, m in items:
|
|
876
|
+
word = outcome.get(ident, "no_proposal")
|
|
877
|
+
versions = records.version_list(m)
|
|
878
|
+
if word in {"changed", "failed_edit"} or not versions:
|
|
879
|
+
continue
|
|
880
|
+
key, on = _key_of(m), versions[-1][0]
|
|
881
|
+
entry = lessons.get(key, {})
|
|
882
|
+
if word == "written":
|
|
883
|
+
lessons[key] = {"version": on.isoformat(), "count": _count(entry, on), "spent": True}
|
|
884
|
+
continue
|
|
885
|
+
count = _count(entry, on) + 1
|
|
886
|
+
lessons[key] = {
|
|
887
|
+
"version": on.isoformat(),
|
|
888
|
+
"count": count,
|
|
889
|
+
"spent": entry.get("spent") is True,
|
|
890
|
+
}
|
|
891
|
+
if count >= REWORD_ATTEMPTS:
|
|
892
|
+
giveup.append(ident)
|
|
893
|
+
return new, giveup
|