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.
Files changed (128) hide show
  1. memory_cli/__init__.py +1 -0
  2. memory_cli/__main__.py +49 -0
  3. memory_cli/capture/__init__.py +7 -0
  4. memory_cli/capture/codex_rollout.py +164 -0
  5. memory_cli/capture/event_lines.py +66 -0
  6. memory_cli/capture/extract.py +458 -0
  7. memory_cli/capture/state.py +183 -0
  8. memory_cli/commands/__init__.py +21 -0
  9. memory_cli/commands/admin.py +363 -0
  10. memory_cli/commands/common.py +609 -0
  11. memory_cli/commands/curate.py +1189 -0
  12. memory_cli/commands/diagnostics.py +126 -0
  13. memory_cli/commands/edit.py +1282 -0
  14. memory_cli/commands/hooks.py +730 -0
  15. memory_cli/commands/import_recovery.py +45 -0
  16. memory_cli/commands/install.py +152 -0
  17. memory_cli/commands/integrate.py +480 -0
  18. memory_cli/commands/memory.py +2152 -0
  19. memory_cli/commands/read.py +1290 -0
  20. memory_cli/commands/sources.py +766 -0
  21. memory_cli/commands/split.py +97 -0
  22. memory_cli/commands/split_plan.py +196 -0
  23. memory_cli/commands/split_transaction.py +230 -0
  24. memory_cli/commands/synthesis.py +1122 -0
  25. memory_cli/core/__init__.py +16 -0
  26. memory_cli/core/auto_state.py +30 -0
  27. memory_cli/core/codex_pass.py +109 -0
  28. memory_cli/core/config.py +87 -0
  29. memory_cli/core/file_journal.py +163 -0
  30. memory_cli/core/headless.py +130 -0
  31. memory_cli/core/jobs.py +130 -0
  32. memory_cli/core/resources.py +57 -0
  33. memory_cli/core/runner.py +398 -0
  34. memory_cli/core/safe_io.py +155 -0
  35. memory_cli/core/store_git.py +407 -0
  36. memory_cli/core/yaml_load.py +14 -0
  37. memory_cli/corroborate/__init__.py +11 -0
  38. memory_cli/corroborate/cli.py +267 -0
  39. memory_cli/corroborate/decide.py +893 -0
  40. memory_cli/corroborate/digest.py +425 -0
  41. memory_cli/corroborate/fill.py +744 -0
  42. memory_cli/corroborate/job.py +15 -0
  43. memory_cli/corroborate/reword.py +446 -0
  44. memory_cli/corroborate/run.py +1142 -0
  45. memory_cli/corroborate/state.py +300 -0
  46. memory_cli/digest/__init__.py +4 -0
  47. memory_cli/digest/lessons.py +483 -0
  48. memory_cli/entry/__init__.py +12 -0
  49. memory_cli/entry/auto.py +660 -0
  50. memory_cli/entry/capture.py +1403 -0
  51. memory_cli/entry/corroborate.py +214 -0
  52. memory_cli/entry/integrate.py +684 -0
  53. memory_cli/entry/integrate_self_check.py +203 -0
  54. memory_cli/entry/research.py +9 -0
  55. memory_cli/entry/settle.py +614 -0
  56. memory_cli/entry/split_auto.py +460 -0
  57. memory_cli/entry/synthesize.py +22 -0
  58. memory_cli/integrate/__init__.py +9 -0
  59. memory_cli/integrate/answers.py +42 -0
  60. memory_cli/integrate/briefs/check-brief.md +16 -0
  61. memory_cli/integrate/briefs/place-brief.md +26 -0
  62. memory_cli/integrate/log.py +43 -0
  63. memory_cli/integrate/plan.py +125 -0
  64. memory_cli/integrate/rows.py +99 -0
  65. memory_cli/integrate/state.py +158 -0
  66. memory_cli/integrate/undo.py +143 -0
  67. memory_cli/mem.py +1180 -0
  68. memory_cli/memories/__init__.py +16 -0
  69. memory_cli/memories/fingerprints.py +51 -0
  70. memory_cli/memories/journal.py +93 -0
  71. memory_cli/memories/locations.py +282 -0
  72. memory_cli/memories/matching.py +451 -0
  73. memory_cli/memories/model.py +205 -0
  74. memory_cli/memories/parse.py +237 -0
  75. memory_cli/memories/records.py +266 -0
  76. memory_cli/memories/rules.py +291 -0
  77. memory_cli/memories/sightings.py +314 -0
  78. memory_cli/memories/terms.py +148 -0
  79. memory_cli/memories/write.py +358 -0
  80. memory_cli/notes/__init__.py +13 -0
  81. memory_cli/notes/check.py +806 -0
  82. memory_cli/notes/due.py +260 -0
  83. memory_cli/notes/fields.py +217 -0
  84. memory_cli/notes/index.py +230 -0
  85. memory_cli/notes/links.py +170 -0
  86. memory_cli/notes/note.py +222 -0
  87. memory_cli/notes/search.py +391 -0
  88. memory_cli/notes/split_candidates.py +72 -0
  89. memory_cli/research/__init__.py +5 -0
  90. memory_cli/research/checks.py +1065 -0
  91. memory_cli/research/pipeline.py +952 -0
  92. memory_cli/session/__init__.py +5 -0
  93. memory_cli/session/handoff.py +139 -0
  94. memory_cli/session/notices.py +111 -0
  95. memory_cli/settle/__init__.py +5 -0
  96. memory_cli/settle/state.py +111 -0
  97. memory_cli/settle/verdicts.py +693 -0
  98. memory_cli/split/briefs/checker-brief.md +5 -0
  99. memory_cli/split/briefs/editor-brief.md +20 -0
  100. memory_cli/syntheses/__init__.py +8 -0
  101. memory_cli/syntheses/document.py +400 -0
  102. memory_cli/syntheses/edit.py +581 -0
  103. memory_cli/syntheses/project.py +384 -0
  104. memory_cli/syntheses/split_conservation.py +50 -0
  105. memory_cli/syntheses/units.py +427 -0
  106. memory_cli/synthesize/__init__.py +9 -0
  107. memory_cli/synthesize/backfill.py +431 -0
  108. memory_cli/synthesize/briefs/backfill-brief.md +26 -0
  109. memory_cli/synthesize/briefs/checker-brief.md +13 -0
  110. memory_cli/synthesize/briefs/fixer-brief.md +19 -0
  111. memory_cli/synthesize/briefs/memory-brief.md +30 -0
  112. memory_cli/synthesize/briefs/settle-brief.md +32 -0
  113. memory_cli/synthesize/briefs/verdict-brief.md +50 -0
  114. memory_cli/synthesize/briefs/web-brief.md +33 -0
  115. memory_cli/synthesize/cli.py +311 -0
  116. memory_cli/synthesize/pipeline.py +764 -0
  117. memory_cli/synthesize/references.py +164 -0
  118. memory_cli/synthesize/run.py +150 -0
  119. memory_cli/synthesize/topics.py +528 -0
  120. memory_cli/templates/knowledge.md +23 -0
  121. memory_cli/templates/literature.md +25 -0
  122. memory_cli/templates/research.md +23 -0
  123. memory_cli/templates/synthesis.md +6 -0
  124. memory_cli-0.1.0.dist-info/METADATA +102 -0
  125. memory_cli-0.1.0.dist-info/RECORD +128 -0
  126. memory_cli-0.1.0.dist-info/WHEEL +4 -0
  127. memory_cli-0.1.0.dist-info/entry_points.txt +9 -0
  128. memory_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,291 @@
1
+ """The lessons that load as rules at session start: which ones, in what order, and the text.
2
+
3
+ Pure: it takes lists of `Memory` and a date and returns data and strings; it reads no file and no environment.
4
+ The standing after each rule is computed here from the record, never taken from text a model wrote."""
5
+
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import dataclass, field
9
+ from typing import TYPE_CHECKING
10
+
11
+ from memory_cli.memories import fingerprints, sightings
12
+ from memory_cli.memories.model import is_live, valid_short
13
+
14
+ if TYPE_CHECKING:
15
+ import datetime
16
+ from collections.abc import Sequence
17
+
18
+ from memory_cli.memories.model import Memory
19
+
20
+ HEADER = (
21
+ "memory: lessons learned in earlier sessions. Apply them with judgment: follow one unless you have a reason "
22
+ "not to, and mention a skipped one only when it matters to the user."
23
+ )
24
+ RULES_LIMIT = 3200
25
+ INDEX_LIMIT = 1600
26
+ # characters of topic headings printed; a heading is at most digest.HEADING_LIMIT
27
+ HEADINGS_LIMIT = 800
28
+ TOPICS_NAMED = 4
29
+ PROJECT_FIRST = 3
30
+ # a project lesson loads once this many sessions held it, unless the owner confirmed it
31
+ MIN_SESSIONS = 2
32
+ OVER, PENDING, INDEX = "over the limit", "awaits triage", "index only"
33
+ _WEIGHT = {"strong": 0, "medium": 1, "light": 2}
34
+
35
+
36
+ @dataclass
37
+ class Choice:
38
+ loaded: list[Memory] = field(default_factory=list)
39
+ left: list[tuple[Memory, str]] = field(default_factory=list)
40
+ unready: int = 0 # lessons that would qualify but have no valid `short`
41
+ # the same lessons, `unready` counts them
42
+ unready_lessons: list[Memory] = field(default_factory=list)
43
+
44
+
45
+ def eligible(m: Memory, today: datetime.date) -> bool:
46
+ """Every condition to load except `triage` and `short`."""
47
+ if m.error is not None or not is_live(m, today) or m.origin != "transcript":
48
+ return False
49
+ if sightings.standing(m) != "established" or sightings.quarantined(m) or m.load == "no":
50
+ return False
51
+ return (
52
+ m.scope == "global" or bool(m.owner_confirmed) or len(sightings.sessions(m)) >= MIN_SESSIONS
53
+ )
54
+
55
+
56
+ def _rank(m: Memory) -> tuple:
57
+ seen = m.last_observed
58
+ return (
59
+ m.owner_confirmed is None,
60
+ _WEIGHT.get(m.weight or "medium", 1),
61
+ -len(sightings.projects(m)),
62
+ -len(sightings.sessions(m)),
63
+ seen is None,
64
+ -(seen.toordinal() if seen else 0),
65
+ m.handle,
66
+ )
67
+
68
+
69
+ def standing_words(m: Memory) -> str:
70
+ if m.from_repository:
71
+ return "(from repository)"
72
+ if m.owner_confirmed:
73
+ return "(the user vouched for it)"
74
+ n, unit = (
75
+ (len(sightings.projects(m)), "project")
76
+ if m.scope == "global"
77
+ else (len(sightings.sessions(m)), "session")
78
+ )
79
+ return f"(held in {n} {unit}{'' if n == 1 else 's'})"
80
+
81
+
82
+ def line(m: Memory) -> str:
83
+ return f"- {m.short} {standing_words(m)}"
84
+
85
+
86
+ def _sorted_out(candidates: Sequence[Memory], out: Choice) -> list[Memory]:
87
+ """Records into `out` the lessons that wait for triage, are index only or have no valid short form; returns the ready ones."""
88
+ ready: list[Memory] = []
89
+ for m in candidates:
90
+ if m.triage == "pending":
91
+ out.left.append((m, PENDING))
92
+ elif m.load == "index":
93
+ out.left.append((m, INDEX))
94
+ elif not valid_short(m.short):
95
+ out.unready += 1
96
+ out.unready_lessons.append(m)
97
+ else:
98
+ ready.append(m)
99
+ return ready
100
+
101
+
102
+ def _fill(ranked: Sequence[Memory], out: Choice) -> None:
103
+ """Loads the lessons in order while the limit holds; the rest are left as over the limit."""
104
+ used, full = 0, False
105
+ for m in ranked:
106
+ size = len(line(m)) + 1
107
+ if not full and used + size <= RULES_LIMIT:
108
+ out.loaded.append(m)
109
+ used += size
110
+ else:
111
+ full = True # the order decides: nothing ranked lower jumps ahead of a rule that did not fit
112
+ out.left.append((m, OVER))
113
+
114
+
115
+ def choose(project: Sequence[Memory], global_: Sequence[Memory], today: datetime.date) -> Choice:
116
+ out = Choice()
117
+ globals_ = [m for m in global_ if eligible(m, today)]
118
+ # ready to load and competing: an index-only global lesson must not hide its twin in the project it came from
119
+ names = {
120
+ m.handle
121
+ for m in globals_
122
+ if m.triage != "pending" and valid_short(m.short) and m.load is None
123
+ }
124
+ projects_ = [
125
+ m
126
+ for m in project
127
+ if eligible(m, today) and (m.general or "").removeprefix("m:") not in names
128
+ ]
129
+ ready = _sorted_out([*projects_, *globals_], out)
130
+ ordered = sorted((m for m in ready if m.scope == "project"), key=_rank)
131
+ first = ordered[:PROJECT_FIRST]
132
+ rest = sorted(
133
+ [*ordered[PROJECT_FIRST:], *(m for m in ready if m.scope != "project")], key=_rank
134
+ )
135
+ _fill([*first, *rest], out)
136
+ return out
137
+
138
+
139
+ LAYOUTS = ("flat", "grouped", "digest")
140
+
141
+
142
+ def _by_topic(choice: Choice) -> dict[str, list[Memory]]:
143
+ groups: dict[str, list[Memory]] = {}
144
+ for m in choice.loaded:
145
+ groups.setdefault(m.topic or "other", []).append(m)
146
+ if "other" in groups:
147
+ groups["other"] = groups.pop("other")
148
+ return groups
149
+
150
+
151
+ def grouped(choice: Choice) -> list[str]:
152
+ """The loaded lessons under a `<topic>:` line each, topics in the order of their first lesson; no topic: `other:`, last."""
153
+ return [x for topic, ms in _by_topic(choice).items() for x in (f"{topic}:", *map(line, ms))]
154
+
155
+
156
+ def _digested(choice: Choice, digest: dict, topics: dict) -> list[str]:
157
+ """`grouped` with the digest's heading after a topic and its line for a global lesson, wherever they are fresh and fit.
158
+ Under a printed heading the lessons with a digest line come first: a short form stands alone, a line leans on the heading."""
159
+ return _printed(_digest_plan(choice, digest, topics))
160
+
161
+
162
+ def _digest_plan(
163
+ choice: Choice, digest: dict, topics: dict
164
+ ) -> list[tuple[str, str | None, list[tuple[Memory, str | None]]]]:
165
+ """Per topic: its name, its heading when one fits, and (lesson, its fresh line) in the order they print."""
166
+ used_heads = 0
167
+ heads_open = True
168
+ plan: list[tuple[str, str | None, list[tuple[Memory, str | None]]]] = []
169
+ for topic, ms in _by_topic(choice).items():
170
+ lessons = topics.get(topic)
171
+ head = fingerprints.heading(digest, topic, lessons) if lessons else None
172
+ items: list[tuple[Memory, str | None]]
173
+ if lessons and head is not None and heads_open and used_heads + len(head) <= HEADINGS_LIMIT:
174
+ used_heads += len(head)
175
+ items = [
176
+ (m, fingerprints.line(digest, topic, m, lessons) if m.scope == "global" else None)
177
+ for m in ms
178
+ ]
179
+ items = [*(x for x in items if x[1] is not None), *(x for x in items if x[1] is None)]
180
+ else:
181
+ heads_open = (
182
+ heads_open and head is None
183
+ ) # a fresh heading that did not fit closes the rest
184
+ head = None
185
+ items = [(m, None) for m in ms]
186
+ plan.append((topic, head, items))
187
+ return plan
188
+
189
+
190
+ def _printed(plan: Sequence[tuple[str, str | None, list[tuple[Memory, str | None]]]]) -> list[str]:
191
+ """The lines of a plan; a digest line prints only while every short form still to come fits under the limit."""
192
+ pending = [
193
+ len(line(m)) + 1 for _, _, items in plan for m, _ in items
194
+ ] # short forms still to print, in printed order
195
+ out: list[str] = []
196
+ used, lines_open = 0, True
197
+ for topic, head, items in plan:
198
+ out.append(f"{topic}: {head}" if head is not None else f"{topic}:")
199
+ for m, text in items:
200
+ short = pending.pop(0)
201
+ printed = line(m)
202
+ if text is not None and lines_open:
203
+ digested = f"- {text} {standing_words(m)}"
204
+ if used + len(digested) + 1 + sum(pending) <= RULES_LIMIT:
205
+ printed, short = digested, len(digested) + 1
206
+ else:
207
+ lines_open = False
208
+ used += short
209
+ out.append(printed)
210
+ return out
211
+
212
+
213
+ def block(
214
+ choice: Choice, layout: str = "flat", *, digest: dict | None = None, topics: dict | None = None
215
+ ) -> list[str]:
216
+ if not choice.loaded:
217
+ return []
218
+ if layout == "digest":
219
+ body = (
220
+ _digested(choice, digest, topics or {})
221
+ if digest and digest.get("topics")
222
+ else grouped(choice)
223
+ )
224
+ else:
225
+ body = grouped(choice) if layout == "grouped" else list(map(line, choice.loaded))
226
+ return [HEADER, *body]
227
+
228
+
229
+ def topic_counts(choice: Choice) -> list[tuple[str, int]]:
230
+ counts: dict[str, int] = {}
231
+ for m, _ in choice.left:
232
+ if m.topic:
233
+ counts[m.topic] = counts.get(m.topic, 0) + 1
234
+ return sorted(counts.items(), key=lambda t: (-t[1], t[0]))
235
+
236
+
237
+ def not_fitted(choice: Choice) -> list[tuple[Memory, str]]:
238
+ """The lessons that qualify and did not fit. A global lesson awaiting triage is announced by the `Triage:` line."""
239
+ return [(m, why) for m, why in choice.left if why in {OVER, INDEX}]
240
+
241
+
242
+ def more_line(choice: Choice) -> str | None:
243
+ left = not_fitted(choice)
244
+ total = len(left)
245
+ if not total:
246
+ return None
247
+ noun = "lesson" if total == 1 else "lessons"
248
+ topics = topic_counts(Choice(left=left))
249
+ if not topics:
250
+ return f"{total} more {noun}: mem rules --more"
251
+ named = topics[:TOPICS_NAMED]
252
+ while True:
253
+ other = total - sum(n for _, n in named)
254
+ parts = [f"{t} {n}" for t, n in named] + ([f"other {other}"] if other else [])
255
+ text = f"{total} more {noun} by topic: {', '.join(parts)} (mem rules --more <topic>, when a topic fits your task)"
256
+ if len(text) <= INDEX_LIMIT or not named:
257
+ break
258
+ named = named[:-1]
259
+ return text if named else f"{total} more {noun}: mem rules --more"
260
+
261
+
262
+ def index_lines(
263
+ choice: Choice, *, digest: dict | None = None, topics: dict | None = None
264
+ ) -> list[str]:
265
+ """The lines after the block for the lessons that did not fit: a line per topic when a fresh heading names one, else `more_line`."""
266
+ left = not_fitted(choice)
267
+ if left and digest and topics:
268
+ counts = dict(topic_counts(Choice(left=left)))
269
+ if other := sum(1 for m, _ in left if not m.topic):
270
+ counts["other"] = other
271
+ heads = {t: fingerprints.heading(digest, t, topics[t]) for t in counts if t in topics}
272
+ if any(h is not None for h in heads.values()):
273
+ names = sorted(counts.items(), key=lambda t: (-t[1], t[0]))
274
+ entries = [
275
+ f"- {t} ({n}): {heads[t]}" if heads.get(t) else f"- {t} ({n})" for t, n in names
276
+ ]
277
+ top = "More lessons, by topic (mem rules --more <topic>):"
278
+ for kept in range(len(entries), -1, -1):
279
+ rest = names[kept:]
280
+ tail = (
281
+ [
282
+ f"- and {sum(n for _, n in rest)} more in {len(rest)} topic{'' if len(rest) == 1 else 's'}"
283
+ ]
284
+ if rest
285
+ else []
286
+ )
287
+ lines = [top, *entries[:kept], *tail]
288
+ if len("\n".join(lines)) <= INDEX_LIMIT:
289
+ return lines
290
+ more = more_line(choice)
291
+ return [more] if more else []
@@ -0,0 +1,314 @@
1
+ """Sightings, cases and versions: the entries a memory's sources, log and versions hold, and what they add up to."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime
6
+ import re
7
+ from typing import TYPE_CHECKING, NamedTuple
8
+
9
+ from memory_cli.memories.model import (
10
+ GLOBAL_MIN_PROJECTS,
11
+ OUTCOMES,
12
+ PROJECT_KEY_LEN,
13
+ SESSION_PREFIX,
14
+ SHORT_DATE_LEN,
15
+ SIGHTINGS_NEEDED,
16
+ UNCONFIRMED_DAYS,
17
+ valid_short,
18
+ )
19
+
20
+ if TYPE_CHECKING:
21
+ from collections.abc import Iterable
22
+
23
+ from memory_cli.memories.model import Memory
24
+
25
+
26
+ MAX_SESSION_ID = 200 # characters of the id after "session "; longer is not a session
27
+ _PROJECT_PART = re.compile(r"(session \S.*?) project (\S+)")
28
+ _PROJECT_KEY = re.compile(rf"[0-9a-f]{{{PROJECT_KEY_LEN}}}")
29
+
30
+
31
+ def sighting(source: str) -> tuple[str, str | None] | None:
32
+ """("session <id>", project key or None) of a sighting entry, normalized (stripped, whitespace collapsed,
33
+ lower-cased), else None. A text after "project" that is not a 12-hex key makes the entry no sighting."""
34
+ text = " ".join(source.split()).lower()
35
+ if not text.startswith(SESSION_PREFIX) or len(text) == len(SESSION_PREFIX):
36
+ return None
37
+ key = None
38
+ found = _PROJECT_PART.fullmatch(text)
39
+ if found:
40
+ text, key = found.group(1), found.group(2)
41
+ if not _PROJECT_KEY.fullmatch(key):
42
+ return None
43
+ elif "project" in text[len(SESSION_PREFIX) :].split():
44
+ return None # "session a project" or "... project <key> extra": a keyed entry gone wrong, not a session id
45
+ return (text, key) if len(text) - len(SESSION_PREFIX) <= MAX_SESSION_ID else None
46
+
47
+
48
+ def sighting_entry(session: str, key: str | None) -> str:
49
+ return f"{session} project {key}" if key else session
50
+
51
+
52
+ def session_key(source: str) -> str | None:
53
+ """The normalized "session <id>" part of a session source (the project, if any, is left out), else None:
54
+ two spellings of one session are one key."""
55
+ found = sighting(source)
56
+ return found[0] if found else None
57
+
58
+
59
+ def _normalized_source(
60
+ source: str, found: tuple[str, str | None] | None, first_key: dict[str, str]
61
+ ) -> str | None:
62
+ """`source` normalized, or None when it repeats a session that another entry names with a project."""
63
+ if found is None:
64
+ return source
65
+ if found[0] in first_key and found[1] != first_key[found[0]]:
66
+ return None
67
+ return sighting_entry(*found)
68
+
69
+
70
+ def normalized_sources(sources: Iterable[str]) -> list[str]:
71
+ """Session entries in their normalized form, one per session (the first one with a project when several
72
+ occur: one session is one sighting, so it cannot count as two projects); other sources unchanged; order kept."""
73
+ parsed = [(s, sighting(s)) for s in sources]
74
+ first_key: dict[str, str] = {}
75
+ for _, f in parsed:
76
+ if f and f[1]:
77
+ first_key.setdefault(f[0], f[1])
78
+ out = (_normalized_source(s, f, first_key) for s, f in parsed)
79
+ return list(dict.fromkeys(e for e in out if e is not None))
80
+
81
+
82
+ def sessions(memory: Memory) -> list[str]:
83
+ """The distinct sessions of `sources` as normalized keys, in order."""
84
+ return list(dict.fromkeys(k for k in map(session_key, memory.sources) if k))
85
+
86
+
87
+ def projects(memory: Memory) -> list[str]:
88
+ """The distinct project keys of the sighting entries, in order: one per session, its first keyed entry, so a
89
+ file that holds one session under two keys still counts one project."""
90
+ first: dict[str, str] = {}
91
+ for found in map(sighting, memory.sources):
92
+ if found and found[1]:
93
+ first.setdefault(found[0], found[1])
94
+ return list(dict.fromkeys(first.values()))
95
+
96
+
97
+ def standing(memory: Memory) -> str | None:
98
+ """None unless the memory comes from a transcript; then "established" once the owner confirmed it or enough
99
+ distinct sessions show it (by its weight), else "unconfirmed". A global record also needs two projects (C31).
100
+ Never computed from `observed`: a plain confirm, a merge and a curation pass raise it without being
101
+ independent evidence."""
102
+ if memory.origin != "transcript":
103
+ return None
104
+ if memory.owner_confirmed:
105
+ return "established"
106
+ weight = memory.weight or "medium"
107
+ if memory.scope == "global":
108
+ enough = len(projects(memory)) >= GLOBAL_MIN_PROJECTS and (
109
+ weight != "strong" or len(sessions(memory)) >= SIGHTINGS_NEEDED["strong"]
110
+ )
111
+ else:
112
+ enough = len(sessions(memory)) >= SIGHTINGS_NEEDED[weight]
113
+ return "established" if enough else "unconfirmed"
114
+
115
+
116
+ def quarantined(memory: Memory) -> bool:
117
+ return memory.scope == "global" and standing(memory) == "unconfirmed"
118
+
119
+
120
+ def standing_changes(before: Memory | None, after: Memory, today: datetime.date) -> dict:
121
+ """The frontmatter changes that follow from the standing of `after` (a transcript record): its end date, and
122
+ the release of a global record the first time it is established, awaiting triage unless the owner confirmed it
123
+ (that confirmation is the triage). `before` is None for a record being written."""
124
+ established = standing(after) == "established"
125
+ changes: dict = {
126
+ "valid_until": None if established else today + datetime.timedelta(days=UNCONFIRMED_DAYS)
127
+ }
128
+ if after.scope == "global" and established:
129
+ if before is None or before.released is None:
130
+ changes["released"] = today
131
+ if not after.owner_confirmed and (after.weight or "medium") == "strong":
132
+ changes["triage"] = "pending"
133
+ if after.owner_confirmed:
134
+ changes["triage"] = None
135
+ return changes
136
+
137
+
138
+ def counted(memory: Memory, source: str) -> bool:
139
+ """True when the sighting entry adds nothing: its session is counted and either it names no project or the
140
+ session already carries one."""
141
+ found = sighting(source)
142
+ if found is None or found[0] not in sessions(memory):
143
+ return False
144
+ return not found[1] or any(
145
+ f and f[0] == found[0] and f[1] for f in map(sighting, memory.sources)
146
+ )
147
+
148
+
149
+ class Case(NamedTuple):
150
+ on: datetime.date
151
+ session: str # the normalized "session <id>"
152
+ outcome: str
153
+
154
+
155
+ _CASE = re.compile(r"(\d{4}-\d{2}-\d{2}) (session \S.*) (" + "|".join(OUTCOMES) + ")")
156
+
157
+
158
+ def case(entry: str) -> Case | None:
159
+ """The case of a log entry "<YYYY-MM-DD> session <id> <outcome>", else None."""
160
+ found = _CASE.fullmatch(entry) if isinstance(entry, str) else None
161
+ if not found:
162
+ return None
163
+ try:
164
+ on = datetime.date.fromisoformat(found.group(1))
165
+ except ValueError:
166
+ return None
167
+ if session_key(found.group(2)) != found.group(2):
168
+ return None
169
+ return Case(on, found.group(2), found.group(3))
170
+
171
+
172
+ def case_entry(on: datetime.date, session: str, outcome: str) -> str:
173
+ return f"{on.isoformat()} {session} {outcome}"
174
+
175
+
176
+ def cases(memory: Memory) -> list[Case]:
177
+ """The valid cases of the log by date; entries of one day keep their file order."""
178
+ return sorted((c for c in map(case, memory.log) if c), key=lambda c: c.on)
179
+
180
+
181
+ def _version(entry) -> tuple[datetime.date, str] | None:
182
+ """(date, short form) of a version entry "<YYYY-MM-DD> <short form>", else None."""
183
+ if not isinstance(entry, str):
184
+ return None
185
+ day, _, text = entry.partition(" ")
186
+ try:
187
+ on = datetime.date.fromisoformat(day)
188
+ except ValueError:
189
+ return None
190
+ return (on, text) if len(day) == SHORT_DATE_LEN and valid_short(text) else None
191
+
192
+
193
+ def version_entry(on: datetime.date, short: str) -> str:
194
+ return f"{on.isoformat()} {short}"
195
+
196
+
197
+ def version_list(memory: Memory) -> list[tuple[datetime.date, str]]:
198
+ """The versions of the short form by date; a lesson written before versions existed reads as one version dated
199
+ `released`, or `created`."""
200
+ found = [v for v in map(_version, memory.versions) if v]
201
+ if found:
202
+ return found
203
+ on = memory.released or memory.created
204
+ return [(on, memory.short)] if memory.short and on else []
205
+
206
+
207
+ def merged_versions(keep: Memory, drop: Memory, today: datetime.date) -> list[str]:
208
+ """The versions of a merged lesson: both records' versions (implicit ones included), one per day with the kept
209
+ record's text winning, and the kept record's short form last, because that is the text that loads."""
210
+ by_day: dict[datetime.date, str] = {}
211
+ for on, text in [*version_list(keep), *version_list(drop)]:
212
+ by_day.setdefault(on, text) # keep's entries come first, so they win
213
+ result = sorted(by_day.items())
214
+ if keep.short and (not result or result[-1][1] != keep.short):
215
+ result = [v for v in result if v[0] != today] + [(today, keep.short)]
216
+ return [version_entry(on, text) for on, text in result]
217
+
218
+
219
+ def merged_log(keep: Memory, drop: Memory) -> list[str]:
220
+ """The log of a merged lesson by date: one entry per (session, outcome), the earlier day kept, and a `seen` entry
221
+ only for a session with no other entry. An entry that is not a case is kept once, as it is."""
222
+ entries = list(dict.fromkeys([*keep.log, *drop.log]))
223
+ earliest: dict[tuple[str, str], tuple[datetime.date, str]] = {}
224
+ for e in entries:
225
+ c = case(e)
226
+ if c is not None:
227
+ held = earliest.get((c.session, c.outcome))
228
+ if held is None or c.on < held[0]:
229
+ earliest[c.session, c.outcome] = (c.on, e)
230
+ best = {key: e for key, (_, e) in earliest.items()}
231
+ cased = {session for session, outcome in best if outcome != "seen"}
232
+ chosen = {
233
+ e for (session, outcome), e in best.items() if outcome != "seen" or session not in cased
234
+ }
235
+ result = [e for e in entries if case(e) is None or e in chosen]
236
+ result.sort(key=lambda e: e[:10])
237
+ return result
238
+
239
+
240
+ class Tally(NamedTuple):
241
+ number: int
242
+ since: datetime.date
243
+ text: str
244
+ worked: int
245
+ failed: int
246
+
247
+ @property
248
+ def balance(self) -> int:
249
+ return self.worked - self.failed
250
+
251
+
252
+ FAILED_TO_LIST = 2
253
+
254
+
255
+ def tallies(memory: Memory) -> list[Tally]:
256
+ """One tally per version; a case counts for the last version dated earlier than the case."""
257
+ versions = version_list(memory)
258
+ counts = [[0, 0] for _ in versions]
259
+ for c in cases(memory):
260
+ if c.outcome == "seen":
261
+ continue
262
+ owners = [i for i, (on, _) in enumerate(versions) if on < c.on]
263
+ if owners:
264
+ counts[owners[-1]][c.outcome == "failed"] += 1
265
+ return [
266
+ Tally(i + 1, on, text, w, f)
267
+ for i, ((on, text), (w, f)) in enumerate(zip(versions, counts, strict=False))
268
+ ]
269
+
270
+
271
+ def reword_note(memory: Memory) -> str:
272
+ """What the automatic rewording did to this lesson, for the owner's queue; "" when it did nothing that still applies."""
273
+ versions = version_list(memory)
274
+ last = versions[-1][0] if versions else None
275
+ if memory.reworded is not None:
276
+ if memory.reworded == last:
277
+ return f"the automatic rewording of {memory.reworded.isoformat()} got worse too"
278
+ return f"an automatic rewording was made on {memory.reworded.isoformat()}; this wording is the owner's"
279
+ if memory.reword_failed is not None and memory.reword_failed == last:
280
+ return "an automatic rewording could not be written"
281
+ return ""
282
+
283
+
284
+ def got_worse(memory: Memory) -> bool:
285
+ """The current version failed at least FAILED_TO_LIST times since `reviewed`, and failed more than it worked or
286
+ stands below the version before it."""
287
+ found = tallies(memory)
288
+ if not found:
289
+ return False
290
+ cur, prev = found[-1], found[-2] if len(found) > 1 else None
291
+ since = memory.reviewed
292
+ recent = sum(
293
+ 1
294
+ for c in cases(memory)
295
+ if c.outcome == "failed" and (since is None or c.on > since) and c.on > cur.since
296
+ )
297
+ return recent >= FAILED_TO_LIST and (
298
+ cur.failed > cur.worked or (prev is not None and cur.balance < prev.balance)
299
+ )
300
+
301
+
302
+ def mark_words(memory: Memory) -> str:
303
+ found = tallies(memory)
304
+ if not found or not found[-1].failed:
305
+ return ""
306
+ cur = found[-1]
307
+ return f"version {cur.number}: worked {cur.worked}, failed {cur.failed}"
308
+
309
+
310
+ def has_case(memory: Memory, key: str, outcome: str) -> bool:
311
+ """True when a case of session `key` with `outcome` adds nothing: the session has an entry with that outcome,
312
+ or the outcome is `seen` and the session has any entry."""
313
+ mine = [c.outcome for c in cases(memory) if c.session == key]
314
+ return outcome in mine or (outcome == "seen" and bool(mine))