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,483 @@
1
+ """The digest of the loaded lessons: a derived file, `rules-digest.json`, in the plugin's data folder.
2
+
3
+ It holds, per topic, a heading and one line per lesson. It never lives in a record. A caller finds the data folder
4
+ with `commands.common.data_dir(os.environ)`; `read` and `write` take it as an argument.
5
+
6
+ Shape: {"topics": {topic: {"heading": str, "of": str, "lines": {handle: {"text": str, "of": str, "under": str}}}}}
7
+ `of` fingerprints what the text was written from; `under` fingerprints the heading a line was written under.
8
+ A text is fresh only while its fingerprint still matches (C88 to C90).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import copy
14
+ import json
15
+ import logging
16
+ import os
17
+ from collections.abc import Mapping
18
+ from pathlib import Path
19
+ from typing import TYPE_CHECKING, NamedTuple
20
+
21
+ from memory_cli.memories import model, records, rules
22
+ from memory_cli.memories.fingerprints import heading, heading_print, line, line_print
23
+
24
+ if TYPE_CHECKING:
25
+ import datetime
26
+ from collections.abc import Sequence
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+ __all__ = [
31
+ "DIGEST_ATTEMPTS",
32
+ "DIGEST_LIMIT",
33
+ "FILE",
34
+ "HEADING_LIMIT",
35
+ "MIN_LESSONS",
36
+ "DigestFormatError",
37
+ "Work",
38
+ "blocks",
39
+ "decide",
40
+ "heading",
41
+ "heading_print",
42
+ "heading_problem",
43
+ "line",
44
+ "line_print",
45
+ "line_problem",
46
+ "pairs",
47
+ "pruned",
48
+ "read",
49
+ "topics_of",
50
+ "validate",
51
+ "work",
52
+ "write",
53
+ ]
54
+
55
+
56
+ class DigestFormatError(ValueError):
57
+ """The writer's answer is not the shape `validate` expects."""
58
+
59
+
60
+ FILE = "rules-digest.json"
61
+ HEADING_LIMIT = 80
62
+ MIN_LESSONS = 2 # a topic is digested only with at least this many ready lessons
63
+ DIGEST_ATTEMPTS = 2 # tries of one heading or one line before it is left alone
64
+ DIGEST_LIMIT = 30 # lessons one run asks lines for; a topic is never split
65
+
66
+
67
+ def _strings(d, *keys) -> bool:
68
+ return isinstance(d, dict) and all(isinstance(d.get(k), str) for k in keys)
69
+
70
+
71
+ def _control(text: str) -> bool:
72
+ return any(c < " " or c == "\x7f" for c in text)
73
+
74
+
75
+ def _printable(text: str, limit: int) -> bool:
76
+ """A non-empty single line with no control character, within `limit`: what a stored text must still be when read."""
77
+ return (
78
+ bool(text.strip())
79
+ and len(text.splitlines()) == 1
80
+ and not _control(text)
81
+ and len(text) <= limit
82
+ )
83
+
84
+
85
+ def _read_topics(data: Path | None, out: dict) -> None:
86
+ """Fills `out` with the file's topics that are well formed; raises on a file that is missing or not the expected shape."""
87
+ if data is None:
88
+ raise TypeError("no data folder")
89
+ raw = json.loads((Path(data) / FILE).read_text(encoding="utf-8"))
90
+ topics = raw["topics"]
91
+ if not isinstance(topics, dict):
92
+ return
93
+ for topic, entry in topics.items():
94
+ if (
95
+ not isinstance(topic, str)
96
+ or not _strings(entry, "heading", "of")
97
+ or not isinstance(entry.get("lines"), dict)
98
+ or not _printable(entry["heading"], HEADING_LIMIT)
99
+ ):
100
+ continue # a heading that is not a plain line takes its topic's lines with it
101
+ lines = {
102
+ h: dict(v)
103
+ for h, v in entry["lines"].items()
104
+ if isinstance(h, str)
105
+ and _strings(v, "text", "of", "under")
106
+ and _printable(v["text"], records.SHORT_LIMIT)
107
+ }
108
+ out["topics"][topic] = {"heading": entry["heading"], "of": entry["of"], "lines": lines}
109
+
110
+
111
+ def read(data: Path | None) -> dict:
112
+ """The file's content; anything missing or wrong reads as empty, entry by entry, and never raises."""
113
+ out: dict = {"topics": {}}
114
+ try:
115
+ _read_topics(data, out)
116
+ except Exception:
117
+ logger.debug(
118
+ "the digest file could not be read; the entries read so far are kept", exc_info=True
119
+ )
120
+ return out
121
+
122
+
123
+ def write(data: Path, digest: dict) -> None:
124
+ """Writes the file through a temporary file in the same folder, then renames it into place."""
125
+ data = Path(data)
126
+ data.mkdir(parents=True, exist_ok=True)
127
+ tmp = data / f"{FILE}.{os.getpid()}.tmp"
128
+ try:
129
+ tmp.write_text(
130
+ json.dumps(digest, ensure_ascii=False, indent=1, sort_keys=True), encoding="utf-8"
131
+ )
132
+ os.replace(tmp, data / FILE)
133
+ finally:
134
+ tmp.unlink(missing_ok=True)
135
+
136
+
137
+ def topics_of(
138
+ global_lessons: Sequence[records.Memory], today: datetime.date
139
+ ) -> dict[str, list[records.Memory]]:
140
+ """Ready global lessons (loaded, or left as over the limit or index only) by topic, topics with two or more."""
141
+ choice = rules.choose([], global_lessons, today)
142
+ ready = [*choice.loaded, *(m for m, why in choice.left if why in {rules.OVER, rules.INDEX})]
143
+ groups: dict[str, list[records.Memory]] = {}
144
+ for m in ready:
145
+ if m.topic:
146
+ groups.setdefault(m.topic, []).append(m)
147
+ return {t: ls for t, ls in groups.items() if len(ls) >= MIN_LESSONS}
148
+
149
+
150
+ class Work(NamedTuple):
151
+ topic: str
152
+ lessons: list # every ready lesson of the topic
153
+ heading_state: (
154
+ str # "keep" (the stored heading is fresh), "write", or "given_up" (its tries are spent)
155
+ )
156
+ heading: str | None # the stored text when the state is "keep"
157
+ write: list # lessons that need a line
158
+ keep: dict # handle -> stored text of the lessons whose line is still written from their claim and short form
159
+
160
+
161
+ def _heading_key(topic: str, lessons: Sequence[records.Memory]) -> str:
162
+ return f"h:{topic}@{heading_print(lessons)}"
163
+
164
+
165
+ def _line_key(m: records.Memory, lessons: Sequence[records.Memory]) -> str:
166
+ return f"l:{m.handle}@{line_print(m)}@{heading_print(lessons)}"
167
+
168
+
169
+ def _tries(state: Mapping, key: str) -> int:
170
+ return state.get("tries", {}).get(key, 0)
171
+
172
+
173
+ def pruned(digest: dict, state: Mapping, topics: Mapping[str, list]) -> tuple[dict, dict]:
174
+ """The digest and the state without what no longer applies: topics that are not in `topics`, lines of lessons that
175
+ left their topic, and tries of texts that can no longer be asked for. Nothing passed in is changed."""
176
+ new = copy.deepcopy(digest)
177
+ st = copy.deepcopy(dict(state))
178
+ keys: set[str] = set()
179
+ for topic, lessons in topics.items():
180
+ keys.add(_heading_key(topic, lessons))
181
+ keys.update(_line_key(m, lessons) for m in lessons if records.valid_short(m.short))
182
+ for topic in list(new.get("topics", {})):
183
+ if topic not in topics:
184
+ del new["topics"][topic]
185
+ else:
186
+ present = {m.handle for m in topics[topic]}
187
+ new["topics"][topic]["lines"] = {
188
+ h: v for h, v in new["topics"][topic]["lines"].items() if h in present
189
+ }
190
+ if "tries" in st:
191
+ st["tries"] = {k: n for k, n in st["tries"].items() if k in keys}
192
+ return new, st
193
+
194
+
195
+ def _line_split(
196
+ lessons: Sequence[records.Memory], stored: Mapping, state: Mapping
197
+ ) -> tuple[list, dict]:
198
+ """The lessons that need a line, and handle -> text of those whose stored line is still fresh."""
199
+ to_write: list = []
200
+ keep: dict = {}
201
+ for m in lessons:
202
+ if not records.valid_short(m.short):
203
+ continue
204
+ old = stored.get(m.handle)
205
+ if old and old["of"] == line_print(m):
206
+ keep[m.handle] = old["text"]
207
+ elif _tries(state, _line_key(m, lessons)) < DIGEST_ATTEMPTS:
208
+ to_write.append(m)
209
+ return to_write, keep
210
+
211
+
212
+ def _topic_work(topic: str, lessons: list, digest: dict, state: Mapping) -> Work | None:
213
+ """What one topic asks for, or None when its heading is given up or nothing is left to write."""
214
+ kept_heading = heading(digest, topic, lessons)
215
+ if kept_heading is not None:
216
+ hstate = "keep"
217
+ elif _tries(state, _heading_key(topic, lessons)) >= DIGEST_ATTEMPTS:
218
+ return None
219
+ else:
220
+ hstate = "write"
221
+ stored = digest.get("topics", {}).get(topic, {}).get("lines", {})
222
+ to_write, keep = _line_split(lessons, stored, state)
223
+ if hstate == "keep" and not to_write:
224
+ return None
225
+ return Work(topic, lessons, hstate, kept_heading, to_write, keep)
226
+
227
+
228
+ def work(topics: Mapping[str, list], digest: dict, state: Mapping) -> list[Work]:
229
+ """What one run asks for, by topic in the order of the names. Lessons without a valid short form get no line."""
230
+ out: list[Work] = []
231
+ asked = 0
232
+ for topic in sorted(topics):
233
+ if asked >= DIGEST_LIMIT:
234
+ break
235
+ topic_work = _topic_work(topic, list(topics[topic]), digest, state)
236
+ if topic_work is not None:
237
+ out.append(topic_work)
238
+ asked += len(topic_work.write)
239
+ return out
240
+
241
+
242
+ def _one_line(text) -> str:
243
+ return " ".join(str(text).split())
244
+
245
+
246
+ def blocks(works: Sequence[Work]) -> str:
247
+ """What the writer reads. A kept heading prints `heading (keep): <text>`, one to write `heading: write`; a lesson prints only when it is
248
+ written or kept; the header of a topic is a block of its own."""
249
+ topics = []
250
+ for w in works:
251
+ parts = [f"topic: {_one_line(w.topic)}"]
252
+ parts.append(
253
+ f"heading (keep): {_one_line(w.heading)}"
254
+ if w.heading_state == "keep"
255
+ else "heading: write"
256
+ )
257
+ items = ["\n".join(parts)]
258
+ for m in w.lessons:
259
+ if m in w.write or m.handle in w.keep:
260
+ rows = [
261
+ f"id: g:{m.handle}",
262
+ f"do: {'write' if m in w.write else 'keep'}",
263
+ f"claim: {_one_line(m.claim)}",
264
+ ]
265
+ if m.context:
266
+ rows.append(f"context: {_one_line(m.context)}")
267
+ rows.append(f"short: {_one_line(m.short)}")
268
+ if m.handle in w.keep:
269
+ rows.append(f"line: {_one_line(w.keep[m.handle])}")
270
+ items.append("\n".join(rows))
271
+ topics.append("\n\n".join(items))
272
+ return "\n\n\n".join(topics)
273
+
274
+
275
+ def _answered_lines(item: dict, w: Work) -> dict[str, str]:
276
+ """handle -> line for the lines the answer gives to lessons that were asked, the first of each."""
277
+ asked = {f"g:{m.handle}": m.handle for m in w.write}
278
+ lines: dict[str, str] = {}
279
+ for entry in item["lines"] if isinstance(item.get("lines"), list) else []:
280
+ if (
281
+ isinstance(entry, dict)
282
+ and isinstance(entry.get("id"), str)
283
+ and isinstance(entry.get("line"), str)
284
+ ):
285
+ handle = asked.get(entry["id"])
286
+ if handle is not None and handle not in lines:
287
+ lines[handle] = entry["line"]
288
+ return lines
289
+
290
+
291
+ def validate(payload, works: Sequence[Work]) -> dict[str, dict]:
292
+ """The writer's answer as {topic: {"heading": str | None, "lines": {handle: str}}}; only what was asked is kept."""
293
+ if not isinstance(payload, dict) or not isinstance(payload.get("topics"), list):
294
+ raise DigestFormatError("the answer must be an object with a list `topics`")
295
+ by_topic = {w.topic: w for w in works}
296
+ out: dict[str, dict] = {}
297
+ for item in payload["topics"]:
298
+ if (
299
+ not isinstance(item, dict)
300
+ or not isinstance(item.get("topic"), str)
301
+ or item["topic"] not in by_topic
302
+ or item["topic"] in out
303
+ ):
304
+ continue
305
+ w = by_topic[item["topic"]]
306
+ text = item.get("heading")
307
+ heading_text = text if w.heading_state == "write" and isinstance(text, str) else None
308
+ out[w.topic] = {"heading": heading_text, "lines": _answered_lines(item, w)}
309
+ return out
310
+
311
+
312
+ def _form_problem(text: str, limit: int) -> str | None:
313
+ if not isinstance(text, str) or not text.strip():
314
+ return "empty"
315
+ if len(text.splitlines()) != 1:
316
+ return "more than one line"
317
+ if _control(text):
318
+ return "a control character"
319
+ if text != text.strip():
320
+ return "spaces at its ends"
321
+ if len(text) > limit:
322
+ return f"over {limit} characters"
323
+ return None
324
+
325
+
326
+ def heading_problem(text: str) -> str | None:
327
+ return _form_problem(text, HEADING_LIMIT) or (
328
+ "ends with a period or a colon" if text[-1] in ".:" else None
329
+ )
330
+
331
+
332
+ def line_problem(text: str, m: records.Memory) -> str | None:
333
+ found = _form_problem(text, records.SHORT_LIMIT)
334
+ if found:
335
+ return found
336
+ return "; ".join(model.short_problems(m.claim, text)) or None
337
+
338
+
339
+ def _work_pairs(w: Work, p: Mapping) -> list[tuple[str, records.Memory, str, str]]:
340
+ proposed_heading = p.get("heading")
341
+ if w.heading_state == "write":
342
+ head = (
343
+ proposed_heading
344
+ if isinstance(proposed_heading, str) and heading_problem(proposed_heading) is None
345
+ else None
346
+ )
347
+ else:
348
+ head = w.heading
349
+ if head is None:
350
+ return []
351
+ lines = p.get("lines", {})
352
+ out = []
353
+ for m in w.lessons:
354
+ text = lines.get(m.handle) if m in w.write else None
355
+ if text is not None and line_problem(text, m) is None:
356
+ out.append((f"g:{m.handle}", m, head, text))
357
+ elif w.heading_state == "write" and m.handle in w.keep:
358
+ out.append((f"g:{m.handle}", m, head, w.keep[m.handle]))
359
+ return out
360
+
361
+
362
+ def pairs(
363
+ works: Sequence[Work], proposed: Mapping[str, Mapping]
364
+ ) -> list[tuple[str, records.Memory, str, str]]:
365
+ """(id, lesson, heading, line) for every line the checker judges."""
366
+ return [pair for w in works for pair in _work_pairs(w, proposed.get(w.topic, {}))]
367
+
368
+
369
+ def _ok(verdicts: Mapping[str, Mapping], ident: str, *keys: str) -> bool:
370
+ v = verdicts.get(ident)
371
+ return isinstance(v, Mapping) and all(v.get(k) is True for k in keys)
372
+
373
+
374
+ class _Ruling:
375
+ """What `decide` keeps while it rules on the works: the verdicts, the tries to update and the counts."""
376
+
377
+ def __init__(self, verdicts: Mapping[str, Mapping], tries: dict) -> None:
378
+ self.verdicts = verdicts
379
+ self.tries = tries
380
+ self.counts = {
381
+ "headings_written": 0,
382
+ "lines_written": 0,
383
+ "refused_code": 0,
384
+ "refused_check": 0,
385
+ "missing": 0,
386
+ "unjudged": 0,
387
+ }
388
+
389
+ def refuse(self, key: str, why: str) -> None:
390
+ self.tries[key] = self.tries.get(key, 0) + 1
391
+ self.counts[why] += 1
392
+
393
+ def ok(self, ident: str, *keys: str) -> bool:
394
+ return _ok(self.verdicts, ident, *keys)
395
+
396
+ def judged(self, topic_pairs: Sequence[tuple]) -> set[str]:
397
+ """The ids of the pairs the checker answered; counts the others as unjudged (an answer that leaves a lesson out is no judgment of it)."""
398
+ got = {ident for ident, _, _, _ in topic_pairs}
399
+ judged = {ident for ident in got if isinstance(self.verdicts.get(ident), Mapping)}
400
+ self.counts["unjudged"] += len(got) - len(judged)
401
+ return judged
402
+
403
+ def new_heading(
404
+ self, w: Work, p: Mapping, topic_pairs: Sequence[tuple], judged: set[str]
405
+ ) -> dict | None:
406
+ """The entry for a heading that was written and passed, or None (refused, or not judged yet)."""
407
+ text = p.get("heading")
408
+ key = _heading_key(w.topic, w.lessons)
409
+ if not isinstance(text, str):
410
+ self.refuse(key, "missing")
411
+ elif heading_problem(text) is not None or not topic_pairs:
412
+ self.refuse(key, "refused_code")
413
+ elif not judged:
414
+ pass
415
+ elif not all(self.ok(ident, "fits") for ident in judged):
416
+ self.refuse(key, "refused_check")
417
+ else:
418
+ self.counts["headings_written"] += 1
419
+ return {"heading": text, "of": heading_print(w.lessons), "lines": {}}
420
+ return None
421
+
422
+ def keep_lines(self, w: Work, entry: dict) -> None:
423
+ """Carries over the stored lines of a rewritten heading whose lesson the checker still finds faithful."""
424
+ for handle, stored_text in w.keep.items():
425
+ if w.heading_state == "write" and self.ok(f"g:{handle}", "fits", "faithful"):
426
+ m = next(x for x in w.lessons if x.handle == handle)
427
+ entry["lines"][handle] = {
428
+ "text": stored_text,
429
+ "of": line_print(m),
430
+ "under": entry["of"],
431
+ }
432
+
433
+ def _line_outcome(self, m: records.Memory, text: str | None, judged: set[str]) -> str:
434
+ if text is None:
435
+ return "missing"
436
+ if line_problem(text, m) is not None:
437
+ return "refused_code"
438
+ if f"g:{m.handle}" not in judged:
439
+ return "unjudged"
440
+ if not self.ok(f"g:{m.handle}", "fits", "faithful"):
441
+ return "refused_check"
442
+ return "written"
443
+
444
+ def write_lines(self, w: Work, entry: dict, lines: Mapping, judged: set[str]) -> None:
445
+ """Rules on each line asked for: writes it into `entry`, or refuses it and counts a try."""
446
+ for m in w.write:
447
+ text = lines.get(m.handle)
448
+ outcome = self._line_outcome(m, text, judged)
449
+ if outcome in {"missing", "refused_code", "refused_check"}:
450
+ self.refuse(_line_key(m, w.lessons), outcome)
451
+ elif outcome == "written":
452
+ entry["lines"][m.handle] = {"text": text, "of": line_print(m), "under": entry["of"]}
453
+ self.counts["lines_written"] += 1
454
+
455
+
456
+ def decide(
457
+ works: Sequence[Work],
458
+ proposed: Mapping[str, Mapping],
459
+ verdicts: Mapping[str, Mapping],
460
+ digest: dict,
461
+ state: Mapping,
462
+ ) -> tuple[dict, dict, dict[str, int]]:
463
+ """The new digest, the new state and the counts. Nothing passed in is changed."""
464
+ new = copy.deepcopy(digest)
465
+ new.setdefault("topics", {})
466
+ st = copy.deepcopy(dict(state))
467
+ tries = st.setdefault("tries", {})
468
+ st.setdefault("failures", {"count": 0, "fingerprint": ""})
469
+ ruling = _Ruling(verdicts, tries)
470
+ for w in works:
471
+ p = proposed.get(w.topic, {})
472
+ topic_pairs = _work_pairs(w, p)
473
+ judged = ruling.judged(topic_pairs)
474
+ if w.heading_state == "write":
475
+ entry = ruling.new_heading(w, p, topic_pairs, judged)
476
+ if entry is None:
477
+ continue
478
+ new["topics"][w.topic] = entry
479
+ else:
480
+ entry = new["topics"][w.topic]
481
+ ruling.keep_lines(w, entry)
482
+ ruling.write_lines(w, entry, p.get("lines", {}), judged)
483
+ return new, st, ruling.counts
@@ -0,0 +1,12 @@
1
+ """The command lines `bin/` launchers start through `engine/run.py --bin NAME`: one module per launcher.
2
+
3
+ `auto`: `bin/mem-auto`, one bounded curation run in the background
4
+ `capture`: `bin/mem-capture`, the offline trial and the automatic capture of a session
5
+ `corroborate`: `bin/mem-corroborate`, the background pass that matches lessons by meaning
6
+ `integrate`: `bin/mem-integrate`, joins loose knowledge notes to the parts of syntheses
7
+ `integrate_self_check`: the no-model check of `mem-integrate --self-check`, with its fixture store and fake `claude`
8
+ `research`: `bin/mem-research`, answers a question from memory and the web
9
+ `settle`: `bin/mem-settle`, one bounded settling run in the background
10
+ `split_auto`: the unattended split of one synthesis part, called under the caller's run lock (not a launcher)
11
+ `synthesize`: `bin/mem-synthesize`, writes syntheses for topics that have none
12
+ """